# How to integrate Quaderno MCP with OpenAI Agents SDK

```json
{
  "title": "How to integrate Quaderno MCP with OpenAI Agents SDK",
  "toolkit": "Quaderno",
  "toolkit_slug": "quaderno",
  "framework": "OpenAI Agents SDK",
  "framework_slug": "open-ai-agents-sdk",
  "url": "https://composio.dev/toolkits/quaderno/framework/open-ai-agents-sdk",
  "markdown_url": "https://composio.dev/toolkits/quaderno/framework/open-ai-agents-sdk.md",
  "updated_at": "2026-05-12T10:23:08.010Z"
}
```

## Introduction

This guide walks you through connecting Quaderno to the OpenAI Agents SDK using the Composio tool router. By the end, you'll have a working Quaderno agent that can calculate tax rate for a u.s. sale, create an invoice for a new customer, email finalized invoice to a client through natural language commands.
This guide will help you understand how to give your OpenAI Agents SDK agent real control over a Quaderno account through Composio's Quaderno MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Quaderno with

- [Claude Agent SDK](https://composio.dev/toolkits/quaderno/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/quaderno/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/quaderno/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/quaderno/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/quaderno/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/quaderno/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/quaderno/framework/cli)
- [Google ADK](https://composio.dev/toolkits/quaderno/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/quaderno/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/quaderno/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/quaderno/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/quaderno/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/quaderno/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- Get and set up your OpenAI and Composio API keys
- Install the necessary dependencies
- Initialize Composio and create a Tool Router session for Quaderno
- Configure an AI agent that can use Quaderno as a tool
- Run a live chat session where you can ask the agent to perform Quaderno operations

## What is OpenAI Agents SDK?

The OpenAI Agents SDK is a lightweight framework for building AI agents that can use tools and maintain conversation state. It provides a simple interface for creating agents with hosted MCP tool support.
Key features include:
- Hosted MCP Tools: Connect to external services through hosted MCP endpoints
- SQLite Sessions: Persist conversation history across interactions
- Simple API: Clean interface with Agent, Runner, and tool configuration
- Streaming Support: Real-time response streaming for interactive applications

## What is the Quaderno MCP server, and what's possible with it?

The Quaderno MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Quaderno account. It provides structured and secure access to your tax automation, invoicing, and compliance workflows, so your agent can calculate taxes, generate invoices, manage contacts and products, and handle essential document delivery on your behalf.
- Automated tax rate calculation: Ask your agent to instantly determine the correct tax rate for any address or transaction type before creating invoices or processing sales.
- Invoice creation and delivery: Let your agent generate detailed invoices for customers and deliver them directly via email, ensuring seamless billing operations.
- Contact and product management: Easily create new customer or vendor contacts, add new products, or permanently delete outdated items from your Quaderno account—all through your agent.
- Expense and tax ID cleanup: Direct your agent to remove specific expenses or registered tax IDs when they're no longer needed, keeping your records tidy and up to date.
- Credit note and coupon handling: Your agent can deliver finalized credit notes to customers and permanently delete coupons as part of your accounting and revenue operations.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `QUADERNO_ADD_EXPENSE_PAYMENT` | Add Expense Payment | Adds a payment to an existing expense in Quaderno. Use when you need to record a payment received for an expense. Returns the payment record with ID, amount in cents, and payment method details. |
| `QUADERNO_CALCULATE_TAX_RATE` | Calculate Tax Rate | Tool to calculate applicable tax rate for given address and transaction type. Use when you need tax details before invoicing. |
| `QUADERNO_CREATE_CONTACT` | Create Contact | Tool to create a new contact (customer or vendor). Use when you need to add a person or company contact in Quaderno. |
| `QUADERNO_CREATE_COUPON` | Create Coupon | Tool to create a new discount coupon in Quaderno. Use when you need to create either a percentage-based or fixed-amount discount coupon. Either percent_off or amount_off must be provided (but not both). For amount_off coupons, currency is required. |
| `QUADERNO_CREATE_ESTIMATE` | Create Estimate | Creates a new estimate/quote in Quaderno for a customer with line items. Returns estimate with ID, number, permalink, and total amounts in cents. Use this when you need to create a cost estimate or quote for a project or service. |
| `QUADERNO_CREATE_EVIDENCE` | Create Evidence | Tool to create a new location evidence for tax compliance. Use when you need to create evidence records with billing country, IP address, or bank country information for verifying customer location. |
| `QUADERNO_CREATE_EXPENSE` | Create Expense | Tool to create a business expense in Quaderno. Use when you need to record an expense from a supplier or vendor with line items and optional attachments. |
| `QUADERNO_CREATE_INVOICE` | Create Invoice | Creates a new invoice in Quaderno for a customer with line items. Returns invoice with ID, number, permalink, PDF URL, and total amounts in cents. Use this when you need to bill a customer for products or services. |
| `QUADERNO_CREATE_PRODUCT` | Create Product | Creates a new product that can be used as a line item in invoices, credit notes, and expenses. Use this to register products with their SKU, pricing, tax classification, and other details in your Quaderno account. |
| `QUADERNO_CREATE_RECEIPT` | Create Receipt | Creates a new receipt in Quaderno documenting payment for goods or services. Returns receipt with ID, number, permalink, PDF URL, and total amounts. Use when you need to create a receipt for a completed transaction. |
| `QUADERNO_CREATE_RECURRING` | Create Recurring | Tool to create a recurring document in Quaderno that automatically generates invoices on a schedule. Use when setting up subscription billing or periodic invoices for a customer. |
| `QUADERNO_CREATE_REPORT_REQUEST` | Create Report Request | Tool to request a new report generation in Quaderno. Use when you need to generate tax summaries, invoice lists, or credit note lists for a specific date range. Reports are generated asynchronously - this action returns immediately with a 'pending' state. Use the List Reporting Requests action to poll for completion status and retrieve the download URL when the report is ready. |
| `QUADERNO_CREATE_TAX_ID` | Create Tax ID | Tool to create a tax ID in a specific jurisdiction. Use when you need to register your business's tax identification number (such as VAT) in a tax jurisdiction. |
| `QUADERNO_CREATE_TRANSACTION` | Create Transaction | Tool to create a sale or refund transaction in Quaderno. Use when you need to record revenue or refunds - the API automatically generates invoices/credit notes when autosend is enabled. Preferred API for automated invoice generation. |
| `QUADERNO_CREATE_WEBHOOK` | Create Webhook | Tool to create a new webhook in Quaderno to receive event notifications. Use when you need to subscribe to real-time events like invoice.created or contact.created. Quaderno signs all webhook events with X-Quaderno-Signature header using HMAC-SHA1. Retry logic: 1 attempt/hour for up to 72 hours. |
| `QUADERNO_DELETE_CONTACT` | Delete Contact | Tool to permanently delete a contact by ID. Use when you have confirmed the contact ID is correct and no longer need the contact. |
| `QUADERNO_DELETE_COUPON` | Delete Coupon | Tool to permanently delete a coupon. Use when you have confirmed the coupon ID is correct and need to remove it permanently (cannot be undone). |
| `QUADERNO_DELETE_ESTIMATE` | Delete Estimate | Permanently deletes an estimate from Quaderno by its ID. This action removes the estimate record from your Quaderno account. Use this when you need to delete an estimate that was created in error or is no longer needed. The deletion is permanent and cannot be undone. Returns an empty response on success (HTTP 204 No Content). |
| `QUADERNO_DELETE_EXPENSE` | Delete Expense | Permanently deletes an expense from Quaderno by its ID. This action removes the expense record from your Quaderno account. Use this when you need to delete an expense that was created in error or is no longer needed. The deletion is permanent and cannot be undone. Returns an empty response on success (HTTP 204 No Content). |
| `QUADERNO_DELETE_PRODUCT` | Delete Product | Tool to permanently delete a product by ID. Use when you have confirmed the product ID is correct and no longer need the product. |
| `QUADERNO_DELETE_RECURRING` | Delete Recurring | Tool to permanently delete a recurring by ID. Use when you need to remove a recurring document from Quaderno. This action is irreversible. |
| `QUADERNO_DELETE_TAX_ID` | Delete Tax ID | Permanently deletes a registered tax ID from your Quaderno account. Use this when you need to remove a tax jurisdiction registration that is no longer needed. |
| `QUADERNO_DELETE_WEBHOOK` | Delete Webhook | Tool to permanently delete a webhook by ID. Use when you have confirmed the webhook ID is correct and no longer need the webhook. |
| `QUADERNO_DELIVER_CREDIT_NOTE` | Deliver Credit Note | Sends a credit note to the customer via email. The contact associated with the credit note must have a valid email address. Returns the credit note details including the delivery email and PDF link. |
| `QUADERNO_DELIVER_ESTIMATE` | Deliver Estimate | Delivers an estimate to the customer via email. The estimate's contact must have a valid email address. Use this after creating or finalizing an estimate to send it to the customer. |
| `QUADERNO_DELIVER_INVOICE` | Deliver Invoice | Delivers an invoice to the customer via email. The invoice's contact must have a valid email address. Use this after creating or finalizing an invoice to send it to the customer. |
| `QUADERNO_DELIVER_RECEIPT` | Deliver Receipt | Sends a receipt to the customer via email. The contact associated with the receipt must have a valid email address. Returns the receipt details including the delivery email and PDF link. |
| `QUADERNO_GET_AUTHORIZATION` | Get Authorization | Tool to retrieve account credentials and verify API access. Use to validate authentication and get account details. |
| `QUADERNO_GET_ESTIMATE` | Get Estimate | Tool to retrieve the details of an existing estimate by ID. Use when you need full estimate information for review or conversion to invoice. |
| `QUADERNO_LIST_CONTACTS` | List Contacts | Tool to list contacts, paginated and filterable by name, email, or tax ID. Use when you need to retrieve subsets of your contacts. |
| `QUADERNO_LIST_COUPONS` | List Coupons | Tool to list all coupons. Use when you need to retrieve available coupons sorted by creation date (newest first). |
| `QUADERNO_LIST_CREDITS` | List Credits | Tool to list all credit notes from Quaderno. Use when you need to retrieve credit notes with optional filtering by search query, date range, state, or processor ID. |
| `QUADERNO_LIST_ESTIMATES` | List Estimates | Tool to list all estimates in the account, paginated and sorted by creation date (newest first). Use when you need to retrieve estimates, optionally filtered by contact name, state, or date range. |
| `QUADERNO_LIST_EVIDENCE` | List Evidence | Tool to list all evidence objects. Use when you need to retrieve location evidences, optionally filtered by state or document ID. |
| `QUADERNO_LIST_EXPENSES` | List Expenses | List all expenses from Quaderno with pagination support. Returns expenses in reverse chronological order (newest first). Each expense includes complete details: contact information, line items, payments, taxes, and custom metadata. Use the 'limit' parameter to control page size (1-100, default 25). Use 'created_before' with an expense ID to paginate through results. Example: List first 50 expenses: ListExpenses(limit=50) Example: Get next page: ListExpenses(limit=50, created_before=168878750) |
| `QUADERNO_LIST_INVOICES` | List Invoices | Tool to list all invoices from Quaderno with filtering support. Use when you need to retrieve invoices by various criteria such as number, customer name, date range, or payment status. |
| `QUADERNO_LIST_JURISDICTIONS` | List Tax Jurisdictions | Tool to list all tax jurisdictions. Use when you need supported jurisdictions for tax calculations. |
| `QUADERNO_LIST_PRODUCTS` | List Products | List all products (goods and services) from your Quaderno account. Supports filtering by name or SKU code using the 'q' parameter. Returns product details including pricing, tax settings, and subscription information. |
| `QUADERNO_LIST_RECEIPTS` | List Receipts | Tool to list all receipts from Quaderno with optional filtering by search query, date range, payment state, processor ID, or customer ID. Use when you need to retrieve receipts for reporting, reconciliation, or customer queries. |
| `QUADERNO_LIST_RECURRINGS` | List Recurrings | List all recurring documents (invoices, expenses, or estimates) from your Quaderno account. Recurring documents automatically generate new documents at specified intervals. Returns documents in reverse chronological order with support for pagination using the 'created_before' parameter. |
| `QUADERNO_LIST_REGISTERED_TAX_I_DS` | List Registered Tax IDs | Tool to list all registered tax IDs. Use when retrieving jurisdictions where your business has registered tax IDs. Supports optional cursor-based pagination. |
| `QUADERNO_LIST_REPORTING_REQUESTS` | List Reporting Requests | Retrieves all reporting requests for the account with their current status and download URLs. Use this tool to check the status of previously created reporting requests and obtain download URLs for completed reports. Reports are generated asynchronously, so use this endpoint to poll for completion status. When a report's state is 'succeeded', the report_url field will contain a temporary download link for the generated CSV file. Common use cases: - Check if a report generation request has completed - Retrieve download URLs for completed reports - Monitor all pending report requests - View historical report generations with their parameters (date ranges, report types) |
| `QUADERNO_LIST_SESSIONS` | List Sessions | List Quaderno Checkout sessions with optional filtering and pagination. Supports cursor-based pagination using 'created_before' and 'limit' parameters, and filtering by session status. Use this to retrieve checkout sessions from your Quaderno account. |
| `QUADERNO_LIST_TAX_CODES` | List Tax Codes | Tool to list all supported tax codes. Use when you need to retrieve the full set of tax codes for classifying items. |
| `QUADERNO_LIST_WEBHOOKS` | List Webhooks | Tool to list all webhooks. Use when you need to retrieve webhook configurations. |
| `QUADERNO_MARK_INVOICE_UNCOLLECTIBLE` | Mark Invoice Uncollectible | Tool to mark an invoice as uncollectible (bad debt). Use when an invoice cannot be collected and should be written off as a loss. |
| `QUADERNO_PING` | Ping API Service | Tool to check if the Quaderno API service is up and verify credentials. Use when testing API connectivity or checking service status before making actual requests. |
| `QUADERNO_RECORD_INVOICE_PAYMENT` | Record Invoice Payment | Tool to record a payment on an existing invoice. Use when a customer has paid an invoice and you need to record the payment details in Quaderno. |
| `QUADERNO_REMOVE_INVOICE_PAYMENT` | Remove Invoice Payment | Tool to remove a payment from an invoice. Use when you need to delete a payment record that was applied to an invoice in error or needs to be adjusted. |
| `QUADERNO_RETRIEVE_CONTACT` | Retrieve Contact | Tool to retrieve details of an existing contact by ID. Use after confirming contact ID. |
| `QUADERNO_RETRIEVE_CONTACT_BY_PROCESSOR_ID` | Retrieve Contact by Processor ID | Tool to retrieve a contact by external payment processor customer ID and gateway name. Use when you have the processor's customer ID instead of Quaderno's internal contact ID. |
| `QUADERNO_RETRIEVE_COUPON` | Retrieve Coupon | Retrieve detailed information about a specific coupon by its ID. Use this action when you need to fetch coupon details like discount percentage, redemption limits, or expiration dates. You must first obtain a valid coupon ID from the List Coupons action or from a coupon creation operation. Returns coupon code, discount amount/percentage, redemption statistics, and validity information. |
| `QUADERNO_RETRIEVE_CREDIT` | Retrieve Credit Note | Tool to retrieve details of an existing credit note by ID. Use when you need full credit note details for refund processing or reporting. |
| `QUADERNO_RETRIEVE_EVIDENCE` | Retrieve Evidence | Retrieves a specific evidence object by its ID. Evidence objects contain location proofs (billing country, IP address, bank country) used for tax compliance. Use this when you need detailed information about a specific evidence record, typically after obtaining the evidence ID from the LIST_EVIDENCE action. |
| `QUADERNO_RETRIEVE_EXPENSE` | Retrieve Expense | Tool to retrieve details of an existing expense by ID. Use after confirming expense ID. |
| `QUADERNO_RETRIEVE_INVOICE` | Retrieve Invoice | Tool to retrieve details of an existing invoice by ID. Use when you need full invoice details for reporting or reconciliation. |
| `QUADERNO_RETRIEVE_JURISDICTION` | Retrieve Tax Jurisdiction | Tool to retrieve a tax jurisdiction by ID. Use when you need the name, country, and region of a specific jurisdiction after confirming its ID. Example: "Retrieve jurisdiction 94". |
| `QUADERNO_RETRIEVE_PRODUCT` | Retrieve Product | Tool to retrieve details of an existing product by ID. Use after confirming the product ID exists. |
| `QUADERNO_RETRIEVE_RECEIPT` | Retrieve Receipt | Tool to retrieve details of an existing receipt by ID. Use when you need full receipt details for reporting or reconciliation. |
| `QUADERNO_RETRIEVE_RECURRING` | Retrieve Recurring | Tool to retrieve details of an existing recurring document by ID. Use when you need information about a recurring invoice or expense subscription. |
| `QUADERNO_RETRIEVE_REPORTING_REQUEST` | Retrieve Reporting Request | Tool to retrieve the status and download URL of a specific report request by ID. Use when you need to check if a report is ready and get the report_url to download it. |
| `QUADERNO_RETRIEVE_TAX_CODE` | Retrieve Tax Code | Tool to retrieve a specific tax code by ID. Use when you need details about a particular tax code classification. |
| `QUADERNO_RETRIEVE_TAX_ID` | Retrieve Tax ID | Tool to retrieve details of a specific tax ID by its ID. Use when you need to get information about a registered tax identification number. |
| `QUADERNO_UPDATE_CONTACT` | Update Contact | Tool to update an existing contact in Quaderno. Use when you need to modify contact details such as name, address, email, or tax information. |
| `QUADERNO_UPDATE_COUPON` | Update Coupon | Tool to update an existing coupon. Use when you need to modify coupon properties like discount amount, name, or redemption limits. Note: Coupons linked to Stripe cannot be edited and will return an error. Only fields provided in the request will be updated; omitted fields remain unchanged. |
| `QUADERNO_UPDATE_CREDIT_NOTE` | Update Credit Note | Tool to update a credit note. Use when you need to modify metadata, tags, notes, billing address, or attach files to an existing credit note. Only limited fields can be updated if it has already been paid or delivered. |
| `QUADERNO_UPDATE_ESTIMATE` | Update Estimate | Updates an existing estimate in Quaderno by modifying allowed fields. Use when you need to change estimate details like notes, purchase order number, tags, payment details, billing address, contact information, or line items. Fields not specified remain unchanged. |
| `QUADERNO_UPDATE_EVIDENCE` | Update Evidence | Tool to update an evidence object. Use when you need to modify location proofs (billing country, IP address, bank country, notes) for tax compliance records. |
| `QUADERNO_UPDATE_EXPENSE` | Update Expense | Updates an existing expense in Quaderno by modifying allowed fields. This action sends a PUT request to /expenses/{id}.json and returns the complete updated expense. Only specific fields can be modified: purchase order number (po_number), tags (tag_list), payment details (payment_details), notes, billing address (street_line_1, street_line_2), and custom metadata. Use this when you need to add or modify administrative information on an expense. Fields not specified in the request remain unchanged. |
| `QUADERNO_UPDATE_INVOICE` | Update Invoice | Updates an existing invoice in Quaderno by modifying allowed fields. This action sends a PUT request to /invoices/{id} and returns the complete updated invoice. Only specific fields can be modified after invoice creation: purchase order number (po_number), tags (tag_list), payment details (payment_details), notes, billing address (street_line_1, street_line_2), custom metadata, and file attachments. Use this when you need to add or modify administrative information on an invoice that hasn't been finalized or paid. Fields not specified in the request remain unchanged. |
| `QUADERNO_UPDATE_PRODUCT` | Update product | Tool to update a product; unspecified fields remain unchanged. Use after fetching the product to apply partial updates. |
| `QUADERNO_UPDATE_RECURRING` | Update Recurring | Tool to update a recurring document in Quaderno. Use when you need to modify subscription details, billing information, line items, or recurring schedule. Only specified fields are updated; unspecified fields remain unchanged. |
| `QUADERNO_UPDATE_TAX_ID` | Update Tax ID | Tool to update an existing tax ID in Quaderno. Use when you need to modify tax ID details such as validity dates, value, or establishment settings. |
| `QUADERNO_UPDATE_WEBHOOK` | Update Webhook | Tool to update an existing webhook configuration. Use when you need to modify webhook URL or event subscriptions. |
| `QUADERNO_VALIDATE_TAX_ID` | Validate Tax ID | Tool to validate a tax ID. Use when confirming whether a given country-specific tax ID is valid. Example: validate tax ID 'DE303954554' for Germany. |
| `QUADERNO_VOID_CREDIT_NOTE` | Void Credit Note | Tool to void a credit note. Use when you need to cancel an existing credit note. |

## Supported Triggers

None listed.

## Creating MCP Server - Stand-alone vs Composio SDK

The Quaderno MCP server is an implementation of the Model Context Protocol that connects your AI agent to Quaderno. It provides structured and secure access so your agent can perform Quaderno operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Composio API Key and OpenAI API Key
- Primary know-how of OpenAI Agents SDK
- A live Quaderno project
- Some knowledge of Python or Typescript

### 1. Getting API Keys for OpenAI and Composio

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Go to Settings and copy your API key.

### 2. Install dependencies

Install the Composio SDK and the OpenAI Agents SDK.
```python
pip install composio_openai_agents openai-agents python-dotenv
```

```typescript
npm install @composio/openai-agents @openai/agents dotenv
```

### 3. Set up environment variables

Create a .env file and add your OpenAI and Composio API keys.
```bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com
```

### 4. Import dependencies

What's happening:
- You're importing all necessary libraries.
- The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like Quaderno.
```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
```

### 5. Set up the Composio instance

No description provided.
```python
load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())
```

```typescript
dotenv.config();

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
```

### 6. Create a Tool Router session

What is happening:
- You give the Tool Router the user id and the toolkits you want available. Here, it is only quaderno.
- The router checks the user's Quaderno connection and prepares the MCP endpoint.
- The returned session.mcp.url is the MCP URL that your agent will use to access Quaderno.
- This approach keeps things lightweight and lets the agent request Quaderno tools only when needed during the conversation.
```python
# Create a Quaderno Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["quaderno"]
)

mcp_url = session.mcp.url
```

```typescript
// Create Tool Router session for Quaderno
const session = await composio.create(userId as string, {
  toolkits: ['quaderno'],
});
const mcpUrl = session.mcp.url;
```

### 7. Configure the agent

No description provided.
```python
# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Quaderno. "
        "Help users perform Quaderno operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)
```

```typescript
// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access Quaderno. Help users perform Quaderno operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
```

### 8. Start chat loop and handle conversation

No description provided.
```python
print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

// Simple CLI
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'You: ',
});

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

  if (!text) {
    rl.prompt();
    return;
  }

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession

load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())

# Create Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["quaderno"]
)
mcp_url = session.mcp.url

# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Quaderno. "
        "Help users perform Quaderno operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)

print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['quaderno'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access Quaderno. Help users perform Quaderno operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

  // Simple CLI
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: ',
  });

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

    if (!text) {
      rl.prompt();
      return;
    }

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\n');
    }

    rl.prompt();
  });

  rl.on('close', () => {
    console.log('\nSession ended.');
    process.exit(0);
  });
}

main().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
```

## Conclusion

This was a starter code for integrating Quaderno MCP with OpenAI Agents SDK to build a functional AI agent that can interact with Quaderno.
Key features:
- Hosted MCP tool integration through Composio's Tool Router
- SQLite session persistence for conversation history
- Simple async chat loop for interactive testing
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.

## How to build Quaderno MCP Agent with another framework

- [Claude Agent SDK](https://composio.dev/toolkits/quaderno/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/quaderno/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/quaderno/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/quaderno/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/quaderno/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/quaderno/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/quaderno/framework/cli)
- [Google ADK](https://composio.dev/toolkits/quaderno/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/quaderno/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/quaderno/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/quaderno/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/quaderno/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/quaderno/framework/crew-ai)

## Related Toolkits

- [Stripe](https://composio.dev/toolkits/stripe) - Stripe is a global online payments platform offering APIs for managing payments, customers, and subscriptions. Trusted by businesses for secure, efficient, and scalable payment processing worldwide.
- [Alpha vantage](https://composio.dev/toolkits/alpha_vantage) - Alpha Vantage is a financial data platform offering real-time and historical stock market APIs. Get instant, reliable access to equities, forex, and technical analysis data for smarter trading decisions.
- [Altoviz](https://composio.dev/toolkits/altoviz) - Altoviz is a cloud-based billing and invoicing platform for businesses. It streamlines online payments, expense tracking, and customizable invoice management.
- [Benzinga](https://composio.dev/toolkits/benzinga) - Benzinga provides real-time financial news and data APIs for market coverage. It helps you track breaking news and actionable market insights instantly.
- [Brex](https://composio.dev/toolkits/brex) - Brex provides corporate credit cards and spend management tailored for startups and tech businesses. It helps optimize company cash flow, streamline accounting, and accelerate business growth.
- [Chaser](https://composio.dev/toolkits/chaser) - Chaser is accounts receivable automation software that sends invoice reminders and helps businesses get paid faster. It streamlines the collections process to save time and improve cash flow.
- [Clientary](https://composio.dev/toolkits/clientary) - Clientary is a platform for managing clients, invoices, projects, proposals, and more. It streamlines client work and saves you serious admin time.
- [Coinbase](https://composio.dev/toolkits/coinbase) - Coinbase is a platform for buying, selling, and storing cryptocurrency. It makes exchanging and managing crypto simple and secure for everyone.
- [Coinranking](https://composio.dev/toolkits/coinranking) - Coinranking is a comprehensive cryptocurrency market data platform offering access to real-time coin prices, market caps, and historical data. Get accurate, up-to-date stats for thousands of digital assets in one place.
- [Coupa](https://composio.dev/toolkits/coupa) - Coupa is a business spend management platform for procurement, invoicing, and expenses. It helps organizations streamline purchasing, control costs, and gain complete visibility over financial operations.
- [CurrencyScoop](https://composio.dev/toolkits/currencyscoop) - CurrencyScoop is a developer-friendly API for real-time and historical currency exchange rates. Easily access fiat and crypto data for smart, up-to-date financial applications.
- [Daffy](https://composio.dev/toolkits/daffy) - Daffy is a modern charitable giving platform with a donor-advised fund. Easily set aside funds, grow them tax-free, and donate to over 1.7 million U.S. charities.
- [Eagle doc](https://composio.dev/toolkits/eagle_doc) - Eagle doc is an AI-powered OCR API for invoices and receipts. It delivers fast, reliable, and accurate document data extraction for seamless automation.
- [Elorus](https://composio.dev/toolkits/elorus) - Elorus is an online invoicing and time-tracking software for freelancers and small businesses. Easily manage finances, bill clients, and track work in one place.
- [Eodhd apis](https://composio.dev/toolkits/eodhd_apis) - Eodhd apis delivers comprehensive financial data, including live and historical stock prices, via robust APIs. Easily access reliable, up-to-date market insights to power your apps, dashboards, and analytics.
- [Fidel api](https://composio.dev/toolkits/fidel_api) - Fidel api is a secure platform for linking payment cards to web and mobile apps. It enables real-time card transaction monitoring and event-based automation for businesses.
- [Finage](https://composio.dev/toolkits/finage) - Finage is a secure API platform delivering real-time and historical financial data for stocks, forex, crypto, indices, and commodities. It empowers developers and businesses to access, analyze, and act on market data instantly.
- [Finmei](https://composio.dev/toolkits/finmei) - Finmei is an invoicing tool that simplifies billing, invoice management, and expense tracking. Ideal for automating and organizing your business finances in one place.
- [Fixer](https://composio.dev/toolkits/fixer) - Fixer is a currency data API offering real-time and historical exchange rates for 170 currencies. Instantly access accurate, up-to-date forex data for your applications and workflows.
- [Fixer io](https://composio.dev/toolkits/fixer_io) - Fixer.io is a lightweight API for real-time and historical foreign exchange rates. It makes global currency conversion fast, accurate, and hassle-free.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Quaderno MCP?

With a standalone Quaderno MCP server, the agents and LLMs can only access a fixed set of Quaderno tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Quaderno and many other apps based on the task at hand, all through a single MCP endpoint.

### Can I use Tool Router MCP with OpenAI Agents SDK?

Yes, you can. OpenAI Agents SDK fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Quaderno tools.

### Can I manage the permissions and scopes for Quaderno while using Tool Router?

Yes, absolutely. You can configure which Quaderno scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

### How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Quaderno data and credentials are handled as safely as possible.

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
