Sub topic 9
Building a minimal server and connecting a client
This chapter builds a working MCP server with the official Python SDK, then writes a client that launches it, negotiates a session, and calls a tool. It assumes you can read Python and JSON. It also assumes you know the host, client and server roles, the shape of JSON-RPC messages, and the initialization handshake from earlier chapters.
What you will build
You will write two files:
server.pyexposes one tool, one resource template, and one prompt over the stdio transport.client.pystartsserver.pyas a subprocess, runs the handshake, lists tools, and calls one.
The client here plays the part that a host application normally plays. A real host such as a desktop assistant embeds one client object per server. Writing the client yourself shows what the host does for you.
Setup
Use Python 3.10 or newer. Create a virtual environment and install the SDK with its command-line extras:
python -m venv .venv
source .venv/bin/activate
pip install "mcp[cli]"The cli extra adds the mcp command, which you will use later to run the server under a debugger.
The server
FastMCP is a high-level class in the SDK. You create one instance, register Python functions with decorators, and call run. The SDK reads each function's name, type hints, and docstring and turns them into protocol metadata.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("demo")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
@mcp.resource("greeting://{name}")
def greeting(name: str) -> str:
"""Return a personalized greeting."""
return f"Hello, {name}!"
@mcp.prompt()
def review_code(code: str) -> str:
"""Ask the model to review a piece of code."""
return f"Please review this code:\n\n{code}"
if __name__ == "__main__":
mcp.run(transport="stdio")Save this as server.py.
What the decorators produce
Each decorator maps to one protocol feature. The feature also determines who is expected to trigger it.
| Decorator | Protocol feature | Controlled by | What the SDK derives |
|---|---|---|---|
| `@mcp.tool()` | Tool, listed with `tools/list` and run with `tools/call` | The model | A JSON Schema for the arguments, built from the type hints. The docstring becomes the description. |
| `@mcp.resource("greeting://{name}")` | Resource template, read with `resources/read` | The application | A URI template. The `{name}` placeholder is passed to the function as an argument. |
| `@mcp.prompt()` | Prompt, fetched with `prompts/get` | The user | A named template whose parameters come from the function signature. |
The type hints matter. For add, the SDK publishes an inputSchema that requires two integers named a and b. It validates incoming arguments against that schema before your function runs. If you drop the hints, the schema loses its types and the model gets less guidance.
Choosing the transport
The last line selects stdio. In this transport the host starts your server as a child process. It sends JSON-RPC messages to the server's standard input and reads replies from its standard output. Streamable HTTP is the alternative for servers that run remotely or serve several clients. For a local, single-user server, stdio is the simplest choice.
The client
The SDK's client side has two layers. stdio_client starts the subprocess and gives you a pair of streams for reading and writing messages. ClientSession sits on those streams and provides one method per protocol request.
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
params = StdioServerParameters(command="python", args=["server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
print([tool.name for tool in tools.tools])
result = await session.call_tool("add", {"a": 2, "b": 3})
print(result.content)
asyncio.run(main())Save this as client.py in the same directory and run python client.py. You should see the tool list ['add'], followed by a list holding one text item whose text is 5.
You do not need to start the server yourself. StdioServerParameters tells the client which command to run, and stdio_client launches it. When the async with block exits, the SDK closes the pipes and ends the subprocess.
If python on your path is not the interpreter with mcp installed, the subprocess will fail with an import error. Use sys.executable as the command in that case.
What happens on the wire
Each line of the client maps to JSON-RPC traffic. The diagram shows the order of messages.
The handshake
session.initialize() sends the first request. It states the protocol version the client supports, the capabilities it offers, and its own name and version:
{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {"sampling": {}}, "clientInfo": {"name": "example-client", "version": "1.0.0"}}}The server replies with the version it will use, its own capabilities, and its serverInfo. Because your server registered tools, resources, and prompts, its capabilities include entries for all three. After the reply, the client sends a notifications/initialized message. A notification has no id and expects no response. Until this step finishes, the client should send nothing except pings, so always await session.initialize() before any other call.
The tool call
call_tool sends a tools/call request and waits for the response with the matching id:
{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "add", "arguments": {"a": 2, "b": 3}}}
{"jsonrpc": "2.0", "id": 2, "result": {"content": [{"type": "text", "text": "5"}], "isError": false}}The id is how a response is paired with its request. Several requests can be in flight at once, so the pairing is not by order. The result's content is always a list of typed items, even when the answer is a single number. FastMCP converted the Python int into a text item for you.
Reading a resource and fetching a prompt
The client above only touches the tool. To exercise the other two features, add these calls after initialize():
templates = await session.list_resource_templates()
print([t.uriTemplate for t in templates.resourceTemplates])
greeting = await session.read_resource("greeting://Ada")
print(greeting.contents[0].text)
prompts = await session.list_prompts()
print([p.name for p in prompts.prompts])
prompt = await session.get_prompt("review_code", {"code": "print(1)"})
print(prompt.messages[0].content.text)greeting://{name} has a placeholder, so it is a template and appears under list_resource_templates, not list_resources. A fixed URI with no placeholder would appear in the plain resource list. Reading the URI greeting://Ada fills name with Ada and runs your function.
Errors you will meet
Failures fall into two groups, and the protocol reports them differently.
- Protocol errors use the JSON-RPC
errorfield. Examples are an unknown tool name or arguments that fail schema validation. In the Python client, these raise an exception from the awaited call. - Tool execution errors happen inside your function, for example when it raises an exception. FastMCP catches these and returns a normal result with
"isError": trueand the message incontent. The model can read that message and try again.
Check result.isError after every call_tool. A call can complete without raising and still report failure.
Other common problems:
- Output before the handshake. Anything your server prints to standard output at import time corrupts the stream.
- A hung client. The client waits for a reply that never comes if the server process exits early. Run
python server.pyby hand first to confirm it starts and waits for input without a traceback. - A relative path.
args=["server.py"]resolves against the client's working directory. Use an absolute path when you launch from elsewhere.
Where this goes next
A host application does what client.py does, but driven by a configuration file instead of code. The next chapter covers that file format. After that, the chapter on MCP Inspector shows how to call your tools from a browser interface without writing a client. You can try it now with mcp dev server.py.
Exercise
Your server works when you run client.py, but after you add print("starting") at the top of server.py, the client fails during session.initialize(). Why, and how do you fix it?
Show answer
With the stdio transport, the server's standard output is the protocol channel. The text "starting" is not a valid JSON-RPC message, so the client cannot parse the stream. Remove the print, or write it to standard error with print("starting", file=sys.stderr) after import sys, or use the logging module.
Exercise
Add a tool named multiply to server.py, then change client.py to call it with a=4 and b=5 and print only the text of the first content item. What do you need to change on each side?
Show answer
On the server, add @mcp.tool() above def multiply(a: int, b: int) -> int: with a docstring and return a * b. On the client, call result = await session.call_tool("multiply", {"a": 4, "b": 5}) and print result.content[0].text. The output is 20. No change to the handshake is needed, because the tool list is read after initialization.