-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathhttp.go
More file actions
213 lines (193 loc) · 5.72 KB
/
Copy pathhttp.go
File metadata and controls
213 lines (193 loc) · 5.72 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
package main
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"path"
"strings"
"syscall"
"time"
"github.com/mark3labs/mcp-go/mcp"
"golang.org/x/sync/errgroup"
)
type MiddlewareFunc func(http.Handler) http.Handler
func chainMiddleware(h http.Handler, middlewares ...MiddlewareFunc) http.Handler {
for _, mw := range middlewares {
h = mw(h)
}
return h
}
func newAuthMiddleware(tokens []string) MiddlewareFunc {
tokenSet := make(map[string]struct{}, len(tokens))
for _, token := range tokens {
tokenSet[token] = struct{}{}
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(tokens) != 0 {
token := r.Header.Get("Authorization")
token = strings.TrimSpace(strings.TrimPrefix(token, "Bearer "))
if token == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if _, ok := tokenSet[token]; !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
next.ServeHTTP(w, r)
})
}
}
func loggerMiddleware(prefix string) MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("<%s> Request [%s] %s", prefix, r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
}
func recoverMiddleware(prefix string) MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("<%s> Recovered from panic: %v", prefix, err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
}
// healthHandler returns an unauthenticated handler for liveness/readiness
// probes. It responds to GET with a small JSON status document and to HEAD with
// an empty 200 body, so it can be used by Docker, reverse proxies, and
// monitoring without speaking MCP or providing the proxy auth token.
func healthHandler(config *Config) http.HandlerFunc {
type healthResponse struct {
Name string `json:"name"`
ServerCount int `json:"serverCount"`
Status string `json:"status"`
Version string `json:"version"`
}
body := healthResponse{
Name: config.McpProxy.Name,
ServerCount: len(config.McpServers),
Status: "ok",
Version: config.McpProxy.Version,
}
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(body)
case http.MethodHead:
w.WriteHeader(http.StatusOK)
default:
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
}
}
}
func startHTTPServer(config *Config) error {
baseURL, uErr := url.Parse(config.McpProxy.BaseURL)
if uErr != nil {
return uErr
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var errorGroup errgroup.Group
httpMux := http.NewServeMux()
httpServer := &http.Server{
Addr: config.McpProxy.Addr,
Handler: httpMux,
}
info := mcp.Implementation{
Name: config.McpProxy.Name,
}
// Unauthenticated health endpoints for liveness/readiness probes.
health := healthHandler(config)
httpMux.HandleFunc("/_healthz", health)
httpMux.HandleFunc("/_readyz", health)
for name, clientConfig := range config.McpServers {
if clientConfig.Options.Disabled {
log.Printf("<%s> Disabled", name)
continue
}
mcpClient, err := newMCPClient(name, clientConfig)
if err != nil {
return err
}
server, err := newMCPServer(name, config.McpProxy, clientConfig)
if err != nil {
return err
}
errorGroup.Go(func() error {
log.Printf("<%s> Connecting", name)
addErr := mcpClient.addToMCPServer(ctx, info, server.mcpServer)
if addErr != nil {
log.Printf("<%s> Failed to add client to server: %v", name, addErr)
if clientConfig.Options.PanicIfInvalid.OrElse(false) {
return addErr
}
return nil
}
log.Printf("<%s> Connected", name)
middlewares := make([]MiddlewareFunc, 0)
middlewares = append(middlewares, recoverMiddleware(name))
if clientConfig.Options.LogEnabled.OrElse(false) {
middlewares = append(middlewares, loggerMiddleware(name))
}
if len(clientConfig.Options.AuthTokens) > 0 {
middlewares = append(middlewares, newAuthMiddleware(clientConfig.Options.AuthTokens))
}
mcpRoute := path.Join(baseURL.Path, name)
if !strings.HasPrefix(mcpRoute, "/") {
mcpRoute = "/" + mcpRoute
}
if !strings.HasSuffix(mcpRoute, "/") {
mcpRoute += "/"
}
log.Printf("<%s> Handling requests at %s", name, mcpRoute)
httpMux.Handle(mcpRoute, chainMiddleware(server.handler, middlewares...))
httpServer.RegisterOnShutdown(func() {
log.Printf("<%s> Shutting down", name)
_ = mcpClient.Close()
})
return nil
})
}
go func() {
err := errorGroup.Wait()
if err != nil {
log.Fatalf("Failed to add clients: %v", err)
}
log.Printf("All clients initialized")
}()
go func() {
log.Printf("Starting %s server", config.McpProxy.Type)
log.Printf("%s server listening on %s", config.McpProxy.Type, config.McpProxy.Addr)
hErr := httpServer.ListenAndServe()
if hErr != nil && !errors.Is(hErr, http.ErrServerClosed) {
log.Fatalf("Failed to start server: %v", hErr)
}
}()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
log.Println("Shutdown signal received")
shutdownCtx, shutdownCancel := context.WithTimeout(ctx, 5*time.Second)
defer shutdownCancel()
err := httpServer.Shutdown(shutdownCtx)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}