Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
102 lines (83 loc) · 2.27 KB
/
Copy pathmain.go
File metadata and controls
102 lines (83 loc) · 2.27 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
package main
import (
"context"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/mark3labs/mcp-go/server"
)
// version is set at build time via -ldflags.
var version = "dev"
func main() {
// Set up structured logging.
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
slog.SetDefault(logger)
// Configuration from environment variables.
apiURL := os.Getenv("SANDBOXAPI_URL")
if apiURL == "" {
apiURL = "https://api.sandboxapi.dev"
}
apiKey := os.Getenv("SANDBOXAPI_API_KEY")
if apiKey == "" {
slog.Error("SANDBOXAPI_API_KEY is required")
os.Exit(1)
}
mcpAPIKey := os.Getenv("MCP_API_KEY")
if mcpAPIKey == "" {
slog.Warn("MCP_API_KEY not set — MCP endpoint has no authentication")
}
port := os.Getenv("MCP_PORT")
if port == "" {
port = "8081"
}
// Create HTTP client for SandboxAPI.
client := NewSandboxClient(apiURL, apiKey)
// Create MCP server with tools.
mcpSrv := NewMCPServer(version, client)
// Create Streamable HTTP transport.
httpServer := server.NewStreamableHTTPServer(mcpSrv,
server.WithStateLess(true),
server.WithHTTPContextFunc(APIKeyAuthFunc(mcpAPIKey)),
)
// Wrap with auth middleware for proper 401 responses.
mux := http.NewServeMux()
mux.Handle("/mcp", AuthMiddleware(mcpAPIKey, httpServer))
srv := &http.Server{
Addr: fmt.Sprintf(":%s", port),
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 5*time.Minute + 5*time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 13,
}
// Start server in goroutine.
go func() {
slog.Info("starting SandboxAPI MCP server",
"port", port,
"version", version,
"api_url", apiURL,
"auth", mcpAPIKey != "",
)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("MCP server failed", "error", err)
os.Exit(1)
}
}()
// Graceful shutdown.
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
slog.Info("shutting down MCP server...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
slog.Error("MCP server forced shutdown", "error", err)
}
slog.Info("MCP server stopped")
}