@jangmanj/mcp-client 0.1.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 (253) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -0
  3. package/dist/auth/client-credentials.d.ts +54 -0
  4. package/dist/auth/client-credentials.d.ts.map +1 -0
  5. package/dist/auth/client-credentials.js +242 -0
  6. package/dist/auth/client-credentials.js.map +1 -0
  7. package/dist/auth/discovery.d.ts +27 -0
  8. package/dist/auth/discovery.d.ts.map +1 -0
  9. package/dist/auth/discovery.js +114 -0
  10. package/dist/auth/discovery.js.map +1 -0
  11. package/dist/auth/index.d.ts +10 -0
  12. package/dist/auth/index.d.ts.map +1 -0
  13. package/dist/auth/index.js +6 -0
  14. package/dist/auth/index.js.map +1 -0
  15. package/dist/auth/node-ports.d.ts +9 -0
  16. package/dist/auth/node-ports.d.ts.map +1 -0
  17. package/dist/auth/node-ports.js +68 -0
  18. package/dist/auth/node-ports.js.map +1 -0
  19. package/dist/auth/protocol.d.ts +13 -0
  20. package/dist/auth/protocol.d.ts.map +1 -0
  21. package/dist/auth/protocol.js +40 -0
  22. package/dist/auth/protocol.js.map +1 -0
  23. package/dist/auth/provider.d.ts +113 -0
  24. package/dist/auth/provider.d.ts.map +1 -0
  25. package/dist/auth/provider.js +407 -0
  26. package/dist/auth/provider.js.map +1 -0
  27. package/dist/auth/safe-fetch.d.ts +15 -0
  28. package/dist/auth/safe-fetch.d.ts.map +1 -0
  29. package/dist/auth/safe-fetch.js +131 -0
  30. package/dist/auth/safe-fetch.js.map +1 -0
  31. package/dist/core/auth-types.d.ts +37 -0
  32. package/dist/core/auth-types.d.ts.map +1 -0
  33. package/dist/core/auth-types.js +12 -0
  34. package/dist/core/auth-types.js.map +1 -0
  35. package/dist/core/bearer-challenge.d.ts +4 -0
  36. package/dist/core/bearer-challenge.d.ts.map +1 -0
  37. package/dist/core/bearer-challenge.js +64 -0
  38. package/dist/core/bearer-challenge.js.map +1 -0
  39. package/dist/core/cancel.d.ts +71 -0
  40. package/dist/core/cancel.d.ts.map +1 -0
  41. package/dist/core/cancel.js +178 -0
  42. package/dist/core/cancel.js.map +1 -0
  43. package/dist/core/extension.d.ts +34 -0
  44. package/dist/core/extension.d.ts.map +1 -0
  45. package/dist/core/extension.js +146 -0
  46. package/dist/core/extension.js.map +1 -0
  47. package/dist/core/index.d.ts +67 -0
  48. package/dist/core/index.d.ts.map +1 -0
  49. package/dist/core/index.js +92 -0
  50. package/dist/core/index.js.map +1 -0
  51. package/dist/core/jsonrpc.d.ts +50 -0
  52. package/dist/core/jsonrpc.d.ts.map +1 -0
  53. package/dist/core/jsonrpc.js +81 -0
  54. package/dist/core/jsonrpc.js.map +1 -0
  55. package/dist/core/lifecycle.d.ts +129 -0
  56. package/dist/core/lifecycle.d.ts.map +1 -0
  57. package/dist/core/lifecycle.js +252 -0
  58. package/dist/core/lifecycle.js.map +1 -0
  59. package/dist/core/outcome.d.ts +99 -0
  60. package/dist/core/outcome.d.ts.map +1 -0
  61. package/dist/core/outcome.js +33 -0
  62. package/dist/core/outcome.js.map +1 -0
  63. package/dist/core/ports.d.ts +145 -0
  64. package/dist/core/ports.d.ts.map +1 -0
  65. package/dist/core/ports.js +68 -0
  66. package/dist/core/ports.js.map +1 -0
  67. package/dist/core/progress.d.ts +82 -0
  68. package/dist/core/progress.d.ts.map +1 -0
  69. package/dist/core/progress.js +206 -0
  70. package/dist/core/progress.js.map +1 -0
  71. package/dist/core/request.d.ts +109 -0
  72. package/dist/core/request.d.ts.map +1 -0
  73. package/dist/core/request.js +579 -0
  74. package/dist/core/request.js.map +1 -0
  75. package/dist/core/schema/index.d.ts +2 -0
  76. package/dist/core/schema/index.d.ts.map +1 -0
  77. package/dist/core/schema/index.js +2 -0
  78. package/dist/core/schema/index.js.map +1 -0
  79. package/dist/core/schema/types.d.ts +4150 -0
  80. package/dist/core/schema/types.d.ts.map +1 -0
  81. package/dist/core/schema/types.js +7 -0
  82. package/dist/core/schema/types.js.map +1 -0
  83. package/dist/core/telemetry.d.ts +26 -0
  84. package/dist/core/telemetry.d.ts.map +1 -0
  85. package/dist/core/telemetry.js +38 -0
  86. package/dist/core/telemetry.js.map +1 -0
  87. package/dist/ext-events/index.d.ts +80 -0
  88. package/dist/ext-events/index.d.ts.map +1 -0
  89. package/dist/ext-events/index.js +219 -0
  90. package/dist/ext-events/index.js.map +1 -0
  91. package/dist/ext-events/model.d.ts +11 -0
  92. package/dist/ext-events/model.d.ts.map +1 -0
  93. package/dist/ext-events/model.js +7 -0
  94. package/dist/ext-events/model.js.map +1 -0
  95. package/dist/ext-events/push.d.ts +19 -0
  96. package/dist/ext-events/push.d.ts.map +1 -0
  97. package/dist/ext-events/push.js +102 -0
  98. package/dist/ext-events/push.js.map +1 -0
  99. package/dist/ext-events/stream.d.ts +7 -0
  100. package/dist/ext-events/stream.d.ts.map +1 -0
  101. package/dist/ext-events/stream.js +61 -0
  102. package/dist/ext-events/stream.js.map +1 -0
  103. package/dist/ext-server-cards/index.d.ts +80 -0
  104. package/dist/ext-server-cards/index.d.ts.map +1 -0
  105. package/dist/ext-server-cards/index.js +199 -0
  106. package/dist/ext-server-cards/index.js.map +1 -0
  107. package/dist/ext-skills/cache.d.ts +21 -0
  108. package/dist/ext-skills/cache.d.ts.map +1 -0
  109. package/dist/ext-skills/cache.js +102 -0
  110. package/dist/ext-skills/cache.js.map +1 -0
  111. package/dist/ext-skills/client.d.ts +83 -0
  112. package/dist/ext-skills/client.d.ts.map +1 -0
  113. package/dist/ext-skills/client.js +293 -0
  114. package/dist/ext-skills/client.js.map +1 -0
  115. package/dist/ext-skills/extension.d.ts +17 -0
  116. package/dist/ext-skills/extension.d.ts.map +1 -0
  117. package/dist/ext-skills/extension.js +30 -0
  118. package/dist/ext-skills/extension.js.map +1 -0
  119. package/dist/ext-skills/index.d.ts +5 -0
  120. package/dist/ext-skills/index.d.ts.map +1 -0
  121. package/dist/ext-skills/index.js +5 -0
  122. package/dist/ext-skills/index.js.map +1 -0
  123. package/dist/ext-skills/verify.d.ts +58 -0
  124. package/dist/ext-skills/verify.d.ts.map +1 -0
  125. package/dist/ext-skills/verify.js +169 -0
  126. package/dist/ext-skills/verify.js.map +1 -0
  127. package/dist/index.d.ts +1 -0
  128. package/dist/index.js +1 -0
  129. package/dist/mrtr-cache/cache.d.ts +52 -0
  130. package/dist/mrtr-cache/cache.d.ts.map +1 -0
  131. package/dist/mrtr-cache/cache.js +296 -0
  132. package/dist/mrtr-cache/cache.js.map +1 -0
  133. package/dist/mrtr-cache/client.d.ts +25 -0
  134. package/dist/mrtr-cache/client.d.ts.map +1 -0
  135. package/dist/mrtr-cache/client.js +45 -0
  136. package/dist/mrtr-cache/client.js.map +1 -0
  137. package/dist/mrtr-cache/common.d.ts +11 -0
  138. package/dist/mrtr-cache/common.d.ts.map +1 -0
  139. package/dist/mrtr-cache/common.js +10 -0
  140. package/dist/mrtr-cache/common.js.map +1 -0
  141. package/dist/mrtr-cache/elicitation.d.ts +43 -0
  142. package/dist/mrtr-cache/elicitation.d.ts.map +1 -0
  143. package/dist/mrtr-cache/elicitation.js +222 -0
  144. package/dist/mrtr-cache/elicitation.js.map +1 -0
  145. package/dist/mrtr-cache/index.d.ts +10 -0
  146. package/dist/mrtr-cache/index.d.ts.map +1 -0
  147. package/dist/mrtr-cache/index.js +9 -0
  148. package/dist/mrtr-cache/index.js.map +1 -0
  149. package/dist/mrtr-cache/mrtr.d.ts +38 -0
  150. package/dist/mrtr-cache/mrtr.d.ts.map +1 -0
  151. package/dist/mrtr-cache/mrtr.js +251 -0
  152. package/dist/mrtr-cache/mrtr.js.map +1 -0
  153. package/dist/mrtr-cache/refresh.d.ts +9 -0
  154. package/dist/mrtr-cache/refresh.d.ts.map +1 -0
  155. package/dist/mrtr-cache/refresh.js +31 -0
  156. package/dist/mrtr-cache/refresh.js.map +1 -0
  157. package/dist/mrtr-cache/stream.d.ts +6 -0
  158. package/dist/mrtr-cache/stream.d.ts.map +1 -0
  159. package/dist/mrtr-cache/stream.js +19 -0
  160. package/dist/mrtr-cache/stream.js.map +1 -0
  161. package/dist/mrtr-cache/subscriptions.d.ts +97 -0
  162. package/dist/mrtr-cache/subscriptions.d.ts.map +1 -0
  163. package/dist/mrtr-cache/subscriptions.js +289 -0
  164. package/dist/mrtr-cache/subscriptions.js.map +1 -0
  165. package/dist/mrtr-cache/tasks.d.ts +104 -0
  166. package/dist/mrtr-cache/tasks.d.ts.map +1 -0
  167. package/dist/mrtr-cache/tasks.js +445 -0
  168. package/dist/mrtr-cache/tasks.js.map +1 -0
  169. package/dist/ops/common.d.ts +19 -0
  170. package/dist/ops/common.d.ts.map +1 -0
  171. package/dist/ops/common.js +40 -0
  172. package/dist/ops/common.js.map +1 -0
  173. package/dist/ops/completion.d.ts +45 -0
  174. package/dist/ops/completion.d.ts.map +1 -0
  175. package/dist/ops/completion.js +66 -0
  176. package/dist/ops/completion.js.map +1 -0
  177. package/dist/ops/content.d.ts +41 -0
  178. package/dist/ops/content.d.ts.map +1 -0
  179. package/dist/ops/content.js +118 -0
  180. package/dist/ops/content.js.map +1 -0
  181. package/dist/ops/icons.d.ts +30 -0
  182. package/dist/ops/icons.d.ts.map +1 -0
  183. package/dist/ops/icons.js +83 -0
  184. package/dist/ops/icons.js.map +1 -0
  185. package/dist/ops/index.d.ts +31 -0
  186. package/dist/ops/index.d.ts.map +1 -0
  187. package/dist/ops/index.js +29 -0
  188. package/dist/ops/index.js.map +1 -0
  189. package/dist/ops/pagination.d.ts +33 -0
  190. package/dist/ops/pagination.d.ts.map +1 -0
  191. package/dist/ops/pagination.js +66 -0
  192. package/dist/ops/pagination.js.map +1 -0
  193. package/dist/ops/prompts.d.ts +33 -0
  194. package/dist/ops/prompts.d.ts.map +1 -0
  195. package/dist/ops/prompts.js +69 -0
  196. package/dist/ops/prompts.js.map +1 -0
  197. package/dist/ops/resources.d.ts +43 -0
  198. package/dist/ops/resources.d.ts.map +1 -0
  199. package/dist/ops/resources.js +105 -0
  200. package/dist/ops/resources.js.map +1 -0
  201. package/dist/ops/schema.d.ts +40 -0
  202. package/dist/ops/schema.d.ts.map +1 -0
  203. package/dist/ops/schema.js +164 -0
  204. package/dist/ops/schema.js.map +1 -0
  205. package/dist/ops/tools.d.ts +89 -0
  206. package/dist/ops/tools.d.ts.map +1 -0
  207. package/dist/ops/tools.js +170 -0
  208. package/dist/ops/tools.js.map +1 -0
  209. package/dist/ops/uri-template.d.ts +4 -0
  210. package/dist/ops/uri-template.d.ts.map +1 -0
  211. package/dist/ops/uri-template.js +102 -0
  212. package/dist/ops/uri-template.js.map +1 -0
  213. package/dist/telemetry-otel/index.d.ts +65 -0
  214. package/dist/telemetry-otel/index.d.ts.map +1 -0
  215. package/dist/telemetry-otel/index.js +197 -0
  216. package/dist/telemetry-otel/index.js.map +1 -0
  217. package/dist/transport-http/headers.d.ts +25 -0
  218. package/dist/transport-http/headers.d.ts.map +1 -0
  219. package/dist/transport-http/headers.js +141 -0
  220. package/dist/transport-http/headers.js.map +1 -0
  221. package/dist/transport-http/index.d.ts +4 -0
  222. package/dist/transport-http/index.d.ts.map +1 -0
  223. package/dist/transport-http/index.js +4 -0
  224. package/dist/transport-http/index.js.map +1 -0
  225. package/dist/transport-http/sse.d.ts +34 -0
  226. package/dist/transport-http/sse.d.ts.map +1 -0
  227. package/dist/transport-http/sse.js +153 -0
  228. package/dist/transport-http/sse.js.map +1 -0
  229. package/dist/transport-http/transport.d.ts +67 -0
  230. package/dist/transport-http/transport.d.ts.map +1 -0
  231. package/dist/transport-http/transport.js +855 -0
  232. package/dist/transport-http/transport.js.map +1 -0
  233. package/dist/transport-stdio/framing.d.ts +51 -0
  234. package/dist/transport-stdio/framing.d.ts.map +1 -0
  235. package/dist/transport-stdio/framing.js +155 -0
  236. package/dist/transport-stdio/framing.js.map +1 -0
  237. package/dist/transport-stdio/index.d.ts +5 -0
  238. package/dist/transport-stdio/index.d.ts.map +1 -0
  239. package/dist/transport-stdio/index.js +5 -0
  240. package/dist/transport-stdio/index.js.map +1 -0
  241. package/dist/transport-stdio/stderr-ring.d.ts +28 -0
  242. package/dist/transport-stdio/stderr-ring.d.ts.map +1 -0
  243. package/dist/transport-stdio/stderr-ring.js +106 -0
  244. package/dist/transport-stdio/stderr-ring.js.map +1 -0
  245. package/dist/transport-stdio/transport.d.ts +112 -0
  246. package/dist/transport-stdio/transport.d.ts.map +1 -0
  247. package/dist/transport-stdio/transport.js +744 -0
  248. package/dist/transport-stdio/transport.js.map +1 -0
  249. package/dist/transport-stdio/write-queue.d.ts +39 -0
  250. package/dist/transport-stdio/write-queue.d.ts.map +1 -0
  251. package/dist/transport-stdio/write-queue.js +148 -0
  252. package/dist/transport-stdio/write-queue.js.map +1 -0
  253. package/package.json +98 -0
