MCP Integration
Master the Model Context Protocol as a tool extension system.
What You’ll Learn
Claude Code ships with a powerful set of built-in tools — Read, Edit, Write, Bash, WebFetch, and more. But what if you need to query a database? Search a company wiki? Interact with a deployment pipeline? You could ask Claude to shell out to curl, but there’s a better way: the Model Context Protocol (MCP).
By the end, you’ll know:
- What MCP is and why it exists
- How MCP servers provide tools, resources, and prompts
- The client-server architecture and transport mechanisms
- How to configure MCP servers in your project
- How MCP tools integrate with Claude Code’s permission system
- How to build a simple MCP server from scratch
The Problem
Every team has its own tools. A frontend team needs Figma integration. A data team needs SQL access. A DevOps team needs Kubernetes controls. Building each integration directly into Claude Code would be:
- Impossible to maintain — thousands of integrations, each with different APIs
- A security nightmare — every integration would need to ship with Claude Code
- Inflexible — organizations can’t add their own internal tools
The pattern is familiar from other domains. Web browsers don’t build in every feature — they support extensions. Code editors don’t bundle every language — they support plugins. Claude Code needs the same thing: a standard protocol for tool extensions.
Without MCP:
┌──────────────────────────────────────────┐
│ Claude Code │
│ │
│ Built-in: Read, Edit, Write, Bash... │
│ Custom: ??? (fork the codebase?) │
└──────────────────────────────────────────┘
With MCP:
┌──────────────────────────────────────────┐
│ Claude Code │
│ │
│ Built-in: Read, Edit, Write, Bash... │
│ MCP: Database, Jira, Slack, │
│ Figma, K8s, your-custom-tool │
└──────────────────────────────────────────┘
How It Works
The MCP Architecture
MCP follows a client-server model. Claude Code is the client. Each external integration is a server. They communicate through a standard protocol:
┌─────────────────────────────────────────────────────┐
│ Claude Code (MCP Client) │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Built-in │ │ MCP Conn │ │ MCP Conn │ ... │
│ │ Tools │ │ #1 │ │ #2 │ │
│ └──────────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │
└─────────────────────│──────────────│────────────────┘
│ │
┌───────▼──────┐ ┌────▼─────────┐
│ MCP Server │ │ MCP Server │
│ (Database) │ │ (Jira) │
│ │ │ │
│ Tools: │ │ Tools: │
│ - query │ │ - search │
│ - schema │ │ - create │
│ - explain │ │ - update │
└──────────────┘ └──────────────┘
Each MCP server is a separate process or remote service. Claude Code connects to it, discovers what it offers, and makes its tools available to the AI alongside the built-in ones.
What MCP Servers Provide
An MCP server can expose three types of capabilities:
1. Tools — Functions the AI can call (most common)
{
"name": "database_query",
"description": "Execute a read-only SQL query against the project database",
"inputSchema": {
"type": "object",
"properties": {
"sql": { "type": "string", "description": "The SQL query to execute" }
},
"required": ["sql"]
}
}
2. Resources — Data the AI can read (files, documents, live data)
{
"uri": "db://schema/users",
"name": "Users table schema",
"mimeType": "application/json"
}
In Claude Code, you reference a resource with an @ mention in the form @server:protocol://resource/path, such as @github:issue://123.
3. Prompts — Reusable prompt templates
{
"name": "code_review",
"description": "Review code for common issues",
"arguments": [
{ "name": "language", "description": "Programming language" }
]
}
Claude Code lists a server’s prompts as commands, such as /mcp__github__pr_review 456.
In practice, tools are by far the most common. When the AI decides to use an MCP tool, the call flows through the same agent loop as built-in tools.
Transport Mechanisms
Claude Code connects to MCP servers over a few transports. Two cover almost every setup:
stdio — For local processes (most common)
Claude Code ──stdin/stdout──► MCP Server Process
The server runs as a child process, and the two sides exchange JSON-RPC messages over its stdin and stdout. This is fast and needs no network configuration, but the server runs with your user account’s full access, outside Claude Code’s Bash sandbox, so run only servers you trust. A stdio server must never write logs to stdout, because that corrupts the message stream; log to stderr instead.
HTTP (Streamable HTTP) — For remote servers (recommended)
Claude Code ──HTTPS──► Remote MCP Server
(running on a server)
The server runs on a remote machine, so a whole team can share it. HTTP is the recommended remote transport and supports OAuth sign-in. The older SSE transport is deprecated; use it only for a service that offers nothing else. Claude Code also accepts WebSocket servers ("type": "ws") in JSON configuration.
Configuration
MCP servers can be configured at three scopes:
| Scope | Loads in | Stored in |
|---|---|---|
| Local (default) | Current project, only for you | ~/.claude.json |
| Project | Current project, shared through version control | .mcp.json in the project root |
| User | All your projects | ~/.claude.json |
The claude mcp commands write these files for you:
# Remote server over HTTP, shared with the team through .mcp.json
claude mcp add --transport http --scope project company-wiki https://mcp.internal.example.com/wiki
# Local stdio server: everything after -- is the command that starts it
claude mcp add --transport stdio memory -- npx -y @modelcontextprotocol/server-memory
claude mcp list # configured servers and their status
claude mcp get memory # details for one server
Inside a session, /mcp shows each server’s status and handles sign-in. A project’s .mcp.json looks like this:
{
"mcpServers": {
"database": {
"type": "stdio",
"command": "node",
"args": ["./mcp/database-server.mjs"],
"env": { "DATABASE_URL": "${DATABASE_URL}" }
},
"memory": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-memory"]
},
"company-wiki": {
"type": "http",
"url": "https://mcp.internal.example.com/wiki"
}
}
}
Each entry defines:
- A name — How the tools will be prefixed (e.g.,
mcp__database__query) - A command/url — How to start or connect to the server
- A type —
stdiofor local processes,httpfor remote servers (sseis deprecated)
Here database stands for a project-owned server, like the one you’ll build below, that exposes query, schema, and explain tools; memory is the reference knowledge-graph server. Claude Code expands ${DATABASE_URL} from your environment, so credentials stay out of the committed file.
Because anyone can commit a .mcp.json, Claude Code asks you to approve its servers the first time you start an interactive session in that project; claude mcp reset-project-choices resets those answers. claude -p runs and Agent SDK sessions can’t show that prompt and connect project servers without asking, so pass --strict-mcp-config or add a disabledMcpjsonServers entry when you script Claude Code over a repository you didn’t write.
Tool Discovery
At startup, Claude Code connects to each configured MCP server and asks: “What tools do you offer?”
Startup sequence:
─────────────────
1. Claude Code reads MCP config (.mcp.json, ~/.claude.json, plugins)
2. For each server:
a. Spawn process (stdio) or connect (http)
b. Send: { "method": "tools/list" }
c. Receive: list of tool definitions
d. Register tools with naming convention
Result:
┌──────────────────────────────────────────────┐
│ Available Tools │
│ │
│ Built-in: │
│ Read, Edit, Write, Bash, Agent, │
│ WebFetch, ToolSearch... │
│ │
│ MCP (database): │
│ mcp__database__query │
│ mcp__database__schema │
│ mcp__database__explain │
│ │
│ MCP (memory): │
│ mcp__memory__add_observations │
│ mcp__memory__search_nodes │
│ mcp__memory__read_graph │
└──────────────────────────────────────────────┘
The naming convention mcp__<server>__<tool> prevents collisions. If two servers both have a tool called search, they become mcp__wiki__search and mcp__jira__search.
On current models, tool search is on by default: only tool names and server instructions load at session start, and Claude loads a tool’s full definition through the built-in ToolSearch tool when it needs it. Connected servers therefore cost little context until they’re used. Set ENABLE_TOOL_SEARCH=false to load every MCP tool definition upfront.
Permission Integration
MCP tools go through the same permission system as built-in tools. This is critical for security:
AI decides to call mcp__database__query
│
▼
┌──────────────────────────┐
│ Permission check │
│ │
│ - PreToolUse hooks │
│ - deny / ask / allow │
│ rules │
│ - permission mode │
└───┬──────────┬───────┬───┘
│ │ │
allow ask deny
│ │ │
▼ ▼ ▼
Execute Prompt Blocked
tool the user
Write MCP permission rules with the same names: mcp__database__query matches one tool, and mcp__database__* matches every tool from that server. In auto mode, a classifier stands in for most prompts, but explicit ask rules still prompt you. A PreToolUse hook (Session 15) with a matcher such as mcp__database__.* can inspect MCP tool calls and block dangerous ones.
The Communication Flow
Here’s a complete flow when the AI uses an MCP tool:
User: "How many users signed up this week?"
│
▼
┌─────────────────────────────────────────────┐
│ Agent Loop │
│ │
│ AI decides: use mcp__database__query │
│ Input: "SELECT COUNT(*) FROM users │
│ WHERE created_at > NOW() - '7d'" │
│ │
│ Permission check → allowed │
│ │ │
│ ▼ │
│ Claude Code sends to MCP server: │
│ { "method": "tools/call", │
│ "params": { │
│ "name": "query", │
│ "arguments": { "sql": "SELECT..." } │
│ } │
│ } │
│ │ │
│ ▼ │
│ MCP server executes query, returns: │
│ { "result": { "content": [ │
│ { "type": "text", "text": "142" } │
│ ]} │
│ } │
│ │ │
│ ▼ │
│ Result injected as tool_result │
│ AI continues: "142 users signed up..." │
└─────────────────────────────────────────────┘
From the AI’s perspective, an MCP tool works like a built-in tool: once its definition is loaded, the AI calls it with the right parameters and gets a result back. The protocol handles everything in between.
Key Insight
MCP is what makes Claude Code infinitely extensible without changing its core. Instead of building integrations into the codebase, MCP lets you plug in any tool through a standard protocol.
This mirrors a proven pattern in software:
| System | Core | Extension Protocol |
|---|---|---|
| Web Browser | Rendering engine | Extension APIs |
| VS Code | Editor core | Language Server Protocol |
| Unix | Kernel | stdin/stdout pipes |
| Claude Code | Agent loop | MCP |
The power is in the standard. Because MCP is an open protocol, anyone can build a server. The ecosystem grows independently of Claude Code itself. A database MCP server built by one team works with any MCP client — not just Claude Code.
Hands-On Example
Building a Simple MCP Server
These servers use the 2.x TypeScript server package that the official MCP server guide uses. Install it next to your scripts (Node.js 20 or later):
npm install @modelcontextprotocol/server zod
Here’s a minimal MCP server that provides a single tool — a word counter:
// word-counter-server.mjs
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
// serveStdio may call this factory more than once, so return a new server each time
function createServer() {
const server = new McpServer({
name: "word-counter",
version: "1.0.0",
});
// Register a tool
server.registerTool(
"count_words",
{
description: "Count words in a given text",
inputSchema: z.object({
text: z.string().describe("The text to count words in"),
}),
},
async ({ text }) => {
const wordCount = text.split(/\s+/).filter(Boolean).length;
const charCount = text.length;
return {
content: [
{
type: "text",
text: `Words: ${wordCount}, Characters: ${charCount}`,
},
],
};
},
);
return server;
}
// Serve over stdio; log to stderr only, because stdout carries the protocol
serveStdio(createServer, {
onerror: (error) => console.error("word-counter error:", error),
});
serveStdio negotiates the protocol revision with each client. Claude Code still connects to servers built with the 1.x @modelcontextprotocol/sdk package, where server.tool() is deprecated in favor of registerTool(), using the earlier protocol revision.
Connecting It to Claude Code
Register the server for the project:
claude mcp add --transport stdio --scope project wordcount -- node word-counter-server.mjs
The command adds an entry like this to your project’s .mcp.json, which you can also write by hand:
{
"mcpServers": {
"wordcount": {
"type": "stdio",
"command": "node",
"args": ["word-counter-server.mjs"]
}
}
}
The next time you start Claude Code in this project, approve the wordcount server when asked and check that /mcp shows it connected. The AI then has access to mcp__wordcount__count_words. You can ask “How many words are in this paragraph?” and the AI will use your custom tool.
A More Practical Example: File Metadata Server
// file-metadata-server.mjs
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
import fs from "fs/promises";
import path from "path";
function createServer() {
const server = new McpServer({
name: "file-metadata",
version: "1.0.0",
});
server.registerTool(
"file_stats",
{
description: "Get detailed metadata about a file (size, dates, permissions)",
inputSchema: z.object({
file_path: z.string().describe("Path to the file"),
}),
},
async ({ file_path }) => {
const stats = await fs.stat(file_path);
return {
content: [{
type: "text",
text: JSON.stringify({
size_bytes: stats.size,
created: stats.birthtime.toISOString(),
modified: stats.mtime.toISOString(),
is_directory: stats.isDirectory(),
permissions: stats.mode.toString(8),
}, null, 2),
}],
};
},
);
server.registerTool(
"directory_size",
{
description: "Total the size of the files directly inside a directory (not recursive)",
inputSchema: z.object({
dir_path: z.string().describe("Path to the directory"),
}),
},
async ({ dir_path }) => {
let totalSize = 0;
const entries = await fs.readdir(dir_path, { withFileTypes: true });
for (const entry of entries) {
if (entry.isFile()) {
const stat = await fs.stat(path.join(dir_path, entry.name));
totalSize += stat.size;
}
}
return {
content: [{
type: "text",
text: `Total size: ${(totalSize / 1024).toFixed(1)} KB (${entries.length} entries)`,
}],
};
},
);
return server;
}
serveStdio(createServer, {
onerror: (error) => console.error("file-metadata error:", error),
});
This gives the AI two new capabilities it didn’t have before — detailed file metadata and directory size calculation — without modifying Claude Code at all.
The demo trusts any path it receives. A real server should confine paths to the project: Claude Code sets CLAUDE_PROJECT_DIR in a stdio server’s environment and answers the MCP roots/list request with the session’s working directories.
What Changed
| Without MCP | With MCP |
|---|---|
| Fixed set of built-in tools | Unlimited extensibility |
| New integrations require code changes | Drop in a server config |
| Every user gets the same tools | Teams customize their toolset |
| AI shells out to CLI for custom work | AI uses structured, typed tools |
| No standard for tool extensions | Open protocol, growing ecosystem |
| Security is ad-hoc per integration | Unified permission system |
Next Session
MCP lets you add tools. But how do you enforce rules about how tools are used? Session 15 covers the Hooks System — event subscribers that fire before and after tool execution, giving you security gates, audit logs, and organizational policy enforcement.