Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | # Tool Router |
| 2 | |
| 3 | The Tool Router provides a powerful way to create isolated MCP (Model Context Protocol) sessions for users with scoped access to toolkits and tools. It enables dynamic configuration of which tools are available within a session and manages authentication for multiple toolkits. |
| 4 | |
| 5 | ## Overview |
| 6 | |
| 7 | Tool Router allows you to: |
| 8 | |
| 9 | - Create isolated sessions with specific toolkit configurations |
| 10 | - Manage authentication flows for users across multiple toolkits |
| 11 | - Access tools via an MCP-compatible server URL |
| 12 | - Query toolkit connection states |
| 13 | - Integrate with multiple AI frameworks (OpenAI, Anthropic, LangChain, LlamaIndex, CrewAI) |
| 14 | |
| 15 | > **Note:** When using MCP clients to connect to Tool Router, you don't need to pass a provider to the Composio constructor. A provider is only required when using `session.tools()` to get framework-specific tool objects. |
| 16 | |
| 17 | ## Installation |
| 18 | |
| 19 | ```bash |
| 20 | pip install composio |
| 21 | ``` |
| 22 | |
| 23 | ## Quick Start |
| 24 | |
| 25 | ### Using MCP (Recommended) |
| 26 | |
| 27 | When using Tool Router with MCP clients, you don't need to pass a provider: |
| 28 | |
| 29 | ```python |
| 30 | from composio import Composio |
| 31 | |
| 32 | composio = Composio() |
| 33 | |
| 34 | # Create a session for a user with access to Gmail tools |
| 35 | session = composio.tool_router.create( |
| 36 | user_id='user_123', |
| 37 | toolkits=['gmail'] |
| 38 | ) |
| 39 | |
| 40 | # Use the MCP URL with any MCP-compatible client |
| 41 | print(session.mcp.url) |
| 42 | ``` |
| 43 | |
| 44 | ### Using Framework-Specific Tools |
| 45 | |
| 46 | If you want to use `session.tools()` to get tools formatted for a specific AI framework, pass the appropriate provider: |
| 47 | |
| 48 | ```python |
| 49 | from composio import Composio |
| 50 | from composio_openai import OpenAIProvider |
| 51 | |
| 52 | composio = Composio(provider=OpenAIProvider()) |
| 53 | |
| 54 | # Create a session for a user with access to Gmail tools |
| 55 | session = composio.tool_router.create( |
| 56 | user_id='user_123', |
| 57 | toolkits=['gmail'] |
| 58 | ) |
| 59 | |
| 60 | # Get the tools formatted for OpenAI |
| 61 | tools = session.tools() |
| 62 | ``` |
| 63 | |
| 64 | ## Creating Sessions |
| 65 | |
| 66 | ### Basic Session Creation |
| 67 | |
| 68 | Use `composio.tool_router.create()` to create a new Tool Router session: |
| 69 | |
| 70 | ```python |
| 71 | from composio import Composio |
| 72 | |
| 73 | composio = Composio() |
| 74 | |
| 75 | # Create a session with Gmail access |
| 76 | session = composio.tool_router.create( |
| 77 | user_id='user_123', |
| 78 | toolkits=['gmail'] |
| 79 | ) |
| 80 | |
| 81 | print(f"Session ID: {session.session_id}") |
| 82 | print(f"MCP URL: {session.mcp.url}") |
| 83 | ``` |
| 84 | |
| 85 | ### Using an Existing Session |
| 86 | |
| 87 | If you have an existing session ID, you can retrieve it using `composio.tool_router.use()`: |
| 88 | |
| 89 | ```python |
| 90 | session = composio.tool_router.use('existing_session_id') |
| 91 | |
| 92 | # Access session properties |
| 93 | print(session.session_id) |
| 94 | print(session.mcp.url) |
| 95 | ``` |
| 96 | |
| 97 | ## Configuration Options |
| 98 | |
| 99 | The session creation accepts the following configuration options: |
| 100 | |
| 101 | ### `toolkits` |
| 102 | |
| 103 | Specify which toolkits to enable or disable in the session. |
| 104 | |
| 105 | ```python |
| 106 | # Simple list of toolkit slugs to enable |
| 107 | session = composio.tool_router.create( |
| 108 | user_id='user_123', |
| 109 | toolkits=['gmail', 'slack', 'github'] |
| 110 | ) |
| 111 | |
| 112 | # Explicit enabled configuration |
| 113 | session = composio.tool_router.create( |
| 114 | user_id='user_123', |
| 115 | toolkits={'enable': ['gmail', 'slack']} |
| 116 | ) |
| 117 | |
| 118 | # Disable specific toolkits (enable all others) |
| 119 | session = composio.tool_router.create( |
| 120 | user_id='user_123', |
| 121 | toolkits={'disable': ['calendar']} |
| 122 | ) |
| 123 | ``` |
| 124 | |
| 125 | ### `tools` |
| 126 | |
| 127 | Fine-grained control over which tools are available within toolkits. This is a dictionary where keys are toolkit slugs and values specify tool configuration for that toolkit. |
| 128 | |
| 129 | ```python |
| 130 | session = composio.tool_router.create( |
| 131 | user_id='user_123', |
| 132 | toolkits=['gmail', 'github', 'slack'], |
| 133 | tools={ |
| 134 | # List shorthand - enables only these tools |
| 135 | 'gmail': ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'], |
| 136 | |
| 137 | # Explicit enable configuration |
| 138 | 'github': {'enable': ['GITHUB_CREATE_AN_ISSUE', 'GITHUB_LIST_ISSUES']}, |
| 139 | |
| 140 | # Explicit disable configuration |
| 141 | 'slack': {'disable': ['SLACK_DELETE_MESSAGE']}, |
| 142 | |
| 143 | # Filter by behavior tags (readOnlyHint, destructiveHint, createHint, updateHint) |
| 144 | 'linear': {'tags': ['readOnlyHint', 'createHint']} |
| 145 | } |
| 146 | ) |
| 147 | ``` |
| 148 | |
| 149 | ### `tags` |
| 150 | |
| 151 | Global MCP tags to filter tools by across all toolkits. Only tools matching these tags will be available. Toolkit-level tags (specified in `tools`) override this global setting. |
| 152 | |
| 153 | ```python |
| 154 | session = composio.tool_router.create( |
| 155 | user_id='user_123', |
| 156 | toolkits=['gmail', 'github', 'slack'], |
| 157 | tags=['readOnlyHint', 'createHint'] # Only show tools that read or create |
| 158 | ) |
| 159 | ``` |
| 160 | |
| 161 | Every tool has a tag for the type of action it takes: |
| 162 | - `'readOnlyHint'`: reads data and changes nothing |
| 163 | - `'createHint'`: adds something new |
| 164 | - `'updateHint'`: changes something that already exists |
| 165 | - `'destructiveHint'`: deletes something |
| 166 | |
| 167 | See [Tool tags](https://docs.composio.dev/docs/tool-tags) for how tools get their tags. |
| 168 | |
| 169 | ### `auth_configs` |
| 170 | |
| 171 | Map toolkits to specific authentication configurations: |
| 172 | |
| 173 | ```python |
| 174 | session = composio.tool_router.create( |
| 175 | user_id='user_123', |
| 176 | toolkits=['gmail', 'github'], |
| 177 | auth_configs={ |
| 178 | 'gmail': 'ac_gmail_work', |
| 179 | 'github': 'ac_github_personal' |
| 180 | } |
| 181 | ) |
| 182 | ``` |
| 183 | |
| 184 | ### `connected_accounts` |
| 185 | |
| 186 | Map toolkits to specific connected account IDs: |
| 187 | |
| 188 | ```python |
| 189 | session = composio.tool_router.create( |
| 190 | user_id='user_123', |
| 191 | toolkits=['gmail'], |
| 192 | connected_accounts={ |
| 193 | 'gmail': 'ca_abc123' |
| 194 | } |
| 195 | ) |
| 196 | ``` |
| 197 | |
| 198 | ### `manage_connections` |
| 199 | |
| 200 | Control how connections are managed within the session: |
| 201 | |
| 202 | ```python |
| 203 | # Boolean: enable/disable automatic connection management |
| 204 | session = composio.tool_router.create( |
| 205 | user_id='user_123', |
| 206 | toolkits=['gmail'], |
| 207 | manage_connections=True # default |
| 208 | ) |
| 209 | |
| 210 | # Dict: fine-grained control |
| 211 | session = composio.tool_router.create( |
| 212 | user_id='user_123', |
| 213 | toolkits=['gmail'], |
| 214 | manage_connections={ |
| 215 | 'enable': True, # Whether to use tools to manage connections |
| 216 | 'callback_url': 'https://your-app.com/auth/callback', # Optional OAuth callback URL |
| 217 | 'wait_for_connections': True # NEW in v0.10.5: Wait for connections to complete |
| 218 | } |
| 219 | ) |
| 220 | ``` |
| 221 | |
| 222 | #### Wait for Connections |
| 223 | |
| 224 | 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. |
| 225 | |
| 226 | ```python |
| 227 | session = composio.tool_router.create( |
| 228 | user_id='user_123', |
| 229 | toolkits=['gmail', 'slack'], |
| 230 | manage_connections={ |
| 231 | 'enable': True, |
| 232 | 'callback_url': 'https://your-app.com/auth/callback', |
| 233 | 'wait_for_connections': True # Session waits for connections to complete |
| 234 | } |
| 235 | ) |
| 236 | ``` |
| 237 | |
| 238 | ### `workbench` |
| 239 | |
| 240 | Configure workbench behavior: |
| 241 | |
| 242 | ```python |
| 243 | # Disable workbench entirely — no code execution tools in the session |
| 244 | session = composio.tool_router.create( |
| 245 | user_id='user_123', |
| 246 | toolkits=['gmail'], |
| 247 | workbench={ |
| 248 | 'enable': False |
| 249 | } |
| 250 | ) |
| 251 | |
| 252 | # Fine-tune workbench settings |
| 253 | session = composio.tool_router.create( |
| 254 | user_id='user_123', |
| 255 | toolkits=['gmail'], |
| 256 | workbench={ |
| 257 | 'enable': True, # default |
| 258 | 'enable_proxy_execution': False, # Whether to allow proxy execute calls in workbench |
| 259 | 'auto_offload_threshold': 300 # Character threshold for auto-offloading large responses to the workbench |
| 260 | } |
| 261 | ) |
| 262 | ``` |
| 263 | |
| 264 | | Field | Type | Default | Description | |
| 265 | |-------|------|---------|-------------| |
| 266 | | `enable` | `bool` | `True` | Enables/disables the workbench entirely. When `False`, `COMPOSIO_REMOTE_WORKBENCH` and `COMPOSIO_REMOTE_BASH_TOOL` are excluded from the session. | |
| 267 | | `enable_proxy_execution` | `bool` | `True` | Controls proxy API execution in the workbench. | |
| 268 | | `auto_offload_threshold` | `int` | auto | Character threshold for auto-offloading large responses to the workbench. | |
| 269 | |
| 270 | ## Session Properties and Methods |
| 271 | |
| 272 | A Tool Router session provides the following properties and methods: |
| 273 | |
| 274 | ### `session_id` |
| 275 | |
| 276 | The unique identifier for this session. |
| 277 | |
| 278 | ```python |
| 279 | print(session.session_id) |
| 280 | ``` |
| 281 | |
| 282 | ### `mcp` |
| 283 | |
| 284 | The MCP server configuration for this session, including authentication headers. |
| 285 | |
| 286 | ```python |
| 287 | print(session.mcp.url) # The URL to connect to |
| 288 | print(session.mcp.type) # ToolRouterMCPServerType.HTTP or ToolRouterMCPServerType.SSE |
| 289 | print(session.mcp.headers) # Authentication headers (includes x-api-key) |
| 290 | ``` |
| 291 | |
| 292 | ### `tools(modifiers=None)` |
| 293 | |
| 294 | Retrieve the tools available in the session, formatted for your AI framework. |
| 295 | |
| 296 | ```python |
| 297 | # Basic usage |
| 298 | tools = session.tools() |
| 299 | |
| 300 | # With session-specific modifiers (new in v0.10.5) |
| 301 | from composio.core.models import before_execute_meta, after_execute_meta |
| 302 | |
| 303 | @before_execute_meta |
| 304 | def before_modifier(tool, toolkit, session_id, params): |
| 305 | print(f"[Session: {session_id}] Executing {tool} from {toolkit}") |
| 306 | # Add custom logging, validation, or parameter transformation |
| 307 | return params |
| 308 | |
| 309 | @after_execute_meta |
| 310 | def after_modifier(tool, toolkit, session_id, response): |
| 311 | print(f"[Session: {session_id}] Completed {tool}") |
| 312 | # Transform results, add telemetry, or handle errors |
| 313 | return response |
| 314 | |
| 315 | tools = session.tools(modifiers=[before_modifier, after_modifier]) |
| 316 | ``` |
| 317 | |
| 318 | #### Session-Specific Modifiers |
| 319 | |
| 320 | Tool Router sessions now support enhanced modifiers (introduced in v0.10.5) that include session context: |
| 321 | |
| 322 | - **`@before_execute_meta`**: Modify parameters before execution, with access to session ID |
| 323 | - **`@after_execute_meta`**: Transform results after execution, with access to session ID |
| 324 | - **`@modify_schema_meta`**: Customize tool schemas before they're sent to the AI model |
| 325 | |
| 326 | These modifiers provide better context for session-based tool execution, allowing you to track which session is executing which tools. |
| 327 | |
| 328 | ### Meta Tools |
| 329 | |
| 330 | 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): |
| 331 | |
| 332 | ```python |
| 333 | from composio import Composio |
| 334 | from composio.core.models import modify_schema_meta |
| 335 | |
| 336 | composio = Composio() |
| 337 | |
| 338 | # Define schema modifier |
| 339 | @modify_schema_meta |
| 340 | def schema_modifier(tool, toolkit, schema): |
| 341 | # Customize meta tool schemas |
| 342 | print(f"Modifying schema for {tool}") |
| 343 | return schema |
| 344 | |
| 345 | # Get raw meta tools for a session |
| 346 | meta_tools = composio.tools.get_raw_tool_router_meta_tools( |
| 347 | session_id='session_123', |
| 348 | modifiers=[schema_modifier] |
| 349 | ) |
| 350 | |
| 351 | print(f"Available meta tools: {[t.name for t in meta_tools]}") |
| 352 | ``` |
| 353 | |
| 354 | Meta tools allow you to: |
| 355 | - Authorize new toolkit connections within a session |
| 356 | - Query toolkit connection states |
| 357 | - Manage session configuration |
| 358 | |
| 359 | This method is useful when you need direct access to the underlying meta tools without creating a full session object. |
| 360 | |
| 361 | ### `authorize(toolkit, *, callback_url=None)` |
| 362 | |
| 363 | Initiate an authorization flow for a toolkit. |
| 364 | |
| 365 | ```python |
| 366 | # Start authorization for Gmail |
| 367 | connection_request = session.authorize('gmail') |
| 368 | |
| 369 | print(connection_request.redirect_url) # URL to redirect user for auth |
| 370 | |
| 371 | # Wait for the user to complete authorization |
| 372 | connected_account = connection_request.wait_for_connection() |
| 373 | print(f"Connected: {connected_account}") |
| 374 | |
| 375 | # With custom callback URL |
| 376 | connection_request = session.authorize( |
| 377 | 'gmail', |
| 378 | callback_url='https://your-app.com/auth/callback' |
| 379 | ) |
| 380 | ``` |
| 381 | |
| 382 | ### `toolkits(...)` |
| 383 | |
| 384 | Query the connection state of toolkits in the session. |
| 385 | |
| 386 | ```python |
| 387 | # Get all toolkits |
| 388 | result = session.toolkits() |
| 389 | |
| 390 | for toolkit in result.items: |
| 391 | print(f"{toolkit.name} ({toolkit.slug})") |
| 392 | if toolkit.connection: |
| 393 | print(f" Connected: {toolkit.connection.is_active}") |
| 394 | if toolkit.connection.connected_account: |
| 395 | print(f" Account ID: {toolkit.connection.connected_account.id}") |
| 396 | print(f" Status: {toolkit.connection.connected_account.status}") |
| 397 | |
| 398 | # With pagination |
| 399 | result = session.toolkits(limit=10, next_cursor='cursor_abc') |
| 400 | |
| 401 | # Filter by specific toolkits |
| 402 | result = session.toolkits(toolkits=['gmail', 'slack']) |
| 403 | |
| 404 | # Filter by connection status |
| 405 | connected_toolkits = session.toolkits(is_connected=True) |
| 406 | disconnected_toolkits = session.toolkits(is_connected=False) |
| 407 | |
| 408 | # Combine all options |
| 409 | result = session.toolkits( |
| 410 | toolkits=['gmail', 'github'], |
| 411 | limit=5, |
| 412 | is_connected=True |
| 413 | ) |
| 414 | ``` |
| 415 | |
| 416 | ## Framework Integrations |
| 417 | |
| 418 | ### OpenAI |
| 419 | |
| 420 | ```python |
| 421 | from openai import OpenAI |
| 422 | from composio import Composio |
| 423 | from composio_openai import OpenAIProvider |
| 424 | |
| 425 | composio = Composio(provider=OpenAIProvider()) |
| 426 | client = OpenAI() |
| 427 | |
| 428 | session = composio.tool_router.create( |
| 429 | user_id='user_123', |
| 430 | toolkits=['gmail'] |
| 431 | ) |
| 432 | |
| 433 | tools = session.tools() |
| 434 | |
| 435 | response = client.chat.completions.create( |
| 436 | model="gpt-4", |
| 437 | messages=[{"role": "user", "content": "Find my last email from gmail"}], |
| 438 | tools=tools, |
| 439 | ) |
| 440 | |
| 441 | print(response.choices[0].message) |
| 442 | ``` |
| 443 | |
| 444 | ### Anthropic |
| 445 | |
| 446 | ```python |
| 447 | from anthropic import Anthropic |
| 448 | from composio import Composio |
| 449 | from composio_anthropic import AnthropicProvider |
| 450 | |
| 451 | composio = Composio(provider=AnthropicProvider()) |
| 452 | client = Anthropic() |
| 453 | |
| 454 | session = composio.tool_router.create( |
| 455 | user_id='user_123', |
| 456 | toolkits=['gmail'] |
| 457 | ) |
| 458 | |
| 459 | tools = session.tools() |
| 460 | |
| 461 | response = client.messages.create( |
| 462 | model="claude-opus-5-5", |
| 463 | max_tokens=1024, |
| 464 | messages=[{"role": "user", "content": "Find my last email from gmail"}], |
| 465 | tools=tools, |
| 466 | ) |
| 467 | |
| 468 | print(response.content) |
| 469 | ``` |
| 470 | |
| 471 | ### LangChain |
| 472 | |
| 473 | ```python |
| 474 | from langchain_openai import ChatOpenAI |
| 475 | from langchain.agents import create_tool_calling_agent, AgentExecutor |
| 476 | from langchain_core.prompts import ChatPromptTemplate |
| 477 | from composio import Composio |
| 478 | from composio_langchain import LangChainProvider |
| 479 | |
| 480 | composio = Composio(provider=LangChainProvider()) |
| 481 | |
| 482 | session = composio.tool_router.create( |
| 483 | user_id='user_123', |
| 484 | toolkits=['gmail'] |
| 485 | ) |
| 486 | |
| 487 | tools = session.tools() |
| 488 | llm = ChatOpenAI(model="gpt-4") |
| 489 | |
| 490 | prompt = ChatPromptTemplate.from_messages([ |
| 491 | ("system", "You are a helpful assistant."), |
| 492 | ("human", "{input}"), |
| 493 | ("placeholder", "{agent_scratchpad}"), |
| 494 | ]) |
| 495 | |
| 496 | agent = create_tool_calling_agent(llm, tools, prompt) |
| 497 | agent_executor = AgentExecutor(agent=agent, tools=tools) |
| 498 | |
| 499 | result = agent_executor.invoke({"input": "Find my last email from gmail"}) |
| 500 | print(result) |
| 501 | ``` |
| 502 | |
| 503 | ### Using MCP URL Directly |
| 504 | |
| 505 | You can also use the MCP URL directly with any MCP-compatible client: |
| 506 | |
| 507 | ```python |
| 508 | from composio import Composio |
| 509 | |
| 510 | composio = Composio() |
| 511 | |
| 512 | session = composio.tool_router.create( |
| 513 | user_id='user_123', |
| 514 | toolkits=['gmail'], |
| 515 | manage_connections=True |
| 516 | ) |
| 517 | |
| 518 | # Use with any MCP client |
| 519 | mcp_url = session.mcp.url |
| 520 | mcp_headers = session.mcp.headers # Pre-configured authentication headers |
| 521 | print(f"MCP URL: {mcp_url}") |
| 522 | print(f"MCP Type: {session.mcp.type}") # 'http' or 'sse' |
| 523 | print(f"MCP Headers: {mcp_headers}") # {'x-api-key': 'your-api-key'} |
| 524 | ``` |
| 525 | |
| 526 | ## Authorization Flow |
| 527 | |
| 528 | When a user needs to connect a toolkit, use the `authorize()` method: |
| 529 | |
| 530 | ```python |
| 531 | from composio import Composio |
| 532 | |
| 533 | composio = Composio() |
| 534 | |
| 535 | session = composio.tool_router.create( |
| 536 | user_id='user_123', |
| 537 | toolkits=['gmail'] |
| 538 | ) |
| 539 | |
| 540 | # Initiate authorization for Gmail |
| 541 | connection_request = session.authorize('gmail') |
| 542 | |
| 543 | # Log the redirect URL for the user |
| 544 | print(f"Redirect URL: {connection_request.redirect_url}") |
| 545 | |
| 546 | # Wait for the user to complete the authorization (with timeout) |
| 547 | connected_account = connection_request.wait_for_connection(timeout=300) |
| 548 | print(f"Connected Account: {connected_account}") |
| 549 | ``` |
| 550 | |
| 551 | You can also provide a custom callback URL: |
| 552 | |
| 553 | ```python |
| 554 | connection_request = session.authorize( |
| 555 | 'gmail', |
| 556 | callback_url='https://your-app.com/auth/callback' |
| 557 | ) |
| 558 | ``` |
| 559 | |
| 560 | ## Querying Toolkit States |
| 561 | |
| 562 | Use the `toolkits()` method to check connection states: |
| 563 | |
| 564 | ```python |
| 565 | from composio import Composio |
| 566 | |
| 567 | composio = Composio() |
| 568 | |
| 569 | session = composio.tool_router.create(user_id='user_123') |
| 570 | |
| 571 | # Get all toolkits |
| 572 | result = session.toolkits() |
| 573 | |
| 574 | for toolkit in result.items: |
| 575 | status = "Connected" if toolkit.connection and toolkit.connection.is_active else "Not connected" |
| 576 | print(f"{toolkit.name}: {status}") |
| 577 | |
| 578 | # Get only connected toolkits |
| 579 | connected = session.toolkits(is_connected=True) |
| 580 | print(f"You have {len(connected.items)} connected toolkits") |
| 581 | |
| 582 | # Get only disconnected toolkits (need authorization) |
| 583 | disconnected = session.toolkits(is_connected=False) |
| 584 | for toolkit in disconnected.items: |
| 585 | print(f"Please connect: {toolkit.name}") |
| 586 | |
| 587 | # Pagination example |
| 588 | result = session.toolkits(limit=10) |
| 589 | all_toolkits = list(result.items) |
| 590 | while result.next_cursor: |
| 591 | result = session.toolkits(limit=10, next_cursor=result.next_cursor) |
| 592 | all_toolkits.extend(result.items) |
| 593 | ``` |
| 594 | |
| 595 | The response structure: |
| 596 | |
| 597 | ```python |
| 598 | { |
| 599 | 'items': [ |
| 600 | { |
| 601 | 'slug': 'gmail', |
| 602 | 'name': 'Gmail', |
| 603 | 'logo': 'https://...', |
| 604 | 'is_no_auth': False, |
| 605 | 'connection': { |
| 606 | 'is_active': True, |
| 607 | 'auth_config': { |
| 608 | 'id': 'ac_xxx', |
| 609 | 'mode': 'OAUTH2', |
| 610 | 'is_composio_managed': True |
| 611 | }, |
| 612 | 'connected_account': { |
| 613 | 'id': 'ca_xxx', |
| 614 | 'status': 'ACTIVE' |
| 615 | } |
| 616 | } |
| 617 | } |
| 618 | ], |
| 619 | 'next_cursor': 'cursor_abc', |
| 620 | 'total_pages': 1 |
| 621 | } |
| 622 | ``` |
| 623 | |
| 624 | ## Best Practices |
| 625 | |
| 626 | 1. **User Isolation**: Create separate sessions per user to ensure proper isolation of connections and tools. |
| 627 | |
| 628 | 2. **Toolkit Selection**: Only enable toolkits that are necessary for the use case to maintain security and reduce complexity. |
| 629 | |
| 630 | 3. **Connection Management**: Use `manage_connections=True` (default) for interactive applications where users can be prompted to connect accounts. |
| 631 | |
| 632 | 4. **Tag Filtering**: Use global `tags` to restrict tools to safe operations (e.g., `['readOnlyHint']`) or toolkit-specific tags in the `tools` configuration for fine-grained control. |
| 633 | |
| 634 | 5. **Session Reuse**: Store and reuse `session_id` to maintain user sessions across requests. |
| 635 | |
| 636 | ```python |
| 637 | import redis |
| 638 | |
| 639 | # Store session ID after creation |
| 640 | session = composio.tool_router.create(user_id='user_123', toolkits=['gmail']) |
| 641 | redis_client.set(f"session:user_123", session.session_id) |
| 642 | |
| 643 | # Retrieve existing session |
| 644 | session_id = redis_client.get(f"session:user_123") |
| 645 | if session_id: |
| 646 | session = composio.tool_router.use(session_id) |
| 647 | ``` |
| 648 | |
| 649 | ## Type Reference |
| 650 | |
| 651 | ### ToolRouterSession |
| 652 | |
| 653 | ```python |
| 654 | @dataclass |
| 655 | class ToolRouterSession: |
| 656 | session_id: str |
| 657 | mcp: ToolRouterMCPServerConfig |
| 658 | tools: Callable[[Optional[Modifiers]], Any] |
| 659 | authorize: Callable[..., ConnectionRequest] |
| 660 | toolkits: Callable[..., ToolkitConnectionsDetails] |
| 661 | ``` |
| 662 | |
| 663 | ### ToolRouterMCPServerConfig |
| 664 | |
| 665 | ```python |
| 666 | class ToolRouterMCPServerType(str, Enum): |
| 667 | HTTP = "http" |
| 668 | SSE = "sse" |
| 669 | |
| 670 | @dataclass |
| 671 | class ToolRouterMCPServerConfig: |
| 672 | type: ToolRouterMCPServerType |
| 673 | url: str |
| 674 | headers: Optional[Dict[str, Optional[str]]] = None # Authentication headers (includes x-api-key) |
| 675 | ``` |
| 676 | |
| 677 | ### ToolkitConnectionState |
| 678 | |
| 679 | ```python |
| 680 | @dataclass |
| 681 | class ToolkitConnectionState: |
| 682 | slug: str |
| 683 | name: str |
| 684 | is_no_auth: bool |
| 685 | connection: Optional[ToolkitConnection] = None |
| 686 | logo: Optional[str] = None |
| 687 | |
| 688 | @dataclass |
| 689 | class ToolkitConnection: |
| 690 | is_active: bool |
| 691 | auth_config: Optional[ToolkitConnectionAuthConfig] = None |
| 692 | connected_account: Optional[ToolkitConnectedAccount] = None |
| 693 | |
| 694 | @dataclass |
| 695 | class ToolkitConnectionAuthConfig: |
| 696 | id: str |
| 697 | mode: str |
| 698 | is_composio_managed: bool |
| 699 | |
| 700 | @dataclass |
| 701 | class ToolkitConnectedAccount: |
| 702 | id: str |
| 703 | status: str |
| 704 | ``` |
| 705 | |
| 706 | ### ToolkitConnectionsDetails |
| 707 | |
| 708 | ```python |
| 709 | @dataclass |
| 710 | class ToolkitConnectionsDetails: |
| 711 | items: List[ToolkitConnectionState] |
| 712 | total_pages: int |
| 713 | next_cursor: Optional[str] = None |
| 714 | ``` |
| 715 | |
| 716 | ### Configuration Types |
| 717 | |
| 718 | ```python |
| 719 | from typing import List, Dict, Union, Literal |
| 720 | from typing_extensions import TypedDict |
| 721 | |
| 722 | # Toolkits configuration |
| 723 | ToolRouterToolkitsEnableConfig = TypedDict('ToolRouterToolkitsEnableConfig', { |
| 724 | 'enable': List[str] |
| 725 | }) |
| 726 | |
| 727 | ToolRouterToolkitsDisableConfig = TypedDict('ToolRouterToolkitsDisableConfig', { |
| 728 | 'disable': List[str] |
| 729 | }) |
| 730 | |
| 731 | toolkits: Union[ |
| 732 | List[str], # ['gmail', 'slack'] |
| 733 | ToolRouterToolkitsEnableConfig, # {'enable': ['gmail', 'slack']} |
| 734 | ToolRouterToolkitsDisableConfig # {'disable': ['calendar']} |
| 735 | ] |
| 736 | |
| 737 | # Tools configuration |
| 738 | ToolRouterToolsEnableConfig = TypedDict('ToolRouterToolsEnableConfig', { |
| 739 | 'enable': List[str] |
| 740 | }) |
| 741 | |
| 742 | ToolRouterToolsDisableConfig = TypedDict('ToolRouterToolsDisableConfig', { |
| 743 | 'disable': List[str] |
| 744 | }) |
| 745 | |
| 746 | ToolRouterToolsTagsConfig = TypedDict('ToolRouterToolsTagsConfig', { |
| 747 | 'tags': List[Literal['readOnlyHint', 'destructiveHint', 'createHint', 'updateHint']] |
| 748 | }) |
| 749 | |
| 750 | ToolRouterToolsConfig = Union[ |
| 751 | List[str], # ['GMAIL_SEND_EMAIL', 'GMAIL_FETCH_EMAILS'] |
| 752 | ToolRouterToolsEnableConfig, # {'enable': ['GMAIL_SEND_EMAIL']} |
| 753 | ToolRouterToolsDisableConfig, # {'disable': ['GMAIL_DELETE_EMAIL']} |
| 754 | ToolRouterToolsTagsConfig # {'tags': ['readOnlyHint']} |
| 755 | ] |
| 756 | |
| 757 | tools: Dict[str, ToolRouterToolsConfig] # Key is toolkit slug, value is ToolRouterToolsConfig |
| 758 | |
| 759 | # Tags configuration (global) |
| 760 | tags: List[Literal['readOnlyHint', 'destructiveHint', 'createHint', 'updateHint']] |
| 761 | |
| 762 | # Manage connections configuration |
| 763 | ToolRouterManageConnectionsConfig = TypedDict('ToolRouterManageConnectionsConfig', { |
| 764 | 'enable': bool, |
| 765 | 'callback_url': str, # Optional |
| 766 | 'wait_for_connections': bool # NEW in v0.10.5: Wait for connections to complete |
| 767 | }) |
| 768 | |
| 769 | manage_connections: Union[ |
| 770 | bool, |
| 771 | ToolRouterManageConnectionsConfig # {'enable': True, 'callback_url': 'https://...', 'wait_for_connections': True} |
| 772 | ] |
| 773 | |
| 774 | # Workbench configuration |
| 775 | ToolRouterWorkbenchConfig = TypedDict('ToolRouterWorkbenchConfig', { |
| 776 | 'enable': bool, # Enable/disable workbench entirely (default: True) |
| 777 | 'enable_proxy_execution': bool, # Whether to allow proxy execute calls |
| 778 | 'auto_offload_threshold': int # Character threshold for auto-offloading execution to workbench |
| 779 | }) |
| 780 | |
| 781 | workbench: ToolRouterWorkbenchConfig |
| 782 | ``` |
| 783 | |
| 784 | ## What's New in v0.10.5 |
| 785 | |
| 786 | ### 1. Wait for Connections |
| 787 | |
| 788 | The new `wait_for_connections` property allows sessions to wait for users to complete authentication before proceeding: |
| 789 | |
| 790 | ```python |
| 791 | session = composio.tool_router.create( |
| 792 | user_id='user_123', |
| 793 | toolkits=['gmail', 'slack'], |
| 794 | manage_connections={ |
| 795 | 'enable': True, |
| 796 | 'callback_url': 'https://your-app.com/callback', |
| 797 | 'wait_for_connections': True # NEW |
| 798 | } |
| 799 | ) |
| 800 | ``` |
| 801 | |
| 802 | ### 2. Enhanced Session Modifiers |
| 803 | |
| 804 | Session-specific modifiers now include session context, making it easier to track and manage tool execution: |
| 805 | |
| 806 | ```python |
| 807 | from composio.core.models import before_execute_meta, after_execute_meta |
| 808 | |
| 809 | @before_execute_meta |
| 810 | def before_modifier(tool, toolkit, session_id, params): |
| 811 | print(f"[{session_id}] Executing {tool}") |
| 812 | return params |
| 813 | |
| 814 | @after_execute_meta |
| 815 | def after_modifier(tool, toolkit, session_id, response): |
| 816 | print(f"[{session_id}] Completed {tool}") |
| 817 | return response |
| 818 | |
| 819 | tools = session.tools(modifiers=[before_modifier, after_modifier]) |
| 820 | ``` |
| 821 | |
| 822 | ### 3. Direct Meta Tools Access |
| 823 | |
| 824 | New method to fetch meta tools directly from a session: |
| 825 | |
| 826 | ```python |
| 827 | from composio.core.models import modify_schema_meta |
| 828 | |
| 829 | @modify_schema_meta |
| 830 | def schema_modifier(tool, toolkit, schema): |
| 831 | return schema |
| 832 | |
| 833 | meta_tools = composio.tools.get_raw_tool_router_meta_tools( |
| 834 | session_id='session_123', |
| 835 | modifiers=[schema_modifier] |
| 836 | ) |
| 837 | ``` |
| 838 | |
| 839 | ### 4. Performance Improvements |
| 840 | |
| 841 | - Optimized tool fetching with fewer API calls |
| 842 | - Improved session API architecture for better reliability |
| 843 | - Simplified internal tool execution paths |
| 844 | |
| 845 | All changes in v0.10.5 are fully backward compatible with existing code. |
| 846 |