Back to Knowledge Base

Model Context Protocol — Deep Dive

🚀 Part of The Agentic Frontier — 2026 Field Guide → · related: Tool Calling → · Computer Use →

01. Why An Open Protocol

The Model Context Protocol, or MCP, is an open standard. It helps assistants connect to tools and data. It is designed to enhance agent tool integration and interoperability. This standard is rapidly emerging as a pivotal way to link agents with resources. A benchmark called MCP Agent Bench tests how well agents work with this protocol. The benchmark has thirty three operational servers and one hundred eighty eight distinct tools. It includes six hundred systematically designed queries across six categories. The evaluation focuses on real world task success. This approach is outcome oriented. It prioritizes whether the agent actually completes the task. The Model Context Protocol aims to unlock a new era of powerful AI systems. These systems will be interconnected and genuinely useful. The protocol makes agent tool connection simple and universal. Without such a standard, each connection would require custom work. MCP provides one universal way to connect assistants to tools and data. It is a key step for agentic AI.

The @tool decorator provides a standard, universal way to define tools, embodying the open protocol's goal of simplifying agent-tool connections.

python
from langchain.tools import tool

@tool
def search_database(query: str, limit: int = 10) -> str:
    """Search the customer database for records matching the query.

    Args:
        query: Search terms to look for
        limit: Maximum number of results to return
    """
    return f"Found {limit} results for '{query}'"
ELI5 — the plain-language version

Think of the Model Context Protocol as a universal power adapter that lets any electronic device work in any country. This open standard is designed to let AI assistants plug into different tools and data sources without needing a separate custom connector for each one. Just as a traveler carries one adapter for outlets worldwide, MCP gives assistants one common language to call functions and retrieve information from many different systems. The protocol’s whole purpose is to make agent tool integration smooth and interoperable, so the same assistant can book a flight, check the weather, or query a database using the same underlying mechanism.

Going deeper, the protocol doesn’t just claim to work—it gets tested systematically. A benchmark called MCP Agent Bench sets up thirty three operational servers, each acting like a different country’s power grid, and equips them with one hundred eighty eight distinct tools, such as a calendar maker or a file reader. The benchmark then runs six hundred carefully designed queries across six categories—for example, travel planning or data analysis—to see if an assistant can actually complete real-world tasks. This is like plugging a device into each outlet and checking that the light actually turns on, not just that the prongs fit. The evaluation is outcome-oriented: success means the assistant correctly called the right tool and the task truly got done, not merely that the call was made.

The non-obvious twist is that calling a tool correctly isn’t enough—the assistant must also handle the tool’s output gracefully and finish the whole job. For instance, even if the assistant picks the right flight-booking tool, if it misinterprets the returned confirmation and leaves the user with a wrong date, the benchmark counts that as a failure. MCP Agent Bench enforces this by scoring only real-world success across its six categories, using the thirty three servers and one hundred eighty eight tools to simulate messy, multi-step scenarios. Without this protocol and its benchmark, every assistant would need its own custom adapter for each tool, leading to an unmanageable tangle of incompatible connectors. A user might find that a weather tool works on one assistant but silently fails on another, and developers would waste time rewriting integrations for every new tool, making AI agents brittle and frustrating to use in everyday life.

System design — mechanism, invariant, trade-off

The Model Context Protocol (MCP) operates as a session-oriented, JSON-RPC framework with a layered host-client-server architecture. The ordered mechanism begins when a client negotiates capabilities with an MCP server, establishing the set of tools and resources available under fine-grained access control. Next, the client invokes external tools or retrieves contextual resources through JSON-RPC method calls. On failure—for instance, if capability negotiation fails—the session lifecycle terminates, and the transport semantics must be re-established from scratch. The lifecycle and transport semantics are formalized in the protocol specification, ensuring that every interaction proceeds through a defined negotiation, invocation, and retrieval sequence, with no silent fallback.

The invariant this design preserves is OAuth 2.1-compliant access control, which guarantees that each tool invocation is authenticated and authorized per session. MCP’s OAuth 2.1-compliant access control ensures that an agent can only access resources and tools explicitly granted by the server, preventing unauthorized data leakage across sessions. This security invariant is enforced at the protocol level, not delegated to ad-hoc per-source implementations, making it a structural guarantee of the architecture.

The key trade-off in adopting MCP is accepting the overhead of a standardized protocol against the alternative of custom implementations per data source. MCP explicitly rejects the fragmented model where “every new data source requires its own custom implementation, making truly connected systems difficult to scale.” This rejection avoids the cost of maintaining separate connectors for each system—a cost that grows linearly with every new source and introduces fragility under schema changes. Instead, MCP introduces known overheads such as transport-layer latency and token-lifecycle overhead, but these are bounded and addressable (e.g., through edge caching or QUIC streaming), whereas custom-integration complexity is unbounded and multiplies across every pair of systems.

A concrete failure mode is cross-server privilege escalation, where an agent in one MCP session attempts to invoke tools on a server it has not been authorized to use. The signal an operator would actually see is an authorization denial log entry from the OAuth 2.1 layer—typically a 403 response or a failed token validation error, reported in the server’s access-control audit trail. This signal is distinct from a network failure because it originates from the protocol’s security enforcement point, isolating the root cause to the session’s capability boundary.

Failure modes — what breaks, what catches it

STDIO Command Injection via Malicious User Input

  • Trigger — User input flows directly into STDIO MCP configuration without sanitization, allowing arbitrary command execution on the tool server.
  • Guard — The source does not identify any guard within the MCP protocol itself. Anthropic confirmed the behavior is by design and stated sanitization is the developer’s responsibility. External guards such as “detects improper use of STDIO-based MCP configurations” (OX Security) exist but are not part of this subsystem.
  • Posture — fail-soft: the agent continues to operate while the vulnerability remains exploitable. If the external guard is applied, it can become fail-closed by blocking patterns.
  • Operator signal — “7,000+ exposed servers” and “150M+ downloads” indicate widespread exposure. Operator may see alerts from OX Security flagging “improper use of STDIO-based MCP configurations” where user input is present.
  • Recovery — “Upgrade to the Latest Versions” of affected services. If no patch exists, “disable it until patched” or “don’t expose it to user input.” Manual step: implement “IP and URL blocking.”

