Skip to content
Index Ai Academy
Phase 9 · Clients and hosts

Hosts: connecting servers to a model

Many servers, one agent: namespacing, routing and approvals.

About 40 minutes · Model names checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers7

First principles

Why does a host need to remember which server owns a tool name?

Model-visible names may come from several servers. The host gives them unambiguous aliases, keeps the mapping to the original server, and applies the user's approval rules before sending work.

  1. Starting point

    Two connected servers each advertise get_report

  2. What changes

    Host gives each tool a distinct alias and keeps its provenance

  3. Result

    Chosen alias resolves to its owner and passes through approval checks

Compare all three steps
  1. Starting point

    Two connected servers each advertise get_report

  2. What changes

    Host gives each tool a distinct alias and keeps its provenance

  3. Result

    Chosen alias resolves to its owner and passes through approval checks

Complete and reverse the trace

Given Two connected servers each advertise get_report and Chosen alias resolves to its owner and passes through approval checks, write down the missing step that connects them.

Compare with the worked step

Host gives each tool a distinct alias and keeps its provenance

Now take Host gives each tool a distinct alias and keeps its provenance and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Two connected servers each advertise get_report. Check that your implementation produces the result shown above.

Try it on a new case

The model chooses sales_get_report, while support also has get_report. Where should the host send the request?

Show worked reasoning

Send it to the sales server recorded for the alias. Approval, audit records, and result attribution should preserve that same tool identity.

Run, change, and build

Check this when debugging. Thinking the model talks to MCP servers directly (the host does).

Trace the cause · MCP message and permission
  1. Mark which message crosses the client–server boundary and which check determines what the caller may do.
  2. Change the tool input or approved scope. Compare the returned message and stored state to distinguish a denial from an allowed change.
  3. Try the same reasoning on this case. The model chooses sales_get_report, while support also has get_report. Where should the host send the request?

Why it matters

The host is where MCP meets the model and the user. Claude Code, Claude's apps and IDE assistants are all hosts, and so is any agent you build that loads MCP servers. Everything from the agent loop in Phase 1 comes together here: tool definitions, tool_use blocks, tool results and approvals, now fed by any number of servers. Getting the host right is what makes plugging in a new server safe.

What you'll be able to do

  • Describe a host's job: many clients, one model, one user to protect
  • Merge tools from several servers without name clashes, within the model API's naming rules
  • Route a model's tool_use to the right server and turn MCP results into tool_result blocks
  • Decide when to ask the user for approval, using annotations only from trusted servers
Quick check
Two connected servers both offer a tool called search. How does a host keep them apart?
  1. It asks the model to guess which one it means
  2. It keeps only the first server's search tool
  3. It merges them into one combined search tool
  4. It prefixes each tool's name with its server's name
Show the answer

It prefixes each tool's name with its server's name

Prefixing (say, docs__search and crm__search) gives every tool a unique name and tells the host which server to route each call to. Hosts also decide which tools to show, and ask the user before risky calls.

The idea: the host between the model and the servers

This rests on The agent loop: the model asks for a tool, the program runs it and sends back the result. Here the tools come from several MCP servers, and the program in the middle is the host.

The host's job

Picture an executive assistant with a phone line to every department. The boss says "get me last month's sales". The assistant knows who to call, checks that the request is fine, makes the call and brings back the answer. The boss never dials anyone.

A host works the same way, with the model as the boss. It holds one MCP client per server, and one conversation with a model. Each turn it:

  1. Gathers tools from every connected server, and adds the servers' instructions to the system prompt.
  2. Sends the conversation and the merged tool list to the model.
  3. When the model replies with tool_use blocks, finds the server for each tool, checks whether to ask the user first, calls tools/call, and turns each MCP result into a tool_result.
  4. Repeats until the model stops asking for tools.

The model never learns which server a tool came from. To the model, they're all tools.

Quick check
How many MCP clients does a host hold?
  1. One for each connected server
  2. One for each tool
  3. One for each turn
  4. One, shared by every server
Show the answer

One for each connected server

Each client holds one connection to one server. The host merges their tools into one list for the model.

Names: clashes and rules

Two people called John in one office become "John in sales" and "John in accounting". Two servers can both offer search too. The host must give each tool a unique name, usually by prefixing the server's name: crm__search and wiki__search. It keeps a route table from that name back to the server and the tool's original name.

The model API has its own naming rules, too. Claude's tool names must match ^[a-zA-Z0-9_-]{1,64}$, while MCP allows dots and up to 128 characters. So the host also cleans names, swapping disallowed characters for _ and shortening long ones, and refuses to load two tools whose cleaned names collide rather than guessing.

