# How to integrate Control d MCP with LangChain

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

## Introduction

This guide walks you through connecting Control d to LangChain 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 LangChain 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)
- [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:
- Get and set up your OpenAI and Composio API keys
- Connect your Control d project to Composio
- Create a Tool Router MCP session for Control d
- Initialize an MCP client and retrieve Control d tools
- Build a LangChain agent that can interact with Control d
- Set up an interactive chat interface for testing

## What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides tools and abstractions for building agents that can reason, use tools, and maintain conversation context.
Key features include:
- Agent Framework: Build agents that can use tools and make decisions
- MCP Integration: Connect to external services through Model Context Protocol adapters
- Memory Management: Maintain conversation history across interactions
- Multi-Provider Support: Works with OpenAI, Anthropic, and other LLM providers

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

No description provided.

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

No description provided.
```python
pip install composio-langchain langchain-mcp-adapters langchain python-dotenv
```

```typescript
npm install @composio/langchain @langchain/core @langchain/openai @langchain/mcp-adapters 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's API
- COMPOSIO_USER_ID identifies the user for session management
- OPENAI_API_KEY enables access to OpenAI's language models
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_composio_user_id_here
OPENAI_API_KEY=your_openai_api_key_here
```

### 4. Import dependencies

No description provided.
```python
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_agent
from dotenv import load_dotenv
from composio import Composio
import asyncio
import os

load_dotenv()
```

```typescript
import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { createAgent } from "langchain";
import * as readline from 'readline';
import 'dotenv/config';

dotenv.config();
```

### 5. Initialize Composio client

What's happening:
- We're loading the COMPOSIO_API_KEY from environment variables and validating it exists
- Creating a Composio instance that will manage our connection to Control d tools
- Validating that COMPOSIO_USER_ID is also set before proceeding
```python
async def main():
    composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))

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

```typescript
const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.COMPOSIO_USER_ID;

if (!composioApiKey) throw new Error('COMPOSIO_API_KEY is not set');
if (!userId) throw new Error('COMPOSIO_USER_ID is not set');

async function main() {
    const composio = new Composio({
        apiKey: composioApiKey as string,
        provider: new LangchainProvider()
    });
```

### 6. 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
- This approach allows the agent to dynamically load and use Control d tools as needed
```python
# Create Tool Router session for Control d
session = composio.create(
    user_id=os.getenv("COMPOSIO_USER_ID"),
    toolkits=['control_d']
)

url = session.mcp.url
```

```typescript
const session = await composio.create(
    userId as string,
    {
        toolkits: ['control_d']
    }
);

const url = session.mcp.url;
```

### 7. Configure the agent with the MCP URL

No description provided.
```python
client = MultiServerMCPClient({
    "control_d-agent": {
        "transport": "streamable_http",
        "url": session.mcp.url,
        "headers": {
            "x-api-key": os.getenv("COMPOSIO_API_KEY")
        }
    }
})

tools = await client.get_tools()

agent = create_agent("gpt-5", tools)
```

```typescript
const client = new MultiServerMCPClient({
    "control_d-agent": {
        transport: "http",
        url: url,
        headers: {
            "x-api-key": process.env.COMPOSIO_API_KEY
        }
    }
});

const tools = await client.getTools();

const agent = createAgent({ model: "gpt-5", tools });
```

### 8. Set up interactive chat interface

No description provided.
```python
conversation_history = []

print("Chat started! Type 'exit' or 'quit' to end the conversation.\n")
print("Ask any Control d related question or task to the agent.\n")

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

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

    if not user_input:
        continue

    conversation_history.append({"role": "user", "content": user_input})
    print("\nAgent is thinking...\n")

    response = await agent.ainvoke({"messages": conversation_history})
    conversation_history = response['messages']
    final_response = response['messages'][-1].content
    print(f"Agent: {final_response}\n")
```

```typescript
let conversationHistory: any[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log("Ask any Control d related question or task to the agent.\n");

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

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;
    }

    conversationHistory.push({ role: "user", content: trimmedInput });
    console.log("\nAgent is thinking...\n");

    const response = await agent.invoke({ messages: conversationHistory });
    conversationHistory = response.messages;

    const finalResponse = response.messages[response.messages.length - 1]?.content;
    console.log(`Agent: ${finalResponse}\n`);
        
        rl.prompt();
    });

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

