# How to integrate Agenty MCP with OpenAI Agents SDK

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

## Introduction

This guide walks you through connecting Agenty to the OpenAI Agents SDK using the Composio tool router. By the end, you'll have a working Agenty agent that can clone your top-performing agent for news sites, list all your running web scraping agents, create a new agent to monitor product prices through natural language commands.
This guide will help you understand how to give your OpenAI Agents SDK agent real control over a Agenty account through Composio's Agenty MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Agenty with

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

## TL;DR

Here's what you'll learn:
- Get and set up your OpenAI and Composio API keys
- Install the necessary dependencies
- Initialize Composio and create a Tool Router session for Agenty
- Configure an AI agent that can use Agenty as a tool
- Run a live chat session where you can ask the agent to perform Agenty operations

## What is OpenAI Agents SDK?

The OpenAI Agents SDK is a lightweight framework for building AI agents that can use tools and maintain conversation state. It provides a simple interface for creating agents with hosted MCP tool support.
Key features include:
- Hosted MCP Tools: Connect to external services through hosted MCP endpoints
- SQLite Sessions: Persist conversation history across interactions
- Simple API: Clean interface with Agent, Runner, and tool configuration
- Streaming Support: Real-time response streaming for interactive applications

## What is the Agenty MCP server, and what's possible with it?

