-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathupstream_cmd.go
More file actions
2184 lines (1872 loc) · 68.2 KB
/
Copy pathupstream_cmd.go
File metadata and controls
2184 lines (1872 loc) · 68.2 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"
"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/reqcontext"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/socket"
)
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. Use the web UI to approve them.`,
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.
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
// Add command flags
upstreamAddHeaders []string
upstreamAddEnvs []string
upstreamAddWorkingDir string
upstreamAddTransport string
upstreamAddIfNotExists bool
upstreamAddNoQuarantine bool
// Remove command flags
upstreamRemoveYes bool
upstreamRemoveIfExists bool
// Inspect command flags
upstreamInspectTool string
// Patch command flags
upstreamPatchHeaders []string
upstreamPatchHeaderRemove []string
upstreamPatchEnvs []string
upstreamPatchEnvRemove []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().StringVarP(&upstreamLogLevel, "log-level", "l", "warn", "Log level (trace, debug, info, warn, error)")
upstreamListCmd.Flags().StringVarP(&upstreamConfigPath, "config", "c", "", "Path to MCP configuration file")
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")
upstreamLogsCmd.Flags().StringVarP(&upstreamConfigPath, "config", "c", "", "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)")
// 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)")
// 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 {
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
if shouldUseUpstreamDaemon(globalConfig.DataDir) {
logger.Info("Detected running daemon, using client mode via socket")
return runUpstreamListClientMode(ctx, globalConfig.DataDir, logger)
}
// No daemon - load from config file
logger.Info("No daemon detected, reading from config file")
return runUpstreamListFromConfig(globalConfig)
}
func shouldUseUpstreamDaemon(dataDir string) bool {
socketPath := socket.DetectSocketPath(dataDir)
return socket.IsSocketAvailable(socketPath)
}
func runUpstreamListClientMode(ctx context.Context, dataDir string, logger *zap.Logger) error {
socketPath := socket.DetectSocketPath(dataDir)
client := cliclient.NewClient(socketPath, logger.Sugar())
// Call GET /api/v1/servers
servers, err := client.GetServers(ctx)
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 {
// 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
if healthStatus.AdminState == health.StateEnabled {
summary = "Daemon not running"
}
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,
},
}
}
return outputServers(servers)
}
func outputServers(servers []map[string]interface{}) error {
// 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 := 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
healthAction := ""
healthDetail := ""
if healthData != nil {
healthLevel = getStringField(healthData, "level")
healthAdminState = getStringField(healthData, "admin_state")
healthSummary = getStringField(healthData, "summary")
healthAction = getStringField(healthData, "action")
healthDetail = getStringField(healthData, "detail")
}
// 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
actionHint := "-"
switch healthAction {
case "login":
actionHint = fmt.Sprintf("auth login --server=%s", name)
case "restart":
actionHint = fmt.Sprintf("upstream restart %s", name)
case "enable":
actionHint = fmt.Sprintf("upstream enable %s", name)
case "approve":
actionHint = "Approve in Web UI"
case "view_logs":
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:
actionHint = "Edit config"
}
rows = append(rows, []string{
statusEmoji,
name,
protocol,
fmt.Sprintf("%d", toolCount),
healthSummary,
actionHint,
})
}
result, err := formatter.FormatTable(headers, rows)
if err != nil {
return fmt.Errorf("failed to format table: %w", err)
}
fmt.Print(result)
return nil
}
// 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
}
func loadUpstreamConfig() (*config.Config, error) {
if upstreamConfigPath != "" {
cfg, err := config.LoadFromFile(upstreamConfigPath)
if err != nil {
return nil, err
}
// Respect global --data-dir flag
if dataDir != "" {
cfg.DataDir = dataDir
}
return cfg, nil
}
cfg, err := config.Load()
if err != nil {
return nil, err
}
// Respect global --data-dir flag
if dataDir != "" {
cfg.DataDir = dataDir
}
return cfg, 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()
}
func runUpstreamLogs(cmd *cobra.Command, args []string) error {
serverName, err := resolveServerName(args, false)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Load configuration
globalConfig, err := loadUpstreamConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading configuration: %v\n", err)
return err
}
// Create logger
logger, err := createUpstreamLogger(upstreamLogLevel)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating logger: %v\n", err)
return err
}
// Follow mode requires daemon
if upstreamLogsFollow {
if !shouldUseUpstreamDaemon(globalConfig.DataDir) {
return fmt.Errorf("--follow requires running daemon")
}
logger.Info("Following logs from daemon")
// Use background context with signal handling for follow mode
bgCtx, bgCancel := context.WithCancel(context.Background())
defer bgCancel()
// Handle Ctrl+C gracefully
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(sigChan)
go func() {
select {
case <-sigChan:
logger.Info("Received interrupt signal, stopping...")
bgCancel()
case <-bgCtx.Done():
// Context canceled, exit goroutine
}
}()
return runUpstreamLogsFollowMode(bgCtx, globalConfig.DataDir, serverName, logger)
}
// Check if daemon is running
if shouldUseUpstreamDaemon(globalConfig.DataDir) {
logger.Info("Detected running daemon, using client mode via socket")
return runUpstreamLogsClientMode(ctx, globalConfig.DataDir, serverName, logger)
}
// No daemon - read from log file
logger.Info("No daemon detected, reading from log file")
return runUpstreamLogsFromFile(globalConfig, serverName)
}
func runUpstreamLogsClientMode(ctx context.Context, dataDir, serverName string, logger *zap.Logger) error {
socketPath := socket.DetectSocketPath(dataDir)
client := cliclient.NewClient(socketPath, logger.Sugar())
// Call GET /api/v1/servers/{name}/logs?tail=N
logs, err := client.GetServerLogs(ctx, serverName, upstreamLogsTail)
if err != nil {
return fmt.Errorf("failed to get logs from daemon: %w", err)
}
for _, entry := range logs {
fmt.Printf("%s [%s] %s\n", entry.Timestamp.Format("2006-01-02 15:04:05"), entry.Level, entry.Message)
}
return nil
}
func runUpstreamLogsFromFile(globalConfig *config.Config, serverName string) error {
// Read from log file directly
logDir := globalConfig.Logging.LogDir
if logDir == "" {
// Use OS-specific standard log directory
var err error
logDir, err = logs.GetLogDir()
if err != nil {
return fmt.Errorf("failed to determine log directory: %w", err)
}
}
logFile := filepath.Join(logDir, logs.ServerLogFilename(serverName))
// Defense-in-depth: logs.ServerLogFilename already sanitizes the (user-controlled)
// server name to a single path element, but verify the resolved path stays inside
// logDir before it reaches os.Stat/tail so a crafted name can never escape the log
// directory (path-injection barrier).
if !strings.HasPrefix(filepath.Clean(logFile), filepath.Clean(logDir)+string(os.PathSeparator)) {
return fmt.Errorf("invalid server name: %s", serverName)
}
// Check if file exists
if _, err := os.Stat(logFile); os.IsNotExist(err) {
return fmt.Errorf("log file not found: %s (daemon may not have run yet)", logFile)
}
// Read last N lines using tail command
cmd := exec.Command("tail", "-n", fmt.Sprintf("%d", upstreamLogsTail), logFile)
output, err := cmd.Output()
if err != nil {
return fmt.Errorf("failed to read log file: %w", err)
}
fmt.Print(string(output))
return nil
}
func runUpstreamLogsFollowMode(ctx context.Context, dataDir, serverName string, logger *zap.Logger) error {
socketPath := socket.DetectSocketPath(dataDir)
client := cliclient.NewClient(socketPath, logger.Sugar())
fmt.Printf("Following logs for server '%s' (Ctrl+C to stop)...\n", serverName)
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
// Ring buffer to track recently seen lines and prevent unbounded memory growth
const maxTrackedLines = 1000
lastLines := make(map[string]bool)
lineOrder := make([]string, 0, maxTrackedLines)
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
logs, err := client.GetServerLogs(ctx, serverName, upstreamLogsTail)
if err != nil {
logger.Warn("Failed to fetch logs", zap.Error(err))
continue
}
// Print only new lines
for _, entry := range logs {
// Format the log entry as a unique string for deduplication
logLine := fmt.Sprintf("%s [%s] %s", entry.Timestamp.Format("2006-01-02 15:04:05"), entry.Level, entry.Message)
if !lastLines[logLine] {
fmt.Println(logLine)
lastLines[logLine] = true
lineOrder = append(lineOrder, logLine)
// Implement ring buffer: remove oldest line if we exceed max
if len(lineOrder) > maxTrackedLines {
oldestLine := lineOrder[0]
delete(lastLines, oldestLine)
lineOrder = lineOrder[1:]
}
}
}
}
}
}
func runUpstreamEnable(cmd *cobra.Command, args []string) error {
if upstreamAll {
if upstreamServerName != "" || len(args) > 0 {
return fmt.Errorf("do not combine --all with a specific server")
}
return runUpstreamBulkAction("enable", upstreamForce)
}
serverName, err := resolveServerName(args, true)
if err != nil {
return err
}
return runUpstreamAction(serverName, "enable")
}
func runUpstreamDisable(cmd *cobra.Command, args []string) error {
if upstreamAll {
if upstreamServerName != "" || len(args) > 0 {
return fmt.Errorf("do not combine --all with a specific server")
}
return runUpstreamBulkAction("disable", upstreamForce)
}
serverName, err := resolveServerName(args, true)
if err != nil {
return err
}
return runUpstreamAction(serverName, "disable")
}
func runUpstreamRestart(cmd *cobra.Command, args []string) error {
if upstreamAll {
if upstreamServerName != "" || len(args) > 0 {
return fmt.Errorf("do not combine --all with a specific server")
}
return runUpstreamBulkAction("restart", false) // restart doesn't need confirmation
}
serverName, err := resolveServerName(args, true)
if err != nil {
return err
}
return runUpstreamAction(serverName, "restart")
}
func resolveServerName(args []string, allowAll bool) (string, error) {
// Prefer --server, but allow positional for parity with other commands
if upstreamServerName != "" && len(args) > 0 {
if args[0] != upstreamServerName {
return "", fmt.Errorf("specify server once, either as positional or with --server")
}
}
if upstreamServerName != "" {
return upstreamServerName, nil
}
if len(args) > 0 {
return args[0], nil
}
if allowAll {
return "", fmt.Errorf("server name required (or use --all)")
}
return "", fmt.Errorf("server name required")
}
// validateServerExists checks if a server exists in the configuration
func validateServerExists(cfg *config.Config, serverName string) error {
for _, srv := range cfg.Servers {
if srv.Name == serverName {
return nil
}
}
return fmt.Errorf("server '%s' not found in configuration", serverName)
}
func runUpstreamAction(serverName, action string) error {
// Create context with correlation ID and request source tracking
ctx := reqcontext.WithMetadata(context.Background(), reqcontext.SourceCLI)
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Load configuration
globalConfig, err := loadUpstreamConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading configuration: %v\n", err)
return err
}
// Validate server exists
if err := validateServerExists(globalConfig, serverName); err != nil {
return err
}
// Create logger
logger, err := createUpstreamLogger(upstreamLogLevel)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating logger: %v\n", err)
return err
}
// Require daemon for actions
if !shouldUseUpstreamDaemon(globalConfig.DataDir) {
return fmt.Errorf("server actions require running daemon. Start with: mcpproxy serve")
}
socketPath := socket.DetectSocketPath(globalConfig.DataDir)
client := cliclient.NewClient(socketPath, logger.Sugar())
fmt.Printf("Performing action '%s' on server '%s'...\n", action, serverName)
err = client.ServerAction(ctx, serverName, action)
if err != nil {
return fmt.Errorf("failed to %s server: %w", action, err)
}
fmt.Printf("✅ Successfully %sed server '%s'\n", action, serverName)
return nil
}
// runUpstreamToolAction toggles a single tool for a server via the daemon.
// The action verb ("enable"/"disable") is derived from `enabled` so the
// surface stays narrow.
func runUpstreamToolAction(serverName, toolName string, enabled bool) error {
verb := "enable"
if !enabled {
verb = "disable"
}
ctx := reqcontext.WithMetadata(context.Background(), reqcontext.SourceCLI)
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
globalConfig, err := loadUpstreamConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading configuration: %v\n", err)
return err
}
if err := validateServerExists(globalConfig, serverName); err != nil {
return err
}
logger, err := createUpstreamLogger(upstreamLogLevel)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating logger: %v\n", err)
return err
}
if !shouldUseUpstreamDaemon(globalConfig.DataDir) {
return fmt.Errorf("tool actions require running daemon. Start with: mcpproxy serve")
}
socketPath := socket.DetectSocketPath(globalConfig.DataDir)
client := cliclient.NewClient(socketPath, logger.Sugar())