claude-code-mcp 标志

claude-code-mcp

社区
xihuai18

Make Claude Code serve as a MCP server with minimal tools.

发布者xihuai18
代码仓库claude-code-mcp
语言TypeScript
复刻数
6
星标数
20
可用工具
4
传输类型stdio
分类
许可协议MIT
链接
  • 将工具接入 AI 工作流

    claude-code-mcp 提供 MCP 功能,可供兼容的 AI 客户端和智能体使用。

  • 4 个可用工具

    浏览下方可调用的操作;如果服务器提供了名称和描述,也会一并显示。

  • 可直接复制的配置

    使用安装配置片段,在您首选的 MCP 客户端中配置此服务器。

  • 开源社区热度

    关联的代码仓库有 20 个 Star 和 6 个 Fork。

claude-code-mcp

npm version license node

MCP server that wraps Claude Code (Claude Agent SDK) as tools, enabling any MCP client to invoke Claude Code for autonomous coding tasks. Designed for local use — the MCP server and client are expected to run on the same machine. It works especially well with OpenCode/Codex-style clients that prefer async polling and explicit permission decisions.

Inspired by the Codex MCP design philosophy — minimum tools, maximum capability.

This package is CLI-first: it is intended to run as an MCP server process (npx @leo000001/claude-code-mcp), not as a stable programmatic library API.

Visibility Boundary

Not every piece of documentation below is visible to an MCP-connected coding agent.

  • Usually visible to the agent: MCP tool names, tool descriptions, input field descriptions, and MCP resources that the client explicitly reads.
  • Not safe to assume visible: this README.md, docs/DESIGN.md, AGENTS.md, and other repository files unless the client or orchestrator copies that content into the model context.
  • Authoring rule: keep protocol-critical calling rules in tool descriptions and MCP resources first; mirror them in README for humans, but do not rely on README alone.

In practice, the most important runtime rules are duplicated in the claude_code* tool descriptions and the quickstart / gotchas / compat-report resources so async polling clients can succeed even when they never read this file.

Features

  • 4 tools covering the full agent lifecycle: start, continue, check/poll, manage
  • Read-only MCP resources for server info, internal tool catalog, and compatibility diagnostics
  • Session management with resume and fork support
  • Local settings loaded by default — automatically reads ~/.claude/settings.json, .claude/settings.json, .claude/settings.local.json, and CLAUDE.md so the agent behaves like your local Claude Code CLI
  • Async permissions — allow/deny lists + explicit approvals via claude_code_check
  • Custom subagents — define specialized agents per session
  • Cost tracking — per-session turn and cost accounting
  • Session cancellation via AbortController
  • Auto-cleanup — 30-minute idle timeout for expired sessions
  • Security — callers control tool permissions via allow/deny lists + explicit permission decisions

See CHANGELOG.md for release history.

Prerequisites

  • Node.js >= 18 is required.
  • Same-platform deployment — this MCP server is designed to run on the same machine as the MCP client. It communicates via stdio (child process), reads local Claude configuration files from ~/.claude/, and accesses the local file system directly. Remote deployment is not supported.

This MCP server uses the @anthropic-ai/claude-agent-sdk package, which bundles its own Claude Code CLI (cli.js). When no explicit pathToClaudeCodeExecutable is provided, this server now prefers a detected local claude command, then claude-internal, and falls back to the SDK-bundled CLI if neither is found.

  • The SDK bundles a Claude Code CLI; its version generally tracks the SDK package version, but the exact scheme is not guaranteed
  • Default executable resolution order is: request-level pathToClaudeCodeExecutable -> CLAUDE_CODE_MCP_DEFAULT_CLAUDE_PATH -> CLAUDE_CODE_MCP_DEFAULT_CLAUDE_COMMAND -> auto-detected claude -> auto-detected claude-internal -> SDK-bundled CLI
  • Configuration is shared — the bundled CLI reads API keys and settings from ~/.claude/, same as the system-installed claude
  • All local settings are loaded by default — unlike the raw SDK (which defaults to isolation mode), this MCP server loads user, project, and local settings automatically, including CLAUDE.md project context. Pass advanced.settingSources: [] to opt out
  • You must have Claude Code configured (API key set up) before using this MCP server: see Claude Code documentation

Note: The bundled CLI version may differ from your system-installed claude. To check: claude --version (system) vs npm ls @anthropic-ai/claude-agent-sdk (SDK).

Quick Start

As an MCP server (recommended)

Install globally or use npx (no install needed):

