MCP (Model Context Protocol): Complete Guide
Master MCP in Claude Code: add servers with claude mcp add, pick local, project, or user scope, manage context cost and tool search, and troubleshoot failures.
Updated October 21, 2026: Refreshed for Claude Code 2.1.305: corrected MCP scopes and config files (
.mcp.jsonand~/.claude.json), replaced retired or nonexistent server packages with current official servers, and documented tool search, managed MCP policy, and the Memory server’s absoluteMEMORY_FILE_PATHrequirement.
MCP (Model Context Protocol) is the open protocol Claude Code uses to connect to external tools, databases, and services, extending what Claude can do. This guide covers everything you need to know to leverage MCP effectively.
What is MCP?
According to the Model Context Protocol documentation, MCP is an open, standardized protocol that allows AI assistants to:
- Access external data sources (databases, APIs, file systems)
- Execute specialized tools (Git, package managers, cloud services)
- Maintain persistent context (memory, knowledge graphs)
- Integrate with development tools (IDEs, CI/CD, project management)
Think of MCP servers as adapters that give Claude new abilities beyond its built-in tools.
MCP Architecture
┌─────────────────────────────────────────────────────────┐
│ Claude Code CLI │
│ ┌─────────────────────────────────────────────────┐ │
│ │ MCP Client │ │
│ │ Manages connections to MCP servers │ │
│ └─────────────────────────────────────────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ MCP Server 1 │ │ MCP Server 2 │ │ MCP Server 3 │ │
│ │ (filesystem) │ │ (memory) │ │ (git) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ Local Files Knowledge Git Repository │
│ Graph │
└─────────────────────────────────────────────────────────┘
Adding MCP Servers
Official CLI Method (Recommended)
From the Claude Code MCP documentation, add servers with the CLI:
# Local stdio server: everything after -- is the server's own command
claude mcp add [--scope <scope>] <name> [-e KEY=value] -- <command> [args...]
# Remote HTTP server (the recommended transport for cloud services)
claude mcp add --transport http [--scope <scope>] <name> <url>
# Scopes:
# --scope local → ~/.claude.json, this project only (default)
# --scope project → .mcp.json in the project root (shared via git)
# --scope user → ~/.claude.json, all your projects
The reference servers below (
@modelcontextprotocol/server-*) published 2.0 releases in October 2026 that declare Node.js 24 or later.
Common MCP Servers
1. Filesystem Access
claude mcp add --scope project filesystem \
-- npx -y @modelcontextprotocol/server-filesystem .
Capabilities:
- Read/write files
- Create directories
- List directory contents
- File search and pattern matching
2. Memory (Knowledge Graph)
# IMPORTANT: Use an absolute MEMORY_FILE_PATH for project isolation
# (run from the project root; the shell expands $PWD)
claude mcp add memory \
-e MEMORY_FILE_PATH="$PWD/.claude/memory.jsonl" \
-- npx -y @modelcontextprotocol/server-memory
Capabilities:
- Persistent knowledge storage
- Entity and relationship tracking
- Cross-session memory
- Keyword search across entity names, types, and observations
⚠️ Critical: Without MEMORY_FILE_PATH, all projects share the same memory! A relative path doesn’t fix that: the server resolves it against its own package directory, not your project, so always pass an absolute path (a leading ~/ also works).
3. Git Operations
# The official Git server is a Python package; run it with uv's uvx
claude mcp add --scope project git \
-- uvx mcp-server-git --repository .
Capabilities:
- Git status, log, diff
- Branch operations
- Commit history
- Staging and commits
4. GitHub Integration
# GitHub's remote MCP server, authenticated with a fine-grained personal access token
claude mcp add --transport http --scope user github \
https://api.githubcopilot.com/mcp/ \
--header "Authorization: Bearer <your-github-pat>"
Capabilities:
- Issues and PRs
- Repository management
- Code search
- Actions workflow
5. Sequential Thinking
claude mcp add --scope user sequential-thinking \
-- npx -y @modelcontextprotocol/server-sequential-thinking
Capabilities:
- Structured reasoning
- Multi-step analysis
- Complex problem decomposition
6. Context7 (Live Documentation)
# Remote server; an API key is optional but recommended for higher rate limits
claude mcp add --transport http --scope user context7 \
https://mcp.context7.com/mcp \
--header "Authorization: Bearer <your-context7-api-key>"
Capabilities:
- Real-time official documentation
- Up-to-date library references
- Framework guidance
Database MCP Servers
PostgreSQL
# DBHub (@bytebase/dbhub) is the example the Claude Code docs use.
# Connect with a read-only database user.
claude mcp add --transport stdio db \
-- npx -y @bytebase/dbhub \
--dsn "postgresql://readonly:pass@localhost:5432/db"
Capabilities:
- SQL execution (
execute_sql) - Schema and table search (
search_objects) - Query plans and health checks (opt-in tools)
- Also connects to MySQL, MariaDB, SQL Server, Oracle, and SQLite
SQLite
claude mcp add sqlite \
-- npx -y @bytebase/dbhub --dsn "sqlite:///path/to/app.db"
MongoDB
# MongoDB's official server; --readOnly blocks create/update/delete tools
claude mcp add mongodb \
-e MDB_MCP_CONNECTION_STRING="mongodb://localhost:27017/db" \
-- npx -y mongodb-mcp-server@latest --readOnly
Cloud Service MCP Servers
AWS
# AWS MCP Server (managed, OAuth sign-in); pick your Region's endpoint
claude mcp add --transport http --scope user aws-mcp \
https://aws-mcp.us-east-1.api.aws/mcp
Cloudflare
# Cloudflare API MCP Server: sign in with OAuth from /mcp,
# or add --header "Authorization: Bearer <api-token>"
claude mcp add --transport http --scope user cloudflare \
https://mcp.cloudflare.com/mcp
Vercel
# Vercel's official remote server; authenticate from /mcp
claude mcp add --transport http --scope user vercel \
https://mcp.vercel.com
For remote servers that use OAuth, run /mcp inside Claude Code (or claude mcp login <name>) to complete the sign-in.
MCP Configuration Files
Project Servers (.mcp.json)
claude mcp add --scope project writes to .mcp.json in the project root. Commit it so the whole team gets the same servers. ${VAR} and ${VAR:-default} are expanded in command, args, env, url, and headers:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
},
"db": {
"command": "npx",
"args": ["-y", "@bytebase/dbhub", "--dsn", "${DATABASE_URL}"]
},
"docs-api": {
"type": "http",
"url": "${API_BASE_URL:-https://api.example.com}/mcp",
"headers": {
"Authorization": "Bearer ${API_KEY}"
}
}
}
}
Claude Code asks before it uses .mcp.json servers in an interactive session. To pre-approve them, set enableAllProjectMcpServers (or list names in enabledMcpjsonServers) in .claude/settings.local.json or ~/.claude/settings.json. The same keys committed to the project’s .claude/settings.json are ignored until you trust the folder.
Local and User Servers (~/.claude.json)
Local-scope (the default) and user-scope servers live in ~/.claude.json, which Claude Code manages for you. Local servers sit under the project’s entry; user servers sit in the top-level mcpServers:
{
"mcpServers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/",
"headers": {
"Authorization": "Bearer <your-github-pat>"
}
},
"sequential-thinking": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-sequential-thinking"]
}
}
}
Prefer claude mcp add / claude mcp remove over hand-editing this file. Don’t put an mcpServers block in settings.json: settings files hold approvals and policy (such as enableAllProjectMcpServers or allowedMcpServers), not your server definitions. The one exception is managedMcpServers, which only organizations set in managed settings.
MCP Scope and Hierarchy
MCP servers come from three scopes, plus organization-managed configuration:
┌─────────────────────────────────────────────┐
│ Organization (managed) │
│ managed-mcp.json or managedMcpServers │
│ allowedMcpServers / deniedMcpServers │
├─────────────────────────────────────────────┤
│ Local scope (default) │
│ ~/.claude.json, this project only │
│ Use: personal or credentialed servers │
├─────────────────────────────────────────────┤
│ Project scope │
│ .mcp.json in the project root │
│ Use: team-shared servers (committed) │
├─────────────────────────────────────────────┤
│ User scope │
│ ~/.claude.json, all your projects │
│ Use: personal tools (github, docs) │
└─────────────────────────────────────────────┘
Priority: Local > Project > User > plugin-provided servers > claude.ai connectors. When the same server is defined in several places, Claude Code uses the whole entry from the highest-precedence source (fields are not merged). Servers your organization provides through managedMcpServers rank above all of these.
MCP Context Cost
Every tool definition costs context tokens when it is loaded. These are the approximate upfront costs this guide published in January 2026:
| MCP Server | Approx. Tokens | Recommendation |
|---|---|---|
| hubspot | ~1,800 | ✅ Small, recommended |
| netlify | ~2,000 | ✅ Small, recommended |
| figma | ~2,500 | ✅ Acceptable |
| notion | Optimized | ✅ Official optimization |
| vercel | ~3,000 | ✅ Acceptable |
| stripe | ~4,000 | ⚠️ Medium |
| linear | ~6,200 | ⚠️ Large |
| atlassian | ~7,100 | ⚠️ Large |
| asana | ~12,800 | ❌ Too large |
| sentry | ~14,000 | ❌ Too large, use sparingly |
Best Practice: Only enable MCP servers you actively use. Every connected server still adds tool names and server instructions to each session, and more servers mean more startup work.
Tool search (on by default): Claude Code defers MCP tool definitions and loads them on demand through the
ToolSearchtool, so only tool names and server instructions load at session start. Tools still load upfront when you setENABLE_TOOL_SEARCH=false, for servers marked"alwaysLoad": true, and on models or deployments that don’t support tool search.ENABLE_TOOL_SEARCH=auto(orauto:N) loads tools upfront until they reach 10% (or N%) of the context window. Run/contextto see what your session actually spends.
MCP Management Commands
# List all MCP servers with a health status
claude mcp list
# Add a new server
claude mcp add --scope project <name> -- <command>
# Add a server from a JSON config block
claude mcp add-json <name> '<json>'
# Inspect one server (status, approval, last error)
claude mcp get <name>
# Remove a server
claude mcp remove --scope project <name>
# Reset approvals for project .mcp.json servers (troubleshooting)
claude mcp reset-project-choices
# Inside a session: status, OAuth sign-in, enable/disable, reconnect
/mcp
Using MCP in Practice
Example 1: Database Queries
With a database MCP (such as DBHub) enabled:
User: "Show me users who signed up in the last 7 days"
Claude: [Uses the db MCP]
→ Queries: SELECT * FROM users WHERE created_at > NOW() - INTERVAL '7 days'
→ Returns formatted results
→ Suggests indexes if query is slow
Example 2: Knowledge Persistence
With memory MCP enabled:
User: "Remember that we use Zod for all API validation"
Claude: [Uses memory MCP]
→ Creates entity: "API Validation"
→ Adds observation: "Use Zod for all API validation"
→ Available in future sessions
Example 3: GitHub Integration
With github MCP enabled:
User: "Create an issue for the login bug we discussed"
Claude: [Uses github MCP]
→ Creates issue with title, body, labels
→ Links to relevant code
→ Assigns to team member if specified
Memory MCP Deep Dive
The Memory MCP deserves special attention as it enables persistent project knowledge.
Memory Commands
The server exposes nine tools that Claude calls directly: create_entities, create_relations, add_observations, delete_entities, delete_observations, delete_relations, read_graph, search_nodes, and open_nodes. Plain requests such as “remember that…” are enough. If you want shortcuts, wrap the tools in custom skills; these are not built into Claude Code:
# Custom skills you can create for memory management
/memory-save # Save important knowledge
/memory-search # Search saved knowledge
/memory-list # List all entities
/memory-audit # Check memory health
Memory Structure
read_graph returns the knowledge graph in this shape (on disk, the server stores one JSON object per line in a .jsonl file):
{
"entities": [
{
"name": "Authentication System",
"entityType": "Architecture",
"observations": [
"Uses JWT with 24-hour expiration",
"Refresh tokens stored in httpOnly cookies",
"Located in src/lib/auth.ts"
]
},
{
"name": "Database Schema",
"entityType": "Infrastructure",
"observations": [
"PostgreSQL with Prisma ORM",
"Users table has email_verified column",
"Soft deletes using deleted_at"
]
}
],
"relations": [
{
"from": "Authentication System",
"to": "Database Schema",
"relationType": "uses"
}
]
}
Best Practices for Memory
## What to Save
✅ Architecture decisions and rationale
✅ Code patterns and conventions
✅ Bug fixes and their root causes
✅ Important configuration details
✅ Team decisions and constraints
## What NOT to Save
❌ Temporary debugging info
❌ One-time implementation details
❌ Information already in CLAUDE.md
❌ Frequently changing data
Troubleshooting MCP
Server Not Loading
# Check if server is registered and healthy
claude mcp list
# See one server's status and last error
claude mcp get <name>
# Verify the project config file
cat .mcp.json
# Reset approvals and re-add
claude mcp reset-project-choices
claude mcp add --scope project <name> -- <command>
Permission Issues
Project servers from .mcp.json stay at “Pending approval” until you approve them in an interactive session. To pre-approve them, add this to .claude/settings.local.json or ~/.claude/settings.json:
{
"enableAllProjectMcpServers": true
}
A server listed in disabledMcpjsonServers stays rejected either way.
Environment Variable Issues
Use ${VAR_NAME} (or ${VAR_NAME:-default}) in .mcp.json:
{
"env": {
"DATABASE_URL": "${DATABASE_URL}"
}
}
Or provide values directly with the -e flag:
claude mcp add --scope project mongodb \
-e MDB_MCP_CONNECTION_STRING="mongodb://..." \
-- npx -y mongodb-mcp-server@latest --readOnly
An unset ${VAR} with no default stays unexpanded and shows a warning in claude mcp list. In a remote server’s url and headers, credential variables such as ANTHROPIC_API_KEY always read as empty, so copy a token into a variable with your own name.
Useful Environment Variables
| Variable | Purpose |
|---|---|
MCP_TIMEOUT | Server startup timeout in ms (default 30000) |
MCP_TOOL_TIMEOUT | Tool execution timeout in ms |
MAX_MCP_OUTPUT_TOKENS | Max tokens per MCP tool result (default 25000; warning above 10,000) |
ENABLE_TOOL_SEARCH | true (default behavior), auto, auto:N, or false |
MCP_CONNECTION_NONBLOCKING | Set to 0 to wait for servers before the first prompt |
Enterprise MCP Management
Administrators control MCP servers through managed configuration:
managed-mcp.jsondeploys a fixed server set with exclusive control (/Library/Application Support/ClaudeCode/on macOS,/etc/claude-code/on Linux and WSL,C:\Program Files\ClaudeCode\on Windows).managedMcpServersin managed settings provides servers to every user alongside their own.allowedMcpServers/deniedMcpServersrestrict which servers may load. Each entry has exactly one key:serverName,serverCommand, orserverUrl. The denylist wins over the allowlist.
// managed-settings.json
{
"allowManagedMcpServersOnly": true,
"allowedMcpServers": [
{ "serverName": "github" },
{ "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] },
{ "serverUrl": "https://mcp.example.com/*" }
]
}
With allowManagedMcpServersOnly, user, project, and local allowlists can’t broaden the managed list, so users can’t load unapproved MCP servers.
Creating Custom MCP Servers
You can create custom MCP servers for specialized needs. The protocol specification is at modelcontextprotocol.io. The official “Build an MCP server” guide uses TypeScript SDK v2 (npm install @modelcontextprotocol/server zod, Node.js 20+).
Basic Structure
import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import { z } from 'zod';
// serveStdio calls this whenever it needs an instance,
// so return a fresh server every time
function createServer() {
const server = new McpServer({ name: 'my-custom-mcp', version: '1.0.0' });
server.registerTool(
'my_tool',
{
description: 'Does something useful',
inputSchema: z.object({
input: z.string().describe('What to process'),
}),
},
async ({ input }) => ({
content: [{ type: 'text', text: `Processed: ${input}` }],
}),
);
return server;
}
serveStdio(createServer, {
onerror: (error) => console.error('my-custom-mcp error:', error),
});
Build it, then register it: claude mcp add my-custom-mcp -- node /path/to/build/index.js.
MCP vs Other Tools
| Feature | MCP | Built-in Tools | Hooks |
|---|---|---|---|
| External data access | ✅ Primary purpose | ❌ Limited | ❌ No |
| Persistent storage | ✅ Memory MCP | ✅ Built-in auto memory | ❌ No |
| Custom integrations | ✅ Extensible | ❌ Fixed | ✅ Via commands |
| Context cost | Variable (low with tool search) | Included | Minimal |
| Setup complexity | Medium | None | Low |
Getting Started with MCP
Today:
- Add filesystem and memory MCP to your project
- Use an absolute
MEMORY_FILE_PATHfor project isolation - Save one important decision to memory
This week:
- Add database MCP if applicable
- Configure GitHub MCP for issue tracking
- Explore the memory tools (or build your own /memory-* skills)
This month:
- Optimize MCP selection for context efficiency
- Create project-specific MCP configurations
- Consider custom MCP for specialized needs
MCP transforms Claude Code from a standalone assistant into an integrated development platform. Choose your servers wisely and unlock Claude’s full potential.
Sources: Model Context Protocol, Claude Code MCP documentation, MCP Servers Repository