Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { Composio as ComposioClient } from '@composio/client'; |
| 2 | import { telemetry } from '../telemetry/Telemetry'; |
| 3 | import { |
| 4 | MCPConfigCreationParams, |
| 5 | MCPConfigCreationParamsSchema, |
| 6 | MCPConfigCreateResponse, |
| 7 | MCPConfigResponseSchema, |
| 8 | MCPServerInstance, |
| 9 | MCPGetInstanceParams, |
| 10 | MCPGetInstanceParamsSchema, |
| 11 | MCPListResponse, |
| 12 | MCPListParams, |
| 13 | MCPListParamsSchema, |
| 14 | MCPListResponseSchema, |
| 15 | MCPItemSchema, |
| 16 | MCPItem, |
| 17 | MCPUpdateParams, |
| 18 | MCPUpdateParamsSchema, |
| 19 | } from '../types/mcp.experimental.types'; |
| 20 | import { MCPServerInstanceSchema } from '../types/mcp.experimental.types'; |
| 21 | import { ValidationError } from '../errors/ValidationErrors'; |
| 22 | import { transform } from '../utils/transform'; |
| 23 | import type { McpRetrieveResponse, McpUpdateResponse } from '@composio/client/resources/mcp'; |
| 24 | import { ComposioRequestOptions } from '../types/requestOptions.types'; |
| 25 | import { withCancellation } from '../utils/cancellation'; |
| 26 | import logger from '../utils/logger'; |
| 27 | |
| 28 | function transformMCPItemResponse(response: McpUpdateResponse | McpRetrieveResponse): MCPItem { |
| 29 | return transform(response) |
| 30 | .with(MCPItemSchema) |
| 31 | .using(raw => ({ |
| 32 | name: raw.name, |
| 33 | allowedTools: raw.allowed_tools, |
| 34 | id: raw.id, |
| 35 | authConfigIds: raw.auth_config_ids, |
| 36 | commands: raw.commands, |
| 37 | MCPUrl: raw.mcp_url, |
| 38 | toolkitIcons: raw.toolkit_icons, |
| 39 | serverInstanceCount: raw.server_instance_count, |
| 40 | toolkits: raw.toolkits, |
| 41 | })); |
| 42 | } |
| 43 | |
| 44 | // `managed_auth_by_composio` is deprecated upstream, but dropping it would strip |
| 45 | // the connection-management tools from generated URLs. Keep sending it, silence |
| 46 | // the API client's notice (it names an internal call), and warn once per process |
| 47 | // in SDK terms instead. |
| 48 | const MANAGED_AUTH_DEPRECATION = |
| 49 | '[Deprecation] composio.mcp.generate() returns URLs that rely on the deprecated ' + |
| 50 | 'include_composio_helper_actions query parameter, which the API will remove in a ' + |
| 51 | 'future version. Switch to a session MCP endpoint: composio.create(userId, { mcp: true }) ' + |
| 52 | 'exposes session.mcp.url with connection-management tools built in. ' + |
| 53 | 'https://docs.composio.dev/docs/sessions-via-mcp'; |
| 54 | let _managedAuthDeprecationWarned = false; |
| 55 | |
| 56 | /** |
| 57 | * MCP (Model Control Protocol) class |
| 58 | * Handles MCP server operations. |
| 59 | * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`. |
| 60 | * |
| 61 | * @deprecated Use a session's MCP endpoint instead: `composio.create(userId, { mcp: true })` |
| 62 | * returns a session that exposes `session.mcp.url` / `session.mcp.headers`. MCP is now |
| 63 | * opt-in per session; the standalone `composio.mcp` server-management API is kept only for |
| 64 | * backwards compatibility. Prefer the session MCP endpoint; do not generate new code against |
| 65 | * `composio.mcp`. See https://docs.composio.dev/docs/sessions-via-mcp |
| 66 | */ |
| 67 | export class MCP { |
| 68 | client: ComposioClient; |
| 69 | |
| 70 | constructor(client: ComposioClient) { |
| 71 | this.client = client; |
| 72 | telemetry.instrument(this, 'MCP'); |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Create a new MCP configuration. |
| 77 | * @param {Object} params - Parameters for creating the MCP configuration |
| 78 | * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools |
| 79 | * @param {Object} params.options - Configuration options |
| 80 | * @param {string} params.options.name - Unique name for the MCP configuration |
| 81 | * @param {boolean} [params.options.manuallyManageConnections] - Whether to use chat-based authentication or manually connect accounts |
| 82 | * @returns {Promise<McpServerCreateResponse<T>>} Created server details with instance getter |
| 83 | * |
| 84 | * @example |
| 85 | * ```typescript |
| 86 | * const server = await composio.mcpConfig.create("personal-mcp-server", { |
| 87 | * toolkits: ["github", "slack"], |
| 88 | * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"], |
| 89 | * manuallyManageConnections: false |
| 90 | * } |
| 91 | * }); |
| 92 | * |
| 93 | * const server = await composio.mcpConfig.create("personal-mcp-server", { |
| 94 | * toolkits: [{ toolkit: "gmail", authConfigId: "ac_243434343" }], |
| 95 | * allowedTools: ["GMAIL_FETCH_EMAILS"], |
| 96 | * manuallyManageConnections: false |
| 97 | * } |
| 98 | * }); |
| 99 | * ``` |
| 100 | */ |
| 101 | async create( |
| 102 | name: string, |
| 103 | mcpConfig: MCPConfigCreationParams, |
| 104 | requestOptions?: ComposioRequestOptions |
| 105 | ): Promise<MCPConfigCreateResponse> { |
| 106 | const config = MCPConfigCreationParamsSchema.safeParse(mcpConfig); |
| 107 | if (config.error) { |
| 108 | throw new ValidationError('Invalid parameters passed to create mcp config', { |
| 109 | cause: config.error, |
| 110 | }); |
| 111 | } |
| 112 | |
| 113 | const toolkits: string[] = []; |
| 114 | const auth_config_ids: string[] = []; |
| 115 | const allowed_tools: string[] = config.data.allowedTools ?? []; |
| 116 | |
| 117 | // extract all the toolkits, authconfigs, and allowed tools to separate slugs |
| 118 | config.data.toolkits.forEach(toolkit => { |
| 119 | if (typeof toolkit === 'string') { |
| 120 | toolkits.push(toolkit); |
| 121 | } else { |
| 122 | if (toolkit.toolkit) { |
| 123 | toolkits.push(toolkit.toolkit); |
| 124 | } |
| 125 | if (toolkit.authConfigId) { |
| 126 | auth_config_ids.push(toolkit.authConfigId); |
| 127 | } |
| 128 | } |
| 129 | }); |
| 130 | |
| 131 | const createBody = { |
| 132 | name, |
| 133 | toolkits, |
| 134 | auth_config_ids, |
| 135 | allowed_tools, |
| 136 | // if manually manage account is set to true, disable composio account management tools |
| 137 | managed_auth_via_composio: config.data.manuallyManageConnections ? false : true, |
| 138 | }; |
| 139 | const server = await withCancellation( |
| 140 | () => this.client.mcp.custom.create(createBody, requestOptions), |
| 141 | requestOptions?.signal |
| 142 | ); |
| 143 | |
| 144 | const camelCaseServer = transform(server) |
| 145 | .with(MCPConfigResponseSchema) |
| 146 | .using(raw => ({ |
| 147 | name: raw.name, |
| 148 | allowedTools: raw.allowed_tools, |
| 149 | id: raw.id, |
| 150 | authConfigIds: raw.auth_config_ids, |
| 151 | commands: raw.commands, |
| 152 | MCPUrl: raw.mcp_url, |
| 153 | })); |
| 154 | |
| 155 | return { |
| 156 | ...camelCaseServer, |
| 157 | generate: async (userId: string): Promise<MCPServerInstance> => { |
| 158 | return await this.generate(userId, server.id, { |
| 159 | manuallyManageConnections: config.data.manuallyManageConnections, |
| 160 | }); |
| 161 | }, |
| 162 | }; |
| 163 | } |
| 164 | |
| 165 | /** |
| 166 | * List the MCP servers with optional filtering and pagination |
| 167 | * @param {Object} options - Filtering and pagination options |
| 168 | * @param {number} [options.page=1] - Page number for pagination (1-based) |
| 169 | * @param {number} [options.limit=10] - Maximum number of items to return per page |
| 170 | * @param {string[]} [options.toolkits=[]] - Array of toolkit names to filter by |
| 171 | * @param {string[]} [options.authConfigs=[]] - Array of auth configuration IDs to filter by |
| 172 | * @param {string} [options.name] - Filter by MCP server name (partial match) |
| 173 | * @returns {Promise<MCPListResponse>} Paginated list of MCP servers with metadata |
| 174 | * |
| 175 | * @example |
| 176 | * ```typescript |
| 177 | * // List all MCP servers |
| 178 | * const allServers = await composio.experimental.mcp.list({}); |
| 179 | * |
| 180 | * // List with pagination |
| 181 | * const pagedServers = await composio.experimental.mcp.list({ |
| 182 | * page: 2, |
| 183 | * limit: 5 |
| 184 | * }); |
| 185 | * |
| 186 | * // Filter by toolkit |
| 187 | * const githubServers = await composio.experimental.mcp.list({ |
| 188 | * toolkits: ['github', 'slack'] |
| 189 | * }); |
| 190 | * |
| 191 | * // Filter by name |
| 192 | * const namedServers = await composio.experimental.mcp.list({ |
| 193 | * name: 'personal' |
| 194 | * }); |
| 195 | * ``` |
| 196 | */ |
| 197 | async list( |
| 198 | options: MCPListParams, |
| 199 | requestOptions?: ComposioRequestOptions |
| 200 | ): Promise<MCPListResponse> { |
| 201 | const { data: params, error } = MCPListParamsSchema.safeParse(options); |
| 202 | if (error) { |
| 203 | throw new ValidationError('Failed to validate list options', { |
| 204 | cause: error, |
| 205 | }); |
| 206 | } |
| 207 | |
| 208 | const listParams = { |
| 209 | page_no: params.page, |
| 210 | limit: params.limit, |
| 211 | toolkits: params.toolkits?.length > 0 ? params.toolkits.join(',') : undefined, |
| 212 | auth_config_ids: params.authConfigs?.length > 0 ? params.authConfigs.join(',') : undefined, |
| 213 | name: params.name, |
| 214 | }; |
| 215 | const listResponse = await withCancellation( |
| 216 | () => this.client.mcp.list(listParams, requestOptions), |
| 217 | requestOptions?.signal |
| 218 | ); |
| 219 | |
| 220 | const transformedListResponse = transform(listResponse) |
| 221 | .with(MCPListResponseSchema) |
| 222 | .using(raw => ({ |
| 223 | currentPage: raw.current_page, |
| 224 | totalPages: raw.total_pages, |
| 225 | items: raw.items.map(item => ({ |
| 226 | name: item.name, |
| 227 | allowedTools: item.allowed_tools, |
| 228 | id: item.id, |
| 229 | authConfigIds: item.auth_config_ids, |
| 230 | commands: item.commands, |
| 231 | MCPUrl: item.mcp_url, |
| 232 | toolkitIcons: item.toolkit_icons, |
| 233 | serverInstanceCount: item.server_instance_count, |
| 234 | toolkits: item.toolkits, |
| 235 | })), |
| 236 | })); |
| 237 | |
| 238 | return transformedListResponse; |
| 239 | } |
| 240 | |
| 241 | /** |
| 242 | * Retrieve detailed information about a specific MCP server by its ID |
| 243 | * @param {string} serverId - The unique identifier of the MCP server to retrieve |
| 244 | * @returns {Promise<MCPItem>} Complete MCP server details including configuration, tools, and metadata |
| 245 | * |
| 246 | * @example |
| 247 | * ```typescript |
| 248 | * // Get a specific MCP server by ID |
| 249 | * const server = await composio.experimental.mcp.get("mcp_12345"); |
| 250 | * |
| 251 | * console.log(server.name); // "My Personal MCP Server" |
| 252 | * console.log(server.allowedTools); // ["GITHUB_CREATE_AN_ISSUE", "SLACK_SEND_MESSAGE"] |
| 253 | * console.log(server.toolkits); // ["github", "slack"] |
| 254 | * console.log(server.serverInstanceCount); // 3 |
| 255 | * |
| 256 | * // Access setup commands for different clients |
| 257 | * console.log(server.commands.claude); // Claude setup command |
| 258 | * console.log(server.commands.cursor); // Cursor setup command |
| 259 | * console.log(server.commands.windsurf); // Windsurf setup command |
| 260 | * |
| 261 | * // Use the MCP URL for direct connections |
| 262 | * const mcpUrl = server.MCPUrl; |
| 263 | * ``` |
| 264 | * |
| 265 | * @throws {ValidationError} When the server ID is invalid or server not found |
| 266 | */ |
| 267 | async get(serverId: string, requestOptions?: ComposioRequestOptions): Promise<MCPItem> { |
| 268 | const response = await withCancellation( |
| 269 | () => this.client.mcp.retrieve(serverId, requestOptions), |
| 270 | requestOptions?.signal |
| 271 | ); |
| 272 | return transformMCPItemResponse(response); |
| 273 | } |
| 274 | |
| 275 | /** |
| 276 | * Delete an MCP server configuration permanently |
| 277 | * @param {string} serverId - The unique identifier of the MCP server to delete |
| 278 | * @returns {Promise<{id: string; deleted: boolean}>} Confirmation object with server ID and deletion status |
| 279 | * |
| 280 | * @example |
| 281 | * ```typescript |
| 282 | * // Delete an MCP server by ID |
| 283 | * const result = await composio.experimental.mcp.delete("mcp_12345"); |
| 284 | * |
| 285 | * if (result.deleted) { |
| 286 | * console.log(`Server ${result.id} has been successfully deleted`); |
| 287 | * } else { |
| 288 | * console.log(`Failed to delete server ${result.id}`); |
| 289 | * } |
| 290 | * |
| 291 | * // Example with error handling |
| 292 | * try { |
| 293 | * const result = await composio.experimental.mcp.delete("mcp_12345"); |
| 294 | * console.log("Deletion successful:", result); |
| 295 | * } catch (error) { |
| 296 | * console.error("Failed to delete MCP server:", error.message); |
| 297 | * } |
| 298 | * |
| 299 | * // Delete and verify from list |
| 300 | * await composio.experimental.mcp.delete("mcp_12345"); |
| 301 | * const servers = await composio.experimental.mcp.list({}); |
| 302 | * const serverExists = servers.items.some(server => server.id === "mcp_12345"); |
| 303 | * console.log("Server still exists:", serverExists); // Should be false |
| 304 | * ``` |
| 305 | * |
| 306 | * @throws {ValidationError} When the server ID is invalid or server not found |
| 307 | * @throws {Error} When the server cannot be deleted due to active connections or other constraints |
| 308 | * |
| 309 | * @warning This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed. |
| 310 | */ |
| 311 | async delete( |
| 312 | serverId: string, |
| 313 | requestOptions?: ComposioRequestOptions |
| 314 | ): Promise<{ id: string; deleted: boolean }> { |
| 315 | return withCancellation( |
| 316 | () => this.client.mcp.delete(serverId, requestOptions), |
| 317 | requestOptions?.signal |
| 318 | ); |
| 319 | } |
| 320 | |
| 321 | /** |
| 322 | * Update an existing MCP server configuration with new settings |
| 323 | * @param {string} serverId - The unique identifier of the MCP server to update |
| 324 | * @param {Object} config - Update configuration parameters |
| 325 | * @param {string} [config.name] - New name for the MCP server |
| 326 | * @param {Array} [config.toolkits] - Updated toolkit configurations |
| 327 | * @param {string} [config.toolkits[].toolkit] - Toolkit identifier (e.g., "github", "slack") |
| 328 | * @param {string} [config.toolkits[].authConfigId] - Auth configuration ID for the toolkit |
| 329 | * @param {string[]} [config.toolkits[].allowedTools] - Specific tools to enable for this toolkit |
| 330 | * @param {boolean} [config.manuallyManageConnections] - Whether to manually manage account connections |
| 331 | * @returns {Promise<MCPItem>} Updated MCP server configuration with all details |
| 332 | * |
| 333 | * @example |
| 334 | * ```typescript |
| 335 | * // Update server name only |
| 336 | * const updatedServer = await composio.experimental.mcp.update("mcp_12345", { |
| 337 | * name: "My Updated MCP Server" |
| 338 | * }); |
| 339 | * |
| 340 | * // Update toolkits and tools |
| 341 | * const serverWithNewTools = await composio.experimental.mcp.update("mcp_12345", { |
| 342 | * toolkits: [ |
| 343 | * { |
| 344 | * toolkit: "github", |
| 345 | * authConfigId: "auth_abc123", |
| 346 | * allowedTools: ["GITHUB_CREATE_AN_ISSUE", "GITHUB_LIST_REPOS"] |
| 347 | * }, |
| 348 | * { |
| 349 | * toolkit: "slack", |
| 350 | * authConfigId: "auth_xyz789", |
| 351 | * allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"] |
| 352 | * } |
| 353 | * ] |
| 354 | * }); |
| 355 | * |
| 356 | * // Update connection management setting |
| 357 | * const serverWithManualAuth = await composio.experimental.mcp.update("mcp_12345", { |
| 358 | * name: "Manual Auth Server", |
| 359 | * manuallyManageConnections: true |
| 360 | * }); |
| 361 | * |
| 362 | * // Complete update example |
| 363 | * const fullyUpdatedServer = await composio.experimental.mcp.update("mcp_12345", { |
| 364 | * name: "Production MCP Server", |
| 365 | * toolkits: [ |
| 366 | * { |
| 367 | * toolkit: "gmail", |
| 368 | * authConfigId: "auth_gmail_prod", |
| 369 | * } |
| 370 | * ], |
| 371 | * allowedTools: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"] |
| 372 | * manuallyManageConnections: false |
| 373 | * }); |
| 374 | * |
| 375 | * console.log("Updated server:", fullyUpdatedServer.name); |
| 376 | * console.log("New tools:", fullyUpdatedServer.allowedTools); |
| 377 | * ``` |
| 378 | * |
| 379 | * @throws {ValidationError} When the update parameters are invalid or malformed |
| 380 | * @throws {Error} When the server ID doesn't exist or update fails |
| 381 | * |
| 382 | * @note Only provided fields will be updated. Omitted fields will retain their current values. |
| 383 | * @note When updating toolkits, the entire toolkit configuration is replaced, not merged. |
| 384 | */ |
| 385 | async update( |
| 386 | serverId: string, |
| 387 | config: MCPUpdateParams, |
| 388 | requestOptions?: ComposioRequestOptions |
| 389 | ): Promise<MCPItem> { |
| 390 | const { data: params, error } = MCPUpdateParamsSchema.safeParse(config); |
| 391 | if (error) { |
| 392 | throw new ValidationError('Failed to validate update params', { |
| 393 | cause: error, |
| 394 | }); |
| 395 | } |
| 396 | |
| 397 | const toolkits: string[] = []; |
| 398 | const auth_config_ids: string[] = []; |
| 399 | |
| 400 | // extract all the toolkits, authconfigs, and allowed tools to separate slugs |
| 401 | params.toolkits?.forEach(toolkit => { |
| 402 | if (typeof toolkit === 'string') { |
| 403 | toolkits.push(toolkit); |
| 404 | } else { |
| 405 | if (toolkit.toolkit) { |
| 406 | toolkits.push(toolkit.toolkit); |
| 407 | } |
| 408 | if (toolkit.authConfigId) { |
| 409 | auth_config_ids.push(toolkit.authConfigId); |
| 410 | } |
| 411 | } |
| 412 | }); |
| 413 | |
| 414 | // Build a sparse PATCH body: only fields the caller provided are sent, so omitted |
| 415 | // fields keep their current server-side values. `allowed_tools` is sent whenever it |
| 416 | // is provided, independently of `toolkits` (tool-only updates are valid), and must |
| 417 | // use the API field `allowed_tools` — the update endpoint does not read the |
| 418 | // deprecated create-only alias `custom_tools`. `manuallyManageConnections` is |
| 419 | // inverted into `managed_auth_via_composio`, matching create() and generate(). |
| 420 | const updateBody = { |
| 421 | ...(params.name !== undefined ? { name: params.name } : {}), |
| 422 | ...(params.toolkits !== undefined |
| 423 | ? { |
| 424 | toolkits: toolkits, |
| 425 | auth_config_ids: auth_config_ids, |
| 426 | } |
| 427 | : {}), |
| 428 | ...(params.allowedTools !== undefined ? { allowed_tools: params.allowedTools } : {}), |
| 429 | ...(params.manuallyManageConnections !== undefined |
| 430 | ? { managed_auth_via_composio: !params.manuallyManageConnections } |
| 431 | : {}), |
| 432 | }; |
| 433 | const response = await withCancellation( |
| 434 | () => this.client.mcp.update(serverId, updateBody, requestOptions), |
| 435 | requestOptions?.signal |
| 436 | ); |
| 437 | return transformMCPItemResponse(response); |
| 438 | } |
| 439 | |
| 440 | /** |
| 441 | * Get server URLs for an existing MCP server. |
| 442 | * The response is wrapped according to the provider's specifications. |
| 443 | * |
| 444 | * @example |
| 445 | * ```typescript |
| 446 | * import { Composio } from "@composio/code"; |
| 447 | * |
| 448 | * const composio = new Composio(); |
| 449 | * const mcp = await composio.experimental.mcp.generate("default", "<mcp_config_id>"); |
| 450 | * ``` |
| 451 | * |
| 452 | * @param userId {string} external user id from your database for whom you want the server for |
| 453 | * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for |
| 454 | * @param options {object} additional options |
| 455 | * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server |
| 456 | */ |
| 457 | async generate( |
| 458 | userId: string, |
| 459 | mcpConfigId: string, |
| 460 | options?: MCPGetInstanceParams, |
| 461 | requestOptions?: ComposioRequestOptions |
| 462 | ): Promise<MCPServerInstance> { |
| 463 | const server = await withCancellation( |
| 464 | () => this.client.mcp.retrieve(mcpConfigId, requestOptions), |
| 465 | requestOptions?.signal |
| 466 | ); |
| 467 | const params = MCPGetInstanceParamsSchema.safeParse( |
| 468 | options ?? { manuallyManageConnections: false } |
| 469 | ); |
| 470 | if (params.error) { |
| 471 | throw new ValidationError('Invalid params passed for Get Instance Params', { |
| 472 | cause: params.error, |
| 473 | }); |
| 474 | } |
| 475 | |
| 476 | const urlBody = { |
| 477 | mcp_server_id: mcpConfigId, |
| 478 | user_ids: [userId], |
| 479 | managed_auth_by_composio: options?.manuallyManageConnections ? false : true, |
| 480 | }; |
| 481 | if (urlBody.managed_auth_by_composio && !_managedAuthDeprecationWarned) { |
| 482 | _managedAuthDeprecationWarned = true; |
| 483 | logger.warn(MANAGED_AUTH_DEPRECATION); |
| 484 | } |
| 485 | const urlResponse = await withCancellation( |
| 486 | () => |
| 487 | this.client.withOptions({ logLevel: 'error' }).mcp.generate.url(urlBody, requestOptions), |
| 488 | requestOptions?.signal |
| 489 | ); |
| 490 | |
| 491 | const userIdsURL = urlResponse.user_ids_url[0]; |
| 492 | const serverInstance = MCPServerInstanceSchema.safeParse({ |
| 493 | id: server.id, |
| 494 | name: server.name, |
| 495 | type: 'streamable_http' as const, |
| 496 | url: userIdsURL, |
| 497 | userId: userId, |
| 498 | allowedTools: server.allowed_tools, |
| 499 | authConfigs: server.auth_config_ids, |
| 500 | }); |
| 501 | |
| 502 | if (serverInstance.error) { |
| 503 | throw new ValidationError('Failed to parse MCP server instance', { |
| 504 | cause: serverInstance.error, |
| 505 | }); |
| 506 | } |
| 507 | |
| 508 | return serverInstance.data; |
| 509 | } |
| 510 | } |