scoped-execution-protocol 0.0.0-stage → 2.0.0-rc.0

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.
@@ -0,0 +1,7 @@
1
+ export * from "./mcp.js";
2
+ export * from "./mcp-proxy.js";
3
+ export * from "./a2a.js";
4
+ export * from "./agui.js";
5
+ export * from "./http.js";
6
+ export { ToolHostAdapter, type ToolHostOutcome } from "./host.js";
7
+ export * from "./providers.js";
@@ -0,0 +1,7 @@
1
+ export * from "./mcp.js";
2
+ export * from "./mcp-proxy.js";
3
+ export * from "./a2a.js";
4
+ export * from "./agui.js";
5
+ export * from "./http.js";
6
+ export { ToolHostAdapter } from "./host.js";
7
+ export * from "./providers.js";
@@ -0,0 +1,39 @@
1
+ import type { AgentKernel } from "../kernel.js";
2
+ import { type Clearance } from "../types.js";
3
+ export interface McpGuardOptions {
4
+ /** Every request must carry `Authorization: Bearer <bearerToken>`. */
5
+ bearerToken?: string;
6
+ /** Serve without a token. Loopback is not a credential: the kernel holds the credentials of the servers behind it. */
7
+ allowUnauthenticated?: boolean;
8
+ /** Browser origins allowed to call the endpoint. A request carrying any other `Origin` is refused. */
9
+ allowedOrigins?: string[];
10
+ /** Host names (or `name:port`) the endpoint answers to, besides loopback. Guards against DNS rebinding. */
11
+ allowedHosts?: string[];
12
+ /** Clearance of the callers; intersected with the kernel's own. */
13
+ callerClearance?: Clearance;
14
+ /** Offer `sxp_inspect` / `sxp_call` instead of every upstream tool (default true). */
15
+ progressiveFacade?: boolean;
16
+ /** The operator vouches for the arguments. Unset (the default) treats every caller as tainted and read-only. */
17
+ trustedInput?: boolean;
18
+ /** Request and response frame limit in bytes. */
19
+ maxFrameBytes?: number;
20
+ /** Only answer at this path (default: any path the host router sends here). */
21
+ path?: string;
22
+ }
23
+ export interface McpGuardHandler {
24
+ (req: Request): Promise<Response>;
25
+ /**
26
+ * Refuse new requests, wait up to `graceMs` (default 5000) for the one in flight, then cancel what is still pending.
27
+ * A call stuck on a hung upstream cannot hold shutdown hostage; give your `rpcFn` an `AbortSignal.timeout` so it also
28
+ * stops. Safe to call twice.
29
+ */
30
+ close(opts?: {
31
+ graceMs?: number;
32
+ }): Promise<void>;
33
+ }
34
+ /**
35
+ * A fetch-style MCP front door for a guarded kernel: MCP in, SXP rails, MCP out. POST only, authenticated, origin and
36
+ * host checked, and bounded in both directions. One handler is one security domain: every caller shares the kernel, so
37
+ * one taint state, one spend ledger and one handle store. Run one per agent session or tenant.
38
+ */
39
+ export declare function createMcpGuardHandler(kernel: AgentKernel, opts?: McpGuardOptions): McpGuardHandler;
@@ -0,0 +1,122 @@
1
+ import { sha256Hex } from "../canonical.js";
2
+ import { MAX_FRAME_BYTES, readFrame } from "../transport.js";
3
+ import { SXPError } from "../types.js";
4
+ import { handleInboundMcpJsonRpc } from "./mcp.js";
5
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
6
+ const CALLER_ID = "mcp-http";
7
+ function rpcError(id, code, message) {
8
+ return { jsonrpc: "2.0", id: id ?? null, error: { code, message } };
9
+ }
10
+ function hostnameOf(host) {
11
+ return host.startsWith("[") ? host.slice(0, host.indexOf("]") + 1) : host.split(":")[0];
12
+ }
13
+ /** Compare secrets without leaking where they differ: digests have equal length, so the loop never exits early. */
14
+ async function sameSecret(a, b) {
15
+ const [x, y] = await Promise.all([sha256Hex(a), sha256Hex(b)]);
16
+ let diff = x.length ^ y.length;
17
+ for (let i = 0; i < x.length; i++)
18
+ diff |= x.charCodeAt(i) ^ y.charCodeAt(i);
19
+ return diff === 0;
20
+ }
21
+ /**
22
+ * A fetch-style MCP front door for a guarded kernel: MCP in, SXP rails, MCP out. POST only, authenticated, origin and
23
+ * host checked, and bounded in both directions. One handler is one security domain: every caller shares the kernel, so
24
+ * one taint state, one spend ledger and one handle store. Run one per agent session or tenant.
25
+ */
26
+ export function createMcpGuardHandler(kernel, opts = {}) {
27
+ const limit = opts.maxFrameBytes ?? MAX_FRAME_BYTES;
28
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_FRAME_BYTES)
29
+ throw new RangeError("Invalid frame limit.");
30
+ const token = opts.bearerToken;
31
+ if (token === "" || (token === undefined && !opts.allowUnauthenticated)) {
32
+ throw new Error("Provide a bearer token or explicitly allow unauthenticated requests.");
33
+ }
34
+ if (opts.path !== undefined && (!opts.path.startsWith("/") || /[\x00-\x20]/.test(opts.path)))
35
+ throw new Error("Invalid endpoint path.");
36
+ const origins = new Set(opts.allowedOrigins ?? []);
37
+ const hosts = new Set((opts.allowedHosts ?? []).map((host) => host.toLowerCase()));
38
+ const expected = token === undefined ? undefined : `Bearer ${token}`;
39
+ let closed = false;
40
+ let queue = Promise.resolve();
41
+ const reply = (status, body, extra = {}) => new Response(body === undefined ? null : typeof body === "string" ? body : JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...extra } });
42
+ const refuse = (status, reason, extra) => reply(status, { error: reason }, extra);
43
+ const handler = async (req) => {
44
+ try {
45
+ if (req.method !== "POST") {
46
+ await req.body?.cancel();
47
+ return refuse(405, "Method not allowed.", { allow: "POST" });
48
+ }
49
+ const url = new URL(req.url);
50
+ if (opts.path !== undefined && url.pathname !== opts.path)
51
+ return refuse(404, "Not found.");
52
+ const host = (req.headers.get("host") ?? url.host).toLowerCase();
53
+ if (!LOOPBACK.has(hostnameOf(host)) && !hosts.has(host) && !hosts.has(hostnameOf(host)))
54
+ return refuse(403, "Host not allowed."); // DNS rebinding
55
+ const origin = req.headers.get("origin");
56
+ if (origin !== null && !origins.has(origin))
57
+ return refuse(403, "Origin not allowed."); // a browser page, not an MCP client
58
+ if (expected !== undefined && !(await sameSecret(req.headers.get("authorization") ?? "", expected))) {
59
+ return refuse(401, "Unauthorized.", { "www-authenticate": "Bearer" });
60
+ }
61
+ if (req.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== "application/json")
62
+ return refuse(415, "Content-Type must be application/json.");
63
+ let text;
64
+ try {
65
+ text = await readFrame(req, limit);
66
+ }
67
+ catch (err) {
68
+ if (err instanceof SXPError && err.code === "FRAME_TOO_LARGE")
69
+ return refuse(413, "Request exceeds the frame limit.");
70
+ if (err instanceof SXPError)
71
+ return refuse(400, "A request body is required.");
72
+ return reply(200, rpcError(null, -32700, "Parse error")); // not valid UTF-8
73
+ }
74
+ if (text.length === 0)
75
+ return refuse(400, "An empty request body.");
76
+ let request;
77
+ try {
78
+ request = JSON.parse(text);
79
+ }
80
+ catch {
81
+ return reply(200, rpcError(null, -32700, "Parse error"));
82
+ }
83
+ const message = request !== null && typeof request === "object" && !Array.isArray(request) ? request : undefined;
84
+ if (!message || typeof message.method !== "string")
85
+ return reply(200, rpcError(null, -32600, "Invalid Request"));
86
+ // The kernel is single threaded by design: one request at a time.
87
+ const run = queue.then(async () => {
88
+ if (closed)
89
+ return rpcError(message.id, -32000, "The proxy is closed.");
90
+ return handleInboundMcpJsonRpc(kernel, message, {
91
+ callerClearance: opts.callerClearance,
92
+ callerId: CALLER_ID,
93
+ progressiveFacade: opts.progressiveFacade ?? true,
94
+ trustedInput: opts.trustedInput ?? false,
95
+ headers: Object.fromEntries(req.headers),
96
+ });
97
+ });
98
+ queue = run.catch(() => undefined);
99
+ const response = await run;
100
+ if (response === null)
101
+ return reply(202);
102
+ let body = JSON.stringify(response);
103
+ if (new TextEncoder().encode(body).byteLength > limit)
104
+ body = JSON.stringify(rpcError(message.id, -32603, "Response exceeds the frame limit."));
105
+ return reply(200, body);
106
+ }
107
+ catch {
108
+ return refuse(500, "Internal error.");
109
+ }
110
+ };
111
+ return Object.assign(handler, {
112
+ async close(closeOpts) {
113
+ if (closed)
114
+ return;
115
+ closed = true; // new requests are refused from here on
116
+ let timer;
117
+ await Promise.race([queue, new Promise((resolve) => { timer = setTimeout(resolve, closeOpts?.graceMs ?? 5000); })]);
118
+ clearTimeout(timer);
119
+ kernel.teardown();
120
+ },
121
+ });
122
+ }
@@ -0,0 +1,88 @@
1
+ import { AppConnector } from "../apps.js";
2
+ import { type AgentKernel } from "../kernel.js";
3
+ import { type Clearance, type EffectClass } from "../types.js";
4
+ import { ResultProjection } from "../policy.js";
5
+ export declare const MCP_PROTOCOL_VERSION = "2026-07-28";
6
+ export declare function mapMcpAnnotationsToEffect(annotations?: Record<string, unknown> | null, defaultMutating?: boolean): EffectClass;
7
+ export declare function effectToMcpAnnotations(effect: EffectClass): Record<string, boolean>;
8
+ /** An upstream connector whose results already use MCP response shapes. */
9
+ export declare class McpConnector extends AppConnector {
10
+ /** Tools and resources that were not exposed because their names were unsafe. */
11
+ readonly rejected: string[];
12
+ }
13
+ /**
14
+ * Collapse a legacy MCP server into one progressive L0/L1/L2 connector.
15
+ *
16
+ * Everything the server says about itself is untrusted text: descriptions and schema prose are flattened to one bounded
17
+ * line, and a tool or resource whose name has line breaks or control characters is not exposed (it is listed in
18
+ * `connector.rejected`).
19
+ *
20
+ * Effects fail closed. A tool runs as `unverified_write` unless the host says otherwise: name it in `toolEffects`
21
+ * (tool -> effect class) or `readOnlyTools`, or opt in with `trustUpstreamAnnotations: true` to believe the server's own
22
+ * annotations. Either way a server can only make a tool more dangerous (`destructiveHint: true` is `irreversible`,
23
+ * `readOnlyHint: false` is at least `unverified_write`); its `readOnlyHint: true` and `idempotentHint: true` never lower a
24
+ * tool. A host pin is a floor, not a ceiling, for the same reason.
25
+ */
26
+ export declare function wrapMcpServer(appId: string, opts: {
27
+ serverOrigin: string;
28
+ rpcFn: (req: Record<string, unknown>) => Record<string, unknown> | Promise<Record<string, unknown>>;
29
+ mutatingTools?: string[];
30
+ readOnlyTools?: string[];
31
+ /** The host's own tool -> effect map. Authoritative as a starting point; a server's hints can only raise it. */
32
+ toolEffects?: Record<string, EffectClass>;
33
+ resultProjections?: Record<string, ResultProjection>;
34
+ summary?: string;
35
+ /** Believe the server's own `readOnlyHint` / `idempotentHint` to run its tools below `unverified_write`. Off by default. */
36
+ trustUpstreamAnnotations?: boolean;
37
+ /**
38
+ * Taint the reading branch when this server's catalog handle (its tool descriptions) is inspected. Off by default.
39
+ * It covers that handle only: not descriptions mounted into tool schemas, and not an MCP proxy, whose per-call branches discard taint.
40
+ */
41
+ taintOnCatalogRead?: boolean;
42
+ }): Promise<McpConnector>;
43
+ interface McpOptions {
44
+ callerClearance?: Clearance;
45
+ callerId?: string;
46
+ progressiveFacade?: boolean;
47
+ trustedInput?: boolean;
48
+ headers?: Record<string, string>;
49
+ }
50
+ type McpRequest = {
51
+ id?: unknown;
52
+ method: string;
53
+ params?: Record<string, unknown>;
54
+ };
55
+ export declare function handleInboundMcpJsonRpc(kernel: AgentKernel, request: McpRequest, opts?: McpOptions): Promise<Record<string, unknown> | null>;
56
+ export declare class McpHttpClient {
57
+ readonly url: string;
58
+ readonly headers: Record<string, string>;
59
+ readonly maxResponseBytes: number;
60
+ readonly protocolVersion: string;
61
+ constructor(url: string, opts?: {
62
+ headers?: Record<string, string>;
63
+ maxResponseBytes?: number;
64
+ protocolVersion?: string;
65
+ });
66
+ rpc(request: {
67
+ jsonrpc: "2.0";
68
+ id: unknown;
69
+ method: string;
70
+ params?: Record<string, unknown>;
71
+ }): Promise<Record<string, unknown>>;
72
+ }
73
+ export declare function connectMcpConfig(kernel: AgentKernel, config: {
74
+ mcpServers?: Record<string, Record<string, unknown>>;
75
+ servers?: Record<string, Record<string, unknown>>;
76
+ }, opts?: {
77
+ rpcFactory?: (serverId: string, entry: Record<string, unknown>) => (req: {
78
+ jsonrpc: "2.0";
79
+ id: unknown;
80
+ method: string;
81
+ params?: Record<string, unknown>;
82
+ }) => Promise<Record<string, unknown>>;
83
+ /** Believe each server's own `readOnlyHint` / `idempotentHint` to run its tools below `unverified_write`. Off by default: only tools pinned in `sxp.readOnlyTools` or `sxp.toolEffects` do. */
84
+ trustUpstreamAnnotations?: boolean;
85
+ /** Taint the reading branch when a server's catalog handle (its tool descriptions) is inspected. Off by default; see `wrapMcpServer`. */
86
+ taintOnCatalogRead?: boolean;
87
+ }): Promise<Record<string, unknown>>;
88
+ export {};