-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathmcp-cli.ts
More file actions
1336 lines (1286 loc) · 46.1 KB
/
Copy pathmcp-cli.ts
File metadata and controls
1336 lines (1286 loc) · 46.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MCP CLI for configured servers, OAuth auth, diagnostics, and channel MCP serving.
import { constants as fsConstants } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import {
normalizeLowercaseStringOrEmpty,
normalizeStringifiedOptionalString,
} from "@openclaw/normalization-core/string-coerce";
import { Command } from "commander";
import { buildBundleMcpToolsFromCatalog } from "../agents/agent-bundle-mcp-materialize.js";
import { createSessionMcpRuntime } from "../agents/agent-bundle-mcp-runtime.js";
import {
buildMcpHttpFetch,
withoutMcpAuthorizationHeader,
withSameOriginMcpHttpHeaders,
} from "../agents/mcp-http-fetch.js";
import {
clearMcpOAuthCredentials,
readMcpOAuthCredentialsStatus,
runMcpOAuthLogin,
type McpOAuthCredentialsStatus,
} from "../agents/mcp-oauth.js";
import { resolveMcpTransportConfig } from "../agents/mcp-transport-config.js";
import { parseConfigValue } from "../auto-reply/reply/config-value.js";
import {
listConfiguredMcpServers,
setConfiguredMcpServer,
unsetConfiguredMcpServer,
updateConfiguredMcpServer,
updateConfiguredMcpServerTools,
} from "../config/mcp-config.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { formatErrorMessage } from "../infra/errors.js";
import { serveOpenClawChannelMcp } from "../mcp/channel-server.js";
import { defaultRuntime } from "../runtime.js";
import { formatCliCommand } from "./command-format.js";
import { resolveGatewayAuthOptions } from "./gateway-secret-options.js";
import { applyParentDefaultHelpAction } from "./program/parent-default-help.js";
function fail(message: string): never {
defaultRuntime.error(message);
defaultRuntime.exit(1);
throw new Error(message);
}
function printJson(value: unknown): void {
defaultRuntime.writeJson(value);
}
function parseCsvList(value: string | undefined): string[] | undefined {
if (!value) {
return undefined;
}
const entries = value
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
return entries.length > 0 ? entries : undefined;
}
function collectOption(value: string, previous: string[] = []): string[] {
return [...previous, value];
}
function parseKeyValueEntries(values: readonly string[] | undefined, label: string) {
const entries: Record<string, string> = {};
for (const raw of values ?? []) {
const separatorIndex = raw.indexOf("=");
if (separatorIndex <= 0) {
fail(`${label} entries must use KEY=VALUE.`);
}
const key = raw.slice(0, separatorIndex).trim();
const value = raw.slice(separatorIndex + 1);
if (!key) {
fail(`${label} entries must use a non-empty key.`);
}
entries[key] = value;
}
return Object.keys(entries).length > 0 ? entries : undefined;
}
function parsePositiveNumberOption(value: string | undefined, label: string): number | undefined {
if (value === undefined) {
return undefined;
}
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed <= 0) {
fail(`${label} must be a positive number.`);
}
return parsed;
}
function parseOAuthConfig(opts: {
scope?: string;
redirectUrl?: string;
clientMetadataUrl?: string;
}): Record<string, string> | undefined {
const oauth = {
...(normalizeStringifiedOptionalString(opts.scope) ? { scope: opts.scope!.trim() } : {}),
...(normalizeStringifiedOptionalString(opts.redirectUrl)
? { redirectUrl: opts.redirectUrl!.trim() }
: {}),
...(normalizeStringifiedOptionalString(opts.clientMetadataUrl)
? { clientMetadataUrl: opts.clientMetadataUrl!.trim() }
: {}),
};
return Object.keys(oauth).length > 0 ? oauth : undefined;
}
async function clearMcpOAuthCredentialsForConfiguredServer(
name: string,
server: unknown,
): Promise<void> {
const resolved = resolveMcpTransportConfig(name, server);
if (resolved?.kind === "http") {
await clearMcpOAuthCredentials({ serverName: name, serverUrl: resolved.url });
}
}
function hasOAuthAuth(server: unknown): boolean {
return (
typeof server === "object" && server !== null && "auth" in server && server.auth === "oauth"
);
}
async function clearStaleMcpOAuthCredentialsForReplacement(params: {
name: string;
previous: unknown;
next: unknown;
}): Promise<void> {
// Replacing an OAuth HTTP server should not leave credentials bound to the old URL.
if (!hasOAuthAuth(params.previous)) {
return;
}
const previousResolved = resolveMcpTransportConfig(params.name, params.previous);
if (previousResolved?.kind !== "http") {
return;
}
const nextResolved = hasOAuthAuth(params.next)
? resolveMcpTransportConfig(params.name, params.next)
: undefined;
if (nextResolved?.kind === "http" && nextResolved.url === previousResolved.url) {
return;
}
await clearMcpOAuthCredentials({
serverName: params.name,
serverUrl: previousResolved.url,
});
}
function setOptionalField(target: Record<string, unknown>, key: string, value: unknown): void {
if (value !== undefined) {
target[key] = value;
}
}
type McpStatusEntry = {
name: string;
configured: true;
enabled: boolean;
ok: boolean;
transport?: string;
launch?: string;
requestTimeoutMs?: number;
connectionTimeoutMs?: number;
supportsParallelToolCalls?: boolean;
auth?: unknown;
authStatus?: McpOAuthCredentialsStatus;
toolFilter?: unknown;
codex?: unknown;
};
type McpDoctorIssue = {
level: "error" | "warning" | "info";
message: string;
};
type McpDoctorServerResult = {
name: string;
ok: boolean;
issues: McpDoctorIssue[];
};
const SENSITIVE_HEADER_NAMES = 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 asRecord(value: unknown): Record<string, unknown> | null {
return typeof value === "object" && value !== null && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function issue(level: McpDoctorIssue["level"], message: string): McpDoctorIssue {
return { level, message };
}
function hasSensitiveKey(name: string): boolean {
return SENSITIVE_HEADER_NAMES.has(name.trim().toLowerCase()) || SENSITIVE_KEY_PATTERN.test(name);
}
function hasLiteralSensitiveValue(value: unknown): boolean {
return typeof value === "string" && value.trim().length > 0 && !value.trim().startsWith("$");
}
function resolveConfiguredPath(filePath: string, cwd: unknown): string {
if (path.isAbsolute(filePath)) {
return filePath;
}
const base = typeof cwd === "string" && cwd.trim() ? cwd.trim() : process.cwd();
return path.resolve(base, filePath);
}
async function fileExists(filePath: string): Promise<boolean> {
try {
const stat = await fs.stat(filePath);
return stat.isFile();
} catch {
return false;
}
}
async function directoryExists(filePath: string): Promise<boolean> {
try {
const stat = await fs.stat(filePath);
return stat.isDirectory();
} catch {
return false;
}
}
async function isExecutable(filePath: string): Promise<boolean> {
try {
await fs.access(filePath, process.platform === "win32" ? fsConstants.F_OK : fsConstants.X_OK);
return true;
} catch {
return false;
}
}
function executableCandidates(command: string): string[] {
if (process.platform !== "win32") {
return [command];
}
const extensions = (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM")
.split(";")
.map((entry) => entry.trim())
.filter(Boolean);
if (path.extname(command)) {
return [command];
}
return [command, ...extensions.map((extension) => `${command}${extension.toLowerCase()}`)];
}
function resolveEffectivePath(env: Record<string, string> | undefined): string {
if (!env) {
return process.env.PATH ?? "";
}
if (typeof env.PATH === "string") {
return env.PATH;
}
if (process.platform === "win32" && typeof env.Path === "string") {
return env.Path;
}
return process.env.PATH ?? "";
}
async function commandExists(
command: string,
cwd: unknown,
env: Record<string, string> | undefined,
): Promise<boolean> {
const hasPathSeparator =
path.isAbsolute(command) || command.includes("/") || command.includes("\\");
if (hasPathSeparator) {
return isExecutable(resolveConfiguredPath(command, cwd));
}
const pathEntries = resolveEffectivePath(env)
.split(path.delimiter)
.map((entry) => entry.trim() || ".");
for (const pathEntry of pathEntries) {
const resolvedPathEntry = path.isAbsolute(pathEntry)
? pathEntry
: resolveConfiguredPath(pathEntry, cwd);
for (const candidate of executableCandidates(command)) {
if (await isExecutable(path.join(resolvedPathEntry, candidate))) {
return true;
}
}
}
return false;
}
async function collectMcpDoctorIssues(params: {
name: string;
server: Record<string, unknown>;
probe: boolean;
config: OpenClawConfig;
path: string;
}): Promise<McpDoctorIssue[]> {
const issues: McpDoctorIssue[] = [];
const { name, server } = params;
const resolved = resolveMcpTransportConfig(name, server);
const disabled = server.enabled === false;
if (server.enabled === false) {
issues.push(issue("warning", "server is disabled"));
}
if (!disabled) {
if (!resolved) {
issues.push(issue("error", "server transport is invalid"));
}
if (resolved?.kind === "stdio") {
if (!(await commandExists(resolved.command, resolved.cwd, resolved.env))) {
issues.push(
issue("error", `stdio command not found or not executable: ${resolved.command}`),
);
}
if (resolved.cwd && !(await directoryExists(resolved.cwd))) {
issues.push(issue("error", `stdio cwd does not exist: ${resolved.cwd}`));
}
}
if (resolved?.kind === "http") {
if (server.auth === "oauth") {
const authStatus = await readMcpOAuthCredentialsStatus({
serverName: name,
serverUrl: resolved.url,
});
if (!authStatus.hasTokens) {
issues.push(
issue(
"warning",
`OAuth credentials are not authorized; run ${formatCliCommand(`openclaw mcp login ${name}`)}`,
),
);
}
const headers = asRecord(server.headers);
if (headers && "Authorization" in headers) {
issues.push(
issue("warning", "OAuth is enabled and the static Authorization header is ignored"),
);
}
}
if (resolved.sslVerify === false) {
issues.push(issue("warning", "TLS certificate verification is disabled"));
}
if (
resolved.clientCert &&
!(await fileExists(resolveConfiguredPath(resolved.clientCert, "")))
) {
issues.push(
issue("error", `client certificate file does not exist: ${resolved.clientCert}`),
);
}
if (
resolved.clientKey &&
!(await fileExists(resolveConfiguredPath(resolved.clientKey, "")))
) {
issues.push(issue("error", `client key file does not exist: ${resolved.clientKey}`));
}
}
}
for (const [field, values] of [
["headers", asRecord(server.headers)],
["env", asRecord(server.env)],
] as const) {
for (const [key, value] of Object.entries(values ?? {})) {
if (hasSensitiveKey(key) && hasLiteralSensitiveValue(value)) {
issues.push(
issue(
"warning",
`${field}.${key} contains a literal sensitive value; prefer an environment-backed value outside committed config`,
),
);
}
}
}
const toolFilter = asRecord(server.toolFilter);
if (toolFilter && !Array.isArray(toolFilter.include) && !Array.isArray(toolFilter.exclude)) {
issues.push(issue("warning", "toolFilter is present but has no include or exclude list"));
}
if (
params.probe &&
server.enabled !== false &&
!issues.some((entry) => entry.level === "error")
) {
const probeIssue = await probeMcpServerIssue({
config: params.config,
name,
server,
});
if (probeIssue) {
issues.push(probeIssue);
}
}
return issues;
}
async function probeMcpServerIssue(params: {
config: OpenClawConfig;
name: string;
server: Record<string, unknown>;
}): Promise<McpDoctorIssue | null> {
const runtime = createSessionMcpRuntime({
sessionId: "openclaw-cli-mcp-doctor",
workspaceDir: process.cwd(),
cfg: buildMcpProbeConfig({
config: params.config,
servers: { [params.name]: params.server },
}),
manifestRegistry: { plugins: [] },
});
try {
const result = formatMcpProbeResult(await runtime.getCatalog());
const diagnostic = result.diagnostics[0];
if (diagnostic) {
return issue("error", `probe failed: ${diagnostic.message}`);
}
if (!result.servers[params.name]) {
return issue("error", "probe did not connect to this server");
}
return null;
} catch (err) {
return issue("error", `probe failed: ${formatErrorMessage(err)}`);
} finally {
await runtime.dispose();
}
}
async function buildMcpStatusEntries(
servers: Record<string, Record<string, unknown>>,
): Promise<McpStatusEntry[]> {
const entries = Object.entries(servers).toSorted(([a], [b]) => a.localeCompare(b));
return Promise.all(
entries.map(async ([name, server]) => {
const resolved = resolveMcpTransportConfig(name, server);
const enabled = server.enabled !== false;
const entry: McpStatusEntry = {
name,
configured: true,
enabled,
ok: enabled && Boolean(resolved),
transport: resolved?.transportType,
launch: resolved?.description,
requestTimeoutMs: resolved?.requestTimeoutMs,
connectionTimeoutMs: resolved?.connectionTimeoutMs,
supportsParallelToolCalls: resolved?.supportsParallelToolCalls,
toolFilter: server.toolFilter,
codex: server.codex,
};
if (server.auth) {
entry.auth = server.auth;
}
if (server.auth === "oauth" && resolved?.kind === "http") {
entry.authStatus = await readMcpOAuthCredentialsStatus({
serverName: name,
serverUrl: resolved.url,
});
}
return entry;
}),
);
}
function formatMcpProbeResult(
catalog: Awaited<ReturnType<ReturnType<typeof createSessionMcpRuntime>["getCatalog"]>>,
) {
const projectedTools = buildBundleMcpToolsFromCatalog({
catalog,
createResourceListExecute: () => async () => {
throw new Error("probe projection cannot execute MCP resources_list");
},
createResourceReadExecute: () => async () => {
throw new Error("probe projection cannot execute MCP resources_read");
},
createPromptListExecute: () => async () => {
throw new Error("probe projection cannot execute MCP prompts_list");
},
createPromptGetExecute: () => async () => {
throw new Error("probe projection cannot execute MCP prompts_get");
},
});
return {
generatedAt: new Date(catalog.generatedAt).toISOString(),
servers: Object.fromEntries(
Object.entries(catalog.servers)
.toSorted(([a], [b]) => a.localeCompare(b))
.map(([name, server]) => [
name,
{
launch: server.launchSummary,
tools: server.toolCount,
...(server.requestTimeoutMs ? { requestTimeoutMs: server.requestTimeoutMs } : {}),
...(server.supportsParallelToolCalls
? { supportsParallelToolCalls: server.supportsParallelToolCalls }
: {}),
...(server.tools?.filteredCount ? { filteredTools: server.tools.filteredCount } : {}),
...(server.resources ? { resources: true } : {}),
...(server.prompts ? { prompts: true } : {}),
...(server.tools?.listChanged ||
server.resources?.listChanged ||
server.prompts?.listChanged
? {
listChanged: {
tools: server.tools?.listChanged === true,
resources: server.resources?.listChanged === true,
prompts: server.prompts?.listChanged === true,
},
}
: {}),
},
]),
),
tools: projectedTools.map((tool) => tool.name).toSorted(),
diagnostics: catalog.diagnostics ?? [],
};
}
function buildMcpProbeConfig(params: {
config: OpenClawConfig;
servers: Record<string, Record<string, unknown>>;
}): OpenClawConfig {
return {
...params.config,
mcp: {
...params.config.mcp,
servers: params.servers,
},
};
}
async function probeMcpServersOrFail(params: {
config: OpenClawConfig;
servers: Record<string, Record<string, unknown>>;
path: string;
}): Promise<ReturnType<typeof formatMcpProbeResult>> {
const runtime = createSessionMcpRuntime({
sessionId: "openclaw-cli-mcp-probe",
workspaceDir: process.cwd(),
cfg: buildMcpProbeConfig({ config: params.config, servers: params.servers }),
manifestRegistry: { plugins: [] },
});
try {
const result = formatMcpProbeResult(await runtime.getCatalog());
if (result.diagnostics.length > 0) {
const first = result.diagnostics[0];
fail(`MCP probe failed for "${first.serverName}" in ${params.path}: ${first.message}`);
}
for (const name of Object.keys(params.servers)) {
if (!result.servers[name]) {
fail(`MCP probe did not connect to "${name}" in ${params.path}.`);
}
}
return result;
} finally {
await runtime.dispose();
}
}
export function registerMcpCli(program: Command) {
const mcp = program.command("mcp").description("Manage OpenClaw MCP config and channel bridge");
mcp
.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 (opts) => {
try {
const { gatewayToken, gatewayPassword } = resolveGatewayAuthOptions(opts);
const claudeChannelMode = normalizeLowercaseStringOrEmpty(
normalizeStringifiedOptionalString(opts.claudeChannelMode) ?? "auto",
);
if (
claudeChannelMode !== "auto" &&
claudeChannelMode !== "on" &&
claudeChannelMode !== "off"
) {
throw new Error('Invalid --claude-channel-mode value. Use "auto", "on", or "off".');
}
await serveOpenClawChannelMcp({
gatewayUrl: opts.url as string | undefined,
gatewayToken,
gatewayPassword,
claudeChannelMode,
verbose: Boolean(opts.verbose),
});
} catch (err) {
defaultRuntime.error(
`MCP server failed to start: ${formatErrorMessage(err)}. Run ${formatCliCommand("openclaw mcp list")} to inspect configured servers.`,
);
defaultRuntime.exit(1);
}
});
mcp
.command("list")
.description("List configured MCP servers")
.option("--json", "Print JSON")
.action(async (opts: { json?: boolean }) => {
const loaded = await listConfiguredMcpServers();
if (!loaded.ok) {
fail(loaded.error);
}
if (opts.json) {
printJson(loaded.mcpServers);
return;
}
const names = Object.keys(loaded.mcpServers).toSorted();
if (names.length === 0) {
defaultRuntime.log(
`No MCP servers configured in ${loaded.path}. Add one with ${formatCliCommand('openclaw mcp set <name> \'{"command":"uvx","args":["context7-mcp"]}\'')}.`,
);
return;
}
defaultRuntime.log(`MCP servers (${loaded.path}):`);
for (const name of names) {
defaultRuntime.log(`- ${name}`);
}
});
mcp
.command("show")
.description("Show one configured MCP server or the full MCP config")
.argument("[name]", "MCP server name")
.option("--json", "Print JSON")
.action(async (name: string | undefined, opts: { json?: boolean }) => {
const loaded = await listConfiguredMcpServers();
if (!loaded.ok) {
fail(loaded.error);
}
const value = name ? loaded.mcpServers[name] : loaded.mcpServers;
if (name && !value) {
fail(
`No MCP server named "${name}" in ${loaded.path}. Run ${formatCliCommand("openclaw mcp list")} to see configured servers.`,
);
}
if (opts.json) {
printJson(value ?? {});
return;
}
if (name) {
defaultRuntime.log(`MCP server "${name}" (${loaded.path}):`);
} else {
defaultRuntime.log(`MCP servers (${loaded.path}):`);
}
printJson(value ?? {});
});
mcp
.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 (opts: { json?: boolean; verbose?: boolean }) => {
const loaded = await listConfiguredMcpServers();
if (!loaded.ok) {
fail(loaded.error);
}
const status = await buildMcpStatusEntries(loaded.mcpServers);
if (opts.json) {
printJson({ path: loaded.path, servers: status });
return;
}
if (status.length === 0) {
defaultRuntime.log(`No MCP servers configured in ${loaded.path}.`);
return;
}
defaultRuntime.log(`MCP server status (${loaded.path}):`);
for (const entry of status) {
const transport = entry.enabled ? (entry.transport ?? "invalid") : "disabled";
const auth = entry.auth === "oauth" ? " oauth" : "";
const oauth = entry.authStatus?.hasTokens ? " authorized" : "";
const filters = entry.toolFilter ? " tool-filtered" : "";
const parallel = entry.supportsParallelToolCalls ? " parallel" : "";
defaultRuntime.log(`- ${entry.name}: ${transport}${auth}${oauth}${filters}${parallel}`);
if (opts.verbose) {
defaultRuntime.log(` launch: ${entry.launch ?? "n/a"}`);
defaultRuntime.log(
` timeouts: connect=${entry.connectionTimeoutMs ?? "n/a"}ms request=${entry.requestTimeoutMs ?? "n/a"}ms`,
);
if (entry.auth === "oauth") {
defaultRuntime.log(
` oauth: tokens=${entry.authStatus?.hasTokens ? "yes" : "no"} client=${entry.authStatus?.hasClientInformation ? "yes" : "no"}`,
);
}
if (entry.toolFilter) {
defaultRuntime.log(` tools: ${JSON.stringify(entry.toolFilter)}`);
}
}
}
});
mcp
.command("probe")
.description("Connect to configured MCP servers and list available capabilities")
.argument("[name]", "MCP server name")
.option("--json", "Print JSON")
.action(async (name: string | undefined, opts: { json?: boolean }) => {
const loaded = await listConfiguredMcpServers();
if (!loaded.ok) {
fail(loaded.error);
}
const servers = name
? loaded.mcpServers[name]
? { [name]: loaded.mcpServers[name] }
: undefined
: loaded.mcpServers;
if (!servers) {
fail(
`No MCP server named "${name}" in ${loaded.path}. Run ${formatCliCommand("openclaw mcp list")} to see configured servers.`,
);
}
if (name && loaded.mcpServers[name]?.enabled === false) {
fail(
`MCP server "${name}" is disabled in ${loaded.path}. Run ${formatCliCommand(`openclaw mcp configure ${name} --enable`)} before probing it.`,
);
}
const runtime = createSessionMcpRuntime({
sessionId: "openclaw-cli-mcp-probe",
workspaceDir: process.cwd(),
cfg: buildMcpProbeConfig({ config: loaded.config, servers }),
manifestRegistry: { plugins: [] },
});
try {
const result = formatMcpProbeResult(await runtime.getCatalog());
if (opts.json) {
printJson(result);
return;
}
defaultRuntime.log(`MCP probe (${loaded.path}):`);
for (const [serverName, server] of Object.entries(result.servers)) {
defaultRuntime.log(
`- ${serverName}: ${server.tools} tools${server.resources ? ", resources" : ""}${server.prompts ? ", prompts" : ""}`,
);
}
for (const diagnostic of result.diagnostics) {
defaultRuntime.log(`! ${diagnostic.serverName}: ${diagnostic.message}`);
}
} finally {
await runtime.dispose();
}
});
mcp
.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 (name: string | undefined, opts: { probe?: boolean; json?: boolean }) => {
const loaded = await listConfiguredMcpServers();
if (!loaded.ok) {
fail(loaded.error);
}
const selected = name
? loaded.mcpServers[name]
? { [name]: loaded.mcpServers[name] }
: undefined
: loaded.mcpServers;
if (!selected) {
fail(
`No MCP server named "${name}" in ${loaded.path}. Run ${formatCliCommand("openclaw mcp list")} to see configured servers.`,
);
}
const servers = await Promise.all(
Object.entries(selected)
.toSorted(([a], [b]) => a.localeCompare(b))
.map(async ([serverName, server]): Promise<McpDoctorServerResult> => {
const issues = await collectMcpDoctorIssues({
name: serverName,
server,
config: loaded.config,
path: loaded.path,
probe: Boolean(opts.probe),
});
return {
name: serverName,
ok: !issues.some((entry) => entry.level === "error"),
issues,
};
}),
);
const ok = servers.every((server) => server.ok);
if (opts.json) {
printJson({ path: loaded.path, ok, servers });
if (!ok) {
fail("MCP doctor found errors.");
}
return;
}
if (servers.length === 0) {
defaultRuntime.log(
`No MCP servers configured in ${loaded.path}. Add one with ${formatCliCommand("openclaw mcp add <name> --command <command>")}.`,
);
return;
}
defaultRuntime.log(`MCP doctor (${loaded.path}):`);
for (const server of servers) {
defaultRuntime.log(`- ${server.name}: ${server.ok ? "ok" : "issues"}`);
for (const entry of server.issues) {
const prefix = entry.level === "error" ? "!" : entry.level === "warning" ? "-" : "i";
defaultRuntime.log(` ${prefix} ${entry.level}: ${entry.message}`);
}
}
if (!ok) {
fail("MCP doctor found errors.");
}
});
mcp
.command("add")
.description("Add one MCP server from flags and probe 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("--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 (
name: string,
opts: {
command?: string;
arg?: string[];
env?: string[];
cwd?: string;
url?: string;
transport?: string;
header?: string[];
auth?: string;
oauthScope?: string;
oauthRedirectUrl?: string;
oauthClientMetadataUrl?: string;
include?: string;
exclude?: string;
timeout?: string;
connectTimeout?: string;
parallel?: boolean;
disabled?: boolean;
sslVerify?: string;
clientCert?: string;
clientKey?: string;
probe?: boolean;
},
) => {
const server: Record<string, unknown> = {};
const command = normalizeStringifiedOptionalString(opts.command);
const url = normalizeStringifiedOptionalString(opts.url);
if (command && url) {
fail("Specify either --command for stdio or --url for HTTP, not both.");
}
if (!command && !url) {
fail("Specify --command for stdio or --url for HTTP.");
}
if (command) {
server.command = command;
if (opts.arg && opts.arg.length > 0) {
server.args = opts.arg;
}
setOptionalField(server, "env", parseKeyValueEntries(opts.env, "--env"));
setOptionalField(server, "cwd", normalizeStringifiedOptionalString(opts.cwd));
}
if (url) {
server.url = url;
setOptionalField(server, "transport", normalizeStringifiedOptionalString(opts.transport));
setOptionalField(server, "headers", parseKeyValueEntries(opts.header, "--header"));
const auth = normalizeLowercaseStringOrEmpty(
normalizeStringifiedOptionalString(opts.auth) ?? "",
);
if (auth && auth !== "oauth") {
fail('Invalid --auth value. Use "oauth".');
}
if (auth) {
server.auth = auth;
}
setOptionalField(
server,
"oauth",
parseOAuthConfig({
scope: opts.oauthScope,
redirectUrl: opts.oauthRedirectUrl,
clientMetadataUrl: opts.oauthClientMetadataUrl,
}),
);
if (opts.sslVerify !== undefined) {
const sslVerify = normalizeLowercaseStringOrEmpty(opts.sslVerify);
if (sslVerify !== "true" && sslVerify !== "false") {
fail("--ssl-verify must be true or false.");
}
server.sslVerify = sslVerify === "true";
}
setOptionalField(
server,
"clientCert",
normalizeStringifiedOptionalString(opts.clientCert),
);
setOptionalField(server, "clientKey", normalizeStringifiedOptionalString(opts.clientKey));
}
if (opts.disabled) {
server.enabled = false;
}
if (opts.parallel) {
server.supportsParallelToolCalls = true;
}
setOptionalField(server, "timeout", parsePositiveNumberOption(opts.timeout, "--timeout"));
setOptionalField(
server,
"connectTimeout",
parsePositiveNumberOption(opts.connectTimeout, "--connect-timeout"),
);
const include = parseCsvList(opts.include);
const exclude = parseCsvList(opts.exclude);
if (include || exclude) {
server.toolFilter = {
...(include ? { include } : {}),
...(exclude ? { exclude } : {}),
};
}
const loaded = await listConfiguredMcpServers();
if (!loaded.ok) {
fail(loaded.error);
}
const current = loaded.mcpServers[name];
const shouldProbe =
opts.probe !== false && server.enabled !== false && server.auth !== "oauth";
if (shouldProbe) {
await probeMcpServersOrFail({
config: loaded.config,
path: loaded.path,
servers: { [name]: server },
});
}
const result = await setConfiguredMcpServer({ name, server });
if (!result.ok) {
fail(result.error);
}
await clearStaleMcpOAuthCredentialsForReplacement({
name,
previous: current,
next: server,
});
defaultRuntime.log(`Saved MCP server "${name}" to ${result.path}.`);
if (server.auth === "oauth") {
defaultRuntime.log(
`Run ${formatCliCommand(`openclaw mcp login ${name}`)} to authorize this MCP server.`,
);
}
},
);
mcp
.command("set")
.description("Set one configured MCP server from a JSON object")
.argument("<name>", "MCP server name")
.argument("<value>", 'JSON object, for example {"command":"uvx","args":["context7-mcp"]}')
.action(async (name: string, rawValue: string) => {
const parsed = parseConfigValue(rawValue);
if (parsed.error) {
fail(parsed.error);
}
const loaded = await listConfiguredMcpServers();
if (!loaded.ok) {
fail(loaded.error);
}
const current = loaded.mcpServers[name];
const result = await setConfiguredMcpServer({ name, server: parsed.value });
if (!result.ok) {