MCP (Model Context Protocol)#
MCP is an open protocol released by Anthropic in 2024 for connecting LLMs to external tools and data sources. It standardizes how “AI calls tools.”
1. What It Is#
MCP (Model Context Protocol) is an open standard protocol that defines how LLM applications communicate with external services, much like a “USB protocol” for AI.
Core concepts:
| Concept | Description |
|---|---|
| Host | The LLM application that initiates requests (e.g. Claude Desktop, Cursor) |
| Client | The MCP client inside the Host; manages connections to Servers |
| Server | The service that provides tools/resources (e.g. file system, database, API) |
Three capabilities:
| Capability | Description | Examples |
|---|---|---|
| Tools | Functions the LLM can call | Run SQL, send email, call an API |
| Resources | Data the LLM can read | File contents, database records |
| Prompts | Predefined prompt templates | Code review template, summary template |
Architecture:
graph LR
A[LLM Host] --> B[MCP Client]
B <-->|JSON-RPC| C[MCP Server 1: File System]
B <-->|JSON-RPC| D[MCP Server 2: Database]
B <-->|JSON-RPC| E[MCP Server 3: Web API]
Why MCP:
- Unified standard: different tools share one protocol, so no per-LLM adapters are needed
- Security isolation: Servers run in separate processes with controllable permissions
- Ecosystem reuse: implement once, use everywhere (Claude, Cursor, custom apps)
2. Using Existing MCP Servers#
Configuring in Claude Desktop#
Edit the config file (macOS: ~/Library/Application Support/Claude/claude_desktop_config.json, Windows: %APPDATA%\Claude\claude_desktop_config.json):
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"]
},
"sqlite": {
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/path/to/database.db"]
}
}
}
Configuring in Cursor#
Edit .cursor/mcp.json (project-level) or the global config:
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "your_token"
}
}
}
}
Common Official MCP Servers#
| Server | Install Command | Function |
|---|---|---|
| filesystem | npx @modelcontextprotocol/server-filesystem | Read/write local files |
| github | npx @modelcontextprotocol/server-github | GitHub repository operations |
| sqlite | uvx mcp-server-sqlite | SQLite database queries |
| postgres | npx @modelcontextprotocol/server-postgres | PostgreSQL queries |
| puppeteer | npx @modelcontextprotocol/server-puppeteer | Browser automation |
| slack | npx @modelcontextprotocol/server-slack | Read/write Slack messages |
Community MCP Servers#
Find more in the MCP Registry or at mcp.so:
- mcp-server-fetch: HTTP requests
- mcp-server-memory: persistent memory
- mcp-server-notion: Notion integration
- mcp-server-brave-search: Brave Search
3. Building Your Own MCP Server#
Python Implementation (Recommended)#
Install the SDK:
pip install mcp
Minimal example (a weather lookup tool):
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
# Create the server
server = Server("weather-server")
# Define the tool list
@server.list_tools()
async def list_tools():
return [
Tool(
name="get_weather",
description="Get the weather for a given city",
inputSchema={
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"]
}
)
]
# Implement the tool logic
@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "get_weather":
city = arguments["city"]
# A real implementation would call a weather API; this returns mock data
return [TextContent(type="text", text=f"{city}: Sunny, 25°C")]
raise ValueError(f"Unknown tool: {name}")
# Start the server
async def main():
async with stdio_server() as (read, write):
await server.run(read, write, server.create_initialization_options())
if __name__ == "__main__":
import asyncio
asyncio.run(main())
TypeScript Implementation#
Install the SDK:
npm install @modelcontextprotocol/sdk
Example:
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new Server(
{ name: "weather-server", version: "1.0.0" },
{ capabilities: { tools: {} } }
);
// List tools
server.setRequestHandler("tools/list", async () => ({
tools: [{
name: "get_weather",
description: "Get the weather for a given city",
inputSchema: {
type: "object",
properties: { city: { type: "string" } },
required: ["city"]
}
}]
}));
// Call a tool
server.setRequestHandler("tools/call", async (request) => {
const { name, arguments: args } = request.params;
if (name === "get_weather") {
return { content: [{ type: "text", text: `${args.city}: Sunny, 25°C` }] };
}
throw new Error(`Unknown tool: ${name}`);
});
// Start
const transport = new StdioServerTransport();
server.connect(transport);
Registering with a Client#
Add your server to the config:
{
"mcpServers": {
"my-weather": {
"command": "python",
"args": ["/path/to/weather_server.py"]
}
}
}
Implementing Resources (Optional)#
from mcp.types import Resource
@server.list_resources()
async def list_resources():
return [
Resource(
uri="file:///config/settings.json",
name="Config file",
mimeType="application/json"
)
]
@server.read_resource()
async def read_resource(uri: str):
if uri == "file:///config/settings.json":
return '{"theme": "dark", "language": "zh"}'
raise ValueError(f"Unknown resource: {uri}")
Debugging Tips#
# Debug with MCP Inspector
npx @modelcontextprotocol/inspector python weather_server.py
# View Claude Desktop logs
tail -f ~/Library/Logs/Claude/mcp*.log
Further Reading#
- Transports: stdio (local process), HTTP+SSE (remote service)
- Security considerations: Servers should restrict file access paths, validate input, and keep logs
- Official docs: modelcontextprotocol.io