Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Add native tool support for tool router TS SDK (#2249)

Musthaq Ahamad07551cd174ef
diff --git a/.changeset/bumpy-jars-turn.md b/.changeset/bumpy-jars-turn.md
new file mode 100644
index 000000000..75b3bf6bb
--- /dev/null
+++ b/.changeset/bumpy-jars-turn.md
@@ -0,0 +1,5 @@
+---
+'@composio/core': patch
+---
+
+Add support for native tool execution in tool router
diff --git a/.github/workflows/ts.audit.yml b/.github/workflows/ts.audit.yml
index d359779fc..71a334f3d 100644
--- a/.github/workflows/ts.audit.yml
+++ b/.github/workflows/ts.audit.yml
@@ -39,7 +39,7 @@ jobs:
if: steps.audit.outcome == 'failure' && github.event_name == 'pull_request'
run: |
{
- echo "⚠️ **Security Audit Failed**"
+ echo "⚠️ **Security Audit Warning**"
echo ""
echo "The \`pnpm audit --prod\` check found security vulnerabilities in production dependencies."
echo ""
@@ -63,9 +63,3 @@ jobs:
uses: thollander/[email protected]
with:
file-path: audit-comment.txt
-
- - name: Fail if audit failed (push events)
- if: steps.audit.outcome == 'failure' && github.event_name == 'push'
- run: |
- echo "Security vulnerabilities found in production dependencies. Please fix them before merging."
- exit 1
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 449d9d42c..3f5b0182d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -13,8 +13,8 @@ catalogs:
specifier: ^4.20250917.0
version: 4.20250917.0
'@composio/client':
- specifier: 0.1.0-alpha.47
- version: 0.1.0-alpha.47
+ specifier: 0.1.0-alpha.50
+ version: 0.1.0-alpha.50
'@modelcontextprotocol/sdk':
specifier: ^1.24.0
version: 1.24.1
@@ -637,8 +637,8 @@ importers:
ts/examples/tool-router:
dependencies:
'@ai-sdk/mcp':
- specifier: ^0.0.10
- version: 0.0.10([email protected])
+ specifier: ^0.0.11
+ version: 0.0.11([email protected])
'@ai-sdk/openai':
specifier: ^2.0.72
version: 2.0.77([email protected])
@@ -806,7 +806,7 @@ importers:
version: 1.0.0-alpha.1
'@composio/client':
specifier: 'catalog:'
- version: 0.1.0-alpha.47
+ version: 0.1.0-alpha.50
'@composio/core':
specifier: workspace:*
version: link:../core
@@ -900,7 +900,7 @@ importers:
dependencies:
'@composio/client':
specifier: 'catalog:'
- version: 0.1.0-alpha.47
+ version: 0.1.0-alpha.50
'@composio/json-schema-to-zod':
specifier: workspace:*
version: link:../json-schema-to-zod
@@ -1255,8 +1255,8 @@ packages:
peerDependencies:
zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-BZ7DQkFFg+oTrLkoAHyd7E8tKbPCR2flVo75ruxjQejPt5gXIVcEXhgC1aE8yvuL9O/rGQ+pzYVRAsU0gX2FmA==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-n0oZsxhPdMaXhAn6LrpMpxABufmeSatfhR3epbrCjJcLEHPOucKwQciwE8CTgIGgwBxHNy1FFLZmcFI77JmJfg==}
engines: {node: '>=18'}
peerDependencies:
zod: ^3.25.76 || ^4.1.8
@@ -1583,8 +1583,8 @@ packages:
'@cloudflare/[email protected]':
resolution: {integrity: sha512-Lsn9dZoRYZZCXXHZNa50cMP8kWhQZG9M7WjxNSiXFzC8bk4Wh/0SYYo4YINxEjEt6h2o69LmAhFaJ+qgaJTh8Q==}
- '@composio/[email protected]':
- resolution: {integrity: sha512-ggrfbsDrntwBhRn+kncKluISKys9lePNQsJLGS6j/mfH4RBFjtDT4almw3N9vnOwJb0q4OIb/hrmAxZvwsc0Iw==}
+ '@composio/[email protected]':
+ resolution: {integrity: sha512-+7LE16XL2D0Z90y0PdBGLDyi9qi8P4TyqTqj2Kwa930rhDaZOkFMmAx9BbjXmx0KWjqpSxwxszcW7FgNpX5jqw==}
'@composio/[email protected]':
resolution: {integrity: sha512-IpbfST0SSs/CEv+PIf6+EL0feNuJhQyUrOHJLPge8NhyLLrCyVqvujRIPyRUUjy0NDsked/Mm5VpJmYM6OACbg==}
@@ -2068,6 +2068,7 @@ packages:
resolution: {integrity: sha512-fL656yBPiWebtfGItvtXLWrFNGlF1NcDFS0WdMQXMs9LluVg0CfT5E2oXYp0pidl0vVG53XkW55ysijNkU5/hA==}
+ 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'
peerDependencies:
zod: ^4.0.14
@@ -5869,6 +5870,7 @@ packages:
resolution: {integrity: sha512-Ka0/iNBblPFcIubTA1Jjh6gvwqfjrGq1Y2MTI5lbjeLIAfmC+p5bQmojpRZqgHHVu5cG4+qdIiwXiBSm/8lZ3w==}
engines: {node: '>=20.9.0'}
+ deprecated: This version has a security vulnerability. Please upgrade to a patched version. See https://nextjs.org/blog/CVE-2025-66478 for more details.
hasBin: true
peerDependencies:
'@opentelemetry/api': ^1.1.0
@@ -7520,10 +7522,10 @@ snapshots:
'@ai-sdk/provider-utils': 3.0.17([email protected])
zod: 4.1.12
dependencies:
'@ai-sdk/provider': 2.0.0
- '@ai-sdk/provider-utils': 3.0.17([email protected])
+ '@ai-sdk/provider-utils': 3.0.18([email protected])
pkce-challenge: 5.0.0
zod: 4.1.12
@@ -7950,7 +7952,7 @@ snapshots:
'@cloudflare/[email protected]': {}
- '@composio/[email protected]': {}
+ '@composio/[email protected]': {}
'@composio/[email protected]': {}
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 6464d7d44..9f219ad26 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -15,7 +15,7 @@ packages:
catalog:
'@cloudflare/vitest-pool-workers': ^0.9.2
'@cloudflare/workers-types': ^4.20250917.0
- '@composio/client': 0.1.0-alpha.47
+ '@composio/client': 0.1.0-alpha.50
'@modelcontextprotocol/sdk': ^1.24.0
ai: 5.0.52
openai: ^5.20.3
diff --git a/ts/docs/api/tool-router.md b/ts/docs/api/tool-router.md
index 8ef0e1fce..9d1b012fb 100644
--- a/ts/docs/api/tool-router.md
+++ b/ts/docs/api/tool-router.md
@@ -127,28 +127,41 @@ const session = await composio.experimental.create('user_123', {
### `tools`
-Fine-grained control over which tools are available within toolkits.
+Fine-grained control over which tools are available within toolkits. Configure tools per toolkit using the toolkit slug as the key.
```typescript
const session = await composio.experimental.create('user_123', {
- toolkits: ['gmail'],
+ toolkits: ['gmail', 'slack'],
tools: {
- // Override tools per toolkit
- overrides: {
- gmail: ['gmail_fetch_emails', 'gmail_send_email'], // Only these tools
- // OR use enabled/disabled objects
- // gmail: { enabled: ['gmail_fetch_emails'] }
- // gmail: { disabled: ['gmail_delete_email'] }
- },
- // Filter by tags
- tags: ['email', 'messaging']
- // OR use enabled/disabled
- // tags: { enabled: ['email'] }
- // tags: { disabled: ['destructive'] }
+ // Configure tools per toolkit
+ gmail: ['gmail_fetch_emails', 'gmail_send_email'], // Only these tools
+ // OR use enabled/disabled objects
+ // gmail: { enabled: ['gmail_fetch_emails'] }
+ // gmail: { disabled: ['gmail_delete_email'] }
+
+ // You can also set tags per toolkit to override global tags
+ slack: { tags: ['readOnlyHint'] }
}
});
```
+### `tags`
+
+Global tags to filter tools by their behavior hints. Tags can be overridden per toolkit in the `tools` configuration.
+
+```typescript
+const session = await composio.experimental.create('user_123', {
+ toolkits: ['gmail', 'github'],
+ // Global tags applied to all toolkits
+ tags: ['readOnlyHint', 'idempotentHint']
+});
+```
+
+Available tags:
+- `readOnlyHint` - Tools that only read data
+- `destructiveHint` - Tools that modify or delete data
+- `idempotentHint` - Tools that can be safely retried
+
### `authConfigs`
Map toolkits to specific authentication configurations:
@@ -192,22 +205,21 @@ const session = await composio.experimental.create('user_123', {
toolkits: ['gmail'],
manageConnections: {
enabled: true,
- callbackUri: 'https://your-app.com/auth/callback',
- inferScopesFromTools: true // Infer OAuth scopes from allowed tools
+ callbackUrl: 'https://your-app.com/auth/callback'
}
});
```
-### `execution`
+### `workbench`
-Configure tool execution behavior:
+Configure workbench behavior for tool execution:
```typescript
const session = await composio.experimental.create('user_123', {
toolkits: ['gmail'],
- execution: {
+ workbench: {
proxyExecutionEnabled: true,
- timeoutSeconds: 30
+ autoOffloadThreshold: 400000 // Automatically offload to workbench if response > 400k characters
}
});
```
@@ -230,8 +242,8 @@ The MCP server configuration for this session, including authentication headers.
```typescript
console.log(session.mcp.url); // The URL to connect to
-console.log(session.mcp.type); // 'HTTP' or 'SSE'
-console.log(session.mcp.headers); // Authentication headers (includes x-api-key)
+console.log(session.mcp.type); // 'http' or 'sse'
+console.log(session.mcp.headers); // Authentication headers (includes x-api-key if configured)
```
### `tools()`
@@ -352,7 +364,12 @@ import { stepCountIs, streamText } from 'ai';
const composio = new Composio();
const { mcp } = await composio.experimental.create('user_123', {
toolkits: ['gmail'],
- manageConnections: true
+ manageConnections: true,
+ tools: {
+ gmail: {
+ disabled: ['gmail_send_email'], // Disable specific tools
+ }
+ }
});
// Create MCP client using the session URL and headers
@@ -360,7 +377,7 @@ const client = await createMCPClient({
transport: {
type: 'http',
url: mcp.url,
- headers: mcp.headers, // Uses pre-configured authentication headers
+ headers: mcp.headers // Uses pre-configured authentication headers
}
});
@@ -410,7 +427,7 @@ const client = new MultiServerMCPClient({
composio: {
transport: "http",
url: session.mcp.url,
- headers: session.mcp.headers, // Uses pre-configured authentication headers
+ headers: session.mcp.headers // Uses pre-configured authentication headers
},
});
@@ -451,7 +468,7 @@ console.log(`Connecting to MCP server: ${session.mcp.url}`);
const mcpTool = hostedMcpTool({
serverLabel: 'ComposioApps',
serverUrl: session.mcp.url,
- headers: session.mcp.headers, // Uses pre-configured authentication headers
+ headers: session.mcp.headers // Uses pre-configured authentication headers
});
const agent = new Agent({
@@ -497,7 +514,7 @@ const stream = await query({
composio: {
type: 'http',
url: session.mcp.url,
- headers: session.mcp.headers, // Uses pre-configured authentication headers
+ headers: session.mcp.headers // Uses pre-configured authentication headers
}
},
}
@@ -620,7 +637,7 @@ const tools = await session.tools(modifiers);
3. **Connection Management**: Use `manageConnections: true` (default) for interactive applications where users can be prompted to connect accounts.
-4. **Scope Inference**: Enable `inferScopesFromTools` when you want OAuth scopes to be automatically derived from the tools you've enabled.
+4. **Tag Filtering**: Use global `tags` to filter tools by their behavior (readOnlyHint, destructiveHint, idempotentHint) and override per toolkit when needed.
5. **Session Reuse**: Store and reuse `sessionId` to maintain user sessions across requests.
@@ -643,20 +660,22 @@ if (sessionId) {
```typescript
interface ToolRouterCreateSessionConfig {
toolkits?: string[] | { enabled: string[] } | { disabled: string[] };
- tools?: {
- overrides?: Record<string, string[] | { enabled: string[] } | { disabled: string[] }>;
- tags?: string[] | { enabled: string[] } | { disabled: string[] };
- };
+ tools?: Record<string,
+ string[] |
+ { enabled: string[] } |
+ { disabled: string[] } |
+ { tags: ('readOnlyHint' | 'destructiveHint' | 'idempotentHint')[] }
+ >;
+ tags?: ('readOnlyHint' | 'destructiveHint' | 'idempotentHint')[];
authConfigs?: Record<string, string>;
connectedAccounts?: Record<string, string>;
manageConnections?: boolean | {
enabled?: boolean;
- callbackUri?: string;
- inferScopesFromTools?: boolean;
+ callbackUrl?: string;
};
- execution?: {
+ workbench?: {
proxyExecutionEnabled?: boolean;
- timeoutSeconds?: number;
+ autoOffloadThreshold?: number;
};
}
```
@@ -667,9 +686,9 @@ interface ToolRouterCreateSessionConfig {
interface ToolRouterSession {
sessionId: string;
mcp: {
- type: 'HTTP' | 'SSE';
+ type: 'http' | 'sse';
url: string;
- headers?: Record<string, string | undefined>; // Authentication headers (includes x-api-key)
+ headers?: Record<string, string>; // Authentication headers (includes x-api-key if configured)
};
tools: (modifiers?: ProviderOptions) => Promise<Tools>;
authorize: (toolkit: string, options?: { callbackUrl?: string }) => Promise<ConnectionRequest>;
diff --git a/ts/examples/tool-router/package.json b/ts/examples/tool-router/package.json
index 296a05ad5..a1739a5b7 100644
--- a/ts/examples/tool-router/package.json
+++ b/ts/examples/tool-router/package.json
@@ -18,7 +18,7 @@
"license": "ISC",
"packageManager": "[email protected]",
"dependencies": {
- "@ai-sdk/mcp": "^0.0.10",
+ "@ai-sdk/mcp": "^0.0.11",
"@ai-sdk/openai": "^2.0.72",
"@anthropic-ai/claude-agent-sdk": "^0.1.55",
"@composio/core": "workspace:*",
diff --git a/ts/examples/tool-router/src/claude-agents-sdk.ts b/ts/examples/tool-router/src/claude-agents-sdk.ts
index 719335287..0453a3787 100644
--- a/ts/examples/tool-router/src/claude-agents-sdk.ts
+++ b/ts/examples/tool-router/src/claude-agents-sdk.ts
@@ -15,9 +15,7 @@ const stream = await query({
composio: {
type: 'http',
url: session.mcp.url,
- headers: {
- 'x-api-key': process.env.COMPOSIO_API_KEY!,
- }
+ headers: session.mcp.headers
}
},
diff --git a/ts/examples/tool-router/src/index.ts b/ts/examples/tool-router/src/index.ts
index 645fe8ce2..d2150a288 100644
--- a/ts/examples/tool-router/src/index.ts
+++ b/ts/examples/tool-router/src/index.ts
@@ -7,6 +7,8 @@ const composio = new Composio({
provider: new VercelProvider(),
});
const session = await composio.experimental.create('user_123', { toolkits: ['gmail'] });
+
+
const tools = await session.tools();
const stream = await streamText({
diff --git a/ts/examples/tool-router/src/langchain.ts b/ts/examples/tool-router/src/langchain.ts
index 6efede0c1..77a81482c 100644
--- a/ts/examples/tool-router/src/langchain.ts
+++ b/ts/examples/tool-router/src/langchain.ts
@@ -18,9 +18,7 @@ async function main() {
math: {
transport: "http",
url: session.mcp.url,
- headers: {
- 'x-api-key': process.env.COMPOSIO_API_KEY!,
- }
+ headers: session.mcp.headers
},
});
diff --git a/ts/examples/tool-router/src/mcp.ts b/ts/examples/tool-router/src/mcp.ts
index 96f66f5f5..0947100f1 100644
--- a/ts/examples/tool-router/src/mcp.ts
+++ b/ts/examples/tool-router/src/mcp.ts
@@ -6,7 +6,15 @@ import ora from 'ora';
const composio = new Composio();
const trProgress = ora("Creating tool router session...").start();
-const { mcp } = await composio.experimental.create('dhawal', { toolkits: ['gmail'], manageConnections: true });
+const { mcp } = await composio.experimental.create('dhawal', {
+ toolkits: ['gmail'],
+ manageConnections: true,
+ tools: {
+ 'gmail': {
+ enabled: ['gmail_search_emails'],
+ }
+ }
+});
trProgress.succeed(`Tool router session created: ${mcp.url}`);
const mcpProgress = ora("Retrieving tools from MCP...").start();
@@ -14,9 +22,7 @@ const client = await createMCPClient({
transport: {
type: 'http',
url: mcp.url,
- headers: {
- 'x-api-key': process.env.COMPOSIO_API_KEY!,
- }
+ headers: mcp.headers
}
});
diff --git a/ts/examples/tool-router/src/openai-agents.ts b/ts/examples/tool-router/src/openai-agents.ts
index dd2ee4898..1d1ec13f0 100644
--- a/ts/examples/tool-router/src/openai-agents.ts
+++ b/ts/examples/tool-router/src/openai-agents.ts
@@ -11,9 +11,7 @@ console.log(`Connecting to MCP server: ${session.mcp.url}`);
const mcpTool = hostedMcpTool({
serverLabel: 'ComposioApps',
serverUrl: session.mcp.url,
- headers: {
- 'x-api-key': process.env.COMPOSIO_API_KEY!,
- }
+ headers: session.mcp.headers
});
diff --git a/ts/packages/core/package.json b/ts/packages/core/package.json
index 9be896719..a7dba4e64 100644
--- a/ts/packages/core/package.json
+++ b/ts/packages/core/package.json
@@ -42,8 +42,8 @@
"devDependencies": {
"@type-challenges/utils": "^0.1.1",
"@types/semver": "^7.7.0",
- "tsup": "catalog:",
"tsdown": "catalog:",
+ "tsup": "catalog:",
"tsx": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
diff --git a/ts/packages/core/src/lib/toolRouterParams.ts b/ts/packages/core/src/lib/toolRouterParams.ts
index 57b900296..68e16b7c8 100644
--- a/ts/packages/core/src/lib/toolRouterParams.ts
+++ b/ts/packages/core/src/lib/toolRouterParams.ts
@@ -1,53 +1,54 @@
import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';
-import { ToolRouterConfigTools } from '../types/toolRouter.types';
+import {
+ ToolRouterConfigTools,
+ ToolRouterConfigToolsSchema,
+ ToolRouterToolsParam,
+} from '../types/toolRouter.types';
+import { ValidationError } from '../errors';
export const transformToolRouterToolsParams = (
- params?: ToolRouterConfigTools | undefined
-): SessionCreateParams.Tools | undefined => {
+ params?: Record<string, ToolRouterToolsParam | ToolRouterConfigTools> | undefined
+):
+ | Record<
+ string,
+ SessionCreateParams.Enable | SessionCreateParams.Disable | SessionCreateParams.Tags
+ >
+ | undefined => {
if (!params) {
return undefined;
}
- const { overrides, tags } = params;
-
- const toolOverrides = overrides
- ? Object.keys(overrides).reduce(
- (acc, key) => {
- const override = overrides[key];
- if (Array.isArray(override)) {
- acc[key] = { enabled: override };
- } else if (override !== undefined) {
- if ('enabled' in override && override.enabled) {
- acc[key] = { enabled: override.enabled };
- } else if ('disabled' in override && override.disabled) {
- acc[key] = { disabled: override.disabled };
+ if (typeof params === 'object') {
+ const result = Object.keys(params).reduce(
+ (acc, key) => {
+ if (Array.isArray(params[key])) {
+ acc[key] = { enable: params[key] };
+ } else if (typeof params[key] === 'object') {
+ const parsedResult = ToolRouterConfigToolsSchema.safeParse(params[key]);
+ if (parsedResult.success) {
+ const data = parsedResult.data;
+ if (Array.isArray(data)) {
+ acc[key] = { enable: data };
+ } else if ('enable' in data) {
+ acc[key] = { enable: data.enable };
+ } else if ('disable' in data) {
+ acc[key] = { disable: data.disable };
+ } else if ('tags' in data) {
+ acc[key] = { tags: data.tags };
}
+ } else {
+ throw new ValidationError(parsedResult.error.message);
}
- return acc;
- },
- {} as Record<string, SessionCreateParams.Tools.Enabled | SessionCreateParams.Tools.Disabled>
- )
- : undefined;
-
- const tagFilters = tags
- ? (() => {
- if (Array.isArray(tags)) {
- return { include: tags };
- } else if ('enabled' in tags && tags.enabled) {
- return { include: tags.enabled };
- } else if ('disabled' in tags && tags.disabled) {
- return { exclude: tags.disabled };
+ } else {
+ acc[key] = { enable: params[key] };
}
- return undefined;
- })()
- : undefined;
-
- return {
- overrides: toolOverrides,
- filters: tagFilters
- ? {
- tags: tagFilters,
- }
- : undefined,
- };
+ return acc;
+ },
+ {} as Record<
+ string,
+ SessionCreateParams.Enable | SessionCreateParams.Disable | SessionCreateParams.Tags
+ >
+ );
+ return result;
+ }
};
diff --git a/ts/packages/core/src/models/ConnectedAccounts.ts b/ts/packages/core/src/models/ConnectedAccounts.ts
index b49737e29..592bd0657 100644
--- a/ts/packages/core/src/models/ConnectedAccounts.ts
+++ b/ts/packages/core/src/models/ConnectedAccounts.ts
@@ -89,7 +89,6 @@ export class ConnectedAccounts {
rawQuery = {
auth_config_ids: parsedQuery.data.authConfigIds,
cursor: parsedQuery.data.cursor?.toString(),
- labels: parsedQuery.data.labels,
limit: parsedQuery.data.limit,
order_by: parsedQuery.data.orderBy,
statuses: parsedQuery.data.statuses,
diff --git a/ts/packages/core/src/models/ToolRouter.ts b/ts/packages/core/src/models/ToolRouter.ts
index ec1298701..7e67164c9 100644
--- a/ts/packages/core/src/models/ToolRouter.ts
+++ b/ts/packages/core/src/models/ToolRouter.ts
@@ -9,7 +9,12 @@
* const composio = new Composio();
* const userId = 'user_123';
*
- * const session = await composio.create(userId);
+ * const session = await composio.experimental.create(userId, {
+ * toolkits: ['gmail'],
+ * manageConnections: true
+ * });
+ *
+ * console.log(session.mcp.url);
* ```
*/
import { Composio as ComposioClient } from '@composio/client';
@@ -29,13 +34,18 @@ import {
} from '../types/toolRouter.types';
import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types';
import { Tools } from './Tools';
-import { ProviderOptions } from '../types/modifiers.types';
+import {
+ ExecuteToolModifiers,
+ ProviderOptions,
+ TransformToolSchemaModifier,
+} from '../types/modifiers.types';
import { ConnectionRequest } from '../types/connectionRequest.types';
import { createConnectionRequest } from './ConnectionRequest';
import { ConnectedAccountStatuses } from '../types/connectedAccounts.types';
import { transform } from '../utils/transform';
import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';
import { ValidationError } from '../errors';
+import { transformToolRouterToolsParams } from '../lib/toolRouterParams';
export class ToolRouter<
TToolCollection,
@@ -77,18 +87,18 @@ export class ToolRouter<
/**
*
- * @param sessionId {string} The session id to create the connections function for
- * @returns {ToolRouterConectionsFn} The connections function
+ * @param sessionId {string} The session id to create the toolkits function for
+ * @returns {ToolRouterToolkitsFn} The toolkits function
*
* @example
* ```typescript
* import { Composio } from '@composio/core';
*
* const composio = new Composio();
- * const sessionId = 'session_123';
+ * const session = await composio.toolRouter.use('session_123');
*
- * const session = await composio.create(sessionId);
- * console.log(connections);
+ * const toolkits = await session.toolkits();
+ * console.log(toolkits);
* ```
*/
private createToolkitsFn = (sessionId: string): ToolRouterToolkitsFn => {
@@ -155,19 +165,27 @@ export class ToolRouter<
* @returns A function that wraps the tools based on the provider.
*/
private createToolsFn = (
- userId: string,
+ sessionId: string,
toolSlugs: string[]
): ((modifiers?: ProviderOptions<TProvider>) => Promise<ReturnType<TProvider['wrapTools']>>) => {
return async (modifiers?: ProviderOptions<TProvider>) => {
const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
- const tools = await ToolsModel.get(
- userId,
+ const tools = await ToolsModel.getRawComposioTools(
{
tools: toolSlugs,
},
- modifiers
+ modifiers?.modifySchema
+ ? {
+ modifySchema: modifiers?.modifySchema,
+ }
+ : undefined
);
- return tools;
+ const wrappedTools = ToolsModel.wrapToolsForToolRouter(
+ sessionId,
+ tools,
+ modifiers as ExecuteToolModifiers
+ );
+ return wrappedTools as ReturnType<TProvider['wrapTools']>;
};
};
@@ -188,7 +206,7 @@ export class ToolRouter<
type,
url,
headers: {
- 'x-api-key': this.config?.apiKey ?? undefined,
+ ...(this.config?.apiKey ? { 'x-api-key': this.config?.apiKey } : {}),
},
};
};
@@ -197,7 +215,7 @@ export class ToolRouter<
* Creates a new tool router session for a user.
*
* @param userId {string} The user id to create the session for
- * @param config {ToolRouterConfig} The config for the tool router session
+ * @param config {ToolRouterCreateSessionConfig} The config for the tool router session
* @returns {Promise<ToolRouterSession<TToolCollection, TTool, TProvider>>} The tool router session
*
* @example
@@ -207,14 +225,25 @@ export class ToolRouter<
* const composio = new Composio();
* const userId = 'user_123';
*
- * const session = await composio.create(userId, {
- * manageConnections: true,
+ * const session = await composio.experimental.create(userId, {
+ * toolkits: ['gmail'],
+ * manageConnections: true,
+ * tools: {
+ * gmail: {
+ * disabled: ['gmail_send_email']
+ * }
+ * },
+ * tags: ['readOnlyHint']
* });
*
* console.log(session.sessionId);
- * console.log(session.url);
- * console.log(session.tools());
- * console.log(session.toolkits());
+ * console.log(session.mcp.url);
+ *
+ * // Get tools formatted for your framework (requires provider)
+ * const tools = await session.tools();
+ *
+ * // Check toolkit connection states
+ * const toolkits = await session.toolkits();
* ```
*/
async create(
@@ -226,46 +255,42 @@ export class ToolRouter<
const manageConnectedAccounts =
typeof routerConfig.manageConnections === 'boolean'
? routerConfig.manageConnections
- : (routerConfig.manageConnections?.enabled ?? true);
+ : (routerConfig.manageConnections?.enable ?? true);
const toolkits = Array.isArray(routerConfig.toolkits)
- ? { enabled: routerConfig.toolkits }
+ ? { enable: routerConfig.toolkits }
: routerConfig.toolkits;
- // const tools = transformToolRouterToolsParams(routerConfig.tools);
-
- const inferScopesFromTools =
- typeof routerConfig.manageConnections === 'object'
- ? routerConfig.manageConnections.inferScopesFromTools
- : false;
+ const tools = transformToolRouterToolsParams(routerConfig.tools);
const payload: SessionCreateParams = {
user_id: userId,
toolkits,
auth_configs: routerConfig.authConfigs,
connected_accounts: routerConfig.connectedAccounts,
- // tools: tools,
- connections: {
- infer_scopes_from_tools: inferScopesFromTools,
- auto_manage_connections: manageConnectedAccounts,
+ tools: tools,
+ tags: routerConfig.tags,
+ manage_connections: {
+ enable: manageConnectedAccounts,
callback_url:
typeof routerConfig.manageConnections === 'object'
? routerConfig.manageConnections.callbackUrl
: undefined,
},
- execution: routerConfig.execution
+ workbench: routerConfig.workbench
? {
- proxy_execution_enabled: routerConfig.execution?.proxyExecutionEnabled,
- timeout_seconds: routerConfig.execution?.timeoutSeconds,
+ enable_proxy_execution: routerConfig.workbench?.enableProxyExecution,
+ auto_offload_threshold: routerConfig.workbench?.autoOffloadThreshold,
}
: undefined,
};
+
const session = await this.client.toolRouter.session.create(payload);
return {
sessionId: session.session_id,
mcp: this.createMCPServerConfig(session.mcp),
- tools: this.createToolsFn(userId, session.tool_router_tools),
+ tools: this.createToolsFn(session.session_id, session.tool_router_tools),
authorize: this.createAuthorizeFn(session.session_id),
toolkits: this.createToolkitsFn(session.session_id),
};
@@ -283,14 +308,17 @@ export class ToolRouter<
* const composio = new Composio();
* const id = 'session_123';
* const session = await composio.toolRouter.use(id);
- *```
+ *
+ * console.log(session.mcp.url);
+ * console.log(session.mcp.headers);
+ * ```
*/
async use(id: string): Promise<ToolRouterSession<TToolCollection, TTool, TProvider>> {
const session = await this.client.toolRouter.session.retrieve(id);
return {
sessionId: session.session_id,
mcp: this.createMCPServerConfig(session.mcp),
- tools: this.createToolsFn(session.config.user_id, session.tool_router_tools),
+ tools: this.createToolsFn(session.session_id, session.tool_router_tools),
authorize: this.createAuthorizeFn(session.session_id),
toolkits: this.createToolkitsFn(session.session_id),
};
diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.ts
index c6eb432d8..b288c6cea 100644
--- a/ts/packages/core/src/models/Tools.ts
+++ b/ts/packages/core/src/models/Tools.ts
@@ -13,6 +13,7 @@ import {
ToolExecuteParamsSchema,
ToolkitVersionParam,
SchemaModifierOptions,
+ ToolExecuteMetaParamsSchema,
} from '../types/tool.types';
import {
ToolGetInputParams,
@@ -50,6 +51,7 @@ import { FileToolModifier } from '../utils/modifiers/FileToolModifier';
import { ComposioConfig } from '../composio';
import { getToolkitVersion } from '../utils/toolkitVersion';
import { handleToolExecutionError } from '../errors/ToolErrors';
+import { ToolExecuteMetaParams } from '../types/tool.types';
/**
* This class is used to manage tools in the Composio SDK.
* It provides methods to list, get, and execute tools.
@@ -626,6 +628,24 @@ export class Tools<
return this.provider.wrapTools(tools, executeToolFn) as ReturnType<T['wrapTools']>;
}
+ /**
+ * @internal
+ * Utility to wrap a given set of tools in the format expected by the tool router
+ *
+ * @param sessionId {string} The session id to execute the tool for
+ * @param tools {Tool[]} The tools to wrap
+ * @param modifiers {ExecuteToolModifiers} The modifiers to apply to the tool
+ * @returns {Tool[]} The wrapped tools
+ */
+ wrapToolsForToolRouter(
+ sessionId: string,
+ tools: Tool[],
+ modifiers?: ExecuteToolModifiers
+ ): Tool[] {
+ const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, modifiers);
+ return this.provider.wrapTools(tools, executeToolFn) as Tool[];
+ }
+
/**
* @internal
* @description
@@ -653,6 +673,34 @@ export class Tools<
return executeToolFn;
}
+ /**
+ * @internal
+ * Creates a function that executes a tool for a tool router session
+ *
+ * @param sessionId {string} The session id to execute the tool for
+ * @param modifiers {ExecuteToolModifiers} The modifiers to apply to the tool
+ * @returns {ExecuteToolFn} The execute tool function
+ */
+ private createExecuteToolFnForToolRouter(
+ sessionId: string,
+ modifiers?: ExecuteToolModifiers
+ ): ExecuteToolFn {
+ const executeToolFn = async (
+ toolSlug: string,
+ input: Record<string, unknown>
+ ): Promise<ToolExecuteResponse> => {
+ return await this.executeMetaTool(
+ toolSlug,
+ {
+ sessionId,
+ arguments: input,
+ },
+ modifiers
+ );
+ };
+ return executeToolFn;
+ }
+
/**
* @internal
* Executes a composio tool via API without modifiers
@@ -820,6 +868,70 @@ export class Tools<
return result;
}
+ /**
+ * Executes a composio meta tool based on tool router session
+ *
+ * @param sessionId {string} The session id to execute the tool for
+ * @param body.slug {string} The slug of the tool to execute
+ * @param body.arguments {Record<string, unknown>} The input to pass to the tool
+ * @param modifiers {ExecuteToolModifiers} The modifiers to apply to the tool
+ * @returns {Promise<ToolExecuteResponse>} The response from the tool execution
+ */
+ async executeMetaTool(
+ toolSlug: string,
+ body: ToolExecuteMetaParams,
+ modifiers?: ExecuteToolModifiers
+ ): Promise<ToolExecuteResponse> {
+ const executeMetaParams = ToolExecuteMetaParamsSchema.safeParse(body);
+ if (!executeMetaParams.success) {
+ throw new ValidationError('Invalid tool execute meta parameters', {
+ cause: executeMetaParams.error,
+ });
+ }
+
+ const tool = await this.getRawComposioToolBySlug(toolSlug);
+ if (!tool) {
+ throw new ComposioToolNotFoundError(`Tool ${toolSlug} not found`, {
+ meta: {
+ slug: toolSlug,
+ sessionId: body.sessionId,
+ },
+ });
+ }
+
+ const params = await this.applyBeforeExecuteModifiers(
+ tool,
+ {
+ toolSlug: toolSlug,
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
+ params: body.arguments ?? {},
+ },
+ modifiers?.beforeExecute
+ );
+
+ const response = await this.client.toolRouter.session.executeMeta(body.sessionId, {
+ slug: toolSlug,
+ arguments: params,
+ });
+
+ const result = await this.applyAfterExecuteModifiers(
+ tool,
+ {
+ toolSlug: toolSlug,
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
+ result: {
+ data: response.data,
+ error: response.error,
+ successful: !response.error,
+ logId: response.log_id,
+ },
+ },
+ modifiers?.afterExecute
+ );
+
+ return result;
+ }
+
/**
* Fetches the list of all available tools in the Composio SDK.
*
diff --git a/ts/packages/core/src/types/connectedAccounts.types.ts b/ts/packages/core/src/types/connectedAccounts.types.ts
index babeb0fe3..1aa823cad 100644
--- a/ts/packages/core/src/types/connectedAccounts.types.ts
+++ b/ts/packages/core/src/types/connectedAccounts.types.ts
@@ -136,11 +136,6 @@ export const ConnectedAccountListParamsSchema = z.object({
.optional()
.describe('The auth config ids of the connected accounts'),
cursor: z.string().nullish().describe('The cursor to paginate through the connected accounts'),
- labels: z
- .array(z.string())
- .nullable()
- .optional()
- .describe('The labels of the connected accounts'),
limit: z.number().nullable().optional().describe('The limit of the connected accounts to return'),
orderBy: z
.enum(['created_at', 'updated_at'])
diff --git a/ts/packages/core/src/types/tool.types.ts b/ts/packages/core/src/types/tool.types.ts
index 8504535ae..6b74a73f1 100644
--- a/ts/packages/core/src/types/tool.types.ts
+++ b/ts/packages/core/src/types/tool.types.ts
@@ -317,6 +317,12 @@ export const ToolExecuteParamsSchema = z.object({
});
export type ToolExecuteParams = z.infer<typeof ToolExecuteParamsSchema>;
+export const ToolExecuteMetaParamsSchema = z.object({
+ sessionId: z.string(),
+ arguments: z.record(z.string(), z.unknown()).optional(),
+});
+export type ToolExecuteMetaParams = z.infer<typeof ToolExecuteMetaParamsSchema>;
+
/**
* ToolResponse Schema
*/
diff --git a/ts/packages/core/src/types/toolRouter.types.ts b/ts/packages/core/src/types/toolRouter.types.ts
index 64c6e3fbc..826de75da 100644
--- a/ts/packages/core/src/types/toolRouter.types.ts
+++ b/ts/packages/core/src/types/toolRouter.types.ts
@@ -9,7 +9,7 @@ export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
// manage connections
export const ToolRouterConfigManageConnectionsSchema = z
.object({
- enabled: z
+ enable: z
.boolean()
.default(true)
.optional()
@@ -20,13 +20,6 @@ export const ToolRouterConfigManageConnectionsSchema = z
.string()
.optional()
.describe('The callback uri to use in the tool router session'),
- inferScopesFromTools: z
- .boolean()
- .default(false)
- .optional()
- .describe(
- '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'
- ),
})
.strict();
@@ -37,21 +30,21 @@ export const ToolRouterToolkitsParamSchema = z
export const ToolRouterToolkitsDisabledConfigSchema = z
.object({
- disabled: ToolRouterToolkitsParamSchema.describe(
+ disable: ToolRouterToolkitsParamSchema.describe(
'List of toolkits to disable in the tool router session'
),
})
.strict();
export const ToolRouterToolkitsEnabledConfigSchema = z
.object({
- enabled: ToolRouterToolkitsParamSchema.describe(
+ enable: ToolRouterToolkitsParamSchema.describe(
'List of toolkits to enable in the tool router session'
),
})
.strict();
export const ToolRouterManageConnectionsConfigSchema = z.object({
- enabled: z
+ enable: z
.boolean()
.optional()
.describe(
@@ -67,12 +60,12 @@ export const ToolRouterTagsParamSchema = z
.describe('The tags to use in the tool router session');
export const ToolRouterEnabledTagsConfigSchema = z
.object({
- enabled: ToolRouterTagsParamSchema.describe('The tags to enable in the tool router session'),
+ enable: ToolRouterTagsParamSchema.describe('The tags to enable in the tool router session'),
})
.strict();
export const ToolRouterDisabledTagsConfigSchema = z
.object({
- disabled: ToolRouterTagsParamSchema.describe('The tags to disable in the tool router session'),
+ disable: ToolRouterTagsParamSchema.describe('The tags to disable in the tool router session'),
})
.strict();
export const ToolRouterConfigTagsSchema = z
@@ -84,21 +77,15 @@ export const ToolRouterConfigTagsSchema = z
.describe('The tags to use in the tool router session');
/**
- * Tools config
+ * Tools config - Configure tools per toolkit using toolkit slug as key
* @example
* ```typescript
* {
- * overrides: {
- * gmail: {
- * enabled: ['gmail_search', 'gmail_send'],
- * disabled: ['gmail_delete']
- * }
- * }
- * filters: {
- * tags: {
- * enabled: ['gmail', 'gmail_search', 'gmail_send'],
- * disabled: ['gmail_delete']
- * }
+ * gmail: {
+ * enable: ['gmail_search', 'gmail_send']
+ * },
+ * slack: {
+ * disable: ['slack_delete_message']
* }
* }
* ```
@@ -106,53 +93,70 @@ export const ToolRouterConfigTagsSchema = z
* @example
* ```typescript
* {
- * overrides: {
- * gmail: ['gmail_search', 'gmail_send']
- * },
- * filters: {
- * tags: ['gmail', 'gmail_search', 'gmail_send']
- * }
+ * gmail: ['gmail_search', 'gmail_send'],
+ * slack: { tags: ['readOnlyHint'] }
* }
* ```
*/
export const ToolRouterToolsParamSchema = z
.array(z.string())
.describe('The tools to use in the tool router session');
+export type ToolRouterToolsParam = z.infer<typeof ToolRouterToolsParamSchema>;
+
+export const ToolRouterToolsTagsParamSchema = z
+ .array(z.enum(['readOnlyHint', 'destructiveHint', 'idempotentHint']))
+ .describe('The tags to filter the tools by');
+export type ToolRouterToolsTagsParam = z.infer<typeof ToolRouterToolsTagsParamSchema>;
+
export const ToolRouterConfigToolsSchema = z
- .object({
- overrides: z
- .record(
- z.string(),
- z.union([
- ToolRouterToolsParamSchema,
- z
- .object({
- enabled: ToolRouterToolsParamSchema.describe(
- 'The tools to enable in the tool router session'
- ),
- })
- .strict(),
- z
- .object({
- disabled: ToolRouterToolsParamSchema.describe(
- 'The tools to disable in the tool router session'
- ),
- })
- .strict(),
- ])
- )
- .describe('The tools to override in the tool router session')
- .optional(),
- tags: ToolRouterConfigTagsSchema.optional().describe('The tags to filter the tools by'),
- })
- .strict();
+ .union([
+ ToolRouterToolsParamSchema,
+ z
+ .object({
+ enable: ToolRouterToolsParamSchema.describe(
+ 'The tools to enable in the tool router session'
+ ),
+ })
+ .strict(),
+ z
+ .object({
+ disable: ToolRouterToolsParamSchema.describe(
+ 'The tools to disable in the tool router session'
+ ),
+ })
+ .strict(),
+ z
+ .object({
+ tags: ToolRouterToolsTagsParamSchema.describe(
+ 'The tags to filter the tools by, this will override the global tags'
+ ),
+ })
+ .strict(),
+ ])
+ .superRefine((val, ctx) => {
+ // If it's an object (not an array), ensure only one property is present
+ if (typeof val === 'object' && !Array.isArray(val)) {
+ const keys = Object.keys(val);
+ if (keys.length > 1) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Only one of 'enable', 'disable', or 'tags' can be specified, but found: ${keys.join(', ')}`,
+ path: keys,
+ });
+ }
+ }
+ });
export type ToolRouterConfigTools = z.infer<typeof ToolRouterConfigToolsSchema>;
export const ToolRouterCreateSessionConfigSchema = z
.object({
- // tools: ToolRouterConfigToolsSchema.optional().describe(
- // 'The tools to use in the tool router session'
- // ),
+ tools: z
+ .record(z.string(), z.union([ToolRouterToolsParamSchema, ToolRouterConfigToolsSchema]))
+ .optional()
+ .describe('The tools to use in the tool router session'),
+
+ tags: ToolRouterToolsTagsParamSchema.optional().describe('Global tags to filter the tools by'),
+
toolkits: z
.union([
ToolRouterToolkitsParamSchema,
@@ -181,16 +185,18 @@ export const ToolRouterCreateSessionConfigSchema = z
.describe(
'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.'
),
- execution: z
+ workbench: z
.object({
- proxyExecutionEnabled: z
+ enableProxyExecution: z
.boolean()
.optional()
.describe('Whether to enable proxy execution in the tool router session'),
- timeoutSeconds: z
+ autoOffloadThreshold: z
.number()
.optional()
- .describe('The timeout in seconds for the tool router session'),
+ .describe(
+ 'The auto offload threshold in characters for the tool execution to be moved into workbench'
+ ),
})
.optional()
.describe('The execution config for the tool router session'),
@@ -201,14 +207,16 @@ export const ToolRouterCreateSessionConfigSchema = z
* The config for the tool router session.
*
* @param {ToolRouterToolkitsParamSchema | ToolRouterToolkitsDisabledConfigSchema | ToolRouterToolkitsEnabledConfigSchema} toolkits - The toolkits to use in the tool router session
- * @param {ToolRouterToolsParamSchema | ToolRouterEnabledToolsConfigSchema | ToolRouterDisabledToolsConfigSchema} tools - The tools to use in the tool router session
- * @param {ToolRouterConfigManageConnectionsSchema | boolean} manageConnections - Whether to use tools to manage connections in the tool router session @default true
+ * @param {Record<string, ToolRouterToolsParam | ToolRouterConfigTools>} tools - The tools to configure per toolkit (key is toolkit slug)
+ * @param {Array<'readOnlyHint' | 'destructiveHint' | 'idempotentHint'>} tags - Global tags to filter tools by behavior
* @param {Record<string, string>} authConfigs - The auth configs to use in the tool router session
* @param {Record<string, string>} connectedAccounts - The connected accounts to use in the tool router session
* @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.
- * @param {boolean} [manageConnections.enabled] - Whether to use tools to manage connections in the tool router session @default true
- * @param {string} [manageConnections.callbackUrl] - The callback uri to use in the tool router session
- * @param {boolean} [manageConnections.inferScopesFromTools] - Whether to infer scopes from tools in the tool router session @default false
+ * @param {boolean} [manageConnections.enable] - Whether to use tools to manage connections in the tool router session @default true
+ * @param {string} [manageConnections.callbackUrl] - The callback url to use in the tool router session
+ * @param {object} workbench - Workbench configuration for tool execution
+ * @param {boolean} [workbench.proxyExecutionEnabled] - Whether to enable proxy execution
+ * @param {number} [workbench.autoOffloadThreshold] - Auto offload threshold in characters for moving execution to workbench
*/
export type ToolRouterCreateSessionConfig = z.infer<typeof ToolRouterCreateSessionConfigSchema>;
@@ -256,7 +264,7 @@ export type ToolkitConnectionState = z.infer<typeof ToolkitConnectionStateSchema
export const ToolRouterMCPServerConfigSchema = z.object({
type: MCPServerTypeSchema,
url: z.string(),
- headers: z.record(z.string(), z.string().optional()).optional(),
+ headers: z.record(z.string(), z.string()).optional(),
});
export type ToolRouterMCPServerConfig = z.infer<typeof ToolRouterMCPServerConfigSchema>;
@@ -293,15 +301,22 @@ export interface ToolRouterSession<
sessionId: string;
/**
* The MCP server config of the tool router session.
+ * Contains the URL, type ('http' or 'sse'), and headers for authentication.
*/
mcp: ToolRouterMCPServerConfig;
/**
- * The tools of the tool router session.
+ * Get the tools available in the session, formatted for your AI framework.
+ * Requires a provider to be configured in the Composio constructor.
*/
tools: ToolRouterToolsFn<TToolCollection, TTool, TProvider>;
/**
- * The authorize function of the tool router session.
+ * Initiate an authorization flow for a toolkit.
+ * Returns a ConnectionRequest with a redirect URL for the user.
*/
authorize: ToolRouterAuthorizeFn;
+ /**
+ * Query the connection state of toolkits in the session.
+ * Supports pagination and filtering by toolkit slugs.
+ */
toolkits: ToolRouterToolkitsFn;
}
diff --git a/ts/packages/core/test/models/toolRouter.test.ts b/ts/packages/core/test/models/toolRouter.test.ts
index a2484374e..409518a7d 100644
--- a/ts/packages/core/test/models/toolRouter.test.ts
+++ b/ts/packages/core/test/models/toolRouter.test.ts
@@ -17,7 +17,8 @@ vi.mock('../../src/telemetry/Telemetry', () => ({
vi.mock('../../src/models/Tools', () => {
return {
Tools: vi.fn().mockImplementation(() => ({
- get: vi.fn().mockResolvedValue('mocked-wrapped-tools'),
+ getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
+ wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
})),
};
});
@@ -32,6 +33,7 @@ const createMockClient = () => ({
retrieve: vi.fn(),
link: vi.fn(),
toolkits: vi.fn(),
+ executeMeta: vi.fn(),
},
},
tools: {
@@ -65,12 +67,11 @@ const mockSessionRetrieveResponse = {
tool_router_tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
config: {
user_id: 'user_123',
- toolkits: { enabled: ['gmail', 'slack', 'github'] },
+ toolkits: { enable: ['gmail', 'slack', 'github'] },
auth_configs: {},
connected_accounts: {},
- connections: {
- auto_manage_connections: true,
- infer_scopes_from_tools: false,
+ manage_connections: {
+ enable: true,
},
},
};
@@ -130,16 +131,14 @@ describe('ToolRouter', () => {
let mockClient: ReturnType<typeof createMockClient>;
let mockProvider: MockProvider;
- // Helper function to create expected connections object
- const createExpectedConnections = (
+ // Helper function to create expected manage_connections object
+ const createExpectedManageConnections = (
overrides: {
- manageConnections?: boolean;
+ enable?: boolean;
callbackUrl?: string;
- inferScopesFromTools?: boolean;
} = {}
) => ({
- infer_scopes_from_tools: overrides.inferScopesFromTools ?? false,
- auto_manage_connections: overrides.manageConnections ?? true,
+ enable: overrides.enable ?? true,
callback_url: overrides.callbackUrl ?? undefined,
});
@@ -183,8 +182,9 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections(),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: undefined,
});
expect(session).toHaveProperty('sessionId', 'session_123');
@@ -212,8 +212,9 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections(),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: undefined,
});
expect(session.sessionId).toBe('session_123');
@@ -230,7 +231,7 @@ describe('ToolRouter', () => {
});
describe('toolkits configuration', () => {
- it('should create a session with toolkits as array (enabled toolkits)', async () => {
+ it('should create a session with toolkits as array (enable toolkits)', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
const config: ToolRouterCreateSessionConfig = {
@@ -242,22 +243,23 @@ describe('ToolRouter', () => {
expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
user_id: userId,
toolkits: {
- enabled: ['gmail', 'slack', 'github'],
+ enable: ['gmail', 'slack', 'github'],
},
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections(),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: undefined,
});
});
- it('should create a session with enabled toolkits configuration', async () => {
+ it('should create a session with enable toolkits configuration', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
const config: ToolRouterCreateSessionConfig = {
toolkits: {
- enabled: ['gmail', 'slack'],
+ enable: ['gmail', 'slack'],
},
};
@@ -266,22 +268,23 @@ describe('ToolRouter', () => {
expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
user_id: userId,
toolkits: {
- enabled: ['gmail', 'slack'],
+ enable: ['gmail', 'slack'],
},
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections(),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: undefined,
});
});
- it('should create a session with disabled toolkits configuration', async () => {
+ it('should create a session with disable toolkits configuration', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
const config: ToolRouterCreateSessionConfig = {
toolkits: {
- disabled: ['notion', 'trello'],
+ disable: ['notion', 'trello'],
},
};
@@ -290,13 +293,14 @@ describe('ToolRouter', () => {
expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
user_id: userId,
toolkits: {
- disabled: ['notion', 'trello'],
+ disable: ['notion', 'trello'],
},
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections(),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: undefined,
});
});
});
@@ -322,7 +326,7 @@ describe('ToolRouter', () => {
// connected_accounts: undefined,
// tools: {
// overrides: {
- // gmail: { enabled: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
+ // gmail: { enable: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
// },
// filters: undefined,
// },
@@ -331,13 +335,13 @@ describe('ToolRouter', () => {
// });
// });
- // it('should create a session with tools overrides with enabled tools', async () => {
+ // it('should create a session with tools overrides with enable tools', async () => {
// mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
// const config: ToolRouterCreateSessionConfig = {
// tools: {
// overrides: {
- // gmail: { enabled: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
+ // gmail: { enable: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
// },
// },
// };
@@ -351,7 +355,7 @@ describe('ToolRouter', () => {
// connected_accounts: undefined,
// tools: {
// overrides: {
- // gmail: { enabled: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
+ // gmail: { enable: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
// },
// filters: undefined,
// },
@@ -360,13 +364,13 @@ describe('ToolRouter', () => {
// });
// });
- // it('should create a session with tools overrides with disabled tools', async () => {
+ // it('should create a session with tools overrides with disable tools', async () => {
// mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
// const config: ToolRouterCreateSessionConfig = {
// tools: {
// overrides: {
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
// },
// },
// };
@@ -380,7 +384,7 @@ describe('ToolRouter', () => {
// connected_accounts: undefined,
// tools: {
// overrides: {
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
// },
// filters: undefined,
// },
@@ -416,12 +420,12 @@ describe('ToolRouter', () => {
// });
// });
- // it('should create a session with enabled tag filters', async () => {
+ // it('should create a session with enable tag filters', async () => {
// mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
// const config: ToolRouterCreateSessionConfig = {
// tools: {
- // tags: { enabled: ['important', 'email'] },
+ // tags: { enable: ['important', 'email'] },
// },
// };
@@ -443,12 +447,12 @@ describe('ToolRouter', () => {
// });
// });
- // it('should create a session with disabled tag filters', async () => {
+ // it('should create a session with disable tag filters', async () => {
// mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
// const config: ToolRouterCreateSessionConfig = {
// tools: {
- // tags: { disabled: ['dangerous'] },
+ // tags: { disable: ['dangerous'] },
// },
// };
@@ -477,7 +481,7 @@ describe('ToolRouter', () => {
// tools: {
// overrides: {
// gmail: ['GMAIL_FETCH_EMAILS'],
- // slack: { disabled: ['SLACK_DELETE_MESSAGE'] },
+ // slack: { disable: ['SLACK_DELETE_MESSAGE'] },
// },
// tags: ['important'],
// },
@@ -492,8 +496,8 @@ describe('ToolRouter', () => {
// connected_accounts: undefined,
// tools: {
// overrides: {
- // gmail: { enabled: ['GMAIL_FETCH_EMAILS'] },
- // slack: { disabled: ['SLACK_DELETE_MESSAGE'] },
+ // gmail: { enable: ['GMAIL_FETCH_EMAILS'] },
+ // slack: { disable: ['SLACK_DELETE_MESSAGE'] },
// },
// filters: {
// tags: { include: ['important'] },
@@ -521,8 +525,9 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections({ manageConnections: true }),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections({ enable: true }),
+ workbench: undefined,
});
});
@@ -541,18 +546,18 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections({ manageConnections: false }),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections({ enable: false }),
+ workbench: undefined,
});
});
- it('should create a session with manageConnections as object with enabled', async () => {
+ it('should create a session with manageConnections as object with enable', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
const config: ToolRouterCreateSessionConfig = {
manageConnections: {
- enabled: true,
- inferScopesFromTools: false,
+ enable: true,
},
};
@@ -564,8 +569,9 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections({ manageConnections: true }),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections({ enable: true }),
+ workbench: undefined,
});
});
@@ -574,9 +580,8 @@ describe('ToolRouter', () => {
const config: ToolRouterCreateSessionConfig = {
manageConnections: {
- enabled: true,
+ enable: true,
callbackUrl: 'https://myapp.com/callback',
- inferScopesFromTools: false,
},
};
@@ -588,37 +593,12 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections({
- manageConnections: true,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections({
+ enable: true,
callbackUrl: 'https://myapp.com/callback',
}),
- execution: undefined,
- });
- });
-
- it('should create a session with manageConnections object with inferScopesFromTools', async () => {
- mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
-
- const config: ToolRouterCreateSessionConfig = {
- manageConnections: {
- enabled: true,
- inferScopesFromTools: true,
- },
- };
-
- await toolRouter.create(userId, config);
-
- expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
- user_id: userId,
- toolkits: undefined,
- auth_configs: undefined,
- connected_accounts: undefined,
- tools: undefined,
- connections: createExpectedConnections({
- manageConnections: true,
- inferScopesFromTools: true,
- }),
- execution: undefined,
+ workbench: undefined,
});
});
@@ -627,9 +607,8 @@ describe('ToolRouter', () => {
const config: ToolRouterCreateSessionConfig = {
manageConnections: {
- enabled: true,
+ enable: true,
callbackUrl: 'https://myapp.com/callback',
- inferScopesFromTools: true,
},
};
@@ -641,12 +620,12 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections({
- manageConnections: true,
- inferScopesFromTools: true,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections({
+ enable: true,
callbackUrl: 'https://myapp.com/callback',
}),
- execution: undefined,
+ workbench: undefined,
});
});
});
@@ -673,8 +652,9 @@ describe('ToolRouter', () => {
},
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections(),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: undefined,
});
});
@@ -699,8 +679,9 @@ describe('ToolRouter', () => {
slack: 'conn_456',
},
tools: undefined,
- connections: createExpectedConnections(),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: undefined,
});
});
@@ -728,19 +709,20 @@ describe('ToolRouter', () => {
slack: 'conn_456',
},
tools: undefined,
- connections: createExpectedConnections(),
- execution: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: undefined,
});
});
});
- describe('execution configuration', () => {
- it('should create a session with proxyExecutionEnabled only', async () => {
+ describe('workbench configuration', () => {
+ it('should create a session with enableProxyExecution only', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
const config: ToolRouterCreateSessionConfig = {
- execution: {
- proxyExecutionEnabled: true,
+ workbench: {
+ enableProxyExecution: true,
},
};
@@ -752,20 +734,21 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections(),
- execution: {
- proxy_execution_enabled: true,
- timeout_seconds: undefined,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: {
+ enable_proxy_execution: true,
+ auto_offload_threshold: undefined,
},
});
});
- it('should create a session with timeoutSeconds only', async () => {
+ it('should create a session with autoOffloadThreshold only', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
const config: ToolRouterCreateSessionConfig = {
- execution: {
- timeoutSeconds: 60,
+ workbench: {
+ autoOffloadThreshold: 1000,
},
};
@@ -777,21 +760,22 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections(),
- execution: {
- proxy_execution_enabled: undefined,
- timeout_seconds: 60,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: {
+ enable_proxy_execution: undefined,
+ auto_offload_threshold: 1000,
},
});
});
- it('should create a session with full execution configuration', async () => {
+ it('should create a session with full workbench configuration', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
const config: ToolRouterCreateSessionConfig = {
- execution: {
- proxyExecutionEnabled: true,
- timeoutSeconds: 30,
+ workbench: {
+ enableProxyExecution: true,
+ autoOffloadThreshold: 500,
},
};
@@ -803,21 +787,22 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections(),
- execution: {
- proxy_execution_enabled: true,
- timeout_seconds: 30,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: {
+ enable_proxy_execution: true,
+ auto_offload_threshold: 500,
},
});
});
- it('should create a session with execution disabled', async () => {
+ it('should create a session with workbench disable', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
const config: ToolRouterCreateSessionConfig = {
- execution: {
- proxyExecutionEnabled: false,
- timeoutSeconds: 0,
+ workbench: {
+ enableProxyExecution: false,
+ autoOffloadThreshold: 0,
},
};
@@ -829,10 +814,11 @@ describe('ToolRouter', () => {
auth_configs: undefined,
connected_accounts: undefined,
tools: undefined,
- connections: createExpectedConnections(),
- execution: {
- proxy_execution_enabled: false,
- timeout_seconds: 0,
+ tags: undefined,
+ manage_connections: createExpectedManageConnections(),
+ workbench: {
+ enable_proxy_execution: false,
+ auto_offload_threshold: 0,
},
});
});
@@ -857,13 +843,12 @@ describe('ToolRouter', () => {
// slack: 'conn_456',
// },
// manageConnections: {
- // enabled: true,
+ // enable: true,
// callbackUri: 'https://myapp.com/callback',
- // inferScopesFromTools: true,
// },
// execution: {
- // proxyExecutionEnabled: true,
- // timeoutSeconds: 30,
+ // enableProxyExecution: true,
+ // autoOffloadThreshould: 30,
// },
// };
@@ -872,7 +857,7 @@ describe('ToolRouter', () => {
// expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
// user_id: userId,
// toolkits: {
- // enabled: ['gmail', 'slack'],
+ // enable: ['gmail', 'slack'],
// },
// auth_configs: {
// gmail: 'auth_config_123',
@@ -882,7 +867,7 @@ describe('ToolRouter', () => {
// },
// tools: {
// overrides: {
- // gmail: { enabled: ['GMAIL_FETCH_EMAILS'] },
+ // gmail: { enable: ['GMAIL_FETCH_EMAILS'] },
// },
// filters: {
// tags: { include: ['important'] },
@@ -890,27 +875,26 @@ describe('ToolRouter', () => {
// },
// connections: createExpectedConnections({
// manageConnections: true,
- // inferScopesFromTools: true,
// callbackUri: 'https://myapp.com/callback',
// }),
// execution: {
- // proxy_execution_enabled: true,
- // timeout_seconds: 30,
+ // enable_proxy_execution: true,
+ // auto_offload_threshould: 30,
// },
// });
// });
- // it('should create a session with toolkits and disabled tools', async () => {
+ // it('should create a session with toolkits and disable tools', async () => {
// mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
// const config: ToolRouterCreateSessionConfig = {
// toolkits: {
- // enabled: ['gmail', 'slack', 'github'],
+ // enable: ['gmail', 'slack', 'github'],
// },
// tools: {
// overrides: {
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
- // slack: { disabled: ['SLACK_DELETE_MESSAGE'] },
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
+ // slack: { disable: ['SLACK_DELETE_MESSAGE'] },
// },
// },
// };
@@ -920,14 +904,14 @@ describe('ToolRouter', () => {
// expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
// user_id: userId,
// toolkits: {
- // enabled: ['gmail', 'slack', 'github'],
+ // enable: ['gmail', 'slack', 'github'],
// },
// auth_configs: undefined,
// connected_accounts: undefined,
// tools: {
// overrides: {
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
- // slack: { disabled: ['SLACK_DELETE_MESSAGE'] },
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
+ // slack: { disable: ['SLACK_DELETE_MESSAGE'] },
// },
// filters: undefined,
// },
@@ -941,13 +925,13 @@ describe('ToolRouter', () => {
// const config: ToolRouterCreateSessionConfig = {
// toolkits: {
- // disabled: ['notion'],
+ // disable: ['notion'],
// },
// tools: {
// overrides: {
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
// },
- // tags: { disabled: ['dangerous'] },
+ // tags: { disable: ['dangerous'] },
// },
// authConfigs: {
// gmail: 'auth_config_123',
@@ -956,8 +940,7 @@ describe('ToolRouter', () => {
// },
// connectedAccounts: {},
// manageConnections: {
- // enabled: false,
- // inferScopesFromTools: false,
+ // enable: false,
// },
// };
@@ -966,7 +949,7 @@ describe('ToolRouter', () => {
// expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
// user_id: userId,
// toolkits: {
- // disabled: ['notion'],
+ // disable: ['notion'],
// },
// auth_configs: {
// gmail: 'auth_config_123',
@@ -976,7 +959,7 @@ describe('ToolRouter', () => {
// connected_accounts: {},
// tools: {
// overrides: {
- // gmail: { disabled: ['GMAIL_DELETE_EMAIL'] },
+ // gmail: { disable: ['GMAIL_DELETE_EMAIL'] },
// },
// filters: {
// tags: { exclude: ['dangerous'] },
@@ -1010,7 +993,7 @@ describe('ToolRouter', () => {
await expect(toolRouter.create(userId, invalidConfig)).rejects.toThrow();
});
- it('should throw error for empty userId', async () => {
+ it('should pass through empty userId', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
// The test validates that even empty userId is passed through
@@ -1474,12 +1457,14 @@ describe('ToolRouter', () => {
describe('tools function', () => {
const userId = 'user_123';
+ const sessionId = 'session_123';
beforeEach(() => {
// Reset the Tools mock before each test
vi.clearAllMocks();
(Tools as any).mockImplementation(() => ({
- get: vi.fn().mockResolvedValue('mocked-wrapped-tools'),
+ getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
+ wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
}));
});
@@ -1495,13 +1480,17 @@ describe('ToolRouter', () => {
});
const toolsInstance = (Tools as any).mock.results[0].value;
- expect(toolsInstance.get).toHaveBeenCalledWith(
- userId,
+ expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
{
tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
},
undefined
);
+ expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
+ sessionId,
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ undefined
+ );
expect(tools).toBe('mocked-wrapped-tools');
});
@@ -1514,17 +1503,22 @@ describe('ToolRouter', () => {
...tool,
description: 'Modified description',
})),
+ beforeExecute: vi.fn(),
};
const session = await toolRouter.create(userId);
const tools = await session.tools(modifiers);
const toolsInstance = (Tools as any).mock.results[0].value;
- expect(toolsInstance.get).toHaveBeenCalledWith(
- userId,
+ expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
{
tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
},
+ { modifySchema: modifiers.modifySchema }
+ );
+ expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
+ sessionId,
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
modifiers
);
@@ -1535,7 +1529,8 @@ describe('ToolRouter', () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
(Tools as any).mockImplementation(() => ({
- get: vi.fn().mockRejectedValue(new Error('Failed to fetch tools')),
+ getRawComposioTools: vi.fn().mockRejectedValue(new Error('Failed to fetch tools')),
+ wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
}));
const session = await toolRouter.create(userId);
@@ -1552,27 +1547,35 @@ describe('ToolRouter', () => {
const session = await toolRouter.create(userId);
// Each call to session.tools() creates a new Tools instance
- // So we need to check that Tools was called twice and each instance's get method was called once
+ // So we need to check that Tools was called twice and each instance's methods were called
await session.tools(modifier1);
await session.tools(modifier2);
expect(Tools).toHaveBeenCalledTimes(2);
const firstToolsInstance = (Tools as any).mock.results[0].value;
- expect(firstToolsInstance.get).toHaveBeenCalledWith(
- userId,
+ expect(firstToolsInstance.getRawComposioTools).toHaveBeenCalledWith(
{
tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
},
+ { modifySchema: modifier1.modifySchema }
+ );
+ expect(firstToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
+ sessionId,
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
modifier1
);
const secondToolsInstance = (Tools as any).mock.results[1].value;
- expect(secondToolsInstance.get).toHaveBeenCalledWith(
- userId,
+ expect(secondToolsInstance.getRawComposioTools).toHaveBeenCalledWith(
{
tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
},
+ { modifySchema: modifier2.modifySchema }
+ );
+ expect(secondToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
+ sessionId,
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
modifier2
);
});
@@ -1594,13 +1597,17 @@ describe('ToolRouter', () => {
apiKey: 'test-api-key',
});
const toolsInstance = (Tools as any).mock.results[0].value;
- expect(toolsInstance.get).toHaveBeenCalledWith(
- userId,
+ expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
{
tools: ['CUSTOM_TOOL_1', 'CUSTOM_TOOL_2'],
},
undefined
);
+ expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
+ 'custom_session_123',
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ undefined
+ );
});
it('should handle empty tool router tools array', async () => {
@@ -1620,13 +1627,17 @@ describe('ToolRouter', () => {
apiKey: 'test-api-key',
});
const toolsInstance = (Tools as any).mock.results[0].value;
- expect(toolsInstance.get).toHaveBeenCalledWith(
- userId,
+ expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
{
tools: [],
},
undefined
);
+ expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
+ 'empty_session_123',
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ undefined
+ );
});
});
@@ -1748,7 +1759,7 @@ describe('ToolRouter', () => {
expect(session).toHaveProperty('toolkits');
});
- it('should return a session with correct user ID from config', async () => {
+ it('should return a session with correct session ID', async () => {
const customResponse = {
...mockSessionRetrieveResponse,
config: {
@@ -1762,7 +1773,7 @@ describe('ToolRouter', () => {
const session = await toolRouter.use(sessionId);
expect(session.sessionId).toBe('session_123');
- // The tools function should be created with the correct user ID from config
+ // The tools function should be created with the session ID
expect(session.tools).toBeDefined();
});
@@ -1775,6 +1786,19 @@ describe('ToolRouter', () => {
expect(tools).toBe('mocked-wrapped-tools');
expect(Tools).toHaveBeenCalled();
+
+ const toolsInstance = (Tools as any).mock.results[0].value;
+ expect(toolsInstance.getRawComposioTools).toHaveBeenCalledWith(
+ {
+ tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
+ },
+ undefined
+ );
+ expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
+ sessionId,
+ [{ slug: 'GMAIL_FETCH_EMAILS' }],
+ undefined
+ );
});
it('should return a session with working authorize function', async () => {
diff --git a/ts/packages/core/test/tools/tools.test.ts b/ts/packages/core/test/tools/tools.test.ts
index 516b36e40..bfcdb5dc1 100644
--- a/ts/packages/core/test/tools/tools.test.ts
+++ b/ts/packages/core/test/tools/tools.test.ts
@@ -721,6 +721,326 @@ describe('Tools', () => {
});
});
+ describe('Tool Router Execution', () => {
+ const sessionId = 'test-session-123';
+
+ describe('executeMetaTool', () => {
+ it('should execute a tool via tool router session', async () => {
+ const toolSlug = 'COMPOSIO_TOOL';
+ const body = {
+ sessionId,
+ arguments: { query: 'test' },
+ };
+
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(
+ toolMocks.transformedTool as unknown as Tool
+ );
+
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
+ data: { results: true },
+ error: null,
+ log_id: '123',
+ });
+
+ const result = await context.tools.executeMetaTool(toolSlug, body);
+
+ expect(mockClient.toolRouter.session.executeMeta).toHaveBeenCalledWith(sessionId, {
+ slug: toolSlug,
+ arguments: body.arguments,
+ });
+ expect(result).toEqual({
+ data: { results: true },
+ error: null,
+ successful: true,
+ logId: '123',
+ });
+ });
+
+ it('should throw validation error for invalid parameters', async () => {
+ const invalidBody = {
+ // missing sessionId
+ arguments: { query: 'test' },
+ } as any;
+
+ await expect(context.tools.executeMetaTool('COMPOSIO_TOOL', invalidBody)).rejects.toThrow(
+ 'Invalid tool execute meta parameters'
+ );
+ });
+
+ it('should throw error if tool is not found', async () => {
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(undefined as any);
+
+ await expect(
+ context.tools.executeMetaTool('NONEXISTENT_TOOL', {
+ sessionId,
+ arguments: { query: 'test' },
+ })
+ ).rejects.toThrow('Tool NONEXISTENT_TOOL not found');
+ });
+
+ it('should apply beforeExecute modifier', async () => {
+ const toolSlug = 'COMPOSIO_TOOL';
+ const body = {
+ sessionId,
+ arguments: { query: 'original' },
+ };
+
+ const toolWithToolkit = {
+ ...toolMocks.transformedTool,
+ toolkit: { slug: 'test-toolkit', name: 'Test Toolkit' },
+ };
+
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(toolWithToolkit as unknown as Tool);
+
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
+ data: { results: true },
+ error: null,
+ log_id: '123',
+ });
+
+ const beforeExecute = vi.fn().mockImplementation(({ params }) => ({
+ ...params,
+ query: 'modified',
+ }));
+
+ await context.tools.executeMetaTool(toolSlug, body, { beforeExecute });
+
+ expect(beforeExecute).toHaveBeenCalledWith({
+ toolSlug,
+ toolkitSlug: 'test-toolkit',
+ params: { query: 'original' },
+ });
+
+ expect(mockClient.toolRouter.session.executeMeta).toHaveBeenCalledWith(sessionId, {
+ slug: toolSlug,
+ arguments: { query: 'modified' },
+ });
+ });
+
+ it('should apply afterExecute modifier', async () => {
+ const toolSlug = 'COMPOSIO_TOOL';
+ const body = {
+ sessionId,
+ arguments: { query: 'test' },
+ };
+
+ const toolWithToolkit = {
+ ...toolMocks.transformedTool,
+ toolkit: { slug: 'test-toolkit', name: 'Test Toolkit' },
+ };
+
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(toolWithToolkit as unknown as Tool);
+
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
+ data: { results: true },
+ error: null,
+ log_id: '123',
+ });
+
+ const afterExecute = vi.fn().mockImplementation(({ result }) => ({
+ ...result,
+ data: { results: 'modified result' },
+ }));
+
+ const result = await context.tools.executeMetaTool(toolSlug, body, { afterExecute });
+
+ expect(afterExecute).toHaveBeenCalledWith({
+ toolSlug,
+ toolkitSlug: 'test-toolkit',
+ result: {
+ data: { results: true },
+ error: null,
+ successful: true,
+ logId: '123',
+ },
+ });
+
+ expect(result.data).toEqual({ results: 'modified result' });
+ });
+
+ it('should handle error responses from tool router', async () => {
+ const toolSlug = 'COMPOSIO_TOOL';
+ const body = {
+ sessionId,
+ arguments: { query: 'test' },
+ };
+
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(
+ toolMocks.transformedTool as unknown as Tool
+ );
+
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
+ data: null,
+ error: 'Something went wrong',
+ log_id: '456',
+ });
+
+ const result = await context.tools.executeMetaTool(toolSlug, body);
+
+ expect(result).toEqual({
+ data: null,
+ error: 'Something went wrong',
+ successful: false,
+ logId: '456',
+ });
+ });
+
+ it('should handle tool without toolkit gracefully', async () => {
+ const toolSlug = 'TOOL_WITHOUT_TOOLKIT';
+ const body = {
+ sessionId,
+ arguments: { query: 'test' },
+ };
+
+ const toolWithoutToolkit = {
+ ...toolMocks.transformedTool,
+ toolkit: undefined,
+ };
+
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(toolWithoutToolkit as unknown as Tool);
+
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
+ data: { results: true },
+ error: null,
+ log_id: '123',
+ });
+
+ const beforeExecute = vi.fn().mockImplementation(({ params }) => params);
+
+ await context.tools.executeMetaTool(toolSlug, body, { beforeExecute });
+
+ expect(beforeExecute).toHaveBeenCalledWith({
+ toolSlug,
+ toolkitSlug: 'unknown',
+ params: { query: 'test' },
+ });
+ });
+ });
+
+ describe('wrapToolsForToolRouter', () => {
+ it('should wrap tools with tool router execute function', async () => {
+ const tools = [toolMocks.transformedTool as unknown as Tool];
+
+ context.mockProvider.wrapTools.mockReturnValueOnce('wrapped-tools');
+
+ const result = context.tools.wrapToolsForToolRouter(sessionId, tools);
+
+ expect(context.mockProvider.wrapTools).toHaveBeenCalledWith(tools, expect.any(Function));
+ expect(result).toBe('wrapped-tools');
+ });
+
+ it('should create execute function that calls executeMetaTool', async () => {
+ const tools = [toolMocks.transformedTool as unknown as Tool];
+
+ let capturedExecuteFn: (toolSlug: string, input: Record<string, unknown>) => Promise<any>;
+
+ context.mockProvider.wrapTools.mockImplementation((tools, executeFn) => {
+ capturedExecuteFn = executeFn;
+ return 'wrapped-tools';
+ });
+
+ context.tools.wrapToolsForToolRouter(sessionId, tools);
+
+ // Setup mocks for execution
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(
+ toolMocks.transformedTool as unknown as Tool
+ );
+
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
+ data: { results: true },
+ error: null,
+ log_id: '123',
+ });
+
+ // Call the captured execute function
+ const result = await capturedExecuteFn!('COMPOSIO_TOOL', { query: 'test' });
+
+ expect(mockClient.toolRouter.session.executeMeta).toHaveBeenCalledWith(sessionId, {
+ slug: 'COMPOSIO_TOOL',
+ arguments: { query: 'test' },
+ });
+ expect(result).toEqual({
+ data: { results: true },
+ error: null,
+ successful: true,
+ logId: '123',
+ });
+ });
+
+ it('should pass modifiers to the execute function', async () => {
+ const tools = [toolMocks.transformedTool as unknown as Tool];
+ const modifiers = {
+ beforeExecute: vi.fn().mockImplementation(({ params }) => ({
+ ...params,
+ modified: true,
+ })),
+ };
+
+ let capturedExecuteFn: (toolSlug: string, input: Record<string, unknown>) => Promise<any>;
+
+ context.mockProvider.wrapTools.mockImplementation((tools, executeFn) => {
+ capturedExecuteFn = executeFn;
+ return 'wrapped-tools';
+ });
+
+ context.tools.wrapToolsForToolRouter(sessionId, tools, modifiers);
+
+ // Setup mocks for execution
+ const getRawComposioToolBySlugSpy = vi.spyOn(context.tools, 'getRawComposioToolBySlug');
+ getRawComposioToolBySlugSpy.mockResolvedValueOnce(
+ toolMocks.transformedTool as unknown as Tool
+ );
+
+ mockClient.toolRouter.session.executeMeta.mockResolvedValueOnce({
+ data: { results: true },
+ error: null,
+ log_id: '123',
+ });
+
+ // Call the captured execute function
+ await capturedExecuteFn!('COMPOSIO_TOOL', { query: 'test' });
+
+ expect(modifiers.beforeExecute).toHaveBeenCalled();
+ expect(mockClient.toolRouter.session.executeMeta).toHaveBeenCalledWith(sessionId, {
+ slug: 'COMPOSIO_TOOL',
+ arguments: { query: 'test', modified: true },
+ });
+ });
+
+ it('should handle multiple tools', async () => {
+ const tools = [
+ toolMocks.transformedTool as unknown as Tool,
+ { ...toolMocks.transformedTool, slug: 'ANOTHER_TOOL' } as unknown as Tool,
+ ];
+
+ context.mockProvider.wrapTools.mockReturnValueOnce('wrapped-tools');
+
+ const result = context.tools.wrapToolsForToolRouter(sessionId, tools);
+
+ expect(context.mockProvider.wrapTools).toHaveBeenCalledWith(tools, expect.any(Function));
+ expect(result).toBe('wrapped-tools');
+ });
+
+ it('should handle empty tools array', async () => {
+ const tools: Tool[] = [];
+
+ context.mockProvider.wrapTools.mockReturnValueOnce([]);
+
+ const result = context.tools.wrapToolsForToolRouter(sessionId, tools);
+
+ expect(context.mockProvider.wrapTools).toHaveBeenCalledWith([], expect.any(Function));
+ expect(result).toEqual([]);
+ });
+ });
+ });
+
describe('Version Integration Tests', () => {
describe('toolkit versions in tool fetching', () => {
it('should pass default "latest" version when no version is configured', async () => {
diff --git a/ts/packages/core/test/utils/mocks/client.mock.ts b/ts/packages/core/test/utils/mocks/client.mock.ts
index 33c5550bc..a1ae2454c 100644
--- a/ts/packages/core/test/utils/mocks/client.mock.ts
+++ b/ts/packages/core/test/utils/mocks/client.mock.ts
@@ -16,4 +16,9 @@ export const mockClient = {
toolkits: {
retrieve: vi.fn(),
},
+ toolRouter: {
+ session: {
+ executeMeta: vi.fn(),
+ },
+ },
};