@yawlabs/caddy-mcp 2.5.3 → 2.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,24 +1,24 @@
1
1
  # @yawlabs/caddy-mcp
2
2
 
3
+ [![Add to Yaw MCP](https://yaw.sh/yaw-mcp-button.svg)](https://yaw.sh/mcp/install?name=Caddy&command=npx&args=-y%2C%40yawlabs%2Fcaddy-mcp&description=Manage%20Caddy%20web%20servers%20-%20config%2C%20routes%2C%20TLS%2C%20PKI&source=https%3A%2F%2Fgithub.com%2FYawLabs%2Fcaddy-mcp)
4
+
5
+ One click adds this to your local Yaw MCP config so it's available in every Yaw Terminal session. Or install manually below.
6
+
3
7
  [![npm version](https://img.shields.io/npm/v/@yawlabs/caddy-mcp)](https://www.npmjs.com/package/@yawlabs/caddy-mcp)
4
8
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
9
  [![GitHub stars](https://img.shields.io/github/stars/YawLabs/caddy-mcp)](https://github.com/YawLabs/caddy-mcp/stargazers)
6
10
 
7
- **Manage Caddy web servers from Claude Code, Cursor, and any MCP client.** 18 tools + 4 resources covering every endpoint of Caddy's admin API — config, routes, reverse proxies, TLS, PKI, metrics, snapshots.
11
+ **Manage Caddy web servers from Claude Code, Cursor, and any MCP client.** 18 tools + 4 resources covering every endpoint in Caddy's admin API reference — config, routes, reverse proxies, TLS, PKI, metrics, snapshots.
8
12
 
9
13
  Built and maintained by [Yaw Labs](https://yaw.sh).
10
14
 
11
- [![Add to Yaw MCP](https://yaw.sh/yaw-mcp-button.svg)](https://yaw.sh/mcp/install?name=Caddy&command=npx&args=-y%2C%40yawlabs%2Fcaddy-mcp&description=Manage%20Caddy%20web%20servers%20-%20config%2C%20routes%2C%20TLS%2C%20PKI&source=https%3A%2F%2Fgithub.com%2FYawLabs%2Fcaddy-mcp)
12
-
13
- One click adds this to your local Yaw MCP config so it's available in every Yaw Terminal session. Or install manually below.
14
-
15
15
  ## Why this one?
16
16
 
17
17
  Other Caddy MCP servers wrap half the admin API and silently swallow errors. This one doesn't.
18
18
 
19
- - **Complete admin API coverage** — every documented endpoint: `/load`, `/config/*`, `/id/*`, `/stop`, `/adapt`, `/pki/ca/*`, `/reverse_proxy/upstreams`, `/metrics`. No placeholder tools that 404.
19
+ - **Complete admin API coverage** — every endpoint in [Caddy's admin API reference](https://caddyserver.com/docs/api): `/load`, `/config/*`, `/id/*`, `/stop`, `/adapt`, `/pki/ca/*`, `/reverse_proxy/upstreams`, `/metrics`. No placeholder tools that 404. Caddy's Go runtime debug endpoints (`/debug/pprof/*`, `/debug/vars`) are deliberately not wrapped — for leak trends use `caddy_metrics` with `filter: "go_goroutines"` or `"go_memstats"`, which come from the same admin registry; for stack dumps, CPU profiles and traces, curl the admin endpoint directly ([Caddy profiling docs](https://caddyserver.com/docs/profiling)).
20
20
  - **Safe concurrent writes** — uses ETags (`If-Match`) so your changes never silently overwrite someone else's. Surfaces `HTTP 412 Precondition Failed` as a clear message, not a cryptic error.
21
- - **Safe-by-default mutations** — `caddy_config_set` defaults to idempotent `overwrite` (PATCH), not `append` (POST). Calling twice doesn't duplicate your route.
21
+ - **Safe-by-default mutations** — `caddy_config_set` defaults to idempotent `overwrite` (PATCH), not `append` (POST). Calling twice doesn't duplicate your route. A write to the config root — which replaces the *entire* config, admin endpoint included — is refused without `confirm=true` and snapshotted first, like `caddy_load`.
22
22
  - **Defensive parsing** — `caddy_list_routes` never crashes on malformed config, even if routes are null, handlers are strings, or matchers are non-arrays. Regression-tested.
23
23
  - **No leaked credentials in errors** — if `CADDY_ADMIN_URL` contains a token in the path/query, the connect-failed message shows only the origin.
24
24
  - **Fallback error surfacing** — when a TLS write PATCH fails and the PUT fallback also fails, both error bodies are returned so you know what actually went wrong.
@@ -78,10 +78,10 @@ That's it. Now ask your AI assistant:
78
78
 
79
79
  | Environment variable | Default | Description |
80
80
  |---|---|---|
81
- | `CADDY_ADMIN_URL` | `http://localhost:2019` | Caddy admin API URL. Set to `http://caddy:2019` inside Docker, or an https URL for remote admin. Also accepts a unix socket, in either `unix:///var/run/caddy-admin.sock` or Caddy's own `unix//var/run/caddy-admin.sock` spelling — see below. |
82
- | `CADDY_API_TOKEN` | (none) | Optional Bearer token for authenticated admin endpoints. Only needed if you've configured Caddy with auth. |
81
+ | `CADDY_ADMIN_URL` | `http://localhost:2019` | Caddy admin API URL. Set to `http://caddy:2019` inside Docker, or an https URL for an admin endpoint behind a TLS-terminating reverse proxy — see Troubleshooting for the `Host` / `Origin` rules Caddy applies to anything that is not its own loopback address. Caddy's native remote admin listener (`admin.remote`, default `:2021`) is **not** supported: it requires a TLS client certificate, which caddy-mcp does not present. Also accepts a unix socket, in either `unix:///var/run/caddy-admin.sock` or Caddy's own `unix//var/run/caddy-admin.sock` spelling — see below. |
82
+ | `CADDY_API_TOKEN` | (none) | Optional Bearer token, sent as `Authorization: Bearer <token>` on every request. Caddy's admin API has no token auth of its own and ignores this header — it matters only to an authenticating proxy in front of the admin endpoint, so leave it unset when caddy-mcp reaches Caddy directly. If the header does arrive at the admin listener, Caddy 2.0 through 2.11.2 writes it in clear into the `admin.api` "received request" log line, at INFO — on every path except `/metrics`, which has logged at DEBUG since 2.2.1. Run Caddy 2.11.3 or later, which logs it as `REDACTED`, or have the proxy strip the header once it has authenticated (Caddy: `header_up -Authorization`; nginx: `proxy_set_header Authorization "";`). |
83
83
  | `CADDY_MCP_SNAPSHOT_DIR` | (none) | Directory for persisting `caddy_revert` snapshots. Unset, snapshots live in memory only and are lost when this server restarts. Snapshots are full Caddy configs and can contain secrets, so the location is opt-in rather than defaulted. |
84
- | `CADDY_MAX_RETRIES` | `2` | Number of retries on transient failures: network errors, and 502/503/504 (which only a proxy in front of Caddy sends). Caddy's own 500s are deterministic rejections and never retry, nor do 4xx and 412. Requests a replay could change the outcome of also skip retry: POSTs to `/config/*` and `/id/*` (they append, or replace an existing key -- retrying could duplicate routes), and a PUT or DELETE at an array index such as `.../routes/0` (a replay would insert a second route, or remove the one that slid into that index), including a PUT to a bare `/id/<id>`, which Caddy resolves to the identified element's array index. A config change whose timeout fired is never retried (see `CADDY_LOAD_TIMEOUT`). A refused connection retries for every method, since nothing was sent. POSTs to `/load`, `/adapt`, `/stop` still retry. Hard-capped at 5; values above the cap log a one-time stderr notice so the clamp is visible. Set to `0` to disable. |
84
+ | `CADDY_MAX_RETRIES` | `2` | Number of retries on transient failures: network errors, and 502/503/504 (which only a proxy in front of Caddy sends). Caddy's own 500s are deterministic rejections and never retry, nor do 4xx and 412. Requests a replay could change the outcome of also skip retry: POSTs to `/config/*` and `/id/*` (they append, or replace an existing key -- retrying could duplicate routes), and a PUT or DELETE at an array index such as `.../routes/0` (a replay would insert a second route, or remove the one that slid into that index), including a PUT to a bare `/id/<id>`, which Caddy resolves to the identified element's array index. Those match however the path is spelled — with trailing slashes, or with the trailing `/...` segment Caddy strips before it picks a method, so `.../routes/0/...` and `PUT /id/<id>/...` are covered too. A config change whose timeout fired is never retried (see `CADDY_LOAD_TIMEOUT`). A refused connection retries for every method, since nothing was sent. POSTs to `/load`, `/adapt`, `/stop` still retry. Hard-capped at 5; values above the cap log a one-time stderr notice so the clamp is visible. Set to `0` to disable. |
85
85
  | `CADDY_TIMEOUT` | `10000` | Timeout in ms for admin API requests that do not change the config: GETs, `/adapt`, `/stop`, PKI, upstreams and metrics. Config changes use `CADDY_LOAD_TIMEOUT`. Non-numeric, `<= 0`, or fractional values below 1ms fall back to the default. |
86
86
  | `CADDY_LOAD_TIMEOUT` | `55000` | Timeout in ms for every request that changes the config: `POST /load`, and every POST/PUT/PATCH/DELETE under `/config/*` and `/id/*`. Each is a full synchronous reload inside Caddy, which can legitimately run long -- Caddy sleeps through `apps.http.shutdown_delay` inside the reload whenever a change closes a listener, and a change can wait behind another reload. A timeout here is never retried: Caddy keeps applying a change after the client gives up, so the error says the outcome is unknown and to re-read the config before retrying (`caddy_load` and `caddy_revert` keep their snapshot in that case). Keep it below your MCP client's request timeout (60 s by default in the MCP SDK), or that error arrives after the client has given up and is never shown; the default sits 5 s under it. Non-numeric, `<= 0`, or fractional values below 1ms fall back to the default. |
87
87
 
@@ -98,8 +98,11 @@ onto a unix socket, where access is governed by filesystem permissions:
98
98
 
99
99
  Point `CADDY_ADMIN_URL` at the same path (`unix:///var/run/caddy-admin.sock`)
100
100
  and requests are sent over the socket instead of TCP. The process running
101
- caddy-mcp needs read/write permission on the socket file. `CADDY_API_TOKEN`
102
- still applies if you have auth in front of the endpoint.
101
+ caddy-mcp needs read/write permission on the socket file. Leave
102
+ `CADDY_API_TOKEN` unset here unless an authenticating proxy actually listens on
103
+ that socket: over a unix path caddy-mcp is usually talking to Caddy's own
104
+ socket, where the token does nothing — and, before Caddy 2.11.3, is logged in
105
+ clear.
103
106
 
104
107
  **Alternate MCP clients:**
105
108
 
@@ -118,11 +121,11 @@ Use the same JSON block shown above in any of these.
118
121
  ### Config management (6)
119
122
 
120
123
  - **caddy_config_get** — Read config at any JSON path (or the full config).
121
- - **caddy_config_set** — Write config at a path. Modes: `overwrite` (PATCH, default, idempotent; the key must exist), `append` (POST: appends to an array, but replaces an existing non-array key and cannot create missing parents), `insert` (PUT: inserts at an array position, or strictly creates a key along with any missing parents and fails with 409 if it exists — the way to create a server or app, even on an instance with no config).
122
- - **caddy_config_delete** — Delete config at a path. Requires `confirm=true` (deleting a parent path also removes every descendant).
124
+ - **caddy_config_set** — Write config at a path. Modes: `overwrite` (PATCH, default, idempotent; the key must exist, and the whole subtree at the path is replaced), `append` (POST: appends to an array, but replaces an existing non-array key and cannot create missing parents), `insert` (PUT: inserts at an array position, or strictly creates a key along with any missing parents and fails with 409 if it exists — the way to create a server or app, even on an instance with no config). `append` at a path ending in `/...` (e.g. `apps/http/servers/srv0/routes/...`) with an **array** value appends every element in one request — all or nothing, one reload; without the `/...`, an array value is added as a single element and Caddy rejects the load for typed arrays like `routes` or `listen`. A path that addresses the config **root** (`''`, `'/'`, `'config'`, `'/config/'`, a slash-only variant, or any of those followed by a lone `...` segment) addresses the **entire** config and requires `confirm=true`: `overwrite` and `append` there replace the whole configuration with `value`, exactly as `caddy_load` would, including the `admin` block unless `value` carries one — after which Caddy re-binds its admin endpoint to the new config's `admin.listen`, to its default address when it sets none, or to no address at all when it sets `admin.disabled`, and a `CADDY_ADMIN_URL` pointing anywhere else stops working. A root write auto-snapshots the prior config first (when it can be read) so `caddy_revert` can restore it; no other path is snapshotted. `insert` at the root only succeeds after a root `caddy_config_delete` (409 otherwise), and `overwrite` is the reverse: after a root delete it answers 404 until `append`, `insert` or `caddy_load` re-creates the config.
125
+ - **caddy_config_delete** — Delete config at a path. Requires `confirm=true` (deleting a parent path also removes every descendant). A path that addresses the config root (`''`, `'/'`, `'config'`, `'/config/'`, a slash-only variant, or any of those followed by a lone `...` segment) addresses the **entire** config: it unloads every app and server plus the `admin` block, after which Caddy re-binds its admin endpoint to its default address (`localhost:2019`, or `$CADDY_ADMIN` in Caddy's environment) — if `CADDY_ADMIN_URL` points anywhere else, neither caddy-mcp nor `caddy_revert` can reach Caddy afterwards. A root delete auto-snapshots the prior config first (when it can be read), so `caddy_revert` can restore it while Caddy is still reachable; no other path is snapshotted. To replace the config rather than unload it, use `caddy_load`.
123
126
  - **caddy_config_by_id** — Get/set/delete config by `@id` tag — much easier than navigating deep paths. The `delete` action requires `confirm=true`.
124
- - **caddy_load** — Replace the entire config atomically. Runs on `CADDY_LOAD_TIMEOUT` (55 seconds by default), like every config change. Auto-snapshots the prior config, and keeps that snapshot when the load times out with its outcome unknown. Lists the Caddyfile adapter's warnings, and reports a load that failed as an error even when Caddy answered HTTP 200 — which Caddy 2.11.4 does for a Caddyfile that adapted with warnings ([caddyserver/caddy#7246](https://github.com/caddyserver/caddy/issues/7246)).
125
- - **caddy_revert** — Manage config snapshots for rollback. Actions: `list`, `save`, `apply` (confirm-gated). In-memory, last 10. An `apply` that times out with its outcome unknown keeps the pre-revert config as snapshot [0], which shifts every older snapshot down one index; the error says where the target now sits.
127
+ - **caddy_load** — Replace the entire config atomically. Runs on `CADDY_LOAD_TIMEOUT` (55 seconds by default), like every config change. Auto-snapshots the prior config, and keeps that snapshot when the load times out with its outcome unknown. Lists the Caddyfile adapter's warnings, and reports a load that failed as an error even when Caddy answered HTTP 200 — which Caddy 2.11.4 does for a Caddyfile that adapted with warnings ([caddyserver/caddy#7246](https://github.com/caddyserver/caddy/issues/7246)). `format` is `json` (default) or `caddyfile`; stock Caddy registers only the `caddyfile` adapter, so for any other adapter compiled into a custom build, adapt first with `caddy_adapt` and load the JSON (the Atomic deploy example below).
128
+ - **caddy_revert** — Manage config snapshots for rollback. Actions: `list`, `save`, `apply` (confirm-gated). In-memory, last 10. Auto-captured before `caddy_load`, and before a `caddy_config_delete` or `caddy_config_set` at the config root. An `apply` that times out with its outcome unknown keeps the pre-revert config as snapshot [0], which shifts every older snapshot down one index; the error says where the target now sits.
126
129
 
127
130
  ### Route operations (4)
128
131
 
@@ -133,14 +136,14 @@ Use the same JSON block shown above in any of these.
133
136
 
134
137
  ### TLS & config conversion (2)
135
138
 
136
- - **caddy_tls** — Check or set TLS settings. Actions: `status`, `set_email` (ACME email), `set_acme_ca` (ACME CA URL), `set_acme_profile` (ACME profile, Caddy 2.10+), and the read-only `ech_status` (the Encrypted ClientHello config at `apps/tls/encrypted_client_hello`, Caddy 2.10+). The set actions PATCH first; when `apps/tls` is not set they PUT a minimal config, which also creates any missing parents, so they work on an instance with no config at all. On an existing config they deep-merge into the issuer path and PATCH the result back, preserving siblings (custom certs, `on_demand`, additional policies). Refuses with a shape-specific error if the existing structure is unexpected — never clobbers.
137
- - **caddy_adapt** — Convert a config in any registered adapter format to Caddy JSON without applying it. `caddyfile` (built-in, default) plus any adapter module compiled into your Caddy binary — e.g., `nginx` ([caddy-nginx-adapter](https://github.com/caddyserver/nginx-adapter)), `yaml` ([caddy-yaml](https://github.com/abiosoft/caddy-yaml)). Great for previewing or porting from existing configs.
139
+ - **caddy_tls** — Check or set TLS settings. Actions: `status`, `set_email` (ACME email), `set_acme_ca` (ACME CA URL), `set_acme_profile` (ACME profile, Caddy 2.10+ — experimental upstream: the ACME profiles spec is still a draft and Caddy marks the field subject to change. Caddy accepts any profile name on load, so a name the CA does not advertise fails only at issuance, in Caddy's own logs), and the read-only `ech_status` (the Encrypted ClientHello config at `apps/tls/encrypted_client_hello`, Caddy 2.10+). The set actions PATCH first; when `apps/tls` is not set they PUT a minimal config, which also creates any missing parents, so they work on an instance with no config at all. On an existing config they deep-merge into the issuer path and PATCH the result back, preserving siblings (custom certs, `on_demand`, additional policies). Refuses with a shape-specific error if the existing structure is unexpected — never clobbers.
140
+ - **caddy_adapt** — Convert a config in any registered adapter format to Caddy JSON without applying it. `caddyfile` (built-in, default) plus any adapter module compiled into your Caddy binary — e.g., `nginx` ([caddy-nginx-adapter](https://github.com/caddyserver/nginx-adapter)), `yaml` ([caddy-yaml](https://github.com/abiosoft/caddy-yaml)). Great for previewing or porting from existing configs. One caveat on Caddy 2.11.4 and earlier: a Caddyfile `order` global option is not preview-only. It mutates that Caddy process's directive order, so it carries into later Caddyfile adapts and loads in the same process, and an `order` line that *fails* still removes the directive it names ([caddyserver/caddy#7995](https://github.com/caddyserver/caddy/pull/7995), fixed upstream but unreleased as of 2.11.4).
138
141
 
139
142
  ### Server operations (6)
140
143
 
141
- - **caddy_status** — Connectivity check + config summary (server count, routes, TLS mode).
142
- - **caddy_list_servers** — List all HTTP servers with names, addresses, route counts, and TLS status.
143
- - **caddy_upstreams** — Reverse proxy backend health.
144
+ - **caddy_status** — Connectivity check + config summary (server count, routes, TLS mode). The TLS label replays Caddy's own automatic-HTTPS rule over the stored config instead of guessing from the listen port, so it reads `enabled`, `enabled (no listener gets TLS: all are on the HTTP port)`, `auto (HTTPS)`, `auto (HTTPS: host matchers on a non-HTTP port)`, `mixed (TLS on non-HTTP listeners only)`, `off (HTTP only)`, `off (no host matchers)`, `off (automatic HTTPS disabled)` or `off (empty tls_connection_policies)`. The two qualified `enabled` readings come from Caddy deciding TLS per socket rather than per server (`app.go:535`): connection policies are ignored on the HTTP-port listener, so a server that binds only that port is configured for TLS and serves none of it.
145
+ - **caddy_list_servers** — List all HTTP servers with names, addresses, route counts, and TLS status. Same labels as `caddy_status`, but this tool reads only `apps/http/servers` and so assumes the default `http_port` 80 / `https_port` 443 — on an instance with custom ports, `caddy_status` is the one that gets the label right.
146
+ - **caddy_upstreams** — Reverse proxy backend health, as Caddy's `/reverse_proxy/upstreams` array returned verbatim. On Caddy 2.11.2+ this is **not** the configured upstream list: dynamic upstreams stay listed about 1 h after the dynamic source last returned them (so an address can outlive the config that referenced it), and a backend with requests in flight can appear twice when its resolved address differs from the entry's dial text. The extra copy always shows `fails 0` and repeats `num_requests` — do not sum `num_requests` across entries.
144
147
  - **caddy_metrics** — Prometheus metrics (request counts, durations, connections, TLS handshakes). Optional `filter` (substring match on metric name, keeps `# HELP` / `# TYPE` lines for retained metrics) and `max_lines` (default 500) keep responses compact on busy servers.
145
148
  - **caddy_pki** — CA info and certificate chains (default CA: `local`).
146
149
  - **caddy_stop** — Graceful shutdown. Requires `confirm=true` to prevent accidents.
@@ -151,7 +154,7 @@ Browsable read-only data — MCP clients can fetch these directly without a tool
151
154
 
152
155
  - `caddy://config` — Current full Caddy JSON configuration.
153
156
  - `caddy://servers` — Summary of all configured HTTP servers.
154
- - `caddy://upstreams` — Reverse proxy upstream health status.
157
+ - `caddy://upstreams` — Reverse proxy upstream health status, verbatim. Same 2.11.2+ caveat as `caddy_upstreams`: lingering dynamic upstreams and duplicate in-flight entries; do not sum `num_requests`.
155
158
  - `caddy://metrics` — Prometheus metrics (text exposition format). Capped at the first 500 lines to keep client context bounded; use the `caddy_metrics` tool with `filter` / `max_lines` for filtered or larger output.
156
159
 
157
160
  ## Examples
@@ -223,16 +226,27 @@ Browsable read-only data — MCP clients can fetch these directly without a tool
223
226
  - Make sure Caddy is running. `caddy run` or `systemctl status caddy`.
224
227
  - Check the admin endpoint. Default is `http://localhost:2019`. If Caddy is in Docker, use the container hostname.
225
228
  - Set `CADDY_ADMIN_URL` in your MCP config `env` to match.
229
+ - Over an SSH tunnel, map the **same** port on both ends (`ssh -L 2019:localhost:2019 <host>`) and leave `CADDY_ADMIN_URL` at its default. Caddy checks the `Host` header against its own listen address, so a tunnel on a different local port answers `403 host not allowed: localhost:<port>`.
230
+ - Behind a reverse proxy, add the proxy's `host:port` to the remote Caddy's `admin.origins`. Caddy checks both `Host` and `Origin`, and setting `admin.origins` **replaces** the default `localhost` / `127.0.0.1` / `::1` entries, so list `localhost:2019` too if local tools still need access. A non-loopback or wildcard `admin.listen` — the Docker `http://caddy:2019` above, for instance — does not allow an arbitrary `Host` either, so it needs `admin.origins` set as well.
231
+ - Pointing `CADDY_ADMIN_URL` at Caddy's native remote admin listener (`admin.remote`, default `:2021`) fails before any HTTP is exchanged, because that listener requires a TLS client certificate and caddy-mcp does not present one. It surfaces as this message even though Caddy is running and accepted the connection.
226
232
 
227
233
  **"HTTP 412 Precondition Failed"**
228
234
 
229
235
  - Someone (or something) changed the config between your read and your write.
230
236
  - The cached ETag has been invalidated. Re-read the config and retry.
231
237
 
232
- **"HTTP 403" on /load or /config writes**
238
+ **"HTTP 401" or "HTTP 403" on any request**
239
+
240
+ - Caddy's own checks run on every admin request, reads included, and always answer with a JSON `{"error":...}` body. If you got one, it is Caddy: the `admin.listen` / `admin.origins` allowlists (`host not allowed: ...`, `client is not allowed to access from origin ...`, `required Origin header is missing or invalid` — see the tunnel and proxy bullets above), or, on `admin.remote`, its mTLS identity and permission checks.
241
+ - A **bodiless** 401/403 came from something in front of Caddy — a proxy, a gateway, an SSO layer. `CADDY_API_TOKEN` applies there and only there, so a missing or wrong token is one cause and the proxy's other access rules are another.
242
+ - Caddy's admin API has no bearer-token auth of its own, so setting `CADDY_API_TOKEN` will not clear a 401/403 that carries a Caddy error body.
243
+
244
+ **"directive 'X' is not an ordered HTTP handler"** from `caddy_adapt`, or from `caddy_load` with `format: "caddyfile"`
233
245
 
234
- - You have `admin.listen` or `admin.origins` restrictions set in your Caddy config, or you're missing an `Authorization` header.
235
- - Set `CADDY_API_TOKEN` in your MCP config env if Caddy expects a Bearer token.
246
+ - Two causes, and Caddy's error cannot tell them apart:
247
+ - The directive has no registered order — usually a plugin directive. Add an `order` global option, or wrap it in a `route` block.
248
+ - On Caddy 2.11.4 and earlier, an earlier failed or concurrent Caddyfile adaptation that used `order` in this same Caddy process removed that directive from the process-wide directive order. Restarting Caddy restores the default order ([caddyserver/caddy#7995](https://github.com/caddyserver/caddy/pull/7995), unreleased).
249
+ - The second cause is why a Caddyfile that adapted a minute ago can start failing with no edit to it. Caddy's own advice ("try … using the order global option") fixes the first cause and papers over the second.
236
250
 
237
251
  **`SIGUSR1` / `systemctl reload caddy` stops reloading the Caddyfile**
238
252
 
@@ -244,6 +258,12 @@ Browsable read-only data — MCP clients can fetch these directly without a tool
244
258
  caddy-mcp read-only tools (`caddy_status`, `caddy_list_routes`, `caddy_adapt`)
245
259
  and reload from the file. If caddy-mcp owns the config, apply changes with
246
260
  `caddy_load` instead of `SIGUSR1`.
261
+ - One qualification on Caddy 2.11.4 and earlier: `caddy_adapt` is read-only with
262
+ respect to the config, but not with respect to the adapter. A Caddyfile `order`
263
+ global option changes that process's directive order, and a failed `order` line
264
+ can break later in-process adaptations — which is what a `SIGUSR1` reload and
265
+ `caddy run --watch` do. `caddy reload`, which is what the packaged
266
+ `systemctl reload caddy` runs, adapts in the CLI process and is unaffected.
247
267
 
248
268
  **Windows: MCP server doesn't start**
249
269
 
@@ -252,9 +272,21 @@ Browsable read-only data — MCP clients can fetch these directly without a tool
252
272
  ## Requirements
253
273
 
254
274
  - Node.js 20+
255
- - Caddy 2.x with admin API enabled (default: `localhost:2019`). Verified against
256
- Caddy 2.11.4; the `@id` write path relies on `PATCH` semantics that the live
257
- integration suite pins per release.
275
+ - Caddy 2.11.3 or later, with the admin API enabled (default: `localhost:2019`).
276
+ The latest 2.11.x is recommended; verified against Caddy 2.11.4. Two admin-side
277
+ reasons for that floor:
278
+ - Caddy 2.11.2 and earlier log every admin request's headers at INFO, so if the
279
+ `Authorization` header from `CADDY_API_TOKEN` reaches the admin listener, the
280
+ token is written to Caddy's log in plain text
281
+ ([caddyserver/caddy#7578](https://github.com/caddyserver/caddy/pull/7578)).
282
+ - Caddy 2.11.1 and earlier accept a duplicate `@id` silently. A racing
283
+ `caddy_reverse_proxy` create, or a `caddy_config_by_id` set with
284
+ `mode: "insert"` on a route id, leaves two elements sharing one `@id`, and
285
+ `/id/` resolves to only one of them.
286
+
287
+ Older 2.x mostly works, but the `If-Match` (ETag) concurrency guard needs Caddy
288
+ 2.5.2 or later — before that Caddy ignores the header silently. The `@id` write
289
+ path relies on `PATCH` semantics that the live integration suite pins per release.
258
290
 
259
291
  ## Contributing
260
292
 
@@ -265,7 +297,7 @@ npm install
265
297
  npm run lint # Biome check
266
298
  npm run lint:fix # Auto-fix
267
299
  npm run build # tsup bundle
268
- npm test # Vitest (636 unit tests, +39 POSIX-only unix-socket and launcher tests; +32 live-Caddy integration tests gated by CADDY_MCP_INTEGRATION=1)
300
+ npm test # Vitest (760 unit tests, +39 POSIX-only unix-socket and launcher tests; +37 live-Caddy integration tests gated by CADDY_MCP_INTEGRATION=1)
269
301
  npm run typecheck # tsc --noEmit
270
302
  ```
271
303
 
@@ -275,4 +307,4 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for the full workflow, including release
275
307
 
276
308
  MIT
277
309
 
278
- [![Follow @TokenLimitNews on X](https://img.shields.io/badge/follow-%40TokenLimitNews-000000?logo=x&logoColor=white)](https://x.com/TokenLimitNews)
310
+ [![Follow @YawLabs on X](https://img.shields.io/badge/follow-%40YawLabs-000000?logo=x&logoColor=white)](https://x.com/YawLabs)
package/dist/api.d.ts CHANGED
@@ -25,6 +25,37 @@ export interface ApiResponse<T = any> {
25
25
  */
26
26
  outcomeUnknown?: boolean;
27
27
  }
28
+ /**
29
+ * Does this config path address the ROOT -- the whole configuration?
30
+ *
31
+ * A write there is a different operation wearing the same request shape: PATCH
32
+ * and POST replace the entire config (Caddy sets `rawCfg["config"]` to the body,
33
+ * admin.go:1279 and :1296 at v2.11.4 -- exactly what `POST /load` does,
34
+ * caddy.go:136), and DELETE unloads it. Every tool that takes a config path has
35
+ * to know, because Caddy itself never distinguishes the root from a leaf.
36
+ *
37
+ * Root spellings, after normalizePath above has eaten one leading "/" and one
38
+ * "config/": nothing ("", "/", "config", "/config/"), only slashes ("//",
39
+ * "config//"), and any of those followed by a single "..." segment ("...",
40
+ * "/...", "config/...", "/config/.../"). The "..." form is Caddy's bulk-append
41
+ * spelling, and it is stripped BEFORE the method switch (admin.go:1196-1199),
42
+ * for every method, so `/config/...` lands on the same root branch as
43
+ * `/config/`. rejectTraversal below lets "..." through on purpose -- a trailing
44
+ * one under a real array is how `POST .../routes/...` appends in bulk -- so the
45
+ * root test has to absorb it here. Only ONE trailing "..." is stripped by Caddy:
46
+ * ".../..." writes a key literally named "...", which is a leaf.
47
+ *
48
+ * Verified against Caddy 2.11.4: PATCH and POST `/config/...` with an object
49
+ * body replaced the whole config, and DELETE `/config/...` unloaded it.
50
+ *
51
+ * Callers that branch on this must SEND the canonical "" rather than the
52
+ * caller's spelling (see caddy_config_delete in tools/config.ts): "//" would be
53
+ * encoded to `/config//`, which Go's ServeMux answers with a redirect to
54
+ * `/config/` instead of dispatching, so the ETag cached under "/config/" is
55
+ * never found and the request goes out with no If-Match; over a unix socket
56
+ * node:http does not follow the redirect at all.
57
+ */
58
+ export declare function isRootConfigPath(path: string): boolean;
28
59
  /**
29
60
  * Caddy's "a segment of this config path does not exist" failure.
30
61
  *
package/dist/index.js CHANGED
@@ -24,6 +24,54 @@ function setEtag(path, etag) {
24
24
  }
25
25
  etagCache.set(path, etag);
26
26
  }
27
+ var GO_WHITESPACE = /* @__PURE__ */ new Set([
28
+ 9,
29
+ 10,
30
+ 11,
31
+ 12,
32
+ 13,
33
+ 32,
34
+ 133,
35
+ 160,
36
+ 5760,
37
+ 8192,
38
+ 8193,
39
+ 8194,
40
+ 8195,
41
+ 8196,
42
+ 8197,
43
+ 8198,
44
+ 8199,
45
+ 8200,
46
+ 8201,
47
+ 8202,
48
+ 8232,
49
+ 8233,
50
+ 8239,
51
+ 8287,
52
+ 12288
53
+ ]);
54
+ function goFields(text) {
55
+ const fields = [];
56
+ let current = "";
57
+ for (const ch of text) {
58
+ if (GO_WHITESPACE.has(ch.codePointAt(0))) {
59
+ if (current) fields.push(current);
60
+ current = "";
61
+ } else {
62
+ current += ch;
63
+ }
64
+ }
65
+ if (current) fields.push(current);
66
+ return fields;
67
+ }
68
+ function isEchoableEtag(etag) {
69
+ const decoded = Buffer.from(etag, "latin1").toString("utf8");
70
+ if (decoded.length < 2 || !decoded.startsWith('"') || !decoded.endsWith('"')) return false;
71
+ const inner = decoded.slice(1, -1);
72
+ const fields = goFields(inner);
73
+ return fields.length === 2 && fields.join(" ") === inner;
74
+ }
27
75
  function isAncestorOf(ancestor, descendant) {
28
76
  const base = ancestor.endsWith("/") ? ancestor.slice(0, -1) : ancestor;
29
77
  return descendant.startsWith(`${base}/`);
@@ -90,15 +138,18 @@ function getHeaders(contentType, overUnixSocket = false) {
90
138
  function normalizePath(path) {
91
139
  return path.replace(/^\/?(config(\/|$))?/, "");
92
140
  }
141
+ function isRootConfigPath(path) {
142
+ return /^\/*(\.\.\.\/*)?$/.test(normalizePath(path));
143
+ }
93
144
  function encodePathSegments(path) {
94
145
  return path.split("/").map((segment) => encodeURIComponent(segment)).join("/");
95
146
  }
96
147
  function rejectTraversal(path) {
97
- if (/(^|\/)\.\.(\/|$)/.test(path)) {
148
+ if (/(^|\/)\.\.?(\/|$)/.test(path)) {
98
149
  return {
99
150
  ok: false,
100
151
  status: 0,
101
- error: `Invalid path "${path}": '..' segments are not allowed`
152
+ error: `Invalid path "${path}": '.' and '..' segments are not allowed`
102
153
  };
103
154
  }
104
155
  return null;
@@ -115,8 +166,8 @@ function isMissingConfigPath(res) {
115
166
  if (res.ok) return false;
116
167
  return (res.error ?? "").toLowerCase().includes("invalid traversal path");
117
168
  }
118
- var ARRAY_INDEX_TAIL_RE = /\/\d+\/*$/;
119
- var BARE_ID_RE = /^\/id\/[^/]+\/*$/;
169
+ var ARRAY_INDEX_TAIL_RE = /\/\d+(\/+\.\.\.)?\/*$/;
170
+ var BARE_ID_RE = /^\/id\/[^/]+(\/+\.\.\.)?\/*$/;
120
171
  function isConfigChange(method, path) {
121
172
  if (method === "GET") return false;
122
173
  return path === "/load" || path.startsWith("/config/") || path.startsWith("/id/");
@@ -350,7 +401,8 @@ async function sendOnce(transport, method, path, body, contentType, rawStringBod
350
401
  const text = res.text;
351
402
  const etag = res.etag;
352
403
  if (method === "GET" && etag && isConfigPath) {
353
- setEtag(path, etag);
404
+ if (isEchoableEtag(etag)) setEtag(path, etag);
405
+ else etagCache.delete(path);
354
406
  }
355
407
  if (isWrite && res.ok && isConfigPath) {
356
408
  invalidateRelated(path);
@@ -573,15 +625,96 @@ function formatResult(res) {
573
625
  }
574
626
 
575
627
  // src/tools/operational.ts
576
- var HTTPS_PORT_RE = /:443(?:\D|$)/;
577
- function describeServer(rawValue) {
628
+ var DEFAULT_HTTP_PORT = 80;
629
+ var DEFAULT_HTTPS_PORT = 443;
630
+ function appPort(value, fallback) {
631
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 65535 ? value : fallback;
632
+ }
633
+ function splitPort(hostport) {
634
+ const i = hostport.lastIndexOf(":");
635
+ if (i < 0) return void 0;
636
+ if (hostport.startsWith("[")) {
637
+ const end = hostport.indexOf("]");
638
+ if (end < 0 || end + 1 !== i) return void 0;
639
+ if (hostport.slice(1).includes("[") || hostport.slice(end + 1).includes("]")) return void 0;
640
+ } else {
641
+ if (hostport.slice(0, i).includes(":")) return void 0;
642
+ if (hostport.includes("[") || hostport.includes("]")) return void 0;
643
+ }
644
+ return hostport.slice(i + 1);
645
+ }
646
+ function parseListenPortRange(entry) {
647
+ let rest = entry;
648
+ const slash = entry.indexOf("/");
649
+ if (slash >= 0) {
650
+ const network = entry.slice(0, slash).trim().toLowerCase();
651
+ rest = entry.slice(slash + 1);
652
+ if (network.startsWith("unix") || network.startsWith("fd")) return { start: 0, end: 0 };
653
+ }
654
+ const port = splitPort(rest);
655
+ if (port === void 0 || port === "") return { start: 0, end: 0 };
656
+ const dash = port.indexOf("-");
657
+ const start = parseUint16(dash < 0 ? port : port.slice(0, dash));
658
+ const end = parseUint16(dash < 0 ? port : port.slice(dash + 1));
659
+ if (start === void 0 || end === void 0 || end < start) return void 0;
660
+ return { start, end };
661
+ }
662
+ function parseUint16(s) {
663
+ if (!/^[0-9]+$/.test(s)) return void 0;
664
+ const n = Number(s);
665
+ return n <= 65535 ? n : void 0;
666
+ }
667
+ function hasQualifyingHost(routes, skip) {
668
+ for (const route of routes) {
669
+ if (!route || typeof route !== "object") continue;
670
+ const matcherSets = route.match;
671
+ if (!Array.isArray(matcherSets)) continue;
672
+ for (const set of matcherSets) {
673
+ if (!set || typeof set !== "object") continue;
674
+ const hosts = set.host;
675
+ if (!Array.isArray(hosts)) continue;
676
+ for (const host of hosts) {
677
+ if (typeof host === "string" && !skip.has(host)) return true;
678
+ }
679
+ }
680
+ }
681
+ return false;
682
+ }
683
+ function describeServer(rawValue, httpPort = DEFAULT_HTTP_PORT, httpsPort = DEFAULT_HTTPS_PORT) {
578
684
  const raw = rawValue !== null && typeof rawValue === "object" && !Array.isArray(rawValue) ? rawValue : {};
579
685
  const listen = Array.isArray(raw.listen) ? raw.listen : [];
580
686
  const routes = Array.isArray(raw.routes) ? raw.routes : [];
687
+ const ranges = [];
688
+ for (const entry of listen) {
689
+ if (typeof entry !== "string") continue;
690
+ const range = parseListenPortRange(entry);
691
+ if (range) ranges.push(range);
692
+ }
693
+ const usesAnyPortOtherThan = (port) => ranges.some((r) => port > r.end || port < r.start);
694
+ const bindsPort = (port) => ranges.some((r) => r.start <= port && port <= r.end);
695
+ const autoHttps = raw.automatic_https !== null && typeof raw.automatic_https === "object" && !Array.isArray(raw.automatic_https) ? raw.automatic_https : {};
696
+ const skip = new Set(
697
+ Array.isArray(autoHttps.skip) ? autoHttps.skip.filter((s) => typeof s === "string") : []
698
+ );
699
+ const allSocketsOnHttpPort = (port) => ranges.length > 0 && ranges.every((r) => r.start === port && r.end === port);
700
+ const perListener = (label) => allSocketsOnHttpPort(httpPort) ? "enabled (no listener gets TLS: all are on the HTTP port)" : bindsPort(httpPort) ? "mixed (TLS on non-HTTP listeners only)" : label;
581
701
  const tlsPolicies = raw.tls_connection_policies;
582
- const hasExplicitTls = Array.isArray(tlsPolicies) ? tlsPolicies.length > 0 : !!tlsPolicies;
583
- const listensHttps = listen.some((l) => typeof l === "string" && HTTPS_PORT_RE.test(l));
584
- const tls = hasExplicitTls ? "enabled" : listensHttps ? "auto (HTTPS)" : "off (HTTP only)";
702
+ let tls;
703
+ if (Array.isArray(tlsPolicies) && tlsPolicies.length === 0) {
704
+ tls = "off (empty tls_connection_policies)";
705
+ } else if (tlsPolicies) {
706
+ tls = perListener("enabled");
707
+ } else if (autoHttps.disable === true) {
708
+ tls = "off (automatic HTTPS disabled)";
709
+ } else if (!usesAnyPortOtherThan(httpPort)) {
710
+ tls = "off (HTTP only)";
711
+ } else if (!usesAnyPortOtherThan(httpsPort)) {
712
+ tls = perListener("auto (HTTPS)");
713
+ } else if (hasQualifyingHost(routes, skip)) {
714
+ tls = perListener("auto (HTTPS: host matchers on a non-HTTP port)");
715
+ } else {
716
+ tls = "off (no host matchers)";
717
+ }
585
718
  const listenStr = listen.length > 0 ? listen.map(String).join(", ") : "default";
586
719
  return `${routes.length} route(s), listen: ${listenStr}, TLS: ${tls}`;
587
720
  }
@@ -640,14 +773,17 @@ function registerOperationalTools(server) {
640
773
  const res = await configGet();
641
774
  if (!res.ok) return formatResult(res);
642
775
  const config = res.data ?? {};
643
- const servers = config.apps?.http?.servers ?? {};
776
+ const httpApp = config.apps?.http;
777
+ const servers = httpApp?.servers ?? {};
644
778
  const serverNames = Object.keys(servers);
779
+ const httpPort = appPort(httpApp?.http_port, DEFAULT_HTTP_PORT);
780
+ const httpsPort = appPort(httpApp?.https_port, DEFAULT_HTTPS_PORT);
645
781
  const lines = ["Caddy is running", ""];
646
782
  if (serverNames.length === 0) {
647
783
  lines.push("No HTTP servers configured");
648
784
  } else {
649
785
  for (const name of serverNames) {
650
- lines.push(`Server "${name}": ${describeServer(servers[name])}`);
786
+ lines.push(`Server "${name}": ${describeServer(servers[name], httpPort, httpsPort)}`);
651
787
  }
652
788
  }
653
789
  const email = findAcmeEmail(config.apps?.tls?.automation?.policies);
@@ -681,7 +817,7 @@ ${lines.join("\n")}` }]
681
817
  );
682
818
  server.tool(
683
819
  "caddy_upstreams",
684
- "Get the current health status of all reverse proxy upstreams. Shows address, active requests, and failure counts.",
820
+ "Caddy's /reverse_proxy/upstreams array (address, num_requests, fails), returned verbatim. On Caddy 2.11.2+ it is not the configured upstream list. Dynamic-upstream backends stay listed about 1 h (up to ~65 min) after the dynamic source last returned them, even after a config change removes them, so an address may appear that no current config references. A backend with requests in flight can appear twice when its resolved address differs from the entry's text (dynamic upstreams, tcp/ or unix// dials, placeholder dials). That extra copy always shows fails 0 and repeats num_requests, so do not sum num_requests across entries.",
685
821
  {},
686
822
  { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
687
823
  async () => formatResult(await getUpstreams())
@@ -755,7 +891,9 @@ function registerResources(server) {
755
891
  server.resource(
756
892
  "caddy-upstreams",
757
893
  "caddy://upstreams",
758
- { description: "Reverse proxy upstream health status" },
894
+ {
895
+ description: "Reverse proxy upstream health: Caddy's /reverse_proxy/upstreams array, returned verbatim. On Caddy 2.11.2+ it is not the configured upstream list -- dynamic upstreams stay listed about 1 h after the dynamic source last returned them (so an address can outlive the config that referenced it), and a backend with requests in flight can appear twice when its resolved address differs from the entry's text. The extra copy always shows fails 0 and repeats num_requests, so do not sum num_requests. See the caddy_upstreams tool for the full caveat."
896
+ },
759
897
  async () => {
760
898
  const res = await getUpstreams();
761
899
  return {
@@ -831,7 +969,7 @@ function formatWarning2(w) {
831
969
  function registerAdaptTools(server) {
832
970
  server.tool(
833
971
  "caddy_adapt",
834
- "Convert a config in any registered adapter format to Caddy JSON without loading it. Useful for previewing what a Caddyfile produces, or for porting from nginx/yaml configs when Caddy is built with the matching adapter module ('caddyfile' is built-in; 'nginx', 'yaml', etc. require their adapter modules to be compiled into the Caddy binary). Returns the adapted JSON and any warnings separately.",
972
+ `Convert a config in any registered adapter format to Caddy JSON without loading it. Useful for previewing what a Caddyfile produces, or for porting from nginx/yaml configs when Caddy is built with the matching adapter module ('caddyfile' is built-in; 'nginx', 'yaml', etc. require their adapter modules to be compiled into the Caddy binary). Returns the adapted JSON and any warnings separately. One exception to 'without loading it': on Caddy <= 2.11.4 a Caddyfile 'order' global option is not preview-only. It mutates that Caddy process's directive order, so it carries into every later Caddyfile adapt or load there, and an 'order' line that FAILS (unknown target, bad positional, extra arg) still removes the directive it names -- later Caddyfiles using that directive then fail with "directive 'X' is not an ordered HTTP handler" until another 'order' line re-places it or Caddy restarts. Fixed upstream in caddyserver/caddy#7995, unreleased as of v2.11.4.`,
835
973
  {
836
974
  config: z2.string().describe("The raw config text (e.g., Caddyfile contents, nginx.conf, yaml)"),
837
975
  adapter: z2.string().regex(/^[a-z0-9_-]+$/, "Adapter must be lowercase alphanumeric, hyphens, or underscores").max(64).optional().default("caddyfile").describe(
@@ -941,6 +1079,43 @@ function getSnapshot(index) {
941
1079
  }
942
1080
 
943
1081
  // src/tools/config.ts
1082
+ function adminListenOf(config) {
1083
+ if (!isSnapshotableConfig(config)) return void 0;
1084
+ const adm = config.admin;
1085
+ if (adm === null || typeof adm !== "object" || Array.isArray(adm)) return void 0;
1086
+ const listen = adm.listen;
1087
+ return typeof listen === "string" && listen !== "" ? listen : void 0;
1088
+ }
1089
+ function adminDisabledIn(config) {
1090
+ if (!isSnapshotableConfig(config)) return false;
1091
+ const adm = config.admin;
1092
+ return adm !== null && typeof adm === "object" && !Array.isArray(adm) && adm.disabled === true;
1093
+ }
1094
+ function priorConfigNote(kept, current, trigger) {
1095
+ if (kept) {
1096
+ return ` The prior config was saved as snapshot [0] (trigger=${trigger}): caddy_revert { action: "apply", index: 0, confirm: true } restores it.`;
1097
+ }
1098
+ return current.ok ? " Warning: the prior config was empty or not a JSON object, so no snapshot was captured -- there was nothing to restore." : " Warning: the prior config could not be read, so no snapshot was captured and this change cannot be reverted.";
1099
+ }
1100
+ function rootWriteAdminNote(current, value) {
1101
+ if (adminDisabledIn(value)) {
1102
+ return " The new config sets admin.disabled, so Caddy no longer answers on ANY admin address: neither this server nor caddy_revert can reach it until Caddy is restarted with a config that does not disable the admin endpoint.";
1103
+ }
1104
+ const adminUrl = process.env.CADDY_ADMIN_URL || "http://localhost:2019";
1105
+ const before = current.ok ? adminListenOf(current.data) : void 0;
1106
+ const after = adminListenOf(value);
1107
+ if (before !== void 0 && after !== before) {
1108
+ return ` The replaced config set admin.listen to "${before}"` + (after !== void 0 ? ` and the new one sets it to "${after}".` : " and the new one sets none.") + ` Unless those resolve to the same address, the admin endpoint has moved (to the new value, or back to the default: localhost:2019 unless $CADDY_ADMIN is set in Caddy's environment) and CADDY_ADMIN_URL (${adminUrl}) may no longer reach it.`;
1109
+ }
1110
+ if (before === void 0 && after !== void 0) {
1111
+ return ` The new config sets admin.listen to "${after}". If that is not the address Caddy was already on, the admin endpoint has moved there and CADDY_ADMIN_URL (${adminUrl}) may no longer reach it.`;
1112
+ }
1113
+ if (!current.ok) return unreadablePriorAdminNote("replaced");
1114
+ return "";
1115
+ }
1116
+ function unreadablePriorAdminNote(verb) {
1117
+ return ` The ${verb} config could not be read, so this server cannot tell whether it set an admin.listen of its own. If it did, and that was not Caddy's default admin address, the endpoint has moved back to the default (localhost:2019, unless $CADDY_ADMIN is set in Caddy's environment) and CADDY_ADMIN_URL (${process.env.CADDY_ADMIN_URL || "http://localhost:2019"}) may no longer reach it.`;
1118
+ }
944
1119
  function registerConfigTools(server) {
945
1120
  server.tool(
946
1121
  "caddy_config_get",
@@ -951,23 +1126,73 @@ function registerConfigTools(server) {
951
1126
  );
952
1127
  server.tool(
953
1128
  "caddy_config_set",
954
- "Write config at a JSON path. Mode 'overwrite' (default) replaces existing values (PATCH) \u2014 safe and idempotent. Mode 'append' (POST) adds to an array \u2014 NOT idempotent: calling twice with the same route duplicates it \u2014 but on a non-array key it REPLACES whatever is there, and it cannot create missing parent objects. Mode 'insert' (PUT) inserts at an array index (useful for route ordering), or strictly creates an object key together with any missing parents and fails with 409 if the key already exists \u2014 the safe way to create a server or app, including on an instance with no config at all.",
1129
+ "Write config at a JSON path. Mode 'overwrite' (default) replaces the value at the path (PATCH) \u2014 idempotent, but it replaces the WHOLE subtree there: writing [] to '.../routes' drops every route. Mode 'append' (POST) adds to an array \u2014 NOT idempotent: calling twice with the same route duplicates it \u2014 but on a non-array key it REPLACES whatever is there, and it cannot create missing parent objects. Mode 'insert' (PUT) inserts at an array index (useful for route ordering), or strictly creates an object key together with any missing parents and fails with 409 if the key already exists \u2014 the safe way to create a server or app, including on an instance with no config at all. Any path that addresses the config ROOT ('', '/', 'config', '/config/', a slash-only variant, or any of those followed by a lone '...' segment) addresses the ENTIRE config and requires confirm=true: 'overwrite' and 'append' there REPLACE the whole configuration with `value` \u2014 Caddy runs it exactly as caddy_load would \u2014 so every app, server and route not in `value` is discarded, and so is the 'admin' block unless `value` carries one. Caddy then re-binds its admin endpoint to the new config's admin.listen, or to its default address (localhost:2019, or $CADDY_ADMIN in Caddy's environment) when it sets none, or to no address at all when it sets admin.disabled; if CADDY_ADMIN_URL points anywhere else, neither this server nor caddy_revert can reach Caddy afterwards. A root write is snapshotted first, so caddy_revert can restore it while Caddy is still reachable; no other path is snapshotted. 'insert' at the root only succeeds after a root caddy_config_delete (Caddy answers 409 on any other instance, including one started with no config), and 'overwrite' is the reverse: after a root caddy_config_delete it answers 404 until 'append', 'insert' or caddy_load re-creates the config. To replace the whole config deliberately, caddy_load does the same thing behind the same gate and also accepts a Caddyfile.",
955
1130
  {
956
1131
  path: z3.string().describe("Config path to write to (e.g., 'apps/http/servers/srv0/routes')"),
957
1132
  value: z3.any().describe("The JSON value to set at the path"),
958
1133
  mode: z3.enum(["append", "overwrite", "insert"]).optional().default("overwrite").describe(
959
1134
  "'overwrite' = PATCH (replace existing, default, idempotent; 404 if the key does not exist), 'append' = POST (appends to arrays, NOT idempotent; REPLACES an existing non-array key; cannot create missing parents), 'insert' = PUT (inserts at an array index, or strictly creates an object key and any missing parents; 409 if the key exists)"
1135
+ ),
1136
+ confirm: z3.boolean().optional().default(false).describe(
1137
+ "Must be true when `path` addresses the config root ('', '/', 'config', '/config/', slash-only variants, or a lone '...' segment): that write replaces the ENTIRE config (safety). Ignored for every other path."
960
1138
  )
961
1139
  },
962
- { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
963
- async ({ path, value, mode }) => {
964
- const res = mode === "overwrite" ? await configPatch(path, value) : mode === "insert" ? await configPut(path, value) : await configPost(path, value);
965
- return formatResult(res);
1140
+ // destructiveHint is TRUE because the hint covers the whole tool and a host
1141
+ // gates on it before it can see the path or the mode: the default mode is a
1142
+ // PATCH that replaces whatever subtree the path names -- a route list, a
1143
+ // server, all of `apps` -- and at the root it replaces the entire config
1144
+ // (below). MCP defines destructiveHint:false as "only additive updates".
1145
+ // Appending to an array or strictly creating a key is additive; the
1146
+ // default mode is not, and neither is 'append' on a non-array key, which
1147
+ // replaces it. idempotentHint stays false for 'append', which is a POST: a
1148
+ // repeated call appends a second copy.
1149
+ { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
1150
+ async ({ path, value, mode, confirm }) => {
1151
+ const write = (p) => mode === "overwrite" ? configPatch(p, value) : mode === "insert" ? configPut(p, value) : configPost(p, value);
1152
+ if (!isRootConfigPath(path)) return formatResult(await write(path));
1153
+ if (!confirm) {
1154
+ return {
1155
+ isError: true,
1156
+ content: [
1157
+ {
1158
+ type: "text",
1159
+ text: `Refusing to write the ENTIRE config without confirm=true. The path "${path}" addresses the config root, so this call REPLACES the whole configuration with \`value\` ('overwrite' and 'append' both do, and Caddy runs it exactly as caddy_load would; after a root caddy_config_delete 'overwrite' answers 404 instead, while 'insert' succeeds only then and answers 409 otherwise): every app, server and route not in \`value\` is discarded, and so is the 'admin' block unless \`value\` carries one. Caddy then re-binds its admin endpoint to the new config's admin.listen, or to its default address (localhost:2019, or $CADDY_ADMIN in Caddy's environment) when it sets none, or to no address at all when it sets admin.disabled; and if CADDY_ADMIN_URL points anywhere else neither this server nor caddy_revert can reach Caddy afterwards. The current config is snapshotted first, so caddy_revert can restore it while Caddy is still reachable. To change one part of the config, pass its path instead (e.g. 'apps/http/servers/srv0'); to replace all of it deliberately, caddy_load does the same behind the same gate. Re-run with confirm:true to proceed.`
1160
+ }
1161
+ ]
1162
+ };
1163
+ }
1164
+ const current = await configGet();
1165
+ const res = await write("");
1166
+ const kept = (res.ok || res.outcomeUnknown === true) && current.ok && isSnapshotableConfig(current.data);
1167
+ if (kept) saveSnapshot(current.data, "caddy_config_set");
1168
+ const adminNote = rootWriteAdminNote(current, value);
1169
+ if (!res.ok) {
1170
+ if (res.outcomeUnknown && (kept || adminNote)) {
1171
+ const snapshotPart = kept ? `The pre-write config was kept anyway, as snapshot [0] (trigger=caddy_config_set): if this write did apply, caddy_revert { action: "apply", index: 0, confirm: true } restores what it replaced, as long as this server can still reach Caddy's admin endpoint.` : "";
1172
+ const adminPart = adminNote ? `If the write applied:${adminNote}` : "";
1173
+ const tail = kept ? "If it did not apply, that snapshot is simply the config read just before it was sent." : "";
1174
+ return formatResult({
1175
+ ...res,
1176
+ error: `${res.error}
1177
+ ${[snapshotPart, adminPart, tail].filter(Boolean).join(" ")}`
1178
+ });
1179
+ }
1180
+ return formatResult(res);
1181
+ }
1182
+ const note = priorConfigNote(kept, current, "caddy_config_set");
1183
+ return {
1184
+ content: [
1185
+ {
1186
+ type: "text",
1187
+ text: `Replaced the entire config (every app and server, and the 'admin' block).${note}${adminNote}`
1188
+ }
1189
+ ]
1190
+ };
966
1191
  }
967
1192
  );
968
1193
  server.tool(
969
1194
  "caddy_config_delete",
970
- "Delete config at a JSON path. Removes the config node at the specified path. Deleting a parent node also deletes every descendant -- e.g. deleting 'apps/http/servers/srv0' removes that server and all of its routes. Requires confirm=true.",
1195
+ "Delete config at a JSON path. Removes the config node at the specified path. Deleting a parent node also deletes every descendant -- e.g. deleting 'apps/http/servers/srv0' removes that server and all of its routes. Requires confirm=true. Any path that addresses the config ROOT ('', '/', 'config', '/config/', slash-only variants of those, or any of those followed by a lone '...' segment) addresses the ENTIRE config and unloads it: every app and server goes, and so does the 'admin' block, after which Caddy re-binds its admin endpoint to its default address (localhost:2019, or $CADDY_ADMIN in Caddy's environment). If CADDY_ADMIN_URL points anywhere else, neither this server nor caddy_revert can reach Caddy afterwards. A root delete is snapshotted first, so caddy_revert can restore it while Caddy is still reachable; no other path is snapshotted. To REPLACE the config rather than unload it, use caddy_load.",
971
1196
  {
972
1197
  path: z3.string().describe("Config path to delete (e.g., 'apps/http/servers/srv0/routes/0')"),
973
1198
  confirm: z3.boolean().optional().default(false).describe("Must be true to actually delete the config node (safety)")
@@ -978,22 +1203,50 @@ function registerConfigTools(server) {
978
1203
  // array after a delete, so repeating that call removes a DIFFERENT route each
979
1204
  // time. caddy_remove_route carries the same correction for the byte-identical
980
1205
  // underlying request; the two must agree. Nothing here is auto-recoverable
981
- // either: only caddy_load captures a snapshot, so a spurious repeat cannot be
982
- // undone with caddy_revert.
1206
+ // either: apart from a root delete (below), only whole-config changes
1207
+ // capture a snapshot -- caddy_load, a caddy_revert apply, and a root
1208
+ // caddy_config_set -- so a spurious repeat cannot be undone with
1209
+ // caddy_revert.
983
1210
  { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
984
1211
  async ({ path, confirm }) => {
1212
+ const root = isRootConfigPath(path);
985
1213
  if (!confirm) {
986
1214
  return {
987
1215
  isError: true,
988
1216
  content: [
989
1217
  {
990
1218
  type: "text",
991
- text: `Refusing to delete "${path}" without confirm=true. Deleting a parent path also removes all descendants. Re-run with confirm:true to proceed.`
1219
+ text: root ? `Refusing to delete the ENTIRE config without confirm=true. The path "${path}" addresses the config root, so this unloads every app and server, and the 'admin' block with them: Caddy then re-binds its admin endpoint to its default address (localhost:2019, or $CADDY_ADMIN in Caddy's environment), and if CADDY_ADMIN_URL points anywhere else neither this server nor caddy_revert can reach Caddy afterwards. The current config is snapshotted first, so caddy_revert can restore it while Caddy is still reachable. To REPLACE the config rather than unload it, use caddy_load. Re-run with confirm:true to proceed.` : `Refusing to delete "${path}" without confirm=true. Deleting a parent path also removes all descendants. Re-run with confirm:true to proceed.`
992
1220
  }
993
1221
  ]
994
1222
  };
995
1223
  }
996
- return formatResult(await configDelete(path));
1224
+ if (!root) return formatResult(await configDelete(path));
1225
+ const current = await configGet();
1226
+ const res = await configDelete("");
1227
+ const kept = (res.ok || res.outcomeUnknown === true) && current.ok && isSnapshotableConfig(current.data);
1228
+ if (kept) saveSnapshot(current.data, "caddy_config_delete");
1229
+ if (!res.ok) {
1230
+ if (res.outcomeUnknown && kept) {
1231
+ return formatResult({
1232
+ ...res,
1233
+ error: `${res.error}
1234
+ The pre-delete config was kept anyway, as snapshot [0] (trigger=caddy_config_delete): if this delete did apply, caddy_revert { action: "apply", index: 0, confirm: true } restores what it unloaded -- as long as this server can still reach Caddy's admin endpoint, which moves back to Caddy's default address when the deleted config set an admin.listen of its own. If the delete did not apply, that snapshot is simply the config read just before it was sent.`
1235
+ });
1236
+ }
1237
+ return formatResult(res);
1238
+ }
1239
+ const note = priorConfigNote(kept, current, "caddy_config_delete");
1240
+ const listen = kept ? adminListenOf(current.data) : void 0;
1241
+ const adminNote = listen !== void 0 ? ` The unloaded config set admin.listen to "${listen}". If that was not already Caddy's default admin address, the endpoint has moved back to the default (localhost:2019, unless $CADDY_ADMIN is set in Caddy's environment) and CADDY_ADMIN_URL (${process.env.CADDY_ADMIN_URL || "http://localhost:2019"}) may no longer reach it.` : current.ok ? "" : unreadablePriorAdminNote("unloaded");
1242
+ return {
1243
+ content: [
1244
+ {
1245
+ type: "text",
1246
+ text: `Unloaded the entire config (every app and server, and the 'admin' block).${note}${adminNote}`
1247
+ }
1248
+ ]
1249
+ };
997
1250
  }
998
1251
  );
999
1252
  server.tool(
@@ -1034,7 +1287,7 @@ The pre-load config was kept anyway, as snapshot [0] (trigger=caddy_load): if th
1034
1287
  );
1035
1288
  server.tool(
1036
1289
  "caddy_revert",
1037
- "Manage config snapshots for rollback. Snapshots are auto-captured before caddy_load (last 10). By default they live in memory only and are LOST when this server restarts -- set CADDY_MCP_SNAPSHOT_DIR to a writable directory to persist them across restarts (they contain full Caddy configs, so pick the location deliberately). Actions: 'list' shows snapshots with timestamps, 'save' manually captures the current config, 'apply' restores a snapshot (requires confirm=true).",
1290
+ "Manage config snapshots for rollback. Snapshots are auto-captured before caddy_load, and before a caddy_config_delete or caddy_config_set at the config root (any path that addresses the whole config); no other delete or set is snapshotted. Last 10. By default they live in memory only and are LOST when this server restarts -- set CADDY_MCP_SNAPSHOT_DIR to a writable directory to persist them across restarts (they contain full Caddy configs, so pick the location deliberately). Actions: 'list' shows snapshots with timestamps, 'save' manually captures the current config, 'apply' restores a snapshot (requires confirm=true).",
1038
1291
  {
1039
1292
  action: z3.enum(["list", "save", "apply"]).describe("Action to perform"),
1040
1293
  index: z3.number().int().nonnegative().optional().default(0).describe("Snapshot index for 'apply' (0 = most recent, default)"),
@@ -1821,7 +2074,7 @@ function registerTlsTools(server) {
1821
2074
  email: z5.string().optional().describe("ACME email address (for 'set_email' action)"),
1822
2075
  ca: z5.string().optional().describe("ACME CA URL (for 'set_acme_ca' action)"),
1823
2076
  profile: z5.string().optional().describe(
1824
- "ACME profile name (for 'set_acme_profile'). Requires Caddy 2.10+ and a CA that offers profiles; Let's Encrypt uses 'shortlived' for 6-day certificates. Valid names are defined by the CA, not by Caddy."
2077
+ "ACME profile name (for 'set_acme_profile'). Requires Caddy 2.10+ and a CA that offers profiles; Let's Encrypt uses 'shortlived' for 6-day certificates. Valid names are defined by the CA, not by Caddy. EXPERIMENTAL upstream (the ACME profiles spec is still a draft; Caddy marks the field 'subject to change' and may rename or drop it). Caddy accepts any name on load, so a success here does not mean the CA offers it: if this issuer's CA does not advertise the name, every order from this issuer fails at issuance time, reported only in Caddy's own logs. Caddy then either falls through to the next issuer in the policy, which issues WITHOUT the profile, or -- when this is the policy's only issuer, which is the shape this tool creates -- keeps retrying and issues no certificate at all."
1825
2078
  )
1826
2079
  },
1827
2080
  { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
package/dist/server.js CHANGED
@@ -22,6 +22,54 @@ function setEtag(path, etag) {
22
22
  }
23
23
  etagCache.set(path, etag);
24
24
  }
25
+ var GO_WHITESPACE = /* @__PURE__ */ new Set([
26
+ 9,
27
+ 10,
28
+ 11,
29
+ 12,
30
+ 13,
31
+ 32,
32
+ 133,
33
+ 160,
34
+ 5760,
35
+ 8192,
36
+ 8193,
37
+ 8194,
38
+ 8195,
39
+ 8196,
40
+ 8197,
41
+ 8198,
42
+ 8199,
43
+ 8200,
44
+ 8201,
45
+ 8202,
46
+ 8232,
47
+ 8233,
48
+ 8239,
49
+ 8287,
50
+ 12288
51
+ ]);
52
+ function goFields(text) {
53
+ const fields = [];
54
+ let current = "";
55
+ for (const ch of text) {
56
+ if (GO_WHITESPACE.has(ch.codePointAt(0))) {
57
+ if (current) fields.push(current);
58
+ current = "";
59
+ } else {
60
+ current += ch;
61
+ }
62
+ }
63
+ if (current) fields.push(current);
64
+ return fields;
65
+ }
66
+ function isEchoableEtag(etag) {
67
+ const decoded = Buffer.from(etag, "latin1").toString("utf8");
68
+ if (decoded.length < 2 || !decoded.startsWith('"') || !decoded.endsWith('"')) return false;
69
+ const inner = decoded.slice(1, -1);
70
+ const fields = goFields(inner);
71
+ return fields.length === 2 && fields.join(" ") === inner;
72
+ }
25
73
  function isAncestorOf(ancestor, descendant) {
26
74
  const base = ancestor.endsWith("/") ? ancestor.slice(0, -1) : ancestor;
27
75
  return descendant.startsWith(`${base}/`);
@@ -88,15 +136,18 @@ function getHeaders(contentType, overUnixSocket = false) {
88
136
  function normalizePath(path) {
89
137
  return path.replace(/^\/?(config(\/|$))?/, "");
90
138
  }
139
+ function isRootConfigPath(path) {
140
+ return /^\/*(\.\.\.\/*)?$/.test(normalizePath(path));
141
+ }
91
142
  function encodePathSegments(path) {
92
143
  return path.split("/").map((segment) => encodeURIComponent(segment)).join("/");
93
144
  }
94
145
  function rejectTraversal(path) {
95
- if (/(^|\/)\.\.(\/|$)/.test(path)) {
146
+ if (/(^|\/)\.\.?(\/|$)/.test(path)) {
96
147
  return {
97
148
  ok: false,
98
149
  status: 0,
99
- error: `Invalid path "${path}": '..' segments are not allowed`
150
+ error: `Invalid path "${path}": '.' and '..' segments are not allowed`
100
151
  };
101
152
  }
102
153
  return null;
@@ -113,8 +164,8 @@ function isMissingConfigPath(res) {
113
164
  if (res.ok) return false;
114
165
  return (res.error ?? "").toLowerCase().includes("invalid traversal path");
115
166
  }
116
- var ARRAY_INDEX_TAIL_RE = /\/\d+\/*$/;
117
- var BARE_ID_RE = /^\/id\/[^/]+\/*$/;
167
+ var ARRAY_INDEX_TAIL_RE = /\/\d+(\/+\.\.\.)?\/*$/;
168
+ var BARE_ID_RE = /^\/id\/[^/]+(\/+\.\.\.)?\/*$/;
118
169
  function isConfigChange(method, path) {
119
170
  if (method === "GET") return false;
120
171
  return path === "/load" || path.startsWith("/config/") || path.startsWith("/id/");
@@ -348,7 +399,8 @@ async function sendOnce(transport, method, path, body, contentType, rawStringBod
348
399
  const text = res.text;
349
400
  const etag = res.etag;
350
401
  if (method === "GET" && etag && isConfigPath) {
351
- setEtag(path, etag);
402
+ if (isEchoableEtag(etag)) setEtag(path, etag);
403
+ else etagCache.delete(path);
352
404
  }
353
405
  if (isWrite && res.ok && isConfigPath) {
354
406
  invalidateRelated(path);
@@ -571,15 +623,96 @@ function formatResult(res) {
571
623
  }
572
624
 
573
625
  // src/tools/operational.ts
574
- var HTTPS_PORT_RE = /:443(?:\D|$)/;
575
- function describeServer(rawValue) {
626
+ var DEFAULT_HTTP_PORT = 80;
627
+ var DEFAULT_HTTPS_PORT = 443;
628
+ function appPort(value, fallback) {
629
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 65535 ? value : fallback;
630
+ }
631
+ function splitPort(hostport) {
632
+ const i = hostport.lastIndexOf(":");
633
+ if (i < 0) return void 0;
634
+ if (hostport.startsWith("[")) {
635
+ const end = hostport.indexOf("]");
636
+ if (end < 0 || end + 1 !== i) return void 0;
637
+ if (hostport.slice(1).includes("[") || hostport.slice(end + 1).includes("]")) return void 0;
638
+ } else {
639
+ if (hostport.slice(0, i).includes(":")) return void 0;
640
+ if (hostport.includes("[") || hostport.includes("]")) return void 0;
641
+ }
642
+ return hostport.slice(i + 1);
643
+ }
644
+ function parseListenPortRange(entry) {
645
+ let rest = entry;
646
+ const slash = entry.indexOf("/");
647
+ if (slash >= 0) {
648
+ const network = entry.slice(0, slash).trim().toLowerCase();
649
+ rest = entry.slice(slash + 1);
650
+ if (network.startsWith("unix") || network.startsWith("fd")) return { start: 0, end: 0 };
651
+ }
652
+ const port = splitPort(rest);
653
+ if (port === void 0 || port === "") return { start: 0, end: 0 };
654
+ const dash = port.indexOf("-");
655
+ const start = parseUint16(dash < 0 ? port : port.slice(0, dash));
656
+ const end = parseUint16(dash < 0 ? port : port.slice(dash + 1));
657
+ if (start === void 0 || end === void 0 || end < start) return void 0;
658
+ return { start, end };
659
+ }
660
+ function parseUint16(s) {
661
+ if (!/^[0-9]+$/.test(s)) return void 0;
662
+ const n = Number(s);
663
+ return n <= 65535 ? n : void 0;
664
+ }
665
+ function hasQualifyingHost(routes, skip) {
666
+ for (const route of routes) {
667
+ if (!route || typeof route !== "object") continue;
668
+ const matcherSets = route.match;
669
+ if (!Array.isArray(matcherSets)) continue;
670
+ for (const set of matcherSets) {
671
+ if (!set || typeof set !== "object") continue;
672
+ const hosts = set.host;
673
+ if (!Array.isArray(hosts)) continue;
674
+ for (const host of hosts) {
675
+ if (typeof host === "string" && !skip.has(host)) return true;
676
+ }
677
+ }
678
+ }
679
+ return false;
680
+ }
681
+ function describeServer(rawValue, httpPort = DEFAULT_HTTP_PORT, httpsPort = DEFAULT_HTTPS_PORT) {
576
682
  const raw = rawValue !== null && typeof rawValue === "object" && !Array.isArray(rawValue) ? rawValue : {};
577
683
  const listen = Array.isArray(raw.listen) ? raw.listen : [];
578
684
  const routes = Array.isArray(raw.routes) ? raw.routes : [];
685
+ const ranges = [];
686
+ for (const entry of listen) {
687
+ if (typeof entry !== "string") continue;
688
+ const range = parseListenPortRange(entry);
689
+ if (range) ranges.push(range);
690
+ }
691
+ const usesAnyPortOtherThan = (port) => ranges.some((r) => port > r.end || port < r.start);
692
+ const bindsPort = (port) => ranges.some((r) => r.start <= port && port <= r.end);
693
+ const autoHttps = raw.automatic_https !== null && typeof raw.automatic_https === "object" && !Array.isArray(raw.automatic_https) ? raw.automatic_https : {};
694
+ const skip = new Set(
695
+ Array.isArray(autoHttps.skip) ? autoHttps.skip.filter((s) => typeof s === "string") : []
696
+ );
697
+ const allSocketsOnHttpPort = (port) => ranges.length > 0 && ranges.every((r) => r.start === port && r.end === port);
698
+ const perListener = (label) => allSocketsOnHttpPort(httpPort) ? "enabled (no listener gets TLS: all are on the HTTP port)" : bindsPort(httpPort) ? "mixed (TLS on non-HTTP listeners only)" : label;
579
699
  const tlsPolicies = raw.tls_connection_policies;
580
- const hasExplicitTls = Array.isArray(tlsPolicies) ? tlsPolicies.length > 0 : !!tlsPolicies;
581
- const listensHttps = listen.some((l) => typeof l === "string" && HTTPS_PORT_RE.test(l));
582
- const tls = hasExplicitTls ? "enabled" : listensHttps ? "auto (HTTPS)" : "off (HTTP only)";
700
+ let tls;
701
+ if (Array.isArray(tlsPolicies) && tlsPolicies.length === 0) {
702
+ tls = "off (empty tls_connection_policies)";
703
+ } else if (tlsPolicies) {
704
+ tls = perListener("enabled");
705
+ } else if (autoHttps.disable === true) {
706
+ tls = "off (automatic HTTPS disabled)";
707
+ } else if (!usesAnyPortOtherThan(httpPort)) {
708
+ tls = "off (HTTP only)";
709
+ } else if (!usesAnyPortOtherThan(httpsPort)) {
710
+ tls = perListener("auto (HTTPS)");
711
+ } else if (hasQualifyingHost(routes, skip)) {
712
+ tls = perListener("auto (HTTPS: host matchers on a non-HTTP port)");
713
+ } else {
714
+ tls = "off (no host matchers)";
715
+ }
583
716
  const listenStr = listen.length > 0 ? listen.map(String).join(", ") : "default";
584
717
  return `${routes.length} route(s), listen: ${listenStr}, TLS: ${tls}`;
585
718
  }
@@ -638,14 +771,17 @@ function registerOperationalTools(server) {
638
771
  const res = await configGet();
639
772
  if (!res.ok) return formatResult(res);
640
773
  const config = res.data ?? {};
641
- const servers = config.apps?.http?.servers ?? {};
774
+ const httpApp = config.apps?.http;
775
+ const servers = httpApp?.servers ?? {};
642
776
  const serverNames = Object.keys(servers);
777
+ const httpPort = appPort(httpApp?.http_port, DEFAULT_HTTP_PORT);
778
+ const httpsPort = appPort(httpApp?.https_port, DEFAULT_HTTPS_PORT);
643
779
  const lines = ["Caddy is running", ""];
644
780
  if (serverNames.length === 0) {
645
781
  lines.push("No HTTP servers configured");
646
782
  } else {
647
783
  for (const name of serverNames) {
648
- lines.push(`Server "${name}": ${describeServer(servers[name])}`);
784
+ lines.push(`Server "${name}": ${describeServer(servers[name], httpPort, httpsPort)}`);
649
785
  }
650
786
  }
651
787
  const email = findAcmeEmail(config.apps?.tls?.automation?.policies);
@@ -679,7 +815,7 @@ ${lines.join("\n")}` }]
679
815
  );
680
816
  server.tool(
681
817
  "caddy_upstreams",
682
- "Get the current health status of all reverse proxy upstreams. Shows address, active requests, and failure counts.",
818
+ "Caddy's /reverse_proxy/upstreams array (address, num_requests, fails), returned verbatim. On Caddy 2.11.2+ it is not the configured upstream list. Dynamic-upstream backends stay listed about 1 h (up to ~65 min) after the dynamic source last returned them, even after a config change removes them, so an address may appear that no current config references. A backend with requests in flight can appear twice when its resolved address differs from the entry's text (dynamic upstreams, tcp/ or unix// dials, placeholder dials). That extra copy always shows fails 0 and repeats num_requests, so do not sum num_requests across entries.",
683
819
  {},
684
820
  { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
685
821
  async () => formatResult(await getUpstreams())
@@ -753,7 +889,9 @@ function registerResources(server) {
753
889
  server.resource(
754
890
  "caddy-upstreams",
755
891
  "caddy://upstreams",
756
- { description: "Reverse proxy upstream health status" },
892
+ {
893
+ description: "Reverse proxy upstream health: Caddy's /reverse_proxy/upstreams array, returned verbatim. On Caddy 2.11.2+ it is not the configured upstream list -- dynamic upstreams stay listed about 1 h after the dynamic source last returned them (so an address can outlive the config that referenced it), and a backend with requests in flight can appear twice when its resolved address differs from the entry's text. The extra copy always shows fails 0 and repeats num_requests, so do not sum num_requests. See the caddy_upstreams tool for the full caveat."
894
+ },
757
895
  async () => {
758
896
  const res = await getUpstreams();
759
897
  return {
@@ -829,7 +967,7 @@ function formatWarning2(w) {
829
967
  function registerAdaptTools(server) {
830
968
  server.tool(
831
969
  "caddy_adapt",
832
- "Convert a config in any registered adapter format to Caddy JSON without loading it. Useful for previewing what a Caddyfile produces, or for porting from nginx/yaml configs when Caddy is built with the matching adapter module ('caddyfile' is built-in; 'nginx', 'yaml', etc. require their adapter modules to be compiled into the Caddy binary). Returns the adapted JSON and any warnings separately.",
970
+ `Convert a config in any registered adapter format to Caddy JSON without loading it. Useful for previewing what a Caddyfile produces, or for porting from nginx/yaml configs when Caddy is built with the matching adapter module ('caddyfile' is built-in; 'nginx', 'yaml', etc. require their adapter modules to be compiled into the Caddy binary). Returns the adapted JSON and any warnings separately. One exception to 'without loading it': on Caddy <= 2.11.4 a Caddyfile 'order' global option is not preview-only. It mutates that Caddy process's directive order, so it carries into every later Caddyfile adapt or load there, and an 'order' line that FAILS (unknown target, bad positional, extra arg) still removes the directive it names -- later Caddyfiles using that directive then fail with "directive 'X' is not an ordered HTTP handler" until another 'order' line re-places it or Caddy restarts. Fixed upstream in caddyserver/caddy#7995, unreleased as of v2.11.4.`,
833
971
  {
834
972
  config: z2.string().describe("The raw config text (e.g., Caddyfile contents, nginx.conf, yaml)"),
835
973
  adapter: z2.string().regex(/^[a-z0-9_-]+$/, "Adapter must be lowercase alphanumeric, hyphens, or underscores").max(64).optional().default("caddyfile").describe(
@@ -939,6 +1077,43 @@ function getSnapshot(index) {
939
1077
  }
940
1078
 
941
1079
  // src/tools/config.ts
1080
+ function adminListenOf(config) {
1081
+ if (!isSnapshotableConfig(config)) return void 0;
1082
+ const adm = config.admin;
1083
+ if (adm === null || typeof adm !== "object" || Array.isArray(adm)) return void 0;
1084
+ const listen = adm.listen;
1085
+ return typeof listen === "string" && listen !== "" ? listen : void 0;
1086
+ }
1087
+ function adminDisabledIn(config) {
1088
+ if (!isSnapshotableConfig(config)) return false;
1089
+ const adm = config.admin;
1090
+ return adm !== null && typeof adm === "object" && !Array.isArray(adm) && adm.disabled === true;
1091
+ }
1092
+ function priorConfigNote(kept, current, trigger) {
1093
+ if (kept) {
1094
+ return ` The prior config was saved as snapshot [0] (trigger=${trigger}): caddy_revert { action: "apply", index: 0, confirm: true } restores it.`;
1095
+ }
1096
+ return current.ok ? " Warning: the prior config was empty or not a JSON object, so no snapshot was captured -- there was nothing to restore." : " Warning: the prior config could not be read, so no snapshot was captured and this change cannot be reverted.";
1097
+ }
1098
+ function rootWriteAdminNote(current, value) {
1099
+ if (adminDisabledIn(value)) {
1100
+ return " The new config sets admin.disabled, so Caddy no longer answers on ANY admin address: neither this server nor caddy_revert can reach it until Caddy is restarted with a config that does not disable the admin endpoint.";
1101
+ }
1102
+ const adminUrl = process.env.CADDY_ADMIN_URL || "http://localhost:2019";
1103
+ const before = current.ok ? adminListenOf(current.data) : void 0;
1104
+ const after = adminListenOf(value);
1105
+ if (before !== void 0 && after !== before) {
1106
+ return ` The replaced config set admin.listen to "${before}"` + (after !== void 0 ? ` and the new one sets it to "${after}".` : " and the new one sets none.") + ` Unless those resolve to the same address, the admin endpoint has moved (to the new value, or back to the default: localhost:2019 unless $CADDY_ADMIN is set in Caddy's environment) and CADDY_ADMIN_URL (${adminUrl}) may no longer reach it.`;
1107
+ }
1108
+ if (before === void 0 && after !== void 0) {
1109
+ return ` The new config sets admin.listen to "${after}". If that is not the address Caddy was already on, the admin endpoint has moved there and CADDY_ADMIN_URL (${adminUrl}) may no longer reach it.`;
1110
+ }
1111
+ if (!current.ok) return unreadablePriorAdminNote("replaced");
1112
+ return "";
1113
+ }
1114
+ function unreadablePriorAdminNote(verb) {
1115
+ return ` The ${verb} config could not be read, so this server cannot tell whether it set an admin.listen of its own. If it did, and that was not Caddy's default admin address, the endpoint has moved back to the default (localhost:2019, unless $CADDY_ADMIN is set in Caddy's environment) and CADDY_ADMIN_URL (${process.env.CADDY_ADMIN_URL || "http://localhost:2019"}) may no longer reach it.`;
1116
+ }
942
1117
  function registerConfigTools(server) {
943
1118
  server.tool(
944
1119
  "caddy_config_get",
@@ -949,23 +1124,73 @@ function registerConfigTools(server) {
949
1124
  );
950
1125
  server.tool(
951
1126
  "caddy_config_set",
952
- "Write config at a JSON path. Mode 'overwrite' (default) replaces existing values (PATCH) \u2014 safe and idempotent. Mode 'append' (POST) adds to an array \u2014 NOT idempotent: calling twice with the same route duplicates it \u2014 but on a non-array key it REPLACES whatever is there, and it cannot create missing parent objects. Mode 'insert' (PUT) inserts at an array index (useful for route ordering), or strictly creates an object key together with any missing parents and fails with 409 if the key already exists \u2014 the safe way to create a server or app, including on an instance with no config at all.",
1127
+ "Write config at a JSON path. Mode 'overwrite' (default) replaces the value at the path (PATCH) \u2014 idempotent, but it replaces the WHOLE subtree there: writing [] to '.../routes' drops every route. Mode 'append' (POST) adds to an array \u2014 NOT idempotent: calling twice with the same route duplicates it \u2014 but on a non-array key it REPLACES whatever is there, and it cannot create missing parent objects. Mode 'insert' (PUT) inserts at an array index (useful for route ordering), or strictly creates an object key together with any missing parents and fails with 409 if the key already exists \u2014 the safe way to create a server or app, including on an instance with no config at all. Any path that addresses the config ROOT ('', '/', 'config', '/config/', a slash-only variant, or any of those followed by a lone '...' segment) addresses the ENTIRE config and requires confirm=true: 'overwrite' and 'append' there REPLACE the whole configuration with `value` \u2014 Caddy runs it exactly as caddy_load would \u2014 so every app, server and route not in `value` is discarded, and so is the 'admin' block unless `value` carries one. Caddy then re-binds its admin endpoint to the new config's admin.listen, or to its default address (localhost:2019, or $CADDY_ADMIN in Caddy's environment) when it sets none, or to no address at all when it sets admin.disabled; if CADDY_ADMIN_URL points anywhere else, neither this server nor caddy_revert can reach Caddy afterwards. A root write is snapshotted first, so caddy_revert can restore it while Caddy is still reachable; no other path is snapshotted. 'insert' at the root only succeeds after a root caddy_config_delete (Caddy answers 409 on any other instance, including one started with no config), and 'overwrite' is the reverse: after a root caddy_config_delete it answers 404 until 'append', 'insert' or caddy_load re-creates the config. To replace the whole config deliberately, caddy_load does the same thing behind the same gate and also accepts a Caddyfile.",
953
1128
  {
954
1129
  path: z3.string().describe("Config path to write to (e.g., 'apps/http/servers/srv0/routes')"),
955
1130
  value: z3.any().describe("The JSON value to set at the path"),
956
1131
  mode: z3.enum(["append", "overwrite", "insert"]).optional().default("overwrite").describe(
957
1132
  "'overwrite' = PATCH (replace existing, default, idempotent; 404 if the key does not exist), 'append' = POST (appends to arrays, NOT idempotent; REPLACES an existing non-array key; cannot create missing parents), 'insert' = PUT (inserts at an array index, or strictly creates an object key and any missing parents; 409 if the key exists)"
1133
+ ),
1134
+ confirm: z3.boolean().optional().default(false).describe(
1135
+ "Must be true when `path` addresses the config root ('', '/', 'config', '/config/', slash-only variants, or a lone '...' segment): that write replaces the ENTIRE config (safety). Ignored for every other path."
958
1136
  )
959
1137
  },
960
- { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
961
- async ({ path, value, mode }) => {
962
- const res = mode === "overwrite" ? await configPatch(path, value) : mode === "insert" ? await configPut(path, value) : await configPost(path, value);
963
- return formatResult(res);
1138
+ // destructiveHint is TRUE because the hint covers the whole tool and a host
1139
+ // gates on it before it can see the path or the mode: the default mode is a
1140
+ // PATCH that replaces whatever subtree the path names -- a route list, a
1141
+ // server, all of `apps` -- and at the root it replaces the entire config
1142
+ // (below). MCP defines destructiveHint:false as "only additive updates".
1143
+ // Appending to an array or strictly creating a key is additive; the
1144
+ // default mode is not, and neither is 'append' on a non-array key, which
1145
+ // replaces it. idempotentHint stays false for 'append', which is a POST: a
1146
+ // repeated call appends a second copy.
1147
+ { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
1148
+ async ({ path, value, mode, confirm }) => {
1149
+ const write = (p) => mode === "overwrite" ? configPatch(p, value) : mode === "insert" ? configPut(p, value) : configPost(p, value);
1150
+ if (!isRootConfigPath(path)) return formatResult(await write(path));
1151
+ if (!confirm) {
1152
+ return {
1153
+ isError: true,
1154
+ content: [
1155
+ {
1156
+ type: "text",
1157
+ text: `Refusing to write the ENTIRE config without confirm=true. The path "${path}" addresses the config root, so this call REPLACES the whole configuration with \`value\` ('overwrite' and 'append' both do, and Caddy runs it exactly as caddy_load would; after a root caddy_config_delete 'overwrite' answers 404 instead, while 'insert' succeeds only then and answers 409 otherwise): every app, server and route not in \`value\` is discarded, and so is the 'admin' block unless \`value\` carries one. Caddy then re-binds its admin endpoint to the new config's admin.listen, or to its default address (localhost:2019, or $CADDY_ADMIN in Caddy's environment) when it sets none, or to no address at all when it sets admin.disabled; and if CADDY_ADMIN_URL points anywhere else neither this server nor caddy_revert can reach Caddy afterwards. The current config is snapshotted first, so caddy_revert can restore it while Caddy is still reachable. To change one part of the config, pass its path instead (e.g. 'apps/http/servers/srv0'); to replace all of it deliberately, caddy_load does the same behind the same gate. Re-run with confirm:true to proceed.`
1158
+ }
1159
+ ]
1160
+ };
1161
+ }
1162
+ const current = await configGet();
1163
+ const res = await write("");
1164
+ const kept = (res.ok || res.outcomeUnknown === true) && current.ok && isSnapshotableConfig(current.data);
1165
+ if (kept) saveSnapshot(current.data, "caddy_config_set");
1166
+ const adminNote = rootWriteAdminNote(current, value);
1167
+ if (!res.ok) {
1168
+ if (res.outcomeUnknown && (kept || adminNote)) {
1169
+ const snapshotPart = kept ? `The pre-write config was kept anyway, as snapshot [0] (trigger=caddy_config_set): if this write did apply, caddy_revert { action: "apply", index: 0, confirm: true } restores what it replaced, as long as this server can still reach Caddy's admin endpoint.` : "";
1170
+ const adminPart = adminNote ? `If the write applied:${adminNote}` : "";
1171
+ const tail = kept ? "If it did not apply, that snapshot is simply the config read just before it was sent." : "";
1172
+ return formatResult({
1173
+ ...res,
1174
+ error: `${res.error}
1175
+ ${[snapshotPart, adminPart, tail].filter(Boolean).join(" ")}`
1176
+ });
1177
+ }
1178
+ return formatResult(res);
1179
+ }
1180
+ const note = priorConfigNote(kept, current, "caddy_config_set");
1181
+ return {
1182
+ content: [
1183
+ {
1184
+ type: "text",
1185
+ text: `Replaced the entire config (every app and server, and the 'admin' block).${note}${adminNote}`
1186
+ }
1187
+ ]
1188
+ };
964
1189
  }
965
1190
  );
966
1191
  server.tool(
967
1192
  "caddy_config_delete",
968
- "Delete config at a JSON path. Removes the config node at the specified path. Deleting a parent node also deletes every descendant -- e.g. deleting 'apps/http/servers/srv0' removes that server and all of its routes. Requires confirm=true.",
1193
+ "Delete config at a JSON path. Removes the config node at the specified path. Deleting a parent node also deletes every descendant -- e.g. deleting 'apps/http/servers/srv0' removes that server and all of its routes. Requires confirm=true. Any path that addresses the config ROOT ('', '/', 'config', '/config/', slash-only variants of those, or any of those followed by a lone '...' segment) addresses the ENTIRE config and unloads it: every app and server goes, and so does the 'admin' block, after which Caddy re-binds its admin endpoint to its default address (localhost:2019, or $CADDY_ADMIN in Caddy's environment). If CADDY_ADMIN_URL points anywhere else, neither this server nor caddy_revert can reach Caddy afterwards. A root delete is snapshotted first, so caddy_revert can restore it while Caddy is still reachable; no other path is snapshotted. To REPLACE the config rather than unload it, use caddy_load.",
969
1194
  {
970
1195
  path: z3.string().describe("Config path to delete (e.g., 'apps/http/servers/srv0/routes/0')"),
971
1196
  confirm: z3.boolean().optional().default(false).describe("Must be true to actually delete the config node (safety)")
@@ -976,22 +1201,50 @@ function registerConfigTools(server) {
976
1201
  // array after a delete, so repeating that call removes a DIFFERENT route each
977
1202
  // time. caddy_remove_route carries the same correction for the byte-identical
978
1203
  // underlying request; the two must agree. Nothing here is auto-recoverable
979
- // either: only caddy_load captures a snapshot, so a spurious repeat cannot be
980
- // undone with caddy_revert.
1204
+ // either: apart from a root delete (below), only whole-config changes
1205
+ // capture a snapshot -- caddy_load, a caddy_revert apply, and a root
1206
+ // caddy_config_set -- so a spurious repeat cannot be undone with
1207
+ // caddy_revert.
981
1208
  { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
982
1209
  async ({ path, confirm }) => {
1210
+ const root = isRootConfigPath(path);
983
1211
  if (!confirm) {
984
1212
  return {
985
1213
  isError: true,
986
1214
  content: [
987
1215
  {
988
1216
  type: "text",
989
- text: `Refusing to delete "${path}" without confirm=true. Deleting a parent path also removes all descendants. Re-run with confirm:true to proceed.`
1217
+ text: root ? `Refusing to delete the ENTIRE config without confirm=true. The path "${path}" addresses the config root, so this unloads every app and server, and the 'admin' block with them: Caddy then re-binds its admin endpoint to its default address (localhost:2019, or $CADDY_ADMIN in Caddy's environment), and if CADDY_ADMIN_URL points anywhere else neither this server nor caddy_revert can reach Caddy afterwards. The current config is snapshotted first, so caddy_revert can restore it while Caddy is still reachable. To REPLACE the config rather than unload it, use caddy_load. Re-run with confirm:true to proceed.` : `Refusing to delete "${path}" without confirm=true. Deleting a parent path also removes all descendants. Re-run with confirm:true to proceed.`
990
1218
  }
991
1219
  ]
992
1220
  };
993
1221
  }
994
- return formatResult(await configDelete(path));
1222
+ if (!root) return formatResult(await configDelete(path));
1223
+ const current = await configGet();
1224
+ const res = await configDelete("");
1225
+ const kept = (res.ok || res.outcomeUnknown === true) && current.ok && isSnapshotableConfig(current.data);
1226
+ if (kept) saveSnapshot(current.data, "caddy_config_delete");
1227
+ if (!res.ok) {
1228
+ if (res.outcomeUnknown && kept) {
1229
+ return formatResult({
1230
+ ...res,
1231
+ error: `${res.error}
1232
+ The pre-delete config was kept anyway, as snapshot [0] (trigger=caddy_config_delete): if this delete did apply, caddy_revert { action: "apply", index: 0, confirm: true } restores what it unloaded -- as long as this server can still reach Caddy's admin endpoint, which moves back to Caddy's default address when the deleted config set an admin.listen of its own. If the delete did not apply, that snapshot is simply the config read just before it was sent.`
1233
+ });
1234
+ }
1235
+ return formatResult(res);
1236
+ }
1237
+ const note = priorConfigNote(kept, current, "caddy_config_delete");
1238
+ const listen = kept ? adminListenOf(current.data) : void 0;
1239
+ const adminNote = listen !== void 0 ? ` The unloaded config set admin.listen to "${listen}". If that was not already Caddy's default admin address, the endpoint has moved back to the default (localhost:2019, unless $CADDY_ADMIN is set in Caddy's environment) and CADDY_ADMIN_URL (${process.env.CADDY_ADMIN_URL || "http://localhost:2019"}) may no longer reach it.` : current.ok ? "" : unreadablePriorAdminNote("unloaded");
1240
+ return {
1241
+ content: [
1242
+ {
1243
+ type: "text",
1244
+ text: `Unloaded the entire config (every app and server, and the 'admin' block).${note}${adminNote}`
1245
+ }
1246
+ ]
1247
+ };
995
1248
  }
996
1249
  );
997
1250
  server.tool(
@@ -1032,7 +1285,7 @@ The pre-load config was kept anyway, as snapshot [0] (trigger=caddy_load): if th
1032
1285
  );
1033
1286
  server.tool(
1034
1287
  "caddy_revert",
1035
- "Manage config snapshots for rollback. Snapshots are auto-captured before caddy_load (last 10). By default they live in memory only and are LOST when this server restarts -- set CADDY_MCP_SNAPSHOT_DIR to a writable directory to persist them across restarts (they contain full Caddy configs, so pick the location deliberately). Actions: 'list' shows snapshots with timestamps, 'save' manually captures the current config, 'apply' restores a snapshot (requires confirm=true).",
1288
+ "Manage config snapshots for rollback. Snapshots are auto-captured before caddy_load, and before a caddy_config_delete or caddy_config_set at the config root (any path that addresses the whole config); no other delete or set is snapshotted. Last 10. By default they live in memory only and are LOST when this server restarts -- set CADDY_MCP_SNAPSHOT_DIR to a writable directory to persist them across restarts (they contain full Caddy configs, so pick the location deliberately). Actions: 'list' shows snapshots with timestamps, 'save' manually captures the current config, 'apply' restores a snapshot (requires confirm=true).",
1036
1289
  {
1037
1290
  action: z3.enum(["list", "save", "apply"]).describe("Action to perform"),
1038
1291
  index: z3.number().int().nonnegative().optional().default(0).describe("Snapshot index for 'apply' (0 = most recent, default)"),
@@ -1819,7 +2072,7 @@ function registerTlsTools(server) {
1819
2072
  email: z5.string().optional().describe("ACME email address (for 'set_email' action)"),
1820
2073
  ca: z5.string().optional().describe("ACME CA URL (for 'set_acme_ca' action)"),
1821
2074
  profile: z5.string().optional().describe(
1822
- "ACME profile name (for 'set_acme_profile'). Requires Caddy 2.10+ and a CA that offers profiles; Let's Encrypt uses 'shortlived' for 6-day certificates. Valid names are defined by the CA, not by Caddy."
2075
+ "ACME profile name (for 'set_acme_profile'). Requires Caddy 2.10+ and a CA that offers profiles; Let's Encrypt uses 'shortlived' for 6-day certificates. Valid names are defined by the CA, not by Caddy. EXPERIMENTAL upstream (the ACME profiles spec is still a draft; Caddy marks the field 'subject to change' and may rename or drop it). Caddy accepts any name on load, so a success here does not mean the CA offers it: if this issuer's CA does not advertise the name, every order from this issuer fails at issuance time, reported only in Caddy's own logs. Caddy then either falls through to the next issuer in the policy, which issues WITHOUT the profile, or -- when this is the policy's only issuer, which is the shape this tool creates -- keeps retrying and issues no certificate at all."
1823
2076
  )
1824
2077
  },
1825
2078
  { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yawlabs/caddy-mcp",
3
- "version": "2.5.3",
3
+ "version": "2.5.5",
4
4
  "mcpName": "io.github.YawLabs/caddy-mcp",
5
5
  "description": "Caddy MCP server for Claude Code, Cursor, and any MCP client: admin API, config, routes, reverse proxy, TLS, PKI, metrics",
6
6
  "license": "MIT",