Skip to content

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)

Alberto Schiabelc90ae95f4316
diff --git a/.changeset/anthropic-sanitize-tool-property-keys.md b/.changeset/anthropic-sanitize-tool-property-keys.md
new file mode 100644
index 000000000..1b7858b77
--- /dev/null
+++ b/.changeset/anthropic-sanitize-tool-property-keys.md
@@ -0,0 +1,7 @@
+---
+'@composio/anthropic': patch
+---
+
+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.
+
+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.
diff --git a/ts/packages/providers/anthropic/src/index.ts b/ts/packages/providers/anthropic/src/index.ts
index 040c0dedb..82c0da293 100644
--- a/ts/packages/providers/anthropic/src/index.ts
+++ b/ts/packages/providers/anthropic/src/index.ts
@@ -19,6 +19,12 @@ import {
} from '@composio/core';
import Anthropic from '@anthropic-ai/sdk';
import { AnthropicTool, InputSchema } from './types';
+import {
+ sanitizeSchemaPropertyKeys,
+ restoreOriginalKeys,
+ mappingHasRenames,
+ KeyMapping,
+} from './sanitize-keys';
export type AnthropicMcpServerGetResponse = {
type: 'url';
@@ -60,6 +66,15 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
readonly name = 'anthropic';
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.
+ */
+ private toolKeyMappings: Map<string, KeyMapping> = new Map();
+
/**
* Creates a new instance of the AnthropicProvider.
*
@@ -119,14 +134,29 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
* ```
*/
override wrapTool(tool: ComposioTool): AnthropicTool {
+ const rawSchema = (tool.inputParameters || {
+ type: 'object',
+ properties: {},
+ required: [],
+ }) as InputSchema;
+
+ // 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>
+ );
+
+ if (mappingHasRenames(mapping)) {
+ this.toolKeyMappings.set(tool.slug, mapping);
+ } else {
+ this.toolKeyMappings.delete(tool.slug);
+ }
+
return {
name: tool.slug,
description: tool.description || '',
- input_schema: (tool.inputParameters || {
- type: 'object',
- properties: {},
- required: [],
- }) as InputSchema,
+ input_schema: schema as unknown as InputSchema,
cache_control: this.chacheTools ? { type: 'ephemeral' } : undefined,
};
}
@@ -211,9 +241,20 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
options?: ExecuteToolFnOptions,
modifiers?: ExecuteToolModifiers
): Promise<string> {
+ // Models occasionally emit tool input as a JSON string rather than an object
+ // (issue #2406). Normalize to a plain object first so key restoration below can
+ // walk it; restoring before normalizing would no-op on a raw string.
+ 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`).
+ const mapping = this.toolKeyMappings.get(toolUse.name);
+ const toolArguments = mapping
+ ? (restoreOriginalKeys(normalizedInput, mapping) as Record<string, unknown>)
+ : normalizedInput;
+
const payload: ToolExecuteParams = {
- // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
- arguments: normalizeToolArguments(toolUse.input, toolUse.name),
+ arguments: toolArguments,
connectedAccountId: options?.connectedAccountId,
customAuthParams: options?.customAuthParams,
customConnectionData: options?.customConnectionData,
diff --git a/ts/packages/providers/anthropic/src/sanitize-keys.ts b/ts/packages/providers/anthropic/src/sanitize-keys.ts
new file mode 100644
index 000000000..a3173095d
--- /dev/null
+++ b/ts/packages/providers/anthropic/src/sanitize-keys.ts
@@ -0,0 +1,286 @@
+/**
+ * Anthropic 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.
+ *
+ * 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).
+ *
+ * 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
+ */
+
+/** Anthropic's allowed property-key pattern. */
+const VALID_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;
+
+/** Maximum length Anthropic accepts for a property key. */
+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.
+ */
+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.
+ */
+function shortHash(input: string): string {
+ let hash = 5381;
+ for (let i = 0; i < input.length; i++) {
+ hash = (hash * 33) ^ input.charCodeAt(i);
+ }
+ // Force unsigned and keep it short but collision-resistant enough for keys.
+ 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.
+ */
+function sanitizeKey(name: string): string {
+ let sanitized = name;
+ for (const [char, replacement] of Object.entries(ILLEGAL_CHAR_MAP)) {
+ sanitized = sanitized.split(char).join(replacement);
+ }
+ sanitized = sanitized.replace(/[^a-zA-Z0-9_.-]/g, '_');
+
+ if (sanitized.length > MAX_KEY_LENGTH) {
+ const suffix = `_${shortHash(name)}`;
+ sanitized = sanitized.slice(0, MAX_KEY_LENGTH - suffix.length) + suffix;
+ }
+
+ 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;
+}
+
+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);
+ }
+ }
+
+ 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;
+ }
+ }
+
+ const mapping: KeyMapping = { renames, children };
+ if (items !== undefined) {
+ mapping.items = items;
+ }
+
+ return { node: result, mapping };
+}
+
+/**
+ * Sanitizes a tool `input_schema` so all property keys conform to Anthropic's
+ * pattern.
+ *
+ * @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.
+ */
+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;
+}
diff --git a/ts/packages/providers/anthropic/test/sanitize-keys.test.ts b/ts/packages/providers/anthropic/test/sanitize-keys.test.ts
new file mode 100644
index 000000000..34e8427b8
--- /dev/null
+++ b/ts/packages/providers/anthropic/test/sanitize-keys.test.ts
@@ -0,0 +1,384 @@
+import { describe, it, expect, vi } from 'vitest';
+import { AnthropicProvider } from '../src';
+import type { AnthropicTool } from '../src/types';
+import type { Tool } from '@composio/core';
+import {
+ sanitizeSchemaPropertyKeys,
+ restoreOriginalKeys,
+ mappingHasRenames,
+} from '../src/sanitize-keys';
+
+vi.mock('@anthropic-ai/sdk', () => ({
+ default: vi.fn().mockImplementation(() => ({ messages: { create: vi.fn() } })),
+}));
+
+const ANTHROPIC_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;
+
+describe('sanitizeSchemaPropertyKeys', () => {
+ it('leaves already-valid keys untouched and reports no mapping', () => {
+ const schema = {
+ type: 'object',
+ properties: { query: { type: 'string' }, limit: { type: 'number' } },
+ required: ['query'],
+ };
+
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
+
+ expect(out).toEqual(schema);
+ expect(mappingHasRenames(mapping)).toBe(false);
+ });
+
+ it('rewrites OData keys with illegal `$` and `@` characters', () => {
+ const schema = {
+ type: 'object',
+ properties: {
+ $top: { type: 'integer' },
+ $filter: { type: 'string' },
+ '@microsoft.graph.conflictBehavior': { type: 'string' },
+ },
+ required: ['$top', '@microsoft.graph.conflictBehavior'],
+ };
+
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
+ const props = out.properties as Record<string, unknown>;
+
+ // Every emitted key must satisfy Anthropic's pattern.
+ for (const key of Object.keys(props)) {
+ expect(key).toMatch(ANTHROPIC_KEY_RE);
+ }
+
+ expect(props).toHaveProperty('dollar_top');
+ expect(props).toHaveProperty('dollar_filter');
+ expect(props).toHaveProperty('at_microsoft.graph.conflictBehavior');
+
+ // Mapping points sanitized keys back to the originals (at this level).
+ expect(mapping.renames['dollar_top']).toBe('$top');
+ expect(mapping.renames['at_microsoft.graph.conflictBehavior']).toBe(
+ '@microsoft.graph.conflictBehavior'
+ );
+
+ // `required` is rewritten to match the sanitized keys.
+ expect(out.required).toEqual(['dollar_top', 'at_microsoft.graph.conflictBehavior']);
+
+ // Property values are preserved.
+ expect(props['dollar_top']).toEqual({ type: 'integer' });
+ });
+
+ it('preserves the legal `.` and `-` characters Anthropic allows', () => {
+ const schema = {
+ type: 'object',
+ properties: { 'a.b-c': { type: 'string' } },
+ };
+
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
+
+ expect(out.properties).toHaveProperty('a.b-c');
+ expect(mappingHasRenames(mapping)).toBe(false);
+ });
+
+ it('truncates keys longer than 64 characters to a deterministic alias', () => {
+ const longKey = 'settings__continuous__meeting__chat__auto__add__invited__external__users';
+ expect(longKey.length).toBeGreaterThan(64);
+
+ const schema = { type: 'object', properties: { [longKey]: { type: 'boolean' } } };
+
+ const first = sanitizeSchemaPropertyKeys(schema);
+ const second = sanitizeSchemaPropertyKeys(schema);
+
+ const [aliasA] = Object.keys(first.schema.properties as Record<string, unknown>);
+ const [aliasB] = Object.keys(second.schema.properties as Record<string, unknown>);
+
+ expect(aliasA).toMatch(ANTHROPIC_KEY_RE);
+ expect(aliasA.length).toBeLessThanOrEqual(64);
+ expect(aliasA).toBe(aliasB); // deterministic
+ expect(first.mapping.renames[aliasA]).toBe(longKey);
+ });
+
+ it('keeps distinct originals distinct when they would collide', () => {
+ const schema = {
+ type: 'object',
+ properties: { $top: { type: 'integer' }, dollar_top: { type: 'string' } },
+ };
+
+ const { schema: out } = sanitizeSchemaPropertyKeys(schema);
+ const keys = Object.keys(out.properties as Record<string, unknown>);
+
+ expect(keys).toHaveLength(2);
+ expect(new Set(keys).size).toBe(2);
+ keys.forEach(k => expect(k).toMatch(ANTHROPIC_KEY_RE));
+ });
+
+ it('sanitizes nested object properties recursively', () => {
+ const schema = {
+ type: 'object',
+ properties: {
+ options: {
+ type: 'object',
+ properties: { $skip: { type: 'integer' } },
+ required: ['$skip'],
+ },
+ },
+ };
+
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
+ const nested = (out.properties as any).options;
+
+ expect(nested.properties).toHaveProperty('dollar_skip');
+ expect(nested.required).toEqual(['dollar_skip']);
+
+ // The rename is recorded at the nested level, not flattened onto the root.
+ expect(mapping.renames).toEqual({});
+ expect(mapping.children['options'].renames['dollar_skip']).toBe('$skip');
+ });
+
+ it('does not mutate the input schema', () => {
+ const schema = {
+ type: 'object',
+ properties: { $top: { type: 'integer' } },
+ required: ['$top'],
+ };
+ const snapshot = JSON.parse(JSON.stringify(schema));
+
+ sanitizeSchemaPropertyKeys(schema);
+
+ expect(schema).toEqual(snapshot);
+ });
+
+ // P2-2: illegal keys nested inside array element schemas must be sanitized too,
+ // otherwise they slip past a `properties`-only walk and still trigger a 400.
+ it('sanitizes illegal keys nested inside array item schemas', () => {
+ const schema = {
+ type: 'object',
+ properties: {
+ rows: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: { $top: { type: 'integer' } },
+ required: ['$top'],
+ },
+ },
+ },
+ };
+
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
+ const itemSchema = (out.properties as any).rows.items;
+
+ expect(itemSchema.properties).toHaveProperty('dollar_top');
+ expect(itemSchema.properties).not.toHaveProperty('$top');
+ expect(itemSchema.required).toEqual(['dollar_top']);
+
+ // Restoration walks into array elements via the items mapping.
+ const restored = restoreOriginalKeys({ rows: [{ dollar_top: 1 }, { dollar_top: 2 }] }, mapping);
+ expect(restored).toEqual({ rows: [{ $top: 1 }, { $top: 2 }] });
+ });
+
+ it('sanitizes illegal keys in tuple (positional) array item schemas', () => {
+ const schema = {
+ type: 'object',
+ properties: {
+ pair: {
+ type: 'array',
+ items: [
+ { type: 'object', properties: { $top: { type: 'integer' } } },
+ { type: 'object', properties: { plain: { type: 'string' } } },
+ ],
+ },
+ },
+ };
+
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
+ const [first, second] = (out.properties as any).pair.items;
+
+ expect(first.properties).toHaveProperty('dollar_top');
+ expect(second.properties).toHaveProperty('plain');
+
+ const restored = restoreOriginalKeys({ pair: [{ dollar_top: 9 }, { plain: 'x' }] }, mapping);
+ expect(restored).toEqual({ pair: [{ $top: 9 }, { plain: 'x' }] });
+ });
+});
+
+describe('restoreOriginalKeys', () => {
+ it('restores sanitized keys back to their originals, including nested values', () => {
+ const { mapping } = sanitizeSchemaPropertyKeys({
+ type: 'object',
+ properties: {
+ $top: { type: 'integer' },
+ nested: { type: 'object', properties: { $skip: { type: 'integer' } } },
+ },
+ });
+
+ expect(
+ restoreOriginalKeys({ dollar_top: 10, nested: { dollar_skip: 5, keep: 'x' } }, mapping)
+ ).toEqual({ $top: 10, nested: { $skip: 5, keep: 'x' } });
+ });
+
+ it('passes through values when nothing was renamed', () => {
+ const { mapping } = sanitizeSchemaPropertyKeys({
+ type: 'object',
+ properties: { query: { type: 'string' } },
+ });
+ const args = { query: 'hello', items: [1, 2, 3] };
+ expect(restoreOriginalKeys(args, mapping)).toEqual(args);
+ });
+
+ // P2-1: a sanitized alias generated at one nesting level must not rewrite a
+ // legitimately-named key that equals that alias at a *different* level. The old
+ // flat global map corrupted the nested `dollar_top` into `$top`.
+ it('does not rewrite a legitimate key that collides with an alias at another level', () => {
+ const schema = {
+ type: 'object',
+ properties: {
+ $top: { type: 'integer' }, // -> dollar_top at the root
+ filters: {
+ type: 'object',
+ // A genuine, already-valid `dollar_top` that must survive untouched.
+ properties: { dollar_top: { type: 'string' } },
+ },
+ },
+ };
+
+ const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
+
+ expect(out.properties).toHaveProperty('dollar_top');
+ expect((out.properties as any).filters.properties).toHaveProperty('dollar_top');
+
+ const restored = restoreOriginalKeys(
+ { dollar_top: 10, filters: { dollar_top: 'keep-me' } },
+ mapping
+ );
+
+ expect(restored).toEqual({
+ $top: 10, // root alias restored to the OData name
+ filters: { dollar_top: 'keep-me' }, // nested genuine key left alone
+ });
+ });
+});
+
+describe('AnthropicProvider key sanitization', () => {
+ const odataTool: Tool = {
+ slug: 'list_drive_item_activities',
+ name: 'List drive item activities',
+ description: 'Lists activities on a OneDrive item',
+ inputParameters: {
+ type: 'object',
+ properties: {
+ $top: { type: 'integer' },
+ $filter: { type: 'string' },
+ },
+ required: ['$top'],
+ },
+ tags: [],
+ } as unknown as Tool;
+
+ it('emits an Anthropic-compatible schema from wrapTool', () => {
+ const provider = new AnthropicProvider();
+ const wrapped = provider.wrapTool(odataTool) as AnthropicTool;
+ const props = wrapped.input_schema.properties as Record<string, unknown>;
+
+ for (const key of Object.keys(props)) {
+ expect(key).toMatch(ANTHROPIC_KEY_RE);
+ }
+ expect(props).toHaveProperty('dollar_top');
+ });
+
+ it('restores original OData keys before executing the tool call', async () => {
+ const provider = new AnthropicProvider();
+ const executeToolFn = vi
+ .fn()
+ .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
+ provider._setExecuteToolFn(executeToolFn);
+
+ // Wrapping registers the reverse mapping for this tool slug.
+ provider.wrapTool(odataTool);
+
+ // The model calls the tool using the sanitized key names.
+ await provider.executeToolCall('user-1', {
+ type: 'tool_use',
+ id: 'tu_1',
+ name: 'list_drive_item_activities',
+ input: { dollar_top: 25 },
+ });
+
+ expect(executeToolFn).toHaveBeenCalledTimes(1);
+ const [, payload] = executeToolFn.mock.calls[0];
+ expect(payload.arguments).toEqual({ $top: 25 });
+ });
+
+ it('leaves arguments untouched for tools without sanitized keys', async () => {
+ const provider = new AnthropicProvider();
+ const executeToolFn = vi
+ .fn()
+ .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
+ provider._setExecuteToolFn(executeToolFn);
+
+ const plainTool: Tool = {
+ slug: 'plain-tool',
+ name: 'Plain',
+ description: 'no illegal keys',
+ inputParameters: { type: 'object', properties: { query: { type: 'string' } } },
+ tags: [],
+ } as unknown as Tool;
+
+ provider.wrapTool(plainTool);
+ await provider.executeToolCall('user-1', {
+ type: 'tool_use',
+ id: 'tu_2',
+ name: 'plain-tool',
+ input: { query: 'hello' },
+ });
+
+ const [, payload] = executeToolFn.mock.calls[0];
+ expect(payload.arguments).toEqual({ query: 'hello' });
+ });
+
+ // Models occasionally emit tool input as a JSON *string* (issue #2406). The
+ // provider normalizes it to an object before restoring keys; restoring a raw
+ // string would be a no-op, so this guards the normalize-then-restore ordering.
+ it('normalizes a JSON-string input before restoring sanitized keys', async () => {
+ const provider = new AnthropicProvider();
+ const executeToolFn = vi
+ .fn()
+ .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
+ provider._setExecuteToolFn(executeToolFn);
+
+ provider.wrapTool(odataTool);
+
+ await provider.executeToolCall('user-1', {
+ type: 'tool_use',
+ id: 'tu_3',
+ name: 'list_drive_item_activities',
+ input: '{"dollar_top": 25}' as unknown as Record<string, unknown>,
+ });
+
+ const [, payload] = executeToolFn.mock.calls[0];
+ expect(payload.arguments).toEqual({ $top: 25 });
+ });
+
+ it('normalizes a JSON-string input for tools without sanitized keys (issue #2406)', async () => {
+ const provider = new AnthropicProvider();
+ const executeToolFn = vi
+ .fn()
+ .mockResolvedValue({ data: { ok: true }, error: null, successful: true });
+ provider._setExecuteToolFn(executeToolFn);
+
+ const plainTool: Tool = {
+ slug: 'plain-tool',
+ name: 'Plain',
+ description: 'no illegal keys',
+ inputParameters: { type: 'object', properties: { query: { type: 'string' } } },
+ tags: [],
+ } as unknown as Tool;
+
+ provider.wrapTool(plainTool);
+ await provider.executeToolCall('user-1', {
+ type: 'tool_use',
+ id: 'tu_4',
+ name: 'plain-tool',
+ input: '{"query":"hello"}' as unknown as Record<string, unknown>,
+ });
+
+ const [, payload] = executeToolFn.mock.calls[0];
+ expect(payload.arguments).toEqual({ query: 'hello' });
+ });
+});