-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathmain.go
More file actions
308 lines (266 loc) · 10.6 KB
/
Copy pathmain.go
File metadata and controls
308 lines (266 loc) · 10.6 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
package main
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"gtm-mcp-server/auth"
"gtm-mcp-server/config"
"gtm-mcp-server/gtm"
"gtm-mcp-server/middleware"
"github.com/modelcontextprotocol/go-sdk/mcp"
"golang.org/x/oauth2"
)
//go:embed llms.txt
var llmsTxt string
const (
serverName = "gtm-mcp-server"
serverVersion = "1.8.2"
)
func main() {
// Set up structured logging to stderr (stdout is reserved for MCP in stdio mode)
logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
slog.SetDefault(logger)
// Load configuration
cfg, err := config.Load()
if err != nil {
logger.Error("failed to load configuration", "error", err)
os.Exit(1)
}
// Adjust log level
if cfg.LogLevel == "debug" {
logger = slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
slog.SetDefault(logger)
}
// Create MCP server
server := mcp.NewServer(&mcp.Implementation{
Name: serverName,
Version: serverVersion,
}, nil)
// Add logging middleware
server.AddReceivingMiddleware(middleware.NewLoggingMiddleware(logger))
// Register tools
registerTools(server)
// Create HTTP handler for MCP
mcpHandler := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
return server
}, nil)
// Set up HTTP routes
mux := http.NewServeMux()
// Health check endpoint (no auth required)
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{
"status": "healthy",
"service": serverName,
"version": serverVersion,
})
})
// LLM context endpoint (no auth required)
mux.HandleFunc("GET /llms.txt", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(llmsTxt))
})
// URL resolver for dynamic base URL resolution in Docker-to-Docker contexts.
// Only resolves dynamically for hosts in the allowlist; falls back to cfg.BaseURL.
var urlResolver *auth.URLResolver
if len(cfg.AllowedHosts) > 0 {
urlResolver = auth.NewURLResolver(cfg.BaseURL, cfg.AllowedHosts)
logger.Info("dynamic URL resolution enabled", "allowed_hosts", cfg.AllowedHosts)
}
// OAuth metadata endpoints (always served, no auth required)
// RFC 9728: Protected Resource Metadata - tells clients where to find the authorization server
mux.HandleFunc("GET /.well-known/oauth-protected-resource",
auth.ProtectedResourceMetadataHandler(cfg.BaseURL, cfg.BaseURL, urlResolver))
// RFC 8414: Authorization Server Metadata - tells clients about OAuth endpoints
mux.HandleFunc("GET /.well-known/oauth-authorization-server", auth.MetadataHandler(cfg.BaseURL, urlResolver))
// Service account S2S mode (runs alongside OAuth when both are configured)
var saTokenSource oauth2.TokenSource
if cfg.ServiceAccountAPIKey != "" {
var saErr error
saTokenSource, saErr = auth.NewServiceAccountTokenSource(context.Background(), cfg.ServiceAccountKeyJSON)
if saErr != nil {
logger.Error("s2s_mode_failed",
"error", saErr,
"hint", "set GOOGLE_SERVICE_ACCOUNT_KEY_JSON or deploy on GCP for Workload Identity",
)
os.Exit(1)
}
credSource := "workload_identity"
if cfg.ServiceAccountKeyJSON != "" {
credSource = "key_json"
}
logger.Info("s2s_mode_enabled", "credential_source", credSource)
}
// Check if OAuth is configured
var authServer *auth.Server
var tokenStore auth.TokenStore
oauthConfigured := cfg.ValidateAuth() == nil
// Rate limiters for public endpoints
oauthLimiter := middleware.NewRateLimiter(10, 20, cfg.TrustProxy) // 10 req/s, burst 20
registerLimiter := middleware.NewRateLimiter(2, 5, cfg.TrustProxy) // 2 req/s, burst 5
if oauthConfigured {
// Set up OAuth
tokenStore = auth.NewMemoryTokenStore()
googleProvider := auth.NewGoogleProvider(
cfg.GoogleClientID,
cfg.GoogleClientSecret,
cfg.BaseURL+"/oauth/callback",
)
authServer = auth.NewServer(cfg.BaseURL, googleProvider, tokenStore, logger, cfg.AccessTokenTTL)
if urlResolver != nil {
authServer.SetURLResolver(urlResolver)
}
// OAuth endpoints with rate limiting and body size limits
mux.HandleFunc("GET /authorize", oauthLimiter.MiddlewareFunc(authServer.AuthorizeHandler))
mux.HandleFunc("GET /oauth/callback", oauthLimiter.MiddlewareFunc(authServer.CallbackHandler))
mux.HandleFunc("POST /token", oauthLimiter.MiddlewareFunc(middleware.MaxBytesMiddleware(1<<20, authServer.TokenHandler)))
mux.HandleFunc("POST /register", registerLimiter.MiddlewareFunc(middleware.MaxBytesMiddleware(1<<20, authServer.RegistrationHandler)))
// MCP endpoint with REQUIRED auth middleware and body size limit
// Returns 401 if no valid Bearer token - triggers Claude's OAuth flow
authMiddleware := auth.Middleware(tokenStore, googleProvider, logger, cfg.BaseURL, cfg.AccessTokenTTL, urlResolver, saTokenSource, cfg.ServiceAccountAPIKey)
mux.Handle("/", authMiddleware(maxBytesHandler(5<<20, mcpHandler)))
logger.Info("OAuth configured",
"authorize_endpoint", cfg.BaseURL+"/authorize",
"token_endpoint", cfg.BaseURL+"/token",
"callback_endpoint", cfg.BaseURL+"/oauth/callback",
"register_endpoint", cfg.BaseURL+"/register",
"protected_resource_metadata", cfg.BaseURL+"/.well-known/oauth-protected-resource",
"authorization_server_metadata", cfg.BaseURL+"/.well-known/oauth-authorization-server",
)
} else if saTokenSource != nil {
// S2S-only mode: no OAuth, but SA key is configured.
// Require API-key auth — don't serve MCP unauthenticated.
logger.Info("S2S-only mode (no OAuth), API key required for all MCP requests")
oauthNotConfiguredHandler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusServiceUnavailable)
json.NewEncoder(w).Encode(map[string]string{
"error": "server_error",
"error_description": "OAuth is not configured on this server. Use API key authentication.",
})
}
mux.HandleFunc("GET /authorize", oauthLimiter.MiddlewareFunc(oauthNotConfiguredHandler))
mux.HandleFunc("GET /oauth/callback", oauthLimiter.MiddlewareFunc(oauthNotConfiguredHandler))
mux.HandleFunc("POST /token", oauthLimiter.MiddlewareFunc(oauthNotConfiguredHandler))
mux.HandleFunc("POST /register", registerLimiter.MiddlewareFunc(oauthNotConfiguredHandler))
s2sMiddleware := auth.Middleware(auth.NewMemoryTokenStore(), nil, logger, cfg.BaseURL, cfg.AccessTokenTTL, urlResolver, saTokenSource, cfg.ServiceAccountAPIKey)
mux.Handle("/", s2sMiddleware(maxBytesHandler(5<<20, mcpHandler)))
} else {
logger.Warn("No authentication configured (no OAuth, no API key), running open")
oauthNotConfiguredHandler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusServiceUnavailable)
json.NewEncoder(w).Encode(map[string]string{
"error": "server_error",
"error_description": "OAuth is not configured on this server.",
})
}
mux.HandleFunc("GET /authorize", oauthLimiter.MiddlewareFunc(oauthNotConfiguredHandler))
mux.HandleFunc("GET /oauth/callback", oauthLimiter.MiddlewareFunc(oauthNotConfiguredHandler))
mux.HandleFunc("POST /token", oauthLimiter.MiddlewareFunc(oauthNotConfiguredHandler))
mux.HandleFunc("POST /register", registerLimiter.MiddlewareFunc(oauthNotConfiguredHandler))
// Truly open — no auth at all (local dev only)
mux.Handle("/", maxBytesHandler(5<<20, mcpHandler))
}
// Create HTTP server
addr := fmt.Sprintf(":%d", cfg.Port)
httpServer := &http.Server{
Addr: addr,
Handler: mux,
ReadTimeout: 30 * time.Second,
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 0, // Disabled for SSE streams
IdleTimeout: 120 * time.Second,
}
// Graceful shutdown
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// Start server
go func() {
logger.Info("starting GTM MCP server",
"port", cfg.Port,
"base_url", cfg.BaseURL,
)
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error("server error", "error", err)
os.Exit(1)
}
}()
// Wait for shutdown signal
<-ctx.Done()
logger.Info("shutting down server")
// Give outstanding requests 10 seconds to complete
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
logger.Error("shutdown error", "error", err)
}
logger.Info("server stopped")
}
// registerTools adds MCP tools to the server.
func registerTools(server *mcp.Server) {
registerUtilityTools(server)
gtm.RegisterTools(server)
}
// maxBytesHandler wraps an http.Handler with a request body size limit.
func maxBytesHandler(maxBytes int64, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Body != nil {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
}
next.ServeHTTP(w, r)
})
}
// registerUtilityTools adds ping and auth_status tools.
func registerUtilityTools(server *mcp.Server) {
// Ping tool for testing connectivity
type PingInput struct {
Message string `json:"message,omitempty" jsonschema:"Optional message to echo back"`
}
type PingOutput struct {
Reply string `json:"reply"`
Timestamp string `json:"timestamp"`
}
mcp.AddTool(server, &mcp.Tool{
Name: "ping",
Description: "Test connectivity to the GTM MCP server",
}, func(ctx context.Context, req *mcp.CallToolRequest, input PingInput) (*mcp.CallToolResult, PingOutput, error) {
reply := "pong"
if input.Message != "" {
reply = fmt.Sprintf("pong: %s", input.Message)
}
return nil, PingOutput{Reply: reply, Timestamp: time.Now().UTC().Format(time.RFC3339)}, nil
})
// Auth status tool
type AuthStatusInput struct{}
type AuthStatusOutput struct {
Authenticated bool `json:"authenticated"`
Message string `json:"message"`
}
mcp.AddTool(server, &mcp.Tool{
Name: "auth_status",
Description: "Check authentication status with Google Tag Manager",
}, func(ctx context.Context, req *mcp.CallToolRequest, input AuthStatusInput) (*mcp.CallToolResult, AuthStatusOutput, error) {
tokenInfo := auth.GetTokenInfo(ctx)
output := AuthStatusOutput{Authenticated: tokenInfo != nil}
if tokenInfo != nil {
output.Message = "You are authenticated and can access GTM data"
} else {
output.Message = "Not authenticated. GTM tools will require authentication."
}
return nil, output, nil
})
}