Skip to content

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

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

Musthaq Ahamadc7e121706f1e
diff --git a/.changeset/angry-foxes-wear.md b/.changeset/angry-foxes-wear.md
new file mode 100644
index 000000000..b4e432a3c
--- /dev/null
+++ b/.changeset/angry-foxes-wear.md
@@ -0,0 +1,15 @@
+---
+'@composio/core': minor
+'@composio/anthropic': minor
+'@composio/claude-agent-sdk': minor
+'@composio/cloudflare': minor
+'@composio/google': minor
+'@composio/langchain': minor
+'@composio/llamaindex': minor
+'@composio/mastra': minor
+'@composio/openai': minor
+'@composio/openai-agents': minor
+'@composio/vercel': minor
+---
+
+Add support for dedicated tools for tool router
diff --git a/fern/pages/src/changelog/01-12-26-tool-router-improvements.md b/fern/pages/src/changelog/01-12-26-tool-router-improvements.md
new file mode 100644
index 000000000..c2046918b
--- /dev/null
+++ b/fern/pages/src/changelog/01-12-26-tool-router-improvements.md
@@ -0,0 +1,127 @@
+# Tool Router Improvements and New Features
+
+## Version Information
+
+### TypeScript/JavaScript
+- Package: `@composio/core` and provider packages
+- Version: `0.3.4` to `0.4.0`
+
+### Python
+- Package: `composio-core` and provider packages
+- Version: `0.10.4` to `0.10.5`
+
+## New Features
+
+### 1. Wait for Connections Property
+
+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.
+
+**TypeScript:**
+```typescript
+const session = await composio.toolRouter.create(userId, {
+ manageConnections: {
+ enable: true,
+ callbackUrl: 'https://example.com/callback',
+ waitForConnections: true // NEW
+ }
+});
+```
+
+**Python:**
+```python
+session = tool_router.create(
+ user_id="user_123",
+ manage_connections={
+ "enable": True,
+ "callback_url": "https://example.com/callback",
+ "wait_for_connections": True # NEW
+ }
+)
+```
+
+### 2. Session-Specific Modifier Types
+
+Introduced new modifier types for better session-based tool execution: `SessionExecuteMetaModifiers` and `SessionMetaToolOptions`.
+
+**TypeScript:**
+```typescript
+const tools = await session.tools({
+ modifySchema: ({ toolSlug, toolkitSlug, schema }) => schema,
+ beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => params,
+ afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => result
+});
+```
+
+**Python:**
+```python
+from composio.core.models import before_execute_meta, after_execute_meta
+
+@before_execute_meta
+def before_modifier(tool, toolkit, session_id, params):
+ return params
+
+@after_execute_meta
+def after_modifier(tool, toolkit, session_id, response):
+ return response
+
+tools = session.tools(modifiers=[before_modifier, after_modifier])
+```
+
+### 3. Dedicated Method for Tool Router Meta Tools
+
+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.
+
+**TypeScript:**
+```typescript
+const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123', {
+ modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
+ // Customize schema
+ return schema;
+ }
+});
+```
+
+**Python:**
+```python
+meta_tools = tools_model.get_raw_tool_router_meta_tools(
+ session_id="session_123",
+ modifiers=[schema_modifier]
+)
+```
+
+## Internal Improvements
+
+### 1. Performance Optimization
+
+Eliminated unnecessary tool fetching during tool router execution, resulting in faster tool execution with fewer API calls.
+
+### 2. Improved Architecture
+
+Tool router sessions now fetch tools directly from the session API endpoint instead of using tool slugs, providing better consistency and reliability.
+
+### 3. Simplified Implementation
+
+Removed redundant tool schema fetching in execution paths, using a hardcoded 'composio' toolkit slug for meta tools.
+
+## Backward Compatibility
+
+This release is fully backward compatible:
+
+- All existing code continues to work without modifications
+- New properties are optional with sensible defaults
+- New modifier types can be adopted incrementally
+- Internal changes have no impact on public APIs
+- No migration required
+
+## Impact Summary
+
+| Change | Runtime Breaking | TypeScript Breaking | Migration Required |
+|--------|------------------|---------------------|-------------------|
+| `wait_for_connections` property | No | No | No |
+| Session-specific modifiers | No | No | No |
+| `getRawToolRouterMetaTools` method | No | No | No |
+| Tool router uses session API | No | No | No |
+| Optimized tool execution | No | No | No |
+
+All changes follow semantic versioning principles and maintain full backward compatibility.
+
diff --git a/fern/pyproject.toml b/fern/pyproject.toml
index 84d7f6d48..cc3b6cf1d 100644
--- a/fern/pyproject.toml
+++ b/fern/pyproject.toml
@@ -10,7 +10,7 @@ dependencies = [
"click>=8.1.7",
"ruamel-yaml>=0.18.10",
"typing-extensions>=4.13.0",
- "composio-client==1.22.0",
+ "composio-client==1.25.0",
"openai>=1.79.0",
"composio==1.0.0rc5",
# Dependencies for SDK doc generation
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c987c6ab3..77e372939 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -13,8 +13,8 @@ catalogs:
specifier: ^4.20250917.0
version: 4.20250917.0
'@composio/client':
- specifier: 0.1.0-alpha.52
- version: 0.1.0-alpha.52
+ specifier: 0.1.0-alpha.54
+ version: 0.1.0-alpha.54
'@modelcontextprotocol/sdk':
specifier: ^1.24.0
version: 1.24.1
@@ -827,7 +827,7 @@ importers:
version: 1.0.0-alpha.1
'@composio/client':
specifier: 'catalog:'
- version: 0.1.0-alpha.52
+ version: 0.1.0-alpha.54
'@composio/core':
specifier: workspace:*
version: link:../core
@@ -921,7 +921,7 @@ importers:
dependencies:
'@composio/client':
specifier: 'catalog:'
- version: 0.1.0-alpha.52
+ version: 0.1.0-alpha.54
'@composio/json-schema-to-zod':
specifier: workspace:*
version: link:../json-schema-to-zod
@@ -1654,8 +1654,8 @@ packages:
'@cloudflare/[email protected]':
resolution: {integrity: sha512-Lsn9dZoRYZZCXXHZNa50cMP8kWhQZG9M7WjxNSiXFzC8bk4Wh/0SYYo4YINxEjEt6h2o69LmAhFaJ+qgaJTh8Q==}
- '@composio/[email protected]':
- resolution: {integrity: sha512-IFPa77R/v4JUX0QeRHRTEkJCBZ+OqMQBh1rIn4Nv5PIP1eP3sZqxlTYJUKPS4qLNnwBJRD+Vn7/jUs5J7pdv5g==}
+ '@composio/[email protected]':
+ resolution: {integrity: sha512-3whr4XjaMQUTcxmkaePMPeISUEE3NDRmGaf6lHReS9M2t6jiQbuZT3OktBvvw9QHrH+AZPXgaDoH65Hlr4qGWA==}
'@composio/[email protected]':
resolution: {integrity: sha512-IpbfST0SSs/CEv+PIf6+EL0feNuJhQyUrOHJLPge8NhyLLrCyVqvujRIPyRUUjy0NDsked/Mm5VpJmYM6OACbg==}
@@ -8563,7 +8563,7 @@ snapshots:
'@cloudflare/[email protected]': {}
- '@composio/[email protected]': {}
+ '@composio/[email protected]': {}
'@composio/[email protected]': {}
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 76220c449..ad0265b11 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -15,7 +15,7 @@ packages:
catalog:
'@cloudflare/vitest-pool-workers': ^0.9.2
'@cloudflare/workers-types': ^4.20250917.0
- '@composio/client': 0.1.0-alpha.52
+ '@composio/client': 0.1.0-alpha.54
'@modelcontextprotocol/sdk': ^1.24.0
ai: ^6.0.3
openai: ^5.20.3
diff --git a/python/composio/core/models/_modifiers.py b/python/composio/core/models/_modifiers.py
index 7b936e87a..cb4195dc4 100644
--- a/python/composio/core/models/_modifiers.py
+++ b/python/composio/core/models/_modifiers.py
@@ -74,8 +74,20 @@ SchemaModifierL: t.TypeAlias = t.Literal["schema"]
class Modifier:
def __init__(
self,
- modifier: t.Optional[AfterExecute | BeforeExecute | SchemaModifier],
- type_: AfterExecuteModifierL | BeforeExecuteModifierL | SchemaModifierL,
+ modifier: t.Optional[
+ AfterExecute
+ | BeforeExecute
+ | SchemaModifier
+ | BeforeExecuteMeta
+ | AfterExecuteMeta
+ ],
+ type_: (
+ AfterExecuteModifierL
+ | BeforeExecuteModifierL
+ | SchemaModifierL
+ | AfterExecuteMetaModifierL
+ | BeforeExecuteMetaModifierL
+ ),
tools: t.List[str],
toolkits: t.List[str],
) -> None:
@@ -234,6 +246,84 @@ def schema_modifier(
raise ValueError("Either tools or toolkits must be provided")
+def before_execute_meta(modifier: t.Optional[BeforeExecuteMeta]) -> Modifier: ...
+
+
+def before_execute_meta(
+ *,
+ tools: t.Optional[t.List[str]] = None,
+ toolkits: t.Optional[t.List[str]] = None,
+) -> t.Callable[[BeforeExecuteMeta], Modifier]: ...
+
+
+def before_execute_meta(
+ modifier: t.Optional[BeforeExecuteMeta] = None,
+ *,
+ tools: t.Optional[t.List[str]] = None,
+ toolkits: t.Optional[t.List[str]] = None,
+) -> Modifier | t.Callable[[BeforeExecuteMeta], Modifier]:
+ if modifier is not None:
+ return Modifier(
+ modifier=modifier,
+ type_="before_execute_meta",
+ tools=tools or [],
+ toolkits=toolkits or [],
+ )
+
+ if tools is not None or toolkits is not None:
+ return t.cast(
+ t.Callable[[BeforeExecuteMeta], Modifier],
+ functools.partial(
+ before_execute_meta,
+ tools=tools or [],
+ toolkits=toolkits or [],
+ ),
+ )
+
+ raise ValueError("Either tools or toolkits must be provided")
+
+
+def after_execute_meta(modifier: t.Optional[AfterExecuteMeta]) -> Modifier: ...
+
+
+def after_execute_meta(
+ *,
+ tools: t.Optional[t.List[str]] = None,
+ toolkits: t.Optional[t.List[str]] = None,
+) -> t.Callable[[AfterExecuteMeta], Modifier]: ...
+
+
+def after_execute_meta(
+ modifier: t.Optional[AfterExecuteMeta] = None,
+ *,
+ tools: t.Optional[t.List[str]] = None,
+ toolkits: t.Optional[t.List[str]] = None,
+) -> Modifier | t.Callable[[AfterExecuteMeta], Modifier]:
+ if modifier is not None:
+ return Modifier(
+ modifier=modifier,
+ type_="after_execute_meta",
+ tools=tools or [],
+ toolkits=toolkits or [],
+ )
+
+ if tools is not None or toolkits is not None:
+ return t.cast(
+ t.Callable[[AfterExecuteMeta], Modifier],
+ functools.partial(
+ after_execute_meta,
+ tools=tools or [],
+ toolkits=toolkits or [],
+ ),
+ )
+
+ raise ValueError("Either tools or toolkits must be provided")
+
+
Modifiers = t.List[Modifier]
@@ -270,29 +360,142 @@ def apply_modifier_by_type(
) -> "Tool": ...
+def apply_modifier_by_type(
+ modifiers: Modifiers,
+ toolkit: str,
+ tool: str,
+ *,
+ type: BeforeExecuteMetaModifierL,
+ session_id: str,
+ params: t.Dict[str, t.Any],
+) -> t.Dict[str, t.Any]: ...
+
+
+def apply_modifier_by_type(
+ modifiers: Modifiers,
+ toolkit: str,
+ tool: str,
+ *,
+ type: AfterExecuteMetaModifierL,
+ session_id: str,
+ response: "ToolExecutionResponse",
+) -> "ToolExecutionResponse": ...
+
+
def apply_modifier_by_type(
modifiers: Modifiers,
toolkit: str,
tool: str,
*,
- type: t.Literal["before_execute", "after_execute", "schema"],
+ type: t.Literal[
+ "before_execute",
+ "after_execute",
+ "schema",
+ "before_execute_meta",
+ "after_execute_meta",
+ ],
schema: t.Optional["Tool"] = None,
request: t.Optional["ToolExecuteParams"] = None,
response: t.Optional["ToolExecutionResponse"] = None,
-) -> ModifierInOut:
+ session_id: t.Optional[str] = None,
+ params: t.Optional[t.Dict[str, t.Any]] = None,
+) -> t.Union[ModifierInOut, t.Dict[str, t.Any]]:
"""Apply a modifier to a tool."""
- data = schema or request or response
- if data is None:
+ # For meta modifiers, we handle them differently
+ if type in ("before_execute_meta", "after_execute_meta"):
+ if session_id is None:
+ raise ValueError("session_id is required for meta modifiers")
+
+ if type == "before_execute_meta":
+ if params is None:
+ raise ValueError("params is required for before_execute_meta")
+ result_params: t.Dict[str, t.Any] = params
+ for modifier in modifiers:
+ if modifier.type == type:
+ # Check if modifier should be applied
+ should_apply = (
+ (len(modifier.tools) == 0 and len(modifier.toolkits) == 0)
+ or tool in modifier.tools
+ or toolkit in modifier.toolkits
+ )
+
+ if should_apply and modifier.modifier is not None:
+ result_params = t.cast(BeforeExecuteMeta, modifier.modifier)(
+ tool, toolkit, session_id, result_params
+ )
+ return result_params
+ else: # after_execute_meta
+ if response is None:
+ raise ValueError("response is required for after_execute_meta")
+ result_response: "ToolExecutionResponse" = response
+ for modifier in modifiers:
+ if modifier.type == type:
+ # Check if modifier should be applied
+ should_apply = (
+ (len(modifier.tools) == 0 and len(modifier.toolkits) == 0)
+ or tool in modifier.tools
+ or toolkit in modifier.toolkits
+ )
+
+ if should_apply and modifier.modifier is not None:
+ result_response = t.cast(AfterExecuteMeta, modifier.modifier)(
+ tool, toolkit, session_id, result_response
+ )
+ return result_response
+
+ # For regular modifiers
+ result: ModifierInOut
+ if schema is not None:
+ result = schema
+ elif request is not None:
+ result = request
+ elif response is not None:
+ result = response
+ else:
raise ValueError("No data provided")
for modifier in modifiers:
- data = modifier.apply(
+ result = modifier.apply(
toolkit=toolkit,
tool=tool,
- data=data,
+ data=result,
modifer_type=type,
)
- return data
+ return result
+
+
+class BeforeExecuteMeta(t.Protocol):
+ """
+ A modifier that is called before the meta tool is executed in a session context.
+ """
+
+ def __call__(
+ self,
+ tool: str,
+ toolkit: str,
+ session_id: str,
+ params: t.Dict[str, t.Any],
+ ) -> t.Dict[str, t.Any]: ...
+
+
+class AfterExecuteMeta(t.Protocol):
+ """
+ A modifier that is called after the meta tool is executed in a session context.
+ """
+
+ def __call__(
+ self,
+ tool: str,
+ toolkit: str,
+ session_id: str,
+ response: ToolExecutionResponse,
+ ) -> ToolExecutionResponse: ...
+
+
+AfterExecuteMetaModifierL: t.TypeAlias = t.Literal["after_execute_meta"]
+BeforeExecuteMetaModifierL: t.TypeAlias = t.Literal["before_execute_meta"]
class ToolOptions(te.TypedDict):
diff --git a/python/composio/core/models/tool_router.py b/python/composio/core/models/tool_router.py
index d93a5e8f1..00d9c757d 100644
--- a/python/composio/core/models/tool_router.py
+++ b/python/composio/core/models/tool_router.py
@@ -162,10 +162,15 @@ class ToolRouterManageConnectionsConfig(te.TypedDict, total=False):
enable: Whether to use tools to manage connections. Defaults to True.
If False, you need to manage connections manually.
callback_url: Optional callback URL to use for OAuth redirects.
+ wait_for_connections: 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.
"""
enable: bool
callback_url: str
+ wait_for_connections: bool
@dataclass
@@ -559,17 +564,15 @@ class ToolRouter(Resource, t.Generic[TProvider]):
def _create_tools_fn(
self,
session_id: str,
- tool_slugs: t.Sequence[str],
) -> ToolsFn:
"""
Create a tools function that wraps tools for the provider.
:param session_id: The session ID
- :param tool_slugs: List of tool slugs to wrap
+ :param tool_slugs: List of tool slugs to wrap (not used anymore, kept for backward compatibility)
:return: Function that returns provider-wrapped tools
"""
- from composio.core.models._modifiers import apply_modifier_by_type
- from composio.core.models.tools import Tool, Tools as ToolsModel
+ from composio.core.models.tools import Tools as ToolsModel
from composio.core.provider import AgenticProvider, NonAgenticProvider
if self._provider is None:
@@ -628,10 +631,14 @@ class ToolRouter(Resource, t.Generic[TProvider]):
)
# With custom modifiers
- tools = session.tools(modifiers={
- 'pre_execute': lambda tool, args: print(f"Executing {tool}"),
- 'post_execute': lambda tool, result: print(f"Result: {result}"),
- })
+ from composio.core.models import schema_modifier
+
+ @schema_modifier
+ def modify_schema(tool: str, toolkit: str, schema):
+ print(f"Executing {tool} from {toolkit}")
+ return schema
+
+ tools = session.tools(modifiers=[modify_schema])
```
Note:
@@ -639,22 +646,13 @@ class ToolRouter(Resource, t.Generic[TProvider]):
only the tools enabled for this session based on the configuration
provided during session creation.
"""
- # Get raw tool schemas
- router_tools = tools_model.get_raw_composio_tools(tools=list(tool_slugs))
-
- # Apply schema modifiers
- if modifiers is not None:
- type_schema: t.Literal["schema"] = "schema"
- router_tools = [
- apply_modifier_by_type(
- modifiers=modifiers,
- toolkit=tool.toolkit.slug if tool.toolkit else "unknown",
- tool=tool.slug,
- type=type_schema,
- schema=t.cast(Tool, tool),
- )
- for tool in router_tools
- ]
+
+ # Get raw meta tools from the session (instead of using tool_slugs)
+ # This fetches tools directly from the tool router session
+ router_tools = tools_model.get_raw_tool_router_meta_tools(
+ session_id=session_id,
+ modifiers=modifiers,
+ )
# Always enhance schema descriptions (type hints and required notes)
for tool in router_tools:
@@ -664,15 +662,6 @@ class ToolRouter(Resource, t.Generic[TProvider]):
)
)
- # Process file uploadable schemas
- if self._auto_upload_download_files:
- for tool in router_tools:
- tool.input_parameters = (
- tools_model._file_helper.process_file_uploadable_schema(
- schema=tool.input_parameters,
- )
- )
-
# Wrap tools with provider
if issubclass(type(self._provider), NonAgenticProvider):
return t.cast(NonAgenticProvider, self._provider).wrap_tools(
@@ -794,7 +783,10 @@ class ToolRouter(Resource, t.Generic[TProvider]):
connections. Defaults to True.
- 'callback_url' (str, optional): Callback URL for
OAuth redirects.
- Example: {'enable': True, 'callback_url': 'https://example.com/callback'}
+ - 'wait_for_connections' (bool, optional): Whether to wait
+ for users to finish authenticating connections before
+ proceeding to the next step. Defaults to False.
+ Example: {'enable': True, 'callback_url': 'https://example.com/callback', 'wait_for_connections': True}
:param auth_configs: Optional mapping of toolkit slug to auth config ID.
Example: {'github': 'ac_xxx', 'slack': 'ac_yyy'}
:param connected_accounts: Optional mapping of toolkit slug to connected account ID.
@@ -859,6 +851,7 @@ class ToolRouter(Resource, t.Generic[TProvider]):
manage_connections={
'enable': True,
'callback_url': 'https://example.com/callback',
+ 'wait_for_connections': True,
}
)
@@ -933,12 +926,17 @@ class ToolRouter(Resource, t.Generic[TProvider]):
transformed_config["tags"] = transformed_tags
tools_payload[toolkit_slug] = transformed_config
- # Parse callback_uri
+ # Parse callback_url and wait_for_connections from manage_connections config
callback_url = (
manage_connections.get("callback_url")
if isinstance(manage_connections, dict)
else omit
)
+ wait_for_connections = (
+ manage_connections.get("wait_for_connections")
+ if isinstance(manage_connections, dict)
+ else omit
+ )
# Build the API payload
create_params: t.Dict[str, t.Any] = {
@@ -951,6 +949,8 @@ class ToolRouter(Resource, t.Generic[TProvider]):
}
if callback_url is not None and callback_url is not omit:
connections_config["callback_url"] = callback_url
+ if wait_for_connections is not None and wait_for_connections is not omit:
+ connections_config["enable_wait_for_connections"] = wait_for_connections
create_params["manage_connections"] = connections_config
@@ -996,7 +996,7 @@ class ToolRouter(Resource, t.Generic[TProvider]):
mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
url=session.mcp.url,
),
- tools=self._create_tools_fn(session.session_id, session.tool_router_tools),
+ tools=self._create_tools_fn(session.session_id),
authorize=self._create_authorize_fn(session.session_id),
toolkits=self._create_toolkits_fn(session.session_id),
)
@@ -1034,7 +1034,7 @@ class ToolRouter(Resource, t.Generic[TProvider]):
mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
url=session.mcp.url,
),
- tools=self._create_tools_fn(session.session_id, session.tool_router_tools),
+ tools=self._create_tools_fn(session.session_id),
authorize=self._create_authorize_fn(session.session_id),
toolkits=self._create_toolkits_fn(session.session_id),
)
diff --git a/python/composio/core/models/tools.py b/python/composio/core/models/tools.py
index d06014c5f..d51823ed6 100644
--- a/python/composio/core/models/tools.py
+++ b/python/composio/core/models/tools.py
@@ -162,6 +162,73 @@ class Tools(Resource, t.Generic[TProvider]):
)
return tools_list
+ def get_raw_tool_router_meta_tools(
+ self,
+ session_id: str,
+ modifiers: t.Optional["Modifiers"] = None,
+ ) -> list[Tool]:
+ """
+ Fetches the meta tools for a tool router session.
+
+ This method fetches the meta tools from the Composio API and transforms them to
+ the expected format. It provides access to the underlying meta tool data without
+ provider-specific wrapping.
+
+ :param session_id: The session ID to get the meta tools for
+ :param modifiers: Optional modifiers to apply to the tool schemas
+ :return: The list of meta tools
+
+ Example:
+ ```python
+ from composio import Composio
+
+ composio = Composio()
+ tools_model = composio.tools
+
+ # Get meta tools for a session
+ meta_tools = tools_model.get_raw_tool_router_meta_tools("session_123")
+ print(meta_tools)
+
+ # Get meta tools with schema modifiers
+ from composio.core.models import schema_modifier
+
+ @schema_modifier
+ def modify_schema(tool: str, toolkit: str, schema):
+ # Customize the schema
+ schema.description = f"Modified: {schema.description}"
+ return schema
+
+ meta_tools = tools_model.get_raw_tool_router_meta_tools(
+ "session_123",
+ modifiers=[modify_schema]
+ )
+ ```
+ """
+ # Fetch meta tools from the API
+ tools_response = self._client.tool_router.session.tools(session_id=session_id)
+ # Cast to Tool type - session.tools returns compatible Item type from different response schema
+ tools_list: t.List[Tool] = [t.cast(Tool, item) for item in tools_response.items]
+
+ # Apply schema modifiers if provided
+ if modifiers is not None:
+ from composio.core.models._modifiers import apply_modifier_by_type
+
+ tools_list = [
+ t.cast(
+ Tool,
+ apply_modifier_by_type(
+ modifiers=modifiers,
+ toolkit=tool.toolkit.slug,
+ tool=tool.slug,
+ type="schema",
+ schema=tool,
+ ),
+ )
+ for tool in tools_list
+ ]
+
+ return tools_list
+
def _get(
self,
user_id: str,
@@ -352,10 +419,8 @@ class Tools(Resource, t.Generic[TProvider]):
:param arguments: The tool arguments
:return: Tool execution response
"""
- # Get tool schema for modifiers
- tool = self.get_raw_composio_tool_by_slug(slug)
-
# Apply before_execute modifiers
+ # Meta tools are always from the 'composio' toolkit
processed_arguments = arguments
if modifiers is not None:
params: ToolExecuteParams = {
@@ -364,7 +429,7 @@ class Tools(Resource, t.Generic[TProvider]):
type_before: t.Literal["before_execute"] = "before_execute"
modified_params = apply_modifier_by_type(
modifiers=modifiers,
- toolkit=tool.toolkit.slug if tool.toolkit else "unknown",
+ toolkit="composio",
tool=slug,
type=type_before,
request=params,
@@ -392,7 +457,7 @@ class Tools(Resource, t.Generic[TProvider]):
type_after: t.Literal["after_execute"] = "after_execute"
result = apply_modifier_by_type(
modifiers=modifiers,
- toolkit=tool.toolkit.slug if tool.toolkit else "unknown",
+ toolkit="composio",
tool=slug,
type=type_after,
response=result,
@@ -644,7 +709,6 @@ __all__ = [
"ToolExecuteParams",
"ToolExecutionResponse",
"Modifiers",
- "Modifiers",
"after_execute",
"before_execute",
"schema_modifier",
diff --git a/python/providers/anthropic/pyproject.toml b/python/providers/anthropic/pyproject.toml
index 2f91cc7c6..c9420142a 100644
--- a/python/providers/anthropic/pyproject.toml
+++ b/python/providers/anthropic/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-anthropic"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get an array of tools with your Anthropic LLMs."
readme = "README.md"
requires-python = ">=3.10,<4"
diff --git a/python/providers/anthropic/setup.py b/python/providers/anthropic/setup.py
index 9907b28cf..5388140e5 100644
--- a/python/providers/anthropic/setup.py
+++ b/python/providers/anthropic/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_anthropic",
- version="0.10.4",
+ version="0.10.5",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Anthropic LLMs.",
diff --git a/python/providers/autogen/pyproject.toml b/python/providers/autogen/pyproject.toml
index bfa92c6ec..b3640a72c 100644
--- a/python/providers/autogen/pyproject.toml
+++ b/python/providers/autogen/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-autogen"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get an array of tools with your autogen agent."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/autogen/setup.py b/python/providers/autogen/setup.py
index 77190fcf1..a069efcb8 100644
--- a/python/providers/autogen/setup.py
+++ b/python/providers/autogen/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_autogen",
- version="0.10.4",
+ version="0.10.5",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Autogen agent.",
diff --git a/python/providers/claude_agent_sdk/pyproject.toml b/python/providers/claude_agent_sdk/pyproject.toml
index 5cc8d443b..5734cfa6b 100644
--- a/python/providers/claude_agent_sdk/pyproject.toml
+++ b/python/providers/claude_agent_sdk/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-claude-agent-sdk"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get an array of tools with Claude Code Agents SDK."
readme = "README.md"
requires-python = ">=3.10,<4"
diff --git a/python/providers/claude_agent_sdk/setup.py b/python/providers/claude_agent_sdk/setup.py
index 2164eeab4..b8653c40a 100644
--- a/python/providers/claude_agent_sdk/setup.py
+++ b/python/providers/claude_agent_sdk/setup.py
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
setup(
name="composio_claude_agent_sdk",
- version="0.10.4",
+ version="0.10.5",
author="Composio",
author_email="[email protected]",
description="Use Composio to get array of tools for Claude Agent SDK",
diff --git a/python/providers/crewai/pyproject.toml b/python/providers/crewai/pyproject.toml
index f50e46058..b67a20763 100644
--- a/python/providers/crewai/pyproject.toml
+++ b/python/providers/crewai/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-crewai"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get an array of tools with your CrewAI agent."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/crewai/setup.py b/python/providers/crewai/setup.py
index d5c0ebd7c..47c2af21e 100644
--- a/python/providers/crewai/setup.py
+++ b/python/providers/crewai/setup.py
@@ -6,7 +6,7 @@ from setuptools import setup
setup(
name="composio_crewai",
- version="0.10.4",
+ version="0.10.5",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your CrewAI agent.",
diff --git a/python/providers/gemini/pyproject.toml b/python/providers/gemini/pyproject.toml
index 4e745ab6b..3427520a3 100644
--- a/python/providers/gemini/pyproject.toml
+++ b/python/providers/gemini/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-gemini"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get an array of tools with your Gemini agent."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/gemini/setup.py b/python/providers/gemini/setup.py
index fe3ed113f..746537b26 100644
--- a/python/providers/gemini/setup.py
+++ b/python/providers/gemini/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_gemini",
- version="0.10.4",
+ version="0.10.5",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Gemini agent.",
diff --git a/python/providers/google/pyproject.toml b/python/providers/google/pyproject.toml
index a7c1ffe0b..efee93ec0 100644
--- a/python/providers/google/pyproject.toml
+++ b/python/providers/google/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-google"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/google/setup.py b/python/providers/google/setup.py
index 4e72b09ae..c73ca5227 100644
--- a/python/providers/google/setup.py
+++ b/python/providers/google/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_google",
- version="0.10.4",
+ version="0.10.5",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
diff --git a/python/providers/google_adk/pyproject.toml b/python/providers/google_adk/pyproject.toml
index 611b9caf8..6f7145e4f 100644
--- a/python/providers/google_adk/pyproject.toml
+++ b/python/providers/google_adk/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-google-adk"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/google_adk/setup.py b/python/providers/google_adk/setup.py
index 404fb545d..aa949f5ba 100644
--- a/python/providers/google_adk/setup.py
+++ b/python/providers/google_adk/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_google_adk",
- version="0.10.4",
+ version="0.10.5",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
diff --git a/python/providers/langchain/pyproject.toml b/python/providers/langchain/pyproject.toml
index 691e3398e..f7f4e257f 100644
--- a/python/providers/langchain/pyproject.toml
+++ b/python/providers/langchain/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-langchain"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get an array of tools with your Langchain agent."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/langchain/setup.py b/python/providers/langchain/setup.py
index cc633d920..dbdf06f95 100644
--- a/python/providers/langchain/setup.py
+++ b/python/providers/langchain/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_langchain",
- version="0.10.4",
+ version="0.10.5",
author="composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Langchain agent.",
diff --git a/python/providers/langgraph/pyproject.toml b/python/providers/langgraph/pyproject.toml
index b9c205a54..0918f5ad9 100644
--- a/python/providers/langgraph/pyproject.toml
+++ b/python/providers/langgraph/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-langgraph"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get array of tools with LangGraph Agent Workflows."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/langgraph/setup.py b/python/providers/langgraph/setup.py
index cb51e6d4c..9beed004f 100644
--- a/python/providers/langgraph/setup.py
+++ b/python/providers/langgraph/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_langgraph",
- version="0.10.4",
+ version="0.10.5",
author="composio",
author_email="[email protected]",
description="Use Composio to get array of tools with LangGraph Agent Workflows",
diff --git a/python/providers/llamaindex/pyproject.toml b/python/providers/llamaindex/pyproject.toml
index 128824b68..9c85661b2 100644
--- a/python/providers/llamaindex/pyproject.toml
+++ b/python/providers/llamaindex/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-llamaindex"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get array of tools with LlamaIndex Agent Workflows."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/llamaindex/setup.py b/python/providers/llamaindex/setup.py
index bacd9dbf8..c4922c717 100644
--- a/python/providers/llamaindex/setup.py
+++ b/python/providers/llamaindex/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_llamaindex",
- version="0.10.4",
+ version="0.10.5",
author="composio",
author_email="[email protected]",
description="Use Composio to get array of tools with LlamaIndex Agent Workflows",
diff --git a/python/providers/openai/pyproject.toml b/python/providers/openai/pyproject.toml
index f7553aae7..d01b28251 100644
--- a/python/providers/openai/pyproject.toml
+++ b/python/providers/openai/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-openai"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get an array of tools with your OpenAI Function Call."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/openai/setup.py b/python/providers/openai/setup.py
index afcb8400a..23c639267 100644
--- a/python/providers/openai/setup.py
+++ b/python/providers/openai/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_openai",
- version="0.10.4",
+ version="0.10.5",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your OpenAI Function Call.",
diff --git a/python/providers/openai_agents/pyproject.toml b/python/providers/openai_agents/pyproject.toml
index 310916603..541618d04 100644
--- a/python/providers/openai_agents/pyproject.toml
+++ b/python/providers/openai_agents/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-openai-agents"
-version = "0.10.4"
+version = "0.10.5"
description = "Use Composio to get array of strongly typed tools for OpenAI Agents"
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/openai_agents/setup.py b/python/providers/openai_agents/setup.py
index 2ae1d67e7..ac6bb972e 100644
--- a/python/providers/openai_agents/setup.py
+++ b/python/providers/openai_agents/setup.py
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
setup(
name="composio_openai_agents",
- version="0.10.4",
+ version="0.10.5",
author="Composio",
author_email="[email protected]",
description="Use Composio to get array of strongly typed tools for OpenAI Agents",
diff --git a/python/pyproject.toml b/python/pyproject.toml
index a866d9c20..95910a008 100644
--- a/python/pyproject.toml
+++ b/python/pyproject.toml
@@ -1,13 +1,13 @@
[project]
name = "composio"
-version = "0.10.4"
+version = "0.10.5"
description = "SDK for integrating Composio with your applications."
readme = "README.md"
requires-python = ">=3.10,<4"
dependencies = [
"pysher>=1.0.8",
"pydantic>=2.6.4",
- "composio-client==1.22.0",
+ "composio-client==1.25.0",
"typing-extensions>=4.0.0",
"openai",
]
diff --git a/python/setup.py b/python/setup.py
index 6624426e3..3485a408d 100644
--- a/python/setup.py
+++ b/python/setup.py
@@ -25,7 +25,7 @@ setup(
install_requires=[
"pysher==1.0.8",
"pydantic>=2.6.4",
- "composio-client==1.22.0",
+ "composio-client==1.25.0",
"typing-extensions>=4.0.0",
],
include_package_data=True,
diff --git a/python/tests/test_tool_router.py b/python/tests/test_tool_router.py
index 1b88f6d85..c1b68e1c7 100644
--- a/python/tests/test_tool_router.py
+++ b/python/tests/test_tool_router.py
@@ -446,6 +446,28 @@ class TestToolRouter:
== "https://example.com/callback"
)
+ def test_create_session_with_wait_for_connections(self, tool_router, mock_client):
+ """Test creating a session with wait_for_connections in manage_connections config."""
+ session = tool_router.create(
+ user_id="user_123",
+ manage_connections={
+ "enable": True,
+ "callback_url": "https://example.com/callback",
+ "wait_for_connections": True,
+ },
+ )
+
+ assert session.session_id == "session_123"
+
+ call_args = mock_client.tool_router.session.create.call_args
+ kwargs = call_args.kwargs
+ assert kwargs["manage_connections"]["enable"] is True
+ assert (
+ kwargs["manage_connections"]["callback_url"]
+ == "https://example.com/callback"
+ )
+ assert kwargs["manage_connections"]["enable_wait_for_connections"] is True
+
def test_create_session_with_auth_configs(self, tool_router, mock_client):
"""Test creating a session with auth configs."""
session = tool_router.create(
@@ -750,8 +772,9 @@ class TestToolRouter:
mock_tool.slug = "GMAIL_FETCH_EMAILS"
mock_tool.toolkit.slug = "gmail"
mock_tool.input_parameters = {}
- mock_tools_instance.get_raw_composio_tools.return_value = [mock_tool]
- mock_tools_instance._file_helper.process_schema_recursively.return_value = {}
+ mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool]
+ mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {}
+ mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {}
mock_tools_class.return_value = mock_tools_instance
# Setup provider mock
@@ -765,18 +788,16 @@ class TestToolRouter:
client=mock_client, provider=mock_provider, auto_upload_download_files=True
)
- # Verify get_raw_composio_tools was called
- mock_tools_instance.get_raw_composio_tools.assert_called_once()
+ # Verify get_raw_tool_router_meta_tools was called
+ mock_tools_instance.get_raw_tool_router_meta_tools.assert_called_once()
# Verify provider's wrap_tools was called
mock_provider.wrap_tools.assert_called_once()
assert result == "mocked-wrapped-tools"
@patch("composio.core.models.tools.Tools")
- @patch("composio.core.models._modifiers.apply_modifier_by_type")
def test_tools_function_with_modifiers(
self,
- mock_apply_modifier,
mock_tools_class,
tool_router,
mock_client,
@@ -788,13 +809,11 @@ class TestToolRouter:
mock_tool.slug = "GMAIL_FETCH_EMAILS"
mock_tool.toolkit.slug = "gmail"
mock_tool.input_parameters = {}
- mock_tools_instance.get_raw_composio_tools.return_value = [mock_tool]
- mock_tools_instance._file_helper.process_schema_recursively.return_value = {}
+ mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool]
+ mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {}
+ mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {}
mock_tools_class.return_value = mock_tools_instance
- # Setup apply_modifier_by_type to return the tool unchanged
- mock_apply_modifier.return_value = mock_tool
-
# Setup provider mock
mock_provider.wrap_tools.return_value = "mocked-wrapped-tools"
@@ -809,8 +828,9 @@ class TestToolRouter:
# Verify provider's wrap_tools was called
mock_provider.wrap_tools.assert_called_once()
- # Verify apply_modifier_by_type was called with the modifier
- assert mock_apply_modifier.called
+ # Verify get_raw_tool_router_meta_tools was called with modifiers
+ call_args = mock_tools_instance.get_raw_tool_router_meta_tools.call_args
+ assert call_args.kwargs.get("modifiers") == modifiers
assert result == "mocked-wrapped-tools"
def test_session_mcp_type_http(self, tool_router, mock_client):
@@ -989,8 +1009,9 @@ class TestToolRouterExecution:
mock_tool.slug = "GMAIL_SEND_EMAIL"
mock_tool.toolkit.slug = "gmail"
mock_tool.input_parameters = {}
- mock_tools_instance.get_raw_composio_tools.return_value = [mock_tool]
- mock_tools_instance._file_helper.process_schema_recursively.return_value = {}
+ mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool]
+ mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {}
+ mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {}
mock_tools_instance._wrap_execute_tool_for_tool_router = MagicMock(
return_value=lambda slug, args: {
"data": {},
@@ -1024,14 +1045,6 @@ class TestToolRouterExecution:
mock_execute_response
)
- # Setup mock tool
- mock_tool = MagicMock()
- mock_tool.slug = "GMAIL_SEND_EMAIL"
- mock_tool.toolkit.slug = "gmail"
-
- # Mock get_raw_composio_tool_by_slug
- mock_client.tools.retrieve.return_value = mock_tool
-
# Create a real Tools instance to test the execute function
from composio.core.models.tools import Tools as RealTools
@@ -1059,14 +1072,6 @@ class TestToolRouterExecution:
self, tool_router, mock_client, mock_provider
):
"""Test that modifiers are applied before and after tool execution."""
- # Setup mock tool
- mock_tool = MagicMock()
- mock_tool.slug = "GMAIL_SEND_EMAIL"
- mock_tool.toolkit.slug = "gmail"
-
- # Mock get_raw_composio_tool_by_slug
- mock_client.tools.retrieve.return_value = mock_tool
-
# Setup execute_meta response
mock_execute_response = MagicMock()
mock_execute_response.data = {"result": "success"}
@@ -1118,14 +1123,6 @@ class TestToolRouterExecution:
def test_execute_tool_error_handling(self, tool_router, mock_client, mock_provider):
"""Test that tool execution errors are handled correctly."""
- # Setup mock tool
- mock_tool = MagicMock()
- mock_tool.slug = "GMAIL_SEND_EMAIL"
- mock_tool.toolkit.slug = "gmail"
-
- # Mock get_raw_composio_tool_by_slug
- mock_client.tools.retrieve.return_value = mock_tool
-
# Setup execute_meta to return an error
mock_execute_response = MagicMock()
mock_execute_response.data = {}
@@ -1165,8 +1162,9 @@ class TestToolRouterIntegration:
mock_tool.slug = "TOOL1"
mock_tool.toolkit.slug = "github"
mock_tool.input_parameters = {}
- mock_tools_instance.get_raw_composio_tools.return_value = [mock_tool]
- mock_tools_instance._file_helper.process_schema_recursively.return_value = {}
+ mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool]
+ mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {}
+ mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {}
mock_tools_class.return_value = mock_tools_instance
# Setup provider mock
diff --git a/ts/examples/tool-router/src/logger.ts b/ts/examples/tool-router/src/logger.ts
index e6340c8cc..533f3a693 100644
--- a/ts/examples/tool-router/src/logger.ts
+++ b/ts/examples/tool-router/src/logger.ts
@@ -1,8 +1,8 @@
-import { ExecuteToolModifiers } from "@composio/core";
+import { SessionExecuteMetaModifiers } from "@composio/core";
import ora from 'ora';
let spinner = ora();
-export const modifiers: ExecuteToolModifiers = {
+export const modifiers: SessionExecuteMetaModifiers = {
beforeExecute: ({ toolSlug, params }) => {
spinner = ora();
spinner.start(`Executing ${toolSlug}`);
diff --git a/ts/packages/core/src/composio.ts b/ts/packages/core/src/composio.ts
index dfe92189e..dd539fe3d 100644
--- a/ts/packages/core/src/composio.ts
+++ b/ts/packages/core/src/composio.ts
@@ -5,8 +5,7 @@ import { Toolkits } from './models/Toolkits';
import { Triggers } from './models/Triggers';
import { AuthConfigs } from './models/AuthConfigs';
import { ConnectedAccounts } from './models/ConnectedAccounts';
-import { MCP } from './models/MCP.experimental';
-import { MCP as DeprecatedMCP } from './models/MCP';
+import { MCP } from './models/MCP';
import { telemetry } from './telemetry/Telemetry';
import { getSDKConfig, getToolkitVersionsFromEnv } from './utils/sdk';
import logger from './utils/logger';
@@ -196,11 +195,6 @@ export class Composio<
*/
use: (id: string) => Promise<ToolRouterSession<unknown, unknown, TProvider>>;
- /**
- * Experimental features
- */
- experimental: {};
-
/**
* Creates a new instance of the Composio SDK.
*
@@ -289,21 +283,6 @@ export class Composio<
this.create = this.toolRouter.create.bind(this.toolRouter);
this.use = this.toolRouter.use.bind(this.toolRouter);
- /**
- * Initialize Experimental features
- */
- this.experimental = {
- create: async (
- userId: string,
- routerConfig?: ToolRouterCreateSessionConfig
- ): Promise<ToolRouterSession<unknown, unknown, TProvider>> => {
- return this.toolRouter.create(userId, routerConfig);
- },
- use: async (id: string): Promise<ToolRouterSession<unknown, unknown, TProvider>> => {
- return this.toolRouter.use(id);
- },
- };
-
/**
* Initialize the client telemetry.
*/
diff --git a/ts/packages/core/src/lib/toolRouterParams.ts b/ts/packages/core/src/lib/toolRouterParams.ts
index 6db26eca9..c9c6fd0cc 100644
--- a/ts/packages/core/src/lib/toolRouterParams.ts
+++ b/ts/packages/core/src/lib/toolRouterParams.ts
@@ -4,8 +4,14 @@ import {
ToolRouterConfigTools,
ToolRouterConfigToolsSchema,
ToolRouterToolsParam,
+ ToolRouterConfigManageConnectionsSchema,
+ ToolRouterCreateSessionConfig,
+ ToolRouterToolkitsParamSchema,
+ ToolRouterToolkitsDisabledConfigSchema,
+ ToolRouterToolkitsEnabledConfigSchema,
} from '../types/toolRouter.types';
import { ValidationError } from '../errors';
+import { z } from 'zod';
export const transformToolRouterToolsParams = (
params?: Record<string, ToolRouterToolsParam | ToolRouterConfigTools> | undefined
@@ -72,3 +78,64 @@ export const transformToolRouterTagsParams = (
};
}
};
+
+export const transformToolRouterManageConnectionsParams = (
+ params?: boolean | z.infer<typeof ToolRouterConfigManageConnectionsSchema>
+): SessionCreateParams.ManageConnections => {
+ if (params === undefined) {
+ // Default case when params is undefined
+ return {
+ enable: true,
+ };
+ }
+
+ if (typeof params === 'boolean') {
+ return {
+ enable: params,
+ };
+ }
+
+ // Parse the params using the zod schema for type safety
+ const parsedResult = ToolRouterConfigManageConnectionsSchema.safeParse(params);
+ if (!parsedResult.success) {
+ throw new ValidationError('Failed to parse manage connections config', {
+ cause: parsedResult.error,
+ });
+ }
+
+ const config = parsedResult.data;
+ return {
+ enable: config.enable ?? true,
+ callback_url: config.callbackUrl,
+ enable_wait_for_connections: config.waitForConnections,
+ };
+};
+
+export const transformToolRouterWorkbenchParams = (
+ params?: ToolRouterCreateSessionConfig['workbench']
+): SessionCreateParams.Workbench | undefined => {
+ if (!params) {
+ return undefined;
+ }
+
+ return {
+ enable_proxy_execution: params.enableProxyExecution,
+ auto_offload_threshold: params.autoOffloadThreshold,
+ };
+};
+
+export const transformToolRouterToolkitsParams = (
+ params?: ToolRouterCreateSessionConfig['toolkits']
+): SessionCreateParams.Enable | SessionCreateParams.Disable | undefined => {
+ if (!params) {
+ return undefined;
+ }
+
+ // If it's an array, convert to enable format
+ if (Array.isArray(params)) {
+ return { enable: params };
+ }
+
+ // Otherwise return as-is (already in enable/disable format)
+ return params as SessionCreateParams.Enable | SessionCreateParams.Disable;
+};
diff --git a/ts/packages/core/src/models/MCP.experimental.ts b/ts/packages/core/src/models/MCP.experimental.ts
deleted file mode 100644
index 8eef1ea73..000000000
--- a/ts/packages/core/src/models/MCP.experimental.ts
+++ /dev/null
@@ -1,430 +0,0 @@
-import { Composio as ComposioClient } from '@composio/client';
-import { telemetry } from '../telemetry/Telemetry';
-import {
- MCPConfigCreationParams,
- MCPConfigCreationParamsSchema,
- MCPConfigCreateResponse,
- MCPConfigResponseSchema,
- MCPServerInstance,
- MCPGetInstanceParams,
- MCPGetInstanceParamsSchema,
- MCPListResponse,
- MCPListParams,
- MCPListParamsSchema,
- MCPListResponseSchema,
- MCPItemSchema,
- MCPItem,
- MCPUpdateParams,
- MCPUpdateParamsSchema,
-} from '../types/mcp.experimental.types';
-import { MCPServerInstanceSchema } from '../types/mcp.experimental.types';
-import { ValidationError } from '../errors/ValidationErrors';
-import { transform } from '../utils/transform';
-import { McpUpdateResponse } from '@composio/client/resources.js';
-import { McpRetrieveResponse } from '@composio/client/resources';
-
-function transformMCPItemResponse(response: McpUpdateResponse | McpRetrieveResponse): MCPItem {
- return transform(response)
- .with(MCPItemSchema)
- .using(raw => ({
- name: raw.name,
- allowedTools: raw.allowed_tools,
- id: raw.id,
- authConfigIds: raw.auth_config_ids,
- commands: raw.commands,
- MCPUrl: raw.mcp_url,
- toolkitIcons: raw.toolkit_icons,
- serverInstanceCount: raw.server_instance_count,
- toolkits: raw.toolkits,
- }));
-}
-/**
- * MCP (Model Control Protocol) class
- * Handles MCP server operations.
- * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
- */
-export class MCP {
- client: ComposioClient;
-
- constructor(client: ComposioClient) {
- this.client = client;
- telemetry.instrument(this, 'MCP');
- }
-
- /**
- * Create a new MCP configuration.
- * @param {Object} params - Parameters for creating the MCP configuration
- * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
- * @param {Object} params.options - Configuration options
- * @param {string} params.options.name - Unique name for the MCP configuration
- * @param {boolean} [params.options.manuallyManageConnections] - Whether to use chat-based authentication or manually connect accounts
- * @returns {Promise<McpServerCreateResponse<T>>} Created server details with instance getter
- *
- * @example
- * ```typescript
- * const server = await composio.mcpConfig.create("personal-mcp-server", {
- * toolkits: ["github", "slack"],
- * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
- * manuallyManageConnections: false
- * }
- * });
- *
- * const server = await composio.mcpConfig.create("personal-mcp-server", {
- * toolkits: [{ toolkit: "gmail", authConfigId: "ac_243434343" }],
- * allowedTools: ["GMAIL_FETCH_EMAILS"],
- * manuallyManageConnections: false
- * }
- * });
- * ```
- */
- async create(name: string, mcpConfig: MCPConfigCreationParams): Promise<MCPConfigCreateResponse> {
- const config = MCPConfigCreationParamsSchema.safeParse(mcpConfig);
- if (config.error) {
- throw new ValidationError('Invalid parameters passed to create mcp config', {
- cause: config.error,
- });
- }
-
- const toolkits: string[] = [];
- const auth_config_ids: string[] = [];
- const custom_tools: string[] = config.data.allowedTools ?? [];
-
- // extract all the toolkits, authconfigs, and allowed tools to separate slugs
- config.data.toolkits.forEach(toolkit => {
- if (typeof toolkit === 'string') {
- toolkits.push(toolkit);
- } else if (toolkit.toolkit) {
- toolkits.push(toolkit.toolkit);
- } else if (toolkit.authConfigId) {
- auth_config_ids.push(toolkit.authConfigId);
- }
- });
-
- const server = await this.client.mcp.custom.create({
- name,
- toolkits,
- auth_config_ids,
- custom_tools,
- // if manually manage account is set to true, disable composio account management tools
- managed_auth_via_composio: config.data.manuallyManageConnections ? false : true,
- });
-
- const camelCaseServer = transform(server)
- .with(MCPConfigResponseSchema)
- .using(raw => ({
- name: raw.name,
- allowedTools: raw.allowed_tools,
- id: raw.id,
- authConfigIds: raw.auth_config_ids,
- commands: raw.commands,
- MCPUrl: raw.mcp_url,
- }));
-
- return {
- ...camelCaseServer,
- generate: async (userId: string): Promise<MCPServerInstance> => {
- return await this.generate(userId, server.id, {
- manuallyManageConnections: config.data.manuallyManageConnections,
- });
- },
- };
- }
-
- /**
- * List the MCP servers with optional filtering and pagination
- * @param {Object} options - Filtering and pagination options
- * @param {number} [options.page=1] - Page number for pagination (1-based)
- * @param {number} [options.limit=10] - Maximum number of items to return per page
- * @param {string[]} [options.toolkits=[]] - Array of toolkit names to filter by
- * @param {string[]} [options.authConfigs=[]] - Array of auth configuration IDs to filter by
- * @param {string} [options.name] - Filter by MCP server name (partial match)
- * @returns {Promise<MCPListResponse>} Paginated list of MCP servers with metadata
- *
- * @example
- * ```typescript
- * // List all MCP servers
- * const allServers = await composio.experimental.mcp.list({});
- *
- * // List with pagination
- * const pagedServers = await composio.experimental.mcp.list({
- * page: 2,
- * limit: 5
- * });
- *
- * // Filter by toolkit
- * const githubServers = await composio.experimental.mcp.list({
- * toolkits: ['github', 'slack']
- * });
- *
- * // Filter by name
- * const namedServers = await composio.experimental.mcp.list({
- * name: 'personal'
- * });
- * ```
- */
- async list(options: MCPListParams): Promise<MCPListResponse> {
- const { data: params, error } = MCPListParamsSchema.safeParse(options);
- if (error) {
- throw new ValidationError('Failed to validate list options', {
- cause: error,
- });
- }
-
- const listResponse = await this.client.mcp.list({
- page_no: params.page,
- limit: params.limit,
- toolkits: params.toolkits?.length > 0 ? params.toolkits.join(',') : undefined,
- auth_config_ids: params.authConfigs?.length > 0 ? params.authConfigs.join(',') : undefined,
- name: params.name,
- });
-
- const transformedListResponse = transform(listResponse)
- .with(MCPListResponseSchema)
- .using(raw => ({
- currentPage: raw.current_page,
- totalPages: raw.total_pages,
- items: raw.items.map(item => ({
- name: item.name,
- allowedTools: item.allowed_tools,
- id: item.id,
- authConfigIds: item.auth_config_ids,
- commands: item.commands,
- MCPUrl: item.mcp_url,
- toolkitIcons: item.toolkit_icons,
- serverInstanceCount: item.server_instance_count,
- toolkits: item.toolkits,
- })),
- }));
-
- return transformedListResponse;
- }
-
- /**
- * Retrieve detailed information about a specific MCP server by its ID
- * @param {string} serverId - The unique identifier of the MCP server to retrieve
- * @returns {Promise<MCPItem>} Complete MCP server details including configuration, tools, and metadata
- *
- * @example
- * ```typescript
- * // Get a specific MCP server by ID
- * const server = await composio.experimental.mcp.get("mcp_12345");
- *
- * console.log(server.name); // "My Personal MCP Server"
- * console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
- * console.log(server.toolkits); // ["github", "slack"]
- * console.log(server.serverInstanceCount); // 3
- *
- * // Access setup commands for different clients
- * console.log(server.commands.claude); // Claude setup command
- * console.log(server.commands.cursor); // Cursor setup command
- * console.log(server.commands.windsurf); // Windsurf setup command
- *
- * // Use the MCP URL for direct connections
- * const mcpUrl = server.MCPUrl;
- * ```
- *
- * @throws {ValidationError} When the server ID is invalid or server not found
- */
- async get(serverId: string): Promise<MCPItem> {
- const response = await this.client.mcp.retrieve(serverId);
- return transformMCPItemResponse(response);
- }
-
- /**
- * Delete an MCP server configuration permanently
- * @param {string} serverId - The unique identifier of the MCP server to delete
- * @returns {Promise<{id: string; deleted: boolean}>} Confirmation object with server ID and deletion status
- *
- * @example
- * ```typescript
- * // Delete an MCP server by ID
- * const result = await composio.experimental.mcp.delete("mcp_12345");
- *
- * if (result.deleted) {
- * console.log(`Server ${result.id} has been successfully deleted`);
- * } else {
- * console.log(`Failed to delete server ${result.id}`);
- * }
- *
- * // Example with error handling
- * try {
- * const result = await composio.experimental.mcp.delete("mcp_12345");
- * console.log("Deletion successful:", result);
- * } catch (error) {
- * console.error("Failed to delete MCP server:", error.message);
- * }
- *
- * // Delete and verify from list
- * await composio.experimental.mcp.delete("mcp_12345");
- * const servers = await composio.experimental.mcp.list({});
- * const serverExists = servers.items.some(server => server.id === "mcp_12345");
- * console.log("Server still exists:", serverExists); // Should be false
- * ```
- *
- * @throws {ValidationError} When the server ID is invalid or server not found
- * @throws {Error} When the server cannot be deleted due to active connections or other constraints
- *
- * @warning This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
- */
- async delete(serverId: string): Promise<{ id: string; deleted: boolean }> {
- return await this.client.mcp.delete(serverId);
- }
-
- /**
- * Update an existing MCP server configuration with new settings
- * @param {string} serverId - The unique identifier of the MCP server to update
- * @param {Object} config - Update configuration parameters
- * @param {string} [config.name] - New name for the MCP server
- * @param {Array} [config.toolkits] - Updated toolkit configurations
- * @param {string} [config.toolkits[].toolkit] - Toolkit identifier (e.g., "github", "slack")
- * @param {string} [config.toolkits[].authConfigId] - Auth configuration ID for the toolkit
- * @param {string[]} [config.toolkits[].allowedTools] - Specific tools to enable for this toolkit
- * @param {boolean} [config.manuallyManageConnections] - Whether to manually manage account connections
- * @returns {Promise<MCPItem>} Updated MCP server configuration with all details
- *
- * @example
- * ```typescript
- * // Update server name only
- * const updatedServer = await composio.experimental.mcp.update("mcp_12345", {
- * name: "My Updated MCP Server"
- * });
- *
- * // Update toolkits and tools
- * const serverWithNewTools = await composio.experimental.mcp.update("mcp_12345", {
- * toolkits: [
- * {
- * toolkit: "github",
- * authConfigId: "auth_abc123",
- * allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
- * },
- * {
- * toolkit: "slack",
- * authConfigId: "auth_xyz789",
- * allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]
- * }
- * ]
- * });
- *
- * // Update connection management setting
- * const serverWithManualAuth = await composio.experimental.mcp.update("mcp_12345", {
- * name: "Manual Auth Server",
- * manuallyManageConnections: true
- * });
- *
- * // Complete update example
- * const fullyUpdatedServer = await composio.experimental.mcp.update("mcp_12345", {
- * name: "Production MCP Server",
- * toolkits: [
- * {
- * toolkit: "gmail",
- * authConfigId: "auth_gmail_prod",
- * }
- * ],
- * allowedTools: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"]
- * manuallyManageConnections: false
- * });
- *
- * console.log("Updated server:", fullyUpdatedServer.name);
- * console.log("New tools:", fullyUpdatedServer.allowedTools);
- * ```
- *
- * @throws {ValidationError} When the update parameters are invalid or malformed
- * @throws {Error} When the server ID doesn't exist or update fails
- *
- * @note Only provided fields will be updated. Omitted fields will retain their current values.
- * @note When updating toolkits, the entire toolkit configuration is replaced, not merged.
- */
- async update(serverId: string, config: MCPUpdateParams): Promise<MCPItem> {
- const { data: params, error } = MCPUpdateParamsSchema.safeParse(config);
- if (error) {
- throw new ValidationError('Failed to validate update params', {
- cause: error,
- });
- }
-
- const toolkits: string[] = [];
- const auth_config_ids: string[] = [];
- const custom_tools: string[] | undefined = params.allowedTools ?? undefined;
-
- // extract all the toolkits, authconfigs, and allowed tools to separate slugs
- params.toolkits?.forEach(toolkit => {
- if (typeof toolkit === 'string') {
- toolkits.push(toolkit);
- } else if (toolkit.toolkit) {
- toolkits.push(toolkit.toolkit);
- } else if (toolkit.authConfigId) {
- auth_config_ids.push(toolkit.authConfigId);
- }
- });
- const response = await this.client.mcp.update(serverId, {
- ...{ name: params.name ?? undefined },
- ...(params.toolkits
- ? {
- custom_tools: custom_tools,
- toolkits: toolkits,
- auth_config_ids: auth_config_ids,
- }
- : {}),
- ...{ managed_auth_via_composio: params.manuallyManageConnections ?? undefined },
- });
- return transformMCPItemResponse(response);
- }
-
- /**
- * Get server URLs for an existing MCP server.
- * The response is wrapped according to the provider's specifications.
- *
- * @example
- * ```typescript
- * import { Composio } from "@composio/code";
- *
- * const composio = new Composio();
- * const mcp = await composio.experimental.mcp.generate("default", "<mcp_config_id>");
- * ```
- *
- * @param userId {string} external user id from your database for whom you want the server for
- * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
- * @param options {object} additional options
- * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
- */
- async generate(
- userId: string,
- mcpConfigId: string,
- options?: MCPGetInstanceParams
- ): Promise<MCPServerInstance> {
- const server = await this.client.mcp.retrieve(mcpConfigId);
- const params = MCPGetInstanceParamsSchema.safeParse(
- options ?? { manuallyManageConnections: false }
- );
- if (params.error) {
- throw new ValidationError('Invalid params passed for Get Instance Params', {
- cause: params.error,
- });
- }
-
- const urlResponse = await this.client.mcp.generate.url({
- mcp_server_id: mcpConfigId,
- user_ids: [userId],
- managed_auth_by_composio: options?.manuallyManageConnections ? false : true,
- });
-
- const userIdsURL = urlResponse.user_ids_url[0];
- const serverInstance = MCPServerInstanceSchema.safeParse({
- id: server.id,
- name: server.name,
- type: 'streamable_http' as const,
- url: userIdsURL,
- userId: userId,
- allowedTools: server.allowed_tools,
- authConfigs: server.auth_config_ids,
- });
-
- if (serverInstance.error) {
- throw new ValidationError('Failed to parse MCP server instance', {
- cause: serverInstance.error,
- });
- }
-
- return serverInstance.data;
- }
-}
diff --git a/ts/packages/core/src/models/MCP.ts b/ts/packages/core/src/models/MCP.ts
index 8604c7113..8eef1ea73 100644
--- a/ts/packages/core/src/models/MCP.ts
+++ b/ts/packages/core/src/models/MCP.ts
@@ -1,880 +1,430 @@
-/**
- * @fileoverview MCP class for Composio SDK, used to manage MCP servers.
- *
- * @module MCP
- */
-import ComposioClient from '@composio/client';
+import { Composio as ComposioClient } from '@composio/client';
import { telemetry } from '../telemetry/Telemetry';
import {
- MCPToolkitConfig,
- MCPAuthOptions,
- MCPGetServerParams,
- MCPToolkitConfigsArraySchema,
- MCPAuthOptionsSchema,
- ComposioCustomCreateResponseSchema,
- ComposioMcpListResponseSchema,
- McpRetrieveResponseSchema,
- ComposioMcpDeleteResponseSchema,
- ComposioMcpUpdateResponseSchema,
- McpUrlResponse,
- McpUrlResponseCamelCase,
- McpServerGetResponse,
- McpServerCreateResponse,
- ComposioGenerateURLResponseSchema,
- McpListResponse,
- McpRetrieveResponse,
- McpDeleteResponse,
- McpUpdateResponse,
- GenerateURLResponse,
- GenerateURLParamsSchema,
- GenerateURLParams,
- McpToolkitConnectionStatus,
- McpUserConnectionStatus,
- ConnectionStatus,
-} from '../types/mcp.types';
-import { CustomCreateResponse as CustomCreateResponseRaw } from '@composio/client/resources/mcp';
+ MCPConfigCreationParams,
+ MCPConfigCreationParamsSchema,
+ MCPConfigCreateResponse,
+ MCPConfigResponseSchema,
+ MCPServerInstance,
+ MCPGetInstanceParams,
+ MCPGetInstanceParamsSchema,
+ MCPListResponse,
+ MCPListParams,
+ MCPListParamsSchema,
+ MCPListResponseSchema,
+ MCPItemSchema,
+ MCPItem,
+ MCPUpdateParams,
+ MCPUpdateParamsSchema,
+} from '../types/mcp.experimental.types';
+import { MCPServerInstanceSchema } from '../types/mcp.experimental.types';
import { ValidationError } from '../errors/ValidationErrors';
-import { BaseComposioProvider } from '../provider/BaseProvider';
-import {
- transformMcpCreateResponse,
- transformMcpListResponse,
- transformMcpRetrieveResponse,
- transformMcpDeleteResponse,
- transformMcpUpdateResponse,
- transformMcpGenerateUrlResponse,
-} from '../utils/transformers/mcp';
-import { Toolkits } from './Toolkits';
-import { ToolkitAuthFieldsResponse } from '../types/toolkit.types';
-import { ConnectionRequest } from '../types/connectionRequest.types';
-import logger from '../utils/logger';
-
-/**
- * Extract the MCP response type from a provider.
- */
-type ExtractMcpResponseType<T> =
- T extends BaseComposioProvider<unknown, unknown, infer TMcp>
- ? TMcp
- : /* @default */ McpServerGetResponse;
-
+import { transform } from '../utils/transform';
+import { McpUpdateResponse } from '@composio/client/resources.js';
+import { McpRetrieveResponse } from '@composio/client/resources';
+
+function transformMCPItemResponse(response: McpUpdateResponse | McpRetrieveResponse): MCPItem {
+ return transform(response)
+ .with(MCPItemSchema)
+ .using(raw => ({
+ name: raw.name,
+ allowedTools: raw.allowed_tools,
+ id: raw.id,
+ authConfigIds: raw.auth_config_ids,
+ commands: raw.commands,
+ MCPUrl: raw.mcp_url,
+ toolkitIcons: raw.toolkit_icons,
+ serverInstanceCount: raw.server_instance_count,
+ toolkits: raw.toolkits,
+ }));
+}
/**
* MCP (Model Control Protocol) class
- * Handles MCP server operations
+ * Handles MCP server operations.
+ * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
*/
-export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknown>> {
- private client: ComposioClient;
- private toolkits: Toolkits;
- protected provider: TProvider;
-
- // Trick to store types derived from a generic parameter inside the class.
- // It's similar to `using type` declarations in C++.
- // See: https://stackoverflow.com/questions/76017389/type-or-interface-inside-class-in-typescript.
- declare readonly TMcpResponse: ExtractMcpResponseType<TProvider>;
+export class MCP {
+ client: ComposioClient;
- constructor(client: ComposioClient, provider: TProvider) {
+ constructor(client: ComposioClient) {
this.client = client;
- this.provider = provider;
- this.toolkits = new Toolkits(client);
telemetry.instrument(this, 'MCP');
}
/**
- * Validates toolkit configurations using Zod schema
- * @private
- * @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations to validate
- * @param {MCPAuthOptions} [authOptions] - Authentication options to validate
- * @throws {ValidationError} If validation fails
- */
- private validateInputs(toolkitConfigs: MCPToolkitConfig[], authOptions?: MCPAuthOptions): void {
- // Validate toolkit configurations
- const toolkitConfigsResult = MCPToolkitConfigsArraySchema.safeParse(toolkitConfigs);
- if (toolkitConfigsResult.error) {
- throw new ValidationError('Failed to parse toolkit configurations', {
- cause: toolkitConfigsResult.error,
- });
- }
-
- // Validate auth options if provided
- if (authOptions !== undefined) {
- const authOptionsResult = MCPAuthOptionsSchema.safeParse(authOptions);
- if (authOptionsResult.error) {
- throw new ValidationError('Failed to parse auth options', {
- cause: authOptionsResult.error,
- });
- }
- }
- }
-
- /**
- * Create a new MCP server
- * @param {Object} params - Parameters for creating the MCP server
+ * Create a new MCP configuration.
+ * @param {Object} params - Parameters for creating the MCP configuration
* @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
- * @param {Object} params.options - Server creation options
- * @param {string} params.options.name - Unique name for the MCP server
- * @param {boolean} [params.options.isChatAuth] - Whether to use chat-based authentication
- * @returns {Promise<McpServerCreateResponse<TMcpResponse>>} Created server details with instance getter
+ * @param {Object} params.options - Configuration options
+ * @param {string} params.options.name - Unique name for the MCP configuration
+ * @param {boolean} [params.options.manuallyManageConnections] - Whether to use chat-based authentication or manually connect accounts
+ * @returns {Promise<McpServerCreateResponse<T>>} Created server details with instance getter
*
* @example
* ```typescript
- * const server = await composio.mcp.create("personal-mcp-server", [
- * {
- * authConfigId: "ac_xyz",
- * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
- * }
- * ],
- * {
- * isChatAuth: true
- * }
+ * const server = await composio.mcpConfig.create("personal-mcp-server", {
+ * toolkits: ["github", "slack"],
+ * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
+ * manuallyManageConnections: false
+ * }
* });
*
- * // Use convenience method on response
- * const urls = await server.getServer({
- * userId: "user123"
+ * const server = await composio.mcpConfig.create("personal-mcp-server", {
+ * toolkits: [{ toolkit: "gmail", authConfigId: "ac_243434343" }],
+ * allowedTools: ["GMAIL_FETCH_EMAILS"],
+ * manuallyManageConnections: false
+ * }
* });
* ```
*/
- async create(
- name: string,
- serverConfig: Array<{
- authConfigId: string;
- allowedTools: string[];
- }>,
- options: {
- isChatAuth?: boolean;
- }
- ): Promise<McpServerCreateResponse<typeof this.TMcpResponse>> {
- // Validate inputs using Zod schemas
- if (!serverConfig || serverConfig.length === 0) {
- throw new ValidationError('At least one auth config is required', {});
- }
-
- if (!name) {
- throw new ValidationError('Server name is required', {});
- }
-
- // Check if server with this name already exists
- try {
- const mcpServer = await this.getByName(name);
- const authConfigs = mcpServer.authConfigIds?.sort()!;
- const sortedCurrentAuthConfigs = serverConfig.map(config => config.authConfigId).sort();
- if (
- authConfigs.length > 0 &&
- !authConfigs.every((config, index) => config === sortedCurrentAuthConfigs[index])
- ) {
- throw new ValidationError(
- 'MCP server with this name already exists with different auth configs',
- {
- meta: { serverName: name },
- }
- );
- }
- // If we reach here, server exists
- const tools = mcpServer.tools?.sort()!;
- const sortedCurrentTools = serverConfig.flatMap(config => config.allowedTools).sort();
- if (tools?.length > 0 && !tools.every((tool, index) => tool === sortedCurrentTools[index])) {
- throw new ValidationError('MCP server with this name already exists with different tools', {
- meta: { serverName: name },
- });
- }
-
- // Get toolkits from auth configs
- const authConfigDetails = await Promise.all(
- serverConfig.map(config => this.client.authConfigs.retrieve(config.authConfigId))
- );
- const toolkits = authConfigDetails.map(config => config.toolkit.slug);
-
- const camelCaseResponse = transformMcpCreateResponse({
- id: mcpServer.id,
- name: mcpServer.name,
- auth_config_ids: serverConfig.map(config => config.authConfigId),
- allowed_tools: serverConfig.flatMap(config => config.allowedTools),
- managed_auth_via_composio: options.isChatAuth || false,
- commands: mcpServer.commands!,
- created_at: mcpServer.createdAt!,
- updated_at: mcpServer.updatedAt!,
- mcp_url: mcpServer.mcpUrl!,
+ async create(name: string, mcpConfig: MCPConfigCreationParams): Promise<MCPConfigCreateResponse> {
+ const config = MCPConfigCreationParamsSchema.safeParse(mcpConfig);
+ if (config.error) {
+ throw new ValidationError('Invalid parameters passed to create mcp config', {
+ cause: config.error,
});
-
- return {
- ...camelCaseResponse,
- toolkits,
- getServer: async (params: MCPGetServerParams): Promise<typeof this.TMcpResponse> => {
- return this.getServer(camelCaseResponse.id, params.userId || '', {
- isChatAuth: options.isChatAuth,
- });
- },
- } as McpServerCreateResponse<typeof this.TMcpResponse>;
- } catch (error) {
- // If error is not about server not found, re-throw it
- if (error instanceof ValidationError && !error.message.includes('not found')) {
- throw error;
- }
- // Server doesn't exist, we can proceed with creation
}
- // Get toolkits from auth configs
- const authConfigDetails = await Promise.all(
- serverConfig.map(config => this.client.authConfigs.retrieve(config.authConfigId))
- );
- const toolkits = authConfigDetails.map(config => config.toolkit.slug);
+ const toolkits: string[] = [];
+ const auth_config_ids: string[] = [];
+ const custom_tools: string[] = config.data.allowedTools ?? [];
- // Create a custom MCP server with the toolkit configurations
- let mcpServerCreatedResponse: CustomCreateResponseRaw;
- try {
- mcpServerCreatedResponse = await this.client.mcp.custom.create({
- name: name,
- toolkits: toolkits,
- custom_tools: serverConfig.flatMap(config => config.allowedTools),
- managed_auth_via_composio: options.isChatAuth || false,
- auth_config_ids: serverConfig.map(config => config.authConfigId),
- });
- } catch (error) {
- throw new ValidationError('Failed to create MCP server', {
- cause: error,
- });
- }
+ // extract all the toolkits, authconfigs, and allowed tools to separate slugs
+ config.data.toolkits.forEach(toolkit => {
+ if (typeof toolkit === 'string') {
+ toolkits.push(toolkit);
+ } else if (toolkit.toolkit) {
+ toolkits.push(toolkit.toolkit);
+ } else if (toolkit.authConfigId) {
+ auth_config_ids.push(toolkit.authConfigId);
+ }
+ });
- // Validate the server creation response
- const serverResponseResult =
- ComposioCustomCreateResponseSchema.safeParse(mcpServerCreatedResponse);
- if (serverResponseResult.error) {
- throw new ValidationError('Failed to parse MCP server creation response', {
- cause: serverResponseResult.error,
- });
- }
+ const server = await this.client.mcp.custom.create({
+ name,
+ toolkits,
+ auth_config_ids,
+ custom_tools,
+ // if manually manage account is set to true, disable composio account management tools
+ managed_auth_via_composio: config.data.manuallyManageConnections ? false : true,
+ });
- // Transform the response to camelCase
- const camelCaseResponse = transformMcpCreateResponse(mcpServerCreatedResponse);
+ const camelCaseServer = transform(server)
+ .with(MCPConfigResponseSchema)
+ .using(raw => ({
+ name: raw.name,
+ allowedTools: raw.allowed_tools,
+ id: raw.id,
+ authConfigIds: raw.auth_config_ids,
+ commands: raw.commands,
+ MCPUrl: raw.mcp_url,
+ }));
- // Return response with convenience getServer method
return {
- ...camelCaseResponse,
- toolkits,
- getServer: async (params: MCPGetServerParams): Promise<typeof this.TMcpResponse> => {
- // Delegate to the standalone getServer method
- return this.getServer(camelCaseResponse.id, params.userId || '', {
- isChatAuth: options.isChatAuth,
+ ...camelCaseServer,
+ generate: async (userId: string): Promise<MCPServerInstance> => {
+ return await this.generate(userId, server.id, {
+ manuallyManageConnections: config.data.manuallyManageConnections,
});
},
- } as McpServerCreateResponse<typeof this.TMcpResponse>;
+ };
}
/**
- * Get the connection status of a user for an MCP server
- *
- * Checks whether a user has the necessary connected accounts to use all toolkits
- * configured in the specified MCP server. Returns both overall connection status
- * and individual status for each toolkit.
- *
- * @param {Object} params - Parameters for checking connection status
- * @param {string} params.id - The UUID of the MCP server to check
- * @param {string} params.userId - The ID of the user to check connection status for
- * @returns {Promise<McpUserConnectionStatus>} Complete connection status including:
- * - `type`: Overall status (CONNECTED if all toolkits are connected, DISCONNECTED otherwise)
- * - `connected`: Boolean indicating if user can use the MCP server
- * - `connectedToolkits`: Record mapping each toolkit name to its individual connection status
- *
- * @throws {ValidationError} When MCP server has no toolkits configured
- * @throws {ValidationError} When MCP server retrieval fails
+ * List the MCP servers with optional filtering and pagination
+ * @param {Object} options - Filtering and pagination options
+ * @param {number} [options.page=1] - Page number for pagination (1-based)
+ * @param {number} [options.limit=10] - Maximum number of items to return per page
+ * @param {string[]} [options.toolkits=[]] - Array of toolkit names to filter by
+ * @param {string[]} [options.authConfigs=[]] - Array of auth configuration IDs to filter by
+ * @param {string} [options.name] - Filter by MCP server name (partial match)
+ * @returns {Promise<MCPListResponse>} Paginated list of MCP servers with metadata
*
* @example
* ```typescript
- * // Check if user can access an MCP server with Gmail and Slack toolkits
- * const connectionStatus = await composio.mcp.getUserConnectionStatus('user123', 'mcp-server-uuid');
+ * // List all MCP servers
+ * const allServers = await composio.experimental.mcp.list({});
*
- * if (connectionStatus.connected) {
- * console.log('User can access all required toolkits');
- * // connectionStatus.type === ConnectionStatus.CONNECTED
- * } else {
- * console.log('User is missing some toolkit connections');
- * // Check individual toolkit statuses
- * Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {
- * if (!status.connected) {
- * console.log(`Missing connection for toolkit: ${toolkit}`);
- * }
- * });
- * }
- * ```
+ * // List with pagination
+ * const pagedServers = await composio.experimental.mcp.list({
+ * page: 2,
+ * limit: 5
+ * });
*
- * @example
- * ```typescript
- * // Example response when user has Gmail connected but missing Slack
- * {
- * type: ConnectionStatus.DISCONNECTED,
- * connected: false,
- * connectedToolkits: {
- * GMAIL: {
- * type: ConnectionStatus.CONNECTED,
- * connected: true,
- * toolkit: 'GMAIL',
- * connectedAccountId: 'conn_gmail_123'
- * },
- * SLACK: {
- * type: ConnectionStatus.DISCONNECTED,
- * connected: false,
- * toolkit: 'SLACK'
- * }
- * }
- * }
+ * // Filter by toolkit
+ * const githubServers = await composio.experimental.mcp.list({
+ * toolkits: ['github', 'slack']
+ * });
+ *
+ * // Filter by name
+ * const namedServers = await composio.experimental.mcp.list({
+ * name: 'personal'
+ * });
* ```
*/
- async getUserConnectionStatus(
- userId: string,
- serverId: string
- ): Promise<McpUserConnectionStatus> {
- const serverDetails = await this.get(serverId);
-
- if (!serverDetails.toolkits || serverDetails.toolkits.length === 0) {
- throw new ValidationError('MCP server has no toolkits configured', {
- meta: { serverId: serverId },
+ async list(options: MCPListParams): Promise<MCPListResponse> {
+ const { data: params, error } = MCPListParamsSchema.safeParse(options);
+ if (error) {
+ throw new ValidationError('Failed to validate list options', {
+ cause: error,
});
}
- // @TODO(utkarsh-dixit): Add auth_config_ids support here
- const connectedAccounts = await this.client.connectedAccounts.list({
- user_ids: [userId],
- toolkit_slugs: serverDetails.toolkits.map(toolkit => toolkit.toLowerCase()),
- statuses: ['ACTIVE'],
- });
-
- const connectedAccountsByToolkit = new Map<string, string>();
- connectedAccounts.items?.forEach(account => {
- connectedAccountsByToolkit.set(account.toolkit.slug.toLowerCase(), account.id);
+ const listResponse = await this.client.mcp.list({
+ page_no: params.page,
+ limit: params.limit,
+ toolkits: params.toolkits?.length > 0 ? params.toolkits.join(',') : undefined,
+ auth_config_ids: params.authConfigs?.length > 0 ? params.authConfigs.join(',') : undefined,
+ name: params.name,
});
- const connectedToolkits: Record<string, McpToolkitConnectionStatus> = {};
- let allToolkitsConnected = true;
-
- for (const toolkit of serverDetails.toolkits) {
- const connectedAccountId = connectedAccountsByToolkit.get(toolkit.toLowerCase());
-
- if (connectedAccountId) {
- connectedToolkits[toolkit] = {
- type: ConnectionStatus.CONNECTED,
- connected: true,
- toolkit,
- connectedAccountId,
- };
- } else {
- connectedToolkits[toolkit] = {
- type: ConnectionStatus.DISCONNECTED,
- connected: false,
- toolkit,
- };
- allToolkitsConnected = false;
- }
- }
-
- if (allToolkitsConnected) {
- return {
- type: ConnectionStatus.CONNECTED,
- connected: true,
- connectedToolkits,
- };
- } else {
- return {
- type: ConnectionStatus.DISCONNECTED,
- connected: false,
- connectedToolkits,
- };
- }
+ const transformedListResponse = transform(listResponse)
+ .with(MCPListResponseSchema)
+ .using(raw => ({
+ currentPage: raw.current_page,
+ totalPages: raw.total_pages,
+ items: raw.items.map(item => ({
+ name: item.name,
+ allowedTools: item.allowed_tools,
+ id: item.id,
+ authConfigIds: item.auth_config_ids,
+ commands: item.commands,
+ MCPUrl: item.mcp_url,
+ toolkitIcons: item.toolkit_icons,
+ serverInstanceCount: item.server_instance_count,
+ toolkits: item.toolkits,
+ })),
+ }));
+
+ return transformedListResponse;
}
/**
- * Get the connection parameters for a toolkit
- * @param {string} serverId - The UUID of the MCP server
- * @param {string} toolkit - The toolkit to get connection parameters for
- * @returns {Promise<ToolkitAuthFieldsResponse>} Connection parameters for the toolkit
- */
- async getConnectionParams(serverId: string, toolkit: string): Promise<ToolkitAuthFieldsResponse> {
- const mcpServerDetails = await this.get(serverId);
- const authConfigs = mcpServerDetails.authConfigIds
- ? await Promise.all(
- mcpServerDetails.authConfigIds.map(id => this.client.authConfigs.retrieve(id))
- )
- : [];
-
- const authConfig = authConfigs.find(config => config.toolkit.slug === toolkit);
- if (!authConfig) {
- throw new ValidationError('Auth config not found', {
- meta: { serverId: serverId, toolkit },
- });
- }
-
- const connectionParams = await this.toolkits.getConnectedAccountInitiationFields(
- toolkit,
- authConfig.auth_scheme!
- );
- return connectionParams;
- }
-
- /**
- * Authorize a user for a toolkit
- * @param {string} serverId - The UUID of the MCP server
- * @param {string} userId - The ID of the user to authorize
- * @param {string} toolkit - The toolkit to authorize
- * @returns {Promise<ConnectionRequest>} Connection request for the toolkit
- */
- async authorize(userId: string, serverId: string, toolkit: string): Promise<ConnectionRequest> {
- const mcpServerDetails = await this.get(serverId);
- const authConfigId = mcpServerDetails.authConfigIds?.[0];
- return this.toolkits.authorize(userId, toolkit, authConfigId);
- }
-
- /**
- * Get server URLs for an existing MCP server
- * @param {string} serverId - Server UUID
- * @param {string} userId - User ID to get server URLs for
- * @param {Object} [options] - Additional options for server configuration
- * @param {string[]} [options.limitTools] - Subset of tools to limit (from MCP config)
- * @param {boolean} [options.isChatAuth] - Whether to use chat-based authentication
- * @returns {Promise<TMcpResponse>} Transformed server URLs in provider-specific format
+ * Retrieve detailed information about a specific MCP server by its ID
+ * @param {string} serverId - The unique identifier of the MCP server to retrieve
+ * @returns {Promise<MCPItem>} Complete MCP server details including configuration, tools, and metadata
*
* @example
* ```typescript
- * // Get URLs for an existing server with basic user ID
- * const urls = await composio.mcp.getServer("mcp_xyz", "[email protected]");
+ * // Get a specific MCP server by ID
+ * const server = await composio.experimental.mcp.get("mcp_12345");
*
- * // Get URLs with additional options
- * const urls = await composio.mcp.getServer("mcp_xyz", "[email protected]", {
- * limitTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
- * isChatAuth: true
- * });
+ * console.log(server.name); // "My Personal MCP Server"
+ * console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
+ * console.log(server.toolkits); // ["github", "slack"]
+ * console.log(server.serverInstanceCount); // 3
+ *
+ * // Access setup commands for different clients
+ * console.log(server.commands.claude); // Claude setup command
+ * console.log(server.commands.cursor); // Cursor setup command
+ * console.log(server.commands.windsurf); // Windsurf setup command
+ *
+ * // Use the MCP URL for direct connections
+ * const mcpUrl = server.MCPUrl;
* ```
*
+ * @throws {ValidationError} When the server ID is invalid or server not found
*/
- async getServer(
- serverId: string,
- userId: string,
- options?: {
- limitTools?: string[];
- isChatAuth?: boolean;
- }
- ): Promise<typeof this.TMcpResponse> {
- // Get server details first
- const serverDetails = await this.get(serverId);
-
- // Validate userId is provided
- if (!userId) {
- throw new ValidationError('User ID is required', {});
- }
-
- // Extract toolkits from server details
- const toolkits = serverDetails.toolkits || [];
-
- const connectedAccountIds = (
- await Promise.all(
- toolkits.map(toolkit =>
- this.client.connectedAccounts
- .list({
- user_ids: [userId],
- toolkit_slugs: [toolkit],
- statuses: ['ACTIVE'],
- })
- .then(res => res.items?.[0]?.id)
- )
- )
- ).filter(Boolean);
-
- // Generate URL with error handling
- let data;
- try {
- data = await this.client.mcp.generate.url({
- user_ids: [userId],
- // @TODO(utkarsh-dixit): Add support for this later
- connected_account_ids: [],
- mcp_server_id: serverId,
- managed_auth_by_composio:
- options?.isChatAuth ?? serverDetails.managedAuthViaComposio ?? false,
- });
- } catch (error) {
- throw new ValidationError('Failed to generate MCP server URL', {
- cause: error,
- });
- }
-
- // Validate the URL generation response
- const urlResponseResult = ComposioGenerateURLResponseSchema.safeParse(data);
- if (urlResponseResult.error) {
- throw new ValidationError('Failed to parse MCP URL generation response', {
- cause: urlResponseResult.error,
- });
- }
-
- // Transform to camelCase
- const camelCaseData = transformMcpGenerateUrlResponse(data);
-
- // Use the wrapMcpServerResponse method to transform the response
- return this.wrapMcpServerResponse(
- camelCaseData,
- serverDetails.name,
- connectedAccountIds,
- [userId],
- toolkits
- );
+ async get(serverId: string): Promise<MCPItem> {
+ const response = await this.client.mcp.retrieve(serverId);
+ return transformMCPItemResponse(response);
}
/**
- * List MCP server configurations with filtering options
- * @param {Object} options - Filtering and pagination options
- * @param {number} [options.page] - Page number for pagination
- * @param {number} [options.limit] - Number of items per page
- * @param {string[]} [options.toolkits] - Filter servers by toolkit names
- * @param {string[]} [options.authConfigs] - Filter servers by auth config IDs
- * @param {string} [options.name] - Filter servers by name
- * @param {string} [options.user] - Filter servers by user ID
- * @returns {Promise<McpListResponse>} List of MCP servers matching the filters
+ * Delete an MCP server configuration permanently
+ * @param {string} serverId - The unique identifier of the MCP server to delete
+ * @returns {Promise<{id: string; deleted: boolean}>} Confirmation object with server ID and deletion status
*
* @example
* ```typescript
- * // List all servers with pagination
- * const servers = await composio.mcp.list({
- * page: 1,
- * limit: 10
- * });
+ * // Delete an MCP server by ID
+ * const result = await composio.experimental.mcp.delete("mcp_12345");
*
- * // List Gmail and Supabase servers
- * const filteredServers = await composio.mcp.list({
- * toolkits: ['GMAIL', 'SUPABASE'],
- * authConfigIds: ['auth_123', 'auth_456']
- * });
- * ```
- */
- async list(options: {
- page?: number;
- limit?: number;
- toolkits?: string[];
- authConfigs?: string[];
- name?: string;
- }): Promise<McpListResponse> {
- // List MCP servers with error handling
- let listResponse;
- try {
- listResponse = await this.client.mcp.list({
- page_no: options.page || 1,
- limit: options.limit || 10,
- toolkits: options?.toolkits?.join(',') || undefined,
- auth_config_ids: options?.authConfigs?.join(',') || undefined,
- name: options?.name,
- });
- } catch (error) {
- throw new ValidationError('Failed to list MCP servers', {
- cause: error,
- });
- }
-
- // Validate the list response
- const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
- if (listResponseResult.error) {
- throw new ValidationError('Failed to parse MCP server list response', {
- cause: listResponseResult.error,
- });
- }
-
- // Transform the response to camelCase
- return transformMcpListResponse(listResponse);
- }
-
- /**
- * Get details of a specific MCP server
- * @param {string} serverId - Server UUID
- * @returns {Promise<McpRetrieveResponse>} Server details
+ * if (result.deleted) {
+ * console.log(`Server ${result.id} has been successfully deleted`);
+ * } else {
+ * console.log(`Failed to delete server ${result.id}`);
+ * }
*
- * @example
- * ```typescript
- * const serverDetails = await composio.mcp.get('server-uuid');
- * ```
- */
- async get(serverId: string): Promise<McpRetrieveResponse> {
- // Retrieve MCP server with error handling
- let retrieveResponse;
- try {
- retrieveResponse = await this.client.mcp.retrieve(serverId);
- } catch (error) {
- throw new ValidationError('Failed to retrieve MCP server', {
- cause: error,
- });
- }
-
- // Validate the retrieve response
- const retrieveResponseResult = McpRetrieveResponseSchema.safeParse({
- ...retrieveResponse,
- mcpUrl: retrieveResponse.mcp_url,
- });
- if (retrieveResponseResult.error) {
- throw new ValidationError('Failed to parse MCP server retrieve response', {
- cause: retrieveResponseResult.error,
- });
- }
-
- // Transform the response to camelCase
- return transformMcpRetrieveResponse(retrieveResponse);
- }
-
- /**
- * Delete an MCP server
- * @param {string} serverId - Server UUID
- * @returns {Promise<McpDeleteResponse>} Deletion response
+ * // Example with error handling
+ * try {
+ * const result = await composio.experimental.mcp.delete("mcp_12345");
+ * console.log("Deletion successful:", result);
+ * } catch (error) {
+ * console.error("Failed to delete MCP server:", error.message);
+ * }
*
- * @example
- * ```typescript
- * const result = await composio.mcp.delete('server-uuid');
+ * // Delete and verify from list
+ * await composio.experimental.mcp.delete("mcp_12345");
+ * const servers = await composio.experimental.mcp.list({});
+ * const serverExists = servers.items.some(server => server.id === "mcp_12345");
+ * console.log("Server still exists:", serverExists); // Should be false
* ```
+ *
+ * @throws {ValidationError} When the server ID is invalid or server not found
+ * @throws {Error} When the server cannot be deleted due to active connections or other constraints
+ *
+ * @warning This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
*/
- async delete(serverId: string): Promise<McpDeleteResponse> {
- // Delete MCP server with error handling
- let deleteResponse;
- try {
- deleteResponse = await this.client.mcp.delete(serverId);
- } catch (error) {
- throw new ValidationError('Failed to delete MCP server', {
- cause: error,
- });
- }
-
- // Validate the delete response
- const deleteResponseResult = ComposioMcpDeleteResponseSchema.safeParse(deleteResponse);
- if (deleteResponseResult.error) {
- throw new ValidationError('Failed to parse MCP server delete response', {
- cause: deleteResponseResult.error,
- });
- }
-
- // Transform the response to camelCase
- return transformMcpDeleteResponse(deleteResponse);
+ async delete(serverId: string): Promise<{ id: string; deleted: boolean }> {
+ return await this.client.mcp.delete(serverId);
}
/**
- * Update an MCP server configuration
- * @param {string} id - Server UUID
- * @param {string} name - New unique name for the server
- * @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations
- * @param {MCPAuthOptions} [authOptions] - Updated authentication options
- * @returns {Promise<McpUpdateResponse>} Updated server details
+ * Update an existing MCP server configuration with new settings
+ * @param {string} serverId - The unique identifier of the MCP server to update
+ * @param {Object} config - Update configuration parameters
+ * @param {string} [config.name] - New name for the MCP server
+ * @param {Array} [config.toolkits] - Updated toolkit configurations
+ * @param {string} [config.toolkits[].toolkit] - Toolkit identifier (e.g., "github", "slack")
+ * @param {string} [config.toolkits[].authConfigId] - Auth configuration ID for the toolkit
+ * @param {string[]} [config.toolkits[].allowedTools] - Specific tools to enable for this toolkit
+ * @param {boolean} [config.manuallyManageConnections] - Whether to manually manage account connections
+ * @returns {Promise<MCPItem>} Updated MCP server configuration with all details
*
* @example
* ```typescript
- * const updatedServer = await composio.mcp.update(
- * "server-uuid",
- * "my-updated-server",
- * [
+ * // Update server name only
+ * const updatedServer = await composio.experimental.mcp.update("mcp_12345", {
+ * name: "My Updated MCP Server"
+ * });
+ *
+ * // Update toolkits and tools
+ * const serverWithNewTools = await composio.experimental.mcp.update("mcp_12345", {
+ * toolkits: [
* {
- * toolkit: "GMAIL",
- * authConfigId: "ac_sdhkjfhjksdk",
- * allowedTools: ["GMAIL_FETCH_EMAILS"],
+ * toolkit: "github",
+ * authConfigId: "auth_abc123",
+ * allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
* },
- * ],
- * {
- * isChatAuth: true,
- * }
- * );
- * ```
- */
- async update(
- serverId: string,
- name: string,
- toolkitConfigs: MCPToolkitConfig[],
- authOptions?: MCPAuthOptions
- ): Promise<McpUpdateResponse> {
- // Validate inputs using Zod schemas
- this.validateInputs(toolkitConfigs, authOptions);
-
- const toolkits = toolkitConfigs.map(config => config.toolkit);
-
- // Update MCP server with error handling
- let updateResponse;
- try {
- updateResponse = await this.client.mcp.update(serverId, {
- name,
- toolkits: toolkits,
- allowed_tools: toolkitConfigs.flatMap(config => config.allowedTools),
- managed_auth_via_composio: authOptions?.isChatAuth || false,
- });
- } catch (error) {
- throw new ValidationError('Failed to update MCP server', {
- cause: error,
- });
- }
-
- // Validate the update response
- const updateResponseResult = ComposioMcpUpdateResponseSchema.safeParse(updateResponse);
- if (updateResponseResult.error) {
- throw new ValidationError('Failed to parse MCP server update response', {
- cause: updateResponseResult.error,
- });
- }
-
- // Transform the response to camelCase
- return transformMcpUpdateResponse(updateResponse);
- }
-
- /**
- * Generate URL for an MCP server
- * @param {string} serverId - Server UUID
- * @param {GenerateURLParams} params - Parameters for URL generation
- * @returns {Promise<GenerateURLResponse>} Generated URL response
+ * {
+ * toolkit: "slack",
+ * authConfigId: "auth_xyz789",
+ * allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]
+ * }
+ * ]
+ * });
*
- * @example
- * ```typescript
- * const urlResponse = await composio.mcp.generateUrl('server-uuid', {
- * userIds: ['user123'],
- * connectedAccountIds: ['account456'],
- * isChatAuth: true
+ * // Update connection management setting
+ * const serverWithManualAuth = await composio.experimental.mcp.update("mcp_12345", {
+ * name: "Manual Auth Server",
+ * manuallyManageConnections: true
+ * });
+ *
+ * // Complete update example
+ * const fullyUpdatedServer = await composio.experimental.mcp.update("mcp_12345", {
+ * name: "Production MCP Server",
+ * toolkits: [
+ * {
+ * toolkit: "gmail",
+ * authConfigId: "auth_gmail_prod",
+ * }
+ * ],
+ * allowedTools: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"]
+ * manuallyManageConnections: false
* });
+ *
+ * console.log("Updated server:", fullyUpdatedServer.name);
+ * console.log("New tools:", fullyUpdatedServer.allowedTools);
* ```
+ *
+ * @throws {ValidationError} When the update parameters are invalid or malformed
+ * @throws {Error} When the server ID doesn't exist or update fails
+ *
+ * @note Only provided fields will be updated. Omitted fields will retain their current values.
+ * @note When updating toolkits, the entire toolkit configuration is replaced, not merged.
*/
- async generateUrl(serverId: string, params: GenerateURLParams): Promise<GenerateURLResponse> {
- // Validate parameters using Zod schema (snake_case)
- const paramsResult = GenerateURLParamsSchema.safeParse(params);
- if (paramsResult.error) {
- throw new ValidationError('Failed to parse generateUrl parameters', {
- cause: paramsResult.error,
- });
- }
-
- // No transformation needed - params are already in snake_case
- let urlResponse;
- try {
- urlResponse = await this.client.mcp.generate.url({
- mcp_server_id: serverId,
- user_ids: params.userIds,
- connected_account_ids: params.connectedAccountIds,
- managed_auth_by_composio: params.composioManagedAuth,
- });
- } catch (error) {
- throw new ValidationError('Failed to generate MCP URL', {
+ async update(serverId: string, config: MCPUpdateParams): Promise<MCPItem> {
+ const { data: params, error } = MCPUpdateParamsSchema.safeParse(config);
+ if (error) {
+ throw new ValidationError('Failed to validate update params', {
cause: error,
});
}
- // Validate the response
- const responseResult = ComposioGenerateURLResponseSchema.safeParse(urlResponse);
- if (responseResult.error) {
- throw new ValidationError('Failed to parse MCP URL generation response', {
- cause: responseResult.error,
- });
- }
-
- // Transform the response to camelCase
- return transformMcpGenerateUrlResponse(urlResponse);
- }
+ const toolkits: string[] = [];
+ const auth_config_ids: string[] = [];
+ const custom_tools: string[] | undefined = params.allowedTools ?? undefined;
- /**
- * Transform MCP URL response into the appropriate format.
- * If the provider has a custom transform method, use it.
- * Otherwise, use the default transformation.
- *
- * @param data - The MCP URL response data (in camelCase)
- * @param serverName - Name of the MCP server
-
- * @returns Transformed response in appropriate format
- * @deprecated
- */
- private wrapMcpServerResponse(
- data: McpUrlResponseCamelCase,
- serverName: string,
- connectedAccountIds?: string[],
- userIds?: string[],
- toolkits?: string[]
- ): typeof this.TMcpResponse {
- // Check if provider has a custom transform method
- if (this.provider && typeof this.provider.wrapMcpServerResponse === 'function') {
- // Convert to array of name and url based on connected accounts or user ids
- let snakeCaseData: McpUrlResponse;
-
- if (data.connectedAccountUrls?.length) {
- snakeCaseData = data.connectedAccountUrls.map((url, index) => ({
- name: serverName + '-' + connectedAccountIds?.[index],
- url: url,
- }));
- } else if (data.userIdsUrl?.length) {
- snakeCaseData = data.userIdsUrl.map((url, index) => ({
- name: serverName + '-' + userIds?.[index],
- url: url,
- }));
- } else {
- snakeCaseData = [
- {
- name: serverName,
- url: data.mcpUrl,
- },
- ];
+ // extract all the toolkits, authconfigs, and allowed tools to separate slugs
+ params.toolkits?.forEach(toolkit => {
+ if (typeof toolkit === 'string') {
+ toolkits.push(toolkit);
+ } else if (toolkit.toolkit) {
+ toolkits.push(toolkit.toolkit);
+ } else if (toolkit.authConfigId) {
+ auth_config_ids.push(toolkit.authConfigId);
}
-
- const transformed = this.provider.wrapMcpServerResponse(snakeCaseData);
- return transformed as typeof this.TMcpResponse;
- }
-
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- const self = this;
-
- // Default transformation
- if (connectedAccountIds?.length && data.connectedAccountUrls) {
- return data.connectedAccountUrls.map((url: string, index: number) => ({
- url: new URL(url),
- name: `${serverName}-${connectedAccountIds[index]}`,
- toolkit: toolkits?.[index],
- })) as typeof self.TMcpResponse;
- } else if (userIds?.length && data.userIdsUrl) {
- return data.userIdsUrl.map((url: string, index: number) => ({
- url: new URL(url),
- name: `${serverName}-${userIds[index]}`,
- toolkit: toolkits?.[index],
- })) as typeof self.TMcpResponse;
- }
- return {
- url: new URL(data.mcpUrl),
- name: serverName,
- } as typeof self.TMcpResponse;
+ });
+ const response = await this.client.mcp.update(serverId, {
+ ...{ name: params.name ?? undefined },
+ ...(params.toolkits
+ ? {
+ custom_tools: custom_tools,
+ toolkits: toolkits,
+ auth_config_ids: auth_config_ids,
+ }
+ : {}),
+ ...{ managed_auth_via_composio: params.manuallyManageConnections ?? undefined },
+ });
+ return transformMCPItemResponse(response);
}
/**
- * Get details of a specific MCP server by name
- * @param {string} name - Server name
- * @returns {Promise<McpRetrieveResponse>} Server details
- * @throws {ValidationError} If no server found with the given name
- * @throws {ValidationError} If multiple servers found with the same name
+ * Get server URLs for an existing MCP server.
+ * The response is wrapped according to the provider's specifications.
*
* @example
* ```typescript
- * const serverDetails = await composio.mcp.getByName('my-gmail-server');
+ * import { Composio } from "@composio/code";
+ *
+ * const composio = new Composio();
+ * const mcp = await composio.experimental.mcp.generate("default", "<mcp_config_id>");
* ```
+ *
+ * @param userId {string} external user id from your database for whom you want the server for
+ * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
+ * @param options {object} additional options
+ * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
*/
- async getByName(serverName: string): Promise<McpRetrieveResponse> {
- if (!serverName) {
- throw new ValidationError('Server name is required', {});
- }
-
- // List MCP servers filtered by name
- let listResponse;
- try {
- listResponse = await this.client.mcp.list({
- name: serverName,
- limit: 10,
- });
- } catch (error) {
- logger.error(error);
- throw new ValidationError('Failed to search MCP servers by name', {
- cause: error,
+ async generate(
+ userId: string,
+ mcpConfigId: string,
+ options?: MCPGetInstanceParams
+ ): Promise<MCPServerInstance> {
+ const server = await this.client.mcp.retrieve(mcpConfigId);
+ const params = MCPGetInstanceParamsSchema.safeParse(
+ options ?? { manuallyManageConnections: false }
+ );
+ if (params.error) {
+ throw new ValidationError('Invalid params passed for Get Instance Params', {
+ cause: params.error,
});
}
- // Validate the list response
- const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
- if (listResponseResult.error) {
- throw new ValidationError('Failed to parse MCP server list response', {
- cause: listResponseResult.error,
- });
- }
+ const urlResponse = await this.client.mcp.generate.url({
+ mcp_server_id: mcpConfigId,
+ user_ids: [userId],
+ managed_auth_by_composio: options?.manuallyManageConnections ? false : true,
+ });
- const servers = listResponse.items || [];
+ const userIdsURL = urlResponse.user_ids_url[0];
+ const serverInstance = MCPServerInstanceSchema.safeParse({
+ id: server.id,
+ name: server.name,
+ type: 'streamable_http' as const,
+ url: userIdsURL,
+ userId: userId,
+ allowedTools: server.allowed_tools,
+ authConfigs: server.auth_config_ids,
+ });
- if (servers.length === 0) {
- throw new ValidationError(`MCP server with name '${serverName}' not found`, {
- meta: { serverName: serverName },
+ if (serverInstance.error) {
+ throw new ValidationError('Failed to parse MCP server instance', {
+ cause: serverInstance.error,
});
}
- // Get the full server details using the server ID
- return this.get(servers[0].id);
+ return serverInstance.data;
}
}
diff --git a/ts/packages/core/src/models/ToolRouter.ts b/ts/packages/core/src/models/ToolRouter.ts
index 54190fac1..7b9ff1a94 100644
--- a/ts/packages/core/src/models/ToolRouter.ts
+++ b/ts/packages/core/src/models/ToolRouter.ts
@@ -36,6 +36,8 @@ import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types';
import { Tools } from './Tools';
import {
ExecuteToolModifiers,
+ SessionExecuteMetaModifiers,
+ SessionMetaToolOptions,
ProviderOptions,
TransformToolSchemaModifier,
} from '../types/modifiers.types';
@@ -48,6 +50,9 @@ import { ValidationError } from '../errors';
import {
transformToolRouterTagsParams,
transformToolRouterToolsParams,
+ transformToolRouterManageConnectionsParams,
+ transformToolRouterWorkbenchParams,
+ transformToolRouterToolkitsParams,
} from '../lib/toolRouterParams';
export class ToolRouter<
@@ -164,31 +169,23 @@ export class ToolRouter<
* Creates a function that wraps the tools based on the provider.
* The returned tools will be of the type the frameworks expects.
*
- * @param userId - The user id to get the tools for
- * @param tools - The tools to wrap
- * @returns A function that wraps the tools based on the provider.
+ * @param sessionId - The session id to get the tools for
+ * @returns A function that wraps the tools based on the provider with session-specific modifiers.
*/
private createToolsFn = (
- sessionId: string,
- toolSlugs: string[]
- ): ((modifiers?: ProviderOptions<TProvider>) => Promise<ReturnType<TProvider['wrapTools']>>) => {
- return async (modifiers?: ProviderOptions<TProvider>) => {
+ sessionId: string
+ ): ((modifiers?: SessionMetaToolOptions) => Promise<ReturnType<TProvider['wrapTools']>>) => {
+ return async (modifiers?: SessionMetaToolOptions) => {
const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
- const tools = await ToolsModel.getRawComposioTools(
- {
- tools: toolSlugs,
- },
+ const tools = await ToolsModel.getRawToolRouterMetaTools(
+ sessionId,
modifiers?.modifySchema
? {
modifySchema: modifiers?.modifySchema,
}
: undefined
);
- const wrappedTools = ToolsModel.wrapToolsForToolRouter(
- sessionId,
- tools,
- modifiers as ExecuteToolModifiers
- );
+ const wrappedTools = ToolsModel.wrapToolsForToolRouter(sessionId, tools, modifiers);
return wrappedTools as ReturnType<TProvider['wrapTools']>;
};
};
@@ -256,38 +253,17 @@ export class ToolRouter<
): Promise<ToolRouterSession<TToolCollection, TTool, TProvider>> {
const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});
- const manageConnectedAccounts =
- typeof routerConfig.manageConnections === 'boolean'
- ? routerConfig.manageConnections
- : (routerConfig.manageConnections?.enable ?? true);
-
- const toolkits = Array.isArray(routerConfig.toolkits)
- ? { enable: routerConfig.toolkits }
- : routerConfig.toolkits;
-
- const tags = transformToolRouterTagsParams(routerConfig.tags);
- const tools = transformToolRouterToolsParams(routerConfig.tools);
-
const payload: SessionCreateParams = {
user_id: userId,
- toolkits,
auth_configs: routerConfig.authConfigs,
connected_accounts: routerConfig.connectedAccounts,
- tools: tools,
- tags: tags,
- manage_connections: {
- enable: manageConnectedAccounts,
- callback_url:
- typeof routerConfig.manageConnections === 'object'
- ? routerConfig.manageConnections.callbackUrl
- : undefined,
- },
- workbench: routerConfig.workbench
- ? {
- enable_proxy_execution: routerConfig.workbench?.enableProxyExecution,
- auto_offload_threshold: routerConfig.workbench?.autoOffloadThreshold,
- }
- : undefined,
+ toolkits: transformToolRouterToolkitsParams(routerConfig.toolkits),
+ tools: transformToolRouterToolsParams(routerConfig.tools),
+ tags: transformToolRouterTagsParams(routerConfig.tags),
+ manage_connections: transformToolRouterManageConnectionsParams(
+ routerConfig.manageConnections
+ ),
+ workbench: transformToolRouterWorkbenchParams(routerConfig.workbench),
};
const session = await this.client.toolRouter.session.create(payload);
@@ -295,7 +271,7 @@ export class ToolRouter<
return {
sessionId: session.session_id,
mcp: this.createMCPServerConfig(session.mcp),
- tools: this.createToolsFn(session.session_id, session.tool_router_tools),
+ tools: this.createToolsFn(session.session_id),
authorize: this.createAuthorizeFn(session.session_id),
toolkits: this.createToolkitsFn(session.session_id),
};
@@ -323,7 +299,7 @@ export class ToolRouter<
return {
sessionId: session.session_id,
mcp: this.createMCPServerConfig(session.mcp),
- tools: this.createToolsFn(session.session_id, session.tool_router_tools),
+ tools: this.createToolsFn(session.session_id),
authorize: this.createAuthorizeFn(session.session_id),
toolkits: this.createToolkitsFn(session.session_id),
};
diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.ts
index bf6ab479b..d4d28505c 100644
--- a/ts/packages/core/src/models/Tools.ts
+++ b/ts/packages/core/src/models/Tools.ts
@@ -32,6 +32,7 @@ import {
afterExecuteModifier,
beforeExecuteModifier,
ExecuteToolModifiers,
+ SessionExecuteMetaModifiers,
ProviderOptions,
TransformToolSchemaModifier,
} from '../types/modifiers.types';
@@ -395,6 +396,48 @@ export class Tools<
return modifiedTools;
}
+ /**
+ * Fetches the meta tools for a tool router session.
+ * This method fetches the meta tools from the Composio API and transforms them to the expected format.
+ * It provides access to the underlying meta tool data without provider-specific wrapping.
+ *
+ * @param sessionId {string} The session id to get the meta tools for
+ * @param options {SchemaModifierOptions} Optional configuration for tool retrieval
+ * @param {TransformToolSchemaModifier} [options.modifySchema] - Function to transform the tool schema
+ * @returns {Promise<ToolList>} The list of meta tools
+ *
+ * @example
+ * ```typescript
+ * const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123');
+ * console.log(metaTools);
+ * ```
+ */
+ async getRawToolRouterMetaTools(
+ sessionId: string,
+ options?: SchemaModifierOptions
+ ): Promise<ToolList> {
+ const tools = await this.client.toolRouter.session.tools(sessionId);
+ let modifiedTools = tools.items.map(tool => this.transformToolCases(tool));
+ // apply local modifiers if they are provided
+ if (options?.modifySchema) {
+ const modifier = options.modifySchema;
+ if (typeof modifier === 'function') {
+ const modifiedPromises = modifiedTools.map(tool =>
+ modifier({
+ toolSlug: tool.slug,
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
+ schema: tool,
+ })
+ );
+ modifiedTools = await Promise.all(modifiedPromises);
+ } else {
+ throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
+ }
+ }
+
+ return modifiedTools;
+ }
+
/**
* Retrieves a specific tool by its slug from the Composio API.
*
@@ -635,13 +678,13 @@ export class Tools<
*
* @param {string} sessionId - The session id to execute the tool for
* @param {Tool[]} tools - The tools to wrap
- * @param {ExecuteToolModifiers} modifiers - The modifiers to apply to the tool
+ * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
* @returns {Tool[]} The wrapped tools
*/
wrapToolsForToolRouter(
sessionId: string,
tools: Tool[],
- modifiers?: ExecuteToolModifiers
+ modifiers?: SessionExecuteMetaModifiers
): Tool[] {
const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, modifiers);
return this.provider.wrapTools(tools, executeToolFn) as Tool[];
@@ -679,12 +722,12 @@ export class Tools<
* Creates a function that executes a tool for a tool router session
*
* @param {string} sessionId - The session id to execute the tool for
- * @param {ExecuteToolModifiers} modifiers - The modifiers to apply to the tool
+ * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
* @returns {ExecuteToolFn} The execute tool function
*/
private createExecuteToolFnForToolRouter(
sessionId: string,
- modifiers?: ExecuteToolModifiers
+ modifiers?: SessionExecuteMetaModifiers
): ExecuteToolFn {
const executeToolFn = async (
toolSlug: string,
@@ -876,13 +919,13 @@ export class Tools<
* @param {ToolExecuteMetaParams} body - The execution parameters
* @param {string} body.sessionId - The session id to execute the tool for
* @param {Record<string, unknown>} body.arguments - The input to pass to the tool
- * @param {ExecuteToolModifiers} modifiers - The modifiers to apply to the tool
+ * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
* @returns {Promise<ToolExecuteResponse>} The response from the tool execution
*/
async executeMetaTool(
toolSlug: string,
body: ToolExecuteMetaParams,
- modifiers?: ExecuteToolModifiers
+ modifiers?: SessionExecuteMetaModifiers
): Promise<ToolExecuteResponse> {
const executeMetaParams = ToolExecuteMetaParamsSchema.safeParse(body);
if (!executeMetaParams.success) {
@@ -891,46 +934,41 @@ export class Tools<
});
}
- const tool = await this.getRawComposioToolBySlug(toolSlug);
- if (!tool) {
- throw new ComposioToolNotFoundError(`Tool ${toolSlug} not found`, {
- meta: {
- slug: toolSlug,
- sessionId: body.sessionId,
- },
+ // Apply beforeExecute modifier if provided
+ let modifiedParams = body.arguments ?? {};
+ if (modifiers?.beforeExecute) {
+ modifiedParams = await modifiers.beforeExecute({
+ toolSlug,
+ toolkitSlug: 'composio',
+ sessionId: body.sessionId,
+ params: modifiedParams,
});
}
- const params = await this.applyBeforeExecuteModifiers(
- tool,
- {
- toolSlug: toolSlug,
- toolkitSlug: tool.toolkit?.slug ?? 'unknown',
- params: body.arguments ?? {},
- },
- modifiers?.beforeExecute
- );
-
+ // Execute the meta tool
const response = await this.client.toolRouter.session.executeMeta(body.sessionId, {
// assert this because backend might keep adding more tool slugs
slug: toolSlug as SessionExecuteMetaParams['slug'],
- arguments: params,
+ arguments: modifiedParams,
});
- const result = await this.applyAfterExecuteModifiers(
- tool,
- {
- toolSlug: toolSlug,
- toolkitSlug: tool.toolkit?.slug ?? 'unknown',
- result: {
- data: response.data,
- error: response.error,
- successful: !response.error,
- logId: response.log_id,
- },
- },
- modifiers?.afterExecute
- );
+ // Prepare the result
+ let result: ToolExecuteResponse = {
+ data: response.data,
+ error: response.error,
+ successful: !response.error,
+ logId: response.log_id,
+ };
+
+ // Apply afterExecute modifier if provided
+ if (modifiers?.afterExecute) {
+ result = await modifiers.afterExecute({
+ toolSlug,
+ toolkitSlug: 'composio',
+ sessionId: body.sessionId,
+ result,
+ });
+ }
return result;
}
diff --git a/ts/packages/core/src/types/modifiers.types.ts b/ts/packages/core/src/types/modifiers.types.ts
index 310369f2e..fb9564105 100644
--- a/ts/packages/core/src/types/modifiers.types.ts
+++ b/ts/packages/core/src/types/modifiers.types.ts
@@ -1,5 +1,5 @@
import { BaseAgenticProvider, BaseComposioProvider } from '../provider/BaseProvider';
-import { ToolExecuteParams, ToolExecuteResponse, Tool } from './tool.types';
+import { ToolExecuteParams, ToolExecuteResponse, Tool, ToolExecuteMetaParams } from './tool.types';
/**
* Modifier for altering the tool execute parameters before execution.
@@ -392,6 +392,131 @@ export type ExecuteToolModifiers = {
afterExecute?: afterExecuteModifier;
};
+/**
+ * Type alias for meta tool execution arguments.
+ * Represents the arguments passed to a meta tool during execution.
+ * This is derived from ToolExecuteMetaParams but guaranteed to be non-null.
+ */
+export type MetaToolArguments = NonNullable<ToolExecuteMetaParams['arguments']>;
+
+/**
+ * Modifier for altering the meta tool execute parameters before execution in a session context.
+ *
+ * This function is specifically designed for meta tools executed within a tool router session,
+ * allowing you to intercept and modify the parameters before execution. Meta tools are
+ * grouped under the 'composio' toolkit slug for organizational purposes.
+ *
+ * @param {string} toolSlug - The slug identifier of the meta tool being executed
+ * @param {string} toolkitSlug - The toolkit slug (always 'composio' for meta tools)
+ * @param {string} sessionId - The session ID for the tool router context
+ * @param {MetaToolArguments} params - The parameters being passed to the meta tool
+ * @returns {MetaToolArguments} The modified parameters
+ *
+ * @example
+ * ```typescript
+ * const beforeExecuteMeta = ({ toolSlug, toolkitSlug, sessionId, params }) => {
+ * console.log(`Executing ${toolkitSlug} meta tool ${toolSlug} in session ${sessionId}`);
+ *
+ * // Add or modify parameters
+ * return {
+ * ...params,
+ * timestamp: new Date().toISOString()
+ * };
+ * };
+ * ```
+ */
+export type beforeExecuteMetaModifier = (context: {
+ toolSlug: string;
+ toolkitSlug: string;
+ sessionId: string;
+ params: MetaToolArguments;
+}) => Promise<MetaToolArguments> | MetaToolArguments;
+
+/**
+ * Modifier for altering the meta tool execution response after execution completes in a session context.
+ *
+ * This function is specifically designed for meta tools executed within a tool router session,
+ * allowing you to intercept and modify the response after execution. This is useful for
+ * session-specific transformations, logging, or error handling.
+ *
+ * @param {string} toolSlug - The slug identifier of the meta tool that was executed
+ * @param {string} toolkitSlug - The toolkit slug (always 'composio' for meta tools)
+ * @param {string} sessionId - The session ID for the tool router context
+ * @param {ToolExecuteResponse} result - The original execution response
+ * @returns {ToolExecuteResponse} The modified execution response
+ *
+ * @example
+ * ```typescript
+ * const afterExecuteMeta = ({ toolSlug, toolkitSlug, sessionId, result }) => {
+ * // Log session-specific execution
+ * console.log(`${toolkitSlug} meta tool ${toolSlug} completed in session ${sessionId}`);
+ *
+ * if (!result.successful) {
+ * console.error(`Session ${sessionId} error:`, result.error);
+ * }
+ *
+ * return result;
+ * };
+ * ```
+ */
+export type afterExecuteMetaModifier = (context: {
+ toolSlug: string;
+ toolkitSlug: string;
+ sessionId: string;
+ result: ToolExecuteResponse;
+}) => Promise<ToolExecuteResponse> | ToolExecuteResponse;
+
+/**
+ * Modifiers specifically for meta tool execution within a session context.
+ *
+ * These modifiers are designed for tool router session-based meta tool execution,
+ * providing hooks to intercept and modify both the request and response of meta tools.
+ * Meta tools are grouped under the 'composio' toolkit for organizational consistency.
+ *
+ * @example
+ * ```typescript
+ * const metaModifiers: SessionExecuteMetaModifiers = {
+ * beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {
+ * // Add session tracking
+ * console.log(`Executing ${toolkitSlug}/${toolSlug}`);
+ * return {
+ * ...params,
+ * sessionMetadata: {
+ * startTime: Date.now(),
+ * sessionId
+ * }
+ * };
+ * },
+ *
+ * afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => {
+ * // Transform session results
+ * return {
+ * ...result,
+ * sessionInfo: {
+ * sessionId,
+ * toolSlug,
+ * toolkitSlug,
+ * completedAt: new Date().toISOString()
+ * }
+ * };
+ * }
+ * };
+ * ```
+ */
+export type SessionExecuteMetaModifiers = {
+ /**
+ * Function to intercept and modify meta tool execution parameters before the tool is executed.
+ * This allows customizing the request based on session-specific needs.
+ */
+ beforeExecute?: beforeExecuteMetaModifier;
+
+ /**
+ * Function to intercept and modify meta tool execution responses after the tool has executed.
+ * This allows transforming the response or implementing custom session-specific handling.
+ */
+ afterExecute?: afterExecuteMetaModifier;
+};
+
/**
* Options for agentic tool configuration.
*
@@ -430,6 +555,47 @@ export type ExecuteToolModifiers = {
*/
export type AgenticToolOptions = ToolOptions & ExecuteToolModifiers;
+/**
+ * Options for session-based meta tool configuration in tool router contexts.
+ *
+ * These options combine schema modification capabilities with session-specific execution
+ * behavior customization, providing control over both the definition and execution
+ * of meta tools within a tool router session. Meta tools are grouped under the 'composio' toolkit.
+ *
+ * @example
+ * ```typescript
+ * // Configure meta tools with schema and session-specific execution modifications
+ * const sessionTools = await toolRouter.getTools(sessionId, {
+ * modifySchema: (context) => {
+ * return {
+ * ...context.schema,
+ * description: `Session-specific ${context.toolSlug}`
+ * };
+ * },
+ *
+ * // Intercept before meta tool execution
+ * beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {
+ * // Add session tracking
+ * console.log(`Executing ${toolkitSlug}/${toolSlug}`);
+ * return {
+ * ...params,
+ * sessionMetadata: { sessionId, timestamp: Date.now() }
+ * };
+ * },
+ *
+ * // Transform after meta tool execution
+ * afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => {
+ * // Log session results
+ * if (!result.successful) {
+ * logSessionError(sessionId, toolkitSlug, toolSlug, result.error);
+ * }
+ * return result;
+ * }
+ * });
+ * ```
+ */
+export type SessionMetaToolOptions = ToolOptions & SessionExecuteMetaModifiers;
+
/**
* Provider-specific options determined by the type of provider being used.
*
diff --git a/ts/packages/core/src/types/toolRouter.types.ts b/ts/packages/core/src/types/toolRouter.types.ts
index 2defad89a..db2a4aaa4 100644
--- a/ts/packages/core/src/types/toolRouter.types.ts
+++ b/ts/packages/core/src/types/toolRouter.types.ts
@@ -1,6 +1,6 @@
import z from 'zod/v3';
import { BaseComposioProvider } from '../provider/BaseProvider';
-import { ExecuteToolModifiers, ProviderOptions } from './modifiers.types';
+import { SessionMetaToolOptions } from './modifiers.types';
import { ConnectionRequest } from './connectionRequest.types';
export const MCPServerTypeSchema = z.enum(['http', 'sse']);
@@ -20,6 +20,12 @@ export const ToolRouterConfigManageConnectionsSchema = z
.string()
.optional()
.describe('The callback uri to use in the tool router session'),
+ waitForConnections: z
+ .boolean()
+ .optional()
+ .describe(
+ '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'
+ ),
})
.strict();
@@ -264,7 +270,7 @@ export type ToolRouterToolsFn<
TToolCollection,
TTool,
TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
-> = (modifiers?: ProviderOptions<TProvider>) => Promise<ReturnType<TProvider['wrapTools']>>;
+> = (modifiers?: SessionMetaToolOptions) => Promise<ReturnType<TProvider['wrapTools']>>;
export type ToolRouterAuthorizeFn = (
toolkit: string,
diff --git a/ts/packages/core/test/models/mcp.test.ts b/ts/packages/core/test/models/mcp.test.ts
index d2edb9906..7b133e68a 100644
--- a/ts/packages/core/test/models/mcp.test.ts
+++ b/ts/packages/core/test/models/mcp.test.ts
@@ -3,18 +3,6 @@ import { MCP } from '../../src/models/MCP';
import ComposioClient from '@composio/client';
import { telemetry } from '../../src/telemetry/Telemetry';
import { ValidationError } from '../../src/errors/ValidationErrors';
-import { BaseAgenticProvider } from '../../src/provider/BaseProvider';
-import { Tool } from '../../src/types/tool.types';
-import { ExecuteToolFn } from '../../src/types/provider.types';
-import { McpUrlResponse } from '../../src/types/mcp.types';
-import {
- transformMcpCreateResponse,
- transformMcpListResponse,
- transformMcpRetrieveResponse,
- transformMcpDeleteResponse,
- transformMcpUpdateResponse,
- transformMcpGenerateUrlResponse,
-} from '../../src/utils/transformers/mcp';
// Mock dependencies
vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -23,83 +11,7 @@ vi.mock('../../src/telemetry/Telemetry', () => ({
},
}));
-// Define types for mock responses
-interface MockItem {
- id: string;
- name: string;
- created_at?: string;
- updated_at?: string;
- status?: string;
-}
-
-interface MockListResponse {
- items?: MockItem[];
-}
-
-vi.mock('../../src/utils/transformers/mcp', () => ({
- transformMcpCreateResponse: vi.fn(response => ({
- id: response.id,
- name: response.name,
- createdAt: response.created_at,
- updatedAt: response.updated_at,
- status: response.status,
- mcpUrl: response.mcp_url || 'https://mcp.example.com/server',
- commands: response.commands || {
- claude: 'claude-command',
- cursor: 'cursor-command',
- windsurf: 'windsurf-command',
- },
- toolkits: response.toolkits || [],
- tools: response.tools || [],
- managedAuthViaComposio: response.managed_auth_via_composio || false,
- })),
- transformMcpListResponse: vi.fn((response: MockListResponse) => ({
- items: response.items?.map(item => ({
- id: item.id,
- name: item.name,
- createdAt: item.created_at,
- updatedAt: item.updated_at,
- status: item.status,
- })),
- })),
- transformMcpRetrieveResponse: vi.fn(response => ({
- id: response.id,
- name: response.name,
- createdAt: response.created_at,
- updatedAt: response.updated_at,
- status: response.status,
- toolkits: response.toolkits,
- tools: response.tools,
- managedAuthViaComposio: response.managed_auth_via_composio,
- mcpUrl: response.mcpUrl || 'https://mcp.example.com/server',
- commands: response.commands || {
- claude: 'claude-command',
- cursor: 'cursor-command',
- windsurf: 'windsurf-command',
- },
- })),
- transformMcpDeleteResponse: vi.fn(response => ({
- id: response.id,
- deleted: response.deleted,
- message: response.message,
- })),
- transformMcpUpdateResponse: vi.fn(response => ({
- id: response.id,
- name: response.name,
- createdAt: response.created_at,
- updatedAt: response.updated_at,
- status: response.status,
- toolkits: response.toolkits,
- tools: response.tools,
- })),
- transformMcpGenerateUrlResponse: vi.fn(response => ({
- connectedAccountUrls: response.connected_account_urls,
- userIdsUrl: response.user_ids_url,
- mcpUrl: response.mcp_url,
- })),
-}));
-
-// Create mock client with MCP-related methods
+// Create mock client with MCP methods
const createMockClient = () => ({
baseURL: 'https://api.composio.dev',
apiKey: 'test-api-key',
@@ -107,317 +19,137 @@ const createMockClient = () => ({
custom: {
create: vi.fn(),
},
- generate: {
- url: vi.fn(),
- },
list: vi.fn(),
retrieve: vi.fn(),
delete: vi.fn(),
update: vi.fn(),
- },
- authConfigs: {
- retrieve: vi.fn(),
- },
- connectedAccounts: {
- list: vi.fn(),
- },
- toolkits: {
- retrieve: vi.fn(),
- },
-});
-
-// Mock response data
-const mockCreateResponse = {
- id: 'mcp_123',
- name: 'test-mcp-server',
- created_at: '2024-01-01T00:00:00Z',
- updated_at: '2024-01-01T00:00:00Z',
- status: 'active',
- mcp_url: 'https://mcp.example.com/server',
- commands: {
- claude: 'claude-command',
- cursor: 'cursor-command',
- windsurf: 'windsurf-command',
- },
- toolkits: ['gmail'],
- tools: ['GMAIL_FETCH_EMAILS'],
- managed_auth_via_composio: true,
-};
-
-const mockListResponse = {
- items: [
- {
- id: 'mcp_123',
- name: 'test-mcp-server',
- created_at: '2024-01-01T00:00:00Z',
- updated_at: '2024-01-01T00:00:00Z',
- status: 'active',
- },
- {
- id: 'mcp_456',
- name: 'another-mcp-server',
- created_at: '2024-01-02T00:00:00Z',
- updated_at: '2024-01-02T00:00:00Z',
- status: 'active',
+ generate: {
+ url: vi.fn(),
},
- ],
-};
-
-const mockRetrieveResponse = {
- id: 'mcp_123',
- name: 'test-mcp-server',
- created_at: '2024-01-01T00:00:00Z',
- updated_at: '2024-01-01T00:00:00Z',
- status: 'active',
- toolkits: ['gmail', 'github'],
- tools: ['GMAIL_FETCH_EMAILS', 'GITHUB_GET_REPO'],
- managed_auth_via_composio: true,
- mcp_url: 'https://mcp.example.com/server',
- commands: {
- claude: 'claude-command',
- cursor: 'cursor-command',
- windsurf: 'windsurf-command',
},
-};
-
-const mockGenerateUrlResponse = {
- connected_account_urls: ['https://mcp.example.com/account1', 'https://mcp.example.com/account2'],
- user_ids_url: ['https://mcp.example.com/user1', 'https://mcp.example.com/user2'],
- mcp_url: 'https://mcp.example.com/server',
-};
-
-// Define types for mock provider
-type MockTool = Tool & { mockWrapped: boolean };
-type MockToolCollection = MockTool[];
-type MockMcpResponse = {
- customFormat: boolean;
- serverName: string;
- urls: string[];
-};
-
-// Mock provider
-class MockProvider extends BaseAgenticProvider<MockToolCollection, MockTool, MockMcpResponse> {
- readonly name = 'mock-provider';
-
- wrapTool(tool: Tool, executeTool: ExecuteToolFn): MockTool {
- return { ...tool, mockWrapped: true };
- }
-
- wrapTools(tools: Tool[], executeTool: ExecuteToolFn): MockToolCollection {
- return tools.map(tool => this.wrapTool(tool, executeTool));
- }
-
- wrapMcpServerResponse(data: McpUrlResponse): MockMcpResponse {
- // McpUrlResponse is an array of { name, url } objects
- return {
- customFormat: true,
- serverName: data[0]?.name || 'test-mcp-server',
- urls: data.map(item => item.url),
- };
- }
-}
+});
describe('MCP', () => {
let mcp: MCP;
let mockClient: ReturnType<typeof createMockClient>;
- let mockProvider: MockProvider;
beforeEach(() => {
- vi.clearAllMocks();
mockClient = createMockClient();
mcp = new MCP(mockClient as unknown as ComposioClient);
-
- // Default mock for connected accounts
- mockClient.connectedAccounts.list.mockResolvedValue({
- items: [
- { id: 'account_123', toolkit: { slug: 'gmail' } },
- { id: 'account_456', toolkit: { slug: 'gmail' } },
- ],
- });
});
describe('constructor', () => {
it('should create an instance successfully', () => {
expect(mcp).toBeInstanceOf(MCP);
- expect(telemetry.instrument).toHaveBeenCalledWith(mcp, 'MCP');
+ expect(mcp.client).toBe(mockClient);
});
- it('should store the client reference', () => {
- expect(mcp['client']).toBe(mockClient);
- });
-
- it('should accept an optional provider', () => {
- mockProvider = new MockProvider();
- const mcpWithProvider = new MCP(mockClient as unknown as ComposioClient, mockProvider);
- expect(mcpWithProvider['provider']).toBe(mockProvider);
+ it('should instrument the class with telemetry', () => {
+ expect(telemetry.instrument).toHaveBeenCalledWith(mcp, 'MCP');
});
});
describe('create', () => {
- const serverConfig = [
- {
- authConfigId: 'ac_gmail123',
- allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
- },
- ];
-
- beforeEach(() => {
- // Mock authConfigs.retrieve to return toolkit information
- mockClient.authConfigs.retrieve.mockResolvedValue({
- id: 'ac_gmail123',
- toolkit: { slug: 'gmail' },
- auth_scheme: 'OAUTH2',
- });
- });
-
it('should create an MCP server successfully', async () => {
- mockClient.mcp.custom.create.mockResolvedValue(mockCreateResponse);
- mockClient.mcp.list.mockResolvedValue(mockListResponse);
- const result = await mcp.create('test-server', serverConfig, {
- isChatAuth: true,
- });
-
- expect(mockClient.mcp.custom.create).toHaveBeenCalledWith({
- name: 'test-server',
- toolkits: ['gmail'],
- custom_tools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
- managed_auth_via_composio: true,
- auth_config_ids: ['ac_gmail123'],
- });
-
- expect(result).toMatchObject({
+ const mockResponse = {
id: 'mcp_123',
- name: 'test-mcp-server',
- toolkits: ['gmail'],
- });
-
- expect(result.getServer).toBeDefined();
- expect(typeof result.getServer).toBe('function');
- });
-
- it('should validate server configuration', async () => {
- const invalidConfigs: any[] = []; // Empty array
-
- await expect(
- mcp.create('test-server', invalidConfigs, {
- isChatAuth: true,
- })
- ).rejects.toThrow('At least one auth config is required');
- });
-
- it('should validate server name', async () => {
- await expect(
- mcp.create('', serverConfig, {
- isChatAuth: true,
- })
- ).rejects.toThrow('Server name is required');
- });
- });
-
- describe('getServer', () => {
- beforeEach(() => {
- // Mock the get method that getServer calls internally
- vi.spyOn(mcp, 'get').mockResolvedValue({
- id: mockRetrieveResponse.id,
- name: mockRetrieveResponse.name,
- createdAt: mockRetrieveResponse.created_at,
- updatedAt: mockRetrieveResponse.updated_at,
- status: mockRetrieveResponse.status,
- toolkits: mockRetrieveResponse.toolkits,
- tools: mockRetrieveResponse.tools,
- managedAuthViaComposio: mockRetrieveResponse.managed_auth_via_composio,
- mcpUrl: 'https://mcp.example.com/server',
+ name: 'test-server',
+ allowed_tools: ['GMAIL_SEND_EMAIL'],
+ auth_config_ids: ['auth_456'],
commands: {
claude: 'claude-command',
cursor: 'cursor-command',
windsurf: 'windsurf-command',
},
- });
-
- // Mock connectedAccounts.list
- mockClient.connectedAccounts.list.mockResolvedValue({
- items: [
- { id: 'account_123', toolkit: { slug: 'gmail' } },
- { id: 'account_456', toolkit: { slug: 'github' } },
- ],
- });
- });
-
- it('should get server URLs with user ID', async () => {
- mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
+ mcp_url: 'https://mcp.example.com/server',
+ };
- const result = await mcp.getServer('mcp_123', 'user_123');
+ mockClient.mcp.custom.create.mockResolvedValueOnce(mockResponse);
- expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
- user_ids: ['user_123'],
- connected_account_ids: [],
- mcp_server_id: 'mcp_123',
- managed_auth_by_composio: true,
+ const result = await mcp.create('test-server', {
+ toolkits: ['gmail'],
+ manuallyManageConnections: false,
});
- expect(result).toBeDefined();
- });
-
- it('should get server URLs with options', async () => {
- mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
-
- const result = await mcp.getServer('mcp_123', 'user_123');
-
- expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
- user_ids: ['user_123'],
- connected_account_ids: [],
- mcp_server_id: 'mcp_123',
- managed_auth_by_composio: true,
+ expect(result).toHaveProperty('id', 'mcp_123');
+ expect(result).toHaveProperty('name', 'test-server');
+ expect(result).toHaveProperty('generate');
+ expect(typeof result.generate).toBe('function');
+ expect(mockClient.mcp.custom.create).toHaveBeenCalledWith({
+ name: 'test-server',
+ toolkits: ['gmail'],
+ auth_config_ids: [],
+ custom_tools: [],
+ managed_auth_via_composio: true,
});
});
- it('should validate that userId is provided', async () => {
- await expect(mcp.getServer('mcp_123', '')).rejects.toThrow('User ID is required');
- });
-
- it('should use custom provider transformation', async () => {
- mockProvider = new MockProvider();
- const mcpWithProvider = new MCP(mockClient as unknown as ComposioClient, mockProvider);
- vi.spyOn(mcpWithProvider, 'get').mockResolvedValue({
- id: mockRetrieveResponse.id,
- name: mockRetrieveResponse.name,
- createdAt: mockRetrieveResponse.created_at,
- updatedAt: mockRetrieveResponse.updated_at,
- status: mockRetrieveResponse.status,
- toolkits: mockRetrieveResponse.toolkits,
- tools: mockRetrieveResponse.tools,
- managedAuthViaComposio: mockRetrieveResponse.managed_auth_via_composio,
- mcpUrl: 'https://mcp.example.com/server',
+ it('should handle toolkits with auth config IDs', async () => {
+ const mockResponse = {
+ id: 'mcp_123',
+ name: 'test-server',
+ allowed_tools: [],
+ auth_config_ids: ['auth_456'],
commands: {
- claude: 'claude-command',
- cursor: 'cursor-command',
- windsurf: 'windsurf-command',
+ claude: 'cmd',
+ cursor: 'cmd',
+ windsurf: 'cmd',
},
- });
-
- // Mock a response with only one URL for the single userId
- const singleUserResponse = {
- user_ids_url: ['https://mcp.example.com/user_123'],
- mcp_url: 'https://mcp.example.com/server',
+ mcp_url: 'https://mcp.example.com',
};
- mockClient.mcp.generate.url.mockResolvedValue(singleUserResponse);
- const result = await mcpWithProvider.getServer('mcp_123', 'user_123');
+ mockClient.mcp.custom.create.mockResolvedValueOnce(mockResponse);
- expect(result).toMatchObject({
- customFormat: true,
- serverName: 'test-mcp-server-user_123',
- urls: ['https://mcp.example.com/user_123'],
+ await mcp.create('test-server', {
+ toolkits: [{ toolkit: 'gmail', authConfigId: 'auth_456' }],
+ });
+
+ expect(mockClient.mcp.custom.create).toHaveBeenCalledWith({
+ name: 'test-server',
+ toolkits: ['gmail'],
+ auth_config_ids: [],
+ custom_tools: [],
+ managed_auth_via_composio: true,
});
});
+
+ it('should validate configuration', async () => {
+ await expect(mcp.create('test', { toolkits: null as any })).rejects.toThrow(ValidationError);
+ });
});
describe('list', () => {
it('should list MCP servers with default options', async () => {
- mockClient.mcp.list.mockResolvedValue(mockListResponse);
+ const mockResponse = {
+ items: [
+ {
+ id: 'mcp_1',
+ name: 'server-1',
+ allowed_tools: ['TOOL_1'],
+ auth_config_ids: ['auth_1'],
+ commands: {
+ claude: 'cmd',
+ cursor: 'cmd',
+ windsurf: 'cmd',
+ },
+ mcp_url: 'https://mcp.example.com',
+ toolkit_icons: {},
+ server_instance_count: 0,
+ toolkits: ['gmail'],
+ },
+ ],
+ current_page: 1,
+ total_pages: 1,
+ };
+
+ mockClient.mcp.list.mockResolvedValueOnce(mockResponse);
const result = await mcp.list({});
+ expect(result).toHaveProperty('items');
+ expect(result).toHaveProperty('currentPage', 1);
+ expect(result).toHaveProperty('totalPages', 1);
+ expect(result.items).toHaveLength(1);
expect(mockClient.mcp.list).toHaveBeenCalledWith({
page_no: 1,
limit: 10,
@@ -425,283 +157,243 @@ describe('MCP', () => {
auth_config_ids: undefined,
name: undefined,
});
-
- expect(result).toMatchObject({
- items: expect.arrayContaining([
- expect.objectContaining({
- id: 'mcp_123',
- name: 'test-mcp-server',
- }),
- ]),
- });
});
it('should list MCP servers with filters', async () => {
- mockClient.mcp.list.mockResolvedValue(mockListResponse);
+ const mockResponse = {
+ items: [],
+ current_page: 1,
+ total_pages: 1,
+ };
- const result = await mcp.list({
+ mockClient.mcp.list.mockResolvedValueOnce(mockResponse);
+
+ await mcp.list({
page: 2,
limit: 20,
- toolkits: ['gmail', 'github'],
- authConfigs: ['auth_123', 'auth_456'],
- name: 'production',
+ toolkits: ['gmail', 'slack'],
+ authConfigs: ['auth_1'],
+ name: 'test',
});
expect(mockClient.mcp.list).toHaveBeenCalledWith({
page_no: 2,
limit: 20,
- toolkits: 'gmail,github',
- auth_config_ids: 'auth_123,auth_456',
- name: 'production',
+ toolkits: 'gmail,slack',
+ auth_config_ids: 'auth_1',
+ name: 'test',
});
});
- it('should handle list errors', async () => {
- mockClient.mcp.list.mockRejectedValue(new Error('List failed'));
-
- await expect(mcp.list({})).rejects.toThrow('Failed to list MCP servers');
+ it('should handle validation errors', async () => {
+ await expect(mcp.list({ page: 'invalid' as any })).rejects.toThrow(ValidationError);
});
});
describe('get', () => {
it('should retrieve an MCP server by ID', async () => {
- mockClient.mcp.retrieve.mockResolvedValue(mockRetrieveResponse);
+ const mockResponse = {
+ id: 'mcp_123',
+ name: 'test-server',
+ allowed_tools: ['GMAIL_SEND_EMAIL'],
+ auth_config_ids: ['auth_456'],
+ commands: {
+ claude: 'cmd',
+ cursor: 'cmd',
+ windsurf: 'cmd',
+ },
+ mcp_url: 'https://mcp.example.com',
+ toolkit_icons: {},
+ server_instance_count: 5,
+ toolkits: ['gmail'],
+ };
+
+ mockClient.mcp.retrieve.mockResolvedValueOnce(mockResponse);
const result = await mcp.get('mcp_123');
+ expect(result).toHaveProperty('id', 'mcp_123');
+ expect(result).toHaveProperty('name', 'test-server');
+ expect(result).toHaveProperty('serverInstanceCount', 5);
expect(mockClient.mcp.retrieve).toHaveBeenCalledWith('mcp_123');
- expect(result).toMatchObject({
- id: 'mcp_123',
- name: 'test-mcp-server',
- toolkits: ['gmail', 'github'],
- });
- });
-
- it('should handle retrieval errors', async () => {
- mockClient.mcp.retrieve.mockRejectedValue(new Error('Not found'));
-
- await expect(mcp.get('mcp_123')).rejects.toThrow('Failed to retrieve MCP server');
});
});
describe('delete', () => {
it('should delete an MCP server', async () => {
- const mockDeleteResponse = {
+ const mockResponse = {
id: 'mcp_123',
deleted: true,
- message: 'Server deleted successfully',
};
- mockClient.mcp.delete.mockResolvedValue(mockDeleteResponse);
+ mockClient.mcp.delete.mockResolvedValueOnce(mockResponse);
const result = await mcp.delete('mcp_123');
+ expect(result).toEqual(mockResponse);
expect(mockClient.mcp.delete).toHaveBeenCalledWith('mcp_123');
- expect(result).toMatchObject({
- id: 'mcp_123',
- deleted: true,
- });
- });
-
- it('should handle deletion errors', async () => {
- mockClient.mcp.delete.mockRejectedValue(new Error('Cannot delete'));
-
- await expect(mcp.delete('mcp_123')).rejects.toThrow('Failed to delete MCP server');
});
});
describe('update', () => {
- const updatedConfigs = [
- {
- toolkit: 'gmail',
- authConfigId: 'ac_gmail789',
- allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL', 'GMAIL_CREATE_DRAFT'],
- },
- ];
-
it('should update an MCP server', async () => {
- const mockUpdateResponse = {
+ const mockResponse = {
id: 'mcp_123',
name: 'updated-server',
- created_at: '2024-01-01T00:00:00Z',
- updated_at: '2024-01-02T00:00:00Z',
- status: 'active',
- toolkits: ['gmail'],
- tools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL', 'GMAIL_CREATE_DRAFT'],
+ allowed_tools: ['NEW_TOOL'],
+ auth_config_ids: ['auth_789'],
+ commands: {
+ claude: 'cmd',
+ cursor: 'cmd',
+ windsurf: 'cmd',
+ },
+ mcp_url: 'https://mcp.example.com',
+ toolkit_icons: {},
+ server_instance_count: 3,
+ toolkits: ['slack'],
};
- mockClient.mcp.update.mockResolvedValue(mockUpdateResponse);
+ mockClient.mcp.update.mockResolvedValueOnce(mockResponse);
- const result = await mcp.update('mcp_123', 'updated-server', updatedConfigs, {
- isChatAuth: true,
- });
-
- expect(mockClient.mcp.update).toHaveBeenCalledWith('mcp_123', {
+ const result = await mcp.update('mcp_123', {
name: 'updated-server',
- toolkits: ['gmail'],
- allowed_tools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL', 'GMAIL_CREATE_DRAFT'],
- managed_auth_via_composio: true,
+ toolkits: ['slack'],
});
- expect(result).toMatchObject({
- id: 'mcp_123',
+ expect(result).toHaveProperty('id', 'mcp_123');
+ expect(result).toHaveProperty('name', 'updated-server');
+ expect(mockClient.mcp.update).toHaveBeenCalledWith('mcp_123', {
name: 'updated-server',
+ custom_tools: undefined,
+ toolkits: ['slack'],
+ auth_config_ids: [],
});
});
it('should validate update parameters', async () => {
- const invalidConfigs = [
- {
- toolkit: '',
- authConfigId: 'ac_123',
- allowedTools: [],
- },
- ];
-
- await expect(mcp.update('mcp_123', 'updated', invalidConfigs)).rejects.toThrow(
+ await expect(mcp.update('mcp_123', { toolkits: 'invalid' as any })).rejects.toThrow(
ValidationError
);
});
-
- it('should handle update errors', async () => {
- mockClient.mcp.update.mockRejectedValue(new Error('Update failed'));
-
- await expect(mcp.update('mcp_123', 'updated', updatedConfigs)).rejects.toThrow(
- 'Failed to update MCP server'
- );
- });
});
- describe('generateUrl', () => {
- it('should generate URLs with valid parameters', async () => {
- mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
+ describe('generate', () => {
+ it('should generate server instance with valid parameters', async () => {
+ const mockRetrieveResponse = {
+ id: 'mcp_123',
+ name: 'test-server',
+ allowed_tools: ['GMAIL_SEND_EMAIL'],
+ auth_config_ids: ['auth_456'],
+ };
- const params = {
- userIds: ['user123'],
- connectedAccountIds: ['account456'],
- mcpServerId: 'mcp_123',
- composioManagedAuth: true,
+ const mockUrlResponse = {
+ user_ids_url: ['https://mcp.example.com/instance/user123'],
+ connected_account_urls: [],
+ mcp_url: 'https://mcp.example.com',
};
- const result = await mcp.generateUrl('mcp_123', params);
+ mockClient.mcp.retrieve.mockResolvedValueOnce(mockRetrieveResponse);
+ mockClient.mcp.generate.url.mockResolvedValueOnce(mockUrlResponse);
+
+ const result = await mcp.generate('user123', 'mcp_123');
+ expect(result).toHaveProperty('id', 'mcp_123');
+ expect(result).toHaveProperty('userId', 'user123');
+ expect(result).toHaveProperty('type', 'streamable_http');
+ expect(result).toHaveProperty('url', 'https://mcp.example.com/instance/user123');
expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
- user_ids: ['user123'],
- connected_account_ids: ['account456'],
mcp_server_id: 'mcp_123',
+ user_ids: ['user123'],
managed_auth_by_composio: true,
});
+ });
- expect(result).toMatchObject({
- connectedAccountUrls: [
- 'https://mcp.example.com/account1',
- 'https://mcp.example.com/account2',
- ],
- userIdsUrl: ['https://mcp.example.com/user1', 'https://mcp.example.com/user2'],
- mcpUrl: 'https://mcp.example.com/server',
+ it('should handle manual connection management', async () => {
+ const mockRetrieveResponse = {
+ id: 'mcp_123',
+ name: 'test-server',
+ allowed_tools: [],
+ auth_config_ids: [],
+ };
+
+ const mockUrlResponse = {
+ user_ids_url: ['https://mcp.example.com/instance/user123'],
+ connected_account_urls: [],
+ mcp_url: 'https://mcp.example.com',
+ };
+
+ mockClient.mcp.retrieve.mockResolvedValueOnce(mockRetrieveResponse);
+ mockClient.mcp.generate.url.mockResolvedValueOnce(mockUrlResponse);
+
+ await mcp.generate('user123', 'mcp_123', {
+ manuallyManageConnections: true,
+ });
+
+ expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
+ mcp_server_id: 'mcp_123',
+ user_ids: ['user123'],
+ managed_auth_by_composio: false,
});
});
it('should validate parameters', async () => {
- const invalidParams = {
- userIds: 'not-an-array' as unknown as string[], // Should be an array
- mcpServerId: 'mcp_123',
+ const mockRetrieveResponse = {
+ id: 'mcp_123',
+ name: 'test-server',
+ allowed_tools: [],
+ auth_config_ids: [],
};
- await expect(mcp.generateUrl('mcp_123', invalidParams)).rejects.toThrow(ValidationError);
- });
-
- it('should handle URL generation errors', async () => {
- mockClient.mcp.generate.url.mockRejectedValue(new Error('Generation failed'));
+ mockClient.mcp.retrieve.mockResolvedValueOnce(mockRetrieveResponse);
await expect(
- mcp.generateUrl('mcp_123', {
- userIds: ['user123'],
- mcpServerId: 'mcp_123',
- })
- ).rejects.toThrow('Failed to generate MCP URL');
+ mcp.generate('user123', 'mcp_123', { manuallyManageConnections: 'invalid' as any })
+ ).rejects.toThrow(ValidationError);
});
});
- describe('convenience getServer method', () => {
- it('should work on create response', async () => {
- mockClient.mcp.custom.create.mockResolvedValue(mockCreateResponse);
- mockClient.mcp.retrieve.mockResolvedValue(mockRetrieveResponse);
- mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
- mockClient.mcp.list.mockResolvedValue(mockListResponse);
- mockClient.authConfigs.retrieve.mockResolvedValue({
- id: 'ac_gmail123',
- toolkit: { slug: 'gmail' },
- });
-
- const serverConfig = [
- {
- authConfigId: 'ac_gmail123',
- allowedTools: ['GMAIL_FETCH_EMAILS'],
+ describe('create response with generate method', () => {
+ it('should create server and use the generate method', async () => {
+ const mockCreateResponse = {
+ id: 'mcp_123',
+ name: 'test-server',
+ allowed_tools: ['GMAIL_SEND_EMAIL'],
+ auth_config_ids: ['auth_456'],
+ commands: {
+ claude: 'cmd',
+ cursor: 'cmd',
+ windsurf: 'cmd',
},
- ];
+ mcp_url: 'https://mcp.example.com',
+ };
- const server = await mcp.create('test-server', serverConfig, {
- isChatAuth: true,
- });
+ const mockRetrieveResponse = {
+ id: 'mcp_123',
+ name: 'test-server',
+ allowed_tools: ['GMAIL_SEND_EMAIL'],
+ auth_config_ids: ['auth_456'],
+ };
- // Mock the internal get call
- vi.spyOn(mcp, 'get').mockResolvedValue({
- id: mockRetrieveResponse.id,
- name: mockRetrieveResponse.name,
- createdAt: mockRetrieveResponse.created_at,
- updatedAt: mockRetrieveResponse.updated_at,
- status: mockRetrieveResponse.status,
- toolkits: mockRetrieveResponse.toolkits,
- tools: mockRetrieveResponse.tools,
- managedAuthViaComposio: mockRetrieveResponse.managed_auth_via_composio,
- mcpUrl: 'https://mcp.example.com/server',
- commands: {
- claude: 'claude-command',
- cursor: 'cursor-command',
- windsurf: 'windsurf-command',
- },
- });
+ const mockUrlResponse = {
+ user_ids_url: ['https://mcp.example.com/instance/user123'],
+ connected_account_urls: [],
+ mcp_url: 'https://mcp.example.com',
+ };
- // Mock connectedAccounts.list for the convenience method
- mockClient.connectedAccounts.list.mockResolvedValue({
- items: [
- { id: 'account_123', toolkit: { slug: 'gmail' } },
- { id: 'account_456', toolkit: { slug: 'gmail' } },
- ],
- });
+ mockClient.mcp.custom.create.mockResolvedValueOnce(mockCreateResponse);
+ mockClient.mcp.retrieve.mockResolvedValueOnce(mockRetrieveResponse);
+ mockClient.mcp.generate.url.mockResolvedValueOnce(mockUrlResponse);
- const urls = await server.getServer({
- userId: 'user123',
+ const server = await mcp.create('test-server', {
+ toolkits: ['gmail'],
});
- expect(urls).toBeDefined();
- expect(mockClient.mcp.generate.url).toHaveBeenCalled();
- });
- });
+ expect(server.generate).toBeDefined();
- describe('validation error messages', () => {
- it('should provide meaningful error messages for empty auth config', async () => {
- await expect(
- mcp.create('test-server', [], {
- isChatAuth: true,
- })
- ).rejects.toThrow('At least one auth config is required');
- });
+ const instance = await server.generate('user123');
- it('should provide meaningful error messages for empty server name', async () => {
- const serverConfig = [
- {
- authConfigId: 'ac_123',
- allowedTools: ['GMAIL_FETCH_EMAILS'],
- },
- ];
-
- await expect(
- mcp.create('', serverConfig, {
- isChatAuth: true,
- })
- ).rejects.toThrow('Server name is required');
+ expect(instance).toHaveProperty('userId', 'user123');
+ expect(instance).toHaveProperty('url', 'https://mcp.example.com/instance/user123');
});
});
});
diff --git a/ts/packages/core/test/models/toolRouter.test.ts b/ts/packages/core/test/models/toolRouter.test.ts
index 0373d0cfe..91b3f83ed 100644
--- a/ts/packages/core/test/models/toolRouter.test.ts
+++ b/ts/packages/core/test/models/toolRouter.test.ts
@@ -18,6 +18,7 @@ vi.mock('../../src/models/Tools', () => {
return {
Tools: vi.fn().mockImplementation(() => ({
getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
+ getRawToolRouterMetaTools: vi.fn().mockResolvedValue([{ slug: 'COMPOSIO_SEARCH_TOOLS' }]),
wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
})),
};
@@ -1639,6 +1640,7 @@ describe('ToolRouter', () => {
vi.clearAllMocks();
(Tools as any).mockImplementation(() => ({
getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
+ getRawToolRouterMetaTools: vi.fn().mockResolvedValue([{ slug: 'COMPOSIO_SEARCH_TOOLS' }]),
wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
}));
});
@@ -1655,15 +1657,10 @@ describe('ToolRouter', () => {
});
const toolsInstance = (Tools as any).mock.results[0].value;
- expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
- {
- tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
- },
- undefined
- );
+ expect(toolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(sessionId, undefined);
expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
sessionId,
- [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
undefined
);
@@ -1685,15 +1682,12 @@ describe('ToolRouter', () => {
const tools = await session.tools(modifiers);
const toolsInstance = (Tools as any).mock.results[0].value;
- expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
- {
- tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
- },
- { modifySchema: modifiers.modifySchema }
- );
+ expect(toolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(sessionId, {
+ modifySchema: modifiers.modifySchema,
+ });
expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
sessionId,
- [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
modifiers
);
@@ -1705,6 +1699,7 @@ describe('ToolRouter', () => {
(Tools as any).mockImplementation(() => ({
getRawComposioTools: vi.fn().mockRejectedValue(new Error('Failed to fetch tools')),
+ getRawToolRouterMetaTools: vi.fn().mockRejectedValue(new Error('Failed to fetch tools')),
wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
}));
@@ -1729,28 +1724,22 @@ describe('ToolRouter', () => {
expect(Tools).toHaveBeenCalledTimes(2);
const firstToolsInstance = (Tools as any).mock.results[0].value;
- expect(firstToolsInstance.getRawComposioTools).toHaveBeenCalledWith(
- {
- tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
- },
- { modifySchema: modifier1.modifySchema }
- );
+ expect(firstToolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(sessionId, {
+ modifySchema: modifier1.modifySchema,
+ });
expect(firstToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
sessionId,
- [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
modifier1
);
const secondToolsInstance = (Tools as any).mock.results[1].value;
- expect(secondToolsInstance.getRawComposioTools).toHaveBeenCalledWith(
- {
- tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
- },
- { modifySchema: modifier2.modifySchema }
- );
+ expect(secondToolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(sessionId, {
+ modifySchema: modifier2.modifySchema,
+ });
expect(secondToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
sessionId,
- [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
modifier2
);
});
@@ -1772,15 +1761,13 @@ describe('ToolRouter', () => {
apiKey: 'test-api-key',
});
const toolsInstance = (Tools as any).mock.results[0].value;
- expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
- {
- tools: ['CUSTOM_TOOL_1', 'CUSTOM_TOOL_2'],
- },
+ expect(toolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(
+ 'custom_session_123',
undefined
);
expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
'custom_session_123',
- [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
undefined
);
});
@@ -1802,15 +1789,13 @@ describe('ToolRouter', () => {
apiKey: 'test-api-key',
});
const toolsInstance = (Tools as any).mock.results[0].value;
- expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
- {
- tools: [],
- },
+ expect(toolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(
+ 'empty_session_123',
undefined
);
expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
'empty_session_123',
- [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
undefined
);
});
@@ -1963,15 +1948,10 @@ describe('ToolRouter', () => {
expect(Tools).toHaveBeenCalled();
const toolsInstance = (Tools as any).mock.results[0].value;
- expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
- {
- tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
- },
- undefined
- );
+ expect(toolsInstance.getRawToolRouterMetaTools).toHaveBeenCalledWith(sessionId, undefined);
expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
sessionId,
- [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
undefined
);
});
diff --git a/ts/packages/core/test/tools/tools.test.ts b/ts/packages/core/test/tools/tools.test.ts
index bfcdb5dc1..8184b0a46 100644
--- a/ts/packages/core/test/tools/tools.test.ts
+++ b/ts/packages/core/test/tools/tools.test.ts
@@ -769,15 +769,15 @@ describe('Tools', () => {
});
it('should throw error if tool is not found', async () => {
- const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
- getRawComposioToolBySlugSpy.mockResolvedValueOnce(undefined as any);
+ const apiError = new Error('Tool not found');
+ mockClient.toolRouter.session.executeMeta.mockRejectedValueOnce(apiError);
await expect(
context.tools.executeMetaTool('NONEXISTENT_TOOL', {
sessionId,
arguments: { query: 'test' },
})
- ).rejects.toThrow('Tool NONEXISTENT_TOOL not found');
+ ).rejects.toThrow('Tool not found');
});
it('should apply beforeExecute modifier', async () => {
@@ -810,7 +810,8 @@ describe('Tools', () => {
expect(beforeExecute).toHaveBeenCalledWith({
toolSlug,
- toolkitSlug: 'test-toolkit',
+ toolkitSlug: 'composio',
+ sessionId,
params: { query: 'original' },
});
@@ -850,7 +851,8 @@ describe('Tools', () => {
expect(afterExecute).toHaveBeenCalledWith({
toolSlug,
- toolkitSlug: 'test-toolkit',
+ toolkitSlug: 'composio',
+ sessionId,
result: {
data: { results: true },
error: null,
@@ -917,7 +919,8 @@ describe('Tools', () => {
expect(beforeExecute).toHaveBeenCalledWith({
toolSlug,
- toolkitSlug: 'unknown',
+ toolkitSlug: 'composio',
+ sessionId,
params: { query: 'test' },
});
});
diff --git a/uv.lock b/uv.lock
index 73f31d3d9..53b5aa191 100644
--- a/uv.lock
+++ b/uv.lock
@@ -477,7 +477,7 @@ wheels = [
[[package]]
name = "composio"
-version = "0.10.3"
+version = "0.10.5"
source = { virtual = "python" }
dependencies = [
{ name = "composio-client" },
@@ -506,7 +506,7 @@ dev = [
[package.metadata]
requires-dist = [
- { name = "composio-client", specifier = "==1.22.0" },
+ { name = "composio-client", specifier = "==1.25.0" },
{ name = "openai" },
{ name = "pydantic", specifier = ">=2.6.4" },
{ name = "pysher", specifier = ">=1.0.8" },
@@ -532,7 +532,7 @@ dev = [
[[package]]
name = "composio-anthropic"
-version = "0.10.3"
+version = "0.10.5"
source = { virtual = "python/providers/anthropic" }
dependencies = [
{ name = "anthropic" },
@@ -547,7 +547,7 @@ requires-dist = [
[[package]]
name = "composio-client"
-version = "1.22.0"
+version = "1.25.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
@@ -557,14 +557,14 @@ dependencies = [
{ name = "sniffio" },
{ name = "typing-extensions" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/44/a7/81fe217a855992ee3854acd07939c0eed893d9b8019ea544e28fd0aa1b86/composio_client-1.22.0.tar.gz", hash = "sha256:13dd4ecf3b1289cfd6acdb538f9144d123d0344c03b387aa411d6fb0f1dec6d0", size = 185804 }
+sdist = { url = "https://files.pythonhosted.org/packages/c4/72/270a24236f4580d1eced2eb4b38c4a9bd399714ef2b76c74952729687276/composio_client-1.25.0.tar.gz", hash = "sha256:ae335bc90309b9d5f222c48c85a20a4c701afda5e3015cb3472245c01aa632bb", size = 190472 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/8f/1f/2abe83f3363edc3d5be94002f97eafed9ea95d7129fe6ea1c33655751aeb/composio_client-1.22.0-py3-none-any.whl", hash = "sha256:3afe32fd3206c3bd2a7183d729817908fdc4bfac2b52da22144334fab2384932", size = 201474 },
+ { url = "https://files.pythonhosted.org/packages/56/0b/9f92a8b2bce0a23f39c98e860fe14e58365d804c0dea8277ed6b4e5e66f4/composio_client-1.25.0-py3-none-any.whl", hash = "sha256:de6b05667f29692a4425b43d53349c7b31439012ffc3f93059ceacb5cc3fbe56", size = 209162 },
]
[[package]]
name = "composio-crewai"
-version = "0.10.3"
+version = "0.10.5"
source = { virtual = "python/providers/crewai" }
dependencies = [
{ name = "composio" },
@@ -579,7 +579,7 @@ requires-dist = [
[[package]]
name = "composio-gemini"
-version = "0.10.3"
+version = "0.10.5"
source = { virtual = "python/providers/gemini" }
dependencies = [
{ name = "composio" },
@@ -594,7 +594,7 @@ requires-dist = [
[[package]]
name = "composio-google"
-version = "0.10.3"
+version = "0.10.5"
source = { virtual = "python/providers/google" }
dependencies = [
{ name = "composio" },
@@ -609,7 +609,7 @@ requires-dist = [
[[package]]
name = "composio-google-adk"
-version = "0.10.3"
+version = "0.10.5"
source = { virtual = "python/providers/google_adk" }
dependencies = [
{ name = "composio" },
@@ -624,7 +624,7 @@ requires-dist = [
[[package]]
name = "composio-langchain"
-version = "0.10.3"
+version = "0.10.5"
source = { virtual = "python/providers/langchain" }
dependencies = [
{ name = "composio" },
@@ -639,7 +639,7 @@ requires-dist = [
[[package]]
name = "composio-openai"
-version = "0.10.3"
+version = "0.10.5"
source = { virtual = "python/providers/openai" }
dependencies = [
{ name = "composio" },
@@ -654,7 +654,7 @@ requires-dist = [
[[package]]
name = "composio-openai-agents"
-version = "0.10.3"
+version = "0.10.5"
source = { virtual = "python/providers/openai_agents" }
dependencies = [
{ name = "composio" },
@@ -892,7 +892,7 @@ dev = [
requires-dist = [
{ name = "click", specifier = ">=8.1.7" },
{ name = "composio", virtual = "python" },
- { name = "composio-client", specifier = "==1.22.0" },
+ { name = "composio-client", specifier = "==1.25.0" },
{ name = "composio-gemini", virtual = "python/providers/gemini" },
{ name = "composio-langchain", virtual = "python/providers/langchain" },
{ name = "composio-openai", virtual = "python/providers/openai" },