8 Applications 8 / 8
  1. In this chapter
  2. Your first agent
  3. Prompt Engineering
  4. Structured Outputs and Function Calling
  5. RAG in Practice
  6. Agents and Tool Calling in Practice
  7. Agent context and memory
  8. Agent Evaluation
  9. MCP and the Tool Ecosystem
All chapters →

Chapter 8 · Applications 8.8

MCP and the Tool Ecosystem: How It Works and What to Do When Tools Pile Up

MCP, the Model Context Protocol, is the open protocol that connects AI applications to external tools and data; its 2026-07-28 revision is stateless. This page shows the protocol in real messages, measures what 96 tool definitions cost in tokens, and compares three ways to pick a tool.

Intermediate 109 min read Updated Companion code ↓

After this page you will be able to

  • Explain that MCP solves integration, not selection: the roles of host, client and server, and who decides when each of the three primitives is used.
  • Read the stateless connection of the 2026-07-28 revision: no handshake and no session, a _meta block on every request, and server/discover for version negotiation.
  • Tell protocol errors from tool execution errors, and write error messages a model can act on.
  • Know what the request-header check, the Origin check and the authorization framework of Streamable HTTP each defend against, and the common attack surfaces such as local servers and token passthrough.
  • Compute how many tokens tool definitions take, shrink 96 tools to a few hundred or about a thousand tokens with BM25 retrieval and an index-then-inspect scheme, and measure the accuracy price of doing so.
  • Choose among putting everything in the prompt, retrieval, progressive disclosure and code mode by tool count and definition size, and say how each affects prompt caching.
On this page
  1. Two Ledgers: Integration Cost and Context Cost
  2. The Protocol at a Glance
  3. Participants and Layers
  4. Three Primitives: Who Decides When to Use Them
  5. Five Revisions
  6. Experiment 1: What One Call Looks Like on the Wire
  7. The Handshake Era and the Stateless Era
  8. What Is in the Messages
  9. No Handshake, No SDK: Speaking the Protocol by Hand
  10. What a Tool Looks Like
  11. Streamable HTTP: Headers and Origin
  12. Security Boundaries
  13. Experiment 2: What Tool Definitions Cost, and Whether the Model Still Chooses Well
  14. Design: one catalog, 24 requests, three ways to choose
  15. Code: how definitions enter the prompt
  16. Code: the requests and the runner
  17. Code: three ways to choose
  18. Results: What 96 Tools Cost and What They Buy
  19. Cost: tokens and seconds
  20. Accuracy: the 4B model barely notices
  21. Three Models, Side by Side
  22. Position and Failures
  23. Reading the Replies
  24. What This Experiment Cannot Say
  25. Choosing: Four Ways to Put Tools in Front of a Model
  26. What the Experiment Says About Each Way
  27. Prompt Caching Decides What Is Cheap
  28. Writing Definitions That Are Cheap to Choose Among
  29. Vendor-Reported Figures
  30. Summary and Exercises
  31. Quick Check
  32. Exercises
  33. Further Reading
  34. FAQ

MCP (the Model Context Protocol) is the open protocol that connects AI applications to external systems: a system implements one server, and every MCP-capable application can discover and call its tools, read its resources and use its prompt templates. It solves integration, not selection: the protocol does not decide which tools to hand to a model, nor whether the model picks the right one. The 2026-07-28 revision of the specification made the protocol stateless and removed the handshake and the session. This page first opens the protocol with real messages, then measures what 96 tool definitions cost in tokens, and compares three ways of choosing among them: everything in the prompt, retrieval, and progressive disclosure.

Two Ledgers: Integration Cost and Context Cost

Without a protocol, N applications that need M external systems need N×M adapters; with one, each system implements a server once and each application implements a client once, so the work becomes N+M. That is MCP’s value, and the reason applications adopted it quickly after its release in November 2024. In its 2025-12-09 announcement Anthropic reported more than 10,000 active public MCP servers and adoption by ChatGPT, Cursor, Gemini, Microsoft Copilot, Visual Studio Code and others (vendor-reported figures), and on the same day donated MCP to the Agentic AI Foundation, a directed fund under the Linux Foundation.

Cheap integration brings out the other ledger. Every tool carries a definition (name, description, a JSON Schema of its parameters), and connect a few servers and the definitions fill the context. Anthropic’s post of 2025-11-24 gives an example: five servers with 58 tools in total took about 55K tokens before the conversation started, and internally they had seen tool definitions reach 134K tokens (vendor-reported). The official client best practices treat this as a problem too: loading every definition up front wastes tokens, adds latency and degrades the model’s performance.

So read this page with two questions in mind: how the protocol works, and what to do about the part it does not solve. The architecture documentation says it plainly: MCP focuses solely on the protocol for context exchange, and does not dictate how AI applications use LLMs or manage the provided context.

AspectWhat MCP coversWhat MCP leaves to you
IntegrationOne message format for discovering and calling tools, reading resources, fetching prompt templatesWhich tools to expose to the model
ConnectionTwo transports (stdio, Streamable HTTP), version and capability negotiationHow the model chooses tools and how context is managed
SecurityAn authorization framework (OAuth 2.1), Origin checks, header checksWhether one particular call should run, and whether returned content can be trusted

The Protocol at a Glance

Participants and Layers

Participants in MCP: one host, one client per server Structure diagram. The big box on the left is the host, an AI application, containing the model with its tool loop and three MCP clients; each client keeps a dedicated connection to one server on the right, the first two over stdio (local processes) and the third over Streamable HTTP (a remote service). Each server offers three kinds of primitives: tools, resources and prompts. Host: the AI application (IDE, chat client, your agent) model plus tool loop decides what to call MCP client 1 MCP client 2 MCP client 3 Server A filesystem (local process) stdio Server B database (local process) stdio Server C SaaS service (remote service) Streamable HTTP each server offers: tools: actions the model calls resources: data the app reads prompts: templates the user picks
The host creates one client per server and each pair has its own connection (the wording of the official architecture page). A local server usually serves one client, a remote server usually serves many. The protocol covers these lines; it does not cover how the model picks tools.

MCP is a client-server architecture with three roles:

  • the host is the AI application itself, such as Claude Code, Visual Studio Code or an agent you wrote, and coordinates one or more clients;
  • a client is a component inside the host that keeps a connection to one server and obtains context for the host;
  • a server is a program that provides context, wherever it runs.

The host creates one client per server, each with a dedicated connection. The protocol has two layers: a data layer, a JSON-RPC 2.0 message protocol (discovery, the three primitives, notifications), and a transport layer that handles how to connect, how to frame messages and how to authorize. There are two standard transports: stdio (the host launches the server as a subprocess and talks over standard input and output; a local server usually serves one client) and Streamable HTTP (the client sends messages with HTTP POST and the response can be JSON or a stream; a remote server usually serves many clients).

Three Primitives: Who Decides When to Use Them

A server offers three kinds of primitives, and the specification states for each one who decides when it is used, which determines where each belongs:

PrimitiveWho decides when to use itTypical contentDiscovery and use
ToolsThe model (model-controlled)Querying a database, calling an API, writing a filetools/list, tools/call
ResourcesThe application (application-driven)File contents, a database schemaresources/list, resources/read
PromptsThe user (user-controlled)Slash commands, reusable prompt templatesprompts/list, prompts/get

For tools the specification adds a requirement: for trust and safety there SHOULD always be a human in the loop who can deny tool invocations (applications should show which tools are exposed to the model, signal clearly when a tool is invoked, and ask the user to confirm operations). The client side has one more primitive, elicitation, which lets a server ask the user for more information. Roots, Sampling (a server asking the host’s model for a completion) and Logging are deprecated in the 2026-07-28 revision; the official migration advice is to pass directories through tool parameters or resource URIs, to call a model provider’s API directly, and to log to stderr or with OpenTelemetry.

Five Revisions

The specification names versions by date. The table below picks the main points of each revision from the changelogs, which helps when you meet an older tutorial:

VersionMain points
2024-11-05First public revision (announced 2024-11-25); transports were stdio and HTTP+SSE
2025-03-26An authorization framework based on OAuth 2.1; Streamable HTTP replaces HTTP+SSE; tool annotations (read-only, destructive and so on)
2025-06-18Structured tool output; MCP servers classified as OAuth resource servers; elicitation; the MCP-Protocol-Version header
2025-11-25Tool-naming guidance; URL-mode elicitation; Client ID Metadata Documents; experimental tasks; a clarification that an invalid Origin must get 403
2026-07-28Stateless: no handshake and no session; server/discover; subscriptions/listen; Mcp-Method and Mcp-Name headers; cache hints on list results; Roots, Sampling and Logging deprecated

The experiments below use both eras: the client of the official Python SDK 2.3.0 has three modes, legacy (the handshake era), auto (probe first) and 2026-07-28.

Experiment 1: What One Call Looks Like on the Wire

The documentation describes the specification; this experiment looks at the bytes that actually flow. The setup:

  • an invented company, Acme, with a back office of 12 services (orders, billing, shipping, CRM, tickets, inventory, calendar, email, docs, HR, analytics, deploy) and 8 tools each, 96 tools in all, with names like orders_cancel_order;
  • the server is written with the official SDK’s MCPServer, and the tool functions are generated from the catalog: they only validate their arguments and return ok, so data and logic are for demonstration;
  • between client and server sits a 19-line logging proxy that writes every JSON-RPC message line, with its direction and time, to a log;
  • the client is the SDK’s Client, connecting in legacy, auto and 2026-07-28 modes in turn, listing all the tools and then calling orders_cancel_order once.

The code blocks below, joined in order, are the complete script. Environment: Apple M2 Max (64 GB), CPU only; Python 3.14.3 and the official SDK mcp 2.3.0 (versions are printed by setup), no deep-learning framework. The server and the proxy are subprocesses talking over pipes, so no network port is used (except in the HTTP part, which listens on a free port of 127.0.0.1). A complete run takes about 3 seconds; the byte counts are deterministic and will only change with the SDK version.

import asyncio, json, os, platform, subprocess, sys, tempfile
import unicodedata
import importlib.metadata as md
from mcp import Client
from mcp.client.stdio import StdioServerParameters
from mcp_types.version import (HANDSHAKE_PROTOCOL_VERSIONS,
                               MODERN_PROTOCOL_VERSIONS)

print("python", platform.python_version(), "| mcp", md.version("mcp"))
print("versions with a handshake: "
      + ", ".join(HANDSHAKE_PROTOCOL_VERSIONS))
print("stateless versions: "
      + ", ".join(MODERN_PROTOCOL_VERSIONS))
WORK = tempfile.mkdtemp(prefix="mcp-")
PY = sys.executable


def pad(s, width):
    """Left-align s in width display columns (CJK counts 2)."""
    return s + " " * (width - sum(2 if unicodedata.east_asian_width(c) in "WF"
                                  else 1 for c in s))
python 3.14.3 | mcp 2.3.0
versions with a handshake: 2024-11-05, 2025-03-26, 2025-06-18, 2025-11-25
stateless versions: 2026-07-28

First the tool catalog. It is data, not an algorithm, so it is folded; the server block writes it into a temporary directory and the server reads it line by line.

