@devries-cameron20 / composio Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 06:00 UTC

next
ts 388 lines 12.8 KB
Raw
1 import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
2 import { Tool, GlobalExecuteToolFn } from '@composio/core';
3 import { ClaudeAgentSDKProvider } from '../src';
4
5 // Mock the claude-agent-sdk module
6 vi.mock('@anthropic-ai/claude-agent-sdk', () => {
7 return {
8 tool: vi.fn().mockImplementation((name, description, schema, handler) => {
9 return {
10 name,
11 description,
12 schema,
13 handler,
14 _isMockedClaudeAgentTool: true,
15 };
16 }),
17 };
18 });
19
20 // Import mocked functions for assertions
21 import { tool } from '@anthropic-ai/claude-agent-sdk';
22
23 // Define interface for mocked tool
24 interface MockedClaudeAgentTool {
25 name: string;
26 description: string;
27 schema: unknown;
28 handler: Function;
29 _isMockedClaudeAgentTool: boolean;
30 }
31
32 // Minimal structural type for the complete Zod object schema the provider registers, matching
33 // only the member these tests dereference (`safeParse`).
34 type MinimalZodSchema = {
35 safeParse: (value: unknown) => { success: boolean };
36 };
37
38 // The handler captured off the mocked `tool()` call. Some tests intentionally pass a raw
39 // (possibly malformed) JSON string instead of an object to exercise the stringified-input
40 // normalization path (issue #2406), so the parameter is typed `unknown` here rather than the
41 // stricter `Record<string, unknown>` used by the real `wrapTool` handler signature.
42 type MockedToolHandler = (
43 args: unknown
44 ) => Promise<{ content: Array<{ type: string; text: string }> }>;
45
46 type MockedToolFn = Mock<
47 (
48 name: string,
49 description: string | undefined,
50 schema: MinimalZodSchema,
51 handler: MockedToolHandler
52 ) => unknown
53 >;
54
55 // `mockExecuteToolFn` is declared against the real `GlobalExecuteToolFn` contract, which always
56 // resolves with a `ToolExecuteResponse`. A couple of tests deliberately stub it with a plain
57 // string / `undefined` to exercise the wrapTool handler's defensive "stringify anything" branch,
58 // so those specific stubbing calls need a widened, minimal view of just the method they use.
59 type MockResolvableWithAnyValue = {
60 mockResolvedValueOnce: (value: unknown) => void;
61 };
62
63 describe('ClaudeAgentSDKProvider', () => {
64 let provider: ClaudeAgentSDKProvider;
65 let mockTool: Tool;
66 let mockExecuteToolFn: Mock<GlobalExecuteToolFn>;
67
68 beforeEach(() => {
69 provider = new ClaudeAgentSDKProvider();
70
71 // Mock the global execute tool function
72 mockExecuteToolFn = vi.fn().mockResolvedValue({
73 data: { result: 'success' },
74 error: null,
75 successful: true,
76 });
77 provider._setExecuteToolFn(mockExecuteToolFn);
78
79 // Create a mock Composio tool
80 mockTool = {
81 slug: 'GMAIL_SEND_EMAIL',
82 name: 'Gmail Send Email',
83 description: 'Send an email via Gmail',
84 version: '20250909_00',
85 availableVersions: ['20250909_00'],
86 inputParameters: {
87 type: 'object',
88 properties: {
89 to: {
90 type: 'string',
91 description: 'Recipient email address',
92 },
93 subject: {
94 type: 'string',
95 description: 'Email subject',
96 },
97 body: {
98 type: 'string',
99 description: 'Email body content',
100 },
101 },
102 required: ['to', 'subject', 'body'],
103 },
104 tags: ['email', 'gmail'],
105 };
106
107 // Reset mocks before each test
108 vi.clearAllMocks();
109 });
110
111 describe('name property', () => {
112 it('should have the correct name', () => {
113 expect(provider.name).toBe('claude-agent-sdk');
114 });
115 });
116
117 describe('_isAgentic property', () => {
118 it('should be agentic', () => {
119 expect(provider._isAgentic).toBe(true);
120 });
121 });
122
123 describe('wrapTool', () => {
124 it('should wrap a tool in Claude Agent SDK MCP tool format', () => {
125 const wrapped = provider.wrapTool(
126 mockTool,
127 mockExecuteToolFn
128 ) as unknown as MockedClaudeAgentTool;
129
130 expect(tool).toHaveBeenCalledWith(
131 mockTool.slug,
132 mockTool.description,
133 expect.any(Object), // Zod schema
134 expect.any(Function) // Handler
135 );
136
137 expect(wrapped._isMockedClaudeAgentTool).toBe(true);
138 expect(wrapped.name).toBe(mockTool.slug);
139 expect(wrapped.description).toBe(mockTool.description);
140 });
141
142 it('should pass a complete Zod object schema to the Claude Agent SDK', () => {
143 // A raw property shape drops every root-level constraint, so the provider registers the
144 // whole object schema instead. See claude-agent-sdk.registration.test.ts for what that
145 // buys at the real SDK boundary.
146 provider.wrapTool(mockTool, mockExecuteToolFn);
147
148 const schema = (tool as unknown as MockedToolFn).mock.calls[0][2];
149 expect(schema.safeParse({ to: 'test@example.com', subject: 's', body: 'b' }).success).toBe(
150 true
151 );
152 expect(schema.safeParse({ to: 123, subject: 's', body: 'b' }).success).toBe(false);
153 // The root is strict: `additionalProperties` is omitted on a named-properties schema.
154 expect(
155 schema.safeParse({ to: 'test@example.com', subject: 's', body: 'b', extra: 'x' }).success
156 ).toBe(false);
157 });
158
159 it('should handle tools without input parameters', () => {
160 const toolWithoutParams: Tool = {
161 ...mockTool,
162 inputParameters: undefined,
163 };
164
165 const wrapped = provider.wrapTool(
166 toolWithoutParams,
167 mockExecuteToolFn
168 ) as unknown as MockedClaudeAgentTool;
169
170 expect(tool).toHaveBeenCalledWith(
171 toolWithoutParams.slug,
172 toolWithoutParams.description,
173 expect.any(Object), // Empty Zod schema
174 expect.any(Function)
175 );
176 expect(wrapped._isMockedClaudeAgentTool).toBe(true);
177 });
178
179 it('should handle tools without description', () => {
180 const toolWithoutDescription: Tool = {
181 ...mockTool,
182 description: undefined,
183 };
184
185 const wrapped = provider.wrapTool(
186 toolWithoutDescription,
187 mockExecuteToolFn
188 ) as unknown as MockedClaudeAgentTool;
189
190 expect(tool).toHaveBeenCalledWith(
191 toolWithoutDescription.slug,
192 `Execute ${toolWithoutDescription.slug}`,
193 expect.any(Object),
194 expect.any(Function)
195 );
196 expect(wrapped._isMockedClaudeAgentTool).toBe(true);
197 });
198
199 it('should create a handler that executes the tool with correct parameters', async () => {
200 provider.wrapTool(mockTool, mockExecuteToolFn);
201
202 // Extract the handler function from the call to tool()
203 const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
204
205 // Test the handler
206 const params = { to: 'test@example.com', subject: 'Test', body: 'Hello' };
207 const result = await handler(params);
208
209 expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
210 expect(result).toEqual({
211 content: [
212 {
213 type: 'text',
214 text: JSON.stringify({
215 data: { result: 'success' },
216 error: null,
217 successful: true,
218 }),
219 },
220 ],
221 });
222 });
223
224 it('should normalize a stringified-JSON input to an object before executing (issue #2406)', async () => {
225 provider.wrapTool(mockTool, mockExecuteToolFn);
226 const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
227
228 const params = { to: 'test@example.com', subject: 'Test', body: 'Hello' };
229 await handler(JSON.stringify(params));
230
231 expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
232 });
233
234 it('should surface a typed error for a malformed-JSON string input (issue #2406)', async () => {
235 provider.wrapTool(mockTool, mockExecuteToolFn);
236 const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
237
238 const result = await handler('{"to":');
239
240 expect(mockExecuteToolFn).not.toHaveBeenCalled();
241 expect(JSON.parse(result.content[0].text)).toMatchObject({
242 successful: false,
243 error: expect.stringContaining('not valid JSON'),
244 });
245 });
246
247 it('should handle string results from tool execution', async () => {
248 (mockExecuteToolFn as unknown as MockResolvableWithAnyValue).mockResolvedValueOnce(
249 'Simple string result'
250 );
251 provider.wrapTool(mockTool, mockExecuteToolFn);
252
253 const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
254 const result = await handler({ to: 'test@example.com', subject: 'Test', body: 'Hello' });
255
256 expect(result).toEqual({
257 content: [
258 {
259 type: 'text',
260 text: 'Simple string result',
261 },
262 ],
263 });
264 });
265
266 it('should handle undefined results from tool execution and convert to "null" string', async () => {
267 (mockExecuteToolFn as unknown as MockResolvableWithAnyValue).mockResolvedValueOnce(undefined);
268 provider.wrapTool(mockTool, mockExecuteToolFn);
269
270 const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
271 const result = await handler({ to: 'test@example.com', subject: 'Test', body: 'Hello' });
272
273 // text should always be a string, never undefined
274 expect(result.content[0].text).toBe('');
275 expect(typeof result.content[0].text).toBe('string');
276 });
277
278 it('should handle errors from tool execution and return formatted error response', async () => {
279 const testError = new Error('Test execution error');
280 mockExecuteToolFn.mockRejectedValueOnce(testError);
281 provider.wrapTool(mockTool, mockExecuteToolFn);
282
283 const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
284 const result = await handler({ to: 'test@example.com', subject: 'Test', body: 'Hello' });
285
286 expect(result.content[0].type).toBe('text');
287 expect(typeof result.content[0].text).toBe('string');
288
289 const errorResponse = JSON.parse(result.content[0].text);
290 expect(errorResponse.successful).toBe(false);
291 expect(errorResponse.error).toBe('Test execution error');
292 expect(errorResponse.data).toBe(null);
293 });
294 });
295
296 describe('wrapTools', () => {
297 it('should wrap multiple tools', () => {
298 const anotherTool: Tool = {
299 ...mockTool,
300 slug: 'SLACK_POST_MESSAGE',
301 name: 'Slack Post Message',
302 description: 'Post a message to Slack',
303 };
304 const tools = [mockTool, anotherTool];
305
306 const wrapped = provider.wrapTools(tools, mockExecuteToolFn);
307
308 expect(wrapped).toHaveLength(2);
309 expect(tool).toHaveBeenCalledTimes(2);
310 });
311
312 it('should return an empty array for empty tools array', () => {
313 const wrapped = provider.wrapTools([], mockExecuteToolFn);
314 expect(wrapped).toEqual([]);
315 expect(tool).not.toHaveBeenCalled();
316 });
317 });
318
319 describe('wrapMcpServerResponse', () => {
320 it('should transform MCP URL response to standard format', () => {
321 const mcpUrlResponse = [
322 { url: 'https://example.com/mcp1', name: 'Server 1' },
323 { url: 'https://example.com/mcp2', name: 'Server 2' },
324 ];
325
326 const result = provider.wrapMcpServerResponse(mcpUrlResponse) as Array<{
327 url: URL;
328 name: string;
329 }>;
330
331 expect(result).toHaveLength(2);
332 expect(result[0]).toEqual({
333 url: new URL('https://example.com/mcp1'),
334 name: 'Server 1',
335 });
336 expect(result[1]).toEqual({
337 url: new URL('https://example.com/mcp2'),
338 name: 'Server 2',
339 });
340 });
341 });
342
343 describe('JSON Schema to Zod conversion', () => {
344 it('should handle various property types', () => {
345 const toolWithVariousTypes: Tool = {
346 ...mockTool,
347 inputParameters: {
348 type: 'object',
349 properties: {
350 stringProp: { type: 'string', description: 'A string' },
351 numberProp: { type: 'number', description: 'A number' },
352 integerProp: { type: 'integer', description: 'An integer' },
353 booleanProp: { type: 'boolean', description: 'A boolean' },
354 arrayProp: { type: 'array', description: 'An array' },
355 objectProp: { type: 'object', description: 'An object' },
356 unknownProp: { type: 'custom', description: 'Unknown type' },
357 },
358 required: ['stringProp'],
359 },
360 };
361
362 const wrapped = provider.wrapTool(toolWithVariousTypes, mockExecuteToolFn);
363
364 // Verify tool was called (schema conversion happened without error)
365 expect(tool).toHaveBeenCalled();
366 expect(wrapped).toBeDefined();
367 });
368
369 it('should handle optional properties', () => {
370 const toolWithOptionalProps: Tool = {
371 ...mockTool,
372 inputParameters: {
373 type: 'object',
374 properties: {
375 required: { type: 'string' },
376 optional: { type: 'string' },
377 },
378 required: ['required'],
379 },
380 };
381
382 const wrapped = provider.wrapTool(toolWithOptionalProps, mockExecuteToolFn);
383
384 expect(tool).toHaveBeenCalled();
385 expect(wrapped).toBeDefined();
386 });
387 });
388 });