LLM Field Guide 06 — Reasoning Models and Agents: Thinking, Tool Calling, and MCP¶
A model spends roughly the same compute on every token, so the only way to make it think harder is to let it write more tokens. And it can't call an API at all: it writes text naming a function, and your code runs it. Those two facts explain reasoning models, tool calling, agents, and MCP. The rest is knobs, a while loop, and a wire protocol.
In this post:
- Every token gets the same compute budget
- Era 1: chain-of-thought prompting and self-consistency
- Era 2: models trained to reason
- Test-time compute: a new way to buy accuracy
- Thinking on the wire, the control knobs, and the bill
- When to think, and whether to trust the reasoning
- The model writes a function call as text, your code runs it
- Tool calling end to end on a self-hosted model
- An agent is tool calling inside a
whileloop - MCP turns N×M integrations into N+M
- Build an MCP server in 20 lines
- Tool calling vs MCP vs skills
- Production reality: what breaks first
LLM Field Guide — all 12 posts
Where this fits: Post 05 put the right facts in the window. This post gets the model to reason over them, then gives it hands: tools it can call, a loop that feeds results back, and MCP, the protocol that plugs one agent into many systems.
Every token gets the same compute budget¶
A forward pass costs roughly 2 FLOPs per parameter per token1. For an 8B model that's ~16 GFLOPs, whether the next token is the "sat" in "The cat sat" or the first digit of 17 × 24 × 13.
The model can't pause and think harder inside one token. It has a fixed stack of layers (post 02) and gets one pass through them. Answer a multi-step problem in one token and all the steps have to happen in that one pass. Usually they can't.
Written-out reasoning changes that. Every token the model writes lands in the KV cache (post 04) and becomes input to every later token:
Direct: Q: 17 × 24 × 13 = ? A: 5,304 ← one pass must do two multiplications
Reasoned: 17 × 24 = 408. 408 × 13 = 408×10 + 408×3 = 4,080 + 1,224 = 5,304.
↑ each intermediate result is written down, then read back by later steps
Reasoning tokens work like scratch paper. More tokens means more forward passes, which means more total compute on the problem. Everything in the first half of this post is a way of spending that compute well.
Era 1: chain-of-thought prompting (2022)¶
Chain-of-thought (CoT) prompting puts worked reasoning in the few-shot examples, so the model imitates the reasoning, not just the answer format. Wei et al. showed that eight CoT exemplars on a 540B-parameter model hit state of the art on the GSM8K math benchmark, beating a fine-tuned GPT-3 with a verifier2.
Kojima et al. then found you didn't need examples. Appending "Let's think step by step" raised text-davinci-002's accuracy3:
| Benchmark | Zero-shot | Zero-shot + "Let's think step by step" |
|---|---|---|
| MultiArith | 17.7% | 78.7% |
| GSM8K | 10.4% | 40.7% |
Models already had reasoning ability that the answer-immediately format wasn't using.
Sample many, take the vote: self-consistency¶
One reasoning chain can take a wrong turn. Self-consistency samples several chains at temperature > 0 (post 03) and returns the most common final answer. It improved CoT by +17.9 points on GSM8K, +11.0 on SVAMP, and +12.2 on AQuA4.
Why voting works: say one chain is right 60% of the time and wrong chains scatter across different wrong answers. With 5 samples, a strict majority (3+ correct) alone happens with probability:
That's 60% → at least 68%, and higher in practice because 2 correct votes still win when the 3 wrong ones disagree. The price is 5× the tokens. Every test-time technique makes the same trade: more compute for more accuracy.
Era 2: models trained to reason (2024–)¶
Prompting only coaxes out reasoning the model learned by accident. In September 2024, OpenAI's o1 showed what happens when you train a model to reason with reinforcement learning5:
- Accuracy kept improving with more RL training compute and with more thinking time at inference (test-time compute), a second scaling axis next to parameters and data.
- On AIME 2024 (hard high-school competition math), GPT-4o solved ~12%; o1 solved 74% with one sample and 83% with consensus over 64 samples5.
OpenAI hid o1's raw reasoning, so how to train one stayed open until DeepSeek published a recipe.
DeepSeek-R1: reasoning emerges from reward¶
DeepSeek-R1 (January 2025, later published in Nature6) showed that reasoning can be "incentivized through pure reinforcement learning"6. R1-Zero got no human-written reasoning examples at all: a <think>…</think> template, a reward for a correct answer, and a reward for using the tags7. The training method, RL from verifiable rewards with GRPO, is explained in post 08.
What came out is the point here. Over training, R1-Zero's AIME 2024 pass@1 climbed from 15.6% to 71.0%, and to 86.7% with majority voting7. Nobody told it how to reason. Longer chains, self-checking, and backtracking emerged because they earned reward. The paper documents an "aha moment" where a checkpoint stops mid-solution to re-evaluate ("Wait, wait. Wait.")7.
R1-Zero's output was hard to read, so the released R1 added a small cold-start SFT stage and more RL rounds, reaching 79.8% pass@1 on AIME 2024 and 97.3% on MATH-5007. That reasoning then transfers to small models by plain SFT on teacher outputs (post 08 covers reasoning distillation).
Budget forcing: thinking longer on demand¶
The s1 paper fine-tuned Qwen2.5-32B-Instruct on just 1,000 curated reasoning examples and added budget forcing: when the model tries to stop thinking, append "Wait" so it keeps going. It beat o1-preview by up to 27% on competition math, and forcing longer thinking lifted AIME24 from 50% to 57%8. That's test-time compute as a dial.
Test-time compute: a new way to buy accuracy¶
Snell et al. studied how best to spend inference compute. Allocating it adaptively per prompt was more than 4× more efficient than best-of-N, and at matched FLOPs a small model with extra test-time compute outperformed a 14× larger model on problems where the small model had a non-trivial success rate9.
The menu, cheapest to most expensive:
| Method | How it spends compute | Needs | Typical use |
|---|---|---|---|
| CoT prompt | One longer answer | Nothing | Non-reasoning models, quick wins |
| Native thinking (o-series, R1, Qwen3, Claude) | Trained long reasoning before answering | A thinking model | Default for hard tasks in 2026 |
| Budget forcing / effort level | Longer or shorter thinking on demand | API or engine support | Tuning cost vs accuracy |
| Self-consistency | N full answers, majority vote | Answers you can compare | Math, classification, extraction |
| Best-of-N + verifier | N answers, a checker picks the best | Tests, a reward model, or a judge | Code (run the tests), formal tasks |
Test-time compute doesn't replace a better model. It helps most when the model can sometimes solve the problem. If it never can, more samples just give you more wrong answers.
What thinking looks like on the wire¶
Open reasoning models emit reasoning as text between markers, then the answer. Qwen3 is a hybrid model: one set of weights with thinking on or off. Thinking is on by default, inside a <think>…</think> block10:
<think>
The user wants 17 × 24 × 13. First 17 × 24 = 408. Then 408 × 13 = 5,304.
Let me double-check: 400 × 13 = 5,200 and 8 × 13 = 104, so 5,304. ✓
</think>
17 × 24 × 13 = **5,304**.
Inference engines split that into separate fields so your app can show, log, or hide the reasoning. Qwen3-8B on vLLM with the reasoning parser:
# pip install "openai==3.46.0"
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
def ask(question: str, think: bool):
resp = client.chat.completions.create(
model="Qwen/Qwen3-8B",
messages=[{"role": "user", "content": question}],
# Qwen's recommended sampling: thinking 0.6/0.95, non-thinking 0.7/0.8
temperature=0.6 if think else 0.7,
top_p=0.95 if think else 0.8,
max_tokens=8192,
extra_body={"top_k": 20,
"chat_template_kwargs": {"enable_thinking": think}},
)
msg = resp.choices[0].message
return getattr(msg, "reasoning", None), msg.content, resp.usage.completion_tokens
for think in (False, True):
reasoning, answer, n = ask("Is 9.11 greater than 9.8? Answer yes or no.", think)
print(f"think={think} completion_tokens={n} answer={answer!r}")
Compare completion_tokens: the thinking run spends far more tokens on the same one-word answer. That gap is the cost you'll be managing.
Three gotchas when serving open reasoning models
- The field is
reasoning, notreasoning_content. vLLM renamed it; old clients silently read an empty value11. - Don't use greedy decoding in thinking mode. Qwen's model card warns it causes repetition loops; use temperature 0.6, top-p 0.95, top-k 2010.
max_tokenscovers thinking + answer. Set it too low and the model runs out mid-thought and never answers.
The control knobs on every major platform¶
Every provider now exposes "how hard to think" as a parameter. The names differ:
| Platform | Knob | Values | Notes |
|---|---|---|---|
| Claude API12 | output_config.effort + thinking: {type: "adaptive"} | low · medium · high · xhigh · max (per model) | Model decides when and how much to think; default high on most models, medium on Opus 5.5 and Haiku 5.5. budget_tokens returns a 400 on Claude 4.7+13 |
| OpenAI API14 | reasoning.effort | none · minimal · low · medium · high · xhigh · max (subset per model) | Reasoning tokens hidden but billed as output; opt-in summaries |
| Qwen3 (open)10 | enable_thinking in chat template; /think, /no_think in a message | on / off per request or per turn | Soft switches work only when enable_thinking=True |
| gpt-oss (open)15 | System prompt line Reasoning: high | low · medium · high | 117B total / 5.1B active MoE, Apache 2.0 |
| vLLM (any parser-supported model)11 | thinking_token_budget per request | Integer token cap | Needs --reasoning-config; vLLM forces the end-of-thinking string at the cap |
Claude with adaptive thinking and an explicit effort level:
# pip install anthropic
import anthropic
client = anthropic.Anthropic()
resp = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=32000, # hard cap on thinking + answer
thinking={"type": "adaptive"},
output_config={"effort": "medium"}, # low | medium | high | xhigh | max
messages=[{"role": "user", "content": "Find the race condition in this Go code: ..."}],
)
for block in resp.content:
print(block.type) # "thinking" blocks, then "text"
Anthropic's advice for current models: run an effort sweep on your own evals instead of carrying settings over from an older model, and give a large max_tokens at high effort12.
The bill: thinking can cost 10× on the same answer¶
Thinking tokens are output tokens. They're billed at the output rate, take decode time, and occupy the context window1416. OpenAI recommends reserving at least 25,000 tokens for reasoning and output when you start out14.
An illustrative support-bot answer, 300 visible tokens:
| Mode | Output tokens | Relative output cost | Decode time at 60 tok/s |
|---|---|---|---|
| No thinking | 300 | 1× | 5 s |
| Thinking, ~2,000 reasoning tokens | 2,300 | ~7.7× | 38 s |
| Thinking, ~8,000 reasoning tokens | 8,300 | ~27.7× | 2 min 18 s |
| Self-consistency, 5 × no thinking | 1,500 | 5× | 5 s if run in parallel |
The reasoning lengths and the 60 tok/s speed are illustrative; measure your own with usage fields. The order of magnitude is the point: thinking can multiply output cost by 10× or more. Spend it where it changes the result.
When to think, and when not to¶
| Task | Thinking? | Why |
|---|---|---|
| Multi-step math, proofs, puzzles | High | Exactly what RL with verifiable rewards trained for |
| Debugging, code review, non-trivial coding | Medium–high | Planning and self-checking pay off |
| Agent planning, multi-tool tasks | Medium | Thinking between tool calls helps; long agent runs multiply cost |
| Long documents with conflicting facts | Medium | Reconciling sources is multi-step |
| Classification, extraction, routing | Off / low | Single-step; use structured outputs (post 05) instead |
| Chat, rewriting, translation, summaries | Off / low | Fluency task; latency matters more |
| RAG answer generation over good retrieval | Low | The hard part (finding facts) already happened |
Models also overthink: researchers documented o1-style models spending large amounts of compute on trivial questions like "2+3=?" for little benefit18. The default should be the lowest effort that passes your evals.
How you prompt changes too:
- Don't add "think step by step" to a thinking model. It already does. Anthropic recommends general instructions ("think thoroughly") over hand-written step-by-step plans, because the model's reasoning often beats the plan you'd prescribe13.
- State success criteria and ask it to verify against them ("before finishing, check the answer against the test cases")13.
- Keep reasoning in the thinking channel. On some current Claude models, a prompt asking for written-out reasoning in visible
<thinking>tags may be declined; lower the effort instead if you need it cheaper13. - For non-thinking models, manual CoT still works: ask for reasoning first and the final answer in
<answer>tags you can parse.
Can you trust what the model says it was thinking?¶
Not fully. Anthropic tested whether reasoning models admit to using a hint planted in the prompt. Claude 3.7 Sonnet mentioned the hint only 25% of the time and DeepSeek R1 39%; in reward-hacking setups, models acknowledged the hack in under 2% of cases in most scenarios19.
A chain of thought is a debugging signal, not an audit log.
- Don't treat displayed reasoning as proof of why a decision was made, especially for compliance or safety.
- Judge outputs by verifiable checks (tests, citations, schema validation), not by how convincing the reasoning reads.
- Many hosted APIs return summaries or encrypted reasoning rather than raw tokens14; design logging around what you actually get.
Operational notes for thinking models:
- Multi-turn history: on some Claude models the API strips old thinking blocks; on newer ones it keeps them and they count as input16. With open models, drop old
<think>content from history yourself unless the model card says otherwise. - Tool use on Claude: pass the thinking block back unmodified with its tool result; the API checks a cryptographic signature16.
- Changing thinking settings breaks the Claude prompt cache for message content17; pick one setting per session.
- Stream long thinking responses and track thinking tokens separately per route. That's where surprise bills come from.
The model writes a function call as text, your code runs it¶
Now the second half: acting. When you pass tools=[...] to a chat API, the server doesn't hand the model a special "function" object. The chat template turns your JSON schemas into plain text in the system prompt. Here's the tool section of the Qwen3-8B template20:
# Tools
You may call one or more functions to assist with the user query.
You are provided with function signatures within <tools></tools> XML tags:
<tools>
{"type": "function", "function": {"name": "get_pod_status", ...}}
</tools>
For each function call, return a json object with function name and arguments
within <tool_call></tool_call> XML tags:
<tool_call>
{"name": <function-name>, "arguments": <args-json-object>}
</tool_call>
Post-training showed the model thousands of conversations in this format, so it learned to reply with a <tool_call> block when a tool would help. A tool call is next-token prediction that happens to produce JSON between agreed-on tags. (Forcing that JSON to match the schema exactly is constrained decoding, covered in post 03.)
The rest happens outside the model:
Your app Inference server (vLLM) Model
──────── ─────────────────────── ─────
messages + tools ──────▶ chat template renders tools ────────▶ reads prompt
into system prompt as text
◀─────── emits text:
<tool_call>{...}</tool_call>
tool-call PARSER pulls JSON out,
◀─────────────────────── returns OpenAI-style tool_calls[]
run get_pod_status()
append role:"tool" msg ─▶ template renders result as ────▶ reads result,
<tool_response>...</tool_response> writes final answer
Three consequences:
- Every tool definition costs tokens on every request. I tokenized one modest schema (name, one-line description, two string params) with the Qwen3 tokenizer: 100 tokens. The fixed instructions around
<tools>add 77 more. A call itself (get_pod_statuswith two arguments) is 31 tokens. - The parser has to match the model. Qwen emits
<tool_call>tags, gpt-oss uses its "harmony" format, Llama 3.1 emits bare JSON. Wrong parser, and you get raw text instead oftool_calls. - The model can produce a malformed or hallucinated call. It's sampling tokens. Validate arguments against the schema before executing anything.
Tool calling end to end on a self-hosted model¶
Qwen3.5-9B is Apache-2.0, its 9.65B parameters are about 19.3 GB in BF16 (one 24 GB GPU at modest context), and its model card gives the exact vLLM flags21:
pip install "vllm==0.33.0"
vllm serve Qwen/Qwen3.5-9B \
--port 8000 \
--max-model-len 32768 \
--reasoning-parser qwen3 \
--enable-auto-tool-choice \
--tool-call-parser qwen3_coder
--enable-auto-tool-choice lets the model decide when to call a tool; --tool-call-parser turns its output into OpenAI-format tool_calls. vLLM also supports tool_choice set to "required", "none", or a named function to force or block a call22.
Send a request with one tool:
curl -s http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen3.5-9B",
"messages": [
{"role": "user", "content": "Is the api-7f9c pod in payments healthy?"}
],
"tools": [{
"type": "function",
"function": {
"name": "get_pod_status",
"description": "Return the phase, restart count and last event for a Kubernetes pod.",
"parameters": {
"type": "object",
"properties": {
"namespace": {"type": "string", "description": "Kubernetes namespace, e.g. payments"},
"pod": {"type": "string", "description": "Pod name or prefix"}
},
"required": ["namespace", "pod"]
}
}
}]
}'
The response has no answer. It has a call to make (OpenAI Chat Completions shape, abbreviated):
{
"choices": [{
"finish_reason": "tool_calls",
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call_01",
"type": "function",
"function": {
"name": "get_pod_status",
"arguments": "{\"namespace\": \"payments\", \"pod\": \"api-7f9c\"}"
}
}]
}
}]
}
arguments is a JSON string, not an object. Parse it, validate it, run your function, then send the whole conversation back with a role: "tool" message carrying the result.
| Model family | What the model emits | vLLM --tool-call-parser | Source |
|---|---|---|---|
| Qwen3.5 | XML-style tool call tags | qwen3_coder | Qwen3.5 model card21 |
| Qwen2.5 / QwQ | <tool_call> JSON (Hermes style) | hermes | vLLM docs22 |
| gpt-oss | Harmony format | openai | vLLM docs22 |
| Llama 3.1 | Bare JSON | llama3_json | vLLM docs22 |
| DeepSeek V3 / V3.1 | DeepSeek special tokens | deepseek_v3 / deepseek_v31 | vLLM docs22 |
Copy the serve command from the model card, not from a blog post about a different model. A wrong parser fails quietly: the call shows up as text in content and your agent never runs it.
An agent is tool calling inside a while loop¶
One tool call answers one question. An agent keeps calling tools until it decides it's done. The pattern goes back to ReAct (Yao et al., 2022), which interleaved thought → action → observation and beat both reasoning-only and acting-only prompting23.
A complete minimal agent against the vLLM server above, about 50 lines. Every production framework is a more careful version of this:
# pip install "openai==3.46.0"
import json
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="unused")
MODEL = "Qwen/Qwen3.5-9B"
def get_pod_status(namespace: str, pod: str) -> dict:
# Stub: call the Kubernetes API here (read-only service account!)
return {"phase": "CrashLoopBackOff", "restarts": 14,
"last_event": "Back-off restarting failed container"}
def get_recent_deploys(namespace: str, limit: int = 3) -> list:
return [{"image": "payments-api:1.42.0", "at": "2026-11-05T09:12:00Z"}]
TOOLS = {"get_pod_status": get_pod_status, "get_recent_deploys": get_recent_deploys}
SCHEMAS = [
{"type": "function", "function": {
"name": "get_pod_status",
"description": "Return the phase, restart count and last event for a Kubernetes pod.",
"parameters": {"type": "object", "required": ["namespace", "pod"],
"properties": {"namespace": {"type": "string"}, "pod": {"type": "string"}}}}},
{"type": "function", "function": {
"name": "get_recent_deploys",
"description": "List the most recent image deployments in a namespace, newest first.",
"parameters": {"type": "object", "required": ["namespace"],
"properties": {"namespace": {"type": "string"},
"limit": {"type": "integer", "minimum": 1, "maximum": 10}}}}},
]
def run_agent(task: str, max_steps: int = 8) -> str:
messages = [{"role": "system", "content": "You are an SRE assistant. Use tools; never guess."},
{"role": "user", "content": task}]
for step in range(max_steps):
resp = client.chat.completions.create(model=MODEL, messages=messages, tools=SCHEMAS)
msg = resp.choices[0].message
messages.append(msg.model_dump(exclude_none=True))
if not msg.tool_calls: # model chose to answer -> done
return msg.content
for call in msg.tool_calls:
fn = TOOLS.get(call.function.name)
try:
args = json.loads(call.function.arguments)
result = fn(**args) if fn else {"error": f"unknown tool {call.function.name}"}
except Exception as e: # bad JSON or bad args: tell the model
result = {"error": str(e)}
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result)})
return "Stopped: step budget exhausted."
print(run_agent("Why is api-7f9c in payments unhealthy? Check recent deploys too."))
Four lines do most of the safety work:
-
max_steps. Without a budget, a confused model loops forever and burns tokens. - Errors go back as tool results. Feed the model
{"error": ...}and it can often fix its own call. Raise an exception and the agent just dies. - Unknown tool names are handled. Models sometimes invent plausible-sounding tools.
- The full assistant message is appended. Drop the
tool_callsmessage and the nexttoolmessage has nothing to attach to; most templates break.
The hidden cost: every step re-sends everything¶
Each loop iteration is a fresh request carrying the whole history. Using the token counts measured above: a 500-token system prompt, 40 tools at ~100 tokens plus the 77-token header (4,077 tokens), and a 50-token task. Each step adds a 31-token call and a 400-token result.
| Step | Input tokens sent | Running total |
|---|---|---|
| 1 | 4,627 | 4,627 |
| 2 | 5,058 | 9,685 |
| 5 | 6,351 | 27,445 |
| 10 | 8,506 | 65,665 |
That's arithmetic, not a benchmark: a 10-step run sends about 14× the tokens of one request. Two things claw most of it back:
- Prefix caching. Steps share a long identical prefix, so an engine with prefix caching (post 04) computes only the new ~431 tokens per step: about 8.5K tokens of prefill instead of 65.7K. Keep the tool order stable. The MCP 2026-07-28 spec now says servers SHOULD return tools in a deterministic order for exactly this reason24.
- Fewer, sharper tools. Forty tools is 4K tokens before the user says a word. Anthropic measured one Drive-to-Salesforce workflow dropping from 150,000 tokens to 2,000 (98.7%) when tools were exposed as code APIs the agent calls from a sandbox, instead of loading every definition and piping every intermediate result through the model25.
MCP turns N×M integrations into N+M¶
Tool calling solves "how does the model ask for a function." It doesn't solve "who writes the function." Without a standard, every agent framework writes its own GitHub tool, Postgres tool, and Jira tool.
Five agent hosts × eight backend systems = 40 custom integrations. With a shared protocol, it's 5 clients + 8 servers = 13. That's the pitch of the Model Context Protocol (MCP), JSON-RPC 2.0 between three roles26:
| Role | What it is | Example |
|---|---|---|
| Host | The LLM application the user talks to | An IDE, a chat app, your agent service |
| Client | A connector inside the host, one per server | The MCP client library in your agent |
| Server | A process exposing capabilities | k8s-readonly, a GitHub server, a Postgres server |
Servers offer three primitives, and clients can offer one back26:
- Tools: functions the model decides to call (
get_pod_status). - Resources: data the app or user attaches as context (
runbook://payments). - Prompts: templated workflows the user picks (
/incident-summary). - Elicitation (client feature): the server asks the user for more input mid-request.
Two standard transports: stdio (newline-delimited JSON-RPC to a subprocess the client launches, for local tools) and Streamable HTTP (each message is an HTTP POST to one endpoint, with replies as JSON or a request-scoped SSE stream, for remote servers)27.
What changed in the 2026-07-28 spec¶
If you learned MCP in 2025, the current revision is a real break. MCP is now stateless24:
| Area | 2025-11-25 and earlier | 2026-07-28 |
|---|---|---|
| Handshake | initialize / notifications/initialized | Removed; every request carries protocol version and client capabilities in _meta; new server/discover RPC |
| HTTP sessions | Mcp-Session-Id header | Removed; cross-call state goes in explicit server-minted handles passed as tool arguments |
| Server → client requests | Server sends sampling/createMessage, elicitation/create, roots/list | Replaced by Multi Round-Trip Requests: server returns resultType: "input_required", client retries with answers |
| Long-running work | Experimental tasks in core | Official io.modelcontextprotocol/tasks extension with polling |
| Roots, Sampling, Logging | Active | Deprecated (12-month window); log to stderr or OpenTelemetry instead |
| Tracing | Ad hoc | Documented W3C traceparent/tracestate propagation in _meta |
Stateless servers scale like any other HTTP service: a plain load balancer, no sticky sessions. Governance moved too: Anthropic donated MCP to the Agentic AI Foundation, a Linux Foundation directed fund co-founded with Block and OpenAI, on December 9, 202528.
Build an MCP server in 20 lines¶
The official Python SDK is at mcp 2.3.029. Heads-up: in 2.x, FastMCP was renamed MCPServer. Importing mcp.server.fastmcp now raises an error pointing to the migration guide30, and most tutorials online still show the old import.
# k8s_mcp.py — pip install "mcp==2.3.0"
from mcp.server.mcpserver import MCPServer
from mcp.types import ToolAnnotations
mcp = MCPServer("k8s-readonly", instructions="Read-only Kubernetes inspection tools.")
@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
def get_pod_status(namespace: str, pod: str) -> dict:
"""Return the phase, restart count and last event for a Kubernetes pod."""
return {"namespace": namespace, "pod": pod, "phase": "CrashLoopBackOff", "restarts": 14}
@mcp.resource("runbook://{service}")
def runbook(service: str) -> str:
"""Return the on-call runbook for a service."""
return f"# Runbook for {service}\n1. Check pod status\n2. Check recent deploys"
if __name__ == "__main__":
mcp.run(transport="streamable-http", port=8765, stateless_http=True)
The SDK builds the JSON Schema from your type hints and the description from the docstring. I ran this server and called it with raw JSON-RPC, using the 2026-07-28 per-request _meta and no handshake:
curl -s -X POST localhost:8765/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'Mcp-Method: tools/call' -H 'Mcp-Name: get_pod_status' \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call",
"params":{"name":"get_pod_status",
"arguments":{"namespace":"payments","pod":"api-7f9c"},
"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28",
"io.modelcontextprotocol/clientCapabilities":{}}}}'
event: message
data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"text":"{\n \"namespace\": \"payments\",
\"pod\": \"api-7f9c\",\n \"phase\": \"CrashLoopBackOff\",\n \"restarts\": 14\n}",
"type":"text"}],"isError":false}}
stateless_http=True matters
Without it, SDK 2.3.0 ran in backward-compatible session mode in my test and rejected handshake-free requests with Bad Request: Missing session ID. Turn it on for 2026-07-28 clients behind a load balancer.
Your agent's MCP client calls tools/list, turns the result into the tools=[...] array from earlier, and forwards each tool_calls entry as a tools/call. MCP doesn't replace tool calling. It's the plumbing that feeds it.
Tool calling vs MCP vs skills: pick the layer¶
| Native tool calling | MCP server | Skill / playbook | |
|---|---|---|---|
| What it is | Functions defined in your app code | Tools/resources behind a protocol | Instructions + scripts loaded on demand |
| Reuse across apps | None | Any MCP host | Any agent that loads it |
| Best for | 1–5 app-specific functions | Shared systems (GitHub, DB, K8s) | Multi-step procedures ("how we do releases") |
| Token cost | Schema per request | Schema per request (unless filtered) | Small index; body loaded only when used |
| Auth | Your app's credentials | Per-server OAuth / tokens | Inherits from tools it uses |
The MCP vs tool calling vs skills post goes deeper on when to add each layer.
Production reality: what breaks first¶
Agents fail in boring ways long before they fail in exotic ones.
1. Tool selection degrades as the tool list grows¶
Every extra tool is another option to confuse. Similar names (get_user, fetch_user, lookup_user) are worse than many tools. Fixes, in order:
- Write descriptions that say when to use a tool, not just what it does.
- Merge overlapping tools; return rich results instead of chaining three calls.
- Filter tools per task or per agent role instead of exposing everything.
- Re-test after every tool change with a fixed eval set (post 11).
2. Tool results are untrusted input¶
A web page, ticket, or commit message in a tool result can carry instructions the model follows, and in an agent that injected text can trigger the next tool call; prompt injection and the architectural defenses against it are in post 11. The agent-side controls:
- An agent that reads untrusted content (the internet, inbound email) shouldn't also hold write credentials to prod.
- Mark write tools
destructiveHintand require human approval before executing them. - Give MCP servers least-privilege credentials (a read-only Kubernetes ServiceAccount, not cluster-admin).
- Treat tool annotations from third-party servers as untrusted. The MCP spec itself says so26.
3. Tools behave like distributed systems, because they are¶
- Timeouts on every tool call, returned to the model as an error result.
- Idempotency keys on writes. Models retry.
- Trace every call. Propagate
traceparentthrough MCP_meta24 and log tool name, args, latency, and result size. - Cap result size. A 2 MB log dump in a tool result blows the context window and the bill.
The MCP gateway and MCP servers in production posts cover auth, policy, and Kubernetes deployment.
Summary¶
| You want | Use | Knob / rule |
|---|---|---|
| Better answers from a non-thinking model | CoT prompt, answer in tags | Prompt |
| Reliability on comparable answers | Self-consistency (N=3–5, majority vote) | N samples, temperature > 0 |
| Hard reasoning, hosted | Claude adaptive thinking / OpenAI reasoning models | effort / reasoning.effort |
| Hard reasoning, self-hosted | Qwen3, DeepSeek-R1 distills, gpt-oss | enable_thinking, Reasoning: high, thinking_token_budget |
| Cheap and fast | Thinking off or low effort | Lowest effort that passes your evals |
| Code correctness | Best-of-N + run the tests | N, verifier |
| A model that can act | Tool calling with the model card's parser | --enable-auto-tool-choice --tool-call-parser ... |
| Multi-step tasks | Agent loop with budget and error feedback | max_steps, errors as tool results |
| Shared integrations | MCP server (spec 2026-07-28, stateless) | SDK 2.x MCPServer, stateless_http=True |
| Lower agent cost | Prefix caching, stable tool order, fewer tools | Deterministic tools/list |
Ship-it checklist:
- Effort sweep run on your evals;
max_tokensbudgets thinking + answer - Thinking tokens tracked per route; outputs verified by checks, not narrated reasoning
- Serve command (reasoning and tool parser flags) copied from the model card
- Arguments validated against schema before execution
-
max_stepsbudget and per-tool timeouts; errors returned as tool results - Read-only by default; human approval on destructive tools
- Tool list ≤ what the task needs, in a stable order
- Every tool call traced and logged
- MCP servers on SDK 2.x, stateless HTTP, least-privilege creds
Next: Post 07 — Choosing a Base Model: which open-weight family to build on, and what its license lets you do.
Go deeper:
- Building Effective AI Agents: The Anthropic Playbook — when not to build an agent, and how to keep it simple
- MCP vs Tool Calling vs Skills — the three-layer mental model
- MCP Servers in Production — transports, auth, and Kubernetes patterns
- Production AI Agents Need an MCP Gateway — policy, audit, and cost control
- Agentic AI Architectures — design patterns and frameworks (LangGraph and others)
- Building an LLM from Scratch in PyTorch — the forward pass that each reasoning token pays for
-
Kaplan et al., Scaling Laws for Neural Language Models (2020), §2.1: "Evaluating a forward pass of the Transformer involves roughly C_forward ≈ 2N + 2 n_layer n_ctx d_model" add-multiply operations per token. ↩
-
Wei et al., Chain-of-Thought Prompting Elicits Reasoning in Large Language Models (2022): eight CoT exemplars, 540B-parameter model, state of the art on GSM8K. ↩
-
Kojima et al., Large Language Models are Zero-Shot Reasoners (2022): text-davinci-002, MultiArith 17.7% → 78.7%, GSM8K 10.4% → 40.7%. ↩
-
Wang et al., Self-Consistency Improves Chain of Thought Reasoning in Language Models (2022): GSM8K +17.9%, SVAMP +11.0%, AQuA +12.2%, StrategyQA +6.4%, ARC-challenge +3.9%. ↩
-
OpenAI, Learning to reason with LLMs (Sep 12, 2024): performance improves with train-time and test-time compute; AIME 2024 GPT-4o ~12%, o1 74% (single sample), 83% (consensus of 64). ↩↩
-
DeepSeek-AI, DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning (2025); published in Nature 645, 633–638 (2025). ↩↩
-
DeepSeek-AI, DeepSeek-R1 paper (v1 full text): R1-Zero AIME 2024 pass@1 15.6% → 71.0%, 86.7% with majority voting; R1 79.8% AIME 2024, 97.3% MATH-500; accuracy and format rewards. ↩↩↩↩
-
Muennighoff et al., s1: Simple test-time scaling (2025): 1,000 examples (s1K), budget forcing with "Wait"; up to 27% over o1-preview on MATH and AIME24; AIME24 50% → 57%. ↩
-
Snell et al., Scaling LLM Test-Time Compute Optimally can be More Effective than Scaling Model Parameters (2024): >4× efficiency vs best-of-N; outperforms a 14× larger model in a FLOPs-matched comparison. ↩
-
Qwen, Qwen3-8B model card:
enable_thinking(default on),/thinkand/no_thinksoft switches, recommended sampling (thinking: T=0.6, top-p 0.95, top-k 20; non-thinking: T=0.7, top-p 0.8), "DO NOT use greedy decoding." ↩↩↩ -
vLLM docs, Reasoning Outputs:
--reasoning-parser(e.g.qwen3,deepseek_r1),reasoningfield (formerlyreasoning_content),chat_template_kwargs.enable_thinking,thinking_token_budgetwith--reasoning-config. ↩↩ -
Anthropic, Effort: levels low / medium / high / xhigh / max; defaults per model; run an effort sweep on your evals. ↩↩
-
Anthropic, Prompting best practices: adaptive thinking;
budget_tokensreturns 400 on Claude 4.7+; prefer general instructions over prescriptive steps; ask Claude to self-check. ↩↩↩↩ -
OpenAI, Reasoning models:
reasoning.effortvalues; reasoning tokens billed as output and occupy context; summaries; encrypted reasoning items; reserve at least 25,000 tokens. ↩↩↩↩ -
OpenAI, gpt-oss-120b model card: 117B parameters, 5.1B active; reasoning level via system prompt ("Reasoning: high"); harmony format; Apache 2.0. ↩
-
Anthropic, Context windows: thinking tokens count toward the window and
max_tokens, billed as output; per-model thinking-block preservation; signed thinking blocks with tool use. ↩↩↩ -
Anthropic, Prompt caching: thinking parameters and effort changes invalidate the message cache. ↩
-
Chen et al., Do NOT Think That Much for 2+3=? On the Overthinking of o1-Like LLMs (2024). ↩
-
Anthropic, Reasoning models don't always say what they think (Apr 3, 2025): hint mentioned 25% (Claude 3.7 Sonnet) and 39% (DeepSeek R1); reward hacks admitted <2% in most scenarios. ↩
-
Qwen, Qwen3-8B
tokenizer_config.jsonchat template. Token counts in this section were measured by the author with the Qwen3-8B tokenizer (tokenizers0.22.1). ↩ -
Qwen, Qwen3.5-9B model card: Apache-2.0, 262,144-token native context, and the
vllm serve ... --enable-auto-tool-choice --tool-call-parser qwen3_codercommand. ↩↩ -
vLLM, Tool Calling documentation:
--enable-auto-tool-choice, parser list,tool_choiceoptions (requiredsince vLLM 0.8.3). ↩↩↩↩↩ -
Yao et al., ReAct: Synergizing Reasoning and Acting in Language Models, 2022. ↩
-
Model Context Protocol, Specification 2026-07-28: Key Changes: stateless protocol,
server/discover, MRTR, tasks extension, deterministictools/listorder, Roots/Sampling/Logging deprecated, OpenTelemetry_metakeys. ↩↩↩ -
Anthropic Engineering, Code execution with MCP, November 4, 2025. ↩
-
Model Context Protocol, Specification (latest, 2026-07-28): hosts/clients/servers, resources/prompts/tools, elicitation, security principles. ↩↩↩
-
Model Context Protocol, Transports (2026-07-28): stdio and Streamable HTTP bindings. ↩
-
Anthropic, Donating the Model Context Protocol and establishing the Agentic AI Foundation, December 9, 2025. See also the MCP blog post. ↩
-
MCP Python SDK, v2 migration guide: FastMCP renamed to MCPServer. The message is raised by
mcp/server/fastmcp.pyin the 2.3.0 wheel. ↩
Discussion
Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.