UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

294 lines (293 loc) • 18.3 kB
/** * The host's read ports onto one connected MCP server — its prompts and its resources — and the ONE reader each of those methods has in * the engine. The model's resource tools (mcp.ts `buildResourceTools`) and the host's ports below call the same readers over the same * route: the same door (the revocation ledger asked as the request leaves), the same `_meta`, the same per-call timeout, the same idle * watchdog, the same liveness writer and the same lenient page read. What differs is only the rendering: the model's tools fence what * they read into a tool result; the host's ports hand back core's own projection of it. * * THE PROJECTION. A port never hands out an SDK type or a server's `_meta`: every listed entry, prompt message and resource content is * read member by member into a closed shape of core's own, and an element that does not fit — a member of the wrong kind, an unknown * content type, a role outside `user` / `assistant`, text and a blob both present or both absent — is dropped and COUNTED (`dropped`). * Every string member is one of two kinds. A NAME the host hands back to the server (a prompt's and its arguments', a resource's uri and * name, a template's) is kept verbatim, and on a listing one holding a credential the connection's requests carried refuses its entry. * Everything else — a title, a description, a mime type, a page failure's words — is DISPLAY text: erased in place on a listing * (credential-echo.ts, sites `prompt_listing` / `resource_listing`) and neutralized everywhere (`sanitizeUntrustedText`; a failure's words * inlined as the refusal's are); a prompt's text goes into a model turn only through {@link renderMcpPromptForModel}, which fences it. A text block is cut at the remote result bound * ({@link MCP_REMOTE_RESULT_MAX_CHARS}, `truncated: true`); a binary block is never inlined — its bytes go to the one byte keeper a * tool result's bytes go to (the run's tool-result store, `McpReadDeps.keep`) and come back as `kept` ({@link KeptBytes}: the ref they * are kept under, or why they are not). * * THE ANSWER. Every port answers {@link McpHostRead}: `read`, `refused` (with the failure record's fields, spread flat, exactly when the one * classifier read the failure), or `not_declared`. The judgment runs in one order, the first row that holds answers: no declaration ⇒ * `not_declared`; the materialization stopped ⇒ `refused`; no live connection (never dialed, its dial failed) ⇒ `refused` (a port never * dials); the transport already closed ⇒ `refused` (`connection_closed` / `no`); the ledger revoked the server ⇒ `refused` (`revoked` / * `no`), asked before anything else is judged; the server's `allowTools` list does not name the port's face word ⇒ `refused`; the server * declared no capability for it ⇒ a listing reads `[]` and a fetch is `refused`, nothing sent; a first listing page answered * `MethodNotFound` ⇒ `[]` (a tool listing is NOT judged by this rule: its failure still fails the server's dial); any other failure ⇒ * `refused` with the classifier's reading; a continuation page that failed (or the walk's other stops) ⇒ `read` with what was read and * `listingIncomplete`; and a read whose server was re-dialed while it was in the air ⇒ `refused` (what it read came from the replaced * connection). A caller's abort rejects with the signal's own reason; a malformed argument throws `config.invalid_argument`. */ import { type Client } from "@modelcontextprotocol/client"; import { type CredentialEcho } from "./credential-echo.js"; import { type McpFailureFields } from "./mcp-failure.js"; import { type ServerHealth } from "./mcp-server-link.js"; import { ProtocolRevokedRefusal } from "./protocol-revocation.js"; import { type KeptBytes, type ToolResultBytesKeeper } from "./tool-result-bytes.js"; import type { McpListingIncomplete, listEntryFingerprint, walkMcpListPages } from "./mcp.js"; import type { McpServerSpec } from "./mcp-server-spec.js"; /** One prompt a server lists (`prompts/list`), as core projects it. */ export interface McpPromptEntry { name: string; title?: string; description?: string; arguments?: Array<{ name: string; title?: string; description?: string; required?: boolean; }>; } /** One resource a server lists (`resources/list`), as core projects it. */ export interface McpResourceEntry { uri: string; name: string; title?: string; description?: string; mimeType?: string; size?: number; } /** One resource template a server lists (`resources/templates/list`), as core projects it. */ export interface McpResourceTemplateEntry { uriTemplate: string; name: string; title?: string; description?: string; mimeType?: string; } /** One content block of a prompt message, as core projects it: text (cut at the remote result bound), a binary block as its kept * bytes, an embedded resource (its text, or its blob's kept bytes), or a link to a resource. */ export type McpContentBlock = { type: "text"; text: string; truncated?: true; } | { type: "image" | "audio"; mimeType: string; kept: KeptBytes; } | { type: "resource"; resource: { uri: string; mimeType?: string; text: string; truncated?: true; } | { uri: string; mimeType?: string; kept: KeptBytes; }; } | { type: "resource_link"; uri: string; name: string; title?: string; description?: string; mimeType?: string; }; /** A prompt as a server answers `prompts/get`, projected. The text in it is for DISPLAY; into a model turn it goes through {@link renderMcpPromptForModel}. */ export interface McpPromptAnswer { description?: string; messages: Array<{ role: "user" | "assistant"; content: McpContentBlock; }>; } /** A resource as a server answers `resources/read`, projected. */ export interface McpResourceContents { contents: Array<{ uri: string; mimeType?: string; text: string; truncated?: true; } | { uri: string; mimeType?: string; kept: KeptBytes; }>; } type McpHostRefused = { server: string; outcome: "refused"; reason: string; } & Partial<McpFailureFields>; type McpHostNotDeclared = { server: string; outcome: "not_declared"; reason: string; }; /** * What a host read port answers — three words, the shape `McpReconnectResult.outcome` already taught every consumer: `read` (the * projection, `dropped` when elements were dropped, `listingIncomplete` when a listing's walk did not reach its end), `refused` (`reason`, * plus the failure record's fields spread flat when — and only when — the one classifier read the failure), `not_declared`. */ export type McpHostRead<T> = ({ server: string; outcome: "read"; dropped?: number; listingIncomplete?: McpListingIncomplete; } & T) | McpHostRefused | McpHostNotDeclared; /** * The host's five read ports on a materialization (`MaterializedMcp` carries them). Each reads ONE named server over the connection this * materialization already holds — it never dials and never re-dials — and judges in the order the module note gives. The faces they * open are the server's `allowTools` face words (mounted-mcp.ts): `list_prompts`, `get_prompt`, `list_resources`, * `list_resource_templates`, `read_resource`. A host reading several servers may call them concurrently; each spends at most the * per-call MCP timeout, bounded further by `signal`. */ export interface McpHostReadPorts { listPrompts(server: string, signal?: AbortSignal): Promise<McpHostRead<{ prompts: McpPromptEntry[]; }>>; /** `args` is a plain record of strings (the prompt's arguments as the server declared them); a required argument left out is the * server's to refuse (its `-32602` answers `refused`, `protocol` / `yes`). The answer's text is for display — a host puts the prompt * into a model turn ONLY through {@link renderMcpPromptForModel}. */ getPrompt(server: string, name: string, args?: Readonly<Record<string, string>>, signal?: AbortSignal): Promise<McpHostRead<McpPromptAnswer>>; listResources(server: string, signal?: AbortSignal): Promise<McpHostRead<{ resources: McpResourceEntry[]; }>>; listResourceTemplates(server: string, signal?: AbortSignal): Promise<McpHostRead<{ resourceTemplates: McpResourceTemplateEntry[]; }>>; readResource(server: string, uri: string, signal?: AbortSignal): Promise<McpHostRead<McpResourceContents>>; } /** The request door of a connection ({@link McpReadRoute.through}): every request leaves through it, the revocation ledger asked as it does. */ export type McpRequestDoor = <T>(send: () => Promise<T>) => Promise<T>; /** One connected server as its reads reach it — minted once per connection, where the dial took it, and read by every face. */ export interface McpReadRoute { readonly server: string; readonly client: Client; /** The leg's door to this server: every request leaves through it. */ readonly through: McpRequestDoor; /** Liveness flag flipped by the transport-close hook, and the liveness writer each exchange reports to. */ readonly health: ServerHealth; /** Which idle-watchdog default applies: list, read and fetch carry no progress channel, so the watchdog is their only bound below the per-call timeout. */ readonly transportKind: "stdio" | "http"; /** The header values this server's requests carry: its failure texts are read without them. */ readonly declared: readonly string[]; /** The `_meta` a fetch (`resources/read`, `prompts/get`) carries — the one mint's: the leg's session id under the declared key and the leg's caller where the server declared `callerMeta`, or none. */ readonly meta: () => Record<string, unknown> | undefined; /** How this connection's account of itself is read: without its credentials, a site that held one announced. */ readonly echo: CredentialEcho; } /** What the readers take from the module that owns the connections (mcp.ts) — passed in, so this module never imports it back. */ export interface McpReadDeps { readonly walk: typeof walkMcpListPages; readonly fingerprint: typeof listEntryFingerprint; /** The byte keeper a binary block's decoded bytes go to — the one a tool result's bytes go to (the run's tool-result store); absent ⇒ * nothing is kept (`notKept: "no_byte_store"`). */ readonly keep?: ToolResultBytesKeeper; readonly timeoutMs: () => number; readonly idleMs: (kind: "stdio" | "http") => number; readonly idleTripText: (idleMs: number) => string; /** A failure's text as every MCP face mints it: the remote's words without the request's credentials, a protocol-range condition named. */ readonly failureText: (err: unknown, declared: readonly string[]) => string; } /** The idle watchdog a read runs under ({@link armMcpIdleWatchdog}). */ export interface McpReadWatch { readonly combinedSignal: AbortSignal; readonly idleSignal: AbortSignal; readonly rearm: () => void; } export declare const MCP_CHARS_PER_TOKEN = 4; export declare function mcpMaxOutputTokens(): number; /** * Did the server answer that it does not serve the method (`MethodNotFound`, `-32601`)? The one reading of that fact: a standard * listing of prompts, resources or templates reads it as an empty listing; the directory-read extension as "fall back to the prefix * filter". The consequence is the method's, the reading is this one. */ export declare function notServed(err: unknown): boolean; type Raw = Record<string, unknown>; /** The three standard listings: the method, the result member that carries the page's entries, and the projection of one entry. */ interface ListingEntries { prompts: McpPromptEntry; resources: McpResourceEntry; resourceTemplates: McpResourceTemplateEntry; } export type McpListingKind = keyof ListingEntries; /** * One answer read as an ENVELOPE only: an object whose `member` is an array (a listing page's `prompts` / `resources` / * `resourceTemplates`, a fetch's `messages` / `contents`). Each element is judged afterwards on its own, so one that does not fit costs * itself, never the answer — the lenient tool listing's contract. The check runs twice by construction: as the `~standard` result schema * the SDK runs inside `request()` (an envelope that does not fit fails the request there, classified like any invalid result), and again * where the answer is read ({@link envelopeOf}), which is what reads it. */ interface Envelope { readonly answer: Raw; readonly items: readonly unknown[]; } /** * THE reader of a standard listing (`prompts/list`, `resources/list`, `resources/templates/list`) over one route — the model's resource * tools and the host's ports alike. Walked to the end by the one walker (one per-call timeout for the whole walk, its page cap, its cursor * guards), each page sent through the door with page one carrying no params (the uncursored request, as the SDK's own list verb spells * it) and a continuation the server's cursor alone — through `request()` a page at a time, never that list verb (called without a * cursor it walks every page itself and caches the aggregate, so the walk's budget and its truncation disclosure would never see a page) * — each page received rearming the watchdog and recorded as a completed exchange, a continuation that failed recorded as the exchange it * was (the caller's own abort is none). A first page answered `MethodNotFound` is an empty * listing; any other first-page failure, and the door's refusal of any page, is thrown — the caller's face decides what it owes. A page's * failure is thrown as it arrived (an idle-watchdog trip as its own sentence), or through `told` when the face tells a failed request in * its own words: `told` gets the page's own deadline, so a continuation that times out names the wait that happened, and what it throws is * what an incomplete listing then carries. Not asked here: whether the server declared the capability (each face asks that before it reads). */ export declare function readMcpListing<K extends McpListingKind>(route: McpReadRoute, kind: K, watch: McpReadWatch, idleMs: number, signal: AbortSignal | undefined, deps: McpReadDeps, told?: (err: unknown, remainingMs: number) => never): Promise<{ entries: Array<ListingEntries[K]>; dropped: number; incomplete?: McpListingIncomplete; }>; /** A fetch's answer read as an envelope: the answer itself, and the array its list member carries (`messages`, `contents`). */ export type McpFetched = Envelope; declare const FETCH_MEMBERS: { readonly "prompts/get": "messages"; readonly "resources/read": "contents"; }; /** A fetch's params: what the caller names, plus the route's `_meta` when the one mint answers one. */ export declare function fetchParamsOf(route: McpReadRoute, params: Raw): Raw; /** * THE reader of a fetch (`resources/read`, `prompts/get`) over one route: one request through the door, under the per-call timeout and * the watchdog's signal, recorded as a completed exchange when it answers. The answer is checked as an envelope only (an object whose * `contents` / `messages` is an array); a failure is thrown as it arrived. */ export declare function fetchMcpAnswer(route: McpReadRoute, method: keyof typeof FETCH_MEMBERS, params: Raw, watch: McpReadWatch, timeoutMs: number): Promise<McpFetched>; type Keep = ToolResultBytesKeeper | undefined; /** A `prompts/get` answer projected: its messages in order (a message whose role is not `user` / `assistant`, or whose block does not fit, * dropped and counted), its description when it is a string. Like a tool result, fetched content is not read for the connection's credentials. */ export declare function promptAnswerOf(fetched: McpFetched, keep: Keep): Promise<McpPromptAnswer & { dropped?: number; }>; /** A `resources/read` answer projected: each content entry's text (cut at the bound) or its blob kept; an entry that does not fit dropped and counted. */ export declare function resourceContentsOf(fetched: McpFetched, keep: Keep): Promise<McpResourceContents & { dropped?: number; }>; /** * THE way a prompt a host fetched ({@link McpHostReadPorts.getPrompt}) goes into a model turn — the instructions' posture (turn-attachments.ts * `fenceMcpServerInstructions`): the messages' text, an embedded resource's text and a resource link's line, in order and without roles, * inside ONE untrusted fence (which neutralizes the whole authority-envelope family, not only the reminder tag the projection's * `sanitizeUntrustedText` defuses), bounded by the MCP result budget ({@link mcpMaxOutputTokens} × {@link MCP_CHARS_PER_TOKEN}) — the bound a * tool result has, not the 4096 of a standing system-prompt section. Each cut is said on a trusted line outside the fence: the fence's own, * a text block the projection already cut, and the binary blocks (images, audio, blobs) that are not carried into the turn. */ export declare function renderMcpPromptForModel(server: string, prompt: string, answer: McpPromptAnswer): string; /** What the ports read of the materialization that holds the connections. */ export interface McpHostReadSeat { /** The declared entry named `server` (a declaration whose dial was refused included), or `undefined`. */ readonly declaration: (server: string) => McpServerSpec | undefined; /** Why this materialization reads nothing any more (disposed, its run aborted), or `undefined`. */ readonly stopped: () => string | undefined; /** The route of the connection this materialization holds for `server` right now, or `undefined`. */ readonly route: (server: string) => McpReadRoute | undefined; /** The revocation ledger's answer for the declaration, asked now. */ readonly revoked: (spec: McpServerSpec) => ProtocolRevokedRefusal | undefined; readonly deps: McpReadDeps; } /** The host's five read ports over `seat` — the judgment order of the module note, once, for all five. */ export declare function mcpHostReadPorts(seat: McpHostReadSeat): McpHostReadPorts; export {};