HTTP API iOS 4.4.0+ Mac 4.0.0+
You may use the HTTP API to control Surge programmatically.
Configuration
[General]
http-api = examplekey@0.0.0.0:6171
http-api-tls = false
http-api-web-dashboard = false
http-api-mcp = false
Setting http-api-web-dashboard = true enables a web dashboard served on the same listener, so you can control Surge from a web browser. See the [General] section reference for these options.
Authentication
The API key must be filled in the X-Key header for all requests.
GET /v1/events
X-Key: examplekey
Accept: */*
In some specific situations, if it is not convenient to set the header, you can also pass it through the URL query. For example, directly downloading the CA certificate through a browser.
http://127.0.0.1:6171/v1/mitm/ca?x-key=examplekey
Clients that only support bearer tokens, such as MCP clients, may send the key as Authorization: Bearer examplekey instead. iOS 6.0.0+ Mac 6.11.0+
HTTPS (TLS)
Setting http-api-tls = true enables HTTPS support for the HTTP API service. Surge will use the CA certificate of MITM to generate the server certificate for the corresponding access address. You need to install the certificate on the client device manually.
Basic Constraints
Surge only uses GET and POST methods.
- For the GET method, use URL queries to send parameters.
- For the POST method, use a JSON body to send parameters.
Surge always returns a JSON body as the response.
Paths
Toggle Capabilities
- GET /v1/features/mitm
- POST /v1/features/mitm
- GET /v1/features/capture
- POST /v1/features/capture
- GET /v1/features/rewrite
- POST /v1/features/rewrite
- GET /v1/features/scripting
- POST /v1/features/scripting
- GET /v1/features/system_proxy (Surge Mac Only)
- POST /v1/features/system_proxy (Surge Mac Only)
- GET /v1/features/enhanced_mode (Surge Mac Only)
- POST /v1/features/enhanced_mode (Surge Mac Only)
Use the GET method to obtain the state of a capability. capture is HTTP Capture; see HTTP Capture Automation for running a capture session and reading its results.
GET Response example:
{"enabled":true}
Use the POST method to adjust the state of a capability.
POST Request example:
{"enabled":true}
Capture Filters iOS 6.0.0+ Mac 6.11.0+
- GET /v1/capture/filters
- POST /v1/capture/filters
Obtain or change the filters that decide which requests are recorded. in-memory applies to the recent requests kept while HTTP Capture is off, and on-disk applies to an HTTP Capture session. active names the filter currently in effect.
GET Response example:
{
"active": "in-memory",
"filters": {
"in-memory": {
"httpOnly": false,
"hideCrashReporterRequests": true,
"hideAppleRequests": false,
"hideUDP": false,
"type": "off",
"keywords": [],
"disabledKeywords": []
},
"on-disk": {
"httpOnly": true,
"hideCrashReporterRequests": true,
"hideAppleRequests": true,
"hideUDP": true,
"type": "pattern",
"keywords": ["-*google*", "*"],
"disabledKeywords": []
}
}
}
type:off,with-keywords(record only URLs containing one of the keywords),without-keywords(record only URLs containing none of them), orpattern(record URLs that match a pattern;*and?are supported, and a pattern prefixed with-excludes a hostname).disabledKeywords: entries kept inkeywordsthat do not take effect.
Use POST to change one filter. Pass scope (in-memory or on-disk) and any of the fields above; fields that are omitted stay unchanged. When keywords is replaced without disabledKeywords, disabled entries that remain in the list stay disabled.
POST Request example:
{"scope": "on-disk", "httpOnly": true, "type": "with-keywords", "keywords": ["example.com"]}
The response contains the filter as applied:
{"scope": "on-disk", "active": false, "filter": {"httpOnly": true, ...}}
Saved Capture Sessions iOS 6.0.0+ Mac 6.11.0+
Read the HTTP Capture sessions saved to disk. Start and stop a session with /v1/features/capture and choose what it records with /v1/capture/filters; see HTTP Capture Automation for the complete workflow and the meaning of each field.
- GET /v1/capture/sessions
List the saved sessions, newest first. Add include_size=true to also measure each session on disk, which reads every file in it.
Response example:
{
"sessions": [
{
"name": "2026-11-03-102105",
"active": false,
"createdDate": 1793672465.2,
"requestCount": 152,
"source": "http-capture",
"startDate": 1793672465.2,
"endDate": 1793674265.4,
"endReason": "time-limit",
"limits": {"time": 1800, "size": 0, "requestCount": 0},
"filter": {"httpOnly": true, "type": "with-keywords", "keywords": ["example.com"], ...}
}
]
}
- GET /v1/capture/sessions/requests?name=2026-11-03-102105&offset=0&limit=100
List the requests of one session in the order they were saved, in the same format as /v1/requests/recent, plus a key that identifies each request within the session. limit defaults to 100 and is at most 500. Add filter to keep the requests whose URL, host, address, policy, rule, process, device, status, or method contains the text, ignoring case; the response then also contains matched, and offset counts within the matching requests.
{"session": "2026-11-03-102105", "active": false, "total": 152, "offset": 0, "returned": 100, "requests": [{"id": 123, "URL": "https://api.example.com/v1/items", "key": "000123 - 10.21.07 - GET - https%3A%2F%2Fapi.example.com%2Fv1%2Fitems", ...}]}
- GET /v1/capture/sessions/data?name=2026-11-03-102105&key=...&type=response
Obtain the request or response body of one request; type is request or response. The response contains up to length bytes (512 KB by default, at most 1 MB) from offset, in base64. length in the response is the full size of the body; when truncated is true, request again with a larger offset. Bodies are saved as transferred, so a body with a Content-Encoding stays compressed.
{"session": "2026-11-03-102105", "key": "...", "type": "response", "length": 1843, "offset": 0, "truncated": false, "data": "eyJpdGVtcyI6..."}
Percent-encode the session name and key in the query string. Errors are answered with 400 and an error field.
Outbound Mode
- GET /v1/outbound
- POST /v1/outbound
Use GET to obtain the outbound mode, and use POST to change it.
GET Response example:
{"mode":"rule"}
POST Request example:
{"mode":"rule"}
Possible modes: direct, proxy, rule
- GET /v1/outbound/global
- POST /v1/outbound/global
Obtain or change the default policy for global outbound mode.
GET Response example:
{"policy":"ProxyA"}
POST Request example:
{"policy":"ProxyB"}
Proxy Policy
- GET /v1/policies
List all policies.
Add the query parameter include_external=true to also list the policies loaded by external policy groups (policy-path). iOS 6.0.0+ Mac 6.11.0+
The result then contains an additional external-policies field. Each entry has the policy name, the external group it belongs to, and an identifier. External policies can't be referenced by name, so pass the identifier as the policy option of $httpClient to use one in a script.
{
"proxies": ["ProxyA", "ProxyB"],
"policy-groups": ["GroupA", "ExternalGroup"],
"external-policies": [
{"name": "Node 1", "group": "ExternalGroup", "identifier": "POLICY::..."}
]
}
- GET /v1/policies/avoided iOS 6.0.0+ Mac 6.11.0+
List the policies that automatic groups avoid. See Temporary Avoidance.
Response example:
{"policies": ["ProxyA"]}
- POST /v1/policies/avoided iOS 6.0.0+ Mac 6.11.0+
Avoid a policy, or stop avoiding it. The response lists the avoided policies afterwards. A policy that doesn't exist is answered with 400.
Request example:
{"policy_name": "ProxyA", "avoided": true}
Pass {"clear": true} to stop avoiding every policy.
- GET /v1/policies/detail?policy_name=ProxyNameHere
Obtain the detail of a policy.
- POST /v1/policies/test
Test policies with a URL.
Request example:
{"policy_names": ["ProxyA", "ProxyB"], "url": "http://bing.com"}
- GET /v1/policy_groups
List all policy groups and their options.
- GET /v1/policy_groups/test_results
Obtain the test result of a url-test/fallback/load-balance group.
- GET /v1/policy_groups/select?group_name=GroupNameHere
Obtain the option of a select group.
Response example:
{"policy": "ProxyA"}
- POST /v1/policy_groups/select
Change the option of a select group.
Request example:
{"group_name": "GroupA", "policy": "ProxyA"}
- POST /v1/policy_groups/test
Test a group immediately.
Request example:
{"group_name": "GroupA"}
Response example:
{
"available": [
"ProxyA",
"ProxyB"
]
}
Requests
- GET /v1/requests/recent
List recent requests.
- GET /v1/requests/active
List all active requests.
- POST /v1/requests/kill
Kill an active request.
Request example:
{"id": 100}
Profiles
- GET /v1/profiles/current?sensitive=0
Obtain the text content of the current profile. If sensitive is false, both profile and originalProfile in the response are sanitized so they can be shared:
[Proxy]: the server and port of every proxy becomemasked, 1234. Usernames, passwords, PSKs, tokens, UUIDs and the other per-protocol secrets become<masked>.[Proxy Group]: a remotepolicy-pathbecomeshttps://masked/.[General]: the key inhttp-apiandexternal-controller-access, the credentials inhttp-listenandsocks5-listen, and the value ofwifi-access-http-authbecome<masked>. The listen addresses and ports are kept. iOS 6.0.0+ Mac 6.11.0+[MITM]:ca-p12andca-passphrasebecome-.[Keystore]: thebase64content and thepasswordof every item become-.[WireGuard *],[Tailscale *],[Snell Server]and[MTProto]: private keys, pre-shared keys, auth keys, PSKs and secrets are masked.
Other values are returned as written, including rules, MITM hostnames and DNS servers.
- POST /v1/profiles/reload
Execute profile reloading immediately.
- POST /v1/profiles/switch (Surge Mac Only)
Request example:
{"name": "Profile2"}
Switch to another profile.
- GET /v1/profiles Mac Only 4.0.6+
Get all available profile names.
- POST /v1/profiles/check Mac Only 4.0.6+
Request example:
{"name": "Profile2"}
Check the profile. If the profile is invalid, an error is returned. Otherwise, the error field is null.
Profile Sections iOS 6.0.0+ Mac 6.11.0+
A profile can be spread over several files with #!include, so it is changed one section at a time, the same way as with surge-cli profile section.
- GET /v1/profiles/sections
List every section of the current profile, with the file that holds it, whether it can be edited (and the reason when it cannot), and its revision.
- GET /v1/profiles/section?name=Rule
Obtain one section. The content field holds the section's lines without the header, and revision identifies the version that was read. Percent-encode the name when it contains spaces, such as Ruleset%20Streaming.
- POST /v1/profiles/section
Request example:
{"name": "Rule", "content": "DOMAIN-SUFFIX,example.com,DIRECT\nFINAL,Proxy", "revision": "<revision>"}
Replace the entire content of the section, or create it in the main profile when it does not exist yet. The section is written to the file that holds it, and every other section and file is left untouched. The whole profile is validated with the new content before anything is written, then reloaded. revision is optional; when given, the change is refused if the section was modified after it was read. The response reports the file that was written, whether anything changed, and the new revision for a follow-up edit.
Managed and enterprise profiles, sections included from a URL or a managed profile, sections assembled from several files, and sections that mix their own lines with #!include directives are read-only. Errors are answered with 400 and an error field.
External Resources iOS 5.23.0+ Mac 6.10.0+
- GET /v1/external_resources
List all external resources referenced by the current profile and enabled modules, such as rule sets, domain sets, scripts and policy group lists.
Response example:
{
"defines": [
{
"path": "https://example.com/ruleset.list",
"type": "ruleset",
"key": "5d41402abc4b2a76b9719d911017c592",
"local": false,
"ready": true,
"updatedAt": 1759800000,
"updating": false,
"fromModule": null
}
]
}
type: One ofruleset,domainset,script,policy-groupanddata.key: The identifier of the resource, used by the update endpoint.local: Whether the resource is a local file. Local resources have noupdatedAtfield.ready: Whether the resource content is available.updatedAt: The UNIX timestamp of the last successful download, or 0 if the resource has never been downloaded.fromModule: The name of the module that references the resource, or null if it's from the profile.error: Present only if the last update or parsing failed.POST /v1/external_resources/update
Download remote external resources immediately. Use "all" as the key to update all remote resources. Local resources are skipped.
Request example:
{"key": "5d41402abc4b2a76b9719d911017c592"}
The response maps each updated key to "success" or an error message. If the key is not found, a 400 error is returned.
DNS
- POST /v1/dns/flush
Flush the DNS cache.
- GET /v1/dns
Obtain the current DNS cache content.
- POST /v1/test/dns_delay
Test the DNS delay.
Modules
- GET /v1/modules
List the available and enabled modules.
Response example:
{
"enabled": [
"router.com"
],
"available": [
"Game Console SNAT",
"Google Home Devices",
"router.com",
"MitM All Hostnames"
],
"modules": [
{
"name": "router.com",
"enabled": true,
"type": "installed",
"path": "/Users/me/Library/Application Support/Surge/Modules/router.com.sgmodule",
"description": "Access the router at router.com",
"category": null,
"header": {"name": "router.com", "desc": "Access the router at router.com", "version": "1.2"},
"arguments": [],
"updated-at": 1793000000,
"sections": {"Host": 1, "Rule": 1}
}
]
}
modules iOS 6.0.0+ Mac 6.11.0+ describes each module:
type:internal,localorinstalled.header: every#!key=valuefield of the module header, with lowercased keys, including fields Surge does not interpret such asauthor,homepageandversion.arguments: the names of the declared arguments. Their values are never included.updated-at: when the module file was last modified, in seconds since 1970, ornullfor internal modules.sections: the number of non-comment lines in each section, counted after loading the module with its stored arguments. When the module cannot be loaded,load-errorgives the reason instead.GET /v1/modules/detail?name=router.com iOS 6.0.0+ Mac 6.11.0+
Return one module with the fields above plus text, the module file as written. Responds with 404 when no module has that name.
- POST /v1/modules
Enable or disable modules.
Request example:
{
"router.com": false,
"Google Home Devices": true
}
Scripting
- GET /v1/scripting
List all the configured scripts.
- POST /v1/scripting/evaluate
Evaluate a script with a mock environment. script_text is required; mock_type is a script type string such as http-request or cron (default: cron). The $trigger global is set to http-api during evaluation.
Request example:
{
"script_text": "The content of JS script",
"mock_type": "cron",
"timeout": 5
}
- POST /v1/scripting/cron/evaluate
Evaluate a configured cron script immediately by name. Only cron-type scripts are accepted.
Request example:
{
"script_name": "script1"
}
Device Management Mac Only 4.0.6+
- GET /v1/devices
Obtain the list of the current active and saved devices.
- GET /v1/resources/devices-icon?id={iconID}
Obtain the icon of a device. You may get the iconID from device.dhcpDevice.icon.
- POST /v1/devices
Change the device properties. The physicalAddress field is required. You may adjust one or more properties from name, address, and shouldHandledBySurge.
Request example:
{
"physicalAddress":"F0:9F:C2:00:00:00",
"name": "Computer",
"address": "192.168.1.200",
"shouldHandledBySurge": true
}
Misc
- POST /v1/stop
Shutdown the Surge engine. If Always On is enabled on Surge iOS, the Surge engine will restart.
- POST /v1/ponte/restart iOS 6.0.0+ Mac 6.11.0+
Restart the device's Ponte server: its channels are set up again, and connections to it from other devices are dropped. If Ponte isn't enabled, a 400 error is returned.
- GET /v1/events
Obtain the content of the event center.
- GET /v1/rules
Obtain the list of rules.
- GET /v1/traffic
Obtain traffic information.
Each policy under connector also reports testBytes: how many of its bytes, in and out, were carried by proxy tests rather than requests. iOS 6.0.0+ Mac 6.11.0+
- POST /v1/log/level
Change the log level for the current session.
Request example:
{"level": "verbose"}
- GET /v1/mitm/ca
Obtain the CA certificate for MITM, in DER binary format. (Certificate only, no private key included)
- GET /v1/geoip?ip=1.1.1.1 iOS 5.23.0+ Mac 6.10.0+
Look up the region (ISO 3166-1 alpha-2 code), ASN and AS organization of an IPv4 or IPv6 address, using the same databases as the GEOIP, IP-ASN rules and the $utils.geoip, $utils.ipasn, $utils.ipaso scripting APIs.
Response example:
{
"address": "1.1.1.1",
"country": "AU",
"asn": 13335,
"organization": "Cloudflare, Inc.",
"geoip-db-date": 1759800000,
"asn-db-date": 1759800000
}
Fields without a result are null. geoip-db-date and asn-db-date are the UNIX timestamps of the databases in use. If ip is not a valid IP address, a 400 error is returned.
Prometheus Metrics iOS 5.22.0+ Mac 6.9.0+
- GET /v1/metrics
Expose runtime statistics in the Prometheus text format, so Surge can be monitored with Prometheus and Grafana. This is especially useful for gateway deployments running around the clock. Unlike other endpoints, the response body is plain text instead of JSON.
Exposed metrics:
| Metric | Type | Description |
|---|---|---|
surge_build_info{version,build,system} |
gauge | Always 1; the build information is attached as labels |
surge_uptime_seconds |
gauge | Engine uptime |
surge_memory_bytes |
gauge | Physical memory footprint of the engine process |
surge_active_requests |
gauge | Number of in-flight requests |
surge_dns_cache_entries |
gauge | Number of cached DNS results |
surge_active_bans |
gauge | Number of active unauthorized-access bans |
surge_interface_in_bytes_total{interface} |
counter | Downloaded bytes per network interface since the engine started |
surge_interface_out_bytes_total{interface} |
counter | Uploaded bytes per network interface since the engine started |
surge_policy_in_bytes_total{policy} |
counter | Downloaded bytes per policy since the engine started |
surge_policy_out_bytes_total{policy} |
counter | Uploaded bytes per policy since the engine started |
The traffic counters reset when the engine restarts. PromQL functions such as rate() and increase() handle counter resets automatically: use rate() to derive real-time speeds, and increase() to aggregate traffic over any time window.
Since Prometheus does not send custom headers by default, pass the API key as a query parameter in the scrape configuration:
scrape_configs:
- job_name: surge
metrics_path: /v1/metrics
params:
x-key: ["examplekey"]
static_configs:
- targets: ["192.168.1.1:6171"]
Model Context Protocol (MCP) iOS 6.0.0+ Mac 6.11.0+
- POST /v1/mcp
The HTTP API also serves a Model Context Protocol endpoint, so AI agents such as Claude Code can inspect and control Surge directly, including Surge iOS running on another device. The tools cover the same capabilities as Surge CLI: status and network summary, policies and policy groups, rule matching with an explanation of every policy group decision, DNS and GeoIP lookups, active and recent requests with their captured bodies, saved HTTP Capture sessions, logs, the logbook and live events, policy and network tests, diagnostics, temporary rules, profiles, modules, features, capture filters, scripts, and on Surge Mac the gateway devices and plugins.
The endpoint is off by default; enable it with http-api-mcp = true. While it is off, authorized requests to it are answered with 403.
The endpoint uses the Streamable HTTP transport in its stateless form: every message is a POST answered with a single JSON body. It is authenticated with the same key as the other paths. For example, to add it to Claude Code:
claude mcp add --transport http surge http://192.168.1.10:6171/v1/mcp --header "X-Key: examplekey"
Clients that read a JSON configuration use an entry like this:
{
"mcpServers": {
"surge": {
"type": "http",
"url": "http://192.168.1.10:6171/v1/mcp",
"headers": { "X-Key": "examplekey" }
}
}
}
Profiles are changed one section at a time, the same way as with surge-cli profile section: an agent reads a section with get_profile_section and replaces its whole content with replace_profile_section, passing back the revision it read. The change is written to the file that holds the section and validated with the rest of the profile first.
Each tool declares whether it only reads state, sends test traffic, changes settings, or is destructive (such as stopping Surge or replacing the profile rules), so the client can ask for confirmation before running it. Results are limited to 256 KB; tools that return lists accept filters and limits to narrow them.
The API key grants full control of Surge, including running scripts and stopping Surge. Only expose the listener on trusted networks. Without http-api-tls, the key is sent in plain text. With http-api-tls, the client must trust the MITM CA certificate; Node.js based clients read additional CA certificates from the NODE_EXTRA_CA_CERTS environment variable.
Shortcuts iOS 6.0.0+
Surge iOS provides a Call HTTP API action in the Shortcuts app. It sends a request to the running Surge engine and returns the response body as text. The action needs no API key, and it works even if http-api is not configured.
- Method: GET or POST.
- Path: An API path, such as
/v1/outbound. The/v1prefix can be omitted. - Body: An optional JSON object. For GET requests, its fields are sent as query parameters.
The action fails if the Surge engine is not running, or if the API answers with an error status.