Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(mcp): name what MCP cannot do in search_api (#21864)
Vincent Huang3264d8a11c35
diff --git a/backend/api/auth/auth.go b/backend/api/auth/auth.goindex cd7e11c1be..6d40d6c864 100644--- a/backend/api/auth/auth.go+++ b/backend/api/auth/auth.go@@ -534,36 +534,52 @@ func MCPClassIsRefused(class v1pb.MCPMethodClass) bool {// enforcement path must not — it reads the class off the AuthContext, which// fails the request outright when the annotation cannot be resolved.func MCPMethodClassOfProcedure(procedure string) (v1pb.MCPMethodClass, error) {+ class, _, err := MCPAnnotationsOfProcedure(procedure)+ return class, err+}++// MCPAnnotationsOfProcedure resolves both MCP annotations of a procedure, its+// class and its recorded denial reason, under the same caveat as+// MCPMethodClassOfProcedure.+func MCPAnnotationsOfProcedure(procedure string) (v1pb.MCPMethodClass, v1pb.MCPDenialReason, error) {+ unresolved := func(err error) (v1pb.MCPMethodClass, v1pb.MCPDenialReason, error) {+ return v1pb.MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED, v1pb.MCPDenialReason_MCP_DENIAL_REASON_UNSPECIFIED, err+ }tokens := strings.Split(procedure, "/")if len(tokens) != 3 {- return v1pb.MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED, errs.Errorf("invalid procedure name %q", procedure)+ return unresolved(errs.Errorf("invalid procedure name %q", procedure))}rd, err := protoregistry.GlobalFiles.FindDescriptorByName(protoreflect.FullName(tokens[1]))if err != nil {- return v1pb.MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED, errs.Wrapf(err, "invalid service descriptor for procedure %q", procedure)+ return unresolved(errs.Wrapf(err, "invalid service descriptor for procedure %q", procedure))}sd, ok := rd.(protoreflect.ServiceDescriptor)if !ok {- return v1pb.MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED, errs.Errorf("invalid service descriptor for procedure %q", procedure)+ return unresolved(errs.Errorf("invalid service descriptor for procedure %q", procedure))}method := sd.Methods().ByName(protoreflect.Name(tokens[2]))if method == nil {- return v1pb.MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED, errs.Errorf("unknown method for procedure %q", procedure)+ return unresolved(errs.Errorf("unknown method for procedure %q", procedure))}md, ok := method.Options().(*descriptorpb.MethodOptions)if !ok {- return v1pb.MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED, errs.Errorf("invalid method options for procedure %q", procedure)+ return unresolved(errs.Errorf("invalid method options for procedure %q", procedure))}class, ok := proto.GetExtension(md, v1pb.E_McpMethodClass).(v1pb.MCPMethodClass)if !ok {- return v1pb.MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED, errs.Errorf("invalid MCP method class extension for procedure %q", procedure)+ return unresolved(errs.Errorf("invalid MCP method class extension for procedure %q", procedure))}- return class, nil+ reason, ok := proto.GetExtension(md, v1pb.E_McpDenialReason).(v1pb.MCPDenialReason)+ if !ok {+ return unresolved(errs.Errorf("invalid MCP denial reason extension for procedure %q", procedure))+ }+ return class, reason, nil}// mcpReadableSettings are the settings an MCP session may read through// SettingService/GetSetting, which is READ for these alone: the MCP gate refuses-// every other name.+// every other name, and MCP discovery names these. It lives here, like+// MCPClassIsRefused, so the two cannot disagree.//// A setting joins only when its read returns nothing an agent must not hold.// SEMANTIC_TYPES qualifies because GetSetting strips the MD5 masking salt for MCP@@ -575,10 +591,14 @@ var mcpReadableSettings = []v1pb.Setting_SettingName{v1pb.Setting_DATA_CLASSIFICATION,}-// MCPReadableSettings returns the settings an MCP session may read, in a fixed-// order.-func MCPReadableSettings() []v1pb.Setting_SettingName {- return slices.Clone(mcpReadableSettings)+// MCPReadableSettingNames returns the settings an MCP session may read as+// resource names, such as "settings/ENVIRONMENT", in a fixed order.+func MCPReadableSettingNames() []string {+ names := make([]string, 0, len(mcpReadableSettings))+ for _, setting := range mcpReadableSettings {+ names = append(names, common.SettingNamePrefix+setting.String())+ }+ return names}// MCPCanReadSetting reports whether an MCP session may read the setting.diff --git a/backend/api/auth/mcp_denial.go b/backend/api/auth/mcp_denial.gonew file mode 100644index 0000000000..f4ecedf38a--- /dev/null+++ b/backend/api/auth/mcp_denial.go@@ -0,0 +1,198 @@+package auth++import (+ "maps"++ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++// MCPDenialWording is one reason's sentence plus the class it belongs to. The+// class is carried here because a reason implies one — a mechanism that breaks+// the MCP boundary is what FORBIDDEN means, a scope decision is what EXCLUDED+// means — and one table saying so is what lets the lint check the pairing and+// the gate refuse to print the wrong half of it.+type MCPDenialWording struct {+ Class v1pb.MCPMethodClass+ Sentence string+}++// mcpDenialReasons is UX copy, NOT the classification and NOT the mapping.+// Both of those live on the RPC itself, as the bytebase.v1.mcp_method_class and+// bytebase.v1.mcp_denial_reason annotations, beside permission / audit /+// auth_method — one source of truth, visible where the RPC is defined. The gate+// reads them off the AuthContext the auth interceptor resolves, and MCP+// discovery reads them off the same descriptors; the table lives here, like+// MCPClassIsRefused, so both give the same reason. It only turns a reason into a+// sentence the agent can act on, so it has one row per mechanism rather than+// one per method, and a missing row costs wording, never enforcement.+//+// Each sentence completes "<procedure> is not available to MCP sessions because+// ___", so it states what the method does rather than merely that it is+// refused: a denial whose stated reason has drifted from the mechanism is worse+// than a bare refusal, because it is the thing the next reader trusts.+var mcpDenialReasons = map[v1pb.MCPDenialReason]MCPDenialWording{+ // The method hands a token back to the caller. For a non-web caller — and+ // an MCP session is always one — finalizeLogin and switchWorkspaceInternal+ // put a plain bb.user.access token in the response body. That token is not+ // audience-bound to the MCP resource, survives revocation of the OAuth+ // grant, and ignores the workspace MCP kill switch, so obtaining one ends+ // the MCP boundary for good.+ v1pb.MCPDenialReason_MINTS_CREDENTIAL: {v1pb.MCPMethodClass_FORBIDDEN, "it hands back a login token that would outlive the MCP grant"},++ // The method drives the out-of-band reset flow — mailing a reset or login+ // code, or consuming one — that sets or delivers the very secret Login+ // accepts. Denying Login alone would leave the agent holding the credential+ // for the next human login.+ v1pb.MCPDenialReason_RESETS_CREDENTIAL: {v1pb.MCPMethodClass_FORBIDDEN, "it drives the credential-reset flow that sets or delivers the secret a login accepts"},++ // UpdateUser's password and MFA branches take no proof of the old password.+ // A caller updating itself needs no permission at all, and on self-hosted a+ // caller holding bb.users.update reaches any other end user's password too+ // (user_service.go: the caller != subject branch checks that permission and+ // nothing further). Either way the session ends up holding credentials it+ // can log in with. The whole method is refused, not just those branches —+ // the classification is per method.+ v1pb.MCPDenialReason_TAKES_OVER_ACCOUNT: {v1pb.MCPMethodClass_FORBIDDEN, "it can rewrite an account's credentials, which would let the session take that account over"},++ // Logout deletes the web refresh token and expires the session cookies. It+ // mints nothing; it destroys the human's own login session, which an agent+ // acting on their behalf has no business doing.+ v1pb.MCPDenialReason_ENDS_SESSION: {v1pb.MCPMethodClass_FORBIDDEN, "it ends the human's own login session"},++ // The workspace-lifecycle pair. Both end in+ // AuthService.switchWorkspaceInternal, which mints a plain workspace token+ // whenever the caller has no refresh cookie — and an MCP session never has+ // one — after having already destroyed the caller's membership.+ v1pb.MCPDenialReason_ENDS_MEMBERSHIP: {v1pb.MCPMethodClass_FORBIDDEN, "it destroys the caller's own workspace membership and mints a plain workspace token"},++ // The method leaves someone holding a principal the caller is not. Four+ // ways, all of them annotated:+ // - issuing the credential outright — a service key or SCIM token+ // returned in plaintext, a caller-chosen password on a new account;+ // - carrying an existing one out — a stored client secret or SMTP+ // password sent to a host the caller named;+ // - choosing what will later be trusted to mint one — the issuer and+ // subject ExchangeToken validates against;+ // - redirecting where one gets delivered — UpdateEmail rebinds any+ // account to an address the caller picked, and the reset flow mails the+ // code to whatever address the account then carries.+ // The levers that contain a runaway session all act on the caller's own+ // principal: revoke the OAuth grant, flip the workspace MCP switch,+ // deactivate the human. None of them reaches a principal that was never the+ // caller's, so what these give away outlives all three.+ //+ // InstanceService/UpdateDataSource is the same "carry an existing one out"+ // shape as the two Test methods, against the database's credentials rather+ // than Bytebase's own: it merges a partial request onto the STORED,+ // already-decrypted data source, so an update_mask naming only a+ // destination field (host, port, ssh_host, additional_addresses,+ // sasl_config.kdc_host) keeps the stored password, ssl_key and+ // ssh_private_key. With validate_only it dials the caller's host+ // immediately and persists nothing; without it the retarget is written and+ // SyncInstance triggers the connection on demand. No allowlist filters the+ // host on either path. A database user is a principal other than the+ // caller, the same way the SMTP account behind TestEmailSetting is.+ //+ // Its siblings are NOT here and the line is severity, not tidiness:+ // UpdateInstance and BatchUpdateInstances rebuild the data-source list+ // wholesale, so every secret is wiped unless resent — except the Kerberos+ // keytab, which retainStoredKeytabs used to inherit by data-source ID.+ // That narrower, persist-only version of the vector is now closed at the+ // retention rule instead of at reachability: a keytab is not inherited to+ // a destination the caller moved (instance_service_converter.go). It costs+ // an agent no instance management, something no one has yet decided it+ // should lose, and it binds human callers too — a Kerberos host edit now+ // asks for the keytab again, on the console as much as on the API.+ // The keytab is the ONLY secret that rule reaches, because it is the only+ // one those two methods inherit. On UpdateDataSource above, every other+ // stored secret still rides an update_mask that names only a destination,+ // which is why that method is refused here rather than fixed there:+ // requiring a password re-supplied on every host edit is a product call.+ // AddDataSource and CreateInstance also dial on validate_only but build+ // the data source entirely from the request, so they carry no stored+ // secret and are not this class. BOT-57.+ //+ // The Undelete* family (user, service account, workload identity) is+ // deliberately NOT in this group, and it is the nearest thing left out, so+ // the reasoning is recorded rather than left to be rediscovered. It+ // restores a principal whose password or key hash survived the soft+ // delete, so an operator's deactivation is undone. It is out because the+ // caller learns and chooses nothing: the credential goes back to whoever+ // already had it, and a second delete takes it away again. Issuing beats+ // re-arming, and this mechanism is about issuing. BOT-54.+ v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS: {v1pb.MCPMethodClass_FORBIDDEN, "it hands someone control of a principal other than the caller, which revoking this session would not take back"},++ // SettingService/UpdateSetting, refused for the boundary it rewrites+ // rather than for any credential it hands out. Three mask paths carry it:+ // value.workspace_profile.mcp_capability IS the MCP ceiling, so a session+ // that reaches it is not bounded by it; value.email.smtp keeps the+ // stored password when the request omits it while accepting a new host,+ // which hands over the relay resolvePreLoginEmailSetting reads to mail+ // password resets and login codes; and value.ai.endpoint does the same to+ // the AI key it never names — the stored api_key survives the mask, and the+ // next AIService/Chat puts it in an auth header to the host just written+ // (ai_service.go). SaaS refuses AI writes outright (setting_service.go), so+ // that third one is a self-hosted vector, and the key it carries out is+ // whatever the operator configured — GEMINI_API_KEY, where it is set, seeds+ // one key into every workspace created after it (getAdditionalWorkspaceSettings).+ // TestEmailSetting is the one-shot version of the second; this is the+ // persisting one. The same method also writes the SSO domain allowlist and+ // the sign-in switches.+ //+ // Classification is per method, so this refuses the whole RPC — including+ // the settings that have nothing to do with any of them. Splitting the+ // handler so ordinary configuration stays reachable to an agent is the+ // follow-up (BOT-53); disallowing first is the deliberate order.+ v1pb.MCPDenialReason_REWRITES_SESSION_BOUNDARY: {v1pb.MCPMethodClass_FORBIDDEN, "it rewrites the workspace settings that bound this session, including the switch meant to contain it"},++ v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION: {v1pb.MCPMethodClass_FORBIDDEN, "it can let a change or an access request pass its approval without an approver deciding it"},++ // The other refused class. An EXCLUDED method is out of scope for the modes+ // this release ships, and an admin-capable ceiling could legitimately serve+ // it one day; a FORBIDDEN method breaks the MCP boundary, so no ceiling+ // serves it. A denial that blurred the two would tell an operator the wrong+ // thing about whether asking is worth it. The class on each row is what+ // keeps them apart.+ v1pb.MCPDenialReason_ADMINISTERS_THE_WORKSPACE: {v1pb.MCPMethodClass_EXCLUDED, "it administers the workspace rather than doing database work, and no MCP mode this release ships covers workspace administration"},+ v1pb.MCPDenialReason_READS_OTHER_USERS_SQL: {v1pb.MCPMethodClass_EXCLUDED, "it returns SQL that other people wrote, across the workspace or past the sharing that keeps a saved query private"},+ v1pb.MCPDenialReason_OPENS_AN_ADMIN_CONNECTION: {v1pb.MCPMethodClass_EXCLUDED, "it opens an admin-credentialed connection to the database and returns other sessions' live, unmasked SQL"},+ v1pb.MCPDenialReason_SENDS_DATA_TO_A_THIRD_PARTY: {v1pb.MCPMethodClass_EXCLUDED, "it spends a stored workspace credential to send whatever the caller passes to a third party"},+ v1pb.MCPDenialReason_REDRAWS_GOVERNANCE_BOUNDARY: {v1pb.MCPMethodClass_EXCLUDED, "it changes which rules govern a database or which databases a change that targets a database group runs on, and an agent does not choose the checks on its own changes"},+ // No method carries this one: the three leaks it was written for are+ // redacted on the read path and their eight methods are READ. The row+ // stays so the next read found leaking is one annotation away from a+ // denial that explains itself, rather than two edits away.+ v1pb.MCPDenialReason_RETURNS_A_STORED_SECRET: {v1pb.MCPMethodClass_EXCLUDED, "its response carries a stored secret that the product redacts everywhere else"},+}++// The fallback wording, per class, for a method whose reason is unset, unknown+// to this build, or recorded for the other refused class. The class annotation+// is what denies; the table only supplies a better sentence.+const (+ reasonForbiddenClass = "it is not reachable by an AI agent session"+ reasonExcludedClass = "no MCP mode this release ships serves it"+)++// MCPDenialReasons returns the wording table, for the lint that holds every+// annotated reason against it.+func MCPDenialReasons() map[v1pb.MCPDenialReason]MCPDenialWording {+ return maps.Clone(mcpDenialReasons)+}++// MCPDenialSentence is the sentence for a refused method's recorded reason, or+// its class's fallback.+//+// The class is checked here as well as in the lint, and that is the point of+// carrying it on the row. One enum means a reason recorded for the wrong class+// is a value, not a parse error, so the runtime has to decline it: a FORBIDDEN+// method must never explain itself with an exclusion's sentence. A mismatch+// costs wording, the way a missing row does — never enforcement.+func MCPDenialSentence(class v1pb.MCPMethodClass, reason v1pb.MCPDenialReason) string {+ if wording, ok := mcpDenialReasons[reason]; ok && wording.Class == class {+ return wording.Sentence+ }+ if class == v1pb.MCPMethodClass_FORBIDDEN {+ return reasonForbiddenClass+ }+ return reasonExcludedClass+}diff --git a/backend/api/mcp/openapi_index.go b/backend/api/mcp/openapi_index.goindex 74b98aaa5a..bba65e5a9e 100644--- a/backend/api/mcp/openapi_index.go+++ b/backend/api/mcp/openapi_index.go@@ -56,6 +56,9 @@ type EndpointInfo struct {RequestSchemaRef string `json:"requestSchemaRef,omitempty"`// ResponseSchemaRef is the reference to the response schema.ResponseSchemaRef string `json:"responseSchemaRef,omitempty"`+ // Refusal is why no MCP session can call this endpoint, in the gate's words.+ // It is empty for an endpoint a ceiling serves.+ Refusal string `json:"refusal,omitempty"`}// PropertyInfo describes a property in a schema.@@ -72,16 +75,15 @@ type OpenAPIIndex struct {// endpoints holds every endpoint an MCP session may be offered. Discovery// walks this slice, so anything in it is advertisable by construction.endpoints []EndpointInfo- // hiddenEndpoints holds every endpoint no MCP capability ceiling serves —- // FORBIDDEN and EXCLUDED alike — resolvable through byOperation so a- // direct call still gets the gate's actionable denial, but reachable by no- // discovery path. A service whose every method is refused leaves- // Services() entirely.- hiddenEndpoints []EndpointInfo- byOperation map[string]*EndpointInfo- byService map[string][]*EndpointInfo- services []string- keywords map[string][]*EndpointInfo+ // unavailableEndpoints holds every endpoint no MCP capability ceiling+ // serves; parseSpec says how discovery treats them.+ unavailableEndpoints []EndpointInfo+ unavailableByService map[string][]*EndpointInfo+ byOperation map[string]*EndpointInfo+ byService map[string][]*EndpointInfo+ services []string+ serviceDescriptions map[string]string+ keywords map[string][]*EndpointInfo}// NewOpenAPIIndex creates a new OpenAPI index from the embedded spec.@@ -97,10 +99,12 @@ func NewOpenAPIIndex() (*OpenAPIIndex, error) {}idx := &OpenAPIIndex{- doc: model,- byOperation: make(map[string]*EndpointInfo),- byService: make(map[string][]*EndpointInfo),- keywords: make(map[string][]*EndpointInfo),+ doc: model,+ unavailableByService: make(map[string][]*EndpointInfo),+ byOperation: make(map[string]*EndpointInfo),+ byService: make(map[string][]*EndpointInfo),+ serviceDescriptions: make(map[string]string),+ keywords: make(map[string][]*EndpointInfo),}idx.parseSpec()@@ -168,20 +172,26 @@ func (idx *OpenAPIIndex) parseSpec() {}}- // An endpoint an MCP session can never call is not advertised: it stays- // out of search results, service listings and the keyword index, so the- // agent is not offered work that will only ever come back refused. It- // lands in hiddenEndpoints rather than endpoints — every discovery path+ // An endpoint an MCP session can never call is not offered: it stays+ // out of the served listings and the keyword index, so the agent is not+ // offered work that will only ever come back refused. It lands in+ // unavailableEndpoints rather than endpoints — every path that offers work// walks the latter, so keeping it out of that slice is what makes this- // hold for search paths added later, not just today's.+ // hold for search paths added later, not just today's. Discovery still+ // names it with the gate's reason, in the service listings and in+ // detail mode, never with its schema, so the agent sends the user to+ // the console instead of guessing.//// It stays resolvable by operation ID on purpose: an agent that calls it// anyway (from memory, or from a skill written before the// classification) should meet the gate's actionable denial rather than// "unknown operation".- if refusedToMCP(path) {- idx.hiddenEndpoints = append(idx.hiddenEndpoints, endpoint)- idx.byOperation[endpoint.OperationID] = &idx.hiddenEndpoints[len(idx.hiddenEndpoints)-1]+ if refusal, refused := mcpRefusal(path); refused {+ endpoint.Refusal = refusal+ idx.unavailableEndpoints = append(idx.unavailableEndpoints, endpoint)+ ptr := &idx.unavailableEndpoints[len(idx.unavailableEndpoints)-1]+ idx.byOperation[endpoint.OperationID] = ptr+ idx.unavailableByService[service] = append(idx.unavailableByService[service], ptr)continue}@@ -200,24 +210,28 @@ func (idx *OpenAPIIndex) parseSpec() {idx.services = append(idx.services, s)}slices.Sort(idx.services)++ for _, tag := range idx.doc.Model.Tags {+ idx.serviceDescriptions[strings.TrimPrefix(tag.Name, "bytebase.v1.")] = tag.Description+ }}-// refusedToMCP reports whether the RPC behind a connect path is served by no-// MCP capability ceiling — FORBIDDEN and EXCLUDED alike, since the ceiling gate-// refuses both whatever the workspace is set to. It keys on that predicate-// rather than on one class, so a class the ceiling stops serving stops being-// advertised in the same change.+// mcpRefusal reports whether the RPC behind a connect path is served by no MCP+// capability ceiling — FORBIDDEN and EXCLUDED alike, since the ceiling gate+// refuses both whatever the workspace is set to — and if so, the reason the+// gate gives. It keys on that predicate rather than on one class, so a class+// the ceiling stops serving stops being advertised in the same change.//// A path whose descriptor cannot be resolved is treated as not refused: this// decides only what to advertise, and hiding a legitimate endpoint because a// lookup failed would be the worse failure — enforcement is the interceptor's// job and reads the annotation itself.-func refusedToMCP(path string) bool {- class, err := auth.MCPMethodClassOfProcedure(path)- if err != nil {- return false+func mcpRefusal(path string) (string, bool) {+ class, reason, err := auth.MCPAnnotationsOfProcedure(path)+ if err != nil || !auth.MCPClassIsRefused(class) {+ return "", false}- return auth.MCPClassIsRefused(class)+ return auth.MCPDenialSentence(class, reason), true}func extractPermissions(description string) []string {@@ -371,6 +385,30 @@ func (idx *OpenAPIIndex) GetServiceEndpoints(service string) []*EndpointInfo {return idx.byService[service]}+// GetUnavailableEndpoints returns the endpoints of a service that no MCP+// session can call.+func (idx *OpenAPIIndex) GetUnavailableEndpoints(service string) []*EndpointInfo {+ return idx.unavailableByService[service]+}++// UnavailableServices returns the services no MCP session can call any+// endpoint of, sorted by name.+func (idx *OpenAPIIndex) UnavailableServices() []string {+ var services []string+ for service := range idx.unavailableByService {+ if len(idx.byService[service]) == 0 {+ services = append(services, service)+ }+ }+ slices.Sort(services)+ return services+}++// ServiceDescription returns the service's one-line description from the spec.+func (idx *OpenAPIIndex) ServiceDescription(service string) string {+ return idx.serviceDescriptions[service]+}+// Search searches for endpoints matching the query.func (idx *OpenAPIIndex) Search(query string) []*EndpointInfo {queryKeywords := extractKeywords(query)@@ -523,6 +561,10 @@ func extractPropertyTypeAndDesc(prop *v3base.SchemaProxy) (string, string) {if propSchema != nil && len(propSchema.Type) > 0 {propType = propSchema.Type[0]+ // A proto bytes field: protojson reads it only as base64.+ if propType == "string" && propSchema.Format == "byte" {+ propType = "string (base64-encoded bytes)"+ }// For arrays, get the item typeif propType == "array" && propSchema.Items != nil && propSchema.Items.A != nil {diff --git a/backend/api/mcp/openapi_index_refused_test.go b/backend/api/mcp/openapi_index_refused_test.goindex ff0439b045..aaf30e8fe9 100644--- a/backend/api/mcp/openapi_index_refused_test.go+++ b/backend/api/mcp/openapi_index_refused_test.go@@ -7,10 +7,11 @@ import ()// TestRefusedEndpointsAreNotAdvertised pins the two halves of how the index-// treats an RPC no MCP ceiling serves: invisible to every discovery path an-// agent has, and still resolvable by operation ID so a call that arrives anyway-// meets the gate's actionable denial rather than "unknown operation, use-// search_api".+// treats an RPC no MCP ceiling serves: never offered (absent from the served+// listings and the keyword index, never shown with a schema; discovery names it+// as unavailable instead), and still resolvable by operation ID so a call that+// arrives anyway meets the gate's actionable denial rather than "unknown+// operation, use search_api".//// The predicate is "refused under every ceiling", not "FORBIDDEN". Both refused// classes are covered because the gate refuses both, and an agent offered work@@ -22,11 +23,11 @@ func TestRefusedEndpointsAreNotAdvertised(t *testing.T) {const forbidden = "bytebase.v1.AuthService.Login"const forbiddenPath = "/bytebase.v1.AuthService/Login"- require.True(t, refusedToMCP(forbiddenPath), "precondition: Login is annotated FORBIDDEN")+ require.True(t, refused(forbiddenPath), "precondition: Login is annotated FORBIDDEN")const excluded = "bytebase.v1.UserService.ListUsers"const excludedPath = "/bytebase.v1.UserService/ListUsers"- require.True(t, refusedToMCP(excludedPath), "precondition: ListUsers is annotated EXCLUDED")+ require.True(t, refused(excludedPath), "precondition: ListUsers is annotated EXCLUDED")t.Run("still resolvable by operation ID", func(t *testing.T) {for operation, path := range map[string]string{forbidden: forbiddenPath, excluded: excludedPath} {@@ -44,12 +45,13 @@ func TestRefusedEndpointsAreNotAdvertised(t *testing.T) {require.Equal(t, "bytebase.v1.AuthService.GetAuthenticationInfo", endpoints[0].OperationID)})- t.Run("a service whose every method is refused is not listed at all", func(t *testing.T) {+ t.Run("a service whose every method is refused is not on the served list", func(t *testing.T) {// Every identity-provider method is refused: the writes choose what// will later be trusted to mint a credential, and the reads are- // workspace administration. Nothing about the service is offered.+ // workspace administration.require.NotContains(t, idx.Services(), "IdentityProviderService")require.Empty(t, idx.GetServiceEndpoints("IdentityProviderService"))+ require.Contains(t, idx.UnavailableServices(), "IdentityProviderService")})t.Run("a service keeps only the methods a ceiling serves", func(t *testing.T) {@@ -77,7 +79,7 @@ func TestRefusedEndpointsAreNotAdvertised(t *testing.T) {t.Run("absent from search", func(t *testing.T) {for _, query := range []string{"login", "password", "workspace", "project", "user", "instance"} {for _, hit := range idx.Search(query) {- require.False(t, refusedToMCP(hit.Path),+ require.False(t, refused(hit.Path),"search %q offered %s, which an MCP session can never call", query, hit.Path)}}@@ -90,3 +92,8 @@ func TestRefusedEndpointsAreNotAdvertised(t *testing.T) {require.NotEmpty(t, idx.Search("database"))})}++func refused(path string) bool {+ _, ok := mcpRefusal(path)+ return ok+}diff --git a/backend/api/mcp/tool_search.go b/backend/api/mcp/tool_search.goindex 44b50ed92b..b5a791892f 100644--- a/backend/api/mcp/tool_search.go+++ b/backend/api/mcp/tool_search.go@@ -3,11 +3,14 @@ package mcpimport ("context""fmt"+ "slices""strings""github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect")// SearchInput is the input for the search_api tool.@@ -33,7 +36,9 @@ const searchAPIDescription = `Discover Bytebase API endpoints. **Always call bef| Details | operationId="SQLService/Query" | Request/response schema || Schema | schema="Instance" | Message type definition |-**Workflow:** search_api() → search_api(service="...") → search_api(operationId="...") → call_api(...)`+**Workflow:** search_api() → search_api(service="...") → search_api(operationId="...") → call_api(...)++The results also name what no MCP session can do, whatever the workspace's MCP mode and the user's permissions, and why: those are done in the Bytebase console.`func (s *Server) registerSearchTool() {mcp.AddTool(s.mcpServer, &mcp.Tool{@@ -59,14 +64,7 @@ func (s *Server) handleSearchAPI(_ context.Context, _ *mcp.CallToolRequest, inputext = s.formatServiceList()default:- // List all endpoints in a service (no limit)- endpoints := s.openAPIIndex.GetServiceEndpoints(input.Service)- if len(endpoints) == 0 {- text = fmt.Sprintf("No endpoints found for service: %s\n\nAvailable services:\n%s",- input.Service, s.formatServiceList())- } else {- text = s.formatEndpoints(endpoints, 0)- }+ text = s.formatService(input.Service)}return &mcp.CallToolResult{@@ -87,9 +85,108 @@ func (s *Server) formatServiceList() string {}fmt.Fprintf(&sb, "\nTotal: %d services\n", len(services))++ unavailable := s.openAPIIndex.UnavailableServices()+ if len(unavailable) == 0 {+ return sb.String()+ }+ sb.WriteString("\n## Not available over MCP\n\n")+ sb.WriteString("These services exist in Bytebase, but no MCP session can call them, whatever the user's permissions. " ++ mcpUnavailableWayOut + " `search_api(service=\"...\")` lists each operation and why.\n\n")+ for _, svc := range unavailable {+ fmt.Fprintf(&sb, "- **%s**", svc)+ if description := s.describeService(svc); description != "" {+ fmt.Fprintf(&sb, ": %s", description)+ }+ sb.WriteString("\n")+ for _, reason := range refusalReasons(s.openAPIIndex.GetUnavailableEndpoints(svc)) {+ fmt.Fprintf(&sb, " - Refused because %s.\n", reason)+ }+ }+ return sb.String()+}++// mcpUnavailableWayOut is where the user does what MCP refuses.+const mcpUnavailableWayOut = "Do this work signed in to the Bytebase console."++// formatService lists a service's endpoints and the ones MCP cannot call, and+// tells a service MCP cannot call at all apart from a name the index does not+// list.+func (s *Server) formatService(service string) string {+ endpoints := s.openAPIIndex.GetServiceEndpoints(service)+ unavailable := s.openAPIIndex.GetUnavailableEndpoints(service)+ switch {+ case len(endpoints) > 0 && len(unavailable) > 0:+ return s.formatEndpoints(endpoints, 0) + "## Not available over MCP\n\n" ++ "These exist in Bytebase, but no MCP session can call them, whatever the user's permissions. " ++ mcpUnavailableWayOut + "\n\n" + formatRefusals(unavailable)+ case len(endpoints) > 0:+ return s.formatEndpoints(endpoints, 0)+ case len(unavailable) > 0:+ var sb strings.Builder+ fmt.Fprintf(&sb, "%s is not available over MCP: no MCP session can call its operations, whatever the user's permissions. %s\n\n",+ service, mcpUnavailableWayOut)+ if description := s.describeService(service); description != "" {+ fmt.Fprintf(&sb, "%s: %s\n\n", service, description)+ }+ sb.WriteString(formatRefusals(unavailable))+ return sb.String()+ default:+ return fmt.Sprintf("Unknown service: %s\n\n%s", service, s.formatServiceList())+ }+}++// describeService is the service's spec description without its leading name:+// "WorkloadIdentityService manages workload identities" becomes "manages+// workload identities".+func (s *Server) describeService(service string) string {+ description := strings.TrimSpace(s.openAPIIndex.ServiceDescription(service))+ return strings.TrimPrefix(description, service+" ")+}++// refusalReasons returns the distinct reasons MCP refuses these endpoints, in+// the order they first appear.+func refusalReasons(endpoints []*EndpointInfo) []string {+ var reasons []string+ for _, ep := range endpoints {+ if !slices.Contains(reasons, ep.Refusal) {+ reasons = append(reasons, ep.Refusal)+ }+ }+ return reasons+}++// formatRefusals lists endpoints MCP cannot call, grouped by the reason.+func formatRefusals(endpoints []*EndpointInfo) string {+ var sb strings.Builder+ for _, reason := range refusalReasons(endpoints) {+ var operations []string+ for _, ep := range endpoints {+ if ep.Refusal == reason {+ operations = append(operations, ep.Service+"/"+ep.Method)+ }+ }+ slices.Sort(operations)+ fmt.Fprintf(&sb, "- %s: refused because %s.\n", strings.Join(operations, ", "), reason)+ }return sb.String()}+// endpointNote is what an agent must know about an endpoint that MCP serves+// only in part.+func endpointNote(ep *EndpointInfo) string {+ if ep.Path != v1connect.SettingServiceGetSettingProcedure {+ return ""+ }+ // Masking adds the built-in types to the saved ones+ // (getSemanticTypesSettingWithBuiltins, backend/api/v1/semantic_type.go).+ return fmt.Sprintf("MCP sessions read only these settings: %s. The user's own Bytebase permissions still apply. "++ "A setting the workspace has never saved returns \"setting <NAME> not found\". "++ "SEMANTIC_TYPES lists the saved types only, without the MD5 masking salt. "++ "The built-in types bb.default (full mask) and bb.default-partial (partial mask) always exist as well, "++ "so \"not found\" for SEMANTIC_TYPES means only that no custom types are saved.", strings.Join(auth.MCPReadableSettingNames(), ", "))+}+func (*Server) formatEndpoints(endpoints []*EndpointInfo, limit int) string {var sb strings.Builder@@ -107,6 +204,9 @@ func (*Server) formatEndpoints(endpoints []*EndpointInfo, limit int) string {if len(ep.Permissions) > 0 {fmt.Fprintf(&sb, "Permissions: `%s`\n", strings.Join(ep.Permissions, "`, `"))}+ if note := endpointNote(ep); note != "" {+ fmt.Fprintf(&sb, "%s\n", note)+ }sb.WriteString("\n")}@@ -124,9 +224,18 @@ func (s *Server) formatEndpointDetail(operationID string) string {fmt.Fprintf(&sb, "## %s/%s\n\n", ep.Service, ep.Method)fmt.Fprintf(&sb, "%s\n\n", ep.Summary)+ if ep.Refusal != "" {+ fmt.Fprintf(&sb, "Not available over MCP: no MCP session can call this operation, whatever the user's permissions, because %s. %s\n",+ ep.Refusal, mcpUnavailableWayOut)+ return sb.String()+ }+if len(ep.Permissions) > 0 {fmt.Fprintf(&sb, "**Permissions:** `%s`\n\n", strings.Join(ep.Permissions, "`, `"))}+ if note := endpointNote(ep); note != "" {+ fmt.Fprintf(&sb, "%s\n\n", note)+ }// Request schemaif ep.RequestSchemaRef != "" {diff --git a/backend/api/mcp/tool_search_test.go b/backend/api/mcp/tool_search_test.goindex 95cd9fa6f6..5d5ef3ac82 100644--- a/backend/api/mcp/tool_search_test.go+++ b/backend/api/mcp/tool_search_test.go@@ -2,14 +2,19 @@ package mcpimport ("context"+ "fmt""strings""testing"mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp""github.com/stretchr/testify/require"+ "google.golang.org/protobuf/reflect/protoreflect"+ "google.golang.org/protobuf/reflect/protoregistry"+ "github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/component/config"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1")func TestSearchAPIListServices(t *testing.T) {@@ -27,14 +32,18 @@ func TestSearchAPIListServices(t *testing.T) {require.Contains(t, text, "Available Services")require.Contains(t, text, "SQLService")require.Contains(t, text, "DatabaseService")- // A service the MCP ceiling serves nothing of is not on the menu.- // IdentityProviderService is the clearest case: its writes choose what will- // later be trusted to mint a credential and its reads are workspace- // administration, so every one of its methods is refused.- require.NotContains(t, text, "IdentityProviderService")+ available, unavailable, ok := strings.Cut(text, "## Not available over MCP")+ require.True(t, ok, "the list names what MCP cannot do")+ // A service the MCP ceiling serves nothing of is not on the menu, only on+ // the list of what MCP cannot do. IdentityProviderService is the clearest+ // case: its writes choose what will later be trusted to mint a credential+ // and its reads are workspace administration, so every one of its methods+ // is refused.+ require.NotContains(t, available, "IdentityProviderService")+ require.Contains(t, unavailable, "**IdentityProviderService**")// ProjectService is the mixed case, on the menu with only its reads: an// agent that cannot name a project cannot reach a database at all.- require.Contains(t, text, "ProjectService")+ require.Contains(t, available, "ProjectService")}func TestSearchAPIByService(t *testing.T) {@@ -71,8 +80,8 @@ func TestSearchAPIByServiceNotFound(t *testing.T) {require.Len(t, result.Content, 1)text := result.Content[0].(*mcpsdk.TextContent).Text- require.Contains(t, text, "No endpoints found")- require.Contains(t, text, "Available services")+ require.Contains(t, text, "Unknown service: NonExistentService")+ require.Contains(t, text, "Available Services")}func TestSearchAPIDetailMode(t *testing.T) {@@ -144,7 +153,7 @@ func TestSearchAPIDetailModeNotFound(t *testing.T) {require.Len(t, result.Content, 1)text := result.Content[0].(*mcpsdk.TextContent).Text- require.Contains(t, text, "Unknown operationId")+ require.Contains(t, text, "Unknown operationId: unknown.operation.id")}func TestSearchAPIServiceShowsAll(t *testing.T) {@@ -260,3 +269,142 @@ func TestSearchAPIProtobufDescriptionTruncation(t *testing.T) {require.Contains(t, text, "ISO 8601")}}++func newSearchServer(t *testing.T) *Server {+ t.Helper()+ s, err := newServerWithStore(newTestServerStore(), &config.Profile{Mode: common.ReleaseModeDev}, "test-secret", nil)+ require.NoError(t, err)+ return s+}++func searchText(t *testing.T, s *Server, input SearchInput) string {+ t.Helper()+ result, _, err := s.handleSearchAPI(context.Background(), nil, input)+ require.NoError(t, err)+ require.Len(t, result.Content, 1)+ return result.Content[0].(*mcpsdk.TextContent).Text+}++func TestSearchAPINamesWhatMCPCannotDo(t *testing.T) {+ s := newSearchServer(t)+ administers := auth.MCPDenialSentence(v1pb.MCPMethodClass_EXCLUDED, v1pb.MCPDenialReason_ADMINISTERS_THE_WORKSPACE)+ mintsForOthers := auth.MCPDenialSentence(v1pb.MCPMethodClass_FORBIDDEN, v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS)++ t.Run("the service list names each unavailable service, why, and the console", func(t *testing.T) {+ _, unavailable, ok := strings.Cut(searchText(t, s, SearchInput{}), "## Not available over MCP")+ require.True(t, ok)+ require.Contains(t, unavailable, "whatever the user's permissions")+ require.Contains(t, unavailable, "Bytebase console")+ require.NotContains(t, unavailable, "Request Body")+ _, block, ok := strings.Cut(unavailable, "- **WorkloadIdentityService**")+ require.True(t, ok)+ block, _, _ = strings.Cut(block, "\n- **")+ require.Equal(t, ": manages workload identities for external CI/CD integrations.\n"++ " - Refused because "+mintsForOthers+".\n"++ " - Refused because "+administers+".\n", block, "the service's reasons sit under it")+ })++ t.Run("a service MCP cannot call is not reported as missing", func(t *testing.T) {+ text := searchText(t, s, SearchInput{Service: "WorkloadIdentityService"})+ require.Contains(t, text, "WorkloadIdentityService is not available over MCP")+ require.Contains(t, text, "- WorkloadIdentityService/CreateWorkloadIdentity, WorkloadIdentityService/UpdateWorkloadIdentity: refused because "+mintsForOthers+".\n",+ "operations refused for one reason share one line")+ require.NotContains(t, text, "Unknown service")+ require.NotContains(t, text, "Request Body")+ })++ t.Run("a served service also names the operations MCP cannot call", func(t *testing.T) {+ text := searchText(t, s, SearchInput{Service: "InstanceService"})+ served, unavailable, ok := strings.Cut(text, "## Not available over MCP")+ require.True(t, ok)+ require.Contains(t, served, "InstanceService/GetInstance")+ require.NotContains(t, served, "InstanceService/CreateInstance")+ require.Contains(t, unavailable, "InstanceService/CreateInstance")+ require.Equal(t, 1, strings.Count(unavailable, "refused because "+administers), "one line per reason")+ })++ t.Run("detail mode gives the refusal, not the schema", func(t *testing.T) {+ text := searchText(t, s, SearchInput{OperationID: "InstanceService/CreateInstance"})+ require.Contains(t, text, "## InstanceService/CreateInstance")+ require.Contains(t, text, "Not available over MCP")+ require.Contains(t, text, administers)+ require.Contains(t, text, "Bytebase console")+ require.NotContains(t, text, "Request Body")+ require.NotContains(t, text, "Response Body")+ require.NotContains(t, text, "Unknown operationId")+ })++ t.Run("the setting read names the settings it serves", func(t *testing.T) {+ const readable = "settings/WORKSPACE_APPROVAL, settings/ENVIRONMENT, settings/SEMANTIC_TYPES, settings/DATA_CLASSIFICATION"+ text := searchText(t, s, SearchInput{Service: "SettingService"})+ served, unavailable, ok := strings.Cut(text, "## Not available over MCP")+ require.True(t, ok)+ require.Contains(t, served, "SettingService/GetSetting")+ require.Contains(t, served, readable)+ require.Contains(t, served, "own Bytebase permissions still apply")+ require.Contains(t, served, `returns "setting <NAME> not found"`)+ require.Contains(t, served, "bb.default (full mask) and bb.default-partial (partial mask) always exist")+ for _, method := range []string{"ListSettings", "UpdateSetting", "TestEmailSetting"} {+ require.Contains(t, unavailable, "SettingService/"+method)+ }++ detail := searchText(t, s, SearchInput{OperationID: "SettingService/GetSetting"})+ require.Contains(t, detail, readable)+ require.Contains(t, detail, "Request Body")+ })+}++// TestSearchAPINamesEveryRefusedMethod derives the refused methods from the+// annotations, so a method refused later is named with the gate's reason+// without anyone listing it here.+func TestSearchAPINamesEveryRefusedMethod(t *testing.T) {+ type refusedMethod struct {+ service, method, reason string+ }+ var refused []refusedMethod+ protoregistry.GlobalFiles.RangeFiles(func(fd protoreflect.FileDescriptor) bool {+ if fd.Package() != "bytebase.v1" {+ return true+ }+ for i := range fd.Services().Len() {+ sd := fd.Services().Get(i)+ for j := range sd.Methods().Len() {+ if md := sd.Methods().Get(j); md.IsStreamingClient() || md.IsStreamingServer() {+ // The spec has no path for a streaming RPC, so neither search nor+ // call_api can reach one.+ continue+ }+ procedure := fmt.Sprintf("/%s/%s", sd.FullName(), sd.Methods().Get(j).Name())+ class, reason, err := auth.MCPAnnotationsOfProcedure(procedure)+ require.NoError(t, err)+ if !auth.MCPClassIsRefused(class) {+ continue+ }+ refused = append(refused, refusedMethod{string(sd.Name()), string(sd.Methods().Get(j).Name()), auth.MCPDenialSentence(class, reason)})+ }+ }+ return true+ })+ require.NotEmpty(t, refused)++ s := newSearchServer(t)+ listings := map[string]string{}+ for _, m := range refused {+ if _, ok := listings[m.service]; !ok {+ listings[m.service] = searchText(t, s, SearchInput{Service: m.service})+ }+ require.Contains(t, listings[m.service], fmt.Sprintf("%s/%s", m.service, m.method))+ require.Contains(t, listings[m.service], "refused because "+m.reason)++ detail := searchText(t, s, SearchInput{OperationID: m.service + "/" + m.method})+ require.Contains(t, detail, m.reason, "%s/%s", m.service, m.method)+ require.NotContains(t, detail, "Request Body", "%s/%s", m.service, m.method)+ }+}++func TestSearchAPIShowsBytesAsBase64(t *testing.T) {+ s := newSearchServer(t)+ text := searchText(t, s, SearchInput{Schema: "Release.File"})+ require.Contains(t, text, `"statement": string (base64-encoded bytes)`)+ require.Contains(t, text, `"path": string //`, "other strings keep their plain type")+}diff --git a/backend/api/v1/mcp_gate.go b/backend/api/v1/mcp_gate.goindex 9a49bcf351..9bc8a49269 100644--- a/backend/api/v1/mcp_gate.go+++ b/backend/api/v1/mcp_gate.go@@ -18,187 +18,6 @@ import ("github.com/bytebase/bytebase/backend/generated-go/v1/v1connect")-// mcpDenialWording is one reason's sentence plus the class it belongs to. The-// class is carried here because a reason implies one — a mechanism that breaks-// the MCP boundary is what FORBIDDEN means, a scope decision is what EXCLUDED-// means — and one table saying so is what lets the lint check the pairing and-// the gate refuse to print the wrong half of it.-type mcpDenialWording struct {- class v1pb.MCPMethodClass- sentence string-}--// mcpDenialReasons is UX copy, NOT the classification and NOT the mapping.-// Both of those live on the RPC itself, as the bytebase.v1.mcp_method_class and-// bytebase.v1.mcp_denial_reason annotations, beside permission / audit /-// auth_method — one source of truth, visible where the RPC is defined, and read-// here off the AuthContext the auth interceptor already resolves. This table-// only turns a reason into a sentence the agent can act on, so it has one row-// per mechanism rather than one per method, and a missing row costs wording,-// never enforcement.-//-// Each sentence completes "<procedure> is not available to MCP sessions because-// ___", so it states what the method does rather than merely that it is-// refused: a denial whose stated reason has drifted from the mechanism is worse-// than a bare refusal, because it is the thing the next reader trusts.-var mcpDenialReasons = map[v1pb.MCPDenialReason]mcpDenialWording{- // The method hands a token back to the caller. For a non-web caller — and- // an MCP session is always one — finalizeLogin and switchWorkspaceInternal- // put a plain bb.user.access token in the response body. That token is not- // audience-bound to the MCP resource, survives revocation of the OAuth- // grant, and ignores the workspace MCP kill switch, so obtaining one ends- // the MCP boundary for good.- v1pb.MCPDenialReason_MINTS_CREDENTIAL: {v1pb.MCPMethodClass_FORBIDDEN, "it hands back a login token that would outlive the MCP grant"},-- // The method drives the out-of-band reset flow — mailing a reset or login- // code, or consuming one — that sets or delivers the very secret Login- // accepts. Denying Login alone would leave the agent holding the credential- // for the next human login.- v1pb.MCPDenialReason_RESETS_CREDENTIAL: {v1pb.MCPMethodClass_FORBIDDEN, "it drives the credential-reset flow that sets or delivers the secret a login accepts"},-- // UpdateUser's password and MFA branches take no proof of the old password.- // A caller updating itself needs no permission at all, and on self-hosted a- // caller holding bb.users.update reaches any other end user's password too- // (user_service.go: the caller != subject branch checks that permission and- // nothing further). Either way the session ends up holding credentials it- // can log in with. The whole method is refused, not just those branches —- // the classification is per method.- v1pb.MCPDenialReason_TAKES_OVER_ACCOUNT: {v1pb.MCPMethodClass_FORBIDDEN, "it can rewrite an account's credentials, which would let the session take that account over"},-- // Logout deletes the web refresh token and expires the session cookies. It- // mints nothing; it destroys the human's own login session, which an agent- // acting on their behalf has no business doing.- v1pb.MCPDenialReason_ENDS_SESSION: {v1pb.MCPMethodClass_FORBIDDEN, "it ends the human's own login session"},-- // The workspace-lifecycle pair. Both end in- // AuthService.switchWorkspaceInternal, which mints a plain workspace token- // whenever the caller has no refresh cookie — and an MCP session never has- // one — after having already destroyed the caller's membership.- v1pb.MCPDenialReason_ENDS_MEMBERSHIP: {v1pb.MCPMethodClass_FORBIDDEN, "it destroys the caller's own workspace membership and mints a plain workspace token"},-- // The method leaves someone holding a principal the caller is not. Four- // ways, all of them annotated:- // - issuing the credential outright — a service key or SCIM token- // returned in plaintext, a caller-chosen password on a new account;- // - carrying an existing one out — a stored client secret or SMTP- // password sent to a host the caller named;- // - choosing what will later be trusted to mint one — the issuer and- // subject ExchangeToken validates against;- // - redirecting where one gets delivered — UpdateEmail rebinds any- // account to an address the caller picked, and the reset flow mails the- // code to whatever address the account then carries.- // The levers that contain a runaway session all act on the caller's own- // principal: revoke the OAuth grant, flip the workspace MCP switch,- // deactivate the human. None of them reaches a principal that was never the- // caller's, so what these give away outlives all three.- //- // InstanceService/UpdateDataSource is the same "carry an existing one out"- // shape as the two Test methods, against the database's credentials rather- // than Bytebase's own: it merges a partial request onto the STORED,- // already-decrypted data source, so an update_mask naming only a- // destination field (host, port, ssh_host, additional_addresses,- // sasl_config.kdc_host) keeps the stored password, ssl_key and- // ssh_private_key. With validate_only it dials the caller's host- // immediately and persists nothing; without it the retarget is written and- // SyncInstance triggers the connection on demand. No allowlist filters the- // host on either path. A database user is a principal other than the- // caller, the same way the SMTP account behind TestEmailSetting is.- //- // Its siblings are NOT here and the line is severity, not tidiness:- // UpdateInstance and BatchUpdateInstances rebuild the data-source list- // wholesale, so every secret is wiped unless resent — except the Kerberos- // keytab, which retainStoredKeytabs used to inherit by data-source ID.- // That narrower, persist-only version of the vector is now closed at the- // retention rule instead of at reachability: a keytab is not inherited to- // a destination the caller moved (instance_service_converter.go). It costs- // an agent no instance management, something no one has yet decided it- // should lose, and it binds human callers too — a Kerberos host edit now- // asks for the keytab again, on the console as much as on the API.- // The keytab is the ONLY secret that rule reaches, because it is the only- // one those two methods inherit. On UpdateDataSource above, every other- // stored secret still rides an update_mask that names only a destination,- // which is why that method is refused here rather than fixed there:- // requiring a password re-supplied on every host edit is a product call.- // AddDataSource and CreateInstance also dial on validate_only but build- // the data source entirely from the request, so they carry no stored- // secret and are not this class. BOT-57.- //- // The Undelete* family (user, service account, workload identity) is- // deliberately NOT in this group, and it is the nearest thing left out, so- // the reasoning is recorded rather than left to be rediscovered. It- // restores a principal whose password or key hash survived the soft- // delete, so an operator's deactivation is undone. It is out because the- // caller learns and chooses nothing: the credential goes back to whoever- // already had it, and a second delete takes it away again. Issuing beats- // re-arming, and this mechanism is about issuing. BOT-54.- v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS: {v1pb.MCPMethodClass_FORBIDDEN, "it hands someone control of a principal other than the caller, which revoking this session would not take back"},-- // SettingService/UpdateSetting, refused for the boundary it rewrites- // rather than for any credential it hands out. Three mask paths carry it:- // value.workspace_profile.mcp_capability IS the MCP ceiling, so a session- // that reaches it is not bounded by it; value.email.smtp keeps the- // stored password when the request omits it while accepting a new host,- // which hands over the relay resolvePreLoginEmailSetting reads to mail- // password resets and login codes; and value.ai.endpoint does the same to- // the AI key it never names — the stored api_key survives the mask, and the- // next AIService/Chat puts it in an auth header to the host just written- // (ai_service.go). SaaS refuses AI writes outright (setting_service.go), so- // that third one is a self-hosted vector, and the key it carries out is- // whatever the operator configured — GEMINI_API_KEY, where it is set, seeds- // one key into every workspace created after it (getAdditionalWorkspaceSettings).- // TestEmailSetting is the one-shot version of the second; this is the- // persisting one. The same method also writes the SSO domain allowlist and- // the sign-in switches.- //- // Classification is per method, so this refuses the whole RPC — including- // the settings that have nothing to do with any of them. Splitting the- // handler so ordinary configuration stays reachable to an agent is the- // follow-up (BOT-53); disallowing first is the deliberate order.- v1pb.MCPDenialReason_REWRITES_SESSION_BOUNDARY: {v1pb.MCPMethodClass_FORBIDDEN, "it rewrites the workspace settings that bound this session, including the switch meant to contain it"},-- v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION: {v1pb.MCPMethodClass_FORBIDDEN, "it can let a change or an access request pass its approval without an approver deciding it"},-- // The other refused class. An EXCLUDED method is out of scope for the modes- // this release ships, and an admin-capable ceiling could legitimately serve- // it one day; a FORBIDDEN method breaks the MCP boundary, so no ceiling- // serves it. A denial that blurred the two would tell an operator the wrong- // thing about whether asking is worth it. The class on each row is what- // keeps them apart.- v1pb.MCPDenialReason_ADMINISTERS_THE_WORKSPACE: {v1pb.MCPMethodClass_EXCLUDED, "it administers the workspace rather than doing database work, and no MCP mode this release ships covers workspace administration"},- v1pb.MCPDenialReason_READS_OTHER_USERS_SQL: {v1pb.MCPMethodClass_EXCLUDED, "it returns SQL that other people wrote, across the workspace or past the sharing that keeps a saved query private"},- v1pb.MCPDenialReason_OPENS_AN_ADMIN_CONNECTION: {v1pb.MCPMethodClass_EXCLUDED, "it opens an admin-credentialed connection to the database and returns other sessions' live, unmasked SQL"},- v1pb.MCPDenialReason_SENDS_DATA_TO_A_THIRD_PARTY: {v1pb.MCPMethodClass_EXCLUDED, "it spends a stored workspace credential to send whatever the caller passes to a third party"},- v1pb.MCPDenialReason_REDRAWS_GOVERNANCE_BOUNDARY: {v1pb.MCPMethodClass_EXCLUDED, "it changes which rules govern a database or which databases a change that targets a database group runs on, and an agent does not choose the checks on its own changes"},- // No method carries this one: the three leaks it was written for are- // redacted on the read path and their eight methods are READ. The row- // stays so the next read found leaking is one annotation away from a- // denial that explains itself, rather than two edits away.- v1pb.MCPDenialReason_RETURNS_A_STORED_SECRET: {v1pb.MCPMethodClass_EXCLUDED, "its response carries a stored secret that the product redacts everywhere else"},-}--// The fallback wording, per class, for a method whose reason is unset, unknown-// to this build, or recorded for the other refused class. The class annotation-// is what denies; the table only supplies a better sentence.-const (- reasonForbiddenClass = "it is not reachable by an AI agent session"- reasonExcludedClass = "no MCP mode this release ships serves it"-)--// denialReason is the sentence for this method's recorded reason, or the-// class's fallback.-//-// The class is checked here as well as in the lint, and that is the point of-// carrying it on the row. One enum means a reason recorded for the wrong class-// is a value, not a parse error, so the runtime has to decline it: a FORBIDDEN-// method must never explain itself with an exclusion's sentence. A mismatch-// costs wording, the way a missing row does — never enforcement.-func denialReason(class v1pb.MCPMethodClass, reason v1pb.MCPDenialReason, fallback string) string {- if wording, ok := mcpDenialReasons[reason]; ok && wording.class == class {- return wording.sentence- }- return fallback-}-// mcpServingClasses is the ceiling: which method classes each stored capability// serves. It is the whole of what the gate evaluates against the classification,// and the lint in mcp_gate_test.go holds the annotations against this same@@ -358,11 +177,11 @@ func (in *internalMCPGateInterceptor) refuse(ctx context.Context, req connect.Ancase v1pb.MCPMethodClass_FORBIDDEN:return ctx, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf("%s is not available to MCP sessions because %s. %s",- procedure, denialReason(authCtx.MCPMethodClass, authCtx.MCPDenialReason, reasonForbiddenClass), mcpConsoleWayOut))+ procedure, auth.MCPDenialSentence(authCtx.MCPMethodClass, authCtx.MCPDenialReason), mcpConsoleWayOut))case v1pb.MCPMethodClass_EXCLUDED:return ctx, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf("%s is served by no MCP capability ceiling because %s. %s",- procedure, denialReason(authCtx.MCPMethodClass, authCtx.MCPDenialReason, reasonExcludedClass), mcpConsoleWayOut))+ procedure, auth.MCPDenialSentence(authCtx.MCPMethodClass, authCtx.MCPDenialReason), mcpConsoleWayOut))case v1pb.MCPMethodClass_READ, v1pb.MCPMethodClass_WRITE:default:return ctx, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(@@ -608,9 +427,6 @@ func refuseUnreadableSetting(_ context.Context, msg any) string {return ""}}- var readable []string- for _, setting := range auth.MCPReadableSettings() {- readable = append(readable, common.SettingNamePrefix+setting.String())- }- return fmt.Sprintf("%q is not one of the settings an MCP session reads (%s)", request.GetName(), strings.Join(readable, ", "))+ return fmt.Sprintf("%q is not one of the settings an MCP session reads (%s)",+ request.GetName(), strings.Join(auth.MCPReadableSettingNames(), ", "))}diff --git a/backend/api/v1/mcp_gate_test.go b/backend/api/v1/mcp_gate_test.goindex 91e3f10765..b04c37d803 100644--- a/backend/api/v1/mcp_gate_test.go+++ b/backend/api/v1/mcp_gate_test.go@@ -229,7 +229,7 @@ func checkEveryMethodIsClassified(rows []mcpClassification) []string {// practice, only added the states where a method carried both or carried the// kind that contradicted its class — states this clause used to spend four of// its six branches policing. What is left is the one thing that was ever real.-func checkReasonsMatchTheClass(rows []mcpClassification, wording map[v1pb.MCPDenialReason]mcpDenialWording) []string {+func checkReasonsMatchTheClass(rows []mcpClassification, wording map[v1pb.MCPDenialReason]auth.MCPDenialWording) []string {var violations []stringfor _, row := range rows {refused := row.class == v1pb.MCPMethodClass_FORBIDDEN || row.class == v1pb.MCPMethodClass_EXCLUDED@@ -242,9 +242,9 @@ func checkReasonsMatchTheClass(rows []mcpClassification, wording map[v1pb.MCPDenswitch {case !ok:violations = append(violations, fmt.Sprintf("%s: is refused for %v, which has no sentence to say so", row.procedure, row.reason))- case recorded.class != row.class:+ case recorded.Class != row.class:violations = append(violations, fmt.Sprintf("%s: is %v but records %v, which is a %v reason",- row.procedure, row.class, row.reason, recorded.class))+ row.procedure, row.class, row.reason, recorded.Class))default:}case hasReason:@@ -355,7 +355,7 @@ func TestLintEveryMethodIsClassified(t *testing.T) {func TestLintReasonsMatchTheClass(t *testing.T) {t.Parallel()- require.Empty(t, checkReasonsMatchTheClass(mcpClassificationsFromDescriptors(t), mcpDenialReasons))+ require.Empty(t, checkReasonsMatchTheClass(mcpClassificationsFromDescriptors(t), auth.MCPDenialReasons()))}// mcpEnums reads the two enums the serving decision spans out of the compiled@@ -376,10 +376,10 @@ func TestLintEveryClassHasAServingDecision(t *testing.T) {// TestLintRefusedClassesMatchTheServingTable is what lets a second package// decide what to advertise without carrying a copy of the serving rules. The-// MCP OpenAPI index hides an endpoint no ceiling serves, and it asks+// MCP OpenAPI index never offers an endpoint no ceiling serves, and it asks// auth.MCPClassIsRefused, which cannot see this table. This holds the two// against each other over the whole class vocabulary, so a mode that starts-// serving a class cannot leave discovery hiding it — or the reverse, which is+// serving a class cannot leave discovery withholding it — or the reverse, which is// the one that would offer an agent work it can never do.func TestLintRefusedClassesMatchTheServingTable(t *testing.T) {t.Parallel()@@ -468,7 +468,7 @@ func TestLintClausesFireWhenBroken(t *testing.T) {require.Equal(t, []string{"/p: is FORBIDDEN and records no mcp_denial_reason","/q: is EXCLUDED and records no mcp_denial_reason",- }, checkReasonsMatchTheClass(broken, mcpDenialReasons))+ }, checkReasonsMatchTheClass(broken, auth.MCPDenialReasons()))})t.Run("a reason with no wording fails", func(t *testing.T) {@@ -478,7 +478,7 @@ func TestLintClausesFireWhenBroken(t *testing.T) {reason: v1pb.MCPDenialReason(9999),}}require.Equal(t, []string{"/p: is refused for 9999, which has no sentence to say so"},- checkReasonsMatchTheClass(broken, mcpDenialReasons))+ checkReasonsMatchTheClass(broken, auth.MCPDenialReasons()))})t.Run("a reason belonging to the other refused class fails", func(t *testing.T) {@@ -494,7 +494,7 @@ func TestLintClausesFireWhenBroken(t *testing.T) {require.Equal(t, []string{"/p: is FORBIDDEN but records ADMINISTERS_THE_WORKSPACE, which is a EXCLUDED reason","/q: is EXCLUDED but records MINTS_CREDENTIAL, which is a FORBIDDEN reason",- }, checkReasonsMatchTheClass(broken, mcpDenialReasons))+ }, checkReasonsMatchTheClass(broken, auth.MCPDenialReasons()))})t.Run("a served method carrying a denial reason fails", func(t *testing.T) {@@ -505,7 +505,7 @@ func TestLintClausesFireWhenBroken(t *testing.T) {require.Equal(t, []string{"/p: records MINTS_CREDENTIAL, a denial reason, but is not refused","/q: records ADMINISTERS_THE_WORKSPACE, a denial reason, but is not refused",- }, checkReasonsMatchTheClass(broken, mcpDenialReasons))+ }, checkReasonsMatchTheClass(broken, auth.MCPDenialReasons()))})// The serving-decision clause is over the vocabulary, so its mutations are@@ -739,7 +739,10 @@ func TestMCPGateServesOnlyTheReadableSettings(t *testing.T) {readable := []v1pb.Setting_SettingName{v1pb.Setting_WORKSPACE_APPROVAL, v1pb.Setting_ENVIRONMENT, v1pb.Setting_SEMANTIC_TYPES, v1pb.Setting_DATA_CLASSIFICATION,}- require.Equal(t, readable, auth.MCPReadableSettings(), "the settings an MCP session reads are a decision, recorded here as well as in auth")+ for _, setting := range v1pb.Setting_SettingName_value {+ require.Equal(t, slices.Contains(readable, v1pb.Setting_SettingName(setting)), auth.MCPCanReadSetting(v1pb.Setting_SettingName(setting)),+ "the settings an MCP session reads are a decision, recorded here as well as in auth")+ }read := classContext(v1pb.MCPMethodClass_READ)get := func(name string) connect.AnyRequest {return connect.NewRequest(&v1pb.GetSettingRequest{Name: name})@@ -1065,7 +1068,7 @@ func TestMCPGateRefusesTheDeniedClasses(t *testing.T) {if row.class != v1pb.MCPMethodClass_FORBIDDEN && row.class != v1pb.MCPMethodClass_EXCLUDED {continue}- wantReason := mcpDenialReasons[row.reason].sentence+ wantReason := auth.MCPDenialReasons()[row.reason].Sentencet.Run(row.procedure, func(t *testing.T) {got := invokeMCPGate(t, readWriteCeiling(), &common.AuthContext{MCPMethodClass: row.class,@@ -1252,7 +1255,7 @@ func TestMCPGateFallsBackToGenericWording(t *testing.T) {}, v1connect.AuthServiceLoginProcedure, connect.NewRequest(&v1pb.LoginRequest{}))require.Error(t, got.err)require.False(t, got.dispatched)- require.Contains(t, got.err.Error(), reasonForbiddenClass)+ require.Contains(t, got.err.Error(), "it is not reachable by an AI agent session")})t.Run("excluded", func(t *testing.T) {@@ -1262,7 +1265,7 @@ func TestMCPGateFallsBackToGenericWording(t *testing.T) {}, v1connect.UserServiceListUsersProcedure, connect.NewRequest(&v1pb.ListUsersRequest{}))require.Error(t, got.err)require.False(t, got.dispatched)- require.Contains(t, got.err.Error(), reasonExcludedClass)+ require.Contains(t, got.err.Error(), "no MCP mode this release ships serves it")})}diff --git a/backend/tests/mcp_forbidden_credential_mints_test.go b/backend/tests/mcp_forbidden_credential_mints_test.goindex 253d649b93..aa68736373 100644--- a/backend/tests/mcp_forbidden_credential_mints_test.go+++ b/backend/tests/mcp_forbidden_credential_mints_test.go@@ -837,16 +837,16 @@ func TestMCPCredentialMintsLeaveDiscovery(t *testing.T) {session := openMCPSession(ctx, t, ctl, ctl.authInterceptor.token)defer session.Close()- // Browsing a service must not list a method the session can never call,- // and the hiding is per method: a service keeping any served method stays- // on the menu with that method on it.+ // Browsing a service never offers a method the session can never call: the+ // method is not in the served listing and its schema is never shown. It is+ // named under "Not available over MCP" with the gate's reason, so the agent+ // can send the user to the console instead of guessing.//// The positive control comes first and on the same tool: without one,// NotContains over an opaque text blob passes for the wrong reason as soon// as search_api returns anything that is not an endpoint listing — an// error string, an empty result — and a test that cannot fail is worse- // here than no test, because this is the assertion standing between an- // agent and a menu of work it can never do.+ // here than no test.servedListing := searchAPIOnSession(ctx, t, session, map[string]any{"service": "DatabaseService"})a.Contains(servedListing, "DatabaseService/ListDatabases","positive control: a service the ceiling serves must really come back as an endpoint listing")@@ -854,7 +854,7 @@ func TestMCPCredentialMintsLeaveDiscovery(t *testing.T) {// These services host the credential mints, and since the ceiling gate// refuses EXCLUDED as well as FORBIDDEN, every one of their methods is now// refused — the mints outright, their read siblings as workspace- // administration. So they do not come back as a listing at all.+ // administration. So they come back as unavailable, with no listing.for _, row := range []struct {service stringrefused []string@@ -864,58 +864,73 @@ func TestMCPCredentialMintsLeaveDiscovery(t *testing.T) {{"WorkloadIdentityService", []string{"CreateWorkloadIdentity", "UpdateWorkloadIdentity"}},} {listing := searchAPIOnSession(ctx, t, session, map[string]any{"service": row.service})- a.Contains(listing, "No endpoints found for service: "+row.service,+ a.Contains(listing, row.service+" is not available over MCP","%s serves no method under any ceiling, so it is not a menu", row.service)+ a.NotContains(listing, "Found ", "%s offers no endpoint", row.service)for _, method := range row.refused {- a.NotContains(listing, row.service+"/"+method,- "search_api must not offer %s/%s, which the session can never call", row.service, method)+ a.Contains(listing, row.service+"/"+method,+ "search_api names %s/%s as unavailable", row.service, method)}}+ // servedAndUnavailable splits a mixed service's listing at the section that+ // names what MCP cannot do.+ servedAndUnavailable := func(service string) (string, string) {+ listing := searchAPIOnSession(ctx, t, session, map[string]any{"service": service})+ served, unavailable, ok := strings.Cut(listing, "## Not available over MCP")+ a.True(ok, "%s names what MCP cannot do", service)+ return served, unavailable+ }+// WorkspaceService is the mixed case and the one that proves the hiding is// per method rather than per service: it keeps GetWorkspace and- // ListWorkspaces, so it stays on the menu, and the token rotation is gone- // from it.- workspaceListing := searchAPIOnSession(ctx, t, session, map[string]any{"service": "WorkspaceService"})- a.Contains(workspaceListing, "WorkspaceService/ListWorkspaces",- "a service keeps the methods the ceiling serves")- a.NotContains(workspaceListing, "WorkspaceService/RotateDirectorySyncToken",+ // ListWorkspaces, so it stays on the menu, and the token rotation is only+ // named as unavailable.+ served, unavailable := servedAndUnavailable("WorkspaceService")+ a.Contains(served, "WorkspaceService/ListWorkspaces", "a service keeps the methods the ceiling serves")+ a.NotContains(served, "WorkspaceService/RotateDirectorySyncToken","search_api must not offer the token rotation, which the session can never call")+ a.Contains(unavailable, "WorkspaceService/RotateDirectorySyncToken")// UserService is the second mixed case, and it moved here when// GetCurrentUser stopped returning the MFA enrollment secrets. Reading who// you are is the one thing an agent does on this service; creating a user,// redirecting an account's email and reading somebody else's profile stay// refused, and stay off the menu.- userListing := searchAPIOnSession(ctx, t, session, map[string]any{"service": "UserService"})- a.Contains(userListing, "UserService/GetCurrentUser",+ served, unavailable = servedAndUnavailable("UserService")+ a.Contains(served, "UserService/GetCurrentUser","the session reads its own identity, so the service is a menu with that on it")for _, method := range []string{"CreateUser", "UpdateEmail", "GetUser", "ListUsers"} {- a.NotContains(userListing, "UserService/"+method,+ a.NotContains(served, "UserService/"+method,"search_api must not offer UserService/%s, which the session can never call", method)+ a.Contains(unavailable, "UserService/"+method)}// SettingService hosts TestEmailSetting, a mint, and keeps GetSetting, which// the gate serves for the governance settings alone.- settingListing := searchAPIOnSession(ctx, t, session, map[string]any{"service": "SettingService"})- a.Contains(settingListing, "SettingService/GetSetting", "the session reads the governance settings")+ served, unavailable = servedAndUnavailable("SettingService")+ a.Contains(served, "SettingService/GetSetting", "the session reads the governance settings")for _, method := range []string{"TestEmailSetting", "UpdateSetting", "ListSettings"} {- a.NotContains(settingListing, "SettingService/"+method,+ a.NotContains(served, "SettingService/"+method,"search_api must not offer SettingService/%s, which the session can never call", method)+ a.Contains(unavailable, "SettingService/"+method)}// The service list is the entry point into discovery, and a service whose- // every method is refused drops out of it entirely.+ // every method is refused leaves the menu for the list of what MCP cannot do.services := searchAPIOnSession(ctx, t, session, map[string]any{})+ available, unavailableServices, ok := strings.Cut(services, "## Not available over MCP")+ a.True(ok, "the service list names what MCP cannot do")for _, service := range []string{"ServiceAccountService", "IdentityProviderService", "WorkloadIdentityService",} {- a.NotContains(services, service, "%s serves nothing, so it must not be listed", service)+ a.NotContains(available, service, "%s serves nothing, so it is not on the menu", service)+ a.Contains(unavailableServices, "**"+service+"**", "%s is named as unavailable", service)}- a.Contains(services, "DatabaseService", "positive control: services the ceiling serves stay listed")- a.Contains(services, "WorkspaceService", "a service keeping any served method stays listed")- a.Contains(services, "UserService", "and so does the one that kept only GetCurrentUser")- a.Contains(services, "SettingService", "and the one that kept only GetSetting")+ a.Contains(available, "DatabaseService", "positive control: services the ceiling serves stay listed")+ a.Contains(available, "WorkspaceService", "a service keeping any served method stays listed")+ a.Contains(available, "UserService", "and so does the one that kept only GetCurrentUser")+ a.Contains(available, "SettingService", "and the one that kept only GetSetting")// Still resolvable by operation ID, and a call still reaches the gate.for _, operation := range []string{@@ -932,6 +947,7 @@ func TestMCPCredentialMintsLeaveDiscovery(t *testing.T) {"UserService/UpdateEmail",} {detail := searchAPIOnSession(ctx, t, session, map[string]any{"operationId": operation})+ a.Contains(detail, "Not available over MCP", "%s says why instead of showing a schema", operation)a.NotContains(detail, "Unknown operationId","%s must stay resolvable so the denial can explain itself", operation)}