Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(mcp): show what an access policy mode allows
zchpeter54597dd9a4e9
diff --git a/AGENTS.md b/AGENTS.mdindex 1d9b367f66..1532f1cbdc 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -23,6 +23,7 @@ Bytebase is the standard for database development. Every product and engineering- Metadata JSONB uses `protojson.Marshal`: keys are camelCase (`taskRun`), not proto snake_case (`task_run`).- Follow Google language style guides and AIPs for API/proto design. AIPs take precedence over the proto guide. Enum values use `HELLO`, not `TYPE_HELLO`.- Use American English. Avoid collection names ending in `List`.+- Annotating an RPC `mcp_method_class = READ` or `WRITE` also changes what the MCP Access policy page promises, and nothing enforces that. Before changing one, read [mcp-capability-ladder.md](docs/design/mcp-capability-ladder.md#keeping-the-rows-true).## Code commentsdiff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 34576b4537..67641af183 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -16793,6 +16793,9 @@ components:between, EXCLUDED and FORBIDDEN are served by no ceiling, and an unclassifiedmethod is refused rather than served. Annotating a method is therefore achange to what an MCP session can reach, taking effect on the next request.+ READ and WRITE methods are also disclosed to workspace admins, as capability+ rows on the Access policy page, so annotating a method changes what the+ product promises as well as what it serves.bytebase.v1.MCPSetting:type: objectproperties:diff --git a/backend/generated-go/v1/annotation.pb.go b/backend/generated-go/v1/annotation.pb.goindex d5ca7d103f..8f273b35c3 100644--- a/backend/generated-go/v1/annotation.pb.go+++ b/backend/generated-go/v1/annotation.pb.go@@ -142,6 +142,9 @@ func (AuthMethod) EnumDescriptor() ([]byte, []int) {// between, EXCLUDED and FORBIDDEN are served by no ceiling, and an unclassified// method is refused rather than served. Annotating a method is therefore a// change to what an MCP session can reach, taking effect on the next request.+// READ and WRITE methods are also disclosed to workspace admins, as capability+// rows on the Access policy page, so annotating a method changes what the+// product promises as well as what it serves.type MCPMethodClass int32const (diff --git a/docs/design/mcp-capability-ladder.md b/docs/design/mcp-capability-ladder.mdindex 4660a4c4db..9e72daaf89 100644--- a/docs/design/mcp-capability-ladder.md+++ b/docs/design/mcp-capability-ladder.md@@ -1,6 +1,6 @@# MCP access policy — show what a mode allows-Status: proposal · 2026-09-10+Status: accepted · 2026-09-10The MCP settings page offers three modes (Disabled, Read-only, Read-write) and describes each inone sentence. Since [#21324](https://github.com/bytebase/bytebase/pull/21324) removed the per-mode@@ -10,10 +10,11 @@ Read-only and Read-write has nothing to compare beyond two sentences. The rule twhich each mode is a prefix, collapsed by default inside the existing Access policy section, andfollowing the picked mode while editing.** The page also gets shorter: the mode cards shrink to anicon, a label and a three-word caption, with the selected mode's "Best for" under them; the-disclosure line is the mode's description, and row details sit behind one toggle. The product-change is frontend-only. One backend lint binds the row wording to the method classification, so-the list cannot drift from what the gate serves. A custom access policy is out of scope, but the-list is shaped so that it becomes that editor later without a redesign.+disclosure line is the mode's description, and row details sit behind one toggle. The product change+is frontend-only, with one comment added to the `mcp_method_class` annotation and its generated+output; keeping the row wording true to the method classification is a rule in `AGENTS.md`+rather than a lint (D11). A custom access policy is out of scope, but the list is shaped so that it+becomes that editor later without a redesign.## Problem@@ -42,8 +43,7 @@ detail line was visible whether or not anyone wanted it.## Principle-> **A capability is a verb phrase an admin recognizes, backed by an exact set of served methods in-> code. The three modes are nested, so one ordered list with two dividers shows all three at once,+> **A capability is a verb phrase an admin recognizes, standing for an exact set of served methods. The three modes are nested, so one ordered list with two dividers shows all three at once,> and the mode in force — or the mode being picked — is a highlighted prefix of that list.**What follows from it:@@ -59,23 +59,110 @@ What follows from it:## The rows-Eight rows: three read, five write. Each has a title, a one-line list of sub-items in plain words,-and — in code only — the set of served methods it stands for. The right column here is the code-mapping; it never appears in the product.+Eight rows: three read, five write. Each has a title and a one-line list of sub-items in plain+words. The right column records which classified methods the row's wording has to cover; it is+documentation for whoever rereads these rows after a classification change, and never appears in+the product.-| Tier | Row | Sub-items shown | Backed by (code only) |+| Tier | Row | Sub-items shown | Classified methods the wording must cover ||---|---|---|---|| read | Read schemas and metadata | Schemas · Databases and instances · Projects and database groups · Catalogs, changelogs and revisions · SQL review configs · Your own session and workspace facts | 31 READ methods: `DatabaseService` reads, projects, instances, database groups, catalogs, changelogs, revisions, review configs, session facts |-| read | Read data by running queries | Run read-only queries; a request is refused whole if any statement is not a read, and on engines other than PostgreSQL, CockroachDB and Redshift the check is by statement shape only · Query history · Saved queries and sheets | 9 READ methods: `SQLService/Query`, query history (4), saved-query reads (3), `GetSheet` |+| read | Read data by running queries | Run read-only queries · Under Read-only, a request is refused whole unless every statement is shown to be a read that returns data; how deeply that can be checked varies by engine, and on some engines no statement can be shown to be a read at all · Your own query history · Saved queries and sheets you have access to | 9 READ methods: `SQLService/Query`, query history (4), saved-query reads (3), `GetSheet` || read | Read the change workflow | Issues and comments · Plans and plan checks · Rollouts, task runs and logs · Releases · Rollback previews | 16 READ methods: issue, plan, rollout and release reads || — | *Read-only stops here* | | 56 methods |-| write | Propose changes | Create sheets · Create and edit plans and issues · Run plan checks and reviews · Create and delete releases and revisions · Generate schema diffs. An agent never approves its own change; the project's approval policy decides whether a human must | 22 WRITE methods: sheet, plan, issue, release and revision writes, `RequestIssue`, `RunReview`, `DiffSchema`, `DiffMetadata` |+| write | Propose changes | Create sheets · Create and edit plans and issues · Run plan checks and reviews · Create, delete and restore releases · Create and delete revisions · Generate schema diffs. An agent never approves its own change; the project's approval policy decides whether a human must | 22 WRITE methods: sheet, plan, issue, release and revision writes, `RequestIssue`, `RunReview`, `DiffSchema`, `DiffMetadata` || write | Run rollouts and tasks | Create a rollout · Run, skip or cancel its tasks, under the project's approval policy | 4 WRITE methods: `CreateRollout`, `BatchRunTasks`, `BatchSkipTasks`, `BatchCancelTaskRuns` |-| write | Run DML and DDL statements | INSERT, UPDATE, DELETE, CREATE, ALTER, DROP through queries, where the engine checks each statement and the user may run it | Not a method: the statement clamp in `mcp_sql_clamp.go`, which Read-write lifts |+| write | Run DML and DDL statements | INSERT, UPDATE, DELETE, CREATE, ALTER, DROP through queries, as far as the engine and the user's own permissions allow | Not a method: the statement clamp in `mcp_sql_clamp.go`, which Read-write lifts || write | Export query results | Download results as a file. Data leaves Bytebase | 1 WRITE method: `SQLService/Export` || write | Manage database housekeeping | Sync instances and databases · Database settings and labels · Move databases between projects · Database groups · Saved queries | 14 WRITE methods: sync, `UpdateDatabase`, database groups, saved-query writes || — | *Read-write stops here* | | 97 methods |-| floor | Never, in any mode: approve issues, administer the workspace, or handle credentials. | | 121 methods: 35 FORBIDDEN, 86 EXCLUDED |+| floor | Never, in any mode: approve issues, administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history. | | 121 methods: 35 FORBIDDEN, 86 EXCLUDED |++Every row is displayed under every mode — served, or muted with a `—` — and against every engine a+workspace happens to hold, so **every line on this card must be true on both axes: mode and engine.**+That covers the eight rows, and equally the collapsed summary, the card captions and the "Best for"+lines, which are not rows and were missed the first time the rule was applied. The summary is the+line most admins read and often the only one. A+claim whose truth depends on the mode names the mode as a condition; a claim whose truth depends on+the engine says so without naming engines, because per-engine depth is out of scope for this card+(see below) and an enumeration goes stale the release a driver changes.++Both axes have caught lines here, and the engine axis caught the same line twice. On the mode axis,+the read-only clamp holds only under Read-only (`mcpReadOnlyClampApplies`), so without its qualifier+row 2 promised a whole-request refusal under Read-write while row 6 on the same screen offered INSERT+and DROP.++On the engine axis, three drafts failed in three different ways, and the shape of the failure is the+lesson. Naming engines (PostgreSQL, CockroachDB, Redshift) went stale against the Redshift datashare+carve-out and was outright false where an engine has no query validator: `refuseNonReadOnlyStatement`+bails before classification and refuses *every* statement, so Read-only serves no query there rather+than a shallowly-checked one. Replacing that with a universal — "queries stay read-only where+Bytebase does not gate per statement" — was false in the permissive direction, because the real+predicate is a conjunction (`HasQueryValidator && !EngineSupportQueryNewACL`) that the sentence+collapsed: on Databricks, outside the ACL set and with no validator, `ValidateSQLForEditor` returns+its permissive default and the write executes. `mcp_sql_clamp.go` carries a comment warning against+exactly that call, eight lines from where the clamp reads it.++So: **state the bound, never the behavior.** Where a claim's truth varies along an axis the card+cannot enumerate, say what limits it — "as far as the engine and the user's own permissions allow",+"how deeply that can be checked varies by engine" — and let the reader learn the specifics from the+docs. An enumeration is wrong the release a driver changes; a universal is wrong the release an+engine is added.++Two further axes were found in review, each after it had already shipped a false line.++**Effect.** A refusal is a claim about what a session can cause, not about which methods it can+call, and the two come apart wherever a permitted method has an effect no annotation names.+`CreateIssue` is an ordinary WRITE; `startIssueWorkflow` calls `emitIssueCreated`, and the webhook+manager posts the issue title and description to whatever endpoint the project configured+(`backend/component/webhook/manager.go`). A Read-write session can put anything it has read into a+description, so the floor's "never … send data to a third party" was false while every method it+reasoned about was classified correctly. Reasoning from the annotation set cannot find this; only+following the effect can. **Check a claim about effects against effects, including the ones no+annotation names.**++The same axis caught a second verb in the same sentence one round later, and the tell was+vocabulary. "Never … open an admin connection" reads as a denial-reason+(`OPENS_AN_ADMIN_CONNECTION`, carried only by `AdminExecute` and `GetTaskRunSession`) and is false as+plumbing: `resolveDataSourceID` falls through to the ADMIN data source for any instance with no+read-only one, in either mode, and `sql_service.go` opens it with+`ReadOnly: clamped || type == READ_ONLY` — so under Read-write an ordinary MCP query runs on the+admin data source, not read-only. **A verb that names a mechanism is a claim about the plumbing and+has to be checked against the plumbing; name the feature the reader knows instead** — here Admin+mode, which really is refused.++**Complement.** A conditional line also asserts something about its complement, and a reader takes+the reassuring half. "Where Bytebase cannot check a statement, it is not verified before it runs" is+true as written and implies that where Bytebase can check, it does — but Read-write leaves+`mcpReadOnlyClampApplies` false and skips `validateQueryRequest` for every engine in+`EngineSupportQueryNewACL`, so on PostgreSQL, the engine with the most complete parser, nothing+checks the statement at all. The conditional pointed its reassurance exactly where the product is+weakest. **If negating the condition yields a promise the product does not keep, drop the condition+or state the bound unconditionally.**++Dropping it unconditionally was the next round's defect, and the two rounds after that are the more+useful half of this entry. "This mode does not require a statement to be a read" is what the MCP+ceiling does — the clamp is off — but not what the product does: `Query` runs `validateQueryRequest`+under every mode for engines outside `EngineSupportQueryNewACL`, and 13 of those 14 have a+registered validator, so a Read-write session there is still refused a write. The repair for the+complement axis had removed the engine axis from the one line that carried it, on a screen that+renders no row details. **A line being fixed on one axis is still a line, and has to be rechecked+against every axis — the one being repaired crowds out the rest.**++**Method.** The replacement kept the engine axis and named a consequence — lifted where Bytebase can+check, refused where it cannot — and that is still one variable too few. `Query` and `Export` do not+share a gate: `Query` skips the check for the ten `EngineSupportQueryNewACL` engines, while `Export`+skips it only for MySQL. So on PostgreSQL under Read-write the same write runs through `Query` and is+refused through `Export`, and Export is a served row on the same card. The fourteenth engine breaks+it the other way: Databricks is outside the ACL set *and* registers no validator, so+`ValidateSQLForEditor` returns its permissive default, `GetQuerySpan` returns no spans, and the+access check falls back to `bb.sql.select` — a `DELETE` that runs unrefused, unclassified, and+authorized by a read permission. **The same statement, mode and engine can get different answers from+different RPCs; a claim about what runs has to name the operation as well as the engine.**++Four wordings later, the line states the bound and stops: "Capped by your own Bytebase permissions, and by what Bytebase supports for each database engine and each operation".+Its Read-only sibling keeps a consequence because there the clamp really is one rule with one+outcome. Parallelism between the two is broken on purpose.Two choices in the wording are deliberate. Row 2 says *Read data by running queries* rather than"Run queries" so the verb stays Read and the sub-item carries the rule that keeps it true under@@ -145,8 +232,9 @@ name, which the chip (view) or theselector (edit) already shows. Expanded, it becomes the list heading "Read-write allows", with a"Show details" control on the right. In view state it sits under the chip line; in edit state itsits under the selector and its "Best for" line, above the masking toggle, so the cause and its-effect are adjacent. The open state persists per browser and carries across the view-to-edit-transition within a page visit.+effect are adjacent. The open state carries across the view-to-edit transition within a page+visit, and starts collapsed on the next one. Remembering it per browser was cut in review as more+machinery than a settings page visited this rarely earns.**D2 — Content: rows first, sub-items behind one toggle.** Expanded, each row shows its title andits tier tag, nothing else. "Show details" reveals the sub-item line for every row at once, so@@ -169,17 +257,19 @@ The separate sentence under the chip is retired for Read-only and Read-write, siline says the same thing; Disabled keeps its sentence, "No MCP session can connect to thisworkspace.", because it has no list. "Active" was considered and rejected as the label: "Active ·Disabled" contradicts itself, and a chip under a section titled Access policy needs no label. The-chip carries `aria-label="Current policy: Read-only"`.+chip announces "Current policy: Read-only" through visually hidden text, never through+`aria-label`: a chip is a bare `span`, whose implicit `generic` role ARIA forbids naming, so a+label put there is dropped and the deleted "In force" text is replaced by nothing. Tests assert+the rendered name rather than the attribute, which satisfies a DOM query while naming nothing.**D4 — The two notes under the card move and shrink.** "A ceiling change applies to the nextrequest…" shows only while editing, as "Applies to every running session's next request.", andnames the change when the form is dirty: "Read-only → Read-write applies to every runningsession's next request." "MCP policy denials are recorded in the audit log" is a fact about the-feature, not about the current state, so it joins the section description, which becomes: "The-most any MCP session may do here. Sessions are also capped by each user's permissions, and policy-refusals are audited." Since [audit-what-produces-a-row.md](audit-what-produces-a-row.md), a-refusal is streamed to stdout when audit logging to stdout is enabled, so the shipped sentence-says "streamed to stdout" rather than "recorded in the audit log".+feature, not about the current state, so it joins the section description. Per+[audit-what-produces-a-row.md](audit-what-produces-a-row.md) a refusal reaches stdout only when+audit logging to stdout is enabled, so the description carries that condition rather than an+unqualified "audited": "The most any MCP session may do here. Sessions are also capped by each user's permissions, and policy refusals are streamed to stdout when audit logging to stdout is enabled."**D5 — Edit state: icon cards, the selected mode's "Best for", and the pick's ladder.** Thethree mode cards lose their descriptions; they duplicated the ladder. What remains is the shape of@@ -210,6 +300,59 @@ disclosure slot holds a static line in the floor's soft error tone, "Nothing issession can connect.", so red means "no capability" everywhere on the card. It is not a button anddoes not repeat the mode name.+The rule extends past color: **a control that governs only a serving session is withheld while+Disabled is picked, and the save leaves its stored value alone.** The masking toggle is the one+such control today. `mcpIgnoresMaskingExemptions` (`backend/api/v1/mcp_masking.go`) answers on the+delegated grant an MCP request carries, and Disabled admits no MCP session, so the stored flag is+never read there — a live toggle under a red line saying no session can connect would be the card+asserting two things that cannot both hold. Withholding the control is not a reason to discard what the admin set with it, and two attempts to+make it one both lost an explicit choice. Gating the write dropped the edit on a save under Disabled;+resetting the draft on the pick dropped it earlier and even when the admin returned to a serving+mode. The draft is therefore kept and saved whatever the pick: clicking through the modes to read+their descriptions must not silently undo an unrelated edit, and under Disabled the stored flag is+inert rather than wrong, so writing it costs nothing now and honors the choice when MCP is turned+back on.++The "Masking exemptions ignored" chip belongs to the **view**. It reports the stored flag in the+present tense and says which of three things that flag is doing: in effect, stored but unlicensed,+or stored with MCP off. Withholding it was tried and is wrong in both inert cases — the flag is+storable under Disabled, which preserving the draft makes reachable by design, and hiding it leaves+a set flag with nowhere to see it. The reasons it might be inert live in the editor and in the+Disabled sentence, and the editor is a different branch behind `bb.settings.set`, so a reader of+this page may never reach them; the chip therefore carries the reason itself. Its inventory is+therefore Disabled, then licensed or not — three arms, because a Disabled policy is reported as off+whether or not the workspace holds a masking license. It renders only where a stored mode exists to+qualify it, and takes that mode as an argument so the branch that proved there is one passes the+proof in. A predicate would not: `!isServingMode(storedMode)` also catches the ceiling this build+cannot parse, and would label a policy nobody turned off as "MCP is off". That ceiling gets no chip+at all, which is the one place this decision accepts a set flag with nowhere to see it: the repair+card carries a single instruction — pick a mode — and a second chip beside it competes with the only+action that resolves the state.++The editor does not render it, and an attempt to do so failed three ways at once. A present-tense+chip under a pick that admits no session states a live restriction directly beneath the red line+saying nothing can connect — the contradiction this decision withholds the toggle to prevent,+restated as a chip. Its text came from the stored pair while Save writes the draft, so it could+assert the opposite of what Save was about to do, in both directions. And gating it on the stored+flag left the "turned it on, then picked Disabled" case showing nothing at all — the very gap it was+added to close. **A surface discloses the state it owns: the view reports what is stored, the editor+reports what Save will write.** Under a pick that withholds the toggle the editor says so in the+footer, in the future tense, naming the direction — and whenever the saved flag will be set, not+only when this edit changed it, because an admin who cannot see the control cannot see the value+either.++Two bounds on that line, both found by making it say too much. It is gated on the form being+saveable: an editor opened and not touched has no save to describe, and under no pick at all the card+would otherwise say "pick a mode to save this policy" and "this policy will be saved" at once. And it+says only what will be written, never when that takes effect — "takes effect when MCP is enabled" is+false on a workspace with no masking license, and the caveat that would fix it lives in the toggle+this pick withholds. **State what is written, never when it takes effect**: the write is a fact this+card owns, the effect depends on axes it cannot see.++The consent page still withholds its masking line without a license, because its reader sees neither+the setting nor any caveat and would read the line as "my data is covered".+(Mock E draws the toggle under Disabled; the implementation does not.)+**D8 — Copy that shrinks, but keeps the coverage limit.** The masking toggle's two paragraphsbecome: "If enabled, masked data stays masked in MCP sessions even for users with exemptions orunmask grants. Coverage depends on the engine: where Bytebase does not mask, this changes nothing.@@ -227,41 +370,71 @@ exist on the page: "approve access in the browser" in the Connect a client descrwas useful: "Add Bytebase to your AI client and start asking. On first connection you sign in andapprove access in the browser."-**D10 — The consent page uses the row titles.** "This session may" lists the served rows with ✓,-one ✕ line for the unserved tier under Read-only ("No changes, rollouts or exports"), then the+**D10 — The consent page uses the row titles, and bounds them once.** "This session may" lists the served rows with ✓,+one ✕ line for the unserved tier under Read-only ( + NO_WRITE + ), then theexisting capped, masking and audit lines. Read-write keeps its caution. Its mode chip carries thesame icon as the settings page's. One wording table serves both surfaces.-**D11 — A backend lint binds the wording to the classification.** A table in-`backend/api/v1/mcp_gate.go` assigns every served method to exactly one row, and a lint in-`mcp_gate_test.go` holds it: every READ or WRITE method is in a row, no FORBIDDEN or EXCLUDED-method is, the read rows are exactly the READ set and the write rows exactly the WRITE set. A-class change that moves a method across tiers then fails CI until the table — and therefore the row-wording — is reviewed. No proto change, no new API, no generated file for the frontend: the product-shows no counts, so the frontend needs only the static tier of each row.+Titles alone carry no caveats, and the caveats live in the row details this screen does not render —+so on a workspace whose engine refuses every statement, an unqualified "Read data by running queries+✓" promises a capability the session does not have. The screen cannot carry eight detail lines and+stay an approval screen, so it bounds the whole list once instead, on the line that already limits it+by the reader's own permissions. That bound is per mode, because the statement clamp it describes+runs only under Read-only: "Capped by your own Bytebase permissions, and by what Bytebase can check on each database engine — where it cannot show a statement is a read, no query runs at all" against+"Capped by your own Bytebase permissions, and by what Bytebase supports for each database engine and each operation". The Read-only line names a+consequence because the clamp is one rule with one outcome. The Read-write line does not: what runs+there varies by engine *and* by operation, and every consequence clause written for it has been false+once (see the complement and method axes in The rows). It states the bound and stops. One line either way, and the ✓ marks+read as what the policy admits rather than what will succeed. It carries a neutral glyph and no+"Allowed" mark, so a bound is not counted as a further grant.++**D11 — The wording is bound to the classification by instruction, not by a lint.** The eight+titles claim to cover every READ and WRITE method, and a method annotated into either class is+served the moment it is annotated, whether or not a row names it. The first draft closed that with+a row table in `backend/api/v1/mcp_gate.go` and a lint in `mcp_gate_test.go`, so a class change+failed CI until the table — and therefore the row wording — was reviewed. That was dropped: it+bought a mechanical check at the cost of a second table to keep in step, on a set that changes+rarely and only in commits already about MCP classification. A later review pointed out that a+cheaper check exists and needs no second table: `TestMCPClassificationInventory` already renders the+annotations into `backend/api/v1/testdata/mcp_method_classification.md`, whose header carries the+same per-class counts this row table sums to, so asserting those integers would fail on exactly the+change that requires the reread. That is a real option and it is not the one taken; what it buys is+a prompt to reread, not proof that the wording is right, and the decision here is to spend the+reread on the instruction rather than on a gate. The cost of the trade is unchanged and stated+below. The rule instead lives under Metadata+and API conventions in the root `AGENTS.md`: annotating an RPC READ or WRITE means rereading the+rows and rewording one, or adding one, when none describes it. The cost of the trade is that a+reclassification which skips that reread is silent — the page keeps its old sentences and an admin+picks a ceiling on them. No new API and no field the frontend reads: the product shows no counts, so+it needs only the static tier of each row. The one code change is a comment on `MCPMethodClass` in+`proto/v1/v1/annotation.proto`, stating that the class is disclosed to admins as capability rows —+put where the annotation is typed, since that is where the reread has to happen. It is worded as a+fact rather than a chore, and names no repo path, because proto comments ship into the published API+reference.## States| State | What the section shows ||---|---|-| View · Read-only or Read-write | Chip line with Edit policy; the disclosure line as the description, collapsed. Nothing below it. |-| View · Disabled | Chip line; "No MCP session can connect to this workspace." No disclosure. |+| View · Read-only or Read-write | Chip line with Edit policy, plus the masking chip when the flag is stored (D7); the disclosure line as the description, collapsed on every visit (D1). |+| View · Disabled | Chip line, with the masking chip naming MCP as off when the flag is stored (D7); "No MCP session can connect to this workspace." No disclosure. || View · unreadable, unserved, read failed | The existing warning or error, unchanged. No disclosure. |-| Edit · Read-only or Read-write picked | Icon cards with the pick selected; the pick's "Best for" line; the disclosure for the pick, collapsed by default, rendering the post-save view, with "Show details" once expanded; masking toggle; separator; footer sentence (naming the change when dirty), Cancel, Save (enabled only when dirty). |-| Edit · Disabled picked | Icon cards with Disabled selected; its "Best for" line; the static soft-error line in the disclosure slot. |+| Edit · Read-only or Read-write picked | Icon cards with the pick selected; the pick's "Best for" line; the disclosure for the pick, collapsed by default, rendering the post-save view, with "Show details" once expanded; masking toggle; separator; footer sentence (naming the change when dirty), Cancel, Save (enabled only when dirty). No masking chip: in edit the toggle is the flag's disclosure (D7). |+| Edit · Disabled picked | Icon cards with Disabled selected; its "Best for" line; the static soft-error line in the disclosure slot; NO masking toggle and NO masking chip (D7); separator; footer — the mode sentence, plus, once the form is saveable and the flag is set on either side of the edit, the line naming what Save writes for it — Cancel, Save. |+| Edit · nothing picked | Only reachable from an unreadable or unserved ceiling: icon cards with no selection; "Pick a mode to save this policy." in the disclosure slot; no masking toggle, no masking chip, and no pending line, because nothing can be saved yet; Cancel, Save disabled. || Consent page | Served row titles with ✓, the ✕ line under Read-only, then the existing constants and caution. |## Copy-All strings, so the change and the locale files have one source. Keys under+The strings as decided, with the reasoning that picked them. The locale files are what ships and+what to edit; this section is the record of why, and a copy edit is expected to update both. Keys+under`settings.mcp.ladder.*` are new; the rest replace existing `settings.mcp.*` and`oauth2.consent.mcp.*` values.-- Section description: "The most any MCP session may do here. Sessions are also capped by each- user's permissions, and policy refusals are audited."-- Disclosure line, collapsed — Read-only: "Read schemas, data and the change workflow; statements- that write are refused, nothing is exported". Read-write: "Read schemas, data and the change- workflow; propose, run, export and manage".+- Section description: "The most any MCP session may do here. Sessions are also capped by each user's permissions, and policy refusals are streamed to stdout when audit logging to stdout is enabled."+- Disclosure line, collapsed — Read-only: "Read schemas, data and the change workflow; a request carrying anything that cannot be shown to be a read is refused, and nothing is exported".+ Read-write: "Read schemas, data and the change workflow; propose, run, export and manage".Expanded heading: "{mode} allows". Details control: "Show details" / "Hide details".- Disabled — view sentence: "No MCP session can connect to this workspace." Edit static line:"Nothing is allowed; no MCP session can connect."@@ -272,20 +445,41 @@ All strings, so the change and the locale files have one source. Keys under"making database changes through an AI agent, still capped by each user's own permissions".- Row titles and sub-items: the table above, verbatim.- Dividers: "Read-only stops here", "Read-write stops here".-- Floor: "Never, in any mode: approve issues, administer the workspace, or handle credentials."+- Floor: "Never, in any mode: approve issues, administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history."+ The verbs cover every denial reason, and claim only what is refused **whatever the caller's+ permissions** and by **whatever effect** a served method has. That second rule cost three drafts. MCP's ceiling removes methods by class; it+ never adds per-row privacy, so an ownership claim — "never read other people's SQL", then+ "never browse everyone's saved SQL" — is false at whatever permission level makes it true in the+ console: `GetSavedQuery` reaches SQL shared by a binding, and `searchScope` drops all scoping for+ a caller holding project-wide `bb.savedQueries.get`. Query history is the one that qualifies,+ because `SearchQueryHistories` pins the creator and nothing widens it. A fourth draft added "or+ send data to a third party" and was false on the effect axis: `CreateIssue` is served under+ Read-write and its webhook posts the title and description outward. It is not replaced by a row+ caveat — the webhook fires identically for an issue a human files in the console, so it is a+ property of the workspace's notification config rather than of this ceiling, and the "Propose+ changes" row already says the session can file issues. The fifth draft read "open an admin+ connection" and was false on the same axis for the opposite reason — it named the plumbing rather+ than the feature, and MCP does reach the admin data source. It names Admin mode now.- Tier badges: "read", "write".- Masking toggle: the three sentences in D8, including the engine-coverage limit.+- Masking chip, by what the stored flag is doing: "Masking exemptions ignored",+ "Masking exemptions ignored — masking not licensed",+ "Masking exemptions ignored — MCP is off".+- Footer, once the form is saveable under a pick that withholds the toggle and the flag is set+ before or after the edit, naming what Save writes and not when it takes effect:+ "This policy will be saved with masking exemptions ignored."+ and "This policy will be saved with masking exemptions applied.".- Footer, clean: "Applies to every running session's next request." Dirty: "{from} → {to} appliesto every running session's next request."- Connect a client: the sentence in D9.-- Consent: row titles; "No changes, rollouts or exports".+- Consent: row titles; "No changes, rollouts, exports or database management"; the two capped lines above.## Implementation### Frontend- New `MCPCapabilityLadder` beside `MCPAccessPolicySection.tsx`, props `mode`, `expanded`,- `details`, `onToggle`, `onToggleDetails`. It derives the served set from the mode by tier:+ `details`, `onExpandedChange`, `onDetailsChange`. It derives the served set from the mode by tier:READ_ONLY serves the read rows, READ_WRITE both tiers, DISABLED none. No comparison logic.- Disclosure behavior belongs in a shared primitive per the UX contract. There is no`Collapsible` in `frontend/src/components/ui/` today; add one wrapping Base UI's Collapsible@@ -305,19 +499,25 @@ All strings, so the change and the locale files have one source. Keys underDisabled static line use the `error` semantic tokens at low opacity; no raw palette colors, no`dark:` variants.- `MCPAccessPolicySection.tsx`: remove the `Rows3` icon, the in-force string, the mode cards and- the mode sentence; render the chip with its aria-label and the mode's Lucide icon as its first- child at `size-3.5`; strip the mode cards to icon, label and caption and add the "Best for" line+ the mode sentence; render the chip through the shared `MCPModeBadge`, which the consent page+ also uses, so one component carries the glyph and the accessible name for both surfaces;+ strip the mode cards to icon, label and caption and add the "Best for" lineunder them;move the audit sentence to the section description; show the footer sentence only while editingand interpolate both modes when dirty; replace the masking copy.- `MCPPage.tsx`: remove the Authentication Required alert; extend the Connect a client description.- `MCPConsentCeiling.tsx`: replace the read, write and workflow lines with the row titles from thesame table.-- Locale: keys under `settings.mcp.ladder.*` in all five locale files;- `frontend/scripts/check-i18n.mjs` guards them. The retired mode-description keys are- removed, not left empty.-- Tests: the served set per mode; the disclosure collapsed by default, opens, persists, and follows- the pick; the details toggle reveals sub-items on every row and persists with the open state; the+- Locale: keys under `settings.mcp.ladder.*` in all five locale files. The retired mode-description+ keys are removed, not left empty. `frontend/scripts/check-i18n.mjs` enforces cross-locale+ parity over all of them; the four template-keyed families (`ladder.row.`, `.stops.`, `.summary.`,+ `.tier.`) are registered in its `DYNAMIC_PREFIXES`, which exempts them from both the missing-key+ and unused-key checks, as it does for every other template-keyed family in the product. A row id+ with no copy renders its raw key on the page, and the e2e spec, which reads every row's title from+ `en-US.json`, fails to load; an orphaned line after a rename is dead weight in the locale files. Both need a row renamed, which is rare, so neither+ earns a check of its own.+- Tests: the served set per mode; the disclosure collapsed by default, opens, follows the pick, and+ starts over on the next visit; the details toggle reveals sub-items on every row; the"Best for" line follows the selection; Disabled renders the static line in edit and the sentence inview; the consent page renders the row titles; one e2e case that edits Read-only to Read-write,saves, and sees the chip change.@@ -326,13 +526,36 @@ All strings, so the change and the locale files have one source. Keys under### Backend-- `mcpCapabilityRows` in `backend/api/v1/mcp_gate.go`: a map from row id to procedure names, next- to `mcpRequestShapeRefusals`, which it resembles in shape and intent.-- Lint clauses in `mcp_gate_test.go`, each with a RED test that breaks one input: every served- method in exactly one row; no refused method in any row; read rows equal the READ set; write rows- equal the WRITE set.-- `TestMCPClassificationInventory` gains a Row column in `testdata/mcp_method_classification.md`,- so a class or row change shows up as a reviewable diff.+No behavior change. One comment on `MCPMethodClass` in `proto/v1/v1/annotation.proto` and its+regenerated output; the rule that keeps the row wording true is an instruction under Metadata and+API conventions in the root `AGENTS.md` (D11), not code.++## Keeping the rows true++Nothing enforces the wording, so annotating an RPC `mcp_method_class = READ` or `WRITE` — a new RPC,+or a reclassified one — is also a change to what the Access policy page and the OAuth consent screen+promise. What to do:++1. Read the row table above and judge whether a row still describes the method. The right column+ records the method families each row stands for, not an exhaustive list, so this is a judgment+ about the wording rather than a lookup. `backend/api/v1/testdata/mcp_method_classification.md` is+ the generated list of every method and its class, and CI forces a diff on it for the same change.+2. If none covers it, reword a row or add one. The copy is `settings.mcp.ladder.row.*` in+ `frontend/src/locales/` — all five files — and the order and tier are in+ `frontend/src/components/mcp/mcpCapabilityRows.ts`. Update the table above in the same change.+3. Check the new wording on all five axes in The rows — mode, engine, effect, complement and+ method — against their rules: state the bound and never the behavior, name the feature and never+ the mechanism, and claim only what holds whatever the caller's permissions. A line you are+ changing to fix one axis still has to hold on the other four; every regression this page has+ shipped came from checking only the axis that prompted the edit.+4. For any claim of the form "refused where X", check `HasQueryValidator` and+ `EngineSupportQueryNewACL` as a conjunction rather than either alone, and check each RPC that+ executes statements separately — `SQLService/Query` and `SQLService/Export` gate on different+ conditions, so a sentence true of one is not thereby true of the other.++The consent screen renders row titles only, so a caveat that belongs to one mode or one engine has+to live in the bound line there (D10), not in a row's sub-items.+## Out of scope@@ -343,9 +566,16 @@ All strings, so the change and the locale files have one source. Keys underOn MySQL it skips statement validation and the driver executes non-query statements, and theclamp today lives only in `SQLService/Query`. Under the presets Export is served only alongsidethe DML/DDL row, so there is no exposure until then. That clamp is an MCP implementation change,- tracked separately from this doc.+ tracked separately from this doc. The same split is why the consent card's Read-write bound names+ the operation as well as the engine (the method axis in The rows).- A docs page listing the methods per row, generated from the inventory. Worth doing; not linkedfrom the card until it exists.+- Making the collapsed list findable by the browser's find-in-page. Base UI unmounts a closed panel,+ so the rows and the floor line are absent from the DOM until the disclosure is opened, and+ `hiddenUntilFound` would keep them mounted instead. Declined: collapsing by default is D1's+ decision, the summary line states what the mode allows and the trigger is beside it, and the+ attribute's browser support is uneven — the unmount also keeps eight rows out of the accessibility+ tree while they are not shown. Revisit if the list stops being a disclosure.- Per-engine read-only depth and masking coverage. The removed drawer showed both; they belong indocs, not on the policy card.- The ceiling gate itself, the classification, and the consent flow's mechanics.diff --git a/frontend/scripts/check-i18n.mjs b/frontend/scripts/check-i18n.mjsindex 0a2d7f3a24..2e1dd67f85 100644--- a/frontend/scripts/check-i18n.mjs+++ b/frontend/scripts/check-i18n.mjs@@ -80,6 +80,15 @@ const DYNAMIC_PREFIXES = ["settings.mcp.policy.unreadable.title","settings.mcp.policy.unserved.description","settings.mcp.policy.unserved.title",+ // The capability ladder's template-driven families only: row titles and+ // detail lines keyed by row id, the per-mode summary, and the tier tag and+ // divider keyed by tier. Listed per family rather than as the+ // `settings.mcp.ladder.` subtree, which would also exempt every sibling key+ // the ladder names literally — the floor line among them.+ "settings.mcp.ladder.row.",+ "settings.mcp.ladder.stops.",+ "settings.mcp.ladder.summary.",+ "settings.mcp.ladder.tier.",// Built as `…undisclosed.${reason}.<suffix>` over a reason the consent page// derives: title, description and line for both, plus retry for the one that// offers it. Listed per reason rather than as one subtree, which would alsodiff --git a/frontend/src/components/mcp/MCPModeBadge.test.tsx b/frontend/src/components/mcp/MCPModeBadge.test.tsxnew file mode 100644index 0000000000..cd8c6c7b59--- /dev/null+++ b/frontend/src/components/mcp/MCPModeBadge.test.tsx@@ -0,0 +1,91 @@+import { act, type ReactElement } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, test, vi } from "vitest";+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";+import { MCP_CAPABILITY_CHOICES, MCP_MODE_PRESENTATION } from "./mcpPolicy";+import { MCPModeBadge } from "./MCPModeBadge";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ act(() => {+ root.render(element);+ });+ return {+ container,+ unmount: () =>+ act(() => {+ root.unmount();+ container.remove();+ }),+ };+};++describe("MCPModeBadge", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ // The identity an admin picked in the selector is the identity shown in force+ // and on the consent screen. Without this the glyph can be deleted or wired to+ // the wrong mode with every gate still green.+ test("every mode carries its own glyph beside its name", () => {+ const glyphs = new Set<string>();+ for (const mode of MCP_CAPABILITY_CHOICES) {+ const { container, unmount } = renderIntoContainer(+ <MCPModeBadge mode={mode} />+ );+ const icon = container.querySelector("svg");+ expect(icon).not.toBeNull();+ glyphs.add(icon?.outerHTML ?? "");+ expect(container.textContent).toContain(+ `settings.mcp.policy.mode.${MCP_MODE_PRESENTATION[mode].key}.title`+ );+ unmount();+ }+ // Three modes, three distinct glyphs: a table wired to one icon for all+ // would still satisfy the per-mode assertions above.+ expect(glyphs.size).toBe(MCP_CAPABILITY_CHOICES.length);+ });++ test("without a description the badge is just the mode's name", () => {+ const { container, unmount } = renderIntoContainer(+ <MCPModeBadge mode={MCPSetting_Capability.READ_ONLY} />+ );+ expect(container.querySelector("span.sr-only")).toBeNull();+ expect(container.querySelector("[aria-hidden='true']")?.tagName).toBe(+ "svg"+ );+ unmount();+ });++ test("a described badge reads the sentence once, not the name twice", () => {+ const { container, unmount } = renderIntoContainer(+ <MCPModeBadge+ mode={MCPSetting_Capability.READ_ONLY}+ describedAs="Current policy: Read-only"+ />+ );+ expect(container.querySelector("span.sr-only")?.textContent).toBe(+ "Current policy: Read-only"+ );+ const visible = [...container.querySelectorAll("span")].find(+ (node) =>+ node.getAttribute("aria-hidden") === "true" && node.textContent !== ""+ );+ expect(visible?.textContent).toBe(+ "settings.mcp.policy.mode.read-only.title"+ );+ expect(container.querySelector("[aria-label]")).toBeNull();+ unmount();+ });+});diff --git a/frontend/src/components/mcp/MCPModeBadge.tsx b/frontend/src/components/mcp/MCPModeBadge.tsxnew file mode 100644index 0000000000..ba239adccd--- /dev/null+++ b/frontend/src/components/mcp/MCPModeBadge.tsx@@ -0,0 +1,51 @@+import { useTranslation } from "react-i18next";+import {+ MCP_MODE_PRESENTATION,+ type MCPMode,+ mcpModeKey,+} from "@/components/mcp/mcpPolicy";+import { Badge } from "@/components/ui/badge";++interface Props {+ readonly mode: MCPMode;+ /**+ * A sentence naming what this badge reports, already translated. Where it is+ * given, the badge announces it instead of the bare mode name — for the+ * surface where the badge is the subject of the view and its name alone+ * would not say what it names.+ *+ * Resolved by the caller rather than threaded in as a locale key, so the key+ * stays a literal translation call the unused-key checker can trace.+ */+ readonly describedAs?: string;+}++/**+ * A mode's identity: its glyph, its name, and its color.+ *+ * One component rather than one per surface, because the identity has to be the+ * same on the settings page and on the consent page: the admin who picked the+ * eye is shown the eye when a session asks to connect.+ */+export function MCPModeBadge({ mode, describedAs }: Props) {+ const { t } = useTranslation();+ const { icon: Icon, badge } = MCP_MODE_PRESENTATION[mode];+ const label = t(mcpModeKey(mode, "title"));+ return (+ <Badge variant={badge} className="gap-x-1">+ <Icon className="size-3.5 shrink-0" aria-hidden="true" />+ {/* Carried as text rather than aria-label: a Badge renders a bare span,+ and ARIA forbids naming its implicit `generic` role, so a label put+ there is dropped. Swapping which copy each audience gets keeps the+ sentence whole in every locale's word order. */}+ {describedAs ? (+ <>+ <span className="sr-only">{describedAs}</span>+ <span aria-hidden="true">{label}</span>+ </>+ ) : (+ label+ )}+ </Badge>+ );+}diff --git a/frontend/src/components/mcp/mcpCapabilityRows.test.ts b/frontend/src/components/mcp/mcpCapabilityRows.test.tsnew file mode 100644index 0000000000..16560f74f9--- /dev/null+++ b/frontend/src/components/mcp/mcpCapabilityRows.test.ts@@ -0,0 +1,77 @@+// @vitest-environment node+import { describe, expect, test } from "vitest";+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";+import {+ isRowServed,+ MCP_CAPABILITY_ROWS,+ MCP_CAPABILITY_TIERS,+ rowsInTier,+ servedRows,+} from "./mcpCapabilityRows";+import { isServingMode, MCP_CAPABILITY_CHOICES } from "./mcpPolicy";++describe("mcpCapabilityRows", () => {+ // Each mode is a PREFIX of the one list. It is what lets a single ladder show+ // all three modes at once, and what a custom policy would later select over.+ test("every mode serves a prefix of the list", () => {+ for (const mode of [+ MCPSetting_Capability.DISABLED,+ MCPSetting_Capability.READ_ONLY,+ MCPSetting_Capability.READ_WRITE,+ ] as const) {+ const served = servedRows(mode);+ expect(served).toEqual(MCP_CAPABILITY_ROWS.slice(0, served.length));+ }+ });++ test("the served set grows with the mode and never shrinks a read row", () => {+ expect(servedRows(MCPSetting_Capability.DISABLED)).toHaveLength(0);+ expect(+ servedRows(MCPSetting_Capability.READ_ONLY).map((row) => row.id)+ ).toEqual(["read-schemas", "read-data", "read-workflow"]);+ expect(servedRows(MCPSetting_Capability.READ_WRITE)).toHaveLength(+ MCP_CAPABILITY_ROWS.length+ );+ });++ // isServingMode gates the ladder, the masking toggle and the consent routing,+ // and is the one mode predicate the compiler does not force: a fourth serving+ // mode breaks SERVES and MCP_MODE_PRESENTATION, but leaves this answering+ // "false" and sending the session to the Disabled consent screen.+ test("a mode serves a session exactly when it serves a row", () => {+ for (const mode of MCP_CAPABILITY_CHOICES) {+ expect(isServingMode(mode), String(mode)).toBe(+ MCP_CAPABILITY_ROWS.some((row) => isRowServed(mode, row))+ );+ }+ });++ test("read-only serves no write row, so no write tag can appear under it", () => {+ for (const row of MCP_CAPABILITY_ROWS) {+ expect(isRowServed(MCPSetting_Capability.READ_ONLY, row)).toBe(+ row.tier === "read"+ );+ expect(isRowServed(MCPSetting_Capability.DISABLED, row)).toBe(false);+ expect(isRowServed(MCPSetting_Capability.READ_WRITE, row)).toBe(true);+ }+ });++ // The ladder renders one list per tier, in MCP_CAPABILITY_TIERS order. This+ // pins that doing so reproduces the ordered list exactly — which is both the+ // contiguity of each tier and the position of its "stops here" divider.+ test("rendering tier by tier reproduces the one ordered list", () => {+ expect(+ MCP_CAPABILITY_TIERS.flatMap((tier) => [...rowsInTier(tier)])+ ).toEqual([...MCP_CAPABILITY_ROWS]);+ expect(MCP_CAPABILITY_TIERS).toEqual(["read", "write"]);+ // Every tier carries rows, so no divider is emitted for an empty list.+ for (const tier of MCP_CAPABILITY_TIERS) {+ expect(rowsInTier(tier).length).toBeGreaterThan(0);+ }+ });++ test("row ids are unique, so a row cannot key another row's copy", () => {+ const ids = MCP_CAPABILITY_ROWS.map((row) => row.id);+ expect(new Set(ids).size).toBe(ids.length);+ });+});diff --git a/frontend/src/components/mcp/mcpCapabilityRows.ts b/frontend/src/components/mcp/mcpCapabilityRows.tsnew file mode 100644index 0000000000..1aa100ee9c--- /dev/null+++ b/frontend/src/components/mcp/mcpCapabilityRows.ts@@ -0,0 +1,106 @@+import type { MCPMode } from "@/components/mcp/mcpPolicy";+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";++/**+ * The two tiers a capability row can belong to. They are the product's words+ * for the READ and WRITE method classes the gate serves (`mcpServingClasses`,+ * backend/api/v1/mcp_gate.go), and a mode serves whole tiers — never part of+ * one.+ */+export type MCPCapabilityTier = "read" | "write";++/**+ * The rows, by the id their copy is keyed under. A union rather than `string`+ * so the table and its consumers cannot drift to an id nothing else knows.+ * Locale coverage is not checked: these keys are built from the id, so a row+ * with no copy renders the raw key.+ */+export type MCPCapabilityRowId =+ | "read-schemas"+ | "read-data"+ | "read-workflow"+ | "propose"+ | "run-rollouts"+ | "run-statements"+ | "export"+ | "manage";++export interface MCPCapabilityRow {+ /** Keys the row's copy under `settings.mcp.ladder.row.<id>.*`. */+ readonly id: MCPCapabilityRowId;+ readonly tier: MCPCapabilityTier;+}++/**+ * One ordered list in which every mode is a prefix. Read rows first, then write+ * rows.+ *+ * Between them these titles claim to cover every READ and WRITE method, and+ * nothing checks that: a method annotated into either class is served the moment+ * it is annotated, whether or not a row names it. Which methods each row stands+ * for is NOT here — this file carries only the order and the tier. Reclassifying+ * an RPC means rereading the row table in docs/design/mcp-capability-ladder.md+ * and updating it in the same change.+ *+ * `run-statements` is the one row backed by no method: it names the statement+ * clamp (`mcp_sql_clamp.go`) that Read-write lifts, which is a real difference+ * between the modes that no method name shows.+ */+export const MCP_CAPABILITY_ROWS: readonly MCPCapabilityRow[] = [+ { id: "read-schemas", tier: "read" },+ { id: "read-data", tier: "read" },+ { id: "read-workflow", tier: "read" },+ { id: "propose", tier: "write" },+ { id: "run-rollouts", tier: "write" },+ { id: "run-statements", tier: "write" },+ { id: "export", tier: "write" },+ { id: "manage", tier: "write" },+];++/** Tier order, and with it the order the "stops here" dividers appear in. */+export const MCP_CAPABILITY_TIERS: readonly MCPCapabilityTier[] = [+ "read",+ "write",+];++/**+ * The bundle's copy of the ceiling the gate evaluates (`mcpServingClasses`,+ * backend/api/v1/mcp_gate.go).+ *+ * A table rather than a switch, because a switch is exhaustive over the modes+ * and not over the tiers: a comparison against the tiers that exist today+ * compiles unchanged against a widened union and answers "refused" for rows+ * nobody classified. Every cell here has to be filled in, so adding either a+ * mode or a tier fails to compile until someone decides what it serves.+ */+const SERVES: Record<MCPMode, Record<MCPCapabilityTier, boolean>> = {+ [MCPSetting_Capability.DISABLED]: { read: false, write: false },+ [MCPSetting_Capability.READ_ONLY]: { read: true, write: false },+ [MCPSetting_Capability.READ_WRITE]: { read: true, write: true },+};++export const isRowServed = (mode: MCPMode, row: MCPCapabilityRow): boolean =>+ SERVES[mode][row.tier];++export const servedRows = (mode: MCPMode): readonly MCPCapabilityRow[] =>+ MCP_CAPABILITY_ROWS.filter((row) => isRowServed(mode, row));++/**+ * The locale keys the ladder's copy is stored under, built in one place beside+ * the ids they are built from. These families are template-keyed, so+ * `check-i18n.mjs` exempts them by prefix and cannot report a missing line.+ */+export const mcpTierKey = (+ tier: MCPCapabilityTier,+ part: "tier" | "stops"+): string => `settings.mcp.ladder.${part}.${tier}`;++export const mcpRowKey = (+ row: MCPCapabilityRow,+ part: "title" | "details"+): string => `settings.mcp.ladder.row.${row.id}.${part}`;++export const rowsInTier = (+ tier: MCPCapabilityTier+): readonly MCPCapabilityRow[] =>+ MCP_CAPABILITY_ROWS.filter((row) => row.tier === tier);diff --git a/frontend/src/components/mcp/mcpPolicy.test.ts b/frontend/src/components/mcp/mcpPolicy.test.tsindex 8f814e5a6d..e09921c1b5 100644--- a/frontend/src/components/mcp/mcpPolicy.test.ts+++ b/frontend/src/components/mcp/mcpPolicy.test.ts@@ -7,7 +7,9 @@ import {} from "@/types/proto-es/v1/setting_service_pb";import {isMCPMode,+ isServingMode,MCP_CAPABILITY_CHOICES,+ mcpModeKey,readConsentCeiling,} from "./mcpPolicy";@@ -51,38 +53,77 @@ describe("readConsentCeiling", () => {expect(readConsentCeiling(undefined)).toEqual({ kind: "unknown" });});- test("a served ceiling carries the response the disclosure needs", () => {- const setting = settingWith(MCPSetting_Capability.READ_WRITE);- expect(readConsentCeiling(setting)).toEqual({ kind: "mode", setting });+ test("a served ceiling carries the mode and the flag the disclosure reads", () => {+ expect(+ readConsentCeiling(+ create(MCPSettingSchema, {+ capability: MCPSetting_Capability.READ_WRITE,+ ignoreMaskingExemptions: true,+ })+ )+ ).toEqual({+ kind: "mode",+ mode: MCPSetting_Capability.READ_WRITE,+ ignoreMaskingExemptions: true,+ });});test("disabled is a policy, so it reaches its own screen", () => {// Not undisclosable: an admin turned MCP off, which is a decision this page// can name and the one refusing ceiling with a screen of its own.- const setting = settingWith(MCPSetting_Capability.DISABLED);- expect(readConsentCeiling(setting)).toEqual({ kind: "mode", setting });+ expect(+ readConsentCeiling(settingWith(MCPSetting_Capability.DISABLED))+ ).toEqual({+ kind: "mode",+ mode: MCPSetting_Capability.DISABLED,+ ignoreMaskingExemptions: false,+ });});// The three ways a stored ceiling reaches this page without a name for it.// They differed once, by whether the server's serving table carried a row;// the remedy the page prints now names both repairs, so they are one state.- test("a value nothing could resolve is undisclosable", () => {- expect(- readConsentCeiling(- settingWith(MCPSetting_Capability.CAPABILITY_UNSPECIFIED)- )- ).toEqual({ kind: "undisclosable" });- });-- test("the reserved tier is undisclosable", () => {- expect(readConsentCeiling(settingWith(2))).toEqual({+ test.each([+ [+ "a value nothing could resolve",+ MCPSetting_Capability.CAPABILITY_UNSPECIFIED,+ ],+ ["the reserved tier", 2],+ ["a tier a newer release wrote", 5],+ ])("%s is undisclosable", (_label, capability) => {+ expect(readConsentCeiling(settingWith(capability))).toEqual({kind: "undisclosable",});});+});- test("a tier a newer release wrote is undisclosable", () => {- expect(readConsentCeiling(settingWith(5))).toEqual({- kind: "undisclosable",- });+// The predicate answers "is there a session to describe" once, including for+// the value a mode holds before anyone has picked one.+describe("isServingMode", () => {+ test("admits exactly the ceilings that serve a session", () => {+ expect(isServingMode(MCPSetting_Capability.READ_ONLY)).toBe(true);+ expect(isServingMode(MCPSetting_Capability.READ_WRITE)).toBe(true);+ expect(isServingMode(MCPSetting_Capability.DISABLED)).toBe(false);+ });++ test("refuses the values that are not a ceiling at all", () => {+ expect(isServingMode(undefined)).toBe(false);+ expect(isServingMode(MCPSetting_Capability.CAPABILITY_UNSPECIFIED)).toBe(+ false+ );+ // The reserved 2, and anything a newer release writes.+ expect(isServingMode(2 as MCPSetting_Capability)).toBe(false);+ expect(isServingMode(99 as MCPSetting_Capability)).toBe(false);+ });+});++describe("mcpModeKey", () => {+ test("builds the locale key each mode's copy is stored under", () => {+ expect(mcpModeKey(MCPSetting_Capability.READ_WRITE, "title")).toBe(+ "settings.mcp.policy.mode.read-write.title"+ );+ expect(mcpModeKey(MCPSetting_Capability.DISABLED, "best-for")).toBe(+ "settings.mcp.policy.mode.disabled.best-for"+ );});});diff --git a/frontend/src/components/mcp/mcpPolicy.ts b/frontend/src/components/mcp/mcpPolicy.tsindex 5feda5f609..5a00ded691 100644--- a/frontend/src/components/mcp/mcpPolicy.ts+++ b/frontend/src/components/mcp/mcpPolicy.ts@@ -1,3 +1,5 @@+import { Eye, type LucideIcon, PencilLine, Unplug } from "lucide-react";+import type { BadgeProps } from "@/components/ui/badge";import {type MCPSetting,MCPSetting_Capability,@@ -8,6 +10,44 @@ export type MCPMode =| MCPSetting_Capability.READ_ONLY| MCPSetting_Capability.READ_WRITE;+/**+ * A mode that admits MCP sessions. Anything describing what a session may do —+ * the capability ladder, the consent disclosure, the masking toggle — takes+ * this rather than MCPMode, so "there is a session to describe" is checked by+ * the compiler instead of by a comparison at each call site.+ */+export type MCPServingMode =+ | MCPSetting_Capability.READ_ONLY+ | MCPSetting_Capability.READ_WRITE;++/**+ * How a mode identifies itself wherever it appears: the locale-key stem, the+ * glyph, and the chip variant. One row per mode rather than parallel tables;+ * `MCPModeBadge` is what renders it, and says why. The variant is the only+ * place a mode's color appears — the selector cards stay neutral so the accent+ * keeps meaning "selected".+ */+export const MCP_MODE_PRESENTATION: Record<+ MCPMode,+ { key: string; icon: LucideIcon; badge: BadgeProps["variant"] }+> = {+ [MCPSetting_Capability.DISABLED]: {+ key: "disabled",+ icon: Unplug,+ badge: "destructive",+ },+ [MCPSetting_Capability.READ_ONLY]: {+ key: "read-only",+ icon: Eye,+ badge: "success",+ },+ [MCPSetting_Capability.READ_WRITE]: {+ key: "read-write",+ icon: PencilLine,+ badge: "warning",+ },+};+/*** The ceilings an admin picks between, least to most capable. The bundle's copy* of the serving table the gate evaluates (`mcpServingClasses`,@@ -24,6 +64,29 @@ export const isMCPMode = (): capability is MCPMode =>MCP_CAPABILITY_CHOICES.some((choice) => choice === capability);+/**+ * Whether a mode admits MCP sessions at all.+ *+ * Stated by the modes it admits rather than as "not Disabled", because the+ * caller's mode is often not yet chosen: an unreadable stored ceiling leaves+ * the editor with no pick, and a negation would count that absence as serving.+ */+export const isServingMode = (+ capability: MCPSetting_Capability | undefined+): capability is MCPServingMode =>+ capability === MCPSetting_Capability.READ_ONLY ||+ capability === MCPSetting_Capability.READ_WRITE;++/** The locale keys a mode's strings are stored under, built in one place. */+export const mcpSummaryKey = (mode: MCPServingMode): string =>+ `settings.mcp.ladder.summary.${MCP_MODE_PRESENTATION[mode].key}`;++export const mcpModeKey = (+ mode: MCPMode,+ part: "title" | "caption" | "best-for"+): string =>+ `settings.mcp.policy.mode.${MCP_MODE_PRESENTATION[mode].key}.${part}`;+/*** What the consent page can truthfully tell someone about to approve a client.*@@ -32,8 +95,13 @@ export const isMCPMode = (* then find an admin (BOT-106).*/export type ConsentCeiling =- /** Carries the response, so the disclosure cannot be rendered without it. */- | { kind: "mode"; setting: MCPSetting }+ /**+ * The disclosable policy: the mode already narrowed to one this bundle can+ * name, plus the only other field the disclosure reads. The response itself+ * does not travel, so no consumer can re-derive the mode from it and reach a+ * different answer.+ */+ | { kind: "mode"; mode: MCPMode; ignoreMaskingExemptions: boolean }/** Actuator info did not provide a policy. The policy is not known to be anything. */| { kind: "unknown" }/** A stored ceiling this build has no wording for, whatever wrote it. */@@ -56,5 +124,9 @@ export const readConsentCeiling = (if (!isMCPMode(setting.capability)) {return { kind: "undisclosable" };}- return { kind: "mode", setting };+ return {+ kind: "mode",+ mode: setting.capability,+ ignoreMaskingExemptions: setting.ignoreMaskingExemptions,+ };};diff --git a/frontend/src/components/sql-review/RuleTable.test.tsx b/frontend/src/components/sql-review/RuleTable.test.tsxindex 7436511dab..d477919421 100644--- a/frontend/src/components/sql-review/RuleTable.test.tsx+++ b/frontend/src/components/sql-review/RuleTable.test.tsx@@ -123,7 +123,10 @@ vi.mock("@/components/ui/tooltip", () => ({vi.mock("./RuleComponents", () => ({RuleConfig: () => <div data-testid="rule-config" />,- RuleEditDialog: () => <div data-testid="rule-edit-dialog" />,+ // Rendered in row position inside <tbody>, where the real dialog portals its+ // content out and leaves nothing structural. A <tr> is the valid stand-in; a+ // <div> here is markup the real component never produces.+ RuleEditDialog: () => <tr data-testid="rule-edit-dialog" />,RuleLevelFilter: () => <div data-testid="rule-level-filter" />,RuleLevelSwitch: () => {mocks.ruleLevelSwitch();diff --git a/frontend/src/components/ui/collapsible.test.tsx b/frontend/src/components/ui/collapsible.test.tsxnew file mode 100644index 0000000000..5a7279fb73--- /dev/null+++ b/frontend/src/components/ui/collapsible.test.tsx@@ -0,0 +1,97 @@+import { act, createElement, type ReactElement } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, test } from "vitest";+import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "./collapsible";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ act(() => {+ root.render(element);+ });+ return {+ container,+ rerender: (next: ReactElement) => act(() => root.render(next)),+ unmount: () =>+ act(() => {+ root.unmount();+ container.remove();+ }),+ };+};++const tree = (props: Record<string, unknown>) =>+ createElement(+ Collapsible,+ props,+ createElement(CollapsibleTrigger, null, "Toggle"),+ createElement(CollapsiblePanel, null, "Panel body")+ );++const trigger = (container: HTMLElement) => {+ const el = container.querySelector("button");+ if (!el) throw new Error("trigger not found");+ return el;+};++describe("Collapsible", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ // The whole point of using the primitive rather than a `useState` and a div:+ // the trigger has to announce the panel it controls, and a hand-rolled+ // disclosure routinely ships without it.+ test("the trigger carries the expanded state assistive tech reads", () => {+ const { container, rerender, unmount } = renderIntoContainer(+ tree({ open: false, onOpenChange: () => undefined })+ );+ expect(trigger(container).getAttribute("aria-expanded")).toBe("false");++ rerender(tree({ open: true, onOpenChange: () => undefined }));+ expect(trigger(container).getAttribute("aria-expanded")).toBe("true");+ // The panel only exists while open, so the association is asserted there.+ const controls = trigger(container).getAttribute("aria-controls");+ expect(controls).toBeTruthy();+ expect(container.querySelector(`#${controls}`)?.textContent).toContain(+ "Panel body"+ );+ unmount();+ });++ test("the panel is absent while closed and rendered while open", () => {+ const { container, rerender, unmount } = renderIntoContainer(+ tree({ open: false, onOpenChange: () => undefined })+ );+ expect(container.textContent).not.toContain("Panel body");++ rerender(tree({ open: true, onOpenChange: () => undefined }));+ expect(container.textContent).toContain("Panel body");+ unmount();+ });++ test("pressing the trigger asks the owner to toggle", () => {+ const seen: boolean[] = [];+ const { container, unmount } = renderIntoContainer(+ tree({ open: false, onOpenChange: (next: boolean) => seen.push(next) })+ );+ act(() => {+ trigger(container).click();+ });+ expect(seen).toEqual([true]);+ unmount();+ });++ test("the trigger keeps a visible keyboard focus state", () => {+ const { container, unmount } = renderIntoContainer(+ tree({ open: false, onOpenChange: () => undefined })+ );+ expect(trigger(container).className).toContain("focus-visible:ring-2");+ unmount();+ });+});diff --git a/frontend/src/components/ui/collapsible.tsx b/frontend/src/components/ui/collapsible.tsxnew file mode 100644index 0000000000..40068163f0--- /dev/null+++ b/frontend/src/components/ui/collapsible.tsx@@ -0,0 +1,41 @@+import { Collapsible as BaseCollapsible } from "@base-ui/react/collapsible";+import type { ComponentProps } from "react";+import { cn } from "@/lib/utils";++function Collapsible({+ className,+ ...props+}: ComponentProps<typeof BaseCollapsible.Root>) {+ return (+ <BaseCollapsible.Root+ className={cn("flex flex-col", className)}+ {...props}+ />+ );+}++/**+ * The button that opens and closes the panel. Base UI owns `aria-expanded` and+ * `aria-controls`; a consumer supplies the visible label and its own indicator.+ */+function CollapsibleTrigger({+ className,+ ...props+}: ComponentProps<typeof BaseCollapsible.Trigger>) {+ return (+ <BaseCollapsible.Trigger+ className={cn(+ "flex w-full items-center gap-x-2 text-left cursor-pointer",+ "focus:outline-hidden focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2",+ className+ )}+ {...props}+ />+ );+}++// Re-exported rather than wrapped: unlike the root and the trigger, the panel+// needs no styling or behavior of ours.+const CollapsiblePanel = BaseCollapsible.Panel;++export { Collapsible, CollapsiblePanel, CollapsibleTrigger };diff --git a/frontend/src/components/ui/popover.test.tsx b/frontend/src/components/ui/popover.test.tsxindex eaa77a6af3..e7ca0f3d88 100644--- a/frontend/src/components/ui/popover.test.tsx+++ b/frontend/src/components/ui/popover.test.tsx@@ -20,9 +20,10 @@ describe("Popover", () => {await act(async () => {root.render(<Popover>- <PopoverTrigger>- <button type="button">Open</button>- </PopoverTrigger>+ {/* The trigger renders the button itself. Nesting one inside it+ produced button-in-button, which the parser resolves by closing+ the outer element early. */}+ <PopoverTrigger>Open</PopoverTrigger><PopoverContent>Popover body</PopoverContent></Popover>);@@ -43,9 +44,7 @@ describe("Popover", () => {await act(async () => {root.render(<Popover>- <PopoverTrigger>- <button type="button">Open</button>- </PopoverTrigger>+ <PopoverTrigger>Open</PopoverTrigger>{/* Popover content renders via portal into bb-react-layer-overlay.We query document.body since the popup lives outside `container`. */}<PopoverContent>Popover body</PopoverContent>@@ -75,9 +74,7 @@ describe("Popover", () => {function ControlledPopover({ open }: { open: boolean }) {return (<Popover open={open}>- <PopoverTrigger>- <button type="button">Open</button>- </PopoverTrigger>+ <PopoverTrigger>Open</PopoverTrigger><PopoverContent>Controlled content</PopoverContent></Popover>);diff --git a/frontend/src/components/ui/radio-group.test.tsx b/frontend/src/components/ui/radio-group.test.tsxindex dacc566019..77ef6bb748 100644--- a/frontend/src/components/ui/radio-group.test.tsx+++ b/frontend/src/components/ui/radio-group.test.tsx@@ -95,22 +95,53 @@ describe("RadioGroupItem", () => {unmount();});- test("uses a not-allowed cursor for a disabled option", () => {+ // The cursor follows the radio's resolved disabled state rather than this+ // component's own prop, because Base UI resolves that state from the group+ // too. Asserted on the attribute the CSS selects: `[data-disabled]` on the+ // radio, as a direct child of the label.+ test.each([+ ["the option's own prop", { group: false }],+ ["the group's disabled state", { group: true }],+ ])("a not-allowed cursor follows %s", (_label, { group }) => {const { container, unmount } = renderIntoContainer(createElement(RadioGroup,- { value: "workspace", onValueChange: () => undefined },+ {+ value: "workspace",+ onValueChange: () => undefined,+ ...(group ? { disabled: true } : {}),+ },createElement(RadioGroupItem,- { value: "workspace", disabled: true },+ { value: "workspace", ...(group ? {} : { disabled: true }) },"Workspace")));- const label = container.querySelector("label");- expect(label?.className).toContain("cursor-not-allowed");- expect(label?.className).not.toContain("cursor-pointer");+ expect(container.querySelector("label > [data-disabled]")).not.toBeNull();++ unmount();+ });++ // The selector is scoped to the direct child because an item may wrap a+ // disabled control of its own — InstanceFormBody's "Custom" option holds a+ // number input that is disabled until that option is picked.+ test("a disabled control inside an option does not disable the option", () => {+ const { container, unmount } = renderIntoContainer(+ createElement(+ RadioGroup,+ { value: "default", onValueChange: () => undefined },+ createElement(+ RadioGroupItem,+ { value: "custom" },+ createElement("input", { type: "number", disabled: true })+ )+ )+ );++ expect(container.querySelector("input:disabled")).not.toBeNull();+ expect(container.querySelector("label > [data-disabled]")).toBeNull();unmount();});diff --git a/frontend/src/components/ui/radio-group.tsx b/frontend/src/components/ui/radio-group.tsxindex 2ac8c26437..1f679ceefe 100644--- a/frontend/src/components/ui/radio-group.tsx+++ b/frontend/src/components/ui/radio-group.tsx@@ -30,8 +30,14 @@ function RadioGroupItem({return (<labelclassName={cn(- "flex items-center gap-x-2",- disabled ? "cursor-not-allowed" : "cursor-pointer",+ "flex items-center gap-x-2 cursor-pointer",+ // Base UI resolves the radio's disabled state from the group as well as+ // from this prop, so reading the prop alone leaves a group-disabled item+ // with a pointer over a control that ignores the click. Matched on the+ // direct child, which is only ever the radio: `children` render inside+ // the content div, and an item that wraps a disabled input of its own+ // would otherwise turn the whole row not-allowed.+ "has-[>[data-disabled]]:cursor-not-allowed",className)}>@@ -42,7 +48,9 @@ function RadioGroupItem({"flex size-4 shrink-0 items-center justify-center rounded-full border border-control-border","data-[checked]:border-[rgb(var(--color-accent))] data-[checked]:border-[5px]","focus:outline-hidden focus-visible:ring-2 focus-visible:ring-[rgb(var(--color-accent))] focus-visible:ring-offset-2",- "disabled:cursor-not-allowed disabled:opacity-50",+ // Root renders a span, which `:disabled` cannot match. `data-disabled:`+ // is the convention this directory already uses (see checkbox.tsx).+ "data-disabled:cursor-not-allowed data-disabled:opacity-50",radioClassName)}{...props}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 65824df4e5..277000371d 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1630,12 +1630,10 @@},"line": {"audit": "Audited actions carry an MCP tag, and anything the policy refuses is streamed to stdout when audit logging to stdout is enabled",- "capped": "Capped by your own Bytebase permissions",+ "capped-read-only": "Capped by your own Bytebase permissions, and by what Bytebase can check on each database engine — where it cannot show a statement is a read, no query runs at all",+ "capped-read-write": "Capped by your own Bytebase permissions, and by what Bytebase supports for each database engine and each operation","masking": "Your masking exemptions do not apply to this session",- "no-write": "No data or schema changes",- "read": "Read schemas and run read-only queries",- "workflow": "Open issues, plans and rollouts, and export query results",- "write": "Make the data and schema changes your permissions allow"+ "no-write": "No changes, rollouts, exports or database management"},"title": "This session may","undisclosed": {@@ -2671,12 +2669,8 @@"description": "The IM integration will be used to push direct messages to users for specific issue events. Works with the project webhook."},"mcp": {- "auth": {- "description": "OAuth authentication is required on first connection. Ensure you have appropriate Bytebase permissions.",- "title": "Authentication Required"- },"connect": {- "description": "Add Bytebase to your AI client, approve access in the browser, and start asking.",+ "description": "Add Bytebase to your AI client and start asking. On first connection you sign in and approve access in the browser.","desktop-note": "Claude Desktop reads remote servers from your Claude account, not from the config file. Add this URL as a custom connector under Customize > Connectors on claude.ai, then it appears in Claude Desktop.","json-note": "This is the mcpServers shape. Client config formats differ: VS Code, for example, expects servers in its own mcp.json, so use the VS Code tab for that.","title": "Connect a client"@@ -2687,33 +2681,98 @@"example": "List all projects in my Bytebase instance","title": "Your First Prompt"},+ "ladder": {+ "disabled": "Nothing is allowed; no MCP session can connect.",+ "floor": {+ "label": "Never, in any mode:",+ "text": "approve issues, administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history."+ },+ "heading": "{{mode}} allows",+ "hide-details": "Hide details",+ "mark": {+ "allowed": "Allowed",+ "refused": "Not allowed"+ },+ "row": {+ "export": {+ "details": "Download results as a file. Data leaves Bytebase",+ "title": "Export query results"+ },+ "manage": {+ "details": "Sync instances and databases · Database settings and labels · Move databases between projects · Database groups · Saved queries",+ "title": "Manage database housekeeping"+ },+ "propose": {+ "details": "Create sheets · Create and edit plans and issues · Run plan checks and reviews · Create, delete and restore releases · Create and delete revisions · Generate schema diffs. An agent never approves its own change; the project's approval policy decides whether a human must",+ "title": "Propose changes"+ },+ "read-data": {+ "details": "Run read-only queries · Under Read-only, a request is refused whole unless every statement is shown to be a read that returns data; how deeply that can be checked varies by engine, and on some engines no statement can be shown to be a read at all · Your own query history · Saved queries and sheets you have access to",+ "title": "Read data by running queries"+ },+ "read-schemas": {+ "details": "Schemas · Databases and instances · Projects and database groups · Catalogs, changelogs and revisions · SQL review configs · Your own session and workspace facts",+ "title": "Read schemas and metadata"+ },+ "read-workflow": {+ "details": "Issues and comments · Plans and plan checks · Rollouts, task runs and logs · Releases · Rollback previews",+ "title": "Read the change workflow"+ },+ "run-rollouts": {+ "details": "Create a rollout · Run, skip or cancel its tasks, under the project's approval policy",+ "title": "Run rollouts and tasks"+ },+ "run-statements": {+ "details": "INSERT, UPDATE, DELETE, CREATE, ALTER, DROP through queries, as far as the engine and the user's own permissions allow",+ "title": "Run DML and DDL statements"+ }+ },+ "show-details": "Show details",+ "stops": {+ "read": "Read-only stops here",+ "write": "Read-write stops here"+ },+ "summary": {+ "read-only": "Read schemas, data and the change workflow; a request carrying anything that cannot be shown to be a read is refused, and nothing is exported",+ "read-write": "Read schemas, data and the change workflow; propose, run, export and manage"+ },+ "tier": {+ "read": "read",+ "write": "write"+ }+ },"policy": {- "audit": "MCP policy denials are streamed to stdout when audit logging to stdout is enabled.",- "description": "The most any MCP session may do in this workspace. Every session is also capped by the connecting user's own permissions.",+ "current": "Current policy: {{mode}}",+ "description": "The most any MCP session may do here. Sessions are also capped by each user's permissions, and policy refusals are streamed to stdout when audit logging to stdout is enabled.","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.",+ "badge-disabled": "Masking exemptions ignored — MCP is off",+ "badge-unlicensed": "Masking exemptions ignored — masking not licensed",+ "description": "If enabled, masked data stays masked in MCP sessions even for users with exemptions or unmask grants. Coverage depends on the engine: where Bytebase does not mask, this changes nothing. The console is unaffected.","title": "Ignore masking exemptions","unavailable": "Data masking is not licensed for this workspace, so nothing is masked whatever this is set to."},+ "masking-pending": {+ "applied": "This policy will be saved with masking exemptions applied.",+ "ignored": "This policy will be saved with masking exemptions ignored."+ },"mode": {"disabled": {"best-for": "Best for: keeping MCP off until you are ready to turn it on.",+ "caption": "No sessions connect","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.",+ "caption": "Explore and query","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.",+ "caption": "Change data and schemas","title": "Read-write"}},@@ -2723,7 +2782,8 @@},"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.",+ "tightening": "Applies to every running session's next request.",+ "tightening-change": "{{from}} → {{to}} applies to every running session's next request.","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.",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 63cbf215a2..091eac1665 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1630,12 +1630,10 @@},"line": {"audit": "Las acciones auditadas llevan una etiqueta MCP, y lo que la política rechaza se envía a la salida estándar cuando el registro de auditoría en la salida estándar está habilitado",- "capped": "Limitada por sus propios permisos de Bytebase",+ "capped-read-only": "Limitado por sus propios permisos de Bytebase y por lo que Bytebase puede comprobar en cada motor: donde no puede demostrar que una sentencia es de lectura, no se ejecuta ninguna consulta",+ "capped-read-write": "Limitado por sus propios permisos de Bytebase y por lo que Bytebase admite para cada motor de base de datos y cada operación","masking": "Sus exenciones de enmascaramiento no se aplican a esta sesión",- "no-write": "Ningún cambio de datos ni de esquema",- "read": "Explorar esquemas y ejecutar consultas de solo lectura",- "workflow": "Abrir incidencias, planes y despliegues, y exportar resultados de consultas",- "write": "Hacer los cambios de datos y esquema que permitan sus permisos"+ "no-write": "Sin cambios, despliegues, exportaciones ni administración de bases de datos"},"title": "Esta sesión puede","undisclosed": {@@ -2671,12 +2669,8 @@"description": "La integración de IM se utilizará para enviar mensajes directos a los usuarios para eventos de incidencias específicos. Funciona con el webhook del proyecto."},"mcp": {- "auth": {- "description": "Se requiere autenticación OAuth en la primera conexión. Asegúrese de tener los permisos apropiados en Bytebase.",- "title": "Autenticación requerida"- },"connect": {- "description": "Añada Bytebase a su cliente de IA, apruebe el acceso en el navegador y empiece a preguntar.",+ "description": "Añada Bytebase a su cliente de IA y empiece a preguntar. En la primera conexión inicia sesión y aprueba el acceso en el navegador.","desktop-note": "Claude Desktop lee los servidores remotos de su cuenta de Claude, no del archivo de configuración. Añada esta URL como conector personalizado en Customize > Connectors de claude.ai y aparecerá en Claude Desktop.","json-note": "Este es el formato mcpServers. Los formatos de configuración varían según el cliente: VS Code, por ejemplo, espera servers en su propio mcp.json, así que use la pestaña de VS Code para eso.","title": "Conectar un cliente"@@ -2687,33 +2681,98 @@"example": "Listar todos los proyectos en mi instancia de Bytebase","title": "Tu primer prompt"},+ "ladder": {+ "disabled": "No se permite nada; ninguna sesión MCP puede conectarse.",+ "floor": {+ "label": "Nunca, en ningún modo:",+ "text": "aprobar issues, administrar el espacio de trabajo, manejar credenciales, abrir una sesión de modo Admin ni leer el historial de consultas de otra persona."+ },+ "heading": "{{mode}} permite",+ "hide-details": "Ocultar detalles",+ "mark": {+ "allowed": "Permitido",+ "refused": "No permitido"+ },+ "row": {+ "export": {+ "details": "Descargar resultados como archivo. Los datos salen de Bytebase",+ "title": "Exportar resultados de consulta"+ },+ "manage": {+ "details": "Sincronizar instancias y bases de datos · Configuración y etiquetas de bases de datos · Mover bases de datos entre proyectos · Grupos de bases de datos · Consultas guardadas",+ "title": "Gestionar el mantenimiento de bases de datos"+ },+ "propose": {+ "details": "Crear hojas · Crear y editar plans e issues · Ejecutar comprobaciones de plan y revisiones · Crear, eliminar y restaurar versiones · Crear y eliminar revisiones · Generar diferencias de esquema. Un agente nunca aprueba su propio cambio; la política de aprobación del proyecto decide si una persona debe hacerlo",+ "title": "Proponer cambios"+ },+ "read-data": {+ "details": "Ejecutar consultas de solo lectura · En Solo lectura, una solicitud se rechaza por completo salvo que cada sentencia se demuestre ser una lectura que devuelve datos; la profundidad de esa comprobación depende del motor y, en algunos motores, ninguna sentencia puede demostrarse que sea una lectura · Su propio historial de consultas · Consultas guardadas y hojas a las que tiene acceso",+ "title": "Leer datos ejecutando consultas"+ },+ "read-schemas": {+ "details": "Esquemas · Bases de datos e instancias · Proyectos y grupos de bases de datos · Catálogos, historiales de cambios y revisiones · Configuraciones de revisión SQL · Datos de su propia sesión y del espacio de trabajo",+ "title": "Leer esquemas y metadatos"+ },+ "read-workflow": {+ "details": "Issues y comentarios · Plans y comprobaciones de plan · Despliegues, ejecuciones de tareas y registros · Versiones · Vistas previas de reversión",+ "title": "Leer el flujo de cambios"+ },+ "run-rollouts": {+ "details": "Crear un despliegue · Ejecutar, omitir o cancelar sus tareas, bajo la política de aprobación del proyecto",+ "title": "Ejecutar despliegues y tareas"+ },+ "run-statements": {+ "details": "INSERT, UPDATE, DELETE, CREATE, ALTER, DROP a través de consultas, hasta donde el motor y los permisos del propio usuario lo permitan",+ "title": "Ejecutar sentencias DML y DDL"+ }+ },+ "show-details": "Mostrar detalles",+ "stops": {+ "read": "Solo lectura termina aquí",+ "write": "Lectura y escritura termina aquí"+ },+ "summary": {+ "read-only": "Leer esquemas, datos y el flujo de cambios; una solicitud que lleve algo que no pueda demostrarse que es una lectura se rechaza, y no se exporta nada",+ "read-write": "Leer esquemas, datos y el flujo de cambios; proponer, ejecutar, exportar y gestionar"+ },+ "tier": {+ "read": "lectura",+ "write": "escritura"+ }+ },"policy": {- "audit": "Las denegaciones de la política MCP se envían a la salida estándar cuando el registro de auditoría en la salida estándar está habilitado.",- "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.",+ "current": "Política actual: {{mode}}",+ "description": "Lo máximo que puede hacer aquí cualquier sesión MCP. Las sesiones también están limitadas por los permisos de cada usuario, y las denegaciones de la política se envían a la salida estándar cuando el registro de auditoría en la salida estándar está habilitado.","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.",+ "badge-disabled": "Exenciones de enmascaramiento ignoradas — MCP está desactivado",+ "badge-unlicensed": "Exenciones de enmascaramiento ignoradas — enmascaramiento sin licencia",+ "description": "Si se activa, los datos enmascarados siguen enmascarados en las sesiones MCP incluso para usuarios con exenciones o permisos de desenmascarado. La cobertura depende del motor: donde Bytebase no enmascara, esto no cambia nada. La consola no se ve afectada.","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."},+ "masking-pending": {+ "applied": "Esta política se guardará con las exenciones de enmascaramiento aplicadas.",+ "ignored": "Esta política se guardará con las exenciones de enmascaramiento ignoradas."+ },"mode": {"disabled": {"best-for": "Ideal para: mantener MCP apagado hasta que esté listo para activarlo.",+ "caption": "Ninguna sesión conecta","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.",+ "caption": "Explorar y consultar","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.",+ "caption": "Cambiar datos y esquemas","title": "Lectura y escritura"}},@@ -2723,7 +2782,8 @@},"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.",+ "tightening": "Se aplica a la siguiente solicitud de cada sesión en curso.",+ "tightening-change": "{{from}} → {{to}} se aplica a la siguiente solicitud de cada sesión en curso.","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.",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex dd4c8efbc9..8a4b58e2f1 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1630,12 +1630,10 @@},"line": {"audit": "監査対象の操作には MCP タグが付き、監査ログの標準出力への出力が有効な場合、ポリシーが拒否したものは標準出力に出力されます",- "capped": "上限はあなた自身の Bytebase 権限",+ "capped-read-only": "上限はあなた自身の Bytebase 権限と、Bytebase が各データベースエンジンで確認できる範囲。ステートメントが読み取りだと示せないエンジンでは、クエリは一切実行されません",+ "capped-read-write": "上限はあなた自身の Bytebase 権限と、Bytebase が各データベースエンジンおよび各操作にどこまで対応しているか","masking": "あなたのマスキング適用除外はこのセッションには適用されません",- "no-write": "データやスキーマの変更はできない",- "read": "スキーマを調べ、読み取り専用のクエリを実行する",- "workflow": "イシュー・プラン・ロールアウトの作成、およびクエリ結果のエクスポート",- "write": "あなたの権限の範囲でデータとスキーマを変更する"+ "no-write": "変更・ロールアウト・エクスポート・データベース管理はできない"},"title": "このセッションでできること","undisclosed": {@@ -2671,12 +2669,8 @@"description": "IM 連携は、特定のイシューイベントについてユーザーにダイレクトメッセージをプッシュするために使用されます。プロジェクト Webhook と連携して動作します。"},"mcp": {- "auth": {- "description": "初回接続時に OAuth 認証が必要です。適切な Bytebase 権限があることを確認してください。",- "title": "認証が必要"- },"connect": {- "description": "Bytebase を AI クライアントに追加し、ブラウザーでアクセスを承認して、質問を始めてください。",+ "description": "Bytebase を AI クライアントに追加すれば、すぐに質問を始められます。初回接続時にはブラウザーでサインインし、アクセスを承認します。","desktop-note": "Claude Desktop はリモートサーバーを設定ファイルではなく Claude アカウントから読み込みます。claude.ai の Customize > Connectors でこの URL をカスタムコネクタとして追加すると、Claude Desktop に表示されます。","json-note": "これは mcpServers 形式です。クライアントごとに設定形式が異なります。たとえば VS Code は独自の mcp.json で servers を使うため、その場合は VS Code タブを使ってください。","title": "クライアントを接続"@@ -2687,33 +2681,98 @@"example": "Bytebase インスタンス内のすべてのプロジェクトをリストする","title": "最初のプロンプト"},+ "ladder": {+ "disabled": "何も許可されません。MCP セッションは接続できません。",+ "floor": {+ "label": "どのモードでも決してできないこと:",+ "text": "Issue の承認、ワークスペースの管理、認証情報の取り扱い、Admin モードのセッションの開始、他人のクエリ履歴の閲覧。"+ },+ "heading": "{{mode}} で許可されること",+ "hide-details": "詳細を隠す",+ "mark": {+ "allowed": "許可",+ "refused": "不許可"+ },+ "row": {+ "export": {+ "details": "結果をファイルとしてダウンロード。データが Bytebase の外に出ます",+ "title": "クエリ結果をエクスポートする"+ },+ "manage": {+ "details": "インスタンスとデータベースの同期 · データベースの設定とラベル · データベースをプロジェクト間で移動 · データベースグループ · 保存済みクエリ",+ "title": "データベースの運用設定を管理する"+ },+ "propose": {+ "details": "シートの作成 · Plan と Issue の作成・編集 · プランチェックとレビューの実行 · リリースの作成・削除・復元 · リビジョンの作成・削除 · スキーマ差分の生成。エージェントが自分の変更を承認することはありません。人の承認が必要かどうかはプロジェクトの承認ポリシーが決めます",+ "title": "変更を提案する"+ },+ "read-data": {+ "details": "読み取り専用のクエリを実行 · 読み取り専用では、すべてのステートメントがデータを返す読み取りだと確認できない限りリクエスト全体を拒否します。どこまで確認できるかはエンジンによって異なり、どのステートメントも読み取りだと確認できないエンジンもあります · 自分のクエリ履歴 · アクセス権のある保存済みクエリとシート",+ "title": "クエリを実行してデータを読み取る"+ },+ "read-schemas": {+ "details": "スキーマ · データベースとインスタンス · プロジェクトとデータベースグループ · カタログ・変更履歴・リビジョン · SQL レビュー設定 · 自分のセッションとワークスペースの情報",+ "title": "スキーマとメタデータの読み取り"+ },+ "read-workflow": {+ "details": "Issue とコメント · Plan とプランチェック · ロールアウト・タスク実行・ログ · リリース · ロールバックのプレビュー",+ "title": "変更ワークフローの読み取り"+ },+ "run-rollouts": {+ "details": "ロールアウトの作成 · プロジェクトの承認ポリシーのもとでタスクを実行・スキップ・キャンセル",+ "title": "ロールアウトとタスクを実行する"+ },+ "run-statements": {+ "details": "クエリを通じた INSERT・UPDATE・DELETE・CREATE・ALTER・DROP。エンジンとそのユーザー自身の権限が許す範囲で行われます",+ "title": "DML と DDL のステートメントを実行する"+ }+ },+ "show-details": "詳細を表示",+ "stops": {+ "read": "読み取り専用はここまで",+ "write": "読み書きはここまで"+ },+ "summary": {+ "read-only": "スキーマ・データ・変更ワークフローの読み取り。読み取りだと確認できないものを含むリクエストは拒否され、エクスポートもできません",+ "read-write": "スキーマ・データ・変更ワークフローの読み取り。提案・実行・エクスポート・管理"+ },+ "tier": {+ "read": "読み取り",+ "write": "書き込み"+ }+ },"policy": {- "audit": "監査ログの標準出力への出力が有効な場合、MCP ポリシーによる拒否は標準出力に出力されます。",- "description": "このワークスペースで MCP セッションが実行できる操作の上限です。各セッションは接続ユーザー自身の権限によってもさらに制限されます。",+ "current": "現在のポリシー:{{mode}}",+ "description": "このワークスペースで MCP セッションが実行できる操作の上限です。各セッションは接続ユーザー自身の権限によっても制限され、監査ログの標準出力への出力が有効な場合、ポリシーによる拒否は標準出力に出力されます。","edit": "ポリシーを編集",- "in-force": "適用中","loading": "アクセスポリシーを読み込んでいます…","masking": {"badge": "適用除外を無視中",- "description": "MCP セッションではマスクされたデータがマスクされたままになります。ユーザーに付与されたマスキングの適用除外も、アクセスグラントに伴うマスク解除も、その MCP リクエストには適用されなくなります。同じユーザーでも Bytebase コンソールでは影響を受けません。",- "limits": "マスキングの適用範囲はエンジンによって異なります。Bytebase がマスクしないエンジン、または適用除外を参照せずにマスクするエンジンでは、この設定は何も変えません。",+ "badge-disabled": "マスキング適用除外を無視 — MCP は無効",+ "badge-unlicensed": "マスキング適用除外を無視 — マスキングは未ライセンス",+ "description": "有効にすると、適用除外やマスク解除の権限を持つユーザーであっても、MCP セッションではマスクされたデータがマスクされたままになります。範囲はエンジンによって異なり、Bytebase がマスクしないところでは何も変わりません。コンソールには影響しません。","title": "マスキングの適用除外を無視する","unavailable": "このワークスペースではデータマスキングのライセンスがないため、この設定にかかわらず何もマスクされません。"},+ "masking-pending": {+ "applied": "このポリシーは、マスキング適用除外を有効にしたまま保存されます。",+ "ignored": "このポリシーは、マスキング適用除外を無視した状態で保存されます。"+ },"mode": {"disabled": {"best-for": "適する場面:有効にする準備が整うまで MCP をオフにしておきたいとき。",+ "caption": "セッションは接続不可","description": "このワークスペースにはどの MCP セッションも接続できません。","title": "無効"},"read-only": {"best-for": "適する場面:SQL を書かない人も含めた、データの照会と探索。",- "description": "セッションはスキーマを調べ、読み取り専用のクエリを実行できます。Bytebase は実行前にすべてのステートメントを分類し、読み取りでないものが 1 つでもあればリクエスト全体を拒否します。エンジンのドライバーが対応していれば、データベースセッション自体も読み取り専用で開きます。どこまで踏み込めるかはエンジンによって異なります。",+ "caption": "探索と照会","title": "読み取り専用"},"read-write": {"best-for": "適する場面:AI エージェント経由でのデータベース変更。各ユーザー自身の権限による制限は残ります。",- "description": "セッションはデータやスキーマの変更も行えます。範囲は接続ユーザー自身の権限までです。",+ "caption": "データとスキーマの変更","title": "読み書き"}},@@ -2723,7 +2782,8 @@},"save": "ポリシーを保存","saved": "ポリシーを保存しました。{{mode}} はすべてのセッションの次のリクエストから適用されます。",- "tightening": "上限の変更は、実行中のすべてのセッションの次のリクエストから適用されます。エージェントがすでに許可された処理は最後まで実行されます。",+ "tightening": "実行中のすべてのセッションの次のリクエストから適用されます。",+ "tightening-change": "{{from}} → {{to}} は、実行中のすべてのセッションの次のリクエストから適用されます。","title": "アクセスポリシー","unreadable": {"description": "このワークスペースには、このビルドが解釈できない機能レベルの値が保存されています。MCP 接続はすべて拒否されています。モードを選択して保存し、修正してください。",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex c146488fb5..57d5f22919 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1630,12 +1630,10 @@},"line": {"audit": "Hành động được kiểm toán mang nhãn MCP, và những gì chính sách từ chối được ghi vào đầu ra chuẩn khi bật ghi nhật ký kiểm toán vào đầu ra chuẩn",- "capped": "Giới hạn bởi chính quyền Bytebase của bạn",+ "capped-read-only": "Giới hạn bởi quyền Bytebase của chính bạn, và bởi những gì Bytebase có thể kiểm tra trên từng engine — nơi không thể chứng minh một câu lệnh là đọc, không truy vấn nào chạy",+ "capped-read-write": "Giới hạn bởi quyền Bytebase của chính bạn và bởi mức hỗ trợ của Bytebase cho từng loại cơ sở dữ liệu và từng thao tác","masking": "Các miễn trừ che dữ liệu của bạn không áp dụng cho phiên này",- "no-write": "Không thay đổi dữ liệu hay lược đồ",- "read": "Khám phá lược đồ và chạy truy vấn chỉ đọc",- "workflow": "Tạo vấn đề, kế hoạch và triển khai, và xuất kết quả truy vấn",- "write": "Thay đổi dữ liệu và lược đồ trong phạm vi quyền của bạn"+ "no-write": "Không thay đổi, triển khai, xuất dữ liệu hay quản trị cơ sở dữ liệu"},"title": "Phiên này có thể","undisclosed": {@@ -2671,12 +2669,8 @@"description": "Tích hợp IM sẽ được sử dụng để đẩy tin nhắn trực tiếp đến người dùng cho các sự kiện vấn đề cụ thể. Hoạt động với webhook của dự án."},"mcp": {- "auth": {- "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"- },"connect": {- "description": "Thêm Bytebase vào client AI của bạn, phê duyệt truy cập trong trình duyệt, rồi bắt đầu hỏi.",+ "description": "Thêm Bytebase vào ứng dụng AI của bạn và bắt đầu hỏi. Ở lần kết nối đầu tiên, bạn đăng nhập và phê duyệt quyền truy cập trong trình duyệt.","desktop-note": "Claude Desktop đọc máy chủ từ xa từ tài khoản Claude của bạn, không phải từ tệp cấu hình. Hãy thêm URL này làm trình kết nối tùy chỉnh tại Customize > Connectors trên claude.ai, sau đó nó sẽ xuất hiện trong Claude Desktop.","json-note": "Đây là định dạng mcpServers. Mỗi client có định dạng cấu hình khác nhau: ví dụ VS Code dùng servers trong mcp.json của nó, nên hãy dùng tab VS Code cho trường hợp đó.","title": "Kết nối một client"@@ -2687,33 +2681,98 @@"example": "Liệt kê tất cả các dự án trong phiên bản Bytebase của tôi","title": "Prompt đầu tiên của bạn"},+ "ladder": {+ "disabled": "Không cho phép gì; không phiên MCP nào có thể kết nối.",+ "floor": {+ "label": "Không bao giờ, ở mọi chế độ:",+ "text": "phê duyệt Issue, quản trị không gian làm việc, xử lý thông tin xác thực, mở phiên chế độ Admin, hoặc đọc lịch sử truy vấn của người khác."+ },+ "heading": "{{mode}} cho phép",+ "hide-details": "Ẩn chi tiết",+ "mark": {+ "allowed": "Được phép",+ "refused": "Không được phép"+ },+ "row": {+ "export": {+ "details": "Tải kết quả về dưới dạng tệp. Dữ liệu rời khỏi Bytebase",+ "title": "Xuất kết quả truy vấn"+ },+ "manage": {+ "details": "Đồng bộ phiên bản và cơ sở dữ liệu · Cài đặt và nhãn cơ sở dữ liệu · Chuyển cơ sở dữ liệu giữa các dự án · Nhóm cơ sở dữ liệu · Truy vấn đã lưu",+ "title": "Quản lý vận hành cơ sở dữ liệu"+ },+ "propose": {+ "details": "Tạo sheet · Tạo và sửa Plan và Issue · Chạy kiểm tra plan và rà soát · Tạo, xóa và khôi phục bản phát hành · Tạo và xóa bản sửa đổi · Tạo khác biệt lược đồ. Một tác nhân không bao giờ tự phê duyệt thay đổi của mình; chính sách phê duyệt của dự án quyết định liệu có cần người phê duyệt hay không",+ "title": "Đề xuất thay đổi"+ },+ "read-data": {+ "details": "Chạy truy vấn chỉ đọc · Ở chế độ Chỉ đọc, toàn bộ yêu cầu bị từ chối trừ khi mọi câu lệnh đều được chứng minh là một truy vấn đọc có trả về dữ liệu; mức độ kiểm tra tùy theo engine, và trên một số engine không câu lệnh nào có thể được chứng minh là đọc · Lịch sử truy vấn của riêng bạn · Truy vấn đã lưu và sheet mà bạn có quyền truy cập",+ "title": "Đọc dữ liệu bằng cách chạy truy vấn"+ },+ "read-schemas": {+ "details": "Lược đồ · Cơ sở dữ liệu và phiên bản · Dự án và nhóm cơ sở dữ liệu · Danh mục, nhật ký thay đổi và bản sửa đổi · Cấu hình rà soát SQL · Thông tin phiên và không gian làm việc của chính bạn",+ "title": "Đọc lược đồ và siêu dữ liệu"+ },+ "read-workflow": {+ "details": "Issue và bình luận · Plan và kiểm tra plan · Triển khai, lần chạy tác vụ và nhật ký · Bản phát hành · Xem trước khôi phục",+ "title": "Đọc quy trình thay đổi"+ },+ "run-rollouts": {+ "details": "Tạo một triển khai · Chạy, bỏ qua hoặc hủy các tác vụ của nó, theo chính sách phê duyệt của dự án",+ "title": "Chạy triển khai và tác vụ"+ },+ "run-statements": {+ "details": "INSERT, UPDATE, DELETE, CREATE, ALTER, DROP qua truy vấn, trong phạm vi engine và quyền của chính người dùng cho phép",+ "title": "Chạy câu lệnh DML và DDL"+ }+ },+ "show-details": "Hiện chi tiết",+ "stops": {+ "read": "Chỉ đọc dừng ở đây",+ "write": "Đọc và ghi dừng ở đây"+ },+ "summary": {+ "read-only": "Đọc lược đồ, dữ liệu và quy trình thay đổi; yêu cầu chứa bất kỳ thứ gì không thể chứng minh là đọc đều bị từ chối, và không xuất được gì",+ "read-write": "Đọc lược đồ, dữ liệu và quy trình thay đổi; đề xuất, chạy, xuất và quản lý"+ },+ "tier": {+ "read": "đọc",+ "write": "ghi"+ }+ },"policy": {- "audit": "Các lần từ chối theo chính sách MCP được ghi vào đầu ra chuẩn khi bật ghi nhật ký kiểm toán vào đầu ra chuẩ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.",+ "current": "Chính sách hiện tại: {{mode}}",+ "description": "Mức tối đa mà bất kỳ phiên MCP nào có thể làm ở đây. Các phiên còn bị giới hạn bởi quyền của từng người dùng, và những lần từ chối theo chính sách được ghi vào đầu ra chuẩn khi bật ghi nhật ký kiểm toán vào đầu ra chuẩn.","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ì.",+ "badge-disabled": "Bỏ qua miễn trừ che dữ liệu — MCP đang tắt",+ "badge-unlicensed": "Bỏ qua miễn trừ che dữ liệu — chưa có bản quyền che dữ liệu",+ "description": "Nếu bật, dữ liệu đã che vẫn được che trong phiên MCP kể cả với người dùng có miễn trừ hoặc quyền bỏ che. Phạm vi phụ thuộc vào engine: ở nơi Bytebase không che, điều này không thay đổi gì. Console không bị ảnh hưởng.","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."},+ "masking-pending": {+ "applied": "Chính sách này sẽ được lưu với các miễn trừ che dữ liệu được áp dụng.",+ "ignored": "Chính sách này sẽ được lưu với các miễn trừ che dữ liệu bị bỏ qua."+ },"mode": {"disabled": {"best-for": "Phù hợp khi: giữ MCP tắt cho tới khi bạn sẵn sàng bật.",+ "caption": "Không phiên nào kết nối","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ụ.",+ "caption": "Khám phá và truy vấn","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.",+ "caption": "Thay đổi dữ liệu và lược đồ","title": "Đọc và ghi"}},@@ -2723,7 +2782,8 @@},"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.",+ "tightening": "Áp dụng cho yêu cầu tiếp theo của mọi phiên đang chạy.",+ "tightening-change": "{{from}} → {{to}} áp dụng cho yêu cầu tiếp theo của mọi phiên đang chạy.","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.",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 673c99805d..065e96b45e 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1630,12 +1630,10 @@},"line": {"audit": "被审计的操作会带上 MCP 标记,启用审计日志输出到标准输出时,策略拒绝的操作会输出到标准输出",- "capped": "以你本人的 Bytebase 权限为上限",+ "capped-read-only": "上限取决于你自己的 Bytebase 权限,以及 Bytebase 在各数据库引擎上能确认的范围——在无法确认语句是读取的引擎上,任何查询都不会执行",+ "capped-read-write": "上限取决于你自己的 Bytebase 权限,以及 Bytebase 对每种数据库引擎和每种操作的支持程度","masking": "你的脱敏豁免对此会话不生效",- "no-write": "不能修改任何数据或模式",- "read": "浏览模式并执行只读查询",- "workflow": "创建工单、计划和发布,以及导出查询结果",- "write": "在你的权限范围内修改数据和模式"+ "no-write": "不能变更、部署、导出或管理数据库"},"title": "此会话可以","undisclosed": {@@ -2671,12 +2669,8 @@"description": "即时通讯集成用于针对特定工单事件向用户推送私信消息。需要与项目 webhook 配合使用。"},"mcp": {- "auth": {- "description": "首次连接需要 OAuth 身份验证。请确保您拥有相应的 Bytebase 权限。",- "title": "需要身份验证"- },"connect": {- "description": "将 Bytebase 添加到你的 AI 客户端,在浏览器中批准访问,然后开始提问。",+ "description": "把 Bytebase 添加到你的 AI 客户端就可以开始提问。首次连接时会在浏览器中登录并批准访问。","desktop-note": "Claude Desktop 从你的 Claude 账户读取远程服务器,而不是配置文件。请在 claude.ai 的 Customize > Connectors 中将此 URL 添加为自定义连接器,随后它会出现在 Claude Desktop 中。","json-note": "这是 mcpServers 格式。各客户端的配置格式并不相同:例如 VS Code 在自己的 mcp.json 中使用 servers,此时请改用 VS Code 标签页。","title": "连接客户端"@@ -2687,33 +2681,98 @@"example": "列出我的 Bytebase 实例中的所有项目","title": "您的第一个提示"},+ "ladder": {+ "disabled": "不允许任何操作;MCP 会话无法连接。",+ "floor": {+ "label": "在任何模式下都不允许:",+ "text": "审批工单、管理工作空间、处理凭据、开启 Admin 模式会话、查看他人的查询历史。"+ },+ "heading": "{{mode}} 允许",+ "hide-details": "隐藏详情",+ "mark": {+ "allowed": "允许",+ "refused": "不允许"+ },+ "row": {+ "export": {+ "details": "将结果下载为文件。数据会离开 Bytebase",+ "title": "导出查询结果"+ },+ "manage": {+ "details": "同步实例和数据库 · 数据库设置和标签 · 在项目之间移动数据库 · 数据库组 · 已保存的查询",+ "title": "管理数据库日常维护"+ },+ "propose": {+ "details": "创建工作表 · 创建和编辑 Plan 与工单 · 执行计划检查和审核 · 创建、删除和恢复发布 · 创建和删除修订 · 生成模式差异。智能体绝不会审批自己的变更;是否需要人来审批由项目的审批策略决定",+ "title": "提议变更"+ },+ "read-data": {+ "details": "执行只读查询 · 在只读模式下,除非每条语句都能被确认为返回数据的读取,否则整体拒绝该请求;能确认到多深取决于引擎,在部分引擎上没有任何语句能被确认为读取 · 你自己的查询历史 · 你有权访问的已保存查询和工作表",+ "title": "通过执行查询读取数据"+ },+ "read-schemas": {+ "details": "模式 · 数据库和实例 · 项目和数据库组 · 目录、变更历史和修订 · SQL 审核配置 · 你自己的会话和工作空间信息",+ "title": "读取模式和元数据"+ },+ "read-workflow": {+ "details": "工单和评论 · Plan 和计划检查 · 部署、任务运行和日志 · 发布 · 回滚预览",+ "title": "读取变更流程"+ },+ "run-rollouts": {+ "details": "创建部署 · 在项目审批策略之下执行、跳过或取消其任务",+ "title": "执行部署和任务"+ },+ "run-statements": {+ "details": "通过查询执行 INSERT、UPDATE、DELETE、CREATE、ALTER、DROP,以引擎和该用户自身权限允许的范围为限",+ "title": "执行 DML 和 DDL 语句"+ }+ },+ "show-details": "显示详情",+ "stops": {+ "read": "只读到此为止",+ "write": "读写到此为止"+ },+ "summary": {+ "read-only": "读取模式、数据和变更流程;只要请求中含有无法被确认为读取的内容就会被拒绝,也不能导出",+ "read-write": "读取模式、数据和变更流程;提议、执行、导出和管理"+ },+ "tier": {+ "read": "读取",+ "write": "写入"+ }+ },"policy": {- "audit": "启用审计日志输出到标准输出时,MCP 策略拒绝会输出到标准输出。",- "description": "本工作空间中任何 MCP 会话所能执行操作的上限。每个会话还会受到连接用户自身权限的限制。",+ "current": "当前策略:{{mode}}",+ "description": "MCP 会话在此最多能做的事。每个会话还受各用户自身权限的限制;启用审计日志输出到标准输出时,策略拒绝会输出到标准输出。","edit": "编辑策略",- "in-force": "当前生效","loading": "正在读取访问策略…","masking": {"badge": "已忽略脱敏豁免",- "description": "在 MCP 会话中,脱敏数据保持脱敏。授予用户的脱敏豁免,以及访问授权所携带的解除脱敏,都不再对其 MCP 请求生效。同一用户在 Bytebase 控制台中不受影响。",- "limits": "脱敏覆盖范围取决于引擎。若 Bytebase 在该引擎上不做脱敏,或者脱敏时不查询豁免,此项不产生任何变化。",+ "badge-disabled": "已忽略脱敏豁免 — MCP 已关闭",+ "badge-unlicensed": "已忽略脱敏豁免 — 未授权脱敏功能",+ "description": "启用后,即使用户拥有豁免或解除脱敏的授权,在 MCP 会话中被脱敏的数据仍保持脱敏。覆盖范围取决于引擎:Bytebase 本来就不脱敏的地方,这不会有任何改变。控制台不受影响。","title": "忽略脱敏豁免","unavailable": "本工作空间未授权数据脱敏功能,因此无论此项如何设置都不会脱敏。"},+ "masking-pending": {+ "applied": "此策略将在保留脱敏豁免的状态下保存。",+ "ignored": "此策略将在忽略脱敏豁免的状态下保存。"+ },"mode": {"disabled": {"best-for": "适用于:在准备好开启之前先关闭 MCP。",+ "caption": "会话无法连接","description": "任何 MCP 会话都无法连接到本工作空间。","title": "禁用"},"read-only": {"best-for": "适用于:查询和探索数据,包括不写 SQL 的人。",- "description": "会话可以浏览模式并执行只读查询。Bytebase 会在每条语句执行前对其分类,只要其中有一条不是读取,就整体拒绝该请求。若引擎的驱动支持,还会以只读方式打开数据库会话。具体强度因引擎而异。",+ "caption": "探索与查询","title": "只读"},"read-write": {"best-for": "适用于:通过 AI 代理执行数据库变更,仍受每位用户自身权限的限制。",- "description": "会话还可以修改数据和模式,范围以连接用户自身的权限为限。",+ "caption": "变更数据和模式","title": "读写"}},@@ -2723,7 +2782,8 @@},"save": "保存策略","saved": "策略已保存。{{mode}} 将对每个会话的下一次请求生效。",- "tightening": "上限变更会对每个运行中会话的下一次请求生效。代理已被放行的工作会继续执行完毕。",+ "tightening": "从每个运行中会话的下一个请求起生效。",+ "tightening-change": "{{from}} → {{to}} 从每个运行中会话的下一个请求起生效。","title": "访问策略","unreadable": {"description": "此工作区存储的能力值是当前构建无法理解的。所有 MCP 连接都会被拒绝。请选择一种模式并保存以修正。",diff --git a/frontend/src/routes/auth/MCPConsentCeiling.tsx b/frontend/src/routes/auth/MCPConsentCeiling.tsxindex 0a03c63d3a..c977e0ec60 100644--- a/frontend/src/routes/auth/MCPConsentCeiling.tsx+++ b/frontend/src/routes/auth/MCPConsentCeiling.tsx@@ -1,21 +1,16 @@-import { Check, EyeOff, ScrollText, X } from "lucide-react";-import type { ReactNode } from "react";+import { Check, EyeOff, Info, ScrollText, X } from "lucide-react";import { useTranslation } from "react-i18next";+import { mcpRowKey, servedRows } from "@/components/mcp/mcpCapabilityRows";+import type { MCPServingMode } from "@/components/mcp/mcpPolicy";import { Alert } from "@/components/ui/alert";-import { Badge } from "@/components/ui/badge";-import {- type MCPSetting,- MCPSetting_Capability,-} from "@/types/proto-es/v1/setting_service_pb";--interface Line {- readonly key: string;- readonly icon: ReactNode;- readonly text: string;-}+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";+import type { MCPConsentLine } from "./MCPConsentPolicyCard";+import { MCPConsentPolicyCard } from "./MCPConsentPolicyCard";interface Props {- readonly setting: MCPSetting;+ /** The ceiling this session runs at, narrowed by the caller. */+ readonly mode: MCPServingMode;+ readonly ignoreMaskingExemptions: boolean;readonly dataMaskingAvailable: boolean;}@@ -23,56 +18,57 @@ interface Props {* What the workspace's ceiling lets this session do, shown before the person* approves rather than after.*- * The same ceiling refuses the POST server-side, so this page is the richer- * render of a decision the backend makes either way — never the decision- * itself.+ * The capability rows are the settings page's, from the same table, so the+ * wording an admin chose the policy by is the wording the person approving+ * reads. The same ceiling refuses the POST server-side, so this page is the+ * richer render of a decision the backend makes either way — never the+ * decision itself.*/-export function MCPConsentCeiling({ setting, dataMaskingAvailable }: Props) {+export function MCPConsentCeiling({+ mode,+ ignoreMaskingExemptions,+ dataMaskingAvailable,+}: Props) {const { t } = useTranslation();- const readWrite = setting.capability === MCPSetting_Capability.READ_WRITE;- const modeKey = readWrite ? "read-write" : "read-only";- const modeLabel = t(`settings.mcp.policy.mode.${modeKey}.title`);-- const lines: Line[] = [- {- key: "read",+ const readWrite = mode === MCPSetting_Capability.READ_WRITE;+ const lines: MCPConsentLine[] = [+ ...servedRows(mode).map((row) => ({+ key: row.id,icon: <Check className="size-4 text-success" />,- text: t("oauth2.consent.mcp.line.read"),- },- readWrite- ? {- key: "write",- icon: <Check className="size-4 text-success" />,- text: t("oauth2.consent.mcp.line.write"),- }- : {- key: "no-write",- icon: <X className="size-4 text-error" />,- text: t("oauth2.consent.mcp.line.no-write"),- },- // The WRITE class is not only data and schema: CreateIssue, CreatePlan,- // CreateRollout, BatchRunTasks, Export and the saved-query methods all- // carry it, so approving read-write approves workflow and egress too.+ mark: t("settings.mcp.ladder.mark.allowed"),+ text: t(mcpRowKey(row, "title")),+ })),+ // One line for the whole unserved tier rather than five muted rows: this+ // screen is an approval, not a comparison, and the person is deciding+ // about what the session gains....(readWrite- ? [+ ? []+ : [{- key: "workflow",- icon: <Check className="size-4 text-success" />,- text: t("oauth2.consent.mcp.line.workflow"),+ // No mark: the sentence states the prohibition itself, and+ // prefixing "Not allowed" would double the negative.+ key: "no-write",+ icon: <X className="size-4 text-error" />,+ text: t("oauth2.consent.mcp.line.no-write"),},- ]- : []),+ ]),+ // A bound, not a grant: neutral glyph and no mark, so it is not counted+ // among the rows above it. Scoped by mode because Read-only's statement+ // clamp is one rule with one consequence, while Read-write's answer varies+ // by engine and by operation — so that line states the bound and stops.{key: "capped",- icon: <Check className="size-4 text-success" />,- text: t("oauth2.consent.mcp.line.capped"),+ icon: <Info className="size-4 text-control-light" />,+ text: readWrite+ ? t("oauth2.consent.mcp.line.capped-read-write")+ : t("oauth2.consent.mcp.line.capped-read-only"),},// Both halves, because the line promises a restriction. The toggle// withholds unmasking exemptions from MCP sessions, which changes nothing// where masking does not run at all — asserting it there would tell the// person approving that their data is covered when it is not.- ...(setting.ignoreMaskingExemptions && dataMaskingAvailable+ ...(ignoreMaskingExemptions && dataMaskingAvailable? [{key: "masking",@@ -90,22 +86,11 @@ export function MCPConsentCeiling({ setting, dataMaskingAvailable }: Props) {return (<div className="flex flex-col gap-3">- <div className="bg-control-bg rounded-sm p-4 flex flex-col gap-3">- <div className="flex items-center justify-between gap-x-2">- <p className="text-sm text-control-light">- {t("oauth2.consent.mcp.title")}- </p>- <Badge variant={readWrite ? "warning" : "success"}>{modeLabel}</Badge>- </div>- <ul className="text-sm text-main flex flex-col gap-2">- {lines.map((line) => (- <li key={line.key} className="flex items-start gap-2">- <span className="mt-0.5 shrink-0">{line.icon}</span>- <span>{line.text}</span>- </li>- ))}- </ul>- </div>+ <MCPConsentPolicyCard+ label={t("oauth2.consent.mcp.title")}+ mode={mode}+ lines={lines}+ />{readWrite && (<Alertdiff --git a/frontend/src/routes/auth/MCPConsentDisabled.tsx b/frontend/src/routes/auth/MCPConsentDisabled.tsxindex d5b4729832..d0c9758791 100644--- a/frontend/src/routes/auth/MCPConsentDisabled.tsx+++ b/frontend/src/routes/auth/MCPConsentDisabled.tsx@@ -1,8 +1,9 @@import { ScrollText, X } from "lucide-react";import type { ReactNode } from "react";import { useTranslation } from "react-i18next";-import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";+import { MCPConsentPolicyCard } from "./MCPConsentPolicyCard";interface Props {readonly workspaceTitle: string;@@ -50,26 +51,22 @@ export function MCPConsentDisabled({{workspaceCard}- <div className="bg-control-bg rounded-sm p-4 flex flex-col gap-3">- <div className="flex items-center justify-between gap-x-2">- <p className="text-sm text-control-light">- {t("oauth2.consent.mcp.disabled.policy-label")}- </p>- <Badge variant="destructive">- {t("settings.mcp.policy.mode.disabled.title")}- </Badge>- </div>- <ul className="text-sm text-main flex flex-col gap-2">- <li className="flex items-start gap-2">- <X className="mt-0.5 size-4 shrink-0 text-error" />- <span>{t("oauth2.consent.mcp.disabled.line.no-session")}</span>- </li>- <li className="flex items-start gap-2">- <ScrollText className="mt-0.5 size-4 shrink-0 text-control-light" />- <span>{t("oauth2.consent.mcp.disabled.line.recorded")}</span>- </li>- </ul>- </div>+ <MCPConsentPolicyCard+ label={t("oauth2.consent.mcp.disabled.policy-label")}+ mode={MCPSetting_Capability.DISABLED}+ lines={[+ {+ key: "no-session",+ icon: <X className="size-4 text-error" />,+ text: t("oauth2.consent.mcp.disabled.line.no-session"),+ },+ {+ key: "recorded",+ icon: <ScrollText className="size-4 text-control-light" />,+ text: t("oauth2.consent.mcp.disabled.line.recorded"),+ },+ ]}+ /><div className="flex flex-col gap-2"><Buttondiff --git a/frontend/src/routes/auth/MCPConsentPolicyCard.tsx b/frontend/src/routes/auth/MCPConsentPolicyCard.tsxnew file mode 100644index 0000000000..97392116d5--- /dev/null+++ b/frontend/src/routes/auth/MCPConsentPolicyCard.tsx@@ -0,0 +1,50 @@+import type { ReactNode } from "react";+import { MCPModeBadge } from "@/components/mcp/MCPModeBadge";+import type { MCPMode } from "@/components/mcp/mcpPolicy";++export interface MCPConsentLine {+ readonly key: string;+ readonly icon: ReactNode;+ /**+ * What the mark means, for a reader who cannot see it. Allowed and refused+ * are otherwise carried by a green check against a red cross — color and+ * glyph, both visual — on the screen where someone decides whether to hand an+ * agent access.+ */+ readonly mark?: string;+ readonly text: string;+}++interface Props {+ readonly label: string;+ /** Omitted by the panel for a ceiling this build has no name for. */+ readonly mode?: MCPMode;+ readonly lines: readonly MCPConsentLine[];+}++/**+ * The panel each consent screen shows: the workspace's policy, and what it+ * means for the session being approved. Shared so the three screens cannot+ * drift apart.+ */+export function MCPConsentPolicyCard({ label, mode, lines }: Props) {+ return (+ <div className="bg-control-bg rounded-sm p-4 flex flex-col gap-3">+ <div className="flex items-center justify-between gap-x-2">+ <p className="text-sm text-control-light">{label}</p>+ {mode !== undefined && <MCPModeBadge mode={mode} />}+ </div>+ <ul role="list" className="text-sm text-main flex flex-col gap-2">+ {lines.map((line) => (+ <li key={line.key} className="flex items-start gap-2">+ <span className="mt-0.5 shrink-0" aria-hidden="true">+ {line.icon}+ </span>+ {line.mark && <span className="sr-only">{line.mark}</span>}+ <span>{line.text}</span>+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/frontend/src/routes/auth/MCPConsentUndisclosed.tsx b/frontend/src/routes/auth/MCPConsentUndisclosed.tsxindex caf353656d..e5dfb3cc69 100644--- a/frontend/src/routes/auth/MCPConsentUndisclosed.tsx+++ b/frontend/src/routes/auth/MCPConsentUndisclosed.tsx@@ -3,6 +3,7 @@ import type { ReactNode } from "react";import { useTranslation } from "react-i18next";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";+import { MCPConsentPolicyCard } from "./MCPConsentPolicyCard";/** Why this page cannot say what approving would grant. */export type UndisclosedReason = "unknown" | "undisclosable";@@ -56,19 +57,17 @@ export function MCPConsentUndisclosed({inside it, the way MCPConsentCeiling places its write caution. */}<Alert variant="error" description={t(`${key}.line`)} />- <div className="bg-control-bg rounded-sm p-4 flex flex-col gap-3">- <p className="text-sm text-control-light">- {t("oauth2.consent.mcp.undisclosed.policy-label")}- </p>- <ul className="text-sm text-main flex flex-col gap-2">- <li className="flex items-start gap-2">- <ScrollText className="mt-0.5 size-4 shrink-0 text-control-light" />- <span>- {t("oauth2.consent.mcp.undisclosed.line.nothing-approved")}- </span>- </li>- </ul>- </div>+ {/* No mode: this panel exists because there is no ceiling to name. */}+ <MCPConsentPolicyCard+ label={t("oauth2.consent.mcp.undisclosed.policy-label")}+ lines={[+ {+ key: "nothing-approved",+ icon: <ScrollText className="size-4 text-control-light" />,+ text: t("oauth2.consent.mcp.undisclosed.line.nothing-approved"),+ },+ ]}+ /><div className="flex gap-x-2"><Buttondiff --git a/frontend/src/routes/auth/OAuth2ConsentPage.test.tsx b/frontend/src/routes/auth/OAuth2ConsentPage.test.tsxindex 1a252460ea..7e044f7f26 100644--- a/frontend/src/routes/auth/OAuth2ConsentPage.test.tsx+++ b/frontend/src/routes/auth/OAuth2ConsentPage.test.tsx@@ -546,7 +546,7 @@ describe("OAuth2ConsentPage", () => {expect(mocks.refreshServerInfo).toHaveBeenCalledOnce();expect(mocks.loadServerInfo).not.toHaveBeenCalled();- expect(container.textContent).toContain("oauth2.consent.mcp.line.write");+ expect(container.textContent).toContain("settings.mcp.ladder.row.run-statements.title");unmount();});@@ -602,9 +602,9 @@ describe("OAuth2ConsentPage", () => {capability: 3,ignoreMaskingExemptions: false,});- expect(container.textContent).toContain("oauth2.consent.mcp.line.read");+ expect(container.textContent).toContain("settings.mcp.ladder.row.read-schemas.title");expect(container.textContent).toContain("oauth2.consent.mcp.line.no-write");- expect(container.textContent).not.toContain("oauth2.consent.mcp.line.write");+ expect(container.textContent).not.toContain("settings.mcp.ladder.row.run-statements.title");// The masking line is the toggle's, not the ceiling's.expect(container.textContent).not.toContain("oauth2.consent.mcp.line.masking"@@ -613,12 +613,48 @@ describe("OAuth2ConsentPage", () => {unmount();});+ // The row titles carry no caveats, so this bound is the only thing limiting+ // the check marks. It has to be the RIGHT bound: the statement clamp it+ // describes runs only under Read-only, so claiming it under Read-write would+ // promise an approver that no query runs where writes execute unverified.+ test("each ceiling states the bound that holds for it", async () => {+ const readOnly = await renderWithCeiling({+ capability: 3,+ ignoreMaskingExemptions: false,+ });+ expect(readOnly.container.textContent).toContain(+ "oauth2.consent.mcp.line.capped-read-only"+ );+ expect(readOnly.container.textContent).not.toContain(+ "oauth2.consent.mcp.line.capped-read-write"+ );+ expect(readOnly.container.textContent).toContain(+ "oauth2.consent.mcp.line.audit"+ );+ readOnly.unmount();++ const readWrite = await renderWithCeiling({+ capability: 4,+ ignoreMaskingExemptions: false,+ });+ expect(readWrite.container.textContent).toContain(+ "oauth2.consent.mcp.line.capped-read-write"+ );+ expect(readWrite.container.textContent).not.toContain(+ "oauth2.consent.mcp.line.capped-read-only"+ );+ expect(readWrite.container.textContent).toContain(+ "oauth2.consent.mcp.line.audit"+ );+ readWrite.unmount();+ });+test("a read-write ceiling adds the write line and the caution", async () => {const { container, unmount } = await renderWithCeiling({capability: 4,ignoreMaskingExemptions: true,});- expect(container.textContent).toContain("oauth2.consent.mcp.line.write");+ expect(container.textContent).toContain("settings.mcp.ladder.row.run-statements.title");expect(container.textContent).toContain("oauth2.consent.mcp.write-caution");expect(container.textContent).toContain("oauth2.consent.mcp.line.masking");unmount();@@ -635,7 +671,7 @@ describe("OAuth2ConsentPage", () => {ignoreMaskingExemptions: true,});// The rest of the card is unchanged, so this is the line and not the card.- expect(container.textContent).toContain("oauth2.consent.mcp.line.write");+ expect(container.textContent).toContain("settings.mcp.ladder.row.run-statements.title");expect(container.textContent).not.toContain("oauth2.consent.mcp.line.masking");@@ -699,16 +735,12 @@ describe("OAuth2ConsentPage", () => {unmount();});- // BOT-106, and the reason this is a blocker rather than a tidy-up. The page- // used to fall through to a generic "access your account" card with Allow- // live whenever actuator info lacked the MCP setting for ANY reason. The POST refuses a stored- // value nothing resolves, so that half was cosmetic; it refuses neither a- // transient failure nor a tier this bundle is merely too old to name. In both- // of those the POST reads the ceiling for itself, succeeds, and issues a grant- // against a card that never named the ceiling it was granting.- //- // A timeout arrives here the same way: the client throws, and the page cannot- // tell a deadline from a refusal, which is the whole point of failing closed.+ // Failing closed here is load-bearing. The POST refuses a stored value+ // nothing resolves, but it refuses neither a transient failure nor a tier+ // this bundle is too old to name; in both, it reads the ceiling for itself,+ // succeeds, and issues a grant against a card that never named what it was+ // granting. A timeout arrives the same way: the client throws, and the page+ // cannot tell a deadline from a refusal.test("a failed policy read offers no grant and can be retried", async () => {mocks.currentRoute.value.query = consentQuery();mocks.fetchImpl.mockResolvedValue({@@ -740,7 +772,7 @@ describe("OAuth2ConsentPage", () => {retry?.click();});await flushPromises();- expect(container.textContent).toContain("oauth2.consent.mcp.line.read");+ expect(container.textContent).toContain("settings.mcp.ladder.row.read-schemas.title");expect(container.textContent).toContain("common.allow");unmount();});diff --git a/frontend/src/routes/auth/OAuth2ConsentPage.tsx b/frontend/src/routes/auth/OAuth2ConsentPage.tsxindex f4d459570a..c1dea3d9f5 100644--- a/frontend/src/routes/auth/OAuth2ConsentPage.tsx+++ b/frontend/src/routes/auth/OAuth2ConsentPage.tsx@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";import { router } from "@/app/router";import { AUTH_SIGNIN_MODULE } from "@/app/router/handles";import { BytebaseLogo } from "@/components/BytebaseLogo";-import { readConsentCeiling } from "@/components/mcp/mcpPolicy";+import { isServingMode, readConsentCeiling } from "@/components/mcp/mcpPolicy";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import {@@ -16,10 +16,7 @@ import {} from "@/components/ui/select";import { useWorkspace } from "@/hooks/useAppState";import { useAppStore } from "@/stores/app";-import {- type MCPSetting,- MCPSetting_Capability,-} from "@/types/proto-es/v1/setting_service_pb";+import type { MCPSetting } from "@/types/proto-es/v1/setting_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import { MCPConsentCeiling } from "./MCPConsentCeiling";import { MCPConsentDisabled } from "./MCPConsentDisabled";@@ -322,7 +319,7 @@ export function OAuth2ConsentPage() {/>);}- if (ceiling.setting.capability === MCPSetting_Capability.DISABLED) {+ if (!isServingMode(ceiling.mode)) {return (<MCPConsentDisabledworkspaceTitle={@@ -346,7 +343,8 @@ export function OAuth2ConsentPage() {</div>{workspaceCard}<MCPConsentCeiling- setting={ceiling.setting}+ mode={ceiling.mode}+ ignoreMaskingExemptions={ceiling.ignoreMaskingExemptions}dataMaskingAvailable={dataMaskingAvailable}/><form method="POST" action={AUTHORIZE_URL}>diff --git a/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.test.tsx b/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.test.tsxindex 3ba8843097..63f8faacd7 100644--- a/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.test.tsx+++ b/frontend/src/routes/project/database-detail/panels/DatabaseCatalogPanel.test.tsx@@ -3,7 +3,14 @@ import type {InputHTMLAttributes,ReactNode,} from "react";-import { act, createContext, createElement, useContext } from "react";+import {+ act,+ Children,+ createContext,+ createElement,+ isValidElement,+ useContext,+} from "react";import { createRoot } from "react-dom/client";import { beforeEach, describe, expect, test, vi } from "vitest";import type { DatabaseCatalog } from "@/types/proto-es/v1/database_catalog_service_pb";@@ -514,6 +521,16 @@ vi.mock("@/components/ui/sheet", () => ({}));vi.mock("@/components/ui/select", () => {+ // A native <option> may hold only text, and items can render markup — a+ // semantic type's title over its masking effect — so the mock flattens it.+ const textOf = (node: ReactNode): string =>+ Children.toArray(node)+ .map((child) =>+ isValidElement<{ children?: ReactNode }>(child)+ ? textOf(child.props.children)+ : String(child)+ )+ .join("");const SelectContext = createContext<{value?: string;disabled?: boolean;@@ -570,7 +587,7 @@ vi.mock("@/components/ui/select", () => {}: {value: string;children: ReactNode;- }) => <option value={value}>{children}</option>,+ }) => <option value={value}>{textOf(children)}</option>,};});diff --git a/frontend/src/routes/workspace/MCPPage.tsx b/frontend/src/routes/workspace/MCPPage.tsxindex 66fe9e00ce..f608f98531 100644--- a/frontend/src/routes/workspace/MCPPage.tsx+++ b/frontend/src/routes/workspace/MCPPage.tsx@@ -1,7 +1,6 @@import { useMemo } from "react";import { useTranslation } from "react-i18next";import { ExternalUrlAlert } from "@/components/ExternalUrlAlert";-import { Alert } from "@/components/ui/alert";import { CopyButton } from "@/components/ui/copy-button";import { Input } from "@/components/ui/input";import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";@@ -99,13 +98,6 @@ export function MCPPage() {<MCPAccessPolicySection />- {/* Authentication Notice */}- <Alert- variant="info"- title={t("settings.mcp.auth.title")}- description={t("settings.mcp.auth.description")}- />-{/* Connect a client */}<div className="flex flex-col gap-y-3"><div className="flex flex-col gap-y-1">diff --git a/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsx b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsxindex 00a310ca02..e38f10adae 100644--- a/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsx+++ b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.test.tsx@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => ({dataMaskingAvailable: { value: true },permissionDisabled: { value: false },permissionGuard: vi.fn(),+ pushNotification: vi.fn(),}));vi.mock("@/hooks/useUnsavedChangesGuard", () => ({@@ -43,7 +44,7 @@ vi.mock("@/components/PermissionGuard", () => ({},}));-vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));+vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));vi.mock("@/stores/app", () => {const state = {@@ -61,7 +62,10 @@ vi.mock("@/stores/app", () => {});vi.mock("react-i18next", () => ({- useTranslation: () => ({ t: (key: string) => key }),+ useTranslation: () => ({+ t: (key: string, vars?: Record<string, string>) =>+ vars ? `${key}(${Object.values(vars).join(",")})` : key,+ }),initReactI18next: { type: "3rdParty", init: () => {} },}));@@ -84,16 +88,25 @@ const flush = () =>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 storePolicy = (+ capability: MCPSetting_Capability,+ ignoreMaskingExemptions = false+) => {+ mocks.serverInfo.value = { mcpSetting: { capability, ignoreMaskingExemptions } };+ mocks.loadServerInfo.mockResolvedValue(mocks.serverInfo.value);+ mocks.refreshServerInfo.mockResolvedValue(mocks.serverInfo.value);};+const maskingBadgeText = (container: HTMLElement) =>+ [...container.querySelectorAll("span")].find((node) =>+ node.textContent?.startsWith("settings.mcp.policy.masking.badge")+ )?.textContent;++const maskingSwitch = (container: HTMLElement) =>+ container.querySelector(+ '[aria-label="settings.mcp.policy.masking.title"]'+ ) as HTMLElement | null;+const clickText = (container: HTMLElement, text: string) => {const el = [...container.querySelectorAll("button, label")].find((n) =>n.textContent?.includes(text)@@ -107,14 +120,7 @@ beforeEach(async () => {vi.clearAllMocks();mocks.permissionDisabled.value = false;mocks.dataMaskingAvailable.value = true;- mocks.serverInfo.value = {- mcpSetting: {- capability: MCPSetting_Capability.READ_ONLY,- ignoreMaskingExemptions: false,- },- };- mocks.loadServerInfo.mockResolvedValue(mocks.serverInfo.value);- mocks.refreshServerInfo.mockResolvedValue(mocks.serverInfo.value);+ storePolicy(MCPSetting_Capability.READ_ONLY);mocks.upsertSetting.mockResolvedValue(undefined);({ MCPAccessPolicySection } = await import("./MCPAccessPolicySection"));});@@ -128,14 +134,12 @@ describe("MCPAccessPolicySection", () => {await flush();expect(mocks.loadServerInfo).toHaveBeenCalledOnce();- expect(container.textContent).toContain("settings.mcp.policy.in-force");+ expect(container.textContent).toContain(+ "settings.mcp.policy.mode.read-only.title"+ );unmount();});- // 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 />@@ -174,7 +178,9 @@ describe("MCPAccessPolicySection", () => {expect(container.textContent).toContain("settings.mcp.policy.read-failed.title");- expect(container.textContent).not.toContain("settings.mcp.policy.in-force");+ expect(container.textContent).not.toContain(+ "settings.mcp.policy.mode.read-only.title"+ );unmount();});@@ -197,12 +203,7 @@ describe("MCPAccessPolicySection", () => {});test("repairs an unspecified capability reported by actuator info", async () => {- mocks.serverInfo.value = {- mcpSetting: {- capability: MCPSetting_Capability.CAPABILITY_UNSPECIFIED,- ignoreMaskingExemptions: false,- },- };+ storePolicy(MCPSetting_Capability.CAPABILITY_UNSPECIFIED);const { container, render, unmount } = renderIntoContainer(<MCPAccessPolicySection />);@@ -212,7 +213,9 @@ describe("MCPAccessPolicySection", () => {expect(container.textContent).toContain("settings.mcp.policy.unreadable.title");- expect(container.textContent).not.toContain("settings.mcp.policy.in-force");+ expect(container.textContent).not.toContain(+ "settings.mcp.policy.mode.read-only.title"+ );clickText(container, "settings.mcp.policy.edit");await flush();@@ -239,7 +242,7 @@ describe("MCPAccessPolicySection", () => {});test("waits for actuator info before offering policy editing", async () => {- const pending = deferred<undefined>();+ const pending = Promise.withResolvers<undefined>();mocks.serverInfo.value = undefined;mocks.loadServerInfo.mockReturnValue(pending.promise);@@ -250,7 +253,9 @@ describe("MCPAccessPolicySection", () => {await flush();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.mode.read-only.title"+ );expect(container.textContent).not.toContain("settings.mcp.policy.edit");unmount();@@ -273,7 +278,7 @@ describe("MCPAccessPolicySection", () => {unmount();});- test("keeps policy-card content compact", async () => {+ test("the Best for line is shown once and follows the selection", async () => {const { container, render, unmount } = renderIntoContainer(<MCPAccessPolicySection />);@@ -282,68 +287,581 @@ describe("MCPAccessPolicySection", () => {clickText(container, "settings.mcp.policy.edit");await flush();- const bestForLines = [...container.querySelectorAll("p")].filter((line) =>- line.textContent?.includes(".best-for")+ const bestForLines = () =>+ [...container.querySelectorAll("p")].filter((line) =>+ line.textContent?.includes(".best-for")+ );+ expect(bestForLines()).toHaveLength(1);+ expect(bestForLines()[0]?.textContent).toBe(+ "settings.mcp.policy.mode.read-only.best-for");- expect(bestForLines).toHaveLength(3);- expect(bestForLines.every((line) => !line.classList.contains("mt-auto"))).toBe(- true++ clickText(container, "settings.mcp.policy.mode.read-write.title");+ await flush();+ expect(bestForLines()).toHaveLength(1);+ expect(bestForLines()[0]?.textContent).toBe(+ "settings.mcp.policy.mode.read-write.best-for");unmount();});- test("keeps the masking switch intrinsic", async () => {+ test("the policy inputs are locked while a save is in flight", async () => {+ const inFlight = Promise.withResolvers<undefined>();+ mocks.upsertSetting.mockReturnValue(inFlight.promise);+const { container, render, unmount } = renderIntoContainer(<MCPAccessPolicySection />);render();await flush();+clickText(container, "settings.mcp.policy.edit");await flush();+ // A SERVING mode, so the masking switch is on screen and inside the set+ // this asserts on. Picking Disabled here would withhold it (D7) and the+ // test would silently stop covering `disabled={saving}` on the Switch.+ clickText(container, "settings.mcp.policy.mode.read-write.title");+ await flush();++ // The Switch renders a span plus a hidden checkbox, and the checkbox is+ // what carries `disabled`, so the masking control is in this set only while+ // a serving mode is picked: three radios and that one checkbox.+ const controls = () =>+ [+ ...container.querySelectorAll(+ 'input[type="radio"], input[type="checkbox"]'+ ),+ ] as HTMLInputElement[];+ expect(controls()).toHaveLength(4);+ 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();+ expect(mocks.refreshServerInfo).toHaveBeenCalledOnce();+ unmount();+ });++ // The chip is the subject of the view: it carries the mode's own glyph, so+ // the identity picked in the selector is the identity shown in force and, on+ // the consent page, the identity the person approving sees.+ test("the chip names the policy in force, not only the mode", async () => {+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();- const maskingSwitch = container.querySelector(- '[aria-label="settings.mcp.policy.masking.title"]'+ expect(container.textContent).toContain(+ "settings.mcp.policy.current(settings.mcp.policy.mode.read-only.title)");- expect(maskingSwitch?.classList.contains("shrink-0")).toBe(true);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);+ test("the disclosure is collapsed by default, opens, and follows the pick", async () => {+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ expect(container.textContent).toContain(+ "settings.mcp.ladder.summary.read-only"+ );+ expect(container.querySelectorAll("li")).toHaveLength(0);++ clickText(container, "settings.mcp.ladder.summary.read-only");+ await flush();+ expect(container.querySelectorAll("li").length).toBeGreaterThan(0);++ // The open state carries into editing, and the list follows the pick+ // rather than the stored mode.+ clickText(container, "settings.mcp.policy.edit");+ await flush();+ expect(container.textContent).toContain(+ "settings.mcp.ladder.heading(settings.mcp.policy.mode.read-only.title)"+ );+ clickText(container, "settings.mcp.policy.mode.read-write.title");+ await flush();+ expect(container.textContent).toContain(+ "settings.mcp.ladder.heading(settings.mcp.policy.mode.read-write.title)"+ );+ expect(container.textContent).toContain("settings.mcp.ladder.tier.write");+ unmount();+ });++ test("the open and details state start over when the page is reopened", async () => {+ const first = renderIntoContainer(<MCPAccessPolicySection />);+ first.render();+ await flush();+ clickText(first.container, "settings.mcp.ladder.summary.read-only");+ await flush();+ clickText(first.container, "settings.mcp.ladder.show-details");+ await flush();+ expect(first.container.textContent).toContain(+ "settings.mcp.ladder.row.read-schemas.details"+ );+ first.unmount();++ const second = renderIntoContainer(<MCPAccessPolicySection />);+ second.render();+ await flush();+ expect(second.container.querySelectorAll("li")).toHaveLength(0);+ clickText(second.container, "settings.mcp.ladder.summary.read-only");+ await flush();+ expect(second.container.querySelectorAll("li").length).toBeGreaterThan(0);+ expect(second.container.textContent).not.toContain(+ "settings.mcp.ladder.row.read-schemas.details"+ );+ second.unmount();+ });++ // Disabled has no list, so red means "no capability" on both surfaces: the+ // plain sentence in view, the static line in the disclosure slot in edit.+ test("Disabled says its one sentence in view and its static line in edit", async () => {+ storePolicy(MCPSetting_Capability.DISABLED);const { container, render, unmount } = renderIntoContainer(<MCPAccessPolicySection />);render();await flush();+ expect(container.textContent).toContain(+ "settings.mcp.policy.mode.disabled.description"+ );+ expect(container.textContent).not.toContain("settings.mcp.ladder.summary");++ clickText(container, "settings.mcp.policy.edit");+ await flush();+ expect(container.textContent).toContain("settings.mcp.ladder.disabled");+ expect(container.textContent).not.toContain("settings.mcp.ladder.heading");+ unmount();+ });++ // The toggle governs what an MCP session may unmask, and Disabled admits+ // none, so offering it there would put a live control under a red line+ // saying no session can connect.+ test("the masking toggle is withheld while Disabled is picked", async () => {+ 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.title");+clickText(container, "settings.mcp.policy.mode.disabled.title");await flush();+ expect(+ maskingSwitch(container)+ ).toBeNull();- 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);+ // Picking a serving mode again brings the control back.+ clickText(container, "settings.mcp.policy.mode.read-write.title");+ await flush();+ expect(+ maskingSwitch(container)+ ).not.toBeNull();+ unmount();+ });++ // The flag is inert under Disabled but still stored, so an explicit choice is+ // kept for when MCP is turned back on rather than quietly rolled back — and+ // the footer says so, since the control that made it is off screen.+ test("saving Disabled still carries a masking edit the admin made", async () => {+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ clickText(container, "settings.mcp.policy.edit");+ await flush();++ act(() => maskingSwitch(container)?.click());+ await flush();++ clickText(container, "settings.mcp.policy.mode.disabled.title");+ await flush();+ expect(container.textContent).toContain(+ "settings.mcp.policy.masking-pending.ignored"+ );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);+ const request = mocks.upsertSetting.mock.calls.at(-1)?.[0];+ expect(request.updateMask.paths).toEqual([+ "value.mcp.capability",+ "value.mcp.ignore_masking_exemptions",+ ]);+ expect(request.value.value.value.ignoreMaskingExemptions).toBe(true);+ unmount();+ });- act(() => inFlight.resolve(undefined));+ // Picking back to the stored mode with no other edit leaves nothing to write.+ test("returning to the stored mode with no edit cannot save", async () => {+ storePolicy(MCPSetting_Capability.DISABLED);+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();await flush();- expect(mocks.refreshServerInfo).toHaveBeenCalledOnce();+ clickText(container, "settings.mcp.policy.edit");+ await flush();++ clickText(container, "settings.mcp.policy.mode.read-only.title");+ await flush();+ clickText(container, "settings.mcp.policy.mode.disabled.title");+ await flush();++ expect(mocks.useUnsavedChangesGuard).toHaveBeenLastCalledWith(false);+ expect(+ [...container.querySelectorAll("button")].find((button) =>+ button.textContent?.includes("settings.mcp.policy.save")+ )+ ).toHaveProperty("disabled", true);unmount();});+ test("a masking change reaches the update mask", async () => {+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ clickText(container, "settings.mcp.policy.edit");+ await flush();++ act(() => maskingSwitch(container)?.click());+ await flush();+ expect(mocks.useUnsavedChangesGuard).toHaveBeenLastCalledWith(true);++ clickText(container, "settings.mcp.policy.save");+ await flush();++ const request = mocks.upsertSetting.mock.calls.at(-1)?.[0];+ expect(request.updateMask.paths).toEqual([+ "value.mcp.ignore_masking_exemptions",+ ]);+ expect(request.value.value.value.ignoreMaskingExemptions).toBe(true);+ unmount();+ });++ // Clicking through the modes to read their descriptions must not undo an+ // unrelated edit. Withholding the control where it governs nothing is not a+ // reason to discard what the admin set with it.+ test("the masking draft survives a detour through Disabled", async () => {+ storePolicy(MCPSetting_Capability.READ_WRITE, true);+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ clickText(container, "settings.mcp.policy.edit");+ await flush();++ act(() => maskingSwitch(container)?.click());+ await flush();+ expect(mocks.useUnsavedChangesGuard).toHaveBeenLastCalledWith(true);++ clickText(container, "settings.mcp.policy.mode.disabled.title");+ await flush();+ // The control is withheld — it governs nothing under Disabled — but the+ // draft behind it is still the admin's, and the footer names the value Save+ // will write rather than the one that is stored.+ expect(maskingSwitch(container)).toBeNull();+ expect(container.textContent).toContain(+ "settings.mcp.policy.masking-pending.applied"+ );+ expect(container.textContent).not.toContain(+ "settings.mcp.policy.masking-pending.ignored"+ );+ expect(maskingBadgeText(container)).toBeUndefined();++ clickText(container, "settings.mcp.policy.mode.read-write.title");+ await flush();+ expect(maskingSwitch(container)?.getAttribute("aria-checked")).toBe("false");++ clickText(container, "settings.mcp.policy.save");+ await flush();+ const request = mocks.upsertSetting.mock.calls.at(-1)?.[0];+ expect(request.updateMask.paths).toEqual([+ "value.mcp.ignore_masking_exemptions",+ ]);+ expect(request.value.value.value.ignoreMaskingExemptions).toBe(false);+ unmount();+ });++ // An admin who cannot see the control cannot see the value either, so the+ // disclosure follows the value being saved rather than the edit that set it.+ test("a stored flag nobody touched is still named under a pick that hides it", async () => {+ storePolicy(MCPSetting_Capability.READ_ONLY, true);+ 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();+ expect(container.textContent).toContain(+ "settings.mcp.policy.masking-pending.ignored"+ );++ clickText(container, "settings.mcp.policy.save");+ await flush();+ const request = mocks.upsertSetting.mock.calls.at(-1)?.[0];+ expect(request.value.value.value.ignoreMaskingExemptions).toBe(true);+ unmount();+ });++ // The chip is the stored flag's disclosure and the toggle is the draft's.+ // Rendering the chip in the editor asserted a live restriction under a pick+ // that admits no session, and read the stored pair while Save wrote the+ // draft.+ test("the masking chip belongs to the view, never to the editor", async () => {+ storePolicy(MCPSetting_Capability.READ_ONLY, true);+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ expect(maskingBadgeText(container)).toBe("settings.mcp.policy.masking.badge");++ clickText(container, "settings.mcp.policy.edit");+ await flush();+ expect(maskingBadgeText(container)).toBeUndefined();++ clickText(container, "settings.mcp.policy.mode.disabled.title");+ await flush();+ expect(maskingBadgeText(container)).toBeUndefined();+ unmount();+ });++ // "MCP is off" is a claim about a mode somebody chose. A ceiling this build+ // cannot parse is failing closed instead, which has a different remedy.+ test("an unreadable ceiling is never reported as MCP being off", async () => {+ storePolicy(MCPSetting_Capability.CAPABILITY_UNSPECIFIED, true);+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ expect(maskingBadgeText(container)).toBeUndefined();++ clickText(container, "settings.mcp.policy.edit");+ await flush();+ expect(maskingBadgeText(container)).toBeUndefined();+ expect(container.textContent).toContain("settings.mcp.policy.unreadable.pick");+ // "Pick a mode to save this policy" and "this policy will be saved" cannot+ // both hold. Nothing is pending until a mode is picked.+ expect(container.textContent).not.toContain(+ "settings.mcp.policy.masking-pending"+ );+ unmount();+ });++ // The write landed but the card can no longer read it back. Closing the+ // editor would present the pre-save policy as current, so the editor stays+ // open with the pick intact and saving again is the same write.+ test("a failed re-read keeps the editor open and claims no success", async () => {+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ clickText(container, "settings.mcp.policy.edit");+ await flush();+ clickText(container, "settings.mcp.policy.mode.read-write.title");+ await flush();++ mocks.refreshServerInfo.mockRejectedValue(new Error("read failed"));+ clickText(container, "settings.mcp.policy.save");+ await flush();++ expect(mocks.upsertSetting).toHaveBeenCalledOnce();+ expect(mocks.pushNotification).not.toHaveBeenCalled();+ expect(container.textContent).toContain("settings.mcp.policy.save");+ expect(+ [...container.querySelectorAll("button")].find((button) =>+ button.textContent?.includes("settings.mcp.policy.save")+ )+ ).toHaveProperty("disabled", false);+ unmount();+ });++ test("a failed save closes nothing and reports no success", async () => {+ mocks.upsertSetting.mockRejectedValue(new Error("write failed"));+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ clickText(container, "settings.mcp.policy.edit");+ await flush();+ clickText(container, "settings.mcp.policy.mode.read-write.title");+ await flush();++ clickText(container, "settings.mcp.policy.save");+ await flush();++ expect(mocks.pushNotification).not.toHaveBeenCalled();+ expect(mocks.refreshServerInfo).not.toHaveBeenCalled();+ expect(container.textContent).toContain("settings.mcp.policy.save");+ unmount();+ });++ // Opening the editor is not an edit. A form that cannot be saved has no save+ // to describe, and the view's chip is where the stored flag is reported.+ test("a pristine editor promises no save", async () => {+ storePolicy(MCPSetting_Capability.DISABLED, true);+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ clickText(container, "settings.mcp.policy.edit");+ await flush();++ expect(container.textContent).not.toContain(+ "settings.mcp.policy.masking-pending"+ );+ expect(+ [...container.querySelectorAll("button")].find((button) =>+ button.textContent?.includes("settings.mcp.policy.save")+ )+ ).toHaveProperty("disabled", true);+ unmount();+ });++ // The footer says what will be written, never when it takes effect — so it+ // does not vary with a masking license the way the view's chip does.+ test("the pending line reads the same on an unlicensed workspace", async () => {+ mocks.dataMaskingAvailable.value = false;+ storePolicy(MCPSetting_Capability.READ_ONLY, true);+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ expect(maskingBadgeText(container)).toBe(+ "settings.mcp.policy.masking.badge-unlicensed"+ );++ clickText(container, "settings.mcp.policy.edit");+ await flush();+ clickText(container, "settings.mcp.policy.mode.disabled.title");+ await flush();+ expect(container.textContent).toContain(+ "settings.mcp.policy.masking-pending.ignored"+ );+ unmount();+ });++ // With no mode picked, nothing is known to serve, so the control that+ // configures a session has nothing to configure.+ test("the masking toggle is withheld when no mode is picked", async () => {+ storePolicy(MCPSetting_Capability.CAPABILITY_UNSPECIFIED);+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ clickText(container, "settings.mcp.policy.edit");+ await flush();++ expect(container.textContent).toContain(+ "settings.mcp.policy.unreadable.pick"+ );+ expect(+ maskingSwitch(container)+ ).toBeNull();+ expect(mocks.useUnsavedChangesGuard).toHaveBeenLastCalledWith(false);+ unmount();+ });++ test("the masking badge reports a stored restriction", async () => {+ storePolicy(MCPSetting_Capability.READ_ONLY, true);+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ // Exact, not substring: the plain key is a prefix of both suffixed ones, so+ // `toContain` would pass for every state including the two that report the+ // flag as inert.+ expect(maskingBadgeText(container)).toBe("settings.mcp.policy.masking.badge");+ unmount();+ });++ // Still shown without a license — hiding it would leave a stored flag with+ // nowhere to see it — but it must not assert a restriction nothing applies.+ // The editor's "not licensed" note is a different branch, behind+ // bb.settings.set, which a reader of this page may never reach.+ test("the masking badge says so when masking is unlicensed", async () => {+ mocks.dataMaskingAvailable.value = false;+ storePolicy(MCPSetting_Capability.READ_ONLY, true);+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ expect(maskingBadgeText(container)).toBe(+ "settings.mcp.policy.masking.badge-unlicensed"+ );+ unmount();+ });++ // Storable under Disabled, so it needs a view there rather than a hole: the+ // badge says the flag is set and that MCP is off, instead of asserting a+ // restriction on sessions that cannot exist.+ test("the masking badge says MCP is off on a disabled policy", async () => {+ storePolicy(MCPSetting_Capability.DISABLED, true);+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();++ expect(maskingBadgeText(container)).toBe(+ "settings.mcp.policy.masking.badge-disabled"+ );+ unmount();+ });++ // The tightening note is about a change being made, not about the current+ // state, so it belongs to the editor; the audit fact moved to the section+ // description and must not come back as a second line under the chip.+ test("the footer shows only while editing and names the change when dirty", async () => {+ const { container, render, unmount } = renderIntoContainer(+ <MCPAccessPolicySection />+ );+ render();+ await flush();+ expect(container.textContent).not.toContain("settings.mcp.policy.tightening");+ expect(container.textContent).not.toContain("settings.mcp.policy.audit");++ clickText(container, "settings.mcp.policy.edit");+ await flush();+ expect(container.textContent).toContain("settings.mcp.policy.tightening");+ expect(container.textContent).not.toContain(+ "settings.mcp.policy.tightening-change"+ );++ clickText(container, "settings.mcp.policy.mode.read-write.title");+ await flush();+ expect(container.textContent).toContain(+ "settings.mcp.policy.tightening-change(settings.mcp.policy.mode.read-only.title,settings.mcp.policy.mode.read-write.title)"+ );+ unmount();+ });});diff --git a/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsx b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsxindex 7e3a1cc289..4894d3ca4d 100644--- a/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsx+++ b/frontend/src/routes/workspace/mcp/MCPAccessPolicySection.tsx@@ -1,13 +1,18 @@import { create } from "@bufbuild/protobuf";import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";-import { Rows3 } from "lucide-react";import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";+import { MCPModeBadge } from "@/components/mcp/MCPModeBadge";import type { MCPMode } from "@/components/mcp/mcpPolicy";-import { isMCPMode, MCP_CAPABILITY_CHOICES } from "@/components/mcp/mcpPolicy";+import {+ isMCPMode,+ isServingMode,+ MCP_CAPABILITY_CHOICES,+ MCP_MODE_PRESENTATION,+ mcpModeKey,+} from "@/components/mcp/mcpPolicy";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";@@ -24,31 +29,7 @@ import {SettingValueSchema,} from "@/types/proto-es/v1/setting_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";--// 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<- MCPMode,- { key: string; tone: string; badge: BadgeProps["variant"] }-> = {- [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",- },-};+import { MCPCapabilityLadder } from "./MCPCapabilityLadder";export function MCPAccessPolicySection() {const { t } = useTranslation();@@ -57,8 +38,11 @@ export function MCPAccessPolicySection() {const [saving, setSaving] = useState(false);const [pick, setPick] = useState<MCPMode | undefined>(undefined);const [ignoreMasking, setIgnoreMasking] = useState(false);- const [readFailed, setReadFailed] = useState(false);const [readSettled, setReadSettled] = useState(false);+ // Held here rather than in the ladder so the open state carries from the view+ // into the editor, which renders the ladder in a different place.+ const [ladderOpen, setLadderOpen] = useState(false);+ const [ladderDetails, setLadderDetails] = useState(false);const serverInfo = useAppStore((state) => state.serverInfo);const loadServerInfo = useAppStore((state) => state.loadServerInfo);const refreshServerInfo = useAppStore((state) => state.refreshServerInfo);@@ -67,10 +51,7 @@ export function MCPAccessPolicySection() {);useEffect(() => {- void loadServerInfo().then((info) => {- setReadFailed(!info?.mcpSetting);- setReadSettled(true);- });+ void loadServerInfo().then(() => setReadSettled(true));}, [loadServerInfo]);const storedCapability = serverInfo?.mcpSetting?.capability;@@ -92,18 +73,20 @@ export function MCPAccessPolicySection() {setEditing(true);};- const isDirty =- editing && (pick !== storedMode || 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.+ // Only a serving mode admits a session for the masking flag to govern, so the+ // toggle is withheld elsewhere — but the draft behind it is kept and saved+ // whatever the pick, because withholding a control is not a reason to discard+ // what the admin set with it.+ const maskingApplies = isServingMode(pick);+ const maskingChanged = ignoreMasking !== storedIgnoreMasking;+ const isDirty = editing && (pick !== storedMode || maskingChanged);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: MCPMode): string =>- t(`settings.mcp.policy.mode.${MODES[capability].key}.title`);+ t(mcpModeKey(capability, "title"));const save = async () => {if (pick === undefined) {@@ -113,7 +96,7 @@ export function MCPAccessPolicySection() {if (pick !== storedMode) {paths.push("value.mcp.capability");}- if (ignoreMasking !== storedIgnoreMasking) {+ if (maskingChanged) {paths.push("value.mcp.ignore_masking_exemptions");}setSaving(true);@@ -131,23 +114,103 @@ export function MCPAccessPolicySection() {}),updateMask: create(FieldMaskSchema, { paths }),});- setEditing(false);+ // Re-read before leaving the editor. refreshServerInfo throws without+ // clearing what it holds, so closing first would present the pre-save+ // policy as current; staying in the editor keeps the pick the admin made,+ // and saving again is the same write.await refreshServerInfo();+ setEditing(false);pushNotification({module: "bytebase",style: "SUCCESS",title: t("settings.mcp.policy.saved", { mode: modeLabel(pick) }),});+ } catch {+ // The response interceptor reports both failures; there is nothing to add+ // and nothing to undo, and an unhandled rejection would escape onClick.} finally {setSaving(false);}};+ // Disabled has no list, so it says its one sentence instead.+ const disclosure = (mode: MCPMode) => {+ if (!isServingMode(mode)) {+ return editing ? (+ <p className="rounded-sm bg-error/5 px-3 py-2 text-sm text-error">+ {t("settings.mcp.ladder.disabled")}+ </p>+ ) : (+ <p className="textinfolabel">+ {t("settings.mcp.policy.mode.disabled.description")}+ </p>+ );+ }+ return (+ <MCPCapabilityLadder+ mode={mode}+ expanded={ladderOpen}+ details={ladderDetails}+ onExpandedChange={setLadderOpen}+ onDetailsChange={setLadderDetails}+ />+ );+ };++ // The footer names the change while the form is dirty, so an admin reads the+ // transition they are about to apply rather than a general rule. A repair of+ // an unreadable row has no "from" to name, so it keeps the plain sentence.+ const footerSentence =+ pick !== undefined && storedMode !== undefined && pick !== storedMode+ ? t("settings.mcp.policy.tightening-change", {+ from: modeLabel(storedMode),+ to: modeLabel(pick),+ })+ : t("settings.mcp.policy.tightening");++ // Where the pick withholds the toggle and the form can still be saved, the+ // footer is the flag's only disclosure. It names the value Save writes+ // whenever that value will be set, not only when this edit changed it — and+ // says nothing about when the value takes effect, which depends on a masking+ // license this line cannot see.+ const maskingPending =+ canSave && !maskingApplies && (ignoreMasking || storedIgnoreMasking)+ ? ignoreMasking+ ? t("settings.mcp.policy.masking-pending.ignored")+ : t("settings.mcp.policy.masking-pending.applied")+ : undefined;++ // What the stored flag is doing, for the view that reports it. Takes the mode+ // rather than reading `storedMode`, so the branch that already proved there is+ // a stored mode passes the proof in instead of re-testing for it.+ const maskingBadgeFor = (mode: MCPMode) =>+ mode === MCPSetting_Capability.DISABLED ? (+ <Badge variant="default">+ {t("settings.mcp.policy.masking.badge-disabled")}+ </Badge>+ ) : dataMaskingAvailable ? (+ <Badge variant="secondary">+ {t("settings.mcp.policy.masking.badge")}+ </Badge>+ ) : (+ <Badge variant="default">+ {t("settings.mcp.policy.masking.badge-unlicensed")}+ </Badge>+ );+// 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) {+ if (!readSettled) {+ return (+ <p className="textinfolabel">{t("settings.mcp.policy.loading")}</p>+ );+ }+ // A settled read with no setting is a failed one: loadServerInfo resolves+ // with what it stored, and a refresh that comes back without the setting+ // has to land here rather than on a spinner that never clears.+ if (storedCapability === undefined) {return (<Alertvariant="error"@@ -156,41 +219,29 @@ export function MCPAccessPolicySection() {/>);}- if (!readSettled || storedCapability === undefined) {- 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">- {storedMode === undefined ? (- <span className="text-sm font-medium text-warning">- {t(- 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[storedMode].tone)}- />- <span className="text-sm text-control-light">- {t("settings.mcp.policy.in-force")}+ {!editing && (+ <div className="flex items-start justify-between gap-x-2">+ {storedMode === undefined ? (+ <span className="text-sm font-medium text-warning">+ {t(+ unreadable+ ? "settings.mcp.policy.unreadable.title"+ : "settings.mcp.policy.unserved.title"+ )}</span>- <Badge variant={MODES[storedMode].badge}>- {modeLabel(storedMode)}- </Badge>- {storedIgnoreMasking && (- <Badge variant="secondary">- {t("settings.mcp.policy.masking.badge")}- </Badge>- )}- </div>- )}- {!editing && (+ ) : (+ <div className="flex flex-wrap items-center gap-2">+ <MCPModeBadge+ mode={storedMode}+ describedAs={t("settings.mcp.policy.current", {+ mode: modeLabel(storedMode),+ })}+ />+ {storedIgnoreMasking && maskingBadgeFor(storedMode)}+ </div>+ )}<PermissionGuard permissions={["bb.settings.set"]}>{({ disabled }) => (<Button@@ -203,8 +254,8 @@ export function MCPAccessPolicySection() {</Button>)}</PermissionGuard>- )}- </div>+ </div>+ )}{storedMode === undefined && (<Alert@@ -226,7 +277,7 @@ export function MCPAccessPolicySection() {nothing else, then vanish when the editor closes. */}<RadioGrouparia-label={t("settings.mcp.policy.title")}- className="grid grid-cols-1 gap-4 lg:grid-cols-3"+ className="grid grid-cols-1 items-stretch gap-2 sm:grid-cols-3"disabled={saving}value={pick === undefined ? "" : String(pick)}onValueChange={(value) => {@@ -237,78 +288,99 @@ export function MCPAccessPolicySection() {}}>{MCP_CAPABILITY_CHOICES.map((capability) => {- const mode = MODES[capability];+ const { icon: Icon } = MCP_MODE_PRESENTATION[capability];+ const picked = pick === capability;return (<RadioGroupItemkey={capability}value={String(capability)}- // The item wraps the whole card in a label, so without- // this the radio's name absorbs the description and the- // "Best for" line.- aria-label={t(`settings.mcp.policy.mode.${mode.key}.title`)}+ // The item wraps the whole card in a label, so without this+ // the radio's name absorbs the caption too.+ aria-label={modeLabel(capability)}className={cn(- "relative h-full flex-col items-stretch rounded-sm border p-4",- pick === capability- ? "border-accent"- : "border-control-border"+ "h-full rounded-sm border px-3 py-2",+ "has-[:focus-visible]:outline-hidden has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-accent has-[:focus-visible]:ring-offset-2",+ picked+ ? // Border, tint and ring are all color, and forced+ // colors resolves every one of them to the same+ // system value; the outline is what still separates+ // the selected card from the other two.+ "border-accent bg-accent/5 ring-1 ring-accent forced-colors:outline-2"+ : "border-control-border",+ !picked &&+ !saving &&+ "hover:border-accent/50 hover:bg-control-bg")}- contentClassName="flex h-full flex-col gap-2"- radioClassName="absolute right-4 top-4"+ contentClassName="flex min-w-0 items-center gap-x-2"+ // Hidden rather than placed: the card is the control, and+ // the label carries the focus ring for it.+ radioClassName="sr-only">- <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`)}+ <Icon+ className={cn(+ "size-5 shrink-0",+ picked ? "text-accent" : "text-control-light"+ )}+ />+ <span className="flex min-w-0 flex-col">+ <span className="text-sm font-medium text-main">+ {modeLabel(capability)}</span>- </div>- <p className="textinfolabel">- {t(`settings.mcp.policy.mode.${mode.key}.description`)}- </p>- <p className="textinfolabel pt-2">- {t(`settings.mcp.policy.mode.${mode.key}.best-for`)}- </p>+ <span className="text-xs text-control-light">+ {t(mcpModeKey(capability, "caption"))}+ </span>+ </span></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 shrink-0"- />- <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 && (+ {pick === undefined ? (<p className="text-sm text-warning">{t("settings.mcp.policy.unreadable.pick")}</p>+ ) : (+ <>+ <p className="textinfolabel">+ {t(mcpModeKey(pick, "best-for"))}+ </p>+ {disclosure(pick)}+ </>+ )}++ {maskingApplies && (+ <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 shrink-0"+ />+ <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>+ {!dataMaskingAvailable && (+ <div className="text-sm text-warning">+ {t("settings.mcp.policy.masking.unavailable")}+ </div>+ )}+ </div>+ </div>)}<Separator /><div className="flex flex-wrap items-center justify-between gap-4">- <p className="textinfolabel">- {t("settings.mcp.policy.tightening")}- </p>+ <div className="flex flex-col gap-1">+ <p className="textinfolabel">{footerSentence}</p>+ {maskingPending && (+ <p className="textinfolabel">{maskingPending}</p>+ )}+ </div><div className="flex shrink-0 gap-x-2"><Buttonappearance="outline"@@ -324,23 +396,7 @@ export function MCPAccessPolicySection() {</div></>) : (- <>- {storedMode !== undefined && (- <p className="textinfolabel">- {t(- `settings.mcp.policy.mode.${- MODES[storedMode].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>- </>+ storedMode !== undefined && disclosure(storedMode))}</div>);diff --git a/frontend/src/routes/workspace/mcp/MCPCapabilityLadder.test.tsx b/frontend/src/routes/workspace/mcp/MCPCapabilityLadder.test.tsxnew file mode 100644index 0000000000..32d24df8ec--- /dev/null+++ b/frontend/src/routes/workspace/mcp/MCPCapabilityLadder.test.tsx@@ -0,0 +1,244 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, test, vi } from "vitest";+import { MCP_CAPABILITY_ROWS } from "@/components/mcp/mcpCapabilityRows";+import { MCPSetting_Capability } from "@/types/proto-es/v1/setting_service_pb";+import { MCPCapabilityLadder } from "./MCPCapabilityLadder";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, vars?: Record<string, string>) =>+ vars ? `${key}(${Object.values(vars).join(",")})` : key,+ }),+}));++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ act(() => {+ root.render(element);+ });+ return {+ container,+ rerender: (next: ReactElement) => act(() => root.render(next)),+ unmount: () =>+ act(() => {+ root.unmount();+ container.remove();+ }),+ };+};++const ladder = (props: Partial<Parameters<typeof MCPCapabilityLadder>[0]>) => (+ <MCPCapabilityLadder+ mode={MCPSetting_Capability.READ_ONLY}+ expanded={true}+ details={false}+ onExpandedChange={() => undefined}+ onDetailsChange={() => undefined}+ {...props}+ />+);++const rowItems = (container: HTMLElement) => [+ ...container.querySelectorAll("li:not([role='presentation'])"),+];++const servedIds = (container: HTMLElement) =>+ rowItems(container)+ .filter((item) => item.textContent?.includes("settings.mcp.ladder.tier."))+ .map(+ (item) =>+ MCP_CAPABILITY_ROWS.find((row) =>+ item.textContent?.includes(`row.${row.id}.title`)+ )?.id+ );++describe("MCPCapabilityLadder", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ // Comparing modes must never need a second surface, so an unserved row stays+ // on screen — muted, with no tier tag — rather than disappearing.+ test("every row is listed under every mode, served or not", () => {+ for (const mode of [+ MCPSetting_Capability.READ_ONLY,+ MCPSetting_Capability.READ_WRITE,+ ] as const) {+ const { container, unmount } = renderIntoContainer(ladder({ mode }));+ // One list, so a row's position is announced as "n of 8". The dividers+ // live in it too but are presentational, so they do not inflate that+ // count or shift a row's index.+ expect(container.querySelectorAll("ul")).toHaveLength(1);+ expect(rowItems(container)).toHaveLength(MCP_CAPABILITY_ROWS.length);+ for (const row of MCP_CAPABILITY_ROWS) {+ expect(container.textContent).toContain(+ `settings.mcp.ladder.row.${row.id}.title`+ );+ }+ unmount();+ }+ });++ test("the tier tag rides the served rows only", () => {+ const readOnly = renderIntoContainer(+ ladder({ mode: MCPSetting_Capability.READ_ONLY })+ );+ expect(servedIds(readOnly.container)).toEqual([+ "read-schemas",+ "read-data",+ "read-workflow",+ ]);+ // No "write" badge may appear under a mode that serves no write row.+ expect(readOnly.container.textContent).not.toContain(+ "settings.mcp.ladder.tier.write"+ );+ expect(readOnly.container.textContent).toContain(+ "settings.mcp.ladder.tier.read"+ );+ readOnly.unmount();++ const readWrite = renderIntoContainer(+ ladder({ mode: MCPSetting_Capability.READ_WRITE })+ );+ expect(servedIds(readWrite.container)).toEqual(+ MCP_CAPABILITY_ROWS.map((row) => row.id)+ );+ expect(readWrite.container.textContent).toContain(+ "settings.mcp.ladder.tier.write"+ );+ readWrite.unmount();+ });++ test("collapsed, the trigger is the mode's description and nothing else shows", () => {+ const { container, unmount } = renderIntoContainer(+ ladder({ expanded: false })+ );+ expect(container.textContent).toContain(+ "settings.mcp.ladder.summary.read-only"+ );+ expect(container.querySelectorAll("li")).toHaveLength(0);+ expect(container.textContent).not.toContain(+ "settings.mcp.ladder.floor.label"+ );+ // The details control belongs to the list, so it is absent with the list.+ expect(container.textContent).not.toContain(+ "settings.mcp.ladder.show-details"+ );+ unmount();+ });++ test("expanded, the trigger becomes the list heading naming the mode", () => {+ const { container, unmount } = renderIntoContainer(ladder({}));+ expect(container.textContent).toContain(+ "settings.mcp.ladder.heading(settings.mcp.policy.mode.read-only.title)"+ );+ expect(container.textContent).not.toContain(+ "settings.mcp.ladder.summary.read-only"+ );+ unmount();+ });++ // One second-level control rather than eight: the toggle reveals the+ // sub-item line on every row at once.+ test("the details toggle reveals sub-items on every row at once", () => {+ const { container, rerender, unmount } = renderIntoContainer(ladder({}));+ for (const row of MCP_CAPABILITY_ROWS) {+ expect(container.textContent).not.toContain(+ `settings.mcp.ladder.row.${row.id}.details`+ );+ }+ expect(container.textContent).toContain("settings.mcp.ladder.show-details");++ rerender(ladder({ details: true }));+ for (const row of MCP_CAPABILITY_ROWS) {+ expect(container.textContent).toContain(+ `settings.mcp.ladder.row.${row.id}.details`+ );+ }+ expect(container.textContent).toContain("settings.mcp.ladder.hide-details");+ unmount();+ });++ test("toggling asks the owner rather than keeping its own state", () => {+ const expanded: boolean[] = [];+ const details: boolean[] = [];+ const { container, unmount } = renderIntoContainer(+ ladder({+ onExpandedChange: (next) => expanded.push(next),+ onDetailsChange: (next) => details.push(next),+ })+ );+ const buttons = [...container.querySelectorAll("button")];+ act(() => buttons[0]?.click());+ act(() => buttons[1]?.click());+ expect(expanded).toEqual([false]);+ expect(details).toEqual([true]);+ unmount();+ });++ // The floor is what keeps the list honest about the methods no mode reaches.+ // It belongs to no tier, so it is not a row.+ test("the floor line closes the list without being a row", () => {+ const { container, unmount } = renderIntoContainer(ladder({}));+ expect(container.textContent).toContain("settings.mcp.ladder.floor.label");+ expect(container.textContent).toContain("settings.mcp.ladder.floor.text");+ const floor = [...container.querySelectorAll("p")].find((node) =>+ node.textContent?.includes("settings.mcp.ladder.floor.text")+ );+ expect(floor).toBeDefined();+ expect(floor?.closest("li")).toBeNull();+ unmount();+ });++ test("each tier is closed by a divider outside its rows, in list order", () => {+ const { container, unmount } = renderIntoContainer(ladder({}));+ for (const tier of ["read", "write"]) {+ const divider = [...container.querySelectorAll("li")].find((node) =>+ node.textContent?.includes(`settings.mcp.ladder.stops.${tier}`)+ );+ expect(divider).toBeDefined();+ // Its own item, and presentational: not content inside the row it closes,+ // and not an item of the eight.+ expect(divider?.getAttribute("role")).toBe("presentation");+ expect(divider?.textContent).not.toContain("settings.mcp.ladder.row.");+ }++ const text = container.textContent ?? "";+ const readStop = text.indexOf("settings.mcp.ladder.stops.read");+ const writeStop = text.indexOf("settings.mcp.ladder.stops.write");+ expect(writeStop).toBeGreaterThan(readStop);+ // The read divider sits between the last read row and the first write row.+ expect(readStop).toBeGreaterThan(+ text.indexOf("settings.mcp.ladder.row.read-workflow.title")+ );+ expect(readStop).toBeLessThan(+ text.indexOf("settings.mcp.ladder.row.propose.title")+ );+ unmount();+ });++ test("every row states whether it is allowed, not only shows it", () => {+ const { container, unmount } = renderIntoContainer(+ ladder({ mode: MCPSetting_Capability.READ_ONLY })+ );+ const markOf = (rowId: string) => {+ const item = rowItems(container).find((node) =>+ node.textContent?.includes(`row.${rowId}.title`)+ );+ return [...(item?.querySelectorAll("span.sr-only") ?? [])]+ .map((node) => node.textContent)+ .join("");+ };+ expect(markOf("read-schemas")).toBe("settings.mcp.ladder.mark.allowed");+ expect(markOf("propose")).toBe("settings.mcp.ladder.mark.refused");+ unmount();+ });+});diff --git a/frontend/src/routes/workspace/mcp/MCPCapabilityLadder.tsx b/frontend/src/routes/workspace/mcp/MCPCapabilityLadder.tsxnew file mode 100644index 0000000000..4c2bdd1816--- /dev/null+++ b/frontend/src/routes/workspace/mcp/MCPCapabilityLadder.tsx@@ -0,0 +1,223 @@+import { Check, ChevronRight, Minus } from "lucide-react";+import { Fragment } from "react";+import { useTranslation } from "react-i18next";+import type {+ MCPCapabilityRow,+ MCPCapabilityTier,+} from "@/components/mcp/mcpCapabilityRows";+import {+ isRowServed,+ MCP_CAPABILITY_TIERS,+ mcpRowKey,+ mcpTierKey,+ rowsInTier,+} from "@/components/mcp/mcpCapabilityRows";+import {+ type MCPServingMode,+ mcpModeKey,+ mcpSummaryKey,+} from "@/components/mcp/mcpPolicy";+import type { BadgeProps } from "@/components/ui/badge";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ Collapsible,+ CollapsiblePanel,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";+import { Separator } from "@/components/ui/separator";+import { cn } from "@/lib/utils";++const TIER_VARIANT: Record<MCPCapabilityTier, BadgeProps["variant"]> = {+ read: "success",+ write: "warning",+};++interface Props {+ readonly mode: MCPServingMode;+ readonly expanded: boolean;+ readonly details: boolean;+ readonly onExpandedChange: (expanded: boolean) => void;+ readonly onDetailsChange: (details: boolean) => void;+}++/**+ * What a mode allows, as capability rows in one ordered list of which every+ * mode is a prefix.+ *+ * The served set comes from the mode's tier alone, so there is no comparison+ * against a stored mode and the edit state renders exactly what the view will+ * show after saving. Rows a mode does not serve stay visible and muted, which is+ * what lets an admin compare two modes without opening a second surface.+ */+export function MCPCapabilityLadder({+ mode,+ expanded,+ details,+ onExpandedChange,+ onDetailsChange,+}: Props) {+ const { t } = useTranslation();++ return (+ <Collapsible open={expanded} onOpenChange={onExpandedChange}>+ <div className="flex items-center justify-between gap-x-2 border-b border-block-border py-2">+ <CollapsibleTrigger+ className="min-w-0 flex-1 rounded-xs"+ data-testid="mcp-ladder-trigger"+ >+ <ChevronRight+ className={cn(+ "size-4 shrink-0 text-control-light transition-transform",+ expanded && "rotate-90"+ )}+ />+ {/* Neither label repeats the mode name the chip or the selector+ already shows, except the heading, whose job is to say whose list+ this is. */}+ <span+ className={cn(+ "min-w-0 text-sm",+ expanded ? "font-medium text-main" : "text-control-light"+ )}+ >+ {expanded+ ? t("settings.mcp.ladder.heading", {+ mode: t(mcpModeKey(mode, "title")),+ })+ : t(mcpSummaryKey(mode))}+ </span>+ </CollapsibleTrigger>+ {expanded && (+ <Button+ appearance="link"+ size="sm"+ className="shrink-0"+ onClick={() => onDetailsChange(!details)}+ >+ {details+ ? t("settings.mcp.ladder.hide-details")+ : t("settings.mcp.ladder.show-details")}+ </Button>+ )}+ </div>++ <CollapsiblePanel>+ {/* One list, so the rows are announced as a single ordered set and a+ row's position in it survives without sight — the prefix the design+ rests on. Each divider is a presentational sibling of the rows it+ closes, never content inside the last of them. */}+ {/* Tailwind's preflight removes the marker from every `ul`, and Safari+ drops list semantics from an unstyled list — so the position+ announcement this list depends on needs the role stated. */}+ <ul role="list" className="flex flex-col">+ {MCP_CAPABILITY_TIERS.map((tier) => (+ <Fragment key={tier}>+ {rowsInTier(tier).map((row) => (+ <LadderRow+ key={row.id}+ row={row}+ served={isRowServed(mode, row)}+ details={details}+ />+ ))}+ <TierDivider tier={tier} />+ </Fragment>+ ))}+ </ul>+ {/* The floor is one line rather than a row: it is what no mode serves,+ so it has no mark and belongs to no tier. */}+ <p className="bg-error/5 px-3 py-2 text-sm text-error">+ <span className="font-medium">+ {t("settings.mcp.ladder.floor.label")}+ </span>{" "}+ {t("settings.mcp.ladder.floor.text")}+ </p>+ </CollapsiblePanel>+ </Collapsible>+ );+}++function LadderRow({+ row,+ served,+ details,+}: {+ row: MCPCapabilityRow;+ served: boolean;+ details: boolean;+}) {+ const { t } = useTranslation();+ return (+ <li className="flex items-start gap-x-2 border-b border-block-border px-1 py-2">+ <span+ className={cn(+ "mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full",+ served+ ? "bg-success/10 text-success"+ : "bg-control-bg text-control-light"+ )}+ >+ {served ? (+ <Check className="size-3" aria-hidden="true" />+ ) : (+ <Minus className="size-3" aria-hidden="true" />+ )}+ {/* Served and unserved are otherwise carried by the glyph, the muting+ and the presence of the tier tag — all of them visual. Without this+ a refused row is announced the same as an allowed one. */}+ <span className="sr-only">+ {served+ ? t("settings.mcp.ladder.mark.allowed")+ : t("settings.mcp.ladder.mark.refused")}+ </span>+ </span>+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex flex-wrap items-center gap-2">+ <span+ className={cn(+ "text-sm",+ served ? "font-medium text-main" : "text-control-light"+ )}+ >+ {t(mcpRowKey(row, "title"))}+ </span>+ {served && (+ <Badge+ variant={TIER_VARIANT[row.tier]}+ className="px-2 py-0 text-xs"+ >+ {t(mcpTierKey(row.tier, "tier"))}+ </Badge>+ )}+ </div>+ {details && (+ <p+ className={cn(+ "text-xs leading-4",+ served ? "text-control" : "text-control-light"+ )}+ >+ {t(mcpRowKey(row, "details"))}+ </p>+ )}+ </div>+ </li>+ );+}++function TierDivider({ tier }: { tier: MCPCapabilityTier }) {+ const { t } = useTranslation();+ return (+ <li+ role="presentation"+ className="flex items-center gap-x-2 border-b border-block-border py-2 text-xs text-control-light"+ >+ <Separator className="flex-1" />+ <span className="uppercase tracking-wide">+ {t(mcpTierKey(tier, "stops"))}+ </span>+ <Separator className="flex-1" />+ </li>+ );+}diff --git a/frontend/src/types/proto-es/v1/annotation_pb.d.ts b/frontend/src/types/proto-es/v1/annotation_pb.d.tsindex 191e4bf0eb..8a7bcd027c 100644--- a/frontend/src/types/proto-es/v1/annotation_pb.d.ts+++ b/frontend/src/types/proto-es/v1/annotation_pb.d.ts@@ -91,6 +91,9 @@ export declare const AuthMethodSchema: GenEnum<AuthMethod>;* between, EXCLUDED and FORBIDDEN are served by no ceiling, and an unclassified* method is refused rather than served. Annotating a method is therefore a* change to what an MCP session can reach, taking effect on the next request.+ * READ and WRITE methods are also disclosed to workspace admins, as capability+ * rows on the Access policy page, so annotating a method changes what the+ * product promises as well as what it serves.** @generated from enum bytebase.v1.MCPMethodClass*/diff --git a/frontend/src/types/proto-es/v1/annotation_pb.js b/frontend/src/types/proto-es/v1/annotation_pb.jsindex e26e39d844..c977c3a338 100644--- a/frontend/src/types/proto-es/v1/annotation_pb.js+++ b/frontend/src/types/proto-es/v1/annotation_pb.js@@ -56,6 +56,9 @@ export const MCPMethodClassSchema = /*@__PURE__*/* between, EXCLUDED and FORBIDDEN are served by no ceiling, and an unclassified* method is refused rather than served. Annotating a method is therefore a* change to what an MCP session can reach, taking effect on the next request.+ * READ and WRITE methods are also disclosed to workspace admins, as capability+ * rows on the Access policy page, so annotating a method changes what the+ * product promises as well as what it serves.** @generated from enum bytebase.v1.MCPMethodClass*/diff --git a/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.ts b/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.tsnew file mode 100644index 0000000000..4f3d8fc993--- /dev/null+++ b/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.ts@@ -0,0 +1,274 @@+// Workspace Settings → MCP Integration → Access policy: the capability ladder.+//+// State safety: the MCP setting is snapshotted in beforeAll and restored via+// API in afterAll, because a workspace left on Read-write would change what a+// later suite's MCP session is allowed to do. This file runs before+// workspace-seat-limit's license drop (directory order).++import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { test, expect, type Page } from "@playwright/test";+import { rowsInTier } from "../../../src/components/mcp/mcpCapabilityRows";+import enUS from "../../../src/locales/en-US.json";+import { loadTestEnv, type TestEnv } from "../framework/env";+import { BytebaseApiClient } from "../framework/api-client";++// Prose the page must SHOW is read from the locale file, so a copy edit cannot+// leave an assertion pointing at a sentence that does not exist. Copy that must+// be ABSENT stays a literal below, since it has no key to read.+const COPY = enUS.settings.mcp;++test.setTimeout(120_000);++let env: TestEnv & { api: BytebaseApiClient };+// No default. getSetting turns every read error into null, so a fabricated+// baseline here would be indistinguishable from a real one — and teardown would+// then "restore" the workspace to a ceiling it never had.+let originalMCPSetting: Record<string, unknown>;++// The row titles, in list order, derived from the table the product renders, so+// a row added there is covered here without editing this file. The inventory+// itself is pinned in mcpCapabilityRows.test.ts, not here.+const rowTitle = (id: keyof typeof COPY.ladder.row) => COPY.ladder.row[id].title;+const titlesInTier = (tier: "read" | "write") =>+ rowsInTier(tier).map((row) => rowTitle(row.id));+const READ_ROWS = titlesInTier("read");+const WRITE_ROWS = titlesInTier("write");++const READ_ONLY_SUMMARY = COPY.ladder.summary["read-only"];+const READ_WRITE_SUMMARY = COPY.ladder.summary["read-write"];+const EXPORT_DETAILS = COPY.ladder.row.export.details;++async function readCapability(): Promise<string> {+ const setting = (await env.api.getSetting("MCP")) as {+ value?: { mcp?: { capability?: string } };+ } | null;+ return setting?.value?.mcp?.capability ?? "";+}++async function setCapability(capability: string): Promise<void> {+ await env.api.upsertSetting(+ "MCP",+ { mcp: { capability } },+ "value.mcp.capability"+ );+}++async function gotoMCPPage(page: Page): Promise<void> {+ await page.goto(`${env.baseURL}/integration/mcp`);+ await page.waitForLoadState("networkidle").catch(() => {});+ await expect(+ page.getByRole("heading", { name: "Access policy", exact: true })+ ).toBeVisible({ timeout: 10_000 });+}++// Matched on rendered text: an attribute-based locator would pass while no+// name reached the accessibility tree.+function chip(page: Page, mode: string) {+ return page.getByText(COPY.policy.current.replace("{{mode}}", mode));+}++// The row's list item, so a title that also appears inside a summary sentence+// cannot satisfy the locator.+function row(page: Page, title: string) {+ return page.locator("li").filter({ hasText: title }).first();+}++// Located by test id, not by label: the trigger's accessible name is the mode+// summary only while collapsed and the list heading once expanded, so a+// name-based locator cannot see the state it is meant to branch on — it would+// match nothing in the already-open case and block until the test timeout.+async function openLadder(page: Page): Promise<void> {+ const trigger = page.getByTestId("mcp-ladder-trigger");+ if ((await trigger.getAttribute("aria-expanded")) === "false") {+ await trigger.click();+ }+ await expect(trigger).toHaveAttribute("aria-expanded", "true");+ await expect(row(page, READ_ROWS[0])).toBeVisible();+}++test.beforeAll(async ({}, testInfo) => {+ env = loadTestEnv();+ await env.api.login(env.adminEmail, env.adminPassword);++ // Captured once per run, not once per attempt. A CI retry restarts the worker+ // and re-runs this hook, so an attempt that died after M3 persisted+ // Read-write would otherwise be re-snapshotted as the baseline — and teardown+ // would pin the shared workspace there, which is the outcome the snapshot+ // exists to prevent. The project output directory is cleared at the start of+ // a run and survives its retries.+ const baselinePath = join(testInfo.project.outputDir, "mcp-baseline.json");+ if (existsSync(baselinePath)) {+ originalMCPSetting = JSON.parse(readFileSync(baselinePath, "utf8"));+ return;+ }++ const setting = (await env.api.getSetting("MCP")) as {+ value?: { mcp?: Record<string, unknown> };+ } | null;+ // Workspace creation persists an MCP row (backend/store/workspace.go), so a+ // missing one means the read failed. Refuse to mutate a ceiling that could not+ // be snapshotted, rather than leave the workspace on whatever this suite last+ // wrote.+ if (!setting?.value?.mcp?.capability) {+ throw new Error(+ "could not read the workspace MCP setting; refusing to run, since teardown could not restore it"+ );+ }+ originalMCPSetting = setting.value.mcp;+ mkdirSync(testInfo.project.outputDir, { recursive: true });+ writeFileSync(baselinePath, JSON.stringify(originalMCPSetting));+});++test.afterAll(async () => {+ // Nothing was written if the snapshot never resolved, and PATCHing an absent+ // body would fail with "mcp setting is required" — a second, misleading error+ // stacked on the one that actually stopped the run.+ if (!originalMCPSetting) {+ return;+ }+ // Not best-effort otherwise: M3 persists Read-write on a shared server, and a+ // silent restore failure would broaden what every later suite's MCP session+ // may do. A failure here fails this run rather than poisoning the next one.+ await env.api.upsertSetting(+ "MCP",+ { mcp: originalMCPSetting },+ "value.mcp.capability"+ );+ expect(await readCapability()).toBe(originalMCPSetting.capability);+});++test.describe("MCP access policy capability ladder", () => {+ test("the chip is the subject of the view and the disclosure carries the description (M1)", async ({+ page,+ }) => {+ await setCapability("READ_ONLY");+ await gotoMCPPage(page);++ await expect(chip(page, "Read-only")).toBeVisible();+ await expect(page.getByText(READ_ONLY_SUMMARY)).toBeVisible();++ // The chip names the policy without an "In force" label, and the audit+ // fact belongs to the section description rather than to the current state.+ await expect(page.getByText("In force")).toHaveCount(0);+ await expect(+ page.getByText(/^MCP policy denials are streamed to stdout/)+ ).toHaveCount(0);+ await expect(page.getByText(COPY.policy.description)).toBeVisible();+ // Pinned as a literal, not read from the locale: this description carries+ // the page's only audit disclosure, so the claim has to survive a copy edit+ // that keeps the sentence and drops the clause.+ await expect(+ page.getByText(/policy refusals are streamed to stdout when audit logging/)+ ).toBeVisible();++ // Connect a client carries the authentication clause; nothing repeats it+ // as a separate alert.+ await expect(page.getByText("Authentication Required")).toHaveCount(0);+ await expect(page.getByText(COPY.connect.description)).toBeVisible();++ // Collapsed by default: the list is a disclosure, not the card.+ await expect(row(page, READ_ROWS[0])).toHaveCount(0);+ });++ test("the list shows every row under either mode, tagging only the mode's prefix (M2)", async ({+ page,+ }) => {+ await setCapability("READ_ONLY");+ await gotoMCPPage(page);+ await openLadder(page);++ // Rows a mode does not serve stay visible and muted, so comparing two+ // modes never needs a second surface.+ for (const title of [...READ_ROWS, ...WRITE_ROWS]) {+ await expect(row(page, title)).toBeVisible();+ }+ // The tier tag rides the served rows only, so the word "write" never+ // appears beside something Read-only allows.+ for (const title of READ_ROWS) {+ await expect(+ row(page, title).getByText(COPY.ladder.tier.read, { exact: true })+ ).toBeVisible();+ }+ for (const title of WRITE_ROWS) {+ await expect(+ row(page, title).getByText(COPY.ladder.tier.write, { exact: true })+ ).toHaveCount(0);+ }+ await expect(page.getByText(COPY.ladder.stops.read)).toBeVisible();+ await expect(page.getByText(COPY.ladder.stops.write)).toBeVisible();+ await expect(page.getByText(COPY.ladder.floor.text)).toBeVisible();++ // One second-level control for all eight rows, not eight expanders.+ await expect(page.getByText(EXPORT_DETAILS)).toHaveCount(0);+ await page.getByRole("button", { name: "Show details" }).click();+ await expect(page.getByText(EXPORT_DETAILS)).toBeVisible();+ await expect(+ page.getByText(COPY.ladder.row["read-workflow"].details)+ ).toBeVisible();++ });++ test("picking Read-write renders the post-save list, and Save persists it (M3)", async ({+ page,+ }) => {+ await setCapability("READ_ONLY");+ await gotoMCPPage(page);+ await page.getByRole("button", { name: "Edit policy" }).click();++ // The cards are an icon, the mode name and a three-word caption; the+ // "Best for" line is shown once, for the pick.+ await expect(+ page.getByText(COPY.policy.mode["read-only"].caption)+ ).toBeVisible();+ await expect(+ page.getByText(COPY.policy.mode["read-only"]["best-for"])+ ).toBeVisible();++ await page.getByText(COPY.policy.mode["read-write"].caption).click();+ await expect(+ page.getByText(COPY.policy.mode["read-write"]["best-for"])+ ).toBeVisible();++ // The disclosure line follows the pick: collapsed, it already describes+ // Read-write before anything is saved. No delta marks and no "adds N" —+ // the edit state renders exactly the view that saving will produce.+ await expect(page.getByText(READ_WRITE_SUMMARY)).toBeVisible();+ await openLadder(page);+ for (const title of WRITE_ROWS) {+ await expect(+ row(page, title).getByText(COPY.ladder.tier.write, { exact: true })+ ).toBeVisible();+ }++ // The footer names the transition rather than stating a general rule.+ await expect(+ page.getByText(+ COPY.policy["tightening-change"]+ .replace("{{from}}", COPY.policy.mode["read-only"].title)+ .replace("{{to}}", COPY.policy.mode["read-write"].title)+ )+ ).toBeVisible();++ await page.getByRole("button", { name: "Save policy" }).click();+ await expect.poll(readCapability, { timeout: 10_000 }).toBe("READ_WRITE");+ await expect(chip(page, "Read-write")).toBeVisible();+ // The ladder was opened above and stays open across the save, so the+ // trigger carries the heading rather than the summary. Asserting the view's+ // write rows proves it re-read the stored mode, which the summary string+ // would not.+ await expect(+ page.getByText(+ COPY.ladder.heading.replace(+ "{{mode}}",+ COPY.policy.mode["read-write"].title+ )+ )+ ).toBeVisible();+ for (const title of WRITE_ROWS) {+ await expect(+ row(page, title).getByText(COPY.ladder.tier.write, { exact: true })+ ).toBeVisible();+ }+ });+});diff --git a/frontend/vitest.setup.ts b/frontend/vitest.setup.tsindex 7ff2b98d92..778bf7be3d 100644--- a/frontend/vitest.setup.ts+++ b/frontend/vitest.setup.ts@@ -1,36 +1,48 @@import "@testing-library/jest-dom/vitest";import { afterEach, vi } from "vitest";-// App-wide guardrail against React infinite-render-loop bugs. Both signatures-// below are ALWAYS real bugs, never benign:+// App-wide guardrail against React bugs that only ever surface as a console+// warning, which the default reporter hides — so a broken component would+// otherwise pass its own tests. Every signature below is ALWAYS a real bug:// - "getSnapshot should be cached" — a `useSyncExternalStore` whose// getSnapshot returns a fresh value every call (this crashed the SQL-// Editor: GutterBar → useVueRoute → "Maximum update depth"). It is only a-// console warning, so a looping component would otherwise pass its tests.+// Editor: GutterBar → useVueRoute → "Maximum update depth").// - "Maximum update depth exceeded" — setState/store-write on every render.+// - "cannot be a descendant of" / "cannot be a child of" — invalid HTML+// nesting, e.g. a <div> inside a <p>, or a <tr> outside a <tbody>. The+// parser closes the ancestor early, so the rendered tree is not the one the+// component describes and hydration mismatches. React emits four such+// messages; the second string is a substring of the three that name a+// direct-parent rule, including both text-node cases.// Any test that renders a component triggering these now fails, so the whole-// existing render-test suite doubles as loop detection across the app.-const RENDER_LOOP_SIGNATURES = [+// existing render-test suite doubles as detection across the app. React dedupes+// the nesting warning per module, and vitest isolates modules per file, so a+// file reports its FIRST invalid nesting and not the rest — fix one and re-run+// rather than assuming the file is clean.+const FORBIDDEN_WARNING_SIGNATURES = ["getSnapshot should be cached","Maximum update depth exceeded",+ "cannot be a descendant of",+ "cannot be a child of",];-let renderLoopWarnings: string[] = [];+let forbiddenWarnings: string[] = [];const realConsoleError = console.error.bind(console);console.error = (...args: unknown[]) => {const message = args.map((arg) => String(arg)).join(" ");- if (RENDER_LOOP_SIGNATURES.some((sig) => message.includes(sig))) {- renderLoopWarnings.push(message);+ if (FORBIDDEN_WARNING_SIGNATURES.some((sig) => message.includes(sig))) {+ forbiddenWarnings.push(message);}realConsoleError(...args);};afterEach(() => {- if (renderLoopWarnings.length > 0) {- const captured = renderLoopWarnings;- renderLoopWarnings = [];+ if (forbiddenWarnings.length > 0) {+ const captured = forbiddenWarnings;+ forbiddenWarnings = [];throw new Error(- `React infinite-render-loop detected during this test. A useSyncExternalStore ` +- `getSnapshot must return a cached/stable value, and effects must not ` +- `setState unconditionally every render:\n${captured.join("\n")}`+ `React reported a defect this test would otherwise have passed through. ` ++ `A useSyncExternalStore getSnapshot must return a cached/stable value, ` ++ `effects must not setState unconditionally every render, and element ` ++ `nesting must be valid HTML:\n${captured.join("\n")}`);}});diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex 4e2af63807..d623f72688 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -24438,6 +24438,9 @@ components:between, EXCLUDED and FORBIDDEN are served by no ceiling, and an unclassifiedmethod is refused rather than served. Annotating a method is therefore achange to what an MCP session can reach, taking effect on the next request.+ READ and WRITE methods are also disclosed to workspace admins, as capability+ rows on the Access policy page, so annotating a method changes what the+ product promises as well as what it serves.bytebase.v1.MCPSetting:type: objectproperties:diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex f07a4d4430..a6d4dd43de 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -902,6 +902,9 @@ WRITE are the serving classes the workspace's MCP capability ceiling selectsbetween, EXCLUDED and FORBIDDEN are served by no ceiling, and an unclassifiedmethod is refused rather than served. Annotating a method is therefore achange to what an MCP session can reach, taking effect on the next request.+READ and WRITE methods are also disclosed to workspace admins, as capability+rows on the Access policy page, so annotating a method changes what the+product promises as well as what it serves.| Name | Number | Description || ---- | ------ | ----------- |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex a7cb0aa114..2889d81231 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -3468,7 +3468,7 @@ retiring an enum value costs a reserved number for nothing.</p></td></table><h3 id="bytebase.v1.MCPMethodClass">MCPMethodClass</h3>- <p>Classification of an RPC for MCP (AI agent) sessions. The effective</p><p>authorization of an MCP session is this classification intersected with the</p><p>caller's own RBAC: it can only ever narrow what the human could do, never</p><p>widen it.</p><p>Every value is enforced, at the gate on the internal MCP chain. READ and</p><p>WRITE are the serving classes the workspace's MCP capability ceiling selects</p><p>between, EXCLUDED and FORBIDDEN are served by no ceiling, and an unclassified</p><p>method is refused rather than served. Annotating a method is therefore a</p><p>change to what an MCP session can reach, taking effect on the next request.</p>+ <p>Classification of an RPC for MCP (AI agent) sessions. The effective</p><p>authorization of an MCP session is this classification intersected with the</p><p>caller's own RBAC: it can only ever narrow what the human could do, never</p><p>widen it.</p><p>Every value is enforced, at the gate on the internal MCP chain. READ and</p><p>WRITE are the serving classes the workspace's MCP capability ceiling selects</p><p>between, EXCLUDED and FORBIDDEN are served by no ceiling, and an unclassified</p><p>method is refused rather than served. Annotating a method is therefore a</p><p>change to what an MCP session can reach, taking effect on the next request.</p><p>READ and WRITE methods are also disclosed to workspace admins, as capability</p><p>rows on the Access policy page, so annotating a method changes what the</p><p>product promises as well as what it serves.</p><table class="enum-table"><thead><tr><td>Name</td><td>Number</td><td>Description</td></tr>diff --git a/proto/v1/v1/annotation.proto b/proto/v1/v1/annotation.protoindex d93e5501ca..69c3195e28 100644--- a/proto/v1/v1/annotation.proto+++ b/proto/v1/v1/annotation.proto@@ -74,6 +74,9 @@ enum AuthMethod {// between, EXCLUDED and FORBIDDEN are served by no ceiling, and an unclassified// method is refused rather than served. Annotating a method is therefore a// change to what an MCP session can reach, taking effect on the next request.+// READ and WRITE methods are also disclosed to workspace admins, as capability+// rows on the Access policy page, so annotating a method changes what the+// product promises as well as what it serves.enum MCPMethodClass {// Not yet classified, and refused. CI rejects this value on any v1 RPC, so// it survives only inside a build that has not been linted: a new RPC is