Lazy Agent Failure to Activate Tool Mode

  • Trigger — The model detects tool necessity from mid-layer activations but remains conservative, failing to enter tool mode and missing calls that are clearly needed.
  • Guard — “Activation Steering Adapter (ASA)” — a training-free, inference-time controller that performs single-shot mid-layer intervention with a router-conditioned mixture of steering vectors and a probe-guided signed gate.
  • Posture — fail-soft: without ASA, the agent produces no tool calls and degrades task performance. With ASA applied, the agent correctly enters tool mode and continues.
  • Operator signal — “strict tool-use F1 from 0.18 to 0.50” after ASA; “false positive rate from 0.15 to 0.05.” Operator would observe low tool invocation rate before intervention.
  • Recovery — ASA is a one-shot intervention; no retry loop is described. If not deployed, the model persists in text-only mode, requiring manual re-prompt or architecture change.

Incorrect Tool Selection Leading to Wrong Execution

  • Trigger — The model is uncertain between two tools (e.g., send vs. delete) and picks the wrong one. “Queries where the model is unsure between two tools fail 21x more often than queries where it is not” (Gemma 3 27B).
  • Guard — The source proposes “UQ methods” such as “logit-based uncertainty scores” and “semantic entropy” to quantify confidence and prevent execution. Specifically, “single-sample UQ methods can be improved by selecting only semantically meaningful tokens when calculating logit-based uncertainty scores.”
  • Posture — fail-soft: the incorrect function call executes (e.g., email sent) before any guard can act. If UQ is applied before execution, it can refuse the call (fail-closed), but the source does not specify an enforced guard.
  • Operator signal — “the failure is invisible until execution: the email gets sent, the meeting gets missed.” No immediate alert; only later observation of unintended action.
  • Recovery — No automatic recovery for executed wrong calls. Manual undo or notification is required. If UQ is used, the call is aborted without retry.

Benchmark Evaluation Distortion from MCP Testbed Mismatch

  • Trigger — Existing benchmarks fail to capture real-world agent performance within the MCP paradigm, leading to “a distorted perception of their true operational value and an inability to reliably differentiate proficiencies.”
  • Guard — “MCP-Eval” — the novel outcome-oriented evaluation methodology introduced in MCP-AgentBench, prioritizing real-world task success. This is a revision of the benchmark, not a guard that prevents the distortion during an ongoing run.
  • Posture — fail-soft: agents may appear capable on flawed benchmarks while failing in deployment. The benchmark does not abort; it simply measures incorrectly.
  • Operator signal — “distorted perception” — operator sees high benchmark scores but low real-world success. No log line indicates the distortion.
  • Recovery — Re-evaluate agents using “MCP-Eval” methodology. No automatic recovery; manual shift to proper evaluation.

Multi-Turn Agent Loop Instability from Activation Steering

  • Trigger — Activation steering interventions (like ASA or linear readout) that work well in single-turn settings become unstable in multi-turn loops, with “matched-baseline gain or loss of up to 30 percentage points with no consistent direction.”
  • Guard — The source does not provide a guard specifically for multi-turn instability. The intervention itself is applied per-turn but results are unpredictable and unsteerable.
  • Posture — fail-soft: the agent may switch tools erratically across turns, leading to degraded or failed task completion.
  • Operator signal — “gain or loss of up to 30 percentage points” — operator observes volatile task performance across turns with no consistent pattern.
  • Recovery — Manual tuning or disabling activation steering for multi-turn scenarios. No automatic retry or fallback is documented.

02. Servers Clients And Hosts

The Model Context Protocol, or M C P, is an open standard. It helps developers build secure two-way connections between data sources and AI tools. The architecture is simple. Developers expose their data through M C P servers. They also build AI applications as M C P clients that connect to these servers. A server exposes its data once. A client can connect to many different servers. The connection between them is secure and allows data to flow both ways. This creates a session where the client and server exchange information. The protocol replaces the need for many custom integrations. The result is a simpler and more reliable way to give AI systems the data they need.

A simple tool function illustrating an MCP server exposing a data endpoint.

python
from langchain.tools import tool


@tool
def get_weather(city: str) -> str:
    """Get weather for a city."""
    return f"It is currently sunny in {city}."
ELI5 — the plain-language version

Imagine a universal adapter that lets any home appliance plug into any power outlet without needing a different cord for each brand. The Model Context Protocol (MCP) is exactly that kind of adapter for data sources and AI tools, giving developers a standard way to create secure two-way connections between them. It is designed to replace the need for dozens of custom integrations, so any AI application can talk to any data source that speaks the same simple language.

In practice, developers set up an MCP server that exposes their data once—like a power outlet built into the wall. Then they build AI applications as MCP clients that can plug into many different servers, each connection secured and allowing information to flow both ways. The protocol defines a session where the client and server exchange information, so a client can connect to a Google Drive server, a GitHub server, and a Postgres server without changing its internal wiring. This standard handshake eliminates the fragile, one-off connectors teams used to maintain for each pair of tools.

The trickiest detail is that MCP does not store or process the data itself—it only specifies the rules for conversation. An MCP client sends a request, the server responds, and the protocol maintains the context across multiple exchanges, so an AI agent can move between datasets without losing track of what it was doing. Without MCP, every developer would have to write and maintain custom connectors for each data source and tool combination, leading to brittle integrations that break when one side changes—like needing a different power cord for every appliance you own, and having to rewire your house each time you buy a new toaster.

System design — mechanism, invariant, trade-off

