Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(anthropic): harden tool property-key sanitizer (#3650)
Alberto Schiabel507318d56a0b
diff --git a/.changeset/anthropic-sanitize-keys-hardening.md b/.changeset/anthropic-sanitize-keys-hardening.mdnew file mode 100644index 000000000..67a37653f--- /dev/null+++ b/.changeset/anthropic-sanitize-keys-hardening.md@@ -0,0 +1,14 @@+---+'@composio/anthropic': patch+---++Harden the Anthropic tool property-key sanitizer:++- **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).+- **`$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.+- **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.+- **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.+- **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.+- **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.+- **Collision loop.** Replaced a latent non-terminating fixed point in the alias collision resolver with a counter that always makes progress.+- **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.diff --git a/.changeset/core-schema-property-key-sanitizer.md b/.changeset/core-schema-property-key-sanitizer.mdnew file mode 100644index 000000000..bebf58f0b--- /dev/null+++ b/.changeset/core-schema-property-key-sanitizer.md@@ -0,0 +1,7 @@+---+'@composio/core': patch+---++Add a provider-agnostic JSON-schema property-key sanitizer: `sanitizeSchemaPropertyKeys(schema, policy)`, `restoreOriginalKeys(value, mapping)`, `mappingHasRenames(mapping)`, and the `KeyMapping` / `KeySanitizationPolicy` types.++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.diff --git a/ts/packages/core/src/index.ts b/ts/packages/core/src/index.tsindex 7395d56a1..327493d3c 100644--- a/ts/packages/core/src/index.ts+++ b/ts/packages/core/src/index.ts@@ -16,6 +16,12 @@ export type {} from './utils/jsonSchema';export { getExtensionFromMimeType } from './utils/mime';export { normalizeToolArguments } from './utils/toolArguments';+export {+ sanitizeSchemaPropertyKeys,+ restoreOriginalKeys,+ mappingHasRenames,+} from './utils/schemaPropertyKeys';+export type { KeyMapping, KeySanitizationPolicy } from './utils/schemaPropertyKeys';export { AuthScheme } from './models/AuthScheme';export { MCP } from './models/MCP';export { RemoteFile } from './models/RemoteFile';diff --git a/ts/packages/core/src/utils/schemaPropertyKeys.ts b/ts/packages/core/src/utils/schemaPropertyKeys.tsnew file mode 100644index 000000000..2ad24f7c9--- /dev/null+++ b/ts/packages/core/src/utils/schemaPropertyKeys.ts@@ -0,0 +1,433 @@+/**+ * JSON-schema property-key sanitization.+ *+ * Some providers constrain the characters and/or length of tool `input_schema`+ * property keys (e.g. Anthropic's Messages API validates every key against+ * `^[a-zA-Z0-9_.-]{1,64}$` and rejects the whole `tools` array on a single+ * violation). Composio tool schemas can surface keys that break such rules —+ * OData parameters like `$top` / `@microsoft.graph.conflictBehavior`, or+ * over-long `__`-flattened keys.+ *+ * This module rewrites offending keys to conforming aliases before the schema is+ * sent to the provider, and records a reverse mapping so the original parameter+ * names can be restored before a tool call is executed against the Composio+ * backend. The *constraint* (which keys are valid and how an illegal key is+ * rewritten) is injected as a {@link KeySanitizationPolicy} so the mechanism+ * stays provider-agnostic; the traversal, collision handling, reverse mapping,+ * prototype safety and depth cap live here.+ *+ * The reverse mapping mirrors the schema's nesting (object `properties`, array+ * `items`/`prefixItems`, and the composition keywords `allOf`/`anyOf`/`oneOf` /+ * `not`/`if`/`then`/`else`, whose renames fold into the value level they share)+ * rather than being a single flat lookup. This matters because an alias generated+ * at one nesting level (e.g. `$top` -> `dollar_top`) must not rewrite a+ * legitimately-named `dollar_top` key that happens to exist at a different level.+ * Keys nested only under dynamic / `$ref` positions (`additionalProperties`,+ * `patternProperties`, `$defs`/`definitions`, `contains`) are still rewritten so+ * the provider accepts the schema, but are not restored — see the keyword lists+ * below. Dereferencing the schema first (see `dereferenceJsonSchema`) inlines+ * `$ref`/`$defs` into restorable value positions, shrinking that residual gap.+ *+ * @packageDocumentation+ * @module utils/schemaPropertyKeys+ */++import { isPlainObject } from './modifiers/FileToolModifier.utils.neutral';++/** Maximum schema nesting we traverse, matching `dereferenceJsonSchema`'s cap. */+const MAX_SCHEMA_DEPTH = 512;++/**+ * Provider-specific key constraint. The mechanism reserves every already-valid+ * sibling key before aliasing, so {@link aliasKey} only needs to produce a+ * conforming alias that is distinct from the supplied `taken` set.+ */+export interface KeySanitizationPolicy {+ /** Whether a key already conforms to the provider's constraint. */+ isValidKey(key: string): boolean;+ /**+ * Produce a conforming alias for an illegal `key`, guaranteed distinct from+ * every entry in `taken` (the already-assigned keys at the same object level).+ */+ aliasKey(key: string, taken: ReadonlySet<string>): string;+}++/**+ * Reverse mapping used to restore original property names at execution time.+ *+ * It is shaped like the schema it was derived from so restoration is scoped to+ * the exact location a rename happened:+ * - `renames` — `sanitized -> original` for keys renamed at *this* value level+ * (including renames folded in from composition keywords).+ * - `children` — restoration mapping for the value under each (sanitized) key,+ * keyed by the sanitized key. Only present for children that contain renames.+ * - `items` — restoration mapping for array element values. A single mapping+ * applies to every element; an array of mappings applies positionally (JSON+ * Schema tuple validation / `prefixItems`). Only present when array elements+ * contain renames.+ * - `restItems` — restoration mapping for array elements *past* a positional+ * `items`/`prefixItems` tuple (a 2020-12 single `items` schema sitting next to+ * `prefixItems`). Only present when those trailing elements contain renames.+ */+export interface KeyMapping {+ renames: Record<string, string>;+ children: Record<string, KeyMapping>;+ items?: KeyMapping | (KeyMapping | null)[];+ restItems?: KeyMapping;+}++/** Whether a mapping (or any of its descendants) actually renames a key. */+export function mappingHasRenames(mapping: KeyMapping): boolean {+ // `children` and `items` are only populated when they carry renames (see+ // `sanitizeNode`), so this stays a shallow check.+ return (+ Object.keys(mapping.renames).length > 0 ||+ Object.keys(mapping.children).length > 0 ||+ mapping.items != null ||+ mapping.restItems != null+ );+}++/**+ * Composition/applicator keywords whose sub-schema(s) constrain the *same* value+ * as the parent. Property-key renames generated inside them are merged into the+ * parent's value level, because the value carries no extra nesting for these+ * keywords. `not`/`if`/`then`/`else` hold a single sub-schema; `allOf`/`anyOf`/+ * `oneOf` hold an array of sub-schemas.+ */+const COMPOSITION_SINGLE_KEYWORDS = ['not', 'if', 'then', 'else'] as const;+const COMPOSITION_LIST_KEYWORDS = ['allOf', 'anyOf', 'oneOf'] as const;++/**+ * Positions whose nested keys are rewritten so the provider accepts the schema,+ * but which we cannot tie to a concrete value position for restoration: dynamic+ * keys (`additionalProperties`, `patternProperties`) and `$ref` targets (`$defs`/+ * `definitions`, unresolved unless the caller dereferences first), plus+ * `contains`. A value filled via an alias generated here reaches the backend+ * un-restored — strictly better than the whole `tools` array being rejected.+ */+const REWRITE_ONLY_SINGLE_KEYWORDS = ['additionalProperties', 'contains'] as const;+const REWRITE_ONLY_MAP_KEYWORDS = ['patternProperties', '$defs', 'definitions'] as const;++/**+ * Sanitizes a single sub-schema. Returns the rewritten node and its mapping, or+ * a `null` mapping when nothing inside it was renamed (keeps mappings sparse).+ */+function sanitizeSubschema(+ value: unknown,+ policy: KeySanitizationPolicy,+ depth: number+): { node: unknown; mapping: KeyMapping | null } {+ if (!isPlainObject(value)) {+ return { node: value, mapping: null };+ }+ const { node, mapping } = sanitizeNode(value, policy, depth + 1);+ return { node, mapping: mappingHasRenames(mapping) ? mapping : null };+}++/** Sanitizes an array of positional sub-schemas (tuple `items` / `prefixItems`). */+function sanitizeTuple(+ entries: unknown[],+ policy: KeySanitizationPolicy,+ depth: number+): { nodes: unknown[]; mappings: (KeyMapping | null)[] | undefined } {+ const nodes: unknown[] = [];+ const mappings: (KeyMapping | null)[] = [];+ let anyRenamed = false;+ for (const entry of entries) {+ const { node, mapping } = sanitizeSubschema(entry, policy, depth);+ nodes.push(node);+ mappings.push(mapping);+ if (mapping) anyRenamed = true;+ }+ return { nodes, mappings: anyRenamed ? mappings : undefined };+}++/**+ * Rewrites the nested keys of a `{ name -> sub-schema }` map (e.g. `$defs`,+ * `patternProperties`). The map's own keys are names/patterns, not value+ * property keys, so they are left untouched and no restoration mapping is kept.+ */+function sanitizeSchemaMap(+ map: Record<string, unknown>,+ policy: KeySanitizationPolicy,+ depth: number+): Record<string, unknown> {+ const out: Record<string, unknown> = Object.create(null);+ for (const [key, value] of Object.entries(map)) {+ out[key] = sanitizeSubschema(value, policy, depth).node;+ }+ return out;+}++/**+ * Merges `source`'s renames into `target`, both describing the same value level+ * (used to fold composition branches into their parent). `target` wins on+ * conflict, since it is the more direct (`properties`-level) mapping.+ *+ * Known limitation: folding sibling `allOf`/`anyOf`/`oneOf` branches into one+ * value level is lossy when two branches disagree on an alias. If branch A aliases+ * an illegal key to `X` while branch B has a distinct illegal key that also aliases+ * to `X` — or a *legitimate* property literally named `X` — only the first-seen+ * entry survives, so an argument that satisfied the other branch restores to the+ * wrong original name. Which branch a runtime value matched can't be recovered from+ * the value alone (that needs full schema evaluation against the value), so these+ * cross-branch collisions stay effectively rewrite-only — still strictly better+ * than the whole `tools` array being rejected. They are rare in practice.+ */+function mergeMappingInto(target: KeyMapping, source: KeyMapping): void {+ for (const [alias, original] of Object.entries(source.renames)) {+ if (!(alias in target.renames)) {+ target.renames[alias] = original;+ }+ }+ for (const [key, childSource] of Object.entries(source.children)) {+ const existing = target.children[key];+ if (existing) {+ mergeMappingInto(existing, childSource);+ } else {+ target.children[key] = childSource;+ }+ }+ if (target.items === undefined && source.items !== undefined) {+ target.items = source.items;+ if (source.restItems !== undefined) {+ target.restItems = source.restItems;+ }+ }+}++/**+ * Recursively sanitizes the property keys of a JSON-schema node, returning the+ * rewritten node and a {@link KeyMapping} shaped like the node. Traversal covers+ * object `properties`, array `items`/`prefixItems`, the composition keywords+ * (`allOf`/`anyOf`/`oneOf`, `not`/`if`/`then`/`else` — whose renames merge into+ * this level), and the rewrite-only positions in {@link REWRITE_ONLY_SINGLE_KEYWORDS}+ * / {@link REWRITE_ONLY_MAP_KEYWORDS}.+ *+ * The input node is never mutated; a new node is returned.+ */+function sanitizeNode(+ node: Record<string, unknown>,+ policy: KeySanitizationPolicy,+ depth = 0+): {+ node: Record<string, unknown>;+ mapping: KeyMapping;+} {+ if (depth >= MAX_SCHEMA_DEPTH) {+ throw new Error(+ `Tool schema nesting exceeded the maximum supported depth (${MAX_SCHEMA_DEPTH})`+ );+ }++ const result: Record<string, unknown> = { ...node };+ // Lookup/result tables are prototype-free so a property key that collides with+ // an `Object.prototype` member (`__proto__`, `constructor`, `toString`, …)+ // becomes a plain own entry instead of resolving to (or reparenting via) the+ // inherited member. Mirrors the `POLLUTING_KEYS` defense in `jsonSchema.ts`.+ const renames: Record<string, string> = Object.create(null);+ const children: Record<string, KeyMapping> = Object.create(null);+ const mapping: KeyMapping = { renames, children };++ const properties = node.properties;+ if (isPlainObject(properties)) {+ const newProperties: Record<string, unknown> = Object.create(null);+ const renamedOriginalToSanitized: Record<string, string> = Object.create(null);++ // Reserve all already-valid keys up front so they keep their exact names and+ // sanitized aliases are generated around them (a valid `dollar_top` must not+ // be clobbered by a sanitized `$top`).+ const taken = new Set<string>();+ for (const key of Object.keys(properties)) {+ if (policy.isValidKey(key)) {+ taken.add(key);+ }+ }++ for (const [key, rawValue] of Object.entries(properties)) {+ const safeKey = policy.isValidKey(key) ? key : policy.aliasKey(key, taken);+ taken.add(safeKey);++ const { node: childNode, mapping: childMapping } = sanitizeSubschema(rawValue, policy, depth);+ newProperties[safeKey] = childNode;+ if (childMapping) {+ children[safeKey] = childMapping;+ }++ if (safeKey !== key) {+ renames[safeKey] = key;+ renamedOriginalToSanitized[key] = safeKey;+ }+ }++ result.properties = newProperties;++ // Keep `required` in sync with the renamed keys at this level.+ if (Array.isArray(node.required)) {+ result.required = node.required.map(name =>+ typeof name === 'string' && renamedOriginalToSanitized[name]+ ? renamedOriginalToSanitized[name]+ : name+ );+ }+ }++ // Array element schemas come from up to two positional sources — a Draft-7+ // `items` tuple and the 2020-12 `prefixItems` tuple — plus one "applies to every+ // element" source, a single `items` schema. When `prefixItems` provides the+ // positional mapping, a sibling single `items` schema constrains the elements+ // *past* the tuple (2020-12 semantics); its renames are kept separately as+ // `restItems` so those tail elements restore too instead of being dropped (or+ // the rest mapping bleeding onto the tuple positions). Restoration reaches array+ // elements through `mapping.items`/`mapping.restItems` — a `properties`-only walk+ // would let illegal keys nested in elements through and still be rejected.+ const itemsSchema = node.items;+ let positionalItems: (KeyMapping | null)[] | undefined;+ let uniformItems: KeyMapping | undefined;+ if (isPlainObject(itemsSchema)) {+ const { node: childNode, mapping: childMapping } = sanitizeSubschema(+ itemsSchema,+ policy,+ depth+ );+ result.items = childNode;+ if (childMapping) {+ uniformItems = childMapping;+ }+ } else if (Array.isArray(itemsSchema)) {+ const { nodes, mappings } = sanitizeTuple(itemsSchema, policy, depth);+ result.items = nodes;+ positionalItems = mappings;+ }+ if (Array.isArray(node.prefixItems)) {+ const { nodes, mappings } = sanitizeTuple(node.prefixItems, policy, depth);+ result.prefixItems = nodes;+ // `prefixItems` is the 2020-12 positional keyword; use it for the positional+ // mapping when a Draft-7 `items` tuple didn't already provide one.+ if (positionalItems === undefined) {+ positionalItems = mappings;+ }+ }+ if (positionalItems) {+ mapping.items = positionalItems;+ // A single `items` schema sitting next to a `prefixItems` tuple describes the+ // elements after the tuple; keep its mapping so they restore positionally.+ if (uniformItems && Array.isArray(node.prefixItems)) {+ mapping.restItems = uniformItems;+ }+ } else if (uniformItems) {+ mapping.items = uniformItems;+ }++ // Composition keywords constrain the *same* value, so renames generated inside+ // them are merged into this level (the value has no extra nesting for them).+ for (const keyword of COMPOSITION_SINGLE_KEYWORDS) {+ const sub = node[keyword];+ if (isPlainObject(sub)) {+ const { node: childNode, mapping: childMapping } = sanitizeSubschema(sub, policy, depth);+ result[keyword] = childNode;+ if (childMapping) {+ mergeMappingInto(mapping, childMapping);+ }+ }+ }+ for (const keyword of COMPOSITION_LIST_KEYWORDS) {+ const list = node[keyword];+ if (Array.isArray(list)) {+ result[keyword] = list.map(entry => {+ const { node: childNode, mapping: childMapping } = sanitizeSubschema(entry, policy, depth);+ if (childMapping) {+ mergeMappingInto(mapping, childMapping);+ }+ return childNode;+ });+ }+ }++ // Rewrite-only positions: keys are made compliant, but no restoration mapping+ // is kept (see the keyword lists above for why).+ for (const keyword of REWRITE_ONLY_SINGLE_KEYWORDS) {+ const sub = node[keyword];+ if (isPlainObject(sub)) {+ result[keyword] = sanitizeSubschema(sub, policy, depth).node;+ }+ }+ for (const keyword of REWRITE_ONLY_MAP_KEYWORDS) {+ const sub = node[keyword];+ if (isPlainObject(sub)) {+ result[keyword] = sanitizeSchemaMap(sub, policy, depth);+ }+ }++ return { node: result, mapping };+}++/**+ * Sanitizes a tool `input_schema` so all property keys conform to `policy`.+ *+ * @param schema - The tool input schema to sanitize.+ * @param policy - Provider constraint describing valid keys and how to rewrite+ * illegal ones.+ * @returns The sanitized schema (a copy) and a {@link KeyMapping} for restoring+ * the original keys. Use {@link mappingHasRenames} to tell whether+ * anything was rewritten.+ */+export function sanitizeSchemaPropertyKeys<T extends Record<string, unknown>>(+ schema: T,+ policy: KeySanitizationPolicy+): { schema: T; mapping: KeyMapping } {+ const { node, mapping } = sanitizeNode(schema, policy);+ return { schema: node as T, mapping };+}++/**+ * Restores original property names in a tool-call argument object using the+ * mapping produced by {@link sanitizeSchemaPropertyKeys}. The mapping is walked+ * in lockstep with the value, so a key is only renamed at the nesting level where+ * its alias was actually generated. Nested objects and arrays are handled+ * recursively. Returns a new value; the input is not mutated.+ */+export function restoreOriginalKeys(value: unknown, mapping: KeyMapping, depth = 0): unknown {+ if (depth >= MAX_SCHEMA_DEPTH) {+ throw new Error(+ `Tool arguments nesting exceeded the maximum supported depth (${MAX_SCHEMA_DEPTH})`+ );+ }++ if (Array.isArray(value)) {+ const { items, restItems } = mapping;+ if (Array.isArray(items)) {+ return value.map((item, index) => {+ // Elements inside the tuple use their positional mapping; elements past it+ // use the trailing single-`items` rest mapping (2020-12), if any.+ const itemMapping = index < items.length ? items[index] : restItems;+ return itemMapping ? restoreOriginalKeys(item, itemMapping, depth + 1) : item;+ });+ }+ if (items) {+ return value.map(item => restoreOriginalKeys(item, items, depth + 1));+ }+ return value;+ }++ if (isPlainObject(value)) {+ // Prototype-free so a model-supplied key equal to an `Object.prototype`+ // member name (`__proto__`, `constructor`, …) is written as a plain own+ // property rather than reparenting the result or hitting an inherited member.+ const restored: Record<string, unknown> = Object.create(null);+ for (const [key, val] of Object.entries(value)) {+ // `renames`/`children` are themselves prototype-free (see `sanitizeNode`),+ // so these lookups return `undefined` for non-own keys instead of an+ // inherited function — no spurious rename and no crash on recursion.+ const originalKey = mapping.renames[key] ?? key;+ const childMapping = mapping.children[key];+ restored[originalKey] = childMapping+ ? restoreOriginalKeys(val, childMapping, depth + 1)+ : val;+ }+ return restored;+ }++ return value;+}diff --git a/ts/packages/providers/anthropic/src/index.ts b/ts/packages/providers/anthropic/src/index.tsindex 82c0da293..30865a037 100644--- a/ts/packages/providers/anthropic/src/index.ts+++ b/ts/packages/providers/anthropic/src/index.ts@@ -16,6 +16,7 @@ import {logger,McpUrlResponse,normalizeToolArguments,+ dereferenceJsonSchema,} from '@composio/core';import Anthropic from '@anthropic-ai/sdk';import { AnthropicTool, InputSchema } from './types';@@ -67,11 +68,25 @@ export class AnthropicProvider extends BaseNonAgenticProvider<private chacheTools: boolean = false;/**- * Per-tool `sanitized -> original` property-key mappings, populated by- * {@link wrapTool} whenever a tool's schema contains keys that violate- * Anthropic's `^[a-zA-Z0-9_.-]{1,64}$` constraint. Used by- * {@link executeToolCall} to restore the original parameter names before the- * call reaches the Composio backend.+ * Per-tool reverse key mappings (`sanitized -> original`, shaped like the+ * schema), keyed by tool slug. Populated by {@link wrapTool} whenever a tool's+ * schema contains keys that violate Anthropic's `^[a-zA-Z0-9_.-]{1,64}$`+ * constraint, and read by {@link executeToolCall} to restore the original+ * parameter names before the call reaches the Composio backend.+ *+ * **Contract:** a tool must be wrapped and executed through the *same* provider+ * instance. This holds for the standard Composio flow — the model can only call+ * tools previously emitted by {@link wrapTools}/{@link wrapTool} on this+ * instance, and that wrapping registers the mapping. If a tool is somehow+ * executed on an instance that never wrapped it, no mapping is found and the+ * model's (already sanitized) argument keys are forwarded unchanged, so the+ * backend would see e.g. `dollar_top` instead of `$top`. {@link executeToolCall}+ * emits a `debug` log on the path that actually restores keys so this is+ * diagnosable.+ *+ * Re-wrapping a slug refreshes its entry (or clears it when the new schema+ * needs no rewriting), so the map stays consistent and its size is bounded by+ * the number of distinct sanitized tool slugs this instance has wrapped.*/private toolKeyMappings: Map<string, KeyMapping> = new Map();@@ -140,23 +155,40 @@ export class AnthropicProvider extends BaseNonAgenticProvider<required: [],}) as InputSchema;+ // Inline internal `$ref` / `$defs` first so keys reachable only through a+ // reference become ordinary value positions that can be both sanitized and+ // restored. Lenient mode keeps an upstream schema with a dangling ref usable+ // (it degrades the branch to a permissive object) instead of throwing.+ const dereferenced = dereferenceJsonSchema(rawSchema, {+ onUnresolved: 'sentinel',+ onReplace: ref =>+ logger.debug(+ `AnthropicProvider: unresolved $ref "${ref}" in tool "${tool.slug}" replaced ` ++ `with a permissive schema`+ ),+ });+// Anthropic rejects the whole `tools` array if any property key falls outside// `^[a-zA-Z0-9_.-]{1,64}$` (e.g. OData params like `$top`, `@odata.type`, or// over-long flattened keys). Rewrite offending keys and remember how to undo it.- const { schema, mapping } = sanitizeSchemaPropertyKeys(- rawSchema as unknown as Record<string, unknown>- );+ const { schema, mapping } = sanitizeSchemaPropertyKeys(dereferenced);if (mappingHasRenames(mapping)) {this.toolKeyMappings.set(tool.slug, mapping);+ logger.debug(+ `AnthropicProvider rewrote non-conforming schema keys for tool "${tool.slug}"; ` ++ `original parameter names will be restored at execution time`+ );} else {+ // Clear any stale mapping from a previous wrap of the same slug whose+ // schema no longer needs rewriting, so restoration stays consistent.this.toolKeyMappings.delete(tool.slug);}return {name: tool.slug,description: tool.description || '',- input_schema: schema as unknown as InputSchema,+ input_schema: schema,cache_control: this.chacheTools ? { type: 'ephemeral' } : undefined,};}@@ -247,11 +279,15 @@ export class AnthropicProvider extends BaseNonAgenticProvider<const normalizedInput = normalizeToolArguments(toolUse.input, toolUse.name);// Undo any key sanitization applied in `wrapTool` so the backend receives the- // tool's original parameter names (e.g. `dollar_top` -> `$top`).+ // tool's original parameter names (e.g. `dollar_top` -> `$top`). The mapping+ // is only present when this same instance wrapped the tool and rewrote keys+ // (see `toolKeyMappings`); otherwise the arguments pass through untouched.const mapping = this.toolKeyMappings.get(toolUse.name);- const toolArguments = mapping- ? (restoreOriginalKeys(normalizedInput, mapping) as Record<string, unknown>)- : normalizedInput;+ let toolArguments = normalizedInput;+ if (mapping) {+ toolArguments = restoreOriginalKeys(normalizedInput, mapping) as Record<string, unknown>;+ logger.debug(`AnthropicProvider restored original argument keys for tool "${toolUse.name}"`);+ }const payload: ToolExecuteParams = {arguments: toolArguments,diff --git a/ts/packages/providers/anthropic/src/sanitize-keys.ts b/ts/packages/providers/anthropic/src/sanitize-keys.tsindex a3173095d..68eaceb3c 100644--- a/ts/packages/providers/anthropic/src/sanitize-keys.ts+++ b/ts/packages/providers/anthropic/src/sanitize-keys.ts@@ -1,30 +1,30 @@/**- * Anthropic tool-schema key sanitization.+ * Anthropic-bound tool-schema key sanitization.*- * Anthropic's Messages API validates every tool `input_schema` property key- * against the pattern `^[a-zA-Z0-9_.-]{1,64}$`. A single non-conforming key- * makes the API reject the entire `tools` array with HTTP 400, so one bad tool- * takes down every other tool in the same request.+ * The traversal/restoration mechanism lives in `@composio/core`+ * (`sanitizeSchemaPropertyKeys` / `restoreOriginalKeys`); this module supplies the+ * Anthropic key constraint as a {@link KeySanitizationPolicy} and re-exports a+ * policy-bound sanitizer plus the restore side, so call sites in this package+ * import everything from one place.*- * Composio tools can surface keys that break this pattern in two ways:- * - **Illegal characters** — e.g. the OneDrive toolkit exposes Microsoft Graph- * OData parameters such as `$top`, `$filter` or `@microsoft.graph.conflictBehavior`- * whose `$` and `@` are outside the allowed set.- * - **Length** — flattening nested objects with `__` separators can produce keys- * longer than 64 characters (e.g. several Zoom tools).+ * Anthropic's Messages API validates every property key against+ * `^[a-zA-Z0-9_.-]{1,64}$` and rejects the entire `tools` array on a single+ * violation. Composio tools can surface keys that break this — OData parameters+ * like `$top` / `@microsoft.graph.conflictBehavior` (illegal `$`/`@`), or+ * over-long `__`-flattened keys.*- * This module rewrites offending keys to conforming aliases before the schema is- * sent to Anthropic, and records a reverse mapping so the original parameter names- * can be restored before a tool call is executed against the Composio backend.- *- * The reverse mapping mirrors the schema's nesting (object `properties` and array- * `items`) rather than being a single flat lookup. This matters because an alias- * generated at one nesting level (e.g. `$top` -> `dollar_top`) must not rewrite a- * legitimately-named `dollar_top` key that happens to exist at a different level.- *- * @packageDocumentation* @module providers/anthropic/sanitize-keys*/+import {+ sanitizeSchemaPropertyKeys as sanitizeWithPolicy,+ restoreOriginalKeys,+ mappingHasRenames,+ type KeyMapping,+ type KeySanitizationPolicy,+} from '@composio/core';++export { restoreOriginalKeys, mappingHasRenames };+export type { KeyMapping };/** Anthropic's allowed property-key pattern. */const VALID_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;@@ -33,45 +33,16 @@ const VALID_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;const MAX_KEY_LENGTH = 64;/**- * Readable replacements for the most common illegal characters so aliases stay- * recognizable (e.g. `$top` -> `dollar_top`, `@odata.type` -> `at_odata.type`).- * Any other illegal character falls back to `_`. Mirrors the Python SDK's- * sanitization for cross-language consistency.+ * Readable replacements for the two most common illegal characters — the OData+ * prefixes Composio surfaces — so aliases stay recognizable on the wire (e.g.+ * `$top` -> `dollar_top`, `@odata.type` -> `at_odata.type`). Any other illegal+ * character falls back to `_` (see {@link sanitizeKey}).*/const ILLEGAL_CHAR_MAP: Record<string, string> = {$: 'dollar_','@': 'at_',};-/**- * Reverse mapping used to restore original property names at execution time.- *- * It is shaped like the schema it was derived from so restoration is scoped to- * the exact location a rename happened:- * - `renames` — `sanitized -> original` for keys renamed at *this* object level.- * - `children` — restoration mapping for the value under each (sanitized) key,- * keyed by the sanitized key. Only present for children that contain renames.- * - `items` — restoration mapping for array element values. A single mapping- * applies to every element; an array of mappings applies positionally (JSON- * Schema tuple validation). Only present when array elements contain renames.- */-export interface KeyMapping {- renames: Record<string, string>;- children: Record<string, KeyMapping>;- items?: KeyMapping | (KeyMapping | null)[];-}--/** Whether a mapping (or any of its descendants) actually renames a key. */-export function mappingHasRenames(mapping: KeyMapping): boolean {- // `children` and `items` are only populated when they carry renames (see- // `sanitizeNode`), so this stays a shallow check.- return (- Object.keys(mapping.renames).length > 0 ||- Object.keys(mapping.children).length > 0 ||- mapping.items != null- );-}-/*** Deterministic, dependency-free hash (djb2) rendered as a short base-36 string.* Used as a uniqueness suffix when truncating long keys or resolving collisions.@@ -85,15 +56,11 @@ function shortHash(input: string): string {return (hash >>> 0).toString(36).slice(0, 7);}-/** Whether a key is already valid for Anthropic and needs no rewriting. */-function isValidKey(name: string): boolean {- return VALID_KEY_RE.test(name);-}-/*** Rewrites a single key so it matches Anthropic's pattern. Replaces known illegal- * characters with readable aliases, any remaining illegal character with `_`, and- * truncates keys over 64 characters with a deterministic hash suffix.+ * characters with readable aliases, any remaining illegal character with `_`,+ * substitutes a non-empty fallback for an otherwise-empty result, and truncates+ * keys over 64 characters with a deterministic hash suffix.*/function sanitizeKey(name: string): string {let sanitized = name;@@ -102,6 +69,13 @@ function sanitizeKey(name: string): string {}sanitized = sanitized.replace(/[^a-zA-Z0-9_.-]/g, '_');+ // Anthropic's pattern requires at least one character; an empty original (or+ // one made entirely of stripped characters) would otherwise emit `''`, which+ // still fails validation. Fall back to a deterministic non-empty alias.+ if (sanitized.length === 0) {+ sanitized = `key_${shortHash(name)}`;+ }+if (sanitized.length > MAX_KEY_LENGTH) {const suffix = `_${shortHash(name)}`;sanitized = sanitized.slice(0, MAX_KEY_LENGTH - suffix.length) + suffix;@@ -110,177 +84,41 @@ function sanitizeKey(name: string): string {return sanitized;}-/** Returns a sanitized key guaranteed to be unique within `taken`. */-function uniqueSanitizedKey(name: string, taken: Set<string>): string {- let candidate = sanitizeKey(name);- if (!taken.has(candidate)) {- return candidate;- }- // Collision (different originals mapping to the same alias) — append a hash.- const suffix = `_${shortHash(name)}`;- const base = candidate.slice(0, MAX_KEY_LENGTH - suffix.length);- candidate = base + suffix;- while (taken.has(candidate)) {- candidate = `${candidate.slice(0, MAX_KEY_LENGTH - 1)}_`;- }- return candidate;-}+/** The Anthropic key-sanitization policy consumed by core's sanitizer. */+const anthropicKeyPolicy: KeySanitizationPolicy = {+ isValidKey(name) {+ return VALID_KEY_RE.test(name);+ },-function isPlainObject(value: unknown): value is Record<string, unknown> {- return typeof value === 'object' && value !== null && !Array.isArray(value);-}--/**- * Recursively sanitizes the property keys of a JSON-schema node, returning the- * rewritten node and a {@link KeyMapping} shaped like the node. Both object- * `properties` and array `items` schemas are traversed, matching how Composio- * nests its tool parameters.- *- * The input node is never mutated; a new node is returned.- */-function sanitizeNode(node: Record<string, unknown>): {- node: Record<string, unknown>;- mapping: KeyMapping;-} {- const result: Record<string, unknown> = { ...node };- const renames: Record<string, string> = {};- const children: Record<string, KeyMapping> = {};- let items: KeyMapping | (KeyMapping | null)[] | undefined;-- const properties = node.properties;- if (isPlainObject(properties)) {- const newProperties: Record<string, unknown> = {};- const renamedOriginalToSanitized: Record<string, string> = {};-- // Reserve all already-valid keys up front so they keep their exact names and- // sanitized aliases are generated around them (a valid `dollar_top` must not- // be clobbered by a sanitized `$top`).- const taken = new Set<string>();- for (const key of Object.keys(properties)) {- if (isValidKey(key)) {- taken.add(key);- }+ aliasKey(name, taken) {+ const candidate = sanitizeKey(name);+ if (!taken.has(candidate)) {+ return candidate;}-- for (const [key, rawValue] of Object.entries(properties)) {- const safeKey = isValidKey(key) ? key : uniqueSanitizedKey(key, taken);- taken.add(safeKey);-- const child = isPlainObject(rawValue) ? sanitizeNode(rawValue) : null;- newProperties[safeKey] = child ? child.node : rawValue;- if (child && mappingHasRenames(child.mapping)) {- children[safeKey] = child.mapping;- }-- if (safeKey !== key) {- renames[safeKey] = key;- renamedOriginalToSanitized[key] = safeKey;- }- }-- result.properties = newProperties;-- // Keep `required` in sync with the renamed keys at this level.- if (Array.isArray(node.required)) {- result.required = node.required.map(name =>- typeof name === 'string' && renamedOriginalToSanitized[name]- ? renamedOriginalToSanitized[name]- : name- );- }- }-- // Recurse into array element schemas so illegal keys nested inside array items- // (e.g. `{ type: 'array', items: { properties: { $top: ... } } }`) are sanitized- // too — `properties`-only traversal would let them through and still 400.- const itemsSchema = node.items;- if (isPlainObject(itemsSchema)) {- const child = sanitizeNode(itemsSchema);- result.items = child.node;- if (mappingHasRenames(child.mapping)) {- items = child.mapping;- }- } else if (Array.isArray(itemsSchema)) {- // Tuple validation: one positional schema per array index.- const sanitizedItems: unknown[] = [];- const itemMappings: (KeyMapping | null)[] = [];- let anyRenamed = false;- for (const entry of itemsSchema) {- if (isPlainObject(entry)) {- const child = sanitizeNode(entry);- sanitizedItems.push(child.node);- if (mappingHasRenames(child.mapping)) {- itemMappings.push(child.mapping);- anyRenamed = true;- } else {- itemMappings.push(null);- }- } else {- sanitizedItems.push(entry);- itemMappings.push(null);- }- }- result.items = sanitizedItems;- if (anyRenamed) {- items = itemMappings;+ // Collision (different originals mapping to the same alias) — append a hash,+ // then an incrementing counter if that still collides. The counter changes+ // every iteration, so this always makes progress and can't spin.+ const suffix = `_${shortHash(name)}`;+ const base = candidate.slice(0, MAX_KEY_LENGTH - suffix.length);+ let resolved = base + suffix;+ for (let counter = 1; taken.has(resolved); counter++) {+ const tail = `${suffix}_${counter}`;+ resolved = base.slice(0, MAX_KEY_LENGTH - tail.length) + tail;}- }-- const mapping: KeyMapping = { renames, children };- if (items !== undefined) {- mapping.items = items;- }-- return { node: result, mapping };-}+ return resolved;+ },+};/**- * Sanitizes a tool `input_schema` so all property keys conform to Anthropic's- * pattern.+ * Sanitizes a tool `input_schema` so every property key satisfies Anthropic's+ * `^[a-zA-Z0-9_.-]{1,64}$` constraint, returning the rewritten schema and a+ * {@link KeyMapping} for restoring the original keys at execution time.*- * @param schema - The tool input schema to sanitize.- * @returns The sanitized schema (a copy) and a {@link KeyMapping} for restoring- * the original keys. Use {@link mappingHasRenames} to tell whether- * anything was rewritten.+ * `inputParameters` should be dereferenced first (see `wrapTool`) so keys that+ * are reachable only through a `$ref` are sanitized and restored as well.*/export function sanitizeSchemaPropertyKeys<T extends Record<string, unknown>>(schema: T): { schema: T; mapping: KeyMapping } {- const { node, mapping } = sanitizeNode(schema);- return { schema: node as T, mapping };-}--/**- * Restores original property names in a tool-call argument object using the- * mapping produced by {@link sanitizeSchemaPropertyKeys}. The mapping is walked- * in lockstep with the value, so a key is only renamed at the nesting level where- * its alias was actually generated. Nested objects and arrays are handled- * recursively. Returns a new value; the input is not mutated.- */-export function restoreOriginalKeys(value: unknown, mapping: KeyMapping): unknown {- if (Array.isArray(value)) {- const { items } = mapping;- if (Array.isArray(items)) {- return value.map((item, index) => {- const itemMapping = items[index];- return itemMapping ? restoreOriginalKeys(item, itemMapping) : item;- });- }- if (items) {- return value.map(item => restoreOriginalKeys(item, items));- }- return value;- }-- if (isPlainObject(value)) {- const restored: Record<string, unknown> = {};- for (const [key, val] of Object.entries(value)) {- const originalKey = mapping.renames[key] ?? key;- const childMapping = mapping.children[key];- restored[originalKey] = childMapping ? restoreOriginalKeys(val, childMapping) : val;- }- return restored;- }-- return value;+ return sanitizeWithPolicy(schema, anthropicKeyPolicy);}diff --git a/ts/packages/providers/anthropic/test/sanitize-keys.test.ts b/ts/packages/providers/anthropic/test/sanitize-keys.test.tsindex 34e8427b8..e7553e1c1 100644--- a/ts/packages/providers/anthropic/test/sanitize-keys.test.ts+++ b/ts/packages/providers/anthropic/test/sanitize-keys.test.ts@@ -196,6 +196,215 @@ describe('sanitizeSchemaPropertyKeys', () => {const restored = restoreOriginalKeys({ pair: [{ dollar_top: 9 }, { plain: 'x' }] }, mapping);expect(restored).toEqual({ pair: [{ $top: 9 }, { plain: 'x' }] });});++ // A key that is empty (or made entirely of stripped characters) would emit+ // `''`, which still violates Anthropic's `{1,64}` length bound.+ it('emits a non-empty conforming alias for empty / all-illegal keys', () => {+ const schema = {+ type: 'object',+ properties: { '': { type: 'string' }, '@@@': { type: 'integer' } },+ };++ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);+ const keys = Object.keys(out.properties as Record<string, unknown>);++ expect(keys).toHaveLength(2);+ keys.forEach(k => expect(k).toMatch(ANTHROPIC_KEY_RE)); // each ≥ 1 char and conforming+ expect(new Set(Object.values(mapping.renames))).toEqual(new Set(['', '@@@']));+ });++ // Pathologically deep schemas must fail loudly rather than overflow the stack.+ it('throws instead of overflowing the stack on deeply nested schemas', () => {+ let deep: Record<string, unknown> = {+ type: 'object',+ properties: { $x: { type: 'integer' } },+ };+ for (let i = 0; i < 2000; i++) {+ deep = { type: 'object', properties: { nested: deep } };+ }++ expect(() => sanitizeSchemaPropertyKeys(deep)).toThrow(/depth/i);+ });++ // Property keys that collide with `Object.prototype` member names must be+ // treated as ordinary keys, never reparent the emitted schema, and never+ // mutate `Object.prototype`. Built via JSON.parse so `__proto__` is a real+ // own key rather than prototype-setting literal syntax.+ it('treats prototype-member property names as ordinary keys', () => {+ const schema = JSON.parse(+ '{"type":"object","properties":{"$top":{"type":"integer"},"__proto__":{"type":"string"},"constructor":{"type":"string"}}}'+ );++ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);+ const props = out.properties as Record<string, unknown>;++ expect(Object.prototype.hasOwnProperty.call(props, '__proto__')).toBe(true);+ expect(Object.prototype.hasOwnProperty.call(props, 'constructor')).toBe(true);+ expect(props['constructor']).toEqual({ type: 'string' });+ expect(({} as Record<string, unknown>).type).toBeUndefined(); // prototype untouched++ const restored = restoreOriginalKeys({ dollar_top: 1, constructor: 'c' }, mapping) as Record<+ string,+ unknown+ >;+ expect(restored['$top']).toBe(1);+ expect(restored['constructor']).toBe('c');+ });+});++describe('sanitizeSchemaPropertyKeys composition coverage', () => {+ // Asserts every emitted `properties` key (at any depth) conforms to Anthropic's+ // pattern — i.e. nothing illegal slipped through the traversal and could 400.+ const expectNoIllegalPropertyKeys = (schema: unknown) => {+ const walk = (node: unknown): void => {+ if (Array.isArray(node)) return node.forEach(walk);+ if (!node || typeof node !== 'object') return;+ const obj = node as Record<string, unknown>;+ if (obj.properties && typeof obj.properties === 'object') {+ for (const key of Object.keys(obj.properties as Record<string, unknown>)) {+ expect(key).toMatch(ANTHROPIC_KEY_RE);+ }+ }+ Object.values(obj).forEach(walk);+ };+ walk(schema);+ };++ it('sanitizes and restores illegal keys nested under `anyOf` branches', () => {+ const schema = {+ type: 'object',+ properties: {+ foo: {+ anyOf: [+ { type: 'object', properties: { $top: { type: 'integer' } }, required: ['$top'] },+ { type: 'object', properties: { bar: { type: 'string' } } },+ ],+ },+ },+ };++ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);+ expectNoIllegalPropertyKeys(out);+ expect((out.properties as any).foo.anyOf[0].properties).toHaveProperty('dollar_top');++ // The branch rename folds into `foo`'s value level, so restoration finds it.+ expect(restoreOriginalKeys({ foo: { dollar_top: 5 } }, mapping)).toEqual({ foo: { $top: 5 } });+ });++ it('merges `oneOf` / `allOf` renames into the shared value level', () => {+ const oneOf = sanitizeSchemaPropertyKeys({+ type: 'object',+ oneOf: [{ properties: { $top: { type: 'integer' } } }, { properties: { plain: {} } }],+ });+ expectNoIllegalPropertyKeys(oneOf.schema);+ expect(restoreOriginalKeys({ dollar_top: 1 }, oneOf.mapping)).toEqual({ $top: 1 });++ const allOf = sanitizeSchemaPropertyKeys({+ type: 'object',+ properties: { keep: { type: 'string' } },+ allOf: [{ properties: { '@odata.type': { type: 'string' } } }],+ });+ expectNoIllegalPropertyKeys(allOf.schema);+ expect(restoreOriginalKeys({ 'at_odata.type': 'x', keep: 'y' }, allOf.mapping)).toEqual({+ '@odata.type': 'x',+ keep: 'y',+ });+ });++ it('selects the right branch mapping by value type for a mixed `anyOf`', () => {+ const { mapping } = sanitizeSchemaPropertyKeys({+ type: 'object',+ properties: {+ field: {+ anyOf: [+ { type: 'array', items: { type: 'object', properties: { $top: { type: 'integer' } } } },+ { type: 'object', properties: { $skip: { type: 'integer' } } },+ ],+ },+ },+ });++ // Array value → array-branch (`items`) mapping; object value → object branch.+ expect(restoreOriginalKeys({ field: [{ dollar_top: 1 }] }, mapping)).toEqual({+ field: [{ $top: 1 }],+ });+ expect(restoreOriginalKeys({ field: { dollar_skip: 2 } }, mapping)).toEqual({+ field: { $skip: 2 },+ });+ });++ it('sanitizes (but does not restore) keys nested under `additionalProperties`', () => {+ const schema = {+ type: 'object',+ properties: {},+ additionalProperties: { type: 'object', properties: { $top: { type: 'integer' } } },+ };++ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);+ // 400-prevention: the alias is emitted so Anthropic accepts the schema.+ expect((out as any).additionalProperties.properties).toHaveProperty('dollar_top');+ // Documented limitation: dynamic-key values are not restored — the alias+ // reaches the backend rather than being silently (mis)mapped at every level.+ expect(restoreOriginalKeys({ anyKey: { dollar_top: 1 } }, mapping)).toEqual({+ anyKey: { dollar_top: 1 },+ });+ });++ it('sanitizes keys nested under `$defs` for Anthropic acceptance', () => {+ const { schema: out } = sanitizeSchemaPropertyKeys({+ type: 'object',+ properties: { x: { $ref: '#/$defs/Foo' } },+ $defs: { Foo: { type: 'object', properties: { $top: { type: 'integer' } } } },+ });++ expectNoIllegalPropertyKeys(out);+ expect((out as any).$defs.Foo.properties).toHaveProperty('dollar_top');+ });++ it('sanitizes and restores `prefixItems` tuples', () => {+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys({+ type: 'object',+ properties: {+ pair: {+ type: 'array',+ prefixItems: [+ { type: 'object', properties: { $top: { type: 'integer' } } },+ { type: 'object', properties: { plain: { type: 'string' } } },+ ],+ },+ },+ });++ expectNoIllegalPropertyKeys(out);+ expect(restoreOriginalKeys({ pair: [{ dollar_top: 9 }, { plain: 'x' }] }, mapping)).toEqual({+ pair: [{ $top: 9 }, { plain: 'x' }],+ });+ });++ it('restores a `prefixItems` tuple and a trailing `items` rest schema independently', () => {+ // 2020-12: `prefixItems` pins positions 0..n-1; a sibling single `items` schema+ // applies to every element past the tuple. Both carry illegal keys that must+ // round-trip at their own positions — the prefix rename must not be dropped,+ // and the rest mapping must not bleed onto the prefix position.+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys({+ type: 'object',+ properties: {+ tuple: {+ type: 'array',+ prefixItems: [{ type: 'object', properties: { $top: { type: 'integer' } } }],+ items: { type: 'object', properties: { '@odata.type': { type: 'string' } } },+ },+ },+ });++ expectNoIllegalPropertyKeys(out);+ expect(+ restoreOriginalKeys(+ { tuple: [{ dollar_top: 5 }, { 'at_odata.type': 'a' }, { 'at_odata.type': 'b' }] },+ mapping+ )+ ).toEqual({ tuple: [{ $top: 5 }, { '@odata.type': 'a' }, { '@odata.type': 'b' }] });+ });});describe('restoreOriginalKeys', () => {@@ -253,6 +462,34 @@ describe('restoreOriginalKeys', () => {filters: { dollar_top: 'keep-me' }, // nested genuine key left alone});});++ // Security: a model can emit argument keys equal to Object.prototype member+ // names (and `__proto__` reaches restoration via the JSON-string input path).+ // Restoration must not crash, must not corrupt the payload, and must never+ // mutate Object.prototype — the reverse maps and result object are all+ // prototype-free.+ it('handles prototype-member keys in tool arguments without crashing or polluting', () => {+ const { mapping } = sanitizeSchemaPropertyKeys({+ type: 'object',+ properties: { $top: { type: 'integer' }, name: { type: 'string' } },+ required: ['$top'],+ });++ const input = JSON.parse(+ '{"dollar_top":1,"constructor":{"inner":2},"toString":"t","__proto__":{"polluted":true},"hasOwnProperty":"h","name":"n"}'+ );++ // Threw with `TypeError` before this PR's hardening (lookups resolved to the+ // inherited `Object` function); a plain assignment here would also fail.+ const restored = restoreOriginalKeys(input, mapping) as Record<string, unknown>;++ expect(restored['$top']).toBe(1);+ expect(restored['name']).toBe('n');+ expect(restored['toString']).toBe('t');+ expect(restored['hasOwnProperty']).toBe('h');+ expect((restored['constructor'] as Record<string, unknown>).inner).toBe(2);+ expect(({} as Record<string, unknown>).polluted).toBeUndefined(); // prototype untouched+ });});describe('AnthropicProvider key sanitization', () => {@@ -381,4 +618,75 @@ describe('AnthropicProvider key sanitization', () => {const [, payload] = executeToolFn.mock.calls[0];expect(payload.arguments).toEqual({ query: 'hello' });});++ // Re-wrapping the same slug with a schema that no longer needs rewriting must+ // clear the stale mapping, so a later execution does not restore keys that the+ // current schema never sanitized.+ it('clears a stale key mapping when a slug is re-wrapped with a clean schema', async () => {+ const provider = new AnthropicProvider();+ const executeToolFn = vi+ .fn()+ .mockResolvedValue({ data: { ok: true }, error: null, successful: true });+ provider._setExecuteToolFn(executeToolFn);++ // First wrap registers a `dollar_top -> $top` mapping for this slug.+ provider.wrapTool(odataTool);++ // Re-wrap the SAME slug with a schema that has no illegal keys.+ const cleanedTool: Tool = {+ ...odataTool,+ inputParameters: { type: 'object', properties: { dollar_top: { type: 'integer' } } },+ } as unknown as Tool;+ provider.wrapTool(cleanedTool);++ // The model now legitimately sends `dollar_top`; it must reach the backend+ // unchanged rather than being restored to `$top` by the stale mapping.+ await provider.executeToolCall('user-1', {+ type: 'tool_use',+ id: 'tu_5',+ name: odataTool.slug,+ input: { dollar_top: 7 },+ });++ const [, payload] = executeToolFn.mock.calls[0];+ expect(payload.arguments).toEqual({ dollar_top: 7 });+ });++ // `wrapTool` dereferences `$ref`/`$defs` before sanitizing, so an illegal key+ // reachable only through a reference is both made compliant for Anthropic and+ // restored to its original name at execution time.+ it('dereferences $ref so $ref-nested illegal keys round-trip', async () => {+ const provider = new AnthropicProvider();+ const executeToolFn = vi+ .fn()+ .mockResolvedValue({ data: { ok: true }, error: null, successful: true });+ provider._setExecuteToolFn(executeToolFn);++ const refTool: Tool = {+ slug: 'ref-tool',+ name: 'Ref',+ description: 'uses $ref into $defs',+ inputParameters: {+ type: 'object',+ properties: { filter: { $ref: '#/$defs/Filter' } },+ $defs: { Filter: { type: 'object', properties: { $top: { type: 'integer' } } } },+ },+ tags: [],+ } as unknown as Tool;++ const wrapped = provider.wrapTool(refTool) as AnthropicTool;+ // The $ref is inlined, `$defs` removed, and the nested `$top` sanitized.+ expect((wrapped.input_schema.properties as any).filter.properties).toHaveProperty('dollar_top');+ expect((wrapped.input_schema as any).$defs).toBeUndefined();++ await provider.executeToolCall('user-1', {+ type: 'tool_use',+ id: 'tu_ref',+ name: 'ref-tool',+ input: { filter: { dollar_top: 3 } },+ });++ const [, payload] = executeToolFn.mock.calls[0];+ expect(payload.arguments).toEqual({ filter: { $top: 3 } });+ });});