Clash and Mihomo expose an external-controller API that lets a local script inspect proxy groups, choose a node in a selector group, and confirm that the requested choice became active. This is useful when a scheduled task needs to move traffic to a known node, when a developer wants to add a node switch to a deployment workflow, or when a monitoring script should report which proxy is currently selected. The API changes the running core’s state; it does not edit the subscription or permanently rewrite the YAML configuration.
Reliable automation needs more than sending one HTTP request. A script should confirm that the controller is reachable, authenticate, check that the requested group and node exist, make the change, and read the group again to verify the result. It should also distinguish an API error from a node that is selected but cannot reach the destination. This guide uses a local Mihomo-compatible controller and a select proxy group as the example.
Automate Clash Node Switching With the External Controller API
Understand the controller API and proxy groups
The external controller accepts HTTP requests on the address configured by external-controller. A common local address is 127.0.0.1:9090, but clients and configurations can use a different port. This address is separate from settings such as mixed-port: 7890, which accepts application proxy connections. If a script sends an API request to the mixed port, it is talking to a proxy listener rather than the controller and will not receive the expected API response.
In a YAML configuration, the relevant settings may look like this:
external-controller: 127.0.0.1:9090
secret: "replace-with-a-long-random-secret"
proxy-groups:
- name: "🌐 Select"
type: select
proxies:
- "Node A"
- "Node B"
- DIRECT
Use the configuration actually loaded by the running core. A graphical client may generate runtime configuration from a subscription and local overrides, so editing a source YAML file does not always change the active controller address or group list. Check the client’s controller or core settings, the active configuration view, or the startup log. Restart or reload the configuration if the client requires it before the changed settings take effect.
The API’s GET /proxies endpoint returns the available proxies and groups. A group entry commonly includes its type, its candidate names in all, and its current selection in now. For a selector group, a request such as PUT /proxies/{group} with a JSON body containing a candidate name asks the core to switch the group. The name in the request body must match one of the group’s current candidates exactly, including capitalization, spaces, punctuation, and emoji.
These endpoints operate on the running core. Switching a selector does not change the subscription provider’s node order, remove a failed node, or guarantee that every new connection will succeed. Existing connections may continue using their established route until they close. If a group is an automatic type such as url-test or fallback, its selection is controlled by its own testing behavior; do not assume it can be managed like a manual selector. Check the group’s reported type before attempting a manual switch.
Enable and secure the controller
Before writing automation, verify that the core exposes the controller on a reachable address and that authentication is configured. A controller bound to 127.0.0.1 accepts local connections only. Avoid changing this to 0.0.0.0 merely to make a script on another device connect: that can expose administrative operations to every host able to reach the machine. If remote administration is necessary, use a properly protected private network, firewall restrictions, and a secure transport or tunnel supported by the environment.
When a secret is set, send it in the HTTP Authorization header using the bearer-token format. Do not place it in a URL query string, print it in routine logs, commit it to a source repository, or include it in a command that may be recorded in shell history. For scheduled jobs, read the value from an environment variable or a protected local secret store. A secret should be long and unique; a short example string is not suitable for a real controller.
Authorization: Bearer YOUR_CONTROLLER_SECRET
Test reachability before debugging node selection. From the same machine and user account that will run the script, request the controller’s version endpoint. A connection refusal usually points to a wrong address or port, a stopped core, or a controller that is disabled. An HTTP 401 or 403 indicates an authentication or permission problem. An HTTP 404 may mean the request path is wrong or the installed core does not provide that endpoint.
curl -sS \
-H "Authorization: Bearer YOUR_CONTROLLER_SECRET" \
http://127.0.0.1:9090/version
Do not confuse controller authentication with authentication for a proxy server or subscription. The controller secret authorizes operations on the local Clash or Mihomo core. It does not log in to a remote node, and changing a node through the API cannot repair invalid credentials on that node.
Switch a selector node with a script
The following Python example performs a guarded switch. It reads the current group data, checks that the group is a manual Select group, confirms the requested node is among the available candidates, sends the update, and polls the group until the reported current selection matches. The example uses only the Python standard library and expects the controller to be available on the same computer.
import json
import os
import time
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen
BASE_URL = os.environ.get("CLASH_CONTROLLER", "http://127.0.0.1:9090")
SECRET = os.environ["CLASH_CONTROLLER_SECRET"]
GROUP_NAME = "🌐 Select"
TARGET_NODE = "Node B"
def request_json(path, method="GET", payload=None):
body = None if payload is None else json.dumps(payload).encode("utf-8")
request = Request(
BASE_URL.rstrip("/") + path,
data=body,
method=method,
headers={
"Authorization": f"Bearer {SECRET}",
"Content-Type": "application/json",
"Accept": "application/json",
},
)
with urlopen(request, timeout=5) as response:
return json.loads(response.read().decode("utf-8"))
group_path = "/proxies/" + quote(GROUP_NAME, safe="")
node_path = "/proxies"
try:
proxies = request_json(node_path)["proxies"]
group = proxies.get(GROUP_NAME)
if group is None:
raise RuntimeError(f"Proxy group not found: {GROUP_NAME}")
if group.get("type") != "Selector":
raise RuntimeError(
f"Expected a Selector group, got {group.get('type')!r}"
)
if TARGET_NODE not in group.get("all", []):
raise RuntimeError(f"Node is not available in this group: {TARGET_NODE}")
if group.get("now") != TARGET_NODE:
request_json(group_path, method="PUT", payload={"name": TARGET_NODE})
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
updated = request_json(node_path)["proxies"].get(GROUP_NAME, {})
if updated.get("now") == TARGET_NODE:
print(f"Selected {TARGET_NODE} in {GROUP_NAME}")
break
time.sleep(0.25)
else:
raise RuntimeError("Controller did not confirm the requested selection")
except HTTPError as error:
raise RuntimeError(f"Controller returned HTTP {error.code}") from error
except URLError as error:
raise RuntimeError(f"Cannot reach the controller: {error.reason}") from error
Set the secret before running the script rather than writing it into the file. For example, in a Unix-like shell, set CLASH_CONTROLLER_SECRET in the environment used by the job. On Windows, configure the same variable in the task’s environment or retrieve it from a protected credential store. If the controller is not on the default address, set CLASH_CONTROLLER to the actual local controller URL. Keep the group and node names synchronized with the configuration currently loaded by the core.
Encoding the group name in the URL matters when a name contains spaces, non-ASCII characters, or URL-reserved punctuation. The script uses quote() for the path segment rather than assembling an unescaped URL. The JSON body contains the selected proxy name, so it should remain a JSON string and must not be manually URL-encoded.
The verification step reads /proxies again instead of assuming that a successful HTTP response means the switch has completed. A core may reject the request, the group may have changed between inspection and update, or the response may indicate an error. Polling for a short bounded period also avoids waiting indefinitely if the core does not reach the requested state. In production, keep the timeout finite and make the failure visible to the calling scheduler or monitoring system.
Add health checks, retries, and failure handling
Confirming that a group reports now: "Node B" proves that the selector accepted the requested choice; it does not prove that the node can reach a specific website or service. Treat selection verification and connectivity verification as separate checks. A node can be selected while its remote server is unavailable, DNS resolution fails, the destination is blocked, or the target service rejects the connection.
Mihomo-compatible controllers provide delay-testing endpoints for proxies. A client can request a test for an individual proxy using a path of the form /proxies/{name}/delay, with parameters such as a test URL and timeout. The exact supported parameters and response format can vary with core version, so check the documentation for the installed core before depending on them. Use a stable HTTPS endpoint that is appropriate for the network and policy being tested; a test against one destination is not a universal measurement of performance for every site.
A practical automation sequence is to inspect the group, test one or more candidate nodes, select an eligible node, confirm the group’s now field, and then perform a lightweight application-level request through the proxy. A delay result can identify unreachable candidates, but it is not equivalent to measuring throughput, reliability over time, or access to the actual destination your application needs. If the target application has a health endpoint, use that for the final check.
- Bound each request. Set a short HTTP timeout for local controller calls and a separate, reasonable timeout for network health checks.
- Retry only transient failures. A brief connection reset may justify a retry; a missing group, unknown node, or authentication error should normally stop the job immediately.
- Use limited backoff. If retrying a temporary failure, wait progressively longer for a small number of attempts rather than sending a rapid request loop.
- Re-read state before repeating a switch. The first update may have succeeded even if the client lost the response. Check the current selection before sending the same operation again.
- Record useful, non-secret details. Log the group, requested node, result, elapsed time, and error category, but never the bearer token.
Automation should also account for concurrent changes. A person may switch the group in the GUI while a scheduled task is running, or a configuration update may replace node names between the initial query and the update. If the desired selection is no longer available, refresh the group data and make a deliberate decision: select a configured fallback, report an error, or leave the current route untouched. Do not silently choose the first candidate in a list, because order may change after a subscription refresh and the first entry may not be suitable.
Troubleshoot common API problems
If a request cannot connect, confirm the controller address from the active runtime settings and verify that the core is running. Check that the URL uses the controller port, not the HTTP, SOCKS, or mixed proxy port. A local firewall or another service occupying the configured port can also prevent the core from listening where expected.
If the controller answers but rejects the request, inspect the HTTP status and response body without exposing credentials in logs. Authentication failures usually mean that the secret is missing, stale, or sent in the wrong header format. If the API returns a successful response but the displayed node does not change, inspect the group’s type and candidate list. The requested name may be misspelled, may belong to a different group, or may no longer exist after a configuration update.
If the group changes but traffic still appears to use the previous route, remember that a selector update is not a command to terminate every existing connection. Test with a new connection, check the core’s connection log, and confirm that the relevant rule actually routes the destination through the group you changed. A rule may direct that traffic to another group, DIRECT, or a different policy. The API can select a node only within the group addressed by the request; it cannot override unrelated rule matching.
- Connection refused: check the core state, controller bind address, port, and whether the request is local.
- Unauthorized response: check the active controller secret and bearer header; rotate the secret if it may have been exposed.
- Group not found: query
/proxiesand copy the exact active group name, including symbols and spacing. - Node not found: refresh the group’s
alllist and check whether the node is nested under another group or provider. - Selection is correct but traffic fails: test a new connection, review rules and logs, then test the node against the actual destination.
Frequently asked questions
Does switching a node through the API change the YAML file?
No. The request changes the running core’s selector state. It does not rewrite a subscription, edit the source YAML, or guarantee that the same choice will remain after a restart or configuration reload. If a choice must persist, use the client’s supported configuration or override mechanism and confirm how that client stores selections.
Can I use the controller API from another device?
It is safer to keep the controller bound to loopback and run the automation on the same machine. If remote access is required, do not expose an unauthenticated controller to a public or shared network. Restrict access at the network layer, use a secure private connection, and protect the controller secret as an administrative credential.
Can a script manually switch a url-test group?
A url-test group selects a proxy according to its testing behavior, unlike a manual select group. Check the group type returned by the controller and the capabilities of the installed core. If a human or script must choose among candidates directly, create or use an appropriate selector group and route the relevant rules through it.
Does a successful update prove the new node works?
No. Verify the group’s current selection to confirm the control-plane change, then run a separate delay test or application-level request to confirm connectivity. These checks answer different questions: one verifies which proxy the group selected, and the other tests whether a particular network path can reach a particular destination.