This prompt template is for engineering teams building tool-using AI systems with Anthropic's Claude models. Use it when you need Claude to reliably select and call external tools by embedding tool definitions in Anthropic's expected XML structure. The template wraps tool schemas, argument descriptions, and usage examples into a single system prompt that enforces schema compliance and predictable tool-call parsing. It belongs in the prompt assembly layer before any user input is added, serving as the foundation for single-turn tool selection and argument population.
Prompt
Anthropic Tool Use XML Prompt Template

When to Use This Prompt
Defines the job-to-be-done, ideal user, required context, and boundaries for the Anthropic Tool Use XML Prompt Template.
The ideal user is a developer or AI engineer who already has tool definitions ready and needs a production-grade prompt that produces parseable tool calls. You should have your tool schemas defined with clear names, descriptions, and parameter types before using this template. The prompt expects you to populate placeholders for tool definitions in Anthropic's XML format, optional few-shot examples, and output constraints. It works best for single-step tool selection where one tool call is expected per turn, not for multi-step agent workflows that require planning prompts layered on top of tool selection.
Do not use this template for OpenAI function calling, which requires a different JSON schema format and tool call structure. Avoid it for multi-step agent workflows that need planning, reflection, or tool call sequencing prompts layered on top. It is not designed for dynamic tool discovery where available tools change mid-session without prompt reassembly. If your use case involves parallel tool calls, user confirmation before execution, or tool call retry with error context, pair this template with the specialized sibling prompts in the Tool Schema and Function Definition Integration group rather than trying to overload this single template.
Use Case Fit
Where the Anthropic Tool Use XML Prompt Template works well and where it introduces risk. Use these cards to decide if this pattern fits your production context.
Good Fit: Claude-Only Tool Calling
Use when: your application exclusively uses Anthropic Claude models and you need fine-grained control over tool definitions. Why: the XML format aligns with Claude's native tool-use training, reducing schema misinterpretation compared to generic JSON function-calling prompts.
Bad Fit: Multi-Provider Architectures
Avoid when: your system routes tool calls across OpenAI, Gemini, or open-weight models. Risk: XML-wrapped tool schemas are Anthropic-specific; other providers expect JSON function-calling formats. Guardrail: use a provider-agnostic schema normalization layer and adapt at assembly time rather than forcing XML everywhere.
Required Input: Complete Tool Definitions
What to watch: missing argument descriptions, vague tool names, or absent usage examples cause the model to hallucinate parameters or select the wrong tool. Guardrail: validate that every tool definition includes a clear name, description, required parameter list with types, and at least one usage example before assembly.
Operational Risk: Schema Drift at Runtime
What to watch: tool schemas change in your backend but the prompt template still references stale definitions. Risk: the model emits calls with deprecated arguments or missing required fields. Guardrail: version your tool schemas alongside prompt templates and add preflight validation that checks schema freshness before inference.
Good Fit: High-Stakes Argument Discipline
Use when: tool calls involve financial transactions, provisioning, or destructive operations where argument correctness is critical. Why: the XML structure encourages explicit parameter documentation and usage examples, which improves argument population accuracy compared to terse JSON schemas alone.
Operational Risk: Token Budget Bloat
What to watch: XML tool definitions with verbose descriptions and multiple examples consume significant context window space. Risk: reduced room for conversation history, retrieved evidence, or user input, leading to truncated context or higher costs. Guardrail: monitor token allocation per tool definition and compress descriptions without losing argument clarity; consider dynamic schema injection to include only relevant tools.
Copy-Ready Prompt Template
A reusable system prompt that wraps tool definitions in Anthropic's expected XML structure with argument descriptions, usage examples, and output constraints.
This template assembles tool definitions into the XML format Claude expects for tool use. Inject it before the user message in your prompt assembly pipeline. The structure enforces argument discipline, provides usage examples, and constrains output to valid tool calls or clarification requests. Replace each square-bracket placeholder with your actual tool definitions, constraints, and risk policies before sending to the model.
xml<system> You are an AI assistant with access to the following tools. Use them when they help complete the user's task. Do not invent tools or capabilities not listed below. <tools> [TOOLS] </tools> <tool_use_rules> 1. Select the most appropriate tool for the user's request. If multiple tools could apply, choose the one that requires fewer assumptions. 2. Populate all required arguments. If a required argument is missing and cannot be reasonably inferred, ask the user for clarification instead of guessing. 3. Use the exact argument types specified in each tool definition. Do not pass strings where numbers are expected, or vice versa. 4. For [RISK_LEVEL] operations, explain what will happen and wait for user confirmation before executing. 5. If a tool call fails, read the error message and correct your next attempt. Do not retry more than [MAX_RETRIES] times without escalating. 6. After receiving tool output, synthesize a clear response for the user. Do not expose raw error stacks or internal identifiers unless the user asks for debugging details. </tool_use_rules> <output_format> Respond with a tool call in this XML structure when using a tool: <function_calls> <invoke name="tool_name"> <parameter name="param1">value1</parameter> <parameter name="param2">value2</parameter> </invoke> </function_calls> When asking the user for clarification, respond in plain text explaining what information you need and why. </output_format> <constraints> [CONSTRAINTS] </constraints> <examples> [EXAMPLES] </examples> </system>
Adapting the template: Replace [TOOLS] with one or more <tool_description> blocks, each containing a <name>, <description>, <parameters> with typed <parameter> entries, and optional <example> usage. Set [RISK_LEVEL] to high-risk, destructive, irreversible, or all depending on your confirmation policy. [MAX_RETRIES] should be a small integer, typically 2 or 3. Use [CONSTRAINTS] to add domain-specific rules such as prohibited argument combinations, rate limits, or data handling requirements. Populate [EXAMPLES] with 2-4 few-shot demonstrations showing correct tool selection, argument population, clarification requests, and error recovery.
Validation and testing: Before deploying, validate that every tool definition in [TOOLS] includes a name, description, and typed parameters with required/optional flags. Test with inputs that should trigger each tool, inputs where multiple tools could apply, inputs with missing required arguments, and inputs that should produce no tool call. Run eval checks for correct tool selection, argument type adherence, appropriate clarification requests, and refusal of out-of-policy actions. For high-risk domains, require human review of tool call logs during the first [N] production hours.
What to avoid: Do not omit the <tool_use_rules> block—without explicit rules, Claude may invent tools, skip required arguments, or execute high-risk actions without confirmation. Do not use this template with non-Anthropic models without adapting the XML structure to their expected format. Do not set [MAX_RETRIES] to 0 unless you want the model to give up on the first failure without correction. Do not skip <examples> when introducing new or ambiguous tools; few-shot demonstrations significantly improve selection accuracy.
Prompt Variables
Required inputs for the Anthropic Tool Use XML prompt template. Each placeholder must be populated before assembly. Validation checks prevent malformed tool definitions and argument errors at runtime.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TOOL_NAME] | Unique identifier for the tool the model can invoke | get_weather | Must match regex ^[a-zA-Z0-9_-]+$. No spaces. Must be unique across all tools in the prompt. |
[TOOL_DESCRIPTION] | Natural language description of what the tool does and when to use it | Retrieves current weather conditions for a given city and country | Must be 1-3 sentences. Should include selection cues to disambiguate from similar tools. Null not allowed. |
[PARAMETER_NAME] | Name of a single input parameter the tool accepts | city | Must match regex ^[a-zA-Z0-9_-]+$. Required parameters must be listed before optional ones. No duplicate names within a tool. |
[PARAMETER_TYPE] | Data type of the parameter as expected by the tool | string | Must be one of: string, number, boolean, object, array. Use JSON Schema type names. Null not allowed. |
[PARAMETER_DESCRIPTION] | What the parameter represents and any format constraints | City name, e.g. 'San Francisco' | Must describe expected format if type alone is ambiguous. Include enum values here if applicable. Null not allowed. |
[PARAMETER_REQUIRED] | Whether the model must provide this argument | Must be true or false. At least one parameter should be required unless the tool takes no arguments. Schema check: required array must match. | |
[EXAMPLE_USER_QUERY] | A realistic user message that should trigger this tool | What's the weather in Tokyo? | Must be a plausible natural language query. Used for few-shot conditioning. Include 1-3 examples per tool. Null allowed if no examples provided. |
[EXAMPLE_TOOL_CALL] | The correct XML tool call block for the example query | <function_calls> <invoke name="get_weather"> <parameter name="city">Tokyo</parameter> </invoke> </function_calls> | Must be valid Anthropic XML tool call format. Parse check: XML well-formedness. Schema check: all required params present, types match, no hallucinated parameters. |
Implementation Harness Notes
How to wire the Anthropic Tool Use XML prompt into a production application with validation, retries, and observability.
This prompt template is designed to be assembled at runtime by an application layer, not pasted once into a static system prompt. The application is responsible for injecting the correct tool definitions, user input, and context into the XML structure before each API call. The core integration pattern is: fetch available tools for the current user or session, serialize them into the <tools> XML block using the schema defined in the template, append the user's message inside <user_query>, and send the complete payload to the Anthropic Messages API. The model will return either a text response or a tool_use content block. Your harness must handle both paths.
Validation and parsing is the first critical integration point. When the model returns a tool_use block, validate that the tool name matches one of the provided definitions, that all required arguments are present, and that argument types match the schema. If validation fails, do not execute the tool. Instead, construct a retry prompt that includes the original tool definitions, the failed tool call, and a clear error message such as 'Tool call failed validation: missing required argument [start_date]. Please correct and retry.' Set a maximum retry count (typically 2-3 attempts) and escalate to a human or fallback response if retries are exhausted. For high-risk operations like database writes, financial transactions, or user data mutations, insert a human approval step before execution: surface the proposed tool call with a clear explanation of side effects and wait for explicit confirmation.
Logging and observability are essential for debugging tool-use workflows. Log the full assembled prompt (with PII redacted), the model's raw response, any validation errors, retry attempts, and the final tool execution result. Attach a trace ID that spans the entire request chain so you can reconstruct what happened when a tool call produces an unexpected outcome. Use structured logging fields: trace_id, model_id, tools_provided, tool_called, validation_passed, retry_count, and human_approval_required. This data feeds both debugging sessions and eval pipelines that measure tool selection accuracy and argument correctness over time. Wire these logs into your existing observability stack rather than building a separate AI-specific silo.
Model choice and fallback should be configured in the harness, not hardcoded in the prompt. Start with Claude Sonnet for most tool-use workloads; it balances speed, cost, and instruction-following reliability. For complex multi-tool scenarios with many overlapping definitions, consider Claude Opus for its stronger disambiguation. Implement a fallback path: if the primary model returns an unparseable response after all retries, either escalate to a more capable model or route to a human review queue. Do not silently drop failed tool calls. The harness should also enforce a timeout on tool execution (e.g., 30 seconds for API calls) and return a clear timeout error to the model so it can decide whether to retry, ask the user to wait, or abandon the operation.
Expected Output Contract
Defines the required structure, types, and validation rules for the XML-formatted tool call response expected from Claude. Use this contract to build a parser and validator in your application harness before executing any tool.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
<function_calls> | XML block | Must be present exactly once. Parse check: count occurrences; fail if count != 1. | |
XML element | Must appear at least once inside <function_calls>. Parse check: count >= 1; fail if 0. | ||
<tool_name> | string | Must match a tool name from the provided [TOOL_SCHEMAS]. Schema check: exact string match required; fail on mismatch or hallucinated name. | |
XML element | Must contain valid XML with one child element per argument. Parse check: well-formed XML; fail on parse error. | ||
<[ARGUMENT_NAME]> | string | number | boolean | object | array | Must match a parameter defined in the corresponding tool schema. Schema check: name and type must conform to [TOOL_SCHEMAS]; fail on unknown or missing required arguments. | |
string | If present, must be non-empty and precede the tool call. Null allowed. Confidence threshold: if [REQUIRE_REASONING] is true, fail when missing or empty. | ||
<idempotency_key> | string (UUID v4) | If present, must match UUID v4 format. Format check: regex validation; fail on malformed key. Required when [IDEMPOTENCY_REQUIRED] is true for the selected tool. | |
XML element | Must appear exactly once as the final element inside <function_calls>. Parse check: must be last child; fail if missing or followed by other elements. |
Common Failure Modes
When using Anthropic's XML tool-use format, these failures surface first in production. Each card identifies a specific breakage pattern and the guardrail that prevents it.
XML Tag Mismatch or Malformation
What to watch: The model emits tool calls with missing closing tags, incorrect nesting, or tag name typos that break XML parsing. This happens most often when multiple tools are available and the model mixes tag conventions. Guardrail: Validate XML well-formedness before attempting to parse tool calls. Use a strict schema validator that rejects unknown tags and enforces the exact <tool_call>, <tool_name>, and <arguments> structure. On parse failure, retry with an explicit XML correction instruction rather than falling through to a null tool call.
Argument Type Coercion Errors
What to watch: The model passes string values where integers or booleans are required, or nests objects incorrectly inside <arguments>. JSON parsers reject these, but the failure happens after the tool call is extracted. Guardrail: Post-extraction, validate each argument against the tool's JSON Schema definition before execution. Check types, required fields, and enum membership. Return a structured error message with the specific field and expected type so a retry prompt can target the exact violation.
Tool Hallucination Outside Schema
What to watch: The model invents tool names, parameters, or capabilities not present in the provided XML schema. This is common when user requests resemble capabilities the model was pre-trained on but that aren't in the current tool set. Guardrail: Maintain a whitelist of valid tool names from your schema. After extracting <tool_name>, reject any call whose name isn't in the whitelist. Log the hallucinated name for schema gap analysis—it may indicate a missing tool you should add.
Multiple Tool Calls in Single Block
What to watch: The model wraps several independent tool calls inside one <tool_call> block or nests them incorrectly, making it ambiguous which arguments belong to which tool. Guardrail: Enforce a strict parsing rule: one <tool_call> block per tool invocation. If the parser encounters multiple <tool_name> elements inside a single block, split them into separate calls or reject the block and request single-call-per-block formatting in the retry prompt.
Tool Call Interleaved with User-Facing Text
What to watch: The model emits explanatory text before, after, or between tool call XML blocks, making it hard to extract clean tool calls without also capturing conversational filler. Guardrail: Use a dedicated extraction step that isolates all <tool_call> blocks and ignores surrounding text. If your application requires the model to explain its actions, instruct it to place explanations inside a separate <explanation> block, not interleaved with tool calls.
Silent Argument Omission
What to watch: The model skips required arguments without asking for clarification, either by omitting the field entirely or by inserting placeholder values like "string" or null. This produces tool calls that parse successfully but execute with garbage data. Guardrail: Post-extraction, check that every required field is present and non-null. For string fields, reject known placeholder patterns. If a required argument is missing, do not execute the tool—instead, return a clarification request to the model specifying exactly which argument is needed.
Evaluation Rubric
Run these checks against a golden dataset of at least 50 test cases covering normal requests, edge cases, and error conditions.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
XML Schema Compliance | Output wraps tool definitions in valid <function> blocks with correct <name>, <description>, and <parameters> nesting | Missing closing tags, malformed XML, or tool definitions placed outside <functions> container | XML parser validation against expected element tree; count of <function> blocks matches input tool count |
Argument Type Accuracy | All parameter <type> values match the provided tool schema exactly (string, number, boolean, object, array) | Type mismatch between schema definition and generated XML (e.g., integer instead of number, text instead of string) | Schema diff between input tool definitions and generated parameter types; automated type enumeration check |
Required Field Presence | All required parameters from the input schema appear in the generated XML with <required>true</required> or equivalent annotation | Missing required parameter in output XML; required field marked as optional; parameter present in schema but absent from prompt | Field-by-field comparison of input schema required list against generated parameter elements |
Description Fidelity | Parameter descriptions are preserved verbatim from input schema without hallucinated additions or omissions | Added capabilities not in source schema; truncated descriptions that lose constraint details; invented default values | String similarity check between input schema descriptions and generated XML descriptions; threshold above 0.95 |
Enum Value Completeness | All enum values from input schema appear in generated XML without modification, reordering, or omission | Missing enum values; extra enum values not in source; enum values rewritten or rephrased | Set equality check between input schema enum arrays and generated XML enum elements |
Tool Call Parsability | Generated XML can be parsed by Anthropic's tool-use response parser without errors | Parser throws exceptions on tool call extraction; tool name not found in schema; arguments fail type coercion | End-to-end parse test using Anthropic SDK tool result extraction on model responses using the generated prompt |
Multi-Tool Disambiguation | When multiple tools are provided, each has a distinct name and non-overlapping description sufficient for correct selection | Two tools share identical or near-identical descriptions; model selects wrong tool in disambiguation test cases | Golden dataset with ambiguous requests; measure tool selection accuracy across 20+ disambiguation scenarios |
Edge Case Argument Handling | Empty strings, null values, zero values, and maximum-length strings are handled according to schema constraints | Null passed for required field; empty string where minLength > 0; overflow on maxLength or maxValue constraints | Boundary value test suite with 15+ edge case argument combinations; validate against schema constraints |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base XML template and a single tool. Remove strict validation instructions. Focus on getting the model to emit valid <function_calls> blocks with correct argument names.
xml<functions> <function> <name>[TOOL_NAME]</name> <description>[TOOL_DESCRIPTION]</description> <parameters>[PARAMETER_SCHEMA]</parameters> </function> </functions>
Watch for
- Missing closing XML tags causing parse failures
- Arguments placed outside
<parameters>blocks - Model inventing tools not in the schema

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us