Expand: the catalog of 96 tools
CATALOG = """
[orders]
get_order order_id:int; Get an order's status, items and total
list_orders customer_id:int status:str; List a customer's orders by status
cancel_order order_id:int reason:str; Cancel an order that has not shipped
update_order_address order_id:int address:str; Change where an order is sent
add_order_note order_id:int note:str; Attach an internal note to an order
return_order order_id:int reason:str; Register a return of delivered goods
reorder order_id:int; Place a new order copying a past one
export_orders since:str; Export orders since a date as CSV
[billing]
get_invoice invoice_id:int; Get an invoice with its line items
list_invoices customer_id:int; List the invoices of a customer
create_invoice customer_id:int amount:float; Create an invoice for a customer
void_invoice invoice_id:int; Void an invoice issued by mistake
issue_refund payment_id:str amount:float; Refund money to the card of a payment
list_payments customer_id:int; List the payments made by a customer
update_payment_method customer_id:int method:str; Set the default payment method
cancel_subscription subscription_id:str; Cancel a recurring subscription
[shipping]
track_shipment tracking_no:str; Get the tracking events of a parcel
create_label order_id:int carrier:str; Buy a shipping label for an order
schedule_pickup order_id:int date:str; Book a carrier pickup for an order
cancel_pickup pickup_id:str; Cancel a booked carrier pickup
change_delivery_date tracking_no:str date:str; Reschedule a parcel's delivery
update_ship_address tracking_no:str address:str; Redirect a parcel in transit
list_carriers country:str; List the carriers serving a country
get_shipping_rates weight_kg:float country:str; Quote shipping prices by weight
[crm]
get_contact contact_id:int; Get a contact's profile
search_contacts query:str; Search contacts by name or email
create_contact name:str email:str; Create a new contact
update_contact contact_id:int field:str value:str; Change one field of a contact
merge_contacts source_id:int target_id:int; Merge two duplicate contacts
delete_contact contact_id:int; Delete a contact and its history
add_contact_note contact_id:int note:str; Add a note to a contact's timeline
list_segments; List the customer segments
[tickets]
create_ticket title:str body:str; Open a new support ticket
get_ticket ticket_id:int; Get a ticket with its comments
update_ticket ticket_id:int field:str value:str; Change one field of a ticket
assign_ticket ticket_id:int assignee:str; Assign a ticket to an agent
close_ticket ticket_id:int resolution:str; Close a ticket with a resolution note
reopen_ticket ticket_id:int; Reopen a closed ticket
list_tickets status:str; List tickets by status
add_ticket_comment ticket_id:int comment:str; Post a comment on a ticket
[inventory]
get_stock sku:str; Get the units in stock for a SKU
reserve_stock sku:str quantity:int; Reserve units of a SKU for an order
release_stock reservation_id:str; Release a stock reservation
adjust_stock sku:str delta:int; Correct the stock count after a recount
list_warehouses; List the warehouses
transfer_stock sku:str to_wh:str quantity:int; Move stock to another warehouse
set_reorder_level sku:str level:int; Set the restock threshold of a SKU
list_low_stock threshold:int; List SKUs below a stock threshold
[calendar]
create_event title:str start:str; Create a calendar event
list_events date:str; List the events of a day
cancel_event event_id:str; Cancel a calendar event
reschedule_event event_id:str start:str; Move an event to a new start time
find_free_slot attendees:str duration_min:int; Find a time when everyone is free
add_attendee event_id:str email:str; Invite a person to an event
set_reminder event_id:str minutes:int; Set a reminder before an event
list_rooms; List the bookable meeting rooms
[email]
send_email to:str subject:str body:str; Send an email
search_emails query:str; Search the mailbox
get_email email_id:str; Read one email
draft_reply email_id:str instructions:str; Draft a reply to an email
forward_email email_id:str to:str; Forward an email to someone
archive_email email_id:str; Move an email to the archive
list_labels; List the mailbox labels
add_label email_id:str label:str; Put a label on an email
[docs]
search_docs query:str; Search the document library
get_doc doc_id:str; Read a document
create_doc title:str content:str; Create a document
update_doc doc_id:str content:str; Replace the content of a document
share_doc doc_id:str email:str; Share a document with a person
delete_doc doc_id:str; Delete a document
list_doc_versions doc_id:str; List the saved versions of a document
export_doc_pdf doc_id:str; Export a document as PDF
[hr]
get_employee employee_id:int; Get an employee's profile
request_leave employee_id:int start:str end:str; Submit a leave request
approve_leave request_id:str; Approve a leave request
cancel_leave request_id:str; Cancel a leave request
list_holidays year:int; List the public holidays of a year
get_leave_balance employee_id:int; Get the remaining leave days
list_team manager_id:int; List the people reporting to a manager
update_employee_phone employee_id:int phone:str; Change an employee's phone
[analytics]
run_report report_id:str month:str; Run a saved report for a month
get_metric metric:str date:str; Get one metric value for a date
list_reports; List the saved reports
schedule_report report_id:str cron:str; Run a report on a schedule
cancel_report_schedule schedule_id:str; Stop a scheduled report
export_report_csv report_id:str; Export a report's rows as CSV
create_dashboard title:str; Create an empty dashboard
share_dashboard dashboard_id:str email:str; Share a dashboard with a person
[deploy]
deploy_service service:str version:str; Deploy a version of a service
rollback_service service:str; Roll a service back to its previous version
get_deploy_status deploy_id:str; Get the status of a deployment
list_services; List the deployable services
restart_service service:str; Restart all instances of a service
scale_service service:str replicas:int; Set the number of instances of a service
get_service_logs service:str lines:int; Get the last log lines of a service
cancel_deploy deploy_id:str; Cancel a deployment in progress
"""
rows = [r for r in CATALOG.strip().split("\n") if not r.startswith("[")]
print(f"services: {CATALOG.count(chr(10) + '[')}"
      f", tools: {len(rows)}")
services: 12, tools: 96

The server itself is 33 lines. check is the prototype of two kinds of failure: a negative value is a failure we saw coming and raises the SDK’s ToolError; a zero simulates a bug nobody planned for and raises RuntimeError. The error experiment below contrasts the two.

SERVER = '''
import sys
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

mcp = MCPServer("acme-backoffice")


def check(name, value):
    if value < 0:                         # a failure we saw coming
        raise ToolError(f"{name} must be >= 0, got {value}")
    if value == 0:                        # a bug nobody planned for
        raise RuntimeError("database connection lost")
    return "ok"


service = None
for row in open(sys.argv[1], encoding="utf-8").read().strip().split("\\n"):
    if row.startswith("["):
        service = row.strip("[]")
        continue
    head, desc = row.split("; ", 1)
    name, *params = head.split()
    name, args = f"{service}_{name}", [p.split(":") for p in params]
    body = "return 'ok'"
    if args and args[0][1] == "int":
        body = f"return check('{args[0][0]}', {args[0][0]})"
    scope = {"check": check}
    exec(f"def {name}({', '.join(f'{a}: {t}' for a, t in args)}) -> str:\\n"
         f"    {body}", scope)
    scope[name].__doc__ = desc
    mcp.tool()(scope[name])

mcp.run()
'''

TEE = '''
import subprocess, sys, threading, time

log, cmd, t0 = open(sys.argv[1], "w"), sys.argv[2:], time.time()
srv = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                       stderr=subprocess.DEVNULL, text=True, bufsize=1)


def pump(src, dst, tag):
    for line in src:
        log.write(f"{time.time() - t0:.3f} {tag} {line}")
        log.flush()
        dst.write(line)
        dst.flush()
    dst.close()


a = threading.Thread(target=pump, args=(sys.stdin, srv.stdin, ">"))
b = threading.Thread(target=pump, args=(srv.stdout, sys.stdout, "<"))
a.start(), b.start(), a.join(), b.join(), srv.wait()
'''
for name, text in (("catalog.txt", CATALOG.strip()), ("server.py", SERVER),
                   ("tee.py", TEE)):
    open(os.path.join(WORK, name), "w", encoding="utf-8").write(text)
n_server, n_tee = (len(t.strip().split("\n")) for t in (SERVER, TEE))
print(f"server.py: {n_server} lines, tee.py: {n_tee} lines")
server.py: 33 lines, tee.py: 19 lines

The Handshake Era and the Stateless Era

def argv(log):
    return [os.path.join(WORK, "tee.py"), log, PY,
            os.path.join(WORK, "server.py"), os.path.join(WORK, "catalog.txt")]


async def session(mode):
    log = os.path.join(WORK, f"{mode}.log")
    params = StdioServerParameters(command=PY, args=argv(log))
    async with Client(params, mode=mode) as client:
        tools = await client.list_tools()
        result = await client.call_tool(
            "orders_cancel_order",
            {"order_id": 4821, "reason": "changed mind"})
    lines = [l.split(" ", 2) for l in open(log, encoding="utf-8")]
    return [(l[1], json.loads(l[2]), len(l[2].encode())) for l in lines], \
        len(tools.tools), result


def label(msg, asked):
    if "method" in msg:
        return msg["method"]
    return "result of " + asked.get(msg["id"], "?")


SESSIONS = {}
for mode in ("legacy", "auto", "2026-07-28"):
    SESSIONS[mode] = asyncio.run(session(mode))
    wire, n_tools, result = SESSIONS[mode]
    asked = {m["id"]: m["method"] for _, m, _ in wire if "method" in m
             and "id" in m}
    print(f"mode={mode}: {len(wire)} messages, {n_tools} "
          "tools listed")
    for i, (arrow, msg, size) in enumerate(wire, 1):
        print(f"  {i}  {'->' if arrow == '>' else '<-'}  "
              f"{pad(label(msg, asked), 34)}{size:>8,} bytes")
mode=legacy: 7 messages, 96 tools listed
  1  ->  initialize                             153 bytes
  2  <-  result of initialize                   251 bytes
  3  ->  notifications/initialized               55 bytes
  4  ->  tools/list                              47 bytes
  5  <-  result of tools/list                39,808 bytes
  6  ->  tools/call                             141 bytes
  7  <-  result of tools/call                   128 bytes
mode=auto: 6 messages, 96 tools listed
  1  ->  server/discover                        246 bytes
  2  <-  result of server/discover              342 bytes
  3  ->  tools/list                             241 bytes
  4  <-  result of tools/list                39,952 bytes
  5  ->  tools/call                             324 bytes
  6  <-  result of tools/call                   239 bytes
mode=2026-07-28: 4 messages, 96 tools listed
  1  ->  tools/list                             241 bytes
  2  <-  result of tools/list                39,952 bytes
  3  ->  tools/call                             324 bytes
  4  <-  result of tools/call                   239 bytes
Message flow of one call: the handshake era and the stateless era Two sequence diagrams side by side. On the left the handshake era (spec 2025-11-25 and earlier): an initialize request and result, an initialized notification, then tools/list and tools/call, 7 messages in all, 396 bytes sent and 40,187 bytes received. On the right the stateless 2026-07-28 flow: tools/list and tools/call directly, 4 messages, 565 bytes sent and 40,191 received. The tools/list result, about 39,952 bytes, is most of the traffic. handshake era (2025-11-25 and earlier) client server initialize · 153 B initialize · result · 251 B notifications/initialized · 55 B tools/list · 47 B tools/list · result · 39,808 B tools/call · 141 B tools/call · result · 128 B 7 messages · sent 396 B · received 40,187 B the handshake itself: 3 messages, 459 B stateless (2026-07-28) client server no handshake: no initialize, no initialized tools/list · 241 B tools/list · result · 39,952 B tools/call · 324 B tools/call · result · 239 B 4 messages · sent 565 B · received 40,191 B price: every request carries _meta (tools/list grows from 47 B to 241 B)
A server with 96 tools, driven by the official Python SDK client in legacy and in 2026-07-28 mode; byte counts come from a logging proxy that counts every JSON message line in both directions (UTF-8, without the newline).

All three modes list the same 96 tools and all calls succeed; the difference is in the message count:

  • legacy is the handshake-era flow: an initialize request (153 bytes), its result (251 bytes), a notifications/initialized notification (55 bytes), so the handshake itself is 3 messages and 459 bytes, and only then does tools/list start;
  • 2026-07-28 sends tools/list right away, 4 messages in all; the price is that every request carries _meta, so the tools/list request grows from 47 to 241 bytes and tools/call from 141 to 324 bytes;
  • auto first sends a server/discover probe (request 246 bytes, response 342 bytes) and uses the new protocol once it sees the server supports 2026-07-28, so it costs two more messages than pinning the version, in return for compatibility with older servers.

The widget below turns this wire log into a step-by-step replay: pick a connection mode and walk the call with previous/next to see each message’s direction, byte count and role — and which single message dominates the traffic.

Add up the bytes and the protocol overhead turns out to be small next to the tool list:

for mode, (wire, n_tools, result) in SESSIONS.items():
    up = sum(s for a, _, s in wire if a == ">")
    down = sum(s for a, _, s in wire if a == "<")
    big = max(s for _, _, s in wire)
    print(f"{mode:<11} sent {up:>5,} B received {down:>6,} B "
          f"without the big reply {up + down - big:>5,} B")
print(f"tool-list reply: {big:,} bytes, "
      f"{big / len(rows):.0f} bytes per tool")
legacy      sent   396 B received 40,187 B without the big reply   775 B
auto        sent   811 B received 40,533 B without the big reply 1,392 B
2026-07-28  sent   565 B received 40,191 B without the big reply   804 B
tool-list reply: 39,952 bytes, 416 bytes per tool

The total traffic of the two protocols is almost the same (sent plus received: legacy 40,583 bytes, 2026-07-28 40,756 bytes), while the tools/list response alone is 39,952 bytes, 98% of the 2026-07-28 traffic. What statelessness saves is round trips and session state on the server, not bandwidth; the bulk is the tool definitions. At 96 tools that is 416 bytes per tool on average, which the next experiment turns into tokens.

What Is in the Messages

The code below prints three representative messages from the auto session (long strings shortened, the serverInfo stamp of responses dropped):

def cut(x):
    if isinstance(x, dict):
        return {k: cut(v) for k, v in x.items()}
    if isinstance(x, list):
        return [cut(v) for v in x]
    return x[:70] + "..." if isinstance(x, str) and len(x) > 73 else x


def pretty(msg):
    """Print a message: long strings cut, the serverInfo stamp dropped."""
    msg = json.loads(json.dumps(msg))
    msg.get("result", {}).pop("_meta", None)
    print(json.dumps(cut(msg), indent=1, ensure_ascii=False))


wire = SESSIONS["auto"][0]
print("# server/discover reply")
pretty(wire[1][1])
print("# tools/call request")
pretty(wire[4][1])
print("# tools/call reply")
pretty(wire[5][1])
# server/discover reply
{
 "jsonrpc": "2.0",
 "id": 1,
 "result": {
  "cacheScope": "private",
  "capabilities": {
   "prompts": {
    "listChanged": true
   },
   "resources": {
    "listChanged": true,
    "subscribe": true
   },
   "tools": {
    "listChanged": true
   }
  },
  "resultType": "complete",
  "supportedVersions": [
   "2026-07-28"
  ],
  "ttlMs": 0
 }
}
# tools/call request
{
 "jsonrpc": "2.0",
 "id": 3,
 "method": "tools/call",
 "params": {
  "name": "orders_cancel_order",
  "arguments": {
   "order_id": 4821,
   "reason": "changed mind"
  },
  "_meta": {
   "io.modelcontextprotocol/protocolVersion": "2026-07-28",
   "io.modelcontextprotocol/clientInfo": {
    "name": "mcp",
    "version": "0.1.0"
   },
   "io.modelcontextprotocol/clientCapabilities": {}
  }
 }
}
# tools/call reply
{
 "jsonrpc": "2.0",
 "id": 3,
 "result": {
  "content": [
   {
    "text": "ok",
    "type": "text"
   }
  ],
  "isError": false,
  "resultType": "complete",
  "structuredContent": {
   "result": "ok"
  }
 }
}

