openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 17.1 kB
JavaScript
import{i as resolveGlobalMap}from"./global-singleton-DolL9xGt.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{o as racePromiseWithAbortSignal}from"./src-De06gkOi.mjs";import"./abort-signal-BKkRe6pu.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{i as getOrCreatePromise}from"./lazy-promise-CismJCQR.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey,l as resolveAgentIdFromSessionKey}from"./session-key-BPgKfU2m.mjs";import{a as resolveAgentDir,f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{Yt as discriminatedUnion}from"./schemas-DuCQi-Qb.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{f as resolveGatewayOperatorRoleActor}from"./operator-role-policy-g-dxw0h4.mjs";import{t as captureSessionEntryMetadataRead}from"./session-entry-source-authority-DYDyuUDE.mjs";import{i as logWarn}from"./logger-BHIcoxTH.mjs";import{n as runWithSessionMcpRequestSignal,t as getSessionMcpRequestSignal}from"./agent-bundle-mcp-request-context-Cztgq5sC.mjs";import{i as runWithMcpElicitationHandler,r as createMcpClientElicitationHandler}from"./mcp-client-elicitation-gnhPSETv.mjs";import{p as releaseSessionMcpRuntime,u as completeDeferredSessionMcpRuntimeRetirement}from"./mcp-app-model-context-DcetPZR0.mjs";import{n as acquireSessionMcpRuntime,o as peekSessionMcpRuntime}from"./agent-bundle-mcp-manager-api-CpNDElt4.mjs";import{a as getMcpAppViewLeaseForSession,c as releaseMcpAppView,i as getMcpAppViewLease,r as fetchMcpAppView,t as acquireMcpAppViewRequest}from"./mcp-ui-resource-C1InHjbh.mjs";import{g as readSessionTranscriptSummaryAsync}from"./session-transcript-readers-D9Cuet3N.mjs";import{n as withGatewaySessionEntryReadOnly}from"./session-utils-read-lifetime-zMibBQo6.mjs";import path from"node:path";import{randomUUID}from"node:crypto";import{CallToolRequestSchema,ListResourceTemplatesRequestSchema,ListResourcesRequestSchema,ListToolsRequestSchema,ReadResourceRequestSchema}from"@modelcontextprotocol/core";
//!src/gateway/mcp-app-reconstruction.ts
const MCP_APP_RESTORE_IN_FLIGHT_KEY=Symbol.for(`openclaw.mcpAppRestoreInFlight`);async function reconstructMcpAppView(e){const t=e.agentId??resolveAgentIdFromSessionKey(e.sessionKey);const reconstruct=async(n,r)=>{const i=n.entry?.sessionId;if(!i)return;const a={agentId:t,sessionId:i,sessionKey:n.canonicalKey,storePath:n.storePath,sessionEntry:n.entry};const{data:o}=await readSessionTranscriptSummaryAsync(a,{kind:`mcp-app`,lookup:e.lookup});r();if(!o)return;const s=await acquireSessionMcpRuntime({sessionId:i,sessionKey:n.canonicalKey,agentId:t,workspaceDir:resolveAgentWorkspaceDir(e.cfg,t),agentDir:resolveAgentDir(e.cfg,t),cfg:e.cfg});const{runtime:c}=s;try{r();if(c.mcpAppsEnabled!==true)return;const n=await fetchMcpAppView({runtime:c,agentId:t,serverName:o.descriptor.serverName,toolName:o.descriptor.toolName,uiResourceUri:o.descriptor.uiResourceUri,toolCallId:o.descriptor.toolCallId,toolInput:o.toolInput,toolResult:o.toolResult,...e.viewId?{viewId:e.viewId}:{},allowedAppToolNames:e.allowedAppToolNames,...e.authorizeAppInteraction?{authorizeAppInteraction:e.authorizeAppInteraction}:{},...e.readOnly?{readOnly:true}:{}});try{r()}catch(e){if(n)releaseMcpAppView(n.viewId,c);throw e}const i=n?getMcpAppViewLease(n.viewId,c):void 0;return i?{runtime:c,view:i}:void 0}finally{await releaseSessionMcpRuntime(s)}};if(isIncognitoSessionKey(e.sessionKey))return withGatewaySessionEntryReadOnly({cfg:e.cfg,key:e.sessionKey,agentId:t},async(n,r)=>{const i=captureSessionEntryMetadataRead({sessionKey:e.sessionKey,agentId:t},r);const assertCurrent=()=>{const e=i?.readCurrent();if(e?.sessionId!==n.entry?.sessionId||e?.lifecycleRevision!==n.entry?.lifecycleRevision||e?.archivedAt!==n.entry?.archivedAt)throw new Error(`MCP App reconstruction session changed`)};return reconstruct(n,assertCurrent)});return withGatewaySessionEntryReadOnly({cfg:e.cfg,key:e.sessionKey,agentId:t},reconstruct)}async function mintMcpAppViewFromTranscript(e){const{descriptor:t,...n}=e;return await reconstructMcpAppView({...n,lookup:{descriptor:t}})}async function restoreMcpAppView(e){const t=`${e.agentId??``}\0${e.sessionKey}\0${e.viewId}`;const n=resolveGlobalMap(MCP_APP_RESTORE_IN_FLIGHT_KEY);return await getOrCreatePromise(n,t,async()=>{if(!e.viewId.startsWith(`mcp-app-`)||e.viewId.length>128)return;return reconstructMcpAppView({...e,lookup:{viewId:e.viewId},allowedAppToolNames:/* @__PURE__ */ new Set,readOnly:true})},{evictOnSettled:true})}
//!src/gateway/mcp-app-operations.ts
function resolveMcpAppRequesterId(e){const t=resolveGatewayOperatorRoleActor(e);return e?.authenticatedUserProfile?.profileId??(t?.kind===`operator`?t.profileId:void 0)}var McpAppViewExpiredError=class extends Error{constructor(){super(`MCP App view expired or is not authorized for this session`);this.name=`McpAppViewExpiredError`}};const McpAppOperationSchema=discriminatedUnion(`method`,[CallToolRequestSchema,ListToolsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema]);function isAppCallableTool(e,t){return t.serverName===e.serverName&&(t.uiVisibility===void 0||t.uiVisibility.includes(`app`))&&(e.allowedAppToolNames===void 0||e.allowedAppToolNames.has(t.toolName))}function isAppCallableListedTool(e){const t=asOptionalRecord(e._meta?.ui)?.visibility;return!Array.isArray(t)||t.includes(`app`)}async function requireMcpAppInteraction(e){if(e.readOnly===true||e.allowedAppToolNames===void 0)throw new Error(`MCP App view is read-only`);if(e.authorizeAppInteraction&&!await e.authorizeAppInteraction())throw new Error(`MCP App widget grant is no longer active`)}async function supportsMcpAppInteraction(e){try{await requireMcpAppInteraction(e);return true}catch{return false}}async function resolveMcpAppAllowedToolNames(e){if(e.view.readOnly===true||e.view.allowedAppToolNames===void 0)return[];return(await e.runtime.getCatalog()).tools.filter(t=>isAppCallableTool(e.view,t)).map(e=>e.toolName).filter((e,t,n)=>n.indexOf(e)===t).toSorted()}async function getRequestCatalog(e){const t=getSessionMcpRequestSignal();t?.throwIfAborted();return racePromiseWithAbortSignal(e.getCatalog(),t)}async function requireCallableTool(e,t,n){await requireMcpAppInteraction(t);const r=(await getRequestCatalog(e)).tools.find(e=>e.serverName===t.serverName&&e.toolName===n);if(!r||!isAppCallableTool(t,r))throw new Error(`MCP tool "${n}" is not app-callable`)}async function resolveMcpAppActiveView(e){const requireRequester=t=>{if(t.view.requesterId!==void 0&&t.view.requesterId!==e.requesterId)throw new McpAppViewExpiredError;t.runtime.assertOwnerCurrent?.();return t};if(e.cfg&&e.cfg.mcp?.apps?.enabled!==true)throw new Error(`MCP App runtime is unavailable`);const t=e.agentId?getMcpAppViewLeaseForSession(e.viewId,e.sessionKey,e.agentId):void 0;if(t){if(t.runtime.mcpAppsEnabled!==true)throw new Error(`MCP App runtime is unavailable`);return requireRequester({runtime:t.runtime,view:t})}const n=e.agentId&&!parseAgentSessionKey(e.sessionKey)?void 0:peekSessionMcpRuntime({sessionKey:e.sessionKey});if(n&&n.mcpAppsEnabled!==true)throw new Error(`MCP App runtime is unavailable`);const r=n?getMcpAppViewLease(e.viewId,n):void 0;const i=n?.mcpAppsEnabled===true&&r?{runtime:n,view:r}:e.cfg&&e.restore!==false?await restoreMcpAppView({cfg:e.cfg,agentId:e.agentId,sessionKey:e.sessionKey,viewId:e.viewId}):void 0;if(!i)throw new McpAppViewExpiredError;return requireRequester(i)}async function withMcpAppActiveView(e,t,n){e.runtime.assertOwnerCurrent?.();e.runtime.markUsed();const r=acquireMcpAppViewRequest(e.view,t);const i=e.runtime.acquireLease?.();try{return await n()}finally{r();i?.();await completeDeferredSessionMcpRuntimeRetirement(e.runtime).catch(e=>{logWarn(`mcp-app: deferred runtime cleanup failed: ${formatErrorMessage(e)}`)})}}async function withMcpAppReadAuthority(e,t){return await withMcpAppActiveView(e,`read`,async()=>{await requireMcpAppInteraction(e.view);const n=await t();await requireMcpAppInteraction(e.view);return n})}async function prepareModelCreatedAppToolCall(e,t){const[{loadSessionMcpConfig:n},{buildBundleMcpToolsFromCatalog:r},{getPluginToolMeta:i},{createMcpToolFilter:a,mcpCatalogToolFilterScope:o,normalizeMcpToolFilter:s},{requiresMcpCodexToolApproval:c,resolveProjectedMcpCodexToolApprovalMode:l},{getSessionRowProjection:u},{resolveSessionResourceToolPolicy:d},{requestMcpAppToolApproval:f}]=await Promise.all([import(`./agent-bundle-mcp-runtime-config-BmTzB7LK.mjs`),import(`./agents/agent-bundle-mcp-materialize.js`),import(`./plugins/tool-metadata.js`),import(`./mcp-tool-filter-C5Li-lav.mjs`),import(`./mcp-codex-tool-approval-IS3m5aNJ.mjs`),import(`./session-row-projection-access-BEoBkkxz.mjs`),import(`./session-resource-tool-policy-_bFfmaZR.mjs`),import(`./mcp-app-tool-approval-BWx2eKzp.mjs`)]);t.assertCurrent();const{runtime:p,view:m}=e;const{options:h}=t;const g=p.sessionKey;const _=u(h.context);if(!g||!_)throw new Error(`MCP App current session policy is unavailable`);const v=h.context.getRuntimeConfig();const y={agentId:m.agentId,key:g};const b=resolveMcpAppRequesterId(h.client);const current=()=>{t.assertCurrent();if(h.context.getRuntimeConfig()!==v||v.mcp?.apps?.enabled!==true||u(h.context)!==_||resolveMcpAppRequesterId(h.client)!==b||m.requesterId!==void 0&&b!==m.requesterId)throw new Error(`MCP App requester or configuration changed`);const e=_.sharingTarget(y);if(!e||e.entry.sessionId!==p.sessionId||m.sessionId!==p.sessionId)throw new Error(`MCP App session changed`);return e};const x=current();const S=x.entry.lifecycleRevision;const{loaded:C}=n({workspaceDir:p.workspaceDir,cfg:v,toolOverrides:x.entry.toolOverrides});const w=C.mcpServers[m.serverName];const T=p.peekCatalog();const E=T?.servers[m.serverName];const D=T?.tools.find(e=>e.serverName===m.serverName&&e.toolName===t.toolName);if(!T||!E||!D||!w&&!(p.assertOwnerCurrent&&E.pluginId))throw new Error(`MCP App approval origin is not known to the current server/native owner`);const O=r({catalog:T,includeAppOnlyInventory:true}).find(e=>{const n=i(e)?.mcp;return n?.operation===`tool`&&n.serverName===m.serverName&&n.toolName===t.toolName});if(!O)throw new Error(`MCP App current tool projection is unavailable`);const k=JSON.stringify({server:E,tool:D});const assertPolicy=()=>{const e=current();if(e.entry.lifecycleRevision!==S)throw new Error(`MCP App session lifecycle changed`);const n=p.peekCatalog();const r=n?.tools.find(e=>e.serverName===m.serverName&&e.toolName===t.toolName);if(!n||!r||!isAppCallableTool(m,r)||r.deniedBySession||JSON.stringify({server:n.servers[m.serverName],tool:r})!==k||e.entry.toolOverrides?.mcpServers?.[m.serverName]===false||e.entry.toolOverrides?.mcpToolsDeny?.[m.serverName]?.includes(t.toolName)||w&&!a(s(w.toolFilter),o(n,m.serverName))(t.toolName))throw new Error(`MCP App tool is denied by current policy`);d({config:v,client:h.client,current:e,readPreparedSessionEntry:e=>_.sharingTarget(e)?.entry,toolName:O.name,assertNativeRuntimeCurrent:p.assertOwnerCurrent});return c({mode:w?l(m.serverName,w):`prompt`,fullPermission:e.entry.permissionMode===`full`,annotations:r.codexAnnotations})};const A=assertPolicy();if(A)await f({options:h,agentId:m.agentId,sessionKey:g,serverName:m.serverName,toolName:t.toolName,input:t.input,view:t.view,requesterId:b,signal:h.signal,assertCurrent:()=>{assertPolicy()}});const assertExecutionCurrent=()=>{if(assertPolicy()&&!A)throw new Error(`MCP App approval policy changed before execution`)};assertExecutionCurrent();return assertExecutionCurrent}async function executeMcpAppOperation(e,t,n){const{runtime:r,view:i}=e;if(t.method===`tools/call`)return await withMcpAppActiveView(e,`tool`,async()=>{await requireCallableTool(r,i,t.params.name);await requireMcpAppInteraction(i);const a=t.params.arguments??{};const assertViewCurrent=()=>{n?.assertCurrent();r.assertOwnerCurrent?.();n?.options.signal?.throwIfAborted();if(getMcpAppViewLease(i.viewId,r)!==i||i.readOnly||i.allowedAppToolNames===void 0)throw new McpAppViewExpiredError};let o;const assertCurrent=()=>{assertViewCurrent();if(o)o()};if(i.prepareToolCall){if(!n)throw new Error(`This App tool requires an authenticated request for approval`);o=await i.prepareToolCall({options:n.options,toolName:t.params.name,input:a,view:i,assertCurrent:assertViewCurrent,signal:n.options.signal});assertCurrent()}else if(n)o=await prepareModelCreatedAppToolCall(e,{options:n.options,toolName:t.params.name,input:a,view:i,assertCurrent:assertViewCurrent});await requireMcpAppInteraction(i);if(n){if(!r.sessionKey)throw new Error(`MCP App session is unavailable`);return await callMcpAppToolWithElicitation({options:n.options,origin:{runtime:r,serverName:i.serverName,agentId:i.agentId,sessionKey:r.sessionKey,requesterId:resolveMcpAppRequesterId(n.options.client),assertCurrent,prepareToolCall:i.prepareToolCall},toolName:t.params.name,input:a,assertCurrent,uploadResources:i.uploadResources,...i.hostFile?{_meta:{"openai/resource":{path:path.join(i.hostFile.rootDir,i.hostFile.path)}}}:{}})}if(i.hostFile)return await r.callTool(i.serverName,t.params.name,a,{_meta:{"openai/resource":{path:path.join(i.hostFile.rootDir,i.hostFile.path)}}});return await r.callTool(i.serverName,t.params.name,a)});return await withMcpAppReadAuthority(e,async()=>{switch(t.method){case`tools/list`:{if(!r.listTools)throw new Error(`MCP tools/list is unavailable`);const[e,n]=await Promise.all([r.listTools(i.serverName,t.params?.cursor!==void 0?{cursor:t.params.cursor}:void 0),getRequestCatalog(r)]);const a=new Set(n.tools.filter(e=>isAppCallableTool(i,e)).map(e=>e.toolName));return{...e,tools:e.tools.filter(e=>a.has(e.name.trim())&&isAppCallableListedTool(e))}}case`resources/list`:{if(!r.listResources)throw new Error(`MCP resources/list is unavailable`);const e=await r.listResources(i.serverName);return Array.isArray(e)?{resources:e}:e}case`resources/templates/list`:if(!r.listResourceTemplates)throw new Error(`MCP resources/templates/list is unavailable`);return await r.listResourceTemplates(i.serverName,t.params?.cursor!==void 0?{cursor:t.params.cursor}:void 0);case`resources/read`:if(!r.readResource)throw new Error(`MCP resources/read is unavailable`);return await r.readResource(i.serverName,t.params.uri);default:throw new Error(`Unsupported MCP App operation: ${String(t)}`)}})}function parseMcpAppOperation(e){const t=McpAppOperationSchema.safeParse(e);return t.success?t.data:void 0}async function callMcpAppToolWithElicitation(e){const t=[e.options.signal,e.signal,getSessionMcpRequestSignal()].filter(e=>e!==void 0);const n=t.length?AbortSignal.any(t):new AbortController().signal;const assertCurrent=()=>{n.throwIfAborted();e.assertCurrent();e.origin.assertCurrent()};assertCurrent();const r=/* @__PURE__ */ new Map;const retireQuestions=()=>{const t=e.options.context.questionManager;for(const[e,n]of r){try{if(t&&n.isCurrent()&&n.record.status===`pending`)t.cancel(e,`mcp-app-request-retired`)}catch(e){logWarn(`mcp-app: question cleanup failed: ${formatErrorMessage(e)}`)}r.delete(e)}};n.addEventListener(`abort`,retireQuestions,{once:true});const i=createMcpClientElicitationHandler({sessionKey:e.origin.sessionKey,agentId:e.origin.agentId,assertCurrent,gatewayCall:{version:2,call:async({method:t,params:i,signal:a,authority:o})=>{const assertDispatchCurrent=()=>{assertCurrent();if(o.kind===`source-bound`)o.assertCurrent()};assertDispatchCurrent();const{handleGatewayRequest:s}=await import(`./server-methods-DZVMDOjo.mjs`);assertDispatchCurrent();return await new Promise((o,c)=>{s({req:{type:`req`,id:randomUUID(),method:t,params:i},client:e.options.client,context:e.options.context,methodRegistry:e.options.context.getGatewayMethodRegistry?.(),isWebchatConnect:e.options.isWebchatConnect,signal:a??n,sessionMutationCommitGuard:assertDispatchCurrent,hasCurrentClientAuthority:e.options.hasCurrentClientAuthority,respond:(i,a,s)=>{if(!i){c(new Error(s?.message??`App question request failed`));return}if(t===`question.request`){const t=asOptionalRecord(a)?.id;const i=typeof t===`string`?e.options.context.questionManager?.observe(t):void 0;if(i&&typeof t===`string`){r.set(t,i);if(n.aborted)retireQuestions()}}o(a)}}).catch(c)})}},prepareResourceContext:async t=>{const{createMcpAppFormResourceContext:n}=await import(`./mcp-app-form-resources-DQz6jYUU.mjs`);assertCurrent();return n({snapshot:t.snapshot,signal:t.signal,origin:e.origin,uploadResources:e.uploadResources})}});try{return await runWithSessionMcpRequestSignal(n,()=>runWithMcpElicitationHandler(i,()=>e.origin.runtime.callTool(e.origin.serverName,e.toolName,e.input,{...e._meta?{_meta:e._meta}:{},assertCurrent})))}finally{n.removeEventListener(`abort`,retireQuestions);retireQuestions()}}export{prepareModelCreatedAppToolCall as a,resolveMcpAppAllowedToolNames as c,withMcpAppActiveView as d,mintMcpAppViewFromTranscript as f,parseMcpAppOperation as i,resolveMcpAppRequesterId as l,callMcpAppToolWithElicitation as n,requireMcpAppInteraction as o,executeMcpAppOperation as r,resolveMcpAppActiveView as s,McpAppViewExpiredError as t,supportsMcpAppInteraction as u};