Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(tool-router): align session and context response shapes
Dhawal Upadhyay635473ac3766
diff --git a/python/composio/core/models/custom_tool_types.py b/python/composio/core/models/custom_tool_types.pyindex 81bf391d4..4fae37115 100644--- a/python/composio/core/models/custom_tool_types.py+++ b/python/composio/core/models/custom_tool_types.py@@ -63,7 +63,10 @@ class SessionContext(te.Protocol):tool_slug: str,arguments: t.Dict[str, t.Any],) -> SessionExecuteResponse:- """Execute any Composio tool from within a custom tool."""+ """Execute any Composio tool from within a custom tool.++ Returns the same response model as ``session.execute()``.+ """...def proxy_execute(@@ -75,7 +78,10 @@ class SessionContext(te.Protocol):body: t.Any = None,parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,) -> SessionProxyExecuteResponse:- """Proxy API calls through Composio's auth layer."""+ """Proxy API calls through Composio's auth layer.++ Returns the same response model as ``session.proxy_execute()``.+ """...diff --git a/python/composio/core/models/session_context.py b/python/composio/core/models/session_context.pyindex b0c0dcd3e..fe1969b0f 100644--- a/python/composio/core/models/session_context.py+++ b/python/composio/core/models/session_context.py@@ -118,6 +118,8 @@ class SessionContextImpl:Routes to sibling local tools in-process when available,otherwise delegates to the backend API.++ Returns the same response model as ``session.execute()``."""# Try local tool first (sibling routing)entry = find_custom_tool(self._custom_tools_map, tool_slug)@@ -148,7 +150,10 @@ class SessionContextImpl:body: t.Any = None,parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,) -> SessionProxyExecuteResponse:- """Proxy API calls through Composio's auth layer."""+ """Proxy API calls through Composio's auth layer.++ Returns the same response model as ``session.proxy_execute()``.+ """return proxy_execute_impl(self._client,self._session_id,diff --git a/python/tests/test_custom_tools.py b/python/tests/test_custom_tools.pyindex ec14615fe..8687a3852 100644--- a/python/tests/test_custom_tools.py+++ b/python/tests/test_custom_tools.py@@ -15,6 +15,12 @@ Covers:from unittest.mock import MagicMockimport pytest+from composio_client.types.tool_router.session_execute_response import (+ SessionExecuteResponse,+)+from composio_client.types.tool_router.session_proxy_execute_response import (+ SessionProxyExecuteResponse,+)from pydantic import BaseModel, Fieldfrom composio.core.models.custom_tool import (@@ -478,14 +484,16 @@ class TestSessionContextImpl:client=MagicMock(), user_id="u", session_id="s", custom_tools_map=m)result = ctx.execute("GREP", {"pattern": "test"})+ assert isinstance(result, SessionExecuteResponse)assert result.error is None+ assert result.log_id == ""assert result.data["matches"] == ["test"]def test_remote_fallback(self, grep_tool):m = build_custom_tools_map([grep_tool])mock_client = MagicMock()- mock_client.tool_router.session.execute.return_value = MagicMock(- data={"remote": True}, error=None+ mock_client.tool_router.session.execute.return_value = SessionExecuteResponse(+ data={"remote": True}, error=None, log_id="log_123")ctx = SessionContextImpl(client=mock_client, user_id="u", session_id="s", custom_tools_map=m@@ -495,13 +503,16 @@ class TestSessionContextImpl:def test_proxy_execute(self):mock_client = MagicMock()- mock_client.tool_router.session.proxy_execute.return_value = MagicMock(- status=200, data={"ok": True}, headers={}, binary_data=None+ mock_client.tool_router.session.proxy_execute.return_value = (+ SessionProxyExecuteResponse(+ status=200, data={"ok": True}, headers={}, binary_data=None+ ))ctx = SessionContextImpl(client=mock_client, user_id="u", session_id="s")result = ctx.proxy_execute(toolkit="gmail", endpoint="https://example.com", method="GET")+ assert isinstance(result, SessionProxyExecuteResponse)assert result.status == 200@@ -540,16 +551,16 @@ class TestToolRouterSessionCustomTools:s = _session(mock_session_deps)result = s.execute("GREP", arguments={"pattern": "x"})# Returns SessionExecuteResponse — same type as remote+ assert isinstance(result, SessionExecuteResponse)assert result.error is Noneassert result.log_id == ""assert result.data["matches"] == ["x"]mock_session_deps["client"].tool_router.session.execute.assert_not_called()def test_execute_remote(self, mock_session_deps):- mock_response = MagicMock()- mock_response.data = {"sent": True}- mock_response.error = None- mock_response.log_id = "log_123"+ mock_response = SessionExecuteResponse(+ data={"sent": True}, error=None, log_id="log_123"+ )mock_session_deps["client"].tool_router.session.execute.return_value = mock_response@@ -557,9 +568,23 @@ class TestToolRouterSessionCustomTools:result = s.execute("GMAIL_SEND_EMAIL", arguments={"to": "[email protected]"})mock_session_deps["client"].tool_router.session.execute.assert_called_once()# Remote returns client model as-is (backward compat, supports attribute access)+ assert isinstance(result, SessionExecuteResponse)assert result.data == {"sent": True}assert result.log_id == "log_123"+ def test_proxy_execute(self, mock_session_deps):+ mock_session_deps["client"].tool_router.session.proxy_execute.return_value = (+ SessionProxyExecuteResponse(+ status=200, data={"ok": True}, headers={}, binary_data=None+ )+ )+ s = _session(mock_session_deps)+ result = s.proxy_execute(+ toolkit="gmail", endpoint="https://example.com", method="GET"+ )+ assert isinstance(result, SessionProxyExecuteResponse)+ assert result.status == 200+def test_custom_tools_list(self, mock_session_deps):s = _session(mock_session_deps)assert len(s.custom_tools()) == 3diff --git a/ts/docs/api/tool-router.md b/ts/docs/api/tool-router.mdindex 5c78a2887..ca15f96ca 100644--- a/ts/docs/api/tool-router.md+++ b/ts/docs/api/tool-router.md@@ -39,8 +39,8 @@ import { Composio } from '@composio/core';const composio = new Composio();// Create a session for a user with access to Gmail tools-const session = await composio.create('user_123', {- toolkits: ['gmail']+const session = await composio.create('user_123', {+ toolkits: ['gmail'],});// Use the MCP URL with any MCP-compatible client@@ -60,8 +60,8 @@ const composio = new Composio({});// Create a session for a user with access to Gmail tools-const session = await composio.create('user_123', {- toolkits: ['gmail']+const session = await composio.create('user_123', {+ toolkits: ['gmail'],});// Get the tools formatted for Vercel AI SDK@@ -80,8 +80,8 @@ import { Composio } from '@composio/core';const composio = new Composio();// Create a session with Gmail access-const session = await composio.create('user_123', {- toolkits: ['gmail']+const session = await composio.create('user_123', {+ toolkits: ['gmail'],});console.log('Session ID:', session.sessionId);@@ -111,17 +111,17 @@ Specify which toolkits to enable or disable in the session.```typescript// Simple array of toolkit slugs to enableconst session = await composio.create('user_123', {- toolkits: ['gmail', 'slack', 'github']+ toolkits: ['gmail', 'slack', 'github'],});// Explicit enabled configurationconst session = await composio.create('user_123', {- toolkits: { enable: ['gmail', 'slack'] }+ toolkits: { enable: ['gmail', 'slack'] },});// Disable specific toolkits (enable all others)const session = await composio.create('user_123', {- toolkits: { disable: ['calendar'] }+ toolkits: { disable: ['calendar'] },});```@@ -138,10 +138,10 @@ const session = await composio.create('user_123', {// OR use enable/disable objects// gmail: { enable: ['gmail_fetch_emails'] }// gmail: { disable: ['gmail_delete_email'] }-+// You can also set tags per toolkit to override global tags- slack: { tags: ['readOnlyHint'] }- }+ slack: { tags: ['readOnlyHint'] },+ },});```@@ -153,11 +153,12 @@ Global tags to filter tools by their behavior hints. Tags can be overridden perconst session = await composio.create('user_123', {toolkits: ['gmail', 'github'],// Global tags applied to all toolkits- tags: ['readOnlyHint', 'idempotentHint']+ 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@@ -172,8 +173,8 @@ const session = await composio.create('user_123', {toolkits: ['gmail', 'github'],authConfigs: {gmail: 'ac_gmail_work',- github: 'ac_github_personal'- }+ github: 'ac_github_personal',+ },});```@@ -185,8 +186,8 @@ Map toolkits to specific connected account IDs:const session = await composio.create('user_123', {toolkits: ['gmail'],connectedAccounts: {- gmail: 'ca_abc123'- }+ gmail: 'ca_abc123',+ },});```@@ -198,7 +199,7 @@ Control how connections are managed within the session:// Boolean: enable/disable automatic connection managementconst session = await composio.create('user_123', {toolkits: ['gmail'],- manageConnections: true // default+ manageConnections: true, // default});// Object: fine-grained control@@ -207,8 +208,8 @@ const session = await composio.create('user_123', {manageConnections: {enable: true,callbackUrl: 'https://your-app.com/auth/callback',- waitForConnections: true // Wait for user to complete authentication before proceeding- }+ waitForConnections: true, // Wait for user to complete authentication before proceeding+ },});```@@ -222,8 +223,8 @@ const session = await composio.create('user_123', {manageConnections: {enable: true,callbackUrl: 'https://your-app.com/auth/callback',- waitForConnections: true // Session waits for connections to complete- }+ waitForConnections: true, // Session waits for connections to complete+ },});```@@ -236,8 +237,8 @@ const session = await composio.create('user_123', {toolkits: ['gmail'],workbench: {enableProxyExecution: true,- autoOffloadThreshold: 400000 // Automatically offload to workbench if response > 400k characters- }+ autoOffloadThreshold: 400000, // Automatically offload to workbench if response > 400k characters+ },});```@@ -252,9 +253,9 @@ const session = await composio.create('user_123', {toolkits: ['gmail'],experimental: {assistivePrompt: {- userTimezone: 'America/New_York' // IANA timezone identifier for timezone-aware assistive prompts- }- }+ userTimezone: 'America/New_York', // IANA timezone identifier for timezone-aware assistive prompts+ },+ },});// Access the generated assistive prompt from the session response@@ -281,7 +282,7 @@ const grep = experimental_createTool('GREP', {name: 'Grep Search',description: 'Search for patterns in files',inputParams: z.object({ pattern: z.string(), path: z.string() }),- execute: async (input) => ({ matches: [] }),+ execute: async input => ({ matches: [] }),});```@@ -294,6 +295,7 @@ const getImportant = experimental_createTool('GET_IMPORTANT_EMAILS', {extendsToolkit: 'gmail',inputParams: z.object({ limit: z.number().default(10) }),execute: async (input, ctx) => {+ // Same response shape as session.execute(): { data, error, logId }const result = await ctx.execute('GMAIL_SEARCH', { query: 'is:important' });return { emails: result.data };},@@ -309,7 +311,7 @@ const sed = experimental_createTool('SED', {name: 'Sed Replace',description: 'Find and replace in files',inputParams: z.object({ pattern: z.string(), replacement: z.string() }),- execute: async (input) => ({ replaced: 0 }),+ execute: async input => ({ replaced: 0 }),});const devTools = experimental_createToolkit('DEV_TOOLS', {@@ -363,8 +365,8 @@ console.log(session.sessionId);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.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 if configured)```@@ -388,7 +390,7 @@ const tools = await session.tools({afterExecute: ({ toolSlug, toolkitSlug, sessionId, result }) => {console.log(`Completed ${toolSlug} in session ${sessionId}`);return result;- }+ },});```@@ -417,13 +419,17 @@ const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123',// Customize meta tool schemasconsole.log(`Modifying schema for ${toolSlug}`);return schema;- }+ },});-console.log('Available meta tools:', metaTools.map(t => t.name));+console.log(+ 'Available meta tools:',+ metaTools.map(t => t.name)+);```Meta tools allow you to:+- Authorize new toolkit connections within a session- Query toolkit connection states- Manage session configuration@@ -437,7 +443,7 @@ Execute a tool within the session. Custom tools run in-process; remote tools are```typescript// Custom toolconst result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });-console.log(result.data); // { preferences: { ... } }+console.log(result.data); // { preferences: { ... } }console.log(result.error); // null on success// Remote Composio tool — same API@@ -461,14 +467,14 @@ for (const result of results.results) {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.+`ctx.proxyExecute()` inside a custom tool returns the same response shape as `session.proxyExecute()`.+```typescriptconst result = await session.proxyExecute({toolkit: 'github',endpoint: 'https://api.github.com/user',method: 'GET',- parameters: [- { in: 'header', name: 'X-Custom', value: 'value' },- ],+ parameters: [{ in: 'header', name: 'X-Custom', value: 'value' }],});```@@ -504,21 +510,21 @@ for (const toolkit of items) {}// Pagination support-const moreToolkits = await session.toolkits({+const moreToolkits = await session.toolkits({nextCursor: nextCursor,- limit: 10+ limit: 10,});// Filter by specific toolkitsconst filteredToolkits = await session.toolkits({- toolkits: ['gmail', 'slack']+ toolkits: ['gmail', 'slack'],});// Combine filtering with paginationconst paginatedFilteredToolkits = await session.toolkits({toolkits: ['gmail', 'github'],limit: 5,- nextCursor: 'cursor_abc'+ nextCursor: 'cursor_abc',});```@@ -561,8 +567,8 @@ const composio = new Composio({provider: new VercelProvider(),});-const session = await composio.create('user_123', {- toolkits: ['gmail']+const session = await composio.create('user_123', {+ toolkits: ['gmail'],});const tools = await session.tools();@@ -591,14 +597,14 @@ import { stepCountIs, streamText } from 'ai';// No provider needed when using MCPconst composio = new Composio();-const { mcp } = await composio.create('user_123', {- toolkits: ['gmail'],+const { mcp } = await composio.create('user_123', {+ toolkits: ['gmail'],manageConnections: true,tools: {gmail: {disable: ['gmail_send_email'], // Disable specific tools- }- }+ },+ },});// Create MCP client using the session URL and headers@@ -606,8 +612,8 @@ 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+ },});const tools = await client.tools();@@ -616,7 +622,7 @@ const stream = await streamText({model: openai('gpt-4o-mini'),prompt: 'Find my last email from gmail?',stopWhen: stepCountIs(10),- onStepFinish: (step) => {+ onStepFinish: step => {if (step.toolCalls.length > 0) {for (const toolCall of step.toolCalls) {console.log(`Executed ${toolCall.toolName}`);@@ -636,41 +642,41 @@ for await (const textPart of stream.textStream) {LangChain can connect to Tool Router via MCP adapters. No provider is needed:```typescript-import { MultiServerMCPClient } from "@langchain/mcp-adapters";-import { ChatOpenAI } from "@langchain/openai";-import { createAgent } from "langchain";-import { Composio } from "@composio/core";+import { MultiServerMCPClient } from '@langchain/mcp-adapters';+import { ChatOpenAI } from '@langchain/openai';+import { createAgent } from 'langchain';+import { Composio } from '@composio/core';// No provider needed when using MCPconst composio = new Composio();const llm = new ChatOpenAI({- model: "gpt-4o",+ model: 'gpt-4o',});-const session = await composio.create('user_123', {- toolkits: ['gmail']+const session = await composio.create('user_123', {+ toolkits: ['gmail'],});-const client = new MultiServerMCPClient({+const client = new MultiServerMCPClient({composio: {- transport: "http",+ transport: 'http',url: session.mcp.url,- headers: session.mcp.headers // Uses pre-configured authentication headers+ headers: session.mcp.headers, // Uses pre-configured authentication headers},});-const tools = await client.getTools();+const tools = await client.getTools();const agent = createAgent({- name: "Gmail Assistant",- systemPrompt: "You are a helpful gmail assistant.",+ name: 'Gmail Assistant',+ systemPrompt: 'You are a helpful gmail assistant.',model: llm,- tools,+ tools,});const result = await agent.invoke({- messages: [{ role: "user", content: "Fetch my last email from gmail" }],+ messages: [{ role: 'user', content: 'Fetch my last email from gmail' }],});console.log(result);@@ -687,8 +693,8 @@ import { Composio } from '@composio/core';// No provider needed when using MCPconst composio = new Composio();-const session = await composio.create('user_123', {- toolkits: ['gmail']+const session = await composio.create('user_123', {+ toolkits: ['gmail'],});console.log(`Tool Router Session Created: ${session.sessionId}`);@@ -697,7 +703,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({@@ -724,33 +730,33 @@ for await (const event of stream) {Claude Agents SDK supports MCP servers natively. No provider is needed:```typescript-import { query } from "@anthropic-ai/claude-agent-sdk";+import { query } from '@anthropic-ai/claude-agent-sdk';import { Composio } from '@composio/core';// No provider needed when using MCPconst composio = new Composio();-const session = await composio.create('user_123', {- toolkits: ['gmail']+const session = await composio.create('user_123', {+ toolkits: ['gmail'],});const stream = await query({prompt: 'Use composio tools to fetch my last email from gmail',options: {model: 'claude-sonnet-4-5-20250929',- permissionMode: "bypassPermissions",+ permissionMode: 'bypassPermissions',mcpServers: {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+ },},- }+ },});for await (const event of stream) {- if (event.type === "result" && event.subtype === "success") {+ if (event.type === 'result' && event.subtype === 'success') {process.stdout.write(event.result);}}@@ -764,12 +770,12 @@ When a user needs to connect a toolkit, use the `authorize()` method:import { Composio } from '@composio/core';const composio = new Composio();-const session = await composio.create('user_123', {- toolkits: ['gmail']+const session = await composio.create('user_123', {+ toolkits: ['gmail'],});// Initiate authorization for Gmail-const connectionRequest = await session.authorize("gmail");+const connectionRequest = await session.authorize('gmail');// Log the redirect URL for the userconsole.log('Redirect URL:', connectionRequest.redirectUrl);@@ -782,8 +788,8 @@ console.log('Connected Account:', connectedAccount);You can also provide a custom callback URL:```typescript-const connectionRequest = await session.authorize("gmail", {- callbackUrl: 'https://your-app.com/auth/callback'+const connectionRequest = await session.authorize('gmail', {+ callbackUrl: 'https://your-app.com/auth/callback',});```@@ -798,13 +804,13 @@ const composio = new Composio();const session = await composio.create('user_123');// Get all toolkits-const toolkits = await session.toolkits();+const toolkits = await session.toolkits();console.log(JSON.stringify({ toolkits }, null, 2));// Filter by specific toolkitsconst gmailAndSlack = await session.toolkits({- toolkits: ['gmail', 'slack']+ toolkits: ['gmail', 'slack'],});```@@ -842,7 +848,7 @@ The response includes:Add custom behavior before and after tool execution. Tool Router supports enhanced session-specific modifiers (v0.4.0+):```typescript-import { SessionExecuteMetaModifiers } from "@composio/core";+import { SessionExecuteMetaModifiers } from '@composio/core';const modifiers: SessionExecuteMetaModifiers = {modifySchema: ({ toolSlug, toolkitSlug, schema }) => {@@ -905,20 +911,23 @@ if (sessionId) {```typescriptinterface ToolRouterCreateSessionConfig {toolkits?: string[] | { enable: string[] } | { disable: string[] };- tools?: Record<string,- string[] |- { enable: string[] } |- { disable: string[] } |- { tags: ('readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint')[] }+ tools?: Record<+ string,+ | string[]+ | { enable: string[] }+ | { disable: string[] }+ | { tags: ('readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint')[] }>;tags?: ('readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint')[];authConfigs?: Record<string, string>;connectedAccounts?: Record<string, string>;- manageConnections?: boolean | {- enable?: boolean;- callbackUrl?: string;- waitForConnections?: boolean; // NEW in v0.4.0: Wait for connections to complete- };+ manageConnections?:+ | boolean+ | {+ enable?: boolean;+ callbackUrl?: string;+ waitForConnections?: boolean; // NEW in v0.4.0: Wait for connections to complete+ };workbench?: {enableProxyExecution?: boolean;autoOffloadThreshold?: number;@@ -927,7 +936,7 @@ interface ToolRouterCreateSessionConfig {assistivePrompt?: {userTimezone?: string; // IANA timezone identifier for timezone-aware assistive prompts};- customTools?: CustomTool[]; // Standalone or extension tools (from experimental_createTool)+ customTools?: CustomTool[]; // Standalone or extension tools (from experimental_createTool)customToolkits?: CustomToolkit[]; // Grouped no-auth tools (from experimental_createToolkit)};}@@ -944,16 +953,24 @@ interface ToolRouterSession {headers?: Record<string, string>; // Authentication headers (includes x-api-key if configured)};tools: (modifiers?: ProviderOptions) => Promise<Tools>;- execute: (toolSlug: string, arguments?: Record<string, unknown>) => Promise<ToolRouterSessionExecuteResponse>;- search: (params: { query: string; toolkits?: string[] }) => Promise<ToolRouterSessionSearchResponse>;- proxyExecute: (params: SessionProxyExecuteParams) => Promise<ToolRouterSessionExecuteResponse>;+ execute: (+ toolSlug: string,+ arguments?: Record<string, unknown>+ ) => Promise<ToolRouterSessionExecuteResponse>;+ search: (params: {+ query: string;+ toolkits?: string[];+ }) => Promise<ToolRouterSessionSearchResponse>;+ proxyExecute: (+ params: SessionProxyExecuteParams+ ) => Promise<ToolRouterSessionProxyExecuteResponse>;authorize: (toolkit: string, options?: { callbackUrl?: string }) => Promise<ConnectionRequest>;toolkits: (options?: {- toolkits?: string[]; // Filter by specific toolkit slugs- nextCursor?: string; // Pagination cursor- limit?: number; // Number of items per page+ toolkits?: string[]; // Filter by specific toolkit slugs+ nextCursor?: string; // Pagination cursor+ limit?: number; // Number of items per page}) => Promise<ToolkitConnectionsDetails>;- files: ToolRouterSessionFilesMount; // List, upload, download, delete files. See tool-router-files.md+ files: ToolRouterSessionFilesMount; // List, upload, download, delete files. See tool-router-files.mdexperimental?: {assistivePrompt?: string; // Generated system prompt for optimal tool router usage};@@ -987,19 +1004,15 @@ interface ToolkitConnectionState {```typescriptinterface SessionExecuteMetaModifiers {- modifySchema?: (context: {- toolSlug: string;- toolkitSlug: string;- schema: any;- }) => any;-+ modifySchema?: (context: { toolSlug: string; toolkitSlug: string; schema: any }) => any;+beforeExecute?: (context: {toolSlug: string;toolkitSlug: string;sessionId: string;params: any;}) => any;-+afterExecute?: (context: {toolSlug: string;toolkitSlug: string;@@ -1021,8 +1034,8 @@ const session = await composio.create('user_123', {manageConnections: {enable: true,callbackUrl: 'https://your-app.com/callback',- waitForConnections: true // NEW- }+ waitForConnections: true, // NEW+ },});```@@ -1035,7 +1048,7 @@ const tools = await session.tools({beforeExecute: ({ toolSlug, toolkitSlug, sessionId, params }) => {console.log(`[${sessionId}] Executing ${toolSlug}`);return params;- }+ },});```@@ -1045,7 +1058,7 @@ New method to fetch meta tools directly from a session:```typescriptconst metaTools = await composio.tools.getRawToolRouterMetaTools('session_123', {- modifySchema: ({ toolSlug, schema }) => schema+ modifySchema: ({ toolSlug, schema }) => schema,});```@@ -1056,4 +1069,3 @@ const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123',- Simplified internal tool execution pathsAll changes in v0.4.0 are fully backward compatible with existing code.-diff --git a/ts/packages/core/src/models/CustomTool.ts b/ts/packages/core/src/models/CustomTool.tsindex 200bcee3d..3b8d21852 100644--- a/ts/packages/core/src/models/CustomTool.ts+++ b/ts/packages/core/src/models/CustomTool.ts@@ -51,24 +51,30 @@ const MAX_SLUG_LENGTH = 60;*/function computeFinalSlugLength(toolSlug: string, toolkitSlug?: string): number {// LOCAL_ + optional TOOLKIT_ + SLUG- return LOCAL_TOOL_PREFIX.length- + (toolkitSlug ? toolkitSlug.length + 1 : 0) // +1 for underscore separator- + toolSlug.length;+ return (+ LOCAL_TOOL_PREFIX.length ++ (toolkitSlug ? toolkitSlug.length + 1 : 0) + // +1 for underscore separator+ toolSlug.length+ );}/*** Validate that the final slug won't exceed the max length.* Called early in createCustomTool/createCustomToolkit for fast feedback.*/-function validateSlugLength(toolSlug: string, toolkitSlug: string | undefined, context: string): void {+function validateSlugLength(+ toolSlug: string,+ toolkitSlug: string | undefined,+ context: string+): void {const finalLength = computeFinalSlugLength(toolSlug, toolkitSlug);if (finalLength > MAX_SLUG_LENGTH) {const prefix = LOCAL_TOOL_PREFIX + (toolkitSlug ? `${toolkitSlug.toUpperCase()}_` : '');const available = MAX_SLUG_LENGTH - prefix.length;throw new ValidationError(`${context}: slug "${toolSlug}" is too long. ` +- `With prefix "${prefix}", the final slug would be ${finalLength} characters (max ${MAX_SLUG_LENGTH}). ` +- `Shorten the slug to at most ${available} characters.`+ `With prefix "${prefix}", the final slug would be ${finalLength} characters (max ${MAX_SLUG_LENGTH}). ` ++ `Shorten the slug to at most ${available} characters.`);}}@@ -110,6 +116,7 @@ function validateSlugLength(toolSlug: string, toolkitSlug: string | undefined, c* extendsToolkit: 'gmail',* inputParams: z.object({ limit: z.number().default(10) }),* execute: async (input, ctx) => {+ * // Same response shape as session.execute(): { data, error, logId }* const result = await ctx.execute('GMAIL_SEARCH', { query: 'is:important' });* return { emails: result.data };* },@@ -123,7 +130,9 @@ export function createCustomTool<T extends z.ZodType>(// Validate slug separatelyconst slugResult = CustomToolSlugSchema.safeParse(slug);if (!slugResult.success) {- throw new ValidationError(`createCustomTool: ${slugResult.error.issues[0].message}`, { cause: slugResult.error });+ throw new ValidationError(`createCustomTool: ${slugResult.error.issues[0].message}`, {+ cause: slugResult.error,+ });}// Validate string/scalar fields via Zod schema@@ -137,7 +146,7 @@ export function createCustomTool<T extends z.ZodType>(if ((options.inputParams as { _def?: { typeName?: string } })?._def?.typeName !== 'ZodObject') {throw new ValidationError('createCustomTool: inputParams must be a z.object() schema. ' +- 'Tool input parameters are always an object with named properties.'+ 'Tool input parameters are always an object with named properties.');}if (typeof options.execute !== 'function') {@@ -211,7 +220,9 @@ export function createCustomToolkit(// Validate slugconst slugResult = CustomToolSlugSchema.safeParse(slug);if (!slugResult.success) {- throw new ValidationError(`createCustomToolkit: ${slugResult.error.issues[0].message}`, { cause: slugResult.error });+ throw new ValidationError(`createCustomToolkit: ${slugResult.error.issues[0].message}`, {+ cause: slugResult.error,+ });}// Validate name/description@@ -228,7 +239,7 @@ export function createCustomToolkit(if (tool.extendsToolkit) {throw new ValidationError(`createCustomToolkit: tool "${tool.slug}" has extendsToolkit set. ` +- `Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`+ `Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`);}// Early length validation — we know both toolkit slug and tool slug@@ -278,20 +289,22 @@ export function buildCustomToolsMap(if (finalSlug.length > MAX_SLUG_LENGTH) {throw new ValidationError(`Custom tool slug "${handle.slug}" produces final slug "${finalSlug}" ` +- `which exceeds ${MAX_SLUG_LENGTH} characters.`+ `which exceeds ${MAX_SLUG_LENGTH} characters.`);}// Check cross-group collisions on final slugif (byFinalSlug.has(finalSlug)) {- throw new ValidationError(`Custom tool slug collision: "${finalSlug}" is already registered.`);+ throw new ValidationError(+ `Custom tool slug collision: "${finalSlug}" is already registered.`+ );}// Check cross-group collisions on original slugif (byOriginalSlug.has(originalSlug)) {throw new ValidationError(`Custom tool slug collision: original slug "${handle.slug}" maps to multiple final slugs. ` +- `"${byOriginalSlug.get(originalSlug)!.finalSlug}" and "${finalSlug}" both resolve from "${originalSlug}".`+ `"${byOriginalSlug.get(originalSlug)!.finalSlug}" and "${finalSlug}" both resolve from "${originalSlug}".`);}@@ -302,11 +315,7 @@ export function buildCustomToolsMap(// Process standalone toolsfor (const handle of tools) {- addEntry(- handle,- buildFinalSlug(handle.slug, handle.extendsToolkit),- handle.extendsToolkit- );+ addEntry(handle, buildFinalSlug(handle.slug, handle.extendsToolkit), handle.extendsToolkit);}// Process toolkit tools@@ -330,9 +339,7 @@ export function buildCustomToolsMap(* @param tools - The custom tools to serialize* @returns Array of CustomToolDefinition for the API payload*/-export function serializeCustomTools(- tools: CustomTool[]-): CustomToolDefinition[] {+export function serializeCustomTools(tools: CustomTool[]): CustomToolDefinition[] {return tools.map(handle => ({slug: handle.slug,name: handle.name,@@ -350,9 +357,7 @@ export function serializeCustomTools(* @param toolkits - The custom toolkits to serialize* @returns Array of CustomToolkitDefinition for the API payload*/-export function serializeCustomToolkits(- toolkits: CustomToolkit[]-): CustomToolkitDefinition[] {+export function serializeCustomToolkits(toolkits: CustomToolkit[]): CustomToolkitDefinition[] {return toolkits.map(tk => ({slug: tk.slug,name: tk.name,@@ -388,7 +393,10 @@ export function buildCustomToolsMapFromResponse(// Build a lookup from original slug → custom tool handle (for matching response items)const handlesByOriginalSlug = new Map<string, { handle: CustomTool; toolkit?: string }>();for (const handle of tools) {- handlesByOriginalSlug.set(handle.slug.toUpperCase(), { handle, toolkit: handle.extendsToolkit });+ handlesByOriginalSlug.set(handle.slug.toUpperCase(), {+ handle,+ toolkit: handle.extendsToolkit,+ });}if (toolkits) {for (const tk of toolkits) {diff --git a/ts/packages/core/src/models/SessionContext.ts b/ts/packages/core/src/models/SessionContext.tsindex a7e8233b7..cf21cca7f 100644--- a/ts/packages/core/src/models/SessionContext.ts+++ b/ts/packages/core/src/models/SessionContext.ts@@ -3,12 +3,19 @@*/import { Composio as ComposioClient } from '@composio/client';import type { SessionContext, CustomToolsMap } from '../types/customTool.types';-import type { ToolExecuteResponse } from '../types/tool.types';-import type { SessionProxyExecuteParams, ToolRouterSessionProxyExecuteResponse } from '../types/toolRouter.types';-import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';+import type {+ SessionProxyExecuteParams,+ ToolRouterSessionExecuteResponse,+ ToolRouterSessionProxyExecuteResponse,+} from '../types/toolRouter.types';+import {+ SessionProxyExecuteParamsSchema,+ ToolRouterSessionExecuteResponseSchema,+} from '../types/toolRouter.types';import { ValidationError } from '../errors';import { transformProxyParams } from './proxyParamsTransform';import { findCustomTool, executeCustomTool } from './customToolExecution';+import { transformExecuteResponse } from '../utils/transformers/toolRouterResponseTransform';/*** Concrete implementation of SessionContext.@@ -35,37 +42,39 @@ export class SessionContextImpl implements SessionContext {* Execute any tool from within a custom tool.* Routes to sibling local tools in-process when available,* otherwise delegates to the backend API.+ *+ * Returns the same response shape as session.execute().*/async execute(toolSlug: string,arguments_: Record<string, unknown>- ): Promise<ToolExecuteResponse> {+ ): Promise<ToolRouterSessionExecuteResponse> {// Try local tool first (sibling routing)const entry = findCustomTool(this.customToolsMap, toolSlug);if (entry) {- return executeCustomTool(entry, arguments_, this);+ const result = await executeCustomTool(entry, arguments_, this);+ return ToolRouterSessionExecuteResponseSchema.parse({+ data: result.data,+ error: result.error,+ logId: '',+ });}// Fall back to remote execution- const response = await this.client.toolRouter.session.execute(- this.sessionId,- {- tool_slug: toolSlug,- arguments: arguments_,- }- );- return {- data: response.data,- error: response.error,- successful: !response.error,- };+ const response = await this.client.toolRouter.session.execute(this.sessionId, {+ tool_slug: toolSlug,+ arguments: arguments_,+ });+ return ToolRouterSessionExecuteResponseSchema.parse(transformExecuteResponse(response));}/*** Proxy API calls through Composio's auth layer.* The backend resolves the connected account from the toolkit within the session.*/- async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse> {+ async proxyExecute(+ params: SessionProxyExecuteParams+ ): Promise<ToolRouterSessionProxyExecuteResponse> {const validated = SessionProxyExecuteParamsSchema.safeParse(params);if (!validated.success) {throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });@@ -81,14 +90,16 @@ export class SessionContextImpl implements SessionContext {status: response.status,data: response.data,headers: response.headers,- ...(response.binary_data ? {- binaryData: {- contentType: response.binary_data.content_type,- size: response.binary_data.size,- url: response.binary_data.url,- expiresAt: response.binary_data.expires_at,- },- } : {}),+ ...(response.binary_data+ ? {+ binaryData: {+ contentType: response.binary_data.content_type,+ size: response.binary_data.size,+ url: response.binary_data.url,+ expiresAt: response.binary_data.expires_at,+ },+ }+ : {}),};}}diff --git a/ts/packages/core/src/types/customTool.types.ts b/ts/packages/core/src/types/customTool.types.tsindex 5a944e6cc..e077af92c 100644--- a/ts/packages/core/src/types/customTool.types.ts+++ b/ts/packages/core/src/types/customTool.types.ts@@ -1,6 +1,10 @@import { z } from 'zod/v3';-import { Tool, ToolProxyParams, ToolExecuteResponse as SdkToolExecuteResponse } from './tool.types';-import type { SessionProxyExecuteParams, ToolRouterSessionProxyExecuteResponse } from './toolRouter.types';+import { Tool, ToolProxyParams } from './tool.types';+import type {+ SessionProxyExecuteParams,+ ToolRouterSessionExecuteResponse,+ ToolRouterSessionProxyExecuteResponse,+} from './toolRouter.types';import { ToolExecuteResponse } from '@composio/client/resources/tools';import { ConnectionData } from './connectedAccountAuthStates.types';import type {@@ -74,11 +78,11 @@ export interface ExecuteMetadata {export interface SessionContext {/** The user ID for this session */readonly userId: string;- /** Execute any Composio native tool from within a custom tool */+ /** Execute any Composio native tool from within a custom tool. Returns the same shape as session.execute(). */execute(toolSlug: string,arguments_: Record<string, unknown>- ): Promise<SdkToolExecuteResponse>;+ ): Promise<ToolRouterSessionExecuteResponse>;/** Proxy API calls through Composio's auth layer (resolved from session toolkit). */proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse>;}@@ -109,8 +113,7 @@ export const CustomToolSlugSchema = z'slug must only contain alphanumeric characters, underscores, and hyphens').refine(s => !s.toUpperCase().startsWith('LOCAL_'), {- message:- 'slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',+ message: 'slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',}).refine(s => !s.toUpperCase().startsWith('COMPOSIO_'), {message:diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.tsindex 1372a661d..498c80c92 100644--- a/ts/packages/core/test/models/customTool.test.ts+++ b/ts/packages/core/test/models/customTool.test.ts@@ -44,7 +44,10 @@ describe('createCustomTool', () => {});it('should include extendsToolkit when provided', () => {- const tool = createCustomTool('GET_AD_ACCOUNTS', { ...baseOptions, extendsToolkit: 'meta_ads' });+ const tool = createCustomTool('GET_AD_ACCOUNTS', {+ ...baseOptions,+ extendsToolkit: 'meta_ads',+ });expect(tool.extendsToolkit).toBe('meta_ads');});@@ -137,7 +140,9 @@ describe('createCustomTool', () => {describe('other validation', () => {it('should throw if name is missing', () => {- expect(() => createCustomTool('SLUG', { ...baseOptions, name: '' })).toThrow('name is required');+ expect(() => createCustomTool('SLUG', { ...baseOptions, name: '' })).toThrow(+ 'name is required'+ );});it('should throw if description is missing', () => {@@ -251,9 +256,9 @@ describe('createCustomToolkit', () => {});it('should throw if tools array is empty', () => {- expect(() =>- createCustomToolkit('TK', { name: 'X', description: 'X', tools: [] })- ).toThrow('at least one tool is required');+ expect(() => createCustomToolkit('TK', { name: 'X', description: 'X', tools: [] })).toThrow(+ 'at least one tool is required'+ );});it('should reject tools with extendsToolkit set', () => {@@ -349,9 +354,7 @@ describe('buildCustomToolsMap', () => {describe('collision detection', () => {it('should throw on duplicate standalone slugs', () => {- expect(() => buildCustomToolsMap([makeTool('DUPE'), makeTool('DUPE')])).toThrow(- 'collision'- );+ expect(() => buildCustomToolsMap([makeTool('DUPE'), makeTool('DUPE')])).toThrow('collision');});it('should throw on cross-group collision (standalone vs toolkit same original slug)', () => {@@ -371,26 +374,40 @@ describe('buildCustomToolsMap', () => {describe('length validation', () => {it('should throw early in createCustomTool when slug is too long (standalone)', () => {const longSlug = 'A'.repeat(56); // LOCAL_ + 56 = 62 > 60- expect(() => createCustomTool(longSlug, {- name: 'Long', description: 'Too long', inputParams: z.object({}), execute: vi.fn().mockResolvedValue({}),- })).toThrow('too long');+ expect(() =>+ createCustomTool(longSlug, {+ name: 'Long',+ description: 'Too long',+ inputParams: z.object({}),+ execute: vi.fn().mockResolvedValue({}),+ })+ ).toThrow('too long');});it('should throw early in createCustomTool when slug is too long (extension)', () => {// LOCAL_GMAIL_ = 12 chars, so slug > 48 chars overflowsconst longSlug = 'A'.repeat(49);- expect(() => createCustomTool(longSlug, {- name: 'Long', description: 'Too long', extendsToolkit: 'gmail',- inputParams: z.object({}), execute: vi.fn().mockResolvedValue({}),- })).toThrow('too long');+ expect(() =>+ createCustomTool(longSlug, {+ name: 'Long',+ description: 'Too long',+ extendsToolkit: 'gmail',+ inputParams: z.object({}),+ execute: vi.fn().mockResolvedValue({}),+ })+ ).toThrow('too long');});it('should throw early in createCustomToolkit when tool slug is too long', () => {const longSlug = 'A'.repeat(50); // LOCAL_DEV_TOOLS_ + 50 = 66 > 60const tool = makeTool(longSlug);- expect(() => createCustomToolkit('DEV_TOOLS', {- name: 'Dev Tools', description: 'Utilities', tools: [tool],- })).toThrow('too long');+ expect(() =>+ createCustomToolkit('DEV_TOOLS', {+ name: 'Dev Tools',+ description: 'Utilities',+ tools: [tool],+ })+ ).toThrow('too long');});it('should still validate in buildCustomToolsMap as safety net', () => {@@ -549,11 +566,11 @@ describe('SessionContextImpl', () => {expect(result).toEqual({data: { result: 'ok' },error: null,- successful: true,+ logId: 'log_1',});});- it('should set successful=false when execute() returns an error', async () => {+ it('should preserve logId and error when execute() returns an error', async () => {mockClient.toolRouter.session.execute.mockResolvedValue({data: {},error: 'something went wrong',@@ -563,7 +580,7 @@ describe('SessionContextImpl', () => {const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');const result = await ctx.execute('BAD_TOOL', {});- expect(result.successful).toBe(false);+ expect(result.logId).toBe('log_2');expect(result.error).toBe('something went wrong');});@@ -581,15 +598,12 @@ describe('SessionContextImpl', () => {parameters: [{ in: 'header' as const, name: 'X-Custom', value: 'val' }],});- expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith(- 'sess_1',- {- toolkit_slug: 'github',- endpoint: 'https://api.github.com/user',- method: 'GET',- parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],- }- );+ expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith('sess_1', {+ toolkit_slug: 'github',+ endpoint: 'https://api.github.com/user',+ method: 'GET',+ parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],+ });expect(result).toEqual({status: 200,data: { proxy_result: true },@@ -619,7 +633,7 @@ describe('SessionContextImpl', () => {const result = await ctx.execute('SIBLING_TOOL', { key: 'val' });expect(siblingExecute).toHaveBeenCalledWith({ key: 'val' }, ctx);- expect(result).toEqual({ data: { local: true }, error: null, successful: true });+ expect(result).toEqual({ data: { local: true }, error: null, logId: '' });// Should NOT call remoteexpect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();});@@ -646,7 +660,7 @@ describe('SessionContextImpl', () => {tool_slug: 'REMOTE_TOOL',arguments: { key: 'val' },});- expect(result).toEqual({ data: { remote: true }, error: null, successful: true });+ expect(result).toEqual({ data: { remote: true }, error: null, logId: 'log_3' });});it('should delegate to remote when no customToolsMap is provided', async () => {@@ -660,7 +674,7 @@ describe('SessionContextImpl', () => {const result = await ctx.execute('ANY_TOOL', {});expect(mockClient.toolRouter.session.execute).toHaveBeenCalled();- expect(result.successful).toBe(true);+ expect(result.logId).toBe('log_4');});});});diff --git a/ts/packages/core/test/models/customToolRouting.test.ts b/ts/packages/core/test/models/customToolRouting.test.tsindex f057185ec..c35248f64 100644--- a/ts/packages/core/test/models/customToolRouting.test.ts+++ b/ts/packages/core/test/models/customToolRouting.test.ts@@ -46,6 +46,11 @@ const createMockClient = () => ({toolkits: vi.fn(),executeMeta: vi.fn(),search: vi.fn(),+ proxyExecute: vi.fn().mockResolvedValue({+ status: 200,+ data: { ok: true },+ headers: { 'x-test': '1' },+ }),execute: vi.fn().mockResolvedValue({data: { remote_result: true },error: null,@@ -276,6 +281,31 @@ describe('ToolRouterSession execution routing', () => {});});+ describe('session.proxyExecute()', () => {+ it('should expose the same proxy response shape used by SessionContext', async () => {+ const session = createSession(mockClient, [customToolHandle]);++ const result = await session.proxyExecute({+ toolkit: 'github',+ endpoint: 'https://api.github.com/user',+ method: 'GET',+ parameters: [{ in: 'header', name: 'X-Test', value: '1' }],+ });++ expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith('sess_123', {+ toolkit_slug: 'github',+ endpoint: 'https://api.github.com/user',+ method: 'GET',+ parameters: [{ name: 'X-Test', type: 'header', value: '1' }],+ });+ expect(result).toEqual({+ status: 200,+ data: { ok: true },+ headers: { 'x-test': '1' },+ });+ });+ });+describe('session.execute() — SessionContext injection', () => {it('should inject SessionContext with correct userId', async () => {const session = createSession(mockClient, [sessionToolHandle]);@@ -380,10 +410,7 @@ describe('ToolRouterSession execution routing', () => {const session = createSession(mockClient, [toolWithDefaults]);const result = await session.execute('DEFAULTS_TOOL', {});- expect(defaultExecute).toHaveBeenCalledWith(- { category: 'all' },- expect.anything()- );+ expect(defaultExecute).toHaveBeenCalledWith({ category: 'all' }, expect.anything());expect(result.data).toEqual({ category: 'all' });});@@ -429,9 +456,7 @@ describe('ToolRouterSession execution routing', () => {const executeFn = (provider as any)._capturedExecuteFn;const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {- tools: [- { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'test' } },- ],+ tools: [{ tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'test' } }],sync_response_to_workbench: false,});@@ -451,9 +476,7 @@ describe('ToolRouterSession execution routing', () => {const executeFn = (provider as any)._capturedExecuteFn;const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {- tools: [- { tool_slug: 'GET_USER_CONTEXT', arguments: { category: 'no-prefix' } },- ],+ tools: [{ tool_slug: 'GET_USER_CONTEXT', arguments: { category: 'no-prefix' } }],sync_response_to_workbench: false,});@@ -473,9 +496,7 @@ describe('ToolRouterSession execution routing', () => {const executeFn = (provider as any)._capturedExecuteFn;const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {- tools: [- { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: '[email protected]' } },- ],+ tools: [{ tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: '[email protected]' } }],sync_response_to_workbench: false,});@@ -522,15 +543,12 @@ describe('ToolRouterSession execution routing', () => {const session = createSessionWithProvider(client, provider, customTools);await session.tools();const executeFn = (provider as any)._capturedExecuteFn;- const toolsInstance = (Tools as any).mock.results[- (Tools as any).mock.results.length - 1- ].value;+ const toolsInstance = (Tools as any).mock.results[(Tools as any).mock.results.length - 1]+ .value;return { executeFn, toolsInstance, provider, session };};- const backendResponse = (- results: Array<{ tool_slug: string; data: any; error?: string }>,- ) => {+ const backendResponse = (results: Array<{ tool_slug: string; data: any; error?: string }>) => {const items = results.map((r, i) => ({response: {successful: !r.error,@@ -583,7 +601,10 @@ describe('ToolRouterSession execution routing', () => {});it('should handle multiple local tools in same batch', async () => {- const { executeFn } = await setupMultiExecute(mockClient, [customToolHandle, sessionToolHandle]);+ const { executeFn } = await setupMultiExecute(mockClient, [+ customToolHandle,+ sessionToolHandle,+ ]);const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {tools: [@@ -609,10 +630,10 @@ describe('ToolRouterSession execution routing', () => {});it('should handle mixed batch with multiple locals + multiple remotes', async () => {- const { executeFn, toolsInstance } = await setupMultiExecute(- mockClient,- [customToolHandle, sessionToolHandle]- );+ const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [+ customToolHandle,+ sessionToolHandle,+ ]);toolsInstance.executeMetaTool.mockResolvedValueOnce(backendResponse([@@ -655,18 +676,24 @@ describe('ToolRouterSession execution routing', () => {name: 'Throws in batch',description: 'Throws',inputParams: z.object({}),- execute: async () => { throw new Error('batch-boom'); },+ execute: async () => {+ throw new Error('batch-boom');+ },});- const { executeFn, toolsInstance } = await setupMultiExecute(- mockClient,- [customToolHandle, throwingHandle]- );+ const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [+ customToolHandle,+ throwingHandle,+ ]);toolsInstance.executeMetaTool.mockResolvedValueOnce(backendResponse([{ tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } },- { tool_slug: 'SLACK_POST_MESSAGE', data: { message: 'auth failed' }, error: 'auth failed' },+ {+ tool_slug: 'SLACK_POST_MESSAGE',+ data: { message: 'auth failed' },+ error: 'auth failed',+ },]));@@ -719,12 +746,14 @@ describe('ToolRouterSession execution routing', () => {it('should handle non-object items in tools array gracefully', async () => {const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);- toolsInstance.executeMetaTool.mockResolvedValueOnce(- backendResponse([])- );+ toolsInstance.executeMetaTool.mockResolvedValueOnce(backendResponse([]));const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {- tools: ['not-an-object', null, { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } }],+ tools: [+ 'not-an-object',+ null,+ { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } },+ ],sync_response_to_workbench: false,});@@ -756,9 +785,8 @@ describe('ToolRouterSession execution routing', () => {const session = createSessionWithProvider(mockClient, provider, [slowLocalHandle]);await session.tools();const executeFn = (provider as any)._capturedExecuteFn;- const toolsInstance = (Tools as any).mock.results[- (Tools as any).mock.results.length - 1- ].value;+ const toolsInstance = (Tools as any).mock.results[(Tools as any).mock.results.length - 1]+ .value;toolsInstance.executeMetaTool.mockImplementation(async () => {callOrder.push('remote-start');@@ -818,8 +846,16 @@ describe('ToolRouterSession execution routing', () => {latestToolsInstance.executeMetaTool.mockResolvedValueOnce({data: {results: [- { response: { successful: true, data: { message_id: 'msg_1' } }, tool_slug: 'GMAIL_SEND_EMAIL', index: 0 },- { response: { successful: true, data: { ts: '123456' } }, tool_slug: 'SLACK_POST_MESSAGE', index: 1 },+ {+ response: { successful: true, data: { message_id: 'msg_1' } },+ tool_slug: 'GMAIL_SEND_EMAIL',+ index: 0,+ },+ {+ response: { successful: true, data: { ts: '123456' } },+ tool_slug: 'SLACK_POST_MESSAGE',+ index: 1,+ },],total_count: 2,success_count: 2,@@ -872,5 +908,4 @@ describe('ToolRouterSession execution routing', () => {);});});-});