The subsystem follows a layered host-client-server architecture. The ordered mechanism begins when an MCP client, embedded in an AI application, initiates a session-oriented connection to an MCP server over JSON-RPC. First, the client and server negotiate capabilities—exchanging details about supported tools, resources, and transport options—under the fine-grained access control of OAuth 2.1. Once capabilities are agreed, the client can invoke external tools and retrieve contextual resources in a two-way data flow. On failure, such as a timeout during capability negotiation or a rejected tool invocation due to insufficient privileges, the client may retry the handshake or fall back to a cached capability list; the protocol does not guarantee exactly-once execution, so idempotency is left to individual server implementations.

The core invariant the design preserves is a session-oriented, OAuth 2.1-compliant access control boundary. This ensures that every tool invocation and resource retrieval is authorized per session, preventing unauthorized access across different MCP servers. The guarantee is that the context exchanged between a client and a server remains bound to that specific session and cannot leak into other sessions without explicit renegotiation. This replaces the ad-hoc security controls that previously plagued stateless integrations.

The key trade-off is standardization versus custom optimization. The protocol rejects the obvious alternative of maintaining separate connectors for each data source—a fragmented model that requires custom implementations and is difficult to scale. By adopting MCP, developers avoid the cost of building and maintaining those bespoke integrations, gaining portability and interoperability at the expense of potential performance fine-tuning for a specific data source. The cost avoided is a "more sustainable architecture" that would otherwise require updating every connector independently when interfaces change.

A concrete failure mode is token-lifecycle overhead during a long-running multi-turn session. An operator would see repeated OAuth token expiration errors in the MCP client logs—requests to the server are rejected mid-conversation because the session token has expired without being refreshed. This exemplifies an open challenge identified in the source: the protocol’s token management can introduce latency and failure if not handled with cryptographic hardening or edge caching. The operator’s signal is a stream of 401 Unauthorized responses from the MCP server after the initial capabilities handshake succeeded.

Failure modes — what breaks, what catches it

Failure 1: Unrestricted STDIO MCP Execution Leading to Arbitrary Command Injection

  • Trigger — User input flows directly into a STDIO-based MCP configuration without sanitization, as documented in the OX Security research.
  • Guard — No guard exists within the MCP protocol or official SDKs. Anthropic "declined to modify the protocol, stating the STDIO execution model represents a secure default and that sanitization is the developer’s responsibility."
  • PostureFail-soft — The system continues to operate, but the attacker's commands are executed on the host, compromising security. There is no crash or abort.
  • Operator signal — Surprising tool invocations or network traffic to unknown URLs; OX Security detected "executed commands on six live production platforms and produced 10+ Critical/High CVEs from this single root cause."
  • Recovery — Manual investigation and remediation required: "Upgrade to the Latest Versions" of affected services, "implement IP and URL blocking", or "disable it until patched." No automatic retry or fallback exists.

Failure 2: Unauthorized Data Exfiltration via Malicious Tool Calls

  • Trigger — An attacker-controlled or compromised MCP server invokes a tool that sends data to an unknown external URL.
  • Guard — The MCP protocol provides no built-in guard. The source advises operators to "Monitor Tool Invocations" and "Be wary of any 'background' activity or tools that attempt to exfiltrate data to unknown external URLs. If possible, implement IP and URL blocking."
  • PostureFail-soft — The data exfiltration proceeds; the subsystem does not halt or refuse the write.
  • Operator signal — Log entries showing connections to "unknown external URLs" or unexpected outbound traffic, as highlighted in the advisory.
  • Recovery — Manual step: block the offending IPs/URLs, audit tool permissions, and potentially revoke the compromised server's credentials. No automatic retry or fallback.

Failure 3: Wide Exposure of MCP Servers Without Authentication

  • Trigger — MCP servers are deployed in default configurations without access controls, leading to "7,000+ exposed servers" and "200+ open-source projects" being reachable.
  • Guard — No authentication or authorization guard is enforced by the MCP protocol itself. The source notes that "Anthropic could implement manifest-only execution or a command allowlist in the official SDKs" — but this is only a suggestion, not an existing guard.
  • PostureFail-soft — Servers remain accessible and continue to process requests from any client, even malicious ones.
  • Operator signal — A network scan reveals "150M+ downloads, 7,000+ exposed servers, and 200+ open-source projects" — any external party can enumerate and connect to these servers.
  • Recovery — "Upgrade to the Latest Versions" or "don’t expose it to user input or disable it until patched." Manual configuration of authentication or network-level restrictions is required.

Failure 4: Zero-Interaction Exploitation in MCP-Capable IDEs (CVE-2026-30615)

  • Trigger — A specifically crafted MCP request targeting Windsurf, where "exploitation required zero user interaction" (CVE-2026-30615).
  • Guard — No guard exists at the protocol level. The CVE implies a patch was issued for Windsurf, but the MCP protocol itself remains unchanged.
  • PostureFail-soft — The IDE continues operation while the exploit executes; the system does not crash or refuse the write.
  • Operator signal — Unexpected tool execution without any user action, potentially observable as a new process or network activity.
  • Recovery — "Upgrade to the Latest Versions" of the affected IDE (Windsurf). For other IDEs (Cursor, VS Code, Claude Code, Gemini-CLI) the source states they are "all vulnerable" but does not list CVEs; manual inspection and patching are required. No automatic fallback.

03. Tools Resources And Prompts

A server using the Model Context Protocol offers callable tools. This protocol, known as M C P, is an open standard for agent-tool integration. It lets a model discover and invoke tools without custom glue code. The server also provides readable resources. These include messages, user preferences, and long-term memory. The model accesses them through the tool runtime context. That runtime gives access to state, context, and store. It makes tools context-aware, stateful, and memory-enabled. The trade-off is that developers must follow the protocol's interface instead of writing bespoke code. But the benefit is a consistent, interoperable system. The protocol works in real-world testbeds with many servers and tools. This standard simplifies how models interact with external capabilities. It removes the need for one-off integrations.

A tool uses ToolRuntime to access conversation messages as a resource.

python
from langchain.tools import tool, ToolRuntime

@tool
def get_message_count(runtime: ToolRuntime) -> str:
    """Get the number of messages in the conversation."""
    messages = runtime.state["messages"]
    return f"There are {len(messages)} messages."
ELI5 — the plain-language version

