About this notebook
Companion to Module 3: Tools and MCP. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
In Notebook 3a every tool lived in the agent’s own process, written by you. In practice an agent also wants tools that someone else wrote and maintains: a GitHub integration, a database, a browser. The Model Context Protocol (MCP) is the standard way to offer tools to any agent and to use them from any agent. This notebook
- builds an MCP server with the official Python SDK’s
FastMCP; - talks to it in memory, to see the three things a server can offer;
- talks to it by hand over stdio, to see that the protocol is just JSON lines;
- uses the SDK client over stdio, the way real deployments run;
- wraps the server’s tools as
agentlabtools and gives them to an agent; - looks at what you are trusting when you plug a server in.
Which model answers here?
The MCP parts are real: a real server process, the real protocol, the official SDK. Only the agent in section 5 needs a model, and with no
MODELset it is the offline policy model, which picks a tool by counting words shared with the tool’s description. Read its choices as mechanics, not as evidence of what a real model would do.
from agentlab.nbsetup import setup
nb = setup("03b_mcp")
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. Why a protocol
Without a standard, every agent framework writes its own adapter for every tool provider. With one, each side implements the protocol once:
without a standard: M x N adapters with MCP: M + N implementations
agent A ---+--- GitHub agent A --+ +-- GitHub server
agent B ---+--- database agent B --+-- MCP -----+-- database server
agent C ---+--- browser agent C --+ +-- browser server
(every agent wires up every tool) (clients) (servers)An application (Claude Code, an IDE, your agent) runs an MCP client for each server it connects to. A server offers three kinds of things:
| primitive | who decides to use it | example |
|---|---|---|
| tools | the model, by calling them | search_kb(query) |
| resources | the application, by reading them into context | kb://index, a list of pages |
| prompts | the user, by picking one | “answer with sources” |
Messages are JSON-RPC 2.0. A local server runs as a subprocess and talks over its stdin and stdout (the stdio transport); a remote one uses Streamable HTTP.
2. A server in a few lines
The server below offers the knowledge base from Notebook 3a: the same thirteen pages,
with the same search, imported from agentlab.mcp.servers.kb_server so that both notebooks
agree. FastMCP builds each tool’s schema from the signature, as schema_for did in 3a.
from mcp.server.fastmcp import FastMCP
from agentlab.mcp.servers.kb_server import load_pages, search_pages
server = FastMCP("course-kb", log_level="WARNING") # INFO would log every request
@server.tool()
def search_kb(query: str, max_results: int = 3) -> str:
"""Search the course knowledge base; return titles, URLs and one-sentence snippets.
Args:
query: A few keywords describing what to find.
max_results: How many results to return, at most 5.
"""
return search_pages(query, max_results)
@server.tool()
def read_page(url: str) -> str:
"""Return the full text of one knowledge-base page.
Args:
url: The page's address, exactly as returned by search_kb.
"""
pages = load_pages()
if url not in pages:
raise ValueError(f"no page at {url}; use a URL returned by search_kb")
return pages[url]["title"] + "\n" + pages[url]["text"]
@server.resource("kb://index", mime_type="text/plain")
def index() -> str:
"""Every page in the knowledge base: title and URL, one per line."""
return "\n".join(f"{p['title']}: {u}" for u, p in load_pages().items())
@server.prompt()
def answer_with_sources(question: str) -> str:
"""A prompt that asks for an answer grounded in the knowledge base, with citations."""
return (f"Answer this question using only pages from the course knowledge base. "
f"Search first, read what you need, and cite each page's URL.\n\n"
f"Question: {question}")Nothing runs yet: server is an object with registered handlers. A real server would end
with server.run(), which serves stdio until its input closes.
agentlab/mcp/servers/kb_server.py is this same server saved as a module, so that section
3 can start it as a separate process.
3. Talking to it in memory
The SDK can connect a client to a server object inside the same process, with no
subprocess. That is the quickest way to see what a client gets. The helper performs the
protocol’s opening handshake (initialize) for us.
import json
from mcp.shared.memory import create_connected_server_and_client_session
async with create_connected_server_and_client_session(server) as session:
listed = await session.list_tools()
for t in listed.tools:
print(f"{t.name}: {t.description.splitlines()[0]}")
print()
print(json.dumps(listed.tools[0].inputSchema, indent=2))search_kb: Search the course knowledge base; return titles, URLs and one-sentence snippets.
read_page: Return the full text of one knowledge-base page.
{
"properties": {
"query": {
"title": "Query",
"type": "string"
},
"max_results": {
"default": 3,
"title": "Max Results",
"type": "integer"
}
},
"required": [
"query"
],
"title": "search_kbArguments",
"type": "object"
}
The inputSchema is plain JSON Schema, so it drops into the parameters field of a tool
definition unchanged. Compare it with Notebook 3a’s schema_for. FastMCP adds title
fields, and it does not copy the Args: descriptions into the properties; they reach
the model only as part of the tool’s description. If per-argument descriptions matter for
your tool, annotate the parameters (for example with Pydantic’s Field(description=...)).
Now a call that works, a call that fails, a resource and a prompt:
async with create_connected_server_and_client_session(server) as session:
ok = await session.call_tool("search_kb", {"query": "JSON-RPC transports"})
print("isError:", ok.isError)
print(ok.content[0].text, "\n")
bad = await session.call_tool("read_page", {"url": "https://kb.example/nowhere"})
print("isError:", bad.isError)
print(bad.content[0].text, "\n")
resource = await session.read_resource("kb://index")
print("\n".join(resource.contents[0].text.splitlines()[:4]), "\n...\n")
prompt = await session.get_prompt("answer_with_sources", {"question": "What is BFCL?"})
print(prompt.messages[0].role, "->", prompt.messages[0].content.text)isError: False 1. Model Context Protocol (MCP) (https://kb.example/protocols/model-context-protocol) Messages use JSON-RPC 2.0. 2. JSON Schema in brief (https://kb.example/formats/json-schema) JSON Schema is a vocabulary for describing the shape of JSON data. 3. Pydantic (https://kb.example/python/pydantic) A Pydantic model can emit a JSON Schema of itself, which is how many agent frameworks describe structured outputs and tool arguments to a model. isError: True Error executing tool read_page: no page at https://kb.example/nowhere; use a URL returned by search_kb HTTP 429 Too Many Requests: https://kb.example/http/429-too-many-requests HTTP 503 Service Unavailable: https://kb.example/http/503-service-unavailable Exponential backoff with jitter: https://kb.example/patterns/exponential-backoff JSON Schema in brief: https://kb.example/formats/json-schema ... user -> Answer this question using only pages from the course knowledge base. Search first, read what you need, and cite each page's URL. Question: What is BFCL?
Note how the failure arrives: not as an exception in the client, but as a normal result
with isError: true and a message. That is the same “errors are observations” rule as in
Notebook 3a, built into the protocol: the server keeps running, and the message is meant
to be shown to the model.
4. The protocol by hand
Over stdio, MCP is one JSON object per line. Starting the packaged server as a subprocess
and writing those lines ourselves shows everything the SDK hides. Every request carries an
id, and the reply carries the same id; a notification has no id and gets no reply.
import select
import subprocess
import sys
from mcp.client.stdio import get_default_environment
from mcp.types import LATEST_PROTOCOL_VERSION
proc = subprocess.Popen(
[sys.executable, "-m", "agentlab.mcp.servers.kb_server"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
env=get_default_environment(), # the same short list of variables the SDK passes on
)
def send(message: dict) -> None:
line = json.dumps(message)
print(">>>", line if len(line) <= 120 else line[:117] + "...")
proc.stdin.write(line + "\n")
proc.stdin.flush()
def receive(timeout_s: float = 10.0) -> dict:
ready, _, _ = select.select([proc.stdout], [], [], timeout_s)
if not ready:
raise TimeoutError("the server did not answer")
line = proc.stdout.readline()
print("<<<", line.strip() if len(line) <= 120 else line[:117] + "...")
return json.loads(line)
send({"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": LATEST_PROTOCOL_VERSION, "capabilities": {},
"clientInfo": {"name": "notebook-3b", "version": "0.1"}}})
init = receive()
send({"jsonrpc": "2.0", "method": "notifications/initialized"})>>> {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-11-25", "capabilities": {}, "...
<<< {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{"experimental":{},"prompts":{"listCh...
>>> {"jsonrpc": "2.0", "method": "notifications/initialized"}
The server answered with the protocol version it agreed to, its name, and its
capabilities (which primitives it offers). After the client’s initialized
notification, the session is open. Listing and calling tools are two more requests:
print(init["result"]["serverInfo"], init["result"]["protocolVersion"], "\n")
send({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
tools_reply = receive()
print([t["name"] for t in tools_reply["result"]["tools"]], "\n")
send({"jsonrpc": "2.0", "id": 3, "method": "tools/call",
"params": {"name": "search_kb",
"arguments": {"query": "Unix time", "max_results": 1}}})
call_reply = receive()
print(call_reply["result"]["content"][0]["text"]){'name': 'course-kb', 'version': '1.30.0'} 2025-11-25
>>> {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
<<< {"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"search_kb","description":"Search the course knowledge base; retur...
['search_kb', 'read_page']
>>> {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "search_kb", "arguments": {"query": "Unix time...
<<< {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"1. Unix time (https://kb.example/formats/unix-tim...
1. Unix time (https://kb.example/formats/unix-time)
Unix time counts the seconds that have passed since 00:00:00 UTC on 1 January 1970, not counting leap seconds.
Closing the server’s stdin is the stdio transport’s way of hanging up; the server exits.
proc.stdin.close()
print("server exit code:", proc.wait(timeout=10))server exit code: 0
5. The SDK over stdio
The SDK does the same exchange for you: stdio_client starts the process and gives you two
streams, and ClientSession speaks JSON-RPC over them. Server logs go to errlog; inside
Jupyter, send them to /dev/null (or a file), or they clutter the output.
import os
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
params = StdioServerParameters(command=sys.executable,
args=["-m", "agentlab.mcp.servers.kb_server"])
with open(os.devnull, "w") as devnull:
async with stdio_client(params, errlog=devnull) as (read, write):
async with ClientSession(read, write) as session:
info = await session.initialize()
names = [t.name for t in (await session.list_tools()).tools]
print(info.serverInfo.name, names)course-kb ['search_kb', 'read_page']
This pattern has a catch for agents. The connection exists only inside the async with
block, and the SDK’s transports must be closed by the same asyncio task that opened them.
A notebook runs each cell as its own task, and an agent may run for many steps, so you
want one connection that stays open and can be used from anywhere. Starting a new server
for every tool call would work, but costs a process start each time.
6. MCP tools in an agent
Turning an MCP tool into something an LLM can call is a small step, because inputSchema
is already JSON Schema. Here is the conversion for one tool, using the definition helper
from Notebook 3a’s package:
from agentlab.tools import format_tool_definition
spec = listed.tools[0]
definition = format_tool_definition(spec.name, spec.description, spec.inputSchema)
print(json.dumps(definition, indent=2)){
"type": "function",
"function": {
"name": "search_kb",
"description": "Search the course knowledge base; return titles, URLs and one-sentence snippets.\n\nArgs:\n query: A few keywords describing what to find.\n max_results: How many results to return, at most 5.\n",
"parameters": {
"properties": {
"query": {
"title": "Query",
"type": "string"
},
"max_results": {
"default": 3,
"title": "Max Results",
"type": "integer"
}
},
"required": [
"query"
],
"title": "search_kbArguments",
"type": "object"
}
}
}
agentlab.mcp.MCPToolset packages this. It keeps one connection to a server open inside a
background task and hands requests to that task through a queue, so any cell, and any step
of an agent, can use it. Each tool the server offers becomes an MCPTool, a BaseTool
whose execute sends tools/call and raises an error if the result has isError set.
Agent.act ──► MCPTool.execute ──► queue ──► background task ──► ClientSession ──► server
(owns stdio_client) JSON-RPC processfrom agentlab.mcp import MCPToolset
toolset = await MCPToolset.python_module("agentlab.mcp.servers.kb_server").start()
print(toolset)
print("protocol version:", toolset.protocol_version)<MCPToolset course-kb: ['search_kb', 'read_page']> protocol version: 2025-11-25
The connection opened in the cell above is still open in this one:
from agentlab import Agent, show_trajectory
agent = Agent(model=llm, tools=toolset.tools,
instructions="Answer from the knowledge base and cite the URL.")
for question in ["Search the knowledge base for the transports MCP uses",
"Read the page https://kb.example/nowhere"]:
show_trajectory(await agent.run(question))
print()[user] Search the knowledge base for the transports MCP uses
[agent -> search_kb] {"query": "the knowledge base for the transports MCP uses"}
[search_kb ok] 1. Model Context Protocol (MCP) (https://kb.example/protocols/model-context-protocol) The two...
[agent] According to `search_kb`: 1. Model Context Protocol (MCP) (https://kb.example/protocols/model...
--- status: complete, steps: 2
[user] Read the page https://kb.example/nowhere
[agent -> read_page] {"url": "https://kb.example/nowhere"}
[read_page ERROR] MCPToolError: Error executing tool read_page: no page at https://kb.example/nowhere; use a UR...
[agent -> read_page] {"url": "https://kb.example/nowhere"}
[read_page ERROR] MCPToolError: Error executing tool read_page: no page at https://kb.example/nowhere; use a UR...
[agent] I could not complete this: the tool `read_page` failed with: MCPToolError: Error executing to...
--- status: complete, steps: 3
The agent cannot tell these tools from local ones, which is the point. The second question
shows the error path end to end. The server reported isError, MCPTool raised
MCPToolError, and the agent turned the exception into an observation. The offline model
retried once and then gave up with an explanation.
7. What you are trusting
Plugging in an MCP server is not like importing a library you have read. Three things deserve a look before an agent uses one:
- The server is a program running with your permissions. A stdio server is a process on your machine; it can read your files and use your network. Run servers you did not write in a sandbox (Module 8), and pin their versions. By default the SDK passes the server only a short list of environment variables, so your API keys are not inherited unless you pass them:
print(sorted(get_default_environment()))['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER']
- Tool descriptions are prompts written by someone else. Everything below goes into your model’s context, verbatim, on every request. A description can contain instructions aimed at the model, and a server can change its descriptions between sessions. Read them, and allowlist the tools you actually need.
for t in toolset.tools:
print(f"--- {t.name}\n{t.description}\n")--- search_kb
Search the course knowledge base; return titles, URLs and one-sentence snippets.
Args:
query: A few keywords describing what to find.
max_results: How many results to return, at most 5.
--- read_page
Return the full text of one knowledge-base page.
Args:
url: The page's address, exactly as returned by search_kb.
- Tool results are untrusted data.
read_pagereturns whatever the page says. If it says “ignore your instructions”, that is text, not a command (Module 12 builds defences).
Close the connection when you are done; the server process exits with it.
await toolset.close()
try:
await toolset.call_tool("search_kb", {"query": "MCP"})
except RuntimeError as exc:
print("after close:", exc)after close: the MCP connection is not running; call start() first
Try this
- Add a tool
list_pages(prefix: str)tokb_server.pythat returns the URLs under a prefix such ashttps://kb.example/http/. Restart the toolset and check that the agent sees the new tool without any change to the agent code.- Use
Field(description=...)from Pydantic insearch_kb’s signature and look at theinputSchemaagain. Do the descriptions now appear on each property?- In section 4, send
tools/callfor a tool that does not exist, and with a missing argument. Which errors come back as JSON-RPC errors, and which as results withisErrorset?- Time
MCPToolset.start()against a singlecall_tool. How many tool calls would an agent have to make before keeping the connection open pays off?
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 5 (fake: 5) | ≈ 1,585 | ≈ 187 | ≈ USD 0.0023 (reference price) |