Sub topic 7
Building a small server to test against
This chapter builds a small MCP server. The rest of the tutorial uses it as a test target for the client, the schema mapping and the agent loop. It assumes you can read async Python, know what JSON Schema is, and have called an LLM API with tools before. You don't need a model or an API key for this chapter.
Why write your own server first
When your host misbehaves, you need to know whether the fault is in your code or in the server. A third-party server hides that. A server you wrote, with a few lines and known behavior, removes the doubt.
The test server needs to be small, deterministic, and able to produce both success and failure results. It also needs to run locally over stdio, so the host can launch it as a subprocess with no network setup.
Install the SDK
Install the official Python SDK into a virtual environment:
# Run in a shell, not in Python:
# pip install "mcp[cli]"
# The [cli] extra adds the "mcp" command, which includes the Inspector launcher.
import mcp
print("mcp imported from", mcp.__file__)The minimal server
Save this as server.py:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("calc")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
if __name__ == "__main__":
mcp.run(transport="stdio")Four things happen here.
FastMCP("calc")creates a server object. The namecalcis reported to clients during initialization.@mcp.tool()registers the function as a tool. The function name becomes the tool name.- The docstring becomes the tool's
description. This is the text the model reads when deciding whether to call the tool, so write it for the model. mcp.run(transport="stdio")starts a loop that reads JSON-RPC messages from standard input and writes responses to standard output.
How the schema is derived
You never write a JSON Schema by hand. FastMCP reads the type hints and builds the inputSchema for you.
For add, the schema a client receives looks roughly like this:
{
"type": "object",
"properties": {
"a": {"title": "A", "type": "integer"},
"b": {"title": "B", "type": "integer"}
},
"required": ["a", "b"]
}Parameters without defaults become required. A parameter such as limit: int = 10 is optional and carries its default into the schema. The SDK also validates incoming arguments against the hints, so a call with "a": "two" fails before your function runs.
Add a tool that fails on purpose
A happy-path tool is not enough. The chapter on handling errors needs a tool that fails, so add one now. Extend server.py:
import sys
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("calc")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
@mcp.tool()
def divide(a: float, b: float) -> float:
"""Divide a by b. Fails if b is zero."""
print(f"divide called with a={a}, b={b}", file=sys.stderr)
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
if __name__ == "__main__":
mcp.run(transport="stdio")When divide raises, the SDK does not crash the server or the connection. It catches the exception and returns a normal tool result with isError set to true and the message in the content. That is the shape your agent loop will have to handle later.
The print call writes to sys.stderr on purpose, as explained next.
The stdout rule
Over stdio, standard output carries the protocol. Every line on stdout must be a valid JSON-RPC message. If your tool code calls print("debug") with no file= argument, that text lands in the message stream, and the client may fail to parse it or drop the connection.
- Send diagnostics to stderr, or use the
loggingmodule, which writes to stderr by default. - Don't import libraries that print banners to stdout at import time.
- Remember this when you wrap an existing script as a server. Stray prints are the most common reason a new stdio server "connects and then hangs".
Optional: a resource and a prompt
A tool is the primitive the model controls. The same server can also offer the other two primitives, so you can test them later in the chapter on using resources and prompts. Add these before the if __name__ block:
@mcp.resource("note://{name}")
def get_note(name: str) -> str:
"""Return a fixed note body for the given name."""
return f"This is the note called {name}."
@mcp.prompt()
def explain_sum(a: int, b: int) -> str:
"""Ask the model to explain how two numbers add up."""
return f"Explain step by step why {a} + {b} equals {a + b}."The resource uses a URI template, so note://todo calls get_note("todo"). The prompt returns text that a host can offer to the user as a reusable template. The server now exposes one of each kind of primitive plus one failing tool. That is enough surface to test every later chapter.
Run it and check it
Don't run python server.py and wait for output. It will sit silently, because it is waiting for JSON-RPC on stdin. There are two quick checks.
- Run
python server.pyand confirm it starts without a traceback. Stop it with Ctrl+C. - Run
mcp dev server.pyto open the MCP Inspector in a browser. It launches the server for you, shows each tool with its schema, and lets you calladdanddivideby hand. The Inspector needs Node.js installed. A later chapter covers it in detail.
If a tool does not appear in the Inspector, check these first:
| Symptom | Likely cause |
|---|---|
| Server starts, no tools listed | The `@mcp.tool()` decorator is missing its parentheses, or the file registers tools after `mcp.run()` |
| Connection closes at startup | An import error, or something printed to stdout |
| Schema shows `string` for every field | The parameters have no type hints |
| Tool description is empty | The function has no docstring |
What this server gives later chapters
Here is what each part of the test server is for:
addis the success case for the client session and the agent loop.dividewithb=0is the failure case that returnsisError: true.- The stderr print shows where server logs go when the client launches the server as a subprocess.
- The resource and prompt exercise the other two primitives.
Exercise
Your teammate adds print("computing...") inside the add tool. The server still starts, but clients fail intermittently when calling add. Why does this happen, and what is the fix?
Show answer
With the stdio transport, stdout is the protocol channel, so the text "computing..." is mixed into the JSON-RPC stream and can't be parsed as a message. Change the call to print("computing...", file=sys.stderr), or use the logging module, which writes to stderr.
Exercise
Call divide with b = 0. Does the server crash or close the connection? What does the client receive?
Show answer
No. The SDK catches the ValueError and returns a normal tool result with isError set to true and the error message in its content. The connection stays open, and the client can keep calling tools.