Automate Clash Node Switching With The External Controller API

Understand What the External Controller API Can Change

Clash-compatible cores such as Mihomo expose an HTTP API called the external controller. A desktop client can use it to display connections, read proxy groups, test latency, and change the selected proxy in a selectable group. A script can use the same interface to automate a narrowly defined task: check eligible nodes, compare their responses to a test URL, and ask the core to select a node that passed the check.

This is different from editing a subscription or rewriting a YAML file. The API changes runtime state in the running core. If a subscription update, profile reload, or client restart recreates the proxy group, the selection may change again according to the configuration. Treat the controller as a way to manage the current running instance, not as a replacement for the configuration that defines available proxies and groups.

There are also two different kinds of automatic behavior to distinguish. A url-test group can test its members and choose a node according to its configured URL, interval, and tolerance. A script-controlled select group lets an external process choose a member explicitly. If the requirement is only “use a responsive node,” a built-in url-test group may be simpler and less fragile. An API script is useful when the decision needs custom checks, notifications, maintenance windows, or a policy that a normal group does not provide.

Before writing a script, confirm which core is running and whether the client exposes an external-controller setting. In a YAML configuration, the relevant settings commonly resemble the following; the address, port, and secret must match the active runtime configuration:

external-controller: 127.0.0.1:9090
secret: "replace-with-a-long-random-secret"

Some graphical clients manage these values outside the imported profile, or generate a runtime configuration that differs from the source YAML. Check the client’s core or controller settings and startup log rather than assuming that a sample port such as 9090 is active. If the controller is disabled, the API requests will fail even if the proxy itself is working normally.

Authenticate and Inspect the Running Proxy Groups

When a controller secret is configured, send it in the HTTP Authorization header as a bearer token. A request to /proxies returns the proxy objects known to the running core, including group types, member names, and, for selectable groups, the currently selected member. This is a useful first check because it verifies the controller address, authentication, and exact group spelling before any switching logic is introduced.

For example, a local request can be made with curl. Replace the secret and controller port with the values used by the active instance:

curl -H "Authorization: Bearer replace-with-a-long-random-secret" \
  http://127.0.0.1:9090/proxies

The response is JSON. Under its proxies object, a group may look conceptually like this:

{
  "proxies": {
    "Proxy": {
      "type": "Selector",
      "now": "Region A 01",
      "all": ["Region A 01", "Region A 02", "Region B 01"]
    }
  }
}

Names such as Proxy and Region A 01 are examples, not universal defaults. A configuration might instead have groups named PROXY, Global, or Auto. The script must use the exact name returned by the API, including capitalization and spaces. A group’s all list is also more reliable than a hard-coded node list because subscriptions can add, remove, or rename proxies.

Only send a selection request to a group that supports explicit selection, typically a Selector group. A URL-test or load-balancing group has its own selection behavior and should not be treated as a manual selector just because it contains proxy names. Inspect the returned type before attempting to change anything. Also exclude special entries such as DIRECT or REJECT from a node-latency routine unless the policy intentionally tests those options.

  • Use GET /version to confirm that the controller responds and identify the running core version.
  • Use GET /proxies to discover current group names, group types, members, and selected values.
  • Use a local-only controller address for desktop scripts running on the same machine.
  • Use HTTPS or a protected private network if remote controller access is unavoidable; a bearer secret sent over plain HTTP can be intercepted.

If a request returns 401 Unauthorized, check the bearer token and whether the client has replaced the configured secret. A 404 can indicate a wrong API path, a wrong controller port, or a request reaching another local service. A connection refusal usually means the core is stopped, the port is different, or the controller is not listening on the address used by the script.

Test Node Health Before Choosing the Lowest Latency

A node’s displayed delay is not a guarantee that every application will work through it. A latency test measures a request to one URL from the core through the candidate proxy. It does not prove that all destination domains, protocols, or regions are reachable. A useful failover routine therefore needs a consistent test URL, a timeout, a failure policy, and a rule for handling results that are too close to distinguish meaningfully.

