Sub topic 6
Tools: actions the model can invoke
This chapter assumes you have read the earlier chapters on hosts, clients, and servers, on JSON-RPC messages, and on the initialization handshake. You should be able to read a JSON-RPC request and a short Python function.
What a tool is
A tool is a function that a server exposes so that a language model can ask for it to be run. Tools are how an MCP session does things: add two numbers, query a database, create a ticket, or send a message.
Tools are described as model-controlled. The server publishes the list, and the model decides during a conversation whether to call one. The host application sits in the middle. It shows the tool definitions to the model, receives the model's request to call a tool, and then asks the client to send the call to the server. A well-built host also asks the user to approve calls that have side effects.
Compare this with the two other server features:
| Feature | Who decides to use it | Typical purpose |
|---|---|---|
| Tools | The model | Perform an action or computation |
| Resources | The application | Supply context to read |
| Prompts | The user | Start from a reusable template |
Use a tool when the result depends on arguments the model chooses, or when the call changes something in the outside world. If you only need to hand the model a fixed document, a resource is usually a better fit.
Declaring the capability
A server that offers tools must say so during initialization. In its initialize response it includes a tools entry in its capabilities. The listChanged flag states whether the server will send a notification when its tool list changes.
{"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-06-18", "capabilities": {"tools": {"listChanged": true}}, "serverInfo": {"name": "demo", "version": "1.0.0"}}}If the server does not declare tools, the client must not send tools/list or tools/call.
The anatomy of a tool definition
Each tool in the list has these fields:
name: a unique identifier within the server, such asadd.description: plain-language text that tells the model what the tool does and when to use it.inputSchema: a JSON Schema object that describes the arguments.title(optional): a human-readable display name.outputSchema(optional): a JSON Schema that describes structured results.annotations(optional): hints about behavior, such as whether the tool is read-only or destructive.
The description and inputSchema are what the model sees. They are the only information it has for choosing a tool and building arguments, so vague descriptions lead to wrong calls.
Discovering tools with tools/list
A client asks for the tools with tools/list. The response may be paginated, so it can include a nextCursor that the client sends back as cursor to get the next page.
{"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}{"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": "add", "description": "Add two numbers.", "inputSchema": {"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"]}}]}}Calling a tool with tools/call
To run a tool, the client sends tools/call with the tool's name and an arguments object. The server replies with a result that has the same id.
{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "add", "arguments": {"a": 2, "b": 3}}}{"jsonrpc": "2.0", "id": 3, "result": {"content": [{"type": "text", "text": "5"}], "isError": false}}The content field is a list of items. Each item has a type. The common types are text, image, audio, an embedded resource, and a link to a resource. A single result can mix them. A tool that returns a chart might return one text item with a summary and one image item with the picture.
A server may also return structuredContent, a JSON object that follows the tool's outputSchema. When a tool declares an output schema, clients can validate the data and use it in code without parsing text. For compatibility, a tool that returns structured content should also put a serialized copy in a text item.
The flow of one call
Two kinds of failure
Tool calls can fail in two different ways, and the protocol reports them differently. Mixing them up is the most common error when writing clients.
- Protocol errors are JSON-RPC
errorresponses. They mean the request itself was wrong: an unknown tool name, malformed arguments that fail schema checks, or a server fault. The response has anerrorobject with acodeand amessageand has noresult. - Tool execution errors mean the tool ran and failed. The server returns a normal
resultwithisErrorset totrueand an explanation incontent.
{"jsonrpc": "2.0", "id": 4, "result": {"content": [{"type": "text", "text": "Division by zero is not allowed."}], "isError": true}}{"jsonrpc": "2.0", "id": 5, "error": {"code": -32602, "message": "Unknown tool: multiply"}}The distinction matters because the model can usually recover from an execution error. The host passes the error text back to the model, which can fix its arguments and try again. A protocol error normally points to a bug in the client or server, and the model cannot repair it.
Writing a tool with FastMCP
With the official Python SDK, the FastMCP class builds the definition for you. It reads the function name as name, the docstring as description, and the type hints as inputSchema. The following server defines two tools. The second shows how to report an execution error.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("calc")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two integers and return the sum."""
return a + b
@mcp.tool()
def divide(numerator: float, denominator: float) -> float:
"""Divide numerator by denominator."""
if denominator == 0:
raise ValueError("Division by zero is not allowed.")
return numerator / denominator
if __name__ == "__main__":
mcp.run(transport="stdio")When divide raises an exception, FastMCP catches it and returns a result with isError set to true. The server process keeps running.
Type hints do real work here. The hint a: int becomes {"type": "integer"} in the schema, and the SDK validates incoming arguments against it before your function runs. Without hints, the model gets a schema with no type information and has to guess.
Calling tools from a client
The client side of a call is short. This script starts the server above as a subprocess, lists its tools, and calls both, checking isError on the second.
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
params = StdioServerParameters(command="python", args=["calc_server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
listing = await session.list_tools()
for tool in listing.tools:
print(tool.name, "-", tool.description)
ok = await session.call_tool("add", {"a": 2, "b": 3})
print(ok.isError, ok.content[0].text)
bad = await session.call_tool("divide", {"numerator": 1, "denominator": 0})
print(bad.isError, bad.content[0].text)
asyncio.run(main())Save the server as calc_server.py in the same directory and run the client with python. The first call prints False 5. The second prints True followed by an error message that includes the text of your exception.
Changes to the tool list
If the server declared listChanged: true, it sends a notifications/tools/list_changed message whenever its tools are added, removed, or altered. A notification has no id and expects no reply. On receiving one, the client should call tools/list again and refresh what the model can see. A server might change its list after the user signs in, for example, to reveal tools that need authorization.
Design guidance and edge cases
- Write descriptions for the model. Say what the tool does, what each argument means, and when not to use it. Keep tool names short and distinct.
- Keep schemas narrow. Use
enum,minimum, andrequiredto rule out bad input. The server must still validate, because the model's output is not trusted input. - Return useful errors. A message like "No file named report.txt in /data" lets the model correct itself. A bare "failed" does not.
- Limit result size. Everything a tool returns goes into the model's context window. Return summaries or page through results instead of dumping large files.
- Do not trust arguments. If a tool builds a shell command or SQL query from its arguments, use parameterized queries and avoid shell interpolation. A model can be steered by untrusted text it has read.
- Do not trust annotations. Hints such as
readOnlyHintanddestructiveHintare advisory. A client should treat them as trustworthy only when they come from a server it trusts. - Keep the number of tools modest. Each definition uses context tokens, and a long list makes it harder for the model to pick the right tool.
- Respect user consent. The host should show which tool is about to run and with what arguments, and it should let the user decline. Security and consent are covered in a later chapter.
Exercises
Exercise
A tool named read_file receives a path that does not exist. Should the server answer with a JSON-RPC error or with a result that has isError: true? Explain why.
Show answer
It should return a normal result with isError: true and a message such as "No file at that path". The tool was found and called correctly, and the failure happened during execution. The model can read the message, choose a different path, and call again. A JSON-RPC error is for protocol-level faults such as an unknown tool name or arguments that do not match the schema.
Exercise
You add a third tool to a running server that declared "tools": {"listChanged": true}. What should the server send, and what should the client do next?
Show answer
The server sends a notifications/tools/list_changed notification, which has no id. The client should respond by calling tools/list again and updating the tool definitions it gives to the model.