pi-knowledge 0.14.0 → 0.16.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 (63) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +63 -24
  3. package/dist/index.d.ts +10 -4
  4. package/dist/index.js +300 -187
  5. package/dist/src/coverage-snapshot.d.ts +23 -0
  6. package/dist/src/coverage-snapshot.js +53 -0
  7. package/dist/src/daemon/client.d.ts +60 -0
  8. package/dist/src/daemon/client.js +360 -0
  9. package/dist/src/daemon/main.d.ts +2 -0
  10. package/dist/src/daemon/main.js +109 -0
  11. package/dist/src/daemon/protocol.d.ts +71 -0
  12. package/dist/src/daemon/protocol.js +170 -0
  13. package/dist/src/daemon/runtime.d.ts +26 -0
  14. package/dist/src/daemon/runtime.js +192 -0
  15. package/dist/src/daemon/server.d.ts +46 -0
  16. package/dist/src/daemon/server.js +500 -0
  17. package/dist/src/daemon/service.d.ts +49 -0
  18. package/dist/src/daemon/service.js +527 -0
  19. package/dist/src/diagnostics/health.d.ts +6 -0
  20. package/dist/src/diagnostics/health.js +135 -2
  21. package/dist/src/engine.d.ts +63 -9
  22. package/dist/src/engine.js +959 -170
  23. package/dist/src/filesystem-access.d.ts +9 -0
  24. package/dist/src/filesystem-access.js +100 -0
  25. package/dist/src/indexer/chunker.d.ts +10 -0
  26. package/dist/src/indexer/chunker.js +284 -9
  27. package/dist/src/mcp/http.d.ts +47 -0
  28. package/dist/src/mcp/http.js +564 -0
  29. package/dist/src/mcp/main.d.ts +2 -0
  30. package/dist/src/mcp/main.js +97 -0
  31. package/dist/src/mcp/protocol.d.ts +81 -0
  32. package/dist/src/mcp/protocol.js +444 -0
  33. package/dist/src/mcp/server.d.ts +42 -0
  34. package/dist/src/mcp/server.js +378 -0
  35. package/dist/src/model-worker-client.js +9 -0
  36. package/dist/src/model-worker-contract.d.ts +3 -0
  37. package/dist/src/model-worker-contract.js +8 -0
  38. package/dist/src/model-worker.js +76 -4
  39. package/dist/src/network/safe-fetch.d.ts +7 -0
  40. package/dist/src/network/safe-fetch.js +199 -0
  41. package/dist/src/node-runtime.d.ts +3 -0
  42. package/dist/src/node-runtime.js +78 -0
  43. package/dist/src/profiles.d.ts +15 -0
  44. package/dist/src/profiles.js +160 -0
  45. package/dist/src/runtime-config.js +5 -6
  46. package/dist/src/search/tuning.d.ts +2 -0
  47. package/dist/src/search/tuning.js +2 -0
  48. package/dist/src/secure-files.d.ts +17 -0
  49. package/dist/src/secure-files.js +184 -0
  50. package/dist/src/status.js +12 -7
  51. package/dist/src/storage/sqlite.d.ts +4 -1
  52. package/dist/src/storage/sqlite.js +46 -3
  53. package/dist/src/type-guards.d.ts +1 -0
  54. package/dist/src/type-guards.js +3 -0
  55. package/dist/src/watcher/file-watcher.d.ts +3 -1
  56. package/dist/src/watcher/file-watcher.js +166 -32
  57. package/dist/src/windows-security.d.ts +4 -0
  58. package/dist/src/windows-security.js +47 -0
  59. package/docs/configuration.md +42 -10
  60. package/docs/daemon-profiles.md +302 -0
  61. package/docs/mcp-clients.md +266 -0
  62. package/docs/offline-mode.md +6 -6
  63. package/package.json +28 -2
