|
| 1 | +import { |
| 2 | + type CallToolRequest, |
| 3 | + CallToolRequestSchema, |
| 4 | + type ListResourcesRequest, |
| 5 | + ListResourcesRequestSchema, |
| 6 | + type ListResourceTemplatesRequest, |
| 7 | + ListResourceTemplatesRequestSchema, |
| 8 | + type ListToolsRequest, |
| 9 | + ListToolsRequestSchema, |
| 10 | + type ReadResourceRequest, |
| 11 | + ReadResourceRequestSchema, |
| 12 | + type Tool, |
| 13 | +} from "@modelcontextprotocol/sdk/types.js"; |
| 14 | +import { |
| 15 | + completeDeferredSessionMcpRuntimeRetirement, |
| 16 | + peekSessionMcpRuntime, |
| 17 | +} from "../agents/agent-bundle-mcp-runtime.js"; |
| 18 | +import type { McpCatalogTool, SessionMcpRuntime } from "../agents/agent-bundle-mcp-types.js"; |
| 19 | +import { |
| 20 | + acquireMcpAppViewRequest, |
| 21 | + getMcpAppViewLease, |
| 22 | + type McpAppViewLease, |
| 23 | +} from "../agents/mcp-ui-resource.js"; |
| 24 | +import type { OpenClawConfig } from "../config/types.openclaw.js"; |
| 25 | +import { formatErrorMessage } from "../infra/errors.js"; |
| 26 | +import { logWarn } from "../logger.js"; |
| 27 | +import { restoreMcpAppView } from "./mcp-app-reconstruction.js"; |
| 28 | + |
| 29 | +export type McpAppActiveView = { |
| 30 | + runtime: SessionMcpRuntime; |
| 31 | + view: McpAppViewLease; |
| 32 | +}; |
| 33 | + |
| 34 | +export type McpAppOperation = |
| 35 | + | Pick<CallToolRequest, "method" | "params"> |
| 36 | + | Pick<ListToolsRequest, "method" | "params"> |
| 37 | + | Pick<ListResourcesRequest, "method" | "params"> |
| 38 | + | Pick<ListResourceTemplatesRequest, "method" | "params"> |
| 39 | + | Pick<ReadResourceRequest, "method" | "params">; |
| 40 | + |
| 41 | +function isAppCallableTool(tool: McpCatalogTool): boolean { |
| 42 | + return tool.uiVisibility === undefined || tool.uiVisibility.includes("app"); |
| 43 | +} |
| 44 | + |
| 45 | +function isAppCallableListedTool(tool: Tool): boolean { |
| 46 | + const { _meta: metadata } = tool; |
| 47 | + const ui = |
| 48 | + metadata?.ui && typeof metadata.ui === "object" && !Array.isArray(metadata.ui) |
| 49 | + ? (metadata.ui as { visibility?: unknown }) |
| 50 | + : undefined; |
| 51 | + const visibility = Array.isArray(ui?.visibility) |
| 52 | + ? ui.visibility.filter( |
| 53 | + (entry): entry is "app" | "model" => entry === "app" || entry === "model", |
| 54 | + ) |
| 55 | + : undefined; |
| 56 | + return visibility === undefined || visibility.includes("app"); |
| 57 | +} |
| 58 | + |
| 59 | +function isAllowedByView(view: McpAppViewLease, toolName: string): boolean { |
| 60 | + return view.allowedAppToolNames === undefined || view.allowedAppToolNames.has(toolName); |
| 61 | +} |
| 62 | + |
| 63 | +async function requireCallableTool( |
| 64 | + runtime: SessionMcpRuntime, |
| 65 | + view: McpAppViewLease, |
| 66 | + toolName: string, |
| 67 | +): Promise<void> { |
| 68 | + if (view.readOnly === true) { |
| 69 | + throw new Error("MCP App view is read-only"); |
| 70 | + } |
| 71 | + const catalog = await runtime.getCatalog(); |
| 72 | + const tool = catalog.tools.find( |
| 73 | + (entry) => entry.serverName === view.serverName && entry.toolName === toolName, |
| 74 | + ); |
| 75 | + if (!tool || !isAppCallableTool(tool) || !isAllowedByView(view, toolName)) { |
| 76 | + throw new Error(`MCP tool "${toolName}" is not app-callable`); |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +export async function resolveMcpAppActiveView(params: { |
| 81 | + sessionKey: string; |
| 82 | + viewId: string; |
| 83 | + cfg?: OpenClawConfig; |
| 84 | +}): Promise<McpAppActiveView> { |
| 85 | + const existingRuntime = peekSessionMcpRuntime({ sessionKey: params.sessionKey }); |
| 86 | + if ( |
| 87 | + (existingRuntime && existingRuntime.mcpAppsEnabled !== true) || |
| 88 | + (params.cfg && params.cfg.mcp?.apps?.enabled !== true) |
| 89 | + ) { |
| 90 | + throw new Error("MCP App runtime is unavailable"); |
| 91 | + } |
| 92 | + const existingView = existingRuntime |
| 93 | + ? getMcpAppViewLease(params.viewId, existingRuntime) |
| 94 | + : undefined; |
| 95 | + const restored = |
| 96 | + existingRuntime?.mcpAppsEnabled === true && existingView |
| 97 | + ? { runtime: existingRuntime, view: existingView } |
| 98 | + : params.cfg |
| 99 | + ? await restoreMcpAppView({ |
| 100 | + cfg: params.cfg, |
| 101 | + sessionKey: params.sessionKey, |
| 102 | + viewId: params.viewId, |
| 103 | + }) |
| 104 | + : undefined; |
| 105 | + if (!restored) { |
| 106 | + throw new Error("MCP App view expired or is not authorized for this session"); |
| 107 | + } |
| 108 | + return restored; |
| 109 | +} |
| 110 | + |
| 111 | +export async function withMcpAppActiveView<T>( |
| 112 | + active: McpAppActiveView, |
| 113 | + kind: "read" | "tool", |
| 114 | + operation: () => Promise<T> | T, |
| 115 | +): Promise<T> { |
| 116 | + active.runtime.markUsed(); |
| 117 | + const release = acquireMcpAppViewRequest(active.view, kind); |
| 118 | + const releaseRuntimeLease = active.runtime.acquireLease?.(); |
| 119 | + try { |
| 120 | + return await operation(); |
| 121 | + } finally { |
| 122 | + release(); |
| 123 | + releaseRuntimeLease?.(); |
| 124 | + await completeDeferredSessionMcpRuntimeRetirement(active.runtime).catch((error: unknown) => { |
| 125 | + // A completed app tool call may have side effects. Cleanup failure must |
| 126 | + // never turn its successful response into an apparent retryable failure. |
| 127 | + logWarn(`mcp-app: deferred runtime cleanup failed: ${formatErrorMessage(error)}`); |
| 128 | + }); |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +export async function executeMcpAppOperation( |
| 133 | + active: McpAppActiveView, |
| 134 | + operation: McpAppOperation, |
| 135 | +): Promise<unknown> { |
| 136 | + const { runtime, view } = active; |
| 137 | + switch (operation.method) { |
| 138 | + case "tools/call": |
| 139 | + return await withMcpAppActiveView(active, "tool", async () => { |
| 140 | + await requireCallableTool(runtime, view, operation.params.name); |
| 141 | + return await runtime.callTool( |
| 142 | + view.serverName, |
| 143 | + operation.params.name, |
| 144 | + operation.params.arguments ?? {}, |
| 145 | + ); |
| 146 | + }); |
| 147 | + case "tools/list": |
| 148 | + return await withMcpAppActiveView(active, "read", async () => { |
| 149 | + if (!runtime.listTools) { |
| 150 | + throw new Error("MCP tools/list is unavailable"); |
| 151 | + } |
| 152 | + const [listed, catalog] = await Promise.all([ |
| 153 | + runtime.listTools( |
| 154 | + view.serverName, |
| 155 | + operation.params?.cursor ? { cursor: operation.params.cursor } : undefined, |
| 156 | + ), |
| 157 | + runtime.getCatalog(), |
| 158 | + ]); |
| 159 | + const allowed = new Set( |
| 160 | + catalog.tools |
| 161 | + .filter( |
| 162 | + (tool) => |
| 163 | + tool.serverName === view.serverName && |
| 164 | + isAppCallableTool(tool) && |
| 165 | + isAllowedByView(view, tool.toolName), |
| 166 | + ) |
| 167 | + .map((tool) => tool.toolName), |
| 168 | + ); |
| 169 | + return { |
| 170 | + ...listed, |
| 171 | + tools: listed.tools.filter( |
| 172 | + (tool) => allowed.has(tool.name.trim()) && isAppCallableListedTool(tool), |
| 173 | + ), |
| 174 | + }; |
| 175 | + }); |
| 176 | + case "resources/list": |
| 177 | + return await withMcpAppActiveView(active, "read", async () => { |
| 178 | + if (!runtime.listResources) { |
| 179 | + throw new Error("MCP resources/list is unavailable"); |
| 180 | + } |
| 181 | + // SessionMcpRuntime aggregates every upstream resources/list page, so |
| 182 | + // callers receive the complete list and no nextCursor is exposed. |
| 183 | + const resources = await runtime.listResources(view.serverName); |
| 184 | + return Array.isArray(resources) ? { resources } : resources; |
| 185 | + }); |
| 186 | + case "resources/templates/list": |
| 187 | + return await withMcpAppActiveView(active, "read", async () => { |
| 188 | + if (!runtime.listResourceTemplates) { |
| 189 | + throw new Error("MCP resources/templates/list is unavailable"); |
| 190 | + } |
| 191 | + return await runtime.listResourceTemplates( |
| 192 | + view.serverName, |
| 193 | + operation.params?.cursor ? { cursor: operation.params.cursor } : undefined, |
| 194 | + ); |
| 195 | + }); |
| 196 | + case "resources/read": |
| 197 | + return await withMcpAppActiveView(active, "read", async () => { |
| 198 | + if (!runtime.readResource) { |
| 199 | + throw new Error("MCP resources/read is unavailable"); |
| 200 | + } |
| 201 | + return await runtime.readResource(view.serverName, operation.params.uri); |
| 202 | + }); |
| 203 | + default: { |
| 204 | + const unsupported: never = operation; |
| 205 | + throw new Error(`Unsupported MCP App operation: ${String(unsupported)}`); |
| 206 | + } |
| 207 | + } |
| 208 | +} |
| 209 | + |
| 210 | +export function parseMcpAppOperation(value: unknown): McpAppOperation | undefined { |
| 211 | + const method = |
| 212 | + value && typeof value === "object" && !Array.isArray(value) |
| 213 | + ? (value as { method?: unknown }).method |
| 214 | + : undefined; |
| 215 | + const schema = |
| 216 | + method === "tools/call" |
| 217 | + ? CallToolRequestSchema |
| 218 | + : method === "tools/list" |
| 219 | + ? ListToolsRequestSchema |
| 220 | + : method === "resources/list" |
| 221 | + ? ListResourcesRequestSchema |
| 222 | + : method === "resources/templates/list" |
| 223 | + ? ListResourceTemplatesRequestSchema |
| 224 | + : method === "resources/read" |
| 225 | + ? ReadResourceRequestSchema |
| 226 | + : undefined; |
| 227 | + if (!schema) { |
| 228 | + return undefined; |
| 229 | + } |
| 230 | + const parsed = schema.safeParse(value); |
| 231 | + return parsed.success ? (parsed.data as McpAppOperation) : undefined; |
| 232 | +} |
0 commit comments