Imagine a waiter who can order from any kitchen using a single, universal order pad instead of learning each chef’s secret handshake. That is what the Model Context Protocol does: it lets a large language model discover and call tools through a common interface, so no custom code is needed to connect them. This subsystem is for giving the model access to external functions and data without rewriting everything for each new tool.

Now picture the waiter’s order pad as the “tool runtime context.” The server offers callable tools—like dishes on a menu—and also provides readable resources: past messages, user preferences, and long-term memory. When the model wants to act, it reads these resources through the runtime context, which gives it state, context, and store. This makes each tool call context‑aware and memory‑enabled, just as the waiter remembers a regular’s dietary restrictions. The tool runtime context is the crucial mechanism that feeds the model the information it needs before it picks a function.

The trickiest part is the unavoidable trade‑off: developers must follow the protocol’s strict interface instead of writing bespoke glue code. That interface is what keeps all tools interchangeable—without it, every integration would be one‑off and fragile. If the protocol were skipped, the model might call the wrong tool with the wrong arguments, like a waiter sending a steak to a vegan table. The concrete failure a beginner would feel: an irreversible action—deleting a file, transferring money, or sending an email to the wrong person—because there was no standard guard to catch the mistake before execution.

System design — mechanism, invariant, trade-off

The subsystem operates through a session-oriented, JSON-RPC framework where the server first negotiates capabilities with the client via the MCP lifecycle, then the client issues tool invocations and resource retrieval requests under OAuth 2.1-compliant access control. On failure—such as when a tool parameter is malformed or a token expires—the server returns a standard JSON-RPC error response, and the client may retry after renegotiating capabilities or refreshing credentials. The invariant the design preserves is session-oriented state continuity: each interaction is scoped to a negotiated session, ensuring that tool-use context (messages, user preferences, long-term memory) remains consistent across multiple turns without bespoke session management. This guarantee is enforced by the protocol’s transport semantics and fine-grained access control, preventing stateless drift.

The key trade-off is requiring developers to build against a single, standard interface rather than writing custom glue code for each data source. This design explicitly rejects the alternative of maintaining separate connectors for each enterprise system (e.g., Google Drive, Slack, GitHub). The cost that rejection avoids is the fragmented integration architecture described in the source: “Instead of maintaining separate connectors for each data source, developers can now build against a standard protocol,” which eliminates the overhead of repeated ad-hoc integration and the brittleness of mismatched schemas. The trade-off is accepted because the protocol’s uniformity enables sustainable, scalable agent-tool interoperability even though it constrains developers to a fixed negotiation and invocation pattern.

A concrete failure mode is cross-server privilege escalation, where a tool invoked from one MCP server attempts to access resources or invoke tools on another server without proper authorization. An operator would see repeated OAuth 2.1 access token rejection logs in the server’s audit trail, accompanied by errors such as "error": {"code": -32001, "message": "Unauthorized cross-server tool invocation"}. This signal directly indicates a violation of the capability-graph isolation boundary that the protocol’s security model enforces, prompting an operator to review the server’s capability negotiation settings and token lifecycle configurations.

Failure modes — what breaks, what catches it

1. Security Exploit via STDIO MCP Command Injection

  • Trigger – User input flows directly into a STDIO-based MCP configuration, enabling arbitrary command execution on the server.
  • Guard – No guard exists within the MCP protocol itself; the source notes that Anthropic “declined to modify the protocol” and that “sanitization is the developer’s responsibility.” The recommended external guard is IP and URL blocking, but it is not part of the subsystem.
  • Posture – Fail-open: the exploit executes and the attacker gains control; the server continues running but is compromised.
  • Operator signalCVE-2026-30615 (the Windsurf CVE) or observations of “exfiltration to unknown external URLs.”
  • Recovery – Manual step: disable the STDIO server until a patched version is deployed, then upgrade to a fixed release as stated in “Upgrade to the Latest Versions.”

2. Lazy Agent Tool Invocation Failure

  • Trigger – The model is conservative in entering tool mode even when tool necessity is nearly perfectly decodable from mid-layer activations; the Lazy Agent failure mode prevents the server from invoking a required tool.
  • GuardActivation Steering Adapter (ASA) with a probe-guided signed gate; this is a training-time intervention that “amplif[ies] true intent while suppressing spurious triggers.”
  • Posture – Fail-soft: the agent degrades by not calling the tool, but the server continues processing the request without it.
  • Operator signal – Degraded strict tool-use F1 (e.g., from 0.50 to 0.18) and an elevated false positive rate (e.g., from 0.05 to 0.15).
  • Recovery – The ASA intervention is single-shot at inference time; no retry is performed. The model proceeds without the tool call.

3. Incorrect Tool Selection Undetected Until Execution

  • Trigger – The model picks the wrong tool; the failure is “invisible until execution” because the server has no built-in check before the tool runs.
  • GuardCosine readout of the model’s internal state can read the chosen tool before generation (61–82% accuracy on BFCL). The same per-tool directions also “flag likely errors before they happen” – queries where the model is unsure fail 21× more often on Gemma 3 27B.
  • Posture – Fail-closed if the flag is raised: the server refuses to execute the tool call. If no guard is present, the call proceeds and the failure is only visible post-execution.
  • Operator signal – A uncertainty flag or a logged cosine readout indicating mismatch between the intended and generated tool.
  • Recovery – Manual review of the flagged call; the operator can manually issue the correct tool invocation.

4. Irreversible Action Due to Low‑Confidence Function Call

  • Trigger – The LLM calls a function that is irreversible (e.g., transferring money, deleting data) with low actual confidence, but the server has no uncertainty quantification to gate execution.
  • Guard – If implemented, logit-based uncertainty scores (by selecting only semantically meaningful tokens) or Semantic Entropy with abstract syntax tree parsing would serve as the guard. The source states these are “UQ methods” that “can be used to prevent potentially incorrect function calls.” If absent, there is no guard.
  • Posture – Without a guard: fail-open – the irreversible action executes. With a guard: fail-closed – the server refuses the call when the uncertainty score exceeds a threshold.
  • Operator signal – An uncertainty score (e.g., high semantic entropy) logged alongside the call, or no signal if the guard is missing.
  • Recovery – Without a guard: manual rollback or compensation (e.g., reversing a transaction). With a guard: the call is blocked and the operator receives an alert to re‑prompt or override.

