Sub topic 10
Designing tools a model can use well
This chapter assumes you can write a basic MCP tool with the Python SDK, that you know how JSON Schema describes inputs, and that you have seen how a model chooses a tool during a tool-calling loop. Chapter 5 built a first tool. Chapter 6 covered typed inputs. Here the question is different: given a working tool, how do you shape it so a model picks it at the right time, fills in its arguments correctly, and recovers when something goes wrong?
The model sees only your metadata
A model never reads your function body. It sees three things for each tool: the name, the description, and the input schema. Everything it knows about when to call the tool and how to fill in arguments comes from those. A tool that works for you in a debugger can still fail with a model because the metadata is vague.
In the Python SDK these three things come from the function:
- The function name becomes the tool name.
- The docstring becomes the description.
- The type hints and
Fieldannotations become the input schema.
Design work is mostly the work of making these three parts precise.
Naming tools
Names are the strongest signal a model has when choosing between tools. Follow these rules:
- Start with a verb that says what happens:
get_,list_,search_,create_,restart_. - Name the object the tool acts on:
get_service_owner, notownerorlookup. - Keep names distinct. If
get_deployandfetch_deploymentboth exist, the model has to guess. - Use one style everywhere, such as
snake_case. Some hosts restrict the allowed characters, so avoid spaces and punctuation other than_and-. - Do not put your server name in each tool name. Hosts already show which server a tool belongs to, and many prefix it automatically.
| Weak name | Better name | Reason |
|---|---|---|
| `deploys` | `list_deploys` | The verb tells the model it returns a collection |
| `handle_incident` | `create_incident` | "Handle" hides what the call changes |
| `do_restart` | `restart_worker` | Names the object being restarted |
| `info` | `get_service_owner` | Says what information comes back |
Writing descriptions
The description answers three questions: what does the tool do, when should it be used, and what does it return? A one-line docstring is a good start, but ambiguity often needs more.
from typing import Annotated, Literal
from mcp.server.fastmcp import FastMCP
from pydantic import Field
mcp = FastMCP("team-tools")
DEPLOYS = {
"staging": ["v1.4.2", "v1.4.1", "v1.4.0"],
"production": ["v1.4.0", "v1.3.9"],
}
@mcp.tool()
def list_deploys(
environment: Literal["staging", "production"],
limit: Annotated[
int, Field(ge=1, le=20, description="How many versions to return")
] = 5,
) -> list[str]:
"""List the most recent deployed versions for an environment, newest first.
Use this to answer "what is running in staging?" or "what shipped last?".
Returns version tags only. It does not return commit hashes or deploy times.
"""
return DEPLOYS[environment][:limit]Notice the last sentence. Saying what the tool does not return stops the model from expecting commit hashes and guessing them when they are missing. When two tools sit near each other, say which one to prefer: "To read a runbook, use runbook://{service} instead."
Designing parameters
Parameters are where most real failures happen. A model fills them from the conversation, and it will invent values if the schema lets it.
- Constrain with types. Use
Literalfor fixed choices, andgeandlefor numeric ranges. The SDK turns these into JSON Schemaenum,minimum, andmaximum, and the server rejects invalid values before your function runs. - Describe each parameter. Add
Field(description=...)with the format and an example, such as "Short service name, for examplebilling". - Use as few required parameters as possible. Give optional parameters sensible defaults, as
limitdoes above. - Accept what the user has, not what your system uses internally. If people say "billing" but your API wants a UUID, resolve the name inside the tool. Do not ask the model to look up IDs first.
- Avoid flags that change the tool's meaning. A
modeparameter that switches between reading and deleting hides a dangerous action behind a string. Split it into two tools.
A good check is to read the schema as if you had never seen the code. If you could not fill in every field correctly from the schema alone, the model cannot either.
One tool per task, not per endpoint
It is tempting to wrap each internal API endpoint as its own tool. This gives the model dozens of low-level tools and forces it to chain them correctly. Design around what a person wants to accomplish instead.
Suppose answering "who should I page for billing?" takes three internal calls: resolve the service, fetch the on-call schedule, and fetch the contact. Expose one tool, get_oncall_contact(service), that does all three. The model makes one decision rather than three, and there are fewer places to make a mistake.
Balance this against the opposite problem. A single tool with fifteen optional parameters is hard to describe and hard to call correctly. A reasonable target is a tool that does one task and has fewer than about six parameters. If the description needs the word "or" to explain what it does, consider splitting it.
Also keep the total tool count modest. Every tool's metadata takes space in the model's context, and a long list makes selection less reliable. If your team has many tools, group them into several focused servers and let each user enable only what they need.
Designing results
What you return is as important as what you accept. The result goes back into the model's context, so shape it for reading, not for completeness.
- Return only what is needed. A raw API response with 40 fields wastes context and can distract the model. Select the fields that answer the question.
- Use readable identifiers. Return
"payments-team"rather than an internal ID that the model cannot explain to the user. - Cap and say so. If you truncate a long list, include that fact: "Showing 20 of 134 results. Narrow the search with
query." - Be consistent. Return the same shape every time, so the model does not need to handle several formats.
- Prefer structured output for data, text for narrative. Chapter 6 covered structured results. A list of deploys suits a list. A log excerpt suits plain text.
@mcp.tool()
def search_services(
query: Annotated[str, Field(min_length=2, description="Part of a service name")],
limit: Annotated[int, Field(ge=1, le=50)] = 10,
) -> dict:
"""Search services by name. Returns matching names and owning teams.
If more services match than `limit`, `truncated` is true and the model
should ask for a more specific query.
"""
owners = {"billing": "payments-team", "search": "discovery-team"}
matches = [
{"service": name, "owner": owner}
for name, owner in owners.items()
if query.lower() in name
]
return {
"results": matches[:limit],
"total": len(matches),
"truncated": len(matches) > limit,
}Because total and truncated are in the result, the model knows whether it has seen everything.
Writing errors that guide the next step
When a call fails, the model reads the error message and decides what to try next. A message like KeyError: 'bill' gives it nothing. A message that names the problem and the valid options lets it fix the call without involving the user.
SERVICES = ["billing", "search", "checkout"]
@mcp.tool()
def get_service_status(service: str) -> str:
"""Return the current status of a service by its short name."""
if service not in SERVICES:
raise ValueError(
f"Unknown service '{service}'. Valid services: {', '.join(SERVICES)}. "
"Use search_services to find a name."
)
return f"{service}: healthy"The error does three things: it states what was wrong, lists valid values, and points to the tool that helps. Chapter 8 covers how these errors reach the client as tool result errors. Never include stack traces, secrets, or internal hostnames in the message, since the text is visible to the model and often to the user.
Reads, writes, and side effects
Tools that change things need extra care, and your descriptions should make the difference obvious.
- State plainly in the description when a tool modifies data: "Restarts the billing worker. This interrupts in-flight jobs."
- Keep read tools and write tools separate, so a host can allow reads automatically and ask for confirmation on writes.
- Make writes idempotent where you can. If the model retries after a timeout, a second call should not create a duplicate.
- Return what changed, such as "Restarted worker billing-1. It was last restarted 3 days ago," so the model can report accurately.
MCP lets a tool declare hints about its behavior, such as whether it is read-only or destructive. Hosts may use these to decide how to prompt the user, but treat them as advisory. Chapter 13 covers enforcement, which must happen in your server.
A design workflow
Test with the way people actually ask, not the way you would write a function call. "Who owns billing?" and "which team looks after the billing stuff" should both lead to get_service_owner. When a prompt fails, look at the tool list from the model's point of view. Chapter 11 shows how to use the MCP Inspector to see exactly the metadata a host receives.
Common mistakes
- Vague descriptions such as "Gets data". The model cannot tell when to use it.
- Overlapping tools with similar names and no guidance on which to prefer.
- Free-form strings for values that have a fixed set. Use
Literal. - Internal IDs as required inputs, forcing the model to chain lookups.
- Huge outputs that fill the context and bury the answer.
- Opaque errors that leave the model retrying the same bad call.
- Hidden side effects in a tool that sounds like a read.
Exercise
A teammate wrote def run(action: str, target: str) -> dict with the docstring "Runs an action." It accepts "status", "restart", and "delete", and returns the full API response. Name four design problems and say how you would fix them.
Show answer
(1) The name and description are vague, so the model cannot tell when to use it. Rename and describe specific tools. (2) action is a free-form string that switches between reads and destructive writes. Split into get_service_status, restart_service, and delete_service, so hosts can require confirmation only for the writes. (3) target has no constraint or description. Use a Literal or a documented format with an example. (4) Returning the full API response wastes context. Return only the needed fields, and note when results are truncated. Errors should also list valid values.
Exercise
Users ask "who do I page for billing?" Your API needs three calls to answer: resolve the service ID, fetch the schedule, fetch the contact. Should you expose three tools or one? Why?
Show answer
Expose one tool, such as get_oncall_contact(service), that makes the three calls internally and accepts the short name people use. The model then makes one decision with one required argument, which means fewer chances to pick the wrong tool or pass an internal ID incorrectly.