InkdownInkdown
Start writing

Claude-Code

62 files·4 subfolders

Shared Workspace

Claude-Code
codex

08-mcp-services

Shared from "Claude-Code" on Inkdown

MCP Services

Model Context Protocol — how Claude Code connects to external tools and data sources.


What Is MCP?

MCP (Model Context Protocol) is a standard for connecting AI models to external tools and data sources. In Claude Code, MCP servers provide:

  • Tools — Callable functions the AI can use
  • Resources — Data sources the AI can read
  • Prompts — Pre-built prompt templates

Architecture

Plain text
┌─────────────────────────────────────────────────────┐
│                  Claude Code                         │
│                                                      │
│  ┌──────────────┐    ┌──────────────────────────┐   │
│  │  MCP Client  │◄──►│  MCP Server (stdio)      │   │
│  │  Manager     │    │  or                      │   │
│  │              │    │  MCP Server (SSE/HTTP)   │   │
│  └──────┬───────┘    └──────────────────────────┘   │
│         │                                           │
│         ▼                                           │
│  ┌──────────────┐                                   │
│  │  Tool Pool   │ — MCP tools merged with built-in  │
│  │  Command List│ — MCP commands as skills          │
│  │  Resources   │ — MCP resources for reading       │
│  └──────────────┘                                   │
└─────────────────────────────────────────────────────┘
0000_start_here_index_and_recommended_reading_order.md
0100_project_overview_tech_stack_runtime_modes_and_folder_map.md
0200_startup_flow_entry_points_and_cold_start_sequence.md
0300_codebase_modules_layers_state_models_and_schemas.md
0400_system_architecture_and_design_rationale.md
0500_interactive_repl_request_flow_end_to_end.md
0600_headless_sdk_and_print_mode_request_flow_end_to_end.md
0700_mcp_integration_connection_and_tool_call_flow.md
0800_external_services_sdks_storage_and_local_dependencies.md
0900_environment_variables_settings_feature_flags_and_failure_modes.md
1000_non_obvious_patterns_gotchas_and_debugging_traps.md
1100_full_codebase_file_inventory_grouped_by_directory.md
kimi
00-overview.md
01-entrypoints.md
02-state-management.md
03-query-system.md
04-tools-system.md
05-tasks-system.md
06-ui-components.md
07-bridge-remote.md
08-services.md
09-skills-plugins.md
10-commands.md
11-testing-architecture.md
12-permission-system.md
13-build-system.md
14-ink-internals.md
15-git-internals.md
16-context-compaction.md
17-vim-mode.md
18-mailbox-notifications.md
19-session-persistence.md
20-hooks-system.md
21-error-recovery.md
README.md
qwen
00-overview.md
01-entry-points.md
02-query-engine.md
03-tools-and-tasks.md
04-commands-and-skills.md
05-state-management.md
06-ink-rendering.md
07-bridge-remote.md
08-mcp-services.md
09-services-overview.md
10-multi-agent.md
11-system-prompt-constants.md
12-tool-interface.md
13-memory-system.md
14-buddy-companion.md
15-keybindings.md
16-stop-hooks.md
17-vim-mode.md
18-upstreamproxy.md
19-cost-tracking-history.md
20-contexts-styles-onboarding.md
21-hooks.md
22-screens.md
tweets-explain
claude-code-memory-analysis.md
compact
memory-system
agentic-architecture

MCP Client

Each MCP server connection is managed by an McpClient:

TypeScript
interface McpClient {
  type: 'connected' | 'pending' | 'error'
  serverName: string
  serverConfig: McpServerConfig
  transport: Transport
  tools: Tool[]
  resources: Resource[]
  prompts: Prompt[]
  capabilities: ServerCapabilities
}
Transport Types
TransportProtocolUse Case
stdiostdin/stdoutLocal subprocess servers
SSEServer-Sent EventsRemote HTTP servers
HTTPHTTP POSTRemote servers with HTTP
Client Lifecycle
Plain text
1. Configuration loaded (from settings, project, etc.)
    │
    ▼
2. Client created (type: 'pending')
    │
    ▼
3. Transport connected
    │
    ▼
4. Initialize handshake
    │
    ▼
5. Tools, resources, prompts fetched
    │
    ▼
6. Client type: 'connected'
    │
    ▼
7. Tools merged into tool pool
   Resources available for reading
   Commands registered as skills

Server Configuration

Configuration Sources (Priority Order)
  1. User settings (~/.claude/settings.json)
  2. Project settings (.claude/settings.json)
  3. Claude.ai settings (from claude.ai MCP registry)
  4. Enterprise MCP config (policy-managed)
