Sub topic 9
Building a Minimal Server and Connecting a Client
This chapter assumes you can read Python, know basic JSON, and have used a command line. You also need to know the roles of host, client, and server, and how the initialization handshake works. You will build one server that exposes a tool, a resource, and a prompt. Then you will write a client that starts the server and calls it.
Setup
Install the official Python SDK in a virtual environment. Python 3.10 or newer is required.
python -m venv .venv
source .venv/bin/activate
pip install "mcp[cli]"The server
The SDK includes FastMCP, a class that turns ordinary Python functions into MCP features. Save this as server.py.
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")Each decorator maps to one server feature:
| Decorator | Feature | Who controls it |
|---|---|---|
| `@mcp.tool()` | Tool | The model decides when to call it |
| `@mcp.resource()` | Resource | The application decides what to read |
| `@mcp.prompt()` | Prompt | The user selects it |
FastMCP builds the rest from your code. The function name becomes the tool name. The docstring becomes the description. The type hints become the JSON Schema for the arguments, so a client knows a and b must be integers. The string greeting://{name} is a URI template, and the name parameter is filled in from the URI that the client requests.
The transport="stdio" argument makes the server read requests from standard input and write responses to standard output.
What happens on the wire
When a client calls the tool, it sends a tools/call request. The server replies with a result that has the same 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 matching id lets the client pair each response with its request. The result is a list of content items, not a bare number, because tools can return text, images, and other content types.
The client
A client starts the server as a subprocess and talks to it over its pipes. Save this as client.py in the same folder.
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())Run it with python client.py. The flow has four steps:
stdio_clientlaunchespython server.pyand gives you a read stream and a write stream.ClientSessionwraps those streams and handles the JSON-RPC details.initialize()sends theinitializerequest, receives the server's capabilities, and completes the handshake.list_tools()andcall_tool()sendtools/listandtools/call.
The output looks like this. The exact formatting of the second line depends on your SDK version.
['add']
[TextContent(type='text', text='5', annotations=None)]Common errors
- The client hangs or fails to parse messages. The server probably wrote to stdout. Remove
print()calls. FileNotFoundErrorforpython. The command is not on the path of the client process. Usesys.executableas the command, or an absolute path.- A call fails with a validation error. The arguments did not match the schema generated from your type hints, for example a string passed for an integer.
- Calls before
initialize()fail. The session is not ready until the handshake completes.
Exercise
Add a second tool named multiply to server.py, then change the client to call it with a=4 and b=5. What text does the result contain, and why do you not need to edit any schema by hand?
Show answer
Add @mcp.tool() above def multiply(a: int, b: int) -> int: returning a * b, then call session.call_tool("multiply", {"a": 4, "b": 5}). The result content is a text item with "20". You write no schema because FastMCP generates the input schema from the type hints, and the description from the docstring.
Exercise
Why does the client call initialize() before list_tools()?
Show answer
The initialization handshake negotiates the protocol version and capabilities. The server will not accept normal requests such as tools/list until it completes.