Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | /** |
| 2 | * Anthropic Provider |
| 3 | * |
| 4 | * This provider provides a set of tools for interacting with Anthropic's API. |
| 5 | * It implements the non-agentic provider interface for Anthropic's Claude models. |
| 6 | * |
| 7 | * @packageDocumentation |
| 8 | * @module providers/anthropic |
| 9 | */ |
| 10 | import { |
| 11 | BaseNonAgenticProvider, |
| 12 | Tool as ComposioTool, |
| 13 | ExecuteToolModifiers, |
| 14 | ExecuteToolFnOptions, |
| 15 | ToolCallExecutionTarget, |
| 16 | ToolCallSession, |
| 17 | logger, |
| 18 | McpUrlResponse, |
| 19 | normalizeToolArguments, |
| 20 | dereferenceJsonSchema, |
| 21 | deduplicateJsonSchemaRequiredArrays, |
| 22 | } from '@composio/core'; |
| 23 | import Anthropic from '@anthropic-ai/sdk'; |
| 24 | import { AnthropicTool, InputSchema } from './types'; |
| 25 | import { |
| 26 | sanitizeSchemaPropertyKeys, |
| 27 | restoreOriginalKeys, |
| 28 | mappingHasRenames, |
| 29 | KeyMapping, |
| 30 | } from './sanitize-keys'; |
| 31 | |
| 32 | export type AnthropicMcpServerGetResponse = { |
| 33 | type: 'url'; |
| 34 | url: string; |
| 35 | name: string; |
| 36 | }[]; |
| 37 | |
| 38 | export type { AnthropicTool, InputSchema, CacheControlEphemeral } from './types'; |
| 39 | |
| 40 | /** |
| 41 | * Collection of Anthropic tools |
| 42 | */ |
| 43 | export type AnthropicToolCollection = AnthropicTool[]; |
| 44 | |
| 45 | /** |
| 46 | * Type for Anthropic tool use block in message content |
| 47 | */ |
| 48 | export interface AnthropicToolUseBlock { |
| 49 | type: 'tool_use'; |
| 50 | id: string; |
| 51 | name: string; |
| 52 | input: Record<string, unknown>; |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Type for Anthropic message content block |
| 57 | */ |
| 58 | export type AnthropicContentBlock = { |
| 59 | type: string; |
| 60 | [key: string]: unknown; |
| 61 | }; |
| 62 | |
| 63 | /** |
| 64 | * Anthropic Provider implementation for Composio |
| 65 | */ |
| 66 | export class AnthropicProvider extends BaseNonAgenticProvider< |
| 67 | AnthropicToolCollection, |
| 68 | AnthropicTool, |
| 69 | AnthropicMcpServerGetResponse |
| 70 | > { |
| 71 | readonly name = 'anthropic'; |
| 72 | private cacheTools: boolean = false; |
| 73 | |
| 74 | /** |
| 75 | * Per-tool reverse key mappings (`sanitized -> original`, shaped like the |
| 76 | * schema), keyed by tool slug. Populated by {@link wrapTool} whenever a tool's |
| 77 | * schema contains keys that violate Anthropic's `^[a-zA-Z0-9_.-]{1,64}$` |
| 78 | * constraint, and read by {@link executeToolCall} to restore the original |
| 79 | * parameter names before the call reaches the Composio backend. |
| 80 | * |
| 81 | * **Contract:** a tool must be wrapped and executed through the *same* provider |
| 82 | * instance. This holds for the standard Composio flow — the model can only call |
| 83 | * tools previously emitted by {@link wrapTools}/{@link wrapTool} on this |
| 84 | * instance, and that wrapping registers the mapping. If a tool is somehow |
| 85 | * executed on an instance that never wrapped it, no mapping is found and the |
| 86 | * model's (already sanitized) argument keys are forwarded unchanged, so the |
| 87 | * backend would see e.g. `dollar_top` instead of `$top`. {@link executeToolCall} |
| 88 | * emits a `debug` log on the path that actually restores keys so this is |
| 89 | * diagnosable. |
| 90 | * |
| 91 | * Re-wrapping a slug refreshes its entry (or clears it when the new schema |
| 92 | * needs no rewriting), so the map stays consistent and its size is bounded by |
| 93 | * the number of distinct sanitized tool slugs this instance has wrapped. |
| 94 | */ |
| 95 | private toolKeyMappings: Map<string, KeyMapping> = new Map(); |
| 96 | |
| 97 | /** |
| 98 | * Creates a new instance of the AnthropicProvider. |
| 99 | * |
| 100 | * @param {Object} [options] - Configuration options for the provider |
| 101 | * @param {boolean} [options.cacheTools=false] - Whether to cache tools using Anthropic's ephemeral |
| 102 | * cache. Anthropic allows at most 4 cache_control breakpoints per request, shared across the |
| 103 | * system prompt, tools, and messages, and a breakpoint caches everything up to and including |
| 104 | * it — so {@link wrapTools} places a single breakpoint on the last tool, covering the whole |
| 105 | * tool list with one breakpoint. Tool results are never marked, since they accumulate in the |
| 106 | * message history across turns. |
| 107 | * |
| 108 | * @example |
| 109 | * ```typescript |
| 110 | * // Initialize with default settings (no caching) |
| 111 | * const provider = new AnthropicProvider(); |
| 112 | * |
| 113 | * // Initialize with tool caching enabled |
| 114 | * const providerWithCaching = new AnthropicProvider({ |
| 115 | * cacheTools: true |
| 116 | * }); |
| 117 | * |
| 118 | * // Use with Composio |
| 119 | * const composio = new Composio({ |
| 120 | * apiKey: 'your-api-key', |
| 121 | * provider: new AnthropicProvider({ |
| 122 | * cacheTools: true |
| 123 | * }) |
| 124 | * }); |
| 125 | * ``` |
| 126 | */ |
| 127 | constructor(options?: { cacheTools?: boolean }) { |
| 128 | super(); |
| 129 | this.cacheTools = options?.cacheTools ?? false; |
| 130 | logger.debug(`AnthropicProvider initialized [cacheTools: ${this.cacheTools}]`); |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * Wraps a Composio tool in the Anthropic format. |
| 135 | * |
| 136 | * This method transforms a Composio tool definition into the format |
| 137 | * expected by Anthropic's Claude API for tool use. |
| 138 | * |
| 139 | * @param tool - The Composio tool to wrap |
| 140 | * @returns The wrapped tool in Anthropic format |
| 141 | * |
| 142 | * @example |
| 143 | * ```typescript |
| 144 | * // Wrap a single tool for use with Anthropic |
| 145 | * const composioTool = { |
| 146 | * slug: 'SEARCH_TOOL', |
| 147 | * description: 'Search for information', |
| 148 | * inputParameters: { |
| 149 | * type: 'object', |
| 150 | * properties: { |
| 151 | * query: { type: 'string' } |
| 152 | * }, |
| 153 | * required: ['query'] |
| 154 | * } |
| 155 | * }; |
| 156 | * |
| 157 | * const anthropicTool = provider.wrapTool(composioTool); |
| 158 | * ``` |
| 159 | */ |
| 160 | override wrapTool(tool: ComposioTool): AnthropicTool { |
| 161 | const rawSchema = (tool.inputParameters || { |
| 162 | type: 'object', |
| 163 | properties: {}, |
| 164 | required: [], |
| 165 | }) as InputSchema; |
| 166 | |
| 167 | // Inline internal `$ref` / `$defs` first so keys reachable only through a |
| 168 | // reference become ordinary value positions that can be both sanitized and |
| 169 | // restored. Lenient mode keeps an upstream schema with a dangling ref usable |
| 170 | // (it degrades the branch to a permissive object) instead of throwing. |
| 171 | const dereferenced = dereferenceJsonSchema(rawSchema, { |
| 172 | onUnresolved: 'sentinel', |
| 173 | onReplace: ref => |
| 174 | logger.debug( |
| 175 | `AnthropicProvider: unresolved $ref "${ref}" in tool "${tool.slug}" replaced ` + |
| 176 | `with a permissive schema` |
| 177 | ), |
| 178 | }); |
| 179 | |
| 180 | // Anthropic rejects the whole `tools` array if any property key falls outside |
| 181 | // `^[a-zA-Z0-9_.-]{1,64}$` (e.g. OData params like `$top`, `@odata.type`, or |
| 182 | // over-long flattened keys). Rewrite offending keys and remember how to undo it. |
| 183 | const { schema: sanitizedSchema, mapping } = sanitizeSchemaPropertyKeys(dereferenced); |
| 184 | const schema = deduplicateJsonSchemaRequiredArrays(sanitizedSchema) as InputSchema; |
| 185 | |
| 186 | if (mappingHasRenames(mapping)) { |
| 187 | this.toolKeyMappings.set(tool.slug, mapping); |
| 188 | logger.debug( |
| 189 | `AnthropicProvider rewrote non-conforming schema keys for tool "${tool.slug}"; ` + |
| 190 | `original parameter names will be restored at execution time` |
| 191 | ); |
| 192 | } else { |
| 193 | // Clear any stale mapping from a previous wrap of the same slug whose |
| 194 | // schema no longer needs rewriting, so restoration stays consistent. |
| 195 | this.toolKeyMappings.delete(tool.slug); |
| 196 | } |
| 197 | |
| 198 | return { |
| 199 | name: tool.slug, |
| 200 | description: tool.description || '', |
| 201 | input_schema: schema, |
| 202 | ...(this.cacheTools ? { cache_control: { type: 'ephemeral' } } : {}), |
| 203 | }; |
| 204 | } |
| 205 | |
| 206 | /** |
| 207 | * Wraps a list of Composio tools in the Anthropic format. |
| 208 | * |
| 209 | * This method transforms multiple Composio tool definitions into the format |
| 210 | * expected by Anthropic's Claude API for tool use. |
| 211 | * |
| 212 | * @param tools - Array of Composio tools to wrap |
| 213 | * @returns Array of wrapped tools in Anthropic format |
| 214 | * |
| 215 | * @example |
| 216 | * ```typescript |
| 217 | * // Wrap multiple tools for use with Anthropic |
| 218 | * const composioTools = [ |
| 219 | * { |
| 220 | * slug: 'SEARCH_TOOL', |
| 221 | * description: 'Search for information', |
| 222 | * inputParameters: { |
| 223 | * type: 'object', |
| 224 | * properties: { |
| 225 | * query: { type: 'string' } |
| 226 | * } |
| 227 | * } |
| 228 | * }, |
| 229 | * { |
| 230 | * slug: 'WEATHER_TOOL', |
| 231 | * description: 'Get weather information', |
| 232 | * inputParameters: { |
| 233 | * type: 'object', |
| 234 | * properties: { |
| 235 | * location: { type: 'string' } |
| 236 | * } |
| 237 | * } |
| 238 | * } |
| 239 | * ]; |
| 240 | * |
| 241 | * const anthropicTools = provider.wrapTools(composioTools); |
| 242 | * ``` |
| 243 | */ |
| 244 | override wrapTools(tools: ComposioTool[]): AnthropicToolCollection { |
| 245 | const wrapped = tools.map(tool => this.wrapTool(tool)); |
| 246 | // A cache_control breakpoint caches every block up to and including it, |
| 247 | // so one breakpoint on the last tool covers the entire tool list. |
| 248 | // Anthropic caps breakpoints at 4 per request (shared with the system |
| 249 | // prompt and messages); a breakpoint on every tool would exceed that |
| 250 | // limit as soon as a caller passes 5+ tools. |
| 251 | if (this.cacheTools) { |
| 252 | for (const tool of wrapped.slice(0, -1)) { |
| 253 | delete tool.cache_control; |
| 254 | } |
| 255 | } |
| 256 | return wrapped; |
| 257 | } |
| 258 | |
| 259 | /** |
| 260 | * Executes a tool call from Anthropic's Claude API. |
| 261 | * |
| 262 | * This method processes a tool call from Anthropic's Claude API, |
| 263 | * executes the corresponding Composio tool, and returns the result. |
| 264 | * |
| 265 | * @param executionTarget - A user ID for direct tools or the session that produced session tools |
| 266 | * @param toolUse - The tool use object from Anthropic |
| 267 | * @param options - Additional options for tool execution |
| 268 | * @param modifiers - Modifiers for tool execution |
| 269 | * @returns A JSON string: data when error is null, otherwise { error }. This |
| 270 | * projection omits the execution status; use session.execute or direct |
| 271 | * execution when application logic needs resultType or successful. |
| 272 | * |
| 273 | * @example |
| 274 | * ```typescript |
| 275 | * // Execute a tool call from Anthropic |
| 276 | * const toolUse = { |
| 277 | * type: 'tool_use', |
| 278 | * id: 'tu_abc123', |
| 279 | * name: 'SEARCH_TOOL', |
| 280 | * input: { |
| 281 | * query: 'composio documentation' |
| 282 | * } |
| 283 | * }; |
| 284 | * |
| 285 | * const result = await provider.executeToolCall( |
| 286 | * 'user123', |
| 287 | * toolUse, |
| 288 | * { connectedAccountId: 'conn_xyz456' } |
| 289 | * ); |
| 290 | * console.log(JSON.parse(result)); |
| 291 | * ``` |
| 292 | */ |
| 293 | async executeToolCall(session: ToolCallSession, toolUse: AnthropicToolUseBlock): Promise<string>; |
| 294 | async executeToolCall( |
| 295 | userId: string, |
| 296 | toolUse: AnthropicToolUseBlock, |
| 297 | options?: ExecuteToolFnOptions, |
| 298 | modifiers?: ExecuteToolModifiers |
| 299 | ): Promise<string>; |
| 300 | async executeToolCall( |
| 301 | executionTarget: ToolCallExecutionTarget, |
| 302 | toolUse: AnthropicToolUseBlock, |
| 303 | options?: ExecuteToolFnOptions, |
| 304 | modifiers?: ExecuteToolModifiers |
| 305 | ): Promise<string> { |
| 306 | // Models occasionally emit tool input as a JSON string rather than an object |
| 307 | // (issue #2406). Normalize to a plain object first so key restoration below can |
| 308 | // walk it; restoring before normalizing would no-op on a raw string. |
| 309 | const normalizedInput = normalizeToolArguments(toolUse.input, toolUse.name); |
| 310 | |
| 311 | // Undo any key sanitization applied in `wrapTool` so the backend receives the |
| 312 | // tool's original parameter names (e.g. `dollar_top` -> `$top`). The mapping |
| 313 | // is only present when this same instance wrapped the tool and rewrote keys |
| 314 | // (see `toolKeyMappings`); otherwise the arguments pass through untouched. |
| 315 | const mapping = this.toolKeyMappings.get(toolUse.name); |
| 316 | let toolArguments = normalizedInput; |
| 317 | if (mapping) { |
| 318 | toolArguments = restoreOriginalKeys(normalizedInput, mapping) as Record<string, unknown>; |
| 319 | logger.debug(`AnthropicProvider restored original argument keys for tool "${toolUse.name}"`); |
| 320 | } |
| 321 | |
| 322 | const result = await this.executeToolForTarget( |
| 323 | executionTarget, |
| 324 | toolUse.name, |
| 325 | toolArguments, |
| 326 | options, |
| 327 | modifiers |
| 328 | ); |
| 329 | return JSON.stringify(result.error === null ? result.data : { error: result.error }); |
| 330 | } |
| 331 | |
| 332 | /** |
| 333 | * Handles tool calls from Anthropic's message response. |
| 334 | * |
| 335 | * This method processes tool calls from an Anthropic message response, |
| 336 | * extracts the tool use blocks, executes each tool call, and returns the results. |
| 337 | * |
| 338 | * @param executionTarget - A user ID for direct tools or the session that produced session tools |
| 339 | * @param message - The message response from Anthropic |
| 340 | * @param options - Additional options for tool execution |
| 341 | * @param modifiers - Modifiers for tool execution |
| 342 | * @returns Ready-to-append user messages containing ordered tool_result blocks, |
| 343 | * each correlated by tool_use_id. Content is the JSON projection returned by |
| 344 | * executeToolCall, not a full execution response or a success discriminator. |
| 345 | * |
| 346 | * @example |
| 347 | * ```typescript |
| 348 | * // Handle tool calls from an Anthropic message response |
| 349 | * const anthropic = new Anthropic({ apiKey: 'your-anthropic-api-key' }); |
| 350 | * |
| 351 | * const message = await anthropic.messages.create({ |
| 352 | * model: 'claude-opus-5-5', |
| 353 | * max_tokens: 1024, |
| 354 | * tools: provider.wrapTools(composioTools), |
| 355 | * messages: [ |
| 356 | * { |
| 357 | * role: 'user', |
| 358 | * content: 'Search for information about Composio' |
| 359 | * } |
| 360 | * ] |
| 361 | * }); |
| 362 | * |
| 363 | * // Process any tool calls in the response |
| 364 | * const results = await provider.handleToolCalls( |
| 365 | * 'user123', |
| 366 | * message, |
| 367 | * { connectedAccountId: 'conn_xyz456' } |
| 368 | * ); |
| 369 | * |
| 370 | * // Use the results to continue the conversation |
| 371 | * console.log(results); |
| 372 | * ``` |
| 373 | */ |
| 374 | async handleToolCalls( |
| 375 | session: ToolCallSession, |
| 376 | message: Anthropic.Message |
| 377 | ): Promise<Anthropic.Messages.MessageParam[]>; |
| 378 | async handleToolCalls( |
| 379 | userId: string, |
| 380 | message: Anthropic.Message, |
| 381 | options?: ExecuteToolFnOptions, |
| 382 | modifiers?: ExecuteToolModifiers |
| 383 | ): Promise<Anthropic.Messages.MessageParam[]>; |
| 384 | async handleToolCalls( |
| 385 | executionTarget: ToolCallExecutionTarget, |
| 386 | message: Anthropic.Message, |
| 387 | options?: ExecuteToolFnOptions, |
| 388 | modifiers?: ExecuteToolModifiers |
| 389 | ): Promise<Anthropic.Messages.MessageParam[]> { |
| 390 | this.assertToolCallExecutionOptions(executionTarget, options, modifiers); |
| 391 | const outputs: Anthropic.Messages.ToolResultBlockParam[] = []; |
| 392 | |
| 393 | // Filter and map tool use blocks from message content |
| 394 | const toolUseBlocks: AnthropicToolUseBlock[] = []; |
| 395 | |
| 396 | for (const content of message.content) { |
| 397 | if ( |
| 398 | typeof content === 'object' && |
| 399 | content !== null && |
| 400 | 'type' in content && |
| 401 | typeof content.type === 'string' && |
| 402 | content.type.toString() === 'tool_use' && |
| 403 | 'id' in content && |
| 404 | 'name' in content && |
| 405 | 'input' in content |
| 406 | ) { |
| 407 | toolUseBlocks.push({ |
| 408 | type: 'tool_use', |
| 409 | id: String(content.id), |
| 410 | name: String(content.name), |
| 411 | input: content.input as Record<string, unknown>, |
| 412 | }); |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | for (const toolUse of toolUseBlocks) { |
| 417 | const toolResult = |
| 418 | typeof executionTarget === 'string' |
| 419 | ? await this.executeToolCall(executionTarget, toolUse, options, modifiers) |
| 420 | : await this.executeToolCall(executionTarget, toolUse); |
| 421 | outputs.push({ |
| 422 | type: 'tool_result', |
| 423 | tool_use_id: toolUse.id, |
| 424 | content: toolResult, |
| 425 | }); |
| 426 | } |
| 427 | |
| 428 | // Tool results are not marked as cache breakpoints. The caller appends |
| 429 | // every turn's results to the message history, so a breakpoint here would |
| 430 | // add one more to each later request until the 4-breakpoint limit is hit. |
| 431 | return outputs.length > 0 ? [{ role: 'user', content: outputs }] : []; |
| 432 | } |
| 433 | |
| 434 | /** |
| 435 | * Transform MCP URL response into Anthropic-specific format. |
| 436 | * By default, Anthropic uses the standard format (same as default), |
| 437 | * but this method is here to show providers can customize if needed. |
| 438 | * |
| 439 | * @param data - The MCP URL response data |
| 440 | * @returns Standard MCP server response format |
| 441 | */ |
| 442 | wrapMcpServerResponse(data: McpUrlResponse): AnthropicMcpServerGetResponse { |
| 443 | // Anthropic uses the standard format with URL objects |
| 444 | return data.map(item => ({ |
| 445 | url: item.url, |
| 446 | name: item.name, |
| 447 | type: 'url', |
| 448 | })); |
| 449 | } |
| 450 | } |