Defining Tools: Schemas, Validation, and Error Responses
- Use Literal, Optional, and default values in type hints to generate constrained tool schemas
- Write tool descriptions that specify preconditions, expected inputs, and what the LLM should do next
- Raise ValueError inside a tool function to produce a tool execution error with an actionable message
- Implement the handle pattern for tools that need state across multiple calls
The Tool Schema in Full
When a client calls tools/list, the server returns a JSON array of tool definitions. Each definition has these fields:
name— unique identifier, 1–128 characters, letters/digits/underscore/hyphen/dot only, no spacestitle— optional human-readable display name (shown in UI, not passed to the LLM)description— what the tool does and when to use it; this is the only description the LLM readsinputSchema— a JSON Schema object defining expected parametersoutputSchema— optional JSON Schema for the return value, used for validation
FastMCP generates all of this from your function signature and docstring. The name comes from the function name; the description from the docstring; the input schema from the type hints.
Richer Type Hints for Better Schemas
Basic type hints (str, int, bool) produce minimal schemas. More specific hints produce schemas with constraints that help the LLM pass correct arguments and that the server can validate before executing the tool.
Using Python's type system to constrain inputs:
from typing import Literal
from fastmcp import FastMCP
mcp = FastMCP("Demo")
@mcp.tool
def search_notes(
query: str,
sort_by: Literal["date", "title", "relevance"] = "date",
max_results: int = 10,
) -> str:
"""Search saved notes by keyword.
Args:
query: The search term to look for in note titles and content.
sort_by: How to order the results.
max_results: Maximum number of notes to return (1-50).
"""
...
This generates a schema with sort_by as an enum restricted to three values and max_results as an integer with a default of 10. The LLM sees these constraints and is more likely to pass valid arguments.
For optional parameters with no default, use Optional[str] = None. FastMCP marks these as not required in the schema, so the LLM can call the tool without providing them.
Writing Good Descriptions
The description is the most important part of a tool definition. The LLM uses it to decide which tool to call, what arguments to pass, and whether the tool is relevant to the current task. These two descriptions define the same tool differently:
Weak: "Get note." The LLM does not know what parameters are needed or what it gets back.
Strong: "Retrieve the full text content of a saved note by its numeric ID. Returns the title, creation date, and body text. Use list_notes first to find the correct ID." This tells the LLM when to use it, what it needs, and what it returns.
Mention preconditions in the description. If get_note requires a valid ID from list_notes, say so. The LLM reads this and plans accordingly — it will call list_notes first if it does not already have an ID.
The Two Error Types
MCP distinguishes two categories of error, and the distinction matters for how your agent handles them.
Protocol errors are JSON-RPC level failures — the tool name does not exist, the request was malformed, the server crashed. These arrive as JSON-RPC error objects at the transport level. The LLM typically cannot recover from these; they indicate a programming error in the host or server.
Tool execution errors are failures during tool execution that the LLM can reason about and potentially retry with different arguments. These are returned as normal tool results with "isError": true in the response. Examples: a file path that does not exist, an invalid date format, a note ID that was deleted.
In FastMCP, you produce a tool execution error by raising an exception in the tool function:
@mcp.tool
def get_note(note_id: int) -> str:
"""Retrieve the full content of a note by its ID."""
notes = _load()
for note in notes:
if note["id"] == note_id:
return f"# {note['title']}
{note['content']}"
raise ValueError(f"Note {note_id} does not exist. Call list_notes to see available IDs.")
FastMCP catches the exception and wraps it in a proper error response. The LLM receives the message "Note 7 does not exist. Call list_notes to see available IDs." as a tool result with isError: true. A capable model can read this, call list_notes to find valid IDs, and retry with the correct one.
The rule: raise for recoverable errors (bad input, missing data) with a message that tells the LLM how to fix it. Do not raise for unrecoverable server-side failures that the LLM cannot act on — log those and return a neutral message instead.
Stateful Tools and the Handle Pattern
MCP is stateless — the server does not remember anything between calls. Tools that need to maintain state across multiple calls (an open file, a database transaction, a running process) must use the handle pattern: return an identifier from the creation step and require it as a parameter on subsequent steps.
Example: a tool that opens a file for sequential reading:
import uuid
OPEN_FILES: dict = {}
@mcp.tool
def open_file(path: str) -> str:
"""Open a file for reading and return a handle for subsequent read calls."""
p = Path(path)
if not p.exists():
raise FileNotFoundError(f"File not found: {path}")
handle = str(uuid.uuid4())[:8]
OPEN_FILES[handle] = p.read_text().splitlines()
return f"File opened. Handle: {handle}. Lines: {len(OPEN_FILES[handle])}"
@mcp.tool
def read_lines(handle: str, start: int, count: int = 20) -> str:
"""Read lines from an open file. Use the handle returned by open_file."""
if handle not in OPEN_FILES:
raise ValueError(f"Handle {handle} not found. Call open_file first.")
lines = OPEN_FILES[handle][start:start + count]
return "
".join(lines)
The LLM calls open_file, receives a handle like a3f9b1c2, and uses that handle in subsequent read_lines calls. The server stores the file contents in memory under that handle. This is the standard pattern for multi-step operations.
Important: in-memory handles are lost when the server restarts. For handles that must survive restarts, store them in a file or database. Set an expiry policy and return a clear error when an expired handle is used.
Tools With No Parameters
Tools with no parameters are valid but require a specific schema. An empty inputSchema must still be a valid JSON Schema object:
@mcp.tool
def clear_notes() -> str:
"""Delete all saved notes. This action cannot be undone."""
_save([])
return "All notes cleared."
FastMCP generates the correct empty-object schema automatically. If you are writing the schema by hand, use {"type": "object", "additionalProperties": false} — this explicitly accepts only empty objects, which is the clearest signal to the LLM that no arguments are needed.
Tool Naming Conventions
Tool names should be short, lowercase, and use underscores. Descriptive verb-noun pairs work well: add_note, search_files, fetch_url. Avoid generic names like do_thing or process. If you are building a server that will be used alongside other servers, prefix names with the server's domain to avoid collisions: notes_add, notes_list, notes_get. Two servers both exposing a search tool create ambiguity for the LLM.
- Tool execution errors (raised exceptions, isError: true) are actionable feedback the LLM can reason about — write the error message as a recovery instruction, not a debug log
- Protocol errors (JSON-RPC level) mean a programming mistake in the host or server — the LLM cannot recover from them
- The docstring on the tool function is the entire description the LLM receives — mention preconditions, what the tool returns, and what to call next
- In-memory handles are lost on server restart — for persistent handles, store them in a file or database and document the expiry policy in the tool description
Progress is saved in this browser only — clear your cache or switch device and it's gone. Create a free account and it follows you everywhere.