bash
npm install -g @leo000001/claude-code-mcp

Add to your MCP client configuration (Claude Desktop, Cursor, etc.):

json
{
  "mcpServers": {
    "claude-code": {
      "command": "npx",
      "args": ["-y", "@leo000001/claude-code-mcp"]
    }
  }
}

Some clients cache tool/resource metadata at connect-time. This server emits notifications/tools/list_changed and notifications/resources/list_changed after runtime tool discovery so clients can refresh both the claude_code tool description and internal-tools resource.

Anthropic Claude Code CLI (as an MCP client)

bash
claude mcp add --transport stdio claude-code -- npx -y @leo000001/claude-code-mcp

OpenCode

Add a local MCP entry in opencode.json / opencode.jsonc (project) or the global OpenCode config under ~/.config/opencode/:

json
{
  "mcp": {
    "claude-code": {
      "type": "local",
      "command": ["npx", "-y", "@leo000001/claude-code-mcp"],
      "enabled": true
    }
  }
}

OpenCode tip: start with claude_code, keep the returned sessionId, then background-poll with claude_code_check. When approvals appear, decision: "allow_for_session" is usually the best UX because it reduces repeated prompts for the same tool in a session.

OpenCode project configs can launch local commands. Only enable repository-level MCP configs in repos you trust.

OpenAI Codex CLI

bash
codex mcp add claude-code -- npx -y @leo000001/claude-code-mcp

Or manually add to ~/.codex/config.toml:

toml
[mcp_servers.claude-code-mcp]
command = "npx"
args = ["-y", "@leo000001/claude-code-mcp"]

Codex supports both user-level (~/.codex/config.toml) and project-level (.codex/config.toml) configuration. See Codex config reference for advanced options like tool_timeout_sec and enabled_tools.

From source

bash
git clone https://github.com/xihuai18/claude-code-mcp.git
cd claude-code-mcp
npm install
npm run build
npm start

Tools

claude_code — Start a new session

Start a new Claude Code session. The agent autonomously performs coding tasks: reading/writing files, running shell commands, searching code, managing git, and interacting with APIs.

Important protocol note: this call starts background work and returns quickly with sessionId; it does not return the final result. Callers must poll claude_code_check(action="poll"), persist nextCursor, and use claude_code_reply to continue the same session later.

