# How to integrate Encodian MCP with OpenAI Agents SDK

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

## Introduction

This guide walks you through connecting Encodian to the OpenAI Agents SDK using the Composio tool router. By the end, you'll have a working Encodian agent that can resize all images in project folder, extract author and page count from pdf, add custom header to every pdf file through natural language commands.
This guide will help you understand how to give your OpenAI Agents SDK agent real control over a Encodian account through Composio's Encodian MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Encodian with

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

The Encodian MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Encodian account. It provides structured and secure access to your Encodian document automation suite, so your agent can perform actions like managing files, processing PDFs, encoding or decoding content, and automating workflow tasks on your behalf.
- File management and property retrieval: Quickly get detailed information about files, move documents between containers, and keep your Microsoft 365 storage organized automatically.
- Document processing and automation: Direct your agent to add headers and footers to PDFs, extract PDF metadata, or resize images for seamless document formatting and compliance tasks.
- Base64 content conversion: Effortlessly encode text or files to Base64, or decode Base64 strings back to usable files for secure data exchange and workflow integration.
- Archive extraction and manipulation: Unzip files and retrieve their contents, making it easy to automate bulk document handling or trigger downstream processing steps.
- Data integrity and comparison tools: Use hashing and text comparison utilities to verify file integrity, detect changes, or ensure consistency across your documents and workflows.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `ENCODIAN_ADD_ATTACHMENTS_TO_PDF` | Add Attachments to PDF | Tool to add file attachments to a PDF document. Use when you need to embed files within a PDF as attachments that can be extracted later. |
| `ENCODIAN_ADD_IMAGE_WATERMARK` | Add Image Watermark to PDF | Tool to add an image watermark to a PDF document. Use when you need to overlay an image on PDF pages with configurable opacity and orientation. |
| `ENCODIAN_ADD_IMAGE_WATERMARK_ADVANCED` | Add Image Watermark to PDF (Advanced) | Tool to add an advanced image watermark to a PDF with precise control over positioning, opacity, scale, quality, and rotation. Use when you need to overlay a watermark image onto PDF pages with page-level targeting and advanced customization options. |
| `ENCODIAN_ADD_ITEMS_TO_ARRAY` | Array Add Items | Tool to add items to a JSON array at a specified position (first, last, or specific index). Use when you need to append or insert elements into an existing JSON array structure. |
| `ENCODIAN_ADD_TO_ZIP` | Create ZIP Archive | Tool to create a ZIP archive from multiple documents. Use when you need to compress and package multiple files into a single ZIP file, with optional password protection and folder structure. |
| `ENCODIAN_APPLY_AI_OCR_PDF_DOCUMENT` | Apply AI OCR to PDF | Tool to apply AI-powered OCR to a PDF document with optional preprocessing filters. Use when you need to extract text from scanned PDFs or images by recognizing and converting visual text into machine-readable format. Supports advanced preprocessing like deskew, despeckle, binarization, and automatic rotation. |
| `ENCODIAN_APPLY_OCR_PDF_DOCUMENT` | Apply OCR to PDF (Standard) | Tool to apply standard OCR to a PDF document with optional preprocessing filters. Use when you need to extract text from scanned PDFs or images by recognizing and converting visual text into machine-readable format. Supports language selection, quality vs speed trade-off, and preprocessing options. |
| `ENCODIAN_BASE64_DECODE` | Decode Base64 String | Tool to decode a Base64 string to a file. Use when you need to extract binary content (e.g., PDF, image) from Base64 data. |
| `ENCODIAN_BASE64_ENCODE` | Base64 Encode | Tool to encode a string to Base64. Use when you need to convert text into Base64 representation for use in other operations. |
| `ENCODIAN_CALCULATE_DATE` | Calculate Date | Tool to calculate a date by adding or subtracting a time interval from a given date. Use when you need to compute a future or past date based on a starting date and time offset. |
| `ENCODIAN_CHECK_ARRAY_CONTAINS_VALUE` | Check Array Contains Value | Tool to check if a value exists within a JSON array. Use when you need to verify if a specific value is present in an array, with optional case-insensitive matching and JSONPath support for nested data structures. |
| `ENCODIAN_CHECK_TEXT_CONTAINS_VALUE` | Check Text Contains Value | Tool to check if a text string contains a specific value with configurable comparison rules. Use when you need to validate whether text contains a substring with options for case sensitivity and culture-specific comparison. |
| `ENCODIAN_CLEAN_STRING` | Clean String | Tool to clean text by removing control characters, invalid filename characters, and custom character sets. Use when you need to sanitize or clean text strings for safe usage in filenames or other contexts. |
| `ENCODIAN_CLEAN_UP_IMAGE_PHOTO` | Clean Up Photo Image | Tool to clean up photo images by removing artifacts, correcting orientation, and enhancing quality. Use when you need to improve image quality through operations like auto-rotation, deskewing, despeckling, and color balancing. |
| `ENCODIAN_COMBINE_ARRAYS` | Combine Arrays | Tool to combine two JSON arrays by matching a key attribute. Use when you need to merge data from two arrays based on a common identifier. |
| `ENCODIAN_COMPARE_TEXT` | Compare Text | Tool to compare two text strings and determine if they match. Use when you have two strings and need to verify if they are equal. |
| `ENCODIAN_COMPARE_WORD_DOCUMENTS` | Compare Word Documents | Tool to compare two Microsoft Word or PDF documents and generate a document with tracked changes. Use when you need to identify differences between two document versions. The output document highlights insertions, deletions, and modifications with the specified author name. |
| `ENCODIAN_COMPRESS_IMAGE` | Compress Image | Tool to compress an image in JPG or PNG format. Use when you need to reduce the file size of an image while maintaining format compatibility. |
| `ENCODIAN_COMPRESS_PDF` | Compress PDF | Tool to compress a PDF document by optimizing images, removing unused objects, and applying various compression techniques. Use when you need to reduce PDF file size while maintaining readability and functionality. |
| `ENCODIAN_CONCATENATE_TEXT` | Concatenate Text | Tool to concatenate an array of text values with an optional delimiter. Use when you need to combine multiple strings into a single text value with optional separator. |
| `ENCODIAN_CONVERT_ARRAY_TO_JSON` | Array to JSON | Tool to convert an array to a named JSON object. Use when you need to wrap an array in a JSON object with a specific key name, optionally selecting a specific array from nested JSON using JSONPath. |
| `ENCODIAN_CONVERT_ARRAY_TO_XML` | Array to XML | Tool to convert a JSON array to XML format. Use when you need to transform JSON data into XML structure with custom root and item node names. |
| `ENCODIAN_CONVERT_FILE_TO_PDF` | Convert File to PDF | Tool to convert a file to PDF format. Use when you need to transform documents (Word, Excel, PowerPoint, text files, etc.) into PDF format with optional bookmarks, markup removal, and PDF/A compliance. |
| `ENCODIAN_CONVERT_HTML_TO_IMAGE` | Convert HTML to Image | Tool to convert HTML content to an image. Use when you need to render HTML as an image file, supporting URL, raw HTML string, or HTML file content with optional JavaScript execution and CSS styling control. |
| `ENCODIAN_CONVERT_HTML_TO_PDF_V2` | Convert HTML to PDF (V2) | Tool to convert HTML content or a URL to PDF format (V2). Use when you need to transform HTML strings, HTML files, or live web pages into PDF documents with advanced options like custom page sizes, margins, JavaScript support, and bookmarks. |
| `ENCODIAN_CONVERT_HTML_TO_WORD` | Convert HTML to Word | Tool to convert HTML content to Word (DOCX) format. Use when you need to transform HTML documents, web pages, or HTML strings into Word documents with customizable page settings, margins, and compliance levels. |
| `ENCODIAN_CONVERT_IMAGE_TO_GRAYSCALE` | Convert Image to Grayscale | Tool to convert an image to grayscale. Use when you need to remove color from an image and convert it to shades of gray. |
| `ENCODIAN_CONVERT_IMAGE_TO_PDF` | Convert Image to PDF | Tool to convert an image file to PDF format with optional OCR. Use when you need to transform image files (PNG, JPG, etc.) into PDF documents, optionally extracting text via OCR. |
| `ENCODIAN_CONVERT_JSON_TO_EXCEL` | Convert JSON to Excel | Tool to convert JSON data to Excel format. Use when you need to transform JSON arrays into Excel spreadsheets with customizable formatting options. |
| `ENCODIAN_CONVERT_JSON_TO_XML` | Convert JSON to XML | Tool to convert JSON data to XML format. Use when you need to transform JSON strings into XML documents with customizable root element names and array attributes. |
| `ENCODIAN_CONVERT_TIME_ZONE_ENC` | Convert Time Zone | Tool to convert a date and time value from one time zone to another using Encodian's time zone conversion API. Use when you need to transform timestamps between different time zones (e.g., UTC to Eastern Standard Time). |
| `ENCODIAN_CONVERT_XML_TO_JSON` | Convert XML to JSON | Tool to convert XML strings to JSON format. Use when you need to transform XML data into a JSON representation for easier parsing or processing. |
| `ENCODIAN_COUNT_ARRAY_ITEMS` | Count Array Items | Tool to count the number of items in a JSON array or object. Use when you need to determine the size of an array or evaluate specific nodes using JSONPath expressions. |
| `ENCODIAN_CREATE_QR_CODE` | Create QR Code | Tool to generate a QR code barcode image with customizable size, colors, border, and encoding options. Use when you need to create QR codes for URLs, contact information, or any text data. |
| `ENCODIAN_FORMAT_TEXT_CASE` | Format Text Case | Tool to format text with various case transformations (uppercase, lowercase, title case, etc.). Use when you need to standardize or change the capitalization of text strings. |
| `ENCODIAN_GENERAL_HASH` | Hash Data | Tool to compute a cryptographic hash (MD5, SHA256, etc.) of text or file data. Use when you need to verify integrity or generate digests. |
| `ENCODIAN_GENERAL_UNZIP_FILE` | Unzip File | Extracts all files from a ZIP archive and returns their base64-encoded contents. Supports password-protected archives and optionally extracts files from nested folders. Use this when you need to access the contents of compressed archive files. |
| `ENCODIAN_GET_CONVERT_EXCEL_SCHEMA` | Get Convert Excel Schema | Tool to retrieve the dynamic schema for Excel conversion operations. Returns the schema definition including required fields and available properties based on the specified output format. Use when you need to understand what parameters are available for converting Excel files to different formats. |
| `ENCODIAN_GET_CONVERT_WORD_SCHEMA` | Get Convert Word Schema | Tool to retrieve the dynamic JSON schema for Word document conversion operations. Use when you need to discover available parameters and their constraints for converting Word documents to various formats. |
| `ENCODIAN_GET_DYNAMIC_SCHEMA_CONVERT_CAD` | Get Convert CAD Schema | Tool to retrieve the dynamic schema for CAD file conversion operations. Returns the schema definition that specifies available parameters for converting CAD files to various output formats. Use when you need to understand the conversion parameters available for a specific output format. |
| `ENCODIAN_GET_DYNAMIC_SCHEMA_CONVERT_IMAGE_TO_PDF` | Get Convert Image to PDF Schema | Tool to retrieve the dynamic schema for Convert - Image to PDF operations. Use when you need to understand the available configuration options for image-to-PDF conversion based on OCR type. |
| `ENCODIAN_GET_DYNAMIC_SCHEMA_CONVERT_POWER_POINT` | Get Convert PowerPoint Schema | Tool to retrieve the dynamic schema for PowerPoint conversion operations. Use when you need to understand the available parameters and requirements for converting PowerPoint files to different formats. |
| `ENCODIAN_GET_DYNAMIC_SCHEMA_CONVERT_VISIO` | Get Convert Visio Schema | Tool to retrieve the dynamic schema for Visio file conversion. Returns format-specific field definitions based on the selected output format (PDF, PNG, SVG, etc.). Use when you need to understand what parameters are available for converting Visio files to a specific format. |
| `ENCODIAN_GET_DYNAMIC_SCHEMA_CREATE_BARCODE` | Get Create Barcode Schema | Tool to retrieve the dynamic schema for creating a barcode. Use this to understand the required parameters and configuration options for a specific barcode type before creating it. |
| `ENCODIAN_GET_DYNAMIC_SCHEMA_CROP_IMAGE` | Get Crop Image Schema | Tool to retrieve the dynamic schema for the Crop Image action. Returns an OpenAPI-style schema definition that varies based on the specified crop type (Border or Rectangle). |
| `ENCODIAN_GET_DYNAMIC_SCHEMA_SEND_HTTP_REQUEST` | Get Dynamic Schema for HTTP Request | Tool to retrieve the dynamic schema for the HTTP Request utility based on authentication type. Use when you need to understand what parameters are required for sending HTTP requests with specific authentication methods. |
| `ENCODIAN_GET_DYNAMIC_SCHEMA_WORD_INSERT_TEXT` | Get Word Insert Text Schema | Tool to retrieve the dynamic schema for Word Insert Text operations. Use when you need to understand the available parameters and their types for inserting text into Word documents. |
| `ENCODIAN_GET_FILE_PROPERTIES` | Get File Properties | Tool to retrieve properties of a file. Attempts multiple Encodian Filer endpoints and fallbacks. |
| `ENCODIAN_GET_OPERATION_STATUS_AI_RUN_PROMPT_TEXT` | Get Operation Status for AIRunPromptText | Tool to get the operation status of an AIRunPromptText operation. Use when you need to check the completion status of a previously initiated AI prompt operation. |
| `ENCODIAN_GET_OPERATION_STATUS_ENCODIAN_SEND_TO_FILER` | Get Operation Status for Encodian Send to Filer | Tool to get the operation status for an Encodian Send to Filer operation. Use when you need to check the completion status and retrieve results from a previously submitted Send to Filer operation. |
| `ENCODIAN_GET_OPERATION_STATUS_EXTRACT_IMAGE` | Get Operation Status Extract Image | Tool to retrieve the operation status of a PDF ExtractImage operation. Use when you need to check if an image extraction operation has completed, is queued, or has failed. |
| `ENCODIAN_GET_OPERATION_STATUS_EXTRACT_TEXT_REGION` | Get Operation Status for ExtractTextRegion | Tool to retrieve the operation status of an ExtractTextRegion operation. Use when you need to check if a text region extraction operation has completed and retrieve the extracted text results. |
| `ENCODIAN_GET_OPERATION_STATUS_FILE_ONLY` | Get Operation Status File Only | Tool to retrieve operation status for file-only operations. Use when you need to check if an asynchronous file operation has completed. |
| `ENCODIAN_GET_OPERATION_STATUS_IMAGE_EXTRACT_TEXT` | Get Operation Status for Image Extract Text | Tool to get the operation status of an ImageExtractText operation. Use when you need to check if an image text extraction operation has completed and retrieve the extracted text. |
| `ENCODIAN_GET_OPERATION_STATUS_MULTIPLE_FILES` | Get Operation Status for Multiple Files | Tool to retrieve the operation status of a Word MultipleFiles operation. Use when you need to check the status and retrieve results of a previously submitted batch operation on multiple Word documents. |
| `ENCODIAN_GET_OPERATION_STATUS_PDF_SPLIT_BARCODE` | Get Operation Status - PDF Split Barcode | Tool to retrieve operation status for a PDF split barcode operation. Use when you need to check the status and results of an asynchronous PDF split operation initiated previously. |
| `ENCODIAN_GET_OPERATION_STATUS_SPLIT_DOCUMENT` | Get Operation Status for Split Document | Tool to retrieve the operation status of a PDF SplitDocument operation. Use when you need to check the progress or completion status of a previously initiated split document operation by providing its operation ID. |
| `ENCODIAN_GET_SIGN_PDF_SCHEMA` | Get Sign PDF Schema | Tool to retrieve the dynamic schema for PDF signing operations. Returns the schema definition including required fields and available properties based on the specified certificate type. Use when you need to understand what parameters are available for signing PDF documents. |
| `ENCODIAN_GET_SUBSCRIPTION_STATUS` | Get Subscription Status | Tool to retrieve Encodian subscription status for Flowr and Vertr. Use when you need to check remaining credits, billing interval, subscription level, or expiry date. |
| `ENCODIAN_IMAGE_RESIZE` | Resize Image | Tool to resize an image by percentage or dimensions. Use when you need to scale or reshape an image with optional aspect-ratio enforcement. |
| `ENCODIAN_MOVE_FILE` | Move File | Tool to move a file between containers. Use when you need to relocate a blob within your storage without manually copying then deleting. |
| `ENCODIAN_PDF_ADD_HEADER_FOOTER` | Add PDF Header Footer | Tool to add HTML header and footer to a PDF. Use when you need to embed consistent headers or footers across pages with margin and range options. |
| `ENCODIAN_PDF_GET_METADATA` | Get PDF Metadata | Extract comprehensive metadata and properties from PDF documents. Returns page count, dimensions, author/creator/producer information, creation/modification dates, PDF format version, compliance flags (PDF/A, PDF/UA), encryption status, text layer presence, and custom properties. Useful for document analysis, validation, and cataloging workflows. |
| `ENCODIAN_PDF_WATERMARK` | Watermark PDF | Tool to apply a text watermark to a PDF. Use when you need to annotate PDF pages with custom labels or marks; supports page selection, positioning, opacity, and rotation. |
| `ENCODIAN_READ_QR_CODE_FROM_DOCUMENT` | Read QR Code from Document | Tool to read QR codes from PDF or DOCX documents. Returns an array of detected QR code values. Supports configuration of detection confidence, page range, and control character handling. |
| `ENCODIAN_REPLACE_TEXT_WITH_IMAGE` | Word - Replace Text With Image | Tool to replace text with an image in a Word document. Use when you need to substitute text placeholders with images; supports case-sensitive matching, whole-word matching, and replacing all occurrences. |
| `ENCODIAN_VALIDATE_EMAIL_ADDRESS` | Validate Email Address | Validates an email address string against a custom regex pattern using Encodian's validation API. Use this when you need to check if an email address matches a specific format or pattern. The regex parameter allows you to define custom validation rules beyond standard email format. Returns a boolean result indicating whether the email matches the pattern. |
| `ENCODIAN_VALIDATE_URL_AVAILABILITY` | Validate URL Availability | Tool to validate the availability of a specified URL. Use when needing to confirm if a web address is reachable before processing. |
| `ENCODIAN_WRITE_RANGE` | Write Range to Excel | Tool to write values to a cell range in an Excel worksheet. Use when you need to programmatically update worksheet data by specifying a range and a 2D array of values. |

## Supported Triggers

None listed.

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

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

mcp_url = session.mcp.url
```

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

- [Claude Agent SDK](https://composio.dev/toolkits/encodian/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/encodian/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/encodian/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/encodian/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/encodian/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/encodian/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/encodian/framework/cli)
- [Google ADK](https://composio.dev/toolkits/encodian/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/encodian/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/encodian/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/encodian/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/encodian/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/encodian/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 Encodian MCP?

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

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

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

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