@devries-cameron20 / composio Mirror · read-only / commits / c7e121706
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 15:45 UTC

Fix. Use dedicated tools endpoint for tool router (#2368)

Musthaq Ahamad committed Jan 12, 2026 at 20:37 UTC c7e121706f1e1e477ea8d5c5f06e53218ad339bb
48 files changed +1482 -2048
.changeset/angry-foxes-wear.md new
+15
@@ -0,0 +1,15 @@
1 +---
2 +'@composio/core': minor
3 +'@composio/anthropic': minor
4 +'@composio/claude-agent-sdk': minor
5 +'@composio/cloudflare': minor
6 +'@composio/google': minor
7 +'@composio/langchain': minor
8 +'@composio/llamaindex': minor
9 +'@composio/mastra': minor
10 +'@composio/openai': minor
11 +'@composio/openai-agents': minor
12 +'@composio/vercel': minor
13 +---
14 +
15 +Add support for dedicated tools for tool router
fern/pages/src/changelog/01-12-26-tool-router-improvements.md new
+127
@@ -0,0 +1,127 @@
1 +# Tool Router Improvements and New Features
2 +
3 +## Version Information
4 +
5 +### TypeScript/JavaScript
6 +- Package: `@composio/core` and provider packages
7 +- Version: `0.3.4` to `0.4.0`
8 +
9 +### Python
10 +- Package: `composio-core` and provider packages
11 +- Version: `0.10.4` to `0.10.5`
12 +
13 +## New Features
14 +
15 +### 1. Wait for Connections Property
16 +
17 +Added `waitForConnections` (TypeScript) / `wait_for_connections` (Python) property to manage connections configuration. This allows tool router sessions to wait for users to complete authentication before proceeding to the next step.
18 +
19 +**TypeScript:**
20 +```typescript
21 +const session = await composio.toolRouter.create(userId, {
22 + manageConnections: {
23 + enable: true,
24 + callbackUrl: 'https://example.com/callback',
25 + waitForConnections: true // NEW
26 + }
27 +});
28 +```
29 +
30 +**Python:**
31 +```python
32 +session = tool_router.create(
33 + user_id="user_123",
34 + manage_connections={
35 + "enable": True,
36 + "callback_url": "https://example.com/callback",
37 + "wait_for_connections": True # NEW
38 + }
39 +)
40 +```
41 +
42 +### 2. Session-Specific Modifier Types
43 +
44 +Introduced new modifier types for better session-based tool execution: `SessionExecuteMetaModifiers` and `SessionMetaToolOptions`.
45 +
46 +**TypeScript:**
47 +```typescript
48 +const tools = await session.tools({
49 + modifySchema: ({ toolSlug, toolkitSlug, schema }) => schema,
50 + beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => params,
51 + afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => result
52 +});
53 +```
54 +
55 +**Python:**
56 +```python
57 +from composio.core.models import before_execute_meta, after_execute_meta
58 +
59 +@before_execute_meta
60 +def before_modifier(tool, toolkit, session_id, params):
61 + return params
62 +
63 +@after_execute_meta
64 +def after_modifier(tool, toolkit, session_id, response):
65 + return response
66 +
67 +tools = session.tools(modifiers=[before_modifier, after_modifier])
68 +```
69 +
70 +### 3. Dedicated Method for Tool Router Meta Tools
71 +
72 +Added `getRawToolRouterMetaTools` (TypeScript) / `get_raw_tool_router_meta_tools` (Python) method in the Tools class for fetching meta tools directly from a tool router session.
73 +
74 +**TypeScript:**
75 +```typescript
76 +const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123', {
77 + modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
78 + // Customize schema
79 + return schema;
80 + }
81 +});
82 +```
83 +
84 +**Python:**
85 +```python
86 +meta_tools = tools_model.get_raw_tool_router_meta_tools(
87 + session_id="session_123",
88 + modifiers=[schema_modifier]
89 +)
90 +```
91 +
92 +## Internal Improvements
93 +
94 +### 1. Performance Optimization
95 +
96 +Eliminated unnecessary tool fetching during tool router execution, resulting in faster tool execution with fewer API calls.
97 +
98 +### 2. Improved Architecture
99 +
100 +Tool router sessions now fetch tools directly from the session API endpoint instead of using tool slugs, providing better consistency and reliability.
101 +
102 +### 3. Simplified Implementation
103 +
104 +Removed redundant tool schema fetching in execution paths, using a hardcoded 'composio' toolkit slug for meta tools.
105 +
106 +## Backward Compatibility
107 +
108 +This release is fully backward compatible:
109 +
110 +- All existing code continues to work without modifications
111 +- New properties are optional with sensible defaults
112 +- New modifier types can be adopted incrementally
113 +- Internal changes have no impact on public APIs
114 +- No migration required
115 +
116 +## Impact Summary
117 +
118 +| Change | Runtime Breaking | TypeScript Breaking | Migration Required |
119 +|--------|------------------|---------------------|-------------------|
120 +| `wait_for_connections` property | No | No | No |
121 +| Session-specific modifiers | No | No | No |
122 +| `getRawToolRouterMetaTools` method | No | No | No |
123 +| Tool router uses session API | No | No | No |
124 +| Optimized tool execution | No | No | No |
125 +
126 +All changes follow semantic versioning principles and maintain full backward compatibility.
127 +
fern/pyproject.toml
+1 -1
@@ -10,7 +10,7 @@ dependencies = [
10 "click>=8.1.7",
11 "ruamel-yaml>=0.18.10",
12 "typing-extensions>=4.13.0",
13 - "composio-client==1.22.0",
13 + "composio-client==1.25.0",
14 "openai>=1.79.0",
15 "composio==1.0.0rc5",
16 # Dependencies for SDK doc generation
pnpm-lock.yaml
+7 -7
@@ -13,8 +13,8 @@ catalogs:
13 specifier: ^4.20250917.0
14 version: 4.20250917.0
15 '@composio/client':
16 - specifier: 0.1.0-alpha.52
17 - version: 0.1.0-alpha.52
16 + specifier: 0.1.0-alpha.54
17 + version: 0.1.0-alpha.54
18 '@modelcontextprotocol/sdk':
19 specifier: ^1.24.0
20 version: 1.24.1
@@ -827,7 +827,7 @@ importers:
827 version: 1.0.0-alpha.1
828 '@composio/client':
829 specifier: 'catalog:'
830 - version: 0.1.0-alpha.52
830 + version: 0.1.0-alpha.54
831 '@composio/core':
832 specifier: workspace:*
833 version: link:../core
@@ -921,7 +921,7 @@ importers:
921 dependencies:
922 '@composio/client':
923 specifier: 'catalog:'
924 - version: 0.1.0-alpha.52
924 + version: 0.1.0-alpha.54
925 '@composio/json-schema-to-zod':
926 specifier: workspace:*
927 version: link:../json-schema-to-zod
@@ -1654,8 +1654,8 @@ packages:
1654 '@cloudflare/workers-types@4.20250917.0':
1655 resolution: {integrity: sha512-Lsn9dZoRYZZCXXHZNa50cMP8kWhQZG9M7WjxNSiXFzC8bk4Wh/0SYYo4YINxEjEt6h2o69LmAhFaJ+qgaJTh8Q==}
1656
1657 - '@composio/client@0.1.0-alpha.52':
1658 - resolution: {integrity: sha512-IFPa77R/v4JUX0QeRHRTEkJCBZ+OqMQBh1rIn4Nv5PIP1eP3sZqxlTYJUKPS4qLNnwBJRD+Vn7/jUs5J7pdv5g==}
1657 + '@composio/client@0.1.0-alpha.54':
1658 + resolution: {integrity: sha512-3whr4XjaMQUTcxmkaePMPeISUEE3NDRmGaf6lHReS9M2t6jiQbuZT3OktBvvw9QHrH+AZPXgaDoH65Hlr4qGWA==}
1659
1660 '@composio/mcp@1.0.3-0':
1661 resolution: {integrity: sha512-IpbfST0SSs/CEv+PIf6+EL0feNuJhQyUrOHJLPge8NhyLLrCyVqvujRIPyRUUjy0NDsked/Mm5VpJmYM6OACbg==}
@@ -8563,7 +8563,7 @@ snapshots:
8563
8564 '@cloudflare/workers-types@4.20250917.0': {}
8565
8566 - '@composio/client@0.1.0-alpha.52': {}
8566 + '@composio/client@0.1.0-alpha.54': {}
8567
8568 '@composio/mcp@1.0.3-0': {}
8569
pnpm-workspace.yaml
+1 -1
@@ -15,7 +15,7 @@ packages:
15 catalog:
16 '@cloudflare/vitest-pool-workers': ^0.9.2
17 '@cloudflare/workers-types': ^4.20250917.0
18 - '@composio/client': 0.1.0-alpha.52
18 + '@composio/client': 0.1.0-alpha.54
19 '@modelcontextprotocol/sdk': ^1.24.0
20 ai: ^6.0.3
21 openai: ^5.20.3
python/composio/core/models/_modifiers.py
+212 -9
@@ -74,8 +74,20 @@ SchemaModifierL: t.TypeAlias = t.Literal["schema"]
74 class Modifier:
75 def __init__(
76 self,
77 - modifier: t.Optional[AfterExecute | BeforeExecute | SchemaModifier],
78 - type_: AfterExecuteModifierL | BeforeExecuteModifierL | SchemaModifierL,
77 + modifier: t.Optional[
78 + AfterExecute
79 + | BeforeExecute
80 + | SchemaModifier
81 + | BeforeExecuteMeta
82 + | AfterExecuteMeta
83 + ],
84 + type_: (
85 + AfterExecuteModifierL
86 + | BeforeExecuteModifierL
87 + | SchemaModifierL
88 + | AfterExecuteMetaModifierL
89 + | BeforeExecuteMetaModifierL
90 + ),
91 tools: t.List[str],
92 toolkits: t.List[str],
93 ) -> None:
@@ -234,6 +246,84 @@ def schema_modifier(
246 raise ValueError("Either tools or toolkits must be provided")
247
248
249 +@t.overload
250 +def before_execute_meta(modifier: t.Optional[BeforeExecuteMeta]) -> Modifier: ...
251 +
252 +
253 +@t.overload
254 +def before_execute_meta(
255 + *,
256 + tools: t.Optional[t.List[str]] = None,
257 + toolkits: t.Optional[t.List[str]] = None,
258 +) -> t.Callable[[BeforeExecuteMeta], Modifier]: ...
259 +
260 +
261 +def before_execute_meta(
262 + modifier: t.Optional[BeforeExecuteMeta] = None,
263 + *,
264 + tools: t.Optional[t.List[str]] = None,
265 + toolkits: t.Optional[t.List[str]] = None,
266 +) -> Modifier | t.Callable[[BeforeExecuteMeta], Modifier]:
267 + if modifier is not None:
268 + return Modifier(
269 + modifier=modifier,
270 + type_="before_execute_meta",
271 + tools=tools or [],
272 + toolkits=toolkits or [],
273 + )
274 +
275 + if tools is not None or toolkits is not None:
276 + return t.cast(
277 + t.Callable[[BeforeExecuteMeta], Modifier],
278 + functools.partial(
279 + before_execute_meta,
280 + tools=tools or [],
281 + toolkits=toolkits or [],
282 + ),
283 + )
284 +
285 + raise ValueError("Either tools or toolkits must be provided")
286 +
287 +
288 +@t.overload
289 +def after_execute_meta(modifier: t.Optional[AfterExecuteMeta]) -> Modifier: ...
290 +
291 +
292 +@t.overload
293 +def after_execute_meta(
294 + *,
295 + tools: t.Optional[t.List[str]] = None,
296 + toolkits: t.Optional[t.List[str]] = None,
297 +) -> t.Callable[[AfterExecuteMeta], Modifier]: ...
298 +
299 +
300 +def after_execute_meta(
301 + modifier: t.Optional[AfterExecuteMeta] = None,
302 + *,
303 + tools: t.Optional[t.List[str]] = None,
304 + toolkits: t.Optional[t.List[str]] = None,
305 +) -> Modifier | t.Callable[[AfterExecuteMeta], Modifier]:
306 + if modifier is not None:
307 + return Modifier(
308 + modifier=modifier,
309 + type_="after_execute_meta",
310 + tools=tools or [],
311 + toolkits=toolkits or [],
312 + )
313 +
314 + if tools is not None or toolkits is not None:
315 + return t.cast(
316 + t.Callable[[AfterExecuteMeta], Modifier],
317 + functools.partial(
318 + after_execute_meta,
319 + tools=tools or [],
320 + toolkits=toolkits or [],
321 + ),
322 + )
323 +
324 + raise ValueError("Either tools or toolkits must be provided")
325 +
326 +
327 Modifiers = t.List[Modifier]
328
329
@@ -270,29 +360,142 @@ def apply_modifier_by_type(
360 ) -> "Tool": ...
361
362
363 +@t.overload
364 +def apply_modifier_by_type(
365 + modifiers: Modifiers,
366 + toolkit: str,
367 + tool: str,
368 + *,
369 + type: BeforeExecuteMetaModifierL,
370 + session_id: str,
371 + params: t.Dict[str, t.Any],
372 +) -> t.Dict[str, t.Any]: ...
373 +
374 +
375 +@t.overload
376 +def apply_modifier_by_type(
377 + modifiers: Modifiers,
378 + toolkit: str,
379 + tool: str,
380 + *,
381 + type: AfterExecuteMetaModifierL,
382 + session_id: str,
383 + response: "ToolExecutionResponse",
384 +) -> "ToolExecutionResponse": ...
385 +
386 +
387 def apply_modifier_by_type(
388 modifiers: Modifiers,
389 toolkit: str,
390 tool: str,
391 *,
278 - type: t.Literal["before_execute", "after_execute", "schema"],
392 + type: t.Literal[
393 + "before_execute",
394 + "after_execute",
395 + "schema",
396 + "before_execute_meta",
397 + "after_execute_meta",
398 + ],
399 schema: t.Optional["Tool"] = None,
400 request: t.Optional["ToolExecuteParams"] = None,
401 response: t.Optional["ToolExecutionResponse"] = None,
282 -) -> ModifierInOut:
402 + session_id: t.Optional[str] = None,
403 + params: t.Optional[t.Dict[str, t.Any]] = None,
404 +) -> t.Union[ModifierInOut, t.Dict[str, t.Any]]:
405 """Apply a modifier to a tool."""
284 - data = schema or request or response
285 - if data is None:
406 + # For meta modifiers, we handle them differently
407 + if type in ("before_execute_meta", "after_execute_meta"):
408 + if session_id is None:
409 + raise ValueError("session_id is required for meta modifiers")
410 +
411 + if type == "before_execute_meta":
412 + if params is None:
413 + raise ValueError("params is required for before_execute_meta")
414 + result_params: t.Dict[str, t.Any] = params
415 + for modifier in modifiers:
416 + if modifier.type == type:
417 + # Check if modifier should be applied
418 + should_apply = (
419 + (len(modifier.tools) == 0 and len(modifier.toolkits) == 0)
420 + or tool in modifier.tools
421 + or toolkit in modifier.toolkits
422 + )
423 +
424 + if should_apply and modifier.modifier is not None:
425 + result_params = t.cast(BeforeExecuteMeta, modifier.modifier)(
426 + tool, toolkit, session_id, result_params
427 + )
428 + return result_params
429 + else: # after_execute_meta
430 + if response is None:
431 + raise ValueError("response is required for after_execute_meta")
432 + result_response: "ToolExecutionResponse" = response
433 + for modifier in modifiers:
434 + if modifier.type == type:
435 + # Check if modifier should be applied
436 + should_apply = (
437 + (len(modifier.tools) == 0 and len(modifier.toolkits) == 0)
438 + or tool in modifier.tools
439 + or toolkit in modifier.toolkits
440 + )
441 +
442 + if should_apply and modifier.modifier is not None:
443 + result_response = t.cast(AfterExecuteMeta, modifier.modifier)(
444 + tool, toolkit, session_id, result_response
445 + )
446 + return result_response
447 +
448 + # For regular modifiers
449 + result: ModifierInOut
450 + if schema is not None:
451 + result = schema
452 + elif request is not None:
453 + result = request
454 + elif response is not None:
455 + result = response
456 + else:
457 raise ValueError("No data provided")
458
459 for modifier in modifiers:
289 - data = modifier.apply(
460 + result = modifier.apply(
461 toolkit=toolkit,
462 tool=tool,
292 - data=data,
463 + data=result,
464 modifer_type=type,
465 )
295 - return data
466 + return result
467 +
468 +
469 +class BeforeExecuteMeta(t.Protocol):
470 + """
471 + A modifier that is called before the meta tool is executed in a session context.
472 + """
473 +
474 + def __call__(
475 + self,
476 + tool: str,
477 + toolkit: str,
478 + session_id: str,
479 + params: t.Dict[str, t.Any],
480 + ) -> t.Dict[str, t.Any]: ...
481 +
482 +
483 +class AfterExecuteMeta(t.Protocol):
484 + """
485 + A modifier that is called after the meta tool is executed in a session context.
486 + """
487 +
488 + def __call__(
489 + self,
490 + tool: str,
491 + toolkit: str,
492 + session_id: str,
493 + response: ToolExecutionResponse,
494 + ) -> ToolExecutionResponse: ...
495 +
496 +
497 +AfterExecuteMetaModifierL: t.TypeAlias = t.Literal["after_execute_meta"]
498 +BeforeExecuteMetaModifierL: t.TypeAlias = t.Literal["before_execute_meta"]
499
500
501 class ToolOptions(te.TypedDict):
python/composio/core/models/tool_router.py
+37 -37
@@ -162,10 +162,15 @@ class ToolRouterManageConnectionsConfig(te.TypedDict, total=False):
162 enable: Whether to use tools to manage connections. Defaults to True.
163 If False, you need to manage connections manually.
164 callback_url: Optional callback URL to use for OAuth redirects.
165 + wait_for_connections: Whether to wait for users to finish authenticating
166 + connections before proceeding to the next step. Defaults to False.
167 + If set to True, a wait for connections tool call will happen and
168 + finish when the connections are ready.
169 """
170
171 enable: bool
172 callback_url: str
173 + wait_for_connections: bool
174
175
176 @dataclass
@@ -559,17 +564,15 @@ class ToolRouter(Resource, t.Generic[TProvider]):
564 def _create_tools_fn(
565 self,
566 session_id: str,
562 - tool_slugs: t.Sequence[str],
567 ) -> ToolsFn:
568 """
569 Create a tools function that wraps tools for the provider.
570
571 :param session_id: The session ID
568 - :param tool_slugs: List of tool slugs to wrap
572 + :param tool_slugs: List of tool slugs to wrap (not used anymore, kept for backward compatibility)
573 :return: Function that returns provider-wrapped tools
574 """
571 - from composio.core.models._modifiers import apply_modifier_by_type
572 - from composio.core.models.tools import Tool, Tools as ToolsModel
575 + from composio.core.models.tools import Tools as ToolsModel
576 from composio.core.provider import AgenticProvider, NonAgenticProvider
577
578 if self._provider is None:
@@ -628,10 +631,14 @@ class ToolRouter(Resource, t.Generic[TProvider]):
631 )
632
633 # With custom modifiers
631 - tools = session.tools(modifiers={
632 - 'pre_execute': lambda tool, args: print(f"Executing {tool}"),
633 - 'post_execute': lambda tool, result: print(f"Result: {result}"),
634 - })
634 + from composio.core.models import schema_modifier
635 +
636 + @schema_modifier
637 + def modify_schema(tool: str, toolkit: str, schema):
638 + print(f"Executing {tool} from {toolkit}")
639 + return schema
640 +
641 + tools = session.tools(modifiers=[modify_schema])
642 ```
643
644 Note:
@@ -639,22 +646,13 @@ class ToolRouter(Resource, t.Generic[TProvider]):
646 only the tools enabled for this session based on the configuration
647 provided during session creation.
648 """
642 - # Get raw tool schemas
643 - router_tools = tools_model.get_raw_composio_tools(tools=list(tool_slugs))
644 -
645 - # Apply schema modifiers
646 - if modifiers is not None:
647 - type_schema: t.Literal["schema"] = "schema"
648 - router_tools = [
649 - apply_modifier_by_type(
650 - modifiers=modifiers,
651 - toolkit=tool.toolkit.slug if tool.toolkit else "unknown",
652 - tool=tool.slug,
653 - type=type_schema,
654 - schema=t.cast(Tool, tool),
655 - )
656 - for tool in router_tools
657 - ]
649 +
650 + # Get raw meta tools from the session (instead of using tool_slugs)
651 + # This fetches tools directly from the tool router session
652 + router_tools = tools_model.get_raw_tool_router_meta_tools(
653 + session_id=session_id,
654 + modifiers=modifiers,
655 + )
656
657 # Always enhance schema descriptions (type hints and required notes)
658 for tool in router_tools:
@@ -664,15 +662,6 @@ class ToolRouter(Resource, t.Generic[TProvider]):
662 )
663 )
664
667 - # Process file uploadable schemas
668 - if self._auto_upload_download_files:
669 - for tool in router_tools:
670 - tool.input_parameters = (
671 - tools_model._file_helper.process_file_uploadable_schema(
672 - schema=tool.input_parameters,
673 - )
674 - )
675 -
665 # Wrap tools with provider
666 if issubclass(type(self._provider), NonAgenticProvider):
667 return t.cast(NonAgenticProvider, self._provider).wrap_tools(
@@ -794,7 +783,10 @@ class ToolRouter(Resource, t.Generic[TProvider]):
783 connections. Defaults to True.
784 - 'callback_url' (str, optional): Callback URL for
785 OAuth redirects.
797 - Example: {'enable': True, 'callback_url': 'https://example.com/callback'}
786 + - 'wait_for_connections' (bool, optional): Whether to wait
787 + for users to finish authenticating connections before
788 + proceeding to the next step. Defaults to False.
789 + Example: {'enable': True, 'callback_url': 'https://example.com/callback', 'wait_for_connections': True}
790 :param auth_configs: Optional mapping of toolkit slug to auth config ID.
791 Example: {'github': 'ac_xxx', 'slack': 'ac_yyy'}
792 :param connected_accounts: Optional mapping of toolkit slug to connected account ID.
@@ -859,6 +851,7 @@ class ToolRouter(Resource, t.Generic[TProvider]):
851 manage_connections={
852 'enable': True,
853 'callback_url': 'https://example.com/callback',
854 + 'wait_for_connections': True,
855 }
856 )
857
@@ -933,12 +926,17 @@ class ToolRouter(Resource, t.Generic[TProvider]):
926 transformed_config["tags"] = transformed_tags
927 tools_payload[toolkit_slug] = transformed_config
928
936 - # Parse callback_uri
929 + # Parse callback_url and wait_for_connections from manage_connections config
930 callback_url = (
931 manage_connections.get("callback_url")
932 if isinstance(manage_connections, dict)
933 else omit
934 )
935 + wait_for_connections = (
936 + manage_connections.get("wait_for_connections")
937 + if isinstance(manage_connections, dict)
938 + else omit
939 + )
940
941 # Build the API payload
942 create_params: t.Dict[str, t.Any] = {
@@ -951,6 +949,8 @@ class ToolRouter(Resource, t.Generic[TProvider]):
949 }
950 if callback_url is not None and callback_url is not omit:
951 connections_config["callback_url"] = callback_url
952 + if wait_for_connections is not None and wait_for_connections is not omit:
953 + connections_config["enable_wait_for_connections"] = wait_for_connections
954
955 create_params["manage_connections"] = connections_config
956
@@ -996,7 +996,7 @@ class ToolRouter(Resource, t.Generic[TProvider]):
996 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
997 url=session.mcp.url,
998 ),
999 - tools=self._create_tools_fn(session.session_id, session.tool_router_tools),
999 + tools=self._create_tools_fn(session.session_id),
1000 authorize=self._create_authorize_fn(session.session_id),
1001 toolkits=self._create_toolkits_fn(session.session_id),
1002 )
@@ -1034,7 +1034,7 @@ class ToolRouter(Resource, t.Generic[TProvider]):
1034 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
1035 url=session.mcp.url,
1036 ),
1037 - tools=self._create_tools_fn(session.session_id, session.tool_router_tools),
1037 + tools=self._create_tools_fn(session.session_id),
1038 authorize=self._create_authorize_fn(session.session_id),
1039 toolkits=self._create_toolkits_fn(session.session_id),
1040 )
python/composio/core/models/tools.py
+70 -6
@@ -162,6 +162,73 @@ class Tools(Resource, t.Generic[TProvider]):
162 )
163 return tools_list
164
165 + def get_raw_tool_router_meta_tools(
166 + self,
167 + session_id: str,
168 + modifiers: t.Optional["Modifiers"] = None,
169 + ) -> list[Tool]:
170 + """
171 + Fetches the meta tools for a tool router session.
172 +
173 + This method fetches the meta tools from the Composio API and transforms them to
174 + the expected format. It provides access to the underlying meta tool data without
175 + provider-specific wrapping.
176 +
177 + :param session_id: The session ID to get the meta tools for
178 + :param modifiers: Optional modifiers to apply to the tool schemas
179 + :return: The list of meta tools
180 +
181 + Example:
182 + ```python
183 + from composio import Composio
184 +
185 + composio = Composio()
186 + tools_model = composio.tools
187 +
188 + # Get meta tools for a session
189 + meta_tools = tools_model.get_raw_tool_router_meta_tools("session_123")
190 + print(meta_tools)
191 +
192 + # Get meta tools with schema modifiers
193 + from composio.core.models import schema_modifier
194 +
195 + @schema_modifier
196 + def modify_schema(tool: str, toolkit: str, schema):
197 + # Customize the schema
198 + schema.description = f"Modified: {schema.description}"
199 + return schema
200 +
201 + meta_tools = tools_model.get_raw_tool_router_meta_tools(
202 + "session_123",
203 + modifiers=[modify_schema]
204 + )
205 + ```
206 + """
207 + # Fetch meta tools from the API
208 + tools_response = self._client.tool_router.session.tools(session_id=session_id)
209 + # Cast to Tool type - session.tools returns compatible Item type from different response schema
210 + tools_list: t.List[Tool] = [t.cast(Tool, item) for item in tools_response.items]
211 +
212 + # Apply schema modifiers if provided
213 + if modifiers is not None:
214 + from composio.core.models._modifiers import apply_modifier_by_type
215 +
216 + tools_list = [
217 + t.cast(
218 + Tool,
219 + apply_modifier_by_type(
220 + modifiers=modifiers,
221 + toolkit=tool.toolkit.slug,
222 + tool=tool.slug,
223 + type="schema",
224 + schema=tool,
225 + ),
226 + )
227 + for tool in tools_list
228 + ]
229 +
230 + return tools_list
231 +
232 def _get(
233 self,
234 user_id: str,
@@ -352,10 +419,8 @@ class Tools(Resource, t.Generic[TProvider]):
419 :param arguments: The tool arguments
420 :return: Tool execution response
421 """
355 - # Get tool schema for modifiers
356 - tool = self.get_raw_composio_tool_by_slug(slug)
357 -
422 # Apply before_execute modifiers
423 + # Meta tools are always from the 'composio' toolkit
424 processed_arguments = arguments
425 if modifiers is not None:
426 params: ToolExecuteParams = {
@@ -364,7 +429,7 @@ class Tools(Resource, t.Generic[TProvider]):
429 type_before: t.Literal["before_execute"] = "before_execute"
430 modified_params = apply_modifier_by_type(
431 modifiers=modifiers,
367 - toolkit=tool.toolkit.slug if tool.toolkit else "unknown",
432 + toolkit="composio",
433 tool=slug,
434 type=type_before,
435 request=params,
@@ -392,7 +457,7 @@ class Tools(Resource, t.Generic[TProvider]):
457 type_after: t.Literal["after_execute"] = "after_execute"
458 result = apply_modifier_by_type(
459 modifiers=modifiers,
395 - toolkit=tool.toolkit.slug if tool.toolkit else "unknown",
460 + toolkit="composio",
461 tool=slug,
462 type=type_after,
463 response=result,
@@ -644,7 +709,6 @@ __all__ = [
709 "ToolExecuteParams",
710 "ToolExecutionResponse",
711 "Modifiers",
647 - "Modifiers",
712 "after_execute",
713 "before_execute",
714 "schema_modifier",
python/providers/anthropic/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-anthropic"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get an array of tools with your Anthropic LLMs."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/anthropic/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_anthropic",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Anthropic LLMs.",
python/providers/autogen/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-autogen"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get an array of tools with your autogen agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/autogen/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_autogen",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Autogen agent.",
python/providers/claude_agent_sdk/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-claude-agent-sdk"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get an array of tools with Claude Code Agents SDK."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/claude_agent_sdk/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
8
9 setup(
10 name="composio_claude_agent_sdk",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools for Claude Agent SDK",
python/providers/crewai/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-crewai"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get an array of tools with your CrewAI agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/crewai/setup.py
+1 -1
@@ -6,7 +6,7 @@ from setuptools import setup
6
7 setup(
8 name="composio_crewai",
9 - version="0.10.4",
9 + version="0.10.5",
10 author="Composio",
11 author_email="tech@composio.dev",
12 description="Use Composio to get an array of tools with your CrewAI agent.",
python/providers/gemini/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-gemini"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get an array of tools with your Gemini agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/gemini/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_gemini",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Gemini agent.",
python/providers/google/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-google"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/google/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_google",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
python/providers/google_adk/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-google-adk"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/google_adk/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_google_adk",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
python/providers/langchain/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-langchain"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get an array of tools with your Langchain agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/langchain/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_langchain",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Langchain agent.",
python/providers/langgraph/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-langgraph"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get array of tools with LangGraph Agent Workflows."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/langgraph/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_langgraph",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools with LangGraph Agent Workflows",
python/providers/llamaindex/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-llamaindex"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get array of tools with LlamaIndex Agent Workflows."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/llamaindex/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_llamaindex",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools with LlamaIndex Agent Workflows",
python/providers/openai/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-openai"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get an array of tools with your OpenAI Function Call."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/openai/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_openai",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your OpenAI Function Call.",
python/providers/openai_agents/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-openai-agents"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "Use Composio to get array of strongly typed tools for OpenAI Agents"
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/openai_agents/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
8
9 setup(
10 name="composio_openai_agents",
11 - version="0.10.4",
11 + version="0.10.5",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of strongly typed tools for OpenAI Agents",
python/pyproject.toml
+2 -2
@@ -1,13 +1,13 @@
1 [project]
2 name = "composio"
3 -version = "0.10.4"
3 +version = "0.10.5"
4 description = "SDK for integrating Composio with your applications."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
7 dependencies = [
8 "pysher>=1.0.8",
9 "pydantic>=2.6.4",
10 - "composio-client==1.22.0",
10 + "composio-client==1.25.0",
11 "typing-extensions>=4.0.0",
12 "openai",
13 ]
python/setup.py
+1 -1
@@ -25,7 +25,7 @@ setup(
25 install_requires=[
26 "pysher==1.0.8",
27 "pydantic>=2.6.4",
28 - "composio-client==1.22.0",
28 + "composio-client==1.25.0",
29 "typing-extensions>=4.0.0",
30 ],
31 include_package_data=True,
python/tests/test_tool_router.py
+39 -41
@@ -446,6 +446,28 @@ class TestToolRouter:
446 == "https://example.com/callback"
447 )
448
449 + def test_create_session_with_wait_for_connections(self, tool_router, mock_client):
450 + """Test creating a session with wait_for_connections in manage_connections config."""
451 + session = tool_router.create(
452 + user_id="user_123",
453 + manage_connections={
454 + "enable": True,
455 + "callback_url": "https://example.com/callback",
456 + "wait_for_connections": True,
457 + },
458 + )
459 +
460 + assert session.session_id == "session_123"
461 +
462 + call_args = mock_client.tool_router.session.create.call_args
463 + kwargs = call_args.kwargs
464 + assert kwargs["manage_connections"]["enable"] is True
465 + assert (
466 + kwargs["manage_connections"]["callback_url"]
467 + == "https://example.com/callback"
468 + )
469 + assert kwargs["manage_connections"]["enable_wait_for_connections"] is True
470 +
471 def test_create_session_with_auth_configs(self, tool_router, mock_client):
472 """Test creating a session with auth configs."""
473 session = tool_router.create(
@@ -750,8 +772,9 @@ class TestToolRouter:
772 mock_tool.slug = "GMAIL_FETCH_EMAILS"
773 mock_tool.toolkit.slug = "gmail"
774 mock_tool.input_parameters = {}
753 - mock_tools_instance.get_raw_composio_tools.return_value = [mock_tool]
754 - mock_tools_instance._file_helper.process_schema_recursively.return_value = {}
775 + mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool]
776 + mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {}
777 + mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {}
778 mock_tools_class.return_value = mock_tools_instance
779
780 # Setup provider mock
@@ -765,18 +788,16 @@ class TestToolRouter:
788 client=mock_client, provider=mock_provider, auto_upload_download_files=True
789 )
790
768 - # Verify get_raw_composio_tools was called
769 - mock_tools_instance.get_raw_composio_tools.assert_called_once()
791 + # Verify get_raw_tool_router_meta_tools was called
792 + mock_tools_instance.get_raw_tool_router_meta_tools.assert_called_once()
793
794 # Verify provider's wrap_tools was called
795 mock_provider.wrap_tools.assert_called_once()
796 assert result == "mocked-wrapped-tools"
797
798 @patch("composio.core.models.tools.Tools")
776 - @patch("composio.core.models._modifiers.apply_modifier_by_type")
799 def test_tools_function_with_modifiers(
800 self,
779 - mock_apply_modifier,
801 mock_tools_class,
802 tool_router,
803 mock_client,
@@ -788,13 +809,11 @@ class TestToolRouter:
809 mock_tool.slug = "GMAIL_FETCH_EMAILS"
810 mock_tool.toolkit.slug = "gmail"
811 mock_tool.input_parameters = {}
791 - mock_tools_instance.get_raw_composio_tools.return_value = [mock_tool]
792 - mock_tools_instance._file_helper.process_schema_recursively.return_value = {}
812 + mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool]
813 + mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {}
814 + mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {}
815 mock_tools_class.return_value = mock_tools_instance
816
795 - # Setup apply_modifier_by_type to return the tool unchanged
796 - mock_apply_modifier.return_value = mock_tool
797 -
817 # Setup provider mock
818 mock_provider.wrap_tools.return_value = "mocked-wrapped-tools"
819
@@ -809,8 +828,9 @@ class TestToolRouter:
828
829 # Verify provider's wrap_tools was called
830 mock_provider.wrap_tools.assert_called_once()
812 - # Verify apply_modifier_by_type was called with the modifier
813 - assert mock_apply_modifier.called
831 + # Verify get_raw_tool_router_meta_tools was called with modifiers
832 + call_args = mock_tools_instance.get_raw_tool_router_meta_tools.call_args
833 + assert call_args.kwargs.get("modifiers") == modifiers
834 assert result == "mocked-wrapped-tools"
835
836 def test_session_mcp_type_http(self, tool_router, mock_client):
@@ -989,8 +1009,9 @@ class TestToolRouterExecution:
1009 mock_tool.slug = "GMAIL_SEND_EMAIL"
1010 mock_tool.toolkit.slug = "gmail"
1011 mock_tool.input_parameters = {}
992 - mock_tools_instance.get_raw_composio_tools.return_value = [mock_tool]
993 - mock_tools_instance._file_helper.process_schema_recursively.return_value = {}
1012 + mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool]
1013 + mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {}
1014 + mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {}
1015 mock_tools_instance._wrap_execute_tool_for_tool_router = MagicMock(
1016 return_value=lambda slug, args: {
1017 "data": {},
@@ -1024,14 +1045,6 @@ class TestToolRouterExecution:
1045 mock_execute_response
1046 )
1047
1027 - # Setup mock tool
1028 - mock_tool = MagicMock()
1029 - mock_tool.slug = "GMAIL_SEND_EMAIL"
1030 - mock_tool.toolkit.slug = "gmail"
1031 -
1032 - # Mock get_raw_composio_tool_by_slug
1033 - mock_client.tools.retrieve.return_value = mock_tool
1034 -
1048 # Create a real Tools instance to test the execute function
1049 from composio.core.models.tools import Tools as RealTools
1050
@@ -1059,14 +1072,6 @@ class TestToolRouterExecution:
1072 self, tool_router, mock_client, mock_provider
1073 ):
1074 """Test that modifiers are applied before and after tool execution."""
1062 - # Setup mock tool
1063 - mock_tool = MagicMock()
1064 - mock_tool.slug = "GMAIL_SEND_EMAIL"
1065 - mock_tool.toolkit.slug = "gmail"
1066 -
1067 - # Mock get_raw_composio_tool_by_slug
1068 - mock_client.tools.retrieve.return_value = mock_tool
1069 -
1075 # Setup execute_meta response
1076 mock_execute_response = MagicMock()
1077 mock_execute_response.data = {"result": "success"}
@@ -1118,14 +1123,6 @@ class TestToolRouterExecution:
1123
1124 def test_execute_tool_error_handling(self, tool_router, mock_client, mock_provider):
1125 """Test that tool execution errors are handled correctly."""
1121 - # Setup mock tool
1122 - mock_tool = MagicMock()
1123 - mock_tool.slug = "GMAIL_SEND_EMAIL"
1124 - mock_tool.toolkit.slug = "gmail"
1125 -
1126 - # Mock get_raw_composio_tool_by_slug
1127 - mock_client.tools.retrieve.return_value = mock_tool
1128 -
1126 # Setup execute_meta to return an error
1127 mock_execute_response = MagicMock()
1128 mock_execute_response.data = {}
@@ -1165,8 +1162,9 @@ class TestToolRouterIntegration:
1162 mock_tool.slug = "TOOL1"
1163 mock_tool.toolkit.slug = "github"
1164 mock_tool.input_parameters = {}
1168 - mock_tools_instance.get_raw_composio_tools.return_value = [mock_tool]
1169 - mock_tools_instance._file_helper.process_schema_recursively.return_value = {}
1165 + mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool]
1166 + mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {}
1167 + mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {}
1168 mock_tools_class.return_value = mock_tools_instance
1169
1170 # Setup provider mock
ts/examples/tool-router/src/logger.ts
+2 -2
@@ -1,8 +1,8 @@
1 -import { ExecuteToolModifiers } from "@composio/core";
1 +import { SessionExecuteMetaModifiers } from "@composio/core";
2 import ora from 'ora';
3 let spinner = ora();
4
5 -export const modifiers: ExecuteToolModifiers = {
5 +export const modifiers: SessionExecuteMetaModifiers = {
6 beforeExecute: ({ toolSlug, params }) => {
7 spinner = ora();
8 spinner.start(`Executing ${toolSlug}`);
ts/packages/core/src/composio.ts
+1 -22
@@ -5,8 +5,7 @@ import { Toolkits } from './models/Toolkits';
5 import { Triggers } from './models/Triggers';
6 import { AuthConfigs } from './models/AuthConfigs';
7 import { ConnectedAccounts } from './models/ConnectedAccounts';
8 -import { MCP } from './models/MCP.experimental';
9 -import { MCP as DeprecatedMCP } from './models/MCP';
8 +import { MCP } from './models/MCP';
9 import { telemetry } from './telemetry/Telemetry';
10 import { getSDKConfig, getToolkitVersionsFromEnv } from './utils/sdk';
11 import logger from './utils/logger';
@@ -196,11 +195,6 @@ export class Composio<
195 */
196 use: (id: string) => Promise<ToolRouterSession<unknown, unknown, TProvider>>;
197
199 - /**
200 - * Experimental features
201 - */
202 - experimental: {};
203 -
198 /**
199 * Creates a new instance of the Composio SDK.
200 *
@@ -289,21 +283,6 @@ export class Composio<
283 this.create = this.toolRouter.create.bind(this.toolRouter);
284 this.use = this.toolRouter.use.bind(this.toolRouter);
285
292 - /**
293 - * Initialize Experimental features
294 - */
295 - this.experimental = {
296 - create: async (
297 - userId: string,
298 - routerConfig?: ToolRouterCreateSessionConfig
299 - ): Promise<ToolRouterSession<unknown, unknown, TProvider>> => {
300 - return this.toolRouter.create(userId, routerConfig);
301 - },
302 - use: async (id: string): Promise<ToolRouterSession<unknown, unknown, TProvider>> => {
303 - return this.toolRouter.use(id);
304 - },
305 - };
306 -
286 /**
287 * Initialize the client telemetry.
288 */
ts/packages/core/src/lib/toolRouterParams.ts
+67
@@ -4,8 +4,14 @@ import {
4 ToolRouterConfigTools,
5 ToolRouterConfigToolsSchema,
6 ToolRouterToolsParam,
7 + ToolRouterConfigManageConnectionsSchema,
8 + ToolRouterCreateSessionConfig,
9 + ToolRouterToolkitsParamSchema,
10 + ToolRouterToolkitsDisabledConfigSchema,
11 + ToolRouterToolkitsEnabledConfigSchema,
12 } from '../types/toolRouter.types';
13 import { ValidationError } from '../errors';
14 +import { z } from 'zod';
15
16 export const transformToolRouterToolsParams = (
17 params?: Record<string, ToolRouterToolsParam | ToolRouterConfigTools> | undefined
@@ -72,3 +78,64 @@ export const transformToolRouterTagsParams = (
78 };
79 }
80 };
81 +
82 +export const transformToolRouterManageConnectionsParams = (
83 + params?: boolean | z.infer<typeof ToolRouterConfigManageConnectionsSchema>
84 +): SessionCreateParams.ManageConnections => {
85 + if (params === undefined) {
86 + // Default case when params is undefined
87 + return {
88 + enable: true,
89 + };
90 + }
91 +
92 + if (typeof params === 'boolean') {
93 + return {
94 + enable: params,
95 + };
96 + }
97 +
98 + // Parse the params using the zod schema for type safety
99 + const parsedResult = ToolRouterConfigManageConnectionsSchema.safeParse(params);
100 + if (!parsedResult.success) {
101 + throw new ValidationError('Failed to parse manage connections config', {
102 + cause: parsedResult.error,
103 + });
104 + }
105 +
106 + const config = parsedResult.data;
107 + return {
108 + enable: config.enable ?? true,
109 + callback_url: config.callbackUrl,
110 + enable_wait_for_connections: config.waitForConnections,
111 + };
112 +};
113 +
114 +export const transformToolRouterWorkbenchParams = (
115 + params?: ToolRouterCreateSessionConfig['workbench']
116 +): SessionCreateParams.Workbench | undefined => {
117 + if (!params) {
118 + return undefined;
119 + }
120 +
121 + return {
122 + enable_proxy_execution: params.enableProxyExecution,
123 + auto_offload_threshold: params.autoOffloadThreshold,
124 + };
125 +};
126 +
127 +export const transformToolRouterToolkitsParams = (
128 + params?: ToolRouterCreateSessionConfig['toolkits']
129 +): SessionCreateParams.Enable | SessionCreateParams.Disable | undefined => {
130 + if (!params) {
131 + return undefined;
132 + }
133 +
134 + // If it's an array, convert to enable format
135 + if (Array.isArray(params)) {
136 + return { enable: params };
137 + }
138 +
139 + // Otherwise return as-is (already in enable/disable format)
140 + return params as SessionCreateParams.Enable | SessionCreateParams.Disable;
141 +};
ts/packages/core/src/models/MCP.experimental.ts deleted
-430
@@ -1,430 +0,0 @@
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 { McpUpdateResponse } from '@composio/client/resources.js';
24 -import { McpRetrieveResponse } from '@composio/client/resources';
25 -
26 -function transformMCPItemResponse(response: McpUpdateResponse | McpRetrieveResponse): MCPItem {
27 - return transform(response)
28 - .with(MCPItemSchema)
29 - .using(raw => ({
30 - name: raw.name,
31 - allowedTools: raw.allowed_tools,
32 - id: raw.id,
33 - authConfigIds: raw.auth_config_ids,
34 - commands: raw.commands,
35 - MCPUrl: raw.mcp_url,
36 - toolkitIcons: raw.toolkit_icons,
37 - serverInstanceCount: raw.server_instance_count,
38 - toolkits: raw.toolkits,
39 - }));
40 -}
41 -/**
42 - * MCP (Model Control Protocol) class
43 - * Handles MCP server operations.
44 - * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
45 - */
46 -export class MCP {
47 - client: ComposioClient;
48 -
49 - constructor(client: ComposioClient) {
50 - this.client = client;
51 - telemetry.instrument(this, 'MCP');
52 - }
53 -
54 - /**
55 - * Create a new MCP configuration.
56 - * @param {Object} params - Parameters for creating the MCP configuration
57 - * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
58 - * @param {Object} params.options - Configuration options
59 - * @param {string} params.options.name - Unique name for the MCP configuration
60 - * @param {boolean} [params.options.manuallyManageConnections] - Whether to use chat-based authentication or manually connect accounts
61 - * @returns {Promise<McpServerCreateResponse<T>>} Created server details with instance getter
62 - *
63 - * @example
64 - * ```typescript
65 - * const server = await composio.mcpConfig.create("personal-mcp-server", {
66 - * toolkits: ["github", "slack"],
67 - * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
68 - * manuallyManageConnections: false
69 - * }
70 - * });
71 - *
72 - * const server = await composio.mcpConfig.create("personal-mcp-server", {
73 - * toolkits: [{ toolkit: "gmail", authConfigId: "ac_243434343" }],
74 - * allowedTools: ["GMAIL_FETCH_EMAILS"],
75 - * manuallyManageConnections: false
76 - * }
77 - * });
78 - * ```
79 - */
80 - async create(name: string, mcpConfig: MCPConfigCreationParams): Promise<MCPConfigCreateResponse> {
81 - const config = MCPConfigCreationParamsSchema.safeParse(mcpConfig);
82 - if (config.error) {
83 - throw new ValidationError('Invalid parameters passed to create mcp config', {
84 - cause: config.error,
85 - });
86 - }
87 -
88 - const toolkits: string[] = [];
89 - const auth_config_ids: string[] = [];
90 - const custom_tools: string[] = config.data.allowedTools ?? [];
91 -
92 - // extract all the toolkits, authconfigs, and allowed tools to separate slugs
93 - config.data.toolkits.forEach(toolkit => {
94 - if (typeof toolkit === 'string') {
95 - toolkits.push(toolkit);
96 - } else if (toolkit.toolkit) {
97 - toolkits.push(toolkit.toolkit);
98 - } else if (toolkit.authConfigId) {
99 - auth_config_ids.push(toolkit.authConfigId);
100 - }
101 - });
102 -
103 - const server = await this.client.mcp.custom.create({
104 - name,
105 - toolkits,
106 - auth_config_ids,
107 - custom_tools,
108 - // if manually manage account is set to true, disable composio account management tools
109 - managed_auth_via_composio: config.data.manuallyManageConnections ? false : true,
110 - });
111 -
112 - const camelCaseServer = transform(server)
113 - .with(MCPConfigResponseSchema)
114 - .using(raw => ({
115 - name: raw.name,
116 - allowedTools: raw.allowed_tools,
117 - id: raw.id,
118 - authConfigIds: raw.auth_config_ids,
119 - commands: raw.commands,
120 - MCPUrl: raw.mcp_url,
121 - }));
122 -
123 - return {
124 - ...camelCaseServer,
125 - generate: async (userId: string): Promise<MCPServerInstance> => {
126 - return await this.generate(userId, server.id, {
127 - manuallyManageConnections: config.data.manuallyManageConnections,
128 - });
129 - },
130 - };
131 - }
132 -
133 - /**
134 - * List the MCP servers with optional filtering and pagination
135 - * @param {Object} options - Filtering and pagination options
136 - * @param {number} [options.page=1] - Page number for pagination (1-based)
137 - * @param {number} [options.limit=10] - Maximum number of items to return per page
138 - * @param {string[]} [options.toolkits=[]] - Array of toolkit names to filter by
139 - * @param {string[]} [options.authConfigs=[]] - Array of auth configuration IDs to filter by
140 - * @param {string} [options.name] - Filter by MCP server name (partial match)
141 - * @returns {Promise<MCPListResponse>} Paginated list of MCP servers with metadata
142 - *
143 - * @example
144 - * ```typescript
145 - * // List all MCP servers
146 - * const allServers = await composio.experimental.mcp.list({});
147 - *
148 - * // List with pagination
149 - * const pagedServers = await composio.experimental.mcp.list({
150 - * page: 2,
151 - * limit: 5
152 - * });
153 - *
154 - * // Filter by toolkit
155 - * const githubServers = await composio.experimental.mcp.list({
156 - * toolkits: ['github', 'slack']
157 - * });
158 - *
159 - * // Filter by name
160 - * const namedServers = await composio.experimental.mcp.list({
161 - * name: 'personal'
162 - * });
163 - * ```
164 - */
165 - async list(options: MCPListParams): Promise<MCPListResponse> {
166 - const { data: params, error } = MCPListParamsSchema.safeParse(options);
167 - if (error) {
168 - throw new ValidationError('Failed to validate list options', {
169 - cause: error,
170 - });
171 - }
172 -
173 - const listResponse = await this.client.mcp.list({
174 - page_no: params.page,
175 - limit: params.limit,
176 - toolkits: params.toolkits?.length > 0 ? params.toolkits.join(',') : undefined,
177 - auth_config_ids: params.authConfigs?.length > 0 ? params.authConfigs.join(',') : undefined,
178 - name: params.name,
179 - });
180 -
181 - const transformedListResponse = transform(listResponse)
182 - .with(MCPListResponseSchema)
183 - .using(raw => ({
184 - currentPage: raw.current_page,
185 - totalPages: raw.total_pages,
186 - items: raw.items.map(item => ({
187 - name: item.name,
188 - allowedTools: item.allowed_tools,
189 - id: item.id,
190 - authConfigIds: item.auth_config_ids,
191 - commands: item.commands,
192 - MCPUrl: item.mcp_url,
193 - toolkitIcons: item.toolkit_icons,
194 - serverInstanceCount: item.server_instance_count,
195 - toolkits: item.toolkits,
196 - })),
197 - }));
198 -
199 - return transformedListResponse;
200 - }
201 -
202 - /**
203 - * Retrieve detailed information about a specific MCP server by its ID
204 - * @param {string} serverId - The unique identifier of the MCP server to retrieve
205 - * @returns {Promise<MCPItem>} Complete MCP server details including configuration, tools, and metadata
206 - *
207 - * @example
208 - * ```typescript
209 - * // Get a specific MCP server by ID
210 - * const server = await composio.experimental.mcp.get("mcp_12345");
211 - *
212 - * console.log(server.name); // "My Personal MCP Server"
213 - * console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
214 - * console.log(server.toolkits); // ["github", "slack"]
215 - * console.log(server.serverInstanceCount); // 3
216 - *
217 - * // Access setup commands for different clients
218 - * console.log(server.commands.claude); // Claude setup command
219 - * console.log(server.commands.cursor); // Cursor setup command
220 - * console.log(server.commands.windsurf); // Windsurf setup command
221 - *
222 - * // Use the MCP URL for direct connections
223 - * const mcpUrl = server.MCPUrl;
224 - * ```
225 - *
226 - * @throws {ValidationError} When the server ID is invalid or server not found
227 - */
228 - async get(serverId: string): Promise<MCPItem> {
229 - const response = await this.client.mcp.retrieve(serverId);
230 - return transformMCPItemResponse(response);
231 - }
232 -
233 - /**
234 - * Delete an MCP server configuration permanently
235 - * @param {string} serverId - The unique identifier of the MCP server to delete
236 - * @returns {Promise<{id: string; deleted: boolean}>} Confirmation object with server ID and deletion status
237 - *
238 - * @example
239 - * ```typescript
240 - * // Delete an MCP server by ID
241 - * const result = await composio.experimental.mcp.delete("mcp_12345");
242 - *
243 - * if (result.deleted) {
244 - * console.log(`Server ${result.id} has been successfully deleted`);
245 - * } else {
246 - * console.log(`Failed to delete server ${result.id}`);
247 - * }
248 - *
249 - * // Example with error handling
250 - * try {
251 - * const result = await composio.experimental.mcp.delete("mcp_12345");
252 - * console.log("Deletion successful:", result);
253 - * } catch (error) {
254 - * console.error("Failed to delete MCP server:", error.message);
255 - * }
256 - *
257 - * // Delete and verify from list
258 - * await composio.experimental.mcp.delete("mcp_12345");
259 - * const servers = await composio.experimental.mcp.list({});
260 - * const serverExists = servers.items.some(server => server.id === "mcp_12345");
261 - * console.log("Server still exists:", serverExists); // Should be false
262 - * ```
263 - *
264 - * @throws {ValidationError} When the server ID is invalid or server not found
265 - * @throws {Error} When the server cannot be deleted due to active connections or other constraints
266 - *
267 - * @warning This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
268 - */
269 - async delete(serverId: string): Promise<{ id: string; deleted: boolean }> {
270 - return await this.client.mcp.delete(serverId);
271 - }
272 -
273 - /**
274 - * Update an existing MCP server configuration with new settings
275 - * @param {string} serverId - The unique identifier of the MCP server to update
276 - * @param {Object} config - Update configuration parameters
277 - * @param {string} [config.name] - New name for the MCP server
278 - * @param {Array} [config.toolkits] - Updated toolkit configurations
279 - * @param {string} [config.toolkits[].toolkit] - Toolkit identifier (e.g., "github", "slack")
280 - * @param {string} [config.toolkits[].authConfigId] - Auth configuration ID for the toolkit
281 - * @param {string[]} [config.toolkits[].allowedTools] - Specific tools to enable for this toolkit
282 - * @param {boolean} [config.manuallyManageConnections] - Whether to manually manage account connections
283 - * @returns {Promise<MCPItem>} Updated MCP server configuration with all details
284 - *
285 - * @example
286 - * ```typescript
287 - * // Update server name only
288 - * const updatedServer = await composio.experimental.mcp.update("mcp_12345", {
289 - * name: "My Updated MCP Server"
290 - * });
291 - *
292 - * // Update toolkits and tools
293 - * const serverWithNewTools = await composio.experimental.mcp.update("mcp_12345", {
294 - * toolkits: [
295 - * {
296 - * toolkit: "github",
297 - * authConfigId: "auth_abc123",
298 - * allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
299 - * },
300 - * {
301 - * toolkit: "slack",
302 - * authConfigId: "auth_xyz789",
303 - * allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]
304 - * }
305 - * ]
306 - * });
307 - *
308 - * // Update connection management setting
309 - * const serverWithManualAuth = await composio.experimental.mcp.update("mcp_12345", {
310 - * name: "Manual Auth Server",
311 - * manuallyManageConnections: true
312 - * });
313 - *
314 - * // Complete update example
315 - * const fullyUpdatedServer = await composio.experimental.mcp.update("mcp_12345", {
316 - * name: "Production MCP Server",
317 - * toolkits: [
318 - * {
319 - * toolkit: "gmail",
320 - * authConfigId: "auth_gmail_prod",
321 - * }
322 - * ],
323 - * allowedTools: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"]
324 - * manuallyManageConnections: false
325 - * });
326 - *
327 - * console.log("Updated server:", fullyUpdatedServer.name);
328 - * console.log("New tools:", fullyUpdatedServer.allowedTools);
329 - * ```
330 - *
331 - * @throws {ValidationError} When the update parameters are invalid or malformed
332 - * @throws {Error} When the server ID doesn't exist or update fails
333 - *
334 - * @note Only provided fields will be updated. Omitted fields will retain their current values.
335 - * @note When updating toolkits, the entire toolkit configuration is replaced, not merged.
336 - */
337 - async update(serverId: string, config: MCPUpdateParams): Promise<MCPItem> {
338 - const { data: params, error } = MCPUpdateParamsSchema.safeParse(config);
339 - if (error) {
340 - throw new ValidationError('Failed to validate update params', {
341 - cause: error,
342 - });
343 - }
344 -
345 - const toolkits: string[] = [];
346 - const auth_config_ids: string[] = [];
347 - const custom_tools: string[] | undefined = params.allowedTools ?? undefined;
348 -
349 - // extract all the toolkits, authconfigs, and allowed tools to separate slugs
350 - params.toolkits?.forEach(toolkit => {
351 - if (typeof toolkit === 'string') {
352 - toolkits.push(toolkit);
353 - } else if (toolkit.toolkit) {
354 - toolkits.push(toolkit.toolkit);
355 - } else if (toolkit.authConfigId) {
356 - auth_config_ids.push(toolkit.authConfigId);
357 - }
358 - });
359 - const response = await this.client.mcp.update(serverId, {
360 - ...{ name: params.name ?? undefined },
361 - ...(params.toolkits
362 - ? {
363 - custom_tools: custom_tools,
364 - toolkits: toolkits,
365 - auth_config_ids: auth_config_ids,
366 - }
367 - : {}),
368 - ...{ managed_auth_via_composio: params.manuallyManageConnections ?? undefined },
369 - });
370 - return transformMCPItemResponse(response);
371 - }
372 -
373 - /**
374 - * Get server URLs for an existing MCP server.
375 - * The response is wrapped according to the provider's specifications.
376 - *
377 - * @example
378 - * ```typescript
379 - * import { Composio } from "@composio/code";
380 - *
381 - * const composio = new Composio();
382 - * const mcp = await composio.experimental.mcp.generate("default", "<mcp_config_id>");
383 - * ```
384 - *
385 - * @param userId {string} external user id from your database for whom you want the server for
386 - * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
387 - * @param options {object} additional options
388 - * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
389 - */
390 - async generate(
391 - userId: string,
392 - mcpConfigId: string,
393 - options?: MCPGetInstanceParams
394 - ): Promise<MCPServerInstance> {
395 - const server = await this.client.mcp.retrieve(mcpConfigId);
396 - const params = MCPGetInstanceParamsSchema.safeParse(
397 - options ?? { manuallyManageConnections: false }
398 - );
399 - if (params.error) {
400 - throw new ValidationError('Invalid params passed for Get Instance Params', {
401 - cause: params.error,
402 - });
403 - }
404 -
405 - const urlResponse = await this.client.mcp.generate.url({
406 - mcp_server_id: mcpConfigId,
407 - user_ids: [userId],
408 - managed_auth_by_composio: options?.manuallyManageConnections ? false : true,
409 - });
410 -
411 - const userIdsURL = urlResponse.user_ids_url[0];
412 - const serverInstance = MCPServerInstanceSchema.safeParse({
413 - id: server.id,
414 - name: server.name,
415 - type: 'streamable_http' as const,
416 - url: userIdsURL,
417 - userId: userId,
418 - allowedTools: server.allowed_tools,
419 - authConfigs: server.auth_config_ids,
420 - });
421 -
422 - if (serverInstance.error) {
423 - throw new ValidationError('Failed to parse MCP server instance', {
424 - cause: serverInstance.error,
425 - });
426 - }
427 -
428 - return serverInstance.data;
429 - }
430 -}
ts/packages/core/src/models/MCP.ts
+327 -777
@@ -1,880 +1,430 @@
1 -/**
2 - * @fileoverview MCP class for Composio SDK, used to manage MCP servers.
3 - *
4 - * @module MCP
5 - */
6 -import ComposioClient from '@composio/client';
1 +import { Composio as ComposioClient } from '@composio/client';
2 import { telemetry } from '../telemetry/Telemetry';
3 import {
9 - MCPToolkitConfig,
10 - MCPAuthOptions,
11 - MCPGetServerParams,
12 - MCPToolkitConfigsArraySchema,
13 - MCPAuthOptionsSchema,
14 - ComposioCustomCreateResponseSchema,
15 - ComposioMcpListResponseSchema,
16 - McpRetrieveResponseSchema,
17 - ComposioMcpDeleteResponseSchema,
18 - ComposioMcpUpdateResponseSchema,
19 - McpUrlResponse,
20 - McpUrlResponseCamelCase,
21 - McpServerGetResponse,
22 - McpServerCreateResponse,
23 - ComposioGenerateURLResponseSchema,
24 - McpListResponse,
25 - McpRetrieveResponse,
26 - McpDeleteResponse,
27 - McpUpdateResponse,
28 - GenerateURLResponse,
29 - GenerateURLParamsSchema,
30 - GenerateURLParams,
31 - McpToolkitConnectionStatus,
32 - McpUserConnectionStatus,
33 - ConnectionStatus,
34 -} from '../types/mcp.types';
35 -import { CustomCreateResponse as CustomCreateResponseRaw } from '@composio/client/resources/mcp';
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';
37 -import { BaseComposioProvider } from '../provider/BaseProvider';
38 -import {
39 - transformMcpCreateResponse,
40 - transformMcpListResponse,
41 - transformMcpRetrieveResponse,
42 - transformMcpDeleteResponse,
43 - transformMcpUpdateResponse,
44 - transformMcpGenerateUrlResponse,
45 -} from '../utils/transformers/mcp';
46 -import { Toolkits } from './Toolkits';
47 -import { ToolkitAuthFieldsResponse } from '../types/toolkit.types';
48 -import { ConnectionRequest } from '../types/connectionRequest.types';
49 -import logger from '../utils/logger';
50 -
51 -/**
52 - * Extract the MCP response type from a provider.
53 - */
54 -type ExtractMcpResponseType<T> =
55 - T extends BaseComposioProvider<unknown, unknown, infer TMcp>
56 - ? TMcp
57 - : /* @default */ McpServerGetResponse;
58 -
22 +import { transform } from '../utils/transform';
23 +import { McpUpdateResponse } from '@composio/client/resources.js';
24 +import { McpRetrieveResponse } from '@composio/client/resources';
25 +
26 +function transformMCPItemResponse(response: McpUpdateResponse | McpRetrieveResponse): MCPItem {
27 + return transform(response)
28 + .with(MCPItemSchema)
29 + .using(raw => ({
30 + name: raw.name,
31 + allowedTools: raw.allowed_tools,
32 + id: raw.id,
33 + authConfigIds: raw.auth_config_ids,
34 + commands: raw.commands,
35 + MCPUrl: raw.mcp_url,
36 + toolkitIcons: raw.toolkit_icons,
37 + serverInstanceCount: raw.server_instance_count,
38 + toolkits: raw.toolkits,
39 + }));
40 +}
41 /**
42 * MCP (Model Control Protocol) class
61 - * Handles MCP server operations
43 + * Handles MCP server operations.
44 + * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
45 */
63 -export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknown>> {
64 - private client: ComposioClient;
65 - private toolkits: Toolkits;
66 - protected provider: TProvider;
67 -
68 - // Trick to store types derived from a generic parameter inside the class.
69 - // It's similar to `using type` declarations in C++.
70 - // See: https://stackoverflow.com/questions/76017389/type-or-interface-inside-class-in-typescript.
71 - declare readonly TMcpResponse: ExtractMcpResponseType<TProvider>;
46 +export class MCP {
47 + client: ComposioClient;
48
73 - constructor(client: ComposioClient, provider: TProvider) {
49 + constructor(client: ComposioClient) {
50 this.client = client;
75 - this.provider = provider;
76 - this.toolkits = new Toolkits(client);
51 telemetry.instrument(this, 'MCP');
52 }
53
54 /**
81 - * Validates toolkit configurations using Zod schema
82 - * @private
83 - * @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations to validate
84 - * @param {MCPAuthOptions} [authOptions] - Authentication options to validate
85 - * @throws {ValidationError} If validation fails
86 - */
87 - private validateInputs(toolkitConfigs: MCPToolkitConfig[], authOptions?: MCPAuthOptions): void {
88 - // Validate toolkit configurations
89 - const toolkitConfigsResult = MCPToolkitConfigsArraySchema.safeParse(toolkitConfigs);
90 - if (toolkitConfigsResult.error) {
91 - throw new ValidationError('Failed to parse toolkit configurations', {
92 - cause: toolkitConfigsResult.error,
93 - });
94 - }
95 -
96 - // Validate auth options if provided
97 - if (authOptions !== undefined) {
98 - const authOptionsResult = MCPAuthOptionsSchema.safeParse(authOptions);
99 - if (authOptionsResult.error) {
100 - throw new ValidationError('Failed to parse auth options', {
101 - cause: authOptionsResult.error,
102 - });
103 - }
104 - }
105 - }
106 -
107 - /**
108 - * Create a new MCP server
109 - * @param {Object} params - Parameters for creating the MCP server
55 + * Create a new MCP configuration.
56 + * @param {Object} params - Parameters for creating the MCP configuration
57 * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
111 - * @param {Object} params.options - Server creation options
112 - * @param {string} params.options.name - Unique name for the MCP server
113 - * @param {boolean} [params.options.isChatAuth] - Whether to use chat-based authentication
114 - * @returns {Promise<McpServerCreateResponse<TMcpResponse>>} Created server details with instance getter
58 + * @param {Object} params.options - Configuration options
59 + * @param {string} params.options.name - Unique name for the MCP configuration
60 + * @param {boolean} [params.options.manuallyManageConnections] - Whether to use chat-based authentication or manually connect accounts
61 + * @returns {Promise<McpServerCreateResponse<T>>} Created server details with instance getter
62 *
63 * @example
64 * ```typescript
118 - * const server = await composio.mcp.create("personal-mcp-server", [
119 - * {
120 - * authConfigId: "ac_xyz",
121 - * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
122 - * }
123 - * ],
124 - * {
125 - * isChatAuth: true
126 - * }
65 + * const server = await composio.mcpConfig.create("personal-mcp-server", {
66 + * toolkits: ["github", "slack"],
67 + * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
68 + * manuallyManageConnections: false
69 + * }
70 * });
71 *
129 - * // Use convenience method on response
130 - * const urls = await server.getServer({
131 - * userId: "user123"
72 + * const server = await composio.mcpConfig.create("personal-mcp-server", {
73 + * toolkits: [{ toolkit: "gmail", authConfigId: "ac_243434343" }],
74 + * allowedTools: ["GMAIL_FETCH_EMAILS"],
75 + * manuallyManageConnections: false
76 + * }
77 * });
78 * ```
79 */
135 - async create(
136 - name: string,
137 - serverConfig: Array<{
138 - authConfigId: string;
139 - allowedTools: string[];
140 - }>,
141 - options: {
142 - isChatAuth?: boolean;
143 - }
144 - ): Promise<McpServerCreateResponse<typeof this.TMcpResponse>> {
145 - // Validate inputs using Zod schemas
146 - if (!serverConfig || serverConfig.length === 0) {
147 - throw new ValidationError('At least one auth config is required', {});
148 - }
149 -
150 - if (!name) {
151 - throw new ValidationError('Server name is required', {});
152 - }
153 -
154 - // Check if server with this name already exists
155 - try {
156 - const mcpServer = await this.getByName(name);
157 - const authConfigs = mcpServer.authConfigIds?.sort()!;
158 - const sortedCurrentAuthConfigs = serverConfig.map(config => config.authConfigId).sort();
159 - if (
160 - authConfigs.length > 0 &&
161 - !authConfigs.every((config, index) => config === sortedCurrentAuthConfigs[index])
162 - ) {
163 - throw new ValidationError(
164 - 'MCP server with this name already exists with different auth configs',
165 - {
166 - meta: { serverName: name },
167 - }
168 - );
169 - }
170 - // If we reach here, server exists
171 - const tools = mcpServer.tools?.sort()!;
172 - const sortedCurrentTools = serverConfig.flatMap(config => config.allowedTools).sort();
173 - if (tools?.length > 0 && !tools.every((tool, index) => tool === sortedCurrentTools[index])) {
174 - throw new ValidationError('MCP server with this name already exists with different tools', {
175 - meta: { serverName: name },
176 - });
177 - }
178 -
179 - // Get toolkits from auth configs
180 - const authConfigDetails = await Promise.all(
181 - serverConfig.map(config => this.client.authConfigs.retrieve(config.authConfigId))
182 - );
183 - const toolkits = authConfigDetails.map(config => config.toolkit.slug);
184 -
185 - const camelCaseResponse = transformMcpCreateResponse({
186 - id: mcpServer.id,
187 - name: mcpServer.name,
188 - auth_config_ids: serverConfig.map(config => config.authConfigId),
189 - allowed_tools: serverConfig.flatMap(config => config.allowedTools),
190 - managed_auth_via_composio: options.isChatAuth || false,
191 - commands: mcpServer.commands!,
192 - created_at: mcpServer.createdAt!,
193 - updated_at: mcpServer.updatedAt!,
194 - mcp_url: mcpServer.mcpUrl!,
80 + async create(name: string, mcpConfig: MCPConfigCreationParams): Promise<MCPConfigCreateResponse> {
81 + const config = MCPConfigCreationParamsSchema.safeParse(mcpConfig);
82 + if (config.error) {
83 + throw new ValidationError('Invalid parameters passed to create mcp config', {
84 + cause: config.error,
85 });
196 -
197 - return {
198 - ...camelCaseResponse,
199 - toolkits,
200 - getServer: async (params: MCPGetServerParams): Promise<typeof this.TMcpResponse> => {
201 - return this.getServer(camelCaseResponse.id, params.userId || '', {
202 - isChatAuth: options.isChatAuth,
203 - });
204 - },
205 - } as McpServerCreateResponse<typeof this.TMcpResponse>;
206 - } catch (error) {
207 - // If error is not about server not found, re-throw it
208 - if (error instanceof ValidationError && !error.message.includes('not found')) {
209 - throw error;
210 - }
211 - // Server doesn't exist, we can proceed with creation
86 }
87
214 - // Get toolkits from auth configs
215 - const authConfigDetails = await Promise.all(
216 - serverConfig.map(config => this.client.authConfigs.retrieve(config.authConfigId))
217 - );
218 - const toolkits = authConfigDetails.map(config => config.toolkit.slug);
88 + const toolkits: string[] = [];
89 + const auth_config_ids: string[] = [];
90 + const custom_tools: string[] = config.data.allowedTools ?? [];
91
220 - // Create a custom MCP server with the toolkit configurations
221 - let mcpServerCreatedResponse: CustomCreateResponseRaw;
222 - try {
223 - mcpServerCreatedResponse = await this.client.mcp.custom.create({
224 - name: name,
225 - toolkits: toolkits,
226 - custom_tools: serverConfig.flatMap(config => config.allowedTools),
227 - managed_auth_via_composio: options.isChatAuth || false,
228 - auth_config_ids: serverConfig.map(config => config.authConfigId),
229 - });
230 - } catch (error) {
231 - throw new ValidationError('Failed to create MCP server', {
232 - cause: error,
233 - });
234 - }
92 + // extract all the toolkits, authconfigs, and allowed tools to separate slugs
93 + config.data.toolkits.forEach(toolkit => {
94 + if (typeof toolkit === 'string') {
95 + toolkits.push(toolkit);
96 + } else if (toolkit.toolkit) {
97 + toolkits.push(toolkit.toolkit);
98 + } else if (toolkit.authConfigId) {
99 + auth_config_ids.push(toolkit.authConfigId);
100 + }
101 + });
102
236 - // Validate the server creation response
237 - const serverResponseResult =
238 - ComposioCustomCreateResponseSchema.safeParse(mcpServerCreatedResponse);
239 - if (serverResponseResult.error) {
240 - throw new ValidationError('Failed to parse MCP server creation response', {
241 - cause: serverResponseResult.error,
242 - });
243 - }
103 + const server = await this.client.mcp.custom.create({
104 + name,
105 + toolkits,
106 + auth_config_ids,
107 + custom_tools,
108 + // if manually manage account is set to true, disable composio account management tools
109 + managed_auth_via_composio: config.data.manuallyManageConnections ? false : true,
110 + });
111
245 - // Transform the response to camelCase
246 - const camelCaseResponse = transformMcpCreateResponse(mcpServerCreatedResponse);
112 + const camelCaseServer = transform(server)
113 + .with(MCPConfigResponseSchema)
114 + .using(raw => ({
115 + name: raw.name,
116 + allowedTools: raw.allowed_tools,
117 + id: raw.id,
118 + authConfigIds: raw.auth_config_ids,
119 + commands: raw.commands,
120 + MCPUrl: raw.mcp_url,
121 + }));
122
248 - // Return response with convenience getServer method
123 return {
250 - ...camelCaseResponse,
251 - toolkits,
252 - getServer: async (params: MCPGetServerParams): Promise<typeof this.TMcpResponse> => {
253 - // Delegate to the standalone getServer method
254 - return this.getServer(camelCaseResponse.id, params.userId || '', {
255 - isChatAuth: options.isChatAuth,
124 + ...camelCaseServer,
125 + generate: async (userId: string): Promise<MCPServerInstance> => {
126 + return await this.generate(userId, server.id, {
127 + manuallyManageConnections: config.data.manuallyManageConnections,
128 });
129 },
258 - } as McpServerCreateResponse<typeof this.TMcpResponse>;
130 + };
131 }
132
133 /**
262 - * Get the connection status of a user for an MCP server
263 - *
264 - * Checks whether a user has the necessary connected accounts to use all toolkits
265 - * configured in the specified MCP server. Returns both overall connection status
266 - * and individual status for each toolkit.
267 - *
268 - * @param {Object} params - Parameters for checking connection status
269 - * @param {string} params.id - The UUID of the MCP server to check
270 - * @param {string} params.userId - The ID of the user to check connection status for
271 - * @returns {Promise<McpUserConnectionStatus>} Complete connection status including:
272 - * - `type`: Overall status (CONNECTED if all toolkits are connected, DISCONNECTED otherwise)
273 - * - `connected`: Boolean indicating if user can use the MCP server
274 - * - `connectedToolkits`: Record mapping each toolkit name to its individual connection status
275 - *
276 - * @throws {ValidationError} When MCP server has no toolkits configured
277 - * @throws {ValidationError} When MCP server retrieval fails
134 + * List the MCP servers with optional filtering and pagination
135 + * @param {Object} options - Filtering and pagination options
136 + * @param {number} [options.page=1] - Page number for pagination (1-based)
137 + * @param {number} [options.limit=10] - Maximum number of items to return per page
138 + * @param {string[]} [options.toolkits=[]] - Array of toolkit names to filter by
139 + * @param {string[]} [options.authConfigs=[]] - Array of auth configuration IDs to filter by
140 + * @param {string} [options.name] - Filter by MCP server name (partial match)
141 + * @returns {Promise<MCPListResponse>} Paginated list of MCP servers with metadata
142 *
143 * @example
144 * ```typescript
281 - * // Check if user can access an MCP server with Gmail and Slack toolkits
282 - * const connectionStatus = await composio.mcp.getUserConnectionStatus('user123', 'mcp-server-uuid');
145 + * // List all MCP servers
146 + * const allServers = await composio.experimental.mcp.list({});
147 *
284 - * if (connectionStatus.connected) {
285 - * console.log('User can access all required toolkits');
286 - * // connectionStatus.type === ConnectionStatus.CONNECTED
287 - * } else {
288 - * console.log('User is missing some toolkit connections');
289 - * // Check individual toolkit statuses
290 - * Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {
291 - * if (!status.connected) {
292 - * console.log(`Missing connection for toolkit: ${toolkit}`);
293 - * }
294 - * });
295 - * }
296 - * ```
148 + * // List with pagination
149 + * const pagedServers = await composio.experimental.mcp.list({
150 + * page: 2,
151 + * limit: 5
152 + * });
153 *
298 - * @example
299 - * ```typescript
300 - * // Example response when user has Gmail connected but missing Slack
301 - * {
302 - * type: ConnectionStatus.DISCONNECTED,
303 - * connected: false,
304 - * connectedToolkits: {
305 - * GMAIL: {
306 - * type: ConnectionStatus.CONNECTED,
307 - * connected: true,
308 - * toolkit: 'GMAIL',
309 - * connectedAccountId: 'conn_gmail_123'
310 - * },
311 - * SLACK: {
312 - * type: ConnectionStatus.DISCONNECTED,
313 - * connected: false,
314 - * toolkit: 'SLACK'
315 - * }
316 - * }
317 - * }
154 + * // Filter by toolkit
155 + * const githubServers = await composio.experimental.mcp.list({
156 + * toolkits: ['github', 'slack']
157 + * });
158 + *
159 + * // Filter by name
160 + * const namedServers = await composio.experimental.mcp.list({
161 + * name: 'personal'
162 + * });
163 * ```
164 */
320 - async getUserConnectionStatus(
321 - userId: string,
322 - serverId: string
323 - ): Promise<McpUserConnectionStatus> {
324 - const serverDetails = await this.get(serverId);
325 -
326 - if (!serverDetails.toolkits || serverDetails.toolkits.length === 0) {
327 - throw new ValidationError('MCP server has no toolkits configured', {
328 - meta: { serverId: serverId },
165 + async list(options: MCPListParams): Promise<MCPListResponse> {
166 + const { data: params, error } = MCPListParamsSchema.safeParse(options);
167 + if (error) {
168 + throw new ValidationError('Failed to validate list options', {
169 + cause: error,
170 });
171 }
172
332 - // @TODO(utkarsh-dixit): Add auth_config_ids support here
333 - const connectedAccounts = await this.client.connectedAccounts.list({
334 - user_ids: [userId],
335 - toolkit_slugs: serverDetails.toolkits.map(toolkit => toolkit.toLowerCase()),
336 - statuses: ['ACTIVE'],
337 - });
338 -
339 - const connectedAccountsByToolkit = new Map<string, string>();
340 - connectedAccounts.items?.forEach(account => {
341 - connectedAccountsByToolkit.set(account.toolkit.slug.toLowerCase(), account.id);
173 + const listResponse = await this.client.mcp.list({
174 + page_no: params.page,
175 + limit: params.limit,
176 + toolkits: params.toolkits?.length > 0 ? params.toolkits.join(',') : undefined,
177 + auth_config_ids: params.authConfigs?.length > 0 ? params.authConfigs.join(',') : undefined,
178 + name: params.name,
179 });
180
344 - const connectedToolkits: Record<string, McpToolkitConnectionStatus> = {};
345 - let allToolkitsConnected = true;
346 -
347 - for (const toolkit of serverDetails.toolkits) {
348 - const connectedAccountId = connectedAccountsByToolkit.get(toolkit.toLowerCase());
349 -
350 - if (connectedAccountId) {
351 - connectedToolkits[toolkit] = {
352 - type: ConnectionStatus.CONNECTED,
353 - connected: true,
354 - toolkit,
355 - connectedAccountId,
356 - };
357 - } else {
358 - connectedToolkits[toolkit] = {
359 - type: ConnectionStatus.DISCONNECTED,
360 - connected: false,
361 - toolkit,
362 - };
363 - allToolkitsConnected = false;
364 - }
365 - }
366 -
367 - if (allToolkitsConnected) {
368 - return {
369 - type: ConnectionStatus.CONNECTED,
370 - connected: true,
371 - connectedToolkits,
372 - };
373 - } else {
374 - return {
375 - type: ConnectionStatus.DISCONNECTED,
376 - connected: false,
377 - connectedToolkits,
378 - };
379 - }
181 + const transformedListResponse = transform(listResponse)
182 + .with(MCPListResponseSchema)
183 + .using(raw => ({
184 + currentPage: raw.current_page,
185 + totalPages: raw.total_pages,
186 + items: raw.items.map(item => ({
187 + name: item.name,
188 + allowedTools: item.allowed_tools,
189 + id: item.id,
190 + authConfigIds: item.auth_config_ids,
191 + commands: item.commands,
192 + MCPUrl: item.mcp_url,
193 + toolkitIcons: item.toolkit_icons,
194 + serverInstanceCount: item.server_instance_count,
195 + toolkits: item.toolkits,
196 + })),
197 + }));
198 +
199 + return transformedListResponse;
200 }
201
202 /**
383 - * Get the connection parameters for a toolkit
384 - * @param {string} serverId - The UUID of the MCP server
385 - * @param {string} toolkit - The toolkit to get connection parameters for
386 - * @returns {Promise<ToolkitAuthFieldsResponse>} Connection parameters for the toolkit
387 - */
388 - async getConnectionParams(serverId: string, toolkit: string): Promise<ToolkitAuthFieldsResponse> {
389 - const mcpServerDetails = await this.get(serverId);
390 - const authConfigs = mcpServerDetails.authConfigIds
391 - ? await Promise.all(
392 - mcpServerDetails.authConfigIds.map(id => this.client.authConfigs.retrieve(id))
393 - )
394 - : [];
395 -
396 - const authConfig = authConfigs.find(config => config.toolkit.slug === toolkit);
397 - if (!authConfig) {
398 - throw new ValidationError('Auth config not found', {
399 - meta: { serverId: serverId, toolkit },
400 - });
401 - }
402 -
403 - const connectionParams = await this.toolkits.getConnectedAccountInitiationFields(
404 - toolkit,
405 - authConfig.auth_scheme!
406 - );
407 - return connectionParams;
408 - }
409 -
410 - /**
411 - * Authorize a user for a toolkit
412 - * @param {string} serverId - The UUID of the MCP server
413 - * @param {string} userId - The ID of the user to authorize
414 - * @param {string} toolkit - The toolkit to authorize
415 - * @returns {Promise<ConnectionRequest>} Connection request for the toolkit
416 - */
417 - async authorize(userId: string, serverId: string, toolkit: string): Promise<ConnectionRequest> {
418 - const mcpServerDetails = await this.get(serverId);
419 - const authConfigId = mcpServerDetails.authConfigIds?.[0];
420 - return this.toolkits.authorize(userId, toolkit, authConfigId);
421 - }
422 -
423 - /**
424 - * Get server URLs for an existing MCP server
425 - * @param {string} serverId - Server UUID
426 - * @param {string} userId - User ID to get server URLs for
427 - * @param {Object} [options] - Additional options for server configuration
428 - * @param {string[]} [options.limitTools] - Subset of tools to limit (from MCP config)
429 - * @param {boolean} [options.isChatAuth] - Whether to use chat-based authentication
430 - * @returns {Promise<TMcpResponse>} Transformed server URLs in provider-specific format
203 + * Retrieve detailed information about a specific MCP server by its ID
204 + * @param {string} serverId - The unique identifier of the MCP server to retrieve
205 + * @returns {Promise<MCPItem>} Complete MCP server details including configuration, tools, and metadata
206 *
207 * @example
208 * ```typescript
434 - * // Get URLs for an existing server with basic user ID
435 - * const urls = await composio.mcp.getServer("mcp_xyz", "hey@example.com");
209 + * // Get a specific MCP server by ID
210 + * const server = await composio.experimental.mcp.get("mcp_12345");
211 *
437 - * // Get URLs with additional options
438 - * const urls = await composio.mcp.getServer("mcp_xyz", "hey@example.com", {
439 - * limitTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
440 - * isChatAuth: true
441 - * });
212 + * console.log(server.name); // "My Personal MCP Server"
213 + * console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
214 + * console.log(server.toolkits); // ["github", "slack"]
215 + * console.log(server.serverInstanceCount); // 3
216 + *
217 + * // Access setup commands for different clients
218 + * console.log(server.commands.claude); // Claude setup command
219 + * console.log(server.commands.cursor); // Cursor setup command
220 + * console.log(server.commands.windsurf); // Windsurf setup command
221 + *
222 + * // Use the MCP URL for direct connections
223 + * const mcpUrl = server.MCPUrl;
224 * ```
225 *
226 + * @throws {ValidationError} When the server ID is invalid or server not found
227 */
445 - async getServer(
446 - serverId: string,
447 - userId: string,
448 - options?: {
449 - limitTools?: string[];
450 - isChatAuth?: boolean;
451 - }
452 - ): Promise<typeof this.TMcpResponse> {
453 - // Get server details first
454 - const serverDetails = await this.get(serverId);
455 -
456 - // Validate userId is provided
457 - if (!userId) {
458 - throw new ValidationError('User ID is required', {});
459 - }
460 -
461 - // Extract toolkits from server details
462 - const toolkits = serverDetails.toolkits || [];
463 -
464 - const connectedAccountIds = (
465 - await Promise.all(
466 - toolkits.map(toolkit =>
467 - this.client.connectedAccounts
468 - .list({
469 - user_ids: [userId],
470 - toolkit_slugs: [toolkit],
471 - statuses: ['ACTIVE'],
472 - })
473 - .then(res => res.items?.[0]?.id)
474 - )
475 - )
476 - ).filter(Boolean);
477 -
478 - // Generate URL with error handling
479 - let data;
480 - try {
481 - data = await this.client.mcp.generate.url({
482 - user_ids: [userId],
483 - // @TODO(utkarsh-dixit): Add support for this later
484 - connected_account_ids: [],
485 - mcp_server_id: serverId,
486 - managed_auth_by_composio:
487 - options?.isChatAuth ?? serverDetails.managedAuthViaComposio ?? false,
488 - });
489 - } catch (error) {
490 - throw new ValidationError('Failed to generate MCP server URL', {
491 - cause: error,
492 - });
493 - }
494 -
495 - // Validate the URL generation response
496 - const urlResponseResult = ComposioGenerateURLResponseSchema.safeParse(data);
497 - if (urlResponseResult.error) {
498 - throw new ValidationError('Failed to parse MCP URL generation response', {
499 - cause: urlResponseResult.error,
500 - });
501 - }
502 -
503 - // Transform to camelCase
504 - const camelCaseData = transformMcpGenerateUrlResponse(data);
505 -
506 - // Use the wrapMcpServerResponse method to transform the response
507 - return this.wrapMcpServerResponse(
508 - camelCaseData,
509 - serverDetails.name,
510 - connectedAccountIds,
511 - [userId],
512 - toolkits
513 - );
228 + async get(serverId: string): Promise<MCPItem> {
229 + const response = await this.client.mcp.retrieve(serverId);
230 + return transformMCPItemResponse(response);
231 }
232
233 /**
517 - * List MCP server configurations with filtering options
518 - * @param {Object} options - Filtering and pagination options
519 - * @param {number} [options.page] - Page number for pagination
520 - * @param {number} [options.limit] - Number of items per page
521 - * @param {string[]} [options.toolkits] - Filter servers by toolkit names
522 - * @param {string[]} [options.authConfigs] - Filter servers by auth config IDs
523 - * @param {string} [options.name] - Filter servers by name
524 - * @param {string} [options.user] - Filter servers by user ID
525 - * @returns {Promise<McpListResponse>} List of MCP servers matching the filters
234 + * Delete an MCP server configuration permanently
235 + * @param {string} serverId - The unique identifier of the MCP server to delete
236 + * @returns {Promise<{id: string; deleted: boolean}>} Confirmation object with server ID and deletion status
237 *
238 * @example
239 * ```typescript
529 - * // List all servers with pagination
530 - * const servers = await composio.mcp.list({
531 - * page: 1,
532 - * limit: 10
533 - * });
240 + * // Delete an MCP server by ID
241 + * const result = await composio.experimental.mcp.delete("mcp_12345");
242 *
535 - * // List Gmail and Supabase servers
536 - * const filteredServers = await composio.mcp.list({
537 - * toolkits: ['GMAIL', 'SUPABASE'],
538 - * authConfigIds: ['auth_123', 'auth_456']
539 - * });
540 - * ```
541 - */
542 - async list(options: {
543 - page?: number;
544 - limit?: number;
545 - toolkits?: string[];
546 - authConfigs?: string[];
547 - name?: string;
548 - }): Promise<McpListResponse> {
549 - // List MCP servers with error handling
550 - let listResponse;
551 - try {
552 - listResponse = await this.client.mcp.list({
553 - page_no: options.page || 1,
554 - limit: options.limit || 10,
555 - toolkits: options?.toolkits?.join(',') || undefined,
556 - auth_config_ids: options?.authConfigs?.join(',') || undefined,
557 - name: options?.name,
558 - });
559 - } catch (error) {
560 - throw new ValidationError('Failed to list MCP servers', {
561 - cause: error,
562 - });
563 - }
564 -
565 - // Validate the list response
566 - const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
567 - if (listResponseResult.error) {
568 - throw new ValidationError('Failed to parse MCP server list response', {
569 - cause: listResponseResult.error,
570 - });
571 - }
572 -
573 - // Transform the response to camelCase
574 - return transformMcpListResponse(listResponse);
575 - }
576 -
577 - /**
578 - * Get details of a specific MCP server
579 - * @param {string} serverId - Server UUID
580 - * @returns {Promise<McpRetrieveResponse>} Server details
243 + * if (result.deleted) {
244 + * console.log(`Server ${result.id} has been successfully deleted`);
245 + * } else {
246 + * console.log(`Failed to delete server ${result.id}`);
247 + * }
248 *
582 - * @example
583 - * ```typescript
584 - * const serverDetails = await composio.mcp.get('server-uuid');
585 - * ```
586 - */
587 - async get(serverId: string): Promise<McpRetrieveResponse> {
588 - // Retrieve MCP server with error handling
589 - let retrieveResponse;
590 - try {
591 - retrieveResponse = await this.client.mcp.retrieve(serverId);
592 - } catch (error) {
593 - throw new ValidationError('Failed to retrieve MCP server', {
594 - cause: error,
595 - });
596 - }
597 -
598 - // Validate the retrieve response
599 - const retrieveResponseResult = McpRetrieveResponseSchema.safeParse({
600 - ...retrieveResponse,
601 - mcpUrl: retrieveResponse.mcp_url,
602 - });
603 - if (retrieveResponseResult.error) {
604 - throw new ValidationError('Failed to parse MCP server retrieve response', {
605 - cause: retrieveResponseResult.error,
606 - });
607 - }
608 -
609 - // Transform the response to camelCase
610 - return transformMcpRetrieveResponse(retrieveResponse);
611 - }
612 -
613 - /**
614 - * Delete an MCP server
615 - * @param {string} serverId - Server UUID
616 - * @returns {Promise<McpDeleteResponse>} Deletion response
249 + * // Example with error handling
250 + * try {
251 + * const result = await composio.experimental.mcp.delete("mcp_12345");
252 + * console.log("Deletion successful:", result);
253 + * } catch (error) {
254 + * console.error("Failed to delete MCP server:", error.message);
255 + * }
256 *
618 - * @example
619 - * ```typescript
620 - * const result = await composio.mcp.delete('server-uuid');
257 + * // Delete and verify from list
258 + * await composio.experimental.mcp.delete("mcp_12345");
259 + * const servers = await composio.experimental.mcp.list({});
260 + * const serverExists = servers.items.some(server => server.id === "mcp_12345");
261 + * console.log("Server still exists:", serverExists); // Should be false
262 * ```
263 + *
264 + * @throws {ValidationError} When the server ID is invalid or server not found
265 + * @throws {Error} When the server cannot be deleted due to active connections or other constraints
266 + *
267 + * @warning This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
268 */
623 - async delete(serverId: string): Promise<McpDeleteResponse> {
624 - // Delete MCP server with error handling
625 - let deleteResponse;
626 - try {
627 - deleteResponse = await this.client.mcp.delete(serverId);
628 - } catch (error) {
629 - throw new ValidationError('Failed to delete MCP server', {
630 - cause: error,
631 - });
632 - }
633 -
634 - // Validate the delete response
635 - const deleteResponseResult = ComposioMcpDeleteResponseSchema.safeParse(deleteResponse);
636 - if (deleteResponseResult.error) {
637 - throw new ValidationError('Failed to parse MCP server delete response', {
638 - cause: deleteResponseResult.error,
639 - });
640 - }
641 -
642 - // Transform the response to camelCase
643 - return transformMcpDeleteResponse(deleteResponse);
269 + async delete(serverId: string): Promise<{ id: string; deleted: boolean }> {
270 + return await this.client.mcp.delete(serverId);
271 }
272
273 /**
647 - * Update an MCP server configuration
648 - * @param {string} id - Server UUID
649 - * @param {string} name - New unique name for the server
650 - * @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations
651 - * @param {MCPAuthOptions} [authOptions] - Updated authentication options
652 - * @returns {Promise<McpUpdateResponse>} Updated server details
274 + * Update an existing MCP server configuration with new settings
275 + * @param {string} serverId - The unique identifier of the MCP server to update
276 + * @param {Object} config - Update configuration parameters
277 + * @param {string} [config.name] - New name for the MCP server
278 + * @param {Array} [config.toolkits] - Updated toolkit configurations
279 + * @param {string} [config.toolkits[].toolkit] - Toolkit identifier (e.g., "github", "slack")
280 + * @param {string} [config.toolkits[].authConfigId] - Auth configuration ID for the toolkit
281 + * @param {string[]} [config.toolkits[].allowedTools] - Specific tools to enable for this toolkit
282 + * @param {boolean} [config.manuallyManageConnections] - Whether to manually manage account connections
283 + * @returns {Promise<MCPItem>} Updated MCP server configuration with all details
284 *
285 * @example
286 * ```typescript
656 - * const updatedServer = await composio.mcp.update(
657 - * "server-uuid",
658 - * "my-updated-server",
659 - * [
287 + * // Update server name only
288 + * const updatedServer = await composio.experimental.mcp.update("mcp_12345", {
289 + * name: "My Updated MCP Server"
290 + * });
291 + *
292 + * // Update toolkits and tools
293 + * const serverWithNewTools = await composio.experimental.mcp.update("mcp_12345", {
294 + * toolkits: [
295 * {
661 - * toolkit: "GMAIL",
662 - * authConfigId: "ac_sdhkjfhjksdk",
663 - * allowedTools: ["GMAIL_FETCH_EMAILS"],
296 + * toolkit: "github",
297 + * authConfigId: "auth_abc123",
298 + * allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
299 * },
665 - * ],
666 - * {
667 - * isChatAuth: true,
668 - * }
669 - * );
670 - * ```
671 - */
672 - async update(
673 - serverId: string,
674 - name: string,
675 - toolkitConfigs: MCPToolkitConfig[],
676 - authOptions?: MCPAuthOptions
677 - ): Promise<McpUpdateResponse> {
678 - // Validate inputs using Zod schemas
679 - this.validateInputs(toolkitConfigs, authOptions);
680 -
681 - const toolkits = toolkitConfigs.map(config => config.toolkit);
682 -
683 - // Update MCP server with error handling
684 - let updateResponse;
685 - try {
686 - updateResponse = await this.client.mcp.update(serverId, {
687 - name,
688 - toolkits: toolkits,
689 - allowed_tools: toolkitConfigs.flatMap(config => config.allowedTools),
690 - managed_auth_via_composio: authOptions?.isChatAuth || false,
691 - });
692 - } catch (error) {
693 - throw new ValidationError('Failed to update MCP server', {
694 - cause: error,
695 - });
696 - }
697 -
698 - // Validate the update response
699 - const updateResponseResult = ComposioMcpUpdateResponseSchema.safeParse(updateResponse);
700 - if (updateResponseResult.error) {
701 - throw new ValidationError('Failed to parse MCP server update response', {
702 - cause: updateResponseResult.error,
703 - });
704 - }
705 -
706 - // Transform the response to camelCase
707 - return transformMcpUpdateResponse(updateResponse);
708 - }
709 -
710 - /**
711 - * Generate URL for an MCP server
712 - * @param {string} serverId - Server UUID
713 - * @param {GenerateURLParams} params - Parameters for URL generation
714 - * @returns {Promise<GenerateURLResponse>} Generated URL response
300 + * {
301 + * toolkit: "slack",
302 + * authConfigId: "auth_xyz789",
303 + * allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]
304 + * }
305 + * ]
306 + * });
307 *
716 - * @example
717 - * ```typescript
718 - * const urlResponse = await composio.mcp.generateUrl('server-uuid', {
719 - * userIds: ['user123'],
720 - * connectedAccountIds: ['account456'],
721 - * isChatAuth: true
308 + * // Update connection management setting
309 + * const serverWithManualAuth = await composio.experimental.mcp.update("mcp_12345", {
310 + * name: "Manual Auth Server",
311 + * manuallyManageConnections: true
312 + * });
313 + *
314 + * // Complete update example
315 + * const fullyUpdatedServer = await composio.experimental.mcp.update("mcp_12345", {
316 + * name: "Production MCP Server",
317 + * toolkits: [
318 + * {
319 + * toolkit: "gmail",
320 + * authConfigId: "auth_gmail_prod",
321 + * }
322 + * ],
323 + * allowedTools: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"]
324 + * manuallyManageConnections: false
325 * });
326 + *
327 + * console.log("Updated server:", fullyUpdatedServer.name);
328 + * console.log("New tools:", fullyUpdatedServer.allowedTools);
329 * ```
330 + *
331 + * @throws {ValidationError} When the update parameters are invalid or malformed
332 + * @throws {Error} When the server ID doesn't exist or update fails
333 + *
334 + * @note Only provided fields will be updated. Omitted fields will retain their current values.
335 + * @note When updating toolkits, the entire toolkit configuration is replaced, not merged.
336 */
725 - async generateUrl(serverId: string, params: GenerateURLParams): Promise<GenerateURLResponse> {
726 - // Validate parameters using Zod schema (snake_case)
727 - const paramsResult = GenerateURLParamsSchema.safeParse(params);
728 - if (paramsResult.error) {
729 - throw new ValidationError('Failed to parse generateUrl parameters', {
730 - cause: paramsResult.error,
731 - });
732 - }
733 -
734 - // No transformation needed - params are already in snake_case
735 - let urlResponse;
736 - try {
737 - urlResponse = await this.client.mcp.generate.url({
738 - mcp_server_id: serverId,
739 - user_ids: params.userIds,
740 - connected_account_ids: params.connectedAccountIds,
741 - managed_auth_by_composio: params.composioManagedAuth,
742 - });
743 - } catch (error) {
744 - throw new ValidationError('Failed to generate MCP URL', {
337 + async update(serverId: string, config: MCPUpdateParams): Promise<MCPItem> {
338 + const { data: params, error } = MCPUpdateParamsSchema.safeParse(config);
339 + if (error) {
340 + throw new ValidationError('Failed to validate update params', {
341 cause: error,
342 });
343 }
344
749 - // Validate the response
750 - const responseResult = ComposioGenerateURLResponseSchema.safeParse(urlResponse);
751 - if (responseResult.error) {
752 - throw new ValidationError('Failed to parse MCP URL generation response', {
753 - cause: responseResult.error,
754 - });
755 - }
756 -
757 - // Transform the response to camelCase
758 - return transformMcpGenerateUrlResponse(urlResponse);
759 - }
345 + const toolkits: string[] = [];
346 + const auth_config_ids: string[] = [];
347 + const custom_tools: string[] | undefined = params.allowedTools ?? undefined;
348
761 - /**
762 - * Transform MCP URL response into the appropriate format.
763 - * If the provider has a custom transform method, use it.
764 - * Otherwise, use the default transformation.
765 - *
766 - * @param data - The MCP URL response data (in camelCase)
767 - * @param serverName - Name of the MCP server
768 -
769 - * @returns Transformed response in appropriate format
770 - * @deprecated
771 - */
772 - private wrapMcpServerResponse(
773 - data: McpUrlResponseCamelCase,
774 - serverName: string,
775 - connectedAccountIds?: string[],
776 - userIds?: string[],
777 - toolkits?: string[]
778 - ): typeof this.TMcpResponse {
779 - // Check if provider has a custom transform method
780 - if (this.provider && typeof this.provider.wrapMcpServerResponse === 'function') {
781 - // Convert to array of name and url based on connected accounts or user ids
782 - let snakeCaseData: McpUrlResponse;
783 -
784 - if (data.connectedAccountUrls?.length) {
785 - snakeCaseData = data.connectedAccountUrls.map((url, index) => ({
786 - name: serverName + '-' + connectedAccountIds?.[index],
787 - url: url,
788 - }));
789 - } else if (data.userIdsUrl?.length) {
790 - snakeCaseData = data.userIdsUrl.map((url, index) => ({
791 - name: serverName + '-' + userIds?.[index],
792 - url: url,
793 - }));
794 - } else {
795 - snakeCaseData = [
796 - {
797 - name: serverName,
798 - url: data.mcpUrl,
799 - },
800 - ];
349 + // extract all the toolkits, authconfigs, and allowed tools to separate slugs
350 + params.toolkits?.forEach(toolkit => {
351 + if (typeof toolkit === 'string') {
352 + toolkits.push(toolkit);
353 + } else if (toolkit.toolkit) {
354 + toolkits.push(toolkit.toolkit);
355 + } else if (toolkit.authConfigId) {
356 + auth_config_ids.push(toolkit.authConfigId);
357 }
802 -
803 - const transformed = this.provider.wrapMcpServerResponse(snakeCaseData);
804 - return transformed as typeof this.TMcpResponse;
805 - }
806 -
807 - // eslint-disable-next-line @typescript-eslint/no-this-alias
808 - const self = this;
809 -
810 - // Default transformation
811 - if (connectedAccountIds?.length && data.connectedAccountUrls) {
812 - return data.connectedAccountUrls.map((url: string, index: number) => ({
813 - url: new URL(url),
814 - name: `${serverName}-${connectedAccountIds[index]}`,
815 - toolkit: toolkits?.[index],
816 - })) as typeof self.TMcpResponse;
817 - } else if (userIds?.length && data.userIdsUrl) {
818 - return data.userIdsUrl.map((url: string, index: number) => ({
819 - url: new URL(url),
820 - name: `${serverName}-${userIds[index]}`,
821 - toolkit: toolkits?.[index],
822 - })) as typeof self.TMcpResponse;
823 - }
824 - return {
825 - url: new URL(data.mcpUrl),
826 - name: serverName,
827 - } as typeof self.TMcpResponse;
358 + });
359 + const response = await this.client.mcp.update(serverId, {
360 + ...{ name: params.name ?? undefined },
361 + ...(params.toolkits
362 + ? {
363 + custom_tools: custom_tools,
364 + toolkits: toolkits,
365 + auth_config_ids: auth_config_ids,
366 + }
367 + : {}),
368 + ...{ managed_auth_via_composio: params.manuallyManageConnections ?? undefined },
369 + });
370 + return transformMCPItemResponse(response);
371 }
372
373 /**
831 - * Get details of a specific MCP server by name
832 - * @param {string} name - Server name
833 - * @returns {Promise<McpRetrieveResponse>} Server details
834 - * @throws {ValidationError} If no server found with the given name
835 - * @throws {ValidationError} If multiple servers found with the same name
374 + * Get server URLs for an existing MCP server.
375 + * The response is wrapped according to the provider's specifications.
376 *
377 * @example
378 * ```typescript
839 - * const serverDetails = await composio.mcp.getByName('my-gmail-server');
379 + * import { Composio } from "@composio/code";
380 + *
381 + * const composio = new Composio();
382 + * const mcp = await composio.experimental.mcp.generate("default", "<mcp_config_id>");
383 * ```
384 + *
385 + * @param userId {string} external user id from your database for whom you want the server for
386 + * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
387 + * @param options {object} additional options
388 + * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
389 */
842 - async getByName(serverName: string): Promise<McpRetrieveResponse> {
843 - if (!serverName) {
844 - throw new ValidationError('Server name is required', {});
845 - }
846 -
847 - // List MCP servers filtered by name
848 - let listResponse;
849 - try {
850 - listResponse = await this.client.mcp.list({
851 - name: serverName,
852 - limit: 10,
853 - });
854 - } catch (error) {
855 - logger.error(error);
856 - throw new ValidationError('Failed to search MCP servers by name', {
857 - cause: error,
390 + async generate(
391 + userId: string,
392 + mcpConfigId: string,
393 + options?: MCPGetInstanceParams
394 + ): Promise<MCPServerInstance> {
395 + const server = await this.client.mcp.retrieve(mcpConfigId);
396 + const params = MCPGetInstanceParamsSchema.safeParse(
397 + options ?? { manuallyManageConnections: false }
398 + );
399 + if (params.error) {
400 + throw new ValidationError('Invalid params passed for Get Instance Params', {
401 + cause: params.error,
402 });
403 }
404
861 - // Validate the list response
862 - const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
863 - if (listResponseResult.error) {
864 - throw new ValidationError('Failed to parse MCP server list response', {
865 - cause: listResponseResult.error,
866 - });
867 - }
405 + const urlResponse = await this.client.mcp.generate.url({
406 + mcp_server_id: mcpConfigId,
407 + user_ids: [userId],
408 + managed_auth_by_composio: options?.manuallyManageConnections ? false : true,
409 + });
410
869 - const servers = listResponse.items || [];
411 + const userIdsURL = urlResponse.user_ids_url[0];
412 + const serverInstance = MCPServerInstanceSchema.safeParse({
413 + id: server.id,
414 + name: server.name,
415 + type: 'streamable_http' as const,
416 + url: userIdsURL,
417 + userId: userId,
418 + allowedTools: server.allowed_tools,
419 + authConfigs: server.auth_config_ids,
420 + });
421
871 - if (servers.length === 0) {
872 - throw new ValidationError(`MCP server with name '${serverName}' not found`, {
873 - meta: { serverName: serverName },
422 + if (serverInstance.error) {
423 + throw new ValidationError('Failed to parse MCP server instance', {
424 + cause: serverInstance.error,
425 });
426 }
427
877 - // Get the full server details using the server ID
878 - return this.get(servers[0].id);
428 + return serverInstance.data;
429 }
430 }
ts/packages/core/src/models/ToolRouter.ts
+22 -46
@@ -36,6 +36,8 @@ import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types';
36 import { Tools } from './Tools';
37 import {
38 ExecuteToolModifiers,
39 + SessionExecuteMetaModifiers,
40 + SessionMetaToolOptions,
41 ProviderOptions,
42 TransformToolSchemaModifier,
43 } from '../types/modifiers.types';
@@ -48,6 +50,9 @@ import { ValidationError } from '../errors';
50 import {
51 transformToolRouterTagsParams,
52 transformToolRouterToolsParams,
53 + transformToolRouterManageConnectionsParams,
54 + transformToolRouterWorkbenchParams,
55 + transformToolRouterToolkitsParams,
56 } from '../lib/toolRouterParams';
57
58 export class ToolRouter<
@@ -164,31 +169,23 @@ export class ToolRouter<
169 * Creates a function that wraps the tools based on the provider.
170 * The returned tools will be of the type the frameworks expects.
171 *
167 - * @param userId - The user id to get the tools for
168 - * @param tools - The tools to wrap
169 - * @returns A function that wraps the tools based on the provider.
172 + * @param sessionId - The session id to get the tools for
173 + * @returns A function that wraps the tools based on the provider with session-specific modifiers.
174 */
175 private createToolsFn = (
172 - sessionId: string,
173 - toolSlugs: string[]
174 - ): ((modifiers?: ProviderOptions<TProvider>) => Promise<ReturnType<TProvider['wrapTools']>>) => {
175 - return async (modifiers?: ProviderOptions<TProvider>) => {
176 + sessionId: string
177 + ): ((modifiers?: SessionMetaToolOptions) => Promise<ReturnType<TProvider['wrapTools']>>) => {
178 + return async (modifiers?: SessionMetaToolOptions) => {
179 const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
177 - const tools = await ToolsModel.getRawComposioTools(
178 - {
179 - tools: toolSlugs,
180 - },
180 + const tools = await ToolsModel.getRawToolRouterMetaTools(
181 + sessionId,
182 modifiers?.modifySchema
183 ? {
184 modifySchema: modifiers?.modifySchema,
185 }
186 : undefined
187 );
187 - const wrappedTools = ToolsModel.wrapToolsForToolRouter(
188 - sessionId,
189 - tools,
190 - modifiers as ExecuteToolModifiers
191 - );
188 + const wrappedTools = ToolsModel.wrapToolsForToolRouter(sessionId, tools, modifiers);
189 return wrappedTools as ReturnType<TProvider['wrapTools']>;
190 };
191 };
@@ -256,38 +253,17 @@ export class ToolRouter<
253 ): Promise<ToolRouterSession<TToolCollection, TTool, TProvider>> {
254 const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});
255
259 - const manageConnectedAccounts =
260 - typeof routerConfig.manageConnections === 'boolean'
261 - ? routerConfig.manageConnections
262 - : (routerConfig.manageConnections?.enable ?? true);
263 -
264 - const toolkits = Array.isArray(routerConfig.toolkits)
265 - ? { enable: routerConfig.toolkits }
266 - : routerConfig.toolkits;
267 -
268 - const tags = transformToolRouterTagsParams(routerConfig.tags);
269 - const tools = transformToolRouterToolsParams(routerConfig.tools);
270 -
256 const payload: SessionCreateParams = {
257 user_id: userId,
273 - toolkits,
258 auth_configs: routerConfig.authConfigs,
259 connected_accounts: routerConfig.connectedAccounts,
276 - tools: tools,
277 - tags: tags,
278 - manage_connections: {
279 - enable: manageConnectedAccounts,
280 - callback_url:
281 - typeof routerConfig.manageConnections === 'object'
282 - ? routerConfig.manageConnections.callbackUrl
283 - : undefined,
284 - },
285 - workbench: routerConfig.workbench
286 - ? {
287 - enable_proxy_execution: routerConfig.workbench?.enableProxyExecution,
288 - auto_offload_threshold: routerConfig.workbench?.autoOffloadThreshold,
289 - }
290 - : undefined,
260 + toolkits: transformToolRouterToolkitsParams(routerConfig.toolkits),
261 + tools: transformToolRouterToolsParams(routerConfig.tools),
262 + tags: transformToolRouterTagsParams(routerConfig.tags),
263 + manage_connections: transformToolRouterManageConnectionsParams(
264 + routerConfig.manageConnections
265 + ),
266 + workbench: transformToolRouterWorkbenchParams(routerConfig.workbench),
267 };
268
269 const session = await this.client.toolRouter.session.create(payload);
@@ -295,7 +271,7 @@ export class ToolRouter<
271 return {
272 sessionId: session.session_id,
273 mcp: this.createMCPServerConfig(session.mcp),
298 - tools: this.createToolsFn(session.session_id, session.tool_router_tools),
274 + tools: this.createToolsFn(session.session_id),
275 authorize: this.createAuthorizeFn(session.session_id),
276 toolkits: this.createToolkitsFn(session.session_id),
277 };
@@ -323,7 +299,7 @@ export class ToolRouter<
299 return {
300 sessionId: session.session_id,
301 mcp: this.createMCPServerConfig(session.mcp),
326 - tools: this.createToolsFn(session.session_id, session.tool_router_tools),
302 + tools: this.createToolsFn(session.session_id),
303 authorize: this.createAuthorizeFn(session.session_id),
304 toolkits: this.createToolkitsFn(session.session_id),
305 };
ts/packages/core/src/models/Tools.ts
+76 -38
@@ -32,6 +32,7 @@ import {
32 afterExecuteModifier,
33 beforeExecuteModifier,
34 ExecuteToolModifiers,
35 + SessionExecuteMetaModifiers,
36 ProviderOptions,
37 TransformToolSchemaModifier,
38 } from '../types/modifiers.types';
@@ -395,6 +396,48 @@ export class Tools<
396 return modifiedTools;
397 }
398
399 + /**
400 + * Fetches the meta tools for a tool router session.
401 + * This method fetches the meta tools from the Composio API and transforms them to the expected format.
402 + * It provides access to the underlying meta tool data without provider-specific wrapping.
403 + *
404 + * @param sessionId {string} The session id to get the meta tools for
405 + * @param options {SchemaModifierOptions} Optional configuration for tool retrieval
406 + * @param {TransformToolSchemaModifier} [options.modifySchema] - Function to transform the tool schema
407 + * @returns {Promise<ToolList>} The list of meta tools
408 + *
409 + * @example
410 + * ```typescript
411 + * const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123');
412 + * console.log(metaTools);
413 + * ```
414 + */
415 + async getRawToolRouterMetaTools(
416 + sessionId: string,
417 + options?: SchemaModifierOptions
418 + ): Promise<ToolList> {
419 + const tools = await this.client.toolRouter.session.tools(sessionId);
420 + let modifiedTools = tools.items.map(tool => this.transformToolCases(tool));
421 + // apply local modifiers if they are provided
422 + if (options?.modifySchema) {
423 + const modifier = options.modifySchema;
424 + if (typeof modifier === 'function') {
425 + const modifiedPromises = modifiedTools.map(tool =>
426 + modifier({
427 + toolSlug: tool.slug,
428 + toolkitSlug: tool.toolkit?.slug ?? 'unknown',
429 + schema: tool,
430 + })
431 + );
432 + modifiedTools = await Promise.all(modifiedPromises);
433 + } else {
434 + throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
435 + }
436 + }
437 +
438 + return modifiedTools;
439 + }
440 +
441 /**
442 * Retrieves a specific tool by its slug from the Composio API.
443 *
@@ -635,13 +678,13 @@ export class Tools<
678 *
679 * @param {string} sessionId - The session id to execute the tool for
680 * @param {Tool[]} tools - The tools to wrap
638 - * @param {ExecuteToolModifiers} modifiers - The modifiers to apply to the tool
681 + * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
682 * @returns {Tool[]} The wrapped tools
683 */
684 wrapToolsForToolRouter(
685 sessionId: string,
686 tools: Tool[],
644 - modifiers?: ExecuteToolModifiers
687 + modifiers?: SessionExecuteMetaModifiers
688 ): Tool[] {
689 const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, modifiers);
690 return this.provider.wrapTools(tools, executeToolFn) as Tool[];
@@ -679,12 +722,12 @@ export class Tools<
722 * Creates a function that executes a tool for a tool router session
723 *
724 * @param {string} sessionId - The session id to execute the tool for
682 - * @param {ExecuteToolModifiers} modifiers - The modifiers to apply to the tool
725 + * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
726 * @returns {ExecuteToolFn} The execute tool function
727 */
728 private createExecuteToolFnForToolRouter(
729 sessionId: string,
687 - modifiers?: ExecuteToolModifiers
730 + modifiers?: SessionExecuteMetaModifiers
731 ): ExecuteToolFn {
732 const executeToolFn = async (
733 toolSlug: string,
@@ -876,13 +919,13 @@ export class Tools<
919 * @param {ToolExecuteMetaParams} body - The execution parameters
920 * @param {string} body.sessionId - The session id to execute the tool for
921 * @param {Record<string, unknown>} body.arguments - The input to pass to the tool
879 - * @param {ExecuteToolModifiers} modifiers - The modifiers to apply to the tool
922 + * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
923 * @returns {Promise<ToolExecuteResponse>} The response from the tool execution
924 */
925 async executeMetaTool(
926 toolSlug: string,
927 body: ToolExecuteMetaParams,
885 - modifiers?: ExecuteToolModifiers
928 + modifiers?: SessionExecuteMetaModifiers
929 ): Promise<ToolExecuteResponse> {
930 const executeMetaParams = ToolExecuteMetaParamsSchema.safeParse(body);
931 if (!executeMetaParams.success) {
@@ -891,46 +934,41 @@ export class Tools<
934 });
935 }
936
894 - const tool = await this.getRawComposioToolBySlug(toolSlug);
895 - if (!tool) {
896 - throw new ComposioToolNotFoundError(`Tool ${toolSlug} not found`, {
897 - meta: {
898 - slug: toolSlug,
899 - sessionId: body.sessionId,
900 - },
937 + // Apply beforeExecute modifier if provided
938 + let modifiedParams = body.arguments ?? {};
939 + if (modifiers?.beforeExecute) {
940 + modifiedParams = await modifiers.beforeExecute({
941 + toolSlug,
942 + toolkitSlug: 'composio',
943 + sessionId: body.sessionId,
944 + params: modifiedParams,
945 });
946 }
947
904 - const params = await this.applyBeforeExecuteModifiers(
905 - tool,
906 - {
907 - toolSlug: toolSlug,
908 - toolkitSlug: tool.toolkit?.slug ?? 'unknown',
909 - params: body.arguments ?? {},
910 - },
911 - modifiers?.beforeExecute
912 - );
913 -
948 + // Execute the meta tool
949 const response = await this.client.toolRouter.session.executeMeta(body.sessionId, {
950 // assert this because backend might keep adding more tool slugs
951 slug: toolSlug as SessionExecuteMetaParams['slug'],
917 - arguments: params,
952 + arguments: modifiedParams,
953 });
954
920 - const result = await this.applyAfterExecuteModifiers(
921 - tool,
922 - {
923 - toolSlug: toolSlug,
924 - toolkitSlug: tool.toolkit?.slug ?? 'unknown',
925 - result: {
926 - data: response.data,
927 - error: response.error,
928 - successful: !response.error,
929 - logId: response.log_id,
930 - },
931 - },
932 - modifiers?.afterExecute
933 - );
955 + // Prepare the result
956 + let result: ToolExecuteResponse = {
957 + data: response.data,
958 + error: response.error,
959 + successful: !response.error,
960 + logId: response.log_id,
961 + };
962 +
963 + // Apply afterExecute modifier if provided
964 + if (modifiers?.afterExecute) {
965 + result = await modifiers.afterExecute({
966 + toolSlug,
967 + toolkitSlug: 'composio',
968 + sessionId: body.sessionId,
969 + result,
970 + });
971 + }
972
973 return result;
974 }
ts/packages/core/src/types/modifiers.types.ts
+167 -1
@@ -1,5 +1,5 @@
1 import { BaseAgenticProvider, BaseComposioProvider } from '../provider/BaseProvider';
2 -import { ToolExecuteParams, ToolExecuteResponse, Tool } from './tool.types';
2 +import { ToolExecuteParams, ToolExecuteResponse, Tool, ToolExecuteMetaParams } from './tool.types';
3
4 /**
5 * Modifier for altering the tool execute parameters before execution.
@@ -392,6 +392,131 @@ export type ExecuteToolModifiers = {
392 afterExecute?: afterExecuteModifier;
393 };
394
395 +/**
396 + * Type alias for meta tool execution arguments.
397 + * Represents the arguments passed to a meta tool during execution.
398 + * This is derived from ToolExecuteMetaParams but guaranteed to be non-null.
399 + */
400 +export type MetaToolArguments = NonNullable<ToolExecuteMetaParams['arguments']>;
401 +
402 +/**
403 + * Modifier for altering the meta tool execute parameters before execution in a session context.
404 + *
405 + * This function is specifically designed for meta tools executed within a tool router session,
406 + * allowing you to intercept and modify the parameters before execution. Meta tools are
407 + * grouped under the 'composio' toolkit slug for organizational purposes.
408 + *
409 + * @param {string} toolSlug - The slug identifier of the meta tool being executed
410 + * @param {string} toolkitSlug - The toolkit slug (always 'composio' for meta tools)
411 + * @param {string} sessionId - The session ID for the tool router context
412 + * @param {MetaToolArguments} params - The parameters being passed to the meta tool
413 + * @returns {MetaToolArguments} The modified parameters
414 + *
415 + * @example
416 + * ```typescript
417 + * const beforeExecuteMeta = ({ toolSlug, toolkitSlug, sessionId, params }) => {
418 + * console.log(`Executing ${toolkitSlug} meta tool ${toolSlug} in session ${sessionId}`);
419 + *
420 + * // Add or modify parameters
421 + * return {
422 + * ...params,
423 + * timestamp: new Date().toISOString()
424 + * };
425 + * };
426 + * ```
427 + */
428 +export type beforeExecuteMetaModifier = (context: {
429 + toolSlug: string;
430 + toolkitSlug: string;
431 + sessionId: string;
432 + params: MetaToolArguments;
433 +}) => Promise<MetaToolArguments> | MetaToolArguments;
434 +
435 +/**
436 + * Modifier for altering the meta tool execution response after execution completes in a session context.
437 + *
438 + * This function is specifically designed for meta tools executed within a tool router session,
439 + * allowing you to intercept and modify the response after execution. This is useful for
440 + * session-specific transformations, logging, or error handling.
441 + *
442 + * @param {string} toolSlug - The slug identifier of the meta tool that was executed
443 + * @param {string} toolkitSlug - The toolkit slug (always 'composio' for meta tools)
444 + * @param {string} sessionId - The session ID for the tool router context
445 + * @param {ToolExecuteResponse} result - The original execution response
446 + * @returns {ToolExecuteResponse} The modified execution response
447 + *
448 + * @example
449 + * ```typescript
450 + * const afterExecuteMeta = ({ toolSlug, toolkitSlug, sessionId, result }) => {
451 + * // Log session-specific execution
452 + * console.log(`${toolkitSlug} meta tool ${toolSlug} completed in session ${sessionId}`);
453 + *
454 + * if (!result.successful) {
455 + * console.error(`Session ${sessionId} error:`, result.error);
456 + * }
457 + *
458 + * return result;
459 + * };
460 + * ```
461 + */
462 +export type afterExecuteMetaModifier = (context: {
463 + toolSlug: string;
464 + toolkitSlug: string;
465 + sessionId: string;
466 + result: ToolExecuteResponse;
467 +}) => Promise<ToolExecuteResponse> | ToolExecuteResponse;
468 +
469 +/**
470 + * Modifiers specifically for meta tool execution within a session context.
471 + *
472 + * These modifiers are designed for tool router session-based meta tool execution,
473 + * providing hooks to intercept and modify both the request and response of meta tools.
474 + * Meta tools are grouped under the 'composio' toolkit for organizational consistency.
475 + *
476 + * @example
477 + * ```typescript
478 + * const metaModifiers: SessionExecuteMetaModifiers = {
479 + * beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {
480 + * // Add session tracking
481 + * console.log(`Executing ${toolkitSlug}/${toolSlug}`);
482 + * return {
483 + * ...params,
484 + * sessionMetadata: {
485 + * startTime: Date.now(),
486 + * sessionId
487 + * }
488 + * };
489 + * },
490 + *
491 + * afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => {
492 + * // Transform session results
493 + * return {
494 + * ...result,
495 + * sessionInfo: {
496 + * sessionId,
497 + * toolSlug,
498 + * toolkitSlug,
499 + * completedAt: new Date().toISOString()
500 + * }
501 + * };
502 + * }
503 + * };
504 + * ```
505 + */
506 +export type SessionExecuteMetaModifiers = {
507 + /**
508 + * Function to intercept and modify meta tool execution parameters before the tool is executed.
509 + * This allows customizing the request based on session-specific needs.
510 + */
511 + beforeExecute?: beforeExecuteMetaModifier;
512 +
513 + /**
514 + * Function to intercept and modify meta tool execution responses after the tool has executed.
515 + * This allows transforming the response or implementing custom session-specific handling.
516 + */
517 + afterExecute?: afterExecuteMetaModifier;
518 +};
519 +
520 /**
521 * Options for agentic tool configuration.
522 *
@@ -430,6 +555,47 @@ export type ExecuteToolModifiers = {
555 */
556 export type AgenticToolOptions = ToolOptions & ExecuteToolModifiers;
557
558 +/**
559 + * Options for session-based meta tool configuration in tool router contexts.
560 + *
561 + * These options combine schema modification capabilities with session-specific execution
562 + * behavior customization, providing control over both the definition and execution
563 + * of meta tools within a tool router session. Meta tools are grouped under the 'composio' toolkit.
564 + *
565 + * @example
566 + * ```typescript
567 + * // Configure meta tools with schema and session-specific execution modifications
568 + * const sessionTools = await toolRouter.getTools(sessionId, {
569 + * modifySchema: (context) => {
570 + * return {
571 + * ...context.schema,
572 + * description: `Session-specific ${context.toolSlug}`
573 + * };
574 + * },
575 + *
576 + * // Intercept before meta tool execution
577 + * beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {
578 + * // Add session tracking
579 + * console.log(`Executing ${toolkitSlug}/${toolSlug}`);
580 + * return {
581 + * ...params,
582 + * sessionMetadata: { sessionId, timestamp: Date.now() }
583 + * };
584 + * },
585 + *
586 + * // Transform after meta tool execution
587 + * afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => {
588 + * // Log session results
589 + * if (!result.successful) {
590 + * logSessionError(sessionId, toolkitSlug, toolSlug, result.error);
591 + * }
592 + * return result;
593 + * }
594 + * });
595 + * ```
596 + */
597 +export type SessionMetaToolOptions = ToolOptions & SessionExecuteMetaModifiers;
598 +
599 /**
600 * Provider-specific options determined by the type of provider being used.
601 *
ts/packages/core/src/types/toolRouter.types.ts
+8 -2
@@ -1,6 +1,6 @@
1 import z from 'zod/v3';
2 import { BaseComposioProvider } from '../provider/BaseProvider';
3 -import { ExecuteToolModifiers, ProviderOptions } from './modifiers.types';
3 +import { SessionMetaToolOptions } from './modifiers.types';
4 import { ConnectionRequest } from './connectionRequest.types';
5
6 export const MCPServerTypeSchema = z.enum(['http', 'sse']);
@@ -20,6 +20,12 @@ export const ToolRouterConfigManageConnectionsSchema = z
20 .string()
21 .optional()
22 .describe('The callback uri to use in the tool router session'),
23 + waitForConnections: z
24 + .boolean()
25 + .optional()
26 + .describe(
27 + 'Whether to wait for users to finish authenticating connections before proceeding to the next step. Defaults to false, if set to true, a wait for connections tool call will happen and finish when the connections are ready'
28 + ),
29 })
30 .strict();
31
@@ -264,7 +270,7 @@ export type ToolRouterToolsFn<
270 TToolCollection,
271 TTool,
272 TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
267 -> = (modifiers?: ProviderOptions<TProvider>) => Promise<ReturnType<TProvider['wrapTools']>>;
273 +> = (modifiers?: SessionMetaToolOptions) => Promise<ReturnType<TProvider['wrapTools']>>;
274
275 export type ToolRouterAuthorizeFn = (
276 toolkit: string,
ts/packages/core/test/models/mcp.test.ts
+228 -536
@@ -3,18 +3,6 @@ import { MCP } from '../../src/models/MCP';
3 import ComposioClient from '@composio/client';
4 import { telemetry } from '../../src/telemetry/Telemetry';
5 import { ValidationError } from '../../src/errors/ValidationErrors';
6 -import { BaseAgenticProvider } from '../../src/provider/BaseProvider';
7 -import { Tool } from '../../src/types/tool.types';
8 -import { ExecuteToolFn } from '../../src/types/provider.types';
9 -import { McpUrlResponse } from '../../src/types/mcp.types';
10 -import {
11 - transformMcpCreateResponse,
12 - transformMcpListResponse,
13 - transformMcpRetrieveResponse,
14 - transformMcpDeleteResponse,
15 - transformMcpUpdateResponse,
16 - transformMcpGenerateUrlResponse,
17 -} from '../../src/utils/transformers/mcp';
6
7 // Mock dependencies
8 vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -23,83 +11,7 @@ vi.mock('../../src/telemetry/Telemetry', () => ({
11 },
12 }));
13
26 -// Define types for mock responses
27 -interface MockItem {
28 - id: string;
29 - name: string;
30 - created_at?: string;
31 - updated_at?: string;
32 - status?: string;
33 -}
34 -
35 -interface MockListResponse {
36 - items?: MockItem[];
37 -}
38 -
39 -vi.mock('../../src/utils/transformers/mcp', () => ({
40 - transformMcpCreateResponse: vi.fn(response => ({
41 - id: response.id,
42 - name: response.name,
43 - createdAt: response.created_at,
44 - updatedAt: response.updated_at,
45 - status: response.status,
46 - mcpUrl: response.mcp_url || 'https://mcp.example.com/server',
47 - commands: response.commands || {
48 - claude: 'claude-command',
49 - cursor: 'cursor-command',
50 - windsurf: 'windsurf-command',
51 - },
52 - toolkits: response.toolkits || [],
53 - tools: response.tools || [],
54 - managedAuthViaComposio: response.managed_auth_via_composio || false,
55 - })),
56 - transformMcpListResponse: vi.fn((response: MockListResponse) => ({
57 - items: response.items?.map(item => ({
58 - id: item.id,
59 - name: item.name,
60 - createdAt: item.created_at,
61 - updatedAt: item.updated_at,
62 - status: item.status,
63 - })),
64 - })),
65 - transformMcpRetrieveResponse: vi.fn(response => ({
66 - id: response.id,
67 - name: response.name,
68 - createdAt: response.created_at,
69 - updatedAt: response.updated_at,
70 - status: response.status,
71 - toolkits: response.toolkits,
72 - tools: response.tools,
73 - managedAuthViaComposio: response.managed_auth_via_composio,
74 - mcpUrl: response.mcpUrl || 'https://mcp.example.com/server',
75 - commands: response.commands || {
76 - claude: 'claude-command',
77 - cursor: 'cursor-command',
78 - windsurf: 'windsurf-command',
79 - },
80 - })),
81 - transformMcpDeleteResponse: vi.fn(response => ({
82 - id: response.id,
83 - deleted: response.deleted,
84 - message: response.message,
85 - })),
86 - transformMcpUpdateResponse: vi.fn(response => ({
87 - id: response.id,
88 - name: response.name,
89 - createdAt: response.created_at,
90 - updatedAt: response.updated_at,
91 - status: response.status,
92 - toolkits: response.toolkits,
93 - tools: response.tools,
94 - })),
95 - transformMcpGenerateUrlResponse: vi.fn(response => ({
96 - connectedAccountUrls: response.connected_account_urls,
97 - userIdsUrl: response.user_ids_url,
98 - mcpUrl: response.mcp_url,
99 - })),
100 -}));
101 -
102 -// Create mock client with MCP-related methods
14 +// Create mock client with MCP methods
15 const createMockClient = () => ({
16 baseURL: 'https://api.composio.dev',
17 apiKey: 'test-api-key',
@@ -107,317 +19,137 @@ const createMockClient = () => ({
19 custom: {
20 create: vi.fn(),
21 },
110 - generate: {
111 - url: vi.fn(),
112 - },
22 list: vi.fn(),
23 retrieve: vi.fn(),
24 delete: vi.fn(),
25 update: vi.fn(),
117 - },
118 - authConfigs: {
119 - retrieve: vi.fn(),
120 - },
121 - connectedAccounts: {
122 - list: vi.fn(),
123 - },
124 - toolkits: {
125 - retrieve: vi.fn(),
126 - },
127 -});
128 -
129 -// Mock response data
130 -const mockCreateResponse = {
131 - id: 'mcp_123',
132 - name: 'test-mcp-server',
133 - created_at: '2024-01-01T00:00:00Z',
134 - updated_at: '2024-01-01T00:00:00Z',
135 - status: 'active',
136 - mcp_url: 'https://mcp.example.com/server',
137 - commands: {
138 - claude: 'claude-command',
139 - cursor: 'cursor-command',
140 - windsurf: 'windsurf-command',
141 - },
142 - toolkits: ['gmail'],
143 - tools: ['GMAIL_FETCH_EMAILS'],
144 - managed_auth_via_composio: true,
145 -};
146 -
147 -const mockListResponse = {
148 - items: [
149 - {
150 - id: 'mcp_123',
151 - name: 'test-mcp-server',
152 - created_at: '2024-01-01T00:00:00Z',
153 - updated_at: '2024-01-01T00:00:00Z',
154 - status: 'active',
155 - },
156 - {
157 - id: 'mcp_456',
158 - name: 'another-mcp-server',
159 - created_at: '2024-01-02T00:00:00Z',
160 - updated_at: '2024-01-02T00:00:00Z',
161 - status: 'active',
26 + generate: {
27 + url: vi.fn(),
28 },
163 - ],
164 -};
165 -
166 -const mockRetrieveResponse = {
167 - id: 'mcp_123',
168 - name: 'test-mcp-server',
169 - created_at: '2024-01-01T00:00:00Z',
170 - updated_at: '2024-01-01T00:00:00Z',
171 - status: 'active',
172 - toolkits: ['gmail', 'github'],
173 - tools: ['GMAIL_FETCH_EMAILS', 'GITHUB_GET_REPO'],
174 - managed_auth_via_composio: true,
175 - mcp_url: 'https://mcp.example.com/server',
176 - commands: {
177 - claude: 'claude-command',
178 - cursor: 'cursor-command',
179 - windsurf: 'windsurf-command',
29 },
181 -};
182 -
183 -const mockGenerateUrlResponse = {
184 - connected_account_urls: ['https://mcp.example.com/account1', 'https://mcp.example.com/account2'],
185 - user_ids_url: ['https://mcp.example.com/user1', 'https://mcp.example.com/user2'],
186 - mcp_url: 'https://mcp.example.com/server',
187 -};
188 -
189 -// Define types for mock provider
190 -type MockTool = Tool & { mockWrapped: boolean };
191 -type MockToolCollection = MockTool[];
192 -type MockMcpResponse = {
193 - customFormat: boolean;
194 - serverName: string;
195 - urls: string[];
196 -};
197 -
198 -// Mock provider
199 -class MockProvider extends BaseAgenticProvider<MockToolCollection, MockTool, MockMcpResponse> {
200 - readonly name = 'mock-provider';
201 -
202 - wrapTool(tool: Tool, executeTool: ExecuteToolFn): MockTool {
203 - return { ...tool, mockWrapped: true };
204 - }
205 -
206 - wrapTools(tools: Tool[], executeTool: ExecuteToolFn): MockToolCollection {
207 - return tools.map(tool => this.wrapTool(tool, executeTool));
208 - }
209 -
210 - wrapMcpServerResponse(data: McpUrlResponse): MockMcpResponse {
211 - // McpUrlResponse is an array of { name, url } objects
212 - return {
213 - customFormat: true,
214 - serverName: data[0]?.name || 'test-mcp-server',
215 - urls: data.map(item => item.url),
216 - };
217 - }
218 -}
30 +});
31
32 describe('MCP', () => {
33 let mcp: MCP;
34 let mockClient: ReturnType<typeof createMockClient>;
223 - let mockProvider: MockProvider;
35
36 beforeEach(() => {
226 - vi.clearAllMocks();
37 mockClient = createMockClient();
38 mcp = new MCP(mockClient as unknown as ComposioClient);
229 -
230 - // Default mock for connected accounts
231 - mockClient.connectedAccounts.list.mockResolvedValue({
232 - items: [
233 - { id: 'account_123', toolkit: { slug: 'gmail' } },
234 - { id: 'account_456', toolkit: { slug: 'gmail' } },
235 - ],
236 - });
39 });
40
41 describe('constructor', () => {
42 it('should create an instance successfully', () => {
43 expect(mcp).toBeInstanceOf(MCP);
242 - expect(telemetry.instrument).toHaveBeenCalledWith(mcp, 'MCP');
44 + expect(mcp.client).toBe(mockClient);
45 });
46
245 - it('should store the client reference', () => {
246 - expect(mcp['client']).toBe(mockClient);
247 - });
248 -
249 - it('should accept an optional provider', () => {
250 - mockProvider = new MockProvider();
251 - const mcpWithProvider = new MCP(mockClient as unknown as ComposioClient, mockProvider);
252 - expect(mcpWithProvider['provider']).toBe(mockProvider);
47 + it('should instrument the class with telemetry', () => {
48 + expect(telemetry.instrument).toHaveBeenCalledWith(mcp, 'MCP');
49 });
50 });
51
52 describe('create', () => {
257 - const serverConfig = [
258 - {
259 - authConfigId: 'ac_gmail123',
260 - allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
261 - },
262 - ];
263 -
264 - beforeEach(() => {
265 - // Mock authConfigs.retrieve to return toolkit information
266 - mockClient.authConfigs.retrieve.mockResolvedValue({
267 - id: 'ac_gmail123',
268 - toolkit: { slug: 'gmail' },
269 - auth_scheme: 'OAUTH2',
270 - });
271 - });
272 -
53 it('should create an MCP server successfully', async () => {
274 - mockClient.mcp.custom.create.mockResolvedValue(mockCreateResponse);
275 - mockClient.mcp.list.mockResolvedValue(mockListResponse);
276 - const result = await mcp.create('test-server', serverConfig, {
277 - isChatAuth: true,
278 - });
279 -
280 - expect(mockClient.mcp.custom.create).toHaveBeenCalledWith({
281 - name: 'test-server',
282 - toolkits: ['gmail'],
283 - custom_tools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
284 - managed_auth_via_composio: true,
285 - auth_config_ids: ['ac_gmail123'],
286 - });
287 -
288 - expect(result).toMatchObject({
54 + const mockResponse = {
55 id: 'mcp_123',
290 - name: 'test-mcp-server',
291 - toolkits: ['gmail'],
292 - });
293 -
294 - expect(result.getServer).toBeDefined();
295 - expect(typeof result.getServer).toBe('function');
296 - });
297 -
298 - it('should validate server configuration', async () => {
299 - const invalidConfigs: any[] = []; // Empty array
300 -
301 - await expect(
302 - mcp.create('test-server', invalidConfigs, {
303 - isChatAuth: true,
304 - })
305 - ).rejects.toThrow('At least one auth config is required');
306 - });
307 -
308 - it('should validate server name', async () => {
309 - await expect(
310 - mcp.create('', serverConfig, {
311 - isChatAuth: true,
312 - })
313 - ).rejects.toThrow('Server name is required');
314 - });
315 - });
316 -
317 - describe('getServer', () => {
318 - beforeEach(() => {
319 - // Mock the get method that getServer calls internally
320 - vi.spyOn(mcp, 'get').mockResolvedValue({
321 - id: mockRetrieveResponse.id,
322 - name: mockRetrieveResponse.name,
323 - createdAt: mockRetrieveResponse.created_at,
324 - updatedAt: mockRetrieveResponse.updated_at,
325 - status: mockRetrieveResponse.status,
326 - toolkits: mockRetrieveResponse.toolkits,
327 - tools: mockRetrieveResponse.tools,
328 - managedAuthViaComposio: mockRetrieveResponse.managed_auth_via_composio,
329 - mcpUrl: 'https://mcp.example.com/server',
56 + name: 'test-server',
57 + allowed_tools: ['GMAIL_SEND_EMAIL'],
58 + auth_config_ids: ['auth_456'],
59 commands: {
60 claude: 'claude-command',
61 cursor: 'cursor-command',
62 windsurf: 'windsurf-command',
63 },
335 - });
336 -
337 - // Mock connectedAccounts.list
338 - mockClient.connectedAccounts.list.mockResolvedValue({
339 - items: [
340 - { id: 'account_123', toolkit: { slug: 'gmail' } },
341 - { id: 'account_456', toolkit: { slug: 'github' } },
342 - ],
343 - });
344 - });
345 -
346 - it('should get server URLs with user ID', async () => {
347 - mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
64 + mcp_url: 'https://mcp.example.com/server',
65 + };
66
349 - const result = await mcp.getServer('mcp_123', 'user_123');
67 + mockClient.mcp.custom.create.mockResolvedValueOnce(mockResponse);
68
351 - expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
352 - user_ids: ['user_123'],
353 - connected_account_ids: [],
354 - mcp_server_id: 'mcp_123',
355 - managed_auth_by_composio: true,
69 + const result = await mcp.create('test-server', {
70 + toolkits: ['gmail'],
71 + manuallyManageConnections: false,
72 });
73
358 - expect(result).toBeDefined();
359 - });
360 -
361 - it('should get server URLs with options', async () => {
362 - mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
363 -
364 - const result = await mcp.getServer('mcp_123', 'user_123');
365 -
366 - expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
367 - user_ids: ['user_123'],
368 - connected_account_ids: [],
369 - mcp_server_id: 'mcp_123',
370 - managed_auth_by_composio: true,
74 + expect(result).toHaveProperty('id', 'mcp_123');
75 + expect(result).toHaveProperty('name', 'test-server');
76 + expect(result).toHaveProperty('generate');
77 + expect(typeof result.generate).toBe('function');
78 + expect(mockClient.mcp.custom.create).toHaveBeenCalledWith({
79 + name: 'test-server',
80 + toolkits: ['gmail'],
81 + auth_config_ids: [],
82 + custom_tools: [],
83 + managed_auth_via_composio: true,
84 });
85 });
86
374 - it('should validate that userId is provided', async () => {
375 - await expect(mcp.getServer('mcp_123', '')).rejects.toThrow('User ID is required');
376 - });
377 -
378 - it('should use custom provider transformation', async () => {
379 - mockProvider = new MockProvider();
380 - const mcpWithProvider = new MCP(mockClient as unknown as ComposioClient, mockProvider);
381 - vi.spyOn(mcpWithProvider, 'get').mockResolvedValue({
382 - id: mockRetrieveResponse.id,
383 - name: mockRetrieveResponse.name,
384 - createdAt: mockRetrieveResponse.created_at,
385 - updatedAt: mockRetrieveResponse.updated_at,
386 - status: mockRetrieveResponse.status,
387 - toolkits: mockRetrieveResponse.toolkits,
388 - tools: mockRetrieveResponse.tools,
389 - managedAuthViaComposio: mockRetrieveResponse.managed_auth_via_composio,
390 - mcpUrl: 'https://mcp.example.com/server',
87 + it('should handle toolkits with auth config IDs', async () => {
88 + const mockResponse = {
89 + id: 'mcp_123',
90 + name: 'test-server',
91 + allowed_tools: [],
92 + auth_config_ids: ['auth_456'],
93 commands: {
392 - claude: 'claude-command',
393 - cursor: 'cursor-command',
394 - windsurf: 'windsurf-command',
94 + claude: 'cmd',
95 + cursor: 'cmd',
96 + windsurf: 'cmd',
97 },
396 - });
397 -
398 - // Mock a response with only one URL for the single userId
399 - const singleUserResponse = {
400 - user_ids_url: ['https://mcp.example.com/user_123'],
401 - mcp_url: 'https://mcp.example.com/server',
98 + mcp_url: 'https://mcp.example.com',
99 };
403 - mockClient.mcp.generate.url.mockResolvedValue(singleUserResponse);
100
405 - const result = await mcpWithProvider.getServer('mcp_123', 'user_123');
101 + mockClient.mcp.custom.create.mockResolvedValueOnce(mockResponse);
102
407 - expect(result).toMatchObject({
408 - customFormat: true,
409 - serverName: 'test-mcp-server-user_123',
410 - urls: ['https://mcp.example.com/user_123'],
103 + await mcp.create('test-server', {
104 + toolkits: [{ toolkit: 'gmail', authConfigId: 'auth_456' }],
105 + });
106 +
107 + expect(mockClient.mcp.custom.create).toHaveBeenCalledWith({
108 + name: 'test-server',
109 + toolkits: ['gmail'],
110 + auth_config_ids: [],
111 + custom_tools: [],
112 + managed_auth_via_composio: true,
113 });
114 });
115 +
116 + it('should validate configuration', async () => {
117 + await expect(mcp.create('test', { toolkits: null as any })).rejects.toThrow(ValidationError);
118 + });
119 });
120
121 describe('list', () => {
122 it('should list MCP servers with default options', async () => {
417 - mockClient.mcp.list.mockResolvedValue(mockListResponse);
123 + const mockResponse = {
124 + items: [
125 + {
126 + id: 'mcp_1',
127 + name: 'server-1',
128 + allowed_tools: ['TOOL_1'],
129 + auth_config_ids: ['auth_1'],
130 + commands: {
131 + claude: 'cmd',
132 + cursor: 'cmd',
133 + windsurf: 'cmd',
134 + },
135 + mcp_url: 'https://mcp.example.com',
136 + toolkit_icons: {},
137 + server_instance_count: 0,
138 + toolkits: ['gmail'],
139 + },
140 + ],
141 + current_page: 1,
142 + total_pages: 1,
143 + };
144 +
145 + mockClient.mcp.list.mockResolvedValueOnce(mockResponse);
146
147 const result = await mcp.list({});
148
149 + expect(result).toHaveProperty('items');
150 + expect(result).toHaveProperty('currentPage', 1);
151 + expect(result).toHaveProperty('totalPages', 1);
152 + expect(result.items).toHaveLength(1);
153 expect(mockClient.mcp.list).toHaveBeenCalledWith({
154 page_no: 1,
155 limit: 10,
@@ -425,283 +157,243 @@ describe('MCP', () => {
157 auth_config_ids: undefined,
158 name: undefined,
159 });
428 -
429 - expect(result).toMatchObject({
430 - items: expect.arrayContaining([
431 - expect.objectContaining({
432 - id: 'mcp_123',
433 - name: 'test-mcp-server',
434 - }),
435 - ]),
436 - });
160 });
161
162 it('should list MCP servers with filters', async () => {
440 - mockClient.mcp.list.mockResolvedValue(mockListResponse);
163 + const mockResponse = {
164 + items: [],
165 + current_page: 1,
166 + total_pages: 1,
167 + };
168
442 - const result = await mcp.list({
169 + mockClient.mcp.list.mockResolvedValueOnce(mockResponse);
170 +
171 + await mcp.list({
172 page: 2,
173 limit: 20,
445 - toolkits: ['gmail', 'github'],
446 - authConfigs: ['auth_123', 'auth_456'],
447 - name: 'production',
174 + toolkits: ['gmail', 'slack'],
175 + authConfigs: ['auth_1'],
176 + name: 'test',
177 });
178
179 expect(mockClient.mcp.list).toHaveBeenCalledWith({
180 page_no: 2,
181 limit: 20,
453 - toolkits: 'gmail,github',
454 - auth_config_ids: 'auth_123,auth_456',
455 - name: 'production',
182 + toolkits: 'gmail,slack',
183 + auth_config_ids: 'auth_1',
184 + name: 'test',
185 });
186 });
187
459 - it('should handle list errors', async () => {
460 - mockClient.mcp.list.mockRejectedValue(new Error('List failed'));
461 -
462 - await expect(mcp.list({})).rejects.toThrow('Failed to list MCP servers');
188 + it('should handle validation errors', async () => {
189 + await expect(mcp.list({ page: 'invalid' as any })).rejects.toThrow(ValidationError);
190 });
191 });
192
193 describe('get', () => {
194 it('should retrieve an MCP server by ID', async () => {
468 - mockClient.mcp.retrieve.mockResolvedValue(mockRetrieveResponse);
195 + const mockResponse = {
196 + id: 'mcp_123',
197 + name: 'test-server',
198 + allowed_tools: ['GMAIL_SEND_EMAIL'],
199 + auth_config_ids: ['auth_456'],
200 + commands: {
201 + claude: 'cmd',
202 + cursor: 'cmd',
203 + windsurf: 'cmd',
204 + },
205 + mcp_url: 'https://mcp.example.com',
206 + toolkit_icons: {},
207 + server_instance_count: 5,
208 + toolkits: ['gmail'],
209 + };
210 +
211 + mockClient.mcp.retrieve.mockResolvedValueOnce(mockResponse);
212
213 const result = await mcp.get('mcp_123');
214
215 + expect(result).toHaveProperty('id', 'mcp_123');
216 + expect(result).toHaveProperty('name', 'test-server');
217 + expect(result).toHaveProperty('serverInstanceCount', 5);
218 expect(mockClient.mcp.retrieve).toHaveBeenCalledWith('mcp_123');
473 - expect(result).toMatchObject({
474 - id: 'mcp_123',
475 - name: 'test-mcp-server',
476 - toolkits: ['gmail', 'github'],
477 - });
478 - });
479 -
480 - it('should handle retrieval errors', async () => {
481 - mockClient.mcp.retrieve.mockRejectedValue(new Error('Not found'));
482 -
483 - await expect(mcp.get('mcp_123')).rejects.toThrow('Failed to retrieve MCP server');
219 });
220 });
221
222 describe('delete', () => {
223 it('should delete an MCP server', async () => {
489 - const mockDeleteResponse = {
224 + const mockResponse = {
225 id: 'mcp_123',
226 deleted: true,
492 - message: 'Server deleted successfully',
227 };
228
495 - mockClient.mcp.delete.mockResolvedValue(mockDeleteResponse);
229 + mockClient.mcp.delete.mockResolvedValueOnce(mockResponse);
230
231 const result = await mcp.delete('mcp_123');
232
233 + expect(result).toEqual(mockResponse);
234 expect(mockClient.mcp.delete).toHaveBeenCalledWith('mcp_123');
500 - expect(result).toMatchObject({
501 - id: 'mcp_123',
502 - deleted: true,
503 - });
504 - });
505 -
506 - it('should handle deletion errors', async () => {
507 - mockClient.mcp.delete.mockRejectedValue(new Error('Cannot delete'));
508 -
509 - await expect(mcp.delete('mcp_123')).rejects.toThrow('Failed to delete MCP server');
235 });
236 });
237
238 describe('update', () => {
514 - const updatedConfigs = [
515 - {
516 - toolkit: 'gmail',
517 - authConfigId: 'ac_gmail789',
518 - allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL', 'GMAIL_CREATE_DRAFT'],
519 - },
520 - ];
521 -
239 it('should update an MCP server', async () => {
523 - const mockUpdateResponse = {
240 + const mockResponse = {
241 id: 'mcp_123',
242 name: 'updated-server',
526 - created_at: '2024-01-01T00:00:00Z',
527 - updated_at: '2024-01-02T00:00:00Z',
528 - status: 'active',
529 - toolkits: ['gmail'],
530 - tools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL', 'GMAIL_CREATE_DRAFT'],
243 + allowed_tools: ['NEW_TOOL'],
244 + auth_config_ids: ['auth_789'],
245 + commands: {
246 + claude: 'cmd',
247 + cursor: 'cmd',
248 + windsurf: 'cmd',
249 + },
250 + mcp_url: 'https://mcp.example.com',
251 + toolkit_icons: {},
252 + server_instance_count: 3,
253 + toolkits: ['slack'],
254 };
255
533 - mockClient.mcp.update.mockResolvedValue(mockUpdateResponse);
256 + mockClient.mcp.update.mockResolvedValueOnce(mockResponse);
257
535 - const result = await mcp.update('mcp_123', 'updated-server', updatedConfigs, {
536 - isChatAuth: true,
537 - });
538 -
539 - expect(mockClient.mcp.update).toHaveBeenCalledWith('mcp_123', {
258 + const result = await mcp.update('mcp_123', {
259 name: 'updated-server',
541 - toolkits: ['gmail'],
542 - allowed_tools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL', 'GMAIL_CREATE_DRAFT'],
543 - managed_auth_via_composio: true,
260 + toolkits: ['slack'],
261 });
262
546 - expect(result).toMatchObject({
547 - id: 'mcp_123',
263 + expect(result).toHaveProperty('id', 'mcp_123');
264 + expect(result).toHaveProperty('name', 'updated-server');
265 + expect(mockClient.mcp.update).toHaveBeenCalledWith('mcp_123', {
266 name: 'updated-server',
267 + custom_tools: undefined,
268 + toolkits: ['slack'],
269 + auth_config_ids: [],
270 });
271 });
272
273 it('should validate update parameters', async () => {
553 - const invalidConfigs = [
554 - {
555 - toolkit: '',
556 - authConfigId: 'ac_123',
557 - allowedTools: [],
558 - },
559 - ];
560 -
561 - await expect(mcp.update('mcp_123', 'updated', invalidConfigs)).rejects.toThrow(
274 + await expect(mcp.update('mcp_123', { toolkits: 'invalid' as any })).rejects.toThrow(
275 ValidationError
276 );
277 });
565 -
566 - it('should handle update errors', async () => {
567 - mockClient.mcp.update.mockRejectedValue(new Error('Update failed'));
568 -
569 - await expect(mcp.update('mcp_123', 'updated', updatedConfigs)).rejects.toThrow(
570 - 'Failed to update MCP server'
571 - );
572 - });
278 });
279
575 - describe('generateUrl', () => {
576 - it('should generate URLs with valid parameters', async () => {
577 - mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
280 + describe('generate', () => {
281 + it('should generate server instance with valid parameters', async () => {
282 + const mockRetrieveResponse = {
283 + id: 'mcp_123',
284 + name: 'test-server',
285 + allowed_tools: ['GMAIL_SEND_EMAIL'],
286 + auth_config_ids: ['auth_456'],
287 + };
288
579 - const params = {
580 - userIds: ['user123'],
581 - connectedAccountIds: ['account456'],
582 - mcpServerId: 'mcp_123',
583 - composioManagedAuth: true,
289 + const mockUrlResponse = {
290 + user_ids_url: ['https://mcp.example.com/instance/user123'],
291 + connected_account_urls: [],
292 + mcp_url: 'https://mcp.example.com',
293 };
294
586 - const result = await mcp.generateUrl('mcp_123', params);
295 + mockClient.mcp.retrieve.mockResolvedValueOnce(mockRetrieveResponse);
296 + mockClient.mcp.generate.url.mockResolvedValueOnce(mockUrlResponse);
297 +
298 + const result = await mcp.generate('user123', 'mcp_123');
299
300 + expect(result).toHaveProperty('id', 'mcp_123');
301 + expect(result).toHaveProperty('userId', 'user123');
302 + expect(result).toHaveProperty('type', 'streamable_http');
303 + expect(result).toHaveProperty('url', 'https://mcp.example.com/instance/user123');
304 expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
589 - user_ids: ['user123'],
590 - connected_account_ids: ['account456'],
305 mcp_server_id: 'mcp_123',
306 + user_ids: ['user123'],
307 managed_auth_by_composio: true,
308 });
309 + });
310
595 - expect(result).toMatchObject({
596 - connectedAccountUrls: [
597 - 'https://mcp.example.com/account1',
598 - 'https://mcp.example.com/account2',
599 - ],
600 - userIdsUrl: ['https://mcp.example.com/user1', 'https://mcp.example.com/user2'],
601 - mcpUrl: 'https://mcp.example.com/server',
311 + it('should handle manual connection management', async () => {
312 + const mockRetrieveResponse = {
313 + id: 'mcp_123',
314 + name: 'test-server',
315 + allowed_tools: [],
316 + auth_config_ids: [],
317 + };
318 +
319 + const mockUrlResponse = {
320 + user_ids_url: ['https://mcp.example.com/instance/user123'],
321 + connected_account_urls: [],
322 + mcp_url: 'https://mcp.example.com',
323 + };
324 +
325 + mockClient.mcp.retrieve.mockResolvedValueOnce(mockRetrieveResponse);
326 + mockClient.mcp.generate.url.mockResolvedValueOnce(mockUrlResponse);
327 +
328 + await mcp.generate('user123', 'mcp_123', {
329 + manuallyManageConnections: true,
330 + });
331 +
332 + expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
333 + mcp_server_id: 'mcp_123',
334 + user_ids: ['user123'],
335 + managed_auth_by_composio: false,
336 });
337 });
338
339 it('should validate parameters', async () => {
606 - const invalidParams = {
607 - userIds: 'not-an-array' as unknown as string[], // Should be an array
608 - mcpServerId: 'mcp_123',
340 + const mockRetrieveResponse = {
341 + id: 'mcp_123',
342 + name: 'test-server',
343 + allowed_tools: [],
344 + auth_config_ids: [],
345 };
346
611 - await expect(mcp.generateUrl('mcp_123', invalidParams)).rejects.toThrow(ValidationError);
612 - });
613 -
614 - it('should handle URL generation errors', async () => {
615 - mockClient.mcp.generate.url.mockRejectedValue(new Error('Generation failed'));
347 + mockClient.mcp.retrieve.mockResolvedValueOnce(mockRetrieveResponse);
348
349 await expect(
618 - mcp.generateUrl('mcp_123', {
619 - userIds: ['user123'],
620 - mcpServerId: 'mcp_123',
621 - })
622 - ).rejects.toThrow('Failed to generate MCP URL');
350 + mcp.generate('user123', 'mcp_123', { manuallyManageConnections: 'invalid' as any })
351 + ).rejects.toThrow(ValidationError);
352 });
353 });
354
626 - describe('convenience getServer method', () => {
627 - it('should work on create response', async () => {
628 - mockClient.mcp.custom.create.mockResolvedValue(mockCreateResponse);
629 - mockClient.mcp.retrieve.mockResolvedValue(mockRetrieveResponse);
630 - mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
631 - mockClient.mcp.list.mockResolvedValue(mockListResponse);
632 - mockClient.authConfigs.retrieve.mockResolvedValue({
633 - id: 'ac_gmail123',
634 - toolkit: { slug: 'gmail' },
635 - });
636 -
637 - const serverConfig = [
638 - {
639 - authConfigId: 'ac_gmail123',
640 - allowedTools: ['GMAIL_FETCH_EMAILS'],
355 + describe('create response with generate method', () => {
356 + it('should create server and use the generate method', async () => {
357 + const mockCreateResponse = {
358 + id: 'mcp_123',
359 + name: 'test-server',
360 + allowed_tools: ['GMAIL_SEND_EMAIL'],
361 + auth_config_ids: ['auth_456'],
362 + commands: {
363 + claude: 'cmd',
364 + cursor: 'cmd',
365 + windsurf: 'cmd',
366 },
642 - ];
367 + mcp_url: 'https://mcp.example.com',
368 + };
369
644 - const server = await mcp.create('test-server', serverConfig, {
645 - isChatAuth: true,
646 - });
370 + const mockRetrieveResponse = {
371 + id: 'mcp_123',
372 + name: 'test-server',
373 + allowed_tools: ['GMAIL_SEND_EMAIL'],
374 + auth_config_ids: ['auth_456'],
375 + };
376
648 - // Mock the internal get call
649 - vi.spyOn(mcp, 'get').mockResolvedValue({
650 - id: mockRetrieveResponse.id,
651 - name: mockRetrieveResponse.name,
652 - createdAt: mockRetrieveResponse.created_at,
653 - updatedAt: mockRetrieveResponse.updated_at,
654 - status: mockRetrieveResponse.status,
655 - toolkits: mockRetrieveResponse.toolkits,
656 - tools: mockRetrieveResponse.tools,
657 - managedAuthViaComposio: mockRetrieveResponse.managed_auth_via_composio,
658 - mcpUrl: 'https://mcp.example.com/server',
659 - commands: {
660 - claude: 'claude-command',
661 - cursor: 'cursor-command',
662 - windsurf: 'windsurf-command',
663 - },
664 - });
377 + const mockUrlResponse = {
378 + user_ids_url: ['https://mcp.example.com/instance/user123'],
379 + connected_account_urls: [],
380 + mcp_url: 'https://mcp.example.com',
381 + };
382
666 - // Mock connectedAccounts.list for the convenience method
667 - mockClient.connectedAccounts.list.mockResolvedValue({
668 - items: [
669 - { id: 'account_123', toolkit: { slug: 'gmail' } },
670 - { id: 'account_456', toolkit: { slug: 'gmail' } },
671 - ],
672 - });
383 + mockClient.mcp.custom.create.mockResolvedValueOnce(mockCreateResponse);
384 + mockClient.mcp.retrieve.mockResolvedValueOnce(mockRetrieveResponse);
385 + mockClient.mcp.generate.url.mockResolvedValueOnce(mockUrlResponse);
386
674 - const urls = await server.getServer({
675 - userId: 'user123',
387 + const server = await mcp.create('test-server', {
388 + toolkits: ['gmail'],
389 });
390
678 - expect(urls).toBeDefined();
679 - expect(mockClient.mcp.generate.url).toHaveBeenCalled();
680 - });
681 - });
391 + expect(server.generate).toBeDefined();
392
683 - describe('validation error messages', () => {
684 - it('should provide meaningful error messages for empty auth config', async () => {
685 - await expect(
686 - mcp.create('test-server', [], {
687 - isChatAuth: true,
688 - })
689 - ).rejects.toThrow('At least one auth config is required');
690 - });
393 + const instance = await server.generate('user123');
394
692 - it('should provide meaningful error messages for empty server name', async () => {
693 - const serverConfig = [
694 - {
695 - authConfigId: 'ac_123',
696 - allowedTools: ['GMAIL_FETCH_EMAILS'],
697 - },
698 - ];
699 -
700 - await expect(
701 - mcp.create('', serverConfig, {
702 - isChatAuth: true,
703 - })
704 - ).rejects.toThrow('Server name is required');
395 + expect(instance).toHaveProperty('userId', 'user123');
396 + expect(instance).toHaveProperty('url', 'https://mcp.example.com/instance/user123');
397 });
398 });
399 });
ts/packages/core/test/models/toolRouter.test.ts
+25 -45
@@ -18,6 +18,7 @@ vi.mock('../../src/models/Tools', () => {
18 return {
19 Tools: vi.fn().mockImplementation(() => ({
20 getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
21 + getRawToolRouterMetaTools: vi.fn().mockResolvedValue([{ slug: 'COMPOSIO_SEARCH_TOOLS' }]),
22 wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
23 })),
24 };
@@ -1639,6 +1640,7 @@ describe('ToolRouter', () => {
1640 vi.clearAllMocks();
1641 (Tools as any).mockImplementation(() => ({
1642 getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
1643 + getRawToolRouterMetaTools: vi.fn().mockResolvedValue([{ slug: 'COMPOSIO_SEARCH_TOOLS' }]),
1644 wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
1645 }));
1646 });
@@ -1655,15 +1657,10 @@ describe('ToolRouter', () => {
1657 });
1658
1659 const toolsInstance = (Tools as any).mock.results[0].value;
1658 - expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1659 - {
1660 - tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
1661 - },
1662 - undefined
1663 - );
1660 + expect(toolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(sessionId, undefined);
1661 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1662 sessionId,
1666 - [{ slug: 'GMAIL_FETCH_EMAILS' }],
1663 + [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
1664 undefined
1665 );
1666
@@ -1685,15 +1682,12 @@ describe('ToolRouter', () => {
1682 const tools = await session.tools(modifiers);
1683
1684 const toolsInstance = (Tools as any).mock.results[0].value;
1688 - expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1689 - {
1690 - tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
1691 - },
1692 - { modifySchema: modifiers.modifySchema }
1693 - );
1685 + expect(toolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(sessionId, {
1686 + modifySchema: modifiers.modifySchema,
1687 + });
1688 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1689 sessionId,
1696 - [{ slug: 'GMAIL_FETCH_EMAILS' }],
1690 + [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
1691 modifiers
1692 );
1693
@@ -1705,6 +1699,7 @@ describe('ToolRouter', () => {
1699
1700 (Tools as any).mockImplementation(() => ({
1701 getRawComposioTools: vi.fn().mockRejectedValue(new Error('Failed to fetch tools')),
1702 + getRawToolRouterMetaTools: vi.fn().mockRejectedValue(new Error('Failed to fetch tools')),
1703 wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
1704 }));
1705
@@ -1729,28 +1724,22 @@ describe('ToolRouter', () => {
1724 expect(Tools).toHaveBeenCalledTimes(2);
1725
1726 const firstToolsInstance = (Tools as any).mock.results[0].value;
1732 - expect(firstToolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1733 - {
1734 - tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
1735 - },
1736 - { modifySchema: modifier1.modifySchema }
1737 - );
1727 + expect(firstToolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(sessionId, {
1728 + modifySchema: modifier1.modifySchema,
1729 + });
1730 expect(firstToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1731 sessionId,
1740 - [{ slug: 'GMAIL_FETCH_EMAILS' }],
1732 + [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
1733 modifier1
1734 );
1735
1736 const secondToolsInstance = (Tools as any).mock.results[1].value;
1745 - expect(secondToolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1746 - {
1747 - tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
1748 - },
1749 - { modifySchema: modifier2.modifySchema }
1750 - );
1737 + expect(secondToolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(sessionId, {
1738 + modifySchema: modifier2.modifySchema,
1739 + });
1740 expect(secondToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1741 sessionId,
1753 - [{ slug: 'GMAIL_FETCH_EMAILS' }],
1742 + [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
1743 modifier2
1744 );
1745 });
@@ -1772,15 +1761,13 @@ describe('ToolRouter', () => {
1761 apiKey: 'test-api-key',
1762 });
1763 const toolsInstance = (Tools as any).mock.results[0].value;
1775 - expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1776 - {
1777 - tools: ['CUSTOM_TOOL_1', 'CUSTOM_TOOL_2'],
1778 - },
1764 + expect(toolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(
1765 + 'custom_session_123',
1766 undefined
1767 );
1768 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1769 'custom_session_123',
1783 - [{ slug: 'GMAIL_FETCH_EMAILS' }],
1770 + [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
1771 undefined
1772 );
1773 });
@@ -1802,15 +1789,13 @@ describe('ToolRouter', () => {
1789 apiKey: 'test-api-key',
1790 });
1791 const toolsInstance = (Tools as any).mock.results[0].value;
1805 - expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1806 - {
1807 - tools: [],
1808 - },
1792 + expect(toolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(
1793 + 'empty_session_123',
1794 undefined
1795 );
1796 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1797 'empty_session_123',
1813 - [{ slug: 'GMAIL_FETCH_EMAILS' }],
1798 + [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
1799 undefined
1800 );
1801 });
@@ -1963,15 +1948,10 @@ describe('ToolRouter', () => {
1948 expect(Tools).toHaveBeenCalled();
1949
1950 const toolsInstance = (Tools as any).mock.results[0].value;
1966 - expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1967 - {
1968 - tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
1969 - },
1970 - undefined
1971 - );
1951 + expect(toolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(sessionId, undefined);
1952 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1953 sessionId,
1974 - [{ slug: 'GMAIL_FETCH_EMAILS' }],
1954 + [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
1955 undefined
1956 );
1957 });
ts/packages/core/test/tools/tools.test.ts
+9 -6
@@ -769,15 +769,15 @@ describe('Tools', () => {
769 });
770
771 it('should throw error if tool is not found', async () => {
772 - const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
773 - getRawComposioToolBySlugSpy.mockResolvedValueOnce(undefined as any);
772 + const apiError = new Error('Tool not found');
773 + mockClient.toolRouter.session.executeMeta.mockRejectedValueOnce(apiError);
774
775 await expect(
776 context.tools.executeMetaTool('NONEXISTENT_TOOL', {
777 sessionId,
778 arguments: { query: 'test' },
779 })
780 - ).rejects.toThrow('Tool NONEXISTENT_TOOL not found');
780 + ).rejects.toThrow('Tool not found');
781 });
782
783 it('should apply beforeExecute modifier', async () => {
@@ -810,7 +810,8 @@ describe('Tools', () => {
810
811 expect(beforeExecute).toHaveBeenCalledWith({
812 toolSlug,
813 - toolkitSlug: 'test-toolkit',
813 + toolkitSlug: 'composio',
814 + sessionId,
815 params: { query: 'original' },
816 });
817
@@ -850,7 +851,8 @@ describe('Tools', () => {
851
852 expect(afterExecute).toHaveBeenCalledWith({
853 toolSlug,
853 - toolkitSlug: 'test-toolkit',
854 + toolkitSlug: 'composio',
855 + sessionId,
856 result: {
857 data: { results: true },
858 error: null,
@@ -917,7 +919,8 @@ describe('Tools', () => {
919
920 expect(beforeExecute).toHaveBeenCalledWith({
921 toolSlug,
920 - toolkitSlug: 'unknown',
922 + toolkitSlug: 'composio',
923 + sessionId,
924 params: { query: 'test' },
925 });
926 });
uv.lock
+14 -14
@@ -477,7 +477,7 @@ wheels = [
477
478 [[package]]
479 name = "composio"
480 -version = "0.10.3"
480 +version = "0.10.5"
481 source = { virtual = "python" }
482 dependencies = [
483 { name = "composio-client" },
@@ -506,7 +506,7 @@ dev = [
506
507 [package.metadata]
508 requires-dist = [
509 - { name = "composio-client", specifier = "==1.22.0" },
509 + { name = "composio-client", specifier = "==1.25.0" },
510 { name = "openai" },
511 { name = "pydantic", specifier = ">=2.6.4" },
512 { name = "pysher", specifier = ">=1.0.8" },
@@ -532,7 +532,7 @@ dev = [
532
533 [[package]]
534 name = "composio-anthropic"
535 -version = "0.10.3"
535 +version = "0.10.5"
536 source = { virtual = "python/providers/anthropic" }
537 dependencies = [
538 { name = "anthropic" },
@@ -547,7 +547,7 @@ requires-dist = [
547
548 [[package]]
549 name = "composio-client"
550 -version = "1.22.0"
550 +version = "1.25.0"
551 source = { registry = "https://pypi.org/simple" }
552 dependencies = [
553 { name = "anyio" },
@@ -557,14 +557,14 @@ dependencies = [
557 { name = "sniffio" },
558 { name = "typing-extensions" },
559 ]
560 -sdist = { url = "https://files.pythonhosted.org/packages/44/a7/81fe217a855992ee3854acd07939c0eed893d9b8019ea544e28fd0aa1b86/composio_client-1.22.0.tar.gz", hash = "sha256:13dd4ecf3b1289cfd6acdb538f9144d123d0344c03b387aa411d6fb0f1dec6d0", size = 185804 }
560 +sdist = { url = "https://files.pythonhosted.org/packages/c4/72/270a24236f4580d1eced2eb4b38c4a9bd399714ef2b76c74952729687276/composio_client-1.25.0.tar.gz", hash = "sha256:ae335bc90309b9d5f222c48c85a20a4c701afda5e3015cb3472245c01aa632bb", size = 190472 }
561 wheels = [
562 - { url = "https://files.pythonhosted.org/packages/8f/1f/2abe83f3363edc3d5be94002f97eafed9ea95d7129fe6ea1c33655751aeb/composio_client-1.22.0-py3-none-any.whl", hash = "sha256:3afe32fd3206c3bd2a7183d729817908fdc4bfac2b52da22144334fab2384932", size = 201474 },
562 + { url = "https://files.pythonhosted.org/packages/56/0b/9f92a8b2bce0a23f39c98e860fe14e58365d804c0dea8277ed6b4e5e66f4/composio_client-1.25.0-py3-none-any.whl", hash = "sha256:de6b05667f29692a4425b43d53349c7b31439012ffc3f93059ceacb5cc3fbe56", size = 209162 },
563 ]
564
565 [[package]]
566 name = "composio-crewai"
567 -version = "0.10.3"
567 +version = "0.10.5"
568 source = { virtual = "python/providers/crewai" }
569 dependencies = [
570 { name = "composio" },
@@ -579,7 +579,7 @@ requires-dist = [
579
580 [[package]]
581 name = "composio-gemini"
582 -version = "0.10.3"
582 +version = "0.10.5"
583 source = { virtual = "python/providers/gemini" }
584 dependencies = [
585 { name = "composio" },
@@ -594,7 +594,7 @@ requires-dist = [
594
595 [[package]]
596 name = "composio-google"
597 -version = "0.10.3"
597 +version = "0.10.5"
598 source = { virtual = "python/providers/google" }
599 dependencies = [
600 { name = "composio" },
@@ -609,7 +609,7 @@ requires-dist = [
609
610 [[package]]
611 name = "composio-google-adk"
612 -version = "0.10.3"
612 +version = "0.10.5"
613 source = { virtual = "python/providers/google_adk" }
614 dependencies = [
615 { name = "composio" },
@@ -624,7 +624,7 @@ requires-dist = [
624
625 [[package]]
626 name = "composio-langchain"
627 -version = "0.10.3"
627 +version = "0.10.5"
628 source = { virtual = "python/providers/langchain" }
629 dependencies = [
630 { name = "composio" },
@@ -639,7 +639,7 @@ requires-dist = [
639
640 [[package]]
641 name = "composio-openai"
642 -version = "0.10.3"
642 +version = "0.10.5"
643 source = { virtual = "python/providers/openai" }
644 dependencies = [
645 { name = "composio" },
@@ -654,7 +654,7 @@ requires-dist = [
654
655 [[package]]
656 name = "composio-openai-agents"
657 -version = "0.10.3"
657 +version = "0.10.5"
658 source = { virtual = "python/providers/openai_agents" }
659 dependencies = [
660 { name = "composio" },
@@ -892,7 +892,7 @@ dev = [
892 requires-dist = [
893 { name = "click", specifier = ">=8.1.7" },
894 { name = "composio", virtual = "python" },
895 - { name = "composio-client", specifier = "==1.22.0" },
895 + { name = "composio-client", specifier = "==1.25.0" },
896 { name = "composio-gemini", virtual = "python/providers/gemini" },
897 { name = "composio-langchain", virtual = "python/providers/langchain" },
898 { name = "composio-openai", virtual = "python/providers/openai" },