@zyro-sec/core 1.0.0 → 1.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 (1087) hide show
  1. package/AGENTS.md +7 -0
  2. package/bunfig.toml +2 -0
  3. package/drizzle.config.ts +10 -0
  4. package/package.json +24 -30
  5. package/perf/location.bench.ts +44 -0
  6. package/perf/location.ts +140 -0
  7. package/perf/session.bench.ts +22 -0
  8. package/perf/snapshot.bench.ts +67 -0
  9. package/perf/snapshot.ts +423 -0
  10. package/schema.json +2763 -0
  11. package/script/build.ts +44 -0
  12. package/script/fix-node-pty.ts +28 -0
  13. package/script/generate-api-skill.ts +361 -0
  14. package/script/migration.ts +216 -0
  15. package/script/models-snapshot.ts +82 -0
  16. package/script/pack.ts +5 -0
  17. package/script/snapshot-parity-compare.ts +22 -0
  18. package/script/snapshot-parity-run.sh +20 -0
  19. package/script/snapshot-parity.ts +710 -0
  20. package/script/test.ts +53 -0
  21. package/script/update-models-snapshot.ts +14 -0
  22. package/script/wellknown-server.ts +112 -0
  23. package/src/account/sql.ts +36 -0
  24. package/src/agent.ts +115 -0
  25. package/src/aisdk-native.ts +397 -0
  26. package/src/aisdk.ts +1063 -0
  27. package/src/app.ts +31 -0
  28. package/src/artifact.ts +617 -0
  29. package/src/automation/author.ts +10 -0
  30. package/src/automation/code.ts +269 -0
  31. package/src/automation/event.ts +35 -0
  32. package/src/automation/shell.ts +82 -0
  33. package/src/automation/sql.ts +50 -0
  34. package/src/automation.ts +1293 -0
  35. package/src/blob-store.ts +115 -0
  36. package/src/bus.ts +909 -0
  37. package/src/codemode/api.ts +44 -0
  38. package/src/codemode/bun.ts +550 -0
  39. package/src/codemode/catalog.ts +177 -0
  40. package/src/codemode/diffs.ts +134 -0
  41. package/src/codemode/execution.ts +9 -0
  42. package/src/codemode/fetch.ts +179 -0
  43. package/src/codemode/instructions.ts +169 -0
  44. package/src/codemode/job.ts +144 -0
  45. package/src/codemode/path.ts +45 -0
  46. package/src/codemode/tool.ts +564 -0
  47. package/src/command.ts +109 -0
  48. package/src/config/discovery.ts +183 -0
  49. package/src/config/integration.ts +134 -0
  50. package/src/config/managed.ts +6 -0
  51. package/src/config/markdown.ts +123 -0
  52. package/src/config/normalize.ts +870 -0
  53. package/src/config/plugin/agent.ts +192 -0
  54. package/src/config/plugin/command.ts +229 -0
  55. package/src/config/plugin/compaction.ts +27 -0
  56. package/src/config/plugin/compatibility.ts +94 -0
  57. package/src/config/plugin/entry-observer.ts +79 -0
  58. package/src/config/plugin/formatter.ts +76 -0
  59. package/src/config/plugin/image.ts +29 -0
  60. package/src/config/plugin/instruction.ts +260 -0
  61. package/src/config/plugin/location-watcher.ts +22 -0
  62. package/src/config/plugin/mcp.ts +57 -0
  63. package/src/config/plugin/policy.ts +117 -0
  64. package/src/config/plugin/provider.ts +274 -0
  65. package/src/config/plugin/reference.ts +67 -0
  66. package/src/config/plugin/session-search.ts +21 -0
  67. package/src/config/plugin/shell.ts +20 -0
  68. package/src/config/plugin/skill-file.ts +62 -0
  69. package/src/config/plugin/skill-scan.ts +46 -0
  70. package/src/config/plugin/skill.ts +202 -0
  71. package/src/config/plugin/snapshot.ts +21 -0
  72. package/src/config/plugin/source.ts +194 -0
  73. package/src/config/plugin/tool-output.ts +24 -0
  74. package/src/config/plugin/websearch.ts +19 -0
  75. package/src/config/plugin/worktree.ts +35 -0
  76. package/src/config/variable.ts +84 -0
  77. package/src/config/watch.ts +73 -0
  78. package/src/config.ts +574 -0
  79. package/src/console-access.ts +22 -0
  80. package/src/credential/sql.ts +14 -0
  81. package/src/credential.ts +350 -0
  82. package/src/database/batch.ts +21 -0
  83. package/src/database/database.ts +126 -0
  84. package/src/database/drizzle/README.md +35 -0
  85. package/src/database/drizzle/effect-sqlite/driver.ts +78 -0
  86. package/src/database/drizzle/effect-sqlite/index.ts +4 -0
  87. package/src/database/drizzle/effect-sqlite/session.ts +252 -0
  88. package/src/database/drizzle/index.ts +5 -0
  89. package/src/database/drizzle/internal/drizzle-utils.ts +147 -0
  90. package/src/database/drizzle/sqlite-core/effect/count.ts +58 -0
  91. package/src/database/drizzle/sqlite-core/effect/db.ts +243 -0
  92. package/src/database/drizzle/sqlite-core/effect/delete.ts +261 -0
  93. package/src/database/drizzle/sqlite-core/effect/index.ts +10 -0
  94. package/src/database/drizzle/sqlite-core/effect/insert.ts +340 -0
  95. package/src/database/drizzle/sqlite-core/effect/query.ts +198 -0
  96. package/src/database/drizzle/sqlite-core/effect/raw.ts +49 -0
  97. package/src/database/drizzle/sqlite-core/effect/select.ts +278 -0
  98. package/src/database/drizzle/sqlite-core/effect/session.ts +421 -0
  99. package/src/database/drizzle/sqlite-core/effect/update.ts +402 -0
  100. package/src/database/drizzle.ts +1 -0
  101. package/src/database/migration/20260127222353_familiar_lady_ursula.ts +109 -0
  102. package/src/database/migration/20260211171708_add_project_commands.ts +13 -0
  103. package/src/database/migration/20260213144116_wakeful_the_professor.ts +25 -0
  104. package/src/database/migration/20260225215848_workspace.ts +21 -0
  105. package/src/database/migration/20260227213759_add_session_workspace_id.ts +14 -0
  106. package/src/database/migration/20260228203230_blue_harpoon.ts +32 -0
  107. package/src/database/migration/20260303231226_add_workspace_fields.ts +17 -0
  108. package/src/database/migration/20260309230000_move_org_to_state.ts +17 -0
  109. package/src/database/migration/20260312043431_session_message_cursor.ts +18 -0
  110. package/src/database/migration/20260323234822_events.ts +28 -0
  111. package/src/database/migration/20260410174513_workspace-name.ts +34 -0
  112. package/src/database/migration/20260413175956_chief_energizer.ts +26 -0
  113. package/src/database/migration/20260423070820_add_icon_url_override.ts +16 -0
  114. package/src/database/migration/20260427172553_slow_nightmare.ts +32 -0
  115. package/src/database/migration/20260428004200_add_session_path.ts +13 -0
  116. package/src/database/migration/20260501142318_next_venus.ts +14 -0
  117. package/src/database/migration/20260504145000_add_sync_owner.ts +13 -0
  118. package/src/database/migration/20260507164347_add_workspace_time.ts +13 -0
  119. package/src/database/migration/20260510033149_session_usage.ts +58 -0
  120. package/src/database/migration/20260511000411_data_migration_state.ts +18 -0
  121. package/src/database/migration/20260511173437_session-metadata.ts +18 -0
  122. package/src/database/migration/20260601010001_normalize_storage_paths.ts +24 -0
  123. package/src/database/migration/20260601202201_amazing_prowler.ts +13 -0
  124. package/src/database/migration/20260602002951_lowly_union_jack.ts +26 -0
  125. package/src/database/migration/20260602182828_add_project_directories.ts +22 -0
  126. package/src/database/migration/20260603001617_session_message_projection_indexes.ts +21 -0
  127. package/src/database/migration/20260603040000_session_message_projection_order.ts +21 -0
  128. package/src/database/migration/20260603141458_session_input_inbox.ts +27 -0
  129. package/src/database/migration/20260603160727_jittery_ezekiel_stane.ts +22 -0
  130. package/src/database/migration/20260604172448_event_sourced_session_input.ts +49 -0
  131. package/src/database/migration/20260605003541_add_session_context_snapshot.ts +23 -0
  132. package/src/database/migration/20260605042240_add_context_epoch_agent.ts +13 -0
  133. package/src/database/migration/20260611035744_credential.ts +27 -0
  134. package/src/database/migration/20260611192811_lush_chimera.ts +27 -0
  135. package/src/database/migration/20260612174303_project_dir_strategy.ts +31 -0
  136. package/src/database/migration/20260622142730_simplify_session_context_epoch.ts +15 -0
  137. package/src/database/migration/20260622170816_reset_v2_session_state.ts +17 -0
  138. package/src/database/migration/20260622202450_simplify_session_input.ts +19 -0
  139. package/src/database/migration/20260804233008_loose_psylocke.ts +173 -0
  140. package/src/database/migration/20260805200742_import_legacy_credentials.ts +109 -0
  141. package/src/database/migration/20260808023530_workspace_domain.ts +22 -0
  142. package/src/database/migration/20260811161259_execution_claim_attempts.ts +13 -0
  143. package/src/database/migration/20260812181746_session_inbox.ts +30 -0
  144. package/src/database/migration/20260812213948_worktree.ts +35 -0
  145. package/src/database/migration/20260819222447_session_viewed_state.ts +15 -0
  146. package/src/database/migration/20260823191254_nullable_workspace_binding.ts +27 -0
  147. package/src/database/migration/20260910120000_clear_v1_session_permission.ts +13 -0
  148. package/src/database/migration/20260923013825_project_time_active.ts +14 -0
  149. package/src/database/migration/20261007190000_azure_cli_external_credential.ts +21 -0
  150. package/src/database/migration/20261010180456_project_time_archived.ts +13 -0
  151. package/src/database/migration/20261024002554_session_allowance.ts +13 -0
  152. package/src/database/migration/20261024175301_drop_session_allowance.ts +13 -0
  153. package/src/database/migration/20261025123711_blob.ts +36 -0
  154. package/src/database/migration/20261025154125_drop_session_pending.ts +16 -0
  155. package/src/database/migration/20261026223005_schedule.ts +38 -0
  156. package/src/database/migration/20261029002625_session_part.ts +30 -0
  157. package/src/database/migration/20261029073502_session_time_busy.ts +13 -0
  158. package/src/database/migration/20261029165540_schedule_checks.ts +16 -0
  159. package/src/database/migration/20261030054400_job.ts +60 -0
  160. package/src/database/migration/20261116043204_automation.ts +83 -0
  161. package/src/database/migration/20261116181958_automation_event_position.ts +13 -0
  162. package/src/database/migration/20261116213417_automation_active_index.ts +16 -0
  163. package/src/database/migration/20261119211416_machine.ts +18 -0
  164. package/src/database/migration/20261120004954_machine-key.ts +14 -0
  165. package/src/database/migration.gen.ts +132 -0
  166. package/src/database/migration.ts +155 -0
  167. package/src/database/path.ts +98 -0
  168. package/src/database/schema.gen.ts +363 -0
  169. package/src/database/schema.sql.ts +10 -0
  170. package/src/database/sqlite.bun.ts +17 -0
  171. package/src/database/sqlite.node.ts +25 -0
  172. package/src/database/sqlite.workerd.ts +227 -0
  173. package/src/database/storage-failure.ts +58 -0
  174. package/src/database/v1-migration.bun.ts +1234 -0
  175. package/src/database/v1-migration.noop.ts +11 -0
  176. package/src/database/v1-migration.ts +2 -0
  177. package/src/effect/app-node-builder.ts +30 -0
  178. package/src/effect/app-node-platform.ts +71 -0
  179. package/src/effect/client-tls/client-tls.bun.ts +8 -0
  180. package/src/effect/client-tls/client-tls.node.ts +17 -0
  181. package/src/effect/client-tls/client-tls.ts +12 -0
  182. package/src/effect/client-tls/client-tls.workerd.ts +8 -0
  183. package/src/effect/keyed-mutex.ts +45 -0
  184. package/src/effect/websocket-constructor.ts +81 -0
  185. package/src/environment/driver.ts +68 -0
  186. package/src/environment/environment.ts +152 -0
  187. package/src/environment/environments.ts +78 -0
  188. package/src/environment/exec-defaults.ts +200 -0
  189. package/src/environment/files.ts +79 -0
  190. package/src/environment/index.ts +34 -0
  191. package/src/environment/local.ts +101 -0
  192. package/src/environment/memory.ts +186 -0
  193. package/src/environment/path.ts +68 -0
  194. package/src/environment/unavailable.ts +17 -0
  195. package/src/event/sql.ts +26 -0
  196. package/src/event-logger.ts +19 -0
  197. package/src/file-access.ts +352 -0
  198. package/src/file-mutation.ts +185 -0
  199. package/src/file-retention.ts +23 -0
  200. package/src/file-write.ts +110 -0
  201. package/src/filesystem/fff.bun.ts +15 -0
  202. package/src/filesystem/fff.node.ts +12 -0
  203. package/src/filesystem/fff.ts +67 -0
  204. package/src/filesystem/fff.workerd.ts +12 -0
  205. package/src/filesystem/file-watch.ts +164 -0
  206. package/src/filesystem/location-watcher-policy.ts +64 -0
  207. package/src/filesystem/location-watcher.ts +108 -0
  208. package/src/filesystem/protected.ts +31 -0
  209. package/src/filesystem/search.ts +251 -0
  210. package/src/filesystem/watcher-binding.ts +14 -0
  211. package/src/filesystem/watcher.ts +282 -0
  212. package/src/filesystem.ts +270 -0
  213. package/src/flag/resolve.ts +66 -0
  214. package/src/flag.ts +64 -0
  215. package/src/form.ts +370 -0
  216. package/src/formatter/builtins.ts +294 -0
  217. package/src/formatter.ts +108 -0
  218. package/src/generate.ts +397 -0
  219. package/src/git.ts +1609 -0
  220. package/src/github-copilot/models.ts +289 -0
  221. package/src/image/notice.ts +8 -0
  222. package/src/image/photon-normalize.ts +148 -0
  223. package/src/image/photon-wasm.bun.ts +4 -0
  224. package/src/image/photon-wasm.node.ts +4 -0
  225. package/src/image/photon-wasm.workerd.ts +4 -0
  226. package/src/image/photon-worker.ts +26 -0
  227. package/src/image/photon.ts +156 -0
  228. package/src/image.ts +95 -0
  229. package/src/instance/service.ts +21 -0
  230. package/src/instance.ts +191 -0
  231. package/src/instruction-discovery.ts +165 -0
  232. package/src/instructions/agent.ts +50 -0
  233. package/src/instructions/builtins.ts +103 -0
  234. package/src/instructions/index.ts +287 -0
  235. package/src/integration/connection.ts +26 -0
  236. package/src/integration.ts +869 -0
  237. package/src/job/list.ts +160 -0
  238. package/src/job/recovery.ts +51 -0
  239. package/src/job/sql.ts +27 -0
  240. package/src/job.ts +766 -0
  241. package/src/kv/sql.ts +9 -0
  242. package/src/kv.ts +92 -0
  243. package/src/location-activity.ts +130 -0
  244. package/src/location-lifecycle.ts +97 -0
  245. package/src/location-service-map.ts +50 -0
  246. package/src/location-services.ts +125 -0
  247. package/src/location.ts +44 -0
  248. package/src/machine/driver.ts +487 -0
  249. package/src/machine/frames.ts +133 -0
  250. package/src/machine/identity.ts +187 -0
  251. package/src/machine/index.ts +4 -0
  252. package/src/machine/instructions.ts +61 -0
  253. package/src/machine/iroh-binding.ts +18 -0
  254. package/src/machine/iroh.ts +157 -0
  255. package/src/machine/join.ts +54 -0
  256. package/src/machine/link.ts +313 -0
  257. package/src/machine/machines.ts +280 -0
  258. package/src/machine/noise.ts +326 -0
  259. package/src/machine/sql.ts +13 -0
  260. package/src/machine/wire.ts +140 -0
  261. package/src/machine/worker-client.ts +276 -0
  262. package/src/managed-policy.ts +65 -0
  263. package/src/markdown.d.ts +4 -0
  264. package/src/mcp/client.ts +1198 -0
  265. package/src/mcp/connection.ts +292 -0
  266. package/src/mcp/event-stream.ts +34 -0
  267. package/src/mcp/index.ts +1349 -0
  268. package/src/mcp/instructions.ts +108 -0
  269. package/src/mcp/oauth.ts +665 -0
  270. package/src/mcp/pool.ts +386 -0
  271. package/src/mcp/socket-client.ts +86 -0
  272. package/src/mcp/stdio.ts +227 -0
  273. package/src/mime.ts +75 -0
  274. package/src/modal/models.ts +150 -0
  275. package/src/model-resolver.ts +639 -0
  276. package/src/model-retry.ts +134 -0
  277. package/src/model.ts +373 -0
  278. package/src/models-dev/snapshot.txt +1 -0
  279. package/src/models-dev/v1.ts +203 -0
  280. package/src/models-dev.ts +899 -0
  281. package/src/node-ffi.d.ts +18 -0
  282. package/src/oauth/page.ts +260 -0
  283. package/src/oauth/redirect.ts +42 -0
  284. package/src/pentest/mcp-catalog.ts +144 -0
  285. package/src/permission/policy.ts +240 -0
  286. package/src/permission/saved.ts +140 -0
  287. package/src/permission/sql.ts +20 -0
  288. package/src/permission.ts +419 -0
  289. package/src/persistent-pty/binary.bun.ts +85 -0
  290. package/src/persistent-pty/binary.node.ts +5 -0
  291. package/src/persistent-pty/binary.workerd.ts +5 -0
  292. package/src/persistent-pty/daemon.ts +750 -0
  293. package/src/persistent-pty/index.ts +661 -0
  294. package/src/persistent-pty/pty-binding.ts +6 -0
  295. package/src/persistent-pty.ts +1 -0
  296. package/src/plugin/agent.ts +235 -0
  297. package/src/plugin/command/automation.txt +7 -0
  298. package/src/plugin/command/initialize.txt +65 -0
  299. package/src/plugin/command/review.txt +100 -0
  300. package/src/plugin/command.ts +113 -0
  301. package/src/plugin/fork-notice.ts +30 -0
  302. package/src/plugin/goal/continuation.txt +13 -0
  303. package/src/plugin/goal/judge.txt +20 -0
  304. package/src/plugin/goal/kickoff.txt +13 -0
  305. package/src/plugin/goal/reminder.txt +9 -0
  306. package/src/plugin/goal.ts +501 -0
  307. package/src/plugin/home-memory.ts +155 -0
  308. package/src/plugin/hooks.ts +108 -0
  309. package/src/plugin/host.ts +770 -0
  310. package/src/plugin/identity.ts +31 -0
  311. package/src/plugin/instance.ts +45 -0
  312. package/src/plugin/internal.ts +360 -0
  313. package/src/plugin/mcp-codemode-defaults.ts +41 -0
  314. package/src/plugin/mcp-skill.ts +171 -0
  315. package/src/plugin/models-dev.ts +128 -0
  316. package/src/plugin/module.ts +186 -0
  317. package/src/plugin/optimize.ts +97 -0
  318. package/src/plugin/plan.ts +52 -0
  319. package/src/plugin/promise.ts +3 -0
  320. package/src/plugin/provider/amazon-bedrock.ts +121 -0
  321. package/src/plugin/provider/azure.ts +568 -0
  322. package/src/plugin/provider/cerebras.ts +16 -0
  323. package/src/plugin/provider/chatgpt.ts +594 -0
  324. package/src/plugin/provider/claude-agent/aisdk.ts +36 -0
  325. package/src/plugin/provider/claude-agent/claude/accounts.ts +104 -0
  326. package/src/plugin/provider/claude-agent/claude/agent-sdk.ts +1 -0
  327. package/src/plugin/provider/claude-agent/claude/agent-sdk.workerd.ts +4 -0
  328. package/src/plugin/provider/claude-agent/claude/claude-folder-worker.ts +10 -0
  329. package/src/plugin/provider/claude-agent/claude/fork.ts +34 -0
  330. package/src/plugin/provider/claude-agent/claude/io.ts +88 -0
  331. package/src/plugin/provider/claude-agent/claude/probe.ts +124 -0
  332. package/src/plugin/provider/claude-agent/claude/query-options.ts +143 -0
  333. package/src/plugin/provider/claude-agent/claude/sdk.ts +17 -0
  334. package/src/plugin/provider/claude-agent/claude/session.ts +162 -0
  335. package/src/plugin/provider/claude-agent/claude/sessions.ts +508 -0
  336. package/src/plugin/provider/claude-agent/claude/status.ts +66 -0
  337. package/src/plugin/provider/claude-agent/claude/websearch.ts +96 -0
  338. package/src/plugin/provider/claude-agent/index.ts +63 -0
  339. package/src/plugin/provider/claude-agent/instructions.ts +54 -0
  340. package/src/plugin/provider/claude-agent/integration.ts +62 -0
  341. package/src/plugin/provider/claude-agent/language-model/claude-agent-error.ts +49 -0
  342. package/src/plugin/provider/claude-agent/language-model/claude-agent-language-model.ts +112 -0
  343. package/src/plugin/provider/claude-agent/language-model/convert-claude-stream.ts +139 -0
  344. package/src/plugin/provider/claude-agent/language-model/convert-to-claude-message.ts +55 -0
  345. package/src/plugin/provider/claude-agent/language-model/request-kind.ts +5 -0
  346. package/src/plugin/provider/claude-agent/language-model/system-prompt.ts +28 -0
  347. package/src/plugin/provider/claude-agent/language-model/usage.ts +58 -0
  348. package/src/plugin/provider/claude-agent/provider.ts +178 -0
  349. package/src/plugin/provider/claude-agent/session.ts +61 -0
  350. package/src/plugin/provider/claude-agent/sync/catch-up.ts +21 -0
  351. package/src/plugin/provider/claude-agent/sync/checkpoints.ts +41 -0
  352. package/src/plugin/provider/claude-agent/sync/decide.ts +58 -0
  353. package/src/plugin/provider/claude-agent/sync/fingerprint.ts +117 -0
  354. package/src/plugin/provider/claude-agent/sync/record.ts +42 -0
  355. package/src/plugin/provider/claude-agent/tools/hooks.ts +23 -0
  356. package/src/plugin/provider/claude-agent/tools/names.ts +30 -0
  357. package/src/plugin/provider/claude-agent/tools/pending.ts +72 -0
  358. package/src/plugin/provider/claude-agent/tools/result.ts +110 -0
  359. package/src/plugin/provider/claude-agent/tools/server.ts +34 -0
  360. package/src/plugin/provider/claude-agent/websearch.ts +57 -0
  361. package/src/plugin/provider/cloudflare-ai-gateway.ts +68 -0
  362. package/src/plugin/provider/cloudflare-workers-ai.ts +70 -0
  363. package/src/plugin/provider/configured.ts +18 -0
  364. package/src/plugin/provider/credential-settings.ts +77 -0
  365. package/src/plugin/provider/databricks.ts +31 -0
  366. package/src/plugin/provider/digitalocean.ts +197 -0
  367. package/src/plugin/provider/dynamic.ts +19 -0
  368. package/src/plugin/provider/github-copilot.ts +646 -0
  369. package/src/plugin/provider/gitlab.ts +496 -0
  370. package/src/plugin/provider/google-vertex.ts +231 -0
  371. package/src/plugin/provider/kilo.ts +17 -0
  372. package/src/plugin/provider/llmgateway.ts +27 -0
  373. package/src/plugin/provider/lmstudio.ts +52 -0
  374. package/src/plugin/provider/local.ts +240 -0
  375. package/src/plugin/provider/modal.ts +72 -0
  376. package/src/plugin/provider/neon.ts +12 -0
  377. package/src/plugin/provider/nvidia.ts +22 -0
  378. package/src/plugin/provider/ollama.ts +92 -0
  379. package/src/plugin/provider/openai-context-caps.ts +52 -0
  380. package/src/plugin/provider/openai-subscription-models.ts +59 -0
  381. package/src/plugin/provider/openai.ts +447 -0
  382. package/src/plugin/provider/opencode-artifacts.ts +216 -0
  383. package/src/plugin/provider/opencode-watches.ts +753 -0
  384. package/src/plugin/provider/opencode.ts +883 -0
  385. package/src/plugin/provider/openrouter.ts +30 -0
  386. package/src/plugin/provider/poe.ts +176 -0
  387. package/src/plugin/provider/prompt-cache-key.ts +37 -0
  388. package/src/plugin/provider/refresh.ts +80 -0
  389. package/src/plugin/provider/sap-ai-core.ts +39 -0
  390. package/src/plugin/provider/sdk-factory.ts +24 -0
  391. package/src/plugin/provider/snowflake-cortex.ts +266 -0
  392. package/src/plugin/provider/vllm.ts +34 -0
  393. package/src/plugin/provider/xai.ts +236 -0
  394. package/src/plugin/provider/zenmux.ts +21 -0
  395. package/src/plugin/provider.ts +64 -0
  396. package/src/plugin/sdk.ts +44 -0
  397. package/src/plugin/service.ts +42 -0
  398. package/src/plugin/skill/opencode/api/agent.md +18 -0
  399. package/src/plugin/skill/opencode/api/automation.md +63 -0
  400. package/src/plugin/skill/opencode/api/blob.md +10 -0
  401. package/src/plugin/skill/opencode/api/command.md +12 -0
  402. package/src/plugin/skill/opencode/api/form.md +22 -0
  403. package/src/plugin/skill/opencode/api/generate.md +96 -0
  404. package/src/plugin/skill/opencode/api/info.md +11 -0
  405. package/src/plugin/skill/opencode/api/location.md +17 -0
  406. package/src/plugin/skill/opencode/api/model.md +22 -0
  407. package/src/plugin/skill/opencode/api/permission.md +13 -0
  408. package/src/plugin/skill/opencode/api/project.md +29 -0
  409. package/src/plugin/skill/opencode/api/provider.md +18 -0
  410. package/src/plugin/skill/opencode/api/session.md +313 -0
  411. package/src/plugin/skill/opencode/api/skill.md +12 -0
  412. package/src/plugin/skill/opencode/api/vcs.md +60 -0
  413. package/src/plugin/skill/opencode/api/worktree.md +49 -0
  414. package/src/plugin/skill/opencode/api.md +119 -0
  415. package/src/plugin/skill/opencode/api.ts +40 -0
  416. package/src/plugin/skill/opencode-api.md +17 -0
  417. package/src/plugin/skill/opencode.md +154 -0
  418. package/src/plugin/skill/report.md +152 -0
  419. package/src/plugin/skill.ts +111 -0
  420. package/src/plugin/source-directory.ts +33 -0
  421. package/src/plugin/supervisor.ts +288 -0
  422. package/src/plugin/system-prompt/AGENTS.md +5 -0
  423. package/src/plugin/system-prompt/anthropic.txt +2 -0
  424. package/src/plugin/system-prompt/gpt-6.2.txt +71 -0
  425. package/src/plugin/system-prompt/gpt-astra.txt +46 -0
  426. package/src/plugin/system-prompt/gpt.txt +40 -0
  427. package/src/plugin/system-prompt/kimi.txt +96 -0
  428. package/src/plugin/system-prompt/meta.txt +56 -0
  429. package/src/plugin/system-prompt/trinity.txt +98 -0
  430. package/src/plugin/tool-input-repair.ts +232 -0
  431. package/src/plugin/update.ts +87 -0
  432. package/src/plugin/vcs/git.ts +802 -0
  433. package/src/plugin/vcs/hg.ts +234 -0
  434. package/src/plugin/verbosity.ts +58 -0
  435. package/src/plugin/warming.ts +224 -0
  436. package/src/plugin/websearch/exa.ts +69 -0
  437. package/src/plugin/websearch/firecrawl.ts +71 -0
  438. package/src/plugin/websearch/index.ts +13 -0
  439. package/src/plugin/websearch/mcp.ts +69 -0
  440. package/src/plugin/websearch/parallel.ts +90 -0
  441. package/src/plugin/websearch/provider.ts +44 -0
  442. package/src/plugin/websearch/tavily.ts +73 -0
  443. package/src/plugin/websearch/tinyfish.ts +131 -0
  444. package/src/plugin.ts +320 -0
  445. package/src/project/icon.ts +167 -0
  446. package/src/project/schema.ts +25 -0
  447. package/src/project/sql.ts +63 -0
  448. package/src/project.ts +536 -0
  449. package/src/provider.ts +553 -0
  450. package/src/pty/protocol.ts +37 -0
  451. package/src/pty/pty.bun.ts +44 -0
  452. package/src/pty/pty.node.ts +34 -0
  453. package/src/pty/pty.ts +25 -0
  454. package/src/pty/pty.workerd.ts +9 -0
  455. package/src/pty/ticket.ts +74 -0
  456. package/src/pty.ts +311 -0
  457. package/src/push/crypto.ts +39 -0
  458. package/src/push/list.ts +380 -0
  459. package/src/push/sender.ts +185 -0
  460. package/src/push/watcher.ts +169 -0
  461. package/src/reference/instructions.ts +82 -0
  462. package/src/reference.ts +129 -0
  463. package/src/repository-cache.ts +251 -0
  464. package/src/repository.ts +205 -0
  465. package/src/ripgrep/binary.ts +166 -0
  466. package/src/ripgrep.ts +311 -0
  467. package/src/rpc.ts +288 -0
  468. package/src/schema.ts +39 -0
  469. package/src/session/affinity.ts +8 -0
  470. package/src/session/background-result.ts +5 -0
  471. package/src/session/background.ts +125 -0
  472. package/src/session/blob.ts +503 -0
  473. package/src/session/command.ts +38 -0
  474. package/src/session/compaction-background.ts +55 -0
  475. package/src/session/compaction-subagents.ts +103 -0
  476. package/src/session/compaction.ts +1320 -0
  477. package/src/session/context.ts +296 -0
  478. package/src/session/cwd-instructions.ts +147 -0
  479. package/src/session/cwd-store.ts +66 -0
  480. package/src/session/cwd.ts +75 -0
  481. package/src/session/diff.ts +149 -0
  482. package/src/session/environment.ts +33 -0
  483. package/src/session/error.ts +105 -0
  484. package/src/session/event.ts +2 -0
  485. package/src/session/execution/restart.ts +558 -0
  486. package/src/session/execution/subagent-report.ts +203 -0
  487. package/src/session/execution.ts +241 -0
  488. package/src/session/generate.ts +78 -0
  489. package/src/session/history.ts +405 -0
  490. package/src/session/inbox.ts +625 -0
  491. package/src/session/info.ts +62 -0
  492. package/src/session/instruction-entry.ts +171 -0
  493. package/src/session/instruction-state.ts +277 -0
  494. package/src/session/instructions.ts +126 -0
  495. package/src/session/message-updater.ts +497 -0
  496. package/src/session/message.ts +2 -0
  497. package/src/session/model-request.ts +474 -0
  498. package/src/session/model-transport.ts +571 -0
  499. package/src/session/move.ts +199 -0
  500. package/src/session/projector.ts +1197 -0
  501. package/src/session/prompt.ts +253 -0
  502. package/src/session/recent-text.ts +93 -0
  503. package/src/session/revert.ts +112 -0
  504. package/src/session/run-coordinator.ts +198 -0
  505. package/src/session/runner/index.ts +46 -0
  506. package/src/session/runner/live-tool-metadata.ts +41 -0
  507. package/src/session/runner/llm.ts +481 -0
  508. package/src/session/runner/max-steps.ts +16 -0
  509. package/src/session/runner/model.ts +138 -0
  510. package/src/session/runner/prompt/system.txt +16 -0
  511. package/src/session/runner/publish-llm-event.ts +642 -0
  512. package/src/session/runner/retry.ts +78 -0
  513. package/src/session/runner/step.ts +401 -0
  514. package/src/session/runner/to-llm-message.ts +341 -0
  515. package/src/session/schema.ts +9 -0
  516. package/src/session/search-build.ts +116 -0
  517. package/src/session/search-index.ts +552 -0
  518. package/src/session/search.ts +672 -0
  519. package/src/session/session.ts +407 -0
  520. package/src/session/shell.ts +35 -0
  521. package/src/session/skill.ts +16 -0
  522. package/src/session/sql.ts +215 -0
  523. package/src/session/stats.ts +463 -0
  524. package/src/session/store.ts +323 -0
  525. package/src/session/stored.ts +44 -0
  526. package/src/session/subagent-completion.ts +95 -0
  527. package/src/session/subagent-depth.ts +21 -0
  528. package/src/session/subagent-job.ts +61 -0
  529. package/src/session/synthetic.ts +49 -0
  530. package/src/session/system-prompt.ts +28 -0
  531. package/src/session/title.ts +174 -0
  532. package/src/session/to-session-error.ts +179 -0
  533. package/src/session/transfer.ts +369 -0
  534. package/src/session/usage.ts +64 -0
  535. package/src/session.ts +602 -0
  536. package/src/shared-cache.ts +103 -0
  537. package/src/shell/parse.ts +645 -0
  538. package/src/shell/permissions.ts +60 -0
  539. package/src/shell/result.ts +115 -0
  540. package/src/shell/scan.ts +2585 -0
  541. package/src/shell/select.ts +241 -0
  542. package/src/shell.ts +1274 -0
  543. package/src/skill/discovery.ts +205 -0
  544. package/src/skill/instructions.ts +84 -0
  545. package/src/skill.ts +277 -0
  546. package/src/snapshot.ts +248 -0
  547. package/src/state.ts +271 -0
  548. package/src/tool/AGENTS.md +71 -0
  549. package/src/tool/html-markdown.ts +651 -0
  550. package/src/tool/http-body.ts +30 -0
  551. package/src/tool/mcp.ts +177 -0
  552. package/src/tool/model-policy.ts +38 -0
  553. package/src/tool/patch-grammar.txt +19 -0
  554. package/src/tool/patch.txt +33 -0
  555. package/src/tool/plugin/artifact.ts +171 -0
  556. package/src/tool/plugin/automation.ts +246 -0
  557. package/src/tool/plugin/cd.ts +103 -0
  558. package/src/tool/plugin/edit.ts +371 -0
  559. package/src/tool/plugin/file-diff.ts +42 -0
  560. package/src/tool/plugin/glob.ts +123 -0
  561. package/src/tool/plugin/grep.ts +152 -0
  562. package/src/tool/plugin/image-generate.ts +396 -0
  563. package/src/tool/plugin/machine.ts +36 -0
  564. package/src/tool/plugin/mcp-events.ts +72 -0
  565. package/src/tool/plugin/mcp-resource.ts +100 -0
  566. package/src/tool/plugin/opencode.ts +316 -0
  567. package/src/tool/plugin/patch.ts +358 -0
  568. package/src/tool/plugin/question.ts +130 -0
  569. package/src/tool/plugin/read.ts +413 -0
  570. package/src/tool/plugin/session-interrupt.ts +63 -0
  571. package/src/tool/plugin/session-search.ts +99 -0
  572. package/src/tool/plugin/shell.ts +594 -0
  573. package/src/tool/plugin/skill.ts +74 -0
  574. package/src/tool/plugin/subagent.ts +269 -0
  575. package/src/tool/plugin/todo.ts +83 -0
  576. package/src/tool/plugin/video-generate.ts +403 -0
  577. package/src/tool/plugin/webfetch.ts +214 -0
  578. package/src/tool/plugin/websearch.ts +196 -0
  579. package/src/tool/plugin/write.ts +72 -0
  580. package/src/tool/read-filesystem.ts +350 -0
  581. package/src/tool/runtime.ts +311 -0
  582. package/src/tool/search.ts +34 -0
  583. package/src/tool/todowrite.txt +7 -0
  584. package/src/tool-output.ts +220 -0
  585. package/src/tool.ts +579 -0
  586. package/src/usage-limits.ts +192 -0
  587. package/src/util/canonical-json.ts +11 -0
  588. package/src/util/error-summary.ts +33 -0
  589. package/src/util/git-executable.ts +59 -0
  590. package/src/util/lazy.ts +11 -0
  591. package/src/util/slug.ts +74 -0
  592. package/src/util/token.ts +5 -0
  593. package/src/util/which.ts +37 -0
  594. package/src/util/wildcard.ts +15 -0
  595. package/src/v1/config/agent.ts +69 -0
  596. package/src/v1/config/command.ts +13 -0
  597. package/src/v1/config/mcp.ts +69 -0
  598. package/src/v1/config/migrate.ts +269 -0
  599. package/src/v1/config/permission.ts +42 -0
  600. package/src/v1/config/plugin.ts +9 -0
  601. package/src/v1/config/provider-options.ts +59 -0
  602. package/src/v1/config/provider.ts +113 -0
  603. package/src/variant.ts +699 -0
  604. package/src/vcs/patch.ts +106 -0
  605. package/src/vcs.ts +262 -0
  606. package/src/video-generation.ts +344 -0
  607. package/src/voice.ts +194 -0
  608. package/src/websearch.ts +239 -0
  609. package/src/wellknown/plugin.ts +36 -0
  610. package/src/wellknown.ts +230 -0
  611. package/src/workspace/driver.ts +89 -0
  612. package/src/workspace/sql.ts +11 -0
  613. package/src/workspace.ts +566 -0
  614. package/src/worktree/directory.ts +16 -0
  615. package/src/worktree/git.ts +39 -0
  616. package/src/worktree/sql.ts +21 -0
  617. package/src/worktree/strategies.ts +74 -0
  618. package/src/worktree.ts +357 -0
  619. package/test/agent.test.ts +224 -0
  620. package/test/aisdk-native.test.ts +590 -0
  621. package/test/aisdk.test.ts +1259 -0
  622. package/test/app.test.ts +6 -0
  623. package/test/artifact.test.ts +216 -0
  624. package/test/automation-event.test.ts +688 -0
  625. package/test/automation-shell.test.ts +293 -0
  626. package/test/automation.test.ts +1950 -0
  627. package/test/blob-store.test.ts +37 -0
  628. package/test/boot-work.test.ts +215 -0
  629. package/test/browser-attach.test.ts +150 -0
  630. package/test/browser-idle.test.ts +107 -0
  631. package/test/bus-session-routing.test.ts +334 -0
  632. package/test/bus-unpersisted.test.ts +50 -0
  633. package/test/bus.test.ts +1347 -0
  634. package/test/catalog.test.ts +704 -0
  635. package/test/codemode/catalog.test.ts +339 -0
  636. package/test/codemode/diffs.test.ts +90 -0
  637. package/test/codemode/instructions.test.ts +123 -0
  638. package/test/codemode-execute-options.test.ts +172 -0
  639. package/test/codemode-script-diffs.test.ts +131 -0
  640. package/test/codemode.test.ts +132 -0
  641. package/test/command.test.ts +71 -0
  642. package/test/config/agent.test.ts +847 -0
  643. package/test/config/command-subagent.test.ts +165 -0
  644. package/test/config/command.test.ts +628 -0
  645. package/test/config/compaction.test.ts +184 -0
  646. package/test/config/config.test.ts +2113 -0
  647. package/test/config/discovery.test.ts +150 -0
  648. package/test/config/entry-observer.test.ts +51 -0
  649. package/test/config/fixture/skills/first-source/first/SKILL.md +6 -0
  650. package/test/config/fixture/skills/second-source/second/SKILL.md +6 -0
  651. package/test/config/image.test.ts +78 -0
  652. package/test/config/markdown.test.ts +129 -0
  653. package/test/config/model.test.ts +28 -0
  654. package/test/config/normalization.test.ts +854 -0
  655. package/test/config/overlay.test.ts +205 -0
  656. package/test/config/policy.test.ts +432 -0
  657. package/test/config/provider-options.test.ts +55 -0
  658. package/test/config/provider.test.ts +1338 -0
  659. package/test/config/reload.test.ts +526 -0
  660. package/test/config/session-search.test.ts +61 -0
  661. package/test/config/shell.test.ts +42 -0
  662. package/test/config/skill.test.ts +602 -0
  663. package/test/config/snapshot.test.ts +61 -0
  664. package/test/config/tool-output.test.ts +59 -0
  665. package/test/config/watch.test.ts +53 -0
  666. package/test/config/websearch.test.ts +45 -0
  667. package/test/credential-refresh.test.ts +113 -0
  668. package/test/credential.test.ts +271 -0
  669. package/test/database-drizzle.test.ts +228 -0
  670. package/test/database-migration.test.ts +783 -0
  671. package/test/database.test.ts +39 -0
  672. package/test/effect/cross-spawn-spawner.test.ts +522 -0
  673. package/test/effect/keyed-mutex.test.ts +73 -0
  674. package/test/effect/layer-node/layer-node-types.test.ts +230 -0
  675. package/test/effect/layer-node/layer-node.test.ts +467 -0
  676. package/test/effect/layer-node/node-build.test.ts +148 -0
  677. package/test/effect/observability.test.ts +141 -0
  678. package/test/effect-app-node-platform.test.ts +86 -0
  679. package/test/effect-simplification-types.test.ts +12 -0
  680. package/test/environment.test.ts +154 -0
  681. package/test/environments.test.ts +406 -0
  682. package/test/event-logger.test.ts +50 -0
  683. package/test/file-access-path.test.ts +336 -0
  684. package/test/file-access.test.ts +178 -0
  685. package/test/file-mutation.test.ts +244 -0
  686. package/test/filesystem/file-watch.test.ts +213 -0
  687. package/test/filesystem/filesystem.test.ts +383 -0
  688. package/test/filesystem/location-watcher-policy.test.ts +70 -0
  689. package/test/filesystem/search.test.ts +385 -0
  690. package/test/filesystem/watcher.test.ts +719 -0
  691. package/test/fixture/app-execution-alias.ts +17 -0
  692. package/test/fixture/codemode.ts +63 -0
  693. package/test/fixture/config-nodes.ts +40 -0
  694. package/test/fixture/durable-object-storage.ts +58 -0
  695. package/test/fixture/effect-flock-worker.ts +60 -0
  696. package/test/fixture/env.ts +22 -0
  697. package/test/fixture/environment.ts +52 -0
  698. package/test/fixture/event-server.ts +65 -0
  699. package/test/fixture/flock-worker.ts +72 -0
  700. package/test/fixture/git.ts +86 -0
  701. package/test/fixture/global.ts +26 -0
  702. package/test/fixture/held-stdio.cjs +36 -0
  703. package/test/fixture/html-markdown.ts +7 -0
  704. package/test/fixture/link-v1-transcript.json +27 -0
  705. package/test/fixture/location.ts +27 -0
  706. package/test/fixture/lock-worker.ts +53 -0
  707. package/test/fixture/machine-v2.json +66 -0
  708. package/test/fixture/machine-worker.ts +284 -0
  709. package/test/fixture/mcp-echo.ts +14 -0
  710. package/test/fixture/mcp-legacy-silent.ts +22 -0
  711. package/test/fixture/mcp-modern-stdio.ts +15 -0
  712. package/test/fixture/mcp-output-schema.ts +63 -0
  713. package/test/fixture/mcp-prompts.ts +29 -0
  714. package/test/fixture/mcp-timeout.ts +32 -0
  715. package/test/fixture/mcp-union-output-schema.ts +41 -0
  716. package/test/fixture/mcp.ts +44 -0
  717. package/test/fixture/models.ts +6 -0
  718. package/test/fixture/native/2.0.14-media.json +22 -0
  719. package/test/fixture/noise-xx-vectors.json +75 -0
  720. package/test/fixture/persistent-pty-daemon.ts +347 -0
  721. package/test/fixture/persistent-pty.ts +9 -0
  722. package/test/fixture/photon-crash-worker.ts +10 -0
  723. package/test/fixture/photon-exit.ts +29 -0
  724. package/test/fixture/photon-hang-worker.ts +2 -0
  725. package/test/fixture/policy.ts +98 -0
  726. package/test/fixture/prompt-location.ts +33 -0
  727. package/test/fixture/pty-windows.ts +69 -0
  728. package/test/fixture/selector.ts +12 -0
  729. package/test/fixture/shell-daemon.ts +122 -0
  730. package/test/fixture/spawn.ts +24 -0
  731. package/test/fixture/sqlite-node-client.ts +100 -0
  732. package/test/fixture/target-environment.ts +58 -0
  733. package/test/fixture/tmpdir.ts +44 -0
  734. package/test/fixture/v1-config/attachment.ts +25 -0
  735. package/test/fixture/v1-config/config.ts +182 -0
  736. package/test/fixture/v1-config/formatter.ts +13 -0
  737. package/test/fixture/v1-config/layout.ts +6 -0
  738. package/test/fixture/v1-config/lsp.ts +80 -0
  739. package/test/fixture/v1-config/server.ts +19 -0
  740. package/test/fixture/v1-config/skills.ts +13 -0
  741. package/test/fixtures/recordings/session-runner/openai-chat-streams-text.json +27 -0
  742. package/test/flag.test.ts +203 -0
  743. package/test/form.test.ts +357 -0
  744. package/test/formatter-target-environment.test.ts +138 -0
  745. package/test/formatter.test.ts +350 -0
  746. package/test/generate.test.ts +752 -0
  747. package/test/git.test.ts +666 -0
  748. package/test/github-copilot/models.test.ts +167 -0
  749. package/test/image-photon.test.ts +177 -0
  750. package/test/instance-vanilla.test.ts +124 -0
  751. package/test/instruction-discovery.test.ts +804 -0
  752. package/test/instruction-state.test.ts +537 -0
  753. package/test/instructions/builtins.test.ts +83 -0
  754. package/test/instructions/index.test.ts +248 -0
  755. package/test/integration-refresh.test.ts +118 -0
  756. package/test/integration.test.ts +716 -0
  757. package/test/job.test.ts +968 -0
  758. package/test/kv.test.ts +81 -0
  759. package/test/lib/clock.ts +43 -0
  760. package/test/lib/effect.ts +80 -0
  761. package/test/lib/environment-conformance.ts +204 -0
  762. package/test/lib/eventually.ts +20 -0
  763. package/test/lib/image.ts +7 -0
  764. package/test/lib/instructions.ts +47 -0
  765. package/test/lib/permission.ts +12 -0
  766. package/test/lib/project.ts +26 -0
  767. package/test/lib/session-message.ts +26 -0
  768. package/test/lib/tool.ts +102 -0
  769. package/test/lib/websearch.ts +63 -0
  770. package/test/lib/websocket-server.ts +73 -0
  771. package/test/location-activity.test.ts +315 -0
  772. package/test/location-filesystem.test.ts +332 -0
  773. package/test/location-layer.test.ts +784 -0
  774. package/test/location-missing-project.test.ts +71 -0
  775. package/test/location-retain.test.ts +98 -0
  776. package/test/location.test.ts +46 -0
  777. package/test/logging.test.ts +14 -0
  778. package/test/machine-frames.test.ts +768 -0
  779. package/test/machine-instructions.test.ts +135 -0
  780. package/test/machine-join.test.ts +223 -0
  781. package/test/machine-link.test.ts +527 -0
  782. package/test/machine-noise.test.ts +429 -0
  783. package/test/machine-path.test.ts +1202 -0
  784. package/test/machine.test.ts +786 -0
  785. package/test/machines.test.ts +730 -0
  786. package/test/mcp-attach.test.ts +403 -0
  787. package/test/mcp-events.test.ts +299 -0
  788. package/test/mcp-import-boundary.test.ts +44 -0
  789. package/test/mcp-instructions.test.ts +221 -0
  790. package/test/mcp-oauth.test.ts +1289 -0
  791. package/test/mcp-skills.test.ts +274 -0
  792. package/test/mcp-socket-client.test.ts +210 -0
  793. package/test/mcp-stdio.test.ts +145 -0
  794. package/test/mcp.test.ts +4196 -0
  795. package/test/mime.test.ts +80 -0
  796. package/test/modal/models.test.ts +137 -0
  797. package/test/model-free.test.ts +120 -0
  798. package/test/model-plugins.test.ts +469 -0
  799. package/test/model-resolver.test.ts +1695 -0
  800. package/test/model.test.ts +16 -0
  801. package/test/models.test.ts +1404 -0
  802. package/test/network-guard.test.ts +56 -0
  803. package/test/npm-config.test.ts +42 -0
  804. package/test/npm.test.ts +545 -0
  805. package/test/oauth-page.test.ts +15 -0
  806. package/test/opencode-api-skill.test.ts +16 -0
  807. package/test/patch.test.ts +509 -0
  808. package/test/permission.test.ts +1179 -0
  809. package/test/persistent-pty-daemon.test.ts +337 -0
  810. package/test/persistent-pty-session.test.ts +295 -0
  811. package/test/plugin/automation.test.ts +124 -0
  812. package/test/plugin/command.test.ts +137 -0
  813. package/test/plugin/fixture.ts +174 -0
  814. package/test/plugin/fixtures/greeting.ts +14 -0
  815. package/test/plugin/fixtures/models-dev-reasoning.json +811 -0
  816. package/test/plugin/fixtures/models-dev.json +92 -0
  817. package/test/plugin/fixtures/provider-factory.ts +9 -0
  818. package/test/plugin/goal-watchdog.test.ts +212 -0
  819. package/test/plugin/goal.test.ts +609 -0
  820. package/test/plugin/home-memory.test.ts +131 -0
  821. package/test/plugin/host-model.test.ts +34 -0
  822. package/test/plugin/host.ts +540 -0
  823. package/test/plugin/identity.test.ts +60 -0
  824. package/test/plugin/internal-flag.test.ts +101 -0
  825. package/test/plugin/mcp-codemode-defaults.test.ts +124 -0
  826. package/test/plugin/models-dev.test.ts +1406 -0
  827. package/test/plugin/module.test.ts +494 -0
  828. package/test/plugin/optimize.test.ts +343 -0
  829. package/test/plugin/permission-assert.test.ts +94 -0
  830. package/test/plugin/plan.test.ts +162 -0
  831. package/test/plugin/promise-tool-cancel.test.ts +279 -0
  832. package/test/plugin/promise-tool.test.ts +227 -0
  833. package/test/plugin/provider/claude-agent/claude/accounts.test.ts +326 -0
  834. package/test/plugin/provider/claude-agent/claude/branches.test.ts +300 -0
  835. package/test/plugin/provider/claude-agent/claude/probe.test.ts +99 -0
  836. package/test/plugin/provider/claude-agent/claude/recorder.test.ts +19 -0
  837. package/test/plugin/provider/claude-agent/claude/session.test.ts +30 -0
  838. package/test/plugin/provider/claude-agent/claude/sessions.test.ts +490 -0
  839. package/test/plugin/provider/claude-agent/claude/status.test.ts +67 -0
  840. package/test/plugin/provider/claude-agent/claude/sync.test.ts +70 -0
  841. package/test/plugin/provider/claude-agent/claude/tools.test.ts +382 -0
  842. package/test/plugin/provider/claude-agent/fixtures/marker.pdf +68 -0
  843. package/test/plugin/provider/claude-agent/fixtures/recordings/api-error.jsonl +16 -0
  844. package/test/plugin/provider/claude-agent/fixtures/recordings/controls.jsonl +107 -0
  845. package/test/plugin/provider/claude-agent/fixtures/recordings/max-steps.jsonl +133 -0
  846. package/test/plugin/provider/claude-agent/fixtures/recordings/startup-logged-out.jsonl +4 -0
  847. package/test/plugin/provider/claude-agent/fixtures/recordings/startup.jsonl +52 -0
  848. package/test/plugin/provider/claude-agent/fixtures/recordings/sync.jsonl +73 -0
  849. package/test/plugin/provider/claude-agent/fixtures/recordings/text-cancel.jsonl +37 -0
  850. package/test/plugin/provider/claude-agent/fixtures/recordings/text-resume.jsonl +21 -0
  851. package/test/plugin/provider/claude-agent/fixtures/recordings/text.jsonl +35 -0
  852. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-abort.jsonl +62 -0
  853. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-cancel.jsonl +63 -0
  854. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-continue.jsonl +58 -0
  855. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-media.jsonl +80 -0
  856. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-waiting-cancel.jsonl +58 -0
  857. package/test/plugin/provider/claude-agent/fixtures/recordings/tools.jsonl +74 -0
  858. package/test/plugin/provider/claude-agent/fixtures/recordings/utility.jsonl +28 -0
  859. package/test/plugin/provider/claude-agent/fixtures/recordings/websearch.jsonl +13 -0
  860. package/test/plugin/provider/claude-agent/fixtures/red.png +0 -0
  861. package/test/plugin/provider/claude-agent/language-model/convert.test.ts +95 -0
  862. package/test/plugin/provider/claude-agent/language-model/error.test.ts +94 -0
  863. package/test/plugin/provider/claude-agent/lib/fake-claude.ts +411 -0
  864. package/test/plugin/provider/claude-agent/lib/fake-io.ts +20 -0
  865. package/test/plugin/provider/claude-agent/lib/recorder.ts +61 -0
  866. package/test/plugin/provider/claude-agent/lib/sessions.ts +126 -0
  867. package/test/plugin/provider/claude-agent/lib/tools.ts +95 -0
  868. package/test/plugin/provider/claude-agent/plugin.test.ts +651 -0
  869. package/test/plugin/provider/claude-agent/sync/sync.test.ts +213 -0
  870. package/test/plugin/provider/claude-agent/tools/tools.test.ts +85 -0
  871. package/test/plugin/provider/claude-agent/websearch.test.ts +106 -0
  872. package/test/plugin/provider-amazon-bedrock.test.ts +225 -0
  873. package/test/plugin/provider-azure.test.ts +793 -0
  874. package/test/plugin/provider-cerebras.test.ts +62 -0
  875. package/test/plugin/provider-chatgpt.test.ts +1278 -0
  876. package/test/plugin/provider-cloudflare-ai-gateway.test.ts +160 -0
  877. package/test/plugin/provider-cloudflare-workers-ai.test.ts +158 -0
  878. package/test/plugin/provider-databricks.test.ts +45 -0
  879. package/test/plugin/provider-digitalocean.test.ts +322 -0
  880. package/test/plugin/provider-dynamic.test.ts +179 -0
  881. package/test/plugin/provider-github-copilot.test.ts +806 -0
  882. package/test/plugin/provider-gitlab-oauth.test.ts +407 -0
  883. package/test/plugin/provider-gitlab.test.ts +546 -0
  884. package/test/plugin/provider-google-vertex.test.ts +288 -0
  885. package/test/plugin/provider-kilo.test.ts +66 -0
  886. package/test/plugin/provider-llmgateway.test.ts +72 -0
  887. package/test/plugin/provider-lmstudio.test.ts +487 -0
  888. package/test/plugin/provider-nvidia.test.ts +84 -0
  889. package/test/plugin/provider-ollama.test.ts +312 -0
  890. package/test/plugin/provider-openai-context-caps.test.ts +80 -0
  891. package/test/plugin/provider-openai.test.ts +447 -0
  892. package/test/plugin/provider-opencode-artifacts.test.ts +236 -0
  893. package/test/plugin/provider-opencode-watches.test.ts +1103 -0
  894. package/test/plugin/provider-opencode.test.ts +2590 -0
  895. package/test/plugin/provider-openrouter.test.ts +83 -0
  896. package/test/plugin/provider-poe.test.ts +360 -0
  897. package/test/plugin/provider-sap-ai-core.test.ts +138 -0
  898. package/test/plugin/provider-snowflake-cortex.test.ts +294 -0
  899. package/test/plugin/provider-vllm.test.ts +382 -0
  900. package/test/plugin/provider-xai.test.ts +92 -0
  901. package/test/plugin/provider-zenmux.test.ts +100 -0
  902. package/test/plugin/session-compact.test.ts +52 -0
  903. package/test/plugin/session-instructions.test.ts +197 -0
  904. package/test/plugin/session-list.test.ts +52 -0
  905. package/test/plugin/session-remove.test.ts +61 -0
  906. package/test/plugin/skill.test.ts +81 -0
  907. package/test/plugin/supervisor-reload.test.ts +401 -0
  908. package/test/plugin/supervisor.test.ts +485 -0
  909. package/test/plugin/tool-input-repair-integration.test.ts +296 -0
  910. package/test/plugin/tool-input-repair.test.ts +457 -0
  911. package/test/plugin/vcs-init.test.ts +48 -0
  912. package/test/plugin/verbosity.test.ts +163 -0
  913. package/test/plugin/warming.test.ts +314 -0
  914. package/test/plugin/websearch-fixture.ts +63 -0
  915. package/test/plugin/websearch.test.ts +368 -0
  916. package/test/plugin/worktree.test.ts +52 -0
  917. package/test/plugin-failure.test.ts +305 -0
  918. package/test/plugin.test.ts +756 -0
  919. package/test/preload.test.ts +32 -0
  920. package/test/preload.ts +2 -0
  921. package/test/process/process.test.ts +340 -0
  922. package/test/project-activate.test.ts +144 -0
  923. package/test/project-icon.test.ts +198 -0
  924. package/test/project.test.ts +754 -0
  925. package/test/provider.test.ts +92 -0
  926. package/test/pty/info-schema.test.ts +23 -0
  927. package/test/pty/protocol.test.ts +27 -0
  928. package/test/pty/pty-session.test.ts +224 -0
  929. package/test/pty/pty-windows.test.ts +41 -0
  930. package/test/pty/ticket.test.ts +76 -0
  931. package/test/push-list.test.ts +257 -0
  932. package/test/push-sender.test.ts +235 -0
  933. package/test/push-watcher.test.ts +359 -0
  934. package/test/reference-instructions.test.ts +112 -0
  935. package/test/reference.test.ts +209 -0
  936. package/test/repository-cache.test.ts +235 -0
  937. package/test/repository.test.ts +89 -0
  938. package/test/ripgrep.test.ts +253 -0
  939. package/test/rpc-handler-errors.test.ts +62 -0
  940. package/test/session-activation.test.ts +75 -0
  941. package/test/session-archive.test.ts +81 -0
  942. package/test/session-background.test.ts +97 -0
  943. package/test/session-checkpoint-transport.test.ts +168 -0
  944. package/test/session-compact.test.ts +171 -0
  945. package/test/session-compaction-transport.test.ts +131 -0
  946. package/test/session-compaction.test.ts +1871 -0
  947. package/test/session-create.test.ts +1643 -0
  948. package/test/session-cwd-instructions.test.ts +304 -0
  949. package/test/session-cwd.test.ts +484 -0
  950. package/test/session-diff.test.ts +207 -0
  951. package/test/session-environment.test.ts +30 -0
  952. package/test/session-error.test.ts +434 -0
  953. package/test/session-execution.test.ts +2298 -0
  954. package/test/session-generate.test.ts +502 -0
  955. package/test/session-instructions.test.ts +378 -0
  956. package/test/session-list.test.ts +72 -0
  957. package/test/session-live-tool-metadata.test.ts +43 -0
  958. package/test/session-log.test.ts +123 -0
  959. package/test/session-model-request-hooks.test.ts +270 -0
  960. package/test/session-model-request.test.ts +243 -0
  961. package/test/session-model-transport-live.test.ts +329 -0
  962. package/test/session-model-transport.test.ts +1109 -0
  963. package/test/session-move.test.ts +671 -0
  964. package/test/session-native-compaction.test.ts +425 -0
  965. package/test/session-native.test.ts +359 -0
  966. package/test/session-owned.test.ts +1073 -0
  967. package/test/session-projector.test.ts +2797 -0
  968. package/test/session-prompt.test.ts +1549 -0
  969. package/test/session-remove.test.ts +117 -0
  970. package/test/session-revert.test.ts +121 -0
  971. package/test/session-run-coordinator.test.ts +711 -0
  972. package/test/session-runner-message.test.ts +1574 -0
  973. package/test/session-runner-recorded.test.ts +288 -0
  974. package/test/session-runner-retry.test.ts +130 -0
  975. package/test/session-runner-tool-events.test.ts +662 -0
  976. package/test/session-runner.test.ts +7859 -0
  977. package/test/session-search-build.test.ts +214 -0
  978. package/test/session-search-index.test.ts +524 -0
  979. package/test/session-search.test.ts +375 -0
  980. package/test/session-shell.test.ts +437 -0
  981. package/test/session-skill.test.ts +228 -0
  982. package/test/session-sql.types.ts +25 -0
  983. package/test/session-stats.test.ts +429 -0
  984. package/test/session-step.test.ts +435 -0
  985. package/test/session-store.test.ts +543 -0
  986. package/test/session-system-prompt.test.ts +8 -0
  987. package/test/session-title.test.ts +767 -0
  988. package/test/session-tool-progress.test.ts +159 -0
  989. package/test/session-usage.test.ts +24 -0
  990. package/test/session-view.test.ts +218 -0
  991. package/test/session-wait.test.ts +41 -0
  992. package/test/shared-cache.test.ts +161 -0
  993. package/test/shared-schema.test.ts +187 -0
  994. package/test/shell-cleanup.test.ts +52 -0
  995. package/test/shell-daemon.test.ts +663 -0
  996. package/test/shell-parse-compatibility.test.ts +451 -0
  997. package/test/shell-parse-parity.test.ts +170 -0
  998. package/test/shell-parse-syntax.test.ts +201 -0
  999. package/test/shell-parse.test.ts +251 -0
  1000. package/test/shell-restart.test.ts +268 -0
  1001. package/test/shell-result.test.ts +65 -0
  1002. package/test/shell-retention.test.ts +162 -0
  1003. package/test/shell-scan/adversarial.test.ts +112 -0
  1004. package/test/shell-scan/arithmetic.test.ts +143 -0
  1005. package/test/shell-scan/bash-safety.test.ts +291 -0
  1006. package/test/shell-scan/bash-syntax.test.ts +361 -0
  1007. package/test/shell-scan/closure.test.ts +47 -0
  1008. package/test/shell-scan/compound-parity.test.ts +131 -0
  1009. package/test/shell-scan/generated.test.ts +201 -0
  1010. package/test/shell-scan/oracle.test.ts +762 -0
  1011. package/test/shell-scan/parity-regressions.test.ts +146 -0
  1012. package/test/shell-scan/powershell-runtime.test.ts +604 -0
  1013. package/test/shell-scan/powershell-safety.test.ts +470 -0
  1014. package/test/shell-scan/powershell-syntax.test.ts +177 -0
  1015. package/test/shell-scan/redirect.test.ts +168 -0
  1016. package/test/shell-scan/scan.test.ts +496 -0
  1017. package/test/shell.test.ts +140 -0
  1018. package/test/skill/instructions.test.ts +216 -0
  1019. package/test/skill-discovery.test.ts +154 -0
  1020. package/test/skill.test.ts +297 -0
  1021. package/test/snapshot.test.ts +488 -0
  1022. package/test/sqlite-bundle.test.ts +53 -0
  1023. package/test/sqlite-interrupt.test.ts +86 -0
  1024. package/test/sqlite-node.test.ts +80 -0
  1025. package/test/sqlite-workerd.test.ts +111 -0
  1026. package/test/state-group.test.ts +138 -0
  1027. package/test/state-replay.test.ts +207 -0
  1028. package/test/state.test.ts +679 -0
  1029. package/test/storage-failure.test.ts +88 -0
  1030. package/test/subagent-completion.test.ts +170 -0
  1031. package/test/subagent-idle-e2e.test.ts +825 -0
  1032. package/test/subagent-lifetime.test.ts +146 -0
  1033. package/test/subagent-report.test.ts +834 -0
  1034. package/test/tool/file-diff.test.ts +45 -0
  1035. package/test/tool-automation.test.ts +345 -0
  1036. package/test/tool-cd.test.ts +372 -0
  1037. package/test/tool-edit.test.ts +888 -0
  1038. package/test/tool-execute.test.ts +1077 -0
  1039. package/test/tool-html-markdown-budget.test.ts +68 -0
  1040. package/test/tool-image-generate.test.ts +547 -0
  1041. package/test/tool-machine.test.ts +84 -0
  1042. package/test/tool-mcp-events.test.ts +90 -0
  1043. package/test/tool-media-target-environment.test.ts +213 -0
  1044. package/test/tool-model-policy.test.ts +289 -0
  1045. package/test/tool-opencode.test.ts +303 -0
  1046. package/test/tool-output.test.ts +334 -0
  1047. package/test/tool-patch-target-environment.test.ts +239 -0
  1048. package/test/tool-patch.test.ts +1265 -0
  1049. package/test/tool-question.test.ts +260 -0
  1050. package/test/tool-read-filesystem.test.ts +833 -0
  1051. package/test/tool-read.test.ts +1341 -0
  1052. package/test/tool-registry.test.ts +1662 -0
  1053. package/test/tool-schema.test.ts +538 -0
  1054. package/test/tool-search-target-environment.test.ts +103 -0
  1055. package/test/tool-search.test.ts +411 -0
  1056. package/test/tool-session-search.test.ts +178 -0
  1057. package/test/tool-shell-target-environment.test.ts +193 -0
  1058. package/test/tool-shell.test.ts +2650 -0
  1059. package/test/tool-skill.test.ts +203 -0
  1060. package/test/tool-subagent.test.ts +1046 -0
  1061. package/test/tool-target-environment.test.ts +183 -0
  1062. package/test/tool-todo.test.ts +75 -0
  1063. package/test/tool-video-generate.test.ts +227 -0
  1064. package/test/tool-webfetch.test.ts +737 -0
  1065. package/test/tool-websearch.test.ts +482 -0
  1066. package/test/tool-write.test.ts +440 -0
  1067. package/test/usage-limits.test.ts +210 -0
  1068. package/test/util/effect-flock.test.ts +331 -0
  1069. package/test/util/error-summary.test.ts +19 -0
  1070. package/test/util/flock.test.ts +326 -0
  1071. package/test/util/fs-util.test.ts +50 -0
  1072. package/test/util/git-executable.test.ts +80 -0
  1073. package/test/util/which.test.ts +99 -0
  1074. package/test/v1-migration.test.ts +1508 -0
  1075. package/test/variant.test.ts +575 -0
  1076. package/test/vcs-hg.test.ts +239 -0
  1077. package/test/vcs.test.ts +1396 -0
  1078. package/test/video-generation.test.ts +146 -0
  1079. package/test/voice.test.ts +332 -0
  1080. package/test/websearch.test.ts +593 -0
  1081. package/test/wellknown.test.ts +132 -0
  1082. package/test/worker-client.test.ts +529 -0
  1083. package/test/workspace.test.ts +828 -0
  1084. package/test/worktree.test.ts +944 -0
  1085. package/tsconfig.build.json +11 -0
  1086. package/tsconfig.json +18 -0
  1087. package/tsconfig.tests.json +13 -0
