Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(mcp): the MCP access policy settings surface, and the unreadable-ceiling repair (P1b 1b-6, part 1) (#21236)

Vincent Huang5276b29e6dc2
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index 45532e740b..916cfa1b79 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -15357,6 +15357,34 @@ components:
masking policy, and it does nothing on the engines Bytebase does not mask.
It narrows what an agent reads through the paths Bytebase masks; it is not
a confidentiality boundary.
+ capabilityUnreadable:
+ type: boolean
+ title: capability_unreadable
+ description: |-
+ True when the row carries a capability key that this build cannot resolve
+ to a ceiling. An enum name a newer release wrote is the legitimate trigger,
+ during a rolling upgrade; a hand-edited token reaches the same state.
+ False for every readable row, including one that was never configured.
+
+ The capability field cannot carry this on its own: the unmarshaler discards
+ an enum name it does not know, so an unreadable row and a never-configured
+ one both arrive as CAPABILITY_UNSPECIFIED, while MCP is refused for the
+ first and served at READ_WRITE for the second. A client reading only the
+ capability shows the most permissive ceiling over a workspace where every
+ MCP connection is being refused.
+
+ A row protojson cannot parse at all is NOT this state. There is no ceiling
+ in it to describe, so the read fails instead, and repairing it needs an
+ operator rather than this field.
+
+ The stored token itself is deliberately not returned. Telling a typo apart
+ from a value a newer release wrote would only pay off if this enum grew,
+ and it has not: its one reserved slot held a tier removed before any
+ release shipped it.
+
+ Set the row right by writing value.mcp.capability. Any other path is
+ refused while this is true, because the merge that saved it would erase the
+ value nobody could read.
title: MCPSetting
additionalProperties: false
description: |-
diff --git a/backend/api/v1/mcp_info.go b/backend/api/v1/mcp_info.go
index a53ebb537b..5b132541e6 100644
--- a/backend/api/v1/mcp_info.go
+++ b/backend/api/v1/mcp_info.go
@@ -236,6 +236,15 @@ func mcpMaskingSupport(engine storepb.Engine) v1pb.MCPEngineEnforcement_Masking
// mcpEngineNote carries the cases where a per-engine answer is the floor rather
// than the whole story.
+//
+// The console does not render this string: it keys off the engine and reads
+// settings.mcp.contents.notes.<engine> so the caveat is translated. Reword here
+// and the locale files need the same edit. Adding a note for a new engine
+// without its locale entry degrades to a line saying a caveat exists and to
+// reload, which is also what an older bundle shows against a newer server — it
+// never puts this English in a non-English console. An agent reading
+// GetMCPInfo does get this text, which is why it stays prose rather than
+// becoming an enum.
func mcpEngineNote(engine storepb.Engine) string {
if engine == storepb.Engine_REDSHIFT {
return "Outside a datashare database the driver also opens the session read-only. " +
diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.go
index 6038a9143b..4c8cfa7d18 100644
--- a/backend/api/v1/setting_service.go
+++ b/backend/api/v1/setting_service.go
@@ -66,11 +66,20 @@ func (s *SettingService) ListSettings(ctx context.Context, _ *connect.Request[v1
}
response := &v1pb.ListSettingsResponse{}
+ workspaceID := common.GetWorkspaceIDFromContext(ctx)
stored := map[storepb.SettingName]bool{}
for _, setting := range settings {
if s.isSettingDisallowed(setting.Name) {
continue
}
+ // The MCP setting is served below, from its own reader. The bulk read
+ // gives the parsed message and nothing else, and serving that would
+ // report a row whose capability this build cannot resolve as a
+ // never-configured workspace — the permissive default over one that is
+ // refusing every connection.
+ if setting.Name == storepb.SettingName_MCP {
+ continue
+ }
stored[setting.Name] = true
settingMessage, err := convertToSettingMessage(setting)
if err != nil {
@@ -78,11 +87,21 @@ func (s *SettingService) ListSettings(ctx context.Context, _ *connect.Request[v1
}
response.Settings = append(response.Settings, settingMessage)
}
- workspaceID := common.GetWorkspaceIDFromContext(ctx)
for _, name := range alwaysPresentSettings {
if stored[name] || s.isSettingDisallowed(name) {
continue
}
+ // One reader for the MCP setting, so a list and a get cannot describe
+ // the same row two ways — the unreadable state only one of them carried
+ // is the difference an admin acts on.
+ if name == storepb.SettingName_MCP {
+ settingMessage, err := s.mcpSettingMessage(ctx, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ response.Settings = append(response.Settings, settingMessage)
+ continue
+ }
settingMessage, err := convertToSettingMessage(emptySetting(name, workspaceID))
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to convert setting message: %v", err))
@@ -148,6 +167,14 @@ func (s *SettingService) GetSetting(ctx context.Context, request *connect.Reques
return nil, err
}
+ if storeSettingName == storepb.SettingName_MCP {
+ message, err := s.mcpSettingMessage(ctx, common.GetWorkspaceIDFromContext(ctx))
+ if err != nil {
+ return nil, err
+ }
+ return connect.NewResponse(message), nil
+ }
+
setting, err := s.store.GetSetting(ctx, common.GetWorkspaceIDFromContext(ctx), storeSettingName)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get setting: %v", err))
@@ -205,6 +232,18 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Req
}
workspaceID := common.GetWorkspaceIDFromContext(ctx)
+
+ // The MCP setting dispatches before the read below, not after. That read
+ // parses the stored row, and a ceiling this build cannot parse fails it —
+ // which would refuse the write that repairs the row, on the one path an
+ // admin has to repair it (BOT-107). updateMCPSetting needs nothing from it:
+ // it reads the row again under a lock, and takes its audit before-image
+ // from that locked read rather than from the cache this one consults.
+ if storeSettingName == storepb.SettingName_MCP {
+ s.stampMCPAuditBefore(ctx, workspaceID)
+ return s.updateMCPSetting(ctx, request, workspaceID)
+ }
+
existedSetting, err := s.store.GetSetting(ctx, workspaceID, storeSettingName)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to find setting %s with error: %v", settingName, err))
@@ -486,8 +525,6 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Req
}
storeSettingValue = environmentSetting
- case storepb.SettingName_MCP:
- return s.updateMCPSetting(ctx, request, workspaceID)
case storepb.SettingName_EMAIL:
if s.profile.SaaS {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("email setting cannot be changed in SaaS mode"))
@@ -1127,6 +1164,94 @@ func validateAnnouncementTheme(t *storepb.WorkspaceProfileSetting_Announcement_A
return nil
}
+// mcpSettingMessage answers the MCP setting from the row itself, carrying the
+// unreadable state the parsed value cannot.
+//
+// Uncached, unlike its sibling settings: the setting cache has no TTL and only
+// in-process writes refresh it, while every way a capability becomes unreadable
+// — a hand edit, a newer replica during a rolling upgrade — happens out of
+// band. A cached copy would show an admin the ceiling that was readable before
+// the edit, over a workspace where MCP is now refused every connection. The
+// enforcement gate reads the same row the same way
+// (store.GetMCPSettingsUncached).
+func (s *SettingService) mcpSettingMessage(ctx context.Context, workspaceID string) (*v1pb.Setting, error) {
+ raw, exists, err := s.store.RawSettingValue(ctx, workspaceID, storepb.SettingName_MCP)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get setting: %v", err))
+ }
+ stored := &storepb.MCPSetting{}
+ if exists {
+ if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(raw), stored); err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("the mcp setting does not parse: %v", err))
+ }
+ }
+ message, err := convertToSettingMessage(&store.SettingMessage{
+ Name: storepb.SettingName_MCP,
+ Workspace: workspaceID,
+ Value: stored,
+ })
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to convert setting message: %v", err))
+ }
+ message.GetValue().GetMcp().CapabilityUnreadable = mcpCapabilityUnreadable(raw, exists, stored)
+ return message, nil
+}
+
+// mcpCapabilityUnreadable reports whether this build can resolve a ceiling from
+// the stored row.
+//
+// True when the row carries a capability key but protojson leaves the parsed
+// capability unspecified. An enum name a newer release wrote is the legitimate
+// trigger — a rolling upgrade — and a hand-edited token reaches the same state:
+// null, "", and an explicit CAPABILITY_UNSPECIFIED all parse away to unset
+// without erroring (TestMCPUnreadableCeilingIsVisibleToTheAdmin covers all
+// four).
+//
+// An absent key gives the same parsed value and means the opposite: never
+// configured, which resolves to the READ_WRITE default rather than a refusal
+// (BOT-100). A row that does not parse at all never gets this far; the read
+// fails, because there is no ceiling in it to describe.
+//
+// The page and the write path's repair guard both read this. Two copies drift
+// into a row the resolver refuses while the console reports a ceiling, or a
+// repair the page offers and the write rejects.
+func mcpCapabilityUnreadable(raw string, exists bool, stored *storepb.MCPSetting) bool {
+ if !exists || stored.GetCapability() != storepb.MCPSetting_CAPABILITY_UNSPECIFIED {
+ return false
+ }
+ key, err := store.RawMCPCapability(raw)
+ // No capability key is the ordinary never-configured state — a first edit
+ // that set only the masking toggle leaves exactly that — and resolves
+ // READ_WRITE.
+ return err == nil && key != ""
+}
+
+// stampMCPAuditBefore records the pre-lock MCP before-image on the audit row.
+//
+// The generic path below stamps one from the read it does before the merge.
+// MCP dispatches above that read, so without this a refused write — an
+// unreadable ceiling, a rejected mask, a dry run — audits with no before-image
+// at all, and a refusal is where the ceiling that was in force matters most.
+// updateMCPSetting overwrites it from the locked row when the write lands,
+// which is the value that was true at commit time.
+func (s *SettingService) stampMCPAuditBefore(ctx context.Context, workspaceID string) {
+ setServiceData, ok := common.GetSetServiceDataFromContext(ctx)
+ if !ok {
+ return
+ }
+ message, err := s.mcpSettingMessage(ctx, workspaceID)
+ if err != nil {
+ slog.Warn("audit: failed to read the mcp setting for the before-image", log.BBError(err))
+ return
+ }
+ p, err := anypb.New(message)
+ if err != nil {
+ slog.Warn("audit: failed to convert to anypb.Any", log.BBError(err))
+ return
+ }
+ setServiceData(p)
+}
+
// updateMCPSetting merges the named update-mask paths into the stored MCP
// setting under a row lock. Each path sets one field, so an admin changing the
// masking toggle does not have to resend a ceiling they are not changing.
@@ -1152,11 +1277,24 @@ func (s *SettingService) updateMCPSetting(ctx context.Context, request *connect.
repairsCapability := slices.Contains(request.Msg.UpdateMask.Paths, "value.mcp.capability")
var lockedBefore *storepb.MCPSetting
+ // The v1-only capability_unreadable the before-image cannot carry on its
+ // own: lockedBefore is a store message, and that field exists to tell a
+ // repair of an unreadable ceiling apart from configuring a workspace that
+ // never had one. Without it the audit row for the two is byte-identical.
+ var lockedBeforeUnreadable bool
apply := func(current proto.Message, raw []byte) (proto.Message, error) {
existing, ok := current.(*storepb.MCPSetting)
if !ok {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("invalid setting value type for %s", storepb.SettingName_MCP))
}
+ // Captured before anything below can refuse. Every decision here is made
+ // against the LOCKED row, so that is what the audit row has to show —
+ // a refusal most of all, since the refusal names a ceiling only the
+ // locked read saw. The pre-lock stamp can already be describing a value
+ // another replica has replaced, which is the same reason the guard
+ // below reads raw rather than a pre-flight.
+ lockedBefore = proto.CloneOf(existing)
+ lockedBeforeUnreadable = mcpCapabilityUnreadable(string(raw), len(raw) > 0, existing)
// A key this build does not define would be deleted by the merge below:
// the unmarshaler discarded it, so re-marshalling writes the row back
// without it. During a rolling upgrade that is an older replica erasing
@@ -1185,18 +1323,14 @@ func (s *SettingService) updateMCPSetting(ctx context.Context, request *connect.
// Read from the locked row, not before the lock: a newer replica during
// a rolling upgrade can write a name this build has never heard of, and
// a pre-flight would have checked a value that is no longer there.
- if !repairsCapability && len(raw) > 0 && existing.GetCapability() == storepb.MCPSetting_CAPABILITY_UNSPECIFIED {
- stored, err := store.RawMCPCapability(string(raw))
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to read the stored mcp capability: %v", err))
- }
- if stored != "" {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf(
- "this workspace's stored MCP capability is not one this build understands, and saving another field would erase it. "+
- "Set value.mcp.capability in the same request to repair it"))
- }
+ //
+ // The same predicate the page reads, so a row cannot be offered as
+ // repairable on one and refused on the other.
+ if lockedBeforeUnreadable && !repairsCapability {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf(
+ "this workspace's stored MCP capability is not one this build understands, and saving another field would erase it. "+
+ "Set value.mcp.capability in the same request to repair it"))
}
- lockedBefore = proto.CloneOf(existing)
merged := proto.CloneOf(existing)
for _, path := range request.Msg.UpdateMask.Paths {
switch path {
@@ -1219,9 +1353,8 @@ func (s *SettingService) updateMCPSetting(ctx context.Context, request *connect.
// on a request that asked for nothing would be the kill switch turning
// itself off.
if request.Msg.ValidateOnly {
- // The same merge against the same raw view the locked path would see,
- // so a dry run cannot report success on a request the real write
- // refuses.
+ // The same parse and the same apply the locked path runs, so the dry run
+ // cannot disagree with the write it stands in for in either direction.
raw, _, err := s.store.RawSettingValue(ctx, workspaceID, storepb.SettingName_MCP)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to read mcp setting: %v", err))
@@ -1256,16 +1389,15 @@ func (s *SettingService) updateMCPSetting(ctx context.Context, request *connect.
if err := s.store.EnsureSettingRow(ctx, workspaceID, storepb.SettingName_MCP); err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to create mcp setting: %v", err))
}
- setting, err := s.store.UpdateSettingAtomic(ctx, workspaceID, storepb.SettingName_MCP, apply, nil)
- if err != nil {
- var connectErr *connect.Error
- if errors.As(err, &connectErr) {
- return nil, err
+ // Overwrites the pre-lock stamp on either outcome. apply captured this from
+ // the locked row, so it describes the state the write actually decided
+ // against; the pre-lock stamp stays only for failures that never reach the
+ // lock at all.
+ stampLocked := func() {
+ setServiceData, ok := common.GetSetServiceDataFromContext(ctx)
+ if !ok || lockedBefore == nil {
+ return
}
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to set setting: %v", err))
- }
-
- if setServiceData, ok := common.GetSetServiceDataFromContext(ctx); ok && lockedBefore != nil {
v1pbSetting, err := convertToSettingMessage(&store.SettingMessage{
Name: storepb.SettingName_MCP,
Workspace: workspaceID,
@@ -1273,12 +1405,27 @@ func (s *SettingService) updateMCPSetting(ctx context.Context, request *connect.
})
if err != nil {
slog.Warn("audit: failed to convert to v1.Setting", log.BBError(err))
- } else if p, err := anypb.New(v1pbSetting); err != nil {
+ return
+ }
+ v1pbSetting.GetValue().GetMcp().CapabilityUnreadable = lockedBeforeUnreadable
+ p, err := anypb.New(v1pbSetting)
+ if err != nil {
slog.Warn("audit: failed to convert to anypb.Any", log.BBError(err))
- } else {
- setServiceData(p)
+ return
}
+ setServiceData(p)
+ }
+
+ setting, err := s.store.UpdateSettingAtomic(ctx, workspaceID, storepb.SettingName_MCP, apply, nil)
+ if err != nil {
+ stampLocked()
+ var connectErr *connect.Error
+ if errors.As(err, &connectErr) {
+ return nil, err
+ }
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to set setting: %v", err))
}
+ stampLocked()
settingMessage, err := convertToSettingMessage(setting)
if err != nil {
diff --git a/backend/generated-go/v1/setting_service.pb.go b/backend/generated-go/v1/setting_service.pb.go
index a6dda457db..2506dc5247 100644
--- a/backend/generated-go/v1/setting_service.pb.go
+++ b/backend/generated-go/v1/setting_service.pb.go
@@ -1346,8 +1346,33 @@ type MCPSetting struct {
// It narrows what an agent reads through the paths Bytebase masks; it is not
// a confidentiality boundary.
IgnoreMaskingExemptions bool `protobuf:"varint,2,opt,name=ignore_masking_exemptions,json=ignoreMaskingExemptions,proto3" json:"ignore_masking_exemptions,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ // True when the row carries a capability key that this build cannot resolve
+ // to a ceiling. An enum name a newer release wrote is the legitimate trigger,
+ // during a rolling upgrade; a hand-edited token reaches the same state.
+ // False for every readable row, including one that was never configured.
+ //
+ // The capability field cannot carry this on its own: the unmarshaler discards
+ // an enum name it does not know, so an unreadable row and a never-configured
+ // one both arrive as CAPABILITY_UNSPECIFIED, while MCP is refused for the
+ // first and served at READ_WRITE for the second. A client reading only the
+ // capability shows the most permissive ceiling over a workspace where every
+ // MCP connection is being refused.
+ //
+ // A row protojson cannot parse at all is NOT this state. There is no ceiling
+ // in it to describe, so the read fails instead, and repairing it needs an
+ // operator rather than this field.
+ //
+ // The stored token itself is deliberately not returned. Telling a typo apart
+ // from a value a newer release wrote would only pay off if this enum grew,
+ // and it has not: its one reserved slot held a tier removed before any
+ // release shipped it.
+ //
+ // Set the row right by writing value.mcp.capability. Any other path is
+ // refused while this is true, because the merge that saved it would erase the
+ // value nobody could read.
+ CapabilityUnreadable bool `protobuf:"varint,3,opt,name=capability_unreadable,json=capabilityUnreadable,proto3" json:"capability_unreadable,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *MCPSetting) Reset() {
@@ -1394,6 +1419,13 @@ func (x *MCPSetting) GetIgnoreMaskingExemptions() bool {
return false
}
+func (x *MCPSetting) GetCapabilityUnreadable() bool {
+ if x != nil {
+ return x.CapabilityUnreadable
+ }
+ return false
+}
+
type SQLEditorThemeSetting struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
@@ -3646,13 +3678,14 @@ const file_v1_setting_service_proto_rawDesc = "" +
"\x18require_uppercase_letter\x18\x04 \x01(\bR\x16requireUppercaseLetter\x12:\n" +
"\x19require_special_character\x18\x05 \x01(\bR\x17requireSpecialCharacter\x12Q\n" +
"&require_reset_password_for_first_login\x18\x06 \x01(\bR!requireResetPasswordForFirstLogin\x12F\n" +
- "\x11password_rotation\x18\a \x01(\v2\x19.google.protobuf.DurationR\x10passwordRotationJ\x04\b\x0f\x10\x10J\x04\b\x1a\x10\x1bJ\x04\b\x10\x10\x11R\x0emcp_capability\"\xe9\x01\n" +
+ "\x11password_rotation\x18\a \x01(\v2\x19.google.protobuf.DurationR\x10passwordRotationJ\x04\b\x0f\x10\x10J\x04\b\x1a\x10\x1bJ\x04\b\x10\x10\x11R\x0emcp_capability\"\xa3\x02\n" +
"\n" +
"MCPSetting\x12B\n" +
"\n" +
"capability\x18\x01 \x01(\x0e2\".bytebase.v1.MCPSetting.CapabilityR\n" +
"capability\x12:\n" +
- "\x19ignore_masking_exemptions\x18\x02 \x01(\bR\x17ignoreMaskingExemptions\"[\n" +
+ "\x19ignore_masking_exemptions\x18\x02 \x01(\bR\x17ignoreMaskingExemptions\x128\n" +
+ "\x15capability_unreadable\x18\x03 \x01(\bB\x03\xe0A\x03R\x14capabilityUnreadable\"[\n" +
"\n" +
"Capability\x12\x1a\n" +
"\x16CAPABILITY_UNSPECIFIED\x10\x00\x12\f\n" +
diff --git a/backend/generated-go/v1/setting_service_equal.pb.go b/backend/generated-go/v1/setting_service_equal.pb.go
index d87de87740..8c76add619 100644
--- a/backend/generated-go/v1/setting_service_equal.pb.go
+++ b/backend/generated-go/v1/setting_service_equal.pb.go
@@ -425,6 +425,9 @@ func (x *MCPSetting) Equal(y *MCPSetting) bool {
if x.IgnoreMaskingExemptions != y.IgnoreMaskingExemptions {
return false
}
+ if x.CapabilityUnreadable != y.CapabilityUnreadable {
+ return false
+ }
return true
}
diff --git a/backend/store/setting.go b/backend/store/setting.go
index 61675bf865..4b6c340ee0 100644
--- a/backend/store/setting.go
+++ b/backend/store/setting.go
@@ -440,7 +440,27 @@ func (s *Store) EnsureSettingRow(ctx context.Context, workspace string, name sto
// back with that value silently deleted. A caller that must not do that reads
// the raw bytes, and reads them from the locked row rather than a pre-flight, so
// there is no window for a concurrent writer to slip a value in between.
+//
+// A row this build cannot parse is refused: the only message this could hand
+// apply is the zero value, and a merging apply would write that back — a
+// caller that sets one field on current and returns it (RotateDirectorySyncToken)
+// would erase everything else the row held.
func (s *Store) UpdateSettingAtomic(ctx context.Context, workspace string, name storepb.SettingName, apply func(current proto.Message, raw []byte) (proto.Message, error), postCommit func(current *SettingMessage)) (*SettingMessage, error) {
+ return s.writeSettingAtomic(ctx, workspace, name, func(raw string) (proto.Message, error) {
+ current, err := getSettingMessage(name)
+ if err != nil {
+ return nil, err
+ }
+ if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(raw), current); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal setting %s", name)
+ }
+ return apply(current, []byte(raw))
+ }, postCommit)
+}
+
+// writeSettingAtomic locks the row, asks next for the value to store, and
+// writes it in the same transaction.
+func (s *Store) writeSettingAtomic(ctx context.Context, workspace string, name storepb.SettingName, next func(raw string) (proto.Message, error), postCommit func(current *SettingMessage)) (*SettingMessage, error) {
tx, err := s.GetDB().BeginTx(ctx, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to begin transaction")
@@ -461,20 +481,12 @@ func (s *Store) UpdateSettingAtomic(ctx context.Context, workspace string, name
}
return nil, errors.Wrapf(err, "failed to lock setting %s", name)
}
- current, err := getSettingMessage(name)
- if err != nil {
- return nil, err
- }
- if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(valueString), current); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal setting %s", name)
- }
-
- next, err := apply(current, []byte(valueString))
+ value, err := next(valueString)
if err != nil {
return nil, err
}
- nextBytes, err := protojson.Marshal(next)
+ nextBytes, err := protojson.Marshal(value)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal setting value")
}
@@ -498,7 +510,7 @@ func (s *Store) UpdateSettingAtomic(ctx context.Context, workspace string, name
return nil, errors.Wrap(err, "failed to commit transaction")
}
s.publishSetting(ctx, workspace, name, postCommit)
- return &SettingMessage{Name: name, Workspace: workspace, Value: next}, nil
+ return &SettingMessage{Name: name, Workspace: workspace, Value: value}, nil
}
// publishSetting refreshes the served state for a setting after a committed
@@ -735,6 +747,15 @@ func UnknownSettingKeys(raw string, m proto.Message) ([]string, error) {
// rejects an explicit UNSPECIFIED, so no Bytebase write produces this key with
// that value — only a hand-edited row does, and there it is indistinguishable
// from a typo.
+//
+// Read with encoding/json rather than the shared protojson unmarshaler, and
+// that is forced, not legacy: this recovers what protojson DISCARDED.
+// common.ProtojsonUnmarshaler sets DiscardUnknown, so an enum name this build
+// does not know leaves no trace in the message, and protojson exposes no way to
+// ask what token a field carried. A strict unmarshaler is not the alternative —
+// it does reject the unknown enum name, but it rejects an unknown FIELD with
+// the same error, and tolerating a field a newer replica wrote is the rolling
+// upgrade this build has to survive.
func RawMCPCapability(value string) (string, error) {
var fields map[string]json.RawMessage
if err := json.Unmarshal([]byte(value), &fields); err != nil {
diff --git a/backend/store/setting_atomic_test.go b/backend/store/setting_atomic_test.go
index d70afac74c..81f359cb2b 100644
--- a/backend/store/setting_atomic_test.go
+++ b/backend/store/setting_atomic_test.go
@@ -491,3 +491,60 @@ func TestListSettingsSkipsNamesThisBuildDoesNotKnow(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, profile)
}
+
+// TestListSettingsRefusesAnUnparsedRow pins that a row this build cannot parse
+// fails the read rather than reading back absent.
+//
+// GetSettingUncached reads through this, so a skipped row would reach 24
+// callers as "no such setting" — which resolves to the setting's default, and
+// enforcement would then run one policy while the console showed another. That
+// is BOT-100's defect widened to every setting.
+func TestListSettingsRefusesAnUnparsedRow(t *testing.T) {
+ // Cache off: the fixture's own write would otherwise serve every read from
+ // memory, and the point is what the database hands back.
+ ctx, db, s := newSettingAtomicFixtureWithCache(t, false)
+
+ // By hand, because no store call writes a value its own message rejects.
+ _, err := db.ExecContext(ctx,
+ `UPDATE setting SET value = '{"externalUrl": 5}' WHERE name = 'WORKSPACE_PROFILE' AND workspace = 'default'`)
+ require.NoError(t, err)
+
+ _, err = s.ListSettings(ctx, &store.FindSettingMessage{Workspace: "default"})
+ require.Error(t, err, "an unparseable row fails the list")
+
+ setting, err := s.GetSettingUncached(ctx, "default", storepb.SettingName_WORKSPACE_PROFILE)
+ require.Error(t, err, "the read must not report a row it cannot parse as absent")
+ require.Nil(t, setting)
+}
+
+// TestUpdateSettingAtomicRefusesAnUnparsedRow pins that a row this build cannot
+// parse never reaches apply.
+//
+// apply merges onto the message it is handed, and for such a row the only
+// message available is the zero value. RotateDirectorySyncToken sets one field
+// on current and returns it, so letting it through would write back a
+// WorkspaceProfileSetting with the signup settings, password restrictions and
+// announcements erased.
+func TestUpdateSettingAtomicRefusesAnUnparsedRow(t *testing.T) {
+ // Cache off: the point is what the locked row hands the writer.
+ ctx, db, s := newSettingAtomicFixtureWithCache(t, false)
+
+ // By hand, because no store call writes a value its own message rejects.
+ _, err := db.ExecContext(ctx,
+ `UPDATE setting SET value = '{"externalUrl": 5}' WHERE name = 'WORKSPACE_PROFILE' AND workspace = 'default'`)
+ require.NoError(t, err)
+
+ applied := false
+ _, err = s.UpdateSettingAtomic(ctx, "default", storepb.SettingName_WORKSPACE_PROFILE,
+ func(current proto.Message, _ []byte) (proto.Message, error) {
+ applied = true
+ return current, nil
+ }, nil)
+ require.Error(t, err, "a row this build cannot parse must not reach a merging apply")
+ require.False(t, applied, "apply must not be called at all")
+
+ var stored string
+ require.NoError(t, db.QueryRowContext(ctx,
+ `SELECT value::text FROM setting WHERE name = 'WORKSPACE_PROFILE' AND workspace = 'default'`).Scan(&stored))
+ require.Contains(t, stored, "externalUrl", "the refused write must leave the row as it found it")
+}
diff --git a/backend/tests/mcp_audit_provenance_test.go b/backend/tests/mcp_audit_provenance_test.go
index 6e51934f03..086e701104 100644
--- a/backend/tests/mcp_audit_provenance_test.go
+++ b/backend/tests/mcp_audit_provenance_test.go
@@ -55,6 +55,10 @@ func TestMCPAuditProvenance(t *testing.T) {
workspace := memberLogin.Msg.GetUser().GetWorkspace()
a.NotEmpty(workspace)
+ // CreateSheet below is a WRITE method. Pinned so this test does not depend
+ // on the resolved default; it is about what an audit row carries.
+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))
+
// The member consents a real OAuth grant; every audit row the session
// produces must carry this grant's stored scope and resource verbatim.
mcpToken, clientID := mintMCPOAuthToken(t, ctl, memberLogin.Msg.Token)
diff --git a/backend/tests/mcp_capability_setting_test.go b/backend/tests/mcp_capability_setting_test.go
index ec7729d714..3911e12e48 100644
--- a/backend/tests/mcp_capability_setting_test.go
+++ b/backend/tests/mcp_capability_setting_test.go
@@ -37,14 +37,22 @@ func (ctl *controller) updateMCPCapability(ctx context.Context, capability v1pb.
return err
}
-func (ctl *controller) getMCPCapability(ctx context.Context) (v1pb.MCPSetting_Capability, error) {
+func (ctl *controller) getMCPSetting(ctx context.Context) (*v1pb.MCPSetting, error) {
resp, err := ctl.settingServiceClient.GetSetting(ctx, connect.NewRequest(&v1pb.GetSettingRequest{
Name: "settings/" + v1pb.Setting_MCP.String(),
}))
+ if err != nil {
+ return nil, err
+ }
+ return resp.Msg.Value.GetMcp(), nil
+}
+
+func (ctl *controller) getMCPCapability(ctx context.Context) (v1pb.MCPSetting_Capability, error) {
+ setting, err := ctl.getMCPSetting(ctx)
if err != nil {
return v1pb.MCPSetting_CAPABILITY_UNSPECIFIED, err
}
- return resp.Msg.Value.GetMcp().GetCapability(), nil
+ return setting.GetCapability(), nil
}
// currentWorkspaceID returns the id the setting rows are keyed by. setting has
@@ -144,6 +152,7 @@ func TestMCPCapabilitySettingRoundTrip(t *testing.T) {
// settings/MCP exist?" on a workspace that never touched it. Get, List and
// Update have to agree: a client that reads the resource and then cannot patch
// it with default update semantics has been told two different things.
+
func TestMCPSettingIsPresentBeforeItIsConfigured(t *testing.T) {
t.Parallel()
a := require.New(t)
@@ -245,6 +254,185 @@ func TestMCPUnreadableCeilingSurvivesAToggleOnlyUpdate(t *testing.T) {
a.NoError(ctl.setIgnoreMaskingExemptions(ctx, true), "and the toggle saves once the ceiling is readable")
}
+// TestMCPUnreadableCeilingIsVisibleToTheAdmin is the read-path half of the same
+// rule, and the defect BOT-100 records. Enforcement inspects the row's own
+// capability key and refuses; the settings API parses with the shared
+// unmarshaler, which drops an enum name it does not know, so the same row read
+// two ways said READ_WRITE — the most permissive ceiling — over a workspace
+// refusing every MCP connection.
+//
+// The second-order effect is the one an admin feels: with the page already
+// showing Read-write, picking Read-write changes nothing, so the row could not
+// be repaired to READ_WRITE in one save at all.
+func TestMCPUnreadableCeilingIsVisibleToTheAdmin(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_DISABLED))
+
+ workspaceID := currentWorkspaceID(ctx, t, ctl)
+ db, err := sql.Open("pgx", ctl.profile.PgURL)
+ a.NoError(err)
+ defer db.Close()
+ _, err = db.ExecContext(ctx, `
+ UPDATE setting SET value = jsonb_set(value, '{capability}', '"READ_ONLYY"')
+ WHERE workspace = $1 AND name = 'MCP';
+ `, workspaceID)
+ a.NoError(err)
+
+ setting, err := ctl.getMCPSetting(ctx)
+ a.NoError(err)
+ a.True(setting.GetCapabilityUnreadable(),
+ "the admin has to be told, or the page describes a ceiling nobody is enforcing")
+ a.Equal(v1pb.MCPSetting_CAPABILITY_UNSPECIFIED, setting.GetCapability(),
+ "and the parsed capability stays unset, so no reader mistakes it for a choice")
+
+ // Every token the store treats as unreadable, not just the mistyped name.
+ // Each of these unmarshals away to unset without erroring, so a reader that
+ // only looked at the parsed capability would report the permissive default
+ // over a workspace refusing every connection.
+ for _, token := range []string{`null`, `""`, `"CAPABILITY_UNSPECIFIED"`} {
+ _, err = db.ExecContext(ctx, `
+ UPDATE setting SET value = jsonb_set(value, '{capability}', $2::jsonb)
+ WHERE workspace = $1 AND name = 'MCP';
+ `, workspaceID, token)
+ a.NoError(err, token)
+
+ setting, err = ctl.getMCPSetting(ctx)
+ a.NoError(err, token)
+ a.True(setting.GetCapabilityUnreadable(),
+ "%s is a ceiling the store refuses; reporting it as readable is the defect this field ends", token)
+ a.Equal(v1pb.MCPSetting_CAPABILITY_UNSPECIFIED, setting.GetCapability(), token)
+ }
+
+ // A wrong-TYPED token is a different state, and deliberately not a
+ // repairable one. It fails the whole unmarshal rather than just the enum,
+ // so there is no ceiling in the row to describe and no supported writer
+ // that produces one — the read says so plainly instead of offering a fix
+ // it would need a raw-replacement path to deliver.
+ for _, token := range []string{`{}`, `true`, `1.5`, `[]`} {
+ _, err = db.ExecContext(ctx, `
+ UPDATE setting SET value = jsonb_set(value, '{capability}', $2::jsonb)
+ WHERE workspace = $1 AND name = 'MCP';
+ `, workspaceID, token)
+ a.NoError(err, token)
+
+ _, err = ctl.getMCPSetting(ctx)
+ a.Error(err, "%s carries no ceiling to report, so the read fails rather than inventing one", token)
+ }
+
+ // Back to the mistyped name for the repair below.
+ _, err = db.ExecContext(ctx, `
+ UPDATE setting SET value = jsonb_set(value, '{capability}', '"READ_ONLYY"')
+ WHERE workspace = $1 AND name = 'MCP';
+ `, workspaceID)
+ a.NoError(err)
+
+ // The same row through the list surface: a client that discovers the
+ // setting there and then patches it must not be told a different story.
+ list, err := ctl.settingServiceClient.ListSettings(ctx, connect.NewRequest(&v1pb.ListSettingsRequest{}))
+ a.NoError(err)
+ var listed *v1pb.MCPSetting
+ for _, entry := range list.Msg.Settings {
+ if entry.Name == "settings/"+v1pb.Setting_MCP.String() {
+ listed = entry.Value.GetMcp()
+ }
+ }
+ a.NotNil(listed)
+ a.True(listed.GetCapabilityUnreadable())
+
+ // One save repairs it, to the most permissive ceiling included — the pick
+ // the old shape could not express.
+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))
+ repaired, err := ctl.getMCPSetting(ctx)
+ a.NoError(err)
+ a.Equal(v1pb.MCPSetting_READ_WRITE, repaired.GetCapability())
+ a.False(repaired.GetCapabilityUnreadable(), "a readable row carries no unreadable value")
+
+ // A workspace that never configured MCP is not the same state and must not
+ // be reported as one: it resolves READ_WRITE and nothing is wrong with it.
+ _, err = db.ExecContext(ctx, `
+ DELETE FROM setting WHERE workspace = $1 AND name = 'MCP';
+ `, workspaceID)
+ a.NoError(err)
+ unconfigured, err := ctl.getMCPSetting(ctx)
+ a.NoError(err)
+ a.False(unconfigured.GetCapabilityUnreadable())
+ a.Equal(v1pb.MCPSetting_CAPABILITY_UNSPECIFIED, unconfigured.GetCapability())
+}
+
+// TestMCPRepairKeepsTheMaskingToggle pins that fixing the ceiling does not
+// disarm the masking toggle. Repairing a policy must change the one field the
+// request names; handing users' unmasking exemptions back to MCP sessions as a
+// side effect of a ceiling fix would be a silent loosening.
+func TestMCPRepairKeepsTheMaskingToggle(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ workspaceID := currentWorkspaceID(ctx, t, ctl)
+ db, err := sql.Open("pgx", ctl.profile.PgURL)
+ a.NoError(err)
+ defer db.Close()
+
+ _, err = db.ExecContext(ctx, `
+ INSERT INTO setting (name, workspace, value)
+ VALUES ('MCP', $1, '{"capability": "READ_ONLYY", "ignoreMaskingExemptions": true}')
+ ON CONFLICT (name, workspace) DO UPDATE SET value = EXCLUDED.value;
+ `, workspaceID)
+ a.NoError(err)
+
+ // The toggle is readable even though the ceiling is not, so the page must
+ // show it rather than reporting the workspace as not ignoring exemptions.
+ setting, err := ctl.getMCPSetting(ctx)
+ a.NoError(err)
+ a.True(setting.GetCapabilityUnreadable(), "the ceiling is the unreadable part")
+ a.True(setting.GetIgnoreMaskingExemptions(),
+ "the toggle is readable even though the ceiling is not")
+
+ // Repairing the ceiling must not disarm the toggle.
+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_ONLY))
+ repaired, err := ctl.getMCPSetting(ctx)
+ a.NoError(err)
+ a.Equal(v1pb.MCPSetting_READ_ONLY, repaired.GetCapability())
+ a.True(repaired.GetIgnoreMaskingExemptions(),
+ "repairing the ceiling must not return exemptions to MCP sessions")
+ a.False(repaired.GetCapabilityUnreadable())
+}
+
+// TestMCPToggleOnlyRowIsNotUnreadable pins the other direction. A first edit
+// that sets only the masking toggle leaves a row with no capability key at all,
+// which is the ordinary never-configured state resolving READ_WRITE — not a row
+// an admin has to repair.
+func TestMCPToggleOnlyRowIsNotUnreadable(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ a.NoError(ctl.setIgnoreMaskingExemptions(ctx, true))
+
+ setting, err := ctl.getMCPSetting(ctx)
+ a.NoError(err)
+ a.True(setting.GetIgnoreMaskingExemptions())
+ a.False(setting.GetCapabilityUnreadable(),
+ "no capability key is never-configured, not unreadable; claiming otherwise "+
+ "tells the admin every MCP connection is refused when none is")
+ a.Equal(v1pb.MCPSetting_CAPABILITY_UNSPECIFIED, setting.GetCapability())
+}
+
// TestMCPUnknownFieldSurvivesAPartialUpdate is the mixed-version half of the
// same rule. An older replica parses the row with the shared unmarshaler, which
// discards what it cannot name, and re-marshalling writes the row back without
@@ -292,3 +480,61 @@ func TestMCPUnknownFieldSurvivesAPartialUpdate(t *testing.T) {
`, workspaceID).Scan(&present))
a.True(present, "and the field is still there")
}
+
+// TestMCPRefusedRepairAuditsTheCeilingThatCausedIt pins the before-image on a
+// refusal, which nothing else covers.
+//
+// updateMCPSetting decides everything against the LOCKED row — the guard reads
+// raw for exactly that reason — so the audit row for a refusal has to describe
+// that row too. It used to record only the pre-lock snapshot taken before
+// UpdateSetting dispatched, because the locked capture happened after the point
+// where a refusal returns.
+//
+// This covers the deterministic half. The stale case needs another replica to
+// write between the pre-lock read and the lock, and there is no injection point
+// for that in this package, so the fix is structural: the capture is now the
+// first statement in the callback and no refusal can return ahead of it.
+func TestMCPRefusedRepairAuditsTheCeilingThatCausedIt(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ workspace, err := ctl.workspaceServiceClient.GetWorkspace(ctx, connect.NewRequest(&v1pb.GetWorkspaceRequest{
+ Name: "workspaces/-",
+ }))
+ a.NoError(err)
+ workspaceID := currentWorkspaceID(ctx, t, ctl)
+
+ db, err := sql.Open("pgx", ctl.profile.PgURL)
+ a.NoError(err)
+ defer db.Close()
+ _, err = db.ExecContext(ctx, `
+ INSERT INTO setting (name, workspace, value) VALUES ('MCP', $1, '{"capability": "READ_ONLYY"}')
+ ON CONFLICT (name, workspace) DO UPDATE SET value = EXCLUDED.value;
+ `, workspaceID)
+ a.NoError(err)
+
+ // Refused: the toggle alone would marshal the row back without the ceiling.
+ err = ctl.setIgnoreMaskingExemptions(ctx, true)
+ a.Error(err)
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err))
+
+ resp, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{
+ Parent: workspace.Msg.Name,
+ Filter: `method == "/bytebase.v1.SettingService/UpdateSetting"`,
+ OrderBy: "create_time desc",
+ }))
+ a.NoError(err)
+ a.NotEmpty(resp.Msg.AuditLogs, "a refused MCP write still belongs in the audit log")
+
+ before := resp.Msg.AuditLogs[0].ServiceData
+ a.NotNil(before, "the refusal has to say which ceiling it was protecting")
+ setting := &v1pb.Setting{}
+ a.NoError(before.UnmarshalTo(setting))
+ a.True(setting.GetValue().GetMcp().GetCapabilityUnreadable(),
+ "the before-image must show the unreadable ceiling that caused the refusal")
+}
diff --git a/backend/tests/mcp_gate_test.go b/backend/tests/mcp_gate_test.go
index be3149f68b..71fc996b2a 100644
--- a/backend/tests/mcp_gate_test.go
+++ b/backend/tests/mcp_gate_test.go
@@ -46,14 +46,17 @@ func TestMCPGateServesAndRefusesByClass(t *testing.T) {
a.NoError(err)
projectName := project.Msg.Name
+ // Pinned so this test does not depend on the resolved default: the WRITE
+ // arm below is about what the gate serves at READ_WRITE.
+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))
+
session := openMCPSession(ctx, t, ctl, ctl.authInterceptor.token)
defer session.Close()
// READ: served under every ceiling that admits a connection at all.
a.Equal(http.StatusOK, callAPIStatus(ctx, t, session, "WorkspaceService/ListWorkspaces", nil))
- // WRITE: served because the workspace ceiling is unset, which resolves
- // READ_WRITE.
+ // WRITE: served because the ceiling above is READ_WRITE.
sheet := callAPIOnSession(ctx, t, session, "SheetService/CreateSheet", map[string]any{
"parent": projectName,
"sheet": map[string]any{"content": base64.StdEncoding.EncodeToString([]byte("SELECT 1;"))},
@@ -102,6 +105,11 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {
a.NoError(err)
projectName := project.Msg.Name
+ // CreateIssue is WRITE and the refusal under test is the one the class
+ // cannot express. Pinned so this test does not depend on the resolved
+ // default.
+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))
+
session := openMCPSession(ctx, t, ctl, ctl.authInterceptor.token)
defer session.Close()
@@ -197,6 +205,11 @@ func TestMCPCannotRunAnIssuelessRollout(t *testing.T) {
a.NoError(err)
defer ctl.Close(ctx)
+ // CreateRollout is WRITE and the refusal under test is the
+ // issueless-rollout guard. Pinned so this test does not depend on the
+ // resolved default.
+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))
+
pgContainer, err := provisionPgInstance(ctx, t)
a.NoError(err)
instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{
@@ -265,3 +278,47 @@ func TestMCPCannotRunAnIssuelessRollout(t *testing.T) {
a.NoError(err, "the guard binds MCP sessions and nothing else")
a.NotEmpty(consoleRollout.Msg.Name)
}
+
+// TestMCPAbsentRowResolvesReadWrite pins the one permissive default the
+// resolver has: a workspace that never configured MCP serves WRITE.
+//
+// Every other gate test now sets a ceiling explicitly, which is right — each is
+// about what a NAMED ceiling serves, and depending on the default made them say
+// less than their names claimed. That left nothing exercising the unset case on
+// the live path, so changing store.GetMCPSettingsUncached's whenUnset would
+// silently refuse writes for every workspace that has not configured MCP —
+// which today is all of them — with no test to say so.
+func TestMCPAbsentRowResolvesReadWrite(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ project, err := ctl.projectServiceClient.CreateProject(ctx, connect.NewRequest(&v1pb.CreateProjectRequest{
+ ProjectId: "mcp-unset",
+ Project: &v1pb.Project{Title: "MCP unset ceiling"},
+ }))
+ a.NoError(err)
+
+ // No setMCPCapability anywhere in this test: the absence IS the fixture.
+ setting, err := ctl.getMCPSetting(ctx)
+ a.NoError(err)
+ a.Equal(v1pb.MCPSetting_CAPABILITY_UNSPECIFIED, setting.GetCapability(),
+ "this test is about a workspace that never configured MCP")
+ a.False(setting.GetCapabilityUnreadable(),
+ "absent, not unreadable — the two resolve to opposite ceilings")
+
+ session := openMCPSession(ctx, t, ctl, ctl.authInterceptor.token)
+ defer session.Close()
+
+ sheet := callAPIOnSession(ctx, t, session, "SheetService/CreateSheet", map[string]any{
+ "parent": project.Msg.Name,
+ "sheet": map[string]any{"content": base64.StdEncoding.EncodeToString([]byte("SELECT 1;"))},
+ })
+ a.Equal(http.StatusOK, sheet.Status,
+ "an unconfigured workspace resolves READ_WRITE, so a WRITE method is served: %s", sheet.Error)
+}
diff --git a/backend/tests/mcp_migration_matrix_test.go b/backend/tests/mcp_migration_matrix_test.go
index ff90a23df1..c1715adf7c 100644
--- a/backend/tests/mcp_migration_matrix_test.go
+++ b/backend/tests/mcp_migration_matrix_test.go
@@ -185,6 +185,10 @@ func TestMCPMigrationGrantStateMatrix(t *testing.T) {
Project: &v1pb.Project{Title: "MCP grant matrix"},
}))
a.NoError(err)
+ // The probe below is a WRITE method. Pinned so this test does not depend on
+ // the resolved default; it is about which grant state a token carries.
+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))
+
createSheet := func(sql string) map[string]any {
return map[string]any{
"parent": project.Msg.Name,
diff --git a/frontend/scripts/check-react-i18n.mjs b/frontend/scripts/check-react-i18n.mjs
index 042acbbcc2..e5f579d2c8 100644
--- a/frontend/scripts/check-react-i18n.mjs
+++ b/frontend/scripts/check-react-i18n.mjs
@@ -53,6 +53,14 @@ const DYNAMIC_PREFIXES = [
// Role-grant expiration presets, rendered via t(preset.labelKey) in
// MembersPage.tsx (EXPIRATION_PRESETS), not as literal t("…") calls.
"project.members.expiration-presets.",
+ // MCP mode cards and the broken-ceiling banner, rendered via
+ // t(`settings.mcp.policy.mode.${key}.title`) and a ternary over two key
+ // strings in MCPAccessPolicySection.tsx, not as literal t("…") calls.
+ "settings.mcp.policy.mode.",
+ "settings.mcp.policy.unreadable.description",
+ "settings.mcp.policy.unreadable.title",
+ "settings.mcp.policy.unserved.description",
+ "settings.mcp.policy.unserved.title",
// Keys consumed by SHARED non-React `.ts` modules that translate via
// `@/lib/i18n` (the same react-i18next instance — vue-i18n is gone), but
// live OUTSIDE this checker's React-only scan, so they read as unused. They
diff --git a/frontend/src/components/ui/switch.tsx b/frontend/src/components/ui/switch.tsx
index 715849f441..cccc097ee5 100644
--- a/frontend/src/components/ui/switch.tsx
+++ b/frontend/src/components/ui/switch.tsx
@@ -28,6 +28,18 @@ interface SwitchProps {
disabled?: boolean;
className?: string;
size?: SwitchSize;
+ /**
+ * Accessible name for the control. A switch renders no text of its own, so
+ * without this — or a `<label>` wrapping it — assistive technology announces
+ * an unnamed switch and the person cannot tell which setting they are
+ * toggling. Pass it whenever the visible title sits in a sibling element.
+ *
+ * `id` alone does not substitute: Base UI renders the switch as a `<span>`,
+ * and `<label for>` cannot name a span.
+ */
+ "aria-label"?: string;
+ "aria-labelledby"?: string;
+ id?: string;
}
function Switch({
@@ -36,6 +48,9 @@ function Switch({
disabled,
className,
size = "md",
+ id,
+ "aria-label": ariaLabel,
+ "aria-labelledby": ariaLabelledBy,
}: SwitchProps) {
const sizeClasses = SWITCH_SIZES[size];
@@ -44,6 +59,9 @@ function Switch({
checked={checked}
onCheckedChange={onCheckedChange}
disabled={disabled}
+ id={id}
+ aria-label={ariaLabel}
+ aria-labelledby={ariaLabelledBy}
className={cn(
"relative inline-flex cursor-pointer items-center rounded-full transition-colors",
sizeClasses.root,
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 397e02a4b1..58f67bae43 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2459,25 +2459,6 @@
"self": "Maximum SQL result size"
}
},
- "mcp": {
- "capability": {
- "description": "The maximum capability available to MCP (Model Context Protocol) sessions in this workspace. Changes apply to the next MCP request immediately.",
- "disabled": {
- "description": "All MCP connections are rejected.",
- "self": "Disabled"
- },
- "read-only": {
- "description": "MCP sessions can inspect metadata and run read-only queries, still bounded by each user's own permissions. A request is refused whole if Bytebase classifies any statement in it as a write, or cannot determine that it only reads.",
- "self": "Read-only"
- },
- "read-write": {
- "description": "MCP sessions can read and write, still bounded by each user's own permissions. This is the default when not configured.",
- "self": "Read-write"
- },
- "self": "MCP access"
- },
- "self": "MCP"
- },
"no-limit": "No limit when the value <= 0",
"password-restriction": {
"min-length": "Minimum length for password should no less than {{min}} characters",
@@ -2545,6 +2526,38 @@
"description": "OAuth authentication is required on first connection. Ensure you have appropriate Bytebase permissions.",
"title": "Authentication Required"
},
+ "contents": {
+ "depth": {
+ "description": "How far the read-only ceiling is enforced on each engine.",
+ "not-a-proof": "Neither depth is a proof. A statement that classifies as a read can still call a function that turns the session setting back off.",
+ "statement": "Every statement is classified before it runs. The driver does not open a read-only database session.",
+ "statement-and-session": "Every statement is classified, and the driver opens the database session read-only.",
+ "title": "Read-only depth by engine",
+ "unspecified": "Not reported by this build.",
+ "unsupported": "No read-only classifier, so every statement is refused, including a plain SELECT."
+ },
+ "masking": {
+ "column": "Column masking. Exemptions decide who sees the real value, so ignoring them changes what a session reads.",
+ "description-off": "This workspace applies each user's masking exemptions to MCP sessions. Ignoring them would reach only the engines below that consult exemptions.",
+ "description-on": "This workspace ignores masking exemptions, so what a session reads depends on how Bytebase masks each engine.",
+ "document": "Document masking. Exemptions are never consulted here, so ignoring them changes nothing.",
+ "none": "Bytebase does not mask on this engine. Ignoring exemptions changes nothing.",
+ "title": "Masking by engine",
+ "unspecified": "Not reported by this build."
+ },
+ "methods": {
+ "count": "{{served}} of {{total}} methods MCP can reach. Being listed is not permission: the connecting user still needs their own.",
+ "handler": "No declared IAM permission",
+ "none": "This mode serves no API method.",
+ "write-legend": "The {{count}} highlighted are what this mode adds over Read-only."
+ },
+ "notes": {
+ "redshift": "Outside a datashare database the driver also opens the session read-only. A datashare database cannot run a read-only transaction, so there it is statement classification alone.",
+ "title": "Where the answer above is the floor",
+ "unavailable": "This engine has a caveat this page cannot show yet. Reload to pick up the current version."
+ },
+ "title": "{{mode}} — what this mode serves"
+ },
"description": "Connect AI assistants to Bytebase using the Model Context Protocol.",
"first-prompt": {
"description": "Once connected, try asking your AI assistant:",
@@ -2554,6 +2567,55 @@
"general-config": {
"title": "Option 1: JSON Configuration"
},
+ "policy": {
+ "audit": "MCP policy denials are recorded in the audit log.",
+ "description": "The most any MCP session may do in this workspace. Every session is also capped by the connecting user's own permissions.",
+ "edit": "Edit policy",
+ "in-force": "In force",
+ "loading": "Reading the access policy…",
+ "masking": {
+ "badge": "Masking exemptions ignored",
+ "description": "Masked data stays masked in MCP sessions. The masking exemptions granted to a user, and the unmask carried by an access grant, stop applying to their MCP requests. The same user is unaffected in the Bytebase console.",
+ "limits": "Masking coverage depends on the engine. Where Bytebase does not mask, or masks without consulting exemptions, this changes nothing.",
+ "title": "Ignore masking exemptions",
+ "unavailable": "Data masking is not licensed for this workspace, so nothing is masked whatever this is set to."
+ },
+ "mode": {
+ "contents": "See what {{mode}} serves",
+ "disabled": {
+ "best-for": "Best for: keeping MCP off until you are ready to turn it on.",
+ "description": "No MCP session can connect to this workspace.",
+ "title": "Disabled"
+ },
+ "read-only": {
+ "best-for": "Best for: querying and exploring data, including by people who do not write SQL.",
+ "description": "Sessions can explore schemas and run read-only queries. Bytebase classifies every statement before it runs and refuses a request whole if any statement is not a read. Where the engine's driver has one, the database session is opened read-only as well. How deep this goes varies by engine.",
+ "title": "Read-only"
+ },
+ "read-write": {
+ "best-for": "Best for: making database changes through an AI agent, still capped by each user's own permissions.",
+ "description": "Sessions can also change data and schemas, as far as the connecting user's own permissions allow.",
+ "title": "Read-write"
+ }
+ },
+ "read-failed": {
+ "description": "Reload to try again. If it keeps failing, the stored policy is one Bytebase cannot parse and an operator has to repair the row directly. Until it can be read, every MCP connection is refused.",
+ "title": "The access policy could not be read"
+ },
+ "save": "Save policy",
+ "saved": "Policy saved. {{mode}} applies to every session's next request.",
+ "tightening": "A ceiling change applies to the next request of every running session. Work an agent has already been admitted to runs to completion.",
+ "title": "Access policy",
+ "unreadable": {
+ "description": "This workspace stores a capability value this build does not understand. Every MCP connection is being refused. Pick a mode and save to set it right.",
+ "pick": "Pick a mode to save this policy.",
+ "title": "The stored access policy cannot be read"
+ },
+ "unserved": {
+ "description": "This workspace stores {{stored}}, which is not a ceiling this build serves. Every MCP connection is being refused. Pick a mode and save to set it right.",
+ "title": "The stored access policy is not one this build serves"
+ }
+ },
"quick-start": {
"description": "Alternatively, use one of these CLI commands.",
"title": "Option 2: CLI Commands"
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index be89336222..69eddefc61 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2459,25 +2459,6 @@
"self": "Tamaño máximo del resultado de SQL"
}
},
- "mcp": {
- "capability": {
- "description": "La capacidad máxima disponible para las sesiones MCP (Model Context Protocol) en este espacio de trabajo. Los cambios se aplican de inmediato a la siguiente solicitud MCP.",
- "disabled": {
- "description": "Se rechazan todas las conexiones MCP.",
- "self": "Deshabilitado"
- },
- "read-only": {
- "description": "Las sesiones MCP pueden inspeccionar metadatos y ejecutar consultas de solo lectura, siempre limitadas por los permisos de cada usuario. Se rechaza la solicitud completa si Bytebase clasifica alguna de sus instrucciones como escritura o no puede determinar que solo lee.",
- "self": "Solo lectura"
- },
- "read-write": {
- "description": "Las sesiones MCP pueden leer y escribir, siempre limitadas por los permisos de cada usuario. Es el valor predeterminado cuando no está configurado.",
- "self": "Lectura y escritura"
- },
- "self": "Acceso MCP"
- },
- "self": "MCP"
- },
"no-limit": "No hay límite cuando el valor <= 0",
"password-restriction": {
"min-length": "La longitud mínima de la contraseña no debe ser inferior a {{min}} caracteres",
@@ -2545,6 +2526,38 @@
"description": "Se requiere autenticación OAuth en la primera conexión. Asegúrese de tener los permisos apropiados en Bytebase.",
"title": "Autenticación requerida"
},
+ "contents": {
+ "depth": {
+ "description": "Hasta dónde se aplica el techo de solo lectura en cada motor.",
+ "not-a-proof": "Ninguna de las dos profundidades es una prueba. Una sentencia clasificada como lectura todavía puede llamar a una función que vuelva a desactivar el ajuste de sesión.",
+ "statement": "Cada sentencia se clasifica antes de ejecutarse. El controlador no abre la sesión de base de datos en solo lectura.",
+ "statement-and-session": "Cada sentencia se clasifica y el controlador abre la sesión de base de datos en solo lectura.",
+ "title": "Profundidad de solo lectura por motor",
+ "unspecified": "Esta versión no lo informa.",
+ "unsupported": "No hay clasificador de solo lectura, así que se rechaza cada sentencia, incluido un SELECT simple."
+ },
+ "masking": {
+ "column": "Enmascaramiento de columnas. Las exenciones deciden quién ve el valor real, así que ignorarlas cambia lo que lee una sesión.",
+ "description-off": "Este espacio de trabajo aplica las exenciones de enmascaramiento de cada usuario a las sesiones MCP. Ignorarlas solo alcanzaría a los motores de abajo que consultan exenciones.",
+ "description-on": "Este espacio de trabajo ignora las exenciones de enmascaramiento, así que lo que lee una sesión depende de cómo enmascara Bytebase cada motor.",
+ "document": "Enmascaramiento de documentos. Aquí nunca se consultan las exenciones, así que ignorarlas no cambia nada.",
+ "none": "Bytebase no enmascara en este motor. Ignorar las exenciones no cambia nada.",
+ "title": "Enmascaramiento por motor",
+ "unspecified": "Esta versión no lo informa."
+ },
+ "methods": {
+ "count": "{{served}} de {{total}} métodos que MCP puede alcanzar. Estar en la lista no es un permiso: el usuario que se conecta sigue necesitando el suyo.",
+ "handler": "Sin permiso de IAM declarado",
+ "none": "Este modo no ofrece ningún método de la API.",
+ "write-legend": "Los {{count}} resaltados son lo que este modo añade sobre Solo lectura."
+ },
+ "notes": {
+ "redshift": "Fuera de una base de datos datashare, el controlador también abre la sesión en solo lectura. Una base de datos datashare no puede ejecutar una transacción de solo lectura, así que allí solo hay clasificación de sentencias.",
+ "title": "Dónde la respuesta de arriba es el mínimo",
+ "unavailable": "Este motor tiene una salvedad que esta página aún no puede mostrar. Recargue para obtener la versión actual."
+ },
+ "title": "{{mode}}: qué ofrece este modo"
+ },
"description": "Conecte asistentes de IA a Bytebase usando el Model Context Protocol.",
"first-prompt": {
"description": "Una vez conectado, intente preguntar a su asistente de IA:",
@@ -2554,6 +2567,55 @@
"general-config": {
"title": "Opción 1: Configuración JSON"
},
+ "policy": {
+ "audit": "Las denegaciones de la política MCP se registran en el registro de auditoría.",
+ "description": "Lo máximo que puede hacer cualquier sesión MCP en este espacio de trabajo. Cada sesión está además limitada por los permisos del propio usuario que se conecta.",
+ "edit": "Editar política",
+ "in-force": "En vigor",
+ "loading": "Leyendo la política de acceso…",
+ "masking": {
+ "badge": "Exenciones de enmascaramiento ignoradas",
+ "description": "Los datos enmascarados siguen enmascarados en las sesiones MCP. Las exenciones de enmascaramiento concedidas a un usuario, y el desenmascarado que lleva una concesión de acceso, dejan de aplicarse a sus solicitudes MCP. El mismo usuario no se ve afectado en la consola de Bytebase.",
+ "limits": "La cobertura del enmascaramiento depende del motor. Donde Bytebase no enmascara, o enmascara sin consultar las exenciones, esto no cambia nada.",
+ "title": "Ignorar las exenciones de enmascaramiento",
+ "unavailable": "El enmascaramiento de datos no está licenciado para este espacio de trabajo, así que no se enmascara nada sea cual sea este ajuste."
+ },
+ "mode": {
+ "contents": "Ver qué ofrece {{mode}}",
+ "disabled": {
+ "best-for": "Ideal para: mantener MCP apagado hasta que esté listo para activarlo.",
+ "description": "Ninguna sesión MCP puede conectarse a este espacio de trabajo.",
+ "title": "Desactivado"
+ },
+ "read-only": {
+ "best-for": "Ideal para: consultar y explorar datos, incluso por personas que no escriben SQL.",
+ "description": "Las sesiones pueden explorar esquemas y ejecutar consultas de solo lectura. Bytebase clasifica cada sentencia antes de ejecutarla y rechaza la solicitud entera si alguna no es una lectura. Donde el controlador del motor lo permite, la sesión de base de datos también se abre en solo lectura. Hasta dónde llega esto varía según el motor.",
+ "title": "Solo lectura"
+ },
+ "read-write": {
+ "best-for": "Ideal para: hacer cambios en la base de datos a través de un agente de IA, siempre limitado por los permisos de cada usuario.",
+ "description": "Las sesiones también pueden cambiar datos y esquemas, hasta donde permitan los permisos del propio usuario que se conecta.",
+ "title": "Lectura y escritura"
+ }
+ },
+ "read-failed": {
+ "description": "Recargue para reintentar. Si sigue fallando, la política almacenada es una que Bytebase no puede analizar y un operador debe reparar la fila directamente. Mientras no se pueda leer, se rechaza toda conexión MCP.",
+ "title": "No se pudo leer la política de acceso"
+ },
+ "save": "Guardar política",
+ "saved": "Política guardada. {{mode}} se aplica a la siguiente solicitud de cada sesión.",
+ "tightening": "Un cambio de techo se aplica a la siguiente solicitud de cada sesión en curso. El trabajo que un agente ya tiene admitido termina de ejecutarse.",
+ "title": "Política de acceso",
+ "unreadable": {
+ "description": "Este espacio de trabajo almacena un valor de capacidad que esta versión no entiende. Se rechaza toda conexión MCP. Elija un modo y guarde para corregirlo.",
+ "pick": "Elija un modo para guardar esta política.",
+ "title": "No se puede leer la política de acceso almacenada"
+ },
+ "unserved": {
+ "description": "Este espacio de trabajo almacena {{stored}}, que no es un techo que esta versión ofrezca. Se está rechazando cada conexión MCP. Elija un modo y guarde para corregirlo.",
+ "title": "La política de acceso almacenada no es una que esta versión ofrezca"
+ }
+ },
"quick-start": {
"description": "Alternativamente, use uno de estos comandos CLI.",
"title": "Opción 2: Comandos CLI"
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index a403ae2c99..3c97d44bd5 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2459,25 +2459,6 @@
"self": "最大SQL結果サイズ"
}
},
- "mcp": {
- "capability": {
- "description": "このワークスペースで MCP(Model Context Protocol)セッションに許可される最大の権限です。変更は次の MCP リクエストから直ちに適用されます。",
- "disabled": {
- "description": "すべての MCP 接続を拒否します。",
- "self": "無効"
- },
- "read-only": {
- "description": "MCP セッションはメタデータを参照し、読み取り専用クエリを実行できますが、各ユーザー自身の権限の範囲内に制限されます。リクエスト内のいずれかのステートメントが書き込みと判定された場合、または読み取りのみであると確認できない場合、リクエスト全体が拒否されます。",
- "self": "読み取り専用"
- },
- "read-write": {
- "description": "MCP セッションは読み書きできますが、各ユーザー自身の権限の範囲内に制限されます。未設定の場合のデフォルトです。",
- "self": "読み書き"
- },
- "self": "MCP アクセス"
- },
- "self": "MCP"
- },
"no-limit": "値が0以下の場合、制限なし",
"password-restriction": {
"min-length": "パスワードの最小文字数は {{min}} 文字以上である必要があります",
@@ -2545,6 +2526,38 @@
"description": "初回接続時に OAuth 認証が必要です。適切な Bytebase 権限があることを確認してください。",
"title": "認証が必要"
},
+ "contents": {
+ "depth": {
+ "description": "読み取り専用の上限が各エンジンでどこまで適用されるか。",
+ "not-a-proof": "どちらの深さも証明ではありません。読み取りと分類されたステートメントが、セッション設定を元に戻す関数を呼ぶことはあり得ます。",
+ "statement": "実行前にすべてのステートメントが分類されます。ドライバーはデータベースセッションを読み取り専用では開きません。",
+ "statement-and-session": "すべてのステートメントが分類され、ドライバーがデータベースセッションを読み取り専用で開きます。",
+ "title": "エンジン別の読み取り専用の深さ",
+ "unspecified": "このビルドでは報告されません。",
+ "unsupported": "読み取り専用の分類器がないため、単純な SELECT も含めてすべてのステートメントが拒否されます。"
+ },
+ "masking": {
+ "column": "列マスキング。誰が実際の値を見られるかを適用除外が決めるため、無視するとセッションが読める内容が変わります。",
+ "description-off": "このワークスペースは MCP セッションにも各ユーザーのマスキング適用除外を適用します。無視した場合に影響するのは、下記のうち適用除外を参照するエンジンだけです。",
+ "description-on": "このワークスペースはマスキングの適用除外を無視するため、セッションが何を読めるかは Bytebase が各エンジンをどうマスクするかで決まります。",
+ "document": "ドキュメントマスキング。この経路では適用除外を参照しないため、無視しても何も変わりません。",
+ "none": "Bytebase はこのエンジンではマスクしません。適用除外を無視しても何も変わりません。",
+ "title": "エンジン別のマスキング",
+ "unspecified": "このビルドでは報告されません。"
+ },
+ "methods": {
+ "count": "MCP が到達できる {{total}} 件のメソッドのうち {{served}} 件。掲載は権限ではありません。接続ユーザー自身の権限が別途必要です。",
+ "handler": "宣言された IAM 権限なし",
+ "none": "このモードが提供する API メソッドはありません。",
+ "write-legend": "強調されている {{count}} 件が、読み取り専用に対してこのモードが追加する分です。"
+ },
+ "notes": {
+ "redshift": "datashare データベース以外では、ドライバーがセッションも読み取り専用で開きます。datashare データベースは読み取り専用トランザクションを実行できないため、そこではステートメント分類のみになります。",
+ "title": "上記の答えが下限にとどまる場合",
+ "unavailable": "このエンジンには、このページがまだ表示できない注意事項があります。再読み込みして最新バージョンを取得してください。"
+ },
+ "title": "{{mode}} — このモードが提供する内容"
+ },
"description": "Model Context Protocol を使用して、AI アシスタントを Bytebase に接続します。",
"first-prompt": {
"description": "接続後、AI アシスタントに聞いてみてください:",
@@ -2554,6 +2567,55 @@
"general-config": {
"title": "方法 1:JSON 設定"
},
+ "policy": {
+ "audit": "MCP ポリシーによる拒否は監査ログに記録されます。",
+ "description": "このワークスペースで MCP セッションが実行できる操作の上限です。各セッションは接続ユーザー自身の権限によってもさらに制限されます。",
+ "edit": "ポリシーを編集",
+ "in-force": "適用中",
+ "loading": "アクセスポリシーを読み込んでいます…",
+ "masking": {
+ "badge": "適用除外を無視中",
+ "description": "MCP セッションではマスクされたデータがマスクされたままになります。ユーザーに付与されたマスキングの適用除外も、アクセスグラントに伴うマスク解除も、その MCP リクエストには適用されなくなります。同じユーザーでも Bytebase コンソールでは影響を受けません。",
+ "limits": "マスキングの適用範囲はエンジンによって異なります。Bytebase がマスクしないエンジン、または適用除外を参照せずにマスクするエンジンでは、この設定は何も変えません。",
+ "title": "マスキングの適用除外を無視する",
+ "unavailable": "このワークスペースではデータマスキングのライセンスがないため、この設定にかかわらず何もマスクされません。"
+ },
+ "mode": {
+ "contents": "{{mode}} が提供する内容を見る",
+ "disabled": {
+ "best-for": "適する場面:有効にする準備が整うまで MCP をオフにしておきたいとき。",
+ "description": "このワークスペースにはどの MCP セッションも接続できません。",
+ "title": "無効"
+ },
+ "read-only": {
+ "best-for": "適する場面:SQL を書かない人も含めた、データの照会と探索。",
+ "description": "セッションはスキーマを調べ、読み取り専用のクエリを実行できます。Bytebase は実行前にすべてのステートメントを分類し、読み取りでないものが 1 つでもあればリクエスト全体を拒否します。エンジンのドライバーが対応していれば、データベースセッション自体も読み取り専用で開きます。どこまで踏み込めるかはエンジンによって異なります。",
+ "title": "読み取り専用"
+ },
+ "read-write": {
+ "best-for": "適する場面:AI エージェント経由でのデータベース変更。各ユーザー自身の権限による制限は残ります。",
+ "description": "セッションはデータやスキーマの変更も行えます。範囲は接続ユーザー自身の権限までです。",
+ "title": "読み書き"
+ }
+ },
+ "read-failed": {
+ "description": "再読み込みしてやり直してください。失敗が続く場合、保存されたポリシーは Bytebase が解釈できないもので、運用担当者が行を直接修復する必要があります。読み取れない間、MCP 接続はすべて拒否されます。",
+ "title": "アクセスポリシーを読み取れませんでした"
+ },
+ "save": "ポリシーを保存",
+ "saved": "ポリシーを保存しました。{{mode}} はすべてのセッションの次のリクエストから適用されます。",
+ "tightening": "上限の変更は、実行中のすべてのセッションの次のリクエストから適用されます。エージェントがすでに許可された処理は最後まで実行されます。",
+ "title": "アクセスポリシー",
+ "unreadable": {
+ "description": "このワークスペースには、このビルドが解釈できない機能レベルの値が保存されています。MCP 接続はすべて拒否されています。モードを選択して保存し、修正してください。",
+ "pick": "このポリシーを保存するにはモードを選んでください。",
+ "title": "保存されたアクセスポリシーを読み取れません"
+ },
+ "unserved": {
+ "description": "このワークスペースには {{stored}} が保存されていますが、このビルドが提供する上限ではありません。MCP 接続はすべて拒否されています。モードを選んで保存すると修復されます。",
+ "title": "保存されたアクセスポリシーはこのビルドが提供するものではありません"
+ }
+ },
"quick-start": {
"description": "または、以下の CLI コマンドを使用してください。",
"title": "方法 2:CLI コマンド"
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index fa38e44454..1e0c1e6f37 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2459,25 +2459,6 @@
"self": "Kích thước kết quả SQL tối đa"
}
},
- "mcp": {
- "capability": {
- "description": "Khả năng tối đa dành cho các phiên MCP (Model Context Protocol) trong không gian làm việc này. Thay đổi áp dụng ngay cho yêu cầu MCP tiếp theo.",
- "disabled": {
- "description": "Từ chối tất cả kết nối MCP.",
- "self": "Tắt"
- },
- "read-only": {
- "description": "Các phiên MCP có thể xem siêu dữ liệu và chạy truy vấn chỉ đọc, vẫn bị giới hạn bởi quyền của từng người dùng. Toàn bộ yêu cầu sẽ bị từ chối nếu Bytebase xác định bất kỳ câu lệnh nào trong đó là ghi, hoặc không thể xác nhận rằng nó chỉ đọc.",
- "self": "Chỉ đọc"
- },
- "read-write": {
- "description": "Các phiên MCP có thể đọc và ghi, vẫn bị giới hạn bởi quyền của từng người dùng. Đây là mặc định khi chưa cấu hình.",
- "self": "Đọc và ghi"
- },
- "self": "Truy cập MCP"
- },
- "self": "MCP"
- },
"no-limit": "Không giới hạn khi giá trị <= 0",
"password-restriction": {
"min-length": "Độ dài tối thiểu cho mật khẩu không được ít hơn {{min}} ký tự",
@@ -2545,6 +2526,38 @@
"description": "Xác thực OAuth được yêu cầu khi kết nối lần đầu. Đảm bảo bạn có quyền Bytebase phù hợp.",
"title": "Yêu cầu xác thực"
},
+ "contents": {
+ "depth": {
+ "description": "Mức trần chỉ đọc được thực thi sâu tới đâu trên mỗi công cụ.",
+ "not-a-proof": "Không mức nào trong hai mức là một bằng chứng. Một câu lệnh được phân loại là đọc vẫn có thể gọi một hàm tắt lại thiết lập phiên.",
+ "statement": "Mọi câu lệnh đều được phân loại trước khi chạy. Trình điều khiển không mở phiên cơ sở dữ liệu ở chế độ chỉ đọc.",
+ "statement-and-session": "Mọi câu lệnh đều được phân loại, và trình điều khiển mở phiên cơ sở dữ liệu ở chế độ chỉ đọc.",
+ "title": "Mức độ chỉ đọc theo công cụ",
+ "unspecified": "Bản dựng này không báo cáo.",
+ "unsupported": "Không có bộ phân loại chỉ đọc, nên mọi câu lệnh đều bị từ chối, kể cả một câu SELECT đơn giản."
+ },
+ "masking": {
+ "column": "Che theo cột. Miễn trừ quyết định ai thấy giá trị thật, nên bỏ qua chúng sẽ thay đổi những gì một phiên đọc được.",
+ "description-off": "Không gian làm việc này vẫn áp dụng miễn trừ che dữ liệu của từng người dùng cho phiên MCP. Bỏ qua chúng chỉ ảnh hưởng tới các công cụ bên dưới có tra cứu miễn trừ.",
+ "description-on": "Không gian làm việc này bỏ qua miễn trừ che dữ liệu, nên một phiên đọc được gì tuỳ thuộc vào cách Bytebase che trên từng công cụ.",
+ "document": "Che theo tài liệu. Đường đi này không bao giờ tra cứu miễn trừ, nên bỏ qua chúng không thay đổi gì.",
+ "none": "Bytebase không che trên công cụ này. Bỏ qua miễn trừ không thay đổi gì.",
+ "title": "Che dữ liệu theo công cụ",
+ "unspecified": "Bản dựng này không báo cáo."
+ },
+ "methods": {
+ "count": "{{served}} trong {{total}} phương thức MCP có thể gọi. Có tên trong danh sách không phải là quyền: người dùng kết nối vẫn cần quyền của chính họ.",
+ "handler": "Không khai báo quyền IAM",
+ "none": "Chế độ này không phục vụ phương thức API nào.",
+ "write-legend": "{{count}} mục được làm nổi bật là phần chế độ này thêm so với Chỉ đọc."
+ },
+ "notes": {
+ "redshift": "Ngoài cơ sở dữ liệu datashare, trình điều khiển còn mở phiên ở chế độ chỉ đọc. Cơ sở dữ liệu datashare không chạy được giao dịch chỉ đọc, nên ở đó chỉ có phân loại câu lệnh.",
+ "title": "Nơi câu trả lời ở trên chỉ là mức sàn",
+ "unavailable": "Công cụ này có một lưu ý mà trang này chưa hiển thị được. Hãy tải lại để lấy phiên bản hiện tại."
+ },
+ "title": "{{mode}} — chế độ này phục vụ những gì"
+ },
"description": "Kết nối trợ lý AI với Bytebase bằng Model Context Protocol.",
"first-prompt": {
"description": "Sau khi kết nối, hãy thử hỏi trợ lý AI của bạn:",
@@ -2554,6 +2567,55 @@
"general-config": {
"title": "Cách 1: Cấu hình JSON"
},
+ "policy": {
+ "audit": "Các lần từ chối theo chính sách MCP được ghi vào nhật ký kiểm toán.",
+ "description": "Mức tối đa mà một phiên MCP được phép làm trong không gian làm việc này. Mỗi phiên còn bị giới hạn thêm bởi quyền của chính người dùng đang kết nối.",
+ "edit": "Sửa chính sách",
+ "in-force": "Đang áp dụng",
+ "loading": "Đang đọc chính sách truy cập…",
+ "masking": {
+ "badge": "Đã bỏ qua miễn trừ che dữ liệu",
+ "description": "Dữ liệu được che vẫn bị che trong phiên MCP. Các miễn trừ che dữ liệu cấp cho người dùng, và việc bỏ che đi kèm một cấp quyền truy cập, đều ngừng áp dụng cho yêu cầu MCP của họ. Cũng người dùng đó không bị ảnh hưởng trong bảng điều khiển Bytebase.",
+ "limits": "Phạm vi che dữ liệu tuỳ theo công cụ. Ở nơi Bytebase không che, hoặc che mà không tra cứu miễn trừ, thiết lập này không thay đổi gì.",
+ "title": "Bỏ qua miễn trừ che dữ liệu",
+ "unavailable": "Không gian làm việc này chưa có giấy phép che dữ liệu, nên sẽ không có gì bị che dù thiết lập này ra sao."
+ },
+ "mode": {
+ "contents": "Xem {{mode}} phục vụ những gì",
+ "disabled": {
+ "best-for": "Phù hợp khi: giữ MCP tắt cho tới khi bạn sẵn sàng bật.",
+ "description": "Không phiên MCP nào có thể kết nối tới không gian làm việc này.",
+ "title": "Tắt"
+ },
+ "read-only": {
+ "best-for": "Phù hợp khi: truy vấn và khám phá dữ liệu, kể cả với người không viết SQL.",
+ "description": "Phiên có thể khám phá lược đồ và chạy truy vấn chỉ đọc. Bytebase phân loại từng câu lệnh trước khi chạy và từ chối trọn yêu cầu nếu có bất kỳ câu lệnh nào không phải là đọc. Nơi trình điều khiển của công cụ hỗ trợ, phiên cơ sở dữ liệu cũng được mở ở chế độ chỉ đọc. Mức độ sâu tới đâu tuỳ theo công cụ.",
+ "title": "Chỉ đọc"
+ },
+ "read-write": {
+ "best-for": "Phù hợp khi: thực hiện thay đổi cơ sở dữ liệu qua tác nhân AI, vẫn bị giới hạn bởi quyền của từng người dùng.",
+ "description": "Phiên còn có thể thay đổi dữ liệu và lược đồ, trong phạm vi quyền của chính người dùng đang kết nối.",
+ "title": "Đọc và ghi"
+ }
+ },
+ "read-failed": {
+ "description": "Hãy tải lại để thử lần nữa. Nếu vẫn lỗi, chính sách đã lưu là loại Bytebase không phân tích được và cần người vận hành sửa trực tiếp bản ghi. Trong lúc chưa đọc được, mọi kết nối MCP đều bị từ chối.",
+ "title": "Không đọc được chính sách truy cập"
+ },
+ "save": "Lưu chính sách",
+ "saved": "Đã lưu chính sách. {{mode}} áp dụng cho yêu cầu kế tiếp của mọi phiên.",
+ "tightening": "Thay đổi mức trần áp dụng cho yêu cầu kế tiếp của mọi phiên đang chạy. Công việc mà tác nhân đã được cho phép vẫn chạy đến khi xong.",
+ "title": "Chính sách truy cập",
+ "unreadable": {
+ "description": "Không gian làm việc này lưu một giá trị năng lực mà bản dựng hiện tại không hiểu. Mọi kết nối MCP đều bị từ chối. Hãy chọn một chế độ và lưu để sửa lại.",
+ "pick": "Hãy chọn một chế độ để lưu chính sách này.",
+ "title": "Không đọc được chính sách truy cập đã lưu"
+ },
+ "unserved": {
+ "description": "Không gian làm việc này lưu {{stored}}, không phải mức trần mà bản dựng này phục vụ. Mọi kết nối MCP đang bị từ chối. Hãy chọn một chế độ và lưu để sửa lại.",
+ "title": "Chính sách truy cập đã lưu không phải loại bản dựng này phục vụ"
+ }
+ },
"quick-start": {
"description": "Hoặc sử dụng một trong các lệnh CLI sau.",
"title": "Cách 2: Lệnh CLI"
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index c3f48a00d6..6bfc1631ca 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2459,25 +2459,6 @@
"self": "最大 SQL 结果大小"
}
},
- "mcp": {
- "capability": {
- "description": "此工作空间中 MCP(Model Context Protocol)会话可用的最高能力上限。变更对下一个 MCP 请求立即生效。",
- "disabled": {
- "description": "拒绝所有 MCP 连接。",
- "self": "禁用"
- },
- "read-only": {
- "description": "MCP 会话可以查看元数据并执行只读查询,仍受每个用户自身权限的约束。如果 Bytebase 将其中任一语句判定为写入,或无法确认其仅执行读取,整个请求都会被拒绝。",
- "self": "只读"
- },
- "read-write": {
- "description": "MCP 会话可以读写,仍受每个用户自身权限的约束。未配置时默认为此项。",
- "self": "读写"
- },
- "self": "MCP 访问"
- },
- "self": "MCP"
- },
"no-limit": "当值 <= 0 时无限制",
"password-restriction": {
"min-length": "密码最小长度不得少于 {{min}} 个字符",
@@ -2545,6 +2526,38 @@
"description": "首次连接需要 OAuth 身份验证。请确保您拥有相应的 Bytebase 权限。",
"title": "需要身份验证"
},
+ "contents": {
+ "depth": {
+ "description": "只读上限在每个引擎上的执行强度。",
+ "not-a-proof": "两种强度都不是证明。被判定为读取的语句仍可能调用某个函数,把会话设置改回去。",
+ "statement": "每条语句在执行前都会被分类。驱动不会以只读方式打开数据库会话。",
+ "statement-and-session": "每条语句都会被分类,并且驱动会以只读方式打开数据库会话。",
+ "title": "各引擎的只读强度",
+ "unspecified": "当前版本未报告。",
+ "unsupported": "没有只读分类器,因此每条语句都会被拒绝,包括普通的 SELECT。"
+ },
+ "masking": {
+ "column": "列级脱敏。豁免决定谁能看到真实值,因此忽略豁免会改变会话读到的内容。",
+ "description-off": "本工作空间在 MCP 会话中仍应用每位用户的脱敏豁免。忽略这些豁免只会影响下列会查询豁免的引擎。",
+ "description-on": "本工作空间忽略脱敏豁免,因此会话能读到什么,取决于 Bytebase 在各引擎上的脱敏方式。",
+ "document": "文档级脱敏。此路径从不查询豁免,因此忽略豁免不产生任何变化。",
+ "none": "Bytebase 在该引擎上不做脱敏。忽略豁免不产生任何变化。",
+ "title": "各引擎的脱敏方式",
+ "unspecified": "当前版本未报告。"
+ },
+ "methods": {
+ "count": "MCP 可访问的 {{total}} 个方法中的 {{served}} 个。列出并不等于授权:连接用户仍需具备自身权限。",
+ "handler": "未声明 IAM 权限",
+ "none": "该模式不提供任何 API 方法。",
+ "write-legend": "其中高亮的 {{count}} 个是该模式相较只读新增的部分。"
+ },
+ "notes": {
+ "redshift": "在非 datashare 数据库中,驱动还会以只读方式打开会话。datashare 数据库无法运行只读事务,因此在那里仅有语句分类。",
+ "title": "上述答案只是下限的情况",
+ "unavailable": "此引擎有一条本页面尚无法显示的注意事项。请重新加载以获取当前版本。"
+ },
+ "title": "{{mode}} — 该模式提供的内容"
+ },
"description": "使用模型上下文协议将 AI 助手连接到 Bytebase。",
"first-prompt": {
"description": "连接后,尝试向 AI 助手提问:",
@@ -2554,6 +2567,55 @@
"general-config": {
"title": "方式一:JSON 配置"
},
+ "policy": {
+ "audit": "MCP 策略拒绝会记录在审计日志中。",
+ "description": "本工作空间中任何 MCP 会话所能执行操作的上限。每个会话还会受到连接用户自身权限的限制。",
+ "edit": "编辑策略",
+ "in-force": "当前生效",
+ "loading": "正在读取访问策略…",
+ "masking": {
+ "badge": "已忽略脱敏豁免",
+ "description": "在 MCP 会话中,脱敏数据保持脱敏。授予用户的脱敏豁免,以及访问授权所携带的解除脱敏,都不再对其 MCP 请求生效。同一用户在 Bytebase 控制台中不受影响。",
+ "limits": "脱敏覆盖范围取决于引擎。若 Bytebase 在该引擎上不做脱敏,或者脱敏时不查询豁免,此项不产生任何变化。",
+ "title": "忽略脱敏豁免",
+ "unavailable": "本工作空间未授权数据脱敏功能,因此无论此项如何设置都不会脱敏。"
+ },
+ "mode": {
+ "contents": "查看 {{mode}} 提供的内容",
+ "disabled": {
+ "best-for": "适用于:在准备好开启之前先关闭 MCP。",
+ "description": "任何 MCP 会话都无法连接到本工作空间。",
+ "title": "禁用"
+ },
+ "read-only": {
+ "best-for": "适用于:查询和探索数据,包括不写 SQL 的人。",
+ "description": "会话可以浏览模式并执行只读查询。Bytebase 会在每条语句执行前对其分类,只要其中有一条不是读取,就整体拒绝该请求。若引擎的驱动支持,还会以只读方式打开数据库会话。具体强度因引擎而异。",
+ "title": "只读"
+ },
+ "read-write": {
+ "best-for": "适用于:通过 AI 代理执行数据库变更,仍受每位用户自身权限的限制。",
+ "description": "会话还可以修改数据和模式,范围以连接用户自身的权限为限。",
+ "title": "读写"
+ }
+ },
+ "read-failed": {
+ "description": "请重新加载重试。如果持续失败,说明已存储的策略是 Bytebase 无法解析的,需要运维人员直接修复该行。在无法读取期间,所有 MCP 连接都会被拒绝。",
+ "title": "无法读取访问策略"
+ },
+ "save": "保存策略",
+ "saved": "策略已保存。{{mode}} 将对每个会话的下一次请求生效。",
+ "tightening": "上限变更会对每个运行中会话的下一次请求生效。代理已被放行的工作会继续执行完毕。",
+ "title": "访问策略",
+ "unreadable": {
+ "description": "此工作区存储的能力值是当前构建无法理解的。所有 MCP 连接都会被拒绝。请选择一种模式并保存以修正。",
+ "pick": "请选择一种模式后再保存此策略。",
+ "title": "无法读取已存储的访问策略"
+ },
+ "unserved": {
+ "description": "本工作空间存储的值为 {{stored}},当前版本不提供该上限。所有 MCP 连接都会被拒绝。请选择一种模式并保存以修复。",
+ "title": "当前版本不提供已存储的访问策略"
+ }
+ },
"quick-start": {
"description": "或者使用以下 CLI 命令。",
"title": "方式二:CLI 命令"
diff --git a/frontend/src/routes/workspace/MCPPage.tsx b/frontend/src/routes/workspace/MCPPage.tsx
index 0a27f27bc8..d562d5ed70 100644
--- a/frontend/src/routes/workspace/MCPPage.tsx
+++ b/frontend/src/routes/workspace/MCPPage.tsx
@@ -7,6 +7,8 @@ import { Input } from "@/components/ui/input";
import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { useServerState } from "@/hooks/useAppState";
+import { isDev } from "@/utils";
+import { MCPAccessPolicySection } from "./mcp/MCPAccessPolicySection";
export function MCPPage() {
const { t } = useTranslation();
@@ -79,6 +81,10 @@ export function MCPPage() {
{/* Warning if external URL not configured */}
<ExternalUrlAlert actionAppearance="outline" />
+ {/* Hidden in prod builds until release readiness; the settings API and
+ server-side enforcement stay live intentionally. */}
+ {isDev() && <MCPAccessPolicySection />}
+
{/* Authentication Notice */}
<Alert
variant="info"
diff --git a/frontend/src/routes/workspace/general/GeneralPage.tsx b/frontend/src/routes/workspace/general/GeneralPage.tsx
index e96462658b..9dade81b5c 100644
--- a/frontend/src/routes/workspace/general/GeneralPage.tsx
+++ b/frontend/src/routes/workspace/general/GeneralPage.tsx
@@ -7,7 +7,7 @@ import { WorkspacePageLayout } from "@/components/WorkspacePageLayout";
import { useServerState } from "@/hooks/useAppState";
import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";
import { pushNotification } from "@/stores";
-import { hasWorkspacePermissionV2, isDev } from "@/utils";
+import { hasWorkspacePermissionV2 } from "@/utils";
import { AccountSection } from "./AccountSection";
import { AIAugmentationSection } from "./AIAugmentationSection";
import { AnnouncementSection } from "./AnnouncementSection";
@@ -15,7 +15,6 @@ import { AuditLogSection } from "./AuditLogSection";
import { BrandingSection } from "./BrandingSection";
import { DangerZoneSection } from "./DangerZoneSection";
import { GeneralSection } from "./GeneralSection";
-import { MCPSection } from "./MCPSection";
import { ProductImprovementSection } from "./ProductImprovementSection";
import { SecuritySection } from "./SecuritySection";
import { SQLEditorSection } from "./SQLEditorSection";
@@ -34,7 +33,6 @@ export function GeneralPage() {
const securityRef = useRef<SectionHandle>(null);
const sqlEditorRef = useRef<SectionHandle>(null);
const aiRef = useRef<SectionHandle>(null);
- const mcpRef = useRef<SectionHandle>(null);
const announcementRef = useRef<SectionHandle>(null);
const productImprovementRef = useRef<SectionHandle>(null);
const auditLogRef = useRef<SectionHandle>(null);
@@ -51,7 +49,6 @@ export function GeneralPage() {
securityRef,
sqlEditorRef,
aiRef,
- mcpRef,
announcementRef,
productImprovementRef,
auditLogRef,
@@ -91,12 +88,6 @@ export function GeneralPage() {
handle: announcementRef.current!,
},
];
- if (mcpRef.current) {
- sections.push({
- name: t("settings.general.workspace.mcp.self"),
- handle: mcpRef.current,
- });
- }
if (productImprovementRef.current) {
sections.push({
name: t("settings.general.workspace.product-improvement.self"),
@@ -185,15 +176,6 @@ export function GeneralPage() {
title={t("settings.general.workspace.ai-assistant.self")}
onDirtyChange={onDirtyChange}
/>
- {/* Hidden in prod builds until release readiness; the settings API and
- server-side enforcement stay live intentionally. */}
- {isDev() && (
- <MCPSection
- ref={mcpRef}
- title={t("settings.general.workspace.mcp.self")}
- onDirtyChange={onDirtyChange}
- />
- )}
<AnnouncementSection
ref={announcementRef}
title={t("settings.general.workspace.announcement.self")}
diff --git a/frontend/src/routes/workspace/general/GeneralPageLayout.test.ts b/frontend/src/routes/workspace/general/GeneralPageLayout.test.ts
index cd6c37b633..2f0f9a68f8 100644
--- a/frontend/src/routes/workspace/general/GeneralPageLayout.test.ts
+++ b/frontend/src/routes/workspace/general/GeneralPageLayout.test.ts
@@ -12,7 +12,6 @@ const configurableSections = [
"AuditLogSection.tsx",
"BrandingSection.tsx",
"GeneralSection.tsx",
- "MCPSection.tsx",
"ProductImprovementSection.tsx",
"SecuritySection.tsx",
"SQLEditorSection.tsx",
diff --git a/frontend/src/routes/workspace/general/MCPSection.test.ts b/frontend/src/routes/workspace/general/MCPSection.test.ts
deleted file mode 100644
index 580fe3bd8e..0000000000
--- a/frontend/src/routes/workspace/general/MCPSection.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { describe, expect, test } from "vitest";
-import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";
-import { hydrateWhilePristine, normalizeCapability } from "./MCPSection";
-
-const { CAPABILITY_UNSPECIFIED, DISABLED, READ_ONLY, READ_WRITE } =
- MCPSetting_Capability;
-
-describe("normalizeCapability", () => {
- test("unset renders as Read-write (server resolves absent to READ_WRITE)", () => {
- expect(normalizeCapability(CAPABILITY_UNSPECIFIED)).toBe(READ_WRITE);
- });
-
- test("known values render as themselves", () => {
- expect(normalizeCapability(DISABLED)).toBe(DISABLED);
- expect(normalizeCapability(READ_ONLY)).toBe(READ_ONLY);
- expect(normalizeCapability(READ_WRITE)).toBe(READ_WRITE);
- });
-
- test("unknown and reserved stored values render as Disabled (matching the /mcp fail-closed gate)", () => {
- // 2 is the reserved number (was METADATA_ONLY); 99 is any unknown value.
- expect(normalizeCapability(2 as MCPSetting_Capability)).toBe(DISABLED);
- expect(normalizeCapability(99 as MCPSetting_Capability)).toBe(DISABLED);
- });
-});
-
-describe("hydrateWhilePristine", () => {
- const readWrite = { mcpCapability: MCPSetting_Capability.READ_WRITE };
- const readOnly = { mcpCapability: MCPSetting_Capability.READ_ONLY };
- const disabled = { mcpCapability: MCPSetting_Capability.DISABLED };
-
- test("takes the fetched value when the admin has not touched the form", () => {
- expect(hydrateWhilePristine(readWrite, readWrite, disabled)).toEqual(
- disabled
- );
- });
-
- test("keeps an edit the admin made before the fetch landed", () => {
- // Rendered with the placeholder, admin picked READ_ONLY, then DISABLED
- // arrived from the server. Overwriting here loses the edit and clears the
- // dirty footer with it.
- expect(hydrateWhilePristine(readOnly, readWrite, disabled)).toEqual(
- readOnly
- );
- });
-
- test("is a no-op when the edit already matches what arrived", () => {
- expect(hydrateWhilePristine(disabled, readWrite, disabled)).toEqual(
- disabled
- );
- });
-});
diff --git a/frontend/src/routes/workspace/general/MCPSection.tsx b/frontend/src/routes/workspace/general/MCPSection.tsx
deleted file mode 100644
index ee8e6f3721..0000000000
--- a/frontend/src/routes/workspace/general/MCPSection.tsx
+++ /dev/null
@@ -1,239 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
-import { isEqual } from "lodash-es";
-import {
- forwardRef,
- useCallback,
- useEffect,
- useImperativeHandle,
- useMemo,
- useRef,
- useState,
-} from "react";
-import { useTranslation } from "react-i18next";
-import {
- PermissionGuard,
- usePermissionCheck,
-} from "@/components/PermissionGuard";
-import { FormField, FormFieldGroup, FormSection } from "@/components/ui/form";
-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
-import { useAppStore } from "@/stores/app";
-import {
- MCPSetting_Capability,
- MCPSettingSchema,
- Setting_SettingName,
- SettingValueSchema,
-} from "@/types/proto-es/v1/setting_service_pb";
-import type { SectionHandle } from "./useSettingSection";
-
-interface MCPSectionProps {
- title: string;
- onDirtyChange: () => void;
-}
-
-export interface LocalState {
- mcpCapability: MCPSetting_Capability;
-}
-
-// Unset resolves to READ_WRITE server-side, so it renders as Read-write.
-// Unknown or reserved capability numbers fail closed at /mcp, so they render as
-// Disabled — the option matching their actual behavior; selecting Read-only
-// or Read-write then persists a valid value. A stored capability name this
-// build does not know never reaches that arm: protojson discards it, so it
-// arrives as unset and renders Read-write while /mcp fails closed (BOT-100).
-export const normalizeCapability = (
- capability: MCPSetting_Capability
-): MCPSetting_Capability => {
- switch (capability) {
- case MCPSetting_Capability.CAPABILITY_UNSPECIFIED:
- case MCPSetting_Capability.READ_WRITE:
- return MCPSetting_Capability.READ_WRITE;
- case MCPSetting_Capability.DISABLED:
- case MCPSetting_Capability.READ_ONLY:
- return capability;
- default:
- return MCPSetting_Capability.DISABLED;
- }
-};
-
-/**
- * Re-hydration rule for the form. The store value arrives after the first
- * render, so hydrating unconditionally would replace a capability the admin
- * had already picked in between — and clear the dirty footer that is their
- * only way to save it. `hydratedFrom` is what the form was last hydrated to,
- * so "unedited" is a comparison against that rather than against the value
- * just fetched.
- */
-export const hydrateWhilePristine = (
- current: LocalState,
- hydratedFrom: LocalState,
- next: LocalState
-): LocalState => (isEqual(current, hydratedFrom) ? next : current);
-
-export const MCPSection = forwardRef<SectionHandle, MCPSectionProps>(
- function MCPSection({ title, onDirtyChange }, ref) {
- const { t } = useTranslation();
-
- const [canEdit] = usePermissionCheck(["bb.settings.set"]);
-
- const settingsByName = useAppStore((s) => s.settingsByName);
- const mcpSetting = useMemo(() => {
- const setting = useAppStore
- .getState()
- .getSettingByName(Setting_SettingName.MCP);
- if (setting?.value?.value?.case === "mcp") {
- return setting.value.value.value;
- }
- return undefined;
- }, [settingsByName]);
-
- const getInitialState = useCallback(
- (): LocalState => ({
- mcpCapability: normalizeCapability(
- mcpSetting?.capability ?? MCPSetting_Capability.CAPABILITY_UNSPECIFIED
- ),
- }),
- [mcpSetting]
- );
-
- const [state, setState] = useState<LocalState>(getInitialState);
-
- // Re-sync state when the store value changes (e.g. after the initial
- // fetch, or after a save). Only a pristine form is re-hydrated: the fetch
- // lands after the first render, so an admin who picks a capability in
- // between would otherwise have it replaced by the fetched value — and the
- // dirty footer that is their only way to save it would clear with it.
- const prevMcpSettingRef = useRef(mcpSetting);
- const hydratedRef = useRef<LocalState>(state);
- useEffect(() => {
- if (prevMcpSettingRef.current === mcpSetting) {
- return;
- }
- prevMcpSettingRef.current = mcpSetting;
- const hydrated = getInitialState();
- setState((current) =>
- hydrateWhilePristine(current, hydratedRef.current, hydrated)
- );
- hydratedRef.current = hydrated;
- }, [mcpSetting, getInitialState]);
-
- // Fetch setting on mount.
- useEffect(() => {
- useAppStore
- .getState()
- .getOrFetchSettingByName(Setting_SettingName.MCP, true);
- }, []);
-
- const isDirty = useCallback(
- () => !isEqual(state, getInitialState()),
- [state, getInitialState]
- );
-
- const revert = useCallback(() => {
- setState(getInitialState());
- }, [getInitialState]);
-
- const update = useCallback(async () => {
- const initState = getInitialState();
- if (state.mcpCapability !== initState.mcpCapability) {
- // The server merges the named path onto the stored row, so
- // ignore_masking_exemptions survives a capability-only write.
- await useAppStore.getState().upsertSetting({
- name: Setting_SettingName.MCP,
- value: create(SettingValueSchema, {
- value: {
- case: "mcp",
- value: create(MCPSettingSchema, {
- capability: state.mcpCapability,
- }),
- },
- }),
- updateMask: create(FieldMaskSchema, {
- paths: ["value.mcp.capability"],
- }),
- });
- }
- }, [state, getInitialState]);
-
- useImperativeHandle(
- ref,
- () => ({
- isDirty,
- revert,
- update,
- }),
- [isDirty, revert, update]
- );
-
- // Notify parent when state changes.
- useEffect(() => {
- onDirtyChange();
- }, [state, onDirtyChange]);
-
- const options = [
- {
- capability: MCPSetting_Capability.DISABLED,
- label: t("settings.general.workspace.mcp.capability.disabled.self"),
- description: t(
- "settings.general.workspace.mcp.capability.disabled.description"
- ),
- },
- {
- capability: MCPSetting_Capability.READ_ONLY,
- label: t("settings.general.workspace.mcp.capability.read-only.self"),
- description: t(
- "settings.general.workspace.mcp.capability.read-only.description"
- ),
- },
- {
- capability: MCPSetting_Capability.READ_WRITE,
- label: t("settings.general.workspace.mcp.capability.read-write.self"),
- description: t(
- "settings.general.workspace.mcp.capability.read-write.description"
- ),
- },
- ];
-
- return (
- <FormSection id="mcp" title={title}>
- <PermissionGuard permissions={["bb.settings.set"]} display="block">
- <FormFieldGroup>
- <FormField
- title={t("settings.general.workspace.mcp.capability.self")}
- description={t(
- "settings.general.workspace.mcp.capability.description"
- )}
- className="gap-y-4"
- >
- <RadioGroup
- className="flex-col items-stretch gap-4"
- value={String(state.mcpCapability)}
- onValueChange={(value) =>
- setState({ mcpCapability: Number(value) })
- }
- >
- {options.map((option) => (
- <RadioGroupItem
- key={option.capability}
- value={String(option.capability)}
- disabled={!canEdit || mcpSetting === undefined}
- className="items-start gap-x-3"
- contentClassName="flex flex-col gap-1"
- radioClassName="mt-1"
- >
- <div className="flex flex-col gap-1">
- <div className="textinfo font-semibold">
- {option.label}
- </div>
- <div className="textinfolabel">{option.description}</div>
- </div>
- </RadioGroupItem>
- ))}
- </RadioGroup>
- </FormField>
- </FormFieldGroup>
- </PermissionGuard>
- </FormSection>
- );
- }
-);
diff --git a/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsx b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsx
new file mode 100644
index 0000000000..b55e3c6b24
--- /dev/null
+++ b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsx
@@ -0,0 +1,392 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ useUnsavedChangesGuard: vi.fn(),
+ getSetting: vi.fn(),
+ getMCPInfo: vi.fn(),
+ setSettingByName: vi.fn(),
+ upsertSetting: vi.fn(),
+ hasFeature: vi.fn(() => true),
+ sheetProps: [] as Record<string, unknown>[],
+ mcpSetting: {
+ value: undefined as
+ | {
+ capability: number;
+ ignoreMaskingExemptions: boolean;
+ capabilityUnreadable?: boolean;
+ }
+ | undefined,
+ },
+}));
+
+vi.mock("@/hooks/useUnsavedChangesGuard", () => ({
+ useUnsavedChangesGuard: mocks.useUnsavedChangesGuard,
+}));
+
+vi.mock("@/api", () => ({
+ settingServiceClientConnect: { getSetting: mocks.getSetting },
+ workspaceServiceClientConnect: { getMCPInfo: mocks.getMCPInfo },
+}));
+
+vi.mock("@/components/PermissionGuard", () => ({
+ PermissionGuard: ({
+ children,
+ }: {
+ children: (props: { disabled: boolean }) => ReactElement;
+ }) => children({ disabled: false }),
+}));
+
+// Stubbed to record its props: the drawer is rendered unconditionally, so this
+// captures what the section hands it on every render without opening it.
+vi.mock("./MCPModeContentsSheet", () => ({
+ MCPModeContentsSheet: (props: Record<string, unknown>) => {
+ mocks.sheetProps.push(props);
+ return null;
+ },
+}));
+
+vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));
+
+vi.mock("@/stores/app", () => {
+ const state = {
+ settingsByName: {},
+ getSettingByName: () =>
+ mocks.mcpSetting.value === undefined
+ ? undefined
+ : { value: { value: { case: "mcp", value: mocks.mcpSetting.value } } },
+ setSettingByName: mocks.setSettingByName,
+ upsertSetting: mocks.upsertSetting,
+ hasFeature: mocks.hasFeature,
+ };
+ const useAppStore = (selector: (s: unknown) => unknown) => selector(state);
+ useAppStore.getState = () => state;
+ return { useAppStore };
+});
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+ initReactI18next: { type: "3rdParty", init: () => {} },
+}));
+
+let MCPAccessPolicySection: typeof import("./MCPAccessPolicySection").MCPAccessPolicySection;
+
+const renderIntoContainer = (element: ReactElement) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ return {
+ container,
+ render: () => act(() => root.render(element)),
+ unmount: () => act(() => root.unmount()),
+ };
+};
+
+const flush = () =>
+ act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+const deferred = <T,>() => {
+ let resolve!: (v: T) => void;
+ let reject!: (e: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+};
+
+const toggleMasking = (container: HTMLElement) => {
+ const input = container.querySelector('input[type="checkbox"]');
+ act(() => {
+ (input as HTMLInputElement).click();
+ });
+};
+
+const clickText = (container: HTMLElement, text: string) => {
+ const el = [...container.querySelectorAll("button, label")].find((n) =>
+ n.textContent?.includes(text)
+ );
+ act(() => {
+ (el as HTMLElement)?.click();
+ });
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.sheetProps.length = 0;
+ mocks.mcpSetting.value = {
+ capability: 3, // READ_ONLY
+ ignoreMaskingExemptions: false,
+ capabilityUnreadable: false,
+ };
+ mocks.upsertSetting.mockResolvedValue(undefined);
+ mocks.hasFeature.mockReturnValue(true);
+ mocks.getSetting.mockResolvedValue({ name: "settings/MCP" });
+ mocks.getMCPInfo.mockResolvedValue({
+ capability: 3,
+ ignoreMaskingExemptions: false,
+ dataMaskingAvailable: true,
+ modes: [],
+ methods: [],
+ engines: [],
+ });
+ ({ MCPAccessPolicySection } = await import("./MCPAccessPolicySection"));
+});
+
+describe("MCPAccessPolicySection", () => {
+ // Codex raised exactly this on #21236 after the form moved off GeneralPage,
+ // where it had been registered in the guarded section refs. Without an
+ // assertion the regression returns silently, which is why both sibling forms
+ // pin the call the same way (CreateInstanceView.test.tsx, ReviewCreation.test.tsx).
+ test("registers unsaved edits with the navigation guard", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <MCPAccessPolicySection />
+ );
+ render();
+ await flush();
+
+ expect(mocks.useUnsavedChangesGuard).toHaveBeenLastCalledWith(false);
+
+ clickText(container, "settings.mcp.policy.edit");
+ await flush();
+ expect(mocks.useUnsavedChangesGuard).toHaveBeenLastCalledWith(false);
+
+ // Picking a different ceiling is the unsaved edit that must be guarded.
+ clickText(container, "settings.mcp.policy.mode.disabled.title");
+ await flush();
+ expect(mocks.useUnsavedChangesGuard).toHaveBeenLastCalledWith(true);
+
+ // Cancelling drops the edit, so the guard must stand down again.
+ clickText(container, "common.cancel");
+ await flush();
+ expect(mocks.useUnsavedChangesGuard).toHaveBeenLastCalledWith(false);
+
+ unmount();
+ });
+
+ // The read is deliberately uncached because the row changes out of band. When
+ // it fails, the store may still hold a value from an earlier visit, and
+ // rendering that reports a ceiling nobody is enforcing.
+ test("a failed read outranks a value left in the store", async () => {
+ mocks.getSetting.mockRejectedValue(new Error("does not parse"));
+ const { container, render, unmount } = renderIntoContainer(
+ <MCPAccessPolicySection />
+ );
+ render();
+ await flush();
+
+ expect(container.textContent).toContain(
+ "settings.mcp.policy.read-failed.title"
+ );
+ expect(container.textContent).not.toContain("settings.mcp.policy.in-force");
+ unmount();
+ });
+
+ // Codex, #21236: the drawer opens from a mode card the admin is choosing, so
+ // it previews the candidate policy. Reading the persisted value described the
+ // masking behavior they were about to replace.
+ test("the drawer previews the draft masking value, not the stored one", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <MCPAccessPolicySection />
+ );
+ render();
+ await flush();
+
+ clickText(container, "settings.mcp.policy.edit");
+ await flush();
+ expect(
+ mocks.sheetProps.at(-1)?.ignoreMaskingExemptions
+ ).toBe(false);
+
+ toggleMasking(container);
+ await flush();
+
+ // Self-checking: if the click failed to flip the draft, the guard assertion
+ // fails rather than the prop assertion passing for the wrong reason.
+ expect(mocks.useUnsavedChangesGuard).toHaveBeenLastCalledWith(true);
+ expect(mocks.sheetProps.at(-1)?.ignoreMaskingExemptions).toBe(true);
+ expect(mocks.mcpSetting.value?.ignoreMaskingExemptions).toBe(false);
+
+ unmount();
+ });
+
+ // Codex, #21236. Two halves of one race, both pinned here.
+ test("waits for its own read before offering the cached policy for editing", async () => {
+ // Second visit: the store already holds a value from visit one.
+ const pending = deferred<{ name: string }>();
+ mocks.getSetting.mockReturnValue(pending.promise);
+
+ const { container, render, unmount } = renderIntoContainer(
+ <MCPAccessPolicySection />
+ );
+ render();
+ await flush();
+
+ // The cached ceiling must not be presented as authoritative, and Edit must
+ // not be reachable, while this mount's own read is still in flight.
+ expect(container.textContent).toContain("settings.mcp.policy.loading");
+ expect(container.textContent).not.toContain("settings.mcp.policy.in-force");
+ expect(container.textContent).not.toContain("settings.mcp.policy.edit");
+
+ act(() => pending.resolve({ name: "settings/MCP" }));
+ await flush();
+ expect(container.textContent).toContain("settings.mcp.policy.in-force");
+
+ unmount();
+ });
+
+ test("a mode-contents read that lands after a save does not revert the page", async () => {
+ // The setting read is gated, so the save path cannot start until it
+ // answers. GetMCPInfo is not gated and genuinely fires twice — once on
+ // mount, once after the save — so this is the interleaving that survives.
+ const slowInfo = deferred<Record<string, unknown>>();
+ mocks.getMCPInfo.mockReturnValueOnce(slowInfo.promise);
+ const freshInfo = {
+ capability: 1,
+ ignoreMaskingExemptions: true,
+ dataMaskingAvailable: true,
+ modes: [],
+ methods: [],
+ engines: [],
+ };
+ mocks.getMCPInfo.mockResolvedValue(freshInfo);
+
+ const { container, render, unmount } = renderIntoContainer(
+ <MCPAccessPolicySection />
+ );
+ render();
+ await flush();
+
+ clickText(container, "settings.mcp.policy.edit");
+ await flush();
+ clickText(container, "settings.mcp.policy.mode.disabled.title");
+ await flush();
+ clickText(container, "settings.mcp.policy.save");
+ await flush();
+
+ // Now the mount's read finally answers, with what it captured beforehand.
+ act(() =>
+ slowInfo.resolve({
+ capability: 4,
+ ignoreMaskingExemptions: false,
+ dataMaskingAvailable: false,
+ modes: [],
+ methods: [],
+ engines: [],
+ })
+ );
+ await flush();
+
+ expect(mocks.sheetProps.at(-1)?.info).toBe(freshInfo);
+ unmount();
+ });
+
+ // Codex, #21236: this warning used to be gated on GetMCPInfo, which refuses
+ // outright under an unreadable or unserved ceiling (BOT-106) — the state an
+ // admin is on this page to repair. Hiding it there lets them arm a toggle
+ // that does nothing while believing they tightened masking.
+ test("says masking is unlicensed even when the mode data fails", async () => {
+ mocks.hasFeature.mockReturnValue(false);
+ mocks.getMCPInfo.mockRejectedValue(new Error("the ceiling cannot be read"));
+
+ const { container, render, unmount } = renderIntoContainer(
+ <MCPAccessPolicySection />
+ );
+ render();
+ await flush();
+ clickText(container, "settings.mcp.policy.edit");
+ await flush();
+
+ expect(container.textContent).toContain(
+ "settings.mcp.policy.masking.unavailable"
+ );
+ unmount();
+ });
+
+ // Codex, #21236: the drawer's info is a required prop now, so a pending or
+ // refused GetMCPInfo cannot render as a mode that serves nothing — "0 of 0"
+ // over the workspace whose ceiling the drawer exists to explain. GetMCPInfo
+ // refuses outright under an unreadable ceiling (BOT-106), which is the state
+ // an admin is on this page to repair.
+ test("no mode-contents drawer while the mode data is missing", async () => {
+ mocks.getMCPInfo.mockRejectedValue(new Error("the ceiling cannot be read"));
+
+ const { container, render, unmount } = renderIntoContainer(
+ <MCPAccessPolicySection />
+ );
+ render();
+ await flush();
+
+ // The policy itself still reads, so the page is up and editable.
+ expect(container.textContent).toContain("settings.mcp.policy.in-force");
+ expect(mocks.sheetProps).toHaveLength(0);
+
+ unmount();
+ });
+
+ // Codex, #21236: setSaving gated only the footer buttons. The request has
+ // already captured pick and ignoreMasking, so a card clicked after Save went
+ // out changed the visible draft and nothing else — then the success path
+ // closed the editor and the click was gone, with no sign it had been dropped.
+ test("the policy inputs are locked while a save is in flight", async () => {
+ const inFlight = deferred<undefined>();
+ mocks.upsertSetting.mockReturnValue(inFlight.promise);
+
+ const { container, render, unmount } = renderIntoContainer(
+ <MCPAccessPolicySection />
+ );
+ render();
+ await flush();
+
+ clickText(container, "settings.mcp.policy.edit");
+ await flush();
+ clickText(container, "settings.mcp.policy.mode.disabled.title");
+ await flush();
+
+ const controls = () => [
+ ...container.querySelectorAll('input[type="radio"], input[type="checkbox"]'),
+ ] as HTMLInputElement[];
+ expect(controls().length).toBeGreaterThan(0);
+ expect(controls().every((c) => !c.disabled)).toBe(true);
+
+ clickText(container, "settings.mcp.policy.save");
+ await flush();
+
+ // Still open, still showing the draft — and now untouchable.
+ expect(controls().length).toBeGreaterThan(0);
+ expect(controls().every((c) => c.disabled)).toBe(true);
+
+ act(() => inFlight.resolve(undefined));
+ await flush();
+ unmount();
+ });
+
+ // The generations are per-mount; the setting store they write is the
+ // application's. A read left flying by a visit the admin navigated away from
+ // still passed its own check and wrote — which is Codex's corruption with
+ // "the cached policy" replaced by "the previous visit's unfinished read".
+ test("a read left in flight by an unmounted visit cannot write", async () => {
+ const abandoned = deferred<{ name: string }>();
+ mocks.getSetting.mockReturnValueOnce(abandoned.promise);
+
+ const first = renderIntoContainer(<MCPAccessPolicySection />);
+ first.render();
+ await flush();
+ first.unmount();
+
+ mocks.setSettingByName.mockClear();
+ act(() => abandoned.resolve({ name: "settings/MCP" }));
+ await flush();
+
+ expect(mocks.setSettingByName).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsx b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsx
new file mode 100644
index 0000000000..94bd65f128
--- /dev/null
+++ b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsx
@@ -0,0 +1,524 @@
+import { create } from "@bufbuild/protobuf";
+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+import { createContextValues } from "@connectrpc/connect";
+import { Rows3 } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ settingServiceClientConnect,
+ workspaceServiceClientConnect,
+} from "@/api";
+import { silentContextKey } from "@/api/context-key";
+import { PermissionGuard } from "@/components/PermissionGuard";
+import { Alert } from "@/components/ui/alert";
+import type { BadgeProps } from "@/components/ui/badge";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import { Separator } from "@/components/ui/separator";
+import { Switch } from "@/components/ui/switch";
+import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";
+import { settingNamePrefix } from "@/lib/resourceName";
+import { cn } from "@/lib/utils";
+import { pushNotification } from "@/stores";
+import { useAppStore } from "@/stores/app";
+import {
+ MCPSetting_Capability,
+ MCPSettingSchema,
+ Setting_SettingName,
+ SettingValueSchema,
+} from "@/types/proto-es/v1/setting_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import type { MCPInfo } from "@/types/proto-es/v1/workspace_service_pb";
+import { MCPModeContentsSheet } from "./MCPModeContentsSheet";
+import type { StoredCeiling } from "./mcpPolicy";
+import {
+ ceilingIsBroken,
+ initialCapabilityPick,
+ MCP_CAPABILITY_CHOICES,
+ readStoredCeiling,
+} from "./mcpPolicy";
+
+// One row per ceiling an admin can pick: the locale-key stem, the glyph tone,
+// and the chip variant. The tone and the variant always agree, and carry from
+// the card to the in-force chip, so they belong on one row rather than in
+// parallel tables that can drift apart.
+const MODES: Record<
+ MCPSetting_Capability,
+ { key: string; tone: string; badge: BadgeProps["variant"] }
+> = {
+ [MCPSetting_Capability.CAPABILITY_UNSPECIFIED]: {
+ key: "read-write",
+ tone: "text-warning",
+ badge: "warning",
+ },
+ [MCPSetting_Capability.DISABLED]: {
+ key: "disabled",
+ tone: "text-error",
+ badge: "destructive",
+ },
+ [MCPSetting_Capability.READ_ONLY]: {
+ key: "read-only",
+ tone: "text-success",
+ badge: "success",
+ },
+ [MCPSetting_Capability.READ_WRITE]: {
+ key: "read-write",
+ tone: "text-warning",
+ badge: "warning",
+ },
+};
+
+export function MCPAccessPolicySection() {
+ const { t } = useTranslation();
+
+ const settingsByName = useAppStore((s) => s.settingsByName);
+ // Read from the licence, not from GetMCPInfo. That request refuses outright
+ // under an unreadable or unserved ceiling (BOT-106), which is exactly when an
+ // admin is on this page — and hiding this line there lets them arm a toggle
+ // that does nothing while believing they tightened masking.
+ const dataMaskingAvailable = useAppStore((s) =>
+ s.hasFeature(PlanFeature.FEATURE_DATA_MASKING)
+ );
+ const mcpSetting = useMemo(() => {
+ const setting = useAppStore
+ .getState()
+ .getSettingByName(Setting_SettingName.MCP);
+ if (setting?.value?.value?.case === "mcp") {
+ return setting.value.value.value;
+ }
+ return undefined;
+ }, [settingsByName]);
+
+ const [info, setInfo] = useState<MCPInfo | undefined>(undefined);
+ const [editing, setEditing] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [pick, setPick] = useState<MCPSetting_Capability | undefined>(
+ undefined
+ );
+ const [ignoreMasking, setIgnoreMasking] = useState(false);
+ const [contentsFor, setContentsFor] = useState<
+ MCPSetting_Capability | undefined
+ >(undefined);
+
+ // GetMCPInfo resolves what a mode contains from the live descriptors, so it
+ // is re-read after a save rather than patched: the ceiling in force is part
+ // of the same answer.
+ //
+ // Silent: a ceiling this build cannot read refuses this call, and the banner
+ // below already says so in the words an admin can act on. The interceptor's
+ // toast would put the same fact on screen twice, once as a status code.
+ // Both reads carry a generation, and the effect retires them on unmount. A
+ // response has no way of knowing it was overtaken, and the store it writes is
+ // shared: a read left flying by a visit the admin navigated away from would
+ // otherwise land later and put that visit's row back, reverting a save made
+ // since. getMCPInfo is also re-issued after every save, so its two responses
+ // can land out of order on one mount.
+ const infoGeneration = useRef(0);
+ const settingGeneration = useRef(0);
+
+ const loadInfo = useCallback(() => {
+ const generation = ++infoGeneration.current;
+ workspaceServiceClientConnect
+ .getMCPInfo(
+ {},
+ { contextValues: createContextValues().set(silentContextKey, true) }
+ )
+ .then((next) => {
+ if (generation === infoGeneration.current) {
+ setInfo(next);
+ }
+ })
+ .catch(() => {
+ if (generation === infoGeneration.current) {
+ setInfo(undefined);
+ }
+ });
+ }, []);
+
+ // Read the setting past the store's cache. The server reads this row uncached
+ // for a reason — a hand edit or a newer replica changes it out of band — and
+ // getOrFetchSettingByName returns a cached snapshot without revalidating, so
+ // a second visit in one session would compute the form's dirty state against
+ // a value that is no longer stored. On an unreadable row that makes the
+ // one-save repair unreachable without a reload.
+ const [readFailed, setReadFailed] = useState(false);
+ // Whether this mount's own read has answered. Until it has, a value left in
+ // the store by an earlier visit is a guess, not the ceiling — so the page
+ // waits rather than offering it for editing.
+ const [readSettled, setReadSettled] = useState(false);
+ useEffect(() => {
+ setReadFailed(false);
+ setReadSettled(false);
+ const generation = ++settingGeneration.current;
+ const settle = (failed: boolean) => {
+ if (generation !== settingGeneration.current) {
+ return;
+ }
+ setReadFailed(failed);
+ setReadSettled(true);
+ };
+ settingServiceClientConnect
+ .getSetting(
+ {
+ name: `${settingNamePrefix}${Setting_SettingName[Setting_SettingName.MCP]}`,
+ },
+ {
+ contextValues: createContextValues().set(silentContextKey, true),
+ // The card waits for this read, so an unbounded one is a page that
+ // never loads. The transport declares no default timeout.
+ timeoutMs: 30_000,
+ }
+ )
+ .then((setting) => {
+ if (generation !== settingGeneration.current) {
+ return;
+ }
+ useAppStore.getState().setSettingByName(setting);
+ settle(false);
+ })
+ // A row this build cannot unmarshal fails this read. The store may still
+ // hold a value from an earlier visit, and rendering that would report a
+ // ceiling nobody is enforcing — the failure outranks it below.
+ .catch(() => settle(true));
+ loadInfo();
+ // Retire both reads when this instance goes away. The generations are this
+ // mount's; the setting store they write is the application's.
+ return () => {
+ settingGeneration.current++;
+ infoGeneration.current++;
+ };
+ }, [loadInfo]);
+
+ const stored: StoredCeiling | undefined = useMemo(
+ () => (mcpSetting ? readStoredCeiling(mcpSetting) : undefined),
+ [mcpSetting]
+ );
+ const storedPick = stored ? initialCapabilityPick(stored) : undefined;
+ const storedIgnoreMasking = mcpSetting?.ignoreMaskingExemptions ?? false;
+
+ // The form is seeded when editing opens, not on every store change: the
+ // stored value only moves under an open form when someone else saved, and
+ // replacing an admin's unsaved pick is worse than showing it stale.
+ const startEditing = () => {
+ setPick(storedPick);
+ setIgnoreMasking(storedIgnoreMasking);
+ setEditing(true);
+ };
+
+ const isDirty =
+ editing && (pick !== storedPick || ignoreMasking !== storedIgnoreMasking);
+ // The section this replaced was registered in GeneralPage's guarded refs, so
+ // moving it to its own route would otherwise drop the confirm an admin gets
+ // when navigating away from an unsaved ceiling.
+ useUnsavedChangesGuard(isDirty);
+ // A row nobody can read is repaired by naming a capability. Saving anything
+ // else would erase it, and the server refuses that write.
+ const canSave = isDirty && pick !== undefined;
+
+ const modeLabel = (capability: MCPSetting_Capability): string =>
+ t(`settings.mcp.policy.mode.${MODES[capability].key}.title`);
+
+ const save = async () => {
+ if (pick === undefined) {
+ return;
+ }
+ const paths: string[] = [];
+ if (pick !== storedPick) {
+ paths.push("value.mcp.capability");
+ }
+ if (ignoreMasking !== storedIgnoreMasking) {
+ paths.push("value.mcp.ignore_masking_exemptions");
+ }
+ setSaving(true);
+ try {
+ await useAppStore.getState().upsertSetting({
+ name: Setting_SettingName.MCP,
+ value: create(SettingValueSchema, {
+ value: {
+ case: "mcp",
+ value: create(MCPSettingSchema, {
+ capability: pick,
+ ignoreMaskingExemptions: ignoreMasking,
+ }),
+ },
+ }),
+ updateMask: create(FieldMaskSchema, { paths }),
+ });
+ setEditing(false);
+ loadInfo();
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("settings.mcp.policy.saved", { mode: modeLabel(pick) }),
+ });
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const inForceCapability = (state: StoredCeiling): MCPSetting_Capability =>
+ state.kind === "mode" ? state.capability : MCPSetting_Capability.READ_WRITE;
+
+ // The mode the drawer is showing, frozen while it closes. The Sheet unmounts
+ // after its close animation, so reading contentsFor directly would swap the
+ // contents for another mode's for those ~200ms.
+ const openContentsRef = useRef(MCPSetting_Capability.READ_ONLY);
+ if (contentsFor !== undefined) {
+ openContentsRef.current = contentsFor;
+ }
+ const openContents = openContentsRef.current;
+
+ // Three states share this slot and only the last renders a policy. Early
+ // returns rather than a ternary chain, so each state is named where it is
+ // decided and the card reads as the ordinary case it is.
+ const policyBody = () => {
+ if (readFailed) {
+ return (
+ <Alert
+ variant="error"
+ title={t("settings.mcp.policy.read-failed.title")}
+ description={t("settings.mcp.policy.read-failed.description")}
+ />
+ );
+ }
+ if (!readSettled || !stored) {
+ return (
+ <p className="textinfolabel">{t("settings.mcp.policy.loading")}</p>
+ );
+ }
+ return (
+ <div className="rounded-sm border border-control-border p-4 flex flex-col gap-y-4">
+ <div className="flex items-start justify-between gap-x-2">
+ {ceilingIsBroken(stored) ? (
+ <span className="text-sm font-medium text-warning">
+ {t(
+ stored.kind === "unreadable"
+ ? "settings.mcp.policy.unreadable.title"
+ : "settings.mcp.policy.unserved.title"
+ )}
+ </span>
+ ) : (
+ <div className="flex flex-wrap items-center gap-2">
+ <Rows3
+ className={cn(
+ "size-4 shrink-0",
+ MODES[inForceCapability(stored)].tone
+ )}
+ />
+ <span className="text-sm text-control-light">
+ {t("settings.mcp.policy.in-force")}
+ </span>
+ <Badge variant={MODES[inForceCapability(stored)].badge}>
+ {modeLabel(inForceCapability(stored))}
+ </Badge>
+ {storedIgnoreMasking && (
+ <Badge variant="secondary">
+ {t("settings.mcp.policy.masking.badge")}
+ </Badge>
+ )}
+ </div>
+ )}
+ {!editing && (
+ <PermissionGuard permissions={["bb.settings.set"]}>
+ {({ disabled }) => (
+ <Button
+ appearance="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={startEditing}
+ >
+ {t("settings.mcp.policy.edit")}
+ </Button>
+ )}
+ </PermissionGuard>
+ )}
+ </div>
+
+ {ceilingIsBroken(stored) && (
+ <Alert
+ variant="warning"
+ description={
+ stored.kind === "unreadable"
+ ? t("settings.mcp.policy.unreadable.description")
+ : t("settings.mcp.policy.unserved.description", {
+ stored: stored.stored,
+ })
+ }
+ />
+ )}
+
+ {editing ? (
+ <>
+ {/* Locked while the save is out: the request already captured
+ this draft, so a later edit would change what is on screen and
+ nothing else, then vanish when the editor closes. */}
+ <RadioGroup
+ aria-label={t("settings.mcp.policy.title")}
+ className="grid grid-cols-1 gap-4 md:grid-cols-3"
+ disabled={saving}
+ value={pick === undefined ? "" : String(pick)}
+ onValueChange={(value) => setPick(Number(value))}
+ >
+ {MCP_CAPABILITY_CHOICES.map((capability) => {
+ const mode = MODES[capability];
+ return (
+ <RadioGroupItem
+ key={capability}
+ value={String(capability)}
+ // The item wraps the whole card in a label, so without
+ // this the radio's name absorbs the description, the
+ // contents link and the "Best for" line.
+ aria-label={t(`settings.mcp.policy.mode.${mode.key}.title`)}
+ className={cn(
+ "relative h-full flex-col items-stretch rounded-sm border p-4",
+ pick === capability
+ ? "border-accent"
+ : "border-control-border"
+ )}
+ contentClassName="flex h-full flex-col gap-2"
+ radioClassName="absolute right-4 top-4"
+ >
+ <div className="flex items-center gap-x-2 pr-6">
+ <Rows3 className={cn("size-4 shrink-0", mode.tone)} />
+ <span className="textinfo font-semibold">
+ {t(`settings.mcp.policy.mode.${mode.key}.title`)}
+ </span>
+ </div>
+ <p className="textinfolabel">
+ {t(`settings.mcp.policy.mode.${mode.key}.description`)}
+ </p>
+ {info && capability !== MCPSetting_Capability.DISABLED && (
+ <Button
+ appearance="link"
+ size="sm"
+ className="self-start px-0"
+ onClick={(e) => {
+ // This sits inside the card's own label, so a click
+ // here would otherwise pick the mode too.
+ e.preventDefault();
+ e.stopPropagation();
+ setContentsFor(capability);
+ }}
+ >
+ {t("settings.mcp.policy.mode.contents", {
+ mode: modeLabel(capability),
+ })}
+ </Button>
+ )}
+ {/* Pinned to the bottom so the three "Best for" lines sit
+ on one row, however long each description runs. */}
+ <p className="textinfolabel mt-auto pt-2">
+ {t(`settings.mcp.policy.mode.${mode.key}.best-for`)}
+ </p>
+ </RadioGroupItem>
+ );
+ })}
+ </RadioGroup>
+
+ <div className="flex items-start gap-x-3">
+ <Switch
+ checked={ignoreMasking}
+ onCheckedChange={setIgnoreMasking}
+ disabled={saving}
+ aria-label={t("settings.mcp.policy.masking.title")}
+ className="mt-0.5"
+ />
+ <div className="flex flex-col gap-1">
+ <div className="textinfo font-semibold">
+ {t("settings.mcp.policy.masking.title")}
+ </div>
+ <div className="textinfolabel">
+ {t("settings.mcp.policy.masking.description")}
+ </div>
+ <div className="textinfolabel">
+ {t("settings.mcp.policy.masking.limits")}
+ </div>
+ {!dataMaskingAvailable && (
+ <div className="text-sm text-warning">
+ {t("settings.mcp.policy.masking.unavailable")}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {pick === undefined && (
+ <p className="text-sm text-warning">
+ {t("settings.mcp.policy.unreadable.pick")}
+ </p>
+ )}
+
+ <Separator />
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <p className="textinfolabel">
+ {t("settings.mcp.policy.tightening")}
+ </p>
+ <div className="flex shrink-0 gap-x-2">
+ <Button
+ appearance="outline"
+ disabled={saving}
+ onClick={() => setEditing(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button disabled={!canSave || saving} onClick={save}>
+ {t("settings.mcp.policy.save")}
+ </Button>
+ </div>
+ </div>
+ </>
+ ) : (
+ <>
+ {!ceilingIsBroken(stored) && (
+ <p className="textinfolabel">
+ {t(
+ `settings.mcp.policy.mode.${
+ MODES[inForceCapability(stored)].key
+ }.description`
+ )}
+ </p>
+ )}
+ <div className="flex flex-col gap-y-1">
+ <p className="textinfolabel">
+ {t("settings.mcp.policy.tightening")}
+ </p>
+ <p className="textinfolabel">{t("settings.mcp.policy.audit")}</p>
+ </div>
+ </>
+ )}
+ </div>
+ );
+ };
+
+ return (
+ <div className="flex flex-col gap-y-3">
+ <div className="flex flex-col gap-y-1">
+ <h3 className="text-base font-medium">
+ {t("settings.mcp.policy.title")}
+ </h3>
+ <p className="textinfolabel">{t("settings.mcp.policy.description")}</p>
+ </div>
+
+ {policyBody()}
+
+ {/* No info, no drawer. The trigger is already gated on it, and rendering
+ without it would describe a mode that serves nothing rather than
+ admitting the contents are unknown. */}
+ {info && (
+ <MCPModeContentsSheet
+ open={contentsFor !== undefined}
+ capability={openContents}
+ info={info}
+ modeLabel={modeLabel(openContents)}
+ // While editing, the drawer previews the policy about to be saved,
+ // not the one stored — the admin opens it from a card they are
+ // choosing.
+ ignoreMaskingExemptions={
+ editing ? ignoreMasking : storedIgnoreMasking
+ }
+ onClose={() => setContentsFor(undefined)}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/routes/workspace/mcp/MCPModeContentsSheet.test.tsx b/frontend/src/routes/workspace/mcp/MCPModeContentsSheet.test.tsx
new file mode 100644
index 0000000000..668552d676
--- /dev/null
+++ b/frontend/src/routes/workspace/mcp/MCPModeContentsSheet.test.tsx
@@ -0,0 +1,191 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";
+import { MCPEngineEnforcement_ReadOnlyDepth } from "@/types/proto-es/v1/workspace_service_pb";
+import { MCPMethodClass } from "@/types/proto-es/v1/annotation_pb";
+import { MCPModeContentsSheet } from "./MCPModeContentsSheet";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+ initReactI18next: { type: "3rdParty", init: () => {} },
+}));
+
+const REDSHIFT_NOTE =
+ "Outside a datashare database the driver also opens the session read-only. " +
+ "A datashare database cannot run a read-only transaction, so there it is " +
+ "statement classification alone.";
+
+const info = {
+ workspace: "workspaces/ws",
+ capability: MCPSetting_Capability.READ_ONLY,
+ modes: [
+ {
+ capability: MCPSetting_Capability.READ_ONLY,
+ servedClasses: [MCPMethodClass.READ],
+ },
+ ],
+ methods: [
+ {
+ method: "/bytebase.v1.SQLService/Query",
+ operationId: "bytebase.v1.SQLService.Query",
+ class: MCPMethodClass.READ,
+ permission: "bb.sql.select",
+ authMethod: 0,
+ },
+ {
+ method: "/bytebase.v1.ActuatorService/GetActuatorInfo",
+ operationId: "bytebase.v1.ActuatorService.GetActuatorInfo",
+ class: MCPMethodClass.READ,
+ permission: "",
+ authMethod: 0,
+ },
+ ],
+ engines: [
+ {
+ engine: Engine.REDSHIFT,
+ readOnlyDepth: MCPEngineEnforcement_ReadOnlyDepth.STATEMENT,
+ masking: 0,
+ note: REDSHIFT_NOTE,
+ },
+ ],
+ ignoreMaskingExemptions: false,
+ dataMaskingAvailable: true,
+} as unknown as Parameters<typeof MCPModeContentsSheet>[0]["info"];
+
+// The sheet portals, so the container is attached to the document.
+const renderSheet = (element: ReactElement) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => root.render(element));
+ return () => {
+ act(() => root.unmount());
+ container.remove();
+ };
+};
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+describe("MCPModeContentsSheet", () => {
+ // Codex, #21236: engine.note is server-authored English (mcp_info.go
+ // mcpEngineNote). Rendering it raw shows English in every other locale, which
+ // is the rule at AGENTS.md:146-150. The server owns whether an engine has a
+ // caveat; the words are the frontend's.
+ test("translates the engine note instead of rendering the server's prose", () => {
+ const unmount = renderSheet(
+ <MCPModeContentsSheet
+ open
+ capability={MCPSetting_Capability.READ_ONLY}
+ info={info}
+ modeLabel="Read-only"
+ ignoreMaskingExemptions={false}
+ onClose={() => {}}
+ />
+ );
+
+ expect(document.body.textContent).toContain(
+ "settings.mcp.contents.notes.redshift"
+ );
+ expect(document.body.textContent).not.toContain("datashare");
+
+ unmount();
+ });
+
+ // Codex, #21236: a newer backend can attach a note to an engine this bundle
+ // has no wording for. Returning the server's sentence put English prose in
+ // every locale; dropping it lost a caveat that is the only place a
+ // per-engine floor is stated. It announces the caveat in the viewer's
+ // language and names the remedy instead.
+ test("an engine with no wording announces the caveat rather than quoting it", () => {
+ const future = {
+ ...info,
+ engines: [
+ {
+ engine: Engine.SPANNER,
+ readOnlyDepth: MCPEngineEnforcement_ReadOnlyDepth.STATEMENT,
+ masking: 0,
+ note: "Spanner does something this build has never heard of.",
+ },
+ ],
+ } as unknown as Parameters<typeof MCPModeContentsSheet>[0]["info"];
+
+ const unmount = renderSheet(
+ <MCPModeContentsSheet
+ open
+ capability={MCPSetting_Capability.READ_ONLY}
+ info={future}
+ modeLabel="Read-only"
+ ignoreMaskingExemptions={false}
+ onClose={() => {}}
+ />
+ );
+
+ expect(document.body.textContent).toContain(
+ "settings.mcp.contents.notes.unavailable"
+ );
+ expect(document.body.textContent).not.toContain("never heard of");
+
+ unmount();
+ });
+
+ test("the masking description follows the value it is given", () => {
+ const unmount = renderSheet(
+ <MCPModeContentsSheet
+ open
+ capability={MCPSetting_Capability.READ_ONLY}
+ info={info}
+ modeLabel="Read-only"
+ ignoreMaskingExemptions
+ onClose={() => {}}
+ />
+ );
+
+ // Not info.ignoreMaskingExemptions, which is false above.
+ expect(document.body.textContent).toContain(
+ "settings.mcp.contents.masking.description-on"
+ );
+ expect(document.body.textContent).not.toContain(
+ "settings.mcp.contents.masking.description-off"
+ );
+
+ unmount();
+ });
+
+ // Codex, #21236: the permission lived in a native title on a Badge, which is
+ // a span — unfocusable, so a keyboard user could never read it, and it
+ // appeared nowhere else. It is rendered now.
+ test("renders each method's permission rather than hiding it in a tooltip", () => {
+ const unmount = renderSheet(
+ <MCPModeContentsSheet
+ open
+ capability={MCPSetting_Capability.READ_ONLY}
+ info={info}
+ modeLabel="Read-only"
+ ignoreMaskingExemptions={false}
+ onClose={() => {}}
+ />
+ );
+
+ expect(document.body.textContent).toContain("bb.sql.select");
+ // A method that authorizes in its handler says so, rather than blank.
+ expect(document.body.textContent).toContain(
+ "settings.mcp.contents.methods.handler"
+ );
+ // Nothing depends on hover: no title attribute carries the information.
+ const titled = [...document.querySelectorAll("[title]")].filter((n) =>
+ n.getAttribute("title")?.includes("bb.")
+ );
+ expect(titled).toHaveLength(0);
+
+ unmount();
+ });
+});
diff --git a/frontend/src/routes/workspace/mcp/MCPModeContentsSheet.tsx b/frontend/src/routes/workspace/mcp/MCPModeContentsSheet.tsx
new file mode 100644
index 0000000000..2f77b14cd2
--- /dev/null
+++ b/frontend/src/routes/workspace/mcp/MCPModeContentsSheet.tsx
@@ -0,0 +1,273 @@
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { Separator } from "@/components/ui/separator";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/ui/sheet";
+import { cn } from "@/lib/utils";
+import { MCPMethodClass } from "@/types/proto-es/v1/annotation_pb";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";
+import type { MCPInfo } from "@/types/proto-es/v1/workspace_service_pb";
+import {
+ MCPEngineEnforcement_Masking,
+ MCPEngineEnforcement_ReadOnlyDepth,
+} from "@/types/proto-es/v1/workspace_service_pb";
+import { engineNameV1 } from "@/utils";
+import {
+ engineNotes,
+ groupEnginesByMasking,
+ groupEnginesByReadOnlyDepth,
+ groupMethodsByService,
+ methodsServedBy,
+ modeFor,
+} from "./mcpPolicy";
+
+const engineLabel = (engine: Engine): string =>
+ engineNameV1(engine) || Engine[engine] || String(engine);
+
+interface Props {
+ readonly open: boolean;
+ readonly capability: MCPSetting_Capability;
+ /**
+ * Required, and every caller gates its trigger on having it. An optional one
+ * would let a pending or refused GetMCPInfo render as a mode that serves
+ * nothing — "0 of 0" over a workspace whose ceiling this drawer exists to
+ * explain. GetMCPInfo refuses outright under an unreadable or unserved
+ * ceiling (BOT-106), which is exactly when an admin opens this.
+ */
+ readonly info: MCPInfo;
+ readonly modeLabel: string;
+ /**
+ * The masking answer this drawer describes. Required, not defaulted from
+ * `info`: the settings form previews a candidate policy the admin has not
+ * saved, the consent page describes the one in force, and defaulting to
+ * either silently gives the other consumer the wrong one.
+ */
+ readonly ignoreMaskingExemptions: boolean;
+ readonly onClose: () => void;
+}
+
+export function MCPModeContentsSheet({
+ open,
+ capability,
+ info,
+ modeLabel,
+ ignoreMaskingExemptions,
+ onClose,
+}: Props) {
+ const { t } = useTranslation();
+
+ const served = useMemo(
+ () => methodsServedBy(modeFor(info, capability), info.methods),
+ [info, capability]
+ );
+ const groups = useMemo(() => groupMethodsByService(served), [served]);
+ // What this mode adds over Read-only: the WRITE class is the only one a
+ // lower ceiling does not serve, so highlighting it is the mode delta.
+ const writeCount = useMemo(
+ () => served.filter((m) => m.class === MCPMethodClass.WRITE).length,
+ [served]
+ );
+ const depthGroups = useMemo(
+ () => groupEnginesByReadOnlyDepth(info.engines),
+ [info]
+ );
+ const maskingGroups = useMemo(
+ () => groupEnginesByMasking(info.engines),
+ [info]
+ );
+ const notes = useMemo(() => engineNotes(info.engines), [info]);
+
+ const depthText = (depth: MCPEngineEnforcement_ReadOnlyDepth): string => {
+ switch (depth) {
+ case MCPEngineEnforcement_ReadOnlyDepth.STATEMENT_AND_SESSION:
+ return t("settings.mcp.contents.depth.statement-and-session");
+ case MCPEngineEnforcement_ReadOnlyDepth.STATEMENT:
+ return t("settings.mcp.contents.depth.statement");
+ case MCPEngineEnforcement_ReadOnlyDepth.UNSUPPORTED:
+ return t("settings.mcp.contents.depth.unsupported");
+ default:
+ return t("settings.mcp.contents.depth.unspecified");
+ }
+ };
+
+ // The server's note is English prose and is never rendered. The console keys
+ // off the engine, which is what keeps the caveat translated — and a newer
+ // backend can carry a note for an engine this bundle has no wording for, so
+ // the caveat is still announced rather than dropped or shown in English.
+ // The caller only passes engines that have a note (engineNotes filters).
+ const noteText = (engine: Engine): string =>
+ engine === Engine.REDSHIFT
+ ? t("settings.mcp.contents.notes.redshift")
+ : t("settings.mcp.contents.notes.unavailable");
+
+ const maskingText = (masking: MCPEngineEnforcement_Masking): string => {
+ switch (masking) {
+ case MCPEngineEnforcement_Masking.COLUMN:
+ return t("settings.mcp.contents.masking.column");
+ case MCPEngineEnforcement_Masking.DOCUMENT:
+ return t("settings.mcp.contents.masking.document");
+ case MCPEngineEnforcement_Masking.NONE:
+ return t("settings.mcp.contents.masking.none");
+ default:
+ return t("settings.mcp.contents.masking.unspecified");
+ }
+ };
+
+ return (
+ <Sheet open={open} onOpenChange={(next) => !next && onClose()}>
+ <SheetContent width="standard">
+ <SheetHeader>
+ <SheetTitle>
+ {t("settings.mcp.contents.title", { mode: modeLabel })}
+ </SheetTitle>
+ <SheetDescription>
+ {t("settings.mcp.contents.methods.count", {
+ served: served.length,
+ total: info?.methods.length ?? 0,
+ })}
+ {writeCount > 0 && (
+ <>
+ {" "}
+ {t("settings.mcp.contents.methods.write-legend", {
+ count: writeCount,
+ })}
+ </>
+ )}
+ </SheetDescription>
+ </SheetHeader>
+
+ <SheetBody>
+ <div className="flex flex-col gap-y-6">
+ <section className="flex flex-col gap-y-4">
+ {groups.length === 0 ? (
+ <p className="textinfolabel">
+ {t("settings.mcp.contents.methods.none")}
+ </p>
+ ) : (
+ groups.map((group) => (
+ <div key={group.service} className="flex flex-col gap-y-2">
+ <h4 className="text-xs font-medium tracking-wide text-control-light">
+ {group.service}
+ </h4>
+ {/* The permission is rendered, not hovered. It used to sit
+ in a native title on a Badge, which is a span: a keyboard
+ user could never open it, and it was the only place the
+ permission appeared. */}
+ <div className="flex flex-col gap-y-1">
+ {group.methods.map((method) => (
+ <div
+ key={method.method}
+ className="grid grid-cols-[1fr_auto] items-baseline gap-x-4 text-xs"
+ >
+ <span
+ className={cn(
+ "font-mono",
+ method.class === MCPMethodClass.WRITE
+ ? "text-warning"
+ : "text-main"
+ )}
+ >
+ {method.operationId.split(".").pop()}
+ </span>
+ <span className="font-mono text-control-light">
+ {method.permission ||
+ t("settings.mcp.contents.methods.handler")}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ ))
+ )}
+ </section>
+
+ {capability === MCPSetting_Capability.READ_ONLY && (
+ <>
+ <Separator />
+ <section className="flex flex-col gap-y-3">
+ <div className="flex flex-col gap-y-1">
+ <h3 className="text-base font-medium">
+ {t("settings.mcp.contents.depth.title")}
+ </h3>
+ <p className="textinfolabel">
+ {t("settings.mcp.contents.depth.description")}
+ </p>
+ </div>
+ {depthGroups.map((group) => (
+ <div key={group.value} className="flex flex-col gap-y-1">
+ <p className="text-sm text-main">
+ {depthText(group.value)}
+ </p>
+ <p className="text-sm text-control-light">
+ {group.engines.map(engineLabel).join(", ")}
+ </p>
+ </div>
+ ))}
+ <p className="textinfolabel">
+ {t("settings.mcp.contents.depth.not-a-proof")}
+ </p>
+ </section>
+ </>
+ )}
+
+ <Separator />
+ <section className="flex flex-col gap-y-3">
+ <div className="flex flex-col gap-y-1">
+ <h3 className="text-base font-medium">
+ {t("settings.mcp.contents.masking.title")}
+ </h3>
+ <p className="textinfolabel">
+ {ignoreMaskingExemptions
+ ? t("settings.mcp.contents.masking.description-on")
+ : t("settings.mcp.contents.masking.description-off")}
+ </p>
+ </div>
+ {!info.dataMaskingAvailable && (
+ <p className="text-sm text-warning">
+ {t("settings.mcp.policy.masking.unavailable")}
+ </p>
+ )}
+ {maskingGroups.map((group) => (
+ <div key={group.value} className="flex flex-col gap-y-1">
+ <p className="text-sm text-main">
+ {maskingText(group.value)}
+ </p>
+ <p className="text-sm text-control-light">
+ {group.engines.map(engineLabel).join(", ")}
+ </p>
+ </div>
+ ))}
+ </section>
+
+ {notes.length > 0 && (
+ <>
+ <Separator />
+ <section className="flex flex-col gap-y-2">
+ <h3 className="text-base font-medium">
+ {t("settings.mcp.contents.notes.title")}
+ </h3>
+ {notes.map((engine) => (
+ <p key={engine.engine} className="text-sm text-control">
+ <span className="font-medium">
+ {engineLabel(engine.engine)}
+ </span>
+ {": "}
+ {noteText(engine.engine)}
+ </p>
+ ))}
+ </section>
+ </>
+ )}
+ </div>
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/frontend/src/routes/workspace/mcp/mcpPolicy.test.ts b/frontend/src/routes/workspace/mcp/mcpPolicy.test.ts
new file mode 100644
index 0000000000..2f70eb74eb
--- /dev/null
+++ b/frontend/src/routes/workspace/mcp/mcpPolicy.test.ts
@@ -0,0 +1,273 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test } from "vitest";
+import { MCPMethodClass } from "@/types/proto-es/v1/annotation_pb";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import {
+ MCPSetting_Capability,
+ MCPSettingSchema,
+} from "@/types/proto-es/v1/setting_service_pb";
+import {
+ MCPCapabilityModeSchema,
+ MCPEngineEnforcement_Masking,
+ MCPEngineEnforcement_ReadOnlyDepth,
+ MCPEngineEnforcementSchema,
+ MCPMethodSchema,
+} from "@/types/proto-es/v1/workspace_service_pb";
+import {
+ ceilingIsBroken,
+ groupEnginesByMasking,
+ groupEnginesByReadOnlyDepth,
+ groupMethodsByService,
+ initialCapabilityPick,
+ methodsServedBy,
+ readStoredCeiling,
+ serviceOfMethod,
+} from "./mcpPolicy";
+
+const setting = (
+ fields: Partial<{ capability: number; unreadable: boolean }>
+) =>
+ create(MCPSettingSchema, {
+ capability:
+ fields.capability ?? MCPSetting_Capability.CAPABILITY_UNSPECIFIED,
+ capabilityUnreadable: fields.unreadable ?? false,
+ });
+
+describe("readStoredCeiling", () => {
+ test("a stored mode is the mode", () => {
+ expect(readStoredCeiling(setting({ capability: 3 }))).toEqual({
+ kind: "mode",
+ capability: MCPSetting_Capability.READ_ONLY,
+ });
+ });
+
+ test("no row is unconfigured, not a choice", () => {
+ expect(readStoredCeiling(setting({}))).toEqual({ kind: "unconfigured" });
+ });
+
+ test("an unreadable row is its own state, never read-write", () => {
+ // The defect BOT-100 records: the two arrive as the same capability and
+ // mean opposite things — one resolves READ_WRITE, the other is refused.
+ const stored = readStoredCeiling(setting({ unreadable: true }));
+ expect(stored).toEqual({ kind: "unreadable" });
+ expect(readStoredCeiling(setting({}))).toEqual({ kind: "unconfigured" });
+ });
+
+ test("the flag outranks a capability that parsed away to unset", () => {
+ // The row reads back CAPABILITY_UNSPECIFIED either way. Only the flag
+ // separates a ceiling nobody can resolve from a workspace that never
+ // configured one, and they resolve to opposite ceilings — refused, versus
+ // the READ_WRITE default (BOT-100).
+ expect(readStoredCeiling(setting({ unreadable: true }))).toEqual({
+ kind: "unreadable",
+ });
+ expect(readStoredCeiling(setting({}))).toEqual({ kind: "unconfigured" });
+ });
+
+ test("a number no mode serves is unserved", () => {
+ // The reserved 2 (was METADATA_ONLY), or a ceiling a newer release wrote.
+ expect(readStoredCeiling(setting({ capability: 2 }))).toEqual({
+ kind: "unserved",
+ stored: "2",
+ });
+ });
+});
+
+describe("initialCapabilityPick", () => {
+ test("a stored mode preselects itself", () => {
+ expect(
+ initialCapabilityPick({
+ kind: "mode",
+ capability: MCPSetting_Capability.DISABLED,
+ })
+ ).toBe(MCPSetting_Capability.DISABLED);
+ });
+
+ test("an unconfigured row preselects the ceiling it resolves to", () => {
+ expect(initialCapabilityPick({ kind: "unconfigured" })).toBe(
+ MCPSetting_Capability.READ_WRITE
+ );
+ });
+
+ test("a broken row preselects nothing, so every pick is savable", () => {
+ // Preselecting read-write here is what left an admin unable to repair the
+ // row to read-write at all: the pick matched the preselection, so the form
+ // was never dirty and the footer never enabled.
+ for (const stored of [
+ { kind: "unreadable" as const },
+ { kind: "unserved" as const, stored: "2" },
+ ]) {
+ expect(ceilingIsBroken(stored)).toBe(true);
+ expect(initialCapabilityPick(stored)).toBeUndefined();
+ }
+ });
+
+ test("a readable row is not broken", () => {
+ // Without this the whole suite passes on `ceilingIsBroken = () => true`,
+ // which would put every workspace into the repair banner.
+ expect(ceilingIsBroken({ kind: "unconfigured" })).toBe(false);
+ expect(
+ ceilingIsBroken({
+ kind: "mode",
+ capability: MCPSetting_Capability.READ_ONLY,
+ })
+ ).toBe(false);
+ });
+});
+
+describe("methodsServedBy", () => {
+ const query = create(MCPMethodSchema, {
+ method: "/bytebase.v1.SQLService/Query",
+ operationId: "bytebase.v1.SQLService.Query",
+ class: MCPMethodClass.READ,
+ });
+ const createSheet = create(MCPMethodSchema, {
+ method: "/bytebase.v1.SheetService/CreateSheet",
+ operationId: "bytebase.v1.SheetService.CreateSheet",
+ class: MCPMethodClass.WRITE,
+ });
+
+ test("a mode serves a method when it serves the method's class", () => {
+ const readOnly = create(MCPCapabilityModeSchema, {
+ capability: MCPSetting_Capability.READ_ONLY,
+ servedClasses: [MCPMethodClass.READ],
+ });
+ expect(methodsServedBy(readOnly, [query, createSheet])).toEqual([query]);
+ });
+
+ test("a mode that serves nothing serves nothing", () => {
+ const disabled = create(MCPCapabilityModeSchema, {
+ capability: MCPSetting_Capability.DISABLED,
+ servedClasses: [],
+ });
+ expect(methodsServedBy(disabled, [query, createSheet])).toEqual([]);
+ expect(methodsServedBy(undefined, [query, createSheet])).toEqual([]);
+ });
+});
+
+describe("grouping", () => {
+ test("methods group under their service's short name", () => {
+ const rows = [
+ create(MCPMethodSchema, {
+ method: "/bytebase.v1.SQLService/Query",
+ operationId: "bytebase.v1.SQLService.Query",
+ }),
+ create(MCPMethodSchema, {
+ method: "/bytebase.v1.SQLService/Export",
+ operationId: "bytebase.v1.SQLService.Export",
+ }),
+ create(MCPMethodSchema, {
+ method: "/bytebase.v1.DatabaseService/GetDatabase",
+ operationId: "bytebase.v1.DatabaseService.GetDatabase",
+ }),
+ ];
+ expect(serviceOfMethod(rows[0])).toBe("SQLService");
+ expect(groupMethodsByService(rows)).toEqual([
+ { service: "DatabaseService", methods: [rows[2]] },
+ { service: "SQLService", methods: [rows[1], rows[0]] },
+ ]);
+ });
+
+ // Codex, #21236: a bundle in an open tab can outlive a backend upgrade, and
+ // the server answers with the depth it computed, not the ones this build was
+ // compiled against. Filtering the known order dropped the group entirely, so
+ // the engine left the page rather than being described imprecisely — and both
+ // renderers already have a default arm for exactly this.
+ test("a depth this build does not know sorts last instead of vanishing", () => {
+ const future = 99 as MCPEngineEnforcement_ReadOnlyDepth;
+ const engines = [
+ create(MCPEngineEnforcementSchema, {
+ engine: Engine.SPANNER,
+ readOnlyDepth: future,
+ }),
+ create(MCPEngineEnforcementSchema, {
+ engine: Engine.POSTGRES,
+ readOnlyDepth: MCPEngineEnforcement_ReadOnlyDepth.STATEMENT_AND_SESSION,
+ }),
+ ];
+ expect(groupEnginesByReadOnlyDepth(engines)).toEqual([
+ {
+ value: MCPEngineEnforcement_ReadOnlyDepth.STATEMENT_AND_SESSION,
+ engines: [Engine.POSTGRES],
+ },
+ { value: future, engines: [Engine.SPANNER] },
+ ]);
+ });
+
+ test("a masking mode this build does not know sorts last too", () => {
+ const future = 99 as MCPEngineEnforcement_Masking;
+ const engines = [
+ create(MCPEngineEnforcementSchema, {
+ engine: Engine.SPANNER,
+ masking: future,
+ }),
+ create(MCPEngineEnforcementSchema, {
+ engine: Engine.POSTGRES,
+ masking: MCPEngineEnforcement_Masking.COLUMN,
+ }),
+ ];
+ expect(groupEnginesByMasking(engines)).toEqual([
+ {
+ value: MCPEngineEnforcement_Masking.COLUMN,
+ engines: [Engine.POSTGRES],
+ },
+ { value: future, engines: [Engine.SPANNER] },
+ ]);
+ });
+
+ test("engines group by read-only depth, deepest first", () => {
+ const engines = [
+ create(MCPEngineEnforcementSchema, {
+ engine: Engine.MYSQL,
+ readOnlyDepth: MCPEngineEnforcement_ReadOnlyDepth.STATEMENT,
+ }),
+ create(MCPEngineEnforcementSchema, {
+ engine: Engine.POSTGRES,
+ readOnlyDepth: MCPEngineEnforcement_ReadOnlyDepth.STATEMENT_AND_SESSION,
+ }),
+ create(MCPEngineEnforcementSchema, {
+ engine: Engine.DATABRICKS,
+ readOnlyDepth: MCPEngineEnforcement_ReadOnlyDepth.UNSUPPORTED,
+ }),
+ ];
+ expect(groupEnginesByReadOnlyDepth(engines)).toEqual([
+ {
+ value: MCPEngineEnforcement_ReadOnlyDepth.STATEMENT_AND_SESSION,
+ engines: [Engine.POSTGRES],
+ },
+ {
+ value: MCPEngineEnforcement_ReadOnlyDepth.STATEMENT,
+ engines: [Engine.MYSQL],
+ },
+ {
+ value: MCPEngineEnforcement_ReadOnlyDepth.UNSUPPORTED,
+ engines: [Engine.DATABRICKS],
+ },
+ ]);
+ });
+
+ test("masking keeps three states, never two", () => {
+ // An engine Bytebase does not mask and an engine that masks without
+ // consulting exemptions are different answers to "does ignoring exemptions
+ // change anything here", and the copy must not flatten them.
+ const engines = [
+ create(MCPEngineEnforcementSchema, {
+ engine: Engine.REDIS,
+ masking: MCPEngineEnforcement_Masking.NONE,
+ }),
+ create(MCPEngineEnforcementSchema, {
+ engine: Engine.MONGODB,
+ masking: MCPEngineEnforcement_Masking.DOCUMENT,
+ }),
+ create(MCPEngineEnforcementSchema, {
+ engine: Engine.POSTGRES,
+ masking: MCPEngineEnforcement_Masking.COLUMN,
+ }),
+ ];
+ expect(groupEnginesByMasking(engines).map((group) => group.value)).toEqual([
+ MCPEngineEnforcement_Masking.COLUMN,
+ MCPEngineEnforcement_Masking.DOCUMENT,
+ MCPEngineEnforcement_Masking.NONE,
+ ]);
+ });
+});
diff --git a/frontend/src/routes/workspace/mcp/mcpPolicy.ts b/frontend/src/routes/workspace/mcp/mcpPolicy.ts
new file mode 100644
index 0000000000..34de95eaa8
--- /dev/null
+++ b/frontend/src/routes/workspace/mcp/mcpPolicy.ts
@@ -0,0 +1,217 @@
+import type { Engine } from "@/types/proto-es/v1/common_pb";
+import type { MCPSetting } from "@/types/proto-es/v1/setting_service_pb";
+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";
+import type {
+ MCPCapabilityMode,
+ MCPEngineEnforcement,
+ MCPInfo,
+ MCPMethod,
+} from "@/types/proto-es/v1/workspace_service_pb";
+import {
+ MCPEngineEnforcement_Masking,
+ MCPEngineEnforcement_ReadOnlyDepth,
+} from "@/types/proto-es/v1/workspace_service_pb";
+
+/** The ceilings an admin picks between, least to most capable. */
+export const MCP_CAPABILITY_CHOICES: readonly MCPSetting_Capability[] = [
+ MCPSetting_Capability.DISABLED,
+ MCPSetting_Capability.READ_ONLY,
+ MCPSetting_Capability.READ_WRITE,
+];
+
+/**
+ * What the stored row says, which is not always a mode.
+ *
+ * `unconfigured` and `unreadable` both arrive as CAPABILITY_UNSPECIFIED and
+ * mean opposite things: the first resolves READ_WRITE server-side, the second
+ * is refused every connection. Collapsing them is the defect BOT-100 records.
+ */
+export type StoredCeiling =
+ | { kind: "mode"; capability: MCPSetting_Capability }
+ | { kind: "unconfigured" }
+ | { kind: "unreadable" }
+ | { kind: "unserved"; stored: string };
+
+const isChoice = (capability: MCPSetting_Capability): boolean =>
+ MCP_CAPABILITY_CHOICES.includes(capability);
+
+/** Reads the stored row into the state the page renders. */
+export const readStoredCeiling = (setting: MCPSetting): StoredCeiling => {
+ // The server does not return the stored token, only that it could not
+ // resolve one. Unserved is different: that value parsed, so the number is
+ // already here and costs nothing to show.
+ if (setting.capabilityUnreadable) {
+ return { kind: "unreadable" };
+ }
+ if (isChoice(setting.capability)) {
+ return { kind: "mode", capability: setting.capability };
+ }
+ if (setting.capability === MCPSetting_Capability.CAPABILITY_UNSPECIFIED) {
+ return { kind: "unconfigured" };
+ }
+ // A number that parsed but no mode serves: the reserved 2, or a ceiling a
+ // newer release wrote. Enforcement refuses it, so it is not a choice either.
+ return { kind: "unserved", stored: String(setting.capability) };
+};
+
+/** A stored row the server refuses, which carries the value nobody could read. */
+export type BrokenCeiling = Extract<
+ StoredCeiling,
+ { kind: "unreadable" } | { kind: "unserved" }
+>;
+
+/** Whether the stored row is one the server can act on. */
+export const ceilingIsBroken = (
+ stored: StoredCeiling
+): stored is BrokenCeiling =>
+ stored.kind === "unreadable" || stored.kind === "unserved";
+
+/**
+ * The card the form starts on, or undefined when the row is broken.
+ *
+ * A broken row starts on no card so that every pick is a change the footer can
+ * save — including the most permissive one. Preselecting the ceiling such a row
+ * resolves to is what left an admin unable to repair it in one save (BOT-100).
+ */
+export const initialCapabilityPick = (
+ stored: StoredCeiling
+): MCPSetting_Capability | undefined => {
+ switch (stored.kind) {
+ case "mode":
+ return stored.capability;
+ case "unconfigured":
+ // No row resolves READ_WRITE server-side, so this is the ceiling in
+ // force, not a guess.
+ return MCPSetting_Capability.READ_WRITE;
+ default:
+ return undefined;
+ }
+};
+
+/**
+ * The methods a mode serves, by the same rule the gate evaluates: a method is
+ * served when its class is one of the mode's served classes.
+ */
+export const methodsServedBy = (
+ mode: MCPCapabilityMode | undefined,
+ methods: MCPMethod[]
+): MCPMethod[] => {
+ if (!mode) {
+ return [];
+ }
+ const served = new Set(mode.servedClasses);
+ return methods.filter((method) => served.has(method.class));
+};
+
+/** The service a method belongs to: `/bytebase.v1.SQLService/Query` -> `SQLService`. */
+export const serviceOfMethod = (method: MCPMethod): string => {
+ const parts = method.method.split("/");
+ const service = parts.length > 1 ? parts[1] : method.method;
+ const short = service.split(".").pop();
+ return short || service;
+};
+
+export interface MethodGroup {
+ service: string;
+ methods: MCPMethod[];
+}
+
+/** Groups served methods by service, both the groups and their rows sorted. */
+export const groupMethodsByService = (methods: MCPMethod[]): MethodGroup[] => {
+ const groups = new Map<string, MCPMethod[]>();
+ for (const method of methods) {
+ const service = serviceOfMethod(method);
+ const existing = groups.get(service);
+ if (existing) {
+ existing.push(method);
+ } else {
+ groups.set(service, [method]);
+ }
+ }
+ return [...groups.entries()]
+ .map(([service, rows]) => ({
+ service,
+ methods: [...rows].sort((a, b) => a.method.localeCompare(b.method)),
+ }))
+ .sort((a, b) => a.service.localeCompare(b.service));
+};
+
+export interface EngineGroup<T> {
+ value: T;
+ engines: Engine[];
+}
+
+const groupEnginesBy = <T>(
+ engines: MCPEngineEnforcement[],
+ order: readonly T[],
+ pick: (engine: MCPEngineEnforcement) => T
+): EngineGroup<T>[] => {
+ const groups = new Map<T, Engine[]>();
+ for (const enforcement of engines) {
+ const value = pick(enforcement);
+ const existing = groups.get(value);
+ if (existing) {
+ existing.push(enforcement.engine);
+ } else {
+ groups.set(value, [enforcement.engine]);
+ }
+ }
+ // Rank rather than filter. The server answers with the depth or masking mode
+ // it computed, which a bundle in an open tab across a backend upgrade may not
+ // have been compiled against; filtering the known order would take that
+ // engine off the page entirely rather than describe it imprecisely. Both
+ // renderers already have a default arm for a value they cannot name.
+ const rank = (value: T): number => {
+ const at = order.indexOf(value);
+ return at === -1 ? order.length : at;
+ };
+ return [...groups.keys()]
+ .sort((a, b) => rank(a) - rank(b))
+ .map((value) => ({ value, engines: groups.get(value) ?? [] }));
+};
+
+/**
+ * Read-only depth groups, deepest first. Grouping rather than listing every
+ * engine is the point: an admin choosing Read-only is asking which engines the
+ * ceiling reaches all the way down, and thirty rows do not answer that.
+ */
+export const READ_ONLY_DEPTH_ORDER = [
+ MCPEngineEnforcement_ReadOnlyDepth.STATEMENT_AND_SESSION,
+ MCPEngineEnforcement_ReadOnlyDepth.STATEMENT,
+ MCPEngineEnforcement_ReadOnlyDepth.UNSUPPORTED,
+ MCPEngineEnforcement_ReadOnlyDepth.READ_ONLY_DEPTH_UNSPECIFIED,
+] as const;
+
+export const groupEnginesByReadOnlyDepth = (
+ engines: MCPEngineEnforcement[]
+): EngineGroup<MCPEngineEnforcement_ReadOnlyDepth>[] =>
+ groupEnginesBy(engines, READ_ONLY_DEPTH_ORDER, (e) => e.readOnlyDepth);
+
+/**
+ * Masking groups. Three states, never two: an engine Bytebase does not mask
+ * and an engine whose masking never consults exemptions are different answers
+ * to "does ignoring exemptions change anything here".
+ */
+export const MASKING_ORDER = [
+ MCPEngineEnforcement_Masking.COLUMN,
+ MCPEngineEnforcement_Masking.DOCUMENT,
+ MCPEngineEnforcement_Masking.NONE,
+ MCPEngineEnforcement_Masking.MASKING_UNSPECIFIED,
+] as const;
+
+export const groupEnginesByMasking = (
+ engines: MCPEngineEnforcement[]
+): EngineGroup<MCPEngineEnforcement_Masking>[] =>
+ groupEnginesBy(engines, MASKING_ORDER, (e) => e.masking);
+
+/** The engines whose per-engine answer carries a note. */
+export const engineNotes = (
+ engines: MCPEngineEnforcement[]
+): MCPEngineEnforcement[] => engines.filter((engine) => engine.note !== "");
+
+/** The mode row for one capability, or undefined when this build serves none. */
+export const modeFor = (
+ info: MCPInfo | undefined,
+ capability: MCPSetting_Capability
+): MCPCapabilityMode | undefined =>
+ info?.modes.find((mode) => mode.capability === capability);
diff --git a/frontend/src/types/proto-es/v1/setting_service_pb.d.ts b/frontend/src/types/proto-es/v1/setting_service_pb.d.ts
index b9e127e931..29c116feab 100644
--- a/frontend/src/types/proto-es/v1/setting_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/setting_service_pb.d.ts
@@ -779,6 +779,36 @@ export declare type MCPSetting = Message<"bytebase.v1.MCPSetting"> & {
* @generated from field: bool ignore_masking_exemptions = 2;
*/
ignoreMaskingExemptions: boolean;
+
+ /**
+ * True when the row carries a capability key that this build cannot resolve
+ * to a ceiling. An enum name a newer release wrote is the legitimate trigger,
+ * during a rolling upgrade; a hand-edited token reaches the same state.
+ * False for every readable row, including one that was never configured.
+ *
+ * The capability field cannot carry this on its own: the unmarshaler discards
+ * an enum name it does not know, so an unreadable row and a never-configured
+ * one both arrive as CAPABILITY_UNSPECIFIED, while MCP is refused for the
+ * first and served at READ_WRITE for the second. A client reading only the
+ * capability shows the most permissive ceiling over a workspace where every
+ * MCP connection is being refused.
+ *
+ * A row protojson cannot parse at all is NOT this state. There is no ceiling
+ * in it to describe, so the read fails instead, and repairing it needs an
+ * operator rather than this field.
+ *
+ * The stored token itself is deliberately not returned. Telling a typo apart
+ * from a value a newer release wrote would only pay off if this enum grew,
+ * and it has not: its one reserved slot held a tier removed before any
+ * release shipped it.
+ *
+ * Set the row right by writing value.mcp.capability. Any other path is
+ * refused while this is true, because the merge that saved it would erase the
+ * value nobody could read.
+ *
+ * @generated from field: bool capability_unreadable = 3;
+ */
+ capabilityUnreadable: boolean;
};
/**
diff --git a/frontend/src/types/proto-es/v1/setting_service_pb.js b/frontend/src/types/proto-es/v1/setting_service_pb.js
index 5395a08713..63eb248fe6 100644
--- a/frontend/src/types/proto-es/v1/setting_service_pb.js
+++ b/frontend/src/types/proto-es/v1/setting_service_pb.js
@@ -18,7 +18,7 @@ import { file_v1_issue_service } from "./issue_service_pb";
* Describes the file v1/setting_service.proto.
*/
export const file_v1_setting_service = /*@__PURE__*/
- fileDesc("Chh2MS9zZXR0aW5nX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIhUKE0xpc3RTZXR0aW5nc1JlcXVlc3QiPgoUTGlzdFNldHRpbmdzUmVz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Z28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_field_mask, file_google_type_color, file_google_type_expr, file_v1_annotation, file_v1_common, file_v1_issue_service]);
+ fileDesc("Chh2MS9zZXR0aW5nX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIhUKE0xpc3RTZXR0aW5nc1JlcXVlc3QiPgoUTGlzdFNldHRpbmdzUmVzcG9uc2USJgoIc2V0dGluZ3MYASADKAsyFC5ieXRlYmFzZS52MS5TZXR0aW5nIj8KEUdldFNldHRpbmdSZXF1ZXN0EioKBG5hbWUYASABKAlCHOBBAvpBFgoUYnl0ZWJhc2UuY29tL1NldHRpbmciOwoSR2V0U2V0dGluZ1Jlc3BvbnNlEiUKB3NldHRpbmcYASABKAsyFC5ieXRlYmFzZS52MS5TZXR0aW5nIqEBChRVcGRhdGVTZXR0aW5nUmVxdWVzdBIqCgdzZXR0aW5nGAEgASgLMhQuYnl0ZWJhc2UudjEuU2V0dGluZ0ID4EECEhUKDXZhbGlkYXRlX29ubHkYAiABKAgSFQoNYWxsb3dfbWlzc2luZxgDIAEoCBIvCgt1cGRhdGVfbWFzaxgEIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE1hc2sivQIKB1NldHRpbmcSEQoEbmFtZRgBIAEoCUID4EEIEi0KBXZhbHVlGAIgASgLMhkuYnl0ZWJhc2UudjEuU2V0dGluZ1ZhbHVlQgPgQQIiwAEKC1NldHRpbmdOYW1lEhwKGFNFVFRJTkdfTkFNRV9VTlNQRUNJRklFRBAAEhUKEVdPUktTUEFDRV9QUk9GSUxFEAESFgoSV09SS1NQQUNFX0FQUFJPVkFMEAISCgoGQVBQX0lNEAMSBgoCQUkQBBIXChNEQVR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luZy5uYW1lPXNldHRpbmdzLyp9ErgBChBUZXN0RW1haWxTZXR0aW5nEiQuYnl0ZWJhc2UudjEuVGVzdEVtYWlsU2V0dGluZ1JlcXVlc3QaJS5ieXRlYmFzZS52MS5UZXN0RW1haWxTZXR0aW5nUmVzcG9uc2UiV4rqMA9iYi5zZXR0aW5ncy5zZXSQ6jABoOowA6jqMAaC0+STAjI6ASoiLS92MS97cGFyZW50PXdvcmtzcGFjZXMvKn0vc2V0dGluZ3MvRU1BSUw6dGVzdEKpAQoPY29tLmJ5dGViYXNlLnYxQhNTZXR0aW5nU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_field_mask, file_google_type_color, file_google_type_expr, file_v1_annotation, file_v1_common, file_v1_issue_service]);
/**
* Describes the message bytebase.v1.ListSettingsRequest.
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index d449bb425f..9e9179bf77 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -26327,6 +26327,35 @@ components:
masking policy, and it does nothing on the engines Bytebase does not mask.
It narrows what an agent reads through the paths Bytebase masks; it is not
a confidentiality boundary.
+ capabilityUnreadable:
+ type: boolean
+ title: capability_unreadable
+ description: |-
+ True when the row carries a capability key that this build cannot resolve
+ to a ceiling. An enum name a newer release wrote is the legitimate trigger,
+ during a rolling upgrade; a hand-edited token reaches the same state.
+ False for every readable row, including one that was never configured.
+
+ The capability field cannot carry this on its own: the unmarshaler discards
+ an enum name it does not know, so an unreadable row and a never-configured
+ one both arrive as CAPABILITY_UNSPECIFIED, while MCP is refused for the
+ first and served at READ_WRITE for the second. A client reading only the
+ capability shows the most permissive ceiling over a workspace where every
+ MCP connection is being refused.
+
+ A row protojson cannot parse at all is NOT this state. There is no ceiling
+ in it to describe, so the read fails instead, and repairing it needs an
+ operator rather than this field.
+
+ The stored token itself is deliberately not returned. Telling a typo apart
+ from a value a newer release wrote would only pay off if this enum grew,
+ and it has not: its one reserved slot held a tier removed before any
+ release shipped it.
+
+ Set the row right by writing value.mcp.capability. Any other path is
+ refused while this is true, because the merge that saved it would erase the
+ value nobody could read.
+ readOnly: true
title: MCPSetting
additionalProperties: false
description: |-
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index fee5acb86a..c4eb25f9d5 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -4974,6 +4974,15 @@ workspace.
| ignore_masking_exemptions | [bool](#bool) | | Whether a request that arrived over MCP stops applying the caller&#39;s own unmasking provisioning. Two mechanisms let a user see a real value and this suppresses both: the masking exemptions granted to them, and the unmask carried by an access grant. The same user in the console is untouched.
It cannot force masking where there is none. Masking substitutes values in query results, so this does not reach data copied into a column carrying no masking policy, and it does nothing on the engines Bytebase does not mask. It narrows what an agent reads through the paths Bytebase masks; it is not a confidentiality boundary. |
+| capability_unreadable | [bool](#bool) | | True when the row carries a capability key that this build cannot resolve to a ceiling. An enum name a newer release wrote is the legitimate trigger, during a rolling upgrade; a hand-edited token reaches the same state. False for every readable row, including one that was never configured.
+
+The capability field cannot carry this on its own: the unmarshaler discards an enum name it does not know, so an unreadable row and a never-configured one both arrive as CAPABILITY_UNSPECIFIED, while MCP is refused for the first and served at READ_WRITE for the second. A client reading only the capability shows the most permissive ceiling over a workspace where every MCP connection is being refused.
+
+A row protojson cannot parse at all is NOT this state. There is no ceiling in it to describe, so the read fails instead, and repairing it needs an operator rather than this field.
+
+The stored token itself is deliberately not returned. Telling a typo apart from a value a newer release wrote would only pay off if this enum grew, and it has not: its one reserved slot held a tier removed before any release shipped it.
+
+Set the row right by writing value.mcp.capability. Any other path is refused while this is true, because the merge that saved it would erase the value nobody could read. |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 8182e0021a..998d1cf22f 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -14318,6 +14318,36 @@ It narrows what an agent reads through the paths Bytebase masks; it is not
a confidentiality boundary. </p></td>
</tr>
+ <tr>
+ <td>capability_unreadable</td>
+ <td><a href="#bool">bool</a></td>
+ <td></td>
+ <td><p>True when the row carries a capability key that this build cannot resolve
+to a ceiling. An enum name a newer release wrote is the legitimate trigger,
+during a rolling upgrade; a hand-edited token reaches the same state.
+False for every readable row, including one that was never configured.
+
+The capability field cannot carry this on its own: the unmarshaler discards
+an enum name it does not know, so an unreadable row and a never-configured
+one both arrive as CAPABILITY_UNSPECIFIED, while MCP is refused for the
+first and served at READ_WRITE for the second. A client reading only the
+capability shows the most permissive ceiling over a workspace where every
+MCP connection is being refused.
+
+A row protojson cannot parse at all is NOT this state. There is no ceiling
+in it to describe, so the read fails instead, and repairing it needs an
+operator rather than this field.
+
+The stored token itself is deliberately not returned. Telling a typo apart
+from a value a newer release wrote would only pay off if this enum grew,
+and it has not: its one reserved slot held a tier removed before any
+release shipped it.
+
+Set the row right by writing value.mcp.capability. Any other path is
+refused while this is true, because the merge that saved it would erase the
+value nobody could read. </p></td>
+ </tr>
+
</tbody>
</table>
diff --git a/proto/v1/v1/setting_service.proto b/proto/v1/v1/setting_service.proto
index ff93ba4379..9ff4376c11 100644
--- a/proto/v1/v1/setting_service.proto
+++ b/proto/v1/v1/setting_service.proto
@@ -358,6 +358,32 @@ message MCPSetting {
// It narrows what an agent reads through the paths Bytebase masks; it is not
// a confidentiality boundary.
bool ignore_masking_exemptions = 2;
+
+ // True when the row carries a capability key that this build cannot resolve
+ // to a ceiling. An enum name a newer release wrote is the legitimate trigger,
+ // during a rolling upgrade; a hand-edited token reaches the same state.
+ // False for every readable row, including one that was never configured.
+ //
+ // The capability field cannot carry this on its own: the unmarshaler discards
+ // an enum name it does not know, so an unreadable row and a never-configured
+ // one both arrive as CAPABILITY_UNSPECIFIED, while MCP is refused for the
+ // first and served at READ_WRITE for the second. A client reading only the
+ // capability shows the most permissive ceiling over a workspace where every
+ // MCP connection is being refused.
+ //
+ // A row protojson cannot parse at all is NOT this state. There is no ceiling
+ // in it to describe, so the read fails instead, and repairing it needs an
+ // operator rather than this field.
+ //
+ // The stored token itself is deliberately not returned. Telling a typo apart
+ // from a value a newer release wrote would only pay off if this enum grew,
+ // and it has not: its one reserved slot held a tier removed before any
+ // release shipped it.
+ //
+ // Set the row right by writing value.mcp.capability. Any other path is
+ // refused while this is true, because the merge that saved it would erase the
+ // value nobody could read.
+ bool capability_unreadable = 3 [(google.api.field_behavior) = OUTPUT_ONLY];
}
message SQLEditorThemeSetting {