Tools: Letting the Model Act

Intermediate 🕐 30 min Lesson 4 of 11
What you'll learn
  • Explain the difference between protocol errors and execution errors in MCP tools
  • Describe the stateful handle pattern for modeling multi-step tool interactions
  • List the human-in-the-loop requirements the MCP spec places on host applications

What Makes a Tool

A tool is a named, typed function that an AI model can call. When the model encounters a situation where it needs information it cannot generate itself — the current weather, the contents of a file, the result of a database query — it calls a tool. The tool executes, the result comes back, and the model incorporates it into its response.

Tools are model-controlled. This distinguishes them from the other two MCP primitives. Resources are controlled by the application (the host decides when to include them). Prompts are controlled by the user (the user picks which one to apply). Tools are controlled by the model: the LLM reads the tool descriptions and decides autonomously which tool to call, with which arguments, and when.

This autonomy is powerful and comes with responsibility. Because the model decides when to call a tool, and tools can have real-world side effects (writing files, sending emails, charging a card), the protocol requires that applications provide humans with meaningful oversight. We will return to this in the human-in-the-loop section.

Tool Definition Anatomy

Every tool is defined by a set of fields. Some are required; others add richness that improves model behavior and user experience.

  • name (required) — the identifier used in tools/call. Must match exactly what the discovery listed.
  • title (optional) — a human-readable display name for UIs. Distinct from name, which is for the protocol.
  • description (optional but critical) — explains what the tool does, when to call it, what its arguments mean, and what it returns. The model reads this description to decide whether and how to use the tool. A vague or misleading description produces bad tool calls. Write descriptions as if you are explaining the tool to a smart colleague who cannot read the implementation.
  • inputSchema — a JSON Schema object describing the tool's parameters. Must be of type object. For tools with no parameters, use {"type": "object", "additionalProperties": false}. The schema is used by the model to understand what arguments to provide and by the server to validate them.
  • outputSchema (optional) — a JSON Schema describing the structured result. When present, the tool should also return the result as a text block for backward compatibility with clients that do not support structured outputs.
  • annotations (optional) — behavioral hints such as whether the tool is read-only, whether it is destructive, or whether it is idempotent. These hints are advisory: the protocol does not enforce them, and they are only as trustworthy as the server that declares them.

Naming Your Tools

Tool names must be unique within a server. The protocol recommends names between 1 and 128 characters, using only letters, digits, underscores, hyphens, and periods. Names should be descriptive and unambiguous — the model uses the name in combination with the description to understand what a tool does.

When a host aggregates tools from multiple servers, it must handle name collisions. The common pattern is to prefix each tool name with the server identifier: filesystem__read_file and github__read_file are both read_file at the server level, disambiguated by the host. As a server author, you do not need to build in this prefix — the host adds it. But you should keep your tool names clearly scoped to what your server does, to make disambiguation straightforward.

Listing Tools

Clients discover a server's tools by sending a tools/list request. The server returns an array of tool definitions, paginated if the list is long. The result includes a nextCursor field when there are more tools to fetch.

Servers should return tools in a deterministic order — the same order every time. This matters for LLM prompt caching: if the host includes the tool list in a cached prefix of the system prompt, a non-deterministic order would invalidate the cache on every request, adding cost and latency.

If a server declares "tools": {"listChanged": true}, it may send a notifications/tools/list_changed notification when the tool list changes. Clients that subscribe to this notification should re-fetch the tool list when they receive it, so the model always has an up-to-date view of available tools.

Calling a Tool

A tool call is a tools/call request with the tool's name and a JSON object of arguments:

{
  "jsonrpc": "2.0",
  "id": "5",
  "method": "tools/call",
  "params": {
    "name": "get_forecast",
    "arguments": {
      "latitude": 37.77,
      "longitude": -122.42
    }
  }
}

The tool name in the request must match the name in the discovery response exactly. Hosts that prefix tool names for disambiguation must strip the prefix before forwarding the call to the server.

Result Content Types

A tool call response contains a content array. Each element of the array is a typed content block. The supported types are:

  • text — a plain or Markdown string. This is the most common result type.
  • image — a base64-encoded image with a declared MIME type (e.g., image/png). The model can read image content in multimodal contexts.
  • audio — a base64-encoded audio clip with a MIME type. Used for voice or sound results.
  • resource_link — a URI the client can fetch independently or subscribe to. Useful for large results that should not be inlined.
  • resource — an embedded resource with URI, MIME type, and either text or base64 content. This avoids a separate network round trip for small resources.

