Configuration November 20, 2026

Clash API Node Switching: Advanced External Controller Setup

Use the Clash external-controller API to check proxy health and switch a proxy-group selector automatically. This guide covers authentication, endpoint calls, script design, troubleshooting, and controller security.

Docker Proxy GitHub Acceleration Advanced Config YAML

1. What the external controller can—and cannot—automate

If you already use Mihomo through Clash Verge, Clash Verge Rev, or another compatible client, the external-controller API can turn a manual proxy-group choice into a small, observable automation workflow. A script can inspect the current proxy list, test candidate nodes, and ask a select group to use a different member when the active route is unhealthy. The useful distinction is that the API changes the group selection; it does not magically improve an unreliable node, discover every service endpoint, or guarantee that an application will reconnect immediately.

Mihomo exposes an HTTP control interface when the configuration enables external-controller. Common local setups use an address such as 127.0.0.1:9090, but the exact address and port depend on the profile and client. The controller API is generally available at the configured base URL, with endpoints such as /proxies for the proxy and group inventory, /proxies/{name} for details about a specific item, and a group-specific update endpoint for selecting a member. Check the API behavior supported by the Mihomo version you actually run; older Clash cores and client wrappers may expose different details.

A practical design separates four jobs. First, discover the relevant group and its candidates. Second, test reachability using the same kind of URL and timeout for every candidate. Third, apply a switching policy that accounts for failures, latency, and cooldowns. Finally, record what happened and make sure the controller remains accessible only to trusted local processes. Keeping these jobs distinct makes it easier to understand why a switch occurred and prevents a transient timeout from turning into constant node hopping.

The controller is a management interface, not a public service endpoint. A process with access may read connection metadata and change proxy selection; depending on the core and endpoints, it may also inspect other runtime information. Treat the API secret as a credential. Do not expose the controller to a public network, place its secret in a shared profile, or assume that a desktop firewall alone is sufficient protection. For a first test, keep the listener on loopback and run your script on the same machine as Mihomo.

2. Enable the controller, authenticate, and inspect groups

Before writing automation, confirm that the active profile—not merely a file saved elsewhere—contains an external-controller setting and a secret. In Mihomo-compatible YAML, a local configuration commonly resembles the following. Do not paste a real secret into a public issue, repository, screenshot, or chat history.

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

Some graphical clients manage the core settings separately from the profile, and a profile reload may overwrite settings you edited by hand. Use the client’s own settings or verify the effective configuration after applying changes. If the controller is already listening on a different port, use that port rather than opening a second listener. A port conflict, disabled controller, or stale profile is more common than a defect in the switching script itself.

The API uses an HTTP Authorization: Bearer header when a secret is configured. Query the inventory endpoint first and check the response before attempting to switch anything. For a local test with curl, the request has this general shape:

curl -sS \
  -H "Authorization: Bearer YOUR_SECRET" \
  http://127.0.0.1:9090/proxies

The response includes proxy and group information. A proxy group typically has a type such as Select, a list of current members, and a currently selected member. Use the exact group name and exact candidate names returned by the running controller. Names may contain spaces, punctuation, emoji, or non-ASCII characters; do not infer them from a subscription label or hard-code a translated version. In scripts, URL-encode path components when constructing a URL that includes a group or proxy name.

Start with a group that is explicitly designed for manual selection, often a select group that contains the nodes or a nested group you want to control. Do not assume every group is writable. A url-test or fallback group already has its own selection behavior, so a second script can fight the core’s built-in logic. If you automate an outer selector whose members are other groups, be clear about which layer you intend to change. The UI can help confirm the hierarchy, but the controller response is the authoritative source for the active runtime state.

Before enabling any scheduler, perform one deliberate switch against a test group. For a selector named Auto-Choice, a request to the group endpoint is typically a PUT with a JSON body naming a member:

curl -sS -X PUT \
  -H "Authorization: Bearer YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"name":"Candidate-A"}' \
  "http://127.0.0.1:9090/proxies/Auto-Choice"

