openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 6.86 kB
JavaScript
import{l as isRecord}from"../../record-coerce-BTbqdJ3-.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import{t as definePluginEntry}from"../../plugin-entry-DhKiQ4Uu.mjs";import{l as safeError,n as RelayError}from"../../protocol-Cfda5t_C.mjs";import{i as relayPrincipalForDisplay,r as relayCaller,t as consentAuthority}from"../../caller-C9nJQXfs.mjs";
//!extensions/mcp-relay/openclaw.plugin.json
var configSchema={"type":`object`,"additionalProperties":false,"properties":{"relayUrl":{"type":`string`,"default":`https://mcp.openclaw.ai`,"pattern":`^(?:https://[^\\s/?#@\\\\]+|http://(?:localhost|127\\.0\\.0\\.1)(?::[0-9]+)?)/?$`},"agentId":{"type":`string`,"minLength":1}}};
//!extensions/mcp-relay/src/config.ts
const DEFAULT_RELAY_URL=`https://mcp.openclaw.ai`;function parseMcpRelayConfig(e){const t=e===void 0?{}:e;if(!t||typeof t!==`object`||Array.isArray(t))throw new Error(`MCP relay config must be an object.`);if(Object.keys(t).some(e=>e!==`relayUrl`&&e!==`agentId`))throw new Error(`MCP relay config supports only relayUrl and agentId.`);const n=`relayUrl`in t?t.relayUrl:DEFAULT_RELAY_URL;if(typeof n!==`string`||!new RegExp(configSchema.properties.relayUrl.pattern).test(n))throw new Error(`relayUrl must be an HTTPS origin without credentials, a path, query, or fragment; use HTTP only with localhost or 127.0.0.1 for development.`);let r;try{r=new URL(n)}catch{throw new Error(`relayUrl must be a valid relay origin. Check its hostname and port.`)}if(r.pathname!==`/`||r.username||r.password||r.search||r.hash)throw new Error(`relayUrl must contain only the relay origin. Remove credentials and paths.`);const i=`agentId`in t?t.agentId:void 0;if(i!==void 0&&(typeof i!==`string`||!i.trim()))throw new Error(`agentId must be a nonempty agent ID. Omit it to use the Gateway default.`);return{relayUrl:r.origin,...i===void 0?{}:{agentId:i}}}const mcpRelayConfigSchema={jsonSchema:configSchema,safeParse(e){try{return{success:true,data:parseMcpRelayConfig(e)}}catch(e){return{success:false,error:{issues:[{path:[],message:e instanceof Error?e.message:`Invalid MCP relay config.`}]}}}}};
//!extensions/mcp-relay/src/gateway-methods.ts
function registerMcpRelayGatewayMethods(e,t){for(const n of[`status`,`pair`,`grants`,`revoke`,`authorize.describe`,`authorize.approve`,`authorize.deny`])e.registerGatewayMethod(`mcp-relay.${n}`,async({params:r,client:i,respond:a,signal:o,hasCurrentClientAuthority:s})=>{const assertCurrent=()=>{o?.throwIfAborted();if(!s?.())throw new RelayError(`unavailable`,`Gateway authorization ended. Reconnect and retry the command.`)};try{assertCurrent();const o=t();if(!o)throw new RelayError(`unavailable`,`MCP relay is not running. Enable mcp-relay and restart the Gateway.`);const s=n===`revoke`?[`grantId`]:n===`pair`?[`ceiling`]:n.startsWith(`authorize.`)?[`requestId`,...n===`authorize.approve`?[`ceiling`]:[]]:[];if(!isRecord(r)||Object.keys(r).some(e=>!s.includes(e)))throw new RelayError(`invalid_params`,`Use the Connected apps controls or the mcp-relay CLI commands.`);let c;if(n===`status`)c=await o.status();else{const t=relayCaller(i,e.runtime.config.current());if(n===`grants`)c=await o.grants(t);else if(n===`revoke`){if(typeof r.grantId!==`string`||!r.grantId||r.grantId.length>200)throw new RelayError(`invalid_params`,`Choose a connected app to revoke.`);const{grants:e}=await o.grants(t);if(!e.some(e=>e.grantId===r.grantId))throw new RelayError(`not_found`,`Connected app not found. Refresh the list and choose one of your apps.`);c=await o.revoke(r.grantId,assertCurrent)}else if(n===`pair`)c=await o.pair(assertCurrent,consentAuthority(t,r.ceiling));else{if(typeof r.requestId!==`string`||!/^[A-Za-z0-9_-]{43}$/.test(r.requestId))throw new RelayError(`invalid_params`,`This connection link is invalid. Start connecting again.`);if(n===`authorize.describe`)c={...await o.describeConsent(r.requestId,assertCurrent),caller:{...t,principal:relayPrincipalForDisplay(t.principal)}};else if(n===`authorize.approve`)c=await o.approveConsent(r.requestId,consentAuthority(t,r.ceiling),assertCurrent);else c=await o.denyConsent(r.requestId,assertCurrent)}}assertCurrent();a(true,c)}catch(e){const t=safeError(e);a(false,void 0,{code:t.code===`invalid_params`?`INVALID_REQUEST`:`UNAVAILABLE`,message:t.message,details:{code:t.code}})}},{scope:n===`status`||n===`grants`||n===`authorize.describe`?`operator.read`:`operator.write`})}function registerMcpRelayConnectRoute(e,t){const n=e.config.gateway?.controlUi?.basePath?.trim().replace(/^\/+|\/+$/gu,``);const r=n?`/${n}`:``;for(const n of/* @__PURE__ */ new Set([`/mcp-relay/connect`,`${r}/mcp-relay/connect`]))e.registerHttpRoute({path:n,auth:`plugin`,match:`exact`,handler(e,n){const i=new URL(e.url??`/`,`http://gateway.invalid`);const a=i.searchParams.get(`request`);const o=i.searchParams.get(`relay`);n.setHeader(`Cache-Control`,`no-store`);n.setHeader(`Referrer-Policy`,`no-referrer`);if(e.method!==`GET`&&e.method!==`HEAD`||!a||!/^[A-Za-z0-9_-]{43}$/.test(a)||o!==null&&o!==t){n.statusCode=400;n.end(`Invalid connection link. Start connecting again from your app.`);return}const s=new URLSearchParams({plugin:`mcp-relay`,id:`connected-apps`,"p.request":a});n.statusCode=303;n.setHeader(`Location`,`${r}/plugin?${s}`);n.end()}})}
//!extensions/mcp-relay/index.ts
var mcp_relay_default=definePluginEntry({id:`mcp-relay`,name:`MCP Relay`,description:`Connect remote MCP clients to this Gateway through an outbound relay`,configSchema:mcpRelayConfigSchema,register(e){let t;e.registerCli(async e=>{const{registerMcpRelayCli:t}=await import(`../../cli-B0pavt5Q.mjs`);await t(e)},{descriptors:[{name:`mcp-relay`,description:`Inspect the MCP relay connection and manage client grants`,hasSubcommands:true}]});registerMcpRelayGatewayMethods(e,()=>t);registerMcpRelayConnectRoute(e,parseMcpRelayConfig(e.pluginConfig).relayUrl);e.session.controls.registerControlUiDescriptor({surface:`tab`,id:`connected-apps`,slug:`connected-apps`,label:`Connected apps`,icon:`plug`,group:`control`,placement:`settings`,requiredScopes:[`operator.read`]});e.registerService({id:`mcp-relay`,apiVersion:2,async start(n){const{RelayState:r}=await import(`../../state-Cv3m0h9N.mjs`);const{RelayService:i}=await import(`../../service-B1d4kcXE.mjs`);const{createOperations:a}=await import(`../../operations-fLnsiapp.mjs`);const o=parseMcpRelayConfig(e.pluginConfig);const s=n.scheduler;const c=new r(e.runtime,o.relayUrl,()=>s.signal.throwIfAborted());const l=await c.initialize();s.signal.throwIfAborted();const u={name:`OpenClaw`,version:e.runtime.version};t=new i({scheduler:s,state:c,identity:l,relayUrl:o.relayUrl,gateway:u,controlUiIngress:n.controlUiIngress,config:()=>e.runtime.config.current(),operations:a({logger:e.logger,gateway:u,agentId:o.agentId})});await t.start()},async stop(){const e=t;t=void 0;await e?.stop()}})}});export{mcp_relay_default as default};