@devries-cameron20 / composio-1 / commits / c90ae95f4
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): sanitize illegal/over-long tool property keys for Messages API (#3649)

## Problem Anthropic's Messages API validates every tool `input_schema` property key against `^[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 (e.g. a subagent that loads all MCP schemas up front dies before running anything). The `@composio/anthropic` provider passed `tool.inputParameters` straight through as `input_schema` with no key sanitization, so two real cases break: - **Illegal characters** — OneDrive exposes Microsoft Graph OData parameters as schema keys: `$top` / `$filter` / `$skip` / `$orderby` and `@microsoft.graph.conflictBehavior`. `$` and `@` are outside the allowed set. - **Length** — `__`-flattened nested keys can exceed 64 characters (several Zoom tools). Fixes #3500. TypeScript-side counterpart to the Python fix in #3504; supersedes the earlier #3067 / #2330 attempts. ## What this changes - New `sanitize-keys.ts`: `sanitizeSchemaPropertyKeys()` rewrites offending keys to conforming aliases (`$` → `dollar_`, `@` → `at_`, any other illegal char → `_`, keys > 64 chars truncated with a deterministic hash suffix), recursing through nested object `properties` **and array `items`** schemas, keeps `required` in sync, and never mutates the input. `restoreOriginalKeys()` reverses the rename on tool-call arguments. - `AnthropicProvider.wrapTool()` sanitizes the schema and stores a per-tool reverse mapping; `executeToolCall()` restores the original parameter names before the call reaches the Composio backend, so the model sees `dollar_top` while the backend still receives `$top`. ## Supersedes #3574 This rebuilds @serhiizghama's #3574 — his three commits are cherry-picked here with authorship preserved — rebased onto current `next` and hardened after review. Changes on top of #3574: 1. **Resolved the merge conflict with `next` (it was semantic, not just textual).** `next` now routes tool arguments through `normalizeToolArguments()` (issue #2406 — models sometimes emit input as a JSON *string*). `executeToolCall()` now **normalizes first, then restores keys**; restoring a raw string would be a no-op, so the order matters. 2. **Fixed the cross-level key-collision bug** flagged by Cursor Bugbot on #3574. The reverse mapping was a single flat `sanitized → original` lookup applied at every nesting depth, so an alias generated at one level (`$top` → `dollar_top`) could rewrite a legitimately-named `dollar_top` key at a *different* level and corrupt the backend payload. The mapping is now shaped like the schema and walked in lockstep with the value, so a rename only applies where its alias was generated. 3. **Sanitize keys nested in array `items`** (single schema and positional tuples), which the original `properties`-only walk missed. 4. **Added a changeset** (`@composio/anthropic` patch) so the fix actually ships. ## Testing Unit tests in `sanitize-keys.test.ts` cover: illegal-character rewriting, `.`/`-` preservation, deterministic length truncation, same-level collision, nested recursion, array `items` (single + tuple), no-mutation, the cross-level collision regression (#2 above), the `wrapTool` → `executeToolCall` round-trip, and the JSON-string-input → normalize → restore composition (#1 above / issue #2406). > ⚠️ The full vitest suite could not run in my local environment due to a workspace toolchain drift (a stale `node_modules` link made `@composio/core` fail to resolve `picocolors`). The dependency-free sanitizer logic was verified in isolation (including a counter-check proving the old flat mapping corrupted the nested key), and `tsc --noEmit` on the provider sources is clean. Please confirm CI is green before merging. --------- Co-authored-by: serhiizghama <zmrser@gmail.com>

Alberto Schiabel committed Jun 24, 2026 at 20:19 UTC c90ae95f4316226b7b0f4d7ace7207422ba21a42
4 files changed +725 -7
.changeset/anthropic-sanitize-tool-property-keys.md new
+7
@@ -0,0 +1,7 @@
1 +---
2 +'@composio/anthropic': patch
3 +---
4 +
5 +Sanitize tool `input_schema` property keys that violate Anthropic's `^[a-zA-Z0-9_.-]{1,64}$` constraint before sending tools to the Messages API, then restore the original names when the tool is executed.
6 +
7 +A single non-conforming key previously made Anthropic reject the entire `tools` array with HTTP 400, taking down every other tool in the same request. This commonly happened with OneDrive's Microsoft Graph OData parameters (`$top`, `$filter`, `@microsoft.graph.conflictBehavior`) and with over-long flattened keys from tools such as Zoom. Offending keys are now rewritten to conforming aliases (`$` → `dollar_`, `@` → `at_`, any other illegal character → `_`, keys longer than 64 characters truncated with a deterministic suffix), recursing through nested object `properties` and array `items` schemas. The original parameter names are restored before the call reaches the Composio backend, so the model sees `dollar_top` while the backend still receives `$top`. Schemas whose keys already conform are left unchanged.
ts/packages/providers/anthropic/src/index.ts
+48 -7
@@ -19,6 +19,12 @@ import {
19 } from '@composio/core';
20 import Anthropic from '@anthropic-ai/sdk';
21 import { AnthropicTool, InputSchema } from './types';
22 +import {
23 + sanitizeSchemaPropertyKeys,
24 + restoreOriginalKeys,
25 + mappingHasRenames,
26 + KeyMapping,
27 +} from './sanitize-keys';
28
29 export type AnthropicMcpServerGetResponse = {
30 type: 'url';
@@ -60,6 +66,15 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
66 readonly name = 'anthropic';
67 private chacheTools: boolean = false;
68
69 + /**
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.
75 + */
76 + private toolKeyMappings: Map<string, KeyMapping> = new Map();
77 +
78 /**
79 * Creates a new instance of the AnthropicProvider.
80 *
@@ -119,14 +134,29 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
134 * ```
135 */
136 override wrapTool(tool: ComposioTool): AnthropicTool {
137 + const rawSchema = (tool.inputParameters || {
138 + type: 'object',
139 + properties: {},
140 + required: [],
141 + }) as InputSchema;
142 +
143 + // Anthropic rejects the whole `tools` array if any property key falls outside
144 + // `^[a-zA-Z0-9_.-]{1,64}$` (e.g. OData params like `$top`, `@odata.type`, or
145 + // 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 + );
149 +
150 + if (mappingHasRenames(mapping)) {
151 + this.toolKeyMappings.set(tool.slug, mapping);
152 + } else {
153 + this.toolKeyMappings.delete(tool.slug);
154 + }
155 +
156 return {
157 name: tool.slug,
158 description: tool.description || '',
125 - input_schema: (tool.inputParameters || {
126 - type: 'object',
127 - properties: {},
128 - required: [],
129 - }) as InputSchema,
159 + input_schema: schema as unknown as InputSchema,
160 cache_control: this.chacheTools ? { type: 'ephemeral' } : undefined,
161 };
162 }
@@ -211,9 +241,20 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
241 options?: ExecuteToolFnOptions,
242 modifiers?: ExecuteToolModifiers
243 ): Promise<string> {
244 + // Models occasionally emit tool input as a JSON string rather than an object
245 + // (issue #2406). Normalize to a plain object first so key restoration below can
246 + // walk it; restoring before normalizing would no-op on a raw string.
247 + const normalizedInput = normalizeToolArguments(toolUse.input, toolUse.name);
248 +
249 + // Undo any key sanitization applied in `wrapTool` so the backend receives the
250 + // tool's original parameter names (e.g. `dollar_top` -> `$top`).
251 + const mapping = this.toolKeyMappings.get(toolUse.name);
252 + const toolArguments = mapping
253 + ? (restoreOriginalKeys(normalizedInput, mapping) as Record<string, unknown>)
254 + : normalizedInput;
255 +
256 const payload: ToolExecuteParams = {
215 - // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
216 - arguments: normalizeToolArguments(toolUse.input, toolUse.name),
257 + arguments: toolArguments,
258 connectedAccountId: options?.connectedAccountId,
259 customAuthParams: options?.customAuthParams,
260 customConnectionData: options?.customConnectionData,
ts/packages/providers/anthropic/src/sanitize-keys.ts new
+286
@@ -0,0 +1,286 @@
1 +/**
2 + * Anthropic 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.
8 + *
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).
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
26 + * @module providers/anthropic/sanitize-keys
27 + */
28 +
29 +/** Anthropic's allowed property-key pattern. */
30 +const VALID_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;
31 +
32 +/** Maximum length Anthropic accepts for a property key. */
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.
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 +
75 +/**
76 + * Deterministic, dependency-free hash (djb2) rendered as a short base-36 string.
77 + * Used as a uniqueness suffix when truncating long keys or resolving collisions.
78 + */
79 +function shortHash(input: string): string {
80 + let hash = 5381;
81 + for (let i = 0; i < input.length; i++) {
82 + hash = (hash * 33) ^ input.charCodeAt(i);
83 + }
84 + // Force unsigned and keep it short but collision-resistant enough for keys.
85 + return (hash >>> 0).toString(36).slice(0, 7);
86 +}
87 +
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 +
93 +/**
94 + * 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.
97 + */
98 +function sanitizeKey(name: string): string {
99 + let sanitized = name;
100 + for (const [char, replacement] of Object.entries(ILLEGAL_CHAR_MAP)) {
101 + sanitized = sanitized.split(char).join(replacement);
102 + }
103 + sanitized = sanitized.replace(/[^a-zA-Z0-9_.-]/g, '_');
104 +
105 + if (sanitized.length > MAX_KEY_LENGTH) {
106 + const suffix = `_${shortHash(name)}`;
107 + sanitized = sanitized.slice(0, MAX_KEY_LENGTH - suffix.length) + suffix;
108 + }
109 +
110 + return sanitized;
111 +}
112 +
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 +}
128 +
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 + }
163 + }
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;
226 + }
227 + }
228 +
229 + const mapping: KeyMapping = { renames, children };
230 + if (items !== undefined) {
231 + mapping.items = items;
232 + }
233 +
234 + return { node: result, mapping };
235 +}
236 +
237 +/**
238 + * Sanitizes a tool `input_schema` so all property keys conform to Anthropic's
239 + * pattern.
240 + *
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.
245 + */
246 +export function sanitizeSchemaPropertyKeys<T extends Record<string, unknown>>(
247 + schema: T
248 +): { 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;
286 +}
ts/packages/providers/anthropic/test/sanitize-keys.test.ts new
+384
@@ -0,0 +1,384 @@
1 +import { describe, it, expect, vi } from 'vitest';
2 +import { AnthropicProvider } from '../src';
3 +import type { AnthropicTool } from '../src/types';
4 +import type { Tool } from '@composio/core';
5 +import {
6 + sanitizeSchemaPropertyKeys,
7 + restoreOriginalKeys,
8 + mappingHasRenames,
9 +} from '../src/sanitize-keys';
10 +
11 +vi.mock('@anthropic-ai/sdk', () => ({
12 + default: vi.fn().mockImplementation(() => ({ messages: { create: vi.fn() } })),
13 +}));
14 +
15 +const ANTHROPIC_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;
16 +
17 +describe('sanitizeSchemaPropertyKeys', () => {
18 + it('leaves already-valid keys untouched and reports no mapping', () => {
19 + const schema = {
20 + type: 'object',
21 + properties: { query: { type: 'string' }, limit: { type: 'number' } },
22 + required: ['query'],
23 + };
24 +
25 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
26 +
27 + expect(out).toEqual(schema);
28 + expect(mappingHasRenames(mapping)).toBe(false);
29 + });
30 +
31 + it('rewrites OData keys with illegal `$` and `@` characters', () => {
32 + const schema = {
33 + type: 'object',
34 + properties: {
35 + $top: { type: 'integer' },
36 + $filter: { type: 'string' },
37 + '@microsoft.graph.conflictBehavior': { type: 'string' },
38 + },
39 + required: ['$top', '@microsoft.graph.conflictBehavior'],
40 + };
41 +
42 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
43 + const props = out.properties as Record<string, unknown>;
44 +
45 + // Every emitted key must satisfy Anthropic's pattern.
46 + for (const key of Object.keys(props)) {
47 + expect(key).toMatch(ANTHROPIC_KEY_RE);
48 + }
49 +
50 + expect(props).toHaveProperty('dollar_top');
51 + expect(props).toHaveProperty('dollar_filter');
52 + expect(props).toHaveProperty('at_microsoft.graph.conflictBehavior');
53 +
54 + // Mapping points sanitized keys back to the originals (at this level).
55 + expect(mapping.renames['dollar_top']).toBe('$top');
56 + expect(mapping.renames['at_microsoft.graph.conflictBehavior']).toBe(
57 + '@microsoft.graph.conflictBehavior'
58 + );
59 +
60 + // `required` is rewritten to match the sanitized keys.
61 + expect(out.required).toEqual(['dollar_top', 'at_microsoft.graph.conflictBehavior']);
62 +
63 + // Property values are preserved.
64 + expect(props['dollar_top']).toEqual({ type: 'integer' });
65 + });
66 +
67 + it('preserves the legal `.` and `-` characters Anthropic allows', () => {
68 + const schema = {
69 + type: 'object',
70 + properties: { 'a.b-c': { type: 'string' } },
71 + };
72 +
73 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
74 +
75 + expect(out.properties).toHaveProperty('a.b-c');
76 + expect(mappingHasRenames(mapping)).toBe(false);
77 + });
78 +
79 + it('truncates keys longer than 64 characters to a deterministic alias', () => {
80 + const longKey = 'settings__continuous__meeting__chat__auto__add__invited__external__users';
81 + expect(longKey.length).toBeGreaterThan(64);
82 +
83 + const schema = { type: 'object', properties: { [longKey]: { type: 'boolean' } } };
84 +
85 + const first = sanitizeSchemaPropertyKeys(schema);
86 + const second = sanitizeSchemaPropertyKeys(schema);
87 +
88 + const [aliasA] = Object.keys(first.schema.properties as Record<string, unknown>);
89 + const [aliasB] = Object.keys(second.schema.properties as Record<string, unknown>);
90 +
91 + expect(aliasA).toMatch(ANTHROPIC_KEY_RE);
92 + expect(aliasA.length).toBeLessThanOrEqual(64);
93 + expect(aliasA).toBe(aliasB); // deterministic
94 + expect(first.mapping.renames[aliasA]).toBe(longKey);
95 + });
96 +
97 + it('keeps distinct originals distinct when they would collide', () => {
98 + const schema = {
99 + type: 'object',
100 + properties: { $top: { type: 'integer' }, dollar_top: { type: 'string' } },
101 + };
102 +
103 + const { schema: out } = sanitizeSchemaPropertyKeys(schema);
104 + const keys = Object.keys(out.properties as Record<string, unknown>);
105 +
106 + expect(keys).toHaveLength(2);
107 + expect(new Set(keys).size).toBe(2);
108 + keys.forEach(k => expect(k).toMatch(ANTHROPIC_KEY_RE));
109 + });
110 +
111 + it('sanitizes nested object properties recursively', () => {
112 + const schema = {
113 + type: 'object',
114 + properties: {
115 + options: {
116 + type: 'object',
117 + properties: { $skip: { type: 'integer' } },
118 + required: ['$skip'],
119 + },
120 + },
121 + };
122 +
123 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
124 + const nested = (out.properties as any).options;
125 +
126 + expect(nested.properties).toHaveProperty('dollar_skip');
127 + expect(nested.required).toEqual(['dollar_skip']);
128 +
129 + // The rename is recorded at the nested level, not flattened onto the root.
130 + expect(mapping.renames).toEqual({});
131 + expect(mapping.children['options'].renames['dollar_skip']).toBe('$skip');
132 + });
133 +
134 + it('does not mutate the input schema', () => {
135 + const schema = {
136 + type: 'object',
137 + properties: { $top: { type: 'integer' } },
138 + required: ['$top'],
139 + };
140 + const snapshot = JSON.parse(JSON.stringify(schema));
141 +
142 + sanitizeSchemaPropertyKeys(schema);
143 +
144 + expect(schema).toEqual(snapshot);
145 + });
146 +
147 + // P2-2: illegal keys nested inside array element schemas must be sanitized too,
148 + // otherwise they slip past a `properties`-only walk and still trigger a 400.
149 + it('sanitizes illegal keys nested inside array item schemas', () => {
150 + const schema = {
151 + type: 'object',
152 + properties: {
153 + rows: {
154 + type: 'array',
155 + items: {
156 + type: 'object',
157 + properties: { $top: { type: 'integer' } },
158 + required: ['$top'],
159 + },
160 + },
161 + },
162 + };
163 +
164 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
165 + const itemSchema = (out.properties as any).rows.items;
166 +
167 + expect(itemSchema.properties).toHaveProperty('dollar_top');
168 + expect(itemSchema.properties).not.toHaveProperty('$top');
169 + expect(itemSchema.required).toEqual(['dollar_top']);
170 +
171 + // Restoration walks into array elements via the items mapping.
172 + const restored = restoreOriginalKeys({ rows: [{ dollar_top: 1 }, { dollar_top: 2 }] }, mapping);
173 + expect(restored).toEqual({ rows: [{ $top: 1 }, { $top: 2 }] });
174 + });
175 +
176 + it('sanitizes illegal keys in tuple (positional) array item schemas', () => {
177 + const schema = {
178 + type: 'object',
179 + properties: {
180 + pair: {
181 + type: 'array',
182 + items: [
183 + { type: 'object', properties: { $top: { type: 'integer' } } },
184 + { type: 'object', properties: { plain: { type: 'string' } } },
185 + ],
186 + },
187 + },
188 + };
189 +
190 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
191 + const [first, second] = (out.properties as any).pair.items;
192 +
193 + expect(first.properties).toHaveProperty('dollar_top');
194 + expect(second.properties).toHaveProperty('plain');
195 +
196 + const restored = restoreOriginalKeys({ pair: [{ dollar_top: 9 }, { plain: 'x' }] }, mapping);
197 + expect(restored).toEqual({ pair: [{ $top: 9 }, { plain: 'x' }] });
198 + });
199 +});
200 +
201 +describe('restoreOriginalKeys', () => {
202 + it('restores sanitized keys back to their originals, including nested values', () => {
203 + const { mapping } = sanitizeSchemaPropertyKeys({
204 + type: 'object',
205 + properties: {
206 + $top: { type: 'integer' },
207 + nested: { type: 'object', properties: { $skip: { type: 'integer' } } },
208 + },
209 + });
210 +
211 + expect(
212 + restoreOriginalKeys({ dollar_top: 10, nested: { dollar_skip: 5, keep: 'x' } }, mapping)
213 + ).toEqual({ $top: 10, nested: { $skip: 5, keep: 'x' } });
214 + });
215 +
216 + it('passes through values when nothing was renamed', () => {
217 + const { mapping } = sanitizeSchemaPropertyKeys({
218 + type: 'object',
219 + properties: { query: { type: 'string' } },
220 + });
221 + const args = { query: 'hello', items: [1, 2, 3] };
222 + expect(restoreOriginalKeys(args, mapping)).toEqual(args);
223 + });
224 +
225 + // P2-1: a sanitized alias generated at one nesting level must not rewrite a
226 + // legitimately-named key that equals that alias at a *different* level. The old
227 + // flat global map corrupted the nested `dollar_top` into `$top`.
228 + it('does not rewrite a legitimate key that collides with an alias at another level', () => {
229 + const schema = {
230 + type: 'object',
231 + properties: {
232 + $top: { type: 'integer' }, // -> dollar_top at the root
233 + filters: {
234 + type: 'object',
235 + // A genuine, already-valid `dollar_top` that must survive untouched.
236 + properties: { dollar_top: { type: 'string' } },
237 + },
238 + },
239 + };
240 +
241 + const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
242 +
243 + expect(out.properties).toHaveProperty('dollar_top');
244 + expect((out.properties as any).filters.properties).toHaveProperty('dollar_top');
245 +
246 + const restored = restoreOriginalKeys(
247 + { dollar_top: 10, filters: { dollar_top: 'keep-me' } },
248 + mapping
249 + );
250 +
251 + expect(restored).toEqual({
252 + $top: 10, // root alias restored to the OData name
253 + filters: { dollar_top: 'keep-me' }, // nested genuine key left alone
254 + });
255 + });
256 +});
257 +
258 +describe('AnthropicProvider key sanitization', () => {
259 + const odataTool: Tool = {
260 + slug: 'list_drive_item_activities',
261 + name: 'List drive item activities',
262 + description: 'Lists activities on a OneDrive item',
263 + inputParameters: {
264 + type: 'object',
265 + properties: {
266 + $top: { type: 'integer' },
267 + $filter: { type: 'string' },
268 + },
269 + required: ['$top'],
270 + },
271 + tags: [],
272 + } as unknown as Tool;
273 +
274 + it('emits an Anthropic-compatible schema from wrapTool', () => {
275 + const provider = new AnthropicProvider();
276 + const wrapped = provider.wrapTool(odataTool) as AnthropicTool;
277 + const props = wrapped.input_schema.properties as Record<string, unknown>;
278 +
279 + for (const key of Object.keys(props)) {
280 + expect(key).toMatch(ANTHROPIC_KEY_RE);
281 + }
282 + expect(props).toHaveProperty('dollar_top');
283 + });
284 +
285 + it('restores original OData keys before executing the tool call', async () => {
286 + const provider = new AnthropicProvider();
287 + const executeToolFn = vi
288 + .fn()
289 + .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
290 + provider._setExecuteToolFn(executeToolFn);
291 +
292 + // Wrapping registers the reverse mapping for this tool slug.
293 + provider.wrapTool(odataTool);
294 +
295 + // The model calls the tool using the sanitized key names.
296 + await provider.executeToolCall('user-1', {
297 + type: 'tool_use',
298 + id: 'tu_1',
299 + name: 'list_drive_item_activities',
300 + input: { dollar_top: 25 },
301 + });
302 +
303 + expect(executeToolFn).toHaveBeenCalledTimes(1);
304 + const [, payload] = executeToolFn.mock.calls[0];
305 + expect(payload.arguments).toEqual({ $top: 25 });
306 + });
307 +
308 + it('leaves arguments untouched for tools without sanitized keys', async () => {
309 + const provider = new AnthropicProvider();
310 + const executeToolFn = vi
311 + .fn()
312 + .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
313 + provider._setExecuteToolFn(executeToolFn);
314 +
315 + const plainTool: Tool = {
316 + slug: 'plain-tool',
317 + name: 'Plain',
318 + description: 'no illegal keys',
319 + inputParameters: { type: 'object', properties: { query: { type: 'string' } } },
320 + tags: [],
321 + } as unknown as Tool;
322 +
323 + provider.wrapTool(plainTool);
324 + await provider.executeToolCall('user-1', {
325 + type: 'tool_use',
326 + id: 'tu_2',
327 + name: 'plain-tool',
328 + input: { query: 'hello' },
329 + });
330 +
331 + const [, payload] = executeToolFn.mock.calls[0];
332 + expect(payload.arguments).toEqual({ query: 'hello' });
333 + });
334 +
335 + // Models occasionally emit tool input as a JSON *string* (issue #2406). The
336 + // provider normalizes it to an object before restoring keys; restoring a raw
337 + // string would be a no-op, so this guards the normalize-then-restore ordering.
338 + it('normalizes a JSON-string input before restoring sanitized keys', async () => {
339 + const provider = new AnthropicProvider();
340 + const executeToolFn = vi
341 + .fn()
342 + .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
343 + provider._setExecuteToolFn(executeToolFn);
344 +
345 + provider.wrapTool(odataTool);
346 +
347 + await provider.executeToolCall('user-1', {
348 + type: 'tool_use',
349 + id: 'tu_3',
350 + name: 'list_drive_item_activities',
351 + input: '{"dollar_top": 25}' as unknown as Record<string, unknown>,
352 + });
353 +
354 + const [, payload] = executeToolFn.mock.calls[0];
355 + expect(payload.arguments).toEqual({ $top: 25 });
356 + });
357 +
358 + it('normalizes a JSON-string input for tools without sanitized keys (issue #2406)', async () => {
359 + const provider = new AnthropicProvider();
360 + const executeToolFn = vi
361 + .fn()
362 + .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
363 + provider._setExecuteToolFn(executeToolFn);
364 +
365 + const plainTool: Tool = {
366 + slug: 'plain-tool',
367 + name: 'Plain',
368 + description: 'no illegal keys',
369 + inputParameters: { type: 'object', properties: { query: { type: 'string' } } },
370 + tags: [],
371 + } as unknown as Tool;
372 +
373 + provider.wrapTool(plainTool);
374 + await provider.executeToolCall('user-1', {
375 + type: 'tool_use',
376 + id: 'tu_4',
377 + name: 'plain-tool',
378 + input: '{"query":"hello"}' as unknown as Record<string, unknown>,
379 + });
380 +
381 + const [, payload] = executeToolFn.mock.calls[0];
382 + expect(payload.arguments).toEqual({ query: 'hello' });
383 + });
384 +});