Skip to content

Model Context Protocol (MCP) explained

  • What the Model Context Protocol standardizes, and the roles of host, client and server.
  • The three server features (tools, resources, prompts) and who controls each.
  • How the two standard transports work, and what changed in the stateless 2026-07-28 revision.
  • How to build and call a minimal server with the official Python SDK.
  • The security risks that come with MCP, and when plain function calling is the better choice.

The Model Context Protocol (MCP) is an open protocol, created at Anthropic and published in November 2024, that standardizes how AI applications connect to external tools and data. A server exposes capabilities; any compliant host application (a chat app, an IDE, an agent runtime) can use them through a client. Messages are JSON-RPC 2.0, carried over stdio for local servers or Streamable HTTP for remote ones. In December 2025 Anthropic donated MCP to the Agentic AI Foundation, a directed fund under the Linux Foundation; the protocol’s maintainers still make technical decisions through the public specification enhancement proposal (SEP) process.

The value is reuse: an integration written once as an MCP server works in every MCP-capable application, instead of being rewritten for each one. The cost is a new trust boundary: a server’s tool descriptions and results flow into the model’s context, and its tools can act on real systems.

As of November 2026 the latest specification revision is 2026-07-28. It made the protocol stateless and removed the connection handshake, so material written for earlier revisions describes a different message flow.

A language model knows its training data and the current conversation. Useful work needs more: the order database, the ticket system, the repository, an API that performs an action.

Function calling already lets a model request a function, but the definition lives inside one application and is written against one provider’s API. With M applications and N systems you maintain M times N integrations. Each one also has its own conventions for authentication, errors and discovery.

MCP moves the integration behind a protocol. The system owner publishes one server; application authors implement one client. The forces to balance are the same as for any plug-in system: capability against control, and convenience against the risk of running or trusting third-party code.

Diagram of an MCP host containing a model and two MCP clients, each connected by JSON-RPC 2.0 to a separate MCP server (local over stdio, remote over Streamable HTTP with OAuth) that exposes tools, resources and prompts, with a trust boundary between host and servers.

Role What it is Example
Host The AI application the user works in. It owns the model, the user interface and the permission decisions A desktop chat app, an AI code editor, an agent service
Client The connector inside the host that speaks MCP to one server One client instance per configured server
Server A program that exposes capabilities from one system An orders server, a filesystem server, a Git server

The model never talks to a server directly. The host lists a server’s tools, passes their descriptions to the model, receives the model’s tool request, decides whether to allow it, and has the client make the call.

Feature Controlled by Purpose Example
Tools The model (it chooses to call them, subject to host approval) Actions and queries with a JSON Schema for input, and optionally for output get_order_status(order_id)
Resources The application Read-only context addressed by URI orders://policy/returns
Prompts The user Reusable prompt templates, often shown as slash commands delay_apology(order_id)

Tools are by far the most used. A tool result can carry unstructured content (text for the model) and structuredContent (JSON matching the declared output schema) together.

  • stdio. The host launches the server as a subprocess and exchanges one JSON-RPC message per line over standard input and output. The server must write nothing else to stdout; logs go to stderr. Credentials come from the environment. This is the usual choice for local tools.
  • Streamable HTTP. The server is an independent process with a single HTTP endpoint. Each request is a POST; the response is one JSON object or a Server-Sent Events stream scoped to that request. Authorization, when used, follows OAuth 2.1, with the MCP server acting as a resource server.

The older HTTP+SSE transport from the first revision has been deprecated since 2025-03-26. Configuration examples that end in /sse are for that legacy transport.

Earlier revisions opened every connection with an initialize handshake and, over HTTP, kept a session identified by an Mcp-Session-Id header. The 2026-07-28 revision removed both:

  • No handshake, no protocol-level session. Every request carries its protocol version and the client’s capabilities in _meta. A server accepts or rejects each request on its own, which lets HTTP servers sit behind an ordinary load balancer.
  • server/discover. Servers must implement this method to advertise supported versions, capabilities and identity.
  • Multi round-trip requests. A server no longer sends requests to the client. If it needs more input (for example user confirmation through elicitation), it returns a result with resultType: "input_required" and the client retries with the answers. Every result now has a resultType.
  • subscriptions/listen replaces the HTTP GET stream and the resource subscribe methods for change notifications.
  • Deprecations. Roots, Sampling and Logging are deprecated, along with the legacy HTTP+SSE transport. Experimental tasks moved to an official extension.
  • Caching hints. List and read results carry ttlMs and cacheScope.

The specification calls 2026-07-28 and later “modern” and 2025-11-25 and earlier “legacy”. Many deployed clients and servers still speak a legacy revision, so check what your host and SDK support before relying on a modern-only feature.

The example domain is an invented shop, OrdersPortal. The server exposes one tool, one resource and one prompt; the client launches it over stdio and calls each.

To run it: Python 3.10 or later and pip install mcp (verified with Python 3.11 and mcp 2.3.0, which speaks protocol revision 2026-07-28). Save both files in one directory and run python orders_client.py. No API key or model is involved: this exercises the protocol only.

