# How to integrate Encodian MCP with CrewAI

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

## Introduction

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

## TL;DR

Here's what you'll learn:
- Get a Composio API key and configure your Encodian connection
- Set up CrewAI with an MCP enabled agent
- Create a Tool Router session or standalone MCP server for Encodian
- Build a conversational loop where your agent can execute Encodian operations

## What is CrewAI?

CrewAI is a powerful framework for building multi-agent AI systems. It provides primitives for defining agents with specific roles, creating tasks, and orchestrating workflows through crews.
Key features include:
- Agent Roles: Define specialized agents with specific goals and backstories
- Task Management: Create tasks with clear descriptions and expected outputs
- Crew Orchestration: Combine agents and tasks into collaborative workflows
- MCP Integration: Connect to external tools through Model Context Protocol

## 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 and API key
- A Encodian connection authorized in Composio
- An OpenAI API key for the CrewAI LLM
- Basic familiarity with Python

### 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

**What's happening:**
- composio connects your agent to Encodian via MCP
- crewai provides Agent, Task, Crew, and LLM primitives
- crewai-tools[mcp] includes MCP helpers
- python-dotenv loads environment variables from .env
```bash
pip install composio crewai crewai-tools[mcp] python-dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates with Composio
- USER_ID scopes the session to your account
- OPENAI_API_KEY lets CrewAI use your chosen OpenAI model
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here
```

### 4. Import dependencies

**What's happening:**
- CrewAI classes define agents and tasks, and run the workflow
- MCPServerHTTP connects the agent to an MCP endpoint
- Composio will give you a short lived Encodian MCP URL
```python
import os
from composio import Composio
from crewai import Agent, Task, Crew
from crewai_tools import MCPServerAdapter
import dotenv

dotenv.load_dotenv()

COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set")
```

### 5. Create a Composio Tool Router session for Encodian

**What's happening:**
- You create a Encodian only session through Composio
- Composio returns an MCP HTTP URL that exposes Encodian tools
```python
composio_client = Composio(api_key=COMPOSIO_API_KEY)
session = composio_client.create(user_id=COMPOSIO_USER_ID, toolkits=["encodian"])

url = session.mcp.url
```

### 6. Initialize the MCP Server

**What's Happening:**
- Server Configuration: The code sets up connection parameters including the MCP server URL, streamable HTTP transport, and Composio API key authentication.
- MCP Adapter Bridge: MCPServerAdapter acts as a context manager that converts Composio MCP tools into a CrewAI-compatible format.
- Agent Setup: Creates a CrewAI Agent with a defined role (Search Assistant), goal (help with internet searches), and access to the MCP tools.
- Configuration Options: The agent includes settings like verbose=False for clean output and max_iter=10 to prevent infinite loops.
- Dynamic Tool Usage: Once created, the agent automatically accesses all Composio Search tools and decides when to use them based on user queries.
```python
server_params = {
    "url": url,
    "transport": "streamable-http",
    "headers": {"x-api-key": COMPOSIO_API_KEY},
}

with MCPServerAdapter(server_params) as tools:
    agent = Agent(
        role="Search Assistant",
        goal="Help users search the internet effectively",
        backstory="You are a helpful assistant with access to search tools.",
        tools=tools,
        verbose=False,
        max_iter=10,
    )
```

### 7. Create a CLI Chatloop and define the Crew

**What's Happening:**
- Interactive CLI Setup: The code creates an infinite loop that continuously prompts for user input and maintains the entire conversation history in a string variable.
- Input Validation: Empty inputs are ignored to prevent processing blank messages and keep the conversation clean.
- Context Building: Each user message is appended to the conversation context, which preserves the full dialogue history for better agent responses.
- Dynamic Task Creation: For every user input, a new Task is created that includes both the full conversation history and the current request as context.
- Crew Execution: A Crew is instantiated with the agent and task, then kicked off to process the request and generate a response.
- Response Management: The agent's response is converted to a string, added to the conversation context, and displayed to the user, maintaining conversational continuity.
```python
print("Chat started! Type 'exit' or 'quit' to end.\n")

conversation_context = ""

while True:
    user_input = input("You: ").strip()

    if user_input.lower() in ["exit", "quit", "bye"]:
        print("\nGoodbye!")
        break

    if not user_input:
        continue

    conversation_context += f"\nUser: {user_input}\n"
    print("\nAgent is thinking...\n")

    task = Task(
        description=(
            f"Conversation history:\n{conversation_context}\n\n"
            f"Current request: {user_input}"
        ),
        expected_output="A helpful response addressing the user's request",
        agent=agent,
    )

    crew = Crew(agents=[agent], tasks=[task], verbose=False)
    result = crew.kickoff()
    response = str(result)

    conversation_context += f"Agent: {response}\n"
    print(f"Agent: {response}\n")
```

## Complete Code

```python
from crewai import Agent, Task, Crew, LLM
from crewai_tools import MCPServerAdapter
from composio import Composio
from dotenv import load_dotenv
import os

load_dotenv()

GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not GOOGLE_API_KEY:
    raise ValueError("GOOGLE_API_KEY is not set in the environment.")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set in the environment.")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set in the environment.")

# Initialize Composio and create a session
composio = Composio(api_key=COMPOSIO_API_KEY)
session = composio.create(
    user_id=COMPOSIO_USER_ID,
    toolkits=["encodian"],
)
url = session.mcp.url

# Configure LLM
llm = LLM(
    model="gpt-5",
    api_key=os.getenv("OPENAI_API_KEY"),
)

server_params = {
    "url": url,
    "transport": "streamable-http",
    "headers": {"x-api-key": COMPOSIO_API_KEY},
}

with MCPServerAdapter(server_params) as tools:
    agent = Agent(
        role="Search Assistant",
        goal="Help users with internet searches",
        backstory="You are an expert assistant with access to Composio Search tools.",
        tools=tools,
        llm=llm,
        verbose=False,
        max_iter=10,
    )

    print("Chat started! Type 'exit' or 'quit' to end.\n")

    conversation_context = ""

    while True:
        user_input = input("You: ").strip()

        if user_input.lower() in ["exit", "quit", "bye"]:
            print("\nGoodbye!")
            break

        if not user_input:
            continue

        conversation_context += f"\nUser: {user_input}\n"
        print("\nAgent is thinking...\n")

        task = Task(
            description=(
                f"Conversation history:\n{conversation_context}\n\n"
                f"Current request: {user_input}"
            ),
            expected_output="A helpful response addressing the user's request",
            agent=agent,
        )

        crew = Crew(agents=[agent], tasks=[task], verbose=False)
        result = crew.kickoff()
        response = str(result)

        conversation_context += f"Agent: {response}\n"
        print(f"Agent: {response}\n")
```

## Conclusion

You now have a CrewAI agent connected to Encodian through Composio's Tool Router. The agent can perform Encodian operations through natural language commands.
Next steps:
- Add role-specific instructions to customize agent behavior
- Plug in more toolkits for multi-app workflows
- Chain tasks for complex multi-step operations

## 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)

## 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 CrewAI?

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