Things worth noticing:

  • the params._meta of every request carries three things: io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientInfo and io.modelcontextprotocol/clientCapabilities. With no handshake the server relies on them to understand each request, so the protocol no longer needs sticky sessions and any server instance can handle any request (a server that needs state across requests has to mint its own state handles, see the security section below);
  • the server/discover response lists supportedVersions and capabilities (this server supports tools, resources and prompts, and announces list changes); ttlMs and cacheScope are caching hints, and the SDK defaults to ttlMs: 0, literally “stale at once”, so a server that wants clients to cache its tool list has to set it;
  • every response carries resultType: "complete", a required field since 2026-07-28: "complete" is an ordinary result and "input_required" means the server needs more input before it can continue (the multi round-trip request, which replaces the old server-initiated requests);
  • a tool result comes in two forms: content is the text for the model, and structuredContent is the same result in structured form (because the tool declares an output schema).

No Handshake, No SDK: Speaking the Protocol by Hand

The SDK hides the message details. The Raw class below writes JSON lines straight to a server subprocess, and its seven cases show the behavior of the stateless protocol and both kinds of error:

class Raw:
    """Speak the protocol by hand: no SDK on the client side."""

    META = {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
            "io.modelcontextprotocol/clientCapabilities": {}}

    def __init__(self):
        self.n = 0
        self.proc = subprocess.Popen(
            [PY, os.path.join(WORK, "server.py"),
             os.path.join(WORK, "catalog.txt")], text=True,
            stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)

    def call(self, method, params=None, meta=True):
        self.n += 1
        params = dict(params or {})
        if meta:
            params["_meta"] = meta if isinstance(meta, dict) else self.META
        msg = {"jsonrpc": "2.0", "id": self.n, "method": method,
               "params": params}
        self.proc.stdin.write(json.dumps(msg) + "\n")
        self.proc.stdin.flush()
        return json.loads(self.proc.stdout.readline())

    def close(self):
        self.proc.stdin.close()
        self.proc.wait(timeout=10)
        return self.proc.stderr.read()


raw, asked = Raw(), {"name": "orders_get_order"}
CASES = [
    ("the very first message is tools/call",
     "tools/call",
     {**asked, "arguments": {"order_id": 4821}}, True),
    ("the same call without _meta", "tools/call",
     {**asked, "arguments": {"order_id": 4821}}, False),
    ("a tool name that does not exist", "tools/call",
     {"name": "orders_get_ordr", "arguments": {}}, True),
    ("the tool raises ToolError",
     "tools/call",
     {**asked, "arguments": {"order_id": -1}}, True),
    ("the tool crashes (RuntimeError)",
     "tools/call",
     {**asked, "arguments": {"order_id": 0}}, True),
    ("an argument of the wrong type", "tools/call",
     {**asked, "arguments": {"order_id": "x"}}, True),
    ("a protocol version nobody speaks", "tools/call",
     {**asked, "arguments": {"order_id": 1}},
     {**Raw.META, "io.modelcontextprotocol/protocolVersion": "1999-01-01"}),
]
for title, method, params, meta in CASES:
    msg = raw.call(method, params, meta)
    print("##", title)
    pretty(msg)
## the very first message is tools/call
{
 "jsonrpc": "2.0",
 "id": 1,
 "result": {
  "content": [
   {
    "text": "ok",
    "type": "text"
   }
  ],
  "isError": false,
  "resultType": "complete",
  "structuredContent": {
   "result": "ok"
  }
 }
}
## the same call without _meta
{
 "jsonrpc": "2.0",
 "id": 2,
 "error": {
  "code": -32602,
  "message": "params._meta must be an object carrying the required 'io.modelcontextp..."
 }
}
## a tool name that does not exist
{
 "jsonrpc": "2.0",
 "id": 3,
 "result": {
  "content": [
   {
    "text": "Unknown tool: orders_get_ordr",
    "type": "text"
   }
  ],
  "isError": true,
  "resultType": "complete"
 }
}
## the tool raises ToolError
{
 "jsonrpc": "2.0",
 "id": 4,
 "result": {
  "content": [
   {
    "text": "Error executing tool orders_get_order: order_id must be >= 0, got -1",
    "type": "text"
   }
  ],
  "isError": true,
  "resultType": "complete"
 }
}
## the tool crashes (RuntimeError)
{
 "jsonrpc": "2.0",
 "id": 5,
 "result": {
  "content": [
   {
    "text": "Error executing tool orders_get_order",
    "type": "text"
   }
  ],
  "isError": true,
  "resultType": "complete"
 }
}
## an argument of the wrong type
{
 "jsonrpc": "2.0",
 "id": 6,
 "result": {
  "content": [
   {
    "text": "Error executing tool orders_get_order: 1 validation error for orders_g...",
    "type": "text"
   }
  ],
  "isError": true,
  "resultType": "complete"
 }
}
## a protocol version nobody speaks
{
 "jsonrpc": "2.0",
 "id": 7,
 "error": {
  "code": -32022,
  "message": "Unsupported protocol version",
  "data": {
   "supported": [
    "2026-07-28"
   ],
   "requested": "1999-01-01"
  }
 }
}

The seven cases as a table:

SituationThe server’s responseCategory
The very first message is tools/callSuccess, okWorks without a handshake
The same call without _metaJSON-RPC error -32602, asking for the required fields in _metaProtocol error
A misspelled tool nameA result with isError: true and the text Unknown tool: …See the note below
The tool raises ToolErrorisError: true, the cause in the text (order_id must be >= 0, got -1)Tool execution error; the model can act on it
The tool crashes (RuntimeError)isError: true, only Error executing tool orders_get_order in the textTool execution error, details hidden
An argument of the wrong typeisError: true, a validation report (1 validation error for …)Tool execution error
Version written as 1999-01-01JSON-RPC error -32022, with supported and requested in dataProtocol error

The specification splits tool errors into two kinds. Protocol errors mean the request itself is wrong (an unknown tool, a malformed request, a server fault); they come back as JSON-RPC errors, a model is unlikely to fix them, and the specification says a client MAY pass them to the model. Tool execution errors are problems while the tool ran (an API failure, input validation, a business rule); they sit in the result with isError: true, and a client SHOULD pass them to the model so it can correct itself and retry. The 2025-11-25 revision went further and clarified that input validation errors are returned as tool execution errors so that the model can self-correct.

Two details of this experiment are worth remembering:

  1. A crash and a ToolError look different to the model. The cause in a ToolError went into the result, so the model sees “order id must be at least 0” and can fix it; the details of the RuntimeError went only to the server’s stderr (the Tool … lines at the end of the output above), and the model sees just Error executing tool, with no idea what went wrong or whether to retry. For failures you can foresee, writing an actionable error message is part of tool design;
  2. An unknown tool name comes back as a tool execution error in SDK 2.3.0, while the error example in the 2026-07-28 specification classifies an unknown tool as a protocol error (-32602, Unknown tool: invalid_tool_name). In both representations the model gets to see Unknown tool, but a client has to handle both; we only report what we observed and did not check whether the divergence between specification and SDK is intended or an implementation difference.

What a Tool Looks Like

reply = raw.call("tools/list")["result"]
tools = reply["tools"]
print("fields of the reply: " + ", ".join(sorted(reply)))
print(f"ttlMs: {reply['ttlMs']}, cacheScope: {reply['cacheScope']}")
print(f"tools in one page: {len(tools)}, "
      f"nextCursor: {reply.get('nextCursor')}")
print("fields of one tool: " + ", ".join(sorted(tools[0])))
json.dump(tools, open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                   "catalog.en.json"), "w"))
tool = next(t for t in tools if t["name"] == "orders_cancel_order")
print(json.dumps(tool, indent=1, ensure_ascii=False))
stderr = raw.close().split("\n")
print("what the server wrote to stderr (lines starting with Tool):")
for line in [l for l in stderr if l.startswith("Tool ")]:
    print(" ", line[:78])
fields of the reply: _meta, cacheScope, resultType, tools, ttlMs
ttlMs: 0, cacheScope: private
tools in one page: 96, nextCursor: None
fields of one tool: description, inputSchema, name, outputSchema
{
 "description": "Cancel an order that has not shipped",
 "inputSchema": {
  "type": "object",
  "properties": {
   "order_id": {
    "title": "Order Id",
    "type": "integer"
   },
   "reason": {
    "title": "Reason",
    "type": "string"
   }
  },
  "required": [
   "order_id",
   "reason"
  ],
  "title": "orders_cancel_orderArguments"
 },
 "name": "orders_cancel_order",
 "outputSchema": {
  "properties": {
   "result": {
    "title": "Result",
    "type": "string"
   }
  },
  "required": [
   "result"
  ],
  "title": "orders_cancel_orderOutput",
  "type": "object"
 }
}
what the server wrote to stderr (lines starting with Tool):
  Tool 'orders_get_ordr' failed: 'Unknown tool: orders_get_ordr'
  Tool 'orders_get_order' failed: 'Error executing tool orders_get_order: order_
  Tool 'orders_get_order' raised an unexpected exception
  Tool 'orders_get_order' rejected arguments: ['order_id']

A tool has four fields on the wire: name, description, inputSchema, and an outputSchema that the SDK generated automatically because the function has a return annotation. The SDK also added a title to every parameter (Order Id), a by-product of the JSON Schema generator that carries no information but costs tokens; a later experiment measures how many. The tools/list response is one page: 96 tools and no nextCursor, which shows that pagination is optional and this server chose to send everything at once.

Streamable HTTP: Headers and Origin

The other transport besides stdio is HTTP. The 2026-07-28 revision requires every POST to carry MCP-Protocol-Version and mirrors the method name and tool name of the body into the Mcp-Method and Mcp-Name headers; the stated reason is that load balancers, gateways and observability tools can then route and inspect requests without parsing the body. Mirroring brings a risk: if a router lets a request through based on the header while the server executes the body, any disagreement becomes a way around policy. So the specification requires the server to check that headers and body agree, and to answer HTTP 400 with -32020 (HeaderMismatch) if they do not.

The other check is Origin: the specification requires servers to validate the Origin header on all connections to prevent DNS rebinding attacks, an invalid Origin gets 403, and a server running locally should bind only to 127.0.0.1.

import http.client, shutil, socket, time

HTTP_SERVER = '''
import sys
from mcp.server import MCPServer

mcp = MCPServer("acme-backoffice")


@mcp.tool()
def orders_get_order(order_id: int) -> str:
    return "ok"


mcp.run("streamable-http", host="127.0.0.1", port=int(sys.argv[1]))
'''
open(os.path.join(WORK, "http_server.py"), "w").write(HTTP_SERVER)
with socket.socket() as s:
    s.bind(("127.0.0.1", 0))
    port = s.getsockname()[1]
proc = subprocess.Popen([PY, os.path.join(WORK, "http_server.py"), str(port)],
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(100):
    try:
        socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
        break
    except OSError:
        time.sleep(0.1)


def post(body, headers):
    conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
    conn.request("POST", "/mcp", json.dumps(body),
                 {"Content-Type": "application/json",
                  "Accept": "application/json, text/event-stream", **headers})
    reply = conn.getresponse()
    kind, data = reply.getheader("Content-Type"), reply.read().decode()
    conn.close()
    return reply.status, kind, data


call = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {
    "name": "orders_get_order", "arguments": {"order_id": 5},
    "_meta": Raw.META}}
ok = {"MCP-Protocol-Version": "2026-07-28", "Mcp-Method": "tools/call",
      "Mcp-Name": "orders_get_order"}
HTTP_CASES = [
    ("the three headers match the body", ok),
    ("Mcp-Method says tools/list, the body says tools/call",
     {**ok, "Mcp-Method": "tools/list"}),
    ("Mcp-Name names another tool than the body",
     {**ok, "Mcp-Name": "orders_cancel_order"}),
    ("an Origin header from another site",
     {**ok, "Origin": "http://evil.example"}),
    ("no MCP headers at all", {}),
]
for title, headers in HTTP_CASES:
    status, kind, data = post(call, headers)
    print("##", title)
    print("HTTP", status, kind or "(no content type)")
    try:
        msg = json.loads(data)
        if "error" in msg:
            print("error", msg["error"]["code"])
            print(" ", msg["error"]["message"])
        else:
            print("result:", msg["result"]["content"][0]["text"],
                  "| resultType:", msg["result"]["resultType"])
    except ValueError:
        print(" ", data)
proc.terminate()
proc.wait(timeout=10)
shutil.rmtree(WORK)
## the three headers match the body
HTTP 200 application/json
result: ok | resultType: complete
## Mcp-Method says tools/list, the body says tools/call
HTTP 400 application/json
error -32020
  mcp-method header does not match the request body's method
## Mcp-Name names another tool than the body
HTTP 400 application/json
error -32020
  mcp-name header does not match the request body's 'name' parameter
## an Origin header from another site
HTTP 403 (no content type)
  Invalid Origin header
## no MCP headers at all
HTTP 400 application/json
error -32600
  Bad Request: Missing session ID

The five cases agree with the specification: with three headers that match the body the answer is 200; with Mcp-Method or Mcp-Name disagreeing with the body it is 400 and -32020; an Origin from another site gets 403. The last case carries no MCP headers at all and the SDK answered Missing session ID: this SDK’s server speaks both eras, a request without a version header is treated as a handshake-era request, and handshake-era requests need a session ID. That is the SDK’s compatibility behavior; the 2026-07-28 specification itself has no sessions.

Security Boundaries

The protocol only supplies mechanisms; security comes from host, client and server each doing their part. The table condenses the most common problems from the official security best practices and the authorization specification:

ProblemHow it happensWhat the specification requires
A compromised or poisoned local serverA one-click configuration hides a malicious startup command, or the server itself carries a malicious payload; a forgotten local HTTP server is reached through DNS rebindingA client with one-click configuration MUST show the full command and get consent before running it, should flag dangerous patterns, ideally sandbox the server and start it with minimal privileges; prefer stdio for local servers
Token passthroughA server accepts a token that was not issued to it and forwards it unchanged to a downstream APIA server MUST NOT accept any token not explicitly issued for it, and must check the token’s audience
Confused deputyA proxy server uses a static client ID with a third-party authorization server and allows dynamic registration, and an existing consent cookie is used to obtain an authorization codeA proxy server MUST get the user’s consent for each client separately before forwarding to the third party
SSRFA malicious server puts internal or cloud-metadata addresses into OAuth metadata so the client fetches themClients must validate and restrict OAuth-related URLs (HTTPS in production, among other measures)
State handle hijackingIn a stateless protocol a server that needs cross-request state mints its own handle (a cart ID, say) and an attacker guesses or obtains someone else’sPossessing a handle MUST NOT count as authentication; generate handles with a secure random generator and bind them to the authenticated user
Over-broad tokensAsking for files:* or admin:* up front, so a leaked token has a wide blast radiusLeast privilege: start with low-risk scopes and raise them through WWW-Authenticate scope challenges when a privileged operation first appears

Authorization itself is OPTIONAL. When used, the specification’s approach is that a protected MCP server acts as an OAuth 2.1 resource server and tells clients which authorization server to use through protected resource metadata (RFC 9728); the client MUST implement resource indicators (RFC 8707), so a token is valid only for this server; for client registration Client ID Metadata Documents come first and Dynamic Client Registration is deprecated in 2026-07-28; when permissions are insufficient the server answers 403 with insufficient_scope and the client escalates. A stdio server does not use this flow, and the specification recommends taking credentials from the environment.

One more class of problem is not in the protocol: tool descriptions and results are text that enters the model’s context. A malicious or compromised server can hide instructions in a description or a result, which is one entrance for prompt injection (see Prompt Injection and Jailbreaks). The specification’s stance is that clients confirm sensitive operations with the user, show tool inputs to the user to prevent data exfiltration, and validate tool results before passing them to the model; the protocol itself will not judge for you.

Experiment 2: What Tool Definitions Cost, and Whether the Model Still Chooses Well

Experiment 1 showed that the tool list is almost all of the traffic. This experiment puts the same 96 definitions in front of a model and asks two questions: what do they cost in tokens, and does a model that sees all of them still pick the right tool? It also tries two ways of showing fewer definitions: BM25 retrieval, and a one-line-per-tool index followed by a look at the chosen tool’s full definition.

Design: one catalog, 24 requests, three ways to choose

  • The catalog is the 96 tools of experiment 1, exported to a JSON file with the definitions exactly as the server sent them in tools/list.
  • The model is Qwen3-4B (Apache-2.0), float32 on the MPS backend, thinking switched off, greedy decoding. Definitions enter the prompt through the tools argument of the chat template, so the token counts below are Qwen3 tokenizer counts; another template or tokenizer gives other numbers.
  • The requests are 8 target tools with 3 plain-English phrasings each, 24 requests in all. A phrasing gives the argument values (an order number, an address, a phone number) but not the tool name; some phrasings use the verb of the tool’s name (“cancel”) and others a synonym (“called off”, “give back”). The targets have close neighbours: orders_cancel_order shares the verb cancel with 7 other tools, and shipping_update_ship_address shares update with 7.
  • The verdict. A reply is ok if it is a tool call that names the right tool and contains every key argument value; otherwise wrong_tool, wrong_arg, or no_call / bad_json. This is a keyword judge, and it can be wrong in both directions (a call with the right values in the wrong fields passes), so the failure analysis below reads the replies.
  • Three ways to choose. All in the prompt: the 8 targets plus random other tools, 8, 24, 48 or 96 tools in all, in a random order, with 3 seeds (a seed changes the tool set and the order). BM25 top-5: the BM25 of the RAG page scores every tool’s name, description and parameter names against the request, and the best five go into the prompt. Index, then inspect: the prompt holds one line per tool (name, parameters, description), the model answers with one tool name, and a second prompt with only that tool’s full definition lets it make the call.
Experiment environment

The code blocks below, joined in order, are the complete script. Environment: Apple M2 Max (64 GB), PyTorch’s MPS backend, float32; Python 3.14.3, PyTorch 2.10.0, transformers 5.3.0 (printed by setup). The page shows the run of Qwen3-4B in full. Two smaller models, Qwen2.5-1.5B-Instruct and Qwen2.5-0.5B-Instruct (both Apache-2.0), ran the same script with the MODEL environment variable changed, and their numbers appear only in the summary table. Greedy decoding makes the replies deterministic apart from floating-point differences between machines. The run of the 4B model took about 36 minutes. The run on this page is the first attempt that finished with an empty stderr. Timings are for this laptop in float32 and only show proportions.

Code: how definitions enter the prompt

setup loads the model. tools reads the catalog and renders prompts with the chat template: spec turns a catalog entry into the function format the template expects (optionally without the title fields that the SDK’s schema generator adds), render produces the whole prompt for a set of tools and a request, and split cuts the prompt in front of the user turn, so that everything before it (the part that depends on the tools only) can be computed once and reused as a prefix cache.

import json, math, os, platform, random, re, textwrap, time, unicodedata
import torch, transformers
from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache
from transformers import logging as hf_logging

hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
MODEL = os.environ.get("MODEL", "Qwen/Qwen3-4B")
DEV = "mps"
tok = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)
model = model.to(DEV).eval()
STOP = {tok.convert_tokens_to_ids("<|im_end|>"), tok.eos_token_id}
n_par = sum(p.numel() for p in model.parameters())
print("python", platform.python_version(), "| torch", torch.__version__,
      "| transformers", transformers.__version__)
print(MODEL, f"| {n_par / 1e9:.2f}B parameters | float32 on", DEV)


def wid(s):
    return sum(2 if unicodedata.east_asian_width(c) in "WF" else 1 for c in s)


def row(cells, widths):
    """First cell left-aligned, the rest right-aligned (CJK counts 2)."""
    out = [cells[0] + " " * (widths[0] - wid(cells[0]))]
    out += [" " * (w - wid(c)) + c for c, w in zip(cells[1:], widths[1:])]
    return "  ".join(out)
python 3.14.3 | torch 2.10.0 | transformers 5.3.0
Qwen/Qwen3-4B | 4.02B parameters | float32 on mps
HERE = os.path.dirname(os.path.abspath(__file__))
LIST = json.load(open(os.path.join(HERE, "catalog.en.json")))
TOOLS = {t["name"]: t for t in LIST}
NAMES = list(TOOLS)
SYSTEM = "You are Acme's back-office bot. Make one tool call."


def strip_titles(x):
    """Drop the generated "title" strings of a JSON Schema."""
    if isinstance(x, dict):
        return {k: strip_titles(v) for k, v in x.items()
                if not (k == "title" and isinstance(v, str))}
    return x


def spec(name, titles=True):
    t = TOOLS[name]
    schema = t["inputSchema"] if titles else strip_titles(t["inputSchema"])
    return {"type": "function", "function": {
        "name": name, "description": t["description"], "parameters": schema}}


def render(names, query, titles=True):
    msgs = [{"role": "system", "content": SYSTEM},
            {"role": "user", "content": query}]
    return tok.apply_chat_template(
        msgs, tools=[spec(n, titles) for n in names], tokenize=False,
        add_generation_prompt=True, enable_thinking=False)


def n_tokens(text):
    return len(tok(text, add_special_tokens=False).input_ids)


def split(names, query):
    """Cut the prompt before the user turn: the front part is shared."""
    full = render(names, query)
    cut = full.rindex("<|im_start|>user")
    return full[:cut], full[cut:]


BASE = n_tokens(render([], "x"))
ALL = n_tokens(render(NAMES, "x"))
PLAIN = n_tokens(render(NAMES, "x", titles=False))
print("tools in the catalog:", len(NAMES))
print("prompt with no tools:", BASE, "tokens")
print(f"prompt with all {len(NAMES)} tools:",
      f"{ALL:,} tokens;",
      f"without the title fields {PLAIN:,}")
print("---- one tool's prompt, wrapped ----")
for line in render(NAMES[:1], "x").split("\n"):
    print("\n".join(textwrap.wrap(line, 84)) or "")
tools in the catalog: 96
prompt with no tools: 32 tokens
prompt with all 96 tools: 8,096 tokens; without the title fields 6,364
---- one tool's prompt, wrapped ----
<|im_start|>system
You are Acme's back-office bot. Make one tool call.

# 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": "orders_get_order", "description": "Get an
order's status, items and total", "parameters": {"type": "object", "properties":
{"order_id": {"title": "Order Id", "type": "integer"}}, "required": ["order_id"],
"title": "orders_get_orderArguments"}}}
</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><|im_end|>
<|im_start|>user
x<|im_end|>
<|im_start|>assistant
<think>

</think>

Three things in the output:

  • With no tools the prompt is 32 tokens: the system prompt and the template’s scaffolding.
  • All 96 definitions make it 8,096 tokens, 84 per tool. The one-tool prompt above shows why: each definition is written into the prompt as a line of JSON, and the schema keeps everything the server sent.
  • 1,732 of those tokens, 21%, are title fields ("title": "Order Id" and "title": "orders_get_orderArguments"): a by-product of generating a schema from a Python signature that adds nothing to the description or the parameter names. The accuracy runs below keep them, as the server sent them; whether removing them changes accuracy was not tested, and removing them is a change on the server side.

Code: the requests and the runner

probes defines the 24 requests: for each target tool, the argument values a correct call must contain (keys) and three phrasings. It also counts how many tools share each target’s verb. model is the runner: prefill computes the key-value cache of the shared prefix in chunks of 1,024 tokens, decode greedily continues from the cache until the model closes its </tool_call> tag and then cuts the cache back so that the next request reuses the prefix, and verdict judges a reply. The last lines run one request with two tools as a smoke test.

Expand: the 24 requests and their neighbours
PROBES = [
    ("orders_cancel_order", ["4821"], [
        "Order 4821 hasn't shipped yet; the customer wants to cancel it.",
        "Cancel order 4821, it was placed twice by mistake.",
        "The customer wants order 4821 called off."]),
    ("shipping_update_ship_address", ["Rue Cler"], [
        "Parcel 1Z999AA10123456784 is in transit; send it to 12 Rue Cler.",
        "Tracking 7700112233 has not arrived; redirect it to 12 Rue Cler.",
        "The parcel CX0099, still on the truck, must go to 12 Rue Cler."]),
    ("hr_update_employee_phone", ["311", "5550123"], [
        "Employee 311 has a new phone number: +49 30 5550123.",
        "Change the phone of employee 311 to +49 30 5550123.",
        "Update the number on file for employee 311 to +49 30 5550123."]),
    ("calendar_cancel_event", ["ev-2207"], [
        "Cancel the calendar event ev-2207, the meeting was postponed.",
        "We are not holding ev-2207 any more; drop that event.",
        "Please call off event ev-2207."]),
    ("billing_issue_refund", ["pay_7781", "25"], [
        "Refund 25 to the customer's card for payment pay_7781.",
        "Give back 25 on payment pay_7781.",
        "The customer complained; return 25 from payment pay_7781."]),
    ("docs_share_doc", ["d-310", "[email protected]"], [
        "Share document d-310 with [email protected].",
        "Let [email protected] see the document d-310.",
        "Give [email protected] access to the doc d-310."]),
    ("analytics_cancel_report_schedule", ["sch-12"], [
        "Stop the schedule sch-12; the weekly report need not run again.",
        "Cancel the report schedule sch-12.",
        "We do not need the scheduled run sch-12 any more."]),
    ("crm_merge_contacts", ["118", "342"], [
        "Contacts 118 and 342 are one person; merge 118 into 342.",
        "Merge the duplicate contacts: 118 goes into 342.",
        "118 and 342 are duplicates in the CRM; please merge them."]),
]
QUERIES = [(t, keys, q) for t, keys, qs in PROBES for q in qs]
TARGETS = [p[0] for p in PROBES]
print(len(PROBES), "target tools x 3 phrasings =",
      len(QUERIES), "requests")
for tool in TARGETS:
    verb = tool.split("_")[1]
    kin = [n for n in NAMES if n.split("_")[1] == verb]
    print(f"  {tool:<34} {len(kin)} tools share its verb",
          f"({verb})")
8 target tools x 3 phrasings = 24 requests
  orders_cancel_order                7 tools share its verb (cancel)
  shipping_update_ship_address       7 tools share its verb (update)
  hr_update_employee_phone           7 tools share its verb (update)
  calendar_cancel_event              7 tools share its verb (cancel)
  billing_issue_refund               1 tools share its verb (issue)
  docs_share_doc                     2 tools share its verb (share)
  analytics_cancel_report_schedule   7 tools share its verb (cancel)
  crm_merge_contacts                 1 tools share its verb (merge)
@torch.no_grad()
def prefill(ids, chunk=1024):
    cache = DynamicCache()
    for i in range(0, ids.shape[1], chunk):
        model(input_ids=ids[:, i:i + chunk], past_key_values=cache,
              use_cache=True)
    return cache


@torch.no_grad()
def decode(cache, ids, limit=120, until="</tool_call>"):
    """Greedy continuation of a cached prefix; the cache is cut back."""
    keep, new = cache.get_seq_length(), []
    out = model(input_ids=ids, past_key_values=cache, use_cache=True)
    assert torch.isfinite(out.logits[0, -1]).all()
    for _ in range(limit):
        nxt = int(out.logits[0, -1].argmax())
        if nxt in STOP:
            break
        new.append(nxt)
        if until in tok.decode(new):
            break
        step = torch.tensor([[nxt]], device=DEV)
        out = model(input_ids=step, past_key_values=cache, use_cache=True)
    cache.crop(keep)
    torch.mps.empty_cache()
    return tok.decode(new), len(new)


def to_ids(text):
    return tok(text, add_special_tokens=False,
               return_tensors="pt").input_ids.to(DEV)


def start(names):
    """Prefill the part of the prompt that does not depend on the request."""
    prefix = split(names, "")[0]
    ids = to_ids(prefix)
    return prefill(ids), prefix, ids.shape[1]