# orders_server.py - a minimal MCP server for an invented OrdersPortal shop
from typing import TypedDict
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
mcp = MCPServer("orders-portal", version="1.0.0", instructions="Read-only access to OrdersPortal orders.")
class OrderStatus(TypedDict):
status: str
eta: str | None
ORDERS: dict[str, OrderStatus] = {
"A1001": {"status": "shipped", "eta": "2026-11-19"},
"A1002": {"status": "awaiting payment", "eta": None},
}
@mcp.tool()
def get_order_status(order_id: str) -> OrderStatus:
"""Return the status and estimated delivery date of one order. Use for 'where is my order' questions."""
if order_id not in ORDERS:
raise ToolError(f"Unknown order: {order_id}") # shown to the model as an error result
return ORDERS[order_id]
@mcp.resource("orders://policy/returns")
def returns_policy() -> str:
"""The current returns policy."""
return "Returns are free within 30 days of delivery."
@mcp.prompt()
def delay_apology(order_id: str) -> str:
"""Draft an apology for a late order."""
return f"Write a short, factual apology for the delay of order {order_id}. Do not promise compensation."
if __name__ == "__main__":
mcp.run() # stdio transport by default
# orders_client.py - launch the server as a subprocess and talk to it over stdio
import asyncio
import sys
from mcp import Client, StdioServerParameters
async def main() -> None:
server = StdioServerParameters(command=sys.executable, args=["orders_server.py"])
async with Client(server) as client:
print("server:", client.server_info.name, "| protocol:", client.protocol_version)
tools = await client.list_tools()
for tool in tools.tools:
print("tool:", tool.name, "| required:", tool.input_schema.get("required"))
result = await client.call_tool("get_order_status", {"order_id": "A1001"})
print("result:", result.structured_content, "| is_error:", result.is_error)
missing = await client.call_tool("get_order_status", {"order_id": "Z9"})
print("error:", missing.content[0].text, "| is_error:", missing.is_error)
policy = await client.read_resource("orders://policy/returns")
print("resource:", policy.contents[0].text)
prompt = await client.get_prompt("delay_apology", {"order_id": "A1001"})
print("prompt:", prompt.messages[0].content.text)
asyncio.run(main())

Output:

server: orders-portal | protocol: 2026-07-28
tool: get_order_status | required: ['order_id']
result: {'status': 'shipped', 'eta': '2026-11-19'} | is_error: False
error: Error executing tool get_order_status: Unknown order: Z9 | is_error: True
resource: Returns are free within 30 days of delivery.
prompt: Write a short, factual apology for the delay of order A1001. Do not promise compensation.

What the SDK did for you:

  • The type hints became the tool’s JSON Schema (order_id is required), and the OrderStatus return type became its output schema, which is why structured_content is populated.
  • The docstring became the tool description. It is the only guidance the model gets about when to call the tool, so write it for the model.
  • ToolError produced a normal result with is_error set, so the model can read the message and recover. Any other exception is treated as a crash: the SDK logs the traceback on the server and returns only a generic message, which keeps internal details out of the model’s context.

To see the protocol without the client SDK, send one request by hand. Note the _meta block that replaces the old handshake.

# raw.py - speak JSON-RPC to the server by hand to see the wire format
import json
import subprocess
import sys
server = subprocess.Popen(
[sys.executable, "orders_server.py"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
)
request = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "get_order_status",
"arguments": {"order_id": "A1001"},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": {"name": "raw-demo", "version": "0.1"},
},
},
}
server.stdin.write(json.dumps(request) + "\n") # one JSON message per line
server.stdin.flush()
print(json.dumps(json.loads(server.stdout.readline()), indent=2))
server.kill()

Output:

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"text": "{\n \"status\": \"shipped\",\n \"eta\": \"2026-11-19\"\n}",
"type": "text"
}
],
"isError": false,
"resultType": "complete",
"structuredContent": {
"status": "shipped",
"eta": "2026-11-19"
},
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "orders-portal",
"version": "1.0.0"
}
}
}
}

Hosts are configured with the command that starts a stdio server, or the URL of a remote one. Many desktop hosts use a JSON file with an mcpServers object; the file’s location and exact keys differ per product, so follow the host’s own documentation. A typical stdio entry:

{
"mcpServers": {
"orders-portal": {
"command": "python",
"args": ["/absolute/path/to/orders_server.py"],
"env": { "ORDERS_API_TOKEN": "read-from-your-secret-store" }
}
}
}

This is a configuration fragment and was not loaded into a host for this page. For one host’s specifics, see MCP in Kiro.

The modelcontextprotocol/servers repository now holds only a small set of reference servers (Everything, Fetch, Filesystem, Git, Memory, Sequential Thinking, Time), which its README describes as educational examples, not production-ready solutions. Earlier reference servers for GitHub, GitLab, PostgreSQL, Slack and others are archived; use the vendor-maintained servers instead. The official MCP Registry lists published servers. Official SDKs exist for Python, TypeScript, C#, Go, Java, Kotlin, PHP, Ruby, Rust and Swift.

