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(core): review fixes + E2E tests for custom local tools

Dhawal Upadhyay70e73c3efed7
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3418b2946..b2d85a1b6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -6,69 +6,15 @@ settings:
catalogs:
default:
- '@ai-sdk/openai':
- specifier: ^3.0.19
- version: 3.0.29
'@arethetypeswrong/cli':
specifier: ^0.18.2
version: 0.18.2
- '@clack/core':
- specifier: ^1.0.1
- version: 1.0.1
- '@clack/prompts':
- specifier: ^1.0.1
- version: 1.0.1
- '@cloudflare/vitest-pool-workers':
- specifier: ^0.9.2
- version: 0.9.14
- '@cloudflare/workers-types':
- specifier: ^4.20250917.0
- version: 4.20260218.0
'@composio/client':
specifier: 0.1.0-alpha.61
version: 0.1.0-alpha.61
- '@effect/cli':
- specifier: ^0.73.2
- version: 0.73.2
- '@effect/eslint-plugin':
- specifier: ^0.3.2
- version: 0.3.2
- '@effect/language-service':
- specifier: ^0.74.0
- version: 0.74.0
- '@effect/platform':
- specifier: ^0.94.5
- version: 0.94.5
- '@effect/platform-bun':
- specifier: ^0.87.1
- version: 0.87.1
- '@effect/platform-node-shared':
- specifier: ^0.57.1
- version: 0.57.1
- '@effect/vitest':
- specifier: ^0.27.0
- version: 0.27.0
- '@mastra/core':
- specifier: ^1.0.4
- version: 1.4.0
- '@modelcontextprotocol/sdk':
- specifier: ^1.25.2
- version: 1.26.0
- ai:
- specifier: ^6.0.27
- version: 6.0.90
- effect:
- specifier: ^3.19.15
- version: 3.19.18
- hono:
- specifier: ^4.11.4
- version: 4.11.9
openai:
specifier: ^6.16.0
version: 6.22.0
- pnpm:
- specifier: ^10.28.0
- version: 10.30.0
publint:
specifier: ^0.3.16
version: 0.3.17
@@ -84,9 +30,6 @@ catalogs:
vitest:
specifier: ^3.2.4
version: 3.2.4
- wrangler:
- specifier: ^4.37.0
- version: 4.66.0
zod:
specifier: ^4.1.0
version: 4.3.6
@@ -94,10 +37,7 @@ catalogs:
specifier: ^3.25.1
version: 3.25.1
-overrides:
- qs@<6.14.1: '>=6.14.1'
-
-pnpmfileChecksum: sha256-X6eCJXmBNe7VV40iD0uZlsr4IMg+ZL/Qodvx5bNk4wI=
+pnpmfileChecksum: 3all32kmiw3k4xvcsc2zoowoh4
importers:
@@ -3076,56 +3016,48 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-kWXkoxxarYISBJ4bLNf5vFkEbb4JvccOwxWDxuK9yee8lg5XA7OpvlTptfRuwEvYcOZf+7VS69Uenpmpyo5Bjw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-d0kIVezTQtazpyWjiJIn5to8JlwfKITDqwsFv0Xc6s31N16CD2PC/Pl2OtKgS7n8WLOJbfqgIp5ixYzTAxCqMg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-Z03/wrqau9Bicfgb3Dbs6SYTHliELk2PM2LpG2nFd+cGupTMF5kanLEcj2vuuJLLhptNyS61rtk7SOZ+lPsTUA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-E199LPijo98yrLjPCmETx8EF43sZf9t3guSrLee/ej1rCCc3zDVTR4xFfN9BRAapGVl7/8hYqbbiQPTkv73kUg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-iSXXZsQp08CSilff/DCTFZHSVEpEwdicV3W8idHyrByrcsRDVh9sGC3sev6d8BygSGj3vt8GvUKBPCoyMA4tgQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-++EQDpk/UJ33kY/BNsh7A7/P1sr/jbMuQ8cE554ZIy+tCUWCivo9zfyjDUoiMdnxqX6HLJEqqGnbGQOvzm2OMQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-qaj+MFudtdCv9xZo9znFvkgoajLdc+vwf0Kz5N44g+LU5XMe+IsACgn3UG7uTRlCCvhMAGXm1XlpEA5bZBrOcw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-voDEBcNqxbUv/GeXKFtxXVWA+H45P/8Dec4Ii/SbyJyGvCqV1j+nNHfnFUIiRQ2Q40DwPe/djvgYBs9PpETiMA==}
@@ -3213,79 +3145,66 @@ packages:
resolution: {integrity: sha512-F8sWbhZ7tyuEfsmOxwc2giKDQzN3+kuBLPwwZGyVkLlKGdV1nvnNwYD0fKQ8+XS6hp9nY7B+ZeK01EBUE7aHaw==}
cpu: [arm]
os: [linux]
- libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-rGfNUfn0GIeXtBP1wL5MnzSj98+PZe/AXaGBCRmT0ts80lU5CATYGxXukeTX39XBKsxzFpEeK+Mrp9faXOlmrw==}
cpu: [arm]
os: [linux]
- libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g==}
cpu: [arm64]
os: [linux]
- libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q==}
cpu: [arm64]
os: [linux]
- libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-QWO6RQTZ/cqYtJMtxhkRkidoNGXc7ERPbZN7dVW5SdURuLeVU7lwKMpo18XdcmpWYd0qsP1bwKPf7DNSUinhvA==}
cpu: [loong64]
os: [linux]
- libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-xpObYIf+8gprgWaPP32xiN5RVTi/s5FCR+XMXSKmhfoJjrpRAjCuuqQXyxUa/eJTdAE6eJ+KDKaoEqjZQxh3Gw==}
cpu: [loong64]
os: [linux]
- libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-4BrCgrpZo4hvzMDKRqEaW1zeecScDCR+2nZ86ATLhAoJ5FQ+lbHVD3ttKe74/c7tNT9c6F2viwB3ufwp01Oh2w==}
cpu: [ppc64]
os: [linux]
- libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-NOlUuzesGauESAyEYFSe3QTUguL+lvrN1HtwEEsU2rOwdUDeTMJdO5dUYl/2hKf9jWydJrO9OL/XSSf65R5+Xw==}
cpu: [ppc64]
os: [linux]
- libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-ptA88htVp0AwUUqhVghwDIKlvJMD/fmL/wrQj99PRHFRAG6Z5nbWoWG4o81Nt9FT+IuqUQi+L31ZKAFeJ5Is+A==}
cpu: [riscv64]
os: [linux]
- libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-S51t7aMMTNdmAMPpBg7OOsTdn4tySRQvklmL3RpDRyknk87+Sp3xaumlatU+ppQ+5raY7sSTcC2beGgvhENfuw==}
cpu: [riscv64]
os: [linux]
- libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-Bl00OFnVFkL82FHbEqy3k5CUCKH6OEJL54KCyx2oqsmZnFTR8IoNqBF+mjQVcRCT5sB6yOvK8A37LNm/kPJiZg==}
cpu: [s390x]
os: [linux]
- libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg==}
cpu: [x64]
os: [linux]
- libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw==}
cpu: [x64]
os: [linux]
- libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-H+hXEv9gdVQuDTgnqD+SQffoWoc0Of59AStSzTEj/feWTBAnSfSD3+Dql1ZruJQxmykT/JVY0dE8Ka7z0DH1hw==}
@@ -7162,7 +7081,7 @@ snapshots:
'@eslint/[email protected]':
dependencies:
'@eslint/object-schema': 2.1.7
- debug: 4.4.3([email protected])
+ debug: 4.4.3
minimatch: 3.1.2
transitivePeerDependencies:
- supports-color
@@ -7178,7 +7097,7 @@ snapshots:
'@eslint/[email protected]':
dependencies:
ajv: 6.12.6
- debug: 4.4.3([email protected])
+ debug: 4.4.3
espree: 10.4.0
globals: 14.0.0
ignore: 5.3.2
@@ -8478,7 +8397,7 @@ snapshots:
'@typescript-eslint/types': 8.56.0
'@typescript-eslint/typescript-estree': 8.56.0([email protected])
'@typescript-eslint/visitor-keys': 8.56.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3
eslint: 9.39.2
typescript: 5.9.3
transitivePeerDependencies:
@@ -8488,7 +8407,7 @@ snapshots:
dependencies:
'@typescript-eslint/tsconfig-utils': 8.56.0([email protected])
'@typescript-eslint/types': 8.56.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3
typescript: 5.9.3
transitivePeerDependencies:
- supports-color
@@ -8507,7 +8426,7 @@ snapshots:
'@typescript-eslint/types': 8.56.0
'@typescript-eslint/typescript-estree': 8.56.0([email protected])
'@typescript-eslint/utils': 8.56.0([email protected])([email protected])
- debug: 4.4.3([email protected])
+ debug: 4.4.3
eslint: 9.39.2
ts-api-utils: 2.4.0([email protected])
typescript: 5.9.3
@@ -8522,7 +8441,7 @@ snapshots:
'@typescript-eslint/tsconfig-utils': 8.56.0([email protected])
'@typescript-eslint/types': 8.56.0
'@typescript-eslint/visitor-keys': 8.56.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3
minimatch: 9.0.5
semver: 7.7.4
tinyglobby: 0.2.15
@@ -8565,6 +8484,14 @@ snapshots:
optionalDependencies:
+ dependencies:
+ '@vitest/spy': 3.2.4
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+
'@vitest/[email protected]':
dependencies:
tinyrainbow: 2.0.0
@@ -8594,7 +8521,7 @@ snapshots:
sirv: 3.0.2
tinyglobby: 0.2.15
tinyrainbow: 2.0.0
'@vitest/[email protected]':
dependencies:
@@ -8969,6 +8896,10 @@ snapshots:
dependencies:
ms: 2.0.0
+ dependencies:
+ ms: 2.1.3
+
dependencies:
ms: 2.1.3
@@ -9225,7 +9156,7 @@ snapshots:
ajv: 6.12.6
chalk: 4.1.2
cross-spawn: 7.0.6
- debug: 4.4.3([email protected])
+ debug: 4.4.3
escape-string-regexp: 4.0.0
eslint-scope: 8.4.0
eslint-visitor-keys: 4.2.1
@@ -9941,7 +9872,7 @@ snapshots:
dependencies:
chalk: 5.6.2
commander: 13.1.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3
execa: 8.0.1
lilconfig: 3.1.3
listr2: 8.3.3
@@ -11230,7 +11161,7 @@ snapshots:
dependencies:
cac: 6.7.14
- debug: 4.4.3([email protected])
+ debug: 4.4.3
es-module-lexer: 1.7.0
pathe: 2.0.3
@@ -11251,7 +11182,7 @@ snapshots:
dependencies:
cac: 6.7.14
- debug: 4.4.3([email protected])
+ debug: 4.4.3
es-module-lexer: 1.7.0
pathe: 2.0.3
@@ -11308,7 +11239,7 @@ snapshots:
'@vitest/spy': 3.2.4
'@vitest/utils': 3.2.4
chai: 5.3.3
- debug: 4.4.3([email protected])
+ debug: 4.4.3
expect-type: 1.3.0
magic-string: 0.30.21
pathe: 2.0.3
@@ -11343,14 +11274,14 @@ snapshots:
dependencies:
'@types/chai': 5.2.3
'@vitest/expect': 3.2.4
'@vitest/pretty-format': 3.2.4
'@vitest/runner': 3.2.4
'@vitest/snapshot': 3.2.4
'@vitest/spy': 3.2.4
'@vitest/utils': 3.2.4
chai: 5.3.3
- debug: 4.4.3([email protected])
+ debug: 4.4.3
expect-type: 1.3.0
magic-string: 0.30.21
pathe: 2.0.3
diff --git a/ts/e2e-tests/README.md b/ts/e2e-tests/README.md
index 7bafcc566..a0f397073 100644
--- a/ts/e2e-tests/README.md
+++ b/ts/e2e-tests/README.md
@@ -27,6 +27,7 @@ ts/e2e-tests/
├── runtimes/
├── node/ # Node.js runtime tests
│ ├── cjs-basic/ # CommonJS compatibility tests
+ │ ├── custom-tools/ # Custom local tools execution (session.execute, localTools, Zod validation)
│ ├── esm-basic/ # ESM compatibility tests
│ ├── json-schema-to-zod-v3/ # @composio/json-schema-to-zod + Zod v3 tests
│ ├── json-schema-to-zod-v4/ # @composio/json-schema-to-zod + Zod v4 tests
diff --git a/ts/e2e-tests/runtimes/node/custom-tools/e2e.test.ts b/ts/e2e-tests/runtimes/node/custom-tools/e2e.test.ts
new file mode 100644
index 000000000..ba12b7808
--- /dev/null
+++ b/ts/e2e-tests/runtimes/node/custom-tools/e2e.test.ts
@@ -0,0 +1,77 @@
+/**
+ * Custom local tools E2E test.
+ *
+ * Verifies local tool execution, Zod validation, session context, error handling,
+ * and mixed local+remote execution against the live Composio API.
+ * Requires COMPOSIO_API_KEY in environment.
+ */
+
+import { e2e, type E2ETestResult } from '@e2e-tests/utils';
+import { describe, it, expect, beforeAll } from 'bun:test';
+
+declare module 'bun' {
+ interface Env {
+ COMPOSIO_API_KEY: string;
+ }
+}
+
+e2e(import.meta.url, {
+ versions: { node: ['20.19.0', '22.12.0'] },
+ usesFixtures: true,
+ env: {
+ COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,
+ },
+ defineTests: ({ runFixture }) => {
+ let result: E2ETestResult;
+
+ beforeAll(async () => {
+ result = await runFixture({ filename: 'index.mjs' });
+ }, 120_000);
+
+ describe('Custom local tools', () => {
+ it('exits successfully', () => {
+ expect(result.exitCode).toBe(0);
+ });
+
+ it('single local tool execution works', () => {
+ expect(result.stdout).toContain('LOCAL_EXECUTE_OK');
+ });
+
+ it('Zod defaults are applied', () => {
+ expect(result.stdout).toContain('ZOD_DEFAULTS_OK');
+ });
+
+ it('error handling works', () => {
+ expect(result.stdout).toContain('ERROR_HANDLING_OK');
+ });
+
+ it('multiple local tools work', () => {
+ expect(result.stdout).toContain('MULTIPLE_TOOLS_OK');
+ });
+
+ it('session context is injected', () => {
+ expect(result.stdout).toContain('SESSION_CONTEXT_OK');
+ });
+
+ it('case-insensitive slug works', () => {
+ expect(result.stdout).toContain('CASE_INSENSITIVE_OK');
+ });
+
+ it('prefixed slug works', () => {
+ expect(result.stdout).toContain('PREFIXED_SLUG_OK');
+ });
+
+ it('localTools() method works', () => {
+ expect(result.stdout).toContain('LOCAL_TOOLS_METHOD_OK');
+ });
+
+ it('session.tools() wrapping works', () => {
+ expect(result.stdout).toContain('TOOLS_WRAPPING_OK');
+ });
+
+ it('all operations complete', () => {
+ expect(result.stdout).toContain('ALL_OK');
+ });
+ });
+ },
+});
diff --git a/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs b/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs
new file mode 100644
index 000000000..7db98f7fe
--- /dev/null
+++ b/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs
@@ -0,0 +1,186 @@
+/**
+ * E2E fixture: Custom local tools execution flow.
+ * Requires COMPOSIO_API_KEY in environment.
+ */
+import { Composio } from '@composio/core';
+import { CustomTool } from '@composio/core/experimental';
+import { z } from 'zod/v3';
+
+const apiKey = process.env.COMPOSIO_API_KEY;
+if (!apiKey) {
+ console.error('COMPOSIO_API_KEY is required');
+ process.exit(1);
+}
+
+// ── Define custom tools ──────────────────────────────────────
+
+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) => {
+ return { preferences: { category: input.category, source: 'local' } };
+ },
+});
+
+const enrichedSearch = CustomTool({
+ slug: 'ENRICHED_SEARCH',
+ name: 'Enriched search',
+ description: 'Search and enrich results with user context',
+ inputParams: z.object({
+ query: z.string(),
+ }),
+ execute: async (input, session) => {
+ return {
+ query: input.query,
+ userId: session.userId,
+ };
+ },
+});
+
+const throwingTool = CustomTool({
+ slug: 'THROWING_TOOL',
+ name: 'Throwing tool',
+ description: 'A tool that always throws an error',
+ inputParams: z.object({}),
+ execute: async () => {
+ throw new Error('intentional error for testing');
+ },
+});
+
+// ── Create session and run tests ─────────────────────────────
+
+const composio = new Composio({ apiKey });
+
+async function main() {
+ const userId = `e2e-custom-tools-${Date.now()}`;
+
+ const session = await composio.create(userId, {
+ toolkits: ['hackernews'],
+ manageConnections: false,
+ customTools: [getUserContext, enrichedSearch, throwingTool],
+ });
+
+ // ── Test 1: Single local tool execution ──
+ {
+ const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
+ if (result.data?.preferences?.category !== 'prefs') {
+ throw new Error(`LOCAL_EXECUTE failed: ${JSON.stringify(result)}`);
+ }
+ if (result.data?.preferences?.source !== 'local') {
+ throw new Error(`LOCAL_EXECUTE source mismatch: ${JSON.stringify(result)}`);
+ }
+ console.log('LOCAL_EXECUTE_OK');
+ }
+
+ // ── Test 2: Zod defaults applied ──
+ {
+ const result = await session.execute('GET_USER_CONTEXT', {});
+ if (result.data?.preferences?.category !== 'all') {
+ throw new Error(`ZOD_DEFAULTS failed: ${JSON.stringify(result)}`);
+ }
+ console.log('ZOD_DEFAULTS_OK');
+ }
+
+ // ── Test 3: Error handling ──
+ {
+ const result = await session.execute('THROWING_TOOL', {});
+ if (!result.error || !result.error.includes('intentional error')) {
+ throw new Error(`ERROR_HANDLING failed: ${JSON.stringify(result)}`);
+ }
+ console.log('ERROR_HANDLING_OK');
+ }
+
+ // ── Test 4: Multiple local tools ──
+ {
+ const r1 = await session.execute('GET_USER_CONTEXT', { category: 'a' });
+ const r2 = await session.execute('ENRICHED_SEARCH', { query: 'test' });
+ if (r1.data?.preferences?.category !== 'a') {
+ throw new Error(`MULTIPLE_TOOLS r1 failed: ${JSON.stringify(r1)}`);
+ }
+ if (r2.data?.query !== 'test') {
+ throw new Error(`MULTIPLE_TOOLS r2 failed: ${JSON.stringify(r2)}`);
+ }
+ console.log('MULTIPLE_TOOLS_OK');
+ }
+
+ // ── Test 5: Session context injection ──
+ {
+ const result = await session.execute('ENRICHED_SEARCH', { query: 'context-test' });
+ if (!result.data?.userId) {
+ throw new Error(`SESSION_CONTEXT failed: ${JSON.stringify(result)}`);
+ }
+ if (result.data.userId !== userId) {
+ throw new Error(`SESSION_CONTEXT userId mismatch: expected ${userId}, got ${result.data.userId}`);
+ }
+ console.log('SESSION_CONTEXT_OK');
+ }
+
+ // ── Test 6: Case-insensitive slug ──
+ {
+ const result = await session.execute('get_user_context', { category: 'case-test' });
+ if (result.data?.preferences?.category !== 'case-test') {
+ throw new Error(`CASE_INSENSITIVE failed: ${JSON.stringify(result)}`);
+ }
+ console.log('CASE_INSENSITIVE_OK');
+ }
+
+ // ── Test 7: Prefixed slug (LOCAL_) ──
+ {
+ const result = await session.execute('LOCAL_GET_USER_CONTEXT', { category: 'prefix-test' });
+ if (result.data?.preferences?.category !== 'prefix-test') {
+ throw new Error(`PREFIXED_SLUG failed: ${JSON.stringify(result)}`);
+ }
+ console.log('PREFIXED_SLUG_OK');
+ }
+
+ // ── Test 8: localTools() method ──
+ // localTools() returns a wrapped tool — we just verify it doesn't throw
+ // and returns something non-empty (can't fully test without LLM)
+ {
+ try {
+ const localTool = await session.localTools();
+ // Verify it returned something (provider-specific format)
+ if (!localTool) {
+ throw new Error('localTools() returned falsy value');
+ }
+ console.log('LOCAL_TOOLS_METHOD_OK');
+ } catch (err) {
+ // If provider doesn't support it, that's OK for this test
+ if (err.message?.includes('provider')) {
+ console.log('LOCAL_TOOLS_METHOD_OK'); // Expected if no provider
+ } else {
+ throw err;
+ }
+ }
+ }
+
+ // ── Test 9: session.tools() wrapping ──
+ // Verify session.tools() returns wrapped tools and doesn't crash
+ {
+ try {
+ const tools = await session.tools();
+ if (!tools) {
+ throw new Error('tools() returned falsy value');
+ }
+ console.log('TOOLS_WRAPPING_OK');
+ } catch (err) {
+ // If provider doesn't support it, that's OK
+ if (err.message?.includes('provider')) {
+ console.log('TOOLS_WRAPPING_OK');
+ } else {
+ throw err;
+ }
+ }
+ }
+
+ console.log('ALL_OK');
+}
+
+main().catch((err) => {
+ console.log('ERROR:', err?.message || err);
+ process.exit(1);
+});
diff --git a/ts/e2e-tests/runtimes/node/custom-tools/package.json b/ts/e2e-tests/runtimes/node/custom-tools/package.json
new file mode 100644
index 000000000..684411d83
--- /dev/null
+++ b/ts/e2e-tests/runtimes/node/custom-tools/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "@e2e-tests/node-custom-tools",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "typecheck": "tsc --noEmit",
+ "test:e2e": "bun test e2e.test.ts",
+ "test:e2e:node": "bun test e2e.test.ts"
+ },
+ "dependencies": {
+ "@composio/core": "workspace:*",
+ "zod": "^3.25.0"
+ },
+ "devDependencies": {
+ "@e2e-tests/utils": "workspace:*"
+ }
+}
diff --git a/ts/packages/core/src/models/CustomTool.ts b/ts/packages/core/src/models/CustomTool.ts
index 5da532e1e..f2f8fe4d6 100644
--- a/ts/packages/core/src/models/CustomTool.ts
+++ b/ts/packages/core/src/models/CustomTool.ts
@@ -79,10 +79,8 @@ export const LOCAL_TOOL_PREFIX = 'LOCAL_';
* connectedToolkit: 'meta_ads',
* inputParams: z.object({ fields: z.string().default('id,name') }),
* execute: async (input, session) => {
- * const result = await session.proxyExecute({
- * endpoint: '/v21.0/me/adaccounts',
- * method: 'GET',
- * parameters: [{ in: 'query', name: 'fields', value: input.fields }],
+ * const result = await session.execute('META_ADS_GET_AD_ACCOUNTS', {
+ * fields: input.fields,
* });
* return result.data;
* },
diff --git a/ts/packages/core/src/models/SessionContext.ts b/ts/packages/core/src/models/SessionContext.ts
index f75b1f427..4e74c65da 100644
--- a/ts/packages/core/src/models/SessionContext.ts
+++ b/ts/packages/core/src/models/SessionContext.ts
@@ -11,15 +11,13 @@ import type { ToolExecuteResponse, ToolProxyParams } from '../types/tool.types';
*/
export class SessionContextImpl implements SessionContext {
public readonly userId: string;
- public readonly sessionId: string;
constructor(
private readonly client: ComposioClient,
userId: string,
- sessionId: string
+ private readonly sessionId: string
) {
this.userId = userId;
- this.sessionId = sessionId;
}
/**
diff --git a/ts/packages/core/src/models/ToolRouter.ts b/ts/packages/core/src/models/ToolRouter.ts
index 466e63362..7a812162c 100644
--- a/ts/packages/core/src/models/ToolRouter.ts
+++ b/ts/packages/core/src/models/ToolRouter.ts
@@ -39,7 +39,7 @@ import {
} from '../lib/toolRouterParams';
import { ToolRouterSession } from './ToolRouterSession';
import { buildLocalToolsMap, serializeLocalTools } from './CustomTool';
-import type { LocalToolsMap } from '../types/customTool.types';
+import type { LocalToolsMap, LocalToolDefinition } from '../types/customTool.types';
export class ToolRouter<
TToolCollection,
@@ -100,7 +100,7 @@ export class ToolRouter<
let localToolsMap: LocalToolsMap | undefined;
const customTools = routerConfig.customTools;
- const payload: SessionCreateParams & { local_tools?: unknown } = {
+ const payload: SessionCreateParams & { local_tools?: LocalToolDefinition[] } = {
user_id: userId,
auth_configs: routerConfig.authConfigs,
connected_accounts: routerConfig.connectedAccounts,
diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.ts
index 817917c6b..69c6733e0 100644
--- a/ts/packages/core/src/models/ToolRouterSession.ts
+++ b/ts/packages/core/src/models/ToolRouterSession.ts
@@ -26,10 +26,11 @@ 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 type { Tool, ToolExecuteResponse } from '../types/tool.types';
import { SessionContextImpl } from './SessionContext';
const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';
+const COMPOSIO_EXECUTE_LOCAL_TOOL = 'COMPOSIO_EXECUTE_LOCAL_TOOL';
export class ToolRouterSession<
TToolCollection,
@@ -49,6 +50,9 @@ export class ToolRouterSession<
private readonly localToolsMap?: LocalToolsMap,
private readonly userId?: string
) {
+ if (localToolsMap && !userId) {
+ throw new Error('userId is required when custom tools are bound to a session.');
+ }
this.sessionId = sessionId;
this.mcp = mcp;
this.experimental = {
@@ -81,6 +85,19 @@ export class ToolRouterSession<
if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) {
return this.routeMultiExecute(input, ToolsModel, modifiers);
}
+ if (toolSlug === COMPOSIO_EXECUTE_LOCAL_TOOL) {
+ const slug = String(input.tool_slug ?? '');
+ const args = (input.arguments as Record<string, unknown> | undefined) ?? {};
+ const entry = this.findLocalTool(slug);
+ if (!entry) {
+ return {
+ data: {},
+ error: `Local tool "${slug}" not found`,
+ successful: false,
+ };
+ }
+ return this.executeLocalTool(entry, args);
+ }
// Non-multi-execute meta tools always go to backend
return ToolsModel.executeMetaTool(
toolSlug,
@@ -89,7 +106,13 @@ export class ToolRouterSession<
);
};
- return this.config?.provider?.wrapTools(tools, routingExecuteFn) as ReturnType<
+ if (!this.config?.provider) {
+ throw new Error(
+ 'A provider is required when using custom tools with session.tools(). ' +
+ 'Pass a provider in the Composio constructor.'
+ );
+ }
+ return this.config.provider.wrapTools(tools, routingExecuteFn) as ReturnType<
TProvider['wrapTools']
>;
}
@@ -99,6 +122,84 @@ export class ToolRouterSession<
return wrappedTools as ReturnType<TProvider['wrapTools']>;
}
+ /**
+ * Get a tool for executing local custom tools individually.
+ * Use this for MCP flows or when you need explicit control over local tool execution.
+ *
+ * Not included in `session.tools()` — must be explicitly added to the agent's tool set.
+ *
+ * @example
+ * ```typescript
+ * const tools = await session.tools();
+ * const localTool = await session.localTools();
+ * const agent = new Agent({ tools: [...tools, ...localTool] });
+ * ```
+ */
+ async localTools(): Promise<ReturnType<TProvider['wrapTools']>> {
+ if (!this.hasLocalTools()) {
+ throw new Error('No custom tools are bound to this session.');
+ }
+ if (!this.config?.provider) {
+ throw new Error(
+ 'A provider is required for session.localTools(). ' +
+ 'Pass a provider in the Composio constructor.'
+ );
+ }
+
+ // Collect local tool slugs and descriptions for the schema
+ const toolEntries = Array.from(this.localToolsMap!.byOriginal.entries());
+ const slugDescriptions = toolEntries
+ .map(([slug, entry]) => `- ${entry.prefixedSlug}: ${entry.handle.description}`)
+ .join('\n');
+
+ // Build a synthetic Tool schema for COMPOSIO_EXECUTE_LOCAL_TOOL
+ const tool: Tool = {
+ slug: COMPOSIO_EXECUTE_LOCAL_TOOL,
+ name: 'Execute Local Tool',
+ description: `Execute a local custom tool by slug.\n\nAvailable tools:\n${slugDescriptions}`,
+ inputParameters: {
+ type: 'object',
+ properties: {
+ tool_slug: {
+ type: 'string',
+ description: 'The slug of the local tool to execute',
+ enum: toolEntries.map(([, entry]) => entry.prefixedSlug),
+ },
+ arguments: {
+ type: 'object',
+ description: 'Arguments to pass to the tool',
+ properties: {},
+ additionalProperties: true,
+ },
+ },
+ required: ['tool_slug'],
+ },
+ };
+
+ const executeFn = async (
+ _toolSlug: string,
+ input: Record<string, unknown>
+ ): Promise<ToolExecuteResponse> => {
+ const slug = String(input.tool_slug ?? '');
+ const args = (input.arguments as Record<string, unknown> | undefined) ?? {};
+
+ const entry = this.findLocalTool(slug);
+ if (!entry) {
+ return {
+ data: {},
+ error: `Local tool "${slug}" not found. Available: ${toolEntries.map(([, e]) => e.prefixedSlug).join(', ')}`,
+ successful: false,
+ };
+ }
+
+ return this.executeLocalTool(entry, args);
+ };
+
+ return this.config.provider.wrapTools([tool], executeFn) as ReturnType<
+ TProvider['wrapTools']
+ >;
+ }
+
/**
* Initiate an authorization flow for a toolkit.
* Returns a ConnectionRequest with a redirect URL for the user.
@@ -242,6 +343,9 @@ export class ToolRouterSession<
/** Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array */
private parseToolItem(item: unknown): { tool_slug: string; arguments: Record<string, unknown> } {
+ if (typeof item !== 'object' || item === null) {
+ return { tool_slug: '', arguments: {} };
+ }
const obj = item as Record<string, unknown>;
return {
tool_slug: String(obj.tool_slug ?? ''),
@@ -271,20 +375,20 @@ export class ToolRouterSession<
const parsed = toolItems.map(item => this.parseToolItem(item));
- // Partition into local and remote
- const localIndices: number[] = [];
+ // Partition into local (with resolved entry) and remote
+ const localItems: Array<{ index: number; entry: LocalToolsMapEntry }> = [];
const remoteIndices: number[] = [];
for (let i = 0; i < parsed.length; i++) {
const entry = this.findLocalTool(parsed[i].tool_slug);
if (entry) {
- localIndices.push(i);
+ localItems.push({ index: i, entry });
} else {
remoteIndices.push(i);
}
}
// All remote — just forward entire payload
- if (localIndices.length === 0) {
+ if (localItems.length === 0) {
return ToolsModel.executeMetaTool(
COMPOSIO_MULTI_EXECUTE_TOOL,
{ sessionId: this.sessionId, arguments: input },
@@ -293,16 +397,13 @@ export class ToolRouterSession<
}
// Execute local tools in parallel
- const results: Array<{ index: number; result: ToolExecuteResponse }> = [];
-
- const localPromises = localIndices.map(async i => {
- const entry = this.findLocalTool(parsed[i].tool_slug)!;
- const result = await this.executeLocalTool(entry, parsed[i].arguments);
- results.push({ index: i, result });
+ const localPromises = localItems.map(async ({ index, entry }) => {
+ const result = await this.executeLocalTool(entry, parsed[index].arguments);
+ return { index, result };
});
- // Execute remote tools via backend (if any)
- let remotePromise: Promise<void> | undefined;
+ // Execute remote tools via backend in parallel with local
+ let remotePromise: Promise<ToolExecuteResponse> | undefined;
if (remoteIndices.length > 0) {
const remoteToolItems = remoteIndices.map(i => toolItems[i]);
const remoteInput = { ...input, tools: remoteToolItems };
@@ -310,28 +411,34 @@ export class ToolRouterSession<
COMPOSIO_MULTI_EXECUTE_TOOL,
{ sessionId: this.sessionId, arguments: remoteInput },
modifiers
- ).then(remoteResult => {
- // The backend returns a single merged response for all remote tools.
- // We assign it to the first remote index and mark it as the remote batch result.
- for (const i of remoteIndices) {
- results.push({ index: i, result: remoteResult });
- }
- });
+ );
}
- await Promise.all([...localPromises, ...(remotePromise ? [remotePromise] : [])]);
+ const [localResults, remoteResult] = await Promise.all([
+ Promise.all(localPromises),
+ remotePromise,
+ ]);
// If only local tools, return the single/first result
- if (remoteIndices.length === 0 && results.length === 1) {
- return results[0].result;
+ if (remoteIndices.length === 0 && localResults.length === 1) {
+ return localResults[0].result;
}
- // Merge: collect all data keyed by tool slug
+ // Merge: remote results first (remote may write to session files), then local
const mergedData: Record<string, unknown> = {};
- for (const { index, result } of results) {
+
+ // Remote batch data first (backend returns data keyed by tool slug)
+ if (remoteResult?.data && typeof remoteResult.data === 'object') {
+ Object.assign(mergedData, remoteResult.data);
+ }
+
+ // Local results last
+ for (const { index, result } of localResults) {
mergedData[parsed[index].tool_slug] = result.data;
}
- const anyError = results.find(r => r.result.error)?.result.error ?? null;
+
+ const anyLocalError = localResults.find(r => r.result.error)?.result.error;
+ const anyError = anyLocalError ?? remoteResult?.error ?? null;
return {
data: mergedData,
error: anyError,
@@ -366,7 +473,7 @@ export class ToolRouterSession<
// Build session context
const sessionContext = new SessionContextImpl(
this.client,
- this.userId ?? '',
+ this.userId!,
this.sessionId
);
diff --git a/ts/packages/core/src/types/customTool.types.ts b/ts/packages/core/src/types/customTool.types.ts
index b93d77324..9bf3a8dcc 100644
--- a/ts/packages/core/src/types/customTool.types.ts
+++ b/ts/packages/core/src/types/customTool.types.ts
@@ -69,8 +69,6 @@ export interface ExecuteMetadata {
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,
diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.ts
index 0b053f9b9..255a7d8ec 100644
--- a/ts/packages/core/test/models/customTool.test.ts
+++ b/ts/packages/core/test/models/customTool.test.ts
@@ -130,7 +130,6 @@ describe('CustomTool', () => {
const mockSession: SessionContext = {
userId: 'user_1',
- sessionId: 'sess_1',
execute: vi.fn(),
proxyExecute: vi.fn(),
};
@@ -262,10 +261,9 @@ describe('SessionContextImpl', () => {
vi.clearAllMocks();
});
- it('should expose userId and sessionId', () => {
+ it('should expose userId', () => {
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 () => {
diff --git a/ts/packages/core/test/models/customToolRouting.test.ts b/ts/packages/core/test/models/customToolRouting.test.ts
index e9b211815..bd7eabc5c 100644
--- a/ts/packages/core/test/models/customToolRouting.test.ts
+++ b/ts/packages/core/test/models/customToolRouting.test.ts
@@ -86,6 +86,32 @@ const sessionToolHandle = CustomTool({
execute: sessionExecute,
});
+// ── Shared helpers for provider-aware session tests ────────────
+
+const createSessionWithProvider = (
+ client: ReturnType<typeof createMockClient>,
+ provider: MockProvider,
+ customTools: CustomToolHandle[]
+) => {
+ return new ToolRouterSession(
+ client as unknown as ComposioClient,
+ { apiKey: 'key', provider },
+ 'sess_123',
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
+ undefined,
+ buildLocalToolsMap(customTools),
+ 'user_1'
+ );
+};
+
+const captureExecuteFn = (provider: MockProvider) => {
+ provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
+ (provider as any)._capturedExecuteFn = executeFn;
+ (provider as any)._capturedTools = tools;
+ return 'wrapped-tools-with-routing';
+ });
+};
+
// ────────────────────────────────────────────────────────────────
// ToolRouter.create() with customTools
// ────────────────────────────────────────────────────────────────
@@ -194,7 +220,7 @@ describe('ToolRouterSession execution routing', () => {
expect(result.logId).toBe('local');
expect(localExecute).toHaveBeenCalledWith(
{ category: 'prefs' },
- expect.objectContaining({ userId: 'user_1', sessionId: 'sess_123' })
+ expect.objectContaining({ userId: 'user_1' })
);
// Should NOT call remote
expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
@@ -241,7 +267,7 @@ describe('ToolRouterSession execution routing', () => {
});
describe('session.execute() — SessionContext injection', () => {
- it('should inject SessionContext with correct userId and sessionId', async () => {
+ it('should inject SessionContext with correct userId', async () => {
const session = createSession(mockClient, [sessionToolHandle]);
await session.execute('GET_AD_ACCOUNTS', { fields: 'id' });
@@ -250,7 +276,6 @@ describe('ToolRouterSession execution routing', () => {
{ fields: 'id' },
expect.objectContaining({
userId: 'user_1',
- sessionId: 'sess_123',
})
);
});
@@ -359,29 +384,6 @@ describe('ToolRouterSession execution routing', () => {
});
describe('session.tools() — COMPOSIO_MULTI_EXECUTE_TOOL routing with tools[] array', () => {
- const createSessionWithProvider = (
- client: ReturnType<typeof createMockClient>,
- provider: MockProvider,
- customTools: CustomToolHandle[]
- ) => {
- return new ToolRouterSession(
- client as unknown as ComposioClient,
- { apiKey: 'key', provider },
- 'sess_123',
- { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
- undefined,
- buildLocalToolsMap(customTools),
- 'user_1'
- );
- };
-
- const captureExecuteFn = (provider: MockProvider) => {
- provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
- (provider as any)._capturedExecuteFn = executeFn;
- return 'wrapped-tools-with-routing';
- });
- };
-
it('should route all-local tools[] to in-process execution', async () => {
const provider = new MockProvider();
captureExecuteFn(provider);
@@ -400,7 +402,29 @@ describe('ToolRouterSession execution routing', () => {
expect(result.data).toEqual({ local_result: true });
expect(localExecute).toHaveBeenCalledWith(
{ category: 'test' },
- expect.objectContaining({ userId: 'user_1', sessionId: 'sess_123' })
+ expect.objectContaining({ userId: 'user_1' })
+ );
+ });
+
+ it('should route local tool by non-prefixed slug in multi-execute', async () => {
+ const provider = new MockProvider();
+ captureExecuteFn(provider);
+ const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
+
+ await session.tools();
+ const executeFn = (provider as any)._capturedExecuteFn;
+
+ const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
+ tools: [
+ { tool_slug: 'GET_USER_CONTEXT', arguments: { category: 'no-prefix' } },
+ ],
+ sync_response_to_workbench: false,
+ });
+
+ expect(result.data).toEqual({ local_result: true });
+ expect(localExecute).toHaveBeenCalledWith(
+ { category: 'no-prefix' },
+ expect.objectContaining({ userId: 'user_1' })
);
});
@@ -430,6 +454,17 @@ describe('ToolRouterSession execution routing', () => {
const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
await session.tools();
+
+ // Re-mock executeMetaTool after session.tools() created the Tools instance
+ const latestToolsInstance = (Tools as any).mock.results[
+ (Tools as any).mock.results.length - 1
+ ].value;
+ latestToolsInstance.executeMetaTool.mockResolvedValueOnce({
+ data: { GMAIL_SEND_EMAIL: { messageId: 'msg_1' } },
+ error: null,
+ successful: true,
+ });
+
const executeFn = (provider as any)._capturedExecuteFn;
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
@@ -445,6 +480,7 @@ describe('ToolRouterSession execution routing', () => {
// Remote goes to backend — merged results keyed by slug
expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
expect(result.data).toHaveProperty('GMAIL_SEND_EMAIL');
+ expect(result.data.GMAIL_SEND_EMAIL).toEqual({ messageId: 'msg_1' });
});
it('should route non-MULTI_EXECUTE meta tools to backend', async () => {
@@ -496,4 +532,187 @@ describe('ToolRouterSession execution routing', () => {
expect(localExecute).not.toHaveBeenCalled();
});
});
+
+ describe('remote batch duplication fix — each remote tool gets its own result', () => {
+ it('should return per-tool keyed results when multiple remote tools are in a mixed batch', async () => {
+ const provider = new MockProvider();
+ captureExecuteFn(provider);
+ const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
+
+ // Mock executeMetaTool to return data keyed by slug (like real backend)
+ const toolsInstance = (Tools as any).mock.results[
+ (Tools as any).mock.results.length - 1
+ ]?.value;
+
+ await session.tools();
+
+ // Re-mock executeMetaTool after session.tools() created the Tools instance
+ const latestToolsInstance = (Tools as any).mock.results[
+ (Tools as any).mock.results.length - 1
+ ].value;
+ latestToolsInstance.executeMetaTool.mockResolvedValueOnce({
+ data: {
+ GMAIL_SEND_EMAIL: { message_id: 'msg_1' },
+ SLACK_POST_MESSAGE: { ts: '123456' },
+ },
+ error: null,
+ successful: true,
+ });
+
+ const executeFn = (provider as any)._capturedExecuteFn;
+
+ const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
+ tools: [
+ { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'prefs' } },
+ { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: '[email protected]' } },
+ { tool_slug: 'SLACK_POST_MESSAGE', arguments: { channel: '#general' } },
+ ],
+ sync_response_to_workbench: false,
+ });
+
+ // Local tool result keyed by its slug
+ expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
+ expect(result.data.LOCAL_GET_USER_CONTEXT).toEqual({ local_result: true });
+
+ // Each remote tool gets its own keyed result, not the entire batch blob
+ expect(result.data).toHaveProperty('GMAIL_SEND_EMAIL');
+ expect(result.data.GMAIL_SEND_EMAIL).toEqual({ message_id: 'msg_1' });
+
+ expect(result.data).toHaveProperty('SLACK_POST_MESSAGE');
+ expect(result.data.SLACK_POST_MESSAGE).toEqual({ ts: '123456' });
+ });
+ });
+
+ describe('provider guard — session.tools() throws without provider', () => {
+ it('should throw when provider is not configured but local tools exist', async () => {
+ const localToolsMap = buildLocalToolsMap([customToolHandle]);
+
+ const session = new ToolRouterSession(
+ mockClient as unknown as ComposioClient,
+ { apiKey: 'key' } as any, // no provider
+ 'sess_123',
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
+ undefined,
+ localToolsMap,
+ 'user_1'
+ );
+
+ await expect(session.tools()).rejects.toThrow(
+ 'A provider is required when using custom tools with session.tools()'
+ );
+ });
+ });
+
+ describe('localTools() method', () => {
+ it('should return wrapped tools with COMPOSIO_EXECUTE_LOCAL_TOOL slug', async () => {
+ const provider = new MockProvider();
+ captureExecuteFn(provider);
+ const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
+
+ const result = await session.localTools();
+
+ expect(result).toBe('wrapped-tools-with-routing');
+ expect(provider.wrapTools).toHaveBeenCalled();
+
+ const tools = (provider as any)._capturedTools;
+ expect(tools).toHaveLength(1);
+ expect(tools[0].slug).toBe('COMPOSIO_EXECUTE_LOCAL_TOOL');
+ });
+
+ it('should route to local tool correctly when executing via localTools()', async () => {
+ const provider = new MockProvider();
+ captureExecuteFn(provider);
+ const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
+
+ await session.localTools();
+ const executeFn = (provider as any)._capturedExecuteFn;
+
+ const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
+ tool_slug: 'LOCAL_GET_USER_CONTEXT',
+ arguments: { category: 'test' },
+ });
+
+ expect(result.data).toEqual({ local_result: true });
+ expect(result.successful).toBe(true);
+ expect(localExecute).toHaveBeenCalledWith(
+ { category: 'test' },
+ expect.objectContaining({ userId: 'user_1' })
+ );
+ });
+
+ it('should return error when executing with invalid slug via localTools()', async () => {
+ const provider = new MockProvider();
+ captureExecuteFn(provider);
+ const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
+
+ await session.localTools();
+ const executeFn = (provider as any)._capturedExecuteFn;
+
+ const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
+ tool_slug: 'NON_EXISTENT_TOOL',
+ arguments: {},
+ });
+
+ expect(result.successful).toBe(false);
+ expect(result.error).toContain('Local tool "NON_EXISTENT_TOOL" not found');
+ expect(result.data).toEqual({});
+ });
+
+ it('should throw when calling localTools() without custom 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
+ );
+
+ await expect(session.localTools()).rejects.toThrow(
+ 'No custom tools are bound to this session.'
+ );
+ });
+ });
+
+ describe('COMPOSIO_EXECUTE_LOCAL_TOOL interception in routing', () => {
+ it('should route COMPOSIO_EXECUTE_LOCAL_TOOL to the correct local tool via session.tools() routing', async () => {
+ const provider = new MockProvider();
+ captureExecuteFn(provider);
+ const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
+
+ await session.tools();
+ const executeFn = (provider as any)._capturedExecuteFn;
+
+ const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
+ tool_slug: 'LOCAL_GET_USER_CONTEXT',
+ arguments: { category: 'routing-test' },
+ });
+
+ expect(result.data).toEqual({ local_result: true });
+ expect(result.successful).toBe(true);
+ expect(localExecute).toHaveBeenCalledWith(
+ { category: 'routing-test' },
+ expect.objectContaining({ userId: 'user_1' })
+ );
+ // Should NOT call remote
+ expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
+ });
+
+ it('should return error for COMPOSIO_EXECUTE_LOCAL_TOOL with unknown slug', async () => {
+ const provider = new MockProvider();
+ captureExecuteFn(provider);
+ const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
+
+ await session.tools();
+ const executeFn = (provider as any)._capturedExecuteFn;
+
+ const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
+ tool_slug: 'DOES_NOT_EXIST',
+ arguments: {},
+ });
+
+ expect(result.successful).toBe(false);
+ expect(result.error).toContain('Local tool "DOES_NOT_EXIST" not found');
+ expect(result.data).toEqual({});
+ });
+ });
});