# How to integrate Encodian MCP with Pydantic AI

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

## Introduction

This guide walks you through connecting Encodian to Pydantic AI 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 Pydantic AI 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

- [OpenAI Agents SDK](https://composio.dev/toolkits/encodian/framework/open-ai-agents-sdk)
- [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:
- How to set up your Composio API key and User ID
- How to create a Composio Tool Router session for Encodian
- How to attach an MCP Server to a Pydantic AI agent
- How to stream responses and maintain chat history
- How to build a simple REPL-style chat interface to test your Encodian workflows

## What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.
Key features include:
- Type Safety: Built on Pydantic for automatic data validation
- MCP Support: Native support for Model Context Protocol servers
- Streaming: Built-in support for streaming responses
- Async First: Designed for async/await patterns

## 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:
- Python 3.9 or higher
- A Composio account with an active API key
- Basic familiarity with Python and async programming

### 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).
- Navigate to your API settings and generate a new API key.
- Store this key securely as you'll need it for authentication.

### 2. Install dependencies

Install the required libraries.
What's happening:
- composio connects your agent to external SaaS tools like Encodian
- pydantic-ai lets you create structured AI agents with tool support
- python-dotenv loads your environment variables securely from a .env file
```bash
pip install composio pydantic-ai python-dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates your agent to Composio's API
- USER_ID associates your session with your account for secure tool access
- OPENAI_API_KEY to access OpenAI LLMs
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key
```

### 4. Import dependencies

What's happening:
- We load environment variables and import required modules
- Composio manages connections to Encodian
- MCPServerStreamableHTTP connects to the Encodian MCP server endpoint
- Agent from Pydantic AI lets you define and run the AI assistant
```python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
```

### 5. Create a Tool Router Session

What's happening:
- We're creating a Tool Router session that gives your agent access to Encodian tools
- The create method takes the user ID and specifies which toolkits should be available
- The returned session.mcp.url is the MCP server URL that your agent will use
```python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Encodian
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["encodian"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
```

### 6. Initialize the Pydantic AI Agent

What's happening:
- The MCP client connects to the Encodian endpoint
- The agent uses GPT-5 to interpret user commands and perform Encodian operations
- The instructions field defines the agent's role and behavior
```python
# Attach the MCP server to a Pydantic AI Agent
encodian_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[encodian_mcp],
    instructions=(
        "You are a Encodian assistant. Use Encodian tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
```

### 7. Build the chat interface

What's happening:
- The agent reads input from the terminal and streams its response
- Encodian API calls happen automatically under the hood
- The model keeps conversation history to maintain context across turns
```python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with Encodian.\n")

while True:
    user_input = input("You: ").strip()
    if user_input.lower() in {"exit", "quit", "bye"}:
        print("\nGoodbye!")
        break
    if not user_input:
        continue

    print("\nAgent is thinking...\n", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
```

### 8. Run the application

What's happening:
- The asyncio loop launches the agent and keeps it running until you exit
```python
if __name__ == "__main__":
    asyncio.run(main())
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Encodian
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["encodian"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    encodian_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[encodian_mcp],
        instructions=(
            "You are a Encodian assistant. Use Encodian tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with Encodian.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "bye"}:
            print("\nGoodbye!")
            break
        if not user_input:
            continue

        print("\nAgent is thinking...\n", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

if __name__ == "__main__":
    asyncio.run(main())
```

## Conclusion

You've built a Pydantic AI agent that can interact with Encodian through Composio's Tool Router. With this setup, your agent can perform real Encodian actions through natural language.
You can extend this further by:
- Adding other toolkits like Gmail, HubSpot, or Salesforce
- Building a web-based chat interface around this agent
- Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + Encodian for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.

## How to build Encodian MCP Agent with another framework

- [OpenAI Agents SDK](https://composio.dev/toolkits/encodian/framework/open-ai-agents-sdk)
- [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 Pydantic AI?

Yes, you can. Pydantic AI 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)
