MCP: Model Context Protocol
Scope. This lesson teaches the protocol and agent architecture, the three primitives (Tools/Resources/Prompts), the JSON-RPC handshake, transports, and how to build an MCP server that any agent can consume. For the Claude Code CLI workflow, how to register MCP servers in.claude/settings.json, the/mcpslash command,alwaysLoad, auth patterns, and per-server recipes, see MCP: External Connections (in Claude Code).
After this lesson, you will be able to:
- Explain why MCP became the industry standard for connecting LLMs to tools, data, and prompts, Anthropic's open protocol replacing fragmented per-vendor tool APIs
- Distinguish MCP's three primitives (Tools, Resources, Prompts) and when each is the right abstraction for your integration
- Write a basic MCP server in Python or TypeScript that exposes a custom tool to any MCP-compatible client (Claude, ChatGPT, Cursor, VS Code)
- Pick the right MCP transport (stdio for local, HTTP/SSE for remote) and integrate the official MCP SDK into your agent stack
Before you start
#What Problem Does MCP Solve?
#Architecture: Host, Client, Server
MCP has three architectural roles. Conflating them is the #1 source of confusion when you start writing your first server.
| Role | What it is | Examples |
|---|---|---|
| Host | The application the user actually interacts with. Embeds an LLM and one or more MCP clients. | Claude Desktop, Cursor, VS Code Copilot, Zed, a custom LangChain app. |
| Client | A library inside the host that speaks the MCP protocol on behalf of one server. The host typically runs one client per connected server. | The mcp Python SDK's ClientSession; the TS SDK's Client class. |
| Server | The thing that exposes Tools / Resources / Prompts. Owned by whoever built the integration (GitHub, Postgres, your team). | mcp-server-github, mcp-server-postgres, your sqlite_mcp.py. |
The host:client:server fan-out is 1:N:N, one host instantiates N clients to talk to N servers. Each client is paired with exactly one server. The host arbitrates which tools from which servers get exposed to the LLM, and routes the LLM's tool calls back to the right client.
A useful mental model: the host is the OS, the client is the device driver, and the server is the peripheral. The host doesn't know how a printer works; the printer driver does. Same here, the host doesn't know how to query Postgres; the Postgres MCP server does, and the matching client in the host translates protocol messages.
+-------------------+ +------------+ +------------------+
| Host | === | Client A | <==> | MCP Server A |
| (Claude Desktop | +------------+ | (filesystem) |
| or Cursor) | +------------+ +------------------+
| | === | Client B | <==> | MCP Server B |
| embeds 1 LLM | +------------+ | (github) |
| + N clients | +------------+ +------------------+
| | === | Client C | <==> | MCP Server C |
+-------------------+ +------------+ | (your custom DB) |
+------------------+
#The Three Primitives
query_users, send_slack_message, run_terminal_command. Pattern: model-initiated action.file:///path/to/doc.md, postgres://table/users, or github://repo/owner/branch. Resources are typically attached to a conversation by the user (drag-and-drop, file picker, slash command) rather than fetched autonomously by the model, though servers can implement either pattern. Pattern: data made available to context./summarize_pr {pr_number}) and expand into a full templated message that's sent to the LLM. Pattern: user-initiated workflow.The cleanest mental separation:
| Primitive | Who triggers it | Typical UI surface |
|---|---|---|
| Tool | The model, mid-conversation | (invisible), tool calls appear inline |
| Resource | The user (attach), then model reads | File picker, "@" mention |
| Prompt | The user explicitly | Slash command, menu item |
You're building an MCP server for your company's analytics warehouse. The LLM should be able to run SQL queries autonomously, but you also want users to drag in a saved dashboard's data as context. How do you expose these?
#Capability Negotiation: The Initialize Handshake
capabilities object during the initialize step. This is how each side declares what it supports, and equally important, what it does NOT support. The handshake prevents protocol-version drift between clients and servers that may have shipped months apart. The protocolVersion string in the examples below, 2024-11-05, is the first spec revision; newer dated revisions exist, so use the version your SDK reports.Client -> Server: {
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": { "listChanged": true },
"sampling": {}
},
"clientInfo": { "name": "claude-desktop", "version": "0.7.1" }
}
}
Server -> Client: {
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {
"tools": { "listChanged": true },
"resources": { "subscribe": true, "listChanged": true },
"prompts": { "listChanged": false },
"logging": {}
},
"serverInfo": { "name": "sqlite-server", "version": "1.0.0" }
}
}
tools.listChanged: true means the server can push notifications when its tool list changes (e.g., a tool was just enabled by an admin). resources.subscribe: true means clients can subscribe to live updates of a resource. If a side doesn't advertise the capability, the other side must not invoke the corresponding operation, the JSON-RPC call will return a "method not supported" error.The protocol version field is exact-match in spirit but spec-defined for graceful negotiation: if client and server disagree, the lowest mutually-supported version wins, and unsupported methods simply error. This is what keeps the ecosystem from fragmenting.
#Security Model: Sandbox + Permissions
Three practical layers in 2026:
- Process isolation. stdio servers run as separate subprocesses launched by the host. The host can restrict the subprocess's working directory, environment variables, and (on Linux) seccomp/landlock policies. The filesystem server, for instance, ships with an allowlist of paths it will read or write.
- Per-tool permission prompts. Claude Desktop, Cursor, and VS Code intercept the model's tool calls and pop a UI confirmation for any "write" or "irreversible" action the first time it appears in a session ("Allow this server to write to
~/Documents/notes.md?"). The host caches the user's decision per server + tool + scope. - OAuth for remote servers. HTTP+SSE servers exposing SaaS data (Linear, Stripe, Notion) require an OAuth flow per user. The token lives in the host's secure storage. The server's authorization scope determines which tools the LLM can actually invoke, even if the protocol advertises
delete_account, the user's token may only haveread:issues.
A user installs an MCP server that exposes a `delete_file` tool. The LLM (without any user intent) decides to call it on `~/Documents/important.md`. What SHOULD happen?
#Writing an MCP Server (Python)
mcp package and runs as its own process that a host such as Claude Desktop launches, so it does not run on this page. Copy it to your own machine (or Google Colab to read it with syntax highlighting).# Run on your own machine: needs `pip install mcp` and runs as a server process, so it cannot run on this page.
# Minimal MCP server in Python, exposes one SQL query tool
# Run: pip install mcp
# Then: python sqlite_mcp.py (stdio transport, runs as subprocess of MCP client)
import sqlite3
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
app = Server("sqlite-server")
# In-memory demo database
conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, role TEXT);
INSERT INTO users (name, role) VALUES ('Alice', 'engineer'), ('Bob', 'designer'), ('Carol', 'PM');
""")
# --- Tool: list_users ---
@app.list_tools()
async def list_tools() -> list[Tool]:
return [
Tool(
name="query_users",
description="Run a SELECT query against the users table. Returns matching rows as JSON.",
inputSchema={
"type": "object",
"properties": {
"where": {
"type": "string",
"description": "Optional SQL WHERE clause without the 'WHERE' keyword (e.g., \"role = 'engineer'\"). Empty string returns all rows.",
}
},
"required": ["where"],
},
),
]
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
if name != "query_users":
return [TextContent(type="text", text=f"Unknown tool: {name}")]
where = arguments.get("where", "").strip()
sql = "SELECT * FROM users"
if where:
sql += f" WHERE {where}"
cur = conn.execute(sql)
rows = [{"id": r[0], "name": r[1], "role": r[2]} for r in cur.fetchall()]
import json
return [TextContent(type="text", text=json.dumps(rows, indent=2))]
# --- Run via stdio (Claude Desktop / VS Code launch this as subprocess) ---
async def main():
async with stdio_server() as (read, write):
await app.run(read, write, app.create_initialization_options())
if __name__ == "__main__":
import asyncio
asyncio.run(main())
print("Connect this server to Claude Desktop:")
print(" ~/Library/Application\\ Support/Claude/claude_desktop_config.json")
print("Add:")
print("""
{
"mcpServers": {
"sqlite-demo": {
"command": "python",
"args": ["/full/path/to/sqlite_mcp.py"]
}
}
}
""")
print("Then restart Claude Desktop. Type a query like:")
print('"List all users with role engineer." Claude calls query_users automatically.')query_orders tool that joins against a made-up orders table. Add an MCP Resource at sqlite://schema that returns the database schema. Add an MCP Prompt called analyze_users that takes role as an argument and returns a templated analysis prompt. Then check that tools/list returns query_users and that tools/call with where="role = 'engineer'" returns Alice.#Local vs Remote Transports
| Transport | Use case | Setup |
|---|---|---|
| stdio | Local servers (file system, code, local DB) | Subprocess launched by MCP client |
| HTTP + SSE | Remote/cloud services (GitHub, Slack, Stripe) | Standalone HTTP server, OAuth-protected |
Most early MCP servers use stdio for simplicity. Remote SaaS-grade MCP servers (Stripe, Linear, Notion) use HTTP+SSE with OAuth.
Concretely, the two transports map to two operational models:
| Concern | stdio | HTTP + SSE |
|---|---|---|
| Process model | One subprocess per host launch; dies when host exits | Long-running HTTP service; survives host restarts |
| Auth | None at protocol level, relies on local filesystem trust | OAuth 2.1 with PKCE for first-party; bearer token for service-to-service |
| Latency overhead | ~1ms (pipe round-trip) | 5-50ms (HTTP round-trip + TLS) |
| Multi-tenant | No, one user per process | Yes, single deployment serves many users |
| Best fit | filesystem, sqlite, local git, terminal | GitHub, Linear, Stripe, internal SaaS |
The split is sharp in practice: if the server needs to read the user's local files, stdio is the only sane choice (you can't HTTP into a laptop). If the server is a hosted SaaS, HTTP+SSE with OAuth is the only sane choice. There's no real middle ground.
#Parse a Minimal MCP Server Descriptor
tools/list, the server replies with a JSON array of tool descriptors. Each descriptor follows a strict shape, name, description, and a JSON Schema for arguments. Let's parse one in Python and validate it, exactly the way a client SDK would internally.mcp SDK has more validation (full JSON Schema, async transport, error mapping), but the protocol-level operations are exactly: parse the tool list, validate arguments, dispatch by name. Try adding a new tool to TOOLS_LIST_RESPONSE and confirming the dispatcher rejects unknown names, that's the same defense-in-depth a real client uses.#The Ecosystem (2026)
| Category | Examples |
|---|---|
| Hosts (MCP clients), as of October 2026, verify | Claude Desktop, ChatGPT Desktop, Cursor, VS Code GitHub Copilot, JetBrains AI, Continue.dev, Zed |
| Official servers, as of October 2026, verify | GitHub, GitLab, Slack, Notion, Linear, Stripe, Postgres, SQLite, Filesystem, Brave Search |
| SDKs | Python (mcp), TypeScript (@modelcontextprotocol/sdk), Rust (mcp-rs), Go (mcp-go) |
| Marketplaces | mcp.so, MCPHub, Smithery, discover and install community servers |
#Decision Rubric
You want to expose a custom 'query_company_wiki' tool to Claude AND Cursor AND your custom LangChain agent. Best approach?
The answer: one MCP server, three hosts. You write the tool logic once. Each host (Claude Desktop, Cursor, your LangChain agent via the MCP client SDK) connects to the same MCP server. Any LLM the host runs (Claude / GPT-4 / Gemini) can use it through the client's translation layer.
| Use MCP when | Stay with native tool API when |
|---|---|
| You're integrating multi-host or multi-LLM | Single-LLM single-host (just use OpenAI tools or Anthropic tools natively) |
| You want to ship a tool for community use | Internal one-off automation |
| You're building an SDK or platform | Throwaway scripts |
#Key Takeaways
- MCP is the open protocol for LLM-tool integration. JSON-RPC over stdio or HTTP+SSE, three primitives (Tools/Resources/Prompts)
- Write tools once, run anywhere. Claude, ChatGPT, Cursor, VS Code, custom agents all consume the same MCP server
- Three primitives map to three integration patterns. Tools (functions), Resources (data on-demand), Prompts (templated user actions)
- Local servers use stdio, remote SaaS servers use HTTP + SSE with OAuth
- The ecosystem has grown quickly: official servers from several vendors, marketplaces, multi-language SDKs
#Quick Check
What's the main reason MCP exists?