UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

331 lines (330 loc) • 15.5 kB
import { ProtocolError, SdkError, SdkErrorCode, SdkHttpError } from "@modelcontextprotocol/client"; import { proxyTunnelRefusedSentence, readConnectFailure } from "../brain/errors.js"; import { PeerAuthorizationRefused, PeerSeatFailure } from "./peer-seat.js"; import { ProtocolRevokedRefusal } from "./protocol-revocation.js"; import { readMember, thrownIs } from "./thrown-value.js"; import { hostSeatVerdictOf } from "./mcp-host-seat.js"; import { McpReplyOverReadBound } from "./mcp-read-bound.js"; import { engineTextFor } from "../prompt-assembly/engine-text.js"; export const MCP_FAILURE_KINDS = Object.freeze([ "connect_refused", "connection_failed", "connection_closed", "unauthorized", "http_status", "not_mcp_response", "spawn_failed", "timeout", "protocol", "invalid_config", "credential_unavailable", "host_refused", "revoked", "unknown", ]); export const MCP_AUTHORIZATION_REASONS = Object.freeze(["rejected", "scope", "none", "seat_unavailable"]); export function owesAuthorization(a) { return a.reason !== "seat_unavailable"; } export const MCP_DELIVERY_VERDICTS = Object.freeze(["yes", "no", "unknown"]); export const DELIVERED_BY_KIND = { connect_refused: "no", connection_failed: "unknown", connection_closed: "unknown", unauthorized: "unknown", http_status: "unknown", not_mcp_response: "unknown", spawn_failed: "no", timeout: "unknown", protocol: "yes", invalid_config: "no", credential_unavailable: "no", host_refused: "no", revoked: "unknown", unknown: "unknown", }; export const MCP_LIVENESS_STATES = Object.freeze(["reachable", "unreachable", "unknown"]); export const LIVENESS_BY_FAILURE_KIND = { connect_refused: "unreachable", connection_failed: "unreachable", connection_closed: "unreachable", unauthorized: "unknown", http_status: "unknown", not_mcp_response: "unknown", spawn_failed: "unreachable", timeout: "unreachable", protocol: "reachable", invalid_config: undefined, credential_unavailable: undefined, host_refused: undefined, revoked: undefined, unknown: "unknown", }; export function livenessOf(outcome, observedAt) { if (outcome === "completed") return { state: "reachable", observedAt }; if (outcome === "unsent") return undefined; const state = LIVENESS_BY_FAILURE_KIND[outcome]; if (state === undefined) return undefined; return state === "unreachable" ? { state, observedAt, errorCode: outcome } : { state, observedAt }; } const CONNECT_KEEPS_THE_TABLE_VERDICT = new Set(["protocol", "http_status", "unauthorized"]); export function failureFields(of) { const kind = "kind" in of ? of.kind : of.errorCode; if (kind === undefined) return {}; return { errorCode: kind, ...(of.delivered !== undefined ? { delivered: of.delivered } : {}), ...(of.httpStatus !== undefined ? { httpStatus: of.httpStatus } : {}), ...(of.authorization !== undefined ? { authorization: { ...of.authorization } } : {}), }; } export function failureClassLine(of) { if (of.errorCode === undefined) return {}; const word = of.errorCode === "unauthorized" && of.authorization !== undefined ? of.authorization.reason : of.errorCode; return { error: `(${of.httpStatus !== undefined ? `${word} ${of.httpStatus}` : word})`, classLine: true }; } const NETWORK_CODES_NEVER_DELIVERED = new Set([ "ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT", ]); export function networkErrorCode(err, depth = 0) { if (depth > 5 || !(err instanceof Error)) return undefined; const code = err instanceof SdkError ? undefined : err.code; if (typeof code === "string" && /^(?:E[A-Z_]+|UND_ERR_[A-Z_]+)$/.test(code)) return code; if (err instanceof AggregateError) { for (const inner of err.errors) { const found = networkErrorCode(inner, depth + 1); if (found !== undefined) return found; } } return networkErrorCode(err.cause, depth + 1); } const isNodeErrCode = (code) => code.startsWith("ERR_"); const isDeclarationFault = (code) => code === "ERR_INVALID_URL" || (typeof code === "string" && code.startsWith("config.")); export const SDK_ERROR_READINGS = { [SdkErrorCode.NotConnected]: { kind: "connection_closed", unsent: true }, [SdkErrorCode.AlreadyConnected]: { kind: "unknown" }, [SdkErrorCode.NotInitialized]: { kind: "unknown" }, [SdkErrorCode.CapabilityNotSupported]: { kind: "unknown" }, [SdkErrorCode.RequestTimeout]: { kind: "timeout" }, [SdkErrorCode.ConnectionClosed]: { kind: "connection_closed" }, [SdkErrorCode.SendFailed]: { kind: "unknown" }, [SdkErrorCode.InvalidResult]: { kind: "protocol" }, [SdkErrorCode.UnsupportedResultType]: { kind: "protocol" }, [SdkErrorCode.InputRequiredRoundsExceeded]: { kind: "protocol" }, [SdkErrorCode.ListPaginationExceeded]: { kind: "protocol" }, [SdkErrorCode.MethodNotSupportedByProtocolVersion]: { kind: "protocol", unsent: true }, [SdkErrorCode.EraNegotiationFailed]: { kind: "unknown" }, [SdkErrorCode.ClientHttpNotImplemented]: "status", [SdkErrorCode.ClientHttpAuthentication]: { kind: "unauthorized", reason: "rejected" }, [SdkErrorCode.ClientHttpForbidden]: { kind: "unauthorized", reason: "scope" }, [SdkErrorCode.ClientHttpUnexpectedContent]: { kind: "not_mcp_response" }, [SdkErrorCode.ClientHttpFailedToOpenStream]: "status", [SdkErrorCode.ClientHttpFailedToTerminateSession]: "status", }; function httpStatusClass(err) { const status = err instanceof SdkHttpError ? err.status : undefined; if (status === 401) return { kind: "unauthorized", authorization: { reason: "rejected" } }; return typeof status === "number" && Number.isInteger(status) && status > 0 ? { kind: "http_status", httpStatus: status } : { kind: "not_mcp_response" }; } function sdkErrorClass(err) { const reading = SDK_ERROR_READINGS[err.code]; if (reading === undefined) return { kind: "unknown" }; if (reading === "status") return httpStatusClass(err); if (reading.kind === "unauthorized") return { kind: "unauthorized", authorization: { reason: reading.reason } }; return { kind: reading.kind, ...(reading.unsent === true ? { unsent: true } : {}) }; } export const FAILURE_CLASSIFIER = [ { name: "revocation ledger withdrew the declaration", when: (err) => err instanceof ProtocolRevokedRefusal, reads: (err) => ({ kind: "revoked", ...(err.afterSentHop ? {} : { unsent: true }) }), }, { name: "peer seat answered the principal is not authorized", when: (err) => err instanceof PeerSeatFailure && err.reason === "unauthorized", reads: (err) => ({ kind: "unauthorized", authorization: authorizationOf("none", err.authorizeUrl, undefined), unsent: true }), }, { name: "peer seat did not furnish the request", when: (err) => err instanceof PeerSeatFailure, reads: () => ({ kind: "credential_unavailable", unsent: true }), }, { name: "http endpoint refused the authorization", when: (err) => err instanceof PeerAuthorizationRefused, reads: (err) => { const refused = err; return { kind: "unauthorized", authorization: authorizationOf(refused.reason, refused.authorizeUrl, refused.resourceMetadataUrl) }; }, }, { name: "host seat did not carry the request", when: (err) => hostSeatVerdictOf(err) !== undefined, reads: (err) => ({ kind: hostSeatVerdictOf(err)?.delivered === "no" ? "host_refused" : "unknown" }), }, { name: "reply over the stdio read bound", when: (err) => err instanceof McpReplyOverReadBound, reads: () => ({ kind: "protocol" }), }, { name: "sdk error read by its code", when: (err) => err instanceof SdkError, reads: (err) => sdkErrorClass(err), }, { name: "server answered with a protocol error", when: (err) => err instanceof ProtocolError, reads: () => ({ kind: "protocol" }), }, { name: "malformed declaration", when: (err, at) => at.phase === "connect" && err instanceof Error && isDeclarationFault(err.code), reads: () => ({ kind: "invalid_config" }), }, { name: "proxy refused the tunnel", when: (err) => readConnectFailure(err).proxyRefusal !== undefined, reads: () => ({ kind: "connect_refused" }), }, { name: "node error code, not a network errno", when: (err) => { const code = networkErrorCode(err); return code !== undefined && isNodeErrCode(code); }, reads: () => ({ kind: "unknown" }), }, { name: "stdio spawn failed", when: (err, at) => at.phase === "connect" && at.transport === "stdio" && networkErrorCode(err) !== undefined, reads: () => ({ kind: "spawn_failed" }), }, { name: "connect-phase errno", when: (err) => { const code = networkErrorCode(err); return code !== undefined && NETWORK_CODES_NEVER_DELIVERED.has(code); }, reads: () => ({ kind: "connect_refused" }), }, { name: "network errno past the connect phase", when: (err) => networkErrorCode(err) !== undefined, reads: () => ({ kind: "connection_failed" }), }, { name: "no structure", when: () => true, reads: () => ({ kind: "unknown" }), }, ]; export function classifyMcpFailure(err, at) { return readMcpFailure(err, at).failure; } export function lostInFlight(err, at) { const failure = classifyMcpFailure(err, at); return failure.kind === "connection_closed" && failure.delivered === "unknown"; } export function readMcpFailure(err, at) { const { unsent, ...read } = classOf(err, at); const dialled = at.phase === "connect" && !CONNECT_KEEPS_THE_TABLE_VERDICT.has(read.kind); return { failure: { ...read, delivered: unsent === true || dialled ? "no" : DELIVERED_BY_KIND[read.kind] }, exchange: unsent === true ? "unsent" : read.kind }; } function authorizationOf(reason, authorizeUrl, resourceMetadataUrl) { return { reason, ...(authorizeUrl !== undefined ? { authorizeUrl } : {}), ...(resourceMetadataUrl !== undefined ? { resourceMetadataUrl } : {}) }; } export const authorizationPlace = (say = engineTextFor()) => say("core/engine.mcp-authorization-place"); export function needsAuthorizationArm(entries, max, say = engineTextFor()) { const named = entries.filter((f) => f.authorization !== undefined); if (named.length === 0) return undefined; const lines = named.slice(0, max).map((f) => f.name); const more = named.length > max ? `\n${say("core/event.mcp-unavailable.more", { count: String(named.length - max) })}` : ""; return say("core/event.mcp-unavailable.needs-authorization", { servers: `${lines.join("\n")}${more}`, where: authorizationPlace(say) }); } const SEAT_UNAVAILABLE_SENTENCE = "the server refused the request (HTTP 401) and the credential seat could not answer"; export function unauthorizedLine(what, serverLabel, a, renewed, writeTail) { const owed = `${userMustAuthorize(a.reason)}; its capability is unavailable until they do. Do not ask the user for authorization codes, tokens, or callback URLs.`; if (a.reason === "none") return `${what} was not sent to MCP server "${serverLabel}": the deployment holds no authorization of this user for it. ${owed} The request was not delivered, so the server did not execute it.`; if (a.reason === "seat_unavailable") return `${what} on MCP server "${serverLabel}": ${SEAT_UNAVAILABLE_SENTENCE}. This is the deployment's credential seat, not the server — do not retry the call until it is fixed; use an alternative if one exists. Do not ask the user for authorization codes, tokens, or callback URLs.${writeTail}`; const refused = `${what} on MCP server "${serverLabel}" was refused ${a.reason === "scope" ? "for insufficient scope (HTTP 403)" : "as unauthorized (HTTP 401)"}`; return renewed ? `${refused}; the deployment has since answered another credential, which a new call carries — this call was not sent again. If that call is refused too: ${owed}${writeTail}` : `${refused}. ${owed}${writeTail}`; } export const userMustAuthorize = (reason) => `The user needs to authorize this server${reason === "scope" ? " for the access this request needs" : ""} ${authorizationPlace()}`; export const authorizationClause = (a) => owesAuthorization(a) ? userMustAuthorize(a.reason) : `${SEAT_UNAVAILABLE_SENTENCE.charAt(0).toUpperCase()}${SEAT_UNAVAILABLE_SENTENCE.slice(1)}`; export function authorizationOwed(err) { const read = classOf(err, { phase: "request" }); return read.kind === "unauthorized" ? read.authorization : undefined; } function classOf(err, at) { for (const rule of FAILURE_CLASSIFIER) if (rule.when(err, at)) return rule.reads(err); return { kind: "unknown" }; } function answersLostSession(read, at) { return at.phase === "request" && at.session === true && read.kind === "http_status" && read.httpStatus === 404; } export function describeHttpTransportFailure(err, at = { phase: "request" }) { const f = classifyMcpFailure(err, at); switch (f.kind) { case "http_status": return { condition: sessionGone(err, at) ? LOST_SESSION : `its HTTP endpoint answered ${f.httpStatus} instead of an MCP response`, delivered: f.delivered, httpStatus: f.httpStatus, }; case "not_mcp_response": return { condition: "its HTTP endpoint answered something that is not an MCP response", delivered: f.delivered }; case "connect_refused": { const proxy = readConnectFailure(err).proxyRefusal; return { condition: `its HTTP endpoint could not be reached (${proxy !== undefined ? proxyTunnelRefusedSentence(proxy.status) : networkErrorCode(err)})`, delivered: f.delivered, }; } case "connection_failed": return { condition: `the connection to its HTTP endpoint failed (${networkErrorCode(err)})`, delivered: f.delivered }; case "connection_closed": case "unauthorized": case "spawn_failed": case "timeout": case "protocol": case "invalid_config": case "credential_unavailable": case "host_refused": case "revoked": case "unknown": return undefined; } } export function sessionGone(err, at) { return answersLostSession(classOf(err, at), at); } export const LOST_SESSION = "the server reported the session the request was sent on gone (its HTTP endpoint answered 404 to the session id it issued)"; export function namingLostSession(err, at, text) { return sessionGone(err, at) ? `${LOST_SESSION}: ${text}` : text; } export function isCallerAbortReading(err, signal) { return signal?.aborted === true && thrownIs(err, SdkError) && readMember(err, "code") === SdkErrorCode.RequestTimeout && readMember(err, "data") === undefined; }