-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathmain.go
More file actions
1124 lines (980 loc) · 39.1 KB
/
Copy pathmain.go
File metadata and controls
1124 lines (980 loc) · 39.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"crypto/subtle"
"encoding/json"
"fmt"
"io"
"log/slog"
"maps"
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime/debug"
"slices"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/sammcj/mcp-devtools/internal/mcpapi"
oauthclient "github.com/sammcj/mcp-devtools/internal/oauth/client"
oauthserver "github.com/sammcj/mcp-devtools/internal/oauth/server"
"github.com/sammcj/mcp-devtools/internal/oauth/types"
"github.com/sammcj/mcp-devtools/internal/registry"
"github.com/sammcj/mcp-devtools/internal/security"
"github.com/sammcj/mcp-devtools/internal/telemetry"
"github.com/sammcj/mcp-devtools/internal/tools"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v3"
"go.opentelemetry.io/otel/propagation"
"gopkg.in/yaml.v3"
// Import all tool packages to register them
_ "github.com/sammcj/mcp-devtools/internal/imports"
coderename "github.com/sammcj/mcp-devtools/internal/tools/code_rename"
"github.com/sammcj/mcp-devtools/internal/tools/proxy"
)
// Version information (set during build)
var (
Version = "dev"
Commit = "none"
BuildDate = "unknown"
)
// Global resources that need cleanup
// Using atomic operations to prevent race conditions between signal handlers and cleanup
var (
debugLogFile atomic.Pointer[os.File]
isStdioMode atomic.Bool
telemetryShutdown func() error
metricsShutdown func() error
)
const (
// DefaultMemoryLimit is the default memory limit for the Go application (5GB)
DefaultMemoryLimit = 5 * 1024 * 1024 * 1024
)
// parseLogLevel parses the LOG_LEVEL environment variable and returns the appropriate logrus level.
// Defaults to WarnLevel if not set or invalid.
func parseLogLevel() logrus.Level {
logLevelStr := os.Getenv("LOG_LEVEL")
if logLevelStr == "" {
return logrus.WarnLevel // Default to warn
}
// Normalise to lowercase for comparison
logLevelStr = strings.ToLower(strings.TrimSpace(logLevelStr))
switch logLevelStr {
case "debug":
return logrus.DebugLevel
case "info":
return logrus.InfoLevel
case "warn", "warning":
return logrus.WarnLevel
case "error":
return logrus.ErrorLevel
case "fatal":
return logrus.FatalLevel
case "panic":
return logrus.PanicLevel
default:
// Invalid value, default to warn
return logrus.WarnLevel
}
}
// setMemoryLimit configures the Go runtime memory limit
func setMemoryLimit() {
// Check for environment variable override
memLimitStr := os.Getenv("MCP_DEVTOOLS_MEMORY_LIMIT")
var memLimit int64 = DefaultMemoryLimit
if memLimitStr != "" {
if parsed, err := strconv.ParseInt(memLimitStr, 10, 64); err == nil && parsed > 0 {
memLimit = parsed
}
}
// Set the GOMEMLIMIT for the Go runtime
// This is a soft limit - Go will try to keep memory usage under this value
// The Go runtime will automatically adjust GC behaviour to stay under this limit
debug.SetMemoryLimit(memLimit)
}
// newToolHandler builds the MCP handler for a registered tool. Tool execution
// failures (missing parameters, invalid input, unsupported options, etc.) are
// returned as tool results with isError set rather than Go errors. A Go error
// returned from an SDK tool handler becomes a JSON-RPC protocol error, which
// clients treat as a server fault; an isError result lets the calling agent
// read the message and self-correct.
func newToolHandler(name, transport string, logger *logrus.Logger) mcp.ToolHandler {
return func(toolCtx context.Context, request *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
// Get fresh reference from registry to ensure consistency
currentTool, ok := registry.GetTool(name)
if !ok {
return mcpapi.NewToolResultError(fmt.Sprintf("tool not found: %s", name)), nil
}
// The SDK hands raw JSON to untyped handlers; decoding it is our job.
args := make(map[string]any)
if len(request.Params.Arguments) > 0 {
if err := json.Unmarshal(request.Params.Arguments, &args); err != nil {
return mcpapi.NewToolResultError(fmt.Sprintf("invalid arguments: expected a JSON object: %s", err)), nil
}
}
// Start timing for metrics
startTime := time.Now()
// Start telemetry span for tool execution
spanCtx, span := telemetry.StartToolSpan(toolCtx, name, args)
// Execute tool with error recovery
result, err := currentTool.Execute(spanCtx, registry.GetLogger(), registry.GetCache(), args)
// Calculate duration for metrics
durationMs := float64(time.Since(startTime).Milliseconds())
// Record metrics
telemetry.RecordToolCall(spanCtx, name, transport, err == nil, durationMs)
if err != nil {
// Categorise and record error metric
errorType := telemetry.CategoriseToolError(err)
telemetry.RecordToolError(spanCtx, name, errorType)
}
// End the telemetry span with success or error
telemetry.EndToolSpan(span, err)
if err != nil {
// Log error to stderr for debugging (won't interfere with stdio)
if transport != "stdio" {
logger.WithError(err).Errorf("Tool execution failed: %s", name)
}
// Log tool error to file if enabled
if errorLogger := tools.GetGlobalErrorLogger(); errorLogger != nil && errorLogger.IsEnabled() {
errorLogger.LogToolError(name, args, err, transport)
}
return mcpapi.NewToolResultError(fmt.Sprintf("tool execution failed: %s", err)), nil
}
return result, nil
}
}
func main() {
// Set memory limit for the Go application
setMemoryLimit()
// Create context with signal handling for graceful shutdown
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Create a logger with default configuration
// Initially discard output - will be reconfigured in Action based on transport mode
logger := logrus.New()
logger.SetOutput(io.Discard) // Prevent any early logging before we know the transport mode
logger.SetLevel(parseLogLevel()) // Use LOG_LEVEL env var (default: WarnLevel)
logger.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
})
// Initialise the registry
registry.Init(logger)
// Ensure cleanup runs on normal exit OR signal
defer performCleanup(logger)
// NOTE: Upstream proxy tool registration is now async -- see RegisterUpstreamToolsAsync()
// called after the MCP server is created. This avoids blocking startup for OAuth flows.
// Create and run the CLI app
app := &cli.Command{
Name: "mcp-devtools",
Usage: "MCP server for developer tools",
Version: fmt.Sprintf("%s (commit: %s, built: %s)", Version, Commit, BuildDate),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "transport",
Aliases: []string{"t"},
Value: "stdio",
Usage: "Transport type (stdio or http)",
},
&cli.StringFlag{
Name: "port",
Value: "18080",
Usage: "Port to use for the Streamable HTTP transport",
},
&cli.StringFlag{
Name: "base-url",
Value: "http://localhost",
Usage: "Base URL for HTTP transports",
},
&cli.StringFlag{
Name: "auth-token",
Usage: "Authentication token for Streamable HTTP transport (optional)",
},
&cli.StringFlag{
Name: "endpoint-path",
Value: "/http",
Usage: "Endpoint path for Streamable HTTP transport",
},
// OAuth 2.0/2.1 flags
&cli.BoolFlag{
Name: "oauth-enabled",
Usage: "Enable OAuth 2.0/2.1 authorisation (HTTP transport only)",
Sources: cli.EnvVars("OAUTH_ENABLED", "MCP_OAUTH_ENABLED"),
},
&cli.StringFlag{
Name: "oauth-issuer",
Usage: "OAuth issuer URL (required if oauth-enabled)",
Sources: cli.EnvVars("OAUTH_ISSUER", "MCP_OAUTH_ISSUER"),
},
&cli.StringFlag{
Name: "oauth-audience",
Usage: "OAuth audience for this resource server",
Sources: cli.EnvVars("OAUTH_AUDIENCE", "MCP_OAUTH_AUDIENCE"),
},
&cli.StringFlag{
Name: "oauth-jwks-url",
Usage: "JWKS URL for token validation",
Sources: cli.EnvVars("OAUTH_JWKS_URL", "MCP_OAUTH_JWKS_URL"),
},
&cli.BoolFlag{
Name: "oauth-dynamic-registration",
Usage: "Enable RFC7591 dynamic client registration",
Sources: cli.EnvVars("OAUTH_DYNAMIC_REGISTRATION", "MCP_OAUTH_DYNAMIC_REGISTRATION"),
},
&cli.StringFlag{
Name: "oauth-authorization-server",
Usage: "Authorisation server URL (if different from issuer)",
Sources: cli.EnvVars("OAUTH_AUTHORIZATION_SERVER", "MCP_OAUTH_AUTHORIZATION_SERVER"),
},
&cli.BoolFlag{
Name: "oauth-require-https",
Value: true,
Usage: "Require HTTPS for OAuth endpoints (disable only for development)",
Sources: cli.EnvVars("OAUTH_REQUIRE_HTTPS", "MCP_OAUTH_REQUIRE_HTTPS"),
},
// OAuth Client Browser Authentication flags
&cli.BoolFlag{
Name: "oauth-browser-auth",
Usage: "Enable browser-based OAuth authentication flow at startup",
Sources: cli.EnvVars("OAUTH_BROWSER_AUTH", "MCP_OAUTH_BROWSER_AUTH"),
},
&cli.StringFlag{
Name: "oauth-client-id",
Usage: "OAuth client ID for browser authentication",
Sources: cli.EnvVars("OAUTH_CLIENT_ID", "MCP_OAUTH_CLIENT_ID"),
},
&cli.StringFlag{
Name: "oauth-client-secret",
Usage: "OAuth client secret for browser authentication (optional for public clients)",
Sources: cli.EnvVars("OAUTH_CLIENT_SECRET", "MCP_OAUTH_CLIENT_SECRET"),
},
&cli.StringFlag{
Name: "oauth-scope",
Usage: "OAuth scopes to request during browser authentication",
Sources: cli.EnvVars("OAUTH_SCOPE", "MCP_OAUTH_SCOPE"),
},
&cli.IntFlag{
Name: "oauth-callback-port",
Value: 0,
Usage: "Port for OAuth callback server (0 for random port)",
Sources: cli.EnvVars("OAUTH_CALLBACK_PORT", "MCP_OAUTH_CALLBACK_PORT"),
},
&cli.DurationFlag{
Name: "oauth-auth-timeout",
Value: 5 * time.Minute,
Usage: "Timeout for browser authentication flow",
Sources: cli.EnvVars("OAUTH_AUTH_TIMEOUT", "MCP_OAUTH_AUTH_TIMEOUT"),
},
},
Commands: []*cli.Command{
{
Name: "version",
Usage: "Print version information",
Action: func(ctx context.Context, cmd *cli.Command) error {
fmt.Printf("mcp-devtools version %s\n", Version)
fmt.Printf("Commit: %s\n", Commit)
fmt.Printf("Built: %s\n", BuildDate)
return nil
},
},
{
Name: "security-config-diff",
Usage: "Show differences between user security config and default config",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "update",
Usage: "Update user config with new default rules (preserves user customizations)",
},
&cli.StringFlag{
Name: "config-path",
Usage: "Path to security configuration file (default: ~/.mcp-devtools/security.yaml)",
},
},
Action: func(ctx context.Context, cmd *cli.Command) error {
return handleSecurityConfigDiff(cmd)
},
},
{
Name: "security-config-validate",
Usage: "Validate security configuration file for errors",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config-path",
Usage: "Path to security configuration file (default: ~/.mcp-devtools/security.yaml)",
},
},
Action: func(ctx context.Context, cmd *cli.Command) error {
return handleSecurityConfigValidate(cmd)
},
},
},
Action: func(cliCtx context.Context, cmd *cli.Command) error {
// Get transport settings
transport := cmd.String("transport")
port := cmd.String("port")
// Track stdio mode for error handling (atomic to prevent races with signal handlers)
isStdioMode.Store(transport == "stdio")
// Configure logger - ALWAYS use file logging to avoid breaking stdio protocol
homeDir, err := os.UserHomeDir()
if err == nil {
logDir := filepath.Join(homeDir, ".mcp-devtools", "logs")
if err := os.MkdirAll(logDir, 0700); err == nil {
logFile := filepath.Join(logDir, "mcp-devtools.log")
if file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600); err == nil {
// Store file handle for cleanup
debugLogFile.Store(file)
// Configure loggers for file output
logger.SetOutput(file)
logrus.SetOutput(file)
// Apply LOG_LEVEL setting (stdio mode uses warn level minimum)
logLevel := parseLogLevel()
if isStdioMode.Load() && logLevel < logrus.WarnLevel {
logLevel = logrus.WarnLevel // Minimum warn level for stdio mode
}
logger.SetLevel(logLevel)
logrus.SetLevel(logLevel)
logger.WithField("level", logLevel.String()).Debug("Logging configured")
} else {
// Critical: Cannot create log file - use io.Discard in stdio mode to prevent protocol breakage
if isStdioMode.Load() {
logger.SetOutput(io.Discard)
logrus.SetOutput(io.Discard)
} else {
// Non-stdio mode can fallback to stderr
logger.SetOutput(os.Stderr)
logrus.SetOutput(os.Stderr)
}
logLevel := parseLogLevel()
logger.SetLevel(logLevel)
logrus.SetLevel(logLevel)
}
} else {
// Critical: Cannot create log directory
if isStdioMode.Load() {
logger.SetOutput(io.Discard)
logrus.SetOutput(io.Discard)
} else {
logger.SetOutput(os.Stderr)
logrus.SetOutput(os.Stderr)
}
logLevel := parseLogLevel()
logger.SetLevel(logLevel)
logrus.SetLevel(logLevel)
}
} else {
// Critical: Cannot get home directory
if isStdioMode.Load() {
logger.SetOutput(io.Discard)
logrus.SetOutput(io.Discard)
} else {
logger.SetOutput(os.Stderr)
logrus.SetOutput(os.Stderr)
}
logLevel := parseLogLevel()
logger.SetLevel(logLevel)
logrus.SetLevel(logLevel)
}
// Initialise tool error logger after logging is configured
if err := tools.InitGlobalErrorLogger(logger); err != nil {
logger.WithError(err).Debug("Failed to initialise tool error logger")
if transport != "stdio" {
logger.WithError(err).Warn("Failed to initialise tool error logger")
}
}
// Initialise telemetry system (if enabled) - after logging is configured
logger.Debug("Initialising telemetry system")
shutdown, err := telemetry.InitTracer(logger)
if err != nil {
logger.WithError(err).Debug("Telemetry initialisation failed, continuing with noop tracer")
if transport != "stdio" {
logger.WithError(err).Warn("Telemetry initialisation failed, tracing disabled")
}
}
telemetryShutdown = shutdown
// Initialise metrics system (if enabled) - after tracing is configured
logger.Debug("Initialising metrics system")
metricsShutdown, err = telemetry.InitMetrics(logger)
if err != nil {
logger.WithError(err).Debug("Metrics initialisation failed, continuing with noop meter")
if transport != "stdio" {
logger.WithError(err).Warn("Metrics initialisation failed, metrics disabled")
}
}
// Initialise security system (if enabled) - after logging is configured
logger.Debug("Initialising security system")
if err := security.InitGlobalSecurityManager(); err != nil {
logger.WithError(err).Debug("Security initialisation failed")
if transport != "stdio" {
logger.WithError(err).Warn("Failed to initialise security system")
}
} else {
logger.Debug("Security system initialised successfully")
}
// Only log startup info for non-stdio transports
if transport != "stdio" {
logger.Infof("Starting mcp-devtools version %s (commit: %s, built: %s)",
Version, Commit, BuildDate)
}
// Create MCP server. Capabilities are set explicitly because a nil
// value makes the SDK advertise the deprecated logging capability.
logger.Debug("Creating MCP server")
mcpSrv := mcp.NewServer(
&mcp.Implementation{
Name: "mcp-devtools",
Title: "MCP DevTools Server",
Version: Version,
WebsiteURL: "https://github.com/sammcj/mcp-devtools",
Description: "Developer tools for AI coding agents",
},
&mcp.ServerOptions{Capabilities: &mcp.ServerCapabilities{}},
)
enabledTools := registry.GetEnabledTools()
logger.WithField("tool_count", len(enabledTools)).Debug("MCP server created, registering tools")
// Register tools in name order so tools/list is byte-identical across
// restarts, which prompt caches on the client side depend on.
for _, name := range slices.Sorted(maps.Keys(enabledTools)) {
tool := enabledTools[name]
// Tools holding per-client state in this process cannot serve a
// stateless transport, where consecutive calls may land on
// different instances.
if _, stdioOnly := tool.(tools.StdioOnly); stdioOnly && transport != "stdio" {
logger.Infof("Skipping tool %s: it is stdio-only", name)
continue
}
if transport != "stdio" {
logger.Infof("Registering tool: %s", name)
}
definition := tool.Definition()
mcpSrv.AddTool(&definition, newToolHandler(name, transport, logger))
}
// Register upstream proxy tools asynchronously (avoids blocking startup for OAuth)
proxy.RegisterUpstreamToolsAsync(cliCtx, mcpSrv, logger, func(name string) mcp.ToolHandler {
return newToolHandler(name, transport, logger)
})
// Handle browser-based OAuth authentication if enabled
if cmd.Bool("oauth-browser-auth") {
if err := handleBrowserAuthentication(cmd, transport, logger); err != nil {
return fmt.Errorf("browser authentication failed: %w", err)
}
}
// Start the server
logger.WithField("transport", transport).Debug("Starting server")
switch transport {
case "stdio":
logger.Debug("Starting stdio server")
// Track session start time for metrics
sessionStartTime := time.Now()
// Create a session span and track metrics (if tracing or metrics enabled)
if telemetry.IsEnabled() || telemetry.IsMetricsEnabled() {
sessionID := telemetry.GenerateSessionID()
ctx := telemetry.ContextWithSessionID(context.Background(), sessionID)
// Create session span (only if tracing enabled)
_, sessionSpan := telemetry.StartSessionSpan(ctx, sessionID, "stdio")
// Record session start metric (only if metrics enabled)
telemetry.RecordSessionStart(ctx, "stdio")
defer func() {
// Calculate session duration
sessionDuration := time.Since(sessionStartTime).Seconds()
// Record session end metric (only if metrics enabled)
telemetry.RecordSessionEnd(ctx, "stdio", sessionDuration, 0)
// Clear session span context when stdio server exits
telemetry.EndSessionSpan(sessionSpan, 0, 0, 0)
}()
logger.WithField("session_id", sessionID).Debug("Created session span/metrics for stdio transport")
}
return mcpSrv.Run(cliCtx, &mcp.StdioTransport{})
case "http":
logger.WithField("port", port).Debug("Starting HTTP server")
return startStreamableHTTPServer(cliCtx, cmd, mcpSrv, logger)
case "sse":
return fmt.Errorf("the sse transport was removed in v2; use --transport http, which now serves stateless Streamable HTTP")
default:
return fmt.Errorf("unsupported transport: %s (expected stdio or http)", transport)
}
},
}
if err := app.Run(ctx, os.Args); err != nil {
// CRITICAL: In stdio mode, we must NOT log to stdout or stderr as it breaks the MCP protocol
// Even though this occurs after ServeStdio() returns, initialisation errors could occur
// before the protocol starts, so we avoid all logging in stdio mode
if !isStdioMode.Load() {
logger.Fatalf("Error: %v", err)
}
os.Exit(1)
}
}
// performCleanup handles cleanup of resources on shutdown
func performCleanup(logger *logrus.Logger) {
// Shutdown metrics first to flush any pending metrics
if metricsShutdown != nil {
if err := metricsShutdown(); err != nil {
logger.WithError(err).Warn("Metrics shutdown failed")
}
}
// Shutdown telemetry to flush any pending traces
if telemetryShutdown != nil {
if err := telemetryShutdown(); err != nil {
logger.WithError(err).Warn("Telemetry shutdown failed")
}
}
// Close the debug log file if it was opened (atomic load to prevent races)
if file := debugLogFile.Load(); file != nil {
// Silently close - we're in cleanup and can't safely log errors
// (stdio mode: no output allowed; non-stdio: logger might write to this file)
_ = file.Close()
}
// Close the tool error logger if it was initialised
if errorLogger := tools.GetGlobalErrorLogger(); errorLogger != nil {
// Use Warn level - in stdio mode this won't output (ErrorLevel only)
if err := errorLogger.Close(); err != nil {
logger.WithError(err).Warn("Failed to close tool error logger")
}
}
// Stop LSP client cleanup routine and close all cached LSP clients
// Uses Debug level logging internally - won't output in stdio mode
coderename.StopCleanupRoutine(registry.GetCache(), logger)
}
// maxRequestBodyBytes caps a single MCP request body. Tool arguments are small;
// anything larger is a mistake or an attempt to exhaust memory.
const maxRequestBodyBytes = 8 << 20 // 8MB
// startStreamableHTTPServer configures and starts the stateless Streamable HTTP
// server with graceful shutdown.
//
// The server is stateless (MCP 2026-07-28): every request carries its own
// context, no session is created or tracked, and GET and DELETE on the MCP
// endpoint return 405.
func startStreamableHTTPServer(ctx context.Context, cmd *cli.Command, mcpServer *mcp.Server, logger *logrus.Logger) error {
port := cmd.String("port")
authToken := cmd.String("auth-token")
endpointPath := cmd.String("endpoint-path")
baseURL := cmd.String("base-url")
logger.Infof("Starting stateless Streamable HTTP server on port %s with endpoint %s", port, endpointPath)
var handler http.Handler = mcp.NewStreamableHTTPHandler(
func(*http.Request) *mcp.Server { return mcpServer },
&mcp.StreamableHTTPOptions{
Stateless: true,
// A dropped connection cancels the tool's context rather than
// leaving it running. Only honoured on protocol 2026-07-28+.
PropagateRequestCancellation: true,
MaxRequestBodyBytes: maxRequestBodyBytes,
Logger: slog.New(logrusSlogHandler{logger: logger}),
},
)
// Trace context has to be extracted per request now that there is no
// session-scoped context func.
handler = withWriteDeadline(withTraceContext(handler))
mux := http.NewServeMux()
if cmd.Bool("oauth-enabled") {
oauthConfig := &types.OAuth2Config{
Enabled: true,
Issuer: cmd.String("oauth-issuer"),
Audience: cmd.String("oauth-audience"),
JWKSUrl: cmd.String("oauth-jwks-url"),
DynamicRegistration: cmd.Bool("oauth-dynamic-registration"),
AuthorizationServer: cmd.String("oauth-authorization-server"),
RequireHTTPS: cmd.Bool("oauth-require-https"),
}
if err := validateOAuthConfig(oauthConfig); err != nil {
return fmt.Errorf("invalid OAuth configuration: %w", err)
}
fullBaseURL := fmt.Sprintf("%s:%s", baseURL, port)
oauthServer, err := oauthserver.NewOAuth2Server(oauthConfig, fullBaseURL, logger)
if err != nil {
return fmt.Errorf("failed to create OAuth server: %w", err)
}
// AuthMiddleware rejects unauthenticated requests with 401 rather than
// only annotating the context, which is what the old HTTPContextFunc did.
handler = oauthServer.CreateMiddleware()(handler)
oauthServer.RegisterHandlers(mux)
logger.Info("OAuth 2.1 authentication enabled")
logger.Infof("OAuth issuer: %s", oauthConfig.Issuer)
logger.Infof("OAuth audience: %s", oauthConfig.Audience)
logger.Infof("Dynamic client registration: %t", oauthConfig.DynamicRegistration)
logger.Infof("OAuth endpoints available at %s/.well-known/", fullBaseURL)
} else if authToken != "" {
handler = requireBearerToken(authToken, logger)(handler)
logger.Info("Legacy token authentication enabled")
}
mux.Handle(endpointPath, handler)
// Reject cross-origin browser requests. The SDK already blocks the
// DNS-rebinding case; this covers the wider CSRF surface.
server := &http.Server{
Addr: ":" + port,
Handler: http.NewCrossOriginProtection().Handler(mux),
ReadHeaderTimeout: 10 * time.Second, // Prevent slow loris attacks
ReadTimeout: 30 * time.Second, // Prevent slow reads
IdleTimeout: 120 * time.Second, // Close idle connections
MaxHeaderBytes: 1 << 20, // 1MB max header size
// No server-wide WriteTimeout: it starts when the request headers are
// read, so any value also caps how long a tool may run, and document
// processing and the agent tools routinely take minutes. withWriteDeadline
// bounds a stalled reader per request instead.
}
serverErr := make(chan error, 1)
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
select {
case serverErr <- err:
case <-ctx.Done():
}
}
}()
select {
case err := <-serverErr:
return fmt.Errorf("HTTP server failed: %w", err)
case <-ctx.Done():
logger.Info("Shutdown signal received, stopping HTTP server")
}
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 30*time.Second)
defer shutdownCancel()
if err := server.Shutdown(shutdownCtx); err != nil {
logger.WithError(err).Error("HTTP server shutdown failed")
return err
}
logger.Info("HTTP server stopped gracefully")
return nil
}
// extractTraceContext extracts W3C Trace Context from HTTP request headers
// This enables distributed tracing across HTTP boundaries
func extractTraceContext(ctx context.Context, req *http.Request) context.Context {
if !telemetry.IsEnabled() {
return ctx
}
// Extract trace context from HTTP headers using the global propagator
// This was configured in telemetry.InitTracer() with W3C TraceContext and Baggage
propagator := telemetry.GetTextMapPropagator()
return propagator.Extract(ctx, propagation.HeaderCarrier(req.Header))
}
// withTraceContext puts any inbound W3C trace context on the request context so
// tool spans join the caller's trace.
func withTraceContext(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r.WithContext(extractTraceContext(r.Context(), r)))
})
}
// maxResponseWriteWait bounds how long a single response may stall on a client
// that has stopped reading. It has to clear the slowest tool, so it is far
// longer than a normal call takes.
const maxResponseWriteWait = 60 * time.Minute
// withWriteDeadline replaces the server-wide WriteTimeout, which would have
// capped tool runtime. A client that opens a request and then reads at zero
// rate would otherwise pin a connection and a goroutine indefinitely.
func withWriteDeadline(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Not supported by every ResponseWriter, and not fatal when it is not.
_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(maxResponseWriteWait))
next.ServeHTTP(w, r)
})
}
// requireBearerToken rejects requests that do not present the shared token.
// The previous implementation only logged, letting unauthenticated requests
// through.
func requireBearerToken(expectedToken string, logger *logrus.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || subtle.ConstantTimeCompare([]byte(token), []byte(expectedToken)) != 1 {
logger.Warn("Rejected request with missing or invalid bearer token")
w.Header().Set("WWW-Authenticate", `Bearer realm="mcp-devtools"`)
http.Error(w, "unauthorised", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}
// logrusSlogHandler routes the SDK's slog output through logrus so HTTP server
// logs land in the same file as everything else.
type logrusSlogHandler struct {
logger *logrus.Logger
attrs []slog.Attr
}
func (h logrusSlogHandler) Enabled(_ context.Context, level slog.Level) bool {
return h.logger.IsLevelEnabled(slogToLogrusLevel(level))
}
func (h logrusSlogHandler) Handle(_ context.Context, record slog.Record) error {
fields := make(logrus.Fields, len(h.attrs)+record.NumAttrs())
for _, attr := range h.attrs {
fields[attr.Key] = attr.Value.Any()
}
record.Attrs(func(attr slog.Attr) bool {
fields[attr.Key] = attr.Value.Any()
return true
})
h.logger.WithFields(fields).Log(slogToLogrusLevel(record.Level), record.Message)
return nil
}
func (h logrusSlogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return logrusSlogHandler{logger: h.logger, attrs: append(slices.Clip(h.attrs), attrs...)}
}
// WithGroup is a no-op: logrus fields are flat, so grouping would only mangle
// key names.
func (h logrusSlogHandler) WithGroup(string) slog.Handler { return h }
func slogToLogrusLevel(level slog.Level) logrus.Level {
switch {
case level >= slog.LevelError:
return logrus.ErrorLevel
case level >= slog.LevelWarn:
return logrus.WarnLevel
case level >= slog.LevelInfo:
return logrus.InfoLevel
default:
return logrus.DebugLevel
}
}
// validateOAuthConfig validates OAuth configuration
func validateOAuthConfig(config *types.OAuth2Config) error {
if !config.Enabled {
return fmt.Errorf("OAuth is not enabled")
}
if config.Issuer == "" {
return fmt.Errorf("oauth-issuer is required when OAuth is enabled")
}
if config.Audience == "" {
return fmt.Errorf("oauth-audience is required when OAuth is enabled")
}
if config.JWKSUrl == "" {
return fmt.Errorf("oauth-jwks-url is required when OAuth is enabled")
}
return nil
}
// handleBrowserAuthentication handles the browser-based OAuth authentication flow
func handleBrowserAuthentication(cmd *cli.Command, transport string, logger *logrus.Logger) error {
// Browser authentication is not compatible with stdio mode
if transport == "stdio" {
logger.Debug("Browser authentication disabled for stdio transport")
return nil
}
// Validate required configuration
clientID := cmd.String("oauth-client-id")
if clientID == "" {
return fmt.Errorf("oauth-client-id is required for browser authentication")
}
issuerURL := cmd.String("oauth-issuer")
if issuerURL == "" {
return fmt.Errorf("oauth-issuer is required for browser authentication")
}
// Build OAuth client configuration
clientConfig := &oauthclient.OAuth2ClientConfig{
ClientID: clientID,
ClientSecret: cmd.String("oauth-client-secret"),
IssuerURL: issuerURL,
Scope: cmd.String("oauth-scope"),
ServerPort: cmd.Int("oauth-callback-port"),
AuthTimeout: cmd.Duration("oauth-auth-timeout"),
RequireHTTPS: cmd.Bool("oauth-require-https"),
}
// Set resource parameter for audience binding (RFC8707)
audience := cmd.String("oauth-audience")
if audience != "" {
clientConfig.Resource = audience
}
// Create and validate browser authentication flow
browserAuth, err := oauthclient.NewBrowserAuthFlow(clientConfig, logger)
if err != nil {
return fmt.Errorf("failed to create browser authentication flow: %w", err)
}
if err := browserAuth.ValidateConfig(); err != nil {
return fmt.Errorf("invalid browser authentication configuration: %w", err)
}
// Log authentication details
logger.Info("Browser-based OAuth authentication enabled")
logger.Infof("OAuth client ID: %s", clientConfig.ClientID)
logger.Infof("OAuth issuer: %s", clientConfig.IssuerURL)
if clientConfig.Scope != "" {
logger.Infof("OAuth scope: %s", clientConfig.Scope)
}
if clientConfig.Resource != "" {
logger.Infof("OAuth resource: %s", clientConfig.Resource)
}
// Perform the authentication
logger.Info("Starting browser authentication flow...")
logger.Info("Please complete the authentication in your browser")
tokenResponse, err := browserAuth.AuthenticateWithTimeout(clientConfig.AuthTimeout)
if err != nil {
return fmt.Errorf("authentication failed: %w", err)
}
if tokenResponse == nil {
// This shouldn't happen, but let's be defensive
return fmt.Errorf("authentication completed but no token received")
}
// Log successful authentication (without sensitive token data)
logger.Info("Browser authentication completed successfully")
logger.Infof("Token type: %s", tokenResponse.TokenType)
if tokenResponse.ExpiresIn > 0 {
logger.Infof("Token expires in: %d seconds", tokenResponse.ExpiresIn)
}
if tokenResponse.Scope != "" {
logger.Infof("Granted scope: %s", tokenResponse.Scope)
}
// Store the access token for use by the MCP server
// For now, we'll store it in an environment variable that the OAuth middleware can use
// In a production implementation, you might want to use a more secure storage mechanism
if err := os.Setenv("MCP_ACCESS_TOKEN", tokenResponse.AccessToken); err != nil {
logger.WithError(err).Warn("Failed to store access token in environment")
}
logger.Info("MCP DevTools is now authenticated and ready to start")
return nil
}
// handleSecurityConfigDiff compares user config against default config and optionally updates it
func handleSecurityConfigDiff(cmd *cli.Command) error {
// Get config path
configPath := cmd.String("config-path")
if configPath == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
configPath = fmt.Sprintf("%s/.mcp-devtools/security.yaml", homeDir)
}
// Check if user config exists
if _, err := os.Stat(configPath); os.IsNotExist(err) {
fmt.Printf("User config file does not exist at: %s\n", configPath)
fmt.Println("A default configuration will be created when the security system is first used.")
return nil
}
// Generate default config
defaultConfig := security.GenerateDefaultConfig()
// Read user config
userConfigData, err := os.ReadFile(configPath)
if err != nil {
return fmt.Errorf("failed to read user config: %w", err)
}
// Compare configs
userConfigStr := string(userConfigData)
if userConfigStr == defaultConfig {
fmt.Println("✅ User configuration matches the current default configuration")
return nil
}
fmt.Println("📋 Configuration Differences Found")
fmt.Println("==================================")
fmt.Printf("User config: %s\n", configPath)
fmt.Println("Default config: (generated)")
fmt.Println()
// Show basic comparison
fmt.Println("User config size:", len(userConfigStr), "bytes")
fmt.Println("Default config size:", len(defaultConfig), "bytes")
fmt.Println()
// Parse both configs to show structural differences
var userRules security.SecurityRules
var defaultRules security.SecurityRules
if err := yaml.Unmarshal(userConfigData, &userRules); err != nil {
fmt.Printf("⚠️ Warning: User config has parsing errors: %v\n", err)
fmt.Println("Run 'security-config-validate' command for detailed error information")
} else {
if err := yaml.Unmarshal([]byte(defaultConfig), &defaultRules); err != nil {
return fmt.Errorf("failed to parse default config: %w", err)
}
// Compare versions
if userRules.Version != defaultRules.Version {
fmt.Printf("📄 Version difference: user=%s, default=%s\n", userRules.Version, defaultRules.Version)
}
// Compare rule counts
fmt.Printf("📊 Rules: user=%d, default=%d\n", len(userRules.Rules), len(defaultRules.Rules))
// Show new rules available in default