Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
md 94 lines 5.43 KB
Rendered Raw
1 # @composio/anthropic
2
3 Adapts Composio tools to the Claude Messages API and executes the tool calls Claude returns.
4
5 ## Installation
6
7 ```bash
8 npm install @composio/core @composio/anthropic @anthropic-ai/sdk
9 ```
10
11 Set `COMPOSIO_API_KEY` (create one at https://dashboard.composio.dev/settings) and `ANTHROPIC_API_KEY` (from https://console.anthropic.com/settings/keys) in your environment.
12
13 ## Quickstart
14
15 Create a session for your user, pass its tools to the Messages API, and run the tool-call loop until Claude replies with text. `handleToolCalls` executes every `tool_use` block and returns a ready-to-append `user` message of `tool_result` blocks.
16
17 ```typescript
18 import Anthropic from '@anthropic-ai/sdk';
19 import { Composio } from '@composio/core';
20 import { AnthropicProvider } from '@composio/anthropic';
21
22 const composio = new Composio({
23 provider: new AnthropicProvider(),
24 });
25 const client = new Anthropic();
26
27 // Create a session for your user
28 const session = await composio.create('user_123');
29 const tools = await session.tools();
30
31 const messages: Anthropic.MessageParam[] = [
32 {
33 role: 'user',
34 content:
35 "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
36 },
37 ];
38
39 let response = await client.messages.create({
40 model: 'claude-opus-5-5',
41 max_tokens: 4096,
42 tools,
43 messages,
44 });
45
46 // Agentic loop: keep executing tool calls until the model responds with text
47 while (response.stop_reason === 'tool_use') {
48 const toolResults = await composio.provider.handleToolCalls(session, response);
49 messages.push({ role: 'assistant', content: response.content });
50 messages.push(...toolResults);
51 response = await client.messages.create({
52 model: 'claude-opus-5-5',
53 max_tokens: 4096,
54 tools,
55 messages,
56 });
57 }
58
59 // Print final response
60 for (const block of response.content) {
61 if (block.type === 'text') {
62 console.log(block.text);
63 }
64 }
65 ```
66
67 Building on the Claude Agent SDK instead? Use [`@composio/claude-agent-sdk`](../claude-agent-sdk), which exposes Composio tools as an in-process MCP server and lets the SDK run the loop.
68
69 ## Provider options
70
71 - `cacheTools`: pass `new AnthropicProvider({ cacheTools: true })` to attach Anthropic's ephemeral `cache_control` to your tool definitions, letting Claude reuse the cached tool schemas across requests. It is the only constructor option.
72 - Anthropic allows at most 4 `cache_control` breakpoints per request, shared across the system prompt, tools, and messages. A breakpoint caches everything up to and including it, so `wrapTools` places one breakpoint on the last tool instead of one per tool. Tool-result blocks from `handleToolCalls` are never marked, because you append them to the message list every turn and their breakpoints would pile up.
73 - The cap applies to the whole request, not to a single call. If you merge the results of several `wrapTools` calls (for example from several `tools.get()` calls), each list's last tool carries a breakpoint, so keep the total within the limit.
74 - `handleToolCalls(session, message)` returns `Anthropic.Messages.MessageParam[]`, not raw strings, so you append the result directly to your message list. Pass a user ID instead of a session for tools fetched with `tools.get()`. For finer control, `executeToolCall(session, toolUseBlock)` runs a single `tool_use` block and returns the result as a JSON string.
75 - Claude occasionally emits a tool's `input` as a JSON string instead of an object; the provider normalizes this before execution.
76
77 ## Execution contracts
78
79 | Entry point | Arguments | Return value |
80 | --- | --- | --- |
81 | `session.execute` | `toolSlug`, `arguments` | Plain object with `resultType`, `data`, `error`, and `logId`. Check `result.resultType === 'completed'`; serialize with `JSON.stringify(result)`. |
82 | `composio.tools.execute` | `toolSlug`, `{ arguments, userId }` | `ToolExecuteResponse`; check `result.successful`. |
83 | `afterExecute` modifier | `{ toolSlug, toolkitSlug, result }` | Receives and returns `ToolExecuteResponse`; check `result.successful`. |
84 | `executeToolCall` | `session, toolUse` or `userId, toolUse, options?, modifiers?` | JSON string: `data` when `error === null`, otherwise `{ error }`. |
85 | `handleToolCalls` | `session, message` or `userId, message, options?, modifiers?` | `Anthropic.Messages.MessageParam[]`: a `user` message containing ordered `tool_result` blocks, or `[]` when there are no tool uses. |
86
87 `handleToolCalls` sets each block's `tool_use_id` from the original `tool_use.id`. It doesn't include the full execution metadata or an `is_error` flag; its serialized content is **not** an explicit success discriminator. If your application needs to inspect execution outcomes, use `session.execute` or direct execution and retain the model call ID when building your own message blocks. Python's `handle_tool_calls` returns execution dictionaries instead of TypeScript-native messages.
88
89 Session adapters derive `successful` from `resultType === 'completed'`. A failed execution can have an empty or `null` error. A log ID is for correlation, not proof of a provider-side side effect. Check the explicit status and tool-specific `data`. Transport/authentication errors can throw; handle authentication recovery separately from returned execution failures. A batch can stop after earlier calls have run, so don't blindly replay it. Retry and idempotency decisions remain yours.
90
91 ## Links
92
93 - [Anthropic provider docs](https://docs.composio.dev/docs/providers/anthropic)
94 - [Composio documentation](https://docs.composio.dev)