UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

234 lines (233 loc) • 18 kB
/** * How a tool call finds its server's connection. The connection under a server is not for life: a re-dial replaces it — at the host's * request, or because the server dropped the session a call was sent on (`sessionGone`) — and the tools already mounted keep reaching * the server. One rule decides where a mounted tool may be sent ({@link reach}): only on the server's LIVE connection, and only while the * latest listing taken on that connection — by this leg or by another holder of a pooled one — through this leg's intake, mints the tool * the gate it was mounted with (mcp-listing-drift.ts). The listing is compared, never adopted: the leg's roster stays the leg's own. No connection ⇒ the * server is down; another gate ⇒ the tool is refused before it runs, until a re-dial or refresh re-folds the roster. Neither the connection * a tool was minted around nor whoever opened the re-dial that replaced it enters the answer. * * A call that finds its session gone recovers once ({@link callThroughLink}). The re-dials of a server go one at a time ({@link Flights}): * a host verb that finds one running is refused; a call joins the one running, and starts one only for the connection that lost its * session while that connection is still the live one — a call that lost its session on a connection already replaced is sent on the * replacement, so a late 404 never closes a connection other calls have moved to. */ import type { Client, Tool } from "@modelcontextprotocol/client"; import { type McpAuthorization, type McpExchangeOutcome, type McpFailure, type McpFailureSite } from "./mcp-failure.js"; import { type ToolAxesSurface } from "./mcp-server-spec.js"; import { type ProtocolRevokedRefusal } from "./protocol-revocation.js"; /** * One request failure, read once and told to the server's two writers: its reach ({@link ServerHealth.observe}) always, and — when * `answer` (this failure is the request's answer: the lane sends nothing again) — the authorization the user owes * ({@link ServerHealth.owed}). Returns the record. */ export declare function observedFailure(err: unknown, site: McpFailureSite, health: ServerHealth | undefined, answer: boolean): McpFailure; /** A tool call's FINAL failure (the translated error: its `cause` is the refusal the request met) tells the server's announcer what the user * owes — the call lane's one announcement, made once its attempts are over. The record is read off the refusal itself, by the one classifier * every face reads it with: the translated error's `details` is the card the run loop copies onto the tool result (and the session keeps), * and it carries the reason alone — the seat's address is not on it. */ export declare function owedByAnswer(err: unknown, health: ServerHealth): void; /** Mutable per-server liveness flag, shared between a server's tool closures and its transport-close hook. * `pendingElicitations` (RB-199 FO-1 codex review): a live count of in-flight `onElicit` waits on THIS * server — the idle watchdog ({@link armMcpIdleWatchdog}) reads it before aborting a call (incremented when the wait starts, * decremented in a `finally`): elicitation is a nested incoming request the * server sends WHILE the outer callTool stays open (the elicitation handler's own LIVE-ONLY note in mcp.ts: * "the handler runs WHILE the agent's `callTool` awaits the server, so the connection is held") * — a human answering a form legitimately produces no progress notifications on the outer call for * as long as they take, and the HTTP idle default (5min) is well within normal human response time. */ export interface ServerHealth { dead: boolean; /** * THE liveness writer for this server — one lifecycle-aware function every observation goes through, * so no site can record an outage the engine itself caused. It writes `McpServerStatus.liveness` * on the SAME record the merge stage pushes into `MaterializedMcp.statuses` (never a second copy), and * it is SILENT while the task is tearing down, for the reason `announceClose` is: our own dispose * closes every transport, and stamping "this server died" on the way out is a lie a consumer reading * the statuses afterwards cannot tell from the truth. * * Same slot discipline as `announce.fn`: filled by the merge stage (which is where the lifecycle flag * lives), and DISARMED when this handle is deliberately replaced — a re-dial's own close is not an * outage either, and the in-flight calls it fails belong to a connection we chose to replace. */ observe?: (outcome: McpExchangeOutcome) => void; /** The other thing a request can learn: its ANSWER was a refusal as `unauthorized`, so the user owes this authorization — the * materialization's once-per-server announcer, filled by the merge stage beside `observe` (the same lifecycle silence applies). */ owed?: (authorization: McpAuthorization) => void; pendingElicitations: number; /** Stamped on EVERY * elicitation close (finally, unconditional — not just when the count returns to 0). Closes a race * the count alone cannot: an idle check can land microseconds after the count drops to 0 but before * the server has had any real chance to reply to the outer call — that check must still treat the * close as fresh activity, not silence. 0 = never closed. */ lastElicitationClosedAt: number; } /** Identity-tagged abort reason for {@link armMcpIdleWatchdog}'s own `.abort()` calls (independent review * hardening): attribution reads `signal.reason === IDLE_WATCHDOG_ABORT_REASON`, a single atomic identity * check, rather than re-reading two separate `.aborted` booleans after the fact and inferring which fired * first — closes a theoretical (unconfirmed in review) same-tick interleaving window between the idle * timer's own abort and an unrelated outer-signal abort landing in an already-queued microtask. */ export declare const IDLE_WATCHDOG_ABORT_REASON: unique symbol; /** * RB-199 FO-1 (independent review, "sweep the class"): a reusable idle watchdog shared by EVERY * agent-reachable MCP request that can otherwise hang on nothing but the huge total-ceiling default — * callTool AND the three resource tools (list/read/directory), all of which had only the single * `mcpToolTimeoutMs()` bound before this RB. Elicitation-aware by construction (server-scoped * `health.pendingElicitations`/`lastElicitationClosedAt` — see the ServerHealth docstring): a pending * elicitation on ANY call to this server can legitimately stall the server's single request-processing * turn, so it freezes the clock for every idle watchdog on that server, not just the call that issued it. * `rearm()` is the reset-on-liveness hook — callTool's `onprogress` calls it every notification (the only * MCP method family with a progress channel); a caller with no progress channel (resource calls have * none — `resources/*` carries no `_meta.progressToken`) may still call it once per unit of real * evidence-of-life it does have (e.g. `readDirViaExtension` calls it once per page received). */ export declare function armMcpIdleWatchdog(health: ServerHealth, idleMs: number, outerSignal: AbortSignal | undefined): { combinedSignal: AbortSignal; idleSignal: AbortSignal; rearm: () => void; dispose: () => void; }; /** One `tools/list` entry as the lenient listing parse keeps it (mcp.ts `LenientListToolsResultSchema`) — every field the intake * pipeline actually reads (`intakeListedTools`), `inputSchema` UNVALIDATED (see that schema's docstring). */ export interface LenientListedTool { name: string; description?: string; inputSchema?: unknown; annotations?: unknown; _meta?: unknown; /** Carried through UNVALIDATED (same posture as inputSchema): the tool's definition rides every call to it (mcp.ts * `toolDefinitionOf`), and the SDK validates a structured result against it; whether this client can compile it is judged at intake. */ outputSchema?: unknown; execution?: unknown; } /** A mounted tool as its calls hand it to the SDK (`callTool`'s `toolDefinition`), from the connection's latest listing through the * leg's own intake: the definition the server listed, and whether this client's schema validator cannot compile its `outputSchema` * (`outputSchemaUncompilable`) — {@link reach} then refuses the call before it is sent, rather than leaving it to the SDK's refusal in * words a reader would take for the server's answer. The compiler's own message is not kept: it quotes the server's schema. */ export interface McpToolDefinition { readonly tool: Tool; readonly outputSchemaUncompilable?: true; } /** * The server's listing as one connection knows it, from whichever of its holders listed last (each leg of a pooled run lists on the * shared connection) — what every holder's mounted tools are checked against, each through its own leg's intake, and what a leg mounts. * * Three rules, all here and nowhere else. Listings answer in the order they were opened: an answer that arrives after a later-opened one * was recorded is superseded and records nothing. A walk that stopped early cannot prove a tool gone: an incomplete answer speaks only for * the names it reached, and every other name keeps its entry from the listing before it (on a new connection, from what the connection it * replaced knew — `carried`). And an entry vouches for a tool's gate only if a listing of THIS connection reached it: one carried across * from the connection this one replaced keeps its tool mounted but stays `unproven` (its tool is not sent) until a listing of this * connection reaches it — a reconnect is exactly when a declaration may have changed. The entries kept are the server's raw ones, not what * an intake accepted, so a tool the walk did reach and the intake then dropped is gone, and every kept entry goes through the intake again. * Accepted cost: an entry this connection listed earlier and a later walk did not reach is still read as it was listed — a tool the server * withdrew or re-declared on an unreached page, with no reconnect between, is read as before until a walk reaches it (as it would be if * nothing had listed again); calling a withdrawn one fails at the server. */ export declare class ConnectionListing<T extends { readonly name: string; }> { private opened; private recorded; private entries; private unprovenNames; /** Open a listing, before its request goes out: its place in the order. */ open(): number; /** The answer of the listing opened at `at`, as the server's listing (`view`), with the names it kept from before (`kept`) and the kept names no listing of this connection reached (`unproven`); recorded unless a listing opened after it already answered. */ answer(at: number, entries: readonly T[], incomplete: boolean, carried?: readonly T[]): { readonly recorded: boolean; readonly view: readonly T[]; readonly kept: ReadonlySet<string>; readonly unproven: ReadonlySet<string>; }; latest(): { readonly at: number; readonly entries: readonly T[]; readonly unproven: ReadonlySet<string>; }; } /** A server's connection with its health record, as a call dispatches on it. */ export interface McpLiveConnection { readonly client: Client; readonly health: ServerHealth; /** Minted tool name → the gate the connection's latest listing ({@link ConnectionListing}) mints it, through this leg's intake. */ gates(): ReadonlyMap<string, string>; /** Minted tool name → its definition from that same listing through that same intake ({@link McpToolDefinition}): what a call to it * hands the SDK. One reading with {@link gates}, so a call is never validated against a listing other than the one that let it go. */ definitions(): ReadonlyMap<string, McpToolDefinition>; } export interface McpServerLink { /** The connection the materialization holds for the server now; `undefined` while it holds none (a re-dial's old one is gone and the new one has not landed, or the last dial failed). */ live(): McpLiveConnection | undefined; /** Replace `lost`: join the re-dial running for the server, or start one while `lost` is still the live connection. Settles when there * is nothing left to wait for. `cause`: the server dropped the session (`session`, the default), or the peer seat's pieces the * connection was started with expired (`expired`: the calls in flight on it settle before it is closed, and the run tree's pooled * connection is replaced once for all its holders). */ recover(lost: McpLiveConnection, cause?: "session" | "expired"): Promise<unknown>; } /** Why a tool may not be sent on a live connection: its listing mints the tool another gate or none (`changed`), no listing of the connection has reached it (`unreached`), or that * listing gives it an output schema this connection's validator cannot compile (`output_schema`: the SDK would refuse the call unsent itself, in words a reader takes for the * server's answer). */ export type McpListingRefusal = "changed" | "unreached" | "output_schema"; /** Where the tool `name` minted with `gate` may be sent now: the live connection, `"gone"` when there is none (or it closed), or why its listing does not vouch for the tool ({@link McpListingRefusal}). */ export declare function reach(link: McpServerLink, name: string, gate: string): McpLiveConnection | "gone" | McpListingRefusal; /** An attempt whose session was found gone: the connection it was sent on, and its failure as it would have been thrown then. */ export declare class Resendable { readonly on: McpLiveConnection; readonly error: unknown; constructor(on: McpLiveConnection, error: unknown); } /** * One tool call through the link. `send` makes one attempt on a connection (`resent` on the second) and answers {@link Resendable} for a * lost session. Such a call is recovered once: it waits for the shared re-dial — or for its own `signal`, which ends the call at once — * and is sent again only on a connection that replaced the lost one and where {@link reach} says it may go. A call that is not sent again, * whatever the reason (no replacement, a declined re-dial that left the lost connection in place, a replacement whose listing does not * vouch for the tool, its abort), ends with its first attempt's failure; a second lost session ends with that one. `gone` and an * {@link McpListingRefusal} answer only a call that was never sent. */ export declare function callThroughLink<R extends object>(link: McpServerLink, name: string, gate: string, signal: AbortSignal | undefined, send: (on: McpLiveConnection, resent: boolean) => Promise<R | Resendable>, gone: () => never): Promise<R | McpListingRefusal>; /** What judges a call a refusal turned away: the live connection's listing, the operator's revocation list, the declaration a tool was mounted with, the connection itself (a transport that closed or an endpoint that did not answer). */ export type RefusalJudge = "listing" | "revocation" | "declaration" | "connection"; /** * THE closing sentence of a protocol call refused before it was sent: what the refusal covers (this call) and what judges a later call, * never how that call will come out — a host's re-dial, refresh or un-revoke lands between two calls, and the call after it is * judged against what it took. The listing's refusal, a revoked server's or peer's outlets ({@link revokedCallResult}), the * task-required one and a server's gone or unreachable connection end with it; no site words it again. */ export declare function refusalScope(judge: RefusalJudge, at: ToolAxesSurface): string; /** * THE answer of a call whose request the revocation ledger stopped at the request exit ({@link ProtocolRevokedRefusal}) — one writer for * both protocols and every outlet (a tool call, a resource read, a directory listing, an A2A skill call): the refusal record * (`isError`; `code` beside `error` — the wire's errorCode lift reads `details.code`; `delivered`, the refusal's own: `no`, or `unknown` * for a redirect stopped after the request's first hop was sent; the server or peer). The A2A outlet adds its own card (the A2A card, * minted in a2a.ts only). `what` names the call (already neutralized by the caller). `accepted` is an A2A task the peer took on before a later status request was stopped: that * call was delivered (`delivered: "yes"`), its outcome is unknown, and no continuation is offered — calling the tool again would send the * peer a new message, not ask about the task. */ export declare function revokedCallResult(refusal: ProtocolRevokedRefusal, what: string, accepted?: { readonly taskId: string | undefined; }): { content: Array<{ type: "text"; text: string; }>; details: Record<string, string>; terminate: false; isError: true; }; /** The answer to a call {@link reach} refused before it was sent: the pre-send refusal record (`delivered: "no"`; `code` beside `error`, as the revocation refusal's). */ export declare function listingRefusal(refusal: McpListingRefusal, remoteName: string, server: string): { content: Array<{ type: "text"; text: string; }>; details: Record<string, string>; terminate: false; isError: true; }; /** The runs of one kind of work that may only run once at a time per key (a server's re-dial). */ export declare class Flights<V> { private readonly open; /** The flight running under `key`, or `undefined`. */ running(key: string): Promise<V> | undefined; /** Start `run` as the flight of `key`; it leaves the table when it settles. The caller has checked that none is running. */ start(key: string, run: () => Promise<V>): Promise<V>; }