### 9. Run the application

No description provided.
```python
if __name__ == "__main__":
    asyncio.run(main())
```

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

## Complete Code

```python
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_agent
from dotenv import load_dotenv
from composio import Composio
import asyncio
import os

load_dotenv()

async def main():
    composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))
    
    if not os.getenv("COMPOSIO_API_KEY"):
        raise ValueError("COMPOSIO_API_KEY is not set")
    if not os.getenv("COMPOSIO_USER_ID"):
        raise ValueError("COMPOSIO_USER_ID is not set")
    
    session = composio.create(
        user_id=os.getenv("COMPOSIO_USER_ID"),
        toolkits=['control_d']
    )

    url = session.mcp.url
    
    client = MultiServerMCPClient({
        "control_d-agent": {
            "transport": "streamable_http",
            "url": url,
            "headers": {
                "x-api-key": os.getenv("COMPOSIO_API_KEY")
            }
        }
    })
    
    tools = await client.get_tools()
  
    agent = create_agent("gpt-5", tools)
    
    conversation_history = []
    
    print("Chat started! Type 'exit' or 'quit' to end the conversation.\n")
    print("Ask any Control d related question or task to the agent.\n")
    
    while True:
        user_input = input("You: ").strip()
        
        if user_input.lower() in ['exit', 'quit', 'bye']:
            print("\nGoodbye!")
            break
        
        if not user_input:
            continue
        
        conversation_history.append({"role": "user", "content": user_input})
        print("\nAgent is thinking...\n")
        
        response = await agent.ainvoke({"messages": conversation_history})
        conversation_history = response['messages']
        final_response = response['messages'][-1].content
        print(f"Agent: {final_response}\n")

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

```typescript
import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
import { MultiServerMCPClient } from "@langchain/mcp-adapters";  
import { createAgent } from "langchain";
import * as readline from 'readline';
import 'dotenv/config';

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

if (!composioApiKey) throw new Error('COMPOSIO_API_KEY is not set');
if (!userId) throw new Error('COMPOSIO_USER_ID is not set');

async function main() {
    const composio = new Composio({
        apiKey: composioApiKey as string,
        provider: new LangchainProvider()
    });

    const session = await composio.create(
        userId as string,
        {
            toolkits: ['control_d']
        }
    );

    const url = session.mcp.url;
    
    const client = new MultiServerMCPClient({
        "control_d-agent": {
            transport: "http",
            url: url,
            headers: {
                "x-api-key": process.env.COMPOSIO_API_KEY
            }
        }
    });
    
    const tools = await client.getTools();
  
    const agent = createAgent({ model: "gpt-5", tools });
    
    let conversationHistory: any[] = [];
    
    console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
    console.log("Ask any Control d related question or task to the agent.\n");
    
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        prompt: 'You: '
    });

    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;
        }
        
        conversationHistory.push({ role: "user", content: trimmedInput });
        console.log("\nAgent is thinking...\n");
        
        const response = await agent.invoke({ messages: conversationHistory });
        conversationHistory = response.messages;
        
        const finalResponse = response.messages[response.messages.length - 1]?.content;
        console.log(`Agent: ${finalResponse}\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

You've successfully built a LangChain agent that can interact with Control d through Composio's Tool Router.
Key features of this implementation:
- Dynamic tool loading through Composio's Tool Router
- Conversation history maintenance for context-aware responses
- Async Python provides clean, efficient execution of agent workflows
You can extend this further by adding error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.

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

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