@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,300 @@
1
+ import type { CallToolResult, GetPromptResult, ReadResourceResult } from "@modelcontextprotocol/server";
2
+ import { McpServer } from "@modelcontextprotocol/server";
3
+ import * as z from "zod/v4";
4
+ import manifest from "../../package.json" with { type: "json" };
5
+ import { checkPackage } from "./check/conformance.js";
6
+ import { inspectHost } from "./check/inspect.js";
7
+ import { checkManifest } from "./check/manifest.js";
8
+ import { DEFAULT_CHECK_TIMEOUT_MS, MAX_CHECK_TIMEOUT_MS } from "./check/runner.js";
9
+ import { type CheckTargets, findTarget, resolveCheckTargets } from "./check/targets.js";
10
+ import { HostBuilderError } from "./errors.js";
11
+ import { type LoadHostBuilderIndexOptions, loadHostBuilderIndex } from "./indexes.js";
12
+ import { lookupApi } from "./lookup/api.js";
13
+ import { boundedJson, byteLength, MAX_RESULT_BYTES, truncateBytes, truncationMarker } from "./lookup/bound.js";
14
+ import { DocsIndex } from "./lookup/docs.js";
15
+ import { lookupError } from "./lookup/errors.js";
16
+ import { lookupExamples } from "./lookup/examples.js";
17
+ import { checkVersion } from "./version.js";
18
+
19
+ export interface HostBuilderMcpOptions extends LoadHostBuilderIndexOptions {
20
+ /** The host project. Docs are read from `<root>/node_modules/@arnilo/` and the installed Prism version from the same place. */
21
+ readonly root: string;
22
+ /** Turns a version mismatch from a tool error into a `warning` field on every result. */
23
+ readonly allowVersionMismatch?: boolean;
24
+ /** `file#export` of async functions that return an `Agent`, for `prism_inspect_host`. Resolved under `root` at creation. */
25
+ readonly entries?: readonly string[];
26
+ /** `file#export` of package definitions or factories, for `prism_check_package`. Resolved under `root` at creation. */
27
+ readonly packages?: readonly string[];
28
+ /** Let `prism_check_manifest` import project-scope packages (what `prism verify --trust-project` does). */
29
+ readonly trustProject?: boolean;
30
+ /** Seconds a check may run before its child is killed (default 30, at most 120). */
31
+ readonly checkTimeoutSeconds?: number;
32
+ /** Names of environment variables the check child may see besides PATH, HOME, TMPDIR and PRISM_HOME. */
33
+ readonly passEnv?: readonly string[];
34
+ }
35
+
36
+ const SKILL_PATH = "node_modules/@arnilo/prism-hosts/host-builder/skills/prism-host-builder/SKILL.md";
37
+
38
+ const READ_ONLY = { readOnlyHint: true, idempotentHint: true, openWorldHint: false } as const;
39
+
40
+ function text(value: string): CallToolResult {
41
+ return { content: [{ type: "text", text: value }] };
42
+ }
43
+
44
+ const CHECK = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true } as const;
45
+
46
+ function failure(error: unknown): CallToolResult {
47
+ if (error instanceof HostBuilderError) return { isError: true, content: [{ type: "text", text: `${error.code}: ${error.message}` }] };
48
+ throw error;
49
+ }
50
+
51
+ function prompt(body: string): GetPromptResult {
52
+ return { messages: [{ role: "user", content: { type: "text", text: body } }] };
53
+ }
54
+
55
+ /**
56
+ * The host-builder MCP server: four read-only lookup tools, the installed docs as resources, and three prompts.
57
+ *
58
+ * Tools check the project's installed `@arnilo/prism` version against the indexes before answering; a mismatch is
59
+ * a tool error unless `allowVersionMismatch` is set. Resources are the pages installed under
60
+ * `<root>/node_modules/@arnilo/`; a page whose real path leaves `node_modules` is refused. Nothing here writes,
61
+ * runs host code, calls a model or opens the network. The exception is the three check tools
62
+ * (`prism_inspect_host`, `prism_check_manifest`, `prism_check_package`): each runs the host's own code in a
63
+ * bounded child process, only for targets the server was started with, never for a path a tool call supplies.
64
+ */
65
+ export function createHostBuilderMcpServer(options: HostBuilderMcpOptions): McpServer {
66
+ const { root } = options;
67
+ const allowMismatch = options.allowVersionMismatch === true;
68
+ const indexOptions: LoadHostBuilderIndexOptions = options.dataDir === undefined ? {} : { dataDir: options.dataDir };
69
+ const docs = new DocsIndex(root);
70
+ const targets: CheckTargets = resolveCheckTargets(root, options.entries, options.packages);
71
+ const checkSettings = {
72
+ root,
73
+ timeoutMs: Math.min(options.checkTimeoutSeconds ?? DEFAULT_CHECK_TIMEOUT_MS / 1000, MAX_CHECK_TIMEOUT_MS / 1000) * 1000,
74
+ passEnv: options.passEnv ?? [],
75
+ };
76
+ const flagHelp = (flag: string) =>
77
+ `No ${flag} target is configured. Restart the server with ${flag} <file>#<export> (for example: prism-host-builder mcp ${flag} src/agent.ts#createInspectionAgent); a check runs only code the user named at start.`;
78
+ const server = new McpServer(
79
+ { name: "prism-host-builder", version: manifest.version },
80
+ { capabilities: { tools: {}, resources: {}, prompts: {} } },
81
+ );
82
+
83
+ /** Runs a lookup after the version check; adds the mismatch warning when one was allowed. */
84
+ async function answer(run: () => Promise<object> | object): Promise<CallToolResult> {
85
+ try {
86
+ const api = await loadHostBuilderIndex("api", indexOptions);
87
+ const { warning } = checkVersion(root, api.prismVersion, allowMismatch);
88
+ const result = await run();
89
+ return text(boundedJson(warning === undefined ? result : { warning, ...result }));
90
+ } catch (error) {
91
+ return failure(error);
92
+ }
93
+ }
94
+
95
+ server.registerTool(
96
+ "prism_api",
97
+ {
98
+ title: "Prism API lookup",
99
+ description:
100
+ "Look up a public Prism name. Pass `symbol` for an exact export name (case-sensitive), or `query` for words matched against names, signatures and summaries; `package` limits either to one package (for example @arnilo/prism-extensions/approval). Returns signature, package, import specifier, docs pages and examples, and for an interface or class its `members` (field and method declarations): read a field name there, never guess it. An unknown name returns the nearest names.",
101
+ inputSchema: z.object({
102
+ symbol: z.string().max(200).optional(),
103
+ query: z.string().max(200).optional(),
104
+ package: z.string().max(200).optional(),
105
+ }),
106
+ annotations: READ_ONLY,
107
+ },
108
+ (args) =>
109
+ answer(async () =>
110
+ lookupApi(await loadHostBuilderIndex("api", indexOptions), {
111
+ ...(args.symbol !== undefined ? { symbol: args.symbol } : {}),
112
+ ...(args.query !== undefined ? { query: args.query } : {}),
113
+ ...(args.package !== undefined ? { package: args.package } : {}),
114
+ }),
115
+ ),
116
+ );
117
+
118
+ server.registerTool(
119
+ "prism_errors",
120
+ {
121
+ title: "Prism error code lookup",
122
+ description:
123
+ "Look up an error code (`ERR_PRISM_*` or a short code such as `model_required`): meaning, owning package, declaring file:line, related docs, and the fix the host-builder skill lists. An unknown code returns the nearest codes.",
124
+ inputSchema: z.object({ code: z.string().min(1).max(200) }),
125
+ annotations: READ_ONLY,
126
+ },
127
+ (args) => answer(async () => lookupError(await loadHostBuilderIndex("errors", indexOptions), args.code)),
128
+ );
129
+
130
+ server.registerTool(
131
+ "prism_examples",
132
+ {
133
+ title: "Prism examples",
134
+ description:
135
+ "Find CI-tested examples by `query` (words) and/or `package` (an imported package), or pass `path` (for example examples/define-package.ts) to read one example's source. Only examples in the shipped index are served.",
136
+ inputSchema: z.object({
137
+ query: z.string().max(200).optional(),
138
+ package: z.string().max(200).optional(),
139
+ path: z.string().max(300).optional(),
140
+ }),
141
+ annotations: READ_ONLY,
142
+ },
143
+ (args) =>
144
+ answer(async () =>
145
+ lookupExamples(
146
+ await loadHostBuilderIndex("examples", indexOptions),
147
+ {
148
+ ...(args.query !== undefined ? { query: args.query } : {}),
149
+ ...(args.package !== undefined ? { package: args.package } : {}),
150
+ ...(args.path !== undefined ? { path: args.path } : {}),
151
+ },
152
+ indexOptions,
153
+ ),
154
+ ),
155
+ );
156
+
157
+ server.registerTool(
158
+ "prism_docs",
159
+ {
160
+ title: "Prism docs search",
161
+ description:
162
+ "Search the Prism docs pages and package READMEs installed in this project (node_modules/@arnilo). Returns heading-anchored excerpts with a prism-docs:// URI to read the whole page. Every word of the query must appear in a section.",
163
+ inputSchema: z.object({ query: z.string().min(1).max(200) }),
164
+ annotations: READ_ONLY,
165
+ },
166
+ (args) => answer(() => docs.search(args.query)),
167
+ );
168
+
169
+ server.registerTool(
170
+ "prism_inspect_host",
171
+ {
172
+ title: "Inspect the host's agent",
173
+ description:
174
+ "Runs the configured inspection factory (`--entry`) in a child process, returns `agent.inspect()` (packages, tools, skills with requiresTools, hooks, slot owners, status notes) and disposes the agent. EXECUTES the host's own code, which can spawn processes and read the allowlisted environment; the factory should build the agent on the mock provider and run nothing. Pass `entry` as one of the configured names.",
175
+ inputSchema: z.object({ entry: z.string().min(1).max(500) }),
176
+ annotations: CHECK,
177
+ },
178
+ (args) =>
179
+ answer(async () => {
180
+ if (targets.entries.length === 0) return { configured: [], guidance: flagHelp("--entry") };
181
+ const target = findTarget(root, targets.entries, args.entry);
182
+ if (target === undefined)
183
+ return {
184
+ ok: false,
185
+ error: { message: `"${args.entry}" is not a configured entry.` },
186
+ configured: targets.entries.map((entry) => entry.name),
187
+ };
188
+ return { ...(await inspectHost(checkSettings, target)) };
189
+ }),
190
+ );
191
+
192
+ server.registerTool(
193
+ "prism_check_manifest",
194
+ {
195
+ title: "Check the Prism manifest",
196
+ description:
197
+ "Runs what `prism verify` does for this project: re-hashes every installed package and re-checks its config against its schema. A project-scope package is imported (so its code runs) only when the server was started with `--trust-project`; otherwise it gets the integrity check alone and `configChecked` is false. Takes no arguments.",
198
+ inputSchema: z.object({}),
199
+ annotations: CHECK,
200
+ },
201
+ () => answer(async () => ({ ...(await checkManifest(checkSettings, options.trustProject === true)) })),
202
+ );
203
+
204
+ server.registerTool(
205
+ "prism_check_package",
206
+ {
207
+ title: "Check a package with packageConformance",
208
+ description:
209
+ "Runs `packageConformance` from the installed @arnilo/prism/testing on a configured package (`--package`) and returns each check's result. EXECUTES the package's code on a mock provider in a child process. Pass `package` as one of the configured names.",
210
+ inputSchema: z.object({ package: z.string().min(1).max(500) }),
211
+ annotations: CHECK,
212
+ },
213
+ (args) =>
214
+ answer(async () => {
215
+ if (targets.packages.length === 0) return { configured: [], guidance: flagHelp("--package") };
216
+ const target = findTarget(root, targets.packages, args.package);
217
+ if (target === undefined)
218
+ return {
219
+ ok: false,
220
+ error: { message: `"${args.package}" is not a configured package.` },
221
+ configured: targets.packages.map((entry) => entry.name),
222
+ };
223
+ return { ...(await checkPackage(checkSettings, target)) };
224
+ }),
225
+ );
226
+
227
+ for (const page of docs.listPages()) {
228
+ server.registerResource(
229
+ `${page.package.replace(/^@arnilo\//, "")}/${page.path}`,
230
+ page.uri,
231
+ { title: page.display, mimeType: "text/markdown" },
232
+ async (uri): Promise<ReadResourceResult> => {
233
+ const read = docs.read(page.uri);
234
+ if (read === undefined)
235
+ throw new HostBuilderError("ERR_PRISM_HOST_BUILDER_INDEX", `${page.display} is not readable inside ${root}/node_modules.`);
236
+ const cut = truncateBytes(read.text, MAX_RESULT_BYTES - 128);
237
+ const body = cut.truncated ? `${cut.text}${truncationMarker(byteLength(read.text) - byteLength(cut.text))}` : cut.text;
238
+ return { contents: [{ uri: uri.href, mimeType: "text/markdown", text: body }] };
239
+ },
240
+ );
241
+ }
242
+
243
+ server.registerPrompt(
244
+ "build-host",
245
+ {
246
+ title: "Build a Prism host",
247
+ description: "Build or extend a Prism host: load the skill, choose with the decision trees, build, verify.",
248
+ argsSchema: z.object({ goal: z.string().max(2000).optional() }),
249
+ },
250
+ (args) =>
251
+ prompt(
252
+ [
253
+ `Build a Prism host${args.goal ? ` for this goal: ${args.goal}` : ""}.`,
254
+ `1. Read the host-builder skill at ${SKILL_PATH} and follow its workflow.`,
255
+ "2. Choose the host library, store, slot owners, approval and provider with references/choosing.md. Confirm every name with prism_api before you import it.",
256
+ "3. Start from a tested example (prism_examples) instead of writing from memory. Read the page it names (prism_docs).",
257
+ "4. Verify with references/verification.md: typecheck, the mock provider and agent.inspect(). Report what ran and what you could not run.",
258
+ ].join("\n"),
259
+ ),
260
+ );
261
+
262
+ server.registerPrompt(
263
+ "add-capability",
264
+ {
265
+ title: "Add a capability to a Prism host",
266
+ description: "Add one capability (a tool, hook, package, provider, store or server) to an existing Prism host.",
267
+ argsSchema: z.object({ capability: z.string().min(1).max(500) }),
268
+ },
269
+ (args) =>
270
+ prompt(
271
+ [
272
+ `Add this capability to the Prism host in this project: ${args.capability}.`,
273
+ `1. Read the host-builder skill at ${SKILL_PATH} and the matching entry in references/recipes.md.`,
274
+ "2. Place it with references/layout.md (kernel, package or host code) and check the public surface rule.",
275
+ "3. Look up each name with prism_api and each error you meet with prism_errors. Copy the tested example, then change the model to the host's.",
276
+ "4. Keep fail-closed behavior and secret refs intact (references/security.md). Verify with references/verification.md.",
277
+ ].join("\n"),
278
+ ),
279
+ );
280
+
281
+ server.registerPrompt(
282
+ "upgrade-host",
283
+ {
284
+ title: "Upgrade a Prism host",
285
+ description: "Move a Prism host to the installed version: read the version, the migration notes and check for retired names.",
286
+ },
287
+ () =>
288
+ prompt(
289
+ [
290
+ "Upgrade the Prism host in this project to the installed @arnilo/prism version.",
291
+ `1. Read the installed version in node_modules/@arnilo/prism/package.json, then the host-builder skill at ${SKILL_PATH} and references/upgrading.md.`,
292
+ '2. Read the installed migration page (prism_docs with query "migrate") and apply each retired-name row to the host\'s code.',
293
+ "3. Search the host's code for every retired name in the table. A hit is a change to make, not a name to alias.",
294
+ "4. Typecheck, load the agent on the mock provider and read agent.inspect() (references/verification.md). Report what you changed and what you could not check.",
295
+ ].join("\n"),
296
+ ),
297
+ );
298
+
299
+ return server;
300
+ }
@@ -0,0 +1,38 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { HostBuilderError } from "./errors.js";
4
+
5
+ /** The `@arnilo/prism` version installed under `root`, or `undefined` when it is not installed or unreadable. */
6
+ export function installedPrismVersion(root: string): string | undefined {
7
+ try {
8
+ const parsed = JSON.parse(readFileSync(join(root, "node_modules", "@arnilo", "prism", "package.json"), "utf8")) as {
9
+ version?: unknown;
10
+ };
11
+ return typeof parsed.version === "string" ? parsed.version : undefined;
12
+ } catch {
13
+ return undefined;
14
+ }
15
+ }
16
+
17
+ export interface VersionCheck {
18
+ /** Set only when a mismatch was allowed: the text to put on every result. */
19
+ readonly warning?: string;
20
+ }
21
+
22
+ /**
23
+ * Compares the project's installed `@arnilo/prism` with the version the indexes describe. A mismatch, or no
24
+ * install at all, fails with `ERR_PRISM_HOST_BUILDER_VERSION` naming both versions and the fix, unless
25
+ * `allowMismatch` turns it into a warning. The indexes are exact for one version, so a lookup against another
26
+ * would answer with the wrong contract.
27
+ */
28
+ export function checkVersion(root: string, indexVersion: string, allowMismatch: boolean): VersionCheck {
29
+ const installed = installedPrismVersion(root);
30
+ if (installed === indexVersion) return {};
31
+ const fix = installed === undefined ? `bun add -d @arnilo/prism@${indexVersion}` : `bun add -d @arnilo/prism-hosts@${installed}`;
32
+ const message =
33
+ installed === undefined
34
+ ? `@arnilo/prism is not installed under ${root}; the indexes describe ${indexVersion}. Fix: ${fix}`
35
+ : `@arnilo/prism ${installed} is installed under ${root}; the indexes describe ${indexVersion}. Fix: ${fix}`;
36
+ if (allowMismatch) return { warning: `version mismatch allowed: ${message}` };
37
+ throw new HostBuilderError("ERR_PRISM_HOST_BUILDER_VERSION", message);
38
+ }
@@ -0,0 +1,219 @@
1
+ # @arnilo/prism-hosts/mcp-server
2
+
3
+ Host library serving a Prism **agent** over the Model Context Protocol (MCP).
4
+
5
+ `serveMcp(agent, options)` exposes the agent as one tool (`prompt`, rename with `toolName`) and lists
6
+ `agent.commands` as MCP prompts. It never dispatches a bare tool: every call runs
7
+ `session.run(prompt)` on the session bound to the MCP session, so approvals, governance hooks, and
8
+ limits all fire. Serving a generic `ToolDefinition[]` to a vendor's own agent is
9
+ [`serveTools`](#serving-tools-and-permissions-to-an-external-agent), built beside `serveMcp` on the
10
+ same transport helpers.
11
+
12
+ ```ts
13
+ import { createAgent } from "@arnilo/prism";
14
+ import { mcpHost, serveMcp } from "@arnilo/prism-hosts/mcp-server";
15
+
16
+ const agent = await createAgent({ model, packages, host: mcpHost() });
17
+ await serveMcp(agent, { stdio: true }).closed;
18
+ ```
19
+
20
+ ## Transports
21
+
22
+ `serveMcp` takes exactly one of:
23
+
24
+ | Option | Transport | Handler |
25
+ | --- | --- | --- |
26
+ | `{ stdio: true }` | dual-era stdio subprocess | `servePrismMcpStdio` |
27
+ | `{ transport }` | caller-owned `Transport` (in-process tests, embedded hosts) | `servePrismMcpStdio` |
28
+ | `{ http: { … } }` | MCP 2026-07-28 Streamable HTTP + 2025 legacy fallback | `createPrismMcpWebHandler` |
29
+
30
+ The returned handle carries `closed`, `close()`, and — for `{ http }` — a web-standard
31
+ `handler(request) => Promise<Response>`. Both transport helpers stay public and can be used
32
+ directly with any `McpServer` factory.
33
+
34
+ ## Serving tools and permissions to an external agent
35
+
36
+ `serveTools(run, options)` bridges a subset of a run's tools to an external agent over the run's
37
+ callback broker, so the vendor's own agent loop calls Prism tools through the same `tool.call` gate
38
+ the internal loop uses. It is what a Prism *driver* hands its vendor binary; the vendor maps the
39
+ neutral `endpoint` into its own MCP configuration.
40
+
41
+ ```ts
42
+ import { serveTools } from "@arnilo/prism-hosts/mcp-server";
43
+
44
+ const served = await serveTools(run, {
45
+ broker,
46
+ tools: definitions,
47
+ allow: ["read", "edit"],
48
+ transport: "loopback-http",
49
+ origin: { kind: "external", agent: "claude", agentId: "claude", vendor: "anthropic", depth: 0 },
50
+ });
51
+ try {
52
+ // spawn the binary with served.endpoint in its MCP config and served.env in its environment
53
+ } finally {
54
+ await served.close();
55
+ }
56
+ ```
57
+
58
+ | Option | Meaning |
59
+ | --- | --- |
60
+ | `broker` | The run's callback broker. `serveTools` mounts its handler on `broker.route("mcp")`. |
61
+ | `tools` | The `ToolDefinition[]` the allow list resolves against (there is no run-time registry read). |
62
+ | `allow` | Tool names to serve. Empty fails with `serve_tools_empty`; an unknown name fails with `unknown_tool` before anything is served. |
63
+ | `transport` | `"loopback-http"` or `"stdio-relay"`. |
64
+ | `origin` | The bridge origin every served call is attributed to. |
65
+ | `prefix` | Prepended to each served tool name in `tools/list` and `tools/call`. |
66
+ | `resources` | Static `{ uri, name, mimeType?, text }` resources, each bounded to 256 KiB. `skillResources` builds the entries for skills that go with the served tools ([below](#lending-skills-with-tools)). |
67
+ | `limits` | `{ maxConcurrentCalls?, resultBytes? }`. Defaults 8 / 1 MiB; hard caps 64 / 8 MiB. Caps text, `structuredContent`, and the envelope body alike. |
68
+ | `permissionTool` | `{ name, effects?, rewrite?, codec? }`: also serve a permission-prompt tool backed by `run.ask`. |
69
+ | `relay` | `{ command }`, required for `stdio-relay`. |
70
+ | `headerEnv` | The bearer-token variable name. Default `PRISM_MCP_TOKEN`. |
71
+
72
+ The handle returns `endpoint`, `env`, `tools`, and `close()`:
73
+
74
+ | Transport | `endpoint` | `env` |
75
+ | --- | --- | --- |
76
+ | `loopback-http` | `{ transport: "http", url: <broker>/mcp, headerEnv }` | `{ [headerEnv]: <broker token> }` |
77
+ | `stdio-relay` | `{ transport: "stdio", command, args: […, "relay", "mcp", "--run", <run dir>] }` | `{}` |
78
+
79
+ The token is never part of `endpoint`. Only the allow-listed tools are registered, so every other
80
+ tool is absent from `tools/list` and a `tools/call` naming one is a JSON-RPC error that never reaches
81
+ `executeTools`. A call over `maxConcurrentCalls` is a JSON-RPC error, never queued. `close()` is
82
+ idempotent, unregisters the route (later relay frames get the broker's `no MCP route is registered`),
83
+ and closes the handler; it runs on `run.signal` abort and after an `approval_pending` result. A call
84
+ after close is refused with JSON-RPC `-32000` and `served tools are closed`.
85
+
86
+ ### What a served call returns
87
+
88
+ A `tools/call` answer carries both halves of the `ToolResult`:
89
+
90
+ | `ToolResult` | Served as |
91
+ | --- | --- |
92
+ | text content | a `text` content block |
93
+ | `value`, a JSON object within `limits.resultBytes` | `structuredContent` (the same value, unmodified) |
94
+ | `value`, with no text content | a `text` block holding the clipped JSON |
95
+ | `error` | `isError: true` and one `text` block, `<code>: <message>` |
96
+ | `metadata.trust === "untrusted_external"` | one `text` block holding the kernel envelope (`formatUntrustedToolText`), so a vendor agent sees exactly what the internal loop would; `structuredContent` still carries the value, and any non-text blocks follow the envelope |
97
+ | nothing | an empty `content` array |
98
+
99
+ `structuredContent` is only sent for a JSON object: a client that advertises no output schema
100
+ validates nothing, so a bare array or primitive would be rejected by strict clients, and the value
101
+ already reaches them as JSON text. An over-cap value is not structured either — the clipped text is
102
+ the whole answer. Redaction happens in the kernel before the bridge, so both halves are the
103
+ redacted ones.
104
+
105
+ ### Lending skills with tools
106
+
107
+ `skillResources(skills, servedToolNames)` turns the skills that go with the served tools into `resources` entries, so a vendor agent that lists MCP resources can read how to use what it was lent. A driver passes its run context's skills and the same list it gives `serveTools` as `allow`:
108
+
109
+ ```ts
110
+ import { serveTools, skillResources } from "@arnilo/prism-hosts/mcp-server";
111
+
112
+ const lent = skillResources(context.skills.list(), allow);
113
+ const served = await serveTools(run, { broker, tools: context.tools, allow, transport: "loopback-http", origin, resources: lent.resources });
114
+ for (const skill of lent.skipped) log(`skill ${skill.name} not lent: ${skill.reason}`);
115
+ ```
116
+
117
+ - **Only skills tied to the lent tools.** A skill is lent when its `requiresTools` is non-empty and every name is in `servedToolNames`. A skill with no `requiresTools` is not lent (nothing says it applies to these tools), and neither is one that needs a tool you did not serve, so guidance for a tool the vendor does not have never leaves the process.
118
+ - **Standard Agent Skills markdown.** Each resource is `prism-skill://<name>`, `text/markdown`, and holds the skill as a `SKILL.md`: frontmatter (`name`, `description`, `metadata`) and the body. It is built from the loaded skill, never from the file path, and the path is not sent.
119
+ - **Never truncated.** A skill whose rendered text is over the 256 KiB resource bound is left out and listed in `skipped` (`{ name, reason: "oversized", bytes }`).
120
+ - **Pure.** It reads nothing and sends nothing; the resources travel only through the endpoint you serve. With `prefix` set, the vendor sees prefixed tool names while a skill names the registered ones; the helper does not rewrite skill text.
121
+ - **Resource text is served verbatim.** Skills are package files and carry no secrets, but a host skill is whatever its author wrote: do not lend one that holds a secret.
122
+
123
+ ### Permission tool
124
+
125
+ `permissionTool` serves one more tool, `prefix + name`, for a vendor whose binary has a
126
+ permission-prompt hook (`claude --permission-prompt-tool`). It only **asks**; it never executes. Each
127
+ call is one `run.ask`, and one bounded `prism.permissions` `external_state` entry holding
128
+ `{ toolName, toolCallId, behavior, reason }` — never the input.
129
+
130
+ Neutral input: `{ toolName: string, input: object, toolCallId?: string }`. Neutral output text:
131
+ JSON `{ behavior: "allow" | "deny", updatedInput?, message? }`.
132
+
133
+ | `run.ask` answer | Output |
134
+ | --- | --- |
135
+ | `{ allow: true }` | `{ behavior: "allow" }` |
136
+ | `{ allow: true, args }` | `{ behavior: "allow", updatedInput: args }`, only with `rewrite: true` |
137
+ | `{ allow: false, reason: "approval_pending" }` | `{ behavior: "deny", message }` — the run is suspended; the server then closes |
138
+ | `{ allow: false, reason: "non_interactive" }` | `{ behavior: "deny", message }` — no one can approve |
139
+ | any other reason | `{ behavior: "deny", message: "denied: <reason>" }` |
140
+
141
+ | Option | Meaning |
142
+ | --- | --- |
143
+ | `name` | The served tool name, `prefix + name`. Must not collide with an allow-listed tool. |
144
+ | `effects` | `(toolName) => effects` for `run.ask`. Default every effect, as `effectsTable` treats an unknown name. |
145
+ | `rewrite` | Pass `rewrite: true` to `run.ask` so a gate rewrite becomes `updatedInput`. Default `false`. |
146
+ | `codec` | `{ decode(args): PermissionRequest; encode(decision): CallToolResult }`, the only vendor-shape hook. |
147
+
148
+ ```ts
149
+ import { effectsTable } from "@arnilo/prism/driver-kit";
150
+
151
+ permissionTool: {
152
+ name: "permission",
153
+ effects: effectsTable({ Bash: ["execute"], Write: ["write"] }),
154
+ rewrite: true,
155
+ };
156
+ ```
157
+
158
+ A `codec` replaces the neutral input and output — its `decode` receives the raw `tools/call`
159
+ arguments and its `encode` returns the whole MCP result. When a codec is set, the tool registers an
160
+ open object input schema, so any vendor shape reaches `decode`.
161
+
162
+ **It fails closed.** A throwing `decode` or gate, an `encode` that throws, and a decision that cannot
163
+ be recorded each answer `deny` in the neutral shape (`isError` only when even that cannot be built).
164
+ A `deny` is a normal result, not `isError`: the vendor reads the JSON as a decision. The tool cannot
165
+ bypass `tool.call` — it only asks, so nothing runs without the gate's own answer.
166
+
167
+ ## Sessions and approvals
168
+
169
+ One Prism session per MCP session: `ctx.sessionId` selects `agent.session({ id, create: true })`,
170
+ and a transport without session ids (stdio, in-process) gets one anonymous session per connection.
171
+ `session.run` always runs with `interactive: false`, so a kernel ask suspends instead of prompting.
172
+
173
+ A suspended run answers the tool call with the SDK's multi-round-trip `input_required` result when
174
+ the client advertised `elicitation.form`; the client's retry arrives as `inputResponses`, which map
175
+ to `session.resume(decisions)`. The `requestedSchema` is `{ outcome: "allow_once" | "allow_for_run" |
176
+ "reject_once" | "reject_for_run" }`; anything missing or unrecognized resumes as `reject_once`.
177
+ Without elicitation the tool result is `isError: true` naming the pending approval and **no gated
178
+ tool runs**.
179
+
180
+ `mcpHost()` is the `HostPort` passed to `createAgent`. It answers `unavailable` for `terminal` requests and for kernel asks
181
+ (`package` absent), `secret` requests, unbound sessions, and every notification; package
182
+ `confirm`/`select`/`input` reach the client only through the 2025-era `elicitInput` channel bound
183
+ while a run is in flight. On the 2026 era `elicitInput` throws, so mid-run package elicitation
184
+ answers `unavailable` (a Phase 14+ gap).
185
+
186
+ ## Security
187
+
188
+ - `authorize` runs before any session is opened and before any run; absent allows a local peer, a
189
+ throwing callback denies. `PrismMcpAuthorization.ownership` is passed through unchanged — identity
190
+ enforcement belongs to the agent's own governance hooks.
191
+ - Results and errors are redacted with `options.redactor` (default `agent.config.redactor`) and
192
+ truncated to `maxResultBytes` (default 1 MiB, hard cap 8 MiB). `maxPromptBytes` bounds one prompt
193
+ (default 64 KiB, hard cap 1 MiB).
194
+ - `serveTools` results are already redacted by the kernel (`dispatchToolCall` applies the agent's
195
+ redactor) and truncated to `limits.resultBytes` here. Its resource `text` is host-supplied and
196
+ served verbatim, so **never put a secret in a `resources` entry**.
197
+ - The HTTP helper keeps exact `allowedHosts`/`allowedOrigins` checks ahead of body parsing, bounded
198
+ request/response bytes, per-principal session binding, and RFC 9728 protected-resource challenges.
199
+ `serveTools` sets no Host/Origin allowlist: the broker's no-`Origin` 403 and bearer 401 already
200
+ gate every relayed frame.
201
+
202
+ ## Example
203
+
204
+ `examples/serve-tools.ts` serves a run's tools to an external agent's own loop, offline. Inside one
205
+ `session.run` an inline `defineDriver` driver binds a `workspace` worktree for the run's session,
206
+ materializes the vendor's MCP configuration into it with `excludeOverlay` (so the file never reaches
207
+ a diff), and serves `read`, `edit`, and the permission tool with `serveTools` — first over
208
+ `loopback-http`, then over `stdio-relay` — driving the scripted `jsonl-stream` CLI as the vendor
209
+ binary through `--mcp-endpoint`. It prints, per transport: the served names, an allowed `edit` that
210
+ changes the file in the worktree, a declined `edit` under `@arnilo/prism-extensions/approval` in `ask` mode, the
211
+ permission tool's `deny` and `allow`, an unserved name as a JSON-RPC error, a call after `close()`
212
+ refused, and the served calls' `origin` on the run's events. Then the worktree diff (the edit, not
213
+ the overlay) and a conflicting `merge` reported unresolved. `bun examples/serve-tools.ts` prints the
214
+ result as JSON; the served environment is printed as `[redacted]`, never with the token.
215
+
216
+ `examples/external-agent.ts` is the Phase 13 counterpart: it bridges tools to a vendor through the
217
+ broker's MCP route itself, without `serveTools`.
218
+
219
+ Protocol dependencies are optional peers of `@arnilo/prism-hosts`. Install `@modelcontextprotocol/server@^2.3.0` and `zod@^4.6.2`. Protocol entrypoints require these peers; see the [bundle dependency table](../README.md).
@@ -0,0 +1,23 @@
1
+ import { McpBridgeError } from "@arnilo/prism-extensions/mcp";
2
+
3
+ /** Resolves a bounded positive integer option, or throws naming the rule. Shared by `serve`, `server`, and `serve-tools`. */
4
+ export function bounded(value: number | undefined, fallback: number, cap: number, name: string): number {
5
+ const resolved = value ?? fallback;
6
+ if (!Number.isSafeInteger(resolved) || resolved < 1 || resolved > cap)
7
+ throw new McpBridgeError(`${name} must be a positive safe integer <= ${cap}`);
8
+ return resolved;
9
+ }
10
+
11
+ /** Truncates to at most `maxBytes` UTF-8 bytes without splitting a code point. */
12
+ export function truncateUtf8(text: string, maxBytes: number): string {
13
+ const encoder = new TextEncoder();
14
+ if (encoder.encode(text).byteLength <= maxBytes) return text;
15
+ let low = 0;
16
+ let high = text.length;
17
+ while (low < high) {
18
+ const middle = Math.ceil((low + high) / 2);
19
+ if (encoder.encode(text.slice(0, middle)).byteLength <= maxBytes) low = middle;
20
+ else high = middle - 1;
21
+ }
22
+ return text.slice(0, low);
23
+ }
@@ -0,0 +1,31 @@
1
+ import type { HostPort, HostUi, HostUiRequest, HostUiResponse } from "@arnilo/prism";
2
+ import { boundMcpSession, brandMcpHost } from "./session-map.js";
3
+
4
+ /**
5
+ * Host port whose `ui` routes by the kernel-stamped `sessionId`.
6
+ * A kernel ask (`package` absent) and `secret` answer `unavailable`, so approvals
7
+ * suspend onto the tool result's `input_required` instead of a boolean confirm.
8
+ * Package `confirm`/`select`/`input` reach the client only through the 2025-era
9
+ * elicitation channel bound while a run is in flight; everything else, including
10
+ * 2026-era mid-run package UI, answers `unavailable`.
11
+ */
12
+ export function mcpHost(): HostPort {
13
+ const port: HostPort = {
14
+ ui: {
15
+ request: (async (request: HostUiRequest): Promise<HostUiResponse> => {
16
+ if (request.package === undefined || request.kind === "secret") return { status: "unavailable" };
17
+ if (request.kind !== "confirm" && request.kind !== "select" && request.kind !== "input") return { status: "unavailable" };
18
+ const bound = boundMcpSession(port, request.sessionId);
19
+ if (!bound?.elicitation) return { status: "unavailable" };
20
+ return bound.elicit({
21
+ kind: request.kind,
22
+ title: request.title,
23
+ detail: "detail" in request ? request.detail : undefined,
24
+ ...(request.kind === "select" ? { options: request.options } : {}),
25
+ });
26
+ }) as HostUi["request"],
27
+ },
28
+ };
29
+ brandMcpHost(port);
30
+ return port;
31
+ }
@@ -0,0 +1,27 @@
1
+ export { McpBridgeError } from "@arnilo/prism-extensions/mcp";
2
+ export { mcpHost } from "./host.js";
3
+ export { ServeToolsError, serveTools } from "./serve-tools.js";
4
+ export { serveMcp } from "./serve.js";
5
+ export { type SkillResources, type SkippedSkillResource, skillResources } from "./skill-resources.js";
6
+ export { createPrismMcpWebHandler, servePrismMcpStdio } from "./server.js";
7
+ export type {
8
+ CreatePrismMcpWebHandlerOptions,
9
+ PermissionCodec,
10
+ PermissionDecision,
11
+ PermissionRequest,
12
+ PrismMcpAuthorization,
13
+ PrismMcpAuthorizationInput,
14
+ PrismMcpAuthorizer,
15
+ PrismMcpRequestIdentity,
16
+ PrismMcpStdioHandle,
17
+ PrismMcpWebHandler,
18
+ ServeMcpHandle,
19
+ ServeMcpOptions,
20
+ ServePrismMcpStdioOptions,
21
+ ServeToolsHandle,
22
+ ServeToolsLimits,
23
+ ServeToolsOptions,
24
+ ServeToolsPermissionTool,
25
+ ServeToolsResource,
26
+ ServeToolsTransport,
27
+ } from "./types.js";