The Agenty MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Agenty account. It provides structured and secure access to your web scraping agents and automation tools, so your agent can perform actions like creating, managing, cloning, and monitoring scraping agents, as well as handling API keys and templates—all on your behalf.
- Agent creation and configuration: Instantly create new scraping or automation agents, set up their configurations, and optionally auto-start them—all without manual coding.
- Clone and update agents: Duplicate existing agents to streamline workflows or update agent settings to refine your data extraction processes.
- Fetch and manage agents: List all active agents in your account, retrieve details for any agent, and organize your entire automation fleet from a single place.
- Template selection and management: Browse public agent templates or sample agents, making it easy to kickstart new projects or standardize scraping tasks.
- API key management: Create, download, or delete API keys for secure programmatic access and efficient credential management, keeping your automation environment safe and organized.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `AGENTY_ADD_LIST_ROWS` | Add List Rows | Tool to add new rows to a list. Use when you need to insert one or more data rows into an existing list. Column names in row objects must match the list's schema. |
| `AGENTY_AGENTS_CONTROLLER_CREATE_AGENT` | Create Agent | Creates a new Agenty agent for web scraping, change detection, crawling, map monitoring, or brand monitoring. Use this tool to set up automated data extraction agents. Requires: - name: A descriptive name for the agent - type: One of 'scraping', 'changedetection', 'crawling', 'mapmonitoring', 'brandmonitoring' - config: Configuration object with url, browser, and collections defining what data to extract The config.collections array contains field definitions with CSS selectors or other extraction methods. Each field specifies what data to extract and how (TEXT content, ATTR for attributes, etc.). Optional: Set start=true to immediately run the agent after creation, or configure a scheduler for recurring runs. Returns the created agent with its unique agent_id for future reference. |
| `AGENTY_AGENTS_CONTROLLER_GET_TEMPLATES` | Get Agent Templates | Tool to fetch all public agent templates and sample agents. Use when listing available templates for users to select. |
| `AGENTY_AGENTS_DELETE_BY_ID` | Delete Agent by ID | Tool to delete a single agent by its ID. Use when you need to permanently remove an agent after confirming it exists. |
| `AGENTY_AGENTS_GET_ALL` | Fetch all agents | Tool to fetch all active agents under an account. Use after authenticating when you need to list agents with pagination and sorting. |
| `AGENTY_AGENTS_GET_BY_ID` | Get Agent by ID | Retrieves complete details of a specific agent including its configuration, input settings, scheduler, and metadata. Use this tool when you need to: - View full agent configuration and settings - Check agent type and current version - Access scheduler and script configurations - Verify agent status before executing jobs - Retrieve agent metadata for updates or cloning |
| `AGENTY_AGENTS_UPDATE_BY_ID` | Update Agent by ID | Updates an existing agent's configuration, settings, and metadata. Use this tool to modify an agent's properties such as name, type, config, tags, scheduler, scripts, or visibility settings. The API only returns the fields that were updated in the response, not the complete agent object. To get the full updated agent details, use the 'Get Agent by ID' action after updating. Example uses: - "Update agent abc123 to change its name to 'Production Scraper'" - "Enable scheduling for agent xyz789 with a cron expression '0 */6 * * *'" - "Update agent def456 config to scrape a different URL" |
| `AGENTY_API_KEYS_CONTROLLER_CREATE_API_KEYS` | Create API Key | Creates a new API key for programmatic access to the Agenty API. The generated API key can be used to authenticate API requests with different permission levels (Owner, Admin, or Manager). The key is returned in the response and should be securely stored as it provides access to your Agenty account. |
| `AGENTY_API_KEYS_DELETE_BY_ID` | Delete API key by ID | Delete an API key by its unique identifier. Use this tool to permanently revoke access for a specific API key. The key_id can be obtained from the "Get all API keys" or "Create API key" actions. This action cannot be undone. |
| `AGENTY_API_KEYS_DOWNLOAD` | Download API keys | Tool to download all API keys under an account in CSV format. Use when you need a complete list of API keys for export or backup. |
| `AGENTY_API_KEYS_GET_ALL` | Get all API keys | Tool to retrieve all API keys under an account. Use after authentication when you need to list API keys with pagination and sorting. |
| `AGENTY_API_KEYS_GET_BY_ID` | Get API key by ID | Retrieves detailed information about a specific API key by its ID. Use this action when you need to: - Get the full details of an API key including its value, role, and status - Verify the existence and properties of a specific API key - Check if an API key is enabled or disabled The key_id can be obtained from the 'Get all API keys' action or when creating a new API key. |
| `AGENTY_API_KEYS_RESET_BY_ID` | Reset API key by ID | Resets (regenerates) the secret value of an existing API key. The old secret becomes invalid immediately. Important: This action only confirms the reset was successful but does NOT return the new secret. After resetting, use the 'Get API Key By ID' action to retrieve the new secret value. Use this when you need to: - Rotate API key secrets for security - Invalidate a compromised API key and generate a new secret - Update credentials as part of security maintenance |
| `AGENTY_API_KEYS_UPDATE_BY_ID` | Update API key by ID | Updates an existing API key's name and role by its unique identifier. This action allows you to modify the display name and permission level of an API key. Only the name and role fields can be updated; other properties are read-only. After updating, the action automatically fetches and returns the complete updated API key details. Use this when you need to: - Rename an API key for better identification - Change the permission level (Owner, Admin, or Manager) of an API key - Update multiple properties of an API key at once |
| `AGENTY_CAPTURE_SCREENSHOT` | Capture Screenshot | Tool to capture a full-page or visible screenshot of any webpage URL. Use when you need to capture visual representation of a webpage as an image file. The screenshot is captured using browser automation with default settings. |
| `AGENTY_CAPTURE_SCREENSHOT_WITH_OPTIONS` | Capture Screenshot with Options | Tool to capture webpage screenshots with extensive customization options including full-page capture, image format, quality settings, viewport configuration, and post-processing. Use when you need to take screenshots of web pages with specific requirements for size, format, or rendering behavior. |
| `AGENTY_CHANGE_API_KEY_STATUS_BY_ID` | Change API key status by ID | Toggles the enabled/disabled status of an API key. This endpoint switches the key between enabled and disabled states - if the key is currently enabled, it will be disabled, and vice versa. Returns a confirmation message upon successful status change. Use this after retrieving the key_id from the list or get API key endpoints. |
| `AGENTY_CONNECTIONS_GET_ALL` | Get all connections | Retrieves all connections from your Agenty account. Supports pagination via limit/offset and sorting by field name. Returns an empty list if no connections exist. |
| `AGENTY_CONVERT_URL_TO_PDF` | Convert URL to PDF | Tool to convert a webpage URL to a PDF document. Use when you need to generate a PDF file from a web page for archival, reporting, or offline viewing purposes. |
| `AGENTY_CONVERT_URL_TO_PDF_WITH_OPTIONS` | Convert URL to PDF with Options | Tool to convert a URL or raw HTML to PDF with customizable options. Use when you need to generate PDFs with specific formatting requirements like custom page sizes, margins, headers/footers, or orientation. Supports both URL-based and HTML content conversion. |
| `AGENTY_COPY_AGENT` | Copy Agent | Tool to copy an existing agent by its ID, creating a duplicate with optionally a new name. Use when you need to duplicate an agent's configuration to create a similar agent without starting from scratch. |
| `AGENTY_CREATE_WORKFLOW` | Create Workflow | Creates a new workflow in Agenty to automate actions based on agent events. Use this to set up automated responses like sending emails, triggering webhooks, or notifications when specific agent events occur (e.g., job completed, job failed). |
| `AGENTY_DASHBOARD_GET_REPORTS_USAGE` | Get dashboard reports and usage | Tool to fetch account reports like pages used by agent, date, and product. Use when analyzing usage over a date range. |
| `AGENTY_DELETE_LIST_ROW` | Delete List Row by ID | Tool to delete a specific row from a list by its unique identifier. Use when you need to permanently remove a single row from a list. |
| `AGENTY_DELETE_LIST_ROWS` | Delete List Rows by IDs | Tool to delete specific rows from a list by their IDs. Use when you need to remove one or more rows from a list by providing their unique identifiers. |
| `AGENTY_DELETE_PROJECT` | Delete Project | Tool to delete a project by its ID. Use when you need to permanently remove a project. This action cannot be undone, so ensure the project ID is correct before deletion. |
| `AGENTY_DELETE_SCHEDULE` | Delete Schedule | Tool to delete a schedule for an agent by its agent ID. Use when you need to remove scheduled automation for a specific agent. |
| `AGENTY_DELETE_WORKFLOW` | Delete Workflow by ID | Tool to delete a workflow by its ID. Use when you need to permanently remove a workflow after confirming it exists. |
| `AGENTY_DOWNLOAD_AGENT_RESULT` | Download Agent Result | Tool to download agent results by agent ID in CSV, TSV or JSON format. Use when you need to export or analyze agent execution results as a file. |
| `AGENTY_DOWNLOAD_LIST_ROWS` | Download List Rows | Tool to download list rows as CSV file. Use when you need to export or backup all rows from a specific list. |
| `AGENTY_DOWNLOAD_USERS` | Download users | Tool to download users list in CSV format. Use when you need to export or backup the complete list of team members and users. |
| `AGENTY_DOWNLOAD_WORKFLOWS` | Download workflows | Tool to download all workflows in CSV format. Use when you need to export or backup all workflows from your account. |
| `AGENTY_EXTRACT_BROWSER_STRUCTURED_DATA` | Extract Structured Data | Tool to auto-extract structured data from a webpage including schema.org, RDFa, Microdata, and JSON-LD formats. Use when you need to automatically extract semantic markup from web pages without writing custom scraping rules. The API returns organized structured data in four categories: metatags, microdata, rdfa, and jsonld. |
| `AGENTY_EXTRACT_STRUCTURED_DATA` | Extract Structured Data from URL | Tool to auto-extract structured data from a webpage URL. Use when you need to extract schema.org, RDFa, Microdata, or JSON-LD structured data from web pages. |
| `AGENTY_GET_AGENT_RESULT` | Get Agent Result | Tool to get the most recent result data for an agent. Use when you need to retrieve and view the scraped/collected data from an agent's latest execution. Returns result data with pagination support. |
| `AGENTY_GET_ALL_TEAM_MEMBERS` | Get all team members | Tool to retrieve all team members (users) under an account. Use after authentication when you need to list team members with pagination, sorting, and search filtering. |
| `AGENTY_GET_BROWSER_REDIRECTS` | Get URL Redirects | Tool to get the complete redirect chain for a URL. Use when you need to trace how a URL redirects, including both server-side (HTTP 3xx redirects) and client-side redirects (JavaScript, meta tags). Returns an ordered list of all redirect steps from the original URL to the final destination. |
| `AGENTY_GET_JOB_RESULT` | Get Job Result | Tool to get the result data from a completed job. Use when you need to retrieve and view the scraped/collected data from a finished job. Returns result data with pagination support. |
| `AGENTY_GET_LIST_BY_ID` | Get list by ID | Retrieves detailed information about a specific list by its ID. Use this action when you need to: - Get the full details of a list including its name, description, and metadata - Verify the existence of a specific list - Check when a list was created or last updated - Access additional data associated with a list The list_id can be obtained from the 'Get all lists' action or when creating a new list. |
| `AGENTY_GET_LIST_ROW_BY_ID` | Get List Row by ID | Tool to fetch a specific row by its ID from a list. Use when you need to retrieve a single data entry from a list using its unique identifier. |
| `AGENTY_GET_PAGE_CONTENT` | Get Page Content | Tool to fetch the complete HTML content of any webpage URL. Use this when you need to retrieve the full HTML source code of a page, including content rendered after JavaScript execution. The API navigates to the URL using proxies and captures the page's source content. |
| `AGENTY_GET_PAGE_CONTENT_WITH_OPTIONS` | Get Page Content with Options | Tool to fetch HTML content of a webpage with custom options including ad blocking. Use this when you need to retrieve the full HTML source of a webpage, particularly for web scraping or content analysis tasks. The tool supports ad blocking to speed up page loads and reduce unnecessary content. |
| `AGENTY_GET_PROJECT_BY_ID` | Get Project by ID | Retrieves complete details of a specific project by its ID, including name, description, creator information, and timestamps. Use this to get project metadata before adding agents, checking project existence, or verifying project details for updates. |
| `AGENTY_GET_REDIRECTS_WITH_OPTIONS` | Get Redirects with Options | Tool to get the complete redirect chain of a URL with custom navigation options. Use when you need to trace URL redirects including both server-side (3xx) and client-side redirects (JavaScript, meta tags). Supports custom timeout and navigation wait conditions to ensure all redirects are captured. |
| `AGENTY_GET_SCHEDULE` | Get Agent Schedule | Tool to retrieve the schedule configuration for a specific agent. Use when you need to check the current scheduling settings for an agent. |
| `AGENTY_GET_USER_BY_ID` | Get User by ID | Tool to retrieve detailed information about a user by their ID. Use this to fetch user profile data including email, role, status, and activity timestamps. |
| `AGENTY_GET_WORKFLOW_BY_ID` | Get Workflow by ID | Retrieves complete details of a specific workflow by its ID. Use this to view workflow configuration including agents, triggers, and actions before updating or deleting. |
| `AGENTY_INPUTS_GET_BY_AGENT_ID` | Get agent input by ID | Retrieves the input configuration for a specific agent by its ID. Returns the input source type (URL, manual list, saved list reference, or another agent's output) and associated configuration details. Use this to inspect an agent's current input setup before modifying it or starting a job, or to verify what data sources an agent will process. |
| `AGENTY_INPUTS_UPDATE_BY_AGENT_ID` | Update Input by Agent ID | Updates the input configuration for a specific agent in Agenty. This tool modifies where an agent gets its input data from. You can configure the agent to: - Pull from a URL feed (type='url') - Use a manually specified list of URLs (type='manual') - Reference data from an Agenty list (type='list') - Use output from another agent (type='agent') Use this after creating or identifying an agent to set up its data source before running jobs. |
| `AGENTY_JOBS_DOWNLOAD` | Download jobs | Tool to download all jobs in CSV format. Use when you need a complete list of jobs for export or analysis. |
| `AGENTY_JOBS_DOWNLOAD_FILES_BY_ID` | Download job file by ID | Tool to download output files by job ID. Use when you need to fetch a specific output file after a job completes. |
| `AGENTY_JOBS_DOWNLOAD_RESULT_BY_ID` | Download Job Result by ID | Tool to download the agent output result by job ID. Use when you need to fetch the final output of a completed job in CSV, TSV, or JSON format. |
| `AGENTY_JOBS_GET_ALL` | Fetch all jobs | Tool to fetch all jobs under an account. Use when you need to view and filter the list of jobs with pagination and sorting. |
| `AGENTY_JOBS_GET_BY_ID` | Get Job by ID | Retrieves comprehensive details about a specific job including its status, progress metrics (pages processed/succeeded/failed), timing information (created/started/completed times), resource consumption (page credits), and any error messages. Use this action to check job status, monitor execution progress, or diagnose job failures. Returns complete job metadata needed before downloading results. |
| `AGENTY_JOBS_GET_LOGS_BY_ID` | Get Job Logs by ID | Tool to fetch logs for a given job by its ID. Use when you need to review or debug job execution logs with pagination support. |
| `AGENTY_JOBS_LIST_FILES_BY_ID` | List job output files | Lists all output files generated by a specific job. Returns file names and sizes for available downloads including CSV/JSON/TSV data exports and compressed logs. Use this after a job completes to discover what output files are available before downloading them. |
| `AGENTY_JOBS_START` | Start Agent Job | Tool to start a new agent job. Use when you need to trigger execution of an existing agent. |
| `AGENTY_JOBS_STOP_BY_ID` | Stop Job by ID | Tool to stop a running job by job ID. Use when you need to halt an in-progress job before it completes. Confirm the job ID beforehand to avoid unintended stops. |
| `AGENTY_LISTS_CLEAR_ROWS` | Clear List Rows | Tool to clear all rows in a list by its ID. Use when you need to wipe out all data in a list before re-populating (e.g., "Clear all rows in list 123"). |
| `AGENTY_LISTS_CONTROLLER_CREATE_LIST` | Create List | Tool to create a new list. Use after preparing the list name and optional description. Example: "Create a list named 'Contacts' with description 'Potential leads'." |
| `AGENTY_LISTS_DELETE_BY_ID` | Delete List by ID | Tool to delete a specific list by its ID. Use when you need to permanently remove a list after confirming it exists. |
| `AGENTY_LISTS_DOWNLOAD` | Download lists | Tool to download all lists in CSV format. Use when you need a complete set of lists for export or backup. |
| `AGENTY_LISTS_GET_ALL` | Get all lists | Tool to retrieve all lists under an account. Use after authentication when you need to list lists with pagination and sorting. |
| `AGENTY_LISTS_GET_ROWS_BY_ID` | Fetch List Rows by ID | Tool to fetch all rows in a specified list. Use when you need to retrieve all data entries from a list with optional pagination and sorting. Example: "Fetch rows from list '61db...' with limit=50". |
| `AGENTY_LISTS_UPDATE_BY_ID` | Update List by ID | Tool to update a list's name and optionally description by list ID. The name field is always required. Use when you need to modify list metadata after confirming its ID. Example: "Update list 123 with name 'My Updated List' and description 'New description'". |
| `AGENTY_LISTS_UPLOAD_CSV` | Upload CSV file to List | Tool to upload a CSV file to an Agenty list for bulk import of data rows. Use this action when you need to: - Import multiple rows of data into an existing list from a CSV file - Bulk update list data - Add structured tabular data to a list Prerequisites: The target list must already exist. Use the 'Create List' action first if needed. |
| `AGENTY_PATCH_WORKFLOW` | Patch Workflow | Tool to partially update a workflow by ID. Use when you need to update specific fields of a workflow without replacing the entire workflow object. This action performs a PATCH operation, allowing you to update only the fields you specify (e.g., just the name) without affecting other workflow properties. Currently supports updating the workflow name. |
| `AGENTY_PROJECTS_ADD_AGENTS` | Add Agents to Project | Add one or more agents to an Agenty project to organize and group related agents together. This action associates agents with a project, allowing better organization and management of your automation workflows. The response includes the complete updated project information with all associated agents. Prerequisites: - Project must exist (use projects_get_all to find valid project IDs) - Agent(s) must exist (use agents_get_all to find valid agent IDs) Example usage: "Add agents ['tx8lubfbun', 'o3xuc2n8es'] to project 7" |
| `AGENTY_PROJECTS_CONTROLLER_CREATE_PROJECT` | Create Project | Creates a new project in Agenty. Use this to initialize a project with a name and optional description. |
| `AGENTY_PROJECTS_GET_ALL` | Get all projects | Retrieve all projects in the authenticated user's account. Returns a paginated list of projects with metadata (total count, pagination info). Use this to discover available projects, check project existence, or get project IDs for other operations. Supports sorting by fields like 'name' or 'created_at'. |
| `AGENTY_REMOVE_AGENT_FROM_PROJECT` | Remove Agent from Project | Remove an agent from an Agenty project. Use when you need to disassociate an agent from a project while keeping both the agent and project intact. The agent will no longer be part of the project's organization structure. |
| `AGENTY_SCRAPE_WEBPAGE_DATA` | Scrape Webpage Data | Tool to scrape data from any webpage using jQuery/CSS selectors. Use when you need to extract specific data from web pages by defining jQuery selector expressions. Each query field maps a name to a jQuery expression (e.g., "$('h1').text()" extracts the h1 text). The browser will load the page, execute JavaScript, and run your jQuery queries to extract the data. |
| `AGENTY_TOGGLE_SCHEDULE` | Toggle Agent Schedule | Tool to toggle schedule on/off for an agent. Use when you need to enable or disable an agent's scheduled execution without modifying other agent settings. |
| `AGENTY_TRANSFER_AGENT_OWNERSHIP` | Transfer Agent Ownership | Tool to transfer agent ownership to another Agenty account. Use when you need to move an agent to a different user's account by specifying their email address. |
| `AGENTY_UPDATE_LIST_ROW` | Update List Row | Tool to update a specific row in a list by list ID and row ID. Use when you need to modify existing data in a list row. The row_data must include the '_id' field and any column fields (col1, col2, etc.) you want to update. |
| `AGENTY_UPDATE_PROJECT` | Update Project | Update an existing project's name and description in Agenty. Use this to modify project details such as changing the project name or updating its description. |
| `AGENTY_UPDATE_SCHEDULE` | Update Agent Schedule | Updates the schedule configuration for a specific agent. Use when you need to modify how often an agent runs automatically. |
| `AGENTY_UPDATE_USER_BY_ID` | Update User by ID | Tool to update a user's information by user ID. Use this to modify user properties including email, role, status, name, and subscription settings. Email, role, and status are required fields. |
| `AGENTY_UPDATE_WORKFLOW` | Update Workflow | Tool to update an existing workflow's configuration by workflow ID. Use this to modify workflow properties including name, agent selection, trigger conditions, and actions to execute. Workflows automate responses to agent events such as job completion, errors, or change detection. Common use cases include sending notifications, triggering webhooks, or updating external systems. |

## Supported Triggers

None listed.

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

The Agenty MCP server is an implementation of the Model Context Protocol that connects your AI agent to Agenty. It provides structured and secure access so your agent can perform Agenty operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Composio API Key and OpenAI API Key
- Primary know-how of OpenAI Agents SDK
- A live Agenty project
- Some knowledge of Python or Typescript

### 1. Getting API Keys for OpenAI and Composio

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Go to Settings and copy your API key.

### 2. Install dependencies

Install the Composio SDK and the OpenAI Agents SDK.
```python
pip install composio_openai_agents openai-agents python-dotenv
```

```typescript
npm install @composio/openai-agents @openai/agents dotenv
```

### 3. Set up environment variables

Create a .env file and add your OpenAI and Composio API keys.
```bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com
```

### 4. Import dependencies

What's happening:
- You're importing all necessary libraries.
- The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like Agenty.
```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
```

### 5. Set up the Composio instance

No description provided.
```python
load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())
```

```typescript
dotenv.config();

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
```

### 6. Create a Tool Router session

What is happening:
- You give the Tool Router the user id and the toolkits you want available. Here, it is only agenty.
- The router checks the user's Agenty connection and prepares the MCP endpoint.
- The returned session.mcp.url is the MCP URL that your agent will use to access Agenty.
- This approach keeps things lightweight and lets the agent request Agenty tools only when needed during the conversation.
```python
# Create a Agenty Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["agenty"]
)

mcp_url = session.mcp.url
```

```typescript
// Create Tool Router session for Agenty
const session = await composio.create(userId as string, {
  toolkits: ['agenty'],
});
const mcpUrl = session.mcp.url;
```

### 7. Configure the agent

No description provided.
```python
# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Agenty. "
        "Help users perform Agenty operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)
```

```typescript
// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access Agenty. Help users perform Agenty operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
```

### 8. Start chat loop and handle conversation

No description provided.
```python
print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

// Simple CLI
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'You: ',
});

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

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

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession

load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())

# Create Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["agenty"]
)
mcp_url = session.mcp.url

# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Agenty. "
        "Help users perform Agenty operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)

print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['agenty'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access Agenty. Help users perform Agenty operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

  // Simple CLI
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: ',
  });

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

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

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\n');
    }

    rl.prompt();
  });

  rl.on('close', () => {
    console.log('\nSession ended.');
    process.exit(0);
  });
}

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

## Conclusion

This was a starter code for integrating Agenty MCP with OpenAI Agents SDK to build a functional AI agent that can interact with Agenty.
Key features:
- Hosted MCP tool integration through Composio's Tool Router
- SQLite session persistence for conversation history
- Simple async chat loop for interactive testing
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.

## How to build Agenty MCP Agent with another framework

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

## Related Toolkits

- [Excel](https://composio.dev/toolkits/excel) - Microsoft Excel is a robust spreadsheet application for organizing, analyzing, and visualizing data. It's the go-to tool for calculations, reporting, and flexible data management.
- [21risk](https://composio.dev/toolkits/_21risk) - 21RISK is a web app built for easy checklist, audit, and compliance management. It streamlines risk processes so teams can focus on what matters.
- [Abstract](https://composio.dev/toolkits/abstract) - Abstract provides a suite of APIs for automating data validation and enrichment tasks. It helps developers streamline workflows and ensure data quality with minimal effort.
- [Addressfinder](https://composio.dev/toolkits/addressfinder) - Addressfinder is a data quality platform for verifying addresses, emails, and phone numbers. It helps you ensure accurate customer and contact data every time.
- [Agentql](https://composio.dev/toolkits/agentql) - Agentql is a toolkit that connects AI agents to the web using a specialized query language. It enables structured web interaction and data extraction for smarter automations.
- [Ambee](https://composio.dev/toolkits/ambee) - Ambee is an environmental data platform providing real-time, hyperlocal APIs for air quality, weather, and pollen. Get precise environmental insights to power smarter decisions in your apps and workflows.
- [Ambient weather](https://composio.dev/toolkits/ambient_weather) - Ambient Weather is a platform for personal weather stations with a robust API for accessing local, real-time, and historical weather data. Get detailed environmental insights directly from your own sensors for smarter apps and automations.
- [Anonyflow](https://composio.dev/toolkits/anonyflow) - Anonyflow is a service for encryption-based data anonymization and secure data sharing. It helps organizations meet GDPR, CCPA, and HIPAA data privacy compliance requirements.
- [Api ninjas](https://composio.dev/toolkits/api_ninjas) - Api ninjas offers 120+ public APIs spanning categories like weather, finance, sports, and more. Developers use it to supercharge apps with real-time data and actionable endpoints.
- [Api sports](https://composio.dev/toolkits/api_sports) - Api sports is a comprehensive sports data platform covering 2,000+ competitions with live scores and 15+ years of stats. Instantly access up-to-date sports information for analysis, apps, or chatbots.
- [Apify](https://composio.dev/toolkits/apify) - Apify is a cloud platform for building, deploying, and managing web scraping and automation tools called Actors. It lets you automate data extraction and workflow tasks at scale—no infrastructure headaches.
- [Autom](https://composio.dev/toolkits/autom) - Autom is a lightning-fast search engine results data platform for Google, Bing, and Brave. Developers use it to access fresh, low-latency SERP data on demand.
- [Beaconchain](https://composio.dev/toolkits/beaconchain) - Beaconchain is a real-time analytics platform for Ethereum 2.0's Beacon Chain. It provides detailed insights into validators, blocks, and overall network performance.
- [Big data cloud](https://composio.dev/toolkits/big_data_cloud) - BigDataCloud provides APIs for geolocation, reverse geocoding, and address validation. Instantly access reliable location intelligence to enhance your applications and workflows.
- [Bigpicture io](https://composio.dev/toolkits/bigpicture_io) - BigPicture.io offers APIs for accessing detailed company and profile data. Instantly enrich your applications with up-to-date insights on 20M+ businesses.
- [Bitquery](https://composio.dev/toolkits/bitquery) - Bitquery is a blockchain data platform offering indexed, real-time, and historical data from 40+ blockchains via GraphQL APIs. Get unified, reliable access to complex on-chain data for analytics, trading, and research.
- [Brightdata](https://composio.dev/toolkits/brightdata) - Brightdata is a leading web data platform offering advanced scraping, SERP APIs, and anti-bot tools. It lets you collect public web data at scale, bypassing blocks and friction.
- [Builtwith](https://composio.dev/toolkits/builtwith) - BuiltWith is a web technology profiler that uncovers the technologies powering any website. Gain actionable insights into analytics, hosting, and content management stacks for smarter research and lead generation.
- [Byteforms](https://composio.dev/toolkits/byteforms) - Byteforms is an all-in-one platform for creating forms, managing submissions, and integrating data. It streamlines workflows by centralizing form data collection and automation.
- [Cabinpanda](https://composio.dev/toolkits/cabinpanda) - Cabinpanda is a data collection platform for building and managing online forms. It helps streamline how you gather, organize, and analyze responses.

## Frequently Asked Questions

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

With a standalone Agenty MCP server, the agents and LLMs can only access a fixed set of Agenty tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Agenty and many other apps based on the task at hand, all through a single MCP endpoint.

### Can I use Tool Router MCP with OpenAI Agents SDK?

Yes, you can. OpenAI Agents SDK fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Agenty tools.

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

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

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