import re

def clean(server, tool):
    name = re.sub(r"[^a-zA-Z0-9_-]", "_", f"{server}__{tool}")
    return name[:64]

for server, tool in [("crm", "search"), ("wiki", "search"), ("files", "fs.read_file"),
                     ("big", "x" * 80)]:
    print(f"{server}/{tool[:20]:20} -> {clean(server, tool)}")
It runs right here in your browser, with nothing to install.
Quick check
From the lesson on the agent loop: only tool_use means "run the tools and call the model again", and a turn limit stops a loop that would never end. What does this print?
def keep_going(stop_reason, turn, max_turns=10):
    return stop_reason == "tool_use" and turn < max_turns

print(keep_going("tool_use", 3), keep_going("end_turn", 3), keep_going("max_tokens", 3),
      keep_going("tool_use", 10))
  1. True True False False
  2. True False True False
  3. True False False True
  4. True False False False
Show the answer

True False False False

The loop continues only while the model is asking for tools and the turn limit hasn't been reached. Any other stop reason ends it, and so does turn 10. A host runs exactly this loop. What it adds is where the tools come from: several MCP servers, each with its own list.

Quick check
What does this print?
tools = [("shop", "search"), ("docs", "search")]
names = [f"{s}__{t}" for s, t in tools]
print(len(set(names)))
  1. 0
  2. 1
  3. 4
  4. 2
Show the answer

2

The names become shop__search and docs__search, which differ, so the set holds 2. A server prefix keeps the two search tools apart.

Quick check
Why does a host prefix tool names with the server's name?
  1. MCP servers reject any call that doesn't begin with their own name
  2. Two servers can offer tools with the same name, and the host must route each call to the right server
  3. Models require a prefix on every tool name, or they refuse to call the tool at all
  4. It makes the tools run faster, since the host can skip looking up which server owns each one
Show the answer

Two servers can offer tools with the same name, and the host must route each call to the right server

The prefix makes names unique across servers, and the route table maps them back to the server and original name.

Drill

Route a prefixed tool name back

A host shows the model names like crm__search, so two servers' search tools don't collide. Write route(name, servers): split at the first __ into server and tool, and return (server, tool). Raise KeyError if there's no __ or the server isn't in servers.

def route(name, servers):
    return name.split("__")


print(route("crm__search", {"crm", "docs"}))
In the lesson, your code is checked as you write it.
Try it now

Every arrow carries the bytes it really carries. The context lane at the side grows as each block joins it.

In your own words
Why prefix tool names with the server's name?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: the host's loop

This part writes the translator and the loop. It ends with one real round trip: discover, call the model, run the tool and answer.

From MCP tool to model tool, and back

The host also acts as a translator, because MCP and the model API describe the same things in slightly different words. Going out, an MCP tool becomes a Claude tool: the cleaned name, the description, and inputSchema as input_schema. Coming back, a tools/call result becomes a tool_result block for the next user turn:

MCP resultClaude tool_result
content text blockscontent: the text
structuredContent with no textcontent: the JSON as text
isError: trueis_error: true, so the model knows to correct itself
image blocksimage content blocks, so the model can see them
the call itself failed (server down, protocol error)is_error: true with a short explanation

Every tool_use must get a tool_result with the same tool_use_id, even when the call failed or the user said no. Otherwise the next model request is rejected.

In plain words: every question the model asks gets an answer, even if the answer is "that failed" or "the user said no".

Approvals