@@ -0,0 +1,855 @@
1
+ import { SUPPORTED_PROTOCOL_VERSION, AuthError, DiagnosticChannel, NotificationQueue, parseBearerChallenges, parseInboundMessage, systemClock, withAbort, } from "../core/index.js";
2
+ import { encodeHeaderValue, extractAtPath, validateXmcpHeaderSchema, } from "./headers.js";
3
+ import { SseParser, DEFAULT_MAX_SSE_EVENT_BYTES } from "./sse.js";
4
+ export const DEFAULT_MAX_JSON_BYTES = 64 * 1024 * 1024; // HTTP-LIMIT-1
5
+ export const DEFAULT_MAX_SSE_STREAM_BYTES = 64 * 1024 * 1024; // HTTP-LIMIT-3
6
+ export const DEFAULT_MAX_REDIRECTS = 3;
7
+ export const DEFAULT_LISTEN_IDLE_MS = 120_000;
8
+ const META_PROTOCOL_VERSION = "io.modelcontextprotocol/protocolVersion";
9
+ const META_PROGRESS_TOKEN = "io.modelcontextprotocol/progressToken";
10
+ const META_SUBSCRIPTION_ID = "io.modelcontextprotocol/subscriptionId";
11
+ const FORBIDDEN_OUTBOUND = new Set(["mcp-session-id", "last-event-id"]);
12
+ const attemptState = () => ({ delivery: "not-sent", authRetries: 0, stepUps: 0 });
13
+ function failed(failure, delivery = "not-sent") {
14
+ return { kind: "final", end: { kind: "failure", failure, delivery } };
15
+ }
16
+ function authFailed(reason, status, kind = "auth-failure") {
17
+ return failed({ kind, reason, message: `${kind}/${reason}`, ...(status !== undefined ? { status } : {}) });
18
+ }
19
+ function providerFailed(error, fallback, status) {
20
+ return error instanceof AuthError ? authFailed(error.reason, status, error.kind) : authFailed(fallback, status);
21
+ }
22
+ function discardBody(response) {
23
+ void response.body?.cancel().catch(() => undefined);
24
+ }
25
+ function isRecord(v) {
26
+ return typeof v === "object" && v !== null && !Array.isArray(v);
27
+ }
28
+ export class HttpTransport {
29
+ binding = "streamable-http";
30
+ url;
31
+ doFetch;
32
+ authProvider;
33
+ logger;
34
+ clock;
35
+ protocolVersion;
36
+ maxJsonBytes;
37
+ maxSseEventBytes;
38
+ maxSseStreamBytes;
39
+ maxRedirects;
40
+ idleTimeoutMs;
41
+ listenIdleMs;
42
+ extraHeaders;
43
+ diag;
44
+ toolParams = new Map();
45
+ inFlight = new Set();
46
+ closed = false;
47
+ constructor(opts) {
48
+ this.url = opts.url;
49
+ if (opts.fetchFn)
50
+ this.doFetch = opts.fetchFn;
51
+ else if (opts.fetchPort)
52
+ this.doFetch = (i, init) => opts.fetchPort.fetch(i, init);
53
+ else
54
+ this.doFetch = (i, init) => globalThis.fetch(i, init);
55
+ if (opts.authProvider)
56
+ this.authProvider = opts.authProvider;
57
+ if (opts.logger)
58
+ this.logger = opts.logger;
59
+ this.clock = opts.clock ?? systemClock;
60
+ if (opts.protocolVersion)
61
+ this.protocolVersion = opts.protocolVersion;
62
+ this.maxJsonBytes = opts.maxJsonBytes ?? DEFAULT_MAX_JSON_BYTES;
63
+ this.maxSseEventBytes = opts.maxSseEventBytes ?? DEFAULT_MAX_SSE_EVENT_BYTES;
64
+ this.maxSseStreamBytes = opts.maxSseStreamBytes ?? DEFAULT_MAX_SSE_STREAM_BYTES;
65
+ this.maxRedirects = opts.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
66
+ if (opts.idleTimeoutMs !== undefined)
67
+ this.idleTimeoutMs = opts.idleTimeoutMs;
68
+ this.listenIdleMs = opts.listenIdleMs ?? DEFAULT_LISTEN_IDLE_MS;
69
+ this.extraHeaders = opts.extraHeaders ?? {};
70
+ this.diag = new DiagnosticChannel(opts.maxDiagnostics);
71
+ }
72
+ get diagnostics() {
73
+ return this.diag;
74
+ }
75
+ diagnosticsSnapshot() {
76
+ return this.diag.snapshot();
77
+ }
78
+ /** Annotated params cached from the most recent tools/list (HTTP-PARAM-5). */
79
+ cachedToolParams(name) {
80
+ return this.toolParams.get(name);
81
+ }
82
+ start(msg, ctx) {
83
+ const notifications = new NotificationQueue();
84
+ const state = attemptState();
85
+ const done = this.execute(msg, ctx, notifications, state).then((end) => {
86
+ notifications.close();
87
+ return end;
88
+ }, () => {
89
+ notifications.close();
90
+ return failed({ kind: "stream-broken", message: "HTTP exchange failed" }, state.delivery).end;
91
+ });
92
+ return { notifications, done, abortDelivery: () => state.delivery };
93
+ }
94
+ async notify(msg, ctx) {
95
+ if (this.closed)
96
+ throw new Error("HttpTransport is closed");
97
+ if (ctx.signal.aborted)
98
+ return;
99
+ // Extension notifications only: same version/method headers, expect 202 (HTTP-NOTIF-1).
100
+ const state = attemptState();
101
+ for (;;) {
102
+ const outcome = await this.performOnce(msg, ctx, new NotificationQueue(), undefined, state);
103
+ if (outcome.kind === "auth-retry")
104
+ continue;
105
+ if (outcome.kind === "header-mismatch")
106
+ throw new Error("notification rejected: header mismatch");
107
+ if (outcome.end.kind === "failure")
108
+ throw new Error(outcome.end.failure.message);
109
+ break;
110
+ }
111
+ // A response payload to a notification is tolerated/logged by performOnce classification.
112
+ }
113
+ async close(_opts) {
114
+ this.closed = true;
115
+ for (const c of this.inFlight)
116
+ c.abort("transport closed");
117
+ this.diag.close();
118
+ }
119
+ // ---- request execution ----
120
+ async execute(msg, ctx, notifications, state) {
121
+ if (this.closed) {
122
+ return { kind: "failure", failure: { kind: "closed", message: "HttpTransport is closed" }, delivery: "not-sent" };
123
+ }
124
+ if (ctx.signal.aborted) {
125
+ return { kind: "failure", failure: { kind: "closed", message: "aborted before send" }, delivery: "not-sent" };
126
+ }
127
+ let headerRetried = false;
128
+ let wireId = msg.id;
129
+ for (;;) {
130
+ const wireMsg = wireId === msg.id ? msg : { ...msg, id: wireId };
131
+ const outcome = await this.performOnce(wireMsg, ctx, notifications, msg.id, state);
132
+ if (outcome.kind === "auth-retry") {
133
+ wireId = outcome.status === 401 ? `${String(msg.id)}~auth-retry-1` : `${String(msg.id)}~step-up-${state.stepUps}`;
134
+ continue;
135
+ }
136
+ if (outcome.kind === "header-mismatch") {
137
+ if (headerRetried || msg.method !== "tools/call") {
138
+ return { kind: "response", message: outcome.message };
139
+ }
140
+ headerRetried = true;
141
+ // HTTP-PARAM-6: refresh tools/list, rebuild headers, retry once with a new id.
142
+ state.delivery = "not-sent";
143
+ if (!await this.refreshToolsList(msg, ctx))
144
+ return { kind: "response", message: outcome.message };
145
+ wireId = `${String(msg.id)}~header-retry-1`;
146
+ continue;
147
+ }
148
+ return outcome.end;
149
+ }
150
+ }
151
+ async refreshToolsList(original, ctx) {
152
+ const params = isRecord(original.params) ? original.params : {};
153
+ const refresh = {
154
+ jsonrpc: "2.0",
155
+ id: `${String(original.id)}~tools-list-refresh`,
156
+ method: "tools/list",
157
+ params: { ...(isRecord(params["_meta"]) ? { _meta: params["_meta"] } : {}) },
158
+ };
159
+ const end = await this.execute(refresh, ctx, new NotificationQueue(), attemptState());
160
+ return end.kind === "response" && "result" in end.message;
161
+ }
162
+ async performOnce(wireMsg, ctx, notifications, expectedId, state) {
163
+ const isRequest = "id" in wireMsg;
164
+ const method = wireMsg.method;
165
+ if (this.closed || ctx.signal.aborted)
166
+ return failed({ kind: "closed", message: "request aborted before send" });
167
+ const controller = new AbortController();
168
+ this.inFlight.add(controller);
169
+ const onCallerAbort = () => controller.abort(ctx.signal.reason);
170
+ if (ctx.signal.aborted)
171
+ controller.abort(ctx.signal.reason);
172
+ else
173
+ ctx.signal.addEventListener("abort", onCallerAbort, { once: true });
174
+ let timedOut = false;
175
+ let idleTimer;
176
+ const isListen = method === "subscriptions/listen";
177
+ const timeoutMs = isRequest ? ctx.timeoutMs : undefined;
178
+ let timeoutTimer;
179
+ if (timeoutMs && timeoutMs > 0 && !isListen) {
180
+ timeoutTimer = setTimeout(() => {
181
+ timedOut = true;
182
+ controller.abort("timeout");
183
+ }, timeoutMs);
184
+ }
185
+ const armIdle = () => {
186
+ if (idleTimer)
187
+ clearTimeout(idleTimer);
188
+ const idleMs = this.idleTimeoutMs !== undefined ? this.idleTimeoutMs : isListen ? this.listenIdleMs : timeoutMs;
189
+ if (idleMs && idleMs > 0) {
190
+ idleTimer = setTimeout(() => {
191
+ if (isListen) {
192
+ this.emit("violation", `listen stream idle for ${idleMs}ms (watchdog)`);
193
+ controller.abort("listen-idle");
194
+ }
195
+ else {
196
+ timedOut = true;
197
+ controller.abort("idle-timeout");
198
+ }
199
+ }, idleMs);
200
+ }
201
+ };
202
+ const authContext = {
203
+ signal: controller.signal,
204
+ ...(ctx.consent ? { consent: ctx.consent } : {}),
205
+ ...(ctx.serverLabel !== undefined ? { serverLabel: ctx.serverLabel } : {}),
206
+ };
207
+ const aborted = () => failed({ kind: timedOut ? "timeout" : "closed", message: "HTTP request interrupted" }, state.delivery);
208
+ try {
209
+ const baseHeaders = this.buildHeaders(wireMsg, ctx);
210
+ const body = JSON.stringify(wireMsg);
211
+ let currentUrl = this.url;
212
+ let response;
213
+ let redirects = 0;
214
+ let credentialVersion;
215
+ const credentials = new Set();
216
+ for (;;) {
217
+ if (controller.signal.aborted)
218
+ return aborted();
219
+ const headers = new Headers(baseHeaders);
220
+ if (this.authProvider || redirects > 0)
221
+ headers.delete("Authorization");
222
+ if (this.authProvider) {
223
+ try {
224
+ const auth = await withAbort(this.authProvider.headerFor(currentUrl, method, authContext), controller.signal, () => new Error("auth wait aborted"));
225
+ credentialVersion = auth?.credentialVersion;
226
+ if (auth)
227
+ headers.set("Authorization", auth.authorization);
228
+ }
229
+ catch (error) {
230
+ return controller.signal.aborted ? aborted() : providerFailed(error, "credentials-unavailable");
231
+ }
232
+ }
233
+ if (controller.signal.aborted)
234
+ return aborted();
235
+ const authorization = headers.get("Authorization");
236
+ if (authorization)
237
+ credentials.add(authorization.replace(/^\S+\s+/u, ""));
238
+ else
239
+ credentialVersion = null;
240
+ const query = new URL(currentUrl).searchParams;
241
+ if (query.has("access_token") || [...query.values()].some(value => credentials.has(value))) {
242
+ return authFailed("credentials-in-query");
243
+ }
244
+ state.delivery = "maybe-delivered";
245
+ try {
246
+ response = await this.doFetch(currentUrl, {
247
+ method: "POST", // POST only: never GET/DELETE (HTTP-NOGET-1)
248
+ headers,
249
+ body,
250
+ redirect: "manual",
251
+ signal: controller.signal,
252
+ });
253
+ }
254
+ catch {
255
+ return controller.signal.aborted ? aborted() : failed({ kind: "connect", message: "HTTP fetch failed" }, state.delivery);
256
+ }
257
+ const status = response.status;
258
+ if (status >= 300 && status < 400) {
259
+ state.delivery = "not-sent";
260
+ const location = response.headers.get("location");
261
+ discardBody(response);
262
+ if (!location || (status !== 307 && status !== 308)) {
263
+ return {
264
+ kind: "final",
265
+ end: {
266
+ kind: "failure",
267
+ failure: { kind: "http-status", message: `redirect ${status} not followed (only 307/308 preserve POST)`, status },
268
+ delivery: "not-sent",
269
+ },
270
+ };
271
+ }
272
+ if (redirects >= this.maxRedirects) {
273
+ return {
274
+ kind: "final",
275
+ end: {
276
+ kind: "failure",
277
+ failure: { kind: "http-status", message: `too many redirects (>${this.maxRedirects})`, status },
278
+ delivery: "not-sent",
279
+ },
280
+ };
281
+ }
282
+ let next;
283
+ try {
284
+ next = new URL(location, currentUrl);
285
+ }
286
+ catch {
287
+ return failed({ kind: "http-status", message: "invalid redirect location", status });
288
+ }
289
+ const prev = new URL(currentUrl);
290
+ if (next.origin !== prev.origin || next.protocol !== prev.protocol || next.username || next.password) {
291
+ this.emit("violation", "refused cross-origin, downgrade or credentialed redirect");
292
+ return {
293
+ kind: "final",
294
+ end: {
295
+ kind: "failure",
296
+ failure: { kind: "forbidden", message: "cross-origin, downgrade or credentialed redirect refused", status },
297
+ delivery: "not-sent",
298
+ },
299
+ };
300
+ }
301
+ redirects += 1;
302
+ currentUrl = next.toString();
303
+ continue;
304
+ }
305
+ break;
306
+ }
307
+ if (!response)
308
+ throw new Error("no response");
309
+ return await this.handleResponse(response, {
310
+ isRequest,
311
+ method,
312
+ expectedId,
313
+ wireId: isRequest ? wireMsg.id : undefined,
314
+ ctx,
315
+ notifications,
316
+ controller,
317
+ timedOut: () => timedOut,
318
+ armIdle,
319
+ state,
320
+ resource: currentUrl,
321
+ credentialVersion,
322
+ credentials,
323
+ authContext,
324
+ });
325
+ }
326
+ finally {
327
+ if (timeoutTimer)
328
+ clearTimeout(timeoutTimer);
329
+ if (idleTimer)
330
+ clearTimeout(idleTimer);
331
+ ctx.signal.removeEventListener("abort", onCallerAbort);
332
+ this.inFlight.delete(controller);
333
+ }
334
+ }
335
+ async handleResponse(response, args) {
336
+ const { isRequest, method, expectedId } = args;
337
+ const status = response.status;
338
+ const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
339
+ // Auth challenges (AUTH-HTTP-1/2): 401 always; 403 only with insufficient_scope.
340
+ const wwwAuth = response.headers.get("www-authenticate") ?? undefined;
341
+ if (status === 401 || (status === 403 && parseBearerChallenges(wwwAuth ?? "").some(ch => ch.error === "insufficient_scope"))) {
342
+ const { state, controller, authContext, credentialVersion, resource } = args;
343
+ state.delivery = "not-sent"; // Definitive rejection; nothing was executed.
344
+ discardBody(response);
345
+ const aborted = () => failed({ kind: args.timedOut() ? "timeout" : "closed", message: "auth wait interrupted" });
346
+ if (controller.signal.aborted)
347
+ return aborted();
348
+ const reason = status === 403 ? "insufficient-scope" : "unauthorized";
349
+ const provider = this.authProvider;
350
+ if (!provider?.onChallenge)
351
+ return authFailed(reason, status);
352
+ if (status === 401) {
353
+ if (state.authRetries >= 1)
354
+ return authFailed("retry-exhausted", status);
355
+ state.authRetries++;
356
+ }
357
+ else {
358
+ const limit = provider.stepUpLimit ?? 3;
359
+ if (state.stepUps >= (Number.isSafeInteger(limit) && limit >= 0 ? limit : 3))
360
+ return authFailed(reason, status);
361
+ state.stepUps++;
362
+ }
363
+ try {
364
+ const retry = await withAbort(provider.onChallenge({
365
+ status,
366
+ resource,
367
+ operation: method,
368
+ ...(wwwAuth ? { wwwAuthenticate: wwwAuth } : {}),
369
+ ...(credentialVersion !== undefined ? { credentialVersion } : {}),
370
+ }, controller.signal, authContext), controller.signal, () => new Error("auth wait aborted"));
371
+ if (controller.signal.aborted)
372
+ return aborted();
373
+ if (retry === true)
374
+ return { kind: "auth-retry", status };
375
+ }
376
+ catch (error) {
377
+ return controller.signal.aborted ? aborted() : providerFailed(error, reason, status);
378
+ }
379
+ return authFailed(reason, status);
380
+ }
381
+ if (status === 403) {
382
+ args.state.delivery = "not-sent";
383
+ discardBody(response);
384
+ return {
385
+ kind: "final",
386
+ end: { kind: "failure", failure: { kind: "forbidden", message: "HTTP 403 forbidden", status }, delivery: "not-sent" },
387
+ };
388
+ }
389
+ if (status === 413 || status === 431) {
390
+ args.state.delivery = "not-sent";
391
+ discardBody(response);
392
+ return {
393
+ kind: "final",
394
+ end: {
395
+ kind: "failure",
396
+ failure: { kind: "too-large", message: `HTTP ${status}: request headers/body too large (not executed)`, status },
397
+ delivery: "not-sent",
398
+ },
399
+ };
400
+ }
401
+ if (status === 429 || status === 408 || status >= 500) {
402
+ const rawRetryAfter = response.headers.get("retry-after");
403
+ const retryAfter = rawRetryAfter && (/^\d+$/u.test(rawRetryAfter) || Number.isFinite(Date.parse(rawRetryAfter))) &&
404
+ ![...args.credentials].some(secret => rawRetryAfter.includes(secret)) ? rawRetryAfter : undefined;
405
+ await response.body?.cancel().catch(() => undefined);
406
+ return {
407
+ kind: "final",
408
+ end: {
409
+ kind: "failure",
410
+ failure: {
411
+ kind: "http-status",
412
+ message: `HTTP ${status}${retryAfter ? ` Retry-After: ${retryAfter}` : ""}`,
413
+ status,
414
+ },
415
+ // Server may have run the call: core turns this into uncertain-write for non-idempotent (§7.4/7.7).
416
+ delivery: "delivered-no-response",
417
+ },
418
+ };
419
+ }
420
+ if (!isRequest) {
421
+ // Notification POST: 202 expected; any other 2xx tolerated+logged; rest is rejection.
422
+ await response.body?.cancel().catch(() => undefined);
423
+ if (status === 202)
424
+ return { kind: "final", end: { kind: "response", message: emptyNotificationAck(expectedId) } };
425
+ if (status >= 200 && status < 300) {
426
+ this.emit("lifecycle", `notification POST answered ${status} (tolerated, expected 202)`);
427
+ return { kind: "final", end: { kind: "response", message: emptyNotificationAck(expectedId) } };
428
+ }
429
+ return {
430
+ kind: "final",
431
+ end: {
432
+ kind: "failure",
433
+ failure: { kind: "http-status", message: `notification rejected with HTTP ${status}`, status },
434
+ delivery: "not-sent",
435
+ },
436
+ };
437
+ }
438
+ if (status === 202) {
439
+ await response.body?.cancel().catch(() => undefined);
440
+ return {
441
+ kind: "final",
442
+ end: {
443
+ kind: "failure",
444
+ failure: { kind: "http-status", message: "unexpected 202 for a request", status },
445
+ delivery: "delivered-no-response",
446
+ },
447
+ };
448
+ }
449
+ if (status >= 200 && status < 300 && contentType.includes("text/event-stream")) {
450
+ return this.handleSse(response, args);
451
+ }
452
+ // JSON (or error-status) bodies.
453
+ let text;
454
+ try {
455
+ text = await this.readBodyText(response, this.maxJsonBytes);
456
+ }
457
+ catch (err) {
458
+ if (err instanceof TooLargeError) {
459
+ return {
460
+ kind: "final",
461
+ end: { kind: "failure", failure: { kind: "too-large", message: err.message }, delivery: "delivered-no-response" },
462
+ };
463
+ }
464
+ if (args.ctx.signal.aborted || args.controller.signal.aborted) {
465
+ return {
466
+ kind: "final",
467
+ end: {
468
+ kind: "failure",
469
+ failure: { kind: args.timedOut() ? "timeout" : "closed", message: "aborted while reading body" },
470
+ delivery: "delivered-no-response",
471
+ },
472
+ };
473
+ }
474
+ return {
475
+ kind: "final",
476
+ end: {
477
+ kind: "failure",
478
+ failure: { kind: "stream-broken", message: "truncated-json: failed to read JSON response" },
479
+ delivery: "delivered-no-response",
480
+ },
481
+ };
482
+ }
483
+ if (status >= 200 && status < 300) {
484
+ if (!contentType.includes("application/json") && !contentType.includes("+json")) {
485
+ this.emit("violation", "unexpected content-type on 2xx");
486
+ return {
487
+ kind: "final",
488
+ end: {
489
+ kind: "failure",
490
+ failure: { kind: "stream-broken", message: "protocol-violation: unexpected content-type" },
491
+ delivery: "delivered-no-response",
492
+ },
493
+ };
494
+ }
495
+ if (text.trim() === "") {
496
+ this.emit("violation", "HTTP 200 with empty body for a request (EDGE-21)");
497
+ return {
498
+ kind: "final",
499
+ end: {
500
+ kind: "failure",
501
+ failure: { kind: "stream-broken", message: "protocol-violation: empty 200 body" },
502
+ delivery: "delivered-no-response",
503
+ },
504
+ };
505
+ }
506
+ }
507
+ let parsed;
508
+ try {
509
+ parsed = JSON.parse(text);
510
+ }
511
+ catch {
512
+ const legacy = status === 400 ? "legacy-or-malformed" : status === 404 || status === 405 ? "legacy-or-wrong-endpoint" : "malformed-body";
513
+ this.emit("violation", `${legacy}: HTTP ${status} with non-JSON body`);
514
+ return {
515
+ kind: "final",
516
+ end: {
517
+ kind: "failure",
518
+ failure: { kind: "http-status", message: `${legacy}: HTTP ${status} body is not a JSON-RPC message`, status },
519
+ delivery: status >= 400 ? "not-sent" : "delivered-no-response",
520
+ },
521
+ };
522
+ }
523
+ if (Array.isArray(parsed)) {
524
+ this.emit("violation", "JSON-RPC batch array rejected (HTTP-REQ-2)");
525
+ return {
526
+ kind: "final",
527
+ end: {
528
+ kind: "failure",
529
+ failure: { kind: "stream-broken", message: "protocol-violation: JSON-RPC batch array" },
530
+ delivery: "delivered-no-response",
531
+ },
532
+ };
533
+ }
534
+ const inbound = parseInboundMessage(parsed);
535
+ if ("error" in inbound || (inbound.kind !== "response" && inbound.kind !== "error")) {
536
+ const legacy = status === 400 ? "legacy-or-malformed" : status === 404 || status === 405 ? "legacy-or-wrong-endpoint" : "protocol-violation";
537
+ this.emit("violation", `${legacy}: HTTP ${status} body is not a JSON-RPC response`);
538
+ return {
539
+ kind: "final",
540
+ end: {
541
+ kind: "failure",
542
+ failure: { kind: "http-status", message: `${legacy}: HTTP ${status}`, status },
543
+ delivery: status >= 400 ? "not-sent" : "delivered-no-response",
544
+ },
545
+ };
546
+ }
547
+ const message = this.normalizeResponseId(inbound.message, args.wireId, expectedId);
548
+ if (expectedId !== undefined && "id" in message && message.id !== expectedId) {
549
+ this.emit("violation", "response id mismatch");
550
+ return {
551
+ kind: "final",
552
+ end: {
553
+ kind: "failure",
554
+ failure: { kind: "stream-broken", message: "protocol-violation: response id does not equal request id" },
555
+ delivery: "delivered-no-response",
556
+ },
557
+ };
558
+ }
559
+ if ("error" in message && message.error.code === -32020 && status === 400) {
560
+ return { kind: "header-mismatch", message };
561
+ }
562
+ if (status >= 400 && !("error" in message)) {
563
+ return {
564
+ kind: "final",
565
+ end: {
566
+ kind: "failure",
567
+ failure: { kind: "http-status", message: `HTTP ${status}`, status },
568
+ delivery: "not-sent",
569
+ },
570
+ };
571
+ }
572
+ const outMessage = method === "tools/list" && !("error" in message)
573
+ ? this.processToolsList(message, args.credentials)
574
+ : message;
575
+ return { kind: "final", end: { kind: "response", message: outMessage } };
576
+ }
577
+ async handleSse(response, args) {
578
+ const { method, expectedId, notifications } = args;
579
+ if (!response.body) {
580
+ return {
581
+ kind: "final",
582
+ end: { kind: "failure", failure: { kind: "stream-broken", message: "SSE response has no body" }, delivery: "delivered-no-response" },
583
+ };
584
+ }
585
+ const reader = response.body.getReader();
586
+ const parser = new SseParser(this.maxSseEventBytes);
587
+ let totalBytes = 0;
588
+ let finalMessage;
589
+ const fail = (failure, delivery) => ({
590
+ kind: "final",
591
+ end: { kind: "failure", failure, delivery },
592
+ });
593
+ args.armIdle();
594
+ try {
595
+ for (;;) {
596
+ let chunk;
597
+ try {
598
+ chunk = await reader.read();
599
+ }
600
+ catch {
601
+ if (finalMessage)
602
+ break;
603
+ if (args.ctx.signal.aborted || args.controller.signal.aborted) {
604
+ return fail({ kind: args.timedOut() ? "timeout" : "closed", message: "stream aborted" }, "delivered-no-response");
605
+ }
606
+ return fail({ kind: "stream-broken", message: "SSE stream broke" }, "delivered-no-response");
607
+ }
608
+ if (chunk.done)
609
+ break;
610
+ args.armIdle();
611
+ totalBytes += chunk.value.byteLength;
612
+ if (totalBytes > this.maxSseStreamBytes) {
613
+ await reader.cancel().catch(() => undefined);
614
+ return fail({ kind: "too-large", message: `SSE stream exceeds ${this.maxSseStreamBytes} bytes` }, "delivered-no-response");
615
+ }
616
+ let events;
617
+ try {
618
+ events = parser.push(chunk.value);
619
+ }
620
+ catch {
621
+ await reader.cancel().catch(() => undefined);
622
+ return fail({ kind: "too-large", message: "SSE event exceeds size limit" }, "delivered-no-response");
623
+ }
624
+ for (const ev of events) {
625
+ if (ev.event !== "" && ev.event !== "message") {
626
+ this.emit("violation", "ignored non-message SSE event (HTTP-SSE-2)");
627
+ continue;
628
+ }
629
+ // ev.id / ev.retry are parsed and deliberately discarded (HTTP-SSE-3).
630
+ let payload;
631
+ try {
632
+ payload = JSON.parse(ev.data);
633
+ }
634
+ catch {
635
+ this.emit("violation", "SSE data is not valid JSON (EDGE-20); event dropped");
636
+ continue;
637
+ }
638
+ if (Array.isArray(payload)) {
639
+ this.emit("violation", "JSON-RPC batch on SSE stream rejected");
640
+ continue;
641
+ }
642
+ const inbound = parseInboundMessage(payload);
643
+ if ("error" in inbound) {
644
+ this.emit("violation", "invalid JSON-RPC message on SSE stream");
645
+ continue;
646
+ }
647
+ if (inbound.kind === "server-request") {
648
+ await reader.cancel().catch(() => undefined);
649
+ this.emit("violation", "server sent an independent JSON-RPC request on the SSE stream (HTTP-SSE-4)");
650
+ return fail({ kind: "stream-broken", message: "protocol-violation: request on SSE stream" }, "delivered-no-response");
651
+ }
652
+ if (inbound.kind === "notification") {
653
+ const notif = inbound.message;
654
+ if (!this.isRelatedNotification(notif, args, method)) {
655
+ this.emit("violation", "dropped unrelated SSE notification (HTTP-SSE-5)");
656
+ continue;
657
+ }
658
+ notifications.push(notif);
659
+ continue;
660
+ }
661
+ const message = this.normalizeResponseId(inbound.message, args.wireId, expectedId);
662
+ if (expectedId !== undefined && message.id !== expectedId) {
663
+ this.emit("violation", "dropped SSE response with mismatched id");
664
+ continue;
665
+ }
666
+ if (finalMessage) {
667
+ this.emit("violation", "second response for same id on SSE stream (HTTP-SSE-7)");
668
+ continue;
669
+ }
670
+ finalMessage = message;
671
+ // Final response should terminate the stream: cancel body, ignore later events (HTTP-SSE-6).
672
+ await reader.cancel().catch(() => undefined);
673
+ if (method === "tools/list" && !("error" in finalMessage)) {
674
+ finalMessage = this.processToolsList(finalMessage, args.credentials);
675
+ }
676
+ if ("error" in finalMessage && finalMessage.error.code === -32020) {
677
+ return { kind: "header-mismatch", message: finalMessage };
678
+ }
679
+ return { kind: "final", end: { kind: "response", message: finalMessage } };
680
+ }
681
+ }
682
+ }
683
+ finally {
684
+ try {
685
+ parser.end();
686
+ }
687
+ catch {
688
+ /* ignore flush errors after settle */
689
+ }
690
+ await reader.cancel().catch(() => undefined);
691
+ }
692
+ if (finalMessage)
693
+ return { kind: "final", end: { kind: "response", message: finalMessage } };
694
+ if (args.ctx.signal.aborted || args.controller.signal.aborted) {
695
+ return fail({ kind: args.timedOut() ? "timeout" : "closed", message: "request aborted" }, "delivered-no-response");
696
+ }
697
+ this.emit("violation", "SSE stream ended without a final response");
698
+ return fail({ kind: "stream-broken", message: "stream-ended-without-response" }, "delivered-no-response");
699
+ }
700
+ isRelatedNotification(notif, args, method) {
701
+ const params = isRecord(notif.params) ? notif.params : {};
702
+ if (notif.method === "notifications/progress") {
703
+ if (method === "subscriptions/listen")
704
+ return false; // HTTP-SSE-8
705
+ const token = params["progressToken"];
706
+ // RequestManager sets progressToken to the request id; accept wire/original id too.
707
+ if (token === args.expectedId || token === args.wireId)
708
+ return true;
709
+ return args.expectedId === undefined && token !== undefined;
710
+ }
711
+ const meta = isRecord(params["_meta"]) ? params["_meta"] : undefined;
712
+ const subId = meta?.[META_SUBSCRIPTION_ID] ?? params["subscriptionId"];
713
+ if (typeof subId === "string") {
714
+ // Accept only when it matches a token/id we know; otherwise still accept on listen streams carrying any sub id.
715
+ return method === "subscriptions/listen" || typeof params["subscriptionId"] === "string";
716
+ }
717
+ // Non-progress notifications without routing keys are treated as related to this request-scoped stream.
718
+ return true;
719
+ }
720
+ normalizeResponseId(message, wireId, expectedId) {
721
+ if (wireId !== undefined && expectedId !== undefined && wireId !== expectedId && message.id === wireId) {
722
+ return { ...message, id: expectedId };
723
+ }
724
+ return message;
725
+ }
726
+ processToolsList(message, credentials) {
727
+ const result = message.result;
728
+ if (!isRecord(result) || !Array.isArray(result["tools"]))
729
+ return message;
730
+ const kept = [];
731
+ for (const tool of result["tools"]) {
732
+ if (!isRecord(tool)) {
733
+ kept.push(tool);
734
+ continue;
735
+ }
736
+ const name = typeof tool["name"] === "string" ? tool["name"] : "(unnamed)";
737
+ const validation = validateXmcpHeaderSchema(tool["inputSchema"]);
738
+ if (!validation.valid) {
739
+ for (const v of validation.violations) {
740
+ const detail = `x-mcp-header: tool '${name}' excluded: ${v}`;
741
+ this.emit("violation", [...credentials].some(secret => detail.includes(secret))
742
+ ? "x-mcp-header: tool excluded due to invalid header annotations" : detail);
743
+ this.logger?.warn("x-mcp-header tool excluded", { tool: name, violation: v });
744
+ }
745
+ continue; // HTTP-PARAM-2
746
+ }
747
+ kept.push(tool);
748
+ if (typeof tool["name"] === "string")
749
+ this.toolParams.set(tool["name"], validation.params);
750
+ }
751
+ return { ...message, result: { ...result, tools: kept } };
752
+ }
753
+ buildHeaders(wireMsg, ctx) {
754
+ const headers = new Headers();
755
+ headers.set("Content-Type", "application/json");
756
+ headers.set("Accept", "application/json, text/event-stream");
757
+ const params = isRecord(wireMsg.params) ? wireMsg.params : {};
758
+ const meta = isRecord(params["_meta"]) ? params["_meta"] : {};
759
+ const version = typeof meta[META_PROTOCOL_VERSION] === "string"
760
+ ? meta[META_PROTOCOL_VERSION]
761
+ : (this.protocolVersion ?? SUPPORTED_PROTOCOL_VERSION);
762
+ headers.set("MCP-Protocol-Version", version);
763
+ headers.set("Mcp-Method", wireMsg.method);
764
+ // Mcp-Name (HTTP-HDR-3)
765
+ let name;
766
+ if ("id" in wireMsg) {
767
+ if (ctx.headersHint?.name)
768
+ name = ctx.headersHint.name;
769
+ else if ((wireMsg.method === "tools/call" || wireMsg.method === "prompts/get") && typeof params["name"] === "string")
770
+ name = params["name"];
771
+ else if (wireMsg.method === "resources/read" && typeof params["uri"] === "string")
772
+ name = params["uri"];
773
+ }
774
+ if (name !== undefined)
775
+ headers.set("Mcp-Name", encodeHeaderValue(name));
776
+ // Mcp-Param-* mirroring (HTTP-PARAM-4/5)
777
+ if ("id" in wireMsg && wireMsg.method === "tools/call") {
778
+ const toolName = typeof params["name"] === "string" ? params["name"] : undefined;
779
+ const annotated = toolName ? this.toolParams.get(toolName) : undefined;
780
+ if (annotated) {
781
+ const args = isRecord(params["arguments"]) ? params["arguments"] : params;
782
+ for (const p of annotated) {
783
+ const value = extractAtPath(args, p.path);
784
+ if (value === undefined || value === null)
785
+ continue;
786
+ if (p.type === "integer" && (typeof value !== "number" || !Number.isSafeInteger(value))) {
787
+ this.emit("violation", `Mcp-Param-${p.headerName} omitted: integer value out of safe range or not an integer`);
788
+ continue;
789
+ }
790
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
791
+ headers.set(`Mcp-Param-${p.headerName}`, encodeHeaderValue(value));
792
+ }
793
+ }
794
+ }
795
+ }
796
+ if ("id" in wireMsg && ctx.headersHint?.params) {
797
+ for (const [k, v] of Object.entries(ctx.headersHint.params)) {
798
+ headers.set(`Mcp-Param-${k}`, encodeHeaderValue(v));
799
+ }
800
+ }
801
+ for (const [k, v] of Object.entries(this.extraHeaders)) {
802
+ if (FORBIDDEN_OUTBOUND.has(k.toLowerCase())) {
803
+ this.emit("violation", `refused forbidden outbound header '${k}'`);
804
+ continue;
805
+ }
806
+ headers.set(k, v);
807
+ }
808
+ // Hard guarantee for the wire scan: these are never emitted.
809
+ headers.delete("Mcp-Session-Id");
810
+ headers.delete("Last-Event-ID");
811
+ return headers;
812
+ }
813
+ async readBodyText(response, maxBytes) {
814
+ if (!response.body) {
815
+ const text = await response.text();
816
+ if (new TextEncoder().encode(text).byteLength > maxBytes)
817
+ throw new TooLargeError(maxBytes);
818
+ return text;
819
+ }
820
+ const reader = response.body.getReader();
821
+ const chunks = [];
822
+ let total = 0;
823
+ for (;;) {
824
+ const { done, value } = await reader.read();
825
+ if (done)
826
+ break;
827
+ total += value.byteLength;
828
+ if (total > maxBytes) {
829
+ await reader.cancel().catch(() => undefined);
830
+ throw new TooLargeError(maxBytes);
831
+ }
832
+ chunks.push(value);
833
+ }
834
+ const merged = new Uint8Array(total);
835
+ let off = 0;
836
+ for (const c of chunks) {
837
+ merged.set(c, off);
838
+ off += c.byteLength;
839
+ }
840
+ return new TextDecoder().decode(merged);
841
+ }
842
+ emit(kind, message) {
843
+ this.diag.emit({ kind, message, atMs: this.clock.now() });
844
+ }
845
+ }
846
+ class TooLargeError extends Error {
847
+ constructor(max) {
848
+ super(`response body exceeds ${max} bytes (HTTP-LIMIT-1)`);
849
+ this.name = "TooLargeError";
850
+ }
851
+ }
852
+ function emptyNotificationAck(id) {
853
+ return { jsonrpc: "2.0", id: id ?? 0, result: { resultType: "complete" } };
854
+ }
855
+ //# sourceMappingURL=transport.js.map