Repository navigation
Expand file tree
/
Copy pathtools_cmd.go
More file actions
1528 lines (1368 loc) · 55.3 KB
/
Copy pathtools_cmd.go
File metadata and controls
1528 lines (1368 loc) · 55.3 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"
"net/url"
"os"
"regexp"
"strings"
"time"
"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/contracts"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/logs"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/preflight"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/secret"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/security/detect"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/storage"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/transport"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/managed"
"github.com/spf13/cobra"
"go.uber.org/zap"
)
var (
toolsCmd = &cobra.Command{
Use: "tools",
Short: "Tools management commands",
Long: "Commands for managing and debugging MCP tools from upstream servers",
}
toolsListCmd = &cobra.Command{
Use: "list",
Short: "List tools from upstream servers",
Long: `List all available tools. Without --server, lists every tool across all
configured servers from the running daemon (global view). With --server,
lists tools from that specific server only.
Examples:
mcpproxy tools list # global list, all servers
mcpproxy tools list -o json # JSON output
mcpproxy tools list --status disabled # only disabled/config-denied
mcpproxy tools list --risk read # read-only tools
mcpproxy tools list --approval pending # tools that are new and need review
mcpproxy tools list --server=github-server # server-scoped (debug mode)
mcpproxy tools list --server=github-server --log-level=trace`,
RunE: runToolsList,
}
toolsEnableCmd = &cobra.Command{
Use: "enable <server:tool> [<server:tool>...]",
Short: "Enable one or more tools",
Long: `Enable one or more tools by their server:tool identifier.
Multiple targets are processed independently. If any target fails, the
command exits non-zero but all other targets are still attempted.
Examples:
mcpproxy tools enable github:create_issue
mcpproxy tools enable github:create_issue github:list_repos`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return runToolsSetEnabled(args, true)
},
}
toolsDisableCmd = &cobra.Command{
Use: "disable <server:tool> [<server:tool>...]",
Short: "Disable one or more tools",
Long: `Disable one or more tools by their server:tool identifier.
Multiple targets are processed independently. If any target fails, the
command exits non-zero but all other targets are still attempted.
Examples:
mcpproxy tools disable github:create_issue
mcpproxy tools disable github:create_issue memory:foo`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return runToolsSetEnabled(args, false)
},
}
// Command flags
serverName string
toolsLogLevel string
configPath string
timeout time.Duration
traceTransport bool // Enable HTTP/SSE frame-by-frame tracing
// Global list filter flags (T019)
toolsStatusFilter string // enabled | disabled | config-denied
// Spec 108 FR-032 view-as: what a client or a profile would see and be able
// to call. Global list only; mutually exclusive.
toolsClientView string
toolsProfileView string
// toolsTierFilter / toolsRiskFilter (Spec 109 FR-028, X11): --risk is kept
// as an alias of --tier for old scripts/muscle-memory; whichever is
// non-empty wins (tier preferred if both are set). Both filter on the
// backend-computed `tier` field (contracts.AnnotationTier) — never a
// locally-derived value.
toolsTierFilter string // read | write | destructive | unannotated
toolsRiskFilter string // alias of --tier
toolsApprovalFilter string // approved | pending | changed
)
// serverToolTarget holds a parsed server:tool pair.
type serverToolTarget struct {
server string
tool string
}
// parseServerTool splits an arg of the form "server:tool" on the first ':'.
// The tool name itself may contain further colons.
func parseServerTool(arg string) (server, tool string, err error) {
if arg == "" {
return "", "", fmt.Errorf("invalid target %q: must be in <server>:<tool> format", arg)
}
idx := strings.Index(arg, ":")
if idx < 0 {
return "", "", fmt.Errorf("invalid target %q: missing ':' separator (use <server>:<tool>)", arg)
}
server = arg[:idx]
tool = arg[idx+1:]
if server == "" {
return "", "", fmt.Errorf("invalid target %q: server name is empty", arg)
}
if tool == "" {
return "", "", fmt.Errorf("invalid target %q: tool name is empty", arg)
}
return server, tool, nil
}
// groupByServer groups targets by their server name.
func groupByServer(targets []serverToolTarget) map[string][]string {
groups := make(map[string][]string)
for _, t := range targets {
groups[t.server] = append(groups[t.server], t.tool)
}
return groups
}
// applyGlobalToolFilters applies client-side filters to the global tool list.
// statusFilter: "enabled" | "disabled" | "config-denied" | ""
// tierFilter: "read" | "write" | "destructive" | "unannotated" | ""
// approvalFilter: "approved" | "pending" | "changed" | ""
//
// Spec 109 FR-028 / X11: tierFilter matches the backend-computed `tier` field
// verbatim. It used to read `annotations.operation_type` — a field that does
// not exist on an MCP tool's annotations (operation_type is an intent-
// declaration concept) — so `--risk read` matched nothing over a fixture of
// read-annotated tools. `tier` is what `GET /tools` actually sends.
func applyGlobalToolFilters(tools []map[string]interface{}, statusFilter, tierFilter, approvalFilter string) []map[string]interface{} {
if statusFilter == "" && tierFilter == "" && approvalFilter == "" {
return tools
}
out := make([]map[string]interface{}, 0, len(tools))
for _, t := range tools {
if statusFilter != "" {
disabled := getBoolField(t, "disabled")
configDenied := getBoolField(t, "config_denied")
isDisabled := disabled || configDenied
switch statusFilter {
case "enabled":
if isDisabled {
continue
}
case "disabled":
if !isDisabled {
continue
}
case "config-denied":
if !configDenied {
continue
}
}
}
if tierFilter != "" {
tier := getStringField(t, "tier")
if !strings.EqualFold(tier, tierFilter) {
continue
}
}
if approvalFilter != "" {
status := getStringField(t, "approval_status")
if !strings.EqualFold(status, approvalFilter) {
continue
}
}
out = append(out, t)
}
return out
}
// filterToolMetadataByTier applies --tier/--risk to the standalone-mode
// (no-daemon) tool list, computing each tool's tier locally via
// contracts.AnnotationTier — the same function the daemon's
// enrichServerTools uses to populate the "tier" field applyGlobalToolFilters
// reads. Unlike --status/--approval (rejected outright for standalone mode,
// since those need daemon-persisted state this path never touches), tier
// needs nothing but the tool's own annotations (review round 6, finding 4).
// An empty tierFilter returns tools unchanged.
func filterToolMetadataByTier(tools []*config.ToolMetadata, tierFilter string) []*config.ToolMetadata {
if tierFilter == "" {
return tools
}
filtered := make([]*config.ToolMetadata, 0, len(tools))
for _, tool := range tools {
if tool == nil {
continue
}
if strings.EqualFold(string(contracts.AnnotationTier(tool.Annotations)), tierFilter) {
filtered = append(filtered, tool)
}
}
return filtered
}
// standaloneNoToolsMessage is the table-mode diagnostic runToolsListStandalone
// prints when the final tool list is empty.
//
// zcode review round 6 (backend fix for finding 4): before
// filterToolMetadataByTier existed, this branch was reachable only when the
// server genuinely exposed zero tools, so guessing "doesn't support tools /
// not properly configured / connection issues" was reasonable. Once a
// --tier/--risk filter can ALSO empty a non-empty discovery result, those
// three guesses are all false for that case — telling an operator who ran
// `--tier destructive` against a server that has tools, just none of that
// tier, that the server "doesn't support tools" is the same misleading
// signal finding 4 was originally about, one step further down the same
// code path. discoveredCount is the count BEFORE tierFilter was applied.
func standaloneNoToolsMessage(serverName, tierFilter string, discoveredCount int) string {
if tierFilter != "" && discoveredCount > 0 {
return fmt.Sprintf("No tools on server '%s' match --tier/--risk=%s (%d tool(s) discovered, none in that tier)\n",
serverName, tierFilter, discoveredCount)
}
return fmt.Sprintf("No tools found on server '%s'\n"+
"This could indicate:\n"+
" Server doesn't support tools\n"+
" Server is not properly configured\n"+
" Connection issues during tool discovery\n", serverName)
}
// resolvedTierFilter returns the effective tier filter from --tier / --risk
// (an alias of --tier, Spec 109 FR-028). --tier wins when both are set.
func resolvedTierFilter() string {
if toolsTierFilter != "" {
return toolsTierFilter
}
return toolsRiskFilter
}
// validTierFilterValues lists the tier strings --tier/--risk accepts,
// mirrored from contracts.Tier — excluding contracts.TierUnknown, which
// AnnotationTier never returns (see internal/contracts/tier.go's own doc
// comment) and so can never legitimately appear in a --tier/--risk match.
var validTierFilterValues = []string{
string(contracts.TierRead),
string(contracts.TierWrite),
string(contracts.TierDestructive),
string(contracts.TierUnannotated),
}
// validateTierFilter rejects an unrecognized --tier/--risk value up front.
// Without this, applyGlobalToolFilters/filterToolMetadataByTier's
// strings.EqualFold match against every known tier simply fails on a typo
// like `--tier destrutive`, silently returning an empty table and exiting 0
// — a CI or audit script grepping for e.g. destructive tools reads that as
// "the host has none", a false all-clear on exactly the safety-relevant
// query this flag exists to answer (review round 8, finding 6).
// flagName is only used to name the offending flag in the error, since
// resolvedTierFilter merges --tier and --risk into one string that no
// longer remembers which flag the caller actually set.
func validateTierFilter(flagName, value string) error {
if value == "" {
return nil
}
for _, v := range validTierFilterValues {
if strings.EqualFold(value, v) {
return nil
}
}
return fmt.Errorf("invalid --%s %q: must be one of: %s (or empty for no filter)",
flagName, value, strings.Join(validTierFilterValues, ", "))
}
// GetToolsCommand returns the tools command for adding to the root command
func GetToolsCommand() *cobra.Command {
return toolsCmd
}
func init() {
// toolsCmd will be added to rootCmd in main.go
toolsCmd.AddCommand(toolsListCmd)
toolsCmd.AddCommand(toolsEnableCmd)
toolsCmd.AddCommand(toolsDisableCmd)
toolsCmd.AddCommand(newToolsApproveCmd())
toolsCmd.AddCommand(newToolsRejectCmd())
toolsCmd.AddCommand(newToolsPreflightCmd())
initToolsFlags()
}
// initToolsFlags registers flags on toolsListCmd. Extracted so tests can call
// it independently of init().
func initToolsFlags() {
// Define flags for tools list command — reset to avoid double-registration
// in tests that call this function more than once.
toolsListCmd.ResetFlags()
toolsListCmd.Flags().StringVarP(&serverName, "server", "s", "", "Name of the upstream server to query (optional; omit for global list)")
toolsListCmd.Flags().StringVarP(&toolsLogLevel, "log-level", "l", "info", "Log level (trace, debug, info, warn, error)")
addConfigFlag(toolsListCmd.Flags(), &configPath, "Path to MCP configuration file (default: ~/.mcpproxy/mcp_config.json)")
toolsListCmd.Flags().DurationVarP(&timeout, "timeout", "t", 30*time.Second, "Connection timeout")
toolsListCmd.Flags().BoolVar(&traceTransport, "trace-transport", false, "Enable detailed HTTP/SSE frame-by-frame tracing")
// Global-list filter flags (T019)
toolsListCmd.Flags().StringVar(&toolsStatusFilter, "status", "", "Filter by state: enabled, disabled, config-denied")
// Spec 109 FR-028/X11: --tier is canonical; --risk is kept as an alias
// (risk stays the scan-score term elsewhere in the CLI).
toolsListCmd.Flags().StringVar(&toolsTierFilter, "tier", "", "Filter by tier: read, write, destructive, unannotated")
toolsListCmd.Flags().StringVar(&toolsRiskFilter, "risk", "", "Alias of --tier")
toolsListCmd.Flags().StringVar(&toolsClientView, "client", "", "View as a client (administrator only): adds ACCESS and REASON columns, the verdict of each tool for that client")
toolsListCmd.Flags().StringVar(&toolsProfileView, "profile", "", "View as a profile: adds ACCESS and REASON columns; a non-administrator sees only the visible tools and a count of the rest")
toolsListCmd.Flags().StringVar(&toolsApprovalFilter, "approval", "", "Filter by approval: approved (Approved), pending (New, needs review), changed (Changed, needs review)")
// Note: -o/--output flag is inherited from root command via globalOutputFormat
// Note: --server is NOT marked required — global list works without it.
toolsListCmd.Example = ` # Global list (all servers) — requires daemon
mcpproxy tools list
mcpproxy tools list -o json | jq '.[0]'
mcpproxy tools list --status disabled
# Server-scoped list (standalone or daemon)
mcpproxy tools list --server=github-server --log-level=trace
# Use custom config file
mcpproxy tools list --server=local-script --config=/path/to/config.json
# Set custom timeout
mcpproxy tools list --server=slow-server --timeout=60s`
}
func runToolsList(_ *cobra.Command, _ []string) error {
if err := validateTierFilter("tier", toolsTierFilter); err != nil {
return err
}
if err := validateTierFilter("risk", toolsRiskFilter); err != nil {
return err
}
if _, err := toolsViewAsQuery(); err != nil {
return err
}
if (toolsClientView != "" || toolsProfileView != "") && serverName != "" {
return errors.New("--client and --profile view-as apply to the global list; omit --server")
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Enable transport tracing if requested
if traceTransport {
transport.SetGlobalTraceEnabled(true)
fmt.Fprintln(os.Stderr, "HTTP/SSE TRANSPORT TRACING ENABLED")
fmt.Fprintln(os.Stderr, " All HTTP requests/responses and SSE frames will be logged")
fmt.Fprintln(os.Stderr)
}
// Load configuration
globalConfig, err := loadToolsConfig()
if err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
// Create logger
logger, err := logs.SetupCommandLogger(false, toolsLogLevel, false, "")
if err != nil {
return fmt.Errorf("failed to setup logger: %w", err)
}
defer func() { _ = logger.Sync() }()
// If no --server given → global list (requires daemon)
if serverName == "" {
return runToolsListGlobal(ctx, globalConfig, logger)
}
// --server given → server-scoped path (daemon or standalone)
if client, ok := newDaemonClient(globalConfig, logger.Sugar()); ok {
logger.Info("Detected running daemon, using client mode",
zap.String("server", serverName))
return runToolsListClientMode(ctx, client, serverName, logger)
}
// No daemon detected, use standalone mode
logger.Info("No daemon detected, using standalone mode",
zap.String("server", serverName))
return runToolsListStandalone(ctx, serverName, globalConfig, logger)
}
// runToolsListGlobal fetches all tools from the global endpoint via the daemon.
func runToolsListGlobal(ctx context.Context, globalConfig *config.Config, logger *zap.Logger) error {
client, ok := newDaemonClient(globalConfig, logger.Sugar())
if !ok {
return fmt.Errorf("global tool list requires the daemon to be running.\n" +
"Start mcpproxy (mcpproxy serve) and try again, or use --server=<name> for a single-server debug listing")
}
pingCtx, pingCancel := context.WithTimeout(ctx, 2*time.Second)
defer pingCancel()
if err := client.Ping(pingCtx); err != nil {
return fmt.Errorf("daemon is not responding: %w\n"+
"Start mcpproxy (mcpproxy serve) and try again", err)
}
fmt.Fprintf(os.Stderr, "Using daemon mode\n\n")
query, err := toolsViewAsQuery()
if err != nil {
return err
}
tools, counts, err := client.GetGlobalToolsView(ctx, query)
if err != nil {
return cliError("failed to get global tools from daemon", err)
}
// An administrator's response carries every row with its verdict and no
// counts (only restricted callers get counts, which must not grow); derive
// the summary from the rows, before the client-side filters narrow them.
if counts == nil && toolsProfileView != "" {
counts = viewAsRowCounts(tools)
}
// Apply client-side filters
tools = applyGlobalToolFilters(tools, toolsStatusFilter, resolvedTierFilter(), toolsApprovalFilter)
if err := outputGlobalToolsView(tools, viewAsPolicyOnly(counts)); err != nil {
return err
}
if counts != nil && ResolveOutputFormat() == "table" {
fmt.Fprint(os.Stderr, "\n"+viewAsCountsSummary(counts, toolsProfileView))
}
return nil
}
// viewAsRowCounts derives {visible, hidden, callable} from the per-row `access`
// verdicts an administrator's view-as response carries. It returns nil when no
// row has a verdict (nothing to summarize).
func viewAsRowCounts(tools []map[string]interface{}) map[string]interface{} {
visible, hidden, callable, seen := 0, 0, 0, false
for _, t := range tools {
access, ok := t["access"].(map[string]interface{})
if !ok {
continue
}
seen = true
if v, _ := access["visible"].(bool); v {
visible++
} else {
hidden++
}
if c, _ := access["callable"].(bool); c {
callable++
}
}
if !seen {
return nil
}
return map[string]interface{}{"visible": float64(visible), "hidden": float64(hidden), "callable": float64(callable)}
}
// viewAsCountsSummary is the footer of `tools --profile`: tools allowed by the
// profile are kept apart from the ones callable right now. The callable and
// held counts, and the explain hint, appear only when the daemon sent
// counts.callable (administrator callers); `access` rows carry the verdict.
func viewAsCountsSummary(counts map[string]interface{}, profile string) string {
line := fmt.Sprintf("%d allowed by profile %s, %d hidden", getIntField(counts, "visible"), profile, getIntField(counts, "hidden"))
if _, admin := counts["callable"]; !admin {
return line + " (hidden tools are administrator-only)\n"
}
callable := getIntField(counts, "callable")
held := getIntField(counts, "visible") - callable
if held < 0 {
held = 0
}
line += fmt.Sprintf(", %d callable now, %d held\n", callable, held)
if held > 0 {
line += "Held tools are allowed by the profile but not callable yet (for example awaiting approval). Run: mcpproxy access explain --profile " + profile + " --tool <server:tool>\n"
}
return line
}
// toolsViewAsQuery is the REST query of the view-as flags (Spec 108 FR-032):
// `client` (administrator only) or `profile`, never both.
func toolsViewAsQuery() (url.Values, error) {
if toolsClientView != "" && toolsProfileView != "" {
return nil, errors.New("use either --client or --profile, not both")
}
q := url.Values{}
if toolsClientView != "" {
q.Set("client", toolsClientView)
}
if toolsProfileView != "" {
q.Set("profile", toolsProfileView)
}
return q, nil
}
// viewAsPolicyOnly reports whether a view-as response is policy-only: the
// daemon sent counts without counts.callable (non-administrator callers), so
// rows must not claim a callable or held verdict beyond the profile policy.
func viewAsPolicyOnly(counts map[string]interface{}) bool {
if counts == nil {
return false
}
_, admin := counts["callable"]
return !admin
}
// viewAsAccessCell renders the ACCESS column of a view-as row: callable (a real
// call would succeed), held (allowed by the profile but a later gate refuses it
// or it awaits approval), hidden (not visible at all). For policy-only
// responses a visible row is just "allowed" (by the profile).
func viewAsAccessCell(t map[string]interface{}, policyOnly bool) string {
access, ok := t["access"].(map[string]interface{})
if !ok {
return "-"
}
if policyOnly {
if getBoolField(access, "visible") {
return "allowed"
}
return "hidden"
}
switch {
case getBoolField(access, "callable"):
return "callable"
case getBoolField(access, "visible"):
return "held"
default:
return "hidden"
}
}
// tpaSignatureRe matches a TPA signature id embedded in a deterministic check id
// (e.g. "tpa.TPA-2026-0001.hidden_instruction" → "TPA-2026-0001").
var tpaSignatureRe = regexp.MustCompile(`TPA-\d{4}-\d{4}`)
// maxHeldSignalsShown is how many hold signals the HELD column renders before
// collapsing the rest into a "+N" suffix.
const maxHeldSignalsShown = 2
// formatToolHold renders the scan-gate hold evidence for the HELD column
// (spec 086 FR-018): the matched TPA signature ids when the bundle fired,
// otherwise the raw check ids (e.g. "phrase.injection"). Returns "-" for tools
// that are not held by the scan gate, so records predating the field render
// exactly as before.
func formatToolHold(t map[string]interface{}) string {
// Collect matched TPA signature ids and the remaining raw check ids
// separately, preserving producer order within each group. TPA ids are
// rendered first so the "+N" truncation never hides them — the scanner
// emits its heuristic checks (directive.imperative, capability.mismatch, …)
// ahead of the tpa.* checks, and FR-018 requires the operator-facing view
// to name the matched TPA-YYYY-NNNN id(s).
var tpaLabels, otherLabels []string
seen := make(map[string]bool)
for _, raw := range getArrayField(t, "held_signals") {
signal, ok := raw.(string)
if !ok || signal == "" {
continue
}
label := signal
isTPA := false
if m := tpaSignatureRe.FindString(signal); m != "" {
label = m
isTPA = true
}
if seen[label] {
continue
}
seen[label] = true
if isTPA {
tpaLabels = append(tpaLabels, label)
} else {
otherLabels = append(otherLabels, label)
}
}
labels := append(tpaLabels, otherLabels...)
if len(labels) == 0 {
// A hold with no signals means the scan itself could not be trusted
// (degraded coverage / missing bundle) — still worth naming.
if reason := getStringField(t, "held_reason"); reason != "" {
// A clean verdict held only for review (Spec 118) is not a scan hold.
if reason == "awaiting_review" {
return "clean"
}
return reason
}
return "-"
}
shown := labels
suffix := ""
if len(labels) > maxHeldSignalsShown {
shown = labels[:maxHeldSignalsShown]
suffix = fmt.Sprintf(" +%d", len(labels)-maxHeldSignalsShown)
}
return strings.Join(shown, ",") + suffix
}
// sanitizeCell makes an upstream-controlled string safe to print in a terminal
// table and truncates it to maxRunes (GH #938 finding 3).
//
// Two bugs it fixes: the server-scoped tool list printed a poisoned description
// verbatim — ANSI escapes, bidi overrides and zero-width runes reached the tty
// unfiltered — and the global list truncated with a BYTE slice, which can split
// a multi-byte rune. detect.CapEvidence is the project-wide render-safe
// contract: it ESCAPES (never drops) control/format runes so smuggled content
// is revealed rather than hidden.
func sanitizeCell(s string, maxRunes int) string {
escaped := detect.CapEvidence(s)
runes := []rune(escaped)
if maxRunes > 3 && len(runes) > maxRunes {
return string(runes[:maxRunes-3]) + "..."
}
return escaped
}
// sanitizeDescriptionCell is sanitizeCell for free-text, one-line table cells
// (tool descriptions, held-tool detail). Multi-line upstream prose is full of
// ordinary \n/\t that CapEvidence would render as literal "\u000a" noise and
// that eats the rune budget, so runs of exactly those ASCII whitespace runes
// (\n \r \t \v \f and space) collapse to one space and the result is trimmed
// BEFORE escaping and truncation. Every other control/format rune (ESC, bidi
// overrides, zero-width, NUL, U+0085, U+2028, ...) is untouched and therefore
// still escaped by CapEvidence. Names and ids keep the strict sanitizeCell: a
// newline inside an identifier is suspicious and should stay visible.
func sanitizeDescriptionCell(s string, maxRunes int) string {
var b strings.Builder
b.Grow(len(s))
pendingSpace := false
for _, r := range s {
switch r {
case ' ', '\n', '\r', '\t', '\v', '\f':
pendingSpace = b.Len() > 0
continue
}
if pendingSpace {
b.WriteByte(' ')
pendingSpace = false
}
b.WriteRune(r)
}
return sanitizeCell(b.String(), maxRunes)
}
// maxToolDescriptionCell is the description column width shared by the global
// and server-scoped tool tables.
const maxToolDescriptionCell = 60
// maxToolNameCell bounds the NAME column. Tool names are upstream-controlled
// just like descriptions — an unbounded one can push every other column off
// screen — so the same cap applies.
const maxToolNameCell = 60
// sanitizeName escapes an upstream-controlled tool name for terminal output.
//
// The description fix alone was bypassable: a server declaring a tool named
// "\x1b[2J\x1b[1;1Happroved" writes ANSI straight to the operator's tty on
// `mcpproxy tools list`, `tools list --server=<name>` and the no-daemon path —
// the same trust boundary, the same attack. Names are upstream-controlled, so
// they get the same render-safe treatment.
func sanitizeName(s string) string {
return sanitizeCell(s, maxToolNameCell)
}
// serverToolRows builds the table for `mcpproxy tools list --server <name>`.
//
// GH #938 finding 3: the server-scoped view used to render only NAME and
// DESCRIPTION, so a tool held by the trust_mode:scan gate was indistinguishable
// from an approved one — the exact view an operator debugging ONE server opens.
// It now carries the same APPROVAL/HELD state as the global view (the
// per-server REST payload has always included those fields; only the renderer
// dropped them) and escapes the description.
func serverToolRows(tools []map[string]interface{}) (headers []string, rows [][]string) {
headers = []string{"NAME", "APPROVAL", "HELD", "DESCRIPTION"}
for _, t := range tools {
approval := getStringField(t, "approval_status")
if approval == "" {
approval = "-"
}
rows = append(rows, []string{
sanitizeName(getStringField(t, "name")),
approval,
formatToolHold(t),
sanitizeDescriptionCell(getStringField(t, "description"), maxToolDescriptionCell),
})
}
return headers, rows
}
// globalToolRows builds the table for `mcpproxy tools list` (all servers).
// Split out of outputGlobalTools so the rendering — in particular the escaping
// of the two upstream-controlled columns, NAME and DESCRIPTION — is directly
// testable.
func globalToolRows(tools []map[string]interface{}) (headers []string, rows [][]string) {
return globalToolRowsView(tools, false)
}
// globalToolRowsView is globalToolRows with the view-as policyOnly mode: rows
// of a non-administrator response show "allowed" and no gate reason.
func globalToolRowsView(tools []map[string]interface{}, policyOnly bool) (headers []string, rows [][]string) {
headers = []string{"NAME", "SERVER", "STATE", "TIER", "APPROVAL", "HELD", "USAGE", "LAST USED", "DESCRIPTION"}
// Spec 108 FR-032: a view-as listing adds ACCESS and REASON after TIER
// (the intrinsic tier stays the TIER column).
viewAs := len(tools) > 0 && tools[0]["access"] != nil
if viewAs {
headers = []string{"NAME", "SERVER", "STATE", "TIER", "ACCESS", "REASON", "APPROVAL", "HELD", "USAGE", "LAST USED", "DESCRIPTION"}
}
for _, t := range tools {
name := sanitizeName(getStringField(t, "name"))
srv := getStringField(t, "server_name")
disabled := getBoolField(t, "disabled")
configDenied := getBoolField(t, "config_denied")
state := "enabled"
if configDenied {
state = "config-denied"
} else if disabled {
state = "disabled"
}
// Spec 109 FR-028/X11: rendered verbatim from the backend-computed
// `tier` field — never derived here.
tier := getStringField(t, "tier")
if tier == "" {
tier = "-"
}
approval := getStringField(t, "approval_status")
if approval == "" {
approval = "-"
}
usage := fmt.Sprintf("%d", getIntField(t, "usage"))
lastUsed := "-"
if lu := getStringField(t, "last_used"); lu != "" {
lastUsed = lu
}
desc := sanitizeDescriptionCell(getStringField(t, "description"), maxToolDescriptionCell)
if viewAs {
reason := "-"
if access, ok := t["access"].(map[string]interface{}); ok {
if r := getStringField(access, "reason"); r != "" && (!policyOnly || !getBoolField(access, "visible")) {
reason = r
}
}
rows = append(rows, []string{name, srv, state, tier, viewAsAccessCell(t, policyOnly), reason, approval, formatToolHold(t), usage, lastUsed, desc})
continue
}
rows = append(rows, []string{name, srv, state, tier, approval, formatToolHold(t), usage, lastUsed, desc})
}
return headers, rows
}
// outputGlobalTools renders the global tool list with extended columns.
func outputGlobalTools(tools []map[string]interface{}) error {
return outputGlobalToolsView(tools, false)
}
// outputGlobalToolsView renders the list; policyOnly marks a non-administrator
// view-as response whose rows carry no callable/held claim.
func outputGlobalToolsView(tools []map[string]interface{}, policyOnly bool) error {
outputFormat := ResolveOutputFormat()
formatter, err := GetOutputFormatter()
if err != nil {
return output.NewStructuredError(output.ErrCodeInvalidOutputFormat, err.Error()).
WithGuidance("Use -o table, -o json, or -o yaml")
}
// JSON / YAML: emit the raw slice
if outputFormat == "json" || outputFormat == "yaml" {
result, fmtErr := formatter.Format(tools)
if fmtErr != nil {
return fmt.Errorf("failed to format output: %w", fmtErr)
}
fmt.Println(result)
return nil
}
headers, rows := globalToolRowsView(tools, policyOnly)
result, fmtErr := formatter.FormatTable(headers, rows)
if fmtErr != nil {
return fmt.Errorf("failed to format table: %w", fmtErr)
}
fmt.Print(result)
return nil
}
// runToolsSetEnabled implements the enable/disable subcommands.
// It parses each arg as server:tool, groups by server, calls the per-tool
// endpoint, prints per-target results, and exits non-zero if any failed.
func runToolsSetEnabled(args []string, enabled bool) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Load config to find the data dir / socket path
globalConfig, err := loadToolsConfig()
if err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
logger, err := logs.SetupCommandLogger(false, "warn", false, "")
if err != nil {
return fmt.Errorf("failed to setup logger: %w", err)
}
defer func() { _ = logger.Sync() }()
client, ok := newDaemonClient(globalConfig, logger.Sugar())
if !ok {
return fmt.Errorf("enable/disable requires the daemon to be running.\n" +
"Start mcpproxy (mcpproxy serve) and try again")
}
pingCtx, pingCancel := context.WithTimeout(ctx, 2*time.Second)
defer pingCancel()
if err := client.Ping(pingCtx); err != nil {
return fmt.Errorf("daemon is not responding: %w", err)
}
// Parse all targets; collect parse errors as per-target failures
type result struct {
arg string
err error
}
var validTargets []serverToolTarget
var results []result
for _, arg := range args {
srv, tool, parseErr := parseServerTool(arg)
if parseErr != nil {
results = append(results, result{arg: arg, err: parseErr})
continue
}
validTargets = append(validTargets, serverToolTarget{server: srv, tool: tool})
}
// Call per-tool endpoint for each valid target
action := "enabled"
if !enabled {
action = "disabled"
}
for _, target := range validTargets {
callErr := client.SetToolEnabled(ctx, target.server, target.tool, enabled)
results = append(results, result{arg: target.server + ":" + target.tool, err: callErr})
}
// Print per-target summary
anyFailed := false
for _, r := range results {
if r.err != nil {
anyFailed = true
fmt.Fprintf(os.Stderr, "FAILED %s: %s\n", r.arg, r.err.Error())
} else {
fmt.Printf("OK %s: %s\n", r.arg, action)
}
}
if anyFailed {
return fmt.Errorf("one or more targets failed (see above)")
}
return nil
}
// loadToolsConfig loads the MCP configuration file for tools command
func loadToolsConfig() (*config.Config, error) {
configFilePath := resolveCLIConfigPath(configPath)
if configFilePath == "" {
var err error
if configFilePath, err = defaultHomeConfigPath(); err != nil {
return nil, err
}
}
// Check if config file exists
if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
return nil, fmt.Errorf("configuration file not found at %s. Please run 'mcpproxy' daemon first to create the config", configFilePath)
}
// Load configuration using file-based loading
globalConfig, err := config.LoadFromFile(configFilePath)
if err != nil {
return nil, fmt.Errorf("failed to load config from %s: %w", configFilePath, err)
}
// Respect global --data-dir flag
if dataDir != "" {
globalConfig.DataDir = dataDir
}
return globalConfig, nil
}
// getAvailableServerNames returns a list of available server names
func getAvailableServerNames(globalConfig *config.Config) []string {
var names []string
for _, server := range globalConfig.Servers {
names = append(names, server.Name)
}
return names
}
// standaloneToolRows builds the no-daemon table. That path has no approval
// records, so it keeps the two-column shape — but BOTH upstream-controlled
// columns are sanitized (#938): a poisoned name or description must never reach
// the terminal raw on ANY path.
func standaloneToolRows(tools []*config.ToolMetadata) (headers []string, rows [][]string) {
headers = []string{"NAME", "DESCRIPTION"}
for _, tool := range tools {
if tool == nil {
continue
}
rows = append(rows, []string{
sanitizeName(tool.Name),
sanitizeDescriptionCell(tool.Description, maxToolDescriptionCell),
})
}
return headers, rows
}
// outputToolsFromMetadata formats and displays tools from ToolMetadata (standalone mode) using unified formatters.
func outputToolsFromMetadata(tools []*config.ToolMetadata, serverName string) error {
// Convert to map format for unified output
toolMaps := make([]map[string]interface{}, len(tools))
for i, tool := range tools {
toolMaps[i] = map[string]interface{}{
"name": tool.Name,
"description": tool.Description,
"server": serverName,
"full_name": fmt.Sprintf("%s:%s", serverName, tool.Name),
}
// Include schema in debug/trace mode
if (toolsLogLevel == "debug" || toolsLogLevel == "trace") && tool.ParamsJSON != "" {
toolMaps[i]["schema"] = tool.ParamsJSON
}
}
outputFormat := ResolveOutputFormat()
formatter, err := GetOutputFormatter()
if err != nil {
return output.NewStructuredError(output.ErrCodeInvalidOutputFormat, err.Error()).
WithGuidance("Use -o table, -o json, or -o yaml")
}
// For JSON/YAML, format directly
if outputFormat == "json" || outputFormat == "yaml" {
result, fmtErr := formatter.Format(toolMaps)
if fmtErr != nil {
return fmt.Errorf("failed to format output: %w", fmtErr)
}
fmt.Println(result)
return nil
}
headers, rows := standaloneToolRows(tools)
result, fmtErr := formatter.FormatTable(headers, rows)
if fmtErr != nil {
return fmt.Errorf("failed to format table: %w", fmtErr)
}
fmt.Print(result)
return nil
}
// runToolsListClientMode executes tools list via the daemon HTTP API.
func runToolsListClientMode(ctx context.Context, client *cliclient.Client, serverName string, logger *zap.Logger) error {
// Ping daemon to verify connectivity
pingCtx, pingCancel := context.WithTimeout(ctx, 2*time.Second)
defer pingCancel()
if err := client.Ping(pingCtx); err != nil {
logger.Warn("Failed to ping daemon, falling back to standalone mode",
zap.Error(err))
// Fall back to standalone mode
cfg, err := loadToolsConfig()