Approach Strengths Costs Choose it when
Direct function calling No extra process or protocol; tools live with your code; easiest to secure Tied to one application; rewritten for each host The tools serve one application you own
MCP server Write once, use in any MCP host; clear process boundary; standard discovery and auth Another component to deploy, version and secure; tool definitions consume context Several hosts need the same integration, or you publish an integration for others
RAG pipeline Grounding in large document sets by semantic search Retrieval only; no actions The need is knowledge, not operations
Plain REST or OpenAPI Mature tooling, well understood Not model-oriented; each host needs an adapter The consumer is ordinary software

These combine: an MCP server commonly wraps an existing REST API, and can expose a RAG search as a tool. MCP does not replace function calling inside the model API. The host still presents MCP tools to the model through the provider’s tool-use mechanism.

  • Prompt injection through tool results. Text a tool returns (a web page, a ticket, a file) can contain instructions. The model may follow them. Treat all tool output as untrusted data, and require approval for consequential actions.
  • Tool poisoning and silent redefinition. A malicious or compromised server can hide instructions in tool descriptions or change a tool after you approved it. The specification says clients must treat tool annotations as untrusted unless the server is trusted. Pin server versions and review changes.
  • Over-broad credentials. A server holding an administrator token gives the model administrator reach. Issue least-privilege, read-only tokens where possible, one per server.
  • Local servers are code execution. A stdio server is a program run with your user’s permissions. Install only servers you would install as ordinary software.
  • Token passthrough and confused deputy. A remote server must validate that a token was issued for it and must not forward a client’s token to downstream APIs. Follow the specification’s authorization and security guidance.
  • Too many tools. Every tool description is sent to the model. Dozens of servers crowd the context, raise cost and reduce tool-selection accuracy. Enable only what a task needs.
  • Writing to stdout. A stray print in a stdio server corrupts the message stream. Log to stderr.
  • Revision mismatch. A modern-only client against a legacy server, or the reverse, fails at the first request. Know which revisions each side supports and test upgrades.
  • Operations. Give tools timeouts, return errors the model can act on, keep results small (paginate or summarize), log each call with its arguments and caller, and make write tools idempotent because a client may retry.
  • One application, a few tools. Define them with the provider’s function calling. A separate server adds deployment and a trust boundary for no reuse.
  • Deterministic integration. If no model chooses the call, use a normal API client.
  • Latency-critical inner loops. A process hop or HTTP round trip per call adds up.
  • Sensitive actions without an approval path. If the host cannot enforce confirmation, do not expose the action as a tool.
  • Bulk data transfer. Tool results enter the model’s context. Use MCP to locate or summarize data, not to move large datasets through the model.

1. Explain the difference between tools, resources and prompts. Tools are functions the model decides to call, with a JSON Schema for arguments. Resources are read-only data identified by URI that the application chooses to attach as context. Prompts are user-invoked templates. The distinction is who is in control: model, application or user.

2. How does MCP relate to function calling? They are layers. Function calling is how a model API lets the model request a call. MCP is how a host discovers and invokes tools that live in other processes. A host turns MCP tool definitions into function-calling definitions for the model, then routes the model’s request back through the MCP client.

3. What did the 2026-07-28 revision change, and why does it matter for deployment? It removed the initialize handshake and protocol-level sessions. Each request carries version and capabilities in _meta, and server-initiated requests were replaced by results that ask the client to retry with input. Servers no longer need session affinity, so they scale behind standard load balancers and are easier to run on serverless platforms. The cost is a compatibility split with legacy clients and servers.

4. Senior scenario: your company wants to give an internal coding assistant access to the production orders database through MCP. How do you design it? Do not expose a generic SQL tool. Build a server with a few narrow, read-only tools (order by ID, orders by customer) backed by parameterized queries and a read-replica account with column-level limits on personal data. Run it as a remote Streamable HTTP server with OAuth so each call carries a user identity, enforce the user’s own permissions on the server side, and log every call. Cap result sizes. Treat returned text fields as untrusted input to the model. Add any write operations later, behind explicit human approval in the host, with idempotency keys. Review the server like any service that touches production data, and pin its version in host configuration.

5. Senior scenario: a developer added a community MCP server and the assistant then pushed code to an unexpected repository. What happened and what controls prevent it? Likely an injection: either the server’s tool description or a result it returned contained instructions, and another connected server had a write-capable token. Controls: allowlist servers and pin versions, scope each server’s credentials to the minimum, require confirmation for write tools, do not auto-approve tool calls, separate untrusted-content servers from servers with write access in the same session, and log tool calls so the chain can be reconstructed.

  • MCP standardizes the connection between AI hosts and external systems: one server, many hosts.
  • Servers expose tools (model-controlled), resources (application-controlled) and prompts (user-controlled).
  • stdio serves local servers; Streamable HTTP serves remote ones, with OAuth 2.1 for authorization.
  • Revision 2026-07-28 is stateless: no handshake, per-request metadata, input requests instead of server-initiated calls.
  • Every server is a trust decision: least privilege, pinned versions, approval for actions, and tool output treated as untrusted.
  • For tools used by a single application, plain function calling is simpler.