SetCorsHeaders is middleware that sets CORS headers to allow browser-based MCP clients to connect from any origin. This is safe because the server authenticates via bearer tokens (not cookies), so cross-origin requests cannot exploit ambient credentials.
(h http.Handler)
| 12 | // authenticates via bearer tokens (not cookies), so cross-origin requests |
| 13 | // cannot exploit ambient credentials. |
| 14 | func SetCorsHeaders(h http.Handler) http.Handler { |
| 15 | allowHeaders := strings.Join([]string{ |
| 16 | "Content-Type", |
| 17 | "Mcp-Session-Id", |
| 18 | "Mcp-Protocol-Version", |
| 19 | "Last-Event-ID", |
| 20 | headers.AuthorizationHeader, |
| 21 | headers.MCPReadOnlyHeader, |
| 22 | headers.MCPToolsetsHeader, |
| 23 | headers.MCPToolsHeader, |
| 24 | headers.MCPExcludeToolsHeader, |
| 25 | headers.MCPFeaturesHeader, |
| 26 | headers.MCPLockdownHeader, |
| 27 | headers.MCPInsidersHeader, |
| 28 | }, ", ") |
| 29 | |
| 30 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 31 | w.Header().Set("Access-Control-Allow-Origin", "*") |
| 32 | w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS") |
| 33 | w.Header().Set("Access-Control-Max-Age", "86400") |
| 34 | w.Header().Set("Access-Control-Expose-Headers", "Mcp-Session-Id, WWW-Authenticate") |
| 35 | w.Header().Set("Access-Control-Allow-Headers", allowHeaders) |
| 36 | |
| 37 | if r.Method == http.MethodOptions { |
| 38 | w.WriteHeader(http.StatusOK) |
| 39 | return |
| 40 | } |
| 41 | h.ServeHTTP(w, r) |
| 42 | }) |
| 43 | } |