This lesson explains the Model Context Protocol at the level you need to build or connect a server safely: the architecture and message model, the changes in the current 2026-07-28 revision (which removed the initialisation handshake that most older tutorials describe), transports, server primitives, authorisation for remote servers, and the security obligations the specification places on hosts and servers. It finishes with a minimal read-only server and client, tested against the official Python SDK, that you can run in a few minutes.
Version note: read this before older tutorials
MCP uses date-stamped revisions that mark the last backwards-incompatible change. The current revision is 2026-07-28 [1]. It made the protocol stateless, and several things that tutorials from 2024 and 2025 describe no longer exist in the current revision [2]:
- The
initialize/notifications/initializedhandshake is gone. Every request carries its protocol version and client capabilities in_meta(io.modelcontextprotocol/protocolVersion,io.modelcontextprotocol/clientCapabilities), and clients should identify themselves per request withio.modelcontextprotocol/clientInfo. - Servers must implement
server/discover, which returns supported versions, capabilities and identity in one call. Clients may call it first, and on stdio it doubles as the probe for falling back to legacy servers. - Protocol-level sessions and the
Mcp-Session-Idheader were removed from Streamable HTTP. Servers needing cross-call state mint explicit handles passed as tool arguments. - Server-initiated requests (elicitation, sampling, roots) are
replaced by the Multi Round-Trip Requests pattern: the
server returns a result with
resultType: "input_required"and the client retries the original request withinputResponses. Every result now carriesresultType. - Roots, Sampling and Logging are deprecated. OAuth Dynamic Client Registration is deprecated in favour of Client ID Metadata Documents.
SDKs adopt revisions on their own schedules [3]. The example in this lesson uses the official Python
SDK mcp 2.3.0, which negotiates 2026-07-28 and falls back
to the handshake for older servers.
Architecture
MCP messages are JSON-RPC 2.0. The specification defines three roles [4]:
- Host: the LLM application. It creates clients, controls connection permissions, “enforces security policies and consent requirements”, handles user authorisation decisions and aggregates context [5].
- Client: a connector inside the host with a 1:1 relationship to one server. It attaches protocol version and capabilities to every request and maintains security boundaries between servers [5].
- Server: exposes tools, resources and prompts. It can be a local process or a remote service [5].
Two of the design principles are security properties worth holding implementers to: servers “should not be able to read the whole conversation, nor see into other servers”, and cross-server interactions are controlled by the host [5]. Nothing in the wire protocol enforces this; it is a host implementation obligation.
Capabilities are negotiated per request. Servers advertise theirs in
the server/discover result; clients send theirs in
_meta on each request [5].
Transports
stdio. The client launches the server as a
subprocess. Messages are newline-delimited JSON-RPC on stdin and stdout
and must not contain embedded newlines. The server may write logs to
stderr and must not write anything to stdout that is
not a valid MCP message [6]. The
commonest beginner bug is a print() in a stdio server
corrupting the stream; the official quickstart warns about exactly this
[7]. All request metadata is carried
in _meta; there is no header layer [6].
Streamable HTTP. Clients POST JSON-RPC requests to a
single endpoint. In 2026-07-28, requests carry an
MCP-Protocol-Version header that must match the
_meta version, plus required Mcp-Method and
Mcp-Name headers so infrastructure can route and filter
without parsing bodies [8]. A broken
response stream loses the in-flight request and the client re-issues it
with a new ID; resumability was removed [2]. Server-to-client change notifications use a single
opt-in subscriptions/listen stream [2].
Local servers using stdio typically serve one client; remote servers using Streamable HTTP typically serve many [9].
Server primitives
| Primitive | Control model | Discovery and use | Security note |
|---|---|---|---|
| Tools | Model-controlled [10] | tools/list, tools/call |
“Arbitrary code execution”; consent required before invocation [4] |
| Resources | Application-driven [11] | resources/list, resources/read,
templates |
Data enters model context; may carry injected instructions |
| Prompts | User-controlled [12] | prompts/list, prompts/get |
Server-authored text the user selects |
Clients can offer elicitation, now delivered through Multi Round-Trip Requests, so a server can ask the user for input or confirmation mid-call [4][9].
Tool definitions carry a name, optional
title and description, an
inputSchema (any JSON Schema 2020-12 keywords are now
allowed), an optional outputSchema, and optional
annotations [10]. Three
rules from the tools specification matter for security:
- Clients must treat tool annotations (such as
readOnlyHintordestructiveHint) as untrusted unless they come from trusted servers [10]. An annotation is a claim by the server, not a guarantee. - There should always be a human in the loop able to deny tool invocations, with clear indicators when tools are invoked and confirmation prompts for operations [10].
- The tool list may vary by the authorisation presented on a request, for example returning only tools the caller’s granted scopes permit, but must not vary per connection [10]. That lets servers implement least privilege at discovery time.
Hosts connecting to several servers should disambiguate tool names
(for example by prefixing with a server identifier), because two servers
may both expose search, and serverInfo.name is
not guaranteed unique [10].
On the wire
Here is a real exchange with the example server below, captured over stdio. The client asks for discovery, then calls a tool. Each request is one line on the server’s stdin:
{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"hand-typed","version":"0.1"},"io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"lookup_policy","arguments":{"section":"client-data"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"hand-typed","version":"0.1"},"io.modelcontextprotocol/clientCapabilities":{}}}}The server’s responses on stdout (reformatted):
{"jsonrpc": "2.0", "id": 1, "result": {
"resultType": "complete",
"supportedVersions": ["2026-07-28"],
"capabilities": {"tools": {"listChanged": true}, "resources": {"listChanged": true, "subscribe": true},
"prompts": {"listChanged": true}},
"instructions": "Read-only lookup of the team's agent use policy.",
"ttlMs": 0, "cacheScope": "private",
"_meta": {"io.modelcontextprotocol/serverInfo": {"name": "policy-lookup", "version": "0.1.0"}}}}
{"jsonrpc": "2.0", "id": 2, "result": {
"resultType": "complete",
"content": [{"type": "text", "text": "Do not paste client personal information into agents that are not on the approved list."}],
"structuredContent": {"result": "Do not paste client personal information into agents that are not on the approved list."},
"isError": false,
"_meta": {"io.modelcontextprotocol/serverInfo": {"name": "policy-lookup", "version": "0.1.0"}}}}Note resultType, the per-result serverInfo,
and the caching hints (ttlMs, cacheScope) that
2026-07-28 introduced [2].
Authorisation for remote servers
Authorisation is optional in MCP. HTTP-based implementations should follow the authorisation specification; stdio implementations should not, and instead take credentials from the environment [13]. The HTTP flow is a selected subset of OAuth 2.1 and related standards [13]:
- The MCP server is an OAuth resource server and
must publish OAuth 2.0 Protected Resource Metadata (RFC
9728), which tells clients which authorisation server to use [13][14]. An unauthenticated request receives
401with aWWW-Authenticateheader pointing at that metadata, optionally with ascopehint [13]. - Clients use Resource Indicators (RFC 8707) so the token is issued for this specific server, and servers must validate that tokens were issued for them as audience [13][15].
- Tokens go in the
Authorization: Bearerheader on every request and must not appear in query strings [13]. - Token passthrough is forbidden: a server must not accept tokens issued for other resources, and must not forward the client’s token to downstream APIs [13][16]. If the server needs to call an upstream API, it obtains its own token for that API.
- Clients key stored credentials by issuer and must not reuse them
with a different authorisation server; authorisation servers should send
the
issparameter (RFC 9207) and clients must validate it, which mitigates mix-up attacks [2]. - Scope design should be progressive: a minimal initial scope, step-up
via
WWW-Authenticatescope challenges when a privileged operation is first attempted, and logged elevation events [16].
The MCP security best practices document covers the attacks this design addresses, including confused deputy problems in OAuth proxies, token passthrough, SSRF during metadata discovery, local server compromise and localhost redirect impersonation [16].
Threat model for a first deployment
Academic analysis of the ecosystem defines a four-phase server life cycle (creation, deployment, operation, maintenance) and a taxonomy of 16 threat scenarios across four attacker types: malicious developers, external attackers, malicious users and security flaws [17]. Radosevich and Halloran demonstrated that industry-leading LLMs could be coerced through MCP tools into malicious code execution, remote access control and credential theft on a developer’s machine [18]. Invariant Labs showed tool poisoning: instructions hidden in tool descriptions that the model reads and the user does not [19].
For a small team, the practical threat model reduces to four questions:
- Who wrote this server, and has it changed? Pin versions; review tool definitions on every update; hash them and alert on change.
- What can it reach? A local stdio server runs with your user’s privileges. The MCP project’s local server security guidance recommends isolating servers (containers or sandboxes), isolating credentials, limiting filesystem access and controlling network egress [20].
- What enters the model’s context through it? Every tool result and resource is untrusted input that may contain instructions [21].
- What can the model do with it? Combine read access to private data, untrusted content and an external send channel, and you have the conditions for exfiltration [22].
A minimal, safe, runnable example
The server below exposes one read-only tool and one resource from an in-memory dictionary. It makes no network requests, does not read application files and holds no secrets. It runs with the permissions of the Python process. It demonstrates four habits: logging to stderr, constrained input schemas, honest annotations, and server-side validation that does not trust the schema alone.
Tested on 13 November 2026 with Python 3.13.5 and mcp
2.3.0, negotiating protocol revision 2026-07-28, and with the MCP
Inspector CLI [24].
Setup
mkdir mcp-first && cd mcp-first
python3 -m venv .venv && . .venv/bin/activate
pip install "mcp==2.3.0"policy_server.py
"""A minimal, read-only MCP server for learning purposes.
It exposes one tool and one resource backed by an in-memory dictionary.
It has no network access, no filesystem access and no secrets.
Tested with the official Python SDK, mcp==2.3.0 (protocol revision 2026-07-28).
"""
import logging
import sys
from typing import Literal
from mcp.server import MCPServer
from mcp.types import ToolAnnotations
# stdio servers must never write to stdout: stdout carries the JSON-RPC messages.
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
log = logging.getLogger("policy-server")
POLICY = {
"approved-tools": "Staff may use agents listed in the AI register. Anything else needs sign-off.",
"client-data": "Do not paste client personal information into agents that are not on the approved list.",
"incidents": "If an agent does something outside its brief, pause it, revoke its access, then tell the policy owner.",
}
mcp = MCPServer("policy-lookup", version="0.1.0", instructions="Read-only lookup of the team's agent use policy.")
@mcp.tool(
title="Look up a policy section",
annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False, openWorldHint=False),
)
def lookup_policy(section: Literal["approved-tools", "client-data", "incidents"]) -> str:
"""Return the text of one section of the agent use policy.
Args:
section: One of: approved-tools, client-data, incidents
"""
log.info("lookup_policy called for section=%r", section)
# The schema already restricts input to known sections; check again anyway.
if section not in POLICY:
raise ValueError(f"Unknown section. Valid sections: {', '.join(sorted(POLICY))}")
return POLICY[section]
@mcp.resource("policy://sections", mime_type="text/plain")
def list_sections() -> str:
"""The list of available policy sections."""
return "\n".join(sorted(POLICY))
if __name__ == "__main__":
mcp.run(transport="stdio")client.py
"""Launch policy_server.py over stdio, discover it, list its tools and call one."""
import asyncio
import sys
from mcp import Client, StdioServerParameters
async def main() -> None:
server = StdioServerParameters(command=sys.executable, args=["policy_server.py"])
async with Client(server) as client:
print("Negotiated protocol version:", client.protocol_version)
print("Server:", client.server_info)
tools = await client.list_tools()
for tool in tools.tools:
print("Tool:", tool.name, "|", tool.annotations)
result = await client.call_tool("lookup_policy", {"section": "incidents"})
print("Result:", result.content[0].text)
sections = await client.read_resource("policy://sections")
print("Resource:", sections.contents[0].text.replace("\n", ", "))
asyncio.run(main())Run it
python client.pyOutput:
Negotiated protocol version: 2026-07-28
Server: name='policy-lookup' title=None version='0.1.0' description=None website_url=None icons=None
Tool: lookup_policy | title=None read_only_hint=True destructive_hint=False idempotent_hint=None open_world_hint=False
Result: If an agent does something outside its brief, pause it, revoke its access, then tell the policy owner.
Resource: approved-tools, client-data, incidents
The Literal type produces an enum in the
tool’s inputSchema, so a host can show valid choices and
the SDK rejects anything else before your function runs. Calling the
tool with "section": "passwords" returns a result with
isError: true and a validation message rather than crashing
the server. Keep the explicit check in the function anyway: schemas are
enforced by the SDK you happen to use today, and defence in depth costs
one line.
Inspect it
The MCP Inspector is the project’s debugging client; it needs Node
22.19 or newer and runs through npx [23]:
npx @modelcontextprotocol/inspector --cli python policy_server.py --method tools/listThis prints the tool definition as a client sees it, including the
enum, the generated outputSchema and the
annotations. Run the command without --cli for the browser
interface.
Connect it to a host
Desktop hosts typically launch local servers from a JSON configuration with a command and arguments. The MCP quickstart shows this shape for Claude for Desktop [7]:
{
"mcpServers": {
"policy-lookup": {
"command": "/ABSOLUTE/PATH/TO/mcp-first/.venv/bin/python",
"args": ["/ABSOLUTE/PATH/TO/mcp-first/policy_server.py"]
}
}
}Other hosts use similar configuration; check your host’s documentation for its file location and whether it supports per-tool permissions.
Extending it safely
Before adding a tool that writes, sends or reaches the network:
- Give it a separate, narrowly named tool rather than a mode flag on an existing one, so hosts can permit or deny it independently.
- Mark it honestly (
destructiveHint=True,openWorldHint=True), remembering that clients treat annotations as untrusted hints, not as enforcement. - If it needs credentials on stdio, read them from the environment the host provides, scoped to this server, never from tool arguments [13].
- If it fetches URLs, validate destinations against an allowlist to avoid SSRF [16].
- Return only what the model needs. Never return secrets in tool results; anything returned enters the model’s context and the host’s logs.
Checklists
Server authors
Host and deployment owners
Key takeaways
MCP is JSON-RPC between a host’s per-server clients and servers that
expose tools, resources and prompts, and the 2026-07-28 revision made it
stateless: no initialise handshake, per-request _meta,
mandatory server/discover, and multi round-trip requests in
place of server-initiated calls. The protocol leaves security
enforcement to implementations, so hosts must handle consent, isolation
between servers and confirmation of tool calls, and must treat tool
descriptions, annotations and results from untrusted servers as
untrusted input. Remote servers use a subset of OAuth 2.1 with protected
resource metadata, resource indicators, audience validation and a strict
ban on token passthrough, while stdio servers take credentials from the
environment. Start with narrow, read-only tools, constrained schemas and
stderr logging, pin and hash what you install, and add write
capabilities as separate tools behind human approval.
primitive’s pass listing says its local MCP workflows use an optional desktop companion; nothing in this lesson depends on it.
Sources and further reading
- Model Context Protocol. (2026). Versioning (Specification). https://modelcontextprotocol.io/specification/versioning
- Model Context Protocol. (2026). Key Changes (Specification, revision 2026-07-28). https://modelcontextprotocol.io/specification/2026-07-28/changelog
- Model Context Protocol. (2026). SDKs (documentation for protocol revision 2026-07-28). https://modelcontextprotocol.io/docs/2026-07-28/sdk
- Model Context Protocol. (2026). Specification, revision 2026-07-28. https://modelcontextprotocol.io/specification/2026-07-28
- Model Context Protocol. (2026). Architecture (Specification, revision 2026-07-28). https://modelcontextprotocol.io/specification/2026-07-28/architecture
- Model Context Protocol. (2026). stdio (Specification, revision 2026-07-28, transports). https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio
- Model Context Protocol. (2026). Build an MCP server (documentation for protocol revision 2026-07-28). https://modelcontextprotocol.io/docs/2026-07-28/develop/build-server
- Model Context Protocol. (2026). Streamable HTTP (Specification, revision 2026-07-28, transports). https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http
- Model Context Protocol. (2026). Architecture overview (documentation for protocol revision 2026-07-28). https://modelcontextprotocol.io/docs/2026-07-28/learn/architecture
- Model Context Protocol. (2026). Tools (Specification, revision 2026-07-28). https://modelcontextprotocol.io/specification/2026-07-28/server/tools
- Model Context Protocol. (2026). Resources (Specification, revision 2026-07-28). https://modelcontextprotocol.io/specification/2026-07-28/server/resources
- Model Context Protocol. (2026). Prompts (Specification, revision 2026-07-28). https://modelcontextprotocol.io/specification/2026-07-28/server/prompts
- Model Context Protocol. (2026). Authorization (Specification, revision 2026-07-28). https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization
- Jones, M. B., Hunt, P., & Parecki, A. (2025). OAuth 2.0 Protected Resource Metadata (RFC 9728). IETF. https://www.rfc-editor.org/rfc/rfc9728
- Campbell, B., Bradley, J., & Tschofenig, H. (2020). Resource Indicators for OAuth 2.0 (RFC 8707). IETF. https://www.rfc-editor.org/rfc/rfc8707
- Model Context Protocol. (2026). Security Best Practices (documentation for protocol revision 2026-07-28). https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices
- Hou, X., Zhao, Y., Wang, S., & Wang, H. (2025). Model Context Protocol (MCP): Landscape, Security Threats, and Future Research Directions. arXiv preprint arXiv:2503.23278. https://arxiv.org/abs/2503.23278
- Radosevich, B., & Halloran, J. (2025). MCP Safety Audit: LLMs with the Model Context Protocol Allow Major Security Exploits. arXiv preprint arXiv:2504.03767. https://arxiv.org/abs/2504.03767
- Invariant Labs. (2025, 1 April). MCP Security Notification: Tool Poisoning Attacks. Invariant Labs blog. https://invariantlabs.ai/blog/mcp-security-notification-tool-poisoning-attacks
- Model Context Protocol. (2026). Local Server Security (documentation for protocol revision 2026-07-28). https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/local-server-security
- Greshake, K., Abdelnabi, S., Mishra, S., Endres, C., Holz, T., & Fritz, M. (2023). Not what you’ve signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection. Proceedings of the 16th ACM Workshop on Artificial Intelligence and Security (AISec ’23), 79–90. https://doi.org/10.1145/3605764.3623985 (preprint: https://arxiv.org/abs/2302.12173)
- Willison, S. (2025, 16 June). The lethal trifecta for AI agents: private data, untrusted content, and external communication. Simon Willison’s Weblog. https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/
- Model Context Protocol. (2026). MCP Inspector (documentation for protocol revision 2026-07-28). https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector
- Model Context Protocol. (2026). Python SDK (GitHub repository). https://github.com/modelcontextprotocol/python-sdk