1
-
2
-# MCP (Model Control Protocol) API
3
-
4
-The `MCP` class provides methods to manage Model Control Protocol servers, enabling AI models to interact with external tools and services through a standardized protocol. MCP servers act as bridges between AI agents and various toolkits, providing secure and managed access to external capabilities.
5
-
6
-## Overview
7
-
8
-MCP (Model Control Protocol) is a protocol for exposing tools and capabilities to AI models in a standardized way. With Composio's MCP integration, you can:
9
-
10
-- Create MCP servers that expose specific toolkits and tools
11
-- Manage authentication for MCP servers
12
-- Generate secure URLs for AI agents to connect to MCP servers
13
-- Support multiple AI frameworks through provider-specific transformations
14
-
15
-## Methods
16
-
17
-### create(name, toolkitConfigs, authOptions?)
18
-
19
-Creates a new MCP server with specified toolkit configurations.
20
-
21
-```typescript
22
-// Create an MCP server with Gmail toolkit
23
-const server = await composio.mcp.create(
24
- "my-gmail-server",
25
- [
26
- {
27
- toolkit: "gmail",
28
- authConfigId: "ac_sdhkjfhjksdk",
29
- allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
30
- }
31
- ],
32
- { isChatAuth: true }
33
-);
34
-
35
-// Create an MCP server with multiple toolkits
36
-const multiToolServer = await composio.mcp.create(
37
- "multi-tool-server",
38
- [
39
- {
40
- toolkit: "github",
41
- authConfigId: "ac_github123",
42
- allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_GET_REPO"]
43
- },
44
- {
45
- toolkit: "slack",
46
- authConfigId: "ac_slack456",
47
- allowedTools: ["SLACK_SEND_MESSAGE"]
48
- }
49
- ]
50
-);
51
-
52
-// Use the convenience method to get server URLs
53
-const urls = await server.getServer({
54
- connectedAccountIds: { gmail: "connected_account_id" }
55
-});
56
-```
57
-
58
-**Parameters:**
59
-
60
-- `name` (string): Unique name for the MCP server
61
-- `toolkitConfigs` (MCPToolkitConfig[]): Array of toolkit configurations
62
- - `toolkit`: The toolkit slug (e.g., "gmail", "github")
63
- - `authConfigId`: The auth configuration ID to use
64
- - `allowedTools`: Array of specific tool IDs to expose
65
-- `authOptions` (MCPAuthOptions): Optional authentication options
66
- - `isChatAuth`: Whether to use Composio-managed authentication
67
-
68
-**Returns:** Promise<McpServerCreateResponse> - Created server details with convenience `getServer` method
69
-
70
-**Throws:** ValidationError if configurations are invalid or server creation fails
71
-
72
-### getServer(id, params, authOptions?)
73
-
74
-Retrieves server URLs for an existing MCP server. This method generates secure URLs that AI agents can use to connect to the MCP server.
75
-
76
-```typescript
77
-// Get URLs for a server using connected account IDs
78
-const urls = await composio.mcp.getServer("server-uuid", {
79
- connectedAccountIds: {
80
- gmail: "connected_account_123",
81
- github: "connected_account_456"
82
- }
83
-});
84
-
85
-// Get URLs for a server using user ID
86
-const userUrls = await composio.mcp.getServer("server-uuid", {
87
- userId: "user_123"
88
-});
89
-
90
-// Override authentication options
91
-const customAuthUrls = await composio.mcp.getServer(
92
- "server-uuid",
93
- { userId: "user_123" },
94
- { isChatAuth: false }
95
-);
96
-```
97
-
98
-**Parameters:**
99
-
100
-- `id` (string): Server UUID
101
-- `params` (MCPGetServerParams): Parameters for getting server URLs
102
- - Either `connectedAccountIds` (object mapping toolkit names to account IDs) OR `userId` (string)
103
-- `authOptions` (MCPAuthOptions): Optional authentication options to override server defaults
104
-
105
-**Returns:** Promise<T> - Transformed server URLs in provider-specific format
106
-
107
-**Throws:** ValidationError if parameters are invalid or URL generation fails
108
-
109
-### list(options)
110
-
111
-Lists MCP server configurations with filtering options.
112
-
113
-```typescript
114
-// List all servers with pagination
115
-const servers = await composio.mcp.list({
116
- page: 1,
117
- limit: 10
118
-});
119
-
120
-// List servers for specific toolkits
121
-const gmailServers = await composio.mcp.list({
122
- toolkits: ['gmail', 'google-calendar'],
123
- limit: 20
124
-});
125
-
126
-// List servers by auth config
127
-const authFilteredServers = await composio.mcp.list({
128
- authConfigs: ['auth_123', 'auth_456'],
129
- name: 'production'
130
-});
131
-```
132
-
133
-**Parameters:**
134
-
135
-- `options` (object): Filtering and pagination options
136
- - `page`: Page number for pagination (default: 1)
137
- - `limit`: Number of items per page (default: 10)
138
- - `toolkits`: Filter by toolkit names
139
- - `authConfigs`: Filter by auth config IDs
140
- - `name`: Filter by server name
141
-
142
-**Returns:** Promise<McpListResponse> - List of MCP servers
143
-
144
-### get(id)
145
-
146
-Retrieves details of a specific MCP server.
147
-
148
-```typescript
149
-const serverDetails = await composio.mcp.get('server-uuid');
150
-console.log(serverDetails.name);
151
-console.log(serverDetails.toolkits);
152
-console.log(serverDetails.status);
153
-```
154
-
155
-**Parameters:**
156
-
157
-- `id` (string): Server UUID
158
-
159
-**Returns:** Promise<McpRetrieveResponse> - Server details including configuration and metadata
160
-
161
-### update(id, name, toolkitConfigs, authOptions?)
162
-
163
-Updates an MCP server configuration.
164
-
165
-```typescript
166
-const updatedServer = await composio.mcp.update(
167
- "server-uuid",
168
- "updated-server-name",
169
- [
170
- {
171
- toolkit: "gmail",
172
- authConfigId: "ac_new_auth_config",
173
- allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL", "GMAIL_CREATE_DRAFT"]
174
- }
175
- ],
176
- { isChatAtuh: true }
177
-);
178
-```
179
-
180
-**Parameters:**
181
-
182
-- `id` (string): Server UUID
183
-- `name` (string): New name for the server
184
-- `toolkitConfigs` (MCPToolkitConfig[]): Updated toolkit configurations
185
-- `authOptions` (MCPAuthOptions): Updated authentication options
186
-
187
-**Returns:** Promise<McpUpdateResponse> - Updated server details
188
-
189
-### delete(id)
190
-
191
-Deletes an MCP server.
192
-
193
-```typescript
194
-const result = await composio.mcp.delete('server-uuid');
195
-console.log(result.deleted); // true
196
-```
197
-
198
-**Parameters:**
199
-
200
-- `id` (string): Server UUID
201
-
202
-**Returns:** Promise<McpDeleteResponse> - Deletion confirmation
203
-
204
-### generateUrl(params)
205
-
206
-Generates URLs for MCP server access. This is a lower-level method primarily used internally.
207
-
208
-```typescript
209
-const urlResponse = await composio.mcp.generateUrl({
210
- userIds: ['user123'],
211
- connectedAccountIds: ['account456'],
212
- mcpServerId: 'server-uuid',
213
- managedAuthByComposio: true
214
-});
215
-```
216
-
217
-**Parameters:**
218
-
219
-- `params` (GenerateURLParams): URL generation parameters
220
- - `userIds`: Array of user IDs
221
- - `connectedAccountIds`: Array of connected account IDs
222
- - `mcpServerId`: MCP server ID
223
- - `managedAuthByComposio`: Whether to use Composio-managed auth
224
-
225
-**Returns:** Promise<GenerateURLResponse> - Generated URLs
226
-
227
-## Provider Integration
228
-
229
-Different AI frameworks expect MCP server URLs in different formats. Composio automatically handles these transformations through provider-specific implementations.
230
-
231
-### Using with Providers
232
-
233
-```typescript
234
-import { Composio } from '@composio/core';
235
-import { MastraProvider } from '@composio/mastra';
236
-import { AnthropicProvider } from '@composio/anthropic';
237
-
238
-// With Mastra provider - returns key-value URL mapping
239
-const composioMastra = new Composio({
240
- apiKey: process.env.COMPOSIO_API_KEY,
241
- provider: new MastraProvider()
242
-});
243
-
244
-const mastraServer = await composioMastra.mcp.create(...);
245
-const mastraUrls = await mastraServer.getServer({
246
- connectedAccountIds: { gmail: "account_id" }
247
-});
248
-// Returns: { "server-0": { url: "..." } }
249
-
250
-// With Anthropic provider - returns array of server info
251
-const composioAnthropic = new Composio({
252
- apiKey: process.env.COMPOSIO_API_KEY,
253
- provider: new AnthropicProvider()
254
-});
255
-
256
-const anthropicServer = await composioAnthropic.mcp.create(...);
257
-const anthropicUrls = await anthropicServer.getServer({
258
- connectedAccountIds: { gmail: "account_id" }
259
-});
260
-// Returns: [{ url: URL, name: "...", toolkit: "gmail" }]
261
-```
262
-
263
-### Supported Providers
264
-
265
-- **Anthropic** - Returns McpServerUrlInfo[]
266
-- **OpenAI** - Returns McpServerUrlInfo[]
267
-- **LangChain** - Returns McpServerUrlInfo[]
268
-- **Vercel** - Returns McpServerUrlInfo[]
269
-- **Google** - Returns McpServerUrlInfo[]
270
-- **CloudFlare** - Returns McpServerUrlInfo[]
271
-- **Mastra** - Returns custom key-value URL mapping
272
-
273
-## Types
274
-
275
-### MCPToolkitConfig
276
-
277
-```typescript
278
-interface MCPToolkitConfig {
279
- toolkit: string; // Toolkit slug (e.g., "gmail", "github")
280
- authConfigId: string; // Auth configuration ID
281
- allowedTools: string[]; // Array of allowed tool IDs
282
-}
283
-```
284
-
285
-### MCPAuthOptions
286
-
287
-```typescript
288
-interface MCPAuthOptions {
289
- isChatAuth?: boolean; // Use Composio-managed authentication
290
-}
291
-```
292
-
293
-### MCPGetServerParams
294
-
295
-```typescript
296
-interface MCPGetServerParams {
297
- userId?: string; // User ID (XOR with connectedAccountIds)
298
- connectedAccountIds?: Record<string, string>; // Toolkit to account ID mapping
299
-}
300
-```
301
-
302
-### McpServerCreateResponse
303
-
304
-```typescript
305
-interface McpServerCreateResponse<T> {
306
- id: string; // Server UUID
307
- name: string; // Server name
308
- createdAt?: string; // Creation timestamp
309
- updatedAt?: string; // Last update timestamp
310
- status?: string; // Server status
311
- toolkits: string[]; // List of enabled toolkits
312
- getServer: (params: MCPGetServerParams) => Promise<T>; // Convenience method
313
-}
314
-```
315
-
316
-### McpListResponse
317
-
318
-```typescript
319
-interface McpListResponse {
320
- items?: Array<{
321
- id: string;
322
- name: string;
323
- createdAt?: string;
324
- updatedAt?: string;
325
- status?: string;
326
- }>;
327
-}
328
-```
329
-
330
-### McpServerUrlInfo
331
-
332
-```typescript
333
-interface McpServerUrlInfo {
334
- url: URL; // MCP server URL
335
- name: string; // Server instance name
336
- toolkit?: string; // Associated toolkit
337
-}
338
-```
339
-
340
-## Complete Example
341
-
342
-Here's a complete example of using MCP with an AI agent:
343
-
344
-```typescript
345
-import { Composio } from '@composio/core';
346
-import { MastraProvider } from '@composio/mastra';
347
-import { MCPClient } from '@mastra/mcp';
348
-import { Agent } from '@mastra/core/agent';
349
-import { openai } from '@ai-sdk/openai';
350
-
351
-// Initialize Composio with Mastra provider
352
-const composio = new Composio({
353
- apiKey: process.env.COMPOSIO_API_KEY,
354
- provider: new MastraProvider(),
355
-});
356
-
357
-// Create an MCP server with Gmail toolkit
358
-const mcpServer = await composio.mcp.create(
359
- "gmail-assistant",
360
- [
361
- {
362
- toolkit: "gmail",
363
- authConfigId: "ac_your_auth_config",
364
- allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
365
- }
366
- ],
367
- { isChatAuth: true }
368
-);
369
-
370
-// Get server URLs for connected accounts
371
-const serverUrls = await mcpServer.getServer({
372
- connectedAccountIds: {
373
- "gmail": "your_connected_account_id"
374
- }
375
-});
376
-
377
-// Initialize MCP client with the server URLs
378
-const mcpClient = new MCPClient({
379
- servers: Object.fromEntries(
380
- Object.entries(serverUrls).map(([key, value]) => [
381
- key,
382
- { url: new URL(value.url) }
383
- ])
384
- )
385
-});
386
-
387
-// Get available tools from MCP
388
-const tools = await mcpClient.getTools();
389
-
390
-// Create an AI agent with MCP tools
391
-const gmailAgent = new Agent({
392
- name: 'Gmail Assistant',
393
- instructions: 'You are a helpful Gmail assistant.',
394
- model: openai('gpt-4'),
395
- tools,
396
-});
397
-
398
-// Use the agent
399
-const response = await gmailAgent.generate('Fetch my latest emails');
400
-console.log(response.text);
401
-```
402
-
403
-## Best Practices
404
-
405
-1. **Toolkit Selection**: Only expose the tools that your AI agent needs to minimize the attack surface
406
-2. **Authentication**: Use Composio-managed authentication when possible for better security
407
-3. **Error Handling**: Always handle validation errors when creating or updating servers
408
-4. **Provider Choice**: Choose the appropriate provider based on your AI framework
409
-5. **Server Naming**: Use descriptive names that indicate the server's purpose
410
-6. **Tool Allowlisting**: Be specific about which tools to expose rather than exposing entire toolkits
411
-
412
-## Error Handling
413
-
414
-All MCP methods throw `ValidationError` when:
415
-- Input parameters fail Zod schema validation
416
-- API responses don't match expected schemas
417
-- Server operations fail (create, update, delete)
418
-- URL generation fails
419
-
420
-```typescript
421
-try {
422
- const server = await composio.mcp.create("my-server", toolkitConfigs);
423
-} catch (error) {
424
- if (error instanceof ValidationError) {
425
- console.error('Validation failed:', error.message);
426
- console.error('Cause:', error.cause);
427
- }
428
-}
429
-```
\ No newline at end of file