Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
mjs 255 lines 8.51 KB
Raw
1 /**
2 * E2E fixture: Custom local tools execution flow.
3 * Tests local execution, remote execution, mixed routing, error handling,
4 * and SessionContext chaining against the live Composio API.
5 *
6 * Uses the hackernews toolkit (public, no auth needed).
7 * Requires COMPOSIO_API_KEY in environment.
8 */
9 import { Composio, experimental_createTool as createCustomTool } from '@composio/core';
10 import { z } from 'zod/v3';
11
12 const apiKey = process.env.COMPOSIO_API_KEY;
13 if (!apiKey) {
14 console.error('COMPOSIO_API_KEY is required');
15 process.exit(1);
16 }
17
18 // ── Define custom tools ──────────────────────────────────────
19
20 const getUserContext = createCustomTool('GET_USER_CONTEXT', {
21 name: 'Get user context',
22 description: 'Retrieve user preferences and history',
23 inputParams: z.object({
24 category: z.string().default('all'),
25 }),
26 execute: async (input) => {
27 return { preferences: { category: input.category, source: 'local' } };
28 },
29 });
30
31 const enrichedSearch = createCustomTool('ENRICHED_SEARCH', {
32 name: 'Enriched search',
33 description: 'Search and enrich results with user context',
34 inputParams: z.object({
35 query: z.string(),
36 }),
37 execute: async (input, ctx) => {
38 return {
39 query: input.query,
40 userId: ctx.userId,
41 };
42 },
43 });
44
45 const throwingTool = createCustomTool('THROWING_TOOL', {
46 name: 'Throwing tool',
47 description: 'A tool that always throws an error',
48 inputParams: z.object({}),
49 execute: async () => {
50 throw new Error('intentional error for testing');
51 },
52 });
53
54 // Tool with strict numeric schema — for Zod validation failure test
55 const strictTool = createCustomTool('STRICT_TOOL', {
56 name: 'Strict tool',
57 description: 'Tool with strict numeric input',
58 inputParams: z.object({
59 count: z.number(),
60 }),
61 execute: async (input) => {
62 return { doubled: input.count * 2 };
63 },
64 });
65
66 // Tool that chains into a remote tool via SessionContext.execute()
67 const hackerNewsChain = createCustomTool('HACKERNEWS_CHAIN', {
68 name: 'Hacker News chain',
69 description: 'Fetches a Hacker News profile via a remote tool and enriches it locally',
70 inputParams: z.object({
71 username: z.string(),
72 }),
73 execute: async (input, ctx) => {
74 // Call remote HACKERNEWS_GET_USER tool through SessionContext
75 const profile = await ctx.execute('HACKERNEWS_GET_USER', {
76 username: input.username,
77 });
78 return {
79 username: input.username,
80 userId: ctx.userId,
81 remoteData: profile.data,
82 remoteError: profile.error,
83 };
84 },
85 });
86
87 // ── Create session and run tests ─────────────────────────────
88
89 const composio = new Composio({ apiKey });
90
91 async function main() {
92 const userId = `e2e-custom-tools-${Date.now()}`;
93
94 const session = await composio.create(userId, {
95 toolkits: ['hackernews'],
96 manageConnections: false,
97 experimental: {
98 customTools: [getUserContext, enrichedSearch, throwingTool, strictTool, hackerNewsChain],
99 },
100 });
101
102 // ── Test 1: Single local tool execution ──
103 {
104 const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
105 if (result.data?.preferences?.category !== 'prefs') {
106 throw new Error(`LOCAL_EXECUTE failed: ${JSON.stringify(result)}`);
107 }
108 if (result.data?.preferences?.source !== 'local') {
109 throw new Error(`LOCAL_EXECUTE source mismatch: ${JSON.stringify(result)}`);
110 }
111 console.log('LOCAL_EXECUTE_OK');
112 }
113
114 // ── Test 2: Zod defaults applied ──
115 {
116 const result = await session.execute('GET_USER_CONTEXT', {});
117 if (result.data?.preferences?.category !== 'all') {
118 throw new Error(`ZOD_DEFAULTS failed: ${JSON.stringify(result)}`);
119 }
120 console.log('ZOD_DEFAULTS_OK');
121 }
122
123 // ── Test 3: Error handling — throw wrapped into { data, error } ──
124 {
125 const result = await session.execute('THROWING_TOOL', {});
126 if (!result.error || !result.error.includes('intentional error')) {
127 throw new Error(`ERROR_HANDLING failed: ${JSON.stringify(result)}`);
128 }
129 // Verify it didn't crash — we got a structured response
130 if (result.data === undefined) {
131 throw new Error(`ERROR_HANDLING no data field: ${JSON.stringify(result)}`);
132 }
133 console.log('ERROR_HANDLING_OK');
134 }
135
136 // ── Test 4: Zod validation failure — wrong type wrapped into error ──
137 {
138 const result = await session.execute('STRICT_TOOL', { count: 'not-a-number' });
139 if (!result.error) {
140 throw new Error(`ZOD_VALIDATION_FAIL expected error: ${JSON.stringify(result)}`);
141 }
142 if (!result.error.toLowerCase().includes('validation')) {
143 throw new Error(`ZOD_VALIDATION_FAIL expected validation error: ${result.error}`);
144 }
145 console.log('ZOD_VALIDATION_FAIL_OK');
146 }
147
148 // ── Test 5: Multiple local tools route correctly ──
149 {
150 const r1 = await session.execute('GET_USER_CONTEXT', { category: 'a' });
151 const r2 = await session.execute('ENRICHED_SEARCH', { query: 'test' });
152 if (r1.data?.preferences?.category !== 'a') {
153 throw new Error(`MULTIPLE_TOOLS r1 failed: ${JSON.stringify(r1)}`);
154 }
155 if (r2.data?.query !== 'test') {
156 throw new Error(`MULTIPLE_TOOLS r2 failed: ${JSON.stringify(r2)}`);
157 }
158 console.log('MULTIPLE_TOOLS_OK');
159 }
160
161 // ── Test 6: Session context injection (userId) ──
162 {
163 const result = await session.execute('ENRICHED_SEARCH', { query: 'context-test' });
164 if (!result.data?.userId) {
165 throw new Error(`SESSION_CONTEXT failed: ${JSON.stringify(result)}`);
166 }
167 if (result.data.userId !== userId) {
168 throw new Error(`SESSION_CONTEXT userId mismatch: expected ${userId}, got ${result.data.userId}`);
169 }
170 console.log('SESSION_CONTEXT_OK');
171 }
172
173 // ── Test 7: Case-insensitive slug ──
174 {
175 const result = await session.execute('get_user_context', { category: 'case-test' });
176 if (result.data?.preferences?.category !== 'case-test') {
177 throw new Error(`CASE_INSENSITIVE failed: ${JSON.stringify(result)}`);
178 }
179 console.log('CASE_INSENSITIVE_OK');
180 }
181
182 // ── Test 8: Prefixed slug (LOCAL_) ──
183 {
184 const result = await session.execute('LOCAL_GET_USER_CONTEXT', { category: 'prefix-test' });
185 if (result.data?.preferences?.category !== 'prefix-test') {
186 throw new Error(`PREFIXED_SLUG failed: ${JSON.stringify(result)}`);
187 }
188 console.log('PREFIXED_SLUG_OK');
189 }
190
191 // ── Test 9: SessionContext.execute() chaining — local tool calls remote tool ──
192 // This is mixed local+remote execution: local tool runs in-process,
193 // then calls HACKERNEWS_GET_USER on the backend via session.execute()
194 {
195 const result = await session.execute('HACKERNEWS_CHAIN', { username: 'pg' });
196 if (result.error) {
197 throw new Error(`CHAINED_EXECUTE failed: ${result.error}`);
198 }
199 if (result.data?.username !== 'pg') {
200 throw new Error(`CHAINED_EXECUTE username mismatch: ${JSON.stringify(result)}`);
201 }
202 if (!result.data?.userId) {
203 throw new Error(`CHAINED_EXECUTE missing userId: ${JSON.stringify(result)}`);
204 }
205 // The chained remote call should have returned the Hacker News profile
206 if (!result.data?.remoteData) {
207 throw new Error(`CHAINED_EXECUTE missing remoteData: ${JSON.stringify(result)}`);
208 }
209 console.log('CHAINED_EXECUTE_OK');
210 }
211
212 // ── Test 10: Non-existent tool returns error gracefully ──
213 // Remote tools that don't exist throw from the backend (400).
214 // Verify the SDK surfaces this as a catchable error, not a silent failure.
215 {
216 let caught = false;
217 try {
218 await session.execute('COMPLETELY_FAKE_TOOL_12345', {});
219 } catch (err) {
220 caught = true;
221 if (!err.message?.includes('not found') && !err.message?.includes('400')) {
222 throw new Error(`NONEXISTENT_TOOL unexpected error: ${err.message}`);
223 }
224 }
225 if (!caught) {
226 throw new Error('NONEXISTENT_TOOL expected an error but got success');
227 }
228 console.log('NONEXISTENT_TOOL_OK');
229 }
230
231 // ── Test 12: session.tools() wrapping ──
232 {
233 try {
234 const tools = await session.tools();
235 if (!tools) {
236 throw new Error('tools() returned falsy value');
237 }
238 console.log('TOOLS_WRAPPING_OK');
239 } catch (err) {
240 // Expected — no provider configured, standard path used
241 if (err.message?.includes('provider')) {
242 console.log('TOOLS_WRAPPING_OK');
243 } else {
244 throw err;
245 }
246 }
247 }
248
249 console.log('ALL_OK');
250 }
251
252 main().catch((err) => {
253 console.log('ERROR:', err?.message || err);
254 process.exit(1);
255 });