@yawlabs/caddy-mcp 2.5.3 → 2.5.4

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
@@ -4,7 +4,7 @@
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
5
  [![GitHub stars](https://img.shields.io/github/stars/YawLabs/caddy-mcp)](https://github.com/YawLabs/caddy-mcp/stargazers)
6
6
 
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.
7
+ **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
8
 
9
9
  Built and maintained by [Yaw Labs](https://yaw.sh).
10
10
 
@@ -16,7 +16,7 @@ One click adds this to your local Yaw MCP config so it's available in every Yaw
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
21
  - **Safe-by-default mutations** — `caddy_config_set` defaults to idempotent `overwrite` (PATCH), not `append` (POST). Calling twice doesn't duplicate your route.
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.
@@ -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), `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`.
125
+ - **caddy_config_delete** — Delete config at a path. Requires `confirm=true` (deleting a parent path also removes every descendant). An empty path (`''`, `'/'`, `'config'`, `'/config/'`) 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` 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**
233
239
 
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.
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"`
245
+
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 (692 unit tests, +39 POSIX-only unix-socket and launcher tests; +33 live-Caddy integration tests gated by CADDY_MCP_INTEGRATION=1)
269
301
  npm run typecheck # tsc --noEmit
270
302
  ```
271
303
 
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}/`);
@@ -115,8 +163,8 @@ function isMissingConfigPath(res) {
115
163
  if (res.ok) return false;
116
164
  return (res.error ?? "").toLowerCase().includes("invalid traversal path");
117
165
  }
118
- var ARRAY_INDEX_TAIL_RE = /\/\d+\/*$/;
119
- var BARE_ID_RE = /^\/id\/[^/]+\/*$/;
166
+ var ARRAY_INDEX_TAIL_RE = /\/\d+(\/+\.\.\.)?\/*$/;
167
+ var BARE_ID_RE = /^\/id\/[^/]+(\/+\.\.\.)?\/*$/;
120
168
  function isConfigChange(method, path) {
121
169
  if (method === "GET") return false;
122
170
  return path === "/load" || path.startsWith("/config/") || path.startsWith("/id/");
@@ -350,7 +398,8 @@ async function sendOnce(transport, method, path, body, contentType, rawStringBod
350
398
  const text = res.text;
351
399
  const etag = res.etag;
352
400
  if (method === "GET" && etag && isConfigPath) {
353
- setEtag(path, etag);
401
+ if (isEchoableEtag(etag)) setEtag(path, etag);
402
+ else etagCache.delete(path);
354
403
  }
355
404
  if (isWrite && res.ok && isConfigPath) {
356
405
  invalidateRelated(path);
@@ -573,15 +622,96 @@ function formatResult(res) {
573
622
  }
574
623
 
575
624
  // src/tools/operational.ts
576
- var HTTPS_PORT_RE = /:443(?:\D|$)/;
577
- function describeServer(rawValue) {
625
+ var DEFAULT_HTTP_PORT = 80;
626
+ var DEFAULT_HTTPS_PORT = 443;
627
+ function appPort(value, fallback) {
628
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 65535 ? value : fallback;
629
+ }
630
+ function splitPort(hostport) {
631
+ const i = hostport.lastIndexOf(":");
632
+ if (i < 0) return void 0;
633
+ if (hostport.startsWith("[")) {
634
+ const end = hostport.indexOf("]");
635
+ if (end < 0 || end + 1 !== i) return void 0;
636
+ if (hostport.slice(1).includes("[") || hostport.slice(end + 1).includes("]")) return void 0;
637
+ } else {
638
+ if (hostport.slice(0, i).includes(":")) return void 0;
639
+ if (hostport.includes("[") || hostport.includes("]")) return void 0;
640
+ }
641
+ return hostport.slice(i + 1);
642
+ }
643
+ function parseListenPortRange(entry) {
644
+ let rest = entry;
645
+ const slash = entry.indexOf("/");
646
+ if (slash >= 0) {
647
+ const network = entry.slice(0, slash).trim().toLowerCase();
648
+ rest = entry.slice(slash + 1);
649
+ if (network.startsWith("unix") || network.startsWith("fd")) return { start: 0, end: 0 };
650
+ }
651
+ const port = splitPort(rest);
652
+ if (port === void 0 || port === "") return { start: 0, end: 0 };
653
+ const dash = port.indexOf("-");
654
+ const start = parseUint16(dash < 0 ? port : port.slice(0, dash));
655
+ const end = parseUint16(dash < 0 ? port : port.slice(dash + 1));
656
+ if (start === void 0 || end === void 0 || end < start) return void 0;
657
+ return { start, end };
658
+ }
659
+ function parseUint16(s) {
660
+ if (!/^[0-9]+$/.test(s)) return void 0;
661
+ const n = Number(s);
662
+ return n <= 65535 ? n : void 0;
663
+ }
664
+ function hasQualifyingHost(routes, skip) {
665
+ for (const route of routes) {
666
+ if (!route || typeof route !== "object") continue;
667
+ const matcherSets = route.match;
668
+ if (!Array.isArray(matcherSets)) continue;
669
+ for (const set of matcherSets) {
670
+ if (!set || typeof set !== "object") continue;
671
+ const hosts = set.host;
672
+ if (!Array.isArray(hosts)) continue;
673
+ for (const host of hosts) {
674
+ if (typeof host === "string" && !skip.has(host)) return true;
675
+ }
676
+ }
677
+ }
678
+ return false;
679
+ }
680
+ function describeServer(rawValue, httpPort = DEFAULT_HTTP_PORT, httpsPort = DEFAULT_HTTPS_PORT) {
578
681
  const raw = rawValue !== null && typeof rawValue === "object" && !Array.isArray(rawValue) ? rawValue : {};
579
682
  const listen = Array.isArray(raw.listen) ? raw.listen : [];
580
683
  const routes = Array.isArray(raw.routes) ? raw.routes : [];
684
+ const ranges = [];
685
+ for (const entry of listen) {
686
+ if (typeof entry !== "string") continue;
687
+ const range = parseListenPortRange(entry);
688
+ if (range) ranges.push(range);
689
+ }
690
+ const usesAnyPortOtherThan = (port) => ranges.some((r) => port > r.end || port < r.start);
691
+ const bindsPort = (port) => ranges.some((r) => r.start <= port && port <= r.end);
692
+ const autoHttps = raw.automatic_https !== null && typeof raw.automatic_https === "object" && !Array.isArray(raw.automatic_https) ? raw.automatic_https : {};
693
+ const skip = new Set(
694
+ Array.isArray(autoHttps.skip) ? autoHttps.skip.filter((s) => typeof s === "string") : []
695
+ );
696
+ const allSocketsOnHttpPort = (port) => ranges.length > 0 && ranges.every((r) => r.start === port && r.end === port);
697
+ 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
698
  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)";
699
+ let tls;
700
+ if (Array.isArray(tlsPolicies) && tlsPolicies.length === 0) {
701
+ tls = "off (empty tls_connection_policies)";
702
+ } else if (tlsPolicies) {
703
+ tls = perListener("enabled");
704
+ } else if (autoHttps.disable === true) {
705
+ tls = "off (automatic HTTPS disabled)";
706
+ } else if (!usesAnyPortOtherThan(httpPort)) {
707
+ tls = "off (HTTP only)";
708
+ } else if (!usesAnyPortOtherThan(httpsPort)) {
709
+ tls = perListener("auto (HTTPS)");
710
+ } else if (hasQualifyingHost(routes, skip)) {
711
+ tls = perListener("auto (HTTPS: host matchers on a non-HTTP port)");
712
+ } else {
713
+ tls = "off (no host matchers)";
714
+ }
585
715
  const listenStr = listen.length > 0 ? listen.map(String).join(", ") : "default";
586
716
  return `${routes.length} route(s), listen: ${listenStr}, TLS: ${tls}`;
587
717
  }
@@ -640,14 +770,17 @@ function registerOperationalTools(server) {
640
770
  const res = await configGet();
641
771
  if (!res.ok) return formatResult(res);
642
772
  const config = res.data ?? {};
643
- const servers = config.apps?.http?.servers ?? {};
773
+ const httpApp = config.apps?.http;
774
+ const servers = httpApp?.servers ?? {};
644
775
  const serverNames = Object.keys(servers);
776
+ const httpPort = appPort(httpApp?.http_port, DEFAULT_HTTP_PORT);
777
+ const httpsPort = appPort(httpApp?.https_port, DEFAULT_HTTPS_PORT);
645
778
  const lines = ["Caddy is running", ""];
646
779
  if (serverNames.length === 0) {
647
780
  lines.push("No HTTP servers configured");
648
781
  } else {
649
782
  for (const name of serverNames) {
650
- lines.push(`Server "${name}": ${describeServer(servers[name])}`);
783
+ lines.push(`Server "${name}": ${describeServer(servers[name], httpPort, httpsPort)}`);
651
784
  }
652
785
  }
653
786
  const email = findAcmeEmail(config.apps?.tls?.automation?.policies);
@@ -681,7 +814,7 @@ ${lines.join("\n")}` }]
681
814
  );
682
815
  server.tool(
683
816
  "caddy_upstreams",
684
- "Get the current health status of all reverse proxy upstreams. Shows address, active requests, and failure counts.",
817
+ "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
818
  {},
686
819
  { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
687
820
  async () => formatResult(await getUpstreams())
@@ -755,7 +888,9 @@ function registerResources(server) {
755
888
  server.resource(
756
889
  "caddy-upstreams",
757
890
  "caddy://upstreams",
758
- { description: "Reverse proxy upstream health status" },
891
+ {
892
+ 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."
893
+ },
759
894
  async () => {
760
895
  const res = await getUpstreams();
761
896
  return {
@@ -831,7 +966,7 @@ function formatWarning2(w) {
831
966
  function registerAdaptTools(server) {
832
967
  server.tool(
833
968
  "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.",
969
+ `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
970
  {
836
971
  config: z2.string().describe("The raw config text (e.g., Caddyfile contents, nginx.conf, yaml)"),
837
972
  adapter: z2.string().regex(/^[a-z0-9_-]+$/, "Adapter must be lowercase alphanumeric, hyphens, or underscores").max(64).optional().default("caddyfile").describe(
@@ -941,6 +1076,9 @@ function getSnapshot(index) {
941
1076
  }
942
1077
 
943
1078
  // src/tools/config.ts
1079
+ function isRootConfigPath(path) {
1080
+ return /^\/*$/.test(path.replace(/^\/?(config(\/|$))?/, ""));
1081
+ }
944
1082
  function registerConfigTools(server) {
945
1083
  server.tool(
946
1084
  "caddy_config_get",
@@ -967,7 +1105,7 @@ function registerConfigTools(server) {
967
1105
  );
968
1106
  server.tool(
969
1107
  "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.",
1108
+ "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/', and slash-only variants of those) 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
1109
  {
972
1110
  path: z3.string().describe("Config path to delete (e.g., 'apps/http/servers/srv0/routes/0')"),
973
1111
  confirm: z3.boolean().optional().default(false).describe("Must be true to actually delete the config node (safety)")
@@ -978,22 +1116,49 @@ function registerConfigTools(server) {
978
1116
  // array after a delete, so repeating that call removes a DIFFERENT route each
979
1117
  // time. caddy_remove_route carries the same correction for the byte-identical
980
1118
  // 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.
1119
+ // either: apart from a root delete (below), only caddy_load captures a
1120
+ // snapshot, so a spurious repeat cannot be undone with caddy_revert.
983
1121
  { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
984
1122
  async ({ path, confirm }) => {
1123
+ const root = isRootConfigPath(path);
985
1124
  if (!confirm) {
986
1125
  return {
987
1126
  isError: true,
988
1127
  content: [
989
1128
  {
990
1129
  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.`
1130
+ 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
1131
  }
993
1132
  ]
994
1133
  };
995
1134
  }
996
- return formatResult(await configDelete(path));
1135
+ if (!root) return formatResult(await configDelete(path));
1136
+ const current = await configGet();
1137
+ const res = await configDelete("");
1138
+ const kept = (res.ok || res.outcomeUnknown === true) && current.ok && isSnapshotableConfig(current.data);
1139
+ if (kept) saveSnapshot(current.data, "caddy_config_delete");
1140
+ if (!res.ok) {
1141
+ if (res.outcomeUnknown && kept) {
1142
+ return formatResult({
1143
+ ...res,
1144
+ error: `${res.error}
1145
+ 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.`
1146
+ });
1147
+ }
1148
+ return formatResult(res);
1149
+ }
1150
+ const note = kept ? ` The prior config was saved as snapshot [0] (trigger=caddy_config_delete): caddy_revert { action: "apply", index: 0, confirm: true } restores it.` : 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 unload cannot be reverted.";
1151
+ const adm = kept ? current.data.admin : void 0;
1152
+ const listen = adm !== null && typeof adm === "object" && !Array.isArray(adm) ? adm.listen : void 0;
1153
+ const adminNote = typeof listen === "string" && listen !== "" ? ` 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.` : "";
1154
+ return {
1155
+ content: [
1156
+ {
1157
+ type: "text",
1158
+ text: `Unloaded the entire config (every app and server, and the 'admin' block).${note}${adminNote}`
1159
+ }
1160
+ ]
1161
+ };
997
1162
  }
998
1163
  );
999
1164
  server.tool(
@@ -1034,7 +1199,7 @@ The pre-load config was kept anyway, as snapshot [0] (trigger=caddy_load): if th
1034
1199
  );
1035
1200
  server.tool(
1036
1201
  "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).",
1202
+ "Manage config snapshots for rollback. Snapshots are auto-captured before caddy_load, and before a caddy_config_delete that unloads the whole config (an empty path); no other delete 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
1203
  {
1039
1204
  action: z3.enum(["list", "save", "apply"]).describe("Action to perform"),
1040
1205
  index: z3.number().int().nonnegative().optional().default(0).describe("Snapshot index for 'apply' (0 = most recent, default)"),
@@ -1821,7 +1986,7 @@ function registerTlsTools(server) {
1821
1986
  email: z5.string().optional().describe("ACME email address (for 'set_email' action)"),
1822
1987
  ca: z5.string().optional().describe("ACME CA URL (for 'set_acme_ca' action)"),
1823
1988
  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."
1989
+ "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
1990
  )
1826
1991
  },
1827
1992
  { 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}/`);
@@ -113,8 +161,8 @@ function isMissingConfigPath(res) {
113
161
  if (res.ok) return false;
114
162
  return (res.error ?? "").toLowerCase().includes("invalid traversal path");
115
163
  }
116
- var ARRAY_INDEX_TAIL_RE = /\/\d+\/*$/;
117
- var BARE_ID_RE = /^\/id\/[^/]+\/*$/;
164
+ var ARRAY_INDEX_TAIL_RE = /\/\d+(\/+\.\.\.)?\/*$/;
165
+ var BARE_ID_RE = /^\/id\/[^/]+(\/+\.\.\.)?\/*$/;
118
166
  function isConfigChange(method, path) {
119
167
  if (method === "GET") return false;
120
168
  return path === "/load" || path.startsWith("/config/") || path.startsWith("/id/");
@@ -348,7 +396,8 @@ async function sendOnce(transport, method, path, body, contentType, rawStringBod
348
396
  const text = res.text;
349
397
  const etag = res.etag;
350
398
  if (method === "GET" && etag && isConfigPath) {
351
- setEtag(path, etag);
399
+ if (isEchoableEtag(etag)) setEtag(path, etag);
400
+ else etagCache.delete(path);
352
401
  }
353
402
  if (isWrite && res.ok && isConfigPath) {
354
403
  invalidateRelated(path);
@@ -571,15 +620,96 @@ function formatResult(res) {
571
620
  }
572
621
 
573
622
  // src/tools/operational.ts
574
- var HTTPS_PORT_RE = /:443(?:\D|$)/;
575
- function describeServer(rawValue) {
623
+ var DEFAULT_HTTP_PORT = 80;
624
+ var DEFAULT_HTTPS_PORT = 443;
625
+ function appPort(value, fallback) {
626
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 65535 ? value : fallback;
627
+ }
628
+ function splitPort(hostport) {
629
+ const i = hostport.lastIndexOf(":");
630
+ if (i < 0) return void 0;
631
+ if (hostport.startsWith("[")) {
632
+ const end = hostport.indexOf("]");
633
+ if (end < 0 || end + 1 !== i) return void 0;
634
+ if (hostport.slice(1).includes("[") || hostport.slice(end + 1).includes("]")) return void 0;
635
+ } else {
636
+ if (hostport.slice(0, i).includes(":")) return void 0;
637
+ if (hostport.includes("[") || hostport.includes("]")) return void 0;
638
+ }
639
+ return hostport.slice(i + 1);
640
+ }
641
+ function parseListenPortRange(entry) {
642
+ let rest = entry;
643
+ const slash = entry.indexOf("/");
644
+ if (slash >= 0) {
645
+ const network = entry.slice(0, slash).trim().toLowerCase();
646
+ rest = entry.slice(slash + 1);
647
+ if (network.startsWith("unix") || network.startsWith("fd")) return { start: 0, end: 0 };
648
+ }
649
+ const port = splitPort(rest);
650
+ if (port === void 0 || port === "") return { start: 0, end: 0 };
651
+ const dash = port.indexOf("-");
652
+ const start = parseUint16(dash < 0 ? port : port.slice(0, dash));
653
+ const end = parseUint16(dash < 0 ? port : port.slice(dash + 1));
654
+ if (start === void 0 || end === void 0 || end < start) return void 0;
655
+ return { start, end };
656
+ }
657
+ function parseUint16(s) {
658
+ if (!/^[0-9]+$/.test(s)) return void 0;
659
+ const n = Number(s);
660
+ return n <= 65535 ? n : void 0;
661
+ }
662
+ function hasQualifyingHost(routes, skip) {
663
+ for (const route of routes) {
664
+ if (!route || typeof route !== "object") continue;
665
+ const matcherSets = route.match;
666
+ if (!Array.isArray(matcherSets)) continue;
667
+ for (const set of matcherSets) {
668
+ if (!set || typeof set !== "object") continue;
669
+ const hosts = set.host;
670
+ if (!Array.isArray(hosts)) continue;
671
+ for (const host of hosts) {
672
+ if (typeof host === "string" && !skip.has(host)) return true;
673
+ }
674
+ }
675
+ }
676
+ return false;
677
+ }
678
+ function describeServer(rawValue, httpPort = DEFAULT_HTTP_PORT, httpsPort = DEFAULT_HTTPS_PORT) {
576
679
  const raw = rawValue !== null && typeof rawValue === "object" && !Array.isArray(rawValue) ? rawValue : {};
577
680
  const listen = Array.isArray(raw.listen) ? raw.listen : [];
578
681
  const routes = Array.isArray(raw.routes) ? raw.routes : [];
682
+ const ranges = [];
683
+ for (const entry of listen) {
684
+ if (typeof entry !== "string") continue;
685
+ const range = parseListenPortRange(entry);
686
+ if (range) ranges.push(range);
687
+ }
688
+ const usesAnyPortOtherThan = (port) => ranges.some((r) => port > r.end || port < r.start);
689
+ const bindsPort = (port) => ranges.some((r) => r.start <= port && port <= r.end);
690
+ const autoHttps = raw.automatic_https !== null && typeof raw.automatic_https === "object" && !Array.isArray(raw.automatic_https) ? raw.automatic_https : {};
691
+ const skip = new Set(
692
+ Array.isArray(autoHttps.skip) ? autoHttps.skip.filter((s) => typeof s === "string") : []
693
+ );
694
+ const allSocketsOnHttpPort = (port) => ranges.length > 0 && ranges.every((r) => r.start === port && r.end === port);
695
+ 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
696
  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)";
697
+ let tls;
698
+ if (Array.isArray(tlsPolicies) && tlsPolicies.length === 0) {
699
+ tls = "off (empty tls_connection_policies)";
700
+ } else if (tlsPolicies) {
701
+ tls = perListener("enabled");
702
+ } else if (autoHttps.disable === true) {
703
+ tls = "off (automatic HTTPS disabled)";
704
+ } else if (!usesAnyPortOtherThan(httpPort)) {
705
+ tls = "off (HTTP only)";
706
+ } else if (!usesAnyPortOtherThan(httpsPort)) {
707
+ tls = perListener("auto (HTTPS)");
708
+ } else if (hasQualifyingHost(routes, skip)) {
709
+ tls = perListener("auto (HTTPS: host matchers on a non-HTTP port)");
710
+ } else {
711
+ tls = "off (no host matchers)";
712
+ }
583
713
  const listenStr = listen.length > 0 ? listen.map(String).join(", ") : "default";
584
714
  return `${routes.length} route(s), listen: ${listenStr}, TLS: ${tls}`;
585
715
  }
@@ -638,14 +768,17 @@ function registerOperationalTools(server) {
638
768
  const res = await configGet();
639
769
  if (!res.ok) return formatResult(res);
640
770
  const config = res.data ?? {};
641
- const servers = config.apps?.http?.servers ?? {};
771
+ const httpApp = config.apps?.http;
772
+ const servers = httpApp?.servers ?? {};
642
773
  const serverNames = Object.keys(servers);
774
+ const httpPort = appPort(httpApp?.http_port, DEFAULT_HTTP_PORT);
775
+ const httpsPort = appPort(httpApp?.https_port, DEFAULT_HTTPS_PORT);
643
776
  const lines = ["Caddy is running", ""];
644
777
  if (serverNames.length === 0) {
645
778
  lines.push("No HTTP servers configured");
646
779
  } else {
647
780
  for (const name of serverNames) {
648
- lines.push(`Server "${name}": ${describeServer(servers[name])}`);
781
+ lines.push(`Server "${name}": ${describeServer(servers[name], httpPort, httpsPort)}`);
649
782
  }
650
783
  }
651
784
  const email = findAcmeEmail(config.apps?.tls?.automation?.policies);
@@ -679,7 +812,7 @@ ${lines.join("\n")}` }]
679
812
  );
680
813
  server.tool(
681
814
  "caddy_upstreams",
682
- "Get the current health status of all reverse proxy upstreams. Shows address, active requests, and failure counts.",
815
+ "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
816
  {},
684
817
  { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
685
818
  async () => formatResult(await getUpstreams())
@@ -753,7 +886,9 @@ function registerResources(server) {
753
886
  server.resource(
754
887
  "caddy-upstreams",
755
888
  "caddy://upstreams",
756
- { description: "Reverse proxy upstream health status" },
889
+ {
890
+ 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."
891
+ },
757
892
  async () => {
758
893
  const res = await getUpstreams();
759
894
  return {
@@ -829,7 +964,7 @@ function formatWarning2(w) {
829
964
  function registerAdaptTools(server) {
830
965
  server.tool(
831
966
  "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.",
967
+ `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
968
  {
834
969
  config: z2.string().describe("The raw config text (e.g., Caddyfile contents, nginx.conf, yaml)"),
835
970
  adapter: z2.string().regex(/^[a-z0-9_-]+$/, "Adapter must be lowercase alphanumeric, hyphens, or underscores").max(64).optional().default("caddyfile").describe(
@@ -939,6 +1074,9 @@ function getSnapshot(index) {
939
1074
  }
940
1075
 
941
1076
  // src/tools/config.ts
1077
+ function isRootConfigPath(path) {
1078
+ return /^\/*$/.test(path.replace(/^\/?(config(\/|$))?/, ""));
1079
+ }
942
1080
  function registerConfigTools(server) {
943
1081
  server.tool(
944
1082
  "caddy_config_get",
@@ -965,7 +1103,7 @@ function registerConfigTools(server) {
965
1103
  );
966
1104
  server.tool(
967
1105
  "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.",
1106
+ "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/', and slash-only variants of those) 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
1107
  {
970
1108
  path: z3.string().describe("Config path to delete (e.g., 'apps/http/servers/srv0/routes/0')"),
971
1109
  confirm: z3.boolean().optional().default(false).describe("Must be true to actually delete the config node (safety)")
@@ -976,22 +1114,49 @@ function registerConfigTools(server) {
976
1114
  // array after a delete, so repeating that call removes a DIFFERENT route each
977
1115
  // time. caddy_remove_route carries the same correction for the byte-identical
978
1116
  // 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.
1117
+ // either: apart from a root delete (below), only caddy_load captures a
1118
+ // snapshot, so a spurious repeat cannot be undone with caddy_revert.
981
1119
  { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
982
1120
  async ({ path, confirm }) => {
1121
+ const root = isRootConfigPath(path);
983
1122
  if (!confirm) {
984
1123
  return {
985
1124
  isError: true,
986
1125
  content: [
987
1126
  {
988
1127
  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.`
1128
+ 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
1129
  }
991
1130
  ]
992
1131
  };
993
1132
  }
994
- return formatResult(await configDelete(path));
1133
+ if (!root) return formatResult(await configDelete(path));
1134
+ const current = await configGet();
1135
+ const res = await configDelete("");
1136
+ const kept = (res.ok || res.outcomeUnknown === true) && current.ok && isSnapshotableConfig(current.data);
1137
+ if (kept) saveSnapshot(current.data, "caddy_config_delete");
1138
+ if (!res.ok) {
1139
+ if (res.outcomeUnknown && kept) {
1140
+ return formatResult({
1141
+ ...res,
1142
+ error: `${res.error}
1143
+ 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.`
1144
+ });
1145
+ }
1146
+ return formatResult(res);
1147
+ }
1148
+ const note = kept ? ` The prior config was saved as snapshot [0] (trigger=caddy_config_delete): caddy_revert { action: "apply", index: 0, confirm: true } restores it.` : 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 unload cannot be reverted.";
1149
+ const adm = kept ? current.data.admin : void 0;
1150
+ const listen = adm !== null && typeof adm === "object" && !Array.isArray(adm) ? adm.listen : void 0;
1151
+ const adminNote = typeof listen === "string" && listen !== "" ? ` 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.` : "";
1152
+ return {
1153
+ content: [
1154
+ {
1155
+ type: "text",
1156
+ text: `Unloaded the entire config (every app and server, and the 'admin' block).${note}${adminNote}`
1157
+ }
1158
+ ]
1159
+ };
995
1160
  }
996
1161
  );
997
1162
  server.tool(
@@ -1032,7 +1197,7 @@ The pre-load config was kept anyway, as snapshot [0] (trigger=caddy_load): if th
1032
1197
  );
1033
1198
  server.tool(
1034
1199
  "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).",
1200
+ "Manage config snapshots for rollback. Snapshots are auto-captured before caddy_load, and before a caddy_config_delete that unloads the whole config (an empty path); no other delete 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
1201
  {
1037
1202
  action: z3.enum(["list", "save", "apply"]).describe("Action to perform"),
1038
1203
  index: z3.number().int().nonnegative().optional().default(0).describe("Snapshot index for 'apply' (0 = most recent, default)"),
@@ -1819,7 +1984,7 @@ function registerTlsTools(server) {
1819
1984
  email: z5.string().optional().describe("ACME email address (for 'set_email' action)"),
1820
1985
  ca: z5.string().optional().describe("ACME CA URL (for 'set_acme_ca' action)"),
1821
1986
  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."
1987
+ "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
1988
  )
1824
1989
  },
1825
1990
  { 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.4",
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",