@devries-cameron20 / composio-1 / commits / ba9762484
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.

refactor: session.customTools/customToolkits, early validation, ctx rename, COMPOSIO_ rejection

- Add session.customTools({ toolkit? }) and session.customToolkits() methods returning registered tools with final slugs, schemas, and resolved toolkit - Early slug length validation in createCustomTool (standalone + extension) and createCustomToolkit (per tool), with buildCustomToolsMap as safety net - Reject COMPOSIO_ prefix in CustomToolSlugSchema (prevents meta tool shadowing) - Rename execute fn param from session → ctx everywhere (type def, docs, examples, tests) - SessionContextImpl as singleton on ToolRouterSession (created once in constructor) - Rename internal byPrefixed/byOriginal → byFinalSlug/byOriginalSlug - Store resolved toolkit on map entries for session.customTools() lookups - Add RegisteredCustomTool and RegisteredCustomToolkit types to Session interface - JSDoc on extendsToolkit: must be a valid Composio toolkit slug Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 17, 2026 at 14:31 UTC ba97624843dc5776e43d8b3106fc63db48f7f049
11 files changed +613 -120
ts/docs/api/tool-router.md
+2 -2
@@ -293,8 +293,8 @@ const getImportant = experimental_createTool('GET_IMPORTANT_EMAILS', {
293 description: 'Fetch high-priority emails',
294 extendsToolkit: 'gmail',
295 inputParams: z.object({ limit: z.number().default(10) }),
296 - execute: async (input, session) => {
297 - const result = await session.execute('GMAIL_SEARCH', { query: 'is:important' });
296 + execute: async (input, ctx) => {
297 + const result = await ctx.execute('GMAIL_SEARCH', { query: 'is:important' });
298 return { emails: result.data };
299 },
300 });
ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs
+5 -5
@@ -34,10 +34,10 @@ const enrichedSearch = createCustomTool('ENRICHED_SEARCH', {
34 inputParams: z.object({
35 query: z.string(),
36 }),
37 - execute: async (input, session) => {
37 + execute: async (input, ctx) => {
38 return {
39 query: input.query,
40 - userId: session.userId,
40 + userId: ctx.userId,
41 };
42 },
43 });
@@ -70,14 +70,14 @@ const weatherChain = createCustomTool('WEATHER_CHAIN', {
70 inputParams: z.object({
71 city: z.string(),
72 }),
73 - execute: async (input, session) => {
73 + execute: async (input, ctx) => {
74 // Call remote WEATHERMAP_WEATHER tool through SessionContext
75 - const weather = await session.execute('WEATHERMAP_WEATHER', {
75 + const weather = await ctx.execute('WEATHERMAP_WEATHER', {
76 location: input.city,
77 });
78 return {
79 city: input.city,
80 - userId: session.userId,
80 + userId: ctx.userId,
81 weatherData: weather.data,
82 weatherError: weather.error,
83 };
ts/examples/tool-router/src/custom-tools-agent.ts
+2 -2
@@ -99,7 +99,7 @@ const formatGmailEmail = experimental_createTool("FORMAT_GMAIL_EMAIL", {
99 subject: z.string().describe("Email subject line"),
100 body: z.string().describe("Email body content in markdown"),
101 }),
102 - execute: async (input, session) => {
102 + execute: async (input, ctx) => {
103 const htmlBody = input.body
104 .replace(/\*\*(.*?)\*\*/g, "<b>$1</b>")
105 .replace(/\*(.*?)\*/g, "<i>$1</i>")
@@ -110,7 +110,7 @@ const formatGmailEmail = experimental_createTool("FORMAT_GMAIL_EMAIL", {
110 subject: input.subject,
111 html_body: htmlBody,
112 plain_body: input.body,
113 - user_id: session.userId,
113 + user_id: ctx.userId,
114 };
115 },
116 });
ts/examples/tool-router/src/custom-tools-e2e.ts new
+357
@@ -0,0 +1,357 @@
1 +/**
2 + * Focused E2E test: Custom tools + custom toolkits against live backend.
3 + *
4 + * Tests session creation, local execution, search indexing, and all three
5 + * tool types (standalone, extendsToolkit, custom toolkit).
6 + *
7 + * Usage:
8 + * COMPOSIO_API_KEY=... COMPOSIO_BASE_URL=... bun src/custom-tools-e2e.ts
9 + */
10 +import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
11 +import { z } from "zod/v3";
12 +
13 +const apiKey = process.env.COMPOSIO_API_KEY;
14 +const baseURL = process.env.COMPOSIO_BASE_URL;
15 +if (!apiKey) {
16 + console.error("COMPOSIO_API_KEY is required");
17 + process.exit(1);
18 +}
19 +
20 +let passed = 0;
21 +let failed = 0;
22 +
23 +function ok(label: string) {
24 + passed++;
25 + console.log(` ✓ ${label}`);
26 +}
27 +function fail(label: string, err: unknown) {
28 + failed++;
29 + console.error(` ✗ ${label}: ${err instanceof Error ? err.message : err}`);
30 +}
31 +
32 +// ── Shared in-memory user store ──────────────────────────────────
33 +
34 +const userStore: Record<string, Record<string, unknown>> = {
35 + "user-1": { id: "user-1", name: "Alice Johnson", email: "alice@acme.com", role: "admin", status: "active" },
36 + "user-2": { id: "user-2", name: "Bob Smith", email: "bob@acme.com", role: "developer", status: "active" },
37 + "user-3": { id: "user-3", name: "Carol Williams", email: "carol@acme.com", role: "viewer", status: "suspended" },
38 +};
39 +
40 +// ────────────────────────────────────────────────────────────────
41 +// 1. Standalone tools (no auth) → LOCAL_<SLUG>
42 +// ────────────────────────────────────────────────────────────────
43 +
44 +const getUserDetails = experimental_createTool("GET_USER_DETAILS", {
45 + name: "Get user details",
46 + description: "Retrieve user profile information including name, email, role, and account status by user ID",
47 + inputParams: z.object({
48 + user_id: z.string().describe("The unique user identifier"),
49 + }),
50 + execute: async (input) => {
51 + const user = userStore[input.user_id];
52 + if (!user) throw new Error(`User "${input.user_id}" not found`);
53 + return { ...user };
54 + },
55 +});
56 +
57 +const listUserKeys = experimental_createTool("LIST_USER_KEYS", {
58 + name: "List user API keys",
59 + description: "List all active API keys for a given user, including creation date and last used timestamp",
60 + inputParams: z.object({
61 + user_id: z.string().describe("The user whose keys to list"),
62 + include_expired: z.boolean().default(false),
63 + }),
64 + execute: async (input) => {
65 + const keys = [
66 + { key_id: "key_abc", prefix: "sk-***abc", expired: false },
67 + { key_id: "key_old", prefix: "sk-***old", expired: true },
68 + ];
69 + const filtered = input.include_expired ? keys : keys.filter((k) => !k.expired);
70 + return { user_id: input.user_id, api_keys: filtered, total: filtered.length };
71 + },
72 +});
73 +
74 +// ────────────────────────────────────────────────────────────────
75 +// 2. Extension tool (inherits gmail auth) → LOCAL_GMAIL_<SLUG>
76 +// ────────────────────────────────────────────────────────────────
77 +
78 +const formatGmailEmail = experimental_createTool("FORMAT_GMAIL_EMAIL", {
79 + name: "Format Gmail email",
80 + description: "Format and prepare an email draft with proper HTML formatting for sending via Gmail",
81 + extendsToolkit: "gmail",
82 + inputParams: z.object({
83 + to: z.string().describe("Recipient email address"),
84 + subject: z.string().describe("Email subject line"),
85 + body: z.string().describe("Email body content"),
86 + }),
87 + execute: async (input, ctx) => {
88 + const htmlBody = input.body.replace(/\n/g, "<br>");
89 + return {
90 + formatted: true,
91 + to: input.to,
92 + subject: input.subject,
93 + html_body: htmlBody,
94 + user_id: ctx.userId,
95 + };
96 + },
97 +});
98 +
99 +// ────────────────────────────────────────────────────────────────
100 +// 3. Custom toolkit (USER_MANAGEMENT) → LOCAL_USER_MANAGEMENT_<SLUG>
101 +// ────────────────────────────────────────────────────────────────
102 +
103 +const setUserRole = experimental_createTool("SET_USER_ROLE", {
104 + name: "Set user role",
105 + description: "Change the role of an existing user (admin, developer, viewer)",
106 + inputParams: z.object({
107 + user_id: z.string().describe("The user to update"),
108 + role: z.enum(["admin", "developer", "viewer"]).describe("The new role to assign"),
109 + }),
110 + execute: async (input) => {
111 + const user = userStore[input.user_id];
112 + if (!user) throw new Error(`User "${input.user_id}" not found`);
113 + const previousRole = user.role;
114 + user.role = input.role;
115 + return { user_id: input.user_id, previous_role: previousRole, new_role: input.role };
116 + },
117 +});
118 +
119 +const updateUserStatus = experimental_createTool("UPDATE_USER_STATUS", {
120 + name: "Update user status",
121 + description: "Activate or suspend a user account",
122 + inputParams: z.object({
123 + user_id: z.string().describe("The user to update"),
124 + status: z.enum(["active", "suspended"]).describe("The new account status"),
125 + reason: z.string().optional().describe("Reason for the status change"),
126 + }),
127 + execute: async (input) => {
128 + const user = userStore[input.user_id];
129 + if (!user) throw new Error(`User "${input.user_id}" not found`);
130 + const previousStatus = user.status;
131 + user.status = input.status;
132 + return { user_id: input.user_id, previous_status: previousStatus, new_status: input.status, reason: input.reason ?? "No reason provided" };
133 + },
134 +});
135 +
136 +const userManagement = experimental_createToolkit("USER_MANAGEMENT", {
137 + name: "User Management",
138 + description: "Tools for managing user profiles, roles, and account status",
139 + tools: [setUserRole, updateUserStatus],
140 +});
141 +
142 +// ────────────────────────────────────────────────────────────────
143 +// Run tests
144 +// ────────────────────────────────────────────────────────────────
145 +
146 +const composio = new Composio({ apiKey, baseURL: baseURL ?? undefined });
147 +
148 +async function main() {
149 + const userId = `e2e-custom-${Date.now()}`;
150 + console.log(`\nCreating session for user: ${userId}`);
151 + console.log(`Base URL: ${baseURL ?? "(default)"}\n`);
152 +
153 + // ── Session creation with all 3 tool types ──
154 + let session: Awaited<ReturnType<typeof composio.create>>;
155 + try {
156 + session = await composio.create(userId, {
157 + toolkits: ["weathermap", "gmail"],
158 + manageConnections: false,
159 + experimental: {
160 + customTools: [getUserDetails, listUserKeys, formatGmailEmail],
161 + customToolkits: [userManagement],
162 + },
163 + });
164 + ok(`Session created: ${session.sessionId}`);
165 + } catch (err) {
166 + fail("Session creation", err);
167 + console.error("\nCannot continue without a session.");
168 + process.exit(1);
169 + }
170 +
171 + // ════════════════════════════════════════════════════════════════
172 + // Standalone tools (LOCAL_GET_USER_DETAILS, LOCAL_LIST_USER_KEYS)
173 + // ════════════════════════════════════════════════════════════════
174 +
175 + try {
176 + const result = await session.execute("GET_USER_DETAILS", { user_id: "user-1" });
177 + if (result.data?.name !== "Alice Johnson") throw new Error(`Unexpected: ${JSON.stringify(result.data)}`);
178 + ok("Standalone: execute by original slug (GET_USER_DETAILS)");
179 + } catch (err) {
180 + fail("Standalone: execute by original slug", err);
181 + }
182 +
183 + try {
184 + const result = await session.execute("LOCAL_GET_USER_DETAILS", { user_id: "user-2" });
185 + if (result.data?.name !== "Bob Smith") throw new Error(`Unexpected: ${JSON.stringify(result.data)}`);
186 + ok("Standalone: execute by prefixed slug (LOCAL_GET_USER_DETAILS)");
187 + } catch (err) {
188 + fail("Standalone: execute by prefixed slug", err);
189 + }
190 +
191 + try {
192 + const result = await session.execute("LIST_USER_KEYS", { user_id: "user-1" });
193 + if (result.data?.total !== 1) throw new Error(`Expected 1 active key, got: ${JSON.stringify(result.data)}`);
194 + ok("Standalone: second tool routes correctly (LIST_USER_KEYS)");
195 + } catch (err) {
196 + fail("Standalone: second tool routes correctly", err);
197 + }
198 +
199 + try {
200 + const result = await session.execute("LIST_USER_KEYS", { user_id: "user-1", include_expired: true });
201 + if (result.data?.total !== 2) throw new Error(`Expected 2 keys with expired, got: ${JSON.stringify(result.data)}`);
202 + ok("Standalone: Zod defaults overridden (include_expired=true → 2 keys)");
203 + } catch (err) {
204 + fail("Standalone: Zod defaults overridden", err);
205 + }
206 +
207 + // ════════════════════════════════════════════════════════════════
208 + // Extension tool (LOCAL_GMAIL_FORMAT_GMAIL_EMAIL)
209 + // ════════════════════════════════════════════════════════════════
210 +
211 + try {
212 + const result = await session.execute("FORMAT_GMAIL_EMAIL", {
213 + to: "test@example.com",
214 + subject: "Hello",
215 + body: "Line 1\nLine 2",
216 + });
217 + if (result.error) throw new Error(`Execute error: ${result.error}`);
218 + if (result.data?.formatted !== true) throw new Error(`Not formatted: ${JSON.stringify(result.data)}`);
219 + if (result.data?.html_body !== "Line 1<br>Line 2") throw new Error(`HTML mismatch: ${result.data?.html_body}`);
220 + if (result.data?.user_id !== userId) throw new Error(`UserId mismatch: ${result.data?.user_id}`);
221 + ok("Extension: execute by original slug (FORMAT_GMAIL_EMAIL) + session context");
222 + } catch (err) {
223 + fail("Extension: execute by original slug", err);
224 + }
225 +
226 + try {
227 + const result = await session.execute("LOCAL_GMAIL_FORMAT_GMAIL_EMAIL", {
228 + to: "x@y.com",
229 + subject: "Test",
230 + body: "body",
231 + });
232 + if (result.data?.to !== "x@y.com") throw new Error(`Unexpected: ${JSON.stringify(result.data)}`);
233 + ok("Extension: execute by prefixed slug (LOCAL_GMAIL_FORMAT_GMAIL_EMAIL)");
234 + } catch (err) {
235 + fail("Extension: execute by prefixed slug", err);
236 + }
237 +
238 + // ════════════════════════════════════════════════════════════════
239 + // Custom toolkit (LOCAL_USER_MANAGEMENT_SET_USER_ROLE, etc.)
240 + // ════════════════════════════════════════════════════════════════
241 +
242 + try {
243 + const result = await session.execute("SET_USER_ROLE", { user_id: "user-3", role: "developer" });
244 + if (result.data?.previous_role !== "viewer") throw new Error(`Previous role wrong: ${JSON.stringify(result.data)}`);
245 + if (result.data?.new_role !== "developer") throw new Error(`New role wrong: ${JSON.stringify(result.data)}`);
246 + ok("Toolkit: execute by original slug (SET_USER_ROLE)");
247 + } catch (err) {
248 + fail("Toolkit: execute by original slug", err);
249 + }
250 +
251 + try {
252 + const result = await session.execute("LOCAL_USER_MANAGEMENT_SET_USER_ROLE", { user_id: "user-2", role: "admin" });
253 + if (result.data?.new_role !== "admin") throw new Error(`Unexpected: ${JSON.stringify(result.data)}`);
254 + ok("Toolkit: execute by prefixed slug (LOCAL_USER_MANAGEMENT_SET_USER_ROLE)");
255 + } catch (err) {
256 + fail("Toolkit: execute by prefixed slug", err);
257 + }
258 +
259 + try {
260 + const result = await session.execute("UPDATE_USER_STATUS", { user_id: "user-3", status: "active", reason: "Suspended by mistake" });
261 + if (result.data?.previous_status !== "suspended") throw new Error(`Previous status wrong: ${JSON.stringify(result.data)}`);
262 + if (result.data?.new_status !== "active") throw new Error(`New status wrong: ${JSON.stringify(result.data)}`);
263 + if (result.data?.reason !== "Suspended by mistake") throw new Error(`Reason wrong: ${JSON.stringify(result.data)}`);
264 + ok("Toolkit: second tool + optional param (UPDATE_USER_STATUS with reason)");
265 + } catch (err) {
266 + fail("Toolkit: second tool + optional param", err);
267 + }
268 +
269 + try {
270 + const result = await session.execute("LOCAL_USER_MANAGEMENT_UPDATE_USER_STATUS", { user_id: "user-1", status: "suspended" });
271 + if (result.data?.reason !== "No reason provided") throw new Error(`Default reason not applied: ${JSON.stringify(result.data)}`);
272 + ok("Toolkit: prefixed slug + optional param default (reason → 'No reason provided')");
273 + } catch (err) {
274 + fail("Toolkit: prefixed slug + optional param default", err);
275 + }
276 +
277 + // Verify state mutations persisted across calls
278 + try {
279 + const result = await session.execute("GET_USER_DETAILS", { user_id: "user-3" });
280 + if (result.data?.role !== "developer") throw new Error(`Role not updated: ${JSON.stringify(result.data)}`);
281 + if (result.data?.status !== "active") throw new Error(`Status not updated: ${JSON.stringify(result.data)}`);
282 + ok("Toolkit: state mutations persisted (user-3 is now developer+active)");
283 + } catch (err) {
284 + fail("Toolkit: state mutations persisted", err);
285 + }
286 +
287 + // ════════════════════════════════════════════════════════════════
288 + // Cross-cutting: case insensitive, error handling, search, remote
289 + // ════════════════════════════════════════════════════════════════
290 +
291 + try {
292 + const result = await session.execute("get_user_details", { user_id: "user-1" });
293 + if (!result.data?.name) throw new Error(`Unexpected: ${JSON.stringify(result.data)}`);
294 + ok("Case-insensitive slug lookup (get_user_details → GET_USER_DETAILS)");
295 + } catch (err) {
296 + fail("Case-insensitive slug", err);
297 + }
298 +
299 + try {
300 + const result = await session.execute("GET_USER_DETAILS", { user_id: "nonexistent" });
301 + if (!result.error?.includes("not found")) throw new Error(`Expected 'not found' error, got: ${result.error}`);
302 + ok("Error handling: thrown error wrapped in response");
303 + } catch (err) {
304 + fail("Error handling", err);
305 + }
306 +
307 + // Search — standalone tools
308 + try {
309 + const searchResult = await session.search({ query: "get user profile details" });
310 + const toolSlugs = searchResult.results.flatMap((r) => r.primaryToolSlugs);
311 + const found = toolSlugs.find((s) => s === "LOCAL_GET_USER_DETAILS");
312 + if (!found) console.log(" (search returned:", toolSlugs.join(", "), ")");
313 + ok(`Search: standalone tool found=${!!found} (${searchResult.results.length} results)`);
314 + } catch (err) {
315 + fail("Search: standalone tools", err);
316 + }
317 +
318 + // Search — toolkit tools
319 + try {
320 + const searchResult = await session.search({ query: "change user role to admin" });
321 + const toolSlugs = searchResult.results.flatMap((r) => r.primaryToolSlugs);
322 + const found = toolSlugs.find((s) => s.includes("USER_MANAGEMENT"));
323 + if (!found) console.log(" (search returned:", toolSlugs.join(", "), ")");
324 + ok(`Search: toolkit tool found=${!!found} (${searchResult.results.length} results)`);
325 + } catch (err) {
326 + fail("Search: toolkit tools", err);
327 + }
328 +
329 + // Search — extension tool
330 + try {
331 + const searchResult = await session.search({ query: "format email draft for gmail" });
332 + const toolSlugs = searchResult.results.flatMap((r) => r.primaryToolSlugs);
333 + const found = toolSlugs.find((s) => s.includes("GMAIL") && s.startsWith("LOCAL_"));
334 + if (!found) console.log(" (search returned:", toolSlugs.join(", "), ")");
335 + ok(`Search: extension tool found=${!!found} (${searchResult.results.length} results)`);
336 + } catch (err) {
337 + fail("Search: extension tool", err);
338 + }
339 +
340 + // Remote tool still works alongside custom tools
341 + try {
342 + const result = await session.execute("WEATHERMAP_WEATHER", { location: "Tokyo" });
343 + if (result.error) throw new Error(`Remote error: ${result.error}`);
344 + ok(`Remote tool execution (WEATHERMAP_WEATHER) — keys: ${Object.keys(result.data ?? {}).join(", ")}`);
345 + } catch (err) {
346 + fail("Remote tool execution", err);
347 + }
348 +
349 + // ── Summary ──
350 + console.log(`\n${passed} passed, ${failed} failed out of ${passed + failed} tests`);
351 + if (failed > 0) process.exit(1);
352 +}
353 +
354 +main().catch((err) => {
355 + console.error("Fatal:", err);
356 + process.exit(1);
357 +});
ts/packages/core/src/models/CustomTool.ts
+76 -45
@@ -42,7 +42,35 @@ import { ValidationError } from '../errors';
42 export const LOCAL_TOOL_PREFIX = 'LOCAL_';
43
44 /** Maximum allowed length for the final prefixed slug. */
45 -const MAX_PREFIXED_SLUG_LENGTH = 60;
45 +const MAX_SLUG_LENGTH = 60;
46 +
47 +/**
48 + * Compute the final slug length for a tool given its context.
49 + * Returns the expected length of LOCAL_[TOOLKIT_]SLUG.
50 + */
51 +function computeFinalSlugLength(toolSlug: string, toolkitSlug?: string): number {
52 + // LOCAL_ + optional TOOLKIT_ + SLUG
53 + return LOCAL_TOOL_PREFIX.length
54 + + (toolkitSlug ? toolkitSlug.length + 1 : 0) // +1 for underscore separator
55 + + toolSlug.length;
56 +}
57 +
58 +/**
59 + * Validate that the final slug won't exceed the max length.
60 + * Called early in createCustomTool/createCustomToolkit for fast feedback.
61 + */
62 +function validateSlugLength(toolSlug: string, toolkitSlug: string | undefined, context: string): void {
63 + const finalLength = computeFinalSlugLength(toolSlug, toolkitSlug);
64 + if (finalLength > MAX_SLUG_LENGTH) {
65 + const prefix = LOCAL_TOOL_PREFIX + (toolkitSlug ? `${toolkitSlug.toUpperCase()}_` : '');
66 + const available = MAX_SLUG_LENGTH - prefix.length;
67 + throw new ValidationError(
68 + `${context}: slug "${toolSlug}" is too long. ` +
69 + `With prefix "${prefix}", the final slug would be ${finalLength} characters (max ${MAX_SLUG_LENGTH}). ` +
70 + `Shorten the slug to at most ${available} characters.`
71 + );
72 + }
73 +}
74
75 /**
76 * Create a custom tool for use in tool router sessions.
@@ -54,7 +82,7 @@ const MAX_PREFIXED_SLUG_LENGTH = 60;
82 * Just return the result data from `execute`, or throw an error.
83 * The SDK wraps it into the standard response format internally.
84 *
57 - * @param slug - Unique tool identifier (alphanumeric, underscores, hyphens; no LOCAL_ prefix)
85 + * @param slug - Unique tool identifier (alphanumeric, underscores, hyphens; no LOCAL_ or COMPOSIO_ prefix)
86 * @param options - Tool definition including name, schema, and execute function
87 * @returns A CustomTool to pass to session creation
88 *
@@ -75,8 +103,8 @@ const MAX_PREFIXED_SLUG_LENGTH = 60;
103 * description: 'Fetch high-priority emails',
104 * extendsToolkit: 'gmail',
105 * inputParams: z.object({ limit: z.number().default(10) }),
78 - * execute: async (input, session) => {
79 - * const result = await session.execute('GMAIL_SEARCH', { query: 'is:important' });
106 + * execute: async (input, ctx) => {
107 + * const result = await ctx.execute('GMAIL_SEARCH', { query: 'is:important' });
108 * return { emails: result.data };
109 * },
110 * });
@@ -103,6 +131,9 @@ export function createCustomTool<T extends z.ZodType>(
131 throw new ValidationError('createCustomTool: execute must be a function');
132 }
133
134 + // Early length validation (standalone or extension — we know both parts)
135 + validateSlugLength(slug, validated.extendsToolkit, 'createCustomTool');
136 +
137 const { inputParams, execute } = options;
138
139 // Convert Zod input schema → JSON Schema
@@ -146,10 +177,9 @@ export function createCustomTool<T extends z.ZodType>(
177 /**
178 * Create a custom toolkit that groups related tools.
179 *
149 - * Tools in a toolkit get prefixed as `LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>`.
180 * Tools passed here must NOT have `extendsToolkit` set — they inherit the toolkit identity instead.
181 *
152 - * @param slug - Unique toolkit identifier (alphanumeric, underscores, hyphens; no LOCAL_ prefix)
182 + * @param slug - Unique toolkit identifier (alphanumeric, underscores, hyphens; no LOCAL_ or COMPOSIO_ prefix)
183 * @param options - Toolkit definition including name, description, and tools
184 * @returns A CustomToolkit to pass to session creation
185 *
@@ -180,14 +210,17 @@ export function createCustomToolkit(
210 throw new ValidationError('createCustomToolkit: at least one tool is required');
211 }
212
183 - // Reject tools with extendsToolkit
213 + // Validate each tool
214 for (const tool of options.tools) {
215 + // Reject tools with extendsToolkit
216 if (tool.extendsToolkit) {
217 throw new ValidationError(
218 `createCustomToolkit: tool "${tool.slug}" has extendsToolkit set. ` +
219 `Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`
220 );
221 }
222 + // Early length validation — we know both toolkit slug and tool slug
223 + validateSlugLength(tool.slug, slug, `createCustomToolkit("${slug}")`);
224 }
225
226 return {
@@ -198,84 +231,82 @@ export function createCustomToolkit(
231 };
232 }
233
234 +/**
235 + * Build the final slug for a custom tool given its context.
236 + * @internal
237 + */
238 +function buildFinalSlug(toolSlug: string, toolkitSlug?: string): string {
239 + const upper = toolSlug.toUpperCase();
240 + return toolkitSlug
241 + ? `${LOCAL_TOOL_PREFIX}${toolkitSlug.toUpperCase()}_${upper}`
242 + : `${LOCAL_TOOL_PREFIX}${upper}`;
243 +}
244 +
245 /**
246 * Build a CustomToolsMap from custom tools and toolkits.
247 * Used internally by ToolRouter.create() to construct the per-session routing map.
248 *
205 - * Prefix rules:
206 - * - Standalone (no extendsToolkit): `LOCAL_<SLUG>`
207 - * - Extends toolkit: `LOCAL_<EXTENDS_TOOLKIT>_<SLUG>`
208 - * - Toolkit tool: `LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>`
209 - *
249 * @internal
250 * @param tools - Standalone custom tools
251 * @param toolkits - Custom toolkits containing grouped tools
213 - * @returns Maps for O(1) lookup by both prefixed and original slug
214 - * @throws If duplicate slugs, slug too long, or cross-group collisions
252 + * @returns Maps for O(1) lookup by both final and original slug
253 + * @throws If duplicate slugs or cross-group collisions
254 */
255 export function buildCustomToolsMap(
256 tools: CustomTool[],
257 toolkits?: CustomToolkit[]
258 ): CustomToolsMap {
220 - const byPrefixed = new Map<string, CustomToolsMapEntry>();
221 - const byOriginal = new Map<string, CustomToolsMapEntry>();
259 + const byFinalSlug = new Map<string, CustomToolsMapEntry>();
260 + const byOriginalSlug = new Map<string, CustomToolsMapEntry>();
261
223 - const addEntry = (handle: CustomTool, prefixedSlug: string) => {
262 + const addEntry = (handle: CustomTool, finalSlug: string, toolkit?: string) => {
263 const originalSlug = handle.slug.toUpperCase();
264
226 - // Validate final prefixed slug length
227 - if (prefixedSlug.length > MAX_PREFIXED_SLUG_LENGTH) {
228 - const prefix = prefixedSlug.substring(0, prefixedSlug.length - originalSlug.length);
229 - const available = MAX_PREFIXED_SLUG_LENGTH - prefix.length;
265 + // Length validated early in createCustomTool/createCustomToolkit, but check as safety net
266 + if (finalSlug.length > MAX_SLUG_LENGTH) {
267 throw new ValidationError(
231 - `Custom tool slug "${handle.slug}" is too long. ` +
232 - `With prefix "${prefix}", the final slug "${prefixedSlug}" exceeds ${MAX_PREFIXED_SLUG_LENGTH} characters. ` +
233 - `Shorten the slug to at most ${available} characters.`
268 + `Custom tool slug "${handle.slug}" produces final slug "${finalSlug}" ` +
269 + `which exceeds ${MAX_SLUG_LENGTH} characters.`
270 );
271 }
272
237 - // Check cross-group collisions on prefixed slug
238 - if (byPrefixed.has(prefixedSlug)) {
239 - throw new ValidationError(`Custom tool slug collision: "${prefixedSlug}" is already registered.`);
273 + // Check cross-group collisions on final slug
274 + if (byFinalSlug.has(finalSlug)) {
275 + throw new ValidationError(`Custom tool slug collision: "${finalSlug}" is already registered.`);
276 }
277
278 // Check cross-group collisions on original slug
243 - if (byOriginal.has(originalSlug)) {
279 + if (byOriginalSlug.has(originalSlug)) {
280 throw new ValidationError(
245 - `Custom tool slug collision: original slug "${handle.slug}" maps to multiple prefixed slugs. ` +
246 - `"${byOriginal.get(originalSlug)!.prefixedSlug}" and "${prefixedSlug}" both resolve from "${originalSlug}".`
281 + `Custom tool slug collision: original slug "${handle.slug}" maps to multiple final slugs. ` +
282 + `"${byOriginalSlug.get(originalSlug)!.finalSlug}" and "${finalSlug}" both resolve from "${originalSlug}".`
283 );
284 }
285
250 - const entry: CustomToolsMapEntry = { handle, prefixedSlug };
251 - byPrefixed.set(prefixedSlug, entry);
252 - byOriginal.set(originalSlug, entry);
286 + const entry: CustomToolsMapEntry = { handle, finalSlug, toolkit };
287 + byFinalSlug.set(finalSlug, entry);
288 + byOriginalSlug.set(originalSlug, entry);
289 };
290
291 // Process standalone tools
292 for (const handle of tools) {
257 - const upperSlug = handle.slug.toUpperCase();
258 - if (handle.extendsToolkit) {
259 - // LOCAL_<EXTENDS_TOOLKIT>_<SLUG>
260 - addEntry(handle, `LOCAL_${handle.extendsToolkit.toUpperCase()}_${upperSlug}`);
261 - } else {
262 - // LOCAL_<SLUG>
263 - addEntry(handle, `LOCAL_${upperSlug}`);
264 - }
293 + addEntry(
294 + handle,
295 + buildFinalSlug(handle.slug, handle.extendsToolkit),
296 + handle.extendsToolkit
297 + );
298 }
299
300 // Process toolkit tools
301 if (toolkits) {
302 for (const toolkit of toolkits) {
270 - const tkSlug = toolkit.slug.toUpperCase();
303 for (const handle of toolkit.tools) {
272 - // LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>
273 - addEntry(handle, `LOCAL_${tkSlug}_${handle.slug.toUpperCase()}`);
304 + addEntry(handle, buildFinalSlug(handle.slug, toolkit.slug), toolkit.slug);
305 }
306 }
307 }
308
278 - return { byPrefixed, byOriginal };
309 + return { byFinalSlug, byOriginalSlug, toolkits };
310 }
311
312 /**
ts/packages/core/src/models/ToolRouterSession.ts
+78 -24
@@ -25,7 +25,13 @@ import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
25 import { ValidationError } from '../errors';
26 import { Tools } from './Tools';
27 import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
28 -import type { CustomToolsMap, CustomToolsMapEntry, SessionContext } from '../types/customTool.types';
28 +import type {
29 + CustomToolsMap,
30 + CustomToolsMapEntry,
31 + SessionContext,
32 + RegisteredCustomTool,
33 + RegisteredCustomToolkit,
34 +} from '../types/customTool.types';
35 import type { ToolExecuteResponse } from '../types/tool.types';
36 import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
37 import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
@@ -44,6 +50,9 @@ export class ToolRouterSession<
50 public readonly mcp: ToolRouterMCPServerConfig;
51 public readonly experimental: SessionExperimental;
52
53 + /** Singleton session context — shared across all custom tool executions */
54 + private readonly sessionContext?: SessionContext;
55 +
56 constructor(
57 private readonly client: ComposioClient,
58 private readonly config: ComposioConfig<TProvider> | undefined,
@@ -62,6 +71,12 @@ export class ToolRouterSession<
71 assistivePrompt: experimentalOverrides?.assistivePrompt,
72 files: new ToolRouterSessionFilesMount(client, sessionId),
73 };
74 +
75 + // Create singleton session context if custom tools are bound
76 + if (customToolsMap && userId) {
77 + this.sessionContext = new SessionContextImpl(client, userId, sessionId, customToolsMap);
78 + }
79 +
80 telemetry.instrument(this, 'ToolRouterSession');
81 }
82
@@ -112,6 +127,60 @@ export class ToolRouterSession<
127 return wrappedTools as ReturnType<TProvider['wrapTools']>;
128 }
129
130 + /**
131 + * List all custom tools registered in this session.
132 + * Returns tools with their final slugs, schemas, and resolved toolkit.
133 + *
134 + * @param options.toolkit - Filter by toolkit slug (e.g. 'gmail', 'DEV_TOOLS')
135 + * @returns Array of registered custom tools
136 + */
137 + customTools(options?: { toolkit?: string }): RegisteredCustomTool[] {
138 + if (!this.customToolsMap) return [];
139 +
140 + const entries = Array.from(this.customToolsMap.byFinalSlug.values());
141 + const filtered = options?.toolkit
142 + ? entries.filter(e => e.toolkit?.toLowerCase() === options.toolkit!.toLowerCase())
143 + : entries;
144 +
145 + return filtered.map(entry => ({
146 + slug: entry.finalSlug,
147 + name: entry.handle.name,
148 + description: entry.handle.description,
149 + toolkit: entry.toolkit,
150 + inputSchema: entry.handle.inputSchema,
151 + outputSchema: entry.handle.outputSchema,
152 + }));
153 + }
154 +
155 + /**
156 + * List all custom toolkits registered in this session.
157 + * Returns toolkits with their tools showing final slugs.
158 + *
159 + * @returns Array of registered custom toolkits
160 + */
161 + customToolkits(): RegisteredCustomToolkit[] {
162 + const toolkits = this.customToolsMap?.toolkits;
163 + if (!toolkits?.length) return [];
164 +
165 + return toolkits.map(tk => ({
166 + slug: tk.slug,
167 + name: tk.name,
168 + description: tk.description,
169 + tools: tk.tools.map(tool => {
170 + // Look up the entry to get the final slug
171 + const entry = this.customToolsMap!.byOriginalSlug.get(tool.slug.toUpperCase());
172 + return {
173 + slug: entry?.finalSlug ?? tool.slug,
174 + name: tool.name,
175 + description: tool.description,
176 + toolkit: tk.slug,
177 + inputSchema: tool.inputSchema,
178 + outputSchema: tool.outputSchema,
179 + };
180 + }),
181 + }));
182 + }
183 +
184 /**
185 * Initiate an authorization flow for a toolkit.
186 * Returns a ConnectionRequest with a redirect URL for the user.
@@ -204,9 +273,9 @@ export class ToolRouterSession<
273 /**
274 * Execute a tool within the session.
275 *
207 - * For custom tools, accepts both the original slug (e.g. "GET_USER_CONTEXT")
208 - * and the prefixed slug (e.g. "LOCAL_GET_USER_CONTEXT"). Custom tools are executed
209 - * in-process; remote tools are sent to the Composio backend.
276 + * For custom tools, accepts the original slug (e.g. "GREP") or the
277 + * full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;
278 + * remote tools are sent to the Composio backend.
279 *
280 * @param toolSlug - The tool slug to execute
281 * @param arguments_ - Optional tool arguments
@@ -216,10 +285,10 @@ export class ToolRouterSession<
285 toolSlug: string,
286 arguments_?: Record<string, unknown>
287 ): Promise<ToolRouterSessionExecuteResponse> {
219 - // Check if this is a local tool (by original or prefixed slug)
288 + // Check if this is a local tool (by original or final slug)
289 const entry = findCustomTool(this.customToolsMap, toolSlug);
290 if (entry) {
222 - const result = await executeCustomTool(entry, arguments_ ?? {}, this.buildSessionContext());
291 + const result = await executeCustomTool(entry, arguments_ ?? {}, this.sessionContext!);
292 return {
293 data: result.data,
294 error: result.error,
@@ -268,20 +337,7 @@ export class ToolRouterSession<
337
338 /** Check if this session has any custom tools bound. */
339 private hasCustomTools(): boolean {
271 - return (this.customToolsMap?.byPrefixed.size ?? 0) > 0;
272 - }
273 -
274 - /**
275 - * Build a SessionContext for local tool execution.
276 - * The context holds the custom tools map and routes sibling calls in-process.
277 - */
278 - private buildSessionContext(): SessionContext {
279 - return new SessionContextImpl(
280 - this.client,
281 - this.userId!,
282 - this.sessionId,
283 - this.customToolsMap
284 - );
340 + return (this.customToolsMap?.byFinalSlug.size ?? 0) > 0;
341 }
342
343 /** Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array */
@@ -339,8 +395,8 @@ export class ToolRouterSession<
395 );
396 }
397
342 - // Execute local tools in parallel (shared context for the entire batch)
343 - const ctx = this.buildSessionContext();
398 + // Execute local tools in parallel (shared singleton context)
399 + const ctx = this.sessionContext!;
400 const localPromises = localItems.map(async ({ index, entry }) => {
401 const result = await executeCustomTool(entry, parsed[index].arguments, ctx);
402 return { index, result };
@@ -369,8 +425,6 @@ export class ToolRouterSession<
425 }
426
427 // Merge results into the backend's results[] format.
372 - // Backend returns: { results: [{ response, tool_slug, index }], total_count, ... }
373 - // We append local tool results in the same shape.
428 const remoteData = (remoteResult?.data ?? {}) as Record<string, unknown>;
429 const remoteResults = (Array.isArray(remoteData.results) ? remoteData.results : []) as unknown[];
430
ts/packages/core/src/models/customToolExecution.ts
+2 -2
@@ -7,7 +7,7 @@ import type { ToolExecuteResponse } from '../types/tool.types';
7
8 /**
9 * Find a custom tool entry by slug.
10 - * Checks both the prefixed map (LOCAL_X — agent path) and original map (X — programmatic path).
10 + * Checks both the final slug map (LOCAL_X — agent/LLM path) and original slug map (X — programmatic path).
11 */
12 export function findCustomTool(
13 map: CustomToolsMap | undefined,
@@ -15,7 +15,7 @@ export function findCustomTool(
15 ): CustomToolsMapEntry | undefined {
16 if (!map) return undefined;
17 const upper = slug.toUpperCase();
18 - return map.byPrefixed.get(upper) ?? map.byOriginal.get(upper);
18 + return map.byFinalSlug.get(upper) ?? map.byOriginalSlug.get(upper);
19 }
20
21 /**
ts/packages/core/src/types/customTool.types.ts
+46 -11
@@ -85,17 +85,17 @@ export interface SessionContext {
85 *
86 * Supports two call patterns:
87 * - `(input) => data` — for tools that don't need session context
88 - * - `(input, session) => data` — for tools that need to call other tools or proxy APIs
88 + * - `(input, ctx) => data` — for tools that need to call other tools or proxy APIs
89 */
90 export type CustomToolExecuteFn<T extends z.ZodType> = (
91 input: z.infer<T>,
92 - session: SessionContext
92 + ctx: SessionContext
93 ) => Promise<Record<string, unknown>>;
94
95 /**
96 * Zod schema for validating a custom tool slug.
97 - * Alphanumeric, underscores, and hyphens only. No `LOCAL_` prefix.
98 - * Length is validated later in `buildCustomToolsMap` with contextual error.
97 + * Alphanumeric, underscores, and hyphens only. No `LOCAL_` or `COMPOSIO_` prefix.
98 + * Length is validated contextually (standalone vs extension vs toolkit) at creation time.
99 */
100 export const CustomToolSlugSchema = z
101 .string()
@@ -107,6 +107,10 @@ export const CustomToolSlugSchema = z
107 .refine(s => !s.toUpperCase().startsWith('LOCAL_'), {
108 message:
109 'slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',
110 + })
111 + .refine(s => !s.toUpperCase().startsWith('COMPOSIO_'), {
112 + message:
113 + 'slug must not start with "COMPOSIO_" — this prefix is reserved for Composio meta tools.',
114 });
115
116 /**
@@ -118,8 +122,9 @@ export const CreateCustomToolBaseSchema = z.object({
122 name: z.string().min(1, 'createCustomTool: name is required'),
123 description: z.string().min(1, 'createCustomTool: description is required'),
124 /**
121 - * Composio toolkit slug that this tool extends (requires an active connection for).
122 - * Set this to the toolkit whose auth your tool needs (e.g. `'meta_ads'`, `'gmail'`).
125 + * Composio toolkit slug that this tool extends (inherits auth from).
126 + * Must be a valid Composio toolkit slug (e.g. `'gmail'`, `'github'`, `'meta_ads'`).
127 + * The backend validates this against the toolkit catalog.
128 * Leave empty for tools that don't need any Composio-managed authentication.
129 */
130 extendsToolkit: z.string().optional(),
@@ -146,7 +151,8 @@ export interface CustomTool {
151 readonly name: string;
152 readonly description: string;
153 /**
149 - * Composio toolkit slug that this tool extends (requires an active connection for).
154 + * Composio toolkit slug that this tool extends (inherits auth from).
155 + * Must be a valid Composio toolkit slug. Validated by the backend.
156 * Undefined means the tool doesn't need any Composio-managed authentication.
157 */
158 readonly extendsToolkit?: string;
@@ -216,13 +222,42 @@ export interface CustomToolkitDefinition {
222 /** @internal Entry in the per-session custom tools routing map. */
223 export type CustomToolsMapEntry = {
224 handle: CustomTool;
219 - prefixedSlug: string;
225 + /** @internal The final slug assigned by the prefixing rules (e.g. LOCAL_GREP, LOCAL_GMAIL_GET_EMAILS) */
226 + finalSlug: string;
227 + /** Resolved toolkit — from extendsToolkit, parent custom toolkit, or undefined for standalone */
228 + toolkit?: string;
229 };
230
231 /** @internal Lookup maps used by ToolRouterSession for routing custom tools. */
232 export type CustomToolsMap = {
224 - /** Lookup by prefixed slug (e.g. LOCAL_GET_USER_CONTEXT) — used for agent execution path */
225 - byPrefixed: Map<string, CustomToolsMapEntry>;
233 + /** Lookup by final slug (e.g. LOCAL_GET_USER_CONTEXT) — used for agent execution path */
234 + byFinalSlug: Map<string, CustomToolsMapEntry>;
235 /** Lookup by original slug (e.g. GET_USER_CONTEXT) — used for programmatic session.execute() */
227 - byOriginal: Map<string, CustomToolsMapEntry>;
236 + byOriginalSlug: Map<string, CustomToolsMapEntry>;
237 + /** The original custom toolkits passed at session creation — used for session.customToolkits() */
238 + toolkits?: CustomToolkit[];
239 };
240 +
241 +// ────────────────────────────────────────────────────────────────
242 +// Registered custom tool types (returned by session.customTools())
243 +// ────────────────────────────────────────────────────────────────
244 +
245 +/** A custom tool as registered in a session, with its final resolved slug. */
246 +export interface RegisteredCustomTool {
247 + /** The final slug as registered with the backend (e.g. LOCAL_GREP, LOCAL_GMAIL_GET_EMAILS) */
248 + slug: string;
249 + name: string;
250 + description: string;
251 + /** Resolved toolkit — extendsToolkit value, custom toolkit slug, or undefined for standalone */
252 + toolkit?: string;
253 + inputSchema: Record<string, unknown>;
254 + outputSchema?: Record<string, unknown>;
255 +}
256 +
257 +/** A custom toolkit as registered in a session, with final slugs on nested tools. */
258 +export interface RegisteredCustomToolkit {
259 + slug: string;
260 + name: string;
261 + description: string;
262 + tools: RegisteredCustomTool[];
263 +}
ts/packages/core/src/types/toolRouter.types.ts
+5 -1
@@ -3,7 +3,7 @@ import type { BaseComposioProvider } from '../provider/BaseProvider';
3 import { SessionMetaToolOptions } from './modifiers.types';
4 import { ConnectionRequest } from './connectionRequest.types';
5 import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';
6 -import type { CustomTool, CustomToolkit } from './customTool.types';
6 +import type { CustomTool, CustomToolkit, RegisteredCustomTool, RegisteredCustomToolkit } from './customTool.types';
7
8 export const MCPServerTypeSchema = z.enum(['http', 'sse']);
9 export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
@@ -474,6 +474,10 @@ export interface Session<
474 execute: ToolRouterSessionExecuteFn;
475 /** Proxy an API call through Composio's auth layer using the session's connected account */
476 proxyExecute: ToolRouterSessionProxyExecuteFn;
477 + /** List custom tools registered in this session, with their final slugs and schemas */
478 + customTools: (options?: { toolkit?: string }) => RegisteredCustomTool[];
479 + /** List custom toolkits registered in this session, with final slugs on nested tools */
480 + customToolkits: () => RegisteredCustomToolkit[];
481 /** Experimental features (files, assistive prompt, etc.) */
482 experimental: SessionExperimental;
483 }
ts/packages/core/test/models/customTool.test.ts
+34 -22
@@ -290,15 +290,15 @@ describe('buildCustomToolsMap', () => {
290 it('should prefix as LOCAL_<SLUG>', () => {
291 const map = buildCustomToolsMap([makeTool('MY_TOOL')]);
292
293 - expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
294 - expect(map.byOriginal.has('MY_TOOL')).toBe(true);
293 + expect(map.byFinalSlug.has('LOCAL_MY_TOOL')).toBe(true);
294 + expect(map.byOriginalSlug.has('MY_TOOL')).toBe(true);
295 });
296
297 it('should handle case-insensitive slugs (uppercased internally)', () => {
298 const map = buildCustomToolsMap([makeTool('my_tool')]);
299
300 - expect(map.byOriginal.has('MY_TOOL')).toBe(true);
301 - expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
300 + expect(map.byOriginalSlug.has('MY_TOOL')).toBe(true);
301 + expect(map.byFinalSlug.has('LOCAL_MY_TOOL')).toBe(true);
302 });
303 });
304
@@ -306,8 +306,8 @@ describe('buildCustomToolsMap', () => {
306 it('should prefix as LOCAL_<EXTENDS_TOOLKIT>_<SLUG>', () => {
307 const map = buildCustomToolsMap([makeTool('GET_EMAILS', 'gmail')]);
308
309 - expect(map.byPrefixed.has('LOCAL_GMAIL_GET_EMAILS')).toBe(true);
310 - expect(map.byOriginal.has('GET_EMAILS')).toBe(true);
309 + expect(map.byFinalSlug.has('LOCAL_GMAIL_GET_EMAILS')).toBe(true);
310 + expect(map.byOriginalSlug.has('GET_EMAILS')).toBe(true);
311 });
312 });
313
@@ -323,8 +323,8 @@ describe('buildCustomToolsMap', () => {
323
324 const map = buildCustomToolsMap([], [tk]);
325
326 - expect(map.byPrefixed.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
327 - expect(map.byOriginal.has('SED')).toBe(true);
326 + expect(map.byFinalSlug.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
327 + expect(map.byOriginalSlug.has('SED')).toBe(true);
328 });
329 });
330
@@ -341,9 +341,9 @@ describe('buildCustomToolsMap', () => {
341
342 const map = buildCustomToolsMap([grep], [tk]);
343
344 - expect(map.byPrefixed.size).toBe(2);
345 - expect(map.byPrefixed.has('LOCAL_GREP')).toBe(true);
346 - expect(map.byPrefixed.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
344 + expect(map.byFinalSlug.size).toBe(2);
345 + expect(map.byFinalSlug.has('LOCAL_GREP')).toBe(true);
346 + expect(map.byFinalSlug.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
347 });
348 });
349
@@ -369,27 +369,39 @@ describe('buildCustomToolsMap', () => {
369 });
370
371 describe('length validation', () => {
372 - it('should throw when prefixed slug exceeds 60 characters with contextual error', () => {
372 + it('should throw early in createCustomTool when slug is too long (standalone)', () => {
373 const longSlug = 'A'.repeat(56); // LOCAL_ + 56 = 62 > 60
374 - expect(() => buildCustomToolsMap([makeTool(longSlug)])).toThrow('too long');
374 + expect(() => createCustomTool(longSlug, {
375 + name: 'Long', description: 'Too long', inputParams: z.object({}), execute: vi.fn().mockResolvedValue({}),
376 + })).toThrow('too long');
377 });
378
377 - it('should show available length in error for toolkit tools', () => {
379 + it('should throw early in createCustomTool when slug is too long (extension)', () => {
380 + // LOCAL_GMAIL_ = 12 chars, so slug > 48 chars overflows
381 + const longSlug = 'A'.repeat(49);
382 + expect(() => createCustomTool(longSlug, {
383 + name: 'Long', description: 'Too long', extendsToolkit: 'gmail',
384 + inputParams: z.object({}), execute: vi.fn().mockResolvedValue({}),
385 + })).toThrow('too long');
386 + });
387 +
388 + it('should throw early in createCustomToolkit when tool slug is too long', () => {
389 const longSlug = 'A'.repeat(50); // LOCAL_DEV_TOOLS_ + 50 = 66 > 60
379 - const tk: CustomToolkit = {
380 - slug: 'DEV_TOOLS',
381 - name: 'Dev Tools',
382 - description: 'Utilities',
383 - tools: [makeTool(longSlug)],
384 - };
390 + const tool = makeTool(longSlug);
391 + expect(() => createCustomToolkit('DEV_TOOLS', {
392 + name: 'Dev Tools', description: 'Utilities', tools: [tool],
393 + })).toThrow('too long');
394 + });
395
386 - expect(() => buildCustomToolsMap([], [tk])).toThrow(/Shorten the slug to at most/);
396 + it('should still validate in buildCustomToolsMap as safety net', () => {
397 + const longSlug = 'A'.repeat(56);
398 + expect(() => buildCustomToolsMap([makeTool(longSlug)])).toThrow('exceeds');
399 });
400
401 it('should accept slugs that fit within 60 chars', () => {
402 const slug = 'A'.repeat(54); // LOCAL_ + 54 = 60 exactly
403 const map = buildCustomToolsMap([makeTool(slug)]);
392 - expect(map.byPrefixed.size).toBe(1);
404 + expect(map.byFinalSlug.size).toBe(1);
405 });
406 });
407 });
ts/packages/core/test/models/customToolRouting.test.ts
+6 -6
@@ -72,8 +72,8 @@ const customToolHandle = createCustomTool('GET_USER_CONTEXT', {
72 execute: localExecute,
73 });
74
75 -const sessionExecute = vi.fn().mockImplementation(async (input: any, session: any) => ({
76 - userId: session.userId,
75 +const sessionExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => ({
76 + userId: ctx.userId,
77 }));
78
79 const sessionToolHandle = createCustomTool('GET_AD_ACCOUNTS', {
@@ -291,8 +291,8 @@ describe('ToolRouterSession execution routing', () => {
291 });
292
293 it('should provide a working execute() on SessionContext for remote tools', async () => {
294 - const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
295 - const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });
294 + const chainedExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => {
295 + const inner = await ctx.execute('GMAIL_SEND_EMAIL', { to: input.to });
296 return { inner_result: inner.data };
297 });
298
@@ -321,8 +321,8 @@ describe('ToolRouterSession execution routing', () => {
321 execute: siblingExecute,
322 });
323
324 - const toolAExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
325 - const inner = await session.execute('TOOL_B', { key: input.value });
324 + const toolAExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => {
325 + const inner = await ctx.execute('TOOL_B', { key: input.value });
326 return { fromA: true, fromB: inner.data };
327 });
328 const toolA = createCustomTool('TOOL_A', {