FastMCP · Chapter 2 of 6
FastMCP tools: validated arguments, results and errors
13 min study · Examples checked with FastMCP 4.2 and MCP Python SDK 2.3 on Python 3.14 ·
A tool is a public operation that another program, potentially guided by a model, may call. Its name, description, parameter schema, and result need to agree. This chapter builds a study planner with bounded inputs, typed output, safe domain errors, and request context. It also distinguishes tool failure from a broken transport.
Start from a small operation
The planner selects complete lessons that fit an available time budget. It does not edit the catalog or claim that a learner completed anything. Making that scope explicit gives the tool a clear contract and makes its behavior easy to test.
In a fresh directory, create server.py:
from typing import Annotated, Literal
from fastmcp import FastMCP
from fastmcp.dependencies import CurrentContext
from fastmcp.exceptions import ToolError
from fastmcp.server.context import Context
from pydantic import BaseModel, Field
mcp = FastMCP("Study planner", mask_error_details=True)
class PlannedLesson(BaseModel):
title: str
minutes: int = Field(ge=1)
class StudyPlan(BaseModel):
topic: str
lessons: list[PlannedLesson]
total_minutes: int
remaining_minutes: int
CATALOG = {
"python": [("Functions", 12), ("Collections", 15), ("Exceptions", 10)],
"fastapi": [("Routing", 10), ("Validation", 15)],
"django": [("Models", 15), ("Forms", 12)],
}
@mcp.tool(annotations={"readOnlyHint": True, "idempotentHint": True})
async def plan_study(
available_minutes: Annotated[int, Field(ge=5, le=180)],
topic: Literal["python", "fastapi", "django"] = "python",
ctx: Context = CurrentContext(),
) -> StudyPlan:
"""Select complete lessons in catalog order within a time budget; never change progress."""
selected = []
remaining = available_minutes
for title, minutes in CATALOG[topic]:
if minutes <= remaining:
selected.append(PlannedLesson(title=title, minutes=minutes))
remaining -= minutes
if not selected:
minimum = min(minutes for _, minutes in CATALOG[topic])
raise ToolError(f"No complete lesson fits. Increase available_minutes to at least {minimum}.")
await ctx.report_progress(progress=1, total=1)
return StudyPlan(
topic=topic, lessons=selected,
total_minutes=available_minutes - remaining,
remaining_minutes=remaining,
)
if __name__ == "__main__":
mcp.run()
The minimum budget permits a five-minute request, but the current catalog has no lesson that short. That is a validly shaped request with a domain-level failure, which is different from a negative budget. The error calculates the selected topic’s shortest duration and tells the caller how to change its request.
Inspect the generated boundary
FastMCP derives input and output schemas from the declarations. The Literal limits supported topics, Field bounds the budget, and the Pydantic classes describe the response. ctx is injected through CurrentContext() and is excluded from the public input schema. The caller should never have to construct a framework context object.
A strict contract begins with named parameters. Tools do not support arbitrary *args and **kwargs because callers need a discoverable schema. Avoid accepting a dictionary of undocumented options merely to bypass that requirement. If an option has a stable meaning, name it and constrain it.
Types constrain shape; the function enforces the planning rule. A model may propose arguments, but the server must validate them just as it would validate a handwritten client. It should not assume that a host’s UI already checked them.
Exercise success and failure paths
Create client.py:
import asyncio
from fastmcp import Client
from server import mcp
async def main():
async with Client(mcp) as client:
tools = await client.list_tools()
schema = tools[0].input_schema
assert "ctx" not in schema["properties"]
success = await client.call_tool("plan_study", {"available_minutes": 30})
print(success.structured_content["total_minutes"])
for minutes in (0, 5):
result = await client.call_tool(
"plan_study", {"available_minutes": minutes}, raise_on_error=False
)
assert result.is_error
print("Both invalid and unworkable requests were rejected")
if __name__ == "__main__":
asyncio.run(main())
Run python client.py. A 30-minute Python budget selects Functions and Collections, totaling 27 minutes. The planner follows catalog order rather than solving an optimization problem. If maximizing lesson count or matching prerequisites becomes necessary, change and document that business rule instead of silently changing the algorithm.
Read results at the right level
content contains MCP display blocks. structured_content contains machine-readable output. data provides the client’s decoded Python value; typed results may be reconstructed objects rather than dictionaries. Use the structured dictionary when you need stable field access independent of that reconstruction.
The Python SDK uses names such as input_schema, structured_content, and is_error. Wire-level JSON and older tutorials can show camelCase equivalents. Keep the protocol’s spelling separate from the current Python model’s attribute names instead of relying on deprecated aliases.
An ordinary tool error is reported through an error-marked result. By default, client.call_tool() raises for such a result; raise_on_error=False lets a caller inspect it explicitly. Connection errors, unknown protocol methods, and tool-domain failures are different categories. Do not convert every exception into a successful-looking dictionary with an error key.
Keep errors and execution limits deliberate
Use ToolError for an expected inability to complete the operation and give a safe corrective message. mask_error_details=True conceals unexpected internal exception details, but explicit ToolError messages remain visible. Do not include credentials, raw database queries, or another user’s record in those messages. See FastMCP tool behavior.
The injected context can report progress during real work. This example sends one completion update; a longer operation should use meaningful bounded stages rather than emit an update for every tiny record. Standard Python logging is suitable for local diagnostics. Older MCP logging callbacks have version-specific behavior, so do not make them the only observability path.
Current FastMCP runs synchronous tool functions in a worker thread by default. An async tool must still avoid blocking the event loop: use an async library or explicitly offload blocking I/O. A timeout or disconnected client does not prove a remote write was undone. For state-changing tools, define durable outcomes and retry semantics before adding automatic retries.
Practice
Add tests for an unsupported topic, a budget above 180, exact-fit input, and a valid request that fits nothing. Change one topic’s shortest duration and confirm its no-fit message changes with it. Check both schema rejection and domain errors through the client.
Answer check: 27 minutes selects the first two Python lessons exactly; a zero budget fails validation; a five-minute Django request reports that at least 12 minutes are needed. No call changes learner progress.
Summary
A useful tool has a narrow operation, a complete schema, a predictable output, and failures the caller can act on. Request context supports execution; it should not leak into the caller’s argument contract.