1
+import { describe, it, expect, vi } from 'vitest';
2
+import { AnthropicProvider } from '../src';
3
+import type { AnthropicTool } from '../src/types';
4
+import type { Tool } from '@composio/core';
5
+import {
6
+ sanitizeSchemaPropertyKeys,
7
+ restoreOriginalKeys,
8
+ mappingHasRenames,
9
+} from '../src/sanitize-keys';
10
+
11
+vi.mock('@anthropic-ai/sdk', () => ({
12
+ default: vi.fn().mockImplementation(() => ({ messages: { create: vi.fn() } })),
13
+}));
14
+
15
+const ANTHROPIC_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;
16
+
17
+describe('sanitizeSchemaPropertyKeys', () => {
18
+ it('leaves already-valid keys untouched and reports no mapping', () => {
19
+ const schema = {
20
+ type: 'object',
21
+ properties: { query: { type: 'string' }, limit: { type: 'number' } },
22
+ required: ['query'],
23
+ };
24
+
25
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
26
+
27
+ expect(out).toEqual(schema);
28
+ expect(mappingHasRenames(mapping)).toBe(false);
29
+ });
30
+
31
+ it('rewrites OData keys with illegal `$` and `@` characters', () => {
32
+ const schema = {
33
+ type: 'object',
34
+ properties: {
35
+ $top: { type: 'integer' },
36
+ $filter: { type: 'string' },
37
+ '@microsoft.graph.conflictBehavior': { type: 'string' },
38
+ },
39
+ required: ['$top', '@microsoft.graph.conflictBehavior'],
40
+ };
41
+
42
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
43
+ const props = out.properties as Record<string, unknown>;
44
+
45
+ // Every emitted key must satisfy Anthropic's pattern.
46
+ for (const key of Object.keys(props)) {
47
+ expect(key).toMatch(ANTHROPIC_KEY_RE);
48
+ }
49
+
50
+ expect(props).toHaveProperty('dollar_top');
51
+ expect(props).toHaveProperty('dollar_filter');
52
+ expect(props).toHaveProperty('at_microsoft.graph.conflictBehavior');
53
+
54
+ // Mapping points sanitized keys back to the originals (at this level).
55
+ expect(mapping.renames['dollar_top']).toBe('$top');
56
+ expect(mapping.renames['at_microsoft.graph.conflictBehavior']).toBe(
57
+ '@microsoft.graph.conflictBehavior'
58
+ );
59
+
60
+ // `required` is rewritten to match the sanitized keys.
61
+ expect(out.required).toEqual(['dollar_top', 'at_microsoft.graph.conflictBehavior']);
62
+
63
+ // Property values are preserved.
64
+ expect(props['dollar_top']).toEqual({ type: 'integer' });
65
+ });
66
+
67
+ it('preserves the legal `.` and `-` characters Anthropic allows', () => {
68
+ const schema = {
69
+ type: 'object',
70
+ properties: { 'a.b-c': { type: 'string' } },
71
+ };
72
+
73
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
74
+
75
+ expect(out.properties).toHaveProperty('a.b-c');
76
+ expect(mappingHasRenames(mapping)).toBe(false);
77
+ });
78
+
79
+ it('truncates keys longer than 64 characters to a deterministic alias', () => {
80
+ const longKey = 'settings__continuous__meeting__chat__auto__add__invited__external__users';
81
+ expect(longKey.length).toBeGreaterThan(64);
82
+
83
+ const schema = { type: 'object', properties: { [longKey]: { type: 'boolean' } } };
84
+
85
+ const first = sanitizeSchemaPropertyKeys(schema);
86
+ const second = sanitizeSchemaPropertyKeys(schema);
87
+
88
+ const [aliasA] = Object.keys(first.schema.properties as Record<string, unknown>);
89
+ const [aliasB] = Object.keys(second.schema.properties as Record<string, unknown>);
90
+
91
+ expect(aliasA).toMatch(ANTHROPIC_KEY_RE);
92
+ expect(aliasA.length).toBeLessThanOrEqual(64);
93
+ expect(aliasA).toBe(aliasB); // deterministic
94
+ expect(first.mapping.renames[aliasA]).toBe(longKey);
95
+ });
96
+
97
+ it('keeps distinct originals distinct when they would collide', () => {
98
+ const schema = {
99
+ type: 'object',
100
+ properties: { $top: { type: 'integer' }, dollar_top: { type: 'string' } },
101
+ };
102
+
103
+ const { schema: out } = sanitizeSchemaPropertyKeys(schema);
104
+ const keys = Object.keys(out.properties as Record<string, unknown>);
105
+
106
+ expect(keys).toHaveLength(2);
107
+ expect(new Set(keys).size).toBe(2);
108
+ keys.forEach(k => expect(k).toMatch(ANTHROPIC_KEY_RE));
109
+ });
110
+
111
+ it('sanitizes nested object properties recursively', () => {
112
+ const schema = {
113
+ type: 'object',
114
+ properties: {
115
+ options: {
116
+ type: 'object',
117
+ properties: { $skip: { type: 'integer' } },
118
+ required: ['$skip'],
119
+ },
120
+ },
121
+ };
122
+
123
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
124
+ const nested = (out.properties as any).options;
125
+
126
+ expect(nested.properties).toHaveProperty('dollar_skip');
127
+ expect(nested.required).toEqual(['dollar_skip']);
128
+
129
+ // The rename is recorded at the nested level, not flattened onto the root.
130
+ expect(mapping.renames).toEqual({});
131
+ expect(mapping.children['options'].renames['dollar_skip']).toBe('$skip');
132
+ });
133
+
134
+ it('does not mutate the input schema', () => {
135
+ const schema = {
136
+ type: 'object',
137
+ properties: { $top: { type: 'integer' } },
138
+ required: ['$top'],
139
+ };
140
+ const snapshot = JSON.parse(JSON.stringify(schema));
141
+
142
+ sanitizeSchemaPropertyKeys(schema);
143
+
144
+ expect(schema).toEqual(snapshot);
145
+ });
146
+
147
+ // P2-2: illegal keys nested inside array element schemas must be sanitized too,
148
+ // otherwise they slip past a `properties`-only walk and still trigger a 400.
149
+ it('sanitizes illegal keys nested inside array item schemas', () => {
150
+ const schema = {
151
+ type: 'object',
152
+ properties: {
153
+ rows: {
154
+ type: 'array',
155
+ items: {
156
+ type: 'object',
157
+ properties: { $top: { type: 'integer' } },
158
+ required: ['$top'],
159
+ },
160
+ },
161
+ },
162
+ };
163
+
164
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
165
+ const itemSchema = (out.properties as any).rows.items;
166
+
167
+ expect(itemSchema.properties).toHaveProperty('dollar_top');
168
+ expect(itemSchema.properties).not.toHaveProperty('$top');
169
+ expect(itemSchema.required).toEqual(['dollar_top']);
170
+
171
+ // Restoration walks into array elements via the items mapping.
172
+ const restored = restoreOriginalKeys({ rows: [{ dollar_top: 1 }, { dollar_top: 2 }] }, mapping);
173
+ expect(restored).toEqual({ rows: [{ $top: 1 }, { $top: 2 }] });
174
+ });
175
+
176
+ it('sanitizes illegal keys in tuple (positional) array item schemas', () => {
177
+ const schema = {
178
+ type: 'object',
179
+ properties: {
180
+ pair: {
181
+ type: 'array',
182
+ items: [
183
+ { type: 'object', properties: { $top: { type: 'integer' } } },
184
+ { type: 'object', properties: { plain: { type: 'string' } } },
185
+ ],
186
+ },
187
+ },
188
+ };
189
+
190
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
191
+ const [first, second] = (out.properties as any).pair.items;
192
+
193
+ expect(first.properties).toHaveProperty('dollar_top');
194
+ expect(second.properties).toHaveProperty('plain');
195
+
196
+ const restored = restoreOriginalKeys({ pair: [{ dollar_top: 9 }, { plain: 'x' }] }, mapping);
197
+ expect(restored).toEqual({ pair: [{ $top: 9 }, { plain: 'x' }] });
198
+ });
199
+});
200
+
201
+describe('restoreOriginalKeys', () => {
202
+ it('restores sanitized keys back to their originals, including nested values', () => {
203
+ const { mapping } = sanitizeSchemaPropertyKeys({
204
+ type: 'object',
205
+ properties: {
206
+ $top: { type: 'integer' },
207
+ nested: { type: 'object', properties: { $skip: { type: 'integer' } } },
208
+ },
209
+ });
210
+
211
+ expect(
212
+ restoreOriginalKeys({ dollar_top: 10, nested: { dollar_skip: 5, keep: 'x' } }, mapping)
213
+ ).toEqual({ $top: 10, nested: { $skip: 5, keep: 'x' } });
214
+ });
215
+
216
+ it('passes through values when nothing was renamed', () => {
217
+ const { mapping } = sanitizeSchemaPropertyKeys({
218
+ type: 'object',
219
+ properties: { query: { type: 'string' } },
220
+ });
221
+ const args = { query: 'hello', items: [1, 2, 3] };
222
+ expect(restoreOriginalKeys(args, mapping)).toEqual(args);
223
+ });
224
+
225
+ // P2-1: a sanitized alias generated at one nesting level must not rewrite a
226
+ // legitimately-named key that equals that alias at a *different* level. The old
227
+ // flat global map corrupted the nested `dollar_top` into `$top`.
228
+ it('does not rewrite a legitimate key that collides with an alias at another level', () => {
229
+ const schema = {
230
+ type: 'object',
231
+ properties: {
232
+ $top: { type: 'integer' }, // -> dollar_top at the root
233
+ filters: {
234
+ type: 'object',
235
+ // A genuine, already-valid `dollar_top` that must survive untouched.
236
+ properties: { dollar_top: { type: 'string' } },
237
+ },
238
+ },
239
+ };
240
+
241
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
242
+
243
+ expect(out.properties).toHaveProperty('dollar_top');
244
+ expect((out.properties as any).filters.properties).toHaveProperty('dollar_top');
245
+
246
+ const restored = restoreOriginalKeys(
247
+ { dollar_top: 10, filters: { dollar_top: 'keep-me' } },
248
+ mapping
249
+ );
250
+
251
+ expect(restored).toEqual({
252
+ $top: 10, // root alias restored to the OData name
253
+ filters: { dollar_top: 'keep-me' }, // nested genuine key left alone
254
+ });
255
+ });
256
+});
257
+
258
+describe('AnthropicProvider key sanitization', () => {
259
+ const odataTool: Tool = {
260
+ slug: 'list_drive_item_activities',
261
+ name: 'List drive item activities',
262
+ description: 'Lists activities on a OneDrive item',
263
+ inputParameters: {
264
+ type: 'object',
265
+ properties: {
266
+ $top: { type: 'integer' },
267
+ $filter: { type: 'string' },
268
+ },
269
+ required: ['$top'],
270
+ },
271
+ tags: [],
272
+ } as unknown as Tool;
273
+
274
+ it('emits an Anthropic-compatible schema from wrapTool', () => {
275
+ const provider = new AnthropicProvider();
276
+ const wrapped = provider.wrapTool(odataTool) as AnthropicTool;
277
+ const props = wrapped.input_schema.properties as Record<string, unknown>;
278
+
279
+ for (const key of Object.keys(props)) {
280
+ expect(key).toMatch(ANTHROPIC_KEY_RE);
281
+ }
282
+ expect(props).toHaveProperty('dollar_top');
283
+ });
284
+
285
+ it('restores original OData keys before executing the tool call', async () => {
286
+ const provider = new AnthropicProvider();
287
+ const executeToolFn = vi
288
+ .fn()
289
+ .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
290
+ provider._setExecuteToolFn(executeToolFn);
291
+
292
+ // Wrapping registers the reverse mapping for this tool slug.
293
+ provider.wrapTool(odataTool);
294
+
295
+ // The model calls the tool using the sanitized key names.
296
+ await provider.executeToolCall('user-1', {
297
+ type: 'tool_use',
298
+ id: 'tu_1',
299
+ name: 'list_drive_item_activities',
300
+ input: { dollar_top: 25 },
301
+ });
302
+
303
+ expect(executeToolFn).toHaveBeenCalledTimes(1);
304
+ const [, payload] = executeToolFn.mock.calls[0];
305
+ expect(payload.arguments).toEqual({ $top: 25 });
306
+ });
307
+
308
+ it('leaves arguments untouched for tools without sanitized keys', async () => {
309
+ const provider = new AnthropicProvider();
310
+ const executeToolFn = vi
311
+ .fn()
312
+ .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
313
+ provider._setExecuteToolFn(executeToolFn);
314
+
315
+ const plainTool: Tool = {
316
+ slug: 'plain-tool',
317
+ name: 'Plain',
318
+ description: 'no illegal keys',
319
+ inputParameters: { type: 'object', properties: { query: { type: 'string' } } },
320
+ tags: [],
321
+ } as unknown as Tool;
322
+
323
+ provider.wrapTool(plainTool);
324
+ await provider.executeToolCall('user-1', {
325
+ type: 'tool_use',
326
+ id: 'tu_2',
327
+ name: 'plain-tool',
328
+ input: { query: 'hello' },
329
+ });
330
+
331
+ const [, payload] = executeToolFn.mock.calls[0];
332
+ expect(payload.arguments).toEqual({ query: 'hello' });
333
+ });
334
+
335
+ // Models occasionally emit tool input as a JSON *string* (issue #2406). The
336
+ // provider normalizes it to an object before restoring keys; restoring a raw
337
+ // string would be a no-op, so this guards the normalize-then-restore ordering.
338
+ it('normalizes a JSON-string input before restoring sanitized keys', async () => {
339
+ const provider = new AnthropicProvider();
340
+ const executeToolFn = vi
341
+ .fn()
342
+ .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
343
+ provider._setExecuteToolFn(executeToolFn);
344
+
345
+ provider.wrapTool(odataTool);
346
+
347
+ await provider.executeToolCall('user-1', {
348
+ type: 'tool_use',
349
+ id: 'tu_3',
350
+ name: 'list_drive_item_activities',
351
+ input: '{"dollar_top": 25}' as unknown as Record<string, unknown>,
352
+ });
353
+
354
+ const [, payload] = executeToolFn.mock.calls[0];
355
+ expect(payload.arguments).toEqual({ $top: 25 });
356
+ });
357
+
358
+ it('normalizes a JSON-string input for tools without sanitized keys (issue #2406)', async () => {
359
+ const provider = new AnthropicProvider();
360
+ const executeToolFn = vi
361
+ .fn()
362
+ .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
363
+ provider._setExecuteToolFn(executeToolFn);
364
+
365
+ const plainTool: Tool = {
366
+ slug: 'plain-tool',
367
+ name: 'Plain',
368
+ description: 'no illegal keys',
369
+ inputParameters: { type: 'object', properties: { query: { type: 'string' } } },
370
+ tags: [],
371
+ } as unknown as Tool;
372
+
373
+ provider.wrapTool(plainTool);
374
+ await provider.executeToolCall('user-1', {
375
+ type: 'tool_use',
376
+ id: 'tu_4',
377
+ name: 'plain-tool',
378
+ input: '{"query":"hello"}' as unknown as Record<string, unknown>,
379
+ });
380
+
381
+ const [, payload] = executeToolFn.mock.calls[0];
382
+ expect(payload.arguments).toEqual({ query: 'hello' });
383
+ });
384
+});