UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 18.8 kB
import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{a as resolveAgentDir,f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{o as getGatewayPluginMetadataSnapshot}from"./plugin-metadata-lifecycle-Bdt91XXL.mjs";import{Dr as ZodError,Et as _enum,Fn as object,Jn as string,Lt as boolean,Nt as array,Pn as number,Un as record,or as union}from"./schemas-DuCQi-Qb.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{i as getPluginToolMeta}from"./tool-metadata-Cb5nBZYD.mjs";import{i as logWarn}from"./logger-BHIcoxTH.mjs";import{n as getSessionRowProjection}from"./session-row-projection-access-w2LnU_PB.mjs";import{i as resolveSandboxRuntimeStatus}from"./runtime-status-DDAPGR6Y.mjs";import{n as getRegisteredAgentHarness}from"./registry-BzjsVuM_.mjs";import{n as captureGatewayOperatorRunAuthority}from"./operator-run-authority-DIEMEkD5.mjs";import{o as resolveEffectiveAgentRuntime}from"./thinking-runtime-V6V09nGt.mjs";import{n as resolveSessionSelectedModelRefAsync}from"./session-utils-model-selection-M8bmLLz0.mjs";import{t as iteratePluginRootContributions}from"./plugin-root-contributions-CmNJYoLA.mjs";import{n as runWithSessionMcpRequestSignal}from"./agent-bundle-mcp-request-context-Cztgq5sC.mjs";import{t as loadSessionMcpConfig}from"./agent-bundle-mcp-runtime-config-pqoelK3d.mjs";import{p as releaseSessionMcpRuntime}from"./mcp-app-model-context-DcetPZR0.mjs";import{n as acquireSessionMcpRuntime}from"./agent-bundle-mcp-manager-api-CpNDElt4.mjs";import{t as buildBundleMcpToolsFromCatalog}from"./agent-bundle-mcp-materialize-BrUeyxQs.mjs";import{i as normalizeMcpToolFilter,n as createMcpToolFilter,r as mcpCatalogToolFilterScope}from"./mcp-tool-filter-BH9FcYdc.mjs";import{i as getMcpAppViewLease,n as buildMcpAppCanvasPayload,r as fetchMcpAppView}from"./mcp-ui-resource-C1InHjbh.mjs";import{i as resolveProjectedMcpCodexToolApprovalMode,r as requiresMcpCodexToolApproval}from"./mcp-codex-tool-approval-BEHr8MWJ.mjs";import{n as readMcpAppSettings}from"./mcp-app-extension-metadata-CiD9piiz.mjs";import{l as resolveMcpAppRequesterId,n as callMcpAppToolWithElicitation}from"./mcp-app-operations-DJwJ400G.mjs";import{t as resolveSessionResourceToolPolicy}from"./session-resource-tool-policy-COv37Fk4.mjs";import{r as prepareMcpAppHostFile}from"./mcp-app-host-files-BDLPhE_9.mjs";import{t as requestMcpAppToolApproval}from"./mcp-app-tool-approval-ClFkaUwG.mjs";import{randomUUID}from"node:crypto";import{ResourceLinkSchema}from"@modelcontextprotocol/core"; //!src/gateway/mcp-app-extension-runtime.ts async function prepareMcpAppExtensionRuntime(e){const t=e.sessionAccessAuthority;const n=getSessionRowProjection(e.context);if(!t||!n)throw new Error(`MCP App session authority is unavailable`);t.assertCurrent();const{agentId:r,sessionKey:i,sessionId:a}=t.target;const o={agentId:r,key:i};const s=n.sharingTarget(o);if(!s||s.entry.sessionId!==a)throw new Error(`MCP App session changed`);const c=e.context.getRuntimeConfig();if(c.mcp?.apps?.enabled!==true)throw new Error(`MCP Apps are disabled`);const l=await resolveSessionSelectedModelRefAsync({cfg:c,agentId:r,sessionKey:i,source:{entry:s.entry,readSourceEntry:e=>n.sharingTarget({agentId:r,key:e})?.entry},manifestPlugins:getGatewayPluginMetadataSnapshot()??[],assertCurrent:t.assertCurrent});const u=resolveEffectiveAgentRuntime({cfg:c,provider:l.provider,modelId:l.model,agentScope:{kind:`prepared`,agentId:r},sessionKey:i,sessionEntry:s.entry});const{authProfileOverride:d,authProfileOverrideSource:f,sandboxMode:p}=s.entry;const current=(r=t.assertCurrent)=>{r();if(e.context.getRuntimeConfig()!==c)throw new Error(`MCP App configuration changed; reopen the App`);const i=n.sharingTarget(o);if(!i||i.entry.sessionId!==a)throw new Error(`MCP App session changed`);if(i.entry.authProfileOverride!==d||i.entry.authProfileOverrideSource!==f||i.entry.sandboxMode!==p)throw new Error(`MCP App session runtime selection changed; reopen the App`);return i};const m=current();const h=m.entry.spawnedWorkspaceDir??resolveAgentWorkspaceDir(c,r);const g=resolveMcpAppRequesterId(e.client);const _=u?getRegisteredAgentHarness(u):void 0;if(u!==`openclaw`&&!_)throw new Error(`The selected session harness is unavailable`);const v=_?.harness;const{loaded:y}=loadSessionMcpConfig({workspaceDir:h,cfg:c,toolOverrides:m.entry.toolOverrides});let b;if(u!==`openclaw`){if(!v?.loadMcpToolCatalog||!v.acquireMcpAppRuntime)throw new Error(`The session harness cannot open MCP Apps`);const n={};let o;let s=false;const u=new AbortController;const prepareSession=()=>{if(s)throw new Error(`MCP App session preparation is closed`);o??=(async()=>{const o=resolveSandboxRuntimeStatus({cfg:c,agentId:r,sessionKey:i,preparedSessionEntry:current().entry});if(t.sandboxRequired||o.sandboxed||o.sandboxRequired)throw new Error(`Native App initialization cannot run outside required session isolation`);if(!_?.ownerPluginId)throw new Error(`Native harness owner is unavailable`);const s=t.retain();n.access=s;const d=AbortSignal.any([u.signal,s.signal,...e.signal?[e.signal]:[]]);const assertPreparationCurrent=()=>{current();s.assertCurrent();d.throwIfAborted()};assertPreparationCurrent();const f=await captureGatewayOperatorRunAuthority({client:e.client,context:e.context,hasCurrentClientAuthority:e.hasCurrentClientAuthority,invocationAuthority:{assertCurrent:assertPreparationCurrent,signal:d}});n.source=f;assertPreparationCurrent();const p=current();const{prepareAgentHarnessSessionRuntime:m}=await import(`./session-preparation-qrLbsOFm.mjs`);const y=await m({ownerPluginId:_.ownerPluginId,nativeModelPolicySupport:v.nativeModelPolicySupport,sourceAuthority:f?.authority,assertCurrent:assertPreparationCurrent,input:{config:c,agentId:r,agentDir:resolveAgentDir(c,r),sessionId:a,sessionKey:i,workspaceDir:h,provider:l.provider,modelId:l.model,authProfileId:p.entry.authProfileOverride,authProfileIdSource:p.entry.authProfileOverrideSource===`auto`?`auto`:p.entry.authProfileOverride?`user`:void 0,senderId:g,messageChannel:`webchat`,messageProvider:`webchat`,abortSignal:d,permissionMode:p.entry.permissionMode,sessionRoot:p.entry.sessionRoot,toolOverrides:p.entry.toolOverrides,spawnedBy:p.entry.spawnedBy,groupId:p.entry.groupId,groupChannel:p.entry.groupChannel,groupSpace:p.entry.space,sessionTarget:{agentId:r,sessionId:a,sessionKey:i,storePath:p.storePath,expectedLifecycleRevision:p.entry.lifecycleRevision}}});n.setup=y;assertPreparationCurrent();return y.preparation})();o.catch(()=>{});return o};const d=[];const settle=async e=>{try{await e()}catch(e){if(!d.includes(e))d.push(e)}};try{b=await v.acquireMcpAppRuntime({config:c,agentId:r,sessionId:a,sessionKey:i,workspaceDir:h,mcpServerNames:Object.keys(y.mcpServers),toolOverrides:m.entry.toolOverrides,assertCurrent:t.assertCurrent,appRequester:g?{kind:`gateway-profile`,profileId:g}:void 0,prepareSession})}catch(e){d.push(e)}finally{s=true;u.abort(/* @__PURE__ */ new Error(`MCP App session preparation is closed`));await settle(()=>o);await settle(()=>n.setup?.dispose());await settle(()=>n.source?.release());await settle(()=>n.access?.release())}if(d.length>0){if(b){const e=b;await settle(()=>releaseSessionMcpRuntime(e));await settle(()=>e.runtime.joinCleanup?.())}throw d.length===1?d[0]:new AggregateError(d,`MCP App runtime preparation failed`)}}else b=await acquireSessionMcpRuntime({sessionId:a,sessionKey:i,agentId:r,workspaceDir:h,agentDir:resolveAgentDir(c,r),cfg:c,requesterSenderId:g,messageChannel:`webchat`,toolOverrides:m.entry.toolOverrides});if(!b)throw new Error(`Open a conversation with this plugin before launching its App`);const x=b;const S=x.runtime;const C=[];try{current();const o=await S.getCatalog();const s={...o,servers:Object.fromEntries(Object.entries(o.servers).map(([e,t])=>[e,{...t,pluginId:t.pluginId??y.pluginIdsByServer?.[e]}]))};current();const c=buildBundleMcpToolsFromCatalog({catalog:s,includeAppOnlyInventory:true});const l=new Map(c.flatMap(e=>{const t=getPluginToolMeta(e)?.mcp;return t?.operation===`tool`?[[JSON.stringify([t.serverName,t.toolName]),e.name]]:[]}));const assertTool=(r,i=false,a=t.assertCurrent)=>{const o=current(a);if(e.context.getRuntimeConfig().mcp?.apps?.enabled!==true)throw new Error(`MCP Apps are disabled`);const c=y.mcpServers[r.serverName];if(!c&&!(S.assertOwnerCurrent&&s.servers[r.serverName]?.pluginId)||c&&!createMcpToolFilter(normalizeMcpToolFilter(c.toolFilter),mcpCatalogToolFilterScope(s,r.serverName))(r.toolName))throw new Error(`MCP App tool is denied by server policy`);const u=l.get(JSON.stringify([r.serverName,r.toolName]));if(!u||o.entry.toolOverrides?.mcpServers?.[r.serverName]===false||o.entry.toolOverrides?.mcpToolsDeny?.[r.serverName]?.includes(r.toolName))throw new Error(`MCP App tool is denied`);resolveSessionResourceToolPolicy({config:e.context.getRuntimeConfig(),client:e.client,current:o,readPreparedSessionEntry:e=>n.sharingTarget(e)?.entry,toolName:u,assertNativeRuntimeCurrent:S.assertOwnerCurrent});return i&&requiresMcpCodexToolApproval({mode:(c?resolveProjectedMcpCodexToolApprovalMode(r.serverName,c):`prompt`)??s.servers[r.serverName]?.codexApprovalMode,fullPermission:o.entry.permissionMode===`full`,annotations:r.codexAnnotations})};const prepareToolCall=async(e,n,a=t.assertCurrent)=>{const assertCurrent=()=>{n.assertCurrent();assertTool(e,false,a)};n.assertCurrent();const o=assertTool(e,true,a);if(o)await requestMcpAppToolApproval({options:n.options,agentId:r,sessionKey:i,serverName:e.serverName,toolName:e.toolName,input:n.input,view:n.view,requesterId:resolveMcpAppRequesterId(n.options.client),signal:n.signal,assertCurrent});const assertExecutionCurrent=()=>{n.assertCurrent();if(assertTool(e,true,a)&&!o)throw new Error(`MCP App approval policy changed before execution`)};assertExecutionCurrent();return assertExecutionCurrent};const approveTool=async(n,r)=>{const i=assertTool(n,true)?t.retain():void 0;if(i)C.push(i.release);return prepareToolCall(n,{options:e,toolName:n.toolName,input:r,signal:i?.signal,assertCurrent:i?.assertCurrent??t.assertCurrent})};const u=s.tools.filter(e=>{try{assertTool(e);return true}catch{return false}});const retainViewAuthority=e=>{const n=t.retain();const prepareViewToolCall=async t=>{const r=e.find(e=>e.toolName===t.toolName);if(!r)throw new Error(`MCP App tool is not granted to this view`);return prepareToolCall(r,{...t,signal:t.signal?AbortSignal.any([n.signal,t.signal]):n.signal},n.assertCurrent)};return{...n,prepareToolCall:prepareViewToolCall,assertCurrent:()=>{if(current(n.assertCurrent).entry.permissionMode!==m.entry.permissionMode)throw new Error(`MCP App permission mode changed; reopen the App`);for(const t of e)assertTool(t,false,n.assertCurrent)}}};return{approveTool,retainViewAuthority,options:e,runtime:S,catalog:{...s,tools:u},agentId:r,sessionKey:i,sessionId:a,workspaceDir:h,requesterId:g,access:t,assertTool,assertCurrent:()=>{current()},dispose:async()=>{for(const e of C.splice(0))e();await releaseSessionMcpRuntime(x);await S.joinCleanup?.()}}}catch(e){for(const e of C.splice(0))e();await releaseSessionMcpRuntime(b);throw e}} //!src/gateway/server-methods/mcp-app-extensions.ts var UnsupportedMcpMentionResultError=class extends Error{};const text=string().trim().min(1).max(2048);const targetSchema=object({sessionKey:text,agentId:text.optional()});const launchSchema=targetSchema.extend({serverName:text,toolName:text,entrypointType:_enum([`global`,`thread`,`file`,`settings`]),quickAction:boolean().optional(),filePath:text.optional(),deepLink:text.optional()});const settingsSchema=targetSchema.extend({serverName:text,action:_enum([`read`,`update`,`tool`]),toolName:text.optional(),arguments:object({set:record(string(),union([string(),number().finite(),boolean()]))}).optional()});const mentionSchema=targetSchema.extend({serverName:text,query:string().max(2048)});function toolFor(e,t,n){const r=e.catalog.tools.find(e=>e.serverName===t&&e.toolName===n);if(!r)throw new Error(`MCP App tool is unavailable or denied`);e.assertTool(r);return r}function appToolsFor(e,t){return e.catalog.tools.filter(n=>{if(n.serverName!==t||n.uiVisibility!==void 0&&!n.uiVisibility.includes(`app`))return false;try{e.assertTool(n);return true}catch{return false}})}async function uploadFor(e,t,n){const{prepareMcpAppFormUpload:r}=await import(`./mcp-form-resource-upload-ByQAfv5W.mjs`);return await r({runtime:e.runtime,serverName:t,agentId:e.agentId,sessionKey:e.sessionKey,requesterId:e.requesterId,assertCurrent:n})}async function call(e,t,n){const r=await e.approveTool(t,n);const i=e.retainViewAuthority(appToolsFor(e,t.serverName));let a;try{a=await callMcpAppToolWithElicitation({options:e.options,uploadResources:await uploadFor(e,t.serverName,r),origin:{runtime:e.runtime,serverName:t.serverName,agentId:e.agentId,sessionKey:e.sessionKey,requesterId:e.requesterId,assertCurrent:r,prepareToolCall:i.prepareToolCall},toolName:t.toolName,input:n,assertCurrent:r})}finally{i.release()}e.assertCurrent();return a}async function launch(e,t,n,r){if(!t.uiResourceUri?.startsWith(`ui://`))throw new Error(`MCP App resource is unavailable`);const i=await call(e,t,n);if(i.isError)return{toolResult:i};const a=appToolsFor(e,t.serverName);const o=e.retainViewAuthority(a);let s=false;try{const c=e.runtime;const l=new Set(a.map(e=>e.toolName));const u=await fetchMcpAppView({runtime:c,agentId:e.agentId,serverName:t.serverName,toolName:t.toolName,uiResourceUri:t.uiResourceUri,toolCallId:randomUUID(),toolInput:n,toolResult:i,allowedAppToolNames:l,requesterId:e.requesterId,displayMode:t.appExtensions?.preferredModelDisplayMode,prepareToolCall:o.prepareToolCall,uploadResources:await uploadFor(e,t.serverName,o.assertCurrent),...r,authorizeAppInteraction:()=>{o.assertCurrent();return true}});if(!u)throw new Error(`MCP App resource could not be loaded`);const d=buildMcpAppCanvasPayload({...u,originSessionKey:e.sessionKey});e.assertCurrent();const f=getMcpAppViewLease(u.viewId,c);if(f){f.disposeCallbacks??=/* @__PURE__ */ new Set;f.disposeCallbacks.add(o.release);s=true}return{viewId:u.viewId,preview:d}}finally{if(!s)o.release()}}function handler(e,t,n){return async r=>{let i;try{const a=e.parse(r.params);if(n&&r.context.getRuntimeConfig().mcp?.apps?.enabled!==true){r.sessionAccessAuthority?.assertCurrent();r.respond(true,n);return}await runWithSessionMcpRequestSignal(r.signal,async()=>{i=await prepareMcpAppExtensionRuntime(r);const e=await t(i,a);i.assertCurrent();r.respond(true,e)})}catch(e){r.respond(false,void 0,errorShape(e instanceof ZodError?ErrorCodes.INVALID_REQUEST:ErrorCodes.UNAVAILABLE,e instanceof Error?e.message:String(e),e instanceof UnsupportedMcpMentionResultError?{details:{code:`MCP_APP_UNSUPPORTED_MENTION_RESULT`}}:void 0))}finally{await i?.dispose().catch(e=>logWarn(`mcp-app: cleanup failed: ${String(e)}`))}}}const mcpAppExtensionHandlers={"mcp.app.discover":handler(targetSchema,e=>({onboarding:(()=>{const t=getGatewayPluginMetadataSnapshot();return t?[...iteratePluginRootContributions({metadataSnapshot:t,config:e.options.context.getRuntimeConfig(),contribution:`skills`})].flatMap(({record:e})=>e.onboardingSkill?[{pluginId:e.id,title:e.name??e.id}]:[]):[]})(),servers:Object.values(e.catalog.servers).flatMap(t=>{const n=t.pluginId?getGatewayPluginMetadataSnapshot()?.index.installRecords[t.pluginId]:void 0;const r=n?.marketplacePlugin??t.pluginId;const i=n?.marketplaceName??t.marketplace;const a=e.catalog.tools.filter(e=>e.serverName===t.serverName);const o=a.flatMap(e=>e.uiResourceUri?.startsWith(`ui://`)?(e.appExtensions?.entrypoints??[]).map(n=>({toolName:e.toolName,title:e.title??e.toolName,resourceUri:e.uiResourceUri,icons:e.appExtensions?.icons??t.icons,entrypoint:n})):[]);const s=t.settings&&a.some(e=>e.toolName===t.settings?.readTool)&&a.some(e=>e.toolName===t.settings?.updateTool)?t.settings:void 0;const c=a.find(e=>e.appExtensions?.mentionSearch)?.toolName;return o.length||s||c?[{serverName:t.serverName,...r?{pluginId:r}:{},...i?{marketplace:i}:{},label:t.title??t.serverName,icons:t.icons,entrypoints:o,...s?{settings:s}:{},...c?{mentionTool:c}:{}}]:[]})}),{servers:[],onboarding:[]}),"mcp.app.launch":handler(launchSchema,async(e,t)=>{const n=toolFor(e,t.serverName,t.toolName);const r=n.appExtensions?.entrypoints?.find(e=>e.type===t.entrypointType);if(!r)throw new Error(`The requested MCP App entrypoint is not advertised`);if(t.quickAction){if(r.type!==`global`||!r.quickAction)throw new Error(`MCP App quick action is unavailable`);const n=r.quickAction.target;const i=toolFor(e,t.serverName,n.name);return i.uiResourceUri?launch(e,i,n.arguments??{}):{toolResult:await call(e,i,n.arguments??{})}}if(r.type===`file`){if(!t.filePath)throw new Error(`Choose a session file to open`);const i=await prepareMcpAppHostFile(e.options,{sessionKey:e.sessionKey,agentId:e.agentId,path:t.filePath});e.assertCurrent();if(!r.extensions.some(e=>i.name.toLowerCase().endsWith(e.toLowerCase())))throw new Error(`The file extension is not supported by this App`);return await launch(e,n,{file:{name:i.name,resourceUri:i.resourceUri}},{hostFile:i})}if(t.deepLink&&(r.type!==`global`||!t.deepLink.startsWith(`/`)||t.deepLink.startsWith(`//`)||t.deepLink.includes(`#`)))throw new Error(`Invalid App-relative deep link`);return await launch(e,n,{},t.deepLink?{deepLink:{url:t.deepLink}}:void 0)}),"mcp.app.settings":handler(settingsSchema,async(e,t)=>{const n=e.catalog.servers[t.serverName]?.settings;if(!n)throw new Error(`Structured MCP settings are unavailable`);if(t.action===`update`){if(!t.arguments)throw new Error(`Changed settings are required`);return{toolResult:await call(e,toolFor(e,t.serverName,n.updateTool),t.arguments)}}const r=await call(e,toolFor(e,t.serverName,n.readTool),{});if(r.isError)throw new Error(`The MCP settings read tool failed`);const i=readMcpAppSettings(r.structuredContent);if(t.action===`read`)return i;if(!i.layout?.some(e=>e.items.some(e=>e.kind===`tool`&&e.tool===t.toolName)))throw new Error(`Settings action is not advertised in the current layout`);const a=toolFor(e,t.serverName,t.toolName);return a.uiResourceUri?launch(e,a,{}):{toolResult:await call(e,a,{})}}),"mcp.app.mention":handler(mentionSchema,async(e,t)=>{const n=e.catalog.tools.find(e=>e.serverName===t.serverName&&e.appExtensions?.mentionSearch);if(!n)throw new Error(`MCP mention search is unavailable`);const r=await call(e,n,{query:t.query});if(r.isError)throw new Error(`MCP mention search failed`);const i=array(ResourceLinkSchema).max(200).safeParse(asOptionalRecord(r.structuredContent)?.items);if(!i.success)throw new UnsupportedMcpMentionResultError(`This app returned an unsupported resource list`);return{resources:i.data}})};export{mcpAppExtensionHandlers};