5. Multi‑Turn Instability of Tool Steering

  • Trigger – In multi‑turn agent loops, the same mid‑layer intervention that works in single‑turn settings becomes unstable; the source reports “matched‑baseline gain or loss of up to 30 percentage points with no consistent direction.”
  • Guard – None is discussed; the source only observes the instability.
  • Posture – Fail-soft: the agent continues with degraded or randomly varying tool selection, but the server does not abort.
  • Operator signal – Fluctuating tool‑use F1 across turns, with up to “30 percentage points” of variance from the baseline.
  • Recovery – No automatic recovery; the operator can disable the intervention for multi‑turn scenarios and fall back to the base model’s tool calling.

04. Elicitation And Structure

The Model Context Protocol is the emerging open standard for connecting AI agents to tools. It gives tools access to runtime context like state, user info, and long-term memory. Tools can also stream output and use store access. This enables context-aware, stateful, and memory-enabled tools. The benchmark MCP-AgentBench evaluates agents using thirty-three servers with one hundred eighty-eight tools. Agents handle six hundred queries across six categories. The protocol uses short-term memory called state for message history and custom fields. A trade-off is that managing all these runtime connections adds complexity. But the design supports real-world task success through outcome-oriented evaluation.

Tool accesses runtime state to retrieve message count.

python
from langchain.tools import tool, ToolRuntime

@tool
def get_message_count(runtime: ToolRuntime) -> str:
    """Get the number of messages in the conversation."""
    messages = runtime.state["messages"]
    return f"There are {len(messages)} messages."
ELI5 — the plain-language version

Think of this subsystem as a universal plug that lets an AI assistant connect to many different tools—like a single charger that works for a phone, tablet, and laptop. The Model Context Protocol is for giving AI agents a standard way to reach tools and share the current situation, so the assistant doesn't have to start from scratch every time.

When the assistant wants to use a tool, the protocol first hands over the current context: the conversation history (called state), user information, and longer-term memories. The tool can then stream its output back as it works, and even read or write to a shared store. To test this, a benchmark named MCP-AgentBench runs assistants against thirty-three servers that offer one hundred eighty-eight different tools, handling six hundred real-world queries.

The trickiest part is that all this context—state, user info, memory—must be managed live, which creates a trade-off: keeping these runtime connections smooth and secure is hard. Without this protocol, each tool would need its own custom adapter and the assistant would have no shared memory of what just happened—so it might send an email to the wrong person because it forgot the earlier part of the conversation, causing a frustrating, real-world failure.

System design — mechanism, invariant, trade-off

The Model Context Protocol (MCP) subsystem operates as a standardized runtime environment for connecting AI agents to external tools. The ordered mechanism begins when an agent receives a query from one of six categories defined by MCP‑AgentBench. The agent then selects and invokes tools from a pool of 188 tools hosted across 33 servers, using the protocol’s short‑term memory called state to preserve message history and custom fields throughout the interaction. If a tool call fails—for example, due to a malformed request or server timeout—the agent may retry the call or fall back to another tool, though the benchmark’s evaluation framework (MCP‑AgentBench) records the outcome as part of its standardized validation. The next step is the tool’s response, which can include streamed output or store access, and the state is updated accordingly before the agent proceeds to the next query or category.

The invariant preserved by this design is the state guarantee: the state must accurately and consistently reflect the message history and custom fields across all tool invocations within a query session. This ensures that the agent remains context‑aware, stateful, and memory‑enabled—properties explicitly cited in the source. Any deviation from this invariant (e.g., state desynchronization or loss of previous turns) would violate the reliable memory that the protocol promises. The benchmark itself, MCP‑AgentBench, enforces this invariant by evaluating agents against 600 queries, requiring that the state be correctly maintained throughout each session.

The key trade-off in adopting MCP is between standardized interoperability and the overhead of managing many runtime connections. The architecture explicitly rejects ad‑hoc, per‑tool integration strategies that would require custom wiring for each tool and server. Instead, MCP centralizes connection management, tool discovery, and state handling. The cost this rejection avoids is the fragmentation and maintenance burden of bespoke integrations—a problem highlighted by the source’s observation that the literature on LLM‑driven agents “lacks a unified view on contemporary frameworks such as Model Context Protocol.” The price paid is the complexity of maintaining a protocol that must handle diverse tool behaviors, streaming output, and store access across 188 tools, but the benchmark provides a standardized way to validate that this complexity is manageable.

A concrete failure mode occurs when the state becomes inconsistent due to a tool returning an unexpected error that corrupts the custom fields or message history. An operator monitoring the MCP‑AgentBench evaluation would see a degraded strict tool‑use F1 score—for example, dropping from an expected 0.50 to below 0.30—accompanied by a spike in the false positive rate (e.g., from 0.05 to 0.15). This signal indicates that the agent is misusing tools because its internal state no longer reflects the correct conversational context, violating the state invariant and causing incorrect tool calls. The benchmark’s standardized logs would pinpoint which queries and tools triggered the failure, enabling the operator to diagnose the root cause in the protocol’s runtime handling.

Failure modes — what breaks, what catches it

Lazy Agent Failure

  • Trigger — The model encounters a query that requires a tool call but remains conservative, failing to enter tool mode despite tool necessity being decodable from mid-layer activations. This is explicitly identified in the ASA paper as a "Lazy Agent failure mode."
  • Guard — "ASA (Activation Steering Adapter)" performs a single-shot mid-layer intervention using a "router-conditioned mixture of steering vectors with a probe-guided signed gate" to amplify true intent and suppress spurious triggers.
  • Posture — Without ASA, the agent continues operating (fail-soft) but with very low tool-use F1 (0.18 baseline); with ASA the failure is corrected, but the baseline system has no built-in guard other than ASA itself.
  • Operator signal — Low strict tool-use F1 (0.18) and elevated false positive rate (0.15) on MTU-Bench, as reported in the ASA evaluation.
  • Recovery — ASA applies a training‑free, inference‑time activation steering that requires no retry or backoff; the improvement is a single‑shot correction using about 20KB of portable assets.

