### Configure Web Fetch Tool Request Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool Example of initializing a request with the web_fetch tool definition. ```json max_tokens: 1024, messages: [ { role: "user", content: "Please analyze the content at https://example.com/article" } ], tools: [{ type: "web_fetch_20250910", name: "web_fetch", max_uses: 5 }] ) puts message ``` -------------------------------- ### Install Anthropic and MCP SDKs Source: https://platform.claude.com/docs/en/agents-and-tools/mcp-connector Install both the Anthropic SDK and the MCP SDK using npm to utilize the client-side helpers. ```bash npm install @anthropic-ai/sdk @modelcontextprotocol/sdk ``` -------------------------------- ### Multi-step Automation Workflow Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool Demonstration of chaining multiple commands to install dependencies, create files, and execute scripts within a persistent session. ```text User request: "Install the requests library and create a simple Python script that fetches a joke from an API, then run it." Claude's tool uses: 1. Install package {"command": "pip install requests"} 2. Create script {"command": "cat > fetch_joke.py << 'EOF'\nimport requests\nresponse = requests.get('https://official-joke-api.appspot.com/random_joke')\njoke = response.json()\nprint(f\"Setup: {joke['setup']}\")\nprint(f\"Punchline: {joke['punchline']}\")\nEOF"} 3. Run script {"command": "python fetch_joke.py"} ``` -------------------------------- ### Deferred Tools with TypeScript SDK Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool This TypeScript example shows how to configure deferred tools when creating a message using the Anthropic SDK. Make sure to install the SDK (`npm install @anthropic-ai/sdk`). ```TypeScript import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic(); async function main() { const response = await client.messages.create({ model: "claude-opus-4-7", max_tokens: 2048, messages: [ { role: "user", content: "What is the weather in San Francisco?" } ], tools: [ { type: "tool_search_tool_regex_20251119", name: "tool_search_tool_regex" }, { name: "get_weather", description: "Get the weather at a specific location", input_schema: { type: "object" as const, properties: { location: { type: "string" }, unit: { type: "string", enum: ["celsius", "fahrenheit"] } }, required: ["location"] }, defer_loading: true }, { name: "search_files", description: "Search through files in the workspace", input_schema: { type: "object" as const, properties: { query: { type: "string" }, file_types: { type: "array" as const, items: { type: "string" } } }, required: ["query"] }, defer_loading: true } ] }); console.log(response); } main(); ``` -------------------------------- ### Create Message with MCP Server and Toolset (Ruby) Source: https://platform.claude.com/docs/en/agents-and-tools/mcp-connector This Ruby example shows how to configure and send a message with an MCP server and toolset using the Anthropic Ruby client. Ensure the gem is installed. ```ruby require "anthropic" client = Anthropic::Client.new response = client.beta.messages.create( model: "claude-opus-4-7", max_tokens: 1000, messages: [ { role: "user", content: "What tools do you have available?" } ], mcp_servers: [ { type: "url", url: "https://example-server.modelcontextprotocol.io/sse", name: "example-mcp", authorization_token: "YOUR_TOKEN" } ], tools: [ { type: "mcp_toolset", mcp_server_name: "example-mcp" } ], betas: ["mcp-client-2025-11-20"] ) puts response ``` -------------------------------- ### Example File Content Output Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool Illustrates the formatted output for file content with line numbers. ```text Here's the content of /memories/notes.txt with line numbers: 1 Hello World 2 This is line two 10 Line ten 100 Line one hundred ``` -------------------------------- ### Use Web Fetch Tool with PHP SDK Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool Analyze web content in PHP by incorporating the web_fetch_20250910 tool. This example assumes the Anthropic PHP SDK is installed and the API key is set. ```php messages->create( maxTokens: 1024, messages: [ ['role' => 'user', 'content' => 'Please analyze the content at https://example.com/article'] ], model: 'claude-opus-4-7', tools: [[ 'type' => 'web_fetch_20250910', 'name' => 'web_fetch', 'max_uses' => 5, ]], ); echo $message; ``` -------------------------------- ### Implement Deferred Tool Loading Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool Example of a tool definition with defer_loading enabled to allow on-demand loading. ```json { "name": "get_weather", "description": "Get current weather for a location", "input_schema": { "type": "object", "properties": { "location": { "type": "string" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] }, "defer_loading": true } ``` -------------------------------- ### Initialize Anthropic Client in Java Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool Setup the Anthropic client using environment variables for subsequent API interactions. ```java public class ContainerReuse { public static void main(String[] args) { AnthropicClient client = AnthropicOkHttpClient.fromEnv(); ``` -------------------------------- ### Streaming Code Execution Events Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool This example shows how to receive code execution events as they occur, including start, delta, and result streams. ```SSE event: content_block_start data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "code_execution"}} // Code execution streamed event: content_block_delta data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"code\":\"import pandas as pd\ndf = pd.read_csv('data.csv')\nprint(df.head())\"}"}} // Pause while code executes // Execution results streamed event: content_block_start data: {"type": "content_block_start", "index": 2, "content_block": {"type": "code_execution_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"stdout": " A B C\n0 1 2 3\n1 4 5 6", "stderr": ""}}} ``` -------------------------------- ### Install Claude API Skill as a Plugin Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/claude-api-skill Install the Claude API skill as a plugin within Claude Code. ```bash /plugin marketplace add anthropics/skills /plugin install claude-api@anthropic-agent-skills ``` -------------------------------- ### Enable MCP Tools via API and CLI Source: https://platform.claude.com/docs/en/agents-and-tools/mcp-connector Examples showing how to configure an MCP server connection using cURL and the Anthropic CLI. ```bash curl https://api.anthropic.com/v1/messages \ -H "Content-Type: application/json" \ -H "X-API-Key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "anthropic-beta: mcp-client-2025-11-20" \ -d '{ "model": "claude-opus-4-7", "max_tokens": 1000, "messages": [{"role": "user", "content": "What tools do you have available?"}], "mcp_servers": [ { "type": "url", "url": "https://example-server.modelcontextprotocol.io/sse", "name": "example-mcp", "authorization_token": "YOUR_TOKEN" } ], "tools": [ { "type": "mcp_toolset", "mcp_server_name": "example-mcp" } ] }' ``` ```bash ant beta:messages create --beta mcp-client-2025-11-20 <<'YAML' model: claude-opus-4-7 max_tokens: 1000 messages: - role: user content: What tools do you have available? mcp_servers: - type: url url: https://example-server.modelcontextprotocol.io/sse name: example-mcp authorization_token: YOUR_TOKEN tools: - type: mcp_toolset mcp_server_name: example-mcp YAML ``` -------------------------------- ### CLI Example for Container Creation Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool This CLI command demonstrates the initial request to create a container and write a file. The container ID is captured for subsequent reuse. ```bash # First request: Create a file with a random number CONTAINER_ID=$(ant messages create \ --transform container.id --format yaml \ --model claude-opus-4-7 \ --max-tokens 4096 \ --message '{role: user, content: Write a file with a random number and save it to "/tmp/number.txt"}' \ --tool '{type: code_execution_20250825, name: code_execution}' ) ``` -------------------------------- ### Migrate an existing project Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/claude-api-skill Example task for migrating a codebase to a specific model version. ```text /claude-api migrate this codebase to claude-opus-4-7 and re-tune effort ``` -------------------------------- ### Define deferred tool Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool Example of a tool definition with defer_loading enabled. ```json { "name": "my_tool", "description": "Full description here", "input_schema": { // complete schema }, "defer_loading": true } ``` -------------------------------- ### Memory Tool Interaction Examples Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool Demonstrates the sequence of tool calls and results for checking directories and reading file contents during a memory-enabled session. ```json { "type": "tool_use", "id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4", "name": "memory", "input": { "command": "view", "path": "/memories" } } ``` ```json { "type": "tool_result", "tool_use_id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4", "content": "Here're the files and directories up to 2 levels deep in /memories, excluding hidden items and node_modules:\n4.0K\t/memories\n1.5K\t/memories/customer_service_guidelines.xml\n2.0K\t/memories/refund_policies.xml" } ``` ```json { "type": "tool_use", "id": "toolu_01D5E6F7G8H9I0J1K2L3M4N5", "name": "memory", "input": { "command": "view", "path": "/memories/customer_service_guidelines.xml" } } ``` ```json { "type": "tool_result", "tool_use_id": "toolu_01D5E6F7G8H9I0J1K2L3M4N5", "content": "Here's the content of /memories/customer_service_guidelines.xml with line numbers:\n 1\t\n 2\t\n 3\t- Always address customers by their first name\n 4\t- Use empathetic language\n..." } ``` -------------------------------- ### Install Claude API Skill using npx Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/claude-api-skill Install the Claude API skill from the Anthropic skills repository using the npx command. ```bash npx skills add https://github.com/anthropics/skills --skill claude-api ``` -------------------------------- ### Initialize Bash Tool Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool Examples of how to enable the bash tool when calling the Anthropic API via cURL, CLI, or the Python SDK. ```bash curl https://api.anthropic.com/v1/messages \ -H "content-type: application/json" \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -d '{ "model": "claude-opus-4-7", "max_tokens": 1024, "tools": [ { "type": "bash_20250124", "name": "bash" } ], "messages": [ { "role": "user", "content": "List all Python files in the current directory." } ] }' ``` ```bash ant messages create \ --model claude-opus-4-7 \ --max-tokens 1024 \ --tool '{type: bash_20250124, name: bash}' \ --message '{role: user, content: List all Python files in the current directory.}' ``` ```python import anthropic client = anthropic.Anthropic() response = client.messages.create( model="claude-opus-4-7", max_tokens=1024, tools=[{"type": "bash_20250124", "name": "bash"}], messages=[ {"role": "user", "content": "List all Python files in the current directory."} ], ) print(response) ``` -------------------------------- ### Scaffold a Managed Agent Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/claude-api-skill Initializes the Managed Agent setup process through an interactive interview. ```text /claude-api managed-agents-onboard ``` -------------------------------- ### Skill Directory Structure Example Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview Illustrates the typical file organization within a Skill directory, including markdown instructions and Python scripts. ```text pdf-skill/ ├── SKILL.md (main instructions) ├── FORMS.md (form-filling guide) ├── REFERENCE.md (detailed API reference) └── scripts/ └── fill_form.py (utility script) ``` -------------------------------- ### Handle Bash Command Response Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool Example of the tool use and result format for bash command execution. ```json [ { "type": "server_tool_use", "id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3", "name": "bash_code_execution", "input": { "command": "ls -la | head -5" } }, { "type": "bash_code_execution_tool_result", "tool_use_id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3", "content": { "type": "bash_code_execution_result", "stdout": "total 24\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 11:00 ..\n-rw-r--r-- 1 user user 220 Jan 1 12:00 data.csv\n-rw-r--r-- 1 user user 180 Jan 1 12:00 config.json", "stderr": "", "return_code": 0 } } ] ``` -------------------------------- ### Skill Metadata Example Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview YAML frontmatter for a Skill, providing discovery information like name and description. This metadata is always loaded. ```yaml --- name: pdf-processing description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. --- ``` -------------------------------- ### Handle File Operation Responses Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool Examples of tool use and result formats for viewing, creating, and editing files. ```json [ { "type": "server_tool_use", "id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4", "name": "text_editor_code_execution", "input": { "command": "view", "path": "config.json" } }, { "type": "text_editor_code_execution_tool_result", "tool_use_id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4", "content": { "type": "text_editor_code_execution_result", "file_type": "text", "content": "{\n \"setting\": \"value\",\n \"debug\": true\n}", "numLines": 4, "startLine": 1, "totalLines": 4 } } ] ``` ```json [ { "type": "server_tool_use", "id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5", "name": "text_editor_code_execution", "input": { "command": "create", "path": "new_file.txt", "file_text": "Hello, World!" } }, { "type": "text_editor_code_execution_tool_result", "tool_use_id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5", "content": { "type": "text_editor_code_execution_result", "is_file_update": false } } ] ``` ```json [ { "type": "server_tool_use", "id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6", "name": "text_editor_code_execution", "input": { "command": "str_replace", "path": "config.json", "old_str": "\"debug\": true", "new_str": "\"debug\": false" } }, { "type": "text_editor_code_execution_tool_result", "tool_use_id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6", "content": { "type": "text_editor_code_execution_result", "oldStart": 3, "oldLines": 1, "newStart": 3, "newLines": 1, "lines": ["- \"debug\": true", "+ \"debug\": false"] } } ] ``` -------------------------------- ### Invoke a server tool Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview Examples of using the web_search server tool via various interfaces. Server tools are executed on Anthropic's infrastructure. ```bash curl https://api.anthropic.com/v1/messages \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "content-type: application/json" \ -d '{ "model": "claude-opus-4-7", "max_tokens": 1024, "tools": [{"type": "web_search_20260209", "name": "web_search"}], "messages": [{"role": "user", "content": "What's the latest on the Mars rover?"}] }' ``` ```bash ant messages create --transform content --format yaml \ --model claude-opus-4-7 \ --max-tokens 1024 \ --tool '{type: web_search_20260209, name: web_search}' \ --message '{role: user, content: "What is the latest on the Mars rover?"}' ``` ```python import anthropic client = anthropic.Anthropic() response = client.messages.create( model="claude-opus-4-7", max_tokens=1024, tools=[{"type": "web_search_20260209", "name": "web_search"}], messages=[{"role": "user", "content": "What's the latest on the Mars rover?"}], ) print(response.content) ``` ```typescript import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic(); const response = await client.messages.create({ model: "claude-opus-4-7", max_tokens: 1024, tools: [{ type: "web_search_20260209", name: "web_search" }], messages: [{ role: "user", content: "What's the latest on the Mars rover?" }] }); console.log(response.content); ``` -------------------------------- ### TypeScript SDK for Computer Use Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool This TypeScript example shows how to use the Anthropic SDK to enable computer use features in messages. ```TypeScript import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic(); const response = await client.beta.messages.create({ model: "claude-opus-4-7", max_tokens: 1024, tools: [ { type: "computer_20251124", name: "computer", display_width_px: 1024, display_height_px: 768, display_number: 1 }, { type: "text_editor_20250728", name: "str_replace_based_edit_tool" }, { type: "bash_20250124", name: "bash" } ], messages: [{ role: "user", content: "Save a picture of a cat to my desktop." }], betas: ["computer-use-2025-11-24"] }); console.log(response); ``` -------------------------------- ### Programmatic Tool Call Example Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling This JSON shows a programmatic tool call, including the tool's name, input, and caller information. ```json { "type": "tool_use", "id": "toolu_abc123", "name": "query_database", "input": { "sql": "" }, "caller": { "type": "code_execution_20260120", "tool_id": "srvtoolu_xyz789" } } ``` -------------------------------- ### Go SDK for Computer Use Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool This Go example shows how to initialize the Anthropic client and create messages with computer use tools. It includes error handling for the API call. ```Go package main import ( "context" "fmt" "log" "github.com/anthropics/anthropic-sdk-go" ) func main() { client := anthropic.NewClient() response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{ Model: anthropic.ModelClaudeOpus4_7, MaxTokens: 1024, Tools: []anthropic.BetaToolUnionParam{ {OfComputerUseTool20251124: &anthropic.BetaToolComputerUse20251124Param{ DisplayWidthPx: 1024, DisplayHeightPx: 768, DisplayNumber: anthropic.Int(1), }}, {OfTextEditor20250728: &anthropic.BetaToolTextEditor20250728Param{}}, {OfBashTool20250124: &anthropic.BetaToolBash20250124Param{}}, }, Messages: []anthropic.BetaMessageParam{ anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Save a picture of a cat to my desktop.")), }, Betas: []anthropic.AnthropicBeta{ anthropic.AnthropicBetaComputerUse2025_11_24, }, }) if err != nil { log.Fatal(err) } fmt.Println(response) } ``` -------------------------------- ### Tool Use Implementation via CLI and Python Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool Demonstrates how to implement the tool use flow using the CLI and the Python SDK. ```bash ant messages create <<'YAML' model: claude-opus-4-7 max_tokens: 1024 tools: - type: text_editor_20250728 name: str_replace_based_edit_tool messages: # Previous messages... - role: assistant content: - type: text text: >- I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you. - type: tool_use id: toolu_01PqRsTuVwXyZAbCdEfGh name: str_replace_based_edit_tool input: command: str_replace path: primes.py old_str: " for num in range(2, limit + 1)" new_str: " for num in range(2, limit + 1):" - role: user content: - type: tool_result tool_use_id: toolu_01PqRsTuVwXyZAbCdEfGh content: Successfully replaced text at exactly one location. YAML ``` ```python response = client.messages.create( model="claude-opus-4-7", max_tokens=1024, tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}], messages=[ # Previous messages... { "role": "assistant", "content": [ { "type": "text", "text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you.", }, { "type": "tool_use", "id": "toolu_01PqRsTuVwXyZAbCdEfGh", "name": "str_replace_based_edit_tool", "input": { "command": "str_replace", "path": "primes.py", "old_str": " for num in range(2, limit + 1)", "new_str": " for num in range(2, limit + 1):", }, }, ], }, { "role": "user", "content": [ { "type": "tool_result", "tool_use_id": "toolu_01PqRsTuVwXyZAbCdEfGh", ``` -------------------------------- ### Stream tool search events Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool Example of the SSE stream format when tool search is enabled, showing content block start, delta, and result events. ```sse event: content_block_start data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "tool_search_tool_regex"}} // Search query streamed event: content_block_delta data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"query\":\"weather\"}"}} // Pause while search executes // Search results streamed event: content_block_start data: {"type": "content_block_start", "index": 2, "content_block": {"type": "tool_search_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"type": "tool_search_tool_search_result", "tool_references": [{"type": "tool_reference", "tool_name": "get_weather"}]}}} // Claude continues with discovered tools ``` -------------------------------- ### Send a message with tools using Go Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool Use the Go SDK to initialize the client and prepare a message request. ```go package main import ( "context" "fmt" "log" "github.com/anthropics/anthropic-sdk-go" ) func main() { client := anthropic.NewClient() response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{ Model: anthropic.ModelClaudeOpus4_7, MaxTokens: 2048, ``` -------------------------------- ### Streaming Web Search Events Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool This example shows the Server-Sent Events (SSE) stream for a web search tool interaction, including message starts, tool use decisions, query streaming, pauses for execution, and result streaming. ```sse event: message_start data: {"type": "message_start", "message": {"id": "msg_abc123", "type": "message"}} event: content_block_start data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}} // Claude's decision to search event: content_block_start data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "web_search"}} // Search query streamed event: content_block_delta data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"query\":\"latest quantum computing breakthroughs 2025\"}"}} // Pause while search executes // Search results streamed event: content_block_start data: {"type": "content_block_start", "index": 2, "content_block": {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": [{"type": "web_search_result", "title": "Quantum Computing Breakthroughs in 2025", "url": "https://example.com"}]}} // Claude's response with citations (omitted in this example) ``` -------------------------------- ### Create Message with Tool Use (Go) Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling Example of creating a message that includes tool use definitions for code execution and database queries in Go. This snippet demonstrates setting up the client and constructing the message parameters. ```go package main import ( "context" "fmt" "log" "github.com/anthropics/anthropic-sdk-go" ) func main() { client := anthropic.NewClient() response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{ Model: anthropic.ModelClaudeOpus4_7, MaxTokens: 4096, Container: anthropic.MessageNewParamsContainerUnion{ OfString: anthropic.String("container_xyz789"), }, Messages: []anthropic.MessageParam{ anthropic.NewUserMessage(anthropic.NewTextBlock("Query customer purchase history from the last quarter and identify our top 5 customers by revenue")), { Role: anthropic.MessageParamRoleAssistant, Content: []anthropic.ContentBlockParamUnion{ anthropic.NewTextBlock("I'll query the purchase history and analyze the results."), {OfServerToolUse: &anthropic.ServerToolUseBlockParam{ ID: "srvtoolu_abc123", Name: anthropic.ServerToolUseBlockParamNameCodeExecution, Input: map[string]any{"code": "..."}}, }, {OfToolUse: &anthropic.ToolUseBlockParam{ ID: "toolu_def456", Name: "query_database", Input: map[string]any{"sql": ""}, Caller: anthropic.ServerToolUseBlockParamCallerUnion{ OfCodeExecution20260120: &anthropic.ServerToolCaller20260120Param{ ToolID: "srvtoolu_abc123", }, }, }}, }, }, { Role: anthropic.MessageParamRoleUser, Content: []anthropic.ContentBlockParamUnion{ {OfToolResult: &anthropic.ToolResultBlockParam{ ToolUseID: "toolu_def456", Content: []anthropic.ToolResultBlockParamContentUnion{ {OfText: &anthropic.TextBlockParam{ Text: `[{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2", "revenue": 38000}, ...]`}}, }, }}, }, }, }, Tools: []anthropic.ToolUnionParam{ {OfCodeExecutionTool20260120: &anthropic.CodeExecutionTool20260120Param{}}, }, }) if err != nil { log.Fatal(err) } fmt.Println(response) } ``` -------------------------------- ### Tool Configuration Merging Example Source: https://platform.claude.com/docs/en/agents-and-tools/mcp-connector Demonstrates how tool-specific settings, default configurations, and system defaults merge. Tool-specific settings in 'configs' have the highest precedence, followed by 'default_config', and then system defaults. ```json { "type": "mcp_toolset", "mcp_server_name": "google-calendar-mcp", "default_config": { "defer_loading": true }, "configs": { "search_events": { "enabled": false } } } ``` -------------------------------- ### Deferred Tools with Python SDK Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool This Python snippet demonstrates how to use the Anthropic SDK to create a message with deferred tools. Ensure you have the SDK installed (`pip install anthropic`). ```Python import anthropic client = anthropic.Anthropic() response = client.messages.create( model="claude-opus-4-7", max_tokens=2048, messages=[{"role": "user", "content": "What is the weather in San Francisco?"}], tools=[ {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}, { "name": "get_weather", "description": "Get the weather at a specific location", "input_schema": { "type": "object", "properties": { "location": {"type": "string"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location"], }, "defer_loading": True, }, { "name": "search_files", "description": "Search through files in the workspace", "input_schema": { "type": "object", "properties": { "query": {"type": "string"}, "file_types": {"type": "array", "items": {"type": "string"}}, }, "required": ["query"], }, "defer_loading": True, }, ], ) print(response) ``` -------------------------------- ### Execute Code and Read File in PHP Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool This PHP example shows how to write a file with a random number and then read it to compute its square, utilizing the code execution tool. ```PHP messages->create( maxTokens: 4096, messages: [ ['role' => 'user', 'content' => "Write a file with a random number and save it to '/tmp/number.txt'"] ], model: 'claude-opus-4-7', tools: [ ['type' => 'code_execution_20250825', 'name' => 'code_execution'] ], ); $containerId = $response1->container->id; $response2 = $client->messages->create( container: $containerId, maxTokens: 4096, messages: [ ['role' => 'user', 'content' => "Read the number from '/tmp/number.txt' and calculate its square"] ], model: 'claude-opus-4-7', tools: [ ['type' => 'code_execution_20250825', 'name' => 'code_execution'] ], ); ``` -------------------------------- ### Create Message with Memory Tool (Java) Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool This Java example demonstrates how to create a message using the memory tool. It utilizes the Anthropic OkHttp client and requires setting up environment variables for authentication. ```java import com.anthropic.client.AnthropicClient; import com.anthropic.client.okhttp.AnthropicOkHttpClient; import com.anthropic.models.messages.MemoryTool20250818; import com.anthropic.models.messages.Message; import com.anthropic.models.messages.MessageCreateParams; import com.anthropic.models.messages.Model; public class MemoryToolExample { public static void main(String[] args) { AnthropicClient client = AnthropicOkHttpClient.fromEnv(); MessageCreateParams params = MessageCreateParams.builder() .model(Model.CLAUDE_OPUS_4_7) .maxTokens(2048L) .addUserMessage("I'm working on a Python web scraper that keeps crashing with a timeout error. Here's the problematic function:\n\n```python\ndef fetch_page(url, retries=3):\n for i in range(retries):\n try:\n response = requests.get(url, timeout=5)\n return response.text\n except requests.exceptions.Timeout:\n if i == retries - 1:\n raise\n time.sleep(1)\n```\n\nPlease help me debug this.") .addTool(MemoryTool20250818.builder().build()) .build(); Message response = client.messages().create(params); System.out.println(response); } } ``` -------------------------------- ### cURL Example for Container Reuse Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool This cURL example demonstrates how to reuse a container for sequential API requests. The first request creates a file, and the container ID is extracted to be used in the second request to read and process the file. ```bash cd "$(mktemp -d)" # First request: Create a file with a random number curl https://api.anthropic.com/v1/messages \ --header "x-api-key: $ANTHROPIC_API_KEY" \ --header "anthropic-version: 2023-06-01" \ --header "content-type: application/json" \ --data '{ "model": "claude-opus-4-7", "max_tokens": 4096, "messages": [{"role": "user", "content": "Write a file with a random number and save it to \"/tmp/number.txt\""}], "tools": [{"type": "code_execution_20250825", "name": "code_execution"}] }' > response1.json # Extract container ID from the response (using jq) CONTAINER_ID=$(jq -r '.container.id' response1.json) # Second request: Reuse the container to read the file curl https://api.anthropic.com/v1/messages \ --header "x-api-key: $ANTHROPIC_API_KEY" \ --header "anthropic-version: 2023-06-01" \ --header "content-type: application/json" \ --data '{ "container": "'$CONTAINER_ID'", "model": "claude-opus-4-7", "max_tokens": 4096, "messages": [{"role": "user", "content": "Read the number from \"/tmp/number.txt\" and calculate its square"}], "tools": [{"type": "code_execution_20250825", "name": "code_execution"}] }' ``` -------------------------------- ### Skill Directory Structure Example Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices Illustrates a recommended directory structure for skills, including a main SKILL.md file and a reference directory for additional documentation. This structure supports progressive disclosure by keeping core information in SKILL.md and detailed content in separate files. ```text bigquery-skill/ ├── SKILL.md (overview, points to reference files) └── reference/ ├── finance.md (revenue metrics) ├── sales.md (pipeline data) └── product.md (usage analytics) ``` -------------------------------- ### Execute Code and Read File in Java Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool This Java example demonstrates creating a file with a random number and then reading that file to calculate its square using the code execution tool. ```Java MessageCreateParams params1 = MessageCreateParams.builder() .model(Model.CLAUDE_OPUS_4_7) .maxTokens(4096L) .addUserMessage("Write a file with a random number and save it to '/tmp/number.txt'") .addTool(CodeExecutionTool20250825.builder().build()) .build(); Message response1 = client.messages().create(params1); String containerId = response1.container().get().id(); MessageCreateParams params2 = MessageCreateParams.builder() .container(containerId) .model(Model.CLAUDE_OPUS_4_7) .maxTokens(4096L) .addUserMessage("Read the number from '/tmp/number.txt' and calculate its square") .addTool(CodeExecutionTool20250825.builder().build()) .build(); Message response2 = client.messages().create(params2); System.out.println(response2); ``` -------------------------------- ### Connecting to Multiple MCP Servers Source: https://platform.claude.com/docs/en/agents-and-tools/mcp-connector Example configuration for connecting to and utilizing tools from multiple MCP servers simultaneously. Each server requires a definition in 'mcp_servers' and a corresponding 'mcp_toolset' in the 'tools' array. ```json { "model": "claude-opus-4-7", "max_tokens": 1000, "messages": [ { "role": "user", "content": "Use tools from both mcp-server-1 and mcp-server-2 to complete this task" } ], "mcp_servers": [ { "type": "url", "url": "https://mcp.example1.com/sse", "name": "mcp-server-1", "authorization_token": "TOKEN1" }, { "type": "url", "url": "https://mcp.example2.com/sse", "name": "mcp-server-2", "authorization_token": "TOKEN2" } ], "tools": [ { "type": "mcp_toolset", "mcp_server_name": "mcp-server-1" }, { "type": "mcp_toolset", "mcp_server_name": "mcp-server-2", "default_config": { "defer_loading": true } } ] } ``` -------------------------------- ### Usage Iterations JSON Structure Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool Example of the usage object containing iterations for both executor and advisor messages. ```json { "usage": { "input_tokens": 412, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0, "output_tokens": 531, "iterations": [ { "type": "message", "input_tokens": 412, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0, "output_tokens": 89 }, { "type": "advisor_message", "model": "claude-opus-4-7", "input_tokens": 823, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0, "output_tokens": 1612 }, { "type": "message", "input_tokens": 1348, "cache_read_input_tokens": 412, "cache_creation_input_tokens": 0, "output_tokens": 442 } ] } } ``` -------------------------------- ### Represent a tool use block Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview Example of the JSON structure returned by Claude when it decides to invoke a tool. ```json { "type": "tool_use", "id": "toolu_01A09q90qw90lq917835lq9", "name": "get_weather", "input": { "location": "New York, NY", "unit": "fahrenheit" } } ``` -------------------------------- ### Python: Self-Documenting Configuration Constants Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices This Python code demonstrates good practice for configuration parameters by using self-documenting constants with comments explaining their justification. ```python # HTTP requests typically complete within 30 seconds # Longer timeout accounts for slow connections REQUEST_TIMEOUT = 30 # Three retries balances reliability vs speed # Most intermittent failures resolve by the second retry MAX_RETRIES = 3 ``` -------------------------------- ### Extract PDF text with pdfplumber Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices A concise example demonstrating text extraction from a PDF using the pdfplumber library. ```python import pdfplumber with pdfplumber.open("file.pdf") as pdf: text = pdf.pages[0].extract_text() ``` -------------------------------- ### Enable All Tools with Default Configuration Source: https://platform.claude.com/docs/en/agents-and-tools/mcp-connector A simple configuration to enable all tools from a specified server without any specific overrides. ```json { "type": "mcp_toolset", "mcp_server_name": "google-calendar-mcp" } ``` -------------------------------- ### Build a streaming chat UI Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/claude-api-skill Example task for building a chat interface using the Claude API in TypeScript. ```text Build a streaming chat UI with the Claude API in TypeScript ``` -------------------------------- ### Execute Code and Read File in Ruby Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool This Ruby example demonstrates writing a file with a random number and subsequently reading it to calculate its square using the code execution tool. ```Ruby require "anthropic" client = Anthropic::Client.new response1 = client.messages.create( model: "claude-opus-4-7", max_tokens: 4096, messages: [ { role: "user", content: "Write a file with a random number and save it to '/tmp/number.txt'" } ], tools: [ { type: "code_execution_20250825", name: "code_execution" } ] ) container_id = response1.container.id response2 = client.messages.create( container: container_id, model: "claude-opus-4-7", max_tokens: 4096, messages: [ { role: "user", content: "Read the number from '/tmp/number.txt' and calculate its square" } ], tools: [ { type: "code_execution_20250825", name: "code_execution" } ] ) puts response2.content ```