@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.
- package/CHANGELOG.md +394 -0
- package/LICENSE +21 -0
- package/README.md +34 -2
- package/acp/README.md +87 -0
- package/acp/src/capabilities.ts +184 -0
- package/acp/src/errors.ts +24 -0
- package/acp/src/host.ts +36 -0
- package/acp/src/index.ts +25 -0
- package/acp/src/limits.ts +49 -0
- package/acp/src/mapper.ts +419 -0
- package/acp/src/permission.ts +37 -0
- package/acp/src/projection.ts +39 -0
- package/acp/src/prompt.ts +170 -0
- package/acp/src/serve.ts +345 -0
- package/acp/src/session-map.ts +49 -0
- package/ag-ui/README.md +56 -0
- package/ag-ui/src/a2ui.ts +570 -0
- package/ag-ui/src/ag-ui-mapper.ts +507 -0
- package/ag-ui/src/encrypted-value.ts +40 -0
- package/ag-ui/src/errors.ts +29 -0
- package/ag-ui/src/handler.ts +642 -0
- package/ag-ui/src/index.ts +177 -0
- package/ag-ui/src/input.ts +190 -0
- package/ag-ui/src/limits.ts +279 -0
- package/ag-ui/src/mcp-apps.ts +256 -0
- package/ag-ui/src/mcp.ts +94 -0
- package/ag-ui/src/projection.ts +201 -0
- package/ag-ui/src/projectors.ts +272 -0
- package/ag-ui/src/renderer/bind.ts +152 -0
- package/ag-ui/src/renderer/core.ts +270 -0
- package/ag-ui/src/renderer/index.ts +165 -0
- package/ag-ui/src/replay.ts +189 -0
- package/ag-ui/src/types.ts +66 -0
- package/channels/README.md +139 -0
- package/channels/src/admission.ts +8 -0
- package/channels/src/approvals.ts +262 -0
- package/channels/src/checkpoint-contract.ts +97 -0
- package/channels/src/delivery.ts +116 -0
- package/channels/src/host-ui.ts +356 -0
- package/channels/src/identity.ts +46 -0
- package/channels/src/index.ts +82 -0
- package/channels/src/limits.ts +49 -0
- package/channels/src/memory-stores.ts +112 -0
- package/channels/src/pairing.ts +178 -0
- package/channels/src/runtime-admit.ts +389 -0
- package/channels/src/runtime-core.ts +621 -0
- package/channels/src/runtime-reconcile.ts +299 -0
- package/channels/src/runtime-turn.ts +664 -0
- package/channels/src/runtime-types.ts +95 -0
- package/channels/src/runtime.ts +86 -0
- package/channels/src/secret-ref.ts +42 -0
- package/channels/src/signal.ts +790 -0
- package/channels/src/state.ts +355 -0
- package/channels/src/telegram.ts +1317 -0
- package/channels/src/types.ts +442 -0
- package/devtools/README.md +92 -0
- package/devtools/bin/prism-devtools.ts +63 -0
- package/devtools/src/args.ts +71 -0
- package/devtools/src/bun.d.ts +27 -0
- package/devtools/src/compare.ts +190 -0
- package/devtools/src/errors.ts +15 -0
- package/devtools/src/index.ts +25 -0
- package/devtools/src/replay.ts +36 -0
- package/devtools/src/security.ts +80 -0
- package/devtools/src/serve.ts +259 -0
- package/devtools/src/ui/assets.ts +108 -0
- package/devtools/src/ui/inspector.ts +182 -0
- package/driver-process/README.md +197 -0
- package/driver-process/src/abort.ts +74 -0
- package/driver-process/src/adapter.ts +211 -0
- package/driver-process/src/driver.ts +303 -0
- package/driver-process/src/errors.ts +17 -0
- package/driver-process/src/extend.ts +72 -0
- package/driver-process/src/index.ts +5 -0
- package/driver-process/src/inspect.ts +33 -0
- package/driver-process/src/session.ts +72 -0
- package/driver-process/src/testing.ts +394 -0
- package/driver-process/src/transports/json-rpc.ts +147 -0
- package/driver-process/src/transports/jsonl-stream.ts +12 -0
- package/driver-process/src/transports/types.ts +11 -0
- package/driver-process/src/turn.ts +106 -0
- package/evals/README.md +843 -0
- package/evals/src/calibration.ts +179 -0
- package/evals/src/citation-integrity.ts +98 -0
- package/evals/src/citations.ts +45 -0
- package/evals/src/compare-experiments.ts +153 -0
- package/evals/src/comparison.ts +230 -0
- package/evals/src/curate.ts +257 -0
- package/evals/src/dataset.ts +81 -0
- package/evals/src/erp-invariants.ts +163 -0
- package/evals/src/errors.ts +23 -0
- package/evals/src/experiment.ts +537 -0
- package/evals/src/failure-injection.ts +77 -0
- package/evals/src/feedback.ts +53 -0
- package/evals/src/index.ts +198 -0
- package/evals/src/injection.ts +247 -0
- package/evals/src/judge-panel.ts +109 -0
- package/evals/src/judge.ts +89 -0
- package/evals/src/limits.ts +50 -0
- package/evals/src/report-record.ts +47 -0
- package/evals/src/rubric-judge.ts +334 -0
- package/evals/src/scenario-runner.ts +317 -0
- package/evals/src/scenarios.ts +81 -0
- package/evals/src/score.ts +328 -0
- package/evals/src/scorer.ts +21 -0
- package/evals/src/state-match.ts +130 -0
- package/evals/src/stats.ts +635 -0
- package/evals/src/threshold.ts +117 -0
- package/evals/src/timeline.ts +38 -0
- package/evals/src/toolless-session.ts +33 -0
- package/evals/src/trace.ts +80 -0
- package/evals/src/trajectory.ts +623 -0
- package/evals/src/types.ts +672 -0
- package/evals/src/user-simulator.ts +101 -0
- package/evals/src/util.ts +207 -0
- package/headless/README.md +172 -0
- package/headless/src/answers.ts +91 -0
- package/headless/src/authority.ts +32 -0
- package/headless/src/errors.ts +36 -0
- package/headless/src/index.ts +17 -0
- package/headless/src/limits.ts +11 -0
- package/headless/src/pending.ts +16 -0
- package/headless/src/policy.ts +36 -0
- package/headless/src/resume.ts +103 -0
- package/headless/src/route.ts +153 -0
- package/headless/src/scheduler/clock.ts +22 -0
- package/headless/src/scheduler/cron.ts +19 -0
- package/headless/src/scheduler/firing.ts +58 -0
- package/headless/src/scheduler/index.ts +399 -0
- package/headless/src/scheduler/lease.ts +38 -0
- package/headless/src/scheduler/missed.ts +12 -0
- package/headless/src/scheduler/state.ts +132 -0
- package/host-builder/README.md +251 -0
- package/host-builder/bin/prism-host-builder.ts +169 -0
- package/host-builder/data/api.json +6197 -0
- package/host-builder/data/errors.json +558 -0
- package/host-builder/data/examples/acp.ts +63 -0
- package/host-builder/data/examples/adapters/conformance.ts +34 -0
- package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
- package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
- package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
- package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
- package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
- package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
- package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
- package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
- package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
- package/host-builder/data/examples/advisor.ts +94 -0
- package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
- package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
- package/host-builder/data/examples/ag-ui-server.ts +118 -0
- package/host-builder/data/examples/agent-durable-approval.ts +43 -0
- package/host-builder/data/examples/api-key-auth.ts +23 -0
- package/host-builder/data/examples/approval.ts +92 -0
- package/host-builder/data/examples/attention-compiler.ts +81 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
- package/host-builder/data/examples/behavior-evaluation.ts +303 -0
- package/host-builder/data/examples/build-workflow.ts +334 -0
- package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
- package/host-builder/data/examples/caveman-ponytail.ts +197 -0
- package/host-builder/data/examples/cli.ts +31 -0
- package/host-builder/data/examples/coding-approval.ts +115 -0
- package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
- package/host-builder/data/examples/coding-compaction.ts +30 -0
- package/host-builder/data/examples/coding-goal-verify.ts +121 -0
- package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
- package/host-builder/data/examples/compaction.ts +36 -0
- package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
- package/host-builder/data/examples/context.ts +29 -0
- package/host-builder/data/examples/custom-adapter.ts +256 -0
- package/host-builder/data/examples/custom-builders.ts +66 -0
- package/host-builder/data/examples/custom-loop.ts +89 -0
- package/host-builder/data/examples/custom-provider.ts +70 -0
- package/host-builder/data/examples/custom-session-store.ts +72 -0
- package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
- package/host-builder/data/examples/decision-models.ts +98 -0
- package/host-builder/data/examples/define-package.ts +188 -0
- package/host-builder/data/examples/delegate.ts +200 -0
- package/host-builder/data/examples/discover-skills.ts +65 -0
- package/host-builder/data/examples/drive-rag-sync.ts +44 -0
- package/host-builder/data/examples/durable-approval.ts +139 -0
- package/host-builder/data/examples/durable-investigation.ts +93 -0
- package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
- package/host-builder/data/examples/enterprise-identity.ts +21 -0
- package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
- package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
- package/host-builder/data/examples/eval-injection.ts +73 -0
- package/host-builder/data/examples/eval-judges.ts +145 -0
- package/host-builder/data/examples/evals.ts +86 -0
- package/host-builder/data/examples/evaluation-gate.ts +40 -0
- package/host-builder/data/examples/execution-timeline.ts +173 -0
- package/host-builder/data/examples/external-agent.ts +541 -0
- package/host-builder/data/examples/external-app-db-backed.ts +344 -0
- package/host-builder/data/examples/governance-deny.ts +122 -0
- package/host-builder/data/examples/guardrail-packs.ts +240 -0
- package/host-builder/data/examples/headless-host.ts +245 -0
- package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
- package/host-builder/data/examples/hooks-json.ts +87 -0
- package/host-builder/data/examples/host-builder-agent.ts +150 -0
- package/host-builder/data/examples/host-hooks.ts +71 -0
- package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
- package/host-builder/data/examples/hosted-sandbox.ts +48 -0
- package/host-builder/data/examples/instruction-injection.ts +127 -0
- package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
- package/host-builder/data/examples/long-term-memory.ts +158 -0
- package/host-builder/data/examples/manifest.ts +112 -0
- package/host-builder/data/examples/mcp-server.ts +48 -0
- package/host-builder/data/examples/mcp-trust.ts +173 -0
- package/host-builder/data/examples/memory-and-wiki.ts +315 -0
- package/host-builder/data/examples/memory-lifecycle.ts +302 -0
- package/host-builder/data/examples/memory-system.ts +255 -0
- package/host-builder/data/examples/messaging-agent.ts +70 -0
- package/host-builder/data/examples/minimal-host-app.ts +41 -0
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
- package/host-builder/data/examples/model-router.ts +106 -0
- package/host-builder/data/examples/obscura.ts +48 -0
- package/host-builder/data/examples/observability.ts +116 -0
- package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
- package/host-builder/data/examples/openai-compatible.ts +70 -0
- package/host-builder/data/examples/package-skills.ts +85 -0
- package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
- package/host-builder/data/examples/provider-registration.ts +29 -0
- package/host-builder/data/examples/provider-resolver.ts +39 -0
- package/host-builder/data/examples/rag.ts +40 -0
- package/host-builder/data/examples/remote-agent-server.ts +45 -0
- package/host-builder/data/examples/remote-agent.ts +124 -0
- package/host-builder/data/examples/research-ledger.ts +79 -0
- package/host-builder/data/examples/revocation-propagation.ts +287 -0
- package/host-builder/data/examples/run-feedback.ts +93 -0
- package/host-builder/data/examples/scanned-document-rag.ts +48 -0
- package/host-builder/data/examples/sdk-basics.ts +21 -0
- package/host-builder/data/examples/secure-agent.ts +55 -0
- package/host-builder/data/examples/semantic-memory.ts +52 -0
- package/host-builder/data/examples/serve-tools.ts +495 -0
- package/host-builder/data/examples/session-memory.ts +318 -0
- package/host-builder/data/examples/session-search.ts +131 -0
- package/host-builder/data/examples/session.ts +52 -0
- package/host-builder/data/examples/side-call.ts +68 -0
- package/host-builder/data/examples/signal-agent.ts +9 -0
- package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
- package/host-builder/data/examples/skills.ts +19 -0
- package/host-builder/data/examples/sqlite-resume.ts +147 -0
- package/host-builder/data/examples/system-project-prompts.ts +74 -0
- package/host-builder/data/examples/system-prompts.ts +19 -0
- package/host-builder/data/examples/telegram-agent.ts +30 -0
- package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
- package/host-builder/data/examples/tools.ts +29 -0
- package/host-builder/data/examples/validator.ts +67 -0
- package/host-builder/data/examples/web-no-key.ts +85 -0
- package/host-builder/data/examples/web-research.ts +35 -0
- package/host-builder/data/examples/workflow-event-sink.ts +114 -0
- package/host-builder/data/examples/workflow-loop.ts +93 -0
- package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
- package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
- package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
- package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
- package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
- package/host-builder/data/examples.json +130 -0
- package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
- package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
- package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
- package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
- package/host-builder/skills/prism-host-builder/references/security.md +52 -0
- package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
- package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
- package/host-builder/src/check/child.ts +108 -0
- package/host-builder/src/check/conformance.ts +13 -0
- package/host-builder/src/check/inspect.ts +20 -0
- package/host-builder/src/check/manifest.ts +23 -0
- package/host-builder/src/check/runner.ts +181 -0
- package/host-builder/src/check/targets.ts +65 -0
- package/host-builder/src/errors.ts +35 -0
- package/host-builder/src/index.ts +25 -0
- package/host-builder/src/indexes.ts +145 -0
- package/host-builder/src/install/install.ts +400 -0
- package/host-builder/src/install/targets.ts +50 -0
- package/host-builder/src/lookup/api.ts +127 -0
- package/host-builder/src/lookup/bound.ts +38 -0
- package/host-builder/src/lookup/docs.ts +238 -0
- package/host-builder/src/lookup/errors.ts +92 -0
- package/host-builder/src/lookup/examples.ts +117 -0
- package/host-builder/src/lookup/text.ts +60 -0
- package/host-builder/src/server.ts +300 -0
- package/host-builder/src/version.ts +38 -0
- package/mcp-server/README.md +219 -0
- package/mcp-server/src/bounds.ts +23 -0
- package/mcp-server/src/host.ts +31 -0
- package/mcp-server/src/index.ts +27 -0
- package/mcp-server/src/serve-tools.ts +408 -0
- package/mcp-server/src/serve.ts +329 -0
- package/mcp-server/src/server.ts +331 -0
- package/mcp-server/src/session-map.ts +47 -0
- package/mcp-server/src/skill-resources.ts +85 -0
- package/mcp-server/src/types.ts +215 -0
- package/package.json +130 -4
- package/remote/README.md +244 -0
- package/remote/src/attribution.ts +22 -0
- package/remote/src/auth.ts +30 -0
- package/remote/src/bun-module.d.ts +34 -0
- package/remote/src/channel.ts +86 -0
- package/remote/src/connect.ts +212 -0
- package/remote/src/dispatcher.ts +282 -0
- package/remote/src/errors.ts +59 -0
- package/remote/src/host-ui.ts +152 -0
- package/remote/src/http-gate.ts +43 -0
- package/remote/src/index.ts +53 -0
- package/remote/src/jsonl.ts +69 -0
- package/remote/src/limits.ts +43 -0
- package/remote/src/mirror.ts +90 -0
- package/remote/src/pending.ts +22 -0
- package/remote/src/protocol.ts +107 -0
- package/remote/src/serve.ts +560 -0
- package/remote/src/session-proxy.ts +219 -0
- package/remote/src/sse.ts +38 -0
- package/remote/src/stdio-client.ts +41 -0
- package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
- package/remote/src/testing.ts +230 -0
- package/remote/src/transport.ts +139 -0
- package/remote/src/transports/client.ts +126 -0
- package/remote/src/transports/network.ts +268 -0
- package/remote/src/wire.ts +244 -0
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { Agent, ApprovalOutcome, Decision, JsonObject, Message, PendingDecision, RunResult, Session } from "@arnilo/prism";
|
|
3
|
+
import { McpBridgeError } from "@arnilo/prism-extensions/mcp";
|
|
4
|
+
import {
|
|
5
|
+
acceptedContent,
|
|
6
|
+
type CallToolResult,
|
|
7
|
+
CLIENT_CAPABILITIES_META_KEY,
|
|
8
|
+
type ClientCapabilities,
|
|
9
|
+
type ElicitRequestFormParams,
|
|
10
|
+
type InputRequest,
|
|
11
|
+
type InputRequiredResult,
|
|
12
|
+
inputRequired,
|
|
13
|
+
type McpRequestContext,
|
|
14
|
+
McpServer,
|
|
15
|
+
type ServerContext,
|
|
16
|
+
type Transport,
|
|
17
|
+
} from "@modelcontextprotocol/server";
|
|
18
|
+
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
|
19
|
+
import * as z from "zod/v4";
|
|
20
|
+
import manifest from "../../package.json" with { type: "json" };
|
|
21
|
+
import { bounded, truncateUtf8 } from "./bounds.js";
|
|
22
|
+
import { createPrismMcpWebHandler, servePrismMcpStdio } from "./server.js";
|
|
23
|
+
import { bindMcpSession, type ElicitRequest, type ElicitResult, isMcpHost, unbindMcpSession } from "./session-map.js";
|
|
24
|
+
import type { PrismMcpAuthorization, ServeMcpHandle, ServeMcpOptions } from "./types.js";
|
|
25
|
+
|
|
26
|
+
const DEFAULT_TOOL_NAME = "prompt";
|
|
27
|
+
const DEFAULT_MAX_PROMPT_BYTES = 64 * 1024;
|
|
28
|
+
const HARD_MAX_PROMPT_BYTES = 1024 * 1024;
|
|
29
|
+
const DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;
|
|
30
|
+
const HARD_MAX_RESULT_BYTES = 8 * 1024 * 1024;
|
|
31
|
+
const APPROVAL_OUTCOMES: readonly ApprovalOutcome[] = ["allow_once", "allow_for_run", "reject_once", "reject_for_run"];
|
|
32
|
+
const APPROVAL_SCHEMA: ElicitRequestFormParams["requestedSchema"] = {
|
|
33
|
+
type: "object",
|
|
34
|
+
properties: { outcome: { type: "string", enum: [...APPROVAL_OUTCOMES] } },
|
|
35
|
+
required: ["outcome"],
|
|
36
|
+
additionalProperties: false,
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Serve an existing agent over MCP. One tool (`options.toolName`, default `prompt`) runs
|
|
41
|
+
* `session.run(prompt)` on the session bound to the MCP session id; `agent.commands` are
|
|
42
|
+
* listed as MCP prompts. Approvals suspend (`interactive: false`) and resume through the
|
|
43
|
+
* tool result's `input_required` round trip when the client advertised `elicitation.form`.
|
|
44
|
+
* Tool serving is `serveTools` (Phase 14): it bridges a `ToolDefinition[]` onto the run's
|
|
45
|
+
* `tool.call` gate. This server runs the agent, never a bare tool.
|
|
46
|
+
*/
|
|
47
|
+
export function serveMcp(agent: Agent, options: ServeMcpOptions): ServeMcpHandle {
|
|
48
|
+
const transports = [options.stdio === true, options.transport !== undefined, options.http !== undefined].filter(Boolean).length;
|
|
49
|
+
if (transports !== 1) throw new McpBridgeError("serveMcp takes exactly one of { stdio: true }, { transport }, or { http }");
|
|
50
|
+
const toolName = options.toolName ?? DEFAULT_TOOL_NAME;
|
|
51
|
+
if (!toolName) throw new McpBridgeError("toolName must be non-empty");
|
|
52
|
+
const maxPromptBytes = bounded(options.maxPromptBytes, DEFAULT_MAX_PROMPT_BYTES, HARD_MAX_PROMPT_BYTES, "maxPromptBytes");
|
|
53
|
+
const maxResultBytes = bounded(options.maxResultBytes, DEFAULT_MAX_RESULT_BYTES, HARD_MAX_RESULT_BYTES, "maxResultBytes");
|
|
54
|
+
const redactor = options.redactor ?? agent.config.redactor;
|
|
55
|
+
const host = isMcpHost(agent.config.host) ? agent.config.host : undefined;
|
|
56
|
+
const sessions = new Map<string, Session>();
|
|
57
|
+
const pending = new Map<string, readonly PendingDecision[]>();
|
|
58
|
+
let resolveClosed!: () => void;
|
|
59
|
+
const closed = new Promise<void>((resolve) => {
|
|
60
|
+
resolveClosed = resolve;
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
const factory = (request: McpRequestContext): McpServer => {
|
|
64
|
+
const instanceId = `mcp-${randomUUID()}`;
|
|
65
|
+
const server = new McpServer(
|
|
66
|
+
{ name: options.serverName ?? "prism-mcp-server", version: options.serverVersion ?? manifest.version },
|
|
67
|
+
{ capabilities: { tools: {}, prompts: {} } },
|
|
68
|
+
);
|
|
69
|
+
server.registerTool(
|
|
70
|
+
toolName,
|
|
71
|
+
{ description: "Run the Prism agent and return its final text.", inputSchema: z.object({ prompt: z.string() }) },
|
|
72
|
+
(args, ctx) => runTool(args.prompt, ctx, server, instanceId, request.era),
|
|
73
|
+
);
|
|
74
|
+
for (const command of agent.commands.list()) {
|
|
75
|
+
server.registerPrompt(
|
|
76
|
+
command.name,
|
|
77
|
+
{ description: command.description, argsSchema: z.record(z.string(), z.string()).default({}) },
|
|
78
|
+
async (args, ctx) => {
|
|
79
|
+
const name = command.name;
|
|
80
|
+
if (!(await authorize("prompt", name, jsonObject(args), ctx))) throw new McpBridgeError("ERR_PRISM_MCP_FORBIDDEN: Forbidden");
|
|
81
|
+
const session = await sessionFor(sessionKey(ctx, instanceId), ctx);
|
|
82
|
+
const result = await agent.commands.run(name, jsonObject(args), { session });
|
|
83
|
+
return { messages: [{ role: "user" as const, content: { type: "text" as const, text: clip(stringify(result)) } }] };
|
|
84
|
+
},
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
return server;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
if (options.http) {
|
|
91
|
+
let ready: Promise<Awaited<ReturnType<typeof createPrismMcpWebHandler>>> | undefined;
|
|
92
|
+
const init = () => (ready ??= createPrismMcpWebHandler(factory, options.http));
|
|
93
|
+
return {
|
|
94
|
+
closed,
|
|
95
|
+
close: async () => {
|
|
96
|
+
await (await init()).close();
|
|
97
|
+
resolveClosed();
|
|
98
|
+
},
|
|
99
|
+
handler: (request) => init().then((web) => web(request)),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
const wire = options.stdio === true ? new StdioServerTransport() : (options.transport as Transport);
|
|
103
|
+
const stdio = servePrismMcpStdio(factory, { transport: wire });
|
|
104
|
+
const upstream = wire.onclose;
|
|
105
|
+
wire.onclose = () => {
|
|
106
|
+
upstream?.();
|
|
107
|
+
resolveClosed();
|
|
108
|
+
};
|
|
109
|
+
return {
|
|
110
|
+
closed,
|
|
111
|
+
close: async () => {
|
|
112
|
+
for (const id of sessions.keys()) unbindMcpSession(host, id);
|
|
113
|
+
sessions.clear();
|
|
114
|
+
pending.clear();
|
|
115
|
+
await stdio.close();
|
|
116
|
+
resolveClosed();
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
async function runTool(
|
|
121
|
+
prompt: unknown,
|
|
122
|
+
ctx: ServerContext,
|
|
123
|
+
server: McpServer,
|
|
124
|
+
instanceId: string,
|
|
125
|
+
era: "legacy" | "modern",
|
|
126
|
+
): Promise<CallToolResult | InputRequiredResult> {
|
|
127
|
+
if (!(await authorize("tool", toolName, { prompt: typeof prompt === "string" ? prompt : "" }, ctx)))
|
|
128
|
+
return errorResult("Forbidden", "ERR_PRISM_MCP_FORBIDDEN");
|
|
129
|
+
if (typeof prompt !== "string" || prompt.length === 0 || Buffer.byteLength(prompt, "utf8") > maxPromptBytes)
|
|
130
|
+
return errorResult(`prompt must be a non-empty string <= ${maxPromptBytes} bytes`, "ERR_PRISM_MCP_INPUT");
|
|
131
|
+
const key = sessionKey(ctx, instanceId);
|
|
132
|
+
const stored = pending.get(key);
|
|
133
|
+
const responses = ctx.mcpReq.inputResponses;
|
|
134
|
+
if (responses !== undefined && Object.keys(responses).length > 0) {
|
|
135
|
+
// A retry without a matching pending decision (a new server instance on a
|
|
136
|
+
// stateless transport) must never re-run the prompt: fail closed.
|
|
137
|
+
if (!stored) return errorResult("Approval cannot be resumed on this MCP session", "ERR_PRISM_MCP_APPROVAL_REQUIRED");
|
|
138
|
+
pending.delete(key);
|
|
139
|
+
const decisions = decisionsFor(stored, responses);
|
|
140
|
+
return settleStream(await sessionFor(key, ctx), ctx, server, key, decisions);
|
|
141
|
+
}
|
|
142
|
+
const session = await sessionFor(key, ctx);
|
|
143
|
+
if (host) {
|
|
144
|
+
bindMcpSession(host, session.id, {
|
|
145
|
+
elicitation: era === "legacy" && elicitationAvailable(server, ctx),
|
|
146
|
+
elicit: (request) => elicit(ctx, request),
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
const result = await session.run(prompt, { interactive: false, signal: ctx.mcpReq.signal });
|
|
151
|
+
return settleResult(result, ctx, server, key);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
return errorResult(clip(errorMessage(error)), "ERR_PRISM_MCP_RUN");
|
|
154
|
+
} finally {
|
|
155
|
+
unbindMcpSession(host, session.id);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function settleStream(
|
|
160
|
+
session: Session,
|
|
161
|
+
ctx: ServerContext,
|
|
162
|
+
server: McpServer,
|
|
163
|
+
key: string,
|
|
164
|
+
decisions: readonly Decision[],
|
|
165
|
+
): Promise<CallToolResult | InputRequiredResult> {
|
|
166
|
+
let text = "";
|
|
167
|
+
let failed: string | undefined;
|
|
168
|
+
let suspended: readonly PendingDecision[] | undefined;
|
|
169
|
+
try {
|
|
170
|
+
for await (const event of session.resume(decisions, { interactive: false, signal: ctx.mcpReq.signal })) {
|
|
171
|
+
if (event.type === "message.completed") text = textOf(event.message);
|
|
172
|
+
else if (event.type === "run.failed") failed = event.error.message;
|
|
173
|
+
else if (event.type === "run.suspended") suspended = event.interruption.pendingDecisions ?? [];
|
|
174
|
+
}
|
|
175
|
+
} catch (error) {
|
|
176
|
+
return errorResult(clip(errorMessage(error)), "ERR_PRISM_MCP_RUN");
|
|
177
|
+
}
|
|
178
|
+
if (failed !== undefined) return errorResult(clip(failed), "ERR_PRISM_MCP_RUN");
|
|
179
|
+
if (suspended) return suspend(suspended, ctx, server, key);
|
|
180
|
+
return textResult(clip(text));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function settleResult(result: RunResult, ctx: ServerContext, server: McpServer, key: string): CallToolResult | InputRequiredResult {
|
|
184
|
+
if (result.status === "failed") return errorResult(clip(result.error?.message ?? "Run failed"), "ERR_PRISM_MCP_RUN");
|
|
185
|
+
if (result.status === "aborted") return errorResult(clip(result.abortReason ?? "Run aborted"), "ERR_PRISM_MCP_ABORTED");
|
|
186
|
+
if (result.status === "suspended") return suspend(result.pending ?? [], ctx, server, key);
|
|
187
|
+
return textResult(clip(result.text));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function suspend(
|
|
191
|
+
decisions: readonly PendingDecision[],
|
|
192
|
+
ctx: ServerContext,
|
|
193
|
+
server: McpServer,
|
|
194
|
+
key: string,
|
|
195
|
+
): CallToolResult | InputRequiredResult {
|
|
196
|
+
if (decisions.length === 0) return errorResult("Run suspended without a pending decision", "ERR_PRISM_MCP_APPROVAL_REQUIRED");
|
|
197
|
+
if (!elicitationAvailable(server, ctx))
|
|
198
|
+
return errorResult(`Approval required: ${decisions.map(approvalLabel).join(", ")}`, "ERR_PRISM_MCP_APPROVAL_REQUIRED");
|
|
199
|
+
pending.set(key, decisions);
|
|
200
|
+
const inputRequests: Record<string, InputRequest> = {};
|
|
201
|
+
for (const decision of decisions) {
|
|
202
|
+
inputRequests[decision.approvalId] = inputRequired.elicit({
|
|
203
|
+
message: `Approve ${approvalLabel(decision)}?`,
|
|
204
|
+
requestedSchema: APPROVAL_SCHEMA,
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
return inputRequired({ inputRequests });
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function authorize(kind: "tool" | "prompt", name: string, args: JsonObject, ctx: ServerContext): Promise<boolean> {
|
|
211
|
+
if (!options.authorize) return true;
|
|
212
|
+
let decision: false | PrismMcpAuthorization;
|
|
213
|
+
try {
|
|
214
|
+
decision = await options.authorize({
|
|
215
|
+
kind,
|
|
216
|
+
name,
|
|
217
|
+
arguments: args,
|
|
218
|
+
authInfo: ctx.http?.authInfo,
|
|
219
|
+
sessionId: ctx.sessionId,
|
|
220
|
+
signal: ctx.mcpReq.signal,
|
|
221
|
+
});
|
|
222
|
+
} catch {
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
return decision !== false;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function sessionFor(key: string, ctx: ServerContext): Promise<Session> {
|
|
229
|
+
const existing = sessions.get(key);
|
|
230
|
+
if (existing) return existing;
|
|
231
|
+
const session = ctx.sessionId ? await agent.session({ id: key, create: true }) : await agent.session();
|
|
232
|
+
sessions.set(key, session);
|
|
233
|
+
return session;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function clip(value: string): string {
|
|
237
|
+
const redacted = redactor?.redact(value) ?? value;
|
|
238
|
+
return truncateUtf8(redacted, maxResultBytes);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function textResult(text: string): CallToolResult {
|
|
242
|
+
return { content: [{ type: "text", text }] };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function errorResult(message: string, code: string): CallToolResult {
|
|
246
|
+
return { isError: true, content: [{ type: "text", text: truncateUtf8(`${code}: ${message}`, maxResultBytes) }] };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function sessionKey(ctx: ServerContext, instanceId: string): string {
|
|
251
|
+
return ctx.sessionId ?? instanceId;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function elicitationAvailable(server: McpServer, ctx: ServerContext): boolean {
|
|
255
|
+
const envelope = ctx.mcpReq.envelope as Record<string, unknown> | undefined;
|
|
256
|
+
const capabilities = (envelope?.[CLIENT_CAPABILITIES_META_KEY] ?? server.server.getClientCapabilities()) as
|
|
257
|
+
| ClientCapabilities
|
|
258
|
+
| undefined;
|
|
259
|
+
return capabilities?.elicitation?.form !== undefined;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async function elicit(ctx: ServerContext, request: ElicitRequest): Promise<ElicitResult> {
|
|
263
|
+
const requestedSchema: ElicitRequestFormParams["requestedSchema"] =
|
|
264
|
+
request.kind === "confirm"
|
|
265
|
+
? { type: "object", properties: { approved: { type: "boolean" } }, required: ["approved"] }
|
|
266
|
+
: request.kind === "select"
|
|
267
|
+
? {
|
|
268
|
+
type: "object",
|
|
269
|
+
properties: { value: { type: "string", enum: (request.options ?? []).map((option) => option.value) } },
|
|
270
|
+
required: ["value"],
|
|
271
|
+
}
|
|
272
|
+
: { type: "object", properties: { value: { type: "string" } }, required: ["value"] };
|
|
273
|
+
try {
|
|
274
|
+
const response = await ctx.mcpReq.elicitInput({
|
|
275
|
+
message: request.detail ? `${request.title}\n${request.detail}` : request.title,
|
|
276
|
+
requestedSchema,
|
|
277
|
+
});
|
|
278
|
+
if (response.action !== "accept") return { status: "dismissed" };
|
|
279
|
+
const content = response.content;
|
|
280
|
+
if (request.kind === "confirm") {
|
|
281
|
+
const approved = content && typeof content === "object" && "approved" in content ? content.approved === true : false;
|
|
282
|
+
return approved ? { status: "answered", value: true } : { status: "dismissed" };
|
|
283
|
+
}
|
|
284
|
+
const value = content && typeof content === "object" && "value" in content ? content.value : undefined;
|
|
285
|
+
return typeof value === "string" ? { status: "answered", value } : { status: "dismissed" };
|
|
286
|
+
} catch {
|
|
287
|
+
return { status: "unavailable" };
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function decisionsFor(stored: readonly PendingDecision[], responses: Record<string, unknown>): Decision[] {
|
|
292
|
+
return stored.map((decision) => {
|
|
293
|
+
const content = acceptedContent<{ outcome?: unknown }>(responses, decision.approvalId);
|
|
294
|
+
const outcome = content?.outcome;
|
|
295
|
+
return { approvalId: decision.approvalId, outcome: isApprovalOutcome(outcome) ? outcome : "reject_once" };
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function isApprovalOutcome(value: unknown): value is ApprovalOutcome {
|
|
300
|
+
return typeof value === "string" && (APPROVAL_OUTCOMES as readonly string[]).includes(value);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function approvalLabel(decision: PendingDecision): string {
|
|
304
|
+
return decision.scope.toolName ?? decision.kind;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function textOf(message: Message): string {
|
|
308
|
+
return message.content
|
|
309
|
+
.filter((block) => block.type === "text")
|
|
310
|
+
.map((block) => block.text)
|
|
311
|
+
.join("");
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function jsonObject(value: unknown): JsonObject {
|
|
315
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
316
|
+
return value as JsonObject;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function stringify(value: unknown): string {
|
|
320
|
+
try {
|
|
321
|
+
return JSON.stringify(value) ?? "null";
|
|
322
|
+
} catch {
|
|
323
|
+
return "[unserializable result]";
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function errorMessage(error: unknown): string {
|
|
328
|
+
return error instanceof Error ? error.message : String(error);
|
|
329
|
+
}
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
McpBridgeError,
|
|
4
|
+
normalizeProtectedResource,
|
|
5
|
+
protectedResourceMetadata,
|
|
6
|
+
unauthorizedResponse,
|
|
7
|
+
WELL_KNOWN_OAUTH_PROTECTED_RESOURCE,
|
|
8
|
+
} from "@arnilo/prism-extensions/mcp";
|
|
9
|
+
import type { McpServerFactory } from "@modelcontextprotocol/server";
|
|
10
|
+
import {
|
|
11
|
+
createMcpHandler,
|
|
12
|
+
InMemoryServerEventBus,
|
|
13
|
+
isLegacyRequest,
|
|
14
|
+
McpServer,
|
|
15
|
+
WebStandardStreamableHTTPServerTransport,
|
|
16
|
+
} from "@modelcontextprotocol/server";
|
|
17
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
18
|
+
import { bounded } from "./bounds.js";
|
|
19
|
+
import type { CreatePrismMcpWebHandlerOptions, PrismMcpStdioHandle, PrismMcpWebHandler, ServePrismMcpStdioOptions } from "./types.js";
|
|
20
|
+
|
|
21
|
+
const DEFAULT_MAX_HTTP_REQUEST_BYTES = 1024 * 1024;
|
|
22
|
+
const HARD_MAX_HTTP_REQUEST_BYTES = 8 * 1024 * 1024;
|
|
23
|
+
const DEFAULT_MAX_HTTP_RESPONSE_BYTES = 2 * 1024 * 1024;
|
|
24
|
+
const HARD_MAX_HTTP_RESPONSE_BYTES = 16 * 1024 * 1024;
|
|
25
|
+
const DEFAULT_SERVER_CALL_TIMEOUT_MS = 60_000;
|
|
26
|
+
const HARD_SERVER_CALL_TIMEOUT_MS = 30 * 60_000;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Dual-era web handler. Modern (2026-07-28) traffic is served by the SDK's
|
|
30
|
+
* `createMcpHandler` — one fresh McpServer per request from the factory, with
|
|
31
|
+
* `server/discover`, result metadata, cancellation and modern headers all
|
|
32
|
+
* SDK-generated. With `sessionIdGenerator` configured, classified legacy
|
|
33
|
+
* session traffic (2025-era) routes to a sessionful
|
|
34
|
+
* `WebStandardStreamableHTTPServerTransport` beside a strict modern handler;
|
|
35
|
+
* without sessions the SDK's stateless legacy fallback serves 2025 traffic.
|
|
36
|
+
* Host/origin validation, auth, identity binding, bounded body parsing and
|
|
37
|
+
* response bounding all run in front of the SDK entries because
|
|
38
|
+
* `createMcpHandler` intentionally provides none of them.
|
|
39
|
+
*/
|
|
40
|
+
export async function createPrismMcpWebHandler(
|
|
41
|
+
server: McpServer | McpServerFactory,
|
|
42
|
+
options: CreatePrismMcpWebHandlerOptions = {},
|
|
43
|
+
): Promise<PrismMcpWebHandler> {
|
|
44
|
+
const createServer: McpServerFactory = typeof server === "function" ? server : () => server;
|
|
45
|
+
const maxRequestBytes = bounded(options.maxRequestBytes, DEFAULT_MAX_HTTP_REQUEST_BYTES, HARD_MAX_HTTP_REQUEST_BYTES, "maxRequestBytes");
|
|
46
|
+
const maxResponseBytes = bounded(
|
|
47
|
+
options.maxResponseBytes,
|
|
48
|
+
DEFAULT_MAX_HTTP_RESPONSE_BYTES,
|
|
49
|
+
HARD_MAX_HTTP_RESPONSE_BYTES,
|
|
50
|
+
"maxResponseBytes",
|
|
51
|
+
);
|
|
52
|
+
const maxConcurrentRequests = bounded(options.maxConcurrentRequests, 32, 512, "maxConcurrentRequests");
|
|
53
|
+
const requestTimeoutMs = bounded(
|
|
54
|
+
options.requestTimeoutMs,
|
|
55
|
+
DEFAULT_SERVER_CALL_TIMEOUT_MS,
|
|
56
|
+
HARD_SERVER_CALL_TIMEOUT_MS,
|
|
57
|
+
"requestTimeoutMs",
|
|
58
|
+
);
|
|
59
|
+
const stateful = options.sessionIdGenerator !== undefined;
|
|
60
|
+
if (stateful && (!options.resolveIdentity || !options.allowedOrigins?.length))
|
|
61
|
+
throw new McpBridgeError("Stateful MCP sessions require resolveIdentity and exact allowedOrigins");
|
|
62
|
+
const protectedResource = options.protectedResource === undefined ? undefined : normalizeProtectedResource(options.protectedResource);
|
|
63
|
+
const maxSessions = bounded(options.maxSessions, 32, 512, "maxSessions");
|
|
64
|
+
const sessions = new Map<string, string>();
|
|
65
|
+
const maxSubscriptions = bounded(options.maxSubscriptions, 1024, 4096, "maxSubscriptions");
|
|
66
|
+
if (
|
|
67
|
+
options.keepAliveMs !== undefined &&
|
|
68
|
+
(!Number.isSafeInteger(options.keepAliveMs) || options.keepAliveMs < 0 || options.keepAliveMs > 300_000)
|
|
69
|
+
)
|
|
70
|
+
throw new McpBridgeError("keepAliveMs must be a safe integer between 0 and 300000");
|
|
71
|
+
// Stateless (and modern-beside-legacy) serving needs a factory: one fresh
|
|
72
|
+
// McpServer per request. A bare McpServer instance can only serve the
|
|
73
|
+
// legacy session path (documented legacy-only).
|
|
74
|
+
if (!stateful && typeof server !== "function") {
|
|
75
|
+
throw new McpBridgeError(
|
|
76
|
+
"Stateless MCP web handlers require a server factory (() => McpServer): serving is one fresh McpServer per request",
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
const modern =
|
|
80
|
+
typeof server === "function"
|
|
81
|
+
? createMcpHandler((ctx) => createServer(ctx), { legacy: stateful ? "reject" : "stateless", maxSubscriptions })
|
|
82
|
+
: undefined;
|
|
83
|
+
|
|
84
|
+
// Legacy session leg: shared transport + shared server (2025-era only).
|
|
85
|
+
const sharedTransport = stateful
|
|
86
|
+
? new WebStandardStreamableHTTPServerTransport({
|
|
87
|
+
sessionIdGenerator: () => {
|
|
88
|
+
if (sessions.size >= maxSessions) throw new McpBridgeError("ERR_PRISM_MCP_SESSION_LIMIT: MCP session limit reached");
|
|
89
|
+
const id = options.sessionIdGenerator?.() ?? randomUUID();
|
|
90
|
+
if (!validCapabilityId(id) || sessions.has(id)) throw new McpBridgeError("Invalid or duplicate MCP session id");
|
|
91
|
+
return id;
|
|
92
|
+
},
|
|
93
|
+
enableJsonResponse: true,
|
|
94
|
+
})
|
|
95
|
+
: undefined;
|
|
96
|
+
const sharedMcpServer = stateful ? ((await createServer({ era: "legacy" })) as McpServer) : undefined;
|
|
97
|
+
if (sharedMcpServer && sharedTransport) await sharedMcpServer.connect(sharedTransport);
|
|
98
|
+
let activeRequests = 0;
|
|
99
|
+
|
|
100
|
+
async function close(): Promise<void> {
|
|
101
|
+
await modern?.close();
|
|
102
|
+
await sharedTransport?.close();
|
|
103
|
+
await sharedMcpServer?.close();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Legacy-only handlers (bare McpServer instance with sessions) publish
|
|
107
|
+
// change notifications through the shared server; the bus stays a local
|
|
108
|
+
// default because nothing subscribes to it without a modern leg.
|
|
109
|
+
const legacyNotifier = {
|
|
110
|
+
toolsChanged: () => void sharedMcpServer?.sendToolListChanged(),
|
|
111
|
+
promptsChanged: () => void sharedMcpServer?.sendPromptListChanged(),
|
|
112
|
+
resourcesChanged: () => void sharedMcpServer?.sendResourceListChanged(),
|
|
113
|
+
resourceUpdated: (uri: string) => void sharedMcpServer?.server.sendResourceUpdated({ uri }),
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const handler = async (request: Request): Promise<Response> => {
|
|
117
|
+
if (activeRequests >= maxConcurrentRequests) return httpError(429, "MCP server is busy");
|
|
118
|
+
activeRequests += 1;
|
|
119
|
+
const controller = linkedController(request.signal);
|
|
120
|
+
const timeout = setTimeout(() => controller.controller.abort(new Error("MCP HTTP request timed out")), requestTimeoutMs);
|
|
121
|
+
try {
|
|
122
|
+
// Host/origin validation runs before parsing, auth, and dispatch —
|
|
123
|
+
// the SDK serving entries intentionally perform none.
|
|
124
|
+
const rejected = hostOriginRejection(request, options);
|
|
125
|
+
if (rejected) return rejected;
|
|
126
|
+
if (protectedResource) {
|
|
127
|
+
const pathname = new URL(request.url).pathname;
|
|
128
|
+
if (pathname === WELL_KNOWN_OAUTH_PROTECTED_RESOURCE) {
|
|
129
|
+
if (request.method !== "GET") return httpError(405, "Method not allowed");
|
|
130
|
+
return Response.json(protectedResourceMetadata(protectedResource), {
|
|
131
|
+
headers: { "content-type": "application/json", "cache-control": "no-store" },
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const authInfo = await awaitWithSignal(Promise.resolve(options.resolveAuthInfo?.(request)), controller.signal);
|
|
136
|
+
const identity = options.resolveIdentity
|
|
137
|
+
? await awaitWithSignal(Promise.resolve(options.resolveIdentity(request, authInfo)), controller.signal)
|
|
138
|
+
: undefined;
|
|
139
|
+
if (options.resolveIdentity && !identity) return unauthorizedResponse(protectedResource, request);
|
|
140
|
+
const identityId = identity ? identity.id : undefined;
|
|
141
|
+
if (identityId !== undefined && (!validCapabilityId(identityId) || Buffer.byteLength(identityId, "utf8") > 256))
|
|
142
|
+
return unauthorizedResponse(protectedResource, request);
|
|
143
|
+
const requestedSession = request.headers.get("mcp-session-id") ?? undefined;
|
|
144
|
+
if (requestedSession && sessions.get(requestedSession) !== identityId) return httpError(404, "MCP session not found");
|
|
145
|
+
// Bounded body parsing; the raw bytes feed the rebuilt request and the
|
|
146
|
+
// parsed value is handed to the era classifier and serving legs so
|
|
147
|
+
// nothing re-reads the stream.
|
|
148
|
+
const boundedBody = request.method === "POST" ? await readBoundedBody(request, maxRequestBytes, controller.signal) : undefined;
|
|
149
|
+
const transportRequest = new Request(request.url, {
|
|
150
|
+
method: request.method,
|
|
151
|
+
headers: request.headers,
|
|
152
|
+
signal: controller.signal,
|
|
153
|
+
...(boundedBody ? { body: boundedBody.bytes } : {}),
|
|
154
|
+
});
|
|
155
|
+
let response: Response;
|
|
156
|
+
if (modern && (!stateful || !(await isLegacyRequest(transportRequest, boundedBody?.parsed)))) {
|
|
157
|
+
response = await awaitWithSignal(modern.fetch(transportRequest, { parsedBody: boundedBody?.parsed, authInfo }), controller.signal);
|
|
158
|
+
} else {
|
|
159
|
+
if (!sharedTransport) throw new McpBridgeError("Stateful MCP transport is not configured");
|
|
160
|
+
response = await awaitWithSignal(
|
|
161
|
+
sharedTransport.handleRequest(transportRequest, { parsedBody: boundedBody?.parsed, authInfo }),
|
|
162
|
+
controller.signal,
|
|
163
|
+
);
|
|
164
|
+
const createdSession = response.headers.get("mcp-session-id") ?? undefined;
|
|
165
|
+
if (createdSession && identityId) {
|
|
166
|
+
const existing = sessions.get(createdSession);
|
|
167
|
+
if (existing && existing !== identityId) return httpError(404, "MCP session not found");
|
|
168
|
+
sessions.set(createdSession, identityId);
|
|
169
|
+
}
|
|
170
|
+
if (request.method === "DELETE" && requestedSession && response.status < 400) sessions.delete(requestedSession);
|
|
171
|
+
}
|
|
172
|
+
return await boundResponse(response, maxResponseBytes);
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (error instanceof McpHttpError) return httpError(error.status, error.message);
|
|
175
|
+
return httpError(controller.signal.aborted ? 408 : 500, controller.signal.aborted ? "MCP request timed out" : "MCP request failed");
|
|
176
|
+
} finally {
|
|
177
|
+
clearTimeout(timeout);
|
|
178
|
+
controller.dispose();
|
|
179
|
+
activeRequests -= 1;
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
return Object.assign(handler, {
|
|
184
|
+
fetch: handler,
|
|
185
|
+
close,
|
|
186
|
+
notify: modern ? modern.notify : legacyNotifier,
|
|
187
|
+
bus: modern ? modern.bus : new InMemoryServerEventBus(),
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function hostOriginRejection(request: Request, options: CreatePrismMcpWebHandlerOptions): Response | undefined {
|
|
192
|
+
if (options.allowedHosts?.length) {
|
|
193
|
+
const host = request.headers.get("host")?.toLowerCase();
|
|
194
|
+
if (!host || !options.allowedHosts.some((allowed) => allowed.toLowerCase() === host)) return httpError(403, "Invalid Host header");
|
|
195
|
+
}
|
|
196
|
+
if (options.allowedOrigins?.length) {
|
|
197
|
+
const origin = request.headers.get("origin");
|
|
198
|
+
if (origin && !options.allowedOrigins.some((allowed) => allowed.toLowerCase() === origin.toLowerCase()))
|
|
199
|
+
return httpError(403, "Invalid Origin header");
|
|
200
|
+
}
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Thin dual-era stdio wrapper: the opening exchange pins the era; one factory instance serves the connection. */
|
|
205
|
+
export function servePrismMcpStdio(server: McpServer | McpServerFactory, options: ServePrismMcpStdioOptions = {}): PrismMcpStdioHandle {
|
|
206
|
+
const factory: McpServerFactory = typeof server === "function" ? server : () => server;
|
|
207
|
+
return serveStdio(factory, {
|
|
208
|
+
legacy: options.legacy ?? "serve",
|
|
209
|
+
...(options.transport !== undefined ? { transport: options.transport } : {}),
|
|
210
|
+
...(options.maxSubscriptions !== undefined
|
|
211
|
+
? { maxSubscriptions: bounded(options.maxSubscriptions, 1024, 4096, "maxSubscriptions") }
|
|
212
|
+
: {}),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function validCapabilityId(value: string): boolean {
|
|
217
|
+
return value.length > 0 && value.length <= 128 && /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(value);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function awaitWithSignal<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
221
|
+
if (signal.aborted) throw signal.reason;
|
|
222
|
+
return new Promise<T>((resolve, reject) => {
|
|
223
|
+
const abort = () => reject(signal.reason ?? new McpBridgeError("MCP request aborted"));
|
|
224
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
225
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function linkedController(signal: AbortSignal) {
|
|
230
|
+
const controller = new AbortController();
|
|
231
|
+
const abort = () => controller.abort(signal.reason);
|
|
232
|
+
if (signal.aborted) abort();
|
|
233
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
234
|
+
return {
|
|
235
|
+
controller,
|
|
236
|
+
signal: controller.signal,
|
|
237
|
+
dispose: () => signal.removeEventListener("abort", abort),
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function readBoundedBody(
|
|
242
|
+
request: Request,
|
|
243
|
+
maxBytes: number,
|
|
244
|
+
signal: AbortSignal,
|
|
245
|
+
): Promise<{ readonly bytes: Uint8Array<ArrayBuffer>; readonly parsed: unknown }> {
|
|
246
|
+
const type = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
247
|
+
if (type !== "application/json") throw new McpHttpError(415, "Content-Type must be application/json");
|
|
248
|
+
const declared = Number(request.headers.get("content-length"));
|
|
249
|
+
if (Number.isFinite(declared) && declared > maxBytes) throw new McpHttpError(413, "MCP request body too large");
|
|
250
|
+
const reader = request.body?.getReader();
|
|
251
|
+
if (!reader) throw new McpHttpError(400, "MCP request body is required");
|
|
252
|
+
const chunks: Uint8Array[] = [];
|
|
253
|
+
let size = 0;
|
|
254
|
+
const abort = () => {
|
|
255
|
+
void reader.cancel(signal.reason);
|
|
256
|
+
};
|
|
257
|
+
if (signal.aborted) abort();
|
|
258
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
259
|
+
try {
|
|
260
|
+
while (true) {
|
|
261
|
+
const next = await reader.read();
|
|
262
|
+
if (next.done) break;
|
|
263
|
+
size += next.value.byteLength;
|
|
264
|
+
if (size > maxBytes) {
|
|
265
|
+
await reader.cancel();
|
|
266
|
+
throw new McpHttpError(413, "MCP request body too large");
|
|
267
|
+
}
|
|
268
|
+
chunks.push(next.value);
|
|
269
|
+
}
|
|
270
|
+
} finally {
|
|
271
|
+
signal.removeEventListener("abort", abort);
|
|
272
|
+
reader.releaseLock();
|
|
273
|
+
}
|
|
274
|
+
if (signal.aborted) throw new McpHttpError(408, "MCP request timed out");
|
|
275
|
+
const bytes = new Uint8Array(size);
|
|
276
|
+
let offset = 0;
|
|
277
|
+
for (const chunk of chunks) {
|
|
278
|
+
bytes.set(chunk, offset);
|
|
279
|
+
offset += chunk.byteLength;
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
return { bytes, parsed: JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)) };
|
|
283
|
+
} catch {
|
|
284
|
+
throw new McpHttpError(400, "Invalid MCP JSON body");
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async function boundResponse(response: Response, maxBytes: number): Promise<Response> {
|
|
289
|
+
if (!response.body) return response;
|
|
290
|
+
// Server-sent-event responses are long-lived and unbounded; buffering them
|
|
291
|
+
// would stall the handler forever. Relay them as-is (the stateless relay
|
|
292
|
+
// below still forwards chunks and closes on client disconnect).
|
|
293
|
+
if ((response.headers.get("content-type") ?? "").includes("text/event-stream")) return response;
|
|
294
|
+
const reader = response.body.getReader();
|
|
295
|
+
const chunks: Uint8Array[] = [];
|
|
296
|
+
let size = 0;
|
|
297
|
+
try {
|
|
298
|
+
while (true) {
|
|
299
|
+
const next = await reader.read();
|
|
300
|
+
if (next.done) break;
|
|
301
|
+
size += next.value.byteLength;
|
|
302
|
+
if (size > maxBytes) {
|
|
303
|
+
await reader.cancel();
|
|
304
|
+
return httpError(507, "MCP response too large");
|
|
305
|
+
}
|
|
306
|
+
chunks.push(next.value);
|
|
307
|
+
}
|
|
308
|
+
} finally {
|
|
309
|
+
reader.releaseLock();
|
|
310
|
+
}
|
|
311
|
+
const body = new Uint8Array(size);
|
|
312
|
+
let offset = 0;
|
|
313
|
+
for (const chunk of chunks) {
|
|
314
|
+
body.set(chunk, offset);
|
|
315
|
+
offset += chunk.byteLength;
|
|
316
|
+
}
|
|
317
|
+
return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function httpError(status: number, message: string): Response {
|
|
321
|
+
return Response.json({ error: { message } }, { status });
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
class McpHttpError extends Error {
|
|
325
|
+
constructor(
|
|
326
|
+
readonly status: number,
|
|
327
|
+
message: string,
|
|
328
|
+
) {
|
|
329
|
+
super(message);
|
|
330
|
+
}
|
|
331
|
+
}
|