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.

feat(core): add custom local tools for tool router sessions

Dhawal Upadhyay2e1d708595c6
diff --git a/ts/packages/core/package.json b/ts/packages/core/package.json
index 48af1e3de..50c803ea9 100644
--- a/ts/packages/core/package.json
+++ b/ts/packages/core/package.json
@@ -74,6 +74,20 @@
"default": "./dist/index.cjs"
}
},
+ "./experimental": {
+ "import": {
+ "types": "./dist/experimental/index.d.mts",
+ "default": "./dist/experimental/index.mjs"
+ },
+ "require": {
+ "types": "./dist/experimental/index.d.cts",
+ "default": "./dist/experimental/index.cjs"
+ },
+ "default": {
+ "types": "./dist/experimental/index.d.cts",
+ "default": "./dist/experimental/index.cjs"
+ }
+ },
"./platform": {
"workerd": {
"types": "./dist/platform/workerd.d.mts",
diff --git a/ts/packages/core/src/experimental/index.ts b/ts/packages/core/src/experimental/index.ts
new file mode 100644
index 000000000..c26db2526
--- /dev/null
+++ b/ts/packages/core/src/experimental/index.ts
@@ -0,0 +1,18 @@
+/**
+ * Experimental APIs for @composio/core.
+ *
+ * Import from '@composio/core/experimental'. These APIs may change
+ * in future releases. When graduating to stable, they will move to
+ * '@composio/core' — only the import path changes.
+ */
+
+// Custom local tools
+export { CustomTool } from '../models/CustomTool';
+export { SessionContextImpl } from '../models/SessionContext';
+export type {
+ CustomToolHandle,
+ NewCustomToolOptions,
+ CustomToolExecuteFn,
+ CustomToolExecuteResponse,
+ SessionContext,
+} from '../types/customTool.types';
diff --git a/ts/packages/core/src/index.ts b/ts/packages/core/src/index.ts
index 6decb7207..cc1183d5d 100644
--- a/ts/packages/core/src/index.ts
+++ b/ts/packages/core/src/index.ts
@@ -11,6 +11,9 @@ export { MCP } from './models/MCP';
export { RemoteFile } from './models/RemoteFile';
export { createConnectionRequest } from './models/ConnectionRequest';
export { ToolRouterSession } from './models/ToolRouterSession';
+/** @experimental Create custom local tools — also available from '@composio/core/experimental' */
+export { CustomTool } from './models/CustomTool';
+export { SessionContextImpl } from './models/SessionContext';
export * from './types/provider.types';
export * from './types/customTool.types';
export * from './types/tool.types';
diff --git a/ts/packages/core/src/models/CustomTool.ts b/ts/packages/core/src/models/CustomTool.ts
new file mode 100644
index 000000000..bbc01e53c
--- /dev/null
+++ b/ts/packages/core/src/models/CustomTool.ts
@@ -0,0 +1,166 @@
+/**
+ * @fileoverview Standalone factory function for creating custom local tools.
+ *
+ * Usage:
+ * ```typescript
+ * import { CustomTool } from '@composio/core/experimental';
+ *
+ * const myTool = CustomTool({
+ * slug: 'GET_USER_CONTEXT',
+ * name: 'Get user context',
+ * description: 'Retrieve what we know about a user',
+ * inputParams: z.object({ category: z.string() }),
+ * execute: async (input) => ({ data: { ... }, error: null, successful: true }),
+ * });
+ * ```
+ */
+import * as zodToJsonSchema from 'zod-to-json-schema';
+import { z } from 'zod/v3';
+import type {
+ NewCustomToolOptions,
+ CustomToolHandle,
+ CustomToolExecuteFn,
+ LocalToolsMap,
+ LocalToolsMapEntry,
+ LocalToolDefinition,
+ InputParamsSchema,
+} from '../types/customTool.types';
+
+/** Prefix applied by the backend to local tool slugs for disambiguation. */
+export const LOCAL_TOOL_PREFIX = 'LOCAL_';
+
+/**
+ * Create a custom local tool for use in tool router sessions.
+ *
+ * The returned handle is a lightweight reference containing the tool's metadata
+ * and execute function. Pass it to `composio.create(userId, { customTools: [...] })`
+ * to bind it to a session.
+ *
+ * @param options - Tool definition including slug, schema, and execute function
+ * @returns A CustomToolHandle to pass to session creation
+ *
+ * @example No-auth tool
+ * ```typescript
+ * const getUserContext = CustomTool({
+ * slug: 'GET_USER_CONTEXT',
+ * name: 'Get user context',
+ * description: 'Retrieve user preferences and history',
+ * inputParams: z.object({ category: z.string().default('all') }),
+ * execute: async (input) => ({
+ * data: await db.userContext.find(input.category),
+ * error: null,
+ * successful: true,
+ * }),
+ * });
+ * ```
+ *
+ * @example Auth tool with session context
+ * ```typescript
+ * const getAdAccounts = CustomTool({
+ * slug: 'GET_AD_ACCOUNTS',
+ * name: 'Get ad accounts',
+ * description: 'Get Meta ad account IDs for the authenticated user',
+ * toolkit: 'meta_ads',
+ * inputParams: z.object({ fields: z.string().default('id,name') }),
+ * execute: async (input, session) => ({
+ * data: await session.proxyExecute({
+ * endpoint: '/v21.0/me/adaccounts',
+ * method: 'GET',
+ * parameters: [{ in: 'query', name: 'fields', value: input.fields }],
+ * }),
+ * error: null,
+ * successful: true,
+ * }),
+ * });
+ * ```
+ */
+export function CustomTool<T extends z.ZodType>(
+ options: NewCustomToolOptions<T>
+): CustomToolHandle {
+ const { slug, name, description, inputParams, execute, toolkit } = options;
+
+ if (!slug) {
+ throw new Error('CustomTool: slug is required');
+ }
+ if (!name) {
+ throw new Error('CustomTool: name is required');
+ }
+ if (!description) {
+ throw new Error('CustomTool: description is required');
+ }
+ if (!inputParams) {
+ throw new Error('CustomTool: inputParams is required');
+ }
+ if (typeof execute !== 'function') {
+ throw new Error('CustomTool: execute must be a function');
+ }
+
+ // Convert Zod schema → JSON Schema (reuses same pattern as legacy CustomTools.createTool)
+ const paramsSchema = zodToJsonSchema.default(inputParams, {
+ name: 'input',
+ }) as InputParamsSchema;
+ const paramsSchemaJson = paramsSchema.definitions.input;
+
+ const inputSchema: Record<string, unknown> = {
+ type: 'object',
+ properties: paramsSchemaJson.properties,
+ ...(paramsSchemaJson.required ? { required: paramsSchemaJson.required } : {}),
+ };
+
+ return {
+ slug,
+ name,
+ description,
+ toolkit,
+ inputSchema,
+ execute: execute as CustomToolExecuteFn<z.ZodType>,
+ };
+}
+
+/**
+ * Build a LocalToolsMap from an array of handles.
+ * Used internally by ToolRouter.create() to construct the per-session routing map.
+ *
+ * @internal
+ * @param handles - The custom tool handles to include in the session
+ * @returns Maps for O(1) lookup by both prefixed and original slug
+ * @throws If duplicate slugs are detected
+ */
+export function buildLocalToolsMap(handles: CustomToolHandle[]): LocalToolsMap {
+ const byPrefixed = new Map<string, LocalToolsMapEntry>();
+ const byOriginal = new Map<string, LocalToolsMapEntry>();
+
+ for (const handle of handles) {
+ const upperSlug = handle.slug.toUpperCase();
+ const prefixedSlug = `${LOCAL_TOOL_PREFIX}${upperSlug}`;
+
+ if (byOriginal.has(upperSlug)) {
+ throw new Error(`CustomTool: duplicate slug "${handle.slug}"`);
+ }
+
+ const entry: LocalToolsMapEntry = { handle, prefixedSlug };
+ byPrefixed.set(prefixedSlug, entry);
+ byOriginal.set(upperSlug, entry);
+ }
+
+ return { byPrefixed, byOriginal };
+}
+
+/**
+ * Serialize custom tool handles into the format expected by the backend session creation API.
+ *
+ * @internal
+ * @param handles - The custom tool handles to serialize
+ * @returns Array of LocalToolDefinition for the API payload
+ */
+export function serializeLocalTools(
+ handles: CustomToolHandle[]
+): LocalToolDefinition[] {
+ return handles.map(handle => ({
+ slug: handle.slug,
+ name: handle.name,
+ description: handle.description,
+ input_schema: handle.inputSchema,
+ ...(handle.toolkit ? { toolkit: handle.toolkit } : {}),
+ }));
+}
diff --git a/ts/packages/core/src/models/SessionContext.ts b/ts/packages/core/src/models/SessionContext.ts
new file mode 100644
index 000000000..f75b1f427
--- /dev/null
+++ b/ts/packages/core/src/models/SessionContext.ts
@@ -0,0 +1,61 @@
+/**
+ * @fileoverview Session context implementation injected into custom tool execute functions.
+ */
+import { Composio as ComposioClient } from '@composio/client';
+import type { SessionContext } from '../types/customTool.types';
+import type { ToolExecuteResponse, ToolProxyParams } from '../types/tool.types';
+
+/**
+ * Concrete implementation of SessionContext.
+ * Built per local tool invocation inside ToolRouterSession.executeLocalTool().
+ */
+export class SessionContextImpl implements SessionContext {
+ public readonly userId: string;
+ public readonly sessionId: string;
+
+ constructor(
+ private readonly client: ComposioClient,
+ userId: string,
+ sessionId: string
+ ) {
+ this.userId = userId;
+ this.sessionId = sessionId;
+ }
+
+ /**
+ * Execute any Composio native tool from within a custom tool.
+ * Delegates to the tool router session execute endpoint.
+ */
+ async execute(
+ toolSlug: string,
+ arguments_: Record<string, unknown>
+ ): Promise<ToolExecuteResponse> {
+ const response = await this.client.toolRouter.session.execute(
+ this.sessionId,
+ {
+ tool_slug: toolSlug,
+ arguments: arguments_,
+ }
+ );
+ return {
+ data: response.data,
+ error: response.error,
+ successful: !response.error,
+ };
+ }
+
+ /**
+ * Proxy API calls through Composio's auth layer.
+ * The session-scoped backend endpoint resolves the connected account automatically.
+ *
+ * TODO: Wire to session-scoped proxy endpoint (proxyExecuteForSessionRPC).
+ * Currently a skeleton — will be connected to backend API.
+ */
+ async proxyExecute(_params: ToolProxyParams): Promise<ToolExecuteResponse> {
+ // TODO: Call session-scoped proxy endpoint that resolves connected account from session.
+ // Backend API: apps/apollo/src/lib/toolRouterV2/features/execution/proxyExecuteForSessionRPC.ts
+ throw new Error(
+ 'proxyExecute is not yet implemented. Session-scoped proxy endpoint pending backend support.'
+ );
+ }
+}
diff --git a/ts/packages/core/src/models/ToolRouter.ts b/ts/packages/core/src/models/ToolRouter.ts
index 245f97e03..466e63362 100644
--- a/ts/packages/core/src/models/ToolRouter.ts
+++ b/ts/packages/core/src/models/ToolRouter.ts
@@ -38,6 +38,8 @@ import {
transformToolRouterToolkitsParams,
} from '../lib/toolRouterParams';
import { ToolRouterSession } from './ToolRouterSession';
+import { buildLocalToolsMap, serializeLocalTools } from './CustomTool';
+import type { LocalToolsMap } from '../types/customTool.types';
export class ToolRouter<
TToolCollection,
@@ -77,29 +79,15 @@ export class ToolRouter<
* @example
* ```typescript
* import { Composio } from '@composio/core';
+ * import { CustomTool } from '@composio/core/experimental';
*
* const composio = new Composio();
- * const userId = 'user_123';
*
- * const session = await composio.experimental.create(userId, {
+ * const session = await composio.create('user_123', {
* toolkits: ['gmail'],
* manageConnections: true,
- * tools: {
- * gmail: {
- * disabled: ['gmail_send_email']
- * }
- * },
- * tags: ['readOnlyHint']
+ * customTools: [myCustomTool],
* });
- *
- * console.log(session.sessionId);
- * console.log(session.mcp.url);
- *
- * // Get tools formatted for your framework (requires provider)
- * const tools = await session.tools();
- *
- * // Check toolkit connection states
- * const toolkits = await session.toolkits();
* ```
*/
async create(
@@ -108,7 +96,11 @@ export class ToolRouter<
): Promise<Session<TToolCollection, TTool, TProvider>> {
const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});
- const payload: SessionCreateParams = {
+ // Build local tools map and backend payload from custom tool handles
+ let localToolsMap: LocalToolsMap | undefined;
+ const customTools = routerConfig.customTools;
+
+ const payload: SessionCreateParams & { local_tools?: unknown } = {
user_id: userId,
auth_configs: routerConfig.authConfigs,
connected_accounts: routerConfig.connectedAccounts,
@@ -128,7 +120,16 @@ export class ToolRouter<
: undefined,
};
- const session = await this.client.toolRouter.session.create(payload);
+ if (customTools?.length) {
+ localToolsMap = buildLocalToolsMap(customTools);
+ // Send definitions to backend for BM25 search indexing
+ // Type assertion: @composio/client doesn't have local_tools yet (Hermes PR #8453)
+ payload.local_tools = serializeLocalTools(customTools);
+ }
+
+ const session = await this.client.toolRouter.session.create(
+ payload as SessionCreateParams
+ );
const assistivePrompt =
session.experimental?.assistive_prompt;
@@ -138,7 +139,9 @@ export class ToolRouter<
this.config,
session.session_id,
this.createMCPServerConfig(session.mcp),
- { assistivePrompt }
+ { assistivePrompt },
+ localToolsMap,
+ userId
);
}
diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.ts
index 06f88bf3d..ccfb56890 100644
--- a/ts/packages/core/src/models/ToolRouterSession.ts
+++ b/ts/packages/core/src/models/ToolRouterSession.ts
@@ -25,6 +25,11 @@ import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
import { ValidationError } from '../errors';
import { Tools } from './Tools';
import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
+import type { LocalToolsMap, LocalToolsMapEntry } from '../types/customTool.types';
+import type { ToolExecuteResponse } from '../types/tool.types';
+import { SessionContextImpl } from './SessionContext';
+
+const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';
export class ToolRouterSession<
TToolCollection,
@@ -40,7 +45,9 @@ export class ToolRouterSession<
private readonly config: ComposioConfig<TProvider> | undefined,
sessionId: string,
mcp: ToolRouterMCPServerConfig,
- experimentalOverrides?: Pick<SessionExperimental, 'assistivePrompt'>
+ experimentalOverrides?: Pick<SessionExperimental, 'assistivePrompt'>,
+ private readonly localToolsMap?: LocalToolsMap,
+ private readonly userId?: string
) {
this.sessionId = sessionId;
this.mcp = mcp;
@@ -54,6 +61,9 @@ export class ToolRouterSession<
/**
* Get the tools available in the session, formatted for your AI framework.
* Requires a provider to be configured in the Composio constructor.
+ *
+ * When custom tools are bound to the session, execution of COMPOSIO_MULTI_EXECUTE_TOOL
+ * is intercepted: local tools are executed in-process, remote tools are sent to the backend.
*/
async tools(modifiers?: SessionMetaToolOptions): Promise<ReturnType<TProvider['wrapTools']>> {
const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
@@ -61,6 +71,38 @@ export class ToolRouterSession<
this.sessionId,
modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined
);
+
+ if (this.hasLocalTools()) {
+ // Create an execute function that routes between local and remote execution
+ const routingExecuteFn = async (
+ toolSlug: string,
+ input: Record<string, unknown>
+ ): Promise<ToolExecuteResponse> => {
+ // Intercept COMPOSIO_MULTI_EXECUTE_TOOL and check if the inner tool is local
+ if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) {
+ const innerSlug = String((input as Record<string, unknown>).tool_slug ?? '');
+ const entry = this.findLocalTool(innerSlug);
+ if (entry) {
+ return this.executeLocalTool(
+ entry,
+ (input as Record<string, unknown>).arguments as Record<string, unknown> ?? {}
+ );
+ }
+ }
+ // Default: send to backend
+ return ToolsModel.executeMetaTool(
+ toolSlug,
+ { sessionId: this.sessionId, arguments: input },
+ modifiers
+ );
+ };
+
+ return this.config?.provider?.wrapTools(tools, routingExecuteFn) as ReturnType<
+ TProvider['wrapTools']
+ >;
+ }
+
+ // Standard path (no local tools)
const wrappedTools = ToolsModel.wrapToolsForToolRouter(this.sessionId, tools, modifiers);
return wrappedTools as ReturnType<TProvider['wrapTools']>;
}
@@ -141,20 +183,6 @@ export class ToolRouterSession<
/**
* Search for tools by semantic use case.
* Returns relevant tools for the given query with schemas and guidance.
- *
- * @param params - Search parameters
- * @param params.query - Semantic use-case query (e.g. "send emails", "create GitHub issues")
- * @param params.toolkits - Optional toolkit slugs to filter by
- * @returns Search results with matching tools and schemas
- *
- * @example
- * ```typescript
- * const session = await composio.toolRouter.use('session_123');
- * const results = await session.search({
- * query: 'send emails and notify Slack',
- * toolkits: ['gmail', 'slack'],
- * });
- * ```
*/
async search(params: {
query: string;
@@ -171,30 +199,30 @@ export class ToolRouterSession<
/**
* Execute a tool within the session.
*
- * @param toolSlug - The tool slug to execute (e.g. "GMAIL_SEND_EMAIL")
- * @param arguments_ - Optional tool arguments. Defaults to empty object if omitted.
- * @returns The tool execution result
- *
- * @example
- * ```typescript
- * const session = await composio.toolRouter.use('session_123');
- * const result = await session.execute('GMAIL_SEND_EMAIL', {
- * subject: 'Hello',
- * body: 'Hi!',
- * });
- * ```
+ * For custom local tools, accepts both the original slug (e.g. "GET_USER_CONTEXT")
+ * and the prefixed slug (e.g. "LOCAL_GET_USER_CONTEXT"). Local tools are executed
+ * in-process; remote tools are sent to the Composio backend.
*
- * @example
- * ```typescript
- * // Execute with no arguments
- * const result = await session.execute('HACKERNEWS_GET_USER');
- * ```
+ * @param toolSlug - The tool slug to execute
+ * @param arguments_ - Optional tool arguments
+ * @returns The tool execution result
*/
async execute(
toolSlug: string,
arguments_?: Record<string, unknown>
): Promise<ToolRouterSessionExecuteResponse> {
+ // Check if this is a local tool (by original or prefixed slug)
+ const entry = this.findLocalTool(toolSlug);
+ if (entry) {
+ const result = await this.executeLocalTool(entry, arguments_ ?? {});
+ return {
+ data: result.data,
+ error: result.error,
+ logId: 'local',
+ };
+ }
+
+ // Remote execution
const response = await this.client.toolRouter.session.execute(this.sessionId, {
tool_slug: toolSlug,
arguments: arguments_ ?? {},
@@ -202,4 +230,63 @@ export class ToolRouterSession<
const transformed = transformExecuteResponse(response);
return ToolRouterSessionExecuteResponseSchema.parse(transformed);
}
+
+ // ── Private helpers ──────────────────────────────────────────
+
+ /** Check if this session has any local tools bound. */
+ private hasLocalTools(): boolean {
+ return (this.localToolsMap?.byPrefixed.size ?? 0) > 0;
+ }
+
+ /**
+ * Find a local tool entry by slug.
+ * Checks both the prefixed map (LOCAL_X — agent path) and original map (X — programmatic path).
+ */
+ private findLocalTool(slug: string): LocalToolsMapEntry | undefined {
+ if (!this.localToolsMap) return undefined;
+ const upper = slug.toUpperCase();
+ return this.localToolsMap.byPrefixed.get(upper) ?? this.localToolsMap.byOriginal.get(upper);
+ }
+
+ /**
+ * Execute a local tool in-process.
+ * Builds a SessionContext, validates input, and calls the user's execute function.
+ */
+ private async executeLocalTool(
+ entry: LocalToolsMapEntry,
+ arguments_: Record<string, unknown>
+ ): Promise<ToolExecuteResponse> {
+ const { handle } = entry;
+
+ // Validate input against the Zod schema
+ // The handle was created from a Zod schema, but we stored the execute fn.
+ // We need to re-validate at execution time. The inputParams is on the original options,
+ // but the handle doesn't store the Zod schema — only the JSON Schema.
+ // The execute function itself should handle its input. We trust the LLM/caller here
+ // and let the execute function handle validation. If the user used Zod in their execute,
+ // it will validate there.
+
+ // Build session context
+ const sessionContext = new SessionContextImpl(
+ this.client,
+ this.userId ?? '',
+ this.sessionId
+ );
+
+ try {
+ const result = await handle.execute(arguments_, sessionContext);
+ return {
+ data: result.data,
+ error: result.error,
+ successful: result.successful,
+ };
+ } catch (err: unknown) {
+ const message = err instanceof Error ? err.message : String(err);
+ return {
+ data: {},
+ error: message,
+ successful: false,
+ };
+ }
+ }
}
diff --git a/ts/packages/core/src/types/customTool.types.ts b/ts/packages/core/src/types/customTool.types.ts
index 074b1ed29..b55a0cb56 100644
--- a/ts/packages/core/src/types/customTool.types.ts
+++ b/ts/packages/core/src/types/customTool.types.ts
@@ -1,8 +1,12 @@
import { z } from 'zod/v3';
-import { Tool, ToolProxyParams } from './tool.types';
+import { Tool, ToolProxyParams, ToolExecuteResponse as SdkToolExecuteResponse } from './tool.types';
import { ToolExecuteResponse } from '@composio/client/resources/tools';
import { ConnectionData } from './connectedAccountAuthStates.types';
+// ────────────────────────────────────────────────────────────────
+// Legacy custom tool types (used by composio.tools.createCustomTool)
+// ────────────────────────────────────────────────────────────────
+
type BaseCustomToolOptions<T extends z.ZodType> = {
name: string;
description?: string;
@@ -53,3 +57,96 @@ export interface ExecuteMetadata {
userId: string;
connectedAccountId?: string;
}
+
+// ────────────────────────────────────────────────────────────────
+// New custom tool types (for tool router integration via CustomTool())
+// ────────────────────────────────────────────────────────────────
+
+/**
+ * Session context injected into custom tool execute functions at runtime.
+ * Provides identity context and methods to call other tools or proxy API requests.
+ */
+export interface SessionContext {
+ /** The user ID for this session */
+ readonly userId: string;
+ /** The tool router session ID */
+ readonly sessionId: string;
+ /** Execute any Composio native tool from within a custom tool */
+ execute(
+ toolSlug: string,
+ arguments_: Record<string, unknown>
+ ): Promise<SdkToolExecuteResponse>;
+ /** Proxy API calls through Composio's auth layer (resolved from session) */
+ proxyExecute(params: ToolProxyParams): Promise<SdkToolExecuteResponse>;
+}
+
+/** Response shape returned by custom tool execute functions. */
+export type CustomToolExecuteResponse = {
+ data: Record<string, unknown>;
+ error: string | null;
+ successful: boolean;
+};
+
+/**
+ * Execute function for custom tools.
+ * Supports two call patterns:
+ * - `(input) => result` — for tools that don't need session context
+ * - `(input, session) => result` — for tools that need to call other tools or proxy APIs
+ */
+export type CustomToolExecuteFn<T extends z.ZodType> = (
+ input: z.infer<T>,
+ session: SessionContext
+) => Promise<CustomToolExecuteResponse>;
+
+/** Options for creating a custom local tool via `CustomTool()`. */
+export type NewCustomToolOptions<T extends z.ZodType> = {
+ /** Unique slug identifier (e.g. 'GET_USER_CONTEXT') */
+ slug: string;
+ /** Human-readable name */
+ name: string;
+ /** Description — required for search indexing */
+ description: string;
+ /** Zod schema for input parameters */
+ inputParams: T;
+ /** Optional toolkit slug for auth-based tools (e.g. 'meta_ads') */
+ toolkit?: string;
+ /** The function that executes the tool */
+ execute: CustomToolExecuteFn<T>;
+};
+
+/**
+ * Handle returned from `CustomTool()`.
+ * Pass to `composio.create(userId, { customTools: [...] })` to bind to a session.
+ */
+export interface CustomToolHandle {
+ readonly slug: string;
+ readonly name: string;
+ readonly description: string;
+ readonly toolkit?: string;
+ readonly inputSchema: Record<string, unknown>;
+ /** Direct reference to the execute function — useful for testing */
+ readonly execute: CustomToolExecuteFn<z.ZodType>;
+}
+
+/** Serialized tool definition sent to backend for BM25 search indexing. */
+export interface LocalToolDefinition {
+ slug: string;
+ name: string;
+ description: string;
+ input_schema: Record<string, unknown>;
+ toolkit?: string;
+}
+
+/** @internal Entry in the per-session local tools routing map. */
+export type LocalToolsMapEntry = {
+ handle: CustomToolHandle;
+ prefixedSlug: string;
+};
+
+/** @internal Lookup maps used by ToolRouterSession for routing. */
+export type LocalToolsMap = {
+ /** Lookup by prefixed slug (e.g. LOCAL_GET_USER_CONTEXT) — used for agent execution path */
+ byPrefixed: Map<string, LocalToolsMapEntry>;
+ /** Lookup by original slug (e.g. GET_USER_CONTEXT) — used for programmatic session.execute() */
+ byOriginal: Map<string, LocalToolsMapEntry>;
+};
diff --git a/ts/packages/core/src/types/toolRouter.types.ts b/ts/packages/core/src/types/toolRouter.types.ts
index 327e004cb..6664970f0 100644
--- a/ts/packages/core/src/types/toolRouter.types.ts
+++ b/ts/packages/core/src/types/toolRouter.types.ts
@@ -3,6 +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 { CustomToolHandle } from './customTool.types';
export const MCPServerTypeSchema = z.enum(['http', 'sse']);
export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
@@ -215,6 +216,12 @@ export const ToolRouterCreateSessionConfigSchema = z
})
.optional()
.describe('Experimental features configuration - not stable, may be modified or removed'),
+ customTools: z
+ .array(z.custom<CustomToolHandle>())
+ .optional()
+ .describe(
+ 'Custom local tools to include in this session. Created via CustomTool() from @composio/core/experimental.'
+ ),
})
.partial()
.describe('The config for the tool router session');
diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.ts
new file mode 100644
index 000000000..575d5f2b9
--- /dev/null
+++ b/ts/packages/core/test/models/customTool.test.ts
@@ -0,0 +1,320 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { z } from 'zod/v3';
+import { CustomTool, buildLocalToolsMap, serializeLocalTools, LOCAL_TOOL_PREFIX } from '../../src/models/CustomTool';
+import { SessionContextImpl } from '../../src/models/SessionContext';
+import type { CustomToolHandle, SessionContext } from '../../src/types/customTool.types';
+
+// ────────────────────────────────────────────────────────────────
+// CustomTool() factory
+// ────────────────────────────────────────────────────────────────
+
+describe('CustomTool', () => {
+ const baseOptions = {
+ slug: 'GET_USER_CONTEXT',
+ name: 'Get user context',
+ description: 'Retrieve what we know about a user',
+ inputParams: z.object({
+ category: z.string().describe('The category'),
+ }),
+ execute: vi.fn().mockResolvedValue({
+ data: { result: 'ok' },
+ error: null,
+ successful: true,
+ }),
+ };
+
+ it('should return a valid handle with correct fields', () => {
+ const handle = CustomTool(baseOptions);
+
+ expect(handle.slug).toBe('GET_USER_CONTEXT');
+ expect(handle.name).toBe('Get user context');
+ expect(handle.description).toBe('Retrieve what we know about a user');
+ expect(handle.toolkit).toBeUndefined();
+ expect(handle.execute).toBe(baseOptions.execute);
+ expect(handle.inputSchema).toMatchObject({
+ type: 'object',
+ properties: {
+ category: { type: 'string', description: 'The category' },
+ },
+ required: ['category'],
+ });
+ });
+
+ it('should include toolkit when provided', () => {
+ const handle = CustomTool({ ...baseOptions, toolkit: 'meta_ads' });
+ expect(handle.toolkit).toBe('meta_ads');
+ });
+
+ it('should convert Zod schema with optional fields correctly', () => {
+ const handle = CustomTool({
+ ...baseOptions,
+ inputParams: z.object({
+ required_field: z.string(),
+ optional_field: z.number().optional(),
+ }),
+ });
+
+ expect(handle.inputSchema).toMatchObject({
+ type: 'object',
+ properties: {
+ required_field: { type: 'string' },
+ optional_field: { type: 'number' },
+ },
+ required: ['required_field'],
+ });
+ });
+
+ it('should convert Zod schema with defaults correctly', () => {
+ const handle = CustomTool({
+ ...baseOptions,
+ inputParams: z.object({
+ category: z.string().default('all'),
+ }),
+ });
+
+ expect(handle.inputSchema).toMatchObject({
+ type: 'object',
+ properties: {
+ category: expect.objectContaining({ type: 'string' }),
+ },
+ });
+ });
+
+ describe('validation', () => {
+ it('should throw if slug is missing', () => {
+ expect(() => CustomTool({ ...baseOptions, slug: '' })).toThrow('slug is required');
+ });
+
+ it('should throw if name is missing', () => {
+ expect(() => CustomTool({ ...baseOptions, name: '' })).toThrow('name is required');
+ });
+
+ it('should throw if description is missing', () => {
+ expect(() => CustomTool({ ...baseOptions, description: '' })).toThrow(
+ 'description is required'
+ );
+ });
+
+ it('should throw if inputParams is missing', () => {
+ expect(() => CustomTool({ ...baseOptions, inputParams: null as any })).toThrow(
+ 'inputParams is required'
+ );
+ });
+
+ it('should throw if execute is not a function', () => {
+ expect(() => CustomTool({ ...baseOptions, execute: 'not-fn' as any })).toThrow(
+ 'execute must be a function'
+ );
+ });
+ });
+
+ describe('execute function signatures', () => {
+ it('should allow no-session execute (input only)', async () => {
+ const noSessionExecute = vi.fn().mockResolvedValue({
+ data: { result: 42 },
+ error: null,
+ successful: true,
+ });
+
+ const handle = CustomTool({
+ ...baseOptions,
+ execute: noSessionExecute,
+ });
+
+ // Call without session — JS ignores extra params
+ const result = await handle.execute({ category: 'test' } as any);
+ expect(result.data.result).toBe(42);
+ expect(noSessionExecute).toHaveBeenCalledWith({ category: 'test' });
+ });
+
+ it('should allow session-based execute (input + session)', async () => {
+ const sessionExecute = vi.fn().mockResolvedValue({
+ data: { userId: 'u1' },
+ error: null,
+ successful: true,
+ });
+
+ const handle = CustomTool({
+ ...baseOptions,
+ execute: sessionExecute,
+ });
+
+ const mockSession: SessionContext = {
+ userId: 'user_1',
+ sessionId: 'sess_1',
+ execute: vi.fn(),
+ proxyExecute: vi.fn(),
+ };
+
+ const result = await handle.execute({ category: 'test' }, mockSession);
+ expect(result.data.userId).toBe('u1');
+ expect(sessionExecute).toHaveBeenCalledWith({ category: 'test' }, mockSession);
+ });
+ });
+});
+
+// ────────────────────────────────────────────────────────────────
+// buildLocalToolsMap()
+// ────────────────────────────────────────────────────────────────
+
+describe('buildLocalToolsMap', () => {
+ const makeHandle = (slug: string): CustomToolHandle => ({
+ slug,
+ name: `Tool ${slug}`,
+ description: `Description for ${slug}`,
+ inputSchema: { type: 'object', properties: {} },
+ execute: vi.fn(),
+ });
+
+ it('should create maps with both prefixed and original slug keys', () => {
+ const handles = [makeHandle('MY_TOOL'), makeHandle('OTHER_TOOL')];
+ const map = buildLocalToolsMap(handles);
+
+ expect(map.byPrefixed.size).toBe(2);
+ expect(map.byOriginal.size).toBe(2);
+
+ // Prefixed lookup
+ expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
+ expect(map.byPrefixed.has('LOCAL_OTHER_TOOL')).toBe(true);
+
+ // Original lookup
+ expect(map.byOriginal.has('MY_TOOL')).toBe(true);
+ expect(map.byOriginal.has('OTHER_TOOL')).toBe(true);
+ });
+
+ it('should store correct prefixedSlug on each entry', () => {
+ const handles = [makeHandle('FOO')];
+ const map = buildLocalToolsMap(handles);
+
+ const entry = map.byPrefixed.get('LOCAL_FOO');
+ expect(entry?.prefixedSlug).toBe('LOCAL_FOO');
+ expect(entry?.handle.slug).toBe('FOO');
+ });
+
+ it('should handle case-insensitive slugs (uppercased internally)', () => {
+ const handle = makeHandle('my_tool');
+ const map = buildLocalToolsMap([handle]);
+
+ expect(map.byOriginal.has('MY_TOOL')).toBe(true);
+ expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
+ });
+
+ it('should throw on duplicate slugs', () => {
+ const handles = [makeHandle('DUPE'), makeHandle('DUPE')];
+ expect(() => buildLocalToolsMap(handles)).toThrow('duplicate slug "DUPE"');
+ });
+
+ it('should return empty maps for empty input', () => {
+ const map = buildLocalToolsMap([]);
+ expect(map.byPrefixed.size).toBe(0);
+ expect(map.byOriginal.size).toBe(0);
+ });
+});
+
+// ────────────────────────────────────────────────────────────────
+// serializeLocalTools()
+// ────────────────────────────────────────────────────────────────
+
+describe('serializeLocalTools', () => {
+ it('should serialize handles into backend format', () => {
+ const handle: CustomToolHandle = {
+ slug: 'GET_DATA',
+ name: 'Get Data',
+ description: 'Gets some data',
+ toolkit: 'my_toolkit',
+ inputSchema: { type: 'object', properties: { id: { type: 'string' } } },
+ execute: vi.fn(),
+ };
+
+ const result = serializeLocalTools([handle]);
+
+ expect(result).toEqual([
+ {
+ slug: 'GET_DATA',
+ name: 'Get Data',
+ description: 'Gets some data',
+ toolkit: 'my_toolkit',
+ input_schema: { type: 'object', properties: { id: { type: 'string' } } },
+ },
+ ]);
+ });
+
+ it('should omit toolkit when not provided', () => {
+ const handle: CustomToolHandle = {
+ slug: 'NO_TOOLKIT',
+ name: 'No Toolkit',
+ description: 'No toolkit tool',
+ inputSchema: { type: 'object', properties: {} },
+ execute: vi.fn(),
+ };
+
+ const result = serializeLocalTools([handle]);
+ expect(result[0]).not.toHaveProperty('toolkit');
+ });
+});
+
+// ────────────────────────────────────────────────────────────────
+// SessionContextImpl
+// ────────────────────────────────────────────────────────────────
+
+describe('SessionContextImpl', () => {
+ const mockClient = {
+ toolRouter: {
+ session: {
+ execute: vi.fn(),
+ },
+ },
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should expose userId and sessionId', () => {
+ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ expect(ctx.userId).toBe('user_1');
+ expect(ctx.sessionId).toBe('sess_1');
+ });
+
+ it('should delegate execute() to client.toolRouter.session.execute()', async () => {
+ mockClient.toolRouter.session.execute.mockResolvedValue({
+ data: { result: 'ok' },
+ error: null,
+ log_id: 'log_1',
+ });
+
+ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ const result = await ctx.execute('GMAIL_SEND_EMAIL', { to: '[email protected]' });
+
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {
+ tool_slug: 'GMAIL_SEND_EMAIL',
+ arguments: { to: '[email protected]' },
+ });
+ expect(result).toEqual({
+ data: { result: 'ok' },
+ error: null,
+ successful: true,
+ });
+ });
+
+ it('should set successful=false when execute() returns an error', async () => {
+ mockClient.toolRouter.session.execute.mockResolvedValue({
+ data: {},
+ error: 'something went wrong',
+ log_id: 'log_2',
+ });
+
+ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ const result = await ctx.execute('BAD_TOOL', {});
+
+ expect(result.successful).toBe(false);
+ expect(result.error).toBe('something went wrong');
+ });
+
+ it('should throw on proxyExecute() (not yet implemented)', async () => {
+ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ await expect(
+ ctx.proxyExecute({ endpoint: '/test', method: 'GET' })
+ ).rejects.toThrow('proxyExecute is not yet implemented');
+ });
+});
diff --git a/ts/packages/core/test/models/customToolRouting.test.ts b/ts/packages/core/test/models/customToolRouting.test.ts
new file mode 100644
index 000000000..0abee961d
--- /dev/null
+++ b/ts/packages/core/test/models/customToolRouting.test.ts
@@ -0,0 +1,454 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { z } from 'zod/v3';
+import { ToolRouter } from '../../src/models/ToolRouter';
+import { ToolRouterSession } from '../../src/models/ToolRouterSession';
+import { CustomTool, buildLocalToolsMap } from '../../src/models/CustomTool';
+import { MockProvider } from '../utils/mocks/provider.mock';
+import ComposioClient from '@composio/client';
+import { Tools } from '../../src/models/Tools';
+import type { CustomToolHandle } from '../../src/types/customTool.types';
+
+// Mock telemetry
+vi.mock('../../src/telemetry/Telemetry', () => ({
+ telemetry: { instrument: vi.fn() },
+}));
+
+// Mock Tools class
+vi.mock('../../src/models/Tools', () => ({
+ Tools: vi.fn().mockImplementation(() => ({
+ getRawToolRouterMetaTools: vi.fn().mockResolvedValue([
+ { slug: 'COMPOSIO_SEARCH_TOOLS', name: 'Search Tools' },
+ { slug: 'COMPOSIO_MULTI_EXECUTE_TOOL', name: 'Multi Execute' },
+ ]),
+ wrapToolsForToolRouter: vi.fn().mockReturnValue('wrapped-tools'),
+ executeMetaTool: vi.fn().mockResolvedValue({
+ data: { remote: true },
+ error: null,
+ successful: true,
+ }),
+ })),
+}));
+
+// ── Fixtures ─────────────────────────────────────────────────────
+
+const createMockClient = () => ({
+ baseURL: 'https://api.composio.dev',
+ apiKey: 'test-api-key',
+ toolRouter: {
+ session: {
+ create: vi.fn().mockResolvedValue({
+ session_id: 'sess_123',
+ mcp: { type: 'http', url: 'https://mcp.example.com/sess_123' },
+ tool_router_tools: [],
+ }),
+ retrieve: vi.fn(),
+ link: vi.fn(),
+ toolkits: vi.fn(),
+ executeMeta: vi.fn(),
+ search: vi.fn(),
+ execute: vi.fn().mockResolvedValue({
+ data: { remote_result: true },
+ error: null,
+ log_id: 'log_remote',
+ }),
+ tools: vi.fn(),
+ },
+ },
+ tools: {
+ list: vi.fn(),
+ retrieve: vi.fn(),
+ execute: vi.fn(),
+ proxy: vi.fn(),
+ },
+});
+
+const localExecute = vi.fn().mockResolvedValue({
+ data: { local_result: true },
+ error: null,
+ successful: true,
+});
+
+const customToolHandle = CustomTool({
+ slug: 'GET_USER_CONTEXT',
+ name: 'Get user context',
+ description: 'Retrieve user preferences',
+ inputParams: z.object({ category: z.string() }),
+ execute: localExecute,
+});
+
+const sessionExecute = vi.fn().mockImplementation(async (input: any, session: any) => ({
+ data: { userId: session.userId },
+ error: null,
+ successful: true,
+}));
+
+const sessionToolHandle = CustomTool({
+ slug: 'GET_AD_ACCOUNTS',
+ name: 'Get ad accounts',
+ description: 'Get ad account IDs',
+ toolkit: 'meta_ads',
+ inputParams: z.object({ fields: z.string() }),
+ execute: sessionExecute,
+});
+
+// ────────────────────────────────────────────────────────────────
+// ToolRouter.create() with customTools
+// ────────────────────────────────────────────────────────────────
+
+describe('ToolRouter.create() with customTools', () => {
+ let mockClient: ReturnType<typeof createMockClient>;
+ let router: ToolRouter<unknown, unknown, MockProvider>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockClient = createMockClient();
+ router = new ToolRouter(mockClient as unknown as ComposioClient, {
+ apiKey: 'test-key',
+ provider: new MockProvider(),
+ });
+ });
+
+ it('should send local_tools in the create payload', async () => {
+ await router.create('user_1', {
+ toolkits: ['gmail'],
+ customTools: [customToolHandle],
+ });
+
+ const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
+ expect(payload.local_tools).toEqual([
+ {
+ slug: 'GET_USER_CONTEXT',
+ name: 'Get user context',
+ description: 'Retrieve user preferences',
+ input_schema: customToolHandle.inputSchema,
+ },
+ ]);
+ });
+
+ it('should include toolkit in local_tools when present', async () => {
+ await router.create('user_1', {
+ customTools: [sessionToolHandle],
+ });
+
+ const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
+ expect(payload.local_tools[0].toolkit).toBe('meta_ads');
+ });
+
+ it('should not send local_tools when customTools is omitted', async () => {
+ await router.create('user_1', { toolkits: ['gmail'] });
+
+ const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
+ expect(payload.local_tools).toBeUndefined();
+ });
+
+ it('should not send local_tools when customTools is empty', async () => {
+ await router.create('user_1', { customTools: [] });
+
+ const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
+ expect(payload.local_tools).toBeUndefined();
+ });
+
+ it('should return a session with the correct sessionId', async () => {
+ const session = await router.create('user_1', {
+ customTools: [customToolHandle],
+ });
+
+ expect(session.sessionId).toBe('sess_123');
+ });
+});
+
+// ────────────────────────────────────────────────────────────────
+// ToolRouterSession — execution routing
+// ────────────────────────────────────────────────────────────────
+
+describe('ToolRouterSession execution routing', () => {
+ let mockClient: ReturnType<typeof createMockClient>;
+
+ const createSession = (
+ client: ReturnType<typeof createMockClient>,
+ customTools: CustomToolHandle[] = []
+ ) => {
+ const localToolsMap = customTools.length ? buildLocalToolsMap(customTools) : undefined;
+
+ return new ToolRouterSession(
+ client as unknown as ComposioClient,
+ { apiKey: 'key', provider: new MockProvider() },
+ 'sess_123',
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
+ undefined,
+ localToolsMap,
+ 'user_1'
+ );
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockClient = createMockClient();
+ localExecute.mockClear();
+ sessionExecute.mockClear();
+ });
+
+ describe('session.execute() routing', () => {
+ it('should route local tool by original slug to in-process execution', async () => {
+ const session = createSession(mockClient, [customToolHandle]);
+
+ const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
+
+ expect(result.data).toEqual({ local_result: true });
+ expect(result.logId).toBe('local');
+ expect(localExecute).toHaveBeenCalledWith(
+ { category: 'prefs' },
+ expect.objectContaining({ userId: 'user_1', sessionId: 'sess_123' })
+ );
+ // Should NOT call remote
+ expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
+ });
+
+ it('should route local tool by prefixed slug to in-process execution', async () => {
+ const session = createSession(mockClient, [customToolHandle]);
+
+ const result = await session.execute('LOCAL_GET_USER_CONTEXT', { category: 'all' });
+
+ expect(result.data).toEqual({ local_result: true });
+ expect(localExecute).toHaveBeenCalled();
+ expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
+ });
+
+ it('should be case-insensitive for local tool lookup', async () => {
+ const session = createSession(mockClient, [customToolHandle]);
+
+ const result = await session.execute('get_user_context', { category: 'test' });
+
+ expect(result.data).toEqual({ local_result: true });
+ });
+
+ it('should route non-local tool to remote execution', async () => {
+ const session = createSession(mockClient, [customToolHandle]);
+
+ await session.execute('GMAIL_SEND_EMAIL', { to: '[email protected]' });
+
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {
+ tool_slug: 'GMAIL_SEND_EMAIL',
+ arguments: { to: '[email protected]' },
+ });
+ expect(localExecute).not.toHaveBeenCalled();
+ });
+
+ it('should route all tools to remote when no customTools are bound', async () => {
+ const session = createSession(mockClient);
+
+ await session.execute('GET_USER_CONTEXT', { category: 'test' });
+
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalled();
+ expect(localExecute).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('session.execute() — SessionContext injection', () => {
+ it('should inject SessionContext with correct userId and sessionId', async () => {
+ const session = createSession(mockClient, [sessionToolHandle]);
+
+ await session.execute('GET_AD_ACCOUNTS', { fields: 'id' });
+
+ expect(sessionExecute).toHaveBeenCalledWith(
+ { fields: 'id' },
+ expect.objectContaining({
+ userId: 'user_1',
+ sessionId: 'sess_123',
+ })
+ );
+ });
+
+ it('should provide a working execute() on SessionContext', async () => {
+ // Tool that calls another tool via session.execute()
+ const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
+ const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });
+ return { data: { inner_result: inner.data }, error: null, successful: true };
+ });
+
+ const chainedTool = CustomTool({
+ slug: 'CHAINED_TOOL',
+ name: 'Chained',
+ description: 'Calls another tool',
+ inputParams: z.object({ to: z.string() }),
+ execute: chainedExecute,
+ });
+
+ const session = createSession(mockClient, [chainedTool]);
+ await session.execute('CHAINED_TOOL', { to: '[email protected]' });
+
+ // The chained tool should have called session.execute, which calls the API
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {
+ tool_slug: 'GMAIL_SEND_EMAIL',
+ arguments: { to: '[email protected]' },
+ });
+ });
+ });
+
+ describe('session.execute() — error handling', () => {
+ it('should catch errors thrown by execute function and return error response', async () => {
+ const throwingTool = CustomTool({
+ slug: 'THROWING_TOOL',
+ name: 'Throwing',
+ description: 'Throws an error',
+ inputParams: z.object({}),
+ execute: async () => {
+ throw new Error('boom');
+ },
+ });
+
+ const session = createSession(mockClient, [throwingTool]);
+ const result = await session.execute('THROWING_TOOL', {});
+
+ expect(result.error).toBe('boom');
+ expect(result.data).toEqual({});
+ });
+
+ it('should handle non-Error throws gracefully', async () => {
+ const throwingTool = CustomTool({
+ slug: 'STRING_THROW',
+ name: 'String throw',
+ description: 'Throws a string',
+ inputParams: z.object({}),
+ execute: async () => {
+ throw 'string error';
+ },
+ });
+
+ const session = createSession(mockClient, [throwingTool]);
+ const result = await session.execute('STRING_THROW', {});
+
+ expect(result.error).toBe('string error');
+ });
+ });
+
+ describe('session.tools() — COMPOSIO_MULTI_EXECUTE_TOOL routing', () => {
+ it('should route local tools via COMPOSIO_MULTI_EXECUTE_TOOL to in-process execution', async () => {
+ const provider = new MockProvider();
+ // Mock wrapTools to capture the execute function and call it
+ provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
+ // Store executeFn so we can call it
+ (provider as any)._capturedExecuteFn = executeFn;
+ return 'wrapped-tools-with-routing';
+ });
+
+ const session = new ToolRouterSession(
+ mockClient as unknown as ComposioClient,
+ { apiKey: 'key', provider },
+ 'sess_123',
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
+ undefined,
+ buildLocalToolsMap([customToolHandle]),
+ 'user_1'
+ );
+
+ await session.tools();
+
+ // Now simulate the LLM calling COMPOSIO_MULTI_EXECUTE_TOOL with a local tool
+ const executeFn = (provider as any)._capturedExecuteFn;
+ expect(executeFn).toBeDefined();
+
+ const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
+ tool_slug: 'LOCAL_GET_USER_CONTEXT',
+ arguments: { category: 'test' },
+ });
+
+ expect(result.data).toEqual({ local_result: true });
+ expect(localExecute).toHaveBeenCalledWith(
+ { category: 'test' },
+ expect.objectContaining({ userId: 'user_1', sessionId: 'sess_123' })
+ );
+ });
+
+ it('should route remote tools via COMPOSIO_MULTI_EXECUTE_TOOL to backend', async () => {
+ const provider = new MockProvider();
+ provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
+ (provider as any)._capturedExecuteFn = executeFn;
+ return 'wrapped';
+ });
+
+ const session = new ToolRouterSession(
+ mockClient as unknown as ComposioClient,
+ { apiKey: 'key', provider },
+ 'sess_123',
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
+ undefined,
+ buildLocalToolsMap([customToolHandle]),
+ 'user_1'
+ );
+
+ await session.tools();
+
+ const executeFn = (provider as any)._capturedExecuteFn;
+ const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
+ tool_slug: 'GMAIL_SEND_EMAIL',
+ arguments: { to: '[email protected]' },
+ });
+
+ // Should have gone to remote via executeMetaTool
+ expect(result.data).toEqual({ remote: true });
+ expect(localExecute).not.toHaveBeenCalled();
+ });
+
+ it('should route non-MULTI_EXECUTE meta tools to backend', async () => {
+ const provider = new MockProvider();
+ provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
+ (provider as any)._capturedExecuteFn = executeFn;
+ return 'wrapped';
+ });
+
+ const session = new ToolRouterSession(
+ mockClient as unknown as ComposioClient,
+ { apiKey: 'key', provider },
+ 'sess_123',
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
+ undefined,
+ buildLocalToolsMap([customToolHandle]),
+ 'user_1'
+ );
+
+ await session.tools();
+
+ const executeFn = (provider as any)._capturedExecuteFn;
+ const result = await executeFn('COMPOSIO_SEARCH_TOOLS', {
+ queries: [{ use_case: 'send email' }],
+ });
+
+ // COMPOSIO_SEARCH_TOOLS always goes remote
+ expect(result.data).toEqual({ remote: true });
+ });
+
+ it('should use standard wrapToolsForToolRouter when no local tools', async () => {
+ const session = new ToolRouterSession(
+ mockClient as unknown as ComposioClient,
+ { apiKey: 'key', provider: new MockProvider() },
+ 'sess_123',
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' }
+ // No localToolsMap, no userId
+ );
+
+ const result = await session.tools();
+
+ // Should use the standard path
+ expect(result).toBe('wrapped-tools');
+ });
+ });
+
+ describe('multiple custom tools', () => {
+ it('should route each tool to its correct execute function', async () => {
+ const session = createSession(mockClient, [customToolHandle, sessionToolHandle]);
+
+ // First tool
+ await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
+ expect(localExecute).toHaveBeenCalled();
+ expect(sessionExecute).not.toHaveBeenCalled();
+
+ localExecute.mockClear();
+
+ // Second tool
+ await session.execute('GET_AD_ACCOUNTS', { fields: 'id' });
+ expect(sessionExecute).toHaveBeenCalled();
+ expect(localExecute).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/ts/packages/core/tsdown.config.ts b/ts/packages/core/tsdown.config.ts
index 459fc6d91..4721e6e89 100644
--- a/ts/packages/core/tsdown.config.ts
+++ b/ts/packages/core/tsdown.config.ts
@@ -7,6 +7,7 @@ export default defineConfig({
copy: [{ from: 'pack/generated/*', to: '.', flatten: false }],
entry: [
'src/index.ts',
+ 'src/experimental/index.ts',
// #platform
'src/platform/node.ts',