AI engineering / Advanced / 03.04
Building an MCP Server
Give a model a new tool: choose what to offer, write names and inputs well, return errors it can read, and watch the messages by hand.
14 min readFree
Give a model a new tool
The last lesson, MCP data and transport layers, ended with a promise: next, building an MCP server, giving models a new tool. Here it is.
A server is the part that does the work. Your app, or someone else's, asks it what it can do, and then asks it to do one thing. In this lesson you will decide what to offer, write the offer so a model understands it, and handle bad requests politely. Then you will run a small server of your own, made from nothing but Python's standard library.
Key words
- Server
- A program that offers tools, data or ready-made prompts to an AI app.
- Tool
- One action the server can do, like "save a note". The model chooses when to use it.
- Input schema
- A description of what a tool needs, written as JSON Schema: which fields, what type, which are required.
- Validation
- Checking that what arrived is what you expected, before you act on it.
- stdio
- Short for standard input and output. The app starts your server as a program and talks to it through those two pipes.
- Logging
- Writing a diary of what the program did, so you can find out later what went wrong.
Pick what to expose
Start small. Ask what one thing a model could not do alone that would help your users. The official quickstart says a server can provide three kinds of capability: resources, which are file-like data a client can read; tools, which are functions the model can call (with user approval); and prompts, which are pre-written templates that help users do a specific task.
Think of a food stall. The menu card is the list of tools. The ingredients you let customers look at are resources. The set meals are prompts. Most first servers just have a short menu.
Tool
An action. The quickstart builds two: one to get weather alerts, one to get a forecast.
Resource
Data to read, like a file or an API response. Nothing is changed by reading it.
Prompt
A ready-made starting message a person picks, such as "summarise this document".
Tip
One server, one job. A small server with three clear tools is easier for a model to use than a big one with thirty.
Write the tool so a model can use it
A model never sees your code. It sees only three things: the tool's name, its description and its input schema. If those are vague, it will pick the wrong tool or send the wrong input. Write them like a label on a kitchen jar.
The Tools page of the specification, revision 2026-07-28, describes a tool as having a name (a unique identifier), an optional title, a description (human-readable text about what it does), and an inputSchema, a JSON Schema for the expected parameters.
Name
The specification says names should be 1 to 128 characters, case-sensitive, using only letters, digits, underscore, hyphen and dot, with no spaces. Use a verb: add_note, not note.
Description
Say what it does and when to use it, in one or two plain sentences.
Input schema
List every field with a type and a short description. Mark the required ones. Say what is allowed, such as a length.
The quickstart's Python tool shows the cheap way to do all three. It has a docstring (the text in triple quotes under the function) and type hints (the "str" after state). The page says the class uses Python type hints and docstrings to automatically generate tool definitions.
The official quickstart
Here is the quickstart's weather server, trimmed to its first tool. It is copied from the docs, not run here: the official software kit (SDK) is not installed in this course, and the real tool calls a weather web service. The two helper functions it uses, make_nws_request and format_alert, are left out to keep it short. The quickstart says it needs Python 3.10 or higher and the Python MCP SDK 2.0.0 or higher.
# From the MCP docs, "Build an MCP server" (Python quickstart), shown without its output (not run here)
from typing import Any
import httpx2
from mcp.server import MCPServer
# Initialize MCPServer
mcp = MCPServer("weather")
# Constants
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"
@mcp.tool()
async def get_alerts(state: str) -> str:
"""Get weather alerts for a US state.
Args:
state: Two-letter US state code (e.g. CA, NY)
"""
url = f"{NWS_API_BASE}/alerts/active/area/{state}"
data = await make_nws_request(url)
if not data or "features" not in data:
return "Unable to fetch alerts or no alerts found."
if not data["features"]:
return "No active alerts for this state."
alerts = [format_alert(feature) for feature in data["features"]]
return "\n---\n".join(alerts)
if __name__ == "__main__":
mcp.run(transport="stdio")Read it in three parts. mcp = MCPServer("weather") makes the server and gives it a name. The line @mcp.tool() marks a function as a tool. The last two lines start the server using stdio, so an app can run it as a program and talk to it.
Errors the model can read
Things go wrong: a bad date, a missing field, a web service that is down. The model can recover from some of them if you tell it what happened in words. The specification names two kinds of error.
Protocol error
The request itself is broken, such as an unknown tool or a request that does not fit the schema. It comes back as a standard JSON-RPC error. The page says models are less likely to fix these.
Tool execution error
The tool ran but could not finish: an API failure, a bad input, a rule broken. It is sent as a normal result with isError set to true.
Why it matters
The page says tool execution errors hold actionable feedback that language models can use to self-correct and retry with adjusted parameters.
Its own example message reads "Invalid departure date: must be in the future. Current date is 08/08/2025." A model can read that, fix the date and try again. Compare "error 400", which tells it nothing.
Tip
Write error text for a reader who cannot see your code: say what was wrong and what would be right.
Quick check
A model sends an empty note. Which reply helps it most?
Validate, hide secrets, keep a diary
Three habits keep a server safe and fixable. The specification says servers MUST validate all tool inputs, implement proper access controls, rate limit tool invocations and sanitize tool outputs. A model's input is just text someone typed, filtered through a model. Never trust it more than a web form.
- 1
Validate every input
Check the type, the size and the allowed values. Refuse extra fields. Do it even when your schema already says so, because the schema is a request, not a lock.
- 2
Keep secrets on the server
Passwords and keys stay in the server's own settings. Never put one in a tool's description, its input or its result. Anything you return goes to the model and on to the user.
- 3
Log what happened
Write a short line for each call. The quickstart gives a rule for stdio servers: never write to stdout, because that corrupts the JSON-RPC messages. Use the standard logging module, which writes to stderr.
Also give the server the least power it needs. A notes tool should only be able to save notes. And never take text from a model and pass it to a shell command. If the text says "; delete everything", the computer would do it. Use fixed actions with checked inputs instead.
Build the same thing by hand
The kit hides the messages. To see them, we build a tiny server with only the standard library. It offers one tool, add_note, which saves a short note in a list. This is a teaching server. It is not production code: there is no network, no real stdio loop, one shared list, and it skips most of the protocol's rules.
It is driven in-process. Instead of reading from a pipe, the code feeds it a list of JSON lines and prints each reply. The protocol revision matters here. The versioning page for 2026-07-28 says there is no negotiation handshake: every request carries its protocol version in its _meta field. Older revisions (2025-11-25 and earlier) open with an initialize request. The code below accepts both, so you can see each style.
Watch for four things in the output: the notification that gets no reply, the empty note that comes back as a readable error, the unknown tool that comes back as a protocol error, and the request missing its _meta that gets refused. The log lines go to stderr, which is hidden here so the output shows only what would travel on stdout.
import json
import logging
import sys
logging.basicConfig(stream=sys.stderr, level=logging.INFO, format="log: %(message)s")
log = logging.getLogger("notes")
NOTES = []
TOOLS = [{
"name": "add_note",
"description": "Save one short text note. Use it when the user asks you to remember something.",
"inputSchema": {
"type": "object",
"properties": {
"text": {"type": "string", "description": "The note, 1 to 200 characters"},
},
"required": ["text"],
"additionalProperties": False,
},
}]
def reply(msg_id, result=None, error=None):
out = {"jsonrpc": "2.0", "id": msg_id}
out["error" if error else "result"] = error or result
return out
def add_note(args):
text = args.get("text") if isinstance(args, dict) else None
if not isinstance(args, dict) or set(args) - {"text"} or not isinstance(text, str) or not 1 <= len(text) <= 200:
return "text must be a string of 1 to 200 characters, and nothing else is accepted", True
NOTES.append(text)
return f"Saved note {len(NOTES)}: {text}", False
def handle(line, state):
try:
msg = json.loads(line)
except json.JSONDecodeError:
return reply(None, error={"code": -32700, "message": "Parse error"})
method, msg_id = msg.get("method"), msg.get("id")
if msg_id is None:
return None # a notification gets no reply
params = msg.get("params", {})
meta = params.get("_meta", {})
if method == "initialize": # older revisions only
state["legacy"] = True
return reply(msg_id, {
"protocolVersion": "2025-11-25",
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {"name": "NotesServer", "version": "0.1.0"},
})
modern = "io.modelcontextprotocol/protocolVersion" in meta
if not (modern or state.get("legacy")):
return reply(msg_id, error={"code": -32602, "message": "Missing _meta protocol version"})
done = {"resultType": "complete"} if modern else {}
if method == "tools/list":
return reply(msg_id, {**done, "tools": TOOLS})
if method == "tools/call":
if params.get("name") != "add_note":
return reply(msg_id, error={"code": -32602, "message": f"Unknown tool: {params.get('name')}"})
text, is_error = add_note(params.get("arguments", {}))
log.info("add_note is_error=%s", is_error)
return reply(msg_id, {**done, "content": [{"type": "text", "text": text}], "isError": is_error})
return reply(msg_id, error={"code": -32601, "message": "Method not found"})
META = {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}
def call(i, args, name="add_note", meta=None):
params = {"name": name, "arguments": args}
if meta:
params["_meta"] = meta
return json.dumps({"jsonrpc": "2.0", "id": i, "method": "tools/call", "params": params})
old_lines = [
json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}),
json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}),
json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
call(3, {"text": "buy milk"}),
call(4, {"text": ""}),
call(5, {"text": "hi"}, name="delete_all"),
"{not json",
]
new_lines = [
json.dumps({"jsonrpc": "2.0", "id": 6, "method": "tools/list"}),
json.dumps({"jsonrpc": "2.0", "id": 7, "method": "tools/list", "params": {"_meta": META}}),
call(8, {"text": "call mum"}, meta=META),
]
for title, lines in (("older style (initialize first)", old_lines), ("2026-07-28 style (no handshake)", new_lines)):
print("==", title)
state = {}
for line in lines:
response = handle(line, state)
print("->", line[:70])
print("<-", json.dumps(response) if response else "(no reply)")
print("notes kept:", NOTES)Output
== older style (initialize first)
-> {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}
<- {"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25", "capabilities": {"tools": {"listChanged": false}}, "serverInfo": {"name": "NotesServer", "version": "0.1.0"}}}
-> {"jsonrpc": "2.0", "method": "notifications/initialized"}
<- (no reply)
-> {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
<- {"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": "add_note", "description": "Save one short text note. Use it when the user asks you to remember something.", "inputSchema": {"type": "object", "properties": {"text": {"type": "string", "description": "The note, 1 to 200 characters"}}, "required": ["text"], "additionalProperties": false}}]}}
-> {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name":
<- {"jsonrpc": "2.0", "id": 3, "result": {"content": [{"type": "text", "text": "Saved note 1: buy milk"}], "isError": false}}
-> {"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name":
<- {"jsonrpc": "2.0", "id": 4, "result": {"content": [{"type": "text", "text": "text must be a string of 1 to 200 characters, and nothing else is accepted"}], "isError": true}}
-> {"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name":
<- {"jsonrpc": "2.0", "id": 5, "error": {"code": -32602, "message": "Unknown tool: delete_all"}}
-> {not json
<- {"jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": "Parse error"}}
== 2026-07-28 style (no handshake)
-> {"jsonrpc": "2.0", "id": 6, "method": "tools/list"}
<- {"jsonrpc": "2.0", "id": 6, "error": {"code": -32602, "message": "Missing _meta protocol version"}}
-> {"jsonrpc": "2.0", "id": 7, "method": "tools/list", "params": {"_meta"
<- {"jsonrpc": "2.0", "id": 7, "result": {"resultType": "complete", "tools": [{"name": "add_note", "description": "Save one short text note. Use it when the user asks you to remember something.", "inputSchema": {"type": "object", "properties": {"text": {"type": "string", "description": "The note, 1 to 200 characters"}}, "required": ["text"], "additionalProperties": false}}]}}
-> {"jsonrpc": "2.0", "id": 8, "method": "tools/call", "params": {"name":
<- {"jsonrpc": "2.0", "id": 8, "result": {"resultType": "complete", "content": [{"type": "text", "text": "Saved note 2: call mum"}], "isError": false}}
notes kept: ['buy milk', 'call mum']Go through it. In the older style, initialize got a reply and the notification got nothing, as JSON-RPC says. tools/list showed add_note with its schema, including "additionalProperties": false, which means no extra fields.
Request 3 saved "buy milk". Request 4 sent an empty text, and the reply is a normal result with isError true and a sentence the model can use. Request 5 asked for a tool that does not exist, and got error code -32602 with "Unknown tool: delete_all", the same code and wording pattern as the specification's example. The line that is not valid JSON got -32700, JSON-RPC's code for a parse error.
In the 2026-07-28 style, request 6 had no _meta, so the stand-in refused it with -32602. The spec says a request missing required _meta fields must be rejected with -32602. Request 7 carried the protocol version and capabilities, and the result includes "resultType": "complete", as the specification's examples show. Request 8 saved a second note, so the notes list ends with two items.
Quick check
In the output, why did the empty note not make the server fail?
Test with the Inspector
You do not need a full AI app to try a server. The official MCP Inspector is described in the docs as the reference developer tool for testing and debugging MCP servers. It has a web version, a command-line version and a terminal version. The page says it requires Node.js and runs through npx, so nothing needs installing. These two commands are copied from that page, not run here.
# From the MCP docs, "MCP Inspector", shown without its output (not run here)
# Launch the web UI and connect to a local stdio server
npx @modelcontextprotocol/inspector node path/to/server/index.js
# List a server's tools and exit
npx @modelcontextprotocol/inspector --cli node path/to/server/index.js --method tools/listThe first command opens a page where you can pick a tool, type its inputs and see the reply. The second lists the tools and exits. The build-a-server page adds a warning: the Inspector defaults to the legacy era, which only tries the 2025-era handshake, so to check a server against 2026-07-28 you run the command again with a flag for the modern era.
Tip
Test the bad cases on purpose: an empty field, a missing field, an unknown tool. Those are the ones a real model will hit.
What to remember
Offer little, describe it well
A short menu of tools with clear names, descriptions and input schemas.
Answer in words
Bad input becomes a result with isError true that a model can read and fix.
Stay careful
Validate every input, keep secrets on the server, log to stderr, and never run a shell command from raw model text.
Quick check
Where should a stdio server write its log lines?
Next: building an MCP client, letting your app use any server.
Sources
Last updated on 16 November 2026
Learn with me
Every lesson is free. I add new ones as I learn. Have a question, or want help with your own work? Book a short call.