|
| 1 | +// Copyright 2026 The Go MCP SDK Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by the license |
| 3 | +// that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package main |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "encoding/json" |
| 10 | + "flag" |
| 11 | + "fmt" |
| 12 | + "log" |
| 13 | + "net/http" |
| 14 | + "net/http/httputil" |
| 15 | + "net/url" |
| 16 | + "strings" |
| 17 | + "time" |
| 18 | + |
| 19 | + "github.com/modelcontextprotocol/go-sdk/auth" |
| 20 | + "github.com/modelcontextprotocol/go-sdk/mcp" |
| 21 | + "github.com/modelcontextprotocol/go-sdk/oauthex" |
| 22 | +) |
| 23 | + |
| 24 | +// Flags. |
| 25 | +var ( |
| 26 | + port = flag.Int("port", 8000, "Port to listen on") |
| 27 | +) |
| 28 | + |
| 29 | +// Configuration required for this example. |
| 30 | +var ( |
| 31 | + // Authorization server to return in the protected resource metadata. |
| 32 | + authorizationServer = "" |
| 33 | + // Introspection endpoint for verifying tokens. |
| 34 | + introspectionEndpoint = "" |
| 35 | + // Client credentials used in the introspection request. |
| 36 | + clientID = "" |
| 37 | + clientSecret = "" |
| 38 | +) |
| 39 | + |
| 40 | +func verifyToken(ctx context.Context, token string, _ *http.Request) (*auth.TokenInfo, error) { |
| 41 | + data := url.Values{} |
| 42 | + data.Set("token", token) |
| 43 | + data.Set("token_type_hint", "access_token") |
| 44 | + |
| 45 | + req, err := http.NewRequestWithContext(ctx, "POST", introspectionEndpoint, strings.NewReader(data.Encode())) |
| 46 | + if err != nil { |
| 47 | + return nil, err |
| 48 | + } |
| 49 | + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 50 | + req.Header.Set("Accept", "application/json") |
| 51 | + req.SetBasicAuth(clientID, clientSecret) |
| 52 | + |
| 53 | + resp, err := http.DefaultClient.Do(req) |
| 54 | + if err != nil { |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + defer resp.Body.Close() |
| 58 | + |
| 59 | + if resp.StatusCode != http.StatusOK { |
| 60 | + dump, _ := httputil.DumpResponse(resp, true) |
| 61 | + log.Printf("Introspection failed: %s", dump) |
| 62 | + return nil, fmt.Errorf("introspection failed with status %d", resp.StatusCode) |
| 63 | + } |
| 64 | + |
| 65 | + var result struct { |
| 66 | + Active bool `json:"active"` |
| 67 | + Scope string `json:"scope"` |
| 68 | + Exp int64 `json:"exp"` |
| 69 | + Sub string `json:"sub"` |
| 70 | + } |
| 71 | + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { |
| 72 | + return nil, err |
| 73 | + } |
| 74 | + |
| 75 | + if !result.Active { |
| 76 | + return nil, auth.ErrInvalidToken |
| 77 | + } |
| 78 | + |
| 79 | + return &auth.TokenInfo{ |
| 80 | + Scopes: strings.Fields(result.Scope), |
| 81 | + Expiration: time.Unix(result.Exp, 0), |
| 82 | + UserID: result.Sub, |
| 83 | + }, nil |
| 84 | +} |
| 85 | + |
| 86 | +func main() { |
| 87 | + flag.Parse() |
| 88 | + metadata := &oauthex.ProtectedResourceMetadata{ |
| 89 | + Resource: fmt.Sprintf("http://localhost:%d/mcp", *port), |
| 90 | + AuthorizationServers: []string{authorizationServer}, |
| 91 | + ScopesSupported: []string{"read"}, |
| 92 | + } |
| 93 | + http.Handle("/.well-known/oauth-protected-resource", auth.ProtectedResourceMetadataHandler(metadata)) |
| 94 | + |
| 95 | + server := mcp.NewServer(&mcp.Implementation{ |
| 96 | + Name: "test-server", |
| 97 | + Version: "1.0.0", |
| 98 | + }, nil) |
| 99 | + server.AddReceivingMiddleware(createLoggingMiddleware()) |
| 100 | + |
| 101 | + handler := mcp.NewStreamableHTTPHandler(func(req *http.Request) *mcp.Server { |
| 102 | + return server |
| 103 | + }, nil) |
| 104 | + |
| 105 | + authMiddleware := auth.RequireBearerToken(verifyToken, &auth.RequireBearerTokenOptions{ |
| 106 | + Scopes: []string{"read"}, |
| 107 | + ResourceMetadataURL: fmt.Sprintf("http://localhost:%d/.well-known/oauth-protected-resource", *port), |
| 108 | + }) |
| 109 | + |
| 110 | + http.Handle("/mcp", authMiddleware(handler)) |
| 111 | + |
| 112 | + log.Printf("Starting server on http://localhost:%d", *port) |
| 113 | + log.Fatal(http.ListenAndServe(fmt.Sprintf("localhost:%d", *port), nil)) |
| 114 | +} |
| 115 | + |
| 116 | +// createLoggingMiddleware creates an MCP middleware that logs method calls. |
| 117 | +func createLoggingMiddleware() mcp.Middleware { |
| 118 | + return func(next mcp.MethodHandler) mcp.MethodHandler { |
| 119 | + return func( |
| 120 | + ctx context.Context, |
| 121 | + method string, |
| 122 | + req mcp.Request, |
| 123 | + ) (mcp.Result, error) { |
| 124 | + start := time.Now() |
| 125 | + sessionID := req.GetSession().ID() |
| 126 | + |
| 127 | + // Log request details. |
| 128 | + log.Printf("[REQUEST] Session: %s | Method: %s", |
| 129 | + sessionID, |
| 130 | + method) |
| 131 | + |
| 132 | + // Call the actual handler. |
| 133 | + result, err := next(ctx, method, req) |
| 134 | + |
| 135 | + // Log response details. |
| 136 | + duration := time.Since(start) |
| 137 | + |
| 138 | + if err != nil { |
| 139 | + log.Printf("[RESPONSE] Session: %s | Method: %s | Status: ERROR | Duration: %v | Error: %v", |
| 140 | + sessionID, |
| 141 | + method, |
| 142 | + duration, |
| 143 | + err) |
| 144 | + } else { |
| 145 | + log.Printf("[RESPONSE] Session: %s | Method: %s | Status: OK | Duration: %v", |
| 146 | + sessionID, |
| 147 | + method, |
| 148 | + duration) |
| 149 | + } |
| 150 | + |
| 151 | + return result, err |
| 152 | + } |
| 153 | + } |
| 154 | +} |
0 commit comments