panelica-mcp 0.2.2 → 0.5.1
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 +154 -16
- package/dist/catalog.js +298 -0
- package/dist/errors.js +234 -0
- package/dist/index.js +258 -46
- package/dist/instructions.js +75 -0
- package/dist/toolsets.js +250 -0
- package/package.json +3 -3
- package/tools/tools.json +1864 -467
package/README.md
CHANGED
|
@@ -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.
|
|
85
|
-
|
|
86
|
-
|
|
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
|
-
|
|
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
|
|
216
|
-
`
|
|
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
|
+
"404 tools available" (the core set plus three meta tools; set `PANELICA_TOOLSETS=all` for all 404).
|
|
293
314
|
|
|
294
315
|
### Cursor
|
|
295
316
|
|
|
@@ -342,6 +363,98 @@ 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
460
|
**404 tools** are auto-generated from the panel's live `/v1/api-spec`, so they never
|
|
@@ -350,6 +463,10 @@ drift from the API. Each tool carries MCP safety annotations
|
|
|
350
463
|
 177 ·
|
|
351
464
|
 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
|
|
@@ -501,13 +626,16 @@ Mutating service control deliberately requires its own action scopes (or
|
|
|
501
626
|
|
|
502
627
|
| Symptom | Likely cause | Fix |
|
|
503
628
|
|---------|--------------|-----|
|
|
504
|
-
| Client reports "
|
|
629
|
+
| Client reports "404 tools available" | Server crashed at startup — usually a missing env var | Run `panelica-mcp` once from a shell with the three env vars set; read stderr |
|
|
505
630
|
| `401 MISSING_API_KEY` | `PANELICA_API_KEY` not set or wrong header passthrough | Re-check the MCP client config; restart the client after editing |
|
|
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
|
|
510
|
-
| Tool
|
|
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 #
|
|
667
|
+
│ └── tools.json # tool definitions, auto-generated (committed)
|
|
536
668
|
├── .github/workflows/
|
|
537
|
-
│ └── refresh-tools.yml # Weekly CI: regenerate
|
|
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
|
|
560
|
-
|
|
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:
|
package/dist/catalog.js
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
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
|
+
{ re: /\/opt\/panelica[\w/.-]*/g, sub: "<path>" },
|
|
28
|
+
{ re: /\/home\/[\w.-]+[\w/.-]*/g, sub: "<path>" },
|
|
29
|
+
{ re: /\b(?:pk|sk)_[A-Za-z0-9]{8,}\b/g, sub: "<key>" },
|
|
30
|
+
];
|
|
31
|
+
export function redactStr(s) {
|
|
32
|
+
let out = String(s ?? "");
|
|
33
|
+
for (const r of REDACTORS)
|
|
34
|
+
out = out.replace(r.re, r.sub);
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
/** Deep-redact a whole spec (used before the snapshot is written to the public repo). */
|
|
38
|
+
export function deepRedact(v) {
|
|
39
|
+
if (typeof v === "string")
|
|
40
|
+
return redactStr(v);
|
|
41
|
+
if (Array.isArray(v))
|
|
42
|
+
return v.map(deepRedact);
|
|
43
|
+
if (v && typeof v === "object") {
|
|
44
|
+
const o = {};
|
|
45
|
+
for (const [k, val] of Object.entries(v))
|
|
46
|
+
o[k] = deepRedact(val);
|
|
47
|
+
return o;
|
|
48
|
+
}
|
|
49
|
+
return v;
|
|
50
|
+
}
|
|
51
|
+
// ── Helpers ───────────────────────────────────────────────────────────────────
|
|
52
|
+
/** The spec renders path params as {name}; the runtime substitutes :name. */
|
|
53
|
+
export function toColonPath(p) {
|
|
54
|
+
return String(p ?? "").replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, ":$1");
|
|
55
|
+
}
|
|
56
|
+
function slugify(s) {
|
|
57
|
+
return String(s ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
58
|
+
}
|
|
59
|
+
function toolName(method, path, category) {
|
|
60
|
+
const cat = slugify(category || "misc");
|
|
61
|
+
const m = String(method || "get").toLowerCase();
|
|
62
|
+
let name = `panelica_${cat}_${m}_${slugify(path)}`;
|
|
63
|
+
if (name.length > 64) {
|
|
64
|
+
const hash = createHash("sha1").update(name).digest("hex").slice(0, 8);
|
|
65
|
+
name = `${name.slice(0, 55)}_${hash}`;
|
|
66
|
+
}
|
|
67
|
+
return name;
|
|
68
|
+
}
|
|
69
|
+
function jsonType(t) {
|
|
70
|
+
return t === "uuid" ? "string" : (t || "string");
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Where an id parameter comes from, for panels whose spec predates the
|
|
74
|
+
* server-side hint: "id" → the collection right before it in the
|
|
75
|
+
* path, "<x>_id" → the collection <x>s. Only used when the spec has no description.
|
|
76
|
+
*/
|
|
77
|
+
const ID_ALIASES = { user: "accounts", account: "accounts", key: "api-keys", zone: "dns/zones" };
|
|
78
|
+
export function idHint(name, path, lists, type) {
|
|
79
|
+
let stem = "";
|
|
80
|
+
if (name === "id") {
|
|
81
|
+
const segs = path.split("/");
|
|
82
|
+
const i = segs.indexOf("{id}");
|
|
83
|
+
if (i > 0)
|
|
84
|
+
stem = segs[i - 1];
|
|
85
|
+
}
|
|
86
|
+
else if (name.endsWith("_id")) {
|
|
87
|
+
stem = name.slice(0, -3);
|
|
88
|
+
}
|
|
89
|
+
if (!stem)
|
|
90
|
+
return "";
|
|
91
|
+
const singular = stem.endsWith("ies") ? stem.slice(0, -3) + "y" : stem.replace(/(es|s)$/, "");
|
|
92
|
+
const candidates = [ID_ALIASES[singular] ? `/v1/${ID_ALIASES[singular]}` : "", `/v1/${stem}`, `/v1/${singular}s`, `/v1/${singular}es`].filter(Boolean);
|
|
93
|
+
const kind = type === "uuid" ? "UUID" : "ID";
|
|
94
|
+
const label = singular.replace(/_/g, " ");
|
|
95
|
+
const list = candidates.find((c) => lists.has(c));
|
|
96
|
+
return list ? `${kind} of the ${label} — obtain it from GET ${list}` : `${kind} of the ${label}`;
|
|
97
|
+
}
|
|
98
|
+
/** List-returning GET tools get _limit/_fields/_match (client-side shaping). */
|
|
99
|
+
export function shapingApplies(ep) {
|
|
100
|
+
if (String(ep.method).toUpperCase() !== "GET")
|
|
101
|
+
return false;
|
|
102
|
+
const dt = ep.response?.data_type;
|
|
103
|
+
if (dt)
|
|
104
|
+
return dt === "array";
|
|
105
|
+
return !String(ep.path).includes("{"); // unknown shape: collections without an id are lists
|
|
106
|
+
}
|
|
107
|
+
function buildInputSchema(ep, lists) {
|
|
108
|
+
const properties = {};
|
|
109
|
+
const required = [];
|
|
110
|
+
const req = ep.request || {};
|
|
111
|
+
const hint = (name, type) => idHint(name, ep.path, lists, type);
|
|
112
|
+
const withEnum = (schema, f) => {
|
|
113
|
+
if (f.enum?.length)
|
|
114
|
+
schema.enum = f.enum;
|
|
115
|
+
if (f.default !== undefined && f.default !== "")
|
|
116
|
+
schema.default = f.default;
|
|
117
|
+
return schema;
|
|
118
|
+
};
|
|
119
|
+
for (const p of req.path_params ?? []) {
|
|
120
|
+
properties[p.name] = withEnum({ type: jsonType(p.type), description: redactStr(p.description || hint(p.name, p.type) || `Path parameter: ${p.name}`) }, p);
|
|
121
|
+
if (p.required !== false)
|
|
122
|
+
required.push(p.name);
|
|
123
|
+
}
|
|
124
|
+
for (const q of req.query_params ?? []) {
|
|
125
|
+
properties[q.name] = withEnum({ type: jsonType(q.type), description: redactStr(q.description || hint(q.name, q.type) || `Query parameter: ${q.name}`) }, q);
|
|
126
|
+
if (q.required)
|
|
127
|
+
required.push(q.name);
|
|
128
|
+
}
|
|
129
|
+
if (shapingApplies(ep)) {
|
|
130
|
+
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." };
|
|
131
|
+
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." };
|
|
132
|
+
properties._match = { type: "string", description: "Keep only items whose JSON contains this text (case-insensitive), e.g. a domain name or status." };
|
|
133
|
+
}
|
|
134
|
+
const body = req.body || {};
|
|
135
|
+
if (body.content_type === "none") {
|
|
136
|
+
// The panel declares this mutating endpoint takes no request body
|
|
137
|
+
// (action endpoints such as …/suspend, …/restart): no body property.
|
|
138
|
+
}
|
|
139
|
+
else if (body.fields?.length) {
|
|
140
|
+
properties.body = {
|
|
141
|
+
type: "object",
|
|
142
|
+
description: `Request body (${body.content_type || "application/json"})`,
|
|
143
|
+
properties: Object.fromEntries(body.fields.map((f) => [f.name, withEnum({
|
|
144
|
+
type: jsonType(f.type),
|
|
145
|
+
description: redactStr(f.description || hint(f.name, f.type) || ""),
|
|
146
|
+
}, f)])),
|
|
147
|
+
required: body.fields.filter((f) => f.required).map((f) => f.name),
|
|
148
|
+
};
|
|
149
|
+
if (body.required)
|
|
150
|
+
required.push("body");
|
|
151
|
+
}
|
|
152
|
+
else if (["POST", "PUT", "PATCH"].includes(ep.method)) {
|
|
153
|
+
properties.body = {
|
|
154
|
+
type: "object",
|
|
155
|
+
description: `Request body (${body.content_type || "application/json"}). Schema not statically declared — see API docs.`,
|
|
156
|
+
additionalProperties: true,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
return { type: "object", properties, required: [...new Set(required)], additionalProperties: false };
|
|
160
|
+
}
|
|
161
|
+
/** MCP tool annotations: clients auto-approve read-only calls and warn before destructive ones. */
|
|
162
|
+
function annotations(ep) {
|
|
163
|
+
const m = String(ep.method || "GET").toUpperCase();
|
|
164
|
+
const readOnly = m === "GET" || m === "HEAD";
|
|
165
|
+
const destructive = m === "DELETE";
|
|
166
|
+
return {
|
|
167
|
+
title: redactStr(ep.summary || `${m} ${ep.path}`),
|
|
168
|
+
readOnlyHint: readOnly,
|
|
169
|
+
destructiveHint: destructive,
|
|
170
|
+
idempotentHint: readOnly || m === "PUT" || m === "DELETE",
|
|
171
|
+
openWorldHint: true, // reaches an external panel over the network
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/** Compact "Returns:" line: the envelope plus the first field names of data. */
|
|
175
|
+
export function returnsLine(r, maxNames = 12) {
|
|
176
|
+
if (!r || !r.data_type)
|
|
177
|
+
return "";
|
|
178
|
+
const names = (r.fields ?? []).map((f) => f.name);
|
|
179
|
+
const shown = names.slice(0, maxNames).join(", ") + (names.length > maxNames ? `, … (+${names.length - maxNames} more)` : "");
|
|
180
|
+
const extra = (r.keys ?? []).filter((k) => k !== "status" && k !== "data");
|
|
181
|
+
if (r.data_type === "none") {
|
|
182
|
+
return `Returns: {status${names.length ? ", " + names.join(", ") : ""}}`;
|
|
183
|
+
}
|
|
184
|
+
const item = names.length ? ` {${shown}}` : "";
|
|
185
|
+
const data = r.data_type === "array" ? `array of${item || " items"}` : (r.data_type === "object" ? `object${item}` : r.data_type);
|
|
186
|
+
return `Returns: {status, data: ${data}${extra.length ? ", " + extra.join(", ") : ""}}`;
|
|
187
|
+
}
|
|
188
|
+
function toolResponse(r) {
|
|
189
|
+
if (!r || !r.data_type)
|
|
190
|
+
return undefined;
|
|
191
|
+
const out = { data_type: r.data_type };
|
|
192
|
+
if (r.keys?.length)
|
|
193
|
+
out.keys = r.keys;
|
|
194
|
+
if (r.fields?.length)
|
|
195
|
+
out.fields = r.fields.map((f) => ({ name: f.name, type: jsonType(f.type), ...(f.description ? { description: redactStr(f.description) } : {}) }));
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
export function scopesLine(ep) {
|
|
199
|
+
const a = ep.auth ?? {};
|
|
200
|
+
const parts = [];
|
|
201
|
+
if (a.scope_rule)
|
|
202
|
+
parts.push(`Required scopes: ${a.scope_rule}`);
|
|
203
|
+
else if (a.scopes?.length)
|
|
204
|
+
parts.push(`Required scopes: ${a.scopes.join(", ")}`);
|
|
205
|
+
else if (a.required)
|
|
206
|
+
parts.push("Required scopes: none (any valid API key)");
|
|
207
|
+
if (a.roles?.length)
|
|
208
|
+
parts.push(`Restricted to key owners with role: ${a.roles.join(", ")}`);
|
|
209
|
+
return parts.join("\n");
|
|
210
|
+
}
|
|
211
|
+
function buildDescription(ep) {
|
|
212
|
+
const colon = toColonPath(ep.path);
|
|
213
|
+
const scopes = scopesLine(ep);
|
|
214
|
+
const risk = ep.method === "DELETE"
|
|
215
|
+
? "WARNING: destructive — permanently removes the resource."
|
|
216
|
+
: (["POST", "PUT", "PATCH"].includes(ep.method) ? "Mutating: changes server state." : "Read-only.");
|
|
217
|
+
return [
|
|
218
|
+
redactStr(ep.description || ep.summary || `${ep.method} ${colon}`),
|
|
219
|
+
`\nHTTP: ${ep.method} ${colon}`,
|
|
220
|
+
`Category: ${redactStr(ep.category)}`,
|
|
221
|
+
scopes,
|
|
222
|
+
redactStr(returnsLine(ep.response)),
|
|
223
|
+
risk,
|
|
224
|
+
].filter(Boolean).join("\n");
|
|
225
|
+
}
|
|
226
|
+
/** Meta / non-REST endpoints that are not tools (unauthenticated, WebSocket, ticket minting for WS). */
|
|
227
|
+
const SKIP_PATHS = /^\/(health|v1\/api-spec|v1\/postman-collection|v1\/metrics\/ws|v1\/metrics\/ws-ticket|v1\/terminal\/ws)$/;
|
|
228
|
+
/** Build the sorted tool list from a spec. Pure; no I/O. */
|
|
229
|
+
export function buildTools(spec) {
|
|
230
|
+
const endpoints = spec.endpoints ?? [];
|
|
231
|
+
const stats = { total: endpoints.length, emitted: 0, skipped: 0, read: 0, mutate: 0, destructive: 0 };
|
|
232
|
+
const seen = new Set();
|
|
233
|
+
const tools = [];
|
|
234
|
+
// GET collections (no path params): where ids are discovered.
|
|
235
|
+
const lists = new Set(endpoints.filter((e) => e.method === "GET" && e.path && !e.path.includes("{")).map((e) => e.path));
|
|
236
|
+
for (const ep of endpoints) {
|
|
237
|
+
if (!ep.method || !ep.path) {
|
|
238
|
+
stats.skipped++;
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (SKIP_PATHS.test(ep.path)) {
|
|
242
|
+
stats.skipped++;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
let name = toolName(ep.method, ep.path, ep.category);
|
|
246
|
+
while (seen.has(name))
|
|
247
|
+
name = `${name.slice(0, 55)}_${createHash("sha1").update(name + tools.length).digest("hex").slice(0, 8)}`;
|
|
248
|
+
seen.add(name);
|
|
249
|
+
const m = String(ep.method).toUpperCase();
|
|
250
|
+
if (m === "GET" || m === "HEAD")
|
|
251
|
+
stats.read++;
|
|
252
|
+
else if (m === "DELETE")
|
|
253
|
+
stats.destructive++;
|
|
254
|
+
else
|
|
255
|
+
stats.mutate++;
|
|
256
|
+
tools.push({
|
|
257
|
+
name,
|
|
258
|
+
description: buildDescription(ep),
|
|
259
|
+
inputSchema: buildInputSchema(ep, lists),
|
|
260
|
+
annotations: annotations(ep),
|
|
261
|
+
metadata: {
|
|
262
|
+
method: m,
|
|
263
|
+
path: toColonPath(ep.path),
|
|
264
|
+
category: redactStr(ep.category || "misc"),
|
|
265
|
+
scopes: ep.auth?.scopes ?? [],
|
|
266
|
+
...(ep.auth?.scope_rule ? { scopeRule: ep.auth.scope_rule } : {}),
|
|
267
|
+
...(ep.auth?.roles?.length ? { roles: ep.auth.roles } : {}),
|
|
268
|
+
...(toolResponse(ep.response) ? { response: toolResponse(ep.response) } : {}),
|
|
269
|
+
...(shapingApplies(ep) ? { shaping: true } : {}),
|
|
270
|
+
},
|
|
271
|
+
});
|
|
272
|
+
stats.emitted++;
|
|
273
|
+
}
|
|
274
|
+
tools.sort((a, b) => a.name.localeCompare(b.name));
|
|
275
|
+
return { tools, stats };
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Fetch a live spec. The response envelope is {status, data} on the panel; a
|
|
279
|
+
* bare spec is accepted too. Rejects on non-2xx, timeout or a malformed body.
|
|
280
|
+
* The caller decides whether to fall back to the committed snapshot.
|
|
281
|
+
*/
|
|
282
|
+
export async function fetchSpec(url, timeoutMs) {
|
|
283
|
+
const ctrl = new AbortController();
|
|
284
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
285
|
+
try {
|
|
286
|
+
const res = await fetch(url, { headers: { Accept: "application/json" }, signal: ctrl.signal });
|
|
287
|
+
if (!res.ok)
|
|
288
|
+
throw new Error(`spec fetch failed: HTTP ${res.status}`);
|
|
289
|
+
const json = (await res.json());
|
|
290
|
+
const spec = (json.data ?? json);
|
|
291
|
+
if (!Array.isArray(spec.endpoints))
|
|
292
|
+
throw new Error("spec has no endpoints array");
|
|
293
|
+
return spec;
|
|
294
|
+
}
|
|
295
|
+
finally {
|
|
296
|
+
clearTimeout(timer);
|
|
297
|
+
}
|
|
298
|
+
}
|