@arnilo/prism-hosts 0.0.0-stage → 0.13.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 (322) hide show
  1. package/CHANGELOG.md +394 -0
  2. package/LICENSE +21 -0
  3. package/README.md +34 -2
  4. package/acp/README.md +87 -0
  5. package/acp/src/capabilities.ts +184 -0
  6. package/acp/src/errors.ts +24 -0
  7. package/acp/src/host.ts +36 -0
  8. package/acp/src/index.ts +25 -0
  9. package/acp/src/limits.ts +49 -0
  10. package/acp/src/mapper.ts +419 -0
  11. package/acp/src/permission.ts +37 -0
  12. package/acp/src/projection.ts +39 -0
  13. package/acp/src/prompt.ts +170 -0
  14. package/acp/src/serve.ts +345 -0
  15. package/acp/src/session-map.ts +49 -0
  16. package/ag-ui/README.md +56 -0
  17. package/ag-ui/src/a2ui.ts +570 -0
  18. package/ag-ui/src/ag-ui-mapper.ts +507 -0
  19. package/ag-ui/src/encrypted-value.ts +40 -0
  20. package/ag-ui/src/errors.ts +29 -0
  21. package/ag-ui/src/handler.ts +642 -0
  22. package/ag-ui/src/index.ts +177 -0
  23. package/ag-ui/src/input.ts +190 -0
  24. package/ag-ui/src/limits.ts +279 -0
  25. package/ag-ui/src/mcp-apps.ts +256 -0
  26. package/ag-ui/src/mcp.ts +94 -0
  27. package/ag-ui/src/projection.ts +201 -0
  28. package/ag-ui/src/projectors.ts +272 -0
  29. package/ag-ui/src/renderer/bind.ts +152 -0
  30. package/ag-ui/src/renderer/core.ts +270 -0
  31. package/ag-ui/src/renderer/index.ts +165 -0
  32. package/ag-ui/src/replay.ts +189 -0
  33. package/ag-ui/src/types.ts +66 -0
  34. package/channels/README.md +139 -0
  35. package/channels/src/admission.ts +8 -0
  36. package/channels/src/approvals.ts +262 -0
  37. package/channels/src/checkpoint-contract.ts +97 -0
  38. package/channels/src/delivery.ts +116 -0
  39. package/channels/src/host-ui.ts +356 -0
  40. package/channels/src/identity.ts +46 -0
  41. package/channels/src/index.ts +82 -0
  42. package/channels/src/limits.ts +49 -0
  43. package/channels/src/memory-stores.ts +112 -0
  44. package/channels/src/pairing.ts +178 -0
  45. package/channels/src/runtime-admit.ts +389 -0
  46. package/channels/src/runtime-core.ts +621 -0
  47. package/channels/src/runtime-reconcile.ts +299 -0
  48. package/channels/src/runtime-turn.ts +664 -0
  49. package/channels/src/runtime-types.ts +95 -0
  50. package/channels/src/runtime.ts +86 -0
  51. package/channels/src/secret-ref.ts +42 -0
  52. package/channels/src/signal.ts +790 -0
  53. package/channels/src/state.ts +355 -0
  54. package/channels/src/telegram.ts +1317 -0
  55. package/channels/src/types.ts +442 -0
  56. package/devtools/README.md +92 -0
  57. package/devtools/bin/prism-devtools.ts +63 -0
  58. package/devtools/src/args.ts +71 -0
  59. package/devtools/src/bun.d.ts +27 -0
  60. package/devtools/src/compare.ts +190 -0
  61. package/devtools/src/errors.ts +15 -0
  62. package/devtools/src/index.ts +25 -0
  63. package/devtools/src/replay.ts +36 -0
  64. package/devtools/src/security.ts +80 -0
  65. package/devtools/src/serve.ts +259 -0
  66. package/devtools/src/ui/assets.ts +108 -0
  67. package/devtools/src/ui/inspector.ts +182 -0
  68. package/driver-process/README.md +197 -0
  69. package/driver-process/src/abort.ts +74 -0
  70. package/driver-process/src/adapter.ts +211 -0
  71. package/driver-process/src/driver.ts +303 -0
  72. package/driver-process/src/errors.ts +17 -0
  73. package/driver-process/src/extend.ts +72 -0
  74. package/driver-process/src/index.ts +5 -0
  75. package/driver-process/src/inspect.ts +33 -0
  76. package/driver-process/src/session.ts +72 -0
  77. package/driver-process/src/testing.ts +394 -0
  78. package/driver-process/src/transports/json-rpc.ts +147 -0
  79. package/driver-process/src/transports/jsonl-stream.ts +12 -0
  80. package/driver-process/src/transports/types.ts +11 -0
  81. package/driver-process/src/turn.ts +106 -0
  82. package/evals/README.md +843 -0
  83. package/evals/src/calibration.ts +179 -0
  84. package/evals/src/citation-integrity.ts +98 -0
  85. package/evals/src/citations.ts +45 -0
  86. package/evals/src/compare-experiments.ts +153 -0
  87. package/evals/src/comparison.ts +230 -0
  88. package/evals/src/curate.ts +257 -0
  89. package/evals/src/dataset.ts +81 -0
  90. package/evals/src/erp-invariants.ts +163 -0
  91. package/evals/src/errors.ts +23 -0
  92. package/evals/src/experiment.ts +537 -0
  93. package/evals/src/failure-injection.ts +77 -0
  94. package/evals/src/feedback.ts +53 -0
  95. package/evals/src/index.ts +198 -0
  96. package/evals/src/injection.ts +247 -0
  97. package/evals/src/judge-panel.ts +109 -0
  98. package/evals/src/judge.ts +89 -0
  99. package/evals/src/limits.ts +50 -0
  100. package/evals/src/report-record.ts +47 -0
  101. package/evals/src/rubric-judge.ts +334 -0
  102. package/evals/src/scenario-runner.ts +317 -0
  103. package/evals/src/scenarios.ts +81 -0
  104. package/evals/src/score.ts +328 -0
  105. package/evals/src/scorer.ts +21 -0
  106. package/evals/src/state-match.ts +130 -0
  107. package/evals/src/stats.ts +635 -0
  108. package/evals/src/threshold.ts +117 -0
  109. package/evals/src/timeline.ts +38 -0
  110. package/evals/src/toolless-session.ts +33 -0
  111. package/evals/src/trace.ts +80 -0
  112. package/evals/src/trajectory.ts +623 -0
  113. package/evals/src/types.ts +672 -0
  114. package/evals/src/user-simulator.ts +101 -0
  115. package/evals/src/util.ts +207 -0
  116. package/headless/README.md +172 -0
  117. package/headless/src/answers.ts +91 -0
  118. package/headless/src/authority.ts +32 -0
  119. package/headless/src/errors.ts +36 -0
  120. package/headless/src/index.ts +17 -0
  121. package/headless/src/limits.ts +11 -0
  122. package/headless/src/pending.ts +16 -0
  123. package/headless/src/policy.ts +36 -0
  124. package/headless/src/resume.ts +103 -0
  125. package/headless/src/route.ts +153 -0
  126. package/headless/src/scheduler/clock.ts +22 -0
  127. package/headless/src/scheduler/cron.ts +19 -0
  128. package/headless/src/scheduler/firing.ts +58 -0
  129. package/headless/src/scheduler/index.ts +399 -0
  130. package/headless/src/scheduler/lease.ts +38 -0
  131. package/headless/src/scheduler/missed.ts +12 -0
  132. package/headless/src/scheduler/state.ts +132 -0
  133. package/host-builder/README.md +251 -0
  134. package/host-builder/bin/prism-host-builder.ts +169 -0
  135. package/host-builder/data/api.json +6197 -0
  136. package/host-builder/data/errors.json +558 -0
  137. package/host-builder/data/examples/acp.ts +63 -0
  138. package/host-builder/data/examples/adapters/conformance.ts +34 -0
  139. package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
  140. package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
  141. package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
  142. package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
  143. package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
  144. package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
  145. package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
  146. package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
  147. package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
  148. package/host-builder/data/examples/advisor.ts +94 -0
  149. package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
  150. package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
  151. package/host-builder/data/examples/ag-ui-server.ts +118 -0
  152. package/host-builder/data/examples/agent-durable-approval.ts +43 -0
  153. package/host-builder/data/examples/api-key-auth.ts +23 -0
  154. package/host-builder/data/examples/approval.ts +92 -0
  155. package/host-builder/data/examples/attention-compiler.ts +81 -0
  156. package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
  157. package/host-builder/data/examples/behavior-evaluation.ts +303 -0
  158. package/host-builder/data/examples/build-workflow.ts +334 -0
  159. package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
  160. package/host-builder/data/examples/caveman-ponytail.ts +197 -0
  161. package/host-builder/data/examples/cli.ts +31 -0
  162. package/host-builder/data/examples/coding-approval.ts +115 -0
  163. package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
  164. package/host-builder/data/examples/coding-compaction.ts +30 -0
  165. package/host-builder/data/examples/coding-goal-verify.ts +121 -0
  166. package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
  167. package/host-builder/data/examples/compaction.ts +36 -0
  168. package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
  169. package/host-builder/data/examples/context.ts +29 -0
  170. package/host-builder/data/examples/custom-adapter.ts +256 -0
  171. package/host-builder/data/examples/custom-builders.ts +66 -0
  172. package/host-builder/data/examples/custom-loop.ts +89 -0
  173. package/host-builder/data/examples/custom-provider.ts +70 -0
  174. package/host-builder/data/examples/custom-session-store.ts +72 -0
  175. package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
  176. package/host-builder/data/examples/decision-models.ts +98 -0
  177. package/host-builder/data/examples/define-package.ts +188 -0
  178. package/host-builder/data/examples/delegate.ts +200 -0
  179. package/host-builder/data/examples/discover-skills.ts +65 -0
  180. package/host-builder/data/examples/drive-rag-sync.ts +44 -0
  181. package/host-builder/data/examples/durable-approval.ts +139 -0
  182. package/host-builder/data/examples/durable-investigation.ts +93 -0
  183. package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
  184. package/host-builder/data/examples/enterprise-identity.ts +21 -0
  185. package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
  186. package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
  187. package/host-builder/data/examples/eval-injection.ts +73 -0
  188. package/host-builder/data/examples/eval-judges.ts +145 -0
  189. package/host-builder/data/examples/evals.ts +86 -0
  190. package/host-builder/data/examples/evaluation-gate.ts +40 -0
  191. package/host-builder/data/examples/execution-timeline.ts +173 -0
  192. package/host-builder/data/examples/external-agent.ts +541 -0
  193. package/host-builder/data/examples/external-app-db-backed.ts +344 -0
  194. package/host-builder/data/examples/governance-deny.ts +122 -0
  195. package/host-builder/data/examples/guardrail-packs.ts +240 -0
  196. package/host-builder/data/examples/headless-host.ts +245 -0
  197. package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
  198. package/host-builder/data/examples/hooks-json.ts +87 -0
  199. package/host-builder/data/examples/host-builder-agent.ts +150 -0
  200. package/host-builder/data/examples/host-hooks.ts +71 -0
  201. package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
  202. package/host-builder/data/examples/hosted-sandbox.ts +48 -0
  203. package/host-builder/data/examples/instruction-injection.ts +127 -0
  204. package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
  205. package/host-builder/data/examples/long-term-memory.ts +158 -0
  206. package/host-builder/data/examples/manifest.ts +112 -0
  207. package/host-builder/data/examples/mcp-server.ts +48 -0
  208. package/host-builder/data/examples/mcp-trust.ts +173 -0
  209. package/host-builder/data/examples/memory-and-wiki.ts +315 -0
  210. package/host-builder/data/examples/memory-lifecycle.ts +302 -0
  211. package/host-builder/data/examples/memory-system.ts +255 -0
  212. package/host-builder/data/examples/messaging-agent.ts +70 -0
  213. package/host-builder/data/examples/minimal-host-app.ts +41 -0
  214. package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
  215. package/host-builder/data/examples/model-router.ts +106 -0
  216. package/host-builder/data/examples/obscura.ts +48 -0
  217. package/host-builder/data/examples/observability.ts +116 -0
  218. package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
  219. package/host-builder/data/examples/openai-compatible.ts +70 -0
  220. package/host-builder/data/examples/package-skills.ts +85 -0
  221. package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
  222. package/host-builder/data/examples/provider-registration.ts +29 -0
  223. package/host-builder/data/examples/provider-resolver.ts +39 -0
  224. package/host-builder/data/examples/rag.ts +40 -0
  225. package/host-builder/data/examples/remote-agent-server.ts +45 -0
  226. package/host-builder/data/examples/remote-agent.ts +124 -0
  227. package/host-builder/data/examples/research-ledger.ts +79 -0
  228. package/host-builder/data/examples/revocation-propagation.ts +287 -0
  229. package/host-builder/data/examples/run-feedback.ts +93 -0
  230. package/host-builder/data/examples/scanned-document-rag.ts +48 -0
  231. package/host-builder/data/examples/sdk-basics.ts +21 -0
  232. package/host-builder/data/examples/secure-agent.ts +55 -0
  233. package/host-builder/data/examples/semantic-memory.ts +52 -0
  234. package/host-builder/data/examples/serve-tools.ts +495 -0
  235. package/host-builder/data/examples/session-memory.ts +318 -0
  236. package/host-builder/data/examples/session-search.ts +131 -0
  237. package/host-builder/data/examples/session.ts +52 -0
  238. package/host-builder/data/examples/side-call.ts +68 -0
  239. package/host-builder/data/examples/signal-agent.ts +9 -0
  240. package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
  241. package/host-builder/data/examples/skills.ts +19 -0
  242. package/host-builder/data/examples/sqlite-resume.ts +147 -0
  243. package/host-builder/data/examples/system-project-prompts.ts +74 -0
  244. package/host-builder/data/examples/system-prompts.ts +19 -0
  245. package/host-builder/data/examples/telegram-agent.ts +30 -0
  246. package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
  247. package/host-builder/data/examples/tools.ts +29 -0
  248. package/host-builder/data/examples/validator.ts +67 -0
  249. package/host-builder/data/examples/web-no-key.ts +85 -0
  250. package/host-builder/data/examples/web-research.ts +35 -0
  251. package/host-builder/data/examples/workflow-event-sink.ts +114 -0
  252. package/host-builder/data/examples/workflow-loop.ts +93 -0
  253. package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
  254. package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
  255. package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
  256. package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
  257. package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
  258. package/host-builder/data/examples.json +130 -0
  259. package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
  260. package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
  261. package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
  262. package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
  263. package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
  264. package/host-builder/skills/prism-host-builder/references/security.md +52 -0
  265. package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
  266. package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
  267. package/host-builder/src/check/child.ts +108 -0
  268. package/host-builder/src/check/conformance.ts +13 -0
  269. package/host-builder/src/check/inspect.ts +20 -0
  270. package/host-builder/src/check/manifest.ts +23 -0
  271. package/host-builder/src/check/runner.ts +181 -0
  272. package/host-builder/src/check/targets.ts +65 -0
  273. package/host-builder/src/errors.ts +35 -0
  274. package/host-builder/src/index.ts +25 -0
  275. package/host-builder/src/indexes.ts +145 -0
  276. package/host-builder/src/install/install.ts +400 -0
  277. package/host-builder/src/install/targets.ts +50 -0
  278. package/host-builder/src/lookup/api.ts +127 -0
  279. package/host-builder/src/lookup/bound.ts +38 -0
  280. package/host-builder/src/lookup/docs.ts +238 -0
  281. package/host-builder/src/lookup/errors.ts +92 -0
  282. package/host-builder/src/lookup/examples.ts +117 -0
  283. package/host-builder/src/lookup/text.ts +60 -0
  284. package/host-builder/src/server.ts +300 -0
  285. package/host-builder/src/version.ts +38 -0
  286. package/mcp-server/README.md +219 -0
  287. package/mcp-server/src/bounds.ts +23 -0
  288. package/mcp-server/src/host.ts +31 -0
  289. package/mcp-server/src/index.ts +27 -0
  290. package/mcp-server/src/serve-tools.ts +408 -0
  291. package/mcp-server/src/serve.ts +329 -0
  292. package/mcp-server/src/server.ts +331 -0
  293. package/mcp-server/src/session-map.ts +47 -0
  294. package/mcp-server/src/skill-resources.ts +85 -0
  295. package/mcp-server/src/types.ts +215 -0
  296. package/package.json +130 -4
  297. package/remote/README.md +244 -0
  298. package/remote/src/attribution.ts +22 -0
  299. package/remote/src/auth.ts +30 -0
  300. package/remote/src/bun-module.d.ts +34 -0
  301. package/remote/src/channel.ts +86 -0
  302. package/remote/src/connect.ts +212 -0
  303. package/remote/src/dispatcher.ts +282 -0
  304. package/remote/src/errors.ts +59 -0
  305. package/remote/src/host-ui.ts +152 -0
  306. package/remote/src/http-gate.ts +43 -0
  307. package/remote/src/index.ts +53 -0
  308. package/remote/src/jsonl.ts +69 -0
  309. package/remote/src/limits.ts +43 -0
  310. package/remote/src/mirror.ts +90 -0
  311. package/remote/src/pending.ts +22 -0
  312. package/remote/src/protocol.ts +107 -0
  313. package/remote/src/serve.ts +560 -0
  314. package/remote/src/session-proxy.ts +219 -0
  315. package/remote/src/sse.ts +38 -0
  316. package/remote/src/stdio-client.ts +41 -0
  317. package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
  318. package/remote/src/testing.ts +230 -0
  319. package/remote/src/transport.ts +139 -0
  320. package/remote/src/transports/client.ts +126 -0
  321. package/remote/src/transports/network.ts +268 -0
  322. package/remote/src/wire.ts +244 -0
