Clash External Controller API: Advanced Node Switching Guide

Why API-driven node switching matters in a real Clash gateway

Clash external controller API is more than a remote button for changing profiles. When a Clash or Mihomo instance acts as a gateway for a laptop, home server, container host, or small office network, the quality of the selected node can change several times during the day. A relay that looks fast during breakfast may develop packet loss at peak hours, while another node with a slightly higher initial latency may deliver much better sustained throughput. Manually opening Clash Verge Rev and clicking through a policy group is useful for testing, but it is not a self-healing strategy.

The external controller lets an authenticated local tool inspect runtime state, read proxy and policy-group information, and select a different member without rewriting the entire YAML profile. That distinction is important. A profile contains long-lived configuration; the controller changes the live state of the running core. You can therefore keep rules, DNS settings, and proxy definitions stable while an automation task reacts to health measurements or an operational event.

A practical design normally has three layers. The first is measurement: determine whether a node can reach a test URL within an acceptable time and whether repeated requests succeed. The second is decision logic: rank candidates according to latency, failure count, region, or a maintenance policy. The third is actuation: call the controller API to switch the selected member of a policy group. Keeping these layers separate prevents a single slow request from causing an endless switching loop.

This approach works with Mihomo-based clients such as Clash Verge Rev, Clash for Android, and other compatible front ends. Endpoint visibility and field names can vary slightly by core version, so treat the runtime API response as the source of truth rather than assuming that every graphical client exposes every advanced option in the same place.

How the Clash external controller API is organised

The controller is usually exposed through a local address such as 127.0.0.1:9090 or another address configured by the running core. The exact port is not universal. Open the active configuration and look for the external-controller field, then check whether an secret is configured. A typical deployment might look conceptually like this:

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

Do not bind the controller to 0.0.0.0 simply because a remote script cannot connect to localhost. A controller is an administrative interface: it can reveal node names, connection metadata, and runtime state, and in many builds it can change traffic policies. If remote access is genuinely required, place it behind a firewall, a private management network, or an authenticated tunnel, and never expose it directly to an untrusted interface.

Security warning: treat the controller secret like a password. Avoid putting it in shell history, public repositories, process listings, or a browser URL. A leaked token combined with an exposed controller can allow someone else to inspect or redirect your traffic.

Most automation begins with a small set of read operations. GET /version confirms that the endpoint is reachable and identifies the running core. GET /proxies returns the available proxies and policy groups. The response generally contains a top-level proxies object, where each item may include fields such as type, history, now, and all. A policy group is different from a concrete outbound node: its all list contains candidates, while now identifies the active member.

To inspect one group, URL-encode its name and request GET /proxies/{group-name}. Names containing spaces, slashes, brackets, or non-ASCII characters must be encoded correctly. For example, a group named 🚀 Auto Select should not be concatenated into an unescaped URL by hand. Use a proper HTTP client that handles path quoting.

Changing a selector normally uses a request similar to the following:

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

The group name in the path and the node name in the JSON body must both match the runtime response. A successful HTTP status does not by itself prove that the desired node is usable. Always perform a follow-up GET and verify that the group’s now field changed. Then run an application-level check through the selected group, because a policy switch can succeed even when the candidate immediately fails its first connection.

There is a useful difference between asking Clash to choose automatically and choosing from an external script. A url-test group can periodically test its members and select the fastest result using settings such as url, interval, and tolerance. A fallback group prioritises an ordered list and moves away from unavailable members. These built-in strategies are usually safer for routine failover. The controller API becomes valuable when the decision requires information that the group cannot express, such as business hours, a region allowlist, a maintenance calendar, a cooldown after failure, or a throughput score.

Designing health checks and a sensible selection policy

“Fastest node” is an incomplete description. A node can return a low latency to a tiny test endpoint while dropping large responses, failing websocket upgrades, or becoming unreliable after several minutes. Define what healthy means for your workload before writing automation. For browsing, a short HTTPS request with a bounded timeout may be enough. For development tools, include a package registry or source-control endpoint that the tool actually uses. For streaming or file transfer, add a larger download test and record transfer time rather than relying only on the handshake latency.

Use a stable, small HTTPS URL that returns predictable content. Avoid testing a page that changes frequently, redirects through many domains, or requires a login. The test URL should be reachable through the proxy group under evaluation and should not be so aggressive that your health checker becomes a source of unnecessary traffic. A five- to ten-second timeout, a modest interval, and a limited number of candidates are usually more responsible than firing requests every second.