ParameterTypeRequiredDescription
promptstringYesTask or question for Claude Code
cwdstringNoWorking directory (defaults to server cwd)
allowedToolsstring[]NoAuto-approved tool names. Default: [] (none). This is not a strict allowlist unless strictAllowedTools=true. Example: ["Bash", "Read", "Write", "Edit"]
strictAllowedToolsbooleanNoServer-side strict allowlist toggle. When true, tools outside allowedTools are denied. Default: false
disallowedToolsstring[]NoForbidden tool names. Default: [] (none). SDK behavior: disallowed tools are removed from the model's context. Takes precedence over allowedTools and will be denied even if later approved interactively
maxTurnsnumberNoMaximum number of agent reasoning steps. Each step may involve one or more tool calls. Default: SDK/Claude Code default
modelstringNoModel to use (e.g. "claude-sonnet-4-5-20250929"). Default: SDK/Claude Code default
effortstringNoEffort string: "low", "medium", "high", "max". Default: SDK/Claude Code default
thinkingobjectNoThinking config object, not a string: { type: "adaptive" }, { type: "enabled", budgetTokens?: N }, or { type: "disabled" }. Do not pass "low"/"high" here. Default: SDK/Claude Code default
systemPromptstring | objectNoOverride the agent's system prompt. Default: SDK/Claude Code default. Pass a string for full replacement, or { type: "preset", preset: "claude_code", append?: "..." } to extend the default prompt
permissionRequestTimeoutMsnumberNoTimeout in milliseconds waiting for permission decisions, auto-deny on expiry. Default: 60000 (server-clamped to 5min)
advancedobjectNoAdvanced/low-frequency parameters (see below)
ParameterTypeDescription
advanced.toolsstring[] | objectVisible built-in tool set. Array of exact tool names, [] to disable built-ins, or { type: "preset", preset: "claude_code" } for the default set. This controls what Claude can see/call; allowedTools only controls pre-approval.
advanced.persistSessionbooleanPersist session history to disk (~/.claude/projects/). Default: true. Set false to disable.
advanced.sessionInitTimeoutMsnumberSession init timeout in milliseconds waiting for system/init. Default: 10000.
advanced.agentsobjectDefine custom sub-agents the main agent can delegate tasks to. Default: none. SDK default: if a sub-agent omits tools, it inherits all tools from the parent.
advanced.agentstringName of a custom agent (defined in agents) to use as the primary agent. Default: omitted
advanced.maxBudgetUsdnumberMaximum budget in USD. Default: SDK/Claude Code default
advanced.betasstring[]Beta features (e.g. ["context-1m-2025-08-07"]). Default: none
advanced.additionalDirectoriesstring[]Additional directories the agent can access beyond cwd. Default: none
advanced.outputFormatobjectStructured output config: { type: "json_schema", schema: {...} }. Default: omitted (plain text)
advanced.pathToClaudeCodeExecutablestringPath to the Claude Code executable. Default: auto-detect claude, then claude-internal, else SDK-bundled Claude Code (cli.js).
advanced.mcpServersobjectMCP server configurations keyed by server name. Default: none
advanced.sandboxobjectSandbox behavior config object. This controls sandbox behavior, not the actual Read/Edit/WebFetch permission rules. Default: SDK/Claude Code default
advanced.fallbackModelstringFallback model if the primary model fails or is unavailable. Default: none
advanced.enableFileCheckpointingbooleanEnable file checkpointing to track file changes during the session. Default: false
advanced.toolConfigobjectPer-tool built-in configuration. Example: { askUserQuestion: { previewFormat: "html" } }. Default: none
advanced.includePartialMessagesbooleanWhen true, includes intermediate streaming messages in the response. Useful for real-time progress monitoring. Default: false
advanced.promptSuggestionsbooleanWhen true, emits post-turn prompt suggestion events (prompt_suggestion). Default: false
advanced.agentProgressSummariesbooleanWhen true, emits AI-generated summaries on system/task_progress events for running subagents. Default: false
advanced.strictMcpConfigbooleanEnforce strict validation of MCP server configurations. Default: false
advanced.settingsstring | objectExtra Claude Code flag settings. Pass either a path to a settings JSON file or an inline settings object. These load at the highest-priority flag-settings layer. Default: none
advanced.settingSourcesstring[]Which filesystem settings to load. Defaults to ["user", "project", "local"] (loads all settings and CLAUDE.md). Pass [] for SDK isolation mode
advanced.debugbooleanEnable debug mode for verbose logging. Default: false
advanced.debugFilestringWrite debug logs to a specific file path (implicitly enables debug mode). Default: omitted
advanced.envobjectEnvironment variables merged over process.env before launching Claude Code (user values take precedence). Default: inherit process.env

Returns: { sessionId, status: "running", pollInterval, resumeToken? }

Notes:

  • resumeToken is omitted by default, and is only returned when CLAUDE_CODE_MCP_RESUME_SECRET is set on the server.
  • On error: { sessionId: "", status: "error", error }
  • model is optional. If omitted, Claude Code chooses the effective model from its own defaults/settings; inspect session/result metadata if you need to know what actually ran.
  • If you plan to continue with claude_code_reply, keep the session persistent (advanced.persistSession=true, which is already the default).

Use claude_code_check to poll events and obtain the final result.

Notes:

  • Subagents require the Task tool to be available to the primary agent. If you use allowedTools, include "Task" or the agent will be unable to invoke subagents.
  • If you configure advanced.mcpServers and want the agent to auto-use tools from those servers without approvals, include the exact tool names in allowedTools (e.g. ["mcp__my_server__tools/list"]). Otherwise you will see permission requests via claude_code_check.
  • advanced.includePartialMessages affects the underlying SDK event stream; intermediate messages are captured as events and returned via claude_code_check (the claude_code call itself does not stream).

Security: Configure permissions based on your own scope. Callers (MCP clients / orchestrating agents) MUST set allowedTools and disallowedTools according to their own permission boundaries. Only pre-approve tools that you yourself are authorized to perform — do not grant the agent broader permissions than you have. For example, if you lack write access to a directory, do not include Write/Edit in allowedTools. When in doubt, leave both lists empty and review each permission request individually via claude_code_check.

claude_code_reply — Continue a session

Continue an existing session by sending a follow-up message. The agent retains full context from previous turns including files read, code analysis, and conversation history.

Important protocol note: prefer claude_code_reply over starting a fresh claude_code session when you want to continue the same work. This requires a persistent in-memory session, or diskResumeConfig when disk resume fallback is enabled.

