@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,744 @@
1
+ import { spawn } from "node:child_process";
2
+ import { clearTimeout, setTimeout } from "node:timers";
3
+ import { DEFAULT_MAX_DIAGNOSTICS, DiagnosticChannel, isReadOnlyMethod, JSONRPC_VERSION, NotificationQueue, parseInboundMessage, systemClock, } from "../core/index.js";
4
+ import { DEFAULT_MAX_LINE_BYTES, encodeStdioMessage, LineSplitter } from "./framing.js";
5
+ import { DEFAULT_STDERR_MAX_BYTES, DEFAULT_STDERR_MAX_LINE_BYTES, StderrRingBuffer, } from "./stderr-ring.js";
6
+ import { WriteQueue } from "./write-queue.js";
7
+ export const META_PROGRESS_TOKEN = "io.modelcontextprotocol/progressToken";
8
+ export const META_SUBSCRIPTION_ID = "io.modelcontextprotocol/subscriptionId";
9
+ export const DEFAULT_MAX_NOISE_LINES = 100;
10
+ export const DEFAULT_MAX_NOISE_BYTES = 1 * 1024 * 1024; // 1 MiB
11
+ export const DEFAULT_GRACE_MS = 2000;
12
+ export const DEFAULT_TERM_MS = 2000;
13
+ export const DEFAULT_MAX_RESTARTS = 3;
14
+ export const DEFAULT_RESTART_WINDOW_MS = 60_000;
15
+ export const DEFAULT_RESTART_BACKOFF_MS = 100;
16
+ export { isReadOnlyMethod };
17
+ function keyOfId(id) {
18
+ return `${typeof id}:${String(id)}`;
19
+ }
20
+ function buildChildEnv(explicitEnv, inheritEnv) {
21
+ const allow = inheritEnv ?? (process.platform === "win32" ? ["PATH", "SystemRoot", "PATHEXT"] : ["PATH"]);
22
+ const out = {};
23
+ for (const k of allow) {
24
+ const val = process.env[k];
25
+ if (val !== undefined) {
26
+ out[k] = val;
27
+ }
28
+ }
29
+ if (explicitEnv) {
30
+ for (const [k, v] of Object.entries(explicitEnv)) {
31
+ out[k] = v;
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+ export class StdioTransport {
37
+ binding = "stdio";
38
+ command;
39
+ args;
40
+ cwd;
41
+ childEnv;
42
+ maxLineBytes;
43
+ maxNoiseLines;
44
+ maxNoiseBytes;
45
+ graceMs;
46
+ termMs;
47
+ restartPolicy;
48
+ maxRestarts;
49
+ restartWindowMs;
50
+ restartBackoffMs;
51
+ clock;
52
+ spawnFn;
53
+ diagChannel;
54
+ stderrRing;
55
+ writeQueue = new WriteQueue();
56
+ splitter;
57
+ pending = new Map();
58
+ progressMap = new Map();
59
+ subscriptionListeners = new Map();
60
+ settledIds = [];
61
+ settledIdSet = new Set();
62
+ _state = "idle";
63
+ run;
64
+ closing;
65
+ hasSpawnedOnce = false;
66
+ restartTimestamps = [];
67
+ cancelRestartTimer;
68
+ noiseLines = 0;
69
+ noiseBytes = 0;
70
+ fatalFailure;
71
+ constructor(opts) {
72
+ this.command = opts.command;
73
+ this.args = opts.args ?? [];
74
+ if (opts.cwd !== undefined) {
75
+ this.cwd = opts.cwd;
76
+ }
77
+ this.childEnv = buildChildEnv(opts.env, opts.inheritEnv);
78
+ this.maxLineBytes = opts.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES;
79
+ this.maxNoiseLines = opts.maxNoiseLines ?? DEFAULT_MAX_NOISE_LINES;
80
+ this.maxNoiseBytes = opts.maxNoiseBytes ?? DEFAULT_MAX_NOISE_BYTES;
81
+ this.graceMs = opts.graceMs ?? DEFAULT_GRACE_MS;
82
+ this.termMs = opts.termMs ?? DEFAULT_TERM_MS;
83
+ this.restartPolicy = opts.restart?.policy ?? "on-demand";
84
+ this.maxRestarts = opts.restart?.maxRestarts ?? DEFAULT_MAX_RESTARTS;
85
+ this.restartWindowMs = opts.restart?.windowMs ?? DEFAULT_RESTART_WINDOW_MS;
86
+ this.restartBackoffMs = opts.restart?.backoffMs ?? DEFAULT_RESTART_BACKOFF_MS;
87
+ this.clock = opts.clock ?? systemClock;
88
+ this.spawnFn = opts.spawnFn ?? spawn;
89
+ this.diagChannel = new DiagnosticChannel(opts.maxDiagnostics ?? DEFAULT_MAX_DIAGNOSTICS);
90
+ this.splitter = new LineSplitter(this.maxLineBytes);
91
+ this.stderrRing = new StderrRingBuffer({
92
+ maxTotalBytes: opts.stderrMaxBytes ?? DEFAULT_STDERR_MAX_BYTES,
93
+ maxLineBytes: opts.stderrMaxLineBytes ?? DEFAULT_STDERR_MAX_LINE_BYTES,
94
+ onLine: (line) => {
95
+ this.emitDiag("stderr", line);
96
+ opts.onStderr?.(line);
97
+ },
98
+ });
99
+ }
100
+ get state() {
101
+ return this._state;
102
+ }
103
+ get pid() {
104
+ return this.run?.child.pid;
105
+ }
106
+ get diagnostics() {
107
+ return this.diagChannel;
108
+ }
109
+ stderrSnapshot() {
110
+ return this.stderrRing.snapshot();
111
+ }
112
+ diagnosticsSnapshot() {
113
+ return this.diagChannel.snapshot();
114
+ }
115
+ /**
116
+ * Registers an external listener for notifications matching `io.modelcontextprotocol/subscriptionId` (STDIO-ROUTE-2).
117
+ */
118
+ registerSubscription(subscriptionId, listener) {
119
+ const key = keyOfId(subscriptionId);
120
+ let set = this.subscriptionListeners.get(key);
121
+ if (!set) {
122
+ set = new Set();
123
+ this.subscriptionListeners.set(key, set);
124
+ }
125
+ set.add(listener);
126
+ return () => {
127
+ set.delete(listener);
128
+ if (set.size === 0 && this.subscriptionListeners.get(key) === set) {
129
+ this.subscriptionListeners.delete(key);
130
+ }
131
+ };
132
+ }
133
+ start(msg, ctx) {
134
+ const notifications = new NotificationQueue();
135
+ // Validate outbound message shape & framing before doing anything (WIRE-DIR-1, STDIO-FRAME-1, STDIO-STDIN-1)
136
+ const payload = encodeStdioMessage(msg);
137
+ // Abort before send -> zero wire bytes (EDGE-6, STDIO-CANCEL-1)
138
+ if (ctx.signal.aborted) {
139
+ notifications.close();
140
+ return {
141
+ notifications,
142
+ done: Promise.resolve({
143
+ kind: "failure",
144
+ failure: { kind: "closed", message: "aborted before send" },
145
+ delivery: "not-sent",
146
+ }),
147
+ };
148
+ }
149
+ if (this._state === "closing" || this._state === "closed") {
150
+ notifications.close();
151
+ return {
152
+ notifications,
153
+ done: Promise.resolve({
154
+ kind: "failure",
155
+ failure: { kind: "closed", message: "StdioTransport is closed" },
156
+ delivery: "not-sent",
157
+ }),
158
+ };
159
+ }
160
+ if (this._state === "failed") {
161
+ notifications.close();
162
+ return {
163
+ notifications,
164
+ done: Promise.resolve({
165
+ kind: "failure",
166
+ failure: this.fatalFailure ?? { kind: "process-exit", message: "StdioTransport is in failed state" },
167
+ delivery: "not-sent",
168
+ }),
169
+ };
170
+ }
171
+ const spawnErr = this.ensureStarted();
172
+ if (spawnErr) {
173
+ notifications.close();
174
+ return {
175
+ notifications,
176
+ done: Promise.resolve({
177
+ kind: "failure",
178
+ failure: spawnErr,
179
+ delivery: "not-sent",
180
+ }),
181
+ };
182
+ }
183
+ const reqKey = keyOfId(msg.id);
184
+ const meta = msg.params && typeof msg.params["_meta"] === "object" && msg.params["_meta"] !== null
185
+ ? msg.params["_meta"]
186
+ : undefined;
187
+ const rawProgressToken = meta?.[META_PROGRESS_TOKEN];
188
+ const progressTokenKey = typeof rawProgressToken === "string" || typeof rawProgressToken === "number"
189
+ ? keyOfId(rawProgressToken)
190
+ : undefined;
191
+ if (this.pending.has(reqKey))
192
+ throw new Error(`Duplicate in-flight request id=${reqKey}`);
193
+ let resolveDone;
194
+ const done = new Promise((resolve) => {
195
+ resolveDone = resolve;
196
+ });
197
+ const entry = {
198
+ key: reqKey,
199
+ id: msg.id,
200
+ method: msg.method,
201
+ ...(progressTokenKey !== undefined ? { progressTokenKey } : {}),
202
+ notifications,
203
+ resolve: resolveDone,
204
+ signal: ctx.signal,
205
+ writeState: "queued",
206
+ settled: false,
207
+ };
208
+ const onAbort = () => {
209
+ this.handleRequestAbort(entry);
210
+ };
211
+ entry.onAbort = onAbort;
212
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
213
+ this.pending.set(reqKey, entry);
214
+ if (progressTokenKey !== undefined) {
215
+ this.progressMap.set(progressTokenKey, entry);
216
+ }
217
+ this.writeQueue
218
+ .enqueue({
219
+ payload,
220
+ key: reqKey,
221
+ priority: false,
222
+ onStateChange: (st) => {
223
+ entry.writeState = st;
224
+ },
225
+ })
226
+ .catch((err) => {
227
+ if (entry.settled || this.run?.disconnected)
228
+ return;
229
+ const message = err instanceof Error ? err.message : String(err);
230
+ if (message === "removed-from-queue")
231
+ return;
232
+ this.settlePending(entry, {
233
+ kind: "failure",
234
+ failure: { kind: "stream-broken", message: `stdin write failed: ${message}`, cause: err },
235
+ delivery: this.deliveryForWriteState(entry.writeState),
236
+ });
237
+ });
238
+ return { notifications, done };
239
+ }
240
+ async notify(msg, ctx) {
241
+ const payload = encodeStdioMessage(msg);
242
+ if (ctx.signal.aborted)
243
+ return;
244
+ if (this._state === "closing" || this._state === "closed" || this._state === "failed") {
245
+ throw new Error(`Cannot send notification while StdioTransport is ${this._state}`);
246
+ }
247
+ const spawnErr = this.ensureStarted();
248
+ if (spawnErr) {
249
+ throw new Error(spawnErr.message);
250
+ }
251
+ const isCancel = msg.method === "notifications/cancelled";
252
+ await this.writeQueue.enqueue({ payload, priority: isCancel });
253
+ }
254
+ close(opts) {
255
+ return this.closing ??= this.closeTransport(opts);
256
+ }
257
+ async closeTransport(opts) {
258
+ this._state = "closing";
259
+ this.cancelRestartTimer?.();
260
+ this.cancelRestartTimer = undefined;
261
+ // Settle all pending requests with delivery certainty (6.3 / 6.5)
262
+ this.settleAllPending({ kind: "closed", message: "StdioTransport closing" });
263
+ this.writeQueue.detach(new Error("transport closing"));
264
+ const run = this.run;
265
+ if (run) {
266
+ await this.stopChild(run, opts?.graceMs ?? this.graceMs, opts?.termMs ?? this.termMs);
267
+ }
268
+ this.subscriptionListeners.clear();
269
+ this._state = "closed";
270
+ this.diagChannel.close();
271
+ }
272
+ ensureStarted() {
273
+ if (this.run) {
274
+ const { child, disconnected } = this.run;
275
+ return disconnected || child.exitCode !== null || child.signalCode !== null
276
+ ? { kind: "process-exit", message: "Previous child is shutting down" }
277
+ : undefined;
278
+ }
279
+ // Cancel any scheduled auto-restart since we are spawning now
280
+ this.cancelRestartTimer?.();
281
+ this.cancelRestartTimer = undefined;
282
+ if (this.hasSpawnedOnce) {
283
+ const now = this.clock.now();
284
+ this.pruneRestartWindow(now);
285
+ if (this.restartTimestamps.length >= this.maxRestarts) {
286
+ const failure = {
287
+ kind: "process-exit",
288
+ message: `Restart loop guard tripped (${this.maxRestarts} restarts within ${this.restartWindowMs}ms)`,
289
+ };
290
+ this.fatalFailure = failure;
291
+ this._state = "failed";
292
+ this.emitDiag("lifecycle", failure.message);
293
+ return failure;
294
+ }
295
+ this.restartTimestamps.push(now);
296
+ this.emitDiag("lifecycle", `restarting child process (attempt ${this.restartTimestamps.length}/${this.maxRestarts})`);
297
+ }
298
+ this.hasSpawnedOnce = true;
299
+ this._state = "spawning";
300
+ this.noiseLines = 0;
301
+ this.noiseBytes = 0;
302
+ this.splitter.reset();
303
+ let child;
304
+ try {
305
+ // STDIO-LAUNCH-1: shell: false, windowsHide: true, stdio: pipe
306
+ child = this.spawnFn(this.command, [...this.args], {
307
+ stdio: ["pipe", "pipe", "pipe"],
308
+ shell: false,
309
+ windowsHide: true,
310
+ ...(this.cwd !== undefined ? { cwd: this.cwd } : {}),
311
+ env: this.childEnv,
312
+ });
313
+ }
314
+ catch (err) {
315
+ const failure = {
316
+ kind: "spawn",
317
+ message: `Failed to spawn '${this.command}': ${err instanceof Error ? err.message : String(err)}`,
318
+ cause: err,
319
+ };
320
+ this.fatalFailure = failure;
321
+ this._state = "failed";
322
+ this.emitDiag("lifecycle", failure.message);
323
+ return failure;
324
+ }
325
+ const run = {
326
+ child,
327
+ closed: new Promise((resolve) => child.once("close", () => resolve())),
328
+ disconnected: false,
329
+ };
330
+ this.run = run;
331
+ child.once("spawn", () => {
332
+ if (this._state !== "spawning")
333
+ return;
334
+ this._state = "ready";
335
+ this.emitDiag("lifecycle", `spawned pid=${String(child.pid)} command=${this.command}`);
336
+ if (child.stdin)
337
+ this.writeQueue.attach(child.stdin);
338
+ });
339
+ child.stdin?.on("error", (err) => {
340
+ this.emitDiag("lifecycle", `stdin error: ${err.message}`);
341
+ this.disconnect(run);
342
+ });
343
+ child.stdin?.once("close", () => this.disconnect(run));
344
+ child.stdout?.on("error", (err) => {
345
+ this.emitDiag("lifecycle", `stdout error: ${err.message}`);
346
+ this.disconnect(run);
347
+ });
348
+ child.stdout?.on("data", (chunk) => {
349
+ if (this._state === "ready")
350
+ this.handleStdoutChunk(chunk);
351
+ });
352
+ child.stdout?.once("end", () => {
353
+ const rem = this.splitter.flushRemainderPreview();
354
+ if (rem) {
355
+ run.eofMidLine = true;
356
+ this.emitDiag("violation", `eof-mid-line: ${rem.byteLength} trailing bytes without newline: ${rem.preview}`);
357
+ }
358
+ this.disconnect(run);
359
+ });
360
+ child.stderr?.on("data", (chunk) => this.stderrRing.push(chunk));
361
+ child.stderr?.once("end", () => this.stderrRing.flush());
362
+ child.on("error", (err) => {
363
+ if (this._state !== "spawning") {
364
+ this.emitDiag("lifecycle", `child process error: ${err.message}`);
365
+ return;
366
+ }
367
+ const failure = {
368
+ kind: "spawn",
369
+ message: `Failed to spawn '${this.command}' (${err.code ?? "ERR"}): ${err.message}`,
370
+ cause: err,
371
+ };
372
+ this.fatalFailure = failure;
373
+ this._state = "failed";
374
+ this.emitDiag("lifecycle", failure.message);
375
+ this.writeQueue.detach(err);
376
+ this.settleAllPending(failure);
377
+ });
378
+ child.once("close", (code, signal) => {
379
+ this.run = undefined;
380
+ this.handleUnexpectedClose(code, signal, run.eofMidLine === true);
381
+ });
382
+ return undefined;
383
+ }
384
+ handleStdoutChunk(chunk) {
385
+ const events = this.splitter.push(chunk);
386
+ for (const ev of events) {
387
+ if (ev.kind === "oversize") {
388
+ const failure = {
389
+ kind: "too-large",
390
+ message: `Oversize stdout line (${ev.byteLength} bytes > ${ev.maxLineBytes} maxLineBytes)`,
391
+ };
392
+ this.emitDiag("violation", failure.message);
393
+ this.failTransportAndKill(failure);
394
+ return;
395
+ }
396
+ if (ev.kind === "invalid-utf8") {
397
+ this.emitDiag("violation", `invalid-utf8 (${ev.byteLength} bytes): ${ev.preview}`);
398
+ if (this.recordNoise(ev.byteLength))
399
+ return;
400
+ continue;
401
+ }
402
+ this.handleInboundLine(ev.text, ev.byteLength);
403
+ if (this._state === "failed" || this._state === "closing" || this._state === "closed") {
404
+ return;
405
+ }
406
+ }
407
+ }
408
+ handleInboundLine(text, byteLength) {
409
+ let parsedJson;
410
+ try {
411
+ parsedJson = JSON.parse(text);
412
+ }
413
+ catch {
414
+ const preview = text.length > 256 ? text.slice(0, 256) : text;
415
+ this.emitDiag("noise", `stdout-noise: ${preview}`);
416
+ this.recordNoise(byteLength);
417
+ return;
418
+ }
419
+ // STDIO-BATCH-1: JSON-RPC batch/array is a protocol violation
420
+ if (Array.isArray(parsedJson)) {
421
+ this.emitDiag("violation", "protocol-violation: JSON-RPC batch array is not supported (STDIO-BATCH-1)");
422
+ // If any element references an in-flight request id, fail it so callers do not hang
423
+ for (const elem of parsedJson) {
424
+ if (typeof elem === "object" && elem !== null && "id" in elem) {
425
+ const id = elem["id"];
426
+ if (typeof id === "string" || typeof id === "number") {
427
+ const entry = this.pending.get(keyOfId(id));
428
+ if (entry) {
429
+ this.settlePending(entry, {
430
+ kind: "failure",
431
+ failure: {
432
+ kind: "stream-broken",
433
+ message: "protocol-violation: JSON-RPC batch array rejected (STDIO-BATCH-1)",
434
+ },
435
+ delivery: this.deliveryForWriteState(entry.writeState),
436
+ });
437
+ }
438
+ }
439
+ }
440
+ }
441
+ this.recordNoise(byteLength);
442
+ return;
443
+ }
444
+ const parsed = parseInboundMessage(parsedJson);
445
+ if ("error" in parsed) {
446
+ const preview = text.length > 256 ? text.slice(0, 256) : text;
447
+ this.emitDiag("noise", `stdout-noise (${parsed.error}): ${preview}`);
448
+ this.recordNoise(byteLength);
449
+ return;
450
+ }
451
+ for (const d of parsed.diagnostics) {
452
+ this.emitDiag("violation", d);
453
+ }
454
+ if (parsed.kind === "server-request") {
455
+ // WIRE-DIR-2 / EDGE-35: never reply to server-initiated JSON-RPC requests
456
+ this.emitDiag("violation", `server-initiated request ignored without reply: method=${parsed.message.method}`);
457
+ this.recordNoise(byteLength);
458
+ return;
459
+ }
460
+ if (parsed.kind === "notification") {
461
+ this.routeNotification(parsed.message);
462
+ return;
463
+ }
464
+ // Response or error response
465
+ const msg = parsed.message;
466
+ if (!("id" in msg) || msg.id === null || (typeof msg.id !== "string" && typeof msg.id !== "number")) {
467
+ // WIRE-ERR-2 / EDGE-4: error with null/missing id is diagnostic only
468
+ this.emitDiag("violation", "uncorrelated error response with null/missing id");
469
+ return;
470
+ }
471
+ const reqKey = keyOfId(msg.id);
472
+ const entry = this.pending.get(reqKey);
473
+ if (!entry) {
474
+ if (this.settledIdSet.has(reqKey)) {
475
+ // EDGE-2 / WIRE-CANCEL-3: duplicate or late response
476
+ this.emitDiag("violation", `duplicate-or-late-response for id=${String(msg.id)}`);
477
+ }
478
+ else {
479
+ // EDGE-3: unknown id or id type mismatch
480
+ this.emitDiag("noise", `unknown response id=${reqKey}`);
481
+ }
482
+ return;
483
+ }
484
+ this.settlePending(entry, {
485
+ kind: "response",
486
+ message: msg,
487
+ });
488
+ }
489
+ routeNotification(notif) {
490
+ // WIRE-LOG-1 / EDGE-33: deprecated logging notifications dropped
491
+ if (notif.method === "notifications/message") {
492
+ this.emitDiag("noise", "dropped deprecated notifications/message");
493
+ return;
494
+ }
495
+ // STDIO-ROUTE-1: progress notifications by progressToken
496
+ if (notif.method === "notifications/progress" && notif.params) {
497
+ const token = notif.params["progressToken"];
498
+ if (typeof token === "string" || typeof token === "number") {
499
+ const entry = this.progressMap.get(keyOfId(token));
500
+ if (entry && !entry.settled) {
501
+ entry.notifications.push(notif);
502
+ return;
503
+ }
504
+ }
505
+ this.emitDiag("noise", `dropped progress notification for inactive token`);
506
+ return;
507
+ }
508
+ // STDIO-ROUTE-2: subscription notifications by _meta["io.modelcontextprotocol/subscriptionId"]
509
+ const meta = notif.params && typeof notif.params["_meta"] === "object" && notif.params["_meta"] !== null
510
+ ? notif.params["_meta"]
511
+ : undefined;
512
+ const subId = meta?.[META_SUBSCRIPTION_ID];
513
+ if ((typeof subId === "string" && subId.length > 0) || (typeof subId === "number" && Number.isInteger(subId))) {
514
+ const key = keyOfId(subId);
515
+ let delivered = false;
516
+ const entry = this.pending.get(key);
517
+ if (entry?.method === "subscriptions/listen") {
518
+ entry.notifications.push(notif);
519
+ delivered = true;
520
+ }
521
+ const listeners = this.subscriptionListeners.get(key);
522
+ if (listeners && listeners.size > 0) {
523
+ for (const fn of listeners) {
524
+ fn(notif);
525
+ }
526
+ delivered = true;
527
+ }
528
+ if (!delivered) {
529
+ this.emitDiag("noise", `unroutable subscription notification for subscriptionId=${subId}`);
530
+ }
531
+ return;
532
+ }
533
+ // WIRE-CANCEL-4: server notifications/cancelled only for subscriptions/listen ids
534
+ if (notif.method === "notifications/cancelled" && notif.params) {
535
+ const reqId = notif.params["requestId"];
536
+ if (typeof reqId === "string" || typeof reqId === "number") {
537
+ const entry = this.pending.get(keyOfId(reqId));
538
+ if (entry && !entry.settled && entry.method === "subscriptions/listen") {
539
+ entry.notifications.push(notif);
540
+ return;
541
+ }
542
+ }
543
+ this.emitDiag("noise", "ignored server notifications/cancelled for non-listen request");
544
+ return;
545
+ }
546
+ this.emitDiag("noise", `unroutable notification: method=${notif.method}`);
547
+ }
548
+ recordNoise(byteLength) {
549
+ this.noiseLines += 1;
550
+ this.noiseBytes += byteLength;
551
+ if (this.noiseLines > this.maxNoiseLines || this.noiseBytes > this.maxNoiseBytes) {
552
+ const failure = {
553
+ kind: "stream-broken",
554
+ message: `protocol-noise: stdout noise budget exceeded (${this.noiseLines} lines, ${this.noiseBytes} bytes)`,
555
+ };
556
+ this.emitDiag("violation", failure.message);
557
+ this.failTransportAndKill(failure);
558
+ return true;
559
+ }
560
+ return false;
561
+ }
562
+ handleRequestAbort(entry) {
563
+ if (entry.settled)
564
+ return;
565
+ // STDIO-CANCEL-1: queued unsent request is removed without writing to stdin
566
+ if (entry.writeState === "queued" && this.writeQueue.removeQueued(entry.key)) {
567
+ this.settlePending(entry, {
568
+ kind: "failure",
569
+ failure: { kind: "closed", message: "cancelled while queued" },
570
+ delivery: "not-sent",
571
+ });
572
+ return;
573
+ }
574
+ // Already writing or sent -> send priority notifications/cancelled
575
+ const delivery = this.deliveryForWriteState(entry.writeState);
576
+ const reason = typeof entry.signal.reason === "string" ? entry.signal.reason : undefined;
577
+ const cancelMsg = {
578
+ jsonrpc: JSONRPC_VERSION,
579
+ method: "notifications/cancelled",
580
+ params: {
581
+ requestId: entry.id,
582
+ ...(reason !== undefined ? { reason } : {}),
583
+ },
584
+ };
585
+ if ((this._state === "ready" || this._state === "spawning") && !this.run?.disconnected) {
586
+ this.writeQueue
587
+ .enqueue({
588
+ payload: encodeStdioMessage(cancelMsg),
589
+ priority: true,
590
+ })
591
+ .catch(() => { });
592
+ }
593
+ this.settlePending(entry, {
594
+ kind: "failure",
595
+ failure: { kind: "closed", message: "request cancelled" },
596
+ delivery,
597
+ });
598
+ }
599
+ disconnect(run) {
600
+ if (this.run !== run || this._state !== "ready" || run.disconnected)
601
+ return;
602
+ run.disconnected = true;
603
+ this.writeQueue.detach(new Error("child pipe disconnected"));
604
+ // Drain any last replies and reap before another child can own the pipes.
605
+ this.retireChild(run);
606
+ }
607
+ handleUnexpectedClose(code, signal, eofMidLine) {
608
+ if (this._state === "closing" || this._state === "closed" || this._state === "failed") {
609
+ return;
610
+ }
611
+ const detail = `child process exited unexpectedly (code=${String(code)}, signal=${String(signal)})${eofMidLine ? ": eof-mid-line" : ""}`;
612
+ this.emitDiag("lifecycle", detail);
613
+ const failure = {
614
+ kind: "process-exit",
615
+ message: detail,
616
+ };
617
+ this.writeQueue.detach(new Error(detail));
618
+ this.settleAllPending(failure);
619
+ if (this.restartPolicy === "auto") {
620
+ const now = this.clock.now();
621
+ this.pruneRestartWindow(now);
622
+ if (this.restartTimestamps.length >= this.maxRestarts) {
623
+ const guardFailure = {
624
+ kind: "process-exit",
625
+ message: `Restart loop guard tripped (${this.maxRestarts} restarts within ${this.restartWindowMs}ms)`,
626
+ };
627
+ this.fatalFailure = guardFailure;
628
+ this._state = "failed";
629
+ this.emitDiag("lifecycle", guardFailure.message);
630
+ return;
631
+ }
632
+ this._state = "idle";
633
+ this.cancelRestartTimer = this.clock.setTimeout(() => {
634
+ this.cancelRestartTimer = undefined;
635
+ if (this._state === "idle") {
636
+ this.ensureStarted();
637
+ }
638
+ }, this.restartBackoffMs);
639
+ }
640
+ else {
641
+ // on-demand: return to idle; next request will respawn (checked against restart loop guard)
642
+ this._state = "idle";
643
+ }
644
+ }
645
+ failTransportAndKill(failure) {
646
+ this.fatalFailure = failure;
647
+ this._state = "failed";
648
+ this.cancelRestartTimer?.();
649
+ this.cancelRestartTimer = undefined;
650
+ this.writeQueue.detach(new Error(failure.message));
651
+ this.settleAllPending(failure);
652
+ if (this.run)
653
+ this.retireChild(this.run);
654
+ }
655
+ retireChild(run) {
656
+ void this.stopChild(run, this.graceMs, this.termMs).catch((err) => {
657
+ this.emitDiag("lifecycle", `child shutdown failed: ${String(err)}`);
658
+ });
659
+ }
660
+ stopChild(run, graceMs, termMs) {
661
+ return run.shutdown ??= this.shutdownChildLadder(run, graceMs, termMs);
662
+ }
663
+ async shutdownChildLadder({ child, closed }, graceMs, termMs) {
664
+ const waitForClose = (ms) => new Promise((resolve) => {
665
+ // Shutdown deadlines are independent of the injected protocol clock.
666
+ const timer = setTimeout(() => resolve(false), ms);
667
+ void closed.then(() => {
668
+ clearTimeout(timer);
669
+ resolve(true);
670
+ });
671
+ });
672
+ const exited = () => child.exitCode !== null || child.signalCode !== null;
673
+ child.stdin?.end();
674
+ if (await waitForClose(graceMs))
675
+ return;
676
+ if (!exited() && child.pid !== undefined) {
677
+ this.emitDiag("lifecycle", `shutdown escalation: sending SIGTERM to pid=${child.pid}`);
678
+ child.kill("SIGTERM");
679
+ if (await waitForClose(termMs))
680
+ return;
681
+ if (!exited()) {
682
+ this.emitDiag("lifecycle", `shutdown escalation: sending SIGKILL to pid=${child.pid}`);
683
+ child.kill("SIGKILL");
684
+ }
685
+ }
686
+ if (!await waitForClose(2000))
687
+ throw new Error(`Child pid=${child.pid} did not close after shutdown`);
688
+ }
689
+ settlePending(entry, end) {
690
+ if (entry.settled)
691
+ return;
692
+ entry.settled = true;
693
+ this.pending.delete(entry.key);
694
+ if (entry.progressTokenKey !== undefined) {
695
+ this.progressMap.delete(entry.progressTokenKey);
696
+ }
697
+ if (entry.onAbort) {
698
+ entry.signal.removeEventListener("abort", entry.onAbort);
699
+ }
700
+ this.recordSettledId(entry.key);
701
+ entry.notifications.close();
702
+ entry.resolve(end);
703
+ }
704
+ settleAllPending(failure) {
705
+ for (const entry of [...this.pending.values()]) {
706
+ this.settlePending(entry, {
707
+ kind: "failure",
708
+ failure,
709
+ delivery: this.deliveryForWriteState(entry.writeState),
710
+ });
711
+ }
712
+ }
713
+ deliveryForWriteState(st) {
714
+ if (st === "queued")
715
+ return "not-sent";
716
+ if (st === "writing")
717
+ return "maybe-delivered";
718
+ return "delivered-no-response";
719
+ }
720
+ recordSettledId(key) {
721
+ if (this.settledIdSet.has(key))
722
+ return;
723
+ this.settledIdSet.add(key);
724
+ this.settledIds.push(key);
725
+ if (this.settledIds.length > 1000) {
726
+ const oldest = this.settledIds.shift();
727
+ this.settledIdSet.delete(oldest);
728
+ }
729
+ }
730
+ pruneRestartWindow(now) {
731
+ const cutoff = now - this.restartWindowMs;
732
+ while (this.restartTimestamps.length > 0 && this.restartTimestamps[0] < cutoff) {
733
+ this.restartTimestamps.shift();
734
+ }
735
+ }
736
+ emitDiag(kind, message) {
737
+ this.diagChannel.emit({
738
+ kind,
739
+ message,
740
+ atMs: this.clock.now(),
741
+ });
742
+ }
743
+ }
744
+ //# sourceMappingURL=transport.js.map