Skip to content

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

Dhawal Upadhyayba97624843dc
diff --git a/ts/docs/api/tool-router.md b/ts/docs/api/tool-router.md
index ac9cbbb54..5c78a2887 100644
--- a/ts/docs/api/tool-router.md
+++ b/ts/docs/api/tool-router.md
@@ -293,8 +293,8 @@ const getImportant = experimental_createTool('GET_IMPORTANT_EMAILS', {
description: 'Fetch high-priority emails',
extendsToolkit: 'gmail',
inputParams: z.object({ limit: z.number().default(10) }),
- execute: async (input, session) => {
- const result = await session.execute('GMAIL_SEARCH', { query: 'is:important' });
+ execute: async (input, ctx) => {
+ const result = await ctx.execute('GMAIL_SEARCH', { query: 'is:important' });
return { emails: result.data };
},
});
diff --git a/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs b/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs
index 646507be4..d006e9c10 100644
--- a/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs
+++ b/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs
@@ -34,10 +34,10 @@ const enrichedSearch = createCustomTool('ENRICHED_SEARCH', {
inputParams: z.object({
query: z.string(),
}),
- execute: async (input, session) => {
+ execute: async (input, ctx) => {
return {
query: input.query,
- userId: session.userId,
+ userId: ctx.userId,
};
},
});
@@ -70,14 +70,14 @@ const weatherChain = createCustomTool('WEATHER_CHAIN', {
inputParams: z.object({
city: z.string(),
}),
- execute: async (input, session) => {
+ execute: async (input, ctx) => {
// Call remote WEATHERMAP_WEATHER tool through SessionContext
- const weather = await session.execute('WEATHERMAP_WEATHER', {
+ const weather = await ctx.execute('WEATHERMAP_WEATHER', {
location: input.city,
});
return {
city: input.city,
- userId: session.userId,
+ userId: ctx.userId,
weatherData: weather.data,
weatherError: weather.error,
};
diff --git a/ts/examples/tool-router/src/custom-tools-agent.ts b/ts/examples/tool-router/src/custom-tools-agent.ts
index 0b85ab8d2..9149add75 100644
--- a/ts/examples/tool-router/src/custom-tools-agent.ts
+++ b/ts/examples/tool-router/src/custom-tools-agent.ts
@@ -99,7 +99,7 @@ const formatGmailEmail = experimental_createTool("FORMAT_GMAIL_EMAIL", {
subject: z.string().describe("Email subject line"),
body: z.string().describe("Email body content in markdown"),
}),
- execute: async (input, session) => {
+ execute: async (input, ctx) => {
const htmlBody = input.body
.replace(/\*\*(.*?)\*\*/g, "<b>$1</b>")
.replace(/\*(.*?)\*/g, "<i>$1</i>")
@@ -110,7 +110,7 @@ const formatGmailEmail = experimental_createTool("FORMAT_GMAIL_EMAIL", {
subject: input.subject,
html_body: htmlBody,
plain_body: input.body,
- user_id: session.userId,
+ user_id: ctx.userId,
};
},
});
diff --git a/ts/examples/tool-router/src/custom-tools-e2e.ts b/ts/examples/tool-router/src/custom-tools-e2e.ts
new file mode 100644
index 000000000..831761e50
--- /dev/null
+++ b/ts/examples/tool-router/src/custom-tools-e2e.ts
@@ -0,0 +1,357 @@
+/**
+ * Focused E2E test: Custom tools + custom toolkits against live backend.
+ *
+ * Tests session creation, local execution, search indexing, and all three
+ * tool types (standalone, extendsToolkit, custom toolkit).
+ *
+ * Usage:
+ * COMPOSIO_API_KEY=... COMPOSIO_BASE_URL=... bun src/custom-tools-e2e.ts
+ */
+import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
+import { z } from "zod/v3";
+
+const apiKey = process.env.COMPOSIO_API_KEY;
+const baseURL = process.env.COMPOSIO_BASE_URL;
+if (!apiKey) {
+ console.error("COMPOSIO_API_KEY is required");
+ process.exit(1);
+}
+
+let passed = 0;
+let failed = 0;
+
+function ok(label: string) {
+ passed++;
+ console.log(` ✓ ${label}`);
+}
+function fail(label: string, err: unknown) {
+ failed++;
+ console.error(` ✗ ${label}: ${err instanceof Error ? err.message : err}`);
+}
+
+// ── Shared in-memory user store ──────────────────────────────────
+
+const userStore: Record<string, Record<string, unknown>> = {
+ "user-1": { id: "user-1", name: "Alice Johnson", email: "[email protected]", role: "admin", status: "active" },
+ "user-2": { id: "user-2", name: "Bob Smith", email: "[email protected]", role: "developer", status: "active" },
+ "user-3": { id: "user-3", name: "Carol Williams", email: "[email protected]", role: "viewer", status: "suspended" },
+};
+
+// ────────────────────────────────────────────────────────────────
+// 1. Standalone tools (no auth) → LOCAL_<SLUG>
+// ────────────────────────────────────────────────────────────────
+
+const getUserDetails = experimental_createTool("GET_USER_DETAILS", {
+ name: "Get user details",
+ description: "Retrieve user profile information including name, email, role, and account status by user ID",
+ inputParams: z.object({
+ user_id: z.string().describe("The unique user identifier"),
+ }),
+ execute: async (input) => {
+ const user = userStore[input.user_id];
+ if (!user) throw new Error(`User "${input.user_id}" not found`);
+ return { ...user };
+ },
+});
+
+const listUserKeys = experimental_createTool("LIST_USER_KEYS", {
+ name: "List user API keys",
+ description: "List all active API keys for a given user, including creation date and last used timestamp",
+ inputParams: z.object({
+ user_id: z.string().describe("The user whose keys to list"),
+ include_expired: z.boolean().default(false),
+ }),
+ execute: async (input) => {
+ const keys = [
+ { key_id: "key_abc", prefix: "sk-***abc", expired: false },
+ { key_id: "key_old", prefix: "sk-***old", expired: true },
+ ];
+ const filtered = input.include_expired ? keys : keys.filter((k) => !k.expired);
+ return { user_id: input.user_id, api_keys: filtered, total: filtered.length };
+ },
+});
+
+// ────────────────────────────────────────────────────────────────
+// 2. Extension tool (inherits gmail auth) → LOCAL_GMAIL_<SLUG>
+// ────────────────────────────────────────────────────────────────
+
+const formatGmailEmail = experimental_createTool("FORMAT_GMAIL_EMAIL", {
+ name: "Format Gmail email",
+ description: "Format and prepare an email draft with proper HTML formatting for sending via Gmail",
+ extendsToolkit: "gmail",
+ inputParams: z.object({
+ to: z.string().describe("Recipient email address"),
+ subject: z.string().describe("Email subject line"),
+ body: z.string().describe("Email body content"),
+ }),
+ execute: async (input, ctx) => {
+ const htmlBody = input.body.replace(/\n/g, "<br>");
+ return {
+ formatted: true,
+ to: input.to,
+ subject: input.subject,
+ html_body: htmlBody,
+ user_id: ctx.userId,
+ };
+ },
+});
+
+// ────────────────────────────────────────────────────────────────
+// 3. Custom toolkit (USER_MANAGEMENT) → LOCAL_USER_MANAGEMENT_<SLUG>
+// ────────────────────────────────────────────────────────────────
+
+const setUserRole = experimental_createTool("SET_USER_ROLE", {
+ name: "Set user role",
+ description: "Change the role of an existing user (admin, developer, viewer)",
+ inputParams: z.object({
+ user_id: z.string().describe("The user to update"),
+ role: z.enum(["admin", "developer", "viewer"]).describe("The new role to assign"),
+ }),
+ execute: async (input) => {
+ const user = userStore[input.user_id];
+ if (!user) throw new Error(`User "${input.user_id}" not found`);
+ const previousRole = user.role;
+ user.role = input.role;
+ return { user_id: input.user_id, previous_role: previousRole, new_role: input.role };
+ },
+});
+
+const updateUserStatus = experimental_createTool("UPDATE_USER_STATUS", {
+ name: "Update user status",
+ description: "Activate or suspend a user account",
+ inputParams: z.object({
+ user_id: z.string().describe("The user to update"),
+ status: z.enum(["active", "suspended"]).describe("The new account status"),
+ reason: z.string().optional().describe("Reason for the status change"),
+ }),
+ execute: async (input) => {
+ const user = userStore[input.user_id];
+ if (!user) throw new Error(`User "${input.user_id}" not found`);
+ const previousStatus = user.status;
+ user.status = input.status;
+ return { user_id: input.user_id, previous_status: previousStatus, new_status: input.status, reason: input.reason ?? "No reason provided" };
+ },
+});
+
+const userManagement = experimental_createToolkit("USER_MANAGEMENT", {
+ name: "User Management",
+ description: "Tools for managing user profiles, roles, and account status",
+ tools: [setUserRole, updateUserStatus],
+});
+
+// ────────────────────────────────────────────────────────────────
+// Run tests
+// ────────────────────────────────────────────────────────────────
+
+const composio = new Composio({ apiKey, baseURL: baseURL ?? undefined });
+
+async function main() {
+ const userId = `e2e-custom-${Date.now()}`;
+ console.log(`\nCreating session for user: ${userId}`);
+ console.log(`Base URL: ${baseURL ?? "(default)"}\n`);
+
+ // ── Session creation with all 3 tool types ──
+ let session: Awaited<ReturnType<typeof composio.create>>;
+ try {
+ session = await composio.create(userId, {
+ toolkits: ["weathermap", "gmail"],
+ manageConnections: false,
+ experimental: {
+ customTools: [getUserDetails, listUserKeys, formatGmailEmail],
+ customToolkits: [userManagement],
+ },
+ });
+ ok(`Session created: ${session.sessionId}`);
+ } catch (err) {
+ fail("Session creation", err);
+ console.error("\nCannot continue without a session.");
+ process.exit(1);
+ }
+
+ // ════════════════════════════════════════════════════════════════
+ // Standalone tools (LOCAL_GET_USER_DETAILS, LOCAL_LIST_USER_KEYS)
+ // ════════════════════════════════════════════════════════════════
+
+ try {
+ const result = await session.execute("GET_USER_DETAILS", { user_id: "user-1" });
+ if (result.data?.name !== "Alice Johnson") throw new Error(`Unexpected: ${JSON.stringify(result.data)}`);
+ ok("Standalone: execute by original slug (GET_USER_DETAILS)");
+ } catch (err) {
+ fail("Standalone: execute by original slug", err);
+ }
+
+ try {
+ const result = await session.execute("LOCAL_GET_USER_DETAILS", { user_id: "user-2" });
+ if (result.data?.name !== "Bob Smith") throw new Error(`Unexpected: ${JSON.stringify(result.data)}`);
+ ok("Standalone: execute by prefixed slug (LOCAL_GET_USER_DETAILS)");
+ } catch (err) {
+ fail("Standalone: execute by prefixed slug", err);
+ }
+
+ try {
+ const result = await session.execute("LIST_USER_KEYS", { user_id: "user-1" });
+ if (result.data?.total !== 1) throw new Error(`Expected 1 active key, got: ${JSON.stringify(result.data)}`);
+ ok("Standalone: second tool routes correctly (LIST_USER_KEYS)");
+ } catch (err) {
+ fail("Standalone: second tool routes correctly", err);
+ }
+
+ try {
+ const result = await session.execute("LIST_USER_KEYS", { user_id: "user-1", include_expired: true });
+ if (result.data?.total !== 2) throw new Error(`Expected 2 keys with expired, got: ${JSON.stringify(result.data)}`);
+ ok("Standalone: Zod defaults overridden (include_expired=true → 2 keys)");
+ } catch (err) {
+ fail("Standalone: Zod defaults overridden", err);
+ }
+
+ // ════════════════════════════════════════════════════════════════
+ // Extension tool (LOCAL_GMAIL_FORMAT_GMAIL_EMAIL)
+ // ════════════════════════════════════════════════════════════════
+
+ try {
+ const result = await session.execute("FORMAT_GMAIL_EMAIL", {
+ subject: "Hello",
+ body: "Line 1\nLine 2",
+ });
+ if (result.error) throw new Error(`Execute error: ${result.error}`);
+ if (result.data?.formatted !== true) throw new Error(`Not formatted: ${JSON.stringify(result.data)}`);
+ if (result.data?.html_body !== "Line 1<br>Line 2") throw new Error(`HTML mismatch: ${result.data?.html_body}`);
+ if (result.data?.user_id !== userId) throw new Error(`UserId mismatch: ${result.data?.user_id}`);
+ ok("Extension: execute by original slug (FORMAT_GMAIL_EMAIL) + session context");
+ } catch (err) {
+ fail("Extension: execute by original slug", err);
+ }
+
+ try {
+ const result = await session.execute("LOCAL_GMAIL_FORMAT_GMAIL_EMAIL", {
+ subject: "Test",
+ body: "body",
+ });
+ if (result.data?.to !== "[email protected]") throw new Error(`Unexpected: ${JSON.stringify(result.data)}`);
+ ok("Extension: execute by prefixed slug (LOCAL_GMAIL_FORMAT_GMAIL_EMAIL)");
+ } catch (err) {
+ fail("Extension: execute by prefixed slug", err);
+ }
+
+ // ════════════════════════════════════════════════════════════════
+ // Custom toolkit (LOCAL_USER_MANAGEMENT_SET_USER_ROLE, etc.)
+ // ════════════════════════════════════════════════════════════════
+
+ try {
+ const result = await session.execute("SET_USER_ROLE", { user_id: "user-3", role: "developer" });
+ if (result.data?.previous_role !== "viewer") throw new Error(`Previous role wrong: ${JSON.stringify(result.data)}`);
+ if (result.data?.new_role !== "developer") throw new Error(`New role wrong: ${JSON.stringify(result.data)}`);
+ ok("Toolkit: execute by original slug (SET_USER_ROLE)");
+ } catch (err) {
+ fail("Toolkit: execute by original slug", err);
+ }
+
+ try {
+ const result = await session.execute("LOCAL_USER_MANAGEMENT_SET_USER_ROLE", { user_id: "user-2", role: "admin" });
+ if (result.data?.new_role !== "admin") throw new Error(`Unexpected: ${JSON.stringify(result.data)}`);
+ ok("Toolkit: execute by prefixed slug (LOCAL_USER_MANAGEMENT_SET_USER_ROLE)");
+ } catch (err) {
+ fail("Toolkit: execute by prefixed slug", err);
+ }
+
+ try {
+ const result = await session.execute("UPDATE_USER_STATUS", { user_id: "user-3", status: "active", reason: "Suspended by mistake" });
+ if (result.data?.previous_status !== "suspended") throw new Error(`Previous status wrong: ${JSON.stringify(result.data)}`);
+ if (result.data?.new_status !== "active") throw new Error(`New status wrong: ${JSON.stringify(result.data)}`);
+ if (result.data?.reason !== "Suspended by mistake") throw new Error(`Reason wrong: ${JSON.stringify(result.data)}`);
+ ok("Toolkit: second tool + optional param (UPDATE_USER_STATUS with reason)");
+ } catch (err) {
+ fail("Toolkit: second tool + optional param", err);
+ }
+
+ try {
+ const result = await session.execute("LOCAL_USER_MANAGEMENT_UPDATE_USER_STATUS", { user_id: "user-1", status: "suspended" });
+ if (result.data?.reason !== "No reason provided") throw new Error(`Default reason not applied: ${JSON.stringify(result.data)}`);
+ ok("Toolkit: prefixed slug + optional param default (reason → 'No reason provided')");
+ } catch (err) {
+ fail("Toolkit: prefixed slug + optional param default", err);
+ }
+
+ // Verify state mutations persisted across calls
+ try {
+ const result = await session.execute("GET_USER_DETAILS", { user_id: "user-3" });
+ if (result.data?.role !== "developer") throw new Error(`Role not updated: ${JSON.stringify(result.data)}`);
+ if (result.data?.status !== "active") throw new Error(`Status not updated: ${JSON.stringify(result.data)}`);
+ ok("Toolkit: state mutations persisted (user-3 is now developer+active)");
+ } catch (err) {
+ fail("Toolkit: state mutations persisted", err);
+ }
+
+ // ════════════════════════════════════════════════════════════════
+ // Cross-cutting: case insensitive, error handling, search, remote
+ // ════════════════════════════════════════════════════════════════
+
+ try {
+ const result = await session.execute("get_user_details", { user_id: "user-1" });
+ if (!result.data?.name) throw new Error(`Unexpected: ${JSON.stringify(result.data)}`);
+ ok("Case-insensitive slug lookup (get_user_details → GET_USER_DETAILS)");
+ } catch (err) {
+ fail("Case-insensitive slug", err);
+ }
+
+ try {
+ const result = await session.execute("GET_USER_DETAILS", { user_id: "nonexistent" });
+ if (!result.error?.includes("not found")) throw new Error(`Expected 'not found' error, got: ${result.error}`);
+ ok("Error handling: thrown error wrapped in response");
+ } catch (err) {
+ fail("Error handling", err);
+ }
+
+ // Search — standalone tools
+ try {
+ const searchResult = await session.search({ query: "get user profile details" });
+ const toolSlugs = searchResult.results.flatMap((r) => r.primaryToolSlugs);
+ const found = toolSlugs.find((s) => s === "LOCAL_GET_USER_DETAILS");
+ if (!found) console.log(" (search returned:", toolSlugs.join(", "), ")");
+ ok(`Search: standalone tool found=${!!found} (${searchResult.results.length} results)`);
+ } catch (err) {
+ fail("Search: standalone tools", err);
+ }
+
+ // Search — toolkit tools
+ try {
+ const searchResult = await session.search({ query: "change user role to admin" });
+ const toolSlugs = searchResult.results.flatMap((r) => r.primaryToolSlugs);
+ const found = toolSlugs.find((s) => s.includes("USER_MANAGEMENT"));
+ if (!found) console.log(" (search returned:", toolSlugs.join(", "), ")");
+ ok(`Search: toolkit tool found=${!!found} (${searchResult.results.length} results)`);
+ } catch (err) {
+ fail("Search: toolkit tools", err);
+ }
+
+ // Search — extension tool
+ try {
+ const searchResult = await session.search({ query: "format email draft for gmail" });
+ const toolSlugs = searchResult.results.flatMap((r) => r.primaryToolSlugs);
+ const found = toolSlugs.find((s) => s.includes("GMAIL") && s.startsWith("LOCAL_"));
+ if (!found) console.log(" (search returned:", toolSlugs.join(", "), ")");
+ ok(`Search: extension tool found=${!!found} (${searchResult.results.length} results)`);
+ } catch (err) {
+ fail("Search: extension tool", err);
+ }
+
+ // Remote tool still works alongside custom tools
+ try {
+ const result = await session.execute("WEATHERMAP_WEATHER", { location: "Tokyo" });
+ if (result.error) throw new Error(`Remote error: ${result.error}`);
+ ok(`Remote tool execution (WEATHERMAP_WEATHER) — keys: ${Object.keys(result.data ?? {}).join(", ")}`);
+ } catch (err) {
+ fail("Remote tool execution", err);
+ }
+
+ // ── Summary ──
+ console.log(`\n${passed} passed, ${failed} failed out of ${passed + failed} tests`);
+ if (failed > 0) process.exit(1);
+}
+
+main().catch((err) => {
+ console.error("Fatal:", err);
+ process.exit(1);
+});
diff --git a/ts/packages/core/src/models/CustomTool.ts b/ts/packages/core/src/models/CustomTool.ts
index 329f57d4d..65ca2f8f7 100644
--- a/ts/packages/core/src/models/CustomTool.ts
+++ b/ts/packages/core/src/models/CustomTool.ts
@@ -42,7 +42,35 @@ import { ValidationError } from '../errors';
export const LOCAL_TOOL_PREFIX = 'LOCAL_';
/** Maximum allowed length for the final prefixed slug. */
-const MAX_PREFIXED_SLUG_LENGTH = 60;
+const MAX_SLUG_LENGTH = 60;
+
+/**
+ * Compute the final slug length for a tool given its context.
+ * Returns the expected length of LOCAL_[TOOLKIT_]SLUG.
+ */
+function computeFinalSlugLength(toolSlug: string, toolkitSlug?: string): number {
+ // LOCAL_ + optional TOOLKIT_ + SLUG
+ return LOCAL_TOOL_PREFIX.length
+ + (toolkitSlug ? toolkitSlug.length + 1 : 0) // +1 for underscore separator
+ + toolSlug.length;
+}
+
+/**
+ * Validate that the final slug won't exceed the max length.
+ * Called early in createCustomTool/createCustomToolkit for fast feedback.
+ */
+function validateSlugLength(toolSlug: string, toolkitSlug: string | undefined, context: string): void {
+ const finalLength = computeFinalSlugLength(toolSlug, toolkitSlug);
+ if (finalLength > MAX_SLUG_LENGTH) {
+ const prefix = LOCAL_TOOL_PREFIX + (toolkitSlug ? `${toolkitSlug.toUpperCase()}_` : '');
+ const available = MAX_SLUG_LENGTH - prefix.length;
+ throw new ValidationError(
+ `${context}: slug "${toolSlug}" is too long. ` +
+ `With prefix "${prefix}", the final slug would be ${finalLength} characters (max ${MAX_SLUG_LENGTH}). ` +
+ `Shorten the slug to at most ${available} characters.`
+ );
+ }
+}
/**
* Create a custom tool for use in tool router sessions.
@@ -54,7 +82,7 @@ const MAX_PREFIXED_SLUG_LENGTH = 60;
* Just return the result data from `execute`, or throw an error.
* The SDK wraps it into the standard response format internally.
*
- * @param slug - Unique tool identifier (alphanumeric, underscores, hyphens; no LOCAL_ prefix)
+ * @param slug - Unique tool identifier (alphanumeric, underscores, hyphens; no LOCAL_ or COMPOSIO_ prefix)
* @param options - Tool definition including name, schema, and execute function
* @returns A CustomTool to pass to session creation
*
@@ -75,8 +103,8 @@ const MAX_PREFIXED_SLUG_LENGTH = 60;
* description: 'Fetch high-priority emails',
* extendsToolkit: 'gmail',
* inputParams: z.object({ limit: z.number().default(10) }),
- * execute: async (input, session) => {
- * const result = await session.execute('GMAIL_SEARCH', { query: 'is:important' });
+ * execute: async (input, ctx) => {
+ * const result = await ctx.execute('GMAIL_SEARCH', { query: 'is:important' });
* return { emails: result.data };
* },
* });
@@ -103,6 +131,9 @@ export function createCustomTool<T extends z.ZodType>(
throw new ValidationError('createCustomTool: execute must be a function');
}
+ // Early length validation (standalone or extension — we know both parts)
+ validateSlugLength(slug, validated.extendsToolkit, 'createCustomTool');
+
const { inputParams, execute } = options;
// Convert Zod input schema → JSON Schema
@@ -146,10 +177,9 @@ export function createCustomTool<T extends z.ZodType>(
/**
* Create a custom toolkit that groups related tools.
*
- * Tools in a toolkit get prefixed as `LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>`.
* Tools passed here must NOT have `extendsToolkit` set — they inherit the toolkit identity instead.
*
- * @param slug - Unique toolkit identifier (alphanumeric, underscores, hyphens; no LOCAL_ prefix)
+ * @param slug - Unique toolkit identifier (alphanumeric, underscores, hyphens; no LOCAL_ or COMPOSIO_ prefix)
* @param options - Toolkit definition including name, description, and tools
* @returns A CustomToolkit to pass to session creation
*
@@ -180,14 +210,17 @@ export function createCustomToolkit(
throw new ValidationError('createCustomToolkit: at least one tool is required');
}
- // Reject tools with extendsToolkit
+ // Validate each tool
for (const tool of options.tools) {
+ // Reject tools with extendsToolkit
if (tool.extendsToolkit) {
throw new ValidationError(
`createCustomToolkit: tool "${tool.slug}" has extendsToolkit set. ` +
`Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`
);
}
+ // Early length validation — we know both toolkit slug and tool slug
+ validateSlugLength(tool.slug, slug, `createCustomToolkit("${slug}")`);
}
return {
@@ -198,84 +231,82 @@ export function createCustomToolkit(
};
}
+/**
+ * Build the final slug for a custom tool given its context.
+ * @internal
+ */
+function buildFinalSlug(toolSlug: string, toolkitSlug?: string): string {
+ const upper = toolSlug.toUpperCase();
+ return toolkitSlug
+ ? `${LOCAL_TOOL_PREFIX}${toolkitSlug.toUpperCase()}_${upper}`
+ : `${LOCAL_TOOL_PREFIX}${upper}`;
+}
+
/**
* Build a CustomToolsMap from custom tools and toolkits.
* Used internally by ToolRouter.create() to construct the per-session routing map.
*
- * Prefix rules:
- * - Standalone (no extendsToolkit): `LOCAL_<SLUG>`
- * - Extends toolkit: `LOCAL_<EXTENDS_TOOLKIT>_<SLUG>`
- * - Toolkit tool: `LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>`
- *
* @internal
* @param tools - Standalone custom tools
* @param toolkits - Custom toolkits containing grouped tools
- * @returns Maps for O(1) lookup by both prefixed and original slug
- * @throws If duplicate slugs, slug too long, or cross-group collisions
+ * @returns Maps for O(1) lookup by both final and original slug
+ * @throws If duplicate slugs or cross-group collisions
*/
export function buildCustomToolsMap(
tools: CustomTool[],
toolkits?: CustomToolkit[]
): CustomToolsMap {
- const byPrefixed = new Map<string, CustomToolsMapEntry>();
- const byOriginal = new Map<string, CustomToolsMapEntry>();
+ const byFinalSlug = new Map<string, CustomToolsMapEntry>();
+ const byOriginalSlug = new Map<string, CustomToolsMapEntry>();
- const addEntry = (handle: CustomTool, prefixedSlug: string) => {
+ const addEntry = (handle: CustomTool, finalSlug: string, toolkit?: string) => {
const originalSlug = handle.slug.toUpperCase();
- // Validate final prefixed slug length
- if (prefixedSlug.length > MAX_PREFIXED_SLUG_LENGTH) {
- const prefix = prefixedSlug.substring(0, prefixedSlug.length - originalSlug.length);
- const available = MAX_PREFIXED_SLUG_LENGTH - prefix.length;
+ // Length validated early in createCustomTool/createCustomToolkit, but check as safety net
+ if (finalSlug.length > MAX_SLUG_LENGTH) {
throw new ValidationError(
- `Custom tool slug "${handle.slug}" is too long. ` +
- `With prefix "${prefix}", the final slug "${prefixedSlug}" exceeds ${MAX_PREFIXED_SLUG_LENGTH} characters. ` +
- `Shorten the slug to at most ${available} characters.`
+ `Custom tool slug "${handle.slug}" produces final slug "${finalSlug}" ` +
+ `which exceeds ${MAX_SLUG_LENGTH} characters.`
);
}
- // Check cross-group collisions on prefixed slug
- if (byPrefixed.has(prefixedSlug)) {
- throw new ValidationError(`Custom tool slug collision: "${prefixedSlug}" is already registered.`);
+ // Check cross-group collisions on final slug
+ if (byFinalSlug.has(finalSlug)) {
+ throw new ValidationError(`Custom tool slug collision: "${finalSlug}" is already registered.`);
}
// Check cross-group collisions on original slug
- if (byOriginal.has(originalSlug)) {
+ if (byOriginalSlug.has(originalSlug)) {
throw new ValidationError(
- `Custom tool slug collision: original slug "${handle.slug}" maps to multiple prefixed slugs. ` +
- `"${byOriginal.get(originalSlug)!.prefixedSlug}" and "${prefixedSlug}" both resolve from "${originalSlug}".`
+ `Custom tool slug collision: original slug "${handle.slug}" maps to multiple final slugs. ` +
+ `"${byOriginalSlug.get(originalSlug)!.finalSlug}" and "${finalSlug}" both resolve from "${originalSlug}".`
);
}
- const entry: CustomToolsMapEntry = { handle, prefixedSlug };
- byPrefixed.set(prefixedSlug, entry);
- byOriginal.set(originalSlug, entry);
+ const entry: CustomToolsMapEntry = { handle, finalSlug, toolkit };
+ byFinalSlug.set(finalSlug, entry);
+ byOriginalSlug.set(originalSlug, entry);
};
// Process standalone tools
for (const handle of tools) {
- const upperSlug = handle.slug.toUpperCase();
- if (handle.extendsToolkit) {
- // LOCAL_<EXTENDS_TOOLKIT>_<SLUG>
- addEntry(handle, `LOCAL_${handle.extendsToolkit.toUpperCase()}_${upperSlug}`);
- } else {
- // LOCAL_<SLUG>
- addEntry(handle, `LOCAL_${upperSlug}`);
- }
+ addEntry(
+ handle,
+ buildFinalSlug(handle.slug, handle.extendsToolkit),
+ handle.extendsToolkit
+ );
}
// Process toolkit tools
if (toolkits) {
for (const toolkit of toolkits) {
- const tkSlug = toolkit.slug.toUpperCase();
for (const handle of toolkit.tools) {
- // LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>
- addEntry(handle, `LOCAL_${tkSlug}_${handle.slug.toUpperCase()}`);
+ addEntry(handle, buildFinalSlug(handle.slug, toolkit.slug), toolkit.slug);
}
}
}
- return { byPrefixed, byOriginal };
+ return { byFinalSlug, byOriginalSlug, toolkits };
}
/**
diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.ts
index c3c0cf2c9..527a32377 100644
--- a/ts/packages/core/src/models/ToolRouterSession.ts
+++ b/ts/packages/core/src/models/ToolRouterSession.ts
@@ -25,7 +25,13 @@ import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
import { ValidationError } from '../errors';
import { Tools } from './Tools';
import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
-import type { CustomToolsMap, CustomToolsMapEntry, SessionContext } from '../types/customTool.types';
+import type {
+ CustomToolsMap,
+ CustomToolsMapEntry,
+ SessionContext,
+ RegisteredCustomTool,
+ RegisteredCustomToolkit,
+} from '../types/customTool.types';
import type { ToolExecuteResponse } from '../types/tool.types';
import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
@@ -44,6 +50,9 @@ export class ToolRouterSession<
public readonly mcp: ToolRouterMCPServerConfig;
public readonly experimental: SessionExperimental;
+ /** Singleton session context — shared across all custom tool executions */
+ private readonly sessionContext?: SessionContext;
+
constructor(
private readonly client: ComposioClient,
private readonly config: ComposioConfig<TProvider> | undefined,
@@ -62,6 +71,12 @@ export class ToolRouterSession<
assistivePrompt: experimentalOverrides?.assistivePrompt,
files: new ToolRouterSessionFilesMount(client, sessionId),
};
+
+ // Create singleton session context if custom tools are bound
+ if (customToolsMap && userId) {
+ this.sessionContext = new SessionContextImpl(client, userId, sessionId, customToolsMap);
+ }
+
telemetry.instrument(this, 'ToolRouterSession');
}
@@ -112,6 +127,60 @@ export class ToolRouterSession<
return wrappedTools as ReturnType<TProvider['wrapTools']>;
}
+ /**
+ * List all custom tools registered in this session.
+ * Returns tools with their final slugs, schemas, and resolved toolkit.
+ *
+ * @param options.toolkit - Filter by toolkit slug (e.g. 'gmail', 'DEV_TOOLS')
+ * @returns Array of registered custom tools
+ */
+ customTools(options?: { toolkit?: string }): RegisteredCustomTool[] {
+ if (!this.customToolsMap) return [];
+
+ const entries = Array.from(this.customToolsMap.byFinalSlug.values());
+ const filtered = options?.toolkit
+ ? entries.filter(e => e.toolkit?.toLowerCase() === options.toolkit!.toLowerCase())
+ : entries;
+
+ return filtered.map(entry => ({
+ slug: entry.finalSlug,
+ name: entry.handle.name,
+ description: entry.handle.description,
+ toolkit: entry.toolkit,
+ inputSchema: entry.handle.inputSchema,
+ outputSchema: entry.handle.outputSchema,
+ }));
+ }
+
+ /**
+ * List all custom toolkits registered in this session.
+ * Returns toolkits with their tools showing final slugs.
+ *
+ * @returns Array of registered custom toolkits
+ */
+ customToolkits(): RegisteredCustomToolkit[] {
+ const toolkits = this.customToolsMap?.toolkits;
+ if (!toolkits?.length) return [];
+
+ return toolkits.map(tk => ({
+ slug: tk.slug,
+ name: tk.name,
+ description: tk.description,
+ tools: tk.tools.map(tool => {
+ // Look up the entry to get the final slug
+ const entry = this.customToolsMap!.byOriginalSlug.get(tool.slug.toUpperCase());
+ return {
+ slug: entry?.finalSlug ?? tool.slug,
+ name: tool.name,
+ description: tool.description,
+ toolkit: tk.slug,
+ inputSchema: tool.inputSchema,
+ outputSchema: tool.outputSchema,
+ };
+ }),
+ }));
+ }
+
/**
* Initiate an authorization flow for a toolkit.
* Returns a ConnectionRequest with a redirect URL for the user.
@@ -204,9 +273,9 @@ export class ToolRouterSession<
/**
* Execute a tool within the session.
*
- * For custom tools, accepts both the original slug (e.g. "GET_USER_CONTEXT")
- * and the prefixed slug (e.g. "LOCAL_GET_USER_CONTEXT"). Custom tools are executed
- * in-process; remote tools are sent to the Composio backend.
+ * For custom tools, accepts the original slug (e.g. "GREP") or the
+ * full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;
+ * remote tools are sent to the Composio backend.
*
* @param toolSlug - The tool slug to execute
* @param arguments_ - Optional tool arguments
@@ -216,10 +285,10 @@ export class ToolRouterSession<
toolSlug: string,
arguments_?: Record<string, unknown>
): Promise<ToolRouterSessionExecuteResponse> {
- // Check if this is a local tool (by original or prefixed slug)
+ // Check if this is a local tool (by original or final slug)
const entry = findCustomTool(this.customToolsMap, toolSlug);
if (entry) {
- const result = await executeCustomTool(entry, arguments_ ?? {}, this.buildSessionContext());
+ const result = await executeCustomTool(entry, arguments_ ?? {}, this.sessionContext!);
return {
data: result.data,
error: result.error,
@@ -268,20 +337,7 @@ export class ToolRouterSession<
/** Check if this session has any custom tools bound. */
private hasCustomTools(): boolean {
- return (this.customToolsMap?.byPrefixed.size ?? 0) > 0;
- }
-
- /**
- * Build a SessionContext for local tool execution.
- * The context holds the custom tools map and routes sibling calls in-process.
- */
- private buildSessionContext(): SessionContext {
- return new SessionContextImpl(
- this.client,
- this.userId!,
- this.sessionId,
- this.customToolsMap
- );
+ return (this.customToolsMap?.byFinalSlug.size ?? 0) > 0;
}
/** Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array */
@@ -339,8 +395,8 @@ export class ToolRouterSession<
);
}
- // Execute local tools in parallel (shared context for the entire batch)
- const ctx = this.buildSessionContext();
+ // Execute local tools in parallel (shared singleton context)
+ const ctx = this.sessionContext!;
const localPromises = localItems.map(async ({ index, entry }) => {
const result = await executeCustomTool(entry, parsed[index].arguments, ctx);
return { index, result };
@@ -369,8 +425,6 @@ export class ToolRouterSession<
}
// Merge results into the backend's results[] format.
- // Backend returns: { results: [{ response, tool_slug, index }], total_count, ... }
- // We append local tool results in the same shape.
const remoteData = (remoteResult?.data ?? {}) as Record<string, unknown>;
const remoteResults = (Array.isArray(remoteData.results) ? remoteData.results : []) as unknown[];
diff --git a/ts/packages/core/src/models/customToolExecution.ts b/ts/packages/core/src/models/customToolExecution.ts
index ea6a0764f..92eb256f4 100644
--- a/ts/packages/core/src/models/customToolExecution.ts
+++ b/ts/packages/core/src/models/customToolExecution.ts
@@ -7,7 +7,7 @@ import type { ToolExecuteResponse } from '../types/tool.types';
/**
* Find a custom tool entry by slug.
- * Checks both the prefixed map (LOCAL_X — agent path) and original map (X — programmatic path).
+ * Checks both the final slug map (LOCAL_X — agent/LLM path) and original slug map (X — programmatic path).
*/
export function findCustomTool(
map: CustomToolsMap | undefined,
@@ -15,7 +15,7 @@ export function findCustomTool(
): CustomToolsMapEntry | undefined {
if (!map) return undefined;
const upper = slug.toUpperCase();
- return map.byPrefixed.get(upper) ?? map.byOriginal.get(upper);
+ return map.byFinalSlug.get(upper) ?? map.byOriginalSlug.get(upper);
}
/**
diff --git a/ts/packages/core/src/types/customTool.types.ts b/ts/packages/core/src/types/customTool.types.ts
index abf362932..a56770abe 100644
--- a/ts/packages/core/src/types/customTool.types.ts
+++ b/ts/packages/core/src/types/customTool.types.ts
@@ -85,17 +85,17 @@ export interface SessionContext {
*
* Supports two call patterns:
* - `(input) => data` — for tools that don't need session context
- * - `(input, session) => data` — for tools that need to call other tools or proxy APIs
+ * - `(input, ctx) => data` — for tools that need to call other tools or proxy APIs
*/
export type CustomToolExecuteFn<T extends z.ZodType> = (
input: z.infer<T>,
- session: SessionContext
+ ctx: SessionContext
) => Promise<Record<string, unknown>>;
/**
* Zod schema for validating a custom tool slug.
- * Alphanumeric, underscores, and hyphens only. No `LOCAL_` prefix.
- * Length is validated later in `buildCustomToolsMap` with contextual error.
+ * Alphanumeric, underscores, and hyphens only. No `LOCAL_` or `COMPOSIO_` prefix.
+ * Length is validated contextually (standalone vs extension vs toolkit) at creation time.
*/
export const CustomToolSlugSchema = z
.string()
@@ -107,6 +107,10 @@ export const CustomToolSlugSchema = z
.refine(s => !s.toUpperCase().startsWith('LOCAL_'), {
message:
'slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',
+ })
+ .refine(s => !s.toUpperCase().startsWith('COMPOSIO_'), {
+ message:
+ 'slug must not start with "COMPOSIO_" — this prefix is reserved for Composio meta tools.',
});
/**
@@ -118,8 +122,9 @@ export const CreateCustomToolBaseSchema = z.object({
name: z.string().min(1, 'createCustomTool: name is required'),
description: z.string().min(1, 'createCustomTool: description is required'),
/**
- * Composio toolkit slug that this tool extends (requires an active connection for).
- * Set this to the toolkit whose auth your tool needs (e.g. `'meta_ads'`, `'gmail'`).
+ * Composio toolkit slug that this tool extends (inherits auth from).
+ * Must be a valid Composio toolkit slug (e.g. `'gmail'`, `'github'`, `'meta_ads'`).
+ * The backend validates this against the toolkit catalog.
* Leave empty for tools that don't need any Composio-managed authentication.
*/
extendsToolkit: z.string().optional(),
@@ -146,7 +151,8 @@ export interface CustomTool {
readonly name: string;
readonly description: string;
/**
- * Composio toolkit slug that this tool extends (requires an active connection for).
+ * Composio toolkit slug that this tool extends (inherits auth from).
+ * Must be a valid Composio toolkit slug. Validated by the backend.
* Undefined means the tool doesn't need any Composio-managed authentication.
*/
readonly extendsToolkit?: string;
@@ -216,13 +222,42 @@ export interface CustomToolkitDefinition {
/** @internal Entry in the per-session custom tools routing map. */
export type CustomToolsMapEntry = {
handle: CustomTool;
- prefixedSlug: string;
+ /** @internal The final slug assigned by the prefixing rules (e.g. LOCAL_GREP, LOCAL_GMAIL_GET_EMAILS) */
+ finalSlug: string;
+ /** Resolved toolkit — from extendsToolkit, parent custom toolkit, or undefined for standalone */
+ toolkit?: string;
};
/** @internal Lookup maps used by ToolRouterSession for routing custom tools. */
export type CustomToolsMap = {
- /** Lookup by prefixed slug (e.g. LOCAL_GET_USER_CONTEXT) — used for agent execution path */
- byPrefixed: Map<string, CustomToolsMapEntry>;
+ /** Lookup by final slug (e.g. LOCAL_GET_USER_CONTEXT) — used for agent execution path */
+ byFinalSlug: Map<string, CustomToolsMapEntry>;
/** Lookup by original slug (e.g. GET_USER_CONTEXT) — used for programmatic session.execute() */
- byOriginal: Map<string, CustomToolsMapEntry>;
+ byOriginalSlug: Map<string, CustomToolsMapEntry>;
+ /** The original custom toolkits passed at session creation — used for session.customToolkits() */
+ toolkits?: CustomToolkit[];
};
+
+// ────────────────────────────────────────────────────────────────
+// Registered custom tool types (returned by session.customTools())
+// ────────────────────────────────────────────────────────────────
+
+/** A custom tool as registered in a session, with its final resolved slug. */
+export interface RegisteredCustomTool {
+ /** The final slug as registered with the backend (e.g. LOCAL_GREP, LOCAL_GMAIL_GET_EMAILS) */
+ slug: string;
+ name: string;
+ description: string;
+ /** Resolved toolkit — extendsToolkit value, custom toolkit slug, or undefined for standalone */
+ toolkit?: string;
+ inputSchema: Record<string, unknown>;
+ outputSchema?: Record<string, unknown>;
+}
+
+/** A custom toolkit as registered in a session, with final slugs on nested tools. */
+export interface RegisteredCustomToolkit {
+ slug: string;
+ name: string;
+ description: string;
+ tools: RegisteredCustomTool[];
+}
diff --git a/ts/packages/core/src/types/toolRouter.types.ts b/ts/packages/core/src/types/toolRouter.types.ts
index e82cb7357..9ca9de5a3 100644
--- a/ts/packages/core/src/types/toolRouter.types.ts
+++ b/ts/packages/core/src/types/toolRouter.types.ts
@@ -3,7 +3,7 @@ import type { BaseComposioProvider } from '../provider/BaseProvider';
import { SessionMetaToolOptions } from './modifiers.types';
import { ConnectionRequest } from './connectionRequest.types';
import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';
-import type { CustomTool, CustomToolkit } from './customTool.types';
+import type { CustomTool, CustomToolkit, RegisteredCustomTool, RegisteredCustomToolkit } from './customTool.types';
export const MCPServerTypeSchema = z.enum(['http', 'sse']);
export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
@@ -474,6 +474,10 @@ export interface Session<
execute: ToolRouterSessionExecuteFn;
/** Proxy an API call through Composio's auth layer using the session's connected account */
proxyExecute: ToolRouterSessionProxyExecuteFn;
+ /** List custom tools registered in this session, with their final slugs and schemas */
+ customTools: (options?: { toolkit?: string }) => RegisteredCustomTool[];
+ /** List custom toolkits registered in this session, with final slugs on nested tools */
+ customToolkits: () => RegisteredCustomToolkit[];
/** Experimental features (files, assistive prompt, etc.) */
experimental: SessionExperimental;
}
diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.ts
index e8d1f39c6..87043776f 100644
--- a/ts/packages/core/test/models/customTool.test.ts
+++ b/ts/packages/core/test/models/customTool.test.ts
@@ -290,15 +290,15 @@ describe('buildCustomToolsMap', () => {
it('should prefix as LOCAL_<SLUG>', () => {
const map = buildCustomToolsMap([makeTool('MY_TOOL')]);
- expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
- expect(map.byOriginal.has('MY_TOOL')).toBe(true);
+ expect(map.byFinalSlug.has('LOCAL_MY_TOOL')).toBe(true);
+ expect(map.byOriginalSlug.has('MY_TOOL')).toBe(true);
});
it('should handle case-insensitive slugs (uppercased internally)', () => {
const map = buildCustomToolsMap([makeTool('my_tool')]);
- expect(map.byOriginal.has('MY_TOOL')).toBe(true);
- expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
+ expect(map.byOriginalSlug.has('MY_TOOL')).toBe(true);
+ expect(map.byFinalSlug.has('LOCAL_MY_TOOL')).toBe(true);
});
});
@@ -306,8 +306,8 @@ describe('buildCustomToolsMap', () => {
it('should prefix as LOCAL_<EXTENDS_TOOLKIT>_<SLUG>', () => {
const map = buildCustomToolsMap([makeTool('GET_EMAILS', 'gmail')]);
- expect(map.byPrefixed.has('LOCAL_GMAIL_GET_EMAILS')).toBe(true);
- expect(map.byOriginal.has('GET_EMAILS')).toBe(true);
+ expect(map.byFinalSlug.has('LOCAL_GMAIL_GET_EMAILS')).toBe(true);
+ expect(map.byOriginalSlug.has('GET_EMAILS')).toBe(true);
});
});
@@ -323,8 +323,8 @@ describe('buildCustomToolsMap', () => {
const map = buildCustomToolsMap([], [tk]);
- expect(map.byPrefixed.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
- expect(map.byOriginal.has('SED')).toBe(true);
+ expect(map.byFinalSlug.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
+ expect(map.byOriginalSlug.has('SED')).toBe(true);
});
});
@@ -341,9 +341,9 @@ describe('buildCustomToolsMap', () => {
const map = buildCustomToolsMap([grep], [tk]);
- expect(map.byPrefixed.size).toBe(2);
- expect(map.byPrefixed.has('LOCAL_GREP')).toBe(true);
- expect(map.byPrefixed.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
+ expect(map.byFinalSlug.size).toBe(2);
+ expect(map.byFinalSlug.has('LOCAL_GREP')).toBe(true);
+ expect(map.byFinalSlug.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
});
});
@@ -369,27 +369,39 @@ describe('buildCustomToolsMap', () => {
});
describe('length validation', () => {
- it('should throw when prefixed slug exceeds 60 characters with contextual error', () => {
+ it('should throw early in createCustomTool when slug is too long (standalone)', () => {
const longSlug = 'A'.repeat(56); // LOCAL_ + 56 = 62 > 60
- expect(() => buildCustomToolsMap([makeTool(longSlug)])).toThrow('too long');
+ expect(() => createCustomTool(longSlug, {
+ name: 'Long', description: 'Too long', inputParams: z.object({}), execute: vi.fn().mockResolvedValue({}),
+ })).toThrow('too long');
});
- it('should show available length in error for toolkit tools', () => {
+ it('should throw early in createCustomTool when slug is too long (extension)', () => {
+ // LOCAL_GMAIL_ = 12 chars, so slug > 48 chars overflows
+ const longSlug = 'A'.repeat(49);
+ expect(() => createCustomTool(longSlug, {
+ name: 'Long', description: 'Too long', extendsToolkit: 'gmail',
+ inputParams: z.object({}), execute: vi.fn().mockResolvedValue({}),
+ })).toThrow('too long');
+ });
+
+ it('should throw early in createCustomToolkit when tool slug is too long', () => {
const longSlug = 'A'.repeat(50); // LOCAL_DEV_TOOLS_ + 50 = 66 > 60
- const tk: CustomToolkit = {
- slug: 'DEV_TOOLS',
- name: 'Dev Tools',
- description: 'Utilities',
- tools: [makeTool(longSlug)],
- };
+ const tool = makeTool(longSlug);
+ expect(() => createCustomToolkit('DEV_TOOLS', {
+ name: 'Dev Tools', description: 'Utilities', tools: [tool],
+ })).toThrow('too long');
+ });
- expect(() => buildCustomToolsMap([], [tk])).toThrow(/Shorten the slug to at most/);
+ it('should still validate in buildCustomToolsMap as safety net', () => {
+ const longSlug = 'A'.repeat(56);
+ expect(() => buildCustomToolsMap([makeTool(longSlug)])).toThrow('exceeds');
});
it('should accept slugs that fit within 60 chars', () => {
const slug = 'A'.repeat(54); // LOCAL_ + 54 = 60 exactly
const map = buildCustomToolsMap([makeTool(slug)]);
- expect(map.byPrefixed.size).toBe(1);
+ expect(map.byFinalSlug.size).toBe(1);
});
});
});
diff --git a/ts/packages/core/test/models/customToolRouting.test.ts b/ts/packages/core/test/models/customToolRouting.test.ts
index e016bcedb..5277bf4a1 100644
--- a/ts/packages/core/test/models/customToolRouting.test.ts
+++ b/ts/packages/core/test/models/customToolRouting.test.ts
@@ -72,8 +72,8 @@ const customToolHandle = createCustomTool('GET_USER_CONTEXT', {
execute: localExecute,
});
-const sessionExecute = vi.fn().mockImplementation(async (input: any, session: any) => ({
- userId: session.userId,
+const sessionExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => ({
+ userId: ctx.userId,
}));
const sessionToolHandle = createCustomTool('GET_AD_ACCOUNTS', {
@@ -291,8 +291,8 @@ describe('ToolRouterSession execution routing', () => {
});
it('should provide a working execute() on SessionContext for remote tools', async () => {
- const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
- const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });
+ const chainedExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => {
+ const inner = await ctx.execute('GMAIL_SEND_EMAIL', { to: input.to });
return { inner_result: inner.data };
});
@@ -321,8 +321,8 @@ describe('ToolRouterSession execution routing', () => {
execute: siblingExecute,
});
- const toolAExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
- const inner = await session.execute('TOOL_B', { key: input.value });
+ const toolAExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => {
+ const inner = await ctx.execute('TOOL_B', { key: input.value });
return { fromA: true, fromB: inner.data };
});
const toolA = createCustomTool('TOOL_A', {