Serve Claude Code
as MCP将 Claude Code
封装为 MCP 服务
Wrap a narrow Claude Code or Claude Agent SDK workflow in typed MCP tools, with explicit workspace, permission, lifecycle, and result contracts.
把范围明确的 Claude Code 或 Claude Agent SDK 工作流封装成类型化 MCP 工具,
并定义工作区、权限、生命周期与结果契约。
There is no one-click “Claude Code MCP server” modeClaude Code 没有“一键变成 MCP 服务器”的内置模式
Claude Code is normally an MCP client: it connects to servers and uses their tools. To serve a Claude-powered coding workflow through MCP, you build a server wrapper that exposes your own task-specific tools and invokes an approved programmatic execution path behind them. That path can use Claude Code print mode for a small job-shaped prototype or the Claude Agent SDK for a service that needs streaming, sessions, hooks, custom tools, and tighter lifecycle control.
Claude Code 通常扮演 MCP 客户端:它连接服务器并调用工具。若要通过 MCP 对外提供 Claude 编码能力,需要自行构建一层服务器封装,暴露任务型工具,并在后端调用获批的程序化执行方式。任务简单、一次调用即结束的原型,可以使用 Claude Code print 模式;需要流式输出、会话、Hook、自定义工具和更完整生命周期控制的服务,则更适合 Claude Agent SDK。
Publish explain_repository, review_diff, or plan_fix with strict schemas. A generic run_any_prompt endpoint hides intent and weakens policy.
The server resolves an opaque workspace ID to an approved directory. Never accept an arbitrary filesystem path or let prompt text choose the working directory.
Set allowed and denied tools, permission mode, model, maximum turns, wall-clock timeout, output limit, cancellation, and artifact retention.
Prove one read-only STDIO tool before adding HTTP, authentication, tenancy, queues, persistence, and horizontal scaling.
提供带严格参数结构的 explain_repository、review_diff 或 plan_fix。通用 run_any_prompt 会隐藏真实意图,削弱策略控制。
服务器应把不透明的 workspace ID 映射到获批目录。不要接受任意文件系统路径,也不要让提示词决定工作目录。
明确允许与禁止工具、权限模式、模型、最大轮次、总超时、输出上限、取消和产物保留规则。
先把一个只读 STDIO 工具验证稳定,再考虑 HTTP、身份验证、多租户、队列、持久化和横向扩容。
Design the trust boundary before the tool catalog先设计信任边界,再设计工具目录
The MCP server is not a transparent protocol adapter. It is the policy enforcement point between a caller and a coding agent that may read source, run commands, modify files, or reach the network. The wrapper must authenticate the caller, authorize the workspace and task, validate every argument, create an isolated execution context, and normalize the result. Claude should never receive powers that the server did not intentionally grant.
MCP 服务器不是一个透明的协议转接器,而是调用方与高权限编码智能体之间的策略执行点。Claude 可能读取源码、运行命令、修改文件或访问网络,因此封装层必须验证调用者身份,授权工作区与任务,校验每个参数,创建隔离执行环境,并规范化结果。服务器没有明确授予的能力,不应通过任何间接方式落到 Claude 手中。
| Layer层级 | Responsibility职责 | Unsafe shortcut危险捷径 | Required evidence所需证据 |
|---|---|---|---|
| MCP surfaceMCP 接口 | Stable tool names, descriptions, typed inputs, bounded outputs.稳定工具名、说明、类型化输入和受限输出。 | One arbitrary-prompt tool with free-form options.只提供一个可传任意参数的通用提示词工具。 | Schema tests and compatibility contract.结构测试与兼容性契约。 |
| Policy策略 | Caller, tenant, workspace, action, tool, and network authorization.调用方、租户、工作区、动作、工具和网络授权。 | Relying only on a system prompt saying “be safe.”只靠系统提示词要求“注意安全”。 | Explicit allow/deny decision and reason.明确的允许或拒绝决定及理由。 |
| Execution执行 | Isolated process or container, fixed workspace, clean environment, limits.隔离进程或容器、固定工作区、干净环境和资源限制。 | Running under a developer's long-lived account on a shared host.在共享主机上继承开发者长期账号运行。 | Image/version, mounts, identity, limits, start time.镜像或版本、挂载、身份、限制和启动时间。 |
| Agent智能体 | Execute the narrow task with selected tools and instructions.使用选定工具与指令执行范围明确的任务。 | Skipping permissions to make unattended runs convenient.为了无人值守方便而跳过权限检查。 | Model, turns, tool calls, permission events, status.模型、轮次、工具调用、权限事件和状态。 |
| Result结果 | Structured status, summary, findings, artifacts, and safe diagnostics.结构化状态、摘要、发现、产物和安全诊断。 | Returning raw logs, secrets, or unlimited repository content.直接返回原始日志、密钥或无限量仓库内容。 | Job ID, timestamps, artifact hashes, redaction record.任务 ID、时间、产物哈希和脱敏记录。 |
Choose the execution interface deliberately有意识地选择执行接口
Useful for a small prototype or independent batch job. claude -p can return text, JSON, or stream JSON and supports limits such as maximum turns and explicit tool policies.
Better when the service needs programmatic sessions, streaming events, custom tools, permission callbacks, hooks, resume behavior, or consistent application-level control.
Consider a managed product when the real requirement is a hosted customer-facing agent with durable sessions, rather than an MCP wrapper you want to operate yourself.
适合小型原型或彼此独立的批处理任务。claude -p 可返回文本、JSON 或流式 JSON,也支持最大轮次和明确工具策略等限制。
如果服务需要程序化会话、流式事件、自定义工具、权限回调、Hook、会话恢复或一致的应用层控制,更适合使用 Agent SDK。
如果真实需求是面向客户、具备持久会话的托管智能体,而不是自己运维 MCP 封装,应评估托管式产品。
Implement one bounded request-to-result path实现一条受控的请求到结果链路
Start with a read-only tool such as review_diff. Its inputs might include an approved workspace ID, base revision, target revision, review categories, and maximum findings. They should not include an arbitrary shell command, environment block, path, model flag, or permission override. The server owns those controls.
建议从 review_diff 这类只读工具开始。输入可以包含获批 workspace ID、基准修订、目标修订、审查类别和最大问题数,但不应允许调用方传入任意 Shell 命令、环境变量块、文件路径、模型参数或权限覆盖;这些控制项必须由服务器掌握。
Parse against a closed schema, reject unknown fields, normalize revisions, cap strings and arrays, and resolve the workspace through an allowlist. Return a protocol error without invoking Claude when validation fails.
Assign a job ID, temporary writable directory, execution identity, deadline, output budget, and cancellation token. Mount the approved source read-only for analysis unless the tool contract explicitly permits edits.
Keep policy and response format in server-owned instructions. Insert validated task data into clearly delimited fields. Treat repository content and caller text as untrusted data, not instructions that can expand permissions.
For print mode, select a structured output format, maximum turns, allowed and disallowed tools, and an appropriate permission mode. For the SDK, configure the same boundaries through options and permission callbacks.
Map internal events to a small status vocabulary such as queued, running, awaiting approval, completed, canceled, or failed. Redact secrets, absolute host paths, raw environment data, and unrelated source content.
Return typed findings, summary, changed-file list, test results, artifact references, and a terminal status. Include the workspace revision and artifact hashes so clients can verify what was analyzed.
使用封闭结构解析输入,拒绝未知字段,规范化修订版本,限制字符串与数组长度,并通过允许列表解析工作区。校验失败时直接返回协议错误,不要调用 Claude。
为任务分配 ID、临时可写目录、执行身份、截止时间、输出预算和取消令牌。只读分析应把获批源码以只读方式挂载,除非工具契约明确允许编辑。
策略和响应格式由服务器指令固定,已校验任务数据放入边界清晰的字段。仓库内容和调用方文本都属于不可信数据,不能借此扩大权限。
使用 print 模式时,指定结构化输出、最大轮次、允许与禁止工具以及合适权限模式;使用 SDK 时,通过选项和权限回调落实同样边界。
把内部事件映射为少量状态,例如排队、运行、等待批准、完成、取消或失败。脱敏密钥、主机绝对路径、原始环境数据和无关源码。
返回类型化问题、摘要、变更文件列表、测试结果、产物引用和终态,并附工作区修订与产物哈希,便于客户端核验分析对象。
Critical rule: do not use --dangerously-skip-permissions as the automation strategy. A service cannot replace interactive confirmation by removing the boundary. Implement a permission callback, approval tool, pre-authorized read-only toolset, or job-specific policy instead.
关键规则:不要把 --dangerously-skip-permissions 当成自动化方案。服务不能通过删除边界来替代交互确认;应使用权限回调、批准工具、预授权只读工具集或任务级策略。
Add remote access only after local behavior is deterministic本地行为可预测后,再开放远程访问
STDIO is the smallest deployment boundary because the client starts the process and no listener is exposed. A remote Streamable HTTP server becomes a distributed, multi-user execution service. It needs authentication before tool discovery, per-tool authorization, protected-resource metadata, tenant isolation, session handling, request and output limits, queueing, cancellation, backpressure, and safe shutdown. TLS alone does not provide these controls.
STDIO 的边界最小:客户端启动进程,也不会对外开放监听端口。远程 Streamable HTTP 服务器则会变成分布式、多用户执行服务,需要在工具发现前完成身份验证,并具备逐工具授权、受保护资源元数据、租户隔离、会话管理、请求与输出限制、队列、取消、背压和安全停机。仅有 TLS 并不能替代这些控制。
| Operational risk运行风险 | Control控制措施 | Test测试 |
|---|---|---|
| Duplicate execution重复执行 | Idempotency key and server-owned job record.幂等键与服务端任务记录。 | Retry the same request during timeout and confirm one job.超时时重试相同请求,确认只产生一个任务。 |
| Runaway agent任务失控 | Turn, wall-clock, CPU, memory, disk, output, and cost ceilings.轮次、总时长、CPU、内存、磁盘、输出与费用上限。 | Force loops and large output; verify termination and cleanup.制造循环和超大输出,确认终止与清理。 |
| Cross-tenant access跨租户访问 | Separate identity, workspace mount, session store, cache, and logs.隔离身份、工作区挂载、会话存储、缓存和日志。 | Attempt workspace and session IDs from another tenant.尝试访问另一租户的工作区和会话 ID。 |
| Client disconnect客户端断连 | Cancellation policy, lease, heartbeat, and detached-job rules.取消策略、租约、心跳和脱离任务规则。 | Drop connection at each stage and inspect job outcome.在每个阶段断开连接,检查任务结局。 |
| Secret exposure密钥泄露 | Minimal environment, secret broker, redaction, egress allowlist.最小环境、密钥代理、脱敏和出站白名单。 | Plant synthetic secrets and verify they never reach results or logs.植入测试密钥,确认结果和日志均不出现。 |
| Partial failure部分失败 | Terminal status, artifact commit protocol, cleanup, resumability.终态、产物提交协议、清理和恢复能力。 | Kill process mid-write and verify no ambiguous success.写入中途终止进程,确认不会返回模糊成功。 |
Log decisions, not entire workspaces记录决策,不要记录整个工作区
- Record caller, tenant, tool, schema version, workspace ID, immutable revision, policy decision, job ID, model, duration, tool counts, status, and artifact identifiers.
- Do not retain raw prompts, source files, environment blocks, command output, or model traces by default. Make any diagnostic retention explicit, minimized, encrypted, and time-bounded.
- Expose health separately from MCP, and never make a health response disclose tenants, paths, credentials, prompts, or active task content.
- Pin and roll forward tested versions. A Claude Code or Agent SDK update is an execution-engine change that deserves compatibility and security testing.
- 记录调用方、租户、工具、结构版本、工作区 ID、不可变修订、策略决定、任务 ID、模型、时长、工具调用数、状态和产物标识。
- 默认不要保留原始提示词、源码文件、环境变量块、命令输出或模型轨迹。确需诊断保留时,应明确声明、最小化、加密并设置期限。
- 健康检查应与 MCP 端点分开,而且不能泄露租户、路径、凭据、提示词或当前任务内容。
- 固定并逐步升级经过测试的版本。Claude Code 或 Agent SDK 更新属于执行引擎变更,需要兼容性与安全测试。
Keep external capabilities outside the privileged wrapper把外部能力留在高权限封装之外
The coding service should remain focused on approved repositories and development tasks. This topic has no exact QVeris Tool or Provider profile, so the CTA uses general product destinations. If a workflow needs external APIs or live data, define that as a separate capability boundary, review the integration model in QVeris Docs, and test it independently in the QVeris Playground.
编码服务应只专注于获批仓库和开发任务。这个主题没有准确对应的 QVeris Tool 或 Provider 页面,因此 CTA 使用通用产品入口。如果工作流需要外部 API 或实时数据,应把它定义为单独的能力边界,先在 QVeris 文档 中审查接入模型,再到 QVeris Playground 独立验证。
- Use separate credentials, policies, logs, and approval rules for coding and external calls.
- Pass only the minimal, sourced result into the coding job instead of giving it broad provider credentials.
- Retain provider, timestamp, units, parameters, and result identifiers so downstream code decisions remain auditable.
- 编码与外部调用应使用不同凭据、策略、日志和批准规则。
- 只把带来源的最小结果传入编码任务,不要向高权限智能体提供宽泛供应商凭据。
- 保留供应商、时间、单位、参数和结果标识,让后续代码决策可以审计。
Serving Claude Code as MCP FAQ将 Claude Code 封装为 MCP 服务常见问题
No one-click server mode should be assumed. Build an MCP wrapper around a supported programmatic path such as print mode or the Claude Agent SDK.
It collapses many risk classes into one opaque call. Task-specific tools have clearer schemas, permissions, tests, cost bounds, and expected outputs.
Use print mode for small independent jobs. Use Agent SDK when you need sessions, streaming, hooks, custom tools, permission callbacks, or service-grade lifecycle control.
It can if you intentionally design a write contract, isolated writable workspace, approval flow, validation, tests, artifact handling, and rollback. Read-only is the safer first milestone.
After the STDIO implementation is deterministic and authentication, authorization, isolation, quotas, cancellation, audit, and incident response are ready.
Use server-owned session IDs bound to tenant and workspace. Define expiry, resume rules, concurrency, storage, deletion, and what happens when the client disconnects.
不能假设存在一键服务器模式。应围绕受支持的程序化路径(如 print 模式或 Claude Agent SDK)自行构建 MCP 封装。
它会把多类风险折叠进一个不透明调用。任务型工具的结构、权限、测试、费用上限和预期输出都更清楚。
小型独立任务使用 print 模式;需要会话、流式输出、Hook、自定义工具、权限回调或服务级生命周期时使用 Agent SDK。
可以,但必须明确设计写入契约、隔离可写工作区、批准流程、验证、测试、产物处理和回退。首个里程碑仍应只读。
STDIO 行为已可预测,并且身份验证、授权、隔离、配额、取消、审计和事件响应都准备好之后。
使用服务端生成、绑定租户与工作区的 session ID,并明确过期、恢复、并发、存储、删除和客户端断连行为。
References and next steps参考资料与下一步
Claude Code CLI reference
Claude Code programmatic use
Claude Agent SDK overview
Anthropic agent hosting guide
Claude Code permissions
QVeris MCP Server docs
QVeris Playground
Claude Code CLI 参考
Claude Code 程序化使用
Claude Agent SDK 概览
Anthropic 智能体托管指南
Claude Code 权限
QVeris MCP Server 文档
QVeris Playground
