openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
16 lines (13 loc) • 23.3 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{n as isTruthyEnvValue}from"./env-fLMEolk5.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{t as runInDetachedAsyncContext}from"./detached-async-context-DLLuWsxc.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{c as withPluginRuntimeGatewayContextResolver,l as withPluginRuntimeGatewayRequestScope,o as getPluginRuntimeGatewayRequestScope,t as ExpiredPluginRegistryScopeError}from"./gateway-request-scope-7deHmsb_.mjs";import{C as resolveSessionAgentIds}from"./agent-scope-config-CG9CFpGX.mjs";import{h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import{r as isAutomationsToolName}from"./automations-tool-name-CptnbJ9-.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{t as runOutsidePluginRuntimeGenerationScope}from"./generation-scope-CxHnQlew.mjs";import"./io-Di_yuX3t.mjs";import{n as normalizeMessageChannel}from"./message-channel-core-D_hPOadj.mjs";import{t as safeEqualSecret}from"./secret-equal-BtEZdDeQ.mjs";import{c as resolveAttachGrant,l as resolveMcpLoopbackClientGrant,p as revokeMcpLoopbackClientGrantsForRuntime,s as registerMcpLoopbackClientGrantRevocationListener,t as GatewayConnectionWork}from"./server-connection-work-90yhik6H.mjs";import{r as getHeader}from"./http-header-value-D4bOEsPJ.mjs";import{a as isLoopbackAddress}from"./net-Bu4cO5Pq.mjs";import"./message-channel-514k57tV.mjs";import{a as resolveMainSessionKey}from"./main-session-C6FGqx0x.mjs";import{f as withGatewayToolCallerIdentity,r as createAdmittedGatewayToolCallerIdentity}from"./gateway-caller-context-Dw9IijqV.mjs";import{t as acknowledgeInternalToolResult}from"./internal-hooks-Bn77tst6.mjs";import{s as withPreparedSessionCapabilityRead}from"./subagent-session-store-ClkR5Yv6.mjs";import{n as readResolvedSessionEntryInWorker}from"./session-accessor.entry-read-runtime-VVa9LmzA.mjs";import"./session-accessor.entry-B1qUJ4E1.mjs";import{a as isAgentHarnessSessionKey,r as AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE,s as isAgentHarnessSessionStoreEntryProtected}from"./agent-harness-session-key-B6S2Sx8z.mjs";import"./sessions-DQD7zQ95.mjs";import{i as logWarn,t as logDebug}from"./logger-BHIcoxTH.mjs";import{k as withAgentQuestionAnswerAuthority}from"./host-private-capabilities-B_SEzbNU.mjs";import{t as isPluginReloadingError}from"./plugin-replacement-retry-Sq1mdyOt.mjs";import{a as isPreparedModelRuntimePluginLifecycleFailure}from"./prepared-model-runtime-admission-errors-DZto8oll.mjs";import{f as sendHttpRequestRejection,i as isRequestBodyLimitError,l as createHttpRequestAbortSignal,o as readRequestBodyWithLimit}from"./http-body-CsPV_uT5.mjs";import{t as checkBrowserOrigin}from"./origin-check-CngtffS_.mjs";import{a as writeJsonWithoutCharset}from"./http-json-g_k96dZ_.mjs";import{n as runWithTrackedCancellation}from"./async-work-resources-vg9S-hbA.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-mQ0a9qMc.mjs";import{a as jsonRpcResult,i as jsonRpcError}from"./mcp-http.protocol-k9GBgltP.mjs";import crypto from"node:crypto";import{createServer}from"node:http";
//!src/agents/agent-bundle-mcp-instructions.ts
const serverInstructionsByTool=/* @__PURE__ */ new WeakMap;function setBundleMcpToolServerInstructions(e,t,n){if(n)serverInstructionsByTool.set(e,{serverName:t,instructions:n})}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(`
`):void 0}
//!src/gateway/mcp-http.grant-generation.ts
const retiredGrantScopes=/* @__PURE__ */ new WeakSet;function runInMcpGrantRequestScope(e,t){return withPluginRuntimeGatewayRequestScope(e,retiredGrantScopes.has(e)?()=>runOutsidePluginRuntimeGenerationScope(t):t)}async function resolveInMcpGrantRequestScope(e,t,n){try{return await runInMcpGrantRequestScope(e,t)}catch(r){if(retiredGrantScopes.has(e)||!(isPreparedModelRuntimePluginLifecycleFailure(r)||r instanceof ExpiredPluginRegistryScopeError))throw r;n.throwIfAborted();if(isPluginReloadingError(r)){await r.replacement;n.throwIfAborted()}retiredGrantScopes.add(e);return await runInMcpGrantRequestScope(e,t)}}
//!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(`:
`);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}}
//!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]}async function startMcpLoopbackServer(e){const[{handleMcpJsonRpc:t},{McpLoopbackToolCache:n},{assertCompletionGrantLineage:r,createCompletionGrantLineageAdmission:i}]=await Promise.all([import(`./mcp-http.handlers-C7hXbFkq.mjs`),import(`./mcp-http.runtime-Dpeg-la9.mjs`),import(`./tool-resolution-completion-R_XsTxMe.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`,`:
`);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?resolveInMcpGrantRequestScope(g.requestScope,constructAsCaller,f.signal):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`,`
`);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}if(r.method===`tools/call`&&v.toolCallsRefused){if(shouldSendJsonRpcResponse(r))b.push(jsonRpcResult(readJsonRpcRequestId(r),{content:[{type:`text`,text:`Tools are not callable during compaction.`}],isError:true}));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,...v.requester?{requester:v.requester}:{},...v.trigger?{trigger:v.trigger}:{},approvalReviewerDeviceId:v.approvalReviewerDeviceId,channelId:v.currentChannelId,turnSourceChannel:v.messageProvider,turnSourceTo:v.currentChannelId,turnSourceAccountId:v.accountId,turnSourceThreadId:v.currentThreadTs},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?runInMcpGrantRequestScope(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}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}async function closeMcpLoopbackServer(){if(activeMcpLoopbackServerPromise)await activeMcpLoopbackServerPromise;const e=closeActiveMcpLoopbackServer;closeActiveMcpLoopbackServer=void 0;await e?.()}export{ensureMcpLoopbackServer as n,setBundleMcpToolServerInstructions as r,closeMcpLoopbackServer as t};