@blackbelt-technology/pi-dashboard-mcp-client-plugin 0.10.0 → 0.12.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.
- package/README.md +1 -1
- package/package.json +7 -4
- package/src/client/FolderMcpPage.tsx +30 -6
- package/src/client/FolderMcpSection.tsx +3 -3
- package/src/client/ProjectSettings.tsx +2 -2
- package/src/client/ServerEditor.tsx +2 -2
- package/src/client/ServerList.tsx +2 -2
- package/src/client/api.ts +1 -1
- package/src/client/folder-view.ts +2 -2
- package/src/client/hooks.ts +2 -1
- package/src/client/schema.ts +1 -1
- package/src/core/index.ts +8 -78
- package/src/server/index.ts +4 -4
- package/src/server/pi-runner.ts +1 -1
- package/src/server/routes.ts +4 -4
- package/schema/mcp-config.schema.json +0 -64
- package/src/core/config-io.ts +0 -70
- package/src/core/config-writer.ts +0 -634
- package/src/core/effective-view.ts +0 -251
- package/src/core/layers.ts +0 -61
- package/src/core/live-state.ts +0 -134
- package/src/core/path-utils.ts +0 -41
- package/src/core/pi-rules.ts +0 -297
- package/src/core/schema-validation.ts +0 -57
- package/src/core/service.ts +0 -141
- package/src/core/types.ts +0 -278
|
@@ -1,251 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* mcp-client-plugin · CORE effective-view reader over pi's two MCP layers.
|
|
3
|
-
*
|
|
4
|
-
* Mirrors pi 1.1.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, except an entry with no
|
|
7
|
-
* `command`/`url`/`type`: a project OVERRIDE of `enabled`/`exposure`/
|
|
8
|
-
* `toolExposure` merged onto the kept global entry (one row). Each entry is checked
|
|
9
|
-
* with the mirrored pi rules; an entry pi would reject or drop (invalid,
|
|
10
|
-
* `-`/`_` collision, project `auth`) is shown inactive with pi's message. An
|
|
11
|
-
* untrusted project's entries are shown inactive ("project not trusted").
|
|
12
|
-
*
|
|
13
|
-
* Secrets: in a project view, a GLOBAL entry's secret values are redacted
|
|
14
|
-
* server-side (`headers`/`env` → `{redacted, keys}`, `oauth.clientSecret` →
|
|
15
|
-
* `{redacted}`) — the folder surface must never receive an inherited
|
|
16
|
-
* credential. Own-layer entries are returned verbatim (the client masks them).
|
|
17
|
-
*
|
|
18
|
-
* See change: migrate-mcp-to-pi-builtin (D3); mcp-client-project-overrides (D1-D3);
|
|
19
|
-
* earlier: extract-mcp-client-plugin.
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import { isLegacyFolderCopy } from "./config-writer.js";
|
|
23
|
-
import { type LayerPaths, readLayer } from "./layers.js";
|
|
24
|
-
import { getByName, isPlainObject, setByName } from "./path-utils.js";
|
|
25
|
-
import {
|
|
26
|
-
adapterLeftovers,
|
|
27
|
-
authModeOf,
|
|
28
|
-
classifyProjectEntry,
|
|
29
|
-
displayExposure,
|
|
30
|
-
ignoredKeys,
|
|
31
|
-
keptGlobalOf,
|
|
32
|
-
mcpNamespace,
|
|
33
|
-
transportOf,
|
|
34
|
-
validatePiEntry,
|
|
35
|
-
} from "./pi-rules.js";
|
|
36
|
-
import type { ConfigIO, EffectiveServerView, EffectiveView, LayerStatus, ProjectTrustSource, Provenance, Scope } from "./types.js";
|
|
37
|
-
|
|
38
|
-
/** Credential-name pattern for record keys (key NAMES are never secret). */
|
|
39
|
-
export function isSecretKey(name: string): boolean {
|
|
40
|
-
return /authorization|token|key|secret/i.test(name);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// Adapter-era leftovers (`bearerToken`, `requestHeadersCommand.env`) are
|
|
44
|
-
// ignored by pi but can still hold a credential, so they are redacted too.
|
|
45
|
-
const RECORD_SECRET_PATHS: string[][] = [["env"], ["headers"], ["requestHeadersCommand", "env"]];
|
|
46
|
-
const SCALAR_SECRET_PATHS: string[][] = [["oauth", "clientSecret"], ["bearerToken"]];
|
|
47
|
-
|
|
48
|
-
/** Replace secret values with markers (key names kept). */
|
|
49
|
-
export function redactEntry(entry: Record<string, unknown>): Record<string, unknown> {
|
|
50
|
-
const out = { ...entry };
|
|
51
|
-
for (const path of RECORD_SECRET_PATHS) {
|
|
52
|
-
const v = getByName(entry, path);
|
|
53
|
-
if (isPlainObject(v)) {
|
|
54
|
-
// Copy the parent first: the shallow copy shares nested objects with the raw entry.
|
|
55
|
-
const parent = path.slice(0, -1);
|
|
56
|
-
if (parent.length > 0) setByName(out, parent, { ...(getByName(entry, parent) as Record<string, unknown>) });
|
|
57
|
-
setByName(out, path, { redacted: true, keys: Object.keys(v).map((k) => ({ name: k, secret: isSecretKey(k) })) });
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
for (const path of SCALAR_SECRET_PATHS) {
|
|
61
|
-
if (getByName(entry, path) === undefined) continue;
|
|
62
|
-
// Copy the parent object first: `setByName` mutates in place and the
|
|
63
|
-
// shallow copy above still shares nested objects with the raw entry.
|
|
64
|
-
const parent = path.slice(0, -1);
|
|
65
|
-
if (parent.length > 0) setByName(out, parent, { ...(getByName(entry, parent) as Record<string, unknown>) });
|
|
66
|
-
setByName(out, path, { redacted: true });
|
|
67
|
-
}
|
|
68
|
-
return out;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function trustExtras(deps: EffectiveViewDeps, cwd: string): Pick<EffectiveView, "trustSource" | "trustCoverInteractive"> {
|
|
72
|
-
const out: Pick<EffectiveView, "trustSource" | "trustCoverInteractive"> = {};
|
|
73
|
-
try {
|
|
74
|
-
const source = deps.projectTrustSource?.(cwd);
|
|
75
|
-
if (source) out.trustSource = source;
|
|
76
|
-
if (deps.coverInteractive) out.trustCoverInteractive = deps.coverInteractive();
|
|
77
|
-
} catch {
|
|
78
|
-
/* additive disclosure only: never fails the view */
|
|
79
|
-
}
|
|
80
|
-
return out;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export interface EffectiveViewDeps {
|
|
84
|
-
configIO: ConfigIO;
|
|
85
|
-
paths: LayerPaths;
|
|
86
|
-
isProjectTrusted?: (cwd: string) => boolean;
|
|
87
|
-
/** Optional: who decided the trust (absent → `trustSource` omitted). */
|
|
88
|
-
projectTrustSource?: (cwd: string) => ProjectTrustSource | undefined;
|
|
89
|
-
/** Optional: `piTrustMirror.coverInteractive` (absent → omitted). */
|
|
90
|
-
coverInteractive?: () => boolean;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export interface EffectiveViewReader {
|
|
94
|
-
getEffectiveView(scope: Scope): EffectiveView;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
function describe(
|
|
98
|
-
name: string,
|
|
99
|
-
raw: unknown,
|
|
100
|
-
provenance: Provenance,
|
|
101
|
-
redact: boolean,
|
|
102
|
-
): EffectiveServerView {
|
|
103
|
-
const entry = isPlainObject(raw) ? (raw as Record<string, unknown>) : {};
|
|
104
|
-
const piError = validatePiEntry(name, raw);
|
|
105
|
-
const enabled = entry.enabled !== false;
|
|
106
|
-
const view: EffectiveServerView = {
|
|
107
|
-
name,
|
|
108
|
-
provenance,
|
|
109
|
-
entry: redact ? redactEntry(entry) : { ...entry },
|
|
110
|
-
transport: transportOf(entry),
|
|
111
|
-
enabled,
|
|
112
|
-
exposure: displayExposure(entry.exposure),
|
|
113
|
-
active: piError === null && enabled,
|
|
114
|
-
ignoredKeys: ignoredKeys(entry),
|
|
115
|
-
adapterLeftovers: adapterLeftovers(entry),
|
|
116
|
-
};
|
|
117
|
-
const auth = authModeOf(entry);
|
|
118
|
-
if (auth) view.authMode = auth;
|
|
119
|
-
if (piError) {
|
|
120
|
-
view.piError = piError;
|
|
121
|
-
view.inactiveReason = "invalid-entry";
|
|
122
|
-
} else if (!enabled) {
|
|
123
|
-
view.inactiveReason = "disabled";
|
|
124
|
-
}
|
|
125
|
-
return view;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function deactivate(v: EffectiveServerView, reason: EffectiveServerView["inactiveReason"], message?: string): void {
|
|
129
|
-
v.active = false;
|
|
130
|
-
v.inactiveReason = reason;
|
|
131
|
-
if (message) v.piError = message;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
export function createEffectiveViewReader(deps: EffectiveViewDeps): EffectiveViewReader {
|
|
135
|
-
const { configIO, paths } = deps;
|
|
136
|
-
|
|
137
|
-
function getEffectiveView(scope: Scope): EffectiveView {
|
|
138
|
-
const globalPath = paths.globalPath();
|
|
139
|
-
const g = readLayer(configIO, globalPath);
|
|
140
|
-
const layers: LayerStatus[] = [
|
|
141
|
-
{ layer: "pi-global", path: globalPath, exists: g.exists, ok: g.ok, ...(g.ok ? {} : { message: g.message }) },
|
|
142
|
-
];
|
|
143
|
-
const isProject = scope.kind === "project";
|
|
144
|
-
|
|
145
|
-
// Global layer, in pi's load order (collisions within the file: first wins).
|
|
146
|
-
// `keptGlobalOf` is the one definition of "kept" the writer shares.
|
|
147
|
-
const byName = new Map<string, EffectiveServerView>();
|
|
148
|
-
const loadedNs = new Map<string, string>(); // namespace → loaded name
|
|
149
|
-
const { kept, collisions } = keptGlobalOf(g.ok ? g.servers : {});
|
|
150
|
-
if (g.ok) {
|
|
151
|
-
for (const [name, raw] of Object.entries(g.servers)) {
|
|
152
|
-
const v = describe(name, raw, "pi-global", isProject);
|
|
153
|
-
if (kept.has(name)) loadedNs.set(mcpNamespace(name), name);
|
|
154
|
-
else if (collisions.has(name)) {
|
|
155
|
-
deactivate(v, "name-collision", `server "${name}" conflicts with "${collisions.get(name)}"`);
|
|
156
|
-
}
|
|
157
|
-
byName.set(name, v);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
if (scope.kind === "global") {
|
|
162
|
-
return { scope: "global", servers: sortByName([...byName.values()]), layers };
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
const cwd = scope.cwd;
|
|
166
|
-
const trusted = deps.isProjectTrusted?.(cwd) === true;
|
|
167
|
-
const projectPath = paths.projectPath(cwd);
|
|
168
|
-
const pl = readLayer(configIO, projectPath);
|
|
169
|
-
layers.push({ layer: "pi-folder", path: projectPath, exists: pl.exists, ok: pl.ok, ...(pl.ok ? {} : { message: pl.message }) });
|
|
170
|
-
|
|
171
|
-
const folderRows: EffectiveServerView[] = [];
|
|
172
|
-
if (pl.ok) {
|
|
173
|
-
for (const [name, raw] of Object.entries(pl.servers)) {
|
|
174
|
-
const cls = classifyProjectEntry(name, raw, kept);
|
|
175
|
-
const v = describe(name, raw, "pi-folder", false);
|
|
176
|
-
if (cls.kind !== "replace") {
|
|
177
|
-
// override-shaped: classified below, never "needs command or url"
|
|
178
|
-
delete v.piError;
|
|
179
|
-
delete v.inactiveReason;
|
|
180
|
-
}
|
|
181
|
-
const global = byName.get(name);
|
|
182
|
-
if (!trusted) {
|
|
183
|
-
// pi never reads this file: the global entry (if any) stays in effect.
|
|
184
|
-
deactivate(v, "project-not-trusted");
|
|
185
|
-
folderRows.push(v);
|
|
186
|
-
continue;
|
|
187
|
-
}
|
|
188
|
-
if (cls.kind === "orphan" || cls.kind === "bad-keys" || cls.kind === "invalid") {
|
|
189
|
-
// pi reports the message and applies nothing: the global entry (if any) is unchanged.
|
|
190
|
-
deactivate(v, "invalid-entry", cls.message);
|
|
191
|
-
v.overrideIssue = cls.kind;
|
|
192
|
-
folderRows.push(v);
|
|
193
|
-
continue;
|
|
194
|
-
}
|
|
195
|
-
if (cls.kind === "override") {
|
|
196
|
-
// One row: the global server, merged, redacted like any global row in a project view.
|
|
197
|
-
const merged = describe(name, cls.merged, "pi-global", true);
|
|
198
|
-
const raw2 = raw as Record<string, unknown>;
|
|
199
|
-
const base = kept.get(name) as Record<string, unknown>;
|
|
200
|
-
merged.projectOverride = {
|
|
201
|
-
path: projectPath,
|
|
202
|
-
keys: cls.keys,
|
|
203
|
-
raw: { ...raw2 },
|
|
204
|
-
inherited: { enabled: base.enabled !== false, exposure: displayExposure(base.exposure) },
|
|
205
|
-
};
|
|
206
|
-
byName.set(name, merged);
|
|
207
|
-
continue;
|
|
208
|
-
}
|
|
209
|
-
if (v.piError) {
|
|
210
|
-
// pi drops an invalid project entry; the global one stays in effect.
|
|
211
|
-
folderRows.push(v);
|
|
212
|
-
continue;
|
|
213
|
-
}
|
|
214
|
-
{
|
|
215
|
-
const clash = loadedNs.get(mcpNamespace(name));
|
|
216
|
-
if (clash && clash !== name) {
|
|
217
|
-
deactivate(v, "name-collision", `server "${name}" conflicts with "${clash}"`);
|
|
218
|
-
folderRows.push(v);
|
|
219
|
-
continue;
|
|
220
|
-
}
|
|
221
|
-
if (isPlainObject(raw) && raw.auth !== undefined && v.transport === "http") {
|
|
222
|
-
deactivate(v, "global-only-auth", `server "${name}": auth is only allowed in the global mcp.json`);
|
|
223
|
-
folderRows.push(v);
|
|
224
|
-
continue;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
if (global) {
|
|
228
|
-
v.overridesGlobal = true;
|
|
229
|
-
if (isLegacyFolderCopy(raw, kept.get(name))) v.legacyCopy = true;
|
|
230
|
-
}
|
|
231
|
-
loadedNs.set(mcpNamespace(name), name);
|
|
232
|
-
byName.set(name, v); // whole-entry replace
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
return {
|
|
237
|
-
scope: "project",
|
|
238
|
-
cwd,
|
|
239
|
-
trusted,
|
|
240
|
-
...trustExtras(deps, cwd),
|
|
241
|
-
servers: sortByName([...byName.values(), ...folderRows]),
|
|
242
|
-
layers,
|
|
243
|
-
};
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
return { getEffectiveView };
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
function sortByName(rows: EffectiveServerView[]): EffectiveServerView[] {
|
|
250
|
-
return rows.sort((a, b) => (a.name === b.name ? a.provenance.localeCompare(b.provenance) : a.name < b.name ? -1 : 1));
|
|
251
|
-
}
|
package/src/core/layers.ts
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* mcp-client-plugin · CORE layer paths + strict-JSON layer reads.
|
|
3
|
-
*
|
|
4
|
-
* pi's built-in MCP reads exactly two files: `<agentDir>/mcp.json`
|
|
5
|
-
* (`PI_CODING_AGENT_DIR`, else `~/.pi/agent`) and, for a trusted project,
|
|
6
|
-
* `<cwd>/.pi/mcp.json`. Both are parsed with strict `JSON.parse`; a file with
|
|
7
|
-
* comments or trailing commas is reported and skipped whole. This module reads
|
|
8
|
-
* them the same way, so the dashboard never shows (or writes over) a file pi
|
|
9
|
-
* would skip.
|
|
10
|
-
*
|
|
11
|
-
* See change: migrate-mcp-to-pi-builtin (D3 "Reads").
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
import { homedir } from "node:os";
|
|
15
|
-
import { join } from "node:path";
|
|
16
|
-
import { isPlainObject } from "./path-utils.js";
|
|
17
|
-
import type { ConfigIO } from "./types.js";
|
|
18
|
-
|
|
19
|
-
export interface LayerPaths {
|
|
20
|
-
globalPath(): string;
|
|
21
|
-
projectPath(cwd: string): string;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/** The Pi agent dir, resolved per call so a changed env is honoured. */
|
|
25
|
-
export function piAgentDir(env: NodeJS.ProcessEnv = process.env): string {
|
|
26
|
-
const dir = env.PI_CODING_AGENT_DIR;
|
|
27
|
-
return dir && dir.length > 0 ? dir : join(homedir(), ".pi", "agent");
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export function defaultLayerPaths(): LayerPaths {
|
|
31
|
-
return {
|
|
32
|
-
globalPath: () => join(piAgentDir(), "mcp.json"),
|
|
33
|
-
projectPath: (cwd) => join(cwd, ".pi", "mcp.json"),
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** A null-prototype shallow copy, so a `__proto__` own key can never pollute. */
|
|
38
|
-
export function nullProto<T extends object>(obj: T): T {
|
|
39
|
-
return Object.assign(Object.create(null), obj) as T;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export type LayerRead =
|
|
43
|
-
| { ok: true; path: string; exists: boolean; config: Record<string, unknown>; servers: Record<string, unknown> }
|
|
44
|
-
| { ok: false; path: string; exists: true; message: string };
|
|
45
|
-
|
|
46
|
-
/** Read + strictly parse one layer. A missing file reads as an empty config. */
|
|
47
|
-
export function readLayer(io: ConfigIO, path: string): LayerRead {
|
|
48
|
-
const raw = io.readFile(path);
|
|
49
|
-
if (raw === null) return { ok: true, path, exists: false, config: nullProto({}), servers: nullProto({}) };
|
|
50
|
-
let parsed: unknown;
|
|
51
|
-
try {
|
|
52
|
-
parsed = JSON.parse(raw);
|
|
53
|
-
} catch (e) {
|
|
54
|
-
return { ok: false, path, exists: true, message: `${path}: ${(e as Error).message}` };
|
|
55
|
-
}
|
|
56
|
-
if (!isPlainObject(parsed) || (parsed.mcpServers !== undefined && !isPlainObject(parsed.mcpServers))) {
|
|
57
|
-
return { ok: false, path, exists: true, message: `${path}: expected an object with an "mcpServers" object` };
|
|
58
|
-
}
|
|
59
|
-
const servers = isPlainObject(parsed.mcpServers) ? nullProto(parsed.mcpServers) : nullProto({});
|
|
60
|
-
return { ok: true, path, exists: true, config: nullProto(parsed), servers };
|
|
61
|
-
}
|
package/src/core/live-state.ts
DELETED
|
@@ -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
|
-
}
|
package/src/core/path-utils.ts
DELETED
|
@@ -1,41 +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
|
-
}
|
|
30
|
-
|
|
31
|
-
/** Structural JSON equality (plain objects, arrays, primitives). */
|
|
32
|
-
export function deepEqual(a: unknown, b: unknown): boolean {
|
|
33
|
-
if (a === b) return true;
|
|
34
|
-
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
|
|
35
|
-
if (isPlainObject(a) && isPlainObject(b)) {
|
|
36
|
-
const ka = Object.keys(a);
|
|
37
|
-
const kb = Object.keys(b);
|
|
38
|
-
return ka.length === kb.length && ka.every((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
|
|
39
|
-
}
|
|
40
|
-
return false;
|
|
41
|
-
}
|