Files
Luong NGUYEN ac9ee17169 docs: make version stamps and Compatible Models footers true (#259)
Type: docs

Makes the version stamps, Compatible Models footers and locale README badges say only what has been checked. Every claim below was checked against `https://code.claude.com/docs/en/<page>.md` or the raw changelog (2.1.303–2.1.322), not written from memory.

## Part A: English footers at 2.1.310 / 2.1.302

Each file's behavioural claims were checked against every changelog entry after its stamp, up to 2.1.322, and against the current docs. A stamp moves only when every claim checks out.

| File | Claims checked | Fixes | Sources | New stamp |
|---|---|---|---|---|
| `INDEX.md` | ~75: AGENTS.md rule (v2.1.277); skill/agent/MCP install paths; `/mcp__github__list_prs`; 5 hook types, 33 events, task-tool model note; `--plugin-dir`; checkpoint menu (6 options); `/workflows`, ultracode (v2.1.284), size guideline; 6 permission modes; `/loop` and the cron tools; Chrome; Remote Control; `SendMessage`/`ListAgents`/`notify_when_idle`; CLI flags | 1. Workflow size: medium aims for fewer than 10 agents only since v2.1.271 (15 before), and the default is small on a Pro plan. 2. dontAsk: file reads inside the working directories also run, as do *most* calls a `permissions.allow` rule or a `PreToolUse` hook approves (neither can approve critical-path `rm`/`rmdir` or network-path reads), and an installed mod can approve some calls. No version is given: the changelog doesn't say when a mod's `tool.check` allow arrived (it is already referenced in 2.1.290, 2.1.292 and 2.1.299). 3. `SendMessage` also reaches sessions on other machines and in the cloud, from a session connected to Remote Control with a claude.ai sign-in; a cloud session can't answer with `SendMessage`. The L383 use-case column now says the same. 4. The `--model` list adds the Fable models. 5. Plan mode: "Read-only analysis" → researches and proposes, runs shell commands to explore, edits blocked until the plan is approved. | [workflows#set-a-size-guideline](https://code.claude.com/docs/en/workflows#set-a-size-guideline) ("The default is `medium`, or `small` when you're signed in on a Pro plan with Claude Code v2.1.271 or later"); CL 2.1.219 ("aim for fewer than 15 agents"), CL 2.1.271 ("lowered the medium size guideline from 15 to 10 agents"); [permission-modes](https://code.claude.com/docs/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode) ("a mod you installed can still approve some of those calls"; "Claude still runs … file reads inside your working directories and read-only Bash commands"; "It also denies the built-in `AskUserQuestion` tool even if your allow rules match it"; "An allow rule or `PreToolUse` hook can't approve these: Recognized `rm` and `rmdir` critical-path removals … Reads from a network path"); CL 2.1.292 ("Fixed a plugin's `tool.check` hook answering allow running a tool…"), CL 2.1.299 ("…that a `PreToolUse` hook or a mod's `tool.check` hook allowed"); [permission-modes#analyze-before-you-edit-with-plan-mode](https://code.claude.com/docs/en/permission-modes#analyze-before-you-edit-with-plan-mode) ("Claude reads files, runs shell commands to explore, and writes a plan, but does not edit your source. Except in interactive terminal sessions with bypass permissions available, edits stay blocked until you approve the plan."); [cross-session-messaging](https://code.claude.com/docs/en/cross-session-messaging) ("reach your sessions on other machines or in the cloud"; "from a session that is connected to Remote Control, which needs a claude.ai sign-in"; "A cloud session … can't use `SendMessage` to answer a message from another machine"); model-config. The "device card" line checked out against [whats-new/2026-w34](https://code.claude.com/docs/en/whats-new/2026-w34). | **2.1.322** |
| `LEARNING-ROADMAP.md` | 33 hook events / 5 types; 6 built-in subagents (Explore, Plan, General-purpose, claude, statusline-setup, claude-code-guide); 60+ commands (commands page has 121 rows); `/design` (v2.1.265); `/plan`, `/rewind`, `/loop 5m`, `/schedule`; 6 permission modes (Manual since v2.1.200); Alt+T; skill `effort`/`shell`; plugin `workflows`/`channels`/`dependencies`; agent-teams env var; `claude mcp add --transport http`; `-r`, `--max-turns`, `--output-format json`; all 17 source links resolve | 1. Remote Control: "generally available" → "out of research preview", the docs' own wording. 2. Extended thinking (L368, Exercise 3, checklist): Opus 5.5, Sonnet 5.5, Haiku 5.5 and the Fable models always use extended thinking, so the exercise uses `/effort` and scopes Alt+T / Option+T to models that allow turning thinking off. 3. Exercise 4: checkpoints are automatic and unnamed, so step 1 no longer creates a named "Clean state" checkpoint and step 5 says which one to `/rewind` to. | [whats-new/2026-w34](https://code.claude.com/docs/en/whats-new/2026-w34): "Any machine running `claude remote-control` now shows up as a device card at the top of the Code tab in the Claude app. Remote Control is also out of research preview."; [interactive-mode](https://code.claude.com/docs/en/interactive-mode): Alt+T "Has no effect on Opus 5.5, Sonnet 5.5, Haiku 5.5, or the Fable models, which always use extended thinking."; [model-config](https://code.claude.com/docs/en/model-config): "the effort level is the primary control for how much thinking happens"; [checkpointing](https://code.claude.com/docs/en/checkpointing): "Every prompt you send that starts a turn creates a new checkpoint" | **2.1.322** |
| `resources.md` | Adaptive reasoning on Opus 4.7+, Sonnet 5+, Haiku 5.5 and the Fable models; permission modes; 33 hook events; `/loop` and cron; 7 memory tiers; Chrome; keybinding chords; Code Review; Monitor (2.1.98); `/goal` and `claude agents` (2.1.139); `--json` (2.1.145); all links | none needed | model-config, hooks, memory, agent-view, changelog | **stays 2.1.310**: L253 gives `/run`, `/verify`, `/run-skill-generator` as "(v2.1.145+)". Neither the changelog, the v2.1.145 release notes, the skills/commands docs nor the what's-new pages for weeks 19–22 give a version. |
| `03-skills/claude-md/SKILL.md` | `name`/`description` frontmatter, `$ARGUMENTS`; CLAUDE.md locations and loading; "under 200 lines"; AGENTS.md gates (v2.1.277, v2.1.281), blocking files, `/config` Project instructions values and default; `@AGENTS.md`/symlink fallback; `.claude/agents/` | L196: the list of cases where AGENTS.md isn't read now includes a disabled built-in plugin, and limits the upgrade case to "in some cases" after upgrading from v2.1.276 or earlier | [memory#when-agents-md-support-is-unavailable](https://code.claude.com/docs/en/memory#when-agents-md-support-is-unavailable): "You used `/plugin` to disable the built-in plugin that reads `AGENTS.md`"; "In some cases, it's your first session after you upgrade from v2.1.276 or earlier" | **stays 2.1.302**: no primary source states L24 ("~150-200 instructions", "system prompt already uses ~50") or L214 (the system reminder says CLAUDE.md "may or may not be relevant") |
| `07-plugins/devops-automation/README.md` | `--plugin-dir` install; commands; agents; hooks; MCP; workflow; source URLs (all 200) | none: the stale claims need a design decision (below) | [plugins/components](https://code.claude.com/docs/en/plugins/components): "Save a command at `commands/<file>.md` and it becomes `/<plugin>:<file>`"; [plugins-reference](https://code.claude.com/docs/en/plugins-reference) standard layout: "Hooks \| `hooks/hooks.json`", "MCP servers \| `.mcp.json`" | **stays 2.1.302**: bare `/deploy`, `/rollback`, `/status` (`/status` is also a built-in), `/incident`; `hooks/*.js` are never registered (no `hooks/hooks.json`); `mcp/kubernetes-config.json` never loads (no `.mcp.json` or `mcpServers`) |
| `07-plugins/documentation/README.md` | same | none | same | **stays 2.1.302**: bare command names; `mcp/github-docs-config.json` never loads, so the `GITHUB_TOKEN` setup has no effect |
| `07-plugins/pr-review/README.md` | same | none | same | **stays 2.1.302**: bare command names; `hooks/pre-review.js` is not registered; `mcp/github-config.json` never loads |

No changelog entry from 2.1.303 to 2.1.322 touched the plugin READMEs or SKILL.md. Their problems predate the stamps, and #209 already listed the hook/MCP files that never load.

**Locale copies:** the same factual fixes went into every locale with the same sentence. That's dontAsk and plan mode in all six INDEX files; workflow size in fa and ko; `SendMessage` and the use-case column in fa and ko; the `--model` list in fa and ko; "generally available" in fa and ko LEARNING-ROADMAP; the extended-thinking exercise/checklist and the checkpoint exercise in all six LEARNING-ROADMAP copies; the AGENTS.md cases in all six SKILL.md copies. Locale stamps were not bumped. INDEX and LEARNING-ROADMAP stay at 2.1.310 in every locale, and the SKILL.md copies keep their footers.

## Part B: Compatible Models footers

The new list is **Claude Fable 5.2, Claude Fable 5.1, Claude Fable 5, Claude Opus 5.5, Claude Opus 5, Claude Sonnet 5.5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.8, Claude Haiku 5.5, Claude Haiku 4.5**. It is used on root docs and module pages alike, and it's the README FAQ's list, so the footers and the FAQ no longer disagree.

Why one list for both file types: STYLE_GUIDE's footer rule ("List all compatible models") applies to both. A shorter "current models only" list on module pages would break that rule. Justification from [model-config](https://code.claude.com/docs/en/model-config):

- **Current models:** "| Anthropic API | Opus 5.5 | Sonnet 5.5 | Haiku 5.5 |"; "the `fable` alias resolves to Fable 5 in Claude apps gateway sessions and to Fable 5.2 everywhere else"; "Fable 5.2 requires Claude Code v2.1.321 or later".
- **Older models still in use:**
  - "**Fable 5.1 or Fable 5**: select it by model ID."
  - "| Claude Platform on AWS | Opus 5.5 | Sonnet 4.6 | Haiku 4.5 |".
  - "biology-flagged requests re-run on Opus 5, and cybersecurity-flagged requests re-run on Opus 4.8".
  - "**Sonnet 5.5**: cybersecurity-flagged requests re-run on Sonnet 5."
- **None are retired.** The [models overview](https://platform.claude.com/docs/en/about-claude/models/overview) that model-config links marks only Opus 4.1, Opus 4 and Sonnet 4 as "retired". All eleven listed models appear there without that mark.

Scope: 336 lines in 331 files. The changed lines are the `**Compatible Models**` lines (92, some of them in locale files) and every localized label (`호환 모델`, `مدل‌های سازگار`, `Các Mô Hình Tương Thích`, `Сумісні моделі`, `対応モデル`, `互換モデル`, `兼容模型`), plus the italic `*対応:…*` / `*Для …*` / `*适用于 …*` lines in the ja/uk/zh concepts guides. Labels, separators (`, ` `、` `، `) and locale stamps are unchanged. The README FAQ lines and the 05-mcp `tool_reference` note are not footers and were left alone. The footer lines of `CHANGELOG.md`, `fa/CHANGELOG.md` and `ko/CHANGELOG.md` also carry the new list; only the footer line changed, not the entries.

## Part C: locale README badges

Real state: the newest version that most (more than half) of the locale's ten module READMEs carry or exceed, backed by the sync commit that brought them there.

A badge is marked **(partial)** when one or more of the locale's module READMEs has no version footer (never synced since its first translation), or when the locale is a condensed translation. A module synced to an older version than the badge doesn't make it partial on its own; the majority rule above already covers that. Only zh meets the rule (02-memory and 05-mcp have no footer, and #247 calls zh condensed).

| Locale | Old badge / "latest" | Evidence | New |
|---|---|---|---|
| ja | 2.1.119 (badge, "latest", FAQ) | module footers: 3×2.1.322, 5×2.1.316, 1×2.1.310, 1×2.1.302; 8/10 ≥ 2.1.316 (#230); #247 carried only the sections ja has | **2.1.316** (Oct 2026) |
| uk | 2.1.112 (FAQ line; no badge) | 3×2.1.322, 4×2.1.316, 1×2.1.310, 2×2.1.302; 7/10 ≥ 2.1.316 (#230) | **2.1.316** (Oct 2026) |
| zh | 2.1.112 (badge, "latest", FAQ) | 2.1.316, 2.1.310 ×2, 2.1.302 ×2, 2.1.300 ×2, 2.1.278; 02 and 05 have no footer (untouched since the first translation); 7/10 ≥ 2.1.300 (#193); #247 was "condensed", model lists only | **2.1.300 (partial)** (Oct 2026): the badge, "latest" and FAQ lines say zh is condensed and that 02-memory and 05-mcp haven't been synced since the April 2026 translation |
| ko | 2.1.310 | 5×2.1.322, 5×2.1.310; #228 synced ko to 2.1.310, and #247 says 2.1.316 "was not backfilled" | **2.1.310** (unchanged) |
| fa | 2.1.310 | 5×2.1.322, 5×2.1.316; #241 "syncs the translation from v2.1.310 to v2.1.316"; #247 carried only the 2.1.322 P1 changes | **2.1.316** (Oct 2026) |
| vi | none (README has no badge or version line) | 4×2.1.322, 6×2.1.316 | no change |

Months come from the docs changelog: 2.1.300 was released October 14, 2026 and 2.1.316 October 31, 2026. The README *footers* in fa/ja/ko/uk/zh stay at 2.1.322: #247 checked those files themselves, while the badge describes the whole locale.

## Deliberately left

- **Stamps not bumped:** `resources.md` (2.1.310), `03-skills/claude-md/SKILL.md` and the three plugin READMEs (2.1.302), for the reasons in the Part A table.
- **Example plugins:** the fix is a design choice between wiring up `hooks/hooks.json` / `.mcp.json` and rewording the READMEs, and renaming commands to `/<plugin>:<name>` touches seven languages plus `07-plugins/README.md` (bare `/review-pr`). It needs a follow-up issue.
- **Same unverifiable version elsewhere:** `03-skills/README.md` also said `/run-skill-generator` is v2.1.145+. Handled by #262, now merged into this branch from `main`.
- **Older `--model` lists:** ja/uk/vi/zh INDEX have pre-5.x lists (e.g. "Sonnet 4.6, Opus 4.7, Haiku 4.5"). That isn't the English sentence, so it belongs to a locale sync.

## Follow-ups
- **LEARNING-ROADMAP `/effort` line (review r3 N13):** line 368 can read as if `/effort` applies only to the models that always use extended thinking; per model-config's effort table it also works on Opus 5, Sonnet 5 and Opus 4.8. Not wrong; clarify in the next pass.

- **Compatible Models scope (review S3):** Opus 4.6 is Microsoft Foundry's current `opus`, and Sonnet 4.5 is the current `sonnet` on Bedrock, Google Cloud's Agent Platform and Foundry (deprecated, retiring Nov 30, 2026), per model-config's alias table. Both are still in use, so either add them to the FAQ and every footer (Sonnet 4.5 marked deprecated), or define the list's scope in STYLE_GUIDE (e.g. the models the aliases resolve to on the Anthropic API plus older models in active use) and cite the deprecations table.
- **Model order (review N8):** the list puts Opus 4.8 after Sonnet 4.6. Grouping by family (Fable, Opus 5.5/5/4.8, Sonnet, Haiku) would read better; the order is shared by STYLE_GUIDE, the FAQ and every footer, so change it everywhere at once.
- **Example plugins:** the follow-up issue proposed above.

## Validation

- `SKIP=mermaid,vietnamese-mermaid,japanese-mermaid,korean-mermaid,persian-mermaid pre-commit run --files <338 changed files>`: every hook passes, including link-check (246 URLs per language). The Mermaid hooks can't install here (`language: node must have package.json or additional_dependencies`, the same failure #247 reported). `python scripts/check_mermaid.py --strict` was run directly instead: Pele 1.6.0 rendered all 416 blocks.
- `python scripts/check_cross_references.py`: all valid (674 files).
- Review fix round 1 (18 files): the same `pre-commit run --files` passes every hook (Mermaid hooks skipped as above; no Mermaid block was touched), and the cross-reference check is still valid after merging `main`.
- Review fix round 2 (14 files: the extended-thinking wording in all 7 LEARNING-ROADMAP files, the dontAsk line in all 7 INDEX files): `pre-commit run --files` passes every hook (Mermaid hooks skipped; no Mermaid block touched), and the cross-reference check is valid (674 files) after merging `main` again (#257).
- Pre-push secret scan: it flagged `06-hooks/README.md:1683` (en, fa, vi), a false positive. The `sk-…{20,}` pattern matches the docs anchor `hooks#pretooluse-ask-decisions-in-auto-mode`, which has been on `main` since 11b2ae3 (en), c2f92c8 (fa) and 8de1820 (vi), and is not on a line this PR changes. The PR's added lines have no secret-pattern matches.

Closes #256
2026-11-12 14:29:18 +01:00
..

Claude How To

MCP (Model Context Protocol)

This folder contains comprehensive documentation and examples for MCP server configurations and usage with Claude Code.

Overview

MCP (Model Context Protocol) is a standardized way for Claude to access external tools, APIs, and real-time data sources. Unlike Memory, MCP provides live access to changing data.

Key characteristics:

  • Real-time access to external services
  • Live data synchronization
  • Extensible architecture
  • Secure authentication
  • Tool-based interactions

MCP Architecture

graph TB
    A["Claude"]
    B["MCP Server"]
    C["External Service"]

    A -->|Request: list_issues| B
    B -->|Query| C
    C -->|Data| B
    B -->|Response| A

    A -->|Request: create_issue| B
    B -->|Action| C
    C -->|Result| B
    B -->|Response| A

    style A fill:#e1f5fe,stroke:#333,color:#333
    style B fill:#f3e5f5,stroke:#333,color:#333
    style C fill:#e8f5e9,stroke:#333,color:#333

MCP Ecosystem

graph TB
    A["Claude"] -->|MCP| B["Filesystem<br/>MCP Server"]
    A -->|MCP| C["GitHub<br/>MCP Server"]
    A -->|MCP| D["Database<br/>MCP Server"]
    A -->|MCP| E["Slack<br/>MCP Server"]
    A -->|MCP| F["Google Docs<br/>MCP Server"]

    B -->|File I/O| G["Local Files"]
    C -->|API| H["GitHub Repos"]
    D -->|Query| I["PostgreSQL/MySQL"]
    E -->|Messages| J["Slack Workspace"]
    F -->|Docs| K["Google Drive"]

    style A fill:#e1f5fe,stroke:#333,color:#333
    style B fill:#f3e5f5,stroke:#333,color:#333
    style C fill:#f3e5f5,stroke:#333,color:#333
    style D fill:#f3e5f5,stroke:#333,color:#333
    style E fill:#f3e5f5,stroke:#333,color:#333
    style F fill:#f3e5f5,stroke:#333,color:#333
    style G fill:#e8f5e9,stroke:#333,color:#333
    style H fill:#e8f5e9,stroke:#333,color:#333
    style I fill:#e8f5e9,stroke:#333,color:#333
    style J fill:#e8f5e9,stroke:#333,color:#333
    style K fill:#e8f5e9,stroke:#333,color:#333

MCP Installation Methods

Claude Code supports multiple transport protocols for MCP server connections:

# Basic HTTP connection
claude mcp add --transport http notion https://mcp.notion.com/mcp

# HTTP with authentication header
claude mcp add --transport http secure-api https://api.example.com/mcp \
  --header "Authorization: Bearer your-token"

Stdio Transport (Local)

For locally running MCP servers:

# Local Node.js server
claude mcp add --transport stdio myserver -- npx @myorg/mcp-server

# With environment variables
claude mcp add --transport stdio myserver --env KEY=value -- npx server

CLAUDE_PROJECT_DIR for stdio servers (v2.1.139+)

Every MCP stdio server is spawned with CLAUDE_PROJECT_DIR=<absolute path to repo root> already set in its environment — the same convention used for hooks. Plugin and project .mcp.json files can reference ${CLAUDE_PROJECT_DIR} in the command, args, and env values, and the substitution happens before execve():

{
  "mcpServers": {
    "repo-tools": {
      "type": "stdio",
      "command": "node",
      "args": ["${CLAUDE_PROJECT_DIR:-.}/.claude/mcp/repo-tools.js"],
      "env": {
        "REPO_ROOT": "${CLAUDE_PROJECT_DIR:-.}"
      }
    }
  }
}

Note

: In project, local and user configs, write ${CLAUDE_PROJECT_DIR:-.} with a default: the variable is set in the server's environment, not in Claude Code's own. Only plugin MCP configs substitute ${CLAUDE_PROJECT_DIR} directly.

Use this when your stdio server needs to read files relative to the project root regardless of where Claude Code was launched.

stdio MCP servers also receive CLAUDE_CODE_SESSION_ID (matching the value passed to hooks and Bash), including when the session is resumed with --resume (v2.1.163+).

SSE Transport (Deprecated)

Server-Sent Events transport is deprecated in favor of http but still supported:

claude mcp add --transport sse legacy-server https://example.com/sse

WebSocket Transport (ws)

WebSocket servers hold a persistent bidirectional connection, which suits remote MCP servers that push events to Claude unprompted. Use HTTP instead when your server only responds to requests, since HTTP supports OAuth and the claude mcp add --transport flag, while WebSocket supports neither.

Because --transport does not accept ws, configure it in .mcp.json or through claude mcp add-json:

{
  "type": "ws",
  "url": "wss://mcp.example.com/socket",
  "headers": {
    "Authorization": "Bearer YOUR_TOKEN"
  }
}

The type: "ws" entry accepts the same url, headers, headersHelper, timeout, and alwaysLoad fields as http. Authentication is header-only — there is no OAuth flow for WebSocket servers.

Note

: Since v2.1.285, claude mcp list lists WebSocket (ws) servers with their URL and health status (earlier versions left them out). You can also check them with claude mcp get <name> or the /mcp panel.

Like HTTP and SSE, WebSocket connections use a 5-minute idle window; stdio and WebSocket have no per-request timer. A url entry with no type is an error naming "http", "sse", and "ws" as the valid values.

Session Working Directories (roots/list)

MCP servers can discover the session's working directories: the launch directory plus all --add-dir/additionalDirectories entries are returned via the MCP roots/list request, and a notifications/roots/list_changed notification is sent whenever the set changes (v2.1.203). The idle timeout now also applies to stdio servers (30 minutes), with a per-server timeout acting as an idle floor (v2.1.203).

Windows-Specific Note

On native Windows (not WSL), use cmd /c for npx commands:

claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package

OAuth 2.0 Authentication

Claude Code supports OAuth 2.0 for MCP servers that require it. When connecting to an OAuth-enabled server, Claude Code handles the entire authentication flow:

# Connect to an OAuth-enabled MCP server (interactive flow)
claude mcp add --transport http my-service https://my-service.example.com/mcp

# Pre-configure OAuth credentials for non-interactive setup
claude mcp add --transport http my-service https://my-service.example.com/mcp \
  --client-id "your-client-id" \
  --client-secret "your-client-secret" \
  --callback-port 8080
Feature Description
Interactive OAuth Use /mcp to trigger the browser-based OAuth flow
Pre-configured OAuth clients Built-in OAuth clients for common services like Notion, Stripe, and others (v2.1.30+)
Pre-configured credentials --client-id, --client-secret, --callback-port flags for automated setup
Token storage Tokens are stored securely in your system keychain
Step-up auth Supports step-up authentication for privileged operations
Discovery caching OAuth discovery metadata is cached for faster reconnections
Metadata override oauth.authServerMetadataUrl in .mcp.json to override default OAuth metadata discovery

Overriding OAuth Metadata Discovery

If your MCP server returns errors on the standard OAuth metadata endpoint (/.well-known/oauth-authorization-server) but exposes a working OIDC endpoint, you can tell Claude Code to fetch OAuth metadata from a specific URL. Set authServerMetadataUrl in the oauth object of your server config:

{
  "mcpServers": {
    "my-server": {
      "type": "http",
      "url": "https://mcp.example.com/mcp",
      "oauth": {
        "authServerMetadataUrl": "https://auth.example.com/.well-known/openid-configuration"
      }
    }
  }
}

The URL must use https://. This option requires Claude Code v2.1.64 or later.

Authentication Startup Notice and Dynamic-Header Refresh (v2.1.193)

  • Startup auth notice (v2.1.193+): At startup, Claude Code surfaces a notice listing any MCP servers that still need authentication, so a server that needs a login isn't left silently non-working.
  • headersHelper auto-refresh (v2.1.193+): If you supply custom auth via a headersHelper, the helper is re-invoked automatically when a server returns HTTP 401 or 403. Credentials refresh on the fly without a manual reconnect. See Use dynamic headers for custom authentication.
  • OAuth behind an authenticating proxy (v2.1.299+): pass the proxy's own header with --header, headers, or a headersHelper, keep Authorization out of those headers, and sign in with claude mcp login <name>. A configured Authorization header is used as the credential, with no fallback to OAuth.

Warning

(v2.1.238): A headersHelper in a project .mcp.json, and inline MCP servers in project or --add-dir agent files, now require that folder's trust dialog to have been accepted — including under claude -p. Such helpers also run without inherited credential environment variables; user-, managed-, and claude.ai-scope helpers run from the Claude config directory instead. A project config that relied on inherited credentials or on running untrusted will stop working until you accept the trust dialog and supply credentials another way.

Claude.ai MCP Connectors

MCP servers configured in your Claude.ai account are automatically available in Claude Code. This means any MCP connections you set up through the Claude.ai web interface will be accessible without additional configuration.

Claude.ai MCP connectors are also available in --print mode (v2.1.83+), enabling non-interactive and scripted usage.

Startup note (v2.1.117+): Concurrent connect is the default when both local and claude.ai MCP servers are configured (previously serial), reducing startup latency when multiple servers are in use.

To disable Claude.ai MCP servers in Claude Code, set the ENABLE_CLAUDEAI_MCP_SERVERS environment variable to false:

ENABLE_CLAUDEAI_MCP_SERVERS=false claude

Note: This feature is only available for users logged in with Claude.ai accounts.

MCP Setup Process

sequenceDiagram
    participant User
    participant Claude as Claude Code
    participant Config as Config File
    participant Service as External Service

    User->>Claude: Type /mcp
    Claude->>Claude: List available MCP servers
    Claude->>User: Show options
    User->>Claude: Select GitHub MCP
    Claude->>Config: Update configuration
    Config->>Claude: Activate connection
    Claude->>Service: Test connection
    Service-->>Claude: Authentication successful
    Claude->>User: ✅ MCP connected!

/mcp command

Type /mcp inside a session to list connected servers, trigger OAuth flows, and inspect connection state.

  • Since v2.1.121, MCP retries the initial connection up to 3 times on transient errors.
  • Since v2.1.128, /mcp displays the tool count for each connected server and visually flags servers reporting 0 tools so misconfigured servers stand out at a glance.

Tool search is on by default: MCP tools are deferred and discovered on demand, so their definitions don't fill the model context. Since v2.1.304 it also stays on behind a custom ANTHROPIC_BASE_URL gateway, which must forward defer_loading tool fields and tool_reference blocks; from v2.1.305 Claude Code retries a request the gateway rejects with a 400 or 422 without tool search. Set ENABLE_TOOL_SEARCH=false to load every tool upfront and skip those rejected requests. Before v2.1.304, tool search was off behind a gateway unless ENABLE_TOOL_SEARCH was true, auto, or auto:N.

Setting Value Description
ENABLE_TOOL_SEARCH (unset — default) All MCP tools deferred and loaded on demand
ENABLE_TOOL_SEARCH auto Threshold mode: tools load upfront until their definitions reach 10% of the context window, then all are deferred
ENABLE_TOOL_SEARCH auto:<N> Threshold mode with a custom percentage (0-100) — for example, auto:5 for 5%
ENABLE_TOOL_SEARCH true All MCP tools deferred
ENABLE_TOOL_SEARCH false Disabled; all tool descriptions sent in full

Note: Tool search requires a model that supports tool_reference blocks: Claude Opus 4, Claude Sonnet 4, Claude Haiku 4.5, and later models (Opus 4.5, Sonnet 4.5, Haiku 4.5 and later on Google Cloud's Agent Platform).

Bypassing Tool Search per Server (v2.1.121+)

If a particular MCP server's tools are needed on every turn, mark its configuration with "alwaysLoad": true to skip tool-search deferral and keep its tools always available:

{
  "mcpServers": {
    "always-on-tool": {
      "command": "node",
      "args": ["./tools/always.js"],
      "alwaysLoad": true
    }
  }
}

Use sparingly — every always-loaded tool consumes context that could otherwise be used for tool search to surface a more relevant tool.

To keep all of a server's tools behind tool search, set "alwaysLoad": false in that server's entry (v2.1.287+). That includes tools the server's author has marked to load up front; if you leave alwaysLoad out, those marked tools load up front. Server authors mark an individual tool by setting "anthropic/alwaysLoad" in that tool's _meta object, and the server-level alwaysLoad setting in your configuration can override it.

Server authors: mark tools that are safe to call twice with the idempotentHint or readOnlyHint annotation in their tools/list entry. Since v2.1.307, Claude Code repeats a call that was pending when an HTTP or claude.ai connector connection closed only for those tools; other calls fail with connection closed before the tool call was answered.

Dynamic Tool Updates

Claude Code supports MCP list_changed notifications. When an MCP server dynamically adds, removes, or modifies its available tools, Claude Code receives the update and adjusts its tool list automatically -- no reconnection or restart required.

MCP Apps

MCP Apps is the first official MCP extension, enabling MCP tool calls to return interactive UI components that render directly in the chat interface. Instead of plain text responses, MCP servers can deliver rich dashboards, forms, data visualizations, and multi-step workflows -- all displayed inline without leaving the conversation.

MCP Elicitation

MCP servers can request structured input from the user via interactive dialogs (v2.1.49+). This allows an MCP server to ask for additional information mid-workflow -- for example, prompting for a confirmation, selecting from a list of options, or filling in required fields -- adding interactivity to MCP server interactions.

If a server built on Java MCP SDK 0.17.0 or older refuses to connect with "rejected Claude Code's elicitation capability", upgrade it to Java MCP SDK 0.17.1+ or add "bareElicitationCapability": true to its entry (stdio, sse, http and ws; v2.1.281+), which limits it to form-mode elicitation.

Tool Description and Instruction Cap

Claude Code truncates each MCP tool description and each server's instructions to keep verbose servers from bloating context. The default limits are 4,096 characters for server instructions and for descriptions of tools that load up front (v2.1.296; 2,048 from v2.1.84 until then), and 16,384 characters for descriptions Claude loads through tool search (v2.1.295). Since v2.1.280, CLAUDE_CODE_MAX_MCP_DESCRIPTION_LENGTH overrides them: the number you set replaces both limits (8192 raises the shorter one and lowers the longer one). Since v2.1.299, descriptions and instructions from Anthropic's first-party MCP servers at api.anthropic.com reach Claude in full. Put critical details near the start of a description.

MCP Prompts as Slash Commands

MCP servers can expose prompts that appear as slash commands in Claude Code. Prompts are accessible using the naming convention:

/mcp__<server>__<prompt>

For example, if a server named github exposes a prompt called review, you can invoke it as /mcp__github__review.

Server Deduplication

When the same MCP server is defined at multiple scopes (local, project, user), the local configuration takes precedence. This allows you to override project-level or user-level MCP settings with local customizations without conflicts.

Recent Lifecycle Fixes (v2.1.136)

Two long-standing MCP lifecycle bugs were fixed in v2.1.136 — worth upgrading for if you run multi-server setups:

  • MCP servers persist across /clear: Servers configured via .mcp.json, plugins, or claude.ai connectors no longer disappear after /clear in VS Code, JetBrains, or the Agent SDK. Earlier versions silently dropped them and required a restart.
  • OAuth refresh-token concurrent-refresh fix: Multi-server OAuth setups no longer lose refresh tokens when several servers race to refresh simultaneously. This eliminates the "every morning I have to re-auth" pattern that affected setups with multiple OAuth-protected MCP servers.

MCP Resources via @ Mentions

You can reference MCP resources directly in your prompts using the @ mention syntax:

@server-name:protocol://resource/path

For example, to reference a specific database resource:

@database:postgres://mydb/users

This allows Claude to fetch and include MCP resource content inline as part of the conversation context.

MCP Scopes

MCP configurations can be stored at different scopes with varying levels of sharing:

Scope Flag Location Description Shared With Requires Approval
Local (default) --scope local ~/.claude.json (under project path) Private to current user, current project only (was called project in older versions) Just you No
Project --scope project .mcp.json Checked into git repository Team members Yes (first use)
User --scope user ~/.claude.json Available across all projects (was called global in older versions) Just you No

Select a scope when adding a server with --scope (short form -s). Omit it and Claude Code uses local:

# Project scope — writes to .mcp.json so the team shares it
claude mcp add --scope project --transport http github https://api.githubcopilot.com/mcp/ --header "Authorization: Bearer YOUR_GITHUB_PAT"

# User scope — available in every project
claude mcp add --scope user --transport stdio memory -- npx @modelcontextprotocol/server-memory

Using Project Scope

Store project-specific MCP configurations in .mcp.json:

{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/",
      "headers": {
        "Authorization": "Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}"
      }
    }
  }
}

Team members will see an approval prompt on first use of project MCPs. In an untrusted workspace, servers that a repo self-approved via a committed .claude/settings.json are not auto-spawned by claude mcp list/get — they show ⏸ Pending approval until you accept the trust dialog, and enableAllProjectMcpServers is ignored in an untrusted folder (v2.1.196).

MCP Configuration Management

Adding MCP Servers

# Add HTTP-based server
claude mcp add --transport http github https://api.githubcopilot.com/mcp/ --header "Authorization: Bearer YOUR_GITHUB_PAT"

# Add local stdio server
claude mcp add --transport stdio database -- npx @company/db-server

# List all MCP servers
claude mcp list

# Get details on specific server
claude mcp get github

# Remove an MCP server
claude mcp remove github

# Reset project-specific approval choices
claude mcp reset-project-choices

# Authenticate an MCP server from the CLI (v2.1.186+)
claude mcp login github

# Sign out of an MCP server (v2.1.186+)
claude mcp logout github

# Import from Claude Desktop
claude mcp add-from-claude-desktop

# Add a server from a JSON blob (useful for scripted setup)
claude mcp add-json events-server '{"type":"stdio","command":"npx","args":["@modelcontextprotocol/server-events"]}'

Note

: In JSON configs — .mcp.json, ~/.claude.json, or claude mcp add-json — the type field accepts streamable-http as an alias for http. The MCP specification uses the name streamable-http for this transport, so configurations copied from a server's own documentation work unmodified.

Since v2.1.238, claude mcp list and claude mcp get show disabled servers as ⊘ Disabled without connecting to them for a health check. A server one of your organization's policies refuses shows as ✘ Blocked by enterprise managed policy in both commands; one filtered out by an allowlist, denylist, or other managed MCP restriction is hidden rather than listed.

claude mcp login <name> / claude mcp logout <name> are the non-interactive equivalent of the OAuth flow in the /mcp menu — authenticate or sign out without opening it. Add --no-browser to login to complete OAuth over SSH or in a headless session (it redirects the flow through stdin). claude mcp remove deletes the stored OAuth tokens but doesn't revoke them; to revoke them where the authorization server supports it, run claude mcp logout <name> before claude mcp remove <name>.

Available MCP Servers Table

MCP Server Purpose Common Tools Auth Real-time
Filesystem File operations read, write, delete OS permissions ✅ Yes
GitHub Repository management list_prs, create_issue, push OAuth ✅ Yes
Slack Team communication send_message, list_channels Token ✅ Yes
Database SQL queries query, insert, update Credentials ✅ Yes
Google Docs Document access read, write, share OAuth ✅ Yes
Asana Project management create_task, update_status API Key ✅ Yes
Stripe Payment data list_charges, create_invoice API Key ✅ Yes
Memory Persistent memory store, retrieve, delete Local ❌ No

Practical Examples

Example 1: GitHub MCP Configuration

File: .mcp.json (project root)

{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/",
      "headers": {
        "Authorization": "Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}"
      }
    }
  }
}

Available GitHub MCP Tools:

Pull Request Management

  • list_prs - List all PRs in repository
  • get_pr - Get PR details including diff
  • create_pr - Create new PR
  • update_pr - Update PR description/title
  • merge_pr - Merge PR to main branch
  • review_pr - Add review comments

Example request:

/mcp__github__get_pr 456

# Returns:
Title: Add dark mode support
Author: @alice
Description: Implements dark theme using CSS variables
Status: OPEN
Reviewers: @bob, @charlie

Issue Management

  • list_issues - List all issues
  • get_issue - Get issue details
  • create_issue - Create new issue
  • close_issue - Close issue
  • add_comment - Add comment to issue

Repository Information

  • get_repo_info - Repository details
  • list_files - File tree structure
  • get_file_content - Read file contents
  • search_code - Search across codebase

Commit Operations

  • list_commits - Commit history
  • get_commit - Specific commit details
  • create_commit - Create new commit

Setup:

export GITHUB_PERSONAL_ACCESS_TOKEN="your_github_token"
# Or use the CLI to add directly:
claude mcp add --transport http github https://api.githubcopilot.com/mcp/ --header "Authorization: Bearer YOUR_GITHUB_PAT"

Environment Variable Expansion in Configuration

MCP configurations support environment variable expansion with fallback defaults. The ${VAR} and ${VAR:-default} syntax works in the following fields: command, args, env, url, and headers.

{
  "mcpServers": {
    "api-server": {
      "type": "http",
      "url": "${API_BASE_URL:-https://api.example.com}/mcp",
      "headers": {
        "Authorization": "Bearer ${API_KEY}",
        "X-Custom-Header": "${CUSTOM_HEADER:-default-value}"
      }
    },
    "local-server": {
      "command": "${MCP_BIN_PATH:-npx}",
      "args": ["${MCP_PACKAGE:-@company/mcp-server}"],
      "env": {
        "DB_URL": "${DATABASE_URL:-postgresql://localhost/dev}"
      }
    }
  }
}

Variables are expanded at runtime:

  • ${VAR} - Uses environment variable; if it is unset (and has no default), the server still loads with the literal ${VAR}, and claude mcp list and /mcp warn about the missing variable
  • ${VAR:-default} - Uses environment variable, falls back to default if not set. A variable set to an empty string counts as set and expands to empty (e.g. url becomes /mcp); unset it to get the default

Example 2: Database MCP Setup

Configuration:

{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["-y", "@bytebase/dbhub", "--dsn", "${DATABASE_URL}"]
    }
  }
}

Example Usage:

User: Fetch all users with more than 10 orders

Claude: I'll query your database to find that information.

# Using MCP database tool:
SELECT u.*, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id
HAVING COUNT(o.id) > 10
ORDER BY order_count DESC;

# Results:
- Alice: 15 orders
- Bob: 12 orders
- Charlie: 11 orders

Setup:

export DATABASE_URL="postgresql://user:pass@localhost/mydb"
claude mcp add --transport stdio database -- npx -y @bytebase/dbhub \
  --dsn "$DATABASE_URL"

Warning

: This setup gives Claude write access. DBHub's execute_sql tool runs any SQL it receives, including UPDATE, DELETE, and DROP, unless you turn on read-only mode. Use a local or throwaway database, never production.

Read-only setup (recommended):

Create a database user that can only run SELECT (PostgreSQL example):

CREATE ROLE claude_readonly LOGIN PASSWORD 'change-me';
GRANT CONNECT ON DATABASE mydb TO claude_readonly;
GRANT USAGE ON SCHEMA public TO claude_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO claude_readonly;

Turn on read-only mode in a dbhub.toml. The old --readonly flag no longer works. DBHub fills in ${DATABASE_URL} from your environment, so no credentials go in the file:

[[sources]]
id = "default"
dsn = "${DATABASE_URL}"

[[tools]]
name = "execute_sql"
source = "default"
readonly = true

Then point DBHub at the file instead of passing --dsn. Remove the write-access database server you added above first, because Claude Code won't add a second server with the same name:

# Replace the write-access server added above
claude mcp remove database
export DATABASE_URL="postgresql://claude_readonly:change-me@localhost/mydb"
claude mcp add --transport stdio database -- npx -y @bytebase/dbhub \
  --config "$PWD/dbhub.toml"

Read-only mode filters SQL text and has had bypasses in the past (fixed in DBHub 0.22.6), so the SELECT-only user is what really protects your data. See DBHub read-only mode.

Example 3: Multi-MCP Workflow

Scenario: Daily Report Generation

# Daily Report Workflow using Multiple MCPs

## Setup
1. GitHub MCP - fetch PR metrics
2. Database MCP - query sales data
3. Slack MCP - post report
4. Filesystem MCP - save report

## Workflow

### Step 1: Fetch GitHub Data
/mcp__github__list_prs completed:true last:7days

Output:
- Total PRs: 42
- Average merge time: 2.3 hours
- Review turnaround: 1.1 hours

### Step 2: Query Database
SELECT COUNT(*) as sales, SUM(amount) as revenue
FROM orders
WHERE created_at > NOW() - INTERVAL '1 day'

Output:
- Sales: 247
- Revenue: $12,450

### Step 3: Generate Report
Combine data into HTML report

### Step 4: Save to Filesystem
Write report.html to /reports/

### Step 5: Post to Slack
Send summary to #daily-reports channel

Final Output:
✅ Report generated and posted
📊 47 PRs merged this week
💰 $12,450 in daily sales

Setup:

export GITHUB_PERSONAL_ACCESS_TOKEN="your_github_token"
export DATABASE_URL="postgresql://user:pass@localhost/mydb"
export SLACK_BOT_TOKEN="your_slack_bot_token"
export SLACK_TEAM_ID="your_slack_team_id"
# Add each MCP server via the CLI or configure them in .mcp.json

Example 4: Filesystem MCP Operations

Configuration:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-filesystem", "/home/user/projects"]
    }
  }
}

