Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Tool use patterns for Claude including schema design, tool_choice modes, result handling, parallel execution, error recovery, and extended thinking integration.
.claude/skills/majiayu000-tool-use/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-17 | ✗→✓ | ▲ Improved | 427% | 0% |
| case-07 | ✗→✓ | ▲ Improved | 345% | 0% |
| case-09 | ✗→✓ | ▲ Improved | 163% | 0% |
| case-11 | ✗→✓ | ▲ Improved | 216% | 0% |
| case-14 | ✗→✓ | ▲ Improved | 381% | 0% |
Comprehensive guide to implementing tool use with Claude, covering schema design, tool choice modes, multi-turn conversations, error handling patterns, and advanced features like extended thinking and strict schema conformance.
Activate this skill when:
Every tool requires a JSON Schema input definition with:
^[a-zA-Z0-9_-]{1,64}$)json{ "name": "get_stock_price", "description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. Use this when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company beyond the price.", "input_schema": { "type": "object", "properties": { "ticker": { "type": "string", "description": "The stock ticker symbol, e.g. AAPL for Apple Inc. Must be uppercase." }, "include_historical": { "type": "boolean", "description": "Optional. Whether to include 52-week high/low prices.", "default": false } }, "required": ["ticker"], "additionalProperties": false }, "input_examples": [ {"ticker": "AAPL"}, {"ticker": "MSFT", "include_historical": true}, {"ticker": "GOOGL"} ] }
Key Guidelines:
input_examples for complex nested objects or format-sensitive parametersadditionalProperties: false for strict validationControl how Claude decides whether and how to use tools:
| Mode | Behavior | Use Case | |------|----------|----------| | "auto" | Claude decides to use tools or not (default) | General tool use, letting Claude decide | | "any" | Claude must use one tool but can choose which | Forcing tool use without specific tool | | "tool" | Force specific tool (e.g., {"type": "tool", "name": "get_weather"}) | Structured JSON output, specific tool required | | "none" | Prevent all tool use | Normal text-only responses |
python# Allow Claude to decide # tool_choice="auto" (default) # Force any tool to be used tool_choice={"type": "any"} # Force specific tool (useful for JSON output) tool_choice={"type": "tool", "name": "record_summary"} # Prevent tool use tool_choice={"type": "none"}
Important Constraints with Extended Thinking:
tool_choice: {"type": "auto"} or {"type": "none"}{"type": "any"} or {"type": "tool"} with extended thinkingEnable guaranteed schema validation with strict: true:
pythontools=[{ "name": "search_flights", "strict": True, # Enable strict mode "input_schema": { "type": "object", "properties": { "destination": {"type": "string"}, "departure_date": {"type": "string", "format": "date"}, "passengers": {"type": "integer"} }, "required": ["destination", "departure_date"], "additionalProperties": False } }]
Benefits:
"2" instead of 2)Limitations:
structured-outputs-2025-11-13 beta headerBasic pattern: Define tool → Claude calls tool → Return result → Claude responds
pythonimport anthropic client = anthropic.Anthropic() response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[{ "name": "get_weather", "description": "Get current weather in a location", "input_schema": { "type": "object", "properties": { "location": { "type": "string", "description": "City and state, e.g. San Francisco, CA" } }, "required": ["location"] } }], messages=[{"role": "user", "content": "What's the weather in SF?"}] ) # Check if Claude wants to use tool if response.stop_reason == "tool_use": tool_use = next(b for b in response.content if b.type == "tool_use") print(f"Tool: {tool_use.name}") print(f"Input: {tool_use.input}") # Execute tool (simulate) tool_result = "68°F, partly cloudy" # Return result to Claude response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], # Same tools messages=[ {"role": "user", "content": "What's the weather in SF?"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use.id, "content": tool_result }]} ] ) print(response.content[0].text)
Tools often require sequential calls where one tool's output feeds into another:
python# User asks: "What's the weather where I am?" # Flow: get_location() → get_weather(location) response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[ { "name": "get_location", "description": "Get user's location from IP address", "input_schema": {"type": "object", "properties": {}} }, { "name": "get_weather", "description": "Get weather for location", "input_schema": { "type": "object", "properties": { "location": {"type": "string"} }, "required": ["location"] } } ], messages=[{"role": "user", "content": "What's the weather where I am?"}] ) # Claude calls get_location first tool_use = next(b for b in response.content if b.type == "tool_use") location_result = "San Francisco, CA" # Send location result back response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], messages=[ {"role": "user", "content": "What's the weather where I am?"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use.id, "content": location_result }]} ] ) # Claude now calls get_weather with the location tool_use2 = next(b for b in response.content if b.type == "tool_use") weather_result = "68°F, sunny" # Final result response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], messages=[ {"role": "user", "content": "What's the weather where I am?"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use.id, "content": location_result }]}, {"role": "assistant", "content": response.content}, {"role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use2.id, "content": weather_result }]} ] ) print(response.content[0].text)
Claude can call multiple independent tools simultaneously:
pythonresponse = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], messages=[{ "role": "user", "content": "What's the weather in SF and NYC? What time is it there?" }] ) # Claude makes 4 parallel tool calls (2 weather + 2 time) tool_uses = [b for b in response.content if b.type == "tool_use"] print(f"Parallel calls: {len(tool_uses)}") # 4 # Execute all tools and collect results tool_results = [] for tool_use in tool_uses: if tool_use.name == "get_weather": if "San Francisco" in str(tool_use.input): result = "68°F, partly cloudy" else: result = "45°F, clear" else: # get_time if "Los_Angeles" in str(tool_use.input): result = "2:30 PM PST" else: result = "5:30 PM EST" tool_results.append({ "type": "tool_result", "tool_use_id": tool_use.id, "content": result }) # IMPORTANT: Return all results in ONE user message response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[...], messages=[ {"role": "user", "content": "What's the weather in SF and NYC? What time is it there?"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": tool_results} # All results together! ] ) print(response.content[0].text)
Critical Formatting Rules for Parallel Tools:
python{ "type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9", "content": "15 degrees" }
python{ "type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9", "content": [ {"type": "text", "text": "Current weather screenshot:"}, { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "/9j/4AAQSkZJRg..." } } ] }
python{ "type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9", "content": [ {"type": "text", "text": "Document content:"}, { "type": "document", "source": { "type": "text", "media_type": "text/plain", "data": "Full document content here" } } ] }
python# Tool execution error { "type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9", "content": "ConnectionError: Weather API is unavailable (HTTP 500)", "is_error": True } # Missing parameter error { "type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9", "content": "Error: Missing required 'location' parameter", "is_error": True }
When tool execution fails, report error and Claude retries with corrections:
pythonif tool_execution_failed: tool_result = { "type": "tool_result", "tool_use_id": tool_use.id, "content": f"Error: {error_message}", "is_error": True }
Claude typically retries 2-3 times before apologizing to the user.
With strict: true, invalid parameters are prevented before execution:
python# With strict: true, Claude CANNOT send invalid parameters # Invalid type: "passengers": "two" → prevented by schema # Missing required field → prevented by schema # Type mismatch: int vs string → prevented by schema
If response is cut off during tool use, retry with higher limit:
pythonif response.stop_reason == "max_tokens": last_block = response.content[-1] if last_block.type == "tool_use": # Incomplete tool use, retry with more tokens response = client.messages.create( model="claude-sonnet-4-5", max_tokens=4096, # Increased messages=messages, tools=tools )
Use tools to guarantee structured JSON output without tool execution:
pythonresponse = client.beta.messages.create( model="claude-sonnet-4-5", max_tokens=1024, betas=["structured-outputs-2025-11-13"], tools=[{ "name": "record_summary", "description": "Record structured image summary", "input_schema": { "type": "object", "properties": { "key_colors": { "type": "array", "items": { "type": "object", "properties": { "r": {"type": "number"}, "g": {"type": "number"}, "b": {"type": "number"}, "name": {"type": "string"} }, "required": ["r", "g", "b", "name"] } }, "description": {"type": "string"}, "estimated_year": {"type": "integer"} }, "required": ["key_colors", "description"] } }], tool_choice={"type": "tool", "name": "record_summary"}, messages=[{ "role": "user", "content": [ {"type": "image", "source": {"type": "url", "url": "https://..."}}, {"type": "text", "text": "Describe this image"} ] }] ) # Extract structured output from tool use input tool_use = next(b for b in response.content if b.type == "tool_use") structured_data = tool_use.input
Add to system prompt for stronger parallel tool use:
text<use_parallel_tool_calls> For maximum efficiency, whenever you perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially. Prioritize calling tools in parallel whenever possible. When reading 3 files, run 3 tool calls in parallel. When running multiple commands like 'ls' or 'list_dir', always run all commands in parallel. </use_parallel_tool_calls>
pythondef measure_parallel_efficiency(messages): # Find assistant messages with tool use tool_call_messages = [ msg for msg in messages if msg.get("role") == "assistant" and any(b.get("type") == "tool_use" for b in msg.get("content", [])) ] total_tools = sum( len([b for b in msg.get("content", []) if b.get("type") == "tool_use"]) for msg in tool_call_messages ) if not tool_call_messages: return 0 avg_per_message = total_tools / len(tool_call_messages) print(f"Average tools per message: {avg_per_message}") # > 1.0 indicates parallel tool use working
python# ✅ ALLOWED with extended thinking response = client.messages.create( model="claude-opus-4-5", thinking={"type": "enabled", "budget_tokens": 2048}, tools=[...], tool_choice={"type": "auto"}, # Default messages=[...] ) # ✅ ALLOWED with extended thinking tool_choice={"type": "none"} # No tools # ❌ NOT ALLOWED with extended thinking # tool_choice={"type": "any"} → Error # tool_choice={"type": "tool", "name": "..."} → Error
When you need extended reasoning with tool use, use the "think" tool:
pythontools=[{ "name": "think", "description": "Pause and think carefully before proceeding", "input_schema": { "type": "object", "properties": { "reasoning": { "type": "string", "description": "Your detailed reasoning" } }, "required": ["reasoning"] } }, { "name": "get_weather", "description": "Get weather information", "input_schema": {...} }]
Python and TypeScript SDKs provide tool runners for automatic tool execution:
pythonimport anthropic from anthropic import beta_tool client = anthropic.Anthropic() @beta_tool def get_weather(location: str, unit: str = "fahrenheit") -> str: """Get current weather in a location. Args: location: City and state, e.g. San Francisco, CA unit: Temperature unit, either 'celsius' or 'fahrenheit' """ # Tool implementation return '{"temperature": "20°C", "condition": "Sunny"}' # Tool runner automatically handles tool execution loop runner = client.beta.messages.tool_runner( model="claude-sonnet-4-5", max_tokens=1024, tools=[get_weather], messages=[{"role": "user", "content": "What's the weather in Paris?"}] ) # Iterate through responses for message in runner: print(message.content[0].text) # Or get final message directly final_message = runner.until_done()
enum for constrained valuesconst for fixed valuesanyOf, allOf for complex types$ref, $def, definitions for schema compositionminItems (0 and 1 only)$ref (e.g., HTTP URLs)additionalProperties as anything other than falsepythontools=[{ "name": "extract_info", "description": "Extract structured data from text", "input_schema": { "type": "object", "properties": { "name": {"type": "string"}, "email": {"type": "string"}, "company": {"type": "string"} }, "required": ["name", "email"] } }]
pythontools=[{ "name": "search_api", "description": "Search external API", "input_schema": { "type": "object", "properties": { "query": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 100} }, "required": ["query"] } }]
pythontools=[ {"name": "validate_input", ...}, {"name": "process_data", ...}, {"name": "save_result", ...} ] # Claude orchestrates the workflow
Tool use can quickly consume context in long conversations. Strategies:
Use tool_choice to force specific behavior:
python# Force use of a tool (for JSON output) response = client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=[sentiment_tool], tool_choice={"type": "tool", "name": "sentiment_tool"}, messages=[{"role": "user", "content": "Analyze this text..."}] ) # No prefilled explanations with forced tool_choice # Claude goes straight to tool use # For explanations WITH tool use, use tool_choice="auto" (default) # and add instruction: "Use the sentiment_tool in your response"
tool_useClaude wants to use a tool. Extract tool use blocks and execute tools.
end_turnClaude finished generating response. No more tool calls.
max_tokensResponse cut off. If last block is incomplete tool_use, retry with higher max_tokens.
pause_turn (with server tools)Long operation paused. Continue the conversation to resume.
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-17 | fail→pass | 13,027 | 6,850 | -47% | 1 | 1 | 0% | 1,387 | 7,308 | +427% | 0 | 0 | — |
case-02 | fail→fail | 21,626 | 16,021 | -26% | 1 | 1 | 0% | 4,204 | 8,169 | +94% | 0 | 0 | — |
case-03 | pass→fail | 12,317 | 9,335 | -24% | 1 | 1 | 0% | 2,040 | 7,546 | +270% | 0 | 0 | — |
case-04 | pass→pass | 15,707 | 12,568 | -20% | 1 | 1 | 0% | 2,080 | 7,458 | +259% | 0 | 0 | — |
case-01 | fail→fail | 15,763 | 26,417 | +68% | 1 | 1 | 0% | 3,676 | 9,992 | +172% | 0 | 0 | — |
case-05 | pass→pass | 16,318 | 16,487 | +1% | 1 | 1 | 0% | 2,215 | 8,350 | +277% | 0 | 0 | — |
case-06 | pass→pass | 9,740 | 13,363 | +37% | 1 | 1 | 0% | 2,052 | 7,669 | +274% | 0 | 0 | — |
case-07 | fail→pass | 14,143 | 11,969 | -15% | 1 | 1 | 0% | 1,631 | 7,258 | +345% | 0 | 0 | — |
case-08 | pass→pass | 10,639 | 9,377 | -12% | 1 | 1 | 0% | 1,902 | 7,917 | +316% | 0 | 0 | — |
case-09 | fail→pass | 26,357 | 21,745 | -17% | 1 | 1 | 0% | 3,788 | 9,979 | +163% | 0 | 0 | — |
case-10 | pass→pass | 14,109 | 5,930 | -58% | 1 | 1 | 0% | 1,750 | 6,976 | +299% | 0 | 0 | — |
case-11 | fail→pass | 13,807 | 9,642 | -30% | 1 | 1 | 0% | 2,158 | 6,809 | +216% | 0 | 0 | — |
case-12 | pass→pass | 5,294 | 9,504 | +80% | 1 | 1 | 0% | 944 | 6,749 | +615% | 0 | 0 | — |
case-13 | pass→pass | 20,120 | 10,676 | -47% | 1 | 1 | 0% | 3,502 | 7,953 | +127% | 0 | 0 | — |
case-14 | fail→pass | 13,471 | 12,907 | -4% | 1 | 1 | 0% | 1,445 | 6,954 | +381% | 0 | 0 | — |
case-15 | fail→pass | 27,466 | 8,675 | -68% | 1 | 1 | 0% | 4,015 | 6,699 | +67% | 0 | 0 | — |
case-16 | pass→pass | 8,853 | 6,556 | -26% | 1 | 1 | 0% | 1,825 | 7,377 | +304% | 0 | 0 | — |
case-18 | fail→pass | 15,467 | 8,925 | -42% | 1 | 1 | 0% | 1,822 | 6,646 | +265% | 0 | 0 | — |
case-19 | fail→pass | 9,462 | 12,615 | +33% | 1 | 1 | 0% | 1,608 | 7,082 | +340% | 0 | 0 | — |
case-20 | fail→pass | 30,958 | 9,962 | -68% | 1 | 1 | 0% | 4,692 | 7,049 | +50% | 0 | 0 | — |
case-21 | fail→pass | 18,582 | 11,943 | -36% | 1 | 1 | 0% | 2,160 | 7,264 | +236% | 0 | 0 | — |
case-22 | pass→pass | 8,898 | 7,782 | -13% | 1 | 1 | 0% | 642 | 6,505 | +913% | 0 | 0 | — |
case-23 | fail→pass | 10,223 | 7,008 | -31% | 1 | 1 | 0% | 2,028 | 7,378 | +264% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 23 cases were attempted. The headline lift of +43 percentage points is the difference between those two pass rates over the 23 comparable cases. 1 case got worse with the skill loaded, and it is included in that figure.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.