UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

173 lines (172 loc) • 6.49 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as isAutomationsToolName } from "./automations-tool-name-DNRDs0aJ.mjs"; import { p as copyInternalToolResultState } from "./internal-hooks-Ch3rqxs-.mjs"; import { f as runBeforeToolCallHook } from "./agent-tools.before-tool-call.wrapper-Dh3maIc2.mjs"; import { t as runAgentHarnessAfterToolCallHook } from "./hook-helpers-DKwpcDXZ.mjs"; import { n as createGatewayToolPolicyAssertion } from "./gateway-tool-policy-Bz1T20RP.mjs"; import { r as runWithSessionMcpToolCallAuthority } from "./agent-bundle-mcp-request-context-B-LzHCC-.mjs"; import { c as resolveToolResultFailureKind, i as protectNetworkToolExecutionError, s as resolveToolExecutionErrorKind, t as formatToolExecutionErrorMessage } from "./tool-result-error-B2GHe83l.mjs"; import "./agent-tools.before-tool-call-CCkSq-k3.mjs"; import { i as extractToolErrorMessage } from "./embedded-agent-tool-results-DbtxSr9V.mjs"; import { n as readMcpLoopbackToolName } from "./mcp-http.schema-D3hjCI90.mjs"; import { a as jsonRpcResult, i as jsonRpcError, n as MCP_LOOPBACK_SERVER_VERSION, r as MCP_LOOPBACK_SUPPORTED_PROTOCOL_VERSIONS, t as MCP_LOOPBACK_SERVER_NAME } from "./mcp-http.protocol-CkxPXDT7.mjs"; import crypto from "node:crypto"; import { ContentBlockSchema } from "@modelcontextprotocol/core"; //#region src/gateway/mcp-http.handlers.ts function stringifyMcpContent(e) { return typeof e === "string" ? e : JSON.stringify(e) ?? String(e); } const MCP_LOOPBACK_CONTENT_TYPES = /* @__PURE__ */ new Set([ "text", "image", "resource" ]); function normalizeToolCallContent(e) { const t = e?.content; if (Array.isArray(t)) return t.map((e) => { const t = ContentBlockSchema.safeParse(e); if (t.success && MCP_LOOPBACK_CONTENT_TYPES.has(t.data.type)) return t.data; return { type: "text", text: stringifyMcpContent(e) }; }); return [{ type: "text", text: stringifyMcpContent(e) }]; } /** Handles one MCP loopback JSON-RPC message and returns a response or notification null. */ async function handleMcpJsonRpc(e) { const { id: t, method: n, params: r } = e.message; const toolError = (e) => jsonRpcResult(t, { content: [{ type: "text", text: e }], isError: true }); switch (n) { case "initialize": { const n = r?.protocolVersion ?? ""; const i = MCP_LOOPBACK_SUPPORTED_PROTOCOL_VERSIONS.find((e) => e === n) ?? MCP_LOOPBACK_SUPPORTED_PROTOCOL_VERSIONS[0]; return jsonRpcResult(t, { protocolVersion: i, capabilities: { tools: {} }, serverInfo: { name: MCP_LOOPBACK_SERVER_NAME, version: MCP_LOOPBACK_SERVER_VERSION }, ...e.serverInstructions ? { instructions: e.serverInstructions } : {} }); } case "notifications/initialized": case "notifications/cancelled": return null; case "tools/list": return jsonRpcResult(t, { tools: e.toolSchema }); case "tools/call": { const n = typeof r?.name === "string" ? r.name.trim() : ""; const i = !e.toolSchema.some((e) => e.name === n) && isAutomationsToolName(n) ? e.toolSchema.find((e) => isAutomationsToolName(e.name))?.name ?? n : n; const a = r?.arguments; if (a !== void 0 && !isRecord(a)) return jsonRpcError(t, -32602, "Invalid params: tools/call arguments must be an object"); const o = a ?? {}; const s = i && e.toolSchema.some((e) => e.name === i) ? e.tools.find((e) => readMcpLoopbackToolName(e) === i) : void 0; if (!s) return toolError(`Tool not available: ${i || "unknown"}`); const c = createGatewayToolPolicyAssertion(s, e.hookContext?.config); const l = `mcp-${crypto.randomUUID()}`; const u = Date.now(); let d = o; const reportToolCallResult = (t, n, r) => { runAgentHarnessAfterToolCallHook({ toolName: i, toolCallId: l, runId: e.hookContext?.runId, agentId: e.hookContext?.agentId, sessionId: e.hookContext?.sessionId, sessionKey: e.hookContext?.sessionKey, channelId: e.hookContext?.channelId, startArgs: d, result: n, error: r, startedAt: u }).catch(() => {}); try { e.onToolCallResult?.({ toolName: i, args: d, ...t }); } catch {} }; try { const n = s.prepareBeforeToolCallParams ? await s.prepareBeforeToolCallParams(o, { toolCallId: l, hookContext: e.hookContext, signal: e.signal }) : o; d = n; const r = await runBeforeToolCallHook({ toolName: i, params: n, toolCallId: l, ctx: e.hookContext, signal: e.signal }); if (r.blocked) { const e = r.kind === "failure" ? r.disposition : "blocked"; reportToolCallResult(e === "blocked" ? { outcome: e, deniedReason: r.deniedReason ?? "plugin-before-tool-call" } : { outcome: e }, r.reason, r.reason); return toolError(r.reason); } const a = s.finalizeBeforeToolCallParams?.(r.params, n) ?? r.params; d = a; try { e.onToolCallPrepared?.({ toolName: i, args: d }); } catch {} if (e.authorizeToolCall && !e.authorizeToolCall()) { reportToolCallResult({ outcome: "blocked", deniedReason: "client-grant-revoked" }, void 0, "Tool call authorization expired"); return toolError("Tool call authorization expired"); } c(a); let u; try { const { authorizeToolCall: t } = e; u = await runWithSessionMcpToolCallAuthority(t && (() => { if (!t()) throw new Error("Tool call authorization expired"); }), () => s.execute(l, a, e.signal)); } catch (t) { throw s.resultContentSource === "network" ? protectNetworkToolExecutionError(t, "tool execution failed", e.signal) : t; } const f = resolveToolResultFailureKind(u); reportToolCallResult(f === "blocked" ? { outcome: "blocked", deniedReason: "tool_result_blocked" } : { outcome: f ?? "completed", result: u }, u, f ? extractToolErrorMessage(u) ?? "Tool execution failed" : void 0); return copyInternalToolResultState(u, jsonRpcResult(t, { content: normalizeToolCallContent(u), isError: f !== void 0 })); } catch (t) { const n = formatToolExecutionErrorMessage(t, "tool execution failed"); reportToolCallResult({ outcome: e.signal?.aborted ? "unknown" : resolveToolExecutionErrorKind(t), result: t }, t, n); return toolError(n || "tool execution failed"); } } default: return jsonRpcError(t, -32601, `Method not found: ${n}`); } } //#endregion export { handleMcpJsonRpc };