Available Operations:

Operation Command Purpose
List files ls ~/projects Show directory contents
Read file cat src/main.ts Read file contents
Write file create docs/api.md Create new file
Edit file edit src/app.ts Modify file
Search grep "async function" Search in files
Delete rm old-file.js Delete file

Setup:

# Use the CLI to add directly:
claude mcp add --transport stdio filesystem -- npx @modelcontextprotocol/server-filesystem /home/user/projects

MCP vs Memory: Decision Matrix

graph TD
    A["Need external data?"]
    A -->|No| B["Use Memory"]
    A -->|Yes| C["Does it change frequently?"]
    C -->|No/Rarely| B
    C -->|Yes/Often| D["Use MCP"]

    B -->|Stores| E["Preferences<br/>Context<br/>History"]
    D -->|Accesses| F["Live APIs<br/>Databases<br/>Services"]

    style A fill:#fff3e0,stroke:#333,color:#333
    style B fill:#e1f5fe,stroke:#333,color:#333
    style C fill:#fff3e0,stroke:#333,color:#333
    style D fill:#f3e5f5,stroke:#333,color:#333
    style E fill:#e8f5e9,stroke:#333,color:#333
    style F fill:#e8f5e9,stroke:#333,color:#333

Request/Response Pattern

sequenceDiagram
    participant App as Claude
    participant MCP as MCP Server
    participant DB as Database

    App->>MCP: Request: "SELECT * FROM users WHERE id=1"
    MCP->>DB: Execute query
    DB-->>MCP: Result set
    MCP-->>App: Return parsed data
    App->>App: Process result
    App->>App: Continue task

    Note over MCP,DB: Real-time access<br/>No caching