Mihomo-compatible external controllers provide a delay-test endpoint in the form GET /proxies/{name}/delay?timeout=5000&url=.... The proxy name is a path component and must be URL-encoded; the test URL must also be encoded as a query parameter. A successful response commonly contains a delay value in milliseconds. Treat missing values, non-success HTTP responses, timeouts, and invalid JSON as failed tests rather than as a reason to select the candidate.

One test per node is often enough for a basic desktop failover, but transient network variation can produce misleading results. For more stable automation, test each candidate two or three times and use the median of successful results. Set a practical upper bound, such as 5,000 milliseconds, so an unresponsive endpoint does not stall the entire run. Choose a test URL that is expected to return a quick response in the regions being tested; a service-specific check may be more useful than a generic address if the script is intended to protect a particular workflow.

The following Python example uses the standard library. It reads the selectable group from the API, tests its current members, skips common non-proxy choices, and selects the fastest node that returns a valid delay. Set the environment variables before running it so the controller secret is not embedded in the source file.

import json
import os
import statistics
import time
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen

CONTROLLER = os.getenv("CLASH_CONTROLLER", "http://127.0.0.1:9090")
SECRET = os.environ["CLASH_SECRET"]
GROUP = os.getenv("CLASH_GROUP", "Proxy")
TEST_URL = "https://www.gstatic.com/generate_204"
TIMEOUT_MS = 5000
REPEATS = 2
SKIP = {"DIRECT", "REJECT"}

def api(method, path, params=None, body=None):
    url = CONTROLLER.rstrip("/") + path
    if params:
        url += "?" + urlencode(params)
    payload = None if body is None else json.dumps(body).encode("utf-8")
    request = Request(
        url,
        data=payload,
        method=method,
        headers={
            "Authorization": f"Bearer {SECRET}",
            "Content-Type": "application/json",
        },
    )
    with urlopen(request, timeout=8) as response:
        return json.loads(response.read().decode("utf-8"))

def measure(name):
    samples = []
    for _ in range(REPEATS):
        try:
            result = api(
                "GET",
                "/proxies/" + quote(name, safe="") + "/delay",
                {"timeout": TIMEOUT_MS, "url": TEST_URL},
            )
            delay = result.get("delay")
            if isinstance(delay, (int, float)) and delay > 0:
                samples.append(delay)
        except (HTTPError, URLError, TimeoutError, ValueError):
            pass
        time.sleep(0.2)
    return statistics.median(samples) if samples else None

data = api("GET", "/proxies")
group = data["proxies"].get(GROUP)
if not group or group.get("type") != "Selector":
    raise RuntimeError(f"{GROUP!r} is missing or is not a Selector group")

results = []
for name in group.get("all", []):
    if name in SKIP:
        continue
    delay = measure(name)
    if delay is not None:
        results.append((delay, name))

if not results:
    raise RuntimeError("No candidate passed the delay test")

delay, selected = min(results)
if selected != group.get("now"):
    api("PUT", "/proxies/" + quote(GROUP, safe=""), {"name": selected})
print(f"Selected {selected} at {delay:.0f} ms")

In an HTML code block, the comparison operator in the example is represented as > so it remains valid markup; the Python source uses the normal > operator. The same applies to any other characters that HTML reserves. Install no additional package for this example, but use a supported Python 3 release and verify the script manually against a test configuration before scheduling it.

The example intentionally fails closed: if no candidate returns a valid result, it leaves the existing selection unchanged and reports an error. That is usually safer than switching to an untested node or forcing traffic to DIRECT. For a high-availability server, add a documented fallback policy, such as keeping the current node for one cycle and alerting an operator after repeated failures.

Switch a Selector Group With Verification and Retry Logic

To change the selected member of a selector group, send PUT /proxies/{group-name} with a JSON body containing the desired member name: {"name":"Region A 02"}. Both the group name in the URL and the node name in the JSON must match values returned by GET /proxies. Encode the group name in the path as well; spaces and non-ASCII names should not be inserted into a URL unescaped.

