@Summary Initiate MCP server OAuth2 connect @x-apidocgen {"skip": true} EXPERIMENTAL: this endpoint is experimental and is subject to change. Redirects the user to the MCP server's OAuth2 authorization URL. nolint:revive // HTTP handler writes to ResponseWriter.
(rw http.ResponseWriter, r *http.Request)
| 871 | // |
| 872 | //nolint:revive // HTTP handler writes to ResponseWriter. |
| 873 | func (api *API) mcpServerOAuth2Connect(rw http.ResponseWriter, r *http.Request) { |
| 874 | ctx := r.Context() |
| 875 | |
| 876 | mcpServerID, ok := parseMCPServerConfigID(rw, r) |
| 877 | if !ok { |
| 878 | return |
| 879 | } |
| 880 | |
| 881 | //nolint:gocritic // Any authenticated user can initiate OAuth2 for an enabled MCP server. |
| 882 | config, err := api.Database.GetMCPServerConfigByID(dbauthz.AsSystemRestricted(ctx), mcpServerID) |
| 883 | if err != nil { |
| 884 | if httpapi.Is404Error(err) { |
| 885 | httpapi.ResourceNotFound(rw) |
| 886 | return |
| 887 | } |
| 888 | httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 889 | Message: "Failed to get MCP server config.", |
| 890 | Detail: err.Error(), |
| 891 | }) |
| 892 | return |
| 893 | } |
| 894 | |
| 895 | if !config.Enabled { |
| 896 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 897 | Message: "MCP server is not enabled.", |
| 898 | }) |
| 899 | return |
| 900 | } |
| 901 | |
| 902 | if config.AuthType != "oauth2" { |
| 903 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 904 | Message: "MCP server does not use OAuth2 authentication.", |
| 905 | }) |
| 906 | return |
| 907 | } |
| 908 | |
| 909 | if config.OAuth2AuthURL == "" { |
| 910 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 911 | Message: "MCP server OAuth2 authorization URL is not configured.", |
| 912 | }) |
| 913 | return |
| 914 | } |
| 915 | |
| 916 | // Build the authorization URL. The frontend opens this in a popup. |
| 917 | // The callback URL is on our server; after the exchange we store |
| 918 | // the token and close the popup. |
| 919 | state := uuid.New().String() |
| 920 | callbackPath := fmt.Sprintf("/api/experimental/mcp/servers/%s/oauth2/callback", config.ID) |
| 921 | http.SetCookie(rw, api.DeploymentValues.HTTPCookies.Apply(&http.Cookie{ |
| 922 | Name: "mcp_oauth2_state_" + config.ID.String(), |
| 923 | Value: state, |
| 924 | Path: callbackPath, |
| 925 | MaxAge: 600, // 10 minutes |
| 926 | HttpOnly: true, |
| 927 | SameSite: http.SameSiteLaxMode, |
| 928 | })) |
| 929 | |
| 930 | // PKCE (RFC 7636) is required by many OAuth2 providers (e.g. |
nothing calls this directly
no test coverage detected