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 | /** |
| 2 | * ToolRouter class for managing tool router sessions. |
| 3 | * |
| 4 | * @description Allows you to create an isolated toolRouter MCP session for a user |
| 5 | * @example |
| 6 | * ```typescript |
| 7 | * import { Composio } from '@composio/core'; |
| 8 | * |
| 9 | * const composio = new Composio(); |
| 10 | * const userId = 'user_123'; |
| 11 | * |
| 12 | * const session = await composio.sessions.create(userId, { |
| 13 | * toolkits: ['gmail'], |
| 14 | * manageConnections: true |
| 15 | * }); |
| 16 | * |
| 17 | * console.log(session.mcp.url); |
| 18 | * ``` |
| 19 | */ |
| 20 | import { Composio as ComposioClient } from '@composio/client'; |
| 21 | import { telemetry } from '../telemetry/Telemetry'; |
| 22 | import type { BaseComposioProvider } from '../provider/BaseProvider'; |
| 23 | import type { ComposioConfig } from '../composio'; |
| 24 | import { |
| 25 | ToolRouterCreateSessionConfig, |
| 26 | Session, |
| 27 | SessionWithoutMcp, |
| 28 | MCPServerType, |
| 29 | ToolRouterMCPServerConfig, |
| 30 | ToolRouterSessionMetadata, |
| 31 | SessionPreset, |
| 32 | type ToolRouterSessionDeleteResponse, |
| 33 | } from '../types/toolRouter.types'; |
| 34 | import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types'; |
| 35 | import { |
| 36 | SessionAttachResponse, |
| 37 | SessionCreateParams, |
| 38 | SessionCreateResponse, |
| 39 | SessionRetrieveResponse, |
| 40 | } from '@composio/client/resources/tool-router/session'; |
| 41 | import type { |
| 42 | LocalTool, |
| 43 | LocalToolkit, |
| 44 | InlineCustomToolsWirePayload, |
| 45 | } from '../types/customTool.types'; |
| 46 | import { |
| 47 | transformToolRouterTagsParams, |
| 48 | transformToolRouterToolsParams, |
| 49 | transformToolRouterManageConnectionsParams, |
| 50 | transformToolRouterSandboxParams, |
| 51 | transformToolRouterToolkitsParams, |
| 52 | transformToolRouterMultiAccountParams, |
| 53 | transformToolRouterInstantParams, |
| 54 | transformToolRouterProxyExecuteParams, |
| 55 | transformToolRouterHooksParams, |
| 56 | resolveToolRouterSandboxConfig, |
| 57 | resolveLocalToolsOptions, |
| 58 | type LocalToolsOptions, |
| 59 | } from '../lib/toolRouterParams'; |
| 60 | import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants'; |
| 61 | import { buildMCPServerConfig } from '../lib/toolRouterMcp'; |
| 62 | import { parseSessionConfigInput } from '../lib/sessionConfigConflict'; |
| 63 | import { getSourceSessionConfig } from '../lib/toolRouterSourceSessionConfig'; |
| 64 | import { ToolRouterSession } from './ToolRouterSession'; |
| 65 | import { ComposioRequestOptions } from '../types/requestOptions.types'; |
| 66 | import { withCancellation } from '../utils/cancellation'; |
| 67 | import { deleteToolRouterSession } from '../lib/toolRouterSessionDelete'; |
| 68 | import { |
| 69 | assertNoCustomToolSlugsInPreload, |
| 70 | buildCustomToolsMap, |
| 71 | buildCustomToolsMapFromResponse, |
| 72 | getPreloadedCustomToolSlugs, |
| 73 | serializeCustomTools, |
| 74 | serializeCustomToolkits, |
| 75 | } from './CustomTool'; |
| 76 | import type { CustomToolsMap } from '../types/customTool.types'; |
| 77 | |
| 78 | function getSessionMetadata( |
| 79 | session: SessionCreateResponse | SessionRetrieveResponse | SessionAttachResponse |
| 80 | ) { |
| 81 | const metadata: ToolRouterSessionMetadata = { |
| 82 | config: session.config, |
| 83 | preload: session.config.preload, |
| 84 | workbench: session.config.workbench, |
| 85 | configVersion: session.config_version, |
| 86 | warnings: 'warnings' in session ? (session.warnings ?? []) : [], |
| 87 | }; |
| 88 | return metadata; |
| 89 | } |
| 90 | |
| 91 | function preloadsAllCustomTools(preload?: { tools?: readonly string[] | string }): boolean { |
| 92 | return preload?.tools === PRELOAD_TOOLS_ALL; |
| 93 | } |
| 94 | |
| 95 | function prepareInlineCustomTools(options: { |
| 96 | customTools?: LocalTool[]; |
| 97 | customToolkits?: LocalToolkit[]; |
| 98 | defaultPreload?: boolean; |
| 99 | preloadTools?: readonly string[] | typeof PRELOAD_TOOLS_ALL; |
| 100 | }): InlineCustomToolsWirePayload | undefined { |
| 101 | const { customTools, customToolkits, defaultPreload = false, preloadTools } = options; |
| 102 | const hasCustoms = !!(customTools?.length || customToolkits?.length); |
| 103 | const localCustomToolsMap = hasCustoms |
| 104 | ? buildCustomToolsMap(customTools ?? [], customToolkits) |
| 105 | : undefined; |
| 106 | |
| 107 | // Top-level preload.tools is for Composio-managed slugs only. Custom tools |
| 108 | // use their own preload flag, so reject LOCAL/custom slugs there before |
| 109 | // serializing the inline custom definitions. |
| 110 | assertNoCustomToolSlugsInPreload(preloadTools, localCustomToolsMap); |
| 111 | |
| 112 | const serializedTools = customTools?.length |
| 113 | ? serializeCustomTools(customTools, { defaultPreload }) |
| 114 | : undefined; |
| 115 | const serializedToolkits = customToolkits?.length |
| 116 | ? serializeCustomToolkits(customToolkits, { defaultPreload }) |
| 117 | : undefined; |
| 118 | |
| 119 | const inlineCustomToolsPayload = |
| 120 | serializedTools || serializedToolkits |
| 121 | ? { |
| 122 | ...(serializedTools ? { custom_tools: serializedTools } : {}), |
| 123 | ...(serializedToolkits ? { custom_toolkits: serializedToolkits } : {}), |
| 124 | } |
| 125 | : undefined; |
| 126 | |
| 127 | return inlineCustomToolsPayload; |
| 128 | } |
| 129 | |
| 130 | export class ToolRouter< |
| 131 | TToolCollection, |
| 132 | TTool, |
| 133 | TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>, |
| 134 | > { |
| 135 | constructor( |
| 136 | private client: ComposioClient, |
| 137 | private config?: ComposioConfig<TProvider> |
| 138 | ) { |
| 139 | telemetry.instrument(this, 'ToolRouter'); |
| 140 | } |
| 141 | |
| 142 | /** |
| 143 | * Derives the MCP config for a session from the auth context the session |
| 144 | * request was made with: the project key when one is configured, otherwise |
| 145 | * the resolved user API key, otherwise the organization API key, plus the |
| 146 | * org/project scope when configured. |
| 147 | * Headers are only attached when the MCP URL shares the client's API |
| 148 | * origin. Any other destination throws when the caller passed `mcp: true` |
| 149 | * and otherwise yields empty headers plus a warning; see |
| 150 | * `buildMCPServerConfig`. |
| 151 | */ |
| 152 | private createMCPServerConfig( |
| 153 | { type, url }: { type: MCPServerType; url: string }, |
| 154 | mcpRequested: boolean |
| 155 | ): ToolRouterMCPServerConfig { |
| 156 | return buildMCPServerConfig({ |
| 157 | type, |
| 158 | url, |
| 159 | apiBaseURL: this.client.baseURL, |
| 160 | apiKey: this.config?.apiKey, |
| 161 | userApiKey: this.config?.userApiKey, |
| 162 | orgApiKey: this.config?.orgApiKey, |
| 163 | defaultHeaders: this.config?.defaultHeaders, |
| 164 | orgId: this.config?.orgId, |
| 165 | projectId: this.config?.projectId, |
| 166 | mcpRequested, |
| 167 | }); |
| 168 | } |
| 169 | |
| 170 | /** |
| 171 | * Creates a new tool router session for a user. |
| 172 | * Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools |
| 173 | * should be exposed directly; see `ToolRouterCreateSessionConfig`. |
| 174 | * |
| 175 | * The session's MCP config carries the session credential only when the |
| 176 | * MCP URL shares the origin of the configured API base URL. When it does |
| 177 | * not, `mcp: true` makes the call throw `ComposioMCPDestinationError` |
| 178 | * (naming both origins, never a key); without `mcp: true` the session is |
| 179 | * returned with `session.mcp.headers` empty and a warning naming both |
| 180 | * origins is logged, so native tools keep working. |
| 181 | * |
| 182 | * @param userId {string} The user id to create the session for |
| 183 | * @param config {ToolRouterCreateSessionConfig} The config for the tool router session |
| 184 | * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session |
| 185 | * @throws {ComposioMCPDestinationError} When `mcp: true` is passed and the MCP URL is not on the API origin |
| 186 | * @throws {ValidationError} When a local tools option and its deprecated `custom*` alias are both passed |
| 187 | * |
| 188 | * @example |
| 189 | * ```typescript |
| 190 | * import { Composio } from '@composio/core'; |
| 191 | * |
| 192 | * const composio = new Composio(); |
| 193 | * |
| 194 | * const session = await composio.sessions.create('user_123', { |
| 195 | * toolkits: ['gmail'], |
| 196 | * manageConnections: true, |
| 197 | * experimental: { |
| 198 | * localTools: [myLocalTool], |
| 199 | * localToolkits: [myLocalToolkit], |
| 200 | * }, |
| 201 | * }); |
| 202 | * |
| 203 | * // Start from a saved Session config instead of inline access fields |
| 204 | * const configured = await composio.sessions.create('user_123', { |
| 205 | * authConfigs: { github: 'ac_123' }, |
| 206 | * experimental: { sessionConfigId: 'sc_123' }, |
| 207 | * }); |
| 208 | * ``` |
| 209 | */ |
| 210 | // Overloads: passing `{ mcp: true }` surfaces `session.mcp` in the returned |
| 211 | // type. Otherwise the MCP endpoint is omitted from the type (it still exists |
| 212 | // at runtime). See https://docs.composio.dev/docs/sessions-via-mcp |
| 213 | async create( |
| 214 | userId: string, |
| 215 | config: ToolRouterCreateSessionConfig & { mcp: true }, |
| 216 | requestOptions?: ComposioRequestOptions |
| 217 | ): Promise<Session<TToolCollection, TTool, TProvider>>; |
| 218 | async create( |
| 219 | userId: string, |
| 220 | config?: ToolRouterCreateSessionConfig, |
| 221 | requestOptions?: ComposioRequestOptions |
| 222 | ): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>; |
| 223 | async create( |
| 224 | userId: string, |
| 225 | config?: ToolRouterCreateSessionConfig, |
| 226 | requestOptions?: ComposioRequestOptions |
| 227 | ): Promise<Session<TToolCollection, TTool, TProvider>> { |
| 228 | const routerConfig = parseSessionConfigInput(ToolRouterCreateSessionConfigSchema, config ?? {}); |
| 229 | const isDirectToolsPreset = routerConfig.sessionPreset === SessionPreset.DIRECT_TOOLS; |
| 230 | |
| 231 | const { tools: customTools, toolkits: customToolkits } = resolveLocalToolsOptions( |
| 232 | routerConfig.experimental, |
| 233 | 'create' |
| 234 | ); |
| 235 | const defaultCustomPreload = preloadsAllCustomTools(routerConfig.preload); |
| 236 | const inlineCustomToolsPayload = prepareInlineCustomTools({ |
| 237 | customTools, |
| 238 | customToolkits, |
| 239 | defaultPreload: defaultCustomPreload, |
| 240 | preloadTools: routerConfig.preload?.tools, |
| 241 | }); |
| 242 | |
| 243 | // Build the typed experimental payload for the backend |
| 244 | const experimentalPayload: SessionCreateParams['experimental'] = {}; |
| 245 | |
| 246 | if (routerConfig.experimental?.sessionConfigId !== undefined) { |
| 247 | experimentalPayload.session_config_id = routerConfig.experimental.sessionConfigId; |
| 248 | } |
| 249 | |
| 250 | if (routerConfig.experimental?.noElicitationSupportFallback !== undefined) { |
| 251 | experimentalPayload.no_elicitation_support_fallback = |
| 252 | routerConfig.experimental.noElicitationSupportFallback; |
| 253 | } |
| 254 | |
| 255 | if (routerConfig.experimental?.assistivePrompt?.userTimezone) { |
| 256 | experimentalPayload.assistive_prompt_config = { |
| 257 | user_timezone: routerConfig.experimental.assistivePrompt.userTimezone, |
| 258 | }; |
| 259 | } |
| 260 | |
| 261 | if (inlineCustomToolsPayload?.custom_tools) { |
| 262 | experimentalPayload.custom_tools = inlineCustomToolsPayload.custom_tools; |
| 263 | } |
| 264 | if (inlineCustomToolsPayload?.custom_toolkits) { |
| 265 | experimentalPayload.custom_toolkits = inlineCustomToolsPayload.custom_toolkits; |
| 266 | } |
| 267 | |
| 268 | const multiAccountPayload = transformToolRouterMultiAccountParams(routerConfig.multiAccount); |
| 269 | const sandboxPayload = transformToolRouterSandboxParams( |
| 270 | resolveToolRouterSandboxConfig(routerConfig) |
| 271 | ); |
| 272 | |
| 273 | const connectedAccountsPayload = |
| 274 | routerConfig.connectedAccounts === undefined |
| 275 | ? undefined |
| 276 | : Object.fromEntries( |
| 277 | Object.entries(routerConfig.connectedAccounts).map(([toolkit, ids]) => [ |
| 278 | toolkit, |
| 279 | typeof ids === 'string' ? [ids] : ids, |
| 280 | ]) |
| 281 | ); |
| 282 | |
| 283 | const payload: SessionCreateParams = { |
| 284 | user_id: userId, |
| 285 | auth_configs: routerConfig.authConfigs, |
| 286 | connected_accounts: connectedAccountsPayload, |
| 287 | toolkits: transformToolRouterToolkitsParams(routerConfig.toolkits), |
| 288 | ...(routerConfig.instant !== undefined && { |
| 289 | instant: transformToolRouterInstantParams(routerConfig.instant), |
| 290 | }), |
| 291 | tools: transformToolRouterToolsParams(routerConfig.tools), |
| 292 | tags: transformToolRouterTagsParams(routerConfig.tags), |
| 293 | manage_connections: transformToolRouterManageConnectionsParams( |
| 294 | routerConfig.manageConnections |
| 295 | ), |
| 296 | workbench: sandboxPayload, |
| 297 | multi_account: multiAccountPayload, |
| 298 | ...(routerConfig.proxyExecute !== undefined && { |
| 299 | proxy_execute: transformToolRouterProxyExecuteParams(routerConfig.proxyExecute), |
| 300 | }), |
| 301 | ...(routerConfig.hooks !== undefined && { |
| 302 | hooks: transformToolRouterHooksParams(routerConfig.hooks), |
| 303 | }), |
| 304 | preload: routerConfig.preload, |
| 305 | ...(isDirectToolsPreset && { |
| 306 | search: { enable: false }, |
| 307 | execute: { enable_multi_execute: false }, |
| 308 | }), |
| 309 | experimental: Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined, |
| 310 | }; |
| 311 | |
| 312 | const session = await withCancellation( |
| 313 | () => this.client.toolRouter.session.create(payload, requestOptions), |
| 314 | requestOptions?.signal |
| 315 | ); |
| 316 | |
| 317 | // Build custom tools map from the response's slug/original_slug mapping |
| 318 | // instead of computing LOCAL_ prefix client-side |
| 319 | let customToolsMap: CustomToolsMap | undefined; |
| 320 | if (customTools?.length || customToolkits?.length) { |
| 321 | customToolsMap = buildCustomToolsMapFromResponse( |
| 322 | customTools ?? [], |
| 323 | customToolkits, |
| 324 | session.experimental |
| 325 | ); |
| 326 | } |
| 327 | const metadata = { |
| 328 | ...getSessionMetadata(session), |
| 329 | preloadedCustomToolSlugs: getPreloadedCustomToolSlugs(customToolsMap, defaultCustomPreload), |
| 330 | inlineCustomToolsPayload, |
| 331 | }; |
| 332 | |
| 333 | const assistivePrompt = session.experimental?.assistive_prompt; |
| 334 | |
| 335 | return new ToolRouterSession<TToolCollection, TTool, TProvider>( |
| 336 | this.client, |
| 337 | this.config, |
| 338 | session.session_id, |
| 339 | this.createMCPServerConfig(session.mcp, routerConfig.mcp === true), |
| 340 | { assistivePrompt, sourceSessionConfig: getSourceSessionConfig(session) }, |
| 341 | customToolsMap, |
| 342 | userId, |
| 343 | metadata |
| 344 | ); |
| 345 | } |
| 346 | |
| 347 | /** |
| 348 | * Use an existing session |
| 349 | * |
| 350 | * The session's MCP config carries the session credential only when the |
| 351 | * MCP URL shares the origin of the configured API base URL. When it does |
| 352 | * not, `mcp: true` makes the call throw `ComposioMCPDestinationError` |
| 353 | * (naming both origins, never a key); without `mcp: true` the session is |
| 354 | * returned with `session.mcp.headers` empty and a warning naming both |
| 355 | * origins is logged, so native tools keep working. |
| 356 | * |
| 357 | * @param id {string} The id of the session to use |
| 358 | * @param options {object} Optional session reuse options |
| 359 | * @param options.localTools Local tools to attach to the session; `customTools` is a deprecated alias. |
| 360 | * @param options.localToolkits Toolkits of local tools to attach; `customToolkits` is a deprecated alias. |
| 361 | * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session |
| 362 | * @throws {ComposioMCPDestinationError} When `mcp: true` is passed and the MCP URL is not on the API origin |
| 363 | * @throws {ValidationError} When a local tools option and its deprecated `custom*` alias are both passed |
| 364 | * |
| 365 | * @example |
| 366 | * ```typescript |
| 367 | * import { Composio } from '@composio/core'; |
| 368 | * |
| 369 | * const composio = new Composio(); |
| 370 | * const id = 'session_123'; |
| 371 | * const session = await composio.sessions.use(id); |
| 372 | * |
| 373 | * console.log(session.mcp.url); |
| 374 | * console.log(session.mcp.headers); |
| 375 | * ``` |
| 376 | */ |
| 377 | // Overloads mirror `create()`: pass `{ mcp: true }` to surface `session.mcp` |
| 378 | // in the returned type. See https://docs.composio.dev/docs/sessions-via-mcp |
| 379 | async use( |
| 380 | id: string, |
| 381 | options: LocalToolsOptions & { mcp: true }, |
| 382 | requestOptions?: ComposioRequestOptions |
| 383 | ): Promise<Session<TToolCollection, TTool, TProvider>>; |
| 384 | async use( |
| 385 | id: string, |
| 386 | options?: LocalToolsOptions & { mcp?: boolean }, |
| 387 | requestOptions?: ComposioRequestOptions |
| 388 | ): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>; |
| 389 | async use( |
| 390 | id: string, |
| 391 | options?: LocalToolsOptions & { mcp?: boolean }, |
| 392 | requestOptions?: ComposioRequestOptions |
| 393 | ): Promise<Session<TToolCollection, TTool, TProvider>> { |
| 394 | const { tools: customTools, toolkits: customToolkits } = resolveLocalToolsOptions( |
| 395 | options, |
| 396 | 'use' |
| 397 | ); |
| 398 | const hasCustoms = !!(customTools?.length || customToolkits?.length); |
| 399 | |
| 400 | let session: SessionRetrieveResponse | SessionAttachResponse; |
| 401 | const attachInlineCustomToolsPayload = prepareInlineCustomTools({ |
| 402 | customTools, |
| 403 | customToolkits, |
| 404 | }); |
| 405 | let inlineCustomToolsPayload = attachInlineCustomToolsPayload; |
| 406 | |
| 407 | if (hasCustoms) { |
| 408 | const attachBody = { experimental: attachInlineCustomToolsPayload }; |
| 409 | session = await withCancellation( |
| 410 | () => this.client.toolRouter.session.attach(id, attachBody, requestOptions), |
| 411 | requestOptions?.signal |
| 412 | ); |
| 413 | } else { |
| 414 | session = await withCancellation( |
| 415 | () => this.client.toolRouter.session.retrieve(id, requestOptions), |
| 416 | requestOptions?.signal |
| 417 | ); |
| 418 | } |
| 419 | |
| 420 | const defaultCustomPreload = preloadsAllCustomTools(session.config.preload); |
| 421 | if (hasCustoms && defaultCustomPreload) { |
| 422 | // preload.tools = "all" on the existing session is server-authoritative: |
| 423 | // the backend exposes every custom tool regardless of per-definition |
| 424 | // preload flags, so the initial attach above (which used the caller's |
| 425 | // explicit hints) doesn't need re-sending. We only rebuild the in-memory |
| 426 | // payload so future search/execute calls re-inject with preload=true and |
| 427 | // session.tools() locally mirrors what the server returns. |
| 428 | inlineCustomToolsPayload = prepareInlineCustomTools({ |
| 429 | customTools, |
| 430 | customToolkits, |
| 431 | defaultPreload: true, |
| 432 | }); |
| 433 | } |
| 434 | |
| 435 | let customToolsMap: CustomToolsMap | undefined; |
| 436 | let userId: string | undefined; |
| 437 | if (hasCustoms) { |
| 438 | customToolsMap = buildCustomToolsMapFromResponse( |
| 439 | customTools ?? [], |
| 440 | customToolkits, |
| 441 | session.experimental |
| 442 | ); |
| 443 | userId = session.config.user_id; |
| 444 | } |
| 445 | |
| 446 | const metadata = { |
| 447 | ...getSessionMetadata(session), |
| 448 | preloadedCustomToolSlugs: getPreloadedCustomToolSlugs(customToolsMap, defaultCustomPreload), |
| 449 | inlineCustomToolsPayload, |
| 450 | }; |
| 451 | |
| 452 | return new ToolRouterSession<TToolCollection, TTool, TProvider>( |
| 453 | this.client, |
| 454 | this.config, |
| 455 | session.session_id, |
| 456 | this.createMCPServerConfig(session.mcp, options?.mcp === true), |
| 457 | { sourceSessionConfig: getSourceSessionConfig(session) }, |
| 458 | customToolsMap, |
| 459 | userId, |
| 460 | metadata |
| 461 | ); |
| 462 | } |
| 463 | |
| 464 | /** |
| 465 | * Delete a tool router session by ID. |
| 466 | * |
| 467 | * Deleted sessions immediately stop being retrievable or executable. Deleting |
| 468 | * a missing or already-deleted session surfaces the backend 404. |
| 469 | */ |
| 470 | async delete( |
| 471 | id: string, |
| 472 | requestOptions?: ComposioRequestOptions |
| 473 | ): Promise<ToolRouterSessionDeleteResponse> { |
| 474 | return deleteToolRouterSession(this.client, id, requestOptions); |
| 475 | } |
| 476 | } |