@yolk-sdk/emulators 0.1.0-canary.100

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 (338) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2165 -0
  3. package/dist/anthropic.d.mts +269 -0
  4. package/dist/anthropic.d.mts.map +1 -0
  5. package/dist/anthropic.mjs +177 -0
  6. package/dist/anthropic.mjs.map +1 -0
  7. package/dist/chat-completions.d.mts +288 -0
  8. package/dist/chat-completions.d.mts.map +1 -0
  9. package/dist/chat-completions.mjs +451 -0
  10. package/dist/chat-completions.mjs.map +1 -0
  11. package/dist/codex.d.mts +265 -0
  12. package/dist/codex.d.mts.map +1 -0
  13. package/dist/codex.mjs +199 -0
  14. package/dist/codex.mjs.map +1 -0
  15. package/dist/dropbox/api.d.mts +63 -0
  16. package/dist/dropbox/api.d.mts.map +1 -0
  17. package/dist/dropbox/api.mjs +565 -0
  18. package/dist/dropbox/api.mjs.map +1 -0
  19. package/dist/dropbox/state.d.mts +136 -0
  20. package/dist/dropbox/state.d.mts.map +1 -0
  21. package/dist/dropbox/state.mjs +209 -0
  22. package/dist/dropbox/state.mjs.map +1 -0
  23. package/dist/dropbox.d.mts +79 -0
  24. package/dist/dropbox.d.mts.map +1 -0
  25. package/dist/dropbox.mjs +124 -0
  26. package/dist/dropbox.mjs.map +1 -0
  27. package/dist/email-fixtures.d.mts +36 -0
  28. package/dist/email-fixtures.d.mts.map +1 -0
  29. package/dist/email-fixtures.mjs +1080 -0
  30. package/dist/email-fixtures.mjs.map +1 -0
  31. package/dist/email.d.mts +160 -0
  32. package/dist/email.d.mts.map +1 -0
  33. package/dist/email.mjs +608 -0
  34. package/dist/email.mjs.map +1 -0
  35. package/dist/emulator-compose.d.mts +40 -0
  36. package/dist/emulator-compose.d.mts.map +1 -0
  37. package/dist/emulator-compose.mjs +91 -0
  38. package/dist/emulator-compose.mjs.map +1 -0
  39. package/dist/emulator-http.d.mts +53 -0
  40. package/dist/emulator-http.d.mts.map +1 -0
  41. package/dist/emulator-http.mjs +117 -0
  42. package/dist/emulator-http.mjs.map +1 -0
  43. package/dist/emulator-kernel.d.mts +176 -0
  44. package/dist/emulator-kernel.d.mts.map +1 -0
  45. package/dist/emulator-kernel.mjs +413 -0
  46. package/dist/emulator-kernel.mjs.map +1 -0
  47. package/dist/fixture-route.d.mts +129 -0
  48. package/dist/fixture-route.d.mts.map +1 -0
  49. package/dist/fixture-route.mjs +257 -0
  50. package/dist/fixture-route.mjs.map +1 -0
  51. package/dist/fortnox/api.d.mts +92 -0
  52. package/dist/fortnox/api.d.mts.map +1 -0
  53. package/dist/fortnox/api.mjs +750 -0
  54. package/dist/fortnox/api.mjs.map +1 -0
  55. package/dist/fortnox/state.d.mts +533 -0
  56. package/dist/fortnox/state.d.mts.map +1 -0
  57. package/dist/fortnox/state.mjs +612 -0
  58. package/dist/fortnox/state.mjs.map +1 -0
  59. package/dist/fortnox.d.mts +128 -0
  60. package/dist/fortnox.d.mts.map +1 -0
  61. package/dist/fortnox.mjs +403 -0
  62. package/dist/fortnox.mjs.map +1 -0
  63. package/dist/gateway-evaluate-recordings.d.mts +12 -0
  64. package/dist/gateway-evaluate-recordings.d.mts.map +1 -0
  65. package/dist/gateway-evaluate-recordings.mjs +128 -0
  66. package/dist/gateway-evaluate-recordings.mjs.map +1 -0
  67. package/dist/gateway.d.mts +272 -0
  68. package/dist/gateway.d.mts.map +1 -0
  69. package/dist/gateway.mjs +400 -0
  70. package/dist/gateway.mjs.map +1 -0
  71. package/dist/github/api.d.mts +63 -0
  72. package/dist/github/api.d.mts.map +1 -0
  73. package/dist/github/api.mjs +527 -0
  74. package/dist/github/api.mjs.map +1 -0
  75. package/dist/github/state.d.mts +272 -0
  76. package/dist/github/state.d.mts.map +1 -0
  77. package/dist/github/state.mjs +303 -0
  78. package/dist/github/state.mjs.map +1 -0
  79. package/dist/github.d.mts +77 -0
  80. package/dist/github.d.mts.map +1 -0
  81. package/dist/github.mjs +180 -0
  82. package/dist/github.mjs.map +1 -0
  83. package/dist/google/calendar.d.mts +10 -0
  84. package/dist/google/calendar.d.mts.map +1 -0
  85. package/dist/google/calendar.mjs +252 -0
  86. package/dist/google/calendar.mjs.map +1 -0
  87. package/dist/google/drive.d.mts +8 -0
  88. package/dist/google/drive.d.mts.map +1 -0
  89. package/dist/google/drive.mjs +252 -0
  90. package/dist/google/drive.mjs.map +1 -0
  91. package/dist/google/gmail.d.mts +10 -0
  92. package/dist/google/gmail.d.mts.map +1 -0
  93. package/dist/google/gmail.mjs +591 -0
  94. package/dist/google/gmail.mjs.map +1 -0
  95. package/dist/google/shared.d.mts +107 -0
  96. package/dist/google/shared.d.mts.map +1 -0
  97. package/dist/google/shared.mjs +146 -0
  98. package/dist/google/shared.mjs.map +1 -0
  99. package/dist/google/state.d.mts +385 -0
  100. package/dist/google/state.d.mts.map +1 -0
  101. package/dist/google/state.mjs +496 -0
  102. package/dist/google/state.mjs.map +1 -0
  103. package/dist/google.d.mts +75 -0
  104. package/dist/google.d.mts.map +1 -0
  105. package/dist/google.mjs +210 -0
  106. package/dist/google.mjs.map +1 -0
  107. package/dist/linkedin-search/api.d.mts +45 -0
  108. package/dist/linkedin-search/api.d.mts.map +1 -0
  109. package/dist/linkedin-search/api.mjs +181 -0
  110. package/dist/linkedin-search/api.mjs.map +1 -0
  111. package/dist/linkedin-search/state.d.mts +123 -0
  112. package/dist/linkedin-search/state.d.mts.map +1 -0
  113. package/dist/linkedin-search/state.mjs +261 -0
  114. package/dist/linkedin-search/state.mjs.map +1 -0
  115. package/dist/linkedin-search.d.mts +69 -0
  116. package/dist/linkedin-search.d.mts.map +1 -0
  117. package/dist/linkedin-search.mjs +158 -0
  118. package/dist/linkedin-search.mjs.map +1 -0
  119. package/dist/mcp/afloat-recordings.d.mts +8 -0
  120. package/dist/mcp/afloat-recordings.d.mts.map +1 -0
  121. package/dist/mcp/afloat-recordings.mjs +918 -0
  122. package/dist/mcp/afloat-recordings.mjs.map +1 -0
  123. package/dist/mcp/api.d.mts +45 -0
  124. package/dist/mcp/api.d.mts.map +1 -0
  125. package/dist/mcp/api.mjs +609 -0
  126. package/dist/mcp/api.mjs.map +1 -0
  127. package/dist/mcp/recordings.d.mts +40 -0
  128. package/dist/mcp/recordings.d.mts.map +1 -0
  129. package/dist/mcp/recordings.mjs +2390 -0
  130. package/dist/mcp/recordings.mjs.map +1 -0
  131. package/dist/mcp/state.d.mts +86 -0
  132. package/dist/mcp/state.d.mts.map +1 -0
  133. package/dist/mcp/state.mjs +98 -0
  134. package/dist/mcp/state.mjs.map +1 -0
  135. package/dist/mcp.d.mts +85 -0
  136. package/dist/mcp.d.mts.map +1 -0
  137. package/dist/mcp.mjs +264 -0
  138. package/dist/mcp.mjs.map +1 -0
  139. package/dist/messages.d.mts +183 -0
  140. package/dist/messages.d.mts.map +1 -0
  141. package/dist/messages.mjs +532 -0
  142. package/dist/messages.mjs.map +1 -0
  143. package/dist/microsoft/api.d.mts +47 -0
  144. package/dist/microsoft/api.d.mts.map +1 -0
  145. package/dist/microsoft/api.mjs +178 -0
  146. package/dist/microsoft/api.mjs.map +1 -0
  147. package/dist/microsoft/calendar.d.mts +30 -0
  148. package/dist/microsoft/calendar.d.mts.map +1 -0
  149. package/dist/microsoft/calendar.mjs +271 -0
  150. package/dist/microsoft/calendar.mjs.map +1 -0
  151. package/dist/microsoft/drive.d.mts +36 -0
  152. package/dist/microsoft/drive.d.mts.map +1 -0
  153. package/dist/microsoft/drive.mjs +298 -0
  154. package/dist/microsoft/drive.mjs.map +1 -0
  155. package/dist/microsoft/graph.d.mts +198 -0
  156. package/dist/microsoft/graph.d.mts.map +1 -0
  157. package/dist/microsoft/graph.mjs +264 -0
  158. package/dist/microsoft/graph.mjs.map +1 -0
  159. package/dist/microsoft/mail.d.mts +48 -0
  160. package/dist/microsoft/mail.d.mts.map +1 -0
  161. package/dist/microsoft/mail.mjs +488 -0
  162. package/dist/microsoft/mail.mjs.map +1 -0
  163. package/dist/microsoft/state.d.mts +480 -0
  164. package/dist/microsoft/state.d.mts.map +1 -0
  165. package/dist/microsoft/state.mjs +625 -0
  166. package/dist/microsoft/state.mjs.map +1 -0
  167. package/dist/microsoft.d.mts +168 -0
  168. package/dist/microsoft.d.mts.map +1 -0
  169. package/dist/microsoft.mjs +483 -0
  170. package/dist/microsoft.mjs.map +1 -0
  171. package/dist/node.d.mts +47 -0
  172. package/dist/node.d.mts.map +1 -0
  173. package/dist/node.mjs +178 -0
  174. package/dist/node.mjs.map +1 -0
  175. package/dist/notion/api.d.mts +51 -0
  176. package/dist/notion/api.d.mts.map +1 -0
  177. package/dist/notion/api.mjs +507 -0
  178. package/dist/notion/api.mjs.map +1 -0
  179. package/dist/notion/state.d.mts +329 -0
  180. package/dist/notion/state.d.mts.map +1 -0
  181. package/dist/notion/state.mjs +432 -0
  182. package/dist/notion/state.mjs.map +1 -0
  183. package/dist/notion.d.mts +72 -0
  184. package/dist/notion.d.mts.map +1 -0
  185. package/dist/notion.mjs +127 -0
  186. package/dist/notion.mjs.map +1 -0
  187. package/dist/openai.d.mts +165 -0
  188. package/dist/openai.d.mts.map +1 -0
  189. package/dist/openai.mjs +141 -0
  190. package/dist/openai.mjs.map +1 -0
  191. package/dist/opencode-recordings.d.mts +7 -0
  192. package/dist/opencode-recordings.d.mts.map +1 -0
  193. package/dist/opencode-recordings.mjs +222 -0
  194. package/dist/opencode-recordings.mjs.map +1 -0
  195. package/dist/opencode.d.mts +70 -0
  196. package/dist/opencode.d.mts.map +1 -0
  197. package/dist/opencode.mjs +217 -0
  198. package/dist/opencode.mjs.map +1 -0
  199. package/dist/r2-fixtures.d.mts +36 -0
  200. package/dist/r2-fixtures.d.mts.map +1 -0
  201. package/dist/r2-fixtures.mjs +245 -0
  202. package/dist/r2-fixtures.mjs.map +1 -0
  203. package/dist/r2-guard.d.mts +43 -0
  204. package/dist/r2-guard.d.mts.map +1 -0
  205. package/dist/r2-guard.mjs +216 -0
  206. package/dist/r2-guard.mjs.map +1 -0
  207. package/dist/r2.d.mts +166 -0
  208. package/dist/r2.d.mts.map +1 -0
  209. package/dist/r2.mjs +517 -0
  210. package/dist/r2.mjs.map +1 -0
  211. package/dist/responses.d.mts +231 -0
  212. package/dist/responses.d.mts.map +1 -0
  213. package/dist/responses.mjs +556 -0
  214. package/dist/responses.mjs.map +1 -0
  215. package/dist/route-evidence.d.mts +45 -0
  216. package/dist/route-evidence.d.mts.map +1 -0
  217. package/dist/route-evidence.mjs +56 -0
  218. package/dist/route-evidence.mjs.map +1 -0
  219. package/dist/router.d.mts +93 -0
  220. package/dist/router.d.mts.map +1 -0
  221. package/dist/router.mjs +259 -0
  222. package/dist/router.mjs.map +1 -0
  223. package/dist/stateful-core.d.mts +17 -0
  224. package/dist/stateful-core.d.mts.map +1 -0
  225. package/dist/stateful-core.mjs +41 -0
  226. package/dist/stateful-core.mjs.map +1 -0
  227. package/dist/stateful-emulator.d.mts +578 -0
  228. package/dist/stateful-emulator.d.mts.map +1 -0
  229. package/dist/stateful-emulator.mjs +1248 -0
  230. package/dist/stateful-emulator.mjs.map +1 -0
  231. package/dist/stateful-secrets.d.mts +84 -0
  232. package/dist/stateful-secrets.d.mts.map +1 -0
  233. package/dist/stateful-secrets.mjs +216 -0
  234. package/dist/stateful-secrets.mjs.map +1 -0
  235. package/dist/subscription-usage-recordings.d.mts +9 -0
  236. package/dist/subscription-usage-recordings.d.mts.map +1 -0
  237. package/dist/subscription-usage-recordings.mjs +53 -0
  238. package/dist/subscription-usage-recordings.mjs.map +1 -0
  239. package/dist/subscription-usage.d.mts +53 -0
  240. package/dist/subscription-usage.d.mts.map +1 -0
  241. package/dist/subscription-usage.mjs +21 -0
  242. package/dist/subscription-usage.mjs.map +1 -0
  243. package/dist/telegram/api.d.mts +34 -0
  244. package/dist/telegram/api.d.mts.map +1 -0
  245. package/dist/telegram/api.mjs +257 -0
  246. package/dist/telegram/api.mjs.map +1 -0
  247. package/dist/telegram/state.d.mts +128 -0
  248. package/dist/telegram/state.d.mts.map +1 -0
  249. package/dist/telegram/state.mjs +154 -0
  250. package/dist/telegram/state.mjs.map +1 -0
  251. package/dist/telegram.d.mts +62 -0
  252. package/dist/telegram.d.mts.map +1 -0
  253. package/dist/telegram.mjs +127 -0
  254. package/dist/telegram.mjs.map +1 -0
  255. package/dist/todoist/api.d.mts +55 -0
  256. package/dist/todoist/api.d.mts.map +1 -0
  257. package/dist/todoist/api.mjs +415 -0
  258. package/dist/todoist/api.mjs.map +1 -0
  259. package/dist/todoist/state.d.mts +275 -0
  260. package/dist/todoist/state.d.mts.map +1 -0
  261. package/dist/todoist/state.mjs +345 -0
  262. package/dist/todoist/state.mjs.map +1 -0
  263. package/dist/todoist.d.mts +68 -0
  264. package/dist/todoist.d.mts.map +1 -0
  265. package/dist/todoist.mjs +181 -0
  266. package/dist/todoist.mjs.map +1 -0
  267. package/dist/xai.d.mts +267 -0
  268. package/dist/xai.d.mts.map +1 -0
  269. package/dist/xai.mjs +252 -0
  270. package/dist/xai.mjs.map +1 -0
  271. package/package.json +157 -0
  272. package/src/anthropic.ts +289 -0
  273. package/src/chat-completions.ts +924 -0
  274. package/src/codex.ts +296 -0
  275. package/src/dropbox/api.ts +1084 -0
  276. package/src/dropbox/state.ts +364 -0
  277. package/src/dropbox.ts +203 -0
  278. package/src/email-fixtures.ts +1297 -0
  279. package/src/email.ts +1108 -0
  280. package/src/emulator-compose.ts +147 -0
  281. package/src/emulator-http.ts +184 -0
  282. package/src/emulator-kernel.ts +844 -0
  283. package/src/fixture-route.ts +561 -0
  284. package/src/fortnox/api.ts +1352 -0
  285. package/src/fortnox/state.ts +798 -0
  286. package/src/fortnox.ts +801 -0
  287. package/src/gateway-evaluate-recordings.ts +153 -0
  288. package/src/gateway.ts +530 -0
  289. package/src/github/api.ts +986 -0
  290. package/src/github/state.ts +439 -0
  291. package/src/github.ts +271 -0
  292. package/src/google/calendar.ts +486 -0
  293. package/src/google/drive.ts +471 -0
  294. package/src/google/gmail.ts +1011 -0
  295. package/src/google/shared.ts +321 -0
  296. package/src/google/state.ts +686 -0
  297. package/src/google.ts +298 -0
  298. package/src/linkedin-search/api.ts +363 -0
  299. package/src/linkedin-search/state.ts +373 -0
  300. package/src/linkedin-search.ts +241 -0
  301. package/src/mcp/afloat-recordings.ts +1040 -0
  302. package/src/mcp/api.ts +1105 -0
  303. package/src/mcp/recordings.ts +2665 -0
  304. package/src/mcp/state.ts +144 -0
  305. package/src/mcp.ts +364 -0
  306. package/src/messages.ts +844 -0
  307. package/src/microsoft/api.ts +426 -0
  308. package/src/microsoft/calendar.ts +491 -0
  309. package/src/microsoft/drive.ts +541 -0
  310. package/src/microsoft/graph.ts +550 -0
  311. package/src/microsoft/mail.ts +833 -0
  312. package/src/microsoft/state.ts +822 -0
  313. package/src/microsoft.ts +982 -0
  314. package/src/node.ts +293 -0
  315. package/src/notion/api.ts +976 -0
  316. package/src/notion/state.ts +512 -0
  317. package/src/notion.ts +210 -0
  318. package/src/openai.ts +198 -0
  319. package/src/opencode-recordings.ts +257 -0
  320. package/src/opencode.ts +271 -0
  321. package/src/r2-fixtures.ts +295 -0
  322. package/src/r2-guard.ts +324 -0
  323. package/src/r2.ts +890 -0
  324. package/src/responses.ts +901 -0
  325. package/src/route-evidence.ts +90 -0
  326. package/src/router.ts +490 -0
  327. package/src/stateful-core.ts +70 -0
  328. package/src/stateful-emulator.ts +2620 -0
  329. package/src/stateful-secrets.ts +299 -0
  330. package/src/subscription-usage-recordings.ts +77 -0
  331. package/src/subscription-usage.ts +68 -0
  332. package/src/telegram/api.ts +437 -0
  333. package/src/telegram/state.ts +229 -0
  334. package/src/telegram.ts +227 -0
  335. package/src/todoist/api.ts +736 -0
  336. package/src/todoist/state.ts +456 -0
  337. package/src/todoist.ts +316 -0
  338. package/src/xai.ts +341 -0
