@blackbelt-technology/pi-dashboard-mcp-client-plugin 0.8.0

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.
@@ -0,0 +1,200 @@
1
+ /**
2
+ * mcp-client-plugin · CORE types.
3
+ *
4
+ * Shared vocabulary for the config writer, effective-view reader, live-state
5
+ * reader and the `mcp-client.config` service — all over pi's built-in MCP
6
+ * config (`~/.pi/agent/mcp.json` + trusted `<cwd>/.pi/mcp.json`). `./core`
7
+ * carries NO host, pi or React imports so the hostless `apple-tools`
8
+ * installer can consume it.
9
+ *
10
+ * See change: migrate-mcp-to-pi-builtin (D3); earlier: extract-mcp-client-plugin.
11
+ */
12
+
13
+ import type { AuthMode } from "./pi-rules.js";
14
+
15
+ export type { AuthMode };
16
+
17
+ /** pi's MCP server entry (1.0.0). Unknown keys are preserved, never dropped. */
18
+ export interface ServerEntry {
19
+ type?: "stdio" | "http" | "streamable-http" | string;
20
+ description?: string;
21
+ command?: string;
22
+ args?: string[];
23
+ env?: Record<string, string>;
24
+ cwd?: string;
25
+ url?: string;
26
+ headers?: Record<string, string>;
27
+ oauth?: {
28
+ clientId?: string;
29
+ clientSecret?: string;
30
+ callbackPort?: number;
31
+ callbackUrl?: string;
32
+ scope?: string;
33
+ clientName?: string;
34
+ authServerMetadataUrl?: string;
35
+ [k: string]: unknown;
36
+ };
37
+ auth?: { provider: string; [k: string]: unknown };
38
+ exposure?: string;
39
+ toolExposure?: Record<string, string>;
40
+ timeout?: number;
41
+ enabled?: boolean;
42
+ [k: string]: unknown;
43
+ }
44
+
45
+ /** Which Pi layer a read/write targets. */
46
+ export type Scope = { kind: "global" } | { kind: "project"; cwd: string };
47
+
48
+ /** Injected filesystem surface. `readFile` returns null when the file is absent. */
49
+ export interface ConfigIO {
50
+ readFile: (path: string) => string | null;
51
+ /**
52
+ * Atomic, hardened write (exclusive random temp file mode 0600, fsync, rename).
53
+ * Throws an Error whose `.code` may be EACCES / ENOSPC / ENOENT.
54
+ */
55
+ writeFileAtomic: (path: string, content: string) => void;
56
+ }
57
+
58
+ /** The closed refusal set shared by every write path AND by `checkConfigFiles`. */
59
+ export type ConfigRefusalCode =
60
+ | "unparseable"
61
+ | "entry-not-object"
62
+ | "invalid-name"
63
+ | "name-collision"
64
+ | "transport-conflict"
65
+ | "invalid-entry"
66
+ | "write-failed";
67
+
68
+ export interface ConfigRefusal {
69
+ code: ConfigRefusalCode;
70
+ message: string;
71
+ /** The offending file, when the refusal is file-scoped. */
72
+ path?: string;
73
+ /** For `write-failed`: the IO error code (EACCES / ENOSPC / ENOENT / ...). */
74
+ ioCode?: string;
75
+ /** For `transport-conflict`: the transport fields the resulting entry carries. */
76
+ fields?: string[];
77
+ /** For `name-collision`: the colliding server and where it is defined. */
78
+ conflict?: { name: string; path: string };
79
+ }
80
+
81
+ export type ConfigWriteResult = { ok: true } | { ok: false; refusal: ConfigRefusal };
82
+
83
+ export type RemoveResult =
84
+ | { ok: true; removed: ServerEntry | undefined }
85
+ | { ok: false; refusal: ConfigRefusal };
86
+
87
+ /**
88
+ * `written` — the layer now carries the requested state. `omitted` lists the
89
+ * secret-bearing fields a folder-scope DISABLE copy left out.
90
+ * `needs-choice` — an ENABLE of a folder copy that lacks the global entry's
91
+ * secrets: nothing is written; the caller offers "remove the folder entry" or
92
+ * "re-enter the omitted values".
93
+ */
94
+ export type SetEnabledResult =
95
+ | { ok: true; action: "written"; omitted?: string[] }
96
+ | { ok: true; action: "needs-choice"; omitted: string[] }
97
+ | { ok: false; refusal: ConfigRefusal };
98
+
99
+ /** Parse status of one config file (write-suppressed). */
100
+ export interface ParseStatus {
101
+ path: string;
102
+ ok: boolean;
103
+ /** Present iff `ok` is false: the parser error message. */
104
+ message?: string;
105
+ }
106
+
107
+ export type Provenance = "pi-global" | "pi-folder";
108
+
109
+ export type InactiveReason = "disabled" | "project-not-trusted" | "invalid-entry" | "name-collision" | "global-only-auth";
110
+
111
+ export interface EffectiveServerView {
112
+ name: string;
113
+ provenance: Provenance;
114
+ /** A folder entry that replaces the global entry of the same name. */
115
+ overridesGlobal?: boolean;
116
+ /**
117
+ * The entry as written. In a project view, a GLOBAL entry's secret values
118
+ * (`headers`, `env` → `{redacted, keys}`; `oauth.clientSecret` →
119
+ * `{redacted}`) are redacted server-side; own-layer entries are verbatim.
120
+ */
121
+ entry: Record<string, unknown>;
122
+ transport: "stdio" | "http";
123
+ enabled: boolean;
124
+ /** Exposure for display (alias resolved, default `codemode`). */
125
+ exposure: string;
126
+ /** Whether pi loads this entry for the view's directory. */
127
+ active: boolean;
128
+ inactiveReason?: InactiveReason;
129
+ /** pi's own message when it would reject or drop the entry. */
130
+ piError?: string;
131
+ /** Keys pi ignores on this entry (adapter leftovers, losing dual-transport key). */
132
+ ignoredKeys: string[];
133
+ /** The adapter-only subset of `ignoredKeys`; non-empty → "convert" is offered. */
134
+ adapterLeftovers: string[];
135
+ authMode?: AuthMode;
136
+ }
137
+
138
+ export interface LayerStatus {
139
+ layer: Provenance;
140
+ path: string;
141
+ exists: boolean;
142
+ ok: boolean;
143
+ /** Present iff `ok` is false — pi skips the whole file. */
144
+ message?: string;
145
+ }
146
+
147
+ export interface EffectiveView {
148
+ scope: "global" | "project";
149
+ cwd?: string;
150
+ /** Project views only: pi's trust decision for `cwd` (predicate absent → false). */
151
+ trusted?: boolean;
152
+ servers: EffectiveServerView[];
153
+ layers: LayerStatus[];
154
+ }
155
+
156
+ /** One server's live state as `pi mcp list --json` reports it. */
157
+ export interface LiveServerState {
158
+ state: string;
159
+ tools: number;
160
+ error?: string;
161
+ }
162
+
163
+ export type LiveState =
164
+ | { ok: true; servers: Record<string, LiveServerState>; errors: string[]; note?: string }
165
+ | { ok: false; reason: "spawn-failed" | "timeout" | "unparseable"; message: string };
166
+
167
+ /**
168
+ * Runs `pi mcp list --json` in `cwd`. Resolves with stdout + exit code
169
+ * whatever the code; rejects only when the process cannot run. Must kill the
170
+ * child when `signal` aborts.
171
+ */
172
+ export type PiMcpListRunner = (cwd: string, signal: AbortSignal) => Promise<{ stdout: string; code: number | null }>;
173
+
174
+ /** The in-process service provided as `mcp-client.config`. */
175
+ export interface McpClientConfigService {
176
+ /** The file a scope's write lands in. Throws `NotAllowedCwdError` for an unknown cwd. */
177
+ targetPath(scope: Scope): string;
178
+ /** The raw entry in the scope's layer (no merge), or undefined. */
179
+ readServerEntry(name: string, scope: Scope): ServerEntry | undefined;
180
+ getEffectiveView(scope: Scope): EffectiveView;
181
+ /** Merge `fields` over the existing layer entry (or create it), then validate. */
182
+ ensureServerEntry(name: string, fields: Partial<ServerEntry>, scope: Scope): ConfigWriteResult;
183
+ /**
184
+ * Replace the whole entry. `previousName` renames (the old key is removed);
185
+ * `create` refuses when the name already exists. Neither ever replaces
186
+ * another entry.
187
+ */
188
+ saveServer(
189
+ name: string,
190
+ entry: ServerEntry,
191
+ scope: Scope,
192
+ opts?: { previousName?: string; create?: boolean },
193
+ ): ConfigWriteResult;
194
+ removeServer(name: string, scope: Scope): RemoveResult;
195
+ setEnabled(name: string, enabled: boolean, scope: Scope): SetEnabledResult;
196
+ /** `disabled: true` → `enabled: false`; drop every adapter-only key. */
197
+ convertAdapterLeftovers(name: string, scope: Scope): ConfigWriteResult;
198
+ /** Write-suppressed parse + (optional) dry run of `ensureServerEntry` at global scope. */
199
+ checkConfigFiles(opts?: { serverName?: string; fields?: Partial<ServerEntry> }): { mcpJson: ParseStatus };
200
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * mcp-client-plugin · SERVER entry.
3
+ *
4
+ * Builds the `mcp-client.config` service over pi's built-in MCP config with
5
+ * the real filesystem IO, the host's known-folder set, the host's pi
6
+ * project-trust rule (`host.isProjectTrusted`; absent → every project is
7
+ * untrusted) and the default `pi mcp list` runner. Provides it BEFORE any
8
+ * route is registered, then mounts the REST surface.
9
+ *
10
+ * See change: migrate-mcp-to-pi-builtin; earlier: extract-mcp-client-plugin (task 4.1).
11
+ */
12
+
13
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
14
+ import { createRealConfigIO } from "../core/config-io.js";
15
+ import { createMcpClientConfigService } from "../core/service.js";
16
+ import { createPiMcpListRunner } from "./pi-runner.js";
17
+ import { mountMcpClientRoutes } from "./routes.js";
18
+
19
+ const SERVICE_KEY = "mcp-client.config";
20
+ const HOST_KNOWN_FOLDERS = "host.knownFolderCwds";
21
+ const HOST_PROJECT_TRUST = "host.isProjectTrusted";
22
+
23
+ async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
24
+ ctx.logger.info("mcp-client server entry activated");
25
+ const hostKnown = ctx.consume<() => string[]>(HOST_KNOWN_FOLDERS);
26
+ const knownCwds = (): string[] => (hostKnown ? hostKnown() : []);
27
+ const hostTrust = ctx.consume<(cwd: string) => boolean>(HOST_PROJECT_TRUST);
28
+ if (!hostTrust) {
29
+ ctx.logger.warn(`mcp-client: host service '${HOST_PROJECT_TRUST}' is unavailable — every project's .pi/mcp.json is shown as untrusted`);
30
+ }
31
+ const runtime = createMcpClientConfigService({
32
+ configIO: createRealConfigIO(),
33
+ knownCwds,
34
+ ...(hostTrust ? { isProjectTrusted: (cwd: string) => hostTrust(cwd) } : {}),
35
+ runner: createPiMcpListRunner(),
36
+ });
37
+
38
+ // Provide the service before routes so a dependent plugin registering later
39
+ // observes it during its own registration.
40
+ ctx.provide(SERVICE_KEY, runtime);
41
+
42
+ mountMcpClientRoutes(ctx.fastify, { runtime, knownCwds, networkGuard: ctx.networkGuard });
43
+ }
44
+
45
+ export default registerPlugin;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * mcp-client-plugin · default `pi mcp list --json` runner (server only).
3
+ *
4
+ * Resolves pi through the shared `ToolResolver` (managed / registry / PATH),
5
+ * spawns through the shared `windowsHide` spawn wrapper (never a shell),
6
+ * inherits the server env (so `PI_CODING_AGENT_DIR` matches the files the
7
+ * dashboard reads), forces `ELECTRON_RUN_AS_NODE` when pi is node-wrapped on
8
+ * the Electron execPath, and kills the child's whole process TREE (pi plus
9
+ * the stdio MCP servers it started) when the core's 30 s deadline aborts. The exit code is returned, never thrown: pi exits 1 whenever a
10
+ * server is disconnected or an entry is invalid.
11
+ *
12
+ * See change: migrate-mcp-to-pi-builtin (D3 "Live state").
13
+ */
14
+
15
+ import { ToolResolver } from "@blackbelt-technology/pi-dashboard-shared/platform/binary-lookup.js";
16
+ import { spawn } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
17
+ import { killPidWithGroup, killProcess } from "@blackbelt-technology/pi-dashboard-shared/platform/process.js";
18
+ import { buildSpawnEnvForArgv } from "@blackbelt-technology/pi-dashboard-shared/platform/runner.js";
19
+ import type { PiMcpListRunner } from "../core/types.js";
20
+
21
+ /** stdout cap — a list of servers is small; anything larger is not pi's JSON. */
22
+ const MAX_STDOUT_BYTES = 4 * 1024 * 1024;
23
+
24
+ export function createPiMcpListRunner(resolver = new ToolResolver({ processExecPath: process.execPath, useLoginShell: false })): PiMcpListRunner {
25
+ return (cwd, signal) =>
26
+ new Promise((resolve, reject) => {
27
+ const argv = resolver.resolvePi();
28
+ if (!argv || argv.length === 0) {
29
+ reject(new Error("pi executable not found"));
30
+ return;
31
+ }
32
+ const [cmd, ...prefix] = argv;
33
+ const env = buildSpawnEnvForArgv(cmd) ?? process.env;
34
+ // Own process group (POSIX), so the kill reaches the stdio MCP servers
35
+ // pi started — killing pi alone would orphan them.
36
+ const child = spawn(cmd, [...prefix, "mcp", "list", "--json"], {
37
+ cwd,
38
+ env,
39
+ stdio: ["ignore", "pipe", "ignore"],
40
+ detached: true,
41
+ });
42
+ const chunks: Buffer[] = [];
43
+ let size = 0;
44
+ let killed = false;
45
+ const kill = (): void => {
46
+ const pid = child.pid;
47
+ if (killed || pid === undefined) return;
48
+ killed = true;
49
+ // Shared platform primitives: group SIGKILL on POSIX; `taskkill /T`
50
+ // tree kill on Windows (killProcess). No platform branch here.
51
+ try {
52
+ killPidWithGroup(pid, "SIGKILL");
53
+ } catch {
54
+ /* already gone */
55
+ }
56
+ void killProcess(pid, { timeoutMs: 0 }).catch(() => undefined);
57
+ };
58
+ signal.addEventListener("abort", kill, { once: true });
59
+ child.stdout?.on("data", (b: Buffer) => {
60
+ size += b.length;
61
+ if (size > MAX_STDOUT_BYTES) kill();
62
+ else chunks.push(b);
63
+ });
64
+ child.once("error", (e) => {
65
+ signal.removeEventListener("abort", kill);
66
+ reject(e);
67
+ });
68
+ child.once("close", (code) => {
69
+ signal.removeEventListener("abort", kill);
70
+ resolve({ stdout: Buffer.concat(chunks).toString("utf8"), code });
71
+ });
72
+ });
73
+ }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * mcp-client-plugin · REST routes over pi's built-in MCP config.
3
+ *
4
+ * GET /api/mcp-client/effective?cwd= effective view (files only, fast)
5
+ * GET /api/mcp-client/live?cwd=&fresh=1 live state from `pi mcp list --json`
6
+ * GET /api/mcp-client/schema published entry schema
7
+ * PUT /api/mcp-client/servers/:name {scope, cwd?, entry, previousName?, create?} — whole-entry save
8
+ * DELETE /api/mcp-client/servers/:name?scope=&cwd= → {ok, removed}
9
+ * PUT /api/mcp-client/servers/:name/enabled {scope, cwd?, enabled}
10
+ * POST /api/mcp-client/servers/:name/convert {scope, cwd?} — adapter leftovers → pi
11
+ *
12
+ * Every route (GET included) is registered behind the host `networkGuard`
13
+ * (cookie/token/loopback auth): a write becomes executable configuration for
14
+ * pi and the effective view returns own-layer credentials. Path names are
15
+ * decoded and validated, and a project cwd is admitted against the
16
+ * known-folder set, BEFORE any file is read or written.
17
+ *
18
+ * See change: migrate-mcp-to-pi-builtin (D3); earlier: extract-mcp-client-plugin (D7).
19
+ */
20
+
21
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
22
+ import { isAllowedCwd } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
23
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
24
+ import { isValidServerName } from "../core/pi-rules.js";
25
+ import { errorFields, mcpConfigSchema, validateServerEntry } from "../core/schema-validation.js";
26
+ import type { McpClientRuntime } from "../core/service.js";
27
+ import type { ConfigRefusal, Scope, ServerEntry } from "../core/types.js";
28
+
29
+ export interface McpClientRouteDeps {
30
+ runtime: McpClientRuntime;
31
+ knownCwds: () => string[];
32
+ networkGuard: ServerPluginContext["networkGuard"];
33
+ }
34
+
35
+ const PREFIX = "/api/mcp-client";
36
+
37
+ /**
38
+ * Additive remedy fields on a cwd-allowlist refusal. The known-cwd set already
39
+ * includes pinned directories, so pinning the refused directory is the remedy.
40
+ * See change: add-access-grants-and-review.
41
+ */
42
+ const CWD_DENIED_REASON = "cwd is not a known session or pinned directory.";
43
+ const CWD_DENIED_HINT = "Pin this directory to allow it, or open a session rooted in it.";
44
+
45
+ function notAllowed(cwd: string): { status: number; body: Record<string, unknown> } {
46
+ return {
47
+ status: 403,
48
+ body: { error: "not-allowed", message: `cwd not allowed: ${cwd}`, reason: CWD_DENIED_REASON, hint: CWD_DENIED_HINT },
49
+ };
50
+ }
51
+
52
+ function refusalParts(refusal: ConfigRefusal): { status: number; body: Record<string, unknown> } {
53
+ const body: Record<string, unknown> = { error: refusal.code, message: refusal.message };
54
+ switch (refusal.code) {
55
+ case "invalid-name":
56
+ case "invalid-entry":
57
+ return { status: 400, body };
58
+ case "transport-conflict":
59
+ return { status: 400, body: { ...body, fields: refusal.fields ?? [] } };
60
+ case "name-collision":
61
+ return { status: 409, body: { ...body, ...(refusal.conflict ? { conflict: refusal.conflict } : {}) } };
62
+ case "unparseable":
63
+ case "entry-not-object":
64
+ return { status: 409, body };
65
+ default:
66
+ return { status: 500, body: { ...body, ...(refusal.ioCode ? { ioCode: refusal.ioCode } : {}) } };
67
+ }
68
+ }
69
+
70
+ function sendRefusal(reply: FastifyReply, refusal: ConfigRefusal): FastifyReply {
71
+ const { status, body } = refusalParts(refusal);
72
+ return reply.code(status).send(body);
73
+ }
74
+
75
+ interface ScopeInput {
76
+ scope?: unknown;
77
+ cwd?: unknown;
78
+ }
79
+
80
+ type ParsedScope = { ok: true; scope: Scope } | { ok: false; status: number; body: Record<string, unknown> };
81
+
82
+ /** Parse + ADMIT a scope (no IO): a project cwd must be a known folder. */
83
+ function parseScope(input: ScopeInput, knownCwds: () => string[]): ParsedScope {
84
+ if (input.scope === "global") return { ok: true, scope: { kind: "global" } };
85
+ if (input.scope === "project") {
86
+ if (typeof input.cwd !== "string" || input.cwd.length === 0) {
87
+ return { ok: false, status: 400, body: { error: "invalid-body", message: "project scope requires a cwd" } };
88
+ }
89
+ if (!isAllowedCwd(input.cwd, knownCwds)) return { ok: false, ...notAllowed(input.cwd) };
90
+ return { ok: true, scope: { kind: "project", cwd: input.cwd } };
91
+ }
92
+ return { ok: false, status: 400, body: { error: "invalid-body", message: "scope must be 'global' or 'project'" } };
93
+ }
94
+
95
+ /** Decoded + validated path name, or null. */
96
+ function pathName(request: FastifyRequest): string | null {
97
+ const raw = (request.params as { name?: string }).name ?? "";
98
+ let name = raw;
99
+ try {
100
+ // Fastify already decodes params; decode defensively for double-encoded input.
101
+ name = decodeURIComponent(raw);
102
+ } catch {
103
+ return null;
104
+ }
105
+ return isValidServerName(name) ? name : null;
106
+ }
107
+
108
+ /** `?cwd=` → scope, admitted; a repeated key (array) is refused. */
109
+ function queryScope(request: FastifyRequest, knownCwds: () => string[]): ParsedScope {
110
+ const rawCwd = (request.query as { cwd?: unknown }).cwd;
111
+ if (rawCwd !== undefined && typeof rawCwd !== "string") {
112
+ return { ok: false, status: 400, body: { error: "invalid-cwd", message: "cwd must be a single string" } };
113
+ }
114
+ if (rawCwd === undefined || rawCwd === "") return { ok: true, scope: { kind: "global" } };
115
+ return parseScope({ scope: "project", cwd: rawCwd }, knownCwds);
116
+ }
117
+
118
+ const INVALID_NAME = { error: "invalid-name", message: "invalid server name" };
119
+
120
+ export function mountMcpClientRoutes(fastify: FastifyInstance, deps: McpClientRouteDeps): void {
121
+ const guard = { preHandler: deps.networkGuard };
122
+ const { runtime, knownCwds } = deps;
123
+
124
+ fastify.get(`${PREFIX}/effective`, guard, async (request, reply) => {
125
+ const parsed = queryScope(request, knownCwds);
126
+ if (!parsed.ok) return reply.code(parsed.status).send(parsed.body);
127
+ return runtime.getEffectiveView(parsed.scope);
128
+ });
129
+
130
+ fastify.get(`${PREFIX}/live`, guard, async (request, reply) => {
131
+ const parsed = queryScope(request, knownCwds);
132
+ if (!parsed.ok) return reply.code(parsed.status).send(parsed.body);
133
+ const fresh = (request.query as { fresh?: string }).fresh === "1";
134
+ return runtime.getLiveState(parsed.scope, { fresh });
135
+ });
136
+
137
+ fastify.get(`${PREFIX}/schema`, guard, async () => mcpConfigSchema);
138
+
139
+ fastify.put(`${PREFIX}/servers/:name`, guard, async (request, reply) => {
140
+ const name = pathName(request);
141
+ if (!name) return reply.code(400).send(INVALID_NAME);
142
+ const body = (request.body ?? {}) as ScopeInput & { entry?: unknown; previousName?: unknown; create?: unknown };
143
+ const parsed = parseScope(body, knownCwds);
144
+ if (!parsed.ok) return reply.code(parsed.status).send(parsed.body);
145
+ if (typeof body.entry !== "object" || body.entry === null || Array.isArray(body.entry)) {
146
+ return reply.code(400).send({ error: "invalid-body", message: "body must carry an `entry` object" });
147
+ }
148
+ if (body.previousName !== undefined && (typeof body.previousName !== "string" || !isValidServerName(body.previousName))) {
149
+ return reply.code(400).send(INVALID_NAME);
150
+ }
151
+ const validation = validateServerEntry(body.entry);
152
+ if (!validation.ok) {
153
+ return reply
154
+ .code(400)
155
+ .send({ error: "schema", message: "server entry failed validation", fields: errorFields(validation.errors) });
156
+ }
157
+ const result = runtime.saveServer(name, body.entry as ServerEntry, parsed.scope, {
158
+ ...(typeof body.previousName === "string" ? { previousName: body.previousName } : {}),
159
+ ...(body.create === true ? { create: true } : {}),
160
+ });
161
+ if (!result.ok) return sendRefusal(reply, result.refusal);
162
+ return { ok: true };
163
+ });
164
+
165
+ fastify.delete(`${PREFIX}/servers/:name`, guard, async (request, reply) => {
166
+ const name = pathName(request);
167
+ if (!name) return reply.code(400).send(INVALID_NAME);
168
+ const query = request.query as { scope?: unknown; cwd?: unknown };
169
+ const parsed = parseScope({ scope: query.scope ?? "global", cwd: query.cwd }, knownCwds);
170
+ if (!parsed.ok) return reply.code(parsed.status).send(parsed.body);
171
+ const result = runtime.removeServer(name, parsed.scope);
172
+ if (!result.ok) return sendRefusal(reply, result.refusal);
173
+ return { ok: true, removed: result.removed };
174
+ });
175
+
176
+ fastify.put(`${PREFIX}/servers/:name/enabled`, guard, async (request, reply) => {
177
+ const name = pathName(request);
178
+ if (!name) return reply.code(400).send(INVALID_NAME);
179
+ const body = (request.body ?? {}) as ScopeInput & { enabled?: unknown };
180
+ const parsed = parseScope(body, knownCwds);
181
+ if (!parsed.ok) return reply.code(parsed.status).send(parsed.body);
182
+ if (typeof body.enabled !== "boolean") {
183
+ return reply.code(400).send({ error: "invalid-body", message: "`enabled` must be a boolean" });
184
+ }
185
+ const result = runtime.setEnabled(name, body.enabled, parsed.scope);
186
+ if (!result.ok) return sendRefusal(reply, result.refusal);
187
+ return result;
188
+ });
189
+
190
+ fastify.post(`${PREFIX}/servers/:name/convert`, guard, async (request, reply) => {
191
+ const name = pathName(request);
192
+ if (!name) return reply.code(400).send(INVALID_NAME);
193
+ const parsed = parseScope((request.body ?? {}) as ScopeInput, knownCwds);
194
+ if (!parsed.ok) return reply.code(parsed.status).send(parsed.body);
195
+ const result = runtime.convertAdapterLeftovers(name, parsed.scope);
196
+ if (!result.ok) return sendRefusal(reply, result.refusal);
197
+ return { ok: true };
198
+ });
199
+ }