@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,70 @@
1
+ /**
2
+ * mcp-client-plugin · real filesystem ConfigIO.
3
+ *
4
+ * The hardened atomic write moved here from `apple-tools/src/env.ts` so the
5
+ * core owns it and every consumer (dashboard server, hostless installer CLI)
6
+ * shares one implementation:
7
+ * - `wx` + a random name: never follow or clobber a pre-planted symlink.
8
+ * - mode 0600: a rename carries the temp file's mode onto the destination.
9
+ * - fsync before rename: no zero-length config after a crash.
10
+ * - unlink the temp on failure: no leftovers on ENOSPC/EACCES.
11
+ *
12
+ * See change: extract-mcp-client-plugin (task 2.1).
13
+ */
14
+
15
+ import { randomBytes } from "node:crypto";
16
+ import {
17
+ closeSync,
18
+ existsSync,
19
+ fsyncSync,
20
+ mkdirSync,
21
+ openSync,
22
+ readFileSync,
23
+ renameSync,
24
+ unlinkSync,
25
+ writeSync,
26
+ } from "node:fs";
27
+ import { dirname, join } from "node:path";
28
+ import type { ConfigIO } from "./types.js";
29
+
30
+ export function writeFileAtomic(path: string, content: string): void {
31
+ const dir = dirname(path);
32
+ mkdirSync(dir, { recursive: true });
33
+ const tmp = join(dir, `.${randomBytes(8).toString("hex")}.tmp`);
34
+ const fd = openSync(tmp, "wx", 0o600);
35
+ try {
36
+ const buf = Buffer.from(content, "utf8");
37
+ let off = 0;
38
+ while (off < buf.length) {
39
+ off += writeSync(fd, buf, off, buf.length - off);
40
+ }
41
+ fsyncSync(fd);
42
+ } catch (e) {
43
+ closeSync(fd);
44
+ try {
45
+ unlinkSync(tmp);
46
+ } catch {
47
+ /* best effort */
48
+ }
49
+ throw e;
50
+ }
51
+ closeSync(fd);
52
+ try {
53
+ renameSync(tmp, path);
54
+ } catch (e) {
55
+ try {
56
+ unlinkSync(tmp);
57
+ } catch {
58
+ /* best effort */
59
+ }
60
+ throw e;
61
+ }
62
+ }
63
+
64
+ /** A ConfigIO wired to the real filesystem. */
65
+ export function createRealConfigIO(): ConfigIO {
66
+ return {
67
+ readFile: (p) => (existsSync(p) ? readFileSync(p, "utf8") : null),
68
+ writeFileAtomic,
69
+ };
70
+ }
@@ -0,0 +1,407 @@
1
+ /**
2
+ * mcp-client-plugin · CORE config writer over pi's built-in MCP layers.
3
+ *
4
+ * Every write targets exactly one layer (`global` → the Pi-global `mcp.json`,
5
+ * `project` → `<cwd>/.pi/mcp.json`), replaces or deletes exactly one
6
+ * `mcpServers.<name>` entry, preserves every other entry and top-level key,
7
+ * writes atomically, and refuses to write over a file pi cannot parse
8
+ * (strict JSON). Before any byte is written the resulting entry is checked
9
+ * against the mirrored pi rules (`pi-rules.ts`), the dashboard's transport
10
+ * rule, project-scope `auth`, and `-`/`_` namespace collisions, so the
11
+ * writer never persists an entry pi would reject or drop.
12
+ *
13
+ * Refusals are the closed {@link ConfigRefusalCode} set, shared with
14
+ * `checkConfigFiles` (same `planEnsure` function), so check mode can never
15
+ * report a healthy file that write mode would refuse.
16
+ *
17
+ * See change: migrate-mcp-to-pi-builtin (D3); earlier: extract-mcp-client-plugin.
18
+ */
19
+
20
+ import { isAllowedCwd } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
21
+ import { type LayerPaths, type LayerRead, nullProto, readLayer } from "./layers.js";
22
+ import { isPlainObject } from "./path-utils.js";
23
+ import { ADAPTER_ONLY_KEYS, isValidServerName, mcpNamespace, transportOf, validatePiEntry } from "./pi-rules.js";
24
+ import type {
25
+ ConfigIO,
26
+ ConfigRefusal,
27
+ ConfigWriteResult,
28
+ ParseStatus,
29
+ RemoveResult,
30
+ Scope,
31
+ ServerEntry,
32
+ SetEnabledResult,
33
+ } from "./types.js";
34
+
35
+ /** Thrown when a project scope names a cwd outside the known-folder set. */
36
+ export class NotAllowedCwdError extends Error {
37
+ constructor(public readonly cwd: string) {
38
+ super(`cwd not allowed: ${cwd}`);
39
+ this.name = "NotAllowedCwdError";
40
+ }
41
+ }
42
+
43
+ /** Secret-bearing fields never copied silently from the global entry into a folder copy. */
44
+ export const FOLDER_COPY_OMITTED = ["headers", "env", "oauth.clientSecret", "auth"] as const;
45
+
46
+ export interface ConfigWriterDeps {
47
+ configIO: ConfigIO;
48
+ paths: LayerPaths;
49
+ knownCwds: () => string[];
50
+ /** pi's project-trust rule. Absent → every project is untrusted. */
51
+ isProjectTrusted?: (cwd: string) => boolean;
52
+ }
53
+
54
+ export interface ConfigWriter {
55
+ targetPath(scope: Scope): string;
56
+ readServerEntry(name: string, scope: Scope): ServerEntry | undefined;
57
+ ensureServerEntry(name: string, fields: Partial<ServerEntry>, scope: Scope): ConfigWriteResult;
58
+ saveServer(
59
+ name: string,
60
+ entry: ServerEntry,
61
+ scope: Scope,
62
+ opts?: { previousName?: string; create?: boolean },
63
+ ): ConfigWriteResult;
64
+ removeServer(name: string, scope: Scope): RemoveResult;
65
+ setEnabled(name: string, enabled: boolean, scope: Scope): SetEnabledResult;
66
+ convertAdapterLeftovers(name: string, scope: Scope): ConfigWriteResult;
67
+ /** Dry run of `ensureServerEntry`: the refusal it would return, or null. */
68
+ previewEnsure(name: string, fields: Partial<ServerEntry>, scope: Scope): ConfigRefusal | null;
69
+ readParseStatus(path: string): ParseStatus;
70
+ }
71
+
72
+ type Prepared =
73
+ | { ok: true; path: string; layer: Extract<LayerRead, { ok: true }> }
74
+ | { ok: false; refusal: ConfigRefusal };
75
+
76
+ /** A copy of a global entry for a folder layer, without secret values or `auth`. */
77
+ export function folderCopyOf(entry: Record<string, unknown>): { copy: Record<string, unknown>; omitted: string[] } {
78
+ const copy = nullProto({ ...entry });
79
+ const omitted: string[] = [];
80
+ for (const k of ["headers", "env", "auth"] as const) {
81
+ if (copy[k] !== undefined) {
82
+ delete copy[k];
83
+ omitted.push(k);
84
+ }
85
+ }
86
+ if (isPlainObject(copy.oauth) && copy.oauth.clientSecret !== undefined) {
87
+ const { clientSecret: _drop, ...rest } = copy.oauth;
88
+ copy.oauth = rest;
89
+ omitted.push("oauth.clientSecret");
90
+ }
91
+ return { copy, omitted };
92
+ }
93
+
94
+ export function createConfigWriter(deps: ConfigWriterDeps): ConfigWriter {
95
+ const { configIO, paths, knownCwds } = deps;
96
+ const trusted = (cwd: string): boolean => deps.isProjectTrusted?.(cwd) === true;
97
+
98
+ function targetPath(scope: Scope): string {
99
+ if (scope.kind === "global") return paths.globalPath();
100
+ if (!isAllowedCwd(scope.cwd, knownCwds)) throw new NotAllowedCwdError(scope.cwd);
101
+ return paths.projectPath(scope.cwd);
102
+ }
103
+
104
+ function nameRefusal(name: string): ConfigRefusal | null {
105
+ if (isValidServerName(name)) return null;
106
+ return {
107
+ code: "invalid-name",
108
+ message: `invalid server name ${JSON.stringify(name)} (use letters, digits, "_" and "-")`,
109
+ };
110
+ }
111
+
112
+ function prepare(name: string, scope: Scope): Prepared {
113
+ const bad = nameRefusal(name);
114
+ if (bad) return { ok: false, refusal: bad };
115
+ const path = targetPath(scope);
116
+ const layer = readLayer(configIO, path);
117
+ if (!layer.ok) {
118
+ return {
119
+ ok: false,
120
+ refusal: { code: "unparseable", message: `${layer.message} (pi skips this file; fix it by hand)`, path },
121
+ };
122
+ }
123
+ return { ok: true, path, layer };
124
+ }
125
+
126
+ /** Every entry a write could collide with, and the file it lives in. */
127
+ function collisionCandidates(scope: Scope): Array<{ name: string; path: string }> {
128
+ const out: Array<{ name: string; path: string }> = [];
129
+ const add = (path: string): void => {
130
+ const l = readLayer(configIO, path);
131
+ if (l.ok) for (const n of Object.keys(l.servers)) out.push({ name: n, path });
132
+ };
133
+ add(paths.globalPath());
134
+ if (scope.kind === "project") {
135
+ add(paths.projectPath(scope.cwd));
136
+ } else {
137
+ // pi loads the global layer first, then the trusted project layer, and
138
+ // DROPS the project entry on a collision — so a global write must not
139
+ // collide with any known trusted folder's entry.
140
+ for (const cwd of knownCwds()) if (trusted(cwd)) add(paths.projectPath(cwd));
141
+ }
142
+ return out;
143
+ }
144
+
145
+ /**
146
+ * Validation shared by every write that sets an entry's content. `replacing`
147
+ * names the entry a rename removes; it is excluded from the collision check
148
+ * only in the TARGET layer — a same-named entry in another layer still
149
+ * collides (pi would drop it).
150
+ */
151
+ function validateEntry(
152
+ name: string,
153
+ entry: Record<string, unknown>,
154
+ scope: Scope,
155
+ replacing?: string,
156
+ ): ConfigRefusal | null {
157
+ if (typeof entry.command === "string" && typeof entry.url === "string") {
158
+ return {
159
+ code: "transport-conflict",
160
+ message: `server "${name}" carries both command and url; keep exactly one transport`,
161
+ fields: ["command", "url"],
162
+ };
163
+ }
164
+ const piError = validatePiEntry(name, entry);
165
+ if (piError) return { code: "invalid-entry", message: piError };
166
+ if (scope.kind === "project" && entry.auth !== undefined && transportOf(entry) === "http") {
167
+ return {
168
+ code: "invalid-entry",
169
+ message: `server "${name}": auth is only allowed in the global mcp.json (provider auth is global-only)`,
170
+ };
171
+ }
172
+ const ns = mcpNamespace(name);
173
+ const target = targetPath(scope);
174
+ const clash = collisionCandidates(scope).find(
175
+ (c) =>
176
+ c.name !== name && !(c.name === replacing && c.path === target) && mcpNamespace(c.name) === ns,
177
+ );
178
+ if (clash) {
179
+ return {
180
+ code: "name-collision",
181
+ message: `server "${name}" conflicts with "${clash.name}" in ${clash.path} (pi maps "-" and "_" to one namespace)`,
182
+ conflict: { name: clash.name, path: clash.path },
183
+ };
184
+ }
185
+ return null;
186
+ }
187
+
188
+ function write(path: string, config: Record<string, unknown>, servers: Record<string, unknown>): ConfigWriteResult {
189
+ const next = nullProto({ ...config });
190
+ next.mcpServers = servers;
191
+ if (JSON.stringify(next) === JSON.stringify(config)) return { ok: true };
192
+ try {
193
+ configIO.writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\n`);
194
+ return { ok: true };
195
+ } catch (e) {
196
+ const err = e as NodeJS.ErrnoException;
197
+ return {
198
+ ok: false,
199
+ refusal: {
200
+ code: "write-failed",
201
+ message: `failed to write ${path}: ${err.message}`,
202
+ path,
203
+ ...(err.code ? { ioCode: err.code } : {}),
204
+ },
205
+ };
206
+ }
207
+ }
208
+
209
+ function existingObject(
210
+ p: Extract<Prepared, { ok: true }>,
211
+ name: string,
212
+ ): { ok: true; entry: Record<string, unknown> | undefined } | { ok: false; refusal: ConfigRefusal } {
213
+ const raw = p.layer.servers[name];
214
+ if (raw === undefined) return { ok: true, entry: undefined };
215
+ if (!isPlainObject(raw)) {
216
+ return {
217
+ ok: false,
218
+ refusal: { code: "entry-not-object", message: `${p.path}: server "${name}" is not an object`, path: p.path },
219
+ };
220
+ }
221
+ return { ok: true, entry: nullProto({ ...raw }) };
222
+ }
223
+
224
+ function planEnsure(
225
+ name: string,
226
+ fields: Partial<ServerEntry>,
227
+ scope: Scope,
228
+ ): { ok: true; p: Extract<Prepared, { ok: true }>; next: Record<string, unknown> } | { ok: false; refusal: ConfigRefusal } {
229
+ const p = prepare(name, scope);
230
+ if (!p.ok) return p;
231
+ const existing = existingObject(p, name);
232
+ if (!existing.ok) return existing;
233
+ const next = nullProto({ ...(existing.entry ?? {}) });
234
+ for (const [k, v] of Object.entries(fields)) {
235
+ if (v === undefined) delete next[k];
236
+ else next[k] = v;
237
+ }
238
+ const refusal = validateEntry(name, next, scope);
239
+ if (refusal) return { ok: false, refusal };
240
+ return { ok: true, p, next };
241
+ }
242
+
243
+ function ensureServerEntry(name: string, fields: Partial<ServerEntry>, scope: Scope): ConfigWriteResult {
244
+ const plan = planEnsure(name, fields, scope);
245
+ if (!plan.ok) return plan;
246
+ const servers = nullProto({ ...plan.p.layer.servers });
247
+ servers[name] = plan.next;
248
+ return write(plan.p.path, plan.p.layer.config, servers);
249
+ }
250
+
251
+ function previewEnsure(name: string, fields: Partial<ServerEntry>, scope: Scope): ConfigRefusal | null {
252
+ const plan = planEnsure(name, fields, scope);
253
+ return plan.ok ? null : plan.refusal;
254
+ }
255
+
256
+ function saveServer(
257
+ name: string,
258
+ entry: ServerEntry,
259
+ scope: Scope,
260
+ opts?: { previousName?: string; create?: boolean },
261
+ ): ConfigWriteResult {
262
+ const p = prepare(name, scope);
263
+ if (!p.ok) return p;
264
+ if (!isPlainObject(entry)) {
265
+ return { ok: false, refusal: { code: "invalid-entry", message: `server "${name}" must be an object` } };
266
+ }
267
+ const prev = opts?.previousName;
268
+ const renaming = prev !== undefined && prev !== name;
269
+ if (renaming) {
270
+ const bad = nameRefusal(prev);
271
+ if (bad) return { ok: false, refusal: bad };
272
+ }
273
+ // A rename or a create never replaces another entry: one write, one entry.
274
+ if ((renaming || opts?.create === true) && p.layer.servers[name] !== undefined) {
275
+ return {
276
+ ok: false,
277
+ refusal: {
278
+ code: "name-collision",
279
+ message: `${p.path} already defines "${name}"${renaming ? ` (cannot rename "${prev}" onto it)` : ""}`,
280
+ conflict: { name, path: p.path },
281
+ },
282
+ };
283
+ }
284
+ const next = nullProto({ ...(entry as Record<string, unknown>) });
285
+ const refusal = validateEntry(name, next, scope, prev);
286
+ if (refusal) return { ok: false, refusal };
287
+ const servers = nullProto({ ...p.layer.servers });
288
+ if (renaming) delete servers[prev];
289
+ servers[name] = next;
290
+ return write(p.path, p.layer.config, servers);
291
+ }
292
+
293
+ function removeServer(name: string, scope: Scope): RemoveResult {
294
+ const p = prepare(name, scope);
295
+ if (!p.ok) return p;
296
+ const removed = p.layer.servers[name] as ServerEntry | undefined;
297
+ if (removed === undefined) return { ok: true, removed: undefined };
298
+ const servers = nullProto({ ...p.layer.servers });
299
+ delete servers[name];
300
+ const w = write(p.path, p.layer.config, servers);
301
+ return w.ok ? { ok: true, removed } : w;
302
+ }
303
+
304
+ function setEnabled(name: string, enabled: boolean, scope: Scope): SetEnabledResult {
305
+ const p = prepare(name, scope);
306
+ if (!p.ok) return p;
307
+ const existing = existingObject(p, name);
308
+ if (!existing.ok) return existing;
309
+
310
+ // The global entry a folder entry replaces (project scope only).
311
+ let globalEntry: Record<string, unknown> | undefined;
312
+ if (scope.kind === "project") {
313
+ const g = readLayer(configIO, paths.globalPath());
314
+ const raw = g.ok ? g.servers[name] : undefined;
315
+ globalEntry = isPlainObject(raw) ? raw : undefined;
316
+ }
317
+
318
+ if (existing.entry !== undefined) {
319
+ const next = existing.entry;
320
+ if (enabled) {
321
+ // Enabling a folder copy that lacks the global entry's secrets would
322
+ // connect without credentials: let the caller choose instead.
323
+ if (globalEntry !== undefined && next.enabled === false) {
324
+ const missing = folderCopyOf(globalEntry).omitted.filter((f) => !hasPath(next, f));
325
+ if (missing.length > 0) return { ok: true, action: "needs-choice", omitted: missing };
326
+ }
327
+ delete next.enabled;
328
+ } else {
329
+ next.enabled = false;
330
+ }
331
+ const servers = nullProto({ ...p.layer.servers });
332
+ servers[name] = next;
333
+ const w = write(p.path, p.layer.config, servers);
334
+ return w.ok ? { ok: true, action: "written" } : w;
335
+ }
336
+
337
+ if (scope.kind === "project" && globalEntry !== undefined) {
338
+ if (enabled) return { ok: true, action: "written" }; // the global entry already applies
339
+ // pi replaces entries as a whole: disabling here needs a complete copy.
340
+ const { copy, omitted } = folderCopyOf(globalEntry);
341
+ copy.enabled = false;
342
+ const servers = nullProto({ ...p.layer.servers });
343
+ servers[name] = copy;
344
+ const w = write(p.path, p.layer.config, servers);
345
+ return w.ok ? { ok: true, action: "written", ...(omitted.length ? { omitted } : {}) } : w;
346
+ }
347
+
348
+ return {
349
+ ok: false,
350
+ refusal: { code: "invalid-entry", message: `no MCP server named "${name}" in ${p.path}`, path: p.path },
351
+ };
352
+ }
353
+
354
+ function convertAdapterLeftovers(name: string, scope: Scope): ConfigWriteResult {
355
+ const p = prepare(name, scope);
356
+ if (!p.ok) return p;
357
+ const existing = existingObject(p, name);
358
+ if (!existing.ok) return existing;
359
+ const next = existing.entry;
360
+ if (next === undefined) {
361
+ return {
362
+ ok: false,
363
+ refusal: { code: "invalid-entry", message: `no MCP server named "${name}" in ${p.path}`, path: p.path },
364
+ };
365
+ }
366
+ if (next.disabled === true && next.enabled === undefined) next.enabled = false;
367
+ for (const k of ADAPTER_ONLY_KEYS) delete next[k];
368
+ if (next.auth !== undefined && !isPlainObject(next.auth)) delete next.auth;
369
+ if (next.oauth === false) delete next.oauth;
370
+ const servers = nullProto({ ...p.layer.servers });
371
+ servers[name] = next;
372
+ return write(p.path, p.layer.config, servers);
373
+ }
374
+
375
+ function readServerEntry(name: string, scope: Scope): ServerEntry | undefined {
376
+ if (!isValidServerName(name)) return undefined;
377
+ const l = readLayer(configIO, targetPath(scope));
378
+ if (!l.ok) return undefined;
379
+ const raw = l.servers[name];
380
+ return raw === undefined ? undefined : (raw as ServerEntry);
381
+ }
382
+
383
+ function readParseStatus(path: string): ParseStatus {
384
+ const l = readLayer(configIO, path);
385
+ return l.ok ? { path, ok: true } : { path, ok: false, message: l.message };
386
+ }
387
+
388
+ return {
389
+ targetPath,
390
+ readServerEntry,
391
+ ensureServerEntry,
392
+ saveServer,
393
+ removeServer,
394
+ setEnabled,
395
+ convertAdapterLeftovers,
396
+ previewEnsure,
397
+ readParseStatus,
398
+ };
399
+ }
400
+
401
+ function hasPath(entry: Record<string, unknown>, dotted: string): boolean {
402
+ const [head, tail] = dotted.split(".");
403
+ const v = entry[head];
404
+ if (tail === undefined) return v !== undefined;
405
+ return isPlainObject(v) && v[tail] !== undefined;
406
+ }
407
+
@@ -0,0 +1,197 @@
1
+ /**
2
+ * mcp-client-plugin · CORE effective-view reader over pi's two MCP layers.
3
+ *
4
+ * Mirrors pi 1.0.0 `loadMcpConfig`: the Pi-global layer loads first, then —
5
+ * only when pi trusts the project — `<cwd>/.pi/mcp.json`, whose entries
6
+ * REPLACE global entries of the same name as a whole. Each entry is checked
7
+ * with the mirrored pi rules; an entry pi would reject or drop (invalid,
8
+ * `-`/`_` collision, project `auth`) is shown inactive with pi's message. An
9
+ * untrusted project's entries are shown inactive ("project not trusted").
10
+ *
11
+ * Secrets: in a project view, a GLOBAL entry's secret values are redacted
12
+ * server-side (`headers`/`env` → `{redacted, keys}`, `oauth.clientSecret` →
13
+ * `{redacted}`) — the folder surface must never receive an inherited
14
+ * credential. Own-layer entries are returned verbatim (the client masks them).
15
+ *
16
+ * See change: migrate-mcp-to-pi-builtin (D3); earlier: extract-mcp-client-plugin.
17
+ */
18
+
19
+ import { type LayerPaths, readLayer } from "./layers.js";
20
+ import { getByName, isPlainObject, setByName } from "./path-utils.js";
21
+ import {
22
+ adapterLeftovers,
23
+ authModeOf,
24
+ displayExposure,
25
+ ignoredKeys,
26
+ mcpNamespace,
27
+ transportOf,
28
+ validatePiEntry,
29
+ } from "./pi-rules.js";
30
+ import type { ConfigIO, EffectiveServerView, EffectiveView, LayerStatus, Provenance, Scope } from "./types.js";
31
+
32
+ /** Credential-name pattern for record keys (key NAMES are never secret). */
33
+ export function isSecretKey(name: string): boolean {
34
+ return /authorization|token|key|secret/i.test(name);
35
+ }
36
+
37
+ // Adapter-era leftovers (`bearerToken`, `requestHeadersCommand.env`) are
38
+ // ignored by pi but can still hold a credential, so they are redacted too.
39
+ const RECORD_SECRET_PATHS: string[][] = [["env"], ["headers"], ["requestHeadersCommand", "env"]];
40
+ const SCALAR_SECRET_PATHS: string[][] = [["oauth", "clientSecret"], ["bearerToken"]];
41
+
42
+ /** Replace secret values with markers (key names kept). */
43
+ export function redactEntry(entry: Record<string, unknown>): Record<string, unknown> {
44
+ const out = { ...entry };
45
+ for (const path of RECORD_SECRET_PATHS) {
46
+ const v = getByName(entry, path);
47
+ if (isPlainObject(v)) {
48
+ // Copy the parent first: the shallow copy shares nested objects with the raw entry.
49
+ const parent = path.slice(0, -1);
50
+ if (parent.length > 0) setByName(out, parent, { ...(getByName(entry, parent) as Record<string, unknown>) });
51
+ setByName(out, path, { redacted: true, keys: Object.keys(v).map((k) => ({ name: k, secret: isSecretKey(k) })) });
52
+ }
53
+ }
54
+ for (const path of SCALAR_SECRET_PATHS) {
55
+ if (getByName(entry, path) === undefined) continue;
56
+ // Copy the parent object first: `setByName` mutates in place and the
57
+ // shallow copy above still shares nested objects with the raw entry.
58
+ const parent = path.slice(0, -1);
59
+ if (parent.length > 0) setByName(out, parent, { ...(getByName(entry, parent) as Record<string, unknown>) });
60
+ setByName(out, path, { redacted: true });
61
+ }
62
+ return out;
63
+ }
64
+
65
+ export interface EffectiveViewDeps {
66
+ configIO: ConfigIO;
67
+ paths: LayerPaths;
68
+ isProjectTrusted?: (cwd: string) => boolean;
69
+ }
70
+
71
+ export interface EffectiveViewReader {
72
+ getEffectiveView(scope: Scope): EffectiveView;
73
+ }
74
+
75
+ function describe(
76
+ name: string,
77
+ raw: unknown,
78
+ provenance: Provenance,
79
+ redact: boolean,
80
+ ): EffectiveServerView {
81
+ const entry = isPlainObject(raw) ? (raw as Record<string, unknown>) : {};
82
+ const piError = validatePiEntry(name, raw);
83
+ const enabled = entry.enabled !== false;
84
+ const view: EffectiveServerView = {
85
+ name,
86
+ provenance,
87
+ entry: redact ? redactEntry(entry) : { ...entry },
88
+ transport: transportOf(entry),
89
+ enabled,
90
+ exposure: displayExposure(entry.exposure),
91
+ active: piError === null && enabled,
92
+ ignoredKeys: ignoredKeys(entry),
93
+ adapterLeftovers: adapterLeftovers(entry),
94
+ };
95
+ const auth = authModeOf(entry);
96
+ if (auth) view.authMode = auth;
97
+ if (piError) {
98
+ view.piError = piError;
99
+ view.inactiveReason = "invalid-entry";
100
+ } else if (!enabled) {
101
+ view.inactiveReason = "disabled";
102
+ }
103
+ return view;
104
+ }
105
+
106
+ function deactivate(v: EffectiveServerView, reason: EffectiveServerView["inactiveReason"], message?: string): void {
107
+ v.active = false;
108
+ v.inactiveReason = reason;
109
+ if (message) v.piError = message;
110
+ }
111
+
112
+ export function createEffectiveViewReader(deps: EffectiveViewDeps): EffectiveViewReader {
113
+ const { configIO, paths } = deps;
114
+
115
+ function getEffectiveView(scope: Scope): EffectiveView {
116
+ const globalPath = paths.globalPath();
117
+ const g = readLayer(configIO, globalPath);
118
+ const layers: LayerStatus[] = [
119
+ { layer: "pi-global", path: globalPath, exists: g.exists, ok: g.ok, ...(g.ok ? {} : { message: g.message }) },
120
+ ];
121
+ const isProject = scope.kind === "project";
122
+
123
+ // Global layer, in pi's load order (collisions within the file: first wins).
124
+ const byName = new Map<string, EffectiveServerView>();
125
+ const loadedNs = new Map<string, string>(); // namespace → loaded name
126
+ if (g.ok) {
127
+ for (const [name, raw] of Object.entries(g.servers)) {
128
+ const v = describe(name, raw, "pi-global", isProject);
129
+ if (!v.piError) {
130
+ const clash = loadedNs.get(mcpNamespace(name));
131
+ if (clash) deactivate(v, "name-collision", `server "${name}" conflicts with "${clash}"`);
132
+ else loadedNs.set(mcpNamespace(name), name);
133
+ }
134
+ byName.set(name, v);
135
+ }
136
+ }
137
+
138
+ if (scope.kind === "global") {
139
+ return { scope: "global", servers: sortByName([...byName.values()]), layers };
140
+ }
141
+
142
+ const cwd = scope.cwd;
143
+ const trusted = deps.isProjectTrusted?.(cwd) === true;
144
+ const projectPath = paths.projectPath(cwd);
145
+ const pl = readLayer(configIO, projectPath);
146
+ layers.push({ layer: "pi-folder", path: projectPath, exists: pl.exists, ok: pl.ok, ...(pl.ok ? {} : { message: pl.message }) });
147
+
148
+ const folderRows: EffectiveServerView[] = [];
149
+ if (pl.ok) {
150
+ for (const [name, raw] of Object.entries(pl.servers)) {
151
+ const v = describe(name, raw, "pi-folder", false);
152
+ const global = byName.get(name);
153
+ if (!trusted) {
154
+ // pi never reads this file: the global entry (if any) stays in effect.
155
+ deactivate(v, "project-not-trusted");
156
+ folderRows.push(v);
157
+ continue;
158
+ }
159
+ if (v.piError) {
160
+ // pi drops an invalid project entry; the global one stays in effect.
161
+ folderRows.push(v);
162
+ continue;
163
+ }
164
+ {
165
+ const clash = loadedNs.get(mcpNamespace(name));
166
+ if (clash && clash !== name) {
167
+ deactivate(v, "name-collision", `server "${name}" conflicts with "${clash}"`);
168
+ folderRows.push(v);
169
+ continue;
170
+ }
171
+ if (isPlainObject(raw) && raw.auth !== undefined && v.transport === "http") {
172
+ deactivate(v, "global-only-auth", `server "${name}": auth is only allowed in the global mcp.json`);
173
+ folderRows.push(v);
174
+ continue;
175
+ }
176
+ }
177
+ if (global) v.overridesGlobal = true;
178
+ loadedNs.set(mcpNamespace(name), name);
179
+ byName.set(name, v); // whole-entry replace
180
+ }
181
+ }
182
+
183
+ return {
184
+ scope: "project",
185
+ cwd,
186
+ trusted,
187
+ servers: sortByName([...byName.values(), ...folderRows]),
188
+ layers,
189
+ };
190
+ }
191
+
192
+ return { getEffectiveView };
193
+ }
194
+
195
+ function sortByName(rows: EffectiveServerView[]): EffectiveServerView[] {
196
+ return rows.sort((a, b) => (a.name === b.name ? a.provenance.localeCompare(b.provenance) : a.name < b.name ? -1 : 1));
197
+ }