def ask(cache, prefix, names, query):
    full = render(names, query)
    assert full.startswith(prefix)
    return decode(cache, to_ids(full[len(prefix):]))


def verdict(text, tool, keys):
    m = re.search(r"<tool_call>\s*(\{.*\})\s*</tool_call>", text, re.S)
    if not m:
        return "no_call"
    try:
        call = json.loads(m.group(1))
        args = " ".join(str(v) for v in call.get("arguments", {}).values())
    except (ValueError, AttributeError):
        return "bad_json"
    if call.get("name") != tool:
        return "wrong_tool"
    return "ok" if all(k in args for k in keys) else "wrong_arg"


duo = ["orders_cancel_order", "orders_get_order"]
cache, prefix, n_prefix = start(duo)
text, n_new = ask(cache, prefix, duo, QUERIES[0][2])
print(repr(text), "|", n_new, "new tokens")
print("verdict:", verdict(text, QUERIES[0][0], QUERIES[0][1]))
del cache
torch.mps.empty_cache()
'<tool_call>\n{"name": "orders_cancel_order", "arguments": {"order_id": 4821, "reason": "Customer wants to cancel"}}\n</tool_call>' | 33 new tokens
verdict: ok

The smoke test shows the form of a reply: a <tool_call> block holding a JSON object with the tool name and its arguments. The model used 33 new tokens for it in this test, and the longest reply in the whole run is printed by the cost block below.

Code: three ways to choose

First BM25. Its recall is the ceiling of any retrieval step: if the right tool is not among the five, the model cannot pick it. terms cuts text into Latin words (and, for the Chinese version of this experiment, runs of Chinese characters into two-character pieces, which this run does not use), and the index is built over each tool’s name (with the underscores read as spaces), description and parameter names.

def terms(s):
    s = s.lower()
    out = re.findall(r"[a-z][a-z0-9]*", s)
    for run in re.findall(r"[\u4e00-\u9fff]+", s):
        out += [run[i:i + 2] for i in range(len(run) - 1)] or [run]
    return out


class BM25:
    def __init__(self, names, k1=1.5, b=0.75):
        self.names, self.k1, self.b = names, k1, b
        self.docs = []
        for n in names:
            t = TOOLS[n]
            params = " ".join(t["inputSchema"].get("properties", {}))
            doc = n.replace("_", " ") + " " + t["description"] + " " + params
            self.docs.append(terms(doc))
        self.avg = sum(map(len, self.docs)) / len(self.docs)
        df = {}
        for d in self.docs:
            for w in set(d):
                df[w] = df.get(w, 0) + 1
        N = len(self.docs)
        self.idf = {w: math.log(1 + (N - c + 0.5) / (c + 0.5))
                    for w, c in df.items()}

    def top(self, query, k):
        q, scores = set(terms(query)), []
        for d in self.docs:
            s = 0.0
            for w in q:
                f = d.count(w)
                if f:
                    norm = 1 - self.b + self.b * len(d) / self.avg
                    s += self.idf[w] * f * (self.k1 + 1) / (f + self.k1 * norm)
            scores.append(s)
        order = sorted(range(len(scores)), key=lambda i: -scores[i])
        return [self.names[i] for i in order[:k]]


bm = BM25(NAMES)
for k in (1, 3, 5, 10):
    hit = sum(t in bm.top(q, k) for t, _, q in QUERIES)
    print(f"BM25 top-{k:<2} holds the right tool: "
          f"{hit} / {len(QUERIES)}")
for t, _, q in QUERIES:
    if t not in bm.top(q, 5):
        print(f"  not in the top 5: {q}")
BM25 top-1  holds the right tool: 15 / 24
BM25 top-3  holds the right tool: 20 / 24
BM25 top-5  holds the right tool: 21 / 24
BM25 top-10 holds the right tool: 24 / 24
  not in the top 5: The customer wants order 4821 called off.
  not in the top 5: Let [email protected] see the document d-310.
  not in the top 5: Give [email protected] access to the doc d-310.

Then the main loop. For every seed and every number of tools, pick builds the tool set (always the 8 targets, filled up with random others, then shuffled), start prefills the part of the prompt that does not depend on the request, and each of the 24 requests is answered from that cache. The retrieve block does the same for BM25: the five tools differ per request, so every request needs a fresh prefill of its own short prompt. The index block makes two steps.

SEEDS, SIZES = (0, 1, 2), (8, 24, 48, 96)
RUNS = []


def pick(n, seed):
    """n tools: the 8 targets plus random others, in a random order."""
    others = [x for x in NAMES if x not in TARGETS]
    random.Random(f"pool-{seed}").shuffle(others)
    names = TARGETS + others[:n - len(TARGETS)]
    random.Random(f"order-{seed}-{n}").shuffle(names)
    return names


def log(cond, seed, n, qi, v, text, new, **more):
    tool = QUERIES[qi][0]
    RUNS.append(dict(cond=cond, seed=seed, n=n, qi=qi, tool=tool, v=v,
                     text=text, new=new, **more))


for seed in SEEDS:
    for n in SIZES:
        names = pick(n, seed)
        t0 = time.time()
        cache, prefix, n_prefix = start(names)
        t_pre = time.time() - t0
        t0, ok = time.time(), 0
        for qi, (tool, keys, q) in enumerate(QUERIES):
            t1 = time.time()
            text, new = ask(cache, prefix, names, q)
            v = verdict(text, tool, keys)
            ok += v == "ok"
            log("all", seed, n, qi, v, text, new, pos=names.index(tool),
                tokens=n_prefix, prefill_s=t_pre, sec=time.time() - t1)
        del cache
        torch.mps.empty_cache()
        print(f"seed {seed} n={n:<3} {n_prefix:>6,} "
              f"tokens prefill {t_pre:>5.1f}s | "
              f"{len(QUERIES)} requests "
              f"{time.time() - t0:>5.1f}s | ok {ok}/{len(QUERIES)}")
seed 0 n=8      811 tokens prefill   0.4s | 24 requests  65.4s | ok 24/24
seed 0 n=24   2,173 tokens prefill   3.1s | 24 requests  97.8s | ok 24/24
seed 0 n=48   4,097 tokens prefill   6.3s | 24 requests 156.7s | ok 24/24
seed 0 n=96   8,083 tokens prefill  16.9s | 24 requests 239.4s | ok 24/24
seed 1 n=8      811 tokens prefill   0.5s | 24 requests  65.5s | ok 24/24
seed 1 n=24   2,156 tokens prefill   3.1s | 24 requests  96.4s | ok 24/24
seed 1 n=48   4,074 tokens prefill   6.3s | 24 requests 161.3s | ok 24/24
seed 1 n=96   8,083 tokens prefill  17.0s | 24 requests 257.7s | ok 23/24
seed 2 n=8      811 tokens prefill   0.5s | 24 requests  71.5s | ok 24/24
seed 2 n=24   2,203 tokens prefill   3.4s | 24 requests 104.8s | ok 24/24
seed 2 n=48   4,214 tokens prefill   8.0s | 24 requests 176.6s | ok 24/24
seed 2 n=96   8,083 tokens prefill  18.7s | 24 requests 246.0s | ok 23/24
for qi, (tool, keys, q) in enumerate(QUERIES):
    names = bm.top(q, 5)
    t1 = time.time()
    cache, prefix, n_prefix = start(names)
    text, new = ask(cache, prefix, names, q)
    log("bm25", 0, 5, qi, verdict(text, tool, keys), text, new,
        pos=names.index(tool) if tool in names else -1,
        tokens=n_tokens(render(names, q)), sec=time.time() - t1)
    del cache
    torch.mps.empty_cache()
r = [x for x in RUNS if x["cond"] == "bm25"]
print("BM25 top-5, then the model: ok",
      sum(x["v"] == "ok" for x in r), "/", len(r),
      "| right tool not among the five:",
      sum(x["pos"] < 0 for x in r))
BM25 top-5, then the model: ok 21 / 24 | right tool not among the five: 3
ASK = "Answer with the best tool name and nothing else."
HEAD = "Tools (name, parameters, description):"


def index_prompt(names, query):
    lines = []
    for n in names:
        params = ", ".join(TOOLS[n]["inputSchema"].get("properties", {}))
        lines.append(f"- {n}({params}): {TOOLS[n]['description']}")
    msgs = [{"role": "system",
             "content": SYSTEM + "\n\n" + HEAD + "\n" + "\n".join(lines)},
            {"role": "user", "content": query + "\n\n" + ASK}]
    return tok.apply_chat_template(msgs, tokenize=False,
                                   add_generation_prompt=True,
                                   enable_thinking=False)


for seed in SEEDS:
    names = pick(96, seed)
    full = index_prompt(names, "")
    prefix = full[:full.rindex("<|im_start|>user")]
    pid = to_ids(prefix)
    cache, ok = prefill(pid), 0
    for qi, (tool, keys, q) in enumerate(QUERIES):
        t1 = time.time()
        text, n1 = decode(cache, to_ids(index_prompt(names, q)[len(prefix):]),
                          limit=40, until="\n")
        found = re.findall(r"[a-z]+(?:_[a-z]+)+", text)
        chosen = found[0] if found and found[0] in TOOLS else None
        text2, n2, tokens2, v = "", 0, 0, "no_call"
        if chosen:
            c2, p2, tokens2 = start([chosen])
            text2, n2 = ask(c2, p2, [chosen], q)
            v = verdict(text2, tool, keys)
            del c2
        ok += v == "ok"
        log("index", seed, 96, qi, v, text.strip() + " | " + text2, n1 + n2,
            chosen=chosen, pos=names.index(tool), tokens=pid.shape[1],
            tokens2=tokens2, sec=time.time() - t1)
        torch.mps.empty_cache()
    del cache
    print(f"seed {seed} index of 96 tools "
          f"{pid.shape[1]:>6,} tokens | ok {ok}/{len(QUERIES)}")
seed 0 index of 96 tools  1,481 tokens | ok 23/24
seed 1 index of 96 tools  1,481 tokens | ok 22/24
seed 2 index of 96 tools  1,481 tokens | ok 22/24

Results: What 96 Tools Cost and What They Buy

Cost: tokens and seconds

cost condenses the runs into one table: the tokens of the prompt, the share of it that is one tool, the prefill time (paid once per tool set, because the prefix is cached afterwards), the time per request with the prefix already cached, and the share of a 32,768-token context window.

W = [10, 8, 10, 11, 11, 9]
print(row(["tools", "tokens", "per tool",
           "prefill s", "s/request",
           "of 32k"], W))
COST = {}
for n in SIZES:
    r = [x for x in RUNS if x["cond"] == "all" and x["n"] == n]
    tokens = {x["seed"]: x["tokens"] for x in r}
    prefill_s = {x["seed"]: x["prefill_s"] for x in r}
    tok_mean = sum(tokens.values()) / len(tokens)
    COST[n] = dict(tokens=tok_mean, prefill_s=sum(prefill_s.values())
                   / len(prefill_s), sec=sum(x["sec"] for x in r) / len(r))
    print(row([str(n), f"{tok_mean:,.0f}", f"{(tok_mean - BASE) / n:.0f}",
               f"{COST[n]['prefill_s']:.1f}", f"{COST[n]['sec']:.1f}",
               f"{100 * tok_mean / 32768:.1f}%"], W))
per_tool = (COST[96]["tokens"] - BASE) / 96
for pct in (1, 5):
    limit = 32768 * pct / 100
    print(f"{pct}% of 32,768 tokens = {limit:,.0f}: "
          f"about {(limit - BASE) / per_tool:.0f} tools")
r = [x for x in RUNS if x["cond"] == "bm25"]
mean5 = sum(x["tokens"] for x in r) / len(r)
print(f"BM25 top-5: {mean5:,.0f} tokens per request, "
      f"{sum(x['sec'] for x in r) / len(r):.1f} s per request")
r = [x for x in RUNS if x["cond"] == "index"]
idx_tok = sum({x["seed"]: x["tokens"] for x in r}.values()) / len(SEEDS)
step2 = sum(x["tokens2"] for x in r) / len(r)
secs = sum(x["sec"] for x in r) / len(r)
print(f"index: {idx_tok:,.0f} tokens (cacheable)")
print(f"second step: {step2:,.0f} tokens, "
      f"{secs:.1f} s per request")
print("longest generation: ",
      max(x["new"] for x in RUNS), "tokens")
tools         tokens    per tool    prefill s    s/request     of 32k
8                811          97          0.4          2.8       2.5%
24             2,177          89          3.2          4.2       6.6%
48             4,128          85          6.9          6.9      12.6%
96             8,083          84         17.5         10.3      24.7%
1% of 32,768 tokens = 328: about 4 tools
5% of 32,768 tokens = 1,638: about 19 tools
BM25 top-5: 545 tokens per request, 3.4 s per request
index: 1,481 tokens (cacheable)
second step: 184 tokens, 3.6 s per request
longest generation:  57 tokens
  • Tokens grow almost linearly with the tool count. 8 tools take 811 tokens and 96 take 8,083, 24.7% of a 32,768-token window. From 48 to 96 tools the prompt gains 3,955 tokens, about 82 per tool. The “per tool” column starts higher (97 for 8 tools) because the fixed instructions that the chat template writes in front of any tool list are spread over fewer tools.
  • With definitions this size, the 1% to 5% threshold arrives early. One percent of the window is 328 tokens, which about 4 tools use up; five percent is 1,638 tokens, about 19 tools. A catalog of a few dozen tools is already past the range in which the client best practices still say that loading everything is fine.
  • Prefill grows faster than the token count. 6.9 s for 4,128 tokens and 17.5 s for 8,083: about twice the tokens and more than twice the time, because attention cost grows with the square of the length.
  • A cached prefix still costs time on every request. With the 96-tool prefix already in the cache, one request took 10.3 s, against 2.8 s with 8 tools, for replies of at most 57 tokens. Every generated token reads the whole cache, and on this laptop’s MPS backend that read is expensive. Server GPUs with fused attention kernels pay less per cached token, so take the proportion as a property of this setup, not a law.
  • The two cheaper settings cost less per request. BM25 top-5 put 545 tokens into each prompt and took 3.4 s per request, with a new prompt every time and so nothing to share. The one-line index is 1,481 tokens that every request shares; the second call carries one full definition (184 tokens in all); both calls together took 3.6 s per request.

