openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
12 lines • 34.2 kB
JavaScript
import{m as readNonBlankString,o as normalizeLowercaseStringOrEmpty,p as normalizeStringifiedOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{d as asPositiveFiniteNumber,w as parseStrictFiniteNumber}from"./number-coercion-B3CfI447.mjs";import"./src-0ci69Prg.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{r as asNullableRecord}from"./record-coerce-BTbqdJ3-.mjs";import{o as normalizeCsvOrLooseStringList}from"./string-normalization-D_oBUpO3.mjs";import{r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{r as terminalText}from"./safe-text-B_QTgn0s.mjs";import{a as scanEnvTemplateTokens,r as renderEnvTemplateToken}from"./env-substitution-CbEfgBpH.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as createLazyRuntimeMethod}from"./lazy-runtime-Ds6M7vp4.mjs";import{i as resolveEnvironmentValue}from"./process-env-BMQKxoSL.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{p as safeStat,r as executableFileExists}from"./path-existence-BR9MXlgL.mjs";import{n as resolveMcpTransportConfig}from"./mcp-transport-config-BYp4GLEU.mjs";import{t as runTasksWithConcurrency}from"./run-with-concurrency-BX7H2nwl.mjs";import{t as startOAuthLoopbackCallbackServer}from"./oauth-loopback-callback-BPgd4XrV.mjs";import{r as formatCliJsonFailure}from"./failure-output-Gn9zHEk3.mjs";import{n as requestExitAfterOneShotOutput,t as exitCliAfterOutput}from"./one-shot-exit-LLy48Ehj.mjs";import{t as runWithLocalStateOwner}from"./local-state-owner-fjzTarAw.mjs";import{t as parseConfigValue}from"./config-value-DxtqKUFI.mjs";import{t as applyParentDefaultHelpAction}from"./parent-default-help-BQhbR5_q.mjs";import{i as operatorMcpOAuthIdentity}from"./mcp-oauth-identity-DSHLyzOx.mjs";import{u as readMcpOAuthStoreReadOnly}from"./mcp-oauth-store-BHRXeHZp.mjs";import{a as completeMcpOAuthAuthorization,c as readMcpOAuthCredentialsStatus,f as startMcpOAuthAuthorization,n as clearMcpOAuthCredentials,s as countMcpOAuthPrincipals}from"./mcp-oauth-Df1IQZXw.mjs";import{a as updateConfiguredMcpServerTools,c as mcpConfigInternal,i as updateConfiguredMcpServer,l as redactMcpServersForDisplay,n as setConfiguredMcpServer,r as unsetConfiguredMcpServer,s as listConfiguredMcpServers}from"./mcp-config-mutation-QKXJnupf.mjs";import{t as resolveGatewayAuthOptions}from"./gateway-secret-options-UPUoON4Q.mjs";import{t as collectOption}from"./helpers-C9M4s1yb.mjs";import{t as parseKeyValueEntries}from"./parse-key-value-entries-DXfhxUNi.mjs";import{t as bindConfigOwner}from"./config-cli-owner-patch-B6C3tH2T.mjs";import path from"node:path";import{Command}from"commander";
//!src/cli/mcp-cli-oauth.ts
const MCP_OAUTH_CALLBACK_TIMEOUT_MS=3e5;function registerMcpLoginCommand(e,t){e.command(`login`).description(`Authorize an OAuth MCP server`).argument(`<name>`,`MCP server name`).option(`--code <code>`,`Authorization code from the OAuth redirect`).option(`--issuer <iss>`,`Exact iss value from the same OAuth redirect (with --code)`).action(t)}async function loginMcpServer(e){const{name:t,server:n,code:r,issuer:i,owner:a,fail:o}=e;if(i!==void 0&&!r)return o(`--issuer requires --code from the same OAuth callback.`);if(asNullableRecord(n.oauth)?.identity===`per-requester`)return o(`MCP server "${t}" uses per-requester OAuth. Senders connect from the channel via the MCP connect flow.`);if(n.auth!==`oauth`)return o(`MCP server "${t}" is not configured with auth: "oauth".`);if(typeof n.url!==`string`||n.url.trim().length===0)return o(`MCP server "${t}" needs a URL for OAuth login.`);const s=resolveMcpTransportConfig(t,n);if(!s||s.kind!==`http`)return o(`MCP server "${t}" needs a valid HTTP transport for OAuth login.`);const c=operatorMcpOAuthIdentity(t,s.url);if(r){a.assertCurrent();await completeMcpOAuthAuthorization(c,s,{code:r,...i===void 0?{}:{iss:i}});defaultRuntime.log(`MCP OAuth credentials saved for "${t}".`);return}let l;const u=formatCliCommand(`openclaw mcp login ${t} --code <code>`);try{a.assertCurrent();const e=await startMcpOAuthAuthorization(c,s,{});a.assertCurrent();if(e.status===`authorized`){defaultRuntime.log(`MCP OAuth credentials saved for "${t}".`);return}if(e.state.length>=16)try{l=await startOAuthLoopbackCallbackServer({redirectUrl:e.redirectUrl,expectedState:e.state,timeoutMs:MCP_OAUTH_CALLBACK_TIMEOUT_MS,signal:a.signal})}catch(e){defaultRuntime.log(`Could not start the local OAuth callback (${formatErrorMessage(e)}).`)}defaultRuntime.log(`Open this URL to authorize "${t}":`);defaultRuntime.log(e.authorizationUrl);if(l){defaultRuntime.log(`Waiting for the browser to return to OpenClaw...`);defaultRuntime.log(`If the callback cannot reach this terminal, cancel this attempt, then run ${u}.`)}else defaultRuntime.log(`After approval, run ${u}.`);defaultRuntime.log(`If the callback URL includes iss, pass its exact value with --issuer <iss> when completing login manually.`);if(!l)return;let n;try{n=await l.waitForCallback()}catch(e){return o(`${formatErrorMessage(e)}. Complete login manually with ${u}.`)}if(n.type===`oauth_error`)return o(`OAuth authorization did not complete. Retry login or use ${u}.`);if(n.parameters.getAll(`iss`).length>1)return o(`OAuth callback includes multiple issuer values. Retry login.`);const r=n.parameters.get(`iss`);a.assertCurrent();await completeMcpOAuthAuthorization(c,s,{code:n.code,...r===null?{}:{iss:r}});defaultRuntime.log(`MCP OAuth credentials saved for "${t}".`)}finally{await l?.close()}}
//!src/cli/mcp-cli-probe.ts
const createSessionMcpRuntime=createLazyRuntimeMethod(()=>import(`./agents/agent-bundle-mcp-runtime.js`),e=>e.createSessionMcpRuntime);const MCP_CODEX_APPROVAL_ANNOTATION_HINT=`tools have no safety annotations; calls require approval in prompting session postures`;async function readMcpProbeResult(e){const{buildBundleMcpToolsFromCatalog:t}=await import(`./agents/agent-bundle-mcp-materialize.js`);const n=await e.getCatalog();const r=t({catalog:n});return{generatedAt:new Date(n.generatedAt).toISOString(),servers:Object.fromEntries(Object.entries(n.servers).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>{const r=t.codexApprovalMode??`auto`;const i=n.tools.filter(t=>t.serverName===e);const a=r===`auto`&&i.length>0&&i.every(e=>Object.keys(e.codexAnnotations??{}).length===0)?MCP_CODEX_APPROVAL_ANNOTATION_HINT:void 0;return[e,{launch:t.launchSummary,tools:t.toolCount,codexApprovalMode:r,...a?{approvalHint:a}:{},...t.requestTimeoutMs?{requestTimeoutMs:t.requestTimeoutMs}:{},...t.supportsParallelToolCalls?{supportsParallelToolCalls:t.supportsParallelToolCalls}:{},...t.tools?.filteredCount?{filteredTools:t.tools.filteredCount}:{},...t.resources?{resources:true}:{},...t.prompts?{prompts:true}:{},...t.tools?.listChanged||t.resources?.listChanged||t.prompts?.listChanged?{listChanged:{tools:t.tools?.listChanged===true,resources:t.resources?.listChanged===true,prompts:t.prompts?.listChanged===true}}:{}}]})),tools:r.map(e=>e.name).toSorted(),diagnostics:n.diagnostics??[]}}async function probeMcpServers(e,t,n){const{recoverMcpDockerServers:r}=await import(`./mcp-docker-recovery-BmGWl2S4.mjs`);await r(Object.values(n));const i=await createSessionMcpRuntime({sessionId:e,workspaceDir:process.cwd(),cfg:{...t,mcp:{...t.mcp,servers:n}},manifestRegistry:{plugins:[]}});let a;let o;try{a=await readMcpProbeResult(i)}finally{try{await i.dispose();await i.joinCleanup?.()}catch(e){o=`${formatErrorMessage(e)}. Rerun this command; if local cleanup still fails, restart the process that owns the MCP connection.`}}return{...a,...o?{cleanupError:o}:{}}}function resolveMcpProbeIssue(e){let t;if(e.result.diagnostics.length>0){const n=expectDefined(e.result.diagnostics[0],`diagnostics entry at 0`);t=`MCP check failed for "${n.serverName}" in ${e.path}: ${n.message}`}else for(const[n,r]of Object.entries(e.servers))if(r.enabled!==false&&!e.result.servers[n]){t=`MCP check did not connect to "${n}" in ${e.path}.`;break}const n=e.result.cleanupError?`MCP cleanup failed in ${e.path}: ${e.result.cleanupError}`:void 0;return[t,n].filter(e=>e!==void 0)}function formatMcpProbeIssues(e){return e.map(e=>terminalText`${e}`).join(`
`)}const DEFAULT_MCP_PROBE_INITIALIZE_TIMEOUT_MS=5e3;async function probeMcpServersOrFail(e){const t=Object.fromEntries(Object.entries(e.servers).map(([e,t])=>[e,asPositiveFiniteNumber(t.connectionTimeoutMs)!==void 0?t:{...t,connectionTimeoutMs:DEFAULT_MCP_PROBE_INITIALIZE_TIMEOUT_MS}]));const n=resolveMcpProbeIssue({result:await probeMcpServers(`openclaw-cli-mcp-probe`,e.config,t),servers:e.servers,path:e.path});if(n.length>0){defaultRuntime.error(formatMcpProbeIssues([...n,`Configuration was not saved.`]));exitCliAfterOutput(defaultRuntime,1)}}
//!src/cli/mcp-cli-serve-options.ts
function isClaudeChannelMode(e){return e===`auto`||e===`on`||e===`off`}function resolveMcpServeOptions(e){const{gatewayToken:t,gatewayPassword:n}=resolveGatewayAuthOptions(e);const r=normalizeLowercaseStringOrEmpty(normalizeStringifiedOptionalString(e.claudeChannelMode)??`auto`);if(!isClaudeChannelMode(r))throw new Error(`Invalid --claude-channel-mode value. Use "auto", "on", or "off".`);return{gatewayUrl:typeof e.url===`string`?e.url:void 0,gatewayToken:t,gatewayPassword:n,claudeChannelMode:r,verbose:Boolean(e.verbose)}}
//!src/cli/mcp-cli-state-owner.ts
function offlineMcpAction(e,t,n){return(...r)=>runWithLocalStateOwner({method:`mcp.${e}`,params:{},target:`MCP credentials and configuration`,onForeignOwner:`refuse`,...n?{onlineAlternative:n}:{},runLocal:e=>t(e,...r)})}function mcpConfigMutation(e,t,n){return r=>runWithLocalStateOwner({method:`mcp.${e}`,params:{},target:`MCP configuration`,onForeignOwner:async({env:e,requestOwner:t})=>{return n({...r,commit:await bindConfigOwner(t,e)})},runLocal:()=>t(r)})}const setMcpServer=mcpConfigMutation(`set`,setConfiguredMcpServer,mcpConfigInternal.set);const unsetMcpServer=mcpConfigMutation(`unset`,unsetConfiguredMcpServer,mcpConfigInternal.unset);const configureMcpServer=mcpConfigMutation(`configure`,updateConfiguredMcpServer,mcpConfigInternal.update);const updateMcpTools=mcpConfigMutation(`tools`,updateConfiguredMcpServerTools,mcpConfigInternal.updateTools);
//!src/cli/mcp-cli.ts
const disposeAllSessionMcpRuntimes=createLazyRuntimeMethod(()=>import(`./agents/agent-bundle-mcp-manager-api.js`),e=>e.disposeAllSessionMcpRuntimes);const PROBE_ONLINE_ALTERNATIVE=`Probing a server needs the Gateway stopped. Save without probing (mcp add --no-probe, or mcp configure without --probe) to use the running Gateway.`;function fail(e,t){if(t)defaultRuntime.writeJson(formatCliJsonFailure(e));else defaultRuntime.error(terminalText`${e}`);exitCliAfterOutput(defaultRuntime,1)}async function loadMcpConfig(e){const t=await listConfiguredMcpServers();if(!t.ok)fail(t.error,e?.json);return t}function failUnknownMcpServer(e,t,n){fail(`No MCP server named "${e}" in ${t}. Run ${formatCliCommand(`openclaw mcp list`)} to see configured servers.`,n?.json)}function requireMcpServer(e,t,n){const r=e.mcpServers[t];if(!r)failUnknownMcpServer(t,e.path,n);return r}function selectMcpServers(e,t,n){return t?{[t]:requireMcpServer(e,t,n)}:e.mcpServers}function applyMcpConfigureControls(e,t){const n={...e};if(t.enable)delete n.enabled;if(t.disable)n.enabled=false;applyMcpServerControls(n,t);applyMcpHttpControls(n,t);return n}function parseCsvList(e){const t=normalizeCsvOrLooseStringList(e);return t.length>0?t:void 0}function setOptionalField(e,t,n){if(n!==void 0)e[t]=n}function applyMcpServerControls(e,t){const n=parseCsvList(t.include);const r=parseCsvList(t.exclude);if(t.clearTools)delete e.toolFilter;else if(n||r)e.toolFilter={...asNullableRecord(e.toolFilter),...n?{include:n}:{},...r?{exclude:r}:{}};if(t.clearTimeouts){delete e.requestTimeoutMs;delete e.connectionTimeoutMs}for(const[n,r,i]of[[`timeout`,`requestTimeoutMs`,`--timeout`],[`connectTimeout`,`connectionTimeoutMs`,`--connect-timeout`]]){const a=t[n];if(a===void 0)continue;const o=parseStrictFiniteNumber(a);if(o===void 0||o<=0)fail(`${i} must be a positive number.`);e[r]=o*1e3}if(t.parallel===true)e.supportsParallelToolCalls=true;else if(t.parallel===false){delete e.supportsParallelToolCalls;delete e.supports_parallel_tool_calls}const i=t.approval;if(i!==void 0){const t=normalizeLowercaseStringOrEmpty(i);if(t!==`auto`&&t!==`prompt`&&t!==`approve`)fail(`--approval must be "auto", "prompt", or "approve".`);e.codex={...asNullableRecord(e.codex),defaultToolsApprovalMode:t}}}function applyMcpHttpControls(e,t){if(t.clearAuth){delete e.auth;delete e.oauth}const n=normalizeLowercaseStringOrEmpty(normalizeStringifiedOptionalString(t.auth)??``);if(n&&n!==`oauth`)fail(`Invalid --auth value. Use "oauth".`);if(n)e.auth=n;const r={};for(const[e,n]of[[`scope`,t.oauthScope],[`redirectUrl`,t.oauthRedirectUrl],[`clientMetadataUrl`,t.oauthClientMetadataUrl]]){const t=n?.trim();if(t)r[e]=t}if(Object.keys(r).length>0)e.oauth={...asNullableRecord(e.oauth),...r};if(t.clearTls)for(const t of[`sslVerify`,`ssl_verify`,`clientCert`,`client_cert`,`clientKey`,`client_key`])delete e[t];if(t.sslVerify!==void 0){const n=normalizeLowercaseStringOrEmpty(t.sslVerify);if(n!==`true`&&n!==`false`)fail(`--ssl-verify must be true or false.`);e.sslVerify=n===`true`}setOptionalField(e,`clientCert`,readNonBlankString(t.clientCert));setOptionalField(e,`clientKey`,readNonBlankString(t.clientKey))}const MCP_DOCTOR_CONCURRENCY=4;const SENSITIVE_HEADER_NAMES=/* @__PURE__ */ new Set([`authorization`,`proxy-authorization`,`x-api-key`,`api-key`,`api_key`]);const SENSITIVE_KEY_PATTERN=/(?:^|[_-])(api[_-]?key|authorization|bearer|password|secret|token)$/i;function issue(e,t){return{level:e,message:t}}function hasSensitiveKey(e){return SENSITIVE_HEADER_NAMES.has(e.trim().toLowerCase())||SENSITIVE_KEY_PATTERN.test(e)}function hasLiteralSensitiveValue(e){if(typeof e!==`string`||!e.trim())return false;const t=scanEnvTemplateTokens(e);let n=e;for(const e of t){if(e.kind===`escaped`||e.defaultValue?.trim())return true;n=n.replaceAll(renderEnvTemplateToken(e),``)}return t.length===0||n.trim().length>0&&!/^(Bearer|Basic)$/i.test(n.trim())}function resolveConfiguredPath(e,t){if(path.isAbsolute(e))return e;const n=typeof t===`string`&&t.trim()?t.trim():process.cwd();return path.resolve(n,e)}function executableCandidates(e){if(process.platform!==`win32`)return[e];const t=(process.env.PATHEXT??`.EXE;.CMD;.BAT;.COM`).split(`;`).map(e=>e.trim()).filter(Boolean);if(path.extname(e))return[e];return[e,...t.map(t=>`${e}${t.toLowerCase()}`)]}async function commandExists(e,t,n){if(path.isAbsolute(e)||e.includes(`/`)||e.includes(`\\`))return executableFileExists(resolveConfiguredPath(e,t));const r=((process.platform===`win32`?resolveEnvironmentValue(n,`PATH`):n?.PATH)??process.env.PATH??``).split(path.delimiter).map(e=>e.trim()||`.`);for(const n of r){const r=path.isAbsolute(n)?n:resolveConfiguredPath(n,t);for(const t of executableCandidates(e))if(await executableFileExists(path.join(r,t)))return true}return false}async function collectMcpDoctorIssues(e){const t=[];const{name:n,server:r}=e;const i=resolveMcpTransportConfig(n,r);const a=r.enabled===false;if(a)t.push(issue(`warning`,`server is disabled`));if(!a){if(!i)t.push(issue(`error`,`server transport is invalid`));if(i?.kind===`stdio`){if(!await commandExists(i.command,i.cwd,i.env))t.push(issue(`error`,`stdio command not found or not executable: ${i.command}`));if(i.cwd&&!(await safeStat(i.cwd))?.isDirectory())t.push(issue(`error`,`stdio cwd does not exist: ${i.cwd}`))}if(i?.kind===`http`){if(r.auth===`oauth`){if(asNullableRecord(r.oauth)?.identity!==`per-requester`){const e=await readMcpOAuthCredentialsStatus(operatorMcpOAuthIdentity(n,i.url));if(e.state!==`authorized`){const r=e.state===`requires-authorization`?`require additional authorization`:`are not authorized`;t.push(issue(`warning`,`OAuth credentials ${r}; run ${formatCliCommand(`openclaw mcp login ${n}`)}`))}}const e=asNullableRecord(r.headers);if(e&&Object.keys(e).some(e=>e.toLowerCase()===`authorization`))t.push(issue(`warning`,`OAuth is enabled and the static Authorization header is ignored`))}if(i.sslVerify===false)t.push(issue(`warning`,`TLS certificate verification is disabled`));for(const[e,n]of[[i.clientCert,`client certificate`],[i.clientKey,`client key`]])if(e&&!(await safeStat(resolveConfiguredPath(e,``)))?.isFile())t.push(issue(`error`,`${n} file does not exist: ${e}`))}}for(const[n,r]of[[`headers`,asNullableRecord(e.authoredServer?.headers)],[`env`,asNullableRecord(e.authoredServer?.env)]])for(const[e,i]of Object.entries(r??{}))if(hasSensitiveKey(e)&&hasLiteralSensitiveValue(i))t.push(issue(`warning`,`${n}.${e} contains a literal sensitive value; prefer an environment-backed value outside committed config`));const o=asNullableRecord(r.toolFilter);if(o&&!Array.isArray(o.include)&&!Array.isArray(o.exclude))t.push(issue(`warning`,`toolFilter is present but has no include or exclude list`));if(e.probe&&r.enabled!==false&&!t.some(e=>e.level===`error`))try{const i=await probeMcpServers(`openclaw-cli-mcp-doctor`,e.config,{[n]:r});const a=i.diagnostics[0];if(a)t.push(issue(`error`,`check failed: ${a.message}`));else{const e=i.servers[n];if(!e)t.push(issue(`error`,`check did not connect to this server`));else if(e.approvalHint)t.push(issue(`info`,`Codex approval mode: ${e.codexApprovalMode}; ${e.approvalHint}`))}if(i.cleanupError)t.push(issue(`error`,`cleanup failed: ${i.cleanupError}`))}catch(e){t.push(issue(`error`,`check failed: ${formatErrorMessage(e)}`))}return t}async function countConnectedMcpPrincipals(e,t){const n=resolveMcpTransportConfig(e,t);if(t.auth!==`oauth`||n?.kind!==`http`||asNullableRecord(t.oauth)?.identity!==`per-requester`)return;return countMcpOAuthPrincipals(operatorMcpOAuthIdentity(e,n.url))}async function buildMcpStatusEntries(e){const t=Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t));return Promise.all(t.map(async([e,t])=>{const n=resolveMcpTransportConfig(e,t);const r=t.enabled!==false;const i={name:e,configured:true,enabled:r,ok:r&&Boolean(n),transport:n?.transportType,launch:n?.description,requestTimeoutMs:n?.requestTimeoutMs,connectionTimeoutMs:n?.connectionTimeoutMs,supportsParallelToolCalls:n?.supportsParallelToolCalls,toolFilter:t.toolFilter,codex:t.codex};if(t.auth)i.auth=t.auth;if(t.auth===`oauth`&&n?.kind===`http`&&asNullableRecord(t.oauth)?.identity!==`per-requester`){const t=operatorMcpOAuthIdentity(e,n.url);const r=await readMcpOAuthStoreReadOnly(t.storeKey);i.authStatus={hasTokens:Boolean(r.tokens),requiresAuthorization:r.pendingAuthorizationChallenge?.requiresAuthorization===true,hasClientInformation:Boolean(r.clientInformation),hasCodeVerifier:Boolean(r.codeVerifier),hasDiscoveryState:Boolean(r.discoveryState),hasLastAuthorizationUrl:Boolean(r.lastAuthorizationUrl),...await readMcpOAuthCredentialsStatus(t,r)}}else i.connectedPrincipals=await countConnectedMcpPrincipals(e,t);return i}))}const OPENCLAW_MCP_REGISTRY_SCOPE_NOTE=`Note: this command only shows OpenClaw-managed mcp.servers entries and does not include mcporter servers from config/mcporter.json.`;function registerMcpCli(e){const t=e.command(`mcp`).description(`Manage OpenClaw mcp.servers config and channel bridge`);t.command(`serve`).description(`Expose OpenClaw channels over MCP stdio`).option(`--url <url>`,`Gateway WebSocket URL (defaults to gateway.remote.url when configured)`).option(`--token <token>`,`Gateway token (if required)`).option(`--token-file <path>`,`Read gateway token from file`).option(`--password <password>`,`Gateway password (if required)`).option(`--password-file <path>`,`Read gateway password from file`).option(`--claude-channel-mode <mode>`,`Claude channel notification mode: auto, on, or off`,`auto`).option(`-v, --verbose`,`Verbose logging to stderr`,false).action(async e=>{let t;try{t=resolveMcpServeOptions(e)}catch(e){fail(formatErrorMessage(e))}try{const{serveOpenClawChannelMcp:e}=await import(`./channel-server-B6AbxVeB.mjs`);await e(t)}catch(e){const t=formatErrorMessage(e).replace(/\.+$/u,``);defaultRuntime.error(terminalText`MCP server failed to start: ${t}. Run ${formatCliCommand(`openclaw gateway status --deep --require-rpc`)} to inspect Gateway health.`);exitCliAfterOutput(defaultRuntime,1)}});t.command(`list`).description(`List OpenClaw-managed MCP servers from mcp.servers`).option(`--json`,`Print JSON`).action(async e=>{const t=await loadMcpConfig(e);if(e.json){defaultRuntime.writeJson(redactMcpServersForDisplay(t.mcpServers));return}const n=Object.entries(t.mcpServers).toSorted(([e],[t])=>e.localeCompare(t));if(n.length===0){defaultRuntime.log(terminalText`No OpenClaw-managed MCP servers configured in ${t.path}. Add one with ${formatCliCommand(`openclaw mcp set <name> '{"command":"uvx","args":["context7-mcp"]}'`)}.`);defaultRuntime.log(OPENCLAW_MCP_REGISTRY_SCOPE_NOTE);return}defaultRuntime.log(terminalText`OpenClaw-managed MCP servers (${t.path}):`);for(const[e,t]of n){const n=await countConnectedMcpPrincipals(e,t);const r=n===void 0?``:` (${n} connected principal${n===1?``:`s`})`;defaultRuntime.log(terminalText`- ${e}${r}`)}defaultRuntime.log(``);defaultRuntime.log(OPENCLAW_MCP_REGISTRY_SCOPE_NOTE)});t.command(`show`).description(`Show one OpenClaw-managed MCP server or the full mcp.servers config`).argument(`[name]`,`MCP server name`).option(`--json`,`Print JSON`).action(async(e,t)=>{const n=await loadMcpConfig(t);const r=redactMcpServersForDisplay(selectMcpServers(n,e,t));if(!t.json)defaultRuntime.log(e?terminalText`OpenClaw-managed MCP server "${e}" (${n.path}):`:terminalText`OpenClaw-managed MCP servers (${n.path}):`);defaultRuntime.writeJson(e?r[e]:r)});t.command(`status`).description(`Show configured MCP server transport status without connecting`).option(`-v, --verbose`,`Show transport, auth, timeout, and filter details`,false).option(`--json`,`Print JSON`).action(async e=>{const t=await loadMcpConfig(e);const n=await buildMcpStatusEntries(t.mcpServers);if(e.json){defaultRuntime.writeJson({path:t.path,servers:n});return}if(n.length===0){defaultRuntime.log(terminalText`No MCP servers configured in ${t.path}.`);return}defaultRuntime.log(terminalText`MCP server status (${t.path}):`);for(const t of n){const n=t.enabled?t.transport??`invalid`:`disabled`;const r=t.auth===`oauth`?` oauth`:``;const i=t.authStatus?.state===`requires-authorization`?` authorization-required`:t.authStatus?.state===`authorized`?` authorized`:``;const a=t.toolFilter?` tool-filtered`:``;const o=t.supportsParallelToolCalls?` parallel`:``;const s=t.connectedPrincipals===void 0?``:` ${t.connectedPrincipals}-principal${t.connectedPrincipals===1?``:`s`}-connected`;defaultRuntime.log(terminalText`- ${t.name}: ${n}${r}${i}${s}${a}${o}`);if(e.verbose){defaultRuntime.log(terminalText` launch: ${t.launch??`n/a`}`);defaultRuntime.log(terminalText` timeouts: connect=${t.connectionTimeoutMs??`n/a`}ms request=${t.requestTimeoutMs??`n/a`}ms`);if(t.auth===`oauth`)defaultRuntime.log(t.connectedPrincipals===void 0?terminalText` oauth: ${t.authStatus?.state??`unauthenticated`}`:terminalText` oauth: per-requester, connected principals: ${t.connectedPrincipals}`);if(t.toolFilter)defaultRuntime.log(terminalText` tools: ${JSON.stringify(t.toolFilter)}`)}}});t.command(`probe`).description(`Connect to configured MCP servers and list available capabilities`).argument(`[name]`,`MCP server name`).option(`--json`,`Print JSON`).action(offlineMcpAction(`probe`,async(e,t,n)=>{const r=await loadMcpConfig(n);const i=selectMcpServers(r,t,n);if(t&&r.mcpServers[t]?.enabled===false)fail(`MCP server "${t}" is disabled in ${r.path}. Run ${formatCliCommand(`openclaw mcp configure ${t} --enable`)} before checking it.`,n.json);if(!n.json&&Object.values(i).every(e=>e.enabled===false)){defaultRuntime.log(terminalText`No enabled MCP servers in ${r.path}. Add one with ${formatCliCommand(`openclaw mcp add <name> --command <command>`)} or enable one with ${formatCliCommand(`openclaw mcp configure <name> --enable`)}.`);return}const a=await probeMcpServers(`openclaw-cli-mcp-probe`,r.config,i);if(n.json)defaultRuntime.writeJson(a);else{defaultRuntime.log(terminalText`MCP check (${r.path}):`);for(const[e,t]of Object.entries(a.servers)){defaultRuntime.log(terminalText`- ${e}: ${t.tools} tools${t.resources?`, resources`:``}${t.prompts?`, prompts`:``}, Codex approval ${t.codexApprovalMode}`);if(t.approvalHint)defaultRuntime.log(terminalText` i ${t.approvalHint}`)}for(const e of a.diagnostics)defaultRuntime.log(terminalText`! ${e.serverName}: ${e.message}`);if(a.cleanupError)defaultRuntime.log(terminalText`! cleanup: ${a.cleanupError}`)}const o=resolveMcpProbeIssue({result:a,servers:i,path:r.path});if(o.length>0){defaultRuntime.error(formatMcpProbeIssues(o));if(!requestExitAfterOneShotOutput(defaultRuntime,1))exitCliAfterOutput(defaultRuntime,1)}}));t.command(`doctor`).description(`Check configured MCP servers for static setup problems`).argument(`[name]`,`MCP server name`).option(`--probe`,`Also connect to each checked server`,false).option(`--json`,`Print JSON`).action(async(e,t)=>{const run=async()=>{const n=await loadMcpConfig(t);const r=selectMcpServers(n,e,t);const i=Object.entries(r).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,r])=>async()=>{const i=await collectMcpDoctorIssues({name:e,server:r,authoredServer:n.authoredConfig?.mcp?.servers?.[e],config:n.config,probe:Boolean(t.probe)});return{name:e,ok:!i.some(e=>e.level===`error`),issues:i}});const{results:a,firstError:o,hasError:s}=await runTasksWithConcurrency({tasks:i,limit:MCP_DOCTOR_CONCURRENCY});if(s)throw o;const c=a.every(e=>e.ok);if(t.json){defaultRuntime.writeJson({path:n.path,ok:c,servers:a});if(!c)fail(`MCP doctor found errors.`);return}if(a.length===0){defaultRuntime.log(terminalText`No MCP servers configured in ${n.path}. Add one with ${formatCliCommand(`openclaw mcp add <name> --command <command>`)}.`);return}defaultRuntime.log(terminalText`MCP doctor (${n.path}):`);for(const e of a){defaultRuntime.log(terminalText`- ${e.name}: ${e.ok?`ok`:`issues`}`);for(const t of e.issues){const e=t.level===`error`?`!`:t.level===`warning`?`-`:`i`;defaultRuntime.log(terminalText` ${e} ${t.level}: ${t.message}`)}}if(!c)fail(`MCP doctor found errors.`)};if(t.probe)await offlineMcpAction(`doctor --probe`,run)();else await run()});t.command(`add`).description(`Add one MCP server from flags and check it before saving`).argument(`<name>`,`MCP server name`).option(`--command <command>`,`Stdio command to spawn`).option(`--arg <value>`,`Repeatable stdio argument`,collectOption,[]).option(`--env <key=value>`,`Repeatable stdio environment entry`,collectOption,[]).option(`--cwd <path>`,`Working directory for stdio server`).option(`--url <url>`,`HTTP MCP server URL`).option(`--transport <type>`,`HTTP transport: streamable-http or sse`).option(`--header <key=value>`,`Repeatable HTTP header`,collectOption,[]).option(`--auth <mode>`,`HTTP auth mode: oauth`).option(`--oauth-scope <scope>`,`OAuth scope`).option(`--oauth-redirect-url <url>`,`OAuth redirect URL`).option(`--oauth-client-metadata-url <url>`,`OAuth client metadata URL`).option(`--include <csv>`,`Comma-separated MCP tool names or '*' globs to expose`).option(`--exclude <csv>`,`Comma-separated MCP tool names or '*' globs to hide`).option(`--timeout <seconds>`,`Per-request timeout in seconds`).option(`--connect-timeout <seconds>`,`Connection timeout in seconds`).option(`--parallel`,`Mark this server safe for concurrent tool calls`).option(`--approval <mode>`,`Codex MCP tool approval mode: auto, prompt, or approve`).option(`--disabled`,`Save the server disabled`,false).option(`--ssl-verify <boolean>`,`Verify HTTPS certificates: true or false`).option(`--client-cert <path>`,`HTTP mutual TLS client certificate path`).option(`--client-key <path>`,`HTTP mutual TLS client key path`).option(`--no-probe`,`Save without connecting first`).action(async(e,t)=>{const n={};const r=readNonBlankString(t.command);const i=normalizeStringifiedOptionalString(t.url);if(r&&i)fail(`Specify either --command for stdio or --url for HTTP, not both.`);if(!r&&!i)fail(`Specify --command for stdio or --url for HTTP.`);if(r){n.command=r;if(t.arg&&t.arg.length>0)n.args=t.arg;setOptionalField(n,`env`,parseKeyValueEntries(t.env,`--env`,fail));setOptionalField(n,`cwd`,readNonBlankString(t.cwd))}if(i){n.url=i;setOptionalField(n,`transport`,normalizeStringifiedOptionalString(t.transport));setOptionalField(n,`headers`,parseKeyValueEntries(t.header,`--header`,fail));applyMcpHttpControls(n,t)}if(t.disabled)n.enabled=false;applyMcpServerControls(n,t);const a=t.probe!==false&&n.enabled!==false&&n.auth!==`oauth`;const save=async()=>{const t=await loadMcpConfig();const r=e.trim();if(r&&Object.hasOwn(t.mcpServers,r))fail(`MCP server ${JSON.stringify(r)} already exists.`);if(a)await probeMcpServersOrFail({config:t.config,path:t.path,servers:{[e]:n}});return setMcpServer({name:e,server:n,createOnly:true})};const o=a?await offlineMcpAction(`add`,save,PROBE_ONLINE_ALTERNATIVE)():await save();if(!o.ok)fail(o.error);defaultRuntime.log(terminalText`Saved MCP server "${e}" to ${o.path}.`);if(n.auth===`oauth`)defaultRuntime.log(terminalText`Run ${formatCliCommand(`openclaw mcp login ${e}`)} to authorize this MCP server.`)});t.command(`set`).description(`Set one OpenClaw-managed MCP server from a JSON object`).argument(`<name>`,`MCP server name`).argument(`<value>`,`JSON object, for example {"command":"uvx","args":["context7-mcp"]}`).action(async(e,t)=>{const n=parseConfigValue(t);if(n.error)fail(n.error);const r=await setMcpServer({name:e,server:n.value});if(!r.ok)fail(r.error);defaultRuntime.log(terminalText`Saved MCP server "${e}" to ${r.path}.`)});t.command(`tools`).description(`Update per-server MCP tool include/exclude filters`).argument(`<name>`,`MCP server name`).option(`--include <csv>`,`Comma-separated MCP tool names or '*' globs to expose`).option(`--exclude <csv>`,`Comma-separated MCP tool names or '*' globs to hide`).option(`--clear`,`Clear this server's MCP tool filter`,false).action(async(e,t)=>{if(!t.clear&&t.include===void 0&&t.exclude===void 0)fail(`Specify --include, --exclude, or --clear.`);const n=await updateMcpTools({name:e,tools:t.clear?null:{include:parseCsvList(t.include),exclude:parseCsvList(t.exclude)}});if(!n.ok)fail(n.error);if(!n.updated)failUnknownMcpServer(e,n.path);defaultRuntime.log(terminalText`Updated MCP tool selection for "${e}" in ${n.path}.`)});t.command(`configure`).description(`Update MCP server operator controls without replacing the server`).argument(`<name>`,`MCP server name`).option(`--enable`,`Enable this saved server`,false).option(`--disable`,`Disable this saved server`,false).option(`--include <csv>`,`Comma-separated MCP tool names or '*' globs to expose`).option(`--exclude <csv>`,`Comma-separated MCP tool names or '*' globs to hide`).option(`--clear-tools`,`Clear this server's MCP tool filter`,false).option(`--timeout <seconds>`,`Per-request timeout in seconds`).option(`--connect-timeout <seconds>`,`Connection timeout in seconds`).option(`--clear-timeouts`,`Clear request and connection timeout overrides`,false).option(`--parallel`,`Mark this server safe for concurrent tool calls`).option(`--no-parallel`,`Clear the concurrent tool-call marker`).option(`--approval <mode>`,`Codex MCP tool approval mode: auto, prompt, or approve`).option(`--auth <mode>`,`HTTP auth mode: oauth`).option(`--clear-auth`,`Clear auth and OAuth metadata`,false).option(`--oauth-scope <scope>`,`OAuth scope`).option(`--oauth-redirect-url <url>`,`OAuth redirect URL`).option(`--oauth-client-metadata-url <url>`,`OAuth client metadata URL`).option(`--ssl-verify <boolean>`,`Verify HTTPS certificates: true or false`).option(`--client-cert <path>`,`HTTP mutual TLS client certificate path`).option(`--client-key <path>`,`HTTP mutual TLS client key path`).option(`--clear-tls`,`Clear TLS verification and mTLS overrides`,false).option(`--probe`,`Check the updated server before saving`,false).action(async(e,t)=>{if(t.enable&&t.disable)fail(`Specify only one of --enable or --disable.`);const apply=async()=>{const n=await loadMcpConfig();const r=requireMcpServer(n,e);const i=applyMcpConfigureControls(r,t);if(t.probe&&i.enabled!==false&&i.auth!==`oauth`)await probeMcpServersOrFail({config:n.config,path:n.path,servers:{[e]:i}});if(t.enable&&Object.keys(i).length===0){const t=await unsetMcpServer({name:e,expectedServer:r});if(!t.ok)fail(t.error);defaultRuntime.log(terminalText`Removed disabled MCP override for "${e}" in ${t.path}.`);return}const a=await configureMcpServer({name:e,update:e=>applyMcpConfigureControls(e,t)});if(!a.ok)fail(a.error);if(!a.updated)failUnknownMcpServer(e,a.path);defaultRuntime.log(terminalText`Updated MCP server "${e}" in ${a.path}.`)};await(t.probe?offlineMcpAction(`configure`,apply,PROBE_ONLINE_ALTERNATIVE)():apply())});registerMcpLoginCommand(t,offlineMcpAction(`login`,async(e,t,n)=>{const r=requireMcpServer(await loadMcpConfig(),t);await loginMcpServer({name:t,server:r,code:n.code,issuer:n.issuer,owner:e,fail})}));t.command(`logout`).description(`Clear stored OAuth credentials for an MCP server`).argument(`<name>`,`MCP server name`).action(offlineMcpAction(`logout`,async(e,t)=>{const n=requireMcpServer(await loadMcpConfig(),t);if(asNullableRecord(n.oauth)?.identity===`per-requester`)fail(`MCP server "${t}" uses per-requester OAuth. Remove or replace the server to clear requester credentials.`);const r=resolveMcpTransportConfig(t,n);if(!r||r.kind!==`http`)fail(`MCP server "${t}" needs a valid HTTP transport for OAuth logout.`);await clearMcpOAuthCredentials(operatorMcpOAuthIdentity(t,r.url));defaultRuntime.log(terminalText`MCP OAuth credentials cleared for "${t}".`)}));t.command(`reload`).description(`Dispose cached MCP runtimes so new config is used on the next turn`).action(async()=>{await disposeAllSessionMcpRuntimes();defaultRuntime.log(`Disposed cached MCP runtimes. Active agents use new MCP config on their next runtime build.`)});t.command(`unset`).description(`Remove one OpenClaw-managed MCP server`).argument(`<name>`,`MCP server name`).action(async e=>{const t=await unsetMcpServer({name:e});if(!t.ok)fail(t.error);if(!t.removed)failUnknownMcpServer(e,t.path);defaultRuntime.log(terminalText`Removed MCP server "${e}" from ${t.path}.`)});applyParentDefaultHelpAction(t)}export{registerMcpCli};