forked from smart-mcp-proxy/mcpproxy-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
4355 lines (3820 loc) · 152 KB
/
server.go
File metadata and controls
4355 lines (3820 loc) · 152 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 httpapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"go.uber.org/zap"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/auth"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/connect"
"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/management"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/observability"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/reqcontext"
internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/secret"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/storage"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/telemetry"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/transport"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/updatecheck"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/core"
)
const (
asyncToggleTimeout = 5 * time.Second
secretTypeKeyring = "keyring"
)
// ServerController defines the interface for core server functionality
type ServerController interface {
IsRunning() bool
IsReady() bool
GetListenAddress() string
GetUpstreamStats() map[string]interface{}
StartServer(ctx context.Context) error
StopServer() error
GetStatus() interface{}
StatusChannel() <-chan interface{}
EventsChannel() <-chan internalRuntime.Event
// SubscribeEvents creates a new per-client event subscription channel.
// Each SSE client should get its own channel to avoid competing for events.
SubscribeEvents() chan internalRuntime.Event
// UnsubscribeEvents closes and removes the subscription channel.
UnsubscribeEvents(chan internalRuntime.Event)
// Server management
GetAllServers() ([]map[string]interface{}, error)
AddServer(ctx context.Context, serverConfig *config.ServerConfig) error // T001: Add server
RemoveServer(ctx context.Context, serverName string) error // T002: Remove server
UpdateServer(ctx context.Context, serverName string, updates *config.ServerConfig) error
EnableServer(serverName string, enabled bool) error
GetToolApprovalStatus(serverName, toolName string) (string, error)
RestartServer(serverName string) error
ForceReconnectAllServers(reason string) error
GetDockerRecoveryStatus() *storage.DockerRecoveryState
QuarantineServer(serverName string, quarantined bool) error
GetQuarantinedServers() ([]map[string]interface{}, error)
UnquarantineServer(serverName string) error
GetManagementService() interface{} // Returns the management service for unified operations
DiscoverServerTools(ctx context.Context, serverName string) error
// Tools and search
GetServerTools(serverName string) ([]map[string]interface{}, error)
SearchTools(query string, limit int) ([]map[string]interface{}, error)
// Logs
GetServerLogs(serverName string, tail int) ([]contracts.LogEntry, error)
// Config and OAuth
ReloadConfiguration() error
GetConfigPath() string
GetLogDir() string
TriggerOAuthLogin(serverName string) error
// Secrets management
GetSecretResolver() *secret.Resolver
GetCurrentConfig() interface{}
NotifySecretsChanged(ctx context.Context, operation, secretName string) error
// Tool call history
GetToolCalls(limit, offset int) ([]*contracts.ToolCallRecord, int, error)
GetToolCallByID(id string) (*contracts.ToolCallRecord, error)
GetServerToolCalls(serverName string, limit int) ([]*contracts.ToolCallRecord, error)
ReplayToolCall(id string, arguments map[string]interface{}) (*contracts.ToolCallRecord, error)
GetToolCallsBySession(sessionID string, limit, offset int) ([]*contracts.ToolCallRecord, int, error)
// Session management
GetRecentSessions(limit int) ([]*contracts.MCPSession, int, error)
GetSessionByID(sessionID string) (*contracts.MCPSession, error)
// Configuration management
ValidateConfig(cfg *config.Config) ([]config.ValidationError, error)
ApplyConfig(cfg *config.Config, cfgPath string) (*internalRuntime.ConfigApplyResult, error)
GetConfig() (*config.Config, error)
// Token statistics
GetTokenSavings() (*contracts.ServerTokenMetrics, error)
// Tool execution
CallTool(ctx context.Context, toolName string, arguments map[string]interface{}) (interface{}, error)
// Registry browsing (Phase 7)
ListRegistries() ([]interface{}, error)
SearchRegistryServers(registryID, tag, query string, limit int) ([]interface{}, error)
// Version and updates
GetVersionInfo() *updatecheck.VersionInfo
RefreshVersionInfo() *updatecheck.VersionInfo
// Activity logging (RFC-003)
ListActivities(filter storage.ActivityFilter) ([]*storage.ActivityRecord, int, error)
GetActivity(id string) (*storage.ActivityRecord, error)
StreamActivities(filter storage.ActivityFilter) <-chan *storage.ActivityRecord
// Tool-level quarantine (Spec 032)
ListToolApprovals(serverName string) ([]*storage.ToolApprovalRecord, error)
ApproveTools(serverName string, toolNames []string, approvedBy string) error
ApproveAllTools(serverName string, approvedBy string) (int, error)
GetToolApproval(serverName, toolName string) (*storage.ToolApprovalRecord, error)
// Onboarding wizard (Spec 046)
GetOnboardingState() (*storage.OnboardingState, error)
SaveOnboardingState(state *storage.OnboardingState) error
// Activation state (Spec 044) — read-only access used by the v2
// onboarding wizard's Verify tab to detect whether any MCP client has
// successfully called this mcpproxy. Returns FirstMCPClientEver and
// MCPClientsSeenEver from the activation bucket.
GetActivationFirstMCPClient() (firstEver bool, seen []string)
}
// Server provides HTTP API endpoints with chi router
type Server struct {
controller ServerController
logger *zap.SugaredLogger
httpLogger *zap.Logger // Separate logger for HTTP requests
router *chi.Mux
observability *observability.Manager
tokenStore TokenStore // Agent token CRUD (T022)
dataDir string // Data directory for HMAC key (T022)
feedbackSubmitter FeedbackSubmitter // Feedback submission (Spec 036)
connectService *connect.Service // Client connect/disconnect operations
securityController SecurityController // Security scanner operations (Spec 039)
// telemetryRegistry is the Tier 2 counter aggregator (Spec 042). May be
// nil before SetTelemetryRegistry is called; middlewares use the nil-safe
// telemetry helpers so the call sites do not need to nil-check.
telemetryRegistry *telemetry.CounterRegistry
// telemetryPayloadProvider returns the live telemetry.Service so the
// /api/v1/telemetry/payload endpoint can render the next heartbeat payload
// with runtime stats attached. May be nil before SetTelemetryPayloadProvider
// is called.
telemetryPayloadProvider func() *telemetry.Service
}
// SetTelemetryRegistry attaches the Tier 2 counter registry. Spec 042. Must
// be called before the router serves requests for the surface and REST
// endpoint counters to populate.
func (s *Server) SetTelemetryRegistry(reg *telemetry.CounterRegistry) {
s.telemetryRegistry = reg
}
// SetTelemetryPayloadProvider attaches a provider that returns the live
// telemetry service. Used by the /api/v1/telemetry/payload endpoint to render
// the next heartbeat payload with runtime stats. Spec 042.
func (s *Server) SetTelemetryPayloadProvider(fn func() *telemetry.Service) {
s.telemetryPayloadProvider = fn
}
// NewServer creates a new HTTP API server
func NewServer(controller ServerController, logger *zap.SugaredLogger, obs *observability.Manager) *Server {
// Create HTTP logger for API request logging
httpLogger, err := logs.CreateHTTPLogger(nil) // Use default config
if err != nil {
logger.Warnf("Failed to create HTTP logger: %v", err)
httpLogger = zap.NewNop() // Use no-op logger as fallback
}
s := &Server{
controller: controller,
logger: logger,
httpLogger: httpLogger,
router: chi.NewRouter(),
observability: obs,
}
s.setupRoutes()
return s
}
// SetTokenStore configures agent token management on the server.
// This must be called after NewServer and before serving requests
// to enable the /api/v1/tokens endpoints.
func (s *Server) SetTokenStore(store TokenStore, dataDir string) {
s.tokenStore = store
s.dataDir = dataDir
}
// SetFeedbackSubmitter configures the feedback submission handler (Spec 036).
func (s *Server) SetFeedbackSubmitter(submitter FeedbackSubmitter) {
s.feedbackSubmitter = submitter
}
// SetConnectService configures the client connect/disconnect service.
func (s *Server) SetConnectService(svc *connect.Service) {
s.connectService = svc
}
// Router returns the underlying chi.Mux for external route registration.
// This is used by the server edition to mount OAuth routes outside
// the default API key authentication group.
func (s *Server) Router() *chi.Mux {
return s.router
}
// apiKeyAuthMiddleware creates middleware for API key authentication.
// Connections from Unix socket/named pipe (tray) are trusted and skip API key validation.
// Supports both global API key (admin) and agent tokens (mcp_agt_ prefix) with scope enforcement.
func (s *Server) apiKeyAuthMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// SECURITY: Trust connections from tray (Unix socket/named pipe)
// These connections are authenticated via OS-level permissions (UID/SID matching)
source := transport.GetConnectionSource(r.Context())
if source == transport.ConnectionSourceTray {
s.logger.Debug("Tray connection - skipping API key validation",
zap.String("path", r.URL.Path),
zap.String("remote_addr", r.RemoteAddr),
zap.String("source", string(source)))
ctx := auth.WithAuthContext(r.Context(), auth.AdminContext())
next.ServeHTTP(w, r.WithContext(ctx))
return
}
// Get config from controller
configInterface := s.controller.GetCurrentConfig()
if configInterface == nil {
// No config available (testing scenario) - allow through
next.ServeHTTP(w, r)
return
}
// Cast to config type
cfg, ok := configInterface.(*config.Config)
if !ok {
// Config is not the expected type (testing scenario) - allow through
next.ServeHTTP(w, r)
return
}
// SECURITY: API key is REQUIRED for all TCP connections to REST API
// Empty API key is not allowed - this prevents accidental exposure
if cfg.APIKey == "" {
s.logger.Warn("TCP connection rejected - API key not configured",
zap.String("path", r.URL.Path),
zap.String("remote_addr", r.RemoteAddr))
s.writeError(w, r, http.StatusUnauthorized, "API key authentication required but not configured. Please set MCPPROXY_API_KEY or configure api_key in config file.")
return
}
// Extract token from request
token := ExtractToken(r)
if token == "" {
s.logger.Warn("TCP connection with missing API key",
zap.String("path", r.URL.Path),
zap.String("remote_addr", r.RemoteAddr))
s.writeError(w, r, http.StatusUnauthorized, "Invalid or missing API key")
return
}
// Check if this is an agent token (mcp_agt_ prefix)
if strings.HasPrefix(token, auth.TokenPrefixStr) {
s.handleAgentTokenAuth(w, r, next, token)
return
}
// Check if the token matches the global API key (admin)
if token == cfg.APIKey {
s.logger.Debug("TCP connection with valid API key",
zap.String("path", r.URL.Path),
zap.String("remote_addr", r.RemoteAddr))
ctx := auth.WithAuthContext(r.Context(), auth.AdminContext())
next.ServeHTTP(w, r.WithContext(ctx))
return
}
// Token doesn't match anything
s.logger.Warn("TCP connection with invalid API key",
zap.String("path", r.URL.Path),
zap.String("remote_addr", r.RemoteAddr))
s.writeError(w, r, http.StatusUnauthorized, "Invalid or missing API key")
})
}
}
// handleAgentTokenAuth validates an agent token and sets the appropriate AuthContext.
func (s *Server) handleAgentTokenAuth(w http.ResponseWriter, r *http.Request, next http.Handler, token string) {
if s.tokenStore == nil || s.dataDir == "" {
s.logger.Warn("Agent token presented but token store not configured",
zap.String("path", r.URL.Path),
zap.String("remote_addr", r.RemoteAddr))
s.writeError(w, r, http.StatusUnauthorized, "Agent tokens are not configured on this server")
return
}
hmacKey, err := auth.GetOrCreateHMACKey(s.dataDir)
if err != nil {
s.logger.Error("Failed to get HMAC key for agent token validation", zap.Error(err))
s.writeError(w, r, http.StatusInternalServerError, "Internal server error")
return
}
agentToken, err := s.tokenStore.ValidateAgentToken(token, hmacKey)
if err != nil {
s.logger.Warn("Agent token validation failed",
zap.String("path", r.URL.Path),
zap.String("remote_addr", r.RemoteAddr),
zap.String("error", err.Error()))
s.writeError(w, r, http.StatusUnauthorized, fmt.Sprintf("Agent token invalid: %s", err.Error()))
return
}
// Update last-used timestamp in background
go func() {
if updateErr := s.tokenStore.UpdateAgentTokenLastUsed(agentToken.Name); updateErr != nil {
s.logger.Warn("Failed to update agent token last-used timestamp",
zap.String("name", agentToken.Name),
zap.Error(updateErr))
}
}()
authCtx := &auth.AuthContext{
Type: auth.AuthTypeAgent,
AgentName: agentToken.Name,
TokenPrefix: agentToken.TokenPrefix,
AllowedServers: agentToken.AllowedServers,
Permissions: agentToken.Permissions,
}
ctx := auth.WithAuthContext(r.Context(), authCtx)
s.logger.Debug("Agent token authenticated",
zap.String("agent_name", agentToken.Name),
zap.String("token_prefix", agentToken.TokenPrefix),
zap.String("path", r.URL.Path),
zap.String("remote_addr", r.RemoteAddr))
next.ServeHTTP(w, r.WithContext(ctx))
}
// ExtractToken extracts the authentication token from the request.
// It checks (in order): X-API-Key header, Authorization: Bearer header, ?apikey= query param.
// Returns an empty string if no token is found.
func ExtractToken(r *http.Request) string {
// 1. Check X-API-Key header
if key := r.Header.Get("X-API-Key"); key != "" {
return key
}
// 2. Check Authorization: Bearer header
if authHeader := r.Header.Get("Authorization"); authHeader != "" {
if strings.HasPrefix(authHeader, "Bearer ") {
if token := strings.TrimPrefix(authHeader, "Bearer "); token != "" {
return token
}
}
}
// 3. Check query parameter (for SSE and Web UI initial load)
if key := r.URL.Query().Get("apikey"); key != "" {
return key
}
return ""
}
// correlationIDMiddleware injects correlation ID and request source into context
func (s *Server) correlationIDMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Generate or retrieve correlation ID
correlationID := r.Header.Get("X-Correlation-ID")
if correlationID == "" {
correlationID = reqcontext.GenerateCorrelationID()
}
// Inject correlation ID and request source into context
ctx := reqcontext.WithCorrelationID(r.Context(), correlationID)
ctx = reqcontext.WithRequestSource(ctx, reqcontext.SourceRESTAPI)
// Add correlation ID to response headers for client tracking
w.Header().Set("X-Correlation-ID", correlationID)
// Continue with enriched context
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// ServeHTTP implements http.Handler
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
// setupRoutes configures all API routes
func (s *Server) setupRoutes() {
s.logger.Debug("Setting up HTTP API routes")
// Observability middleware (if available)
if s.observability != nil {
s.router.Use(s.observability.HTTPMiddleware())
s.logger.Debug("Observability middleware configured")
}
// Core middleware
// Request ID middleware MUST be first to ensure all responses have X-Request-Id header
s.router.Use(RequestIDMiddleware)
s.router.Use(RequestIDLoggerMiddleware(s.logger)) // Add request_id to logger context
s.router.Use(s.httpLoggingMiddleware()) // Custom HTTP API logging
s.router.Use(middleware.Recoverer)
s.router.Use(s.correlationIDMiddleware()) // Correlation ID and request source tracking
s.logger.Debug("Core middleware configured (request ID, logging, recovery, correlation ID)")
// CORS headers for browser access
s.router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-API-Key")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
})
// Health and readiness endpoints (Kubernetes-compatible with legacy aliases)
// See healthzHandler() and readyzHandler() for swagger documentation
livenessHandler := func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok"}`))
}
readinessHandler := func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
if s.controller.IsReady() {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"ready":true}`))
return
}
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte(`{"ready":false}`))
}
// Observability endpoints (registered first to avoid conflicts)
if s.observability != nil {
if health := s.observability.Health(); health != nil {
s.router.Get("/healthz", health.HealthzHandler())
s.router.Get("/readyz", health.ReadyzHandler())
}
if metrics := s.observability.Metrics(); metrics != nil {
s.router.Handle("/metrics", metrics.Handler())
}
} else {
// Register custom health endpoints only if observability is not available
for _, path := range []string{"/livez", "/healthz", "/health"} {
s.router.Get(path, livenessHandler)
}
for _, path := range []string{"/readyz", "/ready"} {
s.router.Get(path, readinessHandler)
}
}
// Always register /ready as backup endpoint for tray compatibility
s.router.Get("/ready", readinessHandler)
// API v1 routes with timeout and authentication middleware
s.router.Route("/api/v1", func(r chi.Router) {
// Apply timeout and API key authentication middleware to API routes only
r.Use(middleware.Timeout(60 * time.Second))
r.Use(s.apiKeyAuthMiddleware())
// Spec 042: Tier 2 telemetry middlewares. Both fetch the registry via
// a closure so the registry can be installed after route setup.
r.Use(SurfaceClassifierMiddleware(func() *telemetry.CounterRegistry { return s.telemetryRegistry }))
r.Use(RESTEndpointHistogramMiddleware(func() *telemetry.CounterRegistry { return s.telemetryRegistry }))
// Status endpoint
r.Get("/status", s.handleGetStatus)
// Info endpoint (server version, web UI URL, etc.)
r.Get("/info", s.handleGetInfo)
// Routing mode endpoint
r.Get("/routing", s.handleGetRouting)
// Server management
r.Get("/servers", s.handleGetServers)
r.Post("/servers", s.handleAddServer) // T001: Add server
r.Post("/servers/import", s.handleImportServers) // Import from file upload
r.Post("/servers/import/json", s.handleImportServersJSON) // Import from JSON/TOML content
r.Get("/servers/import/paths", s.handleGetCanonicalConfigPaths) // Get canonical config paths
r.Post("/servers/import/path", s.handleImportFromPath) // Import from file path
r.Post("/servers/reconnect", s.handleForceReconnectServers)
// T076-T077: Bulk operation routes
r.Post("/servers/restart_all", s.handleRestartAll)
r.Post("/servers/enable_all", s.handleEnableAll)
r.Post("/servers/disable_all", s.handleDisableAll)
r.Route("/servers/{id}", func(r chi.Router) {
r.Patch("/", s.handlePatchServer) // Partial update server config
r.Delete("/", s.handleRemoveServer) // T002: Remove server
r.Post("/config-to-secret", s.handleConvertConfigToSecret) // Move a header / env value into OS keyring
r.Post("/enable", s.handleEnableServer)
r.Post("/disable", s.handleDisableServer)
r.Post("/restart", s.handleRestartServer)
r.Post("/login", s.handleServerLogin)
r.Post("/logout", s.handleServerLogout)
r.Post("/quarantine", s.handleQuarantineServer)
r.Post("/unquarantine", s.handleUnquarantineServer)
r.Post("/discover-tools", s.handleDiscoverServerTools)
r.Get("/tools", s.handleGetServerTools)
r.Get("/logs", s.handleGetServerLogs)
// Spec 044: per-server diagnostics with stable error_code.
r.Get("/diagnostics", s.handleGetServerDiagnostics)
r.Get("/tool-calls", s.handleGetServerToolCalls)
// Tool-level quarantine (Spec 032)
r.Post("/tools/approve", s.handleApproveTools)
r.Post("/tools/{tool}/enabled", s.handleSetToolEnabled)
// Bulk per-tool enable/disable. Mirrors /servers/enable_all
// + /servers/disable_all but scoped to a single server's tools.
r.Post("/tools/enable_all", s.handleSetAllToolsEnabled(true))
r.Post("/tools/disable_all", s.handleSetAllToolsEnabled(false))
r.Get("/tools/{tool}/diff", s.handleGetToolDiff)
r.Get("/tools/export", s.handleExportToolDescriptions)
// Security scanner scan/approval routes (Spec 039)
r.Post("/scan", s.handleStartScan)
r.Get("/scan/status", s.handleGetScanStatus)
r.Get("/scan/report", s.handleGetScanReport)
r.Post("/scan/cancel", s.handleCancelScan)
r.Get("/scan/files", s.handleGetScanFiles)
r.Post("/security/approve", s.handleSecurityApprove)
r.Post("/security/reject", s.handleSecurityReject)
r.Get("/integrity", s.handleCheckIntegrity)
})
// Search
r.Get("/index/search", s.handleSearchTools)
// Docker recovery status
r.Get("/docker/status", s.handleGetDockerStatus)
// Secrets management
r.Route("/secrets", func(r chi.Router) {
r.Get("/refs", s.handleGetSecretRefs)
r.Get("/config", s.handleGetConfigSecrets)
r.Post("/migrate", s.handleMigrateSecrets)
r.Post("/", s.handleSetSecret)
r.Delete("/{name}", s.handleDeleteSecret)
})
// Diagnostics
r.Get("/diagnostics", s.handleGetDiagnostics)
r.Get("/doctor", s.handleGetDiagnostics) // Alias for consistency with CLI command
// Spec 044: per-server diagnostics + fix invocation.
r.Post("/diagnostics/fix", s.handleInvokeFix)
// Telemetry payload preview (Spec 042) — renders the next heartbeat
// payload with runtime stats attached. No network call is made.
r.Get("/telemetry/payload", s.handleGetTelemetryPayload)
// Token statistics
r.Get("/stats/tokens", s.handleGetTokenStats)
// Tool call history
r.Get("/tool-calls", s.handleGetToolCalls)
r.Get("/tool-calls/{id}", s.handleGetToolCallDetail)
r.Post("/tool-calls/{id}/replay", s.handleReplayToolCall)
// Session management
r.Get("/sessions", s.handleGetSessions)
r.Get("/sessions/{id}", s.handleGetSessionDetail)
// Tool execution
r.Post("/tools/call", s.handleCallTool)
// Code execution endpoint (for CLI client mode)
r.Post("/code/exec", NewCodeExecHandler(s.controller, s.logger).ServeHTTP)
// Configuration management
r.Get("/config", s.handleGetConfig)
r.Post("/config/validate", s.handleValidateConfig)
r.Post("/config/apply", s.handleApplyConfig)
r.Patch("/config/docker-isolation", s.handlePatchDockerIsolation)
// Registry browsing (Phase 7)
r.Get("/registries", s.handleListRegistries)
r.Get("/registries/{id}/servers", s.handleSearchRegistryServers)
// Activity logging (RFC-003)
r.Get("/activity", s.handleListActivity)
r.Get("/activity/summary", s.handleActivitySummary)
r.Get("/activity/export", s.handleExportActivity)
r.Get("/activity/{id}", s.handleGetActivityDetail)
// Annotation coverage (Spec 035)
r.Get("/annotations/coverage", s.handleAnnotationCoverage)
// Agent token management (Spec 028)
r.Route("/tokens", func(r chi.Router) {
r.Post("/", s.handleCreateToken)
r.Get("/", s.handleListTokens)
r.Route("/{name}", func(r chi.Router) {
r.Get("/", s.handleGetToken)
r.Delete("/", s.handleRevokeToken)
r.Post("/regenerate", s.handleRegenerateToken)
})
})
// Feedback submission (Spec 036)
r.Post("/feedback", s.handleFeedback)
// Client connect/disconnect
r.Get("/connect", s.handleGetConnectStatus)
r.Post("/connect/{client}", s.handleConnectClient)
r.Delete("/connect/{client}", s.handleDisconnectClient)
// Onboarding wizard (Spec 046)
r.Get("/onboarding/state", s.handleGetOnboardingState)
r.Post("/onboarding/mark", s.handleMarkOnboardingState)
// Security scanner management routes (Spec 039)
r.Route("/security", func(r chi.Router) {
r.Get("/scanners", s.handleListScanners)
r.Post("/scanners/{id}/enable", s.handleInstallScanner)
r.Post("/scanners/{id}/disable", s.handleRemoveScanner)
r.Put("/scanners/{id}/config", s.handleConfigureScanner)
r.Get("/scanners/{id}/status", s.handleGetScannerStatus)
r.Get("/overview", s.handleSecurityOverview)
// Legacy routes (backwards compatibility)
r.Post("/scanners/install", s.handleInstallScanner)
r.Delete("/scanners/{id}", s.handleRemoveScanner)
// Batch scan operations
r.Post("/scan-all", s.handleScanAll)
r.Get("/queue", s.handleGetQueueProgress)
r.Post("/cancel-all", s.handleCancelAllScans)
// Scan history
r.Get("/scans", s.handleListScanHistory)
r.Get("/scans/{jobId}/report", s.handleGetScanReportByJobID)
})
})
// SSE events (protected by API key) - support both GET and HEAD
s.router.With(s.apiKeyAuthMiddleware()).Method("GET", "/events", http.HandlerFunc(s.handleSSEEvents))
s.router.With(s.apiKeyAuthMiddleware()).Method("HEAD", "/events", http.HandlerFunc(s.handleSSEEvents))
// Note: Swagger UI is mounted directly on the main mux (not via HTTP API server)
// See internal/server/server.go for swagger handler registration
s.logger.Debug("HTTP API routes setup completed",
"api_routes", "/api/v1/*",
"sse_route", "/events",
"health_routes", "/healthz,/readyz,/livez,/ready")
}
// httpLoggingMiddleware creates custom HTTP request logging middleware
func (s *Server) httpLoggingMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Create a response writer wrapper to capture status code
ww := &responseWriter{ResponseWriter: w, statusCode: 200}
// Process request
next.ServeHTTP(ww, r)
duration := time.Since(start)
// Log request details to http.log
s.httpLogger.Info("HTTP API Request",
zap.String("method", r.Method),
zap.String("path", r.URL.Path),
zap.String("query", r.URL.RawQuery),
zap.String("remote_addr", r.RemoteAddr),
zap.String("user_agent", r.UserAgent()),
zap.Int("status", ww.statusCode),
zap.Duration("duration", duration),
zap.String("referer", r.Referer()),
zap.Int64("content_length", r.ContentLength),
)
})
}
}
// responseWriter wraps http.ResponseWriter to capture status code
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
// Flush implements http.Flusher interface by delegating to the underlying ResponseWriter
func (rw *responseWriter) Flush() {
if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
// Health and readiness documentation handlers (for swagger generation only)
// The actual handlers are registered in setupRoutes() and may come from observability package
// healthzHandler godoc
// @Summary Get health status
// @Description Get comprehensive health status including all component health (Kubernetes-compatible liveness probe)
// @Tags health
// @Produce json
// @Success 200 {object} observability.HealthResponse "Service is healthy"
// @Failure 503 {object} observability.HealthResponse "Service is unhealthy"
// @Router /healthz [get]
func _healthzHandler() {} //nolint:unused // swagger documentation stub
// readyzHandler godoc
// @Summary Get readiness status
// @Description Get readiness status including all component readiness checks (Kubernetes-compatible readiness probe)
// @Tags health
// @Produce json
// @Success 200 {object} observability.ReadinessResponse "Service is ready"
// @Failure 503 {object} observability.ReadinessResponse "Service is not ready"
// @Router /readyz [get]
func _readyzHandler() {} //nolint:unused // swagger documentation stub
// JSON response helpers
func (s *Server) writeJSON(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(data); err != nil {
s.logger.Error("Failed to encode JSON response", "error", err)
}
}
// writeError writes an error response including request_id from the request context
// T014: Updated signature to include request for request_id extraction
func (s *Server) writeError(w http.ResponseWriter, r *http.Request, status int, message string) {
requestID := reqcontext.GetRequestID(r.Context())
s.writeJSON(w, status, contracts.NewErrorResponseWithRequestID(message, requestID))
}
// getRequestLogger returns a logger with request_id attached, or falls back to the server logger
// T019: Helper for request-scoped logging
func (s *Server) getRequestLogger(r *http.Request) *zap.SugaredLogger {
if r == nil {
return s.logger
}
if logger := GetLogger(r.Context()); logger != nil {
return logger
}
return s.logger
}
func (s *Server) writeSuccess(w http.ResponseWriter, data interface{}) {
s.writeJSON(w, http.StatusOK, contracts.NewSuccessResponse(data))
}
// API v1 handlers
// handleGetStatus godoc
// @Summary Get server status
// @Description Get comprehensive server status including running state, listen address, upstream statistics, and timestamp
// @Tags status
// @Produce json
// @Security ApiKeyAuth
// @Security ApiKeyQuery
// @Success 200 {object} contracts.SuccessResponse "Server status information"
// @Failure 500 {object} contracts.ErrorResponse "Internal server error"
// @Router /api/v1/status [get]
func (s *Server) handleGetStatus(w http.ResponseWriter, _ *http.Request) {
// Get routing mode from config
routingMode := config.RoutingModeRetrieveTools
if cfg, err := s.controller.GetConfig(); err == nil && cfg != nil && cfg.RoutingMode != "" {
routingMode = cfg.RoutingMode
}
response := map[string]interface{}{
"running": s.controller.IsRunning(),
"edition": editionValue,
"listen_addr": s.controller.GetListenAddress(),
"upstream_stats": s.controller.GetUpstreamStats(),
"status": s.controller.GetStatus(),
"routing_mode": routingMode,
"timestamp": time.Now().Unix(),
}
// Spec 044 (FR-018): expose process-level env_kind + env_markers so the
// tray and CLI can surface the classifier verdict without waiting for the
// next heartbeat. DetectEnvKindOnce is cached, so repeated calls are free.
envKind, envMarkers := telemetry.DetectEnvKindOnce()
response["env_kind"] = string(envKind)
response["env_markers"] = envMarkers
// Spec 044 (T041): expose the activation funnel snapshot alongside
// env_kind. Read-only — mutation happens on MCP/connect events, never
// through this endpoint. nil when the telemetry service (or activation
// store) is not wired (e.g. very early startup).
if s.telemetryPayloadProvider != nil {
if svc := s.telemetryPayloadProvider(); svc != nil {
if store := svc.ActivationStore(); store != nil {
if db := svc.ActivationDB(); db != nil {
if st, err := store.Load(db); err == nil {
response["activation"] = st
}
}
}
}
}
// Spec 044 (US3): expose launch_source + autostart_enabled. launch_source
// is the cached classifier result (no installer-clearing side-effect here
// — this endpoint is read-only). autostart_enabled reads the tray-owned
// sidecar with its 1h TTL; nil on Linux / tray not running / malformed.
response["launch_source"] = string(telemetry.DetectLaunchSourceOnce())
response["autostart_enabled"] = telemetry.DefaultAutostartReader().Read()
s.writeSuccess(w, response)
}
// handleGetRouting godoc
// @Summary Get routing mode information
// @Description Get the current routing mode and available MCP endpoints
// @Tags status
// @Produce json
// @Security ApiKeyAuth
// @Security ApiKeyQuery
// @Success 200 {object} contracts.SuccessResponse "Routing mode information"
// @Router /api/v1/routing [get]
func (s *Server) handleGetRouting(w http.ResponseWriter, _ *http.Request) {
routingMode := config.RoutingModeRetrieveTools
if cfg, err := s.controller.GetConfig(); err == nil && cfg != nil && cfg.RoutingMode != "" {
routingMode = cfg.RoutingMode
}
// Build mode description
var description string
switch routingMode {
case config.RoutingModeDirect:
description = "All upstream tools exposed directly via serverName__toolName naming"
case config.RoutingModeCodeExecution:
description = "JavaScript orchestration via code_execution tool with tool catalog"
default:
description = "BM25 search via retrieve_tools + call_tool variants (default)"
}
response := map[string]interface{}{
"routing_mode": routingMode,
"description": description,
"endpoints": map[string]interface{}{
"default": "/mcp",
"direct": "/mcp/all",
"code_execution": "/mcp/code",
"retrieve_tools": "/mcp/call",
},
"available_modes": []string{
config.RoutingModeRetrieveTools,
config.RoutingModeDirect,
config.RoutingModeCodeExecution,
},
}
s.writeSuccess(w, response)
}
// handleGetInfo godoc
// @Summary Get server information
// @Description Get essential server metadata including version, web UI URL, endpoint addresses, and update availability
// @Description This endpoint is designed for tray-core communication and version checking
// @Description Use refresh=true query parameter to force an immediate update check against GitHub
// @Tags status
// @Produce json
// @Param refresh query boolean false "Force immediate update check against GitHub"
// @Security ApiKeyAuth
// @Security ApiKeyQuery
// @Success 200 {object} contracts.APIResponse{data=contracts.InfoResponse} "Server information with optional update info"
// @Failure 500 {object} contracts.ErrorResponse "Internal server error"
// @Router /api/v1/info [get]
func (s *Server) handleGetInfo(w http.ResponseWriter, r *http.Request) {
listenAddr := s.controller.GetListenAddress()
// Build web UI URL from listen address (includes API key if configured)
webUIURL := s.buildWebUIURLWithAPIKey(listenAddr, r)
// Get version from build info or environment
version := GetBuildVersion()
response := map[string]interface{}{
"version": version,
"web_ui_url": webUIURL,
"listen_addr": listenAddr,
"endpoints": map[string]interface{}{
"http": listenAddr,
"socket": getSocketPath(), // Returns socket path if enabled, empty otherwise
},
}
// Add update information - refresh if requested
refresh := r.URL.Query().Get("refresh") == "true"
var versionInfo *updatecheck.VersionInfo
if refresh {
versionInfo = s.controller.RefreshVersionInfo()
} else {
versionInfo = s.controller.GetVersionInfo()
}
if versionInfo != nil {
response["update"] = versionInfo.ToAPIResponse()
}
s.writeSuccess(w, response)
}
// buildWebUIURL constructs the web UI URL based on listen address and request
func buildWebUIURL(listenAddr string, r *http.Request) string {
if listenAddr == "" {
return ""
}
// Determine protocol from request
protocol := "http"
if r.TLS != nil {
protocol = "https"
}
// If listen address is just a port, use localhost
if strings.HasPrefix(listenAddr, ":") {
return fmt.Sprintf("%s://127.0.0.1%s/ui/", protocol, listenAddr)
}
// Use the listen address as-is
return fmt.Sprintf("%s://%s/ui/", protocol, listenAddr)
}
// buildWebUIURLWithAPIKey constructs the web UI URL with API key included if configured
func (s *Server) buildWebUIURLWithAPIKey(listenAddr string, r *http.Request) string {
baseURL := buildWebUIURL(listenAddr, r)
if baseURL == "" {
return ""
}
// Add API key if configured
cfg, err := s.controller.GetConfig()
if err == nil && cfg.APIKey != "" {
return baseURL + "?apikey=" + cfg.APIKey
}
return baseURL
}
// buildVersion is set during build using -ldflags
var buildVersion = "development"
// editionValue identifies the MCPProxy edition (personal or teams).
var editionValue = "personal"
// GetBuildVersion returns the build version from build-time variables.
// This should be set during build using -ldflags.
func GetBuildVersion() string {
return buildVersion
}
// SetEdition sets the edition value (called from main during startup).
func SetEdition(edition string) {
editionValue = edition
}
// GetEdition returns the current edition.
func GetEdition() string {
return editionValue
}