From ba068876cd1c86236d03baebbe90135500f882cc Mon Sep 17 00:00:00 2001 From: Ethan <39577870+ethanndickson@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:39:30 +1100 Subject: [PATCH] feat: register MCP OAuth2 clients when MCP server configs are updated (#31559) Relates to CODAGT-779 We only ran Dynamic Client Registration when an MCP server config was created. If an admin later switched an existing server to OAuth2, or changed the URL of a server whose client Coder had registered, the server was left without a working client, and users couldn't connect to it. To fix, create and update now go through the same planner, which registers a client whenever a save needs one. That's when a config becomes `dynamic` (on create, when the auth type changes to OAuth2, or when `oauth2_client_registration` changes from `manual` to `dynamic`), or when the URL of a `dynamic` config changes. The update request gets an optional `oauth2_client_registration` field. When it's omitted, we use `dynamic` if the resulting config has no client ID, auth URL or token URL, and keep the stored value otherwise. Coder owns the client ID, secret, auth URL and token URL of a `dynamic` config, so we ignore them when a request leaves them empty or repeats them, and any other value fails with a 400 unless the request also sets `manual`. Updates that touch auth fields are also validated now, so a `manual` config without a client ID, auth URL or token URL is rejected. A new client replaces the client ID, so it deletes every user's stored token. If discovery or registration fails, nothing changes, and if the config changes whilst we're registering, the request fails with a `409 Conflict`. There are a few gaps I've left for now, and documented. A change to the deployment's access URL doesn't register a new client. Configs broken by the old behaviour stay `manual` until an admin switches them to `dynamic`. We also don't re-register when the provider rejects the client with `invalid_client`. --- coderd/apidoc/docs.go | 24 + coderd/apidoc/swagger.json | 18 + coderd/mcp.go | 487 +++++++++++++----- coderd/mcp_internal_test.go | 255 +++++++++ coderd/mcp_test.go | 354 ++++++++++--- codersdk/mcp.go | 17 + .../agents/platform-controls/mcp-servers.md | 57 +- docs/reference/api/schemas.md | 138 ++--- site/src/api/typesGenerated.ts | 21 + 9 files changed, 1087 insertions(+), 284 deletions(-) diff --git a/coderd/apidoc/docs.go b/coderd/apidoc/docs.go index abe2a77a8c5..1e90c4f46f9 100644 --- a/coderd/apidoc/docs.go +++ b/coderd/apidoc/docs.go @@ -24872,6 +24872,18 @@ const docTemplate = `{ "oauth2_client_id": { "type": "string" }, + "oauth2_client_registration": { + "description": "OAuth2ClientRegistration selects how Coder gets the OAuth2 client.\nWith \"dynamic\", Coder discovers the authorization server of URL and\nregisters a client (RFC 7591), so the client ID, client secret, auth\nURL, and token URL must be empty. With \"manual\", the client ID, auth\nURL, and token URL are required. When empty, Coder uses \"dynamic\" if\nthose three fields are empty, and \"manual\" otherwise.", + "enum": [ + "manual", + "dynamic" + ], + "allOf": [ + { + "$ref": "#/definitions/codersdk.MCPServerOAuth2ClientRegistration" + } + ] + }, "oauth2_client_secret": { "type": "string" }, @@ -33211,6 +33223,18 @@ const docTemplate = `{ "oauth2_client_id": { "type": "string" }, + "oauth2_client_registration": { + "description": "OAuth2ClientRegistration changes how Coder gets the OAuth2 client.\nWhen a request that sets the URL or an auth field omits it, Coder\nuses \"dynamic\" if the resulting config has no client ID, auth URL,\nand token URL, and keeps the stored value otherwise. Coder registers\na new client when the config becomes \"dynamic\" or when the URL of a\n\"dynamic\" config changes. A new client deletes the stored user\ntokens. A \"dynamic\" config ignores empty and unchanged values for\nthe client ID, client secret, auth URL, and token URL. Other values\nfail unless the request also sets \"manual\".", + "enum": [ + "manual", + "dynamic" + ], + "allOf": [ + { + "$ref": "#/definitions/codersdk.MCPServerOAuth2ClientRegistration" + } + ] + }, "oauth2_client_secret": { "type": "string" }, diff --git a/coderd/apidoc/swagger.json b/coderd/apidoc/swagger.json index ef438e715c9..a72fc19084b 100644 --- a/coderd/apidoc/swagger.json +++ b/coderd/apidoc/swagger.json @@ -22605,6 +22605,15 @@ "oauth2_client_id": { "type": "string" }, + "oauth2_client_registration": { + "description": "OAuth2ClientRegistration selects how Coder gets the OAuth2 client.\nWith \"dynamic\", Coder discovers the authorization server of URL and\nregisters a client (RFC 7591), so the client ID, client secret, auth\nURL, and token URL must be empty. With \"manual\", the client ID, auth\nURL, and token URL are required. When empty, Coder uses \"dynamic\" if\nthose three fields are empty, and \"manual\" otherwise.", + "enum": ["manual", "dynamic"], + "allOf": [ + { + "$ref": "#/definitions/codersdk.MCPServerOAuth2ClientRegistration" + } + ] + }, "oauth2_client_secret": { "type": "string" }, @@ -30614,6 +30623,15 @@ "oauth2_client_id": { "type": "string" }, + "oauth2_client_registration": { + "description": "OAuth2ClientRegistration changes how Coder gets the OAuth2 client.\nWhen a request that sets the URL or an auth field omits it, Coder\nuses \"dynamic\" if the resulting config has no client ID, auth URL,\nand token URL, and keeps the stored value otherwise. Coder registers\na new client when the config becomes \"dynamic\" or when the URL of a\n\"dynamic\" config changes. A new client deletes the stored user\ntokens. A \"dynamic\" config ignores empty and unchanged values for\nthe client ID, client secret, auth URL, and token URL. Other values\nfail unless the request also sets \"manual\".", + "enum": ["manual", "dynamic"], + "allOf": [ + { + "$ref": "#/definitions/codersdk.MCPServerOAuth2ClientRegistration" + } + ] + }, "oauth2_client_secret": { "type": "string" }, diff --git a/coderd/mcp.go b/coderd/mcp.go index aad8a2fd4d7..6dd11bfe8bf 100644 --- a/coderd/mcp.go +++ b/coderd/mcp.go @@ -338,94 +338,6 @@ func (api *API) createMCPServerConfig(rw http.ResponseWriter, r *http.Request) { return } - configID := uuid.New() - oauth2ClientRegistration := codersdk.MCPServerOAuth2ClientRegistrationManual - - // Validate auth-type-dependent fields. - switch req.AuthType { - case "oauth2": - // When the admin does not provide OAuth2 credentials, attempt - // automatic discovery and Dynamic Client Registration (RFC 7591) - // using the MCP server URL. This follows the MCP authorization - // spec: discover the authorization server via Protected Resource - // Metadata (RFC 9728) and Authorization Server Metadata - // (RFC 8414), then register a client dynamically. - if req.OAuth2ClientID == "" && req.OAuth2AuthURL == "" && req.OAuth2TokenURL == "" { - // Create-only callers cannot read configs. This pre-DCR check reveals nothing - // beyond the insert's conflict response, which remains authoritative for races. - //nolint:gocritic // Restrict system access to this existence check. - _, err := api.Database.GetMCPServerConfigByOrganizationAndSlug(dbauthz.AsSystemRestricted(ctx), database.GetMCPServerConfigByOrganizationAndSlugParams{ - OrganizationID: organization.ID, - Slug: strings.TrimSpace(req.Slug), - }) - switch { - case err == nil: - httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{ - Message: "MCP server config already exists.", - }) - return - case !errors.Is(err, sql.ErrNoRows): - httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ - Message: "Failed to create MCP server config.", - Detail: err.Error(), - }) - return - } - - result, err := api.registerMCPOAuth2Client(ctx, configID, strings.TrimSpace(req.URL)) - if err != nil { - httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ - Message: "OAuth2 auto-discovery failed. Provide oauth2_client_id, oauth2_auth_url, and oauth2_token_url manually, or ensure the MCP server supports RFC 9728 (Protected Resource Metadata) and RFC 7591 (Dynamic Client Registration).", - Detail: err.Error(), - }) - return - } - - // Determine scopes: use the request value if provided, - // otherwise fall back to the discovered value. - oauth2Scopes := strings.TrimSpace(req.OAuth2Scopes) - if oauth2Scopes == "" { - oauth2Scopes = result.scopes - } - - oauth2RevocationURL := strings.TrimSpace(req.OAuth2RevocationURL) - if oauth2RevocationURL == "" { - oauth2RevocationURL = result.revocationURL - } - - req.OAuth2ClientID = result.clientID - req.OAuth2ClientSecret = result.clientSecret - req.OAuth2AuthURL = result.authURL - req.OAuth2TokenURL = result.tokenURL - req.OAuth2RevocationURL = oauth2RevocationURL - if strings.TrimSpace(req.OAuth2Resource) == "" { - req.OAuth2Resource = result.resource - } - req.OAuth2Scopes = oauth2Scopes - oauth2ClientRegistration = codersdk.MCPServerOAuth2ClientRegistrationDynamic - } else if req.OAuth2ClientID == "" || req.OAuth2AuthURL == "" || req.OAuth2TokenURL == "" { - // Partial manual config: all three fields are required together. - httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ - Message: "OAuth2 auth type requires either all of oauth2_client_id, oauth2_auth_url, and oauth2_token_url (manual configuration), or none of them (automatic discovery via RFC 7591).", - }) - return - } - case "api_key": - if strings.TrimSpace(req.APIKeyHeader) == "" || strings.TrimSpace(req.APIKeyValue) == "" { - httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ - Message: "API key auth type requires api_key_header and api_key_value.", - }) - return - } - case "custom_headers": - if len(req.CustomHeaders) == 0 { - httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ - Message: "Custom headers auth type requires at least one custom header.", - }) - return - } - } - customHeadersJSON, err := marshalCustomHeaders(req.CustomHeaders) if err != nil { httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ @@ -435,39 +347,84 @@ func (api *API) createMCPServerConfig(rw http.ResponseWriter, r *http.Request) { return } + prev := database.MCPServerConfig{ID: uuid.New(), OrganizationID: organization.ID} + change := mcpServerConfigChangeFromCreate(req) + w, err := planMCPServerConfigWrite(prev, change, customHeadersJSON) + if err != nil { + writeInvalidMCPServerAuth(ctx, rw, err) + return + } + var registration *mcpOAuth2Discovery + if w.registerFor != "" { + // Create-only callers cannot read configs. This pre-DCR check reveals nothing + // beyond the insert's conflict response, which remains authoritative for races. + //nolint:gocritic // Restrict system access to this existence check. + _, err := api.Database.GetMCPServerConfigByOrganizationAndSlug(dbauthz.AsSystemRestricted(ctx), database.GetMCPServerConfigByOrganizationAndSlugParams{ + OrganizationID: organization.ID, + Slug: w.next.Slug, + }) + switch { + case err == nil: + httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{ + Message: "MCP server config already exists.", + }) + return + case !errors.Is(err, sql.ErrNoRows): + httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ + Message: "Failed to create MCP server config.", + Detail: err.Error(), + }) + return + } + + registration, err = api.registerMCPOAuth2Client(ctx, prev.ID, w.registerFor) + if err != nil { + writeMCPOAuth2RegistrationFailed(ctx, rw, err) + return + } + } + next, err := w.withRegistration(prev, change, registration) + if err != nil { + httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ + Message: "Failed to create MCP server config.", + Detail: err.Error(), + }) + return + } + inserted, err := api.Database.InsertMCPServerConfig(ctx, database.InsertMCPServerConfigParams{ - ID: configID, - OrganizationID: organization.ID, - DisplayName: strings.TrimSpace(req.DisplayName), - Slug: strings.TrimSpace(req.Slug), - Description: strings.TrimSpace(req.Description), - IconURL: strings.TrimSpace(req.IconURL), - Transport: strings.TrimSpace(req.Transport), - Url: strings.TrimSpace(req.URL), - AuthType: strings.TrimSpace(req.AuthType), - OAuth2ClientID: strings.TrimSpace(req.OAuth2ClientID), - OAuth2ClientSecret: strings.TrimSpace(req.OAuth2ClientSecret), - OAuth2ClientSecretKeyID: sql.NullString{}, - OAuth2AuthURL: strings.TrimSpace(req.OAuth2AuthURL), - OAuth2TokenURL: strings.TrimSpace(req.OAuth2TokenURL), - OAuth2RevocationURL: strings.TrimSpace(req.OAuth2RevocationURL), - OAuth2Resource: strings.TrimSpace(req.OAuth2Resource), - OAuth2Scopes: strings.TrimSpace(req.OAuth2Scopes), - OAuth2ClientRegistration: string(oauth2ClientRegistration), - APIKeyHeader: strings.TrimSpace(req.APIKeyHeader), - APIKeyValue: strings.TrimSpace(req.APIKeyValue), - APIKeyValueKeyID: sql.NullString{}, - CustomHeaders: customHeadersJSON, - CustomHeadersKeyID: sql.NullString{}, - SigningSecret: strings.TrimSpace(req.SigningSecret), - SigningSecretKeyID: sql.NullString{}, - ToolAllowList: coalesceStringSlice(trimStringSlice(req.ToolAllowList)), - ToolDenyList: coalesceStringSlice(trimStringSlice(req.ToolDenyList)), - Availability: strings.TrimSpace(req.Availability), - Enabled: req.Enabled, - ModelIntent: req.ModelIntent, - AllowInPlanMode: req.AllowInPlanMode, - ForwardCoderHeaders: req.ForwardCoderHeaders, + ID: next.ID, + OrganizationID: next.OrganizationID, + DisplayName: next.DisplayName, + Slug: next.Slug, + Description: next.Description, + IconURL: next.IconURL, + Transport: next.Transport, + Url: next.Url, + AuthType: next.AuthType, + OAuth2ClientID: next.OAuth2ClientID, + OAuth2ClientSecret: next.OAuth2ClientSecret, + OAuth2ClientSecretKeyID: next.OAuth2ClientSecretKeyID, + OAuth2AuthURL: next.OAuth2AuthURL, + OAuth2TokenURL: next.OAuth2TokenURL, + OAuth2RevocationURL: next.OAuth2RevocationURL, + OAuth2Resource: next.OAuth2Resource, + OAuth2Scopes: next.OAuth2Scopes, + OAuth2ClientRegistration: next.OAuth2ClientRegistration, + APIKeyHeader: next.APIKeyHeader, + APIKeyValue: next.APIKeyValue, + APIKeyValueKeyID: next.APIKeyValueKeyID, + CustomHeaders: next.CustomHeaders, + CustomHeadersKeyID: next.CustomHeadersKeyID, + SigningSecret: next.SigningSecret, + SigningSecretKeyID: next.SigningSecretKeyID, + ToolAllowList: next.ToolAllowList, + ToolDenyList: next.ToolDenyList, + Availability: next.Availability, + Enabled: next.Enabled, + ModelIntent: next.ModelIntent, + AllowInPlanMode: next.AllowInPlanMode, + ForwardCoderHeaders: next.ForwardCoderHeaders, GroupACL: database.ChatACL{ organization.ID.String(): {Permissions: []policy.Action{policy.ActionRead}}, }, @@ -565,7 +522,7 @@ func (api *API) getMCPServerConfig(rw http.ResponseWriter, r *http.Request) { var errUserOIDCRequiresDeploymentPerms = xerrors.New("managing user_oidc MCP server configs requires deployment-level permissions") -var errAPIKeyAuthRequiresHeaderAndValue = xerrors.New("api_key auth type requires api_key_header and api_key_value") +var errMCPConfigChangedDuringRegistration = xerrors.New("MCP server config changed during OAuth2 client registration") var errMCPConfigSupersededDuringAuth = xerrors.New("MCP server config superseded during authorization") @@ -582,6 +539,12 @@ func (api *API) authorizeUserOIDCMCPServerConfig(rw http.ResponseWriter, r *http return false } +// touchesUserOIDC reports whether updating c with req changes a user_oidc +// config or makes c one. +func touchesUserOIDC(c database.MCPServerConfig, req codersdk.UpdateMCPServerConfigRequest) bool { + return c.AuthType == "user_oidc" || (req.AuthType != nil && *req.AuthType == "user_oidc") +} + // Preserve the param middleware's 404 concealment. Write denial is a 403. func (api *API) getMCPServerConfigForMutation(rw http.ResponseWriter, r *http.Request, action policy.Action) (database.MCPServerConfig, bool) { config := httpmw.MCPServerConfigParam(r) @@ -633,6 +596,12 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { return } + // Authorize before the client registration below, which reaches the + // remote provider. The transaction checks again on the locked row. + if touchesUserOIDC(existing, req) && !api.authorizeUserOIDCMCPServerConfig(rw, r) { + return + } + // Validated here rather than via a struct tag because an empty // string is a valid value that clears the stored URL. if req.OAuth2RevocationURL != nil { @@ -674,8 +643,24 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { } } + // Plan on the unlocked row first, so that the network calls of a + // registration do not run while the row is locked. + w, err := planMCPServerConfigWrite(existing, req, customHeadersJSON) + if err != nil { + writeInvalidMCPServerAuth(ctx, rw, err) + return + } + var registration *mcpOAuth2Discovery + if w.registerFor != "" { + registration, err = api.registerMCPOAuth2Client(ctx, existing.ID, w.registerFor) + if err != nil { + writeMCPOAuth2RegistrationFailed(ctx, rw, err) + return + } + } + var updated database.MCPServerConfig - err := api.Database.InTx(func(tx database.Store) error { + err = api.Database.InTx(func(tx database.Store) error { // Lock and re-fetch the row so omitted fields and the audit baseline // match the row this update replaces, and so grant invalidation // serializes with in-flight OAuth callbacks verifying the config. @@ -687,18 +672,17 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { existing = current aReq.Old = current - touchesUserOIDC := existing.AuthType == "user_oidc" || - (req.AuthType != nil && *req.AuthType == "user_oidc") - if touchesUserOIDC && !api.Authorize(r, policy.ActionUpdate, rbac.ResourceDeploymentConfig) { + if touchesUserOIDC(existing, req) && !api.Authorize(r, policy.ActionUpdate, rbac.ResourceDeploymentConfig) { return errUserOIDCRequiresDeploymentPerms } - next := applyMCPServerConfigChange(existing, req, customHeadersJSON) - if next.OAuth2ClientRegistration == string(codersdk.MCPServerOAuth2ClientRegistrationDynamic) && changesDynamicOAuth2Client(existing, req) { - next.OAuth2ClientRegistration = string(codersdk.MCPServerOAuth2ClientRegistrationManual) + w, err := planMCPServerConfigWrite(existing, req, customHeadersJSON) + if err != nil { + return err } - if next.AuthType == "api_key" && (next.APIKeyHeader == "" || next.APIKeyValue == "") { - return errAPIKeyAuthRequiresHeaderAndValue + next, err := w.withRegistration(existing, req, registration) + if err != nil { + return err } if mcpOAuth2GrantBindingOf(next) != mcpOAuth2GrantBindingOf(existing) { @@ -748,17 +732,21 @@ func (api *API) updateMCPServerConfig(rw http.ResponseWriter, r *http.Request) { return nil }, nil) if err != nil { + var authErr invalidMCPServerAuthError switch { case errors.Is(err, errUserOIDCRequiresDeploymentPerms): httpapi.Write(ctx, rw, http.StatusForbidden, codersdk.Response{ Message: "Managing user_oidc MCP server configs requires deployment-level permissions.", }) return - case errors.Is(err, errAPIKeyAuthRequiresHeaderAndValue): - httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ - Message: "API key auth type requires api_key_header and api_key_value.", + case errors.Is(err, errMCPConfigChangedDuringRegistration): + httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{ + Message: "MCP server config changed during OAuth2 client registration. Try again.", }) return + case errors.As(err, &authErr): + writeInvalidMCPServerAuth(ctx, rw, authErr) + return case httpapi.Is404Error(err): httpapi.ResourceNotFound(rw) return @@ -889,16 +877,229 @@ func clearUnusedMCPServerAuthFields(c database.MCPServerConfig) database.MCPServ return c } -// changesDynamicOAuth2Client reports whether req changes a field that -// Coder owns for a dynamic OAuth2 client. -func changesDynamicOAuth2Client(prev database.MCPServerConfig, req codersdk.UpdateMCPServerConfigRequest) bool { - changes := func(v *string, prevValue string) bool { - return v != nil && strings.TrimSpace(*v) != prevValue +// mcpServerConfigWrite is the result of planning a write to an MCP server +// config. +type mcpServerConfigWrite struct { + // next is the config to store, without the client that a pending + // registration adds. + next database.MCPServerConfig + // registerFor is the server URL that a new dynamic OAuth2 client must + // be registered for, or "" when the write needs no registration. + registerFor string +} + +// withRegistration returns the config to store. registration must be the +// client registered for w.registerFor, or nil when w needs no client. +func (w mcpServerConfigWrite) withRegistration(prev database.MCPServerConfig, req codersdk.UpdateMCPServerConfigRequest, registration *mcpOAuth2Discovery) (database.MCPServerConfig, error) { + var registeredFor string + if registration != nil { + registeredFor = registration.serverURL } - return changes(req.OAuth2ClientID, prev.OAuth2ClientID) || - changes(req.OAuth2ClientSecret, prev.OAuth2ClientSecret) || - changes(req.OAuth2AuthURL, prev.OAuth2AuthURL) || - changes(req.OAuth2TokenURL, prev.OAuth2TokenURL) + if registeredFor != w.registerFor { + return database.MCPServerConfig{}, errMCPConfigChangedDuringRegistration + } + if registration == nil { + return w.next, nil + } + return applyOAuth2Registration(prev, w.next, req, registration), nil +} + +// invalidMCPServerAuthError reports auth fields that make a config unusable. +type invalidMCPServerAuthError struct { + message string +} + +func (e invalidMCPServerAuthError) Error() string { + return e.message +} + +func writeInvalidMCPServerAuth(ctx context.Context, rw http.ResponseWriter, err error) { + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ + Message: err.Error(), + }) +} + +func writeMCPOAuth2RegistrationFailed(ctx context.Context, rw http.ResponseWriter, err error) { + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ + Message: "OAuth2 auto-discovery failed. Set oauth2_client_registration to manual and provide oauth2_client_id, oauth2_auth_url, and oauth2_token_url, or ensure the MCP server supports RFC 9728 (Protected Resource Metadata), RFC 8414 (Authorization Server Metadata), and RFC 7591 (Dynamic Client Registration).", + Detail: err.Error(), + }) +} + +// planMCPServerConfigWrite applies req to prev and decides whether the +// result needs a new dynamic OAuth2 client. The client registration +// method and the auth checks apply only when req sets an auth field, so +// that a request such as an enabled toggle still works on a config with +// invalid auth fields. +func planMCPServerConfigWrite(prev database.MCPServerConfig, req codersdk.UpdateMCPServerConfigRequest, customHeadersJSON string) (mcpServerConfigWrite, error) { + next := applyMCPServerConfigChange(prev, req, customHeadersJSON) + if !setsMCPServerAuthField(req) { + return mcpServerConfigWrite{next: next}, nil + } + + if next.AuthType == "oauth2" { + switch { + case req.OAuth2ClientRegistration != nil: + next.OAuth2ClientRegistration = string(*req.OAuth2ClientRegistration) + case next.OAuth2ClientID == "" && next.OAuth2AuthURL == "" && next.OAuth2TokenURL == "": + next.OAuth2ClientRegistration = string(codersdk.MCPServerOAuth2ClientRegistrationDynamic) + case next.OAuth2ClientRegistration == "": + next.OAuth2ClientRegistration = string(codersdk.MCPServerOAuth2ClientRegistrationManual) + } + if next.OAuth2ClientRegistration == string(codersdk.MCPServerOAuth2ClientRegistrationDynamic) { + if suppliesOAuth2Client(prev, req) { + return mcpServerConfigWrite{}, invalidMCPServerAuthError{ + message: "Set oauth2_client_registration to manual to edit the OAuth2 client ID, client secret, auth URL, or token URL.", + } + } + // Coder owns the client of a dynamic config. A new registration + // replaces it; otherwise the registered client stays. + next.OAuth2ClientID = prev.OAuth2ClientID + next.OAuth2ClientSecret = prev.OAuth2ClientSecret + next.OAuth2ClientSecretKeyID = prev.OAuth2ClientSecretKeyID + next.OAuth2AuthURL = prev.OAuth2AuthURL + next.OAuth2TokenURL = prev.OAuth2TokenURL + } + } + + registerFor := oauth2RegistrationKey(next) + if registerFor == oauth2RegistrationKey(prev) { + registerFor = "" + } + if registerFor == "" { + if err := validateMCPServerConfigAuth(next); err != nil { + return mcpServerConfigWrite{}, err + } + } + return mcpServerConfigWrite{next: next, registerFor: registerFor}, nil +} + +func setsMCPServerAuthField(req codersdk.UpdateMCPServerConfigRequest) bool { + return req.AuthType != nil || + req.URL != nil || + req.OAuth2ClientRegistration != nil || + req.OAuth2ClientID != nil || + req.OAuth2ClientSecret != nil || + req.OAuth2AuthURL != nil || + req.OAuth2TokenURL != nil || + req.OAuth2RevocationURL != nil || + req.OAuth2Resource != nil || + req.OAuth2Scopes != nil || + req.APIKeyHeader != nil || + req.APIKeyValue != nil || + req.CustomHeaders != nil +} + +// oauth2RegistrationKey returns the server URL that the dynamic OAuth2 +// client of c must be registered for, or "" when c has no dynamic client. +func oauth2RegistrationKey(c database.MCPServerConfig) string { + if c.AuthType != "oauth2" || c.OAuth2ClientRegistration != string(codersdk.MCPServerOAuth2ClientRegistrationDynamic) { + return "" + } + return c.Url +} + +// suppliesOAuth2Client reports whether req sets an OAuth2 client field to +// a value that is not empty and is not the stored value. A dynamic config +// cannot use such a value, because Coder owns its client. +func suppliesOAuth2Client(prev database.MCPServerConfig, req codersdk.UpdateMCPServerConfigRequest) bool { + supplies := func(v *string, prevValue string) bool { + if v == nil { + return false + } + trimmed := strings.TrimSpace(*v) + return trimmed != "" && trimmed != prevValue + } + return supplies(req.OAuth2ClientID, prev.OAuth2ClientID) || + supplies(req.OAuth2ClientSecret, prev.OAuth2ClientSecret) || + supplies(req.OAuth2AuthURL, prev.OAuth2AuthURL) || + supplies(req.OAuth2TokenURL, prev.OAuth2TokenURL) +} + +// validateMCPServerConfigAuth checks that c has the credentials that its +// auth type needs. +func validateMCPServerConfigAuth(c database.MCPServerConfig) error { + switch c.AuthType { + case "oauth2": + if c.OAuth2ClientID == "" || c.OAuth2AuthURL == "" || c.OAuth2TokenURL == "" { + return invalidMCPServerAuthError{ + message: "Manual OAuth2 client registration requires oauth2_client_id, oauth2_auth_url, and oauth2_token_url. Set oauth2_client_registration to dynamic for automatic discovery (RFC 7591).", + } + } + case "api_key": + if c.APIKeyHeader == "" || c.APIKeyValue == "" { + return invalidMCPServerAuthError{ + message: "API key auth type requires api_key_header and api_key_value.", + } + } + case "custom_headers": + if c.CustomHeaders == "" || c.CustomHeaders == "{}" { + return invalidMCPServerAuthError{ + message: "Custom headers auth type requires at least one custom header.", + } + } + } + return nil +} + +// applyOAuth2Registration returns next with the client of registration. +// For the scopes, resource, and revocation URL, the discovered value +// wins unless req changes the field from prev to a non-empty value. +func applyOAuth2Registration(prev, next database.MCPServerConfig, req codersdk.UpdateMCPServerConfigRequest, registration *mcpOAuth2Discovery) database.MCPServerConfig { + discoveredUnlessOverridden := func(v *string, prevValue, discovered string) string { + if v != nil { + if trimmed := strings.TrimSpace(*v); trimmed != "" && trimmed != prevValue { + return trimmed + } + } + return discovered + } + + next.OAuth2ClientID = registration.clientID + next.OAuth2ClientSecret = registration.clientSecret + next.OAuth2ClientSecretKeyID = sql.NullString{} + next.OAuth2AuthURL = registration.authURL + next.OAuth2TokenURL = registration.tokenURL + next.OAuth2Scopes = discoveredUnlessOverridden(req.OAuth2Scopes, prev.OAuth2Scopes, registration.scopes) + next.OAuth2Resource = discoveredUnlessOverridden(req.OAuth2Resource, prev.OAuth2Resource, registration.resource) + next.OAuth2RevocationURL = discoveredUnlessOverridden(req.OAuth2RevocationURL, prev.OAuth2RevocationURL, registration.revocationURL) + return next +} + +// mcpServerConfigChangeFromCreate returns req as an update that sets +// every field, so that create plans its write against an empty config. +func mcpServerConfigChangeFromCreate(req codersdk.CreateMCPServerConfigRequest) codersdk.UpdateMCPServerConfigRequest { + change := codersdk.UpdateMCPServerConfigRequest{ + DisplayName: &req.DisplayName, + Slug: &req.Slug, + Description: &req.Description, + IconURL: &req.IconURL, + Transport: &req.Transport, + URL: &req.URL, + AuthType: &req.AuthType, + OAuth2ClientID: &req.OAuth2ClientID, + OAuth2ClientSecret: &req.OAuth2ClientSecret, + OAuth2AuthURL: &req.OAuth2AuthURL, + OAuth2TokenURL: &req.OAuth2TokenURL, + OAuth2RevocationURL: &req.OAuth2RevocationURL, + OAuth2Resource: &req.OAuth2Resource, + OAuth2Scopes: &req.OAuth2Scopes, + APIKeyHeader: &req.APIKeyHeader, + APIKeyValue: &req.APIKeyValue, + CustomHeaders: &req.CustomHeaders, + ToolAllowList: &req.ToolAllowList, + ToolDenyList: &req.ToolDenyList, + Availability: &req.Availability, + Enabled: &req.Enabled, + ModelIntent: &req.ModelIntent, + AllowInPlanMode: &req.AllowInPlanMode, + ForwardCoderHeaders: &req.ForwardCoderHeaders, + SigningSecret: &req.SigningSecret, + } + if req.OAuth2ClientRegistration != "" { + change.OAuth2ClientRegistration = &req.OAuth2ClientRegistration + } + return change } // mcpOAuth2GrantBinding holds the config fields that a stored user grant @@ -1944,6 +2145,7 @@ func withTrailingSlash(path string) string { // mcpOAuth2Discovery holds the result of MCP OAuth2 auto-discovery // and Dynamic Client Registration. type mcpOAuth2Discovery struct { + serverURL string // the MCP server URL the client is registered for clientID string clientSecret string authURL string @@ -2270,6 +2472,7 @@ func (api *API) registerMCPOAuth2Client(ctx context.Context, configID uuid.UUID, result.revocationURL = "" } } + result.serverURL = serverURL return result, nil } diff --git a/coderd/mcp_internal_test.go b/coderd/mcp_internal_test.go index eb464b4535b..825d354cfb5 100644 --- a/coderd/mcp_internal_test.go +++ b/coderd/mcp_internal_test.go @@ -19,6 +19,8 @@ import ( "github.com/coder/coder/v2/coderd/database/dbtestutil" "github.com/coder/coder/v2/coderd/database/dbtime" "github.com/coder/coder/v2/coderd/rbac" + "github.com/coder/coder/v2/coderd/util/ptr" + "github.com/coder/coder/v2/codersdk" "github.com/coder/coder/v2/testutil" ) @@ -466,3 +468,256 @@ func TestMCPOAuth2ResourceIndicator(t *testing.T) { }) } } + +func TestPlanMCPServerConfigWrite(t *testing.T) { + t.Parallel() + + const ( + serverURL = "https://mcp.example.com/mcp" + otherURL = "https://other.example.com/mcp" + manual = string(codersdk.MCPServerOAuth2ClientRegistrationManual) + dynamic = string(codersdk.MCPServerOAuth2ClientRegistrationDynamic) + ) + noAuth := database.MCPServerConfig{ + Url: serverURL, + AuthType: "none", + OAuth2ClientRegistration: manual, + CustomHeaders: "{}", + } + manualOAuth2 := noAuth + manualOAuth2.AuthType = "oauth2" + manualOAuth2.OAuth2ClientID = "manual-client" + manualOAuth2.OAuth2AuthURL = "https://auth.example.com/authorize" + manualOAuth2.OAuth2TokenURL = "https://auth.example.com/token" + dynamicOAuth2 := manualOAuth2 + dynamicOAuth2.OAuth2ClientID = "dynamic-client" + dynamicOAuth2.OAuth2ClientRegistration = dynamic + // A row that an update saved as oauth2 without a client before + // updates could register one. + brokenOAuth2 := noAuth + brokenOAuth2.AuthType = "oauth2" + + cases := []struct { + name string + prev database.MCPServerConfig + req codersdk.UpdateMCPServerConfigRequest + wantMode string + wantRegisterFor string + wantClientID string + wantErr string + }{ + { + name: "CreateWithClientIsManual", + req: mcpServerConfigChangeFromCreate(codersdk.CreateMCPServerConfigRequest{ + URL: serverURL, + AuthType: "oauth2", + OAuth2ClientID: "manual-client", + OAuth2AuthURL: "https://auth.example.com/authorize", + OAuth2TokenURL: "https://auth.example.com/token", + }), + wantMode: manual, + }, + { + name: "CreateWithoutClientRegisters", + req: mcpServerConfigChangeFromCreate(codersdk.CreateMCPServerConfigRequest{ + URL: serverURL, + AuthType: "oauth2", + }), + wantMode: dynamic, + wantRegisterFor: serverURL, + }, + { + name: "NoneToOAuth2Registers", + prev: noAuth, + req: codersdk.UpdateMCPServerConfigRequest{AuthType: ptr.Ref("oauth2"), OAuth2ClientID: ptr.Ref("")}, + wantMode: dynamic, + wantRegisterFor: serverURL, + }, + { + name: "BrokenOAuth2Registers", + prev: brokenOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{URL: ptr.Ref(serverURL)}, + wantMode: dynamic, + wantRegisterFor: serverURL, + }, + { + name: "EnabledOnlySkipsAuth", + prev: brokenOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{Enabled: ptr.Ref(false)}, + wantMode: manual, + }, + { + name: "ManualToDynamicRegisters", + prev: manualOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{OAuth2ClientRegistration: ptr.Ref(codersdk.MCPServerOAuth2ClientRegistrationDynamic)}, + wantMode: dynamic, + wantRegisterFor: serverURL, + }, + { + name: "ManualClearedClientRegisters", + prev: manualOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{OAuth2ClientID: ptr.Ref(""), OAuth2AuthURL: ptr.Ref(""), OAuth2TokenURL: ptr.Ref("")}, + wantMode: dynamic, + wantRegisterFor: serverURL, + }, + { + name: "ManualURLChangeKeepsClient", + prev: manualOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{URL: ptr.Ref(otherURL)}, + wantMode: manual, + }, + { + name: "DynamicURLChangeRegisters", + prev: dynamicOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{URL: ptr.Ref(otherURL)}, + wantMode: dynamic, + wantRegisterFor: otherURL, + }, + { + name: "DynamicRepeatedClientKeepsClient", + prev: dynamicOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{ + URL: ptr.Ref(serverURL), + OAuth2ClientID: ptr.Ref(dynamicOAuth2.OAuth2ClientID), + OAuth2AuthURL: ptr.Ref(dynamicOAuth2.OAuth2AuthURL), + OAuth2TokenURL: ptr.Ref(dynamicOAuth2.OAuth2TokenURL), + }, + wantMode: dynamic, + }, + { + name: "DynamicClearedClientKeepsClient", + prev: dynamicOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{OAuth2ClientID: ptr.Ref("")}, + wantMode: dynamic, + wantClientID: dynamicOAuth2.OAuth2ClientID, + }, + { + name: "DynamicToManualKeepsClient", + prev: dynamicOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{OAuth2ClientRegistration: ptr.Ref(codersdk.MCPServerOAuth2ClientRegistrationManual)}, + wantMode: manual, + }, + { + name: "PartialManualClient", + prev: noAuth, + req: codersdk.UpdateMCPServerConfigRequest{AuthType: ptr.Ref("oauth2"), OAuth2ClientID: ptr.Ref("manual-client")}, + wantErr: "automatic discovery", + }, + { + name: "DynamicRejectsClientChange", + prev: dynamicOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{OAuth2ClientID: ptr.Ref("other-client")}, + wantErr: "Set oauth2_client_registration to manual", + }, + { + name: "ManualToDynamicRejectsClient", + prev: manualOAuth2, + req: codersdk.UpdateMCPServerConfigRequest{ + OAuth2ClientRegistration: ptr.Ref(codersdk.MCPServerOAuth2ClientRegistrationDynamic), + OAuth2ClientID: ptr.Ref("other-client"), + }, + wantErr: "Set oauth2_client_registration to manual", + }, + { + name: "APIKeyWithoutValue", + prev: noAuth, + req: codersdk.UpdateMCPServerConfigRequest{AuthType: ptr.Ref("api_key"), APIKeyHeader: ptr.Ref("X-Api-Key")}, + wantErr: "requires api_key_header and api_key_value", + }, + { + name: "CustomHeadersWithoutHeader", + prev: noAuth, + req: codersdk.UpdateMCPServerConfigRequest{AuthType: ptr.Ref("custom_headers")}, + wantErr: "requires at least one custom header", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + w, err := planMCPServerConfigWrite(tc.prev, tc.req, "") + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + return + } + require.NoError(t, err) + require.Equal(t, tc.wantMode, w.next.OAuth2ClientRegistration) + require.Equal(t, tc.wantRegisterFor, w.registerFor) + if tc.wantClientID != "" { + require.Equal(t, tc.wantClientID, w.next.OAuth2ClientID) + } + }) + } +} + +func TestMCPServerConfigWriteWithRegistration(t *testing.T) { + t.Parallel() + + const ( + serverURL = "https://mcp.example.com/mcp" + otherURL = "https://other.example.com/mcp" + clientID = "dynamic-client" + ) + next := database.MCPServerConfig{ + Url: serverURL, + AuthType: "oauth2", + OAuth2ClientRegistration: string(codersdk.MCPServerOAuth2ClientRegistrationDynamic), + } + registrationFor := func(u string) *mcpOAuth2Discovery { + return &mcpOAuth2Discovery{ + serverURL: u, + clientID: clientID, + authURL: "https://auth.example.com/authorize", + tokenURL: "https://auth.example.com/token", + } + } + + cases := []struct { + name string + registerFor string + registration *mcpOAuth2Discovery + wantClientID string + wantConflict bool + }{ + { + name: "NoRegistration", + }, + { + name: "MatchingRegistration", + registerFor: serverURL, + registration: registrationFor(serverURL), + wantClientID: clientID, + }, + { + name: "MissingRegistration", + registerFor: serverURL, + wantConflict: true, + }, + { + name: "RegistrationForOtherURL", + registerFor: serverURL, + registration: registrationFor(otherURL), + wantConflict: true, + }, + { + name: "UnneededRegistration", + registration: registrationFor(serverURL), + wantConflict: true, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + w := mcpServerConfigWrite{next: next, registerFor: tc.registerFor} + got, err := w.withRegistration(database.MCPServerConfig{}, codersdk.UpdateMCPServerConfigRequest{}, tc.registration) + if tc.wantConflict { + require.ErrorIs(t, err, errMCPConfigChangedDuringRegistration) + return + } + require.NoError(t, err) + require.Equal(t, serverURL, got.Url) + require.Equal(t, tc.wantClientID, got.OAuth2ClientID) + }) + } +} diff --git a/coderd/mcp_test.go b/coderd/mcp_test.go index 02efe94e938..85ed5c56261 100644 --- a/coderd/mcp_test.go +++ b/coderd/mcp_test.go @@ -12,6 +12,7 @@ import ( "net/http/httptest" "net/netip" "net/url" + "slices" "strings" "sync" "sync/atomic" @@ -30,6 +31,7 @@ import ( "github.com/coder/coder/v2/coderd/database/dbgen" "github.com/coder/coder/v2/coderd/database/dbtestutil" "github.com/coder/coder/v2/coderd/rbac" + "github.com/coder/coder/v2/coderd/util/ptr" "github.com/coder/coder/v2/codersdk" "github.com/coder/coder/v2/testutil" ) @@ -74,9 +76,30 @@ func createMCPServerConfig(t testing.TB, client *codersdk.Client, organizationID return config } -func newMCPDiscoveryServer(t testing.TB, registrationRequests *atomic.Int64) string { +// mcpDiscoveryServer is an MCP server whose authorization server supports +// discovery and dynamic client registration (RFC 7591). +type mcpDiscoveryServer struct { + url string + authURL string + + mu sync.Mutex + redirectURIs [][]string +} + +// registrations returns the redirect URIs of each registration request. +func (s *mcpDiscoveryServer) registrations() [][]string { + s.mu.Lock() + defer s.mu.Unlock() + return slices.Clone(s.redirectURIs) +} + +// newMCPDiscoveryServer starts an mcpDiscoveryServer whose URL has the +// path /mcp. When beforeRegister is not nil, it runs before each +// registration response. +func newMCPDiscoveryServer(t testing.TB, beforeRegister func()) *mcpDiscoveryServer { t.Helper() + s := &mcpDiscoveryServer{} authServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/.well-known/oauth-authorization-server": @@ -89,7 +112,19 @@ func newMCPDiscoveryServer(t testing.TB, registrationRequests *atomic.Int64) str "response_types_supported": ["code"] }`)) case "/register": - registrationRequests.Add(1) + var body struct { + RedirectURIs []string `json:"redirect_uris"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "bad json", http.StatusBadRequest) + return + } + s.mu.Lock() + s.redirectURIs = append(s.redirectURIs, body.RedirectURIs) + s.mu.Unlock() + if beforeRegister != nil { + beforeRegister() + } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) _, _ = w.Write([]byte(`{ @@ -115,7 +150,9 @@ func newMCPDiscoveryServer(t testing.TB, registrationRequests *atomic.Int64) str } })) t.Cleanup(mcpServer.Close) - return mcpServer.URL + "/mcp" + s.url = mcpServer.URL + "/mcp" + s.authURL = authServer.URL + return s } func TestMCPServerConfigLegacyRoutesRemoved(t *testing.T) { @@ -346,9 +383,6 @@ func TestMCPServerConfigsAudit(t *testing.T) { AuthType: "api_key", APIKeyHeader: "X-Api-Key", APIKeyValue: "super-secret-api-key", - CustomHeaders: map[string]string{ - "X-Extra": "plaintext-header-value", - }, Availability: "default_on", Enabled: true, }) @@ -1090,29 +1124,53 @@ func TestMCPServerConfigsSecretsNeverLeaked(t *testing.T) { firstUser := coderdtest.CreateFirstUser(t, adminClient) memberClient, _ := coderdtest.CreateAnotherUser(t, adminClient, firstUser.OrganizationID) - // Create a config with ALL secret fields populated. - created, err := adminClient.CreateMCPServerConfig(ctx, firstUser.OrganizationID, codersdk.CreateMCPServerConfigRequest{ - DisplayName: "Secrets Test", - Slug: "secrets-test", - Transport: "streamable_http", - URL: "https://mcp.example.com/secrets", - AuthType: "oauth2", - OAuth2ClientID: "client-id-secret-test", - OAuth2ClientSecret: "THIS-IS-A-SECRET-VALUE", - OAuth2AuthURL: "https://auth.example.com/authorize", - OAuth2TokenURL: "https://auth.example.com/token", - OAuth2RevocationURL: "https://auth.example.com/revoke", - OAuth2Resource: "https://mcp.example.com/secrets", - OAuth2Scopes: "read write", - APIKeyHeader: "X-Api-Key", - APIKeyValue: "THIS-IS-A-SECRET-API-KEY", - CustomHeaders: map[string]string{"X-Custom": "THIS-IS-A-SECRET-HEADER"}, - Availability: "default_on", - Enabled: true, - ToolAllowList: []string{}, - ToolDenyList: []string{}, - }) - require.NoError(t, err) + // A config stores only the secrets of its auth type, so create one + // config for each auth type that has secrets. + requests := []codersdk.CreateMCPServerConfigRequest{ + { + DisplayName: "OAuth2 Secrets Test", + Slug: "secrets-test-oauth2", + Transport: "streamable_http", + URL: "https://mcp.example.com/secrets", + AuthType: "oauth2", + OAuth2ClientID: "client-id-secret-test", + OAuth2ClientSecret: "THIS-IS-A-SECRET-VALUE", + OAuth2AuthURL: "https://auth.example.com/authorize", + OAuth2TokenURL: "https://auth.example.com/token", + OAuth2RevocationURL: "https://auth.example.com/revoke", + OAuth2Resource: "https://mcp.example.com/secrets", + OAuth2Scopes: "read write", + Availability: "default_on", + Enabled: true, + }, + { + DisplayName: "API Key Secrets Test", + Slug: "secrets-test-api-key", + Transport: "streamable_http", + URL: "https://mcp.example.com/secrets", + AuthType: "api_key", + APIKeyHeader: "X-Api-Key", + APIKeyValue: "THIS-IS-A-SECRET-API-KEY", + Availability: "default_on", + Enabled: true, + }, + { + DisplayName: "Custom Headers Secrets Test", + Slug: "secrets-test-custom-headers", + Transport: "streamable_http", + URL: "https://mcp.example.com/secrets", + AuthType: "custom_headers", + CustomHeaders: map[string]string{"X-Custom": "THIS-IS-A-SECRET-HEADER"}, + Availability: "default_on", + Enabled: true, + }, + } + created := make([]codersdk.MCPServerConfig, 0, len(requests)) + for _, req := range requests { + config, err := adminClient.CreateMCPServerConfig(ctx, firstUser.OrganizationID, req) + require.NoError(t, err) + created = append(created, config) + } // The sentinel values we must never see in any JSON response. secrets := []string{ @@ -1132,32 +1190,29 @@ func TestMCPServerConfigsSecretsNeverLeaked(t *testing.T) { } } - // Verify the create response doesn't leak secrets. - assertNoSecrets(t, "admin create response", created) + // Verify the create responses don't leak secrets. + for _, config := range created { + assertNoSecrets(t, "admin create response", config) + } // Verify boolean indicators are set correctly. - require.True(t, created.HasOAuth2Secret, "HasOAuth2Secret should be true") - require.Equal(t, "https://mcp.example.com/secrets", created.OAuth2Resource) - require.True(t, created.HasAPIKey, "HasAPIKey should be true") - require.True(t, created.HasCustomHeaders, "HasCustomHeaders should be true") + require.True(t, created[0].HasOAuth2Secret, "HasOAuth2Secret should be true") + require.Equal(t, "https://mcp.example.com/secrets", created[0].OAuth2Resource) + require.True(t, created[1].HasAPIKey, "HasAPIKey should be true") + require.True(t, created[2].HasCustomHeaders, "HasCustomHeaders should be true") // Admin list endpoint. adminConfigs, err := adminClient.MCPServerConfigs(ctx, firstUser.OrganizationID) require.NoError(t, err) - require.NotEmpty(t, adminConfigs) + require.Len(t, adminConfigs, len(created)) for _, cfg := range adminConfigs { assertNoSecrets(t, "admin list", cfg) } - // Admin get-by-ID endpoint. - adminSingle, err := adminClient.MCPServerConfigByID(ctx, created.OrganizationID, created.ID) - require.NoError(t, err) - assertNoSecrets(t, "admin get-by-id", adminSingle) - // Non-admin list endpoint. memberConfigs, err := memberClient.MCPServerConfigs(ctx, firstUser.OrganizationID) require.NoError(t, err) - require.NotEmpty(t, memberConfigs) + require.Len(t, memberConfigs, len(created)) for _, cfg := range memberConfigs { assertNoSecrets(t, "member list", cfg) // Non-admin should also not see admin-only fields. @@ -1172,18 +1227,25 @@ func TestMCPServerConfigsSecretsNeverLeaked(t *testing.T) { assert.Empty(t, cfg.Transport, "member should not see Transport") } - // Non-admin get-by-ID endpoint. - memberSingle, err := memberClient.MCPServerConfigByID(ctx, created.OrganizationID, created.ID) - require.NoError(t, err) - assertNoSecrets(t, "member get-by-id", memberSingle) - assert.Empty(t, memberSingle.OAuth2ClientID, "member should not see OAuth2ClientID") - assert.Empty(t, memberSingle.OAuth2AuthURL, "member should not see OAuth2AuthURL") - assert.Empty(t, memberSingle.OAuth2TokenURL, "member should not see OAuth2TokenURL") - assert.Empty(t, memberSingle.OAuth2Scopes, "member should not see OAuth2Scopes") - assert.Empty(t, memberSingle.OAuth2Resource, "member should not see OAuth2Resource") - assert.Empty(t, memberSingle.APIKeyHeader, "member should not see APIKeyHeader") - assert.Empty(t, memberSingle.URL, "member should not see URL") - assert.Empty(t, memberSingle.Transport, "member should not see Transport") + for _, config := range created { + // Admin get-by-ID endpoint. + adminSingle, err := adminClient.MCPServerConfigByID(ctx, config.OrganizationID, config.ID) + require.NoError(t, err) + assertNoSecrets(t, "admin get-by-id", adminSingle) + + // Non-admin get-by-ID endpoint. + memberSingle, err := memberClient.MCPServerConfigByID(ctx, config.OrganizationID, config.ID) + require.NoError(t, err) + assertNoSecrets(t, "member get-by-id", memberSingle) + assert.Empty(t, memberSingle.OAuth2ClientID, "member should not see OAuth2ClientID") + assert.Empty(t, memberSingle.OAuth2AuthURL, "member should not see OAuth2AuthURL") + assert.Empty(t, memberSingle.OAuth2TokenURL, "member should not see OAuth2TokenURL") + assert.Empty(t, memberSingle.OAuth2Scopes, "member should not see OAuth2Scopes") + assert.Empty(t, memberSingle.OAuth2Resource, "member should not see OAuth2Resource") + assert.Empty(t, memberSingle.APIKeyHeader, "member should not see APIKeyHeader") + assert.Empty(t, memberSingle.URL, "member should not see URL") + assert.Empty(t, memberSingle.Transport, "member should not see Transport") + } } func TestMCPServerConfigsAuthConnected(t *testing.T) { @@ -1974,6 +2036,16 @@ func TestMCPServerConfigsUserOIDCRequiresDeploymentPerms(t *testing.T) { require.ErrorAs(t, err, &sdkErr) require.Equal(t, http.StatusForbidden, sdkErr.StatusCode()) + // The denied update must not register a client at the provider. + discovery := newMCPDiscoveryServer(t, nil) + _, err = orgAdminClient.UpdateMCPServerConfig(ctx, deploymentOwned.OrganizationID, deploymentOwned.ID, codersdk.UpdateMCPServerConfigRequest{ + URL: &discovery.url, + AuthType: ptr.Ref("oauth2"), + }) + require.ErrorAs(t, err, &sdkErr) + require.Equal(t, http.StatusForbidden, sdkErr.StatusCode()) + require.Empty(t, discovery.registrations()) + updatedURL := "https://mcp.example.com/deployment-oidc-v2" updated, err := adminClient.UpdateMCPServerConfig(ctx, deploymentOwned.OrganizationID, deploymentOwned.ID, codersdk.UpdateMCPServerConfigRequest{ URL: &updatedURL, @@ -2578,18 +2650,19 @@ func TestMCPServerConfigsOAuth2AutoDiscovery(t *testing.T) { require.Equal(t, "https://override.example.com/mcp", overridden.OAuth2Resource) // Resending the registered client ID keeps the client dynamic, and - // replacing it makes the client manual. + // replacing it requires manual registration. updated, err := client.UpdateMCPServerConfig(ctx, overridden.OrganizationID, overridden.ID, codersdk.UpdateMCPServerConfigRequest{ OAuth2ClientID: &overridden.OAuth2ClientID, }) require.NoError(t, err) require.Equal(t, codersdk.MCPServerOAuth2ClientRegistrationDynamic, updated.OAuth2ClientRegistration) replacedClientID := "replaced-client-id" - updated, err = client.UpdateMCPServerConfig(ctx, overridden.OrganizationID, overridden.ID, codersdk.UpdateMCPServerConfigRequest{ + _, err = client.UpdateMCPServerConfig(ctx, overridden.OrganizationID, overridden.ID, codersdk.UpdateMCPServerConfigRequest{ OAuth2ClientID: &replacedClientID, }) - require.NoError(t, err) - require.Equal(t, codersdk.MCPServerOAuth2ClientRegistrationManual, updated.OAuth2ClientRegistration) + var sdkErr *codersdk.Error + require.ErrorAs(t, err, &sdkErr) + require.Equal(t, http.StatusBadRequest, sdkErr.StatusCode()) // Leaving oauth2 resets the registration method with the other // OAuth2 fields. @@ -2620,20 +2693,20 @@ func TestMCPServerConfigsOAuth2AutoDiscovery(t *testing.T) { }) scopedClient := codersdk.New(client.URL) scopedClient.SetSessionToken(token) - var registrationRequests atomic.Int64 + discovery := newMCPDiscoveryServer(t, nil) created, err := scopedClient.CreateMCPServerConfig(ctx, firstUser.OrganizationID, codersdk.CreateMCPServerConfigRequest{ DisplayName: "Create Only Discovery", Slug: "create-only-discovery", Transport: "streamable_http", - URL: newMCPDiscoveryServer(t, ®istrationRequests), + URL: discovery.url, AuthType: "oauth2", Availability: "default_on", Enabled: true, }) require.NoError(t, err) require.Equal(t, "discovered-client-id", created.OAuth2ClientID) - require.EqualValues(t, 1, registrationRequests.Load()) + require.Len(t, discovery.registrations(), 1) }) t.Run("ExistingSlugSkipsRegistration", func(t *testing.T) { @@ -2643,13 +2716,13 @@ func TestMCPServerConfigsOAuth2AutoDiscovery(t *testing.T) { client := newMCPClient(t) firstUser := coderdtest.CreateFirstUser(t, client) createMCPServerConfig(t, client, firstUser.OrganizationID, "discovery-conflict", true) - var registrationRequests atomic.Int64 + discovery := newMCPDiscoveryServer(t, nil) _, err := client.CreateMCPServerConfig(ctx, firstUser.OrganizationID, codersdk.CreateMCPServerConfigRequest{ DisplayName: "Discovery Conflict", Slug: " discovery-conflict ", Transport: "streamable_http", - URL: newMCPDiscoveryServer(t, ®istrationRequests), + URL: discovery.url, AuthType: "oauth2", Availability: "default_on", Enabled: true, @@ -2658,7 +2731,7 @@ func TestMCPServerConfigsOAuth2AutoDiscovery(t *testing.T) { require.ErrorAs(t, err, &sdkErr) require.Equal(t, http.StatusConflict, sdkErr.StatusCode()) require.Equal(t, "MCP server config already exists.", sdkErr.Message) - require.Zero(t, registrationRequests.Load()) + require.Empty(t, discovery.registrations()) }) t.Run("PathAwareTakesPriority", func(t *testing.T) { @@ -3168,6 +3241,159 @@ func TestMCPServerConfigsOAuth2AutoDiscovery(t *testing.T) { // for an internal-only service (e.g. cloud metadata) and must never // be reached, while the attacker's MCP server on 127.0.0.1 is // reachable via the test allowlist. +func TestMCPServerConfigsUpdateOAuth2Registration(t *testing.T) { + t.Parallel() + + callbackURL := func(client *codersdk.Client, configID uuid.UUID) string { + return client.URL.String() + "/api/experimental/mcp/servers/" + configID.String() + "/oauth2/callback" + } + + t.Run("NoneToOAuth2Registers", func(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + client := newMCPClient(t) + firstUser := coderdtest.CreateFirstUser(t, client) + discovery := newMCPDiscoveryServer(t, nil) + config := createMCPServerConfig(t, client, firstUser.OrganizationID, "none-to-oauth2", true) + + updated, err := client.UpdateMCPServerConfig(ctx, firstUser.OrganizationID, config.ID, codersdk.UpdateMCPServerConfigRequest{ + URL: &discovery.url, + AuthType: ptr.Ref("oauth2"), + }) + require.NoError(t, err) + require.Equal(t, codersdk.MCPServerOAuth2ClientRegistrationDynamic, updated.OAuth2ClientRegistration) + require.Equal(t, "discovered-client-id", updated.OAuth2ClientID) + require.True(t, updated.HasOAuth2Secret) + require.Equal(t, discovery.authURL+"/authorize", updated.OAuth2AuthURL) + require.Equal(t, discovery.authURL+"/token", updated.OAuth2TokenURL) + require.Equal(t, discovery.url, updated.OAuth2Resource) + require.Equal(t, [][]string{{callbackURL(client, config.ID)}}, discovery.registrations()) + }) + + t.Run("DynamicURLChangeRegistersAgain", func(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + client := newMCPClient(t) + firstUser := coderdtest.CreateFirstUser(t, client) + first := newMCPDiscoveryServer(t, nil) + second := newMCPDiscoveryServer(t, nil) + created, err := client.CreateMCPServerConfig(ctx, firstUser.OrganizationID, codersdk.CreateMCPServerConfigRequest{ + DisplayName: "URL Change", + Slug: "url-change", + Transport: "streamable_http", + URL: first.url, + AuthType: "oauth2", + Availability: "default_on", + Enabled: true, + }) + require.NoError(t, err) + require.Equal(t, first.url, created.OAuth2Resource) + + // Like the form, repeat the stored client ID and resource. The + // repeated resource is not an override, so the new server's + // resource replaces it. + updated, err := client.UpdateMCPServerConfig(ctx, firstUser.OrganizationID, created.ID, codersdk.UpdateMCPServerConfigRequest{ + URL: &second.url, + OAuth2ClientID: &created.OAuth2ClientID, + OAuth2Resource: &created.OAuth2Resource, + }) + require.NoError(t, err) + require.Equal(t, second.authURL+"/authorize", updated.OAuth2AuthURL) + require.Equal(t, second.authURL+"/token", updated.OAuth2TokenURL) + require.Equal(t, second.url, updated.OAuth2Resource) + require.Len(t, first.registrations(), 1) + require.Equal(t, [][]string{{callbackURL(client, created.ID)}}, second.registrations()) + }) + + t.Run("RegistrationFailureKeepsConfig", func(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + client := newMCPClient(t) + firstUser := coderdtest.CreateFirstUser(t, client) + config := createMCPServerConfig(t, client, firstUser.OrganizationID, "registration-failure", true) + + // Discovery fails immediately: nothing listens on the URL. + _, err := client.UpdateMCPServerConfig(ctx, firstUser.OrganizationID, config.ID, codersdk.UpdateMCPServerConfigRequest{ + URL: ptr.Ref("http://127.0.0.1:1"), + AuthType: ptr.Ref("oauth2"), + }) + var sdkErr *codersdk.Error + require.ErrorAs(t, err, &sdkErr) + require.Equal(t, http.StatusBadRequest, sdkErr.StatusCode()) + require.Contains(t, sdkErr.Message, "auto-discovery failed") + + got, err := client.MCPServerConfigByID(ctx, firstUser.OrganizationID, config.ID) + require.NoError(t, err) + require.Equal(t, "none", got.AuthType) + require.Equal(t, config.URL, got.URL) + }) + + t.Run("ConfigChangedDuringRegistration", func(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + registrationStarted := make(chan struct{}) + completeRegistration := make(chan struct{}) + var blockRegistration sync.Once + var completeRegistrationOnce sync.Once + releaseRegistration := func() { + completeRegistrationOnce.Do(func() { + close(completeRegistration) + }) + } + discovery := newMCPDiscoveryServer(t, func() { + blockRegistration.Do(func() { + close(registrationStarted) + <-completeRegistration + }) + }) + t.Cleanup(releaseRegistration) + + client := newMCPClient(t) + firstUser := coderdtest.CreateFirstUser(t, client) + config, err := client.CreateMCPServerConfig(ctx, firstUser.OrganizationID, codersdk.CreateMCPServerConfigRequest{ + DisplayName: "Registration Race", + Slug: "registration-race", + Transport: "streamable_http", + URL: discovery.url, + AuthType: "none", + Availability: "default_on", + Enabled: true, + }) + require.NoError(t, err) + + updateErr := make(chan error, 1) + testutil.Go(t, func() { + _, err := client.UpdateMCPServerConfig(ctx, firstUser.OrganizationID, config.ID, codersdk.UpdateMCPServerConfigRequest{ + AuthType: ptr.Ref("oauth2"), + }) + updateErr <- err + }) + testutil.TryReceive(ctx, t, registrationStarted) + + // The URL changes while the registration for the old URL runs. + otherURL := "https://mcp.example.com/other" + _, err = client.UpdateMCPServerConfig(ctx, firstUser.OrganizationID, config.ID, codersdk.UpdateMCPServerConfigRequest{ + URL: &otherURL, + }) + require.NoError(t, err) + releaseRegistration() + + err = testutil.RequireReceive(ctx, t, updateErr) + var sdkErr *codersdk.Error + require.ErrorAs(t, err, &sdkErr) + require.Equal(t, http.StatusConflict, sdkErr.StatusCode()) + + got, err := client.MCPServerConfigByID(ctx, firstUser.OrganizationID, config.ID) + require.NoError(t, err) + require.Equal(t, "none", got.AuthType) + require.Equal(t, otherURL, got.URL) + }) +} + func TestMCPServerConfigsOAuth2AutoDiscoverySSRF(t *testing.T) { t.Parallel() diff --git a/codersdk/mcp.go b/codersdk/mcp.go index a5cce14945d..4072e0957e6 100644 --- a/codersdk/mcp.go +++ b/codersdk/mcp.go @@ -186,6 +186,13 @@ type CreateMCPServerConfigRequest struct { APIKeyHeader string `json:"api_key_header,omitempty"` APIKeyValue string `json:"api_key_value,omitempty"` CustomHeaders map[string]string `json:"custom_headers,omitempty"` + // OAuth2ClientRegistration selects how Coder gets the OAuth2 client. + // With "dynamic", Coder discovers the authorization server of URL and + // registers a client (RFC 7591), so the client ID, client secret, auth + // URL, and token URL must be empty. With "manual", the client ID, auth + // URL, and token URL are required. When empty, Coder uses "dynamic" if + // those three fields are empty, and "manual" otherwise. + OAuth2ClientRegistration MCPServerOAuth2ClientRegistration `json:"oauth2_client_registration,omitempty" validate:"omitempty,oneof=manual dynamic"` ToolAllowList []string `json:"tool_allow_list,omitempty"` ToolDenyList []string `json:"tool_deny_list,omitempty"` @@ -228,6 +235,16 @@ type UpdateMCPServerConfigRequest struct { APIKeyHeader *string `json:"api_key_header,omitempty"` APIKeyValue *string `json:"api_key_value,omitempty"` CustomHeaders *map[string]string `json:"custom_headers,omitempty"` + // OAuth2ClientRegistration changes how Coder gets the OAuth2 client. + // When a request that sets the URL or an auth field omits it, Coder + // uses "dynamic" if the resulting config has no client ID, auth URL, + // and token URL, and keeps the stored value otherwise. Coder registers + // a new client when the config becomes "dynamic" or when the URL of a + // "dynamic" config changes. A new client deletes the stored user + // tokens. A "dynamic" config ignores empty and unchanged values for + // the client ID, client secret, auth URL, and token URL. Other values + // fail unless the request also sets "manual". + OAuth2ClientRegistration *MCPServerOAuth2ClientRegistration `json:"oauth2_client_registration,omitempty" validate:"omitempty,oneof=manual dynamic"` ToolAllowList *[]string `json:"tool_allow_list,omitempty"` ToolDenyList *[]string `json:"tool_deny_list,omitempty"` diff --git a/docs/ai-coder/agents/platform-controls/mcp-servers.md b/docs/ai-coder/agents/platform-controls/mcp-servers.md index b1f30abcde9..6ff148ffb82 100644 --- a/docs/ai-coder/agents/platform-controls/mcp-servers.md +++ b/docs/ai-coder/agents/platform-controls/mcp-servers.md @@ -54,7 +54,7 @@ The add and update views always show the target organization, as a read-only fie ## Authentication Each MCP server uses one of five authentication modes. -When you change the auth type, fields from the previous type are automatically cleared. +When you create a server or change its auth type, Coder clears the fields that the selected type doesn't use. OAuth2 client secrets, API keys, and custom headers are never returned in API responses. Boolean flags indicate whether each value is set. @@ -67,9 +67,19 @@ Use this for servers that do not require authentication. ### OAuth2 Per-user authorization. -The administrator configures the OAuth2 provider, and each user independently completes the authorization flow. +The administrator configures the OAuth2 client, and each user independently completes the authorization flow. -**Manual configuration** — provide all three fields together: +The `oauth2_client_registration` field sets how Coder gets the OAuth2 client: + +| Value | Description | +|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------| +| `dynamic` | Coder discovers the provider and registers a client for the MCP server URL. Coder sets the client ID, client secret, authorization URL, and token URL. | +| `manual` | You register a client with the provider and enter its details. | + +When a request sets the server URL or an authentication field but omits `oauth2_client_registration`, Coder uses `dynamic` if `oauth2_client_id`, `oauth2_auth_url`, and `oauth2_token_url` are all empty. +Otherwise, Coder keeps the current value, or uses `manual` for a new server. + +**Manual registration**: provide all three fields together: | Field | Description | |--------------------|-----------------------------| @@ -94,23 +104,46 @@ The value must be an absolute URI without a fragment or user information. A manual configuration sends no `resource` parameter unless you set this field. Leave it empty for providers that reject the parameter, such as Microsoft Entra ID. -**Auto-discovery**: -leave `oauth2_client_id`, `oauth2_auth_url`, and `oauth2_token_url` empty. -The server attempts discovery in this order: +**Dynamic registration**: +Coder discovers the provider and registers a client in this order: -1. RFC 9728 — Protected Resource Metadata -1. RFC 8414 — Authorization Server Metadata -1. RFC 7591 — Dynamic Client Registration +1. RFC 9728: Protected Resource Metadata +1. RFC 8414: Authorization Server Metadata +1. RFC 7591: Dynamic Client Registration -Auto-discovery also records the provider's `revocation_endpoint` from the RFC 8414 metadata when advertised, and sets `oauth2_resource` to the Protected Resource Metadata `resource` that matches the MCP server URL. +Discovery sets `oauth2_scopes` to the `scopes_supported` of the RFC 8414 metadata, and records its `revocation_endpoint` when the metadata advertises one. +It sets `oauth2_resource` to the Protected Resource Metadata `resource` that matches the MCP server URL. When none matches, it uses the server URL with the scheme and host lowercased and any user information or fragment removed. -Explicit `oauth2_revocation_url` and `oauth2_resource` values in the request take precedence over the discovered values. -Discovery runs only when a configuration is created, so to add a resource indicator to an existing configuration, set `oauth2_resource` on it or re-create the server. +When a request registers a client, a new, non-empty value for `oauth2_scopes`, `oauth2_revocation_url`, or `oauth2_resource` in the same request overrides the discovered value. +A value that the request repeats unchanged doesn't override it. + +Coder registers a new client when you save a `dynamic` configuration that has no client for its server URL. +Registration happens when you: + +- Create the server. +- Change the auth type to OAuth2. +- Change `oauth2_client_registration` from `manual` to `dynamic`. +- Change the server URL. + +If discovery or registration fails, the request fails and the server doesn't change. +If the server changes while Coder registers the client, the request fails with `409 Conflict`. +Send the request again. +To register a new client for the same server URL, set `oauth2_client_registration` to `manual`, then set it to `dynamic` in a second request. + +Coder owns the client ID, client secret, authorization URL, and token URL of a `dynamic` configuration. +A request can leave these fields empty or repeat their stored values, and Coder ignores them. +A request that sets one of them to another value fails unless it also sets `oauth2_client_registration` to `manual`. +When you change a configuration to `manual`, Coder keeps the registered client. + +Servers whose client Coder registered automatically before the `oauth2_client_registration` field existed have the field set to `manual`. +A change to their server URL keeps their client. +To register a new client, set `oauth2_client_registration` to `dynamic`. Users connect their own accounts in **Agents** > **Settings** > **MCP connections**, through a popup that redirects through the OAuth2 provider. Refer to [Connect to MCP servers](../extending-agents.md#connect-to-mcp-servers) for the steps users follow. Tokens are stored per-user and refreshed automatically. Changing the server URL, authentication type, `oauth2_client_id`, `oauth2_token_url`, `oauth2_revocation_url`, or `oauth2_resource` deletes every user's stored token, so users must connect again. +A new dynamic registration replaces `oauth2_client_id`, so it also deletes every user's stored token. Users can disconnect in **MCP connections** or through the API to remove stored tokens. When a revocation endpoint is configured, disconnecting also asks the provider to revoke the token (RFC 7009). Provider revocation is best-effort: the stored token is always deleted from Coder, and the disconnect response reports whether provider revocation succeeded via `token_revoked` and `token_revocation_error`. diff --git a/docs/reference/api/schemas.md b/docs/reference/api/schemas.md index d7eeabeb5b5..38e2d96a95c 100644 --- a/docs/reference/api/schemas.md +++ b/docs/reference/api/schemas.md @@ -7367,6 +7367,7 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in "model_intent": true, "oauth2_auth_url": "string", "oauth2_client_id": "string", + "oauth2_client_registration": "manual", "oauth2_client_secret": "string", "oauth2_resource": "string", "oauth2_revocation_url": "string", @@ -7387,42 +7388,44 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in ### Properties -| Name | Type | Required | Restrictions | Description | -|-------------------------|-----------------|----------|--------------|----------------------------------------------------------------------------------------------------------------------------------------| -| `allow_in_plan_mode` | boolean | false | | | -| `api_key_header` | string | false | | | -| `api_key_value` | string | false | | | -| `auth_type` | string | true | | | -| `availability` | string | true | | | -| `custom_headers` | object | false | | | -| » `[any property]` | string | false | | | -| `description` | string | false | | | -| `display_name` | string | true | | | -| `enabled` | boolean | false | | | -| `forward_coder_headers` | boolean | false | | Forward coder headers when true, forwards Coder identity headers on every outgoing MCP request. See MCPServerConfig. | -| `icon_url` | string | false | | | -| `model_intent` | boolean | false | | | -| `oauth2_auth_url` | string | false | | | -| `oauth2_client_id` | string | false | | | -| `oauth2_client_secret` | string | false | | | -| `oauth2_resource` | string | false | | Oauth2 resource is the RFC 8707 resource indicator sent on OAuth2 requests when set. Auto-discovery fills it if empty. | -| `oauth2_revocation_url` | string | false | | Oauth2 revocation URL is the provider's RFC 7009 revocation endpoint; auto-populated by OAuth2 discovery when omitted. | -| `oauth2_scopes` | string | false | | | -| `oauth2_token_url` | string | false | | | -| `signing_secret` | string | false | | Signing secret signs forwarded identity headers and request bodies. Configure the same secret on the MCP server. It is never returned. | -| `slug` | string | true | | | -| `tool_allow_list` | array of string | false | | | -| `tool_deny_list` | array of string | false | | | -| `transport` | string | true | | | -| `url` | string | true | | | +| Name | Type | Required | Restrictions | Description | +|------------------------------|------------------------------------------------------------------------------------------|----------|--------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `allow_in_plan_mode` | boolean | false | | | +| `api_key_header` | string | false | | | +| `api_key_value` | string | false | | | +| `auth_type` | string | true | | | +| `availability` | string | true | | | +| `custom_headers` | object | false | | | +| » `[any property]` | string | false | | | +| `description` | string | false | | | +| `display_name` | string | true | | | +| `enabled` | boolean | false | | | +| `forward_coder_headers` | boolean | false | | Forward coder headers when true, forwards Coder identity headers on every outgoing MCP request. See MCPServerConfig. | +| `icon_url` | string | false | | | +| `model_intent` | boolean | false | | | +| `oauth2_auth_url` | string | false | | | +| `oauth2_client_id` | string | false | | | +| `oauth2_client_registration` | [codersdk.MCPServerOAuth2ClientRegistration](#codersdkmcpserveroauth2clientregistration) | false | | Oauth2 client registration selects how Coder gets the OAuth2 client. With "dynamic", Coder discovers the authorization server of URL and registers a client (RFC 7591), so the client ID, client secret, auth URL, and token URL must be empty. With "manual", the client ID, auth URL, and token URL are required. When empty, Coder uses "dynamic" if those three fields are empty, and "manual" otherwise. | +| `oauth2_client_secret` | string | false | | | +| `oauth2_resource` | string | false | | Oauth2 resource is the RFC 8707 resource indicator sent on OAuth2 requests when set. Auto-discovery fills it if empty. | +| `oauth2_revocation_url` | string | false | | Oauth2 revocation URL is the provider's RFC 7009 revocation endpoint; auto-populated by OAuth2 discovery when omitted. | +| `oauth2_scopes` | string | false | | | +| `oauth2_token_url` | string | false | | | +| `signing_secret` | string | false | | Signing secret signs forwarded identity headers and request bodies. Configure the same secret on the MCP server. It is never returned. | +| `slug` | string | true | | | +| `tool_allow_list` | array of string | false | | | +| `tool_deny_list` | array of string | false | | | +| `transport` | string | true | | | +| `url` | string | true | | | #### Enumerated Values -| Property | Value(s) | -|----------------|------------------------------------------------------------| -| `auth_type` | `api_key`, `custom_headers`, `none`, `oauth2`, `user_oidc` | -| `availability` | `default_off`, `default_on`, `force_on` | -| `transport` | `sse`, `streamable_http` | +| Property | Value(s) | +|------------------------------|------------------------------------------------------------| +| `auth_type` | `api_key`, `custom_headers`, `none`, `oauth2`, `user_oidc` | +| `availability` | `default_off`, `default_on`, `force_on` | +| `oauth2_client_registration` | `dynamic`, `manual` | +| `transport` | `sse`, `streamable_http` | ## codersdk.CreateOrganizationRequest @@ -17543,6 +17546,7 @@ The cursor is owner-scoped, so only the chat owner may set this. Opening a chat' "model_intent": true, "oauth2_auth_url": "string", "oauth2_client_id": "string", + "oauth2_client_registration": "manual", "oauth2_client_secret": "string", "oauth2_resource": "string", "oauth2_revocation_url": "string", @@ -17563,42 +17567,44 @@ The cursor is owner-scoped, so only the chat owner may set this. Opening a chat' ### Properties -| Name | Type | Required | Restrictions | Description | -|-------------------------|-----------------|----------|--------------|-------------------------------------------------------------------------------------------------------------------------| -| `allow_in_plan_mode` | boolean | false | | | -| `api_key_header` | string | false | | | -| `api_key_value` | string | false | | | -| `auth_type` | string | false | | | -| `availability` | string | false | | | -| `custom_headers` | object | false | | | -| » `[any property]` | string | false | | | -| `description` | string | false | | | -| `display_name` | string | false | | | -| `enabled` | boolean | false | | | -| `forward_coder_headers` | boolean | false | | Forward coder headers when set, updates whether Coder identity headers are forwarded on every outgoing MCP request. | -| `icon_url` | string | false | | | -| `model_intent` | boolean | false | | | -| `oauth2_auth_url` | string | false | | | -| `oauth2_client_id` | string | false | | | -| `oauth2_client_secret` | string | false | | | -| `oauth2_resource` | string | false | | Oauth2 resource is the RFC 8707 resource indicator. Omit it to keep the stored value; send "" to clear it. | -| `oauth2_revocation_url` | string | false | | Oauth2 revocation URL is validated in the handler because a validate tag would reject the pointer to "" that clears it. | -| `oauth2_scopes` | string | false | | | -| `oauth2_token_url` | string | false | | | -| `signing_secret` | string | false | | Signing secret replaces the shared signing key. Omit to preserve it; an empty string clears it. It is never returned. | -| `slug` | string | false | | | -| `tool_allow_list` | array of string | false | | | -| `tool_deny_list` | array of string | false | | | -| `transport` | string | false | | | -| `url` | string | false | | | +| Name | Type | Required | Restrictions | Description | +|------------------------------|------------------------------------------------------------------------------------------|----------|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `allow_in_plan_mode` | boolean | false | | | +| `api_key_header` | string | false | | | +| `api_key_value` | string | false | | | +| `auth_type` | string | false | | | +| `availability` | string | false | | | +| `custom_headers` | object | false | | | +| » `[any property]` | string | false | | | +| `description` | string | false | | | +| `display_name` | string | false | | | +| `enabled` | boolean | false | | | +| `forward_coder_headers` | boolean | false | | Forward coder headers when set, updates whether Coder identity headers are forwarded on every outgoing MCP request. | +| `icon_url` | string | false | | | +| `model_intent` | boolean | false | | | +| `oauth2_auth_url` | string | false | | | +| `oauth2_client_id` | string | false | | | +| `oauth2_client_registration` | [codersdk.MCPServerOAuth2ClientRegistration](#codersdkmcpserveroauth2clientregistration) | false | | Oauth2 client registration changes how Coder gets the OAuth2 client. When a request that sets the URL or an auth field omits it, Coder uses "dynamic" if the resulting config has no client ID, auth URL, and token URL, and keeps the stored value otherwise. Coder registers a new client when the config becomes "dynamic" or when the URL of a "dynamic" config changes. A new client deletes the stored user tokens. A "dynamic" config ignores empty and unchanged values for the client ID, client secret, auth URL, and token URL. Other values fail unless the request also sets "manual". | +| `oauth2_client_secret` | string | false | | | +| `oauth2_resource` | string | false | | Oauth2 resource is the RFC 8707 resource indicator. Omit it to keep the stored value; send "" to clear it. | +| `oauth2_revocation_url` | string | false | | Oauth2 revocation URL is validated in the handler because a validate tag would reject the pointer to "" that clears it. | +| `oauth2_scopes` | string | false | | | +| `oauth2_token_url` | string | false | | | +| `signing_secret` | string | false | | Signing secret replaces the shared signing key. Omit to preserve it; an empty string clears it. It is never returned. | +| `slug` | string | false | | | +| `tool_allow_list` | array of string | false | | | +| `tool_deny_list` | array of string | false | | | +| `transport` | string | false | | | +| `url` | string | false | | | #### Enumerated Values -| Property | Value(s) | -|----------------|------------------------------------------------------------| -| `auth_type` | `api_key`, `custom_headers`, `none`, `oauth2`, `user_oidc` | -| `availability` | `default_off`, `default_on`, `force_on` | -| `transport` | `sse`, `streamable_http` | +| Property | Value(s) | +|------------------------------|------------------------------------------------------------| +| `auth_type` | `api_key`, `custom_headers`, `none`, `oauth2`, `user_oidc` | +| `availability` | `default_off`, `default_on`, `force_on` | +| `oauth2_client_registration` | `dynamic`, `manual` | +| `transport` | `sse`, `streamable_http` | ## codersdk.UpdateOrganizationChatSystemPromptRequest diff --git a/site/src/api/typesGenerated.ts b/site/src/api/typesGenerated.ts index eddff3d824b..b6d6a1412f4 100644 --- a/site/src/api/typesGenerated.ts +++ b/site/src/api/typesGenerated.ts @@ -4570,6 +4570,15 @@ export interface CreateMCPServerConfigRequest { readonly api_key_header?: string; readonly api_key_value?: string; readonly custom_headers?: Record; + /** + * OAuth2ClientRegistration selects how Coder gets the OAuth2 client. + * With "dynamic", Coder discovers the authorization server of URL and + * registers a client (RFC 7591), so the client ID, client secret, auth + * URL, and token URL must be empty. With "manual", the client ID, auth + * URL, and token URL are required. When empty, Coder uses "dynamic" if + * those three fields are empty, and "manual" otherwise. + */ + readonly oauth2_client_registration?: MCPServerOAuth2ClientRegistration; readonly tool_allow_list?: readonly string[]; readonly tool_deny_list?: readonly string[]; readonly availability: string; @@ -11162,6 +11171,18 @@ export interface UpdateMCPServerConfigRequest { readonly api_key_header?: string; readonly api_key_value?: string; readonly custom_headers?: Record; + /** + * OAuth2ClientRegistration changes how Coder gets the OAuth2 client. + * When a request that sets the URL or an auth field omits it, Coder + * uses "dynamic" if the resulting config has no client ID, auth URL, + * and token URL, and keeps the stored value otherwise. Coder registers + * a new client when the config becomes "dynamic" or when the URL of a + * "dynamic" config changes. A new client deletes the stored user + * tokens. A "dynamic" config ignores empty and unchanged values for + * the client ID, client secret, auth URL, and token URL. Other values + * fail unless the request also sets "manual". + */ + readonly oauth2_client_registration?: MCPServerOAuth2ClientRegistration; readonly tool_allow_list?: string[]; readonly tool_deny_list?: string[]; readonly availability?: string;