Environment Variables

Store sensitive credentials in environment variables:

# ~/.bashrc or ~/.zshrc
export GITHUB_PERSONAL_ACCESS_TOKEN="ghp_xxxxxxxxxxxxx"
export DATABASE_URL="postgresql://user:pass@localhost/mydb"
export SLACK_BOT_TOKEN="your-slack-bot-token"
export SLACK_TEAM_ID="T0000000000"

Then reference them in MCP config:

{
  "env": {
    "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_PERSONAL_ACCESS_TOKEN}"
  }
}

Claude as MCP Server (claude mcp serve)

Claude Code itself can act as an MCP server for other applications. This enables external tools, editors, and automation systems to leverage Claude's capabilities through the standard MCP protocol.

# Start Claude Code as an MCP server on stdio
claude mcp serve

Other applications can then connect to this server as they would any stdio-based MCP server. For example, to add Claude Code as an MCP server in another Claude Code instance:

claude mcp add --transport stdio claude-agent -- claude mcp serve

This is useful for building multi-agent workflows where one Claude instance orchestrates another.

Managed MCP Configuration (Enterprise)

For enterprise deployments, IT administrators enforce MCP server policy through two separate mechanisms: a managed-mcp.json file that deploys a fixed set of servers with exclusive control, and the allowedMcpServers / deniedMcpServers settings keys that filter which configured servers may load.

