@nexum-hub/agent 0.0.0-stage → 0.0.1

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 (343) hide show
  1. package/README.md +129 -2
  2. package/contracts/v2/common.schema.json +262 -0
  3. package/contracts/v2/fixtures/inputs.json +244 -0
  4. package/contracts/v2/fixtures/wire.json +6493 -0
  5. package/contracts/v2/model/agent.close.input.schema.json +14 -0
  6. package/contracts/v2/model/agent.close.output.schema.json +101 -0
  7. package/contracts/v2/model/agent.list.input.schema.json +57 -0
  8. package/contracts/v2/model/agent.list.output.schema.json +220 -0
  9. package/contracts/v2/model/agent.open.input.schema.json +35 -0
  10. package/contracts/v2/model/agent.open.output.schema.json +41 -0
  11. package/contracts/v2/model/agent.run.cancel.input.schema.json +18 -0
  12. package/contracts/v2/model/agent.run.cancel.output.schema.json +100 -0
  13. package/contracts/v2/model/agent.run.get.input.schema.json +41 -0
  14. package/contracts/v2/model/agent.run.get.output.schema.json +100 -0
  15. package/contracts/v2/model/agent.run.input.input.schema.json +30 -0
  16. package/contracts/v2/model/agent.run.input.output.schema.json +100 -0
  17. package/contracts/v2/model/agent.run.list.input.schema.json +47 -0
  18. package/contracts/v2/model/agent.run.list.output.schema.json +41 -0
  19. package/contracts/v2/model/agent.run.start.input.schema.json +73 -0
  20. package/contracts/v2/model/agent.run.start.output.schema.json +100 -0
  21. package/contracts/v2/wire/bodies.schema.json +383 -0
  22. package/contracts/v2/wire/envelope.schema.json +2280 -0
  23. package/contracts/v2/wire/events.schema.json +242 -0
  24. package/contracts/v2/wire/maintenance.schema.json +308 -0
  25. package/contracts/v2/wire/operations.schema.json +1791 -0
  26. package/contracts/v2/wire/stream.schema.json +74 -0
  27. package/contracts/v2/wire/types.schema.json +2616 -0
  28. package/dist/adapters/mcp-http.d.ts +22 -0
  29. package/dist/adapters/mcp-http.js +472 -0
  30. package/dist/adapters/mcp-http.js.map +1 -0
  31. package/dist/adapters/mcp-oauth.d.ts +29 -0
  32. package/dist/adapters/mcp-oauth.js +653 -0
  33. package/dist/adapters/mcp-oauth.js.map +1 -0
  34. package/dist/adapters/mcp-wire.d.ts +21 -0
  35. package/dist/adapters/mcp-wire.js +307 -0
  36. package/dist/adapters/mcp-wire.js.map +1 -0
  37. package/dist/adapters/mcp.d.ts +56 -0
  38. package/dist/adapters/mcp.js +1989 -0
  39. package/dist/adapters/mcp.js.map +1 -0
  40. package/dist/adapters/openapi-http.d.ts +29 -0
  41. package/dist/adapters/openapi-http.js +504 -0
  42. package/dist/adapters/openapi-http.js.map +1 -0
  43. package/dist/adapters/openapi-request.d.ts +26 -0
  44. package/dist/adapters/openapi-request.js +597 -0
  45. package/dist/adapters/openapi-request.js.map +1 -0
  46. package/dist/adapters/openapi-schema.d.ts +22 -0
  47. package/dist/adapters/openapi-schema.js +471 -0
  48. package/dist/adapters/openapi-schema.js.map +1 -0
  49. package/dist/adapters/openapi-typegen.d.ts +11 -0
  50. package/dist/adapters/openapi-typegen.js +185 -0
  51. package/dist/adapters/openapi-typegen.js.map +1 -0
  52. package/dist/adapters/openapi-types.d.ts +99 -0
  53. package/dist/adapters/openapi-types.js +2 -0
  54. package/dist/adapters/openapi-types.js.map +1 -0
  55. package/dist/adapters/openapi.d.ts +7 -0
  56. package/dist/adapters/openapi.js +768 -0
  57. package/dist/adapters/openapi.js.map +1 -0
  58. package/dist/application/activation.d.ts +28 -0
  59. package/dist/application/activation.js +289 -0
  60. package/dist/application/activation.js.map +1 -0
  61. package/dist/application/attachments.d.ts +24 -0
  62. package/dist/application/attachments.js +87 -0
  63. package/dist/application/attachments.js.map +1 -0
  64. package/dist/application/authority.d.ts +32 -0
  65. package/dist/application/authority.js +213 -0
  66. package/dist/application/authority.js.map +1 -0
  67. package/dist/application/catalog.d.ts +11 -0
  68. package/dist/application/catalog.js +177 -0
  69. package/dist/application/catalog.js.map +1 -0
  70. package/dist/application/config.d.ts +24 -0
  71. package/dist/application/config.js +140 -0
  72. package/dist/application/config.js.map +1 -0
  73. package/dist/application/connection.d.ts +35 -0
  74. package/dist/application/connection.js +465 -0
  75. package/dist/application/connection.js.map +1 -0
  76. package/dist/application/data-plane.d.ts +35 -0
  77. package/dist/application/data-plane.js +437 -0
  78. package/dist/application/data-plane.js.map +1 -0
  79. package/dist/application/diagnostics.d.ts +4 -0
  80. package/dist/application/diagnostics.js +65 -0
  81. package/dist/application/diagnostics.js.map +1 -0
  82. package/dist/application/dispatcher.d.ts +4 -0
  83. package/dist/application/dispatcher.js +16 -0
  84. package/dist/application/dispatcher.js.map +1 -0
  85. package/dist/application/main.d.ts +12 -0
  86. package/dist/application/main.js +167 -0
  87. package/dist/application/main.js.map +1 -0
  88. package/dist/application/maintenance.d.ts +27 -0
  89. package/dist/application/maintenance.js +244 -0
  90. package/dist/application/maintenance.js.map +1 -0
  91. package/dist/application/packages.d.ts +25 -0
  92. package/dist/application/packages.js +208 -0
  93. package/dist/application/packages.js.map +1 -0
  94. package/dist/application/processes.d.ts +49 -0
  95. package/dist/application/processes.js +180 -0
  96. package/dist/application/processes.js.map +1 -0
  97. package/dist/application/run-view.d.ts +17 -0
  98. package/dist/application/run-view.js +286 -0
  99. package/dist/application/run-view.js.map +1 -0
  100. package/dist/application/runtime.d.ts +78 -0
  101. package/dist/application/runtime.js +1747 -0
  102. package/dist/application/runtime.js.map +1 -0
  103. package/dist/application/tasks.d.ts +38 -0
  104. package/dist/application/tasks.js +23 -0
  105. package/dist/application/tasks.js.map +1 -0
  106. package/dist/application/user-state.d.ts +20 -0
  107. package/dist/application/user-state.js +52 -0
  108. package/dist/application/user-state.js.map +1 -0
  109. package/dist/application/work-git.d.ts +14 -0
  110. package/dist/application/work-git.js +67 -0
  111. package/dist/application/work-git.js.map +1 -0
  112. package/dist/cli.d.ts +2 -0
  113. package/dist/cli.js +40 -0
  114. package/dist/cli.js.map +1 -0
  115. package/dist/contracts/caller.d.ts +51 -0
  116. package/dist/contracts/caller.js +95 -0
  117. package/dist/contracts/caller.js.map +1 -0
  118. package/dist/contracts/error-data.d.ts +6 -0
  119. package/dist/contracts/error-data.js +51 -0
  120. package/dist/contracts/error-data.js.map +1 -0
  121. package/dist/contracts/errors.d.ts +10 -0
  122. package/dist/contracts/errors.js +28 -0
  123. package/dist/contracts/errors.js.map +1 -0
  124. package/dist/contracts/json.d.ts +9 -0
  125. package/dist/contracts/json.js +104 -0
  126. package/dist/contracts/json.js.map +1 -0
  127. package/dist/contracts/types.d.ts +122 -0
  128. package/dist/contracts/types.js +19 -0
  129. package/dist/contracts/types.js.map +1 -0
  130. package/dist/contracts/validation.d.ts +4 -0
  131. package/dist/contracts/validation.js +157 -0
  132. package/dist/contracts/validation.js.map +1 -0
  133. package/dist/contracts/wire-validation.d.ts +9 -0
  134. package/dist/contracts/wire-validation.js +399 -0
  135. package/dist/contracts/wire-validation.js.map +1 -0
  136. package/dist/contracts/wire.d.ts +1083 -0
  137. package/dist/contracts/wire.js +62 -0
  138. package/dist/contracts/wire.js.map +1 -0
  139. package/dist/extension-api.d.ts +12 -0
  140. package/dist/extension-api.js +2 -0
  141. package/dist/extension-api.js.map +1 -0
  142. package/dist/extensions/api.d.ts +72 -0
  143. package/dist/extensions/api.js +2 -0
  144. package/dist/extensions/api.js.map +1 -0
  145. package/dist/extensions/host-requests.d.ts +23 -0
  146. package/dist/extensions/host-requests.js +60 -0
  147. package/dist/extensions/host-requests.js.map +1 -0
  148. package/dist/extensions/materials.d.ts +37 -0
  149. package/dist/extensions/materials.js +691 -0
  150. package/dist/extensions/materials.js.map +1 -0
  151. package/dist/extensions/package-loader.d.ts +28 -0
  152. package/dist/extensions/package-loader.js +177 -0
  153. package/dist/extensions/package-loader.js.map +1 -0
  154. package/dist/extensions/packages.d.ts +73 -0
  155. package/dist/extensions/packages.js +441 -0
  156. package/dist/extensions/packages.js.map +1 -0
  157. package/dist/extensions/registry.d.ts +92 -0
  158. package/dist/extensions/registry.js +1540 -0
  159. package/dist/extensions/registry.js.map +1 -0
  160. package/dist/extensions/resources.d.ts +105 -0
  161. package/dist/extensions/resources.js +595 -0
  162. package/dist/extensions/resources.js.map +1 -0
  163. package/dist/extensions/state.d.ts +25 -0
  164. package/dist/extensions/state.js +10 -0
  165. package/dist/extensions/state.js.map +1 -0
  166. package/dist/extensions/transfer.d.ts +81 -0
  167. package/dist/extensions/transfer.js +16 -0
  168. package/dist/extensions/transfer.js.map +1 -0
  169. package/dist/index.d.ts +7 -0
  170. package/dist/index.js +25 -0
  171. package/dist/index.js.map +1 -0
  172. package/dist/maintenance/configuration.d.ts +79 -0
  173. package/dist/maintenance/configuration.js +1503 -0
  174. package/dist/maintenance/configuration.js.map +1 -0
  175. package/dist/maintenance/credentials.d.ts +23 -0
  176. package/dist/maintenance/credentials.js +177 -0
  177. package/dist/maintenance/credentials.js.map +1 -0
  178. package/dist/maintenance/files.d.ts +2 -0
  179. package/dist/maintenance/files.js +40 -0
  180. package/dist/maintenance/files.js.map +1 -0
  181. package/dist/maintenance/npm.d.ts +71 -0
  182. package/dist/maintenance/npm.js +1013 -0
  183. package/dist/maintenance/npm.js.map +1 -0
  184. package/dist/maintenance/oauth.d.ts +45 -0
  185. package/dist/maintenance/oauth.js +686 -0
  186. package/dist/maintenance/oauth.js.map +1 -0
  187. package/dist/maintenance/requests.d.ts +347 -0
  188. package/dist/maintenance/requests.js +959 -0
  189. package/dist/maintenance/requests.js.map +1 -0
  190. package/dist/maintenance/work-git.d.ts +29 -0
  191. package/dist/maintenance/work-git.js +776 -0
  192. package/dist/maintenance/work-git.js.map +1 -0
  193. package/dist/process/backend.d.ts +54 -0
  194. package/dist/process/backend.js +39 -0
  195. package/dist/process/backend.js.map +1 -0
  196. package/dist/process/environment-windows.d.ts +15 -0
  197. package/dist/process/environment-windows.js +151 -0
  198. package/dist/process/environment-windows.js.map +1 -0
  199. package/dist/process/environment.d.ts +28 -0
  200. package/dist/process/environment.js +410 -0
  201. package/dist/process/environment.js.map +1 -0
  202. package/dist/process/launch.d.ts +31 -0
  203. package/dist/process/launch.js +281 -0
  204. package/dist/process/launch.js.map +1 -0
  205. package/dist/process/managed.d.ts +36 -0
  206. package/dist/process/managed.js +459 -0
  207. package/dist/process/managed.js.map +1 -0
  208. package/dist/process/output-log.d.ts +50 -0
  209. package/dist/process/output-log.js +552 -0
  210. package/dist/process/output-log.js.map +1 -0
  211. package/dist/process/pipes.d.ts +16 -0
  212. package/dist/process/pipes.js +588 -0
  213. package/dist/process/pipes.js.map +1 -0
  214. package/dist/process/pty.d.ts +22 -0
  215. package/dist/process/pty.js +512 -0
  216. package/dist/process/pty.js.map +1 -0
  217. package/dist/process/windows-conout-worker.d.ts +1 -0
  218. package/dist/process/windows-conout-worker.js +90 -0
  219. package/dist/process/windows-conout-worker.js.map +1 -0
  220. package/dist/process/windows-conout.d.ts +46 -0
  221. package/dist/process/windows-conout.js +140 -0
  222. package/dist/process/windows-conout.js.map +1 -0
  223. package/dist/process/windows-helper.d.ts +43 -0
  224. package/dist/process/windows-helper.js +255 -0
  225. package/dist/process/windows-helper.js.map +1 -0
  226. package/dist/process/windows-job.d.ts +39 -0
  227. package/dist/process/windows-job.js +224 -0
  228. package/dist/process/windows-job.js.map +1 -0
  229. package/dist/process/windows-pipes.d.ts +16 -0
  230. package/dist/process/windows-pipes.js +475 -0
  231. package/dist/process/windows-pipes.js.map +1 -0
  232. package/dist/results/artifacts.d.ts +118 -0
  233. package/dist/results/artifacts.js +873 -0
  234. package/dist/results/artifacts.js.map +1 -0
  235. package/dist/results/encoder.d.ts +57 -0
  236. package/dist/results/encoder.js +1179 -0
  237. package/dist/results/encoder.js.map +1 -0
  238. package/dist/results/mcp.d.ts +95 -0
  239. package/dist/results/mcp.js +656 -0
  240. package/dist/results/mcp.js.map +1 -0
  241. package/dist/results/media.d.ts +19 -0
  242. package/dist/results/media.js +301 -0
  243. package/dist/results/media.js.map +1 -0
  244. package/dist/results/normalize.d.ts +29 -0
  245. package/dist/results/normalize.js +464 -0
  246. package/dist/results/normalize.js.map +1 -0
  247. package/dist/runtime/control-scripts.d.ts +23 -0
  248. package/dist/runtime/control-scripts.js +242 -0
  249. package/dist/runtime/control-scripts.js.map +1 -0
  250. package/dist/runtime/engine.d.ts +177 -0
  251. package/dist/runtime/engine.js +1159 -0
  252. package/dist/runtime/engine.js.map +1 -0
  253. package/dist/runtime/globals.d.ts +1 -0
  254. package/dist/runtime/globals.js +31 -0
  255. package/dist/runtime/globals.js.map +1 -0
  256. package/dist/runtime/material-retention.d.ts +34 -0
  257. package/dist/runtime/material-retention.js +671 -0
  258. package/dist/runtime/material-retention.js.map +1 -0
  259. package/dist/runtime/modules.d.ts +50 -0
  260. package/dist/runtime/modules.js +320 -0
  261. package/dist/runtime/modules.js.map +1 -0
  262. package/dist/runtime/names.d.ts +2 -0
  263. package/dist/runtime/names.js +22 -0
  264. package/dist/runtime/names.js.map +1 -0
  265. package/dist/runtime/operations.d.ts +20 -0
  266. package/dist/runtime/operations.js +137 -0
  267. package/dist/runtime/operations.js.map +1 -0
  268. package/dist/runtime/paths.d.ts +3 -0
  269. package/dist/runtime/paths.js +38 -0
  270. package/dist/runtime/paths.js.map +1 -0
  271. package/dist/runtime/promises.d.ts +9 -0
  272. package/dist/runtime/promises.js +78 -0
  273. package/dist/runtime/promises.js.map +1 -0
  274. package/dist/runtime/retention.d.ts +88 -0
  275. package/dist/runtime/retention.js +735 -0
  276. package/dist/runtime/retention.js.map +1 -0
  277. package/dist/runtime/run-log.d.ts +30 -0
  278. package/dist/runtime/run-log.js +207 -0
  279. package/dist/runtime/run-log.js.map +1 -0
  280. package/dist/runtime/scripts.d.ts +84 -0
  281. package/dist/runtime/scripts.js +387 -0
  282. package/dist/runtime/scripts.js.map +1 -0
  283. package/dist/runtime/tasks.d.ts +54 -0
  284. package/dist/runtime/tasks.js +290 -0
  285. package/dist/runtime/tasks.js.map +1 -0
  286. package/dist/sdk/maintenance.d.ts +3 -0
  287. package/dist/sdk/maintenance.js +80 -0
  288. package/dist/sdk/maintenance.js.map +1 -0
  289. package/dist/sdk/output-extension.d.ts +3 -0
  290. package/dist/sdk/output-extension.js +44 -0
  291. package/dist/sdk/output-extension.js.map +1 -0
  292. package/dist/sdk/output.d.ts +52 -0
  293. package/dist/sdk/output.js +350 -0
  294. package/dist/sdk/output.js.map +1 -0
  295. package/dist/sdk/runtime.d.ts +3 -0
  296. package/dist/sdk/runtime.js +26 -0
  297. package/dist/sdk/runtime.js.map +1 -0
  298. package/dist/sdk/sh.d.ts +3 -0
  299. package/dist/sdk/sh.js +384 -0
  300. package/dist/sdk/sh.js.map +1 -0
  301. package/dist/sdk/state.d.ts +2 -0
  302. package/dist/sdk/state.js +69 -0
  303. package/dist/sdk/state.js.map +1 -0
  304. package/dist/sdk/transfer.d.ts +3 -0
  305. package/dist/sdk/transfer.js +141 -0
  306. package/dist/sdk/transfer.js.map +1 -0
  307. package/dist/services/extensions.d.ts +19 -0
  308. package/dist/services/extensions.js +183 -0
  309. package/dist/services/extensions.js.map +1 -0
  310. package/dist/services/state.d.ts +37 -0
  311. package/dist/services/state.js +125 -0
  312. package/dist/services/state.js.map +1 -0
  313. package/dist/services/transfer.d.ts +86 -0
  314. package/dist/services/transfer.js +948 -0
  315. package/dist/services/transfer.js.map +1 -0
  316. package/dist/storage/schema.d.ts +8 -0
  317. package/dist/storage/schema.js +241 -0
  318. package/dist/storage/schema.js.map +1 -0
  319. package/dist/storage/sqlite.d.ts +241 -0
  320. package/dist/storage/sqlite.js +1855 -0
  321. package/dist/storage/sqlite.js.map +1 -0
  322. package/dist/storage/transfers.d.ts +90 -0
  323. package/dist/storage/transfers.js +2 -0
  324. package/dist/storage/transfers.js.map +1 -0
  325. package/dist/transfer/io.d.ts +74 -0
  326. package/dist/transfer/io.js +425 -0
  327. package/dist/transfer/io.js.map +1 -0
  328. package/dist/transfer/offers.d.ts +72 -0
  329. package/dist/transfer/offers.js +380 -0
  330. package/dist/transfer/offers.js.map +1 -0
  331. package/dist/transfer/stream-slots.d.ts +12 -0
  332. package/dist/transfer/stream-slots.js +28 -0
  333. package/dist/transfer/stream-slots.js.map +1 -0
  334. package/dist/work/catalog.d.ts +43 -0
  335. package/dist/work/catalog.js +198 -0
  336. package/dist/work/catalog.js.map +1 -0
  337. package/dist/work/discovery.d.ts +70 -0
  338. package/dist/work/discovery.js +465 -0
  339. package/dist/work/discovery.js.map +1 -0
  340. package/dist/work/service.d.ts +83 -0
  341. package/dist/work/service.js +703 -0
  342. package/dist/work/service.js.map +1 -0
  343. package/package.json +66 -4
