Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
py 531 lines 20.9 KB
Raw
1 """
2 MCP (Model Control Protocol) module for Composio SDK.
3
4 This module provides MCP server operations
5 """
6
7 from __future__ import annotations
8
9 import typing as t
10 import warnings
11
12 import typing_extensions as te
13 from composio_client import omit
14 from composio_client.types.mcp.custom_create_response import CustomCreateResponse
15
16 from composio.client import HttpClient
17 from composio.core.models.base import Resource
18 from composio.exceptions import ComposioDeprecationWarning, ValidationError
19 from composio.utils.pydantic import none_to_omit
20
21 # Data Types (matching TypeScript specification)
22
23
24 class ConfigToolkit(te.TypedDict, total=False):
25 """Toolkit configuration for an MCP server.
26
27 Defined locally rather than imported from ``composio_client``: the generated
28 client removed ``types.tool_router_create_session_params.ConfigToolkit`` in
29 1.41.0 when the tool-router session schema was redesigned. The MCP surface
30 only needs the toolkit slug and optional auth config, so we keep our own
31 minimal shape and stay decoupled from tool-router regen churn.
32 """
33
34 toolkit: te.Required[str]
35 """Toolkit identifier (e.g., gmail, slack, github)."""
36
37 auth_config_id: str
38 """Specific auth configuration ID for this toolkit."""
39
40
41 class MCPCreateResponse(CustomCreateResponse):
42 """MCP Create Response with generate method (extends CustomCreateResponse)."""
43
44 generate: t.Callable[[str, t.Optional[bool]], "MCPServerInstance"]
45
46
47 class MCPServerInstance(te.TypedDict):
48 """MCP Server Instance data structure (matching TypeScript implementation)."""
49
50 id: str
51 name: str
52 type: str
53 url: str # User-specific connection URL
54 user_id: str # Associated user ID
55 allowed_tools: t.List[str] # Available tools for the user
56 auth_configs: t.List[str] # Associated auth configurations
57
58
59 class MCPItem(te.TypedDict):
60 """Complete MCP server information."""
61
62 id: str # Unique server identifier
63 name: str # Human-readable server name
64 allowed_tools: t.List[str] # Array of enabled tool identifiers
65 auth_config_ids: t.List[str] # Array of auth configuration IDs
66 toolkits: t.List[str] # Array of toolkit names
67 commands: t.Dict[str, str] # Setup commands for different clients
68 mcp_url: str # Server connection URL
69 toolkit_icons: t.Dict[str, str] # Map of toolkit icons
70 server_instance_count: int # Number of active instances
71 created_at: te.NotRequired[t.Optional[str]]
72 updated_at: te.NotRequired[t.Optional[str]]
73
74
75 class MCPListResponse(te.TypedDict):
76 """Paginated list response."""
77
78 items: t.List[t.Any] # Array of MCP server objects (raw API response)
79 current_page: int # Current page number
80 total_pages: int # Total number of pages
81
82
83 def _add_generate_method(
84 response: CustomCreateResponse, mcp_instance: "MCP"
85 ) -> MCPCreateResponse:
86 """Add generate method to CustomCreateResponse object."""
87
88 def generate(
89 user_id: str, manually_manage_connections: t.Optional[bool] = None
90 ) -> MCPServerInstance:
91 """
92 Generate server instance for this MCP configuration.
93 Matches TypeScript server.generate(userId) method.
94
95 :param user_id: External user ID from your database
96 :param manually_manage_connections: Whether to manually manage connections (optional)
97 :return: MCP server instance
98 """
99 return mcp_instance.generate(user_id, response.id, manually_manage_connections)
100
101 # Add the generate method to the response object and cast to MCPCreateResponse
102 response.generate = generate # type: ignore
103 return t.cast(MCPCreateResponse, response)
104
105
106 # ``managed_auth_by_composio`` is deprecated upstream, but dropping it would strip
107 # the connection-management tools from generated URLs. Keep sending it and warn
108 # once per process in SDK terms. The API client still raises its own notice once
109 # per client instance: it has no per-call switch, and ``warnings.catch_warnings``
110 # would reset every module's "already shown" registry on each call.
111 _MANAGED_AUTH_DEPRECATION = (
112 "composio.mcp.generate() returns URLs that rely on the deprecated "
113 "include_composio_helper_actions query parameter, which the API will remove "
114 "in a future version. Switch to a session MCP endpoint: "
115 "composio.create(user_id, mcp=True) exposes session.mcp.url with "
116 "connection-management tools built in. "
117 "https://docs.composio.dev/docs/sessions-via-mcp"
118 )
119 _managed_auth_deprecation_warned = False
120
121
122 class MCP(Resource):
123 """
124 MCP (Model Control Protocol) class.
125 Provides enhanced MCP server operations
126
127 This matches the TypeScript ExperimentalMCP class functionality.
128
129 .. deprecated::
130 Use a session's MCP endpoint instead:
131 ``composio.create(user_id, mcp=True)`` returns a session that exposes
132 ``session.mcp.url`` / ``session.mcp.headers``. MCP is now opt-in per
133 session; this standalone ``composio.mcp`` server-management API is kept
134 only for backwards compatibility. Prefer the session MCP endpoint; do
135 not generate new code against ``composio.mcp``.
136 See https://docs.composio.dev/docs/sessions-via-mcp
137 """
138
139 def __init__(self, client: HttpClient):
140 """
141 Initialize MCP instance.
142
143 :param client: HTTP client for API calls
144 """
145 super().__init__(client)
146
147 def create(
148 self,
149 name: str,
150 toolkits: t.List[t.Union[ConfigToolkit, str]],
151 manually_manage_connections: bool = False,
152 allowed_tools: t.Optional[t.List[str]] = None,
153 ) -> MCPCreateResponse:
154 """
155 Create a new MCP server configuration with specified toolkits and authentication settings.
156
157 :param name: Unique name for the MCP configuration
158 :param toolkits: List of toolkit configurations. Can be either:
159 - MCPToolkitConfig objects with detailed configuration
160 - Strings representing toolkit names (for simple cases)
161 :param manually_manage_connections: Whether to manually manage account connections (default: False)
162 :param allowed_tools: List of specific tools to enable across all toolkits (default: None for all tools)
163 :return: Created server details with generate method
164
165 Examples:
166 >>> # Using toolkit configuration objects with auth
167 >>> server = composio.experimental.mcp.create(
168 ... 'personal-mcp-server',
169 ... toolkits=[
170 ... {
171 ... 'toolkit': 'github',
172 ... 'auth_config_id': 'ac_xyz',
173 ... },
174 ... {
175 ... 'toolkit': 'slack',
176 ... 'auth_config_id': 'ac_abc',
177 ... },
178 ... ],
179 ... allowed_tools=['GITHUB_CREATE_AN_ISSUE', 'GITHUB_LIST_REPOS', 'SLACK_SEND_MESSAGE'],
180 ... manually_manage_connections=False
181 ... )
182 >>>
183 >>> # Using simple toolkit names (most common usage)
184 >>> server = composio.experimental.mcp.create(
185 ... 'simple-mcp-server',
186 ... toolkits=['composio_search', 'text_to_pdf'],
187 ... allowed_tools=['COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH', 'TEXT_TO_PDF_CONVERT_TEXT_TO_PDF']
188 ... )
189 >>>
190 >>> # Using all tools from toolkits (default behavior)
191 >>> server = composio.experimental.mcp.create(
192 ... 'all-tools-server',
193 ... toolkits=['composio_search', 'text_to_pdf']
194 ... # allowed_tools=None means all tools from these toolkits
195 ... )
196 >>>
197 >>> # Get server instance for a user
198 >>> mcp = server.generate('user_12345')
199 """
200 if not toolkits:
201 raise ValidationError("At least one toolkit configuration is required")
202
203 try:
204 # Normalize toolkits to MCPToolkitConfig format
205 normalized_toolkit_configs: t.List[ConfigToolkit] = []
206 for toolkit in toolkits:
207 if isinstance(toolkit, str):
208 # Convert string to MCPToolkitConfig
209 normalized_toolkit_configs.append(ConfigToolkit(toolkit=toolkit))
210 else:
211 # Already MCPToolkitConfig, use as-is
212 normalized_toolkit_configs.append(toolkit)
213
214 # Extract toolkits and prepare for API call
215 toolkit_configs = normalized_toolkit_configs
216
217 # Get unique toolkits and auth config IDs
218 toolkit_names = []
219 auth_config_ids = []
220
221 for toolkit_config in toolkit_configs:
222 if (
223 "toolkit" in toolkit_config
224 and toolkit_config["toolkit"] not in toolkit_names
225 ):
226 toolkit_names.append(toolkit_config["toolkit"])
227
228 if (
229 "auth_config_id" in toolkit_config
230 and toolkit_config["auth_config_id"] not in auth_config_ids
231 ):
232 auth_config_ids.append(toolkit_config["auth_config_id"])
233
234 # Use the allowed_tools parameter instead of individual toolkit configs
235 # (`custom_tools` is the deprecated create-time alias)
236 allowed_tools_param = none_to_omit(allowed_tools)
237
238 # Use the custom MCP create endpoint
239 response = self._client.mcp.custom.create(
240 name=name,
241 toolkits=toolkit_names,
242 auth_config_ids=auth_config_ids,
243 allowed_tools=allowed_tools_param,
244 managed_auth_via_composio=not manually_manage_connections,
245 )
246
247 # Return response with generate method (matching TypeScript behavior)
248 return _add_generate_method(response, self)
249
250 except Exception as e:
251 raise ValidationError("Failed to create MCP server") from e
252
253 def list(
254 self,
255 page_no: t.Optional[int] = None,
256 limit: t.Optional[int] = None,
257 toolkits: t.Optional[str] = None,
258 auth_config_ids: t.Optional[str] = None,
259 name: t.Optional[str] = None,
260 order_by: t.Optional[te.Literal["created_at", "updated_at"]] = None,
261 order_direction: t.Optional[te.Literal["asc", "desc"]] = None,
262 ) -> MCPListResponse:
263 """
264 List MCP servers with optional filtering and pagination.
265
266 :param page_no: Page number for pagination (default: 1)
267 :param limit: Maximum items per page (default: 10)
268 :param toolkits: Filter by toolkit name (single string)
269 :param auth_config_ids: Filter by auth configuration ID (single string)
270 :param name: Filter by server name (partial match)
271 :param order_by: Order by field ('created_at' or 'updated_at')
272 :param order_direction: Order direction ('asc' or 'desc')
273 :return: Paginated list of MCP servers
274
275 Examples:
276 >>> # List all servers
277 >>> all_servers = composio.experimental.mcp.list()
278 >>>
279 >>> # List with pagination
280 >>> paged_servers = composio.experimental.mcp.list(page_no=2, limit=5)
281 >>>
282 >>> # Filter by toolkit
283 >>> github_servers = composio.experimental.mcp.list(toolkits='github', name='personal')
284 """
285
286 try:
287 # Use the MCP list endpoint with filters
288 response = self._client.mcp.list(
289 page_no=page_no,
290 limit=limit,
291 toolkits=none_to_omit(toolkits),
292 auth_config_ids=none_to_omit(auth_config_ids),
293 name=none_to_omit(name),
294 order_by=none_to_omit(order_by),
295 order_direction=none_to_omit(order_direction),
296 )
297
298 items = (
299 response.items if hasattr(response, "items") and response.items else []
300 )
301
302 return MCPListResponse(
303 items=items,
304 current_page=getattr(response, "current_page", page_no or 1),
305 total_pages=getattr(response, "total_pages", 1),
306 )
307
308 except Exception as e:
309 raise ValidationError("Failed to list MCP servers") from e
310
311 def get(self, server_id: str):
312 """
313 Retrieve detailed information about a specific MCP server/config.
314
315 :param server_id: The unique identifier of the MCP server/config
316 :return: Complete MCP server information
317
318 Example:
319 >>> server = composio.experimental.mcp.get('mcp_12345')
320 >>>
321 >>> print(server['name']) # "My Personal MCP Server"
322 >>> print(server['allowed_tools']) # ["GITHUB_CREATE_AN_ISSUE", "SLACK_SEND_MESSAGE"]
323 >>> print(server['toolkits']) # ["github", "slack"]
324 >>> print(server['server_instance_count']) # 3
325 """
326 try:
327 response = self._client.mcp.retrieve(server_id)
328
329 return response
330
331 except Exception as e:
332 raise ValidationError(f"Failed to retrieve MCP server {server_id}") from e
333
334 def update(
335 self,
336 server_id: str,
337 name: t.Optional[str] = None,
338 toolkits: t.Optional[t.List[t.Union[ConfigToolkit, str]]] = None,
339 manually_manage_connections: t.Optional[bool] = None,
340 allowed_tools: t.Optional[t.List[str]] = None,
341 ):
342 """
343 Update an existing MCP server configuration.
344
345 :param server_id: The unique identifier of the MCP server to update
346 :param name: Optional new name for the MCP server
347 :param toolkits: Optional list of toolkit configurations (strings or objects)
348 :param manually_manage_connections: Optional flag for connection management
349 :param allowed_tools: Optional list of specific tools to enable across all toolkits
350 :return: Updated MCP server information
351
352 Examples:
353 >>> # Update server name only
354 >>> updated_server = composio.experimental.mcp.update(
355 ... 'mcp_12345',
356 ... name='My Updated MCP Server'
357 ... )
358 >>>
359 >>> # Update toolkits and tools
360 >>> server_with_new_tools = composio.experimental.mcp.update(
361 ... 'mcp_12345',
362 ... toolkits=['github', 'slack'],
363 ... allowed_tools=['GITHUB_CREATE_AN_ISSUE', 'SLACK_SEND_MESSAGE']
364 ... )
365 >>>
366 >>> # Update with auth configs
367 >>> server_with_auth = composio.experimental.mcp.update(
368 ... 'mcp_12345',
369 ... toolkits=[
370 ... {'toolkit': 'github', 'auth_config_id': 'auth_abc123'},
371 ... {'toolkit': 'slack', 'auth_config_id': 'auth_def456'}
372 ... ],
373 ... allowed_tools=['GITHUB_CREATE_AN_ISSUE', 'SLACK_SEND_MESSAGE'],
374 ... manually_manage_connections=False
375 ... )
376 """
377 try:
378 update_params: t.Dict[str, t.Any] = {}
379
380 if name is not None:
381 update_params["name"] = name
382
383 if toolkits is not None:
384 # Normalize toolkits to ConfigToolkit format (same as create method)
385 normalized_toolkit_configs: t.List[ConfigToolkit] = []
386 for toolkit in toolkits:
387 if isinstance(toolkit, str):
388 # Convert string to ConfigToolkit
389 normalized_toolkit_configs.append(
390 ConfigToolkit(toolkit=toolkit)
391 )
392 else:
393 # Already ConfigToolkit, use as-is
394 normalized_toolkit_configs.append(toolkit)
395
396 # Extract toolkits and prepare for API call
397 toolkit_names = []
398 auth_config_ids = []
399
400 for toolkit_config in normalized_toolkit_configs:
401 if (
402 "toolkit" in toolkit_config
403 and toolkit_config["toolkit"] not in toolkit_names
404 ):
405 toolkit_names.append(toolkit_config["toolkit"])
406
407 if (
408 "auth_config_id" in toolkit_config
409 and toolkit_config["auth_config_id"] not in auth_config_ids
410 ):
411 auth_config_ids.append(toolkit_config["auth_config_id"])
412
413 update_params["toolkits"] = toolkit_names
414 update_params["auth_config_ids"] = auth_config_ids
415
416 if allowed_tools is not None:
417 # The update endpoint only reads `allowed_tools`; the create-time
418 # `custom_tools` alias is deprecated and ignored on PATCH.
419 update_params["allowed_tools"] = allowed_tools
420
421 if manually_manage_connections is not None:
422 update_params[
423 "managed_auth_via_composio"
424 ] = not manually_manage_connections
425
426 # Use the MCP update endpoint
427 response = self._client.mcp.update(server_id, **update_params)
428
429 return response
430
431 except Exception as e:
432 raise ValidationError(f"Failed to update MCP server {server_id}") from e
433
434 def delete(self, server_id: str) -> t.Dict[str, t.Any]:
435 """
436 Permanently delete an MCP server configuration.
437
438 :param server_id: The unique identifier of the MCP server to delete
439 :return: Deletion result
440
441 Example:
442 >>> # Delete a server
443 >>> result = composio.experimental.mcp.delete('mcp_12345')
444 >>>
445 >>> if result['deleted']:
446 ... print(f"Server {result['id']} has been successfully deleted")
447 >>> else:
448 ... print(f"Failed to delete server {result['id']}")
449 """
450 try:
451 response = self._client.mcp.delete(server_id)
452
453 return {
454 "id": server_id,
455 "deleted": getattr(response, "deleted", True),
456 }
457
458 except Exception as e:
459 raise ValidationError(f"Failed to delete MCP server {server_id}") from e
460
461 def generate(
462 self,
463 user_id: str,
464 mcp_config_id: str,
465 manually_manage_connections: t.Optional[bool] = None,
466 ) -> MCPServerInstance:
467 """
468 Get server URLs for an existing MCP server.
469
470 This matches the TypeScript implementation exactly.
471
472 :param user_id: External user ID from your database
473 :param mcp_config_id: MCP configuration ID
474 :param manually_manage_connections: Whether to manually manage connections (optional)
475 :return: MCP server instance
476
477 Example:
478 >>> mcp = composio.experimental.mcp.generate(
479 ... 'user_12345',
480 ... 'mcp_67890',
481 ... manually_manage_connections=False
482 ... )
483 >>>
484 >>> print(mcp['url']) # Server URL for the user
485 >>> print(mcp['allowed_tools']) # Available tools
486 """
487
488 try:
489 # Get server details first (matching TS: this.client.mcp.retrieve)
490 server_details = self._client.mcp.retrieve(mcp_config_id)
491
492 # Generate server URLs (matching TS: this.client.mcp.generate.url)
493 managed_auth_by_composio = not manually_manage_connections
494 global _managed_auth_deprecation_warned
495 if managed_auth_by_composio and not _managed_auth_deprecation_warned:
496 _managed_auth_deprecation_warned = True
497 # 3: past ``Resource``'s trace wrapper to the caller's line.
498 warnings.warn(
499 _MANAGED_AUTH_DEPRECATION, ComposioDeprecationWarning, stacklevel=3
500 )
501 # The API defaults the field to false, so opting out omits it and
502 # raises no client notice.
503 url_response = self._client.mcp.generate.url(
504 mcp_server_id=mcp_config_id,
505 user_ids=[user_id],
506 managed_auth_by_composio=True if managed_auth_by_composio else omit,
507 )
508
509 # Get the generated URL (matching TS: urlResponse.user_ids_url[0])
510 if hasattr(url_response, "user_ids_url") and url_response.user_ids_url:
511 server_url = url_response.user_ids_url[0]
512 else:
513 raise ValidationError("No server URL generated")
514
515 # Create structured server instance (matching TS MCPServerInstance)
516 server_instance: MCPServerInstance = {
517 "id": server_details.id,
518 "name": server_details.name,
519 "type": "streamable_http",
520 "url": server_url,
521 "user_id": user_id,
522 "allowed_tools": getattr(server_details, "allowed_tools", []),
523 "auth_configs": getattr(server_details, "auth_config_ids", []),
524 }
525
526 return server_instance
527
528 except Exception as e:
529 if isinstance(e, ValidationError):
530 raise
531 raise ValidationError("Failed to parse MCP server instance") from e