Repository navigation
Expand file tree
/
Copy pathupstream_cmd.go
More file actions
2792 lines (2459 loc) · 95.6 KB
/
Copy pathupstream_cmd.go
File metadata and controls
2792 lines (2459 loc) · 95.6 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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sort"
"strings"
"syscall"
"time"
"github.com/spf13/cobra"
"go.uber.org/zap"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/cli/output"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/cliclient"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/configimport"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/health"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/logs"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/reqcontext"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/secret"
)
var (
upstreamCmd = &cobra.Command{
Use: "upstream",
Short: "Manage upstream MCP servers",
Long: "Commands for managing and monitoring upstream MCP servers",
}
upstreamListCmd = &cobra.Command{
Use: "list",
Short: "List all upstream servers with status",
Long: `List all configured upstream MCP servers with connection status, tool counts, and errors.
Examples:
mcpproxy upstream list
mcpproxy upstream list --output=json
mcpproxy upstream list --log-level=debug`,
RunE: runUpstreamList,
}
upstreamLogsCmd = &cobra.Command{
Use: "logs [server-name]",
Short: "Show logs for a specific server",
Long: `Display recent log entries from a specific upstream server.
Examples:
mcpproxy upstream logs --server github-server
mcpproxy upstream logs --server github-server --tail=100
mcpproxy upstream logs weather-api --follow`,
Args: cobra.MaximumNArgs(1),
RunE: runUpstreamLogs,
}
upstreamEnableCmd = &cobra.Command{
Use: "enable [server-name]",
Short: "Enable a server",
Args: cobra.MaximumNArgs(1),
RunE: runUpstreamEnable,
}
upstreamDisableCmd = &cobra.Command{
Use: "disable [server-name]",
Short: "Disable a server",
Args: cobra.MaximumNArgs(1),
RunE: runUpstreamDisable,
}
upstreamRestartCmd = &cobra.Command{
Use: "restart [server-name]",
Short: "Restart a server",
Args: cobra.MaximumNArgs(1),
RunE: runUpstreamRestart,
}
upstreamAddCmd = &cobra.Command{
Use: "add <name> [url] [-- command args...]",
Short: "Add an upstream MCP server",
Long: `Add a new upstream MCP server to the configuration.
For HTTP-based servers:
mcpproxy upstream add notion https://mcp.notion.com/sse
mcpproxy upstream add weather https://api.weather.com/mcp --header "Authorization: Bearer token"
For stdio-based servers (use -- to separate command):
mcpproxy upstream add fs -- npx -y @anthropic/mcp-server-filesystem /path/to/dir
mcpproxy upstream add sqlite -- uvx mcp-server-sqlite --db mydb.db
New servers are quarantined by default for security. Review and admit one
without leaving the CLI:
mcpproxy review fetch <name> # capture its tool definitions (if none yet)
mcpproxy review show <name> # inspect the tools and scan verdicts
mcpproxy security scan <name> # scan it (approval needs a scan result)
mcpproxy security report <name> # read the scan report
mcpproxy review approve <name> --yes # admit it ('mcpproxy security approve <name>' is an alias)
The Web UI and macOS app offer the same review screen.`,
RunE: runUpstreamAdd,
}
upstreamRemoveCmd = &cobra.Command{
Use: "remove <name>",
Short: "Remove an upstream MCP server",
Long: `Remove an upstream MCP server from the configuration.
Examples:
mcpproxy upstream remove notion
mcpproxy upstream remove fs --yes # Skip confirmation`,
Args: cobra.ExactArgs(1),
RunE: runUpstreamRemove,
}
upstreamAddJSONCmd = &cobra.Command{
Use: "add-json <name> <json>",
Short: "Add an upstream server using JSON configuration",
Long: `Add a new upstream MCP server using a JSON configuration object.
Examples:
mcpproxy upstream add-json weather '{"url":"https://api.weather.com/mcp","headers":{"Authorization":"Bearer token"}}'
mcpproxy upstream add-json sqlite '{"command":"uvx","args":["mcp-server-sqlite","--db","mydb.db"]}'`,
Args: cobra.ExactArgs(2),
RunE: runUpstreamAddJSON,
}
upstreamPatchCmd = &cobra.Command{
Use: "patch <name>",
Short: "Update headers / env on an existing upstream server",
Long: `Update HTTP headers and stdio environment variables on an existing upstream server.
The PATCH endpoint uses JSON Merge Patch semantics: keys you specify are
upserted, keys you delete with -remove flags are explicitly removed, and
every other key on the stored config is preserved. So you can safely
rotate a single header without seeing or touching the rest — including
sensitive values the backend redacts from list / inspect responses.
Examples:
# rotate the Authorization header on the synapbus server
mcpproxy upstream patch synapbus --header "Authorization: Bearer new-token"
# add a custom header without disturbing existing ones
mcpproxy upstream patch synapbus --header "X-Trace: on"
# remove a header
mcpproxy upstream patch synapbus --header-remove "X-Stale"
# set + remove in a single round-trip
mcpproxy upstream patch synapbus --header "X-New: v" --header-remove "X-Old"
# update env vars on a stdio server
mcpproxy upstream patch obsidian-pilot --env "LOG_LEVEL=debug" --env-remove "OLD_VAR"
Flags are repeatable. The corresponding null in the JSON Merge Patch body
is constructed automatically — you never have to think about wire format.`,
Args: cobra.ExactArgs(1),
RunE: runUpstreamPatch,
}
upstreamInspectCmd = &cobra.Command{
Use: "inspect <server-name>",
Short: "Inspect tool approval status for a server",
Long: `Show tool-level quarantine status for all tools on a server.
Displays approval status, hashes, and any detected description/schema changes.
Examples:
mcpproxy upstream inspect github
mcpproxy upstream inspect github --output=json
mcpproxy upstream inspect github --tool create_issue`,
Args: cobra.ExactArgs(1),
RunE: runUpstreamInspect,
}
upstreamApproveCmd = &cobra.Command{
Use: "approve <server-name> [tool-names...]",
Short: "Approve quarantined tools for a server",
Long: `Approve pending or changed tools so they can be used by AI agents.
Without specific tool names, approves all pending/changed tools. This legacy
command remains available; use 'mcpproxy review approve <server> --tools ...'
for the unified review workflow.
Examples:
mcpproxy upstream approve github # Approve all tools
mcpproxy upstream approve github create_issue list_repos # Approve specific tools`,
Args: cobra.MinimumNArgs(1),
RunE: runUpstreamApprove,
}
// Per-tool enable/disable. The "tools" subcommand groups the four
// operations so the surface mirrors the server-level
// "upstream enable/disable" + "upstream enable --all/--all" without
// shadowing those flags.
upstreamToolsCmd = &cobra.Command{
Use: "tools",
Short: "Manage per-tool enable/disable state for a server",
Long: `Enable or disable individual tools (or all tools) of an upstream server.
Disabled tools are filtered out of retrieve_tools results and rejected on
direct call_tool_* invocations. Use this to suppress noisy or unused tools
without removing the whole server.`,
}
upstreamToolsEnableCmd = &cobra.Command{
Use: "enable <server-name> <tool-name>",
Short: "Enable a tool for a server",
Args: cobra.ExactArgs(2),
RunE: func(_ *cobra.Command, args []string) error { return runUpstreamToolAction(args[0], args[1], true) },
}
upstreamToolsDisableCmd = &cobra.Command{
Use: "disable <server-name> <tool-name>",
Short: "Disable a tool for a server",
Args: cobra.ExactArgs(2),
RunE: func(_ *cobra.Command, args []string) error { return runUpstreamToolAction(args[0], args[1], false) },
}
upstreamToolsEnableAllCmd = &cobra.Command{
Use: "enable-all <server-name>",
Short: "Enable every tool for a server",
Args: cobra.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error { return runUpstreamToolBulkAction(args[0], true) },
}
upstreamToolsDisableAllCmd = &cobra.Command{
Use: "disable-all <server-name>",
Short: "Disable every tool for a server",
Args: cobra.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error { return runUpstreamToolBulkAction(args[0], false) },
}
upstreamImportCmd = &cobra.Command{
Use: "import <path>",
Short: "Import servers from external configuration file",
Long: `Import MCP server configurations from Claude Desktop, Claude Code, Cursor IDE, Codex CLI, or Gemini CLI.
Supported formats:
- Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json
- Claude Code: .claude/settings.json or .claude.json
- Cursor IDE: ~/.cursor/mcp.json
- Codex CLI: ~/.codex/config.toml
- Gemini CLI: ~/.gemini/settings.json
The format is auto-detected from file content. Imported servers are quarantined by default.
Use --no-quarantine to skip quarantine for trusted configs.
Examples:
# Import all servers from Claude Desktop config
mcpproxy upstream import ~/Library/Application\ Support/Claude/claude_desktop_config.json
# Preview import without making changes
mcpproxy upstream import --dry-run ~/Library/Application\ Support/Claude/claude_desktop_config.json
# Import specific server by name
mcpproxy upstream import --server github ~/.cursor/mcp.json
# Force format detection
mcpproxy upstream import --format claude-desktop config.json
# Import without quarantine (trusted configs)
mcpproxy upstream import --no-quarantine ~/Library/Application\ Support/Claude/claude_desktop_config.json`,
Args: cobra.ExactArgs(1),
RunE: runUpstreamImport,
}
// Command flags
upstreamLogLevel string
upstreamConfigPath string
upstreamLogsTail int
upstreamLogsFollow bool
upstreamAll bool
upstreamForce bool
upstreamServerName string
// upstreamListStatus is FR-015: --status <value> is repeatable, and a
// comma-separated value is equivalent to repeating the flag (StringArrayVar
// preserves each raw token, so we split on "," ourselves in the filter).
upstreamListStatus []string
// Add command flags
upstreamAddHeaders []string
upstreamAddEnvs []string
upstreamAddWorkingDir string
upstreamAddTransport string
upstreamAddIfNotExists bool
upstreamAddNoQuarantine bool
upstreamAddTrustMode string
// upstreamAddSecretEnvs/Headers are the Spec 109 FR-065 secret flags:
// each value is written to the OS keyring under the FR-065 ref name
// (internal/secret.RefName) and the config gets ${keyring:<ref>} instead
// of the raw value.
upstreamAddSecretEnvs []string
upstreamAddSecretHeaders []string
// Remove command flags
upstreamRemoveYes bool
upstreamRemoveIfExists bool
// Inspect command flags
upstreamInspectTool string
// Patch command flags
upstreamPatchHeaders []string
upstreamPatchHeaderRemove []string
upstreamPatchEnvs []string
upstreamPatchEnvRemove []string
upstreamPatchInitTimeout string
// Import command flags
upstreamImportServer string
upstreamImportFormat string
upstreamImportDryRun bool
upstreamImportNoQuarantine bool
)
// GetUpstreamCommand returns the upstream command for adding to the root command.
// The upstream command provides subcommands for managing and monitoring upstream
// MCP servers, including list, logs, enable/disable, and restart operations.
func GetUpstreamCommand() *cobra.Command {
return upstreamCmd
}
func init() {
// Add subcommands
upstreamCmd.AddCommand(upstreamListCmd)
upstreamCmd.AddCommand(upstreamLogsCmd)
upstreamCmd.AddCommand(upstreamEnableCmd)
upstreamCmd.AddCommand(upstreamDisableCmd)
upstreamCmd.AddCommand(upstreamRestartCmd)
upstreamCmd.AddCommand(upstreamAddCmd)
upstreamCmd.AddCommand(upstreamRemoveCmd)
upstreamCmd.AddCommand(upstreamAddJSONCmd)
upstreamCmd.AddCommand(upstreamPatchCmd)
upstreamCmd.AddCommand(upstreamInspectCmd)
upstreamCmd.AddCommand(upstreamApproveCmd)
upstreamCmd.AddCommand(upstreamImportCmd)
upstreamCmd.AddCommand(upstreamToolsCmd)
upstreamToolsCmd.AddCommand(upstreamToolsEnableCmd)
upstreamToolsCmd.AddCommand(upstreamToolsDisableCmd)
upstreamToolsCmd.AddCommand(upstreamToolsEnableAllCmd)
upstreamToolsCmd.AddCommand(upstreamToolsDisableAllCmd)
// Define flags (note: output format handled by global --output/-o flag from root command)
upstreamListCmd.Flags().StringVar(&upstreamListProfile, "profile", "", "Show only the servers of this profile's effective server set; TOOLS is the number of tools visible under it (Spec 108)")
upstreamListCmd.Flags().StringVarP(&upstreamLogLevel, "log-level", "l", "warn", "Log level (trace, debug, info, warn, error)")
addConfigFlag(upstreamListCmd.Flags(), &upstreamConfigPath, "Path to MCP configuration file")
upstreamListCmd.Flags().StringArrayVar(&upstreamListStatus, "status", nil,
"Filter by health status (repeatable; a comma-separated value is equivalent to repeating the flag): "+
"ready, connecting, sign_in_required, needs_review, needs_secret, needs_config, error, disabled")
upstreamLogsCmd.Flags().IntVarP(&upstreamLogsTail, "tail", "n", 50, "Number of log lines to show")
upstreamLogsCmd.Flags().BoolVarP(&upstreamLogsFollow, "follow", "f", false, "Follow log output (requires daemon)")
upstreamLogsCmd.Flags().StringVarP(&upstreamLogLevel, "log-level", "l", "warn", "Log level")
addConfigFlag(upstreamLogsCmd.Flags(), &upstreamConfigPath, "Path to config file")
upstreamLogsCmd.Flags().StringVarP(&upstreamServerName, "server", "s", "", "Name of the upstream server")
// Add --all and --force flags to enable/disable/restart
upstreamEnableCmd.Flags().BoolVar(&upstreamAll, "all", false, "Enable all servers")
upstreamEnableCmd.Flags().BoolVar(&upstreamForce, "force", false, "Skip confirmation prompt")
upstreamEnableCmd.Flags().StringVarP(&upstreamServerName, "server", "s", "", "Name of the upstream server (required unless --all)")
upstreamDisableCmd.Flags().BoolVar(&upstreamAll, "all", false, "Disable all servers")
upstreamDisableCmd.Flags().BoolVar(&upstreamForce, "force", false, "Skip confirmation prompt")
upstreamDisableCmd.Flags().StringVarP(&upstreamServerName, "server", "s", "", "Name of the upstream server (required unless --all)")
upstreamRestartCmd.Flags().BoolVar(&upstreamAll, "all", false, "Restart all servers")
upstreamRestartCmd.Flags().StringVarP(&upstreamServerName, "server", "s", "", "Name of the upstream server (required unless --all)")
// Add command flags
upstreamAddCmd.Flags().StringArrayVar(&upstreamAddHeaders, "header", nil, "HTTP header in 'Name: value' format (repeatable)")
upstreamAddCmd.Flags().StringArrayVar(&upstreamAddEnvs, "env", nil, "Environment variable in KEY=value format (repeatable)")
upstreamAddCmd.Flags().StringVar(&upstreamAddWorkingDir, "working-dir", "", "Working directory for stdio commands")
upstreamAddCmd.Flags().StringVar(&upstreamAddTransport, "transport", "", "Transport type: http or stdio (auto-detected if not specified)")
upstreamAddCmd.Flags().BoolVar(&upstreamAddIfNotExists, "if-not-exists", false, "Don't error if server already exists")
upstreamAddCmd.Flags().BoolVar(&upstreamAddNoQuarantine, "no-quarantine", false, "Don't quarantine the new server (use with caution)")
upstreamAddCmd.Flags().StringVar(&upstreamAddTrustMode, "trust-mode", "", "Per-server trust tier governing admission AND tool-change approval: auto (approve without scanning), scan (auto-approve new tools only when the offline TPA scan is green; changed tools are held for review), manual (human reviews every change). Unset inherits the default (manual)")
upstreamAddCmd.Flags().StringArrayVar(&upstreamAddSecretEnvs, "secret-env", nil, "Environment variable to store in the OS keyring instead of the config, in KEY=value format (repeatable, FR-065)")
upstreamAddCmd.Flags().StringArrayVar(&upstreamAddSecretHeaders, "secret-header", nil, "HTTP header to store in the OS keyring instead of the config, in 'Name: value' format (repeatable, FR-065)")
// Remove command flags
upstreamRemoveCmd.Flags().BoolVar(&upstreamRemoveYes, "yes", false, "Skip confirmation prompt")
upstreamRemoveCmd.Flags().BoolVarP(&upstreamRemoveYes, "y", "y", false, "Skip confirmation prompt (short form)")
upstreamRemoveCmd.Flags().BoolVar(&upstreamRemoveIfExists, "if-exists", false, "Don't error if server doesn't exist")
// Patch command flags
upstreamPatchCmd.Flags().StringArrayVar(&upstreamPatchHeaders, "header", nil, "HTTP header to upsert in 'Name: value' format (repeatable)")
upstreamPatchCmd.Flags().StringArrayVar(&upstreamPatchHeaderRemove, "header-remove", nil, "HTTP header name to delete (repeatable)")
upstreamPatchCmd.Flags().StringArrayVar(&upstreamPatchEnvs, "env", nil, "Environment variable to upsert in KEY=value format (repeatable)")
upstreamPatchCmd.Flags().StringArrayVar(&upstreamPatchEnvRemove, "env-remove", nil, "Environment variable name to delete (repeatable)")
upstreamPatchCmd.Flags().StringVar(&upstreamPatchInitTimeout, "init-timeout", "", "MCP initialize handshake deadline as a duration (e.g. '120s', '3m'); raise for upstreams that warm up before responding to initialize")
// Inspect command flags
upstreamInspectCmd.Flags().StringVar(&upstreamInspectTool, "tool", "", "Show details for a specific tool")
// Import command flags
upstreamImportCmd.Flags().StringVarP(&upstreamImportServer, "server", "s", "", "Import only a specific server by name")
upstreamImportCmd.Flags().StringVar(&upstreamImportFormat, "format", "", "Force format (claude-desktop, claude-code, cursor, codex, gemini)")
upstreamImportCmd.Flags().BoolVar(&upstreamImportDryRun, "dry-run", false, "Preview import without making changes")
upstreamImportCmd.Flags().BoolVar(&upstreamImportNoQuarantine, "no-quarantine", false, "Don't quarantine imported servers (use with caution)")
}
func runUpstreamList(_ *cobra.Command, _ []string) error {
// Refuse a typo'd/miscased --status up front rather than silently
// returning an empty table (GH #938-style validation for FR-015).
if err := validateStatusFlag(upstreamListStatus); err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Load configuration
globalConfig, err := loadUpstreamConfig()
if err != nil {
return outputError(output.NewStructuredError(output.ErrCodeConfigNotFound, err.Error()).
WithGuidance("Check that your config file exists and is valid").
WithRecoveryCommand("mcpproxy doctor"), output.ErrCodeConfigNotFound)
}
// Create logger
logger, err := createUpstreamLogger(upstreamLogLevel)
if err != nil {
return outputError(err, output.ErrCodeOperationFailed)
}
// Check if daemon is running (socket first, then TCP fallback)
if client, ok := newDaemonClient(globalConfig, logger.Sugar()); ok {
logger.Info("Detected running daemon, using client mode")
return runUpstreamListClientMode(ctx, client, logger)
}
if upstreamListProfile != "" {
return outputError(output.NewStructuredError(output.ErrCodeConnectionFailed,
"--profile needs the running daemon: profile scope and tool visibility are resolved there").
WithGuidance("Start the daemon and retry").
WithRecoveryCommand("mcpproxy serve"), output.ErrCodeConnectionFailed)
}
// No daemon - load from config file
logger.Info("No daemon detected, reading from config file")
return runUpstreamListFromConfig(globalConfig)
}
// upstreamListProfile is `upstream list --profile` (Spec 108 FR-032): the REST
// `profile` filter on GET /api/v1/servers.
var upstreamListProfile string
// upstreamListQuery is the REST query of the list flags.
func upstreamListQuery() url.Values {
q := url.Values{}
if upstreamListProfile != "" {
q.Set("profile", upstreamListProfile)
}
return q
}
func runUpstreamListClientMode(ctx context.Context, client *cliclient.Client, _ *zap.Logger) error {
// Call GET /api/v1/servers
servers, err := client.GetServersWithQuery(ctx, upstreamListQuery())
if err != nil {
return outputError(output.NewStructuredError(output.ErrCodeConnectionFailed, err.Error()).
WithGuidance("Ensure the mcpproxy daemon is running").
WithRecoveryCommand("mcpproxy serve"), output.ErrCodeConnectionFailed)
}
return outputServers(servers)
}
func runUpstreamListFromConfig(globalConfig *config.Config) error {
// Review finding (this round): the daemon-less path can only classify
// health.status for a disabled or quarantined server (StateDisabled /
// StatusNeedsReview short-circuit CalculateHealth before it ever looks at
// the synthetic "disconnected" connection state below); every other
// server's status is cleared to "" a few lines down so the STATUS column
// keeps the informative "Daemon not running" summary instead of a bogus
// "Error" (round-6 finding, see upstream_list_daemonless_test.go). But
// filterServersByStatus matches health.status exactly, so `--status
// ready|connecting|sign_in_required|needs_secret|needs_config|error`
// silently returns an empty (headers-only, exit 0) table for every
// enabled server when the daemon is down — indistinguishable from "no
// servers in that state", exactly the GH #938 failure mode
// validateStatusFlag's doc comment says it exists to prevent. Warn on
// stderr instead of fabricating a status this path cannot know; stdout
// output (including -o json/yaml) is untouched.
if statusFilterNeedsDaemon(upstreamListStatus) {
fmt.Fprintln(os.Stderr, "Notice: no mcpproxy daemon running — only 'disabled' and 'needs_review' statuses "+
"can be determined from the config file alone, so --status may return no rows for other values "+
"even though matching servers exist. Run 'mcpproxy serve' for accurate status.")
}
// Convert config servers to output format
servers := make([]map[string]interface{}, len(globalConfig.Servers))
for i, srv := range globalConfig.Servers {
// I-003: Use health.CalculateHealth() instead of inline logic for DRY principle
healthInput := health.HealthCalculatorInput{
Name: srv.Name,
Enabled: srv.Enabled,
Quarantined: srv.Quarantined,
State: "disconnected", // Daemon not running
Connected: false,
ToolCount: 0,
}
healthStatus := health.CalculateHealth(healthInput, health.DefaultHealthConfig())
// Override summary for config-only mode to indicate daemon status
summary := healthStatus.Summary
statusValue := healthStatus.Status
if healthStatus.AdminState == health.StateEnabled {
summary = "Daemon not running"
// Round-6 review finding: the synthetic State: "disconnected"
// input above always makes CalculateHealth set Status =
// StatusError too (a disconnected server with no LastError still
// resolves through connectionErrorStatus(ActionRestart) ==
// StatusError). upstreamServerRows's STATUS column renders
// health.StatusLabel(health.status) INSTEAD OF the free-text
// summary whenever health.status is non-empty (Spec 109 FR-015),
// so leaving it as "error" silently reverted the STATUS column
// from "Daemon not running" back to the generic "Error" for
// every enabled server. This daemon-less path cannot know the
// server's real connection status at all — clear it so
// upstreamServerRows falls back to the summary, matching
// pre-Spec-109 behavior. (`--status` filtering on an empty
// health.status already excludes these rows by design; see
// filterServersByStatus's own doc comment.)
statusValue = ""
}
servers[i] = map[string]interface{}{
"name": srv.Name,
"enabled": srv.Enabled,
"protocol": srv.Protocol,
"connected": false,
"tool_count": 0,
"status": summary,
"health": map[string]interface{}{
"level": healthStatus.Level,
"admin_state": healthStatus.AdminState,
"summary": summary,
"detail": healthStatus.Detail,
"action": healthStatus.Action,
"status": statusValue,
"usable": healthStatus.Usable,
"actions": healthStatus.Actions,
},
}
// Spec 086: surface the per-server trust tier in the daemon-less path
// too, so `mcpproxy upstream list -o json` reads back the same field
// whether or not the daemon is up. Omitted when never configured.
if srv.TrustMode != "" {
servers[i]["trust_mode"] = srv.TrustMode
}
}
return outputServers(servers)
}
func outputServers(servers []map[string]interface{}) error {
// FR-015: --status <value> is repeatable, and a comma-separated value is
// equivalent to repeating the flag; several values select the UNION of
// their statuses. Applies to every output format (table, json, yaml).
servers = filterServersByStatus(servers, upstreamListStatus)
// Sort servers alphabetically by name for consistent output
sort.Slice(servers, func(i, j int) bool {
nameI := getStringField(servers[i], "name")
nameJ := getStringField(servers[j], "name")
return nameI < nameJ
})
// Get the output formatter based on global flags
formatter, err := GetOutputFormatter()
if err != nil {
return output.NewStructuredError(output.ErrCodeInvalidOutputFormat, err.Error()).
WithGuidance("Use -o table, -o json, or -o yaml")
}
outputFormat := ResolveOutputFormat()
// For structured formats (json, yaml), output raw data
if outputFormat == "json" || outputFormat == "yaml" {
result, err := formatter.Format(servers)
if err != nil {
return fmt.Errorf("failed to format output: %w", err)
}
fmt.Println(result)
return nil
}
// For table format, build headers and rows with formatted data
headers := []string{"", "NAME", "PROTOCOL", "TOOLS", "STATUS", "ACTION"}
rows := upstreamServerRows(servers)
result, err := formatter.FormatTable(headers, rows)
if err != nil {
return fmt.Errorf("failed to format table: %w", err)
}
fmt.Print(result)
return nil
}
// validateTrustModeFlag refuses an unrecognized --trust-mode value up front
// (GH #938). Empty means "inherit the default"; matching is case-sensitive
// because the runtime fails closed to manual on anything else, so silently
// accepting "Scan" would leave the operator believing scanning is on.
func validateTrustModeFlag(mode string) error {
if config.IsValidTrustMode(mode) {
return nil
}
return newFlagValidationError("invalid --trust-mode %q: must be one of: %s (values are case-sensitive)",
mode, strings.Join(config.ValidTrustModes(), ", "))
}
// validateStatusFlag refuses an unrecognized --status value up front,
// mirroring validateTrustModeFlag (GH #938): without it, a typo'd or
// wrongly-cased value (e.g. `--status signin_required` or `--status READY`)
// matched nothing in filterServersByStatus and silently returned an empty
// result set (exit 0), indistinguishable from "no servers in that state".
// Accepts the same comma-separated-equals-repeated-flag shape
// filterServersByStatus does, and matching is case-sensitive because the
// vocabulary itself is (internal/health.StatusOrder, Spec 109 FR-015).
func validateStatusFlag(rawFilters []string) error {
valid := make(map[string]bool, len(health.StatusOrder))
for _, s := range health.StatusOrder {
valid[s] = true
}
for _, raw := range rawFilters {
for _, v := range strings.Split(raw, ",") {
v = strings.TrimSpace(v)
if v == "" {
// Deliberately accepted, not a gap: an empty segment (from
// `--status ""`, a trailing/leading comma, or `--status=$VAR`
// with an unset $VAR) contributes nothing to the filter, so
// filterServersByStatus falls back to its own "no filter"
// default — the same result as omitting --status entirely.
// This mirrors --trust-mode's "" = inherit-default contract
// (config.IsValidTrustMode); it does not silently narrow the
// result set the way an unrecognized status would.
continue
}
if !valid[v] {
return newFlagValidationError("invalid --status %q: must be one of: %s (values are case-sensitive)",
v, strings.Join(health.StatusOrder, ", "))
}
}
}
return nil
}
// statusFilterNeedsDaemon reports whether a --status filter contains any
// value the daemon-less config-only path (runUpstreamListFromConfig) cannot
// resolve on its own. Only "disabled" and health.StatusNeedsReview short-
// circuit CalculateHealth before the synthetic "disconnected" state comes
// into play, so those two are safe without a daemon; every other value in the
// vocabulary depends on a live connection state runUpstreamListFromConfig
// deliberately clears to "" (see its own comment).
func statusFilterNeedsDaemon(rawFilters []string) bool {
resolvableWithoutDaemon := map[string]bool{
health.StatusDisabled: true,
health.StatusNeedsReview: true,
}
for _, raw := range rawFilters {
for _, v := range strings.Split(raw, ",") {
v = strings.TrimSpace(v)
if v == "" {
continue
}
if !resolvableWithoutDaemon[v] {
return true
}
}
}
return false
}
// serverHealthStatus extracts a server row's `health.status` value (the
// Spec 109 status vocabulary), or "" when absent (e.g. a payload from an
// older core that predates FR-010).
func serverHealthStatus(srv map[string]interface{}) string {
healthData, ok := srv["health"].(map[string]interface{})
if !ok {
return ""
}
return getStringField(healthData, "status")
}
// filterServersByStatus is FR-015: `--status <value>` is repeatable, and a
// comma-separated value is equivalent to repeating the flag — several values
// select the UNION of their statuses. An empty filter (`--status` omitted)
// returns every server unchanged. A server with no `health.status` (an older
// core) never matches a filter, so an operator's `--status` never silently
// hides it in a mixed-version fleet by exclusion; it just doesn't sort into
// any bucket.
func filterServersByStatus(servers []map[string]interface{}, rawFilters []string) []map[string]interface{} {
if len(rawFilters) == 0 {
return servers
}
wanted := make(map[string]bool)
for _, raw := range rawFilters {
for _, v := range strings.Split(raw, ",") {
v = strings.TrimSpace(v)
if v != "" {
wanted[v] = true
}
}
}
if len(wanted) == 0 {
return servers
}
filtered := make([]map[string]interface{}, 0, len(servers))
for _, srv := range servers {
if wanted[serverHealthStatus(srv)] {
filtered = append(filtered, srv)
}
}
return filtered
}
// serverHoldSummary reports whether any of a server's tools need human review
// (count > 0 is the trigger — a record can be both blocked and pending, so the
// number is not an exact tool total) plus a short label naming the breakdown.
//
// GH #938 finding 3: the quarantine counts have always been in the
// GET /api/v1/servers payload (contracts.QuarantineStats) but `upstream list`
// dropped them, so a server whose only tool was held by the scan gate still
// rendered a green "✅ Connected (1 tool)". Blocked (disabled) tools are
// included because they are equally invisible in the connected/tool-count view.
func serverHoldSummary(srv map[string]interface{}) (count int, label string) {
q, ok := srv["quarantine"].(map[string]interface{})
if !ok {
return 0, ""
}
pending := getIntField(q, "pending_count")
changed := getIntField(q, "changed_count")
blocked := getIntField(q, "blocked_count")
var parts []string
if pending > 0 {
parts = append(parts, fmt.Sprintf("%d pending", pending))
}
if changed > 0 {
parts = append(parts, fmt.Sprintf("%d changed", changed))
}
if blocked > 0 {
parts = append(parts, fmt.Sprintf("%d blocked", blocked))
}
if len(parts) == 0 {
return 0, ""
}
return pending + changed + blocked, strings.Join(parts, ", ")
}
// upstreamServerRows builds the `mcpproxy upstream list` table rows.
func upstreamServerRows(servers []map[string]interface{}) [][]string {
rows := make([][]string, 0, len(servers))
for _, srv := range servers {
name := getStringField(srv, "name")
protocol := getStringField(srv, "protocol")
toolCount := getIntField(srv, "tool_count")
// Extract unified health status
healthData, _ := srv["health"].(map[string]interface{})
healthLevel := "unknown"
healthAdminState := "enabled"
healthSummary := getStringField(srv, "status") // fallback to old status
healthStatusValue := ""
healthAction := ""
healthDetail := ""
if healthData != nil {
healthLevel = getStringField(healthData, "level")
healthAdminState = getStringField(healthData, "admin_state")
healthSummary = getStringField(healthData, "summary")
healthStatusValue = getStringField(healthData, "status")
healthAction = getStringField(healthData, "action")
healthDetail = getStringField(healthData, "detail")
}
// FR-015: STATUS is the status label, not the free-text summary (a
// declared table-output change — the summary stays available in
// `-o json` as health.summary). Falls back to the free-text summary
// for an older core's payload that predates `health.status`.
healthStatusText := healthSummary
if healthStatusValue != "" {
healthStatusText = health.StatusLabel(healthStatusValue)
}
// FR-012: ACTION is keyed on actions[0], not the legacy `action` field,
// though today the two always agree (action == actions[0] is an
// invariant of the health calculator). Falls back to `action` for an
// older core's payload that predates `health.actions`.
primaryAction := healthAction
if healthData != nil {
// The client (daemon) path decodes a JSON API response, where
// `actions` always comes back as []interface{}; the config-only
// (daemon-less) path builds this map directly from
// health.CalculateHealth(...).Actions, a native []string, with no
// JSON round-trip. Both shapes must be handled or ACTION silently
// falls back to the legacy `action` field in config mode.
switch rawActions := healthData["actions"].(type) {
case []interface{}:
if len(rawActions) > 0 {
if first, ok := rawActions[0].(string); ok {
primaryAction = first
}
}
case []string:
if len(rawActions) > 0 {
primaryAction = rawActions[0]
}
}
}
// Status emoji based on health level and admin state
statusEmoji := "⚪" // unknown
switch healthAdminState {
case "disabled":
statusEmoji = "⏸️ " // paused
case "quarantined":
statusEmoji = "🔒" // locked
default:
switch healthLevel {
case "healthy":
statusEmoji = "✅"
case "degraded":
statusEmoji = "⚠️ "
case "unhealthy":
statusEmoji = "❌"
}
}
// Format action as CLI command hint (Spec 109 FR-014, internal/health.ActionLabels).
actionHint := "-"
switch primaryAction {
case health.ActionLogin:
actionHint = fmt.Sprintf("auth login --server=%s", name)
case health.ActionRestart:
actionHint = fmt.Sprintf("upstream restart %s", name)
case health.ActionEnable:
actionHint = fmt.Sprintf("upstream enable %s", name)
case health.ActionApprove:
actionHint = fmt.Sprintf("review show %s", name)
case health.ActionViewLogs:
actionHint = fmt.Sprintf("upstream logs %s", name)
case health.ActionSetSecret:
if healthDetail != "" {
actionHint = fmt.Sprintf("Set %s", healthDetail)
} else {
actionHint = "Set secret in config"
}
case health.ActionConfigure, health.ActionEditURL:
actionHint = "Edit config"
}
// GH #938 finding 3: a tool held by the scan gate (or awaiting approval,
// or blocked) must not hide behind a green "Connected (N tools)". Name
// the hold in STATUS, downgrade the all-clear emoji, and point the
// operator at the view that carries the hold evidence.
if holds, holdLabel := serverHoldSummary(srv); holds > 0 {
healthStatusText = fmt.Sprintf("%s · %s held", healthStatusText, holdLabel)
if statusEmoji == "✅" {
statusEmoji = "⚠️ "
}
if actionHint == "-" {
actionHint = fmt.Sprintf("tools list --server=%s", name)
}
}
rows = append(rows, []string{
statusEmoji,
name,
protocol,
fmt.Sprintf("%d", toolCount),
healthStatusText,
actionHint,
})
}
return rows
}
// outputError formats and outputs an error based on the current output format.
// For structured formats (json, yaml), it outputs a StructuredError.
// For table format, it outputs a human-readable error message to stderr.
// T023: Updated to extract request_id from APIError for log correlation
func outputError(err error, code string) error {
outputFormat := ResolveOutputFormat()
// T023: Extract request_id from APIError if available
var requestID string
var apiErr *cliclient.APIError
if errors.As(err, &apiErr) && apiErr.HasRequestID() {
requestID = apiErr.RequestID
}
// Convert to StructuredError if not already
var structErr output.StructuredError
if se, ok := err.(output.StructuredError); ok {
structErr = se
} else {
structErr = output.NewStructuredError(code, err.Error())
}
// T023: Add request_id to StructuredError if available
if requestID != "" {
structErr = structErr.WithRequestID(requestID)
}
// For structured formats, output JSON/YAML error to stdout
if outputFormat == "json" || outputFormat == "yaml" {
formatter, fmtErr := GetOutputFormatter()
if fmtErr != nil {
// Fallback to plain error if formatter fails
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return err
}
result, formatErr := formatter.FormatError(structErr)
if formatErr != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return err
}
fmt.Println(result)
return structErr
}
// For table format, output human-readable error to stderr
// T023: Include request ID with log retrieval suggestion if available
if requestID != "" {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
fmt.Fprintf(os.Stderr, "\nRequest ID: %s\n", requestID)
fmt.Fprintf(os.Stderr, "Use 'mcpproxy activity list --request-id %s' to find related logs.\n", requestID)
} else {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return err
}
// upstreamConfigFilePath resolves the config path for every `upstream`
// subcommand. Config-mode mutations must use this same path as loading so an
// explicit root --config file is never redirected to DataDir/mcp_config.json.
func upstreamConfigFilePath(globalConfig *config.Config) string {
if p := resolveCLIConfigPath(upstreamConfigPath); p != "" {
return p
}
if globalConfig != nil {
return config.GetConfigPath(globalConfig.DataDir)
}
return ""
}
// loadUpstreamConfig resolves the config path for every `upstream` subcommand.
// Only `upstream list`/`upstream logs` register their own local --config flag
// (bound to upstreamConfigPath); every other upstream subcommand (add,
// remove, enable, disable, restart, patch, inspect, import, ...) has no local
// --config flag, so a user's --config=<path> is parsed against the ROOT
// persistent flag and lands in the package-level configFile variable instead.
// Falling back to configFile when upstreamConfigPath is unset means those
// subcommands honor the flag the user actually passed rather than silently
// defaulting to ~/.mcpproxy/mcp_config.json (found via live QA: this caused
// `upstream add --config=<scratch>` to write into the real production
// config). upstreamConfigPath still wins when a command sets it explicitly.
func loadUpstreamConfig() (*config.Config, error) {
return loadCLIConfig(upstreamConfigFilePath(nil))
}
func createUpstreamLogger(level string) (*zap.Logger, error) {
var zapLevel zap.AtomicLevel
switch level {
case "trace", "debug":
zapLevel = zap.NewAtomicLevelAt(zap.DebugLevel)
case "info":
zapLevel = zap.NewAtomicLevelAt(zap.InfoLevel)
case "warn":
zapLevel = zap.NewAtomicLevelAt(zap.WarnLevel)
case "error":
zapLevel = zap.NewAtomicLevelAt(zap.ErrorLevel)
default:
zapLevel = zap.NewAtomicLevelAt(zap.WarnLevel)
}
cfg := zap.Config{
Level: zapLevel,
Development: false,
Encoding: "console",
EncoderConfig: zap.NewDevelopmentEncoderConfig(),
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
return cfg.Build()