Sub topic 5
Your first tool
This chapter builds a working MCP server with one tool. It assumes you can read Python type hints, have Python 3.10 or later installed, and know the host, client and server roles from the earlier chapters. It also assumes you have seen the initialize handshake. Typed inputs, structured results and error handling get their own chapters. Here the goal is a server that runs and a clear picture of what happens when a model calls it.
What a tool is
A tool is a function the server exposes and the model can ask the host to run. Each tool has three parts:
- A name, which is unique within the server.
- A description, which the model reads to decide when the tool applies.
- An input schema, which is a JSON Schema object describing the arguments.
Tools are model-controlled. The host shows the model the tool list, the model picks a tool and arguments, and the host sends the call to your server. Resources and prompts are usually selected by the application or the user instead.
Your server answers two JSON-RPC methods for tools:
| Method | Direction | Purpose |
|---|---|---|
| `tools/list` | client to server | Return every tool with its name, description and input schema |
| `tools/call` | client to server | Run one tool by name with arguments and return the result |
Install the SDK
The official Python SDK includes FastMCP, a helper that turns ordinary functions into tools. Install it with the CLI extras, which also provide the Inspector integration used later:
pip install "mcp[cli]"
npx @modelcontextprotocol/inspector python server.pyRun the second command only after you have written server.py in the next section.
Write the server
Save this as server.py. It exposes one tool that looks up which team owns a service:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("team-tools")
OWNERS = {"billing": "payments-team", "search": "discovery-team"}
@mcp.tool()
def get_service_owner(service: str) -> str:
"""Return the team that owns a service, given its short name."""
if service not in OWNERS:
raise ValueError(f"Unknown service: {service}")
return OWNERS[service]
if __name__ == "__main__":
mcp.run() # stdio transport by defaultFour things happen here, and each one matters later.
FastMCP("team-tools")creates the server object. The string is the server name that the client sees during initialization.@mcp.tool()registers the function. The function nameget_service_ownerbecomes the tool name.- The docstring becomes the tool description. The model reads it, so write it for the model and not for a code reviewer.
mcp.run()starts the server. With no argument it uses the stdio transport, so the process reads JSON-RPC messages from standard input and writes replies to standard output.
Do not run python server.py and expect output. The process waits silently for a client to send initialize on stdin. That is correct behavior, and you can stop it with Ctrl+C.
What the SDK generates from your function
FastMCP inspects the signature and builds the schema for you. For get_service_owner, a client that sends tools/list receives roughly this entry (the exact set of extra fields depends on the SDK version):
{
"name": "get_service_owner",
"description": "Return the team that owns a service, given its short name.",
"inputSchema": {
"type": "object",
"properties": {
"service": { "title": "Service", "type": "string" }
},
"required": ["service"]
}
}The parameter service: str with no default became a required string property. If you had written service: str = "billing", it would become optional with a default. Type hints are therefore part of your public interface. Changing a hint changes the schema that every connected model sees.
A call looks like this on the wire:
{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "get_service_owner",
"arguments": { "service": "billing" }
}
}The server replies with a result that carries a list of content blocks:
{
"jsonrpc": "2.0",
"id": 7,
"result": {
"content": [{ "type": "text", "text": "payments-team" }],
"isError": false
}
}Your function returned a plain string. FastMCP wrapped it in a text content block. You never build this envelope by hand when you use the helper.
Keep stdout clean
With the stdio transport, standard output is the protocol channel. A stray print() in your code inserts text into the JSON-RPC stream, and the client will fail to parse it. The failure usually shows up as a connection that drops or a host that reports a malformed message, with no hint pointing at your print.
Send diagnostics to standard error instead:
import logging
import sys
# With the stdio transport, stdout carries protocol messages.
# Send all logs to stderr so they do not corrupt the stream.
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
logger = logging.getLogger("team-tools")Put this near the top of server.py, then call logger.info("looking up %s", service) inside the tool. Most hosts capture a server's stderr in their logs, which makes it the right place for debugging output.
How errors surface
The tool raises ValueError for an unknown service. FastMCP catches the exception, so the server process keeps running. It returns a result with "isError": true and the exception message as text content. The model can read that message and try again with a corrected argument.
That is why the message Unknown service: payments is better than a bare failure. It names the bad value. A stronger message would also list the valid names. The error handling chapter covers this in detail. For now, remember that raising inside a tool is safe and does not crash the server.
Sync and async functions
get_service_owner is a plain def, which is fine for fast, in-memory work. Tools that call an HTTP API should usually be async def and use an async client, so one slow call does not block the server from handling other requests:
import httpx
@mcp.tool()
async def get_service_status(service: str) -> str:
"""Return the current health status of a service from the status API."""
async with httpx.AsyncClient(timeout=5.0) as client:
response = await client.get(f"https://status.example.internal/{service}")
response.raise_for_status()
return response.json()["status"]The URL is a placeholder for your own internal API. Always set a timeout. A hung request otherwise leaves the model waiting with no answer.
Common mistakes with a first tool
- Vague or missing docstring. Without a description, the model has only the function name to go on. It may skip the tool or call it at the wrong time.
- Printing to stdout. This corrupts the stdio stream, as described above.
- Relative paths in host config. The host launches your server from its own working directory. Use an absolute path to
server.pyin the host configuration. - Wrong Python environment. If the host runs
pythonand that interpreter lacksmcp, the server exits at import time. Point the host at the interpreter from the environment where you installed the SDK. - Returning huge strings. Everything you return goes into the model's context. Return the fields the model needs, not a whole API response.
- Renaming tools casually. Clients and prompts may refer to the old name. Treat tool names as a public interface.
Check your work
Run the Inspector command from the install section. It starts your server as a subprocess and opens a web interface. In the Tools tab, select List Tools and confirm get_service_owner appears with its description. Enter billing as the argument and run it. You should get payments-team. Then enter an unknown name and confirm you get an error result while the Inspector stays connected. The testing chapter covers the Inspector in more depth.
Exercise
You add a second tool to server.py, and it contains the line print("looking up", service) for debugging. The tool works in your own tests, but a host that launches the server over stdio reports malformed messages after the first call. What is the cause, and how do you fix it?
Show answer
With the stdio transport, standard output carries the JSON-RPC protocol messages. The print call writes extra text into that stream, so the client cannot parse it. Remove the print and log to standard error instead, for example by configuring logging.basicConfig(stream=sys.stderr) and calling logger.info(...), or by using print(..., file=sys.stderr).
Exercise
Starting from getserviceowner, add a tool named list_services that takes no arguments and returns the sorted list of service names in OWNERS. What does the generated inputSchema look like, and what return type hint should you use?
Show answer
Define it with @mcp.tool(), a docstring such as "List the short names of all known services.", and the return type list[str], returning sorted(OWNERS). Because the function has no parameters, the generated inputSchema is an object with an empty properties map and no required list.