UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

360 lines (359 loc) • 14.8 kB
import { DEFAULT_REQUEST_TIMEOUT_MSEC, SdkError, SdkErrorCode, isJSONRPCErrorResponse, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResultResponse } from "@modelcontextprotocol/client"; import { raceSettlementAgainstSignal } from "./runner/abort-race.js"; import { inlineUntrusted } from "./untrusted-text.js"; import { foreignLine } from "./protocol-http-auth.js"; const CONDITION_MAX = 400; export class McpHostSeatFailure extends Error { delivered; condition; constructor(o) { if (o.delivered !== "no" && o.delivered !== "unknown") throw new TypeError(`McpHostSeatFailure: delivered must be "no" or "unknown"`); if (typeof o.condition !== "string") throw new TypeError("McpHostSeatFailure: condition must be a string"); const condition = foreignLine(o.condition, CONDITION_MAX); super(condition); this.name = "McpHostSeatFailure"; this.delivered = o.delivered; this.condition = condition; } } export function hostSeatVerdictOf(err) { try { if (!(err instanceof McpHostSeatFailure)) return undefined; const { delivered, condition } = err; return (delivered === "no" || delivered === "unknown") && typeof condition === "string" ? Object.freeze({ delivered, condition: foreignLine(condition, CONDITION_MAX) }) : undefined; } catch { return undefined; } } export function hostSeatLine(what, serverLabel, seat, writeTail) { return seat.delivered === "no" ? `${what} was not sent to MCP server "${serverLabel}": ${seat.condition}. The host did not hand the request on, so the server did not execute it; sending it again is safe.` : `${what} on MCP server "${serverLabel}" ended without an outcome the host could report: ${seat.condition}. The request may or may not have executed on the server — the outcome is unknown.${writeTail}`; } export function hostSeatMissing(server) { return Object.assign(new Error(`MCP server "${inlineUntrusted(server, 120)}" is declared with a host-supplied transport, and this leg holds no host seat of that name (RunInternals.mcpHostSeats) — not dialed`), { code: MCP_HOST_SEAT_MISSING }); } export const MCP_HOST_SEAT_MISSING = "config.mcp_host_seat_missing"; export function hostSeatNotHandedLine(servers) { const names = servers.map((s) => `"${inlineUntrusted(s, 120)}"`).join(", "); const many = servers.length > 1; return `Its MCP server${many ? "s" : ""} ${names} ${many ? "are" : "is"} declared with a host-supplied transport, and this leg hands no host seat for ${many ? "them" : "it"} (a leg hands a seat only for a server it declares with a host-supplied transport and holds a seat for) — not dialed on this wake (${MCP_HOST_SEAT_MISSING}).`; } export function hostMount(ms, run) { const bound = ms ?? DEFAULT_REQUEST_TIMEOUT_MSEC; const mount = new AbortController(); const follow = () => mount.abort(run?.reason); const timer = setTimeout(() => mount.abort(new SdkError(SdkErrorCode.RequestTimeout, `the host's pipe did not finish mounting within ${bound} ms`, { timeout: bound })), bound); if (run?.aborted === true) follow(); else run?.addEventListener("abort", follow, { once: true }); return { signal: mount.signal, end: () => { clearTimeout(timer); run?.removeEventListener("abort", follow); }, }; } export async function settledBefore(work, stop) { if (stop === undefined) return work; const raced = await raceSettlementAgainstSignal(work, stop); if (raced.tag === "aborted") throw stop.reason; if (raced.tag === "threw") throw raced.error; return raced.value; } const TAKEN = new WeakMap(); const HOST_SEAT_FAULT = Symbol(); function markSeatFault(err) { try { if (!Object.prototype.hasOwnProperty.call(err, HOST_SEAT_FAULT)) Object.defineProperty(err, HOST_SEAT_FAULT, { value: true }); } catch { } return err; } export function hostSeatFailureOrigin(err) { const verdict = hostSeatVerdictOf(err); if (verdict !== undefined) { if (err[HOST_SEAT_FAULT] === true) return "fault"; return verdict.delivered === "no" ? "refused" : undefined; } if (typeof err === "object" && err !== null && err[HOST_SEAT_FAULT] === true) return "fault"; return undefined; } const refusal = (condition) => markSeatFault(new McpHostSeatFailure({ delivered: "no", condition })); const connectionClosed = () => refusal("the host seat's connection to this leg is closed"); export async function openHostPipe(seat, server, stop) { stop?.throwIfAborted(); let open; try { open = seat.open; } catch { open = undefined; } if (typeof open !== "function") throw refusal("the host seat has no open function, so no pipe was opened"); let opened; try { opened = Promise.resolve(Reflect.apply(open, seat, [Object.freeze({ server, signal: stop ?? new AbortController().signal })])); } catch (thrown) { opened = Promise.reject(thrown); } const raced = stop !== undefined ? await raceSettlementAgainstSignal(opened, stop) : await opened.then((value) => ({ tag: "value", value }), (error) => ({ tag: "threw", error })); if (raced.tag === "aborted") { void opened.then((late) => dropLate(late, server), () => undefined); throw stop.reason; } if (raced.tag === "threw") { const said = hostSeatVerdictOf(raced.error); throw said !== undefined ? new McpHostSeatFailure(said) : refusal("the host seat failed to open a pipe for this dial without saying why"); } return take(raced.value, server); } function take(pipe, server) { if ((typeof pipe !== "object" && typeof pipe !== "function") || pipe === null) throw refusal("the host seat's open handed over something that is not an MCP transport"); const holder = TAKEN.get(pipe); if (holder !== undefined) throw refusal(`the host seat handed over a pipe the dial of MCP server "${inlineUntrusted(holder, 120)}" already took — a pipe serves one dial`); TAKEN.set(pipe, server); const parts = partsOf(pipe); if (typeof parts !== "string") return new TakenPipe(pipe, parts); closeUnwaited(pipe); throw refusal(parts); } const pipeFn = (v) => (typeof v === "function" ? v : undefined); function partsOf(pipe) { try { const t = pipe; const [start, send, close, sessionId, setProtocolVersion, setSupportedProtocolVersions, hasPerRequestStream] = [pipeFn(t["start"]), pipeFn(t["send"]), pipeFn(t["close"]), t["sessionId"], t["setProtocolVersion"], t["setSupportedProtocolVersions"], t["hasPerRequestStream"]]; if (start === undefined || send === undefined || close === undefined) return "the host seat's open handed over something that is not an MCP transport (it needs start, send and close functions)"; if (sessionId !== undefined) return "the host seat's open handed over a pipe that already holds a session, so the server's handshake would be skipped"; return { start, send, close, setProtocolVersion: pipeFn(setProtocolVersion), setSupportedProtocolVersions: pipeFn(setSupportedProtocolVersions), hasPerRequestStream: hasPerRequestStream === true ? true : undefined }; } catch { return "the host seat's open handed over a pipe whose members cannot be read"; } } class TakenPipe { onclose; onerror; onmessage; hasPerRequestStream; #pipe; #parts; #inFlight = new Map(); #ended = false; #closing = false; constructor(pipe, parts) { this.#pipe = pipe; this.#parts = parts; this.hasPerRequestStream = parts.hasPerRequestStream; } async start() { try { const p = this.#pipe; const [heard, ended, failed] = [p.onmessage, p.onclose, p.onerror]; p.onmessage = (message, extra) => { heard?.(message, extra); if (this.#ended) return; if ((isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) && this.#inFlight.has(message.id)) this.#inFlight.set(message.id, true); this.onmessage?.(message, extra); }; p.onclose = () => { ended?.(); this.#end(); }; p.onerror = (error) => { failed?.(error); this.onerror?.(error); }; } catch { throw refusal("the host's pipe would not take the engine's callbacks"); } try { await Reflect.apply(this.#parts.start, this.#pipe, []); } catch (err) { if (typeof err === "object" && err !== null && hostSeatVerdictOf(err) === undefined) markSeatFault(err); throw err; } } async send(message, options) { if (this.#ended) throw connectionClosed(); if (!isJSONRPCRequest(message)) { try { await Reflect.apply(this.#parts.send, this.#pipe, [message, options]); return; } catch (err) { if (typeof err === "object" && err !== null && hostSeatVerdictOf(err) === undefined) markSeatFault(err); throw err; } } const id = message.id; this.#inFlight.set(id, false); try { await Reflect.apply(this.#parts.send, this.#pipe, [message, options]); } catch (err) { if (this.#inFlight.get(id) !== true) { if (typeof err === "object" && err !== null && hostSeatVerdictOf(err) === undefined) markSeatFault(err); throw err; } } finally { this.#inFlight.delete(id); } } async close() { if (!this.#closing) { this.#closing = true; closeUnwaited(this.#pipe, this.#parts.close); } this.#end(); } setProtocolVersion(version) { if (this.#parts.setProtocolVersion !== undefined) Reflect.apply(this.#parts.setProtocolVersion, this.#pipe, [version]); } setSupportedProtocolVersions(versions) { if (this.#parts.setSupportedProtocolVersions !== undefined) Reflect.apply(this.#parts.setSupportedProtocolVersions, this.#pipe, [versions]); } #end() { if (this.#ended) return; this.#ended = true; this.onclose?.(); } } function dropLate(late, server) { if ((typeof late !== "object" && typeof late !== "function") || late === null || TAKEN.has(late)) return; TAKEN.set(late, server); closeUnwaited(late); } function closeUnwaited(pipe, close) { try { const fn = close ?? pipeFn(pipe["close"]); if (fn !== undefined) void Promise.resolve(Reflect.apply(fn, pipe, [])).catch(() => undefined); } catch { } } export function hostSeatOfRequests(seat) { return { open: ({ server }) => new RequestSeatPipe(seat, server) }; } function failureOfThrown(thrown) { const said = hostSeatVerdictOf(thrown); return said !== undefined ? new McpHostSeatFailure(said) : markSeatFault(new McpHostSeatFailure({ delivered: "unknown", condition: "the host seat failed without saying whether it handed the request on" })); } function responseOf(id, raw) { let answer; try { answer = JSON.parse(JSON.stringify(raw) ?? "null"); } catch { answer = undefined; } const member = (name) => (typeof answer === "object" && answer !== null && Object.hasOwn(answer, name) ? answer[name] : undefined); const result = member("result"); const candidate = result !== undefined ? { jsonrpc: "2.0", id, result } : { jsonrpc: "2.0", id, error: member("error") }; if (isJSONRPCResultResponse(candidate) || isJSONRPCErrorResponse(candidate)) return candidate; return markSeatFault(new McpHostSeatFailure({ delivered: "unknown", condition: "the host seat answered something the protocol cannot carry as a result or an error" })); } class RequestSeatPipe { seat; serverName; onclose; onerror; onmessage; inFlight = new Map(); closed = false; constructor(seat, serverName) { this.seat = seat; this.serverName = serverName; } async start() { } async send(message) { if (isJSONRPCNotification(message)) { if (message.method === "notifications/cancelled") { const id = message.params?.requestId; const held = typeof id === "string" || typeof id === "number" ? this.inFlight.get(id) : undefined; if (held !== undefined) { this.inFlight.delete(id); held.abort(new Error("the engine cancelled the request")); } } return; } if (!isJSONRPCRequest(message)) return; const { id, method } = message; const params = (message.params ?? {}); if (method === "initialize") { const protocolVersion = params["protocolVersion"]; return this.deliver({ jsonrpc: "2.0", id, result: { protocolVersion, capabilities: { tools: {} }, serverInfo: { name: this.serverName, version: "" } } }); } if (this.closed) throw connectionClosed(); if (method !== "tools/list" && method !== "tools/call") throw new McpHostSeatFailure({ delivered: "no", condition: `the host seat carries tools/list and tools/call only, and ${inlineUntrusted(method, 80)} was not handed on` }); const stop = new AbortController(); this.inFlight.set(id, stop); let answered; try { answered = responseOf(id, await this.seat.request(method, params, stop.signal)); } catch (thrown) { answered = failureOfThrown(thrown); } if (this.inFlight.get(id) !== stop) return; this.inFlight.delete(id); if (answered instanceof McpHostSeatFailure) throw answered; this.deliver(answered); } async close() { if (this.closed) return; this.closed = true; const held = [...this.inFlight.values()]; this.inFlight.clear(); for (const stop of held) stop.abort(new Error("the connection to the host seat closed")); this.onclose?.(); } deliver(message) { queueMicrotask(() => this.onmessage?.(message)); } }