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.
- package/CHANGELOG.md +32 -0
- package/README.md +63 -24
- package/dist/index.d.ts +10 -4
- package/dist/index.js +300 -187
- package/dist/src/coverage-snapshot.d.ts +23 -0
- package/dist/src/coverage-snapshot.js +53 -0
- package/dist/src/daemon/client.d.ts +60 -0
- package/dist/src/daemon/client.js +360 -0
- package/dist/src/daemon/main.d.ts +2 -0
- package/dist/src/daemon/main.js +109 -0
- package/dist/src/daemon/protocol.d.ts +71 -0
- package/dist/src/daemon/protocol.js +170 -0
- package/dist/src/daemon/runtime.d.ts +26 -0
- package/dist/src/daemon/runtime.js +192 -0
- package/dist/src/daemon/server.d.ts +46 -0
- package/dist/src/daemon/server.js +500 -0
- package/dist/src/daemon/service.d.ts +49 -0
- package/dist/src/daemon/service.js +527 -0
- package/dist/src/diagnostics/health.d.ts +6 -0
- package/dist/src/diagnostics/health.js +135 -2
- package/dist/src/engine.d.ts +63 -9
- package/dist/src/engine.js +959 -170
- package/dist/src/filesystem-access.d.ts +9 -0
- package/dist/src/filesystem-access.js +100 -0
- package/dist/src/indexer/chunker.d.ts +10 -0
- package/dist/src/indexer/chunker.js +284 -9
- package/dist/src/mcp/http.d.ts +47 -0
- package/dist/src/mcp/http.js +564 -0
- package/dist/src/mcp/main.d.ts +2 -0
- package/dist/src/mcp/main.js +97 -0
- package/dist/src/mcp/protocol.d.ts +81 -0
- package/dist/src/mcp/protocol.js +444 -0
- package/dist/src/mcp/server.d.ts +42 -0
- package/dist/src/mcp/server.js +378 -0
- package/dist/src/model-worker-client.js +9 -0
- package/dist/src/model-worker-contract.d.ts +3 -0
- package/dist/src/model-worker-contract.js +8 -0
- package/dist/src/model-worker.js +76 -4
- package/dist/src/network/safe-fetch.d.ts +7 -0
- package/dist/src/network/safe-fetch.js +199 -0
- package/dist/src/node-runtime.d.ts +3 -0
- package/dist/src/node-runtime.js +78 -0
- package/dist/src/profiles.d.ts +15 -0
- package/dist/src/profiles.js +160 -0
- package/dist/src/runtime-config.js +5 -6
- package/dist/src/search/tuning.d.ts +2 -0
- package/dist/src/search/tuning.js +2 -0
- package/dist/src/secure-files.d.ts +17 -0
- package/dist/src/secure-files.js +184 -0
- package/dist/src/status.js +12 -7
- package/dist/src/storage/sqlite.d.ts +4 -1
- package/dist/src/storage/sqlite.js +46 -3
- package/dist/src/type-guards.d.ts +1 -0
- package/dist/src/type-guards.js +3 -0
- package/dist/src/watcher/file-watcher.d.ts +3 -1
- package/dist/src/watcher/file-watcher.js +166 -32
- package/dist/src/windows-security.d.ts +4 -0
- package/dist/src/windows-security.js +47 -0
- package/docs/configuration.md +42 -10
- package/docs/daemon-profiles.md +302 -0
- package/docs/mcp-clients.md +266 -0
- package/docs/offline-mode.md +6 -6
- package/package.json +28 -2
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
import { randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { MAX_MCP_CONCURRENT_REQUESTS, MAX_MCP_INPUT_BYTES, MAX_MCP_OUTPUT_BYTES, MAX_MCP_OUTPUT_QUEUE_BYTES, MCP_SHUTDOWN_TIMEOUT_MS, McpProtocolError, McpProtocolSession, mcpErrorMessage, mcpRpcError, modernProtocolVersion, parseMcpRequest, validateModernRequestMetadata, } from "./protocol.js";
|
|
4
|
+
const MAX_HTTP_SESSIONS = 128;
|
|
5
|
+
const LEGACY_SESSION_IDLE_MS = 30 * 60 * 1_000;
|
|
6
|
+
const HTTP_REQUEST_TIMEOUT_MS = 30_000;
|
|
7
|
+
const HTTP_HEADERS_TIMEOUT_MS = 10_000;
|
|
8
|
+
const HTTP_KEEP_ALIVE_TIMEOUT_MS = 5_000;
|
|
9
|
+
class HttpRequestError extends Error {
|
|
10
|
+
status;
|
|
11
|
+
response;
|
|
12
|
+
constructor(status, code, message, data, id = null) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "HttpRequestError";
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.response = mcpRpcError(id, code, message, data);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function isLoopbackHost(host) {
|
|
20
|
+
return host === "127.0.0.1" || host === "::1" || host === "localhost";
|
|
21
|
+
}
|
|
22
|
+
function hostForUrl(host) {
|
|
23
|
+
return host.includes(":") ? `[${host}]` : host;
|
|
24
|
+
}
|
|
25
|
+
function headerValue(request, name) {
|
|
26
|
+
const value = request.headers[name];
|
|
27
|
+
return Array.isArray(value) ? value[0] : value;
|
|
28
|
+
}
|
|
29
|
+
function mediaTypes(value) {
|
|
30
|
+
return new Set((value ?? "")
|
|
31
|
+
.split(",")
|
|
32
|
+
.map((part) => part.split(";", 1)[0]?.trim().toLowerCase())
|
|
33
|
+
.filter((part) => Boolean(part)));
|
|
34
|
+
}
|
|
35
|
+
function secureTokenMatches(header, expected) {
|
|
36
|
+
if (!header?.startsWith("Bearer "))
|
|
37
|
+
return false;
|
|
38
|
+
const actual = Buffer.from(header.slice("Bearer ".length));
|
|
39
|
+
const target = Buffer.from(expected);
|
|
40
|
+
return actual.byteLength === target.byteLength && timingSafeEqual(actual, target);
|
|
41
|
+
}
|
|
42
|
+
function decodeMirroredHeader(value) {
|
|
43
|
+
const sentinel = /^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec(value);
|
|
44
|
+
if (!sentinel) {
|
|
45
|
+
if (!/^[\x20-\x7e]+$/.test(value) || value !== value.trim()) {
|
|
46
|
+
throw new HttpRequestError(400, -32020, "HeaderMismatch: invalid mirrored MCP header value");
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
const encoded = sentinel[1] ?? "";
|
|
51
|
+
const decoded = Buffer.from(encoded, "base64");
|
|
52
|
+
try {
|
|
53
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(decoded);
|
|
54
|
+
if (decoded.toString("base64") !== encoded || !text)
|
|
55
|
+
throw new Error("Invalid mirrored value");
|
|
56
|
+
return text;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
throw new HttpRequestError(400, -32020, "HeaderMismatch: invalid mirrored MCP base64 value");
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function writeSecurityHeaders(response) {
|
|
63
|
+
response.setHeader("Cache-Control", "no-store");
|
|
64
|
+
response.setHeader("X-Content-Type-Options", "nosniff");
|
|
65
|
+
}
|
|
66
|
+
function sendEmpty(response, status, headers = {}) {
|
|
67
|
+
if (response.headersSent || response.destroyed)
|
|
68
|
+
return;
|
|
69
|
+
writeSecurityHeaders(response);
|
|
70
|
+
response.writeHead(status, headers);
|
|
71
|
+
response.end();
|
|
72
|
+
}
|
|
73
|
+
function sendJson(response, status, value, headers = {}) {
|
|
74
|
+
if (response.headersSent || response.destroyed)
|
|
75
|
+
return;
|
|
76
|
+
let body = JSON.stringify(value);
|
|
77
|
+
if (Buffer.byteLength(body) > MAX_MCP_OUTPUT_BYTES) {
|
|
78
|
+
status = 500;
|
|
79
|
+
body = JSON.stringify(mcpRpcError(null, -32603, "MCP response exceeds the output frame limit"));
|
|
80
|
+
}
|
|
81
|
+
writeSecurityHeaders(response);
|
|
82
|
+
response.writeHead(status, {
|
|
83
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
84
|
+
"Content-Length": String(Buffer.byteLength(body)),
|
|
85
|
+
...headers,
|
|
86
|
+
});
|
|
87
|
+
response.end(body);
|
|
88
|
+
}
|
|
89
|
+
async function readJsonBody(request) {
|
|
90
|
+
const declared = headerValue(request, "content-length");
|
|
91
|
+
if (declared !== undefined) {
|
|
92
|
+
const length = Number(declared);
|
|
93
|
+
if (!Number.isSafeInteger(length) || length < 0)
|
|
94
|
+
throw new HttpRequestError(400, -32600, "Invalid Content-Length");
|
|
95
|
+
if (length > MAX_MCP_INPUT_BYTES)
|
|
96
|
+
throw new HttpRequestError(413, -32600, "MCP HTTP body exceeds the input limit");
|
|
97
|
+
}
|
|
98
|
+
const chunks = [];
|
|
99
|
+
let bytes = 0;
|
|
100
|
+
for await (const chunk of request) {
|
|
101
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
102
|
+
bytes += buffer.byteLength;
|
|
103
|
+
if (bytes > MAX_MCP_INPUT_BYTES) {
|
|
104
|
+
request.resume();
|
|
105
|
+
throw new HttpRequestError(413, -32600, "MCP HTTP body exceeds the input limit");
|
|
106
|
+
}
|
|
107
|
+
chunks.push(buffer);
|
|
108
|
+
}
|
|
109
|
+
if (bytes === 0)
|
|
110
|
+
throw new HttpRequestError(400, -32700, "MCP HTTP body is empty");
|
|
111
|
+
try {
|
|
112
|
+
return JSON.parse(Buffer.concat(chunks, bytes).toString("utf8"));
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
throw new HttpRequestError(400, -32700, "Invalid JSON request body");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
class SseSink {
|
|
119
|
+
chain = Promise.resolve();
|
|
120
|
+
queuedBytes = 0;
|
|
121
|
+
failed;
|
|
122
|
+
response;
|
|
123
|
+
constructor(response) {
|
|
124
|
+
this.response = response;
|
|
125
|
+
response.on("error", (error) => {
|
|
126
|
+
this.failed ??= error;
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
start() {
|
|
130
|
+
writeSecurityHeaders(this.response);
|
|
131
|
+
this.response.writeHead(200, {
|
|
132
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
133
|
+
"X-Accel-Buffering": "no",
|
|
134
|
+
Connection: "keep-alive",
|
|
135
|
+
});
|
|
136
|
+
this.response.flushHeaders();
|
|
137
|
+
}
|
|
138
|
+
writeEvent(event) {
|
|
139
|
+
if (this.failed)
|
|
140
|
+
return Promise.reject(this.failed);
|
|
141
|
+
if (this.response.destroyed || this.response.writableEnded) {
|
|
142
|
+
return Promise.reject(new Error("MCP HTTP response stream is closed"));
|
|
143
|
+
}
|
|
144
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
145
|
+
let settled = false;
|
|
146
|
+
const finish = (error) => {
|
|
147
|
+
if (settled)
|
|
148
|
+
return;
|
|
149
|
+
settled = true;
|
|
150
|
+
this.response.off("drain", onDrain);
|
|
151
|
+
this.response.off("error", onError);
|
|
152
|
+
this.response.off("close", onClose);
|
|
153
|
+
if (error)
|
|
154
|
+
reject(error);
|
|
155
|
+
else
|
|
156
|
+
resolve();
|
|
157
|
+
};
|
|
158
|
+
const onDrain = () => finish();
|
|
159
|
+
const onError = (error) => finish(error);
|
|
160
|
+
const onClose = () => finish(new Error("MCP HTTP response stream closed before draining"));
|
|
161
|
+
this.response.once("error", onError);
|
|
162
|
+
this.response.once("close", onClose);
|
|
163
|
+
if (this.response.write(event))
|
|
164
|
+
finish();
|
|
165
|
+
else
|
|
166
|
+
this.response.once("drain", onDrain);
|
|
167
|
+
return promise;
|
|
168
|
+
}
|
|
169
|
+
send(message) {
|
|
170
|
+
const event = `data: ${JSON.stringify(message)}\n\n`;
|
|
171
|
+
const bytes = Buffer.byteLength(event);
|
|
172
|
+
if (bytes > MAX_MCP_OUTPUT_BYTES)
|
|
173
|
+
return Promise.reject(new Error("MCP SSE event exceeds the output frame limit"));
|
|
174
|
+
if (this.failed)
|
|
175
|
+
return Promise.reject(this.failed);
|
|
176
|
+
if (this.queuedBytes + bytes > MAX_MCP_OUTPUT_QUEUE_BYTES) {
|
|
177
|
+
this.failed = new Error("MCP SSE output queue is full");
|
|
178
|
+
return Promise.reject(this.failed);
|
|
179
|
+
}
|
|
180
|
+
this.queuedBytes += bytes;
|
|
181
|
+
const write = this.chain.then(() => this.writeEvent(event));
|
|
182
|
+
this.chain = write
|
|
183
|
+
.catch((error) => {
|
|
184
|
+
this.failed ??= error instanceof Error ? error : new Error(String(error));
|
|
185
|
+
})
|
|
186
|
+
.finally(() => {
|
|
187
|
+
this.queuedBytes -= bytes;
|
|
188
|
+
});
|
|
189
|
+
return write;
|
|
190
|
+
}
|
|
191
|
+
async finish() {
|
|
192
|
+
await this.chain;
|
|
193
|
+
if (this.failed)
|
|
194
|
+
throw this.failed;
|
|
195
|
+
if (!this.response.destroyed && !this.response.writableEnded)
|
|
196
|
+
this.response.end();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
export class McpHttpServer {
|
|
200
|
+
options;
|
|
201
|
+
server;
|
|
202
|
+
sessions = new Map();
|
|
203
|
+
requestSessions = new Set();
|
|
204
|
+
operations = new Set();
|
|
205
|
+
activeRequests = 0;
|
|
206
|
+
accepting = false;
|
|
207
|
+
started = false;
|
|
208
|
+
closePromise;
|
|
209
|
+
startWaiter;
|
|
210
|
+
addressValue;
|
|
211
|
+
closedPromise;
|
|
212
|
+
resolveClosed;
|
|
213
|
+
rejectClosed;
|
|
214
|
+
constructor(options) {
|
|
215
|
+
if (!isLoopbackHost(options.host))
|
|
216
|
+
throw new Error("MCP HTTP host must be 127.0.0.1, ::1, or localhost");
|
|
217
|
+
if (!Number.isSafeInteger(options.port) || options.port < 0 || options.port > 65_535) {
|
|
218
|
+
throw new Error("MCP HTTP port must be an integer from 0 to 65535");
|
|
219
|
+
}
|
|
220
|
+
if (!options.endpoint.startsWith("/") || options.endpoint.startsWith("//") || /[?#\s]/.test(options.endpoint)) {
|
|
221
|
+
throw new Error("MCP HTTP endpoint must be one absolute path without query or fragment");
|
|
222
|
+
}
|
|
223
|
+
if (!/^[\x21-\x7e]{32,512}$/.test(options.authToken)) {
|
|
224
|
+
throw new Error("PI_KNOWLEDGE_MCP_HTTP_TOKEN must contain 32-512 visible ASCII characters");
|
|
225
|
+
}
|
|
226
|
+
this.options = options;
|
|
227
|
+
const closed = Promise.withResolvers();
|
|
228
|
+
this.closedPromise = closed.promise;
|
|
229
|
+
this.resolveClosed = closed.resolve;
|
|
230
|
+
this.rejectClosed = closed.reject;
|
|
231
|
+
this.server = createServer((request, response) => {
|
|
232
|
+
const operation = this.handleHttpRequest(request, response).catch((error) => {
|
|
233
|
+
this.options.onError?.(error);
|
|
234
|
+
if (!response.headersSent)
|
|
235
|
+
sendJson(response, 500, mcpRpcError(null, -32603, "Internal MCP server error"));
|
|
236
|
+
else if (!response.destroyed)
|
|
237
|
+
response.destroy();
|
|
238
|
+
});
|
|
239
|
+
this.operations.add(operation);
|
|
240
|
+
void operation.finally(() => this.operations.delete(operation));
|
|
241
|
+
});
|
|
242
|
+
this.server.maxConnections = 64;
|
|
243
|
+
this.server.requestTimeout = HTTP_REQUEST_TIMEOUT_MS;
|
|
244
|
+
this.server.headersTimeout = HTTP_HEADERS_TIMEOUT_MS;
|
|
245
|
+
this.server.keepAliveTimeout = HTTP_KEEP_ALIVE_TIMEOUT_MS;
|
|
246
|
+
this.server.on("close", () => this.resolveClosed());
|
|
247
|
+
this.server.on("error", (error) => {
|
|
248
|
+
if (this.accepting)
|
|
249
|
+
this.rejectClosed(error);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
get address() {
|
|
253
|
+
return this.addressValue;
|
|
254
|
+
}
|
|
255
|
+
serverOptions() {
|
|
256
|
+
return {
|
|
257
|
+
profile: this.options.profile,
|
|
258
|
+
client: this.options.client,
|
|
259
|
+
tools: this.options.tools,
|
|
260
|
+
serverVersion: this.options.serverVersion,
|
|
261
|
+
allowRoots: this.options.allowRoots,
|
|
262
|
+
allowNetwork: this.options.allowNetwork,
|
|
263
|
+
allowWrite: this.options.allowWrite,
|
|
264
|
+
allowAdmin: this.options.allowAdmin,
|
|
265
|
+
onError: this.options.onError,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
pruneSessions(now = Date.now()) {
|
|
269
|
+
for (const [id, entry] of this.sessions) {
|
|
270
|
+
if (entry.session.activeRequestCount === 0 && now - entry.lastUsed > LEGACY_SESSION_IDLE_MS) {
|
|
271
|
+
entry.session.abortAll();
|
|
272
|
+
this.sessions.delete(id);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
validateOrigin(request) {
|
|
277
|
+
const origin = headerValue(request, "origin");
|
|
278
|
+
if (!origin)
|
|
279
|
+
return;
|
|
280
|
+
const ownOrigin = this.addressValue ? new URL(this.addressValue.url).origin : undefined;
|
|
281
|
+
if (origin !== ownOrigin && !this.options.allowedOrigins.includes(origin)) {
|
|
282
|
+
throw new HttpRequestError(403, -32600, "Forbidden Origin header");
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
validateCommonPostHeaders(request) {
|
|
286
|
+
const contentType = mediaTypes(headerValue(request, "content-type"));
|
|
287
|
+
if (!contentType.has("application/json")) {
|
|
288
|
+
throw new HttpRequestError(415, -32600, "Content-Type must be application/json");
|
|
289
|
+
}
|
|
290
|
+
const accept = mediaTypes(headerValue(request, "accept"));
|
|
291
|
+
if (!accept.has("application/json") || !accept.has("text/event-stream")) {
|
|
292
|
+
throw new HttpRequestError(406, -32600, "Accept must include application/json and text/event-stream");
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
validateModernHeaders(request, rpc) {
|
|
296
|
+
try {
|
|
297
|
+
validateModernRequestMetadata(rpc.params ?? {});
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
if (!(error instanceof McpProtocolError))
|
|
301
|
+
throw error;
|
|
302
|
+
throw new HttpRequestError(error.httpStatus ?? 400, error.code, error.message, error.data, rpc.id ?? null);
|
|
303
|
+
}
|
|
304
|
+
const version = modernProtocolVersion(rpc);
|
|
305
|
+
const protocolHeader = headerValue(request, "mcp-protocol-version");
|
|
306
|
+
if (protocolHeader === undefined || decodeMirroredHeader(protocolHeader) !== version) {
|
|
307
|
+
throw new HttpRequestError(400, -32020, "HeaderMismatch: MCP-Protocol-Version does not match request metadata", undefined, rpc.id ?? null);
|
|
308
|
+
}
|
|
309
|
+
const methodHeader = headerValue(request, "mcp-method");
|
|
310
|
+
if (methodHeader === undefined || decodeMirroredHeader(methodHeader) !== rpc.method) {
|
|
311
|
+
throw new HttpRequestError(400, -32020, "HeaderMismatch: Mcp-Method does not match request method", undefined, rpc.id ?? null);
|
|
312
|
+
}
|
|
313
|
+
if (rpc.method === "tools/call") {
|
|
314
|
+
const bodyName = rpc.params?.name;
|
|
315
|
+
const nameHeader = headerValue(request, "mcp-name");
|
|
316
|
+
if (typeof bodyName !== "string" || nameHeader === undefined || decodeMirroredHeader(nameHeader) !== bodyName) {
|
|
317
|
+
throw new HttpRequestError(400, -32020, "HeaderMismatch: Mcp-Name does not match tool name", undefined, rpc.id ?? null);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
validateLegacyVersion(request, entry) {
|
|
322
|
+
const header = headerValue(request, "mcp-protocol-version");
|
|
323
|
+
if (header !== entry.session.legacyProtocolVersion) {
|
|
324
|
+
throw new HttpRequestError(400, -32600, "MCP-Protocol-Version does not match the legacy session");
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
async executeProtocolRequest(response, rpc, session, modern) {
|
|
328
|
+
const stream = rpc.id !== undefined && rpc.method === "tools/call";
|
|
329
|
+
if (!stream)
|
|
330
|
+
return session.handleRequest(rpc, async () => undefined);
|
|
331
|
+
const abortController = new AbortController();
|
|
332
|
+
let completed = false;
|
|
333
|
+
const onClose = () => {
|
|
334
|
+
if (!completed && modern)
|
|
335
|
+
abortController.abort();
|
|
336
|
+
};
|
|
337
|
+
response.once("close", onClose);
|
|
338
|
+
const sink = new SseSink(response);
|
|
339
|
+
sink.start();
|
|
340
|
+
try {
|
|
341
|
+
const handled = await session.handleRequest(rpc, (message) => sink.send(message), abortController.signal);
|
|
342
|
+
if (handled.response)
|
|
343
|
+
await sink.send(handled.response);
|
|
344
|
+
completed = true;
|
|
345
|
+
await sink.finish();
|
|
346
|
+
return handled;
|
|
347
|
+
}
|
|
348
|
+
finally {
|
|
349
|
+
response.off("close", onClose);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
async initializeLegacy(response, rpc) {
|
|
353
|
+
this.pruneSessions();
|
|
354
|
+
if (this.sessions.size >= MAX_HTTP_SESSIONS) {
|
|
355
|
+
throw new HttpRequestError(503, -32603, "MCP HTTP legacy session limit reached");
|
|
356
|
+
}
|
|
357
|
+
const session = new McpProtocolSession(this.serverOptions());
|
|
358
|
+
const handled = await session.handleRequest(rpc, async () => undefined);
|
|
359
|
+
if (!handled.response || !session.legacyProtocolVersion) {
|
|
360
|
+
sendJson(response, handled.httpStatus ?? 400, handled.response ?? mcpRpcError(rpc.id ?? null, -32602, "Invalid initialize request"));
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
const id = randomUUID();
|
|
364
|
+
this.sessions.set(id, { session, lastUsed: Date.now() });
|
|
365
|
+
sendJson(response, 200, handled.response, {
|
|
366
|
+
"Mcp-Session-Id": id,
|
|
367
|
+
"MCP-Protocol-Version": session.legacyProtocolVersion,
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
async handlePost(request, response) {
|
|
371
|
+
this.validateCommonPostHeaders(request);
|
|
372
|
+
const value = await readJsonBody(request);
|
|
373
|
+
let rpc;
|
|
374
|
+
try {
|
|
375
|
+
rpc = parseMcpRequest(value);
|
|
376
|
+
}
|
|
377
|
+
catch (error) {
|
|
378
|
+
const protocol = error instanceof McpProtocolError ? error : undefined;
|
|
379
|
+
throw new HttpRequestError(protocol?.httpStatus ?? 400, protocol?.code ?? -32600, mcpErrorMessage(error));
|
|
380
|
+
}
|
|
381
|
+
const sessionId = headerValue(request, "mcp-session-id");
|
|
382
|
+
if (rpc.method === "initialize") {
|
|
383
|
+
if (sessionId)
|
|
384
|
+
throw new HttpRequestError(400, -32600, "Initialize must not include MCP-Session-Id", undefined, rpc.id ?? null);
|
|
385
|
+
await this.initializeLegacy(response, rpc);
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
let session;
|
|
389
|
+
let modern = false;
|
|
390
|
+
let legacyEntry;
|
|
391
|
+
if (sessionId) {
|
|
392
|
+
const entry = this.sessions.get(sessionId);
|
|
393
|
+
if (!entry)
|
|
394
|
+
throw new HttpRequestError(404, -32600, "Unknown or expired MCP-Session-Id", undefined, rpc.id ?? null);
|
|
395
|
+
this.validateLegacyVersion(request, entry);
|
|
396
|
+
entry.lastUsed = Date.now();
|
|
397
|
+
legacyEntry = entry;
|
|
398
|
+
session = entry.session;
|
|
399
|
+
}
|
|
400
|
+
else {
|
|
401
|
+
this.validateModernHeaders(request, rpc);
|
|
402
|
+
modern = true;
|
|
403
|
+
session = new McpProtocolSession(this.serverOptions());
|
|
404
|
+
this.requestSessions.add(session);
|
|
405
|
+
}
|
|
406
|
+
try {
|
|
407
|
+
const handled = await this.executeProtocolRequest(response, rpc, session, modern);
|
|
408
|
+
if (response.headersSent)
|
|
409
|
+
return;
|
|
410
|
+
if (!handled.response) {
|
|
411
|
+
sendEmpty(response, 202);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
sendJson(response, handled.httpStatus ?? 200, handled.response);
|
|
415
|
+
}
|
|
416
|
+
finally {
|
|
417
|
+
if (legacyEntry)
|
|
418
|
+
legacyEntry.lastUsed = Date.now();
|
|
419
|
+
if (modern) {
|
|
420
|
+
session.abortAll();
|
|
421
|
+
this.requestSessions.delete(session);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
deleteLegacySession(request, response) {
|
|
426
|
+
const sessionId = headerValue(request, "mcp-session-id");
|
|
427
|
+
if (!sessionId)
|
|
428
|
+
throw new HttpRequestError(400, -32600, "MCP-Session-Id is required for DELETE");
|
|
429
|
+
const entry = this.sessions.get(sessionId);
|
|
430
|
+
if (!entry)
|
|
431
|
+
throw new HttpRequestError(404, -32600, "Unknown or expired MCP-Session-Id");
|
|
432
|
+
this.validateLegacyVersion(request, entry);
|
|
433
|
+
entry.session.abortAll();
|
|
434
|
+
this.sessions.delete(sessionId);
|
|
435
|
+
sendEmpty(response, 204);
|
|
436
|
+
}
|
|
437
|
+
async handleHttpRequest(request, response) {
|
|
438
|
+
try {
|
|
439
|
+
if (!this.accepting)
|
|
440
|
+
throw new HttpRequestError(503, -32603, "MCP HTTP server is not accepting requests");
|
|
441
|
+
if (request.url !== this.options.endpoint)
|
|
442
|
+
throw new HttpRequestError(404, -32601, "MCP endpoint not found");
|
|
443
|
+
this.validateOrigin(request);
|
|
444
|
+
if (!secureTokenMatches(headerValue(request, "authorization"), this.options.authToken)) {
|
|
445
|
+
writeSecurityHeaders(response);
|
|
446
|
+
response.setHeader("WWW-Authenticate", 'Bearer realm="pi-knowledge-mcp"');
|
|
447
|
+
throw new HttpRequestError(401, -32600, "Bearer authentication required");
|
|
448
|
+
}
|
|
449
|
+
if (this.activeRequests >= MAX_MCP_CONCURRENT_REQUESTS) {
|
|
450
|
+
response.setHeader("Retry-After", "1");
|
|
451
|
+
throw new HttpRequestError(429, -32603, "MCP HTTP request limit reached");
|
|
452
|
+
}
|
|
453
|
+
this.activeRequests++;
|
|
454
|
+
try {
|
|
455
|
+
if (request.method === "POST")
|
|
456
|
+
await this.handlePost(request, response);
|
|
457
|
+
else if (request.method === "DELETE")
|
|
458
|
+
this.deleteLegacySession(request, response);
|
|
459
|
+
else {
|
|
460
|
+
response.setHeader("Allow", "POST, DELETE");
|
|
461
|
+
throw new HttpRequestError(405, -32601, "Method not allowed");
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
finally {
|
|
465
|
+
this.activeRequests--;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
catch (error) {
|
|
469
|
+
if (response.headersSent) {
|
|
470
|
+
if (!response.destroyed && !response.writableEnded)
|
|
471
|
+
response.destroy();
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
if (error instanceof HttpRequestError)
|
|
475
|
+
sendJson(response, error.status, error.response);
|
|
476
|
+
else
|
|
477
|
+
throw error;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
async start() {
|
|
481
|
+
if (this.started)
|
|
482
|
+
throw new Error("MCP HTTP server is already started");
|
|
483
|
+
if (this.closePromise)
|
|
484
|
+
throw new Error("MCP HTTP server is closing");
|
|
485
|
+
this.started = true;
|
|
486
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
487
|
+
const onError = (error) => reject(error);
|
|
488
|
+
this.server.once("error", onError);
|
|
489
|
+
this.startWaiter = promise;
|
|
490
|
+
this.server.listen(this.options.port, this.options.host, () => resolve());
|
|
491
|
+
try {
|
|
492
|
+
await promise;
|
|
493
|
+
}
|
|
494
|
+
catch (error) {
|
|
495
|
+
this.started = false;
|
|
496
|
+
throw error;
|
|
497
|
+
}
|
|
498
|
+
finally {
|
|
499
|
+
this.server.off("error", onError);
|
|
500
|
+
}
|
|
501
|
+
if (this.closePromise)
|
|
502
|
+
throw new Error("MCP HTTP server closed during startup");
|
|
503
|
+
const address = this.server.address();
|
|
504
|
+
if (!address || typeof address === "string")
|
|
505
|
+
throw new Error("MCP HTTP server did not publish a TCP address");
|
|
506
|
+
const port = address.port;
|
|
507
|
+
this.addressValue = {
|
|
508
|
+
host: this.options.host,
|
|
509
|
+
port,
|
|
510
|
+
endpoint: this.options.endpoint,
|
|
511
|
+
url: `http://${hostForUrl(this.options.host)}:${port}${this.options.endpoint}`,
|
|
512
|
+
};
|
|
513
|
+
this.accepting = true;
|
|
514
|
+
return this.addressValue;
|
|
515
|
+
}
|
|
516
|
+
waitUntilClosed() {
|
|
517
|
+
return this.closedPromise;
|
|
518
|
+
}
|
|
519
|
+
async closeInternal() {
|
|
520
|
+
for (const entry of this.sessions.values())
|
|
521
|
+
entry.session.abortAll();
|
|
522
|
+
for (const session of this.requestSessions)
|
|
523
|
+
session.abortAll();
|
|
524
|
+
this.sessions.clear();
|
|
525
|
+
await this.startWaiter?.catch(() => { });
|
|
526
|
+
if (!this.started || !this.server.listening) {
|
|
527
|
+
this.resolveClosed();
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
const serverClosed = new Promise((resolve) => {
|
|
531
|
+
this.server.close(() => resolve());
|
|
532
|
+
});
|
|
533
|
+
let timer;
|
|
534
|
+
const timeout = new Promise((resolve) => {
|
|
535
|
+
timer = setTimeout(() => resolve(false), MCP_SHUTDOWN_TIMEOUT_MS);
|
|
536
|
+
timer.unref();
|
|
537
|
+
});
|
|
538
|
+
const closed = await Promise.race([serverClosed.then(() => true), timeout]);
|
|
539
|
+
if (timer)
|
|
540
|
+
clearTimeout(timer);
|
|
541
|
+
if (!closed) {
|
|
542
|
+
this.server.closeAllConnections();
|
|
543
|
+
await serverClosed;
|
|
544
|
+
}
|
|
545
|
+
const operations = Promise.allSettled([...this.operations]);
|
|
546
|
+
let operationTimer;
|
|
547
|
+
const operationTimeout = new Promise((resolve) => {
|
|
548
|
+
operationTimer = setTimeout(resolve, MCP_SHUTDOWN_TIMEOUT_MS);
|
|
549
|
+
operationTimer.unref();
|
|
550
|
+
});
|
|
551
|
+
await Promise.race([operations, operationTimeout]);
|
|
552
|
+
if (operationTimer)
|
|
553
|
+
clearTimeout(operationTimer);
|
|
554
|
+
}
|
|
555
|
+
close() {
|
|
556
|
+
if (this.closePromise)
|
|
557
|
+
return this.closePromise;
|
|
558
|
+
this.accepting = false;
|
|
559
|
+
const closing = Promise.withResolvers();
|
|
560
|
+
this.closePromise = closing.promise;
|
|
561
|
+
void this.closeInternal().then(closing.resolve, closing.reject);
|
|
562
|
+
return this.closePromise;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
3
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
4
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
5
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
return path;
|
|
9
|
+
};
|
|
10
|
+
import { ensureDaemonClient } from "../daemon/client.js";
|
|
11
|
+
import { packageVersion } from "../daemon/protocol.js";
|
|
12
|
+
import { resolveKnowledgeProfile } from "../profiles.js";
|
|
13
|
+
import { McpHttpServer } from "./http.js";
|
|
14
|
+
import { canonicalizeAllowedRoots, McpStdioAdapter, parseMcpArguments } from "./server.js";
|
|
15
|
+
async function run() {
|
|
16
|
+
const cli = parseMcpArguments(process.argv.slice(2));
|
|
17
|
+
if (cli.profileName)
|
|
18
|
+
process.env.PI_KNOWLEDGE_PROFILE = cli.profileName;
|
|
19
|
+
const profile = resolveKnowledgeProfile(cli.profileName);
|
|
20
|
+
const authToken = cli.transport === "http" ? process.env.PI_KNOWLEDGE_MCP_HTTP_TOKEN : undefined;
|
|
21
|
+
if (cli.transport === "http" && authToken === undefined) {
|
|
22
|
+
throw new Error("PI_KNOWLEDGE_MCP_HTTP_TOKEN is required for --transport http");
|
|
23
|
+
}
|
|
24
|
+
const allowRoots = canonicalizeAllowedRoots(cli.allowRoots);
|
|
25
|
+
const client = await ensureDaemonClient(profile);
|
|
26
|
+
const extensionUrl = new URL(import.meta.url.endsWith(".ts") ? "../../index.ts" : "../../index.js", import.meta.url);
|
|
27
|
+
const { getKnowledgeToolDefinitions } = await import(__rewriteRelativeImportExtension(extensionUrl.href));
|
|
28
|
+
const tools = getKnowledgeToolDefinitions();
|
|
29
|
+
if (cli.transport === "stdio") {
|
|
30
|
+
const adapter = new McpStdioAdapter({
|
|
31
|
+
...cli,
|
|
32
|
+
allowRoots,
|
|
33
|
+
profile,
|
|
34
|
+
client,
|
|
35
|
+
tools,
|
|
36
|
+
input: process.stdin,
|
|
37
|
+
output: process.stdout,
|
|
38
|
+
error: process.stderr,
|
|
39
|
+
serverVersion: packageVersion(),
|
|
40
|
+
});
|
|
41
|
+
const stop = () => {
|
|
42
|
+
process.stdin.destroy();
|
|
43
|
+
};
|
|
44
|
+
process.once("SIGINT", stop);
|
|
45
|
+
process.once("SIGTERM", stop);
|
|
46
|
+
try {
|
|
47
|
+
await adapter.run();
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
process.off("SIGINT", stop);
|
|
51
|
+
process.off("SIGTERM", stop);
|
|
52
|
+
}
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (authToken === undefined) {
|
|
56
|
+
throw new Error("PI_KNOWLEDGE_MCP_HTTP_TOKEN is required for --transport http");
|
|
57
|
+
}
|
|
58
|
+
const server = new McpHttpServer({
|
|
59
|
+
profile,
|
|
60
|
+
client,
|
|
61
|
+
tools,
|
|
62
|
+
serverVersion: packageVersion(),
|
|
63
|
+
allowRoots,
|
|
64
|
+
allowNetwork: cli.allowNetwork,
|
|
65
|
+
allowWrite: cli.allowWrite,
|
|
66
|
+
allowAdmin: cli.allowAdmin,
|
|
67
|
+
host: cli.httpHost,
|
|
68
|
+
port: cli.httpPort,
|
|
69
|
+
endpoint: cli.httpEndpoint,
|
|
70
|
+
allowedOrigins: cli.allowOrigins,
|
|
71
|
+
authToken,
|
|
72
|
+
});
|
|
73
|
+
const stop = () => {
|
|
74
|
+
void server.close().catch((error) => {
|
|
75
|
+
process.stderr.write(`MCP HTTP shutdown failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
process.once("SIGINT", stop);
|
|
79
|
+
process.once("SIGTERM", stop);
|
|
80
|
+
try {
|
|
81
|
+
const address = await server.start();
|
|
82
|
+
process.stderr.write(`pi-knowledge MCP HTTP listening at ${address.url}\n`);
|
|
83
|
+
await server.waitUntilClosed();
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
process.off("SIGINT", stop);
|
|
87
|
+
process.off("SIGTERM", stop);
|
|
88
|
+
await server.close();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
await run();
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
96
|
+
process.exitCode = 1;
|
|
97
|
+
}
|