Wrong Tool Selection

  • Trigger — The model is unsure between two tools, leading to selection of the wrong one. The "Tool Calling is Linearly Readable and Steerable" paper notes that queries exhibiting uncertainty between tools fail 21× more often than unambiguous queries.
  • Guard — "cosine readout" recovers the chosen tool from internal state with 61‑82% accuracy on BFCL, and "per‑tool directions" flag likely errors before execution by reading which tool the model will call.
  • Posture — Fail‑closed: the guard is designed to catch the mistake before execution, allowing the agent to refuse or switch the call rather than executing a wrong action.
  • Operator signal — High uncertainty indicated by the probe output or low cosine similarity to a dominant tool direction; the paper reports that "queries where the model is unsure between two tools fail 21x more often."
  • Recovery — Adding the correct tool direction during generation switches the tool automatically; no retry loop is specified—the steerable direction provides a single‑shot correction.

Incorrect Function Call with High Confidence

  • Trigger — The LLM calls a function incorrectly while exhibiting high confidence, which can cause irreversible consequences (e.g., transferring money or deleting data). The Uncertainty Quantification paper highlights this as a critical failure mode.
  • Guard — "Semantic Entropy" is a multi‑sample UQ method, and "single‑sample UQ methods" improved by "selecting only semantically meaningful tokens when calculating logit‑based uncertainty scores" serve as guards to quantify confidence and prevent execution when uncertainty is high.
  • Posture — Fail‑closed: the purpose of the UQ methods is to "prevent potentially incorrect function calls," i.e., refuse to execute the function if confidence is low.
  • Operator signal — High uncertainty score or low confidence value reported by the UQ method, such as an elevated Semantic Entropy score or a low logit‑based certainty metric.
  • Recovery — The agent does not execute the function; the source does not specify automatic fallback behavior—manual review or an alternative call may be required.

Vulnerability Misclassification

  • Trigger — The LLM detects insecure code but classifies it under the wrong Common Weakness Enumeration (CWE) category. The "Can Open Large Language Models Catch Vulnerabilities?" paper reports "high detection rates and markedly poor classification accuracy" with frequent overgeneralization and misclassification.
  • Guard — No guard is identified in the source; the paper evaluates three models (Llama3, Codestral, Deepseek R1) and exposes their failures without proposing a runtime handler.
  • Posture — Fail‑soft: the model still flags a vulnerability (so detection succeeds) but the classification error leads to incorrect remediation advice; the system continues.
  • Operator signal — Low CWE classification F1 despite high detection F1; the paper explicitly contrasts "high detection rates and markedly poor classification accuracy."
  • Recovery — Manual re‑classification by a human security analyst is required; the source states that "challenges must be addressed before reliable deployment" and provides no automatic recovery.

Voice‑Tool Domain Mismatch

  • Trigger — A voice agent attempts to use tools from speech input, but the underlying tool‑calling benchmarks and models are trained primarily on text, causing unreliable tool use. The "From Text to Voice" paper notes that "voice agents increasingly require reliable tool use from speech, whereas prominent tool‑calling benchmarks remain text‑based."
  • Guard — No guard is identified in the source; the paper proposes a reproducible framework for evaluation but does not specify a runtime guard for this mismatch.
  • Posture — Fail‑soft: the agent continues to operate but with degraded accuracy on speech inputs compared to text.
  • Operator signal — Reduced tool‑call accuracy on speech tasks relative to text baselines, as would be observed in a cross‑domain evaluation.
  • Recovery — The source does not define a recovery mechanism; a practical step would be to switch to text‑mediated interaction or retrain the model on speech‑tool data.

05. Registry And Discovery

The Model Context Protocol, or MCP, is an open standard for tool integration. The protocol defines a well-known discovery suffix to help find server endpoints. This is one way to locate services. Governance of the protocol happens through standards track proposals called SEPs. Three key governance SEPs shape how the protocol evolves. There is a feature lifecycle with active, deprecated, and removed stages. Deprecation lasts at least twelve months before any removal. That gives developers time to update their code. An extensions framework lets new capabilities ship as opt-in additions. They can stabilize before moving into the core specification. A conformance suite ensures every implementation meets the standard. A SEP cannot reach final status without a matching conformance test. This vets changes before they become official. The spec also clarifies scope accumulation and how to request refresh tokens from authorization servers. As of July twenty twenty-six, this governance structure is in place. It allows the ecosystem to grow while keeping interoperability stable. The trade-off is that foundational changes require a clean break, but future revisions can now avoid breaking core capabilities.

Tool execution using ToolRuntime for state access in MCP tools

python
from langchain.tools import tool, ToolRuntime

@tool
def summarize(runtime: ToolRuntime) -> str:
    """Summarize the conversation."""
    messages = runtime.state["messages"]
    return f"Conversation length: {len(messages)} messages."
ELI5 — the plain-language version

Imagine a city where every building follows a standard address pattern—a street name plus a number—so you can always find any shop or office without a map. The Model Context Protocol (MCP) does the same for AI tools: it defines a common signpost system so that any AI assistant can locate and connect to the data sources it needs, no matter who built them. This is the registry and discovery subsystem.

The signpost system uses a well-known discovery suffix that servers include in their web addresses. When an AI wants to use a tool like a shared calendar or a code repository, it looks for this suffix to find the right server. Just as a city updates its street signs through a formal process, MCP uses standards-track proposals called SEPs to decide how the protocol evolves. These SEPs define a clear lifecycle: a feature is first active, then becomes deprecated with a warning that lasts at least twelve months—like a yellow caution tape—before it can be fully removed. This gives developers time to update their applications.

