Anthropic's "Writing Tools for Agents" mainly discusses how to write effective tools for agents. The article points out that tools are the bridge connecting deterministic systems (such as APIs) and non-deterministic AI agents. It introduces in detail the three key steps of writing tools: building prototypes, running evaluations, and collaborating with agents to optimize tools. The article summarizes several important principles for writing effective tools, which must follow five major principles: precision, namespacing, rich context, token efficiency, and clear descriptions. Through these methods, tool performance can be improved, making agents more efficient when solving real-world tasks.
The Core Content of "Writing Tools for Agents"
The effectiveness of agents depends entirely on the tools we provide them. We will share how to write high-quality tools and evaluation methods, and how to improve performance by using Claude to self-optimize tools.
ModelsContext Protocol (MCP)can equip LLM agents with hundreds of tools to solve real-world tasks. How can tools achieve maximum effectiveness?
This article will introduce the most effective techniques for improving performance in various intelligent AI systems.
First, it covers how to:
- Build and test tool prototypes
- Create and run comprehensive evaluations of agent tools
- Collaborate withClaude Codeand other agents to automatically improve tool performance
- Finally, it summarizes the key principles discovered in this process for writing high-quality tools:
Choose the right tools to implement (and the tools that should not be implemented):
- Define clear functional boundaries through namespacing
- Return meaningful context from tools to agents
- Optimize tool responses to improve token efficiency
- Optimize tool descriptions and specifications through prompt engineering
What Are Tools?
In computing, deterministic systems produce the same output every time given the same input, while non-deterministic systems, such as agents, can produce different responses even under the same starting conditions.
When we traditionally write software, we are establishing contracts between deterministic systems. For example, a function call like getWeather("NYC") retrieves New York City's weather information in exactly the same way every time it is called.
Tools are a new kind of software, reflecting the contract between deterministic systems and non-deterministic agents. When a user asks "Should I bring an umbrella today?", the agent calls the weather tool, answers based on general knowledge, or even first asks a clarifying question about location. Agents may hallucinate and fail to grasp how to use tools.
When writing software for agents, we need to fundamentally rethink our approach: we need to design tools for agents andMCP servers, not write them as we would write functions and APIs for other developers or systems.
Our goal is to pursue various successful strategies through the use of tools, increasing the range of tasks that agents can effectively solve broadly.
How to Write Tools
In this section, we will provide guidance on how to work with agents to write and improve the tools provided to them. Start by quickly prototyping tools and testing them locally. Run comprehensive evaluations to measure subsequent changes. Working collaboratively with the agent enables repeating the process of evaluating and improving tools until the agent achieves strong performance on real-world tasks.
Build prototypes
Without hands-on practice, it is difficult to predict which tools the agent will find ergonomic and which it will not. Quickly prototype tools. If using Claude Code to write tools (possibly in one go), it is best to provide documentation for any software libraries, APIs, or SDKs the tools will depend on (includingMCP SDK). On official documentation websites, you can find flat llms.txt files suitable for LLMs (this is ourAPI documentation)。
Wrapping tools in alocal MCP serverordesktop extension(DXT) will make it possible to connect and test the tools in Claude Code or the Claude desktop app.
To connect a local MCP server to Claude Code, run claude mcp add <name> <command> [arguments...].
To connect a local MCP server or DXT to the Claude desktop app, navigate to Settings > Developer or Settings > Extensions, respectively.
Tools can be passed directly intoAnthropic APIcalls for programmatic testing.
Test the tools yourself to identify shortcomings. Collect user feedback and build an intuitive understanding around the use cases and prompts you expect the tools to support.
Run evaluations
Next, you need to measure how effectively Claude uses the tools by running evaluations. Generate a large number of evaluation tasks based on real usage scenarios. We recommend collaborating with the agent to help analyze the results and determine how to improve the tools. Please see ourtool evaluation guidefor this end-to-end process.
1. Generate evaluation tasks
Using the early prototype, Claude Code can quickly explore the tools and create dozens of prompt and response pairs. Prompts should be inspired by real usage scenarios and based on real data sources and services (for example, internal knowledge bases and microservices). We recommend avoiding overly simple or superficial "sandbox" environments that cannot stress-test the tools with sufficient complexity. Strong evaluation tasks require multiple tool calls—possibly dozens.
Here are some examples of strong tasks:
- Schedule a meeting with Jane next week to discuss our latest Acme Corp project. Attach the notes from our last project planning meeting and book the meeting room.
- Customer ID 9182 reports that they were charged three times in one purchase attempt. Find all related log entries and determine whether any other customers are affected by the same issue.
- Customer Sarah Chen has just submitted a cancellation request. Prepare a retention offer. Determine: (1) why they are leaving, (2) which retention offer is most appealing, and (3) any risk factors we should be aware of before offering the incentive.
Here are some examples of weaker tasks:
- Schedule a meeting with jane@acme.corp next week.
- Search the payment logs for purchase_complete and customer_id=9182.
- Find the cancellation request for customer ID 45892.
Each evaluation prompt should be paired with a verifiable response or outcome. Verifiers can be as simple as exact string comparison between the ground truth and the sampled response, or as complex as asking Claude to judge the response. Avoid overly strict verifiers that reject correct responses due to spurious differences such as formatting, punctuation, or valid alternative phrasings.
For each prompt-response pair, select the tools that the designated expected agent should call when solving the task, and measure whether the agent successfully grasps the purpose of each tool during evaluation. Since there may be multiple valid paths to correctly solve a task, try to avoid overspecifying or overfitting the strategy.
2. Run the evaluation
We recommend running evaluations programmatically via direct LLM API calls. Use a simple agent loop (a while loop wrapping alternating LLM API and tool calls): one loop per evaluation task. Each evaluation agent is given a single task prompt and tools.
In the evaluation agent's system prompt, it is recommended to instruct the agent to output a structured response block (for verification), and also output reasoning and feedback blocks. Instruct the agent to output these before tool calls and response blocks, improving the LLM's effective intelligence by triggering chain-of-thought (CoT) behavior.
If using Claude to run evaluations, enableinterleaved thinkingto get similar "out-of-the-box" functionality. This will help probe why the agent calls or does not call certain tools, highlighting specific areas in tool descriptions and specifications that need improvement.
In addition to top-level accuracy, it is recommended to collect other metrics, such as the total runtime of individual tool calls and tasks, the total number of tool calls, total token consumption, and tool errors. Tracking tool calls can help reveal common workflows pursued by the agent, providing opportunities for tool consolidation.
3. Analyze the results
Agents are useful partners for finding problems and providing feedback, covering everything from contradictory tool descriptions to inefficient tool implementations and confusing tool schemas. What agents omit in their feedback and responses is often more important than what they include. LLMs do not always accurately express what they really mean.
Observe where agents get stuck or confused. Read through the evaluation agent's reasoning and feedback (or chain of thought) to identify shortcomings. Review the raw transcripts (including tool calls and tool responses) to capture any behavior not explicitly described in the agent's chain of thought. Read between the lines; remember that the evaluation agent does not necessarily know the correct answer or strategy.
Analyze tool call metrics. A large number of redundant tool calls may indicate the need to appropriately adjust pagination or token limit parameters; a large number of tool errors from invalid parameters may indicate that the tool needs clearer descriptions or better examples. When we launchedClaude's web search tool, we found that Claude unnecessarily appended 2025 after the tool query parameter, which skewed search results and reduced performance (we steered Claude in the right direction by improving the tool description).
4. Collaborate with the agent
You can even have the agent analyze the results and improve the tools. Simply concatenate the evaluation agent's transcripts and paste them into Claude Code. Claude is an expert at analyzing transcripts and refactoring large numbers of tools in one go—for example, ensuring that tool implementations and descriptions remain self-consistent when new changes are made.
In fact, much of the advice in this article comes from repeatedly optimizing our internal tool implementations using Claude Code. Our evaluations are built on internal workspaces, reflecting the complexity of our internal workflows, including real projects, documents, and messages.
We rely on held-out test sets to ensure we do not overfit to our "training" evaluations. The test sets show that even when surpassing the performance of "expert" tool implementations, we can extract additional performance improvements—whether the tools were written manually by our researchers or generated by Claude itself.
In the next section, we will share some lessons learned from this process.
Principles for Writing Efficient Tools
In this section, we distill what we have learned into some guiding principles for writing efficient tools.
Choosing the Right Tools for Agents
More tools do not always lead to better results. One common mistake we have observed is tools that merely wrap existing software functionality or API endpoints—regardless of whether the tools are suitable for agents. This is because agents have different "affordances" than traditional software—the way they perceive and use tools is fundamentally different from traditional software.
LLM agents have limited "context" (that is, they can process only a limited amount of information at a time), whereas computer memory is cheap and plentiful. Take the task of searching for a contact in an address book as an example. A traditional software program can efficiently store and process a list of contacts one by one, checking each contact before continuing.
If an LLM agent uses a tool that returns all contacts, it must read each contact token by token, wasting limited context space on irrelevant information (imagine searching for a contact in an address book by reading every page from top to bottom—that is, by brute force). A better and more natural approach (for both agents and humans alike) is to first jump to the relevant page (perhaps by finding it alphabetically).
We recommend first building a small number of carefully considered tools targeting high-value workflows, matching the evaluation tasks, and expanding from there. In the address book case, choose to implement a search_contacts or message_contact tool rather than simply providing a list_contacts tool.
Tools have the ability to consolidate, handling multiple discrete operations (or API calls) under the hood. For example, a tool enriches its response with relevant metadata, or handles frequently chained multi-step tasks in a single tool call.
Here are some examples:
- Instead of implementing list_users, list_events, and create_event tools, consider implementing a schedule_event tool that can find availability and schedule an event.
- Instead of implementing a read_logs tool, consider implementing a search_logs tool that returns only relevant log lines along with some surrounding context.
- Instead of implementing get_customer_by_id, list_transactions, and list_notes tools, implement a get_customer_context tool that compiles all of a customer's recent relevant information at once.
Ensure that every tool you build has a clear and distinct purpose. Tools should enable agents to break down and solve tasks in a way similar to how humans would if given the same underlying resources, while reducing the context that would otherwise be consumed by intermediate outputs.
Too many tools, or tools with overlapping functionality, can also distract agents from pursuing efficient strategies. Careful, selective planning of which tools to build (or not build) really pays off.
Set namespaces for tools
An AI agent may gain access to dozens of MCP servers and hundreds of different tools—including tools provided by other developers. When tool functionality overlaps or their purposes are ambiguous, the agent may be confused about which tools to use.
Namespaces (grouping related tools under a common prefix) help draw boundaries among a large number of tools; MCP clients sometimes do this by default. For example, namespacing by service (such as asana_search, jira_search) and by resource (such as asana_projects_search, asana_users_search) helps the agent choose the right tool at the right time.
We found that prefix- and suffix-based namespace choices have a significant impact on our tool-use evaluation. The effect varies across LLMs, and we recommend choosing a naming scheme based on your own evaluation.
An agent may call the wrong tool, call the right tool with the wrong parameters, call too few tools, or mishandle tool responses. By selectively implementing tools whose names reflect the natural subdivisions of tasks, you can simultaneously reduce the number of tools and tool descriptions loaded into the agent's context, offloading agent computation from the context back to the tool call itself. This lowers the overall risk of the agent making mistakes.
Return meaningful context from tools
Likewise, tool implementations should be careful to return only high-value information to the agent. Context relevance should be prioritized over flexibility, avoiding low-level technical identifiers (for example: uuid, 256px_image_url, mime_type). Fields like name, image_url, and file_type are more likely to directly guide the agent's downstream actions and responses.
Agents are significantly more successful at handling natural-language names, terms, or identifiers than at handling obscure identifiers. We found that simply resolving arbitrary alphanumeric UUIDs into more semantically meaningful and interpretable language (or even a 0-indexed ID scheme) can significantly improve Claude's precision on retrieval tasks by reducing hallucinations.
In some cases, the agent may need the flexibility to handle both natural-language and technical-identifier outputs at the same time, even if only to trigger a downstream tool call (for example, search_user(name='jane') → send_message(id=12345)). You can achieve both by exposing a simple response_format enum parameter in the tool, letting the agent control whether the tool returns a "concise" or "detailed" response (figure below).
You can add more formats for greater flexibility, similar to GraphQL, choosing exactly which pieces of information you want to receive. Below is an example of a ResponseFormat enum that controls the level of detail in a tool response:
enum ResponseFormat {
DETAILED = "detailed",
CONCISE = "concise"
}
Below is an example of a detailed tool response (206 tokens):
Below is an example of a concise tool response (72 tokens):
The structure of tool responses—for example, XML, JSON, or Markdown—can also affect evaluation performance: there is no one-size-fits-all solution. This is because LLMs are trained via next-token prediction and tend to perform better on formats that match their training data. The optimal response structure can vary greatly across tasks and agents. We recommend choosing the best response structure based on your own evaluation.
Optimize the token efficiency of tool responses
Optimizing context quality is important. But optimizing the amount of context returned to the agent in tool responses is equally important.
We recommend implementing some combination of pagination, range selection, filtering, and/or truncation for any tool response that may consume a large amount of context, with reasonable default parameter values. For Claude Code, we limit tool responses to 25,000 tokens by default. We expect the effective context length of agents to grow over time, but the need for context-efficient tools will always exist.
If you choose to truncate responses, be sure to guide the agent with useful instructions. You can directly encourage the agent to pursue more token-efficient strategies, such as performing multiple small targeted searches rather than a single broad search for a knowledge retrieval task. If a tool call raises an error (for example during input validation), you can engineer the error response through prompting to clearly convey specific and actionable suggestions for improvement, rather than providing obscure error codes or traceback information.
The following is an example of a truncated tool response:
The following is an example of a useless error response:
The following is an example of a useful error response:
Now let's discuss one of the most effective ways to improve tools: prompt engineering of tool descriptions and specifications. Because this content is loaded into the agent's context, together they can guide the agent toward effective tool-calling behavior.
When writing tool descriptions and specifications, imagine how you would describe your tool to a new member of the team. Consider the context that may be implicitly introduced — specialized query formats, definitions of jargon, relationships between underlying resources — and make it explicit. Avoid ambiguity by clearly describing (enforced through strict data models) expected inputs and outputs. In particular, note that input parameters should be named unambiguously: instead of using a parameter named user, try using a parameter named user_id.
Through evaluation, you can more confidently measure the impact of prompt engineering. Even small improvements to tool descriptions can bring significant gains. After we made precise improvements to tool descriptions, Claude Sonnet 3.5 achieved state-of-the-art performance inSWE-bench Verifiedevaluations, significantly reducing error rates and improving task completion.
In ourdeveloper guideyou can find other best practices for tool definitions. If you are building tools for Claude, we recommend reading the explanation of how tools are dynamically loaded into Claude'ssystem prompt. If you are writing tools for an MCP server,tool annotationshelp disclose which tools require open-world access or make destructive changes.
Looking ahead
To build effective agent tools, we need to reorient software development practices from predictable deterministic patterns to non-deterministic patterns.
Through the iterative, evaluation-driven process described in this article, we found consistent patterns for tool success: effective tools have clear and explicit definitions, can reasonably utilize agent context, can be composed and used across diverse workflows, and enable agents to intuitively solve real-world tasks.
Looking ahead, the specific mechanisms by which agents interact with the world will continue to evolve — from updates to the MCP protocol to upgrades of the underlying LLM itself. By adopting a systematic, evaluation-driven approach to improving agent tools, we can ensure that as agent capabilities continue to strengthen, the tools they use will also evolve in tandem.
The official website address of "Writing Tools for Agents"
- Official website address:https://www.anthropic.com/engineering/writing-tools-for-agents
Who "Writing Tools for Agents" Is For
-
AI engineers and developers: Provides concrete methods for building, testing, and optimizing tools, helping improve agent performance and efficiency.
-
Data scientists and machine learning experts: The evaluation and optimization techniques in the article help combine models with tools to improve overall system performance.
-
Software architects: The article's advanced guidance helps users design more efficient and flexible system architectures, integrating agents and tools into existing systems.
-
Product managers: The article helps users understand the key points of tool development, better plan product features, and evaluate technical solutions.
-
Researchers: The best practices and case analyses in the article provide references for users' research, helping explore new research directions.