Why API-driven node switching is better than guessing
When a Clash profile contains twenty or more proxies, manually clicking through every node is not a reliable way to find the best route. A node that feels fast while loading one webpage may perform poorly for Git pushes, AI streaming responses, package downloads, or a long-lived SSH session. The useful question is not simply “which node has the lowest ping?” but “which node is responsive for the traffic I actually care about, and can I select it without interrupting the rest of my profile?”
Mihomo-compatible clients expose an external controller API for exactly this kind of automation. The API lets a local script inspect proxy groups, test individual proxies, read current selections, and change the active member of a group. With a small amount of YAML planning and either Shell or Python, you can turn node switching into a repeatable workflow instead of a manual ritual.
This is especially useful when one machine carries several sensitive workloads at the same time. An AI coding tool may need a stable international route, GitHub may prefer a different exit, and domestic websites may need DIRECT. The goal is not to rotate every connection aggressively. The goal is to create purposeful groups, test candidates against a meaningful URL, and switch only the group whose performance has changed.
The external controller is normally bound to a local address such as 127.0.0.1:9090. Some clients use a different port, and some expose a Unix socket or a generated configuration value instead. The controller may also require a secret. Treat that secret like a password: it should never be published in a repository, pasted into a public issue, or exposed on an untrusted network interface.
The API model: groups, proxies, health checks, and selection
Before writing a script, separate four concepts that are often mixed together. A proxy is an individual outbound node such as Tokyo-01 or Frankfurt-02. A proxy group is a policy container that can select one of those proxies. A health check asks the core to measure a proxy against a URL. The selection is the member currently used by rules that point to the group.
For example, a profile might contain a group named AI with several nodes, while a rule sends AI-related domains to that group:
proxy-groups:
- name: AI
type: select
proxies:
- Tokyo-01
- Seoul-02
- Frankfurt-01
- DIRECT
rules:
- DOMAIN-SUFFIX,api.openai.com,AI
- DOMAIN-SUFFIX,github.com,AI
- MATCH,GLOBAL
The YAML defines the structure, but the controller API changes the runtime choice without rewriting the entire profile. A typical API workflow uses GET /proxies to inspect groups and proxies, GET /proxies/{name}/delay to test a candidate, and PUT /proxies/{group} to select a proxy for a group. Names containing spaces or special characters must be URL-encoded when inserted into a path.
A delay test is not a complete quality measurement. It usually reports the time required to reach a test URL, while real applications also depend on packet loss, throughput, TLS behavior, congestion, and session stability. Still, delay testing is a useful first filter. It is much more meaningful when you choose a URL that resembles your workload rather than testing an arbitrary endpoint that happens to respond quickly.
- AI traffic: use a stable HTTPS endpoint associated with the service or a neutral HTTPS endpoint reachable through the same region.
- Git operations: test the Git hosting API or a small metadata endpoint rather than downloading a large repository.
- Remote development: favor a repeatable HTTPS target and then perform a longer connection test, because an editor or agent may keep sessions open for many minutes.
- General browsing: use a lightweight HTTPS URL with predictable response behavior, not a large video or image page.
The response from a delay endpoint commonly includes a numeric delay value when the test succeeds. A failure may appear as an HTTP error, an empty result, or a timeout depending on the core. Your automation must treat all of these cases as “candidate unavailable,” not as a reason to select the failed node.
0.0.0.0 without strict firewall rules can allow another device to inspect your proxy configuration or change your traffic path. Prefer a loopback address and require the controller secret whenever the client supports it.
Hands-on workflow: test candidates and switch a group
The following workflow is intentionally conservative. It assumes that you already have a working profile and want to automate one group, such as AI or Developer, without changing unrelated groups. The same pattern can be adapted to Clash Verge, Clash Verge Rev, Mihomo, or another client that exposes compatible controller endpoints.
- Confirm the controller address. Open the client settings or inspect the active Mihomo configuration. Record the controller URL, port, and secret. Do not assume that every installation uses port
9090. - Inspect the group name. Request the proxy list and identify the exact group name. A group called
AI Servicesis not the same asAI, and URL encoding matters when spaces are present. - List candidate members. Read the group’s
allorproxiesarray and remove unusable entries such asREJECT,COMPATIBLE, nested groups, andDIRECTunless direct access is an intentional fallback. - Run several tests. Test each candidate against the same URL. One successful request can be an outlier; three attempts with a short pause provide a more useful picture.
- Apply a safety threshold. Reject candidates above a latency limit, candidates that fail repeatedly, and candidates that differ wildly between attempts. A slightly slower but consistent node is often better than a fast node with severe jitter.
- Switch only when necessary. Read the group’s current selection and avoid sending another API request if the best candidate is already active. This reduces unnecessary disruption to long-lived sessions.
For a quick manual check, the following Shell examples use curl. Replace the address, secret, group name, and test URL with values appropriate for your installation.
CONTROLLER="http://127.0.0.1:9090"
SECRET="replace-with-your-secret"
GROUP="AI"
TARGET="https://www.gstatic.com/generate_204"
curl -s \
-H "Authorization: Bearer ${SECRET}" \
"${CONTROLLER}/proxies" | jq '.proxies["AI"]'
curl -s \
-H "Authorization: Bearer ${SECRET}" \
"${CONTROLLER}/proxies/Tokyo-01/delay?timeout=5000&url=https%3A%2F%2Fwww.gstatic.com%2Fgenerate_204"
curl -s -X PUT \
-H "Authorization: Bearer ${SECRET}" \
-H "Content-Type: application/json" \
"${CONTROLLER}/proxies/${GROUP}" \
-d '{"name":"Tokyo-01"}'
The exact authorization header depends on the controller configuration. Many Mihomo installations accept the Bearer form shown above, while a controller without a secret may allow the request without that header. If your client returns 401, check the secret and header format before debugging the proxy nodes themselves. If it returns 404, verify the API base path and core compatibility.
A Shell selector with a latency threshold
A useful Shell script should be explicit about failure. It should not interpret a missing delay value as zero, and it should not switch the group simply because the first candidate in the list responded. The example below uses jq to parse JSON and keeps the selection logic readable.
#!/usr/bin/env bash
set -euo pipefail
CONTROLLER="${CONTROLLER:-http://127.0.0.1:9090}"
SECRET="${SECRET:?Set SECRET first}"
GROUP="${GROUP:-AI}"
TARGET="${TARGET:-https://www.gstatic.com/generate_204}"
TIMEOUT="${TIMEOUT:-5000}"
MAX_DELAY="${MAX_DELAY:-900}"
auth=(-H "Authorization: Bearer ${SECRET}")
group_json="$(curl -fsS "${auth[@]}" "${CONTROLLER}/proxies/${GROUP}")"
current="$(jq -r '.now // empty' <<< "${group_json}")"
mapfile -t candidates < <(jq -r '.all[]' <<< "${group_json}" |
grep -vE '^(DIRECT|REJECT|GLOBAL|COMPATIBLE)$')
best=""
best_delay=999999
for proxy in "${candidates[@]}"; do
encoded_proxy="$(jq -rn --arg value "${proxy}" '$value|@uri')"
encoded_url="$(jq -rn --arg value "${TARGET}" '$value|@uri')"
result="$(curl -sS "${auth[@]}" \
"${CONTROLLER}/proxies/${encoded_proxy}/delay?timeout=${TIMEOUT}&url=${encoded_url}" || true)"
delay="$(jq -r '.delay // empty' <<< "${result}" 2>/dev/null || true)"
if [[ "${delay}" =~ ^[0-9]+$ ]] && (( delay < best_delay )) && (( delay <= MAX_DELAY )); then
best="${proxy}"
best_delay="${delay}"
fi
done
if [[ -n "${best}" && "${best}" != "${current}" ]]; then
payload="$(jq -nc --arg name "${best}" '{name:$name}')"
curl -fsS -X PUT "${auth[@]}" \
-H "Content-Type: application/json" \
"${CONTROLLER}/proxies/${GROUP}" \
-d "${payload}"
printf 'Switched %s from %s to %s (%sms)\n' \
"${GROUP}" "${current:-unknown}" "${best}" "${best_delay}"
else
printf 'Kept %s on %s\n' "${GROUP}" "${current:-unknown}"
fi
Do not run this script every few seconds. A short interval can create a self-inflicted outage: active connections are moved while applications are still using them, and transient latency spikes cause needless oscillation. A five- to fifteen-minute schedule is usually more reasonable for ordinary browsing. For AI agents, Git operations, or remote development, you may prefer to run it manually before a work session and only re-run it after observing a real problem.
A Python approach with repeated measurements
Python is a better fit when you want median latency, retries, logging, or different thresholds for different groups. The following example measures each candidate three times and chooses the lowest median that passes the limit. It intentionally leaves policy decisions visible rather than hiding them inside a large framework.
import os
import statistics
import time
from urllib.parse import quote
import requests
controller = os.getenv("CONTROLLER", "http://127.0.0.1:9090")
secret = os.environ["SECRET"]
group = os.getenv("GROUP", "AI")
target = os.getenv("TARGET", "https://www.gstatic.com/generate_204")
timeout_ms = int(os.getenv("TIMEOUT", "5000"))
max_median = int(os.getenv("MAX_MEDIAN", "900"))
headers = {"Authorization": f"Bearer {secret}"}
session = requests.Session()
group_url = f"{controller}/proxies/{quote(group, safe='')}"
group_data = session.get(group_url, headers=headers, timeout=10).json()
current = group_data.get("now")
candidates = [
name for name in group_data.get("all", [])
if name not in {"DIRECT", "REJECT", "GLOBAL", "COMPATIBLE"}
]
measurements = {}
for name in candidates:
values = []
for _ in range(3):
delay_url = (
f"{controller}/proxies/{quote(name, safe='')}/delay"
f"?timeout={timeout_ms}&url={quote(target, safe='')}"
)
try:
response = session.get(delay_url, headers=headers, timeout=10)
delay = response.json().get("delay")
if isinstance(delay, int):
values.append(delay)
except (requests.RequestException, ValueError):
pass
time.sleep(0.3)
if values:
measurements[name] = statistics.median(values)
eligible = {
name: median for name, median in measurements.items()
if median <= max_median
}
if eligible:
best = min(eligible, key=eligible.get)
if best != current:
session.put(
group_url,
headers={**headers, "Content-Type": "application/json"},
json={"name": best},
timeout=10,
)
print(f"Switched {group}: {current} -> {best}")
else:
print(f"Kept {group} on {current}")
else:
print(f"No candidate passed the {max_median} ms threshold")
For production use, add structured logs containing the group, target, selected node, median delay, and failure count. Avoid logging subscription URLs, controller secrets, authorization headers, or full profiles. If several people share the machine, store the secret in an environment variable, an operating-system credential store, or a protected service file rather than embedding it in source code.
Designing stable groups for AI, Git, and remote development
Automation works best when the profile already expresses your intent. A single global group forces unrelated traffic to compete for one node and makes every switch disruptive. Consider separate groups such as AI, Developer, and Streaming, then route only the relevant domains to each group. Keep a stable fallback and make the default choice explicit so that a failed automation job does not leave the profile in an unexpected state.
For AI tools, consistency is usually more important than the lowest one-time delay. Authentication, model requests, telemetry, and streaming responses can use several related domains. A node that wins a small test but loses packets during a long response is a poor choice. Use a moderate threshold, require multiple successful measurements, and avoid changing the group during an active generation or coding session.
For Git, distinguish between HTTPS and SSH. The controller API can select the Clash group used by HTTPS traffic, but an SSH client may require its own proxy command or network path. Testing api.github.com does not prove that an SSH connection to github.com:22 will work. If your team uses HTTPS remotes, test the API and a small authenticated operation. If you use SSH, validate that protocol separately before assuming that node selection solved the problem.
Remote development tools introduce another challenge: they often combine browser login, REST requests, WebSocket streams, extension downloads, and persistent tunnels. A node switch can interrupt one of those channels even when the new node is objectively faster. For this workload, run selection before opening the IDE, pin the group for the duration of a work block, and switch manually only after closing or reconnecting the affected tool.
Troubleshooting common API switching failures
Why does the controller return connection refused?
First confirm that the client is running and that the controller is enabled. Then check the port and bind address in the active configuration rather than relying on a copied example. On a local machine, 127.0.0.1 and localhost normally point to the same service, but a container, virtual machine, or sandbox may have a different network namespace. A firewall or client security feature can also block local connections. Test the base endpoint with a simple authenticated request before testing a proxy-specific path.
Why do delay tests fail while browsing works?
The test URL may be blocked, rate-limited, unavailable from the selected region, or incompatible with the core’s request method. It may also be a DNS issue rather than a proxy issue. Try a small, stable HTTPS target and compare it with a real application request. Do not assume that one failed measurement proves the node is unusable; require several attempts and record whether the failure is a timeout, DNS error, TLS error, or HTTP status problem.
Why does switching a group interrupt my application?
Changing a group affects new connections immediately, but existing TCP or WebSocket sessions may not migrate cleanly. An AI stream, Git operation, remote extension tunnel, or package download can therefore be interrupted. Use API switching before starting a session, avoid rapid rotation, and keep long-lived workloads pinned to a group until the task ends. If the application supports reconnecting, allow it to establish a fresh session after the change.
How can I stop the script from jumping between two nodes?
Add hysteresis. For example, keep the current node unless the replacement is at least 150 milliseconds faster, require the current node to fail twice before switching, and impose a cooldown after every change. You can also select by median latency instead of one sample and penalize recent failures. These rules turn a raw health check into a policy that respects user experience.
Compared with manual switching in a basic GUI or blindly rotating nodes through a generic auto-select group, controller automation gives you measurable criteria, workload-specific targets, and an audit trail for every change. Some lightweight clients expose fewer API controls or make group behavior difficult to inspect, while a Mihomo-compatible ClashSky workflow keeps the controller, YAML profile, and friendly interface in one place. If you want to test this approach without assembling the client setup yourself, download ClashSky for free and start with one carefully scoped group before expanding automation.