The widget below turns this accounting into something you can compute yourself: drag the catalog size and the tokens per definition to see when “all in the prompt” crosses your budget share of the window; the three dots on the chart are measured values from this experiment (full list 8,096, index 1,481, BM25 top-5 545 per request), and the accuracy price is the next section.

Accuracy: the 4B model barely notices

accuracy counts the verdicts: ok needs the right tool and every key value, tool ok needs only the right tool, wrong is another tool, args is the right tool with a missing value, none is no usable call, and the last column is the ok count per seed.

GROUPS = [("all", n, f"all {n}") for n in SIZES] + [
    ("bm25", 5, "BM25 top-5"), ("index", 96, "index+1")]
W = [11, 8, 9, 7, 7, 7, 9]
print(row(["setting", "ok", "tool ok",
           "wrong", "args", "none",
           "ok by seed"], W))
ACC = {}


def share(r, *vs):
    return sum(x["v"] in vs for x in r)


for cond, n, label in GROUPS:
    r = [x for x in RUNS if x["cond"] == cond and x["n"] == n]
    seeds = sorted({x["seed"] for x in r})
    per = [share([x for x in r if x["seed"] == s], "ok") for s in seeds]
    ACC[label] = dict(n=len(r), ok=share(r, "ok"), per=per,
                      tool=share(r, "ok", "wrong_arg"),
                      wrong=share(r, "wrong_tool"), args=share(r, "wrong_arg"),
                      none=share(r, "no_call", "bad_json"))
    a = ACC[label]
    print(row([label, f"{a['ok']}/{a['n']}", f"{a['tool']}/{a['n']}",
               str(a["wrong"]), str(a["args"]), str(a["none"]),
               "/".join(map(str, per)) if cond != "bm25" else "-"], W))
setting            ok    tool ok    wrong     args     none  ok by seed
all 8           72/72      72/72        0        0        0   24/24/24
all 24          72/72      72/72        0        0        0   24/24/24
all 48          72/72      72/72        0        0        0   24/24/24
all 96          70/72      70/72        2        0        0   24/23/23
BM25 top-5      21/24      21/24        1        0        2          -
index+1         67/72      67/72        5        0        0   23/22/22
  • All in the prompt: 72 of 72 with 8, 24 and 48 tools, then 70 of 72 with 96. Qwen3-4B chose the right tool and filled in the right values in every request up to 48 tools. With all 96 it missed 2, and both misses sent a refund to billing_void_invoice instead of billing_issue_refund.
  • BM25 top-5: 21 of 24. BM25 held the right tool in its top five for 21 of the 24 requests (15 in its top one, 20 in its top three, 24 in its top ten), and the model answered every one of those 21 correctly. The three requests BM25 missed had used a synonym of the tool’s verb (“called off” for cancel, “see” and “access” for share). The model cannot choose a tool it was not shown: two replies had no usable call and one called docs_get_doc.
  • Index plus inspect: 67 of 72. The index is 1,481 tokens against 8,083 for the full list, and all 5 misses are the same pair as above, a refund read as the voiding of an invoice.
