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 (Vercel AI SDK, LangChain, OpenAI Agents, Claude Agents SDK) |
| 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 | ## Quick Start |
| 18 | |
| 19 | ### Using MCP (Recommended) |
| 20 | |
| 21 | When using Tool Router with MCP clients, you don't need to pass a provider: |
| 22 | |
| 23 | ## Installation |
| 24 | |
| 25 | ```bash |
| 26 | # npm |
| 27 | npm install @composio/core@0.4.0 |
| 28 | |
| 29 | # pnpm |
| 30 | pnpm add @composio/core@0.4.0 |
| 31 | |
| 32 | # yarn |
| 33 | yarn add @composio/core@0.4.0 |
| 34 | ``` |
| 35 | |
| 36 | ```typescript |
| 37 | import { Composio } from '@composio/core'; |
| 38 | |
| 39 | const composio = new Composio(); |
| 40 | |
| 41 | // Create a session for a user with access to Gmail tools |
| 42 | const session = await composio.create('user_123', { |
| 43 | toolkits: ['gmail'], |
| 44 | }); |
| 45 | |
| 46 | // Use the MCP URL with any MCP-compatible client |
| 47 | console.log(session.mcp.url); |
| 48 | ``` |
| 49 | |
| 50 | ### Using Framework-Specific Tools |
| 51 | |
| 52 | If you want to use `session.tools()` to get tools formatted for a specific AI framework, pass the appropriate provider: |
| 53 | |
| 54 | ```typescript |
| 55 | import { Composio } from '@composio/core'; |
| 56 | import { VercelProvider } from '@composio/vercel'; |
| 57 | |
| 58 | const composio = new Composio({ |
| 59 | provider: new VercelProvider(), |
| 60 | }); |
| 61 | |
| 62 | // Create a session for a user with access to Gmail tools |
| 63 | const session = await composio.create('user_123', { |
| 64 | toolkits: ['gmail'], |
| 65 | }); |
| 66 | |
| 67 | // Get the tools formatted for Vercel AI SDK |
| 68 | const tools = await session.tools(); |
| 69 | ``` |
| 70 | |
| 71 | ## Creating Sessions |
| 72 | |
| 73 | ### Basic Session Creation |
| 74 | |
| 75 | Use `composio.create()` to create a new Tool Router session: |
| 76 | |
| 77 | ```typescript |
| 78 | import { Composio } from '@composio/core'; |
| 79 | |
| 80 | const composio = new Composio(); |
| 81 | |
| 82 | // Create a session with Gmail access |
| 83 | const session = await composio.create('user_123', { |
| 84 | toolkits: ['gmail'], |
| 85 | }); |
| 86 | |
| 87 | console.log('Session ID:', session.sessionId); |
| 88 | console.log('MCP URL:', session.mcp.url); |
| 89 | ``` |
| 90 | |
| 91 | ### Using an Existing Session |
| 92 | |
| 93 | If you have an existing session ID, you can retrieve it using `composio.use()`: |
| 94 | |
| 95 | ```typescript |
| 96 | const session = await composio.use('existing_session_id'); |
| 97 | |
| 98 | // Access session properties |
| 99 | console.log(session.sessionId); |
| 100 | console.log(session.mcp.url); |
| 101 | ``` |
| 102 | |
| 103 | ## Configuration Options |
| 104 | |
| 105 | The session creation accepts a configuration object with the following options: |
| 106 | |
| 107 | ### `toolkits` |
| 108 | |
| 109 | Specify which toolkits to enable or disable in the session. |
| 110 | |
| 111 | ```typescript |
| 112 | // Simple array of toolkit slugs to enable |
| 113 | const session = await composio.create('user_123', { |
| 114 | toolkits: ['gmail', 'slack', 'github'], |
| 115 | }); |
| 116 | |
| 117 | // Explicit enabled configuration |
| 118 | const session = await composio.create('user_123', { |
| 119 | toolkits: { enable: ['gmail', 'slack'] }, |
| 120 | }); |
| 121 | |
| 122 | // Disable specific toolkits (enable all others) |
| 123 | const session = await composio.create('user_123', { |
| 124 | toolkits: { disable: ['calendar'] }, |
| 125 | }); |
| 126 | ``` |
| 127 | |
| 128 | ### `tools` |
| 129 | |
| 130 | Fine-grained control over which tools are available within toolkits. Configure tools per toolkit using the toolkit slug as the key. |
| 131 | |
| 132 | ```typescript |
| 133 | const session = await composio.create('user_123', { |
| 134 | toolkits: ['gmail', 'slack'], |
| 135 | tools: { |
| 136 | // Configure tools per toolkit |
| 137 | gmail: ['gmail_fetch_emails', 'gmail_send_email'], // Only these tools |
| 138 | // OR use enable/disable objects |
| 139 | // gmail: { enable: ['gmail_fetch_emails'] } |
| 140 | // gmail: { disable: ['gmail_delete_email'] } |
| 141 | |
| 142 | // You can also set tags per toolkit to override global tags |
| 143 | slack: { tags: ['readOnlyHint'] }, |
| 144 | }, |
| 145 | }); |
| 146 | ``` |
| 147 | |
| 148 | ### `tags` |
| 149 | |
| 150 | Global tags to filter tools by their behavior hints. Tags can be overridden per toolkit in the `tools` configuration. |
| 151 | |
| 152 | ```typescript |
| 153 | const session = await composio.create('user_123', { |
| 154 | toolkits: ['gmail', 'github'], |
| 155 | // Global tags applied to all toolkits |
| 156 | tags: ['readOnlyHint', 'createHint'], |
| 157 | }); |
| 158 | ``` |
| 159 | |
| 160 | Every tool has a tag for the type of action it takes: |
| 161 | |
| 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 | ### `authConfigs` |
| 170 | |
| 171 | Map toolkits to specific authentication configurations: |
| 172 | |
| 173 | ```typescript |
| 174 | const session = await composio.create('user_123', { |
| 175 | toolkits: ['gmail', 'github'], |
| 176 | authConfigs: { |
| 177 | gmail: 'ac_gmail_work', |
| 178 | github: 'ac_github_personal', |
| 179 | }, |
| 180 | }); |
| 181 | ``` |
| 182 | |
| 183 | ### `connectedAccounts` |
| 184 | |
| 185 | Map toolkits to specific connected account IDs: |
| 186 | |
| 187 | ```typescript |
| 188 | const session = await composio.create('user_123', { |
| 189 | toolkits: ['gmail'], |
| 190 | connectedAccounts: { |
| 191 | gmail: 'ca_abc123', |
| 192 | }, |
| 193 | }); |
| 194 | ``` |
| 195 | |
| 196 | ### `manageConnections` |
| 197 | |
| 198 | Control how connections are managed within the session: |
| 199 | |
| 200 | ```typescript |
| 201 | // Boolean: enable/disable automatic connection management |
| 202 | const session = await composio.create('user_123', { |
| 203 | toolkits: ['gmail'], |
| 204 | manageConnections: true, // default |
| 205 | }); |
| 206 | |
| 207 | // Object: fine-grained control |
| 208 | const session = await composio.create('user_123', { |
| 209 | toolkits: ['gmail'], |
| 210 | manageConnections: { |
| 211 | enable: true, |
| 212 | callbackUrl: 'https://your-app.com/auth/callback', |
| 213 | waitForConnections: true, // Wait for user to complete authentication before proceeding |
| 214 | }, |
| 215 | }); |
| 216 | ``` |
| 217 | |
| 218 | #### Wait for Connections |
| 219 | |
| 220 | 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. |
| 221 | |
| 222 | ```typescript |
| 223 | const session = await composio.create('user_123', { |
| 224 | toolkits: ['gmail', 'slack'], |
| 225 | manageConnections: { |
| 226 | enable: true, |
| 227 | callbackUrl: 'https://your-app.com/auth/callback', |
| 228 | waitForConnections: true, // Session waits for connections to complete |
| 229 | }, |
| 230 | }); |
| 231 | ``` |
| 232 | |
| 233 | ### `workbench` |
| 234 | |
| 235 | Configure workbench behavior for tool execution: |
| 236 | |
| 237 | ```typescript |
| 238 | // Disable workbench entirely — no code execution tools in the session |
| 239 | const session = await composio.create('user_123', { |
| 240 | toolkits: ['gmail'], |
| 241 | workbench: { |
| 242 | enable: false |
| 243 | } |
| 244 | }); |
| 245 | |
| 246 | // Fine-tune workbench settings |
| 247 | const session2 = await composio.create('user_123', { |
| 248 | toolkits: ['gmail'], |
| 249 | workbench: { |
| 250 | enable: true, // default |
| 251 | enableProxyExecution: true, |
| 252 | autoOffloadThreshold: 400000, // Automatically offload to workbench if response > 400k characters |
| 253 | }, |
| 254 | }); |
| 255 | ``` |
| 256 | |
| 257 | | Field | Type | Default | Description | |
| 258 | |-------|------|---------|-------------| |
| 259 | | `enable` | `boolean` | `true` | Enables/disables the workbench entirely. When `false`, `COMPOSIO_REMOTE_WORKBENCH` and `COMPOSIO_REMOTE_BASH_TOOL` are excluded from the session. | |
| 260 | | `enableProxyExecution` | `boolean` | `true` | Controls proxy API execution in the workbench. | |
| 261 | | `autoOffloadThreshold` | `number` | auto | Character threshold for auto-offloading large responses to the workbench. | |
| 262 | |
| 263 | ### `experimental` |
| 264 | |
| 265 | Configure experimental features for the session. These features are not stable and may be modified or removed in future versions. |
| 266 | |
| 267 | #### Assistive Prompt |
| 268 | |
| 269 | ```typescript |
| 270 | const session = await composio.create('user_123', { |
| 271 | toolkits: ['gmail'], |
| 272 | experimental: { |
| 273 | assistivePrompt: { |
| 274 | userTimezone: 'America/New_York', // IANA timezone identifier for timezone-aware assistive prompts |
| 275 | }, |
| 276 | }, |
| 277 | }); |
| 278 | |
| 279 | // Access the generated assistive prompt from the session response |
| 280 | if (session.experimental?.assistivePrompt) { |
| 281 | console.log('Assistive prompt:', session.experimental.assistivePrompt); |
| 282 | } |
| 283 | ``` |
| 284 | |
| 285 | The `userTimezone` field accepts an IANA timezone identifier (e.g., 'America/New_York', 'Europe/London') which is used to generate a timezone-aware system prompt for optimal tool router usage. |
| 286 | |
| 287 | #### Custom Tools & Custom Toolkits |
| 288 | |
| 289 | Define your own tools that run in-process alongside Composio's remote tools. Custom tools are automatically indexed for search and routed to your `execute` function when called. |
| 290 | |
| 291 | There are three ways to define custom tools: |
| 292 | |
| 293 | **1. Standalone tool** — no auth needed, passed in `localTools`: |
| 294 | |
| 295 | ```typescript |
| 296 | import { experimental_createTool } from '@composio/core'; |
| 297 | import { z } from 'zod/v3'; |
| 298 | |
| 299 | const grep = experimental_createTool('GREP', { |
| 300 | name: 'Grep Search', |
| 301 | description: 'Search for patterns in files', |
| 302 | inputParams: z.object({ pattern: z.string(), path: z.string() }), |
| 303 | execute: async input => ({ matches: [] }), |
| 304 | }); |
| 305 | ``` |
| 306 | |
| 307 | **2. Extension tool** — extends a Composio toolkit, inherits its auth. Passed in `localTools` with `extendsToolkit`: |
| 308 | |
| 309 | ```typescript |
| 310 | const getImportant = experimental_createTool('GET_IMPORTANT_EMAILS', { |
| 311 | name: 'Get Important Emails', |
| 312 | description: 'Fetch high-priority emails', |
| 313 | extendsToolkit: 'gmail', |
| 314 | inputParams: z.object({ limit: z.number().default(10) }), |
| 315 | execute: async (input, ctx) => { |
| 316 | // Same response shape as session.execute(): { data, error, logId } |
| 317 | const result = await ctx.execute('GMAIL_SEARCH', { query: 'is:important' }); |
| 318 | return { emails: result.data }; |
| 319 | }, |
| 320 | }); |
| 321 | ``` |
| 322 | |
| 323 | **3. Custom toolkit** — groups related no-auth tools. Passed in `localToolkits`: |
| 324 | |
| 325 | ```typescript |
| 326 | import { experimental_createToolkit } from '@composio/core'; |
| 327 | |
| 328 | const sed = experimental_createTool('SED', { |
| 329 | name: 'Sed Replace', |
| 330 | description: 'Find and replace in files', |
| 331 | inputParams: z.object({ pattern: z.string(), replacement: z.string() }), |
| 332 | execute: async input => ({ replaced: 0 }), |
| 333 | }); |
| 334 | |
| 335 | const devTools = experimental_createToolkit('DEV_TOOLS', { |
| 336 | name: 'Dev Tools', |
| 337 | description: 'Local dev utilities', |
| 338 | tools: [sed], |
| 339 | }); |
| 340 | ``` |
| 341 | |
| 342 | **Creating a session with custom tools:** |
| 343 | |
| 344 | ```typescript |
| 345 | const session = await composio.create('user_123', { |
| 346 | toolkits: ['gmail'], |
| 347 | experimental: { |
| 348 | localTools: [grep, getImportant], |
| 349 | localToolkits: [devTools], |
| 350 | }, |
| 351 | }); |
| 352 | ``` |
| 353 | |
| 354 | **Executing custom tools** — use the same slug you defined: |
| 355 | |
| 356 | ```typescript |
| 357 | // Standalone tool |
| 358 | await session.execute('GREP', { pattern: 'TODO', path: '/src' }); |
| 359 | |
| 360 | // Extension tool |
| 361 | await session.execute('GET_IMPORTANT_EMAILS', { limit: 5 }); |
| 362 | |
| 363 | // Toolkit tool |
| 364 | await session.execute('SED', { pattern: 'foo', replacement: 'bar' }); |
| 365 | ``` |
| 366 | |
| 367 | Custom tools are searched alongside Composio tools. When the LLM calls a custom tool, the SDK executes it in-process — remote tools in the same batch are sent to the backend in parallel. |
| 368 | |
| 369 | ## Session Properties |
| 370 | |
| 371 | A Tool Router session provides the following properties and methods: |
| 372 | |
| 373 | ### `sessionId` |
| 374 | |
| 375 | The unique identifier for this session. |
| 376 | |
| 377 | ```typescript |
| 378 | console.log(session.sessionId); |
| 379 | ``` |
| 380 | |
| 381 | ### `mcp` |
| 382 | |
| 383 | The MCP server configuration for this session, including authentication headers. |
| 384 | |
| 385 | ```typescript |
| 386 | console.log(session.mcp.url); // The URL to connect to |
| 387 | console.log(session.mcp.type); // 'http' or 'sse' |
| 388 | console.log(session.mcp.headers); // Authentication headers (includes x-api-key if configured) |
| 389 | ``` |
| 390 | |
| 391 | ### `tools()` |
| 392 | |
| 393 | Retrieve the tools available in the session, formatted for your AI framework. |
| 394 | |
| 395 | ```typescript |
| 396 | const tools = await session.tools(); |
| 397 | |
| 398 | // With session-specific modifiers (new in v0.4.0) |
| 399 | const tools = await session.tools({ |
| 400 | modifySchema: ({ toolSlug, toolkitSlug, schema }) => { |
| 401 | // Customize the tool schema |
| 402 | return schema; |
| 403 | }, |
| 404 | beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => { |
| 405 | console.log(`Executing ${toolSlug} in session ${sessionId}`); |
| 406 | return params; |
| 407 | }, |
| 408 | afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => { |
| 409 | console.log(`Completed ${toolSlug} in session ${sessionId}`); |
| 410 | return result; |
| 411 | }, |
| 412 | }); |
| 413 | ``` |
| 414 | |
| 415 | #### Session-Specific Modifiers |
| 416 | |
| 417 | Tool Router sessions now support enhanced modifier types (introduced in v0.4.0) that include session context: |
| 418 | |
| 419 | - **`modifySchema`**: Customize tool schemas before they're sent to the AI model |
| 420 | - **`beforeExecute`**: Modify parameters before execution, with access to session ID |
| 421 | - **`afterExecute`**: Transform results after execution, with access to session ID |
| 422 | |
| 423 | These modifiers provide better context for session-based tool execution, allowing you to track which session is executing which tools. |
| 424 | |
| 425 | ### Meta Tools |
| 426 | |
| 427 | 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): |
| 428 | |
| 429 | ```typescript |
| 430 | import { Composio } from '@composio/core'; |
| 431 | |
| 432 | const composio = new Composio(); |
| 433 | |
| 434 | // Get raw meta tools for a session |
| 435 | const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123', { |
| 436 | modifySchema: ({ toolSlug, toolkitSlug, schema }) => { |
| 437 | // Customize meta tool schemas |
| 438 | console.log(`Modifying schema for ${toolSlug}`); |
| 439 | return schema; |
| 440 | }, |
| 441 | }); |
| 442 | |
| 443 | console.log( |
| 444 | 'Available meta tools:', |
| 445 | metaTools.map(t => t.name) |
| 446 | ); |
| 447 | ``` |
| 448 | |
| 449 | Meta tools allow you to: |
| 450 | |
| 451 | - Authorize new toolkit connections within a session |
| 452 | - Query toolkit connection states |
| 453 | - Manage session configuration |
| 454 | |
| 455 | This method is useful when you need direct access to the underlying meta tools without creating a full session object. |
| 456 | |
| 457 | ### `execute()` |
| 458 | |
| 459 | Execute a tool within the session. Custom tools run in-process; remote tools are sent to the Composio backend. Works with any tool — custom or remote — using the same API. |
| 460 | |
| 461 | ```typescript |
| 462 | // Custom tool |
| 463 | const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' }); |
| 464 | console.log(result.data); // { preferences: { ... } } |
| 465 | console.log(result.error); // null on success |
| 466 | |
| 467 | // Remote Composio tool — same API |
| 468 | const weather = await session.execute('WEATHERMAP_WEATHER', { location: 'Tokyo' }); |
| 469 | ``` |
| 470 | |
| 471 | ### `search()` |
| 472 | |
| 473 | Search for tools by semantic use case. Returns relevant tools with schemas and guidance. |
| 474 | |
| 475 | ```typescript |
| 476 | const results = await session.search({ query: 'send an email via gmail' }); |
| 477 | |
| 478 | for (const result of results.results) { |
| 479 | console.log(result.useCase); |
| 480 | console.log(result.primaryToolSlugs); // e.g. ['GMAIL_SEND_EMAIL'] |
| 481 | } |
| 482 | ``` |
| 483 | |
| 484 | ### `proxyExecute()` |
| 485 | |
| 486 | Proxy an API call through Composio's auth layer using the session's connected account. The backend resolves the connected account from the toolkit within the session. |
| 487 | |
| 488 | `ctx.proxyExecute()` inside a custom tool returns the same response shape as `session.proxyExecute()`. |
| 489 | |
| 490 | ```typescript |
| 491 | const result = await session.proxyExecute({ |
| 492 | toolkit: 'github', |
| 493 | endpoint: 'https://api.github.com/user', |
| 494 | method: 'GET', |
| 495 | parameters: [{ in: 'header', name: 'X-Custom', value: 'value' }], |
| 496 | }); |
| 497 | ``` |
| 498 | |
| 499 | ### `authorize()` |
| 500 | |
| 501 | Initiate an authorization flow for a toolkit. |
| 502 | |
| 503 | ```typescript |
| 504 | // Start authorization for Gmail |
| 505 | const connectionRequest = await session.authorize('gmail'); |
| 506 | |
| 507 | console.log(connectionRequest.redirectUrl); // URL to redirect user for auth |
| 508 | |
| 509 | // Wait for the user to complete authorization |
| 510 | const connectedAccount = await connectionRequest.waitForConnection(); |
| 511 | console.log('Connected:', connectedAccount); |
| 512 | ``` |
| 513 | |
| 514 | ### `toolkits()` |
| 515 | |
| 516 | Query the connection state of toolkits in the session. |
| 517 | |
| 518 | ```typescript |
| 519 | const { items, cursor, totalPages } = await session.toolkits(); |
| 520 | |
| 521 | for (const toolkit of items) { |
| 522 | console.log(`${toolkit.name} (${toolkit.slug})`); |
| 523 | console.log(` Connected: ${toolkit.connection?.isActive}`); |
| 524 | if (toolkit.connection?.connectedAccount) { |
| 525 | console.log(` Account ID: ${toolkit.connection.connectedAccount.id}`); |
| 526 | console.log(` Status: ${toolkit.connection.connectedAccount.status}`); |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | // Pagination support |
| 531 | const moreToolkits = await session.toolkits({ |
| 532 | cursor, |
| 533 | limit: 10, |
| 534 | }); |
| 535 | |
| 536 | // Filter by specific toolkits |
| 537 | const filteredToolkits = await session.toolkits({ |
| 538 | toolkits: ['gmail', 'slack'], |
| 539 | }); |
| 540 | |
| 541 | // Combine filtering with pagination |
| 542 | const paginatedFilteredToolkits = await session.toolkits({ |
| 543 | toolkits: ['gmail', 'github'], |
| 544 | limit: 5, |
| 545 | cursor: 'cursor_abc', |
| 546 | }); |
| 547 | ``` |
| 548 | |
| 549 | ### `files` |
| 550 | |
| 551 | Each session has a virtual filesystem mount for storing and retrieving files. Use `session.experimental.files` to list, upload, download, and delete files. This is useful for agent workflows, document processing, and tools that need file access. |
| 552 | |
| 553 | ```typescript |
| 554 | // Upload a file (from path, URL, File, or buffer) |
| 555 | const file = await session.experimental.files.upload('/path/to/report.pdf'); |
| 556 | const file = await session.experimental.files.upload(buffer, { remotePath: 'data.json' }); |
| 557 | |
| 558 | // List files with pagination |
| 559 | const { items, nextCursor } = await session.experimental.files.list({ path: '/' }); |
| 560 | |
| 561 | // Download a file |
| 562 | const remoteFile = await session.experimental.files.download('report.pdf'); |
| 563 | const buffer = await remoteFile.buffer(); |
| 564 | await remoteFile.save('/tmp/report.pdf'); |
| 565 | |
| 566 | // Delete a file |
| 567 | await session.experimental.files.delete('/temp/cache.json'); |
| 568 | ``` |
| 569 | |
| 570 | See [Tool Router Session Files](./tool-router-files.md) for full documentation, including upload input types (paths, URLs, `File`, buffers), mimetype detection, pagination, and the `RemoteFile` API. |
| 571 | |
| 572 | ## Framework Integrations |
| 573 | |
| 574 | ### Vercel AI SDK (with Provider) |
| 575 | |
| 576 | When using the `session.tools()` method, you need to pass a provider to get framework-specific tools: |
| 577 | |
| 578 | ```typescript |
| 579 | import { openai } from '@ai-sdk/openai'; |
| 580 | import { Composio } from '@composio/core'; |
| 581 | import { VercelProvider } from '@composio/vercel'; |
| 582 | import { stepCountIs, streamText } from 'ai'; |
| 583 | |
| 584 | const composio = new Composio({ |
| 585 | provider: new VercelProvider(), |
| 586 | }); |
| 587 | |
| 588 | const session = await composio.create('user_123', { |
| 589 | toolkits: ['gmail'], |
| 590 | }); |
| 591 | |
| 592 | const tools = await session.tools(); |
| 593 | |
| 594 | const stream = await streamText({ |
| 595 | model: openai('gpt-4o-mini'), |
| 596 | prompt: 'Find my last email from gmail?', |
| 597 | stopWhen: stepCountIs(10), |
| 598 | tools, |
| 599 | }); |
| 600 | |
| 601 | for await (const textPart of stream.textStream) { |
| 602 | process.stdout.write(textPart); |
| 603 | } |
| 604 | ``` |
| 605 | |
| 606 | ### Vercel AI SDK (with MCP Client) |
| 607 | |
| 608 | When using MCP clients, no provider is needed. The MCP client fetches tools directly from the MCP server URL: |
| 609 | |
| 610 | ```typescript |
| 611 | import { openai } from '@ai-sdk/openai'; |
| 612 | import { experimental_createMCPClient as createMCPClient } from '@ai-sdk/mcp'; |
| 613 | import { Composio } from '@composio/core'; |
| 614 | import { stepCountIs, streamText } from 'ai'; |
| 615 | |
| 616 | // No provider needed when using MCP |
| 617 | const composio = new Composio(); |
| 618 | const { mcp } = await composio.create('user_123', { |
| 619 | toolkits: ['gmail'], |
| 620 | manageConnections: true, |
| 621 | tools: { |
| 622 | gmail: { |
| 623 | disable: ['gmail_send_email'], // Disable specific tools |
| 624 | }, |
| 625 | }, |
| 626 | }); |
| 627 | |
| 628 | // Create MCP client using the session URL and headers |
| 629 | const client = await createMCPClient({ |
| 630 | transport: { |
| 631 | type: 'http', |
| 632 | url: mcp.url, |
| 633 | headers: mcp.headers, // Uses pre-configured authentication headers |
| 634 | }, |
| 635 | }); |
| 636 | |
| 637 | const tools = await client.tools(); |
| 638 | |
| 639 | const stream = await streamText({ |
| 640 | model: openai('gpt-4o-mini'), |
| 641 | prompt: 'Find my last email from gmail?', |
| 642 | stopWhen: stepCountIs(10), |
| 643 | onStepFinish: step => { |
| 644 | if (step.toolCalls.length > 0) { |
| 645 | for (const toolCall of step.toolCalls) { |
| 646 | console.log(`Executed ${toolCall.toolName}`); |
| 647 | } |
| 648 | } |
| 649 | }, |
| 650 | tools, |
| 651 | }); |
| 652 | |
| 653 | for await (const textPart of stream.textStream) { |
| 654 | process.stdout.write(textPart); |
| 655 | } |
| 656 | ``` |
| 657 | |
| 658 | ### LangChain |
| 659 | |
| 660 | LangChain can connect to Tool Router via MCP adapters. No provider is needed: |
| 661 | |
| 662 | ```typescript |
| 663 | import { MultiServerMCPClient } from '@langchain/mcp-adapters'; |
| 664 | import { ChatOpenAI } from '@langchain/openai'; |
| 665 | import { createAgent } from 'langchain'; |
| 666 | import { Composio } from '@composio/core'; |
| 667 | |
| 668 | // No provider needed when using MCP |
| 669 | const composio = new Composio(); |
| 670 | |
| 671 | const llm = new ChatOpenAI({ |
| 672 | model: 'gpt-4o', |
| 673 | }); |
| 674 | |
| 675 | const session = await composio.create('user_123', { |
| 676 | toolkits: ['gmail'], |
| 677 | }); |
| 678 | |
| 679 | const client = new MultiServerMCPClient({ |
| 680 | composio: { |
| 681 | transport: 'http', |
| 682 | url: session.mcp.url, |
| 683 | headers: session.mcp.headers, // Uses pre-configured authentication headers |
| 684 | }, |
| 685 | }); |
| 686 | |
| 687 | const tools = await client.getTools(); |
| 688 | |
| 689 | const agent = createAgent({ |
| 690 | name: 'Gmail Assistant', |
| 691 | systemPrompt: 'You are a helpful gmail assistant.', |
| 692 | model: llm, |
| 693 | tools, |
| 694 | }); |
| 695 | |
| 696 | const result = await agent.invoke({ |
| 697 | messages: [{ role: 'user', content: 'Fetch my last email from gmail' }], |
| 698 | }); |
| 699 | |
| 700 | console.log(result); |
| 701 | ``` |
| 702 | |
| 703 | ### OpenAI Agents SDK |
| 704 | |
| 705 | OpenAI Agents SDK supports hosted MCP tools. No provider is needed: |
| 706 | |
| 707 | ```typescript |
| 708 | import { Agent, run, hostedMcpTool } from '@openai/agents'; |
| 709 | import { Composio } from '@composio/core'; |
| 710 | |
| 711 | // No provider needed when using MCP |
| 712 | const composio = new Composio(); |
| 713 | |
| 714 | const session = await composio.create('user_123', { |
| 715 | toolkits: ['gmail'], |
| 716 | }); |
| 717 | |
| 718 | console.log(`Tool Router Session Created: ${session.sessionId}`); |
| 719 | console.log(`Connecting to MCP server: ${session.mcp.url}`); |
| 720 | |
| 721 | const mcpTool = hostedMcpTool({ |
| 722 | serverLabel: 'ComposioApps', |
| 723 | serverUrl: session.mcp.url, |
| 724 | headers: session.mcp.headers, // Uses pre-configured authentication headers |
| 725 | }); |
| 726 | |
| 727 | const agent = new Agent({ |
| 728 | name: 'Gmail Assistant', |
| 729 | instructions: 'You are a helpful gmail assistant.', |
| 730 | tools: [mcpTool], |
| 731 | }); |
| 732 | |
| 733 | const result = await run(agent, 'Summarize my last email from gmail', { |
| 734 | stream: true, |
| 735 | }); |
| 736 | |
| 737 | const stream = result.toStream(); |
| 738 | |
| 739 | for await (const event of stream) { |
| 740 | if (event.type === 'raw_model_stream_event' && event.data.delta) { |
| 741 | process.stdout.write(event.data.delta); |
| 742 | } |
| 743 | } |
| 744 | ``` |
| 745 | |
| 746 | ### Claude Agents SDK |
| 747 | |
| 748 | Claude Agents SDK supports MCP servers natively. No provider is needed: |
| 749 | |
| 750 | ```typescript |
| 751 | import { query } from '@anthropic-ai/claude-agent-sdk'; |
| 752 | import { Composio } from '@composio/core'; |
| 753 | |
| 754 | // No provider needed when using MCP |
| 755 | const composio = new Composio(); |
| 756 | |
| 757 | const session = await composio.create('user_123', { |
| 758 | toolkits: ['gmail'], |
| 759 | }); |
| 760 | |
| 761 | const stream = await query({ |
| 762 | prompt: 'Use composio tools to fetch my last email from gmail', |
| 763 | options: { |
| 764 | model: 'claude-sonnet-4-5-20250929', |
| 765 | permissionMode: 'bypassPermissions', |
| 766 | mcpServers: { |
| 767 | composio: { |
| 768 | type: 'http', |
| 769 | url: session.mcp.url, |
| 770 | headers: session.mcp.headers, // Uses pre-configured authentication headers |
| 771 | }, |
| 772 | }, |
| 773 | }, |
| 774 | }); |
| 775 | |
| 776 | for await (const event of stream) { |
| 777 | if (event.type === 'result' && event.subtype === 'success') { |
| 778 | process.stdout.write(event.result); |
| 779 | } |
| 780 | } |
| 781 | ``` |
| 782 | |
| 783 | ## Authorization Flow |
| 784 | |
| 785 | When a user needs to connect a toolkit, use the `authorize()` method: |
| 786 | |
| 787 | ```typescript |
| 788 | import { Composio } from '@composio/core'; |
| 789 | |
| 790 | const composio = new Composio(); |
| 791 | const session = await composio.create('user_123', { |
| 792 | toolkits: ['gmail'], |
| 793 | }); |
| 794 | |
| 795 | // Initiate authorization for Gmail |
| 796 | const connectionRequest = await session.authorize('gmail'); |
| 797 | |
| 798 | // Log the redirect URL for the user |
| 799 | console.log('Redirect URL:', connectionRequest.redirectUrl); |
| 800 | |
| 801 | // Wait for the user to complete the authorization |
| 802 | const connectedAccount = await connectionRequest.waitForConnection(); |
| 803 | console.log('Connected Account:', connectedAccount); |
| 804 | ``` |
| 805 | |
| 806 | You can also provide a custom callback URL: |
| 807 | |
| 808 | ```typescript |
| 809 | const connectionRequest = await session.authorize('gmail', { |
| 810 | callbackUrl: 'https://your-app.com/auth/callback', |
| 811 | }); |
| 812 | ``` |
| 813 | |
| 814 | ## Querying Toolkit States |
| 815 | |
| 816 | Use the `toolkits()` method to check connection states: |
| 817 | |
| 818 | ```typescript |
| 819 | import { Composio } from '@composio/core'; |
| 820 | |
| 821 | const composio = new Composio(); |
| 822 | const session = await composio.create('user_123'); |
| 823 | |
| 824 | // Get all toolkits |
| 825 | const toolkits = await session.toolkits(); |
| 826 | |
| 827 | console.log(JSON.stringify({ toolkits }, null, 2)); |
| 828 | |
| 829 | // Filter by specific toolkits |
| 830 | const gmailAndSlack = await session.toolkits({ |
| 831 | toolkits: ['gmail', 'slack'], |
| 832 | }); |
| 833 | ``` |
| 834 | |
| 835 | The response includes: |
| 836 | |
| 837 | ```typescript |
| 838 | { |
| 839 | items: [ |
| 840 | { |
| 841 | slug: 'gmail', |
| 842 | name: 'Gmail', |
| 843 | logo: 'https://...', |
| 844 | isNoAuth: false, |
| 845 | connection: { |
| 846 | isActive: true, |
| 847 | authConfig: { |
| 848 | id: 'ac_xxx', |
| 849 | mode: 'OAUTH2', |
| 850 | isComposioManaged: true |
| 851 | }, |
| 852 | connectedAccount: { |
| 853 | id: 'ca_xxx', |
| 854 | status: 'ACTIVE' |
| 855 | } |
| 856 | } |
| 857 | } |
| 858 | ], |
| 859 | cursor: 'cursor_abc', |
| 860 | totalPages: 1 |
| 861 | } |
| 862 | ``` |
| 863 | |
| 864 | ## Using Modifiers |
| 865 | |
| 866 | Add custom behavior before and after tool execution. Tool Router supports enhanced session-specific modifiers (v0.4.0+): |
| 867 | |
| 868 | ```typescript |
| 869 | import { SessionExecuteMetaModifiers } from '@composio/core'; |
| 870 | |
| 871 | const modifiers: SessionExecuteMetaModifiers = { |
| 872 | modifySchema: ({ toolSlug, toolkitSlug, schema }) => { |
| 873 | // Customize tool schema |
| 874 | console.log(`Modifying schema for ${toolSlug}`); |
| 875 | return schema; |
| 876 | }, |
| 877 | beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => { |
| 878 | console.log(`[Session: ${sessionId}] Executing ${toolSlug} from ${toolkitSlug}`); |
| 879 | // Add custom logging, validation, or parameter transformation |
| 880 | return params; |
| 881 | }, |
| 882 | afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => { |
| 883 | console.log(`[Session: ${sessionId}] Executed ${toolSlug} from ${toolkitSlug}`); |
| 884 | // Transform results, add telemetry, or handle errors |
| 885 | return result; |
| 886 | }, |
| 887 | }; |
| 888 | |
| 889 | const tools = await session.tools(modifiers); |
| 890 | ``` |
| 891 | |
| 892 | ### Modifier Types |
| 893 | |
| 894 | Tool Router provides specialized modifier types for session-based execution: |
| 895 | |
| 896 | - **`SessionExecuteMetaModifiers`**: Complete set of modifiers with session context |
| 897 | - **`SessionMetaToolOptions`**: Configuration options for meta tools |
| 898 | |
| 899 | These types include the `sessionId` in their parameters, allowing you to track and manage tool execution across different user sessions. |
| 900 | |
| 901 | ## Best Practices |
| 902 | |
| 903 | 1. **User Isolation**: Create separate sessions per user to ensure proper isolation of connections and tools. |
| 904 | |
| 905 | 2. **Toolkit Selection**: Only enable toolkits that are necessary for the use case to maintain security and reduce complexity. |
| 906 | |
| 907 | 3. **Connection Management**: Use `manageConnections: true` (default) for interactive applications where users can be prompted to connect accounts. |
| 908 | |
| 909 | 4. **Tag Filtering**: Use global `tags` to filter tools by their behavior (readOnlyHint, destructiveHint, createHint, updateHint) and override per toolkit when needed. |
| 910 | |
| 911 | 5. **Session Reuse**: Store and reuse `sessionId` to maintain user sessions across requests. |
| 912 | |
| 913 | ```typescript |
| 914 | // Store session ID after creation |
| 915 | const session = await composio.create('user_123', config); |
| 916 | await redis.set(`session:user_123`, session.sessionId); |
| 917 | |
| 918 | // Retrieve existing session |
| 919 | const sessionId = await redis.get(`session:user_123`); |
| 920 | if (sessionId) { |
| 921 | const session = await composio.use(sessionId); |
| 922 | } |
| 923 | ``` |
| 924 | |
| 925 | ## Type Reference |
| 926 | |
| 927 | ### ToolRouterCreateSessionConfig |
| 928 | |
| 929 | ```typescript |
| 930 | interface ToolRouterCreateSessionConfig { |
| 931 | toolkits?: string[] | { enable: string[] } | { disable: string[] }; |
| 932 | tools?: Record< |
| 933 | string, |
| 934 | | string[] |
| 935 | | { enable: string[] } |
| 936 | | { disable: string[] } |
| 937 | | { tags: ('readOnlyHint' | 'destructiveHint' | 'createHint' | 'updateHint')[] } |
| 938 | >; |
| 939 | tags?: ('readOnlyHint' | 'destructiveHint' | 'createHint' | 'updateHint')[]; |
| 940 | authConfigs?: Record<string, string>; |
| 941 | connectedAccounts?: Record<string, string>; |
| 942 | manageConnections?: |
| 943 | | boolean |
| 944 | | { |
| 945 | enable?: boolean; |
| 946 | callbackUrl?: string; |
| 947 | waitForConnections?: boolean; // NEW in v0.4.0: Wait for connections to complete |
| 948 | }; |
| 949 | workbench?: { |
| 950 | enable?: boolean; // Enable/disable workbench entirely (default: true) |
| 951 | enableProxyExecution?: boolean; |
| 952 | autoOffloadThreshold?: number; |
| 953 | }; |
| 954 | experimental?: { |
| 955 | assistivePrompt?: { |
| 956 | userTimezone?: string; // IANA timezone identifier for timezone-aware assistive prompts |
| 957 | }; |
| 958 | localTools?: LocalTool[]; // Standalone or extension tools (from experimental_createTool) |
| 959 | localToolkits?: LocalToolkit[]; // Grouped no-auth tools (from experimental_createToolkit) |
| 960 | }; |
| 961 | } |
| 962 | ``` |
| 963 | |
| 964 | ### ToolRouterSession |
| 965 | |
| 966 | ```typescript |
| 967 | interface ToolRouterSession { |
| 968 | sessionId: string; |
| 969 | mcp: { |
| 970 | type: 'http' | 'sse'; |
| 971 | url: string; |
| 972 | headers?: Record<string, string>; // Authentication headers (includes x-api-key if configured) |
| 973 | }; |
| 974 | tools: (modifiers?: ProviderOptions) => Promise<Tools>; |
| 975 | execute: ( |
| 976 | toolSlug: string, |
| 977 | arguments?: Record<string, unknown> |
| 978 | ) => Promise<ToolRouterSessionExecuteResponse>; |
| 979 | search: (params: { |
| 980 | query: string; |
| 981 | toolkits?: string[]; |
| 982 | }) => Promise<ToolRouterSessionSearchResponse>; |
| 983 | proxyExecute: ( |
| 984 | params: SessionProxyExecuteParams |
| 985 | ) => Promise<ToolRouterSessionProxyExecuteResponse>; |
| 986 | authorize: (toolkit: string, options?: { callbackUrl?: string }) => Promise<ConnectionRequest>; |
| 987 | toolkits: (options?: { |
| 988 | toolkits?: string[]; // Filter by specific toolkit slugs |
| 989 | cursor?: string; // Pagination cursor |
| 990 | limit?: number; // Number of items per page |
| 991 | }) => Promise<ToolkitConnectionsDetails>; |
| 992 | files: ToolRouterSessionFilesMount; // List, upload, download, delete files. See tool-router-files.md |
| 993 | experimental?: { |
| 994 | assistivePrompt?: string; // Generated system prompt for optimal tool router usage |
| 995 | }; |
| 996 | } |
| 997 | ``` |
| 998 | |
| 999 | ### ToolkitConnectionState |
| 1000 | |
| 1001 | ```typescript |
| 1002 | interface ToolkitConnectionState { |
| 1003 | slug: string; |
| 1004 | name: string; |
| 1005 | logo?: string; |
| 1006 | isNoAuth: boolean; |
| 1007 | connection: { |
| 1008 | isActive: boolean; |
| 1009 | authConfig?: { |
| 1010 | id: string; |
| 1011 | mode: string; |
| 1012 | isComposioManaged: boolean; |
| 1013 | }; |
| 1014 | connectedAccount?: { |
| 1015 | id: string; |
| 1016 | status: string; |
| 1017 | }; |
| 1018 | }; |
| 1019 | } |
| 1020 | ``` |
| 1021 | |
| 1022 | ### SessionExecuteMetaModifiers (v0.4.0+) |
| 1023 | |
| 1024 | ```typescript |
| 1025 | interface SessionExecuteMetaModifiers { |
| 1026 | modifySchema?: (context: { toolSlug: string; toolkitSlug: string; schema: any }) => any; |
| 1027 | |
| 1028 | beforeExecute?: (context: { |
| 1029 | toolSlug: string; |
| 1030 | toolkitSlug: string; |
| 1031 | sessionId: string; |
| 1032 | params: any; |
| 1033 | }) => any; |
| 1034 | |
| 1035 | afterExecute?: (context: { |
| 1036 | toolSlug: string; |
| 1037 | toolkitSlug: string; |
| 1038 | sessionId: string; |
| 1039 | result: any; |
| 1040 | }) => any; |
| 1041 | } |
| 1042 | ``` |
| 1043 | |
| 1044 | ## What's New in v0.4.0 |
| 1045 | |
| 1046 | ### 1. Wait for Connections |
| 1047 | |
| 1048 | The new `waitForConnections` property allows sessions to wait for users to complete authentication before proceeding: |
| 1049 | |
| 1050 | ```typescript |
| 1051 | const session = await composio.create('user_123', { |
| 1052 | toolkits: ['gmail', 'slack'], |
| 1053 | manageConnections: { |
| 1054 | enable: true, |
| 1055 | callbackUrl: 'https://your-app.com/callback', |
| 1056 | waitForConnections: true, // NEW |
| 1057 | }, |
| 1058 | }); |
| 1059 | ``` |
| 1060 | |
| 1061 | ### 2. Enhanced Session Modifiers |
| 1062 | |
| 1063 | Session-specific modifiers now include session context, making it easier to track and manage tool execution: |
| 1064 | |
| 1065 | ```typescript |
| 1066 | const tools = await session.tools({ |
| 1067 | beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => { |
| 1068 | console.log(`[${sessionId}] Executing ${toolSlug}`); |
| 1069 | return params; |
| 1070 | }, |
| 1071 | }); |
| 1072 | ``` |
| 1073 | |
| 1074 | ### 3. Direct Meta Tools Access |
| 1075 | |
| 1076 | New method to fetch meta tools directly from a session: |
| 1077 | |
| 1078 | ```typescript |
| 1079 | const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123', { |
| 1080 | modifySchema: ({ toolSlug, schema }) => schema, |
| 1081 | }); |
| 1082 | ``` |
| 1083 | |
| 1084 | ### 4. Performance Improvements |
| 1085 | |
| 1086 | - Optimized tool fetching with fewer API calls |
| 1087 | - Improved session API architecture for better reliability |
| 1088 | - Simplified internal tool execution paths |
| 1089 | |
| 1090 | All changes in v0.4.0 are fully backward compatible with existing code. |