coremind-tools 1.0.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +2 -0
  2. package/dist/file-target.d.ts +2 -0
  3. package/dist/file-target.d.ts.map +1 -1
  4. package/dist/file-target.js +25 -1
  5. package/dist/file-target.js.map +1 -1
  6. package/dist/git-adapter.d.ts +1 -1
  7. package/dist/git-adapter.d.ts.map +1 -1
  8. package/dist/git-adapter.js +1 -1
  9. package/dist/git-adapter.js.map +1 -1
  10. package/dist/host-shell.d.ts +3 -3
  11. package/dist/host-shell.d.ts.map +1 -1
  12. package/dist/host-shell.js.map +1 -1
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/internal.d.ts +6 -2
  17. package/dist/internal.d.ts.map +1 -1
  18. package/dist/internal.js +5 -2
  19. package/dist/internal.js.map +1 -1
  20. package/dist/linux-sandbox-backend.d.ts +33 -0
  21. package/dist/linux-sandbox-backend.d.ts.map +1 -0
  22. package/dist/linux-sandbox-backend.js +119 -0
  23. package/dist/linux-sandbox-backend.js.map +1 -0
  24. package/dist/linux-sandbox.d.ts +5 -5
  25. package/dist/linux-sandbox.d.ts.map +1 -1
  26. package/dist/linux-sandbox.js +5 -19
  27. package/dist/linux-sandbox.js.map +1 -1
  28. package/dist/mcp-authentication-types.d.ts +49 -0
  29. package/dist/mcp-authentication-types.d.ts.map +1 -0
  30. package/dist/mcp-authentication-types.js +2 -0
  31. package/dist/mcp-authentication-types.js.map +1 -0
  32. package/dist/mcp-authentication.d.ts +26 -0
  33. package/dist/mcp-authentication.d.ts.map +1 -0
  34. package/dist/mcp-authentication.js +702 -0
  35. package/dist/mcp-authentication.js.map +1 -0
  36. package/dist/mcp-client.d.ts +74 -0
  37. package/dist/mcp-client.d.ts.map +1 -0
  38. package/dist/mcp-client.js +399 -0
  39. package/dist/mcp-client.js.map +1 -0
  40. package/dist/mcp-http-client.d.ts +18 -0
  41. package/dist/mcp-http-client.d.ts.map +1 -0
  42. package/dist/mcp-http-client.js +21 -0
  43. package/dist/mcp-http-client.js.map +1 -0
  44. package/dist/mcp-http-fetch.d.ts +54 -0
  45. package/dist/mcp-http-fetch.d.ts.map +1 -0
  46. package/dist/mcp-http-fetch.js +603 -0
  47. package/dist/mcp-http-fetch.js.map +1 -0
  48. package/dist/mcp-http-transport.d.ts +31 -0
  49. package/dist/mcp-http-transport.d.ts.map +1 -0
  50. package/dist/mcp-http-transport.js +179 -0
  51. package/dist/mcp-http-transport.js.map +1 -0
  52. package/dist/mcp-stdio-client.d.ts +30 -0
  53. package/dist/mcp-stdio-client.d.ts.map +1 -0
  54. package/dist/mcp-stdio-client.js +17 -0
  55. package/dist/mcp-stdio-client.js.map +1 -0
  56. package/dist/mcp-stdio-error.d.ts +6 -0
  57. package/dist/mcp-stdio-error.d.ts.map +1 -0
  58. package/dist/mcp-stdio-error.js +10 -0
  59. package/dist/mcp-stdio-error.js.map +1 -0
  60. package/dist/mcp-stdio-transport.d.ts +41 -0
  61. package/dist/mcp-stdio-transport.d.ts.map +1 -0
  62. package/dist/mcp-stdio-transport.js +294 -0
  63. package/dist/mcp-stdio-transport.js.map +1 -0
  64. package/dist/platform-execution-environment.d.ts.map +1 -1
  65. package/dist/platform-execution-environment.js +3 -3
  66. package/dist/platform-execution-environment.js.map +1 -1
  67. package/dist/registry.d.ts +4 -0
  68. package/dist/registry.d.ts.map +1 -1
  69. package/dist/registry.js +21 -3
  70. package/dist/registry.js.map +1 -1
  71. package/dist/script-tool.d.ts +1 -1
  72. package/dist/script-tool.d.ts.map +1 -1
  73. package/dist/script-tool.js +4 -2
  74. package/dist/script-tool.js.map +1 -1
  75. package/dist/vendor/linux-sandbox/LICENSE +201 -0
  76. package/dist/vendor/linux-sandbox/backend.d.mts +13 -0
  77. package/dist/vendor/linux-sandbox/backend.mjs +1264 -0
  78. package/dist/vendor/linux-sandbox/bin/arm64/apply-seccomp +0 -0
  79. package/dist/vendor/linux-sandbox/bin/x64/apply-seccomp +0 -0
  80. package/dist/vendor/linux-sandbox/manifest.json +38 -0
  81. package/dist/vendor/linux-sandbox/metafile.json +320 -0
  82. package/dist/vendor/linux-sandbox/musl-COPYRIGHT +193 -0
  83. package/dist/vendor/windows-mcp/THIRD-PARTY-LICENSES.txt +408 -0
  84. package/dist/vendor/windows-mcp/guard.dll +0 -0
  85. package/dist/vendor/windows-mcp/host.exe +0 -0
  86. package/dist/vendor/windows-mcp/manifest.json +325 -0
  87. package/dist/vendor/windows-mcp/metafile.json +3894 -0
  88. package/dist/vendor/windows-mcp/service.mjs +7446 -0
  89. package/dist/web-tools.d.ts +1 -1
  90. package/dist/web-tools.d.ts.map +1 -1
  91. package/dist/web-tools.js +11 -3
  92. package/dist/web-tools.js.map +1 -1
  93. package/dist/windows-mcp-job.d.ts +20 -0
  94. package/dist/windows-mcp-job.d.ts.map +1 -0
  95. package/dist/windows-mcp-job.js +353 -0
  96. package/dist/windows-mcp-job.js.map +1 -0
  97. package/dist/windows-mcp-service-identity.d.ts +6 -0
  98. package/dist/windows-mcp-service-identity.d.ts.map +1 -0
  99. package/dist/windows-mcp-service-identity.js +7 -0
  100. package/dist/windows-mcp-service-identity.js.map +1 -0
  101. package/dist/windows-mcp-service.d.mts +2 -0
  102. package/dist/windows-mcp-service.d.mts.map +1 -0
  103. package/dist/windows-mcp-service.mjs +110 -0
  104. package/dist/windows-mcp-service.mjs.map +1 -0
  105. package/package.json +10 -8