@@ -0,0 +1,408 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { dirname } from "node:path";
3
+ import {
4
+ type ContentBlock,
5
+ type ExternalToolDecision,
6
+ formatUntrustedToolText,
7
+ type JsonObject,
8
+ type JsonValue,
9
+ type RunController,
10
+ type ToolResult,
11
+ UNTRUSTED_EXTERNAL_TRUST,
12
+ } from "@arnilo/prism";
13
+ import { ALL_TOOL_EFFECTS, bridgeTools } from "@arnilo/prism/driver-kit";
14
+ import { type CallToolResult, fromJsonSchema, type JsonSchemaType, McpServer, type McpServerFactory } from "@modelcontextprotocol/server";
15
+ import manifest from "../../package.json" with { type: "json" };
16
+ import { bounded, truncateUtf8 } from "./bounds.js";
17
+ import { createPrismMcpWebHandler } from "./server.js";
18
+ import type { PermissionDecision, PermissionRequest, PrismMcpWebHandler, ServeToolsHandle, ServeToolsOptions } from "./types.js";
19
+
20
+ const DEFAULT_HEADER_ENV = "PRISM_MCP_TOKEN";
21
+ const DEFAULT_MAX_CONCURRENT_CALLS = 8;
22
+ const HARD_MAX_CONCURRENT_CALLS = 64;
23
+ const DEFAULT_RESULT_BYTES = 1024 * 1024;
24
+ const HARD_RESULT_BYTES = 8 * 1024 * 1024;
25
+ export const MAX_RESOURCE_BYTES = 256 * 1024;
26
+ const CLOSED_MESSAGE = "served tools are closed";
27
+ const APPROVAL_PENDING_MESSAGE = "approval is pending; the run is suspended until a decision is recorded, so do not retry this call";
28
+ const PERMISSION_STATE_KEY = "prism.permissions";
29
+ const PERMISSION_PENDING_MESSAGE = "the run is suspended until an approval decision is recorded, so do not retry this call";
30
+ const PERMISSION_NO_UI_MESSAGE = "no one can approve this call, so it is denied";
31
+ const PERMISSION_RESPOND_MESSAGE = "respond is not supported by the permission tool";
32
+
33
+ /** The neutral permission-tool input schema. A codec replaces it with an open object, so any vendor shape reaches `decode`. */
34
+ const PERMISSION_SCHEMA = {
35
+ type: "object",
36
+ properties: {
37
+ toolName: { type: "string" },
38
+ input: { type: "object" },
39
+ toolCallId: { type: "string" },
40
+ },
41
+ required: ["toolName", "input"],
42
+ additionalProperties: false,
43
+ } as const;
44
+ const PERMISSION_CODEC_SCHEMA = { type: "object", additionalProperties: true } as const;
45
+
46
+ /** The `serveTools` rejection reasons. Every one fails closed before anything is served. */
47
+ export type ServeToolsErrorCode =
48
+ | "serve_tools_empty"
49
+ | "serve_tools_transport"
50
+ | "serve_tools_resource_bytes"
51
+ | "serve_tools_permission_conflict";
52
+
53
+ export class ServeToolsError extends Error {
54
+ constructor(
55
+ readonly code: ServeToolsErrorCode,
56
+ message: string,
57
+ ) {
58
+ super(message);
59
+ this.name = "ServeToolsError";
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Serve a run's tools to an external agent over the run's callback broker.
65
+ *
66
+ * `allow` names tools in `options.tools`; `bridgeTools` resolves them, so an unknown name fails
67
+ * before anything is served and `invoke` refuses anything not bridged. Requests arrive through
68
+ * `broker.route("mcp")` — the one seam a `stdio-relay` binary can reach — and are served by a
69
+ * fresh stateless `McpServer` per request. The broker's synthesized `Request` carries only
70
+ * `content-type`, so the route handler restores the streamable-HTTP `accept` header and unwraps an
71
+ * SSE reply to its JSON payload. Tool results are redacted by the kernel (`dispatchToolCall` runs
72
+ * the agent's redactor) and truncated to `limits.resultBytes` here. `options.permissionTool` adds a
73
+ * prompt tool backed by `run.ask` that only asks and never executes. `close()` unregisters the
74
+ * route, and it runs on `run.signal` abort and after an `approval_pending` result.
75
+ */
76
+ export async function serveTools(run: RunController, options: ServeToolsOptions): Promise<ServeToolsHandle> {
77
+ if (options.allow.length === 0 && options.permissionTool === undefined)
78
+ throw new ServeToolsError("serve_tools_empty", "serveTools needs a non-empty allow list");
79
+ const headerEnv = options.headerEnv ?? DEFAULT_HEADER_ENV;
80
+ const maxConcurrentCalls = bounded(
81
+ options.limits?.maxConcurrentCalls,
82
+ DEFAULT_MAX_CONCURRENT_CALLS,
83
+ HARD_MAX_CONCURRENT_CALLS,
84
+ "maxConcurrentCalls",
85
+ );
86
+ const resultBytes = bounded(options.limits?.resultBytes, DEFAULT_RESULT_BYTES, HARD_RESULT_BYTES, "resultBytes");
87
+ const resources = options.resources ?? [];
88
+ for (const resource of resources) {
89
+ if (Buffer.byteLength(resource.text, "utf8") > MAX_RESOURCE_BYTES)
90
+ throw new ServeToolsError("serve_tools_resource_bytes", `resource ${resource.uri} exceeds ${MAX_RESOURCE_BYTES} bytes`);
91
+ }
92
+ const prefix = options.prefix ?? "";
93
+ // Validate the transport before anything is registered, so a bad option leaves no route behind.
94
+ const env: Record<string, string> = {};
95
+ let endpoint: ServeToolsHandle["endpoint"];
96
+ if (options.transport === "loopback-http") {
97
+ endpoint = { transport: "http", url: `${options.broker.url}/mcp`, headerEnv };
98
+ env[headerEnv] = options.broker.token;
99
+ } else {
100
+ const command = options.relay?.command;
101
+ if (command === undefined || command.length === 0 || typeof command[0] !== "string" || command[0] === "")
102
+ throw new ServeToolsError("serve_tools_transport", "stdio-relay needs a non-empty relay.command");
103
+ endpoint = {
104
+ transport: "stdio",
105
+ command: command[0],
106
+ args: [...command.slice(1), "relay", "mcp", "--run", dirname(options.broker.socketPath)],
107
+ };
108
+ }
109
+ const bridge = bridgeTools(run, options.allow, { origin: options.origin, tools: options.tools });
110
+ const exposedNames = new Map(bridge.tools.map((tool) => [`${prefix}${tool.name}`, tool.name] as const));
111
+ const permission = options.permissionTool;
112
+ if (permission !== undefined && (permission.name.length === 0 || exposedNames.has(`${prefix}${permission.name}`)))
113
+ throw new ServeToolsError(
114
+ "serve_tools_permission_conflict",
115
+ "the permission tool needs a non-empty name that no allow-listed tool already takes",
116
+ );
117
+
118
+ let closed = false;
119
+ let closing: Promise<void> | undefined;
120
+ let activeCalls = 0;
121
+ let closeAfterCall = false;
122
+
123
+ const createServer: McpServerFactory = () => {
124
+ const server = new McpServer({ name: "prism-tools", version: manifest.version }, { capabilities: { tools: {}, resources: {} } });
125
+ for (const tool of bridge.tools) {
126
+ const exposed = `${prefix}${tool.name}`;
127
+ server.registerTool(
128
+ exposed,
129
+ { description: tool.description, inputSchema: fromJsonSchema(tool.schema as JsonSchemaType) },
130
+ async (args: unknown): Promise<CallToolResult> => await callTool(exposed, args),
131
+ );
132
+ }
133
+ for (const resource of resources) {
134
+ server.registerResource(
135
+ resource.name,
136
+ resource.uri,
137
+ { title: resource.name, ...(resource.mimeType === undefined ? {} : { mimeType: resource.mimeType }) },
138
+ async (uri) => ({
139
+ contents: [
140
+ {
141
+ uri: uri.href,
142
+ ...(resource.mimeType === undefined ? {} : { mimeType: resource.mimeType }),
143
+ text: resource.text,
144
+ },
145
+ ],
146
+ }),
147
+ );
148
+ }
149
+ if (permission !== undefined) {
150
+ server.registerTool(
151
+ `${prefix}${permission.name}`,
152
+ {
153
+ description: "Ask the host to allow or deny a tool call. Answers JSON { behavior, updatedInput?, message? }.",
154
+ inputSchema: fromJsonSchema((permission.codec === undefined ? PERMISSION_SCHEMA : PERMISSION_CODEC_SCHEMA) as JsonSchemaType),
155
+ },
156
+ async (args: unknown): Promise<CallToolResult> => await permissionCall(args),
157
+ );
158
+ }
159
+ return server;
160
+ };
161
+
162
+ const web: PrismMcpWebHandler = await createPrismMcpWebHandler(createServer);
163
+
164
+ const close = (): Promise<void> => {
165
+ closing ??= (async () => {
166
+ if (closed) return;
167
+ closed = true;
168
+ run.signal.removeEventListener("abort", onAbort);
169
+ options.broker.route("mcp", undefined);
170
+ await web.close();
171
+ })();
172
+ return closing;
173
+ };
174
+ const onAbort = (): void => void close();
175
+ run.signal.addEventListener("abort", onAbort, { once: true });
176
+
177
+ const route = async (request: Request): Promise<Response> => {
178
+ if (closed) return rpcErrorResponse(undefined, -32000, CLOSED_MESSAGE);
179
+ const text = await request.text();
180
+ const message = parseMessage(text);
181
+ const id = message !== undefined && "id" in message ? message.id : undefined;
182
+ const isCall = message?.method === "tools/call";
183
+ if (isCall && activeCalls >= maxConcurrentCalls)
184
+ return rpcErrorResponse(id, -32000, "too many concurrent tool calls; the call was not queued");
185
+ if (isCall) activeCalls += 1;
186
+ try {
187
+ const response = await web(normalizeRequest(request, text));
188
+ const settled = await unwrapSse(response);
189
+ if (closeAfterCall) {
190
+ closeAfterCall = false;
191
+ await close();
192
+ }
193
+ return settled;
194
+ } finally {
195
+ if (isCall) activeCalls -= 1;
196
+ }
197
+ };
198
+
199
+ options.broker.route("mcp", route);
200
+ if (run.signal.aborted) await close();
201
+
202
+ return { endpoint, env, tools: [...exposedNames.keys(), ...(permission === undefined ? [] : [`${prefix}${permission.name}`])], close };
203
+
204
+ async function callTool(exposed: string, args: unknown): Promise<CallToolResult> {
205
+ const name = exposedNames.get(exposed);
206
+ if (name === undefined) return errorResult(`unknown tool ${exposed}`);
207
+ const result = await bridge.invoke({
208
+ type: "tool_call",
209
+ id: randomUUID(),
210
+ name,
211
+ arguments: isRecord(args) ? (args as JsonObject) : ({} as JsonObject),
212
+ });
213
+ if ((result.metadata as { approvalPending?: unknown } | undefined)?.approvalPending === true) {
214
+ closeAfterCall = true;
215
+ return errorResult(APPROVAL_PENDING_MESSAGE);
216
+ }
217
+ return contentResult(result);
218
+ }
219
+
220
+ function errorResult(message: string): CallToolResult {
221
+ return { isError: true, content: [{ type: "text", text: truncateUtf8(message, resultBytes) }] };
222
+ }
223
+
224
+ /**
225
+ * One `run.ask` per call, and never an execution. Every failure path denies: a throwing `decode`
226
+ * or gate, an `encode` that throws, and a decision that cannot be recorded.
227
+ */
228
+ async function permissionCall(args: unknown): Promise<CallToolResult> {
229
+ let request: PermissionRequest;
230
+ try {
231
+ request = permission?.codec === undefined ? decodePermission(args) : permission.codec.decode(args as JsonValue);
232
+ } catch (error) {
233
+ return neutralResult({ behavior: "deny", message: `permission request rejected: ${throwText(error)}` });
234
+ }
235
+ const toolCallId = request.toolCallId ?? randomUUID();
236
+ let decision: ExternalToolDecision;
237
+ try {
238
+ decision = await run.ask(
239
+ {
240
+ toolCallId,
241
+ name: request.toolName,
242
+ args: request.input,
243
+ effects: permission?.effects?.(request.toolName) ?? ALL_TOOL_EFFECTS,
244
+ },
245
+ { rewrite: permission?.rewrite ?? false },
246
+ );
247
+ } catch {
248
+ decision = { allow: false, reason: "tool_call_gate_failed" };
249
+ }
250
+ if ("allow" in decision && decision.allow === false && decision.reason === "approval_pending") closeAfterCall = true;
251
+ let mapped = mapPermission(decision);
252
+ let result: CallToolResult;
253
+ if (permission?.codec === undefined) {
254
+ result = neutralResult(mapped);
255
+ } else {
256
+ try {
257
+ result = permission.codec.encode(mapped);
258
+ } catch (error) {
259
+ mapped = { behavior: "deny", message: `permission codec failed: ${throwText(error)}` };
260
+ result = neutralResult(mapped);
261
+ }
262
+ }
263
+ try {
264
+ await run.state(PERMISSION_STATE_KEY).append([
265
+ {
266
+ toolName: request.toolName,
267
+ toolCallId,
268
+ behavior: mapped.behavior,
269
+ ...(mapped.message === undefined ? {} : { reason: mapped.message }),
270
+ },
271
+ ]);
272
+ } catch {
273
+ if (mapped.behavior === "allow") {
274
+ mapped = { behavior: "deny", message: "permission record failed, so the call is denied" };
275
+ result = neutralResult(mapped);
276
+ }
277
+ }
278
+ return result;
279
+ }
280
+
281
+ /**
282
+ * Both halves of a result: the text a client reads and, when the value is a JSON object that fits
283
+ * the byte cap, `structuredContent` for clients that can use the structure. An untrusted result
284
+ * carries the kernel's envelope instead of the bare blocks, so a client sees what the model sees.
285
+ */
286
+ function contentResult(result: ToolResult): CallToolResult {
287
+ if (result.error !== undefined && result.error !== null) return errorResult(errorText(result.error));
288
+ const untrusted = result.metadata?.trust === UNTRUSTED_EXTERNAL_TRUST;
289
+ const structured = structuredContent(result);
290
+ const blocks = result.content ?? [];
291
+ const content: CallToolResult["content"] = untrusted
292
+ ? [
293
+ { type: "text", text: clipUntrusted(formatUntrustedToolText(result)) },
294
+ ...blocks.filter((block) => block.type !== "text").map(blockToContent),
295
+ ]
296
+ : blocks.map(blockToContent);
297
+ if (!untrusted && content.length === 0 && result.value !== undefined)
298
+ content.push({ type: "text", text: clip(stringify(result.value)) });
299
+ return { content, ...(structured === undefined ? {} : { structuredContent: structured }) };
300
+ }
301
+
302
+ /** The value passes through only when it is a JSON object within the same byte cap as the text. */
303
+ function structuredContent(result: ToolResult): unknown {
304
+ const value = result.value;
305
+ if (value === undefined || value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
306
+ return Buffer.byteLength(stringify(value), "utf8") > resultBytes ? undefined : value;
307
+ }
308
+
309
+ /** The envelope keeps its preamble and closing tag; only the body is clipped. */
310
+ function clipUntrusted(envelope: string): string {
311
+ if (Buffer.byteLength(envelope, "utf8") <= resultBytes) return envelope;
312
+ const tail = envelope.slice(envelope.lastIndexOf("\n"));
313
+ const budget = Math.max(0, resultBytes - Buffer.byteLength(tail, "utf8"));
314
+ return truncateUtf8(envelope.slice(0, envelope.lastIndexOf("\n")), budget) + tail;
315
+ }
316
+
317
+ function blockToContent(block: ContentBlock): CallToolResult["content"][number] {
318
+ if (block.type === "text") return { type: "text", text: clip(block.text) };
319
+ return { type: "text", text: clip(stringify(block)) };
320
+ }
321
+
322
+ function clip(text: string): string {
323
+ return truncateUtf8(text, resultBytes);
324
+ }
325
+ }
326
+
327
+ /** Restores the streamable-HTTP `accept` header the broker drops, preserving the body. */
328
+ function normalizeRequest(request: Request, text: string): Request {
329
+ const headers = new Headers(request.headers);
330
+ headers.set("accept", "application/json, text/event-stream");
331
+ return new Request(request.url, { method: request.method, headers, ...(text === "" ? {} : { body: text }) });
332
+ }
333
+
334
+ /** A streamable-HTTP reply may be SSE; the JSON-RPC message is the last `data:` line. */
335
+ async function unwrapSse(response: Response): Promise<Response> {
336
+ if (!(response.headers.get("content-type") ?? "").includes("text/event-stream")) return response;
337
+ const body = await response.text();
338
+ const payload = body
339
+ .split("\n")
340
+ .filter((line) => line.startsWith("data:"))
341
+ .at(-1)
342
+ ?.slice(5)
343
+ .trim();
344
+ if (payload === undefined) return rpcErrorResponse(undefined, -32603, "empty MCP event stream");
345
+ return new Response(payload, { status: 200, headers: { "content-type": "application/json" } });
346
+ }
347
+
348
+ function rpcErrorResponse(id: unknown, code: number, message: string): Response {
349
+ return Response.json({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
350
+ }
351
+
352
+ /** The neutral permission input, validated. A codec replaces this decode. */
353
+ function decodePermission(args: unknown): PermissionRequest {
354
+ if (!isRecord(args)) throw new TypeError("permission arguments must be an object");
355
+ const { toolName, input, toolCallId } = args;
356
+ if (typeof toolName !== "string" || toolName.length === 0) throw new TypeError("toolName must be a non-empty string");
357
+ if (input === null || typeof input !== "object" || Array.isArray(input)) throw new TypeError("input must be an object");
358
+ if (toolCallId !== undefined && typeof toolCallId !== "string") throw new TypeError("toolCallId must be a string");
359
+ return { toolName, input: input as JsonObject, ...(toolCallId === undefined ? {} : { toolCallId }) };
360
+ }
361
+
362
+ /** The gate's answer as the neutral decision. A `respond` is never forwarded: the tool only asks. */
363
+ function mapPermission(decision: ExternalToolDecision): PermissionDecision {
364
+ if ("respond" in decision) return { behavior: "deny", message: PERMISSION_RESPOND_MESSAGE };
365
+ if (decision.allow) return { behavior: "allow", ...(decision.args === undefined ? {} : { updatedInput: decision.args as JsonObject }) };
366
+ if (decision.reason === "approval_pending") return { behavior: "deny", message: PERMISSION_PENDING_MESSAGE };
367
+ if (decision.reason === "non_interactive") return { behavior: "deny", message: PERMISSION_NO_UI_MESSAGE };
368
+ return { behavior: "deny", message: `denied: ${decision.reason}` };
369
+ }
370
+
371
+ /** The neutral shape: the decision as JSON text, never `isError` (the vendor reads it as a decision). */
372
+ function neutralResult(decision: PermissionDecision): CallToolResult {
373
+ try {
374
+ return { content: [{ type: "text", text: JSON.stringify(decision) }] };
375
+ } catch {
376
+ return { isError: true, content: [{ type: "text", text: "permission decision could not be encoded" }] };
377
+ }
378
+ }
379
+
380
+ function throwText(error: unknown): string {
381
+ return error instanceof Error ? error.message : String(error);
382
+ }
383
+
384
+ function parseMessage(text: string): { method?: string; id?: unknown } | undefined {
385
+ try {
386
+ const value: unknown = JSON.parse(text);
387
+ return isRecord(value) ? (value as { method?: string; id?: unknown }) : undefined;
388
+ } catch {
389
+ return undefined;
390
+ }
391
+ }
392
+
393
+ function errorText(error: { code?: string | number; message?: string }): string {
394
+ const message = error.message ?? "the tool failed";
395
+ return error.code === undefined ? message : `${error.code}: ${message}`;
396
+ }
397
+
398
+ function isRecord(value: unknown): value is Record<string, unknown> {
399
+ return typeof value === "object" && value !== null && !Array.isArray(value);
400
+ }
401
+
402
+ function stringify(value: unknown): string {
403
+ try {
404
+ return JSON.stringify(value) ?? "null";
405
+ } catch {
406
+ return "[unserializable result]";
407
+ }
408
+ }