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
refactor: use official @composio/client types, proxyExecute via client method
Dhawal Upadhyay7b58c4a8d6f8
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8794e0829..d9687fe16 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -25,8 +25,8 @@ catalogs:specifier: ^4.20250917.0version: 4.20260218.0'@composio/client':- specifier: 0.1.0-alpha.61- version: 0.1.0-alpha.61+ specifier: 0.1.0-alpha.62+ version: 0.1.0-alpha.62'@effect/cli':specifier: ^0.73.2version: 0.73.2@@ -703,16 +703,16 @@ importers:version: link:../../packages/providers/llamaindex'@llamaindex/openai':specifier: ^0.4.20- version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])+ version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])'@llamaindex/workflow':specifier: ^1.1.24- version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])dotenv:specifier: ^16.4.1version: 16.6.1llamaindex:specifier: ^0.12.0- version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])+ version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])devDependencies:'@types/bun':specifier: ^1.2.9@@ -863,6 +863,9 @@ importers:'@anthropic-ai/claude-agent-sdk':specifier: ^0.1.55version: 0.1.77([email protected])+ '@composio/claude-agent-sdk':+ specifier: workspace:*+ version: link:../../packages/providers/claude-agent-sdk'@composio/core':specifier: workspace:*version: link:../../packages/core@@ -1048,7 +1051,7 @@ importers:version: 1.0.1'@composio/client':specifier: 'catalog:'- version: 0.1.0-alpha.61+ version: 0.1.0-alpha.62'@composio/core':specifier: workspace:*version: link:../core@@ -1145,7 +1148,7 @@ importers:dependencies:'@composio/client':specifier: 'catalog:'- version: 0.1.0-alpha.61+ version: 0.1.0-alpha.62'@composio/json-schema-to-zod':specifier: workspace:*version: link:../json-schema-to-zod@@ -1318,7 +1321,7 @@ importers:dependencies:llamaindex:specifier: ^0.12.0+ version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])devDependencies:'@composio/core':specifier: workspace:*@@ -1792,8 +1795,8 @@ packages:resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}engines: {node: '>=0.1.90'}- '@composio/[email protected]':- resolution: {integrity: sha512-VSU20mTtMe0TIPHkBBRdCU4IYSy3886U9O69PURU8+ItLXCD2MjIN0S8VTDL8wpA4zFXamUFnvtwQyow11O2KA==}+ '@composio/[email protected]':+ resolution: {integrity: sha512-MUBawDp6Uw85m3T0ZtPUSTe9v4SPa0K/Ey3ADZQ/k1NkWsin0oGWhrB/i9hMzndRobijHmBw6xgnFCwjU1B9MQ==}'@cspotcode/[email protected]':resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}@@ -6862,7 +6865,7 @@ snapshots:'@colors/[email protected]':optional: true- '@composio/[email protected]': {}+ '@composio/[email protected]': {}'@cspotcode/[email protected]':dependencies:@@ -7557,43 +7560,26 @@ snapshots:tree-sitter: 0.22.4web-tree-sitter: 0.24.7- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])':+ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])':dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30- openai: 5.23.2([email protected])([email protected])+ openai: 5.23.2([email protected])([email protected])transitivePeerDependencies:- ws- zod- '@llamaindex/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':+ '@llamaindex/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':optionalDependencies:- '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])+ '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])hono: 4.11.9- zod: 3.25.76-- '@llamaindex/[email protected]([email protected])':- optionalDependencies:zod: 4.3.6- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':- dependencies:- '@llamaindex/core': 0.6.22- '@llamaindex/env': 0.1.30- '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])- transitivePeerDependencies:- - '@modelcontextprotocol/sdk'- - hono- - next- - p-retry- - rxjs- - zod-- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])':+ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30- '@llamaindex/workflow-core': 1.3.3([email protected])+ '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])transitivePeerDependencies:- '@modelcontextprotocol/sdk'- hono@@ -9923,34 +9909,12 @@ snapshots:rfdc: 1.4.1wrap-ansi: 9.0.2- [email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected]):- dependencies:- '@llamaindex/core': 0.6.22- '@llamaindex/env': 0.1.30- '@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])- '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])- '@types/lodash': 4.17.23- '@types/node': 24.10.13- lodash: 4.17.23- magic-bytes.js: 1.13.0- transitivePeerDependencies:- - '@huggingface/transformers'- - '@modelcontextprotocol/sdk'- - gpt-tokenizer- - hono- - next- - p-retry- - rxjs- - tree-sitter- - web-tree-sitter- - zod-+ [email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected]):dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30'@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])- '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])'@types/lodash': 4.17.23'@types/node': 24.10.13lodash: 4.17.23@@ -10230,11 +10194,6 @@ snapshots:is-inside-container: 1.0.0wsl-utils: 0.1.0- optionalDependencies:- ws: 8.19.0- zod: 3.25.76-optionalDependencies:ws: 8.19.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex fc1d8cad5..e8919e7e0 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -20,7 +20,7 @@ catalog:'@clack/prompts': '^1.0.1''@cloudflare/vitest-pool-workers': ^0.9.2'@cloudflare/workers-types': ^4.20250917.0- '@composio/client': 0.1.0-alpha.61+ '@composio/client': 0.1.0-alpha.62'@effect/cli': ^0.73.2'@effect/eslint-plugin': ^0.3.2'@effect/language-service': ^0.74.0diff --git a/ts/examples/tool-router/package.json b/ts/examples/tool-router/package.jsonindex 82109e5af..4edf62ac1 100644--- a/ts/examples/tool-router/package.json+++ b/ts/examples/tool-router/package.json@@ -21,6 +21,7 @@"@ai-sdk/mcp": "^0.0.11","@ai-sdk/openai": "^3.0.11","@anthropic-ai/claude-agent-sdk": "^0.1.55",+ "@composio/claude-agent-sdk": "workspace:*","@composio/core": "workspace:*","@composio/openai-agents": "workspace:*","@composio/vercel": "workspace:*",diff --git a/ts/examples/tool-router/src/custom-tools.ts b/ts/examples/tool-router/src/custom-tools.tsnew file mode 100644index 000000000..05975a661--- /dev/null+++ b/ts/examples/tool-router/src/custom-tools.ts@@ -0,0 +1,115 @@+/**+ * Custom Tools — local tools + proxy execute with OpenAI Agents+ *+ * Shows how to create custom tools that run in-process alongside+ * remote Composio tools. Includes a tool that calls the Gmail API+ * directly via ctx.proxyExecute().+ *+ * Usage:+ * COMPOSIO_API_KEY=... OPENAI_API_KEY=... bun src/custom-tools.ts+ */+import "dotenv/config";+import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";+import { OpenAIAgentsProvider } from "@composio/openai-agents";+import { Agent, run } from "@openai/agents";+import { z } from "zod/v3";++// ── Custom tools ────────────────────────────────────────────────++/** Standalone tool (no auth needed) */+const getUser = experimental_createTool("GET_USER", {+ name: "Get user",+ description: "Look up an internal user by ID",+ inputParams: z.object({+ user_id: z.string().describe("User ID (e.g. user-1)"),+ }),+ execute: async ({ user_id }) => {+ const users: Record<string, Record<string, string>> = {+ "user-1": { name: "Alice Johnson", email: "[email protected]", role: "admin" },+ "user-2": { name: "Bob Smith", email: "[email protected]", role: "developer" },+ };+ const user = users[user_id];+ if (!user) throw new Error(`User "${user_id}" not found`);+ return user;+ },+});++/** Extension tool — inherits Gmail auth, calls the real API via proxy */+const createDraft = experimental_createTool("CREATE_DRAFT", {+ name: "Create Gmail draft",+ description: "Create a real Gmail draft via the Gmail API. Appears in the user's drafts folder.",+ extendsToolkit: "gmail",+ inputParams: z.object({+ to: z.string().describe("Recipient email address"),+ subject: z.string().describe("Email subject"),+ body: z.string().describe("Email body (plain text)"),+ }),+ execute: async (input, ctx) => {+ const raw = Buffer.from(+ `To: ${input.to}\r\nSubject: ${input.subject}\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n${input.body}`+ )+ .toString("base64")+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=+$/, "");++ const res = await ctx.proxyExecute({+ toolkit: "gmail",+ endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/drafts",+ method: "POST",+ body: { message: { raw } },+ });++ if (res.status !== 200) throw new Error(`Gmail API error ${res.status}`);+ const data = res.data as { id: string; message: { id: string } };+ return { draft_id: data.id, message_id: data.message.id, to: input.to, subject: input.subject };+ },+});++/** Custom toolkit — groups related tools under one namespace */+const roleManager = experimental_createToolkit("ROLE_MANAGER", {+ name: "Role Manager",+ description: "Manage user roles",+ tools: [+ experimental_createTool("SET_ROLE", {+ name: "Set role",+ description: "Set a user's role",+ inputParams: z.object({+ user_id: z.string().describe("User ID"),+ role: z.enum(["admin", "developer", "viewer"]).describe("New role"),+ }),+ execute: async ({ user_id, role }) => ({ user_id, role, updated: true }),+ }),+ ],+});++// ── Agent ────────────────────────────────────────────────────────++const composio = new Composio({+ provider: new OpenAIAgentsProvider(),+});++const session = await composio.create("default", {+ toolkits: ["gmail"],+ experimental: {+ customTools: [getUser, createDraft],+ customToolkits: [roleManager],+ },+});++const tools = await session.tools();++const agent = new Agent({+ name: "Assistant",+ instructions:+ "You are a helpful assistant. Use Composio tools to execute tasks. " ++ "In MULTI_EXECUTE, always pass arguments inside the arguments field.",+ model: "gpt-4.1",+ tools,+});++const prompt = process.argv[2] ?? "Get user-1's info and draft an email to them saying hello";++console.log(`> ${prompt}\n`);+const result = await run(agent, prompt);+console.log(result.finalOutput);diff --git a/ts/packages/core/src/lib/toolRouterParams.ts b/ts/packages/core/src/lib/toolRouterParams.tsindex c9c6fd0cc..926eafd21 100644--- a/ts/packages/core/src/lib/toolRouterParams.ts+++ b/ts/packages/core/src/lib/toolRouterParams.ts@@ -1,4 +1,4 @@-import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';+import { SessionCreateParams } from '@composio/client/resources/tool-router/session/session.mjs';import {ToolRouterConfigTags,ToolRouterConfigTools,diff --git a/ts/packages/core/src/models/CustomTool.ts b/ts/packages/core/src/models/CustomTool.tsindex b134fd391..618f69619 100644--- a/ts/packages/core/src/models/CustomTool.ts+++ b/ts/packages/core/src/models/CustomTool.ts@@ -36,6 +36,7 @@ import {type CustomToolkitDefinition,type InputParamsSchema,} from '../types/customTool.types';+import type { SessionCreateResponse } from '@composio/client/resources/tool-router/session/session.mjs';import { ValidationError } from '../errors';/** Prefix applied by the backend to local tool slugs for disambiguation. */@@ -355,3 +356,71 @@ export function serializeCustomToolkits(})),}));}++/**+ * Build a CustomToolsMap using the slug/original_slug mapping from the session create response.+ * This uses the backend's authoritative prefixed slugs instead of computing them client-side.+ *+ * @internal+ * @param tools - The original custom tools passed to session creation+ * @param toolkits - The original custom toolkits passed to session creation+ * @param experimental - The experimental section from the session create response+ * @returns Maps for O(1) lookup by both final and original slug+ */+export function buildCustomToolsMapFromResponse(+ tools: CustomTool[],+ toolkits: CustomToolkit[] | undefined,+ experimental: SessionCreateResponse['experimental'] | undefined+): CustomToolsMap {+ const byFinalSlug = new Map<string, CustomToolsMapEntry>();+ const byOriginalSlug = new Map<string, CustomToolsMapEntry>();++ // 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 });+ }+ if (toolkits) {+ for (const tk of toolkits) {+ for (const handle of tk.tools) {+ handlesByOriginalSlug.set(handle.slug.toUpperCase(), { handle, toolkit: tk.slug });+ }+ }+ }++ const addEntry = (finalSlug: string, originalSlug: string, toolkit?: string) => {+ const match = handlesByOriginalSlug.get(originalSlug.toUpperCase());+ if (!match) return; // Response tool not found in our handles (shouldn't happen)++ const entry: CustomToolsMapEntry = {+ handle: match.handle,+ finalSlug,+ toolkit: toolkit ?? match.toolkit,+ };+ byFinalSlug.set(finalSlug, entry);+ byOriginalSlug.set(originalSlug.toUpperCase(), entry);+ };++ // Map standalone custom tools from response+ if (experimental?.custom_tools) {+ for (const ct of experimental.custom_tools) {+ addEntry(ct.slug, ct.original_slug, ct.extends_toolkit);+ }+ }++ // Map toolkit custom tools from response+ if (experimental?.custom_toolkits) {+ for (const ctk of experimental.custom_toolkits) {+ for (const ct of ctk.tools) {+ addEntry(ct.slug, ct.original_slug, ctk.slug);+ }+ }+ }++ // Fallback: if no response mapping available, use client-side prefix computation+ if (!experimental?.custom_tools && !experimental?.custom_toolkits) {+ return buildCustomToolsMap(tools, toolkits);+ }++ return { byFinalSlug, byOriginalSlug, toolkits };+}diff --git a/ts/packages/core/src/models/SessionContext.ts b/ts/packages/core/src/models/SessionContext.tsindex 8f2553119..a7e8233b7 100644--- a/ts/packages/core/src/models/SessionContext.ts+++ b/ts/packages/core/src/models/SessionContext.ts@@ -4,7 +4,7 @@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 } from '../types/toolRouter.types';+import type { SessionProxyExecuteParams, ToolRouterSessionProxyExecuteResponse } from '../types/toolRouter.types';import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';import { ValidationError } from '../errors';import { transformProxyParams } from './proxyParamsTransform';@@ -65,24 +65,30 @@ export class SessionContextImpl implements SessionContext {* 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<ToolExecuteResponse> {+ async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse> {const validated = SessionProxyExecuteParamsSchema.safeParse(params);if (!validated.success) {throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });}- const body = transformProxyParams(validated.data);-- // TODO: Replace with client.toolRouter.session.proxyExecute() when @composio/client is updated- const response = await (this.client as unknown as { post: (path: string, opts: { body: unknown }) => Promise<{ data: Record<string, unknown>; error: string | null; log_id: string }> }).post(- `/api/v3/tool_router/session/${this.sessionId}/proxy_execute`,- { body }+ const clientParams = transformProxyParams(validated.data);+ const response = await this.client.toolRouter.session.proxyExecute(+ this.sessionId,+ clientParams);return {- data: response.data ?? {},- error: response.error,- successful: !response.error,+ 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,+ },+ } : {}),};}}diff --git a/ts/packages/core/src/models/ToolRouter.ts b/ts/packages/core/src/models/ToolRouter.tsindex bf9f036c3..68791711e 100644--- a/ts/packages/core/src/models/ToolRouter.ts+++ b/ts/packages/core/src/models/ToolRouter.ts@@ -29,7 +29,10 @@ import {ToolRouterMCPServerConfig,} from '../types/toolRouter.types';import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types';-import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';+import {+ SessionCreateParams,+ SessionCreateResponse,+} from '@composio/client/resources/tool-router/session/session.mjs';import {transformToolRouterTagsParams,transformToolRouterToolsParams,@@ -38,7 +41,7 @@ import {transformToolRouterToolkitsParams,} from '../lib/toolRouterParams';import { ToolRouterSession } from './ToolRouterSession';-import { buildCustomToolsMap, serializeCustomTools, serializeCustomToolkits } from './CustomTool';+import { buildCustomToolsMapFromResponse, serializeCustomTools, serializeCustomToolkits } from './CustomTool';import type { CustomToolsMap } from '../types/customTool.types';export class ToolRouter<@@ -101,10 +104,9 @@ export class ToolRouter<// Extract custom tools/toolkits from experimental configconst customTools = routerConfig.experimental?.customTools;const customToolkits = routerConfig.experimental?.customToolkits;- let customToolsMap: CustomToolsMap | undefined;- // Build the experimental payload for the backend- const experimentalPayload: Record<string, unknown> = {};+ // Build the typed experimental payload for the backend+ const experimentalPayload: SessionCreateParams['experimental'] = {};if (routerConfig.experimental?.assistivePrompt?.userTimezone) {experimentalPayload.assistive_prompt_config = {@@ -112,12 +114,11 @@ export class ToolRouter<};}- if (customTools?.length || customToolkits?.length) {- customToolsMap = buildCustomToolsMap(customTools ?? [], customToolkits);- experimentalPayload.custom_tools = serializeCustomTools(customTools ?? []);- if (customToolkits?.length) {- experimentalPayload.custom_toolkits = serializeCustomToolkits(customToolkits);- }+ if (customTools?.length) {+ experimentalPayload.custom_tools = serializeCustomTools(customTools);+ }+ if (customToolkits?.length) {+ experimentalPayload.custom_toolkits = serializeCustomToolkits(customToolkits);}const payload: SessionCreateParams = {@@ -136,12 +137,20 @@ export class ToolRouter<: undefined,};- const session = await this.client.toolRouter.session.create(- payload as SessionCreateParams- );+ const session = await this.client.toolRouter.session.create(payload);++ // Build custom tools map from the response's slug/original_slug mapping+ // instead of computing LOCAL_ prefix client-side+ let customToolsMap: CustomToolsMap | undefined;+ if (customTools?.length || customToolkits?.length) {+ customToolsMap = buildCustomToolsMapFromResponse(+ customTools ?? [],+ customToolkits,+ session.experimental+ );+ }- const assistivePrompt =- session.experimental?.assistive_prompt;+ const assistivePrompt = session.experimental?.assistive_prompt;return new ToolRouterSession<TToolCollection, TTool, TProvider>(this.client,diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.tsindex 527a32377..e2b9846b8 100644--- a/ts/packages/core/src/models/ToolRouterSession.ts+++ b/ts/packages/core/src/models/ToolRouterSession.ts@@ -11,6 +11,7 @@ import {ToolRouterSessionSearchResponseSchema,ToolRouterSessionExecuteResponse,ToolRouterSessionExecuteResponseSchema,+ ToolRouterSessionProxyExecuteResponse,} from '../types/toolRouter.types';import {transformSearchResponse,@@ -292,7 +293,7 @@ export class ToolRouterSession<return {data: result.data,error: result.error,- logId: 'local',+ logId: '',};}@@ -310,27 +311,33 @@ export class ToolRouterSession<* The backend resolves the connected account from the toolkit within the session.** @param params - Proxy request parameters (toolkit, endpoint, method, body, headers/query params)- * @returns The proxied API response+ * @returns The proxied API response with status, data, headers*/- async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionExecuteResponse> {+ async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse> {const validated = SessionProxyExecuteParamsSchema.safeParse(params);if (!validated.success) {throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });}- const body = transformProxyParams(validated.data);-- // TODO: Replace with client.toolRouter.session.proxyExecute() when @composio/client is updated- const response = await (this.client as unknown as { post: (path: string, opts: { body: unknown }) => Promise<{ data: Record<string, unknown>; error: string | null; log_id: string }> }).post(- `/api/v3/tool_router/session/${this.sessionId}/proxy_execute`,- { body }+ const clientParams = transformProxyParams(validated.data);+ const response = await this.client.toolRouter.session.proxyExecute(+ this.sessionId,+ clientParams);- return ToolRouterSessionExecuteResponseSchema.parse({+ return {+ status: response.status,data: response.data,- error: response.error,- logId: response.log_id,- });+ 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,+ },+ } : {}),+ };}// ── Private helpers ──────────────────────────────────────────diff --git a/ts/packages/core/src/models/proxyParamsTransform.ts b/ts/packages/core/src/models/proxyParamsTransform.tsindex 7ef89dad1..e802daea7 100644--- a/ts/packages/core/src/models/proxyParamsTransform.ts+++ b/ts/packages/core/src/models/proxyParamsTransform.ts@@ -1,24 +1,16 @@/*** @fileoverview Shared transform for converting SDK SessionProxyExecuteParams- * to the backend proxy execute request format.+ * to the official @composio/client proxy execute params.*/import type { SessionProxyExecuteParams } from '../types/toolRouter.types';--/** Backend session proxy execute request body shape. */-export interface SessionProxyExecuteRequestBody {- toolkit_slug: string;- endpoint: string;- method: string;- body?: unknown;- parameters?: Array<{ name: string; type: 'header' | 'query'; value: string }>;-}+import type { SessionProxyExecuteParams as ClientProxyExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';/**- * Transform SDK session proxy params to the backend request format.- * Converts `in` (query/header) to `type` and stringifies values.+ * Transform SDK session proxy params to the official client request format.+ * Converts SDK-facing `toolkit` → `toolkit_slug` and `parameters[].in` → `parameters[].type`.*/-export function transformProxyParams(params: SessionProxyExecuteParams): SessionProxyExecuteRequestBody {- const parameters = params.parameters?.map(p => ({+export function transformProxyParams(params: SessionProxyExecuteParams): ClientProxyExecuteParams {+ const parameters: ClientProxyExecuteParams['parameters'] = params.parameters?.map(p => ({name: p.name,type: p.in as 'header' | 'query',value: p.value.toString(),diff --git a/ts/packages/core/src/types/customTool.types.ts b/ts/packages/core/src/types/customTool.types.tsindex a56770abe..5a944e6cc 100644--- a/ts/packages/core/src/types/customTool.types.ts+++ b/ts/packages/core/src/types/customTool.types.ts@@ -1,8 +1,12 @@import { z } from 'zod/v3';import { Tool, ToolProxyParams, ToolExecuteResponse as SdkToolExecuteResponse } from './tool.types';-import type { SessionProxyExecuteParams } from './toolRouter.types';+import type { SessionProxyExecuteParams, ToolRouterSessionProxyExecuteResponse } from './toolRouter.types';import { ToolExecuteResponse } from '@composio/client/resources/tools';import { ConnectionData } from './connectedAccountAuthStates.types';+import type {+ SessionCreateParams,+ SessionCreateResponse,+} from '@composio/client/resources/tool-router/session/session.mjs';// ────────────────────────────────────────────────────────────────// Legacy custom tool types (used by composio.tools.createCustomTool)@@ -76,7 +80,7 @@ export interface SessionContext {arguments_: Record<string, unknown>): Promise<SdkToolExecuteResponse>;/** Proxy API calls through Composio's auth layer (resolved from session toolkit). */- proxyExecute(params: SessionProxyExecuteParams): Promise<SdkToolExecuteResponse>;+ proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse>;}/**@@ -165,16 +169,8 @@ export interface CustomTool {readonly execute: CustomToolExecuteFn<z.ZodType>;}-/** Serialized tool definition sent to backend for search indexing. */-export interface CustomToolDefinition {- slug: string;- name: string;- description: string;- input_schema: Record<string, unknown>;- output_schema?: Record<string, unknown>;- /** Mapped from `extendsToolkit`. Omitted for standalone tools. */- extends_toolkit?: string;-}+/** Serialized tool definition sent to backend for search indexing. Uses official client type. */+export type CustomToolDefinition = SessionCreateParams.Experimental.CustomTool;// ────────────────────────────────────────────────────────────────// Custom toolkit types@@ -206,14 +202,8 @@ export interface CustomToolkit {readonly tools: readonly CustomTool[];}-/** Serialized toolkit definition sent to backend. */-export interface CustomToolkitDefinition {- slug: string;- name: string;- description: string;- /** Nested tools — no extends_toolkit, they inherit the toolkit identity from the parent. */- tools: Omit<CustomToolDefinition, 'extends_toolkit'>[];-}+/** Serialized toolkit definition sent to backend. Uses official client type. */+export type CustomToolkitDefinition = SessionCreateParams.Experimental.CustomToolkit;// ────────────────────────────────────────────────────────────────// Internal routing types@@ -261,3 +251,13 @@ export interface RegisteredCustomToolkit {description: string;tools: RegisteredCustomTool[];}++// ────────────────────────────────────────────────────────────────+// Response types from the backend (slug + original_slug mapping)+// ────────────────────────────────────────────────────────────────++/** Custom tool as returned in the session create response (has prefixed slug + original_slug). */+export type CustomToolResponse = SessionCreateResponse.Experimental.CustomTool;++/** Custom toolkit as returned in the session create response (has prefixed slugs + original_slugs). */+export type CustomToolkitResponse = SessionCreateResponse.Experimental.CustomToolkit;diff --git a/ts/packages/core/src/types/toolRouter.types.ts b/ts/packages/core/src/types/toolRouter.types.tsindex 9ca9de5a3..3c875112a 100644--- a/ts/packages/core/src/types/toolRouter.types.ts+++ b/ts/packages/core/src/types/toolRouter.types.ts@@ -405,6 +405,24 @@ export type ToolRouterSessionExecuteResponse = z.infer<typeof ToolRouterSessionExecuteResponseSchema>;+// --- Session proxy execute response (matches ToolProxyResponse from client) ---++export interface ToolRouterSessionProxyExecuteResponse {+ /** The HTTP status code returned from the proxied API */+ status: number;+ /** The response data from the proxied API */+ data?: unknown;+ /** HTTP headers from the proxied API */+ headers?: Record<string, string>;+ /** Binary response data (present when response is a file) */+ binaryData?: {+ contentType: string;+ size: number;+ url: string;+ expiresAt?: string;+ };+}+/*** Experimental features on a tool router session.* Contains features that may be modified or removed in future versions.@@ -455,7 +473,7 @@ export type SessionProxyExecuteParams = z.infer<typeof SessionProxyExecuteParamsexport type ToolRouterSessionProxyExecuteFn = (params: SessionProxyExecuteParams-) => Promise<ToolRouterSessionExecuteResponse>;+) => Promise<ToolRouterSessionProxyExecuteResponse>;/** Session type returned by ToolRouter.create() and ToolRouter.use() */export interface Session<diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.tsindex 87043776f..1372a661d 100644--- a/ts/packages/core/test/models/customTool.test.ts+++ b/ts/packages/core/test/models/customTool.test.ts@@ -518,6 +518,7 @@ describe('SessionContextImpl', () => {toolRouter: {session: {execute: vi.fn(),+ proxyExecute: vi.fn(),},},};@@ -566,14 +567,12 @@ describe('SessionContextImpl', () => {expect(result.error).toBe('something went wrong');});- it('should call session proxy_execute endpoint via proxyExecute()', async () => {- const mockPost = vi.fn().mockResolvedValue({+ it('should call client.toolRouter.session.proxyExecute() via proxyExecute()', async () => {+ mockClient.toolRouter.session.proxyExecute.mockResolvedValue({+ status: 200,data: { proxy_result: true },- error: null,- log_id: 'log_proxy',});- const clientWithPost = { ...mockClient, post: mockPost };- const ctx = new SessionContextImpl(clientWithPost as any, 'user_1', 'sess_1');+ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');const result = await ctx.proxyExecute({toolkit: 'github',@@ -582,21 +581,18 @@ describe('SessionContextImpl', () => {parameters: [{ in: 'header' as const, name: 'X-Custom', value: 'val' }],});- expect(mockPost).toHaveBeenCalledWith(- '/api/v3/tool_router/session/sess_1/proxy_execute',+ expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith(+ 'sess_1',{- body: {- toolkit_slug: 'github',- endpoint: 'https://api.github.com/user',- method: 'GET',- parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],- },+ 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 },- error: null,- successful: true,});});diff --git a/ts/packages/core/test/models/customToolRouting.test.ts b/ts/packages/core/test/models/customToolRouting.test.tsindex 5277bf4a1..f057185ec 100644--- a/ts/packages/core/test/models/customToolRouting.test.ts+++ b/ts/packages/core/test/models/customToolRouting.test.ts@@ -217,7 +217,7 @@ describe('ToolRouterSession execution routing', () => {const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });expect(result.data).toEqual({ local_result: true });- expect(result.logId).toBe('local');+ expect(result.logId).toBe('');expect(localExecute).toHaveBeenCalledWith({ category: 'prefs' },expect.objectContaining({ userId: 'user_1' })