ParameterTypeRequiredDescription
sessionIdstringYesSession ID from a previous claude_code call
promptstringYesFollow-up prompt
forkSessionbooleanNoCreate a branched copy of this session. Default: false
effortstringNoEffort string override for this run (and for future replies when not forking): "low", "medium", "high", "max". Default: SDK/Claude Code default
thinkingobjectNoThinking config object override for this run (and for future replies when not forking): { type: "adaptive" }, { type: "enabled", budgetTokens?: N }, or { type: "disabled" }. Default: SDK/Claude Code default
permissionRequestTimeoutMsnumberNoTimeout in milliseconds waiting for permission decisions, auto-deny on expiry. Default: 60000 (server-clamped to 5min)
sessionInitTimeoutMsnumberNoFork init timeout in milliseconds (only when forkSession=true). Default: 10000
diskResumeConfigobjectNoDisk resume parameters (see below). Used when CLAUDE_CODE_MCP_ALLOW_DISK_RESUME=1 and in-memory session is missing
ParameterTypeDescription
diskResumeConfig.resumeTokenstringResume token returned by claude_code / claude_code_reply. Required for disk resume fallback
diskResumeConfig.cwdstringWorking directory. Required for disk resume.
diskResumeConfig.allowedToolsstring[]Auto-approved tool names (see claude_code). Default: []
diskResumeConfig.disallowedToolsstring[]Forbidden tool names (see claude_code). Default: []
diskResumeConfig.strictAllowedToolsbooleanServer-side strict allow-list behavior for allowedTools. Default: false
diskResumeConfig.toolsstring[] | objectBase tool set (see claude_code). Default: SDK/Claude Code default
diskResumeConfig.persistSessionbooleanPersist session history to disk. Default: true
diskResumeConfig.maxTurnsnumberMaximum number of agent reasoning steps. Default: SDK/Claude Code default
diskResumeConfig.modelstringModel to use. Default: SDK/Claude Code default
diskResumeConfig.systemPromptstring | objectOverride the agent's system prompt. Default: SDK/Claude Code default
diskResumeConfig.agentsobjectCustom sub-agent definitions (see claude_code). Default: none
diskResumeConfig.agentstringPrimary agent name (see claude_code tool). Default: omitted
diskResumeConfig.maxBudgetUsdnumberMaximum budget in USD. Default: SDK/Claude Code default
diskResumeConfig.effortstringEffort level. Default: SDK/Claude Code default
diskResumeConfig.betasstring[]Beta features. Default: none
diskResumeConfig.additionalDirectoriesstring[]Additional directories. Default: none
diskResumeConfig.outputFormatobjectStructured output config. Default: omitted (plain text)
diskResumeConfig.thinkingobjectThinking config object: { type: "adaptive" }, { type: "enabled", budgetTokens?: N }, or { type: "disabled" }. Default: SDK/Claude Code default
diskResumeConfig.resumeSessionAtstringResume only up to and including a specific message UUID. Default: omitted
diskResumeConfig.pathToClaudeCodeExecutablestringPath to Claude Code executable. Default: auto-detect claude, then claude-internal, else SDK-bundled Claude Code (cli.js)
diskResumeConfig.mcpServersobjectMCP server configurations keyed by server name. Default: none
diskResumeConfig.sandboxobjectSandbox behavior config object. Default: SDK/Claude Code default
diskResumeConfig.fallbackModelstringFallback model. Default: none
diskResumeConfig.enableFileCheckpointingbooleanEnable file checkpointing. Default: false
diskResumeConfig.toolConfigobjectPer-tool built-in configuration. Default: none
diskResumeConfig.includePartialMessagesbooleanInclude intermediate streaming messages. Default: false
diskResumeConfig.promptSuggestionsbooleanEmit post-turn prompt suggestion events (prompt_suggestion). Default: false
diskResumeConfig.agentProgressSummariesbooleanEmit AI-generated subagent progress summaries. Default: false
diskResumeConfig.strictMcpConfigbooleanStrict MCP config validation. Default: false
diskResumeConfig.settingsstring | objectExtra Claude Code flag settings (path or inline object), loaded at the highest-priority flag-settings layer. Default: none
diskResumeConfig.settingSourcesstring[]Which filesystem settings to load. Default: ["user", "project", "local"]
diskResumeConfig.debugbooleanDebug mode. Default: false
diskResumeConfig.debugFilestringDebug log file path (implicitly enables debug). Default: omitted
diskResumeConfig.envobjectEnvironment variables merged over process.env (user values override). Default: inherit process.env

Returns: { sessionId, status: "running", pollInterval, resumeToken? }