package/src/mcp/api.ts ADDED
@@ -0,0 +1,1105 @@
1
+ /**
2
+ * MCP emulator route table (internal): one wire route per recorded HTTP shape (`POST /modern/mcp`,
3
+ * `POST /legacy/mcp`, `GET /legacy/mcp` on the synthetic origin, and `POST /mcp` on the Afloat
4
+ * origin), each answering only the JSON-RPC methods its profile's fixtures record, as manifest
5
+ * variants (`RPC <origin><path>#<method>`, plus the `GET` row).
6
+ *
7
+ * A request is admitted only when it equals a recorded request (`src/mcp/recordings.ts`) within
8
+ * the latitude: the MCP headers (`accept`, `content-type`, `mcp-method`, `mcp-protocol-version`,
9
+ * `mcp-name`, `last-event-id`) equal the recorded values or are absent where the recording has
10
+ * none; `mcp-session-id` is present exactly where recorded; the body has exactly the recorded
11
+ * keys; the id is any JSON-RPC id of the accepted form where one is recorded; and `params` equal
12
+ * the recorded ones except for JSON key order and the `_meta` client info's name and version
13
+ * (and, on the second page of the paged listing, the cursor, checked by issuance). Everything
14
+ * else is refused with a constant reason. The answer is the recorded one with only the request id
15
+ * substituted where the recording carries the recorded request id (the top-level `id` of a JSON
16
+ * answer, or of the SSE response event's payload), the session id (minted, or the request's) in
17
+ * the `mcp-session-id` header, and the cursor of the current generation in `nextCursor`.
18
+ *
19
+ * @experimental
20
+ */
21
+ import { Predicate } from 'effect'
22
+ import type * as Schema from 'effect/Schema'
23
+ import type { EmulatorRouteEvidence } from '../route-evidence.ts'
24
+ import {
25
+ isJsonObject,
26
+ isNotEmulated,
27
+ notEmulated,
28
+ parseJsonText,
29
+ streamedCommit,
30
+ type Admission,
31
+ type EmulatedRequest,
32
+ type NotEmulated,
33
+ type Planned,
34
+ type StatefulRoute,
35
+ type StreamedAnswer
36
+ } from '../stateful-emulator.ts'
37
+ import { mcpEmulatorAfloatFixtures } from './afloat-recordings.ts'
38
+ import {
39
+ mcpEmulatorFixtures,
40
+ type McpRecordedExchange,
41
+ type McpRecordedFixture,
42
+ type McpRecordedRequest,
43
+ type McpRecordedResponse
44
+ } from './recordings.ts'
45
+ import {
46
+ mcpEmulatorAfloatOrigin,
47
+ mcpEmulatorAfloatPath,
48
+ mcpEmulatorLegacyPath,
49
+ mcpEmulatorModernPath,
50
+ mcpEmulatorOrigin,
51
+ mcpEmulatorSessionCap,
52
+ mcpEmulatorSessionPrefix,
53
+ type McpEmulatorState,
54
+ type McpRuntime
55
+ } from './state.ts'
56
+
57
+ /** Drill knobs (tests only): each makes the emulator disagree with exactly one case's claim. */
58
+ export type McpEmulatorDrills = {
59
+ /** `mcp.negotiation.era` (modern): the discover answer also carries a JSON-RPC error. */
60
+ readonly discoverCarriesErrorResponse?: boolean
61
+ /** `mcp.modern.stateless`: the modern discover result lacks `resultType`. */
62
+ readonly discoverWithoutResultType?: boolean
63
+ /** `mcp.legacy.session`: minted session ids hold a space (not visible ASCII). */
64
+ readonly sessionIdNotVisibleAscii?: boolean
65
+ /** `mcp.transport.response-encoding` (modern): the discover answer holds its response twice. */
66
+ readonly discoverAnsweredTwice?: boolean
67
+ /** `mcp.tools.list`: the listing marks the write tool `readOnlyHint: true`. */
68
+ readonly writeToolMarkedReadOnly?: boolean
69
+ /** `mcp.tools.call-read`: the read call answers `isError: true`. */
70
+ readonly readCallAnswersToolError?: boolean
71
+ /** `mcp.tools.call-tool-error`: invalid arguments answer a JSON-RPC error. */
72
+ readonly invalidCallAnswersRpcError?: boolean
73
+ /** `mcp.errors.unknown-tool`: the absent tool answers a tool result. */
74
+ readonly absentCallAnswersResult?: boolean
75
+ /** `mcp.auth.rejected`: the 401 carries no `WWW-Authenticate` challenge. */
76
+ readonly unauthorizedWithoutChallenge?: boolean
77
+ }
78
+
79
+ export const mcpEmulatorDrillKnobs: ReadonlyArray<keyof McpEmulatorDrills> = [
80
+ 'discoverCarriesErrorResponse',
81
+ 'discoverWithoutResultType',
82
+ 'sessionIdNotVisibleAscii',
83
+ 'discoverAnsweredTwice',
84
+ 'writeToolMarkedReadOnly',
85
+ 'readCallAnswersToolError',
86
+ 'invalidCallAnswersRpcError',
87
+ 'absentCallAnswersResult',
88
+ 'unauthorizedWithoutChallenge'
89
+ ]
90
+
91
+ export type McpApiEnv = {
92
+ readonly drills: Readonly<Record<keyof McpEmulatorDrills, boolean>>
93
+ /** The digest of the reserved invalid credential on the synthetic origin. */
94
+ readonly reservedDigest: string
95
+ /** The digest of the reserved invalid Afloat credential's remainder on the Afloat origin. */
96
+ readonly afloatReservedDigest: string
97
+ /** Runtime data the commits advance (never in the state). */
98
+ readonly runtime: McpRuntime
99
+ }
100
+
101
+ type McpRoute = StatefulRoute<McpEmulatorState, McpApiEnv>
102
+
103
+ type RpcId = string | number
104
+
105
+ type JsonObject = Schema.JsonObject
106
+
107
+ const fieldOf = (value: Schema.Json | undefined, key: string): Schema.Json | undefined =>
108
+ isJsonObject(value) ? value[key] : undefined
109
+
110
+ // The recorded exchanges the routes answer, by fixture id and exchange index.
111
+
112
+ /** Every copied fixture: the synthetic profiles', then the Afloat profile's. */
113
+ const allFixtures: ReadonlyArray<McpRecordedFixture> = [
114
+ ...mcpEmulatorFixtures,
115
+ ...mcpEmulatorAfloatFixtures
116
+ ]
117
+
118
+ const exchangeOf = (fixtureId: string, index: number): McpRecordedExchange => {
119
+ const exchange = allFixtures.find(fixture => fixture.id === fixtureId)?.exchanges.at(index)
120
+
121
+ if (exchange === undefined) {
122
+ throw new Error(`the MCP recordings have no exchange ${index} in ${fixtureId}`)
123
+ }
124
+
125
+ return exchange
126
+ }
127
+
128
+ const modern = (caseId: string) => `${caseId}.modern.synthetic`
129
+
130
+ const legacy = (caseId: string) => `${caseId}.legacy.synthetic`
131
+
132
+ const afloat = (caseId: string) => `${caseId}.afloat.synthetic`
133
+
134
+ const recorded = {
135
+ modernDiscover: exchangeOf(modern('mcp.negotiation.era'), 0),
136
+ modernRejected: exchangeOf(modern('mcp.auth.rejected'), 0),
137
+ modernList: exchangeOf(modern('mcp.negotiation.era'), 1),
138
+ modernFirstPage: exchangeOf(modern('mcp.tools.list'), 1),
139
+ modernSecondPage: exchangeOf(modern('mcp.tools.list'), 2),
140
+ modernCallRead: exchangeOf(modern('mcp.tools.call-read'), -1),
141
+ modernCallToolError: exchangeOf(modern('mcp.tools.call-tool-error'), -1),
142
+ modernCallAbsent: exchangeOf(modern('mcp.errors.unknown-tool'), -1),
143
+ legacyDiscover: exchangeOf(legacy('mcp.negotiation.era'), 0),
144
+ legacyRejected: exchangeOf(legacy('mcp.auth.rejected'), 0),
145
+ legacyInitialize: exchangeOf(legacy('mcp.negotiation.era'), 1),
146
+ legacyInitialized: exchangeOf(legacy('mcp.negotiation.era'), 2),
147
+ legacyGet: exchangeOf(legacy('mcp.negotiation.era'), 3),
148
+ legacyList: exchangeOf(legacy('mcp.negotiation.era'), 4),
149
+ legacyCallRead: exchangeOf(legacy('mcp.tools.call-read'), -1),
150
+ legacyCallToolError: exchangeOf(legacy('mcp.tools.call-tool-error'), -1),
151
+ legacyCallAbsent: exchangeOf(legacy('mcp.errors.unknown-tool'), -1),
152
+ afloatDiscover: exchangeOf(afloat('mcp.negotiation.era'), 0),
153
+ afloatRejected: exchangeOf(afloat('mcp.auth.rejected'), 0),
154
+ afloatList: exchangeOf(afloat('mcp.negotiation.era'), 1),
155
+ afloatCallRead: exchangeOf(afloat('mcp.tools.call-read'), -1),
156
+ afloatCallToolError: exchangeOf(afloat('mcp.tools.call-tool-error'), -1),
157
+ afloatCallAbsent: exchangeOf(afloat('mcp.errors.unknown-tool'), -1)
158
+ }
159
+
160
+ type RecordedKey = keyof typeof recorded
161
+
162
+ /** The cursor the paged listing records between its two pages. */
163
+ const recordedCursor = (() => {
164
+ const cursor = fieldOf(fieldOf(recorded.modernSecondPage.request.body, 'params'), 'cursor')
165
+
166
+ if (!Predicate.isString(cursor)) {
167
+ throw new Error('the paged MCP listing records no cursor')
168
+ }
169
+
170
+ return cursor
171
+ })()
172
+
173
+ // The manifest: one row per recorded JSON-RPC method of each profile, plus the GET row.
174
+
175
+ const casesSending = (
176
+ origin: string,
177
+ path: string,
178
+ sends: (request: McpRecordedRequest) => boolean
179
+ ) => [
180
+ ...new Set(
181
+ allFixtures.flatMap(fixture =>
182
+ fixture.endpoint === `${origin}${path}` &&
183
+ fixture.exchanges.some(exchange => sends(exchange.request))
184
+ ? [fixture.caseId]
185
+ : []
186
+ )
187
+ )
188
+ ]
189
+
190
+ const rpcMethodOf = (request: McpRecordedRequest): string | undefined => {
191
+ const method = fieldOf(request.body, 'method')
192
+
193
+ return Predicate.isString(method) ? method : undefined
194
+ }
195
+
196
+ const rpcRow = (origin: string, path: string, method: string): EmulatorRouteEvidence => ({
197
+ method: 'RPC',
198
+ path: `${origin}${path}#${method}`,
199
+ kind: 'connector',
200
+ write: false,
201
+ caseIds: casesSending(
202
+ origin,
203
+ path,
204
+ request => request.method === 'POST' && rpcMethodOf(request) === method
205
+ ),
206
+ evidence: 'unverified'
207
+ })
208
+
209
+ const modernMethods = ['server/discover', 'tools/list', 'tools/call'] as const
210
+
211
+ const legacyMethods = [
212
+ 'server/discover',
213
+ 'initialize',
214
+ 'notifications/initialized',
215
+ 'tools/list',
216
+ 'tools/call'
217
+ ] as const
218
+
219
+ const modernRows = modernMethods.map(method =>
220
+ rpcRow(mcpEmulatorOrigin, mcpEmulatorModernPath, method)
221
+ )
222
+
223
+ const legacyRows = legacyMethods.map(method =>
224
+ rpcRow(mcpEmulatorOrigin, mcpEmulatorLegacyPath, method)
225
+ )
226
+
227
+ /** The Afloat profile records the modern methods only (no paging, no session). */
228
+ const afloatRows = modernMethods.map(method =>
229
+ rpcRow(mcpEmulatorAfloatOrigin, mcpEmulatorAfloatPath, method)
230
+ )
231
+
232
+ const getRow: EmulatorRouteEvidence = {
233
+ method: 'GET',
234
+ path: `${mcpEmulatorOrigin}${mcpEmulatorLegacyPath}`,
235
+ kind: 'connector',
236
+ write: false,
237
+ caseIds: casesSending(
238
+ mcpEmulatorOrigin,
239
+ mcpEmulatorLegacyPath,
240
+ request => request.method === 'GET'
241
+ ),
242
+ evidence: 'unverified'
243
+ }
244
+
245
+ const rowOf = (path: string, method: string, origin: string = mcpEmulatorOrigin): string =>
246
+ `${origin}${path}#${method}`
247
+
248
+ // Answers: the recorded bytes, with only the request id, session id, and cursor substituted.
249
+
250
+ const isEventStream = (headers: Readonly<Record<string, string>>): boolean =>
251
+ headers['content-type'] === 'text/event-stream'
252
+
253
+ /** A recorded answer as status, headers, and chunks (a JSON body is one chunk; none is none). */
254
+ const answerOf = (response: McpRecordedResponse): StreamedAnswer => ({
255
+ status: response.status,
256
+ headers: response.headers,
257
+ chunks: 'chunks' in response ? response.chunks : response.body === '' ? [] : [response.body]
258
+ })
259
+
260
+ const isResponseTo = (message: Schema.Json | undefined, id: RpcId): message is JsonObject =>
261
+ isJsonObject(message) && message['id'] === id && ('result' in message || 'error' in message)
262
+
263
+ const dataPrefix = 'data: '
264
+
265
+ /**
266
+ * `answer` with the JSON-RPC response to `recordedId` (the top-level message of a JSON answer, or
267
+ * the payload of the SSE event that carries it) replaced by `change` of it; every other chunk,
268
+ * line, and event (notifications, `id:` lines) stays byte for byte.
269
+ */
270
+ const mapResponse = (
271
+ answer: StreamedAnswer,
272
+ recordedId: RpcId,
273
+ change: (message: JsonObject) => Schema.Json
274
+ ): StreamedAnswer => {
275
+ const eventStream = isEventStream(answer.headers)
276
+
277
+ const chunks = answer.chunks.map(chunk => {
278
+ if (!eventStream) {
279
+ const message = parseJsonText(chunk)
280
+
281
+ return isResponseTo(message, recordedId) ? JSON.stringify(change(message)) : chunk
282
+ }
283
+
284
+ return chunk
285
+ .split('\n')
286
+ .map(line => {
287
+ if (!line.startsWith(dataPrefix)) return line
288
+
289
+ const message = parseJsonText(line.slice(dataPrefix.length))
290
+
291
+ return isResponseTo(message, recordedId)
292
+ ? `${dataPrefix}${JSON.stringify(change(message))}`
293
+ : line
294
+ })
295
+ .join('\n')
296
+ })
297
+
298
+ return { ...answer, chunks }
299
+ }
300
+
301
+ const recordedIdOf = (exchange: McpRecordedExchange): RpcId | undefined => {
302
+ const id = fieldOf(exchange.request.body, 'id')
303
+
304
+ return Predicate.isString(id) || Predicate.isNumber(id) ? id : undefined
305
+ }
306
+
307
+ /** The recorded answer of `exchange` with the request's id where it carries the recorded id. */
308
+ const answerWithId = (exchange: McpRecordedExchange, id: RpcId | undefined): StreamedAnswer => {
309
+ const answer = answerOf(exchange.response)
310
+ const recordedId = recordedIdOf(exchange)
311
+
312
+ // The recorded request id stays byte for byte; so does an answer that does not carry it.
313
+ if (recordedId === undefined || id === undefined || id === recordedId) return answer
314
+
315
+ return mapResponse(answer, recordedId, message => ({ ...message, id }))
316
+ }
317
+
318
+ /** `answer` with its `mcp-session-id` header (recorded on SSE answers) set to `session`. */
319
+ const withSession = (answer: StreamedAnswer, session: string): StreamedAnswer =>
320
+ answer.headers['mcp-session-id'] === undefined
321
+ ? answer
322
+ : { ...answer, headers: { ...answer.headers, 'mcp-session-id': session } }
323
+
324
+ /** The response message of an answer to `id` with `change` applied to its `result`. */
325
+ const mapResult =
326
+ (change: (result: JsonObject) => JsonObject) =>
327
+ (message: JsonObject): JsonObject => {
328
+ const result = message['result']
329
+
330
+ return isJsonObject(result) ? { ...message, result: change(result) } : message
331
+ }
332
+
333
+ /**
334
+ * Where a copied recording is not in the canonical form id substitution relies on: every JSON
335
+ * answer body, and every SSE `data:` payload, must equal `JSON.stringify(JSON.parse(text))`, and
336
+ * every SSE data line must start with `data: `. `makeMcpEmulator` throws on any problem, so a
337
+ * recording copied in another form (escapes such as `\u00e9` or `\/`, numbers such as `1.0`,
338
+ * spacing) fails loudly instead of answering bytes the substitution would rewrite.
339
+ */
340
+ export const mcpRecordingProblems = (
341
+ fixtures: ReadonlyArray<McpRecordedFixture>
342
+ ): ReadonlyArray<string> =>
343
+ fixtures.flatMap(fixture =>
344
+ fixture.exchanges.flatMap(({ response }, index) => {
345
+ const where = `${fixture.id} exchange ${index}`
346
+
347
+ const canonical = (text: string) => {
348
+ const parsed = parseJsonText(text)
349
+
350
+ return parsed !== undefined && JSON.stringify(parsed) === text
351
+ }
352
+
353
+ if (!('chunks' in response)) {
354
+ return response.body === '' || canonical(response.body)
355
+ ? []
356
+ : [`${where}: the JSON body is not canonical`]
357
+ }
358
+
359
+ return response.chunks.flatMap((chunk, at) =>
360
+ chunk
361
+ .split('\n')
362
+ .flatMap(line =>
363
+ !line.startsWith('data') ||
364
+ (line.startsWith(dataPrefix) && canonical(line.slice(dataPrefix.length)))
365
+ ? []
366
+ : [`${where} chunk ${at}: an SSE data line is not canonical`]
367
+ )
368
+ )
369
+ })
370
+ )
371
+
372
+ // Request checks: constant reasons only (the wrapper ledgers refusals as constant entries).
373
+
374
+ /** The MCP headers compared with the recording (absent where the recording has none). */
375
+ const comparedHeaders = [
376
+ 'accept',
377
+ 'content-type',
378
+ 'last-event-id',
379
+ 'mcp-method',
380
+ 'mcp-name',
381
+ 'mcp-protocol-version'
382
+ ] as const
383
+
384
+ const sessionHeader = 'mcp-session-id'
385
+
386
+ /** The `mcp-*` headers a recording carries; any other (such as `mcp-param-*`) is refused. */
387
+ const recordedMcpHeaders: ReadonlySet<string> = new Set([
388
+ 'mcp-method',
389
+ 'mcp-name',
390
+ 'mcp-protocol-version',
391
+ sessionHeader
392
+ ])
393
+
394
+ /** Refuse an `mcp-*` header no recording carries (fail closed when the names are unknown). */
395
+ const unrecordedMcpHeader = (request: EmulatedRequest): NotEmulated | undefined =>
396
+ request.headerNames === undefined ||
397
+ request.headerNames.some(name => name.startsWith('mcp-') && !recordedMcpHeaders.has(name))
398
+ ? notEmulated('an mcp-* header no recording carries is not emulated')
399
+ : undefined
400
+
401
+ const headerProblem = (
402
+ request: EmulatedRequest,
403
+ recordedRequest: McpRecordedRequest,
404
+ names: ReadonlyArray<string>
405
+ ): NotEmulated | undefined => {
406
+ for (const name of names) {
407
+ if (request.header(name) !== recordedRequest.headers[name]) {
408
+ return notEmulated(`the ${name} header must be the recorded value, or absent where none is`)
409
+ }
410
+ }
411
+
412
+ if (
413
+ (request.header(sessionHeader) === undefined) !==
414
+ (recordedRequest.headers[sessionHeader] === undefined)
415
+ ) {
416
+ return notEmulated('mcp-session-id must be sent exactly where the recording sends one')
417
+ }
418
+
419
+ return undefined
420
+ }
421
+
422
+ /**
423
+ * A JSON-RPC request id of the emulated form: an integer from 0 to 2^53 - 1, or 1 to 64 printable
424
+ * ASCII characters.
425
+ */
426
+ export const isMcpEmulatedRequestId = (id: Schema.Json | undefined): id is RpcId =>
427
+ (Predicate.isNumber(id) && Number.isSafeInteger(id) && id >= 0) ||
428
+ (Predicate.isString(id) && /^[\x20-\x7E]{1,64}$/.test(id))
429
+
430
+ /** Structural JSON equality, ignoring object key order. */
431
+ const jsonEqual = (left: Schema.Json, right: Schema.Json): boolean => {
432
+ if (Array.isArray(left)) {
433
+ return (
434
+ Array.isArray(right) &&
435
+ left.length === right.length &&
436
+ left.every((item, index) => {
437
+ const other = right[index]
438
+
439
+ return other !== undefined && jsonEqual(item, other)
440
+ })
441
+ )
442
+ }
443
+
444
+ if (isJsonObject(left)) {
445
+ if (!isJsonObject(right)) return false
446
+
447
+ const keys = Object.keys(left)
448
+
449
+ return (
450
+ keys.length === Object.keys(right).length &&
451
+ keys.every(key => {
452
+ const value = left[key]
453
+ const other = right[key]
454
+
455
+ return (
456
+ Object.hasOwn(right, key) &&
457
+ value !== undefined &&
458
+ other !== undefined &&
459
+ jsonEqual(value, other)
460
+ )
461
+ })
462
+ )
463
+ }
464
+
465
+ return left === right
466
+ }
467
+
468
+ const clientInfoKey = 'io.modelcontextprotocol/clientInfo'
469
+
470
+ const isClientInfo = (value: Schema.Json | undefined): boolean =>
471
+ isJsonObject(value) &&
472
+ Object.keys(value).length === 2 &&
473
+ Predicate.isString(value['name']) &&
474
+ value['name'].length > 0 &&
475
+ Predicate.isString(value['version']) &&
476
+ value['version'].length > 0
477
+
478
+ /**
479
+ * The request params normalised for comparison with `recordedParams`: the `_meta` client info
480
+ * replaced by the recorded one (when it is any non-empty name and version), and with `cursorFree`
481
+ * the cursor replaced by the recorded one (when it is a string; checked by issuance at plan).
482
+ */
483
+ const normalisedParams = (
484
+ params: Schema.Json | undefined,
485
+ recordedParams: JsonObject,
486
+ cursorFree: boolean
487
+ ): JsonObject | NotEmulated => {
488
+ if (!isJsonObject(params)) return notEmulated('params must be the recorded JSON object')
489
+
490
+ const meta = params['_meta']
491
+ const recordedMeta = recordedParams['_meta']
492
+ let normalised: JsonObject = params
493
+
494
+ if (isJsonObject(recordedMeta) && recordedMeta[clientInfoKey] !== undefined) {
495
+ if (!isJsonObject(meta) || !isClientInfo(meta[clientInfoKey])) {
496
+ return notEmulated('the _meta client info must be a non-empty name and version only')
497
+ }
498
+
499
+ normalised = { ...normalised, _meta: { ...meta, [clientInfoKey]: recordedMeta[clientInfoKey] } }
500
+ }
501
+
502
+ if (cursorFree) {
503
+ if (!Predicate.isString(params['cursor'])) {
504
+ return notEmulated('the second page must send the cursor the first page issued')
505
+ }
506
+
507
+ normalised = { ...normalised, cursor: recordedCursor }
508
+ }
509
+
510
+ return normalised
511
+ }
512
+
513
+ type Matched = {
514
+ readonly key: RecordedKey
515
+ readonly id: RpcId | undefined
516
+ readonly cursor: string | undefined
517
+ }
518
+
519
+ /**
520
+ * The first candidate whose recorded request the JSON-RPC POST equals within the latitude, or
521
+ * not emulated. Every candidate records the same method; candidates differ only in their params
522
+ * and `mcp-name` (the recorded tool calls).
523
+ */
524
+ const matchRpc = (
525
+ request: EmulatedRequest,
526
+ candidates: ReadonlyArray<RecordedKey>,
527
+ options: { readonly cursorFree?: boolean } = {}
528
+ ): Matched | NotEmulated => {
529
+ const [first] = candidates
530
+
531
+ if (first === undefined) return notEmulated('this JSON-RPC method is not emulated here')
532
+
533
+ const firstRequest = recorded[first].request
534
+ const body = request.json
535
+ const recordedBody = firstRequest.body
536
+
537
+ if (!isJsonObject(recordedBody)) return notEmulated('this JSON-RPC method is not emulated here')
538
+
539
+ const common =
540
+ unrecordedMcpHeader(request) ??
541
+ headerProblem(
542
+ request,
543
+ firstRequest,
544
+ comparedHeaders.filter(name => name !== 'mcp-name')
545
+ )
546
+
547
+ if (common !== undefined) return common
548
+
549
+ if (!isJsonObject(body)) {
550
+ return notEmulated('JSON-RPC batches and non-object bodies are not emulated')
551
+ }
552
+
553
+ const keys = Object.keys(body)
554
+ const recordedKeys = Object.keys(recordedBody)
555
+
556
+ if (keys.length !== recordedKeys.length || keys.some(key => !recordedKeys.includes(key))) {
557
+ return notEmulated('the JSON-RPC message must have exactly the recorded members')
558
+ }
559
+
560
+ if (body['jsonrpc'] !== '2.0') return notEmulated('jsonrpc must be "2.0"')
561
+
562
+ const id = body['id']
563
+
564
+ if ('id' in recordedBody && !isMcpEmulatedRequestId(id)) {
565
+ return notEmulated(
566
+ 'the request id must be an integer from 0 to 2^53 - 1 or 1 to 64 printable ASCII characters'
567
+ )
568
+ }
569
+
570
+ const cursor = options.cursorFree === true ? fieldOf(body['params'], 'cursor') : undefined
571
+
572
+ for (const key of candidates) {
573
+ const candidate = recorded[key].request
574
+ const candidateBody = candidate.body
575
+
576
+ if (!isJsonObject(candidateBody)) continue
577
+
578
+ if (headerProblem(request, candidate, ['mcp-name']) !== undefined) continue
579
+
580
+ const recordedParams = candidateBody['params']
581
+
582
+ if (recordedParams !== undefined) {
583
+ const params = isJsonObject(recordedParams)
584
+ ? normalisedParams(body['params'], recordedParams, options.cursorFree === true)
585
+ : notEmulated('params must be the recorded value')
586
+
587
+ if (isNotEmulated(params)) return params
588
+
589
+ if (!jsonEqual(params, recordedParams)) continue
590
+ }
591
+
592
+ return {
593
+ key,
594
+ id: isMcpEmulatedRequestId(id) ? id : undefined,
595
+ cursor: Predicate.isString(cursor) ? cursor : undefined
596
+ }
597
+ }
598
+
599
+ return notEmulated('params other than the recorded ones are not emulated')
600
+ }
601
+
602
+ /** Refuse any query parameter (no fixture records one). */
603
+ const noQuery = (request: EmulatedRequest): NotEmulated | undefined =>
604
+ request.rawQuery === undefined || request.rawQuery === ''
605
+ ? undefined
606
+ : notEmulated('query parameters are not emulated')
607
+
608
+ const isReserved = (request: EmulatedRequest, env: McpApiEnv): boolean =>
609
+ request.bearerDigest === env.reservedDigest
610
+
611
+ const isAfloatReserved = (request: EmulatedRequest, env: McpApiEnv): boolean =>
612
+ request.bearerDigest === env.afloatReservedDigest
613
+
614
+ const reservedOnlyOnProbe = 'the reserved invalid credential is answered only on the era probe'
615
+
616
+ // Plans and commits.
617
+
618
+ type Admitted = Matched & {
619
+ /** The request's `mcp-session-id` (legacy non-handshake requests). */
620
+ readonly session: string | undefined
621
+ }
622
+
623
+ type Plan = (state: McpEmulatorState, admitted: Admitted, env: McpApiEnv) => Planned
624
+
625
+ const admission = (
626
+ variant: string,
627
+ admitted: Admitted,
628
+ plan: Plan
629
+ ): Admission<McpEmulatorState, McpApiEnv> => ({
630
+ variant,
631
+ plan: (state, context) => plan(state, admitted, context.env)
632
+ })
633
+
634
+ /** A commit that answers `answer` and writes nothing. */
635
+ const answerOnly = (answer: StreamedAnswer): Planned => streamedCommit(answer)
636
+
637
+ const sessionOf = (state: McpEmulatorState, admitted: Admitted, phase: 'initializing' | 'ready') =>
638
+ state.sessions.find(session => session.id === admitted.session && session.phase === phase)
639
+
640
+ const unknownSession = (phase: 'initializing' | 'ready') =>
641
+ notEmulated(
642
+ phase === 'ready'
643
+ ? 'a request on no ready session of this emulator is not emulated'
644
+ : 'notifications/initialized on no initializing session of this emulator is not emulated'
645
+ )
646
+
647
+ /** The JSON-RPC error the era drill adds to the discover answer (another id: the SDK skips it). */
648
+ const drillErrorResponse = JSON.stringify({
649
+ jsonrpc: '2.0',
650
+ id: 'yolk-emu-drill',
651
+ error: { code: -32_603, message: 'Synthetic drill error.' }
652
+ })
653
+
654
+ /** The listed tools that write, which the `writeToolMarkedReadOnly` drill marks read-only. */
655
+ const writeToolNames: ReadonlySet<string> = new Set([
656
+ 'create_synthetic_note',
657
+ 'create-receipt-upload'
658
+ ])
659
+
660
+ /** Drill transforms of an answer, by the recorded exchange it answers. */
661
+ const drilled = (key: RecordedKey, answer: StreamedAnswer, id: RpcId, env: McpApiEnv) => {
662
+ const drills = env.drills
663
+
664
+ switch (key) {
665
+ case 'modernDiscover':
666
+ case 'afloatDiscover': {
667
+ let next = answer
668
+
669
+ if (drills.discoverWithoutResultType) {
670
+ next = mapResponse(
671
+ next,
672
+ id,
673
+ mapResult(({ resultType: _resultType, ...result }) => result)
674
+ )
675
+ }
676
+
677
+ if (drills.discoverCarriesErrorResponse) {
678
+ next = {
679
+ ...next,
680
+ chunks: next.chunks.map(chunk => `[${drillErrorResponse},${chunk}]`)
681
+ }
682
+ }
683
+
684
+ if (drills.discoverAnsweredTwice) {
685
+ next = {
686
+ ...next,
687
+ headers: { ...next.headers, 'content-type': 'text/event-stream' },
688
+ chunks: next.chunks.flatMap(chunk => [
689
+ `event: message\ndata: ${chunk}\n\n`,
690
+ `event: message\ndata: ${chunk}\n\n`
691
+ ])
692
+ }
693
+ }
694
+
695
+ return next
696
+ }
697
+
698
+ case 'modernList':
699
+ case 'modernFirstPage':
700
+ case 'modernSecondPage':
701
+ case 'legacyList':
702
+ case 'afloatList':
703
+ return drills.writeToolMarkedReadOnly
704
+ ? mapResponse(
705
+ answer,
706
+ id,
707
+ mapResult(result => {
708
+ const tools = result['tools']
709
+
710
+ return Array.isArray(tools)
711
+ ? {
712
+ ...result,
713
+ tools: tools.map(tool =>
714
+ isJsonObject(tool) && writeToolNames.has(String(tool['name']))
715
+ ? { ...tool, annotations: { readOnlyHint: true } }
716
+ : tool
717
+ )
718
+ }
719
+ : result
720
+ })
721
+ )
722
+ : answer
723
+
724
+ case 'modernCallRead':
725
+ case 'legacyCallRead':
726
+ case 'afloatCallRead':
727
+ return drills.readCallAnswersToolError
728
+ ? mapResponse(
729
+ answer,
730
+ id,
731
+ mapResult(result => ({ ...result, isError: true }))
732
+ )
733
+ : answer
734
+
735
+ case 'modernCallToolError':
736
+ case 'legacyCallToolError':
737
+ case 'afloatCallToolError':
738
+ return drills.invalidCallAnswersRpcError
739
+ ? mapResponse(answer, id, () => ({
740
+ jsonrpc: '2.0',
741
+ id,
742
+ error: { code: -32_602, message: 'Synthetic drill: invalid arguments.' }
743
+ }))
744
+ : answer
745
+
746
+ case 'modernCallAbsent':
747
+ case 'legacyCallAbsent':
748
+ case 'afloatCallAbsent': {
749
+ if (!drills.absentCallAnswersResult) return answer
750
+
751
+ const result: JsonObject = {
752
+ content: [{ type: 'text', text: 'Synthetic drill result.' }],
753
+ isError: true
754
+ }
755
+
756
+ return mapResponse({ ...answer, status: 200 }, id, () => ({
757
+ jsonrpc: '2.0',
758
+ id,
759
+ result: key === 'legacyCallAbsent' ? result : { ...result, resultType: 'complete' }
760
+ }))
761
+ }
762
+
763
+ case 'modernRejected':
764
+ case 'legacyRejected':
765
+ case 'afloatRejected': {
766
+ if (!drills.unauthorizedWithoutChallenge) return answer
767
+
768
+ const { 'www-authenticate': _challenge, ...headers } = answer.headers
769
+
770
+ return { ...answer, headers }
771
+ }
772
+
773
+ default:
774
+ return answer
775
+ }
776
+ }
777
+
778
+ /** The id the answer's response carries: the request's (substituted), else the recorded one. */
779
+ const responseIdOf = (key: RecordedKey, id: RpcId | undefined): RpcId | undefined =>
780
+ id ?? recordedIdOf(recorded[key])
781
+
782
+ /** The recorded answer for `key`, with the request id substituted and any drill applied. */
783
+ const recordedAnswer = (key: RecordedKey, id: RpcId | undefined, env: McpApiEnv) => {
784
+ const answer = answerWithId(recorded[key], id)
785
+ const responseId = responseIdOf(key, id)
786
+
787
+ return responseId === undefined ? answer : drilled(key, answer, responseId, env)
788
+ }
789
+
790
+ /** The cursor value issued in the current generation (the recorded one in its first). */
791
+ const cursorFor = (runtime: McpRuntime): string =>
792
+ (runtime.cursorFirstGeneration ?? runtime.generation) === runtime.generation
793
+ ? recordedCursor
794
+ : `${recordedCursor}.g${runtime.generation}`
795
+
796
+ const planModernList: Plan = (state, admitted, env) => {
797
+ if (state.modernListing === 'one-page') {
798
+ return answerOnly(recordedAnswer('modernList', admitted.id, env))
799
+ }
800
+
801
+ const cursor = cursorFor(env.runtime)
802
+ const recordedPage = recordedAnswer('modernFirstPage', admitted.id, env)
803
+ const responseId = responseIdOf('modernFirstPage', admitted.id)
804
+
805
+ // The recorded bytes in the generation that first issues the cursor; a minted cursor after it.
806
+ const sent =
807
+ cursor === recordedCursor || responseId === undefined
808
+ ? recordedPage
809
+ : mapResponse(
810
+ recordedPage,
811
+ responseId,
812
+ mapResult(result => ({ ...result, nextCursor: cursor }))
813
+ )
814
+
815
+ // The cursor is issued only by the commit, so a faulted or truncated first page issues none.
816
+ return streamedCommit(sent, () => {
817
+ env.runtime.cursorFirstGeneration ??= env.runtime.generation
818
+ env.runtime.issuedCursor = cursor
819
+ }, [cursor])
820
+ }
821
+
822
+ const planModernSecondPage: Plan = (state, admitted, env) =>
823
+ state.modernListing === 'two-pages' &&
824
+ env.runtime.issuedCursor !== undefined &&
825
+ admitted.cursor === env.runtime.issuedCursor
826
+ ? answerOnly(recordedAnswer('modernSecondPage', admitted.id, env))
827
+ : notEmulated(
828
+ 'a cursor this emulator did not issue since the last reset or seed is not emulated'
829
+ )
830
+
831
+ const planInitialize: Plan = (state, admitted, env) => {
832
+ const number = env.runtime.nextSession
833
+
834
+ if (state.sessions.length >= mcpEmulatorSessionCap || !Number.isSafeInteger(number + 1)) {
835
+ return notEmulated('the emulator holds as many sessions as it takes')
836
+ }
837
+
838
+ const session = env.drills.sessionIdNotVisibleAscii
839
+ ? `yolk-emu-session ${number}`
840
+ : `${mcpEmulatorSessionPrefix}${number}`
841
+
842
+ const answer = withSession(recordedAnswer('legacyInitialize', admitted.id, env), session)
843
+
844
+ // The session is minted only by the commit, so a faulted or truncated `initialize` holds none
845
+ // and leaves the counter where it was.
846
+ return streamedCommit(answer, () => {
847
+ env.runtime.nextSession = number + 1
848
+ state.sessions = [...state.sessions, { id: session, phase: 'initializing' }]
849
+ }, [session])
850
+ }
851
+
852
+ const planInitialized: Plan = (state, admitted, env) => {
853
+ const session = sessionOf(state, admitted, 'initializing')
854
+
855
+ if (session === undefined) return unknownSession('initializing')
856
+
857
+ const answer = recordedAnswer('legacyInitialized', undefined, env)
858
+
859
+ return streamedCommit(answer, () => {
860
+ state.sessions = state.sessions.map(held =>
861
+ held.id === session.id ? { id: held.id, phase: 'ready' } : held
862
+ )
863
+ })
864
+ }
865
+
866
+ /** A legacy answer on a ready session: the recorded answer with the session's id. */
867
+ const planOnSession =
868
+ (key: RecordedKey): Plan =>
869
+ (state, admitted, env) => {
870
+ const session = sessionOf(state, admitted, 'ready')
871
+
872
+ return session === undefined
873
+ ? unknownSession('ready')
874
+ : answerOnly(withSession(recordedAnswer(key, admitted.id, env), session.id))
875
+ }
876
+
877
+ const planAnswer =
878
+ (key: RecordedKey): Plan =>
879
+ (_state, admitted, env) =>
880
+ answerOnly(recordedAnswer(key, admitted.id, env))
881
+
882
+ // Routes.
883
+
884
+ const routeEvidenceOf = (
885
+ method: string,
886
+ path: string,
887
+ variants: ReadonlyArray<EmulatorRouteEvidence>,
888
+ origin: string = mcpEmulatorOrigin
889
+ ) => ({
890
+ method,
891
+ path,
892
+ kind: 'connector' as const,
893
+ write: false,
894
+ caseIds: [...new Set(variants.flatMap(variant => variant.caseIds))],
895
+ evidence: 'unverified' as const,
896
+ origin,
897
+ variants
898
+ })
899
+
900
+ const admitted = (matched: Matched, request: EmulatedRequest): Admitted => ({
901
+ ...matched,
902
+ session: request.header(sessionHeader)
903
+ })
904
+
905
+ /** `POST /modern/mcp`: the stateless synthetic server (JSON answers, no session). */
906
+ const modernRoute: McpRoute = {
907
+ ...routeEvidenceOf('POST', mcpEmulatorModernPath, modernRows),
908
+ body: 'json',
909
+ admit: (request, env) => {
910
+ const query = noQuery(request)
911
+
912
+ if (query !== undefined) return query
913
+
914
+ const method = fieldOf(request.json, 'method')
915
+ const variant = (name: string) => rowOf(mcpEmulatorModernPath, name)
916
+
917
+ if (method === 'server/discover') {
918
+ const matched = matchRpc(request, ['modernDiscover'])
919
+
920
+ if (isNotEmulated(matched)) return matched
921
+
922
+ return isReserved(request, env)
923
+ ? admission(variant(method), admitted(matched, request), planAnswer('modernRejected'))
924
+ : admission(variant(method), admitted(matched, request), planAnswer('modernDiscover'))
925
+ }
926
+
927
+ if (isReserved(request, env)) return notEmulated(reservedOnlyOnProbe)
928
+
929
+ if (method === 'tools/list') {
930
+ const paged = fieldOf(fieldOf(request.json, 'params'), 'cursor') !== undefined
931
+
932
+ const matched = paged
933
+ ? matchRpc(request, ['modernSecondPage'], { cursorFree: true })
934
+ : matchRpc(request, ['modernList'])
935
+
936
+ if (isNotEmulated(matched)) return matched
937
+
938
+ return admission(
939
+ variant(method),
940
+ admitted(matched, request),
941
+ paged ? planModernSecondPage : planModernList
942
+ )
943
+ }
944
+
945
+ if (method === 'tools/call') {
946
+ const matched = matchRpc(request, [
947
+ 'modernCallRead',
948
+ 'modernCallToolError',
949
+ 'modernCallAbsent'
950
+ ])
951
+
952
+ if (isNotEmulated(matched)) return matched
953
+
954
+ return admission(variant(method), admitted(matched, request), planAnswer(matched.key))
955
+ }
956
+
957
+ return notEmulated('this JSON-RPC method is not emulated on the modern profile')
958
+ }
959
+ }
960
+
961
+ /** `POST /legacy/mcp`: the initialize-based synthetic server (SSE answers, sessions). */
962
+ const legacyRoute: McpRoute = {
963
+ ...routeEvidenceOf('POST', mcpEmulatorLegacyPath, legacyRows),
964
+ body: 'json',
965
+ admit: (request, env) => {
966
+ const query = noQuery(request)
967
+
968
+ if (query !== undefined) return query
969
+
970
+ const method = fieldOf(request.json, 'method')
971
+ const variant = (name: string) => rowOf(mcpEmulatorLegacyPath, name)
972
+
973
+ if (method === 'server/discover') {
974
+ const matched = matchRpc(request, ['legacyDiscover'])
975
+
976
+ if (isNotEmulated(matched)) return matched
977
+
978
+ return isReserved(request, env)
979
+ ? admission(variant(method), admitted(matched, request), planAnswer('legacyRejected'))
980
+ : admission(variant(method), admitted(matched, request), planAnswer('legacyDiscover'))
981
+ }
982
+
983
+ if (isReserved(request, env)) return notEmulated(reservedOnlyOnProbe)
984
+
985
+ const single = (key: RecordedKey, name: string, plan: Plan) => {
986
+ const matched = matchRpc(request, [key])
987
+
988
+ return isNotEmulated(matched)
989
+ ? matched
990
+ : admission(variant(name), admitted(matched, request), plan)
991
+ }
992
+
993
+ if (method === 'initialize') return single('legacyInitialize', method, planInitialize)
994
+
995
+ if (method === 'notifications/initialized') {
996
+ return single('legacyInitialized', method, planInitialized)
997
+ }
998
+
999
+ if (method === 'tools/list') return single('legacyList', method, planOnSession('legacyList'))
1000
+
1001
+ if (method === 'tools/call') {
1002
+ const matched = matchRpc(request, [
1003
+ 'legacyCallRead',
1004
+ 'legacyCallToolError',
1005
+ 'legacyCallAbsent'
1006
+ ])
1007
+
1008
+ if (isNotEmulated(matched)) return matched
1009
+
1010
+ return admission(variant(method), admitted(matched, request), planOnSession(matched.key))
1011
+ }
1012
+
1013
+ return notEmulated('this JSON-RPC method is not emulated on the legacy profile')
1014
+ }
1015
+ }
1016
+
1017
+ /** `GET /legacy/mcp`: the client's standing event stream, answered the recorded 405. */
1018
+ const legacyGetRoute: McpRoute = {
1019
+ ...routeEvidenceOf('GET', mcpEmulatorLegacyPath, [getRow]),
1020
+ body: 'none',
1021
+ admit: (request, env) => {
1022
+ const query = noQuery(request)
1023
+
1024
+ if (query !== undefined) return query
1025
+
1026
+ if (isReserved(request, env)) return notEmulated(reservedOnlyOnProbe)
1027
+
1028
+ const problem =
1029
+ unrecordedMcpHeader(request) ??
1030
+ headerProblem(request, recorded.legacyGet.request, comparedHeaders)
1031
+
1032
+ if (problem !== undefined) return problem
1033
+
1034
+ return admission(
1035
+ getRow.path,
1036
+ {
1037
+ key: 'legacyGet',
1038
+ id: undefined,
1039
+ cursor: undefined,
1040
+ session: request.header(sessionHeader)
1041
+ },
1042
+ planOnSession('legacyGet')
1043
+ )
1044
+ }
1045
+ }
1046
+
1047
+ /**
1048
+ * `POST /mcp` on the Afloat origin: the Afloat profile (stateless `2026-07-28`, JSON answers, no
1049
+ * session, one listing page). Its bearer is `afloat_<remainder>` (the wrapper's `bearerPrefixes`),
1050
+ * so routes see the digest of the remainder.
1051
+ */
1052
+ const afloatRoute: McpRoute = {
1053
+ ...routeEvidenceOf('POST', mcpEmulatorAfloatPath, afloatRows, mcpEmulatorAfloatOrigin),
1054
+ body: 'json',
1055
+ admit: (request, env) => {
1056
+ const query = noQuery(request)
1057
+
1058
+ if (query !== undefined) return query
1059
+
1060
+ const method = fieldOf(request.json, 'method')
1061
+ const variant = (name: string) => rowOf(mcpEmulatorAfloatPath, name, mcpEmulatorAfloatOrigin)
1062
+
1063
+ if (method === 'server/discover') {
1064
+ const matched = matchRpc(request, ['afloatDiscover'])
1065
+
1066
+ if (isNotEmulated(matched)) return matched
1067
+
1068
+ return isAfloatReserved(request, env)
1069
+ ? admission(variant(method), admitted(matched, request), planAnswer('afloatRejected'))
1070
+ : admission(variant(method), admitted(matched, request), planAnswer('afloatDiscover'))
1071
+ }
1072
+
1073
+ if (isAfloatReserved(request, env)) return notEmulated(reservedOnlyOnProbe)
1074
+
1075
+ if (method === 'tools/list') {
1076
+ const matched = matchRpc(request, ['afloatList'])
1077
+
1078
+ return isNotEmulated(matched)
1079
+ ? matched
1080
+ : admission(variant(method), admitted(matched, request), planAnswer('afloatList'))
1081
+ }
1082
+
1083
+ if (method === 'tools/call') {
1084
+ const matched = matchRpc(request, [
1085
+ 'afloatCallRead',
1086
+ 'afloatCallToolError',
1087
+ 'afloatCallAbsent'
1088
+ ])
1089
+
1090
+ if (isNotEmulated(matched)) return matched
1091
+
1092
+ return admission(variant(method), admitted(matched, request), planAnswer(matched.key))
1093
+ }
1094
+
1095
+ return notEmulated('this JSON-RPC method is not emulated on the Afloat profile')
1096
+ }
1097
+ }
1098
+
1099
+ /** The route table: one wire route per recorded HTTP shape, each with its manifest variants. */
1100
+ export const mcpApiRoutes: ReadonlyArray<McpRoute> = [
1101
+ modernRoute,
1102
+ legacyRoute,
1103
+ legacyGetRoute,
1104
+ afloatRoute
1105
+ ]