All content block types accept an optional annotations field with an audience array (["user"], ["assistant"], or both) and a priority from 0 to 1. Hosts use these annotations to decide how prominently to show each block to the user and how much context to allocate to it.

Two Kinds of Errors

MCP distinguishes between two fundamentally different error situations, and conflating them is a common source of bugs.

Protocol errors are JSON-RPC errors — messages where the response has an error field instead of a result. These indicate that something went wrong at the protocol level: the tool name does not exist, the arguments are malformed, the server crashed, or the client sent an invalid request. The error code -32602 (Invalid params) covers cases like an unknown tool name. Protocol errors are hard for the model to recover from, because they typically indicate a logic error in the client or server rather than a user-correctable problem.

Execution errors are tool results with "isError": true in the content. These indicate that the tool ran, understood the request, and encountered a problem during execution — a network timeout, an invalid date that failed validation, a file that does not exist. The result is returned as a normal content array, with isError: true to signal the problem. The model can read this error message and decide to retry with corrected arguments, ask the user for clarification, or explain the problem in its response.

-- Protocol error (the tool name does not exist)
{ "error": { "code": -32602, "message": "Unknown tool: get_wether" } }

-- Execution error (the tool ran but the city was not found)
{ "result": { "content": [{"type": "text", "text": "No forecast found for coordinates 999, 999"}], "isError": true } }

The key distinction: protocol errors tell the host that something is broken; execution errors tell the model that something went wrong in the external world and give it information to work with.

The Stateful Tool Handle Pattern

MCP is a stateless protocol — the server does not maintain session state between calls. But many real-world tools are inherently stateful: you create a resource, operate on it, and eventually clean it up. How do you model this without server-side session state?

The answer is the handle pattern. A creation tool (e.g., create_session) creates a server-side resource and returns an opaque handle — a string identifier like a UUID. The model passes this handle back to subsequent tools (query_session, close_session) as an argument. The server looks up the resource using the handle. The state lives in the server's backing store (a database, a cache, an in-memory map), not in the protocol session.

Handles should be opaque: clients should not parse or construct them, only pass them around. The server should document their lifetimes — how long a handle remains valid — and return a clear error when an expired handle is used. This gives the model actionable information: it knows to create a new session rather than retry with the old handle.

Human-in-the-Loop Requirements

Because tools can have real-world consequences, the MCP specification places explicit obligations on host applications:

  • Applications should show users which tools are exposed, so they can make informed decisions about what the model can do.
  • Applications should mark tool invocations visually in the UI, so users can see when the model is about to act.
  • Applications must provide a mechanism for users to deny or confirm tool invocations, particularly for destructive or sensitive operations.

These requirements apply to the host, not to the server. As a server author, your responsibility is to describe your tools accurately (especially in annotations, where you can flag destructive or non-idempotent behavior) so hosts can present appropriate UI. As a host author, you must implement the approval flow.

In practice, most hosts use a tiered model: read-only tools run automatically, but tools that write, delete, or call external APIs require user confirmation before they execute.

Security Responsibilities

Both servers and clients have security obligations around tools.

Servers must: validate all input arguments against the declared schema before execution; enforce access controls (do not let the model call a tool on data the user is not authorized to access); rate-limit tool calls to prevent abuse; and sanitize outputs before returning them, to prevent prompt injection attacks where a tool result contains instructions that hijack the model's behavior.

Clients must: confirm sensitive operations before forwarding them to servers; display what arguments will be sent so users can verify; set timeouts on tool calls to prevent hangs; and log tool usage for auditing.

Tool annotations (like readOnly: true or destructive: true) are advisory — a malicious or buggy server could lie. Hosts should not make security decisions based solely on annotations. Trust what you observe, not what the server claims.

Key takeaways
  • Tools are model-controlled — the LLM decides when and how to call them, not the application
  • Protocol errors (JSON-RPC error field) signal broken protocol; execution errors (isError: true) signal runtime failures the model can reason about
  • Stateless MCP servers handle multi-step workflows through handles — opaque identifiers returned by creation tools and passed to subsequent calls
Learn more every week Get 5 hand-picked prompts + new AI tools every Monday. Free.