Configuration August 31, 2026 · ~12 min read

Clash External Controller API: Advanced Auto-Switch Configuration

In the world of proxy tools, Clash is only as powerful as the subscription you feed it. Picking a high-quality "Airport" (proxy provider) is the difference between a seamless 4K streaming experience and a frustrating connection that drops every five minutes. This guide breaks down the technical metrics, price traps, and security protocols you must know in 2026.

What the Clash External Controller Can Automate

Clash’s external controller API turns the client from a manual node picker into a service that can be inspected and operated by another program. Instead of opening Clash Verge Rev or Mihomo and changing a policy group by hand, a local script can read the active configuration, test proxy latency, identify the currently selected node, and switch to a healthier candidate. This is especially useful on a workstation, home server, travel router, or development machine that must remain connected for long periods without constant supervision.

The API is normally exposed by the Clash core used by clients such as Clash Verge Rev, Mihomo, OpenClash, and some other compatible front ends. The graphical interface is only one consumer of the core. The external controller is another consumer, using ordinary HTTP requests such as GET, PUT, and PATCH. When the controller is enabled, you can query endpoints for proxies, proxy groups, configurations, connections, rules, and version information.

A typical automatic failover workflow has four stages. First, a script discovers the proxy groups and their members. Second, it checks the delay or reachability of several nodes against a stable URL. Third, it applies a decision rule, such as “switch when the active node fails twice” or “choose the fastest node below 800 milliseconds.” Finally, it records the action and waits before testing again. The waiting period matters because a provider may briefly lose packets without the node being permanently unusable.

What this guide covers

  • Enabling and securing the external-controller service
  • Authenticating REST requests with the controller secret
  • Reading proxy groups and measuring node delay
  • Switching a policy group through the API
  • Building a conservative auto-switch script with cooldown and failure thresholds

API behavior is not perfectly identical across every Clash fork or client release. Mihomo generally provides the broadest set of current endpoints, while an older Clash core may omit newer fields or return slightly different JSON. For that reason, begin by checking the running core version and test each request manually before putting it into a scheduled job. Do not assume that a button visible in one graphical client is available in another core.

Enable the External Controller Safely

The controller is configured in the Clash YAML profile, usually near the top-level runtime settings. The common form is external-controller: 127.0.0.1:9090. This binds the HTTP service to the local machine and port 9090. Some profiles use 0.0.0.0:9090, which listens on every network interface. That broader binding is convenient for remote administration, but it also creates a network service that must be protected carefully.

external-controller: 127.0.0.1:9090
secret: change-this-to-a-long-random-value

Use a long random secret rather than a short word, a subscription token, or a password reused elsewhere. The secret grants operational access: a client with it may change policy selections and, depending on the core, inspect active connections and runtime state. Store it outside public repositories, screenshots, shared configuration snippets, and shell history. If your client offers a dedicated controller or API field, prefer that interface over editing a generated subscription file that may be overwritten during the next update.

Never expose an unauthenticated controller

If the controller listens on a LAN address, require a secret and restrict access with a firewall. Avoid forwarding port 9090 from the internet. A controller API is an administrative interface, not a public status page. If remote access is genuinely necessary, place it behind a private VPN, an SSH tunnel, or a tightly controlled management network.

After changing the profile, reload the configuration or restart the Clash client according to its normal workflow. Confirm that the process is listening on the expected address, then send a read-only request from the same machine. On Linux and macOS, tools such as ss, lsof, or curl can help verify the listener. On Windows, the client’s log and resource monitoring tools can show whether the port is already occupied.

curl -H "Authorization: Bearer change-this-to-a-long-random-value" \
  http://127.0.0.1:9090/version

A successful response normally contains the running core version. A connection refusal means the service is not listening, the port is different, or a local firewall is blocking it. An HTTP 401 response usually indicates a missing or incorrect authorization header. If the response is valid but does not include fields expected by your script, inspect the actual JSON instead of relying on an example from another fork.

Choose an address and port deliberately

127.0.0.1 is the safest default for a script running on the same computer. An IPv6-only or dual-stack environment may instead use [::1]:9090, but your HTTP client must format the bracketed address correctly. If a home server needs to be managed from another device, bind only to a private interface where possible and create a firewall rule that permits the administrator’s address range. Changing the port does not provide meaningful security by itself; authentication and network restrictions do.

Discover Proxy Groups and Measure Node Health

