The Model Context Protocol is an open standard for connecting AI applications to external tools, data sources and workflows. Think of it as a universal adapter: build a server once and any MCP-capable client can use it.
- Replaces custom one-off integrations (the N x M problem) with one protocol
- Built on JSON-RPC 2.0 messages
- Stateful connections with capability negotiation
- Official SDKs for Python, TypeScript, Java, Kotlin, C#, Go and more
Host: the AI application the user interacts with (Claude Desktop, Claude Code, an IDE)
Client: connector inside the host; one client per server connection
Server: program exposing tools, resources and prompts
┌──────────────── Host (AI app) ────────────────┐
│ LLM <-> Client A ──────────► Server A (files)
│ Client B ──────────► Server B (GitHub)
│ Client C ──────────► Server C (database)
└─────────────────────────────────────────────────┘
Messages: JSON-RPC 2.0 over a transport (stdio / HTTP)
Tools: functions the model can call (side effects allowed); model-controlled
Resources: read-only data addressed by URI (files, records); application-controlled
Prompts: reusable templates the user can invoke (slash commands); user-controlled
Client features (server asks the client):
- Sampling: ask the host LLM for a completion
- Roots: which directories the server may access
- Elicitation: ask the user for more input
// 1. Initialize: negotiate version + capabilities
-> {"jsonrpc":"2.0","id":1,"method":"initialize",
"params":{"protocolVersion":"...","capabilities":{},"clientInfo":{...}}}
<- {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"tools":{}},...}}
-> {"jsonrpc":"2.0","method":"notifications/initialized"}
// 2. Discover and use
-> {"jsonrpc":"2.0","id":2,"method":"tools/list"}
-> {"jsonrpc":"2.0","id":3,"method":"tools/call",
"params":{"name":"get_weather","arguments":{"city":"Paris"}}}
tools/list,resources/list,prompts/listfor discoveryresources/read,prompts/getto fetch content- Notifications (no id) such as
notifications/tools/list_changed
stdio: client launches the server as a subprocess and talks over stdin/stdout; best for local tools
Streamable HTTP: single HTTP endpoint (POST, optional SSE streaming); best for remote, multi-client servers
SSE (legacy): older HTTP+SSE transport, superseded by Streamable HTTP
stdio servers must never print logs to stdout; use stderrRemote HTTP servers use OAuth 2.1: the server is an OAuth resource server, the client obtains a bearer token from an authorization server, and requests carry Authorization: Bearer <token>.
- stdio servers typically take credentials from environment variables instead
- Use least-privilege scopes and short-lived tokens
- Never pass tokens through to downstream APIs on behalf of other users without validation
# pip install "mcp[cli]"
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("demo")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers.""" # docstring becomes the tool description
return a + b
@mcp.resource("greeting://{name}")
def greeting(name: str) -> str:
"""Personalized greeting."""
return f"Hello, {name}!"
@mcp.prompt()
def review(code: str) -> str:
return f"Please review this code:\n\n{code}"
if __name__ == "__main__":
mcp.run() # stdio by default
# mcp.run(transport="streamable-http")
Type hints generate the JSON input schema automatically
// npm i @modelcontextprotocol/sdk zod
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({ name: "demo", version: "1.0.0" });
server.registerTool(
"add",
{
title: "Add",
description: "Add two numbers",
inputSchema: { a: z.number(), b: z.number() },
},
async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }],
})
);
await server.connect(new StdioServerTransport());
# Interactive UI to list and call tools/resources/prompts
npx @modelcontextprotocol/inspector python server.py
npx @modelcontextprotocol/inspector node build/index.js
# Python SDK shortcut
mcp dev server.py
- Check the tool list and input schemas first
- Call each tool with valid and invalid inputs
- Watch stderr for logs and errors
# Remote server (Streamable HTTP)
claude mcp add --transport http notion https://mcp.notion.com/mcp
# Local stdio server (everything after -- is the command)
claude mcp add my-server -- npx -y @acme/mcp-server
# With env vars and scope
claude mcp add db --env DB_URL=postgres://... --scope project -- node db-server.js
claude mcp list
claude mcp get my-server
claude mcp remove my-server
# Inside a session: /mcp (status, auth)
local: only you, this project (default)
project: shared via .mcp.json in the repo
user: all your projects
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "<token>" }
}
}
}
Never commit real tokens; reference environment variables instead
- Server not appearing: restart the host after editing config; check JSON syntax
- Command not found: use absolute paths, or
npx -y/uvxso dependencies resolve - Garbled protocol errors: something is printing to stdout in a stdio server
- Too many tools: large tool lists consume context; enable only the servers you need
- Auth loops on remote servers: re-authenticate via
/mcp
- Few, well-named tools beat many overlapping ones
- Write descriptions for the model: when to use it, inputs, side effects
- Return concise, structured results; paginate large output
- Make errors actionable (say what to change), not stack traces
- Mark destructive tools clearly; consider a dry-run parameter
- Use JSON Schema constraints (enum, min/max) to prevent bad inputs
Prompt injection: untrusted content returned by a tool (web page, email, issue) contains instructions the model may follow
Tool poisoning: malicious instructions hidden in a tool description or metadata
Rug pull: a server changes tool definitions after you approved it
Confused deputy: a server acts with broader privileges than the requesting user
Command injection: unsanitized arguments passed to shells or SQL
Treat every tool result as untrusted input- Only install servers you trust; pin versions and review source
- Least privilege: read-only credentials, narrow filesystem roots
- Require human approval for write/delete/network-egress actions
- Validate and sanitize all tool arguments server-side
- Log tool calls for audit; rate-limit expensive operations
- Separate servers that read untrusted data from servers that can act on sensitive systems