@@ -0,0 +1,54 @@
1
+ import type { FetchLike } from "@modelcontextprotocol/client";
2
+ import { type ExecutionEnvironment } from "./execution-environment.js";
3
+ import type { McpAuthenticationBinding } from "./mcp-authentication.js";
4
+ export interface McpHttpTransportOptions {
5
+ readonly url: string;
6
+ readonly allowedAddresses?: readonly string[];
7
+ readonly headers: Readonly<Record<string, string>>;
8
+ readonly runEnvironment: ExecutionEnvironment;
9
+ readonly signal?: AbortSignal;
10
+ readonly sensitiveValues?: readonly string[];
11
+ readonly authentication?: McpAuthenticationBinding;
12
+ }
13
+ export interface McpHttpDomainSummary {
14
+ readonly isolation: "trusted_host";
15
+ readonly processControl: "none";
16
+ readonly networkEgress: "adapter_scoped";
17
+ readonly credentialIsolation: "none";
18
+ readonly platform: NodeJS.Platform;
19
+ readonly evidence: readonly string[];
20
+ }
21
+ /** 固定目标的私有网络 owner;构造不解析域名、不创建连接。 */
22
+ export declare function createMcpHttpFetch(options: McpHttpTransportOptions): McpHttpFetchOwner;
23
+ export declare class McpHttpFetchOwner {
24
+ private readonly options;
25
+ environmentSummary: McpHttpDomainSummary | undefined;
26
+ readonly fetch: FetchLike;
27
+ private readonly url;
28
+ private readonly headers;
29
+ private readonly allowed;
30
+ private readonly secrets;
31
+ private readonly controller;
32
+ private readonly requests;
33
+ private agent?;
34
+ private closing?;
35
+ private bytes;
36
+ private gets;
37
+ private firstGet?;
38
+ private fatal?;
39
+ constructor(options: McpHttpTransportOptions);
40
+ get remainingGetWindowMs(): number;
41
+ get closed(): boolean;
42
+ close(): Promise<void>;
43
+ private closeOwned;
44
+ private request;
45
+ private readonly lookup;
46
+ private checkOpen;
47
+ private assertSafe;
48
+ private normalize;
49
+ private fail;
50
+ }
51
+ export declare function isMcpHttpFatalError(error: unknown): boolean;
52
+ /** 返回规范化 socket 地址;映射 IPv4 与普通 IPv4 使用同一权限身份。 */
53
+ export declare function validateMcpHttpAddress(address: string, protocol: string, allowed: readonly string[]): string;
54
+ //# sourceMappingURL=mcp-http-fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-http-fetch.d.ts","sourceRoot":"","sources":["../src/mcp-http-fetch.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,EACL,KAAK,oBAAoB,EAG1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AA4BxE,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9C,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD,QAAQ,CAAC,cAAc,EAAE,oBAAoB,CAAC;IAC9C,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;IAC9B,QAAQ,CAAC,eAAe,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7C,QAAQ,CAAC,cAAc,CAAC,EAAE,wBAAwB,CAAC;CACpD;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC;IACnC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,aAAa,EAAE,gBAAgB,CAAC;IACzC,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC;IACnC,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;CACtC;AAQD,qCAAqC;AACrC,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,uBAAuB,GAAG,iBAAiB,CAEtF;AAED,qBAAa,iBAAiB;IAgBhB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAfpC,kBAAkB,EAAE,oBAAoB,GAAG,SAAS,CAAC;IACrD,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;IAC1B,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAM;IAC1B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAU;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;IAC5C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;IAC5C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAyB;IACpD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA2B;IACpD,OAAO,CAAC,KAAK,CAAC,CAAa;IAC3B,OAAO,CAAC,OAAO,CAAC,CAAgB;IAChC,OAAO,CAAC,KAAK,CAAK;IAClB,OAAO,CAAC,IAAI,CAAK;IACjB,OAAO,CAAC,QAAQ,CAAC,CAAS;IAC1B,OAAO,CAAC,KAAK,CAAC,CAAgB;gBAED,OAAO,EAAE,uBAAuB;IA8B7D,IAAI,oBAAoB,IAAI,MAAM,CAIjC;IAED,IAAI,MAAM,IAAI,OAAO,CAIpB;IAED,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;YAKR,UAAU;YAYV,OAAO;IA+RrB,OAAO,CAAC,QAAQ,CAAC,MAAM,CA0BrB;IAEF,OAAO,CAAC,SAAS;IAOjB,OAAO,CAAC,UAAU;IAMlB,OAAO,CAAC,SAAS;IAQjB,OAAO,CAAC,IAAI;CAKb;AAgCD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAW3D;AAwCD,iDAAiD;AACjD,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,SAAS,MAAM,EAAE,GACzB,MAAM,CAkDR"}
@@ -0,0 +1,603 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import dns from "node:dns/promises";
3
+ import { isIP } from "node:net";
4
+ import { ReadableStream } from "node:stream/web";
5
+ import { TextDecoder } from "node:util";
6
+ import { resolveExecutionEnvironment, } from "./execution-environment.js";
7
+ import { McpStdioError } from "./mcp-stdio-transport.js";
8
+ const MAX_BODY_BYTES = 8 * 1024 * 1024;
9
+ const MAX_OWNER_BYTES = 64 * 1024 * 1024;
10
+ const MAX_GETS = 3;
11
+ const GET_WINDOW_MS = 30_000;
12
+ const RESERVED_HEADERS = new Set([
13
+ "host",
14
+ "connection",
15
+ "proxy-authorization",
16
+ "proxy-connection",
17
+ "keep-alive",
18
+ "te",
19
+ "trailer",
20
+ "upgrade",
21
+ "dpop",
22
+ "content-length",
23
+ "transfer-encoding",
24
+ "content-type",
25
+ "accept",
26
+ "mcp-session-id",
27
+ "mcp-protocol-version",
28
+ "mcp-method",
29
+ "mcp-name",
30
+ "last-event-id",
31
+ ]);
32
+ /** 固定目标的私有网络 owner;构造不解析域名、不创建连接。 */
33
+ export function createMcpHttpFetch(options) {
34
+ return new McpHttpFetchOwner(options);
35
+ }
36
+ export class McpHttpFetchOwner {
37
+ options;
38
+ environmentSummary;
39
+ fetch;
40
+ url;
41
+ headers;
42
+ allowed;
43
+ secrets;
44
+ controller = new AbortController();
45
+ requests = new Set();
46
+ agent;
47
+ closing;
48
+ bytes = 0;
49
+ gets = 0;
50
+ firstGet;
51
+ fatal;
52
+ constructor(options) {
53
+ this.options = options;
54
+ this.url = parseTarget(options.url);
55
+ this.allowed = Object.freeze((options.allowedAddresses ?? []).map(normalizeAddress));
56
+ this.secrets = Object.freeze((options.sensitiveValues ?? []).filter(Boolean));
57
+ try {
58
+ this.headers = new Headers();
59
+ const names = new Set();
60
+ for (const [name, value] of Object.entries(options.headers)) {
61
+ const folded = name.toLowerCase();
62
+ if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(name) ||
63
+ names.has(folded) ||
64
+ RESERVED_HEADERS.has(folded) ||
65
+ typeof value !== "string" ||
66
+ [...value].some((character) => {
67
+ const code = character.charCodeAt(0);
68
+ return (code < 32 && code !== 9) || code === 127;
69
+ }))
70
+ throw policy();
71
+ names.add(folded);
72
+ this.headers.append(name, value);
73
+ }
74
+ if (Buffer.byteLength(JSON.stringify([...this.headers]), "utf8") > 16 * 1024)
75
+ throw policy();
76
+ }
77
+ catch {
78
+ throw policy();
79
+ }
80
+ this.fetch = (input, init) => this.request(input, init);
81
+ }
82
+ get remainingGetWindowMs() {
83
+ return this.firstGet === undefined
84
+ ? GET_WINDOW_MS
85
+ : Math.max(0, GET_WINDOW_MS - (performance.now() - this.firstGet));
86
+ }
87
+ get closed() {
88
+ return Boolean(this.fatal || this.closing || this.controller.signal.aborted || this.options.signal?.aborted);
89
+ }
90
+ close() {
91
+ if (!this.closing)
92
+ this.closing = this.closeOwned();
93
+ return this.closing;
94
+ }
95
+ async closeOwned() {
96
+ this.controller.abort();
97
+ const requests = [...this.requests];
98
+ const results = await Promise.allSettled([
99
+ ...requests.map((request) => request.cancel()),
100
+ ...(this.agent ? [this.agent.destroy()] : []),
101
+ ]);
102
+ await Promise.all(requests.map((request) => request.done));
103
+ if (results.some((result) => result.status === "rejected"))
104
+ throw new McpStdioError("mcp_cleanup_failed", "远程连接未能完整关闭");
105
+ }
106
+ async request(input, init = {}) {
107
+ this.checkOpen();
108
+ let target;
109
+ try {
110
+ target = new URL(input);
111
+ }
112
+ catch {
113
+ throw policy();
114
+ }
115
+ if (target.href !== this.url.href)
116
+ throw policy();
117
+ const method = (init.method ?? "GET").toUpperCase();
118
+ if (method !== "GET" && method !== "POST")
119
+ throw policy();
120
+ if (method === "GET") {
121
+ this.firstGet ??= performance.now();
122
+ if (this.gets >= MAX_GETS || this.remainingGetWindowMs <= 0)
123
+ throw this.fail(new McpStdioError("mcp_http_limit_exceeded", "远程事件恢复预算已用尽"));
124
+ this.gets += 1;
125
+ }
126
+ const hostname = this.url.hostname.replace(/^\[|\]$/g, "");
127
+ if (isIP(hostname))
128
+ validateMcpHttpAddress(hostname, this.url.protocol, this.allowed);
129
+ const headers = new Headers(init.headers);
130
+ for (const [name, value] of this.headers) {
131
+ if (headers.has(name) && headers.get(name) !== value)
132
+ throw policy();
133
+ headers.set(name, value);
134
+ }
135
+ if ([
136
+ "host",
137
+ "content-length",
138
+ "transfer-encoding",
139
+ "connection",
140
+ "keep-alive",
141
+ "te",
142
+ "trailer",
143
+ "upgrade",
144
+ "proxy-authorization",
145
+ "proxy-connection",
146
+ "dpop",
147
+ ].some((name) => headers.has(name)))
148
+ throw policy();
149
+ if (typeof init.body === "string" && Buffer.byteLength(init.body, "utf8") > MAX_BODY_BYTES)
150
+ throw this.fail(new McpStdioError("mcp_http_limit_exceeded", "远程请求超过上限"));
151
+ const activities = [];
152
+ const requestController = new AbortController();
153
+ const signal = AbortSignal.any([
154
+ this.controller.signal,
155
+ requestController.signal,
156
+ ...(this.options.authentication ? [this.options.authentication.signal] : []),
157
+ ...(this.options.signal ? [this.options.signal] : []),
158
+ ...(init.signal ? [init.signal] : []),
159
+ ]);
160
+ let settle;
161
+ const done = new Promise((resolve) => {
162
+ settle = resolve;
163
+ });
164
+ let finished = false;
165
+ let reader;
166
+ let output;
167
+ const finish = () => {
168
+ if (finished)
169
+ return;
170
+ finished = true;
171
+ signal.removeEventListener("abort", aborted);
172
+ for (const activity of activities)
173
+ activity.settle();
174
+ this.requests.delete(owned);
175
+ settle();
176
+ };
177
+ const cancel = async () => {
178
+ requestController.abort();
179
+ if (reader) {
180
+ try {
181
+ await reader.cancel();
182
+ }
183
+ catch {
184
+ /* 取消后的管道错误不携带远端原文。 */
185
+ }
186
+ finish();
187
+ }
188
+ };
189
+ const owned = { controller: requestController, done, cancel };
190
+ const aborted = () => {
191
+ try {
192
+ output?.error(this.fatal ?? cancelled());
193
+ }
194
+ catch {
195
+ /* 已结算的流无需重复报错。 */
196
+ }
197
+ if (reader)
198
+ void cancel();
199
+ };
200
+ this.requests.add(owned);
201
+ signal.addEventListener("abort", aborted, { once: true });
202
+ try {
203
+ const domain = this.options.runEnvironment.hostNetwork ?? this.options.runEnvironment;
204
+ activities.push(this.options.runEnvironment.beginActivity({
205
+ id: `mcp-http-run:${randomUUID()}`,
206
+ kind: "network",
207
+ }));
208
+ if (domain !== this.options.runEnvironment)
209
+ activities.push(domain.beginActivity({ id: `mcp-http-domain:${randomUUID()}`, kind: "network" }));
210
+ for (const activity of activities) {
211
+ if (activity.signal.aborted)
212
+ requestController.abort();
213
+ else
214
+ activity.signal.addEventListener("abort", () => requestController.abort(), {
215
+ once: true,
216
+ signal,
217
+ });
218
+ }
219
+ const resolved = await resolveExecutionEnvironment(domain, {});
220
+ if (resolved.capabilities.networkEgress !== "unrestricted")
221
+ throw policy();
222
+ this.checkOpen();
223
+ if (signal.aborted)
224
+ throw cancelled();
225
+ if (this.options.authentication) {
226
+ if (headers.has("authorization"))
227
+ throw policy();
228
+ const token = await this.options.authentication.authorize(signal);
229
+ this.checkOpen();
230
+ if (signal.aborted)
231
+ throw cancelled();
232
+ headers.set("authorization", `Bearer ${token}`);
233
+ }
234
+ this.environmentSummary = Object.freeze({
235
+ isolation: "trusted_host",
236
+ processControl: "none",
237
+ networkEgress: "adapter_scoped",
238
+ credentialIsolation: "none",
239
+ platform: resolved.capabilities.identity.platform,
240
+ evidence: Object.freeze([
241
+ ...resolved.evidence,
242
+ "fixed-target-socket-address-validation",
243
+ "private-http-dispatcher",
244
+ ]),
245
+ });
246
+ const { Agent: HttpAgent, fetch: dispatchFetch } = await import("undici");
247
+ this.checkOpen();
248
+ if (signal.aborted)
249
+ throw cancelled();
250
+ this.agent ??= new HttpAgent({
251
+ connections: 8,
252
+ pipelining: 1,
253
+ maxOrigins: 1,
254
+ allowH2: false,
255
+ headersTimeout: 30_000,
256
+ bodyTimeout: 30_000,
257
+ connectTimeout: 10_000,
258
+ maxHeaderSize: 16 * 1024,
259
+ connect: { lookup: this.lookup, autoSelectFamily: false },
260
+ }).compose(preventMisdirectedReplay);
261
+ const response = await dispatchFetch(this.url, {
262
+ method,
263
+ headers: Array.from(headers),
264
+ body: init.body,
265
+ signal,
266
+ redirect: "manual",
267
+ dispatcher: this.agent,
268
+ });
269
+ if (response.status >= 300 && response.status < 400) {
270
+ await response.body?.cancel();
271
+ throw policy();
272
+ }
273
+ if (!response.ok) {
274
+ await response.body?.cancel();
275
+ throw new McpStdioError(response.status === 401 || response.status === 403
276
+ ? this.options.authentication
277
+ ? "mcp_auth_required"
278
+ : "mcp_http_auth_required"
279
+ : "mcp_http_status_error", response.status === 401 || response.status === 403
280
+ ? "远程服务拒绝当前凭证"
281
+ : "远程服务返回失败状态");
282
+ }
283
+ this.assertSafe(JSON.stringify([...response.headers]));
284
+ for (const [name, value] of response.headers) {
285
+ this.assertSafe(name);
286
+ this.assertSafe(value);
287
+ }
288
+ if (!response.body) {
289
+ finish();
290
+ return new Response(null, { status: response.status, headers: response.headers });
291
+ }
292
+ reader = response.body.getReader();
293
+ if (signal.aborted)
294
+ throw cancelled();
295
+ let bodyBytes = 0;
296
+ let eventBytes = 0;
297
+ let lineBytes = 0;
298
+ let previousCr = false;
299
+ let tail = "";
300
+ const decoder = new TextDecoder("utf-8", { fatal: true });
301
+ const overlap = Math.max(0, ...this.secrets.map((value) => value.length - 1),
302
+ // 在飞响应也须认识之后轮换的新令牌,保留有界的最大重叠长度。
303
+ (this.options.authentication?.maxSecretLength ?? 1) - 1);
304
+ const sse = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ===
305
+ "text/event-stream";
306
+ const body = new ReadableStream({
307
+ start: (controller) => {
308
+ output = controller;
309
+ },
310
+ pull: async (controller) => {
311
+ try {
312
+ if (signal.aborted)
313
+ throw this.fatal ?? cancelled();
314
+ const result = await reader.read();
315
+ if (result.done) {
316
+ let end;
317
+ try {
318
+ end = decoder.decode();
319
+ }
320
+ catch {
321
+ throw invalidUtf8();
322
+ }
323
+ this.assertSafe(tail + end);
324
+ finish();
325
+ controller.close();
326
+ return;
327
+ }
328
+ bodyBytes += result.value.byteLength;
329
+ this.bytes += result.value.byteLength;
330
+ if (bodyBytes > MAX_BODY_BYTES || this.bytes > MAX_OWNER_BYTES)
331
+ throw new McpStdioError("mcp_http_limit_exceeded", "远程响应超过上限");
332
+ if (sse)
333
+ for (const byte of result.value) {
334
+ eventBytes += 1;
335
+ if (eventBytes > MAX_BODY_BYTES)
336
+ throw new McpStdioError("mcp_http_limit_exceeded", "远程事件超过上限");
337
+ if (byte === 10 && previousCr) {
338
+ previousCr = false;
339
+ continue;
340
+ }
341
+ if (byte === 10 || byte === 13) {
342
+ if (lineBytes === 0)
343
+ eventBytes = 0;
344
+ lineBytes = 0;
345
+ previousCr = byte === 13;
346
+ }
347
+ else {
348
+ lineBytes += 1;
349
+ previousCr = false;
350
+ }
351
+ }
352
+ let text;
353
+ try {
354
+ text = decoder.decode(result.value, { stream: true });
355
+ }
356
+ catch {
357
+ throw invalidUtf8();
358
+ }
359
+ this.assertSafe(tail + text);
360
+ tail = overlap ? (tail + text).slice(-overlap) : "";
361
+ controller.enqueue(result.value);
362
+ }
363
+ catch (error) {
364
+ let safe = this.normalize(error, signal);
365
+ let recover = method === "GET" && sse && !signal.aborted && safe.code === "mcp_http_request_failed";
366
+ if (recover) {
367
+ try {
368
+ this.assertSafe(tail + decoder.decode());
369
+ }
370
+ catch (cause) {
371
+ safe = cause instanceof McpStdioError ? cause : invalidUtf8();
372
+ recover = false;
373
+ }
374
+ }
375
+ try {
376
+ // 仅实际 GET 事件流的网络断开交由官方 EOF 恢复;协议和安全失败仍立即失效。
377
+ if (recover)
378
+ controller.close();
379
+ else
380
+ controller.error(safe);
381
+ }
382
+ catch {
383
+ /* 取消可能已结算该流。 */
384
+ }
385
+ if (isMcpHttpFatalError(safe))
386
+ this.fail(safe);
387
+ await cancel();
388
+ }
389
+ },
390
+ cancel: async () => {
391
+ await cancel();
392
+ },
393
+ });
394
+ return new Response(body, { status: response.status, headers: response.headers });
395
+ }
396
+ catch (error) {
397
+ const safe = this.normalize(error, signal);
398
+ if (isMcpHttpFatalError(safe))
399
+ this.fail(safe);
400
+ await cancel();
401
+ finish();
402
+ throw safe;
403
+ }
404
+ }
405
+ lookup = (hostname, options, callback) => {
406
+ if (hostname !== this.url.hostname.replace(/^\[|\]$/g, "")) {
407
+ callback(policy(), "");
408
+ return;
409
+ }
410
+ void dns
411
+ .lookup(hostname, { all: true, verbatim: true })
412
+ .then((records) => {
413
+ this.checkOpen();
414
+ if (!records.length)
415
+ throw policy();
416
+ const addresses = records.map(({ address }) => {
417
+ const approved = validateMcpHttpAddress(address, this.url.protocol, this.allowed);
418
+ return { address: approved, family: isIP(approved) };
419
+ });
420
+ // 将同一次完整校验的结果直接交给 socket,不让连接再次解析域名。
421
+ if (options.all)
422
+ callback(null, addresses);
423
+ else
424
+ callback(null, addresses[0].address, addresses[0].family);
425
+ })
426
+ .catch((error) => {
427
+ const safe = error instanceof McpStdioError
428
+ ? error
429
+ : new McpStdioError("mcp_http_request_failed", "远程地址解析失败");
430
+ if (isMcpHttpFatalError(safe))
431
+ this.fail(safe);
432
+ callback(safe, "");
433
+ });
434
+ };
435
+ checkOpen() {
436
+ this.options.authentication?.assertActive();
437
+ if (this.fatal)
438
+ throw this.fatal;
439
+ if (this.closing || this.controller.signal.aborted || this.options.signal?.aborted)
440
+ throw cancelled();
441
+ }
442
+ assertSafe(text) {
443
+ this.options.authentication?.assertSafe(text);
444
+ if (this.secrets.some((secret) => text.includes(secret)))
445
+ throw new McpStdioError("mcp_secret_blocked", "远程响应包含受保护凭证");
446
+ }
447
+ normalize(error, signal) {
448
+ if (this.fatal)
449
+ return this.fatal;
450
+ if (error instanceof McpStdioError)
451
+ return error;
452
+ if (error instanceof Error && error.cause instanceof McpStdioError)
453
+ return error.cause;
454
+ if (signal.aborted)
455
+ return cancelled();
456
+ return new McpStdioError("mcp_http_request_failed", "远程连接失败,操作结果可能未知");
457
+ }
458
+ fail(error) {
459
+ this.fatal ??= error;
460
+ this.controller.abort();
461
+ return this.fatal;
462
+ }
463
+ }
464
+ // fetch 会透明重发 421;在其读取状态前中止,保证有副作用的 POST 只发送一次。
465
+ const preventMisdirectedReplay = (dispatch) => (options, handler) => dispatch(options, new Proxy(handler, {
466
+ get(target, key) {
467
+ if (key === "onResponseStart") {
468
+ const onResponseStart = (controller, status, headers, message) => {
469
+ if (status === 421) {
470
+ controller.abort(new McpStdioError("mcp_http_status_error", "远程服务返回失败状态"));
471
+ return;
472
+ }
473
+ target.onResponseStart?.(controller, status, headers, message);
474
+ };
475
+ return onResponseStart;
476
+ }
477
+ const value = Reflect.get(target, key, target);
478
+ return typeof value === "function" ? value.bind(target) : value;
479
+ },
480
+ }));
481
+ export function isMcpHttpFatalError(error) {
482
+ return (error instanceof McpStdioError &&
483
+ [
484
+ "mcp_http_policy_denied",
485
+ "mcp_http_limit_exceeded",
486
+ "mcp_secret_blocked",
487
+ "mcp_protocol_error",
488
+ "mcp_cleanup_failed",
489
+ ].includes(error.code));
490
+ }
491
+ function parseTarget(value) {
492
+ try {
493
+ if (value !== value.trim() ||
494
+ [...value].some((character) => character.charCodeAt(0) <= 32 || character.charCodeAt(0) === 127 || character === "\\"))
495
+ throw policy();
496
+ const authority = /^[^:]+:\/\/([^/?#]*)/.exec(value)?.[1];
497
+ if (!authority || authority.includes("@"))
498
+ throw policy();
499
+ const url = new URL(value);
500
+ if ((url.protocol !== "http:" && url.protocol !== "https:") ||
501
+ url.username ||
502
+ url.password ||
503
+ url.search ||
504
+ url.hash ||
505
+ value.includes("?") ||
506
+ value.includes("#"))
507
+ throw policy();
508
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
509
+ const rawHostname = authority.startsWith("[")
510
+ ? authority.slice(1, authority.indexOf("]"))
511
+ : authority.split(":", 1)[0];
512
+ if (url.protocol === "http:" &&
513
+ (!isIP(rawHostname) || !isIP(hostname) || !isLoopback(normalizeAddress(hostname))))
514
+ throw policy();
515
+ return url;
516
+ }
517
+ catch {
518
+ throw policy();
519
+ }
520
+ }
521
+ /** 返回规范化 socket 地址;映射 IPv4 与普通 IPv4 使用同一权限身份。 */
522
+ export function validateMcpHttpAddress(address, protocol, allowed) {
523
+ const normalized = normalizeAddress(address);
524
+ const family = isIP(normalized);
525
+ let privateAddress = false;
526
+ if (family === 4) {
527
+ const [a, b, c] = normalized.split(".").map(Number);
528
+ if (a === 0 || a >= 224 || (a === 169 && b === 254))
529
+ throw policy();
530
+ privateAddress =
531
+ a === 10 ||
532
+ a === 127 ||
533
+ (a === 172 && b >= 16 && b <= 31) ||
534
+ (a === 192 && b === 168) ||
535
+ (a === 100 && b >= 64 && b <= 127);
536
+ if (!privateAddress &&
537
+ ((a === 192 && b === 0 && (c === 0 || c === 2)) ||
538
+ (a === 192 && b === 88 && c === 99) ||
539
+ (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) ||
540
+ (a === 203 && b === 0 && c === 113)))
541
+ throw policy();
542
+ }
543
+ else {
544
+ const words = ipv6Words(normalized);
545
+ const first = words[0];
546
+ if (words.every((word) => word === 0) ||
547
+ (first & 0xffc0) === 0xfe80 ||
548
+ (first & 0xff00) === 0xff00)
549
+ throw policy();
550
+ privateAddress = isLoopback(normalized) || (first & 0xfe00) === 0xfc00;
551
+ if (!privateAddress &&
552
+ ((first & 0xe000) !== 0x2000 ||
553
+ (first === 0x2001 && words[1] < 0x200) ||
554
+ first === 0x2002 ||
555
+ (first === 0x2001 && words[1] === 0xdb8) ||
556
+ (first === 0x3fff && words[1] < 0x1000)))
557
+ throw policy();
558
+ }
559
+ const explicitlyAllowed = allowed.some((value) => normalizeAddress(value) === normalized);
560
+ if (allowed.length > 0 && !explicitlyAllowed)
561
+ throw policy();
562
+ if (protocol === "http:"
563
+ ? !isLoopback(normalized) || !explicitlyAllowed
564
+ : protocol !== "https:" || (privateAddress && !explicitlyAllowed))
565
+ throw policy();
566
+ return normalized;
567
+ }
568
+ function normalizeAddress(value) {
569
+ if (typeof value !== "string" || value.includes("%"))
570
+ throw policy();
571
+ const address = value.replace(/^\[|\]$/g, "");
572
+ const family = isIP(address);
573
+ if (family === 4)
574
+ return address;
575
+ if (family !== 6)
576
+ throw policy();
577
+ const canonical = new URL(`https://[${address}]/`).hostname.slice(1, -1);
578
+ const words = ipv6Words(canonical);
579
+ if (words.slice(0, 5).every((word) => word === 0) && words[5] === 0xffff)
580
+ return `${words[6] >> 8}.${words[6] & 255}.${words[7] >> 8}.${words[7] & 255}`;
581
+ return canonical;
582
+ }
583
+ function ipv6Words(address) {
584
+ const [left, right] = address.split("::");
585
+ const before = left ? left.split(":").map((value) => Number.parseInt(value, 16)) : [];
586
+ const after = right ? right.split(":").map((value) => Number.parseInt(value, 16)) : [];
587
+ return right === undefined
588
+ ? before
589
+ : [...before, ...Array(8 - before.length - after.length).fill(0), ...after];
590
+ }
591
+ function isLoopback(address) {
592
+ return address.startsWith("127.") || address === "::1";
593
+ }
594
+ function policy() {
595
+ return new McpStdioError("mcp_http_policy_denied", "远程目标或请求不符合网络授权");
596
+ }
597
+ function cancelled() {
598
+ return new McpStdioError("mcp_request_cancelled", "远程请求已取消或关闭");
599
+ }
600
+ function invalidUtf8() {
601
+ return new McpStdioError("mcp_protocol_error", "远程响应不是有效 UTF-8");
602
+ }
603
+ //# sourceMappingURL=mcp-http-fetch.js.map