Location:

  • macOS: /Library/Application Support/ClaudeCode/managed-mcp.json
  • Linux and WSL: /etc/claude-code/managed-mcp.json
  • Windows: C:\Program Files\ClaudeCode\managed-mcp.json

managed-mcp.json uses the same format as a project .mcp.json — a top-level mcpServers map. It deploys servers; it does not filter them:

{
  "mcpServers": {
    "example-remote": {
      "type": "http",
      "url": "https://mcp.example.com/mcp"
    },
    "company-internal": {
      "type": "stdio",
      "command": "/usr/local/bin/company-mcp-server",
      "args": ["--config", "/etc/company/mcp-config.json"]
    }
  }
}

Any user on the machine can read this file, so never put credentials in an env block. Use ${VAR} expansion, OAuth, or headersHelper instead.

Note (v2.1.305): Servers in managed-mcp.json need no allowedMcpServers entry. The allowlist checks a managed server only when it uses ${VAR} expansion outside env; before v2.1.305 it also checked servers that used ${VAR} only in env. If you relied on allowedMcpServers to keep such a server off, it now loads on upgrade with no prompt; add a deniedMcpServers entry for it instead.

Filtering: allowlists and denylists

allowedMcpServers, deniedMcpServers, and allowAllClaudeAiMcps are settings keys, not fields of managed-mcp.json. Put them in a managed settings source — server-managed settings, managed-settings.json, an MDM profile, or the registry — for them to be enforceable:

  • allowedMcpServers -- allowlist of permitted servers. Set allowManagedMcpServersOnly: true alongside it, in the same managed source, or allowlists merge from every scope and a user can broaden yours.
  • deniedMcpServers -- denylist of blocked servers. Merges from every scope regardless.
  • allowAllClaudeAiMcps -- loads claude.ai cloud connectors alongside a deployed managed-mcp.json (v2.1.149+). Read only from admin-controlled policy tiers.

