Clash Control MCP

Clash Control MCP

Enables AI agents to safely read, audit, and manage Clash Verge Rev / Mihomo configuration with read-only and controlled runtime operations.

Category
访问服务器

README

Clash Control MCP

A MCP Server that lets AI agents safely read, audit, and manage Clash Verge Rev / Mihomo configuration. v1.0.0-rc.1 — authenticated Clash Verge Adapter writes, recovery inspection, and evidence-driven optimization helpers.

What This Does

Clash Control MCP exposes Clash Verge Rev's configuration and Mihomo's runtime state to AI agents (Codex, ZCode, Claude Code) through the Model Context Protocol. Agents can:

  • Detect Clash Verge Rev installation, version, and config paths
  • Read Mihomo runtime status (version, mode, ports, connections, traffic)
  • List and inspect proxy groups, profiles, and providers
  • Audit configuration for issues
  • Discover Verge settings and their storage locations

The original v0.1 tools remain read-only. v0.2-A adds two runtime-only operations: allowlisted delay testing and confirmed proxy selection with verification and rollback. It does not modify persistent configuration, DNS, TUN, or system proxy settings.

Core MCP Setup from Source

git clone https://github.com/huaqing0/clash-control-mcp.git
cd clash-control-mcp
npm install
npm run build
npm run setup -- --all

This legacy core-only setup keeps the official Clash Verge App unchanged. It detects the local controller, backs up the selected client configurations, and installs the MCP server into Codex and ZCode. The controller secret is never printed, but it must be stored in each selected client's private MCP config.

Install only one client:

npm run setup -- --codex
npm run setup -- --zcode

The supported Adapter installer below configures TRAE's detected global MCP file; it never creates a project-local .trae/mcp.json. Use that path for Codex, ZCode, or TRAE when testing Profile refresh/activation.

Restart the configured client, then ask it to call clash.capabilities.

Uninstall the managed entries:

npm run setup -- --all --uninstall

Upgrade a source installation by pulling the new code and running the same setup command again. The managed entry is replaced rather than duplicated:

git pull
npm install
npm run setup -- --all

The installer creates timestamped backups beside the Codex and ZCode config files and keeps the resulting files at mode 0600. Because stdio MCP clients must pass the controller secret to the server, the secret is stored in the client's local configuration; never publish or share those files.

If auto-detection is unavailable, provide the values only for the setup process:

CLASH_CONTROLLER_URL=http://127.0.0.1:9097 \
CLASH_CONTROLLER_SECRET='your-secret' \
npm run setup -- --all

Clash Verge Adapter Lifecycle

Profile refresh, activation, and future Verge-memory synchronization require the companion Adapter App. From a source checkout, use the single lifecycle entrypoint (Node.js 20.19.0 or newer):

npm ci
npm run build
npm exec -- clash-control-adapter --help
npm exec -- clash-control-adapter install --help

It provides install, upgrade, verify, uninstall, patch-install, patch-verify, and patch-uninstall. Full installation requires a separately built and validated Adapter .app; it does not download or silently replace Clash Verge. See ADAPTER-INSTALLATION.md for the dry-run-first workflow, supported global client paths, recovery model, and recovery rules. Users of the version-pinned Apple Silicon unsigned patch should follow ADAPTER-PATCH-INSTALLATION.md. The GPL-3.0 Adapter source is maintained separately at huaqing0/clash-verge-adapter.

Build Only

npm install
npm run build

Configure

Set environment variables (see .env.example for reference):

CLASH_CONTROLLER_URL=http://127.0.0.1:9097
CLASH_CONTROLLER_SECRET=your-secret-here
# Optional: Unix socket fallback (auto-detected from Verge if not set)
# CLASH_CONTROLLER_SOCKET=/tmp/verge/verge-mihomo.sock

The secret is in your Clash Verge Rev generated config (clash-verge.yaml), under the secret: key.

Never commit your secret to git. Configure it via MCP env in your agent config or system environment variables.

Run

# Start MCP server (stdio)
npm start

# Or run directly
node dist/index.js

Generic MCP client configuration:

{
  "mcpServers": {
    "clash-control": {
      "command": "node",
      "args": ["/path/to/clash-control-mcp/dist/index.js"],
      "env": {
        "CLASH_CONTROLLER_URL": "http://127.0.0.1:9097",
        "CLASH_CONTROLLER_SECRET": "your-secret"
      }
    }
  }
}

Smoke Test

npm run smoke-test

Validates the safe read-only Mihomo endpoints and writes a local, gitignored API-SMOKE-TEST.json. It may contain machine-specific runtime metadata and must not be published. The reload endpoint remains unverified when no side-effect-free probe is available.

Tools (66 tools)

v0.1 Read-Only Tools (15)

Tool Description
clash.capabilities Environment capabilities (must call first)
clash.doctor Comprehensive diagnostics
clash.verge.detect Verge detection: version, paths, compatibility
clash.verge.get_settings Read Verge network/runtime settings
clash.verge.get_directories Get config directories and paths
clash.verge.get_active_profile Get currently active profile
clash.profiles.list List Verge profiles (summarized and paginated)
clash.profiles.inspect Inspect a specific profile by UID
clash.config.get_effective Mihomo runtime config (from API)
clash.config.get_generated Generated Verge config summary with a safe section allowlist
clash.config.get_persistent Verge persistent config (from file)
clash.config.audit Audit configuration for issues
clash.runtime.get_status Mihomo runtime status summary
clash.runtime.list_proxy_groups List policy groups (summarized and paginated)
clash.runtime.get_proxy_group Get one policy group's safe, paginated candidate names and runtime health details

v0.2-A Runtime Control Tools (2)

Tool Description
clash.runtime.test_proxy_delay Test proxy delay with multiple samples, returns median and jitter
clash.runtime.select_proxy Switch proxy in Selector group with verification and auto-rollback

v0.2-B Runtime Discovery and Ops Tools (6)

Tool Description
clash.runtime.list_proxy_providers List safe proxy Provider names and summaries
clash.runtime.list_rule_providers List safe rule Provider names and summaries
clash.runtime.list_connections List redacted connection summaries and IDs
clash.runtime.refresh_proxy_provider Refresh a proxy provider (per-provider lock, confirmed, verified)
clash.runtime.refresh_rule_provider Refresh a rule provider (per-provider lock, confirmed, verified)
clash.runtime.close_connection Close a specific connection by ID (close-all NOT supported)

v0.3 Config and Recovery Tools (7)

Tool Description
clash.config.create_workspace Create an isolated in-memory workspace
clash.config.preview_change Preview a semantic, redacted diff
clash.config.validate_change Fail-closed schema, fingerprint, and risk validation
clash.config.apply_transaction Apply a validated low-risk workspace through the authenticated Adapter, then run file/runtime/network/GUI health checks with automatic rollback
clash.config.rollback Restore a persisted transaction snapshot
clash.transaction.resume Verify a persisted PENDING_RESTART after Verge restart
clash.recovery.status Read durable transaction/recovery state without modifying manifests or snapshots

v0.4 Verge Settings Tools (8, capability-gated)

Tool Description
clash.verge.set_unified_delay Set unified delay through the guarded settings transaction path
clash.verge.set_log_level Set Mihomo log level
clash.verge.set_ipv6 Set IPv6 state
clash.verge.configure_dns_override Strategic-merge the DNS kernel block
clash.verge.configure_ports Configure the mixed proxy port
clash.verge.configure_lan_access Configure LAN access with strong confirmation
clash.verge.configure_tun Strategic-merge the TUN kernel block with strong confirmation
clash.verge.set_auto_close_connection Configure Verge connection cleanup through the native Adapter settings path

Each setting remains independently capability-gated. On the tested Verge 2.5.1 QA Adapter build, the native settings path performs optimistic concurrency checks, updates Verge memory and persistence, applies Mihomo runtime state, queues GUI refresh, verifies desired/persisted/reported/GUI/ observed evidence, and compensates on failure. Official builds without the Adapter continue to fail closed.

v0.5-A/C Profile & Subscription Tools (6)