@@ -0,0 +1,4196 @@
1
+ import path from "node:path"
2
+ import fs from "node:fs/promises"
3
+ import os from "node:os"
4
+ import { describe, expect, spyOn, test } from "bun:test"
5
+ import { StreamableHTTPClientTransport, isJSONRPCRequest, type ListToolsResult } from "@modelcontextprotocol/client"
6
+ import {
7
+ createMcpHandler,
8
+ inputRequired,
9
+ inputResponse,
10
+ Server,
11
+ WebStandardStreamableHTTPServerTransport,
12
+ } from "@modelcontextprotocol/server"
13
+ import { Document, Event, Info } from "@zyro-sec/schema/config"
14
+ import { ConfigMCP } from "@zyro-sec/schema/config/mcp"
15
+ import { McpEvent } from "@zyro-sec/schema/mcp-event"
16
+ import { ConfigPolicy } from "@zyro-sec/schema/config/policy"
17
+ import { Config } from "@zyro-sec/core/config"
18
+ import { ConfigMcpPlugin } from "@zyro-sec/core/config/plugin/mcp"
19
+ import { Credential } from "@zyro-sec/core/credential"
20
+ import { AppNodeBuilder } from "@zyro-sec/core/effect/app-node-builder"
21
+ import { LayerNode } from "@zyro-sec/util/effect/layer-node"
22
+ import { Bus } from "@zyro-sec/core/bus"
23
+ import { ID, type Payload } from "@zyro-sec/schema/event"
24
+ import { Form } from "@zyro-sec/core/form"
25
+ import { Integration } from "@zyro-sec/core/integration"
26
+ import { Environment } from "@zyro-sec/core/environment/index"
27
+ import { App } from "@zyro-sec/core/app"
28
+ import { Flag } from "@zyro-sec/core/flag"
29
+ import { EnvironmentUnavailable } from "@zyro-sec/core/environment/unavailable"
30
+ import { Location } from "@zyro-sec/core/location"
31
+ import { Mcp } from "@zyro-sec/core/mcp/index"
32
+ import { McpClient } from "@zyro-sec/core/mcp/client"
33
+ import { McpPool } from "@zyro-sec/core/mcp/pool"
34
+ import { McpStdio } from "@zyro-sec/core/mcp/stdio"
35
+ import { Permission } from "@zyro-sec/core/permission"
36
+ import { AbsolutePath } from "@zyro-sec/core/schema"
37
+ import { Session } from "@zyro-sec/core/session"
38
+ import { State } from "@zyro-sec/core/state"
39
+ import { McpTool } from "@zyro-sec/core/tool/mcp"
40
+ import { Command } from "@zyro-sec/core/command"
41
+ import { CommandPlugin } from "@zyro-sec/core/plugin/command"
42
+ import { McpResourceTools } from "@zyro-sec/core/tool/plugin/mcp-resource"
43
+ import { Tool } from "@zyro-sec/core/tool"
44
+ import { ToolOutput } from "@zyro-sec/core/tool-output"
45
+ import {
46
+ Clock,
47
+ Context,
48
+ Deferred,
49
+ Effect,
50
+ Exit,
51
+ Fiber,
52
+ FiberSet,
53
+ Layer,
54
+ Logger,
55
+ Option,
56
+ PubSub,
57
+ Queue,
58
+ Ref,
59
+ Schedule,
60
+ Schema,
61
+ Scope,
62
+ Semaphore,
63
+ Sink,
64
+ Stream,
65
+ } from "effect"
66
+ import { TestClock } from "effect/testing"
67
+ import { ChildProcess, ChildProcessSpawner } from "effect/process"
68
+ import { ExitCode, makeHandle, ProcessId } from "effect/process/ChildProcessSpawner"
69
+ import { Global } from "@zyro-sec/util/global"
70
+ import { isRecord } from "@zyro-sec/util/record"
71
+ import { CrossSpawnSpawner } from "@zyro-sec/util/cross-spawn-spawner"
72
+ import { advance, drain } from "./lib/clock"
73
+ import { testEffect } from "./lib/effect"
74
+ import { permissionLayer } from "./lib/permission"
75
+ import { registerIntegrationPolicy, setOrganizationPolicy } from "./fixture/policy"
76
+ import { location } from "./fixture/location"
77
+ import { host } from "./plugin/host"
78
+ import { tmpdirScoped } from "./fixture/tmpdir"
79
+ import { hostEnvironmentLayer, recordingEnvironmentLayer } from "./fixture/environment"
80
+ import {
81
+ codeModeListings,
82
+ executeTool,
83
+ registerToolPlugin,
84
+ toolDefinitions,
85
+ toolIdentity,
86
+ toolNodeReplacements,
87
+ waitForTool,
88
+ } from "./lib/tool"
89
+
90
+ let assertion: Deferred.Deferred<Permission.AssertInput> | undefined
91
+ let decision: Effect.Effect<void, Permission.Error> = Effect.void
92
+ let calls = 0
93
+ let invocations: Array<Parameters<Mcp.Interface["callTool"]>[0]> = []
94
+
95
+ type ResourcePage = {
96
+ items: Array<{ name: string; uri: string; description?: string; mimeType?: string }>
97
+ nextCursor?: string
98
+ }
99
+
100
+ type ResourceTemplatePage = {
101
+ items: Array<{ name: string; uriTemplate: string; description?: string; mimeType?: string }>
102
+ nextCursor?: string
103
+ }
104
+
105
+ function resourceServer(
106
+ input: {
107
+ /** Serve 2026-07-28 only through createMcpHandler; the default is a sessionful legacy transport. */
108
+ modern?: boolean
109
+ resources?: boolean
110
+ listChanged?: boolean
111
+ emptyElicitation?: boolean
112
+ urlElicitation?: boolean
113
+ /**
114
+ * Ahead of the valid tools, list entries that cannot be used (null, not an object, no name, an input
115
+ * schema that is not an object), one whose input schema has a string `required`, and one with a
116
+ * malformed optional field of each kind, then one with every optional field valid.
117
+ */
118
+ malformedTool?: boolean
119
+ /**
120
+ * Listed after the default tools. A call's `structured` argument comes back as structured content and
121
+ * its `text` argument as text content.
122
+ */
123
+ tools?: ListToolsResult["tools"]
124
+ /** Legacy servers give up on the URL elicitation after this many milliseconds. */
125
+ elicitationTimeout?: number
126
+ /** Lists a `roots` tool that asks for the client's roots (2026-07-28 only) and returns them. */
127
+ roots?: boolean
128
+ /** Advertises MCP Events; answer its requests through `respond`. */
129
+ events?: boolean
130
+ respond?: (request: Request) => Response | undefined | Promise<Response | undefined>
131
+ } = {},
132
+ ) {
133
+ return Effect.acquireRelease(
134
+ Effect.promise(async () => {
135
+ const state = {
136
+ resources: [] as ResourcePage["items"],
137
+ templates: [] as ResourceTemplatePage["items"],
138
+ resourcePages: undefined as Record<string, ResourcePage> | undefined,
139
+ templatePages: undefined as Record<string, ResourceTemplatePage> | undefined,
140
+ contents: [
141
+ { uri: "docs://readme", text: "hello", mimeType: "text/plain" },
142
+ { uri: "docs://logo", blob: "aGVsbG8=", mimeType: "image/png" },
143
+ ] as Array<{ uri: string; text: string; mimeType?: string } | { uri: string; blob: string; mimeType?: string }>,
144
+ resourceLists: 0,
145
+ resourceReads: [] as string[],
146
+ templatesUnsupported: false,
147
+ missing: [] as string[],
148
+ templateLists: 0,
149
+ toolLists: 0,
150
+ toolCalls: [] as Array<{
151
+ name: string
152
+ arguments: Record<string, unknown> | undefined
153
+ sessionID: unknown
154
+ progressToken: unknown
155
+ }>,
156
+ initializations: 0,
157
+ /** Listed after the configured tools; change it, then announce the change. */
158
+ extraTools: [] as ListToolsResult["tools"],
159
+ urls: [] as string[],
160
+ sessions: [] as string[],
161
+ }
162
+ // One Server speaks one session, so a restart is a fresh Server and transport. Requests that
163
+ // still carry the previous session id are then unknown to the new transport.
164
+ const server = () => {
165
+ const protocol = new Server(
166
+ { name: "mcp-resources", title: "MCP Resources", version: "1.0.0" },
167
+ {
168
+ capabilities: {
169
+ tools: { listChanged: input.listChanged },
170
+ prompts: {},
171
+ ...(input.resources === false ? {} : { resources: { listChanged: input.listChanged } }),
172
+ ...(input.events ? { extensions: { "io.modelcontextprotocol/events": {} } } : {}),
173
+ },
174
+ instructions: "Use the resources tools.",
175
+ },
176
+ )
177
+ protocol.setRequestHandler("tools/list", () => {
178
+ state.toolLists += 1
179
+ return Promise.resolve({
180
+ tools: [
181
+ // Servers send raw JSON; the cast lets the fixture send a tool the schema rejects.
182
+ ...(input.malformedTool
183
+ ? ([
184
+ null,
185
+ "not-a-tool",
186
+ { inputSchema: { type: "object" } },
187
+ { name: "no-schema" },
188
+ { name: "malformed", inputSchema: { type: "string" } },
189
+ { name: "bad-required", inputSchema: { type: "object", required: "text" } },
190
+ {
191
+ name: "bad-fields",
192
+ title: 1,
193
+ description: 42,
194
+ outputSchema: "none",
195
+ annotations: "read-only",
196
+ execution: true,
197
+ _meta: [],
198
+ inputSchema: { type: "object" },
199
+ },
200
+ {
201
+ name: "full",
202
+ title: "Full",
203
+ description: "Every field",
204
+ inputSchema: { type: "object" },
205
+ annotations: { readOnlyHint: true },
206
+ execution: { taskSupport: "optional" },
207
+ _meta: { "example/key": 1 },
208
+ icons: [{ src: "https://example.com/icon.png" }],
209
+ },
210
+ ] as unknown as ListToolsResult["tools"])
211
+ : []),
212
+ ...(input.emptyElicitation
213
+ ? [{ name: "empty-elicitation", inputSchema: { type: "object" as const, properties: {} } }]
214
+ : input.urlElicitation
215
+ ? [{ name: "url-elicitation", inputSchema: { type: "object" as const, properties: {} } }]
216
+ : [{ name: "echo", inputSchema: { type: "object" as const, properties: {} } }]),
217
+ ...(input.tools ?? []),
218
+ ...(input.roots ? [{ name: "roots", inputSchema: { type: "object" as const, properties: {} } }] : []),
219
+ ...state.extraTools,
220
+ ],
221
+ })
222
+ })
223
+ if (input.emptyElicitation) {
224
+ protocol.setRequestHandler("tools/call", async () => {
225
+ const result = await protocol.elicitInput({
226
+ mode: "form",
227
+ message: "Confirm",
228
+ requestedSchema: { type: "object", properties: {} },
229
+ })
230
+ return {
231
+ content: [{ type: "text", text: JSON.stringify(result) }],
232
+ structuredContent: result,
233
+ }
234
+ })
235
+ }
236
+ if (input.urlElicitation) {
237
+ const url = "https://example.com/authorize"
238
+ // Modern servers cannot call elicitInput; they return input_required and the client retries.
239
+ protocol.setRequestHandler("tools/call", async (request, ctx) => {
240
+ const responses = ctx.mcpReq.inputResponses
241
+ if (input.modern && !responses)
242
+ return inputRequired({ inputRequests: { auth: inputRequired.elicitUrl({ message: "Authorize", url }) } })
243
+ const response = inputResponse(responses, "auth")
244
+ const result = input.modern
245
+ ? { action: response.kind === "elicit" ? response.action : "cancel" }
246
+ : await protocol.elicitInput(
247
+ {
248
+ mode: "url",
249
+ message: "Authorize access",
250
+ url,
251
+ elicitationId: "elicitation-test",
252
+ },
253
+ input.elicitationTimeout === undefined ? undefined : { timeout: input.elicitationTimeout },
254
+ )
255
+ return {
256
+ content: [{ type: "text", text: JSON.stringify(result) }],
257
+ structuredContent: result,
258
+ }
259
+ })
260
+ }
261
+ if (!input.emptyElicitation && !input.urlElicitation) {
262
+ protocol.setRequestHandler("tools/call", (request, ctx) => {
263
+ if (request.params.name === "roots") {
264
+ const responses = ctx.mcpReq.inputResponses
265
+ if (!responses)
266
+ return Promise.resolve(inputRequired({ inputRequests: { roots: inputRequired.listRoots() } }))
267
+ return Promise.resolve({ content: [], structuredContent: inputResponse(responses, "roots") })
268
+ }
269
+ state.toolCalls.push({
270
+ name: request.params.name,
271
+ arguments: request.params.arguments,
272
+ sessionID: request.params._meta?.["ai.opencode/sessionID"],
273
+ progressToken: request.params._meta?.progressToken,
274
+ })
275
+ const structured = request.params.arguments?.structured
276
+ const text = request.params.arguments?.text
277
+ const content = typeof text === "string" ? [{ type: "text" as const, text }] : []
278
+ return Promise.resolve(structured === undefined ? { content } : { content, structuredContent: structured })
279
+ })
280
+ }
281
+ protocol.setRequestHandler("prompts/list", () => Promise.resolve({ prompts: [{ name: "greet" }] }))
282
+ protocol.setRequestHandler("prompts/get", (request) =>
283
+ Promise.resolve({
284
+ messages: [{ role: "user", content: { type: "text", text: `hi ${request.params.arguments?.name}` } }],
285
+ }),
286
+ )
287
+ if (input.resources !== false) {
288
+ protocol.setRequestHandler("resources/list", (request) => {
289
+ state.resourceLists += 1
290
+ const page = state.resourcePages?.[request.params?.cursor ?? "initial"]
291
+ return Promise.resolve({ resources: page?.items ?? state.resources, nextCursor: page?.nextCursor })
292
+ })
293
+ protocol.setRequestHandler("resources/templates/list", (request) => {
294
+ state.templateLists += 1
295
+ if (state.templatesUnsupported) return Promise.reject(new Error("Method not found"))
296
+ const page = state.templatePages?.[request.params?.cursor ?? "initial"]
297
+ return Promise.resolve({ resourceTemplates: page?.items ?? state.templates, nextCursor: page?.nextCursor })
298
+ })
299
+ protocol.setRequestHandler("resources/read", (request) => {
300
+ state.resourceReads.push(request.params.uri)
301
+ if (state.missing.includes(request.params.uri)) return Promise.reject(new Error("Resource not found"))
302
+ return Promise.resolve({ contents: state.contents })
303
+ })
304
+ }
305
+ return protocol
306
+ }
307
+ const build = async () => {
308
+ const protocol = server()
309
+ const transport = new WebStandardStreamableHTTPServerTransport({
310
+ sessionIdGenerator: () => crypto.randomUUID(),
311
+ enableJsonResponse: true,
312
+ })
313
+ await protocol.connect(transport)
314
+ return { protocol, transport }
315
+ }
316
+ let current = await build()
317
+ const modern = input.modern ? createMcpHandler(server, { legacy: "reject" }) : undefined
318
+ const http = Bun.serve({
319
+ port: 0,
320
+ fetch: async (request) => {
321
+ state.urls.push(request.url)
322
+ const session = request.headers.get("mcp-session-id")
323
+ if (session !== null && !state.sessions.includes(session)) state.sessions.push(session)
324
+ const body: unknown = request.method === "POST" ? await request.clone().json() : undefined
325
+ if (typeof body === "object" && body !== null && "method" in body && body.method === "initialize") {
326
+ state.initializations += 1
327
+ }
328
+ return (await input.respond?.(request)) ?? modern?.fetch(request) ?? current.transport.handleRequest(request)
329
+ },
330
+ })
331
+ return {
332
+ state,
333
+ url: http.url.toString(),
334
+ clientVersion: () => current.protocol.getClientVersion(),
335
+ sendToolListChanged: () =>
336
+ modern ? Promise.resolve(modern.notify.toolsChanged()) : current.protocol.sendToolListChanged(),
337
+ sendResourceListChanged: () =>
338
+ modern ? Promise.resolve(modern.notify.resourcesChanged()) : current.protocol.sendResourceListChanged(),
339
+ completeElicitation: () => current.protocol.createElicitationCompletionNotifier("elicitation-test")(),
340
+ restart: async () => {
341
+ await current.protocol.close().catch(() => {})
342
+ current = await build()
343
+ },
344
+ close: async () => {
345
+ await current.protocol.close().catch(() => {})
346
+ await modern?.close()
347
+ await http.stop(true)
348
+ },
349
+ }
350
+ }),
351
+ (server) => Effect.promise(server.close),
352
+ )
353
+ }
354
+
355
+ const poolLayer = McpPool.layer.pipe(Layer.provide(LayerNode.compile(CrossSpawnSpawner.node)))
356
+
357
+ function resourceMcpLayer(
358
+ server: string | typeof ConfigMCP.Server.Type,
359
+ onFormCreated?: (form: Form.Info) => Effect.Effect<void>,
360
+ options?: Mcp.Options,
361
+ overrides?: {
362
+ policies?: readonly ConfigPolicy.Info[]
363
+ entries?: Config.Interface["entries"]
364
+ subscribe?: Bus.Interface["subscribe"]
365
+ environment?: Layer.Layer<Environment.Service>
366
+ published?: string[]
367
+ pool?: Layer.Layer<McpPool.Service>
368
+ directory?: string
369
+ /** The configured server's name; "resources" unless given. */
370
+ name?: string
371
+ credentials?: Partial<Credential.Interface>
372
+ bus?: Layer.Layer<Bus.Service>
373
+ /** `OPENCODE_FLAGS`, such as `-machines`. */
374
+ flags?: string
375
+ },
376
+ ) {
377
+ const directory = AbsolutePath.make(overrides?.directory ?? import.meta.dir)
378
+ const unusedIntegration = () => Effect.die("unused integration service")
379
+ return Layer.effectDiscard(
380
+ Effect.gen(function* () {
381
+ const bus = yield* Bus.Service
382
+ const mcp = yield* Mcp.Service
383
+ yield* State.batch(
384
+ Effect.gen(function* () {
385
+ yield* ConfigMcpPlugin.register(bus.subscribe())
386
+ yield* registerIntegrationPolicy({ mcp, events: bus.subscribe() })
387
+ }),
388
+ )
389
+ }),
390
+ ).pipe(
391
+ Layer.provideMerge(Mcp.layer(options)),
392
+ Layer.provideMerge(Form.layer),
393
+ Layer.provideMerge(Flag.layer),
394
+ Layer.provide(
395
+ Layer.mergeAll(
396
+ overrides?.pool ?? poolLayer,
397
+ overrides?.entries
398
+ ? Layer.succeed(
399
+ Config.Service,
400
+ Config.Service.of({
401
+ entries: overrides.entries,
402
+ changes: () => Stream.never,
403
+ }),
404
+ )
405
+ : Config.testLayer([
406
+ new Document({
407
+ type: "document",
408
+ info: new Info({
409
+ policies: overrides?.policies ?? [],
410
+ mcp: new ConfigMCP.Info({
411
+ servers: {
412
+ [overrides?.name ?? "resources"]:
413
+ typeof server === "string"
414
+ ? new ConfigMCP.Remote({ type: "remote", url: server, oauth: false })
415
+ : server,
416
+ },
417
+ }),
418
+ }),
419
+ }),
420
+ ]),
421
+ Layer.succeed(Location.Service, Location.Service.of(location({ directory }))),
422
+ App.layer(),
423
+ Layer.succeed(Flag.Overrides, overrides?.flags),
424
+ overrides?.bus ??
425
+ Layer.mock(Bus.Service, {
426
+ subscribe: overrides?.subscribe ?? (() => Stream.never),
427
+ publish: (definition, data) =>
428
+ Effect.suspend(() => {
429
+ const event = {
430
+ id: ID.create(),
431
+ type: definition.type,
432
+ data,
433
+ } as Payload<typeof definition>
434
+ overrides?.published?.push(event.type)
435
+ if (event.type !== Form.Event.Created.type || !onFormCreated) return Effect.succeed(event)
436
+ return onFormCreated(Schema.decodeUnknownSync(Form.Event.Created.data)(data).form).pipe(
437
+ Effect.as(event),
438
+ )
439
+ }),
440
+ }),
441
+ Layer.mock(Integration.Service, {
442
+ revision: () => 0,
443
+ transform: () => Effect.succeed({ dispose: Effect.void }),
444
+ connection: {
445
+ active: unusedIntegration,
446
+ resolve: unusedIntegration,
447
+ key: unusedIntegration,
448
+ external: unusedIntegration,
449
+ activate: unusedIntegration,
450
+ update: unusedIntegration,
451
+ remove: unusedIntegration,
452
+ status: unusedIntegration,
453
+ },
454
+ oauth: {
455
+ connect: unusedIntegration,
456
+ status: unusedIntegration,
457
+ complete: unusedIntegration,
458
+ cancel: unusedIntegration,
459
+ },
460
+ command: {
461
+ connect: unusedIntegration,
462
+ status: unusedIntegration,
463
+ cancel: unusedIntegration,
464
+ },
465
+ }),
466
+ Layer.mock(Credential.Service, { list: () => Effect.succeed([]), ...overrides?.credentials }),
467
+ overrides?.environment ?? hostEnvironmentLayer,
468
+ ),
469
+ ),
470
+ )
471
+ }
472
+
473
+ const connect = (server: string, config: typeof ConfigMCP.Server.Type, directory: string) =>
474
+ McpClient.connect({ server, config, directory }).pipe(Effect.provide(hostEnvironmentLayer))
475
+
476
+ // Reads no longer wait for startup, so tests that assert on a connected server settle it first.
477
+ const settled = (service: Mcp.Interface, name = "resources") =>
478
+ Effect.gen(function* () {
479
+ const status = (yield* service.servers()).find((server) => server.name === name)?.status
480
+ if (status?.status === "pending") return yield* Effect.fail(status)
481
+ return status
482
+ }).pipe(Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }))
483
+
484
+ const mcp = Layer.mock(Mcp.Service, {
485
+ awaitStartup: () => Effect.void,
486
+ tools: () =>
487
+ Effect.succeed([
488
+ {
489
+ server: Mcp.ServerName.make("demo"),
490
+ name: "search",
491
+ description: "Search",
492
+ inputSchema: { type: "object", properties: {} },
493
+ outputSchema: {
494
+ type: "object",
495
+ properties: { ok: { type: "boolean" } },
496
+ required: ["ok"],
497
+ },
498
+ } satisfies Mcp.Tool,
499
+ {
500
+ server: Mcp.ServerName.make("demo"),
501
+ name: "status",
502
+ description: "Status",
503
+ inputSchema: { type: "object", properties: {} },
504
+ } satisfies Mcp.Tool,
505
+ {
506
+ server: Mcp.ServerName.make("demo"),
507
+ name: "issues",
508
+ description: "Returns JSON as text",
509
+ inputSchema: { type: "object", properties: {} },
510
+ } satisfies Mcp.Tool,
511
+ {
512
+ server: Mcp.ServerName.make("demo"),
513
+ name: "count",
514
+ description: "Returns a number as text",
515
+ inputSchema: { type: "object", properties: {} },
516
+ } satisfies Mcp.Tool,
517
+ {
518
+ server: Mcp.ServerName.make("demo"),
519
+ name: "typed",
520
+ description: "Declares a string output and returns JSON as text",
521
+ inputSchema: { type: "object", properties: {} },
522
+ outputSchema: { type: "string" },
523
+ } satisfies Mcp.Tool,
524
+ {
525
+ server: Mcp.ServerName.make("direct"),
526
+ name: "issues",
527
+ codemode: false,
528
+ description: "Returns JSON as text",
529
+ inputSchema: { type: "object", properties: {} },
530
+ } satisfies Mcp.Tool,
531
+ {
532
+ server: Mcp.ServerName.make("direct"),
533
+ name: "lookup",
534
+ codemode: false,
535
+ description: "Lookup",
536
+ inputSchema: { type: "object", properties: {} },
537
+ } satisfies Mcp.Tool,
538
+ {
539
+ server: Mcp.ServerName.make("direct"),
540
+ name: "fail",
541
+ codemode: false,
542
+ description: "Always fails",
543
+ inputSchema: { type: "object", properties: {} },
544
+ } satisfies Mcp.Tool,
545
+ {
546
+ server: Mcp.ServerName.make("direct"),
547
+ name: "media",
548
+ codemode: false,
549
+ description: "Returns text and an image",
550
+ inputSchema: { type: "object", properties: {} },
551
+ } satisfies Mcp.Tool,
552
+ {
553
+ server: Mcp.ServerName.make("direct"),
554
+ name: "attachments",
555
+ codemode: false,
556
+ description: "Returns resource blobs that cannot be sent inline",
557
+ inputSchema: { type: "object", properties: {} },
558
+ } satisfies Mcp.Tool,
559
+ ]),
560
+ callTool: (input) =>
561
+ Effect.sync(() => {
562
+ calls += 1
563
+ invocations.push(input)
564
+ if (input.name === "fail")
565
+ return {
566
+ isError: true,
567
+ content: [{ type: "text", text: "search index unavailable" }],
568
+ } satisfies Mcp.ToolResult
569
+ if (input.name === "media")
570
+ return {
571
+ isError: false,
572
+ content: [
573
+ { type: "text", text: "rendered chart" },
574
+ { type: "media", data: "aGVsbG8=", mimeType: "image/png" },
575
+ ],
576
+ } satisfies Mcp.ToolResult
577
+ if (input.name === "attachments")
578
+ return {
579
+ isError: false,
580
+ content: [
581
+ {
582
+ type: "media",
583
+ data: Buffer.from("# Notes").toString("base64"),
584
+ mimeType: "text/markdown",
585
+ uri: "file:///README.md",
586
+ },
587
+ {
588
+ type: "media",
589
+ data: "UEFSMQ==",
590
+ mimeType: "application/vnd.apache.parquet",
591
+ uri: "file:///data.parquet",
592
+ },
593
+ ],
594
+ } satisfies Mcp.ToolResult
595
+ if (input.name === "status")
596
+ return {
597
+ isError: false,
598
+ content: [{ type: "text", text: "hello" }],
599
+ } satisfies Mcp.ToolResult
600
+ if (input.name === "issues" || input.name === "typed")
601
+ return {
602
+ isError: false,
603
+ content: [{ type: "text", text: '{"issues":[{"id":1}]}' }],
604
+ } satisfies Mcp.ToolResult
605
+ if (input.name === "count")
606
+ return {
607
+ isError: false,
608
+ content: [{ type: "text", text: "42" }],
609
+ } satisfies Mcp.ToolResult
610
+ return {
611
+ isError: false,
612
+ structured: { ok: true },
613
+ content: [],
614
+ } satisfies Mcp.ToolResult
615
+ }),
616
+ })
617
+ const permissions = permissionLayer({
618
+ assert: (input) =>
619
+ Effect.gen(function* () {
620
+ if (!assertion) return yield* Effect.die("Permission test is not initialized")
621
+ yield* Deferred.succeed(assertion, input)
622
+ yield* decision
623
+ }),
624
+ })
625
+ const events = Layer.mock(Bus.Service, { subscribe: () => Stream.never })
626
+ const outputData = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-mcp-output-"))
627
+ const it = testEffect(
628
+ AppNodeBuilder.build(LayerNode.group([Tool.node, McpTool.node]), [
629
+ ...toolNodeReplacements(permissions),
630
+ Mcp.node.replace(mcp),
631
+ Bus.node.replace(events),
632
+ Global.node.replace(Global.layerWith({ data: outputData })),
633
+ ]),
634
+ )
635
+
636
+ test("MCP tool names match V1 sanitization", () => {
637
+ expect(McpTool.namespace("context 7")).toBe("context_7")
638
+ expect(McpTool.name("context 7", "resolve.library/id")).toBe("context_7_resolve_library_id")
639
+ })
640
+
641
+ test("passes session IDs as MCP request metadata", async () => {
642
+ await Effect.runPromise(
643
+ Effect.scoped(
644
+ Effect.gen(function* () {
645
+ const server = yield* resourceServer()
646
+ const connection = yield* connect(
647
+ "session-metadata",
648
+ new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false }),
649
+ import.meta.dir,
650
+ )
651
+ yield* connection.callTool({
652
+ name: "echo",
653
+ args: { text: "hello" },
654
+ sessionID: Session.ID.make("ses_mcp_metadata"),
655
+ })
656
+ yield* connection.callTool({ name: "echo" })
657
+
658
+ expect(server.state.toolCalls).toEqual([
659
+ {
660
+ name: "echo",
661
+ arguments: { text: "hello" },
662
+ sessionID: "ses_mcp_metadata",
663
+ progressToken: expect.any(Number),
664
+ },
665
+ {
666
+ name: "echo",
667
+ arguments: {},
668
+ sessionID: undefined,
669
+ progressToken: expect.any(Number),
670
+ },
671
+ ])
672
+ expect(server.state.toolCalls[0]?.progressToken).not.toBe(server.state.toolCalls[1]?.progressToken)
673
+ }),
674
+ ),
675
+ )
676
+ })
677
+
678
+ test("accepts legacy MCP tools whose output schema is not a root object", async () => {
679
+ const result = await Effect.runPromise(
680
+ Effect.scoped(
681
+ Effect.gen(function* () {
682
+ const connection = yield* connect(
683
+ "union",
684
+ new ConfigMCP.Local({
685
+ type: "local",
686
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-union-output-schema.ts")],
687
+ }),
688
+ import.meta.dir,
689
+ )
690
+ return {
691
+ tools: yield* connection.tools(),
692
+ call: yield* connection.callTool({ name: "union" }),
693
+ }
694
+ }),
695
+ ),
696
+ )
697
+
698
+ expect(result.tools.map((tool) => tool.name)).toEqual(["union"])
699
+ expect(result.tools[0]?.outputSchema).toHaveProperty("anyOf")
700
+ expect(result.call.structured).toEqual({ kind: "struct" })
701
+ })
702
+
703
+ test("lists paginated prompts and invokes them through the MCP client", async () => {
704
+ const result = await Effect.runPromise(
705
+ Effect.scoped(
706
+ Effect.gen(function* () {
707
+ const connection = yield* connect(
708
+ "prompts",
709
+ new ConfigMCP.Local({
710
+ type: "local",
711
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-prompts.ts")],
712
+ }),
713
+ import.meta.dir,
714
+ )
715
+ return {
716
+ prompts: yield* connection.prompts(),
717
+ result: yield* connection.prompt({ name: "first", args: { topic: "Effect" } }),
718
+ }
719
+ }),
720
+ ),
721
+ )
722
+
723
+ expect(result.prompts).toEqual([
724
+ {
725
+ name: "first",
726
+ description: "First prompt",
727
+ arguments: [{ name: "topic", description: "Topic to explain", required: true }],
728
+ },
729
+ { name: "second", description: "Second prompt", arguments: undefined },
730
+ ])
731
+ expect(result.result).toEqual({ messages: [{ role: "user", content: { type: "text", text: "Effect" } }] })
732
+ })
733
+
734
+ test("spawns local MCP servers through the location environment", async () => {
735
+ const spawns: Array<ChildProcess.Command> = []
736
+ const cwd = path.join(import.meta.dir, "fixture")
737
+ const config = new ConfigMCP.Local({
738
+ type: "local",
739
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-output-schema.ts")],
740
+ cwd: "fixture",
741
+ environment: { MCP_LOCATION_TEST: "configured" },
742
+ })
743
+
744
+ await Effect.runPromise(
745
+ Effect.scoped(
746
+ Effect.gen(function* () {
747
+ const connection = yield* McpClient.connect({ server: "environment", config, directory: import.meta.dir })
748
+ yield* connection.tools()
749
+ }),
750
+ ).pipe(Effect.provide(recordingEnvironmentLayer(spawns))),
751
+ )
752
+
753
+ expect(spawns).toHaveLength(1)
754
+ const command = spawns[0]
755
+ if (!command || !ChildProcess.isStandardCommand(command)) throw new Error("Expected a standard process command")
756
+ expect(command.command).toBe(process.execPath)
757
+ expect(command.options.cwd).toBe(cwd)
758
+ expect(command.options.extendEnv).toBe(true)
759
+ expect(command.options.env).toEqual({ MCP_LOCATION_TEST: "configured" })
760
+ })
761
+
762
+ test("reports a local MCP server as failed when the location has no execution plane", async () => {
763
+ const config = new ConfigMCP.Local({ type: "local", command: ["example-mcp"] })
764
+ const driver = Environment.makeMemoryDriver()
765
+ const environment = Layer.succeed(
766
+ Environment.Service,
767
+ Environment.Service.of({
768
+ id: Environment.localID,
769
+ local: false,
770
+ files: Environment.makeFiles(driver),
771
+ spawner: EnvironmentUnavailable.spawner,
772
+ }),
773
+ )
774
+
775
+ await Effect.runPromise(
776
+ Effect.gen(function* () {
777
+ const service = yield* Mcp.Service
778
+ const status = yield* settled(service)
779
+ expect(status).toEqual({
780
+ status: "failed",
781
+ error: expect.stringContaining("location has no execution plane"),
782
+ })
783
+ }).pipe(Effect.provide(resourceMcpLayer(config, undefined, undefined, { environment }))),
784
+ )
785
+ })
786
+
787
+ test("rejects sends before the stdio transport is started", async () => {
788
+ await Effect.runPromise(
789
+ Effect.scoped(
790
+ Effect.gen(function* () {
791
+ const transport = yield* McpStdio.make({
792
+ server: "not-started",
793
+ command: process.execPath,
794
+ args: [path.join(import.meta.dir, "fixture/mcp-output-schema.ts")],
795
+ cwd: import.meta.dir,
796
+ environment: {},
797
+ })
798
+ yield* Effect.tryPromise({
799
+ try: () => transport.send({ jsonrpc: "2.0", method: "notifications/initialized" }),
800
+ catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
801
+ }).pipe(
802
+ Effect.flip,
803
+ Effect.tap((error) => Effect.sync(() => expect(error.message).toBe("Not connected"))),
804
+ )
805
+ }).pipe(Effect.provide(hostEnvironmentLayer)),
806
+ ),
807
+ )
808
+ })
809
+
810
+ test("joins concurrent stdio transport closes", async () => {
811
+ await Effect.runPromise(
812
+ Effect.scoped(
813
+ Effect.gen(function* () {
814
+ const transport = yield* McpStdio.make({
815
+ server: "concurrent-close",
816
+ command: "unused",
817
+ args: [],
818
+ cwd: import.meta.dir,
819
+ environment: {},
820
+ })
821
+ const first = transport.close()
822
+ expect(transport.close()).toBe(first)
823
+ yield* Effect.promise(() => first)
824
+ }).pipe(Effect.provide(hostEnvironmentLayer)),
825
+ ),
826
+ )
827
+ })
828
+
829
+ const testMcpDescendants =
830
+ process.platform === "win32" ? testEffect(hostEnvironmentLayer).live.skip : testEffect(hostEnvironmentLayer).live
831
+ testMcpDescendants(
832
+ "terminates MCP descendants after the wrapper exits successfully",
833
+ Effect.gen(function* () {
834
+ const tmp = yield* tmpdirScoped()
835
+ const pidFile = path.join(tmp.path, "child.pid")
836
+ yield* Effect.addFinalizer(() =>
837
+ Effect.tryPromise(async () => process.kill(Number(await fs.readFile(pidFile, "utf8")), "SIGKILL")).pipe(
838
+ Effect.ignore,
839
+ ),
840
+ )
841
+ const ready = yield* Deferred.make<void>()
842
+ // Stdin EOF exits the wrapper, but its ready descendant ignores SIGTERM and retains both pipes.
843
+ const transport = yield* McpStdio.make({
844
+ server: "held-stdio",
845
+ command: "node",
846
+ args: [path.join(import.meta.dir, "fixture/held-stdio.cjs"), "mcp", pidFile],
847
+ cwd: tmp.path,
848
+ environment: {},
849
+ })
850
+ transport.onmessage = () => {
851
+ Deferred.doneUnsafe(ready, Exit.void)
852
+ }
853
+ yield* Effect.promise(() => transport.start())
854
+ yield* Deferred.await(ready).pipe(Effect.timeout("3 seconds"))
855
+ const pid = Number(yield* Effect.promise(() => fs.readFile(pidFile, "utf8")))
856
+
857
+ yield* Effect.promise(() => transport.close()).pipe(Effect.timeout("6 seconds"))
858
+
859
+ // close() must kill the descendant, not merely observe the wrapper's bounded exitCode.
860
+ const stopped = yield* Effect.try(() => process.kill(pid, 0)).pipe(
861
+ Effect.exit,
862
+ Effect.repeat({ while: Exit.isSuccess, schedule: Schedule.spaced("25 millis") }),
863
+ Effect.timeout("2 seconds"),
864
+ )
865
+ expect(Exit.isFailure(stopped)).toBe(true)
866
+ }),
867
+ 15_000,
868
+ )
869
+
870
+ test("closes a stdio process that finishes spawning after close", async () => {
871
+ const spawning = Deferred.makeUnsafe<void>()
872
+ const release = Deferred.makeUnsafe<void>()
873
+ const exited = Deferred.makeUnsafe<ExitCode>()
874
+ const signals: Array<string> = []
875
+ const driver = Environment.makeMemoryDriver()
876
+ const environment = Layer.succeed(
877
+ Environment.Service,
878
+ Environment.Service.of({
879
+ id: Environment.localID,
880
+ local: true,
881
+ files: Environment.makeFiles(driver),
882
+ spawner: ChildProcessSpawner.make(() =>
883
+ Effect.gen(function* () {
884
+ yield* Deferred.succeed(spawning, undefined)
885
+ yield* Deferred.await(release)
886
+ return makeHandle({
887
+ pid: ProcessId(1),
888
+ exitCode: Deferred.await(exited),
889
+ isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
890
+ kill: (options) =>
891
+ Effect.gen(function* () {
892
+ signals.push(options?.killSignal ?? "SIGTERM")
893
+ yield* Deferred.succeed(exited, ExitCode(143))
894
+ }),
895
+ stdin: Sink.drain,
896
+ stdout: Stream.never,
897
+ stderr: Stream.empty,
898
+ all: Stream.never,
899
+ getInputFd: () => Sink.drain,
900
+ getOutputFd: () => Stream.empty,
901
+ unref: Effect.succeed(Effect.void),
902
+ })
903
+ }),
904
+ ),
905
+ }),
906
+ )
907
+
908
+ await Effect.runPromise(
909
+ Effect.scoped(
910
+ Effect.gen(function* () {
911
+ const transport = yield* McpStdio.make({
912
+ server: "close-during-spawn",
913
+ command: "unused",
914
+ args: [],
915
+ cwd: import.meta.dir,
916
+ environment: {},
917
+ })
918
+ const start = transport.start()
919
+ yield* Deferred.await(spawning)
920
+ const close = transport.close()
921
+ yield* Deferred.succeed(release, undefined)
922
+ yield* Effect.promise(() => Promise.all([start, close]))
923
+ }).pipe(Effect.provide(environment)),
924
+ ),
925
+ )
926
+
927
+ expect(signals).toEqual(["SIGTERM"])
928
+ })
929
+
930
+ test("falls back to legacy when a stdio server ignores the version probe", async () => {
931
+ const result = await Effect.runPromise(
932
+ Effect.scoped(
933
+ Effect.gen(function* () {
934
+ const connection = yield* connect(
935
+ "legacy-silent",
936
+ new ConfigMCP.Local({
937
+ type: "local",
938
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-legacy-silent.ts")],
939
+ protocol: "auto",
940
+ // The probe waits out the startup timeout, when shorter than the probe's own, before falling back; Windows needs room to start Bun.
941
+ timeout: new ConfigMCP.Timeout({ startup: 1_000 }),
942
+ }),
943
+ import.meta.dir,
944
+ )
945
+ return { modern: connection.modern, tools: yield* connection.tools() }
946
+ }),
947
+ ),
948
+ )
949
+
950
+ expect(result.modern).toBe(false)
951
+ expect(result.tools.map((tool) => tool.name)).toEqual(["echo"])
952
+ })
953
+
954
+ test("applies the configured MCP catalog timeout", async () => {
955
+ const result = Effect.runPromise(
956
+ Effect.scoped(
957
+ Effect.gen(function* () {
958
+ const connection = yield* connect(
959
+ "catalog-timeout",
960
+ new ConfigMCP.Local({
961
+ type: "local",
962
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-timeout.ts")],
963
+ environment: { MCP_TIMEOUT_TARGET: "catalog" },
964
+ timeout: new ConfigMCP.Timeout({ catalog: 10 }),
965
+ }),
966
+ import.meta.dir,
967
+ )
968
+ return yield* connection.tools()
969
+ }),
970
+ ),
971
+ )
972
+
973
+ await expect(result).rejects.toThrow("Request timed out")
974
+ })
975
+
976
+ test("applies the configured MCP execution timeout", async () => {
977
+ const result = Effect.runPromise(
978
+ Effect.scoped(
979
+ Effect.gen(function* () {
980
+ const connection = yield* connect(
981
+ "execution-timeout",
982
+ new ConfigMCP.Local({
983
+ type: "local",
984
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-timeout.ts")],
985
+ timeout: new ConfigMCP.Timeout({ execution: 10 }),
986
+ }),
987
+ import.meta.dir,
988
+ )
989
+ return yield* connection.callTool({ name: "slow" })
990
+ }),
991
+ ),
992
+ )
993
+
994
+ await expect(result).rejects.toThrow("Request timed out")
995
+ })
996
+
997
+ test("applies the configured MCP execution timeout to prompts", async () => {
998
+ const result = Effect.runPromise(
999
+ Effect.scoped(
1000
+ Effect.gen(function* () {
1001
+ const connection = yield* connect(
1002
+ "prompt-timeout",
1003
+ new ConfigMCP.Local({
1004
+ type: "local",
1005
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-timeout.ts")],
1006
+ timeout: new ConfigMCP.Timeout({ execution: 10 }),
1007
+ }),
1008
+ import.meta.dir,
1009
+ )
1010
+ return yield* connection.prompt({ name: "slow" })
1011
+ }),
1012
+ ),
1013
+ )
1014
+
1015
+ await expect(result).rejects.toThrow("Request timed out")
1016
+ })
1017
+
1018
+ test("applies configured MCP timeouts to resource operations", async () => {
1019
+ const catalog = Effect.runPromise(
1020
+ Effect.scoped(
1021
+ Effect.gen(function* () {
1022
+ const connection = yield* connect(
1023
+ "resource-catalog-timeout",
1024
+ new ConfigMCP.Local({
1025
+ type: "local",
1026
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-timeout.ts")],
1027
+ environment: { MCP_TIMEOUT_TARGET: "resource-catalog" },
1028
+ timeout: new ConfigMCP.Timeout({ catalog: 10 }),
1029
+ }),
1030
+ import.meta.dir,
1031
+ )
1032
+ return yield* connection.resources()
1033
+ }),
1034
+ ),
1035
+ )
1036
+ await expect(catalog).rejects.toThrow("Request timed out")
1037
+
1038
+ const read = Effect.runPromise(
1039
+ Effect.scoped(
1040
+ Effect.gen(function* () {
1041
+ const connection = yield* connect(
1042
+ "resource-read-timeout",
1043
+ new ConfigMCP.Local({
1044
+ type: "local",
1045
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-timeout.ts")],
1046
+ timeout: new ConfigMCP.Timeout({ execution: 10 }),
1047
+ }),
1048
+ import.meta.dir,
1049
+ )
1050
+ return yield* connection.readResource({ uri: "test://slow" })
1051
+ }),
1052
+ ),
1053
+ )
1054
+ await expect(read).rejects.toThrow("Request timed out")
1055
+ })
1056
+
1057
+ for (const entry of [
1058
+ { name: "direct tools", query: "", codemode: false, expected: "" },
1059
+ { name: "explicit remote code mode", query: "?codemode=true", codemode: undefined, expected: "?codemode=true" },
1060
+ ]) {
1061
+ testEffect(Layer.empty).live(`remote MCP code mode preference: ${entry.name}`, () =>
1062
+ Effect.gen(function* () {
1063
+ const server = yield* resourceServer()
1064
+ const config = new ConfigMCP.Remote({
1065
+ type: "remote",
1066
+ url: server.url + entry.query,
1067
+ oauth: false,
1068
+ codemode: entry.codemode,
1069
+ })
1070
+ const connection = yield* connect("resources", config, import.meta.dir)
1071
+ yield* connection.tools()
1072
+ expect(server.state.initializations).toBe(1)
1073
+ expect(server.state.toolLists).toBe(1)
1074
+ expect(server.state.urls.length).toBeGreaterThanOrEqual(3)
1075
+ expect(new Set(server.state.urls)).toEqual(new Set([server.url + entry.expected]))
1076
+ expect(config.url).toBe(server.url + entry.query)
1077
+ }),
1078
+ )
1079
+ }
1080
+
1081
+ for (const entry of [
1082
+ { name: "401", status: 401, query: "", codemode: undefined, attempts: 1 },
1083
+ { name: "403", status: 403, query: "", codemode: undefined, attempts: 1 },
1084
+ { name: "501", status: 501, query: "", codemode: undefined, attempts: 1 },
1085
+ { name: "user codemode=true", status: 404, query: "?codemode=true", codemode: undefined, attempts: 1 },
1086
+ { name: "direct tools", status: 404, query: "", codemode: false, attempts: 1 },
1087
+ { name: "400 with user codemode=true", status: 400, query: "?codemode=true", codemode: undefined, attempts: 1 },
1088
+ ]) {
1089
+ testEffect(Layer.empty).live(`does not retry MCP beyond the query fallback: ${entry.name}`, () =>
1090
+ Effect.gen(function* () {
1091
+ const server = yield* resourceServer({
1092
+ respond: () => new Response(null, { status: entry.status }),
1093
+ })
1094
+ const config = new ConfigMCP.Remote({
1095
+ type: "remote",
1096
+ url: server.url + entry.query,
1097
+ codemode: entry.codemode,
1098
+ oauth: false,
1099
+ protocol: "legacy",
1100
+ })
1101
+ const error = yield* connect("resources", config, import.meta.dir).pipe(Effect.flip)
1102
+
1103
+ expect(error).toBeInstanceOf(McpClient.ConnectError)
1104
+ expect(server.state.initializations).toBe(entry.attempts)
1105
+ expect(server.state.urls).toHaveLength(entry.attempts)
1106
+ if (entry.query || entry.codemode === false) expect(server.state.urls).toEqual([config.url])
1107
+ }),
1108
+ )
1109
+ }
1110
+
1111
+ test("reconnects and retries a tool call after the MCP session expires", async () => {
1112
+ await Effect.runPromise(
1113
+ Effect.scoped(
1114
+ Effect.gen(function* () {
1115
+ const server = yield* resourceServer()
1116
+ yield* Effect.gen(function* () {
1117
+ const service = yield* Mcp.Service
1118
+ yield* service.callTool({ server: "resources", name: "echo", args: { n: 1 } })
1119
+ expect(server.state.toolCalls).toHaveLength(1)
1120
+ expect(server.state.initializations).toBe(1)
1121
+
1122
+ // The restarted server does not know the client's session, so the next request 404s.
1123
+ yield* Effect.promise(server.restart)
1124
+ const result = yield* service.callTool({ server: "resources", name: "echo", args: { n: 2 } })
1125
+
1126
+ expect(result.isError).toBe(false)
1127
+ expect(server.state.toolCalls.map((call) => call.arguments)).toEqual([{ n: 1 }, { n: 2 }])
1128
+ expect(server.state.initializations).toBe(2)
1129
+ expect(server.state.sessions).toHaveLength(2)
1130
+ expect((yield* service.servers()).find((entry) => entry.name === "resources")).toMatchObject({
1131
+ status: { status: "connected" },
1132
+ title: "MCP Resources",
1133
+ })
1134
+ }).pipe(Effect.provide(resourceMcpLayer(server.url)))
1135
+ }),
1136
+ ),
1137
+ )
1138
+ })
1139
+
1140
+ describe.each([
1141
+ ["legacy", undefined],
1142
+ ["modern", "2026-07-28"],
1143
+ ] as const)("MCP connection over the %s protocol", (era, protocol) => {
1144
+ test("exposes every connection operation", async () => {
1145
+ await Effect.runPromise(
1146
+ Effect.scoped(
1147
+ Effect.gen(function* () {
1148
+ const server = yield* resourceServer({ modern: era === "modern", listChanged: true })
1149
+ server.state.resources = [{ name: "Readme", uri: "docs://readme" }]
1150
+ server.state.templates = [{ name: "File", uriTemplate: "docs://{path}" }]
1151
+ const connection = yield* connect(
1152
+ "resources",
1153
+ new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, protocol }),
1154
+ import.meta.dir,
1155
+ )
1156
+
1157
+ expect(connection.modern).toBe(era === "modern")
1158
+ expect(connection.title).toBe("MCP Resources")
1159
+ expect(connection.instructions).toBe("Use the resources tools.")
1160
+ expect((yield* connection.tools()).map((tool) => tool.name)).toEqual(["echo"])
1161
+ expect((yield* connection.prompts()).map((prompt) => prompt.name)).toEqual(["greet"])
1162
+ expect((yield* connection.resources()).map((resource) => resource.uri)).toEqual(["docs://readme"])
1163
+ expect((yield* connection.resourceTemplates()).map((template) => template.uriTemplate)).toEqual([
1164
+ "docs://{path}",
1165
+ ])
1166
+ expect((yield* connection.readResource({ uri: "docs://readme" }))?.contents).toHaveLength(2)
1167
+ expect((yield* connection.prompt({ name: "greet", args: { name: "bob" } })).messages[0]?.content).toEqual({
1168
+ type: "text",
1169
+ text: "hi bob",
1170
+ })
1171
+ const sessionID = Session.ID.make("ses_mcp_era")
1172
+ yield* connection.callTool({ name: "echo", args: { text: "hi" }, sessionID })
1173
+ expect(server.state.toolCalls.at(-1)).toMatchObject({ name: "echo", sessionID })
1174
+
1175
+ const changed = yield* Deferred.make<void>()
1176
+ connection.onResourcesChanged(() => Deferred.doneUnsafe(changed, Exit.void))
1177
+ yield* Effect.promise(server.sendResourceListChanged)
1178
+ yield* Deferred.await(changed)
1179
+ }),
1180
+ ),
1181
+ )
1182
+ })
1183
+
1184
+ test("skips unusable tools and keeps the rest of the server's tools", async () => {
1185
+ await Effect.runPromise(
1186
+ Effect.scoped(
1187
+ Effect.gen(function* () {
1188
+ const server = yield* resourceServer({ modern: era === "modern", resources: false, malformedTool: true })
1189
+ const connection = yield* connect(
1190
+ "malformed",
1191
+ new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, protocol }),
1192
+ import.meta.dir,
1193
+ )
1194
+
1195
+ const tools = yield* connection.tools()
1196
+ expect(tools.map((tool) => tool.name)).toEqual(["bad-required", "bad-fields", "full", "echo"])
1197
+ // A malformed optional field or top-level `required` is dropped, not the tool. Valid fields are
1198
+ // kept except icons; a modern server's SDK strips `execution` before sending.
1199
+ expect(tools.slice(0, 3)).toEqual([
1200
+ { name: "bad-required", inputSchema: { type: "object" } },
1201
+ { name: "bad-fields", inputSchema: { type: "object" } },
1202
+ {
1203
+ name: "full",
1204
+ title: "Full",
1205
+ description: "Every field",
1206
+ inputSchema: { type: "object" },
1207
+ annotations: { readOnlyHint: true },
1208
+ ...(era === "legacy" ? { execution: { taskSupport: "optional" } } : {}),
1209
+ _meta: { "example/key": 1 },
1210
+ },
1211
+ ])
1212
+ for (const name of ["bad-required", "bad-fields", "full", "echo"]) {
1213
+ yield* connection.callTool({ name, args: { text: "hi" } })
1214
+ expect(server.state.toolCalls.at(-1)).toMatchObject({ name, arguments: { text: "hi" } })
1215
+ }
1216
+ }),
1217
+ ),
1218
+ )
1219
+ })
1220
+
1221
+ test("returns results that miss or break the called tool's output schema", async () => {
1222
+ await Effect.runPromise(
1223
+ Effect.scoped(
1224
+ Effect.gen(function* () {
1225
+ const server = yield* resourceServer({
1226
+ modern: era === "modern",
1227
+ resources: false,
1228
+ tools: [
1229
+ // Zoom's meeting_delete declares an empty object and returns nothing for the REST API's 204.
1230
+ { name: "delete", inputSchema: { type: "object" }, outputSchema: { type: "object", properties: {} } },
1231
+ {
1232
+ name: "collaborators",
1233
+ inputSchema: { type: "object" },
1234
+ outputSchema: {
1235
+ type: "object",
1236
+ properties: { role: { type: "string", enum: ["owner", "editor"] } },
1237
+ required: ["role"],
1238
+ },
1239
+ },
1240
+ ],
1241
+ })
1242
+ const connection = yield* connect(
1243
+ "lenient",
1244
+ new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, protocol }),
1245
+ import.meta.dir,
1246
+ )
1247
+ yield* connection.tools()
1248
+
1249
+ expect(yield* connection.callTool({ name: "delete", args: { text: "Meeting deleted." } })).toEqual({
1250
+ isError: false,
1251
+ structured: undefined,
1252
+ content: [{ type: "text", text: "Meeting deleted." }],
1253
+ })
1254
+ expect(yield* connection.callTool({ name: "delete" })).toEqual({
1255
+ isError: false,
1256
+ structured: undefined,
1257
+ content: [],
1258
+ })
1259
+ expect(
1260
+ yield* connection.callTool({ name: "collaborators", args: { structured: { role: "commenter" } } }),
1261
+ ).toMatchObject({ isError: false, structured: { role: "commenter" } })
1262
+ expect(server.state.toolCalls.map((call) => call.name)).toEqual(["delete", "delete", "collaborators"])
1263
+ }),
1264
+ ),
1265
+ )
1266
+ })
1267
+ })
1268
+
1269
+ test("retries a modern MCP tool call whose listed header declaration went stale", async () => {
1270
+ await Effect.runPromise(
1271
+ Effect.scoped(
1272
+ Effect.gen(function* () {
1273
+ const region = { type: "string" as const, "x-mcp-header": "Region" }
1274
+ const rejected: Array<string | null> = []
1275
+ const server = yield* resourceServer({
1276
+ modern: true,
1277
+ resources: false,
1278
+ tools: [{ name: "regional", inputSchema: { type: "object", properties: { region } } }],
1279
+ // Stands in for the server-side check: the region must arrive in the currently declared header.
1280
+ respond: async (request) => {
1281
+ const body: unknown = request.method === "POST" ? await request.clone().json() : undefined
1282
+ if (!isJSONRPCRequest(body) || body.method !== "tools/call") return undefined
1283
+ if (request.headers.get(`mcp-param-${region["x-mcp-header"]}`) === "eu") return undefined
1284
+ rejected.push(request.headers.get("mcp-param-region"))
1285
+ return Response.json(
1286
+ { jsonrpc: "2.0", id: body.id, error: { code: -32020, message: "Header mismatch" } },
1287
+ { status: 400 },
1288
+ )
1289
+ },
1290
+ })
1291
+ const connection = yield* connect(
1292
+ "regional",
1293
+ new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, protocol: "2026-07-28" }),
1294
+ import.meta.dir,
1295
+ )
1296
+ yield* connection.tools()
1297
+ region["x-mcp-header"] = "Zone"
1298
+
1299
+ expect((yield* connection.callTool({ name: "regional", args: { region: "eu" } })).isError).toBe(false)
1300
+ expect(server.state.toolCalls.map((call) => call.arguments)).toEqual([{ region: "eu" }])
1301
+ // The stale Region header is rejected once; the relisted definition then sends Zone.
1302
+ expect(rejected).toEqual(["eu"])
1303
+ expect(server.state.toolLists).toBe(2)
1304
+ }),
1305
+ ),
1306
+ )
1307
+ })
1308
+
1309
+ test("does not reconnect an SSE stream after a JSON-RPC error response", async () => {
1310
+ let requests = 0
1311
+ const transport = new StreamableHTTPClientTransport(new URL("http://mcp.invalid"), {
1312
+ fetch: async () => {
1313
+ requests += 1
1314
+ return new Response(
1315
+ new ReadableStream({
1316
+ start(controller) {
1317
+ controller.enqueue(new TextEncoder().encode("id: prime\nretry: 1\ndata:\n\n"))
1318
+ controller.enqueue(
1319
+ new TextEncoder().encode(
1320
+ 'id: error\ndata: {"jsonrpc":"2.0","error":{"code":-32601,"message":"Method not found"},"id":1}\n\n',
1321
+ ),
1322
+ )
1323
+ controller.close()
1324
+ },
1325
+ }),
1326
+ { status: 200, headers: { "content-type": "text/event-stream" } },
1327
+ )
1328
+ },
1329
+ reconnectionOptions: {
1330
+ initialReconnectionDelay: 1,
1331
+ maxReconnectionDelay: 1,
1332
+ reconnectionDelayGrowFactor: 1,
1333
+ maxRetries: 2,
1334
+ },
1335
+ })
1336
+
1337
+ await transport.start()
1338
+ await transport.send({ jsonrpc: "2.0", method: "resources/list", id: 1 })
1339
+ await Bun.sleep(25)
1340
+ await transport.close()
1341
+
1342
+ expect(requests).toBe(1)
1343
+ })
1344
+
1345
+ test("skips MCP resource requests when the capability is absent", async () => {
1346
+ await Effect.runPromise(
1347
+ Effect.scoped(
1348
+ Effect.gen(function* () {
1349
+ const server = yield* resourceServer({ resources: false })
1350
+ const connection = yield* connect(
1351
+ "resources",
1352
+ new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false }),
1353
+ import.meta.dir,
1354
+ )
1355
+ expect(yield* connection.resources()).toEqual([])
1356
+ expect(yield* connection.resourceTemplates()).toEqual([])
1357
+ expect(yield* connection.readResource({ uri: "docs://readme" })).toBeUndefined()
1358
+ expect({ resources: server.state.resourceLists, templates: server.state.templateLists }).toEqual({
1359
+ resources: 0,
1360
+ templates: 0,
1361
+ })
1362
+ }),
1363
+ ),
1364
+ )
1365
+ })
1366
+
1367
+ type CreatedForm = { readonly form: Form.Info; readonly directory: string | undefined }
1368
+
1369
+ // Clients drop `form.created` events without a Location, so the form must be published inside the server's Location.
1370
+ const recordForm = (created: Deferred.Deferred<CreatedForm>, form: Form.Info) =>
1371
+ Effect.serviceOption(Location.Service).pipe(
1372
+ Effect.flatMap((location) =>
1373
+ Deferred.succeed(created, { form, directory: Option.getOrUndefined(location)?.directory }),
1374
+ ),
1375
+ Effect.asVoid,
1376
+ )
1377
+
1378
+ test("accepts empty MCP elicitations without creating forms", async () => {
1379
+ await Effect.runPromise(
1380
+ Effect.scoped(
1381
+ Effect.gen(function* () {
1382
+ const server = yield* resourceServer({ resources: false, emptyElicitation: true })
1383
+ const result = yield* Effect.gen(function* () {
1384
+ const service = yield* Mcp.Service
1385
+ const forms = yield* Form.Service
1386
+ const result = yield* service.callTool({ server: "resources", name: "empty-elicitation" })
1387
+ expect(yield* forms.list()).toEqual([])
1388
+ return result
1389
+ }).pipe(Effect.provide(resourceMcpLayer(server.url)))
1390
+
1391
+ expect(result.structured).toEqual({ action: "accept", content: {} })
1392
+ }),
1393
+ ),
1394
+ )
1395
+ })
1396
+
1397
+ test("acknowledges completed MCP URL elicitations without returning internal content", async () => {
1398
+ await Effect.runPromise(
1399
+ Effect.scoped(
1400
+ Effect.gen(function* () {
1401
+ const server = yield* resourceServer({ resources: false, urlElicitation: true })
1402
+ const created = yield* Deferred.make<CreatedForm>()
1403
+ const result = yield* Effect.gen(function* () {
1404
+ const service = yield* Mcp.Service
1405
+ const forms = yield* Form.Service
1406
+ const call = yield* service.callTool({ server: "resources", name: "url-elicitation" }).pipe(Effect.forkScoped)
1407
+
1408
+ const { form, directory } = yield* Deferred.await(created)
1409
+ expect(directory).toBe(import.meta.dir)
1410
+ expect(form.fields).toEqual([{ key: "elicitation", type: "external", url: "https://example.com/authorize" }])
1411
+
1412
+ yield* Effect.promise(server.completeElicitation)
1413
+ const result = yield* Fiber.join(call)
1414
+ expect(yield* forms.state(form.id)).toEqual({ status: "answered", answer: { elicitation: true } })
1415
+ return result
1416
+ }).pipe(Effect.provide(resourceMcpLayer(server.url, (form) => recordForm(created, form))))
1417
+
1418
+ expect(result.structured).toEqual({ action: "accept" })
1419
+ }),
1420
+ ),
1421
+ )
1422
+ })
1423
+
1424
+ test("cancels MCP elicitation forms when the server gives up on them", async () => {
1425
+ await Effect.runPromise(
1426
+ Effect.scoped(
1427
+ Effect.gen(function* () {
1428
+ const server = yield* resourceServer({ resources: false, urlElicitation: true, elicitationTimeout: 200 })
1429
+ const created = yield* Deferred.make<CreatedForm>()
1430
+ yield* Effect.gen(function* () {
1431
+ const service = yield* Mcp.Service
1432
+ const forms = yield* Form.Service
1433
+ const call = yield* service.callTool({ server: "resources", name: "url-elicitation" }).pipe(Effect.forkScoped)
1434
+ const { form } = yield* Deferred.await(created)
1435
+ yield* Fiber.await(call)
1436
+ // The server's cancellation and its tool error race; the form settles shortly after either.
1437
+ const state = yield* forms
1438
+ .state(form.id)
1439
+ .pipe(
1440
+ Effect.repeat({ until: (state) => state.status !== "pending", schedule: Schedule.spaced("10 millis") }),
1441
+ Effect.timeout("2 seconds"),
1442
+ )
1443
+ expect(state.status).toBe("cancelled")
1444
+ }).pipe(Effect.provide(resourceMcpLayer(server.url, (form) => recordForm(created, form))))
1445
+ }),
1446
+ ),
1447
+ )
1448
+ })
1449
+
1450
+ test("settles modern MCP URL elicitations when the user confirms", async () => {
1451
+ await Effect.runPromise(
1452
+ Effect.scoped(
1453
+ Effect.gen(function* () {
1454
+ const server = yield* resourceServer({ modern: true, resources: false, urlElicitation: true })
1455
+ const created = yield* Deferred.make<CreatedForm>()
1456
+ const result = yield* Effect.gen(function* () {
1457
+ const service = yield* Mcp.Service
1458
+ const forms = yield* Form.Service
1459
+ const call = yield* service.callTool({ server: "resources", name: "url-elicitation" }).pipe(Effect.forkScoped)
1460
+
1461
+ const { form, directory } = yield* Deferred.await(created)
1462
+ expect(directory).toBe(import.meta.dir)
1463
+ expect(form.metadata).not.toHaveProperty("elicitationID")
1464
+ yield* forms.reply({ id: form.id, answer: { elicitation: true } })
1465
+ return yield* Fiber.join(call)
1466
+ }).pipe(
1467
+ Effect.provide(
1468
+ resourceMcpLayer(
1469
+ new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, protocol: "2026-07-28" }),
1470
+ (form) => recordForm(created, form),
1471
+ ),
1472
+ ),
1473
+ )
1474
+
1475
+ expect(result.structured).toEqual({ action: "accept" })
1476
+ }),
1477
+ ),
1478
+ )
1479
+ })
1480
+
1481
+ test("loads and reads MCP resources", async () => {
1482
+ await Effect.runPromise(
1483
+ Effect.scoped(
1484
+ Effect.gen(function* () {
1485
+ const server = yield* resourceServer()
1486
+ server.state.resources = [{ name: "Readme", uri: "docs://readme" }]
1487
+ server.state.templates = [{ name: "File", uriTemplate: "docs://{path}" }]
1488
+
1489
+ yield* Effect.gen(function* () {
1490
+ const service = yield* Mcp.Service
1491
+ yield* settled(service)
1492
+ expect(yield* service.resourceCatalog()).toEqual({
1493
+ resources: [
1494
+ {
1495
+ server: "resources",
1496
+ name: "Readme",
1497
+ uri: "docs://readme",
1498
+ description: undefined,
1499
+ mimeType: undefined,
1500
+ },
1501
+ ],
1502
+ templates: [
1503
+ {
1504
+ server: "resources",
1505
+ name: "File",
1506
+ uriTemplate: "docs://{path}",
1507
+ description: undefined,
1508
+ mimeType: undefined,
1509
+ },
1510
+ ],
1511
+ })
1512
+
1513
+ server.state.resources = [{ name: "Guide", uri: "docs://guide" }]
1514
+ expect((yield* service.resourceCatalog()).resources.map((resource) => resource.uri)).toEqual(["docs://guide"])
1515
+ expect(yield* service.readResource({ server: "resources", uri: "docs://readme" })).toEqual({
1516
+ server: "resources",
1517
+ uri: "docs://readme",
1518
+ contents: [
1519
+ { type: "text", uri: "docs://readme", text: "hello", mimeType: "text/plain" },
1520
+ { type: "blob", uri: "docs://logo", blob: "aGVsbG8=", mimeType: "image/png" },
1521
+ ],
1522
+ })
1523
+ expect(server.clientVersion()).toMatchObject({ name: "sdk", version: "1.2.3" })
1524
+ }).pipe(
1525
+ Effect.provide(resourceMcpLayer(server.url, undefined, { clientInfo: { name: "sdk", version: "1.2.3" } })),
1526
+ )
1527
+ }),
1528
+ ),
1529
+ )
1530
+ })
1531
+
1532
+ it.live("discovers and reads MCP resources through Code Mode", () =>
1533
+ Effect.gen(function* () {
1534
+ assertion = yield* Deferred.make<Permission.AssertInput>()
1535
+ decision = Effect.void
1536
+ const server = yield* resourceServer()
1537
+ server.state.resourcePages = {
1538
+ initial: { items: [{ name: "Readme", uri: "docs://readme" }], nextCursor: "resources-2" },
1539
+ "resources-2": { items: [{ name: "Guide", uri: "docs://guide" }] },
1540
+ }
1541
+ server.state.templatePages = {
1542
+ initial: { items: [{ name: "File", uriTemplate: "docs://{path}" }], nextCursor: "templates-2" },
1543
+ "templates-2": { items: [{ name: "Issue", uriTemplate: "issue://{id}" }] },
1544
+ }
1545
+
1546
+ yield* Effect.gen(function* () {
1547
+ const mcp = yield* Mcp.Service
1548
+ yield* settled(mcp)
1549
+ yield* registerToolPlugin(McpResourceTools.Plugin).pipe(Effect.provide(permissions))
1550
+ const tools = yield* Tool.Service
1551
+ const snapshot = yield* tools.snapshot()
1552
+ const sessionID = Session.ID.make("ses_resource_tools")
1553
+ const run = (code: string) =>
1554
+ snapshot.execute({
1555
+ sessionID,
1556
+ ...toolIdentity,
1557
+ call: { type: "tool-call", id: "call_resource", name: "execute", input: { code } },
1558
+ })
1559
+
1560
+ // The SDK walks every page, so one call returns the full catalog.
1561
+ const listed = yield* run('return await tools.opencode.list_mcp_resources({ server: "resources" })')
1562
+ expect(JSON.parse(listed.output.output)).toEqual({
1563
+ resources: [
1564
+ { server: "resources", name: "Guide", uri: "docs://guide" },
1565
+ { server: "resources", name: "Readme", uri: "docs://readme" },
1566
+ ],
1567
+ templates: [
1568
+ { server: "resources", name: "File", uriTemplate: "docs://{path}" },
1569
+ { server: "resources", name: "Issue", uriTemplate: "issue://{id}" },
1570
+ ],
1571
+ })
1572
+ expect(server.state.resourceReads).toEqual([])
1573
+
1574
+ // Omitting the server lists every server, so the model can find which one owns a URI.
1575
+ assertion = yield* Deferred.make<Permission.AssertInput>()
1576
+ const everywhere = yield* run("return await tools.opencode.list_mcp_resources({})")
1577
+ expect(yield* Deferred.await(assertion)).toMatchObject({
1578
+ action: "opencode_list_mcp_resources",
1579
+ resources: ["resources"],
1580
+ save: ["resources"],
1581
+ })
1582
+ expect(JSON.parse(everywhere.output.output)).toEqual({
1583
+ resources: [
1584
+ { server: "resources", name: "Guide", uri: "docs://guide" },
1585
+ { server: "resources", name: "Readme", uri: "docs://readme" },
1586
+ ],
1587
+ templates: [
1588
+ { server: "resources", name: "File", uriTemplate: "docs://{path}" },
1589
+ { server: "resources", name: "Issue", uriTemplate: "issue://{id}" },
1590
+ ],
1591
+ })
1592
+
1593
+ // A server may declare resources without implementing template listing.
1594
+ server.state.templatesUnsupported = true
1595
+ const untemplated = yield* run('return await tools.opencode.list_mcp_resources({ server: "resources" })')
1596
+ expect(JSON.parse(untemplated.output.output)).toEqual({
1597
+ resources: [
1598
+ { server: "resources", name: "Guide", uri: "docs://guide" },
1599
+ { server: "resources", name: "Readme", uri: "docs://readme" },
1600
+ ],
1601
+ templates: [],
1602
+ })
1603
+ server.state.templatesUnsupported = false
1604
+
1605
+ assertion = yield* Deferred.make<Permission.AssertInput>()
1606
+ const read = yield* run(
1607
+ 'const resource = await tools.opencode.read_mcp_resource({ server: "resources", uri: "docs://readme" }); return resource.contents.filter(part => part.type === "text").map(part => part.text).join("\\n")',
1608
+ )
1609
+ expect(read.content).toEqual([
1610
+ { type: "text", text: "hello" },
1611
+ { type: "file", uri: "data:image/png;base64,aGVsbG8=", mime: "image/png" },
1612
+ ])
1613
+ expect(read.metadata?.toolCalls).toMatchObject([
1614
+ {
1615
+ tool: "opencode.read_mcp_resource",
1616
+ status: "completed",
1617
+ input: { server: "resources", uri: "docs://readme" },
1618
+ },
1619
+ ])
1620
+ expect(server.state.resourceReads).toEqual(["docs://readme"])
1621
+ expect(yield* Deferred.await(assertion)).toEqual({
1622
+ action: "opencode_read_mcp_resource",
1623
+ resources: ["resources:docs://readme"],
1624
+ save: ["resources:*"],
1625
+ metadata: { server: "resources", uri: "docs://readme" },
1626
+ sessionID,
1627
+ agent: toolIdentity.agent,
1628
+ // The call's own ID. The real service shows the request on the execute call's row.
1629
+ source: { type: "tool", messageID: toolIdentity.messageID, id: expect.not.stringMatching(/^call_resource$/) },
1630
+ })
1631
+
1632
+ server.state.contents = [{ uri: "docs://readme", text: "line\n".repeat(20_000), mimeType: "text/plain" }]
1633
+ const large = yield* run(
1634
+ 'const resource = await tools.opencode.read_mcp_resource({ server: "resources", uri: "docs://readme" }); return resource.contents[0].text',
1635
+ )
1636
+ const bounded = yield* ToolOutput.Service.use((output) => output.truncate(large)).pipe(
1637
+ Effect.provide(AppNodeBuilder.build(ToolOutput.node)),
1638
+ )
1639
+ expect(bounded.metadata?.truncated).toBe(true)
1640
+ expect(bounded.content[0]).toMatchObject({ type: "text" })
1641
+ const outputPath = bounded.metadata?.outputPath
1642
+ expect(typeof outputPath).toBe("string")
1643
+ if (typeof outputPath !== "string") throw new Error("Missing full resource output")
1644
+ expect(yield* Effect.promise(() => Bun.file(outputPath).text())).toBe("line\n".repeat(20_000))
1645
+
1646
+ // An empty contents array means the resource exists without content, not that it is missing.
1647
+ server.state.contents = []
1648
+ const empty = yield* run(
1649
+ 'return await tools.opencode.read_mcp_resource({ server: "resources", uri: "docs://empty" })',
1650
+ )
1651
+ expect(empty.metadata?.error).toBeUndefined()
1652
+ expect(JSON.parse(empty.output.output)).toEqual({ server: "resources", uri: "docs://empty", contents: [] })
1653
+ server.state.missing = ["docs://gone"]
1654
+ const gone = yield* run(
1655
+ 'return await tools.opencode.read_mcp_resource({ server: "resources", uri: "docs://gone" })',
1656
+ )
1657
+ expect(gone.metadata?.error).toBe(true)
1658
+ expect(gone.output.output).toContain("Resource not found")
1659
+ const missing = yield* run(
1660
+ 'return await tools.opencode.read_mcp_resource({ server: "missing", uri: "docs://readme" })',
1661
+ )
1662
+ expect(missing.metadata?.error).toBe(true)
1663
+ expect(missing.output.output).toContain("MCP server not found: missing")
1664
+
1665
+ const reads = server.state.resourceReads.length
1666
+ decision = Effect.fail(
1667
+ new Permission.BlockedError({ rules: [], permission: "opencode_read_mcp_resource", resources: ["*"] }),
1668
+ )
1669
+ const denied = yield* run(
1670
+ 'return await tools.opencode.read_mcp_resource({ server: "resources", uri: "docs://denied" })',
1671
+ )
1672
+ expect(denied.metadata?.error).toBe(true)
1673
+ expect(server.state.resourceReads).toHaveLength(reads)
1674
+ }).pipe(Effect.provide(resourceMcpLayer(server.url)))
1675
+ }),
1676
+ )
1677
+
1678
+ test("adds, disconnects, and reconnects MCP servers at runtime", async () => {
1679
+ const published: string[] = []
1680
+ await Effect.runPromise(
1681
+ Effect.scoped(
1682
+ Effect.gen(function* () {
1683
+ const server = yield* resourceServer({ modern: true, resources: false })
1684
+ const config = { type: "remote", url: server.url, oauth: false, protocol: "2026-07-28" } as const
1685
+ yield* Effect.gen(function* () {
1686
+ const service = yield* Mcp.Service
1687
+
1688
+ expect((yield* service.servers())[0]?.status).toEqual({ status: "disabled" })
1689
+ expect(published).toContain(McpEvent.StatusChanged.type)
1690
+ expect(yield* service.connect("missing").pipe(Effect.flip)).toBeInstanceOf(Mcp.NotFoundError)
1691
+ expect(yield* service.disconnect("missing").pipe(Effect.flip)).toBeInstanceOf(Mcp.NotFoundError)
1692
+ yield* service.add("dynamic", new ConfigMCP.Remote(config))
1693
+ expect((yield* service.servers()).find((server) => server.name === "dynamic")?.status).toEqual({
1694
+ status: "connected",
1695
+ })
1696
+
1697
+ yield* service.add("dynamic", new ConfigMCP.Remote({ ...config, disabled: true }))
1698
+ expect((yield* service.servers()).find((server) => server.name === "dynamic")?.status).toEqual({
1699
+ status: "disabled",
1700
+ })
1701
+ expect(yield* service.tools()).toEqual([])
1702
+
1703
+ yield* service.connect("dynamic")
1704
+ expect((yield* service.servers()).find((server) => server.name === "dynamic")?.status).toEqual({
1705
+ status: "connected",
1706
+ })
1707
+ yield* service.disconnect("dynamic")
1708
+ expect((yield* service.servers()).find((server) => server.name === "dynamic")?.status).toEqual({
1709
+ status: "disabled",
1710
+ })
1711
+ expect(yield* service.tools()).toEqual([])
1712
+
1713
+ yield* service.connect("dynamic")
1714
+ expect((yield* service.servers()).find((server) => server.name === "dynamic")?.status).toEqual({
1715
+ status: "connected",
1716
+ })
1717
+
1718
+ yield* service.remove("dynamic")
1719
+ expect((yield* service.servers()).some((server) => server.name === "dynamic")).toBe(false)
1720
+ expect(yield* service.tools()).toEqual([])
1721
+ expect(yield* service.remove("dynamic").pipe(Effect.flip)).toBeInstanceOf(Mcp.NotFoundError)
1722
+ }).pipe(
1723
+ Effect.provide(
1724
+ resourceMcpLayer(
1725
+ new ConfigMCP.Local({ type: "local", command: ["unused"], disabled: true }),
1726
+ undefined,
1727
+ undefined,
1728
+ { published },
1729
+ ),
1730
+ ),
1731
+ )
1732
+ }),
1733
+ ),
1734
+ )
1735
+ })
1736
+
1737
+ test("marks a remote MCP server with an invalid URL as failed", async () => {
1738
+ await Effect.runPromise(
1739
+ Effect.scoped(
1740
+ Effect.gen(function* () {
1741
+ const server = yield* resourceServer({ modern: true, resources: false })
1742
+ const config = { type: "remote", url: server.url, oauth: false, protocol: "2026-07-28" } as const
1743
+ yield* Effect.gen(function* () {
1744
+ const service = yield* Mcp.Service
1745
+ const status = (name: string) =>
1746
+ service.servers().pipe(Effect.map((servers) => servers.find((server) => server.name === name)?.status))
1747
+ expect(yield* settled(service)).toEqual({ status: "connected" })
1748
+
1749
+ yield* service.add("broken", new ConfigMCP.Remote({ type: "remote", url: "not a url" }))
1750
+ expect(yield* status("broken")).toEqual({ status: "failed", error: "Invalid MCP server URL: not a url" })
1751
+ expect(yield* status("resources")).toEqual({ status: "connected" })
1752
+
1753
+ yield* service.add("broken", new ConfigMCP.Remote(config))
1754
+ expect(yield* status("broken")).toEqual({ status: "connected" })
1755
+ }).pipe(Effect.provide(resourceMcpLayer(new ConfigMCP.Remote(config))))
1756
+ }),
1757
+ ),
1758
+ )
1759
+ })
1760
+
1761
+ testEffect(Layer.empty).live(
1762
+ "merges MCP defaults into the winning configured server without changing runtime overrides",
1763
+ () =>
1764
+ Effect.gen(function* () {
1765
+ const entries = [
1766
+ new Document({
1767
+ type: "document",
1768
+ info: new Info({
1769
+ mcp: new ConfigMCP.Info({
1770
+ timeout: { startup: 10, catalog: 20, execution: 30 },
1771
+ servers: {
1772
+ resources: { type: "local", command: ["earlier"], disabled: true, timeout: { execution: 90 } },
1773
+ pinned: { type: "local", command: ["pinned"], disabled: true, protocol: "2026-07-28" },
1774
+ },
1775
+ }),
1776
+ }),
1777
+ }),
1778
+ new Document({
1779
+ type: "document",
1780
+ info: new Info({
1781
+ mcp: new ConfigMCP.Info({
1782
+ timeout: { catalog: 40 },
1783
+ servers: {
1784
+ resources: { type: "local", command: ["later"], disabled: true, timeout: { startup: 50 } },
1785
+ },
1786
+ }),
1787
+ }),
1788
+ }),
1789
+ ]
1790
+ const original = JSON.stringify(entries)
1791
+ yield* Effect.gen(function* () {
1792
+ const service = yield* Mcp.Service
1793
+ const check = yield* service.transform((editor) => {
1794
+ expect(editor.get("resources")).toEqual({
1795
+ type: "local",
1796
+ command: ["later"],
1797
+ disabled: true,
1798
+ timeout: { startup: 50, catalog: 40, execution: 30 },
1799
+ })
1800
+ expect(editor.get("pinned")).toEqual({
1801
+ type: "local",
1802
+ command: ["pinned"],
1803
+ disabled: true,
1804
+ timeout: { startup: 10, catalog: 40, execution: 30 },
1805
+ protocol: "2026-07-28",
1806
+ })
1807
+ })
1808
+ yield* check.dispose
1809
+ const runtime = {
1810
+ type: "local",
1811
+ command: ["runtime"],
1812
+ disabled: true,
1813
+ timeout: { catalog: 60 },
1814
+ } satisfies ConfigMCP.Local
1815
+ yield* service.add("resources", runtime)
1816
+ yield* service.reload()
1817
+ yield* service.transform((editor) => {
1818
+ expect(editor.get("resources")).toEqual(runtime)
1819
+ })
1820
+ }).pipe(
1821
+ Effect.provide(
1822
+ resourceMcpLayer("https://unused.example", undefined, undefined, {
1823
+ entries: () => Effect.succeed(entries),
1824
+ }),
1825
+ ),
1826
+ )
1827
+ expect(JSON.stringify(entries)).toBe(original)
1828
+ }),
1829
+ )
1830
+
1831
+ testEffect(resourceMcpLayer(new ConfigMCP.Local({ type: "local", command: ["unused"], disabled: true }))).live(
1832
+ "manages live MCP servers entirely through scoped transforms",
1833
+ () =>
1834
+ Effect.gen(function* () {
1835
+ const service = yield* Mcp.Service
1836
+ const server = yield* resourceServer({ modern: true, resources: false })
1837
+
1838
+ yield* Effect.scoped(
1839
+ Effect.gen(function* () {
1840
+ yield* service.transform((editor) => {
1841
+ editor.set("dynamic", { type: "remote", url: server.url, oauth: false, protocol: "2026-07-28" })
1842
+ })
1843
+ expect((yield* service.servers()).find((server) => server.name === "dynamic")?.status.status).toBe(
1844
+ "connected",
1845
+ )
1846
+ expect(yield* service.tools()).toHaveLength(1)
1847
+
1848
+ yield* service.transform((editor) => editor.update("dynamic", (server) => (server.codemode = false)))
1849
+ expect((yield* service.tools()).map((tool) => tool.codemode)).toEqual([false])
1850
+
1851
+ const settings = { disabled: true }
1852
+ yield* service.transform((editor) => {
1853
+ editor.update("dynamic", (server) => {
1854
+ server.disabled = settings.disabled
1855
+ })
1856
+ })
1857
+ expect((yield* service.servers()).find((server) => server.name === "dynamic")?.status.status).toBe("disabled")
1858
+ expect(yield* service.tools()).toEqual([])
1859
+
1860
+ settings.disabled = false
1861
+ yield* service.reload()
1862
+ expect((yield* service.servers()).find((server) => server.name === "dynamic")?.status.status).toBe(
1863
+ "connected",
1864
+ )
1865
+ expect(yield* service.tools()).toHaveLength(1)
1866
+
1867
+ const removed = yield* service.transform((editor) => editor.remove("dynamic"))
1868
+ expect((yield* service.servers()).some((server) => server.name === "dynamic")).toBe(false)
1869
+ expect(yield* service.tools()).toEqual([])
1870
+
1871
+ yield* removed.dispose
1872
+ expect((yield* service.servers()).find((server) => server.name === "dynamic")?.status.status).toBe(
1873
+ "connected",
1874
+ )
1875
+ expect(yield* service.tools()).toHaveLength(1)
1876
+ }),
1877
+ )
1878
+
1879
+ expect((yield* service.servers()).map((server) => server.name)).toEqual([Mcp.ServerName.make("resources")])
1880
+ expect(yield* service.tools()).toEqual([])
1881
+ }),
1882
+ )
1883
+
1884
+ test("restores runtime MCP config when a transform is disposed", async () => {
1885
+ await Effect.runPromise(
1886
+ Effect.scoped(
1887
+ Effect.gen(function* () {
1888
+ const service = yield* Mcp.Service
1889
+ const config = new ConfigMCP.Remote({
1890
+ type: "remote",
1891
+ url: "https://example.com/mcp",
1892
+ headers: { Authorization: "original" },
1893
+ oauth: false,
1894
+ disabled: true,
1895
+ })
1896
+ yield* service.add("dynamic", config)
1897
+ const transformed = yield* service.transform((editor) =>
1898
+ editor.update("dynamic", (server) => {
1899
+ if (server.type === "remote") server.headers = { Authorization: "transformed" }
1900
+ }),
1901
+ )
1902
+ let observed: string | undefined
1903
+ yield* service.transform((editor) => {
1904
+ const server = editor.get("dynamic")
1905
+ observed = server?.type === "remote" ? server.headers?.Authorization : undefined
1906
+ })
1907
+
1908
+ expect(observed).toBe("transformed")
1909
+ expect(config.headers?.Authorization).toBe("original")
1910
+ yield* transformed.dispose
1911
+ expect(observed).toBe("original")
1912
+ }).pipe(
1913
+ Effect.provide(resourceMcpLayer(new ConfigMCP.Local({ type: "local", command: ["unused"], disabled: true }))),
1914
+ ),
1915
+ ),
1916
+ )
1917
+ })
1918
+
1919
+ test("isolates nested configured MCP mutations and reconciles them", async () => {
1920
+ const published: string[] = []
1921
+ const config = new ConfigMCP.Remote({
1922
+ type: "remote",
1923
+ url: "https://example.com/mcp",
1924
+ headers: { Authorization: "original" },
1925
+ oauth: false,
1926
+ disabled: true,
1927
+ })
1928
+ await Effect.runPromise(
1929
+ Effect.scoped(
1930
+ Effect.gen(function* () {
1931
+ const service = yield* Mcp.Service
1932
+ expect(published.filter((type) => type === McpEvent.StatusChanged.type)).toHaveLength(1)
1933
+ yield* service.transform((editor) =>
1934
+ editor.update("resources", (server) => {
1935
+ if (server.type === "remote" && server.headers) server.headers.Authorization = "transformed"
1936
+ }),
1937
+ )
1938
+
1939
+ expect(config.headers?.Authorization).toBe("original")
1940
+ expect(published.filter((type) => type === McpEvent.StatusChanged.type)).toHaveLength(2)
1941
+ }).pipe(Effect.provide(resourceMcpLayer(config, undefined, undefined, { published }))),
1942
+ ),
1943
+ )
1944
+ })
1945
+
1946
+ test("publishes MCP changes while live but not while the location shuts down", async () => {
1947
+ const published: string[] = []
1948
+ await Effect.runPromise(
1949
+ Effect.scoped(
1950
+ Effect.gen(function* () {
1951
+ const server = yield* resourceServer({ listChanged: true })
1952
+ const scope = yield* Scope.make()
1953
+ const context = yield* Layer.buildWithScope(
1954
+ resourceMcpLayer(server.url, undefined, undefined, { published }),
1955
+ scope,
1956
+ )
1957
+ yield* Effect.gen(function* () {
1958
+ const service = yield* Mcp.Service
1959
+ expect(yield* settled(service)).toEqual({ status: "connected" })
1960
+ published.length = 0
1961
+ yield* Effect.promise(server.sendResourceListChanged)
1962
+ yield* Effect.sync(() => published).pipe(
1963
+ Effect.filterOrFail(
1964
+ (types) => types.includes(McpEvent.ResourcesChanged.type),
1965
+ () => new Error("resource change was not published"),
1966
+ ),
1967
+ Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
1968
+ )
1969
+ }).pipe(Effect.provide(context))
1970
+ published.length = 0
1971
+ // Location shutdown closes plugin registrations under State.shutdown, so config does not reconcile.
1972
+ yield* State.shutdown(Scope.close(scope, Exit.void))
1973
+ expect(published.filter((type) => type.startsWith("mcp."))).toEqual([])
1974
+ }),
1975
+ ),
1976
+ )
1977
+ })
1978
+
1979
+ testEffect(Layer.empty).live("batches MCP transforms without connecting intermediate configurations", () =>
1980
+ Effect.gen(function* () {
1981
+ const server = yield* resourceServer()
1982
+ yield* Effect.gen(function* () {
1983
+ const service = yield* Mcp.Service
1984
+ const registrations = yield* State.batch(
1985
+ Effect.gen(function* () {
1986
+ const added = yield* service.transform((editor) =>
1987
+ editor.set("dynamic", {
1988
+ type: "remote",
1989
+ url: server.url,
1990
+ oauth: false,
1991
+ }),
1992
+ )
1993
+ expect((yield* service.servers()).some((server) => server.name === "dynamic")).toBe(false)
1994
+ const disabled = yield* service.transform((editor) =>
1995
+ editor.update("dynamic", (config) => (config.disabled = true)),
1996
+ )
1997
+ return [added, disabled]
1998
+ }),
1999
+ )
2000
+
2001
+ expect((yield* service.servers()).find((server) => server.name === "dynamic")?.status).toEqual({
2002
+ status: "disabled",
2003
+ })
2004
+ expect(yield* service.tools()).toEqual([])
2005
+ yield* State.batch(Effect.forEach(registrations, (registration) => registration.dispose))
2006
+ expect((yield* service.servers()).some((server) => server.name === "dynamic")).toBe(false)
2007
+ expect(server.state.initializations).toBe(0)
2008
+ }).pipe(
2009
+ Effect.provide(resourceMcpLayer(new ConfigMCP.Local({ type: "local", command: ["unused"], disabled: true }))),
2010
+ )
2011
+ }),
2012
+ )
2013
+
2014
+ test("reconciles only changed MCP server config", async () => {
2015
+ await Effect.runPromise(
2016
+ Effect.scoped(
2017
+ Effect.gen(function* () {
2018
+ const server = yield* resourceServer()
2019
+ const updates = yield* PubSub.unbounded<Payload>()
2020
+ const resources = (codemode?: boolean) =>
2021
+ new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, codemode })
2022
+ const added = new ConfigMCP.Local({ type: "local", command: ["unused"], disabled: true })
2023
+ const dynamic = new ConfigMCP.Local({ type: "local", command: ["unused"], disabled: true })
2024
+ const document = (servers: Record<string, typeof ConfigMCP.Server.Type>, username?: string) =>
2025
+ new Document({
2026
+ type: "document",
2027
+ info: new Info({
2028
+ username,
2029
+ mcp: new ConfigMCP.Info({ servers }),
2030
+ }),
2031
+ })
2032
+ let entries = [document({ resources: resources() })]
2033
+ const publishUpdate = () =>
2034
+ PubSub.publish(updates, {
2035
+ id: ID.create(),
2036
+ created: 0,
2037
+ type: Event.Updated.type,
2038
+ data: {},
2039
+ } satisfies Payload<typeof Event.Updated>)
2040
+
2041
+ yield* Effect.gen(function* () {
2042
+ const service = yield* Mcp.Service
2043
+ yield* settled(service)
2044
+ expect(server.state.toolLists).toBe(1)
2045
+ expect(server.state.initializations).toBe(1)
2046
+
2047
+ yield* service.add("dynamic", dynamic)
2048
+ entries = [document({ resources: resources() }, "unrelated")]
2049
+ yield* publishUpdate()
2050
+ entries = [document({ resources: resources(), added }, "unrelated")]
2051
+ yield* publishUpdate()
2052
+ const appended = yield* service.servers().pipe(
2053
+ Effect.filterOrFail(
2054
+ (items) => items.some((item) => item.name === "added"),
2055
+ () => new Error("MCP config addition was not applied"),
2056
+ ),
2057
+ Effect.retry({ times: 100, schedule: Schedule.spaced("10 millis") }),
2058
+ )
2059
+ expect(appended.map((item) => String(item.name)).toSorted()).toEqual(["added", "dynamic", "resources"])
2060
+ expect(server.state.toolLists).toBe(1)
2061
+ expect(server.state.initializations).toBe(1)
2062
+
2063
+ entries = [
2064
+ document(
2065
+ {
2066
+ resources: resources(false),
2067
+ added,
2068
+ },
2069
+ "unrelated",
2070
+ ),
2071
+ ]
2072
+ yield* publishUpdate()
2073
+ yield* Effect.sync(() => server.state.initializations).pipe(
2074
+ Effect.filterOrFail(
2075
+ (count) => count === 2,
2076
+ () => new Error("MCP config change did not reconnect the server"),
2077
+ ),
2078
+ Effect.retry({ times: 100, schedule: Schedule.spaced("10 millis") }),
2079
+ )
2080
+
2081
+ entries = [document({ added }, "unrelated")]
2082
+ yield* publishUpdate()
2083
+ const removed = yield* service.servers().pipe(
2084
+ Effect.filterOrFail(
2085
+ (items) => !items.some((item) => item.name === "resources"),
2086
+ () => new Error("MCP config removal was not applied"),
2087
+ ),
2088
+ Effect.retry({ times: 100, schedule: Schedule.spaced("10 millis") }),
2089
+ )
2090
+ expect(removed.map((item) => String(item.name)).toSorted()).toEqual(["added", "dynamic"])
2091
+ }).pipe(
2092
+ Effect.provide(
2093
+ resourceMcpLayer(resources(), undefined, undefined, {
2094
+ entries: () => Effect.sync(() => entries),
2095
+ subscribe: ((definition?: { readonly type: string }) =>
2096
+ Stream.fromPubSub(updates).pipe(
2097
+ Stream.filter((event) => !definition || event.type === definition.type),
2098
+ )) as Bus.Interface["subscribe"],
2099
+ }),
2100
+ ),
2101
+ )
2102
+ }),
2103
+ ),
2104
+ )
2105
+ })
2106
+
2107
+ testEffect(Layer.empty).live("keeps MCP config snapshots stable during an in-flight replacement", () =>
2108
+ Effect.gen(function* () {
2109
+ const started = yield* Deferred.make<void>()
2110
+ const release = yield* Deferred.make<void>()
2111
+ const accepted = yield* Deferred.make<void>()
2112
+ const server = yield* resourceServer({
2113
+ respond: (request) =>
2114
+ request.method !== "POST"
2115
+ ? undefined
2116
+ : Effect.runPromise(
2117
+ Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(release)), Effect.as(undefined)),
2118
+ ),
2119
+ })
2120
+
2121
+ yield* Effect.gen(function* () {
2122
+ const service = yield* Mcp.Service
2123
+ const replacing = yield* service
2124
+ .transform((editor) => editor.update("resources", (config) => (config.disabled = false)))
2125
+ .pipe(Effect.forkScoped({ startImmediately: true }))
2126
+ yield* Deferred.await(started)
2127
+
2128
+ const restoring = yield* State.batch(
2129
+ Effect.gen(function* () {
2130
+ yield* service.transform((editor) => editor.update("resources", (config) => (config.disabled = true)))
2131
+ yield* Deferred.succeed(accepted, undefined)
2132
+ }),
2133
+ ).pipe(Effect.forkScoped({ startImmediately: true }))
2134
+ yield* Deferred.await(accepted)
2135
+ expect((yield* service.servers())[0]?.status).toEqual({ status: "pending" })
2136
+
2137
+ yield* Deferred.succeed(release, undefined)
2138
+ yield* Fiber.join(replacing)
2139
+ yield* Fiber.join(restoring)
2140
+ expect((yield* service.servers())[0]?.status).toEqual({ status: "disabled" })
2141
+ expect(yield* service.tools()).toEqual([])
2142
+ expect(server.state.initializations).toBe(1)
2143
+ }).pipe(
2144
+ Effect.ensuring(Deferred.succeed(release, undefined)),
2145
+ Effect.provide(
2146
+ resourceMcpLayer(new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, disabled: true })),
2147
+ ),
2148
+ )
2149
+ }),
2150
+ )
2151
+
2152
+ const shutdownIt = testEffect(
2153
+ AppNodeBuilder.build(
2154
+ LayerNode.group([
2155
+ Config.node,
2156
+ Bus.node,
2157
+ Integration.node,
2158
+ Credential.node,
2159
+ Form.node,
2160
+ Environment.node,
2161
+ Location.node,
2162
+ Flag.node,
2163
+ McpPool.node,
2164
+ ]),
2165
+ [
2166
+ Location.node.replace(
2167
+ Layer.succeed(
2168
+ Location.Service,
2169
+ Location.Service.of(location({ directory: AbsolutePath.make(import.meta.dir) })),
2170
+ ),
2171
+ ),
2172
+ Environment.node.replace(hostEnvironmentLayer),
2173
+ ],
2174
+ ),
2175
+ )
2176
+ shutdownIt.effect("discards in-flight and queued MCP notifications after its layer closes", () =>
2177
+ Effect.gen(function* () {
2178
+ const bus = yield* Bus.Service
2179
+ const entered = yield* Deferred.make<void>()
2180
+ const release = yield* Deferred.make<void>()
2181
+ const root = yield* Scope.make()
2182
+ yield* Effect.addFinalizer(() =>
2183
+ Deferred.succeed(release, undefined).pipe(Effect.andThen(State.shutdown(Scope.close(root, Exit.void)))),
2184
+ )
2185
+ const context = yield* Layer.buildWithScope(Mcp.layer(), root)
2186
+ const service = Context.get(context, Mcp.Service)
2187
+ const observed: string[] = []
2188
+ let block = false
2189
+ yield* Effect.acquireRelease(
2190
+ bus.listen((event) =>
2191
+ Effect.gen(function* () {
2192
+ if (event.type !== McpEvent.StatusChanged.type) return
2193
+ observed.push(Schema.decodeUnknownSync(McpEvent.StatusChanged.data)(event.data).server)
2194
+ if (!block) return
2195
+ block = false
2196
+ yield* Deferred.succeed(entered, undefined)
2197
+ yield* Deferred.await(release)
2198
+ }),
2199
+ ),
2200
+ (unsubscribe) => unsubscribe,
2201
+ )
2202
+ const source = { url: "https://example.com/initial", added: false }
2203
+ yield* service
2204
+ .transform((editor) => {
2205
+ editor.set("fixture", { type: "remote", url: source.url, oauth: false, disabled: true })
2206
+ if (source.added) editor.set("queued", { type: "local", command: ["unused"], disabled: true })
2207
+ })
2208
+ .pipe(Scope.provide(root))
2209
+
2210
+ block = true
2211
+ source.url = "https://example.com/first"
2212
+ source.added = true
2213
+ const first = yield* service.reload().pipe(Effect.forkChild({ startImmediately: true }))
2214
+ yield* Deferred.await(entered)
2215
+ source.url = "https://example.com/second"
2216
+ const second = yield* service.reload().pipe(Effect.forkChild({ startImmediately: true }))
2217
+
2218
+ const shutdown = yield* State.shutdown(Scope.close(root, Exit.void)).pipe(
2219
+ Effect.forkChild({ startImmediately: true }),
2220
+ )
2221
+ yield* TestClock.adjust("1 millis")
2222
+ expect(shutdown.pollUnsafe()).toBeDefined()
2223
+ expect(first.pollUnsafe()).toBeDefined()
2224
+ expect(second.pollUnsafe()).toBeDefined()
2225
+ expect(yield* Deferred.isDone(release)).toBe(false)
2226
+ yield* Fiber.join(shutdown)
2227
+ observed.length = 0
2228
+ yield* Deferred.succeed(release, undefined)
2229
+ yield* Fiber.join(first)
2230
+ yield* Fiber.join(second)
2231
+ expect(observed).toEqual([])
2232
+ expect((yield* service.servers()).map((server) => server.name)).toEqual([Mcp.ServerName.make("fixture")])
2233
+ }),
2234
+ )
2235
+
2236
+ describe.each(["connect", "disconnect"] as const)("%s during initial MCP startup", (operation) => {
2237
+ shutdownIt.live("is not undone by the queued startup", () =>
2238
+ Effect.gen(function* () {
2239
+ const bus = yield* Bus.Service
2240
+ const server = yield* resourceServer()
2241
+ const entered = yield* Deferred.make<void>()
2242
+ const release = yield* Deferred.make<void>()
2243
+ const root = yield* Scope.make()
2244
+ yield* Effect.addFinalizer(() =>
2245
+ Deferred.succeed(release, undefined).pipe(Effect.andThen(State.shutdown(Scope.close(root, Exit.void)))),
2246
+ )
2247
+ const service = Context.get(yield* Layer.buildWithScope(Mcp.layer(), root), Mcp.Service)
2248
+ // Pausing the disabled server's status event holds initial reconciliation after every entry exists
2249
+ // but before the enabled server's startup is scheduled.
2250
+ yield* Effect.acquireRelease(
2251
+ bus.listen((event) =>
2252
+ Effect.gen(function* () {
2253
+ if (event.type !== McpEvent.StatusChanged.type) return
2254
+ if (Schema.decodeUnknownSync(McpEvent.StatusChanged.data)(event.data).server !== "gate") return
2255
+ yield* Deferred.succeed(entered, undefined)
2256
+ yield* Deferred.await(release)
2257
+ }),
2258
+ ),
2259
+ (unsubscribe) => unsubscribe,
2260
+ )
2261
+ const reconciling = yield* service
2262
+ .transform((editor) => {
2263
+ editor.set("gate", { type: "local", command: ["unused"], disabled: true })
2264
+ editor.set("resources", { type: "remote", url: server.url, oauth: false })
2265
+ })
2266
+ .pipe(Scope.provide(root), Effect.forkChild({ startImmediately: true }))
2267
+ yield* Deferred.await(entered)
2268
+
2269
+ yield* service[operation]("resources")
2270
+ yield* Deferred.succeed(release, undefined)
2271
+ yield* Fiber.join(reconciling)
2272
+ // The queued startup already holds or awaits the server lock, so this waits for it to finish.
2273
+ yield* service.disconnect("resources")
2274
+
2275
+ expect(server.state.initializations).toBe(operation === "connect" ? 1 : 0)
2276
+ expect((yield* service.servers()).find((item) => item.name === "resources")?.status).toEqual({
2277
+ status: "disabled",
2278
+ })
2279
+ }),
2280
+ )
2281
+ })
2282
+
2283
+ test("serializes concurrent MCP lifecycle operations", async () => {
2284
+ await Effect.runPromise(
2285
+ Effect.scoped(
2286
+ Effect.gen(function* () {
2287
+ const server = yield* resourceServer({ modern: true, resources: false })
2288
+ yield* Effect.gen(function* () {
2289
+ const service = yield* Mcp.Service
2290
+
2291
+ // Whatever order the racing operations land in, the resulting state must be consistent.
2292
+ yield* Effect.all(
2293
+ [
2294
+ service.connect("resources"),
2295
+ service.connect("resources"),
2296
+ service.disconnect("resources"),
2297
+ service.connect("resources"),
2298
+ ],
2299
+ { concurrency: "unbounded", discard: true },
2300
+ )
2301
+ const status = (yield* service.servers()).find((server) => server.name === "resources")?.status
2302
+ const tools = yield* service.tools()
2303
+ expect(status?.status === "connected" || status?.status === "disabled").toBe(true)
2304
+ if (status?.status === "disabled") expect(tools).toEqual([])
2305
+ if (status?.status === "connected") expect(tools.length).toBeGreaterThan(0)
2306
+
2307
+ yield* service.disconnect("resources")
2308
+ expect((yield* service.servers())[0]?.status).toEqual({ status: "disabled" })
2309
+ expect(yield* service.tools()).toEqual([])
2310
+ yield* service.connect("resources")
2311
+ expect((yield* service.servers())[0]?.status).toEqual({ status: "connected" })
2312
+ expect((yield* service.tools()).length).toBeGreaterThan(0)
2313
+ }).pipe(
2314
+ Effect.provide(
2315
+ resourceMcpLayer(
2316
+ new ConfigMCP.Remote({
2317
+ type: "remote",
2318
+ url: server.url,
2319
+ oauth: false,
2320
+ protocol: "2026-07-28",
2321
+ disabled: true,
2322
+ }),
2323
+ ),
2324
+ ),
2325
+ )
2326
+ }),
2327
+ ),
2328
+ )
2329
+ })
2330
+
2331
+ const awaitStatus = (service: Mcp.Interface, status: Mcp.Status["status"]) =>
2332
+ service.servers().pipe(
2333
+ Effect.map((servers) => servers.find((server) => server.name === "resources")?.status),
2334
+ Effect.filterOrFail(
2335
+ (current) => current?.status === status,
2336
+ (current) => new Error(`MCP server status is ${JSON.stringify(current)}, expected ${status}`),
2337
+ ),
2338
+ Effect.retry({ schedule: Schedule.spaced("10 millis") }),
2339
+ Effect.timeout("5 seconds"),
2340
+ )
2341
+
2342
+ testEffect(Layer.empty).live("finishes an MCP connect whose caller is interrupted during the handshake", () =>
2343
+ Effect.gen(function* () {
2344
+ const started = yield* Deferred.make<void>()
2345
+ const release = yield* Deferred.make<void>()
2346
+ const server = yield* resourceServer({
2347
+ respond: async (request) => {
2348
+ if (request.method !== "POST") return undefined
2349
+ const body: unknown = await request.clone().json()
2350
+ if (typeof body !== "object" || body === null || !("method" in body) || body.method !== "initialize")
2351
+ return undefined
2352
+ await Effect.runPromise(Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(release))))
2353
+ return undefined
2354
+ },
2355
+ })
2356
+ yield* Effect.gen(function* () {
2357
+ const service = yield* Mcp.Service
2358
+ const connecting = yield* service.connect("resources").pipe(Effect.forkChild({ startImmediately: true }))
2359
+ yield* Deferred.await(started)
2360
+ yield* Fiber.interrupt(connecting)
2361
+ yield* Deferred.succeed(release, undefined)
2362
+
2363
+ yield* awaitStatus(service, "connected")
2364
+ expect((yield* service.tools()).length).toBeGreaterThan(0)
2365
+ }).pipe(
2366
+ Effect.ensuring(Deferred.succeed(release, undefined)),
2367
+ Effect.provide(
2368
+ resourceMcpLayer(new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, disabled: true })),
2369
+ ),
2370
+ )
2371
+ }),
2372
+ )
2373
+
2374
+ testEffect(Layer.empty).live("finishes an MCP disconnect whose caller is interrupted while the session ends", () =>
2375
+ Effect.gen(function* () {
2376
+ const started = yield* Deferred.make<void>()
2377
+ const release = yield* Deferred.make<void>()
2378
+ const server = yield* resourceServer({
2379
+ respond: async (request) => {
2380
+ if (request.method !== "DELETE") return undefined
2381
+ await Effect.runPromise(Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(release))))
2382
+ return undefined
2383
+ },
2384
+ })
2385
+ yield* Effect.gen(function* () {
2386
+ const service = yield* Mcp.Service
2387
+ expect(yield* settled(service)).toEqual({ status: "connected" })
2388
+ const disconnecting = yield* service.disconnect("resources").pipe(Effect.forkChild({ startImmediately: true }))
2389
+ yield* Deferred.await(started)
2390
+ yield* Fiber.interrupt(disconnecting)
2391
+ yield* Deferred.succeed(release, undefined)
2392
+
2393
+ yield* awaitStatus(service, "disabled")
2394
+ expect(yield* service.tools()).toEqual([])
2395
+ }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)), Effect.provide(resourceMcpLayer(server.url)))
2396
+ }),
2397
+ )
2398
+
2399
+ testEffect(Layer.empty).live("preserves plugin transforms through MCP catalog updates", () =>
2400
+ Effect.gen(function* () {
2401
+ const tool = (server: string, name: string, description = name) =>
2402
+ ({
2403
+ server: Mcp.ServerName.make(server),
2404
+ name,
2405
+ description,
2406
+ codemode: false,
2407
+ inputSchema: { type: "object", properties: {} },
2408
+ }) satisfies Mcp.Tool
2409
+ const healthy = [tool("demo", "search"), tool("other", "lookup")]
2410
+ const catalog = yield* Ref.make(healthy)
2411
+
2412
+ yield* Effect.gen(function* () {
2413
+ const registry = yield* Tool.Service
2414
+ const registration = yield* McpTool.Service
2415
+ const bus = yield* Bus.Service
2416
+ yield* registration.flush
2417
+ expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual([
2418
+ "demo_search",
2419
+ "other_lookup",
2420
+ "execute",
2421
+ ])
2422
+ const override = yield* registry.transform((editor) => {
2423
+ editor.add({
2424
+ name: "search",
2425
+ options: { namespace: "demo", codemode: false },
2426
+ description: "Override search",
2427
+ input: Schema.Struct({}),
2428
+ output: Schema.String,
2429
+ execute: () => Effect.succeed({ output: "override" }),
2430
+ })
2431
+ })
2432
+ const mutation = yield* registry.transform((editor) => {
2433
+ editor.update("other_lookup", (tool) => {
2434
+ tool.description += " updated"
2435
+ })
2436
+ editor.remove("repaired_lookup")
2437
+ })
2438
+
2439
+ yield* Ref.set(catalog, [...healthy, tool("demo", "added")])
2440
+ yield* bus.publish(McpEvent.ToolsChanged, { server: "demo" })
2441
+ yield* waitForTool(registry, "demo_added")
2442
+ expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual([
2443
+ "demo_added",
2444
+ "demo_search",
2445
+ "other_lookup",
2446
+ "execute",
2447
+ ])
2448
+ expect((yield* toolDefinitions(registry)).find((tool) => tool.name === "demo_search")?.description).toBe(
2449
+ "Override search",
2450
+ )
2451
+ expect((yield* toolDefinitions(registry)).find((tool) => tool.name === "other_lookup")?.description).toBe(
2452
+ "lookup updated",
2453
+ )
2454
+ yield* Effect.forEach(["demo_search", "other_lookup"], (name) =>
2455
+ executeTool(registry, {
2456
+ sessionID: Session.ID.make("ses_mcp_invalid_catalog"),
2457
+ ...toolIdentity,
2458
+ call: { type: "tool-call", id: `call_${name}`, name, input: {} },
2459
+ }).pipe(
2460
+ Effect.tap((result) =>
2461
+ Effect.sync(() =>
2462
+ expect(result).toMatchObject({
2463
+ status: "completed",
2464
+ output: name === "demo_search" ? "override" : "healthy",
2465
+ }),
2466
+ ),
2467
+ ),
2468
+ ),
2469
+ )
2470
+
2471
+ yield* Ref.set(catalog, [
2472
+ tool("demo", "status"),
2473
+ tool("other", "lookup"),
2474
+ tool("demo", "added"),
2475
+ tool("repaired", "lookup"),
2476
+ ])
2477
+ yield* bus.publish(McpEvent.ToolsChanged, { server: "demo" })
2478
+ yield* waitForTool(registry, "demo_status")
2479
+ expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual([
2480
+ "demo_added",
2481
+ "demo_search",
2482
+ "demo_status",
2483
+ "other_lookup",
2484
+ "execute",
2485
+ ])
2486
+ expect((yield* toolDefinitions(registry)).find((tool) => tool.name === "demo_search")?.description).toBe(
2487
+ "Override search",
2488
+ )
2489
+ expect((yield* toolDefinitions(registry)).find((tool) => tool.name === "other_lookup")?.description).toBe(
2490
+ "lookup updated",
2491
+ )
2492
+ yield* mutation.dispose
2493
+ expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toContain("repaired_lookup")
2494
+ expect((yield* toolDefinitions(registry)).find((tool) => tool.name === "other_lookup")?.description).toBe(
2495
+ "lookup",
2496
+ )
2497
+
2498
+ yield* Ref.set(catalog, [tool("demo", "search", "Latest search"), tool("demo", "refreshed")])
2499
+ yield* bus.publish(McpEvent.ToolsChanged, { server: "demo" })
2500
+ yield* waitForTool(registry, "demo_refreshed")
2501
+ expect((yield* toolDefinitions(registry)).find((tool) => tool.name === "demo_search")?.description).toBe(
2502
+ "Override search",
2503
+ )
2504
+
2505
+ yield* override.dispose
2506
+ expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual([
2507
+ "demo_refreshed",
2508
+ "demo_search",
2509
+ "execute",
2510
+ ])
2511
+ expect((yield* toolDefinitions(registry)).find((tool) => tool.name === "demo_search")?.description).toBe(
2512
+ "Latest search",
2513
+ )
2514
+ expect(
2515
+ yield* executeTool(registry, {
2516
+ sessionID: Session.ID.make("ses_mcp_invalid_catalog"),
2517
+ ...toolIdentity,
2518
+ call: { type: "tool-call", id: "call_restored_search", name: "demo_search", input: {} },
2519
+ }),
2520
+ ).toMatchObject({ status: "completed", output: "healthy" })
2521
+ }).pipe(
2522
+ Effect.provide(
2523
+ Layer.fresh(
2524
+ AppNodeBuilder.build(LayerNode.group([Tool.node, McpTool.node, Bus.node]), [
2525
+ ...toolNodeReplacements(permissionLayer({ assert: () => Effect.void })),
2526
+ Mcp.node.replace(
2527
+ Layer.mock(Mcp.Service, {
2528
+ awaitStartup: () => Effect.void,
2529
+ tools: () => Ref.get(catalog),
2530
+ callTool: (input) =>
2531
+ Effect.succeed({
2532
+ isError: false,
2533
+ content: [{ type: "text", text: "healthy" }],
2534
+ } satisfies Mcp.ToolResult),
2535
+ }),
2536
+ ),
2537
+ ]),
2538
+ ),
2539
+ ),
2540
+ )
2541
+ }),
2542
+ )
2543
+
2544
+ testEffect(Layer.empty).effect("coalesces queued MCP tool notifications after initial registration", () => {
2545
+ const tool = (name: string) =>
2546
+ ({
2547
+ server: Mcp.ServerName.make("demo"),
2548
+ name,
2549
+ codemode: false,
2550
+ inputSchema: { type: "object", properties: {} },
2551
+ }) satisfies Mcp.Tool
2552
+ let reads = 0
2553
+ let catalog = [tool("read_1")]
2554
+ return Effect.gen(function* () {
2555
+ const registry = yield* Tool.Service
2556
+ const registration = yield* McpTool.Service
2557
+ const bus = yield* Bus.Service
2558
+ yield* registration.flush
2559
+ // Initial registration plus the flush's check that the registry is current.
2560
+ expect(reads).toBe(2)
2561
+ expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["demo_read_1", "execute"])
2562
+
2563
+ catalog = [tool("read_2")]
2564
+ yield* bus.publish(McpEvent.ToolsChanged, { server: "demo" })
2565
+ yield* advance(() => reads >= 3)
2566
+ expect(reads).toBe(3)
2567
+ catalog = [tool("read_3")]
2568
+ yield* Effect.forEach(Array.from({ length: 20 }), () => bus.publish(McpEvent.ToolsChanged, { server: "demo" }))
2569
+ yield* advance(() => reads >= 4)
2570
+ yield* drain
2571
+ expect(reads).toBe(4)
2572
+ expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["demo_read_3", "execute"])
2573
+ }).pipe(
2574
+ Effect.provide(
2575
+ AppNodeBuilder.build(LayerNode.group([Tool.node, McpTool.node, Bus.node]), [
2576
+ ...toolNodeReplacements(permissionLayer({ assert: () => Effect.void })),
2577
+ Mcp.node.replace(
2578
+ Layer.mock(Mcp.Service, {
2579
+ awaitStartup: () => Effect.void,
2580
+ tools: () =>
2581
+ Effect.sync(() => {
2582
+ reads++
2583
+ return catalog
2584
+ }),
2585
+ }),
2586
+ ),
2587
+ ]),
2588
+ ),
2589
+ )
2590
+ })
2591
+
2592
+ // Holds every MCP POST, including the handshake, until the test releases it.
2593
+ const gatedServer = Effect.gen(function* () {
2594
+ const started = yield* Deferred.make<void>()
2595
+ const release = yield* Deferred.make<void>()
2596
+ const server = yield* resourceServer({
2597
+ respond: (request) =>
2598
+ request.method !== "POST"
2599
+ ? undefined
2600
+ : Effect.runPromise(
2601
+ Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(release)), Effect.as(undefined)),
2602
+ ),
2603
+ })
2604
+ return { server, started, release }
2605
+ })
2606
+
2607
+ // The real Mcp layer behind the tool registry; the bus never delivers, so only flush can register tools.
2608
+ const startupRegistry = (url: string) =>
2609
+ AppNodeBuilder.build(LayerNode.group([Mcp.node, Tool.node, McpTool.node]), [
2610
+ ...toolNodeReplacements(permissions),
2611
+ Mcp.node.replace(resourceMcpLayer(new ConfigMCP.Remote({ type: "remote", url, oauth: false, codemode: false }))),
2612
+ Bus.node.replace(events),
2613
+ Global.node.replace(Global.layerWith({ data: outputData })),
2614
+ ])
2615
+
2616
+ testEffect(Layer.empty).effect("flush waits for a server that connects within its startup window", () =>
2617
+ Effect.gen(function* () {
2618
+ const gated = yield* gatedServer
2619
+ yield* Effect.gen(function* () {
2620
+ const registry = yield* Tool.Service
2621
+ const registration = yield* McpTool.Service
2622
+ yield* Deferred.await(gated.started)
2623
+ const flush = yield* registration.flush.pipe(Effect.forkChild({ startImmediately: true }))
2624
+ yield* Effect.yieldNow
2625
+ expect(flush.pollUnsafe()).toBeUndefined()
2626
+
2627
+ yield* Deferred.succeed(gated.release, undefined)
2628
+ yield* Fiber.join(flush)
2629
+ expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toContain("resources_echo")
2630
+ }).pipe(
2631
+ Effect.ensuring(Deferred.succeed(gated.release, undefined)),
2632
+ Effect.provide(startupRegistry(gated.server.url)),
2633
+ )
2634
+ }),
2635
+ )
2636
+
2637
+ testEffect(Layer.empty).effect("flush stops waiting for a hung server when its startup window ends", () =>
2638
+ Effect.gen(function* () {
2639
+ const gated = yield* gatedServer
2640
+ yield* Effect.gen(function* () {
2641
+ const mcp = yield* Mcp.Service
2642
+ const registration = yield* McpTool.Service
2643
+ yield* Deferred.await(gated.started)
2644
+ const flush = yield* registration.flush.pipe(Effect.forkChild({ startImmediately: true }))
2645
+ yield* TestClock.adjust("1999 millis")
2646
+ expect(flush.pollUnsafe()).toBeUndefined()
2647
+
2648
+ yield* TestClock.adjust("1 millis")
2649
+ yield* Fiber.join(flush)
2650
+ // Past its window, the still-pending server no longer holds up a model call.
2651
+ yield* registration.flush
2652
+ expect((yield* mcp.servers())[0]?.status).toEqual({ status: "pending" })
2653
+ }).pipe(
2654
+ // Shutting down mid-handshake would wait on the held request.
2655
+ Effect.ensuring(Deferred.succeed(gated.release, undefined)),
2656
+ Effect.provide(startupRegistry(gated.server.url)),
2657
+ )
2658
+ }),
2659
+ )
2660
+
2661
+ it.effect("advertises MCP output schemas to Code Mode", () =>
2662
+ Effect.gen(function* () {
2663
+ const registry = yield* Tool.Service
2664
+ const registration = yield* McpTool.Service
2665
+ yield* registration.flush
2666
+ const toolSet = yield* registry.snapshot()
2667
+ const execute = toolSet.definitions.find((tool) => tool.name === "execute")
2668
+
2669
+ expect(toolSet.definitions.map((tool) => tool.name)).toEqual([
2670
+ "direct_attachments",
2671
+ "direct_fail",
2672
+ "direct_issues",
2673
+ "direct_lookup",
2674
+ "direct_media",
2675
+ "execute",
2676
+ ])
2677
+ expect(codeModeListings(toolSet.codeModeCatalog!).find((tool) => tool.path === "demo.search")?.line).toContain(
2678
+ "ok: boolean",
2679
+ )
2680
+ expect(execute?.description).not.toContain("tools.demo.search")
2681
+ }),
2682
+ )
2683
+
2684
+ it.effect("forwards the invoking session through direct and Code Mode MCP tools", () =>
2685
+ Effect.gen(function* () {
2686
+ assertion = yield* Deferred.make<Permission.AssertInput>()
2687
+ decision = Effect.void
2688
+ invocations = []
2689
+ const registry = yield* Tool.Service
2690
+ const registration = yield* McpTool.Service
2691
+ yield* registration.flush
2692
+ const toolSet = yield* registry.snapshot()
2693
+
2694
+ expect(toolSet.definitions.find((tool) => tool.name === "direct_lookup")?.inputSchema).not.toHaveProperty(
2695
+ "properties.sessionID",
2696
+ )
2697
+ expect(codeModeListings(toolSet.codeModeCatalog!).find((tool) => tool.path === "demo.search")?.line).not.toContain(
2698
+ "sessionID",
2699
+ )
2700
+
2701
+ const directSessionID = Session.ID.make("ses_mcp_direct")
2702
+ yield* toolSet.execute({
2703
+ sessionID: directSessionID,
2704
+ ...toolIdentity,
2705
+ call: { type: "tool-call", id: "call_mcp_direct", name: "direct_lookup", input: {} },
2706
+ })
2707
+ expect(invocations[0]).toEqual({
2708
+ server: "direct",
2709
+ name: "lookup",
2710
+ args: {},
2711
+ sessionID: directSessionID,
2712
+ })
2713
+
2714
+ const codeModeSessionID = Session.ID.make("ses_mcp_codemode")
2715
+ yield* toolSet.execute({
2716
+ sessionID: codeModeSessionID,
2717
+ ...toolIdentity,
2718
+ call: {
2719
+ type: "tool-call",
2720
+ id: "call_mcp_codemode",
2721
+ name: "execute",
2722
+ input: { code: "return await tools.demo.search({})" },
2723
+ },
2724
+ })
2725
+ expect(invocations[1]).toEqual({
2726
+ server: "demo",
2727
+ name: "search",
2728
+ args: {},
2729
+ sessionID: codeModeSessionID,
2730
+ })
2731
+ }),
2732
+ )
2733
+
2734
+ it.effect("returns content-only MCP results through Code Mode", () =>
2735
+ Effect.gen(function* () {
2736
+ assertion = yield* Deferred.make<Permission.AssertInput>()
2737
+ decision = Effect.void
2738
+ const registry = yield* Tool.Service
2739
+ const registration = yield* McpTool.Service
2740
+ yield* registration.flush
2741
+ const toolSet = yield* registry.snapshot()
2742
+
2743
+ expect(codeModeListings(toolSet.codeModeCatalog!).some((tool) => tool.path === "demo.status")).toBe(true)
2744
+
2745
+ const execution = yield* toolSet.execute({
2746
+ sessionID: Session.ID.make("ses_mcp_content_only"),
2747
+ ...toolIdentity,
2748
+ call: {
2749
+ type: "tool-call",
2750
+ id: "call_mcp_content_only",
2751
+ name: "execute",
2752
+ input: { code: "return await tools.demo.status({})" },
2753
+ },
2754
+ })
2755
+
2756
+ expect(execution).toMatchObject({
2757
+ output: { output: "hello", toolCalls: [{ tool: "demo.status", status: "completed" }] },
2758
+ content: [{ type: "text", text: "hello" }],
2759
+ })
2760
+ }),
2761
+ )
2762
+
2763
+ it.effect("parses JSON text results from MCP tools without an output schema", () =>
2764
+ Effect.gen(function* () {
2765
+ assertion = yield* Deferred.make<Permission.AssertInput>()
2766
+ decision = Effect.void
2767
+ const registry = yield* Tool.Service
2768
+ const registration = yield* McpTool.Service
2769
+ yield* registration.flush
2770
+ const toolSet = yield* registry.snapshot()
2771
+
2772
+ const run = (code: string) =>
2773
+ toolSet
2774
+ .execute({
2775
+ sessionID: Session.ID.make("ses_mcp_json_text"),
2776
+ ...toolIdentity,
2777
+ call: { type: "tool-call", id: `call_${code.length}`, name: "execute", input: { code } },
2778
+ })
2779
+ .pipe(Effect.map((execution) => execution.output.output))
2780
+
2781
+ expect(yield* run("return (await tools.demo.issues({})).issues[0].id")).toBe("1")
2782
+ expect(yield* run("return typeof (await tools.demo.count({}))")).toBe("string")
2783
+ expect(yield* run("return typeof (await tools.demo.typed({}))")).toBe("string")
2784
+
2785
+ // Outside Code Mode the content the model reads is the original text.
2786
+ expect(
2787
+ yield* toolSet.execute({
2788
+ sessionID: Session.ID.make("ses_mcp_json_text"),
2789
+ ...toolIdentity,
2790
+ call: { type: "tool-call", id: "call_direct_issues", name: "direct_issues", input: {} },
2791
+ }),
2792
+ ).toMatchObject({ output: { issues: [{ id: 1 }] }, content: [{ type: "text", text: '{"issues":[{"id":1}]}' }] })
2793
+ }),
2794
+ )
2795
+
2796
+ // Baseline (PLAN.md step 1): MCP isError must become one failed tool call, not a
2797
+ // success whose text happens to describe an error.
2798
+ it.effect("fails the call when MCP reports isError", () =>
2799
+ Effect.gen(function* () {
2800
+ assertion = yield* Deferred.make<Permission.AssertInput>()
2801
+ decision = Effect.void
2802
+ const registry = yield* Tool.Service
2803
+ const registration = yield* McpTool.Service
2804
+ yield* registration.flush
2805
+
2806
+ const execution = yield* executeTool(registry, {
2807
+ sessionID: Session.ID.make("ses_mcp_is_error"),
2808
+ ...toolIdentity,
2809
+ call: { type: "tool-call", id: "call_mcp_is_error", name: "direct_fail", input: {} },
2810
+ })
2811
+
2812
+ expect(execution).toMatchObject({ status: "error", error: { message: "search index unavailable" } })
2813
+ }),
2814
+ )
2815
+
2816
+ // Baseline (PLAN.md step 1): mixed MCP text and media content must reach the model intact.
2817
+ it.effect("preserves MCP text and media content for the model", () =>
2818
+ Effect.gen(function* () {
2819
+ assertion = yield* Deferred.make<Permission.AssertInput>()
2820
+ decision = Effect.void
2821
+ const registry = yield* Tool.Service
2822
+ const registration = yield* McpTool.Service
2823
+ yield* registration.flush
2824
+
2825
+ const execution = yield* executeTool(registry, {
2826
+ sessionID: Session.ID.make("ses_mcp_media"),
2827
+ ...toolIdentity,
2828
+ call: { type: "tool-call", id: "call_mcp_media", name: "direct_media", input: {} },
2829
+ })
2830
+
2831
+ expect(execution.output).toBe("rendered chart")
2832
+ expect(execution.content).toMatchObject([
2833
+ { type: "text", text: "rendered chart" },
2834
+ { type: "file", mime: "image/png" },
2835
+ ])
2836
+ }),
2837
+ )
2838
+
2839
+ it.effect("decodes text blobs and saves other MCP blobs instead of attaching them", () =>
2840
+ Effect.gen(function* () {
2841
+ assertion = yield* Deferred.make<Permission.AssertInput>()
2842
+ decision = Effect.void
2843
+ const registry = yield* Tool.Service
2844
+ const registration = yield* McpTool.Service
2845
+ yield* registration.flush
2846
+
2847
+ const execution = yield* executeTool(registry, {
2848
+ sessionID: Session.ID.make("ses_mcp_attachments"),
2849
+ ...toolIdentity,
2850
+ call: { type: "tool-call", id: "call_mcp_attachments", name: "direct_attachments", input: {} },
2851
+ })
2852
+
2853
+ const text = execution.content?.map((part) => (part.type === "text" ? part.text : part.mime)) ?? []
2854
+ const saved =
2855
+ /^\[Binary resource file:\/\/\/data\.parquet \(application\/vnd\.apache\.parquet, 4 bytes\) saved to (.+)\]$/.exec(
2856
+ text[1] ?? "",
2857
+ )?.[1]
2858
+ expect(text[0]).toBe("[Resource file:///README.md (text/markdown)]\n# Notes")
2859
+ expect(saved?.startsWith(path.join(outputData, ToolOutput.DIRECTORY, "tool_"))).toBe(true)
2860
+ expect(yield* Effect.promise(() => fs.readFile(saved ?? "", "utf8"))).toBe("PAR1")
2861
+ }),
2862
+ )
2863
+
2864
+ it.effect("waits for permission before calling an MCP tool", () =>
2865
+ Effect.gen(function* () {
2866
+ calls = 0
2867
+ assertion = yield* Deferred.make<Permission.AssertInput>()
2868
+ const permission = yield* Deferred.make<void>()
2869
+ decision = Deferred.await(permission)
2870
+ const registry = yield* Tool.Service
2871
+ const registration = yield* McpTool.Service
2872
+ yield* registration.flush
2873
+ const toolSet = yield* registry.snapshot()
2874
+ expect(codeModeListings(toolSet.codeModeCatalog!).some((tool) => tool.path === "demo.search")).toBe(true)
2875
+
2876
+ const fiber = yield* toolSet
2877
+ .execute({
2878
+ sessionID: Session.ID.make("ses_mcp_permission"),
2879
+ ...toolIdentity,
2880
+ call: {
2881
+ type: "tool-call",
2882
+ id: "call_mcp_permission",
2883
+ name: "execute",
2884
+ input: { code: 'return await tools.demo.search({ query: "open issues" })' },
2885
+ },
2886
+ })
2887
+ .pipe(Effect.forkScoped)
2888
+ expect(yield* Deferred.await(assertion)).toEqual({
2889
+ action: "demo_search",
2890
+ resources: ["*"],
2891
+ save: ["*"],
2892
+ metadata: { input: { query: "open issues" } },
2893
+ sessionID: Session.ID.make("ses_mcp_permission"),
2894
+ agent: toolIdentity.agent,
2895
+ source: {
2896
+ type: "tool",
2897
+ messageID: toolIdentity.messageID,
2898
+ id: expect.not.stringMatching(/^call_mcp_permission$/),
2899
+ },
2900
+ })
2901
+ expect(calls).toBe(0)
2902
+
2903
+ yield* Deferred.succeed(permission, undefined)
2904
+ yield* Fiber.join(fiber)
2905
+ expect(calls).toBe(1)
2906
+ }),
2907
+ )
2908
+
2909
+ it.effect("does not call MCP when permission is blocked", () =>
2910
+ Effect.gen(function* () {
2911
+ calls = 0
2912
+ assertion = yield* Deferred.make<Permission.AssertInput>()
2913
+ decision = Effect.fail(
2914
+ new Permission.BlockedError({
2915
+ rules: [],
2916
+ permission: "demo_search",
2917
+ resources: ["*"],
2918
+ reason: "Search is disabled in this workspace",
2919
+ }),
2920
+ )
2921
+ const registry = yield* Tool.Service
2922
+ const registration = yield* McpTool.Service
2923
+ yield* registration.flush
2924
+ const toolSet = yield* registry.snapshot()
2925
+ expect(codeModeListings(toolSet.codeModeCatalog!).some((tool) => tool.path === "demo.search")).toBe(true)
2926
+
2927
+ const execution = yield* toolSet.execute({
2928
+ sessionID: Session.ID.make("ses_mcp_blocked"),
2929
+ ...toolIdentity,
2930
+ call: {
2931
+ type: "tool-call",
2932
+ id: "call_mcp_blocked",
2933
+ name: "execute",
2934
+ input: { code: "return await tools.demo.search({})" },
2935
+ },
2936
+ })
2937
+ expect(execution.content).toEqual([{ type: "text", text: "Search is disabled in this workspace" }])
2938
+ expect(execution.metadata).toEqual({
2939
+ toolCalls: [{ tool: "demo.search", status: "error" }],
2940
+ error: true,
2941
+ })
2942
+ expect(
2943
+ yield* executeTool(registry, {
2944
+ sessionID: Session.ID.make("ses_mcp_blocked"),
2945
+ ...toolIdentity,
2946
+ call: { type: "tool-call", id: "call_mcp_blocked_direct", name: "direct_lookup", input: {} },
2947
+ }),
2948
+ ).toEqual({
2949
+ status: "error",
2950
+ error: { type: "permission.rejected", message: "Search is disabled in this workspace" },
2951
+ })
2952
+ expect(calls).toBe(0)
2953
+ }),
2954
+ )
2955
+
2956
+ it.effect("returns permission feedback instead of calling MCP", () =>
2957
+ Effect.gen(function* () {
2958
+ calls = 0
2959
+ assertion = yield* Deferred.make<Permission.AssertInput>()
2960
+ decision = Effect.fail(new Permission.CorrectedError({ feedback: "Search the docs folder instead" }))
2961
+ const registry = yield* Tool.Service
2962
+ const registration = yield* McpTool.Service
2963
+ yield* registration.flush
2964
+ const toolSet = yield* registry.snapshot()
2965
+
2966
+ const execution = yield* toolSet.execute({
2967
+ sessionID: Session.ID.make("ses_mcp_corrected"),
2968
+ ...toolIdentity,
2969
+ call: {
2970
+ type: "tool-call",
2971
+ id: "call_mcp_corrected",
2972
+ name: "execute",
2973
+ input: { code: "return await tools.demo.search({})" },
2974
+ },
2975
+ })
2976
+ expect(execution.content).toEqual([{ type: "text", text: "Search the docs folder instead" }])
2977
+ expect(
2978
+ yield* executeTool(registry, {
2979
+ sessionID: Session.ID.make("ses_mcp_corrected"),
2980
+ ...toolIdentity,
2981
+ call: { type: "tool-call", id: "call_mcp_corrected_direct", name: "direct_lookup", input: {} },
2982
+ }),
2983
+ ).toEqual({
2984
+ status: "error",
2985
+ error: { type: "permission.rejected", message: "Search the docs folder instead" },
2986
+ })
2987
+ expect(calls).toBe(0)
2988
+ }),
2989
+ )
2990
+
2991
+ testEffect(Layer.empty).live("integration policy denies MCP startup", () =>
2992
+ Effect.gen(function* () {
2993
+ const server = yield* resourceServer()
2994
+ yield* Effect.gen(function* () {
2995
+ const service = yield* Mcp.Service
2996
+ expect(yield* service.servers()).toEqual([])
2997
+ expect(Exit.isFailure(yield* service.connect("resources").pipe(Effect.exit))).toBe(true)
2998
+ yield* service.add("resources", { type: "remote", url: server.url, oauth: false })
2999
+ expect(yield* service.servers()).toEqual([])
3000
+ expect(yield* service.tools()).toEqual([])
3001
+ expect(yield* service.instructions()).toEqual([])
3002
+ expect(yield* service.prompts()).toEqual([])
3003
+ expect(yield* service.resourceCatalog()).toEqual({ resources: [], templates: [] })
3004
+ expect(Exit.isFailure(yield* service.resources({ server: "resources" }).pipe(Effect.exit))).toBe(true)
3005
+ expect(Exit.isFailure(yield* service.prompt({ server: "resources", name: "greet" }).pipe(Effect.exit))).toBe(true)
3006
+ expect(
3007
+ Exit.isFailure(yield* service.readResource({ server: "resources", uri: "docs://readme" }).pipe(Effect.exit)),
3008
+ ).toBe(true)
3009
+ expect(Exit.isFailure(yield* service.callTool({ server: "resources", name: "echo" }).pipe(Effect.exit))).toBe(
3010
+ true,
3011
+ )
3012
+ expect(server.state.initializations).toBe(0)
3013
+ }).pipe(
3014
+ Effect.provide(
3015
+ resourceMcpLayer(server.url, undefined, undefined, {
3016
+ policies: [{ action: "mcp.use", resource: "*", effect: "deny" }],
3017
+ }),
3018
+ ),
3019
+ )
3020
+ }),
3021
+ )
3022
+
3023
+ for (const source of ["config", "organization"] as const) {
3024
+ testEffect(Config.testLayer()).live(`revokes and restores a connected MCP through ${source} policy`, () =>
3025
+ Effect.gen(function* () {
3026
+ const server = yield* resourceServer()
3027
+ const config = yield* Config.Service
3028
+ const test = yield* Config.Test
3029
+ const updates = yield* PubSub.unbounded<{ readonly type: string }>()
3030
+ const document = (effect: ConfigPolicy.Effect) =>
3031
+ new Document({
3032
+ type: "document",
3033
+ info: new Info({
3034
+ mcp: new ConfigMCP.Info({
3035
+ servers: { resources: new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false }) },
3036
+ }),
3037
+ policies: [{ action: "mcp.use", resource: "*", effect }],
3038
+ }),
3039
+ })
3040
+ yield* test.setEntries([document("allow")])
3041
+ yield* Effect.gen(function* () {
3042
+ const service = yield* Mcp.Service
3043
+ expect(yield* settled(service)).toEqual({ status: "connected" })
3044
+ expect((yield* service.tools()).length).toBeGreaterThan(0)
3045
+ if (source === "config") yield* test.setEntries([document("deny")])
3046
+ if (source === "organization")
3047
+ yield* setOrganizationPolicy([{ action: "mcp.use", resource: "*", effect: "deny" }])
3048
+ yield* PubSub.publish(updates, { type: Event.Updated.type })
3049
+ yield* service.servers().pipe(
3050
+ Effect.filterOrFail(
3051
+ (servers) => servers.length === 0,
3052
+ () => new Error("MCP policy was not applied"),
3053
+ ),
3054
+ Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
3055
+ )
3056
+ expect(yield* service.servers()).toEqual([])
3057
+ expect(yield* service.tools()).toEqual([])
3058
+ expect(yield* service.instructions()).toEqual([])
3059
+ expect(yield* service.prompts()).toEqual([])
3060
+ expect(yield* service.resourceCatalog()).toEqual({ resources: [], templates: [] })
3061
+ expect(Exit.isFailure(yield* service.resources({ server: "resources" }).pipe(Effect.exit))).toBe(true)
3062
+ expect(Exit.isFailure(yield* service.prompt({ server: "resources", name: "greet" }).pipe(Effect.exit))).toBe(
3063
+ true,
3064
+ )
3065
+ expect(
3066
+ Exit.isFailure(yield* service.readResource({ server: "resources", uri: "docs://readme" }).pipe(Effect.exit)),
3067
+ ).toBe(true)
3068
+ expect(Exit.isFailure(yield* service.connect("resources").pipe(Effect.exit))).toBe(true)
3069
+ expect(Exit.isFailure(yield* service.callTool({ server: "resources", name: "echo" }).pipe(Effect.exit))).toBe(
3070
+ true,
3071
+ )
3072
+ expect(server.state.toolCalls).toEqual([])
3073
+ expect(server.state.resourceReads).toEqual([])
3074
+ yield* Effect.promise(server.restart)
3075
+ if (source === "config") yield* test.setEntries([document("allow")])
3076
+ if (source === "organization") yield* setOrganizationPolicy(undefined)
3077
+ yield* PubSub.publish(updates, { type: Event.Updated.type })
3078
+ yield* service.servers().pipe(
3079
+ Effect.filterOrFail(
3080
+ (servers) => servers.some((server) => server.status.status === "connected"),
3081
+ () => new Error("MCP policy was not restored"),
3082
+ ),
3083
+ Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
3084
+ )
3085
+ expect(yield* settled(service)).toEqual({ status: "connected" })
3086
+ expect((yield* service.tools()).length).toBeGreaterThan(0)
3087
+ }).pipe(
3088
+ Effect.provide(
3089
+ resourceMcpLayer(server.url, undefined, undefined, {
3090
+ entries: config.entries,
3091
+ subscribe: ((definition?: { readonly type: string }) =>
3092
+ Stream.fromPubSub(updates).pipe(
3093
+ Stream.filter((event) => !definition || event.type === definition.type),
3094
+ )) as Bus.Interface["subscribe"],
3095
+ }),
3096
+ ),
3097
+ )
3098
+ }),
3099
+ )
3100
+ }
3101
+
3102
+ describe("MCP pool", () => {
3103
+ const live = testEffect(Layer.empty).live
3104
+ const pooled = (url: string, fields: Partial<ConfigMCP.Remote> = {}) =>
3105
+ new ConfigMCP.Remote({ type: "remote", url, oauth: false, pool: true, ...fields })
3106
+ const makePool = Layer.build(poolLayer).pipe(Effect.map((context) => Context.get(context, McpPool.Service)))
3107
+ const directories = [import.meta.dir, path.join(import.meta.dir, "fixture")]
3108
+
3109
+ const status = (mcp: Mcp.Interface) => mcp.servers().pipe(Effect.map((servers) => servers[0]?.status))
3110
+
3111
+ // Collects the pool's "not shared" messages with their details.
3112
+ const poolLogs = () => {
3113
+ const logs: Array<readonly [string, unknown]> = []
3114
+ const logger = Logger.map(Logger.formatStructured, (entry) => {
3115
+ if (Array.isArray(entry.message) && String(entry.message[0]).startsWith("mcp pool ignored"))
3116
+ logs.push([entry.message[0], entry.message[1]])
3117
+ })
3118
+ return { logs, layer: Logger.layer([logger]) }
3119
+ }
3120
+
3121
+ // A pool whose own spawns, the attempts at a shared local connection, are recorded.
3122
+ const recordingPool = (spawns: Array<ChildProcess.Command>) =>
3123
+ Layer.build(
3124
+ McpPool.layer.pipe(
3125
+ Layer.provide(
3126
+ Layer.effect(
3127
+ ChildProcessSpawner.ChildProcessSpawner,
3128
+ Effect.gen(function* () {
3129
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
3130
+ return ChildProcessSpawner.make((command) => {
3131
+ spawns.push(command)
3132
+ return spawner.spawn(command)
3133
+ })
3134
+ }),
3135
+ ).pipe(Layer.provide(LayerNode.compile(CrossSpawnSpawner.node))),
3136
+ ),
3137
+ ),
3138
+ ).pipe(Effect.map((context) => Context.get(context, McpPool.Service)))
3139
+
3140
+ // One Location's MCP service on the given pool; `shutdown` closes the Location as eviction would.
3141
+ const open = (
3142
+ config: typeof ConfigMCP.Server.Type,
3143
+ pool: McpPool.Interface,
3144
+ directory: string,
3145
+ overrides: {
3146
+ onFormCreated?: (form: Form.Info) => Effect.Effect<void>
3147
+ published?: string[]
3148
+ environment?: Layer.Layer<Environment.Service>
3149
+ name?: string
3150
+ credentials?: Partial<Credential.Interface>
3151
+ bus?: Layer.Layer<Bus.Service>
3152
+ } = {},
3153
+ ) =>
3154
+ Effect.gen(function* () {
3155
+ const scope = yield* Scope.make()
3156
+ yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
3157
+ const context = yield* Layer.buildWithScope(
3158
+ resourceMcpLayer(config, overrides.onFormCreated, undefined, {
3159
+ pool: Layer.succeed(McpPool.Service, pool),
3160
+ directory,
3161
+ published: overrides.published,
3162
+ environment: overrides.environment,
3163
+ name: overrides.name,
3164
+ credentials: overrides.credentials,
3165
+ bus: overrides.bus,
3166
+ }),
3167
+ scope,
3168
+ )
3169
+ const mcp = Context.get(context, Mcp.Service)
3170
+ // Up to 10 seconds: a server that is down is retried for a while before it shows failed.
3171
+ yield* status(mcp).pipe(
3172
+ Effect.filterOrFail((status) => status?.status !== "pending"),
3173
+ Effect.retry({ times: 1_000, schedule: Schedule.spaced("10 millis") }),
3174
+ )
3175
+ return { mcp, forms: Context.get(context, Form.Service), shutdown: Scope.close(scope, Exit.void) }
3176
+ })
3177
+
3178
+ live("shares one connection and one tool list between Locations", () =>
3179
+ Effect.gen(function* () {
3180
+ const server = yield* resourceServer({ modern: true, resources: false })
3181
+ const pool = yield* makePool
3182
+ const a = yield* open(pooled(server.url), pool, directories[0])
3183
+ const b = yield* open(pooled(server.url), pool, directories[1])
3184
+
3185
+ const [toolsA, toolsB] = [yield* a.mcp.tools(), yield* b.mcp.tools()]
3186
+ expect(toolsA.map((tool) => tool.name)).toEqual(["echo"])
3187
+ expect(toolsB.map((tool) => tool.name)).toEqual(["echo"])
3188
+ // Each Location tags its own copy of the one listed tool.
3189
+ expect(toolsA[0]?.inputSchema).toBe(toolsB[0]?.inputSchema)
3190
+ expect(server.state.toolLists).toBe(1)
3191
+ yield* a.mcp.callTool({ server: "resources", name: "echo" })
3192
+ yield* b.mcp.callTool({ server: "resources", name: "echo" })
3193
+ expect(server.state.toolCalls).toHaveLength(2)
3194
+ }),
3195
+ )
3196
+
3197
+ live("keeps connections apart when the configs differ", () =>
3198
+ Effect.gen(function* () {
3199
+ const server = yield* resourceServer({ modern: true, resources: false })
3200
+ const pool = yield* makePool
3201
+ const a = yield* open(pooled(server.url), pool, directories[0])
3202
+ const b = yield* open(pooled(server.url, { headers: { "x-account": "b" } }), pool, directories[0])
3203
+ expect((yield* a.mcp.tools())[0]?.inputSchema).not.toBe((yield* b.mcp.tools())[0]?.inputSchema)
3204
+ expect(server.state.toolLists).toBe(2)
3205
+ }),
3206
+ )
3207
+
3208
+ test("keys connections on everything that changes them, and on no secret or name", () => {
3209
+ const remote = new ConfigMCP.Remote({
3210
+ type: "remote",
3211
+ url: "https://mcp.example.com",
3212
+ headers: { authorization: "secret" },
3213
+ })
3214
+ const local = new ConfigMCP.Local({ type: "local", command: ["server"], environment: { TOKEN: "secret" } })
3215
+ const key = (input: Partial<Parameters<typeof McpPool.key>[0]> = {}) => McpPool.key({ config: remote, ...input })
3216
+ const localKey = (input: Partial<Parameters<typeof McpPool.key>[0]> = {}) =>
3217
+ McpPool.key({ config: local, cwd: "/a", ...input })
3218
+
3219
+ expect(key()).not.toContain("secret")
3220
+ expect(localKey()).not.toContain("secret")
3221
+ expect(key({ credential: "cred_a" })).not.toBe(key({ credential: "cred_b" }))
3222
+ expect(key({ config: new ConfigMCP.Remote({ ...remote, headers: { authorization: "other" } }) })).not.toBe(key())
3223
+ expect(key({ config: new ConfigMCP.Remote({ ...remote, codemode: false }) })).not.toBe(key())
3224
+ expect(key({ config: new ConfigMCP.Remote({ ...remote, disabled: false }) })).toBe(key())
3225
+ expect(localKey()).not.toBe(localKey({ cwd: "/b" }))
3226
+ expect(localKey({ config: new ConfigMCP.Local({ ...local, environment: { TOKEN: "other" } }) })).not.toBe(
3227
+ localKey(),
3228
+ )
3229
+ expect(localKey({ clientInfo: { name: "other", version: "1" } })).not.toBe(localKey())
3230
+ })
3231
+
3232
+ live("keeps a server that negotiates legacy private to each Location", () => {
3233
+ const captured = poolLogs()
3234
+ return Effect.gen(function* () {
3235
+ const probes: Array<ChildProcess.Command> = []
3236
+ const spawns: Array<ChildProcess.Command> = []
3237
+ const pool = yield* recordingPool(probes)
3238
+ const config = new ConfigMCP.Local({
3239
+ type: "local",
3240
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-output-schema.ts")],
3241
+ cwd: directories[0],
3242
+ pool: true,
3243
+ })
3244
+ const a = yield* open(config, pool, directories[0], { environment: recordingEnvironmentLayer(spawns) })
3245
+ const b = yield* open(config, pool, directories[0], { environment: recordingEnvironmentLayer(spawns) })
3246
+ expect(yield* status(a.mcp)).toEqual({ status: "connected" })
3247
+ expect(yield* status(b.mcp)).toEqual({ status: "connected" })
3248
+ // One discovery attempt through the pool, then each Location spawns its own, as it would unpooled.
3249
+ expect(probes).toHaveLength(1)
3250
+ expect(spawns).toHaveLength(2)
3251
+ // Once, when the verdict is recorded; the second Location skips straight to its own connection.
3252
+ expect(captured.logs).toEqual([
3253
+ ["mcp pool ignored: server speaks an older protocol", { server: "resources", version: "2025-11-25" }],
3254
+ ])
3255
+ }).pipe(Effect.provide(captured.layer))
3256
+ })
3257
+
3258
+ live("connects on its own when a server refuses the pooled handshake", () => {
3259
+ const captured = poolLogs()
3260
+ return Effect.gen(function* () {
3261
+ const probes: Array<ChildProcess.Command> = []
3262
+ const spawns: Array<ChildProcess.Command> = []
3263
+ const pool = yield* recordingPool(probes)
3264
+ // Exits during initialize unless the client declares roots, which shared connections never do.
3265
+ const config = new ConfigMCP.Local({
3266
+ type: "local",
3267
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-output-schema.ts")],
3268
+ cwd: directories[0],
3269
+ environment: { MCP_REQUIRE_ROOTS: "1" },
3270
+ pool: true,
3271
+ })
3272
+ const a = yield* open(config, pool, directories[0], { environment: recordingEnvironmentLayer(spawns) })
3273
+ expect(yield* status(a.mcp)).toEqual({ status: "connected" })
3274
+ const b = yield* open(config, pool, directories[0], { environment: recordingEnvironmentLayer(spawns) })
3275
+ expect(yield* status(b.mcp)).toEqual({ status: "connected" })
3276
+ expect(probes).toHaveLength(1)
3277
+ expect(spawns).toHaveLength(2)
3278
+ expect(captured.logs).toEqual([
3279
+ [
3280
+ "mcp pool ignored: server refused the shared connection",
3281
+ { server: "resources", error: expect.stringContaining("Connection closed") },
3282
+ ],
3283
+ ])
3284
+ }).pipe(Effect.provide(captured.layer))
3285
+ })
3286
+
3287
+ // A server that is down, or that refuses this client, would refuse a private connection too.
3288
+ for (const [code, what, attempts] of [
3289
+ [503, "was down", 3],
3290
+ [401, "rejected the credentials", 1],
3291
+ [403, "refused access", 1],
3292
+ ] as const)
3293
+ live(`keeps pooling a server that ${what} when first tried`, () => {
3294
+ const captured = poolLogs()
3295
+ return Effect.gen(function* () {
3296
+ const refusing = { value: true, count: 0 }
3297
+ const server = yield* resourceServer({
3298
+ modern: true,
3299
+ resources: false,
3300
+ respond: () => {
3301
+ if (!refusing.value) return undefined
3302
+ refusing.count += 1
3303
+ return new Response(null, { status: code })
3304
+ },
3305
+ })
3306
+ const pool = yield* makePool
3307
+ const a = yield* open(pooled(server.url), pool, directories[0])
3308
+ expect((yield* status(a.mcp))?.status).toBe("failed")
3309
+ // The startup retries transient failures, and nothing tries a private connection afterwards.
3310
+ expect(refusing.count).toBe(attempts)
3311
+ expect(captured.logs).toEqual([])
3312
+ refusing.value = false
3313
+ yield* a.mcp.connect("resources")
3314
+ yield* open(pooled(server.url), pool, directories[1])
3315
+ expect(server.state.toolLists).toBe(1)
3316
+ }).pipe(Effect.provide(captured.layer))
3317
+ })
3318
+
3319
+ live("decides a legacy server is private right after the handshake, before listing its tools", () => {
3320
+ const captured = poolLogs()
3321
+ return Effect.gen(function* () {
3322
+ const tmp = yield* tmpdirScoped()
3323
+ const wire = path.join(tmp.path, "wire")
3324
+ // Connects without roots but needs one to list its tools, which shared connections never declare.
3325
+ const config = new ConfigMCP.Local({
3326
+ type: "local",
3327
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-output-schema.ts")],
3328
+ cwd: directories[0],
3329
+ environment: { MCP_REQUIRE_ROOTS_TO_LIST: "1", MCP_WIRE_LOG: wire },
3330
+ pool: true,
3331
+ })
3332
+ const pool = yield* makePool
3333
+ const a = yield* open(config, pool, directories[0])
3334
+ const b = yield* open(config, pool, directories[1])
3335
+ expect(yield* status(a.mcp)).toEqual({ status: "connected" })
3336
+ expect(yield* status(b.mcp)).toEqual({ status: "connected" })
3337
+ const methods = (yield* Effect.promise(() => fs.readFile(wire, "utf8"))).trim().split("\n")
3338
+ const count = (method: string) => methods.filter((item) => item === method).length
3339
+ // The shared attempt probes, falls back to initialize, then closes without listing. The private
3340
+ // connections know the server is legacy, so they skip the probe; each lists its two pages.
3341
+ expect(count("server/discover")).toBe(1)
3342
+ expect(count("initialize")).toBe(3)
3343
+ expect(count("tools/list")).toBe(4)
3344
+ expect(captured.logs).toEqual([
3345
+ ["mcp pool ignored: server speaks an older protocol", { server: "resources", version: expect.any(String) }],
3346
+ ])
3347
+ }).pipe(Effect.provide(captured.layer))
3348
+ })
3349
+
3350
+ live("fails a pooled server that can't be spawned after one attempt", () =>
3351
+ Effect.gen(function* () {
3352
+ const probes: Array<ChildProcess.Command> = []
3353
+ const spawns: Array<ChildProcess.Command> = []
3354
+ const pool = yield* recordingPool(probes)
3355
+ const config = new ConfigMCP.Local({ type: "local", command: ["opencode-missing-mcp-server"], pool: true })
3356
+ const a = yield* open(config, pool, directories[0], { environment: recordingEnvironmentLayer(spawns) })
3357
+ expect((yield* status(a.mcp))?.status).toBe("failed")
3358
+ expect(probes).toHaveLength(1)
3359
+ // On Windows the spawn succeeds through the shell and the missing command shows up only as an exit
3360
+ // during the handshake, which can't be told apart from a server refusing it, so it connects on its own.
3361
+ // That exit also looks like a legacy server quitting on the version probe, so it respawns once for initialize.
3362
+ expect(spawns).toHaveLength(process.platform === "win32" ? 2 : 0)
3363
+ }),
3364
+ )
3365
+
3366
+ live("connects each Location on its own without pool", () =>
3367
+ Effect.gen(function* () {
3368
+ const server = yield* resourceServer({ modern: true, resources: false })
3369
+ const pool = yield* makePool
3370
+ const config = new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, protocol: "2026-07-28" })
3371
+ const a = yield* open(config, pool, directories[0])
3372
+ const b = yield* open(config, pool, directories[0])
3373
+ expect((yield* a.mcp.tools())[0]?.inputSchema).not.toBe((yield* b.mcp.tools())[0]?.inputSchema)
3374
+ expect(server.state.toolLists).toBe(2)
3375
+ }),
3376
+ )
3377
+
3378
+ live("closes the shared connection when its last Location lets go", () =>
3379
+ Effect.gen(function* () {
3380
+ const server = yield* resourceServer({ modern: true, resources: false })
3381
+ const pool = yield* makePool
3382
+ const a = yield* open(pooled(server.url), pool, directories[0])
3383
+ const b = yield* open(pooled(server.url), pool, directories[1])
3384
+ yield* a.shutdown
3385
+ yield* b.mcp.callTool({ server: "resources", name: "echo" })
3386
+ const c = yield* open(pooled(server.url), pool, directories[0])
3387
+ expect(server.state.toolLists).toBe(1)
3388
+
3389
+ yield* b.shutdown
3390
+ yield* c.mcp.disconnect("resources")
3391
+ yield* open(pooled(server.url), pool, directories[0])
3392
+ expect(server.state.toolLists).toBe(2)
3393
+ }),
3394
+ )
3395
+
3396
+ live("connects with the credential its key was made from, even when a sign-in lands mid-start", () =>
3397
+ Effect.gen(function* () {
3398
+ // The authorization header of every tool call, in order.
3399
+ const calls: Array<string | null> = []
3400
+ const server = yield* resourceServer({
3401
+ modern: true,
3402
+ resources: false,
3403
+ respond: async (request) => {
3404
+ if (request.method !== "POST") return undefined
3405
+ const body: unknown = await request.clone().json()
3406
+ if (isRecord(body) && body.method === "tools/call") calls.push(request.headers.get("authorization"))
3407
+ return undefined
3408
+ },
3409
+ })
3410
+ const pool = yield* makePool
3411
+ // "resources" signs in right after its first read of the credential store; "guest" never signs in.
3412
+ let signed: Integration.ID | undefined
3413
+ let reads = 0
3414
+ const row = (integrationID: Integration.ID) =>
3415
+ new Credential.Info({
3416
+ id: Credential.ID.make("cred_signed"),
3417
+ integrationID,
3418
+ label: "signed",
3419
+ value: {
3420
+ type: "oauth",
3421
+ methodID: Integration.MethodID.make("signed"),
3422
+ access: "signed-in",
3423
+ refresh: "signed-refresh",
3424
+ expires: Date.now() + 3_600_000,
3425
+ metadata: { serverUrl: server.url, tokenType: "Bearer" },
3426
+ },
3427
+ })
3428
+ const credentials: Partial<Credential.Interface> = {
3429
+ list: (integrationID) =>
3430
+ Effect.sync(() => {
3431
+ signed ??= integrationID
3432
+ if (integrationID !== signed) return []
3433
+ reads += 1
3434
+ return reads > 1 ? [row(integrationID)] : []
3435
+ }),
3436
+ get: () => Effect.sync(() => (signed ? row(signed) : undefined)),
3437
+ }
3438
+ const config = pooled(server.url, { oauth: undefined })
3439
+ const owner = yield* open(config, pool, directories[0], { credentials })
3440
+ const guest = yield* open(config, pool, directories[1], { credentials, name: "guest" })
3441
+ yield* guest.mcp.callTool({ server: "guest", name: "echo" })
3442
+ // Reconnecting picks up the sign-in under a key of its own.
3443
+ yield* owner.mcp.connect("resources")
3444
+ yield* owner.mcp.callTool({ server: "resources", name: "echo" })
3445
+ yield* guest.mcp.callTool({ server: "guest", name: "echo" })
3446
+ expect(calls).toEqual([null, "Bearer signed-in", null])
3447
+ }),
3448
+ )
3449
+
3450
+ for (const shared of [true, false])
3451
+ live(
3452
+ `registers a server's prompt commands again after reconnecting${shared ? " to a connection another Location holds" : ""}`,
3453
+ () =>
3454
+ Effect.gen(function* () {
3455
+ const server = yield* resourceServer({ modern: true, resources: false })
3456
+ const config = shared
3457
+ ? pooled(server.url)
3458
+ : new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, protocol: "2026-07-28" })
3459
+ const pool = yield* makePool
3460
+ yield* open(config, pool, directories[0])
3461
+ // The second Location gets a working bus, so the command plugin hears its MCP events.
3462
+ const hub = yield* PubSub.unbounded<{ readonly type: string }>()
3463
+ const bus = Layer.mock(Bus.Service, {
3464
+ publish: (definition, data) =>
3465
+ Effect.suspend(() => {
3466
+ const event = { id: ID.create(), type: definition.type, data } as Payload<typeof definition>
3467
+ return PubSub.publish(hub, event).pipe(Effect.as(event))
3468
+ }),
3469
+ subscribe: ((definition?: { readonly type: string }) =>
3470
+ Stream.fromPubSub(hub).pipe(
3471
+ Stream.filter((event) => !definition || event.type === definition.type),
3472
+ )) as Bus.Interface["subscribe"],
3473
+ })
3474
+ const b = yield* open(config, pool, directories[1], { bus })
3475
+ const command = Context.get(yield* Layer.build(Command.layer.pipe(Layer.provide(bus))), Command.Service)
3476
+ yield* CommandPlugin.Plugin.effect(
3477
+ host({
3478
+ command: {
3479
+ list: () => Effect.die("unused command.list"),
3480
+ transform: command.transform,
3481
+ reload: command.reload,
3482
+ },
3483
+ }),
3484
+ ).pipe(
3485
+ Effect.provideService(Mcp.Service, b.mcp),
3486
+ Effect.provide(bus),
3487
+ Effect.provideService(
3488
+ Location.Service,
3489
+ Location.Service.of(location({ directory: AbsolutePath.make(directories[1]) })),
3490
+ ),
3491
+ )
3492
+ const registered = (expected: boolean) =>
3493
+ command.get("resources:greet").pipe(
3494
+ Effect.filterOrFail((found) => (found !== undefined) === expected),
3495
+ Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
3496
+ )
3497
+ yield* registered(true)
3498
+ yield* b.mcp.disconnect("resources")
3499
+ yield* registered(false)
3500
+ yield* b.mcp.connect("resources")
3501
+ expect(yield* status(b.mcp)).toEqual({ status: "connected" })
3502
+ yield* registered(true)
3503
+ // A shared reconnect joins the open connection instead of listing again.
3504
+ expect(server.state.toolLists).toBe(shared ? 1 : 3)
3505
+ }),
3506
+ )
3507
+
3508
+ live("routes an elicitation to the Location whose call caused it", () =>
3509
+ Effect.gen(function* () {
3510
+ const server = yield* resourceServer({ modern: true, resources: false, urlElicitation: true })
3511
+ const pool = yield* makePool
3512
+ const created = yield* Deferred.make<CreatedForm>()
3513
+ const elsewhere: Form.Info[] = []
3514
+ const a = yield* open(pooled(server.url), pool, directories[0], {
3515
+ onFormCreated: (form) => Effect.sync(() => elsewhere.push(form)),
3516
+ })
3517
+ const b = yield* open(pooled(server.url), pool, directories[1], {
3518
+ onFormCreated: (form) => recordForm(created, form),
3519
+ })
3520
+ const call = yield* b.mcp.callTool({ server: "resources", name: "url-elicitation" }).pipe(Effect.forkScoped)
3521
+ const { form, directory } = yield* Deferred.await(created)
3522
+ expect(directory).toBe(directories[1])
3523
+ yield* b.forms.reply({ id: form.id, answer: { elicitation: true } })
3524
+ expect((yield* Fiber.join(call)).structured).toEqual({ action: "accept" })
3525
+ expect(elsewhere).toEqual([])
3526
+ expect(yield* a.forms.list()).toEqual([])
3527
+ }),
3528
+ )
3529
+
3530
+ live("asks every holder about an elicitation no request claims, and takes the first answer", () =>
3531
+ Effect.gen(function* () {
3532
+ const server = yield* resourceServer({ modern: true, resources: false, urlElicitation: true })
3533
+ const pool = yield* makePool
3534
+ const environment = Context.get(yield* Layer.build(hostEnvironmentLayer), Environment.Service)
3535
+ const config = new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, protocol: "2026-07-28" })
3536
+ // Each holder knows the server by its own name; the connection carries the first one's.
3537
+ const holder = (directory: string, name: string) =>
3538
+ Effect.gen(function* () {
3539
+ const asked: string[] = []
3540
+ const forms = Context.get(
3541
+ yield* Layer.build(
3542
+ Form.layer.pipe(
3543
+ Layer.provide(
3544
+ Layer.mock(Bus.Service, {
3545
+ publish: (definition, data) =>
3546
+ Effect.succeed({ id: ID.create(), type: definition.type, data } as Payload<typeof definition>),
3547
+ }),
3548
+ ),
3549
+ ),
3550
+ ),
3551
+ Form.Service,
3552
+ )
3553
+ const scope = yield* Effect.scope
3554
+ const run = yield* FiberSet.makeRuntime<never, void, never>()
3555
+ const connection = pool.connection({
3556
+ name,
3557
+ config,
3558
+ directory,
3559
+ authProvider: Effect.undefined,
3560
+ elicitation: {
3561
+ create: (request) =>
3562
+ Effect.sync(() => asked.push(request.server)).pipe(
3563
+ Effect.andThen(
3564
+ forms.ask({ sessionID: "global", title: "Confirm", fields: [{ key: "ok", type: "boolean" }] }),
3565
+ ),
3566
+ Effect.map((state) => ({ action: state.status === "answered" ? "accept" : "cancel" }) as const),
3567
+ ),
3568
+ complete: () => Effect.void,
3569
+ },
3570
+ environment,
3571
+ fetch,
3572
+ scope,
3573
+ lock: Semaphore.makeUnsafe(1).withPermit,
3574
+ callbacks: run,
3575
+ fork: run,
3576
+ events: {
3577
+ connecting: Effect.void,
3578
+ connected: Effect.void,
3579
+ failed: () => Effect.void,
3580
+ settled: Effect.void,
3581
+ closed: () => Effect.void,
3582
+ changed: () => Effect.void,
3583
+ },
3584
+ select: Effect.succeed({ key: McpPool.key({ config }), authProvider: Effect.undefined }),
3585
+ })
3586
+ yield* connection.start
3587
+ return { connection, forms, asked }
3588
+ })
3589
+ const a = yield* holder(directories[0], "first")
3590
+ const b = yield* holder(directories[1], "second")
3591
+ const client = a.connection.client
3592
+ if (!client) throw new Error("expected a shared connection")
3593
+ expect(b.connection.client).toBe(client)
3594
+
3595
+ // Called on the shared client directly, so no Location claims the request.
3596
+ const call = yield* client.callTool({ name: "url-elicitation" }).pipe(Effect.forkScoped)
3597
+ const pending = (forms: Form.Interface) =>
3598
+ forms.list().pipe(
3599
+ Effect.flatMap((list) => (list[0] ? Effect.succeed(list[0]) : Effect.fail("none"))),
3600
+ Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
3601
+ )
3602
+ const asked = yield* pending(a.forms)
3603
+ const other = yield* pending(b.forms)
3604
+ yield* a.forms.reply({ id: asked.id, answer: { ok: true } })
3605
+ expect((yield* Fiber.join(call)).structured).toEqual({ action: "accept" })
3606
+ expect((yield* b.forms.state(other.id)).status).toBe("cancelled")
3607
+ expect([a.asked, b.asked]).toEqual([["first"], ["second"]])
3608
+ }),
3609
+ )
3610
+
3611
+ live("fans tool list changes out to every Location", () =>
3612
+ Effect.gen(function* () {
3613
+ const server = yield* resourceServer({ modern: true, resources: false, listChanged: true })
3614
+ const pool = yield* makePool
3615
+ const published = [[], []] as string[][]
3616
+ const a = yield* open(pooled(server.url), pool, directories[0], { published: published[0] })
3617
+ const b = yield* open(pooled(server.url), pool, directories[1], { published: published[1] })
3618
+ published.forEach((events) => events.splice(0))
3619
+ server.state.extraTools = [{ name: "added", inputSchema: { type: "object", properties: {} } }]
3620
+ yield* Effect.promise(server.sendToolListChanged)
3621
+ for (const mcp of [a.mcp, b.mcp])
3622
+ yield* mcp.tools().pipe(
3623
+ Effect.filterOrFail((tools) => tools.some((tool) => tool.name === "added")),
3624
+ Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
3625
+ )
3626
+ expect(server.state.toolLists).toBe(2)
3627
+ for (const events of published)
3628
+ yield* Effect.sync(() => events).pipe(
3629
+ Effect.filterOrFail((events) => events.includes(McpEvent.ToolsChanged.type)),
3630
+ Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
3631
+ )
3632
+ }),
3633
+ )
3634
+
3635
+ live("answers no roots on a shared connection", () =>
3636
+ Effect.gen(function* () {
3637
+ const server = yield* resourceServer({ modern: true, resources: false, roots: true })
3638
+ const pool = yield* makePool
3639
+ const own = yield* open(
3640
+ new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false, protocol: "2026-07-28" }),
3641
+ pool,
3642
+ directories[0],
3643
+ )
3644
+ expect((yield* own.mcp.callTool({ server: "resources", name: "roots" })).structured).toEqual({
3645
+ kind: "roots",
3646
+ roots: [{ uri: Bun.pathToFileURL(directories[0]).href }],
3647
+ })
3648
+ const shared = yield* open(pooled(server.url), pool, directories[0])
3649
+ const error = yield* shared.mcp.callTool({ server: "resources", name: "roots" }).pipe(Effect.flip)
3650
+ expect(error.message).toContain("roots/list")
3651
+ }),
3652
+ )
3653
+
3654
+ live("shares a local server across directories only when its cwd is fixed", () => {
3655
+ const captured = poolLogs()
3656
+ return Effect.gen(function* () {
3657
+ const tmp = yield* tmpdirScoped()
3658
+ const server = (pids: string, cwd?: string) =>
3659
+ new ConfigMCP.Local({
3660
+ type: "local",
3661
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-modern-stdio.ts")],
3662
+ environment: { MCP_PID_FILE: path.join(tmp.path, pids) },
3663
+ cwd,
3664
+ pool: true,
3665
+ })
3666
+ const started = (pids: string) =>
3667
+ Effect.promise(() => fs.readFile(path.join(tmp.path, pids), "utf8")).pipe(
3668
+ Effect.map((text) => text.trim().split("\n")),
3669
+ )
3670
+ const pool = yield* makePool
3671
+ for (const directory of directories) yield* open(server("home", "~"), pool, directory)
3672
+ expect(yield* started("home")).toHaveLength(1)
3673
+ expect(captured.logs).toEqual([])
3674
+
3675
+ for (const directory of directories) yield* open(server("project"), pool, directory)
3676
+ expect(yield* started("project")).toHaveLength(2)
3677
+ expect(captured.logs).toEqual([
3678
+ ["mcp pool ignored: local server has no fixed cwd, so each directory runs its own", { server: "resources" }],
3679
+ ])
3680
+ }).pipe(Effect.provide(captured.layer))
3681
+ })
3682
+
3683
+ live("shares one local process, fails every holder when it dies, and closes it after the last", () =>
3684
+ Effect.gen(function* () {
3685
+ const tmp = yield* tmpdirScoped()
3686
+ const pids = path.join(tmp.path, "pids")
3687
+ const config = new ConfigMCP.Local({
3688
+ type: "local",
3689
+ command: [process.execPath, path.join(import.meta.dir, "fixture/mcp-modern-stdio.ts")],
3690
+ environment: { MCP_PID_FILE: pids },
3691
+ pool: true,
3692
+ })
3693
+ const started = () =>
3694
+ Effect.promise(() => fs.readFile(pids, "utf8")).pipe(Effect.map((text) => text.trim().split("\n").map(Number)))
3695
+ const alive = (pid: number) => {
3696
+ try {
3697
+ process.kill(pid, 0)
3698
+ return true
3699
+ } catch {
3700
+ return false
3701
+ }
3702
+ }
3703
+ const until = <A>(effect: Effect.Effect<A>, check: (value: A) => boolean) =>
3704
+ effect.pipe(
3705
+ Effect.filterOrFail(check, () => "pending"),
3706
+ Effect.retry({ times: 500, schedule: Schedule.spaced("10 millis") }),
3707
+ )
3708
+ const pool = yield* makePool
3709
+ const a = yield* open(config, pool, directories[0])
3710
+ const b = yield* open(config, pool, directories[0])
3711
+ const [first] = yield* started()
3712
+ expect(yield* started()).toHaveLength(1)
3713
+ expect((yield* a.mcp.tools())[0]?.inputSchema).toBe((yield* b.mcp.tools())[0]?.inputSchema)
3714
+
3715
+ process.kill(first!, "SIGKILL")
3716
+ for (const location of [a, b]) yield* until(status(location.mcp), (status) => status?.status === "failed")
3717
+ yield* a.mcp.connect("resources")
3718
+ expect(yield* status(a.mcp)).toEqual({ status: "connected" })
3719
+ expect((yield* status(b.mcp))?.status).toBe("failed")
3720
+ yield* b.mcp.connect("resources")
3721
+ expect(yield* status(b.mcp)).toEqual({ status: "connected" })
3722
+ const [, second] = yield* started()
3723
+ expect(yield* started()).toHaveLength(2)
3724
+
3725
+ yield* a.shutdown
3726
+ expect(alive(second!)).toBe(true)
3727
+ yield* b.mcp.callTool({ server: "resources", name: "echo" })
3728
+ yield* b.shutdown
3729
+ yield* until(
3730
+ Effect.sync(() => alive(second!)),
3731
+ (alive) => !alive,
3732
+ )
3733
+ }),
3734
+ )
3735
+
3736
+ live("keeps nothing of a Location that let go of a shared connection", () =>
3737
+ Effect.gen(function* () {
3738
+ const server = yield* resourceServer({ modern: true, resources: false, urlElicitation: true })
3739
+ const pool = yield* makePool
3740
+ // Reading a WeakRef keeps its target alive until the current job ends, so watch for finalization instead.
3741
+ const collected = new Set<string>()
3742
+ const registry = new FinalizationRegistry<string>((name) => collected.add(name))
3743
+ // The first Location opens the connection and makes a call through it, then lets go while another holds on.
3744
+ const shutdown = yield* Effect.gen(function* () {
3745
+ const created = yield* Deferred.make<CreatedForm>()
3746
+ const location = yield* open(pooled(server.url), pool, directories[0], {
3747
+ onFormCreated: (form) => recordForm(created, form),
3748
+ })
3749
+ const call = yield* location.mcp
3750
+ .callTool({ server: "resources", name: "url-elicitation" })
3751
+ .pipe(Effect.forkScoped)
3752
+ const { form } = yield* Deferred.await(created)
3753
+ yield* location.forms.reply({ id: form.id, answer: { elicitation: true } })
3754
+ yield* Fiber.join(call)
3755
+ registry.register(location.mcp, "mcp")
3756
+ registry.register(location.forms, "forms")
3757
+ return location.shutdown
3758
+ })
3759
+ const second = yield* open(pooled(server.url), pool, directories[1])
3760
+ yield* shutdown
3761
+ // The collector also scans the native stack, where a stale pointer from the shutdown can survive in
3762
+ // frames the event loop reuses. Unrelated work through the same paths overwrites those; then collect.
3763
+ for (let attempt = 0; attempt < 50 && collected.size < 2; attempt++) {
3764
+ yield* Effect.forEach(Array.from({ length: 20 }), () => Effect.promise(() => Bun.sleep(0)), {
3765
+ concurrency: "unbounded",
3766
+ })
3767
+ yield* Effect.promise(() => new Promise<void>((resolve) => setTimeout(() => resolve(Bun.gc(true)), 0)))
3768
+ }
3769
+ expect(Array.from(collected).toSorted()).toEqual(["forms", "mcp"])
3770
+ expect(yield* status(second.mcp)).toEqual({ status: "connected" })
3771
+ expect(server.state.toolLists).toBe(1)
3772
+ }),
3773
+ )
3774
+ })
3775
+
3776
+ describe("MCP events", () => {
3777
+ const ready = (mcp: Mcp.Interface) =>
3778
+ mcp.awaitStartup().pipe(
3779
+ Effect.andThen(mcp.servers()),
3780
+ Effect.map((all) => all[0]?.status),
3781
+ )
3782
+
3783
+ // Lists "job.finished", from the second listing on with its `job` argument mirrored into a header, rejects a stream
3784
+ // without that header, and answers any other `events/stream` with one `active` notification, then closes the stream.
3785
+ const eventServer = (input: { events?: boolean } = {}) => {
3786
+ const streams: Array<{ name: string | null; job: string | null; params: unknown }> = []
3787
+ let lists = 0
3788
+ return resourceServer({
3789
+ modern: true,
3790
+ events: input.events,
3791
+ respond: async (request) => {
3792
+ if (request.method !== "POST") return undefined
3793
+ const body: unknown = await request.clone().json()
3794
+ if (!isRecord(body)) return undefined
3795
+ if (body.method === "events/list" && ++lists)
3796
+ return Response.json({
3797
+ jsonrpc: "2.0",
3798
+ id: body.id,
3799
+ result: {
3800
+ resultType: "complete",
3801
+ events: [
3802
+ {
3803
+ name: "job.finished",
3804
+ delivery: ["push"],
3805
+ inputSchema: {
3806
+ type: "object",
3807
+ properties: { job: { type: "string", ...(lists > 1 ? { "x-mcp-header": "Job" } : {}) } },
3808
+ },
3809
+ payloadSchema: { type: "object" },
3810
+ },
3811
+ ],
3812
+ },
3813
+ })
3814
+ if (body.method !== "events/stream") return undefined
3815
+ const job = request.headers.get("mcp-param-job")
3816
+ streams.push({ name: request.headers.get("mcp-name"), job, params: body.params })
3817
+ if (job === null)
3818
+ return Response.json(
3819
+ { jsonrpc: "2.0", id: body.id, error: { code: -32020, message: "Header mismatch" } },
3820
+ { status: 400 },
3821
+ )
3822
+ const meta = { "io.modelcontextprotocol/subscriptionId": body.id }
3823
+ const frame = (message: Record<string, unknown>) =>
3824
+ `data: ${JSON.stringify({ jsonrpc: "2.0", ...message })}\n\n`
3825
+ return new Response(
3826
+ frame({
3827
+ method: "notifications/events/active",
3828
+ params: { cursor: "c1", truncated: false, heartbeatMs: 30_000, _meta: meta },
3829
+ }) + frame({ id: body.id, result: { resultType: "complete", _meta: meta } }),
3830
+ { headers: { "content-type": "text/event-stream" } },
3831
+ )
3832
+ },
3833
+ }).pipe(Effect.map((server) => ({ ...server, streams })))
3834
+ }
3835
+ const layer = (url: string) =>
3836
+ resourceMcpLayer(new ConfigMCP.Remote({ type: "remote", url, oauth: false, protocol: "2026-07-28" }))
3837
+
3838
+ testEffect(Layer.empty).live(
3839
+ "streams a server's events over Streamable HTTP with Mcp-Name and Mcp-Param headers",
3840
+ () =>
3841
+ Effect.gen(function* () {
3842
+ const server = yield* eventServer({ events: true })
3843
+ yield* Effect.gen(function* () {
3844
+ const mcp = yield* Mcp.Service
3845
+ expect(yield* ready(mcp)).toEqual({ status: "connected" })
3846
+ const events = yield* mcp.events("resources")
3847
+ if (!events) throw new Error("expected MCP events")
3848
+ const messages = yield* Stream.runCollect(events.stream({ name: "job.finished", arguments: { job: "j1" } }))
3849
+ expect(messages).toEqual([{ type: "active", cursor: "c1", truncated: false }])
3850
+ // The first listing has no annotation, so the stream relists after the server rejects it for the missing header.
3851
+ const params = expect.objectContaining({ name: "job.finished", arguments: { job: "j1" } })
3852
+ expect(server.streams).toEqual([
3853
+ { name: "job.finished", job: null, params },
3854
+ { name: "job.finished", job: "j1", params },
3855
+ ])
3856
+ }).pipe(Effect.provide(layer(server.url)))
3857
+ }),
3858
+ )
3859
+
3860
+ // Lists "job.finished" and holds each `events/stream` open so a test can send notifications on it or close it.
3861
+ // The first `failedOpens` opens fail, each only once the test releases it with `failOpen`.
3862
+ const streamServer = Effect.fnUntraced(function* (input: { events?: boolean; failedOpens?: number } = {}) {
3863
+ const attempts: unknown[] = []
3864
+ const failures = yield* Queue.unbounded<void>()
3865
+ const streams = yield* Queue.unbounded<{
3866
+ params: unknown
3867
+ aborted: Effect.Effect<void>
3868
+ send: (method: string, params: Record<string, unknown>) => void
3869
+ close: () => void
3870
+ }>()
3871
+ const encode = (message: Record<string, unknown>) =>
3872
+ new TextEncoder().encode(`data: ${JSON.stringify({ jsonrpc: "2.0", ...message })}\n\n`)
3873
+ const server = yield* resourceServer({
3874
+ modern: true,
3875
+ events: input.events ?? true,
3876
+ respond: async (request) => {
3877
+ if (request.method !== "POST") return undefined
3878
+ const body: unknown = await request.clone().json()
3879
+ if (isRecord(body) && body.method === "events/list")
3880
+ return Response.json({
3881
+ jsonrpc: "2.0",
3882
+ id: body.id,
3883
+ result: {
3884
+ resultType: "complete",
3885
+ events: [{ name: "job.finished", delivery: ["push"], inputSchema: {}, payloadSchema: {} }],
3886
+ },
3887
+ })
3888
+ if (!isRecord(body) || body.method !== "events/stream") return undefined
3889
+ attempts.push(body.params)
3890
+ if (attempts.length <= (input.failedOpens ?? 0)) {
3891
+ await Effect.runPromise(Queue.take(failures))
3892
+ return Response.json({ jsonrpc: "2.0", id: body.id, error: { code: -32603, message: "Temporary failure" } })
3893
+ }
3894
+ const meta = { "io.modelcontextprotocol/subscriptionId": body.id }
3895
+ const controller = Promise.withResolvers<ReadableStreamDefaultController<Uint8Array>>()
3896
+ const aborted = Deferred.makeUnsafe<void>()
3897
+ const abort = () => Deferred.doneUnsafe(aborted, Exit.void)
3898
+ Queue.offerUnsafe(streams, {
3899
+ params: body.params,
3900
+ aborted: Deferred.await(aborted),
3901
+ send: (method: string, params: Record<string, unknown>) =>
3902
+ void controller.promise.then((open) =>
3903
+ open.enqueue(encode({ method, params: { ...params, _meta: meta } })),
3904
+ ),
3905
+ close: () =>
3906
+ void controller.promise.then((open) => {
3907
+ open.enqueue(encode({ id: body.id, result: { resultType: "complete", _meta: meta } }))
3908
+ open.close()
3909
+ }),
3910
+ })
3911
+ request.signal.addEventListener("abort", abort)
3912
+ return new Response(
3913
+ new ReadableStream<Uint8Array>({
3914
+ start: (open) => controller.resolve(open),
3915
+ cancel: () => void abort(),
3916
+ }),
3917
+ { headers: { "content-type": "text/event-stream" } },
3918
+ )
3919
+ },
3920
+ })
3921
+ return { url: server.url, attempts, opened: Queue.take(streams), failOpen: Queue.offer(failures, undefined) }
3922
+ })
3923
+
3924
+ // A bus whose published events reach its subscribers, recorded in order.
3925
+ const workingBus = Effect.gen(function* () {
3926
+ const hub = yield* PubSub.unbounded<{ readonly type: string; readonly data: unknown }>()
3927
+ const published: Array<{ readonly type: string; readonly data: unknown }> = []
3928
+ const updates = yield* Queue.unbounded<void>()
3929
+ const layer = Layer.mock(Bus.Service, {
3930
+ publish: (definition, data) =>
3931
+ Effect.suspend(() => {
3932
+ const event = { id: ID.create(), type: definition.type, data } as Payload<typeof definition>
3933
+ published.push({ type: definition.type, data })
3934
+ Queue.offerUnsafe(updates, undefined)
3935
+ return PubSub.publish(hub, event).pipe(Effect.as(event))
3936
+ }),
3937
+ subscribe: ((definition?: { readonly type: string }) =>
3938
+ Stream.fromPubSub(hub).pipe(
3939
+ Stream.filter((event) => !definition || event.type === definition.type),
3940
+ )) as Bus.Interface["subscribe"],
3941
+ })
3942
+ // Recheck the snapshot on publication; buffer signals that arrived before the assertion.
3943
+ const until = <A>(snapshot: Effect.Effect<A>, ready: (value: A) => boolean) =>
3944
+ Effect.gen(function* () {
3945
+ while (true) {
3946
+ const value = yield* snapshot
3947
+ if (ready(value)) return value
3948
+ yield* Queue.take(updates)
3949
+ }
3950
+ })
3951
+ const delivered = (count: number) =>
3952
+ until(
3953
+ Effect.sync(() => published.filter((event) => event.type === "experimental.mcp.event")),
3954
+ (events) => events.length >= count,
3955
+ )
3956
+ return { layer, published, until, delivered }
3957
+ })
3958
+
3959
+ const subscriptionLayer = (url: string, bus: Layer.Layer<Bus.Service>) =>
3960
+ resourceMcpLayer(
3961
+ new ConfigMCP.Remote({ type: "remote", url, oauth: false, protocol: "2026-07-28" }),
3962
+ undefined,
3963
+ undefined,
3964
+ { bus },
3965
+ )
3966
+
3967
+ const only = (mcp: Mcp.Interface) => mcp.subscriptions().pipe(Effect.map((all) => all[0]))
3968
+
3969
+ testEffect(Layer.empty).live("publishes a subscription's events on the bus and follows its status", () =>
3970
+ Effect.gen(function* () {
3971
+ const server = yield* streamServer()
3972
+ const bus = yield* workingBus
3973
+ yield* Effect.gen(function* () {
3974
+ const mcp = yield* Mcp.Service
3975
+ expect(yield* ready(mcp)).toEqual({ status: "connected" })
3976
+ const subscription = yield* mcp.subscribe("resources", {
3977
+ name: "job.finished",
3978
+ arguments: { job: "j1", filter: { a: 1, b: 2 } },
3979
+ })
3980
+ expect(subscription).toMatchObject({
3981
+ id: "mcpsub_2c691983d6df57af6bb5e2e8",
3982
+ server: "resources",
3983
+ status: { status: "pending" },
3984
+ cursor: null,
3985
+ })
3986
+ const stream = yield* server.opened
3987
+ stream.send("notifications/events/active", { cursor: "c1", truncated: false, heartbeatMs: 30_000 })
3988
+ yield* bus.until(only(mcp), (sub) => sub?.status.status === "active")
3989
+ stream.send("notifications/events/event", {
3990
+ eventId: "e1",
3991
+ name: "job.finished",
3992
+ timestamp: "2026-11-11T00:00:00Z",
3993
+ data: { job: "j1", ok: false, note: null },
3994
+ cursor: "c2",
3995
+ })
3996
+ expect(yield* bus.delivered(1)).toEqual([
3997
+ {
3998
+ type: "experimental.mcp.event",
3999
+ data: {
4000
+ id: subscription.id,
4001
+ server: "resources",
4002
+ name: "job.finished",
4003
+ eventId: "e1",
4004
+ timestamp: "2026-11-11T00:00:00Z",
4005
+ data: { job: "j1", ok: false, note: null },
4006
+ cursor: "c2",
4007
+ },
4008
+ },
4009
+ ])
4010
+ expect(bus.published).toContainEqual({
4011
+ type: "experimental.mcp.subscription.changed",
4012
+ data: { id: subscription.id },
4013
+ })
4014
+
4015
+ // The same arguments in another key order are the same subscription.
4016
+ const again = yield* mcp.subscribe("resources", {
4017
+ name: "job.finished",
4018
+ arguments: { filter: { b: 2, a: 1 }, job: "j1" },
4019
+ })
4020
+ expect(again.id).toBe(subscription.id)
4021
+ expect(server.attempts).toHaveLength(1)
4022
+
4023
+ yield* mcp.unsubscribe(subscription.id)
4024
+ expect(yield* mcp.subscriptions()).toEqual([])
4025
+ yield* stream.aborted
4026
+ }).pipe(Effect.provide(subscriptionLayer(server.url, bus.layer)))
4027
+ }),
4028
+ )
4029
+
4030
+ const finishedEvent = (eventId: string, cursor: string) => ({
4031
+ eventId,
4032
+ cursor,
4033
+ name: "job.finished",
4034
+ timestamp: "2026-11-11T00:00:00Z",
4035
+ data: {},
4036
+ })
4037
+
4038
+ testEffect(Layer.empty).effect(
4039
+ "backs off failed opens, resets after active, and resumes with a replay gap once",
4040
+ () =>
4041
+ Effect.gen(function* () {
4042
+ const server = yield* streamServer({ failedOpens: 2 })
4043
+ const bus = yield* workingBus
4044
+ yield* Effect.gen(function* () {
4045
+ const mcp = yield* Mcp.Service
4046
+ expect(yield* ready(mcp)).toEqual({ status: "connected" })
4047
+ const events = yield* mcp.events("resources")
4048
+ if (!events) throw new Error("expected MCP events")
4049
+ const clock = yield* Clock.Clock
4050
+ const openedAt: number[] = []
4051
+ const failed = yield* Queue.unbounded<void>()
4052
+ const open = events.stream
4053
+ // A failed open stays pending. Wait for the client stream to fail, not just for the server to reply.
4054
+ using observer = spyOn(events, "stream")
4055
+ observer.mockImplementation((input) => {
4056
+ openedAt.push(clock.currentTimeMillisUnsafe())
4057
+ return open(input).pipe(Stream.onError(() => Queue.offer(failed, undefined)))
4058
+ })
4059
+ // Each reopen waits its backoff delay after the stream ended, jittered to between 0.8 and 1.2 times it.
4060
+ // The test clock only moves when adjusted, so reading it once the end is seen gives the exact time. A failed
4061
+ // open is released only after the adjust that started it returns: an HTTP reply that landed mid-adjust would
4062
+ // start the next delay at an earlier clock time than the one read here.
4063
+ const waited = (delay: number, since: number) => {
4064
+ const gap = openedAt[openedAt.length - 1] - since
4065
+ expect(gap).toBeGreaterThanOrEqual(delay * 0.8)
4066
+ expect(gap).toBeLessThanOrEqual(delay * 1.2)
4067
+ }
4068
+ yield* mcp.subscribe("resources", { name: "job.finished" })
4069
+ yield* server.failOpen
4070
+ yield* Queue.take(failed)
4071
+ const firstFailure = clock.currentTimeMillisUnsafe()
4072
+ yield* TestClock.adjust("1200 millis")
4073
+ expect(openedAt).toHaveLength(2)
4074
+ waited(1000, firstFailure)
4075
+ yield* server.failOpen
4076
+ yield* Queue.take(failed)
4077
+ const secondFailure = clock.currentTimeMillisUnsafe()
4078
+ yield* TestClock.adjust("2400 millis")
4079
+ expect(openedAt).toHaveLength(3)
4080
+ waited(2000, secondFailure)
4081
+ const first = yield* server.opened
4082
+ first.send("notifications/events/active", { cursor: "c1", truncated: false, heartbeatMs: 30_000 })
4083
+ yield* bus.until(only(mcp), (sub) => sub?.status.status === "active")
4084
+ first.send("notifications/events/heartbeat", { cursor: "c5" })
4085
+ const closedAt = clock.currentTimeMillisUnsafe()
4086
+ first.close()
4087
+ expect(yield* bus.until(only(mcp), (sub) => sub?.status.status === "pending")).toMatchObject({ cursor: "c5" })
4088
+ yield* TestClock.adjust("1200 millis")
4089
+ expect(openedAt).toHaveLength(4)
4090
+ waited(1000, closedAt)
4091
+ const reopened = yield* server.opened
4092
+ expect(server.attempts).toHaveLength(4)
4093
+ expect(reopened.params).toMatchObject({ name: "job.finished", cursor: "c5" })
4094
+ reopened.send("notifications/events/active", { cursor: "c8", truncated: true, heartbeatMs: 30_000 })
4095
+ reopened.send("notifications/events/event", finishedEvent("e9", "c9"))
4096
+ reopened.send("notifications/events/event", finishedEvent("e10", "c10"))
4097
+ const delivered = yield* bus.delivered(2)
4098
+ expect(delivered).toMatchObject([{ data: { eventId: "e9", truncated: true } }, { data: { eventId: "e10" } }])
4099
+ expect(delivered[1].data).not.toHaveProperty("truncated")
4100
+ reopened.close()
4101
+ expect(yield* bus.until(only(mcp), (sub) => sub?.status.status === "pending")).toMatchObject({
4102
+ cursor: "c10",
4103
+ })
4104
+ }).pipe(Effect.provide(subscriptionLayer(server.url, bus.layer)))
4105
+ }),
4106
+ )
4107
+
4108
+ testEffect(Layer.empty).effect("ends a subscription the server terminates or rejects, without reopening it", () =>
4109
+ Effect.gen(function* () {
4110
+ const server = yield* streamServer()
4111
+ const bus = yield* workingBus
4112
+ yield* Effect.gen(function* () {
4113
+ const mcp = yield* Mcp.Service
4114
+ expect(yield* ready(mcp)).toEqual({ status: "connected" })
4115
+ const finished = yield* mcp.subscribe("resources", { name: "job.finished" })
4116
+ const stream = yield* server.opened
4117
+ stream.send("notifications/events/terminated", { error: { code: -32024, message: "Revoked" } })
4118
+
4119
+ const missing = yield* mcp.subscribe("resources", { name: "missing" })
4120
+ const status = (id: string) =>
4121
+ mcp.subscriptions().pipe(Effect.map((all) => all.find((sub) => sub.id === id)?.status))
4122
+ expect(yield* bus.until(status(finished.id), (value) => value?.status === "ended")).toEqual({
4123
+ status: "ended",
4124
+ reason: "terminated",
4125
+ error: { code: -32024, message: "Revoked" },
4126
+ })
4127
+ expect(yield* bus.until(status(missing.id), (value) => value?.status === "ended")).toMatchObject({
4128
+ status: "ended",
4129
+ reason: "rejected",
4130
+ error: { code: -32023 },
4131
+ })
4132
+ yield* TestClock.adjust("30 seconds")
4133
+ // "missing" isn't listed, so the client refuses it without asking the server.
4134
+ expect(server.attempts).toMatchObject([{ name: "job.finished" }])
4135
+ }).pipe(Effect.provide(subscriptionLayer(server.url, bus.layer)))
4136
+ }),
4137
+ )
4138
+
4139
+ testEffect(Layer.empty).live("reopens without a replay gap when cursorless, and ends when disabled", () =>
4140
+ Effect.gen(function* () {
4141
+ const server = yield* streamServer()
4142
+ const bus = yield* workingBus
4143
+ yield* Effect.gen(function* () {
4144
+ const mcp = yield* Mcp.Service
4145
+ expect(yield* ready(mcp)).toEqual({ status: "connected" })
4146
+ yield* mcp.subscribe("resources", { name: "job.finished" })
4147
+ const first = yield* server.opened
4148
+ first.send("notifications/events/active", { cursor: null, heartbeatMs: 30_000 })
4149
+ yield* bus.until(only(mcp), (sub) => sub?.status.status === "active")
4150
+
4151
+ yield* mcp.connect("resources")
4152
+ const reopened = yield* server.opened
4153
+ yield* first.aborted
4154
+ expect(reopened.params).toMatchObject({ cursor: null })
4155
+ // The null cursor means replay is unsupported; reconnecting is not evidence of a gap.
4156
+ reopened.send("notifications/events/active", { cursor: null, truncated: false, heartbeatMs: 30_000 })
4157
+ reopened.send("notifications/events/event", finishedEvent("e2", "c2"))
4158
+ const delivered = yield* bus.delivered(1)
4159
+ expect(delivered).toMatchObject([{ data: { eventId: "e2" } }])
4160
+ expect(delivered[0].data).not.toHaveProperty("truncated")
4161
+
4162
+ yield* mcp.disconnect("resources")
4163
+ expect(yield* bus.until(only(mcp), (sub) => sub?.status.status === "ended")).toMatchObject({
4164
+ status: { status: "ended", reason: "unavailable" },
4165
+ cursor: "c2",
4166
+ })
4167
+ }).pipe(Effect.provide(subscriptionLayer(server.url, bus.layer)))
4168
+ }),
4169
+ )
4170
+
4171
+ testEffect(Layer.empty).live("ends a subscription at a server without events", () =>
4172
+ Effect.gen(function* () {
4173
+ const plain = yield* streamServer({ events: false })
4174
+ const bus = yield* workingBus
4175
+ yield* Effect.gen(function* () {
4176
+ const mcp = yield* Mcp.Service
4177
+ expect(yield* ready(mcp)).toEqual({ status: "connected" })
4178
+ yield* mcp.subscribe("resources", { name: "job.finished" })
4179
+ expect(yield* bus.until(only(mcp), (sub) => sub?.status.status === "ended")).toMatchObject({
4180
+ status: { status: "ended", reason: "unavailable" },
4181
+ })
4182
+ }).pipe(Effect.provide(subscriptionLayer(plain.url, bus.layer)))
4183
+ }),
4184
+ )
4185
+
4186
+ testEffect(Layer.empty).live("offers no events from a server without them", () =>
4187
+ Effect.gen(function* () {
4188
+ const plain = yield* eventServer()
4189
+ yield* Effect.gen(function* () {
4190
+ const mcp = yield* Mcp.Service
4191
+ expect(yield* ready(mcp)).toEqual({ status: "connected" })
4192
+ expect(yield* mcp.events("resources")).toBeUndefined()
4193
+ }).pipe(Effect.provide(layer(plain.url)))
4194
+ }),
4195
+ )
4196
+ })