Measure at least these values:

  • Success rate: the percentage of checks that complete without timeout or transport error.
  • Latency: the elapsed time from request start to a valid response, preferably using several samples rather than one result.
  • Recent failure streak: consecutive failures are often more actionable than a low average caused by an old outage.
  • Switch count: frequent changes indicate instability, an overly sensitive threshold, or a test endpoint that does not represent the real workload.
  • Policy eligibility: remove nodes that violate region, protocol, account, or maintenance requirements before ranking them.

A robust selector should use hysteresis. Do not switch from the current node merely because a competitor is 20 milliseconds faster. Require the new candidate to be faster by a meaningful margin, or require the current node to fail a defined number of consecutive checks. Add a cooldown after every switch, perhaps several minutes, so that two independent automation runs cannot bounce the group back and forth.

Practical rule: prefer stability over a tiny latency advantage. A node with 110 ms latency and a 99 percent success rate is often better for daily work than a 75 ms node that fails one request in ten.

Another important choice is whether to switch an individual node or a policy group. Directly changing a group such as Proxy affects every rule that points to that group, which is convenient but potentially broad. A safer arrangement is to create purposeful groups: one for interactive work, one for downloads, one for streaming, and one for sensitive services that must remain DIRECT. The API script can then switch only the group whose health has degraded.

Keep logs that explain every decision. Record the timestamp, group, current member, candidate scores, reason for switching, controller response status, and the result of the verification check. Do not log subscription URLs, controller tokens, cookies, or complete request headers. Logs should help you diagnose oscillation without becoming a second security problem.

Step-by-step: build a controlled automatic switching workflow

The following workflow is intentionally conservative. It assumes that a policy group already exists in the profile and that the controller is available on a protected local address. Test it manually before scheduling it through a service, cron job, Task Scheduler, or a home-server supervisor.

  1. Open the active Clash or Mihomo configuration and identify the controller address, API secret, and the exact policy-group name. Confirm that the group is a selectable type such as select, rather than a group whose members are controlled exclusively by internal timing logic.
  2. Call GET /version and GET /proxies with the authorization header. Save a redacted response during testing so you can see how your core spells group names, node names, and history fields.
  3. Choose a small candidate set from the group’s all array. Exclude entries such as DIRECT, REJECT, nested groups, and any node that your local policy does not permit. Do not assume that every item in all is a concrete proxy.
  4. Test each candidate through the group or through the core’s supported delay endpoint, depending on your implementation. Run multiple samples, discard timeouts, and calculate a score that combines latency with failure rate. Keep the test method consistent so that results remain comparable.
  5. Read the group again immediately before making a decision. This prevents your script from overwriting a manual selection or another automation task that changed the group while tests were running.
  6. Apply the hysteresis rule and cooldown. Switch only when the current member is unhealthy, or when the leading candidate beats it by your configured margin for enough consecutive rounds.
  7. Send a PUT request with the exact candidate name in the JSON body. Check the HTTP response, query the group again, and confirm that now equals the intended node.
  8. Perform a final end-to-end request through the normal proxy port. A controller acknowledgement proves that the policy state changed; it does not prove DNS resolution, TLS negotiation, or application traffic is working.
  9. Write a compact audit record and wait for the cooldown period. If verification fails, mark the node as temporarily unhealthy instead of immediately trying every member in a tight loop.

A minimal Python outline can make the mechanics clear. It is not a complete production daemon, but it shows the important separation between reading state, selecting a candidate, changing state, and verifying the result:

import time
import requests

BASE = "http://127.0.0.1:9090"
GROUP = "Proxy"
HEADERS = {
    "Authorization": "Bearer replace-with-token",
    "Content-Type": "application/json",
}

def group_state():
    response = requests.get(
        f"{BASE}/proxies/{requests.utils.quote(GROUP, safe='')}",
        headers=HEADERS,
        timeout=5,
    )
    response.raise_for_status()
    return response.json()

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

state = group_state()
current = state.get("now")
candidates = [name for name in state.get("all", [])
              if name not in {"DIRECT", "REJECT"}]

# Replace this placeholder with repeated measurements and policy checks.
candidate = candidates[0] if candidates else None

if candidate and candidate != current:
    select_node(candidate)
    time.sleep(1)
    confirmed = group_state().get("now")
    if confirmed != candidate:
        raise RuntimeError("Controller did not confirm the selected node")