Tool Description
clash.profiles.inspect_chain Inspect a Verge profile's full chain: base profile, merge layer, override/script layer, rule layer; with per-layer fingerprint, parse status, and redacted subscription URL
clash.merge.inspect Inspect a Merge profile's raw structure, fingerprint, and summary
clash.override.inspect Inspect an Override (Script) profile; Script files are fingerprinted by raw content (raw-content algorithm), never parsed as YAML
clash.rules.inspect Inspect a profile's rule list with stable rule IDs, pagination (default 50, hard cap 200), and rule-level fingerprints
clash.profiles.refresh Refresh a remote subscription through the authenticated local Clash Verge Adapter. Local profiles return NOT_APPLICABLE; remote profiles require light confirmation, per-UID limiting/locking, and a bounded timeout. Returns BLOCKED when the Adapter is unavailable
clash.profiles.activate Activate a Profile through Clash Verge itself. Strong two-step nonce confirmation, active-Profile drift detection, and post-operation verification are mandatory because network routing may change

Security and capability notes:

  • All UID/path inputs are validated by ^[A-Za-z0-9_-]{1,120}$ and resolved with realpath + parent-directory walk. Directory-traversal payloads (.., absolute paths, ., -) are rejected before any filesystem access.
  • Inspect payloads are capped (MAX_RULES_RETURNED = 200, DEFAULT_RULES_LIMIT = 50) and paginate via cursor tokens; every layer returns a structured parseStatus (ok / missing / parse_error / not_yaml) with a parseError object — no silent failures.
  • Subscription URLs are deeply redacted to scheme://host/*** (path and query stripped) before entering any return payload.
  • clash.profiles.refresh distinguishes refreshKind: 'subscription' from Mihomo Proxy/Rule Provider refresh (clash.runtime.refresh_proxy_provider / clash.runtime.refresh_rule_provider). It never fakes REFRESHED — when the authenticated Adapter is unavailable it returns BLOCKED with manual GUI steps and the profileRefresh capability stays false.

Clash Verge Adapter

Profile refresh, activation, persistent Profile writes, synchronized proxy selection, and native Verge settings writes require the companion Adapter build. The Adapter is opt-in, listens only on 127.0.0.1, and requires a per-installation Bearer token. The installer stores that token only in a private 0600 credentials file; clients receive CLASH_VERGE_ADAPTER_TOKEN_FILE, not the token itself. Official Clash Verge builds remain supported for read-only and Mihomo runtime tools; Adapter-owned writes fail closed.

v0.5-B Profile Persistent Write Tools (5, capability-gated)

Tool Description
clash.profiles.update_metadata Update non-sensitive profile metadata in profiles.yaml. Allowlist: name, update_interval, desc. Protected fields (uid, type, file, url, option, auth, token, secret) are never modifiable. Two-phase: preview → execute with nonce
clash.merge.update Update a Merge YAML file with a strategic merge patch. Owner resolved from the target Profile's option.merge. Two-phase preview/nonce execution with Adapter verification and compensation
clash.override.update Update a YAML Override. JavaScript Script files (.js/.mjs) return NOT_SUPPORTED
clash.rules.add Add rules to a section (prepend/append/delete) of the independent Rules owner file. Stable anchors via beforeRuleFingerprint/afterRuleFingerprint (no line numbers). Duplicate rules rejected. Max 100 per operation. Two-phase: preview → execute with nonce
clash.rules.remove Remove rules by fingerprint from a section of the Rules owner file. Each fingerprint must uniquely match exactly one rule — ambiguous matches are rejected. Two-phase: preview → execute with nonce

All five tools remain fail closed unless the authenticated Adapter reports the matching capability for the tested Verge version. The 2.5.1 RC QA build has passed controlled real update-and-restore samples for metadata, Merge YAML, YAML Override, and independent Rules; JavaScript mutation remains blocked.