Notes:

  • resumeToken is omitted by default, and is only returned when CLAUDE_CODE_MCP_RESUME_SECRET is set on the server.
  • On error: { sessionId, status: "error", error }

Use claude_code_check to poll events and obtain the final result.

Gotchas:

  • Permission approvals have a timeout (default 60s via permissionRequestTimeoutMs) and will auto-deny; watch actions[].expiresAt / actions[].remainingMs.
  • claude_code_reply requires a persistent session or an enabled disk-resume setup; one-shot/non-persistent sessions cannot be resumed later.
  • Read has a per-call size cap in practice (often ~256KB); for large files use offset/limit or chunk with Grep.
  • Edit with replace_all=true is substring replacement; if no match is found the tool returns a clear error.
  • On Windows, this server normalizes common MSYS-style paths (e.g. /d/..., /mnt/c/..., /cygdrive/c/..., //server/share/...) for cwd, additionalDirectories, and tool inputs that include file_path.
  • On Windows, POSIX home paths like /home/user/... are not rewritten to drive paths; prefer absolute Windows paths under your current cwd to avoid out-of-bounds permission prompts.
  • On Windows, Claude Code itself needs Git Bash; set CLAUDE_CODE_GIT_BASH_PATH in your MCP client config if auto-detection is unreliable.
  • TeamDelete may require members to reach shutdown_approved (otherwise you may see "active member" errors); cleanup can be asynchronous during shutdown.
  • Skills may become available later in the same session (early calls may show "Unknown", later succeed after skills are loaded/registered).
  • toolCatalogCount and availableTools are different views: catalog is server-known tools, while availableTools comes from each session's runtime system/init.tools.
  • Some internal features (e.g. ToolSearch) may not appear in availableTools (derived from SDK system/init.tools).

Resources

If your MCP client supports resources, this server exposes a couple of read-only MCP resources:

  • claude-code-mcp:///server-info (JSON): server metadata (version/platform/runtime + capabilities/limits)
  • claude-code-mcp:///internal-tools (JSON): internal tool catalog (runtime-aware, includes permission/schema metadata)
  • claude-code-mcp:///gotchas (Markdown): practical limits/gotchas
  • claude-code-mcp:///quickstart (Markdown): minimal async start/poll/respond flow
  • claude-code-mcp:///errors (JSON): structured error-code catalog and remediation hints
  • claude-code-mcp:///compat-report (JSON): compatibility report (transport/platform assumptions, runtime warnings, guidance, recommended settings, tool count diagnostics)

Resource templates:

  • claude-code-mcp:///session/{sessionId}: lightweight session snapshot for a specific session
  • claude-code-mcp:///tools/runtime{?sessionId}: runtime tool view globally or per session
  • claude-code-mcp:///compat/diff{?client}: client-specific compatibility guidance

Disk resume (optional): By default, claude_code_reply requires the session to exist in the MCP server's in-memory Session Manager. If you set CLAUDE_CODE_MCP_ALLOW_DISK_RESUME=1, it can attempt to resume using the Claude Code CLI's on-disk transcript even when the in-memory session is missing (e.g. after a restart / TTL cleanup). For safety, disk resume fallback requires CLAUDE_CODE_MCP_RESUME_SECRET to be set on the server and requires callers to pass diskResumeConfig.resumeToken (returned by claude_code / claude_code_reply when CLAUDE_CODE_MCP_RESUME_SECRET is set).

claude_code_session — Manage sessions

List, inspect, cancel, or interrupt sessions.

ParameterTypeRequiredDescription
actionstringYes"list", "get", "cancel", or "interrupt"
sessionIdstringFor get/cancel/interruptTarget session ID
includeSensitivebooleanNoInclude cwd/systemPrompt/agents/additionalDirectories/toolConfig (default: false; settings stays hidden)

Returns: { sessions, message?, isError? }

sessions[] now includes lightweight diagnostics fields: pendingPermissionCount, eventCount, currentCursor, lastEventId, ttlMs, lastError?, lastErrorAt?, fastModeState?, and redactions[].

claude_code_check — Poll events and respond to permission requests

Poll session events/results and approve/deny pending permission requests.

Important protocol note: action="poll" is the main loop, and action="respond_permission" is the only interactive approval flow on this backend. respond_user_input is not supported.

ParameterTypeRequiredDescription
actionstringYes"poll" or "respond_permission"
sessionIdstringYesTarget session ID
cursornumberNoEvent cursor for incremental polling (poll only). Default: omitted (starts from the beginning of the buffer)
responseModestringNo"minimal" (default), "delta_compact" (lightweight polling), or "full" (verbose diagnostics)
maxEventsnumberNoMax events per poll (pagination via nextCursor). Default: 200 in "minimal"; unlimited in "full"/"delta_compact"
requestIdstringFor respond_permissionPermission request ID
decisionstringFor respond_permission"allow", "deny", or "allow_for_session"
denyMessagestringNoDeny reason shown to Claude (deny only). Default: "Permission denied by caller"
interruptbooleanNoWhen true, denying also interrupts the whole agent (deny only). Default: false
pollOptionsobjectNoFine-grained poll control options (see below)
permissionOptionsobjectNoAdvanced permission response options (see below)
ParameterTypeDescription
pollOptions.includeToolsbooleanWhen true, includes availableTools (poll only). Default: false (omitted until session init is received). Derived from SDK system/init.tools (internal features may not appear).
pollOptions.includeEventsbooleanWhen false, omits events (but nextCursor still advances). Default: true
pollOptions.includeActionsbooleanWhen false, omits actions[] even if waiting_permission. Default: true
pollOptions.includeResultbooleanWhen false, omits top-level result even when idle/error. Default: true
pollOptions.includeUsagebooleanInclude result.usage (default: true in "full", false in "minimal"/"delta_compact")
pollOptions.includeModelUsagebooleanInclude result.modelUsage (default: true in "full", false in "minimal"/"delta_compact")
pollOptions.includeStructuredOutputbooleanInclude result.structuredOutput (default: true in "full", false in "minimal"/"delta_compact")
pollOptions.includeTerminalEventsbooleanWhen true, keeps terminal result/error events in events even if top-level result is included. Default: false in "minimal"/"delta_compact", true in "full"
pollOptions.includeProgressEventsbooleanWhen true, includes noisy SDK progress subtypes (e.g. tool_progress, auth_status, system/api_retry, system/task_progress, system/hook_progress) as MCP progress events. Default: false in "minimal"/"delta_compact", true in "full"
pollOptions.maxBytesnumberApproximate max JSON bytes for events in this response. When exceeded, events are truncated and truncatedFields includes "events_bytes". Default: unlimited
ParameterTypeDescription
permissionOptions.updatedInputobjectModified tool input to run (allow/allow_for_session only). Default: none
permissionOptions.updatedPermissionsarrayPermission rule updates suggested/applied (allow/allow_for_session only). Default: none

Returns (poll and respond_permission): { sessionId, status, pollInterval?, cursorResetTo?, truncated?, truncatedFields?, events, nextCursor?, availableTools?, toolValidation?, compatWarnings?, actions?, result?, cancelledAt?, cancelledReason?, cancelledSource?, lastEventId?, lastToolUseId? }

Notes:

  • On error (e.g. invalid arguments, missing/expired session): { sessionId, isError: true, error }
  • respond_user_input is not supported on this backend. Use respond_permission for interactive approvals.
  • Always treat cursor as an incremental position: store nextCursor and pass it back on the next poll to avoid replaying old events.
  • If cursorResetTo is present, your cursor was too old (events were evicted); reset your cursor to cursorResetTo.
  • For safety, de-duplicate events by event.id on the client side.
  • If truncated=true, the server intentionally limited the payload (e.g. maxEvents) — continue polling with nextCursor.
  • nextCursor can remain unchanged with events=[] during quiet intervals; this is normal transient behavior. Retry a few times (for example up to 3) before treating it as abnormal.
  • toolValidation reports whether configured allowedTools/disallowedTools match runtime-discovered tool names.
  • compatWarnings surfaces compatibility hints (for example, unresolved tool names or path/platform mismatch signals) and is non-blocking; treat it as advisory unless the session actually fails.
  • Permission actions[] include timeoutMs, expiresAt, and best-effort remainingMs to help callers avoid auto-deny timeouts.
  • Permission actions[] may also include SDK-provided title / displayName metadata; clients should prefer those strings when rendering approval UI.
  • For decision="allow_for_session", the server now prefers SDK-provided suggestions (for example addDirectories) when present, then falls back to a generic per-session tool allow rule.
  • permission_result event data is { requestId, toolName, behavior, source, message?, interrupt? } (denial details only present for deny).
  • result.fastModeState may be present when the SDK reports fast-mode state, and claude_code_session surfaces the latest known fastModeState for each session.
  • In "minimal" mode (default): assistant message events are slimmed (strips usage, model, id, cache_control from content blocks); noisy SDK progress subtypes (tool_progress, auth_status, system/api_retry, system/task_progress, system/hook_progress) are filtered out; lastEventId/lastToolUseId are omitted; AgentResult omits durationApiMs/sessionTotalTurns/sessionTotalCostUsd. Use responseMode: "full" or individual include* flags to restore any of these.
  • In "delta_compact" mode: defaults minimize per-poll payload size (events and top-level result omitted unless explicitly enabled via pollOptions), while still returning session status/actions/cursors. Note: this does not change the recommended poll interval — running sessions should still be polled at >=2 minute intervals.

Usage Example

python
# 1) Start a new session (async start)
start = await mcp.call_tool("claude_code", {
    "prompt": "Fix the authentication bug in src/auth.ts",
    "cwd": "/path/to/project",
    "allowedTools": ["Read", "Edit", "Bash", "Glob", "Grep"],
    "effort": "high",
    "advanced": {
        "maxBudgetUsd": 5.0
    }
})
session_id = json.loads(start)["sessionId"]
cursor = 0

# 2) Poll until idle/error/cancelled
while True:
    polled = await mcp.call_tool("claude_code_check", {
        "action": "poll",
        "sessionId": session_id,
        "cursor": cursor,
        "pollOptions": {
            "includeProgressEvents": True
        }
    })
    data = json.loads(polled)
    cursor = data.get("nextCursor", cursor)

    # If permission is needed, approve/deny via respond_permission
    for action in data.get("actions", []) or []:
        if action.get("type") == "permission":
            await mcp.call_tool("claude_code_check", {
                "action": "respond_permission",
                "sessionId": session_id,
                "requestId": action["requestId"],
                "decision": "allow"
            })

    # Final result is available when status becomes idle/error
    if data.get("status") in ["idle", "error", "cancelled"]:
        final_result = data.get("result")
        break

# 3) Manage sessions (list/get/cancel/interrupt)
result = await mcp.call_tool("claude_code_session", {"action": "list"})

Windows Support

The Claude Code CLI bundled in the SDK requires Git for Windows (which includes bash.exe). If you run this MCP server on Windows and see:

Claude Code on Windows requires git-bash (https://git-scm.com/downloads/win).

This means the spawned CLI process cannot locate bash.exe. Your locally installed claude command may work fine — the issue is that the MCP server's child process may not inherit your shell environment.

claude-code-mcp will try to auto-detect Git Bash from common install locations and set CLAUDE_CODE_GIT_BASH_PATH for child processes. If you still see this error, set CLAUDE_CODE_GIT_BASH_PATH explicitly in your MCP server config:

For JSON-based MCP clients (Claude Desktop, Cursor, etc.):

json
{
  "mcpServers": {
    "claude-code": {
      "command": "npx",
      "args": ["-y", "@leo000001/claude-code-mcp"],
      "env": {
        "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe"
      }
    }
  }
}

For OpenCode (opencode.json / opencode.jsonc):

json
{
  "mcp": {
    "claude-code": {
      "type": "local",
      "command": ["npx", "-y", "@leo000001/claude-code-mcp"],
      "enabled": true,
      "environm

安装

TypingMind
{
  "mcpServers": {
    "claude-code-mcp": {
      "command": "npx",
      "args": [
        "@leo000001/claude-code-mcp"
      ]
    }
  }
}

可用工具

  • claude_code

    Start a new Claude Code agent session to perform coding tasks autonomously. The agent can read/write files, run commands, search code, and more. Returns a sessionId for continuing the conversation later. Permission mode defaults to "dontAsk" (non-interactive, safe for MCP). By default, loads all local Claude settings (user, project, local) including CLAUDE.md for project context.

  • claude_code_reply

    Continue an existing Claude Code session with full context preserved. Claude remembers all files read, analysis done, and conversation history.

  • claude_code_session

    Manage Claude Code sessions: list all sessions, get status of a specific session, or cancel a running session.

  • claude_code_configure

    Configure the Claude Code MCP server at runtime. Actions: enable_bypass (allow bypassPermissions mode), disable_bypass, get_config.

将 claude-code-mcp MCP 与多个 AI 模型配合使用

TypingMind 在工作区级别连接 MCP 工具,因此连接 claude-code-mcp 后,您就可以在 TypingMind 中搭配不同的 AI 模型使用,无需为每个模型单独设置。 此 MCP 通过您设备上的 TypingMind MCP 连接器在本地运行。

本地连接器设置指南

如果 MCP 服务器需要访问您电脑上的本地文件、应用或私有资源,请选择此方式。

1

打开 MCP 设置

在 TypingMind 中,依次前往“设置”、“高级设置”和“模型上下文协议”,然后选择“设置连接器”。

  1. 在您的浏览器中打开 TypingMind。
  2. 点击“设置”图标。
  3. 进入“高级设置”。
  4. 打开“模型上下文协议”部分。
  5. 点击“设置连接器”,然后选择“此设备”。
TypingMind MCP 连接器设置界面,已选择“此设备”
2

运行连接器命令

选择“此设备”,从 TypingMind 复制命令并在终端中运行。使用 MCP 时,请保持该进程运行。

  1. 复制 TypingMind 显示的设置命令。
  2. 在 macOS 上打开“终端”,或在 Windows 上打开 Windows Terminal。
  3. 粘贴并运行命令。
  4. 如果终端询问您是否继续,请确认安装软件包。
  5. 使用 MCP 工具时,请保持终端窗口及其中的进程运行。
3

将 claude-code-mcp 添加为服务器

当连接器状态为“就绪”时,点击“编辑服务器”,然后粘贴 MCP 服务器配置。

  1. 等待连接器状态显示为“就绪”。
  2. 点击“编辑服务器”。
  3. 粘贴 claude-code-mcp MCP 服务器配置。
  4. 保存服务器列表。
  5. 如需确认连接器是否仍处于就绪状态,请刷新。
TypingMind MCP 设置界面,显示正在运行的服务器和“编辑服务器”按钮
{
  "mcpServers": {
    "claude-code-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "@leo000001/claude-code-mcp"
      ]
    }
  }
}
4

在不同模型中使用同一连接

保存服务器列表,打开“插件”,启用 claude-code-mcp MCP 工具,然后在 TypingMind 中选择任意受支持的 AI 模型,即可在聊天中使用这些工具,或将其分配给智能体。

  1. 在 TypingMind 中打开“插件”页面。
  2. 启用 claude-code-mcp MCP 工具。
  3. 开始聊天并选择您想使用的 AI 模型。
  4. 在聊天中使用 MCP 工具,或将其分配给 AI 智能体。
  5. 根据需要随时切换到其他 AI 模型,无需重新连接 MCP。
在 TypingMind 聊天中使用已启用的 MCP 工具和选定的 AI 模型
您能使用 claude-code-mcp 帮我完成这项任务吗?
claude-code-mcp
当然。我已阅读。
以下是我使用 claude-code-mcp 得到的结果。

常见问题

claude-code-mcp MCP 服务器有什么用途?

claude-code-mcp 是一个 MCP 服务器,可让兼容的 AI 客户端连接外部工具并获取上下文。在 TypingMind 中,只需添加一次此 MCP 服务器,即可在您的 AI 工作区中使用其工具。

可以在 TypingMind 中让多个 AI 模型使用 claude-code-mcp MCP 吗?

可以。TypingMind 在工作区层面连接 MCP 工具,因此您可以让 Claude、ChatGPT、Gemini 等不同 AI 模型,或您在 TypingMind 中配置的其他模型使用 claude-code-mcp,而无需为每个模型单独配置 MCP 服务器。

为什么在 TypingMind 中使用 claude-code-mcp MCP?

TypingMind 将多个 AI 模型、提示词、插件、AI 智能体、API 密钥和 MCP 工具整合到同一个工作区中,是优秀的大语言模型聊天前端之一。连接 claude-code-mcp 后,您可以在偏好的不同模型中使用其 MCP 工具,同时在 TypingMind 中井然有序地管理聊天工作流程。

如何将 claude-code-mcp MCP 连接到 TypingMind?

claude-code-mcp 通过 TypingMind 本地 MCP 连接器运行。当 MCP 服务器需要访问您计算机上的本地文件、桌面应用、命令行工具或私有资源时,这种方式最合适。

claude-code-mcp MCP 在 TypingMind 中提供哪些工具?

claude-code-mcp 提供 4 个 MCP 工具,您可以在 TypingMind 的插件页面启用这些工具,然后在聊天中使用,或将其分配给 AI 智能体。

使用 claude-code-mcp MCP 需要向 TypingMind 提供我的 API 密钥吗?

不需要。TypingMind 采用本地优先的设计,让您自行掌控模型提供商、API 密钥、提示词和 MCP 配置。如果 claude-code-mcp 需要身份验证,请在创建连接时,为该 MCP 服务器添加所需的请求头、OAuth 设置或本地配置。

相关 MCP 服务器

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