The host stands between the model and the world. A good assistant signs for the small things and checks with you before writing a large check. Before running a tool, the host decides whether to ask the user. A reasonable policy:

  • A tool from a trusted server marked readOnlyHint: true may run without asking.
  • Anything else asks first, and the host shows the arguments, because data leaks out through arguments (an email address, a document's contents).
  • If the user declines, return a tool_result with is_error: true saying so. The model can then explain, or try something else.

Annotations from an untrusted server don't relax anything. A malicious server can label its "exfiltrate everything" tool read-only.

Quick check
The user declines a tool call the model asked for. What should the host send back to the model?
  1. A tool_result for that tool_use_id, with is_error true and a note that the user declined
  2. A new user message saying "never mind", with no tool_result for the call
  3. A fake successful result with empty output, so the model carries on with its plan
  4. Nothing: just skip that tool_use, since the call never actually ran at all
Show the answer

A tool_result for that tool_use_id, with is_error true and a note that the user declined

Every tool_use needs a matching tool_result. Saying the user declined lets the model respond sensibly.

Keeping context under control

Every tool definition goes into the model's context on every turn. Five servers with twenty tools each is a hundred definitions, maybe tens of thousands of tokens, before the user has said anything. Too many tools also make the model choose worse, the way a 300-dish menu slows everyone down.

Hosts fight this by letting users turn servers and tools on and off, and by loading tool definitions on demand: the model first sees short names or a search tool, and the full schema is added when it's needed. A tool registry for agents builds this.

Some model APIs can also act as the MCP client themselves: you pass a list of remote server URLs in the request, and the provider calls the servers during generation. That's convenient, but your code then gives up the routing, approval and logging this lesson builds, so check what control you still have.

Quick check
A host connects 12 servers that offer 300 tools in total. What keeps the model's context manageable?
  1. Drop the tool descriptions to save tokens, keeping only the names and their schemas
  2. Merge all 300 tools into one big tool that takes the real tool's name as an argument
  3. Load only the servers and tools a task needs, defer the rest, and keep results short
  4. Send all 300 definitions on every call, so the model always has every option to hand
Show the answer

Load only the servers and tools a task needs, defer the rest, and keep results short

Every definition costs tokens on every call, and long lists make choosing harder. Fewer, relevant tools work better.

Drill

Fit tool definitions into a budget

Every tool definition costs context tokens on every request. Write fit_tools(tools, budget): estimate each definition as math.ceil(len(json.dumps(tool)) / 4) tokens, take tools in order while the running total stays within budget, skipping any single tool that doesn't fit, and return the names taken.

import json
import math


def fit_tools(tools, budget):
    return [t["name"] for t in tools]


tools = [{"name": "search", "description": "x" * 100},
         {"name": "export", "description": "x" * 900},
         {"name": "get", "description": "x" * 40}]
print(fit_tools(tools, 120))
In the lesson, your code is checked as you write it.
Worked example

Converting one result

Three MCP results, converted into the tool_result blocks the model sees.

import json

def to_tool_result(tool_use_id, result):
    texts = [b["text"] for b in result.get("content", []) if b.get("type") == "text"]
    if not texts and "structuredContent" in result:
        texts = [json.dumps(result["structuredContent"])]
    return {"type": "tool_result", "tool_use_id": tool_use_id,
            "content": "\n".join(texts), "is_error": bool(result.get("isError"))}

ok = {"resultType": "complete",
      "content": [{"type": "text", "text": "Retargeting: 3,940 clicks"}]}
data_only = {
    "resultType": "complete", "content": [], "structuredContent": {"stock": 12}}
failed = {"resultType": "complete", "content": [
    {"type": "text", "text": "No campaign cmp_999."}], "isError": True}
for i, r in enumerate([ok, data_only, failed]):
    print(to_tool_result(f"toolu_{i}", r))
In the lesson you can change this and run it.

Text passes through, structured-only results become JSON text, and isError becomes is_error. A full host would also pass images through as image blocks. The model reads these on its next turn exactly as it would the results of your own Python tools.

One real round trip

Here is the whole path from the picture, in one cell: discover the tools, give them to the model, run the tool it asks for after an approval, and let the model answer. The model is the academy's practice stand-in, whose reply has the real shape and is labeled as simulated. On your own machine the same code sends the same request to a real model. The cell prints every block of the context with an estimate of its tokens (the length divided by 4, rounded up).

import json
import requests

MCP = "https://api.gradient.test/mcp"
PV = "io.modelcontextprotocol/protocolVersion"
CAPS = "io.modelcontextprotocol/clientCapabilities"


def rpc(method, params=None, name=None):
    headers = {"MCP-Protocol-Version": "2026-07-28", "Mcp-Method": method}
    if name:
        headers["Mcp-Name"] = name
    body = {"jsonrpc": "2.0", "id": 1, "method": method,
            "params": {**(params or {}), "_meta": {PV: "2026-07-28", CAPS: {}}}}
    return requests.post(MCP, json=body, headers=headers).json()["result"]


def claude(messages, tools):
    reply = requests.post("https://api.anthropic.com/v1/messages", timeout=60,
        headers={"x-api-key": "added-by-the-academy-server",
                 "anthropic-version": "2026-10-21"},
        json={"model": "claude-opus-5-5", "max_tokens": 400,
              "tools": tools, "messages": messages})
    return reply.json()


def tokens(value):
    return -(-len(json.dumps(value)) // 4)


tools = [{"name": "shop__" + t["name"], "description": t["description"],
          "input_schema": t["inputSchema"]} for t in rpc("tools/list")["tools"]]
messages = [{"role": "user", "content": "How is campaign cmp_103 doing?"}]
first = claude(messages, tools)
use = next(b for b in first["content"] if b["type"] == "tool_use")
print("model asked for", use["name"], use["input"], "-", first["stop_reason"])

approved = True          # a real host asks the user here, and shows the arguments
original = use["name"].split("__", 1)[1]
result = rpc("tools/call", {"name": original, "arguments": use["input"]}, original)
messages.append({"role": "assistant", "content": first["content"]})
messages.append({"role": "user", "content": [{
    "type": "tool_result", "tool_use_id": use["id"],
    "content": result["content"][0]["text"], "is_error": result["isError"]}]})
final = claude(messages, tools)
print("final stop_reason:", final["stop_reason"])

print("tools      ", tokens(tools), "tokens")
for message in messages:
    body = message["content"]
    kind = body[0]["type"] if isinstance(body, list) else "text"
    print(message["role"].ljust(10), tokens(body), "tokens", kind)
In your own words
How does a host keep 300 tools from drowning the context?

Write a sentence or two, then compare it with a good answer in the lesson.

Purpose. See how a real host and the model API do what the loop above does, and what you give up when the provider does it for you.

The Messages API can act as the MCP client itself. You send mcp_servers (where the servers are) and an mcp_toolset entry in tools (which of their tools to offer), and the provider connects to the servers while it generates. Two limits matter: it supports tool calls only, not resources or prompts, and the server must be reachable over HTTP, so a local stdio server can't be used.

A desktop or terminal host does the approving itself. Each shows the server's name, the tool and its arguments, and offers "allow once" or "always allow". The always-allow choice is a rule you add for one tool on one server, and it is the setting to review when something surprising happens.

In an engineer's week. A colleague asks you to add a server to the team's host. You check who publishes it, what its tools are called, which are read-only, and what the host will do without asking. What goes wrong is a tool allowlist set to the whole server: the next version of the server adds a new tool, and it runs without a prompt.

Goes deeper in

The claude_tools() and run_tool_use() methods in this lesson's exercise are the interface a harness's loop takes.

In your own words
A provider offers to be the MCP client for you, through one request. What do you gain, and what do you lose?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 3 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

In MCP, what is the host?

  1. The app with the model and the user, holding one client per connected server
  2. The machine the server runs on, whether local or in the cloud
  3. The company that publishes the server and keeps it maintained
  4. The model itself, which decides what to connect to and when to call it

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 9 · about 13 hours of study

Model Context Protocol

Build MCP servers, clients and hosts, from the wire format to production 17 lessons 1 free
  1. JSON-RPC 2.0 in depth FreeRequests, notifications, errors and a dispatcher built from scratch.35 min
  2. Versions and stateless requestsRevisions by date, the legacy handshake, per-request _meta and version negotiation.30 min
  3. Discovery, capabilities and the two erasserver/discover, declared capabilities, and talking to legacy and modern software alike.30 min
  4. Transports I: stdioNewline-delimited JSON over a subprocess's standard streams.30 min
  5. Transports II: Streamable HTTPOne endpoint, required headers, JSON or event-stream replies.40 min
  6. Build a server: toolsTool definitions, schemas from type hints, results and two kinds of error.45 min
  7. Resources and promptsReadable data, URI templates and reusable prompt templates.40 min
  8. The same server with the official SDKsYour registry and dispatcher on the SDK's decorator shape, in Python and TypeScript.40 min
  9. Build a clientMetadata on every request, version fallback, paging and caching.40 min
  10. Hosts: connecting servers to a modelMany servers, one agent: namespacing, routing and approvals.40 min
  11. Progress, subscriptions and multi-round-trip requestsLong-running work, change notifications and asking the user mid-call.45 min
  12. Securing remote servers with OAuthProtected resource metadata, PKCE, audiences and scope challenges.45 min
  13. MCP securityTool poisoning, rug pulls, confused deputies and local-server risks.40 min
  14. Lab: attack and defend a hostPoisoned tools, injected results, token replay and the defenses that stop each.40 min
  15. Testing, designing and shipping serversConformance checks, tool design for models, SDKs and deployment.40 min
  16. MCP in production: gateways, limits and auditAn allowlist, per-user rate limits, header checks and an audit log in front of many servers.35 min
  17. Capstone: a production MCP serverA complete, tested server for the practice shop.45 min
Practice for interviews 21 questions

AI agent interview questions and answers

Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.

Part of a free course 15 lessons

Build and Deploy MCP Integrations

Build a Model Context Protocol client and server, then verify the integration with a compatible host.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write