# How to integrate Encodian MCP with Mastra AI

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

## Introduction

This guide walks you through connecting Encodian to Mastra 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 Mastra 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)
- [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:
- Set up your environment so Mastra, OpenAI, and Composio work together
- Create a Tool Router session in Composio that exposes Encodian tools
- Connect Mastra's MCP client to the Composio generated MCP URL
- Fetch Encodian tool definitions and attach them as a toolset
- Build a Mastra agent that can reason, call tools, and return structured results
- Run an interactive CLI where you can chat with your Encodian agent

## What is Mastra AI?

Mastra AI is a TypeScript framework for building AI agents with tool support. It provides a clean API for creating agents that can use external services through MCP.
Key features include:
- MCP Client: Built-in support for Model Context Protocol servers
- Toolsets: Organize tools into logical groups
- Step Callbacks: Monitor and debug agent execution
- OpenAI Integration: Works with OpenAI models via @ai-sdk/openai

## 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:
- Node.js 18 or higher
- A Composio account with an active API key
- An OpenAI API key
- Basic familiarity with 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 need credits or a connected billing setup to use the models.
- Store the key somewhere 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.
- This key lets your Mastra agent talk to Composio and reach Encodian through MCP.

### 2. Install dependencies

Install the required packages.
What's happening:
- @composio/core is the Composio SDK for creating MCP sessions
- @mastra/core provides the Agent class
- @mastra/mcp is Mastra's MCP client
- @ai-sdk/openai is the model wrapper for OpenAI
- dotenv loads environment variables from .env
```bash
npm install @composio/core @mastra/core @mastra/mcp @ai-sdk/openai dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates your requests to Composio
- COMPOSIO_USER_ID tells Composio which user this session belongs to
- OPENAI_API_KEY lets the Mastra agent call OpenAI models
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here
```

### 4. Import libraries and validate environment

What's happening:
- dotenv/config auto loads your .env so process.env.* is available
- openai gives you a Mastra compatible model wrapper
- Agent is the Mastra agent that will call tools and produce answers
- MCPClient connects Mastra to your Composio MCP server
- Composio is used to create a Tool Router session
```typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey as string,
});
```

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

What's happening:
- create spins up a short-lived MCP HTTP endpoint for this user
- The toolkits array contains "encodian" for Encodian access
- session.mcp.url is the MCP URL that Mastra's MCPClient will connect to
```typescript
async function main() {
  const session = await composio.create(
    composioUserID as string,
    {
      toolkits: ["encodian"],
    },
  );

  const composioMCPUrl = session.mcp.url;
  console.log("Encodian MCP URL:", composioMCPUrl);
```

### 6. Configure Mastra MCP client and fetch tools

What's happening:
- MCPClient takes an id for this client and a list of MCP servers
- The headers property includes the x-api-key for authentication
- getTools fetches the tool definitions exposed by the Encodian toolkit
```typescript
const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      nasdaq: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

console.log("Fetching MCP tools from Composio...");
const composioTools = await mcpClient.getTools();
console.log("Number of tools:", Object.keys(composioTools).length);
```

### 7. Create the Mastra agent

What's happening:
- Agent is the core Mastra agent
- name is just an identifier for logging and debugging
- instructions guide the agent to use tools instead of only answering in natural language
- model uses openai("gpt-5") to configure the underlying LLM
```typescript
const agent = new Agent({
    name: "encodian-mastra-agent",
    instructions: "You are an AI agent with Encodian tools via Composio.",
    model: "openai/gpt-5",
  });
```

### 8. Set up interactive chat interface

What's happening:
- messages keeps the full conversation history in Mastra's expected format
- agent.generate runs the agent with conversation history and Encodian toolsets
- maxSteps limits how many tool calls the agent can take in a single run
- onStepFinish is a hook that prints intermediate steps for debugging
```typescript
let messages: AiMessageType[] = [];

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

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "> ",
});

rl.prompt();

rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

  if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
    console.log("\nGoodbye!");
    rl.close();
    process.exit(0);
  }

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

  messages.push({
    id: crypto.randomUUID(),
    role: "user",
    content: trimmedInput,
  });

  console.log("\nAgent is thinking...\n");

  try {
    const response = await agent.generate(messages, {
      toolsets: {
        encodian: composioTools,
      },
      maxSteps: 8,
    });

    const { text } = response;

    if (text && text.trim().length > 0) {
      console.log(`Agent: ${text}\n`);
        messages.push({
          id: crypto.randomUUID(),
          role: "assistant",
          content: text,
        });
      }
    } catch (error) {
      console.error("\nError:", error);
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    console.log("\nSession ended.");
    await mcpClient.disconnect();
    process.exit(0);
  });
}

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

## Complete Code

```typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({ apiKey: composioAPIKey as string });

async function main() {
  const session = await composio.create(composioUserID as string, {
    toolkits: ["encodian"],
  });

  const composioMCPUrl = session.mcp.url;

  const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      encodian: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

  const composioTools = await mcpClient.getTools();

  const agent = new Agent({
    name: "encodian-mastra-agent",
    instructions: "You are an AI agent with Encodian tools via Composio.",
    model: "openai/gpt-5",
  });

  let messages: AiMessageType[] = [];

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: "> ",
  });

  rl.prompt();

  rl.on("line", async (input: string) => {
    const trimmed = input.trim();
    if (["exit", "quit"].includes(trimmed.toLowerCase())) {
      rl.close();
      return;
    }

    messages.push({ id: crypto.randomUUID(), role: "user", content: trimmed });

    const { text } = await agent.generate(messages, {
      toolsets: { encodian: composioTools },
      maxSteps: 8,
    });

    if (text) {
      console.log(`Agent: ${text}\n`);
      messages.push({ id: crypto.randomUUID(), role: "assistant", content: text });
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main();
```

## Conclusion

You've built a Mastra AI agent that can interact with Encodian through Composio's Tool Router.
You can extend this further by:
- Adding other toolkits like Gmail, Slack, or GitHub
- Building a web-based chat interface around this agent
- Using multiple MCP endpoints to enable cross-app workflows

## 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)
- [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 Mastra AI?

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