探索人工智能驱动的编码:在 Cursor、Claude Code 和 Codex 中使用 Xcode 26.3 MCP 工具

发布时间:2026/7/22 12:19:45

探索人工智能驱动的编码:在 Cursor、Claude Code 和 Codex 中使用 Xcode 26.3 MCP 工具 目录前提条件启用 Xcode 工具 MCP 服务器麦克普布里奇Claude Code 和 Codex CLI在Cursor中设置选项 1一键安装选项 2图形用户界面选项 3JSON 配置Xcode 26.3 RC 1 中的已知限制已在 RC 2 中修复针对 Xcode 26.3 RC 1 的包装器变通方案权限对话框Xcode MCP 工具工具的工作原理文档搜索渲染预览执行代码片段使用 AGENTS.md 添加上下文手动PID配置特殊情况会话 ID高级Xcode 警报自定义 Xcode 内置代理接下来会发生什么如果您喜欢此文章请收藏、点赞、评论谢谢祝您快乐每一天。在深入研究 Xcode 26.3 的内部结构时发现了一些 Xcode 封闭生态系统中不寻常的东西这让我非常兴奋团队构建了一个桥梁使您可以从任何MCP 客户端使用 Xcode 的 AI 工具。不仅限于 Xcode 内置的 Claude 或 Codex 代理还包括 Cursor、Claude CLI 以及任何支持 MCP 的程序。苹果甚至为此提供了官方文档但该文档并未涵盖 Cursor 等第三方工具。前提条件启用 Xcode 工具 MCP 服务器任何外部工具连接之前需要在 Xcode 中启用 MCP 服务器打开Xcode 设置或按⌘,在侧边栏中选择“智能”在“模型上下文协议”下启用Xcode工具这告诉 Xcode 接受来自外部代理的传入 MCP 连接。麦克普布里奇该xcrun mcpbridge桥接器此处双关是一个二进制文件它将 MCP 协议请求转换为 Xcode 的内部 XPC 调用┌─────────────┐ MCP Protocol ┌────────────┐ XPC ┌─────────┐│ Cursor │ ◄────────────────► │ mcpbridge │ ◄───────► │ Xcode ││ (MCP Client)│ │ (Bridge) │ │ (IDE) │└─────────────┘ └────────────┘ └─────────┘要使此功能生效Xcode 必须运行并打开一个项目。该桥接器连接到 Xcode 进程并公开其全部 20 个原生 MCP 工具。Claude Code 和 Codex CLIApple 为 Claude Code 和 Codex 提供了官方的单行命令。对于Claude Code请运行claude mcp add --transport stdio xcode -- xcrun mcpbridge对于Codex请运行codex mcp add xcode -- xcrun mcpbridge验证配置是否有效claude mcp list# orcodex mcp list这就是使用官方 CLI 工具所需的一切。但是 Cursor 或其他 VS Code 分支呢在Cursor中设置将 xcode-tools 添加到 Cursor 有三种方法从最简单到最繁琐选项 1一键安装点击此链接直接安装 xcode-tools将 xcode-tools 添加到 Cursor光标会提示您确认安装。点击“安装”即可完成。选项 2图形用户界面打开光标设置⌘,转到“功能”“MCP”点击“ 添加新 MCP 服务器”选择stdio作为传输类型输入xcode-tools名称输入xcrun mcpbridge命令选项 3JSON 配置添加到~/.cursor/mcp.json{mcpServers: {xcode-tools: {command: xcrun,args: [mcpbridge]}}}它会自动检测 Xcode 进程 ID (PID)无需手动指定。mcpbridgeXcode 26.3 RC 1 中的已知限制已在 RC 2 中修复如果您使用的是Xcode 26.3 RC 1版本并尝试使用上述基本配置在 Cursor 中使用 xcode-tools则可能会遇到以下错误MCP error -32600: Tool XcodeListWindows has an output schema but did not return structured content这是 Xcode 26.3 RC 1 中的一个已知限制。根据 MCP 规范当工具声明一个响应时outputSchema响应必须包含一个structuredContent字段。苹果mcpbridge返回的数据包含在响应中content但不包含在响应中structuredContent。此问题已在 Xcode 26.3 RC 2 中修复。现在mcpbridge能够正确返回structuredContent因此 Cursor 可以使用标准xcrun mcpbridge配置——无需包装器。如果您仍在使用 RC 1 版本可以使用下面的封装器变通方案。否则请跳至下一节。针对 Xcode 26.3 RC 1 的包装器变通方案mcpbridge用脚本将其复制content到structuredContent.请使用这个强化版本它通过监控子进程的存活状态和使用限时关闭来避免常见的程序崩溃。请在以下位置创建此文件~/bin/mcpbridge-wrapper#!/usr/bin/env python3Wrapper for xcrun mcpbridge that adds structuredContent to responses.Hardened for long-running MCP sessions:- monitors child liveness- avoids silent thread crashes on malformed payloads- uses bounded shutdown (terminate - kill) to prevent hangsimport jsonimport subprocessimport sysimport threadingimport timeSHUTDOWN_WAIT_SECONDS 2.0def log(message):try:sys.stderr.write(f[mcpbridge-wrapper] {message}\n)sys.stderr.flush()except Exception:passdef ensure_structured_content(result):if content not in result or structuredContent in result:returncontent result.get(content, [])if not isinstance(content, list):returnif not content:result[structuredContent] contentreturnfor item in content:if not isinstance(item, dict) or item.get(type) ! text:continuetext item.get(text, )if not isinstance(text, str):result[structuredContent] {text: str(text)}returntry:result[structuredContent] json.loads(text)except json.JSONDecodeError:result[structuredContent] {text: text}returnresult[structuredContent] contentdef process_response(line):try:data json.loads(line)except json.JSONDecodeError:return lineexcept Exception as exc:log(fJSON parse failed unexpectedly: {exc!r})return linetry:if isinstance(data, dict):result data.get(result)if isinstance(result, dict):ensure_structured_content(result)return json.dumps(data)except Exception as exc:log(fResponse transformation failed: {exc!r})return linedef pipe_output(proc, stop_event):stdout proc.stdoutif stdout is None:stop_event.set()returntry:for line in stdout:raw line.rstrip(\n)try:processed process_response(raw)except Exception as exc:log(fprocess_response crashed: {exc!r})processed rawtry:sys.stdout.write(processed \n)sys.stdout.flush()except BrokenPipeError:stop_event.set()breakexcept Exception as exc:log(fstdout forwarding failed: {exc!r})stop_event.set()breakexcept Exception as exc:log(fstdout reader failed: {exc!r})finally:stop_event.set()def pipe_input(proc, stop_event):stdin proc.stdinif stdin is None:stop_event.set()returntry:for line in sys.stdin:if stop_event.is_set() or proc.poll() is not None:breaktry:stdin.write(line)stdin.flush()except (BrokenPipeError, OSError):stop_event.set()breakexcept KeyboardInterrupt:stop_event.set()except Exception as exc:log(fstdin forwarding failed: {exc!r})stop_event.set()finally:try:stdin.close()except Exception:passdef shutdown_child(proc):if proc.poll() is not None:returntry:proc.terminate()proc.wait(timeoutSHUTDOWN_WAIT_SECONDS)except subprocess.TimeoutExpired:try:proc.kill()except Exception:passtry:proc.wait(timeoutSHUTDOWN_WAIT_SECONDS)except Exception:passexcept Exception:passdef main():try:proc subprocess.Popen([xcrun, mcpbridge] sys.argv[1:],stdinsubprocess.PIPE,stdoutsubprocess.PIPE,stderrsys.stderr,textTrue,bufsize1,)except Exception as exc:log(fFailed to launch xcrun mcpbridge: {exc!r})return 1stop_event threading.Event()output_thread threading.Thread(targetpipe_output, args(proc, stop_event), daemonTrue)input_thread threading.Thread(targetpipe_input, args(proc, stop_event), daemonTrue)output_thread.start()input_thread.start()try:while not stop_event.is_set():if proc.poll() is not None:stop_event.set()breaktime.sleep(0.1)except KeyboardInterrupt:stop_event.set()finally:stop_event.set()shutdown_child(proc)output_thread.join(timeout1.0)input_thread.join(timeout1.0)return proc.returncode if proc.returncode is not None else 0if __name__ __main__:raise SystemExit(main())使其可执行chmod x ~/bin/mcpbridge-wrapper然后更新你的~/.cursor/mcp.json代码以使用该包装器{mcpServers: {xcode-tools: {command: /Users/YOUR_USERNAME/bin/mcpbridge-wrapper}}}请替换YOUR_USERNAME成您的实际用户名。自动检测逻辑如果只有一个 Xcode 进程正在运行它会连接到该进程。如果运行了多个 Xcode 实例它会xcode-select选择正确的实例。如果 Xcode 没有运行它会退出并报错。重启 Cursor或重新加载窗口您应该会xcode-tools在 MCP 工具列表中看到服务器。权限对话框当 MCP 客户端首次尝试连接时Xcode 会请求权限。点击“允许”即可。这是苹果公司确保您明确授予 Xcode 访问权限的一种方式。对话框会显示代理程序二进制文件的确切路径及其进程 ID (PID)。Xcode MCP 工具以下是您在 Xcode 26.3 MCP 工具中可以访问的所有内容XcodeRead- 读取项目中的文件XcodeWrite- 将文件写入项目XcodeUpdate- 使用 str_replace 样式补丁编辑文件XcodeGlob- 按模式查找文件XcodeGrep搜索文件内容XcodeLS- 列出目录内容XcodeMakeDir- 创建目录XcodeRM- 删除文件XcodeMV- 移动/重命名文件BuildProject- 构建 Xcode 项目GetBuildLog获取构建输出RunAllTests- 运行所有测试RunSomeTests- 运行特定测试GetTestList- 列出可用的测试XcodeListNavigatorIssues- 获取 Xcode 问题/错误信息XcodeRefreshCodeIssuesInFile获取实时诊断信息ExecuteSnippet- 在类似 REPL 的环境中运行代码RenderPreview- 将 SwiftUI 预览渲染为图像DocumentationSearch搜索苹果文档和 WWDC 视频XcodeListWindows- 列出打开的 Xcode 窗口工具的工作原理大多数工具都需要tabIdentifier指定要在哪个 Xcode 窗口中进行操作。代理会自动处理此操作首先在 Xcode 中打开你的项目这些工具会对任何已打开的项目进行操作open MyApp.xcodeproj# oropen MyApp.xcworkspace请经纪人做类似“帮我建项目”之类的事情代理自动打电话询问XcodeListWindows如何发现敞开的窗户获取tabIdentifier例如windowtab1和工作区路径在实际工具调用中使用该标识符以下是您请求“构建我的项目”时的实际操作Agent: Ill first need to get the tabIdentifier by listing open Xcode windows.→ XcodeListWindows()← { message: * tabIdentifier: windowtab1, workspacePath: /Users/you/MyApp.xcodeproj }Agent: I see Xcode has MyApp.xcodeproj open. Ill build that.→ BuildProject({ tabIdentifier: windowtab1 })← { buildResult: The project built successfully., elapsedTime: 2.17, errors: [] }文档搜索此功能可搜索苹果公司的全部文档库和WWDC 视频文字稿。语义搜索由苹果内部称为“Squirrel MLX”的技术提供支持该技术是苹果公司针对 Apple Silicon 芯片优化的 ​​MLX 加速嵌入系统。当你查询某个框架时它可以从你可能错过的 WWDC 会议中提取相关的上下文信息。搜索范围涵盖从 iOS 15 到 iOS 26 的所有文档所有内容都已建立索引并支持语义搜索。渲染预览这段代码会渲染你的 SwiftUI 预览并返回实际图像。你的 AI 代理可以直观地看到UI 的实际效果。你可以让它调整颜色它可以通过视觉方式验证更改。这是其他任何 IDE 都无法为外部代理提供的功能。代理可以根据 UI 更改进行迭代并获得视觉反馈。执行代码片段一个类似 Swift REPL 的环境。无需创建文件或运行完整构建即可测试代码片段。非常适合快速验证逻辑或测试 API 调用。使用 AGENTS.md 添加上下文AGENTS.md苹果建议在项目根目录下的配置文件例如 .xcode.yml或.xcode.yml中添加有关 Xcode 和项目的提示信息CLAUDE.md。这有助于代理理解您的项目结构# Project Context## Build System- This is an iOS 26 SwiftUI project- Use BuildProject to compile, not shell commands- SwiftUI previews available via RenderPreview## Testing- Run tests with RunAllTests or RunSomeTests- Test results available via Xcodes test navigator## Documentation- Use DocumentationSearch to find Apple API docs- WWDC session transcripts are searchable手动PID配置特殊情况在极少数情况下如果自动检测不起作用例如同时运行多个 Xcode 版本您可以手动指定要连接的 Xcode{mcpServers: {xcode-tools: {command: xcrun,args: [mcpbridge],env: {MCP_XCODE_PID: 12345}}}}获取PIDpgrep -x Xcode只要 Xcode 运行PID 就保持不变。会话 ID高级mcpbridge 还接受一个可选的MCP_XCODE_SESSION_ID环境变量该变量被描述为“标识 Xcode 工具会话的 UUID”。Xcode 会自动为其内部代理生成这些 UUID您可以在其中看到它们~/Library/Developer/Xcode/CodingAssistant/codex/config.toml。对于像 Cursor 这样的外部客户端我还没有发现需要手动设置此参数的情况因为即使不手动设置自动检测也能正常工作。Xcode 警报当外部代理连接到 Xcode 时Xcode 中会显示一个指示器表明有外部工具已连接并处于活动状态。这有助于提高安全意识让您始终了解何时有程序或人员正在访问您的项目。自定义 Xcode 内置代理如果您想自定义在 Xcode内部运行的 Codex 或 Claude 代理而非外部代理可以使用以下位置的配置文件法典~/Library/Developer/Xcode/CodingAssistant/codex/克劳德·阿特格~/Library/Developer/Xcode/CodingAssistant/ClaudeAgentConfig/这些目录与标准目录.codex和.claude配置目录相对应但彼此分开因此 Xcode 不会干扰您现有的配置。接下来会发生什么您可以构建工作流程将 Xcode 的原生功能构建、测试、预览与其他 MCP 服务器如 Figma相结合以实现从设计到代码的流程。苹果公司将此功能作为标准的 MCP 接口开放而不是将其限制在自家代理程序中这表明他们希望生态系统以新的方式与 Xcode 集成。官方文档甚至也鼓励这样做。如果您喜欢此文章请收藏、点赞、评论谢谢祝您快乐每一天。

相关新闻