FastMCP turns Python signatures into JSON Schema. That is convenient, but it also means vague types produce a vague tool contract. Pydantic constraints and field descriptions are the difference between a model guessing and a model succeeding.
A contract worth exposing
from typing import Annotated, Literal
from mcp.server.fastmcp import FastMCP
from pydantic import Field
mcp = FastMCP("issue-tools")
@mcp.tool()
def search_issues(
query: Annotated[str, Field(min_length=2, max_length=120, description="Plain words to search for.")],
state: Annotated[
Literal["open", "closed", "all"],
Field(description="Issue state filter."),
] = "open",
limit: Annotated[int, Field(ge=1, le=50, description="Maximum number of results, 1-50.")] = 10,
) -> str:
"""Search a repository issue tracker.
Use this when the user names a symptom or feature. The tool returns
identifiers and titles only; fetch details with get_issue.
"""
# Replace with a real API call. Keep credentials in the environment.
return f"searching {query!r} state={state} limit={limit}"
Annotated plus Field puts constraints and descriptions into the schema without burying them in prose. The Literal becomes an enum. The limits become minimum and maximum values. The default values tell the model it can omit those arguments.
Model the result, too
If your tool returns structured data, serialize a Pydantic model rather than hand-building a dictionary:
from pydantic import BaseModel
class IssueSummary(BaseModel):
id: int
title: str
state: Literal["open", "closed"]
url: str
@mcp.tool()
def get_issue(issue_id: int) -> str:
"""Fetch a single issue by numeric id."""
issue = IssueSummary(id=issue_id, title="Example", state="open", url="https://example.com")
return issue.model_dump_json()
Returning a JSON string keeps the result portable across clients. Keep payloads small and stable. If a field is unknown, use None with an optional annotation rather than inventing data.
Distinguish validation errors from operation errors
FastMCP and Pydantic reject malformed arguments before your function runs. That is the validation layer. Inside the function, handle domain failures explicitly:
@mcp.tool()
def close_issue(issue_id: int, reason: str) -> str:
"""Close an issue after human approval.
This is a destructive operation. Confirm the issue id before use.
"""
if not reason.strip():
raise ValueError("reason must explain the closure")
# Call the API and check the response.
return f"closed {issue_id}"
Use ValueError for invalid arguments that pass schema validation but violate domain rules. For authorization failures, do not return a success message. For upstream failures, return a concise message that names the dependency and status without exposing credentials.
Do not catch every exception and return "ok". That hides failures from the agent and from your monitoring.
Avoid these schema traps
dictorAnyparameters: they produce unconstrained JSON and invite arbitrary payloads. Define the fields you support.- Untyped lists: use
list[str]with a maximum length or a pagination cursor. - Boolean ambiguity: use an enum or a clearly named flag such as
include_closed, not a bareflag. - Implicit units: name fields
timeout_msand put the range in the description. - Secrets in arguments: credentials belong in server configuration, not model-generated input.
Validation and tests
Pydantic validates at the boundary, but you still need tests for:
- A valid minimal call.
- A missing required argument.
- An out-of-range limit.
- An invalid enum value.
- A domain rule failure.
- An upstream authorization error.
FastMCP’s tool functions are plain Python functions (aside from dependency injection for context), so call them directly in unit tests. Then exercise the server through Inspector or a client to verify that the schema and transport behave as expected.
Versioning the contract
Tool schemas are an API. Renaming a field or changing a type breaks prompts and client integrations. Prefer additive changes, keep old fields with deprecation notes for a release, and version breaking changes. Record the change in the server README so users can update their instructions.
A precise Pydantic contract reduces retries, makes errors actionable, and gives the client enough information to request approval for the right action. It is the Python equivalent of designing the interface before writing the implementation.
Sources
Sources were checked on Oct 23, 2026. Versions and client behavior can change; confirm the current documentation before relying on a configuration.