@@ -0,0 +1,81 @@
1
+ import type { ToolDefinition } from "../../index.ts";
2
+ import type { KnowledgeDaemonClient } from "../daemon/client.ts";
3
+ import type { KnowledgeProfile } from "../profiles.ts";
4
+ export declare const MODERN_MCP_PROTOCOL = "2026-07-28";
5
+ export declare const LEGACY_MCP_PROTOCOLS: readonly ["2025-11-25", "2025-06-18", "2025-03-26"];
6
+ export declare const SUPPORTED_MCP_PROTOCOLS: readonly string[];
7
+ export declare const MAX_MCP_INPUT_BYTES: number;
8
+ export declare const MAX_MCP_OUTPUT_BYTES: number;
9
+ export declare const MAX_MCP_OUTPUT_QUEUE_BYTES: number;
10
+ export declare const MAX_MCP_CONCURRENT_REQUESTS = 16;
11
+ export declare const MCP_SHUTDOWN_TIMEOUT_MS = 5000;
12
+ export type JsonRpcId = string | number;
13
+ export type JsonRpcResponseId = JsonRpcId | null;
14
+ export type McpProtocolEra = "legacy" | "modern";
15
+ export interface JsonRpcRequest {
16
+ jsonrpc: "2.0";
17
+ id?: JsonRpcId;
18
+ method: string;
19
+ params?: Record<string, unknown>;
20
+ }
21
+ export interface McpServerOptions {
22
+ profile: KnowledgeProfile;
23
+ client: KnowledgeDaemonClient;
24
+ tools: ToolDefinition[];
25
+ serverVersion: string;
26
+ allowRoots: string[];
27
+ allowNetwork: boolean;
28
+ allowWrite: boolean;
29
+ allowAdmin: boolean;
30
+ onError?: (error: unknown) => void;
31
+ }
32
+ export interface McpHandledMessage {
33
+ request: JsonRpcRequest;
34
+ era?: McpProtocolEra;
35
+ response?: Record<string, unknown>;
36
+ httpStatus?: number;
37
+ }
38
+ export type McpMessageEmitter = (message: Record<string, unknown>) => Promise<void>;
39
+ export declare class McpProtocolError extends Error {
40
+ readonly code: number;
41
+ readonly data?: unknown;
42
+ readonly httpStatus?: number;
43
+ constructor(code: number, message: string, options?: {
44
+ data?: unknown;
45
+ httpStatus?: number;
46
+ });
47
+ }
48
+ export declare function truncateMcpText(value: string, maxBytes: number): string;
49
+ export declare function mcpErrorMessage(error: unknown): string;
50
+ export declare function mcpRpcError(id: JsonRpcResponseId, code: number, message: string, data?: unknown): Record<string, unknown>;
51
+ export declare function parseMcpRequest(value: unknown): JsonRpcRequest;
52
+ export declare function validateModernRequestMetadata(params: Record<string, unknown>): Record<string, unknown>;
53
+ export declare function modernProtocolVersion(request: JsonRpcRequest): string | undefined;
54
+ export declare class McpProtocolSession {
55
+ private readonly options;
56
+ private readonly toolsByName;
57
+ private readonly controllers;
58
+ private legacyProtocolVersionValue;
59
+ constructor(options: McpServerOptions);
60
+ get legacyProtocolVersion(): string | undefined;
61
+ get activeRequestCount(): number;
62
+ abortAll(): void;
63
+ private isToolEnabled;
64
+ private authorizeExistingPath;
65
+ private authorizeOutputPath;
66
+ private authorizeSource;
67
+ private authorizeUpdate;
68
+ private authorizeToolCall;
69
+ private toolList;
70
+ private serverInfo;
71
+ private modernResult;
72
+ private modernCacheableResult;
73
+ private legacyHandshake;
74
+ private modernDiscovery;
75
+ private callTool;
76
+ private requestEra;
77
+ private notificationEra;
78
+ private dispatch;
79
+ private cancel;
80
+ handleRequest(request: JsonRpcRequest, emit: McpMessageEmitter, externalSignal?: AbortSignal): Promise<McpHandledMessage>;
81
+ }
@@ -0,0 +1,444 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { isObjectRecord } from "../type-guards.js";
4
+ export const MODERN_MCP_PROTOCOL = "2026-07-28";
5
+ export const LEGACY_MCP_PROTOCOLS = Object.freeze(["2025-11-25", "2025-06-18", "2025-03-26"]);
6
+ export const SUPPORTED_MCP_PROTOCOLS = Object.freeze([MODERN_MCP_PROTOCOL, ...LEGACY_MCP_PROTOCOLS]);
7
+ export const MAX_MCP_INPUT_BYTES = 2 * 1024 * 1024;
8
+ export const MAX_MCP_OUTPUT_BYTES = 16 * 1024 * 1024;
9
+ export const MAX_MCP_OUTPUT_QUEUE_BYTES = 128 * 1024 * 1024;
10
+ export const MAX_MCP_CONCURRENT_REQUESTS = 16;
11
+ export const MCP_SHUTDOWN_TIMEOUT_MS = 5_000;
12
+ const MAX_PROGRESS_NOTIFICATIONS = 100;
13
+ const MAX_PROGRESS_MESSAGE_BYTES = 4 * 1024;
14
+ const MODERN_STATIC_LIST_TTL_MS = 5 * 60 * 1_000;
15
+ const READ_TOOL_NAMES = new Set(["knowledge_search", "knowledge_symbol_search", "knowledge_show"]);
16
+ const WRITE_TOOL_NAMES = new Set(["knowledge_add", "knowledge_update", "knowledge_import", "knowledge_export"]);
17
+ const ADMIN_TOOL_NAMES = new Set([
18
+ "knowledge_configure",
19
+ "knowledge_status",
20
+ "knowledge_doctor",
21
+ "knowledge_remove",
22
+ "knowledge_clear",
23
+ ]);
24
+ export class McpProtocolError extends Error {
25
+ code;
26
+ data;
27
+ httpStatus;
28
+ constructor(code, message, options = {}) {
29
+ super(message);
30
+ this.name = "McpProtocolError";
31
+ this.code = code;
32
+ this.data = options.data;
33
+ this.httpStatus = options.httpStatus;
34
+ }
35
+ }
36
+ export function truncateMcpText(value, maxBytes) {
37
+ if (Buffer.byteLength(value) <= maxBytes)
38
+ return value;
39
+ const suffix = "…";
40
+ const budget = Math.max(0, maxBytes - Buffer.byteLength(suffix));
41
+ const buffer = Buffer.from(value);
42
+ let end = Math.min(buffer.byteLength, budget);
43
+ const decoder = new TextDecoder("utf-8", { fatal: true });
44
+ while (end > 0) {
45
+ try {
46
+ return `${decoder.decode(buffer.subarray(0, end))}${suffix}`;
47
+ }
48
+ catch {
49
+ end--;
50
+ }
51
+ }
52
+ return suffix;
53
+ }
54
+ export function mcpErrorMessage(error) {
55
+ return truncateMcpText(error instanceof Error ? error.message : String(error), 4_096);
56
+ }
57
+ export function mcpRpcError(id, code, message, data) {
58
+ return {
59
+ jsonrpc: "2.0",
60
+ id,
61
+ error: data === undefined ? { code, message } : { code, message, data },
62
+ };
63
+ }
64
+ export function parseMcpRequest(value) {
65
+ if (!isObjectRecord(value) || value.jsonrpc !== "2.0" || typeof value.method !== "string") {
66
+ throw new McpProtocolError(-32600, "Invalid JSON-RPC request", { httpStatus: 400 });
67
+ }
68
+ let id;
69
+ if ("id" in value) {
70
+ const rawId = value.id;
71
+ if (typeof rawId !== "string" && typeof rawId !== "number") {
72
+ throw new McpProtocolError(-32600, "Invalid JSON-RPC request id", { httpStatus: 400 });
73
+ }
74
+ id = rawId;
75
+ }
76
+ const params = value.params;
77
+ if ("params" in value && params !== undefined && !isObjectRecord(params)) {
78
+ throw new McpProtocolError(-32602, "Invalid JSON-RPC params", { httpStatus: 400 });
79
+ }
80
+ return {
81
+ jsonrpc: "2.0",
82
+ id,
83
+ method: value.method,
84
+ params: isObjectRecord(params) ? params : undefined,
85
+ };
86
+ }
87
+ function requiredString(params, key) {
88
+ const value = params[key];
89
+ if (typeof value !== "string" || !value.trim())
90
+ throw new McpProtocolError(-32602, `Missing or invalid ${key}`);
91
+ return value;
92
+ }
93
+ function requestKey(id) {
94
+ return `${typeof id}:${String(id)}`;
95
+ }
96
+ function isWithin(path, root) {
97
+ const relation = relative(root, path);
98
+ return relation === "" || (relation !== ".." && !relation.startsWith(`..${sep}`) && !isAbsolute(relation));
99
+ }
100
+ export function validateModernRequestMetadata(params) {
101
+ const meta = params._meta;
102
+ if (!isObjectRecord(meta)) {
103
+ throw new McpProtocolError(-32602, "Modern MCP requests require params._meta", { httpStatus: 400 });
104
+ }
105
+ const version = meta["io.modelcontextprotocol/protocolVersion"];
106
+ const capabilities = meta["io.modelcontextprotocol/clientCapabilities"];
107
+ if (typeof version !== "string" || !isObjectRecord(capabilities)) {
108
+ throw new McpProtocolError(-32602, "Modern MCP request metadata is incomplete", { httpStatus: 400 });
109
+ }
110
+ if (version !== MODERN_MCP_PROTOCOL) {
111
+ throw new McpProtocolError(-32022, "Unsupported protocol version", {
112
+ httpStatus: 400,
113
+ data: { supported: [...SUPPORTED_MCP_PROTOCOLS], requested: version },
114
+ });
115
+ }
116
+ const clientInfo = meta["io.modelcontextprotocol/clientInfo"];
117
+ if (clientInfo !== undefined &&
118
+ (!isObjectRecord(clientInfo) || typeof clientInfo.name !== "string" || typeof clientInfo.version !== "string")) {
119
+ throw new McpProtocolError(-32602, "Invalid modern MCP clientInfo", { httpStatus: 400 });
120
+ }
121
+ return meta;
122
+ }
123
+ export function modernProtocolVersion(request) {
124
+ const meta = request.params?._meta;
125
+ if (!isObjectRecord(meta))
126
+ return undefined;
127
+ const version = meta["io.modelcontextprotocol/protocolVersion"];
128
+ return typeof version === "string" ? version : undefined;
129
+ }
130
+ export class McpProtocolSession {
131
+ options;
132
+ toolsByName = new Map();
133
+ controllers = new Map();
134
+ legacyProtocolVersionValue;
135
+ constructor(options) {
136
+ this.options = options;
137
+ for (const tool of options.tools) {
138
+ if (this.isToolEnabled(tool.name))
139
+ this.toolsByName.set(tool.name, tool);
140
+ }
141
+ }
142
+ get legacyProtocolVersion() {
143
+ return this.legacyProtocolVersionValue;
144
+ }
145
+ get activeRequestCount() {
146
+ return this.controllers.size;
147
+ }
148
+ abortAll() {
149
+ for (const controller of this.controllers.values())
150
+ controller.abort();
151
+ }
152
+ isToolEnabled(name) {
153
+ if (READ_TOOL_NAMES.has(name))
154
+ return true;
155
+ if (name === "knowledge_plan")
156
+ return this.options.allowRoots.length > 0 || this.options.allowNetwork;
157
+ if (WRITE_TOOL_NAMES.has(name))
158
+ return this.options.allowWrite;
159
+ if (ADMIN_TOOL_NAMES.has(name))
160
+ return this.options.allowAdmin;
161
+ return false;
162
+ }
163
+ async authorizeExistingPath(input) {
164
+ if (this.options.allowRoots.length === 0)
165
+ throw new Error("No --allow-root capability permits local paths");
166
+ const canonical = realpathSync.native(resolve(input));
167
+ if (!this.options.allowRoots.some((root) => isWithin(canonical, root))) {
168
+ throw new Error(`Local path is outside the configured --allow-root scope: ${input}`);
169
+ }
170
+ return canonical;
171
+ }
172
+ async authorizeOutputPath(input) {
173
+ if (this.options.allowRoots.length === 0)
174
+ throw new Error("No --allow-root capability permits local paths");
175
+ const absolute = resolve(input);
176
+ const canonical = existsSync(absolute)
177
+ ? realpathSync.native(absolute)
178
+ : resolve(realpathSync.native(dirname(absolute)), basename(absolute));
179
+ if (!this.options.allowRoots.some((root) => isWithin(canonical, root))) {
180
+ throw new Error(`Output path is outside the configured --allow-root scope: ${input}`);
181
+ }
182
+ return canonical;
183
+ }
184
+ async authorizeSource(source) {
185
+ if (/^https?:\/\//i.test(source)) {
186
+ if (!this.options.allowNetwork)
187
+ throw new Error("URL access requires --allow-network");
188
+ return source;
189
+ }
190
+ const absolute = resolve(source);
191
+ if (existsSync(absolute))
192
+ return this.authorizeExistingPath(absolute);
193
+ const pathLike = source.startsWith(".") ||
194
+ source.startsWith("/") ||
195
+ source.startsWith("~") ||
196
+ /^[A-Za-z]:[\\/]/.test(source) ||
197
+ (!source.includes("\n") && /[\\/]/.test(source));
198
+ if (pathLike)
199
+ throw new Error(`Local source does not exist or is outside authorized roots: ${source}`);
200
+ return source;
201
+ }
202
+ async authorizeUpdate(target, signal) {
203
+ const knowledgeBases = await this.options.client.list(signal);
204
+ const kb = knowledgeBases.find((candidate) => candidate.id === target) ??
205
+ knowledgeBases.find((candidate) => candidate.name === target);
206
+ if (!kb)
207
+ throw new Error(`Knowledge base not found: ${target}`);
208
+ if (kb.source_type === "url" || (kb.source_path && /^https?:\/\//i.test(kb.source_path))) {
209
+ if (!this.options.allowNetwork)
210
+ throw new Error("Updating this URL knowledge base requires --allow-network");
211
+ }
212
+ else if (kb.source_path) {
213
+ await this.authorizeExistingPath(kb.source_path);
214
+ }
215
+ return kb.id;
216
+ }
217
+ async authorizeToolCall(name, argumentsValue, signal) {
218
+ switch (name) {
219
+ case "knowledge_plan":
220
+ case "knowledge_add":
221
+ return {
222
+ ...argumentsValue,
223
+ source: await this.authorizeSource(requiredString(argumentsValue, "source")),
224
+ };
225
+ case "knowledge_update":
226
+ return {
227
+ ...argumentsValue,
228
+ target: await this.authorizeUpdate(requiredString(argumentsValue, "target"), signal),
229
+ };
230
+ case "knowledge_import":
231
+ return {
232
+ ...argumentsValue,
233
+ input: await this.authorizeExistingPath(requiredString(argumentsValue, "input")),
234
+ };
235
+ case "knowledge_export":
236
+ return {
237
+ ...argumentsValue,
238
+ output: await this.authorizeOutputPath(requiredString(argumentsValue, "output")),
239
+ };
240
+ default:
241
+ return argumentsValue;
242
+ }
243
+ }
244
+ toolList() {
245
+ return [...this.toolsByName.values()].map((tool) => ({
246
+ name: tool.name,
247
+ title: tool.label,
248
+ description: tool.description,
249
+ inputSchema: tool.parameters,
250
+ annotations: {
251
+ readOnlyHint: tool.approval === "read",
252
+ destructiveHint: tool.name === "knowledge_remove" || tool.name === "knowledge_clear",
253
+ },
254
+ }));
255
+ }
256
+ serverInfo() {
257
+ return { name: "pi-knowledge", version: this.options.serverVersion };
258
+ }
259
+ modernResult(result) {
260
+ const existingMeta = isObjectRecord(result._meta) ? result._meta : {};
261
+ return {
262
+ ...result,
263
+ resultType: "complete",
264
+ _meta: {
265
+ ...existingMeta,
266
+ "io.modelcontextprotocol/serverInfo": this.serverInfo(),
267
+ "com.pi-knowledge/profile": this.options.profile.name,
268
+ },
269
+ };
270
+ }
271
+ modernCacheableResult(result) {
272
+ return this.modernResult({
273
+ ...result,
274
+ ttlMs: MODERN_STATIC_LIST_TTL_MS,
275
+ cacheScope: "private",
276
+ });
277
+ }
278
+ legacyHandshake(protocolVersion) {
279
+ return {
280
+ protocolVersion,
281
+ capabilities: { tools: { listChanged: false } },
282
+ serverInfo: this.serverInfo(),
283
+ instructions: "Use knowledge_symbol_search for exact identifiers, then knowledge_search for broader context. Mutating tools follow the server launch capabilities.",
284
+ };
285
+ }
286
+ modernDiscovery() {
287
+ return this.modernCacheableResult({
288
+ supportedVersions: [...SUPPORTED_MCP_PROTOCOLS],
289
+ capabilities: { tools: { listChanged: false } },
290
+ instructions: "Use knowledge_symbol_search for exact identifiers, then knowledge_search for broader context. Mutating tools follow the server launch capabilities.",
291
+ });
292
+ }
293
+ async callTool(request, params, era, emit, externalSignal) {
294
+ if (request.id === undefined)
295
+ throw new McpProtocolError(-32600, "Tool calls require a request id");
296
+ const name = requiredString(params, "name");
297
+ const tool = this.toolsByName.get(name);
298
+ if (!tool || !tool.execute)
299
+ throw new Error(`MCP tool is not enabled: ${name}`);
300
+ const argumentsValue = params.arguments;
301
+ if (argumentsValue !== undefined && !isObjectRecord(argumentsValue))
302
+ throw new Error("Invalid tool arguments");
303
+ const controller = new AbortController();
304
+ const key = requestKey(request.id);
305
+ if (this.controllers.has(key))
306
+ throw new Error(`MCP request id is already active: ${String(request.id)}`);
307
+ this.controllers.set(key, controller);
308
+ const abort = () => controller.abort();
309
+ if (externalSignal?.aborted)
310
+ controller.abort();
311
+ else
312
+ externalSignal?.addEventListener("abort", abort, { once: true });
313
+ let progressCount = 0;
314
+ const meta = isObjectRecord(params._meta) ? params._meta : undefined;
315
+ const progressToken = meta && (typeof meta.progressToken === "string" || typeof meta.progressToken === "number")
316
+ ? meta.progressToken
317
+ : undefined;
318
+ try {
319
+ const authorizedArguments = await this.authorizeToolCall(name, argumentsValue ?? {}, controller.signal);
320
+ const result = await tool.execute(key, authorizedArguments, controller.signal, (update) => {
321
+ if (progressToken === undefined || progressCount >= MAX_PROGRESS_NOTIFICATIONS || controller.signal.aborted)
322
+ return;
323
+ const message = update.content.map((item) => item.text).join("\n");
324
+ if (!message)
325
+ return;
326
+ progressCount++;
327
+ const bounded = truncateMcpText(message, MAX_PROGRESS_MESSAGE_BYTES);
328
+ void emit({
329
+ jsonrpc: "2.0",
330
+ method: "notifications/progress",
331
+ params: { progressToken, progress: progressCount, message: bounded },
332
+ }).catch((error) => this.options.onError?.(error));
333
+ }, {
334
+ profile: this.options.profile.name,
335
+ filesystemAccess: {
336
+ allowedRoots: this.options.allowRoots,
337
+ allowNetwork: this.options.allowNetwork,
338
+ },
339
+ });
340
+ const normalized = result;
341
+ return era === "modern" ? this.modernResult(normalized) : normalized;
342
+ }
343
+ catch (error) {
344
+ const failed = {
345
+ content: [{ type: "text", text: mcpErrorMessage(error) }],
346
+ isError: true,
347
+ };
348
+ return era === "modern" ? this.modernResult(failed) : failed;
349
+ }
350
+ finally {
351
+ externalSignal?.removeEventListener("abort", abort);
352
+ this.controllers.delete(key);
353
+ }
354
+ }
355
+ requestEra(request) {
356
+ if (request.method === "initialize")
357
+ return "legacy";
358
+ if (this.legacyProtocolVersionValue)
359
+ return "legacy";
360
+ validateModernRequestMetadata(request.params ?? {});
361
+ return "modern";
362
+ }
363
+ notificationEra(request) {
364
+ if (this.legacyProtocolVersionValue)
365
+ return "legacy";
366
+ try {
367
+ validateModernRequestMetadata(request.params ?? {});
368
+ return "modern";
369
+ }
370
+ catch (error) {
371
+ this.options.onError?.(error);
372
+ return undefined;
373
+ }
374
+ }
375
+ async dispatch(request, era, emit, externalSignal) {
376
+ const params = request.params ?? {};
377
+ if (request.method === "initialize") {
378
+ if (this.legacyProtocolVersionValue)
379
+ throw new McpProtocolError(-32602, "MCP protocol is already initialized");
380
+ const requested = requiredString(params, "protocolVersion");
381
+ if (!LEGACY_MCP_PROTOCOLS.includes(requested)) {
382
+ throw new McpProtocolError(-32602, `Unsupported legacy MCP protocol version: ${requested}`);
383
+ }
384
+ this.legacyProtocolVersionValue = requested;
385
+ return this.legacyHandshake(requested);
386
+ }
387
+ if (era === "legacy" && !this.legacyProtocolVersionValue) {
388
+ throw new McpProtocolError(-32602, "MCP protocol is not initialized");
389
+ }
390
+ switch (request.method) {
391
+ case "server/discover":
392
+ if (era !== "modern")
393
+ throw new McpProtocolError(-32601, "Method not found: server/discover", { httpStatus: 404 });
394
+ return this.modernDiscovery();
395
+ case "ping":
396
+ return era === "modern" ? this.modernResult({}) : {};
397
+ case "tools/list": {
398
+ const result = { tools: this.toolList() };
399
+ return era === "modern" ? this.modernCacheableResult(result) : result;
400
+ }
401
+ case "tools/call":
402
+ return this.callTool(request, params, era, emit, externalSignal);
403
+ default:
404
+ throw new McpProtocolError(-32601, `Method not found: ${request.method}`, {
405
+ httpStatus: era === "modern" ? 404 : undefined,
406
+ });
407
+ }
408
+ }
409
+ cancel(params) {
410
+ const id = params.requestId;
411
+ if (typeof id !== "string" && typeof id !== "number")
412
+ return;
413
+ this.controllers.get(requestKey(id))?.abort();
414
+ }
415
+ async handleRequest(request, emit, externalSignal) {
416
+ if (request.method === "notifications/cancelled") {
417
+ const era = this.notificationEra(request);
418
+ if (era)
419
+ this.cancel(request.params ?? {});
420
+ return { request, era };
421
+ }
422
+ if (request.method === "notifications/initialized") {
423
+ return { request, era: this.notificationEra(request) };
424
+ }
425
+ if (request.id === undefined)
426
+ return { request, era: this.notificationEra(request) };
427
+ let era;
428
+ try {
429
+ era = this.requestEra(request);
430
+ const result = await this.dispatch(request, era, emit, externalSignal);
431
+ return { request, era, response: { jsonrpc: "2.0", id: request.id, result } };
432
+ }
433
+ catch (error) {
434
+ const protocolError = error instanceof McpProtocolError ? error : undefined;
435
+ const code = protocolError?.code ?? -32602;
436
+ return {
437
+ request,
438
+ era,
439
+ httpStatus: protocolError?.httpStatus,
440
+ response: mcpRpcError(request.id, code, mcpErrorMessage(error), protocolError?.data),
441
+ };
442
+ }
443
+ }
444
+ }
@@ -0,0 +1,42 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import { type McpServerOptions } from "./protocol.ts";
3
+ export type McpTransport = "stdio" | "http";
4
+ export interface McpCliOptions {
5
+ profileName?: string;
6
+ allowRoots: string[];
7
+ allowNetwork: boolean;
8
+ allowWrite: boolean;
9
+ allowAdmin: boolean;
10
+ transport: McpTransport;
11
+ httpHost: string;
12
+ httpPort: number;
13
+ httpEndpoint: string;
14
+ allowOrigins: string[];
15
+ }
16
+ interface McpAdapterOptions extends McpServerOptions {
17
+ profileName?: string;
18
+ input: Readable;
19
+ output: Writable;
20
+ error: Writable;
21
+ }
22
+ export declare function parseMcpArguments(argv: string[]): McpCliOptions;
23
+ export declare function canonicalizeAllowedRoots(paths: string[]): string[];
24
+ export declare class McpStdioAdapter {
25
+ private readonly output;
26
+ private readonly session;
27
+ private readonly active;
28
+ private readonly inputFrame;
29
+ private inputBytes;
30
+ private closing;
31
+ private readonly options;
32
+ private overloadResponse;
33
+ constructor(options: McpAdapterOptions);
34
+ private sendError;
35
+ private logError;
36
+ private handleValue;
37
+ private rejectOverload;
38
+ private acceptLine;
39
+ private consumeChunk;
40
+ run(): Promise<void>;
41
+ }
42
+ export {};