For production use, add a lock so two processes cannot switch the same group simultaneously. Add exponential backoff for temporary controller errors, but do not retry a malformed request forever. Validate node names against the current API response instead of accepting an arbitrary name from a webhook. If an external monitoring system can trigger the script, authenticate that trigger separately from the Clash secret and restrict which groups it is allowed to modify.

Built-in groups still deserve a place in this design. You can let a url-test group handle ordinary latency selection and use the controller only for exceptional actions, such as removing a failing region from consideration or restoring a preferred node after maintenance. This reduces custom code and leaves routine probe scheduling inside the core. External automation should add context, not duplicate every feature already provided by Mihomo.

Debugging, observability, and safe operating limits

When automatic switching appears ineffective, begin by confirming which layer is failing. If /version cannot be reached, investigate the controller bind address, port, firewall, service state, and secret. If /proxies works but a PUT request fails, inspect URL encoding, the group type, the exact node spelling, and the request body. If the group’s now value changes but applications remain offline, examine the normal mixed port, system proxy settings, TUN mode, DNS mode, and the rules that select the group.

Do not confuse controller delay with application performance. An API delay measurement usually tests a particular URL and connection path. It may not reveal congestion on large downloads, websocket reliability, UDP behaviour, or the latency added by DNS. For a meaningful incident report, record the test URL, protocol, time of day, client platform, core version, and whether the request used fake-IP or redirection-based DNS.

Node names are not stable identifiers. Subscription providers may rename, reorder, or remove entries during an update. A script that stores only “the third item in the array” can silently select the wrong server. Match by the current name, and consider maintaining a local allowlist based on a stable property only when your profile format provides one. After a subscription refresh, revalidate all stored preferences and gracefully fall back to the group’s built-in selection.

Operational boundary: automatic switching should not override explicit user choices during incident investigation. Provide a pause flag or maintenance mode, and make the current automation status visible in logs or a small dashboard.

Rate limiting also matters. A health checker that tests twenty nodes every few seconds can create unnecessary traffic, trigger provider protections, and make the controller itself busy. Prefer a small candidate pool, stagger checks, cache recent results, and increase the interval when the network is stable. If all nodes fail, stop switching and report an outage rather than cycling through the entire list indefinitely.

Finally, protect privacy when inspecting runtime information. Connection endpoints and node labels can reveal the services you use or the locations you prefer. Limit API access to the host that needs it, rotate secrets after sharing configuration files, and remove sensitive fields before attaching logs to a support request. The controller is powerful precisely because it has a close view of the running proxy; that power should remain inside a controlled management boundary.

FAQ: Clash controller API and automatic node selection

Should I expose the external controller to my LAN?

Only when there is a clear operational need. A loopback-only controller is the safest default for a script running on the same machine. If a separate monitoring host must use it, bind it to a private management address, restrict access with firewall rules, require a strong secret, and consider an encrypted management tunnel. Do not publish the controller on a public IP or forward it through a router without an additional security layer.

Why does the API return success but the selected node does not work?

The API changes policy state; it does not guarantee that the proxy can complete a real request. Verify the group’s now field, then test through the actual mixed port or TUN path. Check DNS, rules, TLS errors, node expiration, and the candidate’s protocol support. A second application-level check is essential before declaring the switch successful.

Is an external script better than a url-test group?

Not automatically. Use url-test or fallback for straightforward latency-based selection and ordinary failover. Use the controller when you need custom scoring, cooldowns, maintenance windows, region restrictions, notifications, or coordinated changes across several groups. The simplest mechanism that meets the requirement is usually the most reliable.

How can I stop nodes from switching constantly?

Increase the test interval, require several consecutive failures, add a latency margin, and enforce a cooldown after every switch. Also verify that the test URL reflects the application you care about. If a tiny endpoint produces noisy results, a better measurement model may solve the problem more effectively than endlessly tuning thresholds.

Compared with some traditional VPN clients and closed proxy applications, which hide node health behind a single connect button or provide only a manual country list, Clash gives you visible policy groups, measurable runtime state, and an API that can be integrated with scripts and monitoring systems. Other clients may offer a convenient automatic mode but lack dependable controls for cooldowns, candidate filtering, audit logs, or separate decisions for interactive traffic and large downloads. Clash’s Mihomo-based ecosystem lets you combine built-in url-test and fallback behaviour with carefully scoped external automation, so advanced users can switch faster without surrendering configuration transparency. If you want to build this workflow on a supported client, visit the download page to choose a suitable build.

→ Download Clash for free and enjoy a better internet experience

Go to Download Page