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,571 @@
1
+ import { AppConnector, ElicitationNeeded } from "../apps.js";
2
+ import { attenuateCapability } from "../kernel.js";
3
+ import { canAccessPolicy, checkClearance, DEFAULT_CLEARANCE, DEFAULT_POLICY, mergePolicyWatermark, intersectClearance } from "../privacy.js";
4
+ import { CLASSIFICATION_RANK, EFFECT_RANK, ScopeError, SXPError, SXP_VERSION } from "../types.js";
5
+ import { contentHash } from "../canonical.js";
6
+ import { MAX_FRAME_BYTES, readFrame } from "../transport.js";
7
+ import { ResultProjection } from "../policy.js";
8
+ export const MCP_PROTOCOL_VERSION = "2026-07-28";
9
+ const META = "io.modelcontextprotocol/";
10
+ const forms = new WeakMap();
11
+ function object(v) {
12
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
13
+ }
14
+ const CATALOG_DENIED = "This catalog names targets the caller is not cleared for.";
15
+ const LINE_BREAKS = /[\x00-\x1f\x7f\x85\u2028\u2029]+/g;
16
+ const MAX_UNTRUSTED_TEXT = 1024;
17
+ const MAX_IDENTIFIER = 256;
18
+ const MAX_SCHEMA_DEPTH = 32;
19
+ /** Collapse line breaks and control characters, so upstream text cannot open its own line or section in the prefix. */
20
+ function singleLine(text) {
21
+ return text.replace(LINE_BREAKS, " ").replace(/^ +| +$/g, "");
22
+ }
23
+ /** Upstream prose is shown to downstream models: keep it on one line and bounded, so it cannot open its own section. */
24
+ function untrustedText(value, limit = MAX_UNTRUSTED_TEXT) {
25
+ const text = typeof value === "string" ? singleLine(value) : "";
26
+ const points = Array.from(text);
27
+ return points.length <= limit ? text : points.slice(0, limit - 1).join("").trimEnd() + "\u2026";
28
+ }
29
+ /** A tool name or resource URI that is nonempty, bounded and free of line breaks and control characters. */
30
+ function safeIdentifier(value) {
31
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_IDENTIFIER && singleLine(value) === value;
32
+ }
33
+ /** Flatten the prose (`description`, `title`) inside an upstream JSON Schema; the structure is left as declared. */
34
+ function cleanSchema(node, depth = 0) {
35
+ if (depth > MAX_SCHEMA_DEPTH)
36
+ return {};
37
+ if (Array.isArray(node))
38
+ return node.map((item) => cleanSchema(item, depth + 1));
39
+ if (node !== null && typeof node === "object") {
40
+ return Object.fromEntries(Object.entries(node).map(([key, value]) => [key, (key === "description" || key === "title") && typeof value === "string" ? untrustedText(value) : cleanSchema(value, depth + 1)]));
41
+ }
42
+ return node;
43
+ }
44
+ /** An escaped, bounded rendering of untrusted text that is safe to log or return. */
45
+ function preview(value) {
46
+ return JSON.stringify(String(value)).replace(/[^\x20-\x7e]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")).slice(0, 80);
47
+ }
48
+ function targetName(method, params) {
49
+ if (method === "tools/call" || method === "prompts/get")
50
+ return params.name;
51
+ if (method === "resources/read")
52
+ return params.uri;
53
+ return undefined;
54
+ }
55
+ function encodeHeader(value) {
56
+ if (value.trim() === value && /^[\x20-\x7e\t]*$/.test(value) && !(value.startsWith("=?base64?") && value.endsWith("?=")))
57
+ return value;
58
+ return "=?base64?" + btoa(Array.from(new TextEncoder().encode(value), (b) => String.fromCharCode(b)).join("")) + "?=";
59
+ }
60
+ function headerMatches(header, expected) {
61
+ if (header?.startsWith("=?base64?") && header.endsWith("?=")) {
62
+ try {
63
+ const bytes = Uint8Array.from(atob(header.slice(9, -2)), (c) => c.charCodeAt(0));
64
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes) === expected;
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
70
+ return (header ?? undefined) === expected;
71
+ }
72
+ export function mapMcpAnnotationsToEffect(annotations, defaultMutating = false) {
73
+ if (annotations && typeof annotations === "object") {
74
+ if (annotations.readOnlyHint === true)
75
+ return "read";
76
+ if (annotations.destructiveHint === true)
77
+ return "irreversible";
78
+ if (annotations.idempotentHint === true)
79
+ return "idempotent";
80
+ if (annotations.readOnlyHint === false)
81
+ return "unverified_write";
82
+ }
83
+ return defaultMutating ? "unverified_write" : "read";
84
+ }
85
+ export function effectToMcpAnnotations(effect) {
86
+ if (effect === "read") {
87
+ return { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
88
+ }
89
+ if (effect === "idempotent") {
90
+ return { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };
91
+ }
92
+ if (effect === "irreversible") {
93
+ return { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true };
94
+ }
95
+ return { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
96
+ }
97
+ /** Validate the host's own tool -> effect map. It is the one input here that is trusted, so a typo is an error. */
98
+ function hostEffectMap(toolEffects) {
99
+ const pins = new Map();
100
+ for (const [name, effect] of Object.entries(toolEffects ?? {})) {
101
+ if (!name || typeof effect !== "string" || !Object.hasOwn(EFFECT_RANK, effect))
102
+ throw new TypeError(`toolEffects has an unknown effect class for tool ${preview(name)}.`);
103
+ pins.set(name, effect);
104
+ }
105
+ return pins;
106
+ }
107
+ /**
108
+ * The effect an imported tool runs at. A server describes itself, so what it says can raise a tool's risk but never lower it.
109
+ *
110
+ * The starting point is what the host decided (`hostEffect`), else the fail-closed default `unverified_write`, else, only
111
+ * when the host opted in with `trustUpstreamAnnotations`, what the server's annotations map to. Then anything the server
112
+ * says that makes the tool more dangerous is believed: `destructiveHint: true` is `irreversible`, and `readOnlyHint: false`
113
+ * is at least `unverified_write`. `readOnlyHint: true` and `idempotentHint: true` never lower it.
114
+ */
115
+ function classifyUpstreamTool(tool, trustUpstreamAnnotations, hostEffect) {
116
+ const annotations = object(tool.annotations);
117
+ let effect = hostEffect ?? (trustUpstreamAnnotations ? mapMcpAnnotationsToEffect(annotations, true) : "unverified_write");
118
+ if (annotations.readOnlyHint === false && EFFECT_RANK[effect] < EFFECT_RANK.unverified_write)
119
+ effect = "unverified_write";
120
+ if (annotations.destructiveHint === true && EFFECT_RANK[effect] < EFFECT_RANK.irreversible)
121
+ effect = "irreversible";
122
+ return effect;
123
+ }
124
+ /** An upstream connector whose results already use MCP response shapes. */
125
+ export class McpConnector extends AppConnector {
126
+ /** Tools and resources that were not exposed because their names were unsafe. */
127
+ rejected = [];
128
+ }
129
+ /**
130
+ * Collapse a legacy MCP server into one progressive L0/L1/L2 connector.
131
+ *
132
+ * Everything the server says about itself is untrusted text: descriptions and schema prose are flattened to one bounded
133
+ * line, and a tool or resource whose name has line breaks or control characters is not exposed (it is listed in
134
+ * `connector.rejected`).
135
+ *
136
+ * Effects fail closed. A tool runs as `unverified_write` unless the host says otherwise: name it in `toolEffects`
137
+ * (tool -> effect class) or `readOnlyTools`, or opt in with `trustUpstreamAnnotations: true` to believe the server's own
138
+ * annotations. Either way a server can only make a tool more dangerous (`destructiveHint: true` is `irreversible`,
139
+ * `readOnlyHint: false` is at least `unverified_write`); its `readOnlyHint: true` and `idempotentHint: true` never lower a
140
+ * tool. A host pin is a floor, not a ceiling, for the same reason.
141
+ */
142
+ export async function wrapMcpServer(appId, opts) {
143
+ const mutSet = new Set(opts.mutatingTools ?? []);
144
+ const hostEffects = new Map([...(opts.readOnlyTools ?? [])].map((name) => [name, "read"]));
145
+ for (const [name, effect] of hostEffectMap(opts.toolEffects))
146
+ hostEffects.set(name, effect);
147
+ const connector = new McpConnector(appId, {
148
+ summary: untrustedText(opts.summary || `Bridged MCP server at ${opts.serverOrigin}`),
149
+ untrusted: true,
150
+ taintOnCatalogRead: opts.taintOnCatalogRead,
151
+ });
152
+ const toolsResp = await opts.rpcFn({ jsonrpc: "2.0", id: "sxp-init-tools", method: "tools/list", params: {} });
153
+ const advertised = toolsResp.result?.tools ?? [];
154
+ const toolsList = [];
155
+ for (const entry of advertised) {
156
+ const name = object(entry).name;
157
+ if (safeIdentifier(name))
158
+ toolsList.push(object(entry));
159
+ else
160
+ connector.rejected.push("tool " + preview(name));
161
+ }
162
+ const projections = new Map(Object.entries(opts.resultProjections ?? {}));
163
+ for (const projection of projections.values()) {
164
+ if (!(projection instanceof ResultProjection)) {
165
+ throw new TypeError("Expected a compiled ResultProjection.");
166
+ }
167
+ }
168
+ const toolNames = new Set(toolsList.map((tool) => String(tool.name)));
169
+ if ([...projections.keys()].some((name) => !toolNames.has(name))) {
170
+ throw new TypeError("Result projections must name tools advertised by the MCP server.");
171
+ }
172
+ for (const t of toolsList) {
173
+ const tname = String(t.name);
174
+ const mapped = classifyUpstreamTool(t, opts.trustUpstreamAnnotations === true, hostEffects.get(tname));
175
+ let eff = mutSet.has(tname) && EFFECT_RANK[mapped] < EFFECT_RANK.unverified_write ? "unverified_write" : mapped;
176
+ const declared = object(t._meta)["io.sxp/effect"];
177
+ if (typeof declared === "string" && Object.hasOwn(EFFECT_RANK, declared) && EFFECT_RANK[declared] > EFFECT_RANK[eff])
178
+ eff = declared;
179
+ const policy = object(t._meta)["io.sxp/policy"];
180
+ let outputPolicy = DEFAULT_POLICY;
181
+ if (policy !== undefined) {
182
+ const p = object(policy);
183
+ if (policy !== p || (p.classification !== undefined && !Object.hasOwn(CLASSIFICATION_RANK, String(p.classification))) ||
184
+ (p.residency != null && typeof p.residency !== "string") ||
185
+ ["residencies", "pii_fields", "allowed_purposes"].some((key) => p[key] != null &&
186
+ (!Array.isArray(p[key]) || !p[key].every((item) => typeof item === "string"))))
187
+ throw new Error("Invalid MCP output policy.");
188
+ outputPolicy = mergePolicyWatermark(DEFAULT_POLICY, { ...DEFAULT_POLICY, ...p });
189
+ }
190
+ const resultProjection = projections.get(tname);
191
+ if (resultProjection && eff !== "read")
192
+ throw new TypeError("MCP result projections require a read tool: pin it in readOnlyTools or toolEffects, or opt in to trustUpstreamAnnotations.");
193
+ connector.action({
194
+ name: tname,
195
+ resultProjection, outputPolicy,
196
+ description: untrustedText(t.description),
197
+ effect: eff,
198
+ inputSchema: Object.keys(object(t.inputSchema)).length > 0 ? cleanSchema(object(t.inputSchema)) : { type: "object" },
199
+ untrusted: true,
200
+ externalEgress: eff !== "read",
201
+ sinkClearance: { ...DEFAULT_CLEARANCE, max_classification: "internal" },
202
+ fn: async (args) => {
203
+ const resp = await opts.rpcFn({
204
+ jsonrpc: "2.0",
205
+ id: `sxp-call-${tname}`,
206
+ method: "tools/call",
207
+ params: { name: tname, arguments: args },
208
+ });
209
+ if (resp.error) {
210
+ if (resultProjection)
211
+ throw new Error("Upstream MCP tool returned an execution error.");
212
+ throw new Error(`MCP error: ${String(resp.error.message ?? resp.error)}`);
213
+ }
214
+ if (object(resp.result).resultType === "input_required")
215
+ throw new ElicitationNeeded("The upstream MCP tool requires input.");
216
+ if (resp.result?.isError)
217
+ throw new Error("Upstream MCP tool returned an execution error.");
218
+ return resp.result;
219
+ },
220
+ });
221
+ }
222
+ const resResp = await opts.rpcFn({ jsonrpc: "2.0", id: "sxp-init-res", method: "resources/list", params: {} });
223
+ const resList = resResp.result?.resources ?? [];
224
+ for (const entry of resList) {
225
+ const r = object(entry);
226
+ const uri = r.uri;
227
+ if (!safeIdentifier(uri)) {
228
+ connector.rejected.push("resource " + preview(uri));
229
+ continue;
230
+ }
231
+ connector.resource({
232
+ uri,
233
+ description: untrustedText(r.description),
234
+ mimeType: untrustedText(r.mimeType, 128) || "application/json",
235
+ untrusted: true,
236
+ readFn: async () => {
237
+ const resp = await opts.rpcFn({
238
+ jsonrpc: "2.0",
239
+ id: `sxp-read-${uri}`,
240
+ method: "resources/read",
241
+ params: { uri },
242
+ });
243
+ if (resp.error) {
244
+ throw new Error(`MCP resource error: ${String(resp.error.message ?? resp.error)}`);
245
+ }
246
+ return resp.result;
247
+ },
248
+ });
249
+ }
250
+ return connector;
251
+ }
252
+ export async function handleInboundMcpJsonRpc(kernel, request, opts) {
253
+ const params = request.params ?? {};
254
+ const version = object(params._meta)[META + "protocolVersion"];
255
+ const modern = version === MCP_PROTOCOL_VERSION || request.method === "server/discover";
256
+ if (opts?.headers) {
257
+ const h = new Headers(opts.headers);
258
+ if (((modern || h.has("mcp-method")) && h.get("mcp-method") !== request.method) ||
259
+ ((modern || h.has("mcp-name")) && !headerMatches(h.get("mcp-name"), targetName(request.method, params))) ||
260
+ ((modern || h.has("mcp-protocol-version")) && h.get("mcp-protocol-version") !== (version ?? "2025-06-18"))) {
261
+ return { jsonrpc: "2.0", id: request.id, error: { code: -32020, message: "MCP routing headers do not match request." } };
262
+ }
263
+ }
264
+ if (version !== undefined && version !== MCP_PROTOCOL_VERSION && version !== "2025-06-18")
265
+ return {
266
+ jsonrpc: "2.0", id: request.id, error: { code: -32022, message: "Unsupported MCP version.", data: { supported: [MCP_PROTOCOL_VERSION, "2025-06-18"] } },
267
+ };
268
+ const response = await dispatchMcp(kernel, request, opts, modern);
269
+ if (modern && response?.result) {
270
+ const result = object(response.result);
271
+ result.resultType ??= "complete";
272
+ result._meta = { ...object(result._meta), [META + "serverInfo"]: { name: kernel.agentId, version: SXP_VERSION } };
273
+ if (request.method.endsWith("/list") || ["server/discover", "resources/read"].includes(request.method)) {
274
+ // Only catalogs may be cached, and only when the host opted in; always per caller, never shared.
275
+ const catalog = request.method !== "resources/read";
276
+ Object.assign(result, { ttlMs: catalog ? kernel.catalogTtlMs ?? 0 : 0, cacheScope: "private" });
277
+ }
278
+ }
279
+ return response;
280
+ }
281
+ async function dispatchMcp(kernel, request, opts, modern) {
282
+ if (!("id" in request) || (request.id == null && String(request.method ?? "").startsWith("notifications/"))) {
283
+ return null;
284
+ }
285
+ const parent = kernel.capability;
286
+ const clearance = intersectClearance(parent.clearance ?? DEFAULT_CLEARANCE, opts?.callerClearance ?? { ...DEFAULT_CLEARANCE, max_classification: "internal" });
287
+ const params = request.params ?? {};
288
+ if (request.method === "server/discover")
289
+ return { jsonrpc: "2.0", id: request.id, result: {
290
+ supportedVersions: [MCP_PROTOCOL_VERSION, "2025-06-18"], capabilities: { tools: {}, resources: {}, prompts: {} },
291
+ } };
292
+ if (request.method === "ping")
293
+ return { jsonrpc: "2.0", id: request.id, result: {} };
294
+ if (request.method === "initialize") {
295
+ return { jsonrpc: "2.0", id: request.id, result: { protocolVersion: "2025-06-18", serverInfo: { name: "sxp-ts", version: SXP_VERSION }, capabilities: { tools: { listChanged: false }, resources: { listChanged: false }, prompts: { listChanged: false } } } };
296
+ }
297
+ if (request.method === "tools/list") {
298
+ if (opts?.progressiveFacade) {
299
+ const catalog = kernel.listPublicApps(clearance);
300
+ const note = catalog.length > 0 ? ` Apps: ${catalog.join("; ")}.` : "";
301
+ return {
302
+ jsonrpc: "2.0", id: request.id,
303
+ result: {
304
+ tools: [
305
+ { name: "sxp_inspect", description: `Inspect a REF# catalog/result or app:// URI.${note}`, inputSchema: { type: "object", properties: { ref: { type: "string" }, view: { type: "string", enum: ["fields", "raw"] } }, required: ["ref", "view"] } },
306
+ { name: "sxp_call", description: `Invoke any target/app action with optional preview=true.${note}`, inputSchema: { type: "object", properties: { target: { type: "string" }, args: { type: "object" }, preview: { type: "boolean" }, confirm_token: { type: "string" } }, required: ["target", "args"] } },
307
+ ],
308
+ },
309
+ };
310
+ }
311
+ const tools = kernel.listPublicTools(clearance).map((t) => ({
312
+ name: t.name,
313
+ description: t.description,
314
+ inputSchema: t.inputSchema,
315
+ annotations: effectToMcpAnnotations(t.effect),
316
+ _meta: { "io.sxp/effect": t.effect, "io.sxp/policy": kernel.targets.get(t.name)?.outputPolicy ?? DEFAULT_POLICY },
317
+ }));
318
+ return { jsonrpc: "2.0", id: request.id, result: { tools } };
319
+ }
320
+ if (request.method === "tools/call") {
321
+ try {
322
+ let name = String(params.name ?? "");
323
+ let args = { ...(params.arguments ?? {}) };
324
+ if (opts?.progressiveFacade && name === "sxp_inspect") {
325
+ const refArg = String(args.ref);
326
+ const resolvedRef = kernel.resourceIndex.has(refArg) ? (await kernel.readResource(refArg, { callerClearance: clearance })).handle.ref_id : refArg;
327
+ if (kernel.catalogHiddenFrom(resolvedRef, clearance))
328
+ throw new SXPError("PRIVACY_VIOLATION", CATALOG_DENIED);
329
+ const inspected = (await kernel.pendingStatus(resolvedRef, clearance)) ?? kernel.store.inspect(resolvedRef, args.view ?? "fields", { clearance });
330
+ return { jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: JSON.stringify(inspected) }] } };
331
+ }
332
+ if (opts?.progressiveFacade && name === "sxp_call") {
333
+ name = String(args.target ?? "");
334
+ const inner = { ...(args.args ?? {}) };
335
+ if (args.preview !== undefined)
336
+ inner._preview = args.preview;
337
+ if (args.confirm_token !== undefined)
338
+ inner._confirm_token = args.confirm_token;
339
+ args = inner;
340
+ }
341
+ const preview = Boolean(args._preview);
342
+ delete args._preview;
343
+ const confirmToken = typeof args._confirm_token === "string" ? args._confirm_token : undefined;
344
+ delete args._confirm_token;
345
+ if (!kernel.listPublicTools(clearance).some((t) => t.name === name))
346
+ throw new Error(`PRIVACY_VIOLATION: target '${name}' exceeds caller clearance.`);
347
+ const cap = attenuateCapability(parent, {
348
+ subject: parent.subject, clearance,
349
+ ...(opts?.trustedInput ? {} : { taint: "untrusted_data", max_effect: "read" }),
350
+ });
351
+ const namespace = await contentHash([kernel.activeBranch, parent, clearance, Boolean(opts?.trustedInput), opts?.callerId ?? null]);
352
+ const binding = modern ? await contentHash([namespace, name, args, preview, confirmToken ?? null]) : "";
353
+ if (modern && ("requestState" in params || "inputResponses" in params)) {
354
+ const key = String(params.requestState);
355
+ const form = forms.get(kernel)?.get(key);
356
+ const answer = object(object(params.inputResponses).input);
357
+ const fields = object(answer.content);
358
+ if (!form || form.expires <= Date.now() || form.binding !== binding || answer.action !== "accept" ||
359
+ Object.keys(fields).some((k) => !form.fields.includes(k)))
360
+ throw new Error("Invalid or expired input response.");
361
+ forms.get(kernel).delete(key);
362
+ args = { ...args, ...fields };
363
+ }
364
+ let res;
365
+ try {
366
+ res = await kernel.callInbound("mcp", namespace, name, args, { preview, confirmToken, capability: cap });
367
+ }
368
+ catch (err) {
369
+ const failure = { isError: true, content: [{ type: "text", text: err instanceof SXPError ? err.message : "Tool execution failed." }] };
370
+ // AUTH_REQUIRED / INSUFFICIENT_SCOPE: tell the client which consent to request.
371
+ if (err instanceof ScopeError)
372
+ failure._meta = { "io.sxp/error": err.toDict() };
373
+ return { jsonrpc: "2.0", id: request.id, result: failure };
374
+ }
375
+ if (res.elicitation && modern) {
376
+ const caps = object(object(params._meta)[META + "clientCapabilities"]);
377
+ const elicitation = object(caps.elicitation);
378
+ if (!caps.elicitation || (Object.keys(elicitation).length > 0 && !("form" in elicitation)))
379
+ return { jsonrpc: "2.0", id: request.id, error: { code: -32021, message: "Form elicitation required.",
380
+ data: { requiredCapabilities: { elicitation: { form: {} } } } } };
381
+ const req = res.elicitation;
382
+ const pending = forms.get(kernel) ?? new Map();
383
+ for (const [id, form] of pending) {
384
+ if (form.expires > Date.now())
385
+ break;
386
+ pending.delete(id);
387
+ }
388
+ if (pending.size >= 4096)
389
+ throw new Error("Too many pending input requests.");
390
+ const schema = { type: "object", properties: {}, ...req.input_schema };
391
+ pending.set(req.elicit_id, { binding, fields: Object.keys(schema.properties), expires: req.expires_at_ms });
392
+ forms.set(kernel, pending);
393
+ return { jsonrpc: "2.0", id: request.id, result: { resultType: "input_required", requestState: req.elicit_id,
394
+ inputRequests: { input: { method: "elicitation/create", params: { mode: "form", message: req.prompt, requestedSchema: schema } } } } };
395
+ }
396
+ if (res.pausedForElicitation && res.elicitation)
397
+ return { jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: JSON.stringify(res.elicitation) }] } };
398
+ if (res.handle) {
399
+ checkClearance(clearance, res.handle.policy, "inbound_mcp");
400
+ const meta = {
401
+ sxp_ref: res.handle.short_id, sxp_ref_id: res.handle.ref_id,
402
+ ...(res.confirmToken ? { confirm_token: res.confirmToken, status: res.pausedForHuman ? "pause_for_human" : "ready_to_commit" } : {}),
403
+ };
404
+ const spec = kernel.targets.get(name);
405
+ if (!res.preview && spec?.resultProjection && res.handle.byte_size <= 4096) {
406
+ const projected = kernel.store.inspect(res.handle.ref_id, "raw", { clearance }).data;
407
+ return { jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: JSON.stringify(projected) }], structuredContent: projected, _meta: meta } };
408
+ }
409
+ if (!res.preview && !spec?.resultProjection && spec?.appId && kernel.apps.get(spec.appId) instanceof McpConnector) {
410
+ const raw = kernel.store.inspect(res.handle.ref_id, "raw", { clearance }).data;
411
+ if (Array.isArray(raw?.content)) {
412
+ return { jsonrpc: "2.0", id: request.id, result: { content: raw.content, structuredContent: raw.structuredContent, _meta: meta } };
413
+ }
414
+ }
415
+ const l1 = res.handle.byte_size <= 4096 ? kernel.store.inspect(res.handle.ref_id, "fields", { clearance }) : null;
416
+ return {
417
+ jsonrpc: "2.0", id: request.id,
418
+ result: {
419
+ content: [{ type: "text", text: l1 ? JSON.stringify(l1.data) : res.handle.l0_summary }],
420
+ structuredContent: l1 ? l1.data : { summary: res.handle.l0_summary, resource_uri: `sxp://ref/${res.handle.short_id}` },
421
+ _meta: meta,
422
+ },
423
+ };
424
+ }
425
+ return { jsonrpc: "2.0", id: request.id, result: { content: [] } };
426
+ }
427
+ catch (err) {
428
+ return { jsonrpc: "2.0", id: request.id, error: { code: -32000, message: err instanceof Error ? err.message : String(err) } };
429
+ }
430
+ }
431
+ if (request.method === "resources/list") {
432
+ const resources = [...kernel.resourceIndex].flatMap(([uri, connector]) => {
433
+ const resource = connector.resources.get(uri);
434
+ return canAccessPolicy(clearance, resource.dataPolicy ?? DEFAULT_POLICY)
435
+ ? [{ uri, name: uri, description: resource.description, mimeType: resource.mimeType }] : [];
436
+ });
437
+ for (const h of kernel.store.allHandles()) {
438
+ if (canAccessPolicy(clearance, h.policy) && (h.expires_at_ms == null || Date.now() <= h.expires_at_ms) && !kernel.catalogHiddenFrom(h.ref_id, clearance)) {
439
+ resources.push({ uri: `sxp://ref/${h.short_id}`, name: h.label, description: h.l0_summary, mimeType: "application/json" });
440
+ }
441
+ }
442
+ return { jsonrpc: "2.0", id: request.id, result: { resources } };
443
+ }
444
+ if (request.method === "resources/read") {
445
+ try {
446
+ const uri = String(params.uri ?? "");
447
+ if (uri.startsWith("sxp://ref/") && kernel.catalogHiddenFrom(uri.slice("sxp://ref/".length), clearance))
448
+ throw new SXPError("PRIVACY_VIOLATION", CATALOG_DENIED);
449
+ const refKey = uri.startsWith("sxp://ref/") ? uri.slice("sxp://ref/".length) : (await kernel.readResource(uri, { callerClearance: clearance })).handle.ref_id;
450
+ if (kernel.resourceIndex.get(uri) instanceof McpConnector) {
451
+ const raw = kernel.store.inspect(refKey, "raw", { clearance }).data;
452
+ if (Array.isArray(raw?.contents))
453
+ return { jsonrpc: "2.0", id: request.id, result: { contents: raw.contents } };
454
+ }
455
+ const data = kernel.store.inspect(refKey, "fields", { clearance });
456
+ return { jsonrpc: "2.0", id: request.id, result: { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(data) }] } };
457
+ }
458
+ catch (err) {
459
+ return { jsonrpc: "2.0", id: request.id, error: { code: -32000, message: err instanceof Error ? err.message : String(err) } };
460
+ }
461
+ }
462
+ if (request.method === "prompts/list") {
463
+ return { jsonrpc: "2.0", id: request.id, result: { prompts: [...kernel.prompts.values()].map((p) => ({ name: p.name, description: p.description, arguments: p.arguments })) } };
464
+ }
465
+ if (request.method === "prompts/get") {
466
+ const p = kernel.prompts.get(String(params.name ?? ""));
467
+ if (!p)
468
+ return { jsonrpc: "2.0", id: request.id, error: { code: -32602, message: `Unknown prompt: ${String(params.name ?? "")}` } };
469
+ const pArgs = params.arguments ?? {};
470
+ const rendered = p.template.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (m, k) => (k in pArgs ? String(pArgs[k]) : m));
471
+ return { jsonrpc: "2.0", id: request.id, result: { description: p.description, messages: [{ role: "user", content: { type: "text", text: rendered } }] } };
472
+ }
473
+ return { jsonrpc: "2.0", id: request.id, error: { code: -32601, message: `Method not found: ${request.method}` } };
474
+ }
475
+ export class McpHttpClient {
476
+ url;
477
+ headers;
478
+ maxResponseBytes;
479
+ protocolVersion;
480
+ constructor(url, opts) {
481
+ const parsed = new URL(url);
482
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
483
+ throw new Error(`Only http:// and https:// URLs permitted: ${url}`);
484
+ this.url = url;
485
+ this.headers = { ...(opts?.headers ?? {}) };
486
+ this.maxResponseBytes = opts?.maxResponseBytes ?? MAX_FRAME_BYTES;
487
+ this.protocolVersion = opts?.protocolVersion ?? MCP_PROTOCOL_VERSION;
488
+ if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1 || this.maxResponseBytes > MAX_FRAME_BYTES)
489
+ throw new RangeError("Invalid MCP frame byte limit.");
490
+ if (this.protocolVersion !== MCP_PROTOCOL_VERSION)
491
+ throw new Error("Unsupported stateless MCP version.");
492
+ }
493
+ async rpc(request) {
494
+ const meta = { [META + "clientCapabilities"]: {}, ...object(request.params?._meta), [META + "protocolVersion"]: this.protocolVersion };
495
+ const params = { ...request.params, _meta: meta };
496
+ const headers = new Headers(this.headers);
497
+ headers.set("Content-Type", "application/json");
498
+ headers.set("Accept", "application/json, text/event-stream");
499
+ headers.set("MCP-Protocol-Version", this.protocolVersion);
500
+ headers.set("Mcp-Method", request.method);
501
+ const name = targetName(request.method, params);
502
+ if (typeof name === "string")
503
+ headers.set("Mcp-Name", encodeHeader(name));
504
+ else
505
+ headers.delete("Mcp-Name");
506
+ const resp = await fetch(this.url, { method: "POST", redirect: "error", headers, body: JSON.stringify({ ...request, params }) });
507
+ if (!resp.ok) {
508
+ await resp.body?.cancel();
509
+ if (resp.status === 401)
510
+ throw new ElicitationNeeded("MCP authorization required.", { kind: "consent" });
511
+ throw new Error(`MCP HTTP error ${resp.status}`);
512
+ }
513
+ const text = await readFrame(resp, this.maxResponseBytes);
514
+ const messages = resp.headers.get("content-type")?.includes("text/event-stream")
515
+ ? text.split(/\r?\n\r?\n/).map((event) => event.split(/\r?\n/).filter((line) => line.startsWith("data:"))
516
+ .map((line) => line.slice(5).trimStart()).join("\n")).filter((data) => data && data !== "[DONE]")
517
+ : [text];
518
+ for (const data of messages) {
519
+ const message = object(JSON.parse(data));
520
+ if (message.id === request.id && ("result" in message || "error" in message))
521
+ return message;
522
+ }
523
+ throw new Error("Missing matching MCP response.");
524
+ }
525
+ }
526
+ export async function connectMcpConfig(kernel, config, opts) {
527
+ const servers = config.mcpServers ?? config.servers ?? {};
528
+ const connected = {};
529
+ for (const [serverId, entry] of Object.entries(servers).sort(([a], [b]) => a.localeCompare(b))) {
530
+ if (entry.disabled)
531
+ continue;
532
+ let rpcFn;
533
+ if (opts?.rpcFactory) {
534
+ rpcFn = opts.rpcFactory(serverId, entry);
535
+ }
536
+ else if (typeof entry.url === "string") {
537
+ const client = new McpHttpClient(entry.url, { headers: entry.headers });
538
+ rpcFn = (req) => client.rpc(req);
539
+ }
540
+ else {
541
+ throw new Error(`TS connectMcpConfig entry '${serverId}' requires 'url' or a custom rpcFactory.`);
542
+ }
543
+ const sxp = entry.sxp;
544
+ if (sxp !== undefined && sxp !== object(sxp))
545
+ throw new TypeError(`MCP config entry '${serverId}' requires an object for 'sxp'.`);
546
+ const readOnlyTools = object(sxp).readOnlyTools;
547
+ if (readOnlyTools !== undefined && (!Array.isArray(readOnlyTools) || readOnlyTools.some((name) => typeof name !== "string"))) {
548
+ throw new TypeError(`MCP config entry '${serverId}' requires a list of tool names for 'sxp.readOnlyTools'.`);
549
+ }
550
+ const toolEffects = object(sxp).toolEffects;
551
+ if (toolEffects !== undefined && toolEffects !== object(toolEffects)) {
552
+ throw new TypeError(`MCP config entry '${serverId}' requires an object for 'sxp.toolEffects'.`);
553
+ }
554
+ const projectionConfigs = object(sxp).resultProjections;
555
+ if (projectionConfigs !== undefined && projectionConfigs !== object(projectionConfigs)) {
556
+ throw new TypeError("MCP resultProjections must be an object keyed by tool name.");
557
+ }
558
+ const app = await wrapMcpServer(serverId, {
559
+ serverOrigin: String(entry.url ?? serverId),
560
+ rpcFn: (req) => rpcFn(req),
561
+ readOnlyTools: readOnlyTools,
562
+ toolEffects: toolEffects,
563
+ resultProjections: Object.fromEntries(Object.entries(object(projectionConfigs)).map(([name, cfg]) => [name, new ResultProjection(cfg)])),
564
+ summary: typeof entry.description === "string" && entry.description ? entry.description : undefined,
565
+ trustUpstreamAnnotations: opts?.trustUpstreamAnnotations,
566
+ taintOnCatalogRead: opts?.taintOnCatalogRead,
567
+ });
568
+ connected[serverId] = await kernel.connectApp(app);
569
+ }
570
+ return connected;
571
+ }
@@ -0,0 +1,16 @@
1
+ import type { AgentKernel } from "../kernel.js";
2
+ export declare function exportToolsOpenAI(kernel: AgentKernel, opts?: {
3
+ query?: string;
4
+ maxTools?: number;
5
+ flat?: boolean;
6
+ }): Array<Record<string, unknown>>;
7
+ export declare function exportToolsAnthropic(kernel: AgentKernel, opts?: {
8
+ query?: string;
9
+ maxTools?: number;
10
+ flat?: boolean;
11
+ }): Array<Record<string, unknown>>;
12
+ export declare function exportToolsGemini(kernel: AgentKernel, opts?: {
13
+ query?: string;
14
+ maxTools?: number;
15
+ flat?: boolean;
16
+ }): Array<Record<string, unknown>>;
@@ -0,0 +1,9 @@
1
+ export function exportToolsOpenAI(kernel, opts) {
2
+ return kernel.exportActiveTools(opts).map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.parameters } }));
3
+ }
4
+ export function exportToolsAnthropic(kernel, opts) {
5
+ return kernel.exportActiveTools(opts).map((t) => ({ name: t.name, description: t.description, input_schema: t.parameters }));
6
+ }
7
+ export function exportToolsGemini(kernel, opts) {
8
+ return kernel.exportActiveTools(opts).map((t) => ({ name: t.name, description: t.description, parameters: t.parameters }));
9
+ }
@@ -0,0 +1,3 @@
1
+ export declare function canonicalJson(value: unknown): string;
2
+ export declare function sha256Hex(text: string): Promise<string>;
3
+ export declare function contentHash(value: unknown): Promise<string>;
@@ -0,0 +1,46 @@
1
+ function compareKeys(left, right) {
2
+ const a = [...left], b = [...right];
3
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
4
+ const difference = a[i].codePointAt(0) - b[i].codePointAt(0);
5
+ if (difference)
6
+ return difference;
7
+ }
8
+ return a.length - b.length;
9
+ }
10
+ function canonicalString(value) {
11
+ if (/[\uD800-\uDFFF]/u.test(value))
12
+ throw new Error("Invalid Unicode string in canonical JSON.");
13
+ return JSON.stringify(value);
14
+ }
15
+ export function canonicalJson(value) {
16
+ if (typeof value === "string")
17
+ return canonicalString(value);
18
+ if (value === null || typeof value !== "object") {
19
+ if (typeof value === "number" && !Number.isFinite(value)) {
20
+ throw new Error("Non-finite numbers are not allowed in canonical JSON.");
21
+ }
22
+ const serialized = JSON.stringify(value);
23
+ if (serialized === undefined)
24
+ throw new Error("Unsupported canonical JSON value.");
25
+ return serialized;
26
+ }
27
+ if (Array.isArray(value))
28
+ return "[" + Array.from(value, (item) => canonicalJson(item ?? null)).join(",") + "]";
29
+ const obj = value;
30
+ return ("{" +
31
+ Object.keys(obj)
32
+ .sort(compareKeys)
33
+ .filter((k) => obj[k] !== undefined)
34
+ .map((k) => canonicalString(k) + ":" + canonicalJson(obj[k]))
35
+ .join(",") +
36
+ "}");
37
+ }
38
+ export async function sha256Hex(text) {
39
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
40
+ return Array.from(new Uint8Array(digest))
41
+ .map((b) => b.toString(16).padStart(2, "0"))
42
+ .join("");
43
+ }
44
+ export async function contentHash(value) {
45
+ return "sha256:" + (await sha256Hex(canonicalJson(value)));
46
+ }
@@ -0,0 +1,11 @@
1
+ export * from "./canonical.js";
2
+ export * from "./types.js";
3
+ export * from "./privacy.js";
4
+ export { ResultProjection } from "./policy.js";
5
+ export * from "./store.js";
6
+ export * from "./apps.js";
7
+ export * from "./state.js";
8
+ export * from "./transport.js";
9
+ export * from "./kernel.js";
10
+ export { PendingCancelled } from "./pending.js";
11
+ export type { PendingStatus, ToolContext } from "./pending.js";