The trickiest part is the extensions framework: new capabilities are added as opt-in additions, similar to how a city might add bike lanes that not every street needs. This keeps the base protocol lean and avoids conflicts, because each new feature must be explicitly chosen by a server. Without this careful lifecycle and extensions framework, a sudden change could break thousands of tools overnight. A beginner would feel the failure as their favorite AI suddenly unable to access a project’s files or calendar events, because the old address no longer worked and there was no warning.

System design — mechanism, invariant, trade-off

Based solely on the provided context, there is no description of a “Registry And Discovery” subsystem, a well‑known discovery suffix, Standards‑track Proposal (SEP) governance, or a feature‑lifecycle with a twelve‑month deprecation window. The context discusses the Model Context Protocol (MCP) in broad terms—its role as an open standard for connecting AI to data sources, its host‑client‑server architecture, and its JSON‑RPC framework—but does not detail any discovery or registry mechanism. Consequently, a system‑design explanation of the ordered mechanism, invariant, trade‑off, or concrete failure mode for such a subsystem cannot be grounded in the supplied source material. No real function or identifier from the context (e.g., “SEP”, “discovery suffix”, “active/deprecated/removed”) appears in the provided text; the only named components are “MCP servers”, “MCP clients”, and the protocol’s specification and SDKs mentioned in the Anthropic announcement. Therefore, the query cannot be answered using only the given context.

Failure modes — what breaks, what catches it

Discovery Endpoint Returns an Unrecognized Error Code

  • Trigger – A client sends a request to the protocol’s discovery endpoint for a missing resource and receives the old MCP-custom error code -32002 because the server has not yet adopted the change documented in SEP-2164.
  • Guard – SEP-2164 specifies that the error code for a missing resource now uses the JSON-RPC standard -32602 Invalid Params. If the client’s error‑handling code matches on the literal -32002, that guard is not present; the client has no real exception handler for this mismatch.
  • Posture – fail‑hard: the client’s error‑matching logic does not recognize the returned code, so the request is treated as an unexpected failure and the operation aborts.
  • Operator signal – A log line showing the literal error code -32002 where a code‑matching fallback would expect -32602.
  • Recovery – The client must be updated to handle the new error code as specified in SEP-2164. No automatic retry or fallback is described.

Discovery Suffix Not Implemented by Server

  • Trigger – The client attempts to locate the server’s endpoints using the .well-known discovery suffix defined in SEP-2351, but the server does not expose that endpoint.
  • Guard – The source provides no real exception handler, retry, validation, or fallback for this case. The protocol defines the suffix but does not mandate a guard for a missing implementation.
  • Posture – fail‑hard: the client cannot proceed because it has no alternative discovery method and the request fails immediately.
  • Operator signal – A connection failure or HTTP 404 error logged at the point where the client tries to resolve the .well-known URI.
  • Recovery – No automatic recovery is described. An operator must manually configure the server’s endpoint or ensure the server adds the discovery suffix.

Deprecated Feature Used in a Discovery Request

  • Trigger – A client uses a feature that has been marked deprecated (e.g., one of the features under the feature lifecycle policy SEP-2577, such as Roots, Sampling, or Logging) during a discovery‑related interaction.
  • Guard – The feature lifecycle policy (SEP-2577) guarantees at least twelve months of deprecation before removal. During that period the feature still works, but the deprecation annotation is present.
  • Posture – fail‑soft: the feature continues to function during the deprecation window; the system does not abort or refuse the write. After removal (post‑deprecation) it becomes fail‑hard.
  • Operator signal – A deprecation warning emitted by the protocol implementation, derived from the annotation described in SEP-2577.
  • Recovery – The operator should update the client to use the replacement feature before the removal date. No automatic retry or fallback is triggered by the guard.

Extension Activation Fails on the Server

  • Trigger – The client attempts to use an opt-in extension for a new capability (e.g., a trigger or event‑driven update listed in the “On the Horizon” section), but the server does not support that extension.
  • Guard – The extensions framework allows servers to ignore unsupported extensions; there is no explicit handler for activation failure—the capability simply fails to materialize.
  • Posture – fail‑soft: the core protocol continues to operate, and the client falls back to whatever baseline functionality does not require the extension.
  • Operator signal – A log line indicating that a requested capability is missing or that the extension was not recognized.
  • Recovery – The client continues with the core protocol; no automatic retry or fallback value is specified beyond dropping the extension’s optional feature.

06. Securing The Protocol

Trust boundaries between tools and models rely on protocol-level security. In 2026 that protocol saw a major rework. The change included a full feature lifecycle policy. Each feature now has an active, deprecated, and removed phase. At least twelve months pass between deprecation and removal. That gives developers time to update. An extensions framework lets new capabilities ship as opt-in. They stabilize there before moving into the specification. Tool schemas now support full JSON Schema 2020 dash twelve. Input schemas allow composition and references. But implementations must not automatically follow external links. They should also limit schema depth and validation time. That stops untrusted tool output from breaking the model. Authorization also got clearer. The spec explains how to get refresh tokens from Open ID Connect style servers. It clarifies scope accumulation during step up. It also defines the well known discovery suffix. These are all protocol level changes. They outlast any quick fix in a prompt. The stateless rework was foundational. It needed a clean break. Now implementers targeting mid 2026 can adopt future versions without rewriting their transport or lifecycle code. The conformance suite ensures every change is properly tested. That makes trust boundaries more reliable.

Tool runtime access controls state boundaries.

python
from langchain.tools import tool, ToolRuntime

@tool
def summarize(runtime: ToolRuntime) -> str:
    """Summarize the conversation."""
    messages = runtime.state["messages"]
    return f"Conversation length: {len(messages)} messages."
ELI5 — the plain-language version

Think of a chef who picks a knife off the rack to chop onions—but sometimes they grab the wrong one, and the mistake is only obvious after the first cut. This subsystem is a way to peek inside the chef’s head before they touch the knife, so we can catch the error and prevent a ruined dish. It exists to stop large language models from calling the wrong tool when the cost of a mistake is high—like transferring money or deleting data—by checking the model’s internal certainty before any action happens.