Server Config Format
JSON
{
  "mcpServers": {
    "my-server": {
      "command": "npx",
      "args": ["-y", "@my-org/my-mcp-server"],
      "env": {
        "API_KEY": "secret"
      },
      "disabled": false
    }
  }
}
Configuration Parsing
TypeScript
// Parse MCP config from settings
parseMcpConfig(settings.mcpServers)

// Parse from file path
parseMcpConfigFromFilePath(filePath)

// Deduplicate servers
dedupClaudeAiMcpServers(servers)

// Filter by policy
filterMcpServersByPolicy(servers, policy)

MCP Tools

MCP tools are merged with built-in tools:

TypeScript
// In tools.ts
function assembleToolPool(permissionContext, mcpTools) {
  const builtInTools = getTools(permissionContext)
  const allowedMcpTools = filterToolsByDenyRules(mcpTools, permissionContext)

  // Sort for cache stability, deduplicate
  return uniqBy(
    [...builtInTools].sort(byName).concat(allowedMcpTools.sort(byName)),
    'name'
  )
}
Tool Naming

MCP tools are prefixed with the server name:

Plain text
serverName__toolName
// e.g., "github__create_issue"
Tool Permissions

MCP tools respect the same permission system as built-in tools:

  • Deny rules can block entire servers: mcp__serverName
  • Auto-approval rules work the same way
  • Permission mode (yolo, default, plan) applies

MCP Resources

Resources are data sources the AI can read:

TypeScript
interface McpResource {
  uri: string
  name: string
  description: string
  mimeType?: string
}
Resource Tools
ToolPurpose
ListMcpResourcesToolList available resources from all servers
ReadMcpResourceToolRead a specific resource by URI

MCP Commands (Skills)

MCP servers can expose commands as skills:

TypeScript
// In commands.ts
function getMcpSkillCommands(mcpCommands) {
  return mcpCommands.filter(cmd =>
    cmd.type === 'prompt' &&
    cmd.loadedFrom === 'mcp' &&
    !cmd.disableModelInvocation
  )
}

Connection Management

useManageMCPConnections Hook

Manages MCP connections in the UI:

Plain text
┌──────────────────────────────────────┐
│  MCP Servers                         │
│                                      │
│  ● github        connected           │
│  ● filesystem    connected           │
│  ○ postgres      connecting...       │
│  ✗ slack         error: timeout      │
│                                      │
│  [+ Add Server]                      │
└──────────────────────────────────────┘
Connection States
StateDescription
connectedServer is running and responsive
connectingInitial connection in progress
errorConnection failed (with error message)
disabledServer is disabled in settings
Hot Reload

When MCP settings change:

  1. New servers → connect
  2. Removed servers → disconnect
  3. Modified servers → reconnect
  4. Tools/commands cache → invalidate

Official MCP Registry

Claude Code maintains a registry of official MCP servers:

TypeScript
// Prefetched at startup
prefetchOfficialMcpUrls()

// Used to validate server URLs
// Provides metadata about known servers

MCP Commands

CommandDescription
/mcpManage MCP servers (interactive UI)
/mcp add <name>Add a new MCP server
/mcp remove <name>Remove an MCP server
/mcp listList configured MCP servers
/mcp get <name>Show server details

Enterprise MCP

Enterprise customers can manage MCP servers via policy:

TypeScript
// Load policy-managed MCP servers
loadPolicyLimits()

// Check if enterprise config exists
doesEnterpriseMcpConfigExist()

// Check if user config is allowed with enterprise config
areMcpConfigsAllowedWithEnterpriseMcpConfig()

Chicago MCP (Computer Use)

Feature-gated computer use integration:

TypeScript
// Cleanup after turn (on interrupt or natural end)
if (feature('CHICAGO_MCP') && !toolUseContext.agentId) {
  await cleanupComputerUseAfterTurn(toolUseContext)
}

Handles:

  • Screen capture state cleanup
  • App permission locks
  • Display targeting

Key Files Reference

FilePurpose
src/services/mcp/client.tsMCP client management, resource prefetch
src/services/mcp/config.tsServer configuration parsing and merging
src/services/mcp/types.tsMCP type definitions
src/services/mcp/officialRegistry.tsOfficial MCP server registry
src/services/mcp/claudeai.tsClaude.ai MCP integration
src/services/mcp/xaaIdpLogin.tsXAA identity provider login
src/services/mcp/utils.tsCommand/resource exclusion utilities
src/services/mcpServerApproval.tsxServer approval UI
src/tools/ListMcpResourcesTool/List MCP resources tool
src/tools/ReadMcpResourceTool/Read MCP resource tool
src/commands/mcp/MCP slash commands