Ch 9 — Building an MCP Server — Under the Hood

SDK internals, decorator mechanics, lifecycle hooks, and advanced patterns
Under the Hood
-
Click play or press Space to begin...
Step- / 10
ADecorator / Registration InternalsWhat happens when you call @mcp.tool()
1
auto_awesome
@mcp.tool()Decorator called
at import time
inspects
search
IntrospectReads signature,
docstring, hints
builds
2
schema
ToolDescriptorname + description
+ inputSchema
stores
inventory_2
RegistryInternal map of
name → handler
3
arrow_downward Schema generation from types
BSchema Generation PipelinePython type hints and Zod schemas become JSON Schema
code
Type Hintsstr, int, bool
Optional, Annotated
or
data_object
Pydantic / ZodBaseModel fields
z.object() shape
converts
account_tree
JSON Schemaproperties, required
type, default
used by
4
verified
ValidationSDK validates args
before handler
5
arrow_downward Server lifecycle and initialization
CServer LifecycleFrom mcp.run() to handling requests
play_arrow
mcp.run()Starts event loop
opens transport
waits
handshake
initializeClient sends init
server responds
then
6
route
Request RouterDispatches to
correct handler
calls
functions
Your HandlerDecorated function
runs async
7
arrow_downward Context object and server-initiated requests
DContext Object & Server RequestsThe ctx parameter and calling back to the host
token
Contextctx parameter
injected by SDK
provides
notifications
Progressctx.report_progress
ctx.info / ctx.error
+
8
smart_toy
Samplingctx.sample()
ask LLM from tool
+
quiz
Elicitationctx.elicit()
ask user from tool
9
arrow_downward Error handling and return types
EReturn Types & Error HandlingWhat your handler returns and how errors propagate
output
Return strAuto-wrapped in
TextContent
or
list
Return Content[]Explicit text +
image + resource
or
error
Raise / ThrowMcpError or
ToolError
10
arrow_downward Advanced patterns and composition
FAdvanced PatternsComposition, lifespan, middleware, and mounting
account_tree
LifespanStartup/shutdown
resource management
+
merge
ComposeMount servers
as prefixed groups
+
deployed_code
ASGI / ExpressEmbed MCP in
existing web apps
1
Detail