Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

MCP hosts, clients and servers

After this lesson: I can explain how one MCP host uses a separate client for each server it connects to.

70 min lesson7 commandsAgent lab: write an AI agent loop with tools, with a stand-in model

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Why MCP has hosts, clients and servers

The Model Context Protocol (MCP) is a standard way for an AI app to reach tools and data. A chat app, a code editor and a terminal assistant can all use the same weather server.

Without it, every app writes its own adapter for every tool. In this lesson you build a host that talks to two servers at once.

By the end of this lesson

Note

I can explain how one MCP host uses a separate client for each server it connects to.

Key words

WordWhat it meansExample
Hostthe AI app the person uses
Clientthe part of a host that talks to one server
Servera program that offers tools, resources or prompts
Transporthow messages travel between a client and a server
Capabilitya feature one side says it supports
Protocol versionthe dated edition of the rules2026-07-28

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Three roles, one connection each

The host is the app the person uses, such as a chat app or an editor. It holds the model, the conversation and the person's consent.

For each server it connects to, the host makes one client. A client talks to exactly one server and keeps nothing from the others. So a host with five servers has five clients, and a server never sees what another server said.

One host, one client per server

flowchart LR
  P[Person] --> H[Host: chat app]
  H --> C1[Client 1]
  H --> C2[Client 2]
  C1 -->|stdio| S1[Server: buses]
  C2 -->|stdio| S2[Server: weather]

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

N times M adapters become N plus M

Imagine 3 AI apps and 4 tools with no shared protocol. Each app needs its own adapter for each tool: 3 times 4 is 12 adapters to write and fix.

With MCP, each app writes one client side and each tool writes one server: 3 plus 4 is 7 pieces. Adding a fifth tool costs one server, not three adapters.

Try it: adapters against pieces

Code: python
# Without a shared protocol, every app needs its own adapter for every tool.
apps = 3      # a chat app, an editor and a terminal assistant
servers = 4   # files, calendar, buses and weather

print("adapters without a protocol:", apps * servers)
print("pieces with one protocol:", apps + servers)

# Change apps to 10 and servers to 50. Which number grows faster?

Make a free account to save your work and track your progress.

Every request carries its own version

Earlier editions, up to 2025-11-25, began with an initialize handshake, as module 83 showed. The 2026-07-28 edition removed it.

Now every request names its protocol version and the client's capabilities in a _meta field. A client may first send server/discover to learn the versions and capabilities a server supports. A server that does not know the version refuses with error -32022 and lists the ones it does.

Worked example: the messages a host sends

MethodWhat it asksWhat comes back
server/discoverWhich versions and features do you have?supportedVersions, capabilities, serverInfo
tools/listWhich tools do you offer?A list of names, descriptions and input schemas
tools/callRun this tool with these argumentscontent, isError and resultType
Any request, unknown versionThe same, with a version the server lacksError -32022 with the supported list

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Write two servers in one file, part 1

Command
docker exec tools sh -c "mkdir -p mcp && printf '%s\n' '\"\"\"A small MCP server over stdio. Which one it is comes from its first argument.\"\"\"' 'import json' 'import sys' 'VERSION = \"2026-07-28\"' 'SERVERS = {' '    \"buses\": [\"next_bus\", \"Next buses at a stop.\", \"stop\", {\"Market Street\": \"8:05 and 8:20\"}],' '    \"weather\": [\"forecast\", \"Tomorrow in a town.\", \"town\", {\"Leeds\": \"Rain, 9 C\"}],' '}' 'NAME = sys.argv[1]' 'TOOL, ABOUT, ARG, DATA = SERVERS[NAME]' 'SCHEMA = {\"type\": \"object\", \"properties\": {ARG: {\"type\": \"string\"}}, \"required\": [ARG]}' 'def answer(msg):' '    params = msg.get(\"params\", {})' '    asked = params.get(\"_meta\", {}).get(\"io.modelcontextprotocol/protocolVersion\")' '    if not asked == VERSION:' '        return {\"error\": {\"code\": -32022, \"message\": \"Unsupported protocol version\",' '                          \"data\": {\"supported\": [VERSION], \"requested\": asked}}}' > mcp/server.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write two servers in one file, part 2

Command
docker exec tools sh -c "printf '%s\n' '    if msg[\"method\"] == \"server/discover\":' '        about = {\"io.modelcontextprotocol/serverInfo\": {\"name\": NAME, \"version\": \"1.0\"}}' '        return {\"result\": {\"resultType\": \"complete\", \"supportedVersions\": [VERSION],' '                           \"capabilities\": {\"tools\": {}}, \"_meta\": about}}' '    if msg[\"method\"] == \"tools/list\":' '        tool = {\"name\": TOOL, \"description\": ABOUT, \"inputSchema\": SCHEMA}' '        return {\"result\": {\"resultType\": \"complete\", \"tools\": [tool],' '                           \"ttlMs\": 60000, \"cacheScope\": \"public\"}}' '    if msg[\"method\"] == \"tools/call\":' '        value = params[\"arguments\"][ARG]' '        text = DATA.get(value, \"nothing known for \" + value)' '        return {\"result\": {\"resultType\": \"complete\", \"isError\": False,' '                           \"content\": [{\"type\": \"text\", \"text\": text}]}}' >> mcp/server.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write two servers in one file, part 3

