@introspection-ai/recipes 0.50.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/api/api-bindings.d.ts +3 -0
- package/dist/api/api-bindings.d.ts.map +1 -0
- package/dist/api/api-bindings.js +2 -0
- package/dist/api/api-bindings.js.map +1 -0
- package/dist/api/session.d.ts +1 -0
- package/dist/api/session.d.ts.map +1 -1
- package/dist/api-bindings.d.ts +101 -0
- package/dist/api-bindings.d.ts.map +1 -0
- package/dist/api-bindings.js +406 -0
- package/dist/api-bindings.js.map +1 -0
- package/dist/channels/arguments.d.ts +116 -0
- package/dist/channels/arguments.d.ts.map +1 -0
- package/dist/channels/arguments.generated.d.ts +15 -0
- package/dist/channels/arguments.generated.d.ts.map +1 -0
- package/dist/channels/arguments.generated.js +181 -0
- package/dist/channels/arguments.generated.js.map +1 -0
- package/dist/channels/arguments.js +8 -0
- package/dist/channels/arguments.js.map +1 -0
- package/dist/channels/module.d.ts +5 -0
- package/dist/channels/module.d.ts.map +1 -1
- package/dist/channels/module.js +10 -5
- package/dist/channels/module.js.map +1 -1
- package/dist/channels/tools.d.ts.map +1 -1
- package/dist/channels/tools.js +22 -59
- package/dist/channels/tools.js.map +1 -1
- package/dist/channels/types.d.ts +5 -0
- package/dist/channels/types.d.ts.map +1 -1
- package/dist/child/session.d.ts +5 -0
- package/dist/child/session.d.ts.map +1 -1
- package/dist/child/session.js +2 -0
- package/dist/child/session.js.map +1 -1
- package/dist/clock.d.ts +80 -0
- package/dist/clock.d.ts.map +1 -0
- package/dist/clock.js +169 -0
- package/dist/clock.js.map +1 -0
- package/dist/command-parameters.d.ts +37 -5
- package/dist/command-parameters.d.ts.map +1 -1
- package/dist/command-parameters.js +73 -11
- package/dist/command-parameters.js.map +1 -1
- package/dist/connector-tools.d.ts +18 -0
- package/dist/connector-tools.d.ts.map +1 -1
- package/dist/connector-tools.js +49 -6
- package/dist/connector-tools.js.map +1 -1
- package/dist/documents/module.d.ts.map +1 -1
- package/dist/documents/module.js +1 -3
- package/dist/documents/module.js.map +1 -1
- package/dist/documents/tools.d.ts.map +1 -1
- package/dist/documents/tools.js +3 -3
- package/dist/documents/tools.js.map +1 -1
- package/dist/egress.d.ts +23 -0
- package/dist/egress.d.ts.map +1 -0
- package/dist/egress.js +36 -0
- package/dist/egress.js.map +1 -0
- package/dist/issues/index.d.ts +7 -0
- package/dist/issues/index.d.ts.map +1 -0
- package/dist/issues/index.js +4 -0
- package/dist/issues/index.js.map +1 -0
- package/dist/issues/module.d.ts +38 -0
- package/dist/issues/module.d.ts.map +1 -0
- package/dist/issues/module.js +114 -0
- package/dist/issues/module.js.map +1 -0
- package/dist/issues/tool.d.ts +95 -0
- package/dist/issues/tool.d.ts.map +1 -0
- package/dist/issues/tool.js +479 -0
- package/dist/issues/tool.js.map +1 -0
- package/dist/issues/types.d.ts +280 -0
- package/dist/issues/types.d.ts.map +1 -0
- package/dist/issues/types.js +79 -0
- package/dist/issues/types.js.map +1 -0
- package/dist/mcp/cli/command-context.d.ts +20 -1
- package/dist/mcp/cli/command-context.d.ts.map +1 -1
- package/dist/mcp/cli/command-context.js.map +1 -1
- package/dist/mcp/cli/core.d.ts +0 -2
- package/dist/mcp/cli/core.d.ts.map +1 -1
- package/dist/mcp/cli/core.js +9 -33
- package/dist/mcp/cli/core.js.map +1 -1
- package/dist/mcp/cli/handshake-retry.d.ts +5 -0
- package/dist/mcp/cli/handshake-retry.d.ts.map +1 -0
- package/dist/mcp/cli/handshake-retry.js +32 -0
- package/dist/mcp/cli/handshake-retry.js.map +1 -0
- package/dist/mcp/daemon/index.js +3 -4
- package/dist/mcp/daemon/index.js.map +1 -1
- package/dist/mcp/pi-client.d.ts +2 -0
- package/dist/mcp/pi-client.d.ts.map +1 -1
- package/dist/mcp/pi-client.js +5 -1
- package/dist/mcp/pi-client.js.map +1 -1
- package/dist/mcp/pi-mcp-runtime.d.ts +25 -0
- package/dist/mcp/pi-mcp-runtime.d.ts.map +1 -0
- package/dist/mcp/pi-mcp-runtime.js +215 -0
- package/dist/mcp/pi-mcp-runtime.js.map +1 -0
- package/dist/mcp/pi-runtime.d.ts +7 -0
- package/dist/mcp/pi-runtime.d.ts.map +1 -0
- package/dist/mcp/pi-runtime.js +26 -0
- package/dist/mcp/pi-runtime.js.map +1 -0
- package/dist/mcp-chunks/chunk-3UVHZECT.js +31 -0
- package/dist/mcp-chunks/{chunk-PO2SOBEN.js → chunk-CGJ2XOSF.js} +43 -35
- package/dist/mcp-chunks/{chunk-GTETFUPQ.js → chunk-IMG2JMBS.js} +8 -8
- package/dist/mcp-chunks/{chunk-UFV6SVQG.js → chunk-LQKMNWDE.js} +2 -2
- package/dist/mcp-chunks/{chunk-S2F7DDP5.js → chunk-QUDOU7MQ.js} +1 -1
- package/dist/mcp-chunks/{cli-IYD7Y7MO.js → cli-BM23ZXPJ.js} +54 -54
- package/dist/mcp-chunks/{client-5MNBV3Z7.js → client-RKTAKDAY.js} +7 -7
- package/dist/mcp-chunks/{daemon-command-V3B3EMXD.js → daemon-command-VU6WTFCJ.js} +8 -8
- package/dist/mcp-chunks/{generate-cli-runner-PW5WJ7KI.js → generate-cli-runner-JAAPSWGX.js} +12 -12
- package/dist/mcp-chunks/{generated-daemon-runtime-3C4NWGAU.js → generated-daemon-runtime-LX4L2X7Z.js} +8 -8
- package/dist/mcp-chunks/pi-mcp-runtime-GHDEPXUL.js +1231 -0
- package/dist/mcp-chunks/{runtime-RMI3XCYJ.js → runtime-T63YI7TC.js} +6 -6
- package/dist/mcp-chunks/{serve-command-UF5SVREV.js → serve-command-75P4VBJ6.js} +7 -7
- package/dist/mcp-daemon.js +21 -19
- package/dist/mcp-run-worker.js +11 -10
- package/dist/pi-extension.d.ts +3 -0
- package/dist/pi-extension.d.ts.map +1 -1
- package/dist/pi-extension.js +82 -18
- package/dist/pi-extension.js.map +1 -1
- package/dist/productivity/arguments.d.ts +298 -0
- package/dist/productivity/arguments.d.ts.map +1 -0
- package/dist/productivity/arguments.generated.d.ts +28 -0
- package/dist/productivity/arguments.generated.d.ts.map +1 -0
- package/dist/productivity/arguments.generated.js +489 -0
- package/dist/productivity/arguments.generated.js.map +1 -0
- package/dist/productivity/arguments.js +10 -0
- package/dist/productivity/arguments.js.map +1 -0
- package/dist/productivity/http.d.ts.map +1 -1
- package/dist/productivity/http.js +12 -22
- package/dist/productivity/http.js.map +1 -1
- package/dist/productivity/index.d.ts +1 -1
- package/dist/productivity/index.d.ts.map +1 -1
- package/dist/productivity/index.js +1 -1
- package/dist/productivity/index.js.map +1 -1
- package/dist/productivity/module.d.ts +15 -2
- package/dist/productivity/module.d.ts.map +1 -1
- package/dist/productivity/module.js +24 -21
- package/dist/productivity/module.js.map +1 -1
- package/dist/productivity/tools.d.ts +6 -0
- package/dist/productivity/tools.d.ts.map +1 -1
- package/dist/productivity/tools.js +64 -224
- package/dist/productivity/tools.js.map +1 -1
- package/dist/productivity/types.d.ts +2 -0
- package/dist/productivity/types.d.ts.map +1 -1
- package/dist/productivity/types.js.map +1 -1
- package/dist/recipe/agent.d.ts +40 -10
- package/dist/recipe/agent.d.ts.map +1 -1
- package/dist/recipe/agent.js +209 -30
- package/dist/recipe/agent.js.map +1 -1
- package/dist/recipe/companions.d.ts +2 -1
- package/dist/recipe/companions.d.ts.map +1 -1
- package/dist/recipe/companions.js +11 -9
- package/dist/recipe/companions.js.map +1 -1
- package/dist/recipe/manifest.generated.d.ts +4 -1
- package/dist/recipe/manifest.generated.d.ts.map +1 -1
- package/dist/recipe/manifest.generated.js +5 -2
- package/dist/recipe/manifest.generated.js.map +1 -1
- package/dist/recipe/package.d.ts +28 -3
- package/dist/recipe/package.d.ts.map +1 -1
- package/dist/recipe/package.js +155 -1
- package/dist/recipe/package.js.map +1 -1
- package/dist/recipe/providers.d.ts +62 -0
- package/dist/recipe/providers.d.ts.map +1 -0
- package/dist/recipe/providers.js +95 -0
- package/dist/recipe/providers.js.map +1 -0
- package/dist/recipe/resolve.d.ts +7 -3
- package/dist/recipe/resolve.d.ts.map +1 -1
- package/dist/recipe/resolve.js +7 -2
- package/dist/recipe/resolve.js.map +1 -1
- package/dist/run-controller.d.ts +6 -0
- package/dist/run-controller.d.ts.map +1 -1
- package/dist/run-controller.js +2 -0
- package/dist/run-controller.js.map +1 -1
- package/dist/search/egress.d.ts +12 -0
- package/dist/search/egress.d.ts.map +1 -0
- package/dist/search/egress.js +24 -0
- package/dist/search/egress.js.map +1 -0
- package/dist/search/http.d.ts +16 -0
- package/dist/search/http.d.ts.map +1 -0
- package/dist/search/http.js +75 -0
- package/dist/search/http.js.map +1 -0
- package/dist/search/index.d.ts +10 -0
- package/dist/search/index.d.ts.map +1 -0
- package/dist/search/index.js +5 -0
- package/dist/search/index.js.map +1 -0
- package/dist/search/mcp.d.ts +58 -0
- package/dist/search/mcp.d.ts.map +1 -0
- package/dist/search/mcp.js +84 -0
- package/dist/search/mcp.js.map +1 -0
- package/dist/search/module.d.ts +28 -0
- package/dist/search/module.d.ts.map +1 -0
- package/dist/search/module.js +49 -0
- package/dist/search/module.js.map +1 -0
- package/dist/search/tool.d.ts +101 -0
- package/dist/search/tool.d.ts.map +1 -0
- package/dist/search/tool.js +518 -0
- package/dist/search/tool.js.map +1 -0
- package/dist/search/types.d.ts +257 -0
- package/dist/search/types.d.ts.map +1 -0
- package/dist/search/types.js +63 -0
- package/dist/search/types.js.map +1 -0
- package/dist/session.d.ts +21 -1
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +132 -43
- package/dist/session.js.map +1 -1
- package/dist/test-utils.d.ts +2 -0
- package/dist/test-utils.d.ts.map +1 -1
- package/dist/test-utils.js +3 -1
- package/dist/test-utils.js.map +1 -1
- package/dist/tool-search.d.ts +9 -0
- package/dist/tool-search.d.ts.map +1 -1
- package/dist/tool-search.js +23 -0
- package/dist/tool-search.js.map +1 -1
- package/dist/tools/bridge.d.ts +44 -0
- package/dist/tools/bridge.d.ts.map +1 -0
- package/dist/tools/bridge.js +106 -0
- package/dist/tools/bridge.js.map +1 -0
- package/dist/tools/cli.d.ts +20 -0
- package/dist/tools/cli.d.ts.map +1 -0
- package/dist/tools/cli.js +246 -0
- package/dist/tools/cli.js.map +1 -0
- package/dist/tools/entry.d.ts +2 -0
- package/dist/tools/entry.d.ts.map +1 -0
- package/dist/tools/entry.js +3 -0
- package/dist/tools/entry.js.map +1 -0
- package/dist/tools/shell.d.ts +12 -0
- package/dist/tools/shell.d.ts.map +1 -0
- package/dist/tools/shell.js +50 -0
- package/dist/tools/shell.js.map +1 -0
- package/dist/tuning/tpe.d.ts +112 -0
- package/dist/tuning/tpe.d.ts.map +1 -0
- package/dist/tuning/tpe.js +286 -0
- package/dist/tuning/tpe.js.map +1 -0
- package/docs/README.md +4 -1
- package/docs/channels/README.md +10 -0
- package/docs/documents/README.md +20 -19
- package/docs/host-api.md +10 -0
- package/docs/issues/README.md +183 -0
- package/docs/mcp-configuration.md +67 -2
- package/docs/pi-extension.md +5 -0
- package/docs/productivity/README.md +8 -3
- package/docs/providers.md +321 -0
- package/docs/recipe-format.md +103 -32
- package/docs/search/README.md +818 -0
- package/package.json +33 -10
- package/skills/documents/SKILL.md +2 -1
- package/skills/search/SKILL.md +72 -0
- package/dist/mcp-chunks/{auth-command-M7TQE3AL.js → auth-command-UYFOGGQR.js} +6 -6
- package/dist/mcp-chunks/{call-command-7LD7UEFK.js → call-command-6U5BNDR7.js} +17 -17
- package/dist/mcp-chunks/{chunk-PSE442BC.js → chunk-36D4FILJ.js} +26 -26
- package/dist/mcp-chunks/{config-command-6DXILFNO.js → config-command-ZSPJI34E.js} +10 -10
- package/dist/mcp-chunks/{emit-ts-command-NDCDFDRM.js → emit-ts-command-SY4LQE4S.js} +3 -3
- package/dist/mcp-chunks/{inspect-cli-command-4MGF5CPP.js → inspect-cli-command-JPX4ON6N.js} +4 -4
- package/dist/mcp-chunks/{resource-command-SRFQQROJ.js → resource-command-DUY4SVE5.js} +4 -4
|
@@ -0,0 +1,1231 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
MCP_CLIENT_ENV
|
|
4
|
+
} from "./chunk-3UVHZECT.js";
|
|
5
|
+
import "./chunk-QUDOU7MQ.js";
|
|
6
|
+
import "./chunk-HNQSUT44.js";
|
|
7
|
+
import "./chunk-LQKMNWDE.js";
|
|
8
|
+
import "./chunk-3SXP4S2A.js";
|
|
9
|
+
import "./chunk-B6S43WID.js";
|
|
10
|
+
import "./chunk-IMG2JMBS.js";
|
|
11
|
+
import "./chunk-36D4FILJ.js";
|
|
12
|
+
import "./chunk-2AKSS7WR.js";
|
|
13
|
+
import "./chunk-6P3KAQ5N.js";
|
|
14
|
+
import "./chunk-F2X4Y2TQ.js";
|
|
15
|
+
import "./chunk-3ETUDW7N.js";
|
|
16
|
+
import "./chunk-QNXOIF5U.js";
|
|
17
|
+
import "./chunk-6O42UGLI.js";
|
|
18
|
+
import "./chunk-2YV72LUA.js";
|
|
19
|
+
import "./chunk-THRMUZZD.js";
|
|
20
|
+
import "./chunk-V42T3QNK.js";
|
|
21
|
+
import "./chunk-CXST5CVH.js";
|
|
22
|
+
import "./chunk-7U5NSQ5T.js";
|
|
23
|
+
import "./chunk-3LENTPGE.js";
|
|
24
|
+
import "./chunk-JEHI2YU4.js";
|
|
25
|
+
import "./chunk-IWCVZ46B.js";
|
|
26
|
+
import "./chunk-T4MQCFIK.js";
|
|
27
|
+
import "./chunk-BHXCAVFP.js";
|
|
28
|
+
import "./chunk-O3RTM5HD.js";
|
|
29
|
+
import "./chunk-MHUMLEBO.js";
|
|
30
|
+
import "./chunk-IRSL7JRH.js";
|
|
31
|
+
import "./chunk-UVRJ3AAD.js";
|
|
32
|
+
import "./chunk-O7SIXJM6.js";
|
|
33
|
+
import "./chunk-LRKZP7DJ.js";
|
|
34
|
+
|
|
35
|
+
// src/mcp/pi-mcp-runtime.ts
|
|
36
|
+
import { readFileSync } from "node:fs";
|
|
37
|
+
|
|
38
|
+
// node_modules/.pnpm/@earendil-works+pi-mcp@1.4.0/node_modules/@earendil-works/pi-mcp/dist/protocol/jsonrpc.js
|
|
39
|
+
var JSON_RPC_ERROR_CODES = {
|
|
40
|
+
parseError: -32700,
|
|
41
|
+
invalidRequest: -32600,
|
|
42
|
+
methodNotFound: -32601,
|
|
43
|
+
invalidParams: -32602,
|
|
44
|
+
internalError: -32603
|
|
45
|
+
};
|
|
46
|
+
var McpError = class extends Error {
|
|
47
|
+
code;
|
|
48
|
+
data;
|
|
49
|
+
constructor(code, message, data) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = "McpError";
|
|
52
|
+
this.code = code;
|
|
53
|
+
this.data = data;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
var McpConnectionClosedError = class extends Error {
|
|
57
|
+
constructor(message = "MCP connection closed") {
|
|
58
|
+
super(message);
|
|
59
|
+
this.name = "McpConnectionClosedError";
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
var McpTimeoutError = class extends Error {
|
|
63
|
+
timeoutMs;
|
|
64
|
+
constructor(timeoutMs) {
|
|
65
|
+
super(`MCP request timed out after ${timeoutMs}ms`);
|
|
66
|
+
this.name = "McpTimeoutError";
|
|
67
|
+
this.timeoutMs = timeoutMs;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
var McpAbortError = class extends Error {
|
|
71
|
+
constructor(message = "MCP request aborted") {
|
|
72
|
+
super(message);
|
|
73
|
+
this.name = "AbortError";
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
function isObject(value) {
|
|
77
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
78
|
+
}
|
|
79
|
+
function toError(value) {
|
|
80
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
81
|
+
}
|
|
82
|
+
function isJsonRpcId(value) {
|
|
83
|
+
return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
|
|
84
|
+
}
|
|
85
|
+
function isJsonRpcRequest(message) {
|
|
86
|
+
return isObject(message) && message.jsonrpc === "2.0" && isJsonRpcId(message.id) && typeof message.method === "string";
|
|
87
|
+
}
|
|
88
|
+
function isJsonRpcNotification(message) {
|
|
89
|
+
return isObject(message) && message.jsonrpc === "2.0" && !("id" in message) && typeof message.method === "string";
|
|
90
|
+
}
|
|
91
|
+
function isJsonRpcResponse(message) {
|
|
92
|
+
if (!isObject(message) || message.jsonrpc !== "2.0" || !isJsonRpcId(message.id))
|
|
93
|
+
return false;
|
|
94
|
+
if ("result" in message)
|
|
95
|
+
return !("error" in message);
|
|
96
|
+
if (!("error" in message) || !isObject(message.error))
|
|
97
|
+
return false;
|
|
98
|
+
return typeof message.error.code === "number" && typeof message.error.message === "string";
|
|
99
|
+
}
|
|
100
|
+
function parseJsonRpcMessage(value) {
|
|
101
|
+
if (isJsonRpcRequest(value) || isJsonRpcNotification(value) || isJsonRpcResponse(value))
|
|
102
|
+
return value;
|
|
103
|
+
throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid JSON-RPC message");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// node_modules/.pnpm/@earendil-works+pi-mcp@1.4.0/node_modules/@earendil-works/pi-mcp/dist/protocol/types.js
|
|
107
|
+
var LATEST_PROTOCOL_VERSION = "2025-11-25";
|
|
108
|
+
var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05"];
|
|
109
|
+
|
|
110
|
+
// node_modules/.pnpm/@earendil-works+pi-mcp@1.4.0/node_modules/@earendil-works/pi-mcp/dist/client.js
|
|
111
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
112
|
+
var MAX_LIST_PAGES = 1e3;
|
|
113
|
+
function validateInitializeResult(value) {
|
|
114
|
+
if (!isObject(value) || typeof value.protocolVersion !== "string" || !isObject(value.capabilities) || !isObject(value.serverInfo) || typeof value.serverInfo.name !== "string" || typeof value.serverInfo.version !== "string" || value.instructions !== void 0 && typeof value.instructions !== "string") {
|
|
115
|
+
throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid MCP initialize result");
|
|
116
|
+
}
|
|
117
|
+
return value;
|
|
118
|
+
}
|
|
119
|
+
function invalid(message) {
|
|
120
|
+
return new McpError(JSON_RPC_ERROR_CODES.invalidRequest, message);
|
|
121
|
+
}
|
|
122
|
+
function validateListPage(method, key, value, isItem) {
|
|
123
|
+
const items = isObject(value) ? value[key] : void 0;
|
|
124
|
+
if (!isObject(value) || !Array.isArray(items))
|
|
125
|
+
throw invalid(`Invalid MCP ${method} result`);
|
|
126
|
+
for (const item of items) {
|
|
127
|
+
if (!isObject(item) || !isItem(item))
|
|
128
|
+
throw invalid(`Invalid entry in MCP ${method} result`);
|
|
129
|
+
}
|
|
130
|
+
const nextCursor = value.nextCursor === null || value.nextCursor === "" ? void 0 : value.nextCursor;
|
|
131
|
+
if (nextCursor !== void 0 && typeof nextCursor !== "string")
|
|
132
|
+
throw invalid(`Invalid MCP ${method} cursor`);
|
|
133
|
+
return { items, ...nextCursor === void 0 ? {} : { nextCursor } };
|
|
134
|
+
}
|
|
135
|
+
var isTool = (tool) => typeof tool.name === "string" && isObject(tool.inputSchema);
|
|
136
|
+
var isResource = (resource) => typeof resource.uri === "string" && (resource.name === void 0 || typeof resource.name === "string");
|
|
137
|
+
var isResourceTemplate = (template) => typeof template.uriTemplate === "string" && (template.name === void 0 || typeof template.name === "string");
|
|
138
|
+
function toResource(item) {
|
|
139
|
+
return { ...item, name: item.name ?? item.uri };
|
|
140
|
+
}
|
|
141
|
+
function toResourceTemplate(item) {
|
|
142
|
+
return { ...item, name: item.name ?? item.uriTemplate };
|
|
143
|
+
}
|
|
144
|
+
function pageCursor(page) {
|
|
145
|
+
return page.nextCursor === void 0 ? {} : { nextCursor: page.nextCursor };
|
|
146
|
+
}
|
|
147
|
+
function validateReadResourceResult(value) {
|
|
148
|
+
if (!isObject(value) || !Array.isArray(value.contents))
|
|
149
|
+
throw invalid("Invalid MCP resources/read result");
|
|
150
|
+
for (const contents of value.contents) {
|
|
151
|
+
if (!isObject(contents) || typeof contents.uri !== "string" || typeof contents.text !== "string" && typeof contents.blob !== "string") {
|
|
152
|
+
throw invalid("Invalid contents in MCP resources/read result");
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return value;
|
|
156
|
+
}
|
|
157
|
+
function validateCallToolResult(value) {
|
|
158
|
+
if (!isObject(value) || value.content !== void 0 && !Array.isArray(value.content)) {
|
|
159
|
+
throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid MCP tools/call result");
|
|
160
|
+
}
|
|
161
|
+
return value.content === void 0 ? { ...value, content: [] } : value;
|
|
162
|
+
}
|
|
163
|
+
var McpClient = class {
|
|
164
|
+
options;
|
|
165
|
+
state = "idle";
|
|
166
|
+
transport;
|
|
167
|
+
nextRequestId = 1;
|
|
168
|
+
serverInfoValue;
|
|
169
|
+
serverCapabilitiesValue;
|
|
170
|
+
instructionsValue;
|
|
171
|
+
protocolVersionValue;
|
|
172
|
+
pending = /* @__PURE__ */ new Map();
|
|
173
|
+
progressRequests = /* @__PURE__ */ new Map();
|
|
174
|
+
incoming = /* @__PURE__ */ new Map();
|
|
175
|
+
requestHandlers = /* @__PURE__ */ new Map();
|
|
176
|
+
notificationListeners = /* @__PURE__ */ new Map();
|
|
177
|
+
errorListeners = /* @__PURE__ */ new Set();
|
|
178
|
+
closeListeners = /* @__PURE__ */ new Set();
|
|
179
|
+
disposers = [];
|
|
180
|
+
constructor(options) {
|
|
181
|
+
this.options = Object.freeze({ ...options });
|
|
182
|
+
this.requestHandlers.set("ping", () => ({}));
|
|
183
|
+
const roots = options.roots;
|
|
184
|
+
if (roots) {
|
|
185
|
+
this.requestHandlers.set("roots/list", async () => ({
|
|
186
|
+
roots: [...typeof roots === "function" ? await roots() : roots]
|
|
187
|
+
}));
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
get connectionState() {
|
|
191
|
+
return this.state;
|
|
192
|
+
}
|
|
193
|
+
get serverInfo() {
|
|
194
|
+
return this.serverInfoValue;
|
|
195
|
+
}
|
|
196
|
+
get serverCapabilities() {
|
|
197
|
+
return this.serverCapabilitiesValue;
|
|
198
|
+
}
|
|
199
|
+
get instructions() {
|
|
200
|
+
return this.instructionsValue;
|
|
201
|
+
}
|
|
202
|
+
get protocolVersion() {
|
|
203
|
+
return this.protocolVersionValue;
|
|
204
|
+
}
|
|
205
|
+
async connect(transport) {
|
|
206
|
+
if (this.state !== "idle")
|
|
207
|
+
throw new Error(`Cannot connect MCP client in ${this.state} state`);
|
|
208
|
+
this.state = "connecting";
|
|
209
|
+
this.transport = transport;
|
|
210
|
+
this.disposers = [
|
|
211
|
+
transport.onMessage((message) => this.handleMessage(message)),
|
|
212
|
+
// Transport errors are reported only. Pending requests fail when the transport closes.
|
|
213
|
+
transport.onError((error) => this.emitError(error)),
|
|
214
|
+
transport.onClose(() => this.handleTransportClose())
|
|
215
|
+
];
|
|
216
|
+
try {
|
|
217
|
+
await transport.start();
|
|
218
|
+
const capabilities = { ...this.options.capabilities };
|
|
219
|
+
if (this.options.roots && capabilities.roots === void 0)
|
|
220
|
+
capabilities.roots = {};
|
|
221
|
+
const result = validateInitializeResult(await this.requestInternal("initialize", {
|
|
222
|
+
protocolVersion: this.options.protocolVersion ?? LATEST_PROTOCOL_VERSION,
|
|
223
|
+
capabilities,
|
|
224
|
+
clientInfo: {
|
|
225
|
+
name: this.options.name,
|
|
226
|
+
version: this.options.version,
|
|
227
|
+
...this.options.title === void 0 ? {} : { title: this.options.title }
|
|
228
|
+
}
|
|
229
|
+
}, {}, true));
|
|
230
|
+
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
|
|
231
|
+
throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);
|
|
232
|
+
}
|
|
233
|
+
this.protocolVersionValue = result.protocolVersion;
|
|
234
|
+
this.serverInfoValue = result.serverInfo;
|
|
235
|
+
this.serverCapabilitiesValue = result.capabilities;
|
|
236
|
+
this.instructionsValue = result.instructions;
|
|
237
|
+
transport.setProtocolVersion?.(result.protocolVersion);
|
|
238
|
+
await this.notifyInternal("notifications/initialized", void 0, true);
|
|
239
|
+
this.state = "connected";
|
|
240
|
+
return result;
|
|
241
|
+
} catch (error) {
|
|
242
|
+
await this.close().catch(() => {
|
|
243
|
+
});
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
request(method, params, options = {}) {
|
|
248
|
+
return this.requestInternal(method, params, options, false);
|
|
249
|
+
}
|
|
250
|
+
notify(method, params) {
|
|
251
|
+
return this.notifyInternal(method, params, false);
|
|
252
|
+
}
|
|
253
|
+
setRequestHandler(method, handler) {
|
|
254
|
+
this.requestHandlers.set(method, handler);
|
|
255
|
+
return () => {
|
|
256
|
+
if (this.requestHandlers.get(method) === handler)
|
|
257
|
+
this.requestHandlers.delete(method);
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
onNotification(method, listener) {
|
|
261
|
+
const listeners = this.notificationListeners.get(method) ?? /* @__PURE__ */ new Set();
|
|
262
|
+
this.notificationListeners.set(method, listeners);
|
|
263
|
+
listeners.add(listener);
|
|
264
|
+
return () => {
|
|
265
|
+
listeners.delete(listener);
|
|
266
|
+
if (listeners.size === 0)
|
|
267
|
+
this.notificationListeners.delete(method);
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
onError(listener) {
|
|
271
|
+
this.errorListeners.add(listener);
|
|
272
|
+
return () => this.errorListeners.delete(listener);
|
|
273
|
+
}
|
|
274
|
+
/** Called once when the connection closes, whether the transport dropped or `close()` was called. */
|
|
275
|
+
onClose(listener) {
|
|
276
|
+
this.closeListeners.add(listener);
|
|
277
|
+
return () => this.closeListeners.delete(listener);
|
|
278
|
+
}
|
|
279
|
+
async ping(options = {}) {
|
|
280
|
+
await this.request("ping", void 0, options);
|
|
281
|
+
}
|
|
282
|
+
async listTools(options = {}) {
|
|
283
|
+
return await this.listAll("tools/list", "tools", isTool, options);
|
|
284
|
+
}
|
|
285
|
+
/** Every resource, following `nextCursor` through all pages. */
|
|
286
|
+
async listResources(options = {}) {
|
|
287
|
+
return (await this.listAll("resources/list", "resources", isResource, options)).map(toResource);
|
|
288
|
+
}
|
|
289
|
+
/** One page of resources, starting at `cursor`. */
|
|
290
|
+
async listResourcesPage(cursor, options = {}) {
|
|
291
|
+
const page = await this.listPage("resources/list", "resources", isResource, cursor, options);
|
|
292
|
+
return { resources: page.items.map(toResource), ...pageCursor(page) };
|
|
293
|
+
}
|
|
294
|
+
/** Every resource template, following `nextCursor` through all pages. */
|
|
295
|
+
async listResourceTemplates(options = {}) {
|
|
296
|
+
const templates = await this.listAll("resources/templates/list", "resourceTemplates", isResourceTemplate, options);
|
|
297
|
+
return templates.map(toResourceTemplate);
|
|
298
|
+
}
|
|
299
|
+
/** One page of resource templates, starting at `cursor`. */
|
|
300
|
+
async listResourceTemplatesPage(cursor, options = {}) {
|
|
301
|
+
const page = await this.listPage("resources/templates/list", "resourceTemplates", isResourceTemplate, cursor, options);
|
|
302
|
+
return { resourceTemplates: page.items.map(toResourceTemplate), ...pageCursor(page) };
|
|
303
|
+
}
|
|
304
|
+
async readResource(uri, options = {}) {
|
|
305
|
+
return validateReadResourceResult(await this.request("resources/read", { uri }, options));
|
|
306
|
+
}
|
|
307
|
+
async listPage(method, key, isItem, cursor, options) {
|
|
308
|
+
return validateListPage(method, key, await this.request(method, cursor === void 0 ? void 0 : { cursor }, options), isItem);
|
|
309
|
+
}
|
|
310
|
+
/** Every item of a paginated list method. */
|
|
311
|
+
async listAll(method, key, isItem, options) {
|
|
312
|
+
const items = [];
|
|
313
|
+
const cursors = /* @__PURE__ */ new Set();
|
|
314
|
+
let cursor;
|
|
315
|
+
for (let pageNumber = 0; pageNumber < MAX_LIST_PAGES; pageNumber++) {
|
|
316
|
+
const page = await this.listPage(method, key, isItem, cursor, options);
|
|
317
|
+
items.push(...page.items);
|
|
318
|
+
if (page.nextCursor === void 0)
|
|
319
|
+
return items;
|
|
320
|
+
if (cursors.has(page.nextCursor))
|
|
321
|
+
throw new Error(`MCP ${method} returned duplicate cursor: ${page.nextCursor}`);
|
|
322
|
+
cursors.add(page.nextCursor);
|
|
323
|
+
cursor = page.nextCursor;
|
|
324
|
+
}
|
|
325
|
+
throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`);
|
|
326
|
+
}
|
|
327
|
+
async callTool(name, args, options = {}) {
|
|
328
|
+
return validateCallToolResult(await this.request("tools/call", { name, ...args === void 0 ? {} : { arguments: args } }, options));
|
|
329
|
+
}
|
|
330
|
+
async close() {
|
|
331
|
+
const transport = this.transport;
|
|
332
|
+
this.transport = void 0;
|
|
333
|
+
this.disposeTransportListeners();
|
|
334
|
+
this.markClosed(new McpConnectionClosedError());
|
|
335
|
+
await transport?.close();
|
|
336
|
+
}
|
|
337
|
+
async requestInternal(method, params, options, allowConnecting) {
|
|
338
|
+
const transport = this.requireTransport(allowConnecting);
|
|
339
|
+
if (options.signal?.aborted)
|
|
340
|
+
throw new McpAbortError();
|
|
341
|
+
const id = this.nextRequestId++;
|
|
342
|
+
const progressToken = options.onProgress ? id : void 0;
|
|
343
|
+
const requestParams = progressToken === void 0 ? params : { ...params, _meta: { ...isObject(params?._meta) ? params._meta : {}, progressToken } };
|
|
344
|
+
const message = {
|
|
345
|
+
jsonrpc: "2.0",
|
|
346
|
+
id,
|
|
347
|
+
method,
|
|
348
|
+
...requestParams === void 0 ? {} : { params: requestParams }
|
|
349
|
+
};
|
|
350
|
+
return new Promise((resolve, reject) => {
|
|
351
|
+
const entry = {
|
|
352
|
+
resolve,
|
|
353
|
+
reject,
|
|
354
|
+
timeoutMs: options.timeoutMs ?? this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
355
|
+
timer: void 0,
|
|
356
|
+
signal: options.signal,
|
|
357
|
+
// The spec forbids cancelling `initialize`.
|
|
358
|
+
onAbort: () => this.cancelPending(id, new McpAbortError(), method !== "initialize", String(options.signal?.reason ?? "Aborted")),
|
|
359
|
+
sendController: new AbortController(),
|
|
360
|
+
cancellable: method !== "initialize",
|
|
361
|
+
onProgress: options.onProgress,
|
|
362
|
+
progressToken
|
|
363
|
+
};
|
|
364
|
+
this.pending.set(id, entry);
|
|
365
|
+
if (progressToken !== void 0)
|
|
366
|
+
this.progressRequests.set(progressToken, id);
|
|
367
|
+
options.signal?.addEventListener("abort", entry.onAbort, { once: true });
|
|
368
|
+
this.armTimeout(id, entry);
|
|
369
|
+
transport.send(message, { signal: entry.sendController.signal }).catch((error) => this.cancelPending(id, error, false));
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
async notifyInternal(method, params, allowConnecting) {
|
|
373
|
+
await this.requireTransport(allowConnecting).send({
|
|
374
|
+
jsonrpc: "2.0",
|
|
375
|
+
method,
|
|
376
|
+
...params === void 0 ? {} : { params }
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
requireTransport(allowConnecting) {
|
|
380
|
+
if (this.transport && (this.state === "connected" || allowConnecting && this.state === "connecting")) {
|
|
381
|
+
return this.transport;
|
|
382
|
+
}
|
|
383
|
+
throw new McpConnectionClosedError(`MCP client is ${this.state}`);
|
|
384
|
+
}
|
|
385
|
+
handleMessage(message) {
|
|
386
|
+
if (isJsonRpcResponse(message)) {
|
|
387
|
+
this.handleResponse(message);
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
if (isJsonRpcRequest(message)) {
|
|
391
|
+
void this.handleRequest(message);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
if (isJsonRpcNotification(message)) {
|
|
395
|
+
this.handleNotification(message.method, message.params);
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
this.emitError(new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Received invalid JSON-RPC message"));
|
|
399
|
+
}
|
|
400
|
+
handleResponse(message) {
|
|
401
|
+
const entry = this.pending.get(message.id);
|
|
402
|
+
if (!entry) {
|
|
403
|
+
this.emitError(new Error(`Received response for unknown MCP request ${String(message.id)}`));
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
this.removePending(message.id, entry);
|
|
407
|
+
if ("error" in message)
|
|
408
|
+
entry.reject(new McpError(message.error.code, message.error.message, message.error.data));
|
|
409
|
+
else
|
|
410
|
+
entry.resolve(message.result);
|
|
411
|
+
}
|
|
412
|
+
async handleRequest(message) {
|
|
413
|
+
const transport = this.transport;
|
|
414
|
+
if (!transport)
|
|
415
|
+
return;
|
|
416
|
+
const handler = this.requestHandlers.get(message.method);
|
|
417
|
+
if (!handler) {
|
|
418
|
+
await transport.send({
|
|
419
|
+
jsonrpc: "2.0",
|
|
420
|
+
id: message.id,
|
|
421
|
+
error: { code: JSON_RPC_ERROR_CODES.methodNotFound, message: `Method not found: ${message.method}` }
|
|
422
|
+
}).catch((error) => this.emitError(error));
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
const controller = new AbortController();
|
|
426
|
+
this.incoming.set(message.id, controller);
|
|
427
|
+
try {
|
|
428
|
+
const result = await handler(message.params, { signal: controller.signal });
|
|
429
|
+
await transport.send({ jsonrpc: "2.0", id: message.id, result: result ?? {} });
|
|
430
|
+
} catch (error) {
|
|
431
|
+
const responseError = error instanceof McpError ? { code: error.code, message: error.message, data: error.data } : { code: JSON_RPC_ERROR_CODES.internalError, message: toError(error).message };
|
|
432
|
+
await transport.send({ jsonrpc: "2.0", id: message.id, error: responseError }).catch((sendError) => this.emitError(sendError));
|
|
433
|
+
} finally {
|
|
434
|
+
this.incoming.delete(message.id);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
handleNotification(method, params) {
|
|
438
|
+
if (method === "notifications/progress")
|
|
439
|
+
this.handleProgress(params);
|
|
440
|
+
else if (method === "notifications/cancelled")
|
|
441
|
+
this.handleCancelled(params);
|
|
442
|
+
for (const listener of this.notificationListeners.get(method) ?? []) {
|
|
443
|
+
try {
|
|
444
|
+
listener(params);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
this.emitError(error);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
handleProgress(params) {
|
|
451
|
+
if (!isObject(params) || !isJsonRpcId(params.progressToken) || typeof params.progress !== "number")
|
|
452
|
+
return;
|
|
453
|
+
const requestId = this.progressRequests.get(params.progressToken);
|
|
454
|
+
const entry = requestId === void 0 ? void 0 : this.pending.get(requestId);
|
|
455
|
+
if (requestId === void 0 || !entry)
|
|
456
|
+
return;
|
|
457
|
+
this.armTimeout(requestId, entry);
|
|
458
|
+
try {
|
|
459
|
+
entry.onProgress?.(params);
|
|
460
|
+
} catch (error) {
|
|
461
|
+
this.emitError(error);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
handleCancelled(params) {
|
|
465
|
+
if (isObject(params) && isJsonRpcId(params.requestId))
|
|
466
|
+
this.incoming.get(params.requestId)?.abort(params.reason);
|
|
467
|
+
}
|
|
468
|
+
armTimeout(id, entry) {
|
|
469
|
+
if (entry.timer)
|
|
470
|
+
clearTimeout(entry.timer);
|
|
471
|
+
if (!Number.isFinite(entry.timeoutMs) || entry.timeoutMs <= 0)
|
|
472
|
+
return;
|
|
473
|
+
entry.timer = setTimeout(() => {
|
|
474
|
+
this.cancelPending(id, new McpTimeoutError(entry.timeoutMs), entry.cancellable, "Request timed out");
|
|
475
|
+
}, entry.timeoutMs);
|
|
476
|
+
}
|
|
477
|
+
cancelPending(id, error, notifyServer, reason) {
|
|
478
|
+
const entry = this.pending.get(id);
|
|
479
|
+
if (!entry)
|
|
480
|
+
return;
|
|
481
|
+
this.removePending(id, entry);
|
|
482
|
+
entry.reject(error);
|
|
483
|
+
if (notifyServer && this.transport) {
|
|
484
|
+
void this.transport.send({
|
|
485
|
+
jsonrpc: "2.0",
|
|
486
|
+
method: "notifications/cancelled",
|
|
487
|
+
params: { requestId: id, ...reason ? { reason } : {} }
|
|
488
|
+
}).catch((sendError) => this.emitError(sendError));
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
removePending(id, entry) {
|
|
492
|
+
this.pending.delete(id);
|
|
493
|
+
if (entry.timer)
|
|
494
|
+
clearTimeout(entry.timer);
|
|
495
|
+
if (entry.progressToken !== void 0)
|
|
496
|
+
this.progressRequests.delete(entry.progressToken);
|
|
497
|
+
entry.signal?.removeEventListener("abort", entry.onAbort);
|
|
498
|
+
entry.sendController.abort();
|
|
499
|
+
}
|
|
500
|
+
rejectPending(error) {
|
|
501
|
+
for (const [id, entry] of this.pending) {
|
|
502
|
+
this.removePending(id, entry);
|
|
503
|
+
entry.reject(error);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
handleTransportClose() {
|
|
507
|
+
this.markClosed(new McpConnectionClosedError());
|
|
508
|
+
}
|
|
509
|
+
/** Idempotent: rejects in-flight requests, aborts server requests we are serving, and flips the state. */
|
|
510
|
+
markClosed(error) {
|
|
511
|
+
const wasClosed = this.state === "closed";
|
|
512
|
+
this.state = "closed";
|
|
513
|
+
this.rejectPending(error);
|
|
514
|
+
for (const controller of this.incoming.values())
|
|
515
|
+
controller.abort(error);
|
|
516
|
+
this.incoming.clear();
|
|
517
|
+
if (wasClosed)
|
|
518
|
+
return;
|
|
519
|
+
for (const listener of [...this.closeListeners]) {
|
|
520
|
+
try {
|
|
521
|
+
listener();
|
|
522
|
+
} catch (listenerError) {
|
|
523
|
+
this.emitError(listenerError);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
emitError(error) {
|
|
528
|
+
const normalized = toError(error);
|
|
529
|
+
for (const listener of this.errorListeners)
|
|
530
|
+
listener(normalized);
|
|
531
|
+
}
|
|
532
|
+
disposeTransportListeners() {
|
|
533
|
+
for (const dispose of this.disposers.splice(0))
|
|
534
|
+
dispose();
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
// node_modules/.pnpm/@earendil-works+pi-mcp@1.4.0/node_modules/@earendil-works/pi-mcp/dist/transports/transport.js
|
|
539
|
+
var DEFAULT_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
540
|
+
var TransportEvents = class {
|
|
541
|
+
messageListeners = /* @__PURE__ */ new Set();
|
|
542
|
+
errorListeners = /* @__PURE__ */ new Set();
|
|
543
|
+
closeListeners = /* @__PURE__ */ new Set();
|
|
544
|
+
closeEmitted = false;
|
|
545
|
+
onMessage(listener) {
|
|
546
|
+
this.messageListeners.add(listener);
|
|
547
|
+
return () => this.messageListeners.delete(listener);
|
|
548
|
+
}
|
|
549
|
+
onError(listener) {
|
|
550
|
+
this.errorListeners.add(listener);
|
|
551
|
+
return () => this.errorListeners.delete(listener);
|
|
552
|
+
}
|
|
553
|
+
onClose(listener) {
|
|
554
|
+
this.closeListeners.add(listener);
|
|
555
|
+
return () => this.closeListeners.delete(listener);
|
|
556
|
+
}
|
|
557
|
+
emitMessage(message) {
|
|
558
|
+
for (const listener of this.messageListeners)
|
|
559
|
+
listener(message);
|
|
560
|
+
}
|
|
561
|
+
emitError(error) {
|
|
562
|
+
const normalized = toError(error);
|
|
563
|
+
for (const listener of this.errorListeners)
|
|
564
|
+
listener(normalized);
|
|
565
|
+
}
|
|
566
|
+
emitClose() {
|
|
567
|
+
if (this.closeEmitted)
|
|
568
|
+
return;
|
|
569
|
+
this.closeEmitted = true;
|
|
570
|
+
for (const listener of this.closeListeners)
|
|
571
|
+
listener();
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
// node_modules/.pnpm/@earendil-works+pi-mcp@1.4.0/node_modules/@earendil-works/pi-mcp/dist/transports/streamable-http.js
|
|
576
|
+
var MAX_ERROR_BODY_BYTES = 8 * 1024;
|
|
577
|
+
var ERROR_MESSAGE_BODY_CHARS = 500;
|
|
578
|
+
var DEFAULT_RECONNECT_INITIAL_DELAY_MS = 1e3;
|
|
579
|
+
var DEFAULT_RECONNECT_MAX_DELAY_MS = 3e4;
|
|
580
|
+
var DEFAULT_RECONNECT_MAX_RETRIES = 5;
|
|
581
|
+
async function consumeSseStream(stream, options) {
|
|
582
|
+
const reader = stream.getReader();
|
|
583
|
+
const decoder = new TextDecoder();
|
|
584
|
+
let buffered = "";
|
|
585
|
+
let eventName;
|
|
586
|
+
let eventId;
|
|
587
|
+
let dataLines = [];
|
|
588
|
+
let dataBytes = 0;
|
|
589
|
+
const maxEventBytes = options.maxEventBytes ?? DEFAULT_MAX_MESSAGE_BYTES;
|
|
590
|
+
const dispatch = () => {
|
|
591
|
+
if (dataLines.length === 0) {
|
|
592
|
+
eventName = void 0;
|
|
593
|
+
eventId = void 0;
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
const data = dataLines.join("\n");
|
|
597
|
+
options.onEvent({ ...eventName ? { event: eventName } : {}, data, ...eventId ? { id: eventId } : {} });
|
|
598
|
+
eventName = void 0;
|
|
599
|
+
eventId = void 0;
|
|
600
|
+
dataLines = [];
|
|
601
|
+
dataBytes = 0;
|
|
602
|
+
};
|
|
603
|
+
const processLine = (rawLine) => {
|
|
604
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
605
|
+
if (line === "") {
|
|
606
|
+
dispatch();
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
if (line.startsWith(":"))
|
|
610
|
+
return;
|
|
611
|
+
const colon = line.indexOf(":");
|
|
612
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
613
|
+
let value = colon < 0 ? "" : line.slice(colon + 1);
|
|
614
|
+
if (value.startsWith(" "))
|
|
615
|
+
value = value.slice(1);
|
|
616
|
+
if (field === "data") {
|
|
617
|
+
dataBytes += Buffer.byteLength(value) + (dataLines.length > 0 ? 1 : 0);
|
|
618
|
+
if (dataBytes > maxEventBytes)
|
|
619
|
+
throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
|
|
620
|
+
dataLines.push(value);
|
|
621
|
+
} else if (field === "event")
|
|
622
|
+
eventName = value;
|
|
623
|
+
else if (field === "id" && !value.includes("\0")) {
|
|
624
|
+
eventId = value;
|
|
625
|
+
options.onId?.(value);
|
|
626
|
+
} else if (field === "retry" && /^\d+$/.test(value))
|
|
627
|
+
options.onRetry?.(Number(value));
|
|
628
|
+
};
|
|
629
|
+
try {
|
|
630
|
+
while (true) {
|
|
631
|
+
const { done, value } = await reader.read();
|
|
632
|
+
if (done)
|
|
633
|
+
break;
|
|
634
|
+
buffered += decoder.decode(value, { stream: true });
|
|
635
|
+
let newline = buffered.indexOf("\n");
|
|
636
|
+
while (newline >= 0) {
|
|
637
|
+
processLine(buffered.slice(0, newline));
|
|
638
|
+
buffered = buffered.slice(newline + 1);
|
|
639
|
+
newline = buffered.indexOf("\n");
|
|
640
|
+
}
|
|
641
|
+
if (Buffer.byteLength(buffered) > maxEventBytes)
|
|
642
|
+
throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
|
|
643
|
+
}
|
|
644
|
+
buffered += decoder.decode();
|
|
645
|
+
if (buffered)
|
|
646
|
+
processLine(buffered);
|
|
647
|
+
dispatch();
|
|
648
|
+
} finally {
|
|
649
|
+
reader.releaseLock();
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
var McpHttpError = class extends Error {
|
|
653
|
+
status;
|
|
654
|
+
body;
|
|
655
|
+
constructor(status, message, body = "") {
|
|
656
|
+
super(message);
|
|
657
|
+
this.name = "McpHttpError";
|
|
658
|
+
this.status = status;
|
|
659
|
+
this.body = body;
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
var McpAuthRequiredError = class extends McpHttpError {
|
|
663
|
+
wwwAuthenticate;
|
|
664
|
+
constructor(response, body = "") {
|
|
665
|
+
super(401, "MCP server requires authentication", body);
|
|
666
|
+
this.name = "McpAuthRequiredError";
|
|
667
|
+
this.wwwAuthenticate = response.headers.get("www-authenticate");
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
var McpSessionExpiredError = class extends McpHttpError {
|
|
671
|
+
constructor(body = "") {
|
|
672
|
+
super(404, "MCP session expired", body);
|
|
673
|
+
this.name = "McpSessionExpiredError";
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
function contentType(response) {
|
|
677
|
+
return response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
678
|
+
}
|
|
679
|
+
function needsAuthorization(response) {
|
|
680
|
+
if (response.status === 401)
|
|
681
|
+
return true;
|
|
682
|
+
if (response.status !== 403)
|
|
683
|
+
return false;
|
|
684
|
+
return /(?:^|[\s,])error="?insufficient_scope"?/i.test(response.headers.get("www-authenticate") ?? "");
|
|
685
|
+
}
|
|
686
|
+
function isTransientStatus(status) {
|
|
687
|
+
return status === 408 || status === 429 || status >= 500;
|
|
688
|
+
}
|
|
689
|
+
function discard(response) {
|
|
690
|
+
return response.body?.cancel().catch(() => {
|
|
691
|
+
}) ?? Promise.resolve();
|
|
692
|
+
}
|
|
693
|
+
function describeHttpFailure(status, body) {
|
|
694
|
+
const text = body.trim();
|
|
695
|
+
const snippet = text.length > ERROR_MESSAGE_BODY_CHARS ? `${text.slice(0, ERROR_MESSAGE_BODY_CHARS - 3)}...` : text;
|
|
696
|
+
return `MCP HTTP request failed with status ${status}${snippet ? `: ${snippet}` : ""}`;
|
|
697
|
+
}
|
|
698
|
+
var StreamableHttpTransport = class extends TransportEvents {
|
|
699
|
+
url;
|
|
700
|
+
options;
|
|
701
|
+
fetch;
|
|
702
|
+
controller = new AbortController();
|
|
703
|
+
started = false;
|
|
704
|
+
closed = false;
|
|
705
|
+
sessionIdValue;
|
|
706
|
+
protocolVersion;
|
|
707
|
+
getStreamStarted = false;
|
|
708
|
+
/** Access token of the latest request, which `close()` reuses instead of asking the auth provider. */
|
|
709
|
+
lastToken;
|
|
710
|
+
constructor(options) {
|
|
711
|
+
super();
|
|
712
|
+
this.options = Object.freeze({ ...options, headers: options.headers ? { ...options.headers } : void 0 });
|
|
713
|
+
this.url = new URL(options.url);
|
|
714
|
+
const fetch = options.fetch ?? globalThis.fetch;
|
|
715
|
+
this.fetch = (input, init) => fetch(input, init);
|
|
716
|
+
}
|
|
717
|
+
get sessionId() {
|
|
718
|
+
return this.sessionIdValue;
|
|
719
|
+
}
|
|
720
|
+
async start() {
|
|
721
|
+
if (this.started)
|
|
722
|
+
throw new Error("MCP Streamable HTTP transport already started");
|
|
723
|
+
if (this.closed)
|
|
724
|
+
throw new McpConnectionClosedError();
|
|
725
|
+
this.started = true;
|
|
726
|
+
}
|
|
727
|
+
setProtocolVersion(version) {
|
|
728
|
+
this.protocolVersion = version;
|
|
729
|
+
}
|
|
730
|
+
async send(message, { signal } = {}) {
|
|
731
|
+
if (!this.started || this.closed)
|
|
732
|
+
throw new McpConnectionClosedError();
|
|
733
|
+
const response = await this.authorizedFetch("POST", {
|
|
734
|
+
headers: { accept: "application/json, text/event-stream", "content-type": "application/json" },
|
|
735
|
+
body: JSON.stringify(message)
|
|
736
|
+
}, signal);
|
|
737
|
+
await this.checkResponse(response);
|
|
738
|
+
this.captureSession(response);
|
|
739
|
+
if (!isJsonRpcRequest(message)) {
|
|
740
|
+
await discard(response);
|
|
741
|
+
if ("method" in message && message.method === "notifications/initialized")
|
|
742
|
+
this.startGetStream();
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
if (response.status === 202 || response.status === 204) {
|
|
746
|
+
throw new McpHttpError(response.status, `MCP server accepted request ${message.method} without a response`);
|
|
747
|
+
}
|
|
748
|
+
const type = contentType(response);
|
|
749
|
+
if (type === "application/json") {
|
|
750
|
+
const body = await response.json();
|
|
751
|
+
for (const item of Array.isArray(body) ? body : [body])
|
|
752
|
+
this.emitMessage(parseJsonRpcMessage(item));
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
if (type === "text/event-stream" && response.body) {
|
|
756
|
+
void this.consumeResponseStream(response.body, message.id);
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
await discard(response);
|
|
760
|
+
throw new McpHttpError(response.status, `Unsupported MCP response content type: ${type ?? "missing"}`);
|
|
761
|
+
}
|
|
762
|
+
async close() {
|
|
763
|
+
if (this.closed)
|
|
764
|
+
return;
|
|
765
|
+
this.closed = true;
|
|
766
|
+
this.controller.abort();
|
|
767
|
+
if (this.started && this.sessionIdValue) {
|
|
768
|
+
try {
|
|
769
|
+
const response = await this.fetch(this.url, {
|
|
770
|
+
method: "DELETE",
|
|
771
|
+
headers: this.buildHeaders({}, this.lastToken),
|
|
772
|
+
signal: AbortSignal.timeout(1e3)
|
|
773
|
+
});
|
|
774
|
+
await discard(response);
|
|
775
|
+
} catch {
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
this.emitClose();
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Fetch with auth headers. A 401 (or a 403 asking for more scope) is handed to the auth provider
|
|
782
|
+
* once, and the request is retried with whatever credentials it left behind.
|
|
783
|
+
*
|
|
784
|
+
* `signal` only stops dispatch: getting a token or the authorization recovery can take a while, and a
|
|
785
|
+
* request its sender gave up on in the meantime must not reach the server. It does not abort the shared
|
|
786
|
+
* recovery, which other requests may wait for.
|
|
787
|
+
*/
|
|
788
|
+
async authorizedFetch(method, init, signal) {
|
|
789
|
+
const onUnauthorized = this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);
|
|
790
|
+
for (let attempt = 0; ; attempt++) {
|
|
791
|
+
const { headers, token } = await this.headers(init.headers);
|
|
792
|
+
if (signal?.aborted)
|
|
793
|
+
throw new McpAbortError();
|
|
794
|
+
const response = await this.fetch(this.url, {
|
|
795
|
+
method,
|
|
796
|
+
headers,
|
|
797
|
+
body: init.body,
|
|
798
|
+
signal: this.controller.signal
|
|
799
|
+
});
|
|
800
|
+
if (attempt > 0 || !onUnauthorized || !needsAuthorization(response))
|
|
801
|
+
return response;
|
|
802
|
+
try {
|
|
803
|
+
await onUnauthorized({ response, serverUrl: this.url, fetch: this.fetch, token });
|
|
804
|
+
} finally {
|
|
805
|
+
await discard(response);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
async headers(extra = {}) {
|
|
810
|
+
const token = await this.options.authProvider?.token();
|
|
811
|
+
this.lastToken = token;
|
|
812
|
+
return { headers: this.buildHeaders(extra, token), ...token ? { token } : {} };
|
|
813
|
+
}
|
|
814
|
+
buildHeaders(extra, token) {
|
|
815
|
+
const headers = new Headers(this.options.headers);
|
|
816
|
+
for (const [name, value] of Object.entries(extra))
|
|
817
|
+
headers.set(name, value);
|
|
818
|
+
if (this.sessionIdValue)
|
|
819
|
+
headers.set("Mcp-Session-Id", this.sessionIdValue);
|
|
820
|
+
if (this.protocolVersion)
|
|
821
|
+
headers.set("MCP-Protocol-Version", this.protocolVersion);
|
|
822
|
+
if (token)
|
|
823
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
824
|
+
return headers;
|
|
825
|
+
}
|
|
826
|
+
captureSession(response) {
|
|
827
|
+
const sessionId = response.headers.get("mcp-session-id");
|
|
828
|
+
if (sessionId)
|
|
829
|
+
this.sessionIdValue = sessionId;
|
|
830
|
+
}
|
|
831
|
+
async checkResponse(response) {
|
|
832
|
+
if (response.ok)
|
|
833
|
+
return;
|
|
834
|
+
const body = (await response.text().catch(() => "")).slice(0, MAX_ERROR_BODY_BYTES);
|
|
835
|
+
if (response.status === 401)
|
|
836
|
+
throw new McpAuthRequiredError(response, body);
|
|
837
|
+
if (response.status === 404 && this.sessionIdValue)
|
|
838
|
+
throw new McpSessionExpiredError(body);
|
|
839
|
+
throw new McpHttpError(response.status, describeHttpFailure(response.status, body), body);
|
|
840
|
+
}
|
|
841
|
+
async consumeSse(stream, cursor, onMessage) {
|
|
842
|
+
await consumeSseStream(stream, {
|
|
843
|
+
maxEventBytes: this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES,
|
|
844
|
+
onId: (id) => {
|
|
845
|
+
cursor.lastEventId = id;
|
|
846
|
+
},
|
|
847
|
+
onRetry: (delayMs) => {
|
|
848
|
+
cursor.retryMs = delayMs;
|
|
849
|
+
},
|
|
850
|
+
onEvent: (event) => {
|
|
851
|
+
cursor.received = true;
|
|
852
|
+
if (!event.data.trim() || event.event !== void 0 && event.event !== "message")
|
|
853
|
+
return;
|
|
854
|
+
let message;
|
|
855
|
+
try {
|
|
856
|
+
message = parseJsonRpcMessage(JSON.parse(event.data));
|
|
857
|
+
} catch (error) {
|
|
858
|
+
this.emitError(error);
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
onMessage?.(message);
|
|
862
|
+
this.emitMessage(message);
|
|
863
|
+
}
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* Read the SSE stream answering one request. When the stream ends or breaks before the response
|
|
868
|
+
* arrives and the server assigned event IDs, resume it with GET and `Last-Event-ID`, as the
|
|
869
|
+
* server may close response streams at will. Otherwise only this request fails.
|
|
870
|
+
*/
|
|
871
|
+
async consumeResponseStream(body, requestId) {
|
|
872
|
+
const cursor = { lastEventId: void 0, retryMs: void 0, received: false };
|
|
873
|
+
let answered = false;
|
|
874
|
+
const onMessage = (message) => {
|
|
875
|
+
if (isJsonRpcResponse(message) && message.id === requestId)
|
|
876
|
+
answered = true;
|
|
877
|
+
};
|
|
878
|
+
let stream = body;
|
|
879
|
+
let failure;
|
|
880
|
+
for (let attempt = 0; ; ) {
|
|
881
|
+
if (stream) {
|
|
882
|
+
try {
|
|
883
|
+
await this.consumeSse(stream, cursor, onMessage);
|
|
884
|
+
failure = void 0;
|
|
885
|
+
} catch (error) {
|
|
886
|
+
failure = error;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
if (answered || this.closed)
|
|
890
|
+
return;
|
|
891
|
+
if (failure !== void 0 && !this.isRetryable(failure))
|
|
892
|
+
break;
|
|
893
|
+
if (cursor.lastEventId === void 0 || attempt >= this.maxRetries())
|
|
894
|
+
break;
|
|
895
|
+
if (cursor.received)
|
|
896
|
+
attempt = 0;
|
|
897
|
+
cursor.received = false;
|
|
898
|
+
if (!await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))
|
|
899
|
+
return;
|
|
900
|
+
try {
|
|
901
|
+
stream = await this.openSseStream(cursor.lastEventId);
|
|
902
|
+
} catch (error) {
|
|
903
|
+
failure = error;
|
|
904
|
+
if (!this.isRetryable(error))
|
|
905
|
+
break;
|
|
906
|
+
stream = void 0;
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
if (this.closed)
|
|
910
|
+
return;
|
|
911
|
+
const reason = failure === void 0 ? "stream ended without a response" : toError(failure).message;
|
|
912
|
+
this.emitMessage({
|
|
913
|
+
jsonrpc: "2.0",
|
|
914
|
+
id: requestId,
|
|
915
|
+
error: { code: JSON_RPC_ERROR_CODES.internalError, message: `MCP response stream failed: ${reason}` }
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
startGetStream() {
|
|
919
|
+
if (this.options.openGetStream === false || this.getStreamStarted || this.closed)
|
|
920
|
+
return;
|
|
921
|
+
this.getStreamStarted = true;
|
|
922
|
+
void this.runGetStream();
|
|
923
|
+
}
|
|
924
|
+
/** Keep the server-to-client stream open, reconnecting with backoff when it drops. */
|
|
925
|
+
async runGetStream() {
|
|
926
|
+
const cursor = { lastEventId: void 0, retryMs: void 0, received: false };
|
|
927
|
+
for (let attempt = 0; !this.closed; ) {
|
|
928
|
+
try {
|
|
929
|
+
const stream = await this.openSseStream(cursor.lastEventId);
|
|
930
|
+
if (!stream)
|
|
931
|
+
return;
|
|
932
|
+
const openedAt = Date.now();
|
|
933
|
+
await this.consumeSse(stream, cursor);
|
|
934
|
+
if (cursor.received || Date.now() - openedAt > this.maxDelay())
|
|
935
|
+
attempt = 0;
|
|
936
|
+
} catch (error) {
|
|
937
|
+
if (this.closed)
|
|
938
|
+
return;
|
|
939
|
+
if (!this.isRetryable(error)) {
|
|
940
|
+
this.emitError(error);
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
cursor.received = false;
|
|
945
|
+
if (attempt >= this.maxRetries()) {
|
|
946
|
+
this.emitError(new Error("MCP server-to-client stream dropped and could not be reopened"));
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
if (!await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
/** Open a GET SSE stream. Resolves to undefined when the server answers 405 (no GET stream). */
|
|
954
|
+
async openSseStream(lastEventId) {
|
|
955
|
+
const response = await this.authorizedFetch("GET", {
|
|
956
|
+
headers: {
|
|
957
|
+
accept: "text/event-stream",
|
|
958
|
+
...lastEventId === void 0 ? {} : { "last-event-id": lastEventId }
|
|
959
|
+
}
|
|
960
|
+
});
|
|
961
|
+
if (response.status === 405) {
|
|
962
|
+
await discard(response);
|
|
963
|
+
return void 0;
|
|
964
|
+
}
|
|
965
|
+
await this.checkResponse(response);
|
|
966
|
+
this.captureSession(response);
|
|
967
|
+
const type = contentType(response);
|
|
968
|
+
if (type !== "text/event-stream" || !response.body) {
|
|
969
|
+
await discard(response);
|
|
970
|
+
throw new McpHttpError(response.status, `Unsupported MCP GET response content type: ${type ?? "missing"}`);
|
|
971
|
+
}
|
|
972
|
+
return response.body;
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Network failures and transient statuses are retried; auth, session, and protocol errors are not.
|
|
976
|
+
* `fetch` reports network failures, including a connection dropped mid-body, as `TypeError`.
|
|
977
|
+
*/
|
|
978
|
+
isRetryable(error) {
|
|
979
|
+
if (error instanceof McpHttpError)
|
|
980
|
+
return isTransientStatus(error.status);
|
|
981
|
+
if (error instanceof TypeError)
|
|
982
|
+
return true;
|
|
983
|
+
const code = error?.code;
|
|
984
|
+
return typeof code === "string" && (code.startsWith("E") || code.startsWith("UND_ERR"));
|
|
985
|
+
}
|
|
986
|
+
reconnectDelay(attempt, serverDelayMs) {
|
|
987
|
+
if (serverDelayMs !== void 0)
|
|
988
|
+
return serverDelayMs;
|
|
989
|
+
const initial = this.options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS;
|
|
990
|
+
return Math.min(initial * 2 ** attempt, this.maxDelay());
|
|
991
|
+
}
|
|
992
|
+
maxDelay() {
|
|
993
|
+
return this.options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;
|
|
994
|
+
}
|
|
995
|
+
maxRetries() {
|
|
996
|
+
return this.options.reconnect?.maxRetries ?? DEFAULT_RECONNECT_MAX_RETRIES;
|
|
997
|
+
}
|
|
998
|
+
/** Resolves false when the transport closed while waiting. */
|
|
999
|
+
sleep(ms) {
|
|
1000
|
+
const signal = this.controller.signal;
|
|
1001
|
+
if (signal.aborted)
|
|
1002
|
+
return Promise.resolve(false);
|
|
1003
|
+
return new Promise((resolve) => {
|
|
1004
|
+
const onAbort = () => {
|
|
1005
|
+
clearTimeout(timer);
|
|
1006
|
+
resolve(false);
|
|
1007
|
+
};
|
|
1008
|
+
const timer = setTimeout(() => {
|
|
1009
|
+
signal.removeEventListener("abort", onAbort);
|
|
1010
|
+
resolve(true);
|
|
1011
|
+
}, ms);
|
|
1012
|
+
timer.unref?.();
|
|
1013
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
};
|
|
1017
|
+
|
|
1018
|
+
// src/mcp/pi-mcp-runtime.ts
|
|
1019
|
+
var TRANSIENT_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
1020
|
+
var READ_RETRY_DELAYS_MS = [250, 1e3];
|
|
1021
|
+
function pause(ms, deadline, signal) {
|
|
1022
|
+
const wait = deadline === void 0 ? ms : Math.min(ms, deadline - Date.now());
|
|
1023
|
+
return new Promise((resolve) => {
|
|
1024
|
+
const timer = setTimeout(done, Math.max(0, wait));
|
|
1025
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
1026
|
+
function done() {
|
|
1027
|
+
clearTimeout(timer);
|
|
1028
|
+
signal?.removeEventListener("abort", done);
|
|
1029
|
+
resolve();
|
|
1030
|
+
}
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
function interpolateEnv(value, env) {
|
|
1034
|
+
return value.replace(
|
|
1035
|
+
/\$\{([A-Z0-9_]+)\}/gi,
|
|
1036
|
+
(_match, name) => env[name] ?? ""
|
|
1037
|
+
);
|
|
1038
|
+
}
|
|
1039
|
+
function describedError(error, server) {
|
|
1040
|
+
if (error instanceof McpHttpError) {
|
|
1041
|
+
return Object.assign(
|
|
1042
|
+
new Error(`HTTP ${error.status}: ${error.message}`, { cause: error }),
|
|
1043
|
+
{
|
|
1044
|
+
code: error.status
|
|
1045
|
+
}
|
|
1046
|
+
);
|
|
1047
|
+
}
|
|
1048
|
+
if (error instanceof Error && !(error instanceof McpConnectionClosedError))
|
|
1049
|
+
return error;
|
|
1050
|
+
return new Error(
|
|
1051
|
+
`MCP server '${server}' closed the connection: ${error instanceof Error ? error.message : String(error)}`,
|
|
1052
|
+
{ cause: error }
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
function notRun(error) {
|
|
1056
|
+
return error instanceof McpSessionExpiredError;
|
|
1057
|
+
}
|
|
1058
|
+
function transient(error) {
|
|
1059
|
+
return error instanceof McpHttpError && TRANSIENT_STATUSES.has(error.status) || error instanceof McpConnectionClosedError || error instanceof TypeError;
|
|
1060
|
+
}
|
|
1061
|
+
var ServerConnection = class {
|
|
1062
|
+
constructor(id, config, env) {
|
|
1063
|
+
this.id = id;
|
|
1064
|
+
this.config = config;
|
|
1065
|
+
this.env = env;
|
|
1066
|
+
}
|
|
1067
|
+
id;
|
|
1068
|
+
config;
|
|
1069
|
+
env;
|
|
1070
|
+
client;
|
|
1071
|
+
connected;
|
|
1072
|
+
connect() {
|
|
1073
|
+
this.client ??= (async () => {
|
|
1074
|
+
const client = new McpClient({
|
|
1075
|
+
name: "introspection-recipes",
|
|
1076
|
+
version: "1"
|
|
1077
|
+
});
|
|
1078
|
+
client.onClose(() => this.drop(client));
|
|
1079
|
+
await client.connect(
|
|
1080
|
+
new StreamableHttpTransport({
|
|
1081
|
+
url: this.config.baseUrl,
|
|
1082
|
+
headers: Object.fromEntries(
|
|
1083
|
+
Object.entries(this.config.headers ?? {}).map(([name, value]) => [
|
|
1084
|
+
name,
|
|
1085
|
+
interpolateEnv(value, this.env)
|
|
1086
|
+
])
|
|
1087
|
+
)
|
|
1088
|
+
})
|
|
1089
|
+
);
|
|
1090
|
+
this.connected = client;
|
|
1091
|
+
return client;
|
|
1092
|
+
})().catch((error) => {
|
|
1093
|
+
this.client = void 0;
|
|
1094
|
+
throw error;
|
|
1095
|
+
});
|
|
1096
|
+
return this.client;
|
|
1097
|
+
}
|
|
1098
|
+
/** Forgets `client`, so the next request connects afresh. A failed connect clears itself. */
|
|
1099
|
+
drop(client) {
|
|
1100
|
+
if (this.connected !== client) return;
|
|
1101
|
+
this.connected = void 0;
|
|
1102
|
+
this.client = void 0;
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* Runs `request` on a live connection, connecting first if needed. What was
|
|
1106
|
+
* never sent is retried: a failed connect, and a request whose MCP session
|
|
1107
|
+
* had expired. A read is also retried after a transient failure. A
|
|
1108
|
+
* `tools/call` that may have run is never sent twice.
|
|
1109
|
+
*/
|
|
1110
|
+
async request(read, request, bounds = {}) {
|
|
1111
|
+
const { deadline, signal } = bounds;
|
|
1112
|
+
const remaining = () => {
|
|
1113
|
+
if (signal?.aborted)
|
|
1114
|
+
throw describedError(signal.reason ?? new Error("aborted"), this.id);
|
|
1115
|
+
if (deadline === void 0) return void 0;
|
|
1116
|
+
const left = deadline - Date.now();
|
|
1117
|
+
if (left <= 0)
|
|
1118
|
+
throw new Error(
|
|
1119
|
+
`MCP call to '${this.id}' timed out before it could be sent`
|
|
1120
|
+
);
|
|
1121
|
+
return left;
|
|
1122
|
+
};
|
|
1123
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
1124
|
+
remaining();
|
|
1125
|
+
let client;
|
|
1126
|
+
try {
|
|
1127
|
+
client = await this.connect();
|
|
1128
|
+
} catch (error) {
|
|
1129
|
+
const answeredTransient = error instanceof McpHttpError && TRANSIENT_STATUSES.has(error.status);
|
|
1130
|
+
if (!answeredTransient || attempt >= READ_RETRY_DELAYS_MS.length) {
|
|
1131
|
+
throw describedError(error, this.id);
|
|
1132
|
+
}
|
|
1133
|
+
await pause(READ_RETRY_DELAYS_MS[attempt], deadline, signal);
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
try {
|
|
1137
|
+
return await request(client, remaining());
|
|
1138
|
+
} catch (error) {
|
|
1139
|
+
if (notRun(error) || error instanceof McpConnectionClosedError || error instanceof TypeError) {
|
|
1140
|
+
this.drop(client);
|
|
1141
|
+
void client.close().catch(() => {
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
if (notRun(error) && attempt === 0) continue;
|
|
1145
|
+
if (read && transient(error) && attempt < READ_RETRY_DELAYS_MS.length) {
|
|
1146
|
+
await pause(READ_RETRY_DELAYS_MS[attempt], deadline, signal);
|
|
1147
|
+
continue;
|
|
1148
|
+
}
|
|
1149
|
+
throw describedError(error, this.id);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
async close() {
|
|
1154
|
+
const client = this.client;
|
|
1155
|
+
this.client = void 0;
|
|
1156
|
+
this.connected = void 0;
|
|
1157
|
+
await client?.then((value) => value.close()).catch(() => {
|
|
1158
|
+
});
|
|
1159
|
+
}
|
|
1160
|
+
};
|
|
1161
|
+
var PiMcpRuntime = class _PiMcpRuntime {
|
|
1162
|
+
constructor(config, env = process.env) {
|
|
1163
|
+
this.config = config;
|
|
1164
|
+
this.env = env;
|
|
1165
|
+
for (const [id, server] of Object.entries(config.mcpServers)) {
|
|
1166
|
+
if (server.auth === "oauth") {
|
|
1167
|
+
throw new Error(
|
|
1168
|
+
`MCP server '${id}' is bound with an OAuth flow, which the pi-mcp client does not run; set ${MCP_CLIENT_ENV}=mcporter to use mcporter for it`
|
|
1169
|
+
);
|
|
1170
|
+
}
|
|
1171
|
+
this.servers.set(id, new ServerConnection(id, server, env));
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
config;
|
|
1175
|
+
env;
|
|
1176
|
+
servers = /* @__PURE__ */ new Map();
|
|
1177
|
+
static fromConfigFile(path = process.env.MCPORTER_CONFIG, env = process.env) {
|
|
1178
|
+
if (!path)
|
|
1179
|
+
throw new Error(
|
|
1180
|
+
"MCPORTER_CONFIG is not set; the MCP session has no server config"
|
|
1181
|
+
);
|
|
1182
|
+
return new _PiMcpRuntime(
|
|
1183
|
+
JSON.parse(readFileSync(path, "utf8")),
|
|
1184
|
+
env
|
|
1185
|
+
);
|
|
1186
|
+
}
|
|
1187
|
+
listServers() {
|
|
1188
|
+
return [...this.servers.keys()];
|
|
1189
|
+
}
|
|
1190
|
+
server(id) {
|
|
1191
|
+
const server = this.servers.get(id);
|
|
1192
|
+
if (!server) throw new Error(`Unknown MCP server '${id}'`);
|
|
1193
|
+
return server;
|
|
1194
|
+
}
|
|
1195
|
+
async listTools(server, _options) {
|
|
1196
|
+
const tools = await this.server(server).request(
|
|
1197
|
+
true,
|
|
1198
|
+
(client) => client.listTools()
|
|
1199
|
+
);
|
|
1200
|
+
const allowed = this.config.mcpServers[server]?.allowedTools;
|
|
1201
|
+
return allowed ? tools.filter((tool) => allowed.includes(tool.name)) : tools;
|
|
1202
|
+
}
|
|
1203
|
+
async callTool(server, tool, options = {}) {
|
|
1204
|
+
const allowed = this.config.mcpServers[server]?.allowedTools;
|
|
1205
|
+
if (allowed && !allowed.includes(tool)) {
|
|
1206
|
+
throw new Error(
|
|
1207
|
+
`MCP tool '${server}.${tool}' is not in this session's allowed tools.`
|
|
1208
|
+
);
|
|
1209
|
+
}
|
|
1210
|
+
const deadline = options.timeoutMs ? Date.now() + options.timeoutMs : void 0;
|
|
1211
|
+
return await this.server(server).request(
|
|
1212
|
+
false,
|
|
1213
|
+
(client, remainingMs) => client.callTool(tool, options.args ?? {}, {
|
|
1214
|
+
...remainingMs !== void 0 ? { timeoutMs: remainingMs } : {},
|
|
1215
|
+
...options.signal ? { signal: options.signal } : {}
|
|
1216
|
+
}),
|
|
1217
|
+
{
|
|
1218
|
+
...deadline !== void 0 ? { deadline } : {},
|
|
1219
|
+
...options.signal ? { signal: options.signal } : {}
|
|
1220
|
+
}
|
|
1221
|
+
);
|
|
1222
|
+
}
|
|
1223
|
+
async close() {
|
|
1224
|
+
await Promise.all(
|
|
1225
|
+
[...this.servers.values()].map((server) => server.close())
|
|
1226
|
+
);
|
|
1227
|
+
}
|
|
1228
|
+
};
|
|
1229
|
+
export {
|
|
1230
|
+
PiMcpRuntime
|
|
1231
|
+
};
|