# How to integrate Documenso MCP with OpenAI Agents SDK

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

## Introduction

This guide walks you through connecting Documenso to the OpenAI Agents SDK using the Composio tool router. By the end, you'll have a working Documenso agent that can send a contract to client for signature, download the latest signed nda document, list all templates for onboarding paperwork through natural language commands.
This guide will help you understand how to give your OpenAI Agents SDK agent real control over a Documenso account through Composio's Documenso MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Documenso with

- [Claude Agent SDK](https://composio.dev/toolkits/documenso/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/documenso/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/documenso/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/documenso/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/documenso/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/documenso/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/documenso/framework/cli)
- [Google ADK](https://composio.dev/toolkits/documenso/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/documenso/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/documenso/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/documenso/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/documenso/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/documenso/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 Documenso
- Configure an AI agent that can use Documenso as a tool
- Run a live chat session where you can ask the agent to perform Documenso 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 Documenso MCP server, and what's possible with it?

The Documenso MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Documenso account. It provides structured and secure access to your electronic signature workflows, so your agent can create documents, distribute them for signing, manage templates, and download signed files automatically on your behalf.
- Automated document creation and duplication: Prompt your agent to generate new documents or make exact copies of existing ones for rapid workflow setup.
- Seamless document distribution for signatures: Let your agent send documents to one or more recipients, kicking off secure e-signature flows without manual intervention.
- Template management and retrieval: Ask your agent to list, fetch, or delete document templates, keeping your signing processes organized and up-to-date.
- Download and access signed documents: Have your agent retrieve finalized, signed PDFs automatically for seamless archiving or sharing.
- Streamlined document organization: Direct your agent to move documents between personal and team spaces, or remove unnecessary fields to keep everything tidy and current.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `DOCUMENSO_CREATE_DOCUMENT_BETA` | Create Document Beta | Tool to create a new document using the beta endpoint that returns a presigned URL for file upload. After calling this action, upload the PDF file to the returned uploadUrl using a PUT request. Use when you need to create a document and upload the file separately. |
| `DOCUMENSO_CREATE_DOCUMENT_FIELD` | Create Document Field | Tool to create a single field for a document. Use when you need to add a signature, initials, text, or other field type to a specific location on a document page. The document must be in DRAFT status to add fields. |
| `DOCUMENSO_CREATE_DOCUMENT_FIELDS_BULK` | Create Document Fields (Bulk) | Tool to create multiple fields on a document in a single operation. Use when you need to add signature fields, text fields, or other input fields to a DRAFT document. This bulk operation is more efficient than creating fields one at a time. All fields must reference valid recipient IDs from the document. |
| `DOCUMENSO_CREATE_DOCUMENT_RECIPIENT` | Create Document Recipient | Tool to create a single recipient for a document. Use when you need to add a new recipient (signer, viewer, approver, etc.) to an existing document. |
| `DOCUMENSO_CREATE_DOCUMENT_RECIPIENTS_BULK` | Create Document Recipients Bulk | Tool to create multiple recipients for a document at once. Use when you need to add multiple recipients (signers, approvers, viewers, etc.) to a document in a single operation. The document must be in DRAFT status before adding recipients. |
| `DOCUMENSO_CREATE_EMBEDDING_PRESIGN_TOKEN_V2_BETA` | Create Embedding Presign Token V2 Beta | Create a presign token for Documenso embedded authoring sessions. Use this tool to generate a token that authorizes embedding document/template creation and editing interfaces in your application. The token is passed to Documenso embed components (EmbedCreateDocument, EmbedUpdateDocument, etc.). Note: This feature requires a Documenso Teams Plan or above. Returns 401 UNAUTHORIZED if the account lacks embedding permissions. |
| `DOCUMENSO_CREATE_ENVELOPE` | Create Envelope | Tool to create a new envelope in Documenso. Use when you need to create a document or template envelope with optional file uploads, recipients, and configuration settings. The envelope can be configured with signing order, authentication requirements, and notification settings. |
| `DOCUMENSO_CREATE_ENVELOPE_ATTACHMENT` | Create Envelope Attachment | Create a new attachment for an envelope in Documenso. Use this action to add supporting documents or files to an existing envelope. The file must be provided as a base64-encoded data URI in the format: data:;base64,. |
| `DOCUMENSO_CREATE_ENVELOPE_ITEMS_BULK` | Create Envelope Items Bulk | Tool to create multiple items for an envelope with optional file attachments. Use when you need to add items (documents) to an existing envelope in Documenso. |
| `DOCUMENSO_CREATE_ENVELOPE_RECIPIENTS_BULK` | Create Envelope Recipients Bulk | Tool to create multiple recipients for an envelope in bulk. Use when you need to add several recipients to an existing envelope at once. Each recipient must have an email, name, and role (SIGNER, APPROVER, VIEWER, ASSISTANT, or CC). |
| `DOCUMENSO_CREATE_FOLDER` | Create Folder | Create a new folder in Documenso to organize documents or templates. Use this action when you need to create a folder for organizing files, either as a top-level folder or nested within an existing folder. |
| `DOCUMENSO_CREATE_TEMPLATE_BETA` | Create Template Beta | Tool to create a new template using the beta endpoint that returns a presigned URL for file upload. After calling this action, upload the PDF file to the returned uploadUrl using a PUT request. Use when you need to create a template and upload the file separately. |
| `DOCUMENSO_CREATE_TEMPLATE_FIELD` | Create Template Field | Tool to create a single field for a template. Use when you need to add a signature, initials, text, or other field type to a specific location on a template page. |
| `DOCUMENSO_CREATE_TEMPLATE_FIELDS_BULK` | Create Template Fields (Bulk) | Tool to create multiple fields on a template in a single operation. Use when you need to add signature fields, text fields, or other input fields to a template. This bulk operation is more efficient than creating fields one at a time. All fields must reference valid recipient IDs from the template. |
| `DOCUMENSO_CREATE_TEMPLATE_RECIPIENT` | Create Template Recipient | Tool to create a single recipient for a template. Use when you need to add a new recipient (signer, viewer, approver, etc.) to an existing template. |
| `DOCUMENSO_CREATE_TEMPLATE_RECIPIENTS_BULK` | Create Template Recipients Bulk | Tool to create multiple recipients for a template at once. Use when you need to add multiple recipients (signers, approvers, viewers, etc.) to a template in a single operation. |
| `DOCUMENSO_DELETE_DOCUMENT` | Delete Document | Tool to delete a document. Use when you need to permanently remove a document from Documenso. The deletion is irreversible. |
| `DOCUMENSO_DELETE_DOCUMENT_ATTACHMENT` | Delete Document Attachment | Tool to delete an attachment from a document. Use when you need to remove a previously uploaded attachment from a document. The deletion is permanent. |
| `DOCUMENSO_DELETE_DOCUMENT_FIELD` | Delete Document Field | Tool to delete a single document field by ID. Use when you need to remove a specific field from a document. |
| `DOCUMENSO_DELETE_DOCUMENT_FIELDS` | Delete Document Fields | Tool to delete one or more fields from a document. Use when you have confirmed the field IDs to remove. Supports single-field and batch deletion. |
| `DOCUMENSO_DELETE_DOCUMENT_RECIPIENT` | Delete Document Recipient | Tool to delete a recipient from a document. Use when you need to remove a recipient from a document's signing workflow. |
| `DOCUMENSO_DELETE_ENVELOPE` | Delete Envelope | Tool to permanently delete an envelope. Use when you need to remove an envelope from Documenso. The deletion is irreversible and will remove all associated data. |
| `DOCUMENSO_DELETE_ENVELOPE_ATTACHMENT` | Delete Envelope Attachment | Tool to delete an attachment from an envelope. Use when you need to remove a file attachment from a Documenso envelope. |
| `DOCUMENSO_DELETE_ENVELOPE_FIELD` | Delete Envelope Field | Tool to delete a field from an envelope. Use when you need to remove an existing field from a document envelope. |
| `DOCUMENSO_DELETE_ENVELOPE_ITEM` | Delete Envelope Item | Tool to delete an item from an envelope. Use when you need to remove an existing item from a document envelope. |
| `DOCUMENSO_DELETE_ENVELOPE_RECIPIENT` | Delete Envelope Recipient | Tool to delete a recipient from an envelope. Use when you need to remove a recipient from an envelope's signing workflow. |
| `DOCUMENSO_DELETE_FOLDER` | Delete Folder | Tool to permanently delete a folder. Use when you need to remove a folder from Documenso. The deletion is irreversible and will remove all associated data. |
| `DOCUMENSO_DELETE_TEMPLATE` | Delete Template | Permanently delete a template by its ID. Use this action when you need to remove an existing document template from your Documenso account. The deletion is irreversible. Returns success=true with HTTP 200 if deleted, or success=false with HTTP 404 and message='Template not found' if the template does not exist. |
| `DOCUMENSO_DELETE_TEMPLATE_DIRECT_LINK` | Delete Template Direct Link | Delete a direct link for a template. Use this action when you need to remove public direct access to a template. |
| `DOCUMENSO_DELETE_TEMPLATE_RECIPIENT` | Delete Template Recipient | Tool to delete a recipient from a template. Use when you need to remove a recipient from a template's configuration. |
| `DOCUMENSO_DELETE_TEMPLATE_V2` | Delete Template V2 | Tool to permanently delete a template using the v2 API. Use when you need to remove a template from Documenso. The deletion is irreversible. |
| `DOCUMENSO_DISTRIBUTE_DOCUMENT_V2` | Distribute Document V2 | Tool to distribute a document for signing. Use when you need to send a DRAFT document to recipients for the first time. The document must have recipients with signature fields configured before distribution. For re-sending to recipients who already received the document, use Redistribute Document instead. |
| `DOCUMENSO_DISTRIBUTE_ENVELOPE` | Distribute Envelope | Tool to distribute an envelope to recipients for signing. Use when you need to send an envelope to recipients for the first time. The envelope must have recipients with required signature fields configured before distribution. Returns success status of the distribution operation. |
| `DOCUMENSO_DOWNLOAD_ENVELOPE_ITEM` | Download Envelope Item | Download an envelope item as PDF. Use this to retrieve the original or signed version of a document within an envelope. The "signed" version includes all signatures and is available after recipients have signed, while "original" returns the document as initially uploaded. First use DOCUMENSO_GET_ENVELOPE_BY_ID to obtain valid envelope item IDs. |
| `DOCUMENSO_DOWNLOAD_SIGNED_DOCUMENT` | Download Signed Document | Download a completed/signed document as PDF. Use this to retrieve the finalized PDF after all recipients have signed. Important: Only documents with status 'COMPLETED' can be downloaded successfully; attempting to download documents in DRAFT or PENDING status will return an error response. First use DOCUMENSO_FIND_DOCUMENTS_V2 with status='COMPLETED' to find downloadable documents. |
| `DOCUMENSO_DUPLICATE_DOCUMENT_V2` | Duplicate Document V2 | Tool to duplicate a document. Use when you need to create an exact copy of an existing document. Ensure the source document ID is valid before calling. |
| `DOCUMENSO_DUPLICATE_ENVELOPE_V2` | Duplicate Envelope V2 | Tool to duplicate an envelope with all its settings. Use when you need to create an exact copy of an existing envelope including recipients, fields, and configuration. |
| `DOCUMENSO_DUPLICATE_TEMPLATE` | Duplicate Template | Tool to duplicate a template with all its settings. Use when you need to create an exact copy of an existing template including fields, recipients, and configuration. |
| `DOCUMENSO_FIND_DOCUMENTS` | Find Documents | Find documents based on search criteria with filtering and pagination. Use when searching for documents by title, status, template, folder, or source. Supports pagination for retrieving large result sets efficiently. |
| `DOCUMENSO_FIND_DOCUMENTS_V2` | Find Documents V2 | Retrieve a paginated list of documents with optional filtering and sorting. Use this action to list documents, search by title, or filter by status (DRAFT, PENDING, COMPLETED). Commonly used to obtain document IDs for subsequent operations like downloading, updating, or deleting documents. |
| `DOCUMENSO_FIND_ENVELOPES` | Find Envelopes | Tool to find envelopes based on search criteria, filters, and pagination. Use this action to search and filter envelopes by query, type, status, source, template ID, or folder ID. Commonly used to retrieve envelope lists for management, reporting, or subsequent operations. |
| `DOCUMENSO_FIND_FOLDERS` | Find Folders | Tool to find folders based on search criteria and filters. Use this action to search folders by name, filter by type (DOCUMENT or TEMPLATE), or retrieve subfolders by parent ID. Commonly used to organize documents/templates or retrieve folder IDs for subsequent operations. |
| `DOCUMENSO_FIND_TEMPLATES` | Find Templates | Retrieve a paginated list of templates with optional filtering and search. Use this action to find templates, search by title/content, or filter by type (PUBLIC, PRIVATE) or folder. Commonly used to obtain template IDs for subsequent operations like using, updating, or deleting templates. |
| `DOCUMENSO_GET_DOCUMENT_BY_ID` | Get Document By ID | Retrieve complete information about a document by its ID. Returns full document details including metadata, recipients, fields, and signing status. Use find_documents_v2 first to get valid document IDs. |
| `DOCUMENSO_GET_DOCUMENT_FIELD` | Get Document Field | Tool to retrieve a document field by its ID. Use when you need to fetch details about a specific field including its type, position, recipient assignment, and metadata. Useful for inspecting field properties before updating or for validating field configurations. |
| `DOCUMENSO_GET_DOCUMENT_RECIPIENT` | Get Document Recipient | Tool to retrieve detailed information about a document recipient by their ID. Use when you need to check the status, fields, or other details of a specific recipient. |
| `DOCUMENSO_GET_DOCUMENTS_BY_IDS` | Get Documents By IDs | Retrieve multiple documents by their IDs in a single request. Use when you need to fetch detailed information for specific documents. This is more efficient than calling individual get document endpoints when retrieving multiple documents. |
| `DOCUMENSO_GET_ENVELOPE_ATTACHMENT` | Get Envelope Attachment | Tool to find all attachments for a specific envelope. Use this when you need to retrieve attachment information including IDs, types, labels, and data for all attachments associated with an envelope. |
| `DOCUMENSO_GET_ENVELOPE_AUDIT_LOG` | Get Envelope Audit Log | Tool to retrieve audit logs for an envelope. Use this to track all actions performed on an envelope, including who accessed it, when, and from where. Useful for compliance, tracking document history, and debugging workflow issues. |
| `DOCUMENSO_GET_ENVELOPE_BY_ID` | Get Envelope By ID | Retrieve complete information about an envelope by its ID. Returns full envelope details including metadata, recipients, fields, and signing status. Use find_envelopes first to get valid envelope IDs. |
| `DOCUMENSO_GET_ENVELOPE_FIELD` | Get Envelope Field | Tool to fetch an envelope field by ID. Use this to retrieve detailed information about a specific field in an envelope, including its type, position, dimensions, and metadata configuration. |
| `DOCUMENSO_GET_ENVELOPE_RECIPIENT` | Get Envelope Recipient | Tool to retrieve detailed information about an envelope recipient by their ID. Use when you need to check the status, fields, or other details of a specific recipient. |
| `DOCUMENSO_GET_ENVELOPES_BY_IDS` | Get Envelopes By IDs | Tool to retrieve multiple envelopes by their IDs. Use this action when you need to fetch multiple envelopes in a single request using envelope IDs, document IDs, or template IDs. Specify the ID type and provide an array of IDs to retrieve. |
| `DOCUMENSO_GET_TEMPLATE_BY_ID` | Get Template By ID | Retrieve complete information about a template by its ID. Returns full template details including metadata, recipients, fields, and configuration settings. Use find_templates or list_templates first to get valid template IDs. |
| `DOCUMENSO_GET_TEMPLATE_FIELD` | Get Template Field | Tool to fetch a template field by ID. Use this to retrieve detailed information about a specific field in a template, including its type, position, dimensions, and metadata configuration. |
| `DOCUMENSO_GET_TEMPLATE_RECIPIENT` | Get Template Recipient | Tool to retrieve detailed information about a template recipient by their ID. Use when you need to check the status, fields, or other details of a specific template recipient. |
| `DOCUMENSO_GET_TEMPLATES_BY_IDS` | Get Templates By IDs | Retrieve multiple templates by their IDs in a single request. Use when you need to fetch detailed information for specific templates. This is more efficient than calling individual get template endpoints when retrieving multiple templates. |
| `DOCUMENSO_LIST_TEMPLATES` | List Templates | Tool to list templates. Use when fetching available templates with optional pagination. |
| `DOCUMENSO_MOVE_DOCUMENT_V2` | Move Document V2 | Tool to move a document to a team. Use when transferring documents between personal and team accounts. |
| `DOCUMENSO_REDISTRIBUTE_DOCUMENT_V2` | Redistribute Document V2 | Re-send signing request emails to specified recipients of a document. Use this when recipients haven't received or lost their signing emails, or when you need to remind them to sign. The document must be in PENDING status and the recipients must belong to the document. |
| `DOCUMENSO_REDISTRIBUTE_ENVELOPE` | Redistribute Envelope | Tool to redistribute an envelope to recipients who have not actioned it. Use when recipients haven't received or lost their signing emails, or when you need to remind them to sign. The envelope must be in PENDING status and the recipients must belong to the envelope and not have already completed their action. |
| `DOCUMENSO_REMOVE_TEAM_MEMBER_V1` | Remove Team Member V1 | Remove a member from a Documenso team. This action removes an existing member from the specified team. The caller must have appropriate permissions (typically team owner or manager) to remove members. Note: The team_id can be obtained from documents that belong to a team (teamId field in document responses). The member_id should be obtained by listing team members first. |
| `DOCUMENSO_UPDATE_DOCUMENT_ATTACHMENT` | Update Document Attachment | Tool to update an existing document attachment. Use when you need to change the label or file URL of an attachment. Requires the attachment ID and updated data (label and URL). |
| `DOCUMENSO_UPDATE_DOCUMENT_FIELD` | Update Document Field | Tool to update a single document field's properties in Documenso v2 API. Use when you need to modify position, size, or type of an existing field. The field type must always be provided even when updating other properties. |
| `DOCUMENSO_UPDATE_DOCUMENT_FIELDS_BULK` | Update Document Fields Bulk | Tool to update multiple document fields in a single operation. Use when you need to modify properties (position, size, type) of multiple fields at once. This is more efficient than updating fields individually. The document must be in DRAFT status - fields on documents that have been sent for signing cannot be updated. |
| `DOCUMENSO_UPDATE_DOCUMENT_RECIPIENT_V2` | Update Document Recipient V2 | Tool to update a document recipient using the v2 API. Use to change recipient name, email, role, signing order, or authentication options for a specific document recipient. |
| `DOCUMENSO_UPDATE_DOCUMENT_V2` | Update Document V2 | Update document properties like title, visibility, and signing settings. Use find_documents_v2 first to get a valid document ID. Only DRAFT documents can have all properties updated; PENDING documents have limited updates. |
| `DOCUMENSO_UPDATE_ENVELOPE` | Update Envelope | Update envelope properties like title, visibility, and signing settings. Use find_envelopes first to get a valid envelope ID. Only DRAFT envelopes can have all properties updated; PENDING envelopes have limited updates. |
| `DOCUMENSO_UPDATE_ENVELOPE_ATTACHMENT` | Update Envelope Attachment | Tool to update an existing envelope attachment. Use when you need to modify the label or content of an attachment that was previously added to an envelope. The attachment data must be provided in base64-encoded data URI format. |
| `DOCUMENSO_UPDATE_ENVELOPE_FIELDS_BULK` | Update Envelope Fields Bulk | Tool to update multiple envelope fields in a single request. Use when you need to modify properties of multiple existing fields (position, size, type) efficiently. All position and dimension values must be between 0 and 100. The type field is required for all updates, even when only changing position or dimensions. |
| `DOCUMENSO_UPDATE_ENVELOPE_ITEMS_BULK` | Update Envelope Items Bulk | Tool to update multiple envelope items in a single request. Use when you need to modify the title or order of multiple envelope items belonging to the same envelope. This is more efficient than updating items individually when making bulk changes. |
| `DOCUMENSO_UPDATE_FOLDER` | Update Folder | Update properties of an existing folder including name, pinned status, parent folder, and visibility. Use this action to reorganize folder structure or modify folder settings. |
| `DOCUMENSO_UPDATE_TEMPLATE` | Update Template | Update template properties like title, visibility, and signing settings. Use list_templates or find_templates first to get a valid template ID. |
| `DOCUMENSO_UPDATE_TEMPLATE_FIELDS_BULK` | Update Template Fields Bulk | Tool to update multiple template fields in a single operation. Use when you need to modify properties (position, size, type) of multiple fields at once on a template. This is more efficient than updating fields individually. |
| `DOCUMENSO_UPDATE_TEMPLATE_RECIPIENT` | Update Template Recipient | Tool to update a template recipient. Use to change recipient name, email, role, signing order, or authentication options for a specific template recipient. |
| `DOCUMENSO_UPDATE_TEMPLATE_RECIPIENTS_BULK` | Update Template Recipients Bulk | Tool to update multiple template recipients in a single API call. Use when you need to change properties (name, email, role, signing order, authentication) for multiple recipients on the same template efficiently. |
| `DOCUMENSO_USE_TEMPLATE_V2_BETA` | Use Template (v2-beta) | Tool to create a document from a template. Use when you need to instantiate a template with recipients and optional prefills. |

## Supported Triggers

None listed.

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

The Documenso MCP server is an implementation of the Model Context Protocol that connects your AI agent to Documenso. It provides structured and secure access so your agent can perform Documenso 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 Documenso 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 Documenso.
```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 documenso.
- The router checks the user's Documenso connection and prepares the MCP endpoint.
- The returned session.mcp.url is the MCP URL that your agent will use to access Documenso.
- This approach keeps things lightweight and lets the agent request Documenso tools only when needed during the conversation.
```python
# Create a Documenso Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["documenso"]
)

mcp_url = session.mcp.url
```

```typescript
// Create Tool Router session for Documenso
const session = await composio.create(userId as string, {
  toolkits: ['documenso'],
});
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 Documenso. "
        "Help users perform Documenso 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 Documenso. Help users perform Documenso 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=["documenso"]
)
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 Documenso. "
        "Help users perform Documenso 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: ['documenso'],
  });
  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 Documenso. Help users perform Documenso 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 Documenso MCP with OpenAI Agents SDK to build a functional AI agent that can interact with Documenso.
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 Documenso MCP Agent with another framework

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

