MCP Providers

Guide to Using Composio MCP Servers with Your Agent Framework
Only available for TypeScript SDK
At this time, MCP providers using the Composio SDK are only supported in the TypeScript SDK. Support for the Python SDK is coming soon.

Integrating external tools into agent frameworks can be a complex and time-consuming process. Composio MCP (Model Context Protocol) servers simplify this workflow, enabling you to connect your framework to a wide array of tools and services with minimal configuration.

This guide introduces the primary MCP providers, each optimized for a popular agent framework. With these providers, you can focus on developing intelligent agent logic while Composio handles the integration details.


1. Anthropic Provider

The Anthropic Provider is purpose-built for use with the Anthropic Claude API. It supports Model Context Protocol (MCP) tools via a lightweight client that exposes a getServer method for retrieving the appropriate Composio MCP Server URL, preconfigured for your user. This provider ensures seamless compatibility between Composio tools and Anthropic’s function calling APIs.

1import { Composio } from '@composio/core';
2import { AnthropicProvider } from '@composio/anthropic';
3import Anthropic from '@anthropic-ai/sdk';
4
5// Initialize Anthropic client
6const anthropic = new Anthropic({
7 apiKey: process.env.ANTHROPIC_API_KEY,
8});
9
10// Initialize Composio with the Anthropic provider
11const composio = new Composio({
12 apiKey: process.env.COMPOSIO_API_KEY,
13 provider: new AnthropicProvider({ cacheTools: true }),
14});
15
16// Create MCP server with the new API structure
17const mcpConfig = await composio.mcp.create({
18 name: "Gmail Readonly Server",
19 serverConfig: [
20 {
21 authConfigId: "<auth_config_id>", // Your auth config ID
22 allowedTools: ["GMAIL_FETCH_EMAILS"]
23 }
24 ],
25 options: {
26 isChatAuth: true
27 }
28});
29
30console.log(`✅ MCP server created: ${mcpConfig.id}`);
31console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);
32
33// Check user connection status before proceeding
34const connectionStatus = await composio.mcp.getUserConnectionStatus({
35 id: mcpConfig.id,
36 userId: "utkarsh-dixit"
37});
38
39if (!connectionStatus.connected) {
40 console.log("❌ User needs to connect required accounts");
41 // Handle authentication as needed
42 return;
43}
44
45// Retrieve server instances for connected accounts
46const serverInstances = await mcpConfig.getServer({
47 userId: "utkarsh-dixit",
48});
49
50console.log("Server instances for connected accounts:", serverInstances);
51
52console.log("\n=== Fetching and Summarizing Recent Emails ===");
53
54const stream = await anthropic.beta.messages.stream(
55{
56 model: "claude-3-5-sonnet-20241022",
57 max_tokens: 1000,
58 mcp_servers: serverInstances,
59 messages: [
60 {
61 role: "user",
62 content:
63 "Please fetch the latest 10 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email. Format the response in a clear, organized way.",
64 },
65 ],
66},
67{
68 headers: {
69 "anthropic-beta": "mcp-client-2025-04-04",
70 },
71}
72);
73
74console.log("\n📬 Email Summary:");
75for await (const event of stream) {
76 if (
77 event.type === "content_block_delta" &&
78 event.delta.type === "text_delta"
79 ) {
80 process.stdout.write(event.delta.text);
81 }
82}
83process.stdout.write("\n");
84
85console.log("\n✅ Anthropic MCP example completed successfully!");

2. Mastra Provider

The Mastra Provider is tailored for the Mastra TypeScript-native agent framework. This client provides a getServer method to obtain the Composio MCP Server URL, configured for your user.

1import { MastraProvider } from '@composio/mastra';
2import { Composio } from '@composio/core';
3import { MCPClient } from '@mastra/mcp';
4import { Agent } from '@mastra/core/agent';
5import { openai } from '@ai-sdk/openai';
6import type { MastraMCPServerDefinition } from '@mastra/mcp';
7
8const composio = new Composio({
9 apiKey: process.env.COMPOSIO_API_KEY,
10 provider: new MastraProvider(),
11});
12
13// Create an MCP server with the Gmail toolkit using new API structure
14const mcpConfig = await composio.mcp.create({
15 name: "Gmail Readonly Server",
16 serverConfig: [
17 {
18 authConfigId: "<auth_config_id>", // Your auth config ID
19 allowedTools: ["GMAIL_FETCH_EMAILS"]
20 }
21 ],
22 options: {
23 isChatAuth: true
24 }
25});
26
27console.log(`✅ MCP server created: ${mcpConfig.id}`);
28console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);
29
30// Check user connection status
31const connectionStatus = await composio.mcp.getUserConnectionStatus({
32 id: mcpConfig.id,
33 userId: "utkarsh-dixit"
34});
35
36console.log("Connection status:", connectionStatus.connected);
37
38if (!connectionStatus.connected) {
39 console.log("❌ User needs to authenticate with required services");
40 // Handle authentication flow
41 Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {
42 if (!status.connected) {
43 console.log(`Please connect ${toolkit}`);
44 }
45 });
46 return;
47}
48
49// Retrieve server instance for connected accounts
50const serverInstance = await mcpConfig.getServer({
51 userId: "utkarsh-dixit"
52});
53
54console.log("Server instance for connected accounts:", serverInstance);
55
56// Initialize MCPClient with the server URLs
57const mcpClient = new MCPClient({
58servers: Object.fromEntries(
59 Object.entries(serverInstance as Record<string, { url: string }>).map(
60 ([key, value]) => [key, { url: new URL(value.url) }]
61 )
62) satisfies Record<string, MastraMCPServerDefinition>,
63});
64
65// List available tools from MCP client
66const tools = await mcpClient.getTools();
67console.log(`🔧 Available tools: ${Object.keys(tools).join(", ")}`);
68
69// Create a Gmail agent using the MCP tools
70const gmailAgent = new Agent({
71 name: "Gmail Assistant",
72 instructions: `
73 You are a helpful Gmail assistant that fetches and summarizes emails.
74 When fetching emails, provide a clear summary of the results including sender, subject, and date.
75 Be concise and provide actionable information based on the email content.
76 `,
77 model: openai("gpt-4o-mini"),
78 tools,
79});
80
81// Fetch and summarize recent emails
82console.log("\n=== Fetching and Summarizing Recent Emails ===");
83const emailResponse = await gmailAgent.generate(
84"Fetch the latest 10 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email"
85);
86console.log("\n📬 Email Summary:");
87console.log(emailResponse.text);
88
89console.log("\n✅ Gmail MCP example completed successfully!");