Each entry is an object with a single key:

Key Matches
serverUrl A remote server URL, exact or with * wildcards
serverCommand The exact command and arguments that start a stdio server, as an array — every argument, in order
serverName The user-assigned label. Exact match only; wildcards are not expanded

Example configuration:

{
  "allowedMcpServers": [
    { "serverUrl": "https://mcp.example.com/*" },
    { "serverCommand": ["/usr/local/bin/company-mcp-server", "--config", "/etc/company/mcp-config.json"] }
  ],
  "deniedMcpServers": [
    { "serverName": "untrusted-server" },
    { "serverUrl": "http://*" }
  ],
  "allowManagedMcpServersOnly": true
}

A third managed setting, managedMcpServers (v2.1.259+), lets an organization provide HTTP/SSE MCP servers to every user. Entries use the same shape as .mcp.json; entries that name a command to run are skipped.

Note: When both allowedMcpServers and deniedMcpServers match a server, the deny rule takes precedence.

Plugin-Provided MCP Servers

Plugins can bundle their own MCP servers, making them available automatically when the plugin is installed. Plugin-provided MCP servers can be defined in two ways:

  1. Standalone .mcp.json -- Place a .mcp.json file in the plugin root directory
  2. Inline in plugin.json -- Define MCP servers directly within the plugin manifest

