Input Checks and Clear Errors
A model calling a tool gets things wrong sometimes: it sends a number that is too large, a word the tool does not know, or the name of a record that does not exist. A well-built MCP server catches these calls, tells the model in plain text what went wrong so it can try again, and keeps real bugs inside the server, where the developer can see them and the caller cannot.
Constraints declared on the parameters
A type hint such as int already tells the model that an argument must be a whole number. Often that is not enough: a result limit of 5000 is still an integer, but no tool should return 5000 rows. An input constraint narrows a parameter further: a range for a number, a length for a text, or a fixed list of allowed values.
This page uses the official mcp Python SDK, version 2.x, where the server class is called MCPServer. The 1.x line and older tutorials call the same class FastMCP, which is also the name of a separate framework.
The SDK is built on pydantic, a library that checks data against declared types. You declare constraints with two forms, written in the type hint of the parameter:
Annotated[int, Field(...)]means "the type isint, and here is extra information about it".Annotatedcomes from Python's standardtypingmodule.Fieldcomes from pydantic and carries the limits and a description of the parameter.Literal["fiction", "non-fiction", "poetry"], also fromtyping, means "exactly one of these values, and nothing else".
from typing import Annotated, Literal
from pydantic import Field
from mcp.server import MCPServer
mcp = MCPServer("Bookshop")
BOOKS = [
{"title": "Dune", "genre": "fiction"},
{"title": "Cosmos", "genre": "non-fiction"},
]
@mcp.tool()
def search_books(
query: Annotated[str, Field(min_length=2, max_length=100,
description="Words to find in the title.")],
genre: Literal["fiction", "non-fiction", "poetry"],
limit: Annotated[int, Field(ge=1, le=50,
description="Maximum number of results.")] = 10,
) -> list[str]:
"""Search the catalog for books of one genre."""
found = [b["title"] for b in BOOKS
if b["genre"] == genre and query.lower() in b["title"].lower()]
return found[:limit]The function body never mentions these limits, and it does not need to. The SDK reads them from the signature and writes them into the tool's input schema, the JSON Schema a client receives when it lists the tools. Each declaration becomes a standard JSON Schema keyword:
| Declared in Python | In the input schema | What the model learns |
|---|---|---|
| Field(ge=1, le=50) | "minimum": 1, "maximum": 50 | the smallest and largest number allowed |
| Field(min_length=2, max_length=100) | "minLength": 2, "maxLength": 100 | how short and how long a text may be |
| Field(pattern=...) | "pattern": ... | a regular expression the text must match |
| Literal["fiction", ...] | an enum of the values | the only values it can pick |
| Field(description=...) | "description": ... | what the argument is for, in words |
So a constraint does two jobs at once. Before any call, it is part of what the model reads, so a careful model sends a valid value in the first place. During a call, it is a rule the server enforces, which is the subject of the next section.
Checked before the function runs
When a call arrives, MCPServer checks the arguments against the input schema before it calls your function. This check is always on; there is no switch to turn it off. If the arguments pass, the function runs with values that already meet every declared rule. If they fail, the function is never called, and the server answers with a result marked as an error that says which rule was broken.
- Call arrives limit = 999
- Check against schema maximum 50
- Error result a rule broken: function never runs
- Call arrives to Check against schema
- Check against schema to Error result
The text of that error starts with a prefix the SDK adds: Error executing tool search_books: . The rest comes from pydantic. It names the set of arguments it built from the signature (search_booksArguments), then the field that failed, a message, and the value that was sent. For limit=999 the message reads Input should be less than or equal to 50. Other rules have messages of the same kind:
| The model sends | Pydantic message |
|---|---|
| limit = 999 | Input should be less than or equal to 50 |
| limit = 0 | Input should be greater than or equal to 1 |
| query = "a" | String should have at least 2 characters |
| genre = "comics" | Input should be 'fiction', 'non-fiction' or 'poetry' |
| no genre at all | Field required |
Each of these messages names what was wrong and, for ranges, lengths and allowed values, what would have been accepted. The model receives that text as the tool's result and can send a corrected call.
One detail surprises people. Pydantic's default mode converts a value when the conversion is safe instead of rejecting it, so an int parameter accepts the string "5" or the number 5.0 and the function receives 5. A value that cannot be converted without losing something, such as 5.5, is rejected. Literal values are compared exactly, with no conversion.
True or false?
Limits in the input schema are only hints: the function still receives whatever value the model sends.
False. MCPServer validates every call against the schema first. A value outside the range never reaches the function.
A call with an invalid argument still gets a result back, marked as an error, with text the model can read.
True. The call fails as a tool call, not as a request: the client gets a normal result flagged as an error, whose text names the broken rule.
With a parameter declared as int, a call that sends the string "5" is rejected.
False. Pydantic converts "5" to 5 because nothing is lost. It rejects 5.5, which has a fractional part.
Errors the caller can fix
Some mistakes cannot be caught by a schema, because checking them needs the data. "Is this title in the catalog?" is a question only the function can answer. When the answer is no, the call has failed in a way the caller could correct, and the MCP specification has a name for this: a tool execution error. It is an ordinary tool result with the flag isError set to true and a text block explaining the failure. The specification asks clients to pass these errors on to the model, so that it can correct itself and retry.
In the SDK you produce one by raising ToolError:
from mcp.server.mcpserver.exceptions import ToolError
CATALOG = {"Dune": "Frank Herbert", "Neuromancer": "William Gibson"}
@mcp.tool()
def get_author(title: str) -> str:
"""Look up the author of a book in the catalog."""
if title not in CATALOG:
raise ToolError(f"No book titled {title!r} in the catalog.")
return CATALOG[title]A call with title="Nothing" does not make the request fail. A result comes back. The Python client names the flag is_error, and a client reading the result sees three things:
| Part of the result | Value |
|---|---|
| is_error | True |
| content | one text block: Error executing tool get_author: No book titled 'Nothing' in the catalog. |
| structured_content | None, because a failed call has no return value to structure |
On the server, a ToolError leaves a single INFO line in the log, with no traceback: it is expected behaviour, not a bug.
The flag is what makes it an error. A tool that returns the string "No book titled 'Nothing'" instead of raising produces a result with is_error false, which a client and a model read as success. To report a failure, raise.
True or false?
Returning a string that starts with "Error:" is enough to tell the caller a tool call failed.
False. A returned value is a successful result with the error flag off. Only raising ToolError sets the flag.
Checking whether a record exists belongs in the function, not in the input schema.
True. A schema can describe the shape of a value but cannot look up data. The function checks and raises ToolError when the record is missing.
When the tool itself breaks
A ToolError is a failure you planned for. A crash is one you did not: a bug, a missing file, a database that is not reachable. In code it is any other exception that escapes the function, such as a KeyError from CATALOG[title] when the check above was forgotten.
The SDK still turns a crash into a result with is_error true, but it sends almost nothing with it. The text is only Error executing tool get_author: no colon and none of the exception's message. The full story goes to the server log instead, as an ERROR record that reads Tool 'get_author' raised an unexpected exception followed by the traceback.
- MCP server
- server log
- caller
- full details
- generic message
The split is deliberate. An exception's message often contains internals: a file path, a fragment of a database query, a hostname, sometimes a secret. None of that helps a model fix its call, and some of it should never leave the server. The developer still gets everything, in the place where they look for bugs. The log levels help too: a log set to show WARNING and above stays quiet through every ToolError and shows each crash.
Older tutorials, written for the 1.x line, show the exception's message reaching the client. In 2.x only a ToolError's message reaches the caller.
| What happened | What the caller gets | What the server log gets |
|---|---|---|
| Arguments break the schema | is_error true, the broken rule and the value sent | no traceback: the function never ran |
| The tool raises ToolError | is_error true, your message after the prefix | one INFO line, no traceback |
| Any other exception escapes | is_error true, only Error executing tool <name> | an ERROR record with the full traceback |
In all three cases the request itself succeeds and a result comes back. That is why a test of a failing tool asserts on the result (its is_error flag and its text) rather than expecting the client call to raise an exception.
True or false?
When a tool raises a KeyError, the caller receives the text of the KeyError.
False. In the 2.x SDK the caller gets only Error executing tool
The missing colon after the tool name is one way to tell a crash apart from a ToolError in the result text.
True. A ToolError reads Error executing tool
Messages that guide a retry
A tool error is only as useful as its text. The model has nothing else to go on: it cannot open the code or read the log. A message that helps it retry answers two questions, what was wrong and what would be accepted, and it often names the value that was sent so the model can see its own mistake.
| Hard to act on | Guides the next call |
|---|---|
| Not found. | No book titled 'Dun' in the catalog. Call search_books to find the exact title. |
| Invalid date. | Invalid departure date: must be in the future. Current date is 08/08/2025. |
| Bad status. | Unknown status 'finished'. Use one of: open, done. |
The second row is the example the MCP specification itself gives for a tool execution error: it says what rule was broken and supplies the fact the model needs to choose a valid date. Pointing to another tool, as the first row does, is often the fastest path to a correct call, because the model can find the right value instead of guessing.
Constraints in the schema already produce messages of this kind, since pydantic names the rule and the allowed range or values. The messages you write in a ToolError deserve the same care. With a good message, a failed call is usually followed by one that works:
- Model
- Server
- Model to Server: get_author(title="Dun")
- Server to Model: error: no book titled 'Dun'; call search_books
- Model to Server: search_books(query="Dun", genre="fiction")
- Server to Model: ["Dune"]
- Model to Server: get_author(title="Dune")
- Server to Model: Frank Herbert
Write the message for a reader who sees only the tool's name, its schema and this text. Keep internals out of it for the same reason a crash hides them: anything you put in a ToolError goes to the model, and from there into the conversation.
True or false?
A good error message names what would be accepted, not only what was wrong.
True. Knowing the allowed values, range or the tool that finds them lets the model make a valid next call instead of guessing.
Including the database error text in a ToolError message helps the model fix its call.
False. The model cannot act on internal details, and they leak how the server works. Describe the problem in terms of the arguments instead.