Command
docker exec tools sh -c "printf '%s\n' '    return {\"error\": {\"code\": -32601, \"message\": \"Method not found\"}}' '' '' '# One message a line in, one a line out. Logs would go to stderr, never stdout.' 'for line in sys.stdin:' '    msg = json.loads(line)' '    reply = {\"jsonrpc\": \"2.0\", \"id\": msg[\"id\"]}' '    reply.update(answer(msg))' '    print(json.dumps(reply), flush=True)' >> mcp/server.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the host and its clients, part 1

Command
docker exec tools sh -c "mkdir -p mcp && printf '%s\n' '\"\"\"A host with one client per server: it finds every tool and sends each call to its owner.\"\"\"' 'import json' 'import subprocess' 'import sys' 'INFO = {\"name\": \"lab-host\", \"version\": \"1.0\"}' '' '' 'def meta(version):' '    return {\"io.modelcontextprotocol/protocolVersion\": version,' '            \"io.modelcontextprotocol/clientInfo\": INFO,' '            \"io.modelcontextprotocol/clientCapabilities\": {}}' 'class Client:' '    def __init__(self, server):' '        command = [sys.executable, \"mcp/server.py\", server]' '        self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)' '        self.last_id = 0' '' '    def ask(self, method, params, version=\"2026-07-28\", show=False):' '        self.last_id += 1' '        params = dict(params, _meta=meta(version))' > mcp/host.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the host and its clients, part 2

Command
docker exec tools sh -c "printf '%s\n' '        line = json.dumps({\"jsonrpc\": \"2.0\", \"id\": self.last_id, \"method\": method, \"params\": params})' '        self.proc.stdin.write(line + chr(10))' '        self.proc.stdin.flush()' '        reply = self.proc.stdout.readline().strip()' '        if show:' '            print(\"  ->\", line)' '            print(\"  <-\", reply)' '        return json.loads(reply)' 'clients = {\"buses\": Client(\"buses\"), \"weather\": Client(\"weather\")}' 'owner = {}' 'for name, client in clients.items():' '    found = client.ask(\"server/discover\", {})[\"result\"]' '    print(\"server\", name, \"versions\", found[\"supportedVersions\"], \"capabilities\", found[\"capabilities\"])' '    for tool in client.ask(\"tools/list\", {})[\"result\"][\"tools\"]:' '        owner[tool[\"name\"]] = name' 'print(\"tools the host can offer:\", owner)' 'print(\"call forecast, sent to\", owner[\"forecast\"])' >> mcp/host.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the host and its clients, part 3

Command
docker exec tools sh -c "printf '%s\n' 'clients[owner[\"forecast\"]].ask(\"tools/call\", {\"name\": \"forecast\", \"arguments\": {\"town\": \"Leeds\"}}, show=True)' 'print(\"ask with an older version:\")' 'clients[\"buses\"].ask(\"tools/list\", {}, version=\"2025-11-25\", show=True)' 'for client in clients.values():' '    client.proc.stdin.close()' '    client.proc.wait()' >> mcp/host.py"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Run the host against both servers

Command
docker exec tools python3 mcp/host.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What host.py printed

StepWhat it showed
Discoverserver buses and server weather, each with versions ['2026-07-28'] and capabilities {'tools': {}}
Cataloguetools the host can offer: {'next_bus': 'buses', 'forecast': 'weather'}
Route a callcall forecast, sent to weather, answered "Rain, 9 C" with resultType "complete"
Old versiona request naming 2025-11-25 got error -32022, supported ["2026-07-28"]

The cells students fill in are left blank in this preview.

Check the Run

Have a go

Check the Run

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A common mistake

Warning

Many people think one MCP client talks to many servers. In MCP a client is one connection to one server, so a host keeps one per server. That keeps each server apart, and lets the host name two tools called search by their servers.

Match each word to its meaning

Have a go

Loading…

Your answers are marked here and are not kept. An account keeps your marks.

Assignment: build a host's catalogue

Write three functions a host uses when it connects to several servers.

adapters(apps, servers) returns [apps * servers, apps + servers]. catalogue(servers) takes a dictionary from server name to a list of tool names and returns a dictionary from "server__tool" to the server name. clashes(servers) returns the tool names that two or more servers offer, sorted.

Code: python
def adapters(apps, servers):
    # Return a list of two numbers: adapters with no protocol (one per app and
    # server pair), then pieces with one shared protocol (one per app or server).
    return [0, 0]


def catalogue(servers):
    # servers maps a server name to the list of its tool names.
    # Return a dictionary from "server__tool" (two underscores) to the server name.
    return {}


def clashes(servers):
    # The tool names that two or more servers offer, in alphabetical order.
    return []

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.