Use the ${CLAUDE_PLUGIN_ROOT} variable to reference paths relative to the plugin's installation directory:

{
  "mcpServers": {
    "plugin-tools": {
      "command": "node",
      "args": ["${CLAUDE_PLUGIN_ROOT}/dist/mcp-server.js"],
      "env": {
        "CONFIG_PATH": "${CLAUDE_PLUGIN_ROOT}/config.json"
      }
    }
  }
}

Subagent-Scoped MCP

MCP servers can be defined inline within agent frontmatter using the mcpServers: key, scoping them to a specific subagent rather than the entire project. This is useful when an agent needs access to a particular MCP server that other agents in the workflow do not require.

---
name: my-tool-agent
description: Uses my-tool for specialized operations
mcpServers:
  my-tool:
    type: http
    url: https://my-tool.example.com/mcp
---

You are an agent with access to my-tool for specialized operations.

Subagent-scoped MCP servers are only available within that agent's execution context and are not shared with the parent or sibling agents.

MCP Output Limits

Claude Code enforces limits on MCP tool output to prevent context overflow:

Limit Threshold Behavior
Warning 10,000 tokens A warning is displayed that the output is large
Default max 25,000 tokens Larger output is saved to a file, and the file path goes into the conversation instead
Disk persistence 50,000 characters Tool results exceeding 50K characters are persisted to disk