Automatic selection starts with discovery. Do not hard-code a group name such as Proxy unless you control every profile that will run the script. Providers and templates may call the group 手动选择, GLOBAL, Auto, or something entirely different. Query the proxies object, locate groups by their type, and inspect each group’s available members.

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

The response is a JSON object whose proxies property contains both individual proxies and policy groups. A selector group commonly includes fields such as type, all, and now. The now value identifies the member currently selected. A URL-test or fallback group may expose different fields because its selection is controlled by the core. Before issuing a switch request, verify that the target is a selectable group and that the desired node appears in its member list.

Purpose Typical endpoint What to verify
Core version GET /version Controller is reachable and identifies the running core
Proxy inventory GET /proxies Group names, member names, current selection, group type
One node delay GET /proxies/{name}/delay HTTP status, latency value, and encoded proxy name
Active connections GET /connections Whether existing traffic is still using the old path

To test one proxy, call its delay endpoint with a URL and timeout. The exact query parameters are commonly url and timeout, expressed in milliseconds. Because proxy names can contain spaces, slashes, emoji, or non-Latin characters, URL-encode the path segment. A raw request may work for a simple name and then fail unexpectedly when a provider uses a decorative node label.

curl -G \
  -H "Authorization: Bearer YOUR_SECRET" \
  --data-urlencode "url=https://www.gstatic.com/generate_204" \
  --data-urlencode "timeout=5000" \
  "http://127.0.0.1:9090/proxies/Node%20A/delay"

A low delay is not the same as a reliable internet connection. The test URL may be cached, reachable from a special route, or blocked in a way that does not represent the destinations you care about. Choose a small, stable HTTPS endpoint and keep the same URL across comparisons. For a more realistic decision, test two or three times, discard timeouts, and compare the median rather than trusting one unusually fast response.

Measure the path you actually use

A health-check URL should reflect your traffic. If the policy group is mainly used for software downloads, test a dependable download host. If it handles ordinary web browsing, use a lightweight HTTPS endpoint. Avoid large files, aggressive polling, or endpoints that rate-limit repeated checks.

Node names are not guaranteed to be unique across all parts of a profile. A policy group can contain a proxy with a name that looks similar to another entry, and a provider update may rename or remove it. Always select from the current all list returned by the API. If a node disappears between discovery and switching, treat that as a normal race condition and refresh the inventory rather than retrying the same stale name indefinitely.

Switch a Policy Group Through REST

For a selector-style group, changing the active proxy is usually a PUT request to /proxies/{group}. The request body contains a JSON object with the selected proxy name. Because both the group and proxy may include spaces or Unicode characters, encode the URL path and send UTF-8 JSON. A successful request usually returns an empty response or a simple success status.

curl -X PUT \
  -H "Authorization: Bearer YOUR_SECRET" \
  -H "Content-Type: application/json" \
  --data '{"name":"Node A"}' \
  "http://127.0.0.1:9090/proxies/Proxy"

After switching, query /proxies again and confirm that the group’s now field matches the requested member. This read-after-write check catches several practical problems: the group may be controlled by an automatic strategy, the target may no longer exist, or the request may have been sent to a different controller port than the GUI is using. A script should consider the operation successful only after this verification.

Do not switch every group just because one node is slow. Many configurations have separate groups for general traffic, streaming, messaging, downloads, and direct connections. Identify the group that the relevant rule actually references. The rule endpoint can help you inspect which policy is selected for a domain, while the connections endpoint can show the policy used by active flows. This prevents an apparently successful API change from having no visible effect.

Prefer controlled decisions over constant switching

A useful strategy has three safeguards. The first is a failure threshold: require two or three consecutive failed checks before abandoning the current node. The second is a cooldown: do not switch again for several minutes unless the replacement also fails immediately. The third is a recovery rule: when the original node becomes healthy, either keep the current replacement or return only if there is a clear reason, such as lower latency or a preferred geographic route.

Use a small score rather than latency alone when several candidates are available. For example, reject timeouts first, penalize repeated failures, then compare median latency. You can also preserve an explicit priority list so the script does not select a node that is fast but unsuitable for a particular service. A node with 250 milliseconds and stable results may provide a better experience than one alternating between 80 and 2,000 milliseconds.

Conservative failover sequence

  1. Read the group and record the current member.
  2. Test the current member twice using the same HTTPS URL.
  3. Switch only after the failure threshold is reached.
  4. Test candidates with a timeout and ignore unavailable names.
  5. Send one PUT request to the selected group.
  6. Read the group again and log the confirmed result.
  7. Wait for the cooldown interval before another automated decision.

