@sema-agent/core
Version:
Stateless, task-oriented AI agent core
204 lines (203 loc) • 16.9 kB
TypeScript
/**
* The MCP connection pool of ONE run tree: the legs of a tree — the root run and every delegated child it spawns, background
* and kept ones included — that declare the same server lease ONE connection (one client, one stdio process, one authorization,
* one lock holder) instead of dialling a copy each.
*
* WHAT IS SHARED AND WHAT IS NOT. Only the connection is: the SDK client over its transport. Everything a leg binds to
* itself stays the leg's own — the tool objects it mints around the client (their reminder-disclosure counters, their
* revocation probe, their runId), its liveness record, its close announcer. A shared tool object would write into the account of a
* parent leg that ended; a shared connection cannot.
*
* LIFETIME. A lease is released when its leg's materialization is disposed (the leg ended, failed, was cancelled or parked); the
* last holder's release closes the connection. The pool holds no connection between leases. Inside a Runner the pool is the
* session TREE's ({@link SessionMcpPools}: one per tree root's address, principal and peer seat in the process, whichever Runner and
* store object serve the leg — every message of a session, and every leg its runs spawn, kept and revived ones included, leases from
* one pool while their Runners hold the same seat copy, or none); a leg
* prepared outside a Runner, and one whose occupant could not be read, makes its own and it dies with that run. No leg is handed a
* pool: each finds its tree's by address, so the DECLARATION stays the one source of truth — no handle is ever recorded anywhere.
*
* WHAT THE POOL REMEMBERS is the failure of a connection ATTEMPT, per key ({@link attempt}): the dial's handshake, its first
* listing, and the re-dial a 401 answered with other pieces inside it are one attempt; the attempt is opened where the dial
* begins and settled where it ends. A key whose last attempt failed is not dialed again: the next attempt is answered with that
* failure, as it was, at once — the person was told when it failed, and the server is not tried again for the pool's life
* unless its declaration changes (another key), a re-dial replaces it (`fresh`) or the host forgets it ({@link forget}). A
* live connection under the key comes before the memory: one leg's failed listing on a connection another leg holds is that
* leg's alone. What the caller does not settle as a failure is not remembered (its own stop, a refusal of the engine's own
* seats, a server that asks the person to authorize: none of them waits a bound).
*
* THE KEY is the server's declaration as the dial reads it (name and transport), the principal the task runs under, and the peer
* seat the leg's Runner was given: a different principal is a different identity at the server, and a different seat is a
* different source of what the requests carry. A task whose isolation scope names a partition other than that person adds it to
* the key (a connection's state between requests is one partition's working state). The transport holds no value (a declaration
* carries at most an opaque credential reference, so two references that differ never share a connection). Every request on a
* connection carries what the seat that dialled it answers, so only legs whose Runners hold the SAME seat copy share a connection
* or the memory of a failed attempt (`peerSeatIdentityOf`): the same seat object, its members reading as at its last receipt — a
* member replaced makes a new copy, and putting the original back makes another, which does not rejoin the first
* (`receivePeerSeat`). Legs given no seat share among themselves and with no seated leg. A Runner never shares a connection with a
* library entrance: the entrance leases only from the pool its host hands it. A server that opted in to elicitation never enters
* the pool — the answer to its questions belongs to the leg that is waiting on it.
*/
import type { Client } from "@modelcontextprotocol/client";
import { ConnectionListing, type LenientListedTool } from "./mcp-server-link.js";
import type { McpServerSpec } from "./mcp-server-spec.js";
import { type PeerSeat } from "./peer-seat.js";
import type { SessionAddress } from "./task-notification.js";
/** The engine's own dial of `client` under `key` (the key {@link McpConnectionPool.keyOf} gives its declaration): the one connection a pool
* entry for that key may take. */
export declare function recordEngineDial(client: Client, key: string): void;
/** One leg's hold on a pooled connection. */
export interface McpLease {
readonly client: Client;
/** The connection's listing, one record shared by every holder (mcp-server-link.ts `ConnectionListing`): what every holder's tools are
* checked against and what their calls hand the SDK as the tool's definition, each through its own leg's intake. */
readonly listing: ConnectionListing<LenientListedTool>;
/** Run `fn` when the connection closes under the lease (the server died, the transport dropped). Never called for this lease's own release. */
onClose(fn: () => void): void;
/** Give the hold back; the last holder's release closes the connection. Idempotent. */
release(): Promise<void>;
}
/** One connection attempt under a key ({@link McpConnectionPool.attempt}). `recalled`: the key's last word was a failure and no connection
* under it is live — this attempt dials nothing and answers with `recalled.reason`. Otherwise the caller dials and settles: `connected`
* clears the memory, `{ failed }` keeps it, `unkept` leaves it as it was — and only while no newer word on the key has been given.
* `settle` answers whether the pool now remembers the key's failure (the person is told "for this session" only then); a settle is read
* once, and an attempt that recalled settles nothing. */
export interface McpAttempt {
readonly recalled: {
readonly reason: unknown;
} | undefined;
settle(outcome: "connected" | "unkept" | {
readonly failed: unknown;
}): boolean;
}
export declare class McpConnectionPool {
private readonly entries;
private readonly dialing;
private readonly memo;
/** Bumped by each {@link detach}: a dial that finishes after its key was detached serves the legs already waiting on it and publishes nothing. */
private readonly generation;
private leased;
private shut;
/** The root session of the tree this pool is held for ({@link SessionMcpPools}) — the session a failed attempt under it is told to; absent for a pool its caller made. */
readonly sessionId: string | undefined;
constructor(opts?: {
sessionId?: string;
});
/**
* The key a declaration leases under. `kind` is the dial's own single reading of the transport kind (the dial reads it once and threads it, so a
* transport object that answers differently to two readers cannot split the dial from its key); every other transport member is read here.
* The declaration's mount identity (`fingerprint`) is part of the key when declared: the revocation probe is asked with it, so two mounts the
* host tells apart never share one connection (an undeclared fingerprint leaves the key as it always was).
* So is the startup bound the dial runs under (`startupMs`, the dial's one reading of {@link mcpStartupTimeoutMs}, threaded like `kind`):
* a connection is dialled under the declaration of the mount that dials it, so a mount never waits on, or shares, a dial bounded by
* another mount's clock. No bound in force (none declared, no environment seat) leaves the key as it always was.
* So is the task's isolation scope (`isolationScope`, the value of `isolationScopeOf(spec)` — `isolation-scope.ts`) when it names a
* partition other than the person: what a connection holds between requests (a server-side session, its state) belongs to the working
* state of one partition, so the same person in two partitions holds two connections. The identity the connection presents at the server
* stays the person's (`principal`). A partition that is the person (no `TaskSpec.isolationScope`, or the same string) leaves the key as it
* always was.
* So is the peer seat the dial asks (`seat`, the leg's received seat): every request on the connection carries what that seat answers,
* so a connection is one seat's (`peerSeatIdentityOf`). No seat leaves the key as it always was.
*/
static keyOf(spec: McpServerSpec, principal: string | undefined, kind: string | undefined, startupMs: number | undefined, isolationScope?: string, seat?: PeerSeat): string;
/**
* Lease the connection for `key`, dialling it with `dial` when none is live. `fresh` replaces the pool's current connection with a new
* dial (a re-dial): the connection it replaces lives on until its other holders release it. Resolves `undefined` once the pool is
* closed — the caller dials for itself. A dial that rejects rejects every waiter of that dial, and no connection of it is kept (what
* is remembered of a failure is the attempt's, settled by its caller — {@link attempt}).
*
* `signal` is the CALLER's abort, and it is that caller's alone: it ends this caller's wait (rejecting with its reason) and leaves the dial
* to the legs still waiting on it. The dial belongs to the pool: it is given a stop of its own, fired when the last leg waiting on it has
* walked away, so a leg's abort neither holds nor cancels a dial another leg still needs.
*/
acquire(key: string, dial: (stop: AbortSignal) => Promise<Client>, opts?: {
fresh?: boolean;
signal?: AbortSignal;
}): Promise<McpLease | undefined>;
/**
* Wait for a dial as one of its legs; this leg's abort ends only this leg's wait. The last leg to walk away abandons the dial in the
* same step as its abort (see {@link abandon}) — the table holds only dials some leg still waits on, so a leg that asks next dials afresh
* instead of joining a stopped dial and failing with another leg's abort.
*/
private waitOn;
/** A dial nobody waits on any more: out of the table and stopped, and — had it landed already — the connection nobody leased is let go, so such a dial leaves no connection behind. */
private abandon;
/** Make the next lease of `key` dial a new connection. */
detach(key: string): void;
/** The dial in the air under `key` is no next lease's: it serves the legs already waiting on it and publishes nothing. */
private dropDial;
/**
* Open one connection attempt for `key` (the declaration's key, {@link keyOf}; `server` is the name it declares). The key's word is
* its newest: an attempt's settle counts only while no attempt opened after it has settled and no re-dial or forget came after it.
* `fresh` (a re-dial) is such a word — it drops the key's memory before this attempt opens. The memory answers only while no
* connection under the key is live, and a failure settled while one is live is that caller's alone (another holder's connection is
* the server's answer). A closed pool recalls and keeps nothing: its caller dials for itself.
*/
attempt(key: string, server: string, opts?: {
fresh?: boolean;
}): McpAttempt;
/** Forget what this pool remembers of every attempt at the server named `server` (any key that declares it): an attempt still in
* the air settles nothing, and its dial is no next lease's — the next attempt dials. True when a failure was remembered. */
forget(server: string): boolean;
/** Whether no leg holds a lease of this pool (a detached connection's included) or waits on a dial in its table. */
get idle(): boolean;
private liveUnder;
/** No lease is granted after this; the connections still held stay open until their holders release them — one nobody holds is closed now. */
close(): void;
/** How many connections the pool holds open right now (for the lifecycle pins). */
get live(): number;
private dialNew;
private lease;
}
/**
* The MCP pools of session TREES, one per tree root's ADDRESS (its box scope, its session id, its occupant —
* `rootSessionAddressKeyOf`, the one key of that address): the only answer to "which pool does this leg lease from". A leg finds its
* tree's pool here by the delegation fixed point (root-session-lane.ts `treeRootAddressOf`: a descendant the root its anchor records,
* a root its own address under its task scope), so every message of a session and every leg its runs spawn — synchronous, background,
* kept and resumed, revived — lease from one pool and read one memory of a failed attempt ({@link McpConnectionPool.attempt}),
* whichever Runner and whichever session store object serve the leg, as long as those Runners hold the same peer seat copy
* (`receivePeerSeat`; or none); nothing hands a pool down. Another occupant of the same id, another scope, another root, another principal driving the
* same session row, another peer seat: another pool. An address whose occupant could not be read names nobody and has no pool here —
* its leg makes one of its own (the prepare's), shared with no one.
*
* A CACHE, never an authority: bounded (an LRU over addresses, refreshed on read), and only an idle pool (no lease held, no dial
* waited on) is let go. Letting go cuts nothing — a leg that already took the pool keeps it to its end — and costs what the tree's
* next leg then pays: one dial, the memory having gone with the pool; every later leg of the tree reads the new pool. The memory does
* not cross processes and is not persisted: a new process dials afresh.
*/
export declare class SessionMcpPools {
private readonly pools;
private static readonly CAP;
/**
* The pool of the tree whose root is `root`, for the legs that run under `principal` and ask `seat` (the leg's Runner's peer seat), made
* on its first ask; `undefined` for an address that names nobody (its occupant was not read). A leg's connections are keyed by its
* principal and its seat anyway ({@link McpConnectionPool.keyOf}) — a child runs under its spawner's principal unless a deployment
* baseline or a trusted script pins another, and asks its own Runner's seat — so these split nothing two legs could share; they keep two
* principals, or two credential sources, of one tree or one session row out of each other's pool, so nothing a pool does as a whole —
* a forget by server name, letting an idle pool go — reaches another person's or another seat's memory.
*/
of(root: SessionAddress, principal: string | undefined, seat: PeerSeat | undefined): McpConnectionPool | undefined;
/** Forget, in the pools of the trees rooted at the session `sessionId` here whose legs run under `principal` and ask `seat` (any
* occupant, any scope: the request names the id and the person, the asking Runner names its seat), the memory of every attempt at
* `server` ({@link McpConnectionPool.forget}); a session with no such pool here remembers nothing. */
forget(sessionId: string, principal: string | undefined, seat: PeerSeat | undefined, server: string): boolean;
}
/** The MCP pools of this process's session trees ({@link SessionMcpPools}). */
export declare function processSessionMcpPools(): SessionMcpPools;
/** The request of `Runner.forgetMcpFailure`: the session (the one its messages run under — a child's or a workflow agent's legs lease
* from the same pool), the DECLARED name of the server, and the person whose memory it is — the principal the session's tasks run
* under (`TaskSpec.principal`, read by the same reader); absent: tasks that run under no principal. Another principal's memory of the
* same session id is never reached, nor the memory of legs whose Runners were given another peer seat object than the Runner asked. */
export interface ForgetMcpFailureRequest {
sessionId: string;
server: string;
principal?: string;
}
/** What `Runner.forgetMcpFailure` did: `forgotten` — the session remembered a failed connection attempt at the server, and its next
* message dials it again; `none_remembered` — nothing was remembered (an attempt still in the air is no longer remembered either way). */
export interface ForgetMcpFailureResult {
server: string;
outcome: "forgotten" | "none_remembered";
}
/** The out-of-run verb's body (`Runner.forgetMcpFailure`; `seat`: the asking Runner's peer seat): a request whose members are not
* strings, or whose `principal` is given and names nobody, is refused by name, never read as none. */
export declare function forgetSessionMcpFailure(pools: SessionMcpPools, request: ForgetMcpFailureRequest, seat: PeerSeat | undefined): ForgetMcpFailureResult;