MCPcopy Create free account
hub / github.com/modelcontextprotocol/go-sdk / main

Function main

examples/server/auth-middleware/main.go:235–396  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

233}
234
235func main() {
236 flag.Parse()
237
238 // Create the MCP server.
239 server := createMCPServer()
240
241 // Create authentication middleware.
242 jwtAuth := auth.RequireBearerToken(verifyJWT, &auth.RequireBearerTokenOptions{
243 Scopes: []string{"read"}, // Require "read" permission
244 ResourceMetadataURL: "http://localhost:8080/.well-known/oauth-protected-resource",
245 })
246
247 apiKeyAuth := auth.RequireBearerToken(verifyAPIKey, &auth.RequireBearerTokenOptions{
248 Scopes: []string{"read"}, // Require "read" permission
249 })
250
251 // Create HTTP handler with authentication.
252 handler := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
253 return server
254 }, nil)
255
256 // Apply authentication middleware to the MCP handler.
257 authenticatedHandler := jwtAuth(handler)
258 apiKeyHandler := apiKeyAuth(handler)
259
260 // Create router for different authentication methods.
261 http.HandleFunc("/mcp/jwt", authenticatedHandler.ServeHTTP)
262 http.HandleFunc("/mcp/apikey", apiKeyHandler.ServeHTTP)
263
264 // Add utility endpoints for token generation.
265 http.HandleFunc("/generate-token", func(w http.ResponseWriter, r *http.Request) {
266 // Get user ID from query parameters (default: "test-user").
267 userID := r.URL.Query().Get("user_id")
268 if userID == "" {
269 userID = "test-user"
270 }
271
272 // Get scopes from query parameters (default: ["read", "write"]).
273 scopes := strings.Split(r.URL.Query().Get("scopes"), ",")
274 if len(scopes) == 1 && scopes[0] == "" {
275 scopes = []string{"read", "write"}
276 }
277
278 // Get expiration time from query parameters (default: 1 hour).
279 expiresIn := 1 * time.Hour
280 if expStr := r.URL.Query().Get("expires_in"); expStr != "" {
281 if exp, err := time.ParseDuration(expStr); err == nil {
282 expiresIn = exp
283 }
284 }
285
286 // Generate the JWT token.
287 token, err := generateToken(userID, scopes, expiresIn)
288 if err != nil {
289 http.Error(w, "Failed to generate token", http.StatusInternalServerError)
290 return
291 }
292

Callers

nothing calls this directly

Calls 8

RequireBearerTokenFunction · 0.92
NewStreamableHTTPHandlerFunction · 0.92
createMCPServerFunction · 0.85
generateTokenFunction · 0.85
ReadMethod · 0.65
HandleMethod · 0.65
ErrorMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…