panelica-mcp 0.2.2 → 0.5.2

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
@@ -6,7 +6,7 @@
6
6
  > [Model Context Protocol](https://modelcontextprotocol.io) client.
7
7
 
8
8
  [![npm](https://img.shields.io/npm/v/panelica-mcp?color=CB3837&logo=npm)](https://www.npmjs.com/package/panelica-mcp)
9
- [![Tools](https://img.shields.io/badge/tools-404-blue)](tools/tools.json)
9
+ [![Tools](https://img.shields.io/badge/tools-422-blue)](tools/tools.json)
10
10
  [![Scopes](https://img.shields.io/badge/permission%20scopes-50-8A2BE2)](#permission-scopes)
11
11
  [![Docker](https://img.shields.io/badge/ghcr.io-panelica%2Fpanelica--mcp-2496ED?logo=docker&logoColor=white)](https://github.com/Panelica/panelica-mcp/pkgs/container/panelica-mcp)
12
12
  [![Zero drift](https://img.shields.io/badge/catalogue-auto--generated%20weekly-brightgreen)](#keeping-the-tool-catalogue-current)
@@ -81,12 +81,20 @@ SSL, email, MySQL, FTP, security, backups, server resources, and more.
81
81
  `panelica-mcp` is a thin, stateless adapter:
82
82
 
83
83
  1. The MCP client launches the binary over stdio.
84
- 2. The client asks for the tool list — the server reads `tools/tools.json`
85
- (404 entries, auto-generated from the panel's live API spec) and returns it.
86
- 3. When the client calls a tool, the server builds the corresponding HTTP
84
+ 2. At startup the server fetches `<PANELICA_BASE_URL>/v1/api-spec` from **your**
85
+ panel and builds the tool list from it (live catalogue, default). If the panel
86
+ is unreachable it falls back to the bundled `tools/tools.json` snapshot. Set
87
+ `PANELICA_LIVE_SPEC=0` to always use the snapshot.
88
+ 3. The client asks for the tool list and receives it — together with **server
89
+ instructions** (how ids, scopes, response envelopes, errors and rate limits
90
+ work, plus workflow recipes), generated from that same catalogue. See
91
+ [What the assistant knows](#what-the-assistant-knows).
92
+ 4. When the client calls a tool, the server builds the corresponding HTTP
87
93
  request, signs it with HMAC-SHA256 using your local `PANELICA_API_SECRET`,
88
94
  and forwards it to the panel.
89
- 4. The HTTP response is returned to the client as the tool result.
95
+ 5. The HTTP response is returned to the client as the tool result. A failed
96
+ call comes back as an explanation of what to do next (missing scope, wrong
97
+ id, rate-limit reset…) rather than a bare status code.
90
98
 
91
99
  No data is cached, no telemetry is emitted, and the secret never leaves the
92
100
  machine running the MCP server.
@@ -212,8 +220,10 @@ verification client-side.
212
220
  API keys.
213
221
  2. Navigate to **Settings → API Keys → Generate API Key**.
214
222
  3. Pick the scopes you want the MCP server to have. For a read-only assistant,
215
- `*:read` is enough. For full automation, grant `*:write` too. Every tool's
216
- `description` in this server lists the scopes it requires.
223
+ `*:read` is enough (panel 1.0.528+; older panels need the individual
224
+ `<area>:read` scopes). For full automation grant `*:write` and `*:delete`
225
+ too, or `*:*`. Every tool's `description` in this server lists the scopes it
226
+ requires.
217
227
  4. Copy both **key** (looks like `pk_...`) and **secret** (looks like `sk_...`).
218
228
  The secret is shown **only once**; store it in a password manager.
219
229
 
@@ -248,6 +258,17 @@ You should get back JSON listing your API keys. Common 401 responses:
248
258
  | `INVALID_TIMESTAMP` | Local clock drifted more than 5 minutes — sync NTP |
249
259
  | `INVALID_SIGNATURE` | Wrong secret, **or** the path you signed includes `/api/external/` (it must not — nginx strips it before the backend sees it) |
250
260
 
261
+ ### 4. Optional environment variables
262
+
263
+ | Variable | Default | Effect |
264
+ |---|---|---|
265
+ | `PANELICA_TOOLSETS` | `core` | Which tools are registered directly — see [Toolsets](#toolsets--what-the-client-sees) |
266
+ | `PANELICA_LIVE_SPEC` | `1` | Build the catalogue from your panel's `/v1/api-spec` at startup; `0` = bundled snapshot only |
267
+ | `PANELICA_SPEC_TIMEOUT_MS` | `8000` | Live-spec fetch timeout before falling back to the snapshot |
268
+ | `PANELICA_TIMEOUT_MS` | `30000` | Per-call HTTP timeout |
269
+ | `PANELICA_MAX_RESULT_CHARS` | `60000` | Larger list results are cut to the first items with a `_truncated` note so the client context is not flooded |
270
+ | `PANELICA_STARTUP_PROBE` | `1` | Call `GET /v1/me` once at startup to state the key's scopes in the instructions; `0` skips it |
271
+
251
272
  ## Wire it into your MCP client
252
273
 
253
274
  ### Claude Code (one command)
@@ -289,7 +310,7 @@ Edit your Claude Desktop config:
289
310
 
290
311
  Save, fully quit Claude Desktop (not just close the window — *Quit*), and
291
312
  re-open it. A new chat will show `panelica` as a connected MCP server with
292
- "404 tools available".
313
+ "37 tools available" (the core set plus three meta tools; set `PANELICA_TOOLSETS=all` for all 422).
293
314
 
294
315
  ### Cursor
295
316
 
@@ -342,14 +363,110 @@ panelica-mcp
342
363
  The process speaks MCP JSON-RPC over stdin/stdout. Send an `initialize`
343
364
  request first, then `tools/list`, then `tools/call`.
344
365
 
366
+ ## Toolsets — what the client sees
367
+
368
+ MCP clients budget tools: Cursor caps active tools at about 40 across all
369
+ servers and silently drops the rest, and every registered tool costs prompt
370
+ tokens on each turn. So by default the server registers a compact **core** set
371
+ (34 everyday tools: accounts, domains, DNS, SSL, databases, e-mail, FTP,
372
+ backups, server status/services, WordPress, Docker, plans) plus three meta
373
+ tools that reach the whole catalogue:
374
+
375
+ | Tool | What it does |
376
+ |---|---|
377
+ | `panelica_find_tools` | Keyword search over every catalogue tool; returns names, HTTP route, parameters, body fields and what each returns |
378
+ | `panelica_describe_tool` | One tool in full: every parameter with its provenance, body fields (type, required), the response envelope and its data fields |
379
+ | `panelica_call` | Runs any catalogue tool by name with its arguments (same scoped, HMAC-signed client) |
380
+
381
+ Choose the set with `PANELICA_TOOLSETS` (comma-separated, unioned):
382
+
383
+ | Value | Registered tools |
384
+ |---|---|
385
+ | `core` (default) | 34 + 3 meta |
386
+ | `all` | every catalogue tool + 3 meta (the pre-0.3 behaviour; fine for Claude Code / Claude Desktop) |
387
+ | `none` | only the 3 meta tools |
388
+ | category slugs, e.g. `domains,dns,ssl,git,docker,file_manager,laravel_apps,node_js_apps,python_apps,logs` | those categories (+ `core` if listed) |
389
+
390
+ Direct calls to a non-registered catalogue tool are still accepted, so a
391
+ client that learned a tool name from `panelica_find_tools` can call it either
392
+ way.
393
+
394
+ ## What the assistant knows
395
+
396
+ An assistant that only sees 400 tool names guesses ids, retries 403s and
397
+ misreads responses. `panelica-mcp` gives it the API "by heart" instead, and
398
+ everything below is generated from the catalogue, so it can never promise a
399
+ path the panel does not have:
400
+
401
+ - **Server instructions** (sent on `initialize`, so every client injects them
402
+ into the model's context): how calls work, that every id is a UUID coming
403
+ from a list call, that users are called *accounts*, the
404
+ `{"status":"success","data":…}` envelope, unpaginated lists, what each error
405
+ class means and what to do, scope families, the category map with counts,
406
+ safety rules for mutating/destructive tools, and workflow recipes that are
407
+ included only when every step exists in the catalogue.
408
+ - **Your key, up front.** At startup the server calls `GET /v1/me` once and
409
+ tells the model which key it holds, its scopes, tier and expiry — so a
410
+ read-only key is announced as read-only and out-of-scope tools are declined
411
+ with the scope to add, not attempted. A rejected credential is reported in
412
+ the instructions before the first tool call. (`PANELICA_STARTUP_PROBE=0`
413
+ disables the probe.)
414
+ - **Scopes as the code enforces them.** Newer panels derive the required scopes
415
+ from the middleware chain instead of hand-written docs, including "one of a,
416
+ b" rules and role restrictions (ROOT/ADMIN); the tool description repeats
417
+ them verbatim.
418
+ - **Allowed values.** Fields with a declared value list (`ssl_provider`,
419
+ `web_server`, `restart_policy` …) carry a JSON-schema `enum` and `default`,
420
+ so the model does not guess.
421
+ - **Big lists stay usable.** Every list-returning GET accepts `_limit`,
422
+ `_fields` and `_match`; the server applies them to the response (the panel
423
+ never sees them) and reports `{total, matched, shown}` so a 500-domain panel
424
+ can be searched in one call.
425
+ - **Validation errors name the field.** A Gin validation failure becomes
426
+ `field "user_id" is required` / `field "type" must be one of the allowed
427
+ values` using the JSON names the model used.
428
+ - **Search speaks the user's language.** `panelica_find_tools` maps
429
+ website→domain, certificate→ssl, mailbox→email, container→docker and stems
430
+ plurals, so the first query finds the right tool.
431
+ - **Transient limits are absorbed.** A 429 whose window resets within 15 s is
432
+ waited out once; a GET that fails on the network is retried once; a clock
433
+ skew above two minutes against the panel is flagged in the instructions
434
+ (HMAC timestamps would be rejected).
435
+ - **Per-tool descriptions** carry the HTTP route, required scopes, a
436
+ `Returns:` line with the response envelope and the first data fields, and the
437
+ risk class (read-only / mutating / destructive).
438
+ - **Id parameters say where they come from** — `UUID of the domain — obtain
439
+ it from GET /v1/domains` — for path, query and body fields alike. Newer
440
+ panels ship this in the spec; for older panels the server derives it.
441
+ - **`panelica_describe_tool`** returns the exact parameters, body fields and
442
+ response fields of one tool, so the model checks before it calls.
443
+ - **Errors are explained, not echoed**: a 403 names the missing scope and says
444
+ retrying cannot help; a 404 says to re-list and use a real id; a 429 reports
445
+ the reset window; 5xx says to report, not loop. The raw panel response is
446
+ appended for reference.
447
+ - **Results are bounded**: oversized list responses are cut to the first items
448
+ with an explicit `_truncated` note (still valid JSON) instead of flooding the
449
+ context.
450
+ - **Resources** for clients that support them: `panelica://guide` (the
451
+ instructions), `panelica://catalogue` (every tool with route and summary) and,
452
+ in live mode, `panelica://spec` (your panel's full API spec).
453
+
454
+ The response-field lists come from the panel's `/v1/api-spec`, which newer
455
+ panels derive from their handler source at build time; a panel that predates
456
+ this still works — its tools simply show `{status, data}` without field names.
457
+
345
458
  ## Tool catalogue
346
459
 
347
- **404 tools** are auto-generated from the panel's live `/v1/api-spec`, so they never
460
+ **422 tools** are auto-generated from the panel's live `/v1/api-spec`, so they never
348
461
  drift from the API. Each tool carries MCP safety annotations
349
462
  (![read-only](https://img.shields.io/badge/-read--only-brightgreen) 181 ·
350
463
  ![mutating](https://img.shields.io/badge/-mutating-orange) 177 ·
351
464
  ![destructive](https://img.shields.io/badge/-destructive-red) 46)
352
465
  that capable clients use to auto-approve reads and warn before destructive calls.
466
+ Body fields and query parameters are derived from the panel's handler code
467
+ (`gen-external-schemas` in the panel repository), so on panels from 1.0.528 on
468
+ mutating tools carry typed, required-marked bodies and action endpoints such as
469
+ `…/suspend` or `…/restart` declare that they take no body at all.
353
470
 
354
471
  | Category | Tools |
355
472
  |----------|------:|
@@ -476,6 +593,14 @@ Every family also accepts its wildcard (`domains:*`) and `*:*` grants everything
476
593
  Mutating service control deliberately requires its own action scopes (or
477
594
  `server:write`) — a metrics-only `server:read` key can **not** stop MySQL.
478
595
 
596
+ ## Rate limits
597
+
598
+ API keys carry a rate-limit tier (`rate_limit_tier` when creating the key:
599
+ `starter` 60/min, `professional` 300/min, `business` 1000/min, `enterprise`
600
+ unlimited). The default `starter` tier is easy to exhaust when an assistant
601
+ fans out many calls; create the assistant's key with a higher tier if you see
602
+ `429 RATE_LIMIT_EXCEEDED` (the response carries `reset_at`).
603
+
479
604
  ## Security model
480
605
 
481
606
  - **HMAC-SHA256 request signing.** Every request is signed over
@@ -506,8 +631,11 @@ Mutating service control deliberately requires its own action scopes (or
506
631
  | `401 INVALID_SIGNATURE` | Wrong `PANELICA_API_SECRET`, or clock drift > 5 min | `chronyc tracking` (or `timedatectl status`) on both the MCP host and panel host |
507
632
  | `401 INVALID_TIMESTAMP` | Local clock drift > 5 min | Sync NTP on the MCP host |
508
633
  | Connect timeout on `BASE_URL` | Wrong host/port — typically `:8443/api/external` was missed off the URL | Verify with `curl -sk $PANELICA_BASE_URL/health` — should return `{"status":"ok"}` |
509
- | `403 FORBIDDEN` on a tool | API key lacks the required scope | Regenerate the key in the panel with the scope listed in the tool's description |
510
- | Tool description says "Schema not statically extractable" | The endpoint uses dynamic request bodies | Pass a free-form `body` object; the panel will validate and tell you the missing fields with a 400 response |
634
+ | Tool result starts with `Panelica API error 403` and names a scope | API key lacks that scope | Add the scope to the key in the panel (Settings → API Keys); the assistant is told not to retry |
635
+ | Tool result says `Panelica API error 404 … re-list` | The assistant used an id that does not exist for this key's owner | Nothing to fix server-side; the guidance makes it list again and pick a real id |
636
+ | Tool description says "Schema not statically declared" | The endpoint binds a dynamic request body (map / multipart) | Pass a free-form `body` object; the panel validates and answers 400 with the missing field, which the assistant is told to read |
637
+ | Startup log says `clock skew of Ns versus the panel` | The MCP host's clock is off | Sync NTP on the MCP host; signed requests carry a timestamp the panel checks |
638
+ | Startup log says `startup credential check failed` | Key/secret rejected by `GET /v1/me` | The instructions already tell the assistant; fix the key in the panel and restart the client |
511
639
  | TLS verification fails | Panel is using its self-signed cert | If the MCP host trusts that CA, this works out of the box. If not, deploy a real cert on the panel (panel UI → Settings → SSL) — do not disable TLS verification client-side |
512
640
 
513
641
  If you are still stuck, open an issue at
@@ -528,13 +656,17 @@ Project layout:
528
656
 
529
657
  ```
530
658
  .
531
- ├── src/index.ts # MCP server (stdio transport, HMAC client)
659
+ ├── src/index.ts # MCP server (stdio transport, HMAC client, live-spec loader)
660
+ ├── src/catalog.ts # spec → tools generator (shared by runtime and build script)
661
+ ├── src/toolsets.ts # core set, PANELICA_TOOLSETS selection, find/describe/call meta tools
662
+ ├── src/instructions.ts # server instructions generated from the catalogue
663
+ ├── src/errors.ts # error explanations + result bounding
532
664
  ├── tools/
533
665
  │ ├── build-tools.mjs # Generates tools.json from the API spec
534
666
  │ ├── api-spec.json # Committed snapshot of the live /v1/api-spec
535
- │ └── tools.json # 404 tool definitions, auto-generated (committed)
667
+ │ └── tools.json # tool definitions, auto-generated (committed)
536
668
  ├── .github/workflows/
537
- │ └── refresh-tools.yml # Weekly CI: regenerate from the live API, commit if changed
669
+ │ └── refresh-tools.yml # Weekly CI: regenerate, bump, tag, publish npm + Docker + Registry
538
670
  ├── Dockerfile
539
671
  ├── smithery.yaml # Smithery deployment manifest
540
672
  ├── .env.example
@@ -556,8 +688,11 @@ PANELICA_SPEC_URL="https://your-panel:8443/api/external/v1/api-spec" npm run reb
556
688
  ```
557
689
 
558
690
  CI (`refresh-tools.yml`) runs this weekly against the panel named in the
559
- `PANELICA_SPEC_URL` repository variable and commits any changes, so a new API
560
- endpoint becomes an MCP tool automatically. Each tool is tagged with safety
691
+ `PANELICA_SPEC_URL` repository **secret**. When the catalogue changed it bumps the
692
+ patch version, tags, and publishes npm, the Docker image and the MCP Registry
693
+ entry in the same run, so a new API endpoint reaches `npx -y panelica-mcp`
694
+ users automatically. Running servers do not even need that: with the default
695
+ live catalogue they read the spec from the panel they talk to. Each tool is tagged with safety
561
696
  annotations (`readOnlyHint` for `GET`, `destructiveHint` for `DELETE`) that
562
697
  capable MCP clients use to auto-approve reads and warn before destructive calls.
563
698
 
@@ -572,7 +707,10 @@ and training jsonl files are not part of the public repository.
572
707
  change only when the panel itself ships a backward-incompatible API change,
573
708
  and the package's major version is bumped to match.
574
709
  - New endpoints become available the next time we regenerate
575
- `tools/tools.json` and publish a release.
710
+ `tools/tools.json` and publish a release — or immediately, in live mode,
711
+ from your own panel's `/v1/api-spec`.
712
+ - Response-field lists, id provenance and cleaned descriptions come from the
713
+ panel's spec; a panel that predates them still works with plainer tools.
576
714
  - Panel issues (the API itself, not this client): the Panelica forum at
577
715
  [forum.panelica.com](https://forum.panelica.com).
578
716
  - Client / packaging issues:
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Catalogue builder — turns a Panelica External API spec (`/v1/api-spec`) into
3
+ * MCP tool definitions.
4
+ *
5
+ * ZERO-DRIFT by construction: the backend generates the spec at runtime from its
6
+ * route registry, so every tool here mirrors a real endpoint. The same code path
7
+ * serves two consumers:
8
+ * - tools/build-tools.mjs → writes the committed tools/tools.json snapshot
9
+ * - src/index.ts → live mode: fetches the spec from the operator's
10
+ * own panel at startup and builds tools in memory
11
+ *
12
+ * Everything user-visible passes through redactStr(): UUIDs, private IPs,
13
+ * e-mail addresses and panel paths from the spec never reach an LLM prompt or
14
+ * the public repository.
15
+ *
16
+ * MCP tool name format: panelica_<category-slug>_<method>_<path-slug> (≤ 64 chars).
17
+ */
18
+ import { createHash } from "node:crypto";
19
+ // ── Redaction ─────────────────────────────────────────────────────────────────
20
+ // Defensive: the spec is metadata, but a panel operator may have customised
21
+ // descriptions. Nothing that looks like an identifier or an address gets through.
22
+ const REDACTORS = [
23
+ { re: /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, sub: "<uuid>" },
24
+ // Any IPv4 (private or public), with an optional :port.
25
+ { re: /\b(?:\d{1,3}\.){3}\d{1,3}(?::\d{2,5})?\b/g, sub: "<ip>" },
26
+ { re: /\b[\w.+-]+@[\w-]+\.[\w.-]+\b/g, sub: "<email>" },
27
+ // A bare "@domain.tld" (catch-all forwarders, sender block rules) has no local
28
+ // part, so the rule above leaves it; the CI leak guard still flags it.
29
+ { re: /(^|[^\w.+-])@[\w-]+\.[\w.-]+\b/g, sub: "$1@<domain>" },
30
+ { re: /\/opt\/panelica[\w/.-]*/g, sub: "<path>" },
31
+ { re: /\/home\/[\w.-]+[\w/.-]*/g, sub: "<path>" },
32
+ { re: /\b(?:pk|sk)_[A-Za-z0-9]{8,}\b/g, sub: "<key>" },
33
+ ];
34
+ export function redactStr(s) {
35
+ let out = String(s ?? "");
36
+ for (const r of REDACTORS)
37
+ out = out.replace(r.re, r.sub);
38
+ return out;
39
+ }
40
+ /** Deep-redact a whole spec (used before the snapshot is written to the public repo). */
41
+ export function deepRedact(v) {
42
+ if (typeof v === "string")
43
+ return redactStr(v);
44
+ if (Array.isArray(v))
45
+ return v.map(deepRedact);
46
+ if (v && typeof v === "object") {
47
+ const o = {};
48
+ for (const [k, val] of Object.entries(v))
49
+ o[k] = deepRedact(val);
50
+ return o;
51
+ }
52
+ return v;
53
+ }
54
+ // ── Helpers ───────────────────────────────────────────────────────────────────
55
+ /** The spec renders path params as {name}; the runtime substitutes :name. */
56
+ export function toColonPath(p) {
57
+ return String(p ?? "").replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, ":$1");
58
+ }
59
+ function slugify(s) {
60
+ return String(s ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
61
+ }
62
+ function toolName(method, path, category) {
63
+ const cat = slugify(category || "misc");
64
+ const m = String(method || "get").toLowerCase();
65
+ let name = `panelica_${cat}_${m}_${slugify(path)}`;
66
+ if (name.length > 64) {
67
+ const hash = createHash("sha1").update(name).digest("hex").slice(0, 8);
68
+ name = `${name.slice(0, 55)}_${hash}`;
69
+ }
70
+ return name;
71
+ }
72
+ function jsonType(t) {
73
+ return t === "uuid" ? "string" : (t || "string");
74
+ }
75
+ /**
76
+ * Where an id parameter comes from, for panels whose spec predates the
77
+ * server-side hint: "id" → the collection right before it in the
78
+ * path, "<x>_id" → the collection <x>s. Only used when the spec has no description.
79
+ */
80
+ const ID_ALIASES = { user: "accounts", account: "accounts", key: "api-keys", zone: "dns/zones" };
81
+ export function idHint(name, path, lists, type) {
82
+ let stem = "";
83
+ if (name === "id") {
84
+ const segs = path.split("/");
85
+ const i = segs.indexOf("{id}");
86
+ if (i > 0)
87
+ stem = segs[i - 1];
88
+ }
89
+ else if (name.endsWith("_id")) {
90
+ stem = name.slice(0, -3);
91
+ }
92
+ if (!stem)
93
+ return "";
94
+ const singular = stem.endsWith("ies") ? stem.slice(0, -3) + "y" : stem.replace(/(es|s)$/, "");
95
+ const candidates = [ID_ALIASES[singular] ? `/v1/${ID_ALIASES[singular]}` : "", `/v1/${stem}`, `/v1/${singular}s`, `/v1/${singular}es`].filter(Boolean);
96
+ const kind = type === "uuid" ? "UUID" : "ID";
97
+ const label = singular.replace(/_/g, " ");
98
+ const list = candidates.find((c) => lists.has(c));
99
+ return list ? `${kind} of the ${label} — obtain it from GET ${list}` : `${kind} of the ${label}`;
100
+ }
101
+ /** List-returning GET tools get _limit/_fields/_match (client-side shaping). */
102
+ export function shapingApplies(ep) {
103
+ if (String(ep.method).toUpperCase() !== "GET")
104
+ return false;
105
+ const dt = ep.response?.data_type;
106
+ if (dt)
107
+ return dt === "array";
108
+ return !String(ep.path).includes("{"); // unknown shape: collections without an id are lists
109
+ }
110
+ function buildInputSchema(ep, lists) {
111
+ const properties = {};
112
+ const required = [];
113
+ const req = ep.request || {};
114
+ const hint = (name, type) => idHint(name, ep.path, lists, type);
115
+ const withEnum = (schema, f) => {
116
+ if (f.enum?.length)
117
+ schema.enum = f.enum;
118
+ if (f.default !== undefined && f.default !== "")
119
+ schema.default = f.default;
120
+ return schema;
121
+ };
122
+ for (const p of req.path_params ?? []) {
123
+ properties[p.name] = withEnum({ type: jsonType(p.type), description: redactStr(p.description || hint(p.name, p.type) || `Path parameter: ${p.name}`) }, p);
124
+ if (p.required !== false)
125
+ required.push(p.name);
126
+ }
127
+ for (const q of req.query_params ?? []) {
128
+ properties[q.name] = withEnum({ type: jsonType(q.type), description: redactStr(q.description || hint(q.name, q.type) || `Query parameter: ${q.name}`) }, q);
129
+ if (q.required)
130
+ required.push(q.name);
131
+ }
132
+ if (shapingApplies(ep)) {
133
+ properties._limit = { type: "integer", description: "Keep only the first N items of the returned list (applied by this MCP server, not the panel). Use on large lists." };
134
+ properties._fields = { type: "string", description: "Comma-separated item fields to keep, e.g. \"id,domain_name,php_version\" — trims large items to what you need." };
135
+ properties._match = { type: "string", description: "Keep only items whose JSON contains this text (case-insensitive), e.g. a domain name or status." };
136
+ }
137
+ const body = req.body || {};
138
+ if (body.content_type === "none") {
139
+ // The panel declares this mutating endpoint takes no request body
140
+ // (action endpoints such as …/suspend, …/restart): no body property.
141
+ }
142
+ else if (body.fields?.length) {
143
+ properties.body = {
144
+ type: "object",
145
+ description: `Request body (${body.content_type || "application/json"})`,
146
+ properties: Object.fromEntries(body.fields.map((f) => [f.name, withEnum({
147
+ type: jsonType(f.type),
148
+ description: redactStr(f.description || hint(f.name, f.type) || ""),
149
+ }, f)])),
150
+ required: body.fields.filter((f) => f.required).map((f) => f.name),
151
+ };
152
+ if (body.required)
153
+ required.push("body");
154
+ }
155
+ else if (["POST", "PUT", "PATCH"].includes(ep.method)) {
156
+ properties.body = {
157
+ type: "object",
158
+ description: `Request body (${body.content_type || "application/json"}). Schema not statically declared — see API docs.`,
159
+ additionalProperties: true,
160
+ };
161
+ }
162
+ return { type: "object", properties, required: [...new Set(required)], additionalProperties: false };
163
+ }
164
+ /** MCP tool annotations: clients auto-approve read-only calls and warn before destructive ones. */
165
+ function annotations(ep) {
166
+ const m = String(ep.method || "GET").toUpperCase();
167
+ const readOnly = m === "GET" || m === "HEAD";
168
+ const destructive = m === "DELETE";
169
+ return {
170
+ title: redactStr(ep.summary || `${m} ${ep.path}`),
171
+ readOnlyHint: readOnly,
172
+ destructiveHint: destructive,
173
+ idempotentHint: readOnly || m === "PUT" || m === "DELETE",
174
+ openWorldHint: true, // reaches an external panel over the network
175
+ };
176
+ }
177
+ /** Compact "Returns:" line: the envelope plus the first field names of data. */
178
+ export function returnsLine(r, maxNames = 12) {
179
+ if (!r || !r.data_type)
180
+ return "";
181
+ const names = (r.fields ?? []).map((f) => f.name);
182
+ const shown = names.slice(0, maxNames).join(", ") + (names.length > maxNames ? `, … (+${names.length - maxNames} more)` : "");
183
+ const extra = (r.keys ?? []).filter((k) => k !== "status" && k !== "data");
184
+ if (r.data_type === "none") {
185
+ return `Returns: {status${names.length ? ", " + names.join(", ") : ""}}`;
186
+ }
187
+ const item = names.length ? ` {${shown}}` : "";
188
+ const data = r.data_type === "array" ? `array of${item || " items"}` : (r.data_type === "object" ? `object${item}` : r.data_type);
189
+ return `Returns: {status, data: ${data}${extra.length ? ", " + extra.join(", ") : ""}}`;
190
+ }
191
+ function toolResponse(r) {
192
+ if (!r || !r.data_type)
193
+ return undefined;
194
+ const out = { data_type: r.data_type };
195
+ if (r.keys?.length)
196
+ out.keys = r.keys;
197
+ if (r.fields?.length)
198
+ out.fields = r.fields.map((f) => ({ name: f.name, type: jsonType(f.type), ...(f.description ? { description: redactStr(f.description) } : {}) }));
199
+ return out;
200
+ }
201
+ export function scopesLine(ep) {
202
+ const a = ep.auth ?? {};
203
+ const parts = [];
204
+ if (a.scope_rule)
205
+ parts.push(`Required scopes: ${a.scope_rule}`);
206
+ else if (a.scopes?.length)
207
+ parts.push(`Required scopes: ${a.scopes.join(", ")}`);
208
+ else if (a.required)
209
+ parts.push("Required scopes: none (any valid API key)");
210
+ if (a.roles?.length)
211
+ parts.push(`Restricted to key owners with role: ${a.roles.join(", ")}`);
212
+ return parts.join("\n");
213
+ }
214
+ function buildDescription(ep) {
215
+ const colon = toColonPath(ep.path);
216
+ const scopes = scopesLine(ep);
217
+ const risk = ep.method === "DELETE"
218
+ ? "WARNING: destructive — permanently removes the resource."
219
+ : (["POST", "PUT", "PATCH"].includes(ep.method) ? "Mutating: changes server state." : "Read-only.");
220
+ return [
221
+ redactStr(ep.description || ep.summary || `${ep.method} ${colon}`),
222
+ `\nHTTP: ${ep.method} ${colon}`,
223
+ `Category: ${redactStr(ep.category)}`,
224
+ scopes,
225
+ redactStr(returnsLine(ep.response)),
226
+ risk,
227
+ ].filter(Boolean).join("\n");
228
+ }
229
+ /** Meta / non-REST endpoints that are not tools (unauthenticated, WebSocket, ticket minting for WS). */
230
+ const SKIP_PATHS = /^\/(health|v1\/api-spec|v1\/postman-collection|v1\/metrics\/ws|v1\/metrics\/ws-ticket|v1\/terminal\/ws)$/;
231
+ /** Build the sorted tool list from a spec. Pure; no I/O. */
232
+ export function buildTools(spec) {
233
+ const endpoints = spec.endpoints ?? [];
234
+ const stats = { total: endpoints.length, emitted: 0, skipped: 0, read: 0, mutate: 0, destructive: 0 };
235
+ const seen = new Set();
236
+ const tools = [];
237
+ // GET collections (no path params): where ids are discovered.
238
+ const lists = new Set(endpoints.filter((e) => e.method === "GET" && e.path && !e.path.includes("{")).map((e) => e.path));
239
+ for (const ep of endpoints) {
240
+ if (!ep.method || !ep.path) {
241
+ stats.skipped++;
242
+ continue;
243
+ }
244
+ if (SKIP_PATHS.test(ep.path)) {
245
+ stats.skipped++;
246
+ continue;
247
+ }
248
+ let name = toolName(ep.method, ep.path, ep.category);
249
+ while (seen.has(name))
250
+ name = `${name.slice(0, 55)}_${createHash("sha1").update(name + tools.length).digest("hex").slice(0, 8)}`;
251
+ seen.add(name);
252
+ const m = String(ep.method).toUpperCase();
253
+ if (m === "GET" || m === "HEAD")
254
+ stats.read++;
255
+ else if (m === "DELETE")
256
+ stats.destructive++;
257
+ else
258
+ stats.mutate++;
259
+ tools.push({
260
+ name,
261
+ description: buildDescription(ep),
262
+ inputSchema: buildInputSchema(ep, lists),
263
+ annotations: annotations(ep),
264
+ metadata: {
265
+ method: m,
266
+ path: toColonPath(ep.path),
267
+ category: redactStr(ep.category || "misc"),
268
+ scopes: ep.auth?.scopes ?? [],
269
+ ...(ep.auth?.scope_rule ? { scopeRule: ep.auth.scope_rule } : {}),
270
+ ...(ep.auth?.roles?.length ? { roles: ep.auth.roles } : {}),
271
+ ...(toolResponse(ep.response) ? { response: toolResponse(ep.response) } : {}),
272
+ ...(shapingApplies(ep) ? { shaping: true } : {}),
273
+ },
274
+ });
275
+ stats.emitted++;
276
+ }
277
+ tools.sort((a, b) => a.name.localeCompare(b.name));
278
+ return { tools, stats };
279
+ }
280
+ /**
281
+ * Fetch a live spec. The response envelope is {status, data} on the panel; a
282
+ * bare spec is accepted too. Rejects on non-2xx, timeout or a malformed body.
283
+ * The caller decides whether to fall back to the committed snapshot.
284
+ */
285
+ export async function fetchSpec(url, timeoutMs) {
286
+ const ctrl = new AbortController();
287
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
288
+ try {
289
+ const res = await fetch(url, { headers: { Accept: "application/json" }, signal: ctrl.signal });
290
+ if (!res.ok)
291
+ throw new Error(`spec fetch failed: HTTP ${res.status}`);
292
+ const json = (await res.json());
293
+ const spec = (json.data ?? json);
294
+ if (!Array.isArray(spec.endpoints))
295
+ throw new Error("spec has no endpoints array");
296
+ return spec;
297
+ }
298
+ finally {
299
+ clearTimeout(timer);
300
+ }
301
+ }