# How to integrate Control d MCP with Pydantic AI

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

## Introduction

This guide walks you through connecting Control d to Pydantic AI using the Composio tool router. By the end, you'll have a working Control d agent that can list all devices connected to your account, remove a device by its id, show known access ips for your network through natural language commands.
This guide will help you understand how to give your Pydantic AI agent real control over a Control d account through Composio's Control d MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Control d with

- [OpenAI Agents SDK](https://composio.dev/toolkits/control_d/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/control_d/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/control_d/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/control_d/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/control_d/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/control_d/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/control_d/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/control_d/framework/cli)
- [Google ADK](https://composio.dev/toolkits/control_d/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/control_d/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/control_d/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/control_d/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/control_d/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/control_d/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- How to set up your Composio API key and User ID
- How to create a Composio Tool Router session for Control d
- How to attach an MCP Server to a Pydantic AI agent
- How to stream responses and maintain chat history
- How to build a simple REPL-style chat interface to test your Control d workflows

## What is Pydantic AI?

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

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

The Control d MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Control d account. It provides structured and secure access to your DNS filtering and device management environment, so your agent can perform actions like managing devices, enforcing policies, retrieving analytics, and monitoring network access on your behalf.
- Device inventory management: Easily list all devices on your account or remove specific devices by their identifier for streamlined device control.
- Profile and rule administration: Direct your agent to delete profiles, custom rules, or schedules—helping you maintain and enforce up-to-date network policies.
- Network access monitoring: Retrieve a list of known access IPs to keep tabs on which endpoints are connecting to your network infrastructure.
- Analytics endpoints discovery: Quickly fetch available analytics storage regions and endpoints so you can integrate and analyze DNS traffic data efficiently.
- Organization details access: Have the agent fetch and present your organization's account details for easy reference and auditing.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `CONTROL_D_DELETE_DEVICES_DEVICE_ID` | Delete Device by ID | Permanently delete a Control-D device/endpoint by its ID. WARNING: This is a destructive operation. Deleting a device will break DNS resolution on any physical gadget configured to use this device's unique DNS resolvers. Use GET /devices to retrieve valid device IDs before calling this action. |
| `CONTROL_D_DELETE_PROFILES_PROFILE_ID` | Delete Profile | Permanently deletes a Control D profile by its unique identifier (PK). IMPORTANT: The profile must be orphaned (not enforced by any device) before it can be deleted. If the profile is currently assigned to one or more devices, the deletion will fail. Use this tool when you need to remove an unused profile from the account. To check if a profile is safe to delete, first verify it has no associated devices using the Get Devices or Get Profile endpoints. |
| `CONTROL_D_DELETE_PROFILES_PROFILE_ID_RULES_RULE_ID` | Delete Profile Rule by Rule ID | Delete a custom DNS rule from a Control D profile by its rule identifier (hostname/domain). This tool removes a DNS filtering rule from the specified profile. Rules in Control D are identified by the hostname/domain they target (e.g., 'example.com', 'ads.domain.com'). Prerequisites: - Obtain profile_id from GET /profiles endpoint - Obtain rule_id (the hostname/domain) from GET /profiles/{profile_id}/rules endpoint Note: Requires write access to the API (read-only tokens will receive a 403 error). |
| `CONTROL_D_DELETE_PROFILES_PROFILE_ID_RULES_RULE_ID_FOLDER_ID` | Delete Rule from Folder | Delete a custom DNS rule from a specific folder in a Control D profile. This action permanently removes a custom rule (e.g., block, bypass, spoof, or redirect) from the specified folder within a profile. Requires valid profile_id, rule_id, and folder_id which can be obtained from: - profile_id: Get Profiles action - folder_id: Get Profile Folders action - rule_id: List Custom Rules in Folder action |
| `CONTROL_D_DELETE_PROFILES_PROFILE_ID_SCHEDULES_SCHEDULE_ID` | Delete Profile Schedule | Tool to delete a specific schedule within a profile. Use after confirming profile_id and schedule_id. |
| `CONTROL_D_GET_ACCESS` | List Known Access IPs | List up to the latest 50 IP addresses that were used to query against a specific Device (resolver). Use this to retrieve known access IPs associated with a device in your Control D account. |
| `CONTROL_D_GET_ANALYTICS_ENDPOINTS` | Get Analytics Endpoints | Tool to list analytics storage regions and their endpoints. Use after authenticating to retrieve available analytics regions. |
| `CONTROL_D_GET_ANALYTICS_LEVELS` | Get Analytics Levels | Tool to retrieve available analytics log levels for Control D devices. Use when you need to know what analytics options can be configured on devices (No Analytics, Some Analytics, Full Analytics). |
| `CONTROL_D_GET_BILLING_PAYMENTS` | Get Billing Payments | Tool to retrieve billing history of all payments made. Use when you need to access payment records, transaction history, or billing information for the account. |
| `CONTROL_D_GET_BILLING_PRODUCTS` | Get Billing Products | Retrieve all products currently activated on the Control D account. Use this to view active billing products, subscriptions, and their details. |
| `CONTROL_D_GET_DEVICES` | Get Devices | Lists all Control D devices (endpoints) associated with the account. Each device represents a unique DNS resolver that enforces a Profile (set of filtering rules). Use this to retrieve device inventory, check device status, or get resolver configuration details. Optionally filter by device_type to get only 'users' (desktops/mobiles/browsers) or 'routers'. |
| `CONTROL_D_GET_DEVICES_TYPES` | Get Device Types | List all allowed device types in Control D. Returns categorized device types (OS, Browser, TV, Router) with their available icon identifiers and human-readable labels. Use when you need to display device type options or validate device icon identifiers when creating or updating devices. |
| `CONTROL_D_GET_IP` | Get IP | Tool to retrieve the current IP address and datacenter information for the API request. Use when you need to check which IP address is being used or which Control D datacenter is handling requests. |
| `CONTROL_D_GET_NETWORK` | Get Network Stats | Tool to retrieve network stats on available services in different POPs (Points of Presence). Use when you need information about service availability across Control D's network infrastructure. |
| `CONTROL_D_GET_ORGANIZATIONS_MEMBERS` | Get Organization Members | Tool to view organization membership. Use to retrieve a list of all members in the organization including their email, status, permission levels, and last activity. |
| `CONTROL_D_GET_ORGANIZATIONS_ORGANIZATION` | Get Organization Details | Tool to view the authenticated organization's details. Use after confirming a valid API token. |
| `CONTROL_D_GET_ORGANIZATIONS_SUB_ORGANIZATIONS` | Get Sub-Organizations | Tool to view sub-organizations and their details. Use when you need to list all sub-organizations under the authenticated organization account. |
| `CONTROL_D_GET_PROFILES` | Get Profiles | Tool to list all profiles associated with the authenticated account. Use when you need an overview of accessible profiles. |
| `CONTROL_D_GET_PROFILES_OPTIONS` | Get Profile Options | Retrieves all available configuration options for DNS profiles in Control D. Returns a list of profile options including security filters (Safe Search, AI Malware Filter), TTL settings, block responses, and advanced DNS options (DNSSEC, DNS64, CNAME Flattening). Each option includes its type (toggle/dropdown/field), default value, and documentation URL. Use this to discover what settings can be configured when creating or updating profiles. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID` | Get Profile by ID | Tool to retrieve details of a specific profile by its ID. Use when you need full profile details after confirming the profile_id. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_ANALYTICS` | Get Profile Analytics | Retrieve analytics data for a Control D profile. Returns DNS query statistics and traffic data for the specified profile. Use profile_id='0' to get analytics for all profiles, or specify a profile ID from the List Profiles endpoint. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_ANALYTICS_LOGS` | Get Profile Analytics Logs | Retrieves DNS query activity logs for a specific Control D profile. This tool fetches analytics logs that record DNS queries made through the profile, including details about blocked, allowed, and redirected queries. Use this to monitor DNS activity, audit security policies, or troubleshoot DNS resolution issues. Prerequisites: - A valid profile_id obtained from GET /profiles endpoint - Analytics must be enabled for the profile to have log data Common use cases: - View recent DNS queries for a profile - Filter logs by date range to analyze specific time periods - Audit which domains were blocked or allowed |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_ANALYTICS_LOGS_LOG_ID` | Get Analytics Log Entry | Tool to retrieve a specific analytics log entry by its ID. Use when you need details of an analytics log for a given profile. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_ANALYTICS_SUMMARY` | Get Profile Analytics Summary | Tool to fetch a summary of analytics data for a given profile. Use after confirming profile ID and desired date range. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_ANALYTICS_TOP_DOMAINS` | Get Profile Analytics Top Domains | Tool to fetch top domains accessed within a specific profile. Use after confirming profile ID. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_ANALYTICS_TOP_SERVICES` | Get Profile Top Services | Tool to fetch top services accessed within a profile. Use after confirming the profile ID and desired date range. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_FILTERS` | Get Profile Filters | List all native (Control D curated) filters for a profile and their current states. Native filters are hand-curated blocklists maintained by Control D (e.g., 'Ads & Trackers', 'Malware', 'Adult Content'). Use this to see which filters are enabled/disabled for a profile. For 3rd party community filters, use the GET /profiles/{profile_id}/filters/external endpoint instead. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_FILTERS_EXTERNAL` | List External Filters for Profile | Tool to list third-party filters for a specific profile. Use when you need to retrieve all external filters and their states after confirming the profile ID. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_FOLDERS` | Get Profile Folders | List all rule folders (groups) within a Control D profile. Rule folders are used to organize and group custom DNS rules. Each folder has an action type (BLOCK, BYPASS, SPOOF, or REDIRECT) and contains multiple rules. Use this after obtaining a valid profile_id from the list profiles endpoint. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_RULES` | List Custom DNS Rules for Profile | Retrieve custom DNS rules for a Control D profile. Returns rules that control domain resolution (BLOCK, BYPASS, SPOOF, or REDIRECT actions). Omit folder_id to list root folder rules, or provide a folder_id to list rules in a specific folder. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_RULES_RULE_ID_FOLDER_ID` | Get Specific Rule in Folder | Tool to retrieve a specific rule within a folder by its ID. Use when you need full details of a custom rule in a profile's folder. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_SCHEDULES` | Get Profile Schedules | Tool to list schedules associated with a specific profile. Use after confirming the profile ID. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_SCHEDULES_SCHEDULE_ID` | Get Profile Schedule | Tool to retrieve a specific schedule by its ID within a profile. Use when you need details of a profile schedule after confirming the profile_id and schedule_id. |
| `CONTROL_D_GET_PROFILES_PROFILE_ID_SERVICES` | Get Profile Services | Tool to list services associated with a specific profile. Use when you need to retrieve all services that have any associated rules after confirming the profile ID. |
| `CONTROL_D_GET_PROXIES` | Get Proxies | Tool to retrieve the list of usable proxy locations that traffic can be redirected through. Use when you need to see available proxy exit locations for routing traffic via transparent proxies. |
| `CONTROL_D_GET_SERVICES_CATEGORIES` | Get Service Categories | List all available service categories in Control D. Returns categories like audio, video, social, gaming, etc. Each category contains multiple services that can be blocked or allowed. Use the returned 'PK' field as the category identifier when calling other service-related endpoints (e.g., get services by category). No parameters required - returns all available categories. |
| `CONTROL_D_GET_SERVICES_CATEGORIES_CATEGORY` | List Services by Category | Retrieves all services within a specific ControlD service category. Use this to discover available services (like Spotify, Netflix, Steam, etc.) that can be configured for DNS filtering or redirection. Each service includes its unique PK identifier needed for service-level configuration. First call GET /services/categories to get valid category identifiers. |
| `CONTROL_D_GET_USERS` | Get Users | Retrieve the authenticated user's account information from Control D. This tool returns comprehensive user account data including: - Basic user info (email, status, 2FA settings) - Organization membership and permissions (if applicable) - Account limits and features Use this tool to: - Verify the authenticated account details - Check organization membership and permissions - Get account status and capabilities - Retrieve the user's PK (primary key) for other API calls No parameters required - uses the authenticated API token. |
| `CONTROL_D_POST_DEVICES` | Create Device | Create a new device (DNS endpoint) in Control D. Each device gets unique DNS resolvers that enforce configured profiles. Requires a valid profile_id from GET_PROFILES. Returns DNS resolver URLs (DoH, DoT) and IPs for configuring client devices. |
| `CONTROL_D_POST_PROFILES` | Create Profile | Create a new blank profile or clone an existing one. Profiles define DNS filtering rules, services, and settings that can be applied to devices. Use this to provision a new profile before assigning rules, filters, or devices to it. |
| `CONTROL_D_POST_PROFILES_PROFILE_ID_RULES` | Create Custom DNS Rule | Create custom DNS rules for a profile to control domain resolution. Use this to block ads/trackers, bypass filtering for specific domains, spoof DNS responses with custom IPs, or redirect traffic through proxies. |
| `CONTROL_D_POST_PROFILES_PROFILE_ID_RULES_FOLDER_ID` | Create Custom Rules in Profile Folder | Tool to create custom rules within a specific folder for a profile. Use after confirming the profile and folder IDs and preparing rule definitions. |
| `CONTROL_D_POST_PROFILES_PROFILE_ID_SCHEDULES` | Create Profile Schedule | Create a new time-based schedule within a Control D profile. Schedules allow automatic enforcement of profile rules during specified time windows. Use this to set up recurring time periods (e.g., work hours, bedtime) when specific DNS filtering rules should apply. Requires a valid profile_id from GET /profiles. |
| `CONTROL_D_PUT_DEVICES_DEVICE_ID` | Modify Device | Modify an existing Control D device's settings. Use this tool to update device properties such as name, associated profiles, analytics level, IP learning, restrictions, DDNS settings, and status. At least one field to update must be provided alongside the device_id. |
| `CONTROL_D_PUT_ORGANIZATIONS` | Modify Organization | Modify organization settings such as name, contact details, website, and device limits. Use this to update organization metadata or change billing-related limits (max_users, max_routers). Note: Changing max_users or max_routers is a billable event. Requires a write-enabled API token with organization admin permissions. |
| `CONTROL_D_PUT_PROFILES_PROFILE_ID` | Modify Profile | Modify an existing profile by its ID. Use this to update profile properties such as the display name, deactivation timestamp, or lock status. Requires at least one modifiable field (name, disable_ttl, lock_status, lock_message). |
| `CONTROL_D_PUT_PROFILES_PROFILE_ID_FILTERS` | Bulk Update Profile Filters | Tool to bulk update filters on a specific profile. Use when you need to enable or disable multiple filters at once. Provide a list of filter IDs with desired states. |
| `CONTROL_D_PUT_PROFILES_PROFILE_ID_FILTERS_EXTERNAL` | Update External Filters for Profile | Tool to update external filters for a specific profile. Use when toggling third-party filters after listing them. |
| `CONTROL_D_PUT_PROFILES_PROFILE_ID_FILTERS_FILTER_FILTER` | Modify Profile Filter | Modify the enabled state of a specific native filter on a profile. Use this tool to enable or disable individual content filters like 'ads', 'malware', 'social', etc. on a specific profile. The filter status is set using integer values (1 = enabled, 0 = disabled). |
| `CONTROL_D_PUT_PROFILES_PROFILE_ID_RULES` | Modify Custom Rule for Profile | Modify an existing custom DNS rule for a profile in Control D. Use this to update rule properties such as action type (block/bypass/spoof/redirect), status (enabled/disabled), target hostnames, and redirect destinations. Rule types: - BLOCK (do=0): Block DNS resolution for the hostnames - BYPASS (do=1): Bypass all filters for the hostnames - SPOOF (do=2): Return custom IP addresses (set via/via_v6) - REDIRECT (do=3): Route traffic through a proxy (set via to proxy ID) |
| `CONTROL_D_PUT_PROFILES_PROFILE_ID_RULES_RULE_ID` | Update Custom Rule by Rule ID | Tool to update an existing custom rule by its ID. Use when modifying details like name, description, severity, or enabled status for a specific rule. |
| `CONTROL_D_PUT_PROFILES_PROFILE_ID_RULES_RULE_ID_FOLDER_ID` | Move Profile Rule to Folder | Tool to move a specific custom rule into a different folder. Use after confirming profile_id, rule_id, and folder_id. |
| `CONTROL_D_PUT_PROFILES_PROFILE_ID_SCHEDULES_SCHEDULE_ID` | Update Profile Schedule | Tool to update a specific schedule within a profile. Use when you need to modify schedule details after confirming profile_id and schedule_id. |
| `CONTROL_D_PUT_PROFILES_PROFILE_ID_SERVICES_SERVICE` | Modify Service for Profile | Tool to modify a specific service rule for a profile. Use when you need to update blocking, bypassing, spoofing, or proxy-redirect settings after reviewing existing rules. |

## Supported Triggers

None listed.

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

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

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Python 3.9 or higher
- A Composio account with an active API key
- Basic familiarity with Python and async programming

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

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

### 2. Install dependencies

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

### 3. Set up environment variables

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

### 4. Import dependencies

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

load_dotenv()
```

### 5. Create a Tool Router Session

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

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

### 6. Initialize the Pydantic AI Agent

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

### 7. Build the chat interface

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

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

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

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

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

### 8. Run the application

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

## Complete Code

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

load_dotenv()

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

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

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

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

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

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

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

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

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

## Conclusion

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

## How to build Control d MCP Agent with another framework

- [OpenAI Agents SDK](https://composio.dev/toolkits/control_d/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/control_d/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/control_d/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/control_d/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/control_d/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/control_d/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/control_d/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/control_d/framework/cli)
- [Google ADK](https://composio.dev/toolkits/control_d/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/control_d/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/control_d/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/control_d/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/control_d/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/control_d/framework/crew-ai)

## Related Toolkits

- [Firecrawl](https://composio.dev/toolkits/firecrawl) - Firecrawl automates large-scale web crawling and data extraction. It helps organizations efficiently gather, index, and analyze content from online sources.
- [Tavily](https://composio.dev/toolkits/tavily) - Tavily offers powerful search and data retrieval from documents, databases, and the web. It helps teams locate and filter information instantly, saving hours on research.
- [Exa](https://composio.dev/toolkits/exa) - Exa is a data extraction and search platform for gathering and analyzing information from websites, APIs, or databases. It helps teams quickly surface insights and automate data-driven workflows.
- [Serpapi](https://composio.dev/toolkits/serpapi) - SerpApi is a real-time API for structured search engine results. It lets you automate SERP data collection, parsing, and analysis for SEO and research.
- [Peopledatalabs](https://composio.dev/toolkits/peopledatalabs) - Peopledatalabs delivers B2B data enrichment and identity resolution APIs. Supercharge your apps with accurate, up-to-date business and contact data.
- [Snowflake](https://composio.dev/toolkits/snowflake) - Snowflake is a cloud data warehouse built for elastic scaling, secure data sharing, and fast SQL analytics across major clouds.
- [Posthog](https://composio.dev/toolkits/posthog) - PostHog is an open-source analytics platform for tracking user interactions and product metrics. It helps teams refine features, analyze funnels, and reduce churn with actionable insights.
- [Amplitude](https://composio.dev/toolkits/amplitude) - Amplitude is a digital analytics platform for product and behavioral data insights. It helps teams analyze user journeys and make data-driven decisions quickly.
- [Bright Data MCP](https://composio.dev/toolkits/brightdata_mcp) - Bright Data MCP is an AI-powered web scraping and data collection platform. Instantly access public web data in real time with advanced scraping tools.
- [Browseai](https://composio.dev/toolkits/browseai) - Browseai is a web automation and data extraction platform that turns any website into an API. It's perfect for monitoring websites and retrieving structured data without manual scraping.
- [ClickHouse](https://composio.dev/toolkits/clickhouse) - ClickHouse is an open-source, column-oriented database for real-time analytics and big data processing using SQL. Its lightning-fast query performance makes it ideal for handling large datasets and delivering instant insights.
- [Coinmarketcal](https://composio.dev/toolkits/coinmarketcal) - CoinMarketCal is a community-powered crypto calendar for upcoming events, announcements, and releases. It helps traders track market-moving developments and stay ahead in the crypto space.
- [Databox](https://composio.dev/toolkits/databox) - Databox is a business analytics platform that connects your data from any tool and device. It helps you track KPIs, build dashboards, and discover actionable insights.
- [Databricks](https://composio.dev/toolkits/databricks) - Databricks is a unified analytics platform for big data and AI on the lakehouse architecture. It empowers data teams to collaborate, analyze, and build scalable solutions efficiently.
- [Datagma](https://composio.dev/toolkits/datagma) - Datagma delivers data intelligence and analytics for business growth and market discovery. Get actionable market insights and track competitors to inform your strategy.
- [Delighted](https://composio.dev/toolkits/delighted) - Delighted is a customer feedback platform based on the Net Promoter System®. It helps you quickly gather, track, and act on customer sentiment.
- [Dovetail](https://composio.dev/toolkits/dovetail) - Dovetail is a research analysis platform for transcript review and insight generation. It helps teams code interviews, analyze feedback, and create actionable research summaries.
- [Dub](https://composio.dev/toolkits/dub) - Dub is a short link management platform with analytics and API access. Use it to easily create, manage, and track branded short links for your business.
- [Elasticsearch](https://composio.dev/toolkits/elasticsearch) - Elasticsearch is a distributed, RESTful search and analytics engine for all types of data. It delivers fast, scalable search and powerful analytics across massive datasets.
- [Fireflies](https://composio.dev/toolkits/fireflies) - Fireflies.ai is an AI-powered meeting assistant that records, transcribes, and analyzes voice conversations. It helps teams capture call notes automatically and search or summarize meetings effortlessly.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Control d MCP?

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

### Can I use Tool Router MCP with Pydantic AI?

Yes, you can. Pydantic AI fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Control d tools.

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

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

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