Picking one of 96 tools: prompt tokens and share of correct calls Horizontal comparison, one row per setting: 8, 24, 48 and 96 tools all in the prompt, BM25 retrieval of the top 5, and a one-line-per-tool index with on-demand inspection. The left column is the prompt length in tokens, the right column is the share of calls with the right tool and correct arguments for each of three models (three marker shapes). 8 tools: 811 tokens; Qwen3-4B 100.0%, Qwen2.5-1.5B 100.0%, Qwen2.5-0.5B 95.8%. 24 tools: 2,177 tokens; Qwen3-4B 100.0%, Qwen2.5-1.5B 91.7%, Qwen2.5-0.5B 87.5%. 48 tools: 4,128 tokens; Qwen3-4B 100.0%, Qwen2.5-1.5B 90.3%, Qwen2.5-0.5B 63.9%. 96 tools: 8,083 tokens; Qwen3-4B 97.2%, Qwen2.5-1.5B 87.5%, Qwen2.5-0.5B 58.3%. BM25 top 5: 545 tokens; Qwen3-4B 87.5%, Qwen2.5-1.5B 87.5%, Qwen2.5-0.5B 66.7%. index + inspect: 1,481 tokens; Qwen3-4B 93.1%, Qwen2.5-1.5B 94.4%, Qwen2.5-0.5B 44.4%. prompt tokens right tool and arguments Qwen3-4B Qwen2.5-1.5B Qwen2.5-0.5B 1% 5% 0 2k 4k 6k 8k 10k 20% 40% 60% 80% 100% 8 tools 811 24 tools 2,177 48 tools 4,128 96 tools 8,083 BM25 top 5 545 index + inspect 1,481
Three models, greedy decoding; each dot is 3 random seeds (different tool sets and orders) x 24 requests per tool count, BM25 has 24 requests, and the thin lines span the minimum to the maximum over seeds. Tokens on the left are the prompt length after the Qwen3-4B chat template; for the index row it is the index (the second step adds the chosen tool's full definition). Amber dashed lines mark 1% and 5% of a 32,768-token window. The right-hand axis starts at 20%, not at zero.

Three Models, Side by Side

The figure and the table put the ok counts of all three models next to each other. The script was the same for the two smaller models, with only the MODEL environment variable changed: Qwen2.5-1.5B-Instruct took about 13 minutes and Qwen2.5-0.5B-Instruct about 6, both with an empty stderr. The prompts have almost the same length for all three (all 96 definitions are 8,096, 8,092 and 8,092 tokens), so the token bars on the left of the figure stand for all of them.

SettingQwen3-4BQwen2.5-1.5BQwen2.5-0.5B
all 872/72 (100%)72/72 (100%)69/72 (96%)
all 2472/72 (100%)66/72 (92%)63/72 (88%)
all 4872/72 (100%)65/72 (90%)46/72 (64%)
all 9670/72 (97%)63/72 (88%)42/72 (58%)
BM25 top-521/24 (88%)21/24 (88%)16/24 (67%)
index+167/72 (93%)68/72 (94%)32/72 (44%)
  • Model size decides how much the tool count hurts. Qwen3-4B answered 100% of the requests correctly with 8 tools, and still 100% with 48 and 97% with 96. Qwen2.5-1.5B went from 100% with 8 tools to 92%, 90% and 88% with 24, 48 and 96. Qwen2.5-0.5B went from 96% to 88%, 64% and 58%: with all 96 definitions it chose the right tool and values 42/72 times.
  • For the 1.5B model the step is between 8 and 24 tools. After that the changes (92%, 90%, 88%) are smaller than the spread between seeds: with 48 tools one seed got 19 of 24 right and another 24, a wider gap than the whole change from 24 to 96 tools.
  • The 0.5B model loses at every step, most between 24 and 48 tools (88% to 64%), the first step at which the seed ranges no longer overlap.
  • Retrieval is capped by recall, and the model cannot lift the cap. BM25 held the right tool in its top five for 21 of 24 requests. Qwen3-4B and Qwen2.5-1.5B answered all 21 of those correctly; Qwen2.5-0.5B managed 16/24 in all, so even a list of five tools was too much for it to read reliably.
  • The index works for models that can follow two steps. Index plus inspect reached 93% with Qwen3-4B and 94% with Qwen2.5-1.5B, and 44% with Qwen2.5-0.5B, where 20 of the 72 first-step replies named no tool of the catalog and 3 second-step replies had no usable call.
  • The small models go wrong in a different way. The table counts the wrong-tool replies of all settings by whether the tool named belongs to the same service as the target (docs_share_doc called as docs_get_doc) or to another one (billing_issue_refund called as deploy_restart_service). Qwen3-4B stayed within the service every time; the 0.5B model left it in about a third of its wrong replies.
ModelWrong-tool repliesSame service as the targetAnother service
Qwen3-4B88 (100%)0 (0%)
Qwen2.5-1.5B2420 (83%)4 (17%)
Qwen2.5-0.5B8759 (68%)28 (32%)

Position and Failures

position splits the requests of the all-in-the-prompt setting by where the target tool stood in the list: in the first, middle or last third. failures tallies which tool was chosen instead of the right one, prints the first replies with wrong arguments, and breaks the three settings down by target tool.

W = [11, 8, 8, 8]
print(row(["tools", "first", "middle",
           "last"], W))
THIRDS = {}
for n in (48, 96):
    r = [x for x in RUNS if x["cond"] == "all" and x["n"] == n]
    cells = []
    for lo in range(3):
        sub = [x for x in r if x["pos"] * 3 // n == lo]
        cells.append((share(sub, "ok"), len(sub)))
    THIRDS[n] = cells
    print(row([str(n)] + [f"{a}/{b}" for a, b in cells], W))
tools           first    middle      last
48              21/21     30/30     21/21
96              18/18     25/27     27/27
def called(text):
    m = re.search(r'"name":\s*"([^"]+)"', text)
    return m.group(1) if m else None


tally = {}
for x in RUNS:
    if x["v"] == "wrong_tool":
        got = x.get("chosen") or called(x["text"])
        key = (x["tool"], got, x["cond"] if x["cond"] != "all"
               else f"all {x['n']}")
        tally[key] = tally.get(key, 0) + 1
print("wrong tool (target -> chosen):")
for (want, got, cond), c in sorted(tally.items(), key=lambda kv: -kv[1]):
    print(f"  {c}x  {want} -> {got}  ({cond})")
print("wrong arguments (first 6):")
for x in [x for x in RUNS if x["v"] == "wrong_arg"][:6]:
    print(" ", x["text"].replace("\n", " ")[:84])
W = [34, 8, 8, 8]
print(row(["target", "all 96", "BM25", "index"], W))
for t in TARGETS:
    cells = []
    for cond, n in (("all", 96), ("bm25", 5), ("index", 96)):
        r = [x for x in RUNS if x["tool"] == t and x["cond"] == cond
             and x["n"] == n]
        cells.append(f"{share(r, 'ok')}/{len(r)}")
    print(row([t] + cells, W))
wrong tool (target -> chosen):
  5x  billing_issue_refund -> billing_void_invoice  (index)
  2x  billing_issue_refund -> billing_void_invoice  (all 96)
  1x  docs_share_doc -> docs_get_doc  (bm25)
wrong arguments (first 6):
target                                all 96      BM25     index
orders_cancel_order                      9/9       2/3       9/9
shipping_update_ship_address             9/9       3/3       9/9
hr_update_employee_phone                 9/9       3/3       9/9
calendar_cancel_event                    9/9       3/3       9/9
billing_issue_refund                     7/9       3/3       4/9
docs_share_doc                           9/9       1/3       9/9
analytics_cancel_report_schedule         9/9       3/3       9/9
crm_merge_contacts                       9/9       3/3       9/9

The same split for all three models, from the position code run with each model:

Tools in the listModelFirst thirdMiddle thirdLast third
48Qwen3-4B21/21 (100%)30/30 (100%)21/21 (100%)
48Qwen2.5-1.5B20/21 (95%)26/30 (87%)19/21 (90%)
48Qwen2.5-0.5B11/21 (52%)17/30 (57%)18/21 (86%)
96Qwen3-4B18/18 (100%)25/27 (93%)27/27 (100%)
96Qwen2.5-1.5B18/18 (100%)20/27 (74%)25/27 (93%)
96Qwen2.5-0.5B12/18 (67%)12/27 (44%)18/27 (67%)
  • Position. With 48 tools Qwen3-4B failed nowhere. With 96 tools both its misses stood in the middle third (25/27 right there, against 18/18 at the start and 27/27 at the end). The table adds the other two models with the same split: in 4 of the 5 (model, list length) cells where any request failed, the middle third has the lowest accuracy; the exception is Qwen2.5-0.5B with 48 tools, where the first third is lowest. That is the shape reported in Lost in the Middle, but a third holds only 18 to 30 requests, each list order is one random shuffle per seed, and the 4B model’s whole difference is 2 requests, so I read it as consistent with a position effect, not as a measurement of one.
  • The failures cluster in one pair. Of the 8 wrong-tool replies in the tally, 8 named a tool that shares its service or verb with the right one, and the tally has 2 distinct (target, chosen) pairs. billing_issue_refund (“Refund money to the card of a payment”) and billing_void_invoice (“Void an invoice issued by mistake”) are the pair behind every miss of the all-in-the-prompt and index settings, which is why the per-target table shows the refund row alone below 9 of 9 in those two columns. The other seven targets, including orders_cancel_order with its seven verb-sharing neighbours, were answered correctly every time in both settings.
  • No reply had a right tool with wrong arguments, so the keyword judge’s wrong_arg branch never fired. That also means the judge’s blind spot (right values in the wrong fields) was not measured by it; the replies of the misses were read in a follow-up run, described next.

Reading the Replies

A count says that a reply failed; only the reply says why. The runs above printed counts, so I replayed the requests behind the surprising numbers in two follow-up scripts. Each is a separate process built from the setup, tools, probes and model chunks of the experiment above, verbatim; a copied chunk with SEEDS, pick and index_prompt taken unchanged from the run and index chunks; a helpers chunk; and one chunk of its own. The list orders (seeds 0 to 2) and the greedy decoding are the same, and each replay reproduces the counts of the run above. They are follow-ups: I wrote them after seeing the counts, to find out why, and nothing in the tables above was changed because of them.

The Refund Requests of Qwen3-4B

Every miss of Qwen3-4B with all 96 definitions or with the index belonged to one target, billing_issue_refund. The refund chunk replays its three phrasings under both settings and all three list orders and prints what the model said: the tool call for all 96 definitions, and the reply of each step for the index. helpers holds three small functions: brief writes a tool call as name(arguments), clip cuts a line to the width of the page, and two_step is the index setting’s two calls. The first step answers in the form of an index line, name(parameters), and two_step takes the first catalog name in it.

def brief(text):
    """A tool call as name(arguments), any other reply as is."""
    m = re.search(r"<tool_call>\s*(\{.*\})\s*</tool_call>", text, re.S)
    if m:
        try:
            call = json.loads(m.group(1))
            args = ", ".join(f"{k}={v}" for k, v in call["arguments"].items())
            return f"{call['name']}({args})"
        except (ValueError, KeyError, AttributeError):
            pass
    return text.strip().replace("\n", " ")


def clip(s, width=62):
    out = ""
    for ch in s:
        if wid(out + ch) > width - 1:
            return out + "…"
        out += ch
    return out


def two_step(names, cache, prefix, q, tool, keys):
    """Index setting: name a tool, then call it with only its definition."""
    text, _ = decode(cache, to_ids(index_prompt(names, q)[len(prefix):]),
                     limit=40, until="\n")
    found = re.findall(r"[a-z]+(?:_[a-z]+)+", text)
    chosen = found[0] if found and found[0] in TOOLS else None
    if not chosen:
        return "no_call", text, ""
    c2, p2, _ = start([chosen])
    text2, _ = ask(c2, p2, [chosen], q)
    del c2
    return verdict(text2, tool, keys), text, text2
WANT = "billing_issue_refund"
ASKS = [(keys, q) for t, keys, q in QUERIES if t == WANT]
COUNT = {"all96": {}, "index": {}}


def show(setting, seed, j, v, *lines):
    COUNT[setting][v] = COUNT[setting].get(v, 0) + 1
    print(f"{seed} {setting:<5} #{j + 1} {v:<10}", clip(lines[0]))
    for extra in lines[1:]:
        print(" " * 21, clip(extra))


for seed in SEEDS:
    names = pick(96, seed)
    cache, prefix, _ = start(names)
    for j, (keys, q) in enumerate(ASKS):
        text, _ = ask(cache, prefix, names, q)
        show("all96", seed, j, verdict(text, WANT, keys), brief(text))
    del cache
    torch.mps.empty_cache()
    full = index_prompt(names, "")
    prefix = full[:full.rindex("<|im_start|>user")]
    cache = prefill(to_ids(prefix))
    for j, (keys, q) in enumerate(ASKS):
        v, t1, t2 = two_step(names, cache, prefix, q, WANT, keys)
        show("index", seed, j, v, "1: " + brief(t1), "2: " + (brief(t2) or "-"))
        torch.mps.empty_cache()
    del cache
for s, counts in COUNT.items():
    print(s, ", ".join(f"{k} {n}" for k, n in sorted(counts.items())))
0 all96 #1 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
0 all96 #2 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
0 all96 #3 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
0 index #1 ok         1: billing_issue_refund
                      2: billing_issue_refund(payment_id=pay_7781, amount=25)
0 index #2 wrong_tool 1: billing_void_invoice(invoice_id)
                      2: billing_void_invoice(invoice_id=7781)
0 index #3 ok         1: billing_issue_refund
                      2: billing_issue_refund(payment_id=pay_7781, amount=25)
1 all96 #1 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
1 all96 #2 wrong_tool billing_void_invoice(invoice_id=7781)
1 all96 #3 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
1 index #1 ok         1: billing_issue_refund
                      2: billing_issue_refund(payment_id=pay_7781, amount=25)
1 index #2 wrong_tool 1: billing_void_invoice(invoice_id)
                      2: billing_void_invoice(invoice_id=7781)
1 index #3 wrong_tool 1: billing_void_invoice(invoice_id)
                      2: billing_void_invoice(invoice_id=7781)
2 all96 #1 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
2 all96 #2 wrong_tool billing_void_invoice(invoice_id=7781)
2 all96 #3 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
2 index #1 ok         1: billing_issue_refund
                      2: billing_issue_refund(payment_id=pay_7781, amount=25)
2 index #2 wrong_tool 1: billing_void_invoice(invoice_id)
                      2: billing_void_invoice(invoice_id=7781)
2 index #3 wrong_tool 1: billing_void_invoice(invoice_id)
                      2: billing_void_invoice(invoice_id=7781)
all96 ok 7, wrong_tool 2
index ok 4, wrong_tool 5
RequestAll 96 definitions in the promptIndex plus inspect
Refund 25 to the customer’s card for payment pay_7781.3/33/3
Give back 25 on payment pay_7781.1/30/3
The customer complained; return 25 from payment pay_7781.3/31/3
  • The phrasing mattered. The one phrasing that says “refund” was right in all six of its replays (three list orders, two settings). The other two carry all 7 misses: “Give back 25…” was right once in six, “…return 25…” four times in six.
  • So did the list order. Seed 0 produced one miss, seeds 1 and 2 three each, and the replies of the same request differ between orders although the words did not change.
  • The wrong tool is always the same, and so is its id. All 7 wrong calls are billing_void_invoice(invoice_id=7781): the digits of pay_7781 used as an integer id. The refund tool’s payment_id is a string and the voiding tool’s invoice_id is an integer; I did not test whether that difference causes the miss, and neither did I test the obvious fix, a description that says what the tool is not for (the two descriptions are “Refund money to the card of a payment” and “Void an invoice issued by mistake”).
  • In the index setting the second call cannot undo the first. It sees only the definition of the tool the first call named, so it did what it was asked and wrote a well-formed call to the wrong tool.

Replies Without a Usable Call (the Two Smaller Models)

The keyword judge cannot explain a reply that is not a usable call: a missing tool_call block and JSON that does not parse both count as none. The quiet chunk replays the all-in-the-prompt settings with 8 and 96 tools and the index setting for one smaller model, and splits the unusable replies into “no tool_call block” (prose) and “broken JSON”. It prints how many there are, how many of the broken ones never closed the quote after the tool name (the defect I first saw in replies of the 0.5B model), the two targets with the most, and a few replies, clipped.

N = 3 * len(QUERIES)
for n in (8, 96):
    bad, by = {"no_call": [], "bad_json": []}, {}
    for seed in SEEDS:
        names = pick(n, seed)
        cache, prefix, _ = start(names)
        for tool, keys, q in QUERIES:
            text, _ = ask(cache, prefix, names, q)
            v = verdict(text, tool, keys)
            if v in bad:
                bad[v].append(text.strip().replace("\n", " "))
                by[tool] = by.get(tool, 0) + 1
        del cache
        torch.mps.empty_cache()
    a, b = len(bad["no_call"]), len(bad["bad_json"])
    cut = sum(bool(re.search(r'"name": "[a-z_]+,', t)) for t in bad["bad_json"])
    top = sorted(by.items(), key=lambda kv: -kv[1])[:2]
    print(f"{n} tools: {a + b} of {N} replies without a usable call")
    print(f"  no tool_call block: {a}, broken JSON: {b}"
          f" (name never closed: {cut})")
    if top:
        print("  most often: " + ", ".join(f"{t} {k}" for t, k in top))
    for kind in bad:
        for text in bad[kind][::max(1, len(bad[kind]) // 2)][:2]:
            print("   ", clip(text, 80))
first, second = [], []
for seed in SEEDS:
    names = pick(96, seed)
    full = index_prompt(names, "")
    prefix = full[:full.rindex("<|im_start|>user")]
    cache = prefill(to_ids(prefix))
    for tool, keys, q in QUERIES:
        v, t1, t2 = two_step(names, cache, prefix, q, tool, keys)
        if v in ("no_call", "bad_json"):
            reply = (t2 or t1).strip().replace("\n", " ")
            (second if t2 else first).append(reply)
        torch.mps.empty_cache()
    del cache
print("index, 96 tools:")
print(f"  first reply named no catalog tool: {len(first)}")
print(f"  second reply without a usable call: {len(second)}")
for text in (first[::max(1, len(first) // 2)][:2] + second[:1]):
    print("   ", clip(text, 80))

Qwen2.5-1.5B printed:

8 tools: 0 of 72 replies without a usable call
  no tool_call block: 0, broken JSON: 0 (name never closed: 0)
96 tools: 1 of 72 replies without a usable call
  no tool_call block: 1, broken JSON: 0 (name never closed: 0)
  most often: analytics_cancel_report_schedule 1
    Sure, I can help with that. Could you please provide me with the ID of the sche…
index, 96 tools:
  first reply named no catalog tool: 0
  second reply without a usable call: 0

Qwen2.5-0.5B, the same script with only MODEL changed:

8 tools: 2 of 72 replies without a usable call
  no tool_call block: 2, broken JSON: 0 (name never closed: 0)
  most often: analytics_cancel_report_schedule 2
    Sure, I can help with that. Could you please provide me with the ID of the sche…
    Sure, I can help with that. Could you please provide me with the schedule ID fo…
96 tools: 3 of 72 replies without a usable call
  no tool_call block: 3, broken JSON: 0 (name never closed: 0)
  most often: analytics_cancel_report_schedule 3
    Sure, I can help with that. Do you need any other assistance?
    Sure, I can help with that. Do you need any other assistance?
index, 96 tools:
  first reply named no catalog tool: 20
  second reply without a usable call: 3
    cancel_order
    ev-2207_close_event
    Sure, I can help with that. Could you please specify the date of the event you …
  • Qwen2.5-1.5B almost never fails to write a call. 0 of 72 replies had none with 8 tools, 1 with 96, and none in either step of the index setting, so its misses in the accuracy table are wrong tools and wrong arguments, not silence.
  • Qwen2.5-0.5B writes prose for a few requests with the full list (2 of 72 with 8 tools, 3 with 96), all of them for analytics_cancel_report_schedule, and none of its unusable replies in this run was broken JSON. The sampled replies at 8 tools ask for a schedule ID that all three phrasings of that request already contain.
  • The index setting is where the 0.5B model fails to write a call. 20 of its 72 first-step replies named no tool of the catalog: the samples are a shortened name, cancel_order, and an invented one that contains the event id, ev-2207_close_event. Another 3 second-step replies had no usable call.

What This Experiment Cannot Say

  • It is small. 24 requests, one invented catalog, three seeds. One call is about 1 percentage point in a cell of 72 calls and about 4 in the BM25 row of 24. The thin lines in the figure show how far a different tool set and order alone move a result; differences smaller than that are not interpreted.
  • One author wrote everything. The catalog, the 24 phrasings and the keyword judge were written by the same person, so this is a design test, not an independent benchmark. A real catalog has messier names, overlapping descriptions, and requests that do not spell out their argument values.
  • Greedy decoding, thinking off. Greedy decoding is deterministic, but it is not necessarily the setting a model’s authors recommend for chat use, and a model that is allowed to think may select differently.
  • The three models differ in more than size. Qwen3-4B and the two Qwen2.5 models are different generations trained differently, so the table compares models, not a clean scaling curve.
  • Definitions are kept as the server sent them, generated title fields included; whether removing them changes accuracy was not tested.
  • BM25 is the plain lexical baseline. No embeddings, hybrid scoring, reranking or subagent was tried, and neither was a vendor’s built-in tool search.
  • Index-then-inspect is one design among many. One index format, one instruction, one inspect step, and no recovery if the first choice is wrong; a multi-turn search_tools loop could do better or worse.
  • Timings are for one laptop in float32, depend on the implementation (chunk size, cache cropping) and are only good for proportions.
  • The design was fixed before the final run. Short pilots on a CPU with the smallest model were used to debug the script and led to adding the two smaller models; no number from the final run was used to change anything.
  • The replies were read after the counts. The two follow-up scripts were written to explain numbers I had already seen. They are separate processes that each reproduced the counts above, so they explain what happened and test nothing new. The questions they raise (would a description that says what a tool is not for remove the refund confusion, would a lenient JSON repair rescue the broken replies of the smallest model, is asking for a missing value better than inventing one) each need a run of their own.

Choosing: Four Ways to Put Tools in Front of a Model

The official client best practices frame the decision around one number, the share of the context window that tool definitions take. For a handful of tools, “loading all tools is fine”; once the definitions take a significant part of the window, a client should switch to progressive discovery, and the page suggests implementing a threshold as a percentage of the context window, for example 1% to 5%. At 84 tokens per tool, as this catalog is written, a 32,768-token window crosses the 1% line at about 4 tools and the 5% line at about 19; a 128,000-token window crosses them at about 15 and 76. The other half of the decision is what showing fewer definitions costs in accuracy, which is what the experiment measured.

ApproachWhat the model seesSuitsCosts and risks
Everything in the promptEvery tool’s full definitionA few tools, or definitions that stay under the 1% to 5% thresholdTokens grow with the tool count, about 84 per tool here; a list that never changes can be cached as a prefix
Retrieval per requestThe top-k definitions for this requestHundreds of tools; requests that share words with the tool text, or an embedding model that bridges the gapThe ceiling is retrieval recall; every request has its own tool list, so there is no shared prefix to cache; synonyms defeat BM25
Progressive disclosureA compact catalog or a search tool first, then one full definition on demandMany tools with large schemas, when a model can name the right tool from a one-line descriptionAn extra model call; the catalog still grows with the tool count; definitions added mid-conversation can break the cache
Code modeA typed API inside a sandbox; the model writes code that calls itChains of calls with large intermediate resultsA sandbox for model-written code and a new attack surface; not measured on this page

The client best practices list four ways to search for tools: keyword-based (BM25, regex), embedding-based (handles synonyms better), subagent-based (a small, fast secondary model picks the tools, usually works very well but costs more) and hybrids. They describe progressive discovery as three layers, catalog (a lightweight search_tools that returns names and one-line descriptions), inspect (fetch the full definition of one candidate) and execute (call it knowing its interface). The index-then-inspect setting above is a one-shot version of the same idea: the catalog is a one-line-per-tool index in the prompt instead of the result of a search_tools call.

What the Experiment Says About Each Way

The table puts the measured cost of the three settings of experiment 2 next to the accuracy of the three models; the last column is the share with the right tool and values, for Qwen3-4B, Qwen2.5-1.5B and Qwen2.5-0.5B in that order. Code mode was not measured.

SettingTokens in the promptSeconds per request (4B)Right: 4B, 1.5B, 0.5B
Everything in the prompt (96 tools)8,083, cached after one prefill of 17.5 s10.397%, 88%, 58%
BM25 top-5545, new for each request3.488%, 88%, 67%
Index, then inspect1,481 cached, plus 184 for the second call3.693%, 94%, 44%
  • For a capable model, everything in the prompt costs tokens and seconds before it costs accuracy. Qwen3-4B was right 97% of the time with all 96 definitions, but the prompt filled 24.7% of a 32,768-token window and a request took nearly four times as long as with 8 tools (10.3 s against 2.8 s).
  • Both cheaper settings shrink the prompt a lot. BM25 top-5 is about 15 times shorter than the full list and the index more than 5 times shorter, and each takes about a third of the time per request.
  • The order of the three settings changes with the model. Qwen3-4B was right most often with everything in the prompt (97%, against 93% for the index and 88% for BM25), a gap of a few requests. Qwen2.5-1.5B did best with the index (94%, against 88% for both others). Qwen2.5-0.5B did best with BM25 (67%, against 58% and 44%).
  • None of this crowns a winner. A request is 1 to 4 percentage points of a cell, the catalog is invented and has the neighbours the requests were built around, and BM25’s ceiling is its recall (21 of 24 here). What it does show is that the right setting is a property of the model and the catalog together, which is why the client best practices frame the decision as a threshold to tune and the section on definitions ends with “test with your own requests”.

Prompt Caching Decides What Is Cheap

Most model providers cache the prompt prefix, and the tools array is part of the prefix. A list that never changes is paid for once (here, one prefill of 17.5 seconds for 96 tools, then 10.3 seconds per request), while retrieval gives every request a different tool list and so no shared prefix. The client best practices add a warning: adding or removing definitions mid-conversation invalidates the cache, and the miss can cost more tokens than the definitions you removed. Their two remedies are to append newly discovered definitions after the cache breakpoint instead of re-sorting the array, or to route every call through one stable call_tool({name, args}) meta-tool so the array never changes; they also advise treating the disconnection of a server as a conversation-boundary operation, not a per-turn one. The same reasoning explains why prefix caching is the first thing to check when a tool-heavy prompt is slow.

The caching hints on the protocol side matter too. Every tools/list result carries ttlMs and cacheScope; the client best practices say to follow them and to treat a cached list as stale as soon as a notifications/tools/list_changed arrives, even before the TTL expires. In experiment 1 the SDK server answered with ttlMs: 0, so a server that wants clients to cache its catalog has to say so.

Writing Definitions That Are Cheap to Choose Among

Whichever strategy you pick, definitions are the raw material, and most of the following costs nothing:

  • Put the service and the verb in the name (orders_cancel_order, calendar_cancel_event): a name that says what and where gives a model and a keyword index something to hold on to.
  • Start each description with what the tool does, and, where a neighbour does something similar, when to use this one instead.
  • Drop generated noise. The title fields that the schema generator added are 21% of the 96-tool prompt here and say nothing the parameter names do not.
  • Keep parameter descriptions to a short phrase, with an example only where the format is ambiguous.
  • Return errors a model can act on (experiment 1: order_id must be >= 0, got -1 helps, Error executing tool does not).
  • Test with your own requests. The 24 requests used here are a smoke test for a design, not a benchmark.

Vendor-Reported Figures

The numbers below come from two Anthropic posts. They are reported by the vendor, on its own models, tool sets and internal evaluations, so they show how big the problem can get and cannot be compared with the measurements on this page.

SourceWhat it reports
Anthropic, 2025-11-24Five servers with 58 tools took about 55K tokens before the conversation started (Jira alone about 17K), and definitions reached 134K tokens internally. With its Tool Search Tool (about 500 tokens loaded up front) the post reports an 85% reduction in tokens, and on internal MCP evaluations accuracy rose from 49% to 74% for Opus 4 and from 79.5% to 88.1% for Opus 4.5
Anthropic, 2025-11-04Presenting tools as code files the agent reads on demand, and filtering data inside the sandbox, took one example (copying a meeting transcript from Google Drive into Salesforce) from 150,000 tokens to 2,000, a 98.7% saving; the post itself notes that running agent-written code needs sandboxing, resource limits and monitoring

Summary and Exercises

  • MCP solves integration, not selection. One server serves every MCP-capable application, which turns N×M adapters into N+M; which tools reach the model, and whether it picks the right one, stays your job.
  • The 2026-07-28 revision is stateless. There is no handshake and no session; every request carries the protocol version and client capabilities in _meta, and server/discover negotiates versions. In experiment 1 the two eras moved almost the same number of bytes (40,583 against 40,756); what statelessness saves is round trips and server-side session state.
  • Two kinds of error, two audiences. Protocol errors say the request is wrong; tool execution errors (isError: true) say the tool ran and failed, and the model should see them. A crash that hides its cause leaves the model nothing to act on.
  • The security work is the host’s. Confirm sensitive calls, show tool inputs, validate results, never forward a token that was not issued to your server, and treat every description and result as text that can carry instructions.
  • Definitions cost about 84 tokens each here, 21% of which was generated title fields; 96 tools filled 24.7% of a 32,768-token window.
  • Capability decides whether many tools hurt. With 96 tools Qwen3-4B was right 97% of the time, Qwen2.5-1.5B 88% and Qwen2.5-0.5B 58%; for the 4B model the price was tokens and seconds, not accuracy.
  • Retrieval is capped by its recall, and an index needs a model that can follow two steps. BM25 top-5 held the right tool in 21 of 24 requests; the index worked for the 4B and 1.5B models and failed for the 0.5B (44%).
  • The mistakes are neighbours. Every wrong-tool reply of Qwen3-4B named a tool of the right service.
  • A count hides what the replies say. Every miss of Qwen3-4B with all 96 definitions or with the index was a refund request sent to billing_void_invoice, with the digits of pay_7781 as its id, and 20 of the 0.5B model’s 72 first-step index replies named a tool that is not in the catalog.
  • Choose by tool count and definition size. Everything in the prompt for a few tools; retrieval or progressive disclosure once definitions pass roughly 1% to 5% of the window; code mode for chains with large intermediate results; and keep the tool list stable so the prefix cache can do its job.

Quick Check

What does MCP solve, and what does it leave to you?

  • It standardizes how applications discover and call tools, so one server works with every MCP-capable application
  • It decides which tools are shown to the model for each request
  • It guarantees that the model picks the right tool
  • It replaces function calling between the model and the application

MCP is the protocol between an application and an external system. Which tools reach the model and whether it chooses well are not part of it; the architecture documentation says plainly that MCP does not dictate how applications use LLMs or manage context. Function calling remains the layer between model and application.

A tool is called with order_id = -1, and the server knows this is invalid. How should it answer so that the model can recover?

  • A result with isError: true whose text says what is wrong, such as order_id must be >= 0, got -1
  • A JSON-RPC protocol error, because the argument is invalid
  • A crash whose details only go to the server’s log
  • An empty result, so that the model tries again

Tool execution errors are meant to reach the model so that it can correct itself; the 2025-11-25 revision clarified that input validation errors are returned this way. A crash that hides its cause (Error executing tool …) leaves the model nothing to act on, and a protocol error describes a wrong request, not a tool that ran.

Which of the following are true of the _meta block in the 2026-07-28 revision? Select all that apply.

  • Every request carries the protocol version and the client’s capabilities in it
  • It replaces the information that used to be exchanged in the initialize handshake
  • It makes the session ID header mandatory
  • It is optional, because the server remembers the client from an earlier request

With no handshake and no session, the server must learn from each request what version and capabilities apply, which is why _meta is required on every request. In experiment 1, sending tools/call without it was rejected with error -32602.

Each tool definition takes about 84 tokens here. Roughly how many tools reach the 5% line of a 128,000-token window?

  • About 38
  • About 76
  • About 152
  • Never, because definitions are cached

5% of 128,000 is 6,400 tokens; subtract the 32 tokens of the empty prompt and divide by 84. Caching saves compute and money, not window space: the definitions still occupy the context.

You connect six servers and their definitions take 18% of the window, and requests mostly reuse words from the tool descriptions. What is the first thing to try?

  • Progressive disclosure, for example a keyword search over a compact catalog, then load the full definition of the chosen tool
  • Remove the title fields and keep sending all definitions
  • Switch to code mode, because it always saves the most tokens
  • Sort the tools array differently on every turn so the model sees fresh orderings

18% is far past the suggested 1% to 5% threshold, and keyword matching works well when requests share words with the tool text. Dropping titles helps but does not change the order of magnitude; code mode needs a sandbox and mainly pays off for chains with large intermediate results; changing the array on every turn breaks the prefix cache.

Exercises

  1. In experiment 1 the 2026-07-28 tools/call request is 324 bytes against 141 bytes in the handshake era. A service handles 1,000 calls per session. Does stateless or handshake traffic cost more in total, and what is the break-even number of calls? (Use the sizes from the experiment and ignore the response sizes.)
Reference answer

Handshake traffic is paid once per session (459 bytes for its three messages), while stateless traffic adds 183 bytes of _meta to every call. The two are equal after about 3 calls; beyond that the stateless protocol sends more request bytes, 182,541 bytes more over 1,000 calls. So bandwidth is not why the protocol became stateless: what it buys is no handshake round trips before the first call, and servers that need no session affinity (any instance can answer any request).

  1. A server wants clients to cache its tool list for 10 minutes but to refetch immediately when the list changes. Which two protocol features does it use, and how does the client combine them?
Reference answer

It sets ttlMs to 600000 (and a suitable cacheScope) on the tools/list result, and it sends notifications/tools/list_changed whenever the list changes. The client caches the list for up to 10 minutes and treats it as stale as soon as the notification arrives, as the client best practices say, even before the TTL expires. The experiment’s server did neither: it answered with ttlMs: 0.

  1. Take the five tools of one service in your own system and write them as one-line catalog entries (name(params): description). Estimate the tokens of the catalog against the full definitions. When would you still send full definitions for them?
Reference answer

A one-line entry holds the name, the parameter names and one sentence, so it is a fraction of a definition whose schema also lists types, constraints and per-parameter descriptions (in this experiment the index of 96 tools was 1,481 tokens against 8,096 for the full definitions). Send full definitions when there are few tools and a stable list, when the schemas are what disambiguates the tools (several tools with the same parameters and different semantics), or when the extra model call of an inspect step costs more latency than the tokens save.

  1. A teammate proposes that an MCP server should accept whatever bearer token the client sends and pass it to the downstream API, “so the user’s permissions apply automatically”. Name the problem, and give the specification’s rule.
Reference answer

This is token passthrough. The specification forbids it: an MCP server must accept only tokens explicitly issued for it (its audience is checked), because forwarding a foreign token bypasses audience validation, rate limits and auditing, and the downstream service can no longer tell who is calling. If the server needs to call another API on the user’s behalf, it should get a token of its own for that API (for example through an OAuth flow of its own) and keep the two trust relationships separate.

Further Reading

FAQ

What is MCP, and how does it differ from function calling?
Function calling is the contract between a model and your code: the model emits a function name and arguments and your code runs it. MCP is the protocol between an AI application and an external system: it defines how to discover tools (tools/list), call them (tools/call), read resources and fetch prompt templates. They are two layers. The application gets tool definitions over MCP and hands them to the model in its function-calling format; when the model picks a call, the application turns it into a tools/call request to the server.
What changed in the 2026-07-28 MCP specification, and do old servers still work?
The big change is statelessness: the initialize handshake and the Mcp-Session-Id session are gone, every request carries the protocol version and client capabilities in _meta, and a client learns what a server supports through server/discover. Streamable HTTP requires Mcp-Method and Mcp-Name headers, and list results carry ttlMs and cacheScope. Roots, Sampling and Logging are deprecated. The client in the official Python SDK 2.3.0 has legacy and 2026-07-28 modes, and in this page's experiment both talked to the same server.
The model picks the wrong tool after I connected many MCP servers. What now?
Measure first: count the tokens of all tool definitions. The client best practices that accompany the specification suggest a threshold as a percentage of the context window (for example 1% to 5%) and switching to progressive disclosure beyond it: give the model a compact catalog or a search tool, and load a single tool's full definition only when needed. Then test on your own requests, comparing the share of correct calls with everything loaded and with progressive disclosure. This page reports one small-scale reference.
Can I trust what an MCP server returns?
Not by default. Tool descriptions and tool results come from the server and enter the model's context, so a malicious or compromised server can inject instructions through them. The specification asks clients to confirm sensitive operations with the user, show tool inputs before calling, and validate tool results; whether a given call should run is the host's responsibility, and the protocol does not judge it.
How do local stdio servers and remote Streamable HTTP servers differ in security?
A stdio server is a subprocess on the user's machine and runs with the client's privileges, so the main risk is the installation and launch command itself (a malicious startup command or package); the specification requires clients with one-click installation to show the full command and get consent first. A remote server faces network-level issues: validating Origin, the bind address, headers that match the body, and OAuth 2.1 authorization including token audience checks and a ban on token passthrough.