UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

260 lines (259 loc) • 18.5 kB
import { Type } from "typebox"; import { NO_DECLARED_MCP_READ_PORTS, listedNamesOf, materializeLegMcpTools, mcpFirstRequestWaitMs } from "../mcp.js"; import { applyMcpRosterDelta, commitMcpRosterChanges, redialMcpServer, rosterHolding, settledOnRoster, takeLateMcpLandings } from "./mcp-redial.js"; import { valveLeaves, valveLeavesPeer } from "../../agents/tool-filter.js"; import { mcpServerReached } from "../mounted-mcp.js"; import { cardDriftNotices, materializeLegA2aTools } from "../a2a.js"; import { revocationProbe } from "../protocol-revocation.js"; import { authorizationPlace } from "../mcp-failure.js"; import { endMcpServerUnavailable, mcpServerConnectingNotice, mcpServerUnavailableNotice } from "../mcp-server-unavailable-notice.js"; import { inMemoryNoticeTold } from "./announce-once-ledger.js"; import { judgeEntryNameBound } from "../locked-config.js"; import { deliverEngineNotice } from "../types.js"; import { isolationScopeOf } from "../isolation-scope.js"; import { RosterBuilder } from "../tool-roster.js"; import { REFRESH_MCP_TOOLS_TOOL_NAME, mountRuleFace, toolFace } from "../tool-catalog-entries.js"; import { MCP_NAMESPACE, A2A_NAMESPACE, mintNamespacePrefix } from "@sema-agent/primitives"; import { announceA2aUndeclaredToolAxes, applyMcpToolFaces } from "./tool-face-overlay.js"; import { sectionDisposerOf } from "../prompt-section-seat.js"; import { thrownText } from "../thrown-value.js"; import { inlineUntrusted } from "../untrusted-text.js"; import { transportKindOf } from "../mcp-server-spec.js"; import { credentialEchoNotice } from "../credential-echo.js"; import { mcpBinaryKeptSeat } from "./tool-result-media-seat.js"; import { refusalAbout } from "../config-refusal-input.js"; import { plaintextOriginsOf } from "../plaintext-origins-seat.js"; export async function prepareProtocolTools(input) { const { lockedPreflight, hostFloor, spec, deps, mcpPool, reminderMark, reminderDisclosureCounts, runId, sessionId, onceLedger, roster, rosterSeat, remoteToolOffload, toolResultBytes, toolFaceSnapshot, toolEffects, axisExplicitNegatives, irreversibilityTier, irreversibleTools, egressTools, toolMarkSources, abortController, rollback, enrichSpecToolCtx } = input; const markedBy = (name, source) => { const set = toolMarkSources.get(name); if (set !== undefined) set.add(source); else toolMarkSources.set(name, new Set([source])); }; for (const server of lockedPreflight.mcp ?? []) { const bound = judgeEntryNameBound(server); if (!bound.ok) throw refusalAbout("taskConfig", bound.error); } const serverReached = valveLeavesPeer(toolFaceSnapshot.selector); const mcpReached = mcpServerReached(valveLeaves(toolFaceSnapshot.selector), serverReached); const revocations = legRevocationProbe(deps, runId); const noticeLeg = { sessionId: mcpPool?.pool.sessionId ?? sessionId, runId }; const tellWarning = (w, statuses) => { onceLedger.onError(w, { phase: "mcp", sessionId }); const notice = mcpServerUnavailableNotice(w, statuses, noticeLeg); if (notice !== undefined) deliverEngineNotice(deps.onNotice, notice, undefined, onceLedger.told); }; const mcpWait = legMcpWait(deps, onceLedger.told, noticeLeg, tellWarning); const mcp = lockedPreflight.mcp?.length ? await materializeLegMcpTools(input.mcpRequestMeta, input.onSubtreeActivity, lockedPreflight.mcp, spec.principal, deps.onElicit, undefined, { reminderMark, counts: reminderDisclosureCounts }, revocations, mcpPool === undefined ? undefined : { pool: mcpPool.pool, ownsPool: mcpPool.owned, ...poolPartition(spec) }, sectionDisposerOf(input.modBus, abortController.signal), (entry) => mcpReached(entry.name), AbortSignal.any([abortController.signal, ...(spec.signal !== undefined ? [spec.signal] : [])]), hostFloor, deps.peerSeat, mcpAuthorizationNotice(deps, sessionId, runId, spec.principal), input.mcpHostSeats, credentialEchoNotice(deps.onNotice, sessionId, runId, "mcp"), { ...toolResultBytes, onKept: mcpBinaryKeptSeat(deps.onNotice, { sessionId, runId }, toolResultBytes.store !== undefined) }, deps.onNotice, mcpWait, plaintextOriginsOf(deps)) : { tools: [], toolAxes: [], warnings: [], serverInstructions: [], instructionsDelta: { pendingAdds: [], pendingRemovals: [] }, droppedTools: [], statuses: [], refresh: async () => [], reconnect: async (server) => ({ server, prefix: mintNamespacePrefix(MCP_NAMESPACE, server), outcome: "not_declared", reason: "this task declared no MCP servers", toolCount: 0, added: [], removed: [] }), ...NO_DECLARED_MCP_READ_PORTS, dispose: async () => { } }; if (lockedPreflight.mcp?.length) rollback.push(function mcpDispose() { return mcp.dispose(); }); endMcpServerUnavailable(onceLedger.told, mcp.statuses, mcp.warnings); for (const w of mcp.warnings) tellWarning(w, mcp.statuses); for (const name of input.mcpHostSeats?.keys() ?? []) { if (lockedPreflight.mcp?.some((s) => s.name === name && transportKindOf(s) === "host") !== true) onceLedger.onError(Object.assign(new Error(`mcp: this leg holds a host seat named "${inlineUntrusted(name, 120)}" and declares no MCP server of that name with a host-supplied transport — nothing is mounted through it`), { code: "config.mcp_host_seat_undeclared" }), { phase: "mcp", sessionId }); } for (const d of mcp.droppedTools) { onceLedger.onError(new Error(`MCP tool dropped at intake — ${d.tool} (server "${d.server}"): ${d.reason}`), { phase: "mcp", sessionId }); } onceLedger.pruneDroppedTools(mcp.droppedTools); { const callerNames = new Set((spec.tools ?? []).flatMap((t) => [t.name, ...(t.aliases ?? [])])); const clash = mcp.tools.find((t) => [t.name, ...(t.aliases ?? [])].some((name) => callerNames.has(name))); if (clash) { const e = new Error(`Tool name "${clash.name}" is reserved by an injected MCP tool — a caller tool of the same name would silently shadow it.`); e.code = "config.reserved_tool_name"; throw refusalAbout("taskConfig", e); } } const faceAnnounced = new Set(); const withFaces = (tools, serverName, listed) => { const server = (lockedPreflight.mcp ?? []).find((s) => s.name === serverName); return server === undefined ? [...tools] : applyMcpToolFaces({ tools, server, ...(listed !== undefined ? { listed } : {}), onNotice: deps.onNotice, onError: deps.onError, announced: faceAnnounced, sessionId: sessionId ?? "", runId }); }; { const servers = (lockedPreflight.mcp ?? []).map((s) => ({ name: s.name, prefix: mintNamespacePrefix(MCP_NAMESPACE, s.name) })); const faced = new Map(); for (const server of servers) { if (mcp.pending?.names().includes(server.name) === true) continue; const own = mcp.tools.filter((x) => x.name.startsWith(server.prefix)); for (const t of withFaces(own, server.name, listedNamesOf(mcp.statuses.find((s) => s.name === server.name)))) faced.set(t.name, t); } for (const t of mcp.tools) { const server = servers.find((s) => t.name.startsWith(s.prefix)); const mounted = server === undefined ? t : faced.get(t.name); if (mounted === undefined) continue; const member = remoteToolOffload(mounted); if (roster.mounts.judgeMember(server === undefined ? "mcp-resources" : "mcp", member)) roster.mount(member, { source: "mcp", mountedBy: "optional", origin: { peer: server?.name ?? MCP_NAMESPACE.parse(t.name)?.peer ?? t.name } }); } } const rebuildHarnessToolsRef = {}; const contentOriginWrapRef = {}; const toolCallGateArmedRef = { armed: false }; const rosterApply = { toolFaceSnapshot, withFaces, remoteToolOffload, foldProtocolAxes: (axes, label) => foldProtocolAxes(axes, label), toolEffects, axisExplicitNegatives, roster, declared: lockedPreflight.mcp ?? [], instructionsDelta: mcp.instructionsDelta }; const rosterCommit = { rebuildHarnessToolsRef, rosterSeat, toolCallGateArmedRef, irreversibleTools, egressTools }; const redialInput = { ...rosterApply, ...rosterCommit, mcp, deps, sessionId, runId, irreversibilityTier, told: onceLedger.told, warnOnce: (w) => onceLedger.onError(w, { phase: "mcp", sessionId }) }; takeLateMcpLandings(redialInput, lockedPreflight.mcp ?? [], tellWarning); roster.mounts.know({ "spec.mcp": (lockedPreflight.mcp?.length ?? 0) > 0 }); const mcpRedial = roster.mounts.holds("refresh-mcp-tools") ? (server) => redialMcpServer(redialInput, server) : undefined; if (roster.mounts.judge("refresh-mcp-tools")) { roster.mount({ ...toolFace("refresh-mcp-tools"), ...{ ruleFace: mountRuleFace("refresh-mcp-tools") }, name: REFRESH_MCP_TOOLS_TOOL_NAME, label: REFRESH_MCP_TOOLS_TOOL_NAME, description: "Refresh the tool list of connected MCP servers. Never dials or re-dials connections — it only re-reads the tool list over the existing connection. The refreshed tools are available immediately; you can call them on your next step. Use when a server's expected tool is missing, or the tool list looks stale after a connection recovered. Omit `server` to refresh every connected server.", parameters: Type.Object({ server: Type.Optional(Type.String({ description: "Name of a single MCP server to refresh; omit to refresh all connected servers." })), }), execute: async (_toolCallId, params) => { const serverArg = params?.server; const results = await mcp.refresh(typeof serverArg === "string" && serverArg.length > 0 ? serverArg : undefined); const lines = []; let changed = false; let anyActiveFailure = false; let anyRefreshed = false; const reported = []; for (const r of results) { if (r.tools === undefined) { reported.push(settledOnRoster(r, rosterHolding(rosterApply, r.server), roster)); lines.push(`${r.server}: ${r.status}${r.error !== undefined ? ` (${r.error})` : ""}`); if (r.status === "failed") anyActiveFailure = true; continue; } const applied = applyMcpRosterDelta(rosterApply, { server: r.server, prefix: r.prefix, tools: r.tools, axes: r.axes ?? [], dropped: r.dropped ?? [], listed: listedNamesOf(r), ...(r.instructions !== undefined ? { instructions: r.instructions } : {}) }); const settled = settledOnRoster(r, applied, roster); if (!applied.applied) { const { listingIncomplete: _incomplete, instructions: _instructions, ...entry } = settled; reported.push({ ...entry, status: "failed", error: applied.refusal }); lines.push(`${r.server}: failed (${applied.refusal})`); anyActiveFailure = true; changed = true; continue; } reported.push(settled); changed = true; anyRefreshed = true; const detail = []; if (applied.added.length > 0) detail.push(`added: ${applied.added.join(", ")}`); if (applied.removed.length > 0) detail.push(`removed: ${applied.removed.join(", ")}`); if (applied.excluded.length > 0) detail.push(`excluded by deployment config (not mounted): ${applied.excluded.join(", ")}`); if ((r.dropped?.length ?? 0) > 0) detail.push(`dropped: ${r.dropped.map((d) => `${d.tool} (${d.reason.length > 90 ? `${d.reason.slice(0, 90)}…` : d.reason})`).join("; ")}`); lines.push(`${r.server}: refreshed — ${applied.mounted.length} tool${applied.mounted.length === 1 ? "" : "s"}${detail.length > 0 ? ` (${detail.join("; ")})` : ""}`); } if (changed) { const ungated = await commitMcpRosterChanges(rosterCommit); if (ungated !== undefined) lines.push(ungated); } const text = lines.length === 0 ? "No connected MCP servers to refresh." : lines.join("\n"); return { content: [{ type: "text", text }], details: { results: reported }, terminate: false, ...(anyActiveFailure && !anyRefreshed ? { isError: true } : {}), }; }, }, { source: "builtin", mountedBy: "optional", followsDial: true }); } const foldProtocolAxes = (axes, protocolLabel) => { const source = protocolLabel === "A2A" ? "a2a_default" : "mcp_annotation"; for (const axis of axes) { if (axis.irreversibility === "always") { irreversibilityTier.set(axis.name, "always"); irreversibleTools.add(axis.name); markedBy(axis.name, source); } if (axis.irreversibility === "never") { axisExplicitNegatives.set(axis.name, { ...axisExplicitNegatives.get(axis.name), irreversible: false }); } if (axis.egress === false) { axisExplicitNegatives.set(axis.name, { ...axisExplicitNegatives.get(axis.name), egress: false }); } if (axis.egress) { if (axis.effect !== undefined && axis.effect !== "write") { const e = new Error(`${protocolLabel} tool "${axis.name}" resolves to egress:true with effect:"${axis.effect}" — an egress tool (external write) must have effect:"write". Clear egress (toolAxes egress:false) if it is a pure read, or set effect:"write".`); e.code = "config.egress_requires_write_effect"; throw refusalAbout("taskConfig", e); } egressTools.add(axis.name); markedBy(axis.name, source); } if (axis.effect !== undefined && !toolEffects.has(axis.name)) toolEffects.set(axis.name, axis.effect); } }; foldProtocolAxes(mcp.toolAxes, "MCP"); const a2aDeclared = lockedPreflight.a2a; const a2a = a2aDeclared ? await materializeLegA2aTools(revocations, a2aDeclared, spec.principal, abortController.signal, hostFloor, deps.peerSeat, credentialEchoNotice(deps.onNotice, sessionId, runId, "a2a"), (entry) => serverReached(mintNamespacePrefix(A2A_NAMESPACE, entry.name)), deps.a2a?.isolatePeers === true, enrichSpecToolCtx, deps) : { tools: [], toolAxes: [], warnings: [], statuses: [], refresh: async () => [], dispose: async () => { } }; if (a2aDeclared) rollback.push(function a2aDispose() { return a2a.dispose(); }); for (const w of a2a.warnings) deps.onError?.(w, { phase: "a2a", sessionId }); for (const notice of cardDriftNotices(a2a.statuses, sessionId, runId)) deliverEngineNotice(deps.onNotice, notice, undefined, onceLedger.told); if (a2aDeclared !== undefined) announceA2aUndeclaredToolAxes({ peers: a2aDeclared, statuses: a2a.statuses, onNotice: deps.onNotice, announced: faceAnnounced, sessionId: sessionId ?? "", runId }); { const callerNames = new Set((spec.tools ?? []).flatMap((t) => [t.name, ...(t.aliases ?? [])])); const clash = a2a.tools.find((t) => callerNames.has(t.name)); if (clash) { const e = new Error(`Tool name "${clash.name}" is reserved by an injected A2A tool — a caller tool of the same name would silently shadow it.`); e.code = "config.reserved_tool_name"; throw refusalAbout("taskConfig", e); } } for (const t of a2a.tools) { const member = remoteToolOffload(t); if (roster.mounts.judgeMember("a2a", member)) roster.mount(member, { source: "a2a", mountedBy: "optional", origin: { peer: A2A_NAMESPACE.parse(t.name)?.peer ?? t.name } }); } foldProtocolAxes(a2a.toolAxes, "A2A"); return { mcp, a2a, rebuildHarnessToolsRef, contentOriginWrapRef, toolCallGateArmedRef, ...(mcpRedial !== undefined ? { mcpRedial } : {}) }; } function poolPartition(spec) { const isolationScope = isolationScopeOf(spec); return isolationScope !== undefined ? { isolationScope } : {}; } function mcpAuthorizationNotice(deps, sessionId, runId, principal) { return (server, { reason, authorizeUrl }) => deliverEngineNotice(deps.onNotice, { code: "mcp.authorization_required", message: `MCP server "${server}" needs the user's authorization before it serves them (${reason}) — authorize it ${authorizationPlace()}; its tools are unavailable until then.`, detail: { server, reason, ...(authorizeUrl !== undefined ? { authorizeUrl } : {}), ...(principal !== undefined ? { principal } : {}), sessionId, runId }, }); } function legRevocationProbe(deps, runId) { return revocationProbe(deps.protocolRevocations, (e) => deliverEngineNotice(deps.onNotice, { code: "protocol.revocation_probe_failed", message: `the protocolRevocations.revoked probe failed — requests to MCP servers and to A2A peers outside the trust boundary go out as if nothing were revoked, and an A2A peer registered inside the trust boundary is sent nothing (its calls answer a2a.revocation_unreadable), until it recovers: ${thrownText(e)}`, detail: { message: thrownText(e), runId }, })); } function legMcpWait(deps, told, leg, tellWarning) { const budgetMs = mcpFirstRequestWaitMs(deps.mcpFirstRequestWaitMs); const waitTold = inMemoryNoticeTold(); return { ...(budgetMs !== undefined ? { budgetMs } : {}), connecting: { tell: (server, waitedMs, boundMs) => deliverEngineNotice(deps.onNotice, mcpServerConnectingNotice(server, waitedMs, boundMs, leg), undefined, waitTold) }, unheard: (warning, status) => (endMcpServerUnavailable(told, [status], [warning]), tellWarning(warning, [status])), }; }