How Do You Set Up MCP Servers in Claude Code?
Claude Code connects to external tools through the Model Context Protocol (MCP). Anthropic built Claude Code as a terminal-native MCP client. Every server connection runs through one CLI command: claude mcp add.
This guide covers the full setup process. It walks through the claude mcp add syntax, the three configuration scopes, the three transport types, and Tool Search token optimization. Common connection errors and their fixes are merged in. The guide reflects Claude Code’s MCP implementation as of mid-2026.
Claude Code differs from Claude Desktop in one fundamental way. Claude Desktop requires manual JSON editing. Claude Code replaced that workflow with a single CLI command that registers, verifies, and stores server configs automatically.
How Do You Add an MCP Server to Claude Code?
The claude mcp add command registers an MCP server in one line. It accepts a transport flag, a server name, and the server’s URL or command. All flags must precede the server name.
The base syntax follows this pattern:
claude mcp add --transport <type> <server-name> <url-or-command>
Two rules govern flag placement. Every option (--transport, --env, --scope, --header) must come before the server name. The double dash -- separates the server name from command arguments for stdio servers.
A remote HTTP server registration looks like this:
claude mcp add --transport http notion https://mcp.notion.com/mcp
A local stdio server registration uses the double dash separator:
claude mcp add --transport stdio postgres -- npx @modelcontextprotocol/server-postgres postgresql://localhost:5432/mydb
Environment variables pass through --env flags:
claude mcp add --transport stdio github --env GITHUB_TOKEN=ghp_xxxx -- npx @modelcontextprotocol/server-github
What Is the claude mcp add-json Command?
claude mcp add-json registers a server from a raw JSON payload instead of positional arguments. This command suits complex configs with multiple environment variables, custom headers, or nested arguments.
claude mcp add-json weather-api '{"type":"http","url":"https://api.weather.com/mcp","headers":{"Authorization":"Bearer token"}}'
The JSON payload accepts the same fields as .mcp.json entries: type, command, args, env, url, and headers. On Windows, claude mcp add-json occasionally returns “Invalid input” for HTTP servers. The workaround is the standard claude mcp add --transport http syntax.
How Do You Import Servers from Claude Desktop?
claude mcp add-from-claude-desktop opens an interactive dialog that copies existing Claude Desktop server configs into Claude Code. This command works on macOS and WSL.
The dialog lists every server from Claude Desktop’s config file. Select the servers to import. Imported servers keep their original names. Duplicates receive a numerical suffix (e.g., github_1).
This command saves time for developers who already configured servers in Claude Desktop. It eliminates re-entering commands, environment variables, and auth tokens one by one.
Which Configuration Scopes Does Claude Code Support?
Claude Code stores MCP server configs at three scopes: local, project, and user. Each scope controls which projects load the server and whether teammates share it. The scope flag determines where the config file lives on disk.
Local scope is the default. Claude Code stores it in ~/.claude.json, keyed by the current project’s absolute path. The server loads only in that project. Use local scope for personal credentials, experimental servers, and one-off testing.
Project scope writes to .mcp.json at the repository root. This file is committable to git. Every developer who clones the repo picks up the same server set. Use project scope for team-standard tools: shared databases, CI integrations, and monitoring servers.
claude mcp add --scope project --transport http sentry https://mcp.sentry.io
User scope stores the config globally in ~/.claude.json (not keyed by project path). The server loads in every project. Use user scope for tools needed everywhere: GitHub’s MCP server, personal knowledge bases, and general-purpose utilities.
claude mcp add --scope user --transport http github https://api.githubcopilot.com/mcp
The scope flag controls where the config lives. The transport flag controls how the server communicates.
Where Does Each Scope Store Its Config File?
Local and user scopes both store in ~/.claude.json in the home directory. Local entries are keyed by the project’s absolute path. User entries are global.
Project scope stores in .mcp.json at the project root.
One naming detail causes confusion. MCP “local” scope stores in ~/.claude.json (home directory). General local settings use .claude/settings.local.json (project directory). These are different files with different purposes.
What Is the Scope Precedence Order?
local > project > user > plugin-provided > claude.ai connectors. A server defined in multiple scopes resolves to the highest-precedence entry.
Project-scope .mcp.json files also inherit upward. Claude Code searches through all parent directories and merges their .mcp.json files. This inheritance operates independently of git boundaries. A subdirectory with its own .git still inherits the parent’s .mcp.json.
Which Transport Types Work with Claude Code?
Claude Code supports three MCP transport types: stdio, HTTP, and SSE. Stdio runs local processes. HTTP connects to remote servers. SSE is deprecated.
Stdio launches a server as a local subprocess. Communication flows through standard input/output. No network authentication is needed. Stdio suits CLI tools distributed as npm packages (npx), Python scripts, and compiled binaries.
HTTP (streamable HTTP) is the current standard for remote MCP servers. It uses a single HTTPS endpoint for JSON-RPC requests. HTTP supports OAuth 2.1 authentication. Use HTTP for cloud-hosted servers, team-shared services, and vendor-maintained integrations.
SSE (Server-Sent Events) is the legacy remote transport. New servers use HTTP instead. Existing SSE servers still work, but Anthropic recommends migrating. Switch --transport sse to --transport http for any server that supports both.
When Do You Choose stdio Over HTTP?
Stdio suits local tools packaged as npx modules, local database connectors, and file system servers. HTTP suits remote services, vendor APIs, and servers that require OAuth flows. The /mcp command inside a session initiates OAuth authentication for HTTP servers that need it.
How Does Tool Search Reduce Token Overhead?
Tool Search defers MCP tool definitions and loads them on demand. It activates automatically when tool descriptions exceed 10,000 tokens. Anthropic reports an 85% reduction in token overhead with 50+ connected tools.
A five-server setup consumed 55,000 tokens before a single prompt. Tool Search changed that math.
Anthropic shipped Tool Search on January 14, 2026. Thariq Shihipar announced the feature for all Claude Code users. The mechanism works in three steps:
- Claude Code checks total MCP tool definition size at session start.
- Definitions exceeding the 10K-token threshold are marked with
defer_loading: true. - Claude discovers and loads only the tools it needs for the current task.
The benchmarks are specific. Traditional loading consumed ~77,000 tokens with 50+ tools. Tool Search reduced that to ~8,700 tokens. The Tool Search tool itself adds only ~500 tokens of overhead.
Two search modes operate under the hood. Regex mode constructs patterns for precise matching. BM25 mode uses natural language queries for exploratory searches.
Tool Search is enabled by default. No opt-in is required. Developers with simple setups (1-3 servers below the 10K threshold) see no change in behavior.
A fresh Claude Code session spends tokens before the first prompt. The system prompt costs ~4,200 tokens. A project CLAUDE.md adds ~1,800 more. One MCP server adds more. GitHub’s MCP server alone injects ~42,000 tokens of tool definitions without Tool Search. That is 21% of the default 200,000-token context window. With Tool Search active, Claude Code loads only tool names and defers schemas until needed.
How Do You Check Tool Search Status?
Run /context inside a session. The MCP tools line shows “loaded on-demand” when Tool Search is active. It shows a token count when tools are fully preloaded.
Run /mcp to see per-server token costs. Disable individual servers mid-session to reclaim context space.
How Do You Verify and Manage Connected Servers?
Run claude mcp list to see all configured servers and their connection status. Run claude mcp get <name> to inspect a specific server’s scope, transport, and config details. These commands work from any terminal outside a Claude Code session.
Inside a session, the /mcp slash command provides real-time status. It shows which servers are connected, which are disconnected, and which need OAuth authentication. Select a disconnected server to retry the connection or start an auth flow.
Six management commands cover the full lifecycle:
claude mcp addregisters a new server.claude mcp add-jsonregisters from a raw JSON payload.claude mcp add-from-claude-desktopimports from Claude Desktop.claude mcp listshows all servers.claude mcp get <name>inspects one server.claude mcp remove <name>deletes a server.
One additional command, claude mcp serve, exposes Claude Code itself as an MCP server. Other clients (Claude Desktop, Cursor, Windsurf) can then call Claude Code’s file editing and command execution tools remotely.
What Are the Most Common Claude Code MCP Errors and Fixes?
Connection failures cluster into four categories: wrong scope, PATH issues, JSON syntax errors, and auth flow problems. Each category has a specific diagnostic command and a direct fix.
Wrong scope or file. Run claude mcp list in the project directory. A missing server means it was registered under the wrong scope. Run claude mcp get <name> to confirm which scope file holds the entry. Re-add the server with the correct --scope flag.
PATH and environment issues. Claude Code launches MCP subprocesses with a different shell environment than the terminal. Tools installed through nvm often fail because the subprocess cannot find node or npx. Two fixes exist. Use absolute paths to the Node binary. Alternatively, add the nvm initialization block to ~/.zshrc (not just ~/.zprofile). Tilde paths (~/) do not expand in command arguments. Use absolute paths.
JSON syntax errors. Trailing commas, unquoted keys, and unescaped backslashes (common on Windows paths) break .mcp.json silently. Claude Code loads no error message. Validate the JSON before troubleshooting further.
Why Does npx Fail with “Connection Closed” on Windows?
Windows cannot execute npx directly as a Claude Code subprocess. Wrap the command with cmd /c:
claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package
Without the cmd /c wrapper, Windows throws “Connection closed” immediately.
Why Does a Server Disappear After a Teammate Changes .mcp.json?
Claude Code stores approval decisions for project-scope servers. When a teammate changes .mcp.json, the approval prompt does not re-trigger automatically. Run claude mcp reset-project-choices after pulling changes. This clears stored decisions and prompts re-approval from scratch.
Auth flow hangs. First-run authentication for some servers prompts on stderr. Claude Code waits for the subprocess to stabilize, and the auth prompt never surfaces. Run the server command manually first (npx -y @scope/name in a separate terminal). Complete any first-time OAuth flow or API key entry. Then register the server with claude mcp add.
Tool name conflicts. Two servers exposing the same tool name cause Claude Code to prefer one silently. Use the tools field in .mcp.json to rename or filter conflicting tools. Run /mcp to check which tools are active from each server.
Configure the server startup timeout with the MCP_TIMEOUT environment variable. The default is generous, but slow-starting servers on cold npx installs benefit from an explicit value:
MCP_TIMEOUT=10000 claude
Per-server tool execution timeouts use the timeout field in .mcp.json, set in milliseconds.
How Do Subagents and Channels Extend MCP in Claude Code?
Subagents accept a mcpServers field in their YAML frontmatter. Inline MCP definitions connect when the subagent starts and disconnect when it finishes. This keeps server tool definitions out of the parent context window.
A database subagent with a dedicated MCP server looks like this in .claude/agents/db-agent.md:
yaml
---
name: database-assistant
tools:
- "mcp:shared-db:query"
- "mcp:shared-db:list_tables"
model: sonnet
---
The mcp:<server>:<tool> syntax restricts which tools the subagent can call. Omitting the tools field grants access to all available tools, including every MCP tool. Be explicit about permissions.
Subagents can recursively spawn up to 5 levels deep (as of v2.1.172). Each level can have its own scoped MCP servers.
Channels let MCP servers push messages directly into a Claude Code session. A server declares the claude/channel capability, and the user opts in with the --channels flag at startup. Use cases include CI results, monitoring alerts, and chat platform bridges.
How Do Enterprises Manage MCP Servers Across Teams?
Administrators deploy a managed-mcp.json file to define mandatory or prohibited servers across an organization. This file takes the highest precedence in the MCP setup hierarchy. Individual developers cannot modify or remove managed servers.
Two additional settings filter what developers can add on their own. allowedMcpServers accepts glob patterns (e.g., company-*) to restrict server names. deniedMcpServers blocks specific patterns outright.
Server-managed settings deliver these policies remotely through the claude.ai admin console. Claude Code fetches settings at startup and polls hourly. This path works for Claude for Teams and Claude for Enterprise customers (v2.1.38+).
What Security Risks Apply to Claude Code MCP Servers?
MCP servers run as subprocesses with the user’s full system privileges. Anthropic’s security guidance states: only install servers from trusted sources.
In April 2026, OX Security disclosed a systemic vulnerability in the MCP STDIO transport. The flaw affects all official Anthropic SDKs across Python, TypeScript, Java, and Rust. The disclosure documents 14 CVEs, 150 million+ SDK downloads, and an estimated 200,000 vulnerable server instances. Anthropic characterised the behaviour as “expected” and declined to patch the protocol architecture.
Three practices reduce risk in Claude Code specifically:
- Pin server versions in production configs. Never use
npx -y pkg@latestin shared.mcp.jsonfiles. - Use scoped tokens with minimum permissions. Database servers get read-only credentials. API servers get narrow OAuth scopes.
- Run
claude mcp listperiodically and remove servers no longer in use.
The MCP server directory on this site notes which servers are Anthropic reference implementations, which are vendor-maintained, and which are community-built. Check provenance before installing.
Setting up MCP servers in Claude Code takes one command per server. The real work is choosing the right scope, selecting the correct transport, and monitoring context costs. Start with one or two servers that match the current project. Add more as specific workflows demand them.
For the visual setup experience, see the Claude Desktop MCP setup guide. For server recommendations sorted by use case, browse the MCP server directory. To understand how Claude Code compares to other MCP clients, see the MCP clients hub.