Security model:

  • Owner resolution from profiles.yaml real file and option references; no filename guessing. realpath boundary check prevents symlink traversal.
  • Non-reusable nonce binds: target Profile UID, owner UID, owner path, owner fingerprint, chain fingerprint, normalized patch hash, section, ruleset fingerprint, and expiry (5-minute TTL).
  • Full transaction: preview → schema validation → optimistic owner fingerprint check → native Adapter write → persistence/runtime verification → commit or compensating restore.
  • Dual-layer lock (in-process mutex + cross-process file lock with PID liveness).
  • Rules use stable anchors (normalized content + adjacent fingerprints), not line numbers. RULESET_CHANGED_DURING_TRANSACTION aborts on concurrent modification.
  • A write returns COMMITTED only after the Adapter verifies the applicable persistence/runtime state and queues GUI refresh; unverified paths never claim success.

v1.0 Optimization Tools (12, read-only orchestration helpers)

Tool Description
clash.optimize.diagnose_network Collect a versioned network baseline and bounded real probes
clash.optimize.dns Diagnose DNS structure, exposure, consistency, and reachability
clash.optimize.rules Diagnose duplicate, shadowed, invalid, and owner-partitioned rules
clash.optimize.proxy_groups Diagnose group membership, selections, liveness, and failover
clash.optimize.health_checks Diagnose provider/group health-check intervals, targets, and cost
clash.optimize.openai Layered OpenAI connectivity diagnosis without API keys or paid calls
clash.optimize.github Layered GitHub web/API/download diagnosis without repository writes
clash.optimize.youtube Layered YouTube network diagnosis without account or DRM access
clash.optimize.streaming Bounded streaming endpoint diagnosis without unlock claims
clash.optimize.verify_baseline Reject execution when the original baseline has drifted
clash.optimize.compare_probes Classify comparable before/after probes as improved, unchanged, regressed, or inconclusive
clash.optimize.execution_plan Validate proposed actions against their individual lower-level capability gates

Optimizers do not write configuration. They return facts, probes, findings, recommendations, and proposed calls to the existing guarded tools. The calling AI performs one confirmed action at a time, compares identical probes, and invokes the original rollback path immediately on regression.

These helpers are an evidence harness, not a replacement for agent reasoning. They make common routing semantics explicit for less capable models: global and direct modes cannot be mistaken for active rule routing, live connection chains and the current GLOBAL selection are reported separately from static rules, single-candidate groups are identified as lacking group-level failover, and a health-check report distinguishes an unreadable configuration from a verified topology where health checks are not applicable. An agent may still inspect the lower-level MCP facts and form a different recommendation, but every write stays behind the same confirmation, capability, verification, and rollback gates.

v1.1 Verge Preferences Tools (5, capability-gated, fail-closed)

Tool Description
clash.verge.preferences.inspect Read-only inspect of Clash Verge Preferences (Basic/Theme/Layout/Hotkeys) from verge.yaml plus Adapter memory state; sensitive fields (css_injection, WebDAV credentials, system proxy, TUN, DNS, ports) are listed by name only and redacted
clash.verge.preferences.set_basic Write Basic Preferences (language, theme_mode, tray_event, env_type, start_page) with light confirmation. Two-phase preview→confirm; confirm=true must carry the real ownerFingerprint returned by preview
clash.verge.preferences.configure_theme Write Theme Preferences (primary/secondary/text/info/error/warning/success_color, font_family) with light confirmation and ownerFingerprint
clash.verge.preferences.configure_layout Write Layout Preferences (traffic_graph, enable_memory_usage, enable_group_icon, pause_render_traffic_stats_on_blur, collapse_navbar, menu_icon, notice_position, enable_hover_jump_navigator, menu_order) with light confirmation and ownerFingerprint
clash.verge.preferences.configure_hotkeys Write Hotkeys (enable_global_hotkey + 8 function→accelerator mappings) with strong nonce-bound confirmation. Nonce binds mapping digest + ownerFingerprint + enable state + 60s expiry; one-time use; no replay

Schema is keyed to real Clash Verge Rev 2.5.1 source (i18n.ts, setting-verge-basic.tsx, pages/_routers.tsx, layout-viewer.tsx, hotkey-viewer.tsx, core/hotkey.rs, config/verge.rs):

  • 13 real languages, 5 tray events (Linux unsupported), 5 env types (IMMEDIATE), 8 start pages (with leading /), 3 menu icons, 4 notice positions
  • 8 public hotkey functions (open_or_close_dashboard, clash_mode_rule, clash_mode_global, clash_mode_direct, toggle_system_proxy, toggle_tun_mode, entry_lightweight_mode, reactivate_profiles); quit/hide are native internal shortcuts and are NOT in the allowlist
  • Accelerator aliases are canonicalized before duplicate/reserved checks; macOS input/window combinations observed in the real desktop environment (Command+Space, Control+Space, and their protected variants) are rejected by both MCP and Adapter
  • common_tray_icon removed from the write allowlist (no safe icon asset and verifiable side effect)

