UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

2,099 lines • 120 kB
import { __resetEnvKnobAnnouncements } from "./env-knob-announce.js";
import { resolveEnvBudget } from "./env-budget.js";
import { MCP_NAMESPACE, createToolNameClaims, mintNamespacedToolName, mintNamespacePrefix } from "@sema-agent/primitives";
import { followMcpServerStderr } from "./mcp-stderr-lines.js";
import { foreignLine, remoteWords, resolveProtocolHttpHeaders } from "./protocol-http-auth.js";
import { NO_CREDENTIAL_ECHO, carrierEcho, echoAnnouncer, echoedToolDrop, erasedEcho, serverInfoOf } from "./credential-echo.js";
import { PeerAuthorizationRefused, PeerCarrier, Reauthorized, answeredUnauthorized, carrierOf, inFlight, mcpPeerTarget, peerFetch, peerSeatMissing, receivePeerSeat, recordCarrier, refusedThenRenewed, sentOnceMore, settledInFlight } from "./peer-seat.js";
import { disposeSectionEntry, sectionAnswerWarning } from "./prompt-section-seat.js";
import { mcpToolDropReason, refuseCollidingMcpServerNames } from "./mcp-name-judge.js";
import { Client, ProtocolError, ProtocolErrorCode, SdkError, SdkErrorCode } from "@modelcontextprotocol/client";
import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv";
import { ListResourcesResultSchema } from "@modelcontextprotocol/core";
import { McpConnectionPool, recordEngineDial } from "./mcp-connection-pool.js";
import { SessionEndingTransport, requestSite } from "./mcp-session-end.js";
import { mcpToolGate, UNPROVEN_GATE } from "./mcp-listing-drift.js";
import { MCP_CONNECTING_NOTICE_AFTER_MS, pendingFaceOf, settledWithin } from "./mcp-leg-wait.js";
import { ConnectionListing, Flights, IDLE_WATCHDOG_ABORT_REASON, Resendable, armMcpIdleWatchdog, callThroughLink, listingRefusal, observedFailure, owedByAnswer, reach, refusalScope, revokedCallResult } from "./mcp-server-link.js";
import { underStartupBound } from "./mcp-startup-request.js";
import { LIST_MCP_RESOURCES, MCP_FACE_WORD_DROP_REASON, MCP_RESOURCE_LIST_ALLOW, MCP_RESOURCE_READ_ALLOW, READ_MCP_RESOURCE, READ_MCP_RESOURCE_DIR, faceAllowed, isMcpFaceWord, retractInstructions, tellInstructions, toldOnDial, unretractInstructions, withdrawInstructionAdds } from "./mounted-mcp.js";
import { MCP_CHARS_PER_TOKEN, fetchMcpAnswer, mcpHostReadPorts, mcpMaxOutputTokens, notServed, readMcpListing } from "./mcp-host-read.js";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { authorizationClause, authorizationOwed, describeHttpTransportFailure, failureFields, isCallerAbortReading, livenessOf, lostInFlight, namingLostSession, owesAuthorization, readMcpFailure, sessionGone, unauthorizedLine } from "./mcp-failure.js";
import { mcpPeerRegistration, peerRegistrationDigestOf } from "./peer-registration.js";
import { DEFAULT_REQUEST_TIMEOUT_MSEC } from "@modelcontextprotocol/client";
import { mediaBlockTypeOf } from "./image-admission.js";
import { keepBytesWith, mediaTypePhrase, noteKeptPiece, withKeptPieces } from "./tool-result-bytes.js";
import { MCP_STDIO_READ_BOUND, McpReplyOverReadBound, overReadBoundSentence, readBoundBreachOf, readBoundWhy, watchReadBound } from "./mcp-read-bound.js";
import { toolResultBytesKeeper } from "./tool-result-store.js";
import { sliceHeadSafe, sliceTailSafe } from "./surrogate-safe-slice.js";
import { TOOL_INTERRUPTED_TEXT, truncateError } from "./tool-errors.js";
import { transportKindOf } from "./mcp-server-spec.js";
import { ProtocolRevokedRefusal, askCarriedRevocation, carryRevocation, libraryRevocationProbe, mcpRevocationTarget } from "./protocol-revocation.js";
import { hostMount, hostSeatLine, hostSeatMissing, hostSeatVerdictOf, openHostPipe, settledBefore } from "./mcp-host-seat.js";
import { peerRequestRefusal } from "./host-floor.js";
import { MCP_SERVER_UNAVAILABLE, attachUnavailableCause } from "./mcp-server-unavailable-notice.js";
import { MAX_MCP_LIST_PAGES, listingIncompleteNote, listingIncompleteWarning } from "./mcp-listing-incomplete.js";
import { listedNamesOf, recordListedNames, recordRaisedWarnings } from "./mcp-producer-facts.js";
export { listedNamesOf };
import { delimitUntrusted, inlineUntrusted, sanitizeUntrustedText } from "./untrusted-text.js";
import { cutAt, pastWholeReading } from "./untrusted-egress.js";
import { discloseReminderShaped, observeReminderMarkEcho } from "./reminder-disclosure.js";
import { MARKED_BLOCK_AFTER_DATA } from "./reminder-mint.js";
import { resolveMcpDeclaredResultSize, resolveMcpRequiresUserInteraction } from "./mcp-tool-meta.js";
import { mcpCallMeta } from "./mcp-call-meta.js";
export { resolveMcpDeclaredResultSize } from "./mcp-tool-meta.js";
import { withContentOrigin } from "./memory-engine/content-origin.js";
import { judgeMcpEntryCopy, snapshotMcpEntries } from "./locked-config.js";
import { validateJsonSchemaShape } from "./runner/strict-output-schema.js";
import { rosterMemberBoundProblem, rosterRemoteNameOf, schemaKeyBoundProblem } from "./tool-roster.js";
import { boundaryFlowFace } from "./cross-boundary-taint.js";
import { readMember, thrownIs, thrownName, thrownText } from "./thrown-value.js";
import { JSON_SCHEMA_SUBSCHEMA_SEATS } from "./json-schema-seats.js";
import { engineVersion } from "./version.js";
export const MCP_PREFIX = MCP_NAMESPACE.prefix;
function mcpTruncationNote(limitTokens) {
    return (`\n\n[OUTPUT TRUNCATED - exceeded ${limitTokens} token limit]\n\n` +
        `The tool output was truncated. If this MCP server provides pagination or filtering tools, use them to ` +
        `retrieve specific portions of the data. If pagination is not available, inform the user that you are ` +
        `working with truncated output and results may be incomplete.`);
}
export function gateMcpOutput(content, limitTokens = mcpMaxOutputTokens()) {
    const budgetChars = limitTokens * MCP_CHARS_PER_TOKEN;
    let used = 0;
    let truncated = false;
    const gated = [];
    for (const block of content) {
        if (block.type !== "text" || typeof block.text !== "string") {
            gated.push(block);
            continue;
        }
        if (used >= budgetChars) {
            truncated = true;
            continue;
        }
        const remaining = budgetChars - used;
        if (block.text.length <= remaining) {
            used += block.text.length;
            gated.push(block);
        }
        else {
            truncated = true;
            used = budgetChars;
            gated.push({ type: "text", text: block.text.slice(0, remaining) });
        }
    }
    if (!truncated)
        return content;
    gated.push({ type: "text", text: mcpTruncationNote(limitTokens) });
    return gated;
}
const MCP_ERROR_HEAD_CHARS = 8_000;
const MCP_ERROR_TAIL_CHARS = 2_000;
const MCP_FAILURE_TEXT_MAX = MCP_ERROR_HEAD_CHARS + MCP_ERROR_TAIL_CHARS;
const STRUCTURED_CONTENT_DEDUP_MIN_CHARS = 32;
export function structuredContentErrorLine(structuredContent, collectedText) {
    if (structuredContent === undefined)
        return undefined;
    const json = JSON.stringify(structuredContent);
    if (json === undefined)
        return undefined;
    const distinctive = json.length >= STRUCTURED_CONTENT_DEDUP_MIN_CHARS && (json.startsWith("{") || json.startsWith("["));
    if (distinctive && truncateMcpErrorText(collectedText.trim()).includes(json))
        return undefined;
    return `[structuredContent] ${truncateMcpErrorText(json)}`;
}
export function truncateMcpErrorText(s) {
    const max = MCP_ERROR_HEAD_CHARS + MCP_ERROR_TAIL_CHARS;
    if (s.length <= max)
        return s;
    let head = MCP_ERROR_HEAD_CHARS;
    let out = "";
    for (let i = 0; i < 4; i++) {
        const headText = sliceHeadSafe(s, head);
        const tailText = sliceTailSafe(s, MCP_ERROR_TAIL_CHARS);
        const removed = s.length - headText.length - tailText.length;
        out = `${headText}\n\n... [${removed} characters truncated] ...\n\n${tailText}`;
        if (out.length <= max)
            break;
        head = Math.max(0, head - (out.length - max));
    }
    return out.length < s.length ? out : s;
}
export const MCP_TOOL_TIMEOUT_DEFAULT_MS = 100_000_000;
export const MCP_ENV_MS_MIN = 1_000;
export const MCP_ENV_MS_MAX = 2_147_483_647;
export function __resetMcpEnvAnnouncements() {
    __resetEnvKnobAnnouncements();
}
function parseEnvMs(name) {
    return resolveEnvBudget(process.env[name], { name, unit: "milliseconds", default: undefined, min: MCP_ENV_MS_MIN, max: MCP_ENV_MS_MAX });
}
export function mcpToolTimeoutMs() {
    return parseEnvMs("MCP_TOOL_TIMEOUT") ?? MCP_TOOL_TIMEOUT_DEFAULT_MS;
}
export function mcpToolTotalTimeoutMs(perCallMs) {
    return parseEnvMs("MCP_TOOL_TIMEOUT_TOTAL") ?? perCallMs;
}
export const MCP_IDLE_TIMEOUT_STDIO_DEFAULT_MS = 30 * 60_000;
export const MCP_IDLE_TIMEOUT_HTTP_DEFAULT_MS = 5 * 60_000;
export function mcpIdleTimeoutMs(kind) {
    return kind === "stdio"
        ? (parseEnvMs("MCP_IDLE_TIMEOUT_STDIO") ?? MCP_IDLE_TIMEOUT_STDIO_DEFAULT_MS)
        : (parseEnvMs("MCP_IDLE_TIMEOUT_HTTP") ?? MCP_IDLE_TIMEOUT_HTTP_DEFAULT_MS);
}
function idleKindOf(kind) {
    return kind === "stdio" ? "stdio" : "http";
}
export const MCP_STARTUP_TIMEOUT_DEFAULT_MS = 30_000;
export function mcpStartupTimeoutMs(server) {
    const fromEnv = parseEnvMs("MCP_TIMEOUT") ?? MCP_STARTUP_TIMEOUT_DEFAULT_MS;
    const own = server?.startupTimeoutMs;
    if (server === undefined || own === undefined)
        return fromEnv;
    if (typeof own === "number" && Number.isSafeInteger(own) && own >= MCP_ENV_MS_MIN && own <= MCP_ENV_MS_MAX)
        return own;
    throw Object.assign(new Error(`MCP server ${typeof server.name === "string" ? `"${inlineUntrusted(server.name, 160)}"` : "(unnamed)"}: startupTimeoutMs must be a whole number of milliseconds from ${MCP_ENV_MS_MIN} to ${MCP_ENV_MS_MAX} (got ${typeof own === "number" ? String(own) : own === null ? "null" : typeof own}) — not dialed`), { code: "config.mcp_startup_timeout_invalid" });
}
export function mcpFirstRequestWaitMs(value) {
    if (value === undefined)
        return undefined;
    const ceiling = mcpStartupTimeoutMs();
    if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= ceiling)
        return value;
    const got = typeof value === "number" ? String(value) : value === null ? "null" : typeof value;
    throw Object.assign(new Error(`RunnerDeps.mcpFirstRequestWaitMs must be a whole number of milliseconds from 0 to the MCP startup bound in force (${ceiling}) (got ${got}) — omit it to wait each server's own startup bound`), { code: "config.mcp_first_request_wait_invalid", detail: { field: "RunnerDeps.mcpFirstRequestWaitMs" } });
}
function markMcpFailure(e, details) {
    e.details = details;
    return e;
}
function unauthorizedFailure(cause, ctx, failure, renewed) {
    const authorization = failure.authorization;
    const card = { code: failure.kind, delivered: failure.delivered, server: ctx.server, authorization: { reason: authorization.reason } };
    return markMcpFailure(new Error(unauthorizedLine(ctx.what, inlineUntrusted(ctx.server), authorization, renewed, writeEffectWarning(ctx.writeEffect)), { cause }), card);
}
const MCP_SPEC_ERROR_CODE_NAMES = new Map([
    [-32020, "header mismatch (the server saw an HTTP header that disagreed with the tool parameter mapped onto it)"],
    [-32021, "missing required client capability (the server requires a capability this client does not declare)"],
    [-32022, "unsupported protocol version (the server implements no protocol revision this client offers)"],
]);
export function describeMcpSpecErrorCode(code) {
    return typeof code === "number" ? MCP_SPEC_ERROR_CODE_NAMES.get(code) : undefined;
}
function sanitizeMcpErrorTextInPlace(err, declared) {
    if (!(err instanceof Error))
        return;
    const sanitized = remoteFailureText(err, err.message, declared);
    if (sanitized !== err.message)
        err.message = sanitized;
}
function namedMcpFailureText(err, declared) {
    const seat = hostSeatVerdictOf(err);
    if (seat !== undefined)
        return seat.condition;
    const text = thrownText(err);
    const words = (authorizationOwed(err) === undefined ? pastWholeReading(text) : undefined) ?? remoteFailureText(err, text, declared);
    const detail = words.length > MCP_FAILURE_TEXT_MAX ? `${cutAt(words, MCP_FAILURE_TEXT_MAX)}…` : words;
    const code = thrownIs(err, ProtocolError) ? readMember(err, "code") : undefined;
    const condition = describeMcpSpecErrorCode(code);
    return condition !== undefined ? `${condition} (MCP protocol error ${String(code)}): ${detail}` : detail;
}
function remoteErrorText(err, declared) {
    return remoteFailureText(err, thrownText(err), declared);
}
function remoteFailureText(err, text, declared) {
    const refused = authorizationOwed(err);
    return refused !== undefined ? authorizationClause(refused) : remoteWords(text, declared);
}
function inSentence(what) {
    return what.replace(/^The /, "the ");
}
function writeEffectWarning(writeEffect) {
    return writeEffect
        ? " This tool is write-capable: treat its side effects as POSSIBLY APPLIED and verify the actual state before retrying."
        : "";
}
function rethrowHonestMcpError(err, ctx) {
    const finish = (e) => {
        if (ctx.reminder !== undefined) {
            observeReminderMarkEcho({
                text: thrownText(e),
                mark: ctx.reminder.mark,
                outlet: ctx.reminder.outlet,
                counts: ctx.reminder.counts,
            });
        }
        throw e;
    };
    if (err instanceof ProtocolRevokedRefusal)
        finish(err);
    sanitizeMcpErrorTextInPlace(err, ctx.declared);
    if (ctx.idle?.signal.reason === IDLE_WATCHDOG_ABORT_REASON) {
        ctx.liveness?.observe?.("timeout");
        const serverLabel = inlineUntrusted(ctx.server);
        finish(markMcpFailure(new Error(`${ctx.what} on MCP server "${serverLabel}" received no response for ${ctx.idle.idleMs}ms (idle watchdog — ` +
            `distinct from the ${ctx.timeoutMs}ms total ceiling above). The server may still be alive but is not ` +
            `responding; the client stopped waiting.${writeEffectWarning(ctx.writeEffect)} (Set MCP_IDLE_TIMEOUT_STDIO ` +
            `/ MCP_IDLE_TIMEOUT_HTTP (ms) to change this bound.)`, { cause: err }), { code: "timeout", delivered: "unknown", server: ctx.server, timeoutMs: ctx.idle.idleMs, idleTimeout: true }));
    }
    if (ctx.signal?.aborted)
        finish(err);
    const serverLabel = inlineUntrusted(ctx.server);
    const fenceServerText = (label, raw) => delimitUntrusted(label, truncateMcpErrorText(raw));
    const breach = ctx.connection !== undefined && lostInFlight(err, ctx.site) ? readBoundBreachOf(ctx.connection) : undefined;
    const answered = breach?.sole === true ? new McpReplyOverReadBound(breach.bound, err) : undefined;
    const failure = observedFailure(answered ?? err, ctx.site, ctx.liveness, ctx.attempt === undefined);
    const details = (extra) => ({ code: failure.kind, delivered: failure.delivered, server: ctx.server, ...(failure.authorization !== undefined ? { authorization: { reason: failure.authorization.reason } } : {}), ...extra });
    switch (failure.kind) {
        case "timeout": {
            const data = readMember(err, "data");
            const total = typeof data === "object" && data !== null ? readMember(data, "maxTotalTimeout") : undefined;
            const totalMs = typeof total === "number" ? total : undefined;
            finish(markMcpFailure(new Error(totalMs !== undefined
                ? `${ctx.what} on MCP server "${serverLabel}" exceeded its total time ceiling of ${totalMs}ms (the call stayed alive — e.g. via progress notifications — but ran past the total wall-clock budget). The client stopped waiting, but the server may still be executing the request — the outcome is unknown.${writeEffectWarning(ctx.writeEffect)} (Set the MCP_TOOL_TIMEOUT_TOTAL environment variable (ms) to change this ceiling; MCP_TOOL_TIMEOUT only tunes the per-call timer, currently ${ctx.timeoutMs}ms.)`
                : `${ctx.what} on MCP server "${serverLabel}" timed out after ${ctx.timeoutMs}ms. The client stopped waiting, but the server may still be executing the request — the outcome is unknown.${writeEffectWarning(ctx.writeEffect)} (Set the MCP_TOOL_TIMEOUT environment variable (ms) to change this limit.)`, { cause: err }), totalMs !== undefined ? details({ timeoutMs: totalMs, totalTimeout: true }) : details({ timeoutMs: ctx.timeoutMs })));
        }
        case "connection_closed":
            finish(markMcpFailure(new Error(`The connection to MCP server "${serverLabel}" was lost while ${inSentence(ctx.what)} was in flight${breach !== undefined ? readBoundWhy(breach.bound) : ""}. The request may or may not have executed on the server — the outcome is unknown.${writeEffectWarning(ctx.writeEffect)}`, { cause: err }), details()));
        case "http_status":
        case "not_mcp_response":
        case "connect_refused":
        case "connection_failed": {
            const httpFailure = describeHttpTransportFailure(err, ctx.site);
            const detail = remoteErrorText(err, ctx.declared);
            const fenced = `\nThe transport error follows as external/untrusted data:\n${fenceServerText(`${ctx.server} transport error`, detail)}`;
            finish(markMcpFailure(new Error(sessionGone(err, ctx.site)
                ? `${ctx.what} met a lost session on MCP server "${serverLabel}": ${httpFailure.condition}; ${ctx.resent === true ? "the call was sent again once on a fresh session, and the server reported that one gone too — if the server executed it before answering, it ran twice" : "the call was not sent again — if the server executed it before answering, it ran"}. The outcome is unknown.${writeEffectWarning(ctx.writeEffect)}${fenced}`
                : failure.delivered === "no"
                    ? `${ctx.what} could not reach MCP server "${serverLabel}": ${httpFailure.condition}. The request was not delivered, so the server did not execute it. ${refusalScope("connection", "mcp")}${fenced}`
                    : `${ctx.what} failed at the transport layer of MCP server "${serverLabel}": ${httpFailure.condition}. The request may or may not have executed on the server — the outcome is unknown.${writeEffectWarning(ctx.writeEffect)}${fenced}`, { cause: err }), details(failure.httpStatus !== undefined ? { httpStatus: failure.httpStatus } : undefined)));
        }
        case "protocol": {
            if (answered !== undefined)
                finish(markMcpFailure(new Error(overReadBoundSentence(ctx.what, serverLabel, answered.bound, writeEffectWarning(ctx.writeEffect)), { cause: answered }), details({ readBound: answered.bound })));
            const code = thrownIs(err, ProtocolError) ? err.code : undefined;
            const condition = describeMcpSpecErrorCode(code);
            if (condition !== undefined && typeof code === "number") {
                finish(markMcpFailure(new Error(`${ctx.what} on MCP server "${serverLabel}" was rejected with MCP protocol error ${code} — ${condition}. The server's error text follows as external/untrusted data:\n${fenceServerText(`${ctx.server} error`, thrownText(err))}`, { cause: err }), details({ specErrorCode: code })));
            }
            if (ctx.attributeServer) {
                finish(markMcpFailure(new Error(`${ctx.what} on MCP server "${serverLabel}" failed. The server's error text follows as external/untrusted data:\n${fenceServerText(`${ctx.server} error`, remoteErrorText(err, ctx.declared))}`, { cause: err }), details()));
            }
            if (thrownIs(err, SdkError) && readMember(err, "code") === SdkErrorCode.InvalidResult) {
                finish(markMcpFailure(new Error(`${ctx.what} on MCP server "${serverLabel}" got a result it cannot use: the server answered, but the result does not have the shape the protocol requires, so the client dropped it. The request reached the server and may already have been executed there — the outcome is unknown.${writeEffectWarning(ctx.writeEffect)} Repeating the same call would probably meet the same answer; tell the user that the server returns a malformed result. The client's reading of the result follows as external/untrusted data:\n${fenceServerText(`${ctx.server} error`, remoteErrorText(err, ctx.declared))}`, { cause: err }), details()));
            }
            finish(markMcpFailure(err, details()));
        }
        case "unauthorized":
            finish(unauthorizedFailure(err, ctx, failure, refusedThenRenewed(err) && ctx.attempt !== "resent"));
        case "credential_unavailable":
            finish(markMcpFailure(new Error(`${ctx.what} was not sent to MCP server "${serverLabel}": ${foreignLine(thrownText(err), 400, { declared: ctx.declared })}. The request was not delivered, so the server did not execute it. 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.`), details()));
        case "revoked":
            finish(err);
        case "host_refused":
        case "spawn_failed":
        case "invalid_config":
        case "unknown": {
            const seat = hostSeatVerdictOf(err);
            if (seat !== undefined)
                finish(markMcpFailure(new Error(hostSeatLine(ctx.what, serverLabel, seat, writeEffectWarning(ctx.writeEffect)), { cause: err }), details()));
            if (ctx.attributeServer) {
                finish(markMcpFailure(new Error(`${ctx.what} on MCP server "${serverLabel}" failed. The server's error text follows as external/untrusted data:\n${fenceServerText(`${ctx.server} error`, remoteErrorText(err, ctx.declared))}`, { cause: err }), details()));
            }
            if (err instanceof Error)
                finish(markMcpFailure(err, details()));
            finish(err);
        }
    }
}
function throwDeadServer(server, what) {
    throw markMcpFailure(new Error(`MCP server "${inlineUntrusted(server)}" is disconnected (its transport closed earlier in this task). ${what} was not attempted. ${refusalScope("connection", "mcp")}`), { code: "connection_closed", delivered: "no", server });
}
export { normalizeNameSegment as normalizeMcpName, clampNameSegment } from "@sema-agent/primitives";
export * from "./image-downsample.js";
export function inferCompactSchema(value, depth = 2) {
    if (value === null)
        return "null";
    if (Array.isArray(value)) {
        if (value.length === 0)
            return "[]";
        return `[${inferCompactSchema(value[0], depth - 1)}]`;
    }
    if (typeof value === "object") {
        if (depth <= 0)
            return "{...}";
        const entries = Object.entries(value).slice(0, 10);
        const props = entries.map(([k, v]) => `${k}: ${inferCompactSchema(v, depth - 1)}`);
        const suffix = Object.keys(value).length > 10 ? ", ..." : "";
        return `{${props.join(", ")}${suffix}}`;
    }
    return typeof value;
}
function buildTransport(spec, principal, kind, carrier, pieces, pipe, onNotice, plaintextOrigins) {
    const t = spec.transport;
    if (kind === "host")
        return { transport: pipe };
    if (kind === "stdio") {
        if (!("command" in t))
            throw new Error(`MCP server "${spec.name}": transport kind "stdio" carries no command`);
        const transport = new StdioClientTransport({
            command: t.command,
            args: t.args,
            ...(pieces?.env !== undefined ? { env: { ...pieces.env } } : {}),
            stderr: "pipe",
            maxBufferSize: MCP_STDIO_READ_BOUND,
        });
        return { transport, stderr: followMcpServerStderr(transport, spec.name, onNotice, carrier.credentials), readBound: MCP_STDIO_READ_BOUND };
    }
    if (!("url" in t))
        throw new Error(`MCP server "${spec.name}": transport kind "${String(kind)}" carries no url`);
    resolveProtocolHttpHeaders(MCP_NAMESPACE.id, t.principalHeader !== undefined ? { principalHeader: t.principalHeader } : {}, principal);
    return { transport: new SessionEndingTransport(new URL(t.url), { fetch: peerFetch(carrier, t.principalHeader, principal, { server: spec.name, declared: [t.url], fingerprint: spec.fingerprint, ...(plaintextOrigins !== undefined ? { plaintextOrigins } : {}) }), requestInit: { redirect: "manual" } }) };
}
function tellBinaryKept(binarySeat, info) {
    if (info.kept.length === 0 || binarySeat?.onKept === undefined)
        return;
    try {
        binarySeat.onKept(info);
    }
    catch {
    }
}
async function keepBinaryContent(keep, base64, mimeType, prefix) {
    const { kept, clause } = await keepBytesWith(keep, Buffer.from(base64, "base64"), mimeType);
    return { block: { type: "text", text: `${prefix}Binary content (${mediaTypePhrase(mimeType)}, ${kept.bytes} bytes): ${clause}` }, kept };
}
export async function mapContent(content, serverName, bytesKeep, readsDocuments) {
    const out = [];
    const kept = [];
    const pieces = new Map();
    const keep = async (base64, mimeType, prefix) => {
        const k = await keepBinaryContent(bytesKeep, base64, mimeType, prefix);
        out.push(k.block);
        kept.push(k.kept);
        noteKeptPiece(pieces, base64, k.kept);
    };
    for (const item of content ?? []) {
        if (item.type === "text" && typeof item.text === "string") {
            out.push({ type: "text", text: item.text });
        }
        else if (item.type === "image") {
            const data = typeof item.data === "string" ? item.data : "";
            const mimeType = typeof item.mimeType === "string" ? item.mimeType : "";
            out.push({ type: "image", data, mimeType });
        }
        else if (item.type === "audio" && typeof item.data === "string" && item.data) {
            await keep(item.data, item.mimeType, `[Audio from ${inlineUntrusted(serverName ?? "MCP server")}] `);
        }
        else if (item.type === "audio") {
            out.push({ type: "text", text: `[audio attachment${typeof item.mimeType === "string" && item.mimeType !== "" ? `: ${mediaTypePhrase(item.mimeType)}` : ""}]` });
        }
        else if (item.type === "resource" && item.resource) {
            const r = item.resource;
            const blockType = mediaBlockTypeOf(r.mimeType);
            const asBlock = blockType === "image" || (blockType === "document" && readsDocuments !== false) ? blockType : undefined;
            if (typeof r.text === "string") {
                out.push({ type: "text", text: `[resource${r.uri ? ` ${r.uri}` : ""}]\n${r.text}` });
            }
            else if (typeof r.blob === "string" && r.blob !== "" && asBlock !== undefined) {
                out.push({ type: asBlock, data: r.blob, mimeType: r.mimeType });
            }
            else if (typeof r.blob === "string" && r.blob !== "") {
                const uri = typeof r.uri === "string" && r.uri !== "" ? inlineUntrusted(r.uri) : undefined;
                await keep(r.blob, r.mimeType, `[resource${uri !== undefined ? ` ${uri}` : ""}] `);
            }
            else {
                out.push({ type: "text", text: `[resource${r.uri ? ` ${r.uri}` : ""}${typeof r.mimeType === "string" && r.mimeType !== "" ? ` (${mediaTypePhrase(r.mimeType)})` : ""}]` });
            }
        }
        else if (item.type === "resource_link" && item.uri) {
            const label = item.name ? `[resource link: ${item.name}]` : "[resource link]";
            out.push({ type: "text", text: `${label} ${item.uri}${item.description ? ` (${item.description})` : ""}` });
        }
        else {
            out.push({ type: "text", text: JSON.stringify(item) });
        }
    }
    if (out.length === 0) {
        out.push({ type: "text", text: "" });
    }
    return { content: out, kept, pieces };
}
export const MCP_INVISIBLE_TEXT_RE = /[\p{Cf}\p{Co}\p{Cn}]/gu;
const MCP_SANITIZE_MAX_ROUNDS = 10;
function sanitizeMcpModelFacingText(text) {
    let out = text;
    for (let round = 0; round < MCP_SANITIZE_MAX_ROUNDS; round++) {
        const next = out.normalize("NFKC").replace(MCP_INVISIBLE_TEXT_RE, "");
        if (next === out)
            return out;
        out = next;
    }
    return out.replace(MCP_INVISIBLE_TEXT_RE, "");
}
const MCP_SCHEMA_PROSE_KEYS = new Set(["description", "title", "$comment"]);
const MCP_SCHEMA_CHILD_SEAT = new Map([
    ...JSON_SCHEMA_SUBSCHEMA_SEATS,
    ...["required", "dependentRequired", "dependencies", "$ref", "$dynamicRef", "$id", "$anchor", "$dynamicAnchor"].map((k) => [k, "nameRefs"]),
]);
class McpPayloadKeyCollision extends Error {
}
function sanitizeMcpSchemaNameRefs(value) {
    if (typeof value === "string")
        return sanitizeMcpModelFacingText(value);
    if (Array.isArray(value))
        return value.map(sanitizeMcpSchemaNameRefs);
    if (value !== null && typeof value === "object") {
        const out = Object.create(null);
        for (const [key, v] of Object.entries(value)) {
            const neutralized = sanitizeMcpModelFacingText(key);
            if (Object.hasOwn(out, neutralized))
                throw new McpPayloadKeyCollision(neutralized);
            out[neutralized] = Array.isArray(v) ? sanitizeMcpSchemaNameRefs(v) : sanitizeMcpModelFacingValue(v, "schema");
        }
        return out;
    }
    return value;
}
function sanitizeMcpModelFacingValue(value, seat = "schema") {
    if (seat === "data")
        return value;
    if (seat === "nameRefs")
        return sanitizeMcpSchemaNameRefs(value);
    if (Array.isArray(value))
        return value.map((v) => sanitizeMcpModelFacingValue(v, seat === "schema" ? "schema" : "data"));
    if (value !== null && typeof value === "object") {
        const out = Object.create(null);
        for (const [key, v] of Object.entries(value)) {
            if (seat === "schemaMap") {
                out[key] = sanitizeMcpModelFacingValue(v, "schema");
                continue;
            }
            const neutralized = sanitizeMcpModelFacingText(key);
            if (Object.hasOwn(out, neutralized))
                throw new McpPayloadKeyCollision(neutralized);
            if (seat === "properties") {
                out[neutralized] = sanitizeMcpModelFacingValue(v, "schema");
                continue;
            }
            if (MCP_SCHEMA_PROSE_KEYS.has(neutralized)) {
                out[neutralized] = typeof v === "string" ? sanitizeMcpModelFacingText(v) : v;
                continue;
            }
            out[neutralized] = sanitizeMcpModelFacingValue(v, MCP_SCHEMA_CHILD_SEAT.get(neutralized) ?? "data");
        }
        return out;
    }
    return value;
}
const MCP_TOOL_DESCRIPTION_MAX_CHARS = 4096;
const MCP_TOOL_DESCRIPTION_TRUNCATION_MARK = "… [truncated]";
function capMcpToolDescription(description) {
    if (description.length <= MCP_TOOL_DESCRIPTION_MAX_CHARS)
        return description;
    return sliceHeadSafe(description, MCP_TOOL_DESCRIPTION_MAX_CHARS) + MCP_TOOL_DESCRIPTION_TRUNCATION_MARK;
}
const MCP_SCHEMA_COMBINATOR_KEYS = ["anyOf", "oneOf", "allOf"];
const MCP_SCHEMA_PROP_NAME_RE = /^[a-zA-Z0-9_.-]{1,64}$/;
const MCP_SCHEMA_CARRY_KEYS = ["$defs", "definitions", "$schema", "additionalProperties", "description", "title"];
function isPlainSchemaObject(v) {
    return typeof v === "object" && v !== null && !Array.isArray(v);
}
function resolveLocalSchemaRef(fragment, root) {
    const ref = fragment.$ref;
    if (typeof ref !== "string")
        return fragment;
    const m = /^#\/(\$defs|definitions)\/([^/]+)$/.exec(ref);
    if (m === null)
        return fragment;
    const bucket = root[m[1]];
    if (!isPlainSchemaObject(bucket))
        return fragment;
    const resolved = bucket[m[2]];
    return isPlainSchemaObject(resolved) ? resolved : fragment;
}
function summarizeSchemaBranch(branch) {
    if (!isPlainSchemaObject(branch))
        return null;
    const required = branch.required;
    if (Array.isArray(required) && required.length > 0 && required.every((n) => typeof n === "string")) {
        return required.join(", ");
    }
    const properties = branch.properties;
    if (isPlainSchemaObject(properties)) {
        const names = Object.keys(properties);
        if (names.length > 0)
            return names.join(", ");
    }
    return null;
}
function buildSchemaFlattenNote(combinators, schema, hasAnyOfOrOneOf) {
    if (!hasAnyOfOrOneOf) {
        return "Input constraint: all listed parameters apply together (flattened from a JSON Schema allOf).";
    }
    const key = combinators.includes("oneOf") ? "oneOf" : "anyOf";
    const branches = schema[key];
    const summaries = Array.isArray(branches)
        ? [...new Set(branches.map((b) => summarizeSchemaBranch(isPlainSchemaObject(b) ? resolveLocalSchemaRef(b, schema) : b)).filter((s) => s !== null))]
        : [];
    const verb = key === "oneOf" ? "Provide parameters for exactly one of" : "Provide parameters for at least one of";
    if (summaries.length === 0)
        return `Input constraint: ${verb} the documented parameter groups (flattened from a JSON Schema ${key}).`;
    return `Input constraint: ${verb}: ${summaries.map((s) => `(${s})`).join(" or ")}.`;
}
export function normalizeMcpToolSchema(schema) {
    if (!isPlainSchemaObject(schema))
        return { outcome: "unchanged" };
    const combinatorsPresent = MCP_SCHEMA_COMBINATOR_KEYS.filter((k) => k in schema);
    if (combinatorsPresent.length === 0)
        return { outcome: "unchanged" };
    try {
        const properties = Object.create(null);
        const collectProps = (propsObj) => {
            if (!isPlainSchemaObject(propsObj))
                return;
            for (const [name, propSchema] of Object.entries(propsObj)) {
                if (MCP_SCHEMA_PROP_NAME_RE.test(name) && !(name in properties) && isPlainSchemaObject(propSchema)) {
                    properties[name] = propSchema;
                }
            }
        };
        collectProps(schema.properties);
        for (const key of combinatorsPresent) {
            const branches = schema[key];
            if (!Array.isArray(branches)) {
                return { outcome: "drop", reason: `input schema has top-level ${key} that is not an array` };
            }
            for (const branch of branches) {
                if (isPlainSchemaObject(branch))
                    collectProps(resolveLocalSchemaRef(branch, schema).properties);
            }
        }
        const required = new Set();
        const collectRequired = (reqArr) => {
            if (!Array.isArray(reqArr))
                return;
            for (const name of reqArr) {
                if (typeof name === "string" && name in properties)
                    required.add(name);
            }
        };
        collectRequired(schema.required);
        const allOfBranches = schema.allOf;
        if (Array.isArray(allOfBranches)) {
            for (const branch of allOfBranches) {
                if (isPlainSchemaObject(branch))
                    collectRequired(resolveLocalSchemaRef(branch, schema).required);
            }
        }
        const hasAnyOfOrOneOf = combinatorsPresent.includes("anyOf") || combinatorsPresent.includes("oneOf");
        const flattened = { type: "object", properties, required: [...required] };
        for (const key of MCP_SCHEMA_CARRY_KEYS) {
            if (key in schema)
                flattened[key] = schema[key];
        }
        const note = buildSchemaFlattenNote(combinatorsPresent, schema, hasAnyOfOrOneOf);
        return { outcome: "normalized", schema: flattened, note, combinators: combinatorsPresent };
    }
    catch {
        return { outcome: "drop", reason: `input schema uses top-level ${combinatorsPresent.join("/")} and could not be normalized` };
    }
}
export function mcpToolSchemaAdvisory(schema) {
    if (schema === undefined || !isPlainSchemaObject(schema))
        return undefined;
    const properties = schema.properties;
    if (!isPlainSchemaObject(properties))
        return undefined;
    for (const key of Object.keys(properties)) {
        if (!MCP_SCHEMA_PROP_NAME_RE.test(key)) {
            return `its parameter name ${inlineUntrusted(JSON.stringify(key), 80)} is outside the character set some providers accept for tool parameters (${MCP_SCHEMA_PROP_NAME_RE.source}); requests carrying this tool may be rejected by such a provider`;
        }
    }
    return undefined;
}
export function mcpToolSchemaProblem(schema) {
    if (schema === undefined)
        return undefined;
    if (typeof schema !== "object" || schema === null || Array.isArray(schema)) {
        return `advertised inputSchema is ${Array.isArray(schema) ? "an array" : `of type ${schema === null ? "null" : typeof schema}`}, not a JSON-Schema object`;
    }
    const root = schema.type;
    if (root !== undefined && root !== "object") {
        return `advertised inputSchema root type is ${typeof root === "string" ? `"${root}"` : "not a string"} — providers require an object root for tool parameters`;
    }
    try {
        const structural = validateJsonSchemaShape(schema);
        if (structural !== null)
            return `advertised inputSchema is structurally invalid — ${structural}`;
    }
    catch {
        return "advertised inputSchema is structurally invalid — validation overflow (pathological nesting)";
    }
    return undefined;
}
const OPEN_DOOR = (send) => send();
export async function materializeMcpTools(specs, principal, onElicit, _imageProcessor, reminderDisclosure, revocations, poolOpts, promptSections, dialable, signal, hostFloor, peerSeat, onAuthorizationRequired, hostSeats, onCredentialEchoed, binarySeat) {
    return materializeLegMcpTools(undefined, undefined, specs, principal, onElicit, undefined, reminderDisclosure, libraryRevocationProbe(revocations, "materializeMcpTools revocations"), poolOpts, promptSections, dialable, signal, hostFloor, receivePeerSeat(peerSeat, "materializeMcpTools peerSeat"), onAuthorizationRequired, hostSeats, onCredentialEchoed, binarySeat);
}
export async function materializeLegMcpTools(seat, onSubtreeActivity, ...[specs, principal, onElicit, , reminderDisclosure, revocations, poolOpts, promptSections, dialable, signal, hostFloor, peerSeat, onAuthorizationRequired, hostSeats, onCredentialEchoed, binarySeat, onNotice, wait, plaintextOrigins]) {
    const snapshot = snapshotMcpEntries(specs);
    const axesRefused = new WeakMap();
    const entries = snapshot.map((spec) => {
        const judged = judgeMcpEntryCopy(spec);
        if (judged.ok)
            return judged.entry;
        axesRefused.set(spec, judged.error);
        return spec;
    });
    refuseCollidingMcpServerNames(entries.map((s) => s.name));
    const revokedNow = (spec) => {
        if (revocations === undefined)
            return undefined;
        const target = mcpRevocationTarget(spec);
        return revocations(target) === "revoked" ? new ProtocolRevokedRefusal(target) : undefined;
    };
    const doorOf = (spec, kind) => revocations === undefined
        ? OPEN_DOOR
        : kind === "stdio" || kind === "host"
            ? async (send) => {
                const refused = revokedNow(spec);
                if (refused !== undefined)
                    throw refused;
                return send();
            }
            : async (send) => carryRevocation({ about: mcpRevocationTarget(spec), ask: () => revokedNow(spec) }, send);
    const dialGateOf = (spec) => (revocations === undefined ? OPEN_DOOR : async (send) => carryRevocation({ about: mcpRevocationTarget(spec), ask: () => revokedNow(spec) }, send));
    const mcpDisclosure = reminderDisclosure?.reminderMark !== undefined
        ? { mark: reminderDisclosure.reminderMark, windows: new Map(), ...(reminderDisclosure.counts !== undefined ? { counts: reminderDisclosure.counts } : {}) }
        : undefined;
    const connections = [];
    const tools = [];
    const toolAxes = [];
    const warnings = [];
    const serverInstructions = [];
    const statuses = [];
    const authorizationsAnnounced = new Set();
    const announceAuthorization = (server, authorization) => {
        if (onAuthorizationRequired === undefined || !owesAuthorization(authorization) || authorizationsAnnounced.has(server))
            return;
        authorizationsAnnounced.add(server);
        try {
            onAuthorizationRequired(server, { ...authorization });
        }
        catch {
        }
    };
    const announceEcho = echoAnnouncer(onCredentialEchoed);
    const failedStatus = (spec, err, dialKind, declared) => {
        const { failure, exchange } = readMcpFailure(err, { phase: "connect", transport: dialKind });
        const liveness = livenessOf(exchange, Date.now());
        if (failure.authorization !== undefined)
            announceAuthorization(spec.name, failure.authorization);
        return { name: spec.name, status: "failed", ...failureFields(failure), error: namedMcpFailureText(err, declared), ...(liveness !== undefined ? { liveness } : {}) };
    };
    const resourceServers = [];
    const instructionsDelta = { pendingAdds: [], pendingRemovals: [] };
    const droppedTools = [];
    let disposing = false;
    const serverHandles = [];
    const commitConnectedServer = (spec, s, transportKind) => {
        const raised = [];
        connections.push({ client: s.client, close: s.close });
        const handle = { name: spec.name, spec, client: s.client, health: s.health, tools: s.tools, listing: s.listing, intakeAt: s.intakeAt, gates: () => intakeNow(handle).gates, definitions: () => intakeNow(handle).definitions, transportKind, announce: s.announce, instructions: s.instructions, route: s.route };
        const hIdx = serverHandles.findIndex((h) => h.name === spec.name);
        if (hIdx === -1)
            serverHandles.push(handle);
        else
            serverHandles[hIdx] = handle;
        const observe = (outcome) => {
            if (disposing)
                return;
            const observed = livenessOf(outcome, Date.now());
            if (observed !== undefined)
                s.status.liveness = observed;
        };
        s.health.observe = observe;
        s.health.owed = (authorization) => void (disposing || announceAuthorization(spec.name, authorization));
        const announceClose = () => {
            if (disposing)
                return;
            s.status.transportClosed = true;
            observe("connection_closed");
            retractInstructions(instructionsDelta, spec.name);
        };
        s.announce.fn = announceClose;
        if (s.health.dead)
            announceClose();
        if (s.resourceServer) {
            const rIdx = resourceServers.findIndex((rs) => rs.server === spec.name);
            if (rIdx === -1)
                resourceServers.push(s.resourceServer);
            else
                resourceServers[rIdx] = s.resourceServer;
        }
        for (const d of s.dropped)
            droppedTools.push({ server: inlineUntrusted(spec.name, 160), ...d });
        for (const a of s.schemaAdvisories)
            raised.push(schemaAdvisoryWarning(spec.name, a.tool, a.reason));
        if (s.instructionsDefect !== undefined)
            raised.push(sectionAnswerWarning(s.instructionsDefect));
        if (s.toolsCapabilityAbsent === true && spec.allowTools !== undefined && spec.allowTools.some((name) => !isMcpFaceWord(name))) {
            raised.push(toolsCapabilityAbsentWarning(spec.name));
        }
        if (s.listingIncomplete)
            raised.push(listingIncompleteWarning(spec.name, s.listingIncomplete));
        warnings.push(...raised);
        const sIdx = statuses.findIndex((st) => st.name === spec.name);
        if (sIdx === -1)
            statuses.push(s.status);
        else
            statuses[sIdx] = s.status;
        return raised;
    };
    const readDialKind = transportKindOf;
    const dialKinds = entries.map(readDialKind);
    const liveOf = (server) => serverHandles.find((h) => h.name === server);
    const intakeNow = (h) => {
        const latest = h.listing.latest();
        if (latest.at !== h.intakeAt.at) {
            const { gates, definitions } = intakeListedTools({ tools: [...latest.entries], unproven: latest.unproven }, h.spec, linkOf(h.name), echoOf(h.spec), outputSchemaValidatorOf(h.client), binarySeat, mcpDisclosure, doorOf(h.spec, h.transportKind), h.transportKind, seat, echoReadOf(h.spec), onSubtreeActivity);
            h.intakeAt = { at: latest.at, gates, definitions };
        }
        return h.intakeAt;
    };
    const linkOf = (server) => ({
        live: () => liveOf(server),
        recover: (lost, cause = "session") => redialFlights.running(server) ?? (liveOf(server) === lost ? redialFlights.start(server, () => redialDial(server, cause)) : Promise.resolve()),
    });
    const endpointRefusal = (spec, dialKind) => {
        const transport = spec.transport;
        const raw = dialKind !== "stdio" && typeof transport === "object" && transport !== null && "url" in transport ? transport.url : undefined;
        let url;
        try {
            if (typeof raw !== "string")
                return undefined;
            url = new URL(raw);
        }
        catch {
            return undefined;
        }
        return peerRequestRefusal(`mcp: server "${inlineUntrusted(spec.name, 120)}"`, url, hostFloor);
    };
    let legEnded = false;
    const stopping = new AbortController();
    const dialStop = signal === undefined ? undefined : stopping.signal;
    let inAir = 0;
    const follow = () => {
        if (!legEnded)
            stopping.abort(signal?.reason);
    };
    const holdStop = () => {
        if (signal === undefined)
            return () => undefined;
        if (signal.aborted)
            return (follow(), () => undefined);
        if (inAir++ === 0)
            signal.addEventListener("abort", follow, { once: true });
        return () => {
            if (--inAir === 0)
                signal.removeEventListener("abort", follow);
        };
    };
    const dialServer = async (spec, dialKind, dialOpts, start = false) => {
        const stop = start ? dialStop : signal;
        const hostSeat = dialKind === "host" ? hostSeats?.get(spec.name) : undefined;
        const refusal = axesRefused.get(spec) ?? peerSeatMissing(`mcp: server "${inlineUntrusted(spec.name, 120)}"`, "credentials" in spec.transport ? spec.transport.credentials : undefined, peerSeat) ?? endpointRefusal(spec, dialKind) ?? (dialKind === "host" && hostSeat === undefined ? hostSeatMissing(spec.name) : undefined) ?? fingerprintRefusal(spec);
        if (refusal !== undefined)
            throw refusal;
        const carrier = new PeerCarrier(peerSeat, mcpPeerTarget(spec, dialKind), principal, dialKind === "stdio" ? "stdio" : "http", dialKind !== "stdio" && "principalHeader" in spec.transport && spec.transport.principalHeader !== undefined);
        dialedBy.set(spec.name, carrier);
        const startupMs = mcpStartupTimeoutMs(spec);
        const pool = poolOpts?.pool;
        const key = pool !== undefined ? McpConnectionPool.keyOf(spec, principal, dialKind, startupMs, poolOpts?.isolationScope, peerSeat) : undefined;
        const attempt = pool !== undefined && key !== undefined ? pool.attempt(key, spec.name, { fresh: dialOpts.fresh === true }) : undefined;
        if (attempt?.recalled !== undefined) {
            const { reason } = attempt.recalled;
            if (typeof reason === "object" && reason !== null)
                dialedBy.set(spec.name, carrierOf(reason) ?? carrier);
            recalledOf.add(spec.name);
            throw reason;
        }
        const through = doorOf(spec, dialKind);
        const gate = dialGateOf(spec);
        const dial = () => gate(() => connectServer(spec, principal, onElicit, binarySeat, mcpDisclosure, through, dialKind, poolOpts?.pool, { ...dialOpts, startupMs, ...(key !== undefined ? { key } : {}), link: linkOf(spec.name), carrier, announceEcho: (where) => announceEcho(spec.name, where), ...(onNotice !== undefined ? { onNotice } : {}), ...(plaintextOrigins !== undefined ? { plaintextOrigins } : {}), ...(stop !== undefined ? { signal: stop } : {}), ...(hostSeat !== undefined ? { hostSeat } : {}) }, seat, onSubtreeActivity));
        const letGo = start ? holdStop() : () => undefined;
        const connected = await dial()
            .catch(async (err) => {
            if (typeof err === "object" && err !== null)
                dialedBy.set(spec.name, carrierOf(err) ?? carrier);
            const dialing = (typeof err === "object" && err !== null ? carrierOf(err) : undefined) ?? carrier;
            if (!(dialing.renewed && answeredUnauthorized(err)) || stop?.aborted === true)
                throw err;
            return dial();
        })
            .catch((err) => {
            if (attempt?.settle(attemptKeeps(err, dialKind, stop, start) ? { failed: err } : "unkept") === true)
                keptOf.add(spec.name);
            throw err;
        })
            .finally(letGo);
        attempt?.settle("connected");
        dialedBy.set(spec.name, carrierOf(connected.client) ?? carrier);
        return connected;
    };
    const attemptKeeps = (err, dialKind, stop, start) => (start || !disposing) && stop?.aborted !== true && readMcpFailure(err, { phase: "connect", transport: dialKind }).failure.kind === "timeout";
    const recalledOf = new Set();
    const keptOf = new Set();
    const prefixOf = (name) => mintNamespacePrefix(MCP_NAMESPACE, name);
    const dialedBy = new Map();
    const echoOf = (spec) => dialedBy.get(spec.name)?.sent ?? [];
    const echoReadOf = (spec) => carrierEcho(dialedBy.get(spec.name) ?? NO_CREDENTIAL_ECHO, (where) => announceEcho(spec.name, where));
    const heldCount = (name) => serverHandles.find((h) => h.name === name)?.tools.length ?? 0;
    const reconcileInstructions = (name, after, connected) => {
        if (!connected)
            return retractInstructions(instructionsDelta, name);
        unretractInstructions(instructionsDelta, name);
        if (after !== undefined)
            tellInstructions(instructionsDelta, after);
        else
            withdrawInstructionAdds(instructionsDelta, name);
    };
    let dropHeld;
    const stoppedAt = new Set();
    const failedLanding = (spec, declaredAt, err) => {
        if (stoppedAt.has(spec.name))
            return undefined;
        const declared = echoOf(spec);
        const warning = asServerWarning(spec, err, declared, recalledOf.has(spec.name) ? "recalled" : keptOf.has(spec.name) ? "kept" : undefined);
        const status = failedStatus(spec, err, dialKinds[declaredAt], declared);
        warnings.push(warning);
        const sIdx = statuses.findIndex((st) => st.name === spec.name);
        if (sIdx === -1)
            statuses.push(status);
        else
            statuses[sIdx] = status;
        return { server: spec.name, prefix: prefixOf(spec.name), outcome: "failed", status, tools: [], axes: [], dropped: [], warnings: [warning] };
    };
    const connectedLanding = (spec, declaredAt, s) => {
        reconcileInstructions(spec.name, s.instructions, true);
        const raised = commitConnectedServer(spec, s, dialKinds[declaredAt]);
        const resources = s.resourceServer !== undefined ? buildResourceTools(resourceServers, binarySeat) : undefined;
        return {
            server: spec.name,
            prefix: prefixOf(spec.name),
            outcome: "connected",
            status: s.status,
            tools: s.tools,
            axes: s.axes,
            dropped: s.dropped.map((d) => ({ server: inlineUntrusted(spec.name, 160), ...d })),
            warnings: raised,
            ...(resources !== undefined && resources.tools.length > 0 ? { resources } : {}),
        };
    };
    const dialed = entries.map((spec) => dialDecision(dialable, spec));
    const attempts = entries.map((spec, i) => (dialed[i] ? dialServer(spec, dialKinds[i], { sections: promptSections }, true) : Promise.resolve(null)));
    const settled = entries.map(() => undefined);
    attempts.forEach((p, i) => void p.then((value) => void (settled[i] = { status: "fulfilled", value }), (reason) => void (settled[i] = { status: "rejected", reason })));
    const connecting = wait?.connecting;
    const waitStarted = Date.now();
    const boundOf = (spec) => {
        try {
            return mcpStartupTimeoutMs(spec);
        }
        catch {
            return 0;
        }
    };
    const told = connecting === undefined ? undefined : setTimeout(() => entries.forEach((spec, i) => void (dialed[i] && settled[i] === undefined && connecting.tell(spec.name, Date.now() - waitStarted, boundOf(spec)))), MCP_CONNECTING_NOTICE_AFTER_MS);
    try {
        await Promise.all(attempts.map((p, i) => (wait?.budgetMs === undefined ? p.catch(() => undefined) : settledWithin(p, Math.min(wait.budgetMs, boundOf(entries[i]))))));
    }
    finally {
        if (told !== undefined)
            clearTimeout(told);
    }
    const late = [];
    try {
        for (let i = 0; i < entries.length; i++) {
            const r = settled[i];
            const spec = entries[i];
            if (r === undefined) {
                late.push(i);
                statuses.push({ name: spec.name, status: "pending" });
            }
            else if (r.status === "fulfilled") {
                const s = r.value;
                if (s === null)
                    continue;
                tools.push(...s.tools);
                toolAxes.push(...s.axes);
                if (s.instructions) {
                    serverInstructions.push(s.instructions);
                    toldOnDial(instructionsDelta, s.instructions);
                }
                commitConnectedServer(spec, s, dialKinds[i]);
            }
            else {
                const declared = echoOf(spec);
                warnings.push(asServerWarning(spec, r.reason, declared, recalledOf.has(spec.name) ? "recalled" : keptOf.has(spec.name) ? "kept" : undefined));
                statuses.push(failedStatus(spec, r.reason, dialKinds[i], declared));
            }
        }
        const resourceTools = buildResourceTools(resourceServers, binarySeat);
        tools.push(...resourceTools.tools);
        toolAxes.push(...resourceTools.axes);
    }
    catch (mergeErr) {
        disposing = true;
        await Promise.allSettled(settled.map((r) => (r?.status === "fulfilled" && r.value !== null ? r.value.close() : Promise.resolve())));
        for (const i of late)
            void attempts[i].then((s) => s?.close(), () => undefined);
        throw mergeErr;
    }
    for (const i of late)
        void attempts[i].catch(() => void (dialStop?.aborted === true && stoppedAt.add(entries[i].name)));
    const lateFace = late.length === 0
        ? undefined
        : pendingFaceOf(late.map((i) => ({ name: entries[i].name, boundMs: boundOf(entries[i]), declaredAt: i, attempt: attempts[i] })), {
            taken: () => !disposing && !legEnded,
            connected: (l, s) => connectedLanding(entries[l.declaredAt], l.declaredAt, s),
            failed: (l, err) => failedLanding(entries[l.declaredAt], l.declaredAt, err),
            close: (s) => void s.close().catch(() => undefined),
            unheard: (landing) => wait?.unheard?.(landing.warnings[0], landing.status),
        });
    dropHeld = lateFace?.dropHeld;
    const pending = lateFace?.face;
    const declineRedial = (server, outcome, reason) => ({ server, prefix: prefixOf(server), outcome, reason, toolCount: heldCount(server), added: [], removed: [] });
    const redialFlights = new Flights();
    const ownerStopped = () => (disposing ? "this materialization is being disposed — the task is tearing down" : signal?.aborted === true ? "the run was aborted" : undefined);
    const redialDial = async (server, cause = "session") => {
        const prefix = prefixOf(server);
        const declined = (outcome, reason) => declineRedial(server, outcome, reason);
        const stopped = ownerStopped();
        if (stopped !== undefined)
            return declined("refused", stopped);
        const spec = entries.find((e) => e.name === server);
        if (spec === undefined)
            return declined("not_declared", "no MCP server of that name is declared for this task");
        if (revokedNow(spec) !== undefined)
            return declined("refused", "server revoked by the operator — the re-dial did not contact it");
        const hIdx = serverHandles.findIndex((h) => h.name === server);
        const prior = hIdx === -1 ? undefined : serverHandles[hIdx];
        const priorNames = prior ? prior.tools.map((t) => t.name) : [];
        if (prior) {
            prior.announce.fn = undefined;
            prior.health.observe = undefined;
            if (cause !== "expired") {
                serverHandles.splice(hIdx, 1);
                const cIdx = connections.findIndex((c) => c.client === prior.client);
                const priorConnection = cIdx === -1 ? undefined : connections.splice(cIdx, 1)[0];
                await (priorConnection?.close() ?? prior.client.close()).catch(() => undefined);
            }
        }
        const dialKind = readDialKind(spec);
        const dialed = await dialServer(spec, dialKind, { fresh: cause !== "expired", sections: promptSections, ...(prior !== undefined ? { carried: prior.listing.latest().entries } : {}) }).then((connected) => ({ connected }), (err) => ({ err }));
        if (cause === "expired" && prior !== undefined) {
            if (serverHandles.includes(prior))
                serverHandles.splice(serverHandles.indexOf(prior), 1);
            void settledInFlight(prior.client).then(() => (connections.find((c) => c.client === prior.client)?.close() ?? prior.client.close()).catch(() => undefined));
        }
        const stoppedLate = ownerStopped();
        if (stoppedLate !== undefined) {
            if ("connected" in dialed)
                await dialed.connected.close().catch(() => undefined);
            return declined("refused", `${stoppedLate} while the re-dial was in flight — nothing new was kept or recorded`);
        }
        if ("err" in dialed) {
            const err = dialed.err;
            const declared = echoOf(spec);
            const status = failedStatus(spec, err, dialKind, declared);
            const failure = status.error;
            const sIdx = statuses.findIndex((st) => st.name === server);
            if (sIdx === -1)
                statuses.push(status);
            else
                statuses[sIdx] = status;
            const raised = asServerWarning(spec, err, declared);
            warnings.push(raised);
            reconcileInstructions(server, undefined, false);
            return withRaised([raised], {
                server,
                prefix,
                outcome: "refused",
                reason: foreignLine(failure, 240, { declared }),
                toolCount: 0,
                added: [],
                removed: priorNames,
                tools: [],
                axes: [],
                dropped: [],
                warnings: [raised.message],
                status,
            });
        }
        const { connected } = dialed;
        const raised = commitConnectedServer(spec, connected, dialKind);
        reconcileInstructions(server, connected.instructions, true);
        const newNames = connected.tools.map((t) => t.name);
        return withRaised(raised, {
            server,
            prefix,
            outcome: "reconnected",
            toolCount: newNames.length,
            added: newNames.filter((n) => !priorNames.includes(n)),
            removed: priorNames.filter((n) => !newNames.includes(n)),
            tools: connected.tools,
            axes: connected.axes,
            dropped: connected.dropped.map((d) => ({ server: inlineUntrusted(server, 160), ...d })),
            ...(raised.length > 0 ? { warnings: raised.map((w) => w.message) } : {}),
            status: connected.status,
            ...(connected.listingIncomplete !== undefined ? { listingIncomplete: connected.listingIncomplete } : {}),
        });
    };
    const withRaised = (raised, result) => (recordRaisedWarnings(result, raised), result);
    const redialOnce = (server) => pending?.names().includes(server) === true
        ? Promise.resolve(declineRedial(server, "refused", "this server's first connection attempt is still in flight — try again once it has connected or failed (its handshake waits at most the server's startup timeout, `startupTimeoutMs`)"))
        : redialFlights.running(server) === undefined ? redialFlights.start(server, () => redialDial(server)) : Promise.resolve(declineRedial(server, "refused", "a re-dial of this server is already in flight — wait for it to settle"));
    return {
        tools,
        toolAxes,
        warnings,
        serverInstructions,
        instructionsDelta,
        droppedTools,
        statuses,
        refresh: async (server) => {
            if (pending !== undefined && server !== undefined)
                await pending.settled({ servers: [server], ...(signal !== undefined ? { signal } : {}) });
            const targets = server !== undefined ? serverHandles.filter((h) => h.name === server) : [...serverHandles];
            const results = [];
            if (server !== undefined && targets.length === 0) {
                return [{ server, prefix: prefixOf(server), status: "not_connected", toolCount: 0, added: [], removed: [] }];
            }
            for (const h of targets) {
                if (disposing || h.health.dead) {
                    results.push({ server: h.name, prefix: prefixOf(h.name), status: "not_connected", toolCount: h.tools.length, added: [], removed: [] });
                    continue;
                }
                const site = requestSite(h.client);
                try {
                    const at = h.listing.open();
                    const listed = await listToolsLenient(h.client, doorOf(h.spec, h.transportKind), undefined, echoOf(h.spec));
                    const answered = h.listing.answer(at, listed.tools, listed.incomplete !== undefined);
                    const mergedRaw = answered.view;
                    if (!answered.recorded) {
                        results.push({ server: h.name, prefix: prefixOf(h.name), status: "failed", toolCount: h.tools.length, added: [], removed: [], error: "a later listing of this server was opened and applied while this one was in the air — this one was discarded" });
                        continue;
                    }
                    const { serverTools, serverAxes, gates, definitions, dropped } = intakeListedTools({ tools: [...mergedRaw], unproven: answered.unproven }, h.spec, linkOf(h.name), echoOf(h.spec), outputSchemaValidatorOf(h.client), binarySeat, mcpDisclosure, doorOf(h.spec, h.transportKind), h.transportKind, seat, echoReadOf(h.spec), onSubtreeActivity);
                    const priorNames = h.tools.map((t) => t.name);
                    const newNames = serverTools.map((t) => t.name);
                    const added = newNames.filter((n) => !priorNames.includes(n));
                    const removed = priorNames.filter((n) => !newNames.includes(n));
                    h.tools = serverTools;
                    h.intakeAt = { at, gates, definitions };
                    const entry = {
                        server: h.name,
                        prefix: prefixOf(h.name),
                        status: "refreshed",
                        toolCount: newNames.length,
                        added,
                        removed,
                        tools: serverTools,
                        axes: serverAxes,
                        dropped: dropped.map((d) => ({ server: inlineUntrusted(h.name, 160), ...d })),
                        ...(h.instructions !== undefined ? { instructions: h.instructions } : {}),
                        ...(listed.incomplete !== undefined
                            ? { listingIncomplete: listed.incomplete, error: `tool listing incomplete — ${listingIncompleteNote(listed.incomplete)}` }
                            : {}),
                    };
                    if (listed.incomplete === undefined && listed.toolsCapabilityAbsent !== true)
                        recordListedNames(entry, listed.tools.map((t) => t.name));
                    results.push(entry);
                }
                catch (err) {
                    if (err instanceof ProtocolRevokedRefusal) {
                        results.push({ server: h.name, prefix: prefixOf(h.name), status: "revoked", toolCount: h.tools.length, added: [], removed: [], error: "server revoked by the operator — the refresh sent it no further request" });
                        continue;
                    }
                    observedFailure(err, site, h.health, true);
                    results.push({
                        server: h.name,
                        prefix: prefixOf(h.name),
                        status: "failed",
                        toolCount: h.tools.length,
                        added: [],
                        removed: [],
                        error: foreignLine(namingLostSession(err, site, namedMcpFailureText(err, echoOf(h.spec))), 240, { declared: echoOf(h.spec) }),
                    });
                }
            }
            for (let i = 0; i < results.length; i++) {
                const entry = results[i];
                if (entry.status !== "refreshed")
                    continue;
                const live = serverHandles.find((h) => h.name === entry.server);
                if (live !== undefined && live.tools === entry.tools && !live.health.dead)
                    continue;
                const kept = { server: entry.server, prefix: entry.prefix, toolCount: heldCount(entry.server), added: [], removed: [] };
                results[i] =
                    live?.tools === entry.tools
                        ? { ...kept, status: "not_connected" }
                        : { ...kept, status: "failed", error: "this server was re-dialed while the refresh was reading another server — the listing is from the connection that re-dial replaced, so it was discarded" };
            }
            return results;
        },
        reconnect: redialOnce,
        ...(pending !== undefined ? { pending } : {}),
        ended: () => void (legEnded = true),
        ...mcpHostReadPorts({ declaration: (name) => entries.find((e) => e.name === name), stopped: ownerStopped, route: (name) => serverHandles.find((h) => h.name === name)?.route, revoked: revokedNow, deps: binarySeat === undefined ? READ_DEPS : { ...READ_DEPS, keep: toolResultBytesKeeper(binarySeat, MCP_HOST_READ_CALL) } }),
        dispose: async () => {
            disposing = true;
            dropHeld?.();
            await Promise.allSettled(connections.map((c) => c.close()));
            if (poolOpts?.ownsPool === true)
                poolOpts.pool.close();
        },
    };
}
function mcpAxisFor(namespacedName, annotations) {
    if (!annotations)
        return undefined;
    const axis = { name: namespacedName };
    let any = false;
    if (annotations.destructiveHint === true) {
        axis.irreversibility = "always";
        any = true;
    }
    if (annotations.openWorldHint === true) {
        axis.egress = true;
        any = true;
    }
    return any ? axis : undefined;
}
export function applyCallerAxisOverride(name, hint, override) {
    if (!override)
        return hint;
    let effect = hint?.effect;
    let egress = hint?.egress;
    let irrev = hint?.irreversibility;
    if (override.effect !== undefined)
        effect = override.effect;
    if (override.egress !== undefined)
        egress = override.egress;
    if (override.irreversibility !== undefined)
        irrev = override.irreversibility;
    const axis = { name };
    if (effect !== undefined)
        axis.effect = effect;
    if (egress !== undefined)
        axis.egress = egress;
    if (irrev !== undefined)
        axis.irreversibility = irrev;
    return axis.effect !== undefined || axis.egress !== undefined || axis.irreversibility !== undefined ? axis : undefined;
}
const MCP_HOST_READ_CALL = "mcp_host_read";
const READ_DEPS = {
    walk: walkMcpListPages,
    fingerprint: listEntryFingerprint,
    timeoutMs: mcpToolTimeoutMs,
    idleMs: mcpIdleTimeoutMs,
    idleTripText: idleWatchdogTripText,
    failureText: namedMcpFailureText,
};
export const NO_DECLARED_MCP_READ_PORTS = mcpHostReadPorts({ declaration: () => undefined, stopped: () => undefined, route: () => undefined, revoked: () => undefined, deps: READ_DEPS });
const MCP_SKILLS_EXTENSION = "io.modelcontextprotocol/skills";
const MAX_DIR_READ_PAGES = 20;
const DIR_READ_NOT_A_DIRECTORY_RE = /not a directory|isn'?t a directory|not a folder/i;
const DIR_READ_NOT_FOUND_RE = /not found|no such|does not exist|doesn'?t exist|unknown (?:resource|uri)/i;
export function classifyDirReadInvalidParams(message) {
    if (DIR_READ_NOT_A_DIRECTORY_RE.test(message))
        return "not_directory";
    if (DIR_READ_NOT_FOUND_RE.test(message))
        return "not_found";
    return "not_directory";
}
function resourceLine(r) {
    return `${r.uri}${r.name ? ` — ${r.name}` : ""}${r.mimeType ? ` (${r.mimeType})` : ""}${r.description ? `: ${r.description}` : ""}`;
}
function serverNames(servers) {
    return servers.map((r) => r.server).join(", ") || "(none)";
}
const MIN_MCP_PAGE_BUDGET_MS = 250;
function continuationPageFloorMs(budgetMs) {
    return Math.max(1, Math.min(MIN_MCP_PAGE_BUDGET_MS, Math.floor(budgetMs / 10)));
}
export function listEntryFingerprint(entry) {
    try {
        const json = JSON.stringify(entry);
        return typeof json === "string" ? json : undefined;
    }
    catch {
        return undefined;
    }
}
const LIST_ENTRY_FINGERPRINT_MAX_CHARS = 8 * 1024;
const LOOP_REWIND_FINGERPRINT_MAX_CHARS = 1024 * 1024;
export async function walkMcpListPages(fetchPage, opts) {
    const items = [];
    const used = new Set();
    const deadline = Date.now() + opts.budgetMs;
    let cursor;
    let pages = 0;
    for (;;) {
        const remainingMs = pages === 0 ? opts.budgetMs : deadline - Date.now();
        if (pages > 0 && remainingMs < continuationPageFloorMs(opts.budgetMs)) {
            return { items, incomplete: { reason: "budget_exhausted", pages, budgetMs: opts.budgetMs } };
        }
        let page;
        try {
            page = await fetchPage(cursor, remainingMs);
        }
        catch (err) {
            if (pages === 0 || opts.signal?.aborted || err instanceof ProtocolRevokedRefusal)
                throw err;
            return { items, incomplete: { reason: "page_error", pages, error: foreignLine(remoteErrorText(err, opts.declared ?? []), 240, { declared: opts.declared ?? [] }) } };
        }
        opts.onPage?.();
        const pageStart = items.length;
        items.push(...page.items);
        pages++;
        if (page.cursorInvalid === true)
            return { items, incomplete: { reason: "cursor_invalid", pages } };
        const next = page.nextCursor;
        if (next === undefined)
            return { items };
        if (used.has(next)) {
            const fresh = [];
            const fingerprintOf = opts.fingerprintOf;
            if (fingerprintOf !== undefined) {
                const before = new Set();
                let keying = LOOP_REWIND_FINGERPRINT_MAX_CHARS;
                const keyOf = (item) => {
                    if (keying <= 0)
                        return undefined;
                    const fp = fingerprintOf(item);
                    if (fp === undefined) {
                        keying -= LIST_ENTRY_FINGERPRINT_MAX_CHARS;
                        return undefined;
                    }
                    keying -= fp.length;
                    return fp.length <= LIST_ENTRY_FINGERPRINT_MAX_CHARS ? fp : undefined;
                };
                for (let i = 0; i < pageStart; i++) {
                    const fp = keyOf(items[i]);
                    if (fp !== undefined)
                        before.add(fp);
                }
                for (const item of page.items) {
                    const fp = keyOf(item);
                    if (fp !== undefined && before.has(fp))
                        continue;
                    fresh.push(item);
                }
            }
            items.length = pageStart;
            items.push(...fresh);
            return { items, incomplete: { reason: "cursor_loop", pages } };
        }
        if (pages >= MAX_MCP_LIST_PAGES)
            return { items, incomplete: { reason: "page_cap", pages } };
        used.add(next);
        cursor = next;
    }
}
function idleWatchdogTripText(idleMs) {
    return `received no response for ${idleMs}ms (idle watchdog; set MCP_IDLE_TIMEOUT_STDIO / MCP_IDLE_TIMEOUT_HTTP to change this bound)`;
}
async function readDirViaExtension(rs, uri, signal, timeoutMs, watchdog) {
    const resources = [];
    let cursor;
    let pages = 0;
    do {
        let page;
        try {
            const params = { uri, ...(cursor !== undefined ? { cursor } : {}) };
            page = await rs.through(() => rs.client.request({ method: "resources/directory/read", params }, ListResourcesResultSchema, { signal: watchdog.combinedSignal, timeout: timeoutMs }));
        }
        catch (err) {
            if (err instanceof ProtocolRevokedRefusal)
                throw err;
            if (err instanceof ProtocolError && err.code === ProtocolErrorCode.InvalidParams) {
                if (pages > 0)
                    return { kind: "ok", resources, cursorInvalid: true };
                const detail = remoteErrorText(err, rs.declared);
                return { kind: classifyDirReadInvalidParams(detail), detail };
            }
            if (notServed(err))
                return { kind: "unsupported" };
            if (pages > 0 && !signal?.aborted) {
                return { kind: "ok", resources, incomplete: remoteErrorText(err, rs.declared) };
            }
            throw err;
        }
        watchdog.rearm();
        resources.push(...page.resources);
        cursor = page.nextCursor;
        pages++;
    } while (cursor !== undefined && pages < MAX_DIR_READ_PAGES);
    if (cursor !== undefined)
        return { kind: "ok", resources, truncated: true };
    return { kind: "ok", resources };
}
function renderDirChildren(server, uri, children, flags) {
    const notes = [];
    if (flags?.truncated) {
        notes.push(`[listing truncated: the ${MAX_DIR_READ_PAGES}-page pagination limit was reached — more entries may exist beyond this listing]`);
    }
    if (flags?.incomplete !== undefined) {
        notes.push(`[listing incomplete: the server failed mid-pagination (${foreignLine(flags.incomplete.error, undefined, { declared: flags.incomplete.declared })}) — only the pages retrieved before the failure are shown]`);
    }
    if (flags?.cursorInvalid) {
        notes.push(`[listing incomplete: the server rejected the pagination cursor (invalid or expired) — only the pages retrieved before the rejection are shown; more entries may exist beyond this listing]`);
    }
    if (flags?.listing)
        notes.push(listingIncompleteNote(flags.listing));
    const detailFlags = {
        ...(flags?.truncated ? { truncated: true } : {}),
        ...(flags?.incomplete !== undefined ? { incomplete: true, error: flags.incomplete.error } : {}),
        ...(flags?.cursorInvalid ? { incomplete: true, cursorInvalid: true } : {}),
        ...(flags?.listing ? { incomplete: true, listing: flags.listing } : {}),
    };
    const listing = children.length === 0
        ? `(Empty directory: ${inlineUntrusted(uri)})`
        : delimitUntrusted(`${server} dir ${uri}`, children.map((r) => resourceLine(r)).join("\n"));
    return {
        content: [{ type: "text", text: notes.length ? `${listing}\n${notes.join("\n")}` : listing }],
        details: { resources: children.map((r) => ({ server, ...r })), ...detailFlags },
        terminate: false,
    };
}
function buildResourceTools(resourceServers, binarySeat) {
    const listable = () => resourceServers.filter((rs) => rs.listAllowed);
    const readable = () => resourceServers.filter((rs) => rs.readAllowed);
    if (listable().length === 0 && readable().length === 0)
        return { tools: [], axes: [] };
    const tools = [];
    const axes = [];
    if (listable().length > 0) {
        tools.push({
            name: LIST_MCP_RESOURCES,
            description: "List the resources available from connected MCP servers (uri / name / description). Pass `server` to limit " +
                "to one server, or omit it to list across all. Resource metadata is external/untrusted data.",
            label: LIST_MCP_RESOURCES,
            executionMode: "parallel",
            parameters: {
                type: "object",
                properties: { server: { type: "string", description: "Optional: only list this MCP server's resources." } },
            },
            execute: async (_id, params, signal) => {
                const { server } = (params ?? {});
                const live = listable();
                const targets = server ? live.filter((rs) => rs.server === server) : live;
                if (server && targets.length === 0) {
                    return { content: [{ type: "text", text: `Error: no MCP server ${inlineUntrusted(server)} with listable resources. Available: ${serverNames(live)}.` }], details: undefined, terminate: false };
                }
                const sections = [];
                const all = [];
                const errors = [];
                const incomplete = [];
                for (const rs of targets) {
                    if (rs.health.dead) {
                        errors.push({ server: rs.server, error: "server disconnected (transport closed earlier in this task)" });
                        sections.push(`[${rs.server}] Error: server disconnected — its resources are unavailable.`);
                        continue;
                    }
                    const idleMs = mcpIdleTimeoutMs(rs.transportKind);
                    const watchdog = armMcpIdleWatchdog(rs.health, idleMs, signal);
                    const site = requestSite(rs.client);
                    try {
                        const walk = await readMcpListing(rs, "resources", watchdog, idleMs, signal, READ_DEPS);
                        all.push(...walk.entries.map((r) => ({ server: rs.server, ...r })));
                        const lines = walk.entries.map((r) => resourceLine(r));
                        const body = lines.length ? lines.join("\n") : "(no resources)";
                        if (walk.incomplete) {
                            incomplete.push({ server: rs.server, ...walk.incomplete });
                            sections.push(`[${rs.server}]\n${body}\n${listingIncompleteNote(walk.incomplete)}`);
                        }
                        else {
                            sections.push(`[${rs.server}]\n${body}`);
                        }
                    }
                    catch (err) {
                        if (err instanceof ProtocolRevokedRefusal) {
                            errors.push({ server: rs.server, error: "server revoked by the operator (request not sent)" });
                            sections.push(`[${rs.server}] Error: MCP server revoked by the operator — the request was NOT sent. ${refusalScope("revocation", "mcp")}`);
                            continue;
                        }
                        sanitizeMcpErrorTextInPlace(err, rs.declared);
                        if (signal?.aborted)
                            throw err;
                        observedFailure(err, site, rs.health, true);
                        const msg = watchdog.idleSignal.reason === IDLE_WATCHDOG_ABORT_REASON
                            ? idleWatchdogTripText(idleMs)
                            : namingLostSession(err, site, remoteErrorText(err, rs.declared));
                        errors.push({ server: rs.server, error: msg });
                        sections.push(`[${rs.server}] Error: could not list resources: ${foreignLine(msg, undefined, { declared: rs.declared })}`);
                    }
                    finally {
                        watchdog.dispose();
                    }
                }
                const body = sections.join("\n\n");
                return {
                    content: [{ type: "text", text: sections.length ? delimitUntrusted("mcp resources", body) : "(no MCP resources)" }],
                    details: { resources: all, ...(errors.length ? { errors } : {}), ...(incomplete.length ? { incomplete } : {}) },
                    terminate: false,
                };
            },
        });
        axes.push({ name: LIST_MCP_RESOURCES, effect: "read" });
    }
    if (readable().length > 0) {
        tools.push({
            name: READ_MCP_RESOURCE,
            description: "Read a specific MCP resource by `server` + `uri` (from ListMcpResourcesTool). Its content is external/untrusted data.",
            label: READ_MCP_RESOURCE,
            executionMode: "parallel",
            parameters: {
                type: "object",
                properties: {
                    server: { type: "string", description: "The MCP server name (from ListMcpResourcesTool)." },
                    uri: { type: "string", description: "The resource URI to read." },
                },
                required: ["server", "uri"],
            },
            execute: async (toolCallId, params, signal) => {
                const { server, uri } = (params ?? {});
                if (!server || !uri)
                    return { content: [{ type: "text", text: "Error: `server` and `uri` are required." }], details: undefined, terminate: false };
                const live = readable();
                const rs = live.find((r) => r.server === server);
                if (!rs)
                    return { content: [{ type: "text", text: `Error: no MCP server ${inlineUntrusted(server)} with readable resources. Available: ${serverNames(live)}.` }], details: undefined, terminate: false };
                const what = `The read of resource ${inlineUntrusted(uri)}`;
                if (rs.health.dead)
                    throwDeadServer(server, what);
                const timeoutMs = mcpToolTimeoutMs();
                const idleMs = mcpIdleTimeoutMs(rs.transportKind);
                const watchdog = armMcpIdleWatchdog(rs.health, idleMs, signal);
                const site = requestSite(rs.client);
                let res;
                try {
                    res = await fetchMcpAnswer(rs, "resources/read", { uri }, watchdog, timeoutMs).catch((err) => rethrowHonestMcpError(err, { server, declared: rs.declared, what, timeoutMs, writeEffect: false, signal, attributeServer: true, site, idle: { signal: watchdog.idleSignal, idleMs }, liveness: rs.health, connection: rs.client }));
                }
                catch (err) {
                    if (err instanceof ProtocolRevokedRefusal)
                        return revokedCallResult(err, what);
                    throw err;
                }
                finally {
                    watchdog.dispose();
                }
                const keepBlob = toolResultBytesKeeper(binarySeat, toolCallId);
                const entries = await Promise.all(res.items.map(async (entry) => {
                    const c = typeof entry === "object" && entry !== null ? entry : {};
                    const at = typeof c.uri === "string" ? c.uri : uri;
                    const mimeType = typeof c.mimeType === "string" ? c.mimeType : undefined;
                    if (typeof c.text === "string")
                        return { line: c.text };
                    const blob = c.blob;
                    if (typeof blob === "string" && blob) {
                        const k = await keepBinaryContent(keepBlob, blob, mimeType, `[binary resource ${at}] `);
                        return { line: k.block.text, piece: { base64: blob, kept: k.kept } };
                    }
                    return { line: `[binary resource ${at}${mimeType ? ` (${mediaTypePhrase(mimeType)})` : ""}]` };
                }));
                const kept = [];
                const pieces = new Map();
                for (const entry of entries) {
                    const piece = entry?.piece;
                    if (piece === undefined)
                        continue;
                    kept.push(piece.kept);
                    noteKeptPiece(pieces, piece.base64, piece.kept);
                }
                tellBinaryKept(binarySeat, { server, toolName: READ_MCP_RESOURCE, toolCallId, kept });
                const text = entries.map((e) => e?.line ?? "").join("\n");
                return { content: [{ type: "text", text: delimitUntrusted(`${server} resource ${uri}`, text) }], details: withKeptPieces(res.answer, pieces), terminate: false };
            },
        });
        axes.push({ name: READ_MCP_RESOURCE, effect: "read" });
    }
    if (listable().length > 0) {
        tools.push({
            name: READ_MCP_RESOURCE_DIR,
            description: "List the MCP resources UNDER a directory `uri` on `server` — its child resources (those whose uri is " +
                "nested below it; subdirectories carry mimeType \"inode/directory\"). Use it to browse a hierarchical " +
                "resource namespace after ListMcpResourcesTool. Resource metadata is external/untrusted data.",
            label: READ_MCP_RESOURCE_DIR,
            executionMode: "parallel",
            parameters: {
                type: "object",
                properties: {
                    server: { type: "string", description: "The MCP server name (from ListMcpResourcesTool)." },
                    uri: { type: "string", description: "The directory resource URI to list under." },
                },
                required: ["server", "uri"],
            },
            execute: async (_id, params, signal) => {
                const { server, uri } = (params ?? {});
                if (!server || !uri)
                    return { content: [{ type: "text", text: "Error: `server` and `uri` are required." }], details: undefined, terminate: false };
                const live = listable();
                const rs = live.find((r) => r.server === server);
                if (!rs)
                    return { content: [{ type: "text", text: `Error: no MCP server ${inlineUntrusted(server)} with listable resources. Available: ${serverNames(live)}.` }], details: undefined, terminate: false };
                const what = `The directory listing of ${inlineUntrusted(uri)}`;
                if (rs.health.dead)
                    throwDeadServer(server, what);
                const timeoutMs = mcpToolTimeoutMs();
                const idleMs = mcpIdleTimeoutMs(rs.transportKind);
                const watchdog = armMcpIdleWatchdog(rs.health, idleMs, signal);
                const site = requestSite(rs.client);
                try {
                    const ext = rs.client.getServerCapabilities()?.extensions?.[MCP_SKILLS_EXTENSION];
                    if (ext?.directoryRead === true) {
                        const r = await readDirViaExtension(rs, uri, signal, timeoutMs, watchdog).catch((err) => rethrowHonestMcpError(err, { server, declared: rs.declared, what, timeoutMs, writeEffect: false, signal, attributeServer: true, site, idle: { signal: watchdog.idleSignal, idleMs }, liveness: rs.health, connection: rs.client }));
                        const serverSaid = (detail) => `\nThe server's error text follows as external/untrusted data:\n${delimitUntrusted(`${server} error`, truncateMcpErrorText(detail))}`;
                        if (r.kind === "not_found") {
                            return {
                                content: [
                                    {
                                        type: "text",
                                        text: `Resource not found: ${inlineUntrusted(uri)} — the server reports no such resource, so re-reading it will not help either. Use ${LIST_MCP_RESOURCES} to see what this server exposes.${serverSaid(r.detail)}`,
                                    },
                                ],
                                details: { resources: [], notFound: true },
                                terminate: false,
                            };
                        }
                        if (r.kind === "not_directory") {
                            return {
                                content: [{ type: "text", text: `Not a directory resource: ${inlineUntrusted(uri)}. If it is a file resource, use ${READ_MCP_RESOURCE} instead.${serverSaid(r.detail)}` }],
                                details: { resources: [] },
                                terminate: false,
                            };
                        }
                        if (r.kind === "ok")
                            return renderDirChildren(server, uri, r.resources, { truncated: r.truncated, incomplete: r.incomplete === undefined ? undefined : { error: r.incomplete, declared: rs.declared }, cursorInvalid: r.cursorInvalid });
                        watchdog.rearm();
                    }
                    const walk = await readMcpListing(rs, "resources", watchdog, idleMs, signal, READ_DEPS, (err, remainingMs) => rethrowHonestMcpError(err, { server, declared: rs.declared, what, timeoutMs: remainingMs, writeEffect: false, signal, attributeServer: true, site, idle: { signal: watchdog.idleSignal, idleMs }, liveness: rs.health, connection: rs.client }));
                    const dirPrefix = uri.endsWith("/") ? uri : `${uri}/`;
                    const children = walk.entries.filter((r) => r.uri !== uri && r.uri.startsWith(dirPrefix));
                    return renderDirChildren(server, uri, children, walk.incomplete ? { listing: walk.incomplete } : undefined);
                }
                catch (err) {
                    if (err instanceof ProtocolRevokedRefusal)
                        return revokedCallResult(err, what);
                    throw err;
                }
                finally {
                    watchdog.dispose();
                }
            },
        });
        axes.push({ name: READ_MCP_RESOURCE_DIR, effect: "read" });
    }
    for (const t of tools)
        withContentOrigin(t, "external");
    return { tools, axes };
}
const OUTPUT_SCHEMA_VALIDATORS = new WeakMap();
function outputSchemaValidatorOf(client) {
    const validator = OUTPUT_SCHEMA_VALIDATORS.get(client);
    if (validator === undefined)
        throw new Error("internal: an MCP client this module did not dial has no recorded schema validator");
    return validator;
}
function toolDefinitionOf(t, validator) {
    const tool = { ...t, inputSchema: t.inputSchema };
    if (!t.outputSchema)
        return { tool };
    try {
        validator.getValidator(t.outputSchema);
        return { tool };
    }
    catch {
        return { tool, outputSchemaUncompilable: true };
    }
}
const LENIENT_LIST_TOOLS_RESULT_SCHEMA = {
    "~standard": { version: 1, vendor: "@sema-agent/core", validate: parseLenientToolsPage },
};
function parseLenientToolsPage(data) {
    if (typeof data !== "object" || data === null)
        return { issues: [{ message: "tools/list result is not an object" }] };
    const rawTools = data.tools;
    if (!Array.isArray(rawTools))
        return { issues: [{ message: "tools/list result.tools is not an array" }] };
    const tools = [];
    for (const raw of rawTools) {
        if (typeof raw !== "object" || raw === null || typeof raw.name !== "string") {
            return { issues: [{ message: "a tools/list entry is missing a string name" }] };
        }
        const t = raw;
        tools.push({
            name: t.name,
            ...(typeof t.description === "string" ? { description: t.description } : {}),
            inputSchema: t.inputSchema,
            ...(t.annotations !== undefined ? { annotations: t.annotations } : {}),
            ...(t._meta !== undefined ? { _meta: t._meta } : {}),
            ...(t.outputSchema !== undefined ? { outputSchema: t.outputSchema } : {}),
            ...(t.execution !== undefined ? { execution: t.execution } : {}),
        });
    }
    const nextCursor = data.nextCursor;
    const cursorInvalid = nextCursor !== undefined && nextCursor !== null && typeof nextCursor !== "string";
    return { value: { tools, ...(typeof nextCursor === "string" ? { nextCursor } : {}), ...(cursorInvalid ? { cursorInvalid: true } : {}) } };
}
async function listToolsLenient(client, through, options, declared) {
    if (!client.getServerCapabilities()?.tools)
        return { tools: [], toolsCapabilityAbsent: true };
    const walk = await walkMcpListPages(async (cursor, remainingMs) => {
        const params = cursor === undefined ? {} : { cursor };
        const page = await through(() => client.request({ method: "tools/list", params }, LENIENT_LIST_TOOLS_RESULT_SCHEMA, { ...options, timeout: remainingMs }));
        return {
            items: page.tools,
            ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
            ...(page.cursorInvalid === true ? { cursorInvalid: true } : {}),
        };
    }, {
        budgetMs: options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC,
        fingerprintOf: listEntryFingerprint,
        declared,
        ...(options?.signal !== undefined ? { signal: options.signal } : {}),
    });
    return { tools: walk.items, ...(walk.incomplete !== undefined ? { incomplete: walk.incomplete } : {}) };
}
function fingerprintRefusal(spec) {
    const fp = spec.fingerprint;
    if (fp === undefined || (typeof fp === "string" && fp.length > 0 && fp.length <= 128))
        return undefined;
    return Object.assign(new Error(`MCP server "${inlineUntrusted(spec.name, 160)}": fingerprint must be a non-empty string of at most 128 characters (got ${typeof fp === "string" ? `${fp.length} characters` : typeof fp}) — not dialed`), { code: "config.mcp_fingerprint_invalid" });
}
async function connectServer(spec, principal, onElicit, binarySeat, reminderDisclosure, through, transportKind, pool, dialOpts, seat, onSubtreeActivity) {
    const elicitOn = spec.elicitation === true && onElicit !== undefined;
    const health = { dead: false, pendingElicitations: 0, lastElicitationClosedAt: 0 };
    const announce = {};
    const startupMs = dialOpts.startupMs;
    const startupOpts = { timeout: startupMs };
    const answersOneLeg = elicitOn || transportKind === "host";
    const poolKey = pool !== undefined && !answersOneLeg ? dialOpts.key : undefined;
    const dialClient = async (stop = dialOpts?.signal) => {
        stop?.throwIfAborted();
        const outputSchemaValidator = new AjvJsonSchemaValidator();
        const client = new Client({ name: "sema-agent-core", version: engineVersion() }, {
            capabilities: elicitOn ? { elicitation: { form: {} } } : {},
            jsonSchemaValidator: outputSchemaValidator,
        });
        OUTPUT_SCHEMA_VALIDATORS.set(client, outputSchemaValidator);
        if (elicitOn) {
            client.setRequestHandler("elicitation/create", async (request, ctx) => {
                health.pendingElicitations++;
                try {
                    const p = request.params;
                    const req = {
                        server: spec.name,
                        message: typeof p.message === "string" ? p.message : "",
                        ...(p.requestedSchema !== undefined ? { requestedSchema: p.requestedSchema } : {}),
                        ...(principal !== undefined ? { principal } : {}),
                    };
                    const answer = await onElicit(req, ctx.mcpReq.signal);
                    return answer.action === "accept" ? { action: "accept", content: answer.content ?? {} } : { action: answer.action };
                }
                finally {
                    health.pendingElicitations--;
                    health.lastElicitationClosedAt = Date.now();
                }
            });
        }
        const pieces = transportKind === "stdio" ? await dialOpts.carrier.next(stop) : undefined;
        const pipe = transportKind === "host" ? await openHostPipe(dialOpts.hostSeat, spec.name, stop) : undefined;
        if (transportKind === "stdio" || transportKind === "host") {
            try {
                askCarriedRevocation();
            }
            catch (refused) {
                await pipe?.close().catch(() => undefined);
                throw refused;
            }
        }
        const { transport, stderr, readBound } = buildTransport(spec, principal, transportKind, dialOpts.carrier, pieces, pipe, dialOpts.onNotice, dialOpts.plaintextOrigins);
        if (readBound !== undefined)
            watchReadBound(client, transport, readBound);
        const hangUp = () => void client.close().catch(() => undefined);
        stop?.addEventListener("abort", hangUp, { once: true });
        try {
            await settledBefore(client.connect(transport, startupOpts), pipe !== undefined ? stop : undefined);
        }
        catch (err) {
            await client.close().catch(() => undefined);
            await stderr?.settle(stop?.aborted === true ? "stopped" : "failed");
            if (typeof err === "object" && err !== null)
                recordCarrier(err, dialOpts.carrier);
            throw stop?.aborted === true ? stop.reason : err;
        }
        finally {
            stop?.removeEventListener("abort", hangUp);
        }
        await stderr?.settle("connected");
        recordCarrier(client, dialOpts.carrier);
        if (poolKey !== undefined)
            recordEngineDial(client, poolKey);
        return client;
    };
    const mount = transportKind === "host" ? hostMount(startupMs, dialOpts.signal) : undefined;
    const mountStop = mount?.signal ?? dialOpts?.signal;
    const lease = pool !== undefined && poolKey !== undefined ? await pool.acquire(poolKey, dialClient, dialOpts) : undefined;
    const client = lease !== undefined ? lease.client : await dialClient(mountStop).catch((err) => {
        mount?.end();
        throw err;
    });
    const close = () => (lease !== undefined ? lease.release() : client.close());
    try {
        const onClosed = () => {
            health.dead = true;
            announce.fn?.();
        };
        if (lease !== undefined)
            lease.onClose(onClosed);
        else
            client.onclose = onClosed;
        const listing = lease?.listing ?? new ConnectionListing();
        const at = listing.open();
        const declared = (carrierOf(client) ?? dialOpts.carrier).sent;
        const echo = carrierEcho(carrierOf(client) ?? dialOpts.carrier, dialOpts.announceEcho);
        const listed = await underStartupBound(startupMs, mountStop, (options) => listToolsLenient(client, through, options, declared)).finally(() => mount?.end());
        const answered = listing.answer(at, listed.tools, listed.incomplete !== undefined, dialOpts.carried);
        const { serverTools, serverAxes, gates, definitions, dropped, advisories } = intakeListedTools({ tools: [...answered.view], unproven: answered.unproven }, spec, dialOpts.link, declared, outputSchemaValidatorOf(client), binarySeat, reminderDisclosure, through, transportKind, seat, echo, onSubtreeActivity);
        const caps = client.getServerCapabilities();
        const resourceInfo = caps?.resources ? { listAllowed: faceAllowed(spec.allowTools, MCP_RESOURCE_LIST_ALLOW), readAllowed: faceAllowed(spec.allowTools, MCP_RESOURCE_READ_ALLOW) } : undefined;
        const route = { server: spec.name, client, through, health, transportKind: idleKindOf(transportKind), declared, meta: () => mcpCallMeta(undefined, undefined, spec.sessionMetaKey, seat?.sessionId, spec.callerMeta === true ? seat?.caller : undefined), echo };
        const rawInstructions = erasedEcho(client.getInstructions(), echo, "instructions");
        const sanitized = rawInstructions && rawInstructions.trim() ? sanitizeUntrustedText(rawInstructions.trim()) : undefined;
        const disposed = sanitized === undefined ? undefined : await disposeSectionEntry(dialOpts?.sections, { section: "core/discovery.mcp-instructions", server: spec.name, text: sanitized, mountedTools: serverTools.map((t) => t.name) });
        const instructions = disposed?.kept === undefined ? undefined : { server: spec.name, ...disposed.kept };
        const info = serverInfoOf(client.getServerVersion(), echo);
        const status = {
            name: spec.name,
            status: "connected",
            ...(info ? { serverInfo: info } : {}),
            toolNames: serverTools.map((t) => t.name),
            liveness: livenessOf("completed", Date.now()),
        };
        if (listed.incomplete === undefined && listed.toolsCapabilityAbsent !== true)
            recordListedNames(status, listed.tools.map((t) => t.name));
        return {
            status,
            client,
            close,
            health,
            announce,
            tools: serverTools,
            axes: serverAxes,
            listing,
            intakeAt: { at, gates, definitions },
            dropped,
            schemaAdvisories: advisories,
            ...(listed.toolsCapabilityAbsent === true ? { toolsCapabilityAbsent: true } : {}),
            ...(instructions ? { instructions } : {}),
            ...(disposed?.defect !== undefined ? { instructionsDefect: disposed.defect } : {}),
            ...(listed.incomplete !== undefined ? { listingIncomplete: listed.incomplete } : {}),
            route,
            ...(resourceInfo && (resourceInfo.listAllowed || resourceInfo.readAllowed) ? { resourceServer: { ...route, ...resourceInfo } } : {}),
        };
    }
    catch (err) {
        await close().catch(() => undefined);
        if (typeof err === "object" && err !== null)
            recordCarrier(err, carrierOf(client) ?? dialOpts.carrier);
        throw err;
    }
}
function intakeListedTools(listed, spec, link, declared, validator, binarySeat, reminderDisclosure, through = OPEN_DOOR, transportKind, seat, echo = NO_CREDENTIAL_ECHO, onSubtreeActivity) {
    const declaredContentOrigin = spec.contentOrigin;
    const registration = peerRegistrationDigestOf("mcp", mcpPeerRegistration(spec, transportKind));
    const serverTools = [];
    const serverAxes = [];
    const gates = new Map();
    const dropped = [];
    const definitions = new Map();
    const advisories = [];
    const claimToolName = createToolNameClaims(MCP_NAMESPACE, spec.name);
    for (const t of listed.tools) {
        if (spec.allowTools && !spec.allowTools.includes(t.name)) {
            continue;
        }
        if (isMcpFaceWord(t.name)) {
            dropped.push({ tool: inlineUntrusted(t.name), reason: MCP_FACE_WORD_DROP_REASON });
            continue;
        }
        const echoDrop = echoedToolDrop(t.name, t.inputSchema, echo, declared);
        if (echoDrop !== undefined) {
            dropped.push(echoDrop);
            continue;
        }
        let modelFacingSchema;
        let sanitizedDescription;
        try {
            modelFacingSchema = sanitizeMcpModelFacingValue(t.inputSchema);
            sanitizedDescription = t.description !== undefined ? sanitizeMcpModelFacingText(erasedEcho(t.description, echo, "tool_listing")) : undefined;
        }
        catch (err) {
            const reason = err instanceof McpPayloadKeyCollision
                ? `two of its advertised names neutralize to the same model-facing spelling ${inlineUntrusted(JSON.stringify(err.message), 80)}; one parameter would have vanished from the schema the model is given while the server still expects it`
                : "advertised tool payload could not be neutralized for model-facing display (pathological nesting)";
            dropped.push({ tool: inlineUntrusted(t.name), reason: inlineUntrusted(reason, 240) });
            continue;
        }
        const normalized = normalizeMcpToolSchema(modelFacingSchema);
        let effectiveInputSchema = modelFacingSchema;
        let effectiveDescription = sanitizedDescription !== undefined ? sanitizeUntrustedText(sanitizedDescription) : undefined;
        if (normalized.outcome === "drop") {
            dropped.push({ tool: inlineUntrusted(t.name), reason: inlineUntrusted(normalized.reason, 240) });
            continue;
        }
        if (normalized.outcome === "normalized") {
            effectiveInputSchema = normalized.schema;
            effectiveDescription = normalized.note + (effectiveDescription ? `\n\n${effectiveDescription}` : "");
        }
        const schemaProblem = mcpToolSchemaProblem(effectiveInputSchema) ?? schemaKeyBoundProblem(effectiveInputSchema);
        if (schemaProblem !== undefined) {
            dropped.push({ tool: inlineUntrusted(t.name), reason: inlineUntrusted(schemaProblem, 240) });
            continue;
        }
        const schemaAdvisory = mcpToolSchemaAdvisory(effectiveInputSchema);
        if (schemaAdvisory !== undefined) {
            advisories.push({ tool: inlineUntrusted(t.name), reason: inlineUntrusted(schemaAdvisory, 240) });
        }
        const remoteName = t.name;
        const taskRequired = t.execution !== null && typeof t.execution === "object" && t.execution.taskSupport === "required";
        const wireName = mintNamespacedToolName(MCP_NAMESPACE, spec.name, remoteName);
        const rowNameProblem = rosterMemberBoundProblem({ name: wireName, remoteName: rosterRemoteNameOf(wireName, remoteName) });
        if (rowNameProblem !== undefined) {
            dropped.push({ tool: inlineUntrusted(t.name.replace(MCP_INVISIBLE_TEXT_RE, "")), reason: inlineUntrusted(rowNameProblem.message, 240) });
            continue;
        }
        const { minted: namespacedName, heldBy: mintedBy } = claimToolName(remoteName);
        if (mintedBy !== undefined) {
            dropped.push({ tool: inlineUntrusted(t.name), reason: mcpToolDropReason(namespacedName, mintedBy, t.name) });
            continue;
        }
        const hintAxis = mcpAxisFor(namespacedName, t.annotations);
        const axis = applyCallerAxisOverride(namespacedName, hintAxis, spec.toolAxes?.[remoteName]);
        if (axis)
            serverAxes.push(axis);
        const writeEffect = (axis?.effect ?? "write") === "write";
        const mcpToolMeta = t._meta;
        const mcpMaxResultSizeChars = resolveMcpDeclaredResultSize(mcpToolMeta);
        const interaction = resolveMcpRequiresUserInteraction(mcpToolMeta);
        if (interaction.advisory !== undefined)
            advisories.push({ tool: inlineUntrusted(t.name), reason: interaction.advisory });
        const mcpAlwaysLoad = mcpToolMeta?.["anthropic/alwaysLoad"] === true;
        const gateFace = { ...(interaction.declared ? { mcpRequiresUserInteraction: true } : {}), ...(t.annotations?.readOnlyHint === true ? { mcpReadOnlyHint: true } : {}) };
        const gate = mcpToolGate(remoteName, axis, gateFace, taskRequired);
        gates.set(namespacedName, listed.unproven?.has(remoteName) === true ? UNPROVEN_GATE : gate);
        const mounted = {
            name: namespacedName,
            description: capMcpToolDescription(effectiveDescription ?? `MCP tool ${inlineUntrusted(sanitizeMcpModelFacingText(remoteName))} from ${spec.name}`),
            label: `${spec.name}:${remoteName}`,
            parameters: (effectiveInputSchema ?? { type: "object" }),
            ...(mcpMaxResultSizeChars !== undefined ? { mcpMaxResultSizeChars } : {}),
            ...(mcpAlwaysLoad ? { mcpAlwaysLoad: true } : {}),
            ...gateFace,
            mcpRemoteName: remoteName, ...boundaryFlowFace(spec.toolAxes?.[remoteName]), permissionSeat: "passthrough", peerRegistration: () => registration,
            execute: async (toolCallId, params, signal) => {
                const what = `The call to tool ${foreignLine(remoteName, undefined, { declared })}`;
                if (taskRequired) {
                    return {
                        content: [{ type: "text", text: `The call was refused: this tool requires task-based execution (MCP tasks), which this client does not drive. The call was NOT sent, so the server did not execute it. ${refusalScope("declaration", "mcp")}` }],
                        details: { error: "mcp.task_required", code: "mcp.task_required", delivered: "no", server: spec.name },
                        terminate: false,
                        isError: true,
                    };
                }
                const timeoutMs = mcpToolTimeoutMs();
                const idleMs = mcpIdleTimeoutMs(idleKindOf(transportKind));
                const callMeta = mcpCallMeta(toolCallId, seat?.of(toolCallId), spec.sessionMetaKey, seat?.sessionId, spec.callerMeta === true ? seat?.caller : undefined);
                let answeredWith = declared;
                const attempt = async (conn, resent, last) => {
                    const definition = conn.definitions().get(namespacedName);
                    const site = requestSite(conn.client);
                    const watchdog = armMcpIdleWatchdog(conn.health, idleMs, signal);
                    try {
                        const callParams = { name: remoteName, arguments: (params ?? {}), ...(callMeta !== undefined ? { _meta: callMeta } : {}) };
                        const res = await through(() => conn.client.callTool(callParams, {
                            toolDefinition: definition.tool,
                            signal: watchdog.combinedSignal,
                            timeout: timeoutMs,
                            resetTimeoutOnProgress: true,
                            onprogress: () => {
                                onSubtreeActivity?.();
                                watchdog.rearm();
                            },
                            maxTotalTimeout: mcpToolTotalTimeoutMs(timeoutMs),
                        }))
                            .catch((err) => {
                            try {
                                return rethrowHonestMcpError(err, {
                                    server: spec.name,
                                    declared: carrierOf(conn.client)?.sent ?? declared,
                                    what,
                                    timeoutMs,
                                    writeEffect,
                                    signal,
                                    site,
                                    ...(resent ? { resent: true } : {}), attempt: last ? "resent" : "first",
                                    idle: { signal: watchdog.idleSignal, idleMs },
                                    liveness: conn.health,
                                    connection: conn.client,
                                    ...(reminderDisclosure !== undefined
                                        ? { reminder: { mark: reminderDisclosure.mark, outlet: "mcp", ...(reminderDisclosure.counts !== undefined ? { counts: reminderDisclosure.counts } : {}) } }
                                        : {}),
                                });
                            }
                            catch (failure) {
                                if (sessionGone(err, site) && signal?.aborted !== true)
                                    return new Resendable(conn, failure);
                                if (!writeEffect && answeredUnauthorized(err) && carrierOf(conn.client)?.renewed === true && signal?.aborted !== true) {
                                    return new Reauthorized(failure, () => { const lost = new PeerAuthorizationRefused("seat_unavailable", {}); return unauthorizedFailure(lost, { what, server: spec.name, writeEffect }, readMcpFailure(lost, site).failure, false); });
                                }
                                throw failure;
                            }
                        });
                        if (res instanceof Resendable || res instanceof Reauthorized)
                            return res;
                        conn.health.observe?.("completed");
                        answeredWith = carrierOf(conn.client)?.sent ?? declared;
                        return res;
                    }
                    finally {
                        watchdog.dispose();
                    }
                };
                const send = (conn, resent) => inFlight(conn.client, () => sentOnceMore((last) => attempt(conn, resent, last), () => reach(link, namespacedName, gate) === conn && signal?.aborted !== true).catch((err) => (owedByAnswer(err, conn.health), Promise.reject(err))));
                const before = link.live();
                if (before !== undefined && carrierOf(before.client)?.expired() === true)
                    await link.recover(before, "expired");
                const res = await callThroughLink(link, namespacedName, gate, signal, send, () => throwDeadServer(spec.name, what)).catch((err) => (err instanceof ProtocolRevokedRefusal ? err : Promise.reject(isCallerAbortReading(err, signal) ? new Error(TOOL_INTERRUPTED_TEXT) : err)));
                if (res instanceof ProtocolRevokedRefusal)
                    return revokedCallResult(res, what);
                if (typeof res === "string")
                    return listingRefusal(res, remoteName, spec.name);
                const { content: mapped, kept, pieces } = await mapContent(res.content, spec.name, toolResultBytesKeeper(binarySeat, toolCallId), binarySeat?.documents?.());
                tellBinaryKept(binarySeat, { server: spec.name, toolName: namespacedName, toolCallId, kept });
                if (res.isError === true) {
                    const parts = [];
                    for (const block of mapped) {
                        if (block.type === "text")
                            parts.push(block.text);
                        else
                            parts.push(`[${block.type} block omitted from error result]`);
                    }
                    const errScLine = structuredContentErrorLine(res.structuredContent, parts.join("\n"));
                    if (errScLine !== undefined)
                        parts.push(errScLine);
                    const body = truncateMcpErrorText(remoteWords(parts.join("\n").trim(), answeredWith));
                    const msg = body
                        ? `MCP tool ${foreignLine(remoteName, undefined, { declared })} reported an error. The server's error content follows as external/untrusted data:\n${delimitUntrusted(`${spec.name} tool error`, body)}`
                        : `MCP tool ${foreignLine(remoteName, undefined, { declared })} reported an error`;
                    if (reminderDisclosure !== undefined) {
                        observeReminderMarkEcho({ text: msg, mark: reminderDisclosure.mark, outlet: "mcp", counts: reminderDisclosure.counts });
                    }
                    throw Object.assign(new Error(msg), { details: { code: "mcp.tool_error", delivered: "yes", server: spec.name } });
                }
                const content = gateMcpOutput(mapped);
                const sc = res.structuredContent;
                if (sc !== undefined) {
                    content.push({
                        type: "text",
                        text: `[structuredContent] JSON with schema: ${inferCompactSchema(sc)}\n${truncateError(JSON.stringify(sc))}`,
                    });
                }
                if (reminderDisclosure !== undefined) {
                    const textIdx = [];
                    const segments = [];
                    content.forEach((b, i) => {
                        if (b.type === "text" && typeof b.text === "string") {
                            textIdx.push(i);
                            segments.push(b.text);
                        }
                    });
                    const d = discloseReminderShaped({
                        segments,
                        mark: reminderDisclosure.mark,
                        outlet: "mcp",
                        defuseExactMark: true,
                        throttle: { key: `${spec.name}:${remoteName}`, windows: reminderDisclosure.windows },
                        ...(reminderDisclosure.counts !== undefined ? { counts: reminderDisclosure.counts } : {}),
                    });
                    if (d.defused)
                        textIdx.forEach((ci, si) => (content[ci] = { type: "text", text: d.segments[si] }));
                    if (d.trailer !== undefined)
                        content.push({ type: "text", text: `${MARKED_BLOCK_AFTER_DATA}${d.trailer}` });
                }
                if (sc !== undefined)
                    return { content, details: { type: "mcp", structuredContent: withKeptPieces(sc, pieces) }, terminate: false };
                return { content, details: withKeptPieces(res, pieces), terminate: false };
            },
        };
        serverTools.push(declaredContentOrigin !== undefined ? withContentOrigin(mounted, declaredContentOrigin) : mounted);
        definitions.set(namespacedName, toolDefinitionOf(t, validator));
    }
    return { serverTools, serverAxes, gates, definitions, dropped, advisories };
}
function asServerWarning(spec, err, declared, memory) {
    const warning = new Error(`mcp: server "${spec.name}" failed to connect — skipped (${namedMcpFailureText(err, declared)})`, { cause: sanitizedCause(err, declared) });
    const owed = authorizationOwed(err);
    warning.code = owed !== undefined && owesAuthorization(owed) ? "mcp.authorization_required" : MCP_SERVER_UNAVAILABLE;
    warning.server = spec.name;
    return attachUnavailableCause((memory !== undefined ? Object.assign(warning, { memory }) : warning), err);
}
function dialDecision(dialable, spec) {
    if (dialable === undefined)
        return true;
    let why;
    let cause;
    try {
        const answer = dialable(spec);
        if (typeof answer === "boolean")
            return answer;
        const thenable = typeof answer?.then === "function";
        if (thenable)
            Promise.resolve(answer).catch(() => undefined);
        const kind = typeof answer;
        why = `it answered ${thenable ? "a promise (the seat is synchronous)" : answer === null || answer === undefined ? String(answer) : `${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind}`}, not a boolean`;
    }
    catch (e) {
        why = thrownText(e);
        cause = { cause: e };
    }
    throw Object.assign(new Error(`MCP materialization refused: the dialable seat could not decide whether to dial server "${inlineUntrusted(spec.name, 120)}" — ${foreignLine(why, 240)}. No server was dialed.`, cause), { code: "config.mcp_dialable_failed" });
}
function sanitizedCause(err, declared) {
    const copy = new Error(namedMcpFailureText(err, declared));
    const name = thrownName(err);
    if (name !== undefined) {
        if (name !== "")
            copy.name = name;
        const code = readMember(err, "code");
        if (typeof code === "string" || typeof code === "number")
            copy.code = code;
    }
    return copy;
}
function schemaAdvisoryWarning(server, tool, reason) {
    const warning = new Error(`mcp: server "${inlineUntrusted(server, 160)}" tool "${tool}" is mounted, but ${reason}.`);
    warning.code = "mcp.tool_schema_advisory";
    return warning;
}
function toolsCapabilityAbsentWarning(server) {
    const warning = new Error(`mcp: server "${inlineUntrusted(server, 160)}" declared no "tools" capability, so no tool listing was requested and none of the tools named in this server's allowTools can be mounted. If the server does serve tools, it must declare the capability at initialize.`);
    warning.code = "mcp.tools_capability_absent";
    return warning;
}