Skip to main content
Glama
README.md
# computer-use-mcp

一个本地运行的 [Model Context Protocol](https://modelcontextprotocol.io/) 服务,让 LLM Agent 真正操作 macOS 桌面:截屏、移动/点击鼠标、拖拽、滚动、输入文字、按快捷键、查看窗口、读写剪贴板、启动 App。

- **stdio MCP 服务**:服务自身不监听端口;后台 Chrome 使用本机 localhost DevTools 端口,Chrome 页面可访问网络。
- **极简依赖**:Python 标准库 + PyObjC(Quartz / AppKit),CDP WebSocket 客户端无需额外依赖。
- **35 个工具**:包含 macOS 桌面与后台 Chrome 控制,观察类和操作类分离,支持只读模式。
- **坐标可换算**:截图元数据直接给出「图片像素 → 屏幕坐标」的换算系数。

## 环境要求

- macOS 12 或更高版本(在 macOS 14.5 / Apple M2 上验证)。
- Python 3.10+,且能 `import Quartz, AppKit`。
- python.org 安装的系统 Python 通常已自带 PyObjC;如果没有:

```bash
python3 -m pip install pyobjc-framework-Cocoa pyobjc-framework-Quartz
```

先确认:

```bash
python3 -c "import Quartz, AppKit; print('PyObjC ok')"
```

## 快速开始

```bash
cd "<path-to-computer-use-mcp>"

./bin/computer-use-mcp --version     # computer-use-mcp 0.1.0
./bin/computer-use-mcp --print-tools # 查看完整工具 JSON Schema

# 端到端冒烟测试(观察类,不动鼠标)
python3 scripts/smoke_test.py
```

`bin/computer-use-mcp` 会自动寻找一个带 PyObjC 的 `python3`,因此**不需要 pip install** 就能运行。需要指定解释器时:

```bash
COMPUTER_USE_MCP_PYTHON=/path/to/python3 ./bin/computer-use-mcp
```

也可以安装为命令(可选):

```bash
python3 -m pip install -e .
computer-use-mcp
```

## 接入 MCP 客户端

将示例中的 `<path-to-computer-use-mcp>` 替换为本地项目目录的绝对路径。

### StepCode(`~/.stepcode/config.toml`)

```toml
[mcp_servers.computer-use]
command = "<path-to-computer-use-mcp>/bin/computer-use-mcp"
args = []
enabled = true
```

只读模式:

```toml
[mcp_servers.computer-use.env]
COMPUTER_USE_MCP_READ_ONLY = "1"
```

### Claude Desktop / 其他 JSON 配置

见 [examples/claude-desktop-config.json](examples/claude-desktop-config.json):

```json
{
  "mcpServers": {
    "computer-use": {
      "command": "<path-to-computer-use-mcp>/bin/computer-use-mcp",
      "args": []
    }
  }
}
```

通用形式永远是:

```text
command: /绝对路径/computer-use-mcp/bin/computer-use-mcp
args: []
transport: stdio
```

## 权限(必须)

macOS 会按**启动这个 MCP 服务的宿主程序**授予权限,而不是按脚本路径。通常需要给 StepCode / Terminal / iTerm 授权,然后**重启宿主程序和 MCP 服务**。

1. **辅助功能(Accessibility)** — 合成鼠标 / 键盘事件。
   `系统设置 → 隐私与安全性 → 辅助功能`
2. **屏幕录制(Screen Recording)** — 截屏。
   `系统设置 → 隐私与安全性 → 屏幕录制`

授权后可在 Agent 中调用:

```json
{"name": "get_permissions", "arguments": {}}
```

返回:

```json
{
  "accessibility": true,
  "screen_recording": true,
  "screen_locked": false,
  "frontmost_app": {"name": "Safari", "bundle_id": "com.apple.Safari", "pid": 1234}
}
```

如果为 `false`,可以调用 `open_permission_settings` 直接打开对应面板。

> **锁屏注意**:`screen_locked: true` 时,截图看到的是锁屏界面,合成输入无法送达应用窗口。请先解锁 Mac;`get_screen_info` 和截图元数据会返回 `warning` 字段提醒调用方。为避免把按键送进登录密码框,锁屏状态下 `type_text` / `press_keys` / `key_down` / `key_up` 的全局注入会被拒绝;显式指定 `target_pid` 的直投仍可用。

## 坐标系统与截图

- 所有坐标单位是 **screen points**(逻辑点,不是 Retina 像素)。
- 原点在主显示器**左上角**,X 向右,Y 向下。
- 多显示器时,主屏左侧 / 上方的屏幕坐标为负数。`get_screen_info` 会返回每块屏幕的 `bounds`。
- 截图默认:
  - `resolution: "logical"` → 未触发 `max_dimension` 缩小时,1 个图片像素 = 1 个屏幕点;
  - `max_dimension: 1600` → 最长边超过 1600 时等比缩小;
  - `format: "png"`。
- 截图返回的文本元数据包含:

```json
{
  "image_width": 1600,
  "image_height": 1000,
  "region": {"x": 0, "y": 0, "width": 1440, "height": 900},
  "coordinate_mapping": {
    "points_per_image_pixel_x": 0.9,
    "points_per_image_pixel_y": 0.9
  }
}
```

把模型在图片上估的像素坐标换算成工具坐标:

```text
screen_x = region.x + image_x * points_per_image_pixel_x
screen_y = region.y + image_y * points_per_image_pixel_y
```

需要原始 Retina 分辨率时传 `resolution: "native", max_dimension: 0`;只需要局部细节时传 `x / y / width / height` 区域截图,避免整屏缩小后看不清小字。

## 工具

### 观察

| 工具 | 说明 |
| --- | --- |
| `get_screen_info` | 显示器、缩放、光标、虚拟桌面、权限、锁屏状态、前台 App。**建议先调用**。 |
| `screenshot` | 全屏 / 区域 / 窗口截图。参数:`display, x, y, width, height, window_id, resolution, max_dimension, format, quality`。返回文本元数据 + 图片。 |
| `list_windows` | 按前后顺序列出窗口:`window_id, app, title, pid, bounds`。 |
| `get_cursor_position` | 当前光标坐标。 |
| `get_permissions` | 辅助功能 / 屏幕录制 / 锁屏 / 前台 App。 |
| `clipboard_read` | 读取剪贴板文本。 |
| `wait` | 等待 `milliseconds` 毫秒,给动画 / 启动留时间。 |

### 鼠标

| 工具 | 说明 |
| --- | --- |
| `move_mouse` | `x, y, duration_ms`;`duration_ms: 0` 瞬移。 |
| `click` | `x?, y?, button(left/right/middle), clicks(1-5), interval_ms, modifiers`。支持 shift-click。 |
| `mouse_down` / `mouse_up` | 按住 / 松开鼠标键,用于手动拖拽。 |
| `drag` | `x1, y1, x2, y2, duration_ms, button, modifiers`。 |
| `scroll` | `dy, dx?, x?, y?, modifiers`;`dy > 0` 向上滚动。 |

### 键盘

| 工具 | 说明 |
| --- | --- |
| `type_text` | `text, method(unicode/keycode), interval_ms, target_pid?`。Unicode 支持中文、Emoji。 |
| `press_keys` | `keys: "cmd+c"` 或 `["cmd+a", "delete"]`,`repeats, interval_ms, hold_ms, target_pid?`。 |
| `key_down` / `key_up` | 单独按住 / 释放按键或修饰键。 |

支持 `cmd/command`、`shift`、`option/alt`、`control/ctrl`、`fn`,以及 `enter`、`esc`、`tab`、`space`、`backspace`、方向键、`f1`–`f20`、`pageup/pgdn/home/end` 等。

### 窗口、App、系统

| 工具 | 说明 |
| --- | --- |
| `focus_window` | 激活窗口所属 App 并前置。若同 App 有多个窗口,之后再点击目标窗口。 |
| `activate_app` | 将已运行的 App 置前;未运行则启动。 |
| `open_app` | 按名称、路径或 bundle id 启动 App。 |
| `open_url` | 仅允许 `http`、`https`、`mailto`。 |
| `open_permission_settings` | 打开辅助功能 / 屏幕录制设置面板。 |

### 后台 Chrome(Chrome DevTools Protocol)

这组工具通过 Chrome DevTools Protocol 控制标签页,不激活窗口、不用 Spotlight、不移动桌面鼠标。`chrome_start` 会启动独立的无头 Chrome,使用单独的持久化用户目录 `~/Library/Application Support/computer-use-mcp/chrome`;可在 MCP 服务重启后继续连接。它不会复用日常 Chrome 配置或其登录状态。

| 工具 | 说明 |
| --- | --- |
| `chrome_start` | 启动后台 Chrome,可传 `url`,默认 `about:blank`。 |
| `chrome_status` | 检查后台实例状态。 |
| `chrome_connect` | 连接已启用远程调试的本机 Chrome,参数为 `port`。 |
| `chrome_tabs` / `chrome_open_tab` / `chrome_navigate` / `chrome_close_tab` | 列出、打开、导航、关闭标签页。 |
| `chrome_read_page` / `chrome_screenshot` | 读取页面标题、URL、可见文本或后台截图。 |
| `chrome_click` / `chrome_type_text` | 通过 CDP 鼠标事件点击可见元素,或聚焦输入框并写入文本。 |
| `chrome_stop` | 关闭本工具启动的独立 Chrome;拒绝关闭外部连接的实例。 |

最短调用流程:

```text
chrome_start({"url":"https://example.com"})
chrome_tabs({})
chrome_read_page({"tab_id":"上一步返回的 tab_id"})
chrome_screenshot({"tab_id":"上一步返回的 tab_id"})
```

从 MCP 客户端调用 `chrome_start` 后,无需保持 Chrome 窗口在前台。若要接管一个额外启动并启用了调试的 Chrome,可在启动 Chrome 时传入 `--remote-debugging-port=9222 --user-data-dir=/独立的/用户目录`,再调用 `chrome_connect({"port":9222})`。为避免泄露浏览器会话,**不要**对日常个人资料目录开放调试端口。macOS 上 Chrome 136+ 仅对非默认用户目录开放远程调试。

仅允许 `http`、`https` 和 `about:blank` 页面地址;端口及 WebSocket 必须是 localhost。页面点击、表单输入、导航和关闭标签会实际改变网页状态。此实现不暴露任意 JavaScript 执行工具。

### 只读模式

两种开启方式:

```bash
./bin/computer-use-mcp --read-only
COMPUTER_USE_MCP_READ_ONLY=1 ./bin/computer-use-mcp
```

只读模式下,桌面输入操作、启动 / 停止 Chrome、打开 / 导航 / 关闭标签、页面点击和输入会返回 `isError: true`;桌面截图、Chrome 状态 / 标签 / 页面读取仍然可用。

## 典型 Agent 工作流

```text
1. get_screen_info
   → 确认屏幕、权限、是否锁屏、前台 App

2. screenshot {"max_dimension": 1600}
   → 看截图,定位目标

3. click {"x": 742, "y": 318}
   或 type_text {"text": "hello"}
   或 press_keys {"keys": "cmd+s"}

4. screenshot {"x": 600, "y": 200, "width": 600, "height": 400}
   → 用局部截图确认结果
```

给模型的提示词示例:

> 打开 Safari,搜索「Model Context Protocol」,把第一条结果的标题和链接告诉我。每步操作后截图确认。

## 安全设计

- MCP 服务仅使用 **stdio**;本机 Chrome 另通过 loopback-only DevTools 端口通信,Chrome 页面本身可能访问外网。
- 不提供 shell / 任意 JavaScript 执行工具。
- 浏览器 URL 限制为 `http/https/about:blank` 并拒绝凭据;DevTools HTTP 不跟随重定向,WebSocket 地址与连接均限定在 localhost。
- stderr 日志会**脱敏**:不记录输入的文本、URL、按键、App 名、`target_pid` 的具体值,只记录长度 / 类型。
- 合成输入可以造成真实后果(删除、发送、购买)。默认建议在 Agent 侧对危险动作做人工确认;不确定时使用只读模式。
- `clipboard_read` 可能读到密码等敏感内容,仅在需要时使用。

## 项目结构

```text
computer-use-mcp/
├── bin/computer-use-mcp           # 免安装启动器(自动找带 PyObjC 的 python3)
├── src/computer_use_mcp/
│   ├── server.py                  # MCP stdio JSON-RPC
│   ├── tools.py                   # 35 个工具的 JSON Schema 与分发
│   ├── chrome.py                  # 隔离后台 Chrome + DevTools Protocol
│   ├── macos.py                   # Quartz/AppKit 桌面控制
│   └── keymap.py                  # macOS 虚拟键码与快捷键解析
├── tests/                         # 标准库 unittest(无需 pytest)
├── scripts/smoke_test.py          # 通过 stdio 启动真实服务做端到端测试
├── examples/                      # 客户端 Demo + StepCode/Claude 配置
├── pyproject.toml
└── README.md
```

## 测试

```bash
# 单元测试(协议、键位、坐标、参数校验)
PYTHONPATH=src python3 -m unittest discover -s tests -v

# 端到端:握手、工具列表、权限、截屏、窗口截图、错误码、只读模式
python3 scripts/smoke_test.py

# 额外验证真实输入(会移动鼠标;可选向测试 App 注入文字)
python3 scripts/smoke_test.py --input
python3 scripts/smoke_test.py --input --target-pid 12345
```

一次实际运行结果:

```text
58 tests OK
PASS: computer-use-mcp is working
display: 1440.0x900.0 points, scale 2.0
permissions: accessibility=True screen_recording=True screen_locked=False
```

额外验证:

- 用官方 Python MCP SDK `1.30.0` 的 `ClientSession` 通过 stdio 完成 `initialize` / `tools/list` / `tools/call`,并正确解析了返回的 `ImageContent`。
- 对一个本地测试 Cocoa App:验证了单击、双击(本地事件监视器收到 1 次/2 次 mouseDown)、Unicode 文本注入(含中文),以及 `shift+left` 这类带修饰键的按键(`ABC` → 选中 `C` → 输入 `Z` 得到 `ABZ`)。
- 锁屏时 `get_screen_info` / 截图会返回 `warning`,全局键盘输入会被拒绝,避免把按键送进登录密码框。

## 已知限制

- **仅 macOS**;依赖 Quartz / AppKit。
- **锁屏时**输入不会到达普通应用窗口;请先解锁。
- 密码框等 **secure input** 会刻意忽略合成键盘事件。
- `focus_window` 只能激活 App;同一 App 的多个窗口需要通过点击来精确前置(未使用 AXRaise)。
- 受保护窗口(如部分系统窗口、DRM 内容)可能无法截图。
- 某些游戏 / 远程桌面 / 虚拟机使用底层输入抓取,可能忽略合成事件。
- 不包含 OCR;识别截图内容由调用方模型完成。
- 多用户 / 远程桌面场景未专门验证。

## 故障排查

| 现象 | 处理 |
| --- | --- |
| `no python3 with PyObjC found` | 安装 PyObjC,或用 `COMPUTER_USE_MCP_PYTHON` 指定解释器。 |
| 工具列表为空 | 客户端配置里 `command` 必须是绝对路径;用 `--print-tools` 先确认服务能启动。 |
| 权限显示 `true` 但仍无输入 | 权限授予的是启动服务的宿主程序;改完后重启宿主程序和 MCP 服务。 |
| 截图全黑 / 失败 | 检查屏幕录制权限;锁屏时只能看到锁屏画面。 |
| 中文输入失败 | 用 `type_text`(默认 `unicode`);某些 App 需要 `method: "keycode"` 输入 ASCII。 |
| 快捷键没反应 | 确认目标 App 在前台;必要时先 `activate_app`。 |
| 想看服务日志 | 客户端通常把 stderr 显示在 MCP 日志中;也可手动运行 `./bin/computer-use-mcp`。 |

## License

MIT,见 [LICENSE](LICENSE)。