Sub topic 6
Typed inputs and structured results
This chapter assumes you have a working FastMCP server with one tool, as built in the previous chapter. It also assumes you can read JSON Schema and know basic Python type hints. Here you will see how type hints become the input schema a model reads, how to constrain arguments so bad calls are rejected early, and how to return results that are structured instead of free-form text.
Why schemas matter for tools
A tool call has two sides. The model decides which arguments to send, and your code receives them. The only thing the model knows about your tool is its name, its description, and its input schema. If the schema is loose, the model guesses. If the schema is tight, the model has fewer ways to be wrong, and the server can reject a bad call before your function runs.
MCP describes each tool's inputs with JSON Schema. The FastMCP helper in the official Python SDK builds that schema for you from your function signature. You write ordinary Python, and the SDK does the translation.
From type hints to JSON Schema
Consider the tool from the previous chapter:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("team-tools")
OWNERS = {"billing": "payments-team", "search": "discovery-team"}
@mcp.tool()
def get_service_owner(service: str) -> str:
"""Return the team that owns a service, given its short name."""
if service not in OWNERS:
raise ValueError(f"Unknown service: {service}")
return OWNERS[service]
if __name__ == "__main__":
mcp.run() # stdio transport by defaultThe server advertises this tool in response to a tools/list request. The schema it sends is roughly:
{
"name": "get_service_owner",
"description": "Return the team that owns a service, given its short name.",
"inputSchema": {
"type": "object",
"properties": {
"service": { "title": "Service", "type": "string" }
},
"required": ["service"]
}
}The mapping follows a few rules:
| Python | JSON Schema effect |
|---|---|
| Parameter name | Property name |
| `str`, `int`, `float`, `bool` | `string`, `integer`, `number`, `boolean` |
| No default value | Property listed in `required` |
| Default value | Property is optional and the default is included |
| `list[str]` | `array` with `items` of type `string` |
| `Literal["a", "b"]` | `enum` of the allowed values |
| Docstring | Tool `description` |
The exact output can differ slightly between SDK versions, for example in the title fields. Inspect the real output with the MCP Inspector, covered in a later chapter, rather than relying on this listing.
Constraining inputs with Literal and Field
A bare str tells the model almost nothing. Two tools fix that: Literal for a closed set of values, and Annotated with pydantic's Field for ranges and other limits.
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)] = 5,
) -> list[str]:
"""List the most recent deployed versions for an environment, newest first."""
return DEPLOYS[environment][:limit]
if __name__ == "__main__":
mcp.run()The resulting schema has two useful constraints:
environmentbecomes anenumof"staging"and"production". The model sees the only legal values. It cannot reasonably send"prod"or"Production".limitbecomes an integer withminimum: 1andmaximum: 20, plusdefault: 5.
Validation happens when the call arrives. The SDK checks the arguments against the function's types using pydantic. If the model sends limit=500, the call fails validation and your function body never runs. The model receives an error describing the problem, which it can use to correct the call.
Describing individual parameters
The docstring describes the tool as a whole. To describe one parameter, put a description in the Field:
from typing import Annotated
from pydantic import Field
@mcp.tool()
def find_runbook(
service: Annotated[
str,
Field(description="Short service name, lowercase, for example 'billing'."),
],
) -> str:
"""Return the runbook text for a service."""
return RUNBOOKS.get(service, "No runbook found.")Parameter descriptions are where you put format hints, units, and examples. They cost the model a few tokens and often prevent a whole class of wrong calls.
RUNBOOKS = {
"billing": "1. Check the queue depth.\n2. Restart the worker.\n3. Page payments-team.",
}Common constraints
| Need | Annotation | Column |
|---|---|---|
| Closed set of values | `Literal["a", "b"]` or an `Enum` | |
| Numeric range | `Annotated[int, Field(ge=1, le=20)]` | |
| String length | `Annotated[str, Field(min_length=1, max_length=64)]` | |
| Pattern | `Annotated[str, Field(pattern=r"^[a-z][a-z0-9-]*$")]` | |
| Optional value | `str \ | None = None` |
A pattern is especially useful for identifiers that you later pass to a shell command, a file path, or a query. Rejecting unexpected characters at the schema boundary is the first layer of defense, covered further in the security chapter.
Using a model class for complex inputs
When a tool takes several related fields, a pydantic model keeps the signature readable and gives the schema nested structure.
from typing import Literal
from pydantic import BaseModel, Field
class TicketRequest(BaseModel):
title: str = Field(min_length=5, max_length=120)
severity: Literal["low", "medium", "high"] = "medium"
labels: list[str] = Field(default_factory=list, max_length=5)
@mcp.tool()
def create_ticket(request: TicketRequest) -> str:
"""Create a ticket and return its identifier."""
return f"TICKET-{abs(hash(request.title)) % 10000}"The model must now send a single request object. Flat parameters are usually easier for models than nested objects, so use a model class when the fields truly belong together, not by default.
Structured results
So far the tools return a string or a list of strings. A model can read these, but your code cannot easily process them, and a list of strings loses field names. MCP supports returning structured content alongside the text content.
In the Python SDK, recent versions generate an output schema from your return type annotation. If you annotate the return type with a pydantic model, a TypedDict, or a dataclass, the SDK sends the data as structured content and also includes a text copy for clients that only read text. Structured output needs a recent SDK release, so check your installed version if the behavior differs.
from pydantic import BaseModel
class DeployInfo(BaseModel):
version: str
environment: str
deployed_by: str
healthy: bool
DEPLOY_DETAILS = {
("production", "v1.4.0"): DeployInfo(
version="v1.4.0",
environment="production",
deployed_by="dana",
healthy=True,
),
}
@mcp.tool()
def get_deploy(environment: str, version: str) -> DeployInfo:
"""Return details for one deployed version in an environment."""
key = (environment, version)
if key not in DEPLOY_DETAILS:
raise ValueError(f"No deploy {version} in {environment}")
return DEPLOY_DETAILS[key]The tool now advertises an outputSchema describing version, environment, deployed_by, and healthy. A client can validate the result and a program can read healthy as a boolean, not parse it out of prose.
Choosing a return type
| Return annotation | What the client receives |
|---|---|
| `str` | Text content only |
| `list[str]` | Structured content wrapped in a `result` field, plus a text copy |
| Pydantic model or dataclass | Structured object with an output schema |
| `dict[str, int]` | Structured object for a dict with typed values |
| No annotation | Text content, no output schema |
Primitive and list return types are wrapped in an object with a result key, because an output schema must describe an object.
Keep results small and useful
Everything a tool returns goes into the model's context. Practical rules:
- Return the fields the model needs for its next decision, not the whole database row.
- Cap list sizes with a
limitparameter, aslist_deploysdoes. - Prefer stable, descriptive field names such as
deployed_byover short codes. - Do not return secrets, tokens, or internal URLs unless the user needs them.
Common errors
- Missing type hints. An unannotated parameter produces a schema with no type, so the model and the validator both lose information. Annotate every parameter.
- Vague docstrings. A docstring of "Gets data" gives the model nothing to choose with. Say what is returned and when to use the tool.
Literalthat drifts from reality. If you add a"canary"environment in your data but not in theLiteral, the model cannot ask for it. Build theLiteralfrom the same source of truth, or add a test that compares them.- Returning
Noneimplicitly. A branch that forgets to return gives an empty result that looks like success. Return an explicit value for every path. - Over-constraining. A strict
patternthat rejects valid service names forces the model into retry loops. Test constraints against real data. - Mutable defaults. Use
Field(default_factory=list)in model classes, not a shared list literal.
Summary of the working model
Type hints are the contract. The SDK turns them into JSON Schema, the model reads that schema to build a call, and the server validates the call before your code runs. Return types follow the same path in the other direction: annotate a structured type and clients get typed data plus a text fallback.
Exercise
A tool takes region: str, but only "eu", "us", and "apac" are valid. The model sometimes sends "europe" or "US-East". Rewrite the parameter annotation so the model sees the allowed values and invalid values are rejected before the function runs. Also say what the model receives when it sends "europe".
Show answer
Use region: Literal["eu", "us", "apac"]. The schema then contains an enum with those three values, so the model sees the legal options. When it sends "europe", pydantic validation fails before the function body runs, and the model receives a validation error naming the invalid value and the allowed ones, which it can use to retry with a correct value.
Exercise
You change get_deploy to return a DeployInfo model instead of a string. Name two benefits for clients, and name one thing you still must do inside the function that the schema cannot do for you.
Show answer
Clients receive an output schema and typed structured content, so they can validate the result and read fields such as healthy as a boolean without parsing text. A text copy is also included for clients that only read text. The schema cannot check authorization, so the function must still verify that the caller is allowed to see that environment's deploy details.