Here is how it actually works. When the model decides which tool to use, that choice is stored as a specific direction in its internal activation space—a kind of mental label. Researchers can read that direction with a technique called cosine readout, which predicts which tool the model will call with 83–100% accuracy on large instruction-tuned models. At the same time, uncertainty quantification methods like Semantic Entropy measure how confident the model is: if the model is torn between two tools, that unsure state is a red flag. The system then blocks the call before it executes, turning a hidden mistake into a preventable one.

The trickiest part is that even when the model looks confident on the surface, its hidden state may already signal trouble. For example, queries where the model’s internal direction flickers between two tools fail twenty-one times more often than those where the direction is steady—a statistic that comes directly from evaluating the Gemma 3 27B model. Without this subsystem, a wrong tool call—like picking “delete account” instead of “update profile”—would be invisible until the damage is done, and by then the email is sent, the data is gone, and the user feels the irreversible consequence.

System design — mechanism, invariant, trade-off

The security subsystem of the Model Context Protocol (MCP) operates through a session-oriented, JSON-RPC framework that enforces trust boundaries between tools and models. The ordered mechanism begins when an AI application (MCP client) initiates a connection to an MCP server. First, both parties negotiate capabilities via the JSON-RPC handshake, establishing which tools and resources are available. Next, the client authenticates under fine-grained, OAuth 2.1-compliant access control, which authorizes each subsequent invocation of an external tool or retrieval of a contextual resource. On failure of authentication or authorization, the server rejects the request with a standard JSON-RPC error, aborting the operation before any tool execution occurs. Once authorized, every tool call is validated against its schema (now supporting full JSON Schema 2020‑12) to ensure arguments conform to the expected structure; a schema validation failure prevents the call from being dispatched.

The invariant the design preserves is the separation of trust boundaries: no tool is invoked without explicit, OAuth 2.1‑scoped permission, and no model state is exposed beyond the negotiated capabilities. This guarantee is enforced by the protocol’s session‑oriented lifecycle, which ties every request to a valid, authenticated session. The key trade‑off is embracing a heavyweight, stateful security model over a stateless alternative. The obvious rejected approach is the previous state of “stateless integration interfaces” and “ad‑hoc security controls” that were each custom‑built per data source. The cost avoided by rejecting that fragmentation is the inevitable fragility, non‑scalability, and auditing difficulty that arises when every integration must implement its own security. By unifying under OAuth 2.1 and session management, MCP gains a single, verifiable point of enforcement—but pays the price of token‑lifecycle overhead and session management complexity.

A concrete failure mode is cross‑server privilege escalation. An operator would see a JSON‑RPC error response from the MCP server with a code indicating “unauthorized” or “insufficient scope,” accompanied by a log entry showing that a client with credentials scoped to one server attempted to invoke a high‑privilege tool on another server. The signal is an OAuth 2.1 token‑scope mismatch: the token’s claims do not cover the requested resource, and the server denies the request. This failure surfaces because the protocol’s capability‑graph isolation prevents a client from leveraging credentials obtained from one host to access tools on another, even if the same user identity is involved. The operator can trace the incident to the specific MCP server’s access‑control logs, which record the token identifier, the tool name, and the failing scope check.

Failure modes — what breaks, what catches it

STDIO MCP Configuration Injection

  • Trigger — User input flows directly into STDIO MCP configuration, enabling arbitrary command execution.
  • GuardOX Security Platform scans for improper use of STDIO-based MCP configurations and surfaces actionable findings.
  • Posture — fail‑open (vulnerable until detection; the guard is post‑hoc, not preventive).
  • Operator signal — A finding referencing CVE-2026-30615 appears in the OX Security dashboard.
  • Recovery — Reconfigure using manifest-only execution or command allowlist, or apply the vendor patch.

Deprecated Feature Used After Removal

  • Trigger — A tool relies on a deprecated feature (e.g., Roots, Sampling, and Logging) after the removal phase.
  • Guard — None at runtime. The process guard is the feature lifecycle policy (SEP-2577), which mandates at least Twelve months between deprecation and removal, but does not catch usage after removal.
  • Posture — fail‑hard (the missing feature causes the tool call to abort).
  • Operator signal — Error indicating an unknown method or capability, e.g., "unrecognized capability flag".
  • Recovery — Update the tool to use non‑deprecated alternatives; the removal is governed by a separate SEP under the lifecycle policy.

External $ref Schema Dereference

  • Trigger — An attacker supplies a tool input schema containing an external $ref URI that points to malicious schema content.
  • Guard — The specification mandates that implementations must not auto-dereference external $ref URIs. This validation is applied when parsing the schema.
  • Posture — fail‑closed (the schema is rejected, and the tool call is refused).
  • Operator signal — Schema validation error with text referencing the external URI, e.g., "external $ref dereferencing is prohibited".
  • Recovery — The developer must replace the external $ref with a local $defs definition.

MCP Error Code Mismatch

  • Trigger — A client is hard‑coded to match the deprecated error code -32002 for a missing resource.
  • Guard — The protocol change defined in SEP-2164 replaced that code with the JSON‑RPC standard -32602 Invalid Params. The guard is the new error code itself being returned.
  • Posture — fail‑soft (the operation fails gracefully, but the client may misinterpret the error).
  • Operator signal — Client logs an unrecognized error code -32602 (or fails to handle it).
  • Recovery — Update the client to handle -32602 Invalid Params instead of -32002.

Unsafe Structured Content Validation

  • Trigger — A tool output uses structuredContent that is not an object (e.g., an array or primitive) when the caller expects an object.
  • Guard — The specification now allows structuredContent to be any JSON value (not just an object). There is no explicit validation guard; the schema outputSchema is unrestricted.
  • Posture — fail‑soft (the output is accepted but may cause parsing errors downstream).
  • Operator signal — An unexpected type error or schema mismatch in the consumer.
  • Recovery — The consumer must update its parsing logic to accept any JSON value as defined in the 2020-12 schema.