A successful HTTP response means the controller accepted the request, but automation should still read the group again and confirm that its now value matches the requested node. This read-after-write check catches misspelled names, client-side configuration reloads, and cases where a client has replaced or restarted the core during the operation. If the selected value does not update, do not keep sending the same request in a tight loop; record the response, inspect the group type, and check the core log.

For resilient scheduling, separate the workflow into steps: fetch groups, verify the target group is a selector, test eligible candidates, choose a candidate, request the change, and confirm the result. Give each HTTP call a finite timeout. Retry only transient failures, such as a short connection interruption or a temporary server error, with a small increasing delay—for example, 1, 2, and 4 seconds—and then stop. Do not retry authentication failures or malformed requests as if they were temporary network problems.

  • Keep the current selection if every candidate times out or returns an invalid response.
  • Do not switch when the winning delay is only a few milliseconds better than the current node unless that difference matters to the application.
  • Use a threshold or hysteresis rule, such as requiring the current node to be unavailable for two consecutive runs before switching.
  • After switching, verify the group state and, if possible, make a separate application-level request through the normal traffic path.
  • Log the time, group, selected node, test URL, measured delay, and failure reason without writing the controller secret.

Hysteresis prevents a common failure mode called flapping: two nodes have similar results, small measurement changes alternate the winner, and the active route keeps changing. One simple policy is to retain the current node unless it fails all tests or the best alternative is at least 20 percent faster for two consecutive runs. The exact threshold depends on the workload; interactive browsing, long-running downloads, and API calls may have different tolerance for route changes.

Also consider what a route switch does to existing connections. A new selection generally affects new connections, while established sessions may continue through the previous path until they close. Applications using long-lived TCP connections, WebSockets, or connection pools may need to reconnect before the new route becomes visible. Do not interpret one still-open connection as proof that the API change failed.

Secure and Operate the Switching Script Reliably

The external controller is an administrative interface, not a public proxy endpoint. Anyone who can reach it and authenticate may be able to change proxy selections or inspect runtime data, depending on the core and enabled API features. Keep external-controller bound to 127.0.0.1 for a same-machine script. Avoid 0.0.0.0 unless remote access is required and protected by a carefully designed network boundary, firewall rules, and encrypted transport.

Store the secret outside the script. On a desktop, use the operating system’s credential store or a user-only environment configuration; on Linux, restrict the permissions of any environment file to the service account. Avoid passing secrets as command-line arguments, since process listings and shell history can expose them. Rotate the secret if it has appeared in a log, screenshot, shared configuration, or source-control commit. The script’s logs should contain diagnostic details but never the bearer token or a full authenticated request.

Automation should run with the least privilege practical for the machine. A scheduled task or service only needs network access to the local controller and permission to read its own secret. On a shared server, use a dedicated account rather than running the job as an administrator or root user. If a desktop client owns the core lifecycle, schedule the script only when the client is expected to be running and handle a stopped controller as a normal unavailable state.

Before deploying changes, test with a non-critical selector group and a small set of known nodes. Confirm that the test URL is reachable, the expected group is discovered, failures leave the current selection untouched, and successful switches appear in both the API response and the client interface. Then run the script manually for several cycles before enabling a timer. A reasonable interval might be one to five minutes for recovery checks; testing every few seconds can create unnecessary traffic, increase load, and cause route flapping.

When a run fails, diagnose the layer that failed rather than changing nodes blindly. A connection refusal points to controller address or process availability. A 401 points to authentication. A delay-test timeout can mean the candidate is offline, the test URL is blocked, DNS is failing, or the timeout is too short. A valid delay followed by no traffic change may indicate that the group is not the one used by the relevant rule, or that an existing connection has not been recreated. Check the core’s connection list and logs to confirm which group actually handled a new request.

A reliable node-switching script is deliberately conservative. It reads current runtime data instead of assuming names, tests candidates with bounded requests, changes only a selector group, verifies the result, and leaves the existing route alone when evidence is incomplete. Start with those safeguards, then add notifications or service-specific checks only when they solve a clearly defined operational need.

Download Clash