@devries-cameron20 / composio Mirror · read-only / commits / 7b58c4a8d
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 02:00 UTC

refactor: use official @composio/client types, proxyExecute via client method

- Bump @composio/client to 0.1.0-alpha.62 (adds proxyExecute, custom tool types) - Replace hand-rolled CustomToolDefinition/CustomToolkitDefinition with SessionCreateParams.Experimental.CustomTool/CustomToolkit from client - Type experimentalPayload as SessionCreateParams['experimental'] instead of Record<string, unknown> - Replace raw .post() hack in SessionContext/ToolRouterSession proxyExecute with official client.toolRouter.session.proxyExecute() - proxyParamsTransform now returns official ClientProxyExecuteParams type - Add ToolRouterSessionProxyExecuteResponse (status, data, headers, binaryData) matching ToolProxyResponse from client — consistent with tools.proxyExecute() - Build CustomToolsMap from API response slug/original_slug mapping instead of computing LOCAL_ prefix client-side - Add custom-tools.ts example showing standalone, extension (with proxyExecute), and toolkit tools with OpenAI Agents Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 18, 2026 at 13:05 UTC 7b58c4a8d6f88307908173210952fdd8b0f9d8e5
14 files changed +329 -157
pnpm-lock.yaml
+22 -63
@@ -25,8 +25,8 @@ catalogs:
25 specifier: ^4.20250917.0
26 version: 4.20260218.0
27 '@composio/client':
28 - specifier: 0.1.0-alpha.61
29 - version: 0.1.0-alpha.61
28 + specifier: 0.1.0-alpha.62
29 + version: 0.1.0-alpha.62
30 '@effect/cli':
31 specifier: ^0.73.2
32 version: 0.73.2
@@ -703,16 +703,16 @@ importers:
703 version: link:../../packages/providers/llamaindex
704 '@llamaindex/openai':
705 specifier: ^0.4.20
706 - version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)
706 + version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)
707 '@llamaindex/workflow':
708 specifier: ^1.1.24
709 - version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
709 + version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
710 dotenv:
711 specifier: ^16.4.1
712 version: 16.6.1
713 llamaindex:
714 specifier: ^0.12.0
715 - version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76)
715 + version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
716 devDependencies:
717 '@types/bun':
718 specifier: ^1.2.9
@@ -863,6 +863,9 @@ importers:
863 '@anthropic-ai/claude-agent-sdk':
864 specifier: ^0.1.55
865 version: 0.1.77(zod@4.3.6)
866 + '@composio/claude-agent-sdk':
867 + specifier: workspace:*
868 + version: link:../../packages/providers/claude-agent-sdk
869 '@composio/core':
870 specifier: workspace:*
871 version: link:../../packages/core
@@ -1048,7 +1051,7 @@ importers:
1051 version: 1.0.1
1052 '@composio/client':
1053 specifier: 'catalog:'
1051 - version: 0.1.0-alpha.61
1054 + version: 0.1.0-alpha.62
1055 '@composio/core':
1056 specifier: workspace:*
1057 version: link:../core
@@ -1145,7 +1148,7 @@ importers:
1148 dependencies:
1149 '@composio/client':
1150 specifier: 'catalog:'
1148 - version: 0.1.0-alpha.61
1151 + version: 0.1.0-alpha.62
1152 '@composio/json-schema-to-zod':
1153 specifier: workspace:*
1154 version: link:../json-schema-to-zod
@@ -1318,7 +1321,7 @@ importers:
1321 dependencies:
1322 llamaindex:
1323 specifier: ^0.12.0
1321 - version: 0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1324 + version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1325 devDependencies:
1326 '@composio/core':
1327 specifier: workspace:*
@@ -1792,8 +1795,8 @@ packages:
1795 resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
1796 engines: {node: '>=0.1.90'}
1797
1795 - '@composio/client@0.1.0-alpha.61':
1796 - resolution: {integrity: sha512-VSU20mTtMe0TIPHkBBRdCU4IYSy3886U9O69PURU8+ItLXCD2MjIN0S8VTDL8wpA4zFXamUFnvtwQyow11O2KA==}
1798 + '@composio/client@0.1.0-alpha.62':
1799 + resolution: {integrity: sha512-MUBawDp6Uw85m3T0ZtPUSTe9v4SPa0K/Ey3ADZQ/k1NkWsin0oGWhrB/i9hMzndRobijHmBw6xgnFCwjU1B9MQ==}
1800
1801 '@cspotcode/source-map-support@0.8.1':
1802 resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}
@@ -6862,7 +6865,7 @@ snapshots:
6865 '@colors/colors@1.5.0':
6866 optional: true
6867
6865 - '@composio/client@0.1.0-alpha.61': {}
6868 + '@composio/client@0.1.0-alpha.62': {}
6869
6870 '@cspotcode/source-map-support@0.8.1':
6871 dependencies:
@@ -7557,43 +7560,26 @@ snapshots:
7560 tree-sitter: 0.22.4
7561 web-tree-sitter: 0.24.7
7562
7560 - '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)':
7563 + '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)':
7564 dependencies:
7565 '@llamaindex/core': 0.6.22
7566 '@llamaindex/env': 0.1.30
7564 - openai: 5.23.2(ws@8.19.0)(zod@3.25.76)
7567 + openai: 5.23.2(ws@8.19.0)(zod@4.3.6)
7568 transitivePeerDependencies:
7569 - ws
7570 - zod
7571
7569 - '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
7572 + '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
7573 optionalDependencies:
7571 - '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)
7574 + '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6)
7575 hono: 4.11.9
7573 - zod: 3.25.76
7574 -
7575 - '@llamaindex/workflow-core@1.3.3(zod@4.3.6)':
7576 - optionalDependencies:
7576 zod: 4.3.6
7577
7579 - '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
7580 - dependencies:
7581 - '@llamaindex/core': 0.6.22
7582 - '@llamaindex/env': 0.1.30
7583 - '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
7584 - transitivePeerDependencies:
7585 - - '@modelcontextprotocol/sdk'
7586 - - hono
7587 - - next
7588 - - p-retry
7589 - - rxjs
7590 - - zod
7591 -
7592 - '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)':
7578 + '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
7579 dependencies:
7580 '@llamaindex/core': 0.6.22
7581 '@llamaindex/env': 0.1.30
7596 - '@llamaindex/workflow-core': 1.3.3(zod@4.3.6)
7582 + '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
7583 transitivePeerDependencies:
7584 - '@modelcontextprotocol/sdk'
7585 - hono
@@ -9923,34 +9909,12 @@ snapshots:
9909 rfdc: 1.4.1
9910 wrap-ansi: 9.0.2
9911
9926 - llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76):
9927 - dependencies:
9928 - '@llamaindex/core': 0.6.22
9929 - '@llamaindex/env': 0.1.30
9930 - '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
9931 - '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
9932 - '@types/lodash': 4.17.23
9933 - '@types/node': 24.10.13
9934 - lodash: 4.17.23
9935 - magic-bytes.js: 1.13.0
9936 - transitivePeerDependencies:
9937 - - '@huggingface/transformers'
9938 - - '@modelcontextprotocol/sdk'
9939 - - gpt-tokenizer
9940 - - hono
9941 - - next
9942 - - p-retry
9943 - - rxjs
9944 - - tree-sitter
9945 - - web-tree-sitter
9946 - - zod
9947 -
9948 - llamaindex@0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
9912 + llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
9913 dependencies:
9914 '@llamaindex/core': 0.6.22
9915 '@llamaindex/env': 0.1.30
9916 '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
9953 - '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)
9917 + '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
9918 '@types/lodash': 4.17.23
9919 '@types/node': 24.10.13
9920 lodash: 4.17.23
@@ -10230,11 +10194,6 @@ snapshots:
10194 is-inside-container: 1.0.0
10195 wsl-utils: 0.1.0
10196
10233 - openai@5.23.2(ws@8.19.0)(zod@3.25.76):
10234 - optionalDependencies:
10235 - ws: 8.19.0
10236 - zod: 3.25.76
10237 -
10197 openai@5.23.2(ws@8.19.0)(zod@4.3.6):
10198 optionalDependencies:
10199 ws: 8.19.0
pnpm-workspace.yaml
+1 -1
@@ -20,7 +20,7 @@ catalog:
20 '@clack/prompts': '^1.0.1'
21 '@cloudflare/vitest-pool-workers': ^0.9.2
22 '@cloudflare/workers-types': ^4.20250917.0
23 - '@composio/client': 0.1.0-alpha.61
23 + '@composio/client': 0.1.0-alpha.62
24 '@effect/cli': ^0.73.2
25 '@effect/eslint-plugin': ^0.3.2
26 '@effect/language-service': ^0.74.0
ts/examples/tool-router/package.json
+1
@@ -21,6 +21,7 @@
21 "@ai-sdk/mcp": "^0.0.11",
22 "@ai-sdk/openai": "^3.0.11",
23 "@anthropic-ai/claude-agent-sdk": "^0.1.55",
24 + "@composio/claude-agent-sdk": "workspace:*",
25 "@composio/core": "workspace:*",
26 "@composio/openai-agents": "workspace:*",
27 "@composio/vercel": "workspace:*",
ts/examples/tool-router/src/custom-tools.ts new
+115
@@ -0,0 +1,115 @@
1 +/**
2 + * Custom Tools — local tools + proxy execute with OpenAI Agents
3 + *
4 + * Shows how to create custom tools that run in-process alongside
5 + * remote Composio tools. Includes a tool that calls the Gmail API
6 + * directly via ctx.proxyExecute().
7 + *
8 + * Usage:
9 + * COMPOSIO_API_KEY=... OPENAI_API_KEY=... bun src/custom-tools.ts
10 + */
11 +import "dotenv/config";
12 +import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
13 +import { OpenAIAgentsProvider } from "@composio/openai-agents";
14 +import { Agent, run } from "@openai/agents";
15 +import { z } from "zod/v3";
16 +
17 +// ── Custom tools ────────────────────────────────────────────────
18 +
19 +/** Standalone tool (no auth needed) */
20 +const getUser = experimental_createTool("GET_USER", {
21 + name: "Get user",
22 + description: "Look up an internal user by ID",
23 + inputParams: z.object({
24 + user_id: z.string().describe("User ID (e.g. user-1)"),
25 + }),
26 + execute: async ({ user_id }) => {
27 + const users: Record<string, Record<string, string>> = {
28 + "user-1": { name: "Alice Johnson", email: "alice@acme.com", role: "admin" },
29 + "user-2": { name: "Bob Smith", email: "bob@acme.com", role: "developer" },
30 + };
31 + const user = users[user_id];
32 + if (!user) throw new Error(`User "${user_id}" not found`);
33 + return user;
34 + },
35 +});
36 +
37 +/** Extension tool — inherits Gmail auth, calls the real API via proxy */
38 +const createDraft = experimental_createTool("CREATE_DRAFT", {
39 + name: "Create Gmail draft",
40 + description: "Create a real Gmail draft via the Gmail API. Appears in the user's drafts folder.",
41 + extendsToolkit: "gmail",
42 + inputParams: z.object({
43 + to: z.string().describe("Recipient email address"),
44 + subject: z.string().describe("Email subject"),
45 + body: z.string().describe("Email body (plain text)"),
46 + }),
47 + execute: async (input, ctx) => {
48 + const raw = Buffer.from(
49 + `To: ${input.to}\r\nSubject: ${input.subject}\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n${input.body}`
50 + )
51 + .toString("base64")
52 + .replace(/\+/g, "-")
53 + .replace(/\//g, "_")
54 + .replace(/=+$/, "");
55 +
56 + const res = await ctx.proxyExecute({
57 + toolkit: "gmail",
58 + endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/drafts",
59 + method: "POST",
60 + body: { message: { raw } },
61 + });
62 +
63 + if (res.status !== 200) throw new Error(`Gmail API error ${res.status}`);
64 + const data = res.data as { id: string; message: { id: string } };
65 + return { draft_id: data.id, message_id: data.message.id, to: input.to, subject: input.subject };
66 + },
67 +});
68 +
69 +/** Custom toolkit — groups related tools under one namespace */
70 +const roleManager = experimental_createToolkit("ROLE_MANAGER", {
71 + name: "Role Manager",
72 + description: "Manage user roles",
73 + tools: [
74 + experimental_createTool("SET_ROLE", {
75 + name: "Set role",
76 + description: "Set a user's role",
77 + inputParams: z.object({
78 + user_id: z.string().describe("User ID"),
79 + role: z.enum(["admin", "developer", "viewer"]).describe("New role"),
80 + }),
81 + execute: async ({ user_id, role }) => ({ user_id, role, updated: true }),
82 + }),
83 + ],
84 +});
85 +
86 +// ── Agent ────────────────────────────────────────────────────────
87 +
88 +const composio = new Composio({
89 + provider: new OpenAIAgentsProvider(),
90 +});
91 +
92 +const session = await composio.create("default", {
93 + toolkits: ["gmail"],
94 + experimental: {
95 + customTools: [getUser, createDraft],
96 + customToolkits: [roleManager],
97 + },
98 +});
99 +
100 +const tools = await session.tools();
101 +
102 +const agent = new Agent({
103 + name: "Assistant",
104 + instructions:
105 + "You are a helpful assistant. Use Composio tools to execute tasks. " +
106 + "In MULTI_EXECUTE, always pass arguments inside the arguments field.",
107 + model: "gpt-4.1",
108 + tools,
109 +});
110 +
111 +const prompt = process.argv[2] ?? "Get user-1's info and draft an email to them saying hello";
112 +
113 +console.log(`> ${prompt}\n`);
114 +const result = await run(agent, prompt);
115 +console.log(result.finalOutput);
ts/packages/core/src/lib/toolRouterParams.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';
1 +import { SessionCreateParams } from '@composio/client/resources/tool-router/session/session.mjs';
2 import {
3 ToolRouterConfigTags,
4 ToolRouterConfigTools,
ts/packages/core/src/models/CustomTool.ts
+69
@@ -36,6 +36,7 @@ import {
36 type CustomToolkitDefinition,
37 type InputParamsSchema,
38 } from '../types/customTool.types';
39 +import type { SessionCreateResponse } from '@composio/client/resources/tool-router/session/session.mjs';
40 import { ValidationError } from '../errors';
41
42 /** Prefix applied by the backend to local tool slugs for disambiguation. */
@@ -355,3 +356,71 @@ export function serializeCustomToolkits(
356 })),
357 }));
358 }
359 +
360 +/**
361 + * Build a CustomToolsMap using the slug/original_slug mapping from the session create response.
362 + * This uses the backend's authoritative prefixed slugs instead of computing them client-side.
363 + *
364 + * @internal
365 + * @param tools - The original custom tools passed to session creation
366 + * @param toolkits - The original custom toolkits passed to session creation
367 + * @param experimental - The experimental section from the session create response
368 + * @returns Maps for O(1) lookup by both final and original slug
369 + */
370 +export function buildCustomToolsMapFromResponse(
371 + tools: CustomTool[],
372 + toolkits: CustomToolkit[] | undefined,
373 + experimental: SessionCreateResponse['experimental'] | undefined
374 +): CustomToolsMap {
375 + const byFinalSlug = new Map<string, CustomToolsMapEntry>();
376 + const byOriginalSlug = new Map<string, CustomToolsMapEntry>();
377 +
378 + // Build a lookup from original slug → custom tool handle (for matching response items)
379 + const handlesByOriginalSlug = new Map<string, { handle: CustomTool; toolkit?: string }>();
380 + for (const handle of tools) {
381 + handlesByOriginalSlug.set(handle.slug.toUpperCase(), { handle, toolkit: handle.extendsToolkit });
382 + }
383 + if (toolkits) {
384 + for (const tk of toolkits) {
385 + for (const handle of tk.tools) {
386 + handlesByOriginalSlug.set(handle.slug.toUpperCase(), { handle, toolkit: tk.slug });
387 + }
388 + }
389 + }
390 +
391 + const addEntry = (finalSlug: string, originalSlug: string, toolkit?: string) => {
392 + const match = handlesByOriginalSlug.get(originalSlug.toUpperCase());
393 + if (!match) return; // Response tool not found in our handles (shouldn't happen)
394 +
395 + const entry: CustomToolsMapEntry = {
396 + handle: match.handle,
397 + finalSlug,
398 + toolkit: toolkit ?? match.toolkit,
399 + };
400 + byFinalSlug.set(finalSlug, entry);
401 + byOriginalSlug.set(originalSlug.toUpperCase(), entry);
402 + };
403 +
404 + // Map standalone custom tools from response
405 + if (experimental?.custom_tools) {
406 + for (const ct of experimental.custom_tools) {
407 + addEntry(ct.slug, ct.original_slug, ct.extends_toolkit);
408 + }
409 + }
410 +
411 + // Map toolkit custom tools from response
412 + if (experimental?.custom_toolkits) {
413 + for (const ctk of experimental.custom_toolkits) {
414 + for (const ct of ctk.tools) {
415 + addEntry(ct.slug, ct.original_slug, ctk.slug);
416 + }
417 + }
418 + }
419 +
420 + // Fallback: if no response mapping available, use client-side prefix computation
421 + if (!experimental?.custom_tools && !experimental?.custom_toolkits) {
422 + return buildCustomToolsMap(tools, toolkits);
423 + }
424 +
425 + return { byFinalSlug, byOriginalSlug, toolkits };
426 +}
ts/packages/core/src/models/SessionContext.ts
+17 -11
@@ -4,7 +4,7 @@
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 } from '../types/toolRouter.types';
7 +import type { SessionProxyExecuteParams, ToolRouterSessionProxyExecuteResponse } from '../types/toolRouter.types';
8 import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
9 import { ValidationError } from '../errors';
10 import { transformProxyParams } from './proxyParamsTransform';
@@ -65,24 +65,30 @@ export class SessionContextImpl implements SessionContext {
65 * Proxy API calls through Composio's auth layer.
66 * The backend resolves the connected account from the toolkit within the session.
67 */
68 - async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolExecuteResponse> {
68 + async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse> {
69 const validated = SessionProxyExecuteParamsSchema.safeParse(params);
70 if (!validated.success) {
71 throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });
72 }
73
74 - const body = transformProxyParams(validated.data);
75 -
76 - // TODO: Replace with client.toolRouter.session.proxyExecute() when @composio/client is updated
77 - 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(
78 - `/api/v3/tool_router/session/${this.sessionId}/proxy_execute`,
79 - { body }
74 + const clientParams = transformProxyParams(validated.data);
75 + const response = await this.client.toolRouter.session.proxyExecute(
76 + this.sessionId,
77 + clientParams
78 );
79
80 return {
83 - data: response.data ?? {},
84 - error: response.error,
85 - successful: !response.error,
81 + status: response.status,
82 + data: response.data,
83 + 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 + } : {}),
92 };
93 }
94 }
ts/packages/core/src/models/ToolRouter.ts
+25 -16
@@ -29,7 +29,10 @@ import {
29 ToolRouterMCPServerConfig,
30 } from '../types/toolRouter.types';
31 import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types';
32 -import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';
32 +import {
33 + SessionCreateParams,
34 + SessionCreateResponse,
35 +} from '@composio/client/resources/tool-router/session/session.mjs';
36 import {
37 transformToolRouterTagsParams,
38 transformToolRouterToolsParams,
@@ -38,7 +41,7 @@ import {
41 transformToolRouterToolkitsParams,
42 } from '../lib/toolRouterParams';
43 import { ToolRouterSession } from './ToolRouterSession';
41 -import { buildCustomToolsMap, serializeCustomTools, serializeCustomToolkits } from './CustomTool';
44 +import { buildCustomToolsMapFromResponse, serializeCustomTools, serializeCustomToolkits } from './CustomTool';
45 import type { CustomToolsMap } from '../types/customTool.types';
46
47 export class ToolRouter<
@@ -101,10 +104,9 @@ export class ToolRouter<
104 // Extract custom tools/toolkits from experimental config
105 const customTools = routerConfig.experimental?.customTools;
106 const customToolkits = routerConfig.experimental?.customToolkits;
104 - let customToolsMap: CustomToolsMap | undefined;
107
106 - // Build the experimental payload for the backend
107 - const experimentalPayload: Record<string, unknown> = {};
108 + // Build the typed experimental payload for the backend
109 + const experimentalPayload: SessionCreateParams['experimental'] = {};
110
111 if (routerConfig.experimental?.assistivePrompt?.userTimezone) {
112 experimentalPayload.assistive_prompt_config = {
@@ -112,12 +114,11 @@ export class ToolRouter<
114 };
115 }
116
115 - if (customTools?.length || customToolkits?.length) {
116 - customToolsMap = buildCustomToolsMap(customTools ?? [], customToolkits);
117 - experimentalPayload.custom_tools = serializeCustomTools(customTools ?? []);
118 - if (customToolkits?.length) {
119 - experimentalPayload.custom_toolkits = serializeCustomToolkits(customToolkits);
120 - }
117 + if (customTools?.length) {
118 + experimentalPayload.custom_tools = serializeCustomTools(customTools);
119 + }
120 + if (customToolkits?.length) {
121 + experimentalPayload.custom_toolkits = serializeCustomToolkits(customToolkits);
122 }
123
124 const payload: SessionCreateParams = {
@@ -136,12 +137,20 @@ export class ToolRouter<
137 : undefined,
138 };
139
139 - const session = await this.client.toolRouter.session.create(
140 - payload as SessionCreateParams
141 - );
140 + const session = await this.client.toolRouter.session.create(payload);
141 +
142 + // Build custom tools map from the response's slug/original_slug mapping
143 + // instead of computing LOCAL_ prefix client-side
144 + let customToolsMap: CustomToolsMap | undefined;
145 + if (customTools?.length || customToolkits?.length) {
146 + customToolsMap = buildCustomToolsMapFromResponse(
147 + customTools ?? [],
148 + customToolkits,
149 + session.experimental
150 + );
151 + }
152
143 - const assistivePrompt =
144 - session.experimental?.assistive_prompt;
153 + const assistivePrompt = session.experimental?.assistive_prompt;
154
155 return new ToolRouterSession<TToolCollection, TTool, TProvider>(
156 this.client,
ts/packages/core/src/models/ToolRouterSession.ts
+20 -13
@@ -11,6 +11,7 @@ import {
11 ToolRouterSessionSearchResponseSchema,
12 ToolRouterSessionExecuteResponse,
13 ToolRouterSessionExecuteResponseSchema,
14 + ToolRouterSessionProxyExecuteResponse,
15 } from '../types/toolRouter.types';
16 import {
17 transformSearchResponse,
@@ -292,7 +293,7 @@ export class ToolRouterSession<
293 return {
294 data: result.data,
295 error: result.error,
295 - logId: 'local',
296 + logId: '',
297 };
298 }
299
@@ -310,27 +311,33 @@ export class ToolRouterSession<
311 * The backend resolves the connected account from the toolkit within the session.
312 *
313 * @param params - Proxy request parameters (toolkit, endpoint, method, body, headers/query params)
313 - * @returns The proxied API response
314 + * @returns The proxied API response with status, data, headers
315 */
315 - async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionExecuteResponse> {
316 + async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse> {
317 const validated = SessionProxyExecuteParamsSchema.safeParse(params);
318 if (!validated.success) {
319 throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });
320 }
321
321 - const body = transformProxyParams(validated.data);
322 -
323 - // TODO: Replace with client.toolRouter.session.proxyExecute() when @composio/client is updated
324 - 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(
325 - `/api/v3/tool_router/session/${this.sessionId}/proxy_execute`,
326 - { body }
322 + const clientParams = transformProxyParams(validated.data);
323 + const response = await this.client.toolRouter.session.proxyExecute(
324 + this.sessionId,
325 + clientParams
326 );
327
329 - return ToolRouterSessionExecuteResponseSchema.parse({
328 + return {
329 + status: response.status,
330 data: response.data,
331 - error: response.error,
332 - logId: response.log_id,
333 - });
331 + headers: response.headers,
332 + ...(response.binary_data ? {
333 + binaryData: {
334 + contentType: response.binary_data.content_type,
335 + size: response.binary_data.size,
336 + url: response.binary_data.url,
337 + expiresAt: response.binary_data.expires_at,
338 + },
339 + } : {}),
340 + };
341 }
342
343 // ── Private helpers ──────────────────────────────────────────
ts/packages/core/src/models/proxyParamsTransform.ts
+6 -14
@@ -1,24 +1,16 @@
1 /**
2 * @fileoverview Shared transform for converting SDK SessionProxyExecuteParams
3 - * to the backend proxy execute request format.
3 + * to the official @composio/client proxy execute params.
4 */
5 import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
6 -
7 -/** Backend session proxy execute request body shape. */
8 -export interface SessionProxyExecuteRequestBody {
9 - toolkit_slug: string;
10 - endpoint: string;
11 - method: string;
12 - body?: unknown;
13 - parameters?: Array<{ name: string; type: 'header' | 'query'; value: string }>;
14 -}
6 +import type { SessionProxyExecuteParams as ClientProxyExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
7
8 /**
17 - * Transform SDK session proxy params to the backend request format.
18 - * Converts `in` (query/header) to `type` and stringifies values.
9 + * Transform SDK session proxy params to the official client request format.
10 + * Converts SDK-facing `toolkit` → `toolkit_slug` and `parameters[].in` → `parameters[].type`.
11 */
20 -export function transformProxyParams(params: SessionProxyExecuteParams): SessionProxyExecuteRequestBody {
21 - const parameters = params.parameters?.map(p => ({
12 +export function transformProxyParams(params: SessionProxyExecuteParams): ClientProxyExecuteParams {
13 + const parameters: ClientProxyExecuteParams['parameters'] = params.parameters?.map(p => ({
14 name: p.name,
15 type: p.in as 'header' | 'query',
16 value: p.value.toString(),
ts/packages/core/src/types/customTool.types.ts
+20 -20
@@ -1,8 +1,12 @@
1 import { z } from 'zod/v3';
2 import { Tool, ToolProxyParams, ToolExecuteResponse as SdkToolExecuteResponse } from './tool.types';
3 -import type { SessionProxyExecuteParams } from './toolRouter.types';
3 +import type { SessionProxyExecuteParams, ToolRouterSessionProxyExecuteResponse } from './toolRouter.types';
4 import { ToolExecuteResponse } from '@composio/client/resources/tools';
5 import { ConnectionData } from './connectedAccountAuthStates.types';
6 +import type {
7 + SessionCreateParams,
8 + SessionCreateResponse,
9 +} from '@composio/client/resources/tool-router/session/session.mjs';
10
11 // ────────────────────────────────────────────────────────────────
12 // Legacy custom tool types (used by composio.tools.createCustomTool)
@@ -76,7 +80,7 @@ export interface SessionContext {
80 arguments_: Record<string, unknown>
81 ): Promise<SdkToolExecuteResponse>;
82 /** Proxy API calls through Composio's auth layer (resolved from session toolkit). */
79 - proxyExecute(params: SessionProxyExecuteParams): Promise<SdkToolExecuteResponse>;
83 + proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse>;
84 }
85
86 /**
@@ -165,16 +169,8 @@ export interface CustomTool {
169 readonly execute: CustomToolExecuteFn<z.ZodType>;
170 }
171
168 -/** Serialized tool definition sent to backend for search indexing. */
169 -export interface CustomToolDefinition {
170 - slug: string;
171 - name: string;
172 - description: string;
173 - input_schema: Record<string, unknown>;
174 - output_schema?: Record<string, unknown>;
175 - /** Mapped from `extendsToolkit`. Omitted for standalone tools. */
176 - extends_toolkit?: string;
177 -}
172 +/** Serialized tool definition sent to backend for search indexing. Uses official client type. */
173 +export type CustomToolDefinition = SessionCreateParams.Experimental.CustomTool;
174
175 // ────────────────────────────────────────────────────────────────
176 // Custom toolkit types
@@ -206,14 +202,8 @@ export interface CustomToolkit {
202 readonly tools: readonly CustomTool[];
203 }
204
209 -/** Serialized toolkit definition sent to backend. */
210 -export interface CustomToolkitDefinition {
211 - slug: string;
212 - name: string;
213 - description: string;
214 - /** Nested tools — no extends_toolkit, they inherit the toolkit identity from the parent. */
215 - tools: Omit<CustomToolDefinition, 'extends_toolkit'>[];
216 -}
205 +/** Serialized toolkit definition sent to backend. Uses official client type. */
206 +export type CustomToolkitDefinition = SessionCreateParams.Experimental.CustomToolkit;
207
208 // ────────────────────────────────────────────────────────────────
209 // Internal routing types
@@ -261,3 +251,13 @@ export interface RegisteredCustomToolkit {
251 description: string;
252 tools: RegisteredCustomTool[];
253 }
254 +
255 +// ────────────────────────────────────────────────────────────────
256 +// Response types from the backend (slug + original_slug mapping)
257 +// ────────────────────────────────────────────────────────────────
258 +
259 +/** Custom tool as returned in the session create response (has prefixed slug + original_slug). */
260 +export type CustomToolResponse = SessionCreateResponse.Experimental.CustomTool;
261 +
262 +/** Custom toolkit as returned in the session create response (has prefixed slugs + original_slugs). */
263 +export type CustomToolkitResponse = SessionCreateResponse.Experimental.CustomToolkit;
ts/packages/core/src/types/toolRouter.types.ts
+19 -1
@@ -405,6 +405,24 @@ export type ToolRouterSessionExecuteResponse = z.infer<
405 typeof ToolRouterSessionExecuteResponseSchema
406 >;
407
408 +// --- Session proxy execute response (matches ToolProxyResponse from client) ---
409 +
410 +export interface ToolRouterSessionProxyExecuteResponse {
411 + /** The HTTP status code returned from the proxied API */
412 + status: number;
413 + /** The response data from the proxied API */
414 + data?: unknown;
415 + /** HTTP headers from the proxied API */
416 + headers?: Record<string, string>;
417 + /** Binary response data (present when response is a file) */
418 + binaryData?: {
419 + contentType: string;
420 + size: number;
421 + url: string;
422 + expiresAt?: string;
423 + };
424 +}
425 +
426 /**
427 * Experimental features on a tool router session.
428 * Contains features that may be modified or removed in future versions.
@@ -455,7 +473,7 @@ export type SessionProxyExecuteParams = z.infer<typeof SessionProxyExecuteParams
473
474 export type ToolRouterSessionProxyExecuteFn = (
475 params: SessionProxyExecuteParams
458 -) => Promise<ToolRouterSessionExecuteResponse>;
476 +) => Promise<ToolRouterSessionProxyExecuteResponse>;
477
478 /** Session type returned by ToolRouter.create() and ToolRouter.use() */
479 export interface Session<
ts/packages/core/test/models/customTool.test.ts
+12 -16
@@ -518,6 +518,7 @@ describe('SessionContextImpl', () => {
518 toolRouter: {
519 session: {
520 execute: vi.fn(),
521 + proxyExecute: vi.fn(),
522 },
523 },
524 };
@@ -566,14 +567,12 @@ describe('SessionContextImpl', () => {
567 expect(result.error).toBe('something went wrong');
568 });
569
569 - it('should call session proxy_execute endpoint via proxyExecute()', async () => {
570 - const mockPost = vi.fn().mockResolvedValue({
570 + it('should call client.toolRouter.session.proxyExecute() via proxyExecute()', async () => {
571 + mockClient.toolRouter.session.proxyExecute.mockResolvedValue({
572 + status: 200,
573 data: { proxy_result: true },
572 - error: null,
573 - log_id: 'log_proxy',
574 });
575 - const clientWithPost = { ...mockClient, post: mockPost };
576 - const ctx = new SessionContextImpl(clientWithPost as any, 'user_1', 'sess_1');
575 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
576
577 const result = await ctx.proxyExecute({
578 toolkit: 'github',
@@ -582,21 +581,18 @@ describe('SessionContextImpl', () => {
581 parameters: [{ in: 'header' as const, name: 'X-Custom', value: 'val' }],
582 });
583
585 - expect(mockPost).toHaveBeenCalledWith(
586 - '/api/v3/tool_router/session/sess_1/proxy_execute',
584 + expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith(
585 + 'sess_1',
586 {
588 - body: {
589 - toolkit_slug: 'github',
590 - endpoint: 'https://api.github.com/user',
591 - method: 'GET',
592 - parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],
593 - },
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 );
593 expect(result).toEqual({
594 + status: 200,
595 data: { proxy_result: true },
598 - error: null,
599 - successful: true,
596 });
597 });
598
ts/packages/core/test/models/customToolRouting.test.ts
+1 -1
@@ -217,7 +217,7 @@ describe('ToolRouterSession execution routing', () => {
217 const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
218
219 expect(result.data).toEqual({ local_result: true });
220 - expect(result.logId).toBe('local');
220 + expect(result.logId).toBe('');
221 expect(localExecute).toHaveBeenCalledWith(
222 { category: 'prefs' },
223 expect.objectContaining({ userId: 'user_1' })