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
| 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 | /** |
| 18 | * Minimal structural shape for a JSON-schema node carrying a `properties` bag, |
| 19 | * used to dereference `sanitizeSchemaPropertyKeys` output (typed loosely as the |
| 20 | * generic input schema) in test assertions without weakening the cast to `any`. |
| 21 | */ |
| 22 | type SchemaWithProperties = { properties: Record<string, unknown>; required?: string[] }; |
| 23 | |
| 24 | describe('sanitizeSchemaPropertyKeys', () => { |
| 25 | it('leaves already-valid keys untouched and reports no mapping', () => { |
| 26 | const schema = { |
| 27 | type: 'object', |
| 28 | properties: { query: { type: 'string' }, limit: { type: 'number' } }, |
| 29 | required: ['query'], |
| 30 | }; |
| 31 | |
| 32 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 33 | |
| 34 | expect(out).toEqual(schema); |
| 35 | expect(mappingHasRenames(mapping)).toBe(false); |
| 36 | }); |
| 37 | |
| 38 | it('rewrites OData keys with illegal `$` and `@` characters', () => { |
| 39 | const schema = { |
| 40 | type: 'object', |
| 41 | properties: { |
| 42 | $top: { type: 'integer' }, |
| 43 | $filter: { type: 'string' }, |
| 44 | '@microsoft.graph.conflictBehavior': { type: 'string' }, |
| 45 | }, |
| 46 | required: ['$top', '@microsoft.graph.conflictBehavior'], |
| 47 | }; |
| 48 | |
| 49 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 50 | const props = out.properties as Record<string, unknown>; |
| 51 | |
| 52 | // Every emitted key must satisfy Anthropic's pattern. |
| 53 | for (const key of Object.keys(props)) { |
| 54 | expect(key).toMatch(ANTHROPIC_KEY_RE); |
| 55 | } |
| 56 | |
| 57 | expect(props).toHaveProperty('dollar_top'); |
| 58 | expect(props).toHaveProperty('dollar_filter'); |
| 59 | expect(props).toHaveProperty('at_microsoft.graph.conflictBehavior'); |
| 60 | |
| 61 | // Mapping points sanitized keys back to the originals (at this level). |
| 62 | expect(mapping.renames['dollar_top']).toBe('$top'); |
| 63 | expect(mapping.renames['at_microsoft.graph.conflictBehavior']).toBe( |
| 64 | '@microsoft.graph.conflictBehavior' |
| 65 | ); |
| 66 | |
| 67 | // `required` is rewritten to match the sanitized keys. |
| 68 | expect(out.required).toEqual(['dollar_top', 'at_microsoft.graph.conflictBehavior']); |
| 69 | |
| 70 | // Property values are preserved. |
| 71 | expect(props['dollar_top']).toEqual({ type: 'integer' }); |
| 72 | }); |
| 73 | |
| 74 | it('preserves the legal `.` and `-` characters Anthropic allows', () => { |
| 75 | const schema = { |
| 76 | type: 'object', |
| 77 | properties: { 'a.b-c': { type: 'string' } }, |
| 78 | }; |
| 79 | |
| 80 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 81 | |
| 82 | expect(out.properties).toHaveProperty('a.b-c'); |
| 83 | expect(mappingHasRenames(mapping)).toBe(false); |
| 84 | }); |
| 85 | |
| 86 | it('truncates keys longer than 64 characters to a deterministic alias', () => { |
| 87 | const longKey = 'settings__continuous__meeting__chat__auto__add__invited__external__users'; |
| 88 | expect(longKey.length).toBeGreaterThan(64); |
| 89 | |
| 90 | const schema = { type: 'object', properties: { [longKey]: { type: 'boolean' } } }; |
| 91 | |
| 92 | const first = sanitizeSchemaPropertyKeys(schema); |
| 93 | const second = sanitizeSchemaPropertyKeys(schema); |
| 94 | |
| 95 | const [aliasA] = Object.keys(first.schema.properties as Record<string, unknown>); |
| 96 | const [aliasB] = Object.keys(second.schema.properties as Record<string, unknown>); |
| 97 | |
| 98 | expect(aliasA).toMatch(ANTHROPIC_KEY_RE); |
| 99 | expect(aliasA.length).toBeLessThanOrEqual(64); |
| 100 | expect(aliasA).toBe(aliasB); // deterministic |
| 101 | expect(first.mapping.renames[aliasA]).toBe(longKey); |
| 102 | }); |
| 103 | |
| 104 | it('keeps distinct originals distinct when they would collide', () => { |
| 105 | const schema = { |
| 106 | type: 'object', |
| 107 | properties: { $top: { type: 'integer' }, dollar_top: { type: 'string' } }, |
| 108 | }; |
| 109 | |
| 110 | const { schema: out } = sanitizeSchemaPropertyKeys(schema); |
| 111 | const keys = Object.keys(out.properties as Record<string, unknown>); |
| 112 | |
| 113 | expect(keys).toHaveLength(2); |
| 114 | expect(new Set(keys).size).toBe(2); |
| 115 | keys.forEach(k => expect(k).toMatch(ANTHROPIC_KEY_RE)); |
| 116 | }); |
| 117 | |
| 118 | it('sanitizes nested object properties recursively', () => { |
| 119 | const schema = { |
| 120 | type: 'object', |
| 121 | properties: { |
| 122 | options: { |
| 123 | type: 'object', |
| 124 | properties: { $skip: { type: 'integer' } }, |
| 125 | required: ['$skip'], |
| 126 | }, |
| 127 | }, |
| 128 | }; |
| 129 | |
| 130 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 131 | const nested = (out.properties as unknown as { options: SchemaWithProperties }).options; |
| 132 | |
| 133 | expect(nested.properties).toHaveProperty('dollar_skip'); |
| 134 | expect(nested.required).toEqual(['dollar_skip']); |
| 135 | |
| 136 | // The rename is recorded at the nested level, not flattened onto the root. |
| 137 | expect(mapping.renames).toEqual({}); |
| 138 | expect(mapping.children['options'].renames['dollar_skip']).toBe('$skip'); |
| 139 | }); |
| 140 | |
| 141 | it('does not mutate the input schema', () => { |
| 142 | const schema = { |
| 143 | type: 'object', |
| 144 | properties: { $top: { type: 'integer' } }, |
| 145 | required: ['$top'], |
| 146 | }; |
| 147 | const snapshot = JSON.parse(JSON.stringify(schema)); |
| 148 | |
| 149 | sanitizeSchemaPropertyKeys(schema); |
| 150 | |
| 151 | expect(schema).toEqual(snapshot); |
| 152 | }); |
| 153 | |
| 154 | // P2-2: illegal keys nested inside array element schemas must be sanitized too, |
| 155 | // otherwise they slip past a `properties`-only walk and still trigger a 400. |
| 156 | it('sanitizes illegal keys nested inside array item schemas', () => { |
| 157 | const schema = { |
| 158 | type: 'object', |
| 159 | properties: { |
| 160 | rows: { |
| 161 | type: 'array', |
| 162 | items: { |
| 163 | type: 'object', |
| 164 | properties: { $top: { type: 'integer' } }, |
| 165 | required: ['$top'], |
| 166 | }, |
| 167 | }, |
| 168 | }, |
| 169 | }; |
| 170 | |
| 171 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 172 | const itemSchema = (out.properties as unknown as { rows: { items: SchemaWithProperties } }).rows |
| 173 | .items; |
| 174 | |
| 175 | expect(itemSchema.properties).toHaveProperty('dollar_top'); |
| 176 | expect(itemSchema.properties).not.toHaveProperty('$top'); |
| 177 | expect(itemSchema.required).toEqual(['dollar_top']); |
| 178 | |
| 179 | // Restoration walks into array elements via the items mapping. |
| 180 | const restored = restoreOriginalKeys({ rows: [{ dollar_top: 1 }, { dollar_top: 2 }] }, mapping); |
| 181 | expect(restored).toEqual({ rows: [{ $top: 1 }, { $top: 2 }] }); |
| 182 | }); |
| 183 | |
| 184 | it('sanitizes illegal keys in tuple (positional) array item schemas', () => { |
| 185 | const schema = { |
| 186 | type: 'object', |
| 187 | properties: { |
| 188 | pair: { |
| 189 | type: 'array', |
| 190 | items: [ |
| 191 | { type: 'object', properties: { $top: { type: 'integer' } } }, |
| 192 | { type: 'object', properties: { plain: { type: 'string' } } }, |
| 193 | ], |
| 194 | }, |
| 195 | }, |
| 196 | }; |
| 197 | |
| 198 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 199 | const [first, second] = ( |
| 200 | out.properties as unknown as { |
| 201 | pair: { items: [SchemaWithProperties, SchemaWithProperties] }; |
| 202 | } |
| 203 | ).pair.items; |
| 204 | |
| 205 | expect(first.properties).toHaveProperty('dollar_top'); |
| 206 | expect(second.properties).toHaveProperty('plain'); |
| 207 | |
| 208 | const restored = restoreOriginalKeys({ pair: [{ dollar_top: 9 }, { plain: 'x' }] }, mapping); |
| 209 | expect(restored).toEqual({ pair: [{ $top: 9 }, { plain: 'x' }] }); |
| 210 | }); |
| 211 | |
| 212 | // A key that is empty (or made entirely of stripped characters) would emit |
| 213 | // `''`, which still violates Anthropic's `{1,64}` length bound. |
| 214 | it('emits a non-empty conforming alias for empty / all-illegal keys', () => { |
| 215 | const schema = { |
| 216 | type: 'object', |
| 217 | properties: { '': { type: 'string' }, '@@@': { type: 'integer' } }, |
| 218 | }; |
| 219 | |
| 220 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 221 | const keys = Object.keys(out.properties as Record<string, unknown>); |
| 222 | |
| 223 | expect(keys).toHaveLength(2); |
| 224 | keys.forEach(k => expect(k).toMatch(ANTHROPIC_KEY_RE)); // each ≥ 1 char and conforming |
| 225 | expect(new Set(Object.values(mapping.renames))).toEqual(new Set(['', '@@@'])); |
| 226 | }); |
| 227 | |
| 228 | // Pathologically deep schemas must fail loudly rather than overflow the stack. |
| 229 | it('throws instead of overflowing the stack on deeply nested schemas', () => { |
| 230 | let deep: Record<string, unknown> = { |
| 231 | type: 'object', |
| 232 | properties: { $x: { type: 'integer' } }, |
| 233 | }; |
| 234 | for (let i = 0; i < 2000; i++) { |
| 235 | deep = { type: 'object', properties: { nested: deep } }; |
| 236 | } |
| 237 | |
| 238 | expect(() => sanitizeSchemaPropertyKeys(deep)).toThrow(/depth/i); |
| 239 | }); |
| 240 | |
| 241 | // Property keys that collide with `Object.prototype` member names must be |
| 242 | // treated as ordinary keys, never reparent the emitted schema, and never |
| 243 | // mutate `Object.prototype`. Built via JSON.parse so `__proto__` is a real |
| 244 | // own key rather than prototype-setting literal syntax. |
| 245 | it('treats prototype-member property names as ordinary keys', () => { |
| 246 | const schema = JSON.parse( |
| 247 | '{"type":"object","properties":{"$top":{"type":"integer"},"__proto__":{"type":"string"},"constructor":{"type":"string"}}}' |
| 248 | ); |
| 249 | |
| 250 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 251 | const props = out.properties as Record<string, unknown>; |
| 252 | |
| 253 | expect(Object.prototype.hasOwnProperty.call(props, '__proto__')).toBe(true); |
| 254 | expect(Object.prototype.hasOwnProperty.call(props, 'constructor')).toBe(true); |
| 255 | expect(props['constructor']).toEqual({ type: 'string' }); |
| 256 | expect(({} as Record<string, unknown>).type).toBeUndefined(); // prototype untouched |
| 257 | |
| 258 | const restored = restoreOriginalKeys({ dollar_top: 1, constructor: 'c' }, mapping) as Record< |
| 259 | string, |
| 260 | unknown |
| 261 | >; |
| 262 | expect(restored['$top']).toBe(1); |
| 263 | expect(restored['constructor']).toBe('c'); |
| 264 | }); |
| 265 | }); |
| 266 | |
| 267 | describe('sanitizeSchemaPropertyKeys composition coverage', () => { |
| 268 | // Asserts every emitted `properties` key (at any depth) conforms to Anthropic's |
| 269 | // pattern — i.e. nothing illegal slipped through the traversal and could 400. |
| 270 | const expectNoIllegalPropertyKeys = (schema: unknown) => { |
| 271 | const walk = (node: unknown): void => { |
| 272 | if (Array.isArray(node)) return node.forEach(walk); |
| 273 | if (!node || typeof node !== 'object') return; |
| 274 | const obj = node as Record<string, unknown>; |
| 275 | if (obj.properties && typeof obj.properties === 'object') { |
| 276 | for (const key of Object.keys(obj.properties as Record<string, unknown>)) { |
| 277 | expect(key).toMatch(ANTHROPIC_KEY_RE); |
| 278 | } |
| 279 | } |
| 280 | Object.values(obj).forEach(walk); |
| 281 | }; |
| 282 | walk(schema); |
| 283 | }; |
| 284 | |
| 285 | it('sanitizes and restores illegal keys nested under `anyOf` branches', () => { |
| 286 | const schema = { |
| 287 | type: 'object', |
| 288 | properties: { |
| 289 | foo: { |
| 290 | anyOf: [ |
| 291 | { type: 'object', properties: { $top: { type: 'integer' } }, required: ['$top'] }, |
| 292 | { type: 'object', properties: { bar: { type: 'string' } } }, |
| 293 | ], |
| 294 | }, |
| 295 | }, |
| 296 | }; |
| 297 | |
| 298 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 299 | expectNoIllegalPropertyKeys(out); |
| 300 | expect( |
| 301 | ( |
| 302 | out.properties as unknown as { |
| 303 | foo: { anyOf: SchemaWithProperties[] }; |
| 304 | } |
| 305 | ).foo.anyOf[0].properties |
| 306 | ).toHaveProperty('dollar_top'); |
| 307 | |
| 308 | // The branch rename folds into `foo`'s value level, so restoration finds it. |
| 309 | expect(restoreOriginalKeys({ foo: { dollar_top: 5 } }, mapping)).toEqual({ foo: { $top: 5 } }); |
| 310 | }); |
| 311 | |
| 312 | it('merges `oneOf` / `allOf` renames into the shared value level', () => { |
| 313 | const oneOf = sanitizeSchemaPropertyKeys({ |
| 314 | type: 'object', |
| 315 | oneOf: [{ properties: { $top: { type: 'integer' } } }, { properties: { plain: {} } }], |
| 316 | }); |
| 317 | expectNoIllegalPropertyKeys(oneOf.schema); |
| 318 | expect(restoreOriginalKeys({ dollar_top: 1 }, oneOf.mapping)).toEqual({ $top: 1 }); |
| 319 | |
| 320 | const allOf = sanitizeSchemaPropertyKeys({ |
| 321 | type: 'object', |
| 322 | properties: { keep: { type: 'string' } }, |
| 323 | allOf: [{ properties: { '@odata.type': { type: 'string' } } }], |
| 324 | }); |
| 325 | expectNoIllegalPropertyKeys(allOf.schema); |
| 326 | expect(restoreOriginalKeys({ 'at_odata.type': 'x', keep: 'y' }, allOf.mapping)).toEqual({ |
| 327 | '@odata.type': 'x', |
| 328 | keep: 'y', |
| 329 | }); |
| 330 | }); |
| 331 | |
| 332 | it('selects the right branch mapping by value type for a mixed `anyOf`', () => { |
| 333 | const { mapping } = sanitizeSchemaPropertyKeys({ |
| 334 | type: 'object', |
| 335 | properties: { |
| 336 | field: { |
| 337 | anyOf: [ |
| 338 | { type: 'array', items: { type: 'object', properties: { $top: { type: 'integer' } } } }, |
| 339 | { type: 'object', properties: { $skip: { type: 'integer' } } }, |
| 340 | ], |
| 341 | }, |
| 342 | }, |
| 343 | }); |
| 344 | |
| 345 | // Array value → array-branch (`items`) mapping; object value → object branch. |
| 346 | expect(restoreOriginalKeys({ field: [{ dollar_top: 1 }] }, mapping)).toEqual({ |
| 347 | field: [{ $top: 1 }], |
| 348 | }); |
| 349 | expect(restoreOriginalKeys({ field: { dollar_skip: 2 } }, mapping)).toEqual({ |
| 350 | field: { $skip: 2 }, |
| 351 | }); |
| 352 | }); |
| 353 | |
| 354 | it('sanitizes (but does not restore) keys nested under `additionalProperties`', () => { |
| 355 | const schema = { |
| 356 | type: 'object', |
| 357 | properties: {}, |
| 358 | additionalProperties: { type: 'object', properties: { $top: { type: 'integer' } } }, |
| 359 | }; |
| 360 | |
| 361 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 362 | // 400-prevention: the alias is emitted so Anthropic accepts the schema. |
| 363 | expect( |
| 364 | (out as unknown as { additionalProperties: SchemaWithProperties }).additionalProperties |
| 365 | .properties |
| 366 | ).toHaveProperty('dollar_top'); |
| 367 | // Documented limitation: dynamic-key values are not restored — the alias |
| 368 | // reaches the backend rather than being silently (mis)mapped at every level. |
| 369 | expect(restoreOriginalKeys({ anyKey: { dollar_top: 1 } }, mapping)).toEqual({ |
| 370 | anyKey: { dollar_top: 1 }, |
| 371 | }); |
| 372 | }); |
| 373 | |
| 374 | it('sanitizes keys nested under `$defs` for Anthropic acceptance', () => { |
| 375 | const { schema: out } = sanitizeSchemaPropertyKeys({ |
| 376 | type: 'object', |
| 377 | properties: { x: { $ref: '#/$defs/Foo' } }, |
| 378 | $defs: { Foo: { type: 'object', properties: { $top: { type: 'integer' } } } }, |
| 379 | }); |
| 380 | |
| 381 | expectNoIllegalPropertyKeys(out); |
| 382 | expect( |
| 383 | (out as unknown as { $defs: { Foo: SchemaWithProperties } }).$defs.Foo.properties |
| 384 | ).toHaveProperty('dollar_top'); |
| 385 | }); |
| 386 | |
| 387 | it('sanitizes and restores `prefixItems` tuples', () => { |
| 388 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys({ |
| 389 | type: 'object', |
| 390 | properties: { |
| 391 | pair: { |
| 392 | type: 'array', |
| 393 | prefixItems: [ |
| 394 | { type: 'object', properties: { $top: { type: 'integer' } } }, |
| 395 | { type: 'object', properties: { plain: { type: 'string' } } }, |
| 396 | ], |
| 397 | }, |
| 398 | }, |
| 399 | }); |
| 400 | |
| 401 | expectNoIllegalPropertyKeys(out); |
| 402 | expect(restoreOriginalKeys({ pair: [{ dollar_top: 9 }, { plain: 'x' }] }, mapping)).toEqual({ |
| 403 | pair: [{ $top: 9 }, { plain: 'x' }], |
| 404 | }); |
| 405 | }); |
| 406 | |
| 407 | it('restores a `prefixItems` tuple and a trailing `items` rest schema independently', () => { |
| 408 | // 2020-12: `prefixItems` pins positions 0..n-1; a sibling single `items` schema |
| 409 | // applies to every element past the tuple. Both carry illegal keys that must |
| 410 | // round-trip at their own positions — the prefix rename must not be dropped, |
| 411 | // and the rest mapping must not bleed onto the prefix position. |
| 412 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys({ |
| 413 | type: 'object', |
| 414 | properties: { |
| 415 | tuple: { |
| 416 | type: 'array', |
| 417 | prefixItems: [{ type: 'object', properties: { $top: { type: 'integer' } } }], |
| 418 | items: { type: 'object', properties: { '@odata.type': { type: 'string' } } }, |
| 419 | }, |
| 420 | }, |
| 421 | }); |
| 422 | |
| 423 | expectNoIllegalPropertyKeys(out); |
| 424 | expect( |
| 425 | restoreOriginalKeys( |
| 426 | { tuple: [{ dollar_top: 5 }, { 'at_odata.type': 'a' }, { 'at_odata.type': 'b' }] }, |
| 427 | mapping |
| 428 | ) |
| 429 | ).toEqual({ tuple: [{ $top: 5 }, { '@odata.type': 'a' }, { '@odata.type': 'b' }] }); |
| 430 | }); |
| 431 | }); |
| 432 | |
| 433 | describe('restoreOriginalKeys', () => { |
| 434 | it('restores sanitized keys back to their originals, including nested values', () => { |
| 435 | const { mapping } = sanitizeSchemaPropertyKeys({ |
| 436 | type: 'object', |
| 437 | properties: { |
| 438 | $top: { type: 'integer' }, |
| 439 | nested: { type: 'object', properties: { $skip: { type: 'integer' } } }, |
| 440 | }, |
| 441 | }); |
| 442 | |
| 443 | expect( |
| 444 | restoreOriginalKeys({ dollar_top: 10, nested: { dollar_skip: 5, keep: 'x' } }, mapping) |
| 445 | ).toEqual({ $top: 10, nested: { $skip: 5, keep: 'x' } }); |
| 446 | }); |
| 447 | |
| 448 | it('passes through values when nothing was renamed', () => { |
| 449 | const { mapping } = sanitizeSchemaPropertyKeys({ |
| 450 | type: 'object', |
| 451 | properties: { query: { type: 'string' } }, |
| 452 | }); |
| 453 | const args = { query: 'hello', items: [1, 2, 3] }; |
| 454 | expect(restoreOriginalKeys(args, mapping)).toEqual(args); |
| 455 | }); |
| 456 | |
| 457 | // P2-1: a sanitized alias generated at one nesting level must not rewrite a |
| 458 | // legitimately-named key that equals that alias at a *different* level. The old |
| 459 | // flat global map corrupted the nested `dollar_top` into `$top`. |
| 460 | it('does not rewrite a legitimate key that collides with an alias at another level', () => { |
| 461 | const schema = { |
| 462 | type: 'object', |
| 463 | properties: { |
| 464 | $top: { type: 'integer' }, // -> dollar_top at the root |
| 465 | filters: { |
| 466 | type: 'object', |
| 467 | // A genuine, already-valid `dollar_top` that must survive untouched. |
| 468 | properties: { dollar_top: { type: 'string' } }, |
| 469 | }, |
| 470 | }, |
| 471 | }; |
| 472 | |
| 473 | const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema); |
| 474 | |
| 475 | expect(out.properties).toHaveProperty('dollar_top'); |
| 476 | expect( |
| 477 | (out.properties as unknown as { filters: SchemaWithProperties }).filters.properties |
| 478 | ).toHaveProperty('dollar_top'); |
| 479 | |
| 480 | const restored = restoreOriginalKeys( |
| 481 | { dollar_top: 10, filters: { dollar_top: 'keep-me' } }, |
| 482 | mapping |
| 483 | ); |
| 484 | |
| 485 | expect(restored).toEqual({ |
| 486 | $top: 10, // root alias restored to the OData name |
| 487 | filters: { dollar_top: 'keep-me' }, // nested genuine key left alone |
| 488 | }); |
| 489 | }); |
| 490 | |
| 491 | // Security: a model can emit argument keys equal to Object.prototype member |
| 492 | // names (and `__proto__` reaches restoration via the JSON-string input path). |
| 493 | // Restoration must not crash, must not corrupt the payload, and must never |
| 494 | // mutate Object.prototype — the reverse maps and result object are all |
| 495 | // prototype-free. |
| 496 | it('handles prototype-member keys in tool arguments without crashing or polluting', () => { |
| 497 | const { mapping } = sanitizeSchemaPropertyKeys({ |
| 498 | type: 'object', |
| 499 | properties: { $top: { type: 'integer' }, name: { type: 'string' } }, |
| 500 | required: ['$top'], |
| 501 | }); |
| 502 | |
| 503 | const input = JSON.parse( |
| 504 | '{"dollar_top":1,"constructor":{"inner":2},"toString":"t","__proto__":{"polluted":true},"hasOwnProperty":"h","name":"n"}' |
| 505 | ); |
| 506 | |
| 507 | // Threw with `TypeError` before this PR's hardening (lookups resolved to the |
| 508 | // inherited `Object` function); a plain assignment here would also fail. |
| 509 | const restored = restoreOriginalKeys(input, mapping) as Record<string, unknown>; |
| 510 | |
| 511 | expect(restored['$top']).toBe(1); |
| 512 | expect(restored['name']).toBe('n'); |
| 513 | expect(restored['toString']).toBe('t'); |
| 514 | expect(restored['hasOwnProperty']).toBe('h'); |
| 515 | expect((restored['constructor'] as Record<string, unknown>).inner).toBe(2); |
| 516 | expect(({} as Record<string, unknown>).polluted).toBeUndefined(); // prototype untouched |
| 517 | }); |
| 518 | }); |
| 519 | |
| 520 | describe('AnthropicProvider key sanitization', () => { |
| 521 | const odataTool: Tool = { |
| 522 | slug: 'list_drive_item_activities', |
| 523 | name: 'List drive item activities', |
| 524 | description: 'Lists activities on a OneDrive item', |
| 525 | inputParameters: { |
| 526 | type: 'object', |
| 527 | properties: { |
| 528 | $top: { type: 'integer' }, |
| 529 | $filter: { type: 'string' }, |
| 530 | }, |
| 531 | required: ['$top'], |
| 532 | }, |
| 533 | tags: [], |
| 534 | } as unknown as Tool; |
| 535 | |
| 536 | it('emits an Anthropic-compatible schema from wrapTool', () => { |
| 537 | const provider = new AnthropicProvider(); |
| 538 | const wrapped = provider.wrapTool(odataTool) as AnthropicTool; |
| 539 | const props = wrapped.input_schema.properties as Record<string, unknown>; |
| 540 | |
| 541 | for (const key of Object.keys(props)) { |
| 542 | expect(key).toMatch(ANTHROPIC_KEY_RE); |
| 543 | } |
| 544 | expect(props).toHaveProperty('dollar_top'); |
| 545 | }); |
| 546 | |
| 547 | it('restores original OData keys before executing the tool call', async () => { |
| 548 | const provider = new AnthropicProvider(); |
| 549 | const executeToolFn = vi |
| 550 | .fn() |
| 551 | .mockResolvedValue({ data: { ok: true }, error: null, successful: true }); |
| 552 | provider._setExecuteToolFn(executeToolFn); |
| 553 | |
| 554 | // Wrapping registers the reverse mapping for this tool slug. |
| 555 | provider.wrapTool(odataTool); |
| 556 | |
| 557 | // The model calls the tool using the sanitized key names. |
| 558 | await provider.executeToolCall('user-1', { |
| 559 | type: 'tool_use', |
| 560 | id: 'tu_1', |
| 561 | name: 'list_drive_item_activities', |
| 562 | input: { dollar_top: 25 }, |
| 563 | }); |
| 564 | |
| 565 | expect(executeToolFn).toHaveBeenCalledTimes(1); |
| 566 | const [, payload] = executeToolFn.mock.calls[0]; |
| 567 | expect(payload.arguments).toEqual({ $top: 25 }); |
| 568 | }); |
| 569 | |
| 570 | it('leaves arguments untouched for tools without sanitized keys', async () => { |
| 571 | const provider = new AnthropicProvider(); |
| 572 | const executeToolFn = vi |
| 573 | .fn() |
| 574 | .mockResolvedValue({ data: { ok: true }, error: null, successful: true }); |
| 575 | provider._setExecuteToolFn(executeToolFn); |
| 576 | |
| 577 | const plainTool: Tool = { |
| 578 | slug: 'plain-tool', |
| 579 | name: 'Plain', |
| 580 | description: 'no illegal keys', |
| 581 | inputParameters: { type: 'object', properties: { query: { type: 'string' } } }, |
| 582 | tags: [], |
| 583 | } as unknown as Tool; |
| 584 | |
| 585 | provider.wrapTool(plainTool); |
| 586 | await provider.executeToolCall('user-1', { |
| 587 | type: 'tool_use', |
| 588 | id: 'tu_2', |
| 589 | name: 'plain-tool', |
| 590 | input: { query: 'hello' }, |
| 591 | }); |
| 592 | |
| 593 | const [, payload] = executeToolFn.mock.calls[0]; |
| 594 | expect(payload.arguments).toEqual({ query: 'hello' }); |
| 595 | }); |
| 596 | |
| 597 | // Models occasionally emit tool input as a JSON *string* (issue #2406). The |
| 598 | // provider normalizes it to an object before restoring keys; restoring a raw |
| 599 | // string would be a no-op, so this guards the normalize-then-restore ordering. |
| 600 | it('normalizes a JSON-string input before restoring sanitized keys', async () => { |
| 601 | const provider = new AnthropicProvider(); |
| 602 | const executeToolFn = vi |
| 603 | .fn() |
| 604 | .mockResolvedValue({ data: { ok: true }, error: null, successful: true }); |
| 605 | provider._setExecuteToolFn(executeToolFn); |
| 606 | |
| 607 | provider.wrapTool(odataTool); |
| 608 | |
| 609 | await provider.executeToolCall('user-1', { |
| 610 | type: 'tool_use', |
| 611 | id: 'tu_3', |
| 612 | name: 'list_drive_item_activities', |
| 613 | input: '{"dollar_top": 25}' as unknown as Record<string, unknown>, |
| 614 | }); |
| 615 | |
| 616 | const [, payload] = executeToolFn.mock.calls[0]; |
| 617 | expect(payload.arguments).toEqual({ $top: 25 }); |
| 618 | }); |
| 619 | |
| 620 | it('restores sanitized keys before executing through a tool router session', async () => { |
| 621 | const provider = new AnthropicProvider(); |
| 622 | const directExecute = vi.fn(); |
| 623 | const session = { |
| 624 | execute: vi.fn().mockResolvedValue({ |
| 625 | data: { ok: true }, |
| 626 | error: null, |
| 627 | logId: 'log-session', |
| 628 | resultType: 'completed', |
| 629 | }), |
| 630 | }; |
| 631 | provider._setExecuteToolFn(directExecute); |
| 632 | provider.wrapTool(odataTool); |
| 633 | |
| 634 | const result = await provider.executeToolCall(session, { |
| 635 | type: 'tool_use', |
| 636 | id: 'tu_session', |
| 637 | name: 'list_drive_item_activities', |
| 638 | input: '{"dollar_top": 25}' as unknown as Record<string, unknown>, |
| 639 | }); |
| 640 | |
| 641 | expect(session.execute).toHaveBeenCalledWith('list_drive_item_activities', { $top: 25 }); |
| 642 | expect(directExecute).not.toHaveBeenCalled(); |
| 643 | expect(result).toBe(JSON.stringify({ ok: true })); |
| 644 | }); |
| 645 | |
| 646 | it('normalizes a JSON-string input for tools without sanitized keys (issue #2406)', async () => { |
| 647 | const provider = new AnthropicProvider(); |
| 648 | const executeToolFn = vi |
| 649 | .fn() |
| 650 | .mockResolvedValue({ data: { ok: true }, error: null, successful: true }); |
| 651 | provider._setExecuteToolFn(executeToolFn); |
| 652 | |
| 653 | const plainTool: Tool = { |
| 654 | slug: 'plain-tool', |
| 655 | name: 'Plain', |
| 656 | description: 'no illegal keys', |
| 657 | inputParameters: { type: 'object', properties: { query: { type: 'string' } } }, |
| 658 | tags: [], |
| 659 | } as unknown as Tool; |
| 660 | |
| 661 | provider.wrapTool(plainTool); |
| 662 | await provider.executeToolCall('user-1', { |
| 663 | type: 'tool_use', |
| 664 | id: 'tu_4', |
| 665 | name: 'plain-tool', |
| 666 | input: '{"query":"hello"}' as unknown as Record<string, unknown>, |
| 667 | }); |
| 668 | |
| 669 | const [, payload] = executeToolFn.mock.calls[0]; |
| 670 | expect(payload.arguments).toEqual({ query: 'hello' }); |
| 671 | }); |
| 672 | |
| 673 | // Re-wrapping the same slug with a schema that no longer needs rewriting must |
| 674 | // clear the stale mapping, so a later execution does not restore keys that the |
| 675 | // current schema never sanitized. |
| 676 | it('clears a stale key mapping when a slug is re-wrapped with a clean schema', async () => { |
| 677 | const provider = new AnthropicProvider(); |
| 678 | const executeToolFn = vi |
| 679 | .fn() |
| 680 | .mockResolvedValue({ data: { ok: true }, error: null, successful: true }); |
| 681 | provider._setExecuteToolFn(executeToolFn); |
| 682 | |
| 683 | // First wrap registers a `dollar_top -> $top` mapping for this slug. |
| 684 | provider.wrapTool(odataTool); |
| 685 | |
| 686 | // Re-wrap the SAME slug with a schema that has no illegal keys. |
| 687 | const cleanedTool: Tool = { |
| 688 | ...odataTool, |
| 689 | inputParameters: { type: 'object', properties: { dollar_top: { type: 'integer' } } }, |
| 690 | } as unknown as Tool; |
| 691 | provider.wrapTool(cleanedTool); |
| 692 | |
| 693 | // The model now legitimately sends `dollar_top`; it must reach the backend |
| 694 | // unchanged rather than being restored to `$top` by the stale mapping. |
| 695 | await provider.executeToolCall('user-1', { |
| 696 | type: 'tool_use', |
| 697 | id: 'tu_5', |
| 698 | name: odataTool.slug, |
| 699 | input: { dollar_top: 7 }, |
| 700 | }); |
| 701 | |
| 702 | const [, payload] = executeToolFn.mock.calls[0]; |
| 703 | expect(payload.arguments).toEqual({ dollar_top: 7 }); |
| 704 | }); |
| 705 | |
| 706 | // `wrapTool` dereferences `$ref`/`$defs` before sanitizing, so an illegal key |
| 707 | // reachable only through a reference is both made compliant for Anthropic and |
| 708 | // restored to its original name at execution time. |
| 709 | it('dereferences $ref so $ref-nested illegal keys round-trip', async () => { |
| 710 | const provider = new AnthropicProvider(); |
| 711 | const executeToolFn = vi |
| 712 | .fn() |
| 713 | .mockResolvedValue({ data: { ok: true }, error: null, successful: true }); |
| 714 | provider._setExecuteToolFn(executeToolFn); |
| 715 | |
| 716 | const refTool: Tool = { |
| 717 | slug: 'ref-tool', |
| 718 | name: 'Ref', |
| 719 | description: 'uses $ref into $defs', |
| 720 | inputParameters: { |
| 721 | type: 'object', |
| 722 | properties: { filter: { $ref: '#/$defs/Filter' } }, |
| 723 | $defs: { Filter: { type: 'object', properties: { $top: { type: 'integer' } } } }, |
| 724 | }, |
| 725 | tags: [], |
| 726 | } as unknown as Tool; |
| 727 | |
| 728 | const wrapped = provider.wrapTool(refTool) as AnthropicTool; |
| 729 | // The $ref is inlined, `$defs` removed, and the nested `$top` sanitized. |
| 730 | expect( |
| 731 | (wrapped.input_schema.properties as unknown as { filter: SchemaWithProperties }).filter |
| 732 | .properties |
| 733 | ).toHaveProperty('dollar_top'); |
| 734 | expect((wrapped.input_schema as unknown as { $defs?: unknown }).$defs).toBeUndefined(); |
| 735 | |
| 736 | await provider.executeToolCall('user-1', { |
| 737 | type: 'tool_use', |
| 738 | id: 'tu_ref', |
| 739 | name: 'ref-tool', |
| 740 | input: { filter: { dollar_top: 3 } }, |
| 741 | }); |
| 742 | |
| 743 | const [, payload] = executeToolFn.mock.calls[0]; |
| 744 | expect(payload.arguments).toEqual({ filter: { $top: 3 } }); |
| 745 | }); |
| 746 | }); |