Build a Safe Auto-Switch Script

The following Python example demonstrates the control flow without assuming that a particular provider has a particular group name. It discovers a group, checks candidate nodes, avoids direct and special control entries, and changes the selector only when the current node has failed repeatedly. Adapt the names, test URL, and thresholds to your own profile. The example intentionally keeps the secret in an environment variable rather than embedding it in source code.

import os
import statistics
import time
from urllib.parse import quote

import requests

BASE = os.getenv("CLASH_API", "http://127.0.0.1:9090")
SECRET = os.environ["CLASH_SECRET"]
GROUP = os.getenv("CLASH_GROUP", "Proxy")
TEST_URL = os.getenv("CLASH_TEST_URL", "https://www.gstatic.com/generate_204")
TIMEOUT_MS = 5000
HEADERS = {"Authorization": f"Bearer {SECRET}"}

def get_group():
    data = requests.get(f"{BASE}/proxies", headers=HEADERS, timeout=8).json()
    return data["proxies"][GROUP]

def delay(name):
    path_name = quote(name, safe="")
    response = requests.get(
        f"{BASE}/proxies/{path_name}/delay",
        params={"url": TEST_URL, "timeout": TIMEOUT_MS},
        headers=HEADERS,
        timeout=8,
    )
    response.raise_for_status()
    return response.json()["delay"]

def switch(name):
    response = requests.put(
        f"{BASE}/proxies/{quote(GROUP, safe='')}",
        json={"name": name},
        headers=HEADERS,
        timeout=8,
    )
    response.raise_for_status()

current = get_group()["now"]
samples = []
for _ in range(2):
    try:
        samples.append(delay(current))
    except requests.RequestException:
        pass
    time.sleep(1)

if len(samples) < 2:
    candidates = []
    for name in get_group().get("all", []):
        if name in {"DIRECT", "REJECT", current}:
            continue
        try:
            values = [delay(name), delay(name)]
            candidates.append((statistics.median(values), name))
        except requests.RequestException:
            continue

    if candidates:
        candidates.sort()
        switch(candidates[0][1])
        confirmed = get_group()["now"]
        print(f"switched to {confirmed} at {candidates[0][0]} ms")
    else:
        print("no healthy candidate found")
else:
    print(f"{current}: {statistics.median(samples)} ms")

In production, add structured logging, a lock file, and a persistent failure counter. Without a lock, two scheduled runs can test different states and issue competing switches. Without persistence, a restart erases the history needed to distinguish a short outage from a long one. Log only the information needed for diagnosis; never print the controller secret or place it in an exception message.

Schedule the script at a moderate interval, such as once every one to five minutes, rather than creating a tight loop. A short interval increases API traffic, creates unnecessary latency tests, and can cause policy flapping. If your client already has a built-in url-test or fallback group, use that feature first. External automation is most valuable when you need custom rules, notifications, maintenance windows, service-specific testing, or integration with another monitoring system.

Troubleshoot common API failures

  • 401 Unauthorized: confirm the secret and the exact Authorization: Bearer format. Check that the script is using the same controller instance as the GUI.
  • 404 Not Found: the endpoint may not exist in that core version, or the proxy name was not URL-encoded. Query /version and inspect the actual route supported by the fork.
  • 400 Bad Request: verify that the request uses JSON, includes Content-Type: application/json, and sends a selectable member name.
  • Timeout during delay tests: distinguish a dead node from an unreachable test URL. Try a second approved endpoint and check local DNS or firewall behavior.
  • Switch succeeds but traffic does not change: inspect the rules and active connections. The application may be using another policy group, a cached connection, or a direct route.

When debugging, start with read-only calls and save the raw response for one healthy and one unhealthy case. Then test a single manual switch before enabling automation. This staged approach makes it much easier to identify whether the problem is authentication, URL encoding, group selection, health-check design, or the proxy itself.

Some competing proxy clients hide node health behind a limited interface, require repeated GUI clicks, or provide automatic selection without exposing enough information to audit why a node was chosen. That becomes frustrating when you need reproducible failover, custom thresholds, or remote monitoring. Clash and Mihomo expose the controller, proxy inventory, latency checks, and policy switching through a scriptable REST interface, while still leaving the normal GUI available for manual review. If you want a client that can support both everyday selection and an operational workflow, Download Clash for free and begin with a localhost-only controller before expanding the setup.