@jangmanj/mcp 0.0.0-stage → 0.13.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.
Files changed (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +337 -2
  3. package/adapters/pi/bridge.ts +721 -0
  4. package/adapters/pi/config.ts +364 -0
  5. package/adapters/pi/content-offloaded.ts +53 -0
  6. package/adapters/pi/content.ts +78 -0
  7. package/adapters/pi/diagnostics.ts +26 -0
  8. package/adapters/pi/elicitation.ts +133 -0
  9. package/adapters/pi/index.ts +210 -0
  10. package/adapters/pi/oauth.ts +219 -0
  11. package/adapters/pi/pi-api.ts +133 -0
  12. package/adapters/pi/resources.ts +177 -0
  13. package/adapters/pi/result-files.ts +32 -0
  14. package/adapters/pi/tasks.ts +49 -0
  15. package/dist/auth/client-credentials.d.ts +65 -0
  16. package/dist/auth/client-credentials.js +388 -0
  17. package/dist/auth/discovery.d.ts +28 -0
  18. package/dist/auth/discovery.js +125 -0
  19. package/dist/auth/index.d.ts +9 -0
  20. package/dist/auth/index.js +5 -0
  21. package/dist/auth/node-ports.d.ts +8 -0
  22. package/dist/auth/node-ports.js +67 -0
  23. package/dist/auth/protocol.d.ts +12 -0
  24. package/dist/auth/protocol.js +39 -0
  25. package/dist/auth/provider.d.ts +114 -0
  26. package/dist/auth/provider.js +407 -0
  27. package/dist/auth/safe-fetch.d.ts +14 -0
  28. package/dist/auth/safe-fetch.js +130 -0
  29. package/dist/client/events.d.ts +33 -0
  30. package/dist/client/events.js +84 -0
  31. package/dist/client/index.d.ts +65 -0
  32. package/dist/client/index.js +128 -0
  33. package/dist/core/auth-types.d.ts +36 -0
  34. package/dist/core/auth-types.js +11 -0
  35. package/dist/core/bearer-challenge.d.ts +3 -0
  36. package/dist/core/bearer-challenge.js +63 -0
  37. package/dist/core/cancel.d.ts +70 -0
  38. package/dist/core/cancel.js +177 -0
  39. package/dist/core/extension.d.ts +33 -0
  40. package/dist/core/extension.js +145 -0
  41. package/dist/core/index.d.ts +73 -0
  42. package/dist/core/index.js +129 -0
  43. package/dist/core/jsonrpc.d.ts +49 -0
  44. package/dist/core/jsonrpc.js +80 -0
  45. package/dist/core/lifecycle.d.ts +128 -0
  46. package/dist/core/lifecycle.js +251 -0
  47. package/dist/core/outcome.d.ts +98 -0
  48. package/dist/core/outcome.js +32 -0
  49. package/dist/core/ports.d.ts +144 -0
  50. package/dist/core/ports.js +67 -0
  51. package/dist/core/progress.d.ts +81 -0
  52. package/dist/core/progress.js +205 -0
  53. package/dist/core/request.d.ts +108 -0
  54. package/dist/core/request.js +578 -0
  55. package/dist/core/schema/index.d.ts +1 -0
  56. package/dist/core/schema/index.js +1 -0
  57. package/dist/core/schema/types.d.ts +4154 -0
  58. package/dist/core/schema/types.js +6 -0
  59. package/dist/core/telemetry.d.ts +25 -0
  60. package/dist/core/telemetry.js +37 -0
  61. package/dist/ext-events/index.d.ts +79 -0
  62. package/dist/ext-events/index.js +218 -0
  63. package/dist/ext-events/model.d.ts +10 -0
  64. package/dist/ext-events/model.js +6 -0
  65. package/dist/ext-events/push.d.ts +18 -0
  66. package/dist/ext-events/push.js +101 -0
  67. package/dist/ext-events/stream.d.ts +6 -0
  68. package/dist/ext-events/stream.js +60 -0
  69. package/dist/ext-server-cards/index.d.ts +107 -0
  70. package/dist/ext-server-cards/index.js +249 -0
  71. package/dist/ext-skills/cache.d.ts +20 -0
  72. package/dist/ext-skills/cache.js +101 -0
  73. package/dist/ext-skills/client.d.ts +82 -0
  74. package/dist/ext-skills/client.js +292 -0
  75. package/dist/ext-skills/extension.d.ts +16 -0
  76. package/dist/ext-skills/extension.js +29 -0
  77. package/dist/ext-skills/index.d.ts +4 -0
  78. package/dist/ext-skills/index.js +4 -0
  79. package/dist/ext-skills/verify.d.ts +57 -0
  80. package/dist/ext-skills/verify.js +168 -0
  81. package/dist/index.d.ts +1 -0
  82. package/dist/index.js +1 -0
  83. package/dist/mrtr-cache/cache.d.ts +51 -0
  84. package/dist/mrtr-cache/cache.js +295 -0
  85. package/dist/mrtr-cache/client.d.ts +24 -0
  86. package/dist/mrtr-cache/client.js +44 -0
  87. package/dist/mrtr-cache/common.d.ts +10 -0
  88. package/dist/mrtr-cache/common.js +9 -0
  89. package/dist/mrtr-cache/elicitation.d.ts +42 -0
  90. package/dist/mrtr-cache/elicitation.js +221 -0
  91. package/dist/mrtr-cache/index.d.ts +9 -0
  92. package/dist/mrtr-cache/index.js +8 -0
  93. package/dist/mrtr-cache/mrtr.d.ts +37 -0
  94. package/dist/mrtr-cache/mrtr.js +250 -0
  95. package/dist/mrtr-cache/refresh.d.ts +8 -0
  96. package/dist/mrtr-cache/refresh.js +30 -0
  97. package/dist/mrtr-cache/stream.d.ts +5 -0
  98. package/dist/mrtr-cache/stream.js +18 -0
  99. package/dist/mrtr-cache/subscriptions.d.ts +96 -0
  100. package/dist/mrtr-cache/subscriptions.js +288 -0
  101. package/dist/mrtr-cache/tasks.d.ts +103 -0
  102. package/dist/mrtr-cache/tasks.js +444 -0
  103. package/dist/ops/common.d.ts +18 -0
  104. package/dist/ops/common.js +39 -0
  105. package/dist/ops/completion.d.ts +44 -0
  106. package/dist/ops/completion.js +65 -0
  107. package/dist/ops/content.d.ts +40 -0
  108. package/dist/ops/content.js +117 -0
  109. package/dist/ops/icons.d.ts +29 -0
  110. package/dist/ops/icons.js +82 -0
  111. package/dist/ops/index.d.ts +30 -0
  112. package/dist/ops/index.js +28 -0
  113. package/dist/ops/pagination.d.ts +32 -0
  114. package/dist/ops/pagination.js +65 -0
  115. package/dist/ops/prompts.d.ts +32 -0
  116. package/dist/ops/prompts.js +68 -0
  117. package/dist/ops/resources.d.ts +42 -0
  118. package/dist/ops/resources.js +104 -0
  119. package/dist/ops/schema.d.ts +39 -0
  120. package/dist/ops/schema.js +163 -0
  121. package/dist/ops/tools.d.ts +88 -0
  122. package/dist/ops/tools.js +169 -0
  123. package/dist/ops/uri-template.d.ts +3 -0
  124. package/dist/ops/uri-template.js +101 -0
  125. package/dist/server/index.d.ts +5 -0
  126. package/dist/server/index.js +5 -0
  127. package/dist/server/mrtr.d.ts +38 -0
  128. package/dist/server/mrtr.js +99 -0
  129. package/dist/server/protocol.d.ts +21 -0
  130. package/dist/server/protocol.js +49 -0
  131. package/dist/server/server.d.ts +105 -0
  132. package/dist/server/server.js +383 -0
  133. package/dist/server/skills.d.ts +45 -0
  134. package/dist/server/skills.js +73 -0
  135. package/dist/server/uri.d.ts +2 -0
  136. package/dist/server/uri.js +27 -0
  137. package/dist/server-events/bus.d.ts +40 -0
  138. package/dist/server-events/bus.js +84 -0
  139. package/dist/server-events/events.d.ts +36 -0
  140. package/dist/server-events/events.js +108 -0
  141. package/dist/server-events/index.d.ts +6 -0
  142. package/dist/server-events/index.js +6 -0
  143. package/dist/server-events/notices.d.ts +24 -0
  144. package/dist/server-events/notices.js +31 -0
  145. package/dist/server-events/subscriptions.d.ts +33 -0
  146. package/dist/server-events/subscriptions.js +77 -0
  147. package/dist/server-events/tasks.d.ts +43 -0
  148. package/dist/server-events/tasks.js +101 -0
  149. package/dist/server-events/types.d.ts +25 -0
  150. package/dist/server-events/types.js +34 -0
  151. package/dist/server-transport/auth.d.ts +20 -0
  152. package/dist/server-transport/auth.js +29 -0
  153. package/dist/server-transport/channel.d.ts +17 -0
  154. package/dist/server-transport/channel.js +47 -0
  155. package/dist/server-transport/http.d.ts +19 -0
  156. package/dist/server-transport/http.js +209 -0
  157. package/dist/server-transport/index.d.ts +4 -0
  158. package/dist/server-transport/index.js +4 -0
  159. package/dist/server-transport/stdio.d.ts +16 -0
  160. package/dist/server-transport/stdio.js +83 -0
  161. package/dist/telemetry-otel/index.d.ts +64 -0
  162. package/dist/telemetry-otel/index.js +196 -0
  163. package/dist/testing/index.d.ts +36 -0
  164. package/dist/testing/index.js +140 -0
  165. package/dist/transport-http/headers.d.ts +24 -0
  166. package/dist/transport-http/headers.js +140 -0
  167. package/dist/transport-http/index.d.ts +3 -0
  168. package/dist/transport-http/index.js +3 -0
  169. package/dist/transport-http/sse.d.ts +33 -0
  170. package/dist/transport-http/sse.js +152 -0
  171. package/dist/transport-http/transport.d.ts +66 -0
  172. package/dist/transport-http/transport.js +854 -0
  173. package/dist/transport-stdio/framing.d.ts +50 -0
  174. package/dist/transport-stdio/framing.js +154 -0
  175. package/dist/transport-stdio/index.d.ts +4 -0
  176. package/dist/transport-stdio/index.js +4 -0
  177. package/dist/transport-stdio/stderr-ring.d.ts +27 -0
  178. package/dist/transport-stdio/stderr-ring.js +105 -0
  179. package/dist/transport-stdio/transport.d.ts +142 -0
  180. package/dist/transport-stdio/transport.js +743 -0
  181. package/dist/transport-stdio/write-queue.d.ts +48 -0
  182. package/dist/transport-stdio/write-queue.js +147 -0
  183. package/package.json +134 -4
@@ -0,0 +1,364 @@
1
+ /**
2
+ * mcp.json discovery, validation, and merging.
3
+ *
4
+ * Mirrors Pi's built-in rules (docs/mcp.md): user-level servers live in
5
+ * ~/.pi/agent/mcp.json, project servers in .pi/mcp.json (trusted projects
6
+ * only), a project entry replaces a user entry, and a project entry without
7
+ * command/url/type overlays only enabled/exposure/toolExposure.
8
+ */
9
+
10
+ import { execSync } from "node:child_process";
11
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import type { McpServerEntry } from "./pi-api.ts";
14
+
15
+ export type Exposure = "direct" | "codemode" | "deferred" | "hidden";
16
+
17
+ export interface OAuthConfig {
18
+ readonly clientId?: string;
19
+ readonly clientSecret?: string;
20
+ readonly clientName?: string;
21
+ /** Fixed loopback callback port (http://127.0.0.1:<port>/callback). */
22
+ readonly callbackPort?: number;
23
+ /** Full loopback redirect URI; takes precedence over callbackPort. */
24
+ readonly callbackUrl?: string;
25
+ /** Space-separated scopes requested when the server does not advertise them. */
26
+ readonly scope?: string;
27
+ /** Use this AS metadata document instead of discovery; trusted as configured. */
28
+ readonly authServerMetadataUrl?: string;
29
+ }
30
+
31
+ export interface ResolvedServerConfig {
32
+ readonly name: string;
33
+ readonly source: "user" | "project" | "extension";
34
+ readonly kind: "stdio" | "http";
35
+ readonly command?: string;
36
+ readonly args?: readonly string[];
37
+ readonly env?: Record<string, string>;
38
+ readonly cwd?: string;
39
+ readonly url?: string;
40
+ readonly headers?: Record<string, string>;
41
+ readonly enabled: boolean;
42
+ readonly exposure: Exposure;
43
+ readonly toolExposure?: Record<string, string>;
44
+ readonly description?: string;
45
+ readonly timeoutMs: number;
46
+ /** Static client credentials / naming for the OAuth flow, when configured. */
47
+ readonly oauth?: OAuthConfig;
48
+ /** Present when the entry sets `oauth`. */
49
+ readonly wantsOAuth: boolean;
50
+ }
51
+
52
+ export interface LoadedConfigs {
53
+ readonly servers: Map<string, ResolvedServerConfig>;
54
+ readonly warnings: string[];
55
+ }
56
+
57
+ export interface LoadOptions {
58
+ readonly homeDir: string;
59
+ readonly cwd: string;
60
+ readonly projectTrusted: boolean;
61
+ /** Environment for `${VAR}` interpolation; defaults to process.env. */
62
+ readonly env?: Record<string, string | undefined>;
63
+ /** Runner for `!command` values; injectable for tests. */
64
+ readonly exec?: (command: string) => string;
65
+ /** Registered (extension) servers; file entries win on name collision. */
66
+ readonly registered?: ReadonlyMap<string, McpServerEntry>;
67
+ }
68
+
69
+ const NAME_RE = /^[A-Za-z0-9_-]+$/;
70
+ const EXPOSURES = new Set(["direct", "codemode", "codemode-deferred", "deferred", "hidden"]);
71
+ const DEFAULT_TIMEOUT_MS = 60_000;
72
+
73
+ export function normalizeExposure(value: string | undefined): Exposure {
74
+ switch (value) {
75
+ case "direct":
76
+ case "deferred":
77
+ case "hidden":
78
+ return value;
79
+ default:
80
+ return "codemode"; // codemode-deferred and unknown values land here
81
+ }
82
+ }
83
+
84
+ /** Normalized identity: names differing only in `-` vs `_` are the same server. */
85
+ export function serverKey(name: string): string {
86
+ return name.replace(/-/g, "_");
87
+ }
88
+
89
+ function defaultExec(command: string): string {
90
+ return execSync(command, { encoding: "utf8", timeout: 10_000 }).trim();
91
+ }
92
+
93
+ /**
94
+ * Interpolate one config value: `!command` (whole value) runs a command,
95
+ * `${VAR}` reads from env. Returns undefined warnings-free value or the value
96
+ * with failures replaced by "".
97
+ */
98
+ export function interpolate(
99
+ value: string,
100
+ env: Record<string, string | undefined>,
101
+ exec: (command: string) => string,
102
+ warnings: string[],
103
+ where: string,
104
+ ): string {
105
+ if (value.startsWith("!")) {
106
+ try {
107
+ return exec(value.slice(1));
108
+ } catch (err) {
109
+ warnings.push(`${where}: command failed: ${err instanceof Error ? err.message : String(err)}`);
110
+ return "";
111
+ }
112
+ }
113
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_m, name: string) => {
114
+ const v = env[name];
115
+ if (v === undefined) warnings.push(`${where}: environment variable ${name} is not set`);
116
+ return v ?? "";
117
+ });
118
+ }
119
+
120
+ export function expandTilde(path: string, homeDir: string): string {
121
+ if (path === "~") return homeDir;
122
+ if (path.startsWith("~/")) return join(homeDir, path.slice(2));
123
+ return path;
124
+ }
125
+
126
+ /** Persist enabled/exposure changes to the server's mcp.json file. */
127
+ export function persistServerUpdate(
128
+ name: string,
129
+ source: "user" | "project" | "extension",
130
+ updates: { enabled?: boolean; exposure?: string },
131
+ opts: { homeDir: string; cwd: string },
132
+ ): void {
133
+ const path = source === "project"
134
+ ? join(opts.cwd, ".pi", "mcp.json")
135
+ : join(agentDir(process.env as Record<string, string | undefined>, opts.homeDir), "mcp.json");
136
+ let doc: { mcpServers?: Record<string, unknown> } = { mcpServers: {} };
137
+ if (existsSync(path)) doc = JSON.parse(readFileSync(path, "utf8")) as typeof doc;
138
+ doc.mcpServers ??= {};
139
+ const existing = doc.mcpServers[name];
140
+ doc.mcpServers[name] = {
141
+ ...(typeof existing === "object" && existing !== null ? existing : {}),
142
+ ...updates,
143
+ };
144
+ writeFileSync(path, `${JSON.stringify(doc, null, 2)}\n`);
145
+ }
146
+
147
+ function interpolateRecord(
148
+ record: Record<string, string>,
149
+ env: Record<string, string | undefined>,
150
+ exec: (command: string) => string,
151
+ warnings: string[],
152
+ where: string,
153
+ ): Record<string, string> {
154
+ const out: Record<string, string> = {};
155
+ for (const [k, v] of Object.entries(record)) {
156
+ out[k] = interpolate(v, env, exec, warnings, `${where}.${k}`);
157
+ }
158
+ return out;
159
+ }
160
+
161
+ interface RawEntry {
162
+ readonly name: string;
163
+ readonly raw: McpServerEntry;
164
+ readonly source: "user" | "project" | "extension";
165
+ }
166
+
167
+ function readFileEntries(path: string, source: "user" | "project", warnings: string[]): RawEntry[] {
168
+ if (!existsSync(path)) return [];
169
+ let parsed: unknown;
170
+ try {
171
+ parsed = JSON.parse(readFileSync(path, "utf8"));
172
+ } catch (err) {
173
+ warnings.push(`${path}: ${err instanceof Error ? err.message : String(err)}`);
174
+ return [];
175
+ }
176
+ const servers = (parsed as { mcpServers?: unknown })?.mcpServers;
177
+ if (servers === undefined || servers === null) return [];
178
+ if (typeof servers !== "object" || Array.isArray(servers)) {
179
+ warnings.push(`${path}: "mcpServers" must be an object`);
180
+ return [];
181
+ }
182
+ return Object.entries(servers as Record<string, unknown>).map(([name, raw]) => ({
183
+ name,
184
+ raw: (raw ?? {}) as McpServerEntry,
185
+ source,
186
+ }));
187
+ }
188
+
189
+ function isPartialOverride(raw: McpServerEntry): boolean {
190
+ return raw.command === undefined && raw.url === undefined && raw.type === undefined;
191
+ }
192
+
193
+ function resolveOAuth(
194
+ raw: McpServerEntry,
195
+ env: Record<string, string | undefined>,
196
+ exec: (command: string) => string,
197
+ warnings: string[],
198
+ where: string,
199
+ ): OAuthConfig | undefined {
200
+ if (raw.oauth === undefined) return undefined;
201
+ const out: { clientId?: string; clientSecret?: string; clientName?: string; callbackPort?: number; callbackUrl?: string; scope?: string; authServerMetadataUrl?: string } = {};
202
+ for (const key of ["clientId", "clientSecret", "clientName", "callbackUrl", "scope", "authServerMetadataUrl"] as const) {
203
+ const v = raw.oauth[key];
204
+ if (v === undefined) continue;
205
+ if (typeof v !== "string") {
206
+ warnings.push(`${where}: oauth.${key} must be a string`);
207
+ continue;
208
+ }
209
+ out[key] = key === "clientName" ? v : interpolate(v, env, exec, warnings, `${where}.oauth.${key}`);
210
+ }
211
+ if (raw.oauth.callbackPort !== undefined) {
212
+ const p = raw.oauth.callbackPort;
213
+ if (typeof p === "number" && Number.isInteger(p) && p > 0 && p < 65536) out.callbackPort = p;
214
+ else warnings.push(`${where}: oauth.callbackPort must be an integer port`);
215
+ }
216
+ return out;
217
+ }
218
+
219
+ function resolveEntry(
220
+ entry: RawEntry,
221
+ opts: LoadOptions,
222
+ warnings: string[],
223
+ ): ResolvedServerConfig | undefined {
224
+ const { name, raw, source } = entry;
225
+ const where = `${source} server "${name}"`;
226
+ if (!NAME_RE.test(name)) {
227
+ warnings.push(`${where}: invalid name (allowed: letters, digits, _, -)`);
228
+ return undefined;
229
+ }
230
+ if (raw.type !== undefined && raw.type !== "stdio" && raw.type !== "http" && raw.type !== "streamable-http") {
231
+ warnings.push(`${where}: unsupported type ${JSON.stringify(raw.type)} (sse is not supported)`);
232
+ return undefined;
233
+ }
234
+ if (raw.exposure !== undefined && !EXPOSURES.has(raw.exposure)) {
235
+ warnings.push(`${where}: unknown exposure ${JSON.stringify(raw.exposure)}, using "codemode"`);
236
+ }
237
+ for (const [pattern, value] of Object.entries(raw.toolExposure ?? {})) {
238
+ if (!EXPOSURES.has(value)) {
239
+ warnings.push(`${where}: unknown toolExposure ${JSON.stringify(value)} for ${pattern}`);
240
+ }
241
+ }
242
+
243
+ const env = opts.env ?? process.env;
244
+ const exec = opts.exec ?? defaultExec;
245
+
246
+ const oauth = resolveOAuth(raw, env, exec, warnings, where);
247
+
248
+ const base = {
249
+ name,
250
+ source,
251
+ enabled: raw.enabled !== false,
252
+ exposure: normalizeExposure(raw.exposure),
253
+ timeoutMs: raw.timeout !== undefined && raw.timeout > 0 ? raw.timeout * 1000 : DEFAULT_TIMEOUT_MS,
254
+ wantsOAuth: raw.oauth !== undefined,
255
+ ...(oauth !== undefined ? { oauth } : {}),
256
+ ...(raw.toolExposure !== undefined ? { toolExposure: raw.toolExposure } : {}),
257
+ ...(raw.description !== undefined ? { description: raw.description } : {}),
258
+ };
259
+
260
+ if (raw.command !== undefined) {
261
+ return {
262
+ ...base,
263
+ kind: "stdio",
264
+ command: expandTilde(raw.command, opts.homeDir),
265
+ args: (raw.args ?? []).map((a) => expandTilde(a, opts.homeDir)),
266
+ ...(raw.env !== undefined
267
+ ? { env: interpolateRecord(raw.env, env, exec, warnings, where) }
268
+ : {}),
269
+ ...(raw.cwd !== undefined ? { cwd: expandTilde(raw.cwd, opts.homeDir) } : {}),
270
+ };
271
+ }
272
+ if (raw.url !== undefined) {
273
+ return {
274
+ ...base,
275
+ kind: "http",
276
+ url: raw.url,
277
+ ...(raw.headers !== undefined
278
+ ? { headers: interpolateRecord(raw.headers, env, exec, warnings, where) }
279
+ : {}),
280
+ };
281
+ }
282
+ warnings.push(`${where}: needs "command" (stdio) or "url" (http)`);
283
+ return undefined;
284
+ }
285
+
286
+ /**
287
+ * Directory holding mcp.json: PI_CODING_AGENT_DIR when set, else
288
+ * ~/.pi/agent. Mirrors Pi's own resolution (docs/environment-variables.md).
289
+ */
290
+ export function agentDir(env: Record<string, string | undefined>, homeDir: string): string {
291
+ const override = env.PI_CODING_AGENT_DIR;
292
+ if (typeof override === "string" && override !== "") return override;
293
+ return join(homeDir, ".pi", "agent");
294
+ }
295
+
296
+ /**
297
+ * Load and merge user-level and project-level mcp.json, plus servers
298
+ * registered by other extensions. File entries take precedence over
299
+ * registered ones; project entries take precedence over user entries.
300
+ */
301
+ export function loadServerConfigs(opts: LoadOptions): LoadedConfigs {
302
+ const warnings: string[] = [];
303
+ const merged = new Map<string, ResolvedServerConfig>();
304
+ const seenKeys = new Map<string, string>(); // normalized key -> first name
305
+
306
+ const userEntries = readFileEntries(
307
+ join(agentDir(opts.env ?? (process.env as Record<string, string | undefined>), opts.homeDir), "mcp.json"),
308
+ "user",
309
+ warnings,
310
+ );
311
+ const projectEntries = opts.projectTrusted
312
+ ? readFileEntries(join(opts.cwd, ".pi", "mcp.json"), "project", warnings)
313
+ : [];
314
+
315
+ // Extension-registered servers first: file config overrides them by name.
316
+ if (opts.registered) {
317
+ for (const [name, raw] of opts.registered) {
318
+ const cfg = resolveEntry({ name, raw, source: "extension" }, opts, warnings);
319
+ if (cfg) {
320
+ merged.set(name, cfg);
321
+ seenKeys.set(serverKey(name), name);
322
+ }
323
+ }
324
+ }
325
+
326
+ const applyFile = (entries: RawEntry[], overlayOnly: boolean) => {
327
+ for (const entry of entries) {
328
+ const key = serverKey(entry.name);
329
+ const priorName = seenKeys.get(key);
330
+ if (priorName !== undefined && priorName !== entry.name) {
331
+ warnings.push(
332
+ `${entry.source} server "${entry.name}": conflicts with "${priorName}" (names differ only in -/_), skipping`,
333
+ );
334
+ continue;
335
+ }
336
+ if (overlayOnly && isPartialOverride(entry.raw)) {
337
+ const base = merged.get(entry.name);
338
+ if (!base) {
339
+ warnings.push(
340
+ `project server "${entry.name}": partial override without a matching user-level server`,
341
+ );
342
+ continue;
343
+ }
344
+ merged.set(entry.name, {
345
+ ...base,
346
+ enabled: entry.raw.enabled !== undefined ? entry.raw.enabled !== false : base.enabled,
347
+ exposure: entry.raw.exposure !== undefined ? normalizeExposure(entry.raw.exposure) : base.exposure,
348
+ ...(entry.raw.toolExposure !== undefined ? { toolExposure: entry.raw.toolExposure } : {}),
349
+ });
350
+ continue;
351
+ }
352
+ const cfg = resolveEntry(entry, opts, warnings);
353
+ if (cfg) {
354
+ merged.set(entry.name, cfg);
355
+ seenKeys.set(key, entry.name);
356
+ }
357
+ }
358
+ };
359
+
360
+ applyFile(userEntries, false);
361
+ applyFile(projectEntries, true);
362
+
363
+ return { servers: merged, warnings };
364
+ }
@@ -0,0 +1,53 @@
1
+ /** Async content conversion with built-in MCP's 20 KB middle-out truncation. */
2
+
3
+ import type { ContentBlock } from "@jangmanj/mcp/ops";
4
+ import type { PiContent } from "./pi-api.ts";
5
+ import { offloadBinary, offloadText } from "./result-files.ts";
6
+
7
+ function asRecord(v: unknown): Record<string, unknown> | undefined {
8
+ return typeof v === "object" && v !== null ? (v as Record<string, unknown>) : undefined;
9
+ }
10
+
11
+ export async function convertBlocksOffloaded(blocks: readonly ContentBlock[]): Promise<PiContent[]> {
12
+ const out: PiContent[] = [];
13
+ for (const block of blocks) {
14
+ const raw = asRecord(block.raw) ?? {};
15
+ switch (block.type) {
16
+ case "text": {
17
+ const text = typeof raw.text === "string" ? raw.text : JSON.stringify(raw.text);
18
+ out.push({ type: "text", text: (await offloadText(text)).text });
19
+ break;
20
+ }
21
+ case "image": {
22
+ if (typeof raw.data === "string" && typeof raw.mimeType === "string") {
23
+ out.push({ type: "image", data: raw.data, mimeType: raw.mimeType });
24
+ } else out.push({ type: "text", text: "[image block with invalid data omitted]" });
25
+ break;
26
+ }
27
+ case "audio":
28
+ out.push({ type: "text", text: `[audio${typeof raw.mimeType === "string" ? ` ${raw.mimeType}` : ""} omitted]` });
29
+ break;
30
+ case "resource_link":
31
+ out.push({ type: "text", text: `Resource${typeof raw.name === "string" ? ` "${raw.name}"` : ""}: ${typeof raw.uri === "string" ? raw.uri : "(no uri)"}` });
32
+ break;
33
+ case "resource": {
34
+ const resource = asRecord(raw.resource) ?? raw;
35
+ if (typeof resource.text === "string") {
36
+ out.push({ type: "text", text: (await offloadText(resource.text)).text });
37
+ } else if (typeof resource.blob === "string" && typeof resource.mimeType === "string" && resource.mimeType.startsWith("image/")) {
38
+ out.push({ type: "image", data: resource.blob, mimeType: resource.mimeType });
39
+ } else if (typeof resource.blob === "string") {
40
+ const path = await offloadBinary(Buffer.from(resource.blob, "base64"));
41
+ out.push({ type: "text", text: `[binary resource saved to ${path}]` });
42
+ } else {
43
+ out.push({ type: "text", text: `[binary resource${typeof resource.uri === "string" ? ` ${resource.uri}` : ""} omitted]` });
44
+ }
45
+ break;
46
+ }
47
+ default:
48
+ out.push({ type: "text", text: JSON.stringify(block.raw) });
49
+ }
50
+ }
51
+ if (out.length === 0) out.push({ type: "text", text: "(no content)" });
52
+ return out;
53
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Convert MCP content blocks to Pi tool-result content.
3
+ *
4
+ * Pi's built-in MCP support truncates long text and offloads binary to temp
5
+ * files. This bridge truncates text inline at the same order of magnitude and
6
+ * passes images through as Pi image blocks; everything else degrades to a
7
+ * text description so the model always sees something.
8
+ */
9
+
10
+ import type { ContentBlock } from "@jangmanj/mcp/ops";
11
+ import type { PiContent } from "./pi-api.ts";
12
+
13
+ /** Per-text-block cap, matching Pi's generic tool-output limit of ~50 KB. */
14
+ export const MAX_TEXT_CHARS = 50_000;
15
+
16
+ export function truncateText(text: string): string {
17
+ if (text.length <= MAX_TEXT_CHARS) return text;
18
+ return `${text.slice(0, MAX_TEXT_CHARS)}\n…${text.length - MAX_TEXT_CHARS} chars truncated…`;
19
+ }
20
+
21
+ function asRecord(v: unknown): Record<string, unknown> | undefined {
22
+ return typeof v === "object" && v !== null ? (v as Record<string, unknown>) : undefined;
23
+ }
24
+
25
+ function textBlock(text: unknown): PiContent {
26
+ return { type: "text", text: truncateText(typeof text === "string" ? text : JSON.stringify(text)) };
27
+ }
28
+
29
+ export function convertBlocks(blocks: readonly ContentBlock[]): PiContent[] {
30
+ const out: PiContent[] = [];
31
+ for (const block of blocks) {
32
+ const raw = asRecord(block.raw) ?? {};
33
+ switch (block.type) {
34
+ case "text":
35
+ out.push(textBlock(raw.text));
36
+ break;
37
+ case "image": {
38
+ const data = raw.data;
39
+ const mimeType = raw.mimeType;
40
+ if (typeof data === "string" && typeof mimeType === "string") {
41
+ out.push({ type: "image", data, mimeType });
42
+ } else {
43
+ out.push(textBlock("[image block with invalid data omitted]"));
44
+ }
45
+ break;
46
+ }
47
+ case "audio":
48
+ out.push(textBlock(`[audio${typeof raw.mimeType === "string" ? ` ${raw.mimeType}` : ""} omitted]`));
49
+ break;
50
+ case "resource_link": {
51
+ const name = typeof raw.name === "string" ? raw.name : undefined;
52
+ const uri = typeof raw.uri === "string" ? raw.uri : "(no uri)";
53
+ out.push(textBlock(`Resource${name ? ` "${name}"` : ""}: ${uri}`));
54
+ break;
55
+ }
56
+ case "resource": {
57
+ const resource = asRecord(raw.resource) ?? raw;
58
+ const uri = typeof resource.uri === "string" ? resource.uri : undefined;
59
+ if (typeof resource.text === "string") {
60
+ out.push(textBlock(resource.text));
61
+ } else if (
62
+ typeof resource.blob === "string" &&
63
+ typeof resource.mimeType === "string" &&
64
+ resource.mimeType.startsWith("image/")
65
+ ) {
66
+ out.push({ type: "image", data: resource.blob, mimeType: resource.mimeType });
67
+ } else {
68
+ out.push(textBlock(`[binary resource${uri ? ` ${uri}` : ""} omitted]`));
69
+ }
70
+ break;
71
+ }
72
+ default:
73
+ out.push(textBlock(block.raw));
74
+ }
75
+ }
76
+ if (out.length === 0) out.push(textBlock("(no content)"));
77
+ return out;
78
+ }
@@ -0,0 +1,26 @@
1
+ /** Bounded diagnostics log (mcp-client.log), rotated at 5 MB like Pi's mcp.log. */
2
+
3
+ import { appendFile, mkdir, rename, stat } from "node:fs/promises";
4
+ import { dirname } from "node:path";
5
+
6
+ const MAX_BYTES = 5 * 1024 * 1024;
7
+
8
+ export class DiagnosticsLog {
9
+ #writing: Promise<void> = Promise.resolve();
10
+
11
+ constructor(private readonly path: string) {}
12
+
13
+ line(server: string, message: string): void {
14
+ const line = `${new Date().toISOString()} [${server}] ${message}\n`;
15
+ this.#writing = this.#writing.then(async () => {
16
+ await mkdir(dirname(this.path), { recursive: true });
17
+ try {
18
+ const info = await stat(this.path);
19
+ if (info.size > MAX_BYTES) await rename(this.path, `${this.path}.1`);
20
+ } catch {
21
+ // first write
22
+ }
23
+ await appendFile(this.path, line);
24
+ }).catch(() => {});
25
+ }
26
+ }
@@ -0,0 +1,133 @@
1
+ /** MRTR + elicitation support using the host's Pi UI. */
2
+
3
+ import { openSystemBrowser } from "@jangmanj/mcp/auth";
4
+ import type { Outcome } from "@jangmanj/mcp/core";
5
+ import type { ConsentPort } from "@jangmanj/mcp/core";
6
+ import { elicit, type FormRequest } from "@jangmanj/mcp/mrtr-cache";
7
+ import { normalizeContent, type ToolCallResult } from "@jangmanj/mcp/ops";
8
+ import type { ResourceServer } from "./resources.ts";
9
+ import type { Ui } from "./pi-api.ts";
10
+
11
+ function formPort(ui: Ui) {
12
+ return async (request: FormRequest, signal: AbortSignal) => {
13
+ if (!ui.input && !ui.confirm) return { action: "decline" as const };
14
+ const content: Record<string, unknown> = {};
15
+ const properties = (request.schema.properties ?? {}) as Record<string, Record<string, unknown>>;
16
+ for (const [key, schema] of Object.entries(properties)) {
17
+ const def = request.defaults[key];
18
+ const enumValues = Array.isArray(schema.enum) ? schema.enum.filter((v): v is string => typeof v === "string") : undefined;
19
+ let value: unknown = def;
20
+ if (enumValues && ui.select) {
21
+ const selected = await ui.select(`${key}:`, enumValues.map((v) => String(v)));
22
+ if (selected !== undefined) value = selected;
23
+ } else if (ui.input) {
24
+ const answer = await ui.input(`${key}:`, def === undefined ? "" : String(def));
25
+ if (answer !== undefined) value = answer;
26
+ }
27
+ if (value === undefined) return { action: "cancel" as const };
28
+ content[key] = value;
29
+ }
30
+ if (ui.confirm) {
31
+ const ok = await ui.confirm(
32
+ `MCP server "${request.serverLabel}" requests information`,
33
+ `${request.message}\n${request.suspectSensitiveFields.length > 0 ? "\nIncludes potentially sensitive fields." : ""}`,
34
+ );
35
+ if (!ok) return { action: "decline" as const };
36
+ }
37
+ if (signal.aborted) return { action: "cancel" as const };
38
+ return { action: "accept" as const, content };
39
+ };
40
+ }
41
+
42
+ /** ConsentPort used to declare form/url elicitation capabilities to servers. */
43
+ export function consentPort(ui: Ui, serverLabel: string): ConsentPort {
44
+ return {
45
+ request: async (prompt, signal) => {
46
+ if (prompt.kind === "form-elicitation") {
47
+ const result = await formPort(ui)({
48
+ serverLabel,
49
+ message: prompt.message ?? "Input requested",
50
+ schema: prompt.schema ?? { type: "object", properties: {} },
51
+ defaults: {},
52
+ suspectSensitiveFields: [],
53
+ invalidPrevious: false,
54
+ }, signal);
55
+ return result.action === "accept"
56
+ ? { decision: "accept", content: result.content }
57
+ : { decision: result.action };
58
+ }
59
+ const ok = await (ui.confirm?.(
60
+ prompt.kind === "url-elicitation" ? "Open URL?" : "MCP consent",
61
+ prompt.message ?? prompt.url ?? prompt.serverLabel,
62
+ ) ?? Promise.resolve(false));
63
+ return ok ? { decision: "accept" } : { decision: "decline" };
64
+ },
65
+ };
66
+ }
67
+
68
+ /** Call a tool, fulfilling elicitation/create input requests across MRTR rounds. */
69
+ export async function callWithElicitation(
70
+ state: ResourceServer,
71
+ toolName: string,
72
+ params: Record<string, unknown>,
73
+ opts: { signal?: AbortSignal; onProgress?: (p: unknown) => void },
74
+ ui: Ui,
75
+ ): Promise<Outcome<ToolCallResult>> {
76
+ if (!state.ops) throw new Error(`MCP server "${state.name}" is not connected`);
77
+ let current = params;
78
+ let extra: Record<string, unknown> = {};
79
+ for (let round = 0; round < 8; round++) {
80
+ const raw = await state.client!.request("tools/call", {
81
+ name: toolName,
82
+ arguments: current,
83
+ ...extra,
84
+ }, {
85
+ mrtr: "manual",
86
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
87
+ ...(opts.onProgress !== undefined ? { onProgress: opts.onProgress } : {}),
88
+ });
89
+ if (raw.kind === "ok") {
90
+ const value = raw.value as Record<string, unknown>;
91
+ return {
92
+ kind: "ok",
93
+ value: {
94
+ raw: value,
95
+ content: normalizeContent(value.content),
96
+ ...(value.structuredContent !== undefined ? { structuredContent: value.structuredContent } : {}),
97
+ validation: { status: "skipped" },
98
+ },
99
+ meta: raw.meta,
100
+ };
101
+ }
102
+ if (raw.kind !== "mrtr-interim") return raw as Outcome<ToolCallResult>;
103
+ const responses: Record<string, unknown> = {};
104
+ for (const [key, request] of Object.entries(raw.inputRequests ?? {})) {
105
+ const req = request as { method?: string; params?: Record<string, unknown> };
106
+ if (req.method !== "elicitation/create" || !req.params) {
107
+ throw new Error(`unsupported MRTR input request: ${req.method ?? "unknown"}`);
108
+ }
109
+ const result = await elicit(req.params, {
110
+ serverLabel: state.name,
111
+ port: {
112
+ form: formPort(ui),
113
+ url: async (request) => {
114
+ if (!ui.confirm) return "decline";
115
+ const ok = await ui.confirm(
116
+ `MCP server "${state.name}" requests authorization`,
117
+ `${request.message}\nOpen ${request.hostHighlight} in your browser?`,
118
+ );
119
+ return ok ? "accept" : "decline";
120
+ },
121
+ },
122
+ browser: { open: openSystemBrowser },
123
+ }, opts.signal ?? new AbortController().signal);
124
+ if (result.action !== "accept") throw new Error(`elicitation ${result.action}`);
125
+ responses[key] = { action: result.action, ...(result.content !== undefined ? { content: result.content } : {}) };
126
+ }
127
+ extra = {
128
+ inputResponses: responses,
129
+ ...(raw.requestState !== undefined ? { requestState: raw.requestState } : {}),
130
+ };
131
+ }
132
+ throw new Error("too many MRTR rounds");
133
+ }