{{ message }}
Repository navigation
Expand file tree
/
Copy pathconfig.go
More file actions
3874 lines (3501 loc) · 177 KB
/
Copy pathconfig.go
File metadata and controls
3874 lines (3501 loc) · 177 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 config
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"net"
"net/url"
"os"
"strings"
"time"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/headerfwd"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/secureenv"
)
const (
defaultPort = "127.0.0.1:8080" // Localhost-only binding by default for security
// Routing mode constants (Spec 031)
RoutingModeRetrieveTools = "retrieve_tools" // Default: BM25 search via retrieve_tools + call_tool_read/write/destructive
RoutingModeDirect = "direct" // All upstream tools exposed directly with serverName__toolName naming
RoutingModeCodeExecution = "code_execution" // JS orchestration via code_execution tool with tool catalog
// Tool response mode constants (Spec 085)
ToolResponseModeFull = "full" // Default: today's schema-bearing retrieve_tools entries
ToolResponseModeCompact = "compact" // Compact signatures + first-sentence descriptions
// Direct-surface serialization constants (Spec 102). A SEPARATE axis from
// ToolResponseMode above: that one governs the retrieve_tools surface, this
// one governs the direct enumeration surface (/mcp/all, and /mcp plus the
// legacy aliases when routing_mode is "direct"). They are orthogonal, and
// compact + deferred is a legal combination in which each governs only its
// own surface (plan.md D1).
DirectToolResponseModeFull = "full" // Default: today's schema-bearing direct entries
DirectToolResponseModeDeferred = "deferred" // Signature-suffixed descriptions, permissive schema
)
// ResolveRoutingMode resolves a configured routing mode to the one actually
// served, mirroring MCPProxyServer.GetMCPServerForMode: unset — and anything
// unrecognised — falls back to retrieve_tools. Callers that report "the routing
// mode" to an operator must resolve first, or a config holding "" reads as a
// mode nobody can act on.
func ResolveRoutingMode(mode string) string {
switch mode {
case RoutingModeDirect, RoutingModeCodeExecution, RoutingModeRetrieveTools:
return mode
default:
return RoutingModeRetrieveTools
}
}
// Duration is a wrapper around time.Duration that can be marshaled to/from JSON.
// When serialized to JSON, it is represented as a string (e.g., "30s", "5m").
// @swaggertype string
type Duration time.Duration
// MarshalJSON implements json.Marshaler interface
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(d).String())
}
// UnmarshalJSON implements json.Unmarshaler interface
func (d *Duration) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
parsed, err := time.ParseDuration(s)
if err != nil {
return fmt.Errorf("invalid duration format: %w", err)
}
*d = Duration(parsed)
return nil
}
// Duration returns the underlying time.Duration
func (d Duration) Duration() time.Duration {
return time.Duration(d)
}
// Built-in defaults for the discovery/health-check loops (spec 074). They live
// here (not in DefaultConfig) so an unset key resolves to the historical
// behaviour and existing configs are unchanged (SC-005).
const (
defaultHealthCheckInterval = 30 * time.Second
defaultToolDiscoveryInterval = 5 * time.Minute
// defaultInitTimeout is the deadline applied to a stdio/HTTP upstream's MCP
// `initialize` handshake when no per-server or global override is set
// (MCP-3322 / GH #760). It preserves the historical ~30s behaviour.
defaultInitTimeout = 30 * time.Second
// Built-in defaults for the HTTP server's request deadlines (GH #965).
// Like the intervals above they live here (not in DefaultConfig) so an
// unset key resolves to the built-in behaviour and existing configs are
// unchanged.
defaultHTTPReadTimeout = 120 * time.Second
// defaultHTTPWriteTimeout stays at 120s (GH #965). A write deadline is a
// wall-clock cap on the ENTIRE response counted from the moment the request
// headers were read, so it must NOT apply to long tool calls or event
// streams — but it is real slow-reader protection for everything else, and
// dropping it globally would strip that protection from REST, Web UI and
// health endpoints on non-loopback deployments.
//
// The streaming routes are exempted per-request instead: the MCP endpoints
// (/mcp*, plus the legacy /v1/tool_code and /v1/tool-code aliases) and the
// SSE /events stream clear their own write deadline via
// http.ResponseController, so this default never truncates them. Setting the
// key to "0s" still disables the deadline globally.
defaultHTTPWriteTimeout = 120 * time.Second
defaultHTTPIdleTimeout = 180 * time.Second
)
// resolveHTTPTimeout applies the tri-state contract shared by the three HTTP
// server deadlines (GH #965): nil = the built-in default, a pointer to 0 =
// DISABLED (net/http's zero value means "no deadline" — except IdleTimeout,
// where net/http falls back to ReadTimeout; see ResolveHTTPIdleTimeout), a
// positive value = that
// value. A negative value falls back to the default — validation rejects those
// anyway, this only keeps a hand-edited file from producing a nonsense deadline.
//
// Note the deliberate asymmetry with ResolveInitTimeout, where 0 maps back to
// the default: a connect handshake must always have a ceiling, whereas "no
// response deadline at all" is a legitimate HTTP setting an operator may want.
func resolveHTTPTimeout(v *Duration, def time.Duration) time.Duration {
if v == nil {
return def
}
if d := v.Duration(); d >= 0 {
return d
}
return def
}
// ResolveHTTPReadTimeout resolves http.Server.ReadTimeout: unset → 120s,
// 0 → disabled, positive → that value (GH #965).
func (c *Config) ResolveHTTPReadTimeout() time.Duration {
return resolveHTTPTimeout(c.HTTPReadTimeout, defaultHTTPReadTimeout)
}
// ResolveHTTPWriteTimeout resolves http.Server.WriteTimeout: unset → 120s,
// 0 → disabled, positive → that value (GH #965). Streaming routes (MCP + SSE
// /events) clear the resulting deadline per-request, so this value only
// governs non-streaming endpoints — see defaultHTTPWriteTimeout.
func (c *Config) ResolveHTTPWriteTimeout() time.Duration {
return resolveHTTPTimeout(c.HTTPWriteTimeout, defaultHTTPWriteTimeout)
}
// ResolveHTTPIdleTimeout resolves http.Server.IdleTimeout: unset → 180s,
// 0 → no idle deadline of its own, positive → that value (GH #965). NOTE:
// net/http falls back to ReadTimeout when IdleTimeout is zero, so an explicit
// "0s" here fully disables the idle deadline only when http_read_timeout is
// also 0 — otherwise idle connections are reaped after the read timeout.
func (c *Config) ResolveHTTPIdleTimeout() time.Duration {
return resolveHTTPTimeout(c.HTTPIdleTimeout, defaultHTTPIdleTimeout)
}
// resolveInterval applies the per-server → global → default precedence for an
// optional *Duration. A non-nil pointer wins at each level, including a pointer
// to 0 ("disabled"). Returns the resolved duration; a value <= 0 means the
// caller should disable the corresponding loop.
func resolveInterval(server, global *Duration, def time.Duration) time.Duration {
if server != nil {
return server.Duration()
}
if global != nil {
return global.Duration()
}
return def
}
// ResolveHealthCheckInterval resolves the effective health-check probe interval
// for a server: per-server override → global → 30s default. A resolved value
// <= 0 disables the periodic probe for that server (spec 074, FR-006).
func (c *Config) ResolveHealthCheckInterval(sc *ServerConfig) time.Duration {
var server *Duration
if sc != nil {
server = sc.HealthCheckInterval
}
return resolveInterval(server, c.HealthCheckInterval, defaultHealthCheckInterval)
}
// ResolveToolDiscoveryInterval resolves the effective tool-discovery sweep
// interval: per-server override → global → 5m default. A resolved value <= 0
// disables the periodic sweep (connect-time + reactive list_changed discovery
// still run). The periodic index rebuild is global; pass nil for the sweep.
func (c *Config) ResolveToolDiscoveryInterval(sc *ServerConfig) time.Duration {
var server *Duration
if sc != nil {
server = sc.ToolDiscoveryInterval
}
return resolveInterval(server, c.ToolDiscoveryInterval, defaultToolDiscoveryInterval)
}
// ResolveInitTimeout resolves the effective MCP `initialize` handshake deadline
// for a server: per-server override → global → 30s default (MCP-3322 / GH #760).
// Unlike the discovery intervals, a resolved value <= 0 maps to the default
// rather than "disabled" — a zero/negative connect deadline would let a stuck
// upstream hang the connect path forever, so we always keep a real ceiling.
func (c *Config) ResolveInitTimeout(sc *ServerConfig) time.Duration {
var server *Duration
if sc != nil {
server = sc.InitTimeout
}
resolved := resolveInterval(server, c.InitTimeout, defaultInitTimeout)
if resolved <= 0 {
return defaultInitTimeout
}
return resolved
}
// isValidToonOutput reports whether s is an acceptable toon_output value
// (spec 084, FR-001). Empty is valid: it means "off" at the top level and
// "inherit global" per-server. The enum is duplicated from toonenc.Mode by
// design — internal/config must not import internal/toonenc (finding 4).
func isValidToonOutput(s string) bool {
switch s {
case "", "off", "adaptive", "always":
return true
default:
return false
}
}
// ResolveToonOutput resolves the effective toon_output mode for a server
// (spec 084, FR-001): per-server non-empty value > global non-empty value >
// "off". It deliberately returns a raw string, NOT a toonenc.Mode —
// internal/config is imported almost everywhere and must not depend on
// internal/toonenc; callers parse the string via toonenc.ParseMode at the
// server/bench boundary.
func (c *Config) ResolveToonOutput(sc *ServerConfig) string {
if sc != nil && sc.ToonOutput != "" {
return sc.ToonOutput
}
if c.ToonOutput != "" {
return c.ToonOutput
}
return "off"
}
// Config represents the main configuration structure
type Config struct {
Listen string `json:"listen" mapstructure:"listen"`
TrayEndpoint string `json:"tray_endpoint,omitempty" mapstructure:"tray-endpoint"` // Tray endpoint override (unix:// or npipe://)
EnableSocket bool `json:"enable_socket" mapstructure:"enable-socket"` // Enable Unix socket/named pipe for local IPC (default: true)
DataDir string `json:"data_dir" mapstructure:"data-dir"`
// Deprecated: EnableTray is unused and has no runtime effect. Kept for backward compatibility.
EnableTray bool `json:"enable_tray,omitempty" mapstructure:"tray"`
DebugSearch bool `json:"debug_search" mapstructure:"debug-search"`
Servers []*ServerConfig `json:"mcpServers" mapstructure:"servers"`
// Profiles are optional named, server-scoped views exposed at /mcp/p/<name>
// (Spec 057). Absent/empty is fully supported — /mcp is unchanged and configs
// without this key serialize byte-identically (SC-004).
Profiles []ProfileConfig `json:"profiles,omitempty" mapstructure:"profiles"`
// AnonymousProfile confines every caller whose request authenticates as
// credential kind "anonymous" (no credential, or an unrecognised
// non-agent token accepted by the require_mcp_auth:false back-compat
// branch) to the named profile (Spec 108 FR-008). Empty (default) means
// unconfined, legacy anonymous behaviour. A name that does not match any
// configured profile resolves anonymous callers to deny-all and is
// reported as a validation warning (data-model.md §1).
AnonymousProfile string `json:"anonymous_profile,omitempty" mapstructure:"anonymous-profile"`
// Deprecated: TopK is superseded by ToolsLimit and has no runtime effect. Kept for backward compatibility.
TopK int `json:"top_k,omitempty" mapstructure:"top-k"`
ToolsLimit int `json:"tools_limit" mapstructure:"tools-limit"`
ToolResponseLimit int `json:"tool_response_limit" mapstructure:"tool-response-limit"`
CallToolTimeout Duration `json:"call_tool_timeout" mapstructure:"call-tool-timeout" swaggertype:"string"`
// MaxResultSizeChars is advertised on every tool as
// `_meta.anthropic/maxResultSizeChars`; it raises Claude Code's
// inline-response ceiling from 50k to up to 500k chars. Omit the key for
// the 500000 default; set it to 0 to disable the annotation.
MaxResultSizeChars *int `json:"max_result_size_chars,omitempty" mapstructure:"max-result-size-chars"`
// Concurrency limits (spec 093, GH #955). Scope (a) of FR-020: the GLOBAL
// AGGREGATE limiter — one proxy-wide cap on concurrently running upstream
// tool calls, with its own bounded wait queue. Tri-state pointers: absent =
// the limiter does not exist (default, zero behavior change); an explicit 0
// max also disables it; positive = that cap. This scope is NEVER a
// per-server inheritance source — per-server values come from
// ServerConcurrencyDefaults / the per-server overrides — but a server's
// effective concurrency is bounded by BOTH its own limiter and this one.
// Resolved by ResolveGlobalConcurrency; hot-reloadable; overridable via
// MCPPROXY_MAX_CONCURRENT_REQUESTS / _QUEUE_SIZE / _QUEUE_TIMEOUT (FR-022).
MaxConcurrentRequests *int `json:"max_concurrent_requests,omitempty" mapstructure:"max-concurrent-requests"`
QueueSize *int `json:"queue_size,omitempty" mapstructure:"queue-size"`
QueueTimeout *Duration `json:"queue_timeout,omitempty" mapstructure:"queue-timeout" swaggertype:"string"`
// AgentTokenRateLimit caps how many upstream tool calls ONE agent token may
// make: PerMinute on average, Burst at once (issue #1699). Every token is
// counted separately, and a token's own rate_limit (set when it is created)
// replaces this default for that token. Only agent-token callers are
// limited; the admin API key, the unix socket and an unauthenticated /mcp
// caller are not. Absent or per_minute 0 = no limit (default, zero behavior
// change). The counters are in memory: a restart gives every token a full
// allowance again. Hot-reloadable. File/API-configured only, no env scheme.
AgentTokenRateLimit *AgentTokenRateLimit `json:"agent_token_rate_limit,omitempty" mapstructure:"agent-token-rate-limit"`
// ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server
// default set inherited by every server that does not override a setting.
// Absent (the default) = no per-server limiting unless a server configures
// it explicitly. File/API-configured only — no env scheme (FR-022).
ServerConcurrencyDefaults *ConcurrencyDefaults `json:"server_concurrency_defaults,omitempty" mapstructure:"server-concurrency-defaults"`
// ToonOutput selects the TOON encoding mode for call_tool_* result text
// blocks (spec 084): "off" (default — responses byte-identical to
// pre-feature behavior), "adaptive" (encode only tabular-uniform payloads
// that beat compact JSON by ToonMinSavingsPct), or "always"
// (benchmark/debug only — encodes every JSON-parseable block and can
// INCREASE token cost). Per-server override: ServerConfig.ToonOutput.
// Resolved by ResolveToonOutput; hot-reloadable.
ToonOutput string `json:"toon_output,omitempty" mapstructure:"toon-output"`
// ToonMinSavingsPct is the minimum byte-savings percentage (validated
// 1-90; 0/unset → 15) the complete TOON emission (marker + hint + body)
// must achieve over the exact passthrough emission for adaptive mode to
// encode a block. Byte savings approximate token savings for the tabular
// payload class; the spec-083 profiler reports true token deltas.
// Global-only (no per-server override, FR-001).
ToonMinSavingsPct int `json:"toon_min_savings_pct,omitempty" mapstructure:"toon-min-savings-pct"`
// Discovery & health-check cadence (spec 074, #608). Both are *Duration
// tri-state pointers: nil = inherit the built-in default; a pointer to 0s =
// the loop is disabled; a positive value = that interval. Defaults live only
// in the resolvers (ResolveHealthCheckInterval / ResolveToolDiscoveryInterval)
// so an unset key behaves exactly as before this feature (SC-005). Validated
// in Validate(): health-check ∈ {0} ∪ [5s,1h]; tool-discovery ∈ {0} ∪ [30s,24h].
HealthCheckInterval *Duration `json:"health_check_interval,omitempty" mapstructure:"health-check-interval" swaggertype:"string"`
ToolDiscoveryInterval *Duration `json:"tool_discovery_interval,omitempty" mapstructure:"tool-discovery-interval" swaggertype:"string"`
// InitTimeout is the global default deadline for an upstream's MCP
// `initialize` handshake (MCP-3322 / GH #760). *Duration tri-state: nil =
// inherit the built-in 30s default; a positive value = that deadline. A
// per-server InitTimeout overrides this. Resolved by ResolveInitTimeout;
// validated to {0} ∪ [1s, 30m] in Validate(). Servers doing legitimate
// first-run warmup (cache/index build) before answering `initialize` can
// raise this so they are not killed mid-startup.
InitTimeout *Duration `json:"init_timeout,omitempty" mapstructure:"init-timeout" swaggertype:"string"`
// HTTP server request deadlines (GH #965). *Duration tri-state: nil =
// inherit the built-in default; a pointer to 0s = DISABLED (no deadline —
// with the idle-timeout caveat noted on HTTPIdleTimeout); a positive value
// = that deadline. Validated to {0} ∪ [1s, 24h].
//
// Unlike init_timeout, an explicit 0 here is a SUPPORTED value, not a
// synonym for the default: net/http treats a zero deadline as "no timeout".
// Long-running tool calls and the SSE /events stream do not need that
// escape hatch, though — the MCP endpoints (/mcp*, plus the legacy
// /v1/tool_code and /v1/tool-code aliases) and /events clear their own
// per-request write deadline via http.ResponseController, so the write
// default only governs non-streaming endpoints (REST, Web UI, health).
//
// These are baked into http.Server at bind time, so changing any of them
// REQUIRES A RESTART (DetectConfigChanges reports it as such). Resolved by
// ResolveHTTPReadTimeout / ResolveHTTPWriteTimeout / ResolveHTTPIdleTimeout.
// Note that call_tool_timeout separately caps tool execution (default 2m):
// raise it too when allowing tool calls longer than two minutes.
// HTTPReadTimeout caps how long reading a whole request (headers + body)
// may take. Unset = 120s; "0s" disables it. Requires a restart.
HTTPReadTimeout *Duration `json:"http_read_timeout,omitempty" mapstructure:"http-read-timeout" swaggertype:"string"`
// HTTPWriteTimeout caps how long producing a whole response may take on
// non-streaming endpoints (REST, Web UI, health). Unset = 120s; "0s"
// disables it globally. MCP and SSE /events routes are exempt by design.
HTTPWriteTimeout *Duration `json:"http_write_timeout,omitempty" mapstructure:"http-write-timeout" swaggertype:"string"`
// HTTPIdleTimeout caps how long an idle keep-alive connection is kept open.
// Unset = 180s. "0s" removes the dedicated idle deadline, but net/http then
// falls back to ReadTimeout — idle is fully unbounded only when
// http_read_timeout is also "0s". Requires a restart.
HTTPIdleTimeout *Duration `json:"http_idle_timeout,omitempty" mapstructure:"http-idle-timeout" swaggertype:"string"`
// Environment configuration for secure variable filtering
Environment *secureenv.EnvConfig `json:"environment,omitempty" mapstructure:"environment"`
// ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy
// environment variables to spawned stdio upstream servers (MCP-2769). OFF by
// default: proxy URLs commonly embed credentials (http://user:pass@proxy), so
// forwarding them to every upstream is a credential-leak risk. When enabled,
// values are forwarded with their userinfo (credentials) redacted.
ForwardProxyEnv bool `json:"forward_proxy_env,omitempty" mapstructure:"forward-proxy-env"`
// Logging configuration
Logging *LogConfig `json:"logging,omitempty" mapstructure:"logging"`
// Security settings
APIKey string `json:"api_key,omitempty" mapstructure:"api-key"` // API key for REST API authentication
RequireMCPAuth bool `json:"require_mcp_auth" mapstructure:"require-mcp-auth"` // Require authentication on /mcp endpoint (default: false)
// MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that
// carries a ?apikey= query parameter, with a 401, instead of honouring it. A credential in a URL ends up in access logs,
// proxy logs and browser history; MCP clients can send Authorization:
// Bearer or X-API-Key instead. Default false (the query form keeps
// working, for clients that can only configure a URL). It covers only the
// MCP endpoints: the Web UI and its SSE stream (/events) still use the
// query form. Live, no restart needed.
MCPRejectQueryAPIKey bool `json:"mcp_reject_query_apikey,omitempty" mapstructure:"mcp-reject-query-apikey"`
// TrustedHosts lists non-loopback Host header values accepted on loopback
// listeners (GH #898). DNS-rebinding protection rejects requests whose Host
// header is not a loopback address when mcpproxy listens on loopback; a
// reverse proxy (nginx → 127.0.0.1) forwarding the public domain in Host
// trips it. Entries are hostnames, case-insensitive; an entry without a
// port matches any port, with a port it must match exactly; a leading dot
// (".example.com") is a subdomain wildcard. The single entry "*" disables
// Host and Origin validation entirely. The same list also validates the
// Origin header when present (MCP spec DNS-rebinding defense). Empty
// (default) keeps full protection. Env override: MCPPROXY_TRUSTED_HOSTS
// (comma-separated).
TrustedHosts []string `json:"trusted_hosts,omitempty" mapstructure:"trusted-hosts"`
// TrustedProxies lists the CIDRs or IP addresses whose X-Forwarded-For /
// X-Real-IP / X-Forwarded-Proto / X-Forwarded-Host headers are believed
// (Spec 107 FR-027). Empty (default) trusts nobody. Edition-neutral, live
// (hot-reloadable). Env override: MCPPROXY_TRUSTED_PROXIES (comma-separated).
// The one reader is ForwardedHeaders; validation is validateTrustedProxies.
TrustedProxies []string `json:"trusted_proxies,omitempty" mapstructure:"trusted-proxies"`
// ForwardClientHeaders is the global switch for client header forwarding
// (Spec 112): copying allowlisted headers from the inbound /mcp request into
// the upstream tools/call request. nil (absent) means enabled; because every
// per-server forward_headers allowlist is empty by default, the default
// forwards nothing. false disables forwarding for every server. Read via
// IsClientHeaderForwardingEnabled(); MCPPROXY_FORWARD_CLIENT_HEADERS
// overrides it for the process. Distinct from ForwardedHeaders/trusted_proxies
// (Spec 107), which trusts inbound X-Forwarded-*.
ForwardClientHeaders *bool `json:"forward_client_headers,omitempty" mapstructure:"forward-client-headers"`
// AuditLog configures the Spec 107 edition-neutral audit sink
// (internal/audit). nil means "use the per-edition/per-transport
// default" (EffectiveAuditLog); restart-pinned (bound at sink
// construction). See audit_log.go.
AuditLog *AuditLogConfig `json:"audit_log,omitempty" mapstructure:"audit-log"`
ReadOnlyMode bool `json:"read_only_mode" mapstructure:"read-only-mode"`
DisableManagement bool `json:"disable_management" mapstructure:"disable-management"`
AllowServerAdd bool `json:"allow_server_add" mapstructure:"allow-server-add"`
AllowServerRemove bool `json:"allow_server_remove" mapstructure:"allow-server-remove"`
// Internal field to track if API key was explicitly set in config
apiKeyExplicitlySet bool `json:"-"`
// profileWarnings holds non-fatal Spec 057 profile diagnostics (unknown /
// empty servers) captured during Validate(), for the boot path to log.
profileWarnings []string `json:"-"`
// loadDiagnostics holds the non-fatal Spec 107 findings the server-build
// loader recorded while normalising the raw document (removed keys /
// modes dropped, deprecated keys retained), for LogLoadDiagnostics to
// emit once a logger exists. See load_diagnostics.go.
loadDiagnostics []LoadDiagnostic `json:"-"`
// Prompts settings
EnablePrompts bool `json:"enable_prompts" mapstructure:"enable-prompts"`
// AggregateUpstreamPrompts, when true, aggregates every connected upstream
// server's advertised MCP prompts into mcpproxy's own prompts/list
// (exposed as "<server>__<prompt>"). OFF by default: users are safe by
// default and opt in deliberately. EnablePrompts still governs the built-in
// prompts + the prompts capability; this flag gates ONLY the upstream
// aggregation performed by RefreshPrompts. Hot-reloadable.
AggregateUpstreamPrompts bool `json:"aggregate_upstream_prompts" mapstructure:"aggregate-upstream-prompts"`
// Repository detection settings
CheckServerRepo bool `json:"check_server_repo" mapstructure:"check-server-repo"`
// Docker isolation settings
DockerIsolation *DockerIsolationConfig `json:"docker_isolation,omitempty" mapstructure:"docker-isolation"`
// Docker recovery settings
DockerRecovery *DockerRecoveryConfig `json:"docker_recovery,omitempty" mapstructure:"docker-recovery"`
// Registries configuration for MCP server discovery
Registries []RegistryEntry `json:"registries,omitempty" mapstructure:"registries"`
// RegistriesLocked is an enterprise stub knob (MCP-866): when true, runtime
// additions of custom registries (e.g. `registry add-source`, the REST/MCP
// add-source surface) are rejected so an administrator can pin the discovery
// sources. Built-in defaults are unaffected. Documented but otherwise inert
// beyond the add-source rejection.
RegistriesLocked bool `json:"registries_locked,omitempty" mapstructure:"registries-locked"`
// AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,
// CWE-918). By default (false) registry fetches refuse any host that is — or
// resolves to — a non-routable address (loopback, RFC1918/CGNAT private,
// link-local incl. the 169.254.169.254 cloud-metadata endpoint), so a
// malicious or typo'd registry source cannot turn the daemon into a
// request-forgery vector against internal services.
//
// This opt-out is BLANKET (all-or-nothing): setting it true disables the
// guard for EVERY non-routable range at once — loopback, RFC1918/CGNAT
// private, link-local AND the 169.254.169.254 cloud-metadata endpoint. There
// is no way to allow only loopback; enabling it for a localhost dev registry
// also re-opens the cloud-metadata SSRF vector. Set true ONLY when you
// intentionally run a trusted registry mirror on an internal/private address,
// ideally on a host with no cloud-metadata exposure. The change takes effect
// only on daemon (re)start or config reload.
AllowPrivateRegistryFetch bool `json:"allow_private_registry_fetch,omitempty" mapstructure:"allow-private-registry-fetch"`
// Deprecated: Features flags are unused and have no runtime effect. Kept for backward compatibility.
Features *FeatureFlags `json:"features,omitempty" mapstructure:"features"`
// TLS configuration
TLS *TLSConfig `json:"tls,omitempty" mapstructure:"tls"`
// Tokenizer configuration for token counting
Tokenizer *TokenizerConfig `json:"tokenizer,omitempty" mapstructure:"tokenizer"`
// Code execution settings
EnableCodeExecution bool `json:"enable_code_execution" mapstructure:"enable-code-execution"` // Enable JavaScript code execution tool (default: true since v0.66.0)
CodeExecutionTimeoutMs int `json:"code_execution_timeout_ms,omitempty" mapstructure:"code-execution-timeout-ms"` // Timeout in milliseconds (default: 120000, max: 600000)
CodeExecutionMaxToolCalls int `json:"code_execution_max_tool_calls,omitempty" mapstructure:"code-execution-max-tool-calls"` // Max tool calls per execution (0 = unlimited, default: 0)
CodeExecutionPoolSize int `json:"code_execution_pool_size,omitempty" mapstructure:"code-execution-pool-size"` // JavaScript runtime pool size (default: 10)
CodeExecutionMaxParallel int `json:"code_execution_max_parallel,omitempty" mapstructure:"code-execution-max-parallel"` // Default concurrency for call_tools() batches (1-32, default: 8)
// ToolResponseSessionRiskWarning controls whether the prose `warning` field
// is included in the `session_risk` object returned by `retrieve_tools`.
// The structured fields (level, lethal_trifecta, has_open_world_tools, etc.)
// are always included. Default: false (quiet for LLM clients) — see issue #406.
// Most tools lack annotations, so the MCP-spec defaults treat them as fully
// permissive across all three risk axes, which makes the prose warning fire
// on almost every call and wastes tokens.
ToolResponseSessionRiskWarning bool `json:"tool_response_session_risk_warning,omitempty" mapstructure:"tool-response-session-risk-warning"`
// Health status settings
OAuthExpiryWarningHours float64 `json:"oauth_expiry_warning_hours,omitempty" mapstructure:"oauth-expiry-warning-hours"` // Hours before token expiry to show degraded status (default: 1.0)
// Activity logging settings (RFC-003)
ActivityRetentionDays int `json:"activity_retention_days,omitempty" mapstructure:"activity-retention-days"` // Max age before pruning (default: 90)
ActivityMaxRecords int `json:"activity_max_records,omitempty" mapstructure:"activity-max-records"` // Max records before pruning (default: 100000)
// ActivityMaxSizeMB caps the total activity-log size in MB before the
// oldest records are pruned. Omit the key for the 256MB default; set it to
// 0 to disable the size cap.
ActivityMaxSizeMB *int `json:"activity_max_size_mb,omitempty" mapstructure:"activity-max-size-mb"`
ActivityMaxResponseSize int `json:"activity_max_response_size,omitempty" mapstructure:"activity-max-response-size"` // Response truncation limit in bytes (default: 65536)
ActivityCleanupIntervalMin int `json:"activity_cleanup_interval_min,omitempty" mapstructure:"activity-cleanup-interval-min"` // Background cleanup interval in minutes (default: 60)
// Bounds for the per-server tool-call history behind GET /api/v1/tool-calls
// (#1176). It is a recent-debugging window, not an audit log — the activity
// log is the durable record — and it kept every upstream response whole,
// per server, forever. A non-positive value means "use the default", not
// "disable": this store must never be unbounded again, so there is
// deliberately no off switch.
ToolCallMaxResponseSize int `json:"tool_call_max_response_size,omitempty" mapstructure:"tool-call-max-response-size"` // Cap on a stored response, in bytes (default: 65536)
ToolCallMaxRecordsPerServer int `json:"tool_call_max_records_per_server,omitempty" mapstructure:"tool-call-max-records-per-server"` // Calls retained per server (default: 1000)
// Intent declaration settings (Spec 018)
IntentDeclaration *IntentDeclarationConfig `json:"intent_declaration,omitempty" mapstructure:"intent-declaration"`
// Sensitive data detection settings (Spec 026)
SensitiveDataDetection *SensitiveDataDetectionConfig `json:"sensitive_data_detection,omitempty" mapstructure:"sensitive-data-detection"`
// Output-schema validation settings (Spec 056)
OutputValidation *OutputValidationConfig `json:"output_validation,omitempty" mapstructure:"output-validation"`
// Output sanitisation settings (Spec 054 Track B)
OutputSanitisation *OutputSanitisationConfig `json:"output_sanitisation,omitempty" mapstructure:"output-sanitisation"`
// Telemetry settings (Spec 036)
Telemetry *TelemetryConfig `json:"telemetry,omitempty" mapstructure:"telemetry"`
// Observability settings (Spec 069): usage aggregate cache/persistence cadence.
Observability *ObservabilityConfig `json:"observability,omitempty" mapstructure:"observability"`
// Update-check settings (Spec 079 FR-012): config-file control of the
// background upgrade-awareness checker (internal/updatecheck). nil =
// enabled on the stable channel (existing default behavior). The existing
// environment switches keep working and WIN over these keys (FR-014):
// MCPPROXY_DISABLE_AUTO_UPDATE=true force-disables even when
// enabled=true, and MCPPROXY_ALLOW_PRERELEASE_UPDATES=true force-selects
// the rc channel even when channel=stable.
UpdateCheck *UpdateCheckConfig `json:"update_check,omitempty" mapstructure:"update-check"`
// Routing mode (Spec 031): how MCP tools are exposed to clients
// Valid values: "retrieve_tools" (default), "direct", "code_execution"
RoutingMode string `json:"routing_mode,omitempty" mapstructure:"routing-mode"`
// Tool response mode (Spec 085): how retrieve_tools serializes results.
// Valid values: "" (= full), "full" (default: today's schema-bearing
// entries), "compact" (signature + first-sentence entries). Orthogonal to
// routing_mode — routing_mode selects the tool SURFACE, this selects the
// SERIALIZATION within the retrieve_tools surface. Serialization-only: it
// never affects the query, ranking, or result set. Hot-reloadable.
ToolResponseMode string `json:"tool_response_mode,omitempty" mapstructure:"tool-response-mode"`
// DirectToolResponseMode selects the serialization of the DIRECT
// enumeration surface (Spec 102). Valid values: "" (= full), "full"
// (default: today's schema-bearing entries), "deferred" (description +
// compact signature, with a minimal permissive input schema; upstream
// inputSchema and outputSchema are stripped and recovered on demand via
// describe_tool).
//
// Deliberately NOT an extension of tool_response_mode: reusing that axis
// would silently change /mcp/all output for every deployment already
// running compact, which FR-015 forbids. Serialization-only — it never
// changes WHICH tools are listed, only how (FR-008). Hot-reloadable.
DirectToolResponseMode string `json:"direct_tool_response_mode,omitempty" mapstructure:"direct-tool-response-mode"`
// Instructions text returned in the MCP initialize response to guide AI agents.
// When empty, a built-in default is used that explains retrieve_tools workflow.
Instructions string `json:"instructions,omitempty" mapstructure:"instructions"`
// AdvertiseUpstreamServers controls whether MCP clients are told the
// names of the upstream servers they can reach — in the initialize
// instructions and the retrieve_tools description — so agents use the
// proxied tools instead of falling back to shell CLIs. Names are always
// filtered to the caller's profile and agent-token scope. Default true;
// set false to keep server names out of client context. Read live.
AdvertiseUpstreamServers *bool `json:"advertise_upstream_servers,omitempty" mapstructure:"advertise-upstream-servers"`
// QuarantineEnabled controls whether quarantine is active. It gates two
// things together:
// 1. Server-level auto-quarantine for newly added servers (issue #370).
// When true, servers added via the upstream_servers MCP tool or the
// REST API default to quarantined=true; when false, they default to
// quarantined=false. Explicit per-request values always win.
// 2. Tool-level quarantine (Spec 032): per-tool SHA-256 approval of
// tool descriptions/schemas.
// When nil (default), quarantine is enabled (secure by default). Set to
// explicit false to opt out of both. Per-server SkipQuarantine still
// applies for the tool-level check on individual servers.
QuarantineEnabled *bool `json:"quarantine_enabled,omitempty" mapstructure:"quarantine-enabled"`
// Security scanner settings (Spec 039)
Security *SecurityConfig `json:"security,omitempty" mapstructure:"security"`
// RevealSecretHeaders, when true, disables the redaction of the
// secret-bearing server fields — sensitive header values (Authorization,
// X-API-Key, Cookie, …), env-var secrets, and URL query credentials — in
// responses from the `upstream_servers` MCP tool, the `/api/v1/servers`
// REST API, and the SSE event stream. It also lets URL secrets echoed
// into last_error / health.detail through unscrubbed.
//
// Default false — sensitive values are surfaced masked as
// `••••<last2> (<N> chars)` (error strings use `***REDACTED***`) so an
// MCP agent cannot read Bearer tokens / API keys / URL secrets out of
// another upstream's config (PR #425, issue #872). ${env:…}/${keyring:…}
// references are labels, not secrets, and pass through unchanged.
//
// The Web UI / macOS tray edit forms work without seeing the real
// values: PATCH /api/v1/servers/{id} deep-merges (omitted keys are
// preserved, see `headers_remove` / `env_remove` for explicit
// deletes), so clients compute a diff and only send the keys that
// actually changed. Redacted-but-unchanged values never round-trip
// — the backend keeps the real string. Set this to true if a
// downstream tool genuinely needs raw values in the response.
RevealSecretHeaders bool `json:"reveal_secret_headers,omitempty" mapstructure:"reveal-secret-headers"`
// Server edition multi-user configuration (only meaningful with -tags server).
// Renamed from the legacy "teams" key (MCP-1086); an existing config that
// still uses "teams" is normalized onto this field on load (see loader.go).
ServerEdition *ServerEditionConfig `json:"server_edition,omitempty" mapstructure:"server_edition" swaggerignore:"true"`
}
// TLSConfig represents TLS configuration
type TLSConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"` // Enable HTTPS
RequireClientCert bool `json:"require_client_cert" mapstructure:"require_client_cert"` // Enable mTLS
CertsDir string `json:"certs_dir,omitempty" mapstructure:"certs_dir"` // Directory for certificates
HSTS bool `json:"hsts" mapstructure:"hsts"` // Enable HTTP Strict Transport Security
// ExtraSANs are DNS names and IP addresses added to the generated server
// certificate, which is signed by the same local CA. Not used with CertFile.
ExtraSANs []string `json:"extra_sans,omitempty" mapstructure:"extra_sans"`
// CertFile is the absolute path of an operator-provided server certificate
// (PEM, leaf first), served instead of a generated one. Needs KeyFile.
CertFile string `json:"cert_file,omitempty" mapstructure:"cert_file"`
// KeyFile is the absolute path of the private key for CertFile (PEM).
KeyFile string `json:"key_file,omitempty" mapstructure:"key_file"`
}
// TokenizerConfig represents tokenizer configuration for token counting
type TokenizerConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"` // Enable token counting
DefaultModel string `json:"default_model" mapstructure:"default_model"` // Default model for tokenization (e.g., "gpt-4")
Encoding string `json:"encoding" mapstructure:"encoding"` // Default encoding (e.g., "cl100k_base")
}
// LogConfig represents logging configuration
type LogConfig struct {
Level string `json:"level" mapstructure:"level"`
EnableFile bool `json:"enable_file" mapstructure:"enable-file"`
EnableConsole bool `json:"enable_console" mapstructure:"enable-console"`
Filename string `json:"filename" mapstructure:"filename"`
LogDir string `json:"log_dir,omitempty" mapstructure:"log-dir"` // Custom log directory
MaxSize int `json:"max_size" mapstructure:"max-size"` // MB
MaxBackups int `json:"max_backups" mapstructure:"max-backups"` // number of backup files
MaxAge int `json:"max_age" mapstructure:"max-age"` // days
Compress bool `json:"compress" mapstructure:"compress"`
JSONFormat bool `json:"json_format" mapstructure:"json-format"`
}
// TrustMode is a per-server trust tier that governs how tool changes and
// additions are approved (spec 086). It supersedes the legacy skip_quarantine
// and auto_approve_tool_changes flags:
//
// - TrustModeAuto — auto-approve all changes/additions (today's
// skip_quarantine / auto_approve_tool_changes:true behavior).
// - TrustModeScan — auto-approve a change ONLY when a synchronous, offline
// TPA scan of the changed tool returns a green (clean) verdict; otherwise
// the record is held for human review (fail closed).
// - TrustModeManual — never auto-approve; every change/addition is held.
//
// Spec 119: an UNSET trust_mode resolves to scan (DefaultTrustMode); under
// scan a CHANGED contract that scans clean is auto-approved too (reason
// scan_approved) — the 2026-10-11 RT-02 "never approve a changed contract"
// rule now applies to manual only. An unrecognized value still fails closed to
// manual.
type TrustMode string
const (
TrustModeAuto TrustMode = "auto"
TrustModeScan TrustMode = "scan"
TrustModeManual TrustMode = "manual"
)
// ServerConfig represents upstream MCP server configuration
type ServerConfig struct {
Name string `json:"name,omitempty" mapstructure:"name"`
URL string `json:"url,omitempty" mapstructure:"url"`
Protocol string `json:"protocol,omitempty" mapstructure:"protocol"` // stdio, http, sse, streamable-http, auto
Command string `json:"command,omitempty" mapstructure:"command"`
Args []string `json:"args,omitempty" mapstructure:"args"`
WorkingDir string `json:"working_dir,omitempty" mapstructure:"working_dir"` // Working directory for stdio servers
Env map[string]string `json:"env,omitempty" mapstructure:"env"`
Headers map[string]string `json:"headers,omitempty" mapstructure:"headers"` // For HTTP servers
OAuth *OAuthConfig `json:"oauth" mapstructure:"oauth"` // OAuth configuration (keep even when empty to signal OAuth requirement)
Enabled bool `json:"enabled" mapstructure:"enabled"`
Quarantined bool `json:"quarantined" mapstructure:"quarantined"` // Security quarantine status
// quarantineExplicitlySet records whether the decoded JSON actually carried a
// "quarantined" key (issue #937). Quarantined is a plain bool, so an ABSENT
// key and an explicit `false` are otherwise indistinguishable — which is what
// let a hand-written mcp_config.json entry bypass the trust-mode admission
// gate that every add path applies. Set only by UnmarshalJSON; read via
// QuarantineExplicitlySet().
quarantineExplicitlySet bool
// SkipQuarantine is DEPRECATED (MCP-2930): use AutoApproveToolChanges instead.
// Kept for back-compat parsing; on config load a legacy skip_quarantine:true is
// migrated to auto_approve_tool_changes:true only when the new field is unset
// (see normalizeServerQuarantineFlags).
SkipQuarantine bool `json:"skip_quarantine,omitempty" mapstructure:"skip-quarantine"` // Deprecated: use auto_approve_tool_changes
// AutoApproveToolChanges is the per-server intent to auto-approve tool
// changes/additions (disabling per-server rug-pull protection). Supersedes
// skip_quarantine. MCP-2930 only ACCEPTS, persists, and migrates this flag — it
// is NOT yet consulted at runtime; auto-approval is still governed by
// SkipQuarantine until the trust-baseline behavior change (MCP-2931) migrates the
// runtime consumers onto it.
// Tri-state pointer (mirrors QuarantineEnabled): nil = unset (inherit/migrate
// from legacy skip_quarantine), explicit true/false = honored as-is so an
// explicit auto_approve_tool_changes:false overrides a legacy skip_quarantine:true.
// Read via IsAutoApproveToolChanges().
AutoApproveToolChanges *bool `json:"auto_approve_tool_changes,omitempty" mapstructure:"auto-approve-tool-changes"` // Per-server intent to auto-approve tool changes/additions. Accepted/persisted by MCP-2930; runtime enforcement lands in MCP-2931 (until then SkipQuarantine governs behavior)
// TrustMode is the per-server trust tier: auto|scan|manual. Supersedes
// auto_approve_tool_changes (spec 086). An empty value is derived from the
// legacy fields at load via normalizeServerQuarantineFlags; the single
// resolution point is EffectiveTrustMode(), which treats an empty value as
// scan (DefaultTrustMode, spec 119) and an unrecognized value as manual
// (fail closed). Read via
// EffectiveTrustMode(), never the raw string.
TrustMode string `json:"trust_mode,omitempty" mapstructure:"trust-mode"` // Per-server trust tier: auto|scan|manual. Supersedes auto_approve_tool_changes (086)
Shared bool `json:"shared,omitempty" mapstructure:"shared"` // Server edition: shared with all users
Created time.Time `json:"created" mapstructure:"created"`
Updated time.Time `json:"updated,omitempty" mapstructure:"updated"`
Isolation *IsolationConfig `json:"isolation,omitempty" mapstructure:"isolation"` // Per-server isolation settings
ReconnectOnUse bool `json:"reconnect_on_use,omitempty" mapstructure:"reconnect-on-use"` // Attempt reconnection when a tool call targets a disconnected server
// ExposePrompts overrides whether this server's advertised MCP prompts are
// aggregated into mcpproxy's prompts/list. nil (default) inherits the
// default-aggregate behavior (included if the server advertises
// Capabilities.Prompts); false excludes it regardless of capability.
ExposePrompts *bool `json:"expose_prompts,omitempty" mapstructure:"expose-prompts"`
// ForwardHeaders lists inbound MCP-client header NAMES (never values) that
// are copied into this server's upstream tools/call requests (Spec 112).
// Exact names, case-insensitive, at most 32, no wildcards. Empty forwards
// nothing. Only HTTP-based transports (http, streamable-http) forward; the
// deny list (Authorization, Host, hop-by-hop, ...) is enforced at runtime
// regardless of what is configured here.
ForwardHeaders []string `json:"forward_headers,omitempty" mapstructure:"forward_headers"`
// LauncherWaitTimeout caps how long mcpproxy will wait for a locally-launched
// HTTP/SSE upstream's URL to become reachable after Spawn(). Only consulted
// when the server is configured with both Command and an HTTP/SSE URL — i.e.,
// mcpproxy starts the process AND connects via network. Stdio servers ignore
// this field. Zero or unset → 30s default.
LauncherWaitTimeout Duration `json:"launcher_wait_timeout,omitempty" mapstructure:"launcher_wait_timeout" swaggertype:"string"`
// Per-server discovery & health-check overrides (spec 074). Same *Duration
// tri-state as the global keys: nil = inherit the global value (or default),
// pointer to 0s = disabled for this server, positive = that interval.
// HealthCheckInterval is fully wired into the per-server health loop;
// ToolDiscoveryInterval is accepted/validated and round-trips for
// forward-compat, but the periodic index sweep is governed by the global
// cadence in this iteration (see spec 074 plan §C).
HealthCheckInterval *Duration `json:"health_check_interval,omitempty" mapstructure:"health_check_interval" swaggertype:"string"`
ToolDiscoveryInterval *Duration `json:"tool_discovery_interval,omitempty" mapstructure:"tool_discovery_interval" swaggertype:"string"`
// InitTimeout overrides the global init_timeout for this server's MCP
// `initialize` handshake deadline (MCP-3322 / GH #760). *Duration tri-state:
// nil = inherit the global value (or 30s default), positive = that deadline.
// Resolved by Config.ResolveInitTimeout; validated to {0} ∪ [1s, 30m]. Raise
// this for upstreams that do legitimate first-run warmup (e.g. caching many
// channels/users) before responding to `initialize`.
InitTimeout *Duration `json:"init_timeout,omitempty" mapstructure:"init_timeout" swaggertype:"string"`
// Per-server concurrency overrides — scope (c) of FR-020 (spec 093, #955).
// Tri-state per setting, exactly like HealthCheckInterval: absent = inherit
// the per-server default set (server_concurrency_defaults), explicit 0 =
// disable that setting for this server (0 max = no per-server limiter at
// all; 0 queue_size = no pending capacity, shed immediately at the cap),
// positive = override. The global aggregate limiter is never inherited from
// here — it applies on top, so effective concurrency is min(per-server,
// global). Resolved by Config.ResolveServerConcurrency.
MaxConcurrentRequests *int `json:"max_concurrent_requests,omitempty" mapstructure:"max_concurrent_requests"`
QueueSize *int `json:"queue_size,omitempty" mapstructure:"queue_size"`
QueueTimeout *Duration `json:"queue_timeout,omitempty" mapstructure:"queue_timeout" swaggertype:"string"`
// ToonOutput overrides the global toon_output mode for this server's
// tools (spec 084, FR-001). Plain string, not a pointer: ""/absent =
// inherit the global value; "off"|"adaptive"|"always" = override ("off"
// is the explicit force-off). Resolved by Config.ResolveToonOutput.
ToonOutput string `json:"toon_output,omitempty" mapstructure:"toon_output"`
EnabledTools []string `json:"enabled_tools,omitempty" mapstructure:"enabled_tools"` // Allowlist: only these tools are exposed; mutually exclusive with disabled_tools
DisabledTools []string `json:"disabled_tools,omitempty" mapstructure:"disabled_tools"` // Denylist: these tools are hidden; mutually exclusive with enabled_tools
// SourceRegistryID records which registry this server was added from (empty
// for manually-configured servers). MCP-866: surfaced in the approval /
// quarantine view so a reviewer can see a server's origin.
SourceRegistryID string `json:"source_registry_id,omitempty" mapstructure:"source_registry_id"`
// SourceRegistryProvenance records the source registry's provenance at add
// time (RegistryProvenanceOfficial / RegistryProvenanceCustom). It is purely
// informational (MCP-1072) — surfaced so a reviewer can see a server's origin
// — and no longer gates quarantine or skip_quarantine.
SourceRegistryProvenance string `json:"source_registry_provenance,omitempty" mapstructure:"source_registry_provenance"`
// AuthBroker holds the per-upstream `oauth_connect` credential-connect
// block (spec 074, server edition only). When set, a user can complete a
// per-user consent flow and have their credential STORED encrypted for this
// upstream — nothing injects it into the outbound request (Spec 107
// FR-034); the call path keeps using the server's own headers/oauth
// settings. The concrete type is build-tagged: a validated struct in the
// server edition, an opaque json.RawMessage carrier in the personal
// edition (preserved verbatim through load → save → PATCH, FR-040), so
// personal-edition behavior is unaffected. swaggerignore mirrors ServerEdition.
AuthBroker *AuthBrokerConfig `json:"auth_broker,omitempty" mapstructure:"auth_broker" swaggerignore:"true"`
}
// OAuthConfig represents OAuth configuration for a server
type OAuthConfig struct {
ClientID string `json:"client_id,omitempty" mapstructure:"client_id"`
ClientSecret string `json:"client_secret,omitempty" mapstructure:"client_secret"`
RedirectURI string `json:"redirect_uri,omitempty" mapstructure:"redirect_uri"`
CallbackBaseURL string `json:"callback_base_url,omitempty" mapstructure:"callback_base_url"`
Scopes []string `json:"scopes,omitempty" mapstructure:"scopes"`
PKCEEnabled bool `json:"pkce_enabled,omitempty" mapstructure:"pkce_enabled"`
ExtraParams map[string]string `json:"extra_params,omitempty" mapstructure:"extra_params"` // Additional OAuth parameters (e.g., RFC 8707 resource)
// Spec 113-b: optional per-server discovery overrides. Each is an absolute
// https URL (http only on a loopback host) with no query, fragment or
// userinfo; validated at write time only (ValidateOAuthEndpointOverrides).
// The endpoint overrides rewrite the matching fields of the authorization
// server metadata mcp-go reads; AuthServerMetadataURL replaces discovery.
AuthorizationEndpoint string `json:"authorization_endpoint,omitempty" mapstructure:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint,omitempty" mapstructure:"token_endpoint"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty" mapstructure:"registration_endpoint"`
AuthServerMetadataURL string `json:"auth_server_metadata_url,omitempty" mapstructure:"auth_server_metadata_url"`
}
// IsolationMode selects how an stdio MCP server's process is isolated (MCP-34.2).
//
// - "docker" — run the server inside a Docker container (the original behavior).
// - "sandbox" — run under a native OS sandbox (Landlock LSM + rlimits on Linux;
// see MCP-34). No daemon required.
// - "none" — no isolation; the server process runs directly on the host.
//
// The empty string means "unset": back-compat code falls back to the legacy
// boolean Enabled flag (enabled:true ⇒ docker, enabled:false ⇒ none).
type IsolationMode string
const (
// IsolationModeDocker runs the server inside a Docker container.
IsolationModeDocker IsolationMode = "docker"
// IsolationModeSandbox runs the server under a native OS sandbox (Landlock/rlimits).
IsolationModeSandbox IsolationMode = "sandbox"
// IsolationModeNone disables isolation; the process runs directly.
IsolationModeNone IsolationMode = "none"
)
// IsValid reports whether the mode is a recognized value. The empty string
// ("unset") is treated as valid because the global config falls back to the
// legacy Enabled bool; callers that require an explicit mode should check for
// emptiness separately.
func (m IsolationMode) IsValid() bool {
switch m {
case IsolationModeDocker, IsolationModeSandbox, IsolationModeNone, "":
return true
default:
return false
}
}
// DockerIsolationConfig represents global Docker isolation settings
type DockerIsolationConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"` // Global enable/disable for Docker isolation (legacy; superseded by Mode)
Mode IsolationMode `json:"mode,omitempty" mapstructure:"mode"` // Isolation mode: "docker" | "sandbox" | "none". Empty falls back to Enabled (MCP-34.2)
EnableCacheVolume bool `json:"enable_cache_volume" mapstructure:"enable_cache_volume"` // Mount shared cache volumes for faster restarts (default: true)
DefaultImages map[string]string `json:"default_images" mapstructure:"default_images"` // Map of runtime type to Docker image
Registry string `json:"registry,omitempty" mapstructure:"registry"` // Custom registry (defaults to docker.io)
NetworkMode string `json:"network_mode,omitempty" mapstructure:"network_mode"` // Docker network mode (default: bridge)
MemoryLimit string `json:"memory_limit,omitempty" mapstructure:"memory_limit"` // Memory limit for containers
CPULimit string `json:"cpu_limit,omitempty" mapstructure:"cpu_limit"` // CPU limit for containers
Timeout Duration `json:"timeout,omitempty" mapstructure:"timeout" swaggertype:"string"` // Container startup timeout
ExtraArgs []string `json:"extra_args,omitempty" mapstructure:"extra_args"` // Additional docker run arguments
LogDriver string `json:"log_driver,omitempty" mapstructure:"log_driver"` // Docker log driver (default: json-file)
LogMaxSize string `json:"log_max_size,omitempty" mapstructure:"log_max_size"` // Maximum size of log files (default: 100m)
LogMaxFiles string `json:"log_max_files,omitempty" mapstructure:"log_max_files"` // Maximum number of log files (default: 3)
}
// IsolationConfig represents per-server isolation settings
type IsolationConfig struct {
Enabled *bool `json:"enabled,omitempty" mapstructure:"enabled"` // Enable Docker isolation for this server (nil = inherit global; legacy, superseded by Mode)
Mode *IsolationMode `json:"mode,omitempty" mapstructure:"mode"` // Isolation mode: "docker" | "sandbox" | "none" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy "enabled" flag (true ⇒ docker, false ⇒ none)
Image string `json:"image,omitempty" mapstructure:"image"` // Custom Docker image (overrides default)
NetworkMode string `json:"network_mode,omitempty" mapstructure:"network_mode"` // Custom network mode for this server
ExtraArgs []string `json:"extra_args,omitempty" mapstructure:"extra_args"` // Additional docker run arguments for this server
WorkingDir string `json:"working_dir,omitempty" mapstructure:"working_dir"` // Custom working directory in container
LogDriver string `json:"log_driver,omitempty" mapstructure:"log_driver"` // Docker log driver override for this server
LogMaxSize string `json:"log_max_size,omitempty" mapstructure:"log_max_size"` // Maximum size of log files override
LogMaxFiles string `json:"log_max_files,omitempty" mapstructure:"log_max_files"` // Maximum number of log files override
}
// ResolvedMode returns the effective global isolation mode, applying back-compat
// mapping from the legacy Enabled bool (MCP-34.2):
//
// - an explicit Mode always wins;
// - otherwise enabled:true ⇒ docker, enabled:false ⇒ none;
// - a nil config resolves to none.
func (dic *DockerIsolationConfig) ResolvedMode() IsolationMode {
if dic == nil {
return IsolationModeNone
}
if dic.Mode != "" {
return dic.Mode
}
if dic.Enabled {
return IsolationModeDocker
}
return IsolationModeNone
}
// HasEnabledOverride reports whether this server sets the legacy `enabled`
// bool at all. False means "inherit the global isolation setting" (GH #1142).
func (ic *IsolationConfig) HasEnabledOverride() bool {
return ic != nil && ic.Enabled != nil
}
// HasModeOverride reports whether this server sets a per-server
// `isolation.mode` override. A nil pointer AND a pointer to the empty string
// both mean "unset" — the empty string is documented as the unset mode, and
// treating it as an override resolved servers to a mode the spawn path does not
// implement while reporting them isolated (GH #1142).
func (ic *IsolationConfig) HasModeOverride() bool {
return ic != nil && ic.Mode != nil && *ic.Mode != ""
}
// IsExplicitlyEnabled reports whether this server opts IN to isolation via the
// legacy `enabled` bool. A nil Enabled is "inherit", never an opt-in.
//
// This is NOT the answer to "is this server isolated" — that question has
// exactly one answer, upstream/core.IsolationManager.ResolveIsolation, which
// also accounts for the global mode and the structural gates.
func (ic *IsolationConfig) IsExplicitlyEnabled() bool {
return ic != nil && ic.Enabled != nil && *ic.Enabled
}
// IsExplicitlyDisabled reports whether this server opts OUT of isolation via
// the legacy `enabled` bool. A nil Enabled is "inherit", never an opt-out.
func (ic *IsolationConfig) IsExplicitlyDisabled() bool {
return ic != nil && ic.Enabled != nil && !*ic.Enabled
}
// BoolPtr returns a pointer to the given bool value.
// Useful for setting *bool fields in struct literals.
func BoolPtr(b bool) *bool {
return &b
}
// DockerRecoveryConfig represents Docker recovery settings for the tray application
type DockerRecoveryConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"` // Enable Docker recovery monitoring (default: true)
CheckIntervals []Duration `json:"check_intervals,omitempty" mapstructure:"intervals" swaggerignore:"true"` // Custom health check intervals (exponential backoff)
MaxRetries int `json:"max_retries,omitempty" mapstructure:"max_retries"` // Maximum retry attempts (0 = unlimited)
NotifyOnStart bool `json:"notify_on_start" mapstructure:"notify_on_start"` // Show notification when recovery starts (default: true)
NotifyOnSuccess bool `json:"notify_on_success" mapstructure:"notify_on_success"` // Show notification on successful recovery (default: true)
NotifyOnFailure bool `json:"notify_on_failure" mapstructure:"notify_on_failure"` // Show notification on recovery failure (default: true)
NotifyOnRetry bool `json:"notify_on_retry" mapstructure:"notify_on_retry"` // Show notification on each retry (default: false)
PersistentState bool `json:"persistent_state" mapstructure:"persistent_state"` // Save recovery state across restarts (default: true)
}
// DefaultCheckIntervals returns the default Docker recovery check intervals
func DefaultCheckIntervals() []time.Duration {
return []time.Duration{
You can’t perform that action at this time.
