Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Add native tool support for tool router TS SDK (#2249)
Musthaq Ahamad committed
Dec 11, 2025 at 18:40 UTC
07551cd174ef3517a9d2cd423b485c45c16896d4
22 files changed
+926
-399
.changeset/bumpy-jars-turn.md
new
+5
@@ -0,0 +1,5 @@
1
+---
2
+'@composio/core': patch
3
+---
4
+
5
+Add support for native tool execution in tool router
.github/workflows/ts.audit.yml
+1
-7
@@ -39,7 +39,7 @@ jobs:
39
if: steps.audit.outcome == 'failure' && github.event_name == 'pull_request'
40
run: |
41
{
42
- echo "⚠️ **Security Audit Failed**"
42
+ echo "⚠️ **Security Audit Warning**"
43
echo ""
44
echo "The \`pnpm audit --prod\` check found security vulnerabilities in production dependencies."
45
echo ""
@@ -63,9 +63,3 @@ jobs:
63
uses: thollander/actions-comment-pull-request@v3.0.1
64
with:
65
file-path: audit-comment.txt
66
-
67
- - name: Fail if audit failed (push events)
68
- if: steps.audit.outcome == 'failure' && github.event_name == 'push'
69
- run: |
70
- echo "Security vulnerabilities found in production dependencies. Please fix them before merging."
71
- exit 1
pnpm-lock.yaml
+15
-13
@@ -13,8 +13,8 @@ catalogs:
13
specifier: ^4.20250917.0
14
version: 4.20250917.0
15
'@composio/client':
16
- specifier: 0.1.0-alpha.47
17
- version: 0.1.0-alpha.47
16
+ specifier: 0.1.0-alpha.50
17
+ version: 0.1.0-alpha.50
18
'@modelcontextprotocol/sdk':
19
specifier: ^1.24.0
20
version: 1.24.1
@@ -637,8 +637,8 @@ importers:
637
ts/examples/tool-router:
638
dependencies:
639
'@ai-sdk/mcp':
640
- specifier: ^0.0.10
641
- version: 0.0.10(zod@4.1.12)
640
+ specifier: ^0.0.11
641
+ version: 0.0.11(zod@4.1.12)
642
'@ai-sdk/openai':
643
specifier: ^2.0.72
644
version: 2.0.77(zod@4.1.12)
@@ -806,7 +806,7 @@ importers:
806
version: 1.0.0-alpha.1
807
'@composio/client':
808
specifier: 'catalog:'
809
- version: 0.1.0-alpha.47
809
+ version: 0.1.0-alpha.50
810
'@composio/core':
811
specifier: workspace:*
812
version: link:../core
@@ -900,7 +900,7 @@ importers:
900
dependencies:
901
'@composio/client':
902
specifier: 'catalog:'
903
- version: 0.1.0-alpha.47
903
+ version: 0.1.0-alpha.50
904
'@composio/json-schema-to-zod':
905
specifier: workspace:*
906
version: link:../json-schema-to-zod
@@ -1255,8 +1255,8 @@ packages:
1255
peerDependencies:
1256
zod: ^3.25.76 || ^4.1.8
1257
1258
- '@ai-sdk/mcp@0.0.10':
1259
- resolution: {integrity: sha512-BZ7DQkFFg+oTrLkoAHyd7E8tKbPCR2flVo75ruxjQejPt5gXIVcEXhgC1aE8yvuL9O/rGQ+pzYVRAsU0gX2FmA==}
1258
+ '@ai-sdk/mcp@0.0.11':
1259
+ resolution: {integrity: sha512-n0oZsxhPdMaXhAn6LrpMpxABufmeSatfhR3epbrCjJcLEHPOucKwQciwE8CTgIGgwBxHNy1FFLZmcFI77JmJfg==}
1260
engines: {node: '>=18'}
1261
peerDependencies:
1262
zod: ^3.25.76 || ^4.1.8
@@ -1583,8 +1583,8 @@ packages:
1583
'@cloudflare/workers-types@4.20250917.0':
1584
resolution: {integrity: sha512-Lsn9dZoRYZZCXXHZNa50cMP8kWhQZG9M7WjxNSiXFzC8bk4Wh/0SYYo4YINxEjEt6h2o69LmAhFaJ+qgaJTh8Q==}
1585
1586
- '@composio/client@0.1.0-alpha.47':
1587
- resolution: {integrity: sha512-ggrfbsDrntwBhRn+kncKluISKys9lePNQsJLGS6j/mfH4RBFjtDT4almw3N9vnOwJb0q4OIb/hrmAxZvwsc0Iw==}
1586
+ '@composio/client@0.1.0-alpha.50':
1587
+ resolution: {integrity: sha512-+7LE16XL2D0Z90y0PdBGLDyi9qi8P4TyqTqj2Kwa930rhDaZOkFMmAx9BbjXmx0KWjqpSxwxszcW7FgNpX5jqw==}
1588
1589
'@composio/mcp@1.0.3-0':
1590
resolution: {integrity: sha512-IpbfST0SSs/CEv+PIf6+EL0feNuJhQyUrOHJLPge8NhyLLrCyVqvujRIPyRUUjy0NDsked/Mm5VpJmYM6OACbg==}
@@ -2068,6 +2068,7 @@ packages:
2068
2069
'@finom/zod-to-json-schema@3.24.11':
2070
resolution: {integrity: sha512-fL656yBPiWebtfGItvtXLWrFNGlF1NcDFS0WdMQXMs9LluVg0CfT5E2oXYp0pidl0vVG53XkW55ysijNkU5/hA==}
2071
+ deprecated: 'Use https://www.npmjs.com/package/zod-v3-to-json-schema instead. See issue comment for details: https://github.com/StefanTerdell/zod-to-json-schema/issues/178#issuecomment-3533122539'
2072
peerDependencies:
2073
zod: ^4.0.14
2074
@@ -5869,6 +5870,7 @@ packages:
5870
next@16.0.3:
5871
resolution: {integrity: sha512-Ka0/iNBblPFcIubTA1Jjh6gvwqfjrGq1Y2MTI5lbjeLIAfmC+p5bQmojpRZqgHHVu5cG4+qdIiwXiBSm/8lZ3w==}
5872
engines: {node: '>=20.9.0'}
5873
+ deprecated: This version has a security vulnerability. Please upgrade to a patched version. See https://nextjs.org/blog/CVE-2025-66478 for more details.
5874
hasBin: true
5875
peerDependencies:
5876
'@opentelemetry/api': ^1.1.0
@@ -7520,10 +7522,10 @@ snapshots:
7522
'@ai-sdk/provider-utils': 3.0.17(zod@4.1.12)
7523
zod: 4.1.12
7524
7523
- '@ai-sdk/mcp@0.0.10(zod@4.1.12)':
7525
+ '@ai-sdk/mcp@0.0.11(zod@4.1.12)':
7526
dependencies:
7527
'@ai-sdk/provider': 2.0.0
7526
- '@ai-sdk/provider-utils': 3.0.17(zod@4.1.12)
7528
+ '@ai-sdk/provider-utils': 3.0.18(zod@4.1.12)
7529
pkce-challenge: 5.0.0
7530
zod: 4.1.12
7531
@@ -7950,7 +7952,7 @@ snapshots:
7952
7953
'@cloudflare/workers-types@4.20250917.0': {}
7954
7953
- '@composio/client@0.1.0-alpha.47': {}
7955
+ '@composio/client@0.1.0-alpha.50': {}
7956
7957
'@composio/mcp@1.0.3-0': {}
7958
pnpm-workspace.yaml
+1
-1
@@ -15,7 +15,7 @@ packages:
15
catalog:
16
'@cloudflare/vitest-pool-workers': ^0.9.2
17
'@cloudflare/workers-types': ^4.20250917.0
18
- '@composio/client': 0.1.0-alpha.47
18
+ '@composio/client': 0.1.0-alpha.50
19
'@modelcontextprotocol/sdk': ^1.24.0
20
ai: 5.0.52
21
openai: ^5.20.3
ts/docs/api/tool-router.md
+57
-38
@@ -127,28 +127,41 @@ const session = await composio.experimental.create('user_123', {
127
128
### `tools`
129
130
-Fine-grained control over which tools are available within toolkits.
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.experimental.create('user_123', {
134
- toolkits: ['gmail'],
134
+ toolkits: ['gmail', 'slack'],
135
tools: {
136
- // Override tools per toolkit
137
- overrides: {
138
- gmail: ['gmail_fetch_emails', 'gmail_send_email'], // Only these tools
139
- // OR use enabled/disabled objects
140
- // gmail: { enabled: ['gmail_fetch_emails'] }
141
- // gmail: { disabled: ['gmail_delete_email'] }
142
- },
143
- // Filter by tags
144
- tags: ['email', 'messaging']
145
- // OR use enabled/disabled
146
- // tags: { enabled: ['email'] }
147
- // tags: { disabled: ['destructive'] }
136
+ // Configure tools per toolkit
137
+ gmail: ['gmail_fetch_emails', 'gmail_send_email'], // Only these tools
138
+ // OR use enabled/disabled objects
139
+ // gmail: { enabled: ['gmail_fetch_emails'] }
140
+ // gmail: { disabled: ['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.experimental.create('user_123', {
154
+ toolkits: ['gmail', 'github'],
155
+ // Global tags applied to all toolkits
156
+ tags: ['readOnlyHint', 'idempotentHint']
157
+});
158
+```
159
+
160
+Available tags:
161
+- `readOnlyHint` - Tools that only read data
162
+- `destructiveHint` - Tools that modify or delete data
163
+- `idempotentHint` - Tools that can be safely retried
164
+
165
### `authConfigs`
166
167
Map toolkits to specific authentication configurations:
@@ -192,22 +205,21 @@ const session = await composio.experimental.create('user_123', {
205
toolkits: ['gmail'],
206
manageConnections: {
207
enabled: true,
195
- callbackUri: 'https://your-app.com/auth/callback',
196
- inferScopesFromTools: true // Infer OAuth scopes from allowed tools
208
+ callbackUrl: 'https://your-app.com/auth/callback'
209
}
210
});
211
```
212
201
-### `execution`
213
+### `workbench`
214
203
-Configure tool execution behavior:
215
+Configure workbench behavior for tool execution:
216
217
```typescript
218
const session = await composio.experimental.create('user_123', {
219
toolkits: ['gmail'],
208
- execution: {
220
+ workbench: {
221
proxyExecutionEnabled: true,
210
- timeoutSeconds: 30
222
+ autoOffloadThreshold: 400000 // Automatically offload to workbench if response > 400k characters
223
}
224
});
225
```
@@ -230,8 +242,8 @@ The MCP server configuration for this session, including authentication headers.
242
243
```typescript
244
console.log(session.mcp.url); // The URL to connect to
233
-console.log(session.mcp.type); // 'HTTP' or 'SSE'
234
-console.log(session.mcp.headers); // Authentication headers (includes x-api-key)
245
+console.log(session.mcp.type); // 'http' or 'sse'
246
+console.log(session.mcp.headers); // Authentication headers (includes x-api-key if configured)
247
```
248
249
### `tools()`
@@ -352,7 +364,12 @@ import { stepCountIs, streamText } from 'ai';
364
const composio = new Composio();
365
const { mcp } = await composio.experimental.create('user_123', {
366
toolkits: ['gmail'],
355
- manageConnections: true
367
+ manageConnections: true,
368
+ tools: {
369
+ gmail: {
370
+ disabled: ['gmail_send_email'], // Disable specific tools
371
+ }
372
+ }
373
});
374
375
// Create MCP client using the session URL and headers
@@ -360,7 +377,7 @@ const client = await createMCPClient({
377
transport: {
378
type: 'http',
379
url: mcp.url,
363
- headers: mcp.headers, // Uses pre-configured authentication headers
380
+ headers: mcp.headers // Uses pre-configured authentication headers
381
}
382
});
383
@@ -410,7 +427,7 @@ const client = new MultiServerMCPClient({
427
composio: {
428
transport: "http",
429
url: session.mcp.url,
413
- headers: session.mcp.headers, // Uses pre-configured authentication headers
430
+ headers: session.mcp.headers // Uses pre-configured authentication headers
431
},
432
});
433
@@ -451,7 +468,7 @@ console.log(`Connecting to MCP server: ${session.mcp.url}`);
468
const mcpTool = hostedMcpTool({
469
serverLabel: 'ComposioApps',
470
serverUrl: session.mcp.url,
454
- headers: session.mcp.headers, // Uses pre-configured authentication headers
471
+ headers: session.mcp.headers // Uses pre-configured authentication headers
472
});
473
474
const agent = new Agent({
@@ -497,7 +514,7 @@ const stream = await query({
514
composio: {
515
type: 'http',
516
url: session.mcp.url,
500
- headers: session.mcp.headers, // Uses pre-configured authentication headers
517
+ headers: session.mcp.headers // Uses pre-configured authentication headers
518
}
519
},
520
}
@@ -620,7 +637,7 @@ const tools = await session.tools(modifiers);
637
638
3. **Connection Management**: Use `manageConnections: true` (default) for interactive applications where users can be prompted to connect accounts.
639
623
-4. **Scope Inference**: Enable `inferScopesFromTools` when you want OAuth scopes to be automatically derived from the tools you've enabled.
640
+4. **Tag Filtering**: Use global `tags` to filter tools by their behavior (readOnlyHint, destructiveHint, idempotentHint) and override per toolkit when needed.
641
642
5. **Session Reuse**: Store and reuse `sessionId` to maintain user sessions across requests.
643
@@ -643,20 +660,22 @@ if (sessionId) {
660
```typescript
661
interface ToolRouterCreateSessionConfig {
662
toolkits?: string[] | { enabled: string[] } | { disabled: string[] };
646
- tools?: {
647
- overrides?: Record<string, string[] | { enabled: string[] } | { disabled: string[] }>;
648
- tags?: string[] | { enabled: string[] } | { disabled: string[] };
649
- };
663
+ tools?: Record<string,
664
+ string[] |
665
+ { enabled: string[] } |
666
+ { disabled: string[] } |
667
+ { tags: ('readOnlyHint' | 'destructiveHint' | 'idempotentHint')[] }
668
+ >;
669
+ tags?: ('readOnlyHint' | 'destructiveHint' | 'idempotentHint')[];
670
authConfigs?: Record<string, string>;
671
connectedAccounts?: Record<string, string>;
672
manageConnections?: boolean | {
673
enabled?: boolean;
654
- callbackUri?: string;
655
- inferScopesFromTools?: boolean;
674
+ callbackUrl?: string;
675
};
657
- execution?: {
676
+ workbench?: {
677
proxyExecutionEnabled?: boolean;
659
- timeoutSeconds?: number;
678
+ autoOffloadThreshold?: number;
679
};
680
}
681
```
@@ -667,9 +686,9 @@ interface ToolRouterCreateSessionConfig {
686
interface ToolRouterSession {
687
sessionId: string;
688
mcp: {
670
- type: 'HTTP' | 'SSE';
689
+ type: 'http' | 'sse';
690
url: string;
672
- headers?: Record<string, string | undefined>; // Authentication headers (includes x-api-key)
691
+ headers?: Record<string, string>; // Authentication headers (includes x-api-key if configured)
692
};
693
tools: (modifiers?: ProviderOptions) => Promise<Tools>;
694
authorize: (toolkit: string, options?: { callbackUrl?: string }) => Promise<ConnectionRequest>;
ts/examples/tool-router/package.json
+1
-1
@@ -18,7 +18,7 @@
18
"license": "ISC",
19
"packageManager": "pnpm@10.17.0",
20
"dependencies": {
21
- "@ai-sdk/mcp": "^0.0.10",
21
+ "@ai-sdk/mcp": "^0.0.11",
22
"@ai-sdk/openai": "^2.0.72",
23
"@anthropic-ai/claude-agent-sdk": "^0.1.55",
24
"@composio/core": "workspace:*",
ts/examples/tool-router/src/claude-agents-sdk.ts
+1
-3
@@ -15,9 +15,7 @@ const stream = await query({
15
composio: {
16
type: 'http',
17
url: session.mcp.url,
18
- headers: {
19
- 'x-api-key': process.env.COMPOSIO_API_KEY!,
20
- }
18
+ headers: session.mcp.headers
19
}
20
},
21
ts/examples/tool-router/src/index.ts
+2
@@ -7,6 +7,8 @@ const composio = new Composio({
7
provider: new VercelProvider(),
8
});
9
const session = await composio.experimental.create('user_123', { toolkits: ['gmail'] });
10
+
11
+
12
const tools = await session.tools();
13
14
const stream = await streamText({
ts/examples/tool-router/src/langchain.ts
+1
-3
@@ -18,9 +18,7 @@ async function main() {
18
math: {
19
transport: "http",
20
url: session.mcp.url,
21
- headers: {
22
- 'x-api-key': process.env.COMPOSIO_API_KEY!,
23
- }
21
+ headers: session.mcp.headers
22
},
23
});
24
ts/examples/tool-router/src/mcp.ts
+10
-4
@@ -6,7 +6,15 @@ import ora from 'ora';
6
7
const composio = new Composio();
8
const trProgress = ora("Creating tool router session...").start();
9
-const { mcp } = await composio.experimental.create('dhawal', { toolkits: ['gmail'], manageConnections: true });
9
+const { mcp } = await composio.experimental.create('dhawal', {
10
+ toolkits: ['gmail'],
11
+ manageConnections: true,
12
+ tools: {
13
+ 'gmail': {
14
+ enabled: ['gmail_search_emails'],
15
+ }
16
+ }
17
+});
18
trProgress.succeed(`Tool router session created: ${mcp.url}`);
19
20
const mcpProgress = ora("Retrieving tools from MCP...").start();
@@ -14,9 +22,7 @@ const client = await createMCPClient({
22
transport: {
23
type: 'http',
24
url: mcp.url,
17
- headers: {
18
- 'x-api-key': process.env.COMPOSIO_API_KEY!,
19
- }
25
+ headers: mcp.headers
26
}
27
});
28
ts/examples/tool-router/src/openai-agents.ts
+1
-3
@@ -11,9 +11,7 @@ console.log(`Connecting to MCP server: ${session.mcp.url}`);
11
const mcpTool = hostedMcpTool({
12
serverLabel: 'ComposioApps',
13
serverUrl: session.mcp.url,
14
- headers: {
15
- 'x-api-key': process.env.COMPOSIO_API_KEY!,
16
- }
14
+ headers: session.mcp.headers
15
});
16
17
ts/packages/core/package.json
+1
-1
@@ -42,8 +42,8 @@
42
"devDependencies": {
43
"@type-challenges/utils": "^0.1.1",
44
"@types/semver": "^7.7.0",
45
- "tsup": "catalog:",
45
"tsdown": "catalog:",
46
+ "tsup": "catalog:",
47
"tsx": "catalog:",
48
"typescript": "catalog:",
49
"vitest": "catalog:",
ts/packages/core/src/lib/toolRouterParams.ts
+43
-42
@@ -1,53 +1,54 @@
1
import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';
2
-import { ToolRouterConfigTools } from '../types/toolRouter.types';
2
+import {
3
+ ToolRouterConfigTools,
4
+ ToolRouterConfigToolsSchema,
5
+ ToolRouterToolsParam,
6
+} from '../types/toolRouter.types';
7
+import { ValidationError } from '../errors';
8
9
export const transformToolRouterToolsParams = (
5
- params?: ToolRouterConfigTools | undefined
6
-): SessionCreateParams.Tools | undefined => {
10
+ params?: Record<string, ToolRouterToolsParam | ToolRouterConfigTools> | undefined
11
+):
12
+ | Record<
13
+ string,
14
+ SessionCreateParams.Enable | SessionCreateParams.Disable | SessionCreateParams.Tags
15
+ >
16
+ | undefined => {
17
if (!params) {
18
return undefined;
19
}
20
11
- const { overrides, tags } = params;
12
-
13
- const toolOverrides = overrides
14
- ? Object.keys(overrides).reduce(
15
- (acc, key) => {
16
- const override = overrides[key];
17
- if (Array.isArray(override)) {
18
- acc[key] = { enabled: override };
19
- } else if (override !== undefined) {
20
- if ('enabled' in override && override.enabled) {
21
- acc[key] = { enabled: override.enabled };
22
- } else if ('disabled' in override && override.disabled) {
23
- acc[key] = { disabled: override.disabled };
21
+ if (typeof params === 'object') {
22
+ const result = Object.keys(params).reduce(
23
+ (acc, key) => {
24
+ if (Array.isArray(params[key])) {
25
+ acc[key] = { enable: params[key] };
26
+ } else if (typeof params[key] === 'object') {
27
+ const parsedResult = ToolRouterConfigToolsSchema.safeParse(params[key]);
28
+ if (parsedResult.success) {
29
+ const data = parsedResult.data;
30
+ if (Array.isArray(data)) {
31
+ acc[key] = { enable: data };
32
+ } else if ('enable' in data) {
33
+ acc[key] = { enable: data.enable };
34
+ } else if ('disable' in data) {
35
+ acc[key] = { disable: data.disable };
36
+ } else if ('tags' in data) {
37
+ acc[key] = { tags: data.tags };
38
}
39
+ } else {
40
+ throw new ValidationError(parsedResult.error.message);
41
}
26
- return acc;
27
- },
28
- {} as Record<string, SessionCreateParams.Tools.Enabled | SessionCreateParams.Tools.Disabled>
29
- )
30
- : undefined;
31
-
32
- const tagFilters = tags
33
- ? (() => {
34
- if (Array.isArray(tags)) {
35
- return { include: tags };
36
- } else if ('enabled' in tags && tags.enabled) {
37
- return { include: tags.enabled };
38
- } else if ('disabled' in tags && tags.disabled) {
39
- return { exclude: tags.disabled };
42
+ } else {
43
+ acc[key] = { enable: params[key] };
44
}
41
- return undefined;
42
- })()
43
- : undefined;
44
-
45
- return {
46
- overrides: toolOverrides,
47
- filters: tagFilters
48
- ? {
49
- tags: tagFilters,
50
- }
51
- : undefined,
52
- };
45
+ return acc;
46
+ },
47
+ {} as Record<
48
+ string,
49
+ SessionCreateParams.Enable | SessionCreateParams.Disable | SessionCreateParams.Tags
50
+ >
51
+ );
52
+ return result;
53
+ }
54
};
ts/packages/core/src/models/ConnectedAccounts.ts
-1
@@ -89,7 +89,6 @@ export class ConnectedAccounts {
89
rawQuery = {
90
auth_config_ids: parsedQuery.data.authConfigIds,
91
cursor: parsedQuery.data.cursor?.toString(),
92
- labels: parsedQuery.data.labels,
92
limit: parsedQuery.data.limit,
93
order_by: parsedQuery.data.orderBy,
94
statuses: parsedQuery.data.statuses,
ts/packages/core/src/models/ToolRouter.ts
+65
-37
@@ -9,7 +9,12 @@
9
* const composio = new Composio();
10
* const userId = 'user_123';
11
*
12
- * const session = await composio.create(userId);
12
+ * const session = await composio.experimental.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';
@@ -29,13 +34,18 @@ import {
34
} from '../types/toolRouter.types';
35
import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types';
36
import { Tools } from './Tools';
32
-import { ProviderOptions } from '../types/modifiers.types';
37
+import {
38
+ ExecuteToolModifiers,
39
+ ProviderOptions,
40
+ TransformToolSchemaModifier,
41
+} from '../types/modifiers.types';
42
import { ConnectionRequest } from '../types/connectionRequest.types';
43
import { createConnectionRequest } from './ConnectionRequest';
44
import { ConnectedAccountStatuses } from '../types/connectedAccounts.types';
45
import { transform } from '../utils/transform';
46
import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';
47
import { ValidationError } from '../errors';
48
+import { transformToolRouterToolsParams } from '../lib/toolRouterParams';
49
50
export class ToolRouter<
51
TToolCollection,
@@ -77,18 +87,18 @@ export class ToolRouter<
87
88
/**
89
*
80
- * @param sessionId {string} The session id to create the connections function for
81
- * @returns {ToolRouterConectionsFn} The connections function
90
+ * @param sessionId {string} The session id to create the toolkits function for
91
+ * @returns {ToolRouterToolkitsFn} The toolkits function
92
*
93
* @example
94
* ```typescript
95
* import { Composio } from '@composio/core';
96
*
97
* const composio = new Composio();
88
- * const sessionId = 'session_123';
98
+ * const session = await composio.toolRouter.use('session_123');
99
*
90
- * const session = await composio.create(sessionId);
91
- * console.log(connections);
100
+ * const toolkits = await session.toolkits();
101
+ * console.log(toolkits);
102
* ```
103
*/
104
private createToolkitsFn = (sessionId: string): ToolRouterToolkitsFn => {
@@ -155,19 +165,27 @@ export class ToolRouter<
165
* @returns A function that wraps the tools based on the provider.
166
*/
167
private createToolsFn = (
158
- userId: string,
168
+ sessionId: string,
169
toolSlugs: string[]
170
): ((modifiers?: ProviderOptions<TProvider>) => Promise<ReturnType<TProvider['wrapTools']>>) => {
171
return async (modifiers?: ProviderOptions<TProvider>) => {
172
const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
163
- const tools = await ToolsModel.get(
164
- userId,
173
+ const tools = await ToolsModel.getRawComposioTools(
174
{
175
tools: toolSlugs,
176
},
168
- modifiers
177
+ modifiers?.modifySchema
178
+ ? {
179
+ modifySchema: modifiers?.modifySchema,
180
+ }
181
+ : undefined
182
);
170
- return tools;
183
+ const wrappedTools = ToolsModel.wrapToolsForToolRouter(
184
+ sessionId,
185
+ tools,
186
+ modifiers as ExecuteToolModifiers
187
+ );
188
+ return wrappedTools as ReturnType<TProvider['wrapTools']>;
189
};
190
};
191
@@ -188,7 +206,7 @@ export class ToolRouter<
206
type,
207
url,
208
headers: {
191
- 'x-api-key': this.config?.apiKey ?? undefined,
209
+ ...(this.config?.apiKey ? { 'x-api-key': this.config?.apiKey } : {}),
210
},
211
};
212
};
@@ -197,7 +215,7 @@ export class ToolRouter<
215
* Creates a new tool router session for a user.
216
*
217
* @param userId {string} The user id to create the session for
200
- * @param config {ToolRouterConfig} The config for the tool router session
218
+ * @param config {ToolRouterCreateSessionConfig} The config for the tool router session
219
* @returns {Promise<ToolRouterSession<TToolCollection, TTool, TProvider>>} The tool router session
220
*
221
* @example
@@ -207,14 +225,25 @@ export class ToolRouter<
225
* const composio = new Composio();
226
* const userId = 'user_123';
227
*
210
- * const session = await composio.create(userId, {
211
- * manageConnections: true,
228
+ * const session = await composio.experimental.create(userId, {
229
+ * toolkits: ['gmail'],
230
+ * manageConnections: true,
231
+ * tools: {
232
+ * gmail: {
233
+ * disabled: ['gmail_send_email']
234
+ * }
235
+ * },
236
+ * tags: ['readOnlyHint']
237
* });
238
*
239
* console.log(session.sessionId);
215
- * console.log(session.url);
216
- * console.log(session.tools());
217
- * console.log(session.toolkits());
240
+ * console.log(session.mcp.url);
241
+ *
242
+ * // Get tools formatted for your framework (requires provider)
243
+ * const tools = await session.tools();
244
+ *
245
+ * // Check toolkit connection states
246
+ * const toolkits = await session.toolkits();
247
* ```
248
*/
249
async create(
@@ -226,46 +255,42 @@ export class ToolRouter<
255
const manageConnectedAccounts =
256
typeof routerConfig.manageConnections === 'boolean'
257
? routerConfig.manageConnections
229
- : (routerConfig.manageConnections?.enabled ?? true);
258
+ : (routerConfig.manageConnections?.enable ?? true);
259
260
const toolkits = Array.isArray(routerConfig.toolkits)
232
- ? { enabled: routerConfig.toolkits }
261
+ ? { enable: routerConfig.toolkits }
262
: routerConfig.toolkits;
263
235
- // const tools = transformToolRouterToolsParams(routerConfig.tools);
236
-
237
- const inferScopesFromTools =
238
- typeof routerConfig.manageConnections === 'object'
239
- ? routerConfig.manageConnections.inferScopesFromTools
240
- : false;
264
+ const tools = transformToolRouterToolsParams(routerConfig.tools);
265
266
const payload: SessionCreateParams = {
267
user_id: userId,
268
toolkits,
269
auth_configs: routerConfig.authConfigs,
270
connected_accounts: routerConfig.connectedAccounts,
247
- // tools: tools,
248
- connections: {
249
- infer_scopes_from_tools: inferScopesFromTools,
250
- auto_manage_connections: manageConnectedAccounts,
271
+ tools: tools,
272
+ tags: routerConfig.tags,
273
+ manage_connections: {
274
+ enable: manageConnectedAccounts,
275
callback_url:
276
typeof routerConfig.manageConnections === 'object'
277
? routerConfig.manageConnections.callbackUrl
278
: undefined,
279
},
256
- execution: routerConfig.execution
280
+ workbench: routerConfig.workbench
281
? {
258
- proxy_execution_enabled: routerConfig.execution?.proxyExecutionEnabled,
259
- timeout_seconds: routerConfig.execution?.timeoutSeconds,
282
+ enable_proxy_execution: routerConfig.workbench?.enableProxyExecution,
283
+ auto_offload_threshold: routerConfig.workbench?.autoOffloadThreshold,
284
}
285
: undefined,
286
};
287
+
288
const session = await this.client.toolRouter.session.create(payload);
289
290
return {
291
sessionId: session.session_id,
292
mcp: this.createMCPServerConfig(session.mcp),
268
- tools: this.createToolsFn(userId, session.tool_router_tools),
293
+ tools: this.createToolsFn(session.session_id, session.tool_router_tools),
294
authorize: this.createAuthorizeFn(session.session_id),
295
toolkits: this.createToolkitsFn(session.session_id),
296
};
@@ -283,14 +308,17 @@ export class ToolRouter<
308
* const composio = new Composio();
309
* const id = 'session_123';
310
* const session = await composio.toolRouter.use(id);
286
- *```
311
+ *
312
+ * console.log(session.mcp.url);
313
+ * console.log(session.mcp.headers);
314
+ * ```
315
*/
316
async use(id: string): Promise<ToolRouterSession<TToolCollection, TTool, TProvider>> {
317
const session = await this.client.toolRouter.session.retrieve(id);
318
return {
319
sessionId: session.session_id,
320
mcp: this.createMCPServerConfig(session.mcp),
293
- tools: this.createToolsFn(session.config.user_id, session.tool_router_tools),
321
+ tools: this.createToolsFn(session.session_id, session.tool_router_tools),
322
authorize: this.createAuthorizeFn(session.session_id),
323
toolkits: this.createToolkitsFn(session.session_id),
324
};
ts/packages/core/src/models/Tools.ts
+112
@@ -13,6 +13,7 @@ import {
13
ToolExecuteParamsSchema,
14
ToolkitVersionParam,
15
SchemaModifierOptions,
16
+ ToolExecuteMetaParamsSchema,
17
} from '../types/tool.types';
18
import {
19
ToolGetInputParams,
@@ -50,6 +51,7 @@ import { FileToolModifier } from '../utils/modifiers/FileToolModifier';
51
import { ComposioConfig } from '../composio';
52
import { getToolkitVersion } from '../utils/toolkitVersion';
53
import { handleToolExecutionError } from '../errors/ToolErrors';
54
+import { ToolExecuteMetaParams } from '../types/tool.types';
55
/**
56
* This class is used to manage tools in the Composio SDK.
57
* It provides methods to list, get, and execute tools.
@@ -626,6 +628,24 @@ export class Tools<
628
return this.provider.wrapTools(tools, executeToolFn) as ReturnType<T['wrapTools']>;
629
}
630
631
+ /**
632
+ * @internal
633
+ * Utility to wrap a given set of tools in the format expected by the tool router
634
+ *
635
+ * @param sessionId {string} The session id to execute the tool for
636
+ * @param tools {Tool[]} The tools to wrap
637
+ * @param modifiers {ExecuteToolModifiers} The modifiers to apply to the tool
638
+ * @returns {Tool[]} The wrapped tools
639
+ */
640
+ wrapToolsForToolRouter(
641
+ sessionId: string,
642
+ tools: Tool[],
643
+ modifiers?: ExecuteToolModifiers
644
+ ): Tool[] {
645
+ const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, modifiers);
646
+ return this.provider.wrapTools(tools, executeToolFn) as Tool[];
647
+ }
648
+
649
/**
650
* @internal
651
* @description
@@ -653,6 +673,34 @@ export class Tools<
673
return executeToolFn;
674
}
675
676
+ /**
677
+ * @internal
678
+ * Creates a function that executes a tool for a tool router session
679
+ *
680
+ * @param sessionId {string} The session id to execute the tool for
681
+ * @param modifiers {ExecuteToolModifiers} The modifiers to apply to the tool
682
+ * @returns {ExecuteToolFn} The execute tool function
683
+ */
684
+ private createExecuteToolFnForToolRouter(
685
+ sessionId: string,
686
+ modifiers?: ExecuteToolModifiers
687
+ ): ExecuteToolFn {
688
+ const executeToolFn = async (
689
+ toolSlug: string,
690
+ input: Record<string, unknown>
691
+ ): Promise<ToolExecuteResponse> => {
692
+ return await this.executeMetaTool(
693
+ toolSlug,
694
+ {
695
+ sessionId,
696
+ arguments: input,
697
+ },
698
+ modifiers
699
+ );
700
+ };
701
+ return executeToolFn;
702
+ }
703
+
704
/**
705
* @internal
706
* Executes a composio tool via API without modifiers
@@ -820,6 +868,70 @@ export class Tools<
868
return result;
869
}
870
871
+ /**
872
+ * Executes a composio meta tool based on tool router session
873
+ *
874
+ * @param sessionId {string} The session id to execute the tool for
875
+ * @param body.slug {string} The slug of the tool to execute
876
+ * @param body.arguments {Record<string, unknown>} The input to pass to the tool
877
+ * @param modifiers {ExecuteToolModifiers} The modifiers to apply to the tool
878
+ * @returns {Promise<ToolExecuteResponse>} The response from the tool execution
879
+ */
880
+ async executeMetaTool(
881
+ toolSlug: string,
882
+ body: ToolExecuteMetaParams,
883
+ modifiers?: ExecuteToolModifiers
884
+ ): Promise<ToolExecuteResponse> {
885
+ const executeMetaParams = ToolExecuteMetaParamsSchema.safeParse(body);
886
+ if (!executeMetaParams.success) {
887
+ throw new ValidationError('Invalid tool execute meta parameters', {
888
+ cause: executeMetaParams.error,
889
+ });
890
+ }
891
+
892
+ const tool = await this.getRawComposioToolBySlug(toolSlug);
893
+ if (!tool) {
894
+ throw new ComposioToolNotFoundError(`Tool ${toolSlug} not found`, {
895
+ meta: {
896
+ slug: toolSlug,
897
+ sessionId: body.sessionId,
898
+ },
899
+ });
900
+ }
901
+
902
+ const params = await this.applyBeforeExecuteModifiers(
903
+ tool,
904
+ {
905
+ toolSlug: toolSlug,
906
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
907
+ params: body.arguments ?? {},
908
+ },
909
+ modifiers?.beforeExecute
910
+ );
911
+
912
+ const response = await this.client.toolRouter.session.executeMeta(body.sessionId, {
913
+ slug: toolSlug,
914
+ arguments: params,
915
+ });
916
+
917
+ const result = await this.applyAfterExecuteModifiers(
918
+ tool,
919
+ {
920
+ toolSlug: toolSlug,
921
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
922
+ result: {
923
+ data: response.data,
924
+ error: response.error,
925
+ successful: !response.error,
926
+ logId: response.log_id,
927
+ },
928
+ },
929
+ modifiers?.afterExecute
930
+ );
931
+
932
+ return result;
933
+ }
934
+
935
/**
936
* Fetches the list of all available tools in the Composio SDK.
937
*
ts/packages/core/src/types/connectedAccounts.types.ts
-5
@@ -136,11 +136,6 @@ export const ConnectedAccountListParamsSchema = z.object({
136
.optional()
137
.describe('The auth config ids of the connected accounts'),
138
cursor: z.string().nullish().describe('The cursor to paginate through the connected accounts'),
139
- labels: z
140
- .array(z.string())
141
- .nullable()
142
- .optional()
143
- .describe('The labels of the connected accounts'),
139
limit: z.number().nullable().optional().describe('The limit of the connected accounts to return'),
140
orderBy: z
141
.enum(['created_at', 'updated_at'])
ts/packages/core/src/types/tool.types.ts
+6
@@ -317,6 +317,12 @@ export const ToolExecuteParamsSchema = z.object({
317
});
318
export type ToolExecuteParams = z.infer<typeof ToolExecuteParamsSchema>;
319
320
+export const ToolExecuteMetaParamsSchema = z.object({
321
+ sessionId: z.string(),
322
+ arguments: z.record(z.string(), z.unknown()).optional(),
323
+});
324
+export type ToolExecuteMetaParams = z.infer<typeof ToolExecuteMetaParamsSchema>;
325
+
326
/**
327
* ToolResponse Schema
328
*/
ts/packages/core/src/types/toolRouter.types.ts
+88
-73
@@ -9,7 +9,7 @@ export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
9
// manage connections
10
export const ToolRouterConfigManageConnectionsSchema = z
11
.object({
12
- enabled: z
12
+ enable: z
13
.boolean()
14
.default(true)
15
.optional()
@@ -20,13 +20,6 @@ export const ToolRouterConfigManageConnectionsSchema = z
20
.string()
21
.optional()
22
.describe('The callback uri to use in the tool router session'),
23
- inferScopesFromTools: z
24
- .boolean()
25
- .default(false)
26
- .optional()
27
- .describe(
28
- 'Whether to infer scopes from tools in the tool router session. Defaults to false, if set to true, tool router will infer scopes from allowed tools'
29
- ),
23
})
24
.strict();
25
@@ -37,21 +30,21 @@ export const ToolRouterToolkitsParamSchema = z
30
31
export const ToolRouterToolkitsDisabledConfigSchema = z
32
.object({
40
- disabled: ToolRouterToolkitsParamSchema.describe(
33
+ disable: ToolRouterToolkitsParamSchema.describe(
34
'List of toolkits to disable in the tool router session'
35
),
36
})
37
.strict();
38
export const ToolRouterToolkitsEnabledConfigSchema = z
39
.object({
47
- enabled: ToolRouterToolkitsParamSchema.describe(
40
+ enable: ToolRouterToolkitsParamSchema.describe(
41
'List of toolkits to enable in the tool router session'
42
),
43
})
44
.strict();
45
46
export const ToolRouterManageConnectionsConfigSchema = z.object({
54
- enabled: z
47
+ enable: z
48
.boolean()
49
.optional()
50
.describe(
@@ -67,12 +60,12 @@ export const ToolRouterTagsParamSchema = z
60
.describe('The tags to use in the tool router session');
61
export const ToolRouterEnabledTagsConfigSchema = z
62
.object({
70
- enabled: ToolRouterTagsParamSchema.describe('The tags to enable in the tool router session'),
63
+ enable: ToolRouterTagsParamSchema.describe('The tags to enable in the tool router session'),
64
})
65
.strict();
66
export const ToolRouterDisabledTagsConfigSchema = z
67
.object({
75
- disabled: ToolRouterTagsParamSchema.describe('The tags to disable in the tool router session'),
68
+ disable: ToolRouterTagsParamSchema.describe('The tags to disable in the tool router session'),
69
})
70
.strict();
71
export const ToolRouterConfigTagsSchema = z
@@ -84,21 +77,15 @@ export const ToolRouterConfigTagsSchema = z
77
.describe('The tags to use in the tool router session');
78
79
/**
87
- * Tools config
80
+ * Tools config - Configure tools per toolkit using toolkit slug as key
81
* @example
82
* ```typescript
83
* {
91
- * overrides: {
92
- * gmail: {
93
- * enabled: ['gmail_search', 'gmail_send'],
94
- * disabled: ['gmail_delete']
95
- * }
96
- * }
97
- * filters: {
98
- * tags: {
99
- * enabled: ['gmail', 'gmail_search', 'gmail_send'],
100
- * disabled: ['gmail_delete']
101
- * }
84
+ * gmail: {
85
+ * enable: ['gmail_search', 'gmail_send']
86
+ * },
87
+ * slack: {
88
+ * disable: ['slack_delete_message']
89
* }
90
* }
91
* ```
@@ -106,53 +93,70 @@ export const ToolRouterConfigTagsSchema = z
93
* @example
94
* ```typescript
95
* {
109
- * overrides: {
110
- * gmail: ['gmail_search', 'gmail_send']
111
- * },
112
- * filters: {
113
- * tags: ['gmail', 'gmail_search', 'gmail_send']
114
- * }
96
+ * gmail: ['gmail_search', 'gmail_send'],
97
+ * slack: { tags: ['readOnlyHint'] }
98
* }
99
* ```
100
*/
101
export const ToolRouterToolsParamSchema = z
102
.array(z.string())
103
.describe('The tools to use in the tool router session');
104
+export type ToolRouterToolsParam = z.infer<typeof ToolRouterToolsParamSchema>;
105
+
106
+export const ToolRouterToolsTagsParamSchema = z
107
+ .array(z.enum(['readOnlyHint', 'destructiveHint', 'idempotentHint']))
108
+ .describe('The tags to filter the tools by');
109
+export type ToolRouterToolsTagsParam = z.infer<typeof ToolRouterToolsTagsParamSchema>;
110
+
111
export const ToolRouterConfigToolsSchema = z
122
- .object({
123
- overrides: z
124
- .record(
125
- z.string(),
126
- z.union([
127
- ToolRouterToolsParamSchema,
128
- z
129
- .object({
130
- enabled: ToolRouterToolsParamSchema.describe(
131
- 'The tools to enable in the tool router session'
132
- ),
133
- })
134
- .strict(),
135
- z
136
- .object({
137
- disabled: ToolRouterToolsParamSchema.describe(
138
- 'The tools to disable in the tool router session'
139
- ),
140
- })
141
- .strict(),
142
- ])
143
- )
144
- .describe('The tools to override in the tool router session')
145
- .optional(),
146
- tags: ToolRouterConfigTagsSchema.optional().describe('The tags to filter the tools by'),
147
- })
148
- .strict();
112
+ .union([
113
+ ToolRouterToolsParamSchema,
114
+ z
115
+ .object({
116
+ enable: ToolRouterToolsParamSchema.describe(
117
+ 'The tools to enable in the tool router session'
118
+ ),
119
+ })
120
+ .strict(),
121
+ z
122
+ .object({
123
+ disable: ToolRouterToolsParamSchema.describe(
124
+ 'The tools to disable in the tool router session'
125
+ ),
126
+ })
127
+ .strict(),
128
+ z
129
+ .object({
130
+ tags: ToolRouterToolsTagsParamSchema.describe(
131
+ 'The tags to filter the tools by, this will override the global tags'
132
+ ),
133
+ })
134
+ .strict(),
135
+ ])
136
+ .superRefine((val, ctx) => {
137
+ // If it's an object (not an array), ensure only one property is present
138
+ if (typeof val === 'object' && !Array.isArray(val)) {
139
+ const keys = Object.keys(val);
140
+ if (keys.length > 1) {
141
+ ctx.addIssue({
142
+ code: z.ZodIssueCode.custom,
143
+ message: `Only one of 'enable', 'disable', or 'tags' can be specified, but found: ${keys.join(', ')}`,
144
+ path: keys,
145
+ });
146
+ }
147
+ }
148
+ });
149
export type ToolRouterConfigTools = z.infer<typeof ToolRouterConfigToolsSchema>;
150
151
export const ToolRouterCreateSessionConfigSchema = z
152
.object({
153
- // tools: ToolRouterConfigToolsSchema.optional().describe(
154
- // 'The tools to use in the tool router session'
155
- // ),
153
+ tools: z
154
+ .record(z.string(), z.union([ToolRouterToolsParamSchema, ToolRouterConfigToolsSchema]))
155
+ .optional()
156
+ .describe('The tools to use in the tool router session'),
157
+
158
+ tags: ToolRouterToolsTagsParamSchema.optional().describe('Global tags to filter the tools by'),
159
+
160
toolkits: z
161
.union([
162
ToolRouterToolkitsParamSchema,
@@ -181,16 +185,18 @@ export const ToolRouterCreateSessionConfigSchema = z
185
.describe(
186
'The config for the manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually. If set to an object, you can configure the manage connections settings.'
187
),
184
- execution: z
188
+ workbench: z
189
.object({
186
- proxyExecutionEnabled: z
190
+ enableProxyExecution: z
191
.boolean()
192
.optional()
193
.describe('Whether to enable proxy execution in the tool router session'),
190
- timeoutSeconds: z
194
+ autoOffloadThreshold: z
195
.number()
196
.optional()
193
- .describe('The timeout in seconds for the tool router session'),
197
+ .describe(
198
+ 'The auto offload threshold in characters for the tool execution to be moved into workbench'
199
+ ),
200
})
201
.optional()
202
.describe('The execution config for the tool router session'),
@@ -201,14 +207,16 @@ export const ToolRouterCreateSessionConfigSchema = z
207
* The config for the tool router session.
208
*
209
* @param {ToolRouterToolkitsParamSchema | ToolRouterToolkitsDisabledConfigSchema | ToolRouterToolkitsEnabledConfigSchema} toolkits - The toolkits to use in the tool router session
204
- * @param {ToolRouterToolsParamSchema | ToolRouterEnabledToolsConfigSchema | ToolRouterDisabledToolsConfigSchema} tools - The tools to use in the tool router session
205
- * @param {ToolRouterConfigManageConnectionsSchema | boolean} manageConnections - Whether to use tools to manage connections in the tool router session @default true
210
+ * @param {Record<string, ToolRouterToolsParam | ToolRouterConfigTools>} tools - The tools to configure per toolkit (key is toolkit slug)
211
+ * @param {Array<'readOnlyHint' | 'destructiveHint' | 'idempotentHint'>} tags - Global tags to filter tools by behavior
212
* @param {Record<string, string>} authConfigs - The auth configs to use in the tool router session
213
* @param {Record<string, string>} connectedAccounts - The connected accounts to use in the tool router session
214
* @param {ToolRouterConfigManageConnectionsSchema | boolean} manageConnections - The config for the manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually. If set to an object, you can configure the manage connections settings.
209
- * @param {boolean} [manageConnections.enabled] - Whether to use tools to manage connections in the tool router session @default true
210
- * @param {string} [manageConnections.callbackUrl] - The callback uri to use in the tool router session
211
- * @param {boolean} [manageConnections.inferScopesFromTools] - Whether to infer scopes from tools in the tool router session @default false
215
+ * @param {boolean} [manageConnections.enable] - Whether to use tools to manage connections in the tool router session @default true
216
+ * @param {string} [manageConnections.callbackUrl] - The callback url to use in the tool router session
217
+ * @param {object} workbench - Workbench configuration for tool execution
218
+ * @param {boolean} [workbench.proxyExecutionEnabled] - Whether to enable proxy execution
219
+ * @param {number} [workbench.autoOffloadThreshold] - Auto offload threshold in characters for moving execution to workbench
220
*/
221
export type ToolRouterCreateSessionConfig = z.infer<typeof ToolRouterCreateSessionConfigSchema>;
222
@@ -256,7 +264,7 @@ export type ToolkitConnectionState = z.infer<typeof ToolkitConnectionStateSchema
264
export const ToolRouterMCPServerConfigSchema = z.object({
265
type: MCPServerTypeSchema,
266
url: z.string(),
259
- headers: z.record(z.string(), z.string().optional()).optional(),
267
+ headers: z.record(z.string(), z.string()).optional(),
268
});
269
export type ToolRouterMCPServerConfig = z.infer<typeof ToolRouterMCPServerConfigSchema>;
270
@@ -293,15 +301,22 @@ export interface ToolRouterSession<
301
sessionId: string;
302
/**
303
* The MCP server config of the tool router session.
304
+ * Contains the URL, type ('http' or 'sse'), and headers for authentication.
305
*/
306
mcp: ToolRouterMCPServerConfig;
307
/**
299
- * The tools of the tool router session.
308
+ * Get the tools available in the session, formatted for your AI framework.
309
+ * Requires a provider to be configured in the Composio constructor.
310
*/
311
tools: ToolRouterToolsFn<TToolCollection, TTool, TProvider>;
312
/**
303
- * The authorize function of the tool router session.
313
+ * Initiate an authorization flow for a toolkit.
314
+ * Returns a ConnectionRequest with a redirect URL for the user.
315
*/
316
authorize: ToolRouterAuthorizeFn;
317
+ /**
318
+ * Query the connection state of toolkits in the session.
319
+ * Supports pagination and filtering by toolkit slugs.
320
+ */
321
toolkits: ToolRouterToolkitsFn;
322
}
ts/packages/core/test/models/toolRouter.test.ts
+191
-167
@@ -17,7 +17,8 @@ vi.mock('../../src/telemetry/Telemetry', () => ({
17
vi.mock('../../src/models/Tools', () => {
18
return {
19
Tools: vi.fn().mockImplementation(() => ({
20
- get: vi.fn().mockResolvedValue('mocked-wrapped-tools'),
20
+ getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
21
+ wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
22
})),
23
};
24
});
@@ -32,6 +33,7 @@ const createMockClient = () => ({
33
retrieve: vi.fn(),
34
link: vi.fn(),
35
toolkits: vi.fn(),
36
+ executeMeta: vi.fn(),
37
},
38
},
39
tools: {
@@ -65,12 +67,11 @@ const mockSessionRetrieveResponse = {
67
tool_router_tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
68
config: {
69
user_id: 'user_123',
68
- toolkits: { enabled: ['gmail', 'slack', 'github'] },
70
+ toolkits: { enable: ['gmail', 'slack', 'github'] },
71
auth_configs: {},
72
connected_accounts: {},
71
- connections: {
72
- auto_manage_connections: true,
73
- infer_scopes_from_tools: false,
73
+ manage_connections: {
74
+ enable: true,
75
},
76
},
77
};
@@ -130,16 +131,14 @@ describe('ToolRouter', () => {
131
let mockClient: ReturnType<typeof createMockClient>;
132
let mockProvider: MockProvider;
133
133
- // Helper function to create expected connections object
134
- const createExpectedConnections = (
134
+ // Helper function to create expected manage_connections object
135
+ const createExpectedManageConnections = (
136
overrides: {
136
- manageConnections?: boolean;
137
+ enable?: boolean;
138
callbackUrl?: string;
138
- inferScopesFromTools?: boolean;
139
} = {}
140
) => ({
141
- infer_scopes_from_tools: overrides.inferScopesFromTools ?? false,
142
- auto_manage_connections: overrides.manageConnections ?? true,
141
+ enable: overrides.enable ?? true,
142
callback_url: overrides.callbackUrl ?? undefined,
143
});
144
@@ -183,8 +182,9 @@ describe('ToolRouter', () => {
182
auth_configs: undefined,
183
connected_accounts: undefined,
184
tools: undefined,
186
- connections: createExpectedConnections(),
187
- execution: undefined,
185
+ tags: undefined,
186
+ manage_connections: createExpectedManageConnections(),
187
+ workbench: undefined,
188
});
189
190
expect(session).toHaveProperty('sessionId', 'session_123');
@@ -212,8 +212,9 @@ describe('ToolRouter', () => {
212
auth_configs: undefined,
213
connected_accounts: undefined,
214
tools: undefined,
215
- connections: createExpectedConnections(),
216
- execution: undefined,
215
+ tags: undefined,
216
+ manage_connections: createExpectedManageConnections(),
217
+ workbench: undefined,
218
});
219
220
expect(session.sessionId).toBe('session_123');
@@ -230,7 +231,7 @@ describe('ToolRouter', () => {
231
});
232
233
describe('toolkits configuration', () => {
233
- it('should create a session with toolkits as array (enabled toolkits)', async () => {
234
+ it('should create a session with toolkits as array (enable toolkits)', async () => {
235
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
236
237
const config: ToolRouterCreateSessionConfig = {
@@ -242,22 +243,23 @@ describe('ToolRouter', () => {
243
expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
244
user_id: userId,
245
toolkits: {
245
- enabled: ['gmail', 'slack', 'github'],
246
+ enable: ['gmail', 'slack', 'github'],
247
},
248
auth_configs: undefined,
249
connected_accounts: undefined,
250
tools: undefined,
250
- connections: createExpectedConnections(),
251
- execution: undefined,
251
+ tags: undefined,
252
+ manage_connections: createExpectedManageConnections(),
253
+ workbench: undefined,
254
});
255
});
256
255
- it('should create a session with enabled toolkits configuration', async () => {
257
+ it('should create a session with enable toolkits configuration', async () => {
258
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
259
260
const config: ToolRouterCreateSessionConfig = {
261
toolkits: {
260
- enabled: ['gmail', 'slack'],
262
+ enable: ['gmail', 'slack'],
263
},
264
};
265
@@ -266,22 +268,23 @@ describe('ToolRouter', () => {
268
expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
269
user_id: userId,
270
toolkits: {
269
- enabled: ['gmail', 'slack'],
271
+ enable: ['gmail', 'slack'],
272
},
273
auth_configs: undefined,
274
connected_accounts: undefined,
275
tools: undefined,
274
- connections: createExpectedConnections(),
275
- execution: undefined,
276
+ tags: undefined,
277
+ manage_connections: createExpectedManageConnections(),
278
+ workbench: undefined,
279
});
280
});
281
279
- it('should create a session with disabled toolkits configuration', async () => {
282
+ it('should create a session with disable toolkits configuration', async () => {
283
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
284
285
const config: ToolRouterCreateSessionConfig = {
286
toolkits: {
284
- disabled: ['notion', 'trello'],
287
+ disable: ['notion', 'trello'],
288
},
289
};
290
@@ -290,13 +293,14 @@ describe('ToolRouter', () => {
293
expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
294
user_id: userId,
295
toolkits: {
293
- disabled: ['notion', 'trello'],
296
+ disable: ['notion', 'trello'],
297
},
298
auth_configs: undefined,
299
connected_accounts: undefined,
300
tools: undefined,
298
- connections: createExpectedConnections(),
299
- execution: undefined,
301
+ tags: undefined,
302
+ manage_connections: createExpectedManageConnections(),
303
+ workbench: undefined,
304
});
305
});
306
});
@@ -322,7 +326,7 @@ describe('ToolRouter', () => {
326
// connected_accounts: undefined,
327
// tools: {
328
// overrides: {
325
- // gmail: { enabled: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
329
+ // gmail: { enable: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
330
// },
331
// filters: undefined,
332
// },
@@ -331,13 +335,13 @@ describe('ToolRouter', () => {
335
// });
336
// });
337
334
- // it('should create a session with tools overrides with enabled tools', async () => {
338
+ // it('should create a session with tools overrides with enable tools', async () => {
339
// mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
340
341
// const config: ToolRouterCreateSessionConfig = {
342
// tools: {
343
// overrides: {
340
- // gmail: { enabled: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
344
+ // gmail: { enable: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
345
// },
346
// },
347
// };
@@ -351,7 +355,7 @@ describe('ToolRouter', () => {
355
// connected_accounts: undefined,
356
// tools: {
357
// overrides: {
354
- // gmail: { enabled: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
358
+ // gmail: { enable: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
359
// },
360
// filters: undefined,
361
// },
@@ -360,13 +364,13 @@ describe('ToolRouter', () => {
364
// });
365
// });
366
363
- // it('should create a session with tools overrides with disabled tools', async () => {
367
+ // it('should create a session with tools overrides with disable tools', async () => {
368
// mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
369
370
// const config: ToolRouterCreateSessionConfig = {
371
// tools: {
372
// overrides: {
369
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
373
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
374
// },
375
// },
376
// };
@@ -380,7 +384,7 @@ describe('ToolRouter', () => {
384
// connected_accounts: undefined,
385
// tools: {
386
// overrides: {
383
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
387
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
388
// },
389
// filters: undefined,
390
// },
@@ -416,12 +420,12 @@ describe('ToolRouter', () => {
420
// });
421
// });
422
419
- // it('should create a session with enabled tag filters', async () => {
423
+ // it('should create a session with enable tag filters', async () => {
424
// mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
425
426
// const config: ToolRouterCreateSessionConfig = {
427
// tools: {
424
- // tags: { enabled: ['important', 'email'] },
428
+ // tags: { enable: ['important', 'email'] },
429
// },
430
// };
431
@@ -443,12 +447,12 @@ describe('ToolRouter', () => {
447
// });
448
// });
449
446
- // it('should create a session with disabled tag filters', async () => {
450
+ // it('should create a session with disable tag filters', async () => {
451
// mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
452
453
// const config: ToolRouterCreateSessionConfig = {
454
// tools: {
451
- // tags: { disabled: ['dangerous'] },
455
+ // tags: { disable: ['dangerous'] },
456
// },
457
// };
458
@@ -477,7 +481,7 @@ describe('ToolRouter', () => {
481
// tools: {
482
// overrides: {
483
// gmail: ['GMAIL_FETCH_EMAILS'],
480
- // slack: { disabled: ['SLACK_DELETE_MESSAGE'] },
484
+ // slack: { disable: ['SLACK_DELETE_MESSAGE'] },
485
// },
486
// tags: ['important'],
487
// },
@@ -492,8 +496,8 @@ describe('ToolRouter', () => {
496
// connected_accounts: undefined,
497
// tools: {
498
// overrides: {
495
- // gmail: { enabled: ['GMAIL_FETCH_EMAILS'] },
496
- // slack: { disabled: ['SLACK_DELETE_MESSAGE'] },
499
+ // gmail: { enable: ['GMAIL_FETCH_EMAILS'] },
500
+ // slack: { disable: ['SLACK_DELETE_MESSAGE'] },
501
// },
502
// filters: {
503
// tags: { include: ['important'] },
@@ -521,8 +525,9 @@ describe('ToolRouter', () => {
525
auth_configs: undefined,
526
connected_accounts: undefined,
527
tools: undefined,
524
- connections: createExpectedConnections({ manageConnections: true }),
525
- execution: undefined,
528
+ tags: undefined,
529
+ manage_connections: createExpectedManageConnections({ enable: true }),
530
+ workbench: undefined,
531
});
532
});
533
@@ -541,18 +546,18 @@ describe('ToolRouter', () => {
546
auth_configs: undefined,
547
connected_accounts: undefined,
548
tools: undefined,
544
- connections: createExpectedConnections({ manageConnections: false }),
545
- execution: undefined,
549
+ tags: undefined,
550
+ manage_connections: createExpectedManageConnections({ enable: false }),
551
+ workbench: undefined,
552
});
553
});
554
549
- it('should create a session with manageConnections as object with enabled', async () => {
555
+ it('should create a session with manageConnections as object with enable', async () => {
556
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
557
558
const config: ToolRouterCreateSessionConfig = {
559
manageConnections: {
554
- enabled: true,
555
- inferScopesFromTools: false,
560
+ enable: true,
561
},
562
};
563
@@ -564,8 +569,9 @@ describe('ToolRouter', () => {
569
auth_configs: undefined,
570
connected_accounts: undefined,
571
tools: undefined,
567
- connections: createExpectedConnections({ manageConnections: true }),
568
- execution: undefined,
572
+ tags: undefined,
573
+ manage_connections: createExpectedManageConnections({ enable: true }),
574
+ workbench: undefined,
575
});
576
});
577
@@ -574,9 +580,8 @@ describe('ToolRouter', () => {
580
581
const config: ToolRouterCreateSessionConfig = {
582
manageConnections: {
577
- enabled: true,
583
+ enable: true,
584
callbackUrl: 'https://myapp.com/callback',
579
- inferScopesFromTools: false,
585
},
586
};
587
@@ -588,37 +593,12 @@ describe('ToolRouter', () => {
593
auth_configs: undefined,
594
connected_accounts: undefined,
595
tools: undefined,
591
- connections: createExpectedConnections({
592
- manageConnections: true,
596
+ tags: undefined,
597
+ manage_connections: createExpectedManageConnections({
598
+ enable: true,
599
callbackUrl: 'https://myapp.com/callback',
600
}),
595
- execution: undefined,
596
- });
597
- });
598
-
599
- it('should create a session with manageConnections object with inferScopesFromTools', async () => {
600
- mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
601
-
602
- const config: ToolRouterCreateSessionConfig = {
603
- manageConnections: {
604
- enabled: true,
605
- inferScopesFromTools: true,
606
- },
607
- };
608
-
609
- await toolRouter.create(userId, config);
610
-
611
- expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
612
- user_id: userId,
613
- toolkits: undefined,
614
- auth_configs: undefined,
615
- connected_accounts: undefined,
616
- tools: undefined,
617
- connections: createExpectedConnections({
618
- manageConnections: true,
619
- inferScopesFromTools: true,
620
- }),
621
- execution: undefined,
601
+ workbench: undefined,
602
});
603
});
604
@@ -627,9 +607,8 @@ describe('ToolRouter', () => {
607
608
const config: ToolRouterCreateSessionConfig = {
609
manageConnections: {
630
- enabled: true,
610
+ enable: true,
611
callbackUrl: 'https://myapp.com/callback',
632
- inferScopesFromTools: true,
612
},
613
};
614
@@ -641,12 +620,12 @@ describe('ToolRouter', () => {
620
auth_configs: undefined,
621
connected_accounts: undefined,
622
tools: undefined,
644
- connections: createExpectedConnections({
645
- manageConnections: true,
646
- inferScopesFromTools: true,
623
+ tags: undefined,
624
+ manage_connections: createExpectedManageConnections({
625
+ enable: true,
626
callbackUrl: 'https://myapp.com/callback',
627
}),
649
- execution: undefined,
628
+ workbench: undefined,
629
});
630
});
631
});
@@ -673,8 +652,9 @@ describe('ToolRouter', () => {
652
},
653
connected_accounts: undefined,
654
tools: undefined,
676
- connections: createExpectedConnections(),
677
- execution: undefined,
655
+ tags: undefined,
656
+ manage_connections: createExpectedManageConnections(),
657
+ workbench: undefined,
658
});
659
});
660
@@ -699,8 +679,9 @@ describe('ToolRouter', () => {
679
slack: 'conn_456',
680
},
681
tools: undefined,
702
- connections: createExpectedConnections(),
703
- execution: undefined,
682
+ tags: undefined,
683
+ manage_connections: createExpectedManageConnections(),
684
+ workbench: undefined,
685
});
686
});
687
@@ -728,19 +709,20 @@ describe('ToolRouter', () => {
709
slack: 'conn_456',
710
},
711
tools: undefined,
731
- connections: createExpectedConnections(),
732
- execution: undefined,
712
+ tags: undefined,
713
+ manage_connections: createExpectedManageConnections(),
714
+ workbench: undefined,
715
});
716
});
717
});
718
737
- describe('execution configuration', () => {
738
- it('should create a session with proxyExecutionEnabled only', async () => {
719
+ describe('workbench configuration', () => {
720
+ it('should create a session with enableProxyExecution only', async () => {
721
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
722
723
const config: ToolRouterCreateSessionConfig = {
742
- execution: {
743
- proxyExecutionEnabled: true,
724
+ workbench: {
725
+ enableProxyExecution: true,
726
},
727
};
728
@@ -752,20 +734,21 @@ describe('ToolRouter', () => {
734
auth_configs: undefined,
735
connected_accounts: undefined,
736
tools: undefined,
755
- connections: createExpectedConnections(),
756
- execution: {
757
- proxy_execution_enabled: true,
758
- timeout_seconds: undefined,
737
+ tags: undefined,
738
+ manage_connections: createExpectedManageConnections(),
739
+ workbench: {
740
+ enable_proxy_execution: true,
741
+ auto_offload_threshold: undefined,
742
},
743
});
744
});
745
763
- it('should create a session with timeoutSeconds only', async () => {
746
+ it('should create a session with autoOffloadThreshold only', async () => {
747
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
748
749
const config: ToolRouterCreateSessionConfig = {
767
- execution: {
768
- timeoutSeconds: 60,
750
+ workbench: {
751
+ autoOffloadThreshold: 1000,
752
},
753
};
754
@@ -777,21 +760,22 @@ describe('ToolRouter', () => {
760
auth_configs: undefined,
761
connected_accounts: undefined,
762
tools: undefined,
780
- connections: createExpectedConnections(),
781
- execution: {
782
- proxy_execution_enabled: undefined,
783
- timeout_seconds: 60,
763
+ tags: undefined,
764
+ manage_connections: createExpectedManageConnections(),
765
+ workbench: {
766
+ enable_proxy_execution: undefined,
767
+ auto_offload_threshold: 1000,
768
},
769
});
770
});
771
788
- it('should create a session with full execution configuration', async () => {
772
+ it('should create a session with full workbench configuration', async () => {
773
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
774
775
const config: ToolRouterCreateSessionConfig = {
792
- execution: {
793
- proxyExecutionEnabled: true,
794
- timeoutSeconds: 30,
776
+ workbench: {
777
+ enableProxyExecution: true,
778
+ autoOffloadThreshold: 500,
779
},
780
};
781
@@ -803,21 +787,22 @@ describe('ToolRouter', () => {
787
auth_configs: undefined,
788
connected_accounts: undefined,
789
tools: undefined,
806
- connections: createExpectedConnections(),
807
- execution: {
808
- proxy_execution_enabled: true,
809
- timeout_seconds: 30,
790
+ tags: undefined,
791
+ manage_connections: createExpectedManageConnections(),
792
+ workbench: {
793
+ enable_proxy_execution: true,
794
+ auto_offload_threshold: 500,
795
},
796
});
797
});
798
814
- it('should create a session with execution disabled', async () => {
799
+ it('should create a session with workbench disable', async () => {
800
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
801
802
const config: ToolRouterCreateSessionConfig = {
818
- execution: {
819
- proxyExecutionEnabled: false,
820
- timeoutSeconds: 0,
803
+ workbench: {
804
+ enableProxyExecution: false,
805
+ autoOffloadThreshold: 0,
806
},
807
};
808
@@ -829,10 +814,11 @@ describe('ToolRouter', () => {
814
auth_configs: undefined,
815
connected_accounts: undefined,
816
tools: undefined,
832
- connections: createExpectedConnections(),
833
- execution: {
834
- proxy_execution_enabled: false,
835
- timeout_seconds: 0,
817
+ tags: undefined,
818
+ manage_connections: createExpectedManageConnections(),
819
+ workbench: {
820
+ enable_proxy_execution: false,
821
+ auto_offload_threshold: 0,
822
},
823
});
824
});
@@ -857,13 +843,12 @@ describe('ToolRouter', () => {
843
// slack: 'conn_456',
844
// },
845
// manageConnections: {
860
- // enabled: true,
846
+ // enable: true,
847
// callbackUri: 'https://myapp.com/callback',
862
- // inferScopesFromTools: true,
848
// },
849
// execution: {
865
- // proxyExecutionEnabled: true,
866
- // timeoutSeconds: 30,
850
+ // enableProxyExecution: true,
851
+ // autoOffloadThreshould: 30,
852
// },
853
// };
854
@@ -872,7 +857,7 @@ describe('ToolRouter', () => {
857
// expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
858
// user_id: userId,
859
// toolkits: {
875
- // enabled: ['gmail', 'slack'],
860
+ // enable: ['gmail', 'slack'],
861
// },
862
// auth_configs: {
863
// gmail: 'auth_config_123',
@@ -882,7 +867,7 @@ describe('ToolRouter', () => {
867
// },
868
// tools: {
869
// overrides: {
885
- // gmail: { enabled: ['GMAIL_FETCH_EMAILS'] },
870
+ // gmail: { enable: ['GMAIL_FETCH_EMAILS'] },
871
// },
872
// filters: {
873
// tags: { include: ['important'] },
@@ -890,27 +875,26 @@ describe('ToolRouter', () => {
875
// },
876
// connections: createExpectedConnections({
877
// manageConnections: true,
893
- // inferScopesFromTools: true,
878
// callbackUri: 'https://myapp.com/callback',
879
// }),
880
// execution: {
897
- // proxy_execution_enabled: true,
898
- // timeout_seconds: 30,
881
+ // enable_proxy_execution: true,
882
+ // auto_offload_threshould: 30,
883
// },
884
// });
885
// });
886
903
- // it('should create a session with toolkits and disabled tools', async () => {
887
+ // it('should create a session with toolkits and disable tools', async () => {
888
// mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
889
890
// const config: ToolRouterCreateSessionConfig = {
891
// toolkits: {
908
- // enabled: ['gmail', 'slack', 'github'],
892
+ // enable: ['gmail', 'slack', 'github'],
893
// },
894
// tools: {
895
// overrides: {
912
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
913
- // slack: { disabled: ['SLACK_DELETE_MESSAGE'] },
896
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
897
+ // slack: { disable: ['SLACK_DELETE_MESSAGE'] },
898
// },
899
// },
900
// };
@@ -920,14 +904,14 @@ describe('ToolRouter', () => {
904
// expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
905
// user_id: userId,
906
// toolkits: {
923
- // enabled: ['gmail', 'slack', 'github'],
907
+ // enable: ['gmail', 'slack', 'github'],
908
// },
909
// auth_configs: undefined,
910
// connected_accounts: undefined,
911
// tools: {
912
// overrides: {
929
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
930
- // slack: { disabled: ['SLACK_DELETE_MESSAGE'] },
913
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
914
+ // slack: { disable: ['SLACK_DELETE_MESSAGE'] },
915
// },
916
// filters: undefined,
917
// },
@@ -941,13 +925,13 @@ describe('ToolRouter', () => {
925
926
// const config: ToolRouterCreateSessionConfig = {
927
// toolkits: {
944
- // disabled: ['notion'],
928
+ // disable: ['notion'],
929
// },
930
// tools: {
931
// overrides: {
948
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
932
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
933
// },
950
- // tags: { disabled: ['dangerous'] },
934
+ // tags: { disable: ['dangerous'] },
935
// },
936
// authConfigs: {
937
// gmail: 'auth_config_123',
@@ -956,8 +940,7 @@ describe('ToolRouter', () => {
940
// },
941
// connectedAccounts: {},
942
// manageConnections: {
959
- // enabled: false,
960
- // inferScopesFromTools: false,
943
+ // enable: false,
944
// },
945
// };
946
@@ -966,7 +949,7 @@ describe('ToolRouter', () => {
949
// expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
950
// user_id: userId,
951
// toolkits: {
969
- // disabled: ['notion'],
952
+ // disable: ['notion'],
953
// },
954
// auth_configs: {
955
// gmail: 'auth_config_123',
@@ -976,7 +959,7 @@ describe('ToolRouter', () => {
959
// connected_accounts: {},
960
// tools: {
961
// overrides: {
979
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
962
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
963
// },
964
// filters: {
965
// tags: { exclude: ['dangerous'] },
@@ -1010,7 +993,7 @@ describe('ToolRouter', () => {
993
await expect(toolRouter.create(userId, invalidConfig)).rejects.toThrow();
994
});
995
1013
- it('should throw error for empty userId', async () => {
996
+ it('should pass through empty userId', async () => {
997
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
998
999
// The test validates that even empty userId is passed through
@@ -1474,12 +1457,14 @@ describe('ToolRouter', () => {
1457
1458
describe('tools function', () => {
1459
const userId = 'user_123';
1460
+ const sessionId = 'session_123';
1461
1462
beforeEach(() => {
1463
// Reset the Tools mock before each test
1464
vi.clearAllMocks();
1465
(Tools as any).mockImplementation(() => ({
1482
- get: vi.fn().mockResolvedValue('mocked-wrapped-tools'),
1466
+ getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
1467
+ wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
1468
}));
1469
});
1470
@@ -1495,13 +1480,17 @@ describe('ToolRouter', () => {
1480
});
1481
1482
const toolsInstance = (Tools as any).mock.results[0].value;
1498
- expect(toolsInstance.get).toHaveBeenCalledWith(
1499
- userId,
1483
+ expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1484
{
1485
tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
1486
},
1487
undefined
1488
);
1489
+ expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1490
+ sessionId,
1491
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
1492
+ undefined
1493
+ );
1494
1495
expect(tools).toBe('mocked-wrapped-tools');
1496
});
@@ -1514,17 +1503,22 @@ describe('ToolRouter', () => {
1503
...tool,
1504
description: 'Modified description',
1505
})),
1506
+ beforeExecute: vi.fn(),
1507
};
1508
1509
const session = await toolRouter.create(userId);
1510
const tools = await session.tools(modifiers);
1511
1512
const toolsInstance = (Tools as any).mock.results[0].value;
1523
- expect(toolsInstance.get).toHaveBeenCalledWith(
1524
- userId,
1513
+ expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1514
{
1515
tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
1516
},
1517
+ { modifySchema: modifiers.modifySchema }
1518
+ );
1519
+ expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1520
+ sessionId,
1521
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
1522
modifiers
1523
);
1524
@@ -1535,7 +1529,8 @@ describe('ToolRouter', () => {
1529
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1530
1531
(Tools as any).mockImplementation(() => ({
1538
- get: vi.fn().mockRejectedValue(new Error('Failed to fetch tools')),
1532
+ getRawComposioTools: vi.fn().mockRejectedValue(new Error('Failed to fetch tools')),
1533
+ wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
1534
}));
1535
1536
const session = await toolRouter.create(userId);
@@ -1552,27 +1547,35 @@ describe('ToolRouter', () => {
1547
const session = await toolRouter.create(userId);
1548
1549
// Each call to session.tools() creates a new Tools instance
1555
- // So we need to check that Tools was called twice and each instance's get method was called once
1550
+ // So we need to check that Tools was called twice and each instance's methods were called
1551
await session.tools(modifier1);
1552
await session.tools(modifier2);
1553
1554
expect(Tools).toHaveBeenCalledTimes(2);
1555
1556
const firstToolsInstance = (Tools as any).mock.results[0].value;
1562
- expect(firstToolsInstance.get).toHaveBeenCalledWith(
1563
- userId,
1557
+ expect(firstToolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1558
{
1559
tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
1560
},
1561
+ { modifySchema: modifier1.modifySchema }
1562
+ );
1563
+ expect(firstToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1564
+ sessionId,
1565
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
1566
modifier1
1567
);
1568
1569
const secondToolsInstance = (Tools as any).mock.results[1].value;
1571
- expect(secondToolsInstance.get).toHaveBeenCalledWith(
1572
- userId,
1570
+ expect(secondToolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1571
{
1572
tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
1573
},
1574
+ { modifySchema: modifier2.modifySchema }
1575
+ );
1576
+ expect(secondToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1577
+ sessionId,
1578
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
1579
modifier2
1580
);
1581
});
@@ -1594,13 +1597,17 @@ describe('ToolRouter', () => {
1597
apiKey: 'test-api-key',
1598
});
1599
const toolsInstance = (Tools as any).mock.results[0].value;
1597
- expect(toolsInstance.get).toHaveBeenCalledWith(
1598
- userId,
1600
+ expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1601
{
1602
tools: ['CUSTOM_TOOL_1', 'CUSTOM_TOOL_2'],
1603
},
1604
undefined
1605
);
1606
+ expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1607
+ 'custom_session_123',
1608
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
1609
+ undefined
1610
+ );
1611
});
1612
1613
it('should handle empty tool router tools array', async () => {
@@ -1620,13 +1627,17 @@ describe('ToolRouter', () => {
1627
apiKey: 'test-api-key',
1628
});
1629
const toolsInstance = (Tools as any).mock.results[0].value;
1623
- expect(toolsInstance.get).toHaveBeenCalledWith(
1624
- userId,
1630
+ expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1631
{
1632
tools: [],
1633
},
1634
undefined
1635
);
1636
+ expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1637
+ 'empty_session_123',
1638
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
1639
+ undefined
1640
+ );
1641
});
1642
});
1643
@@ -1748,7 +1759,7 @@ describe('ToolRouter', () => {
1759
expect(session).toHaveProperty('toolkits');
1760
});
1761
1751
- it('should return a session with correct user ID from config', async () => {
1762
+ it('should return a session with correct session ID', async () => {
1763
const customResponse = {
1764
...mockSessionRetrieveResponse,
1765
config: {
@@ -1762,7 +1773,7 @@ describe('ToolRouter', () => {
1773
const session = await toolRouter.use(sessionId);
1774
1775
expect(session.sessionId).toBe('session_123');
1765
- // The tools function should be created with the correct user ID from config
1776
+ // The tools function should be created with the session ID
1777
expect(session.tools).toBeDefined();
1778
});
1779
@@ -1775,6 +1786,19 @@ describe('ToolRouter', () => {
1786
1787
expect(tools).toBe('mocked-wrapped-tools');
1788
expect(Tools).toHaveBeenCalled();
1789
+
1790
+ const toolsInstance = (Tools as any).mock.results[0].value;
1791
+ expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
1792
+ {
1793
+ tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
1794
+ },
1795
+ undefined
1796
+ );
1797
+ expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
1798
+ sessionId,
1799
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
1800
+ undefined
1801
+ );
1802
});
1803
1804
it('should return a session with working authorize function', async () => {
ts/packages/core/test/tools/tools.test.ts
+320
@@ -721,6 +721,326 @@ describe('Tools', () => {
721
});
722
});
723
724
+ describe('Tool Router Execution', () => {
725
+ const sessionId = 'test-session-123';
726
+
727
+ describe('executeMetaTool', () => {
728
+ it('should execute a tool via tool router session', async () => {
729
+ const toolSlug = 'COMPOSIO_TOOL';
730
+ const body = {
731
+ sessionId,
732
+ arguments: { query: 'test' },
733
+ };
734
+
735
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
736
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(
737
+ toolMocks.transformedTool as unknown as Tool
738
+ );
739
+
740
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
741
+ data: { results: true },
742
+ error: null,
743
+ log_id: '123',
744
+ });
745
+
746
+ const result = await context.tools.executeMetaTool(toolSlug, body);
747
+
748
+ expect(mockClient.toolRouter.session.executeMeta).toHaveBeenCalledWith(sessionId, {
749
+ slug: toolSlug,
750
+ arguments: body.arguments,
751
+ });
752
+ expect(result).toEqual({
753
+ data: { results: true },
754
+ error: null,
755
+ successful: true,
756
+ logId: '123',
757
+ });
758
+ });
759
+
760
+ it('should throw validation error for invalid parameters', async () => {
761
+ const invalidBody = {
762
+ // missing sessionId
763
+ arguments: { query: 'test' },
764
+ } as any;
765
+
766
+ await expect(context.tools.executeMetaTool('COMPOSIO_TOOL', invalidBody)).rejects.toThrow(
767
+ 'Invalid tool execute meta parameters'
768
+ );
769
+ });
770
+
771
+ it('should throw error if tool is not found', async () => {
772
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
773
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(undefined as any);
774
+
775
+ await expect(
776
+ context.tools.executeMetaTool('NONEXISTENT_TOOL', {
777
+ sessionId,
778
+ arguments: { query: 'test' },
779
+ })
780
+ ).rejects.toThrow('Tool NONEXISTENT_TOOL not found');
781
+ });
782
+
783
+ it('should apply beforeExecute modifier', async () => {
784
+ const toolSlug = 'COMPOSIO_TOOL';
785
+ const body = {
786
+ sessionId,
787
+ arguments: { query: 'original' },
788
+ };
789
+
790
+ const toolWithToolkit = {
791
+ ...toolMocks.transformedTool,
792
+ toolkit: { slug: 'test-toolkit', name: 'Test Toolkit' },
793
+ };
794
+
795
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
796
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(toolWithToolkit as unknown as Tool);
797
+
798
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
799
+ data: { results: true },
800
+ error: null,
801
+ log_id: '123',
802
+ });
803
+
804
+ const beforeExecute = vi.fn().mockImplementation(({ params }) => ({
805
+ ...params,
806
+ query: 'modified',
807
+ }));
808
+
809
+ await context.tools.executeMetaTool(toolSlug, body, { beforeExecute });
810
+
811
+ expect(beforeExecute).toHaveBeenCalledWith({
812
+ toolSlug,
813
+ toolkitSlug: 'test-toolkit',
814
+ params: { query: 'original' },
815
+ });
816
+
817
+ expect(mockClient.toolRouter.session.executeMeta).toHaveBeenCalledWith(sessionId, {
818
+ slug: toolSlug,
819
+ arguments: { query: 'modified' },
820
+ });
821
+ });
822
+
823
+ it('should apply afterExecute modifier', async () => {
824
+ const toolSlug = 'COMPOSIO_TOOL';
825
+ const body = {
826
+ sessionId,
827
+ arguments: { query: 'test' },
828
+ };
829
+
830
+ const toolWithToolkit = {
831
+ ...toolMocks.transformedTool,
832
+ toolkit: { slug: 'test-toolkit', name: 'Test Toolkit' },
833
+ };
834
+
835
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
836
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(toolWithToolkit as unknown as Tool);
837
+
838
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
839
+ data: { results: true },
840
+ error: null,
841
+ log_id: '123',
842
+ });
843
+
844
+ const afterExecute = vi.fn().mockImplementation(({ result }) => ({
845
+ ...result,
846
+ data: { results: 'modified result' },
847
+ }));
848
+
849
+ const result = await context.tools.executeMetaTool(toolSlug, body, { afterExecute });
850
+
851
+ expect(afterExecute).toHaveBeenCalledWith({
852
+ toolSlug,
853
+ toolkitSlug: 'test-toolkit',
854
+ result: {
855
+ data: { results: true },
856
+ error: null,
857
+ successful: true,
858
+ logId: '123',
859
+ },
860
+ });
861
+
862
+ expect(result.data).toEqual({ results: 'modified result' });
863
+ });
864
+
865
+ it('should handle error responses from tool router', async () => {
866
+ const toolSlug = 'COMPOSIO_TOOL';
867
+ const body = {
868
+ sessionId,
869
+ arguments: { query: 'test' },
870
+ };
871
+
872
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
873
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(
874
+ toolMocks.transformedTool as unknown as Tool
875
+ );
876
+
877
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
878
+ data: null,
879
+ error: 'Something went wrong',
880
+ log_id: '456',
881
+ });
882
+
883
+ const result = await context.tools.executeMetaTool(toolSlug, body);
884
+
885
+ expect(result).toEqual({
886
+ data: null,
887
+ error: 'Something went wrong',
888
+ successful: false,
889
+ logId: '456',
890
+ });
891
+ });
892
+
893
+ it('should handle tool without toolkit gracefully', async () => {
894
+ const toolSlug = 'TOOL_WITHOUT_TOOLKIT';
895
+ const body = {
896
+ sessionId,
897
+ arguments: { query: 'test' },
898
+ };
899
+
900
+ const toolWithoutToolkit = {
901
+ ...toolMocks.transformedTool,
902
+ toolkit: undefined,
903
+ };
904
+
905
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
906
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(toolWithoutToolkit as unknown as Tool);
907
+
908
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
909
+ data: { results: true },
910
+ error: null,
911
+ log_id: '123',
912
+ });
913
+
914
+ const beforeExecute = vi.fn().mockImplementation(({ params }) => params);
915
+
916
+ await context.tools.executeMetaTool(toolSlug, body, { beforeExecute });
917
+
918
+ expect(beforeExecute).toHaveBeenCalledWith({
919
+ toolSlug,
920
+ toolkitSlug: 'unknown',
921
+ params: { query: 'test' },
922
+ });
923
+ });
924
+ });
925
+
926
+ describe('wrapToolsForToolRouter', () => {
927
+ it('should wrap tools with tool router execute function', async () => {
928
+ const tools = [toolMocks.transformedTool as unknown as Tool];
929
+
930
+ context.mockProvider.wrapTools.mockReturnValueOnce('wrapped-tools');
931
+
932
+ const result = context.tools.wrapToolsForToolRouter(sessionId, tools);
933
+
934
+ expect(context.mockProvider.wrapTools).toHaveBeenCalledWith(tools, expect.any(Function));
935
+ expect(result).toBe('wrapped-tools');
936
+ });
937
+
938
+ it('should create execute function that calls executeMetaTool', async () => {
939
+ const tools = [toolMocks.transformedTool as unknown as Tool];
940
+
941
+ let capturedExecuteFn: (toolSlug: string, input: Record<string, unknown>) => Promise<any>;
942
+
943
+ context.mockProvider.wrapTools.mockImplementation((tools, executeFn) => {
944
+ capturedExecuteFn = executeFn;
945
+ return 'wrapped-tools';
946
+ });
947
+
948
+ context.tools.wrapToolsForToolRouter(sessionId, tools);
949
+
950
+ // Setup mocks for execution
951
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
952
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(
953
+ toolMocks.transformedTool as unknown as Tool
954
+ );
955
+
956
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
957
+ data: { results: true },
958
+ error: null,
959
+ log_id: '123',
960
+ });
961
+
962
+ // Call the captured execute function
963
+ const result = await capturedExecuteFn!('COMPOSIO_TOOL', { query: 'test' });
964
+
965
+ expect(mockClient.toolRouter.session.executeMeta).toHaveBeenCalledWith(sessionId, {
966
+ slug: 'COMPOSIO_TOOL',
967
+ arguments: { query: 'test' },
968
+ });
969
+ expect(result).toEqual({
970
+ data: { results: true },
971
+ error: null,
972
+ successful: true,
973
+ logId: '123',
974
+ });
975
+ });
976
+
977
+ it('should pass modifiers to the execute function', async () => {
978
+ const tools = [toolMocks.transformedTool as unknown as Tool];
979
+ const modifiers = {
980
+ beforeExecute: vi.fn().mockImplementation(({ params }) => ({
981
+ ...params,
982
+ modified: true,
983
+ })),
984
+ };
985
+
986
+ let capturedExecuteFn: (toolSlug: string, input: Record<string, unknown>) => Promise<any>;
987
+
988
+ context.mockProvider.wrapTools.mockImplementation((tools, executeFn) => {
989
+ capturedExecuteFn = executeFn;
990
+ return 'wrapped-tools';
991
+ });
992
+
993
+ context.tools.wrapToolsForToolRouter(sessionId, tools, modifiers);
994
+
995
+ // Setup mocks for execution
996
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
997
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(
998
+ toolMocks.transformedTool as unknown as Tool
999
+ );
1000
+
1001
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
1002
+ data: { results: true },
1003
+ error: null,
1004
+ log_id: '123',
1005
+ });
1006
+
1007
+ // Call the captured execute function
1008
+ await capturedExecuteFn!('COMPOSIO_TOOL', { query: 'test' });
1009
+
1010
+ expect(modifiers.beforeExecute).toHaveBeenCalled();
1011
+ expect(mockClient.toolRouter.session.executeMeta).toHaveBeenCalledWith(sessionId, {
1012
+ slug: 'COMPOSIO_TOOL',
1013
+ arguments: { query: 'test', modified: true },
1014
+ });
1015
+ });
1016
+
1017
+ it('should handle multiple tools', async () => {
1018
+ const tools = [
1019
+ toolMocks.transformedTool as unknown as Tool,
1020
+ { ...toolMocks.transformedTool, slug: 'ANOTHER_TOOL' } as unknown as Tool,
1021
+ ];
1022
+
1023
+ context.mockProvider.wrapTools.mockReturnValueOnce('wrapped-tools');
1024
+
1025
+ const result = context.tools.wrapToolsForToolRouter(sessionId, tools);
1026
+
1027
+ expect(context.mockProvider.wrapTools).toHaveBeenCalledWith(tools, expect.any(Function));
1028
+ expect(result).toBe('wrapped-tools');
1029
+ });
1030
+
1031
+ it('should handle empty tools array', async () => {
1032
+ const tools: Tool[] = [];
1033
+
1034
+ context.mockProvider.wrapTools.mockReturnValueOnce([]);
1035
+
1036
+ const result = context.tools.wrapToolsForToolRouter(sessionId, tools);
1037
+
1038
+ expect(context.mockProvider.wrapTools).toHaveBeenCalledWith([], expect.any(Function));
1039
+ expect(result).toEqual([]);
1040
+ });
1041
+ });
1042
+ });
1043
+
1044
describe('Version Integration Tests', () => {
1045
describe('toolkit versions in tool fetching', () => {
1046
it('should pass default "latest" version when no version is configured', async () => {
ts/packages/core/test/utils/mocks/client.mock.ts
+5
@@ -16,4 +16,9 @@ export const mockClient = {
16
toolkits: {
17
retrieve: vi.fn(),
18
},
19
+ toolRouter: {
20
+ session: {
21
+ executeMeta: vi.fn(),
22
+ },
23
+ },
24
};