Skip to main content
Glama

bettbox-mcp

让 AI agent 通过 MCP 控制本机正在运行的 Bettbox(基于 mihomo 内核的 Clash 客户端)。

零客户端补丁。 所有能力都来自 Bettbox 自己已经暴露的三个面:mihomo REST API、控制套接字、以及 config.json / profiles/*.yaml。


它能做什么

能力

工具

生效方式

查看整体状态

bettbox_get_status

只读

列出订阅(含配额/到期)

bettbox_list_subscriptions

只读

列出策略组 / 组内节点

bettbox_list_proxy_groups / bettbox_list_proxies

只读

节点测速(单点或整组)

bettbox_test_delay

只读

查看实时连接

bettbox_list_connections

只读

切换节点

bettbox_select_proxy

即时

出站模式(规则/全局/直连)

bettbox_set_mode

即时

TUN 开关

bettbox_set_tun

即时(仅本次运行)

断开连接

bettbox_close_connections

即时

更新订阅内容

bettbox_update_subscription

写 YAML,下次应用生效

全部同步

bettbox_sync_all_subscriptions

同上,并发

添加 / 删除订阅

bettbox_add_subscription / bettbox_remove_subscription

需重启一次

重启 / 退出客户端

bettbox_restart_app / bettbox_stop_app

进程级


Related MCP server: Clash Control MCP

环境要求

  • Python 3.10+

  • uv(推荐)或 pip

  • Bettbox 桌面端已安装并运行

  • 在 Bettbox 里开启「外部控制器」(一次性,见下)

必做的一次性设置

打开 Bettbox → 设置 → 通用 → 外部控制器。

开启后它会自动生成密钥并写入 config.json:

"external-controller": "127.0.0.1:9090",
"secret": "<自动生成>"

验证:

curl -H "Authorization: Bearer <secret>" http://127.0.0.1:9090/version
# {"meta":true,"version":""}

密钥只存在于 config.json 的 patchClashConfig.secret,REST API 不会回显它。本 MCP 从文件读取,写进日志与对话之前会脱敏。


安装

git clone https://github.com/InkiChang/bettbox-mcp.git
cd bettbox-mcp
uv sync

先跑一次体检(只读,不会碰 Bettbox):

uv run python tests/platform_probe.py

输出结尾是 RESULT: all checks passed 就可以继续了。


在 DSH 里安装

方式一:图形界面

DSH → 设置 → MCP 连接器 → 添加自定义连接,填:

字段

值

名称

Bettbox

传输方式

stdio

命令

/home/<你>/…/bettbox-mcp/.venv/bin/python

参数

-m bettbox_mcp

工作目录

…/bettbox-mcp

作用域

全局

保存后 DSH 会拉起服务,16 个工具以 mcp__bettbox__* 前缀注入。

Linux 上不要用 uv run 作为命令——多一层进程会拖慢启动,也更容易被环境变量影响。直接用 venv 里的 python。

方式二:配置文件

DSH 把连接记在 ~/.dsh/storages/mcp_connector.json。用图形界面添加更稳妥;若手改该文件,注意它由宿主维护、结构可能随版本变化。

方式三:给别的 MCP 客户端用

任何支持 MCP 的客户端都可以,标准配置:

{
  "mcpServers": {
    "bettbox": {
      "command": "/home/<你>/bettbox-mcp/.venv/bin/python",
      "args": ["-m", "bettbox_mcp"],
      "cwd": "/home/<你>/bettbox-mcp"
    }
  }
}

Windows 上把命令换成 ...\bettbox-mcp\.venv\Scripts\python.exe。


平台说明

Linux(首选平台)

Linux 上控制通道走 直接 Unix 域套接字连接,不生成子进程、不依赖进程表,最稳。

安装方式

数据目录

备注

deb / rpm / AUR

~/.local/share/bettbox

二进制在 PATH 即可

AppImage

$XDG_DATA_HOME/bettbox

重启时用 $APPIMAGE 指向的真实文件,不是 /tmp/.mount_*;MCP 会自动补 chmod +x

snap

~/snap/<name>/current/.local/share/…

—

flatpak

~/.var/app/<id>/data/…

—

TUN 权限:需要 core 具备 cap_net_admin。

sudo setcap cap_net_admin,cap_net_bind_service,cap_net_raw=+ep <core 路径>

Bettbox 在你第一次开 TUN 时会尝试自动完成(失败回退 setuid)。本 MCP 不接触、不保存任何密码,只做状态探测。

Wayland:启动 GUI 需要 WAYLAND_DISPLAY 或 DISPLAY,headless 环境下 bettbox_restart_app 会明确报错而不是静默失败。

macOS

路径 /Applications/Bettbox.app/Contents/MacOS/Bettbox,控制通道同样是 UDS。首次开 TUN 需在系统弹窗里授权一次。

Windows

⚠️ 已知限制:CPython 在 Windows 上没有 socket.AF_UNIX,控制命令只能通过 Bettbox.exe --exit / --restart 生成子进程转发。如果 MCP 运行在限制了进程可见性的沙箱里(实测 DSH 就是这样:外部 shell 能看到 383 个进程,被沙箱的 Python 只看到 55 个),子进程会报 Bad state: Bettbox is not running,启停类操作不可用。

能力

沙箱内

沙箱外

只读查询 / Clash API 热写 / 更新订阅 YAML

✅

✅

增删订阅、启停 App

❌

✅

只读与热写不受影响,日常使用足够;需要增删订阅时手动操作客户端即可。


工作原理

┌──────────────┐
│  MCP client  │  (DSH / Claude Desktop / Cursor …)
└──────┬───────┘
       │ stdio (JSON-RPC)
┌──────▼───────────────────────────────────────┐
│  bettbox-mcp                                 │
│  ├─ ClashClient  ──HTTP──▶ 127.0.0.1:9090    │  运行时读写,即时生效
│  ├─ app_control  ──UDS──▶  Bettbox.control.sock │  启停/重启
│  └─ store        ──file──▶ config.json, profiles/*.yaml │  订阅增删改
└──────────────────────────────────────────────┘

为什么有些操作要重启

Bettbox 在优雅退出时会把内存里的 Config 写回 config.json(savePreferences())。所以 App 运行期间改这个文件会被覆盖。

  • 订阅列表、应用设置 → 存在 config.json → 必须「退出 → 改 → 启动」

  • 订阅内容 → 存在 profiles/*.yaml → 退出时不重写 → 无需重启

订阅更新的实现

「更新订阅」是复刻了 App 里「全部同步」按钮的逻辑(Profile.update() → saveFile()):

  1. 用 App 自己的 UA(FlClash/ClashMetaForAndroid/…)经代理下载 ——服务商按 UA 决定返回 Clash YAML 还是节点列表

  2. utf8.decode → tab 转两个空格(同 patchYamlConfig)

  3. 结构校验(替代 App 内部的 FFI 校验,见下)

  4. 内容相同则跳过;否则备份后原子写(temp + rename)

  5. 可选:回写 lastUpdateDate 与 subscriptionInfo

唯一无法复刻的部分:App 用 clashCore.validateConfig(Dart↔Go 的 FFI)做完整校验,没有 REST 出口。本 MCP 用轻量结构校验替代(必须含 proxies/proxy-groups、必须含端口键),能拦住空响应、HTML 错误页、被截断的 YAML。


安全边界

  • 密钥不出文件:只从 config.json 读,不写日志、不进 tool 返回值

  • 订阅 URL 默认打码(多数 URL 内含账号 token),需要时用 reveal_urls=true

  • 所有写操作先备份:config.json.mcp-bak-<时间戳>、<id>.yaml.mcp-bak

  • 不提供「修改内核路径」类工具:Bettbox 的 core 带提权位(setuid/setcap),暴露它就等于开放提权链

  • 拒绝删除当前正在使用的订阅,避免自断网络


开发

uv run python -m bettbox_mcp                # 以 stdio 启动

uv run python tests/platform_probe.py       # 环境体检(只读)
uv run python tests/platform_probe.py --apply   # 含启停验证(会短暂断网)
uv run python tests/smoke.py                # 只读工具回归
uv run python tests/write_tools.py          # 可逆写操作回归
uv run python tests/stdio_protocol.py       # 真实 MCP 客户端握手
uv run python tests/agent_workflow.py       # 复合任务:测速→选最优→切换→验证→还原

项目结构

src/bettbox_mcp/
├── config.py       跨平台数据目录 / 可执行文件发现,形状校验
├── clash_api.py    mihomo REST 客户端(httpx, trust_env=False 直连)
├── app_control.py  进程控制:UDS / CLI 双通道,RestartWindow
├── store.py        config.json 原子读写,订阅同步逻辑
├── models.py       Pydantic 输入校验
└── server.py       FastMCP 工具注册

实测记录

Bettbox 1.19.7 / Windows 11 / Python 3.11:

  • 外部控制器开启后 9090 正常监听,无密钥访问返回 401

  • PATCH /configs 改 mode / log-level 即时生效

  • PUT /proxies/{group} 切节点即时生效,/proxies 立即可见

  • GET /proxies/{name}/delay 返回真实延迟

  • 订阅增删:config.json 的 profiles 数组可安全增删,App 启动不回滚

  • 订阅更新:复刻「全部同步」成功,YAML 与配额均被 App 正确读回

  • GET /configs 不含 external-controller / secret(只能从文件读)

  • /traffic 是 WebSocket 端点,普通 GET 会挂起

  • --quick / --boot 是 Android 专属,桌面端只认 --exit / --restart

Linux / macOS 的路径发现与 UDS 通道已实现,但尚未在真机验证——用 tests/platform_probe.py 确认后再接线。


致谢

  • Bettbox — FlClash 分支,本项目所有能力都建立在它已有的接口之上

  • mihomo — 内核

  • mcp-builder — 服务端设计参考

License

MIT

Available Tools

16 tools
bettbox_add_subscriptionA

Register a new subscription and optionally download it right away.

Adding needs a restart because the profile list lives in config.json, which Bettbox overwrites on exit; the tool therefore performs the whole exit -> edit -> start cycle atomically.

Args: params (AddSubscriptionInput): url, optional label and position, and download.

Returns: str: The new profile id plus whether a restart happened.

Inputs: params (required). Returns: result

bettbox_close_connectionsA
Destructive

Close one live connection, or every connection when id is all.

Args: params (CloseConnectionInput): connection_id from bettbox_list_connections, or the literal all.

Returns: str: Confirmation.

Inputs: params (required). Returns: result

bettbox_get_statusA
Read-only

Report whether Bettbox is running and what the proxy is currently doing.

Combines three independent sources so a partial failure is still useful: the OS process table, the on-disk config, and the mihomo REST API.

Args: params (StatusInput): include_traffic adds cumulative byte counters.

Returns: str: Markdown report. Key fields per section: - process: running (bool), executable (path or null) - config: data_dir, current_profile, controller, mixed_port - runtime: mode, tun, nodes, groups, controller_ok Failure text starts with Error:.

Inputs: params (required). Returns: result

bettbox_list_connectionsB
Read-only

List active connections with host, rule, chain and transferred bytes.

Args: params (ListConnectionsInput): limit, sort_by, response_format.

Returns: str: Markdown table or JSON. Per row: host, rule, chain, download, upload, start.

Inputs: params (required). Returns: result

bettbox_list_proxiesA
Read-only

List the member nodes of one proxy group, marking the active one.

Args: params (ListProxiesInput): group is the exact group name from bettbox_list_proxy_groups.

Returns: str: Markdown list or JSON array. Per node: name, type, active (bool), delay (int ms or null).

Inputs: params (required). Returns: result

bettbox_list_proxy_groupsB
Read-only

List proxy groups with their currently selected member and member counts.

Args: params (ListProxyGroupsInput): only_selectable filters out non-selectable groups; response_format picks the layout.

Returns: str: Markdown table or JSON. Per group: name, type, now, members (int), hidden (bool), has_icon (bool).

Inputs: params (required). Returns: result

bettbox_list_subscriptionsA
Read-only

List every subscription configured in Bettbox, with quota and last update.

Reads config.json only; the app does not need to be running.

Args: params (ListSubscriptionsInput): response_format and reveal_urls.

Returns: str: Markdown table or JSON array. Per row: id, label, current (bool), auto_update (bool), last_update (str), used / total (bytes), expire (epoch seconds), url.

Inputs: params (required). Returns: result

bettbox_remove_subscriptionA
Destructive

Delete a subscription. Requires one app restart.

Refuses to delete the currently active profile; switch away first.

Args: params (RemoveSubscriptionInput): profile (id or label) and keep_files.

Returns: str: Confirmation with the removed label and restart flag.

Inputs: params (required). Returns: result

bettbox_restart_appA

Restart the Bettbox app through its control socket.

A restart briefly drops the proxy (the system proxy setting is restored on the way back up). Use it after changing anything in config.json.

Args: params (RestartAppInput): optional reason for the audit trail.

Returns: str: Whether the restart completed and whether the controller is back.

Inputs: params (required). Returns: result

bettbox_select_proxyA

Switch the active node of a group. Takes effect immediately.

This does not restart the app and is not persisted to config.json by this call; Bettbox records the selection itself on the next state save.

Args: params (SelectProxyInput): group and the target proxy.

Returns: str: Confirmation with the group's new active node.

Inputs: params (required). Returns: result

bettbox_set_modeA

Change the outbound routing mode: rule / global / direct.

Runtime-only. Bettbox rebuilds the config from config.json on the next start, so a persisted default still wins after a restart.

Args: params (SetModeInput): mode.

Returns: str: Confirmation naming the previous and the new mode.

Inputs: params (required). Returns: result

bettbox_set_tunA

Enable or disable TUN for the current session only.

Enabling TUN needs the core binary to already hold elevation. Bettbox grants that once (setuid on macOS/Linux, a helper service on Windows); this MCP never handles a password. If elevation is missing the core rejects the change and the tool reports the error.

Args: params (SetTunInput): enable.

Returns: str: Confirmation plus a reminder that the change is not persisted.

Inputs: params (required). Returns: result

bettbox_stop_appB
Destructive

Quit Bettbox, which also stops proxying.

Uses the graceful path, so system proxy, DNS and TUN are restored by the app itself. Force-killing would leave the system proxy pointing at a dead port.

Args: params (StopAppInput): optional reason.

Returns: str: Whether the process exited.

Inputs: params (required). Returns: result

bettbox_sync_all_subscriptionsA

Refresh every subscription at once - the app's "sync all" button.

Skips local-file profiles (they have no URL), runs the downloads concurrently, and reports one row per subscription.

Args: params (SyncAllSubscriptionsInput): sync_metadata and concurrency.

Returns: str: Markdown table with ok / changed / size / error per profile, plus whether a restart happened.

Inputs: params (required). Returns: result

bettbox_test_delayA
Read-only

Measure latency for one node or every member of a group.

Args: params (TestDelayInput): name, kind ('auto' by default) and timeout_ms.

Returns: str: Markdown table. Group mode returns one row per member; a failed node reports timeout.

Inputs: params (required). Returns: result

bettbox_update_subscriptionA

Download fresh configs for the named subscriptions and write them to disk.

Mirrors the app's per-profile refresh: fetch the URL through the proxy, normalise tab indentation, validate the structure, then atomically replace profiles/<id>.yaml. The app does not need to be stopped.

Args: params (UpdateSubscriptionInput): profiles (ids or labels), sync_metadata to also refresh dates/quotas (needs a restart), validate_only to dry-run.

Returns: str: Per-profile result: ok, changed, bytes, nodes, error. Ends with whether a restart happened.

Inputs: params (required). Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 16 tools

    Disambiguation5/5

    Each tool targets a distinct action or resource: runtime settings, status, subscriptions, proxy groups/nodes, latency tests, connections, and app lifecycle are cleanly separated. The only potential overlap is update_subscription vs sync_all_subscriptions, but the bulk-vs-named distinction is explicit.

    Naming Consistency5/5

    All tools use the same bettbox_ prefix and snake_case verb_noun naming. Verbs such as set, get, list, select, close, update, sync_all, add, remove, restart, and stop are used predictably.

    Tool Count4/5

    Sixteen tools is slightly above the typical well-scoped range, but the server covers several distinct areas of Bettbox management and most tools earn their place. It is reasonable rather than bloated.

    Completeness3/5

    Subscription CRUD, proxy selection, connection management, and runtime settings are well covered, but there are notable gaps: no tool starts the app after stop_app, and no tool switches the active subscription despite remove_subscription refusing to remove the current profile until the user switches away. These create avoidable dead ends in otherwise solid lifecycle coverage.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Bridges the mihomo (Clash Meta) RESTful API to the Model Context Protocol, enabling AI clients to switch proxies, test latency, refresh subscriptions, set operating modes, and monitor connections.
      10
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      Enables AI/MCP clients to manage a local mihomo/Clash Meta core by switching proxies, testing latency, viewing or closing connections, changing modes, and toggling TUN and Windows system proxy settings through a named pipe or HTTP control channel.
      10
      MIT