The maximum output limit is configurable via the MAX_MCP_OUTPUT_TOKENS environment variable:

# Increase the max output to 50,000 tokens
export MAX_MCP_OUTPUT_TOKENS=50000

Auto-Backgrounding Long-Running Tool Calls (v2.1.212)

MCP tool calls that run longer than 2 minutes now move to the background automatically, so the session stays usable instead of blocking on a slow tool. The threshold is configurable, and the behavior can be tuned or disabled, via CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS:

# Change the auto-background threshold to 5 minutes (300,000ms)
export CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS=300000

Set it to 0 to turn automatic backgrounding off; CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 turns it off together with background commands and background subagents. To cap how long a call may run, add a per-server timeout in milliseconds (a hard wall-clock limit) or set MCP_TOOL_TIMEOUT across servers (default about 28 hours).

MCP Tasks (public beta, v2.1.304+)

A server that supports the MCP tasks extension can run a long job itself: Claude's tool call returns as soon as the server accepts the job, the footer shows a count such as 1 MCP task, and Claude gets the result when the job ends. Stop one in /tasks with x. A task on a remote server keeps running after you exit; resume the same session to follow it again. Tasks need protocol revision 2026-07-28, feature-flag fetching (so not Bedrock, Vertex, Foundry or telemetry off) and a terminal CLI, Agent SDK or GitHub Actions session. A non-interactive run gets them only from the Agent SDK or claude -p --input-format stream-json, and either needs CLAUDE_AUTO_BACKGROUND_TASKS=1 (a plain claude -p "<prompt>" doesn't get them). VS Code and the desktop app don't get them, and calls from subagents never become tasks. To make Claude wait for a task's result, set CLAUDE_CODE_DISABLE_MCP_TASK_BACKGROUND=1 (or CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS=0 to wait for every MCP call).

Solving Context Bloat with Code Execution

As MCP adoption scales, connecting to dozens of servers with hundreds or thousands of tools creates a significant challenge: context bloat. This is arguably the biggest problem with MCP at scale, and Anthropic's engineering team has proposed an elegant solution — using code execution instead of direct tool calls.

Source: Code Execution with MCP: Building More Efficient Agents — Anthropic Engineering Blog

The Problem: Two Sources of Token Waste

1. Tool definitions overload the context window

Most MCP clients load all tool definitions upfront. When connected to thousands of tools, the model must process hundreds of thousands of tokens before it even reads the user's request.

2. Intermediate results consume additional tokens

Every intermediate tool result passes through the model's context. Consider transferring a meeting transcript from Google Drive to Salesforce — the full transcript flows through context twice: once when reading it, and again when writing it to the destination. A 2-hour meeting transcript could mean 50,000+ extra tokens.

graph LR
    A["Model"] -->|"Tool Call: getDocument"| B["MCP Server"]
    B -->|"Full transcript (50K tokens)"| A
    A -->|"Tool Call: updateRecord<br/>(re-sends full transcript)"| B
    B -->|"Confirmation"| A

    style A fill:#ffcdd2,stroke:#333,color:#333
    style B fill:#f3e5f5,stroke:#333,color:#333

The Solution: MCP Tools as Code APIs

Instead of passing tool definitions and results through the context window, the agent writes code that calls MCP tools as APIs. The code runs in a sandboxed execution environment, and only the final result returns to the model.

graph LR
    A["Model"] -->|"Writes code"| B["Code Execution<br/>Environment"]
    B -->|"Calls tools directly"| C["MCP Servers"]
    C -->|"Data stays in<br/>execution env"| B
    B -->|"Only final result<br/>(minimal tokens)"| A

    style A fill:#c8e6c9,stroke:#333,color:#333
    style B fill:#e1f5fe,stroke:#333,color:#333
    style C fill:#f3e5f5,stroke:#333,color:#333

How It Works

MCP tools are presented as a file tree of typed functions:

servers/
├── google-drive/
│   ├── getDocument.ts
│   └── index.ts
├── salesforce/
│   ├── updateRecord.ts
│   └── index.ts
└── ...

Each tool file contains a typed wrapper:

// ./servers/google-drive/getDocument.ts
import { callMCPTool } from "../../../client.js";

interface GetDocumentInput {
  documentId: string;
}

interface GetDocumentResponse {
  content: string;
}

export async function getDocument(
  input: GetDocumentInput
): Promise<GetDocumentResponse> {
  return callMCPTool<GetDocumentResponse>(
    'google_drive__get_document', input
  );
}

The agent then writes code to orchestrate the tools:

import * as gdrive from './servers/google-drive';
import * as salesforce from './servers/salesforce';

// Data flows directly between tools — never through the model
const transcript = (
  await gdrive.getDocument({ documentId: 'abc123' })
).content;

await salesforce.updateRecord({
  objectType: 'SalesMeeting',
  recordId: '00Q5f000001abcXYZ',
  data: { Notes: transcript }
});

Result: Token usage drops from ~150,000 to ~2,000 — a 98.7% reduction.

Key Benefits

Benefit Description
Progressive Disclosure Agent browses the filesystem to load only the tool definitions it needs, instead of all tools upfront
Context-Efficient Results Data is filtered/transformed in the execution environment before returning to the model
Powerful Control Flow Loops, conditionals, and error handling run in code without round-tripping through the model
Privacy Preservation Intermediate data (PII, sensitive records) stays in the execution environment; never enters the model context
State Persistence Agents can save intermediate results to files and build reusable skill functions

Example: Filtering Large Datasets

// Without code execution — all 10,000 rows flow through context
// TOOL CALL: gdrive.getSheet(sheetId: 'abc123')
//   -> returns 10,000 rows in context

// With code execution — filter in the execution environment
const allRows = await gdrive.getSheet({ sheetId: 'abc123' });
const pendingOrders = allRows.filter(
  row => row["Status"] === 'pending'
);
console.log(`Found ${pendingOrders.length} pending orders`);
console.log(pendingOrders.slice(0, 5)); // Only 5 rows reach the model

Example: Loop Without Round-Tripping

// Poll for a deployment notification — runs entirely in code
let found = false;
while (!found) {
  const messages = await slack.getChannelHistory({
    channel: 'C123456'
  });
  found = messages.some(
    m => m.text.includes('deployment complete')
  );
  if (!found) await new Promise(r => setTimeout(r, 5000));
}
console.log('Deployment notification received');

Trade-offs to Consider

Code execution introduces its own complexity. Running agent-generated code requires:

  • A secure sandboxed execution environment with appropriate resource limits
  • Monitoring and logging of executed code
  • Additional infrastructure overhead compared to direct tool calls