## Related Toolkits

- [Google Drive](https://composio.dev/toolkits/googledrive) - Google Drive is a cloud storage platform for uploading, sharing, and collaborating on files. It's perfect for keeping your documents accessible and organized across devices.
- [Google Docs](https://composio.dev/toolkits/googledocs) - Google Docs is a cloud-based word processor that enables document creation and real-time collaboration. Its seamless sharing and version history make team editing and content management a breeze.
- [Google Super](https://composio.dev/toolkits/googlesuper) - Google Super is an all-in-one suite combining Gmail, Drive, Calendar, Sheets, Analytics, and more. It gives you a unified platform to manage your digital life, boosting productivity and organization.
- [Affinda](https://composio.dev/toolkits/affinda) - Affinda is an AI-powered document processing platform that automates data extraction from resumes, invoices, and more. It streamlines document-heavy workflows by turning files into structured, actionable data.
- [Agility cms](https://composio.dev/toolkits/agility_cms) - Agility CMS is a headless content management system for building and managing digital experiences across platforms. It lets teams update content quickly and deliver omnichannel experiences with ease.
- [Algodocs](https://composio.dev/toolkits/algodocs) - Algodocs is an AI-powered platform that automates data extraction from business documents. It delivers fast, secure, and accurate processing without templates or manual training.
- [Api2pdf](https://composio.dev/toolkits/api2pdf) - Api2Pdf is a REST API for generating PDFs from HTML, URLs, and documents using powerful engines like wkhtmltopdf and Headless Chrome. It streamlines document conversion and automation for developers and businesses.
- [Aryn](https://composio.dev/toolkits/aryn) - Aryn is an AI-powered platform for parsing, extracting, and analyzing data from unstructured documents. Use it to automate document processing and unlock actionable insights from your files.
- [Boldsign](https://composio.dev/toolkits/boldsign) - Boldsign is a digital eSignature platform for sending, signing, and tracking documents online. Organizations use it to automate agreements and manage legally binding workflows efficiently.
- [Boloforms](https://composio.dev/toolkits/boloforms) - BoloForms is an eSignature platform built for small businesses, offering unlimited signatures, templates, and forms. It simplifies digital document signing and team collaboration at a predictable, fixed price.
- [Box](https://composio.dev/toolkits/box) - Box is a cloud content management and file sharing platform for businesses. It helps teams securely store, organize, and collaborate on files from anywhere.
- [Carbone](https://composio.dev/toolkits/carbone) - Carbone is a blazing-fast report generator that turns JSON data into PDFs, Word docs, spreadsheets, and more using flexible templates. It lets you automate document creation at scale with minimal code.
- [Castingwords](https://composio.dev/toolkits/castingwords) - CastingWords is a transcription service specializing in human-powered, accurate transcripts via a simple API. Get seamless audio-to-text conversion for interviews, meetings, podcasts, and more.
- [Cloudconvert](https://composio.dev/toolkits/cloudconvert) - CloudConvert is a powerful file conversion service supporting over 200 file formats. It streamlines converting, compressing, and managing documents, media, and more, all in one place.
- [Cloudlayer](https://composio.dev/toolkits/cloudlayer) - Cloudlayer is a document and asset generation service for creating PDFs and images via API or SDKs. It lets you automate high-quality doc creation, saving dev time and reducing manual work.
- [Cloudpress](https://composio.dev/toolkits/cloudpress) - Cloudpress is a content export tool for Google Docs and Notion. It automates publishing to your favorite Content Management Systems.
- [Contentful graphql](https://composio.dev/toolkits/contentful_graphql) - Contentful graphql is a content delivery API that lets you access Contentful data using GraphQL queries. It gives you efficient, flexible ways to fetch and manage structured content for any digital project.
- [Conversion tools](https://composio.dev/toolkits/conversion_tools) - Conversion Tools is an online service for converting documents between formats such as PDF, Word, Excel, XML, and CSV. It lets you automate complex document workflows with just a few clicks.
- [Convertapi](https://composio.dev/toolkits/convertapi) - ConvertAPI is a robust file conversion service for documents, images, and spreadsheets. It streamlines programmatic format changes and lets developers automate complex workflows with a single API.
- [Craftmypdf](https://composio.dev/toolkits/craftmypdf) - CraftMyPDF is a web-based service for designing and generating PDFs with templates and live data. It streamlines document creation by automating personalized PDFs at scale.

## Frequently Asked Questions

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

With a standalone Documenso MCP server, the agents and LLMs can only access a fixed set of Documenso tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Documenso 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 Documenso tools.

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

Yes, absolutely. You can configure which Documenso 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 Documenso data and credentials are handled as safely as possible.

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