Courses / Agentic AI from Scratch (Python)
Session 29 of 40
MCP basics: host, client and server; tools, resources and prompts
Notes
How to Build an MCP Server in Python: Host, Client, Server, Tools, Resources and Prompts
Agentic AI Foundations · Session 29
Before you start: what do I need before I start building an MCP server?
You need the code folder for this session open in your terminal. It holds code/ticket_server.py (the MCP server), code/call_server.py (a client), code/ask_copilot.py (asks the Copilot one question), code/copilot_graph.py (session 28’s graph, now calling the server) and the sample tickets in code/data/tickets.csv. Session 28’s separate tools file is gone: its two ticket tools now live in the server. You need Python 3.11 or newer, and the MCP Python SDK, added to the earlier libraries with pip install mcp langchain langchain-openai langchain-chroma langchain-community langchain-text-splitters langgraph langgraph-checkpoint-sqlite. Set LLM_BASE_URL, LLM_API_KEY, LLM_MODEL and EMBED_MODEL as in earlier sessions, then build the policy index and the ticket database with python code/build_index.py and python code/make_tickets_db.py. Calling the server from code/call_server.py needs no key, because it only talks to the ticket server on your machine; only code/ask_copilot.py calls a model. Have paper or a notes app ready for the flashcards and the model answer.
Summary: what is an MCP server?
The Model Context Protocol, MCP for short, is an open standard for how an application offers tools and information to a language model. Instead of each assistant carrying its own copy of a tool, one MCP server holds the tool and any number of assistants connect to it. A server offers three kinds of things: tools the model can call, resources the application can hand over, and prompts the user can pick. In this session you read a small server built with the MCPServer class from the Python SDK, run it over stdio, call it from a client, and move the Copilot’s ticket lookup and ticket creation behind it. The change is small to look at and large in effect: a fix to the lookup now reaches the assistants that use it.
Key concepts: what do the MCP terms mean?
| Term | Definition |
|---|---|
| MCP (Model Context Protocol) | An open standard for how applications provide tools and context to language models. |
| Host | The application that creates and manages MCP clients, such as the Copilot program. |
| Client | A connection created by the host that talks to exactly one server. |
| Server | A program that offers tools, resources and prompts to clients. |
| Tool | An action the model may call, such as looking up a ticket. The model decides when to use it. |
| Resource | Data a server makes available, such as the text of a ticket. The application decides what to show the model. |
| Prompt | A message template a server offers, which the user picks from a menu such as a slash command. |
| stdio | A way to connect: the client starts the server as a child process and talks over its input and output streams. |
| Streamable HTTP | The other standard connection type: each message is an HTTP POST to one endpoint, for a server shared across machines. |
MCPServer |
The Python SDK class you create to build a server; functions are registered on it with decorators. |
| URI template | A resource address with a blank in it, such as ticket://{ticket_id}, filled in when the resource is read. |
Explanations: how does MCP work (hosts, clients, servers, tools, resources and prompts)?
Why would I put a tool behind a server instead of copying the function?
Picture the help desk. The Copilot has a Python function that looks up a ticket. The IT team now builds its own assistant and wants the same lookup. You could copy the function into their code. A month later you fix a bug in the original; their copy still has the bug, and nobody remembers there were two. You could let their assistant open the database file directly. Now each assistant needs to know the file’s layout and rules, and each one can break them differently.
The third way is a server both assistants call. That is what MCP standardises: a shared way for an application to offer tools and information to a model, so one server can serve many assistants. Think of a standard wall socket, where any appliance with the right plug works whoever made the socket. Or think of a library front desk: readers ask the same desk, which knows the catalogue. One server means one place to fix a tool and one place to enforce its rules.
What are the host, the client and the server in MCP?
Think of a company switchboard. The host is the reception desk. Each client is one phone line from the desk. Each server is a department at the other end of a line. MCP’s architecture is exactly this shape: a host can run several client instances, the host creates each client, and a client talks to a single server. For the Copilot, the Copilot program is the host, its connection to the ticket server is a client, and code/ticket_server.py is the server.
Copilot program (the host)
|
MCP client ===== stdio (a child process) ===== ticket_server.py (the server)
|-- tool lookup_ticket
|-- tool create_ticket
|-- resource ticket://{ticket_id}
'-- prompt summarise_ticket
|
tickets.db
A server can be a local process or a remote service. The messages between client and server are encoded as JSON-RPC, which the SDK handles for you.
What are tools, resources and prompts in MCP?
Think of a shop counter. You ask the assistant to fetch an item for you: that is a tool, an action you request. The shelf the shop chooses to show you is a resource: data handed over, picked by the shop. The menu card you point at is a prompt: a template you choose. A kitchen gives the same picture: the chef calls for an ingredient (tool), the pantry list is handed over (resource), and the diner picks the set menu (prompt).
The protocol states who decides each one. Tools are designed to be model-controlled: the language model can discover and invoke them based on its understanding of the conversation. Resources are designed to be application-driven: the host application decides how to bring them in as context. Prompts are designed to be user-controlled: they are exposed so the user can select them explicitly, for example as slash commands. The SDK describes a prompt as a message template the user picks.
| Kind | Who decides to use it | In the Copilot |
|---|---|---|
| Tool | The model, while it works | lookup_ticket, create_ticket |
| Resource | The application, which picks what to show the model | The text of a ticket at ticket://{ticket_id} |
| Prompt | The user, from a menu | summarise_ticket |
Because a model can call tools by itself, the specification recommends that a person can refuse a tool call. In the Copilot that human is the approval step you built in session 26: it stays in front of the write tool.
How do I write an MCP server with MCPServer in Python?
You import MCPServer from mcp.server, create one, and register plain functions with decorators. The SDK reads three things from a tool function: its name becomes the tool’s name, its docstring becomes the description the model reads, and its type hints become the input schema. You write no JSON Schema, request parsing or protocol code by hand. This is the shape of code/ticket_server.py, shortened:
from mcp.server import MCPServer
mcp = MCPServer("fernhill-tickets")
@mcp.tool()
def lookup_ticket(ticket_id: str) -> str:
"""Find one help desk ticket by its id, such as T-1042."""
return format_ticket(find_ticket(ticket_id), ticket_id)
@mcp.resource("ticket://{ticket_id}")
def ticket_resource(ticket_id: str) -> str:
return format_ticket(find_ticket(ticket_id), ticket_id)
@mcp.prompt()
def summarise_ticket(ticket_id: str) -> str:
return f"Summarise ticket {ticket_id} for the help desk team in two lines."
if __name__ == "__main__":
mcp.run() # no argument: stdio
The file also holds a second tool, create_ticket(title), which adds a row to the tickets table and returns the new id. The tool is something the model may call. The resource is registered on a URI template, so ticket://T-1043 fills in ticket_id. The prompt returns the text of a message the user can pick. Calling mcp.run() with no argument serves over stdio.
How does the stdio connection work, and why must my server not print?
Imagine two people passing notes through a slot in a door. If one of them also drops a doodle through the slot, the other reads it as a note and gets confused. Over stdio, the client launches your server file as a subprocess and speaks to it over the process’s input and output streams. The specification describes stdio as one message per line, carried on the standard input and output of a process the client starts. The SDK puts it this way: standard output is the wire. A print() line in your server is therefore a doodle in the slot, and the client may wait for a reply that does not arrive. code/ticket_server.py therefore has no print() at all: it sets up the logging module, which writes to standard error, and calls log.info(...) when it wants to say what it did. To see the failure yourself, add print("server starting") near the top of the file, run python code/call_server.py and read the complaint about an invalid message; then take the line out.
There is a second standard connection type, Streamable HTTP, where each message is an HTTP POST to one endpoint. It suits a server shared across machines. An older design, HTTP with server-sent events (SSE), was superseded by Streamable HTTP in the 2025-03-26 revision of the protocol, and the SDK advises building nothing new on it. Older tutorials still show it, so you will meet it. The Copilot uses stdio because the ticket server runs on the same laptop.
How do I call an MCP server from Python?
You describe the process with StdioServerParameters and give it to a Client. Entering the async with Client(...) block starts the server; leaving it stops it. This is the core of code/call_server.py:
SERVER = StdioServerParameters(
command=sys.executable,
args=[str(HERE / "ticket_server.py")],
env={"TICKETS_DB": str(HERE / "tickets.db")},
)
async def call_tool_async(name, arguments):
async with Client(SERVER) as client:
result = await client.call_tool(name, arguments)
return result.content[0].text
def call_ticket_tool(name, arguments):
return anyio.run(call_tool_async, name, arguments)
The child process does not inherit your environment, so anything the server needs, such as the database path, goes in through env=. When you run python code/call_server.py the script lists the tools with client.list_tools(), calls lookup_ticket for T-1042, reads the resource ticket://T-1043 with client.read_resource(...) and fetches the summarise_ticket prompt with client.get_prompt(...): all three kinds of MCP thing from one small client. Look for each of those four results on the screen; a log line from the server is normal, because it goes to standard error. For tests you can skip the process altogether: Client(mcp) connects straight to the server object with no subprocess, no port and no transport.
How does the Copilot call the server?
The graph in code/copilot_graph.py is session 28’s graph with one change. Its lookup_node and create_node no longer import the old tools file; they call call_ticket_tool() from code/call_server.py:
def lookup_node(state):
return {"answer": call_ticket_tool(
"lookup_ticket", {"ticket_id": state["ticket_id"]})}
def create_node(state):
return {"answer": call_ticket_tool(
"create_ticket", {"title": state["title"]})}
anyio.run lets the graph’s ordinary code wait for the client’s async code. The approval step is untouched: approval_node still pauses for a person, and create_node runs only after a yes. Try it with python code/ask_copilot.py "What is the status of ticket T-1043?", which goes through the server, and python code/ask_copilot.py "Please raise a ticket: my monitor flickers.", which pauses and asks you for yes or no. Check the first answer against the T-1043 row in code/data/tickets.csv, and run python code/make_tickets_db.py afterwards to reset the table. Each call starts the server and stops it again, which is simple and good enough here; a larger program would keep one connection open.
What goes wrong with a first MCP server?
Three situations catch nearly everyone once.
- The Copilot waits and does not list the tools. The server file printed a banner when it started. On stdio the output stream carries the messages, so the banner was read as a broken message. Fix: log to standard error instead of printing.
- The server works in your terminal but cannot find the database when the Copilot starts it. The child process did not inherit the environment where you had set the path. Fix: pass the value with
env=. - The IT team’s assistant still shows a bug you fixed last week. The lookup was copied into its code, so the fix did not reach it. Fix: both assistants call the server.
| What you learned | The design decision | Where it shows |
|---|---|---|
| One server can serve many assistants | Keep ticket tool code in one MCP server | code/ticket_server.py |
| On stdio the output stream is the wire | Log; do not print | code/ticket_server.py |
| The child process has its own environment | Pass settings with env= |
code/call_server.py |
| A model may call tools by itself | Keep a person’s approval in front of writes | approval_node in code/copilot_graph.py |
Flashcards: how well do I know the MCP basics?
Say the answer aloud before revealing it. Speaking is a different skill from reading, so practise both.
1. What is MCP?
The Model Context Protocol is an open standard for how an application offers tools and information to a language model. One server can then serve many assistants, like a standard wall socket that any appliance can plug into.2. What are the host, the client and the server?
The host is the application, such as the Copilot, which creates clients. Each client is one connection that talks to a single server. The server is the program that offers tools, resources and prompts, like a department on the end of a switchboard line.3. What is a tool, and who decides to use it?
A tool is an action a server offers, such as looking up a ticket. Tools are designed to be model-controlled, so the model decides when to call one, which is why a person should still be able to deny risky calls.4. What is a resource, and who decides to use it?
A resource is data a server makes available, such as the text of ticket T-1042 at `ticket://T-1042`. Resources are application-driven: the host application decides what to hand to the model.5. What is a prompt in MCP?
A prompt is a message template the server offers and the user picks from a menu, such as a slash command. It is the opposite of a tool, which the model picks.6. How does the SDK turn a Python function into a tool?
The function's name becomes the tool name, its docstring becomes the description the model reads, and its type hints become the input schema. You write no schema or protocol code by hand.7. Which class builds a server, and how does it run over stdio?
You create an `MCPServer` imported from `mcp.server`, register functions with decorators, and call `mcp.run()` with no argument, which serves over stdio.8. Why must a stdio server not print to standard output?
Standard output is the wire: the client reads the messages from it. A stray `print()` is read as a broken message and the client can hang, so use the logging module instead.9. Why does a server started by a client sometimes miss a setting you made in your terminal?
The child process does not inherit the parent's environment. Pass what it needs, such as the database path, with `env=` in `StdioServerParameters`.10. Which connection type should a new project avoid, and why?
HTTP with server-sent events. It was superseded by Streamable HTTP in the 2025-03-26 revision, and the SDK advises building nothing new on it. Use stdio for a local server and Streamable HTTP for a shared one.Model answer: how do I explain MCP in an interview?
The core question this session answers: “A teammate asks: what is MCP, what are its three parts, and what do tools, resources and prompts each give a model?”
Four beats a teammate listens for, in this order: a shared standard · host, client and server · tools, resources and prompts · stdio and logging. Skip any of these four and the answer is incomplete.
- A shared standard: one open protocol, one server, many assistants.
- Host, client and server: who creates what, and how many servers each client talks to.
- Tools, resources and prompts: the model, the application and the user each decide.
- stdio and logging: how a local server runs, and the two mistakes it invites.
The full answer, said aloud:
(A shared standard) “MCP is an open protocol for offering tools and information to a language model. Instead of copying a tool into each assistant, I run it once as a server, and the assistants call it. A fix reaches the other assistants too.
(Host, client and server) The host is the application, like the Copilot. It creates one client for each server, and each client talks to a single server. The server is the program that offers the tools.
(Tools, resources and prompts) A server offers three things. Tools are actions the model decides to call. Resources are data the application chooses to hand over. Prompts are templates the user picks. Because the model can call tools by itself, a person should be able to deny the risky ones.
(stdio and logging) For a local server I use stdio: the client starts the server as a child process and talks over its input and output. So the server logs and does not print, and the client passes settings with
env=, because the child does not inherit them.“
Missing a beat is a failure state. The follow-up question lands where you went quiet: skip the last beat and you are asked why the server hung when someone added a print line. Practise until the four come out without prompting, then stop talking and let the questions come.
Why this matters: why does MCP matter at work?
In a conversation with a teammate or manager: people who build with models are asked how an assistant gets its tools. “One shared server speaking an open protocol” is a short, clear answer, and the three kinds (tool, resource, prompt) show you know what the protocol offers.
On the job: a platform team that shares internal tools with several assistants needs one place to fix a tool and one place to enforce who may call it. MCP gives both. The same habits, logging instead of printing and passing settings explicitly, are the first things to check when a new server will not start.
In the rest of this course: session 30 makes the server check who is calling and records the calls. Session 31 adds a supervisor and a policy agent that use the server, and session 32 brings them together in Milestone 3.
After this unit: what do I do after this lesson, and what comes next?
Assignment. Run python code/call_server.py, then add a second line to the docstring of lookup_ticket, run it again and note which part of the tool listing changed. Project step. Write code/ticket_server.py with lookup_ticket, create_ticket, one resource and one prompt, write the client code/call_server.py with call_ticket_tool(), and make lookup_node and create_node in code/copilot_graph.py call the server. The build prompts are code/prompts/1-write-ticket-server.md, code/prompts/2-write-call-server.md and code/prompts/3-write-ask-copilot.md. Keep the write tool behind the approval step. The brief for the project work is the project file. Next session: MCP in a company, where the same server learns to check who is calling.
Want help building this with someone?
Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.
Ask about mentor-led trainingTechEazy Consulting training material — not affiliated with or endorsed by OpenAI, Anthropic, LangChain or any other company named in this course.