Chapter 2. Tools and MCP
Learning objectives
- Design tools that are hard for agents to misuse and that conserve tokens, and verify the improvement effects through evaluation.
- Manage the size of tool results using pagination, filtering, truncation, and references.
- Explain the host, client, and server roles in MCP and the stateless model of the 2026-07-28 specification.
- Distinguish between protocol errors and tool execution errors, and design errors that lead to recovery actions.
- Handle tool annotations, authentication, and scopes according to trust boundaries, and grant least privilege.
Introduction
Picture a scene where someone hands a 300-page internal system manual to a new hire and says, "Everything you need is in here." The information is complete, but throughout their first week, they will open the wrong screens, confuse similarly named menus, and freeze in front of error codes. This is precisely what happens when an agent receives dozens of tools that merely wrap existing APIs as they are.
Tools are both the windows through which agents view the world and their hands. This chapter first covers what tools to build and how to design their names, parameters, results, and errors. Next, it outlines the structure of MCP, the changes in the 2026-07-28 specification, and how to establish privilege boundaries using annotations, authentication, and scopes; then, in Going deeper, it examines strategies for when tools grow into the hundreds and methods for calling tools via code.
Key concepts
Tools are interfaces for agents
Just as designing screens used by humans is called HCI (Human-Computer Interface), Anthropic calls designing tools and their descriptions used by agents ACI (Agent-Computer Interface) and recommends devoting as much effort to it as to HCI. The same article notes that when building the SWE-bench agent, more time was spent on tool optimization than on the overall prompt.
A representative technique is poka-yoke, namely design that makes it difficult to make mistakes. When the model repeatedly got relative paths wrong after leaving the root directory, the team changed the tool so that it always accepted only absolute paths, and the model used that approach without issue. Instead of writing "be careful with paths" in the prompt instructions, they eliminated the possibility of erroneous input altogether. It is the same concept as cutting off one corner of a SIM card so it cannot be inserted upside down.
The checklist questions are simple: Is the usage clear just from the description and parameters? Are there usage examples and edge cases? Would a junior developer understand it without confusion? Then, test with many inputs to see where the model makes mistakes.
Choosing the right tools
Anthropic's "Writing effective tools for agents" emphasizes that having more tools does not lead to better results. A common mistake is directly wrapping API endpoints one by one. For an address book, instead of a list_contacts that returns everything, provide search_contacts or message_contact; for a calendar, create a single schedule_event that finds free slots and handles booking—grouping multiple steps into a small number of tools tailored to high-impact workflows is recommended.
The criterion for boundaries is: "Would a human practitioner handle this task in a single step?" Dividing tools too granularly increases calls due to the burden of composition, while bundling them too broadly increases the number of parameters, making erroneous calls more likely. Merge overlapping tools, and make the distinction clear in names and descriptions for tools that appear similar but serve different purposes.
Names, descriptions, and parameters
When using tools across multiple services together, names serve as the first clue for selection. The same article recommends namespacing grouped by service or resource-level prefixes (asana_search, jira_search, asana_projects_search). Parameter names should have clear meanings from their names alone. user_id is better than user.
Descriptions specify what the tool will and will not do, the format and units of inputs, and the meaning of results. The difference becomes apparent when rewriting an update tool that merely accepts id and value with the description "Modifies a record" into the following:
{
"name": "shipment_set_weight",
"description": "Records the measured weight of cargo before dispatch. Dispatched cargo cannot be changed. Weight in kilograms, up to one decimal place.",
"inputSchema": {
"type": "object",
"properties": {
"shipment_number": { "type": "string", "description": "e.g., SH-2026-004211" },
"weight_kg": { "type": "number", "minimum": 0.1, "maximum": 30000 }
},
"required": ["shipment_number", "weight_kg"],
"additionalProperties": false
}
}
The improved version puts the unit in the parameter name, restricts the allowed range via the schema, and states in the description cases where changes cannot be made. For values the model frequently gets wrong, such as time zones, eliminate room for error through format enforcement, such as requiring ISO 8601 format and time zone notation or accepting UTC only. Business rules that schemas cannot enforce (e.g., cargo cannot be dispatched in excess of inventory) are validated on the server, because even a well-formed call can be invalid from a business perspective.
Returning meaningful results
Tool results are the ingredients for the next action. The same article advises returning fields the agent can use immediately, such as names, rather than low-level identifiers like uuid, 256px_image_url, or mime_type, noting that search accuracy increased when hard-to-recognize identifiers were replaced with readable terms. If an ID is strictly necessary for a subsequent call, simply provide it alongside the name.
There is also a method of allowing the selection of response verbosity. Letting the agent choose between "concise" and "detailed" via an enum parameter like response_format allows it to use concise responses most of the time, opting for detailed responses only when IDs are needed. In an example from the same article, the detailed response took 206 tokens, while the concise response took 72 tokens—roughly one-third as many.
Managing the size of tool results
Larger results consume more context and accelerate context rot, which will be discussed in Chapter 3. The techniques recommended by the same article are pagination, range selection, filtering, and truncation with sensible defaults; it also notes that Claude Code limits tool responses to 25,000 tokens by default.
| Technique | Design example |
|---|---|
| Default count and pagination | limit default of 20, returns next page cursor |
| Server-side filtering | Parameters that narrow down first by period, status, or assignee |
| Field selection | fields parameter to select only necessary columns |
| Truncation notice | "Showing only 20 of 1,240 results. Narrow the date range or filter by status" |
| Returning references | Place large artifacts in files or resources and return only their location |
When truncating, you must clearly state the fact that it was truncated and the range in the result. Otherwise, the agent will assume that the 20 items received are everything. An MCP tool can return a URI to be read later via resource_link in the result, and if outputSchema is defined, it produces structured results via structuredContent. If an output schema exists, the server MUST return results matching it, the client SHOULD validate them, and it is recommended to include the same JSON as a text block as well for backward compatibility.
Errors are instructions for recovery
The MCP specification divides tool errors into two categories.
| Type | Examples | Delivery method | Model's recoverability |
|---|---|---|---|
| Protocol error | Unknown tool, malformed request, server error | JSON-RPC error |
Low |
| Tool execution error | API failure, input validation failure, business rule violation | isError: true and description in result |
High. Fix arguments and retry |
The specification states that clients SHOULD pass tool execution errors to the model so it can correct itself. Execution errors return in the shape of a normal result. In the 2026-07-28 edition, all results include resultType indicating the kind of result, and a completed result is "complete".
{
"jsonrpc": "2.0",
"id": 4,
"result": {
"resultType": "complete",
"content": [{ "type": "text", "text": "Delivery date must be after today. Today is 2026-10-20." }],
"isError": true
}
}
A good error message indicates the next action. Distinguish whether the agent should fix the input, wait and retry, request more permissions, or escalate to a human. There is one case that warrants caution: errors of unknown execution status, such as timeouts. Because a payment request might have been processed with only the response lost, in this case the correct instruction is not "retry," but "query the processing status." Internal stack traces or sensitive values should never be included in errors.
Tools with side effects: preview and confirm
Calling a read tool incorrectly only wastes tokens, but mutation tools alter the state of external systems. For irreversible changes, separating preview and confirmation is effective.
- The preparation tool calculates the target of change, the values to be changed, and the impact (amount, recipient, count), returns them, and issues a preview identifier with a short expiration time.
- A human or policy check verifies the preview contents.
- The confirmation tool receives only the preview identifier. The server executes precisely the contents pointed to by that identifier.
- Confirming twice with the same identifier produces the effect only once (idempotency).
This architecture closes the gap where what was approved differs from what is executed, and prevents retries from escalating into duplicate executions. Accepting absolute values ("set daily budget to KRW 300,000") rather than relative values ("increase by 10%") is the same kind of poka-yoke, because the result remains the same even if the same request arrives twice.
Architecture of MCP
MCP (Model Context Protocol) is an open protocol connecting LLM applications to external data and tools. Messages follow the JSON-RPC 2.0 format, and there are three participants:
| Role | Description |
|---|---|
| Host | The LLM application that initiates the connection |
| Client | The connector inside the host that communicates with a single server |
| Server | The service that provides context and capabilities |
Servers provide three capabilities: resources (context and data for users or models to use), prompts (templated messages and workflows for users), and tools (functions executed by models). Clients can provide elicitation, where a server requests additional information from the user. The 2026-07-28 edition designated Roots, Sampling, and Logging as Deprecated. A deprecated capability will function during a grace period of at least 12 months, but this indicates that new implementations should not adopt it. However, among the associated methods, logging/setLevel and notifications/roots/list_changed have already been removed in this edition. The log level is now set per request via io.modelcontextprotocol/logLevel in _meta. The alternatives offered by the specification are passing directories via tool parameters or server configuration, integrating directly with LLM provider APIs, and recording logs via standard error or OpenTelemetry, respectively.
According to the specification's safety principles, tools must be treated as arbitrary code execution, hosts must obtain explicit user consent before calling a tool, and humans SHOULD be able to decline calls.
2026-07-28 specification: statelessness and handles
The biggest change in this edition is that MCP has become a stateless protocol. All information required for processing is contained within the request, and the server MUST NOT infer context such as protocol version, client capabilities, or identity from prior requests on the same connection. Therefore, every client request must include io.modelcontextprotocol/protocolVersion and io.modelcontextprotocol/clientCapabilities in _meta; if omitted, the server rejects it with an Invalid Params error (-32602). Including the client name and version (io.modelcontextprotocol/clientInfo) is also recommended, but because it is a self-reported value, it must not be used for security decisions. The initialize handshake and session ID header from earlier editions have been removed, and server/discover was introduced for servers to advertise supported versions and capabilities. An open stdio process is neither a conversation nor a session.
If state across multiple calls is needed (shopping carts, open browsers, database transactions), a creation tool returns an explicit handle, and subsequent calls accept that handle as an argument. The non-normative guidance of the specification is as follows:
- On an authenticated server, a handle is merely a name, not an authorization. Validate the caller's privileges against the handle on every call.
- Make handles opaque identifiers that do not expose internal structure, and state the retention period in the creation tool's description.
- For expired or unknown handles, return a tool execution error stating that fact so the model can create a new one.
If additional user input is required mid-processing, use multi-round-trip requests (MRTR). When the server returns a resultType: "input_required" result containing the necessary prompt and an opaque requestState, the client populates the response and resends the original request with a new ID. Because requestState passes through the client, the server treats it as untrusted input that can be tampered with, and MUST protect its integrity if it affects authorization or business logic. Elicitation offers a form mode, which collects input via forms on the client UI, and a URL mode, which directs the user to an external page. Passwords, API keys, tokens, and payment information must not be requested via form mode; such information is collected via URL mode, which bypasses the client.
Caution
That the protocol is stateless does not mean servers cannot have business data or long-running task states. State is permitted, but it must be bound to explicit identifiers rather than to the connection. Because editions up to 2025-11-25 used the initialize handshake and Streamable HTTP servers could issue session IDs, check the version of the peer you are connecting to first.
Transports, cancellations, and long-running tasks
MCP has two standard transports: stdio, where the client spawns the server as a child process and communicates via standard input/output, and Streamable HTTP, where it communicates with a remote server over HTTP. The earlier HTTP+SSE transport is deprecated.
Cancellation and timeouts differ by transport. In Streamable HTTP, closing the request's response stream constitutes cancellation, and the server must treat the request as cancelled when the client disconnects. Because the 2026-07-28 edition eliminated stream resumption, a disconnected request must be resent with a new ID. In stdio, the client sends notifications/cancelled. The specification recommends setting a timeout on all requests and adds that while timeouts may be reset upon receiving progress notifications, a maximum timeout SHOULD always be enforced regardless of progress notifications.
Holding operations that take minutes or hours on a single connection leaves them vulnerable to intermediary proxy timeouts or client restarts. When using the official Tasks extension, the server returns a durable task handle instead of a result, and the client queries the status (working, input_required, completed, failed, cancelled) via tasks/get, resuming with the same ID even after a restart. Extensions can only be used when both sides explicitly declare support.
Tool annotations and trust
Tool definitions include name, title, description, inputSchema, outputSchema, annotations, and more. Names are recommended to be 1 to 128 characters long, using only alphanumeric characters, underscores, hyphens, and dots. Because collecting tools from multiple servers can lead to name collisions, the specification recommends disambiguation strategies such as server identifier prefixes, and warns against relying on the server name in serverInfo since it is not guaranteed to be unique.
Annotations are hints describing the behavior of a tool.
| Annotation | Meaning | Default |
|---|---|---|
readOnlyHint |
Does not modify the environment | false |
destructiveHint |
May perform destructive modifications (meaningful only when not read-only) | true |
idempotentHint |
Repeated calls with identical arguments produce no additional effects (meaningful only when not read-only) | false |
openWorldHint |
May interact with the external open world (e.g., web search) | true |
Notice that the default values are conservative. A tool without any annotations is assumed to modify the environment, be potentially destructive, and be capable of interacting with the external world. Furthermore, the specification warns that unless originating from a trusted server, clients MUST treat annotations as untrusted. Annotations are a server's self-description, not a guarantee. Authorization decisions such as auto-approval must be tied to the server's trust tier and host policy.
Authentication and least privilege
The specification's authentication scope differs depending on the transport. HTTP-based transports SHOULD follow the MCP Authorization specification, while stdio is advised not to follow this specification and instead obtain credentials from the execution environment.
The core rules from the security best practices documentation are as follows:
| Risk | Rule |
|---|---|
| Token passthrough | MCP servers MUST NOT accept tokens that were not issued to them. Passing received tokens directly to downstream APIs breaks controls such as audit trails and rate limits |
| Confused deputy | Proxy servers connecting to third-party APIs using a static client ID must obtain per-client consent before proceeding to third-party authorization |
| Handle hijacking | Do not treat possession of a handle as authentication. Bind handles to authenticated users on the server side |
| Excessive scopes | Start with minimal scopes and step up progressively using scope demands in WWW-Authenticate when an action requiring privilege is first attempted. Avoid catch-all scopes like * or all |
| Local servers | Clients supporting one-click installation must display the entire command to be executed without truncation and obtain explicit approval. Execution in a least-privilege sandbox is recommended |
A scope is the range of operations permitted by a token. Handing out only the key to the room needed right now and granting more when necessary causes less damage if lost than giving a single master key. While tools/list must not vary by connection, it may vary based on the request's authorization, allowing servers to show only tools permitted by the caller's scopes. However, hiding tools is merely a convenience; actual enforcement is handled by server-side authorization checks on every call.
Human approval and security requirements
The specification's tool security requirements differ in responsibility between server and client:
| Entity | Requirements |
|---|---|
| Server (MUST) | Validate all inputs, appropriate access control, rate limiting, sanitize outputs |
| Client (SHOULD) | User confirmation before sensitive operations, display inputs to be sent to user prior to calling (prevent unintended leaks), validate results before passing to model, timeouts, audit logs |
Which calls require human confirmation will be determined in Chapter 5. For now, simply remember that the confirmation screen must show the exact input to be sent. A confirmation that only asks "Send email?" will permit a call even if the recipient has been altered.
Authorization server discovery and client registration
A client connecting to a remote MCP server for the first time does not know where the authorization server protecting that server is located. The authorization specification of the 2026-07-28 edition establishes rules starting right from this entry point. MCP servers MUST implement OAuth 2.0 Protected Resource Metadata (RFC 9728). Clients must also use this metadata when discovering the authorization server.
The request must also reveal which server the token is intended for. The client includes the canonical URI of the MCP server as the resource parameter (RFC 8707) in both the authorization request and the token request. It MUST send this parameter even if the authorization server does not support it. A token anchored to a specific target cannot be used on another server. This mechanism meshes with the aforementioned rule that servers do not accept tokens not issued to them.
Returning responses are inspected as well. If the authorization response contains iss per RFC 9207, the client MUST compare that value against the recorded issuer before exchanging the authorization code for a token. Even if a response from a different authorization server gets mixed in, it is filtered out at this stage.
Registration methods have changed as well. Dynamic Client Registration (RFC 7591) has been deprecated, and Client ID Metadata Documents take its place. Because the client publishes a document containing its information and presents that URL as the client ID, there is no need to register separately with each authorization server. Dynamic registration remains solely as a path for compatibility with authorization servers that do not support metadata documents.
Consider a scenario where an internal agent connected to the MCP server of 'Hourglass Accounting' for the first time. The client checked the authorization server in the server's protected resource metadata. When that authorization server supported metadata documents, it used the document URL as the client ID. Dynamic registration was invoked only when metadata documents were unsupported. In both the authorization request and the token request, it placed the canonical URI of the accounting server as resource. When iss attached to the callback differed from the recorded issuer, it halted the flow without exchanging the code.
Distinguishing deprecated, removed, and preview
The 2026-07-28 edition, the current protocol version, divides feature lifecycles into three states—Active, Deprecated, and Removed—and sets the deprecation period to a minimum of 12 months. Deprecated features still function. Existing integrations do not need to be ripped out immediately, but newly written code uses alternatives. Removed features do not exist at all in peers adhering to this edition.
Removal occurs at the method level as well. While Logging and Roots are still in the Deprecated stage, some of their associated methods were removed immediately in this edition, and ping disappeared alongside them.
| Earlier editions | 2026-07-28 |
|---|---|
ping, logging/setLevel, notifications/roots/list_changed |
Removed. Log level is set per request via io.modelcontextprotocol/logLevel in _meta |
GET endpoints, resources/subscribe |
Replaced with subscriptions/listen |
Resource not found error -32002 |
-32602 (Invalid Params). Specification reserved range is -32020 to -32099 (e.g., HeaderMismatch -32020) |
The resource not found code was changed to align with the JSON-RPC specification. Because the same -32602 is also used for missing _meta, do not determine recovery actions from the code alone; consider which request it originated from as well. JSON-RPC batching was removed in the earlier 2025-06-18 edition. Sampling gained tool invocation via tools and toolChoice in the 2025-11-25 edition, only to be deprecated in the 2026-07-28 edition.
The official MCP Registry is documented as still in preview, meaning compatibility may break or data may be reset prior to general availability. The Registry API was frozen at v0.1 on 2025-10-24, and no general availability date had been set as of verification.
A client that sends ping every 30 seconds and clears its cache upon receiving -32002 will fail on both behaviors when facing a 2026-07-28 server. Check the peer's supported edition first via server/discover and branch processing paths by edition.
Freeform input and computer use toolsets
There is no reason tool input must always be a JSON object. OpenAI introduced the custom tool call type on 2025-08-07. It is a type where inputs and outputs are exchanged in freeform format when calling a tool. Custom tools, which debuted in GPT-5, can also constrain their input using context-free grammars. Placing values that are inherently text, such as SQL or proprietary query languages, into a JSON string makes it easy for errors to creep into quotes and newline escapes. Defining the shape with a grammar prevents such errors at the syntax level. This effectively elevates poka-yoke to the grammar level. However, grammar only protects the shape. Whether a query is read-only and whether the caller has permission to view that table are checked separately by the server.
Anthropic's computer use tools changed how they are defined. The earlier computer_20251124 required a beta header and selected actions via the action field of a single tool. Today's computer_toolset_20260801 calls member tools belonging to a toolset and passes configuration, requiring no beta header. Migrating to the toolset is optional, so models listed under earlier tool versions continue to accept computer_20251124 alongside the beta header. There is an exception: in the Claude API and Google Cloud's Claude Models (Google-managed), models starting with Claude 5.5 accept only toolsets.
Suppose Breeze Logistics was automating an invoice entry screen with claude-sonnet-4-5-20250929. This model was scheduled to retire on 2026-11-30, and the replacement model was claude-sonnet-5-5. Because the new model in the Claude API did not accept the existing computer_20251124 definition, the team bundled the model replacement and toolset transition into a single deployment and evaluated them under the same task. Changing the model was synonymous with changing the tool contract.
Going deeper
When tools scale into the hundreds
When multiple MCP servers are connected, tool definitions alone take up a significant portion of the context. In this situation, the MCP client best practices documentation recommends progressive discovery. This is a method where the host receives tool definitions but does not place them directly into the context, instead using a lightweight search_tools meta-tool to search only for the necessary tools and load their full definitions. The documentation cites three tiers as an example—list (name and one-line description), detail (full schema of a single tool), and execution—and recommends switching when tool definitions exceed a certain percentage of the context window (e.g., 1–5%). The search is conducted using keywords, embeddings, selection by a small model, or a combination thereof, and some model providers offer built-in tool search.
The pitfall is prompt caching. Because most providers cache the prefix of the prompt, including the tools array, inserting, removing, or reordering tool definitions during a conversation breaks the cache. The documentation recommends appending newly found definitions after the cache breakpoint, or routing all calls through a single, fixed call_tool meta-tool that accepts the tool name and arguments to invoke it on the model's behalf so that the array does not change. The same reasoning is why the specification recommends returning tools/list in a deterministic order.
When a model calls tools with code
When tools are called directly, the entire result passes through the model on each invocation. If the task is to read thousands of lines of logs and create a ticket for each unique error, the model must read all of those thousands of lines. Programmatic tool calling (code mode) allows the model to write code that calls tools, and that code executes inside a sandbox so that only the final result is returned to the model. Because intermediate data does not enter the context, tokens and latency are reduced significantly.
In exchange, a new attack surface emerges: code execution. The MCP documentation lists six conditions: do not grant the sandbox direct network access and route all communication through the host mediator; keep credentials on the host and do not expose them to generated code; do not treat approving a script as approving every call inside it; treat results from one server as untrusted input to another server; limit execution time and memory; and validate and truncate sandbox output before passing it to the model. In interactive tasks with only one or two calls, the complexity may outweigh the benefits, so apply it first to tasks that filter and aggregate large volumes of data.
Managing tool changes as a contract
Even if the schema remains unchanged, if a single line in the description or the meaning of a result field changes, the behavior of the agent changes. Therefore, name, description, schema, and business semantics are versioned together, a change history is maintained, and changes are verified through pre-deployment evaluation. Anthropic recommends measuring execution time, number of tool calls, tokens, and tool errors against realistic tasks, but verifying them on a held-out test set so that the system is not merely fitted to the evaluation set. A research systems article reports that an agent that rewrote tool descriptions reduced subsequent task completion time by 40%. When a server changes its list, it can notify via notifications/tools/list_changed, at which point the client discards the cached list and fetches it again.
At work
Swell Ad: Adding safety mechanisms to budget change tools
The operations agent at the advertising agency Swell Ad used tools that directly wrapped 11 advertising platform APIs. In the previous quarter, there were two types of incidents. There were 9 incidents where campaigns with similar names ('Fall_Special_Search' and 'Fall_Special_Search_Revisit') were mistakenly swapped during execution, and 3 incidents where a retry after a timeout caused "increase daily budget by 20%" to be applied twice.
The team reviewed three alternatives. The proposal to add more cautionary wording to the system prompt was rejected because it had already been tried in the previous quarter. The proposal to retain the 11 tools and merely refine their descriptions was rejected on the grounds that it failed to eliminate the structural causes of relative-value increases and duplicate execution. The chosen option was a redesign of the tools.
Inquiries were consolidated into a single campaigns_find(query, status), with the result including the campaign name, ID, current daily budget, and the person in charge. Modifications were split into two. budget_change_preview(campaign_id, new_daily_budget_krw) accepted only absolute values and returned the amounts before and after the change, the estimated monthly spend, and a preview ID valid for 10 minutes. budget_change_apply(preview_id) accepted only the preview ID and applied it only once even if the same ID was received twice. Any increase exceeding 50% relative to the baseline returned isError: true along with "Approval from the person in charge is required. Please use the approval request tool." When a timeout occurred, the agent was configured to check whether the change had been applied using the preview ID instead of retrying.
The system was evaluated against 40 tasks created by modifying 12 past incidents and 25 separate, new held-out tasks. In both sets, incorrect campaign modifications and duplicate budget increases were zero, and tool calls per task decreased from 4.8 to 2.6.
BlueSoft: Redrawing permissions for the deployment MCP server
Development platform company BlueSoft built a remote MCP server so that an agent could query deployment status and roll back if issues arose. The first version focused on rapid development. It accepted the user's existing CI system token as-is and passed it to the CI API, had only a single scope of deploy:*, and allowed anyone's deployment to be rolled back as long as the deployment ID was known.
The security review pointed out three issues: the server was receiving and forwarding a token that was not issued to itself (token forwarding); users who only queried status also held rollback permissions (excessive scope); and deployment IDs were being used like authorization (treating handles as authentication).
The redesigned server accepted only its own token issued through MCP authorization and verified the audience. It accessed the CI API using the server's own credentials, but queried the internal authorization system on every call regarding the user's deployment permissions and recorded the actual user identifier in the audit log of downstream calls. It initially requested only deploy:read, and when a rollback was first attempted, it required deploy:rollback to prompt step-up authorization. Although tools/list hid the rollback tool based on scope, rollback calls were always rechecked on the server. destructiveHint: true was attached to the rollback tool, and the host registered the internal server as a trusted server and displayed a confirmation screen based on this annotation.
The rejected alternative was "writing 'Roll back carefully' in the tool description." This was because a description is merely a recommendation given to the model, not an authorization boundary.
Common mistakes
- "If all APIs are exposed as tools without exception, the agent will choose on its own." Wrapping existing APIs is tempting because they can be built quickly, but the burden of composition shifts to the model, and it confuses similar tools with one another. A small number of tools organized by workflow units is better.
- "Throwing errors as protocol errors is standard practice." This looks natural because it aligns with general API practices, but business errors that the model can fix must be returned with
isErrorand a specific description so that it can recover on its own. - "Since
readOnlyHintis attached, it is safe." It looks like an official guarantee because it is a field defined in the specification, but annotations are the server's own assertions. Authorization decisions must not be made based on annotations from untrusted servers. - "It is convenient to pass received tokens directly to downstream APIs." This is tempting because implementation is the simplest, but it is token forwarding prohibited by the specification. Audit trails, rate limiting, and trust boundaries collapse together.
- "Truncating results solves the size problem completely." While token counts decrease, if the fact and scope of the truncation are not communicated, the agent believes a part to be the whole and draws conclusions.
- "Since MCP has become stateless, state must not be kept on the server." The name makes it sound that way, but state can be kept. Instead of binding it to the connection, bind it to explicit handles and check permissions for each handle.
- "Tools hidden from the list cannot be called." Because they disappear from the screen, they appear to be blocked, but list filtering is for convenience. Actual blocking is performed by server-side authorization checks on every call.
Summary at a glance
- Tools are ACIs. Eliminate error-prone inputs from the format (absolute paths, absolute values, unit-inclusive names).
- Create a small number of tools based on workflow units rather than endpoint units, and distinguish them with namespaces.
- Keep results to fields needed for the next action, manage detail with
response_format, and control size through pagination, filters, truncation notices, and references. - Handle business errors with
isErrorand recovery instructions. For errors where execution status is unknown, query rather than retry. - Divide changes that are difficult to revert into preview and confirmation stages, and make them idempotent.
- MCP 2026-07-28 is stateless. Versions and capabilities in
_metaare mandatory; state is handled via handles, and handles are not permissions. - Enforce maximum timeouts regardless of progress notifications, and consider the Tasks extension for long-running operations.
- Default values for annotations are conservative, and do not trust annotations from untrusted servers.
- Prohibit token forwarding, escalate step-by-step from minimal scope, and perform server-side authorization checks on every call.
Check the official docs
- Anthropic: Writing effective tools for agents — Tool selection, namespaces, meaningful results, token efficiency, errors, and evaluation-based improvement
- Anthropic: Building effective agents — ACI and poka-yoke in the appendix
- MCP 2026-07-28: Specification — Components and safety principles
- MCP 2026-07-28: Base protocol — Stateless model,
_meta, and authentication scope - MCP 2026-07-28: Tools — Tool definitions, results, errors, state handles, and security requirements
- MCP 2026-07-28: Key changes — Differences from previous editions and deprecated features
- MCP: Security best practices — Prohibiting token forwarding, minimizing scope, handle hijacking, and local servers
- MCP: Client best practices — Progressive discovery, caching, and programmatic tool calling
- MCP — Authorization (2026-07-28): Check protected resource metadata (RFC 9728) and mandatory
resourceparameters (RFC 8707), and why dynamic client registration remains only for backward compatibility. - MCP — About the MCP Registry: Check whether the official MCP Registry is still in the preview stage and review precautions prior to the official release.
- Anthropic — Computer use tool: Check the request format for
computer_toolset_20260801and the models and platforms that continue to acceptcomputer_20251124. - OpenAI — Latest model guide: Check freeform inputs and context-free grammar constraints for custom tools.
Self-check
2-1. Explain why APIs convenient for human developers and good tools for agents differ, from the perspectives of context cost and selection errors.
2-2. What problem does a parameter for selecting response granularity (such as response_format) solve, and when should an agent choose a detailed response?
2-3. Explain the two pieces of information that must be recorded within the result when a tool truncates and returns a result, and the mistake an agent makes when they are absent.
2-4. Name three pieces of information that the server must not pull from previous requests on the same connection in the 2026-07-28 specification, and state where that information is carried instead.
2-5. How does a client assume the behavior of a tool that has no annotations at all? Explain in connection with the annotation default values in the specification.
2-6. Explain in one sentence each why token forwarding breaks audit trails and rate limiting.
2-7. Build an agent tool for the "Extend Loan" function of an in-house book rental system. To make it difficult to misuse, specify the tool name, parameters (including format), one business error and its message, and the condition requiring human confirmation.
Hands-on tasks
Exercise
Redesigning and measuring one tool (60 minutes)
- Choose one tool that agents use frequently or make frequent errors with.
- Select 20 tasks from actual usage logs and divide them into 15 for improvement and 5 for validation.
- Run them with the current tool and record the number of tool calls, tokens, and tool errors per task.
- Redesign the tool using the principles of this chapter (workflow units, parameter names containing units, default counts and truncation notices, errors with recovery instructions).
- Re-run both improvement and validation tasks, and compare the three metrics.
Done when: Completed if two or more of the three metrics improve on the validation tasks and the task success rate does not drop. If they did not improve, there must be a record of finding the point in the transcript where the model misunderstood the tool and revising the description.
Exercise
Creating a permissions table and server-side checks (45 minutes)
- List all tools of one production MCP server (or toolset).
- For each tool, record in a table whether it is read/write, its reversibility, required scopes, and annotations to attach.
- Separate the minimal set of scopes (at initial connection) from scopes that require step-up escalation.
- Select one write tool, write server-side check code that verifies the caller's authorization against the target resource, and determine the error message for unauthorized calls.
Done when: Completed if the test where calls from unauthorized users are rejected by server checks passes, and scopes and annotations for all tools are documented in the table without omission.