-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmcp_cmd.rs
More file actions
1917 lines (1653 loc) · 60.1 KB
/
mcp_cmd.rs
File metadata and controls
1917 lines (1653 loc) · 60.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 (Model Context Protocol) management commands.
use anyhow::{Context, Result, bail};
use clap::{ArgGroup, Parser};
use cortex_common::CliConfigOverrides;
use cortex_engine::{config::find_cortex_home, create_default_client};
use std::io::{self, BufRead, Write};
// ============================================================================
// Input Validation Constants and Utilities
// ============================================================================
/// Maximum length for server names (prevents DoS and storage issues)
const MAX_SERVER_NAME_LENGTH: usize = 64;
/// Maximum length for URLs (reasonable limit for HTTP URLs)
const MAX_URL_LENGTH: usize = 2048;
/// Maximum length for environment variable names
const MAX_ENV_VAR_NAME_LENGTH: usize = 256;
/// Maximum length for environment variable values
const MAX_ENV_VAR_VALUE_LENGTH: usize = 4096;
/// Maximum number of environment variables per server
const MAX_ENV_VARS: usize = 50;
/// Maximum number of command arguments
const MAX_COMMAND_ARGS: usize = 100;
/// Maximum length for a single command argument
const MAX_COMMAND_ARG_LENGTH: usize = 4096;
/// Allowed URL schemes for MCP HTTP transport
const ALLOWED_URL_SCHEMES: &[&str] = &["http", "https"];
/// Dangerous URL patterns that should be blocked
const BLOCKED_URL_PATTERNS: &[&str] = &[
"javascript:",
"data:",
"file:",
"ftp:",
"localhost", // Require explicit localhost allowance
"127.0.0.1",
"0.0.0.0",
"[::1]",
"169.254.", // Link-local
"10.", // Private network
"192.168.", // Private network
"172.16.", // Private network start
"172.17.",
"172.18.",
"172.19.",
"172.20.",
"172.21.",
"172.22.",
"172.23.",
"172.24.",
"172.25.",
"172.26.",
"172.27.",
"172.28.",
"172.29.",
"172.30.",
"172.31.", // Private network end
];
/// Validates and sanitizes a URL for MCP HTTP transport.
///
/// # Validation Rules:
/// - Must not exceed maximum length
/// - Must use allowed schemes (http/https)
/// - Must not contain dangerous patterns
/// - Must be a valid URL format
fn validate_url(url: &str) -> Result<()> {
// Check length
if url.is_empty() {
bail!("URL cannot be empty");
}
if url.len() > MAX_URL_LENGTH {
bail!(
"URL exceeds maximum length of {} characters",
MAX_URL_LENGTH
);
}
// Check for null bytes
if url.contains('\0') {
bail!("URL contains null bytes");
}
let url_lower = url.to_lowercase();
// Check scheme - must start with http:// or https://
let has_valid_scheme = ALLOWED_URL_SCHEMES
.iter()
.any(|&scheme| url_lower.starts_with(&format!("{}://", scheme)));
if !has_valid_scheme {
bail!(
"URL must start with http:// or https://. Got: {}",
url.chars().take(20).collect::<String>()
);
}
// Check for blocked patterns
for pattern in BLOCKED_URL_PATTERNS {
if url_lower.contains(pattern) {
bail!(
"URL contains blocked pattern '{}'. For security, local/private network URLs are not allowed by default. \
Use environment variables for local development servers.",
pattern
);
}
}
// Extract host portion for validation (simple parsing)
let after_scheme = if url_lower.starts_with("https://") {
&url[8..]
} else if url_lower.starts_with("http://") {
&url[7..]
} else {
bail!("Invalid URL scheme");
};
// Host should be non-empty (check up to first / or end)
let host_end = after_scheme.find('/').unwrap_or(after_scheme.len());
let host_port = &after_scheme[..host_end];
if host_port.is_empty() {
bail!("URL must contain a valid host");
}
// Remove port if present to check host
let host = host_port.split(':').next().unwrap_or(host_port);
if host.is_empty() {
bail!("URL must contain a valid host");
}
// Check for path traversal attempts in the path portion
if let Some(path_start) = after_scheme.find('/') {
let path = &after_scheme[path_start..];
if path.contains("..") {
bail!("URL path contains potentially dangerous path traversal patterns");
}
}
// Check for control characters
for c in url.chars() {
if c.is_control() && c != '\t' {
bail!("URL contains control characters");
}
}
Ok(())
}
/// Validates environment variable name.
fn validate_env_var_name(name: &str) -> Result<()> {
if name.is_empty() {
bail!("Environment variable name cannot be empty");
}
if name.len() > MAX_ENV_VAR_NAME_LENGTH {
bail!(
"Environment variable name exceeds maximum length of {} characters",
MAX_ENV_VAR_NAME_LENGTH
);
}
// Env var names should be alphanumeric with underscores
if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
bail!(
"Environment variable name '{}' contains invalid characters. Use only letters, numbers, and underscores.",
name
);
}
// Should not start with a digit
if name
.chars()
.next()
.map(|c| c.is_ascii_digit())
.unwrap_or(false)
{
bail!("Environment variable name cannot start with a digit");
}
Ok(())
}
/// Validates environment variable value.
fn validate_env_var_value(value: &str) -> Result<()> {
if value.len() > MAX_ENV_VAR_VALUE_LENGTH {
bail!(
"Environment variable value exceeds maximum length of {} characters",
MAX_ENV_VAR_VALUE_LENGTH
);
}
// Check for null bytes which could cause issues
if value.contains('\0') {
bail!("Environment variable value contains null bytes");
}
Ok(())
}
/// Validates command arguments for stdio transport.
fn validate_command_args(args: &[String]) -> Result<()> {
if args.is_empty() {
bail!("Command cannot be empty");
}
if args.len() > MAX_COMMAND_ARGS {
bail!(
"Too many command arguments ({}). Maximum allowed is {}",
args.len(),
MAX_COMMAND_ARGS
);
}
for (i, arg) in args.iter().enumerate() {
if arg.len() > MAX_COMMAND_ARG_LENGTH {
bail!(
"Command argument {} exceeds maximum length of {} characters",
i + 1,
MAX_COMMAND_ARG_LENGTH
);
}
// Check for null bytes
if arg.contains('\0') {
bail!("Command argument {} contains null bytes", i + 1);
}
}
Ok(())
}
/// Validates bearer token environment variable name.
fn validate_bearer_token_env_var(var_name: &str) -> Result<()> {
validate_env_var_name(var_name)?;
// Additional checks for token env vars
let upper = var_name.to_uppercase();
if upper.contains("PASSWORD") || upper.contains("PASSWD") {
// Warn but don't block - just log
tracing::warn!(
"Bearer token env var '{}' contains 'PASSWORD' - ensure this is intentional",
var_name
);
}
Ok(())
}
/// MCP management CLI.
#[derive(Debug, Parser)]
pub struct McpCli {
#[clap(flatten)]
pub config_overrides: CliConfigOverrides,
#[command(subcommand)]
pub subcommand: McpSubcommand,
}
/// MCP subcommands.
#[derive(Debug, clap::Subcommand)]
pub enum McpSubcommand {
/// List configured MCP servers.
List(ListArgs),
/// List configured MCP servers (alias for list).
#[command(visible_alias = "ls")]
Ls(ListArgs),
/// Show details for a configured MCP server.
Get(GetArgs),
/// Add a global MCP server entry.
Add(AddArgs),
/// Remove a global MCP server entry.
#[command(visible_alias = "rm")]
Remove(RemoveArgs),
/// Authenticate with an OAuth-enabled MCP server.
Auth(AuthCommand),
/// Remove OAuth credentials for an MCP server.
Logout(LogoutArgs),
/// Debug and test an MCP server connection.
Debug(DebugArgs),
}
/// Arguments for list command.
#[derive(Debug, Parser)]
pub struct ListArgs {
/// Output the configured servers as JSON.
#[arg(long)]
pub json: bool,
}
/// Arguments for get command.
#[derive(Debug, Parser)]
pub struct GetArgs {
/// Name of the MCP server to display.
pub name: String,
/// Output the server configuration as JSON.
#[arg(long)]
pub json: bool,
}
/// Arguments for add command.
#[derive(Debug, Parser)]
#[command(
override_usage = "cortex mcp add [OPTIONS] <NAME> (--url <URL> | -- <COMMAND>...)",
after_help = "IMPORTANT: Use '--' to separate the MCP server command from cortex options.\n\
This is required when the command or its arguments start with a dash (-).\n\n\
Examples:\n \
cortex mcp add myserver -- npx @example/server\n \
cortex mcp add myserver -- python -m my_server\n \
cortex mcp add myserver -- node server.js -v # -v goes to server, not cortex\n \
cortex mcp add myserver --url https://example.com/mcp\n\n\
Without '--', arguments like '-v' or '-m' may be interpreted as cortex flags."
)]
pub struct AddArgs {
/// Name for the MCP server configuration.
pub name: String,
/// Overwrite existing server configuration if it exists.
#[arg(long, short = 'f')]
pub force: bool,
#[command(flatten)]
pub transport_args: AddMcpTransportArgs,
}
/// Transport arguments for add command.
#[derive(Debug, clap::Args)]
#[command(
group(
ArgGroup::new("transport")
.args(["command", "url"])
.required(true)
.multiple(false)
)
)]
pub struct AddMcpTransportArgs {
#[command(flatten)]
pub stdio: Option<AddMcpStdioArgs>,
#[command(flatten)]
pub streamable_http: Option<AddMcpStreamableHttpArgs>,
}
/// Stdio transport arguments.
#[derive(Debug, clap::Args)]
pub struct AddMcpStdioArgs {
/// Command to launch the MCP server.
#[arg(trailing_var_arg = true, num_args = 0..)]
pub command: Vec<String>,
/// Environment variables to set when launching the server.
#[arg(long, value_parser = parse_env_pair, value_name = "KEY=VALUE")]
pub env: Vec<(String, String)>,
}
/// HTTP transport arguments.
#[derive(Debug, clap::Args)]
pub struct AddMcpStreamableHttpArgs {
/// URL for a streamable HTTP MCP server.
#[arg(long)]
pub url: String,
/// Optional environment variable to read for a bearer token.
#[arg(
long = "bearer-token-env-var",
value_name = "ENV_VAR",
requires = "url"
)]
pub bearer_token_env_var: Option<String>,
}
/// Arguments for remove command.
#[derive(Debug, Parser)]
pub struct RemoveArgs {
/// Name of the MCP server configuration to remove.
pub name: String,
/// Skip confirmation prompt.
/// Aliases: --force, -f (for compatibility)
#[arg(short = 'y', long = "yes", visible_aliases = ["force"], short_alias = 'f')]
pub yes: bool,
}
/// Auth command with subcommands.
#[derive(Debug, Parser)]
pub struct AuthCommand {
#[command(subcommand)]
pub action: Option<AuthSubcommand>,
/// Name of the MCP server to authenticate with (if no subcommand).
pub name: Option<String>,
/// Client ID for OAuth (if not using dynamic registration).
#[arg(long)]
pub client_id: Option<String>,
/// Client secret for OAuth (if required).
#[arg(long)]
pub client_secret: Option<String>,
}
/// Auth subcommands.
#[derive(Debug, clap::Subcommand)]
pub enum AuthSubcommand {
/// List OAuth status for all servers.
List(AuthListArgs),
}
/// Arguments for auth list command.
#[derive(Debug, Parser)]
pub struct AuthListArgs {
/// Output as JSON.
#[arg(long)]
pub json: bool,
}
/// Arguments for logout command.
#[derive(Debug, Parser)]
pub struct LogoutArgs {
/// Name of the MCP server to remove credentials for.
#[arg(required_unless_present = "all")]
pub name: Option<String>,
/// Remove OAuth credentials for all servers.
#[arg(long)]
pub all: bool,
}
/// Arguments for debug command.
#[derive(Debug, Parser)]
pub struct DebugArgs {
/// Name of the MCP server to debug.
pub name: String,
/// Output as JSON.
#[arg(long)]
pub json: bool,
/// Test OAuth authentication if configured.
#[arg(long)]
pub test_auth: bool,
/// Timeout in seconds for connection test.
#[arg(long, default_value = "30")]
pub timeout: u64,
}
impl McpCli {
/// Run the MCP command.
pub async fn run(self) -> Result<()> {
let McpCli {
config_overrides: _,
subcommand,
} = self;
match subcommand {
McpSubcommand::List(args) | McpSubcommand::Ls(args) => run_list(args).await,
McpSubcommand::Get(args) => run_get(args).await,
McpSubcommand::Add(args) => run_add(args).await,
McpSubcommand::Remove(args) => run_remove(args).await,
McpSubcommand::Auth(cmd) => run_auth_command(cmd).await,
McpSubcommand::Logout(args) => run_logout(args).await,
McpSubcommand::Debug(args) => run_debug(args).await,
}
}
}
/// Load the config file as a toml::Value.
fn load_config() -> Result<Option<toml::Value>> {
let config_path = find_cortex_home()
.map_err(|e| anyhow::anyhow!("Failed to find cortex home: {}", e))?
.join("config.toml");
if !config_path.exists() {
return Ok(None);
}
let content = std::fs::read_to_string(&config_path)
.with_context(|| format!("failed to read config: {}", config_path.display()))?;
let config: toml::Value = toml::from_str(&content).with_context(|| "failed to parse config")?;
Ok(Some(config))
}
/// Get all MCP servers from config.
fn get_mcp_servers() -> Result<toml::map::Map<String, toml::Value>> {
let config = load_config()?;
let servers = config
.and_then(|c| c.get("mcp_servers").and_then(|v| v.as_table()).cloned())
.unwrap_or_default();
Ok(servers)
}
/// Get a specific MCP server from config.
fn get_mcp_server(name: &str) -> Result<Option<toml::Value>> {
let servers = get_mcp_servers()?;
Ok(servers.get(name).cloned())
}
async fn run_list(args: ListArgs) -> Result<()> {
let servers = get_mcp_servers()?;
if args.json {
let json = serde_json::to_string_pretty(&servers)?;
println!("{json}");
return Ok(());
}
if servers.is_empty() {
println!("No MCP servers configured yet.");
println!("\nTo add a server:");
println!(" cortex mcp add my-tool -- my-command # Local stdio server");
println!(" cortex mcp add my-api --url https://... # Remote HTTP server");
return Ok(());
}
println!(
"{:<20} {:<12} {:<8} {:<18} {:<30}",
"Name", "Status", "Tools", "Auth", "Transport"
);
println!("{}", "-".repeat(90));
for (name, server) in &servers {
let enabled = server
.get("enabled")
.and_then(toml::Value::as_bool)
.unwrap_or(true);
let status = if enabled { "enabled" } else { "disabled" };
// Get tools count if available (would come from cached server info)
let tools_count = server
.get("_cached_tools_count")
.and_then(|v| v.as_integer())
.map(|n| n.to_string())
.unwrap_or_else(|| "-".to_string());
// Determine transport type and auth status
let (transport_info, auth_status) = if let Some(transport) = server.get("transport") {
let transport_type = transport
.get("type")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
match transport_type {
"stdio" => {
let cmd = transport
.get("command")
.and_then(|v| v.as_str())
.unwrap_or("?");
(format!("stdio: {cmd}"), "N/A".to_string())
}
"http" => {
let url = transport.get("url").and_then(|v| v.as_str()).unwrap_or("?");
// Check OAuth status for HTTP servers
let auth = get_auth_status_for_display(name, url)
.await
.unwrap_or_else(|_| "Unknown".to_string());
// Truncate URL if too long
let transport_str = if url.len() > 28 {
format!("http: {}...", &url[..25])
} else {
format!("http: {url}")
};
(transport_str, auth)
}
_ => (transport_type.to_string(), "N/A".to_string()),
}
} else {
("unknown".to_string(), "N/A".to_string())
};
println!("{name:<20} {status:<12} {tools_count:<8} {auth_status:<18} {transport_info:<30}");
}
println!("\nTotal: {} server(s)", servers.len());
println!("\nUse 'cortex mcp get <name>' for details.");
println!("Use 'cortex mcp debug <name>' to test connection.");
Ok(())
}
async fn run_get(args: GetArgs) -> Result<()> {
let server = get_mcp_server(&args.name)?
.ok_or_else(|| anyhow::anyhow!("No MCP server named '{}' found", args.name))?;
if args.json {
let json = serde_json::to_string_pretty(&server)?;
println!("{json}");
return Ok(());
}
println!("MCP Server: {}", args.name);
println!("{}", "=".repeat(40));
let enabled = server
.get("enabled")
.and_then(toml::Value::as_bool)
.unwrap_or(true);
println!("Enabled: {enabled}");
if let Some(transport) = server.get("transport") {
let transport_type = transport
.get("type")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
println!("\nTransport: {transport_type}");
match transport_type {
"stdio" => {
if let Some(cmd) = transport.get("command").and_then(|v| v.as_str()) {
println!(" Command: {cmd}");
}
if let Some(args) = transport.get("args").and_then(|v| v.as_array()) {
let args_str: Vec<_> = args.iter().filter_map(|v| v.as_str()).collect();
if !args_str.is_empty() {
println!(" Args: {}", args_str.join(" "));
}
}
if let Some(env) = transport.get("env").and_then(|v| v.as_table()) {
if !env.is_empty() {
println!(" Environment:");
for (key, value) in env {
let val_str = value.as_str().unwrap_or("***");
// Mask sensitive values
let masked = if key.to_lowercase().contains("key")
|| key.to_lowercase().contains("secret")
|| key.to_lowercase().contains("token")
|| key.to_lowercase().contains("password")
{
"***"
} else {
val_str
};
println!(" {key}={masked}");
}
}
}
}
"http" => {
if let Some(url) = transport.get("url").and_then(|v| v.as_str()) {
println!(" URL: {url}");
}
if let Some(token_var) = transport
.get("bearer_token_env_var")
.and_then(|v| v.as_str())
{
println!(" Bearer Token Env Var: {token_var}");
}
}
_ => {}
}
}
// Show OAuth status if HTTP
if let Some(transport) = server.get("transport") {
let transport_type = transport
.get("type")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
if transport_type == "http" {
if let Some(url) = transport.get("url").and_then(|v| v.as_str()) {
println!("\nOAuth Status:");
match get_auth_status_for_display(&args.name, url).await {
Ok(status) => println!(" {status}"),
Err(_) => println!(" Unknown"),
}
}
}
}
Ok(())
}
async fn run_add(args: AddArgs) -> Result<()> {
let AddArgs {
name,
force,
transport_args,
} = args;
validate_server_name(&name)?;
// Check if server already exists
let server_exists = get_mcp_server(&name)?.is_some();
if server_exists && !force {
bail!(
"MCP server '{}' already exists. Use --force to overwrite, or 'cortex mcp remove {}' first.",
name,
name
);
}
// Validate that bearer token is not used with stdio transport
if let Some(ref http_args) = transport_args.streamable_http {
if http_args.bearer_token_env_var.is_some() {
if let Some(ref stdio_args) = transport_args.stdio {
if !stdio_args.command.is_empty() {
bail!(
"Error: --bearer-token-env-var is only supported for HTTP transport.\n\
You cannot use bearer tokens with stdio transport (command execution).\n\n\
To use bearer token authentication:\n\
• Remove the command arguments (-- <COMMAND>)\n\
• Use --url instead to specify an HTTP MCP server\n\n\
Example: cortex mcp add {name} --url https://api.example.com --bearer-token-env-var MY_TOKEN"
);
}
}
}
}
let cortex_home =
find_cortex_home().map_err(|e| anyhow::anyhow!("Failed to find cortex home: {}", e))?;
let config_path = cortex_home.join("config.toml");
// If force mode and server exists, remove it first
if server_exists && force {
// Parse, remove the server, and re-serialize
if config_path.exists() {
let content = std::fs::read_to_string(&config_path)
.with_context(|| format!("failed to read config: {}", config_path.display()))?;
let mut config: toml::Value =
toml::from_str(&content).with_context(|| "failed to parse config")?;
if let Some(mcp_servers) = config.get_mut("mcp_servers").and_then(|v| v.as_table_mut())
{
mcp_servers.remove(&name);
}
// Write back the config without the old server
let updated_content =
toml::to_string_pretty(&config).with_context(|| "failed to serialize config")?;
std::fs::write(&config_path, &updated_content)
.with_context(|| format!("failed to write config: {}", config_path.display()))?;
println!("✓ Removed existing MCP server '{name}' (--force)");
}
}
// Load existing config or create new
let mut config_content = if config_path.exists() {
std::fs::read_to_string(&config_path)
.with_context(|| format!("failed to read config: {}", config_path.display()))?
} else {
String::new()
};
// Create MCP server entry
// Returns (toml_content, success_message) - message is deferred until config write succeeds
let (transport_toml, success_msg) = match transport_args {
AddMcpTransportArgs {
stdio: Some(stdio), ..
} => {
// Validate command arguments
validate_command_args(&stdio.command)?;
// Validate environment variables
if stdio.env.len() > MAX_ENV_VARS {
bail!(
"Too many environment variables ({}). Maximum allowed is {}",
stdio.env.len(),
MAX_ENV_VARS
);
}
for (key, value) in &stdio.env {
validate_env_var_name(key)?;
validate_env_var_value(value)?;
}
let mut command_parts = stdio.command.into_iter();
let command_bin = command_parts
.next()
.ok_or_else(|| anyhow::anyhow!("command is required"))?;
let command_args: Vec<String> = command_parts.collect();
// Sanitize command_bin for TOML (escape special characters)
let command_bin_escaped = command_bin.replace('\\', "\\\\").replace('"', "\\\"");
let mut toml = format!(
r#"
[mcp_servers.{name}]
enabled = true
[mcp_servers.{name}.transport]
type = "stdio"
command = "{command_bin_escaped}"
"#
);
if !command_args.is_empty() {
toml.push_str(&format!(
"args = [{}]\n",
command_args
.iter()
.map(|a| {
// Escape special characters in args
let escaped = a.replace('\\', "\\\\").replace('"', "\\\"");
format!("\"{escaped}\"")
})
.collect::<Vec<_>>()
.join(", ")
));
}
if !stdio.env.is_empty() {
toml.push_str("[mcp_servers.");
toml.push_str(&name);
toml.push_str(".transport.env]\n");
for (key, value) in &stdio.env {
// Escape special characters in env values
let escaped_value = value.replace('\\', "\\\\").replace('"', "\\\"");
toml.push_str(&format!("{key} = \"{escaped_value}\"\n"));
}
}
// Build success message but defer printing until config write succeeds
let mut success_msg = format!("✓ Added stdio MCP server '{name}'\n");
success_msg.push_str(&format!(" Command: {command_bin}\n"));
if !command_args.is_empty() {
success_msg.push_str(&format!(" Args: {}\n", command_args.join(" ")));
}
(toml, success_msg)
}
AddMcpTransportArgs {
streamable_http:
Some(AddMcpStreamableHttpArgs {
url,
bearer_token_env_var,
}),
..
} => {
// Validate URL format and safety
validate_url(&url)?;
// Validate bearer token env var if provided
if let Some(ref token_var) = bearer_token_env_var {
validate_bearer_token_env_var(token_var)?;
}
// Escape URL for TOML
let url_escaped = url.replace('\\', "\\\\").replace('"', "\\\"");
let mut toml = format!(
r#"
[mcp_servers.{name}]
enabled = true
[mcp_servers.{name}.transport]
type = "http"
url = "{url_escaped}"
"#
);
if let Some(ref token_var) = bearer_token_env_var {
toml.push_str(&format!("bearer_token_env_var = \"{token_var}\"\n"));
}
// Build success message but defer printing until config write succeeds
let mut success_msg = format!("✓ Added HTTP MCP server '{name}'\n");
success_msg.push_str(&format!(" URL: {url}\n"));
if let Some(ref token_var) = bearer_token_env_var {
success_msg.push_str(&format!(" Bearer Token Env Var: {token_var}\n"));
}
(toml, success_msg)
}
_ => bail!("exactly one of --command or --url must be provided"),
};
// Append to config
config_content.push_str(&transport_toml);
// Ensure directory exists
if let Some(parent) = config_path.parent() {
std::fs::create_dir_all(parent)?;
}
// Write config file - only print success message after this succeeds
std::fs::write(&config_path, &config_content)
.with_context(|| format!("failed to write config: {}", config_path.display()))?;
// Now that config was successfully written, print the success message
print!("{success_msg}");
println!("\nUse 'cortex mcp debug {name}' to test the connection.");
Ok(())
}
async fn run_remove(args: RemoveArgs) -> Result<()> {
let RemoveArgs { name, yes } = args;
validate_server_name(&name)?;
// Check if server exists
if get_mcp_server(&name)?.is_none() {
bail!("No MCP server named '{}' found", name);
}
// Confirm removal if not skipped via --yes/-y/--force/-f
if !yes {
print!("Remove MCP server '{name}'? [y/N]: ");
io::stdout().flush()?;
let mut input = String::new();
io::stdin().lock().read_line(&mut input)?;
if !input.trim().eq_ignore_ascii_case("y") {
println!("Cancelled.");
return Ok(());
}
}
let cortex_home =
find_cortex_home().map_err(|e| anyhow::anyhow!("Failed to find cortex home: {}", e))?;
let config_path = cortex_home.join("config.toml");
if !config_path.exists() {
bail!("Config file not found");
}
let content = std::fs::read_to_string(&config_path)
.with_context(|| format!("failed to read config: {}", config_path.display()))?;
// Parse the TOML and remove the server section
let mut config: toml::Value =
toml::from_str(&content).with_context(|| "failed to parse config")?;
if let Some(mcp_servers) = config.get_mut("mcp_servers").and_then(|v| v.as_table_mut()) {
mcp_servers.remove(&name);
}
// Write back the config
let new_content =
toml::to_string_pretty(&config).with_context(|| "failed to serialize config")?;
std::fs::write(&config_path, new_content)
.with_context(|| format!("failed to write config: {}", config_path.display()))?;
println!("✓ Removed MCP server '{name}'.");
// Also remove OAuth credentials if any
match remove_auth_silent(&name).await {
Ok(true) => println!("✓ Removed OAuth credentials for '{name}'."),
Ok(false) => {}
Err(_) => {}
}
Ok(())
}
fn parse_env_pair(raw: &str) -> Result<(String, String), String> {
let mut parts = raw.splitn(2, '=');
let key = parts
.next()
.map(str::trim)
.filter(|s| !s.is_empty())
.ok_or_else(|| "environment entries must be in KEY=VALUE form".to_string())?;
let value = parts
.next()
.map(str::to_string)
.ok_or_else(|| "environment entries must be in KEY=VALUE form".to_string())?;
Ok((key.to_string(), value))
}
fn validate_server_name(name: &str) -> Result<()> {
// Check for empty name
if name.is_empty() {
bail!("server name cannot be empty");
}
// Check length limits
if name.len() > MAX_SERVER_NAME_LENGTH {
bail!(
"server name '{}' exceeds maximum length of {} characters",
name,
MAX_SERVER_NAME_LENGTH
);
}
// Check for valid characters
let is_valid_chars = name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
if !is_valid_chars {
bail!("invalid server name '{name}' (use letters, numbers, '-', '_')");
}
// Must start with a letter or underscore
let first_char = name.chars().next().unwrap();
if first_char.is_ascii_digit() || first_char == '-' {
bail!(
"server name must start with a letter or underscore, not '{}'",
first_char
);
}