Verify the result by querying the group again and checking its selected member, then check the client interface as a second confirmation. A successful HTTP response only confirms that the controller accepted the request; it does not prove that an application’s existing connection moved to the new node. Long-lived TCP connections can continue until they close, while new connections may use the new selection. For a meaningful test, open a fresh connection after switching and compare the route or public IP using a service you trust.

3. Build health checks and switching policy around evidence

A reliable script should not switch merely because one request failed. A health probe can fail due to temporary packet loss, DNS trouble, a target service being unavailable, or a local machine waking from sleep. Decide what “healthy” means for the work you care about. A short HTTPS request may be appropriate for web browsing; a service-specific endpoint is more representative if the proxy is used for a particular API. Use the same probe URL for all candidates, and avoid endpoints that rate-limit repeated checks or return misleading results from caches.

Mihomo provides proxy delay testing through an endpoint under /proxies/{name}/delay, commonly with a probe URL and timeout query parameters. The exact response and supported options can depend on the core version. Test one candidate manually, inspect the status code and JSON, and treat a missing delay value as a failed measurement rather than as zero latency. A delay measurement is a useful signal, but it is not a complete quality score: it does not by itself measure sustained throughput, packet loss over time, or the health of every destination your applications use.

A useful policy uses multiple observations. For example, require two or three consecutive failures before abandoning the current node, and require a candidate to pass more than one probe before promoting it. Add a minimum improvement margin so a node that is only a few milliseconds faster does not trigger a switch. Set a cooldown after each change, then reevaluate only after the cooldown expires. This hysteresis prevents the familiar ping-pong pattern in which two nearly equal nodes alternate whenever a single measurement fluctuates.

The script also needs explicit boundaries. Allow only a configured group and a known list of eligible candidates; skip nodes that the API reports as unavailable; and never select the group itself or a special member such as DIRECT unless that behavior is intentionally part of the policy. Do not blindly choose the lowest measured delay if the node is known to have a geographic, account, or data-handling constraint. Health automation should implement a human-reviewed routing policy, not invent one from latency numbers.

The following Python sketch shows the control flow rather than a drop-in production service. It uses the standard library, checks HTTP errors, and keeps the decision points visible. Adapt field names and API behavior to the response from your Mihomo build, and test it with a noncritical group before scheduling it.

import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request

BASE = os.environ.get("CLASH_CONTROLLER", "http://127.0.0.1:9090")
SECRET = os.environ["CLASH_SECRET"]
GROUP = "Auto-Choice"
PROBE_URL = "https://www.gstatic.com/generate_204"
TIMEOUT_MS = 5000
MIN_IMPROVEMENT_MS = 80

def request(path, method="GET", payload=None):
    data = None if payload is None else json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(
        BASE + path,
        data=data,
        method=method,
        headers={
            "Authorization": "Bearer " + SECRET,
            "Content-Type": "application/json",
        },
    )
    with urllib.request.urlopen(req, timeout=8) as response:
        body = response.read()
        return json.loads(body) if body else None

group_path = "/proxies/" + urllib.parse.quote(GROUP, safe="")
group = request(group_path)
current = group.get("now")
candidates = [name for name in group.get("all", []) if name != current]

results = []
for name in candidates:
    encoded = urllib.parse.quote(name, safe="")
    query = urllib.parse.urlencode({
        "url": PROBE_URL,
        "timeout": TIMEOUT_MS,
    })
    try:
        result = request(f"/proxies/{encoded}/delay?{query}")
        delay = result.get("delay")
        if isinstance(delay, int) and delay > 0:
            results.append((delay, name))
    except (urllib.error.URLError, TimeoutError, ValueError):
        continue

if results:
    best_delay, best_name = min(results)
    current_delay = None  # Populate from a probe of the current member.
    should_switch = current_delay is None or (
        best_delay + MIN_IMPROVEMENT_MS < current_delay
    )
    if should_switch:
        request(group_path, method="PUT", payload={"name": best_name})
        print(f"Selected {best_name} at {best_delay} ms")