@@ -0,0 +1,1989 @@
1
+ import { addAbortListener, EventEmitter, once } from "node:events";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { readFileSync } from "node:fs";
4
+ import { Client, ReadBuffer, serializeMessage, getSupportedElicitationModes, } from "@modelcontextprotocol/client";
5
+ import { AgentError, requireCondition } from "../contracts/errors.js";
6
+ import { canonicalJson, isPlainRecord } from "../contracts/json.js";
7
+ import { compileMethodSchema, } from "../contracts/validation.js";
8
+ import { normalizeLaunch, prepareLaunch } from "../process/launch.js";
9
+ import { projectMcpProtocolResult, copyMcpJSON, } from "../results/mcp.js";
10
+ import { ManagedHttpTransport } from "./mcp-http.js";
11
+ import { McpWire } from "./mcp-wire.js";
12
+ import { createSessionPortFromClient, withTasks, toolDeclarationFromMcpTool, resultFromTaskOutcome, } from "@modelcontextprotocol/ext-tasks/client";
13
+ import { taskId as taskIdentity, } from "@modelcontextprotocol/ext-tasks/core";
14
+ import { CreateTaskResultV1Schema } from "@modelcontextprotocol/ext-tasks/core/v1";
15
+ import { CreateTaskResultV2Schema } from "@modelcontextprotocol/ext-tasks/core/v2";
16
+ // Trusted installed program identity; this does not start or probe a connection.
17
+ const installedAgent = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
18
+ requireCondition(typeof installedAgent.name === "string" &&
19
+ typeof installedAgent.version === "string", "invalid_mcp_host", "The MCP client requires its actual installed Agent identity.");
20
+ const clientIdentity = Object.freeze({
21
+ name: installedAgent.name,
22
+ version: installedAgent.version,
23
+ });
24
+ const MiB = 1024 * 1024;
25
+ const maximumTimeout = 2_147_483_647;
26
+ const allPermissions = Object.freeze(["mcp.use"]);
27
+ const pageSchema = {
28
+ type: "object",
29
+ additionalProperties: false,
30
+ properties: { cursor: { type: "string", minLength: 1, maxLength: 4096 } },
31
+ };
32
+ const readSchema = {
33
+ type: "object",
34
+ required: ["uri"],
35
+ additionalProperties: false,
36
+ properties: { uri: { type: "string", minLength: 1, maxLength: 1024 } },
37
+ };
38
+ const getPromptSchema = {
39
+ type: "object",
40
+ required: ["name"],
41
+ additionalProperties: false,
42
+ properties: {
43
+ name: { type: "string", minLength: 1, maxLength: 1024 },
44
+ arguments: { type: "object", additionalProperties: { type: "string" } },
45
+ },
46
+ };
47
+ export function validateMcpConnectionConfig(value) {
48
+ const input = JSON.parse(canonicalJson(value));
49
+ requireCondition(isPlainRecord(input), "invalid_mcp_config", "An MCP connection needs a configuration object.");
50
+ requireCondition(typeof input.name === "string" &&
51
+ /^[A-Za-z_$][A-Za-z0-9_$-]{0,127}$/.test(input.name), "invalid_mcp_config", "An MCP connection needs a bounded unambiguous name.");
52
+ const fields = input.transport === "stdio"
53
+ ? ["name", "transport", "command", "args", "cwd", "env"]
54
+ : input.transport === "streamable-http"
55
+ ? ["name", "transport", "url", "headers"]
56
+ : [];
57
+ requireCondition(fields.length && Object.keys(input).every((key) => fields.includes(key)), "invalid_mcp_config", "Only the supported MCP transport configuration fields are accepted.");
58
+ if (input.transport === "stdio") {
59
+ // Reuse the same direct-argv/environment validation as the managed process SDK.
60
+ normalizeLaunch([
61
+ {
62
+ command: input.command,
63
+ ...(input.args === undefined ? {} : { args: input.args }),
64
+ ...(input.cwd === undefined ? {} : { cwd: input.cwd }),
65
+ ...(input.env === undefined ? {} : { env: input.env }),
66
+ },
67
+ ], "start");
68
+ if (input.env !== undefined)
69
+ requireCondition(isPlainRecord(input.env) &&
70
+ Object.values(input.env).every((value) => typeof value === "string"), "invalid_mcp_config", "MCP environment values must be strings.");
71
+ }
72
+ else {
73
+ requireCondition(typeof input.url === "string" && Buffer.byteLength(input.url) <= 1024, "invalid_mcp_config", "The MCP HTTP endpoint must be a bounded URL.");
74
+ let endpoint;
75
+ try {
76
+ endpoint = new URL(input.url);
77
+ }
78
+ catch {
79
+ throw new AgentError("invalid_mcp_config", "The MCP HTTP endpoint is not an absolute URL.");
80
+ }
81
+ requireCondition(["http:", "https:"].includes(endpoint.protocol) &&
82
+ !endpoint.username &&
83
+ !endpoint.password &&
84
+ !endpoint.hash, "invalid_mcp_config", "MCP HTTP requires an HTTP(S) endpoint without embedded credentials or fragments.");
85
+ if (input.headers !== undefined) {
86
+ requireCondition(isPlainRecord(input.headers) && Object.keys(input.headers).length <= 64, "invalid_mcp_config", "MCP headers require a bounded data object.");
87
+ const reserved = new Set([
88
+ "host",
89
+ "connection",
90
+ "transfer-encoding",
91
+ "content-length",
92
+ "content-type",
93
+ "accept",
94
+ "mcp-session-id",
95
+ "mcp-protocol-version",
96
+ "last-event-id",
97
+ ]);
98
+ for (const [name, value] of Object.entries(input.headers))
99
+ requireCondition(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name) &&
100
+ !reserved.has(name.toLowerCase()) &&
101
+ typeof value === "string" &&
102
+ !/[\0\r\n]/.test(value) &&
103
+ Buffer.byteLength(value) <= 16384, "invalid_mcp_config", "MCP headers contain an invalid or protocol-reserved field.");
104
+ }
105
+ }
106
+ return deepFreeze(input);
107
+ }
108
+ function optionsSnapshot(value) {
109
+ requireCondition(isPlainRecord(value), "invalid_mcp_options", "MCP adapter options require a trusted data object.");
110
+ const descriptors = Object.getOwnPropertyDescriptors(value);
111
+ requireCondition(Object.values(descriptors).every((descriptor) => "value" in descriptor), "invalid_mcp_options", "MCP adapter options cannot contain accessors.");
112
+ const { authProvider, authProviderFactory, ...data } = value;
113
+ requireCondition(authProviderFactory === undefined ||
114
+ (typeof authProviderFactory === "function" && authProvider === undefined), "invalid_mcp_options", "Use one trusted OAuth provider or its instance-bound factory.");
115
+ if (authProvider !== undefined)
116
+ requireCondition(typeof authProvider === "object" &&
117
+ authProvider !== null &&
118
+ [
119
+ "clientInformation",
120
+ "tokens",
121
+ "saveTokens",
122
+ "redirectToAuthorization",
123
+ "saveCodeVerifier",
124
+ "codeVerifier",
125
+ ].every((key) => typeof authProvider[key] ===
126
+ "function"), "invalid_mcp_options", "MCP OAuth requires the official trusted provider service.");
127
+ const fixed = JSON.parse(canonicalJson(data));
128
+ requireCondition(isPlainRecord(fixed) &&
129
+ Object.keys(fixed).every((key) => [
130
+ "revision",
131
+ "connectTimeoutMs",
132
+ "requestTimeoutMs",
133
+ "maxMessageBytes",
134
+ "maxCatalogBytes",
135
+ "maxCatalogItems",
136
+ "hostCapabilities",
137
+ ].includes(key)), "invalid_mcp_options", "The MCP adapter options contain an unknown field.");
138
+ if (fixed.revision !== undefined)
139
+ requireCondition(typeof fixed.revision === "string" &&
140
+ fixed.revision.length > 0 &&
141
+ Buffer.byteLength(fixed.revision) <= 1024, "invalid_mcp_options", "The source revision must be bounded text.");
142
+ const result = {
143
+ connectTimeoutMs: 10000,
144
+ requestTimeoutMs: maximumTimeout,
145
+ maxMessageBytes: 128 * MiB,
146
+ maxCatalogBytes: 4 * MiB,
147
+ maxCatalogItems: 1000,
148
+ hostCapabilities: {},
149
+ ...fixed,
150
+ };
151
+ for (const key of [
152
+ "connectTimeoutMs",
153
+ "requestTimeoutMs",
154
+ "maxMessageBytes",
155
+ "maxCatalogBytes",
156
+ "maxCatalogItems",
157
+ ])
158
+ requireCondition(Number.isSafeInteger(result[key]) &&
159
+ result[key] >= 1 &&
160
+ result[key] <=
161
+ (key.endsWith("TimeoutMs")
162
+ ? maximumTimeout
163
+ : key === "maxCatalogItems"
164
+ ? 10000
165
+ : 128 * MiB), "invalid_mcp_options", "An MCP adapter limit is outside its supported budget.");
166
+ requireCondition(isPlainRecord(result.hostCapabilities) &&
167
+ Object.keys(result.hostCapabilities).every((key) => ["sampling", "elicitation", "roots"].includes(key)), "invalid_mcp_options", "Only actual Host bridge capabilities may be advertised.");
168
+ // Freeze JSON options, never freeze or enumerate a trusted provider's private
169
+ // mutable token/session service.
170
+ return Object.freeze({
171
+ ...deepFreeze(result),
172
+ ...(authProvider
173
+ ? { authProvider: authProvider }
174
+ : {}),
175
+ ...(authProviderFactory
176
+ ? {
177
+ authProviderFactory: authProviderFactory,
178
+ }
179
+ : {}),
180
+ });
181
+ }
182
+ function deepFreeze(value) {
183
+ if (value && typeof value === "object") {
184
+ for (const child of Object.values(value))
185
+ deepFreeze(child);
186
+ Object.freeze(value);
187
+ }
188
+ return value;
189
+ }
190
+ function publicMetadata(value) {
191
+ if (!isPlainRecord(value))
192
+ return value;
193
+ return Object.fromEntries(Object.entries(value).filter(([key]) => key !== "_meta"));
194
+ }
195
+ function publicError(cause, stage) {
196
+ // Remote protocol/transport messages and Error causes can contain arguments,
197
+ // authorization headers or server stderr. Never put them in ordinary logs/results.
198
+ const code = cause && typeof cause === "object"
199
+ ? Object.getOwnPropertyDescriptor(cause, "code")?.value
200
+ : undefined;
201
+ return new AgentError("mcp_request_failed", `The MCP ${stage} did not complete.`, typeof code === "number" && Number.isFinite(code)
202
+ ? { protocolCode: code }
203
+ : undefined);
204
+ }
205
+ function dialect(schema) {
206
+ const declared = isPlainRecord(schema) ? schema.$schema : undefined;
207
+ return declared === "http://json-schema.org/draft-07/schema#" ||
208
+ declared === "http://json-schema.org/draft-07/schema"
209
+ ? "draft7"
210
+ : "2020-12";
211
+ }
212
+ /** Official MCP framing over the same cold, physically managed process backend as sh. */
213
+ class ManagedStdioTransport {
214
+ config;
215
+ host;
216
+ maximum;
217
+ report;
218
+ committed;
219
+ get pid() {
220
+ return this.#backend?.facts().pid ?? undefined;
221
+ }
222
+ get stderr() {
223
+ return null;
224
+ }
225
+ closed;
226
+ onclose;
227
+ onerror;
228
+ onmessage;
229
+ #done = Promise.withResolvers();
230
+ #signal = new AbortController();
231
+ #backend;
232
+ #backendChanged;
233
+ #reportFailure;
234
+ #start;
235
+ #close;
236
+ #stopping = false;
237
+ #complete = false;
238
+ #buffer;
239
+ #queue = Promise.resolve();
240
+ #pendingBytes = 0;
241
+ #pendingMessages = 0;
242
+ #calls = new AsyncLocalStorage();
243
+ #requestScopes = new Map();
244
+ constructor(config, host, maximum, report, committed) {
245
+ this.config = config;
246
+ this.host = host;
247
+ this.maximum = maximum;
248
+ this.report = report;
249
+ this.committed = committed;
250
+ this.closed = this.#done.promise;
251
+ this.#buffer = new ReadBuffer({ maxBufferSize: maximum });
252
+ }
253
+ start() {
254
+ requireCondition(!this.#start && !this.#stopping, "mcp_connection_closed", "The MCP transport cannot be started again.");
255
+ this.#start = this.#startProcess();
256
+ return this.#start;
257
+ }
258
+ async #startProcess() {
259
+ try {
260
+ const filename = process.platform === "win32" ? "windows-pipes" : "pipes";
261
+ const exported = process.platform === "win32"
262
+ ? "WindowsProcessBackend"
263
+ : "PipeProcessBackend";
264
+ const module = await import(new URL(`../process/${filename}.js`, import.meta.url).href);
265
+ this.#signal.signal.throwIfAborted();
266
+ const options = {
267
+ onOutput: async (stream, bytes) => {
268
+ if (stream !== "stdout")
269
+ return; // Consume stderr with backpressure; do not persist protocol secrets.
270
+ if (this.#stopping)
271
+ return;
272
+ try {
273
+ this.#buffer.append(bytes);
274
+ for (;;) {
275
+ const message = this.#buffer.readMessage();
276
+ if (!message)
277
+ break;
278
+ this.onmessage?.(message);
279
+ }
280
+ }
281
+ catch (cause) {
282
+ this.onerror?.(publicError(cause, "message decoding"));
283
+ queueMicrotask(() => {
284
+ void this.dispose().catch(() => { });
285
+ });
286
+ }
287
+ },
288
+ };
289
+ this.#backend = new module[exported](options);
290
+ this.#backendChanged = () => {
291
+ try {
292
+ this.report({ ...this.#backend.facts() });
293
+ }
294
+ catch (cause) {
295
+ // Reporting must not unwind a native process event or interrupt its
296
+ // stop reservation before a signal reaches the real process tree.
297
+ this.#reportFailure ??= cause;
298
+ queueMicrotask(() => {
299
+ void this.dispose(cause).catch(() => { });
300
+ });
301
+ }
302
+ };
303
+ this.#backend.on("change", this.#backendChanged);
304
+ void this.#backend.closed.then(() => this.#finish());
305
+ const input = normalizeLaunch([
306
+ {
307
+ command: this.config.command,
308
+ args: this.config.args ?? [],
309
+ ...(this.config.cwd ? { cwd: this.config.cwd } : {}),
310
+ env: this.config.env ?? {},
311
+ },
312
+ ], "start");
313
+ const paths = this.host.context.paths;
314
+ requireCondition(paths && typeof paths.work === "string", "invalid_mcp_host", "The MCP instance needs its Agent work directory.");
315
+ const prepared = await prepareLaunch(input, paths.work, this.#signal.signal, (value, access) => this.host.authorize({ type: "path", value, access }));
316
+ this.#signal.signal.throwIfAborted();
317
+ await this.#backend.start(prepared.launch);
318
+ }
319
+ catch (cause) {
320
+ if (!this.#backend)
321
+ this.#finish();
322
+ throw cause;
323
+ }
324
+ }
325
+ async send(message) {
326
+ requireCondition(!this.#stopping && this.#backend, "mcp_connection_closed", "The MCP connection is closed.");
327
+ const serialized = Buffer.from(serializeMessage(message));
328
+ requireCondition(serialized.byteLength <= this.maximum &&
329
+ this.#pendingBytes + serialized.byteLength <= this.maximum &&
330
+ this.#pendingMessages < 256, "mcp_message_too_large", "MCP outbound messages exceed the connection budget.");
331
+ const request = "method" in message && "id" in message;
332
+ const cancellationId = "method" in message && message.method === "notifications/cancelled"
333
+ ? message.params?.requestId
334
+ : undefined;
335
+ const scope = (typeof cancellationId === "string" || typeof cancellationId === "number"
336
+ ? this.#requestScopes.get(cancellationId)
337
+ : undefined) ?? this.#calls.getStore();
338
+ requireCondition(!request || !scope || scope.active, "mcp_call_closed", "The MCP call no longer admits requests.");
339
+ if (request && scope)
340
+ this.#requestScopes.set(message.id, scope);
341
+ this.#pendingBytes += serialized.byteLength;
342
+ this.#pendingMessages++;
343
+ const task = this.#queue.then(async () => {
344
+ // A request not yet committed to the shared stream must not start after
345
+ // its caller stops. A partially written frame must finish before the
346
+ // cancellation frame, otherwise it would corrupt everybody's channel.
347
+ if (request && scope?.signal.aborted) {
348
+ scope.dropped.add(message.id);
349
+ scope.signal.throwIfAborted();
350
+ }
351
+ if ("method" in message &&
352
+ message.method === "notifications/cancelled" &&
353
+ scope) {
354
+ const id = message.params?.requestId;
355
+ if ((typeof id === "string" || typeof id === "number") &&
356
+ scope.dropped.has(id))
357
+ return;
358
+ }
359
+ if (request)
360
+ this.committed?.();
361
+ for (let offset = 0; offset < serialized.byteLength; offset += 65536)
362
+ await this.#backend.write(serialized.subarray(offset, offset + 65536), false, this.#signal.signal);
363
+ });
364
+ scope?.pending.add(task);
365
+ void task.then(() => scope?.pending.delete(task), () => scope?.pending.delete(task));
366
+ this.#queue = task.catch(() => { });
367
+ try {
368
+ await task;
369
+ }
370
+ finally {
371
+ this.#pendingBytes -= serialized.byteLength;
372
+ this.#pendingMessages--;
373
+ }
374
+ }
375
+ async run(signal, callback) {
376
+ signal.throwIfAborted();
377
+ const scope = {
378
+ signal,
379
+ pending: new Set(),
380
+ dropped: new Set(),
381
+ active: true,
382
+ };
383
+ try {
384
+ return await this.#calls.run(scope, callback);
385
+ }
386
+ finally {
387
+ scope.active = false;
388
+ while (scope.pending.size)
389
+ await Promise.allSettled([...scope.pending]);
390
+ for (const [id, owner] of this.#requestScopes)
391
+ if (owner === scope)
392
+ this.#requestScopes.delete(id);
393
+ }
394
+ }
395
+ close() {
396
+ return this.dispose();
397
+ }
398
+ dispose(_reason) {
399
+ if (this.#close)
400
+ return this.#close;
401
+ this.#stopping = true;
402
+ this.#signal.abort(new AgentError("mcp_connection_closed", "The MCP instance is closing."));
403
+ this.#close = (async () => {
404
+ // Initialization/preparation can be in flight; abort it and wait before
405
+ // confirming a cold backend. No late process can start after disposal.
406
+ // Stop a starting backend immediately as well: on Windows, merely
407
+ // waiting for helper readiness could otherwise permit a late spawn.
408
+ const backendStop = this.#backend?.dispose();
409
+ const [_, stopped] = await Promise.allSettled([this.#start, backendStop]);
410
+ if (stopped.status === "rejected")
411
+ throw stopped.reason;
412
+ if (this.#backend)
413
+ await this.#backend.closed;
414
+ else
415
+ this.#finish();
416
+ await this.#queue;
417
+ if (this.#reportFailure)
418
+ throw this.#reportFailure;
419
+ })();
420
+ void this.#close.catch(() => {
421
+ this.#close = undefined;
422
+ });
423
+ return this.#close;
424
+ }
425
+ #finish() {
426
+ if (this.#complete)
427
+ return;
428
+ this.#complete = true;
429
+ if (this.#backend && this.#backendChanged)
430
+ this.#backend.off("change", this.#backendChanged);
431
+ this.#buffer.clear();
432
+ this.#calls.disable();
433
+ this.#done.resolve();
434
+ this.onclose?.();
435
+ }
436
+ }
437
+ /** Tracks the official execution, not a second task runner. Cancel ACK is not terminal evidence. */
438
+ class ManagedMcpExecution {
439
+ session;
440
+ call;
441
+ connection;
442
+ begin;
443
+ drain;
444
+ creation;
445
+ cleanup;
446
+ closed;
447
+ #done = Promise.withResolvers();
448
+ #ref;
449
+ #execution;
450
+ #running;
451
+ #creation;
452
+ #disposal;
453
+ #terminal = false;
454
+ #stopping = false;
455
+ #reportFailure;
456
+ #last;
457
+ #state = "preparing";
458
+ #cancelAcknowledged = false;
459
+ #cleanupActive = false;
460
+ #finishRequested = false;
461
+ #finished = false;
462
+ #confirmedOutcome;
463
+ constructor(session, call, connection, begin, drain, creation, cleanup) {
464
+ this.session = session;
465
+ this.call = call;
466
+ this.connection = connection;
467
+ this.begin = begin;
468
+ this.drain = drain;
469
+ this.creation = creation;
470
+ this.cleanup = cleanup;
471
+ this.closed = this.#done.promise;
472
+ }
473
+ attach(ref) {
474
+ this.#ref = ref;
475
+ this.#report();
476
+ }
477
+ #finish() {
478
+ this.#finishRequested = true;
479
+ if (!this.#cleanupActive && !this.#finished) {
480
+ this.#finished = true;
481
+ this.#done.resolve();
482
+ }
483
+ }
484
+ #report(task) {
485
+ if (this.#finished)
486
+ return;
487
+ if (task &&
488
+ this.#terminal &&
489
+ !["completed", "failed", "cancelled"].includes(task.status))
490
+ return;
491
+ if (task) {
492
+ this.#last = task;
493
+ this.#state = task.status;
494
+ }
495
+ try {
496
+ this.#ref?.report({
497
+ connection: this.connection,
498
+ state: task?.status ?? (this.#stopping ? "stopping" : this.#state),
499
+ remoteTaskId: task?.taskId ?? this.creation.taskId ?? null,
500
+ remoteTerminal: this.#terminal,
501
+ cancelAcknowledged: this.#cancelAcknowledged,
502
+ creationMayHaveStarted: this.creation.maybeStarted,
503
+ creationResponsePending: this.creation.awaitingResponse,
504
+ });
505
+ }
506
+ catch (cause) {
507
+ this.#reportFailure ??= cause;
508
+ }
509
+ }
510
+ execute() {
511
+ requireCondition(!this.#running && !this.#stopping, "mcp_task_closed", "The task controller cannot start again.");
512
+ if (this.#reportFailure) {
513
+ this.#finish();
514
+ throw this.#reportFailure;
515
+ }
516
+ this.#running = (async () => {
517
+ try {
518
+ this.#creation = this.begin();
519
+ this.#execution = await this.#creation;
520
+ const settlement = await this.#execution.settle({
521
+ close: false,
522
+ onEvent: (event) => {
523
+ if (event.type === "task") {
524
+ if (this.#terminal &&
525
+ !["completed", "failed", "cancelled"].includes(event.task.status))
526
+ return;
527
+ this.#terminal ||= ["completed", "failed", "cancelled"].includes(event.task.status);
528
+ this.#report(event.task);
529
+ if (!this.call.signal.aborted)
530
+ this.call.progress({
531
+ connection: this.connection,
532
+ remoteTaskId: event.task.taskId,
533
+ taskStatus: event.task.status,
534
+ });
535
+ }
536
+ },
537
+ });
538
+ if (this.#execution.kind === "immediate") {
539
+ this.#terminal = true;
540
+ this.#state = "completed";
541
+ this.#report();
542
+ }
543
+ if (settlement.lastTask) {
544
+ this.#terminal ||= ["completed", "failed", "cancelled"].includes(settlement.lastTask.status);
545
+ this.#report(settlement.lastTask);
546
+ }
547
+ if (this.#terminal) {
548
+ await this.#execution.detach();
549
+ await this.drain();
550
+ this.#finish();
551
+ }
552
+ if (this.#reportFailure)
553
+ throw this.#reportFailure;
554
+ return resultFromTaskOutcome(this.#confirmedOutcome ?? settlement.outcome);
555
+ }
556
+ catch (cause) {
557
+ if (!this.#execution) {
558
+ this.#state =
559
+ this.creation.taskId ||
560
+ (this.creation.maybeStarted &&
561
+ (this.creation.awaitingResponse || this.creation.malformedTask))
562
+ ? "creation_unknown"
563
+ : this.call.signal.aborted
564
+ ? "cancelled"
565
+ : "failed";
566
+ this.#report();
567
+ await this.drain();
568
+ if (this.#state !== "creation_unknown")
569
+ this.#finish();
570
+ }
571
+ else if (this.#terminal) {
572
+ await this.#execution.detach();
573
+ await this.drain();
574
+ this.#finish();
575
+ }
576
+ throw cause;
577
+ }
578
+ })();
579
+ return this.#running;
580
+ }
581
+ facts() {
582
+ return {
583
+ connection: this.connection,
584
+ state: this.#last?.status ?? this.#state,
585
+ remoteTaskId: this.#last?.taskId ??
586
+ (this.#execution?.kind === "task"
587
+ ? this.#execution.handle.taskId
588
+ : (this.creation.taskId ?? null)),
589
+ remoteTerminal: this.#terminal,
590
+ cancelAcknowledged: this.#cancelAcknowledged,
591
+ creationMayHaveStarted: this.creation.maybeStarted,
592
+ creationResponsePending: this.creation.awaitingResponse,
593
+ };
594
+ }
595
+ async snapshot(signal) {
596
+ if (this.#execution?.kind !== "task")
597
+ return this.facts();
598
+ const task = await this.session
599
+ .task(this.#execution.handle.taskId, { requestTimeoutMs: 5000 })
600
+ .snapshot(signal);
601
+ this.#terminal ||= ["completed", "failed", "cancelled"].includes(task.status);
602
+ this.#report(task);
603
+ return this.facts();
604
+ }
605
+ dispose() {
606
+ if (this.#disposal)
607
+ return this.#disposal;
608
+ this.#stopping = true;
609
+ this.creation.stopping = true;
610
+ this.#report();
611
+ this.#cleanupActive = true;
612
+ this.#disposal = this.cleanup(async () => {
613
+ if (!this.#running) {
614
+ this.#finish();
615
+ return;
616
+ }
617
+ await this.#creation?.catch(() => { });
618
+ if (!this.#execution && !this.creation.taskId) {
619
+ await this.#running.catch(() => { });
620
+ requireCondition(!(this.creation.maybeStarted &&
621
+ (this.creation.awaitingResponse || this.creation.malformedTask)), "mcp_task_creation_unconfirmed", "The committed task creation has no confirmed response or task identity.");
622
+ this.#finish();
623
+ return;
624
+ }
625
+ if (this.#terminal) {
626
+ if (!this.call.signal.aborted)
627
+ await this.#running.catch(() => { });
628
+ await this.#execution?.detach();
629
+ await this.drain();
630
+ this.#finish();
631
+ return;
632
+ }
633
+ if (this.#execution?.kind === "immediate") {
634
+ await this.#execution.detach();
635
+ await this.#running.catch(() => { });
636
+ this.#finish();
637
+ return;
638
+ }
639
+ const signal = AbortSignal.timeout(5000);
640
+ const taskId = this.#execution?.kind === "task"
641
+ ? this.#execution.handle.taskId
642
+ : this.creation.taskId;
643
+ const remote = this.session.task(taskId, { requestTimeoutMs: 5000 });
644
+ await remote.cancel(signal);
645
+ this.#cancelAcknowledged = true;
646
+ try {
647
+ if (!this.#finished)
648
+ this.#ref?.report({
649
+ connection: this.connection,
650
+ state: this.#terminal
651
+ ? (this.#last?.status ?? this.#state)
652
+ : "cancelling",
653
+ remoteTaskId: taskId,
654
+ cancelAcknowledged: true,
655
+ remoteTerminal: this.#terminal,
656
+ });
657
+ }
658
+ catch (cause) {
659
+ this.#reportFailure ??= cause;
660
+ }
661
+ // The official controller performs generation-specific observation. A
662
+ // cooperative V2 cancel is not falsely converted into remote termination.
663
+ const outcome = await remote.result({ signal });
664
+ this.#confirmedOutcome = outcome;
665
+ this.#terminal ||=
666
+ !!outcome.task &&
667
+ ["completed", "failed", "cancelled"].includes(outcome.task.status);
668
+ requireCondition(this.#terminal, "mcp_task_stop_unconfirmed", "The remote task has not reached a confirmed terminal state.");
669
+ this.#report(outcome.task);
670
+ await this.#execution?.detach();
671
+ await this.#running.catch(() => { });
672
+ await this.drain();
673
+ this.#finish();
674
+ if (this.#reportFailure)
675
+ throw this.#reportFailure;
676
+ })
677
+ .finally(async () => {
678
+ await this.drain();
679
+ this.#cleanupActive = false;
680
+ if (this.#finishRequested)
681
+ this.#finish();
682
+ })
683
+ .catch((cause) => {
684
+ throw cause instanceof AgentError
685
+ ? cause
686
+ : publicError(cause, "task cleanup");
687
+ });
688
+ void this.#disposal.catch(() => {
689
+ this.#disposal = undefined;
690
+ });
691
+ return this.#disposal;
692
+ }
693
+ }
694
+ /** A listener is a normal Core resource; its channel uses the registered connection. */
695
+ class ManagedMcpSubscription extends EventEmitter {
696
+ connection;
697
+ uri;
698
+ acquire;
699
+ release;
700
+ closed;
701
+ #done = Promise.withResolvers();
702
+ #channel;
703
+ #ref;
704
+ #events = [];
705
+ #sequence = 0;
706
+ #stopping = false;
707
+ #complete = false;
708
+ #ready = false;
709
+ #opening;
710
+ #disposal;
711
+ #reportFailure;
712
+ constructor(connection, uri, acquire, release) {
713
+ super();
714
+ this.connection = connection;
715
+ this.uri = uri;
716
+ this.acquire = acquire;
717
+ this.release = release;
718
+ this.setMaxListeners(0);
719
+ this.closed = this.#done.promise;
720
+ }
721
+ attach(ref) {
722
+ this.#ref = ref;
723
+ }
724
+ open() {
725
+ requireCondition(!this.#opening && !this.#stopping, "mcp_subscription_closed", "The subscription cannot be opened again.");
726
+ this.#opening = (async () => {
727
+ this.#channel = this.acquire(this);
728
+ try {
729
+ await this.#channel.ready;
730
+ requireCondition(!this.#stopping, "mcp_subscription_closed", "The subscription closed while opening.");
731
+ this.#ready = true;
732
+ this.#report();
733
+ }
734
+ catch (cause) {
735
+ await this.dispose().catch(() => { });
736
+ throw cause;
737
+ }
738
+ })();
739
+ return this.#opening;
740
+ }
741
+ updated() {
742
+ if (this.#stopping || this.#complete)
743
+ return;
744
+ this.#events.push({
745
+ cursor: ++this.#sequence,
746
+ uri: this.uri,
747
+ receivedAt: new Date().toISOString(),
748
+ });
749
+ if (this.#events.length > 256)
750
+ this.#events.shift();
751
+ this.#report();
752
+ this.emit("change");
753
+ }
754
+ #report() {
755
+ try {
756
+ this.#ref?.report({
757
+ connection: this.connection,
758
+ uri: this.uri,
759
+ state: this.#complete
760
+ ? "closed"
761
+ : this.#stopping
762
+ ? "stopping"
763
+ : this.#ready
764
+ ? "subscribed"
765
+ : "opening",
766
+ latestCursor: this.#sequence,
767
+ });
768
+ }
769
+ catch (cause) {
770
+ this.#reportFailure ??= cause;
771
+ queueMicrotask(() => {
772
+ void this.dispose().catch(() => { });
773
+ });
774
+ }
775
+ }
776
+ async read(cursor, waitMs, signal) {
777
+ signal.throwIfAborted();
778
+ if (!this.#complete && this.#sequence <= cursor && waitMs > 0) {
779
+ const waiting = AbortSignal.any([signal, AbortSignal.timeout(waitMs)]);
780
+ try {
781
+ await once(this, "change", { signal: waiting });
782
+ }
783
+ catch {
784
+ signal.throwIfAborted();
785
+ }
786
+ }
787
+ signal.throwIfAborted();
788
+ return {
789
+ uri: this.uri,
790
+ state: this.#complete
791
+ ? "closed"
792
+ : this.#stopping
793
+ ? "stopping"
794
+ : this.#ready
795
+ ? "subscribed"
796
+ : "opening",
797
+ events: this.#events.filter((item) => item.cursor > cursor),
798
+ cursor: this.#sequence,
799
+ historyLost: !!this.#events.length && cursor < this.#events[0].cursor - 1,
800
+ };
801
+ }
802
+ channelClosed() {
803
+ if (this.#complete)
804
+ return;
805
+ this.#complete = true;
806
+ this.#report();
807
+ this.#done.resolve();
808
+ this.emit("change");
809
+ }
810
+ dispose() {
811
+ if (this.#disposal)
812
+ return this.#disposal;
813
+ this.#stopping = true;
814
+ this.#disposal = (async () => {
815
+ try {
816
+ if (this.#channel)
817
+ await this.release(this, this.#channel);
818
+ }
819
+ finally {
820
+ this.channelClosed();
821
+ }
822
+ if (this.#reportFailure)
823
+ throw this.#reportFailure;
824
+ })();
825
+ void this.#disposal.catch(() => {
826
+ this.#disposal = undefined;
827
+ });
828
+ return this.#disposal;
829
+ }
830
+ }
831
+ class McpConnection {
832
+ host;
833
+ config;
834
+ limits;
835
+ get connection() {
836
+ return this.config.name;
837
+ }
838
+ closed;
839
+ client;
840
+ transport;
841
+ #control;
842
+ #wire;
843
+ #calls = new Set();
844
+ #tasks;
845
+ #taskPending = new Map();
846
+ #creations = new WeakMap();
847
+ #knownTasks = new Map();
848
+ #creationContext = new AsyncLocalStorage();
849
+ #cleanupContext = new AsyncLocalStorage();
850
+ #subscriptions = new Map();
851
+ #taskPort;
852
+ #http;
853
+ #stdio;
854
+ #ref;
855
+ #ready = false;
856
+ #stopping = false;
857
+ #stale = false;
858
+ #epoch = 0;
859
+ #detach = [];
860
+ #dispose;
861
+ #catalog = null;
862
+ #initialFailure;
863
+ #physicallyClosed = false;
864
+ constructor(host, config, limits) {
865
+ this.host = host;
866
+ this.config = config;
867
+ this.limits = limits;
868
+ this.client = new Client(clientIdentity, {
869
+ capabilities: limits.hostCapabilities,
870
+ // The official client otherwise selects its own default dialect for
871
+ // outputSchema. Reuse the exact declared-dialect validator used by Core.
872
+ jsonSchemaValidator: {
873
+ getValidator(schema) {
874
+ const validate = compileMethodSchema(schema, dialect(schema));
875
+ return (input) => {
876
+ try {
877
+ validate(input);
878
+ return {
879
+ valid: true,
880
+ data: input,
881
+ errorMessage: undefined,
882
+ };
883
+ }
884
+ catch {
885
+ return {
886
+ valid: false,
887
+ data: undefined,
888
+ errorMessage: "The structured result does not match its declared schema.",
889
+ };
890
+ }
891
+ };
892
+ },
893
+ },
894
+ versionNegotiation: { mode: "auto" },
895
+ });
896
+ if (config.transport === "stdio") {
897
+ const stdio = new ManagedStdioTransport(config, host, limits.maxMessageBytes, (facts) => {
898
+ if (facts.rootExited)
899
+ this.#ready = false;
900
+ this.#ref?.report({
901
+ connection: config.name,
902
+ transport: config.transport,
903
+ state: this.#ready
904
+ ? "ready"
905
+ : this.#stopping
906
+ ? "stopping"
907
+ : "connecting",
908
+ ...facts,
909
+ });
910
+ }, () => {
911
+ const creation = this.#creationContext.getStore();
912
+ if (creation) {
913
+ creation.call.signal.throwIfAborted();
914
+ creation.maybeStarted = true;
915
+ }
916
+ });
917
+ this.#stdio = stdio;
918
+ this.#control = stdio;
919
+ this.transport = stdio;
920
+ }
921
+ else {
922
+ this.#http = new ManagedHttpTransport({
923
+ url: config.url,
924
+ headers: config.headers,
925
+ authProvider: limits.authProviderFactory?.(host) ?? limits.authProvider,
926
+ maxMessageBytes: limits.maxMessageBytes,
927
+ authorize: (value) => {
928
+ host.authorize({ type: "url", value, access: "connect" });
929
+ const creation = this.#creationContext.getStore();
930
+ if (creation) {
931
+ creation.call.signal.throwIfAborted();
932
+ creation.maybeStarted = true;
933
+ }
934
+ },
935
+ });
936
+ this.#control = this.#http;
937
+ this.transport = this.#http.transport;
938
+ }
939
+ this.#wire = new McpWire(this.transport, {
940
+ maxMessageBytes: limits.maxMessageBytes,
941
+ });
942
+ this.transport = this.#wire.transport;
943
+ const send = this.transport.send.bind(this.transport);
944
+ this.transport.send = (message, options) => {
945
+ if ("method" in message && this.client.getProtocolEra() === "modern") {
946
+ const params = isPlainRecord(message.params) ? message.params : {};
947
+ const meta = isPlainRecord(params._meta) ? params._meta : {};
948
+ message = {
949
+ ...message,
950
+ params: {
951
+ ...params,
952
+ _meta: { ...meta, ...this.#metadata(this.#wire.current()) },
953
+ },
954
+ };
955
+ }
956
+ return send(message, options);
957
+ };
958
+ this.closed = this.#control.closed.then(async () => {
959
+ await Promise.allSettled([...this.#subscriptions.values()].map((channel) => channel.stop()));
960
+ this.#wire.finish();
961
+ this.#creationContext.disable();
962
+ this.#cleanupContext.disable();
963
+ });
964
+ if (limits.hostCapabilities.sampling)
965
+ this.client.setRequestHandler("sampling/createMessage", (request, context) => this.#hostRequest(request, context, "sampling"));
966
+ if (limits.hostCapabilities.elicitation)
967
+ this.client.setRequestHandler("elicitation/create", (request, context) => this.#hostRequest(request, context, "elicitation"));
968
+ if (limits.hostCapabilities.roots)
969
+ this.client.setRequestHandler("roots/list", (request, context) => this.#hostRequest(request, context, "roots"));
970
+ void this.closed.then(() => {
971
+ this.#physicallyClosed = true;
972
+ this.#ready = false;
973
+ for (const detach of this.#detach.splice(0))
974
+ detach();
975
+ });
976
+ this.client.setNotificationHandler("notifications/resources/updated", async (notification) => {
977
+ const channel = this.#subscriptions.get(notification.params.uri);
978
+ if (channel?.acceptingUpdates && !channel.closing)
979
+ for (const member of channel.members)
980
+ member.updated();
981
+ });
982
+ this.client.onerror = () => host.log({
983
+ level: "warn",
984
+ message: "An MCP transport reported a protocol or I/O failure.",
985
+ data: { connection: config.name },
986
+ });
987
+ this.client.onclose = () => {
988
+ this.#ready = false;
989
+ };
990
+ for (const method of [
991
+ "notifications/tools/list_changed",
992
+ "notifications/resources/list_changed",
993
+ "notifications/prompts/list_changed",
994
+ ])
995
+ this.client.setNotificationHandler(method, async () => {
996
+ this.#epoch++;
997
+ this.#stale = true;
998
+ this.#ref?.report({
999
+ connection: config.name,
1000
+ transport: config.transport,
1001
+ state: "catalog-stale",
1002
+ });
1003
+ });
1004
+ }
1005
+ #hostCapabilities(call) {
1006
+ const actual = call?.hostRequests?.capabilities;
1007
+ if (!actual ||
1008
+ this.#cleanupContext.getStore() ||
1009
+ call?.signal.aborted ||
1010
+ (call && this.#creations.get(call)?.stopping))
1011
+ return {};
1012
+ const intersect = (left, right) => {
1013
+ if (isPlainRecord(left) && isPlainRecord(right))
1014
+ return Object.fromEntries(Object.keys(left)
1015
+ .filter((key) => Object.hasOwn(right, key))
1016
+ .map((key) => [key, intersect(left[key], right[key])])
1017
+ .filter(([, value]) => value !== undefined));
1018
+ return left === right ? left : undefined;
1019
+ };
1020
+ const capabilities = {};
1021
+ for (const key of ["sampling", "elicitation", "roots"]) {
1022
+ if (Object.hasOwn(this.limits.hostCapabilities, key) &&
1023
+ Object.hasOwn(actual, key)) {
1024
+ if (key === "elicitation") {
1025
+ const left = getSupportedElicitationModes(this.limits.hostCapabilities
1026
+ .elicitation);
1027
+ const right = getSupportedElicitationModes(actual.elicitation);
1028
+ const modes = {};
1029
+ const l = this.limits.hostCapabilities.elicitation, r = actual.elicitation;
1030
+ if (left.supportsFormMode && right.supportsFormMode)
1031
+ modes.form = copyMcpJSON(intersect(l.form ?? {}, r.form ?? {}));
1032
+ if (left.supportsUrlMode && right.supportsUrlMode)
1033
+ modes.url = copyMcpJSON(intersect(l.url ?? {}, r.url ?? {}));
1034
+ if (Object.keys(modes).length)
1035
+ capabilities.elicitation = modes;
1036
+ }
1037
+ else {
1038
+ const value = intersect(this.limits.hostCapabilities[key], actual[key]);
1039
+ if (value !== undefined)
1040
+ capabilities[key] = copyMcpJSON(value);
1041
+ }
1042
+ }
1043
+ }
1044
+ return capabilities;
1045
+ }
1046
+ #metadata(call) {
1047
+ return this.client.getProtocolEra() === "modern"
1048
+ ? {
1049
+ "io.modelcontextprotocol/clientCapabilities": this.#hostCapabilities(call),
1050
+ }
1051
+ : {};
1052
+ }
1053
+ #hostRequest(request, context, kind) {
1054
+ // Legacy task-associated input has protocol evidence owned by ext-tasks.
1055
+ // Its public fallback performs correlation; an unrelated peer request is
1056
+ // rejected rather than borrowing whichever invocation happens to be active.
1057
+ if (!this.#wire.current() &&
1058
+ this.#tasks &&
1059
+ this.client.fallbackRequestHandler)
1060
+ return this.client.fallbackRequestHandler(request, context);
1061
+ return this.#hostInput(kind, (request.params ?? {}), context.mcpReq.signal);
1062
+ }
1063
+ async #hostInput(kind, params, inputSignal) {
1064
+ const call = this.#wire.current();
1065
+ requireCondition(call && this.#calls.has(call) && call.hostRequests, "mcp_input_unassociated", "The remote Host request has no verified active originating invocation.");
1066
+ this.assertCurrent();
1067
+ call.signal.throwIfAborted();
1068
+ requireCondition(!this.#creations.get(call)?.stopping, "mcp_task_stopping", "The originating task is stopping and no longer accepts Host requests.");
1069
+ inputSignal.throwIfAborted();
1070
+ call.hostRequests.assertCurrent();
1071
+ const capabilities = this.#hostCapabilities(call);
1072
+ requireCondition(Object.hasOwn(capabilities, kind), "mcp_host_capability_unavailable", "The original Host does not currently provide the requested capability.");
1073
+ if (kind === "elicitation") {
1074
+ const modes = getSupportedElicitationModes(capabilities.elicitation);
1075
+ requireCondition(params.mode === "url" ? modes.supportsUrlMode : modes.supportsFormMode, "mcp_host_capability_unavailable", "The original Host does not support this elicitation mode.");
1076
+ }
1077
+ if (kind === "sampling" &&
1078
+ (params.tools !== undefined || params.toolChoice !== undefined))
1079
+ requireCondition(isPlainRecord(capabilities.sampling) &&
1080
+ capabilities.sampling.tools !== undefined, "mcp_host_capability_unavailable", "The original Host does not support sampling tools.");
1081
+ call.authorize({
1082
+ type: "connection",
1083
+ value: this.config.name,
1084
+ access: `host.${kind}`,
1085
+ });
1086
+ const signal = AbortSignal.any([call.signal, inputSignal]);
1087
+ const input = copyMcpJSON(params, this.limits.maxMessageBytes);
1088
+ const result = kind === "roots"
1089
+ ? await call.hostRequests.roots({ signal })
1090
+ : await call.hostRequests[kind](input, { signal });
1091
+ signal.throwIfAborted();
1092
+ call.hostRequests.assertCurrent();
1093
+ this.assertCurrent();
1094
+ call.authorize({
1095
+ type: "connection",
1096
+ value: this.config.name,
1097
+ access: `host.${kind}`,
1098
+ });
1099
+ return copyMcpJSON(result, this.limits.maxMessageBytes);
1100
+ }
1101
+ #io(signal, action) {
1102
+ return this.#http
1103
+ ? this.#http.run(signal, action)
1104
+ : this.#stdio.run(signal, action);
1105
+ }
1106
+ #claimTask(creation, id) {
1107
+ const known = this.#knownTasks.get(id);
1108
+ if (known && known !== creation) {
1109
+ creation.malformedTask = true;
1110
+ throw new AgentError("mcp_task_identity_conflict", "The server returned a task identity already owned by another active invocation.");
1111
+ }
1112
+ creation.taskId = taskIdentity(id);
1113
+ this.#knownTasks.set(id, creation);
1114
+ }
1115
+ #setupTasks() {
1116
+ const capabilities = this.client.getServerCapabilities();
1117
+ if (!capabilities?.tasks &&
1118
+ !capabilities?.extensions?.["io.modelcontextprotocol/tasks"])
1119
+ return;
1120
+ const native = createSessionPortFromClient(this.client, this.#ref.id, {
1121
+ rawDispatch: (request, options) => {
1122
+ const value = copyMcpJSON(request, this.limits.maxMessageBytes);
1123
+ const params = isPlainRecord(value.params)
1124
+ ? value.params
1125
+ : {};
1126
+ const meta = isPlainRecord(params._meta)
1127
+ ? params._meta
1128
+ : {};
1129
+ const actual = this.#hostCapabilities(this.#wire.current());
1130
+ // Tasks support belongs to this real extension port; reverse Host
1131
+ // capabilities still come from the one originating invocation.
1132
+ value.params = {
1133
+ ...params,
1134
+ _meta: {
1135
+ ...meta,
1136
+ "io.modelcontextprotocol/clientCapabilities": {
1137
+ ...actual,
1138
+ extensions: { "io.modelcontextprotocol/tasks": {} },
1139
+ },
1140
+ },
1141
+ };
1142
+ return this.#wire.rawDispatch(value, options);
1143
+ },
1144
+ v2RequestFraming: {
1145
+ protocolVersion: this.client.getNegotiatedProtocolVersion(),
1146
+ clientInfo: clientIdentity,
1147
+ clientCapabilities: this.limits.hostCapabilities,
1148
+ },
1149
+ });
1150
+ this.#taskPort = native;
1151
+ const port = {
1152
+ endpointId: native.endpointId,
1153
+ taskCapabilities: native.taskCapabilities,
1154
+ get invalidated() {
1155
+ return native.invalidated;
1156
+ },
1157
+ onServerRequest: (handler) => native.onServerRequest(handler),
1158
+ onNotification: (handler) => native.onNotification(handler),
1159
+ onInvalidated: (handler) => native.onInvalidated(handler),
1160
+ dispatch: (request, options) => {
1161
+ this.host.signal.throwIfAborted();
1162
+ requireCondition(!this.#stopping && this.#ready, "mcp_connection_unavailable", "The original MCP Task connection is unavailable.");
1163
+ this.host.authorize({
1164
+ type: "connection",
1165
+ value: this.config.name,
1166
+ access: isPlainRecord(request) && typeof request.method === "string"
1167
+ ? request.method
1168
+ : "tasks.use",
1169
+ });
1170
+ const owner = this.#wire.current();
1171
+ const creation = isPlainRecord(request) && request.method === "tools/call" && owner
1172
+ ? this.#creations.get(owner)
1173
+ : undefined;
1174
+ const method = isPlainRecord(request) ? request.method : undefined;
1175
+ const params = isPlainRecord(request) && isPlainRecord(request.params)
1176
+ ? request.params
1177
+ : undefined;
1178
+ const cleanup = this.#cleanupContext.getStore() === true;
1179
+ if (owner && !owner.signal.aborted && !cleanup)
1180
+ owner.authorize({
1181
+ type: "connection",
1182
+ value: this.config.name,
1183
+ access: typeof method === "string" ? method : "tasks.use",
1184
+ });
1185
+ if (owner &&
1186
+ (owner.signal.aborted ||
1187
+ this.#creations.get(owner)?.stopping ||
1188
+ cleanup))
1189
+ requireCondition(["tasks/get", "tasks/result", "tasks/cancel"].includes(method) &&
1190
+ typeof params?.taskId === "string" &&
1191
+ this.#knownTasks.has(params.taskId), "mcp_task_stopping", "Only known-task observation and cancellation may continue during cleanup.");
1192
+ if (!owner)
1193
+ requireCondition(["tasks/get", "tasks/result", "tasks/cancel"].includes(method) &&
1194
+ typeof params?.taskId === "string" &&
1195
+ this.#knownTasks.has(params.taskId), "mcp_task_unassociated", "An unassociated task operation cannot use this connection.");
1196
+ if (creation)
1197
+ creation.call.signal.throwIfAborted();
1198
+ const perform = () => this.#io(creation && this.#stdio
1199
+ ? creation.call.signal
1200
+ : (options?.signal ?? this.host.signal), () => native.dispatch(request, options));
1201
+ if (creation)
1202
+ creation.awaitingResponse = true;
1203
+ const pending = creation
1204
+ ? this.#creationContext.run(creation, perform).then((response) => {
1205
+ creation.awaitingResponse = false;
1206
+ if (response.kind === "result") {
1207
+ if (native.taskCapabilities.generation === "v2") {
1208
+ const task = CreateTaskResultV2Schema.safeParse(response.result);
1209
+ if (task.success) {
1210
+ this.#claimTask(creation, task.data.taskId);
1211
+ }
1212
+ else if (isPlainRecord(response.result) &&
1213
+ response.result.resultType === "task")
1214
+ creation.malformedTask = true;
1215
+ }
1216
+ else {
1217
+ const task = CreateTaskResultV1Schema.safeParse(response.result);
1218
+ if (task.success) {
1219
+ this.#claimTask(creation, task.data.task.taskId);
1220
+ }
1221
+ else if (isPlainRecord(response.result) &&
1222
+ Object.hasOwn(response.result, "task"))
1223
+ creation.malformedTask = true;
1224
+ }
1225
+ }
1226
+ return response;
1227
+ })
1228
+ : perform();
1229
+ if (owner) {
1230
+ let group = this.#taskPending.get(owner);
1231
+ if (!group)
1232
+ this.#taskPending.set(owner, (group = new Set()));
1233
+ group.add(pending);
1234
+ void pending.then(() => group.delete(pending), () => group.delete(pending));
1235
+ }
1236
+ return pending;
1237
+ },
1238
+ };
1239
+ this.#tasks = withTasks(port, {
1240
+ signal: this.host.signal,
1241
+ maxInputRounds: 10,
1242
+ tools: {
1243
+ currentTool: (name) => {
1244
+ const tool = this.#catalog.tools.find((item) => item.name === name);
1245
+ return tool ? toolDeclarationFromMcpTool(tool) : undefined;
1246
+ },
1247
+ },
1248
+ onInputRequest: async (request, context) => {
1249
+ const call = context.applicationContext;
1250
+ requireCondition(call && this.#calls.has(call), "mcp_input_unassociated", "Task input has no verified originating invocation.");
1251
+ return (await this.#wire.run(call, () => this.#hostInput(request.kind, copyMcpJSON(request.params ?? {}), context.signal ?? call.signal)));
1252
+ },
1253
+ onError: () => this.host.log({
1254
+ level: "warn",
1255
+ message: "The MCP Tasks adapter reported a protocol error.",
1256
+ data: { connection: this.config.name },
1257
+ }),
1258
+ });
1259
+ }
1260
+ async #drainTasks(call) {
1261
+ const group = this.#taskPending.get(call);
1262
+ while (group?.size)
1263
+ await Promise.allSettled([...group]);
1264
+ if (this.#taskPending.get(call) === group)
1265
+ this.#taskPending.delete(call);
1266
+ }
1267
+ async #withCall(call, action) {
1268
+ this.#calls.add(call);
1269
+ try {
1270
+ return await this.#wire.run(call, action);
1271
+ }
1272
+ catch (cause) {
1273
+ call.signal.throwIfAborted();
1274
+ throw cause instanceof AgentError ? cause : publicError(cause, "call");
1275
+ }
1276
+ finally {
1277
+ await this.#drainTasks(call);
1278
+ this.#calls.delete(call);
1279
+ this.#wire.release(call);
1280
+ this.#creations.delete(call);
1281
+ }
1282
+ }
1283
+ attach(ref) {
1284
+ this.#ref = ref;
1285
+ for (const signal of [this.host.signal, ref.signal]) {
1286
+ const subscription = addAbortListener(signal, () => {
1287
+ void this.dispose(signal.reason).catch(() => { });
1288
+ });
1289
+ this.#detach.push(() => subscription[Symbol.dispose]());
1290
+ }
1291
+ }
1292
+ async connect() {
1293
+ requireCondition(this.#ref && !this.#stopping, "mcp_connection_closed", "The MCP resource must be registered before connection.");
1294
+ this.host.authorize({
1295
+ type: "connection",
1296
+ value: this.config.name,
1297
+ access: "connect",
1298
+ });
1299
+ const timer = setTimeout(() => {
1300
+ this.#initialFailure = new AgentError("mcp_connect_timeout", "The MCP connection or catalog exceeded its initialization deadline.");
1301
+ void this.dispose(this.#initialFailure).catch(() => { });
1302
+ }, this.limits.connectTimeoutMs);
1303
+ try {
1304
+ await this.client.connect(this.transport, {
1305
+ timeout: this.limits.connectTimeoutMs,
1306
+ });
1307
+ const epoch = this.#epoch;
1308
+ const capabilities = this.client.getServerCapabilities() ?? {};
1309
+ const budget = { bytes: 0, items: 0 };
1310
+ const tools = capabilities.tools
1311
+ ? (await this.#collect("tools/list", "tools", budget))
1312
+ : [];
1313
+ const resources = capabilities.resources
1314
+ ? (await this.#collect("resources/list", "resources", budget))
1315
+ : [];
1316
+ const resourceTemplates = capabilities.resources
1317
+ ? (await this.#collect("resources/templates/list", "resourceTemplates", budget))
1318
+ : [];
1319
+ const prompts = capabilities.prompts
1320
+ ? (await this.#collect("prompts/list", "prompts", budget))
1321
+ : [];
1322
+ requireCondition(epoch === this.#epoch, "mcp_catalog_changed", "The MCP catalog changed while it was being prepared.");
1323
+ const header = {
1324
+ server: publicMetadata(this.client.getServerVersion() ?? null),
1325
+ capabilities: Object.fromEntries(Object.entries(capabilities)
1326
+ .filter(([key]) => key !== "_meta")
1327
+ .map(([key, value]) => [key, publicMetadata(value)])),
1328
+ instructions: this.client.getInstructions() ?? null,
1329
+ protocolVersion: this.client.getNegotiatedProtocolVersion() ?? null,
1330
+ };
1331
+ requireCondition(budget.bytes +
1332
+ Buffer.byteLength(canonicalJson(header, this.limits.maxCatalogBytes)) <=
1333
+ this.limits.maxCatalogBytes, "mcp_catalog_too_large", "MCP catalog metadata exceeds its byte budget.");
1334
+ this.#catalog = deepFreeze({
1335
+ name: this.config.name,
1336
+ transport: this.config.transport,
1337
+ instanceId: this.#ref.id,
1338
+ revision: this.limits.revision ?? null,
1339
+ ready: true,
1340
+ stale: false,
1341
+ ...header,
1342
+ tools,
1343
+ resources,
1344
+ resourceTemplates,
1345
+ prompts,
1346
+ });
1347
+ this.#setupTasks();
1348
+ this.#initialCurrent("connect");
1349
+ this.#stale = false;
1350
+ this.#ready = true;
1351
+ this.#ref.report({
1352
+ connection: this.config.name,
1353
+ transport: this.config.transport,
1354
+ state: "ready",
1355
+ toolCount: tools.length,
1356
+ resourceCount: resources.length,
1357
+ promptCount: prompts.length,
1358
+ protocolVersion: header.protocolVersion,
1359
+ });
1360
+ }
1361
+ catch (cause) {
1362
+ await this.dispose(cause);
1363
+ throw (this.#initialFailure ??
1364
+ (cause instanceof AgentError
1365
+ ? cause
1366
+ : publicError(cause, "initialization")));
1367
+ }
1368
+ finally {
1369
+ clearTimeout(timer);
1370
+ }
1371
+ }
1372
+ async #collect(method, field, budget) {
1373
+ const items = [];
1374
+ const identities = new Set();
1375
+ const cursors = new Set();
1376
+ let cursor;
1377
+ for (let page = 0; page < 64; page++) {
1378
+ const result = (await this.#request(method, cursor === undefined ? {} : { cursor }, this.host.signal, this.limits.connectTimeoutMs, false));
1379
+ budget.bytes += Buffer.byteLength(canonicalJson(result, this.limits.maxCatalogBytes));
1380
+ requireCondition(budget.bytes <= this.limits.maxCatalogBytes &&
1381
+ Array.isArray(result[field]), "mcp_catalog_too_large", "An MCP catalog page is invalid or exceeds its byte budget.");
1382
+ for (const item of result[field]) {
1383
+ requireCondition(isPlainRecord(item), "invalid_mcp_catalog", "MCP catalog entries must be data objects.");
1384
+ const identity = item[field === "resources"
1385
+ ? "uri"
1386
+ : field === "resourceTemplates"
1387
+ ? "uriTemplate"
1388
+ : "name"];
1389
+ requireCondition(typeof identity === "string" &&
1390
+ identity.length > 0 &&
1391
+ Buffer.byteLength(identity) <= 1024 &&
1392
+ !/[\0\r\n]/.test(identity) &&
1393
+ !identities.has(identity), "invalid_mcp_catalog", "An MCP catalog has an invalid or duplicate original identity.");
1394
+ identities.add(identity);
1395
+ if (field === "tools") {
1396
+ compileMethodSchema(item.inputSchema, dialect(item.inputSchema));
1397
+ if (item.outputSchema !== undefined)
1398
+ compileMethodSchema(item.outputSchema, dialect(item.outputSchema));
1399
+ }
1400
+ requireCondition(++budget.items <= this.limits.maxCatalogItems, "mcp_catalog_too_large", "The MCP catalog exceeds its item budget.");
1401
+ items.push(item);
1402
+ }
1403
+ if (result.nextCursor === undefined)
1404
+ return items;
1405
+ requireCondition(typeof result.nextCursor === "string" &&
1406
+ result.nextCursor.length > 0 &&
1407
+ Buffer.byteLength(result.nextCursor) <= 4096 &&
1408
+ !cursors.has(result.nextCursor), "invalid_mcp_catalog", "MCP pagination returned an invalid or repeated cursor.");
1409
+ cursor = result.nextCursor;
1410
+ cursors.add(cursor);
1411
+ }
1412
+ throw new AgentError("mcp_catalog_too_large", "The MCP catalog exceeds its page budget.");
1413
+ }
1414
+ catalog() {
1415
+ if (!this.#catalog)
1416
+ return null;
1417
+ const visible = (method, field, items) => projectMcpProtocolResult({ [field]: items }, method)
1418
+ .structuredContent[field];
1419
+ return deepFreeze({
1420
+ ...this.#catalog,
1421
+ tools: visible("tools/list", "tools", this.#catalog.tools),
1422
+ resources: visible("resources/list", "resources", this.#catalog.resources),
1423
+ resourceTemplates: visible("resources/templates/list", "resourceTemplates", this.#catalog.resourceTemplates),
1424
+ prompts: visible("prompts/list", "prompts", this.#catalog.prompts),
1425
+ ready: this.#ready && !this.#stopping && !this.#stale,
1426
+ stale: this.#stale,
1427
+ });
1428
+ }
1429
+ assertCurrent() {
1430
+ requireCondition(this.#ready && !this.#stopping && !this.#stale, "mcp_connection_unavailable", "The original MCP instance is unavailable or needs a catalog refresh.");
1431
+ this.host.authorize({
1432
+ type: "connection",
1433
+ value: this.config.name,
1434
+ access: "use",
1435
+ });
1436
+ }
1437
+ #initialCurrent(access) {
1438
+ this.host.signal.throwIfAborted();
1439
+ this.#ref?.signal.throwIfAborted();
1440
+ requireCondition(!this.#stopping && !this.#initialFailure, "mcp_connection_closed", "The MCP initialization is no longer active.");
1441
+ this.host.authorize({
1442
+ type: "connection",
1443
+ value: this.config.name,
1444
+ access,
1445
+ });
1446
+ }
1447
+ #requestOptions(signal, timeout) {
1448
+ return { signal, timeout, maxTotalTimeout: timeout };
1449
+ }
1450
+ async #request(method, params, signal, timeout, requireReady = true) {
1451
+ if (requireReady)
1452
+ this.assertCurrent();
1453
+ else
1454
+ this.#initialCurrent(method);
1455
+ this.host.authorize({
1456
+ type: "connection",
1457
+ value: this.config.name,
1458
+ access: method,
1459
+ });
1460
+ signal.throwIfAborted();
1461
+ canonicalJson(params, this.limits.maxMessageBytes);
1462
+ const action = () => this.client.request({
1463
+ method: method,
1464
+ params: { ...params, _meta: this.#metadata(this.#wire.current()) },
1465
+ }, this.#requestOptions(signal, timeout));
1466
+ try {
1467
+ const result = await (this.#http
1468
+ ? this.#http.run(signal, action)
1469
+ : this.#stdio.run(signal, action));
1470
+ signal.throwIfAborted();
1471
+ if (requireReady)
1472
+ this.assertCurrent();
1473
+ else
1474
+ this.#initialCurrent(method);
1475
+ this.host.authorize({
1476
+ type: "connection",
1477
+ value: this.config.name,
1478
+ access: method,
1479
+ });
1480
+ return result;
1481
+ }
1482
+ catch (cause) {
1483
+ signal.throwIfAborted();
1484
+ throw cause instanceof AgentError ? cause : publicError(cause, "request");
1485
+ }
1486
+ }
1487
+ invoke(method, params, call, tool) {
1488
+ return this.#withCall(call, () => this.#invoke(method, params, call, tool));
1489
+ }
1490
+ async #invoke(method, params, call, tool) {
1491
+ this.assertCurrent();
1492
+ call.authorize({
1493
+ type: "connection",
1494
+ value: this.config.name,
1495
+ access: method,
1496
+ });
1497
+ this.host.authorize({
1498
+ type: "connection",
1499
+ value: this.config.name,
1500
+ access: method,
1501
+ });
1502
+ if (this.config.transport === "streamable-http")
1503
+ call.authorize({
1504
+ type: "url",
1505
+ value: this.config.url,
1506
+ access: "request",
1507
+ });
1508
+ if (method === "resources/read")
1509
+ call.authorize({
1510
+ type: "resource",
1511
+ value: params.uri,
1512
+ access: "read",
1513
+ });
1514
+ requireCondition(call.deadline > Date.now(), "deadline_exceeded", "The MCP operation deadline has already expired.");
1515
+ const timeout = Math.max(1, Math.min(this.limits.requestTimeoutMs, Math.ceil(call.deadline - Date.now()), maximumTimeout));
1516
+ call.signal.throwIfAborted();
1517
+ if (tool) {
1518
+ canonicalJson(params, this.limits.maxMessageBytes);
1519
+ if (this.#tasks?.capabilities.execution)
1520
+ return this.#invokeTask(tool, params, call, timeout);
1521
+ const action = () => this.client.callTool({ name: tool.name, arguments: params, _meta: this.#metadata(call) }, {
1522
+ ...this.#requestOptions(call.signal, timeout),
1523
+ toolDefinition: this.#catalog.tools.find((item) => item.name === tool.name),
1524
+ });
1525
+ try {
1526
+ const raw = await (this.#http
1527
+ ? this.#http.run(call.signal, action)
1528
+ : this.#stdio.run(call.signal, action));
1529
+ call.signal.throwIfAborted();
1530
+ this.assertCurrent();
1531
+ this.host.authorize({
1532
+ type: "connection",
1533
+ value: this.config.name,
1534
+ access: method,
1535
+ });
1536
+ return call.output.mcpResult(raw, {
1537
+ connectionResourceId: this.#ref.id,
1538
+ connection: this.config.name,
1539
+ });
1540
+ }
1541
+ catch (cause) {
1542
+ call.signal.throwIfAborted();
1543
+ throw cause instanceof AgentError
1544
+ ? cause
1545
+ : publicError(cause, "tool call");
1546
+ }
1547
+ }
1548
+ const raw = await this.#request(method, params, call.signal, timeout);
1549
+ this.assertCurrent();
1550
+ if (method === "resources/read")
1551
+ return call.output.mcpResourceResult(raw, {
1552
+ connectionResourceId: this.#ref.id,
1553
+ connection: this.config.name,
1554
+ });
1555
+ return call.output.mcpResult(raw, {
1556
+ connectionResourceId: this.#ref.id,
1557
+ connection: this.config.name,
1558
+ method,
1559
+ });
1560
+ }
1561
+ #channel(uri, member) {
1562
+ const existing = this.#subscriptions.get(uri);
1563
+ if (existing && !existing.closing) {
1564
+ existing.members.add(member);
1565
+ return existing;
1566
+ }
1567
+ const abort = new AbortController();
1568
+ const signal = AbortSignal.any([this.host.signal, abort.signal]);
1569
+ const ready = Promise.withResolvers(), closed = Promise.withResolvers();
1570
+ void ready.promise.catch(() => { });
1571
+ let running, closing = false, active = false, acceptingUpdates = false;
1572
+ const channel = {
1573
+ uri,
1574
+ members: new Set([member]),
1575
+ ready: ready.promise,
1576
+ closed: closed.promise,
1577
+ get closing() {
1578
+ return closing;
1579
+ },
1580
+ get active() {
1581
+ return active;
1582
+ },
1583
+ get acceptingUpdates() {
1584
+ return acceptingUpdates;
1585
+ },
1586
+ stop: async () => {
1587
+ closing = true;
1588
+ active = false;
1589
+ acceptingUpdates = false;
1590
+ abort.abort();
1591
+ try {
1592
+ await running;
1593
+ }
1594
+ catch (cause) {
1595
+ throw cause instanceof AgentError
1596
+ ? cause
1597
+ : publicError(cause, "subscription cleanup");
1598
+ }
1599
+ },
1600
+ };
1601
+ this.#subscriptions.set(uri, channel);
1602
+ running = this.#wire.run(undefined, async () => {
1603
+ let attempted = false;
1604
+ try {
1605
+ // The old legacy unsubscribe must settle before a replacement subscribe;
1606
+ // otherwise its late ACK can clear the newly accepted subscription.
1607
+ if (existing)
1608
+ await existing.stop();
1609
+ signal.throwIfAborted();
1610
+ this.host.authorize({
1611
+ type: "connection",
1612
+ value: this.config.name,
1613
+ access: "resources.subscribe",
1614
+ });
1615
+ this.host.authorize({
1616
+ type: "resource",
1617
+ value: uri,
1618
+ access: "subscribe",
1619
+ });
1620
+ acceptingUpdates = true;
1621
+ if (this.client.getProtocolEra() === "modern") {
1622
+ await this.#io(signal, async () => {
1623
+ const subscription = await this.client.listen({ resourceSubscriptions: [uri] }, {
1624
+ signal,
1625
+ timeout: Math.min(this.limits.requestTimeoutMs, 10000),
1626
+ });
1627
+ try {
1628
+ requireCondition(subscription.honoredFilter.resourceSubscriptions?.includes(uri), "mcp_subscription_rejected", "The MCP server did not honor this resource subscription.");
1629
+ active = true;
1630
+ ready.resolve();
1631
+ await subscription.closed;
1632
+ }
1633
+ finally {
1634
+ await subscription.close();
1635
+ }
1636
+ });
1637
+ }
1638
+ else {
1639
+ attempted = true;
1640
+ await this.#io(signal, () => this.client.subscribeResource({ uri }, {
1641
+ signal,
1642
+ timeout: Math.min(this.limits.requestTimeoutMs, 10000),
1643
+ }));
1644
+ active = true;
1645
+ ready.resolve();
1646
+ if (!signal.aborted)
1647
+ await once(signal, "abort");
1648
+ }
1649
+ }
1650
+ catch (cause) {
1651
+ ready.reject(cause);
1652
+ throw cause;
1653
+ }
1654
+ finally {
1655
+ active = false;
1656
+ acceptingUpdates = false;
1657
+ closing = true;
1658
+ try {
1659
+ if (attempted && !this.host.signal.aborted) {
1660
+ const stopSignal = AbortSignal.any([
1661
+ this.host.signal,
1662
+ AbortSignal.timeout(5000),
1663
+ ]);
1664
+ this.host.authorize({
1665
+ type: "connection",
1666
+ value: this.config.name,
1667
+ access: "resources.unsubscribe",
1668
+ });
1669
+ await this.#io(stopSignal, () => this.client.unsubscribeResource({ uri }, { signal: stopSignal, timeout: 5000 }));
1670
+ }
1671
+ }
1672
+ finally {
1673
+ if (this.#subscriptions.get(uri) === channel)
1674
+ this.#subscriptions.delete(uri);
1675
+ closed.resolve();
1676
+ for (const listener of channel.members)
1677
+ listener.channelClosed();
1678
+ channel.members.clear();
1679
+ }
1680
+ }
1681
+ });
1682
+ void running.catch(() => { });
1683
+ return channel;
1684
+ }
1685
+ subscriptionControl(action, input, call) {
1686
+ return this.#withCall(call, async () => {
1687
+ this.host.signal.throwIfAborted();
1688
+ call.signal.throwIfAborted();
1689
+ call.authorize({
1690
+ type: "connection",
1691
+ value: this.config.name,
1692
+ access: `resources.${action}`,
1693
+ });
1694
+ if (action === "subscribe") {
1695
+ this.assertCurrent();
1696
+ const uri = input.uri;
1697
+ call.authorize({ type: "resource", value: uri, access: "subscribe" });
1698
+ const member = new ManagedMcpSubscription(this.config.name, uri, (item) => this.#channel(uri, item), async (item, channel) => {
1699
+ channel.members.delete(item);
1700
+ if (!channel.members.size)
1701
+ await channel.stop();
1702
+ });
1703
+ const ref = await call.resources.register({
1704
+ kind: "mcp.subscription",
1705
+ value: member,
1706
+ });
1707
+ member.attach(ref);
1708
+ try {
1709
+ await member.open();
1710
+ call.signal.throwIfAborted();
1711
+ if (input.background === true)
1712
+ await call.resources.handoff(ref.id);
1713
+ return {
1714
+ subscriptionId: ref.id,
1715
+ uri,
1716
+ background: input.background === true,
1717
+ };
1718
+ }
1719
+ catch (cause) {
1720
+ await member.dispose().catch(() => { });
1721
+ throw cause;
1722
+ }
1723
+ }
1724
+ const ref = await call.resources.get(input.subscriptionId);
1725
+ requireCondition(ref.kind === "mcp.subscription" &&
1726
+ ref.value instanceof ManagedMcpSubscription &&
1727
+ ref.value.connection === this.config.name, "mcp_subscription_unavailable", "The resource is not a subscription owned by this original connection.");
1728
+ call.authorize({
1729
+ type: "resource",
1730
+ value: ref.value.uri,
1731
+ access: action === "get" ? "read" : "unsubscribe",
1732
+ });
1733
+ if (action === "unsubscribe") {
1734
+ await ref.value.dispose();
1735
+ return { subscriptionId: ref.id, state: "closed" };
1736
+ }
1737
+ return {
1738
+ subscriptionId: ref.id,
1739
+ ...(await ref.value.read(input.cursor ?? 0, input.waitMs ?? 0, call.signal)),
1740
+ };
1741
+ });
1742
+ }
1743
+ supportsTasks() {
1744
+ return !!this.#tasks?.capabilities.execution;
1745
+ }
1746
+ taskControl(action, input, call) {
1747
+ return this.#withCall(call, async () => {
1748
+ this.host.signal.throwIfAborted();
1749
+ call.signal.throwIfAborted();
1750
+ call.authorize({
1751
+ type: "connection",
1752
+ value: this.config.name,
1753
+ access: `tasks.${action}`,
1754
+ });
1755
+ if (action === "list") {
1756
+ const page = await call.resources.list({
1757
+ kind: "mcp.task",
1758
+ ...(input.limit === undefined
1759
+ ? {}
1760
+ : { limit: input.limit }),
1761
+ ...(input.cursor === undefined
1762
+ ? {}
1763
+ : { cursor: input.cursor }),
1764
+ ...(input.status === undefined
1765
+ ? {}
1766
+ : { state: input.status }),
1767
+ });
1768
+ return {
1769
+ ...page,
1770
+ items: page.items.filter((item) => item.details.connection === this.config.name),
1771
+ };
1772
+ }
1773
+ const ref = await call.resources.get(input.resourceId);
1774
+ requireCondition(ref.kind === "mcp.task" &&
1775
+ ref.value instanceof ManagedMcpExecution &&
1776
+ ref.value.connection === this.config.name, "mcp_task_unavailable", "The resource is not a task owned by this original MCP connection.");
1777
+ if (action === "cancel") {
1778
+ await ref.value.dispose();
1779
+ return { resourceId: ref.id, ...ref.value.facts() };
1780
+ }
1781
+ return { resourceId: ref.id, ...(await ref.value.snapshot(call.signal)) };
1782
+ });
1783
+ }
1784
+ async #invokeTask(tool, params, call, timeout) {
1785
+ const creation = {
1786
+ call,
1787
+ maybeStarted: false,
1788
+ awaitingResponse: false,
1789
+ malformedTask: false,
1790
+ stopping: false,
1791
+ };
1792
+ this.#creations.set(call, creation);
1793
+ const controller = new ManagedMcpExecution(this.#tasks, call, this.config.name, async () => {
1794
+ this.assertCurrent();
1795
+ call.signal.throwIfAborted();
1796
+ return this.#tasks.callTool(tool.name, params, {
1797
+ declaration: toolDeclarationFromMcpTool(tool),
1798
+ applicationContext: call,
1799
+ signal: this.host.signal,
1800
+ metadata: this.#metadata(call),
1801
+ requestTimeoutMs: timeout,
1802
+ });
1803
+ }, () => this.#drainTasks(call), creation, (action) => this.#cleanupContext.run(true, () => this.#wire.run(call, action)));
1804
+ const ref = await call.resources.register({
1805
+ kind: "mcp.task",
1806
+ value: controller,
1807
+ });
1808
+ controller.attach(ref);
1809
+ void controller.closed.then(() => {
1810
+ if (creation.taskId && this.#knownTasks.get(creation.taskId) === creation)
1811
+ this.#knownTasks.delete(creation.taskId);
1812
+ });
1813
+ const raw = await controller.execute();
1814
+ if (tool.outputSchema !== undefined &&
1815
+ isPlainRecord(raw) &&
1816
+ raw.isError !== true) {
1817
+ requireCondition(Object.hasOwn(raw, "structuredContent"), "invalid_mcp_result", "The task result omitted its declared structured content.");
1818
+ compileMethodSchema(tool.outputSchema, dialect(tool.outputSchema))(raw.structuredContent);
1819
+ }
1820
+ call.signal.throwIfAborted();
1821
+ this.assertCurrent();
1822
+ return call.output.mcpResult(raw, {
1823
+ connectionResourceId: this.#ref.id,
1824
+ connection: this.config.name,
1825
+ });
1826
+ }
1827
+ readResource(uri, scope) {
1828
+ this.assertCurrent();
1829
+ scope.assertCurrent();
1830
+ scope.authorizeConnection(this.config.name, uri, "resources.read");
1831
+ this.host.authorize({ type: "resource", value: uri, access: "read" });
1832
+ const signal = scope.signal ?? this.host.signal;
1833
+ return this.#request("resources/read", { uri }, signal, this.limits.requestTimeoutMs).then((result) => {
1834
+ scope.assertCurrent();
1835
+ scope.authorizeConnection(this.config.name, uri, "resources.read");
1836
+ this.assertCurrent();
1837
+ return result;
1838
+ });
1839
+ }
1840
+ listResources(scope, cursor) {
1841
+ this.assertCurrent();
1842
+ scope.assertCurrent();
1843
+ scope.authorizeConnection(this.config.name, undefined, "resources.list");
1844
+ return this.#request("resources/list", cursor === undefined ? {} : { cursor }, scope.signal ?? this.host.signal, this.limits.requestTimeoutMs).then((result) => {
1845
+ scope.assertCurrent();
1846
+ this.assertCurrent();
1847
+ return result;
1848
+ });
1849
+ }
1850
+ dispose(reason) {
1851
+ if (this.#dispose)
1852
+ return this.#dispose;
1853
+ this.#stopping = true;
1854
+ this.#ready = false;
1855
+ let reportFailure;
1856
+ if (!this.#physicallyClosed) {
1857
+ try {
1858
+ this.#ref?.report({
1859
+ connection: this.config.name,
1860
+ transport: this.config.transport,
1861
+ state: "stopping",
1862
+ });
1863
+ }
1864
+ catch (cause) {
1865
+ reportFailure = cause;
1866
+ }
1867
+ }
1868
+ this.#dispose = (async () => {
1869
+ await this.#control.dispose(reason);
1870
+ await this.closed;
1871
+ await this.#tasks?.close();
1872
+ this.#taskPort?.[Symbol.dispose]();
1873
+ if (reportFailure)
1874
+ throw reportFailure;
1875
+ })();
1876
+ void this.#dispose.catch(() => {
1877
+ this.#dispose = undefined;
1878
+ });
1879
+ return this.#dispose;
1880
+ }
1881
+ }
1882
+ /** A trusted, approved final config becomes one public extension instance. */
1883
+ export function createMcpAdapter(value, options = {}) {
1884
+ const config = validateMcpConnectionConfig(value), limits = optionsSnapshot(options);
1885
+ let connection;
1886
+ const factory = async (host) => {
1887
+ requireCondition(!connection, "mcp_adapter_in_use", "Create a new adapter for each MCP source instance.");
1888
+ const current = new McpConnection(host, config, limits);
1889
+ connection = current;
1890
+ try {
1891
+ const ref = await host.resources.register({
1892
+ kind: "mcp.connection",
1893
+ value: current,
1894
+ });
1895
+ current.attach(ref);
1896
+ await current.connect();
1897
+ const catalog = current.catalog();
1898
+ const methods = Object.create(null);
1899
+ const define = (key, path, description, inputSchema, handler, schemaDialect = "2020-12") => {
1900
+ methods[key] = {
1901
+ path,
1902
+ description,
1903
+ permissions: allPermissions,
1904
+ inputSchema,
1905
+ schemaDialect,
1906
+ normalize: (args) => {
1907
+ requireCondition(args.length <= 1, "invalid_arguments", "MCP methods take one argument object.");
1908
+ // Snapshot JSON before Core validates it. Guest mutation while
1909
+ // the official client awaits metadata must not change a checked call.
1910
+ return deepFreeze(copyMcpJSON(args[0] ?? {}, limits.maxMessageBytes));
1911
+ },
1912
+ handle: handler,
1913
+ };
1914
+ };
1915
+ for (const tool of catalog.tools)
1916
+ define(`tools/${tool.name}`, ["tools", tool.name], tool.description ?? `Call MCP tool ${tool.name}.`, tool.inputSchema, (input, call) => current.invoke("tools/call", input, call, tool), dialect(tool.inputSchema));
1917
+ if (catalog.capabilities.resources) {
1918
+ define("resources/list", ["resources", "list"], "List one page of the remote MCP resource catalog.", pageSchema, (input, call) => current.invoke("resources/list", input, call));
1919
+ define("resources/listTemplates", ["resources", "listTemplates"], "List one page of remote MCP resource templates.", pageSchema, (input, call) => current.invoke("resources/templates/list", input, call));
1920
+ define("resources/read", ["resources", "read"], "Read a remote resource through the current MCP connection.", readSchema, (input, call) => current.invoke("resources/read", input, call));
1921
+ }
1922
+ if (catalog.capabilities
1923
+ .resources?.subscribe) {
1924
+ define("resources/subscribe", ["resources", "subscribe"], "Subscribe to real resource updates; ordinary ownership ends with the run unless explicitly handed off.", {
1925
+ type: "object",
1926
+ additionalProperties: false,
1927
+ required: ["uri"],
1928
+ properties: {
1929
+ uri: { type: "string", minLength: 1, maxLength: 1024 },
1930
+ background: { type: "boolean" },
1931
+ },
1932
+ }, (input, call) => current.subscriptionControl("subscribe", input, call));
1933
+ define("resources/getSubscription", ["resources", "getSubscription"], "Read bounded subscription notifications using a stable resource identity.", {
1934
+ type: "object",
1935
+ additionalProperties: false,
1936
+ required: ["subscriptionId"],
1937
+ properties: {
1938
+ subscriptionId: { type: "string", minLength: 1, maxLength: 256 },
1939
+ cursor: { type: "integer", minimum: 0 },
1940
+ waitMs: { type: "integer", minimum: 0, maximum: 30000 },
1941
+ },
1942
+ }, (input, call) => current.subscriptionControl("get", input, call));
1943
+ define("resources/unsubscribe", ["resources", "unsubscribe"], "Stop one registered resource subscription and wait for its actual local closure.", {
1944
+ type: "object",
1945
+ additionalProperties: false,
1946
+ required: ["subscriptionId"],
1947
+ properties: {
1948
+ subscriptionId: { type: "string", minLength: 1, maxLength: 256 },
1949
+ },
1950
+ }, (input, call) => current.subscriptionControl("unsubscribe", input, call));
1951
+ }
1952
+ if (catalog.capabilities.prompts) {
1953
+ define("prompts/list", ["prompts", "list"], "List one page of the remote MCP prompt catalog.", pageSchema, (input, call) => current.invoke("prompts/list", input, call));
1954
+ define("prompts/get", ["prompts", "get"], "Read a prompt, preserving message roles and standard media content.", getPromptSchema, (input, call) => current.invoke("prompts/get", input, call));
1955
+ }
1956
+ if (current.supportsTasks()) {
1957
+ const resource = { type: "string", minLength: 1, maxLength: 256 };
1958
+ for (const action of ["get", "cancel"])
1959
+ define(`tasks/${action}`, ["tasks", action], `Read or stop a Nexum-managed remote task using its resource identity.`, {
1960
+ type: "object",
1961
+ additionalProperties: false,
1962
+ required: ["resourceId"],
1963
+ properties: { resourceId: resource },
1964
+ }, (input, call) => current.taskControl(action, input, call));
1965
+ define("tasks/list", ["tasks", "list"], "List retained Nexum-managed task resources for this connection.", {
1966
+ type: "object",
1967
+ additionalProperties: false,
1968
+ properties: {
1969
+ status: { type: "string", maxLength: 64 },
1970
+ limit: { type: "integer", minimum: 1, maximum: 100 },
1971
+ cursor: { type: "string", maxLength: 8192 },
1972
+ },
1973
+ }, (input, call) => current.taskControl("list", input, call));
1974
+ }
1975
+ return { methods, dispose: () => current.dispose() };
1976
+ }
1977
+ catch (cause) {
1978
+ await current.dispose(cause);
1979
+ throw cause;
1980
+ }
1981
+ };
1982
+ return Object.freeze({
1983
+ factory,
1984
+ bindingPath: Object.freeze(["mcp", config.name]),
1985
+ permissions: allPermissions,
1986
+ catalog: () => connection?.catalog() ?? null,
1987
+ });
1988
+ }
1989
+ //# sourceMappingURL=mcp.js.map