UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 5.29 kB
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as isAutomationsToolName}from"./automations-tool-name-CptnbJ9-.mjs";import{u as copyInternalToolResultState}from"./internal-hooks-Bn77tst6.mjs";import{a as resolveToolResultFailureKind}from"./tool-result-error-DAdEhHzf.mjs";import{f as runBeforeToolCallHook}from"./agent-tools.before-tool-call.wrapper-82hH05Yk.mjs";import{t as runAgentHarnessAfterToolCallHook}from"./hook-helpers-Dmbt-AJr.mjs";import{n as createGatewayToolPolicyAssertion}from"./gateway-tool-policy-B3gT1TWd.mjs";import{r as runWithSessionMcpToolCallAuthority}from"./agent-bundle-mcp-request-context-Cztgq5sC.mjs";import{i as resolveToolExecutionErrorKind,r as protectNetworkToolExecutionError,t as formatToolExecutionErrorMessage}from"./tool-execution-error-C60NwMfa.mjs";import"./agent-tools.before-tool-call-BkUHN8cH.mjs";import{i as extractToolErrorMessage}from"./embedded-agent-tool-results-BPxGp984.mjs";import{n as readMcpLoopbackToolName}from"./mcp-http.schema-BA-97xdx.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-k9GBgltP.mjs";import crypto from"node:crypto";import{ContentBlockSchema}from"@modelcontextprotocol/core"; //!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)}]}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}`)}}export{handleMcpJsonRpc};