Claude · Tool use and structured outputs
A model that can only emit text is a dead end once you need it to check a live database, hit an APIAPIApplication Programming Interface: a standardised interface that lets applications communicate and exchange data without knowing each other's internal workings.View full definition →, or hand clean JSON to the next service in your pipelinepipelineAll active sales opportunities across the stages of the sales process, together with their combined potential value and probability of closing.View full definition →. Tool use and structured outputs close that gap with Claude. You describe capabilities, Claude decides when to invoke them, and you get back data your code can consume.
This lesson covers both mechanics on the Anthropic Messages API. You will see the request and response shapes you send and parse, and how the two techniques relate.
What "tool use" actually means
Tool use (sometimes called function calling) is a protocol. Claude never runs your code. You hand it a list of tool definitions. Each has a name, a description, and a JSON SchemaSchemaA schema is the formal blueprint that defines how data is structured, named, typed, and related within a database, file, or message.View full definition → for its inputs.
When Claude decides a tool would help, it stops writing prose and emits a structured request, for example: "call get_weather with {"location": "Paris"}." Your application runs that function and sends the result back. Then Claude continues.
That back and forth is the tool-use loop. Once you understand it, the rest of this lesson follows.
The four steps of the loop
- You send a user message plus your
toolsarray. - Claude responds with
stop_reason: "tool_use"and atool_usecontent block. - You execute the tool and send the answer back as a
tool_result. - Claude reads the result and produces its final text answer.
A concrete get_weather loop
Here is the full loop in Python with the official SDK. Read it once, then we will break down each shape.
import anthropic
client = anthropic.Anthropic()
tools = [{
"name": "get_weather",
"description": "Get current temperature for a given city.",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name, e.g. 'Paris'"}
},
"required": ["location"],
},
}]
def get_weather(location):
# In real life, call a weather API here.
return {"location": location, "temp_c": 14, "conditions": "cloudy"}
messages = [{"role": "user", "content": "What's the weather in Paris right now?"}]
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=tools,
messages=messages,
)
# Step 2: Claude asked for a tool.
if response.stop_reason == "tool_use":
tool_call = next(b for b in response.content if b.type == "tool_use")
result = get_weather(**tool_call.input)
# Step 3: append Claude's request AND your result.
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_call.id,
"content": str(result),
}],
})
# Step 4: Claude reads the result and writes the answer.
final = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=tools,
messages=messages,
)
print(final.content[0].text)The examples use claude-sonnet-4-5. Any current Claude model ID from the models overview works the same way.
Reading the response shape
When Claude wants a tool, response.content is a list of blocks. The relevant one looks like this:
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "get_weather",
"input": {"location": "Paris"}
}Three fields matter:
nametells you which function to run.inputis already a parsed object matching your schema, so there is no string parsing to do.- `id` is the handle you must echo back.
Sending the result back
The detail people miss: you must append two messages, in this order.
- Claude's own assistant turn: the full
response.content, including thetool_useblock. - A user turn carrying the
tool_result.
The tool_use_id in your result must exactly match the id Claude sent, or the loop breaks.
If your tool fails, set "is_error": true in the result block. Claude will see the error. It can then apologize, retry with different inputs, or pick another tool.
Multiple tools and parallel calls
You rarely ship one tool. Pass several in the tools array and Claude routes to the right one based on the descriptions.
Write those descriptions like documentation, because they are the only thing Claude uses to decide. "Get current temperaturetemperatureA setting that controls how random or predictable an AI model's output is: low keeps it safe and consistent, high makes it more varied and creative.View full definition → for a given city" beats "weather tool" every time.
Claude can also request several tools in a single turn (parallel tool use). When that happens, response.content contains multiple tool_use blocks. Run them all. Then return all the tool_result blocks together in one user message before calling the API again.
Claude may chain several tools before it is done. To handle that, wrap the call in a while response.stop_reason == "tool_use" loop instead of a single if.
Structured outputs: getting clean JSON back
Tool use solves "do something." Structured outputs solve "give me data in an exact shape." Say you are extracting fields from a support email. You need {"category": ..., "urgency": ..., "summary": ...} every single time, with no prose and no markdown fences.
Since November 2025, the Messages API has native structured outputs. It comes in two forms:
- JSON outputs. You pass a JSON Schema as the response format, and Claude's text answer is guaranteed to parse and match it.
- Strict tool use. You add
"strict": trueto a tool definition, and everytool_useinput is guaranteed to match that tool'sinput_schema.
Both use constrained decoding. The model cannot emit tokenstokensA token is the basic unit of text that language models process, often a word fragment, whole word, or punctuation mark rather than a single character.View full definition → that would break your schema, so you no longer need retry-on-bad-JSON logic.
import json
import anthropic
client = anthropic.Anthropic()
ticket_schema = {
"type": "object",
"properties": {
"category": {"type": "string", "enum": ["billing", "bug", "feature", "other"]},
"urgency": {"type": "string", "enum": ["low", "medium", "high"]},
"summary": {"type": "string", "description": "One sentence."},
},
"required": ["category", "urgency", "summary"],
"additionalProperties": False,
}
email = "I was charged twice this month and need this fixed before Friday!"
response = client.beta.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
betas=["structured-outputs-2025-11-13"],
output_format={"type": "json_schema", "schema": ticket_schema},
messages=[{"role": "user", "content": email}],
)
ticket = json.loads(response.content[0].text)
print(ticket)
# {'category': 'billing', 'urgency': 'high', 'summary': 'Customer charged twice and wants a fix by Friday.'}The feature launched as a beta with the header shown above. Check the docs for the current parameter names and which models support it, since beta APIs can change shape when they become generally available.
The Python and TypeScript SDKs can also take a Pydantic or Zod model and convert it to a schema for you.
The enum constraints do real work here. With constrained decoding, Claude cannot invent a fourth urgency level. Tighten your schema and you tighten your outputs.
Some schema features are not supported, such as certain numeric bounds and complex recursive definitions. The first request with a new schema also carries some extra latency while the grammar compiles, after which the compiled grammar is cached.
The forced-tool pattern
Before native structured outputs existed, the standard trick was to define a tool that represents your output and force Claude to call it. You will see it in plenty of existing code. It still works, and adding "strict": true makes it guaranteed.
extract_tool = {
"name": "record_ticket",
"description": "Record the structured fields of a support ticket.",
"strict": True,
"input_schema": ticket_schema,
}
response = client.beta.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
betas=["structured-outputs-2025-11-13"],
tools=[extract_tool],
tool_choice={"type": "tool", "name": "record_ticket"},
messages=[{"role": "user", "content": email}],
)
ticket = next(b.input for b in response.content if b.type == "tool_use")The tool_choice parameter is the lever. Setting it to {"type": "tool", "name": "record_ticket"} forces that exact call. You never run a function here. You just read b.input.
Other tool_choice values:
{"type": "auto"}(default): Claude decides whether to use a tool.{"type": "any"}: Claude must use *some* tool but picks which.{"type": "tool", "name": "..."}: force one specific tool, as above.{"type": "none"}: no tool calls this turn.
As a rule of thumb, use JSON outputs when you want Claude's answer itself in a fixed shape. Use strict tools when Claude is calling real functions in an agent and a malformed argument would break something.
The tool use guide is the authoritative reference for schema edge cases and streaming.
Claude Tool Use Explained
Knowledge check
1. In the tool-use protocol described, what actually happens when Claude 'uses' a tool?
2. Why are tool use and structured outputs valuable when integrating Claude into a software pipeline?
3. After you send a tool_result back to Claude, what happens in the final step of the tool-use loop?
4. Select ALL elements that a single tool definition must include when you send your tools array to Claude.
Select all the correct answers.
5. Select ALL statements that correctly describe how the tool-use loop behaves.
Select all the correct answers.
How this connects to MCPMCPAn open standard that lets AI assistants connect to your company's tools and data in a consistent, governed way, instead of one custom integration at a time.View full definition → and the Agent SDK
Everything above is the raw API. You define tools inline and run them yourself. That is perfect for a handful of bespoke tools inside one service.
You will quickly want reusable tools that any Claude surface can call, such as the desktop app, Claude Code, or your own agent. MCP (Model Context Protocol) standardizes this.
An MCP server exposes tools (plus resources and prompts) over a defined protocol. You write a tool once and plug it into many clients. The Claude apps surface these as Connectors, and there is a connector directory for common ones like Google Drive or GitHub.
MCP tools and API tools are the same idea at different scopes. An MCP server's tool list ultimately becomes entries in a tools array, and the call/result handshake mirrors the loop you just learned. Learn the protocol at modelcontextprotocol.io.
The Claude Agent SDK sits one level higher. It runs the tool-use loop for you, manages context, and handles multi-step agent behavior. You describe tools and goals rather than hand-coding the while stop_reason == "tool_use" machinery.
When you build a real agent, reachreachThe number of unique people exposed to your message in a given period. Unlike impressions, reach counts each person once, no matter how often they see it.View full definition → for the SDK. When you need precise control over a single exchange, drop to the Messages API as shown above. Both use the same tool-use protocol, which is why learning the raw loop pays off.
Practical gotchas
A few things that will bite you in production:
- Token budget. Tool definitions live in the context windowcontext windowThe context window is the maximum amount of text (measured in tokens) a language model can process at once, including both the input prompt and the generated output.View full definition →, so twenty verbose tools cost real tokens on every call. Keep schemas lean and descriptions sharp.
- Validate the values anyway. Strict mode guarantees the shape, not the meaning. A schema-valid
{"user_id": "1 OR 1=1"}is still dangerous. Treatinputlike untrusted user input: check ranges, sanitize, and authorize before you hit a database. - Forced tools skip the reasoning. When you force
tool_choiceto a specific tool, Claude jumps straight to the call, and forced tool choice is not compatible with extended thinking. If you need reasoning first, leave it onauto, use JSON outputs, or split the work into two calls. - Errors are signal, not failure. Returning
is_error: truewith a useful message often lets Claude self-correct on the next turn. That is better than crashing your loop.
Key Takeaways
- Tool use is a four-step loop. Send tools, receive a
tool_useblock, run the function, and return atool_resultwith the matchingtool_use_id. Echo Claude's assistant turn back before the result, or the loop breaks. - For guaranteed JSON, use native structured outputs. Use a
json_schemaoutput format for the answer itself, or"strict": trueon tools. Constrained decoding means the schema always holds. The older forced-tool pattern still works. - Write tool descriptions like docs. Claude uses them to route, so make them specific.
- Validate tool inputs in your code. A valid shape does not mean a safe value. Claude proposes; your application executes.
- Scale up deliberately. Use the raw Messages API for one bespoke exchange, MCP for reusable cross-app tools, and the Agent SDK when you want the loop managed for you. All three use the same protocol.
What to do, from this lesson
These actions are compiled in the role's Playbook.
- Force a tool schema when you need guaranteed parsed JSON