Sub topic 9
Writing Your Own Minimal Server
This chapter walks through building a small MCP server in Python, running it, and checking what it sends over the wire. It assumes you can read Python, know the host, client and server roles, and know what a tool is (a function the model can ask the client to call). You should also be comfortable with the mcpServers configuration shown in the earlier chapter on configuration.
What you are building
You will write a server that exposes one tool, add, over the stdio transport. The assistant (the host) launches your script as a child process. The client inside the host sends JSON-RPC messages to the script's standard input and reads replies from its standard output.
A server has three jobs:
- Answer the
initializehandshake and declare its capabilities. - List its tools when asked (
tools/list). - Run a tool when asked (
tools/call) and return the result.
The official Python SDK handles the protocol framing for all three. You write only the functions.
Setting up
Install the SDK in a virtual environment. The package is named mcp, and the cli extra adds helper commands.
python -m venv .venv
source .venv/bin/activate
pip install "mcp[cli]"Use Python 3.10 or newer. Pin the SDK version in a requirements.txt file once the server works, because the SDK is still changing and newer releases can rename things.
The smallest working server
Save this as server.py.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("calculator")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
if __name__ == "__main__":
mcp.run() # stdio transport by defaultEach part does a specific job:
FastMCP("calculator")creates the server. The string is the server name sent during initialization.@mcp.tool()registers the function as a tool. The SDK reads the function and builds the tool definition from it.mcp.run()starts the message loop. With no argument it uses stdio.
How the function becomes a tool definition
The SDK derives three things from your function:
| Source in your code | Becomes |
|---|---|
| Function name `add` | Tool name |
| Type hints `a: int, b: int` | JSON Schema for the input |
| Docstring | Tool description shown to the model |
The model never sees your Python. It sees the name, the description and the schema, and it picks tools based on them. A vague docstring leads to wrong or missed tool calls, so write the docstring for the model as the reader.
The generated definition looks roughly like this, as returned by tools/list:
{
"name": "add",
"description": "Add two integers.",
"inputSchema": {
"type": "object",
"properties": {
"a": { "type": "integer", "title": "A" },
"b": { "type": "integer", "title": "B" }
},
"required": ["a", "b"]
}
}The exact extra fields, such as title, vary with the SDK version.
What happens when it runs
The diagram shows the messages between the client and your server for one call.
The call itself is a JSON-RPC request:
{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "add", "arguments": {"a": 2, "b": 3}}}The server replies with a result that has a content list. For add, the SDK wraps the integer 5 as a text item. Some SDK versions also return a structuredContent field when the function has a return type hint. The id in the reply matches the request, which is how the client pairs answers with questions.
The SDK validates the arguments against the schema before it calls your function. If the client sends "a": "two", your function never runs, and the server returns an error.
Testing before involving the assistant
Test the server by itself first. If you test through the assistant, you cannot tell whether a failure comes from your code, the configuration, or the model's choices.
The MCP Inspector starts your server and gives you a web page where you can list tools and call them by hand:
npx @modelcontextprotocol/inspector python server.pyRun this from the folder that contains server.py, with the virtual environment active so that python finds the mcp package. In the page, connect, open the Tools tab, choose List Tools, select add, enter 2 and 3, and run it. You should see 5. The Inspector also shows the raw messages, so compare them with the diagram above.
The SDK also ships a development command that does the same job:
mcp dev server.pyConnecting it to the assistant
Once the Inspector shows the tool working, add the server to the assistant's configuration. The file name and location depend on the assistant. The entry itself has the usual shape:
{
"mcpServers": {
"calculator": {
"command": "python",
"args": ["/absolute/path/to/server.py"]
}
}
}Two details cause most first-time failures:
- Use an absolute path to the script. The assistant starts the process from its own working directory, not yours.
- Make sure
commandpoints at the Python that hasmcpinstalled. If you used a virtual environment, setcommandto the full path of.venv/bin/python(on Windows,.venv\Scripts\python.exe).
Restart or reload the assistant after editing the file. Most assistants read it only at startup.
Never write to standard output
With stdio, standard output carries the protocol. Anything else you write there corrupts the stream, and the client may drop the connection or report a parse error.
This is the most common bug in new servers:
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two integers."""
print(f"adding {a} and {b}") # BAD: breaks the stdio stream
return a + bWrite diagnostics to standard error, or use the logging module, which writes to standard error by default:
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("calculator")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two integers."""
log.info("adding %s and %s", a, b)
return a + bClients usually capture standard error and show it in a log view, so these lines are where you look when something goes wrong.
Making the tool useful
The add tool shows the mechanics but does little. A tool worth adding to an assistant usually wraps something the model cannot do alone. This second example reads the line count of a file inside one allowed directory.
from pathlib import Path
from mcp.server.fastmcp import FastMCP
ROOT = Path("/path/to/project").resolve()
mcp = FastMCP("project-tools")
@mcp.tool()
def count_lines(relative_path: str) -> int:
"""Count the lines in a text file inside the project folder.
relative_path is relative to the project root, for example "src/main.py".
"""
target = (ROOT / relative_path).resolve()
if not target.is_relative_to(ROOT):
raise ValueError("Path is outside the project folder")
if not target.is_file():
raise ValueError(f"No such file: {relative_path}")
with target.open("r", encoding="utf-8", errors="replace") as handle:
return sum(1 for _ in handle)
if __name__ == "__main__":
mcp.run()Three habits in this code carry over to every server you write:
- Validate inputs. The model chooses the arguments, and it can be tricked by text in the files it reads. The
resolve()andis_relative_to()check stops a path like../../etc/passwdfrom escaping the project folder.Path.is_relative_toneeds Python 3.9 or newer. - Raise clear errors. When a tool raises an exception, the SDK returns the message to the model with the error flag set. The model can then correct its next call. A message such as
No such file: src/mian.pyis far more useful than a stack trace. - Document the argument. The docstring tells the model what format
relative_pathtakes. The model has no other source for that.
Design guidance for tools
Keep these points in mind as you add more tools:
- Give each tool one purpose and a specific name.
count_linesis easier for a model to choose correctly thanfile_toolwith amodeparameter. - Return compact results. Everything a tool returns goes into the model's context window and is paid for there. Truncate or summarize large output instead of returning it whole.
- Prefer simple argument types: strings, numbers, booleans and short lists. Deeply nested objects are harder for models to fill in correctly.
- Make the tool safe to run twice when you can. Models sometimes repeat calls.
- Do not read secrets from the tool's arguments. Take them from environment variables, set through the
envfield in the configuration.
Reading a token from the environment looks like this:
import os
def get_token() -> str:
token = os.environ.get("API_TOKEN")
if not token:
raise RuntimeError("API_TOKEN is not set for this server")
return tokenThe matching configuration entry passes the value to the process without putting it in your source:
{
"mcpServers": {
"my-api": {
"command": "python",
"args": ["server.py"],
"env": { "API_TOKEN": "<set-in-your-environment>" }
}
}
}Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Server shows as failed at startup | Wrong `command`, or `mcp` not installed for that Python | Use the full path to the virtual environment's Python |
| Connects, then the first call fails with a parse error | Output written to standard output | Remove `print()` calls, log to standard error |
| Tool missing from the assistant | Assistant not restarted, or `tools/list` empty because the decorator was not applied | Reload the assistant, check the Inspector's tool list |
| Script not found | Relative path in `args` | Use an absolute path |
| Model picks the wrong tool | Vague name or docstring | Rewrite them for the model as the reader |
| Tool call returns a validation error | Arguments do not match the type hints | Check the schema in the Inspector and fix the hints |
Beyond one tool
Resources and prompts use the same pattern of decorators. A resource exposes data the application can read by address, and a prompt exposes a reusable template. In FastMCP, these are @mcp.resource("uri://...") and @mcp.prompt(). Start with tools. They are the primitive that every assistant supports, and the one most assistants route through the model.
If you later need a remote server instead of a local process, the same functions can be served over Streamable HTTP by changing the transport passed to run(). Doing that adds authorization and network exposure, which later chapters cover.
Exercise
Your server connects in the Inspector but the assistant reports a parse error on the first tool call. The tool contains the line print("called with", a). Explain why this breaks the connection and give the fix.
Show answer
Over stdio, the server's standard output is the channel for JSON-RPC messages. The print call puts plain text into that channel, so the client tries to parse "called with 2" as a protocol message and fails. Remove the call, or write the diagnostic to standard error, for example with logging.getLogger(...).info(...), which the client can show in its log view without corrupting the stream.
Exercise
Add a second tool named multiply to the calculator server, then say how you would confirm it works before adding it to the assistant.
Show answer
Add this to server.py above the if __name__ block:
@mcp.tool()
def multiply(a: int, b: int) -> int:
"""Multiply two integers."""
return a * b
Then run npx @modelcontextprotocol/inspector python server.py, connect, open the Tools tab, list tools, and check that both add and multiply appear. Call multiply with 4 and 5 and confirm the result is 20. Only then add the server to the assistant's configuration and restart the assistant.
Exercise
In count_lines, why does the code call resolve() before checking is_relative_to(ROOT)?
Show answer
resolve() turns the path into an absolute path with .. segments and symbolic links resolved. Without it, a value like ../secrets.txt would join onto the root and still look like it begins with the root, so the check could pass even though the real file is outside the project folder. Resolving first means the check compares the true location.