The benefits — reduced token costs, lower latency, improved tool composition — should be weighed against these implementation costs. For agents with only a few MCP servers, direct tool calls may be simpler. For agents at scale (dozens of servers, hundreds of tools), code execution is a significant improvement.

MCPorter: A Runtime for MCP Tool Composition

MCPorter is a TypeScript runtime and CLI toolkit that makes calling MCP servers practical without boilerplate — and helps reduce context bloat through selective tool exposure and typed wrappers.

What it solves: Instead of loading all tool definitions from all MCP servers upfront, MCPorter lets you discover, inspect, and call specific tools on demand — keeping your context lean.

Key features:

Feature Description
Zero-config discovery Auto-discovers MCP servers from Cursor, Claude, Codex, or local configs
Typed tool clients mcporter emit-ts generates .d.ts interfaces and ready-to-run wrappers
Composable API createServerProxy() exposes tools as camelCase methods with .text(), .json(), .markdown() helpers
CLI generation mcporter generate-cli converts any MCP server into a standalone CLI with --include-tools / --exclude-tools filtering
Parameter hiding Optional parameters stay hidden by default, reducing schema verbosity

Installation:

npx mcporter list          # No install required — discover servers instantly
pnpm add mcporter          # Add to a project
brew install steipete/tap/mcporter  # macOS via Homebrew

Example — composing tools in TypeScript:

import { createRuntime, createServerProxy } from "mcporter";

const runtime = await createRuntime();
const gdrive = createServerProxy(runtime, "google-drive");
const salesforce = createServerProxy(runtime, "salesforce");

// Data flows between tools without passing through the model context
const doc = await gdrive.getDocument({ documentId: "abc123" });
await salesforce.updateRecord({
  objectType: "SalesMeeting",
  recordId: "00Q5f000001abcXYZ",
  data: { Notes: doc.text() }
});

Example — CLI tool call:

# Call a specific tool directly
npx mcporter call linear.create_comment issueId:ENG-123 body:'Looks good!'

# List available servers and tools
npx mcporter list

MCPorter complements the code-execution approach described above by providing the runtime infrastructure for calling MCP tools as typed APIs — making it straightforward to keep intermediate data out of the model context.

Best Practices

Security Considerations

Do's ✅

  • Use environment variables for all credentials
  • Rotate tokens and API keys regularly (monthly recommended)
  • Use read-only tokens when possible
  • Limit MCP server access scope to minimum required
  • Monitor MCP server usage and access logs
  • Use OAuth for external services when available
  • Implement rate limiting on MCP requests
  • Test MCP connections before production use
  • Document all active MCP connections
  • Keep MCP server packages updated

Don'ts ❌

  • Don't hardcode credentials in config files
  • Don't commit tokens or secrets to git
  • Don't share tokens in team chats or emails
  • Don't use personal tokens for team projects
  • Don't grant unnecessary permissions
  • Don't ignore authentication errors
  • Don't expose MCP endpoints publicly
  • Don't run MCP servers with root/admin privileges
  • Don't cache sensitive data in logs
  • Don't disable authentication mechanisms

Configuration Best Practices

  1. Version Control: Keep .mcp.json in git but use environment variables for secrets
  2. Least Privilege: Grant minimum permissions needed for each MCP server
  3. Isolation: Run different MCP servers in separate processes when possible
  4. Monitoring: Log all MCP requests and errors for audit trails
  5. Testing: Test all MCP configurations before deploying to production

Performance Tips

  • Cache frequently accessed data at the application level
  • Use MCP queries that are specific to reduce data transfer
  • Monitor response times for MCP operations
  • Consider rate limiting for external APIs
  • Use batching when performing multiple operations

Installation Instructions

Prerequisites

  • Node.js and npm installed
  • Claude Code CLI installed
  • API tokens/credentials for external services

Step-by-Step Setup

  1. Add your first MCP server using the CLI (example: GitHub):
claude mcp add --transport http github https://api.githubcopilot.com/mcp/ --header "Authorization: Bearer YOUR_GITHUB_PAT"

Or create a .mcp.json file in your project root:

{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/",
      "headers": {
        "Authorization": "Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}"
      }
    }
  }
}
  1. Set environment variables:
export GITHUB_PERSONAL_ACCESS_TOKEN="your_github_personal_access_token"
  1. Test the connection:
claude /mcp
  1. Use MCP tools:
/mcp__github__list_prs
/mcp__github__create_issue "Title" "Description"

Installation for Specific Services

GitHub MCP:

npm install -g @modelcontextprotocol/server-github

Database MCP:

npm install -g @bytebase/dbhub

Filesystem MCP:

npm install -g @modelcontextprotocol/server-filesystem

Slack MCP (deprecated package):

npm install -g @modelcontextprotocol/server-slack

Troubleshooting

Start With the Error Output (v2.1.219+)

If a server won't connect, run claude mcp list (or /mcp inside a session) before changing anything. Claude Code now prints the HTTP status code and the server's error text next to the failing server, so you get 401 Unauthorized or 404 Not Found instead of a generic "failed to connect":

# Shows connection status plus HTTP status and error text for failures
claude mcp list

Read the status first — it tells you which fix applies:

  • 401 / 403 → bad or expired credentials; re-authenticate with claude mcp login <name>
  • 404 → wrong URL (a missing /mcp or /sse path suffix is the usual cause)
  • 5xx / timeout → the remote server is down; see Connection Timeout

Hidden Whitespace in Config Values (v2.1.219+)

Claude Code warns when an MCP config value has leading or trailing whitespace. This is a common and hard-to-spot cause of auth failures: a token copy-pasted from a browser or a chat message often carries a trailing space or newline, which gets sent verbatim in the Authorization header and fails as an invalid credential.

If you see this warning, re-check the value in .mcp.json (or the env var it expands from) and trim it:

# Reveals hidden leading/trailing whitespace between the delimiters
printf '[%s]\n' "$GITHUB_PERSONAL_ACCESS_TOKEN"

Skipped Servers in Headless Runs (v2.1.219+)

Servers passed via --mcp-config that fail config validation are skipped rather than aborting the run, so a headless script can appear to work while missing half its tools. Claude Code now reports which ones were dropped:

  • Headless / -p runs: the stream-json init event carries an mcp_server_errors field listing every skipped entry. Check it before trusting the run's output.
  • Interactive terminal runs: the same problem is printed as a startup warning when the session begins.
# Inspect skipped --mcp-config entries in a headless run
claude -p "list my tools" --mcp-config ./servers.json \
  --output-format stream-json --verbose \
  | jq -r 'select(.type == "system" and .subtype == "init") | .mcp_server_errors'

MCP Server Not Found

# Verify MCP server is installed
npm list -g @modelcontextprotocol/server-github

# Install if missing
npm install -g @modelcontextprotocol/server-github

Authentication Failed

# Verify environment variable is set
echo $GITHUB_PERSONAL_ACCESS_TOKEN

# Re-export if needed
export GITHUB_PERSONAL_ACCESS_TOKEN="your_token"

# Verify token has correct permissions
# Check GitHub token scopes at: https://github.com/settings/tokens

Connection Timeout

  • Check network connectivity: ping api.github.com
  • Verify API endpoint is accessible
  • Check rate limits on API
  • Raise the server's timeout (milliseconds) in its config entry, or MCP_TOOL_TIMEOUT for all servers
  • Check for firewall or proxy issues

MCP Server Crashes

  • Check MCP server logs: ~/.claude/logs/
  • Verify all environment variables are set
  • Ensure proper file permissions
  • Try reinstalling the MCP server package
  • Check for conflicting processes on the same port

Memory vs MCP

  • Memory: Stores persistent, unchanging data (preferences, context, history)
  • MCP: Accesses live, changing data (APIs, databases, real-time services)

When to Use Each

  • Use Memory for: User preferences, conversation history, learned context
  • Use MCP for: Current GitHub issues, live database queries, real-time data

Integration with Other Claude Features

  • Combine MCP with Memory for rich context
  • Use MCP tools in prompts for better reasoning
  • Leverage multiple MCPs for complex workflows

Additional Resources


Last Updated: November 1, 2026 Claude Code Version: 2.1.316 Sources: