openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
681 lines (680 loc) • 27 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { c as withPluginRuntimeGatewayContextResolver, l as withPluginRuntimeGatewayRequestScope, o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs";
import { C as resolveSessionAgentIds } from "./agent-scope-config-DmXgFGKP.mjs";
import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import "./io-4QsrsWTJ.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import { t as safeEqualSecret } from "./secret-equal-BogABOFr.mjs";
import { c as resolveAttachGrant, l as resolveMcpLoopbackClientGrant, p as revokeMcpLoopbackClientGrantsForRuntime, s as registerMcpLoopbackClientGrantRevocationListener, t as GatewayConnectionWork } from "./server-connection-work-BcD-l4Tl.mjs";
import { r as getHeader } from "./http-header-value-BTQlMYRm.mjs";
import { a as isLoopbackAddress } from "./net-BgRayX-P.mjs";
import "./message-channel-DTYVLJT1.mjs";
import { r as isAutomationsToolName } from "./automations-tool-name-DNRDs0aJ.mjs";
import { f as withGatewayToolCallerIdentity, r as createAdmittedGatewayToolCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs";
import { n as acknowledgeInternalToolResult } from "./internal-hooks-Ch3rqxs-.mjs";
import { a as resolveMainSessionKey } from "./main-session-BNL3-mRV.mjs";
import { s as withPreparedSessionCapabilityRead } from "./subagent-session-store--G7wm9iV.mjs";
import { n as readResolvedSessionEntryInWorker } from "./session-accessor.entry-read-runtime-y5p3nnUX.mjs";
import "./session-accessor.entry-f0bkn7cv.mjs";
import { a as isAgentHarnessSessionKey, r as AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE, s as isAgentHarnessSessionStoreEntryProtected } from "./agent-harness-session-key-BRYGtzM6.mjs";
import "./sessions-D5Vvu3AE.mjs";
import { t as checkBrowserOrigin } from "./origin-check-C_9X1y_u.mjs";
import { i as logWarn, t as logDebug } from "./logger-CIwfuhOU.mjs";
import { T as withAgentQuestionAnswerAuthority } from "./host-private-capabilities-DDumj0c_.mjs";
import { f as sendHttpRequestRejection, i as isRequestBodyLimitError, l as createHttpRequestAbortSignal, o as readRequestBodyWithLimit } from "./http-body-B9w7rzPz.mjs";
import { a as writeJsonWithoutCharset } from "./http-json-ddGJz5CA.mjs";
import { n as runWithTrackedCancellation } from "./async-work-resources-BF09U4aO.mjs";
import { t as resolveToolLoopDetectionConfig } from "./tool-loop-detection-config-Dzb0KwUj.mjs";
import { c as markMcpLoopbackRequestFinished, d as markMcpLoopbackToolCallStarted, f as recordMcpLoopbackToolCallResult, h as updateMcpLoopbackToolCallCapture, l as markMcpLoopbackRequestStarted, m as setActiveMcpLoopbackRuntime, n as clearActiveMcpLoopbackRuntimeByOwnerToken, o as getActiveMcpLoopbackRuntime, p as resolveMcpLoopbackYieldContext, s as markMcpLoopbackRequestClassified, u as markMcpLoopbackToolCallFinished } from "./mcp-http.loopback-runtime-CcKKo9xU.mjs";
import { i as jsonRpcError } from "./mcp-http.protocol-CkxPXDT7.mjs";
import crypto from "node:crypto";
import { createServer } from "node:http";
//#region src/agents/agent-bundle-mcp-instructions.ts
const serverInstructionsByTool = /* @__PURE__ */ new WeakMap();
/** Records the upstream server guidance that accompanies a bridged MCP tool. */
function setBundleMcpToolServerInstructions(e, t, n) {
if (n) serverInstructionsByTool.set(e, {
serverName: t,
instructions: n
});
}
/**
* Server instructions for the loopback initialize reply. A server contributes
* only while one of its tools is listed, so a fully denied server adds nothing;
* servers are ordered by name so the reply, and Claude's prompt, stay stable.
*/
function resolveBundleMcpServerInstructions(e, t) {
const n = /* @__PURE__ */ new Map();
for (const r of e ?? []) {
const e = serverInstructionsByTool.get(r);
if (e && t.has(r.name)) n.set(e.serverName, e.instructions);
}
const r = [...n.keys()].toSorted().map((e) => `## ${e}\n${n.get(e)}`);
return r.length > 0 ? r.join("\n\n") : void 0;
}
//#endregion
//#region src/gateway/mcp-http.request.ts
const DEFAULT_MCP_BODY_TIMEOUT_MS = 3e4;
function readPositiveIntEnv(e, t) {
const n = process.env[e]?.trim();
if (!n) return t;
const r = Number(n);
if (!/^\d+$/u.test(n) || !Number.isSafeInteger(r) || r <= 0) throw new Error(`${e} must be a positive integer. Got: ${JSON.stringify(n)}`);
return r;
}
function logMcpLoopbackTraffic(e, t) {
if (!isTruthyEnvValue(process.env.OPENCLAW_CLI_BACKEND_LOG_OUTPUT) && !isTruthyEnvValue(process.env.OPENCLAW_LIVE_CLI_BACKEND_DEBUG)) return;
console.error(`[mcp-loopback] ${e} ${JSON.stringify(t)}`);
}
function resolveScopedSessionKey(e, t) {
const n = normalizeOptionalString(t);
return !n || n === "main" ? resolveMainSessionKey(e) : n;
}
function normalizeMcpInboundEventKind(e) {
const t = normalizeOptionalString(e);
return t === "room_event" || t === "user_request" ? t : void 0;
}
function normalizeMcpSourceReplyDeliveryMode(e) {
const t = normalizeOptionalString(e);
return t === "automatic" || t === "message_tool_only" ? t : void 0;
}
function normalizeMcpTaskSuggestionDeliveryMode(e) {
return normalizeOptionalString(e) === "gateway" ? "gateway" : void 0;
}
function normalizeMcpBooleanHeader(e) {
const t = normalizeOptionalString(e);
return t ? isTruthyEnvValue(t) : void 0;
}
function rejectsBrowserLoopbackRequest(e) {
const t = getHeader(e, "origin");
if (!t) return false;
return !checkBrowserOrigin({
requestHost: getHeader(e, "host"),
origin: t,
isLocalClient: isLoopbackAddress(e.socket?.remoteAddress)
}).ok;
}
function resolveMcpSender(e) {
const t = getHeader(e.req, "authorization") ?? "";
const n = safeEqualSecret(t, `Bearer ${e.ownerToken}`);
const r = safeEqualSecret(t, `Bearer ${e.nonOwnerToken}`);
if (n || r) return { senderIsOwner: n };
const i = t.startsWith("Bearer ") ? t.slice(7) : "";
const a = normalizeOptionalString(getHeader(e.req, "x-openclaw-cli-capture-key"));
const o = i && a ? resolveMcpLoopbackClientGrant({
token: i,
runtimeOwnerToken: e.ownerToken,
captureKey: a
}) : void 0;
if (o) return {
senderIsOwner: o.context.senderIsOwner,
boundClientGrant: o,
boundGrantToken: i
};
const s = i ? resolveAttachGrant(i) : void 0;
if (s) return {
senderIsOwner: false,
boundSessionKey: s.sessionKey,
...s.agentId ? { boundAgentId: s.agentId } : {}
};
}
function validateMcpLoopbackRequest(e) {
const reply = (t, n) => {
writeJsonWithoutCharset(e.res, t, n);
return null;
};
const t = URL.parse(e.req.url ?? "/", `http://${e.req.headers.host ?? "localhost"}`);
if (!t) {
logMcpLoopbackTraffic("reject", {
reason: "bad_request_url",
method: e.req.method ?? ""
});
return reply(400, { error: "bad_request" });
}
if (e.req.method === "GET" && t.pathname.startsWith("/.well-known/")) {
e.res.writeHead(404);
e.res.end();
return null;
}
if (t.pathname !== "/mcp") {
logMcpLoopbackTraffic("reject", {
reason: "not_found",
method: e.req.method ?? "",
path: t.pathname
});
return reply(404, { error: "not_found" });
}
if (e.req.method !== "GET" && e.req.method !== "DELETE" && e.req.method !== "POST") {
logMcpLoopbackTraffic("reject", {
reason: "method_not_allowed",
method: e.req.method ?? "",
path: t.pathname
});
e.res.writeHead(405, { Allow: "GET, POST, DELETE" });
e.res.end();
return null;
}
if (rejectsBrowserLoopbackRequest(e.req)) {
if (e.req.method === "POST") logMcpLoopbackTraffic("reject", {
reason: "forbidden_origin",
method: e.req.method,
origin: getHeader(e.req, "origin") ?? ""
});
return reply(403, { error: "forbidden" });
}
const n = resolveMcpSender(e);
if (!n) {
if (e.req.method === "POST") logMcpLoopbackTraffic("reject", {
reason: "unauthorized",
method: e.req.method,
hasAuthorization: (getHeader(e.req, "authorization") ?? "").length > 0
});
return reply(401, { error: "unauthorized" });
}
if (e.req.method === "GET") {
logMcpLoopbackTraffic("sse-open", {
method: "GET",
path: t.pathname
});
e.res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache"
});
e.res.flushHeaders();
e.res.write(":\n\n");
e.onSseResponse?.(e.res);
e.req.on("close", () => {
if (!e.res.writableEnded) e.res.end();
});
return null;
}
if (e.req.method === "DELETE") {
logMcpLoopbackTraffic("session-delete", {
method: "DELETE",
path: t.pathname
});
return reply(200, { ok: true });
}
const r = getHeader(e.req, "content-type") ?? "";
if (r.slice(0, 16).toLowerCase() !== "application/json") {
logMcpLoopbackTraffic("reject", {
reason: "unsupported_media_type",
method: e.req.method ?? "",
contentType: r
});
return reply(415, { error: "unsupported_media_type" });
}
return n;
}
function resolveMcpHttpBodyTimeoutMs() {
return readPositiveIntEnv("OPENCLAW_MCP_LOOPBACK_BODY_TIMEOUT_MS", DEFAULT_MCP_BODY_TIMEOUT_MS);
}
function resolveMcpCliCaptureKey(e, t) {
if (t.boundClientGrant || t.boundSessionKey) return t.boundClientGrant?.captureKey;
return normalizeOptionalString(getHeader(e, "x-openclaw-cli-capture-key"));
}
function normalizeMcpClientCapsHeader(e) {
const t = [...new Set((e ?? "").split(",").map((e) => e.trim()))].filter(Boolean);
return t.length > 0 ? t : void 0;
}
function resolveMcpRequestContext(e, t, n) {
if (n.boundClientGrant) return {
...structuredClone(n.boundClientGrant.context),
currentConversationOrigin: "run-bound-grant"
};
if (n.boundSessionKey) return {
sessionKey: n.boundSessionKey,
agentId: n.boundAgentId,
sessionId: void 0,
messageProvider: void 0,
clientCaps: void 0,
currentChannelId: void 0,
currentThreadTs: void 0,
currentMessageId: void 0,
currentConversationOrigin: "server-session",
currentInboundAudio: void 0,
accountId: void 0,
inboundEventKind: void 0,
sourceReplyDeliveryMode: void 0,
taskSuggestionDeliveryMode: void 0,
requireExplicitMessageTarget: void 0,
senderIsOwner: n.senderIsOwner
};
return {
sessionKey: resolveScopedSessionKey(t, getHeader(e, "x-session-key")),
sessionId: normalizeOptionalString(getHeader(e, "x-openclaw-session-id")),
messageProvider: normalizeMessageChannel(getHeader(e, "x-openclaw-message-channel")) ?? void 0,
clientCaps: normalizeMcpClientCapsHeader(getHeader(e, "x-openclaw-client-caps")),
currentChannelId: normalizeOptionalString(getHeader(e, "x-openclaw-current-channel-id")),
currentThreadTs: normalizeOptionalString(getHeader(e, "x-openclaw-current-thread-ts")),
currentMessageId: normalizeOptionalString(getHeader(e, "x-openclaw-current-message-id")),
currentConversationOrigin: "caller-token",
currentInboundAudio: normalizeMcpBooleanHeader(getHeader(e, "x-openclaw-current-inbound-audio")),
accountId: normalizeOptionalString(getHeader(e, "x-openclaw-account-id")),
inboundEventKind: normalizeMcpInboundEventKind(getHeader(e, "x-openclaw-inbound-event-kind")),
sourceReplyDeliveryMode: normalizeMcpSourceReplyDeliveryMode(getHeader(e, "x-openclaw-source-reply-delivery-mode")),
taskSuggestionDeliveryMode: normalizeMcpTaskSuggestionDeliveryMode(getHeader(e, "x-openclaw-task-suggestion-delivery-mode")),
requireExplicitMessageTarget: normalizeMcpBooleanHeader(getHeader(e, "x-openclaw-require-explicit-message-target")),
senderIsOwner: n.senderIsOwner
};
}
//#endregion
//#region src/gateway/mcp-http.ts
const MAX_MCP_BODY_BYTES = 1048576;
const MCP_HTTP_KEEPALIVE_MS = 15e3;
function keepMcpResponseAlive(e, t, n) {
const r = setInterval(() => {
if (e.destroyed || e.writableEnded || e.writableNeedDrain) return;
if (!e.headersSent) e.writeHead(200, { "Content-Type": t });
e.write(n);
}, MCP_HTTP_KEEPALIVE_MS);
r.unref();
const stop = () => {
clearInterval(r);
e.off("close", stop);
e.off("finish", stop);
};
e.once("close", stop);
e.once("finish", stop);
return stop;
}
let closeActiveMcpLoopbackServer;
let activeMcpLoopbackServerPromise = null;
function parseMcpJsonBody(e) {
try {
return JSON.parse(e);
} catch (e) {
throw Object.assign(/* @__PURE__ */ new Error("MCP JSON parse error"), {
cause: e,
code: "mcp_json_parse_error"
});
}
}
function readJsonRpcRequestId(e) {
if (!isRecord(e)) return null;
const t = e.id;
return typeof t === "string" || typeof t === "number" || t === null ? t : void 0;
}
function isJsonRpcRequest(e) {
return isRecord(e) && e.jsonrpc === "2.0" && typeof e.method === "string";
}
function shouldSendJsonRpcResponse(e) {
return !isJsonRpcRequest(e) || Object.hasOwn(e, "id");
}
function collectJsonRpcResponses(e, t) {
return e.filter(shouldSendJsonRpcResponse).map(t);
}
function jsonRpcInternalError(e) {
const t = Array.isArray(e);
const n = collectJsonRpcResponses(t ? e : [e], (e) => jsonRpcError(readJsonRpcRequestId(e), -32603, "Internal error"));
if (n.length === 0) return null;
return t ? n : n[0];
}
/** Starts a new MCP loopback HTTP server and registers its bearer tokens. */
async function startMcpLoopbackServer(e) {
const [{ handleMcpJsonRpc: t }, { McpLoopbackToolCache: n }, { assertCompletionGrantLineage: r, createCompletionGrantLineageAdmission: i }] = await Promise.all([
import("./mcp-http.handlers-C9nydSTa.mjs"),
import("./mcp-http.runtime.js"),
import("./tool-resolution-completion-BEpf_WHr.mjs")
]);
const a = crypto.randomBytes(32).toString("hex");
const o = crypto.randomBytes(32).toString("hex");
const s = new n();
const c = /* @__PURE__ */ new Set();
const trackSseResponse = (e) => {
c.add(e);
keepMcpResponseAlive(e, "text/event-stream", ":\n\n");
const cleanup = () => {
c.delete(e);
e.off("close", cleanup);
e.off("finish", cleanup);
};
e.once("close", cleanup);
e.once("finish", cleanup);
};
const closeActiveSseResponses = () => {
for (const e of c) if (!e.destroyed && !e.writableEnded) e.end();
};
const l = createServer((n, c) => {
c.setHeader("Connection", "close");
const l = validateMcpLoopbackRequest({
req: n,
res: c,
ownerToken: a,
nonOwnerToken: o,
onSseResponse: trackSseResponse
});
if (!l) return;
const u = resolveMcpCliCaptureKey(n, l);
const d = markMcpLoopbackRequestStarted(u);
const f = createHttpRequestAbortSignal(n, c);
e.track(async () => {
let o;
let u;
let p = [];
try {
o = parseMcpJsonBody(await readRequestBodyWithLimit(n, {
maxBytes: MAX_MCP_BODY_BYTES,
timeoutMs: resolveMcpHttpBodyTimeoutMs(),
destroyOnLimit: false
}));
if (Array.isArray(o) && o.length === 0) {
markMcpLoopbackRequestClassified(d);
writeJsonWithoutCharset(c, 200, jsonRpcError(null, -32600, "Invalid Request"));
return;
}
const m = Array.isArray(o) ? o : [o];
p = m.map((e) => {
if (!d || !isJsonRpcRequest(e) || e.method !== "tools/call") return;
const t = isRecord(e.params) && typeof e.params.name === "string" ? e.params.name : "";
const n = isRecord(e.params) && isRecord(e.params.arguments) ? e.params.arguments : {};
return markMcpLoopbackToolCallStarted({
requestCaptureHandle: d,
toolName: t,
args: n
});
});
markMcpLoopbackRequestClassified(d);
const { boundGrantToken: h, boundClientGrant: g } = l;
if (g && !g.isCurrent()) {
writeJsonWithoutCharset(c, 401, { error: "unauthorized" });
return;
}
const _ = readRuntimeConfig();
const v = resolveMcpRequestContext(n, _, l);
await withPreparedSessionCapabilityRead(() => {
r({
cfg: _,
context: v
});
return handlePreparedRequest();
}, { retain: true });
async function handlePreparedRequest() {
const n = i({
cfg: _,
context: v
});
const isGrantAndLineageCurrent = () => (g?.isCurrent() ?? true) && n.isCurrent();
const authorizeToolCall = () => !e.isClosing && getActiveMcpLoopbackRuntime()?.ownerToken === a && isGrantAndLineageCurrent();
const r = isAgentHarnessSessionKey(v.sessionKey) ? await readResolvedSessionEntryInWorker({
cfg: _,
sessionKey: v.sessionKey
}) : void 0;
if (isAgentHarnessSessionKey(v.sessionKey) && (!r || isAgentHarnessSessionStoreEntryProtected(v.sessionKey, r))) {
const e = collectJsonRpcResponses(m, (e) => jsonRpcError(readJsonRpcRequestId(e), -32600, AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE));
if (e.length === 0) {
c.writeHead(202);
c.end();
return;
}
const t = JSON.stringify(Array.isArray(o) ? e : e[0]);
c.writeHead(200, { "Content-Type": "application/json" });
c.end(t);
return;
}
const l = resolveMcpLoopbackYieldContext(d);
const createCallerIdentity = (e, t) => {
const r = g ? createAdmittedGatewayToolCallerIdentity({
admittedRunContext: g.admittedRunContext,
receiptAuthority: isGrantAndLineageCurrent,
receiptAdmission: n.admission,
cronAuthorityCheck: g.cronAuthorityCheck,
mintCronRequesterGrant: t === "execution" ? g.mintCronRequesterGrant : void 0,
agentId: e,
sessionKey: v.sessionKey,
requesterOrigin: v.requesterOrigin,
turnSourceChannel: v.messageProvider,
turnSourceLocal: !v.messageProvider && v.cronCreatorCallerOrigin?.kind === "local" ? true : void 0,
turnSourceTo: v.currentChannelId,
turnSourceAccountId: v.accountId,
turnSourceThreadId: v.currentThreadTs
}) : void 0;
if (r && g?.personalToolParticipants) r.personalToolParticipants = g.personalToolParticipants;
return r;
};
let y;
try {
const resolveTools = () => withAgentQuestionAnswerAuthority(g?.questionAnswerAuthority, () => s.resolve({
context: v,
admittedRunContext: g?.admittedRunContext,
sessionEventSourcePolicy: g?.sessionEventSourcePolicy,
messageActionTurnCapability: g?.messageActionTurnCapability,
memoryAudience: g?.memoryAudience,
cfg: g?.toolPolicyConfig ?? _,
signal: f.signal,
authProfileStore: g?.toolAuth?.store,
authProfileStoreAgentDir: g?.toolAuth?.agentDir || void 0,
...h ? { grantToken: h } : {},
isGrantCurrent: authorizeToolCall,
yieldContextCacheKey: l?.cacheKey,
onYield: l?.onYield,
...g?.skillLibraryAuthoring ? { skillLibraryAuthoring: g.skillLibraryAuthoring } : {},
...g?.bundledTools ? { bundledTools: g.bundledTools } : {}
}));
const e = g?.withCronManagementToolConstruction;
if (g && e) {
const t = resolveSessionAgentIds({
config: g.toolPolicyConfig,
sessionKey: v.sessionKey,
agentId: v.agentId
}).sessionAgentId;
const constructAsCaller = () => withGatewayToolCallerIdentity(createCallerIdentity(t, "construction"), () => e(resolveTools));
y = await (g.requestScope ? withPluginRuntimeGatewayRequestScope(g.requestScope, constructAsCaller) : constructAsCaller());
} else y = await resolveTools();
} catch (e) {
f.signal.throwIfAborted();
if (g && !g.isCurrent()) {
writeJsonWithoutCharset(c, 401, { error: "unauthorized" });
return;
}
throw e;
}
f.signal.throwIfAborted();
if (g && !g.isCurrent()) {
writeJsonWithoutCharset(c, 401, { error: "unauthorized" });
return;
}
logMcpLoopbackTraffic("request", {
batchSize: m.length,
methods: m.map((e) => isJsonRpcRequest(e) ? e.method : void 0),
sessionKey: v.sessionKey,
inboundEventKind: v.inboundEventKind,
senderIsOwner: v.senderIsOwner,
toolCount: y.toolSchema.length,
cronVisible: y.toolSchema.some((e) => isAutomationsToolName(e.name))
});
if (m.some(shouldSendJsonRpcResponse)) u = keepMcpResponseAlive(c, "application/json", "\n");
const b = [];
const x = resolveBundleMcpServerInstructions(g?.bundledTools, new Set(y.toolSchema.map((e) => e.name)));
for (const [n, r] of m.entries()) {
if (!isJsonRpcRequest(r)) {
b.push(jsonRpcError(readJsonRpcRequestId(r), -32600, "Invalid Request"));
continue;
}
if (r.method === "tools/call" && v.nativeCronCreatorToolAllowlist === null) {
if (shouldSendJsonRpcResponse(r)) b.push(jsonRpcError(readJsonRpcRequestId(r), -32e3, "Native tool authority is not initialized. Retry after native startup, or start a fresh session; no tool action was taken."));
continue;
}
const i = p[n];
let a;
try {
const handleRequest = async (e) => await t({
message: r,
tools: y.tools,
toolSchema: y.toolSchema,
...x ? { serverInstructions: x } : {},
hookContext: {
agentId: y.agentId,
config: _,
...y.workspaceDir ? { workspaceDir: y.workspaceDir } : {},
sessionKey: v.sessionKey,
sessionId: v.sessionId,
runId: v.runId,
approvalReviewerDeviceId: v.approvalReviewerDeviceId,
channelId: v.currentChannelId,
turnSourceChannel: v.messageProvider,
turnSourceTo: v.currentChannelId,
turnSourceAccountId: v.accountId,
turnSourceThreadId: v.currentThreadTs,
loopDetection: resolveToolLoopDetectionConfig({
cfg: _,
agentId: y.agentId
})
},
signal: e,
authorizeToolCall,
onToolCallPrepared: i ? ({ toolName: e, args: t }) => {
updateMcpLoopbackToolCallCapture(i, {
toolName: e,
args: t
});
} : void 0,
onToolCallResult: i ? (e) => {
recordMcpLoopbackToolCallResult({
captureHandle: i,
...e
});
} : void 0
});
const n = createCallerIdentity(y.agentId, "execution");
const o = g?.requestScope;
const handleAsCaller = () => withGatewayToolCallerIdentity(n, () => runWithTrackedCancellation(AbortSignal.any([f.signal, e.signal]), handleRequest));
a = await (o ? withPluginRuntimeGatewayRequestScope(o, handleAsCaller) : handleAsCaller());
} finally {
markMcpLoopbackToolCallFinished(i);
}
if (a !== null && shouldSendJsonRpcResponse(r)) {
const e = r.method === "tools/call" && isRecord(r.params) ? r.params.name : void 0;
const t = isRecord(a) && isRecord(a.result) && a.result.isError === true;
logMcpLoopbackTraffic("response", {
method: r.method,
toolName: typeof e === "string" ? e : void 0,
isError: t
});
b.push(a);
}
}
if (b.length === 0) {
c.writeHead(202);
c.end();
return;
}
const S = JSON.stringify(Array.isArray(o) ? b : b[0]);
if (!c.headersSent) c.writeHead(200, { "Content-Type": "application/json" });
c.end(S, () => {
if (c.writableFinished) b.forEach(acknowledgeInternalToolResult);
});
}
} catch (e) {
const t = isRequestBodyLimitError(e) ? {
PAYLOAD_TOO_LARGE: `Request body exceeds ${MAX_MCP_BODY_BYTES} bytes`,
REQUEST_BODY_TIMEOUT: "Request body timed out",
CONNECTION_CLOSED: "Request body connection closed"
}[e.code] : formatErrorMessage(e);
logWarn(`mcp-loopback: request handling failed: ${t}`);
logMcpLoopbackTraffic("request-failed", { message: t });
if (c.headersSent && !c.destroyed && !c.writableEnded) c.end(JSON.stringify(jsonRpcInternalError(o)));
else if (!c.headersSent) {
if (isRequestBodyLimitError(e, "PAYLOAD_TOO_LARGE") || isRequestBodyLimitError(e, "REQUEST_BODY_TIMEOUT")) {
const t = e.code === "PAYLOAD_TOO_LARGE";
sendHttpRequestRejection(n, c, t ? 413 : 408, JSON.stringify({ error: t ? "payload_too_large" : "request_body_timeout" }), "application/json");
} else if (isRecord(e) && e.code === "mcp_json_parse_error") writeJsonWithoutCharset(c, 400, jsonRpcError(null, -32700, "Parse error"));
else {
const e = jsonRpcInternalError(o);
if (e === null) {
c.writeHead(202);
c.end();
} else writeJsonWithoutCharset(c, 500, e);
}
}
} finally {
u?.();
f.cleanup();
for (const e of p) markMcpLoopbackToolCallFinished(e);
markMcpLoopbackRequestFinished(d);
}
});
});
await new Promise((e, t) => {
l.once("error", t);
l.listen(0, "127.0.0.1", () => {
l.removeListener("error", t);
e();
});
});
const u = l.address();
if (!u || typeof u === "string") throw new Error("mcp loopback did not bind to a TCP port");
const d = registerMcpLoopbackClientGrantRevocationListener((e) => {
if (e.runtimeOwnerToken === a) s.evictGrant(e.token);
});
setActiveMcpLoopbackRuntime({
port: u.port,
ownerToken: a,
nonOwnerToken: o
});
logDebug(`mcp loopback listening on 127.0.0.1:${u.port}`);
let f = false;
const cleanup = () => {
if (f) return;
f = true;
clearActiveMcpLoopbackRuntimeByOwnerToken(a);
revokeMcpLoopbackClientGrantsForRuntime(a);
d();
s.clear();
};
const close = async () => {
cleanup();
e.beginClose();
try {
await new Promise((e, t) => {
l.close((n) => n ? t(n) : e());
closeActiveSseResponses();
});
} finally {
await e.drain();
}
};
const handleUnexpectedClose = () => {
cleanup();
if (closeActiveMcpLoopbackServer === close) {
closeActiveMcpLoopbackServer = void 0;
logWarn("mcp-loopback: listener closed unexpectedly; the next run will restart it");
}
e.drain().catch((e) => {
logWarn(`mcp-loopback: unexpected server close drain failed: ${String(e)}`);
});
};
l.once("close", handleUnexpectedClose);
return close;
}
/** Waits for the process-owned MCP loopback server, starting one if needed. */
async function ensureMcpLoopbackServer() {
if (closeActiveMcpLoopbackServer) return;
if (!activeMcpLoopbackServerPromise) {
const e = new GatewayConnectionWork();
const t = getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext;
activeMcpLoopbackServerPromise = runInDetachedAsyncContext(() => withPluginRuntimeGatewayContextResolver(t, () => e.run(() => startMcpLoopbackServer(e)), { inheritRequestScope: false })).then((e) => {
closeActiveMcpLoopbackServer = e;
}).catch(async (t) => {
await e.drain();
throw t;
}).finally(() => {
activeMcpLoopbackServerPromise = null;
});
}
return activeMcpLoopbackServerPromise;
}
/** Closes the active MCP loopback server if one has been started. */
async function closeMcpLoopbackServer() {
if (activeMcpLoopbackServerPromise) await activeMcpLoopbackServerPromise;
const e = closeActiveMcpLoopbackServer;
closeActiveMcpLoopbackServer = void 0;
await e?.();
}
//#endregion
export { ensureMcpLoopbackServer as n, setBundleMcpToolServerInstructions as r, closeMcpLoopbackServer as t };