else:
    print("No candidate passed the health check")

The sketch deliberately leaves the current-node probe and failure counters as explicit work rather than pretending that one comparison is enough. In a production version, probe the active node with the same method, persist consecutive failure counts and the last-switch time, and reset those counters only after a successful observation. Protect state files with appropriate local permissions. If you run the job from a scheduler, prevent overlapping executions with a lock; two copies can otherwise race to select different candidates based on different snapshots.

Make logging useful but restrained. Record the timestamp, group, selected member, probe outcome, and reason for switching. Avoid logging the bearer secret, full request headers, or unrelated connection metadata. A dry-run mode is valuable during rollout: it can report “would switch from A to B” for several days without changing the group. Compare those proposed decisions with actual user experience before enabling automatic writes.

4. Secure the controller and diagnose failures methodically

Keep the controller bound to 127.0.0.1 unless remote administration is an explicit requirement. Binding to 0.0.0.0 makes the listener reachable on network interfaces and can expose a powerful control surface to other devices. If remote access is necessary, place it behind a properly authenticated, encrypted private tunnel and restrict source addresses; do not treat a long secret as a reason to publish the port directly. Rotate the secret if it appears in logs or a configuration backup that is accessible to others.

Store credentials outside the script. Environment variables are convenient for a personal scheduled task, though they can be visible to other processes or administrators on some systems. A dedicated local secret store or operating-system credential manager may be more appropriate for a managed workstation. Restrict file permissions on scripts and state, avoid committing local configuration to Git, and make sure crash reports do not include request headers. When using a container, remember that 127.0.0.1 inside the container refers to the container itself, not automatically to the host; configure a safe host connection rather than widening the controller listener without a threat review.

Troubleshoot from the transport layer upward. If the connection is refused, confirm that Mihomo is running, that the active configuration enabled the controller, and that the host and port match. If you receive 401 or 403, verify the bearer secret and check whether the client or core imposes additional authorization behavior. A 404 commonly points to a malformed path, a missing group, or an endpoint difference in the installed version. A 400 after a selection request often means the group is not writable or the submitted member is not one of its current options.

If the API accepts a selection but traffic appears unchanged, query the group again first. If the selected value changed, the controller did its job; the remaining issue may be an existing connection, an application that bypasses the system proxy, a different routing group, or a rule that sends the relevant destination elsewhere. Confirm the target application’s route with a new connection and inspect Mihomo’s connection view or logs. Do not assume that a successful test from the browser proves a CLI, background service, or another client is following the same path.

If the script switches too often, increase the required failure count, lengthen the cooldown, and require a meaningful latency improvement. If all candidates fail, leave the current selection untouched unless your policy defines a safe fallback. Automatically choosing an arbitrary remaining node can be worse than reporting that no candidate passed. If a candidate is consistently slow, compare results at different times and check whether the probe destination is representative; one measurement taken immediately after startup is not a reliable long-term ranking.

Finally, document the controller address, the group the script owns, the probe target, thresholds, and the manual rollback procedure. Keep the script’s authority narrow: it should control one selector, not rewrite the profile or change unrelated groups. For a household or team workstation, tell other users what automatic switching does and how to pause it. This small operational detail avoids the confusing situation where someone selects a node manually only to have a background task replace it seconds later.

Some one-click VPN clients are simpler for a single device, but they often offer only an all-or-nothing route and limited visibility into why a connection changed. Manual selection is transparent, yet it depends on someone noticing failures and can leave a stale choice in place. With a Mihomo-compatible Clash client, the external controller lets you combine measured health checks, a bounded selector, cooldowns, and auditable decisions—while preserving the ability to take control manually. If that balance fits your setup, you can choose a compatible client and apply the guide’s local-only controller pattern before enabling automation.

Download a client →

Ready to get started?

Choose a compatible client, verify its Mihomo controller settings, and test your switching policy locally before scheduling it.