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.

Update tool router sdk docs (#2369)

Musthaq Ahamad4a9167d7682e
diff --git a/python/docs/tool-router.md b/python/docs/tool-router.md
index f9b70f325..f1ef8abc0 100644
--- a/python/docs/tool-router.md
+++ b/python/docs/tool-router.md
@@ -211,7 +211,24 @@ session = composio.tool_router.create(
toolkits=['gmail'],
manage_connections={
'enable': True, # Whether to use tools to manage connections
- 'callback_url': 'https://your-app.com/auth/callback' # Optional OAuth callback URL
+ 'callback_url': 'https://your-app.com/auth/callback', # Optional OAuth callback URL
+ 'wait_for_connections': True # NEW in v0.10.5: Wait for connections to complete
+ }
+)
+```
+
+#### Wait for Connections
+
+The `wait_for_connections` property (new in v0.10.5) allows the tool router session to wait for users to complete authentication before proceeding to the next step. When set to `True`, the session will block execution until all required connections are established.
+
+```python
+session = composio.tool_router.create(
+ user_id='user_123',
+ toolkits=['gmail', 'slack'],
+ manage_connections={
+ 'enable': True,
+ 'callback_url': 'https://your-app.com/auth/callback',
+ 'wait_for_connections': True # Session waits for connections to complete
}
)
```
@@ -261,13 +278,67 @@ Retrieve the tools available in the session, formatted for your AI framework.
# Basic usage
tools = session.tools()
-# With modifiers
-tools = session.tools(modifiers={
- 'pre_execute': lambda tool, args: print(f"Executing {tool}"),
- 'post_execute': lambda tool, result: print(f"Result: {result}"),
-})
+# With session-specific modifiers (new in v0.10.5)
+from composio.core.models import before_execute_meta, after_execute_meta
+
+@before_execute_meta
+def before_modifier(tool, toolkit, session_id, params):
+ print(f"[Session: {session_id}] Executing {tool} from {toolkit}")
+ # Add custom logging, validation, or parameter transformation
+ return params
+
+@after_execute_meta
+def after_modifier(tool, toolkit, session_id, response):
+ print(f"[Session: {session_id}] Completed {tool}")
+ # Transform results, add telemetry, or handle errors
+ return response
+
+tools = session.tools(modifiers=[before_modifier, after_modifier])
```
+#### Session-Specific Modifiers
+
+Tool Router sessions now support enhanced modifiers (introduced in v0.10.5) that include session context:
+
+- **`@before_execute_meta`**: Modify parameters before execution, with access to session ID
+- **`@after_execute_meta`**: Transform results after execution, with access to session ID
+- **`@modify_schema_meta`**: Customize tool schemas before they're sent to the AI model
+
+These modifiers provide better context for session-based tool execution, allowing you to track which session is executing which tools.
+
+### Meta Tools
+
+Tool Router provides meta tools for managing connections and session state. You can access these directly using the `get_raw_tool_router_meta_tools` method (introduced in v0.10.5):
+
+```python
+from composio import Composio
+from composio.core.models import modify_schema_meta
+
+composio = Composio()
+
+# Define schema modifier
+@modify_schema_meta
+def schema_modifier(tool, toolkit, schema):
+ # Customize meta tool schemas
+ print(f"Modifying schema for {tool}")
+ return schema
+
+# Get raw meta tools for a session
+meta_tools = composio.tools.get_raw_tool_router_meta_tools(
+ session_id='session_123',
+ modifiers=[schema_modifier]
+)
+
+print(f"Available meta tools: {[t.name for t in meta_tools]}")
+```
+
+Meta tools allow you to:
+- Authorize new toolkit connections within a session
+- Query toolkit connection states
+- Manage session configuration
+
+This method is useful when you need direct access to the underlying meta tools without creating a full session object.
+
### `authorize(toolkit, *, callback_url=None)`
Initiate an authorization flow for a toolkit.
@@ -672,12 +743,13 @@ tags: List[Literal['readOnlyHint', 'destructiveHint', 'idempotentHint', 'openWor
# Manage connections configuration
ToolRouterManageConnectionsConfig = TypedDict('ToolRouterManageConnectionsConfig', {
'enable': bool,
- 'callback_url': str # Optional
+ 'callback_url': str, # Optional
+ 'wait_for_connections': bool # NEW in v0.10.5: Wait for connections to complete
})
manage_connections: Union[
bool,
- ToolRouterManageConnectionsConfig # {'enable': True, 'callback_url': 'https://...'}
+ ToolRouterManageConnectionsConfig # {'enable': True, 'callback_url': 'https://...', 'wait_for_connections': True}
]
# Workbench configuration
@@ -689,3 +761,66 @@ ToolRouterWorkbenchConfig = TypedDict('ToolRouterWorkbenchConfig', {
workbench: ToolRouterWorkbenchConfig
```
+## What's New in v0.10.5
+
+### 1. Wait for Connections
+
+The new `wait_for_connections` property allows sessions to wait for users to complete authentication before proceeding:
+
+```python
+session = composio.tool_router.create(
+ user_id='user_123',
+ toolkits=['gmail', 'slack'],
+ manage_connections={
+ 'enable': True,
+ 'callback_url': 'https://your-app.com/callback',
+ 'wait_for_connections': True # NEW
+ }
+)
+```
+
+### 2. Enhanced Session Modifiers
+
+Session-specific modifiers now include session context, making it easier to track and manage tool execution:
+
+```python
+from composio.core.models import before_execute_meta, after_execute_meta
+
+@before_execute_meta
+def before_modifier(tool, toolkit, session_id, params):
+ print(f"[{session_id}] Executing {tool}")
+ return params
+
+@after_execute_meta
+def after_modifier(tool, toolkit, session_id, response):
+ print(f"[{session_id}] Completed {tool}")
+ return response
+
+tools = session.tools(modifiers=[before_modifier, after_modifier])
+```
+
+### 3. Direct Meta Tools Access
+
+New method to fetch meta tools directly from a session:
+
+```python
+from composio.core.models import modify_schema_meta
+
+@modify_schema_meta
+def schema_modifier(tool, toolkit, schema):
+ return schema
+
+meta_tools = composio.tools.get_raw_tool_router_meta_tools(
+ session_id='session_123',
+ modifiers=[schema_modifier]
+)
+```
+
+### 4. Performance Improvements
+
+- Optimized tool fetching with fewer API calls
+- Improved session API architecture for better reliability
+- Simplified internal tool execution paths
+
+All changes in v0.10.5 are fully backward compatible with existing code.
+
diff --git a/ts/docs/advanced/modifiers.md b/ts/docs/advanced/modifiers.md
index 5eda825be..fd6c2df9a 100644
--- a/ts/docs/advanced/modifiers.md
+++ b/ts/docs/advanced/modifiers.md
@@ -563,6 +563,88 @@ const result = await openaiProvider.executeToolCall(
);
```
+## Tool Router Modifiers (v0.4.0+)
+
+Tool Router sessions support enhanced modifier types that include session context. This is useful for tracking and managing tool execution across different user sessions.
+
+### Using Session Modifiers with Tool Router
+
+```typescript
+import { Composio } from '@composio/core';
+import { SessionExecuteMetaModifiers } from '@composio/core';
+
+const composio = new Composio();
+
+const session = await composio.create('user_123', {
+ toolkits: ['gmail', 'slack'],
+});
+
+// Use session-specific modifiers
+const tools = await session.tools({
+ modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
+ // Customize tool schemas
+ console.log(`Modifying schema for ${toolSlug} from ${toolkitSlug}`);
+ return schema;
+ },
+ beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {
+ // Access session ID for tracking
+ console.log(`[Session: ${sessionId}] Executing ${toolSlug} from ${toolkitSlug}`);
+
+ // Add session-specific metadata
+ params.sessionMetadata = {
+ sessionId,
+ timestamp: new Date().toISOString(),
+ };
+
+ return params;
+ },
+ afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => {
+ // Transform results with session context
+ console.log(`[Session: ${sessionId}] Completed ${toolSlug}`);
+
+ if (result.successful) {
+ result.data.sessionId = sessionId;
+ result.data.executedAt = new Date().toISOString();
+ }
+
+ return result;
+ },
+});
+```
+
+### Session-Specific Modifier Benefits
+
+The session-specific modifiers provide several advantages:
+
+1. **Session Tracking**: Access to `sessionId` allows you to track which session executed which tools
+2. **User Context**: Associate tool executions with specific users through session IDs
+3. **Audit Logging**: Log tool executions with session context for compliance and debugging
+4. **Performance Monitoring**: Track tool execution performance per session
+
+### Getting Meta Tools Directly
+
+You can also fetch tool router meta tools directly using the new method:
+
+```typescript
+import { Composio } from '@composio/core';
+
+const composio = new Composio();
+
+// Get raw meta tools for a session
+const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123', {
+ modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
+ // Customize meta tool schemas
+ if (toolSlug === 'composio_authorize_toolkit') {
+ schema.description = 'Custom description for authorization';
+ }
+ return schema;
+ }
+});
+
+// Use the meta tools with your AI framework
+console.log('Available meta tools:', metaTools.map(t => t.name));
+```
+
## Type Definitions
```typescript
@@ -595,4 +677,36 @@ interface ProviderOptions<TProvider> {
beforeExecute?: beforeExecuteModifier; // Only applied by agentic providers
afterExecute?: afterExecuteModifier; // Only applied by agentic providers
}
+
+// Session-Specific Modifiers (v0.4.0+)
+interface SessionExecuteMetaModifiers {
+ modifySchema?: (context: {
+ toolSlug: string;
+ toolkitSlug: string;
+ schema: any;
+ }) => any;
+
+ beforeExecute?: (context: {
+ toolSlug: string;
+ toolkitSlug: string;
+ sessionId: string;
+ params: any;
+ }) => any;
+
+ afterExecute?: (context: {
+ toolSlug: string;
+ toolkitSlug: string;
+ sessionId: string;
+ result: any;
+ }) => any;
+}
+
+// Session Meta Tool Options (v0.4.0+)
+interface SessionMetaToolOptions {
+ modifySchema?: (context: {
+ toolSlug: string;
+ toolkitSlug: string;
+ schema: any;
+ }) => any;
+}
```
diff --git a/ts/docs/api/tool-router.md b/ts/docs/api/tool-router.md
index 4d5a02211..5df033463 100644
--- a/ts/docs/api/tool-router.md
+++ b/ts/docs/api/tool-router.md
@@ -24,13 +24,13 @@ When using Tool Router with MCP clients, you don't need to pass a provider:
```bash
# npm
-npm install @composio/[email protected]
+npm install @composio/[email protected]
# pnpm
-pnpm add @composio/[email protected]
+pnpm add @composio/[email protected]
# yarn
-yarn add @composio/[email protected]
+yarn add @composio/[email protected]
```
```typescript
@@ -206,7 +206,23 @@ const session = await composio.create('user_123', {
toolkits: ['gmail'],
manageConnections: {
enable: true,
- callbackUrl: 'https://your-app.com/auth/callback'
+ callbackUrl: 'https://your-app.com/auth/callback',
+ waitForConnections: true // Wait for user to complete authentication before proceeding
+ }
+});
+```
+
+#### Wait for Connections
+
+The `waitForConnections` property (new in v0.4.0) allows the tool router session to wait for users to complete authentication before proceeding to the next step. When set to `true`, the session will block execution until all required connections are established.
+
+```typescript
+const session = await composio.create('user_123', {
+ toolkits: ['gmail', 'slack'],
+ manageConnections: {
+ enable: true,
+ callbackUrl: 'https://your-app.com/auth/callback',
+ waitForConnections: true // Session waits for connections to complete
}
});
```
@@ -254,19 +270,61 @@ Retrieve the tools available in the session, formatted for your AI framework.
```typescript
const tools = await session.tools();
-// With modifiers
+// With session-specific modifiers (new in v0.4.0)
const tools = await session.tools({
- beforeExecute: ({ toolSlug, params }) => {
- console.log(`Executing ${toolSlug}`);
+ modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
+ // Customize the tool schema
+ return schema;
+ },
+ beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {
+ console.log(`Executing ${toolSlug} in session ${sessionId}`);
return params;
},
- afterExecute: ({ toolSlug, result }) => {
- console.log(`Completed ${toolSlug}`);
+ afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => {
+ console.log(`Completed ${toolSlug} in session ${sessionId}`);
return result;
}
});
```
+#### Session-Specific Modifiers
+
+Tool Router sessions now support enhanced modifier types (introduced in v0.4.0) that include session context:
+
+- **`modifySchema`**: Customize tool schemas before they're sent to the AI model
+- **`beforeExecute`**: Modify parameters before execution, with access to session ID
+- **`afterExecute`**: Transform results after execution, with access to session ID
+
+These modifiers provide better context for session-based tool execution, allowing you to track which session is executing which tools.
+
+### Meta Tools
+
+Tool Router provides meta tools for managing connections and session state. You can access these directly using the `getRawToolRouterMetaTools` method (introduced in v0.4.0):
+
+```typescript
+import { Composio } from '@composio/core';
+
+const composio = new Composio();
+
+// Get raw meta tools for a session
+const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123', {
+ modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
+ // Customize meta tool schemas
+ console.log(`Modifying schema for ${toolSlug}`);
+ return schema;
+ }
+});
+
+console.log('Available meta tools:', metaTools.map(t => t.name));
+```
+
+Meta tools allow you to:
+- Authorize new toolkit connections within a session
+- Query toolkit connection states
+- Manage session configuration
+
+This method is useful when you need direct access to the underlying meta tools without creating a full session object.
+
### `authorize()`
Initiate an authorization flow for a toolkit.
@@ -611,18 +669,25 @@ The response includes:
## Using Modifiers
-Add custom behavior before and after tool execution:
+Add custom behavior before and after tool execution. Tool Router supports enhanced session-specific modifiers (v0.4.0+):
```typescript
-import { ExecuteToolModifiers } from "@composio/core";
+import { SessionExecuteMetaModifiers } from "@composio/core";
-const modifiers: ExecuteToolModifiers = {
- beforeExecute: ({ toolSlug, params }) => {
- console.log(`Executing ${toolSlug}`);
+const modifiers: SessionExecuteMetaModifiers = {
+ modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
+ // Customize tool schema
+ console.log(`Modifying schema for ${toolSlug}`);
+ return schema;
+ },
+ beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {
+ console.log(`[Session: ${sessionId}] Executing ${toolSlug} from ${toolkitSlug}`);
+ // Add custom logging, validation, or parameter transformation
return params;
},
- afterExecute: ({ toolSlug, result }) => {
- console.log(`Executed ${toolSlug}`);
+ afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => {
+ console.log(`[Session: ${sessionId}] Executed ${toolSlug} from ${toolkitSlug}`);
+ // Transform results, add telemetry, or handle errors
return result;
},
};
@@ -630,6 +695,15 @@ const modifiers: ExecuteToolModifiers = {
const tools = await session.tools(modifiers);
```
+### Modifier Types
+
+Tool Router provides specialized modifier types for session-based execution:
+
+- **`SessionExecuteMetaModifiers`**: Complete set of modifiers with session context
+- **`SessionMetaToolOptions`**: Configuration options for meta tools
+
+These types include the `sessionId` in their parameters, allowing you to track and manage tool execution across different user sessions.
+
## Best Practices
1. **User Isolation**: Create separate sessions per user to ensure proper isolation of connections and tools.
@@ -673,6 +747,7 @@ interface ToolRouterCreateSessionConfig {
manageConnections?: boolean | {
enable?: boolean;
callbackUrl?: string;
+ waitForConnections?: boolean; // NEW in v0.4.0: Wait for connections to complete
};
workbench?: {
enableProxyExecution?: boolean;
@@ -724,3 +799,77 @@ interface ToolkitConnectionState {
}
```
+### SessionExecuteMetaModifiers (v0.4.0+)
+
+```typescript
+interface SessionExecuteMetaModifiers {
+ modifySchema?: (context: {
+ toolSlug: string;
+ toolkitSlug: string;
+ schema: any;
+ }) => any;
+
+ beforeExecute?: (context: {
+ toolSlug: string;
+ toolkitSlug: string;
+ sessionId: string;
+ params: any;
+ }) => any;
+
+ afterExecute?: (context: {
+ toolSlug: string;
+ toolkitSlug: string;
+ sessionId: string;
+ result: any;
+ }) => any;
+}
+```
+
+## What's New in v0.4.0
+
+### 1. Wait for Connections
+
+The new `waitForConnections` property allows sessions to wait for users to complete authentication before proceeding:
+
+```typescript
+const session = await composio.create('user_123', {
+ toolkits: ['gmail', 'slack'],
+ manageConnections: {
+ enable: true,
+ callbackUrl: 'https://your-app.com/callback',
+ waitForConnections: true // NEW
+ }
+});
+```
+
+### 2. Enhanced Session Modifiers
+
+Session-specific modifiers now include session context, making it easier to track and manage tool execution:
+
+```typescript
+const tools = await session.tools({
+ beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {
+ console.log(`[${sessionId}] Executing ${toolSlug}`);
+ return params;
+ }
+});
+```
+
+### 3. Direct Meta Tools Access
+
+New method to fetch meta tools directly from a session:
+
+```typescript
+const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123', {
+ modifySchema: ({ toolSlug, schema }) => schema
+});
+```
+
+### 4. Performance Improvements
+
+- Optimized tool fetching with fewer API calls
+- Improved session API architecture for better reliability
+- Simplified internal tool execution paths
+
+All changes in v0.4.0 are fully backward compatible with existing code.
+