Security model (per Codex v1.1 review P0/P1 rectification):

  • No fake COMMITTED — Basic/Theme/Layout remain UNVERIFIED until GUI-visible effects are acknowledged; start_page is PENDING_RESTART until the next Clash Verge launch because closing the dashboard only hides and reuses the current WebView. Hotkeys become COMMITTED only when memory, verge.yaml, and the native Tauri registration set all match; incomplete ok=true bodies remain UNVERIFIED.
  • Structured 409/429 — 409 + errorCode: "CHANGED" → PREFERENCES_CHANGED (state drift, caller must re-preview, returns REJECTED); 409 without errorCode → TRANSACTION_BUSY (mutation busy, returns BLOCKED); 429 + retryAfterMs → ADAPTER_RATE_LIMITED (returns BLOCKED with retryAfterMs).
  • Light confirmation fingerprint — confirm=true for Basic/Theme/Layout must carry the ownerFingerprint returned by a matching, unexpired preview for the identical values. MCP re-reads the strict Adapter snapshot and rejects missing, drifted, changed, or direct-confirm attempts.
  • Real ownerFingerprint — Adapter and read-only inspect both use SHA-256 over the exact verge.yaml bytes (first 16 bytes / 32 lowercase hex); the legacy fixed "adapter" placeholder and JSON-object fingerprint are not used for writes.
  • Adapter-side deny_unknown_fields DTO — VergePreferencesBody/HotkeysBody reject unknown fields; Adapter independently validates types/enums/lengths/colors/fonts/menu_order/platform/prototype pollution and returns 400 REJECTED before any memory/file/OS modification.
  • Compensating rollback re-verification — On failure, the Adapter re-reads memory and persisted state; Hotkeys also re-check the native registration set. A Preferences rollback is ROLLED_BACK only when memory, persisted bytes, native side-effect replay, and GUI-refresh scheduling all succeed; missing evidence remains RECOVERY_REQUIRED. rollbackVerified never relies only on patch_verge(...).is_ok().
  • Hotkeys transactional — Adapter saves original mapping/enable/verifiable OS registration set before writing; on partial registration failure it explicitly unregisters the new keys and restores the old set, then re-verifies. If the Tauri global-shortcut API cannot reliably enumerate or verify OS registration, the result is fail-closed UNVERIFIED/ROLLED_BACK/RECOVERY_REQUIRED, never COMMITTED.

The four write tools require authenticated Adapter capability settings.verge-preferences plus the matching fine-grained write capability. Read-only inspect may fall back to local verge.yaml, but never invents confirmation evidence when the real owner bytes are unavailable. macOS/Clash Verge 2.5.1 real-desktop acceptance covered visible Basic/Theme/Layout changes, NEXT_LAUNCH start-page behavior, native hotkey registration, 409/429/BUSY faults, same-call rollback, byte-exact restoration, and unchanged Profile/network state. Synthetic accessibility key events are not treated as proof of a physical global-hotkey callback.

Supported Versions

Component Verge Rev Version Status
Core MCP controller/read/runtime tools 2.5.1 tested
Core MCP controller/read/runtime tools 2.0.0+ compatible (not fully tested)
Companion Adapter App 2.5.1 only currently accepted upstream version
Any component < 2.0.0 unsupported

Security

  • Controller credentials are read from the selected client's private managed config or process environment; Adapter tokens are read from the private credentials file referenced by CLASH_VERGE_ADAPTER_TOKEN_FILE
  • All outputs are redacted (tokens, passwords, subscription URLs)
  • No arbitrary shell, file, HTTP, or API access
  • See SECURITY.md for details

Roadmap

See ROADMAP.md.

License

MIT

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选