@blackbelt-technology/pi-dashboard-mcp-client-plugin 0.9.0 → 0.11.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.
@@ -1,134 +0,0 @@
1
- /**
2
- * mcp-client-plugin · CORE live server state from `pi mcp list --json`.
3
- *
4
- * Connection state and tool counts come from pi, never re-implemented:
5
- * - 30 s timeout — the runner's child is killed through the AbortSignal and
6
- * the result is "state unknown" (`timeout`), never stale data;
7
- * - 30 s cache per cwd (the command connects to every server, so it is slow
8
- * and may have side effects);
9
- * - stdout is parsed WHATEVER the exit code: pi exits 1 whenever an entry is
10
- * invalid or an enabled server is not connected (normal, not a failure).
11
- * Only a spawn failure, a timeout or unparseable stdout yield `ok: false`.
12
- *
13
- * The global settings view runs the command in an always-empty scratch dir so
14
- * only the Pi-global layer loads (a folder's trusted `.pi/mcp.json` must not
15
- * leak into the global list).
16
- *
17
- * See change: migrate-mcp-to-pi-builtin (D3 "Live state").
18
- */
19
-
20
- import { isPlainObject } from "./path-utils.js";
21
- import type { LiveServerState, LiveState, PiMcpListRunner } from "./types.js";
22
-
23
- export const LIVE_STATE_TIMEOUT_MS = 30_000;
24
- export const LIVE_STATE_CACHE_TTL_MS = 30_000;
25
-
26
- export interface LiveStateReaderDeps {
27
- runner: PiMcpListRunner;
28
- timeoutMs?: number;
29
- cacheTtlMs?: number;
30
- now?: () => number;
31
- }
32
-
33
- export interface LiveStateReader {
34
- /** Live state for `cwd`; `fresh` bypasses (and refills) the cache. */
35
- read(cwd: string, opts?: { fresh?: boolean }): Promise<LiveState>;
36
- }
37
-
38
- /** Parse `pi mcp list --json` stdout; `null` when it is not pi's shape. */
39
- export function parseMcpListJson(stdout: string): Extract<LiveState, { ok: true }> | null {
40
- let parsed: unknown;
41
- try {
42
- parsed = JSON.parse(stdout);
43
- } catch {
44
- return null;
45
- }
46
- if (!isPlainObject(parsed) || !Array.isArray(parsed.servers)) return null;
47
- const servers: Record<string, LiveServerState> = Object.create(null);
48
- for (const s of parsed.servers) {
49
- if (!isPlainObject(s) || typeof s.name !== "string" || typeof s.state !== "string") continue;
50
- servers[s.name] = {
51
- state: s.state,
52
- tools: Array.isArray(s.tools) ? s.tools.length : 0,
53
- ...(typeof s.error === "string" ? { error: s.error } : {}),
54
- };
55
- }
56
- const errors = Array.isArray(parsed.errors) ? parsed.errors.filter((e): e is string => typeof e === "string") : [];
57
- return { ok: true, servers, errors, ...(typeof parsed.note === "string" ? { note: parsed.note } : {}) };
58
- }
59
-
60
- export function createLiveStateReader(deps: LiveStateReaderDeps): LiveStateReader {
61
- const timeoutMs = deps.timeoutMs ?? LIVE_STATE_TIMEOUT_MS;
62
- const ttl = deps.cacheTtlMs ?? LIVE_STATE_CACHE_TTL_MS;
63
- const now = deps.now ?? (() => Date.now());
64
- const cache = new Map<string, { at: number; value: Promise<LiveState>; settled: boolean }>();
65
-
66
-
67
- async function run(cwd: string): Promise<LiveState> {
68
- const controller = new AbortController();
69
- let timer: ReturnType<typeof setTimeout> | undefined;
70
- const timedOut = new Promise<"timeout">((resolve) => {
71
- timer = setTimeout(() => resolve("timeout"), timeoutMs);
72
- });
73
- try {
74
- const outcome = await Promise.race([deps.runner(cwd, controller.signal), timedOut]);
75
- if (outcome === "timeout") {
76
- controller.abort();
77
- return { ok: false, reason: "timeout", message: `pi mcp list did not finish within ${timeoutMs / 1000}s` };
78
- }
79
- const parsed = parseMcpListJson(outcome.stdout);
80
- if (!parsed) {
81
- return { ok: false, reason: "unparseable", message: `pi mcp list printed no JSON (exit ${outcome.code})` };
82
- }
83
- return parsed;
84
- } catch (e) {
85
- return { ok: false, reason: "spawn-failed", message: `could not run pi mcp list: ${(e as Error).message}` };
86
- } finally {
87
- if (timer) clearTimeout(timer);
88
- }
89
- }
90
-
91
- interface Slot {
92
- at: number;
93
- value: Promise<LiveState>;
94
- settled: boolean;
95
- }
96
- /** One queued post-refresh run per cwd, coalescing every fresh request made meanwhile. */
97
- const queued = new Map<string, Promise<LiveState>>();
98
-
99
- function start(cwd: string): Promise<LiveState> {
100
- const value = run(cwd);
101
- const slot: Slot = { at: now(), value, settled: false };
102
- cache.set(cwd, slot);
103
- void value.then((r) => {
104
- slot.settled = true;
105
- // A failure is not cached: the next view retries instead of showing
106
- // "state unknown" for a whole TTL.
107
- if (!r.ok && cache.get(cwd) === slot) cache.delete(cwd);
108
- });
109
- return value;
110
- }
111
-
112
- return {
113
- read(cwd, opts) {
114
- const hit = cache.get(cwd);
115
- if (hit && !hit.settled) {
116
- // One `pi mcp list` (which connects to every server) per cwd at a
117
- // time. A plain read shares the in-flight run; a `fresh` read must see
118
- // a run that STARTS after it, so it queues one follow-up (≤ 1 running
119
- // + 1 queued per cwd; later fresh reads join the same follow-up).
120
- if (!opts?.fresh) return hit.value;
121
- const pending = queued.get(cwd);
122
- if (pending) return pending;
123
- const next = hit.value.then(() => {
124
- queued.delete(cwd);
125
- return start(cwd);
126
- });
127
- queued.set(cwd, next);
128
- return next;
129
- }
130
- if (!opts?.fresh && hit && now() - hit.at < ttl) return hit.value;
131
- return start(cwd);
132
- },
133
- };
134
- }
@@ -1,29 +0,0 @@
1
- /**
2
- * Small structural helpers shared by the core modules.
3
- * See change: extract-mcp-client-plugin.
4
- */
5
-
6
- export function isPlainObject(v: unknown): v is Record<string, unknown> {
7
- return typeof v === "object" && v !== null && !Array.isArray(v);
8
- }
9
-
10
- /** Read a dotted path from a nested object tree, or undefined if any step is absent. */
11
- export function getByName(obj: unknown, path: string[]): unknown {
12
- let cur: unknown = obj;
13
- for (const key of path) {
14
- if (!isPlainObject(cur)) return undefined;
15
- cur = cur[key];
16
- }
17
- return cur;
18
- }
19
-
20
- /** Set a dotted path on a nested object tree, creating intermediate objects. */
21
- export function setByName(obj: Record<string, unknown>, path: string[], value: unknown): void {
22
- let cur: Record<string, unknown> = obj;
23
- for (let i = 0; i < path.length - 1; i += 1) {
24
- const key = path[i];
25
- if (!isPlainObject(cur[key])) cur[key] = {};
26
- cur = cur[key] as Record<string, unknown>;
27
- }
28
- cur[path[path.length - 1]] = value;
29
- }
@@ -1,220 +0,0 @@
1
- /**
2
- * mcp-client-plugin · CORE mirror of pi's built-in MCP entry rules.
3
- *
4
- * pi 1.0.0 does not export `validateMcpServerConfig` (its exports map has
5
- * only `.`, `./rpc-entry`, `./client`, `./experimental/plugin`) and this
6
- * package has no pi dependency, so the checks are mirrored here from
7
- * `dist/core/mcp-servers.js` + `dist/extensions/mcp/config.js`. The writer
8
- * runs them before every write so it never persists an entry pi rejects.
9
- *
10
- * See change: migrate-mcp-to-pi-builtin (D3 "Validation").
11
- */
12
-
13
- import { isPlainObject } from "./path-utils.js";
14
-
15
- export const MCP_EXPOSURES = ["codemode", "deferred", "direct", "hidden"] as const;
16
- export type McpExposure = (typeof MCP_EXPOSURES)[number];
17
- /** Older exposure names pi still accepts and resolves. */
18
- export const MCP_EXPOSURE_ALIASES: Readonly<Record<string, McpExposure>> = { "codemode-deferred": "codemode" };
19
-
20
- const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
21
- const SERVER_NAME = /^[A-Za-z0-9_-]+$/;
22
- /** Never usable as an object key (prototype pollution) — pi's regex alone admits `__proto__`. */
23
- const FORBIDDEN_NAMES = new Set(["__proto__", "constructor", "prototype"]);
24
-
25
- /**
26
- * Adapter-only (`pi-mcp-adapter`) entry keys. pi ignores unknown keys, so these
27
- * stay in a file but have no effect under the built-in MCP. `disabled: true`
28
- * is the dangerous one: pi treats such a server as ENABLED.
29
- */
30
- export const ADAPTER_ONLY_KEYS = [
31
- "disabled",
32
- "socket",
33
- "requestHeadersCommand",
34
- "bearerToken",
35
- "bearerTokenEnv",
36
- "bearerTokenStore",
37
- "lifecycle",
38
- "idleTimeout",
39
- "requestTimeoutMs",
40
- "exposeResources",
41
- "directTools",
42
- "toolPrefix",
43
- "includeTools",
44
- "excludeTools",
45
- "searchKeywords",
46
- "approveTools",
47
- "debug",
48
- "trace",
49
- "httpTransport",
50
- "pluginDataDir",
51
- "literalEnv",
52
- "protocolVersion",
53
- "inheritEnv",
54
- "caFile",
55
- "tasks",
56
- ] as const;
57
-
58
- /** Letters, digits, `_`, `-` (pi's rule), ≤128 chars, never a prototype key. */
59
- export function isValidServerName(name: string): boolean {
60
- return typeof name === "string" && name.length <= 128 && SERVER_NAME.test(name) && !FORBIDDEN_NAMES.has(name);
61
- }
62
-
63
- /** pi maps `-` to `_` for tool namespaces, so `a-b` and `a_b` collide. */
64
- export function mcpNamespace(name: string): string {
65
- return `mcp__${name.replace(/-/g, "_")}`;
66
- }
67
-
68
- function isLoopbackHost(hostname: string): boolean {
69
- return LOOPBACK_HOSTS.includes(hostname);
70
- }
71
-
72
- function isStringRecord(v: unknown): boolean {
73
- return isPlainObject(v) && Object.values(v).every((x) => typeof x === "string");
74
- }
75
-
76
- function isExposure(v: unknown): boolean {
77
- return typeof v === "string" && (MCP_EXPOSURES as readonly string[]).includes(v);
78
- }
79
-
80
- function resolveAlias(v: unknown): unknown {
81
- return typeof v === "string" ? (MCP_EXPOSURE_ALIASES[v] ?? v) : v;
82
- }
83
-
84
- /** Display form of an exposure value: aliases resolved, default `codemode`. */
85
- export function displayExposure(v: unknown): string {
86
- const r = resolveAlias(v);
87
- return typeof r === "string" ? r : "codemode";
88
- }
89
-
90
- function isLoopbackRedirectUri(value: string): boolean {
91
- if (!URL.canParse(value)) return false;
92
- const url = new URL(value);
93
- return url.protocol === "http:" && isLoopbackHost(url.hostname) && url.search === "" && url.hash === "";
94
- }
95
-
96
- function validateOAuth(value: unknown): string | undefined {
97
- if (value === undefined) return undefined;
98
- if (!isPlainObject(value)) return "oauth must be an object";
99
- if (value.clientId !== undefined && typeof value.clientId !== "string") return "oauth.clientId must be a string";
100
- if (value.clientSecret !== undefined && typeof value.clientSecret !== "string") {
101
- return "oauth.clientSecret must be a string";
102
- }
103
- const port = value.callbackPort;
104
- if (port !== undefined && (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)) {
105
- return "oauth.callbackPort must be a port number";
106
- }
107
- if (value.callbackUrl !== undefined) {
108
- if (typeof value.callbackUrl !== "string" || !isLoopbackRedirectUri(value.callbackUrl)) {
109
- return "oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment";
110
- }
111
- const urlPort = new URL(value.callbackUrl).port;
112
- if (urlPort && port !== undefined && Number(urlPort) !== port) {
113
- return "oauth.callbackUrl and oauth.callbackPort name different ports";
114
- }
115
- }
116
- if (value.scope !== undefined && typeof value.scope !== "string") return "oauth.scope must be a string";
117
- if (value.clientName !== undefined && (typeof value.clientName !== "string" || !value.clientName.trim())) {
118
- return "oauth.clientName must be a non-empty string";
119
- }
120
- const meta = value.authServerMetadataUrl;
121
- if (meta !== undefined) {
122
- const url = typeof meta === "string" && URL.canParse(meta) ? new URL(meta) : undefined;
123
- if (!url || !(url.protocol === "https:" || (url.protocol === "http:" && isLoopbackHost(url.hostname)))) {
124
- return "oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]";
125
- }
126
- }
127
- return undefined;
128
- }
129
-
130
- /**
131
- * Mirror of pi 1.0.0 `validateMcpServerConfig(name, raw)`: `null` when pi
132
- * accepts the entry, else pi's error message.
133
- */
134
- export function validatePiEntry(name: string, raw: unknown): string | null {
135
- if (!SERVER_NAME.test(name)) return `invalid server name "${name}" (use letters, digits, "_" and "-")`;
136
- if (!isPlainObject(raw)) return `server "${name}" must be an object`;
137
- const v = raw as Record<string, unknown>;
138
- const exposure = resolveAlias(v.exposure);
139
- const exposures = MCP_EXPOSURES.map((e) => `"${e}"`).join(", ");
140
- if (v.exposure !== undefined && !isExposure(exposure)) return `server "${name}": exposure must be one of ${exposures}`;
141
- if (v.toolExposure !== undefined) {
142
- if (!isPlainObject(v.toolExposure)) return `server "${name}": toolExposure must map tool names to exposures`;
143
- for (const [tool, e] of Object.entries(v.toolExposure)) {
144
- if (!isExposure(resolveAlias(e))) return `server "${name}": toolExposure "${tool}" must be one of ${exposures}`;
145
- }
146
- }
147
- if (v.enabled !== undefined && typeof v.enabled !== "boolean") return `server "${name}": enabled must be a boolean`;
148
- if (v.description !== undefined && typeof v.description !== "string") {
149
- return `server "${name}": description must be a string`;
150
- }
151
- if (v.timeout !== undefined && (typeof v.timeout !== "number" || !(v.timeout > 0))) {
152
- return `server "${name}": timeout must be a positive number of seconds`;
153
- }
154
- const type = v.type;
155
- if (type === "sse") return `server "${name}": legacy SSE transport is not supported; use the streamable HTTP URL`;
156
- if (typeof v.url === "string" && (type === undefined || type === "http" || type === "streamable-http")) {
157
- if (!URL.canParse(v.url) || !/^https?:$/.test(new URL(v.url).protocol)) {
158
- return `server "${name}": url must be an http or https URL`;
159
- }
160
- if (v.headers !== undefined && !isStringRecord(v.headers)) return `server "${name}": headers must map names to strings`;
161
- const oauthError = validateOAuth(v.oauth);
162
- if (oauthError) return `server "${name}": ${oauthError}`;
163
- if (v.auth !== undefined) {
164
- if (!isPlainObject(v.auth) || typeof v.auth.provider !== "string" || !v.auth.provider) {
165
- return `server "${name}": auth.provider must be a provider name`;
166
- }
167
- const url = new URL(v.url);
168
- if (url.protocol !== "https:" && !isLoopbackHost(url.hostname)) {
169
- return `server "${name}": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`;
170
- }
171
- }
172
- return null;
173
- }
174
- if (typeof v.command === "string" && (type === undefined || type === "stdio")) {
175
- if (v.args !== undefined && !(Array.isArray(v.args) && v.args.every((a) => typeof a === "string"))) {
176
- return `server "${name}": args must be an array of strings`;
177
- }
178
- if (v.env !== undefined && !isStringRecord(v.env)) return `server "${name}": env must map names to strings`;
179
- if (v.cwd !== undefined && typeof v.cwd !== "string") return `server "${name}": cwd must be a string`;
180
- return null;
181
- }
182
- return `server "${name}" needs either "command" (stdio) or "url" (streamable HTTP)`;
183
- }
184
-
185
- /** The transport pi picks: HTTP when `url` is set unless `type` is `stdio`. */
186
- export function transportOf(entry: Record<string, unknown>): "stdio" | "http" {
187
- if (typeof entry.url === "string" && entry.type !== "stdio") return "http";
188
- return "stdio";
189
- }
190
-
191
- /** Adapter-only keys present on an entry (plus non-object `auth` / `oauth: false`). */
192
- export function adapterLeftovers(entry: Record<string, unknown>): string[] {
193
- const keys: string[] = ADAPTER_ONLY_KEYS.filter((k) => Object.hasOwn(entry, k));
194
- if (entry.auth !== undefined && !isPlainObject(entry.auth)) keys.push("auth");
195
- if (entry.oauth === false) keys.push("oauth");
196
- return keys;
197
- }
198
-
199
- /** Keys pi ignores on this entry: adapter leftovers + the losing key of a dual transport. */
200
- export function ignoredKeys(entry: Record<string, unknown>): string[] {
201
- const keys = adapterLeftovers(entry);
202
- if (typeof entry.command === "string" && typeof entry.url === "string") {
203
- keys.push(transportOf(entry) === "http" ? "command" : "url");
204
- }
205
- return keys;
206
- }
207
-
208
- export type AuthMode = { kind: "provider"; provider: string } | { kind: "header" } | { kind: "oauth" };
209
-
210
- /** How pi authenticates an HTTP entry; `undefined` for stdio. */
211
- export function authModeOf(entry: Record<string, unknown>): AuthMode | undefined {
212
- if (transportOf(entry) !== "http") return undefined;
213
- if (isPlainObject(entry.auth) && typeof entry.auth.provider === "string" && entry.auth.provider) {
214
- return { kind: "provider", provider: entry.auth.provider };
215
- }
216
- if (isPlainObject(entry.headers) && Object.keys(entry.headers).some((k) => k.toLowerCase() === "authorization")) {
217
- return { kind: "header" };
218
- }
219
- return { kind: "oauth" };
220
- }
@@ -1,52 +0,0 @@
1
- /**
2
- * mcp-client-plugin · JSON-Schema validation for server entries.
3
- *
4
- * Uses the plugin's OWN Ajv instance — `strict: true`, `useDefaults: false`,
5
- * `allErrors: true` — NOT the runtime's `config-validator` (whose
6
- * `useDefaults: true` would inject schema defaults into an entry, and whose
7
- * strict mode rejects the `x-` annotation keywords). The writer additionally
8
- * mirrors pi's own entry rules (`pi-rules.ts`).
9
- *
10
- * See change: migrate-mcp-to-pi-builtin; earlier: extract-mcp-client-plugin (D7).
11
- */
12
-
13
- import Ajv, { type ErrorObject, type ValidateFunction } from "ajv";
14
- import schema from "../../schema/mcp-config.schema.json";
15
-
16
- export interface PatchValidation {
17
- ok: boolean;
18
- errors: ErrorObject[];
19
- }
20
-
21
- function buildAjv(): Ajv {
22
- const ajv = new Ajv({ strict: true, useDefaults: false, allErrors: true });
23
- // Custom annotation keywords: registration is what makes strict mode accept them.
24
- ajv.addKeyword({ keyword: "x-secret" });
25
- ajv.addKeyword({ keyword: "x-transport" });
26
- ajv.addKeyword({ keyword: "x-global-only" });
27
- ajv.addSchema(schema, "mcp-config");
28
- return ajv;
29
- }
30
-
31
- const ajv = buildAjv();
32
-
33
- function compile(ref: string): ValidateFunction {
34
- const fn = ajv.getSchema(`mcp-config#/$defs/${ref}`);
35
- if (!fn) throw new Error(`schema $def ${ref} did not compile`);
36
- return fn;
37
- }
38
-
39
- const validateServer = compile("ServerEntry");
40
-
41
- export function validateServerEntry(entry: unknown): PatchValidation {
42
- const valid = validateServer(entry) as boolean;
43
- return { ok: valid, errors: valid ? [] : (validateServer.errors ?? []) };
44
- }
45
-
46
- /** Field names from Ajv errors (drop the leading slash of `instancePath`). */
47
- export function errorFields(errors: ErrorObject[]): string[] {
48
- return errors.map((e) => e.instancePath.replace(/^\//, "").split("/")[0]).filter((f) => f.length > 0);
49
- }
50
-
51
- /** Exposed for the compile-contract test and the schema route. */
52
- export const mcpConfigSchema = schema;
@@ -1,96 +0,0 @@
1
- /**
2
- * mcp-client-plugin · `mcp-client.config` service factory.
3
- *
4
- * Composes the writer, the effective-view reader and (optionally) the
5
- * `pi mcp list` live-state reader behind the in-process service contract
6
- * other plugins consume. A hostless caller (the apple-tools CLI) gets the
7
- * identical implementation from this factory; without an `isProjectTrusted`
8
- * predicate every project counts as untrusted.
9
- *
10
- * See change: migrate-mcp-to-pi-builtin (D3); earlier: extract-mcp-client-plugin (D4).
11
- */
12
-
13
- import { mkdtempSync } from "node:fs";
14
- import { tmpdir } from "node:os";
15
- import { join } from "node:path";
16
- import { createConfigWriter } from "./config-writer.js";
17
- import { createEffectiveViewReader } from "./effective-view.js";
18
- import { defaultLayerPaths, type LayerPaths } from "./layers.js";
19
- import { createLiveStateReader } from "./live-state.js";
20
- import type { ConfigIO, LiveState, McpClientConfigService, PiMcpListRunner, Scope } from "./types.js";
21
-
22
- export interface McpClientConfigServiceDeps {
23
- configIO: ConfigIO;
24
- knownCwds: () => string[];
25
- /** pi's project-trust rule (`host.isProjectTrusted`). Absent → untrusted. */
26
- isProjectTrusted?: (cwd: string) => boolean;
27
- /** Layer paths. Defaults to `$PI_CODING_AGENT_DIR/mcp.json` + `<cwd>/.pi/mcp.json`. */
28
- paths?: LayerPaths;
29
- /** Runs `pi mcp list --json`. Absent → live state reports `spawn-failed`. */
30
- runner?: PiMcpListRunner;
31
- /** Always-empty dir the global live-state list runs in. Defaults to a fresh mkdtemp. */
32
- scratchCwd?: string;
33
- liveTimeoutMs?: number;
34
- liveCacheTtlMs?: number;
35
- }
36
-
37
- /** The provided service plus the live-state reader the HTTP layer needs. */
38
- export interface McpClientRuntime extends McpClientConfigService {
39
- getLiveState(scope: Scope, opts?: { fresh?: boolean }): Promise<LiveState>;
40
- }
41
-
42
- export function createMcpClientConfigService(deps: McpClientConfigServiceDeps): McpClientRuntime {
43
- const paths = deps.paths ?? defaultLayerPaths();
44
- const writer = createConfigWriter({
45
- configIO: deps.configIO,
46
- paths,
47
- knownCwds: deps.knownCwds,
48
- ...(deps.isProjectTrusted ? { isProjectTrusted: deps.isProjectTrusted } : {}),
49
- });
50
- const viewReader = createEffectiveViewReader({
51
- configIO: deps.configIO,
52
- paths,
53
- ...(deps.isProjectTrusted ? { isProjectTrusted: deps.isProjectTrusted } : {}),
54
- });
55
- const runner: PiMcpListRunner =
56
- deps.runner ?? (() => Promise.reject(new Error("no pi mcp list runner configured")));
57
- const live = createLiveStateReader({
58
- runner,
59
- ...(deps.liveTimeoutMs !== undefined ? { timeoutMs: deps.liveTimeoutMs } : {}),
60
- ...(deps.liveCacheTtlMs !== undefined ? { cacheTtlMs: deps.liveCacheTtlMs } : {}),
61
- });
62
- let scratch = deps.scratchCwd;
63
- const scratchCwd = (): string => {
64
- scratch ??= mkdtempSync(join(tmpdir(), "pi-mcp-client-"));
65
- return scratch;
66
- };
67
-
68
- return {
69
- targetPath: (scope) => writer.targetPath(scope),
70
- readServerEntry: (name, scope) => writer.readServerEntry(name, scope),
71
- getEffectiveView: (scope) => viewReader.getEffectiveView(scope),
72
- ensureServerEntry: (name, fields, scope) => writer.ensureServerEntry(name, fields, scope),
73
- saveServer: (name, entry, scope, opts) => writer.saveServer(name, entry, scope, opts),
74
- removeServer: (name, scope) => writer.removeServer(name, scope),
75
- setEnabled: (name, enabled, scope) => writer.setEnabled(name, enabled, scope),
76
- convertAdapterLeftovers: (name, scope) => writer.convertAdapterLeftovers(name, scope),
77
-
78
- checkConfigFiles(opts) {
79
- const path = paths.globalPath();
80
- let mcpJson = writer.readParseStatus(path);
81
- // A dry run of the ensure the caller is about to perform, so check mode
82
- // and write mode agree on the refusal.
83
- if (mcpJson.ok && opts?.serverName !== undefined) {
84
- const refusal = writer.previewEnsure(opts.serverName, opts.fields ?? {}, { kind: "global" });
85
- if (refusal) mcpJson = { path, ok: false, message: refusal.message };
86
- }
87
- return { mcpJson };
88
- },
89
-
90
- getLiveState(scope, opts) {
91
- const cwd = scope.kind === "project" ? scope.cwd : scratchCwd();
92
- if (scope.kind === "project") writer.targetPath(scope); // admission
93
- return live.read(cwd, opts);
94
- },
95
- };
96
- }