@jangmanj/pi-mcp-ext 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +93 -2
- package/package.json +52 -4
- package/src/client.ts +582 -0
- package/src/config.ts +135 -0
- package/src/events.ts +826 -0
- package/src/index.ts +1546 -0
- package/src/tasks.ts +110 -0
- package/src/transport-http.ts +144 -0
- package/src/transport-stdio.ts +644 -0
- package/src/types.ts +574 -0
package/src/config.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { execSync } from "node:child_process";
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
// Resolve Pi's internal validator beside its public entry point.
|
|
7
|
+
const { validateMcpServerConfig } = await import(new URL("./core/mcp-servers.js", import.meta.resolve("@earendil-works/pi-coding-agent")).href) as {
|
|
8
|
+
validateMcpServerConfig(name: string, raw: unknown): string | Record<string, any>;
|
|
9
|
+
};
|
|
10
|
+
import type { AuthResolver, ConfigLoadOptions, ConfigScope, ConfigWarning, ProviderTokenLookup, ResolvedHttpServer, ResolvedServer } from "./types.ts";
|
|
11
|
+
|
|
12
|
+
export interface DeclaredSubscription {
|
|
13
|
+
name: string;
|
|
14
|
+
arguments?: Record<string, unknown>;
|
|
15
|
+
delivery?: "auto" | "push" | "poll";
|
|
16
|
+
maxAgeMs?: number;
|
|
17
|
+
holdSettle?: boolean;
|
|
18
|
+
}
|
|
19
|
+
export type ConfiguredServer = ResolvedServer & { subscribe?: DeclaredSubscription[] };
|
|
20
|
+
export function expandHome(p: string): string {
|
|
21
|
+
return p === "~" ? homedir() : p.startsWith("~/") || (process.platform === "win32" && p.startsWith("~\\")) ? join(homedir(), p.slice(2)) : p;
|
|
22
|
+
}
|
|
23
|
+
export function getAgentDir(): string {
|
|
24
|
+
return process.env.PI_CODING_AGENT_DIR ? expandHome(process.env.PI_CODING_AGENT_DIR) : join(homedir(), CONFIG_DIR_NAME, "agent");
|
|
25
|
+
}
|
|
26
|
+
export function mcpNamespace(name: string): string { return "mcp__" + name.replace(/-/g, "_"); }
|
|
27
|
+
export function resolveConfigValue(value: string): string {
|
|
28
|
+
if (value.startsWith("!")) {
|
|
29
|
+
let output: string;
|
|
30
|
+
try { output = execSync(value.slice(1), { encoding: "utf8", timeout: 10_000, stdio: ["ignore", "pipe", "ignore"], windowsHide: true }).trim(); }
|
|
31
|
+
catch { throw new Error("Failed to resolve MCP config shell command"); }
|
|
32
|
+
if (!output) throw new Error("MCP config shell command returned empty output");
|
|
33
|
+
return output;
|
|
34
|
+
}
|
|
35
|
+
return value.replace(/\$\$|\$!|\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (match, braced, bare) => {
|
|
36
|
+
if (match === "$$") return "$";
|
|
37
|
+
if (match === "$!") return "!";
|
|
38
|
+
const name = braced ?? bare;
|
|
39
|
+
const result = process.env[name];
|
|
40
|
+
if (!result) throw new Error(`Missing environment variable: ${name}`);
|
|
41
|
+
return result;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function record(v: unknown): v is Record<string, any> { return typeof v === "object" && v !== null && !Array.isArray(v); }
|
|
45
|
+
function subscriptions(value: unknown): DeclaredSubscription[] | undefined {
|
|
46
|
+
if (!Array.isArray(value)) return undefined;
|
|
47
|
+
const result: DeclaredSubscription[] = [];
|
|
48
|
+
for (const raw of value) {
|
|
49
|
+
const v = typeof raw === "string" ? { name: raw } : raw;
|
|
50
|
+
if (!record(v) || typeof v.name !== "string" || !v.name.trim() ||
|
|
51
|
+
(v.arguments !== undefined && !record(v.arguments)) ||
|
|
52
|
+
(v.delivery !== undefined && !["auto", "push", "poll"].includes(v.delivery)) ||
|
|
53
|
+
(v.maxAgeMs !== undefined && (!Number.isInteger(v.maxAgeMs) || v.maxAgeMs < 0)) ||
|
|
54
|
+
(v.holdSettle !== undefined && typeof v.holdSettle !== "boolean")) return undefined;
|
|
55
|
+
result.push({ name: v.name, ...(v.arguments === undefined ? {} : { arguments: v.arguments }), ...(v.delivery === undefined ? {} : { delivery: v.delivery }), ...(v.maxAgeMs === undefined ? {} : { maxAgeMs: v.maxAgeMs }), ...(v.holdSettle === undefined ? {} : { holdSettle: v.holdSettle }) });
|
|
56
|
+
}
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
export async function loadServerConfigs(opts: ConfigLoadOptions): Promise<{ servers: ConfiguredServer[]; warnings: ConfigWarning[] }> {
|
|
60
|
+
const entries = new Map<string, { config: Record<string, any>; scope: ConfigScope }>();
|
|
61
|
+
const warnings: ConfigWarning[] = [];
|
|
62
|
+
function add(name: string, raw: unknown, scope: ConfigScope) {
|
|
63
|
+
const warn = (message: string) => warnings.push({ scope, server: name, message });
|
|
64
|
+
if (scope === "session" && [...entries.keys()].some(n => mcpNamespace(n) === mcpNamespace(name))) return;
|
|
65
|
+
if (scope === "project" && record(raw) && raw.command === undefined && raw.url === undefined && raw.type === undefined) {
|
|
66
|
+
const base = entries.get(name);
|
|
67
|
+
if (!base) { warn("Partial override needs a global server"); return; }
|
|
68
|
+
if (Object.keys(raw).some(k => !["enabled", "exposure", "toolExposure"].includes(k))) { warn("An override can only set enabled, exposure, toolExposure"); return; }
|
|
69
|
+
const config = validateMcpServerConfig(name, { ...base.config, ...raw });
|
|
70
|
+
if (typeof config === "string") warn(config);
|
|
71
|
+
else entries.set(name, { ...base, config });
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const config = validateMcpServerConfig(name, raw);
|
|
75
|
+
if (typeof config === "string") { warn(config); return; }
|
|
76
|
+
if ([...entries.keys()].some(n => n !== name && mcpNamespace(n) === mcpNamespace(name))) { warn("Server namespace conflicts with an earlier entry"); return; }
|
|
77
|
+
if (scope === "project" && "url" in config && config.auth) { warn("auth is only allowed in global or session scope"); return; }
|
|
78
|
+
entries.set(name, { config, scope });
|
|
79
|
+
}
|
|
80
|
+
function file(path: string, scope: ConfigScope) {
|
|
81
|
+
let parsed: unknown;
|
|
82
|
+
try { parsed = JSON.parse(readFileSync(path, "utf8").replace(/^\uFEFF/, "")); }
|
|
83
|
+
catch (e) { if ((e as NodeJS.ErrnoException).code !== "ENOENT") warnings.push({ scope, message: `${path}: ${String(e)}` }); return; }
|
|
84
|
+
if (!record(parsed) || (parsed.mcpServers !== undefined && !record(parsed.mcpServers))) { warnings.push({ scope, message: `${path}: expected an mcpServers object` }); return; }
|
|
85
|
+
for (const [name, raw] of Object.entries(parsed.mcpServers ?? {})) add(name, raw, scope);
|
|
86
|
+
}
|
|
87
|
+
file(join(getAgentDir(), "mcp.json"), "global");
|
|
88
|
+
if (opts.isProjectTrusted) file(join(opts.cwd, CONFIG_DIR_NAME, "mcp.json"), "project");
|
|
89
|
+
for (const s of opts.sessionServers) add(s.name, s.config, "session");
|
|
90
|
+
const servers: ConfiguredServer[] = [];
|
|
91
|
+
for (const [name, { config: c, scope }] of entries) {
|
|
92
|
+
const base = { name, namespace: mcpNamespace(name), scope, enabled: c.enabled !== false, timeoutMs: (c.timeout ?? 60) * 1000 };
|
|
93
|
+
const server: ConfiguredServer = typeof c.url === "string" && c.type !== "stdio"
|
|
94
|
+
? { ...base, transport: "http", url: c.url, headers: c.headers ?? {}, ...(c.auth ? { authProvider: c.auth.provider } : {}) }
|
|
95
|
+
: { ...base, transport: "stdio", command: c.command, args: c.args ?? [], env: c.env ?? {}, ...(c.cwd === undefined ? {} : { cwd: c.cwd }) };
|
|
96
|
+
if (c.subscribe !== undefined) {
|
|
97
|
+
const sub = subscriptions(c.subscribe);
|
|
98
|
+
if (sub) server.subscribe = sub;
|
|
99
|
+
else warnings.push({ scope, server: name, message: "Invalid subscribe value; ignored" });
|
|
100
|
+
}
|
|
101
|
+
servers.push(server);
|
|
102
|
+
}
|
|
103
|
+
return { servers, warnings };
|
|
104
|
+
}
|
|
105
|
+
export function createAuthResolver(server: ResolvedHttpServer, providerToken: ProviderTokenLookup): AuthResolver {
|
|
106
|
+
const path = join(getAgentDir(), "mcp-auth.json");
|
|
107
|
+
let signature = "", states: Record<string, any> = {}, last: string | undefined;
|
|
108
|
+
function stored(): string | undefined {
|
|
109
|
+
try {
|
|
110
|
+
const st = statSync(path), sig = `${st.mtimeMs}:${st.size}`;
|
|
111
|
+
if (sig !== signature) {
|
|
112
|
+
const parsed = JSON.parse(readFileSync(path, "utf8").replace(/^\uFEFF/, ""));
|
|
113
|
+
states = record(parsed) ? parsed : {}; signature = sig;
|
|
114
|
+
}
|
|
115
|
+
} catch { states = {}; signature = ""; }
|
|
116
|
+
const url = String(new URL(server.url));
|
|
117
|
+
const token = (states[`${server.namespace}|${url}`] ?? states[url])?.tokens?.access_token;
|
|
118
|
+
return typeof token === "string" && token ? `Bearer ${token}` : undefined;
|
|
119
|
+
}
|
|
120
|
+
async function resolve(): Promise<string | undefined> {
|
|
121
|
+
const header = Object.entries(server.headers).find(([key]) => key.toLowerCase() === "authorization");
|
|
122
|
+
if (header) return resolveConfigValue(header[1]);
|
|
123
|
+
if (server.authProvider) { const token = await providerToken(server.authProvider); return token ? `Bearer ${token}` : undefined; }
|
|
124
|
+
return stored();
|
|
125
|
+
}
|
|
126
|
+
return {
|
|
127
|
+
async authorization() { last = await resolve(); return last; },
|
|
128
|
+
async refreshAfterUnauthorized() {
|
|
129
|
+
const before = last;
|
|
130
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
131
|
+
last = await resolve();
|
|
132
|
+
return last !== before;
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|