Clash External Controller API: Advanced Auto-Switching Guide
Why the Clash external-controller API matters for reliable failover
A proxy group that can switch nodes manually is useful; a proxy group that can prove a route is unhealthy and recover without a person watching the dashboard is much more valuable. The Clash external-controller API exposes the running Mihomo or Clash-compatible core through HTTP, allowing scripts, monitoring agents, home servers, and deployment jobs to inspect proxies, trigger health checks, and change selectors. This turns automatic proxy switching from a vague “URL-test should handle it” feature into an observable workflow with clear inputs, decisions, and recovery actions.
The practical search intent behind Clash API automatic proxy switching is usually operational rather than theoretical. A laptop loses the current relay during a long download, a small server must keep a webhook reachable, or a household gateway needs to move away from a congested node without changing the entire YAML file. In each case, the hard part is not sending one HTTP request. The hard part is choosing a safe check target, distinguishing temporary latency from a real outage, preventing rapid oscillation, and protecting the controller from unauthorized access.
Clash separates several responsibilities. The proxy-groups section defines which nodes may be selected; the health-check setting measures candidate availability; the external controller provides runtime visibility and control; and your automation layer decides when a change is justified. Keeping those layers separate makes troubleshooting much easier. If a group has no valid members, an API request cannot repair the profile. If the health URL is blocked or returns an unexpected status, switching logic may make a healthy node look broken. If the controller is exposed beyond localhost without authentication, a perfectly designed failover system becomes a security liability.
Configure the controller and proxy groups before writing automation
Start by making the runtime API predictable. In a Mihomo-compatible profile, the controller is commonly configured with an address such as 127.0.0.1:9090 and an authentication secret. The exact field names accepted by a particular client may differ, so treat the following as a configuration pattern rather than a universal copy-and-paste file:
external-controller: 127.0.0.1:9090
secret: "replace-with-a-long-random-secret"
proxy-groups:
- name: "AUTO-PRIMARY"
type: url-test
url: "https://www.gstatic.com/generate_204"
interval: 300
tolerance: 80
proxies:
- "Node A"
- "Node B"
- "Node C"
- name: "WORK"
type: select
proxies:
- "AUTO-PRIMARY"
- "Node A"
- "Node B"
- "DIRECT"
The url-test group is a useful baseline because the core can measure candidate nodes itself. Its interval controls how often the group tests, while tolerance reduces unnecessary movement when two nodes have similar latency. A low tolerance may cause the selected node to change whenever measurements differ by a few milliseconds. A larger tolerance favors stability, which is usually better for websocket sessions, package downloads, and authenticated browser workflows.
Use a small, intentional candidate set instead of placing every imported node in one production group. A node can respond quickly while having poor throughput, unstable TLS behavior, or an exit location unsuitable for a particular service. Divide candidates by purpose when needed: an interactive group for low latency, a bulk-transfer group for throughput, and a fallback group with broader regional coverage. Automation should switch the group that applications actually use, not an unused test group that looks healthy in the dashboard.
Choose the health-check URL carefully. A lightweight endpoint that returns a known success status avoids downloading a large page and keeps measurements comparable. If the endpoint is frequently filtered, rate-limited, or region-dependent, the result describes the test service rather than the proxy. Testing one URL is also not proof that every destination works. A node may reach the check endpoint but fail DNS resolution, UDP traffic, or a specific SaaS domain. Treat health checks as one signal in a decision system, not as an absolute truth.
| Control | What it does | Operational guidance |
|---|---|---|
external-controller |
Defines where the runtime API listens | Prefer loopback or a private management network |
secret |
Authenticates API requests | Generate a long random value and never commit it to a public repository |
url-test |
Measures and selects a fast candidate | Combine with tolerance so minor jitter does not cause flapping |
select |
Provides a manually or programmatically controlled selector | Use it as the stable application-facing group when scripts need explicit control |
Read the API before changing anything
A robust failover script begins with observation. Do not immediately send a selection request after the first timeout. First confirm that the controller is reachable, identify the active group, inspect available proxies, and review the core’s view of recent delays. Most HTTP clients can add an authorization header in the form expected by the running core, commonly Authorization: Bearer YOUR_SECRET. Keep the secret outside shell history where possible.
Typical API workflows use a small set of runtime resources. A request to the proxies resource helps discover proxy names and their current delay information. A request to the proxy-group resource reveals the selected member and the members available for that group. A delay test endpoint can measure one candidate against a chosen URL. Finally, a PUT request to the group resource can select another member. Names containing spaces, slashes, emoji, or non-ASCII characters must be URL-encoded rather than interpolated into a path by hand.
API="http://127.0.0.1:9090"
TOKEN="${CLASH_SECRET}"
curl --fail-with-body \
-H "Authorization: Bearer ${TOKEN}" \
"${API}/proxies"
curl --fail-with-body \
-H "Authorization: Bearer ${TOKEN}" \
"${API}/proxies/AUTO-PRIMARY"
Response schemas differ across versions, so write your parser defensively. Check the HTTP status first, verify that the expected JSON field exists, and treat missing delay data as unknown rather than as zero milliseconds. A zero value can be interpreted as “excellent” and accidentally promote a node that has never completed a test. Record the timestamp, group name, selected proxy, measured delay, status code, and decision taken. This small audit trail is more useful than a dashboard screenshot when a user reports that the route changed during a deployment.
For a direct candidate test, the endpoint commonly accepts a target URL and a timeout value. Some versions use a query parameter such as timeout; others expose delay data through the proxy resource after a core-managed test. Check the API documentation shipped with your build and test with a harmless endpoint first. Do not use a private intranet URL unless the controller and proxy topology make that destination meaningful. A check from the wrong network location can produce false confidence.
Build a safe automatic switching workflow
The central design rule is to require evidence before changing state. A single failed request may be caused by a remote service, a sleeping laptop, a DNS cache transition, or a short packet-loss burst. Use consecutive failures, a cooldown period, and a recovery threshold. For example, switch only after three failed checks within a defined window, then avoid another switch for five minutes. After the new route becomes healthy for several checks, mark the incident recovered. These thresholds should reflect the application: an interactive shell may tolerate a quick retry, while a database migration should favor route stability.
The following shell example demonstrates the control flow. It is intentionally conservative and assumes that the group name and candidate names are known. Adapt the endpoint paths and JSON parsing to your installed core rather than assuming every Clash derivative returns identical fields.
#!/usr/bin/env bash
set -euo pipefail
API="${CLASH_API:-http://127.0.0.1:9090}"
TOKEN="${CLASH_SECRET:?CLASH_SECRET is required}"
GROUP="WORK"
TARGET="https://www.gstatic.com/generate_204"
TIMEOUT_MS=5000
FAIL_LIMIT=3
COOLDOWN_SECONDS=300
STATE_FILE="${XDG_STATE_HOME:-$HOME/.local/state}/clash-failover.state"
mkdir -p "$(dirname "$STATE_FILE")"
last_switch=0
failures=0
if [[ -f "$STATE_FILE" ]]; then
read -r last_switch failures < "$STATE_FILE" || true
fi
now="$(date +%s)"
if (( now - last_switch < COOLDOWN_SECONDS )); then
exit 0
fi
if curl --silent --show-error --fail \
-H "Authorization: Bearer ${TOKEN}" \
"${API}/proxies/${GROUP}" >/dev/null; then
failures=0
else
failures=$((failures + 1))
fi
if (( failures < FAIL_LIMIT )); then
printf '%s %s\n' "$last_switch" "$failures" > "$STATE_FILE"
exit 0
fi
# Select a pre-approved fallback; validate its name before production use.
curl --silent --show-error --fail \
-X PUT \
-H "Authorization: Bearer ${TOKEN}" \
-H "Content-Type: application/json" \
"${API}/proxies/${GROUP}" \
--data '{"name":"Node B"}'
printf '%s 0\n' "$now" > "$STATE_FILE"
This example uses a group read as a basic liveness check, but production logic should perform a real candidate test or inspect a reliable health field. It also selects a fixed fallback for clarity. A more advanced implementation can retrieve the group’s members, test only an allowlist, rank them by recent success rate and latency, then select the best candidate. Keep the allowlist explicit. Automatically selecting any name returned by a remote subscription can route traffic through a newly added node that has not passed your policy review.
- Define the group that carries the traffic and document its acceptable fallback members. Do not let the script change unrelated groups such as a local bypass selector.
- Run a baseline check several times while the current route is known to be healthy. Store normal latency and expected status so a slow but valid connection is not confused with total failure.
- Count consecutive failures and require a cooldown. Reset the counter after a successful check, and prevent two independent timers from issuing conflicting switches.
- Test the fallback before selecting it when the API permits. If it fails, try the next approved member rather than repeatedly choosing the same dead route.
- Verify the selected group after the write request. Log the previous member, new member, reason, and verification result, then notify an operator only when the fallback pool is exhausted.
Concurrency deserves special attention. A cron job, systemd timer, container health probe, and desktop helper may all notice the same outage. Use a lock file or an equivalent single-flight mechanism so only one process can evaluate and change the group at a time. Add jitter to scheduled checks when many gateways share one controller, otherwise they can generate synchronized bursts against the same health endpoint.
Secure, test, and maintain the automation
The external controller is a control plane, not an ordinary browsing endpoint. Anyone who can select a proxy group can influence where traffic leaves the machine, and some API surfaces expose configuration or connection metadata as well. Bind the controller to loopback unless remote administration is genuinely required. If a private network is necessary, restrict it with a firewall or an authenticated tunnel, rotate the secret, and avoid placing the controller directly on a public interface. Never paste the secret into a public issue, a shared screenshot, a CI log, or a shell command that will be retained by an audit system.
Use least privilege around the automation process. A local script may only need to read group state and issue a selection request, while a configuration-management job may need broader access. Separate those use cases where the core supports it, and at minimum run the script as a dedicated user with a protected environment file. Validate all names obtained from API responses before placing them into a URL or JSON body. Encode path segments, reject control characters, and avoid constructing commands from untrusted proxy metadata.
Test failure modes without waiting for a real outage. Temporarily select a disposable test group, block its test endpoint, inject a short timeout, or use a lab profile containing intentionally invalid nodes. Confirm that one failure does not trigger a switch, that the failure threshold does, that cooldown prevents loops, and that the script recovers after the original route becomes healthy. Also test controller restart behavior: state files should not cause an immediate switch based on stale timestamps, and the service should fail closed when the API is unreachable.
Measure outcomes that matter to users. Latency alone cannot explain a broken upload, a failed websocket handshake, or a DNS mismatch. Track request success, time to recovery, number of switches per hour, selected route duration, and fallback exhaustion. A rising switch count with stable latency usually indicates an overly sensitive threshold or an unstable health target. A low switch count combined with long outages suggests checks are too infrequent, the failure limit is too high, or the script is testing a different group from the one applications use.
Some competing clients expose a one-click “fastest server” button but provide little control over the test URL, failure threshold, cooldown, or audit trail. Traditional VPN applications may hide the active route entirely, making it difficult to distinguish a provider outage from a local DNS problem; lightweight scripts can also become dangerous when they expose an unauthenticated API or switch on the first timeout. Clash offers a more transparent alternative: Mihomo-compatible proxy groups, explicit health-check parameters, runtime inspection through the external-controller API, and programmable selection that can be reviewed in logs and version-controlled safely. If you want to build this workflow on a supported client and verify the available core features first, visit the download page and choose the appropriate build for your platform.
→ Download Clash for free and enjoy a better internet experience