🎯 Core Concepts
What MCP is, how hosts, clients and servers fit together, and the three server primitives.
What is MCP?
▼

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
Architecture
▼

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)
Primitives: Tools, Resources, Prompts
▼

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
Rule of thumb: actions = tools, context = resources, workflows = prompts
🔌 Protocol & Transports
The message lifecycle, the two standard transports, and authorization.
Lifecycle & Messages
▼
// 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/list for discovery
  • resources/read, prompts/get to fetch content
  • Notifications (no id) such as notifications/tools/list_changed
Transports
▼

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 stderr
Authorization
▼

Remote 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
🛠️ Building Servers
Minimal Python and TypeScript servers, and how to test them.
Python (FastMCP)
▼
# 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
TypeScript SDK
▼
// 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());
Testing with MCP Inspector
▼
# 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
💻 Using MCP in Clients
Adding servers to Claude Code, Claude Desktop and other hosts.
Claude Code
▼
# 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

Config Files (Claude Desktop, .mcp.json)
▼
{
  "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
Troubleshooting
▼
  • Server not appearing: restart the host after editing config; check JSON syntax
  • Command not found: use absolute paths, or npx -y/uvx so 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
🔒 Security & Best Practices
Designing good tools and defending against prompt injection and tool poisoning.
Tool Design
▼
  • 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
Security Risks
▼

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
Hardening Checklist
▼
  • 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