Sub topic 2
Building an MCP Tool Loop
Assume you can write Python with async/await, read JSON Schema, and use an LLM API's tool-calling feature. This chapter builds the path from an MCP server to an LLM.
Build a small server
An MCP server publishes tools. The Python SDK derives the tool's input schema from its type hints.
# server.py
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("calc")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
if __name__ == "__main__":
mcp.run(transport="stdio")The stdio transport lets a client start the server as a subprocess and exchange protocol messages through standard input and output.
Connect and discover tools
ClientSession performs initialization and provides typed operations for discovery and calls.
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
params = StdioServerParameters(command="python", args=["server.py"])
async def main():
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
response = await session.list_tools()
for tool in response.tools:
print(tool.name, tool.description)
print(tool.inputSchema)
result = await session.call_tool("add", {"a": 2, "b": 3})
print(result.isError, result.content)
asyncio.run(main())inputSchema is a JSON Schema object. It tells the model which arguments the tool accepts.
Map tools and run the loop
Each LLM provider wraps tools differently. For Anthropic's Messages API, MCP fields map directly to name, description, and input_schema.
def to_llm_tools(mcp_tools):
return [
{
"name": tool.name,
"description": tool.description or "",
"input_schema": tool.inputSchema,
}
for tool in mcp_tools
]The loop sends tools to the model, executes every requested call through MCP, and sends the results back.
import anthropic
llm = anthropic.Anthropic()
MODEL = "your-model-id"
async def run_turn(session, user_text):
tools = to_llm_tools((await session.list_tools()).tools)
messages = [{"role": "user", "content": user_text}]
for _ in range(10):
response = llm.messages.create(
model=MODEL, max_tokens=1024, tools=tools, messages=messages
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
return "".join(
block.text for block in response.content if block.type == "text"
)
results = []
for block in response.content:
if block.type != "tool_use":
continue
result = await session.call_tool(block.name, block.input)
text = "\n".join(
item.text for item in result.content if item.type == "text"
)
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": text,
"is_error": bool(result.isError),
})
messages.append({"role": "user", "content": results})
raise RuntimeError("Tool loop exceeded its step limit")Exercise
What does the host do when the model returns a tool_use block?
Show answer
It calls the named MCP tool with the block's input, then sends a tool_result containing the result and matching tool-use ID back to the model.