3. OpenAI SDK Provider

The OpenAI SDK Provider is designed for use with the OpenAI SDK and supports MCP tools through a streamlined client. This client provides a getServer method to obtain the Composio MCP Server URL, configured for your user.

1import { Composio } from '@composio/core';
2import { OpenAIProvider } from '@composio/openai';
3import OpenAI from 'openai';
4
5const openai = new OpenAI({
6 apiKey: process.env.OPENAI_API_KEY,
7});
8
9const composio = new Composio({
10 apiKey: process.env.COMPOSIO_API_KEY,
11 provider: new OpenAIProvider(),
12});
13
14// Create MCP server with new API structure
15const mcpConfig = await composio.mcp.create({
16 name: "Gmail Readonly Server",
17 serverConfig: [
18 {
19 authConfigId: "<auth_config_id>", // Your auth config ID
20 allowedTools: ["GMAIL_FETCH_EMAILS"]
21 }
22 ],
23 options: {
24 isChatAuth: true
25 }
26});
27
28console.log(`✅ MCP server created: ${mcpConfig.id}`);
29console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);
30
31// Check if user has necessary connections
32const connectionStatus = await composio.mcp.getUserConnectionStatus({
33 id: mcpConfig.id,
34 userId: "utkarsh-dixit"
35});
36
37if (!connectionStatus.connected) {
38 console.log("❌ User authentication required");
39 // Handle missing connections
40 for (const [toolkit, status] of Object.entries(connectionStatus.connectedToolkits)) {
41 if (!status.connected) {
42 const authParams = await composio.mcp.getConnectionParams({
43 id: mcpConfig.id,
44 toolkit
45 });
46
47 const authRequest = await composio.mcp.authorize({
48 id: mcpConfig.id,
49 userId: "utkarsh-dixit",
50 toolkit
51 });
52
53 if (authRequest.redirectUrl) {
54 console.log(`Please authenticate with ${toolkit}: ${authRequest.redirectUrl}`);
55 }
56 }
57 }
58 return;
59}
60
61// Retrieve server URLs for connected accounts
62const serverUrls = await mcpConfig.getServer({
63 userId: "utkarsh-dixit",
64 options: {
65 limitTools: ["GMAIL_FETCH_EMAILS"] // Optional: limit to specific tools
66 }
67});
68
69console.log("Server URLs for your MCP server:", serverUrls);
70
71// Use with OpenAI (example with hypothetical OpenAI MCP integration)
72const completion = await openai.chat.completions.create({
73 model: "gpt-4o-mini",
74 messages: [
75 {
76 role: "user",
77 content: "I've connected to Gmail and I want to fetch the latest email from my inbox and summarize it"
78 }
79 ],
80 // Note: This is a hypothetical integration - actual OpenAI MCP support may differ
81 tools: serverUrls,
82});
83
84console.log("\n📬 Email Summary:");
85console.log(completion.choices[0].message.content);
86
87console.log("\n✅ OpenAI MCP example completed successfully!");
88console.log("\n💡 Note: The MCP server URLs can also be used to connect from other MCP-compatible clients.");
89console.log(`📍 Server ID for future reference: ${mcpConfig.id}`);

Managing Existing Servers

You can also work with previously created MCP servers:

1// Find a server by name
2const existingServer = await composio.mcp.getByName("Gmail Readonly Server");
3
4// Check connection status for the existing server
5const status = await composio.mcp.getUserConnectionStatus({
6 id: existingServer.id,
7 userId: "user123@example.com"
8});
9
10// Generate URLs for the existing server
11const urls = await composio.mcp.getServer({
12 id: existingServer.id,
13 userId: "user123@example.com",
14 options: {
15 isChatAuth: true
16 }
17});

Best Practices for Providers

  1. Always check connection status before using MCP servers to ensure users are authenticated
  2. Handle authentication gracefully by providing clear instructions and redirect URLs
  3. Use meaningful server names to make management easier
  4. Limit tools appropriately to only what your application needs
  5. Cache server configurations when possible to reduce API calls
  6. Monitor connection health and provide re-authentication flows when needed

By using Composio MCP Servers with these providers, you can quickly connect your agent framework to a wide range of external tools with minimal effort. This lets you streamline integration, reduce setup time, and focus more on building your AI agent.