-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbridge.rs
More file actions
3331 lines (3086 loc) · 104 KB
/
Copy pathbridge.rs
File metadata and controls
3331 lines (3086 loc) · 104 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
//! The static `BridgeCli` — a fixed `clap` tree that works with any
//! MCP server regardless of whether a discovery cache exists.
//!
//! Compared to [`crate::apps::dynamic`], which generates a bespoke
//! CLI from cached capabilities, the bridge surface is
//! protocol-shaped: commands name MCP primitives (`invoke`, `get`,
//! `prompt`, `subscribe`, `complete`, `log`) rather than server
//! tools. The bridge stays useful in four situations:
//!
//! 1. **First run** — there's no discovery cache yet; the dynamic CLI
//! can't build a tree. `ls` populates the cache via `tools/list` /
//! `resources/list` / `prompts/list`.
//! 2. **Protocol-shaped use** — `mcp2cli invoke <tool> --arg k=v` is
//! a deterministic back-door that bypasses the generated flag
//! schema. Handy for tools whose JSON Schema is odd enough that
//! the dynamic CLI would get confused.
//! 3. **Lifecycle and introspection commands** — `doctor`, `inspect`,
//! `ping`, `auth login/logout/status`, `jobs show/wait/cancel/watch`,
//! and `log level` never belong in the dynamic surface; they're
//! client operations, not server tools.
//! 4. **Scripting** — CI and shell pipelines want stable command
//! shapes. The bridge's `invoke`/`get`/`prompt` commands never
//! change based on which server is on the other end.
//!
//! The bridge composes with [`crate::apps::AppContext::perform`] for
//! every MCP call, so timeouts, events, and telemetry behave
//! identically to the dynamic path.
use std::{ffi::OsString, io::IsTerminal, path::Path};
use anyhow::{Result, anyhow};
use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, error::ErrorKind};
use serde_json::{Map, Number, Value, json};
use crate::{
apps::{AppContext, default_job_detail_lines, default_job_overview_lines},
mcp::model::{DiscoveryCategory, McpOperation, McpOperationResult, TaskState, TransportKind},
output::{CommandOutput, ExecutionReport, OutputFormat},
runtime::{
AuthSessionRecord, AuthSessionState, DiscoveryInventoryView, JobStatus,
NegotiatedCapabilityView, RuntimeEvent, StoredToken,
},
};
#[derive(Debug, Parser)]
#[command(
about = "MCP bridge CLI — domain-shaped commands for MCP servers",
disable_help_subcommand = true,
arg_required_else_help = true,
subcommand_required = true
)]
struct BridgeCli {
#[arg(long, global = true)]
_config: Option<std::path::PathBuf>,
#[arg(long, global = true)]
json: bool,
#[arg(long, global = true, value_enum)]
output: Option<OutputFormat>,
/// Fail instead of prompting for interactive input (CI mode)
#[arg(long, global = true)]
non_interactive: bool,
/// Provide elicitation answers as a JSON object (CI mode)
#[arg(long, global = true, value_name = "JSON")]
input_json: Option<String>,
/// Operation timeout in seconds (0 = no timeout, overrides config)
#[arg(long, global = true, value_name = "SECONDS")]
timeout: Option<u64>,
#[command(subcommand)]
command: BridgeCommand,
}
impl BridgeCli {
fn effective_output(&self, default_format: OutputFormat) -> OutputFormat {
if self.json {
OutputFormat::Json
} else {
self.output.unwrap_or(default_format)
}
}
}
// ---------------------------------------------------------------------------
// Primary domain-shaped command surface
// ---------------------------------------------------------------------------
#[derive(Debug, Subcommand)]
enum BridgeCommand {
/// Manage and call server tools (actions / verbs)
Tool(ToolArgs),
/// Manage and read server resources (nouns / collections)
Resource(ResourceArgs),
/// List and run server prompts (guided flows / recipes)
Prompt(PromptCmdArgs),
/// Authentication management
Auth(AuthArgs),
/// Background job management
Jobs(JobsArgs),
/// Runtime health diagnostics
Doctor,
/// Inspect server capabilities, metadata, and mapped commands
Inspect,
// --- backward-compatible aliases (hidden from primary help) -----------
/// Discover server capabilities [alias: tool list / resource list / prompt list]
#[command(hide = true)]
Discover(DiscoverArgs),
/// Invoke a tool by capability name [alias: tool call]
#[command(hide = true)]
Invoke(InvokeArgs),
/// Read a resource by URI [alias: resource read]
#[command(hide = true)]
Read(ReadArgs),
/// List capabilities [alias: tool list / resource list / prompt list]
#[command(hide = true)]
List(LegacyListArgs),
}
// ---------------------------------------------------------------------------
// tool subcommand
// ---------------------------------------------------------------------------
#[derive(Debug, Args)]
struct ToolArgs {
#[command(subcommand)]
command: ToolCommand,
}
#[derive(Debug, Subcommand)]
enum ToolCommand {
/// List available tools from the server
List(ToolListArgs),
/// Call a tool by name
Call(ToolCallArgs),
}
#[derive(Debug, Args)]
struct ToolListArgs {
/// Filter tools by name/description substring
#[arg(long)]
filter: Option<String>,
#[arg(long)]
limit: Option<u32>,
#[arg(long)]
cursor: Option<String>,
#[arg(long)]
all: bool,
}
#[derive(Debug, Args)]
struct ToolCallArgs {
/// Tool name to call
name: String,
#[arg(long = "arg", value_name = "KEY=VALUE")]
args: Vec<String>,
#[arg(long = "arg-json", value_name = "KEY=JSON")]
json_args: Vec<String>,
#[arg(long = "args-json", value_name = "JSON_OBJECT")]
args_json: Option<String>,
#[arg(long = "args-file", value_name = "PATH")]
args_file: Option<std::path::PathBuf>,
/// Run as background job
#[arg(long)]
background: bool,
}
// ---------------------------------------------------------------------------
// resource subcommand
// ---------------------------------------------------------------------------
#[derive(Debug, Args)]
struct ResourceArgs {
#[command(subcommand)]
command: ResourceCommand,
}
#[derive(Debug, Subcommand)]
enum ResourceCommand {
/// List available resources from the server
List(ResourceListArgs),
/// Read a resource by URI
Read(ResourceReadArgs),
}
#[derive(Debug, Args)]
struct ResourceListArgs {
/// Filter resources by name/URI substring
#[arg(long)]
filter: Option<String>,
#[arg(long)]
limit: Option<u32>,
#[arg(long)]
cursor: Option<String>,
#[arg(long)]
all: bool,
}
#[derive(Debug, Args)]
struct ResourceReadArgs {
/// Resource URI to read
uri: String,
}
// ---------------------------------------------------------------------------
// prompt subcommand
// ---------------------------------------------------------------------------
#[derive(Debug, Args)]
struct PromptCmdArgs {
#[command(subcommand)]
command: PromptCommand,
}
#[derive(Debug, Subcommand)]
enum PromptCommand {
/// List available prompts from the server
List(PromptListArgs),
/// Run a prompt by name
Run(PromptRunArgs),
}
#[derive(Debug, Args)]
struct PromptListArgs {
/// Filter prompts by name/description substring
#[arg(long)]
filter: Option<String>,
#[arg(long)]
limit: Option<u32>,
#[arg(long)]
cursor: Option<String>,
#[arg(long)]
all: bool,
}
#[derive(Debug, Args)]
struct PromptRunArgs {
/// Prompt name to run
name: String,
#[arg(long = "arg", value_name = "KEY=VALUE")]
args: Vec<String>,
#[arg(long = "arg-json", value_name = "KEY=JSON")]
json_args: Vec<String>,
#[arg(long = "args-json", value_name = "JSON_OBJECT")]
args_json: Option<String>,
#[arg(long = "args-file", value_name = "PATH")]
args_file: Option<std::path::PathBuf>,
}
// ---------------------------------------------------------------------------
// auth subcommand
// ---------------------------------------------------------------------------
#[derive(Debug, Args)]
struct AuthArgs {
#[command(subcommand)]
command: AuthCommand,
}
#[derive(Debug, Subcommand)]
enum AuthCommand {
/// Authenticate with the server
Login,
/// Clear stored credentials
Logout,
/// Show current authentication state
Status,
}
// ---------------------------------------------------------------------------
// jobs subcommand
// ---------------------------------------------------------------------------
#[derive(Debug, Args)]
struct JobsArgs {
#[command(subcommand)]
command: JobsCommand,
}
#[derive(Debug, Subcommand)]
enum JobsCommand {
/// List background jobs
List,
/// Show job details
Show(JobSelectorArgs),
/// Wait for job completion
Wait(JobSelectorArgs),
/// Cancel a running job
Cancel(JobSelectorArgs),
/// Watch job progress
Watch(JobSelectorArgs),
}
#[derive(Debug, Args, Clone, PartialEq, Eq)]
struct JobSelectorArgs {
job_id: Option<String>,
#[arg(long, conflicts_with = "job_id")]
latest: bool,
#[arg(long)]
command: Option<String>,
}
// ---------------------------------------------------------------------------
// backward-compatible legacy args (hidden commands)
// ---------------------------------------------------------------------------
#[derive(Debug, Args)]
struct DiscoverArgs {
#[command(subcommand)]
command: DiscoverCommand,
}
#[derive(Debug, Subcommand)]
enum DiscoverCommand {
Capabilities,
Resources,
Prompts,
}
#[derive(Debug, Args)]
struct InvokeArgs {
#[arg(long)]
capability: String,
#[arg(long = "arg", value_name = "KEY=VALUE")]
args: Vec<String>,
#[arg(long = "arg-json", value_name = "KEY=JSON")]
json_args: Vec<String>,
#[arg(long = "args-json", value_name = "JSON_OBJECT")]
args_json: Option<String>,
#[arg(long = "args-file", value_name = "PATH")]
args_file: Option<std::path::PathBuf>,
#[arg(long)]
background: bool,
}
#[derive(Debug, Args)]
struct ReadArgs {
#[arg(long)]
uri: String,
}
#[derive(Debug, Args)]
struct LegacyListArgs {
#[arg(long)]
capability: String,
#[arg(long)]
limit: Option<u32>,
#[arg(long)]
cursor: Option<String>,
#[arg(long)]
page_size: Option<u32>,
#[arg(long)]
all: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum BridgeDomainCommand {
Discover {
category: DiscoveryCategory,
},
Invoke {
capability: String,
arguments: Value,
background: bool,
},
Read {
uri: String,
},
List {
capability: String,
limit: Option<u32>,
cursor: Option<String>,
page_size: Option<u32>,
all: bool,
},
Prompt {
name: String,
arguments: Value,
},
AuthLogin,
AuthLogout,
AuthStatus,
JobsList,
JobsShow {
selector: JobSelector,
},
JobsWait {
selector: JobSelector,
},
JobsCancel {
selector: JobSelector,
},
JobsWatch {
selector: JobSelector,
},
Doctor,
Inspect,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct JobSelector {
job_id: Option<String>,
latest: bool,
command: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ParsedListSelector {
category: DiscoveryCategory,
filter: Option<String>,
}
#[derive(Debug, Clone)]
struct DiscoveryItemsSnapshot {
items: Vec<Value>,
cached: bool,
live_error: Option<String>,
updated_at: Option<chrono::DateTime<chrono::Utc>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CapabilityGroup {
Tools,
Resources,
Prompts,
}
// ---------------------------------------------------------------------------
// Public bridge entry points — called directly by RuntimeHost
// ---------------------------------------------------------------------------
/// Returns true if the given token is a valid bridge root command.
/// With dynamic CLI, any token from the manifest could be valid too,
/// but this only checks the static/runtime commands for `mcp2cli` dispatch.
pub fn supports_root_command(token: &str) -> bool {
matches!(
token,
"tool" | "resource" | "prompt" | "auth" | "jobs" | "doctor" | "inspect" | "ls"
// legacy aliases
| "discover" | "invoke" | "read" | "list"
)
}
fn bridge_command(invoked_as: &str) -> clap::Command {
let mut command = BridgeCli::command();
command = command
.name("mcp2cli")
.bin_name(invoked_as)
.version(env!("CARGO_PKG_VERSION"))
.after_help(if invoked_as == crate::dispatch::HOST_BINARY_NAME {
"Examples:\n mcp2cli tool list\n mcp2cli tool call send --arg to=user@example.com\n mcp2cli resource list\n mcp2cli resource read mail://inbox\n mcp2cli prompt list\n mcp2cli prompt run triage\n mcp2cli tool call search --args-file ./query.json --background\n mcp2cli auth status\n mcp2cli jobs list\n mcp2cli inspect\n\nHost commands:\n mcp2cli config list\n mcp2cli use email".to_owned()
} else {
// Use the alias the binary was actually invoked as, so `email --help`
// shows `email …` examples rather than a hardcoded sample name.
format!(
"Examples:\n {a} tool list\n {a} tool call send --arg to=user@example.com\n {a} resource list\n {a} resource read mail://inbox\n {a} prompt list\n {a} prompt run triage\n {a} tool call search --args-file ./query.json --background\n {a} auth status\n {a} jobs list\n {a} inspect",
a = invoked_as
)
});
command
}
fn parse_bridge_cli(
argv: &[OsString],
invoked_as: &str,
) -> std::result::Result<BridgeCli, clap::Error> {
let mut command = bridge_command(invoked_as);
let matches = command.try_get_matches_from_mut(argv.to_vec())?;
BridgeCli::from_arg_matches(&matches)
}
fn version_report(output_format: OutputFormat, context: &AppContext) -> ExecutionReport {
ExecutionReport {
output_format,
output: CommandOutput::new(
&context.config_name,
"version",
format!("{} {}", context.invoked_as, env!("CARGO_PKG_VERSION")),
vec![
format!("{} {}", context.invoked_as, env!("CARGO_PKG_VERSION")),
format!("config: {}", context.config_name),
format!("server: {}", context.config.server.display_name),
format!("transport: {}", context.config.server.transport.as_str()),
],
json!({
"runtime_version": env!("CARGO_PKG_VERSION"),
"invoked_as": context.invoked_as,
"config_name": context.config_name,
"server": context.config.server,
}),
),
}
}
fn help_report(
output_format: OutputFormat,
context: &AppContext,
error: clap::Error,
) -> ExecutionReport {
let help_text = error.to_string();
let lines = help_text.lines().map(ToOwned::to_owned).collect::<Vec<_>>();
ExecutionReport {
output_format,
output: CommandOutput::new(
&context.config_name,
"help",
format!("showing help for {}", context.invoked_as),
lines,
json!({
"invoked_as": context.invoked_as,
"config_name": context.config_name,
"help": help_text,
}),
),
}
}
async fn execute_domain_command(
command: BridgeDomainCommand,
output_format: OutputFormat,
context: AppContext,
) -> Result<ExecutionReport> {
enforce_cached_capability_support(&context, &command).await?;
let output = match command {
BridgeDomainCommand::Discover { category } => execute_discover(&context, category).await?,
BridgeDomainCommand::Invoke {
capability,
arguments,
background,
} => execute_invoke(&context, capability, arguments, background).await?,
BridgeDomainCommand::Read { uri } => execute_read(&context, uri).await?,
BridgeDomainCommand::List {
capability,
limit,
cursor,
page_size,
all,
} => {
let effective_limit = if all { None } else { page_size.or(limit) };
list_command_output(&context, &capability, effective_limit, cursor).await?
}
BridgeDomainCommand::Prompt { name, arguments } => {
execute_prompt(&context, name, arguments).await?
}
BridgeDomainCommand::AuthLogin => auth_login(&context).await?,
BridgeDomainCommand::AuthLogout => auth_logout(&context).await?,
BridgeDomainCommand::AuthStatus => auth_status(&context).await?,
BridgeDomainCommand::JobsList => execute_jobs_list(&context).await?,
BridgeDomainCommand::JobsShow { selector } => execute_jobs_show(&context, selector).await?,
BridgeDomainCommand::JobsWait { selector } => execute_jobs_wait(&context, selector).await?,
BridgeDomainCommand::JobsCancel { selector } => {
execute_jobs_cancel(&context, selector).await?
}
BridgeDomainCommand::JobsWatch { selector } => {
execute_jobs_watch(&context, selector).await?
}
BridgeDomainCommand::Doctor => execute_doctor(&context).await?,
BridgeDomainCommand::Inspect => execute_inspect(&context).await?,
};
Ok(ExecutionReport {
output_format,
output,
})
}
/// Main entry point: parse CLI, resolve domain command, execute.
pub async fn execute(argv: &[OsString], context: AppContext) -> Result<ExecutionReport> {
let output_format = crate::output::detect_output_format(argv, context.config.defaults.output);
if requests_version(argv) {
return Ok(version_report(output_format, &context));
}
// Try dynamic surface first if we have cached inventory
if let Some(inventory) = context
.services
.state_store
.discovery_inventory_view(&context.config_name)
.await
{
let mut manifest = super::manifest::CommandManifest::from_inventory(&inventory);
let server_display = context.config.server.display_name.as_str();
// Apply profile overlay if configured
if let Some(profile) = &context.config.profile {
manifest.apply_profile(profile);
}
match super::dynamic::parse_dynamic(argv, &context.invoked_as, &manifest, server_display) {
Ok(super::dynamic::DynamicParseResult {
command: super::dynamic::DynamicCommand::LegacyBridge,
..
}) => {
// Fall through to static bridge parser below
}
Ok(super::dynamic::DynamicParseResult {
command: cmd,
output_format: dyn_format,
timeout,
non_interactive,
input_json,
}) => {
let mut context = context.clone();
if let Some(t) = timeout {
context.timeout_override = Some(t);
}
apply_ci_flags(&mut context, non_interactive, input_json.as_deref())?;
match super::dynamic::execute_dynamic(cmd, dyn_format, &context).await {
Ok(report) => return Ok(report),
Err(e) if e.to_string() == "__delegate_to_bridge__" => {
// Runtime commands (auth, jobs, doctor, inspect) —
// fall through to static bridge
}
Err(e) => return Err(e),
}
}
Err(err) => {
// A `--help`/`--version` request against the dynamic surface is
// rendered here. Falling through to the static bridge (which
// lacks dynamic-only commands like `ls`/`ping`/`log`/`complete`/
// `subscribe`) would otherwise print a misleading
// "unrecognized subcommand" error for those.
match err.downcast::<clap::Error>() {
Ok(clap_error)
if matches!(
clap_error.kind(),
ErrorKind::DisplayHelp
| ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
| ErrorKind::DisplayVersion
) =>
{
return Ok(help_report(output_format, &context, clap_error));
}
// Any other parse failure falls through to the static bridge.
_ => {}
}
}
}
}
// Static bridge parser (always available, backward-compatible)
let cli = match parse_bridge_cli(argv, &context.invoked_as) {
Ok(cli) => cli,
Err(error)
if matches!(
error.kind(),
ErrorKind::DisplayHelp | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
) =>
{
return Ok(help_report(output_format, &context, error));
}
Err(error) => return Err(error.into()),
};
let output_format = cli.effective_output(context.config.defaults.output);
let mut context = context;
if let Some(timeout) = cli.timeout {
context.timeout_override = Some(timeout);
}
apply_ci_flags(&mut context, cli.non_interactive, cli.input_json.as_deref())?;
let domain_command = map_command(&cli.command)?;
execute_domain_command(domain_command, output_format, context).await
}
/// Thread the CI-mode flags (`--non-interactive`, `--input-json`) onto the
/// context and install the process-wide interaction config the elicitation
/// handler reads. Parses `--input-json` once so an invalid payload fails fast
/// with a clear message rather than deep inside an operation.
fn apply_ci_flags(
context: &mut AppContext,
non_interactive: bool,
input_json: Option<&str>,
) -> Result<()> {
context.non_interactive = non_interactive;
context.input_json = match input_json {
Some(raw) => Some(
serde_json::from_str(raw)
.map_err(|error| anyhow!("--input-json is not valid JSON: {}", error))?,
),
None => None,
};
crate::mcp::handler::set_interaction_config(crate::mcp::handler::InteractionConfig {
non_interactive: context.non_interactive,
input_json: context.input_json.clone(),
});
Ok(())
}
/// Peek at the output format from argv without full parsing.
pub fn peek_output_format(argv: &[OsString], default_format: OutputFormat) -> OutputFormat {
crate::output::detect_output_format(argv, default_format)
}
fn requests_version(argv: &[OsString]) -> bool {
argv.iter()
.skip(1)
.filter_map(|value| value.to_str())
.any(|token| matches!(token, "-V" | "--version"))
}
async fn command_output_for_action(
command: &str,
result: McpOperationResult,
context: &AppContext,
) -> Result<CommandOutput> {
match result {
McpOperationResult::Action { message, data } => {
let descriptor = context
.services
.state_store
.discovery_inventory_view(&context.config_name)
.await
.and_then(|inventory| {
data.get("capability")
.and_then(Value::as_str)
.and_then(|capability| {
lookup_inventory_item(inventory.tools.as_deref(), capability, |item| {
item.get("id").and_then(Value::as_str)
})
})
});
let mut lines = cached_descriptor_lines(descriptor.as_ref());
lines.push(
data.get("summary")
.and_then(Value::as_str)
.unwrap_or("operation completed")
.to_owned(),
);
Ok(CommandOutput::new(
&context.config_name,
command,
message,
lines,
cached_descriptor_data(data, descriptor.as_ref()),
))
}
McpOperationResult::TaskAccepted {
message,
remote_task_id,
detail,
} => {
let job = context
.services
.state_store
.create_job(
&context.config_name,
&context.config_name,
command,
detail
.get("summary")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
remote_task_id,
)
.await?;
context.services.event_broker.emit(RuntimeEvent::JobUpdate {
app_id: context.config_name.clone(),
job_id: job.job_id.clone(),
status: JobStatus::Queued.as_str().to_owned(),
message: format!("created background job for {}", command),
});
Ok(CommandOutput::new(
&context.config_name,
command,
message,
vec![
format!("job: {}", job.job_id),
format!("status: {}", job.status.as_str()),
],
json!({ "job": job, "detail": detail }),
))
}
other => Err(anyhow!(
"unexpected MCP response for {}: {}",
command,
serde_json::to_string(&other)?
)),
}
}
fn map_command(command: &BridgeCommand) -> Result<BridgeDomainCommand> {
match command {
// -- primary domain-shaped commands --
BridgeCommand::Tool(args) => match &args.command {
ToolCommand::List(list_args) => Ok(BridgeDomainCommand::List {
capability: match &list_args.filter {
Some(f) => format!("tools.{}", f),
None => "tools".to_owned(),
},
limit: list_args.limit,
cursor: list_args.cursor.clone(),
page_size: None,
all: list_args.all,
}),
ToolCommand::Call(call_args) => Ok(BridgeDomainCommand::Invoke {
capability: call_args.name.clone(),
arguments: build_structured_arguments(
&call_args.args,
&call_args.json_args,
call_args.args_json.as_deref(),
call_args.args_file.as_deref(),
)?,
background: call_args.background,
}),
},
BridgeCommand::Resource(args) => match &args.command {
ResourceCommand::List(list_args) => Ok(BridgeDomainCommand::List {
capability: match &list_args.filter {
Some(f) => format!("resources.{}", f),
None => "resources".to_owned(),
},
limit: list_args.limit,
cursor: list_args.cursor.clone(),
page_size: None,
all: list_args.all,
}),
ResourceCommand::Read(read_args) => Ok(BridgeDomainCommand::Read {
uri: read_args.uri.clone(),
}),
},
BridgeCommand::Prompt(args) => match &args.command {
PromptCommand::List(list_args) => Ok(BridgeDomainCommand::List {
capability: match &list_args.filter {
Some(f) => format!("prompts.{}", f),
None => "prompts".to_owned(),
},
limit: list_args.limit,
cursor: list_args.cursor.clone(),
page_size: None,
all: list_args.all,
}),
PromptCommand::Run(run_args) => Ok(BridgeDomainCommand::Prompt {
name: run_args.name.clone(),
arguments: build_structured_arguments(
&run_args.args,
&run_args.json_args,
run_args.args_json.as_deref(),
run_args.args_file.as_deref(),
)?,
}),
},
BridgeCommand::Auth(args) => Ok(match args.command {
AuthCommand::Login => BridgeDomainCommand::AuthLogin,
AuthCommand::Logout => BridgeDomainCommand::AuthLogout,
AuthCommand::Status => BridgeDomainCommand::AuthStatus,
}),
BridgeCommand::Jobs(args) => Ok(match &args.command {
JobsCommand::List => BridgeDomainCommand::JobsList,
JobsCommand::Show(job) => BridgeDomainCommand::JobsShow {
selector: job_selector(job),
},
JobsCommand::Wait(job) => BridgeDomainCommand::JobsWait {
selector: job_selector(job),
},
JobsCommand::Cancel(job) => BridgeDomainCommand::JobsCancel {
selector: job_selector(job),
},
JobsCommand::Watch(job) => BridgeDomainCommand::JobsWatch {
selector: job_selector(job),
},
}),
BridgeCommand::Doctor => Ok(BridgeDomainCommand::Doctor),
BridgeCommand::Inspect => Ok(BridgeDomainCommand::Inspect),
// -- backward-compatible legacy aliases --
BridgeCommand::Discover(args) => Ok(BridgeDomainCommand::Discover {
category: match args.command {
DiscoverCommand::Capabilities => DiscoveryCategory::Capabilities,
DiscoverCommand::Resources => DiscoveryCategory::Resources,
DiscoverCommand::Prompts => DiscoveryCategory::Prompts,
},
}),
BridgeCommand::Invoke(args) => Ok(BridgeDomainCommand::Invoke {
capability: args.capability.clone(),
arguments: build_invoke_arguments(args)?,
background: args.background,
}),
BridgeCommand::Read(args) => Ok(BridgeDomainCommand::Read {
uri: args.uri.clone(),
}),
BridgeCommand::List(args) => Ok(BridgeDomainCommand::List {
capability: args.capability.clone(),
cursor: args.cursor.clone(),
page_size: args.page_size,
all: args.all,
limit: args.limit,
}),
}
}
fn is_demo_config(config: &crate::config::AppConfig) -> bool {
matches!(config.server.transport, TransportKind::StreamableHttp)
&& config
.server
.endpoint
.as_deref()
.and_then(|value| url::Url::parse(value).ok())
.and_then(|url| url.host_str().map(str::to_owned))
.map(|host| host.eq_ignore_ascii_case("demo.invalid"))
.unwrap_or(false)
}
// ---------------------------------------------------------------------------
// Domain command implementations (extracted from execute_domain_command)
// ---------------------------------------------------------------------------
async fn execute_discover(
context: &AppContext,
category: DiscoveryCategory,
) -> Result<CommandOutput> {
let result = context
.perform(McpOperation::Discover {
category: category.clone(),
})
.await;
match result {
Ok(McpOperationResult::Discovery {
message,
category,
items,
}) => {
context
.services
.state_store
.upsert_discovery_inventory(
&context.config_name,
&context.config_name,
category.clone(),
items.clone(),
)
.await?;
Ok(CommandOutput::new(
&context.config_name,
"discover",
message,
discovery_output_lines(&category, &items),
json!({
"category": category,
"items": items,
}),
))
}
Ok(other) => Err(anyhow!(
"unexpected MCP response for discover: {}",
serde_json::to_string(&other)?
)),
Err(error) => {
let Some(output) =
cached_discovery_output_from_state(context, &category, &error.to_string()).await
else {
return Err(error);
};
context.services.event_broker.emit(RuntimeEvent::Info {
app_id: context.config_name.clone(),
message: format!(
"live discover {} failed; returned cached inventory instead",
category.as_str()
),
});
Ok(output)
}
}
}
async fn execute_invoke(
context: &AppContext,
capability: String,
arguments: Value,
background: bool,
) -> Result<CommandOutput> {
context.services.event_broker.emit(RuntimeEvent::Info {
app_id: context.config_name.clone(),
message: format!("invoking capability {}", capability),
});
let result = context
.perform(McpOperation::InvokeAction {
capability,
arguments,
background,
})
.await?;
command_output_for_action("invoke", result, context).await
}
async fn execute_read(context: &AppContext, uri: String) -> Result<CommandOutput> {
let result = context
.perform(McpOperation::ReadResource { uri: uri.clone() })
.await?;
match result {
McpOperationResult::Resource {
message,
uri,
mime_type,
text,
data,
} => {
let descriptor = context
.services
.state_store
.discovery_inventory_view(&context.config_name)
.await