@devries-cameron20 / composio-1 / commits / 635473ac3
Fork 0

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

fix(tool-router): align session and context response shapes

Dhawal Upadhyay committed Mar 24, 2026 at 14:59 UTC 635473ac376615d9f355cd71e6e4684d488f9345
9 files changed +375 -256
python/composio/core/models/custom_tool_types.py
+8 -2
@@ -63,7 +63,10 @@ class SessionContext(te.Protocol):
63 tool_slug: str,
64 arguments: t.Dict[str, t.Any],
65 ) -> SessionExecuteResponse:
66 - """Execute any Composio tool from within a custom tool."""
66 + """Execute any Composio tool from within a custom tool.
67 +
68 + Returns the same response model as ``session.execute()``.
69 + """
70 ...
71
72 def proxy_execute(
@@ -75,7 +78,10 @@ class SessionContext(te.Protocol):
78 body: t.Any = None,
79 parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
80 ) -> SessionProxyExecuteResponse:
78 - """Proxy API calls through Composio's auth layer."""
81 + """Proxy API calls through Composio's auth layer.
82 +
83 + Returns the same response model as ``session.proxy_execute()``.
84 + """
85 ...
86
87
python/composio/core/models/session_context.py
+6 -1
@@ -118,6 +118,8 @@ class SessionContextImpl:
118
119 Routes to sibling local tools in-process when available,
120 otherwise delegates to the backend API.
121 +
122 + Returns the same response model as ``session.execute()``.
123 """
124 # Try local tool first (sibling routing)
125 entry = find_custom_tool(self._custom_tools_map, tool_slug)
@@ -148,7 +150,10 @@ class SessionContextImpl:
150 body: t.Any = None,
151 parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
152 ) -> SessionProxyExecuteResponse:
151 - """Proxy API calls through Composio's auth layer."""
153 + """Proxy API calls through Composio's auth layer.
154 +
155 + Returns the same response model as ``session.proxy_execute()``.
156 + """
157 return proxy_execute_impl(
158 self._client,
159 self._session_id,
python/tests/test_custom_tools.py
+33 -8
@@ -15,6 +15,12 @@ Covers:
15 from unittest.mock import MagicMock
16
17 import pytest
18 +from composio_client.types.tool_router.session_execute_response import (
19 + SessionExecuteResponse,
20 +)
21 +from composio_client.types.tool_router.session_proxy_execute_response import (
22 + SessionProxyExecuteResponse,
23 +)
24 from pydantic import BaseModel, Field
25
26 from composio.core.models.custom_tool import (
@@ -478,14 +484,16 @@ class TestSessionContextImpl:
484 client=MagicMock(), user_id="u", session_id="s", custom_tools_map=m
485 )
486 result = ctx.execute("GREP", {"pattern": "test"})
487 + assert isinstance(result, SessionExecuteResponse)
488 assert result.error is None
489 + assert result.log_id == ""
490 assert result.data["matches"] == ["test"]
491
492 def test_remote_fallback(self, grep_tool):
493 m = build_custom_tools_map([grep_tool])
494 mock_client = MagicMock()
487 - mock_client.tool_router.session.execute.return_value = MagicMock(
488 - data={"remote": True}, error=None
495 + mock_client.tool_router.session.execute.return_value = SessionExecuteResponse(
496 + data={"remote": True}, error=None, log_id="log_123"
497 )
498 ctx = SessionContextImpl(
499 client=mock_client, user_id="u", session_id="s", custom_tools_map=m
@@ -495,13 +503,16 @@ class TestSessionContextImpl:
503
504 def test_proxy_execute(self):
505 mock_client = MagicMock()
498 - mock_client.tool_router.session.proxy_execute.return_value = MagicMock(
499 - status=200, data={"ok": True}, headers={}, binary_data=None
506 + mock_client.tool_router.session.proxy_execute.return_value = (
507 + SessionProxyExecuteResponse(
508 + status=200, data={"ok": True}, headers={}, binary_data=None
509 + )
510 )
511 ctx = SessionContextImpl(client=mock_client, user_id="u", session_id="s")
512 result = ctx.proxy_execute(
513 toolkit="gmail", endpoint="https://example.com", method="GET"
514 )
515 + assert isinstance(result, SessionProxyExecuteResponse)
516 assert result.status == 200
517
518
@@ -540,16 +551,16 @@ class TestToolRouterSessionCustomTools:
551 s = _session(mock_session_deps)
552 result = s.execute("GREP", arguments={"pattern": "x"})
553 # Returns SessionExecuteResponse — same type as remote
554 + assert isinstance(result, SessionExecuteResponse)
555 assert result.error is None
556 assert result.log_id == ""
557 assert result.data["matches"] == ["x"]
558 mock_session_deps["client"].tool_router.session.execute.assert_not_called()
559
560 def test_execute_remote(self, mock_session_deps):
549 - mock_response = MagicMock()
550 - mock_response.data = {"sent": True}
551 - mock_response.error = None
552 - mock_response.log_id = "log_123"
561 + mock_response = SessionExecuteResponse(
562 + data={"sent": True}, error=None, log_id="log_123"
563 + )
564 mock_session_deps[
565 "client"
566 ].tool_router.session.execute.return_value = mock_response
@@ -557,9 +568,23 @@ class TestToolRouterSessionCustomTools:
568 result = s.execute("GMAIL_SEND_EMAIL", arguments={"to": "a@b.com"})
569 mock_session_deps["client"].tool_router.session.execute.assert_called_once()
570 # Remote returns client model as-is (backward compat, supports attribute access)
571 + assert isinstance(result, SessionExecuteResponse)
572 assert result.data == {"sent": True}
573 assert result.log_id == "log_123"
574
575 + def test_proxy_execute(self, mock_session_deps):
576 + mock_session_deps["client"].tool_router.session.proxy_execute.return_value = (
577 + SessionProxyExecuteResponse(
578 + status=200, data={"ok": True}, headers={}, binary_data=None
579 + )
580 + )
581 + s = _session(mock_session_deps)
582 + result = s.proxy_execute(
583 + toolkit="gmail", endpoint="https://example.com", method="GET"
584 + )
585 + assert isinstance(result, SessionProxyExecuteResponse)
586 + assert result.status == 200
587 +
588 def test_custom_tools_list(self, mock_session_deps):
589 s = _session(mock_session_deps)
590 assert len(s.custom_tools()) == 3
ts/docs/api/tool-router.md
+127 -115
@@ -39,8 +39,8 @@ import { Composio } from '@composio/core';
39 const composio = new Composio();
40
41 // Create a session for a user with access to Gmail tools
42 -const session = await composio.create('user_123', {
43 - toolkits: ['gmail']
42 +const session = await composio.create('user_123', {
43 + toolkits: ['gmail'],
44 });
45
46 // Use the MCP URL with any MCP-compatible client
@@ -60,8 +60,8 @@ const composio = new Composio({
60 });
61
62 // Create a session for a user with access to Gmail tools
63 -const session = await composio.create('user_123', {
64 - toolkits: ['gmail']
63 +const session = await composio.create('user_123', {
64 + toolkits: ['gmail'],
65 });
66
67 // Get the tools formatted for Vercel AI SDK
@@ -80,8 +80,8 @@ import { Composio } from '@composio/core';
80 const composio = new Composio();
81
82 // Create a session with Gmail access
83 -const session = await composio.create('user_123', {
84 - toolkits: ['gmail']
83 +const session = await composio.create('user_123', {
84 + toolkits: ['gmail'],
85 });
86
87 console.log('Session ID:', session.sessionId);
@@ -111,17 +111,17 @@ Specify which toolkits to enable or disable in the session.
111 ```typescript
112 // Simple array of toolkit slugs to enable
113 const session = await composio.create('user_123', {
114 - toolkits: ['gmail', 'slack', 'github']
114 + toolkits: ['gmail', 'slack', 'github'],
115 });
116
117 // Explicit enabled configuration
118 const session = await composio.create('user_123', {
119 - toolkits: { enable: ['gmail', 'slack'] }
119 + toolkits: { enable: ['gmail', 'slack'] },
120 });
121
122 // Disable specific toolkits (enable all others)
123 const session = await composio.create('user_123', {
124 - toolkits: { disable: ['calendar'] }
124 + toolkits: { disable: ['calendar'] },
125 });
126 ```
127
@@ -138,10 +138,10 @@ const session = await composio.create('user_123', {
138 // OR use enable/disable objects
139 // gmail: { enable: ['gmail_fetch_emails'] }
140 // gmail: { disable: ['gmail_delete_email'] }
141 -
141 +
142 // You can also set tags per toolkit to override global tags
143 - slack: { tags: ['readOnlyHint'] }
144 - }
143 + slack: { tags: ['readOnlyHint'] },
144 + },
145 });
146 ```
147
@@ -153,11 +153,12 @@ Global tags to filter tools by their behavior hints. Tags can be overridden per
153 const session = await composio.create('user_123', {
154 toolkits: ['gmail', 'github'],
155 // Global tags applied to all toolkits
156 - tags: ['readOnlyHint', 'idempotentHint']
156 + tags: ['readOnlyHint', 'idempotentHint'],
157 });
158 ```
159
160 Available tags:
161 +
162 - `readOnlyHint` - Tools that only read data
163 - `destructiveHint` - Tools that modify or delete data
164 - `idempotentHint` - Tools that can be safely retried
@@ -172,8 +173,8 @@ const session = await composio.create('user_123', {
173 toolkits: ['gmail', 'github'],
174 authConfigs: {
175 gmail: 'ac_gmail_work',
175 - github: 'ac_github_personal'
176 - }
176 + github: 'ac_github_personal',
177 + },
178 });
179 ```
180
@@ -185,8 +186,8 @@ Map toolkits to specific connected account IDs:
186 const session = await composio.create('user_123', {
187 toolkits: ['gmail'],
188 connectedAccounts: {
188 - gmail: 'ca_abc123'
189 - }
189 + gmail: 'ca_abc123',
190 + },
191 });
192 ```
193
@@ -198,7 +199,7 @@ Control how connections are managed within the session:
199 // Boolean: enable/disable automatic connection management
200 const session = await composio.create('user_123', {
201 toolkits: ['gmail'],
201 - manageConnections: true // default
202 + manageConnections: true, // default
203 });
204
205 // Object: fine-grained control
@@ -207,8 +208,8 @@ const session = await composio.create('user_123', {
208 manageConnections: {
209 enable: true,
210 callbackUrl: 'https://your-app.com/auth/callback',
210 - waitForConnections: true // Wait for user to complete authentication before proceeding
211 - }
211 + waitForConnections: true, // Wait for user to complete authentication before proceeding
212 + },
213 });
214 ```
215
@@ -222,8 +223,8 @@ const session = await composio.create('user_123', {
223 manageConnections: {
224 enable: true,
225 callbackUrl: 'https://your-app.com/auth/callback',
225 - waitForConnections: true // Session waits for connections to complete
226 - }
226 + waitForConnections: true, // Session waits for connections to complete
227 + },
228 });
229 ```
230
@@ -236,8 +237,8 @@ const session = await composio.create('user_123', {
237 toolkits: ['gmail'],
238 workbench: {
239 enableProxyExecution: true,
239 - autoOffloadThreshold: 400000 // Automatically offload to workbench if response > 400k characters
240 - }
240 + autoOffloadThreshold: 400000, // Automatically offload to workbench if response > 400k characters
241 + },
242 });
243 ```
244
@@ -252,9 +253,9 @@ const session = await composio.create('user_123', {
253 toolkits: ['gmail'],
254 experimental: {
255 assistivePrompt: {
255 - userTimezone: 'America/New_York' // IANA timezone identifier for timezone-aware assistive prompts
256 - }
257 - }
256 + userTimezone: 'America/New_York', // IANA timezone identifier for timezone-aware assistive prompts
257 + },
258 + },
259 });
260
261 // Access the generated assistive prompt from the session response
@@ -281,7 +282,7 @@ const grep = experimental_createTool('GREP', {
282 name: 'Grep Search',
283 description: 'Search for patterns in files',
284 inputParams: z.object({ pattern: z.string(), path: z.string() }),
284 - execute: async (input) => ({ matches: [] }),
285 + execute: async input => ({ matches: [] }),
286 });
287 ```
288
@@ -294,6 +295,7 @@ const getImportant = experimental_createTool('GET_IMPORTANT_EMAILS', {
295 extendsToolkit: 'gmail',
296 inputParams: z.object({ limit: z.number().default(10) }),
297 execute: async (input, ctx) => {
298 + // Same response shape as session.execute(): { data, error, logId }
299 const result = await ctx.execute('GMAIL_SEARCH', { query: 'is:important' });
300 return { emails: result.data };
301 },
@@ -309,7 +311,7 @@ const sed = experimental_createTool('SED', {
311 name: 'Sed Replace',
312 description: 'Find and replace in files',
313 inputParams: z.object({ pattern: z.string(), replacement: z.string() }),
312 - execute: async (input) => ({ replaced: 0 }),
314 + execute: async input => ({ replaced: 0 }),
315 });
316
317 const devTools = experimental_createToolkit('DEV_TOOLS', {
@@ -363,8 +365,8 @@ console.log(session.sessionId);
365 The MCP server configuration for this session, including authentication headers.
366
367 ```typescript
366 -console.log(session.mcp.url); // The URL to connect to
367 -console.log(session.mcp.type); // 'http' or 'sse'
368 +console.log(session.mcp.url); // The URL to connect to
369 +console.log(session.mcp.type); // 'http' or 'sse'
370 console.log(session.mcp.headers); // Authentication headers (includes x-api-key if configured)
371 ```
372
@@ -388,7 +390,7 @@ const tools = await session.tools({
390 afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => {
391 console.log(`Completed ${toolSlug} in session ${sessionId}`);
392 return result;
391 - }
393 + },
394 });
395 ```
396
@@ -417,13 +419,17 @@ const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123',
419 // Customize meta tool schemas
420 console.log(`Modifying schema for ${toolSlug}`);
421 return schema;
420 - }
422 + },
423 });
424
423 -console.log('Available meta tools:', metaTools.map(t => t.name));
425 +console.log(
426 + 'Available meta tools:',
427 + metaTools.map(t => t.name)
428 +);
429 ```
430
431 Meta tools allow you to:
432 +
433 - Authorize new toolkit connections within a session
434 - Query toolkit connection states
435 - Manage session configuration
@@ -437,7 +443,7 @@ Execute a tool within the session. Custom tools run in-process; remote tools are
443 ```typescript
444 // Custom tool
445 const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
440 -console.log(result.data); // { preferences: { ... } }
446 +console.log(result.data); // { preferences: { ... } }
447 console.log(result.error); // null on success
448
449 // Remote Composio tool — same API
@@ -461,14 +467,14 @@ for (const result of results.results) {
467
468 Proxy an API call through Composio's auth layer using the session's connected account. The backend resolves the connected account from the toolkit within the session.
469
470 +`ctx.proxyExecute()` inside a custom tool returns the same response shape as `session.proxyExecute()`.
471 +
472 ```typescript
473 const result = await session.proxyExecute({
474 toolkit: 'github',
475 endpoint: 'https://api.github.com/user',
476 method: 'GET',
469 - parameters: [
470 - { in: 'header', name: 'X-Custom', value: 'value' },
471 - ],
477 + parameters: [{ in: 'header', name: 'X-Custom', value: 'value' }],
478 });
479 ```
480
@@ -504,21 +510,21 @@ for (const toolkit of items) {
510 }
511
512 // Pagination support
507 -const moreToolkits = await session.toolkits({
513 +const moreToolkits = await session.toolkits({
514 nextCursor: nextCursor,
509 - limit: 10
515 + limit: 10,
516 });
517
518 // Filter by specific toolkits
519 const filteredToolkits = await session.toolkits({
514 - toolkits: ['gmail', 'slack']
520 + toolkits: ['gmail', 'slack'],
521 });
522
523 // Combine filtering with pagination
524 const paginatedFilteredToolkits = await session.toolkits({
525 toolkits: ['gmail', 'github'],
526 limit: 5,
521 - nextCursor: 'cursor_abc'
527 + nextCursor: 'cursor_abc',
528 });
529 ```
530
@@ -561,8 +567,8 @@ const composio = new Composio({
567 provider: new VercelProvider(),
568 });
569
564 -const session = await composio.create('user_123', {
565 - toolkits: ['gmail']
570 +const session = await composio.create('user_123', {
571 + toolkits: ['gmail'],
572 });
573
574 const tools = await session.tools();
@@ -591,14 +597,14 @@ import { stepCountIs, streamText } from 'ai';
597
598 // No provider needed when using MCP
599 const composio = new Composio();
594 -const { mcp } = await composio.create('user_123', {
595 - toolkits: ['gmail'],
600 +const { mcp } = await composio.create('user_123', {
601 + toolkits: ['gmail'],
602 manageConnections: true,
603 tools: {
604 gmail: {
605 disable: ['gmail_send_email'], // Disable specific tools
600 - }
601 - }
606 + },
607 + },
608 });
609
610 // Create MCP client using the session URL and headers
@@ -606,8 +612,8 @@ const client = await createMCPClient({
612 transport: {
613 type: 'http',
614 url: mcp.url,
609 - headers: mcp.headers // Uses pre-configured authentication headers
610 - }
615 + headers: mcp.headers, // Uses pre-configured authentication headers
616 + },
617 });
618
619 const tools = await client.tools();
@@ -616,7 +622,7 @@ const stream = await streamText({
622 model: openai('gpt-4o-mini'),
623 prompt: 'Find my last email from gmail?',
624 stopWhen: stepCountIs(10),
619 - onStepFinish: (step) => {
625 + onStepFinish: step => {
626 if (step.toolCalls.length > 0) {
627 for (const toolCall of step.toolCalls) {
628 console.log(`Executed ${toolCall.toolName}`);
@@ -636,41 +642,41 @@ for await (const textPart of stream.textStream) {
642 LangChain can connect to Tool Router via MCP adapters. No provider is needed:
643
644 ```typescript
639 -import { MultiServerMCPClient } from "@langchain/mcp-adapters";
640 -import { ChatOpenAI } from "@langchain/openai";
641 -import { createAgent } from "langchain";
642 -import { Composio } from "@composio/core";
645 +import { MultiServerMCPClient } from '@langchain/mcp-adapters';
646 +import { ChatOpenAI } from '@langchain/openai';
647 +import { createAgent } from 'langchain';
648 +import { Composio } from '@composio/core';
649
650 // No provider needed when using MCP
651 const composio = new Composio();
652
653 const llm = new ChatOpenAI({
648 - model: "gpt-4o",
654 + model: 'gpt-4o',
655 });
656
651 -const session = await composio.create('user_123', {
652 - toolkits: ['gmail']
657 +const session = await composio.create('user_123', {
658 + toolkits: ['gmail'],
659 });
660
655 -const client = new MultiServerMCPClient({
661 +const client = new MultiServerMCPClient({
662 composio: {
657 - transport: "http",
663 + transport: 'http',
664 url: session.mcp.url,
659 - headers: session.mcp.headers // Uses pre-configured authentication headers
665 + headers: session.mcp.headers, // Uses pre-configured authentication headers
666 },
667 });
668
663 -const tools = await client.getTools();
669 +const tools = await client.getTools();
670
671 const agent = createAgent({
666 - name: "Gmail Assistant",
667 - systemPrompt: "You are a helpful gmail assistant.",
672 + name: 'Gmail Assistant',
673 + systemPrompt: 'You are a helpful gmail assistant.',
674 model: llm,
669 - tools,
675 + tools,
676 });
677
678 const result = await agent.invoke({
673 - messages: [{ role: "user", content: "Fetch my last email from gmail" }],
679 + messages: [{ role: 'user', content: 'Fetch my last email from gmail' }],
680 });
681
682 console.log(result);
@@ -687,8 +693,8 @@ import { Composio } from '@composio/core';
693 // No provider needed when using MCP
694 const composio = new Composio();
695
690 -const session = await composio.create('user_123', {
691 - toolkits: ['gmail']
696 +const session = await composio.create('user_123', {
697 + toolkits: ['gmail'],
698 });
699
700 console.log(`Tool Router Session Created: ${session.sessionId}`);
@@ -697,7 +703,7 @@ console.log(`Connecting to MCP server: ${session.mcp.url}`);
703 const mcpTool = hostedMcpTool({
704 serverLabel: 'ComposioApps',
705 serverUrl: session.mcp.url,
700 - headers: session.mcp.headers // Uses pre-configured authentication headers
706 + headers: session.mcp.headers, // Uses pre-configured authentication headers
707 });
708
709 const agent = new Agent({
@@ -724,33 +730,33 @@ for await (const event of stream) {
730 Claude Agents SDK supports MCP servers natively. No provider is needed:
731
732 ```typescript
727 -import { query } from "@anthropic-ai/claude-agent-sdk";
733 +import { query } from '@anthropic-ai/claude-agent-sdk';
734 import { Composio } from '@composio/core';
735
736 // No provider needed when using MCP
737 const composio = new Composio();
738
733 -const session = await composio.create('user_123', {
734 - toolkits: ['gmail']
739 +const session = await composio.create('user_123', {
740 + toolkits: ['gmail'],
741 });
742
743 const stream = await query({
744 prompt: 'Use composio tools to fetch my last email from gmail',
745 options: {
746 model: 'claude-sonnet-4-5-20250929',
741 - permissionMode: "bypassPermissions",
747 + permissionMode: 'bypassPermissions',
748 mcpServers: {
749 composio: {
750 type: 'http',
751 url: session.mcp.url,
746 - headers: session.mcp.headers // Uses pre-configured authentication headers
747 - }
752 + headers: session.mcp.headers, // Uses pre-configured authentication headers
753 + },
754 },
749 - }
755 + },
756 });
757
758 for await (const event of stream) {
753 - if (event.type === "result" && event.subtype === "success") {
759 + if (event.type === 'result' && event.subtype === 'success') {
760 process.stdout.write(event.result);
761 }
762 }
@@ -764,12 +770,12 @@ When a user needs to connect a toolkit, use the `authorize()` method:
770 import { Composio } from '@composio/core';
771
772 const composio = new Composio();
767 -const session = await composio.create('user_123', {
768 - toolkits: ['gmail']
773 +const session = await composio.create('user_123', {
774 + toolkits: ['gmail'],
775 });
776
777 // Initiate authorization for Gmail
772 -const connectionRequest = await session.authorize("gmail");
778 +const connectionRequest = await session.authorize('gmail');
779
780 // Log the redirect URL for the user
781 console.log('Redirect URL:', connectionRequest.redirectUrl);
@@ -782,8 +788,8 @@ console.log('Connected Account:', connectedAccount);
788 You can also provide a custom callback URL:
789
790 ```typescript
785 -const connectionRequest = await session.authorize("gmail", {
786 - callbackUrl: 'https://your-app.com/auth/callback'
791 +const connectionRequest = await session.authorize('gmail', {
792 + callbackUrl: 'https://your-app.com/auth/callback',
793 });
794 ```
795
@@ -798,13 +804,13 @@ const composio = new Composio();
804 const session = await composio.create('user_123');
805
806 // Get all toolkits
801 -const toolkits = await session.toolkits();
807 +const toolkits = await session.toolkits();
808
809 console.log(JSON.stringify({ toolkits }, null, 2));
810
811 // Filter by specific toolkits
812 const gmailAndSlack = await session.toolkits({
807 - toolkits: ['gmail', 'slack']
813 + toolkits: ['gmail', 'slack'],
814 });
815 ```
816
@@ -842,7 +848,7 @@ The response includes:
848 Add custom behavior before and after tool execution. Tool Router supports enhanced session-specific modifiers (v0.4.0+):
849
850 ```typescript
845 -import { SessionExecuteMetaModifiers } from "@composio/core";
851 +import { SessionExecuteMetaModifiers } from '@composio/core';
852
853 const modifiers: SessionExecuteMetaModifiers = {
854 modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
@@ -905,20 +911,23 @@ if (sessionId) {
911 ```typescript
912 interface ToolRouterCreateSessionConfig {
913 toolkits?: string[] | { enable: string[] } | { disable: string[] };
908 - tools?: Record<string,
909 - string[] |
910 - { enable: string[] } |
911 - { disable: string[] } |
912 - { tags: ('readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint')[] }
914 + tools?: Record<
915 + string,
916 + | string[]
917 + | { enable: string[] }
918 + | { disable: string[] }
919 + | { tags: ('readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint')[] }
920 >;
921 tags?: ('readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint')[];
922 authConfigs?: Record<string, string>;
923 connectedAccounts?: Record<string, string>;
917 - manageConnections?: boolean | {
918 - enable?: boolean;
919 - callbackUrl?: string;
920 - waitForConnections?: boolean; // NEW in v0.4.0: Wait for connections to complete
921 - };
924 + manageConnections?:
925 + | boolean
926 + | {
927 + enable?: boolean;
928 + callbackUrl?: string;
929 + waitForConnections?: boolean; // NEW in v0.4.0: Wait for connections to complete
930 + };
931 workbench?: {
932 enableProxyExecution?: boolean;
933 autoOffloadThreshold?: number;
@@ -927,7 +936,7 @@ interface ToolRouterCreateSessionConfig {
936 assistivePrompt?: {
937 userTimezone?: string; // IANA timezone identifier for timezone-aware assistive prompts
938 };
930 - customTools?: CustomTool[]; // Standalone or extension tools (from experimental_createTool)
939 + customTools?: CustomTool[]; // Standalone or extension tools (from experimental_createTool)
940 customToolkits?: CustomToolkit[]; // Grouped no-auth tools (from experimental_createToolkit)
941 };
942 }
@@ -944,16 +953,24 @@ interface ToolRouterSession {
953 headers?: Record<string, string>; // Authentication headers (includes x-api-key if configured)
954 };
955 tools: (modifiers?: ProviderOptions) => Promise<Tools>;
947 - execute: (toolSlug: string, arguments?: Record<string, unknown>) => Promise<ToolRouterSessionExecuteResponse>;
948 - search: (params: { query: string; toolkits?: string[] }) => Promise<ToolRouterSessionSearchResponse>;
949 - proxyExecute: (params: SessionProxyExecuteParams) => Promise<ToolRouterSessionExecuteResponse>;
956 + execute: (
957 + toolSlug: string,
958 + arguments?: Record<string, unknown>
959 + ) => Promise<ToolRouterSessionExecuteResponse>;
960 + search: (params: {
961 + query: string;
962 + toolkits?: string[];
963 + }) => Promise<ToolRouterSessionSearchResponse>;
964 + proxyExecute: (
965 + params: SessionProxyExecuteParams
966 + ) => Promise<ToolRouterSessionProxyExecuteResponse>;
967 authorize: (toolkit: string, options?: { callbackUrl?: string }) => Promise<ConnectionRequest>;
968 toolkits: (options?: {
952 - toolkits?: string[]; // Filter by specific toolkit slugs
953 - nextCursor?: string; // Pagination cursor
954 - limit?: number; // Number of items per page
969 + toolkits?: string[]; // Filter by specific toolkit slugs
970 + nextCursor?: string; // Pagination cursor
971 + limit?: number; // Number of items per page
972 }) => Promise<ToolkitConnectionsDetails>;
956 - files: ToolRouterSessionFilesMount; // List, upload, download, delete files. See tool-router-files.md
973 + files: ToolRouterSessionFilesMount; // List, upload, download, delete files. See tool-router-files.md
974 experimental?: {
975 assistivePrompt?: string; // Generated system prompt for optimal tool router usage
976 };
@@ -987,19 +1004,15 @@ interface ToolkitConnectionState {
1004
1005 ```typescript
1006 interface SessionExecuteMetaModifiers {
990 - modifySchema?: (context: {
991 - toolSlug: string;
992 - toolkitSlug: string;
993 - schema: any;
994 - }) => any;
995 -
1007 + modifySchema?: (context: { toolSlug: string; toolkitSlug: string; schema: any }) => any;
1008 +
1009 beforeExecute?: (context: {
1010 toolSlug: string;
1011 toolkitSlug: string;
1012 sessionId: string;
1013 params: any;
1014 }) => any;
1002 -
1015 +
1016 afterExecute?: (context: {
1017 toolSlug: string;
1018 toolkitSlug: string;
@@ -1021,8 +1034,8 @@ const session = await composio.create('user_123', {
1034 manageConnections: {
1035 enable: true,
1036 callbackUrl: 'https://your-app.com/callback',
1024 - waitForConnections: true // NEW
1025 - }
1037 + waitForConnections: true, // NEW
1038 + },
1039 });
1040 ```
1041
@@ -1035,7 +1048,7 @@ const tools = await session.tools({
1048 beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {
1049 console.log(`[${sessionId}] Executing ${toolSlug}`);
1050 return params;
1038 - }
1051 + },
1052 });
1053 ```
1054
@@ -1045,7 +1058,7 @@ New method to fetch meta tools directly from a session:
1058
1059 ```typescript
1060 const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123', {
1048 - modifySchema: ({ toolSlug, schema }) => schema
1061 + modifySchema: ({ toolSlug, schema }) => schema,
1062 });
1063 ```
1064
@@ -1056,4 +1069,3 @@ const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123',
1069 - Simplified internal tool execution paths
1070
1071 All changes in v0.4.0 are fully backward compatible with existing code.
1059 -
ts/packages/core/src/models/CustomTool.ts
+33 -25
@@ -51,24 +51,30 @@ const MAX_SLUG_LENGTH = 60;
51 */
52 function computeFinalSlugLength(toolSlug: string, toolkitSlug?: string): number {
53 // LOCAL_ + optional TOOLKIT_ + SLUG
54 - return LOCAL_TOOL_PREFIX.length
55 - + (toolkitSlug ? toolkitSlug.length + 1 : 0) // +1 for underscore separator
56 - + toolSlug.length;
54 + return (
55 + LOCAL_TOOL_PREFIX.length +
56 + (toolkitSlug ? toolkitSlug.length + 1 : 0) + // +1 for underscore separator
57 + toolSlug.length
58 + );
59 }
60
61 /**
62 * Validate that the final slug won't exceed the max length.
63 * Called early in createCustomTool/createCustomToolkit for fast feedback.
64 */
63 -function validateSlugLength(toolSlug: string, toolkitSlug: string | undefined, context: string): void {
65 +function validateSlugLength(
66 + toolSlug: string,
67 + toolkitSlug: string | undefined,
68 + context: string
69 +): void {
70 const finalLength = computeFinalSlugLength(toolSlug, toolkitSlug);
71 if (finalLength > MAX_SLUG_LENGTH) {
72 const prefix = LOCAL_TOOL_PREFIX + (toolkitSlug ? `${toolkitSlug.toUpperCase()}_` : '');
73 const available = MAX_SLUG_LENGTH - prefix.length;
74 throw new ValidationError(
75 `${context}: slug "${toolSlug}" is too long. ` +
70 - `With prefix "${prefix}", the final slug would be ${finalLength} characters (max ${MAX_SLUG_LENGTH}). ` +
71 - `Shorten the slug to at most ${available} characters.`
76 + `With prefix "${prefix}", the final slug would be ${finalLength} characters (max ${MAX_SLUG_LENGTH}). ` +
77 + `Shorten the slug to at most ${available} characters.`
78 );
79 }
80 }
@@ -110,6 +116,7 @@ function validateSlugLength(toolSlug: string, toolkitSlug: string | undefined, c
116 * extendsToolkit: 'gmail',
117 * inputParams: z.object({ limit: z.number().default(10) }),
118 * execute: async (input, ctx) => {
119 + * // Same response shape as session.execute(): { data, error, logId }
120 * const result = await ctx.execute('GMAIL_SEARCH', { query: 'is:important' });
121 * return { emails: result.data };
122 * },
@@ -123,7 +130,9 @@ export function createCustomTool<T extends z.ZodType>(
130 // Validate slug separately
131 const slugResult = CustomToolSlugSchema.safeParse(slug);
132 if (!slugResult.success) {
126 - throw new ValidationError(`createCustomTool: ${slugResult.error.issues[0].message}`, { cause: slugResult.error });
133 + throw new ValidationError(`createCustomTool: ${slugResult.error.issues[0].message}`, {
134 + cause: slugResult.error,
135 + });
136 }
137
138 // Validate string/scalar fields via Zod schema
@@ -137,7 +146,7 @@ export function createCustomTool<T extends z.ZodType>(
146 if ((options.inputParams as { _def?: { typeName?: string } })?._def?.typeName !== 'ZodObject') {
147 throw new ValidationError(
148 'createCustomTool: inputParams must be a z.object() schema. ' +
140 - 'Tool input parameters are always an object with named properties.'
149 + 'Tool input parameters are always an object with named properties.'
150 );
151 }
152 if (typeof options.execute !== 'function') {
@@ -211,7 +220,9 @@ export function createCustomToolkit(
220 // Validate slug
221 const slugResult = CustomToolSlugSchema.safeParse(slug);
222 if (!slugResult.success) {
214 - throw new ValidationError(`createCustomToolkit: ${slugResult.error.issues[0].message}`, { cause: slugResult.error });
223 + throw new ValidationError(`createCustomToolkit: ${slugResult.error.issues[0].message}`, {
224 + cause: slugResult.error,
225 + });
226 }
227
228 // Validate name/description
@@ -228,7 +239,7 @@ export function createCustomToolkit(
239 if (tool.extendsToolkit) {
240 throw new ValidationError(
241 `createCustomToolkit: tool "${tool.slug}" has extendsToolkit set. ` +
231 - `Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`
242 + `Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`
243 );
244 }
245 // Early length validation — we know both toolkit slug and tool slug
@@ -278,20 +289,22 @@ export function buildCustomToolsMap(
289 if (finalSlug.length > MAX_SLUG_LENGTH) {
290 throw new ValidationError(
291 `Custom tool slug "${handle.slug}" produces final slug "${finalSlug}" ` +
281 - `which exceeds ${MAX_SLUG_LENGTH} characters.`
292 + `which exceeds ${MAX_SLUG_LENGTH} characters.`
293 );
294 }
295
296 // Check cross-group collisions on final slug
297 if (byFinalSlug.has(finalSlug)) {
287 - throw new ValidationError(`Custom tool slug collision: "${finalSlug}" is already registered.`);
298 + throw new ValidationError(
299 + `Custom tool slug collision: "${finalSlug}" is already registered.`
300 + );
301 }
302
303 // Check cross-group collisions on original slug
304 if (byOriginalSlug.has(originalSlug)) {
305 throw new ValidationError(
306 `Custom tool slug collision: original slug "${handle.slug}" maps to multiple final slugs. ` +
294 - `"${byOriginalSlug.get(originalSlug)!.finalSlug}" and "${finalSlug}" both resolve from "${originalSlug}".`
307 + `"${byOriginalSlug.get(originalSlug)!.finalSlug}" and "${finalSlug}" both resolve from "${originalSlug}".`
308 );
309 }
310
@@ -302,11 +315,7 @@ export function buildCustomToolsMap(
315
316 // Process standalone tools
317 for (const handle of tools) {
305 - addEntry(
306 - handle,
307 - buildFinalSlug(handle.slug, handle.extendsToolkit),
308 - handle.extendsToolkit
309 - );
318 + addEntry(handle, buildFinalSlug(handle.slug, handle.extendsToolkit), handle.extendsToolkit);
319 }
320
321 // Process toolkit tools
@@ -330,9 +339,7 @@ export function buildCustomToolsMap(
339 * @param tools - The custom tools to serialize
340 * @returns Array of CustomToolDefinition for the API payload
341 */
333 -export function serializeCustomTools(
334 - tools: CustomTool[]
335 -): CustomToolDefinition[] {
342 +export function serializeCustomTools(tools: CustomTool[]): CustomToolDefinition[] {
343 return tools.map(handle => ({
344 slug: handle.slug,
345 name: handle.name,
@@ -350,9 +357,7 @@ export function serializeCustomTools(
357 * @param toolkits - The custom toolkits to serialize
358 * @returns Array of CustomToolkitDefinition for the API payload
359 */
353 -export function serializeCustomToolkits(
354 - toolkits: CustomToolkit[]
355 -): CustomToolkitDefinition[] {
360 +export function serializeCustomToolkits(toolkits: CustomToolkit[]): CustomToolkitDefinition[] {
361 return toolkits.map(tk => ({
362 slug: tk.slug,
363 name: tk.name,
@@ -388,7 +393,10 @@ export function buildCustomToolsMapFromResponse(
393 // Build a lookup from original slug → custom tool handle (for matching response items)
394 const handlesByOriginalSlug = new Map<string, { handle: CustomTool; toolkit?: string }>();
395 for (const handle of tools) {
391 - handlesByOriginalSlug.set(handle.slug.toUpperCase(), { handle, toolkit: handle.extendsToolkit });
396 + handlesByOriginalSlug.set(handle.slug.toUpperCase(), {
397 + handle,
398 + toolkit: handle.extendsToolkit,
399 + });
400 }
401 if (toolkits) {
402 for (const tk of toolkits) {
ts/packages/core/src/models/SessionContext.ts
+37 -26
@@ -3,12 +3,19 @@
3 */
4 import { Composio as ComposioClient } from '@composio/client';
5 import type { SessionContext, CustomToolsMap } from '../types/customTool.types';
6 -import type { ToolExecuteResponse } from '../types/tool.types';
7 -import type { SessionProxyExecuteParams, ToolRouterSessionProxyExecuteResponse } from '../types/toolRouter.types';
8 -import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
6 +import type {
7 + SessionProxyExecuteParams,
8 + ToolRouterSessionExecuteResponse,
9 + ToolRouterSessionProxyExecuteResponse,
10 +} from '../types/toolRouter.types';
11 +import {
12 + SessionProxyExecuteParamsSchema,
13 + ToolRouterSessionExecuteResponseSchema,
14 +} from '../types/toolRouter.types';
15 import { ValidationError } from '../errors';
16 import { transformProxyParams } from './proxyParamsTransform';
17 import { findCustomTool, executeCustomTool } from './customToolExecution';
18 +import { transformExecuteResponse } from '../utils/transformers/toolRouterResponseTransform';
19
20 /**
21 * Concrete implementation of SessionContext.
@@ -35,37 +42,39 @@ export class SessionContextImpl implements SessionContext {
42 * Execute any tool from within a custom tool.
43 * Routes to sibling local tools in-process when available,
44 * otherwise delegates to the backend API.
45 + *
46 + * Returns the same response shape as session.execute().
47 */
48 async execute(
49 toolSlug: string,
50 arguments_: Record<string, unknown>
42 - ): Promise<ToolExecuteResponse> {
51 + ): Promise<ToolRouterSessionExecuteResponse> {
52 // Try local tool first (sibling routing)
53 const entry = findCustomTool(this.customToolsMap, toolSlug);
54 if (entry) {
46 - return executeCustomTool(entry, arguments_, this);
55 + const result = await executeCustomTool(entry, arguments_, this);
56 + return ToolRouterSessionExecuteResponseSchema.parse({
57 + data: result.data,
58 + error: result.error,
59 + logId: '',
60 + });
61 }
62
63 // Fall back to remote execution
50 - const response = await this.client.toolRouter.session.execute(
51 - this.sessionId,
52 - {
53 - tool_slug: toolSlug,
54 - arguments: arguments_,
55 - }
56 - );
57 - return {
58 - data: response.data,
59 - error: response.error,
60 - successful: !response.error,
61 - };
64 + const response = await this.client.toolRouter.session.execute(this.sessionId, {
65 + tool_slug: toolSlug,
66 + arguments: arguments_,
67 + });
68 + return ToolRouterSessionExecuteResponseSchema.parse(transformExecuteResponse(response));
69 }
70
71 /**
72 * Proxy API calls through Composio's auth layer.
73 * The backend resolves the connected account from the toolkit within the session.
74 */
68 - async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse> {
75 + async proxyExecute(
76 + params: SessionProxyExecuteParams
77 + ): Promise<ToolRouterSessionProxyExecuteResponse> {
78 const validated = SessionProxyExecuteParamsSchema.safeParse(params);
79 if (!validated.success) {
80 throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });
@@ -81,14 +90,16 @@ export class SessionContextImpl implements SessionContext {
90 status: response.status,
91 data: response.data,
92 headers: response.headers,
84 - ...(response.binary_data ? {
85 - binaryData: {
86 - contentType: response.binary_data.content_type,
87 - size: response.binary_data.size,
88 - url: response.binary_data.url,
89 - expiresAt: response.binary_data.expires_at,
90 - },
91 - } : {}),
93 + ...(response.binary_data
94 + ? {
95 + binaryData: {
96 + contentType: response.binary_data.content_type,
97 + size: response.binary_data.size,
98 + url: response.binary_data.url,
99 + expiresAt: response.binary_data.expires_at,
100 + },
101 + }
102 + : {}),
103 };
104 }
105 }
ts/packages/core/src/types/customTool.types.ts
+9 -6
@@ -1,6 +1,10 @@
1 import { z } from 'zod/v3';
2 -import { Tool, ToolProxyParams, ToolExecuteResponse as SdkToolExecuteResponse } from './tool.types';
3 -import type { SessionProxyExecuteParams, ToolRouterSessionProxyExecuteResponse } from './toolRouter.types';
2 +import { Tool, ToolProxyParams } from './tool.types';
3 +import type {
4 + SessionProxyExecuteParams,
5 + ToolRouterSessionExecuteResponse,
6 + ToolRouterSessionProxyExecuteResponse,
7 +} from './toolRouter.types';
8 import { ToolExecuteResponse } from '@composio/client/resources/tools';
9 import { ConnectionData } from './connectedAccountAuthStates.types';
10 import type {
@@ -74,11 +78,11 @@ export interface ExecuteMetadata {
78 export interface SessionContext {
79 /** The user ID for this session */
80 readonly userId: string;
77 - /** Execute any Composio native tool from within a custom tool */
81 + /** Execute any Composio native tool from within a custom tool. Returns the same shape as session.execute(). */
82 execute(
83 toolSlug: string,
84 arguments_: Record<string, unknown>
81 - ): Promise<SdkToolExecuteResponse>;
85 + ): Promise<ToolRouterSessionExecuteResponse>;
86 /** Proxy API calls through Composio's auth layer (resolved from session toolkit). */
87 proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse>;
88 }
@@ -109,8 +113,7 @@ export const CustomToolSlugSchema = z
113 'slug must only contain alphanumeric characters, underscores, and hyphens'
114 )
115 .refine(s => !s.toUpperCase().startsWith('LOCAL_'), {
112 - message:
113 - 'slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',
116 + message: 'slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',
117 })
118 .refine(s => !s.toUpperCase().startsWith('COMPOSIO_'), {
119 message:
ts/packages/core/test/models/customTool.test.ts
+47 -33
@@ -44,7 +44,10 @@ describe('createCustomTool', () => {
44 });
45
46 it('should include extendsToolkit when provided', () => {
47 - const tool = createCustomTool('GET_AD_ACCOUNTS', { ...baseOptions, extendsToolkit: 'meta_ads' });
47 + const tool = createCustomTool('GET_AD_ACCOUNTS', {
48 + ...baseOptions,
49 + extendsToolkit: 'meta_ads',
50 + });
51 expect(tool.extendsToolkit).toBe('meta_ads');
52 });
53
@@ -137,7 +140,9 @@ describe('createCustomTool', () => {
140
141 describe('other validation', () => {
142 it('should throw if name is missing', () => {
140 - expect(() => createCustomTool('SLUG', { ...baseOptions, name: '' })).toThrow('name is required');
143 + expect(() => createCustomTool('SLUG', { ...baseOptions, name: '' })).toThrow(
144 + 'name is required'
145 + );
146 });
147
148 it('should throw if description is missing', () => {
@@ -251,9 +256,9 @@ describe('createCustomToolkit', () => {
256 });
257
258 it('should throw if tools array is empty', () => {
254 - expect(() =>
255 - createCustomToolkit('TK', { name: 'X', description: 'X', tools: [] })
256 - ).toThrow('at least one tool is required');
259 + expect(() => createCustomToolkit('TK', { name: 'X', description: 'X', tools: [] })).toThrow(
260 + 'at least one tool is required'
261 + );
262 });
263
264 it('should reject tools with extendsToolkit set', () => {
@@ -349,9 +354,7 @@ describe('buildCustomToolsMap', () => {
354
355 describe('collision detection', () => {
356 it('should throw on duplicate standalone slugs', () => {
352 - expect(() => buildCustomToolsMap([makeTool('DUPE'), makeTool('DUPE')])).toThrow(
353 - 'collision'
354 - );
357 + expect(() => buildCustomToolsMap([makeTool('DUPE'), makeTool('DUPE')])).toThrow('collision');
358 });
359
360 it('should throw on cross-group collision (standalone vs toolkit same original slug)', () => {
@@ -371,26 +374,40 @@ describe('buildCustomToolsMap', () => {
374 describe('length validation', () => {
375 it('should throw early in createCustomTool when slug is too long (standalone)', () => {
376 const longSlug = 'A'.repeat(56); // LOCAL_ + 56 = 62 > 60
374 - expect(() => createCustomTool(longSlug, {
375 - name: 'Long', description: 'Too long', inputParams: z.object({}), execute: vi.fn().mockResolvedValue({}),
376 - })).toThrow('too long');
377 + expect(() =>
378 + createCustomTool(longSlug, {
379 + name: 'Long',
380 + description: 'Too long',
381 + inputParams: z.object({}),
382 + execute: vi.fn().mockResolvedValue({}),
383 + })
384 + ).toThrow('too long');
385 });
386
387 it('should throw early in createCustomTool when slug is too long (extension)', () => {
388 // LOCAL_GMAIL_ = 12 chars, so slug > 48 chars overflows
389 const longSlug = 'A'.repeat(49);
382 - expect(() => createCustomTool(longSlug, {
383 - name: 'Long', description: 'Too long', extendsToolkit: 'gmail',
384 - inputParams: z.object({}), execute: vi.fn().mockResolvedValue({}),
385 - })).toThrow('too long');
390 + expect(() =>
391 + createCustomTool(longSlug, {
392 + name: 'Long',
393 + description: 'Too long',
394 + extendsToolkit: 'gmail',
395 + inputParams: z.object({}),
396 + execute: vi.fn().mockResolvedValue({}),
397 + })
398 + ).toThrow('too long');
399 });
400
401 it('should throw early in createCustomToolkit when tool slug is too long', () => {
402 const longSlug = 'A'.repeat(50); // LOCAL_DEV_TOOLS_ + 50 = 66 > 60
403 const tool = makeTool(longSlug);
391 - expect(() => createCustomToolkit('DEV_TOOLS', {
392 - name: 'Dev Tools', description: 'Utilities', tools: [tool],
393 - })).toThrow('too long');
404 + expect(() =>
405 + createCustomToolkit('DEV_TOOLS', {
406 + name: 'Dev Tools',
407 + description: 'Utilities',
408 + tools: [tool],
409 + })
410 + ).toThrow('too long');
411 });
412
413 it('should still validate in buildCustomToolsMap as safety net', () => {
@@ -549,11 +566,11 @@ describe('SessionContextImpl', () => {
566 expect(result).toEqual({
567 data: { result: 'ok' },
568 error: null,
552 - successful: true,
569 + logId: 'log_1',
570 });
571 });
572
556 - it('should set successful=false when execute() returns an error', async () => {
573 + it('should preserve logId and error when execute() returns an error', async () => {
574 mockClient.toolRouter.session.execute.mockResolvedValue({
575 data: {},
576 error: 'something went wrong',
@@ -563,7 +580,7 @@ describe('SessionContextImpl', () => {
580 const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
581 const result = await ctx.execute('BAD_TOOL', {});
582
566 - expect(result.successful).toBe(false);
583 + expect(result.logId).toBe('log_2');
584 expect(result.error).toBe('something went wrong');
585 });
586
@@ -581,15 +598,12 @@ describe('SessionContextImpl', () => {
598 parameters: [{ in: 'header' as const, name: 'X-Custom', value: 'val' }],
599 });
600
584 - expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith(
585 - 'sess_1',
586 - {
587 - toolkit_slug: 'github',
588 - endpoint: 'https://api.github.com/user',
589 - method: 'GET',
590 - parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],
591 - }
592 - );
601 + expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith('sess_1', {
602 + toolkit_slug: 'github',
603 + endpoint: 'https://api.github.com/user',
604 + method: 'GET',
605 + parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],
606 + });
607 expect(result).toEqual({
608 status: 200,
609 data: { proxy_result: true },
@@ -619,7 +633,7 @@ describe('SessionContextImpl', () => {
633 const result = await ctx.execute('SIBLING_TOOL', { key: 'val' });
634
635 expect(siblingExecute).toHaveBeenCalledWith({ key: 'val' }, ctx);
622 - expect(result).toEqual({ data: { local: true }, error: null, successful: true });
636 + expect(result).toEqual({ data: { local: true }, error: null, logId: '' });
637 // Should NOT call remote
638 expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
639 });
@@ -646,7 +660,7 @@ describe('SessionContextImpl', () => {
660 tool_slug: 'REMOTE_TOOL',
661 arguments: { key: 'val' },
662 });
649 - expect(result).toEqual({ data: { remote: true }, error: null, successful: true });
663 + expect(result).toEqual({ data: { remote: true }, error: null, logId: 'log_3' });
664 });
665
666 it('should delegate to remote when no customToolsMap is provided', async () => {
@@ -660,7 +674,7 @@ describe('SessionContextImpl', () => {
674 const result = await ctx.execute('ANY_TOOL', {});
675
676 expect(mockClient.toolRouter.session.execute).toHaveBeenCalled();
663 - expect(result.successful).toBe(true);
677 + expect(result.logId).toBe('log_4');
678 });
679 });
680 });
ts/packages/core/test/models/customToolRouting.test.ts
+75 -40
@@ -46,6 +46,11 @@ const createMockClient = () => ({
46 toolkits: vi.fn(),
47 executeMeta: vi.fn(),
48 search: vi.fn(),
49 + proxyExecute: vi.fn().mockResolvedValue({
50 + status: 200,
51 + data: { ok: true },
52 + headers: { 'x-test': '1' },
53 + }),
54 execute: vi.fn().mockResolvedValue({
55 data: { remote_result: true },
56 error: null,
@@ -276,6 +281,31 @@ describe('ToolRouterSession execution routing', () => {
281 });
282 });
283
284 + describe('session.proxyExecute()', () => {
285 + it('should expose the same proxy response shape used by SessionContext', async () => {
286 + const session = createSession(mockClient, [customToolHandle]);
287 +
288 + const result = await session.proxyExecute({
289 + toolkit: 'github',
290 + endpoint: 'https://api.github.com/user',
291 + method: 'GET',
292 + parameters: [{ in: 'header', name: 'X-Test', value: '1' }],
293 + });
294 +
295 + expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith('sess_123', {
296 + toolkit_slug: 'github',
297 + endpoint: 'https://api.github.com/user',
298 + method: 'GET',
299 + parameters: [{ name: 'X-Test', type: 'header', value: '1' }],
300 + });
301 + expect(result).toEqual({
302 + status: 200,
303 + data: { ok: true },
304 + headers: { 'x-test': '1' },
305 + });
306 + });
307 + });
308 +
309 describe('session.execute() — SessionContext injection', () => {
310 it('should inject SessionContext with correct userId', async () => {
311 const session = createSession(mockClient, [sessionToolHandle]);
@@ -380,10 +410,7 @@ describe('ToolRouterSession execution routing', () => {
410 const session = createSession(mockClient, [toolWithDefaults]);
411 const result = await session.execute('DEFAULTS_TOOL', {});
412
383 - expect(defaultExecute).toHaveBeenCalledWith(
384 - { category: 'all' },
385 - expect.anything()
386 - );
413 + expect(defaultExecute).toHaveBeenCalledWith({ category: 'all' }, expect.anything());
414 expect(result.data).toEqual({ category: 'all' });
415 });
416
@@ -429,9 +456,7 @@ describe('ToolRouterSession execution routing', () => {
456 const executeFn = (provider as any)._capturedExecuteFn;
457
458 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
432 - tools: [
433 - { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'test' } },
434 - ],
459 + tools: [{ tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'test' } }],
460 sync_response_to_workbench: false,
461 });
462
@@ -451,9 +476,7 @@ describe('ToolRouterSession execution routing', () => {
476 const executeFn = (provider as any)._capturedExecuteFn;
477
478 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
454 - tools: [
455 - { tool_slug: 'GET_USER_CONTEXT', arguments: { category: 'no-prefix' } },
456 - ],
479 + tools: [{ tool_slug: 'GET_USER_CONTEXT', arguments: { category: 'no-prefix' } }],
480 sync_response_to_workbench: false,
481 });
482
@@ -473,9 +496,7 @@ describe('ToolRouterSession execution routing', () => {
496 const executeFn = (provider as any)._capturedExecuteFn;
497
498 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
476 - tools: [
477 - { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'test@test.com' } },
478 - ],
499 + tools: [{ tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'test@test.com' } }],
500 sync_response_to_workbench: false,
501 });
502
@@ -522,15 +543,12 @@ describe('ToolRouterSession execution routing', () => {
543 const session = createSessionWithProvider(client, provider, customTools);
544 await session.tools();
545 const executeFn = (provider as any)._capturedExecuteFn;
525 - const toolsInstance = (Tools as any).mock.results[
526 - (Tools as any).mock.results.length - 1
527 - ].value;
546 + const toolsInstance = (Tools as any).mock.results[(Tools as any).mock.results.length - 1]
547 + .value;
548 return { executeFn, toolsInstance, provider, session };
549 };
550
531 - const backendResponse = (
532 - results: Array<{ tool_slug: string; data: any; error?: string }>,
533 - ) => {
551 + const backendResponse = (results: Array<{ tool_slug: string; data: any; error?: string }>) => {
552 const items = results.map((r, i) => ({
553 response: {
554 successful: !r.error,
@@ -583,7 +601,10 @@ describe('ToolRouterSession execution routing', () => {
601 });
602
603 it('should handle multiple local tools in same batch', async () => {
586 - const { executeFn } = await setupMultiExecute(mockClient, [customToolHandle, sessionToolHandle]);
604 + const { executeFn } = await setupMultiExecute(mockClient, [
605 + customToolHandle,
606 + sessionToolHandle,
607 + ]);
608
609 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
610 tools: [
@@ -609,10 +630,10 @@ describe('ToolRouterSession execution routing', () => {
630 });
631
632 it('should handle mixed batch with multiple locals + multiple remotes', async () => {
612 - const { executeFn, toolsInstance } = await setupMultiExecute(
613 - mockClient,
614 - [customToolHandle, sessionToolHandle]
615 - );
633 + const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [
634 + customToolHandle,
635 + sessionToolHandle,
636 + ]);
637
638 toolsInstance.executeMetaTool.mockResolvedValueOnce(
639 backendResponse([
@@ -655,18 +676,24 @@ describe('ToolRouterSession execution routing', () => {
676 name: 'Throws in batch',
677 description: 'Throws',
678 inputParams: z.object({}),
658 - execute: async () => { throw new Error('batch-boom'); },
679 + execute: async () => {
680 + throw new Error('batch-boom');
681 + },
682 });
683
661 - const { executeFn, toolsInstance } = await setupMultiExecute(
662 - mockClient,
663 - [customToolHandle, throwingHandle]
664 - );
684 + const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [
685 + customToolHandle,
686 + throwingHandle,
687 + ]);
688
689 toolsInstance.executeMetaTool.mockResolvedValueOnce(
690 backendResponse([
691 { tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } },
669 - { tool_slug: 'SLACK_POST_MESSAGE', data: { message: 'auth failed' }, error: 'auth failed' },
692 + {
693 + tool_slug: 'SLACK_POST_MESSAGE',
694 + data: { message: 'auth failed' },
695 + error: 'auth failed',
696 + },
697 ])
698 );
699
@@ -719,12 +746,14 @@ describe('ToolRouterSession execution routing', () => {
746 it('should handle non-object items in tools array gracefully', async () => {
747 const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
748
722 - toolsInstance.executeMetaTool.mockResolvedValueOnce(
723 - backendResponse([])
724 - );
749 + toolsInstance.executeMetaTool.mockResolvedValueOnce(backendResponse([]));
750
751 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
727 - tools: ['not-an-object', null, { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } }],
752 + tools: [
753 + 'not-an-object',
754 + null,
755 + { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } },
756 + ],
757 sync_response_to_workbench: false,
758 });
759
@@ -756,9 +785,8 @@ describe('ToolRouterSession execution routing', () => {
785 const session = createSessionWithProvider(mockClient, provider, [slowLocalHandle]);
786 await session.tools();
787 const executeFn = (provider as any)._capturedExecuteFn;
759 - const toolsInstance = (Tools as any).mock.results[
760 - (Tools as any).mock.results.length - 1
761 - ].value;
788 + const toolsInstance = (Tools as any).mock.results[(Tools as any).mock.results.length - 1]
789 + .value;
790
791 toolsInstance.executeMetaTool.mockImplementation(async () => {
792 callOrder.push('remote-start');
@@ -818,8 +846,16 @@ describe('ToolRouterSession execution routing', () => {
846 latestToolsInstance.executeMetaTool.mockResolvedValueOnce({
847 data: {
848 results: [
821 - { response: { successful: true, data: { message_id: 'msg_1' } }, tool_slug: 'GMAIL_SEND_EMAIL', index: 0 },
822 - { response: { successful: true, data: { ts: '123456' } }, tool_slug: 'SLACK_POST_MESSAGE', index: 1 },
849 + {
850 + response: { successful: true, data: { message_id: 'msg_1' } },
851 + tool_slug: 'GMAIL_SEND_EMAIL',
852 + index: 0,
853 + },
854 + {
855 + response: { successful: true, data: { ts: '123456' } },
856 + tool_slug: 'SLACK_POST_MESSAGE',
857 + index: 1,
858 + },
859 ],
860 total_count: 2,
861 success_count: 2,
@@ -872,5 +908,4 @@ describe('ToolRouterSession execution routing', () => {
908 );
909 });
910 });
875 -
911 });