@devries-cameron20 / composio-1 / commits / 507318d56
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.

fix(anthropic): harden tool property-key sanitizer (#3650)

This PR (builds on https://github.com/ComposioHQ/composio/pull/3649, already merged) hardens the Anthropic tool property-key sanitizer from a multi-agent review, then extracts the mechanism into a reusable core util. **Touches two packages:** `@composio/core` (new util) and `@composio/anthropic` (consumes it). ### Correctness / robustness - **Prototype-safe restoration** — reverse maps and the rebuilt argument object are `Object.create(null)`, so a tool call using a key matching an `Object.prototype` member (`__proto__`, `constructor`, `toString`, `hasOwnProperty`, …) no longer throws a `TypeError` or silently corrupts the backend payload, and `Object.prototype` is never mutated. - **Full schema coverage** — illegal keys are sanitized wherever they appear: `allOf`/`anyOf`/`oneOf`, `not`/`if`/`then`/`else`, `prefixItems`, `additionalProperties`/`patternProperties`, `$defs`/`definitions`. Renames inside composition keywords fold into the value level they share and restore correctly (a mixed array/object `anyOf` resolves by value type at restore time). - **`$ref` keys restored** — `wrapTool` now dereferences internal `$ref`/`$defs` (lenient `sentinel` mode) before sanitizing, so keys reachable only through a reference are both made compliant and restored. - **Depth cap (512)** on sanitization and restoration — a pathologically deep schema/argument fails with a clear error instead of overflowing the stack. - **Empty / all-illegal keys** become a deterministic non-empty alias instead of `''` (which would itself violate `{1,64}`). - **Collision loop** — replaced a latent non-terminating fixed point with a counter that always makes progress. ### Architecture - **Extracted to core** — `sanitizeSchemaPropertyKeys(schema, policy)` / `restoreOriginalKeys` / `mappingHasRenames` (+ `KeyMapping` / `KeySanitizationPolicy`) now live in `@composio/core`, alongside `normalizeToolArguments`. The traversal, collision handling, prototype guard and depth cap are provider-agnostic; the Anthropic constraint is injected as a `KeySanitizationPolicy` defined in the provider's `sanitize-keys.ts`, which also re-exports a policy-bound `sanitizeSchemaPropertyKeys` plus core's restore side so call sites import from one place. - **`wrapTool` → `executeToolCall` contract** documented (same provider instance) and instrumented with `debug` logs on the rewrite/restore paths; re-wrapping a slug refreshes or clears its mapping. - Dropped the inaccurate "mirrors the Python SDK" comment and two `as unknown as` casts. ### Known limitations Both cases below leave a value reaching the backend un-restored — still strictly better than the whole `tools` array 400-ing. - **Dynamic-key positions.** After dereferencing, only genuinely dynamic-key positions remain rewrite-only (not restored): `additionalProperties`, `patternProperties`, and `contains`. These can't be tied to a concrete value location without per-key schema association. - **Composition-branch key collisions.** When sibling `allOf`/`anyOf`/`oneOf` branches fold into their shared value level, two branches that sanitize different illegal keys to the *same* alias — or one branch whose alias equals a legitimately-named property in another branch — keep only the first-seen reverse mapping, so an argument satisfying the other branch restores to the wrong original name. Recovering which branch a runtime value matched needs full schema evaluation against the value; these collisions are rare in OpenAPI-derived schemas. (Documented on `mergeMappingInto`.) ### Testing Locally verified: `tsc --noEmit` clean on the core util and provider sources (0 own-file diagnostics); ESLint clean; Prettier-formatted; the full `@composio/core` (951) and `@composio/anthropic` (51) vitest suites pass after a fresh `pnpm --filter @composio/core build` (the earlier `picocolors` caveat from #3649 was a stale `@composio/core/dist`; rebuilding core clears it). **Please confirm CI is green before merging.**

Alberto Schiabel committed Jun 24, 2026 at 22:26 UTC 507318d56a0b4d52180cd3fbf9f37782a08afae3
7 files changed +879 -237
.changeset/anthropic-sanitize-keys-hardening.md new
+14
@@ -0,0 +1,14 @@
1 +---
2 +'@composio/anthropic': patch
3 +---
4 +
5 +Harden the Anthropic tool property-key sanitizer:
6 +
7 +- **Broader schema coverage.** Illegal keys are now sanitized wherever they appear in a tool schema — under the composition keywords (`allOf`/`anyOf`/`oneOf`, `not`/`if`/`then`/`else`), `prefixItems` tuples, `additionalProperties`/`patternProperties`, and `$defs`/`definitions` — not just top-level `properties` and array `items`. Previously a single illegal key under one of these would still 400 the entire request. Renames inside composition keywords are restored correctly (they fold into the value level they share).
8 +- **`$ref` keys restored.** `wrapTool` now dereferences internal `$ref`/`$defs` (leniently — a dangling ref degrades to a permissive schema instead of throwing) before sanitizing, so keys reachable only through a reference are both made compliant and restored. Only genuinely dynamic positions (`additionalProperties`, `patternProperties`, `contains`) remain rewrite-only.
9 +- **Shared core implementation.** The traversal/restoration mechanism now lives in `@composio/core` (`sanitizeSchemaPropertyKeys` / `restoreOriginalKeys`); this provider supplies only the Anthropic key constraint as a policy, reusing core's prototype-pollution guard and depth cap.
10 +- **Prototype-safe key restoration.** Reverse-mapping lookups and the rebuilt argument object are now prototype-free, so a tool call whose arguments use a key matching an `Object.prototype` member (`__proto__`, `constructor`, `toString`, `hasOwnProperty`, …) no longer throws or silently corrupts the payload sent to the backend. `Object.prototype` is never mutated.
11 +- **Depth cap.** Schema sanitization and key restoration now bound recursion (matching core's JSON-schema walker) so a pathologically deep schema or argument object fails with a clear error instead of overflowing the stack.
12 +- **Empty / all-illegal keys.** A property key that is empty (or made entirely of stripped characters) now becomes a deterministic non-empty alias instead of an empty string, which would itself have violated Anthropic's `{1,64}` length bound.
13 +- **Collision loop.** Replaced a latent non-terminating fixed point in the alias collision resolver with a counter that always makes progress.
14 +- **Observability.** The provider now emits `debug` logs when it rewrites a tool's schema keys and when it restores them at execution time, and the wrap-then-execute (same provider instance) contract for key restoration is documented.
.changeset/core-schema-property-key-sanitizer.md new
+7
@@ -0,0 +1,7 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Add a provider-agnostic JSON-schema property-key sanitizer: `sanitizeSchemaPropertyKeys(schema, policy)`, `restoreOriginalKeys(value, mapping)`, `mappingHasRenames(mapping)`, and the `KeyMapping` / `KeySanitizationPolicy` types.
6 +
7 +Some providers constrain the characters and length of tool `input_schema` property keys and reject the whole request on a single violation. This utility rewrites offending keys to conforming aliases (recursing through `properties`, array `items`/`prefixItems`, the composition keywords `allOf`/`anyOf`/`oneOf` and `not`/`if`/`then`/`else`, plus `additionalProperties`/`patternProperties`/`$defs`/`contains`) and records a schema-shaped reverse mapping so the original parameter names can be restored before execution. The _constraint_ is injected as a `KeySanitizationPolicy`, so the traversal, collision handling, prototype safety, and depth cap stay provider-agnostic. The `@composio/anthropic` provider now consumes it.
ts/packages/core/src/index.ts
+6
@@ -16,6 +16,12 @@ export type {
16 } from './utils/jsonSchema';
17 export { getExtensionFromMimeType } from './utils/mime';
18 export { normalizeToolArguments } from './utils/toolArguments';
19 +export {
20 + sanitizeSchemaPropertyKeys,
21 + restoreOriginalKeys,
22 + mappingHasRenames,
23 +} from './utils/schemaPropertyKeys';
24 +export type { KeyMapping, KeySanitizationPolicy } from './utils/schemaPropertyKeys';
25 export { AuthScheme } from './models/AuthScheme';
26 export { MCP } from './models/MCP';
27 export { RemoteFile } from './models/RemoteFile';
ts/packages/core/src/utils/schemaPropertyKeys.ts new
+433
@@ -0,0 +1,433 @@
1 +/**
2 + * JSON-schema property-key sanitization.
3 + *
4 + * Some providers constrain the characters and/or length of tool `input_schema`
5 + * property keys (e.g. Anthropic's Messages API validates every key against
6 + * `^[a-zA-Z0-9_.-]{1,64}$` and rejects the whole `tools` array on a single
7 + * violation). Composio tool schemas can surface keys that break such rules —
8 + * OData parameters like `$top` / `@microsoft.graph.conflictBehavior`, or
9 + * over-long `__`-flattened keys.
10 + *
11 + * This module rewrites offending keys to conforming aliases before the schema is
12 + * sent to the provider, and records a reverse mapping so the original parameter
13 + * names can be restored before a tool call is executed against the Composio
14 + * backend. The *constraint* (which keys are valid and how an illegal key is
15 + * rewritten) is injected as a {@link KeySanitizationPolicy} so the mechanism
16 + * stays provider-agnostic; the traversal, collision handling, reverse mapping,
17 + * prototype safety and depth cap live here.
18 + *
19 + * The reverse mapping mirrors the schema's nesting (object `properties`, array
20 + * `items`/`prefixItems`, and the composition keywords `allOf`/`anyOf`/`oneOf` /
21 + * `not`/`if`/`then`/`else`, whose renames fold into the value level they share)
22 + * rather than being a single flat lookup. This matters because an alias generated
23 + * at one nesting level (e.g. `$top` -> `dollar_top`) must not rewrite a
24 + * legitimately-named `dollar_top` key that happens to exist at a different level.
25 + * Keys nested only under dynamic / `$ref` positions (`additionalProperties`,
26 + * `patternProperties`, `$defs`/`definitions`, `contains`) are still rewritten so
27 + * the provider accepts the schema, but are not restored — see the keyword lists
28 + * below. Dereferencing the schema first (see `dereferenceJsonSchema`) inlines
29 + * `$ref`/`$defs` into restorable value positions, shrinking that residual gap.
30 + *
31 + * @packageDocumentation
32 + * @module utils/schemaPropertyKeys
33 + */
34 +
35 +import { isPlainObject } from './modifiers/FileToolModifier.utils.neutral';
36 +
37 +/** Maximum schema nesting we traverse, matching `dereferenceJsonSchema`'s cap. */
38 +const MAX_SCHEMA_DEPTH = 512;
39 +
40 +/**
41 + * Provider-specific key constraint. The mechanism reserves every already-valid
42 + * sibling key before aliasing, so {@link aliasKey} only needs to produce a
43 + * conforming alias that is distinct from the supplied `taken` set.
44 + */
45 +export interface KeySanitizationPolicy {
46 + /** Whether a key already conforms to the provider's constraint. */
47 + isValidKey(key: string): boolean;
48 + /**
49 + * Produce a conforming alias for an illegal `key`, guaranteed distinct from
50 + * every entry in `taken` (the already-assigned keys at the same object level).
51 + */
52 + aliasKey(key: string, taken: ReadonlySet<string>): string;
53 +}
54 +
55 +/**
56 + * Reverse mapping used to restore original property names at execution time.
57 + *
58 + * It is shaped like the schema it was derived from so restoration is scoped to
59 + * the exact location a rename happened:
60 + * - `renames` — `sanitized -> original` for keys renamed at *this* value level
61 + * (including renames folded in from composition keywords).
62 + * - `children` — restoration mapping for the value under each (sanitized) key,
63 + * keyed by the sanitized key. Only present for children that contain renames.
64 + * - `items` — restoration mapping for array element values. A single mapping
65 + * applies to every element; an array of mappings applies positionally (JSON
66 + * Schema tuple validation / `prefixItems`). Only present when array elements
67 + * contain renames.
68 + * - `restItems` — restoration mapping for array elements *past* a positional
69 + * `items`/`prefixItems` tuple (a 2020-12 single `items` schema sitting next to
70 + * `prefixItems`). Only present when those trailing elements contain renames.
71 + */
72 +export interface KeyMapping {
73 + renames: Record<string, string>;
74 + children: Record<string, KeyMapping>;
75 + items?: KeyMapping | (KeyMapping | null)[];
76 + restItems?: KeyMapping;
77 +}
78 +
79 +/** Whether a mapping (or any of its descendants) actually renames a key. */
80 +export function mappingHasRenames(mapping: KeyMapping): boolean {
81 + // `children` and `items` are only populated when they carry renames (see
82 + // `sanitizeNode`), so this stays a shallow check.
83 + return (
84 + Object.keys(mapping.renames).length > 0 ||
85 + Object.keys(mapping.children).length > 0 ||
86 + mapping.items != null ||
87 + mapping.restItems != null
88 + );
89 +}
90 +
91 +/**
92 + * Composition/applicator keywords whose sub-schema(s) constrain the *same* value
93 + * as the parent. Property-key renames generated inside them are merged into the
94 + * parent's value level, because the value carries no extra nesting for these
95 + * keywords. `not`/`if`/`then`/`else` hold a single sub-schema; `allOf`/`anyOf`/
96 + * `oneOf` hold an array of sub-schemas.
97 + */
98 +const COMPOSITION_SINGLE_KEYWORDS = ['not', 'if', 'then', 'else'] as const;
99 +const COMPOSITION_LIST_KEYWORDS = ['allOf', 'anyOf', 'oneOf'] as const;
100 +
101 +/**
102 + * Positions whose nested keys are rewritten so the provider accepts the schema,
103 + * but which we cannot tie to a concrete value position for restoration: dynamic
104 + * keys (`additionalProperties`, `patternProperties`) and `$ref` targets (`$defs`/
105 + * `definitions`, unresolved unless the caller dereferences first), plus
106 + * `contains`. A value filled via an alias generated here reaches the backend
107 + * un-restored — strictly better than the whole `tools` array being rejected.
108 + */
109 +const REWRITE_ONLY_SINGLE_KEYWORDS = ['additionalProperties', 'contains'] as const;
110 +const REWRITE_ONLY_MAP_KEYWORDS = ['patternProperties', '$defs', 'definitions'] as const;
111 +
112 +/**
113 + * Sanitizes a single sub-schema. Returns the rewritten node and its mapping, or
114 + * a `null` mapping when nothing inside it was renamed (keeps mappings sparse).
115 + */
116 +function sanitizeSubschema(
117 + value: unknown,
118 + policy: KeySanitizationPolicy,
119 + depth: number
120 +): { node: unknown; mapping: KeyMapping | null } {
121 + if (!isPlainObject(value)) {
122 + return { node: value, mapping: null };
123 + }
124 + const { node, mapping } = sanitizeNode(value, policy, depth + 1);
125 + return { node, mapping: mappingHasRenames(mapping) ? mapping : null };
126 +}
127 +
128 +/** Sanitizes an array of positional sub-schemas (tuple `items` / `prefixItems`). */
129 +function sanitizeTuple(
130 + entries: unknown[],
131 + policy: KeySanitizationPolicy,
132 + depth: number
133 +): { nodes: unknown[]; mappings: (KeyMapping | null)[] | undefined } {
134 + const nodes: unknown[] = [];
135 + const mappings: (KeyMapping | null)[] = [];
136 + let anyRenamed = false;
137 + for (const entry of entries) {
138 + const { node, mapping } = sanitizeSubschema(entry, policy, depth);
139 + nodes.push(node);
140 + mappings.push(mapping);
141 + if (mapping) anyRenamed = true;
142 + }
143 + return { nodes, mappings: anyRenamed ? mappings : undefined };
144 +}
145 +
146 +/**
147 + * Rewrites the nested keys of a `{ name -> sub-schema }` map (e.g. `$defs`,
148 + * `patternProperties`). The map's own keys are names/patterns, not value
149 + * property keys, so they are left untouched and no restoration mapping is kept.
150 + */
151 +function sanitizeSchemaMap(
152 + map: Record<string, unknown>,
153 + policy: KeySanitizationPolicy,
154 + depth: number
155 +): Record<string, unknown> {
156 + const out: Record<string, unknown> = Object.create(null);
157 + for (const [key, value] of Object.entries(map)) {
158 + out[key] = sanitizeSubschema(value, policy, depth).node;
159 + }
160 + return out;
161 +}
162 +
163 +/**
164 + * Merges `source`'s renames into `target`, both describing the same value level
165 + * (used to fold composition branches into their parent). `target` wins on
166 + * conflict, since it is the more direct (`properties`-level) mapping.
167 + *
168 + * Known limitation: folding sibling `allOf`/`anyOf`/`oneOf` branches into one
169 + * value level is lossy when two branches disagree on an alias. If branch A aliases
170 + * an illegal key to `X` while branch B has a distinct illegal key that also aliases
171 + * to `X` — or a *legitimate* property literally named `X` — only the first-seen
172 + * entry survives, so an argument that satisfied the other branch restores to the
173 + * wrong original name. Which branch a runtime value matched can't be recovered from
174 + * the value alone (that needs full schema evaluation against the value), so these
175 + * cross-branch collisions stay effectively rewrite-only — still strictly better
176 + * than the whole `tools` array being rejected. They are rare in practice.
177 + */
178 +function mergeMappingInto(target: KeyMapping, source: KeyMapping): void {
179 + for (const [alias, original] of Object.entries(source.renames)) {
180 + if (!(alias in target.renames)) {
181 + target.renames[alias] = original;
182 + }
183 + }
184 + for (const [key, childSource] of Object.entries(source.children)) {
185 + const existing = target.children[key];
186 + if (existing) {
187 + mergeMappingInto(existing, childSource);
188 + } else {
189 + target.children[key] = childSource;
190 + }
191 + }
192 + if (target.items === undefined && source.items !== undefined) {
193 + target.items = source.items;
194 + if (source.restItems !== undefined) {
195 + target.restItems = source.restItems;
196 + }
197 + }
198 +}
199 +
200 +/**
201 + * Recursively sanitizes the property keys of a JSON-schema node, returning the
202 + * rewritten node and a {@link KeyMapping} shaped like the node. Traversal covers
203 + * object `properties`, array `items`/`prefixItems`, the composition keywords
204 + * (`allOf`/`anyOf`/`oneOf`, `not`/`if`/`then`/`else` — whose renames merge into
205 + * this level), and the rewrite-only positions in {@link REWRITE_ONLY_SINGLE_KEYWORDS}
206 + * / {@link REWRITE_ONLY_MAP_KEYWORDS}.
207 + *
208 + * The input node is never mutated; a new node is returned.
209 + */
210 +function sanitizeNode(
211 + node: Record<string, unknown>,
212 + policy: KeySanitizationPolicy,
213 + depth = 0
214 +): {
215 + node: Record<string, unknown>;
216 + mapping: KeyMapping;
217 +} {
218 + if (depth >= MAX_SCHEMA_DEPTH) {
219 + throw new Error(
220 + `Tool schema nesting exceeded the maximum supported depth (${MAX_SCHEMA_DEPTH})`
221 + );
222 + }
223 +
224 + const result: Record<string, unknown> = { ...node };
225 + // Lookup/result tables are prototype-free so a property key that collides with
226 + // an `Object.prototype` member (`__proto__`, `constructor`, `toString`, …)
227 + // becomes a plain own entry instead of resolving to (or reparenting via) the
228 + // inherited member. Mirrors the `POLLUTING_KEYS` defense in `jsonSchema.ts`.
229 + const renames: Record<string, string> = Object.create(null);
230 + const children: Record<string, KeyMapping> = Object.create(null);
231 + const mapping: KeyMapping = { renames, children };
232 +
233 + const properties = node.properties;
234 + if (isPlainObject(properties)) {
235 + const newProperties: Record<string, unknown> = Object.create(null);
236 + const renamedOriginalToSanitized: Record<string, string> = Object.create(null);
237 +
238 + // Reserve all already-valid keys up front so they keep their exact names and
239 + // sanitized aliases are generated around them (a valid `dollar_top` must not
240 + // be clobbered by a sanitized `$top`).
241 + const taken = new Set<string>();
242 + for (const key of Object.keys(properties)) {
243 + if (policy.isValidKey(key)) {
244 + taken.add(key);
245 + }
246 + }
247 +
248 + for (const [key, rawValue] of Object.entries(properties)) {
249 + const safeKey = policy.isValidKey(key) ? key : policy.aliasKey(key, taken);
250 + taken.add(safeKey);
251 +
252 + const { node: childNode, mapping: childMapping } = sanitizeSubschema(rawValue, policy, depth);
253 + newProperties[safeKey] = childNode;
254 + if (childMapping) {
255 + children[safeKey] = childMapping;
256 + }
257 +
258 + if (safeKey !== key) {
259 + renames[safeKey] = key;
260 + renamedOriginalToSanitized[key] = safeKey;
261 + }
262 + }
263 +
264 + result.properties = newProperties;
265 +
266 + // Keep `required` in sync with the renamed keys at this level.
267 + if (Array.isArray(node.required)) {
268 + result.required = node.required.map(name =>
269 + typeof name === 'string' && renamedOriginalToSanitized[name]
270 + ? renamedOriginalToSanitized[name]
271 + : name
272 + );
273 + }
274 + }
275 +
276 + // Array element schemas come from up to two positional sources — a Draft-7
277 + // `items` tuple and the 2020-12 `prefixItems` tuple — plus one "applies to every
278 + // element" source, a single `items` schema. When `prefixItems` provides the
279 + // positional mapping, a sibling single `items` schema constrains the elements
280 + // *past* the tuple (2020-12 semantics); its renames are kept separately as
281 + // `restItems` so those tail elements restore too instead of being dropped (or
282 + // the rest mapping bleeding onto the tuple positions). Restoration reaches array
283 + // elements through `mapping.items`/`mapping.restItems` — a `properties`-only walk
284 + // would let illegal keys nested in elements through and still be rejected.
285 + const itemsSchema = node.items;
286 + let positionalItems: (KeyMapping | null)[] | undefined;
287 + let uniformItems: KeyMapping | undefined;
288 + if (isPlainObject(itemsSchema)) {
289 + const { node: childNode, mapping: childMapping } = sanitizeSubschema(
290 + itemsSchema,
291 + policy,
292 + depth
293 + );
294 + result.items = childNode;
295 + if (childMapping) {
296 + uniformItems = childMapping;
297 + }
298 + } else if (Array.isArray(itemsSchema)) {
299 + const { nodes, mappings } = sanitizeTuple(itemsSchema, policy, depth);
300 + result.items = nodes;
301 + positionalItems = mappings;
302 + }
303 + if (Array.isArray(node.prefixItems)) {
304 + const { nodes, mappings } = sanitizeTuple(node.prefixItems, policy, depth);
305 + result.prefixItems = nodes;
306 + // `prefixItems` is the 2020-12 positional keyword; use it for the positional
307 + // mapping when a Draft-7 `items` tuple didn't already provide one.
308 + if (positionalItems === undefined) {
309 + positionalItems = mappings;
310 + }
311 + }
312 + if (positionalItems) {
313 + mapping.items = positionalItems;
314 + // A single `items` schema sitting next to a `prefixItems` tuple describes the
315 + // elements after the tuple; keep its mapping so they restore positionally.
316 + if (uniformItems && Array.isArray(node.prefixItems)) {
317 + mapping.restItems = uniformItems;
318 + }
319 + } else if (uniformItems) {
320 + mapping.items = uniformItems;
321 + }
322 +
323 + // Composition keywords constrain the *same* value, so renames generated inside
324 + // them are merged into this level (the value has no extra nesting for them).
325 + for (const keyword of COMPOSITION_SINGLE_KEYWORDS) {
326 + const sub = node[keyword];
327 + if (isPlainObject(sub)) {
328 + const { node: childNode, mapping: childMapping } = sanitizeSubschema(sub, policy, depth);
329 + result[keyword] = childNode;
330 + if (childMapping) {
331 + mergeMappingInto(mapping, childMapping);
332 + }
333 + }
334 + }
335 + for (const keyword of COMPOSITION_LIST_KEYWORDS) {
336 + const list = node[keyword];
337 + if (Array.isArray(list)) {
338 + result[keyword] = list.map(entry => {
339 + const { node: childNode, mapping: childMapping } = sanitizeSubschema(entry, policy, depth);
340 + if (childMapping) {
341 + mergeMappingInto(mapping, childMapping);
342 + }
343 + return childNode;
344 + });
345 + }
346 + }
347 +
348 + // Rewrite-only positions: keys are made compliant, but no restoration mapping
349 + // is kept (see the keyword lists above for why).
350 + for (const keyword of REWRITE_ONLY_SINGLE_KEYWORDS) {
351 + const sub = node[keyword];
352 + if (isPlainObject(sub)) {
353 + result[keyword] = sanitizeSubschema(sub, policy, depth).node;
354 + }
355 + }
356 + for (const keyword of REWRITE_ONLY_MAP_KEYWORDS) {
357 + const sub = node[keyword];
358 + if (isPlainObject(sub)) {
359 + result[keyword] = sanitizeSchemaMap(sub, policy, depth);
360 + }
361 + }
362 +
363 + return { node: result, mapping };
364 +}
365 +
366 +/**
367 + * Sanitizes a tool `input_schema` so all property keys conform to `policy`.
368 + *
369 + * @param schema - The tool input schema to sanitize.
370 + * @param policy - Provider constraint describing valid keys and how to rewrite
371 + * illegal ones.
372 + * @returns The sanitized schema (a copy) and a {@link KeyMapping} for restoring
373 + * the original keys. Use {@link mappingHasRenames} to tell whether
374 + * anything was rewritten.
375 + */
376 +export function sanitizeSchemaPropertyKeys<T extends Record<string, unknown>>(
377 + schema: T,
378 + policy: KeySanitizationPolicy
379 +): { schema: T; mapping: KeyMapping } {
380 + const { node, mapping } = sanitizeNode(schema, policy);
381 + return { schema: node as T, mapping };
382 +}
383 +
384 +/**
385 + * Restores original property names in a tool-call argument object using the
386 + * mapping produced by {@link sanitizeSchemaPropertyKeys}. The mapping is walked
387 + * in lockstep with the value, so a key is only renamed at the nesting level where
388 + * its alias was actually generated. Nested objects and arrays are handled
389 + * recursively. Returns a new value; the input is not mutated.
390 + */
391 +export function restoreOriginalKeys(value: unknown, mapping: KeyMapping, depth = 0): unknown {
392 + if (depth >= MAX_SCHEMA_DEPTH) {
393 + throw new Error(
394 + `Tool arguments nesting exceeded the maximum supported depth (${MAX_SCHEMA_DEPTH})`
395 + );
396 + }
397 +
398 + if (Array.isArray(value)) {
399 + const { items, restItems } = mapping;
400 + if (Array.isArray(items)) {
401 + return value.map((item, index) => {
402 + // Elements inside the tuple use their positional mapping; elements past it
403 + // use the trailing single-`items` rest mapping (2020-12), if any.
404 + const itemMapping = index < items.length ? items[index] : restItems;
405 + return itemMapping ? restoreOriginalKeys(item, itemMapping, depth + 1) : item;
406 + });
407 + }
408 + if (items) {
409 + return value.map(item => restoreOriginalKeys(item, items, depth + 1));
410 + }
411 + return value;
412 + }
413 +
414 + if (isPlainObject(value)) {
415 + // Prototype-free so a model-supplied key equal to an `Object.prototype`
416 + // member name (`__proto__`, `constructor`, …) is written as a plain own
417 + // property rather than reparenting the result or hitting an inherited member.
418 + const restored: Record<string, unknown> = Object.create(null);
419 + for (const [key, val] of Object.entries(value)) {
420 + // `renames`/`children` are themselves prototype-free (see `sanitizeNode`),
421 + // so these lookups return `undefined` for non-own keys instead of an
422 + // inherited function — no spurious rename and no crash on recursion.
423 + const originalKey = mapping.renames[key] ?? key;
424 + const childMapping = mapping.children[key];
425 + restored[originalKey] = childMapping
426 + ? restoreOriginalKeys(val, childMapping, depth + 1)
427 + : val;
428 + }
429 + return restored;
430 + }
431 +
432 + return value;
433 +}
ts/packages/providers/anthropic/src/index.ts
+49 -13
@@ -16,6 +16,7 @@ import {
16 logger,
17 McpUrlResponse,
18 normalizeToolArguments,
19 + dereferenceJsonSchema,
20 } from '@composio/core';
21 import Anthropic from '@anthropic-ai/sdk';
22 import { AnthropicTool, InputSchema } from './types';
@@ -67,11 +68,25 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
68 private chacheTools: boolean = false;
69
70 /**
70 - * Per-tool `sanitized -> original` property-key mappings, populated by
71 - * {@link wrapTool} whenever a tool's schema contains keys that violate
72 - * Anthropic's `^[a-zA-Z0-9_.-]{1,64}$` constraint. Used by
73 - * {@link executeToolCall} to restore the original parameter names before the
74 - * call reaches the Composio backend.
71 + * Per-tool reverse key mappings (`sanitized -> original`, shaped like the
72 + * schema), keyed by tool slug. Populated by {@link wrapTool} whenever a tool's
73 + * schema contains keys that violate Anthropic's `^[a-zA-Z0-9_.-]{1,64}$`
74 + * constraint, and read by {@link executeToolCall} to restore the original
75 + * parameter names before the call reaches the Composio backend.
76 + *
77 + * **Contract:** a tool must be wrapped and executed through the *same* provider
78 + * instance. This holds for the standard Composio flow — the model can only call
79 + * tools previously emitted by {@link wrapTools}/{@link wrapTool} on this
80 + * instance, and that wrapping registers the mapping. If a tool is somehow
81 + * executed on an instance that never wrapped it, no mapping is found and the
82 + * model's (already sanitized) argument keys are forwarded unchanged, so the
83 + * backend would see e.g. `dollar_top` instead of `$top`. {@link executeToolCall}
84 + * emits a `debug` log on the path that actually restores keys so this is
85 + * diagnosable.
86 + *
87 + * Re-wrapping a slug refreshes its entry (or clears it when the new schema
88 + * needs no rewriting), so the map stays consistent and its size is bounded by
89 + * the number of distinct sanitized tool slugs this instance has wrapped.
90 */
91 private toolKeyMappings: Map<string, KeyMapping> = new Map();
92
@@ -140,23 +155,40 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
155 required: [],
156 }) as InputSchema;
157
158 + // Inline internal `$ref` / `$defs` first so keys reachable only through a
159 + // reference become ordinary value positions that can be both sanitized and
160 + // restored. Lenient mode keeps an upstream schema with a dangling ref usable
161 + // (it degrades the branch to a permissive object) instead of throwing.
162 + const dereferenced = dereferenceJsonSchema(rawSchema, {
163 + onUnresolved: 'sentinel',
164 + onReplace: ref =>
165 + logger.debug(
166 + `AnthropicProvider: unresolved $ref "${ref}" in tool "${tool.slug}" replaced ` +
167 + `with a permissive schema`
168 + ),
169 + });
170 +
171 // Anthropic rejects the whole `tools` array if any property key falls outside
172 // `^[a-zA-Z0-9_.-]{1,64}$` (e.g. OData params like `$top`, `@odata.type`, or
173 // over-long flattened keys). Rewrite offending keys and remember how to undo it.
146 - const { schema, mapping } = sanitizeSchemaPropertyKeys(
147 - rawSchema as unknown as Record<string, unknown>
148 - );
174 + const { schema, mapping } = sanitizeSchemaPropertyKeys(dereferenced);
175
176 if (mappingHasRenames(mapping)) {
177 this.toolKeyMappings.set(tool.slug, mapping);
178 + logger.debug(
179 + `AnthropicProvider rewrote non-conforming schema keys for tool "${tool.slug}"; ` +
180 + `original parameter names will be restored at execution time`
181 + );
182 } else {
183 + // Clear any stale mapping from a previous wrap of the same slug whose
184 + // schema no longer needs rewriting, so restoration stays consistent.
185 this.toolKeyMappings.delete(tool.slug);
186 }
187
188 return {
189 name: tool.slug,
190 description: tool.description || '',
159 - input_schema: schema as unknown as InputSchema,
191 + input_schema: schema,
192 cache_control: this.chacheTools ? { type: 'ephemeral' } : undefined,
193 };
194 }
@@ -247,11 +279,15 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
279 const normalizedInput = normalizeToolArguments(toolUse.input, toolUse.name);
280
281 // Undo any key sanitization applied in `wrapTool` so the backend receives the
250 - // tool's original parameter names (e.g. `dollar_top` -> `$top`).
282 + // tool's original parameter names (e.g. `dollar_top` -> `$top`). The mapping
283 + // is only present when this same instance wrapped the tool and rewrote keys
284 + // (see `toolKeyMappings`); otherwise the arguments pass through untouched.
285 const mapping = this.toolKeyMappings.get(toolUse.name);
252 - const toolArguments = mapping
253 - ? (restoreOriginalKeys(normalizedInput, mapping) as Record<string, unknown>)
254 - : normalizedInput;
286 + let toolArguments = normalizedInput;
287 + if (mapping) {
288 + toolArguments = restoreOriginalKeys(normalizedInput, mapping) as Record<string, unknown>;
289 + logger.debug(`AnthropicProvider restored original argument keys for tool "${toolUse.name}"`);
290 + }
291
292 const payload: ToolExecuteParams = {
293 arguments: toolArguments,
ts/packages/providers/anthropic/src/sanitize-keys.ts
+62 -224
@@ -1,30 +1,30 @@
1 /**
2 - * Anthropic tool-schema key sanitization.
2 + * Anthropic-bound tool-schema key sanitization.
3 *
4 - * Anthropic's Messages API validates every tool `input_schema` property key
5 - * against the pattern `^[a-zA-Z0-9_.-]{1,64}$`. A single non-conforming key
6 - * makes the API reject the entire `tools` array with HTTP 400, so one bad tool
7 - * takes down every other tool in the same request.
4 + * The traversal/restoration mechanism lives in `@composio/core`
5 + * (`sanitizeSchemaPropertyKeys` / `restoreOriginalKeys`); this module supplies the
6 + * Anthropic key constraint as a {@link KeySanitizationPolicy} and re-exports a
7 + * policy-bound sanitizer plus the restore side, so call sites in this package
8 + * import everything from one place.
9 *
9 - * Composio tools can surface keys that break this pattern in two ways:
10 - * - **Illegal characters** — e.g. the OneDrive toolkit exposes Microsoft Graph
11 - * OData parameters such as `$top`, `$filter` or `@microsoft.graph.conflictBehavior`
12 - * whose `$` and `@` are outside the allowed set.
13 - * - **Length** — flattening nested objects with `__` separators can produce keys
14 - * longer than 64 characters (e.g. several Zoom tools).
10 + * Anthropic's Messages API validates every property key against
11 + * `^[a-zA-Z0-9_.-]{1,64}$` and rejects the entire `tools` array on a single
12 + * violation. Composio tools can surface keys that break this — OData parameters
13 + * like `$top` / `@microsoft.graph.conflictBehavior` (illegal `$`/`@`), or
14 + * over-long `__`-flattened keys.
15 *
16 - * This module rewrites offending keys to conforming aliases before the schema is
17 - * sent to Anthropic, and records a reverse mapping so the original parameter names
18 - * can be restored before a tool call is executed against the Composio backend.
19 - *
20 - * The reverse mapping mirrors the schema's nesting (object `properties` and array
21 - * `items`) rather than being a single flat lookup. This matters because an alias
22 - * generated at one nesting level (e.g. `$top` -> `dollar_top`) must not rewrite a
23 - * legitimately-named `dollar_top` key that happens to exist at a different level.
24 - *
25 - * @packageDocumentation
16 * @module providers/anthropic/sanitize-keys
17 */
18 +import {
19 + sanitizeSchemaPropertyKeys as sanitizeWithPolicy,
20 + restoreOriginalKeys,
21 + mappingHasRenames,
22 + type KeyMapping,
23 + type KeySanitizationPolicy,
24 +} from '@composio/core';
25 +
26 +export { restoreOriginalKeys, mappingHasRenames };
27 +export type { KeyMapping };
28
29 /** Anthropic's allowed property-key pattern. */
30 const VALID_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;
@@ -33,45 +33,16 @@ const VALID_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;
33 const MAX_KEY_LENGTH = 64;
34
35 /**
36 - * Readable replacements for the most common illegal characters so aliases stay
37 - * recognizable (e.g. `$top` -> `dollar_top`, `@odata.type` -> `at_odata.type`).
38 - * Any other illegal character falls back to `_`. Mirrors the Python SDK's
39 - * sanitization for cross-language consistency.
36 + * Readable replacements for the two most common illegal characters — the OData
37 + * prefixes Composio surfaces — so aliases stay recognizable on the wire (e.g.
38 + * `$top` -> `dollar_top`, `@odata.type` -> `at_odata.type`). Any other illegal
39 + * character falls back to `_` (see {@link sanitizeKey}).
40 */
41 const ILLEGAL_CHAR_MAP: Record<string, string> = {
42 $: 'dollar_',
43 '@': 'at_',
44 };
45
46 -/**
47 - * Reverse mapping used to restore original property names at execution time.
48 - *
49 - * It is shaped like the schema it was derived from so restoration is scoped to
50 - * the exact location a rename happened:
51 - * - `renames` — `sanitized -> original` for keys renamed at *this* object level.
52 - * - `children` — restoration mapping for the value under each (sanitized) key,
53 - * keyed by the sanitized key. Only present for children that contain renames.
54 - * - `items` — restoration mapping for array element values. A single mapping
55 - * applies to every element; an array of mappings applies positionally (JSON
56 - * Schema tuple validation). Only present when array elements contain renames.
57 - */
58 -export interface KeyMapping {
59 - renames: Record<string, string>;
60 - children: Record<string, KeyMapping>;
61 - items?: KeyMapping | (KeyMapping | null)[];
62 -}
63 -
64 -/** Whether a mapping (or any of its descendants) actually renames a key. */
65 -export function mappingHasRenames(mapping: KeyMapping): boolean {
66 - // `children` and `items` are only populated when they carry renames (see
67 - // `sanitizeNode`), so this stays a shallow check.
68 - return (
69 - Object.keys(mapping.renames).length > 0 ||
70 - Object.keys(mapping.children).length > 0 ||
71 - mapping.items != null
72 - );
73 -}
74 -
46 /**
47 * Deterministic, dependency-free hash (djb2) rendered as a short base-36 string.
48 * Used as a uniqueness suffix when truncating long keys or resolving collisions.
@@ -85,15 +56,11 @@ function shortHash(input: string): string {
56 return (hash >>> 0).toString(36).slice(0, 7);
57 }
58
88 -/** Whether a key is already valid for Anthropic and needs no rewriting. */
89 -function isValidKey(name: string): boolean {
90 - return VALID_KEY_RE.test(name);
91 -}
92 -
59 /**
60 * Rewrites a single key so it matches Anthropic's pattern. Replaces known illegal
95 - * characters with readable aliases, any remaining illegal character with `_`, and
96 - * truncates keys over 64 characters with a deterministic hash suffix.
61 + * characters with readable aliases, any remaining illegal character with `_`,
62 + * substitutes a non-empty fallback for an otherwise-empty result, and truncates
63 + * keys over 64 characters with a deterministic hash suffix.
64 */
65 function sanitizeKey(name: string): string {
66 let sanitized = name;
@@ -102,6 +69,13 @@ function sanitizeKey(name: string): string {
69 }
70 sanitized = sanitized.replace(/[^a-zA-Z0-9_.-]/g, '_');
71
72 + // Anthropic's pattern requires at least one character; an empty original (or
73 + // one made entirely of stripped characters) would otherwise emit `''`, which
74 + // still fails validation. Fall back to a deterministic non-empty alias.
75 + if (sanitized.length === 0) {
76 + sanitized = `key_${shortHash(name)}`;
77 + }
78 +
79 if (sanitized.length > MAX_KEY_LENGTH) {
80 const suffix = `_${shortHash(name)}`;
81 sanitized = sanitized.slice(0, MAX_KEY_LENGTH - suffix.length) + suffix;
@@ -110,177 +84,41 @@ function sanitizeKey(name: string): string {
84 return sanitized;
85 }
86
113 -/** Returns a sanitized key guaranteed to be unique within `taken`. */
114 -function uniqueSanitizedKey(name: string, taken: Set<string>): string {
115 - let candidate = sanitizeKey(name);
116 - if (!taken.has(candidate)) {
117 - return candidate;
118 - }
119 - // Collision (different originals mapping to the same alias) — append a hash.
120 - const suffix = `_${shortHash(name)}`;
121 - const base = candidate.slice(0, MAX_KEY_LENGTH - suffix.length);
122 - candidate = base + suffix;
123 - while (taken.has(candidate)) {
124 - candidate = `${candidate.slice(0, MAX_KEY_LENGTH - 1)}_`;
125 - }
126 - return candidate;
127 -}
87 +/** The Anthropic key-sanitization policy consumed by core's sanitizer. */
88 +const anthropicKeyPolicy: KeySanitizationPolicy = {
89 + isValidKey(name) {
90 + return VALID_KEY_RE.test(name);
91 + },
92
129 -function isPlainObject(value: unknown): value is Record<string, unknown> {
130 - return typeof value === 'object' && value !== null && !Array.isArray(value);
131 -}
132 -
133 -/**
134 - * Recursively sanitizes the property keys of a JSON-schema node, returning the
135 - * rewritten node and a {@link KeyMapping} shaped like the node. Both object
136 - * `properties` and array `items` schemas are traversed, matching how Composio
137 - * nests its tool parameters.
138 - *
139 - * The input node is never mutated; a new node is returned.
140 - */
141 -function sanitizeNode(node: Record<string, unknown>): {
142 - node: Record<string, unknown>;
143 - mapping: KeyMapping;
144 -} {
145 - const result: Record<string, unknown> = { ...node };
146 - const renames: Record<string, string> = {};
147 - const children: Record<string, KeyMapping> = {};
148 - let items: KeyMapping | (KeyMapping | null)[] | undefined;
149 -
150 - const properties = node.properties;
151 - if (isPlainObject(properties)) {
152 - const newProperties: Record<string, unknown> = {};
153 - const renamedOriginalToSanitized: Record<string, string> = {};
154 -
155 - // Reserve all already-valid keys up front so they keep their exact names and
156 - // sanitized aliases are generated around them (a valid `dollar_top` must not
157 - // be clobbered by a sanitized `$top`).
158 - const taken = new Set<string>();
159 - for (const key of Object.keys(properties)) {
160 - if (isValidKey(key)) {
161 - taken.add(key);
162 - }
93 + aliasKey(name, taken) {
94 + const candidate = sanitizeKey(name);
95 + if (!taken.has(candidate)) {
96 + return candidate;
97 }
164 -
165 - for (const [key, rawValue] of Object.entries(properties)) {
166 - const safeKey = isValidKey(key) ? key : uniqueSanitizedKey(key, taken);
167 - taken.add(safeKey);
168 -
169 - const child = isPlainObject(rawValue) ? sanitizeNode(rawValue) : null;
170 - newProperties[safeKey] = child ? child.node : rawValue;
171 - if (child && mappingHasRenames(child.mapping)) {
172 - children[safeKey] = child.mapping;
173 - }
174 -
175 - if (safeKey !== key) {
176 - renames[safeKey] = key;
177 - renamedOriginalToSanitized[key] = safeKey;
178 - }
179 - }
180 -
181 - result.properties = newProperties;
182 -
183 - // Keep `required` in sync with the renamed keys at this level.
184 - if (Array.isArray(node.required)) {
185 - result.required = node.required.map(name =>
186 - typeof name === 'string' && renamedOriginalToSanitized[name]
187 - ? renamedOriginalToSanitized[name]
188 - : name
189 - );
190 - }
191 - }
192 -
193 - // Recurse into array element schemas so illegal keys nested inside array items
194 - // (e.g. `{ type: 'array', items: { properties: { $top: ... } } }`) are sanitized
195 - // too — `properties`-only traversal would let them through and still 400.
196 - const itemsSchema = node.items;
197 - if (isPlainObject(itemsSchema)) {
198 - const child = sanitizeNode(itemsSchema);
199 - result.items = child.node;
200 - if (mappingHasRenames(child.mapping)) {
201 - items = child.mapping;
202 - }
203 - } else if (Array.isArray(itemsSchema)) {
204 - // Tuple validation: one positional schema per array index.
205 - const sanitizedItems: unknown[] = [];
206 - const itemMappings: (KeyMapping | null)[] = [];
207 - let anyRenamed = false;
208 - for (const entry of itemsSchema) {
209 - if (isPlainObject(entry)) {
210 - const child = sanitizeNode(entry);
211 - sanitizedItems.push(child.node);
212 - if (mappingHasRenames(child.mapping)) {
213 - itemMappings.push(child.mapping);
214 - anyRenamed = true;
215 - } else {
216 - itemMappings.push(null);
217 - }
218 - } else {
219 - sanitizedItems.push(entry);
220 - itemMappings.push(null);
221 - }
222 - }
223 - result.items = sanitizedItems;
224 - if (anyRenamed) {
225 - items = itemMappings;
98 + // Collision (different originals mapping to the same alias) — append a hash,
99 + // then an incrementing counter if that still collides. The counter changes
100 + // every iteration, so this always makes progress and can't spin.
101 + const suffix = `_${shortHash(name)}`;
102 + const base = candidate.slice(0, MAX_KEY_LENGTH - suffix.length);
103 + let resolved = base + suffix;
104 + for (let counter = 1; taken.has(resolved); counter++) {
105 + const tail = `${suffix}_${counter}`;
106 + resolved = base.slice(0, MAX_KEY_LENGTH - tail.length) + tail;
107 }
227 - }
228 -
229 - const mapping: KeyMapping = { renames, children };
230 - if (items !== undefined) {
231 - mapping.items = items;
232 - }
233 -
234 - return { node: result, mapping };
235 -}
108 + return resolved;
109 + },
110 +};
111
112 /**
238 - * Sanitizes a tool `input_schema` so all property keys conform to Anthropic's
239 - * pattern.
113 + * Sanitizes a tool `input_schema` so every property key satisfies Anthropic's
114 + * `^[a-zA-Z0-9_.-]{1,64}$` constraint, returning the rewritten schema and a
115 + * {@link KeyMapping} for restoring the original keys at execution time.
116 *
241 - * @param schema - The tool input schema to sanitize.
242 - * @returns The sanitized schema (a copy) and a {@link KeyMapping} for restoring
243 - * the original keys. Use {@link mappingHasRenames} to tell whether
244 - * anything was rewritten.
117 + * `inputParameters` should be dereferenced first (see `wrapTool`) so keys that
118 + * are reachable only through a `$ref` are sanitized and restored as well.
119 */
120 export function sanitizeSchemaPropertyKeys<T extends Record<string, unknown>>(
121 schema: T
122 ): { schema: T; mapping: KeyMapping } {
249 - const { node, mapping } = sanitizeNode(schema);
250 - return { schema: node as T, mapping };
251 -}
252 -
253 -/**
254 - * Restores original property names in a tool-call argument object using the
255 - * mapping produced by {@link sanitizeSchemaPropertyKeys}. The mapping is walked
256 - * in lockstep with the value, so a key is only renamed at the nesting level where
257 - * its alias was actually generated. Nested objects and arrays are handled
258 - * recursively. Returns a new value; the input is not mutated.
259 - */
260 -export function restoreOriginalKeys(value: unknown, mapping: KeyMapping): unknown {
261 - if (Array.isArray(value)) {
262 - const { items } = mapping;
263 - if (Array.isArray(items)) {
264 - return value.map((item, index) => {
265 - const itemMapping = items[index];
266 - return itemMapping ? restoreOriginalKeys(item, itemMapping) : item;
267 - });
268 - }
269 - if (items) {
270 - return value.map(item => restoreOriginalKeys(item, items));
271 - }
272 - return value;
273 - }
274 -
275 - if (isPlainObject(value)) {
276 - const restored: Record<string, unknown> = {};
277 - for (const [key, val] of Object.entries(value)) {
278 - const originalKey = mapping.renames[key] ?? key;
279 - const childMapping = mapping.children[key];
280 - restored[originalKey] = childMapping ? restoreOriginalKeys(val, childMapping) : val;
281 - }
282 - return restored;
283 - }
284 -
285 - return value;
123 + return sanitizeWithPolicy(schema, anthropicKeyPolicy);
124 }
ts/packages/providers/anthropic/test/sanitize-keys.test.ts
+308
@@ -196,6 +196,215 @@ describe('sanitizeSchemaPropertyKeys', () => {
196 const restored = restoreOriginalKeys({ pair: [{ dollar_top: 9 }, { plain: 'x' }] }, mapping);
197 expect(restored).toEqual({ pair: [{ $top: 9 }, { plain: 'x' }] });
198 });
199 +
200 + // A key that is empty (or made entirely of stripped characters) would emit
201 + // `''`, which still violates Anthropic's `{1,64}` length bound.
202 + it('emits a non-empty conforming alias for empty / all-illegal keys', () => {
203 + const schema = {
204 + type: 'object',
205 + properties: { '': { type: 'string' }, '@@@': { type: 'integer' } },
206 + };
207 +
208 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
209 + const keys = Object.keys(out.properties as Record<string, unknown>);
210 +
211 + expect(keys).toHaveLength(2);
212 + keys.forEach(k => expect(k).toMatch(ANTHROPIC_KEY_RE)); // each ≥ 1 char and conforming
213 + expect(new Set(Object.values(mapping.renames))).toEqual(new Set(['', '@@@']));
214 + });
215 +
216 + // Pathologically deep schemas must fail loudly rather than overflow the stack.
217 + it('throws instead of overflowing the stack on deeply nested schemas', () => {
218 + let deep: Record<string, unknown> = {
219 + type: 'object',
220 + properties: { $x: { type: 'integer' } },
221 + };
222 + for (let i = 0; i < 2000; i++) {
223 + deep = { type: 'object', properties: { nested: deep } };
224 + }
225 +
226 + expect(() => sanitizeSchemaPropertyKeys(deep)).toThrow(/depth/i);
227 + });
228 +
229 + // Property keys that collide with `Object.prototype` member names must be
230 + // treated as ordinary keys, never reparent the emitted schema, and never
231 + // mutate `Object.prototype`. Built via JSON.parse so `__proto__` is a real
232 + // own key rather than prototype-setting literal syntax.
233 + it('treats prototype-member property names as ordinary keys', () => {
234 + const schema = JSON.parse(
235 + '{"type":"object","properties":{"$top":{"type":"integer"},"__proto__":{"type":"string"},"constructor":{"type":"string"}}}'
236 + );
237 +
238 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
239 + const props = out.properties as Record<string, unknown>;
240 +
241 + expect(Object.prototype.hasOwnProperty.call(props, '__proto__')).toBe(true);
242 + expect(Object.prototype.hasOwnProperty.call(props, 'constructor')).toBe(true);
243 + expect(props['constructor']).toEqual({ type: 'string' });
244 + expect(({} as Record<string, unknown>).type).toBeUndefined(); // prototype untouched
245 +
246 + const restored = restoreOriginalKeys({ dollar_top: 1, constructor: 'c' }, mapping) as Record<
247 + string,
248 + unknown
249 + >;
250 + expect(restored['$top']).toBe(1);
251 + expect(restored['constructor']).toBe('c');
252 + });
253 +});
254 +
255 +describe('sanitizeSchemaPropertyKeys composition coverage', () => {
256 + // Asserts every emitted `properties` key (at any depth) conforms to Anthropic's
257 + // pattern — i.e. nothing illegal slipped through the traversal and could 400.
258 + const expectNoIllegalPropertyKeys = (schema: unknown) => {
259 + const walk = (node: unknown): void => {
260 + if (Array.isArray(node)) return node.forEach(walk);
261 + if (!node || typeof node !== 'object') return;
262 + const obj = node as Record<string, unknown>;
263 + if (obj.properties && typeof obj.properties === 'object') {
264 + for (const key of Object.keys(obj.properties as Record<string, unknown>)) {
265 + expect(key).toMatch(ANTHROPIC_KEY_RE);
266 + }
267 + }
268 + Object.values(obj).forEach(walk);
269 + };
270 + walk(schema);
271 + };
272 +
273 + it('sanitizes and restores illegal keys nested under `anyOf` branches', () => {
274 + const schema = {
275 + type: 'object',
276 + properties: {
277 + foo: {
278 + anyOf: [
279 + { type: 'object', properties: { $top: { type: 'integer' } }, required: ['$top'] },
280 + { type: 'object', properties: { bar: { type: 'string' } } },
281 + ],
282 + },
283 + },
284 + };
285 +
286 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
287 + expectNoIllegalPropertyKeys(out);
288 + expect((out.properties as any).foo.anyOf[0].properties).toHaveProperty('dollar_top');
289 +
290 + // The branch rename folds into `foo`'s value level, so restoration finds it.
291 + expect(restoreOriginalKeys({ foo: { dollar_top: 5 } }, mapping)).toEqual({ foo: { $top: 5 } });
292 + });
293 +
294 + it('merges `oneOf` / `allOf` renames into the shared value level', () => {
295 + const oneOf = sanitizeSchemaPropertyKeys({
296 + type: 'object',
297 + oneOf: [{ properties: { $top: { type: 'integer' } } }, { properties: { plain: {} } }],
298 + });
299 + expectNoIllegalPropertyKeys(oneOf.schema);
300 + expect(restoreOriginalKeys({ dollar_top: 1 }, oneOf.mapping)).toEqual({ $top: 1 });
301 +
302 + const allOf = sanitizeSchemaPropertyKeys({
303 + type: 'object',
304 + properties: { keep: { type: 'string' } },
305 + allOf: [{ properties: { '@odata.type': { type: 'string' } } }],
306 + });
307 + expectNoIllegalPropertyKeys(allOf.schema);
308 + expect(restoreOriginalKeys({ 'at_odata.type': 'x', keep: 'y' }, allOf.mapping)).toEqual({
309 + '@odata.type': 'x',
310 + keep: 'y',
311 + });
312 + });
313 +
314 + it('selects the right branch mapping by value type for a mixed `anyOf`', () => {
315 + const { mapping } = sanitizeSchemaPropertyKeys({
316 + type: 'object',
317 + properties: {
318 + field: {
319 + anyOf: [
320 + { type: 'array', items: { type: 'object', properties: { $top: { type: 'integer' } } } },
321 + { type: 'object', properties: { $skip: { type: 'integer' } } },
322 + ],
323 + },
324 + },
325 + });
326 +
327 + // Array value → array-branch (`items`) mapping; object value → object branch.
328 + expect(restoreOriginalKeys({ field: [{ dollar_top: 1 }] }, mapping)).toEqual({
329 + field: [{ $top: 1 }],
330 + });
331 + expect(restoreOriginalKeys({ field: { dollar_skip: 2 } }, mapping)).toEqual({
332 + field: { $skip: 2 },
333 + });
334 + });
335 +
336 + it('sanitizes (but does not restore) keys nested under `additionalProperties`', () => {
337 + const schema = {
338 + type: 'object',
339 + properties: {},
340 + additionalProperties: { type: 'object', properties: { $top: { type: 'integer' } } },
341 + };
342 +
343 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
344 + // 400-prevention: the alias is emitted so Anthropic accepts the schema.
345 + expect((out as any).additionalProperties.properties).toHaveProperty('dollar_top');
346 + // Documented limitation: dynamic-key values are not restored — the alias
347 + // reaches the backend rather than being silently (mis)mapped at every level.
348 + expect(restoreOriginalKeys({ anyKey: { dollar_top: 1 } }, mapping)).toEqual({
349 + anyKey: { dollar_top: 1 },
350 + });
351 + });
352 +
353 + it('sanitizes keys nested under `$defs` for Anthropic acceptance', () => {
354 + const { schema: out } = sanitizeSchemaPropertyKeys({
355 + type: 'object',
356 + properties: { x: { $ref: '#/$defs/Foo' } },
357 + $defs: { Foo: { type: 'object', properties: { $top: { type: 'integer' } } } },
358 + });
359 +
360 + expectNoIllegalPropertyKeys(out);
361 + expect((out as any).$defs.Foo.properties).toHaveProperty('dollar_top');
362 + });
363 +
364 + it('sanitizes and restores `prefixItems` tuples', () => {
365 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys({
366 + type: 'object',
367 + properties: {
368 + pair: {
369 + type: 'array',
370 + prefixItems: [
371 + { type: 'object', properties: { $top: { type: 'integer' } } },
372 + { type: 'object', properties: { plain: { type: 'string' } } },
373 + ],
374 + },
375 + },
376 + });
377 +
378 + expectNoIllegalPropertyKeys(out);
379 + expect(restoreOriginalKeys({ pair: [{ dollar_top: 9 }, { plain: 'x' }] }, mapping)).toEqual({
380 + pair: [{ $top: 9 }, { plain: 'x' }],
381 + });
382 + });
383 +
384 + it('restores a `prefixItems` tuple and a trailing `items` rest schema independently', () => {
385 + // 2020-12: `prefixItems` pins positions 0..n-1; a sibling single `items` schema
386 + // applies to every element past the tuple. Both carry illegal keys that must
387 + // round-trip at their own positions — the prefix rename must not be dropped,
388 + // and the rest mapping must not bleed onto the prefix position.
389 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys({
390 + type: 'object',
391 + properties: {
392 + tuple: {
393 + type: 'array',
394 + prefixItems: [{ type: 'object', properties: { $top: { type: 'integer' } } }],
395 + items: { type: 'object', properties: { '@odata.type': { type: 'string' } } },
396 + },
397 + },
398 + });
399 +
400 + expectNoIllegalPropertyKeys(out);
401 + expect(
402 + restoreOriginalKeys(
403 + { tuple: [{ dollar_top: 5 }, { 'at_odata.type': 'a' }, { 'at_odata.type': 'b' }] },
404 + mapping
405 + )
406 + ).toEqual({ tuple: [{ $top: 5 }, { '@odata.type': 'a' }, { '@odata.type': 'b' }] });
407 + });
408 });
409
410 describe('restoreOriginalKeys', () => {
@@ -253,6 +462,34 @@ describe('restoreOriginalKeys', () => {
462 filters: { dollar_top: 'keep-me' }, // nested genuine key left alone
463 });
464 });
465 +
466 + // Security: a model can emit argument keys equal to Object.prototype member
467 + // names (and `__proto__` reaches restoration via the JSON-string input path).
468 + // Restoration must not crash, must not corrupt the payload, and must never
469 + // mutate Object.prototype — the reverse maps and result object are all
470 + // prototype-free.
471 + it('handles prototype-member keys in tool arguments without crashing or polluting', () => {
472 + const { mapping } = sanitizeSchemaPropertyKeys({
473 + type: 'object',
474 + properties: { $top: { type: 'integer' }, name: { type: 'string' } },
475 + required: ['$top'],
476 + });
477 +
478 + const input = JSON.parse(
479 + '{"dollar_top":1,"constructor":{"inner":2},"toString":"t","__proto__":{"polluted":true},"hasOwnProperty":"h","name":"n"}'
480 + );
481 +
482 + // Threw with `TypeError` before this PR's hardening (lookups resolved to the
483 + // inherited `Object` function); a plain assignment here would also fail.
484 + const restored = restoreOriginalKeys(input, mapping) as Record<string, unknown>;
485 +
486 + expect(restored['$top']).toBe(1);
487 + expect(restored['name']).toBe('n');
488 + expect(restored['toString']).toBe('t');
489 + expect(restored['hasOwnProperty']).toBe('h');
490 + expect((restored['constructor'] as Record<string, unknown>).inner).toBe(2);
491 + expect(({} as Record<string, unknown>).polluted).toBeUndefined(); // prototype untouched
492 + });
493 });
494
495 describe('AnthropicProvider key sanitization', () => {
@@ -381,4 +618,75 @@ describe('AnthropicProvider key sanitization', () => {
618 const [, payload] = executeToolFn.mock.calls[0];
619 expect(payload.arguments).toEqual({ query: 'hello' });
620 });
621 +
622 + // Re-wrapping the same slug with a schema that no longer needs rewriting must
623 + // clear the stale mapping, so a later execution does not restore keys that the
624 + // current schema never sanitized.
625 + it('clears a stale key mapping when a slug is re-wrapped with a clean schema', async () => {
626 + const provider = new AnthropicProvider();
627 + const executeToolFn = vi
628 + .fn()
629 + .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
630 + provider._setExecuteToolFn(executeToolFn);
631 +
632 + // First wrap registers a `dollar_top -> $top` mapping for this slug.
633 + provider.wrapTool(odataTool);
634 +
635 + // Re-wrap the SAME slug with a schema that has no illegal keys.
636 + const cleanedTool: Tool = {
637 + ...odataTool,
638 + inputParameters: { type: 'object', properties: { dollar_top: { type: 'integer' } } },
639 + } as unknown as Tool;
640 + provider.wrapTool(cleanedTool);
641 +
642 + // The model now legitimately sends `dollar_top`; it must reach the backend
643 + // unchanged rather than being restored to `$top` by the stale mapping.
644 + await provider.executeToolCall('user-1', {
645 + type: 'tool_use',
646 + id: 'tu_5',
647 + name: odataTool.slug,
648 + input: { dollar_top: 7 },
649 + });
650 +
651 + const [, payload] = executeToolFn.mock.calls[0];
652 + expect(payload.arguments).toEqual({ dollar_top: 7 });
653 + });
654 +
655 + // `wrapTool` dereferences `$ref`/`$defs` before sanitizing, so an illegal key
656 + // reachable only through a reference is both made compliant for Anthropic and
657 + // restored to its original name at execution time.
658 + it('dereferences $ref so $ref-nested illegal keys round-trip', async () => {
659 + const provider = new AnthropicProvider();
660 + const executeToolFn = vi
661 + .fn()
662 + .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
663 + provider._setExecuteToolFn(executeToolFn);
664 +
665 + const refTool: Tool = {
666 + slug: 'ref-tool',
667 + name: 'Ref',
668 + description: 'uses $ref into $defs',
669 + inputParameters: {
670 + type: 'object',
671 + properties: { filter: { $ref: '#/$defs/Filter' } },
672 + $defs: { Filter: { type: 'object', properties: { $top: { type: 'integer' } } } },
673 + },
674 + tags: [],
675 + } as unknown as Tool;
676 +
677 + const wrapped = provider.wrapTool(refTool) as AnthropicTool;
678 + // The $ref is inlined, `$defs` removed, and the nested `$top` sanitized.
679 + expect((wrapped.input_schema.properties as any).filter.properties).toHaveProperty('dollar_top');
680 + expect((wrapped.input_schema as any).$defs).toBeUndefined();
681 +
682 + await provider.executeToolCall('user-1', {
683 + type: 'tool_use',
684 + id: 'tu_ref',
685 + name: 'ref-tool',
686 + input: { filter: { dollar_top: 3 } },
687 + });
688 +
689 + const [, payload] = executeToolFn.mock.calls[0];
690 + expect(payload.arguments).toEqual({ filter: { $top: 3 } });
691 + });
692 });