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): let MCP sessions approve and reject issues after the user confirms (#21593)
Vincent Huangbddc8ca1f367
diff --git a/backend/api/auth/mcp_confirmation.go b/backend/api/auth/mcp_confirmation.gonew file mode 100644index 0000000000..ae7b4c5b6f--- /dev/null+++ b/backend/api/auth/mcp_confirmation.go@@ -0,0 +1,35 @@+package auth++import (+ "context"+ "time"+)++// MCPConfirmedDecision is one issue decision the user confirmed in their MCP+// client. The MCP gate serves IssueService/ApproveIssue and RejectIssue only to+// a request whose context carries one naming that procedure and issue.+type MCPConfirmedDecision struct {+ // Procedure is the connect procedure confirmed, such as+ // /bytebase.v1.IssueService/ApproveIssue.+ Procedure string+ // Issue is the issue's resource name: projects/{project}/issues/{issue}.+ Issue string+ // IssueUpdateTime is the issue's update time when the user confirmed. The+ // review workflow refuses the decision when it no longer matches.+ IssueUpdateTime time.Time+}++// mcpConfirmedDecisionKey is unexported so that only code in this process can+// set the value; nothing a request carries can.+type mcpConfirmedDecisionKey struct{}++// WithMCPConfirmedDecision marks ctx as carrying a decision the user confirmed.+func WithMCPConfirmedDecision(ctx context.Context, decision MCPConfirmedDecision) context.Context {+ return context.WithValue(ctx, mcpConfirmedDecisionKey{}, decision)+}++// MCPConfirmedDecisionFromContext returns the confirmed decision ctx carries.+func MCPConfirmedDecisionFromContext(ctx context.Context) (MCPConfirmedDecision, bool) {+ decision, ok := ctx.Value(mcpConfirmedDecisionKey{}).(MCPConfirmedDecision)+ return decision, ok+}diff --git a/backend/api/mcp/openapi_index.go b/backend/api/mcp/openapi_index.goindex aeac20fa43..74b98aaa5a 100644--- a/backend/api/mcp/openapi_index.go+++ b/backend/api/mcp/openapi_index.go@@ -75,8 +75,8 @@ type OpenAPIIndex struct {// hiddenEndpoints holds every endpoint no MCP capability ceiling serves —// FORBIDDEN and EXCLUDED alike — resolvable through byOperation so a// direct call still gets the gate's actionable denial, but reachable by no- // discovery path. That is 114 of the 211 classified RPCs, and 13 services- // whose every method is refused leave Services() entirely.+ // discovery path. A service whose every method is refused leaves+ // Services() entirely.hiddenEndpoints []EndpointInfobyOperation map[string]*EndpointInfobyService map[string][]*EndpointInfodiff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.goindex 1299483a90..ba09ecff5e 100644--- a/backend/api/mcp/server.go+++ b/backend/api/mcp/server.go@@ -235,6 +235,7 @@ func (s *Server) registerTools() {s.registerQueryTool()s.registerSchemaTool()s.registerChangeTool()+ s.registerDecideIssueTool()s.registerReauthorizeTool()}diff --git a/backend/api/mcp/tool_change.go b/backend/api/mcp/tool_change.goindex 5600713ebe..1130fe13c7 100644--- a/backend/api/mcp/tool_change.go+++ b/backend/api/mcp/tool_change.go@@ -29,9 +29,6 @@ const (// nextAction enum constants.const (- // The agent waits; it does not approve. ApproveIssue is FORBIDDEN to MCP- // sessions, so naming it here would send the agent at a call that is- // refused. The issue link in the output is what a human follows instead.nextActionAwaitApproval = "AWAIT_HUMAN_APPROVAL"nextActionCreateRollout = "CREATE_ROLLOUT"nextActionMonitorRollout = "MONITOR_ROLLOUT"@@ -151,6 +148,7 @@ propose_database_change(database="app", sql="UPDATE orders SET status='shipped'- Plan checks run automatically; results included in response when available.- Requires bb.sheets.create, bb.plans.create, bb.issues.create permissions.- If createRollout=true but policy gates aren't satisfied, returns success with rolloutCreated=false and a reason.+- nextAction AWAIT_HUMAN_APPROVAL means the issue waits for its approvers. If the user is one of them, decide_issue asks them to confirm in this client and then approves; otherwise share links.issue with an approver.- Masked data: a masked column reads back as "******". That is a placeholder, not a value anything holds. Any change containing it is refused, because writing it back would overwrite the real value. Ask a human to make the change in the Bytebase console instead.`diff --git a/backend/api/mcp/tool_decide.go b/backend/api/mcp/tool_decide.gonew file mode 100644index 0000000000..7b9d49ae8e--- /dev/null+++ b/backend/api/mcp/tool_decide.go@@ -0,0 +1,743 @@+package mcp++import (+ "bytes"+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "strconv"+ "strings"+ "time"+ "unicode/utf8"++ "github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/pkg/errors"+ spb "google.golang.org/genproto/googleapis/rpc/status"+ "google.golang.org/grpc/codes"++ "github.com/bytebase/bytebase/backend/api/auth"+ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/component/audit"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"+ "github.com/bytebase/bytebase/backend/utils"+)++// DecideIssueInput is the input for the decide_issue tool.+type DecideIssueInput struct {+ Issue string `json:"issue"`+ Decision string `json:"decision"`+ Comment string `json:"comment,omitempty"`+}++// DecideIssueOutput is the output for the decide_issue tool.+type DecideIssueOutput struct {+ Issue string `json:"issue"`+ Decision string `json:"decision"`+ ApprovalStatus string `json:"approvalStatus"`+ Status string `json:"status"`+ Link string `json:"link"`+}++const decideIssueDescription = `Approve or reject a Bytebase issue at its current approval step. The user confirms the decision in this client first.++| Parameter | Required | Description |+|-----------|----------|-------------|+| issue | Yes | Issue name, e.g. "projects/hr/issues/42" |+| decision | Yes | "approve" or "reject" |+| comment | No | Note recorded with the decision |++The tool shows the user what the issue changes and asks them to confirm in a form. It decides only when they accept; declining or cancelling changes nothing. A client that cannot show the form gets the issue's link, to decide it in the Bytebase console instead. Do not ask in chat first: the form is the question.++It decides database changes and access requests. Role requests stay in the Bytebase console, because approving one grants a project role.++The approval rules decide who may approve, as in the console: the user must hold the role of the current step, and approving their own issue, or a plan they last changed, is refused unless the project allows it.++This is the only way to decide an issue over MCP; call_api refuses IssueService/ApproveIssue and RejectIssue.`++// confirmDecisionRequestID is the ID the confirmation is filed under, and+// confirmDecisionField the form field it asks for. The client echoes both back,+// so the two halves of one tool call must agree on them.+const (+ confirmDecisionRequestID = "confirm"+ confirmDecisionField = "confirm"+)++// decisionNote opens the comment recorded with every decision. It claims the+// client confirmed, not that a person did: a hook in the client can answer.+const decisionNote = "Decided over MCP; the decision was confirmed in the MCP client."++// confirmationStatePurpose names this use of the server secret, so the key+// that signs a confirmation's request state signs nothing else.+const confirmationStatePurpose = "bb.mcp.decide_issue.request_state"++const (+ // maxDescribedSpecs bounds how many plan specs the confirmation lists.+ maxDescribedSpecs = 3+ // maxStatementPreview bounds a statement in the confirmation, in runes.+ maxStatementPreview = 300+)++func (s *Server) registerDecideIssueTool() {+ mcp.AddTool(s.mcpServer, &mcp.Tool{+ Name: "decide_issue",+ Description: decideIssueDescription,+ }, s.handleDecideIssue)+}++// issueDecision is a validated decide_issue request.+type issueDecision struct {+ project string+ issue string+ procedure string+ comment string+}++func (d *issueDecision) verb() string {+ if d.procedure == v1connect.IssueServiceApproveIssueProcedure {+ return "approve"+ }+ return "reject"+}++func (d *issueDecision) pastTense() string {+ if d.procedure == v1connect.IssueServiceApproveIssueProcedure {+ return "approved"+ }+ return "rejected"+}++func (s *Server) handleDecideIssue(ctx context.Context, req *mcp.CallToolRequest, input DecideIssueInput) (*mcp.CallToolResult, any, error) {+ decision, err := parseIssueDecision(input)+ if err != nil {+ return formatToolError(err), nil, nil+ }+ link := s.issueLink(ctx, decision.issue)++ // Checked before any answer is read: a client that declared no form cannot+ // have shown one, so an answer it sends is not a confirmation.+ if req == nil || req.Session == nil || !clientSupportsElicitation(req.Session) {+ return formatToolError(&toolError{+ Code: "CONFIRMATION_UNAVAILABLE",+ Message: fmt.Sprintf("this MCP client cannot show the confirmation form decide_issue needs, so %s was not %s and nothing changed",+ decision.issue, decision.pastTense()),+ Suggestion: "decide the issue signed in to the Bytebase console: " + link,+ }), nil, nil+ }++ // Read on both rounds, so a type this tool does not decide is refused before+ // any answer is acted on, and an answer is acted on only while the issue+ // reads as it did when the user was asked.+ var issue issueView+ if err := s.readResource(ctx, "/bytebase.v1.IssueService/GetIssue", decision.issue, "get issues", "bb.issues.get", &issue); err != nil {+ return formatToolError(err), nil, nil+ }+ if refusal := refuseIssueType(issue, decision, link); refusal != nil {+ s.recordRefusedDecision(ctx, decision, refusal.Message)+ return formatToolError(refusal), nil, nil+ }+ view, err := s.readConfirmationView(ctx, decision, issue)+ if err != nil {+ return formatToolError(err), nil, nil+ }+ digest, err := view.digest()+ if err != nil {+ return formatToolError(err), nil, nil+ }++ // An answer counts only with the request state this server signed when it+ // asked. A client can send an answer on a call that was never asked, so+ // without that state the call is asked like a first one.+ if response, state, answered := confirmationAnswer(req); answered {+ if asked, signed := s.verifyConfirmationState(ctx, decision, state); signed {+ result, output := s.decideOnAnswer(ctx, decision, response, bytes.Equal(asked, digest), issue.UpdateTime, link)+ return result, output, nil+ }+ }++ message, err := s.describeIssueDecision(ctx, decision, view)+ if err != nil {+ return formatToolError(err), nil, nil+ }+ // The same multi round-trip shape as elicitDatabaseChoice: the SDK elicits+ // within this tools/call and re-invokes the handler with the answer and the+ // request state. A client on the 2026-07-28 protocol answers and echoes the+ // state itself.+ return &mcp.CallToolResult{+ RequestState: s.signConfirmationState(ctx, decision, digest),+ InputRequests: mcp.InputRequestMap{+ confirmDecisionRequestID: &mcp.ElicitParams{+ Mode: "form",+ Message: message,+ RequestedSchema: map[string]any{+ "type": "object",+ "properties": map[string]any{+ confirmDecisionField: map[string]any{+ "type": "boolean",+ "title": fmt.Sprintf("%s this issue", capitalize(decision.verb())),+ "description": fmt.Sprintf("Check to %s the issue described above. Leaving it unchecked, declining or cancelling changes nothing.", decision.verb()),+ },+ },+ "required": []string{confirmDecisionField},+ },+ },+ },+ }, nil, nil+}++func parseIssueDecision(input DecideIssueInput) (*issueDecision, error) {+ project, _, err := common.GetProjectIDIssueUID(input.Issue)+ if err != nil {+ return nil, &toolError{+ Code: "INVALID_ARGUMENT",+ Message: fmt.Sprintf("invalid issue %q", input.Issue),+ Suggestion: "pass the issue name, e.g. projects/hr/issues/42",+ }+ }+ decision := &issueDecision{project: project, issue: input.Issue, comment: strings.TrimSpace(input.Comment)}+ switch strings.ToLower(strings.TrimSpace(input.Decision)) {+ case "approve":+ decision.procedure = v1connect.IssueServiceApproveIssueProcedure+ case "reject":+ decision.procedure = v1connect.IssueServiceRejectIssueProcedure+ default:+ return nil, &toolError{+ Code: "INVALID_ARGUMENT",+ Message: fmt.Sprintf("invalid decision %q", input.Decision),+ Suggestion: `allowed values: "approve", "reject"`,+ }+ }+ return decision, nil+}++// refuseIssueType serves the issue types this tool decides. It is an+// allow-list, so a type added later is refused until someone decides about it.+// A role request stays in the console: approving one grants a project role.+func refuseIssueType(issue issueView, decision *issueDecision, link string) *toolError {+ switch issue.Type {+ case "DATABASE_CHANGE", "ACCESS_GRANT":+ return nil+ case "ROLE_GRANT":+ return &toolError{+ Code: "ROLE_GRANT_NOT_SUPPORTED",+ Message: fmt.Sprintf("approving a role request grants a project role, which MCP does not do yet, so %s was not %s and nothing changed",+ decision.issue, decision.pastTense()),+ Suggestion: "decide it signed in to the Bytebase console: " + link,+ }+ default:+ return &toolError{+ Code: "ISSUE_TYPE_NOT_SUPPORTED",+ Message: fmt.Sprintf("decide_issue does not decide %q issues, so %s was not %s and nothing changed",+ issue.Type, decision.issue, decision.pastTense()),+ Suggestion: "decide it signed in to the Bytebase console: " + link,+ }+ }+}++// recordRefusedDecision writes the audit row for a decision this tool refuses+// itself. The refusal comes before any decision request, so no connect+// interceptor sees it.+func (s *Server) recordRefusedDecision(ctx context.Context, decision *issueDecision, reason string) {+ delegated, _ := getDelegatedIdentity(ctx)+ row := &storepb.AuditLog{+ Parent: common.FormatProject(decision.project),+ Method: decision.procedure,+ Resource: decision.issue,+ User: common.FormatUserEmail(getUserEmail(ctx)),+ Status: &spb.Status{Code: int32(codes.PermissionDenied), Message: reason},+ RequestMetadata: &storepb.RequestMetadata{CallerIp: getCallerIP(ctx)},+ McpDelegation: &storepb.MCPDelegation{+ Scope: delegated.Scope,+ Resource: delegated.Resource,+ ClientId: delegated.ClientID,+ CorrelationId: delegated.CorrelationID,+ },+ }+ audit.RecordOutOfBandAudit(ctx, s.store, s.profile.RuntimeEnableAuditLogStdout.Load(), getWorkspaceID(ctx), row)+}++// confirmationAnswer returns the answer and the request state this call+// carries, if it carries an answer.+func confirmationAnswer(req *mcp.CallToolRequest) (mcp.InputResponse, string, bool) {+ if req.Params == nil {+ return nil, "", false+ }+ response, answered := req.Params.InputResponses[confirmDecisionRequestID]+ return response, req.Params.RequestState, answered+}++// decideOnAnswer acts on the answer to a form this server sent. Only an+// accepted form with the box checked decides, and only while what the user+// was asked about still matches the issue. A decline is reported before a+// change, so a user who said no is not asked again.+func (s *Server) decideOnAnswer(ctx context.Context, decision *issueDecision, response mcp.InputResponse, unchanged bool, issueUpdateTime, link string) (*mcp.CallToolResult, any) {+ if confirmed, why := confirmationOutcome(response); !confirmed {+ return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf(+ "Not %s: %s, so nothing changed. Do not retry unless the user asks.\nIssue: %s",+ decision.pastTense(), why, link)}}}, nil+ }+ if !unchanged {+ return formatToolError(&toolError{+ Code: "STALE_CONFIRMATION",+ Message: fmt.Sprintf("what the user confirmed no longer matches %s as it is now, so it was not %s and nothing changed",+ decision.issue, decision.pastTense()),+ Suggestion: "call decide_issue again to ask the user about the issue as it is now",+ }), nil+ }+ return s.applyIssueDecision(ctx, decision, issueUpdateTime, link)+}++// signConfirmationState returns the request state the form is sent with: a+// digest of what the user is asked about, signed together with who asks,+// through which client, and which decision on which issue.+func (s *Server) signConfirmationState(ctx context.Context, decision *issueDecision, digest []byte) string {+ return base64.RawURLEncoding.EncodeToString(digest) + "." ++ base64.RawURLEncoding.EncodeToString(s.confirmationMAC(ctx, decision, digest))+}++// verifyConfirmationState returns the digest a request state carries, and+// whether this server signed it for this caller and this decision.+func (s *Server) verifyConfirmationState(ctx context.Context, decision *issueDecision, state string) ([]byte, bool) {+ encodedDigest, encodedMAC, found := strings.Cut(state, ".")+ if !found {+ return nil, false+ }+ digest, err := base64.RawURLEncoding.DecodeString(encodedDigest)+ if err != nil {+ return nil, false+ }+ mac, err := base64.RawURLEncoding.DecodeString(encodedMAC)+ if err != nil {+ return nil, false+ }+ return digest, hmac.Equal(mac, s.confirmationMAC(ctx, decision, digest))+}++func (s *Server) confirmationMAC(ctx context.Context, decision *issueDecision, digest []byte) []byte {+ key := hmac.New(sha256.New, []byte(s.secret))+ _, _ = key.Write([]byte(confirmationStatePurpose))+ signed := strings.Join([]string{getWorkspaceID(ctx), getUserEmail(ctx), getOAuth2ClientID(ctx), decision.procedure, decision.issue, ""}, "\x00")+ mac := hmac.New(sha256.New, key.Sum(nil))+ _, _ = mac.Write(append([]byte(signed), digest...))+ return mac.Sum(nil)+}++// applyIssueDecision records the confirmed decision.+func (s *Server) applyIssueDecision(ctx context.Context, decision *issueDecision, issueUpdateTime, link string) (*mcp.CallToolResult, any) {+ confirmedAt, err := time.Parse(time.RFC3339Nano, issueUpdateTime)+ if err != nil {+ return formatToolError(errors.Wrapf(err, "failed to read the update time of %s, so it was not %s", decision.issue, decision.pastTense())), nil+ }+ comment := decisionNote+ if decision.comment != "" {+ comment += "\n\n" + decision.comment+ }+ confirmedCtx := auth.WithMCPConfirmedDecision(ctx, auth.MCPConfirmedDecision{+ Procedure: decision.procedure,+ Issue: decision.issue,+ IssueUpdateTime: confirmedAt,+ })+ resp, err := s.apiRequest(confirmedCtx, decision.procedure, map[string]any{+ "name": decision.issue,+ "comment": comment,+ })+ if err != nil {+ return formatToolError(errors.Wrapf(err, "failed to %s %s", decision.verb(), decision.issue)), nil+ }+ if resp.Status >= 400 {+ return formatToolError(errors.Errorf("failed to %s %s: HTTP %d: %s; check the issue's current state: %s",+ decision.verb(), decision.issue, resp.Status, parseError(resp.Body), link)), nil+ }++ var decided issueView+ if err := json.Unmarshal(resp.Body, &decided); err != nil {+ return formatToolError(errors.Wrapf(err, "%s %s, but its response could not be read", decision.pastTense(), decision.issue)), nil+ }+ output := &DecideIssueOutput{+ Issue: decision.issue,+ Decision: decision.verb(),+ ApprovalStatus: decided.ApprovalStatus,+ Status: decided.Status,+ Link: link,+ }+ return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf(+ "%s %s. Approval: %s. Issue status: %s.\nIssue: %s",+ capitalize(decision.pastTense()), decision.issue, describeApprovalStep(decided), decided.Status, link)}}}, output+}++// confirmationOutcome reports whether the answer confirms the decision, and if+// not, why, in words the result can carry.+func confirmationOutcome(response mcp.InputResponse) (bool, string) {+ elicited, ok := response.(*mcp.ElicitResult)+ if !ok || elicited == nil {+ return false, "the confirmation answer could not be read"+ }+ switch elicited.Action {+ case "accept":+ if confirmed, ok := elicited.Content[confirmDecisionField].(bool); ok && confirmed {+ return true, ""+ }+ return false, "the form was submitted without the confirmation checked"+ case "decline":+ return false, "the user declined"+ case "cancel":+ return false, "the user cancelled"+ default:+ return false, fmt.Sprintf("the confirmation answer %q is not one Bytebase acts on", elicited.Action)+ }+}++// issueView is the part of an Issue the confirmation and the result read.+type issueView struct {+ Name string `json:"name"`+ Title string `json:"title"`+ Type string `json:"type"`+ Status string `json:"status"`+ Creator string `json:"creator"`+ Plan string `json:"plan"`+ AccessGrant string `json:"accessGrant"`+ ApprovalStatus string `json:"approvalStatus"`+ ApprovalTemplate struct {+ Flow struct {+ Roles []string `json:"roles"`+ } `json:"flow"`+ } `json:"approvalTemplate"`+ Approvers []struct {+ Status string `json:"status"`+ } `json:"approvers"`+ UpdateTime string `json:"updateTime"`+}++type planView struct {+ UpdateTime string `json:"updateTime"`+ Specs []struct {+ ChangeDatabaseConfig *struct {+ Targets []string `json:"targets"`+ Sheet string `json:"sheet"`+ Release string `json:"release"`+ } `json:"changeDatabaseConfig"`+ CreateDatabaseConfig *createDatabaseView `json:"createDatabaseConfig"`+ } `json:"specs"`+}++type createDatabaseView struct {+ Target string `json:"target"`+ Database string `json:"database"`+ Cluster string `json:"cluster"`+ Owner string `json:"owner"`+ Table string `json:"table"`+ CharacterSet string `json:"characterSet"`+ Collation string `json:"collation"`+}++type sheetView struct {+ Content string `json:"content"`+ ContentSize int64 `json:"contentSize,string"`+}++type accessGrantView struct {+ Targets []string `json:"targets"`+ Schema string `json:"schema"`+ Container string `json:"container"`+ Query string `json:"query"`+ Unmask bool `json:"unmask"`+ Export bool `json:"export"`+ ExpireTime string `json:"expireTime"`+ TTL string `json:"ttl"`+ UpdateTime string `json:"updateTime"`+}++// confirmationView is what the user is asked to confirm: the issue, the plan or+// access grant behind it, and the comment the decision records. The request+// state carries a digest of all of it. A change to the issue's approval, the+// plan's specs or the grant also changes that resource's update time, so the+// digest changes even when the changed field is not shown. Statements are left+// out: a sheet's name is its content hash (GetProjectResourceIDSheetSha256), so+// the plan's specs already pin every statement, shown or not.+type confirmationView struct {+ Issue issueView `json:"issue"`+ Plan *planView `json:"plan,omitempty"`+ Grant *accessGrantView `json:"grant,omitempty"`+ Comment string `json:"comment,omitempty"`+}++func (s *Server) readConfirmationView(ctx context.Context, decision *issueDecision, issue issueView) (*confirmationView, error) {+ view := &confirmationView{Issue: issue, Comment: decision.comment}+ switch {+ case issue.AccessGrant != "":+ grant, err := s.readAccessGrant(ctx, decision, issue)+ if err != nil {+ return nil, err+ }+ view.Grant = grant+ case issue.Plan != "":+ view.Plan = &planView{}+ if err := s.readResource(ctx, "/bytebase.v1.PlanService/GetPlan", issue.Plan, "get plans", "bb.plans.get", view.Plan); err != nil {+ return nil, err+ }+ default:+ }+ return view, nil+}++// readAccessGrant reads the grant behind an access request. A requester may+// lack bb.accessGrants.get, as project developers do, so the caller's own+// request is read through SearchMyAccessGrants, as the console's issue page+// reads it. The grant and its issue share a creator (CreateAccessGrant).+func (s *Server) readAccessGrant(ctx context.Context, decision *issueDecision, issue issueView) (*accessGrantView, error) {+ if issue.Creator != common.FormatUserEmail(getUserEmail(ctx)) {+ grant := &accessGrantView{}+ if err := s.readResource(ctx, "/bytebase.v1.AccessGrantService/GetAccessGrant", issue.AccessGrant, "get access grants", "bb.accessGrants.get", grant); err != nil {+ return nil, err+ }+ return grant, nil+ }+ resp, err := s.apiRequest(ctx, "/bytebase.v1.AccessGrantService/SearchMyAccessGrants", map[string]any{+ "parent": common.FormatProject(decision.project),+ "filter": fmt.Sprintf("name == %q", issue.AccessGrant),+ })+ if err != nil {+ return nil, errors.Wrapf(err, "failed to read %s", issue.AccessGrant)+ }+ if err := checkAPIResponse(resp, "search your access grants", "bb.accessGrants.get"); err != nil {+ return nil, err+ }+ var mine struct {+ AccessGrants []accessGrantView `json:"accessGrants"`+ }+ if err := json.Unmarshal(resp.Body, &mine); err != nil {+ return nil, errors.Wrapf(err, "failed to parse %s", issue.AccessGrant)+ }+ if len(mine.AccessGrants) != 1 {+ return nil, errors.Errorf("%s is not among the access grants you requested", issue.AccessGrant)+ }+ return &mine.AccessGrants[0], nil+}++func (v *confirmationView) digest() ([]byte, error) {+ payload, err := json.Marshal(v)+ if err != nil {+ return nil, errors.Wrap(err, "failed to digest the confirmation")+ }+ sum := sha256.Sum256(payload)+ return sum[:], nil+}++// describeIssueDecision builds the confirmation message: the decision, the+// issue, what approving it would let happen, the step it decides, and the+// comment it records. Every value taken from the issue or from the agent enters+// through %q, which escapes line breaks, so no value can pose as a line of the+// message. The message carries no link: the MCP specification asks servers not+// to put clickable URLs in a form.+//+// Claude Code 2.1.302 shows four lines of a message, or three and "… (+N more+// lines)", and cuts each line six columns short of the terminal width. So each+// line does one job, its bounded part first: the decision; the targets, counted+// before they are named; the statement; then the approval step, requester and+// comment. A plan with several changes shows its first change and the total.+//+// It fails closed: if any part cannot be read, nothing is asked.+func (s *Server) describeIssueDecision(ctx context.Context, decision *issueDecision, view *confirmationView) (string, error) {+ issue := view.Issue+ question := fmt.Sprintf("%s issue %q titled %q", capitalize(decision.verb()), issue.Name, issue.Title)+ if email := getUserEmail(ctx); email != "" {+ question += " as " + email+ }+ var details []string+ last := fmt.Sprintf("Approval: %s. Requested by %q.",+ describeApprovalStep(issue), strings.TrimPrefix(issue.Creator, common.UserNamePrefix))+ switch {+ case view.Grant != nil:+ var terms string+ details, terms = describeAccessGrant(view.Grant)+ last = terms + " " + last+ case view.Plan != nil:+ var err error+ if details, err = s.describePlan(ctx, view.Plan); err != nil {+ return "", err+ }+ default:+ }+ if view.Comment != "" {+ last += fmt.Sprintf(" Comment: %q", view.Comment)+ }+ lines := append([]string{question + "?"}, details...)+ return strings.Join(append(lines, last), "\n"), nil+}++func (s *Server) describePlan(ctx context.Context, plan *planView) ([]string, error) {+ var lines []string+ for i, spec := range plan.Specs {+ if i == maxDescribedSpecs {+ lines = append(lines, fmt.Sprintf("(%d of %d changes shown)", maxDescribedSpecs, len(plan.Specs)))+ break+ }+ change, create := "Change", "Create database"+ if len(plan.Specs) > 1 {+ change = fmt.Sprintf("Change %d of %d", i+1, len(plan.Specs))+ create = change + ": create database"+ }+ switch {+ case spec.ChangeDatabaseConfig != nil:+ config := spec.ChangeDatabaseConfig+ what := fmt.Sprintf("Release %q (statements not shown)", config.Release)+ if config.Sheet != "" {+ statement, err := s.statementPreview(ctx, config.Sheet)+ if err != nil {+ return nil, err+ }+ what = statement+ }+ lines = append(lines, fmt.Sprintf("%s on %s", change, describeTargets(config.Targets, "targets")), what)+ case spec.CreateDatabaseConfig != nil:+ lines = append(lines, describeNewDatabase(create, spec.CreateDatabaseConfig)...)+ default:+ }+ }+ return lines, nil+}++func describeNewDatabase(create string, config *createDatabaseView) []string {+ lines := []string{fmt.Sprintf("%s %q on %q", create, config.Database, config.Target)}+ var settings []string+ for _, setting := range []struct{ name, value string }{+ {"cluster", config.Cluster},+ {"owner", config.Owner},+ {"table", config.Table},+ {"character set", config.CharacterSet},+ {"collation", config.Collation},+ } {+ if setting.value != "" {+ settings = append(settings, fmt.Sprintf("%s %q", setting.name, setting.value))+ }+ }+ if len(settings) > 0 {+ lines = append(lines, capitalize(strings.Join(settings, ", ")))+ }+ return lines+}++// statementPreview quotes the start of a change's statement. When it leaves the+// rest out, "(partial)" comes first and the statement's full size last. GetSheet+// cuts content it returns at common.MaxSheetSize, so the size comes from+// contentSize.+func (s *Server) statementPreview(ctx context.Context, sheet string) (string, error) {+ var view sheetView+ if err := s.readResource(ctx, "/bytebase.v1.SheetService/GetSheet", sheet, "get sheets", "bb.sheets.get", &view); err != nil {+ return "", err+ }+ content, err := base64.StdEncoding.DecodeString(view.Content)+ if err != nil {+ return "", errors.Wrapf(err, "failed to decode sheet %s", sheet)+ }+ shown, cut := common.TruncateString(string(content), maxStatementPreview)+ if !cut {+ return fmt.Sprintf("SQL: %q", shown), nil+ }+ return fmt.Sprintf("SQL (partial): %q (first %d characters of %d bytes)", shown, maxStatementPreview, view.ContentSize), nil+}++// describeAccessGrant returns the grant's scope and query lines, and its terms+// for the approval line. The schema and container go on the scope line: the+// requester can set them to any length, and nothing may push the query out.+func describeAccessGrant(grant *accessGrantView) ([]string, string) {+ var qualifiers []string+ if grant.Schema != "" {+ qualifiers = append(qualifiers, fmt.Sprintf("schema %q", grant.Schema))+ }+ if grant.Container != "" {+ qualifiers = append(qualifiers, fmt.Sprintf("container %q", grant.Container))+ }+ scope := "Access on " + describeTargets(grant.Targets, "databases", qualifiers...)+ query := fmt.Sprintf("Query: %q", grant.Query)+ if shown, cut := common.TruncateString(grant.Query, maxStatementPreview); cut {+ query = fmt.Sprintf("Query (partial): %q (first %d of %d characters)", shown, maxStatementPreview, utf8.RuneCountInString(grant.Query))+ }+ terms := fmt.Sprintf("Unmasked: %s. Export: %s.", yesNo(grant.Unmask), yesNo(grant.Export))+ switch {+ case grant.ExpireTime != "":+ terms += fmt.Sprintf(" Expires: %q.", grant.ExpireTime)+ case grant.TTL != "":+ terms += fmt.Sprintf(" Expires: %q after approval.", readableDuration(grant.TTL))+ default:+ }+ return []string{scope, query}, terms+}++// describeTargets names targets and their qualifiers. One target's name comes+// first, so a long name cuts its qualifiers, not itself. With several targets,+// the count and the qualifiers come before the names, so a line cut short keeps+// them.+func describeTargets(targets []string, noun string, qualifiers ...string) string {+ if len(targets) == 1 {+ return strings.Join(append([]string{strconv.Quote(targets[0])}, qualifiers...), ", ")+ }+ head := append([]string{fmt.Sprintf("%d %s", len(targets), noun)}, qualifiers...)+ return strings.Join(head, ", ") + ": " + quoteAll(targets)+}++// readResource reads one resource by name from the internal API.+func (s *Server) readResource(ctx context.Context, path, name, operation, permission string, out any) error {+ resp, err := s.apiRequest(ctx, path, map[string]any{"name": name})+ if err != nil {+ return errors.Wrapf(err, "failed to read %s", name)+ }+ if err := checkAPIResponse(resp, operation, permission); err != nil {+ return err+ }+ if err := json.Unmarshal(resp.Body, out); err != nil {+ return errors.Wrapf(err, "failed to parse %s", name)+ }+ return nil+}++func (s *Server) issueLink(ctx context.Context, issue string) string {+ externalURL, _ := utils.GetEffectiveExternalURL(ctx, s.store, s.profile, getWorkspaceID(ctx))+ return buildResourceURL(externalURL, issue)+}++// describeApprovalStep names the step a decision would record. It mirrors+// utils.FindNextPendingRole: one approver per step, in flow order.+func describeApprovalStep(issue issueView) string {+ roles := issue.ApprovalTemplate.Flow.Roles+ if issue.ApprovalStatus == "PENDING" && len(issue.Approvers) < len(roles) {+ return fmt.Sprintf("step %d of %d, role %q", len(issue.Approvers)+1, len(roles), roles[len(issue.Approvers)])+ }+ if issue.ApprovalStatus == "" {+ return "not started"+ }+ return strconv.Quote(issue.ApprovalStatus)+}++func quoteAll(values []string) string {+ quoted := make([]string, len(values))+ for i, value := range values {+ quoted[i] = strconv.Quote(value)+ }+ return strings.Join(quoted, ", ")+}++// readableDuration renders a protojson duration such as "3600s" as "1h0m0s".+func readableDuration(protoDuration string) string {+ if d, err := time.ParseDuration(protoDuration); err == nil {+ return d.String()+ }+ return protoDuration+}++func yesNo(v bool) string {+ if v {+ return "yes"+ }+ return "no"+}++func capitalize(word string) string {+ if word == "" {+ return word+ }+ return strings.ToUpper(word[:1]) + word[1:]+}diff --git a/backend/api/mcp/tool_decide_test.go b/backend/api/mcp/tool_decide_test.gonew file mode 100644index 0000000000..0f78cda9e5--- /dev/null+++ b/backend/api/mcp/tool_decide_test.go@@ -0,0 +1,1138 @@+package mcp++import (+ "context"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strconv"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"+ "unicode"++ "connectrpc.com/connect"+ "github.com/labstack/echo/v5"+ "github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/pkg/errors"+ "github.com/stretchr/testify/require"+ "golang.org/x/text/width"+ "google.golang.org/grpc/codes"++ "github.com/bytebase/bytebase/backend/api/auth"+ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/component/config"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"+)++const decideIssueName = "projects/hr/issues/42"++// issueUpdateTime is the mock issue's update time, as protojson writes it.+const issueUpdateTime = "2026-10-13T08:00:00.123456Z"++// decisionMock is the internal API behind decide_issue: the reads the+// confirmation is built from, and the two decisions, recorded with the+// confirmation each request's context carried.+type decisionMock struct {+ issue map[string]any+ plan map[string]any+ sheet map[string]any+ grant map[string]any+ // refusal, when set, is the message the decision is refused with.+ refusal string+ // failing, when set, is a read path that answers 500.+ failing string++ mu sync.Mutex+ decisions []decisionCall+}++type decisionCall struct {+ path string+ body map[string]any+ confirmed *auth.MCPConfirmedDecision+}++func (m *decisionMock) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ reply := func(v any) { _ = json.NewEncoder(w).Encode(v) }+ m.mu.Lock()+ issue, plan, sheet, grant := m.issue, m.plan, m.sheet, m.grant+ m.mu.Unlock()+ if r.URL.Path == m.failing {+ w.WriteHeader(http.StatusInternalServerError)+ reply(map[string]any{"code": "internal", "message": "the read failed"})+ return+ }+ switch r.URL.Path {+ case "/bytebase.v1.IssueService/GetIssue":+ reply(issue)+ case "/bytebase.v1.PlanService/GetPlan":+ reply(plan)+ case "/bytebase.v1.SheetService/GetSheet":+ reply(sheet)+ case "/bytebase.v1.AccessGrantService/GetAccessGrant":+ reply(grant)+ case "/bytebase.v1.AccessGrantService/SearchMyAccessGrants":+ var search struct{ Parent, Filter string }+ _ = json.NewDecoder(r.Body).Decode(&search)+ mine := []map[string]any{}+ if grant != nil && search.Parent == "projects/hr" && search.Filter == fmt.Sprintf("name == %q", issue["accessGrant"]) {+ mine = append(mine, grant)+ }+ reply(map[string]any{"accessGrants": mine})+ case v1connect.IssueServiceApproveIssueProcedure, v1connect.IssueServiceRejectIssueProcedure:+ call := decisionCall{path: r.URL.Path}+ _ = json.NewDecoder(r.Body).Decode(&call.body)+ if confirmed, ok := auth.MCPConfirmedDecisionFromContext(r.Context()); ok {+ call.confirmed = &confirmed+ }+ m.mu.Lock()+ m.decisions = append(m.decisions, call)+ m.mu.Unlock()+ if m.refusal != "" {+ w.WriteHeader(http.StatusForbidden)+ reply(map[string]any{"code": "permission_denied", "message": m.refusal})+ return+ }+ reply(map[string]any{"name": decideIssueName, "status": "DONE", "approvalStatus": "APPROVED"})+ default:+ w.WriteHeader(http.StatusNotFound)+ }+}++func (m *decisionMock) calls() []decisionCall {+ m.mu.Lock()+ defer m.mu.Unlock()+ return append([]decisionCall(nil), m.decisions...)+}++// update changes what the reads return while a call is under way.+func (m *decisionMock) update(change func(*decisionMock)) {+ m.mu.Lock()+ defer m.mu.Unlock()+ change(m)+}++// changeIssueMock is a database change waiting on the second of two steps.+func changeIssueMock() *decisionMock {+ return &decisionMock{+ issue: map[string]any{+ "name": decideIssueName,+ "title": "Add status column",+ "type": "DATABASE_CHANGE",+ "status": "OPEN",+ "creator": "users/[email protected]",+ "plan": "projects/hr/plans/7",+ "approvalStatus": "PENDING",+ "approvalTemplate": map[string]any{"flow": map[string]any{+ "roles": []string{"roles/projectOwner", "roles/workspaceDBA"},+ }},+ "approvers": []map[string]any{{"status": "APPROVED", "principal": "users/[email protected]"}},+ "updateTime": issueUpdateTime,+ },+ plan: map[string]any{"updateTime": "2026-10-13T07:00:00Z", "specs": []map[string]any{{+ "id": "spec-1",+ "changeDatabaseConfig": map[string]any{+ "targets": []string{"instances/prod/databases/hr"},+ "sheet": "projects/hr/sheets/9",+ },+ }}},+ sheet: map[string]any{+ "content": base64.StdEncoding.EncodeToString([]byte("ALTER TABLE users\n ADD COLUMN status VARCHAR(20);")),+ },+ }+}++// newDecideServer stands up the real /mcp route over the mock and returns the+// endpoint and a bearer for alice.+func newDecideServer(t *testing.T, mock *decisionMock) (string, string) {+ t.Helper()+ return newDecideServerOn(t, mock, newTestServerStore())+}++func newDecideServerOn(t *testing.T, mock *decisionMock, stores *testServerStore) (string, string) {+ t.Helper()+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}+ s, err := newServerWithStore(stores, profile, revalidationSecret, mock)+ require.NoError(t, err)+ e := echo.New()+ s.RegisterRoutes(e)+ ts := httptest.NewServer(e)+ t.Cleanup(ts.Close)+ return ts.URL + mcpResourcePath, mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-write", time.Hour)+}++// asker is a client elicitation handler that records what it was asked and+// gives a fixed answer.+type asker struct {+ answer *mcp.ElicitResult+ err error+ // whileAsked, when set, runs while the form is open.+ whileAsked func()++ asked atomic.Int32+ mu sync.Mutex+ last *mcp.ElicitParams+}++func (a *asker) handle(_ context.Context, req *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ a.asked.Add(1)+ a.mu.Lock()+ a.last = req.Params+ a.mu.Unlock()+ if a.whileAsked != nil {+ a.whileAsked()+ }+ return a.answer, a.err+}++func (a *asker) lastParams(t *testing.T) *mcp.ElicitParams {+ t.Helper()+ a.mu.Lock()+ defer a.mu.Unlock()+ require.NotNil(t, a.last, "the user was never asked")+ return a.last+}++func confirmAnswer(checked any) *mcp.ElicitResult {+ return &mcp.ElicitResult{Action: "accept", Content: map[string]any{confirmDecisionField: checked}}+}++func callDecideIssue(t *testing.T, session *mcp.ClientSession, decision string) (*mcp.CallToolResult, error) {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ return session.CallTool(ctx, &mcp.CallToolParams{+ Name: "decide_issue",+ Arguments: map[string]any{+ "issue": decideIssueName,+ "decision": decision,+ "comment": "checked the statement",+ },+ })+}++func TestDecideIssueApprovesOnConfirmation(t *testing.T) {+ mock := changeIssueMock()+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: confirmAnswer(true)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res, err := callDecideIssue(t, session, "approve")+ require.NoError(t, err)+ require.False(t, res.IsError, resultText(t, res))+ require.Equal(t, int32(1), user.asked.Load(), "the user must be asked exactly once")++ asked := user.lastParams(t)+ require.Equal(t, "form", asked.Mode)+ require.Equal(t, strings.Join([]string{+ `Approve issue "projects/hr/issues/42" titled "Add status column" as [email protected]?`,+ `Change on "instances/prod/databases/hr"`,+ `SQL: "ALTER TABLE users\n ADD COLUMN status VARCHAR(20);"`,+ `Approval: step 2 of 2, role "roles/workspaceDBA". Requested by "[email protected]". Comment: "checked the statement"`,+ }, "\n"), asked.Message, "Claude Code shows four lines of a form whole, and only three of a longer one")+ require.NotContains(t, asked.Message, "https://", "a form must not carry a clickable URL")+ schema, err := json.Marshal(asked.RequestedSchema)+ require.NoError(t, err)+ require.JSONEq(t, `{"type":"object","required":["confirm"],"properties":{"confirm":{"type":"boolean",+ "title":"Approve this issue",+ "description":"Check to approve the issue described above. Leaving it unchecked, declining or cancelling changes nothing."}}}`,+ string(schema))++ calls := mock.calls()+ require.Len(t, calls, 1)+ require.Equal(t, v1connect.IssueServiceApproveIssueProcedure, calls[0].path)+ require.Equal(t, decideIssueName, calls[0].body["name"])+ require.Equal(t, decisionNote+"\n\nchecked the statement", calls[0].body["comment"],+ "the comment must record that the decision was confirmed in the client")+ require.Equal(t, &auth.MCPConfirmedDecision{+ Procedure: v1connect.IssueServiceApproveIssueProcedure,+ Issue: decideIssueName,+ IssueUpdateTime: time.Date(2026, 10, 13, 8, 0, 0, 123456000, time.UTC),+ }, calls[0].confirmed, "the approval must carry the confirmation the gate admits it on, and the issue version it applies to")++ require.Contains(t, resultText(t, res), `Approved projects/hr/issues/42. Approval: "APPROVED". Issue status: DONE.`)+ output, err := json.Marshal(res.StructuredContent)+ require.NoError(t, err)+ require.JSONEq(t, `{"issue":"projects/hr/issues/42","decision":"approve","approvalStatus":"APPROVED",+ "status":"DONE","link":"https://bb.example.com/projects/hr/issues/42"}`, string(output))+}++func TestDecideIssueRejectsOnConfirmation(t *testing.T) {+ mock := changeIssueMock()+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: confirmAnswer(true)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res, err := callDecideIssue(t, session, "REJECT")+ require.NoError(t, err)+ require.False(t, res.IsError, resultText(t, res))+ require.Contains(t, user.lastParams(t).Message, `Reject issue "projects/hr/issues/42" titled "Add status column"`)++ calls := mock.calls()+ require.Len(t, calls, 1)+ require.Equal(t, v1connect.IssueServiceRejectIssueProcedure, calls[0].path)+ require.Equal(t, &auth.MCPConfirmedDecision{+ Procedure: v1connect.IssueServiceRejectIssueProcedure,+ Issue: decideIssueName,+ IssueUpdateTime: time.Date(2026, 10, 13, 8, 0, 0, 123456000, time.UTC),+ }, calls[0].confirmed)+}++func TestDecideIssueChangesNothingUnlessConfirmed(t *testing.T) {+ for name, tc := range map[string]struct {+ answer *mcp.ElicitResult+ want string+ }{+ "declined": {&mcp.ElicitResult{Action: "decline"}, "the user declined"},+ "cancelled": {&mcp.ElicitResult{Action: "cancel"}, "the user cancelled"},+ "accepted, unticked": {confirmAnswer(false), "the form was submitted without the confirmation checked"},+ } {+ t.Run(name, func(t *testing.T) {+ mock := changeIssueMock()+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: tc.answer}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res, err := callDecideIssue(t, session, "approve")+ require.NoError(t, err)+ require.Equal(t, int32(1), user.asked.Load())+ require.Empty(t, mock.calls(), "an unconfirmed answer must not reach the decision")+ text := resultText(t, res)+ require.Contains(t, text, "Not approved: "+tc.want+", so nothing changed.")+ require.Contains(t, text, "https://bb.example.com/projects/hr/issues/42")+ })+ }+}++// The SDK validates a legacy client's answer against the form and fails the+// whole call on a mismatch, so a malformed answer never reaches the handler;+// confirmationOutcome covers the shapes that can.+func TestDecideIssueMalformedAnswerChangesNothing(t *testing.T) {+ mock := changeIssueMock()+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: confirmAnswer("yes")}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ _, err := callDecideIssue(t, session, "approve")+ require.ErrorContains(t, err, "elicitation result content does not match requested schema")+ require.Empty(t, mock.calls())++ for name, response := range map[string]mcp.InputResponse{+ "no answer at all": nil,+ "a nil elicitation": (*mcp.ElicitResult)(nil),+ "no content": &mcp.ElicitResult{Action: "accept"},+ "a string, not a bool": confirmAnswer("true"),+ "an unknown action": &mcp.ElicitResult{Action: "approve", Content: map[string]any{confirmDecisionField: true}},+ } {+ confirmed, why := confirmationOutcome(response)+ require.False(t, confirmed, name)+ require.NotEmpty(t, why, name)+ }+ confirmed, _ := confirmationOutcome(confirmAnswer(true))+ require.True(t, confirmed)+}++// Under the multi round-trip shape the SDK, not the handler, sends the+// elicitation, and its failure fails the call before the handler runs again.+func TestDecideIssueTransportErrorChangesNothing(t *testing.T) {+ mock := changeIssueMock()+ endpoint, token := newDecideServer(t, mock)+ user := &asker{err: errors.New("the client lost its window")}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ _, err := callDecideIssue(t, session, "approve")+ require.Error(t, err)+ require.Contains(t, err.Error(), `input request "confirm"`)+ require.Empty(t, mock.calls())+}++func TestDecideIssueRefusesAClientThatCannotConfirm(t *testing.T) {+ for name, opts := range map[string]*mcp.ClientOptions{+ "no elicitation": nil,+ "URL elicitation only": {+ Capabilities: &mcp.ClientCapabilities{+ Elicitation: &mcp.ElicitationCapabilities{URL: &mcp.URLElicitationCapabilities{}},+ },+ ElicitationHandler: func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ return confirmAnswer(true), nil+ },+ },+ } {+ t.Run(name, func(t *testing.T) {+ mock := changeIssueMock()+ endpoint, token := newDecideServer(t, mock)+ session := connectLegacy(t, endpoint, token, opts)++ res, err := callDecideIssue(t, session, "approve")+ require.NoError(t, err, "a client that cannot be asked must get a result, not a protocol error")+ require.True(t, res.IsError)+ text := resultText(t, res)+ require.Contains(t, text, "CONFIRMATION_UNAVAILABLE")+ require.Contains(t, text, "decide the issue signed in to the Bytebase console: https://bb.example.com/projects/hr/issues/42")+ require.Empty(t, mock.calls())+ })+ }+}++func TestDecideIssueRefusesAnUnaskedAnswerFromAClientThatCannotConfirm(t *testing.T) {+ mock := changeIssueMock()+ endpoint, token := newDecideServer(t, mock)+ session := connectLegacy(t, endpoint, token, nil)++ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ res, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "decide_issue",+ Arguments: map[string]any{"issue": decideIssueName, "decision": "approve"},+ InputResponses: mcp.InputResponseMap{confirmDecisionRequestID: confirmAnswer(true)},+ })+ require.NoError(t, err)+ require.True(t, res.IsError)+ require.Contains(t, resultText(t, res), "CONFIRMATION_UNAVAILABLE")+ require.Empty(t, mock.calls())+}++func TestDecideIssueAsksDespiteAnUnaskedAnswer(t *testing.T) {+ for name, state := range map[string]string{+ "no request state": "",+ "a forged request state": "AAAA.BBBB",+ } {+ t.Run(name, func(t *testing.T) {+ mock := changeIssueMock()+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: &mcp.ElicitResult{Action: "decline"}}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ res, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "decide_issue",+ Arguments: map[string]any{"issue": decideIssueName, "decision": "approve"},+ InputResponses: mcp.InputResponseMap{confirmDecisionRequestID: confirmAnswer(true)},+ RequestState: state,+ })+ require.NoError(t, err)+ require.Equal(t, int32(1), user.asked.Load(), "an answer nobody asked for must not stand in for asking")+ require.Contains(t, resultText(t, res), "Not approved: the user declined, so nothing changed.")+ require.Empty(t, mock.calls())+ })+ }+}++func TestConfirmationStateIsBoundToTheCallerAndTheDecision(t *testing.T) {+ s, err := newServerWithStore(newTestServerStore(), &config.Profile{Mode: common.ReleaseModeDev}, revalidationSecret, http.NotFoundHandler())+ require.NoError(t, err)+ caller := func(workspace, email, client string) context.Context {+ return withOAuth2ClientID(withUserEmail(withWorkspaceID(context.Background(), workspace), email), client)+ }+ alice := caller("ws-test", "[email protected]", "client-A")+ approve := &issueDecision{issue: decideIssueName, procedure: v1connect.IssueServiceApproveIssueProcedure}+ digest := sha256.Sum256([]byte("what the form was built from"))+ state := s.signConfirmationState(alice, approve, digest[:])++ signedDigest, signed := s.verifyConfirmationState(alice, approve, state)+ require.True(t, signed)+ require.Equal(t, digest[:], signedDigest)++ otherDigest := sha256.Sum256([]byte("something else"))+ _, mac, _ := strings.Cut(state, ".")+ for name, tc := range map[string]struct {+ ctx context.Context+ decision *issueDecision+ state string+ }{+ "another user": {caller("ws-test", "[email protected]", "client-A"), approve, state},+ "another client": {caller("ws-test", "[email protected]", "client-B"), approve, state},+ "another workspace": {caller("ws-other", "[email protected]", "client-A"), approve, state},+ "the other decision": {alice, &issueDecision{issue: decideIssueName, procedure: v1connect.IssueServiceRejectIssueProcedure}, state},+ "another issue": {alice, &issueDecision{issue: "projects/hr/issues/43", procedure: v1connect.IssueServiceApproveIssueProcedure}, state},+ "another digest": {alice, approve, base64.RawURLEncoding.EncodeToString(otherDigest[:]) + "." + mac},+ "no signature": {alice, approve, base64.RawURLEncoding.EncodeToString(digest[:])},+ } {+ _, signed := s.verifyConfirmationState(tc.ctx, tc.decision, tc.state)+ require.False(t, signed, name)+ }+}++// threeStepIssueMock is a database change waiting on the second of three steps.+func threeStepIssueMock() *decisionMock {+ mock := changeIssueMock()+ mock.issue["approvalTemplate"] = map[string]any{"flow": map[string]any{+ "roles": []string{"roles/projectOwner", "roles/workspaceDBA", "roles/workspaceAdmin"},+ }}+ return mock+}++func TestDecideIssueRefusesWhenTheIssueChangesWhileAsking(t *testing.T) {+ for name, change := range map[string]func(*decisionMock){+ "the plan's statement replaced": func(m *decisionMock) {+ m.plan = map[string]any{"specs": []map[string]any{{+ "id": "spec-1",+ "changeDatabaseConfig": map[string]any{+ "targets": []string{"instances/prod/databases/hr"},+ "sheet": "projects/hr/sheets/10",+ },+ }}}+ m.sheet = map[string]any{"content": base64.StdEncoding.EncodeToString([]byte("DROP TABLE users;"))}+ },+ "the step decided by another approver": func(m *decisionMock) {+ m.issue["approvers"] = []map[string]any{{"status": "APPROVED"}, {"status": "APPROVED"}}+ },+ "the title changed": func(m *decisionMock) {+ m.issue["title"] = "Drop users"+ },+ "the plan edited where the form does not show it, such as prior backup": func(m *decisionMock) {+ m.plan["updateTime"] = "2026-10-13T09:00:00Z"+ },+ "the issue rejected and requested again, back at the same step": func(m *decisionMock) {+ m.issue["updateTime"] = "2026-10-13T09:00:00Z"+ },+ } {+ t.Run(name, func(t *testing.T) {+ mock := threeStepIssueMock()+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: confirmAnswer(true), whileAsked: func() { mock.update(change) }}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res, err := callDecideIssue(t, session, "approve")+ require.NoError(t, err)+ require.Equal(t, int32(1), user.asked.Load())+ require.True(t, res.IsError)+ text := resultText(t, res)+ require.Contains(t, text, "STALE_CONFIRMATION")+ require.Contains(t, text, "call decide_issue again")+ require.Empty(t, mock.calls(), "an answer about the issue as it was must not decide the issue as it is")+ })+ }+}++func TestDecideIssueReportsADeclineEvenWhenTheIssueChanged(t *testing.T) {+ mock := threeStepIssueMock()+ endpoint, token := newDecideServer(t, mock)+ user := &asker{+ answer: &mcp.ElicitResult{Action: "decline"},+ whileAsked: func() { mock.update(func(m *decisionMock) { m.issue["title"] = "Drop users" }) },+ }+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res, err := callDecideIssue(t, session, "approve")+ require.NoError(t, err)+ text := resultText(t, res)+ require.Contains(t, text, "Not approved: the user declined, so nothing changed. Do not retry unless the user asks.")+ require.NotContains(t, text, "STALE_CONFIRMATION", "a stale result would send the agent back to a user who said no")+ require.Empty(t, mock.calls())+}++// newDecideMRTRServer returns a decide_issue call for a client on the+// 2026-07-28 protocol, which answers the form and echoes the request state+// itself.+func newDecideMRTRServer(t *testing.T, mock *decisionMock) func(mcp.InputResponseMap, string, string) *mcp.CallToolResult {+ t.Helper()+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}+ s, err := newServerWithStore(newTestServerStore(), profile, revalidationSecret, mock)+ require.NoError(t, err)+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-write", time.Hour)+ session := connectMRTR(t, mrtrEndpoint(t, s), token)+ return func(responses mcp.InputResponseMap, state, comment string) *mcp.CallToolResult {+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ res, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "decide_issue",+ Arguments: map[string]any{"issue": decideIssueName, "decision": "approve", "comment": comment},+ InputResponses: responses,+ RequestState: state,+ })+ require.NoError(t, err)+ return res+ }+}++func TestDecideIssueUnderMRTRClient(t *testing.T) {+ mock := changeIssueMock()+ call := newDecideMRTRServer(t, mock)+ accept := mcp.InputResponseMap{confirmDecisionRequestID: confirmAnswer(true)}++ first := call(nil, "", "checked the statement")+ require.True(t, first.NeedsInput())+ require.NotEmpty(t, first.RequestState)+ asked, ok := first.InputRequests[confirmDecisionRequestID].(*mcp.ElicitParams)+ require.True(t, ok)+ require.Contains(t, asked.Message, `Approve issue "projects/hr/issues/42" titled "Add status column"`)++ unsigned := call(accept, "", "checked the statement")+ require.True(t, unsigned.NeedsInput(), "an answer without the request state must be asked again")+ require.Empty(t, mock.calls())++ swapped := call(accept, first.RequestState, "a comment the user never saw")+ require.True(t, swapped.IsError)+ require.Contains(t, resultText(t, swapped), "STALE_CONFIRMATION")+ require.Empty(t, mock.calls())++ decided := call(accept, first.RequestState, "checked the statement")+ require.False(t, decided.IsError, resultText(t, decided))+ calls := mock.calls()+ require.Len(t, calls, 1)+ require.Equal(t, decisionNote+"\n\nchecked the statement", calls[0].body["comment"])+}++// callDecideIssueWith calls decide_issue on an issue of the given type,+// optionally carrying an answer the client sends without being asked.+func callDecideIssueWith(t *testing.T, issueType string, unasked mcp.InputResponseMap) (*decisionMock, *asker, *mcp.CallToolResult, *testServerStore) {+ t.Helper()+ mock := changeIssueMock()+ mock.issue["type"] = issueType+ stores := newTestServerStore()+ endpoint, token := newDecideServerOn(t, mock, stores)+ user := &asker{answer: confirmAnswer(true)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ res, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "decide_issue",+ Arguments: map[string]any{"issue": decideIssueName, "decision": "approve"},+ InputResponses: unasked,+ })+ require.NoError(t, err)+ return mock, user, res, stores+}++func TestDecideIssueRefusesARoleRequest(t *testing.T) {+ for name, unasked := range map[string]mcp.InputResponseMap{+ "asked as usual": nil,+ "with an answer sent unasked": {confirmDecisionRequestID: confirmAnswer(true)},+ } {+ t.Run(name, func(t *testing.T) {+ mock, user, res, stores := callDecideIssueWith(t, "ROLE_GRANT", unasked)+ require.True(t, res.IsError)+ text := resultText(t, res)+ require.Contains(t, text, "ROLE_GRANT_NOT_SUPPORTED")+ require.Contains(t, text, "approving a role request grants a project role, which MCP does not do yet")+ require.Contains(t, text, "decide it signed in to the Bytebase console: https://bb.example.com/projects/hr/issues/42")+ require.Zero(t, user.asked.Load(), "no form may be sent for a role request")+ require.Empty(t, mock.calls(), "no decision, and so no confirmation, may reach the API")++ require.Len(t, stores.auditRows, 1, "the refusal must be recorded, as its creation-side twin is")+ row := stores.auditRows[0]+ require.Equal(t, "projects/hr", row.Parent)+ require.Equal(t, v1connect.IssueServiceApproveIssueProcedure, row.Method)+ require.Equal(t, decideIssueName, row.Resource)+ require.Equal(t, "users/[email protected]", row.User)+ require.Equal(t, int32(codes.PermissionDenied), row.Status.GetCode())+ require.Contains(t, row.Status.GetMessage(), "approving a role request grants a project role")+ require.Equal(t, "client-A", row.McpDelegation.GetClientId())+ })+ }+}++func TestDecideIssueRefusesAnIssueTypeItDoesNotKnow(t *testing.T) {+ mock, user, res, stores := callDecideIssueWith(t, "SOMETHING_NEW", nil)+ require.True(t, res.IsError)+ require.Contains(t, resultText(t, res), "ISSUE_TYPE_NOT_SUPPORTED")+ require.Zero(t, user.asked.Load())+ require.Empty(t, mock.calls())+ require.Len(t, stores.auditRows, 1)+}++// The tool passes a refusal on in the server's words: the workflow's and the+// ceiling's messages each name their own remedy.+func TestDecideIssueReportsTheRefusalInTheServersWords(t *testing.T) {+ for name, refusal := range map[string]string{+ "the workflow": "cannot approve because self-approval is not allowed for this project",+ "the ceiling": "/bytebase.v1.IssueService/ApproveIssue is a WRITE method and this workspace's MCP capability ceiling is READ_ONLY, " ++ "which serves READ methods. Ask a workspace admin to raise the MCP ceiling in the workspace settings, " ++ "or perform this action signed in to the Bytebase console instead",+ } {+ t.Run(name, func(t *testing.T) {+ mock := changeIssueMock()+ mock.refusal = refusal+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: confirmAnswer(true)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res, err := callDecideIssue(t, session, "approve")+ require.NoError(t, err)+ require.True(t, res.IsError)+ text := resultText(t, res)+ require.Contains(t, text, "failed to approve projects/hr/issues/42: HTTP 403: "+refusal)+ require.Contains(t, text, "check the issue's current state: https://bb.example.com/projects/hr/issues/42")+ require.NotContains(t, text, "approval rules", "the tool must not put its own cause on the server's refusal")+ require.Len(t, mock.calls(), 1, "the server, not the tool, refuses")+ })+ }+}++// accessRequestMock is an access request waiting on its only step.+func accessRequestMock() *decisionMock {+ return &decisionMock{+ issue: map[string]any{+ "name": decideIssueName,+ "title": "Read salaries",+ "type": "ACCESS_GRANT",+ "creator": "users/[email protected]",+ "accessGrant": "projects/hr/accessGrants/5",+ "approvalStatus": "PENDING",+ "approvalTemplate": map[string]any{"flow": map[string]any{"roles": []string{"roles/projectOwner"}}},+ "updateTime": issueUpdateTime,+ },+ grant: map[string]any{+ "targets": []string{"instances/prod/databases/hr"},+ "query": "SELECT salary\nFROM employee",+ "unmask": true,+ "ttl": "3600s",+ "updateTime": "2026-10-13T07:00:00Z",+ },+ }+}++func TestDecideIssueDescribesAnAccessRequest(t *testing.T) {+ require.Equal(t, strings.Join([]string{+ `Approve issue "projects/hr/issues/42" titled "Read salaries" as [email protected]?`,+ `Access on "instances/prod/databases/hr"`,+ `Query: "SELECT salary\nFROM employee"`,+ `Unmasked: yes. Export: no. Expires: "1h0m0s" after approval. Approval: step 1 of 1, role "roles/projectOwner". Requested by "[email protected]". Comment: "checked the statement"`,+ }, "\n"), askedMessage(t, accessRequestMock()))+}++func TestDecideIssueReadsTheCallersOwnAccessRequestAsTheConsoleDoes(t *testing.T) {+ mock := accessRequestMock()+ mock.issue["creator"] = "users/[email protected]"+ mock.failing = "/bytebase.v1.AccessGrantService/GetAccessGrant"+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: confirmAnswer(true)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res, err := callDecideIssue(t, session, "approve")+ require.NoError(t, err)+ require.False(t, res.IsError, "a requester without bb.accessGrants.get reads their own grant: %s", resultText(t, res))+ require.Contains(t, user.lastParams(t).Message, `Query: "SELECT salary\nFROM employee"`)+ require.Len(t, mock.calls(), 1)++ mock.update(func(m *decisionMock) { m.grant = nil })+ user = &asker{answer: confirmAnswer(true)}+ session = connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})+ res, err = callDecideIssue(t, session, "approve")+ require.NoError(t, err)+ require.True(t, res.IsError)+ require.Contains(t, resultText(t, res), "is not among the access grants you requested")+ require.Zero(t, user.asked.Load(), "a form missing the grant must not be sent")+ require.Len(t, mock.calls(), 1)+}++func TestDecideIssueShowsANewDatabasesSettings(t *testing.T) {+ for name, tc := range map[string]struct {+ config map[string]any+ want string+ }{+ "a ClickHouse cluster": {+ map[string]any{"target": "instances/ch", "database": "events", "cluster": "ch-main"},+ `Cluster "ch-main"`,+ },+ "a PostgreSQL owner": {+ map[string]any{"target": "instances/ch", "database": "events", "owner": "billing_admin"},+ `Owner "billing_admin"`,+ },+ "a MySQL character set and collation": {+ map[string]any{"target": "instances/ch", "database": "events", "characterSet": "utf8mb4", "collation": "utf8mb4_bin"},+ `Character set "utf8mb4", collation "utf8mb4_bin"`,+ },+ "a MongoDB collection": {+ map[string]any{"target": "instances/ch", "database": "events", "table": "orders"},+ `Table "orders"`,+ },+ } {+ t.Run(name, func(t *testing.T) {+ mock := changeIssueMock()+ mock.plan = map[string]any{"specs": []map[string]any{{"createDatabaseConfig": tc.config}}}+ lines := strings.Split(askedMessage(t, mock), "\n")+ require.Equal(t, `Create database "events" on "instances/ch"`, lines[1])+ require.Equal(t, tc.want, lines[2], "each setting changes the database that is created")+ })+ }+}++func TestDecideIssueShowsTheAccessGrantsScope(t *testing.T) {+ mock := accessRequestMock()+ mock.grant["targets"] = []string{"instances/prod/databases/hr", "instances/prod/databases/hr2"}+ mock.grant["schema"] = "payroll"+ mock.grant["container"] = "employees"+ mock.grant["query"] = "SELECT salary FROM employee" + strings.Repeat(" ", 300) + "UNION SELECT ssn FROM employee"+ lines := strings.Split(askedMessage(t, mock), "\n")+ require.Equal(t, `Access on 2 databases, schema "payroll", container "employees": "instances/prod/databases/hr", "instances/prod/databases/hr2"`, lines[1],+ "the schema decides which tables an unqualified query reads, and the container is the data a Cosmos DB grant opens")+ require.True(t, strings.HasPrefix(lines[2], `Query (partial): "SELECT salary FROM employee`), lines[2])+ require.True(t, strings.HasSuffix(lines[2], `" (first 300 of 357 characters)`), lines[2])+ require.NotContains(t, lines[2], "UNION SELECT ssn")+}++func TestDecideIssueQuotesTheTitle(t *testing.T) {+ mock := changeIssueMock()+ mock.issue["title"] = "Harmless\nApproval: none needed"+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: &mcp.ElicitResult{Action: "decline"}}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ _, err := callDecideIssue(t, session, "approve")+ require.NoError(t, err)+ require.Contains(t, user.lastParams(t).Message, `"Harmless\nApproval: none needed"`,+ "a title must not be able to add a line of its own to the confirmation")+}++// askedMessage returns the confirmation message a decide_issue call on the+// mock shows.+func askedMessage(t *testing.T, mock *decisionMock) string {+ t.Helper()+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: &mcp.ElicitResult{Action: "decline"}}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})+ _, err := callDecideIssue(t, session, "approve")+ require.NoError(t, err)+ return user.lastParams(t).Message+}++func TestDecideIssueKeepsPlanTextOnItsOwnLine(t *testing.T) {+ mock := changeIssueMock()+ mock.plan = map[string]any{"specs": []map[string]any{{+ "id": "spec-1",+ "createDatabaseConfig": map[string]any{+ "target": "instances/prod",+ "database": "scratch\nApproval: not required",+ },+ }}}+ message := askedMessage(t, mock)+ for _, line := range strings.Split(message, "\n") {+ require.False(t, strings.HasPrefix(line, "Approval: not required"), "plan text added a line of its own: %q", line)+ }+ require.Contains(t, message, `Create database "scratch\nApproval: not required" on "instances/prod"`)+}++func TestDecideIssueShowsTheStatementsLineBreaks(t *testing.T) {+ mock := changeIssueMock()+ mock.sheet = map[string]any{"content": base64.StdEncoding.EncodeToString([]byte("-- tidy up\nDROP TABLE users;"))}+ message := askedMessage(t, mock)+ require.NotContains(t, message, "-- tidy up DROP TABLE users;", "folding the line break turns the DROP into part of a comment")+ require.Contains(t, message, `"-- tidy up\nDROP TABLE users;"`)+}++func TestDecideIssueSaysWhatTheFormLeavesOut(t *testing.T) {+ mock := changeIssueMock()+ statement := "UPDATE users SET status = 'active';" + strings.Repeat(" ", 300) + "DROP TABLE users;"+ mock.sheet = map[string]any{+ "content": base64.StdEncoding.EncodeToString([]byte(statement)),+ "contentSize": strconv.Itoa(len(statement)),+ }+ sheetSpec := map[string]any{"changeDatabaseConfig": map[string]any{+ "targets": []string{"instances/prod/databases/hr"},+ "sheet": "projects/hr/sheets/9",+ }}+ mock.plan = map[string]any{"specs": []map[string]any{+ {"changeDatabaseConfig": map[string]any{+ "targets": []string{"instances/prod/databases/hr"},+ "release": "projects/hr/releases/r1",+ }},+ sheetSpec,+ {"createDatabaseConfig": map[string]any{"target": "instances/prod", "database": "scratch"}},+ sheetSpec,+ sheetSpec,+ }}+ lines := strings.Split(askedMessage(t, mock), "\n")+ require.Equal(t, `Change 1 of 5 on "instances/prod/databases/hr"`, lines[1],+ "Claude Code shows the first lines only, so the first change already says how many there are")+ require.Equal(t, `Release "projects/hr/releases/r1" (statements not shown)`, lines[2])+ require.Equal(t, `Change 2 of 5 on "instances/prod/databases/hr"`, lines[3])+ require.True(t, strings.HasPrefix(lines[4], `SQL (partial): "UPDATE users`), lines[4])+ require.True(t, strings.HasSuffix(lines[4], fmt.Sprintf(`" (first 300 characters of %d bytes)`, len(statement))), lines[4])+ require.NotContains(t, lines[4], "DROP TABLE users;")+ require.Equal(t, `Change 3 of 5: create database "scratch" on "instances/prod"`, lines[5])+ require.Equal(t, "(3 of 5 changes shown)", lines[6])+}++func TestDecideIssueFormShowsTheChangeInClaudeCodesDialog(t *testing.T) {+ longStatement := "ALTER TABLE users ADD COLUMN status VARCHAR(20);" + strings.Repeat(" ", 300) + "DROP TABLE users;"+ manyTargets := make([]string, 12)+ for i := range manyTargets {+ manyTargets[i] = fmt.Sprintf("instances/prod-%02d/databases/hr", i)+ }+ sheetSpec := func(targets ...string) map[string]any {+ return map[string]any{"changeDatabaseConfig": map[string]any{"targets": targets, "sheet": "projects/hr/sheets/9"}}+ }+ withStatement := func(mock *decisionMock, statement string) *decisionMock {+ mock.sheet = map[string]any{+ "content": base64.StdEncoding.EncodeToString([]byte(statement)),+ "contentSize": strconv.Itoa(len(statement)),+ }+ return mock+ }+ for name, tc := range map[string]struct {+ mock *decisionMock+ // The start of each line after the question that must stay visible.+ scope, statement, last string+ }{+ "one long target": {+ mock: func() *decisionMock {+ mock := changeIssueMock()+ mock.plan = map[string]any{"specs": []map[string]any{sheetSpec("instances/" + strings.Repeat("i", 60) + "/databases/" + strings.Repeat("d", 60))}}+ return mock+ }(),+ scope: `Change on "instances/iiii`,+ statement: `SQL: "ALTER TABLE users\n ADD COLUMN status`,+ last: `Approval: step 2 of 2`,+ },+ "many targets": {+ mock: func() *decisionMock {+ mock := changeIssueMock()+ mock.plan = map[string]any{"specs": []map[string]any{sheetSpec(manyTargets...)}}+ return mock+ }(),+ scope: `Change on 12 targets: "instances/prod-00/databases/hr"`,+ statement: `SQL: "ALTER TABLE users\n ADD COLUMN status`,+ last: `Approval: step 2 of 2`,+ },+ "a long statement": {+ mock: withStatement(changeIssueMock(), longStatement),+ scope: `Change on "instances/prod/databases/hr"`,+ statement: `SQL (partial): "ALTER TABLE users ADD COLUMN status`,+ last: `Approval: step 2 of 2`,+ },+ "several changes": {+ mock: func() *decisionMock {+ mock := withStatement(changeIssueMock(), longStatement)+ mock.plan = map[string]any{"specs": []map[string]any{sheetSpec(manyTargets...), sheetSpec(manyTargets...), sheetSpec(manyTargets...)}}+ return mock+ }(),+ scope: `Change 1 of 3 on 12 targets: "instances/prod-00/databases/hr"`,+ statement: `SQL (partial): "ALTER TABLE users ADD COLUMN status`,+ last: `… (+`,+ },+ "an access request": {+ mock: func() *decisionMock {+ mock := accessRequestMock()+ mock.grant["targets"] = manyTargets+ mock.grant["schema"] = "payroll"+ mock.grant["container"] = "employees"+ mock.grant["query"] = "SELECT salary FROM employee" + strings.Repeat(" ", 300) + "UNION SELECT ssn FROM employee"+ return mock+ }(),+ scope: `Access on 12 databases, schema "payroll", container "employees": "`,+ statement: `Query (partial): "SELECT salary FROM employee`,+ last: `Unmasked: yes. Export: no. Expires: "1h0m0s" after approval.`,+ },+ "an access request on one long database": {+ mock: func() *decisionMock {+ mock := accessRequestMock()+ mock.grant["targets"] = []string{"instances/pg-prod-eu-west-1/databases/payroll_reporting"}+ mock.grant["schema"] = "payroll"+ return mock+ }(),+ scope: `Access on "instances/pg-prod-eu-west-1/databases/payroll_reporting"`,+ statement: `Query: "SELECT salary`,+ last: `Unmasked: yes. Export: no. Expires: "1h0m0s" after approval.`,+ },+ "an access request with a long schema": {+ mock: func() *decisionMock {+ mock := accessRequestMock()+ mock.grant["schema"] = "regional_payroll_reporting_archive_for_financial_year_2026"+ return mock+ }(),+ scope: `Access on "instances/prod/databases/hr", schema "regional_payroll`,+ statement: `Query: "SELECT salary`,+ last: `Unmasked: yes. Export: no. Expires: "1h0m0s" after approval.`,+ },+ "an access request with a long container": {+ mock: func() *decisionMock {+ mock := accessRequestMock()+ mock.grant["container"] = "employee_compensation_history_partitioned_by_region_and_year"+ return mock+ }(),+ scope: `Access on "instances/prod/databases/hr", container "employee_compensation`,+ statement: `Query: "SELECT salary`,+ last: `Unmasked: yes. Export: no. Expires: "1h0m0s" after approval.`,+ },+ "wide characters": {+ mock: func() *decisionMock {+ mock := withStatement(changeIssueMock(), "UPDATE 用户 SET 状态 = '有效';")+ mock.issue["title"] = strings.Repeat("为用户表添加状态列", 6)+ return mock+ }(),+ scope: `Change on "instances/prod/databases/hr"`,+ statement: `SQL: "UPDATE 用户 SET 状态 = '有效';"`,+ last: `Approval: step 2 of 2`,+ },+ } {+ message := askedMessage(t, tc.mock)+ for _, columns := range []int{80, 120} {+ t.Run(fmt.Sprintf("%s at %d columns", name, columns), func(t *testing.T) {+ view := claudeCodeView(message, columns)+ require.Len(t, view, 4, "%q", view)+ require.True(t, strings.HasPrefix(view[0], "Approve issue "), "the decision: %q", view)+ require.True(t, strings.HasPrefix(view[1], tc.scope), "the scope: %q", view)+ require.True(t, strings.HasPrefix(view[2], tc.statement), "the statement: %q", view)+ require.True(t, strings.HasPrefix(view[3], tc.last), "the approval, or how much is left out: %q", view)+ })+ }+ }+}++// claudeCodeView is what Claude Code 2.1.302 shows of a form's message in a+// terminal of the given width (BP in its bundle): four lines, or three and+// "… (+N more lines)", each cut six columns short of the width and ended with+// "…". A wide character takes two columns.+func claudeCodeView(message string, columns int) []string {+ lines := strings.Split(message, "\n")+ if len(lines) > 4 {+ lines = append(lines[:3:3], fmt.Sprintf("… (+%d more lines)", len(lines)-3))+ }+ limit := max(20, columns-6)+ view := make([]string, len(lines))+ for i, line := range lines {+ view[i] = cutToColumns(line, limit)+ }+ return view+}++func cutToColumns(line string, limit int) string {+ total := 0+ for _, r := range line {+ total += runeColumns(r)+ }+ if total <= limit {+ return line+ }+ used := 0+ for i, r := range line {+ if used+runeColumns(r) > limit-1 {+ return line[:i] + "…"+ }+ used += runeColumns(r)+ }+ return line+}++func runeColumns(r rune) int {+ if unicode.Is(unicode.Mn, r) {+ return 0+ }+ switch width.LookupRune(r).Kind() {+ case width.EastAsianWide, width.EastAsianFullwidth:+ return 2+ default:+ return 1+ }+}++func TestDecideIssueAsksNothingWhenAReadFails(t *testing.T) {+ for name, tc := range map[string]struct {+ mock *decisionMock+ path string+ }{+ "the plan": {changeIssueMock(), "/bytebase.v1.PlanService/GetPlan"},+ "the statement": {changeIssueMock(), "/bytebase.v1.SheetService/GetSheet"},+ "the access grant": {accessRequestMock(), "/bytebase.v1.AccessGrantService/GetAccessGrant"},+ } {+ t.Run(name, func(t *testing.T) {+ tc.mock.failing = tc.path+ endpoint, token := newDecideServer(t, tc.mock)+ user := &asker{answer: confirmAnswer(true)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res, err := callDecideIssue(t, session, "approve")+ require.NoError(t, err)+ require.True(t, res.IsError)+ require.Zero(t, user.asked.Load(), "a form missing part of the issue must not be sent")+ require.Empty(t, tc.mock.calls())+ })+ }+}++func TestDecideIssueRefusesInvalidArguments(t *testing.T) {+ for name, input := range map[string]DecideIssueInput{+ "an issue that is not a name": {Issue: "42", Decision: "approve"},+ "an unknown decision": {Issue: decideIssueName, Decision: "skip"},+ } {+ t.Run(name, func(t *testing.T) {+ mock := changeIssueMock()+ endpoint, token := newDecideServer(t, mock)+ user := &asker{answer: confirmAnswer(true)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ res, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "decide_issue",+ Arguments: map[string]any{"issue": input.Issue, "decision": input.Decision},+ })+ require.NoError(t, err)+ require.True(t, res.IsError)+ require.Contains(t, resultText(t, res), "INVALID_ARGUMENT")+ require.Zero(t, user.asked.Load())+ require.Empty(t, mock.calls())+ })+ }+}++func TestCallAPICarriesNoConfirmation(t *testing.T) {+ mock := changeIssueMock()+ endpoint, token := newDecideServer(t, mock)+ session := connectLegacy(t, endpoint, token, nil)++ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ _, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "call_api",+ Arguments: map[string]any{+ "operationId": "IssueService/ApproveIssue",+ "body": map[string]any{"name": decideIssueName},+ },+ })+ require.NoError(t, err)+ calls := mock.calls()+ require.Len(t, calls, 1)+ require.Nil(t, calls[0].confirmed)+}++// confirmationProbe is an IssueService that answers ApproveIssue.+type confirmationProbe struct {+ v1connect.UnimplementedIssueServiceHandler+}++func (*confirmationProbe) ApproveIssue(context.Context, *connect.Request[v1pb.ApproveIssueRequest]) (*connect.Response[v1pb.Issue], error) {+ return connect.NewResponse(&v1pb.Issue{Name: decideIssueName}), nil+}++// TestConfirmationReachesTheConnectInterceptors pins the path the gate reads+// the confirmation from: the in-memory transport hands the tool's context to+// the connect handler, and connect hands it to every interceptor, the MCP gate+// among them.+func TestConfirmationReachesTheConnectInterceptors(t *testing.T) {+ var seen atomic.Pointer[auth.MCPConfirmedDecision]+ recorder := connect.UnaryInterceptorFunc(func(next connect.UnaryFunc) connect.UnaryFunc {+ return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {+ if confirmed, ok := auth.MCPConfirmedDecisionFromContext(ctx); ok {+ seen.Store(&confirmed)+ }+ return next(ctx, req)+ }+ })+ mux := http.NewServeMux()+ mux.Handle(v1connect.NewIssueServiceHandler(&confirmationProbe{}, connect.WithInterceptors(recorder)))+ s := newTestServerWithMock(t, mux)++ want := auth.MCPConfirmedDecision{+ Procedure: v1connect.IssueServiceApproveIssueProcedure,+ Issue: decideIssueName,+ IssueUpdateTime: time.Date(2026, 10, 13, 8, 0, 0, 123456000, time.UTC),+ }+ resp, err := s.apiRequest(auth.WithMCPConfirmedDecision(context.Background(), want),+ v1connect.IssueServiceApproveIssueProcedure, map[string]any{"name": decideIssueName})+ require.NoError(t, err)+ require.Equal(t, http.StatusOK, resp.Status, string(resp.Body))+ require.Equal(t, &want, seen.Load())+}diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.goindex f4cb402ea4..628ae5a330 100644--- a/backend/api/mcp/tool_query.go+++ b/backend/api/mcp/tool_query.go@@ -81,7 +81,7 @@ query_database(database="employee", instance="projects/hr/instances/prod-pg", st**Notes:**- Masked data: masking replaces a value fully (by default "******"), partly (e.g. "**rn**"), or with a hash. maskedColumns in the result names each masked column and why (not reported for MongoDB, CosmosDB or Elasticsearch). A masked value is a placeholder, not a value anything holds, so never write it back and never filter on it. Any statement containing "******" is refused. When showing a partly masked value, wrap it in backticks: "**rn**" renders as bold Markdown.-- Seeing masked values: the user can ask a project owner for a masking exemption, or, if the project allows just-in-time access, request an access grant with Unmask for this exact statement, schema and container. In a Read-write session, file the request with call_api(operationId="AccessGrantService/CreateAccessGrant"); otherwise the user requests it in the SQL Editor. After a person approves it, find the grant among the user's access grants, then rerun the granted statement unchanged with the grant's schema and container. appliedAccessGrant in the result names the grant that applied.+- Seeing masked values: the user can ask a project owner for a masking exemption, or, if the project allows just-in-time access, request an access grant with Unmask for this exact statement, schema and container. In a Read-write session, file the request with call_api(operationId="AccessGrantService/CreateAccessGrant"); otherwise the user requests it in the SQL Editor. Once it is approved, find the grant among the user's access grants, then rerun the granted statement unchanged with the grant's schema and container. appliedAccessGrant in the result names the grant that applied.`func (s *Server) registerQueryTool() {diff --git a/backend/api/v1/issue_review.go b/backend/api/v1/issue_review.goindex fd145f67b9..81c3b7d19e 100644--- a/backend/api/v1/issue_review.go+++ b/backend/api/v1/issue_review.go@@ -3,10 +3,12 @@ package v1import ("context""log/slog"+ "time""connectrpc.com/connect""github.com/pkg/errors"+ "github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/component/bus"@@ -42,12 +44,13 @@ func (s *IssueService) reviewIssue(ctx context.Context, name, comment string, acreturn nil, connect.NewError(connect.CodeInternal, errors.New("user not found"))}result, err := s.reviewWorkflow.ReviewIssue(ctx, review.IssueInput{- Workspace: common.GetWorkspaceIDFromContext(ctx),- ProjectID: projectID,- IssueUID: issueUID,- Actor: user,- Action: action,- Comment: comment,+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ ProjectID: projectID,+ IssueUID: issueUID,+ Actor: user,+ Action: action,+ Comment: comment,+ ConfirmedUpdateTime: confirmedUpdateTime(ctx),})if err != nil {return nil, mapReviewError(ctx, err, action)@@ -113,6 +116,16 @@ func (s *IssueService) reviewIssue(ctx context.Context, name, comment string, acreturn connect.NewResponse(converted), nil}+// confirmedUpdateTime returns the issue version an MCP confirmation applies+// to. The MCP gate has checked that it names this procedure and issue.+func confirmedUpdateTime(ctx context.Context) *time.Time {+ confirmed, ok := auth.MCPConfirmedDecisionFromContext(ctx)+ if !ok {+ return nil+ }+ return &confirmed.IssueUpdateTime+}+func mapReviewError(ctx context.Context, err error, action review.Action) error {var workflowErr *review.Errorif !errors.As(err, &workflowErr) {@@ -135,17 +148,21 @@ func mapReviewError(ctx context.Context, err error, action review.Action) error}return connect.NewError(connect.CodePermissionDenied, workflowErr)case review.ErrorConflict:- message := "cannot request issue because approval finding is stale"+ verb := "request issue"switch action {case review.ActionApprove:- message = "cannot approve because approval finding is stale"+ verb = "approve"case review.ActionReject:- message = "cannot reject because approval finding is stale"+ verb = "reject"case review.ActionRequest:default:return connect.NewError(connect.CodeInternal, errors.Errorf("unexpected review action %d", action))}- return connect.NewError(connect.CodeFailedPrecondition, errors.New(message))+ cause := "approval finding is stale"+ if workflowErr.Reason == review.ReasonChangedSinceConfirmed {+ cause = "the issue changed after the decision was confirmed"+ }+ return connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("cannot %s because %s", verb, cause))default:return connect.NewError(connect.CodeInternal, workflowErr)}diff --git a/backend/api/v1/issue_review_test.go b/backend/api/v1/issue_review_test.goindex d0bef6bf2f..bf1c3bf80a 100644--- a/backend/api/v1/issue_review_test.go+++ b/backend/api/v1/issue_review_test.go@@ -3,12 +3,15 @@ package v1import ("context""testing"+ "time""connectrpc.com/connect""github.com/pkg/errors""github.com/stretchr/testify/require"+ "github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/component/review"+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect")func TestMapReviewErrorMarksOnlyTheApproverRoleVerdict(t *testing.T) {@@ -50,3 +53,32 @@ func TestMapReviewErrorMarksOnlyTheApproverRoleVerdict(t *testing.T) {})}}++func TestMapReviewErrorSaysWhenAConfirmedIssueChanged(t *testing.T) {+ t.Parallel()++ err := mapReviewError(context.Background(), &review.Error{+ Code: review.ErrorConflict,+ Reason: review.ReasonChangedSinceConfirmed,+ Err: errors.New("the issue changed after the action was confirmed"),+ }, review.ActionApprove)+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))+ require.Contains(t, err.Error(), "cannot approve because the issue changed after the decision was confirmed")++ err = mapReviewError(context.Background(), &review.Error{Code: review.ErrorConflict, Err: errors.New("approval finding is stale")}, review.ActionReject)+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))+ require.Contains(t, err.Error(), "cannot reject because approval finding is stale")+}++func TestConfirmedUpdateTimeComesFromTheMCPConfirmation(t *testing.T) {+ t.Parallel()++ require.Nil(t, confirmedUpdateTime(context.Background()), "a decision made in the console carries no confirmed version")+ at := time.Date(2026, 10, 13, 8, 0, 0, 123456000, time.UTC)+ ctx := auth.WithMCPConfirmedDecision(context.Background(), auth.MCPConfirmedDecision{+ Procedure: v1connect.IssueServiceApproveIssueProcedure,+ Issue: "projects/hr/issues/42",+ IssueUpdateTime: at,+ })+ require.Equal(t, &at, confirmedUpdateTime(ctx))+}diff --git a/backend/api/v1/mcp_gate.go b/backend/api/v1/mcp_gate.goindex cc07022c9a..85c8af7ee7 100644--- a/backend/api/v1/mcp_gate.go+++ b/backend/api/v1/mcp_gate.go@@ -156,13 +156,14 @@ var mcpDenialReasons = map[v1pb.MCPDenialReason]mcpDenialWording{// follow-up (BOT-53); disallowing first is the deliberate order.v1pb.MCPDenialReason_REWRITES_SESSION_BOUNDARY: {v1pb.MCPMethodClass_FORBIDDEN, "it rewrites the workspace settings that bound this session, including the switch meant to contain it"},- v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION: {v1pb.MCPMethodClass_FORBIDDEN, "it decides whether a change or an access request passes its human approval, and an agent does not decide that for its own work"},+ v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION: {v1pb.MCPMethodClass_FORBIDDEN, "it can let a change or an access request pass its approval without an approver deciding it"},// The other refused class. An EXCLUDED method is out of scope for the modes- // this release ships and an admin-capable ceiling could legitimately serve- // it one day, while a FORBIDDEN method never becomes servable — so a denial- // that blurred the two would tell an operator the wrong thing about whether- // asking is worth it. The class on each row is what keeps them apart.+ // this release ships, and an admin-capable ceiling could legitimately serve+ // it one day; a FORBIDDEN method breaks the MCP boundary, so no ceiling+ // serves it. A denial that blurred the two would tell an operator the wrong+ // thing about whether asking is worth it. The class on each row is what+ // keeps them apart.v1pb.MCPDenialReason_ADMINISTERS_THE_WORKSPACE: {v1pb.MCPMethodClass_EXCLUDED, "it administers the workspace rather than doing database work, and no MCP mode this release ships covers workspace administration"},v1pb.MCPDenialReason_READS_OTHER_USERS_SQL: {v1pb.MCPMethodClass_EXCLUDED, "it returns SQL that other people wrote, across the workspace or past the sharing that keeps a saved query private"},v1pb.MCPDenialReason_OPENS_AN_ADMIN_CONNECTION: {v1pb.MCPMethodClass_EXCLUDED, "it opens an admin-credentialed connection to the database and returns other sessions' live, unmasked SQL"},@@ -461,11 +462,14 @@ func describeServedClasses(served []v1pb.MCPMethodClass) string {const mcpConsoleWayOut = "Perform this action signed in to the Bytebase console instead"// mcpRequestShapeRefusals holds the refusals a per-method class cannot express,-// because what the call does depends on a request field. Each entry returns the-// reason and the way out, or an empty reason to allow. It lives in the gate so a-// refusal is audited and worded like a class refusal, before the handler runs.+// because the verdict depends on a request field or on what the MCP server+// attached to the request context. Each entry returns the reason and the way+// out, or an empty reason to allow. It lives in the gate so a refusal is+// audited and worded like a class refusal, before the handler runs.var mcpRequestShapeRefusals = map[string]func(ctx context.Context, msg any) (reason, wayOut string){v1connect.IssueServiceCreateIssueProcedure: refuseGrantIssueCreation,+ v1connect.IssueServiceApproveIssueProcedure: refuseUnconfirmedIssueDecision,+ v1connect.IssueServiceRejectIssueProcedure: refuseUnconfirmedIssueDecision,v1connect.SheetServiceCreateSheetProcedure: inTheConsole(refuseMaskedWriteSheet),v1connect.SheetServiceBatchCreateSheetsProcedure: inTheConsole(refuseMaskedWriteSheetBatch),v1connect.ReleaseServiceCreateReleaseProcedure: inTheConsole(refuseMaskedWriteRelease),@@ -483,7 +487,8 @@ func inTheConsole(refuse func(context.Context, any) string) func(context.Context}// refuseByRequestShape applies the table above. The context carries what the-// gate resolved, so an entry can key on more than the request; none does today.+// gate resolved and what the MCP server attached, so an entry can key on more+// than the request.func refuseByRequestShape(ctx context.Context, procedure string, msg any) error {refuse, ok := mcpRequestShapeRefusals[procedure]if !ok {@@ -497,6 +502,29 @@ func refuseByRequestShape(ctx context.Context, procedure string, msg any) error"%s is not available to MCP sessions for this request because %s. %s", procedure, reason, wayOut))}+const mcpDecideIssueWayOut = "Use the decide_issue tool, which asks the user to confirm"++// refuseUnconfirmedIssueDecision serves an approval or a rejection only when+// the request context carries that decision as the user confirmed it in the MCP+// client, which decide_issue attaches after asking. call_api reaches the same+// procedures but cannot set a context value, so it is refused here.+func refuseUnconfirmedIssueDecision(ctx context.Context, msg any) (string, string) {+ var want auth.MCPConfirmedDecision+ switch request := msg.(type) {+ case *v1pb.ApproveIssueRequest:+ want = auth.MCPConfirmedDecision{Procedure: v1connect.IssueServiceApproveIssueProcedure, Issue: request.GetName()}+ case *v1pb.RejectIssueRequest:+ want = auth.MCPConfirmedDecision{Procedure: v1connect.IssueServiceRejectIssueProcedure, Issue: request.GetName()}+ default:+ return fmt.Sprintf("its request could not be read as an issue decision (%T)", msg), mcpDecideIssueWayOut+ }+ if confirmed, ok := auth.MCPConfirmedDecisionFromContext(ctx); ok && confirmed.Procedure == want.Procedure && confirmed.Issue == want.Issue {+ return "", ""+ }+ return "an issue is approved or rejected over MCP only after the user confirms that decision in the MCP client, " ++ "and this request carries no such confirmation", mcpDecideIssueWayOut+}+// refuseGrantIssueCreation applies grantIssueRefusal to CreateIssue. UpdateIssue's// allow_missing creation is guarded in its handler (rejectMCPOriginatedGrantIssue).func refuseGrantIssueCreation(_ context.Context, msg any) (string, string) {diff --git a/backend/api/v1/mcp_gate_test.go b/backend/api/v1/mcp_gate_test.goindex bebdb9bb01..44e3efb231 100644--- a/backend/api/v1/mcp_gate_test.go+++ b/backend/api/v1/mcp_gate_test.go@@ -7,6 +7,7 @@ import ("slices""strings""testing"+ "time""connectrpc.com/connect""github.com/pkg/errors"@@ -123,8 +124,6 @@ func TestForbiddenClassMembership(t *testing.T) {v1connect.UserServiceUpdateEmailProcedure,v1connect.SettingServiceUpdateSettingProcedure,v1connect.InstanceServiceUpdateDataSourceProcedure,- v1connect.IssueServiceApproveIssueProcedure,- v1connect.IssueServiceRejectIssueProcedure,v1connect.IssueServiceRetryIssueApprovalProcedure,v1connect.AccessGrantServiceActivateAccessGrantProcedure,v1connect.UserServiceChangePasswordProcedure,@@ -182,8 +181,6 @@ func TestForbiddenClassMembership(t *testing.T) {v1connect.SettingServiceTestEmailSettingProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS,v1connect.SettingServiceUpdateSettingProcedure: v1pb.MCPDenialReason_REWRITES_SESSION_BOUNDARY,v1connect.InstanceServiceUpdateDataSourceProcedure: v1pb.MCPDenialReason_MINTS_CREDENTIAL_FOR_OTHERS,- v1connect.IssueServiceApproveIssueProcedure: v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION,- v1connect.IssueServiceRejectIssueProcedure: v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION,v1connect.IssueServiceRetryIssueApprovalProcedure: v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION,v1connect.AccessGrantServiceActivateAccessGrantProcedure: v1pb.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION,}@@ -867,6 +864,13 @@ type mcpGateResult struct {// TestMCPGateRefusalIsStreamedWithoutAnAuditAnnotation proves the real// interceptor honors the mark.func invokeMCPGate(t *testing.T, stores mcpSettingsReader, authCtx *common.AuthContext, procedure string, req connect.AnyRequest) mcpGateResult {+ t.Helper()+ return invokeMCPGateFrom(context.Background(), t, stores, authCtx, procedure, req)+}++// invokeMCPGateFrom is invokeMCPGate on a caller-supplied context, for the+// requests whose verdict turns on what the MCP server attached to it.+func invokeMCPGateFrom(ctx context.Context, t *testing.T, stores mcpSettingsReader, authCtx *common.AuthContext, procedure string, req connect.AnyRequest) mcpGateResult {t.Helper()out := mcpGateResult{}next := func(ctx context.Context, _ connect.AnyRequest) (connect.AnyResponse, error) {@@ -874,7 +878,6 @@ func invokeMCPGate(t *testing.T, stores mcpSettingsReader, authCtx *common.AuthCout.dispatchedCtx = ctxreturn connect.NewResponse(&v1pb.User{}), nil}- ctx := context.Background()if authCtx != nil {ctx = context.WithValue(ctx, common.AuthContextKey, authCtx)}@@ -1204,6 +1207,80 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {})}+func TestMCPGateServesAnIssueDecisionOnlyWithItsConfirmation(t *testing.T) {+ const issue = "projects/p/issues/1"+ write := classContext(v1pb.MCPMethodClass_WRITE)+ decisions := map[string]func(name string) connect.AnyRequest{+ v1connect.IssueServiceApproveIssueProcedure: func(name string) connect.AnyRequest {+ return connect.NewRequest(&v1pb.ApproveIssueRequest{Name: name})+ },+ v1connect.IssueServiceRejectIssueProcedure: func(name string) connect.AnyRequest {+ return connect.NewRequest(&v1pb.RejectIssueRequest{Name: name})+ },+ }+ confirmed := func(procedure, name string) context.Context {+ return auth.WithMCPConfirmedDecision(context.Background(), auth.MCPConfirmedDecision{+ Procedure: procedure,+ Issue: name,+ IssueUpdateTime: time.Date(2026, 10, 13, 8, 0, 0, 123456000, time.UTC),+ })+ }+ other := map[string]string{+ v1connect.IssueServiceApproveIssueProcedure: v1connect.IssueServiceRejectIssueProcedure,+ v1connect.IssueServiceRejectIssueProcedure: v1connect.IssueServiceApproveIssueProcedure,+ }++ for procedure, request := range decisions {+ t.Run(procedure, func(t *testing.T) {+ t.Run("an unconfirmed request, as call_api sends it, is refused", func(t *testing.T) {+ got := invokeMCPGate(t, readWriteCeiling(), write, procedure, request(issue))+ require.Error(t, got.err)+ require.False(t, got.dispatched)+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(got.err))+ require.Contains(t, got.err.Error(), procedure)+ require.Contains(t, got.err.Error(), "confirms that decision in the MCP client")+ require.Contains(t, got.err.Error(), "decide_issue", "the denial must name the path that can confirm")+ require.True(t, got.auditMarked)+ })++ t.Run("the confirmed request is served", func(t *testing.T) {+ got := invokeMCPGateFrom(confirmed(procedure, issue), t, readWriteCeiling(), write, procedure, request(issue))+ require.NoError(t, got.err)+ require.True(t, got.dispatched)+ require.False(t, got.auditMarked)+ })++ t.Run("a confirmation for another issue is refused", func(t *testing.T) {+ got := invokeMCPGateFrom(confirmed(procedure, "projects/p/issues/2"), t, readWriteCeiling(), write, procedure, request(issue))+ require.Error(t, got.err)+ require.False(t, got.dispatched)+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(got.err))+ })++ t.Run("a confirmation for the other decision is refused", func(t *testing.T) {+ got := invokeMCPGateFrom(confirmed(other[procedure], issue), t, readWriteCeiling(), write, procedure, request(issue))+ require.Error(t, got.err)+ require.False(t, got.dispatched)+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(got.err))+ })++ t.Run("a confirmed request is still held to the ceiling", func(t *testing.T) {+ got := invokeMCPGateFrom(confirmed(procedure, issue), t, readOnlyCeiling(), write, procedure, request(issue))+ require.Error(t, got.err)+ require.False(t, got.dispatched)+ require.Contains(t, got.err.Error(), "READ_ONLY", "the ceiling refuses before the confirmation is looked at")+ })+ })+ }++ t.Run("a request the rule cannot read refuses", func(t *testing.T) {+ got := invokeMCPGateFrom(confirmed(v1connect.IssueServiceApproveIssueProcedure, issue), t, readWriteCeiling(), write,+ v1connect.IssueServiceApproveIssueProcedure, connect.NewRequest(&v1pb.GetIssueRequest{Name: issue}))+ require.Error(t, got.err)+ require.False(t, got.dispatched)+ })+}+// TestMCPGateRefusalIsStreamedWithoutAnAuditAnnotation is the policy-denial// line, end to end through the real audit interceptor. Every method below is// refused and carries no audit annotation, so its refusal is never stored anddiff --git a/backend/api/v1/mcp_masking_test.go b/backend/api/v1/mcp_masking_test.goindex a43d2bd508..d0b852fb79 100644--- a/backend/api/v1/mcp_masking_test.go+++ b/backend/api/v1/mcp_masking_test.go@@ -12,6 +12,7 @@ import ("github.com/bytebase/bytebase/backend/component/masker"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect""github.com/bytebase/bytebase/backend/store")@@ -142,9 +143,10 @@ func TestMaskedWriteGuardIsWiredIntoTheGate(t *testing.T) {}// A door added to the table but not exercised here ships wired to nothing,- // and the unit test above would still pass. CreateIssue is the one entry in- // mcpRequestShapeRefusals that is not a masked-write door.- require.Len(t, doors, len(mcpRequestShapeRefusals)-1,+ // and the unit test above would still pass. CreateIssue, ApproveIssue and+ // RejectIssue are the entries in mcpRequestShapeRefusals that are not+ // masked-write doors.+ require.Len(t, doors, len(mcpRequestShapeRefusals)-3,"every masked-write door in the refusal table needs a row here")for _, door := range doors {@@ -284,6 +286,13 @@ func TestMCPRefusalsNameThemselvesToTheQueryTool(t *testing.T) {unattended := refuseUnattendedMCPAccessGrant(mcpCtx, &storepb.IssuePayloadApproval{ApprovalFindingDone: true})require.Error(t, unattended)require.True(t, mcp.IsPolicyRefusal(unattended.Error()))++ unconfirmed := invokeMCPGate(t, readWrite, &common.AuthContext{+ MCPMethodClass: v1pb.MCPMethodClass_WRITE,+ DelegatedGrant: &common.DelegatedGrant{},+ }, v1connect.IssueServiceApproveIssueProcedure, connect.NewRequest(&v1pb.ApproveIssueRequest{Name: "projects/p/issues/1"}))+ require.Error(t, unconfirmed.err)+ require.True(t, mcp.IsPolicyRefusal(unconfirmed.err.Error()))}// TestMaskPlaceholderMatchIsDeliberatelyBroad records which side of the tradediff --git a/backend/api/v1/rollout_service.go b/backend/api/v1/rollout_service.goindex 8f7e4833fb..441f4615ef 100644--- a/backend/api/v1/rollout_service.go+++ b/backend/api/v1/rollout_service.go@@ -1420,11 +1420,12 @@ func (s *RolloutService) canUserCancelEnvironmentTaskRun(ctx context.Context, us// linked issue.//// Both approval checks on this path need a linked issue, so without this guard-// a session could skip the issue approval it may not give. Other callers keep-// issueless deployment, which the GitOps Service Agent role relies on; BOT-71-// tracks whether to close it for everyone. It must refuse before the rollout exists,-// because approval finding then refuses outright and strands the change, so-// CreateRollout is guarded as well as BatchRunTasks.+// a session could run a change this project requires approval for with no+// approval at all. Other callers keep issueless deployment, which the GitOps+// Service Agent role relies on; BOT-71 tracks whether to close it for everyone.+// It must refuse before the rollout exists, because approval finding then+// refuses outright and strands the change, so CreateRollout is guarded as well+// as BatchRunTasks.func rejectMCPOriginatedIssuelessRollout(ctx context.Context, project *store.ProjectMessage, issue *store.IssueMessage, action string) error {if !mcpSession(ctx) {return nildiff --git a/backend/api/v1/testdata/mcp_method_classification.md b/backend/api/v1/testdata/mcp_method_classification.mdindex 0125d12317..8c990ec4f7 100644--- a/backend/api/v1/testdata/mcp_method_classification.md+++ b/backend/api/v1/testdata/mcp_method_classification.md@@ -17,9 +17,9 @@ served by no ceiling.| Class | Methods | Meaning ||---|---|---|| READ | 68 | served to a read-only session and above |-| WRITE | 37 | served to a read-write session only |+| WRITE | 39 | served to a read-write session only || EXCLUDED | 78 | served by no ceiling this phase ships |-| FORBIDDEN | 36 | never served, whatever the ceiling |+| FORBIDDEN | 34 | never served, whatever the ceiling || MCP_METHOD_CLASS_UNSPECIFIED | 0 | unclassified — CI rejects this, and the gate refuses it || **total** | **219** | |@@ -96,7 +96,7 @@ served by no ceiling.| InstanceService/UndeleteInstance | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.instances.undelete || InstanceService/UpdateDataSource | FORBIDDEN | MINTS_CREDENTIAL_FOR_OTHERS | bb.instances.update || InstanceService/UpdateInstance | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.instances.update |-| IssueService/ApproveIssue | FORBIDDEN | DRIVES_THE_APPROVAL_DECISION | — |+| IssueService/ApproveIssue | WRITE | — | — || IssueService/BatchUpdateIssuesStatus | WRITE | — | bb.issues.update || IssueService/CreateIssue | WRITE | — | bb.issues.create || IssueService/CreateIssueComment | WRITE | — | bb.issueComments.create |@@ -104,7 +104,7 @@ served by no ceiling.| IssueService/GetReviewRun | READ | — | bb.reviewRuns.get || IssueService/ListIssueComments | READ | — | bb.issueComments.list || IssueService/ListIssues | READ | — | bb.issues.list |-| IssueService/RejectIssue | FORBIDDEN | DRIVES_THE_APPROVAL_DECISION | — |+| IssueService/RejectIssue | WRITE | — | — || IssueService/RequestIssue | WRITE | — | — || IssueService/RetryIssueApproval | FORBIDDEN | DRIVES_THE_APPROVAL_DECISION | — || IssueService/RunReview | WRITE | — | bb.reviewRuns.run |diff --git a/backend/component/audit/audit.go b/backend/component/audit/audit.goindex b259cef528..e0d41fcd3d 100644--- a/backend/component/audit/audit.go+++ b/backend/component/audit/audit.go@@ -57,8 +57,8 @@ func RecordOutOfBandAudit(ctx context.Context, writer LogWriter, mirrorToStdoutrow.Severity = storepb.AuditLog_WARNING// WithoutCancel so the row survives a client hanging up on its own refusal,- // bounded because WithoutCancel drops the request deadline too. Both- // callers write on the synchronous path of a refusal already decided, so an+ // bounded because WithoutCancel drops the request deadline too. Every+ // caller writes on the synchronous path of a refusal already decided, so an// unbounded insert holds the user's answer open.ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), outOfBandAuditTimeout)defer cancel()diff --git a/backend/component/review/workflow.go b/backend/component/review/workflow.goindex 7d4caec0d7..d0c60c9e74 100644--- a/backend/component/review/workflow.go+++ b/backend/component/review/workflow.go@@ -40,6 +40,9 @@ const (// is an IAM verdict about the caller from the project and ownership rules// that answer the same code: only the verdict is marked for the audit log.ReasonApproverRoleRequired+ // ReasonChangedSinceConfirmed is an ErrorConflict for an action confirmed+ // against an earlier version of the issue.+ ReasonChangedSinceConfirmed)// Error is a typed review transition error.@@ -150,6 +153,9 @@ type IssueInput struct {Actor *store.UserMessageAction ActionComment string+ // ConfirmedUpdateTime, when set, is the issue version the actor confirmed+ // the action against, as in an MCP client; it is refused on any other.+ ConfirmedUpdateTime *time.Time}// IssueResult is the committed state and its post-commit effects.@@ -255,6 +261,11 @@ func (w *Workflow) ReviewIssue(ctx context.Context, input IssueInput) (*IssueResif lockedIssue == nil {return nil, workflowError(ErrorNotFound, "issue %d not found in project %s", input.IssueUID, input.ProjectID)}+ // Checked on the locked row: the action above was computed from an unlocked+ // read, which can already be newer than what the actor confirmed.+ if input.ConfirmedUpdateTime != nil && !lockedIssue.UpdatedAt.Equal(*input.ConfirmedUpdateTime) {+ return nil, workflowReasonError(ErrorConflict, ReasonChangedSinceConfirmed, "the issue changed after the action was confirmed")+ }plan, err := lockIssuePlan(ctx, tx, lockedIssue)if err != nil {return nil, errdiff --git a/backend/component/review/workflow_test.go b/backend/component/review/workflow_test.goindex 9040586c2b..053191898b 100644--- a/backend/component/review/workflow_test.go+++ b/backend/component/review/workflow_test.go@@ -437,6 +437,55 @@ func TestReviewIssueConcurrentApprovalsHaveOneWinner(t *testing.T) {require.Equal(t, 1, rejected)}+func TestReviewIssueAppliesAConfirmedActionOnlyToTheConfirmedVersion(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ _, err := stores.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{+ Workspace: "default",+ Member: common.FormatUserEmail("[email protected]"),+ Roles: []string{"roles/projectOwner"},+ })+ require.NoError(t, err)+ confirmedApproval := func(issue *store.IssueMessage) IssueInput {+ return IssueInput{+ Workspace: "default",+ ProjectID: "project-a",+ IssueUID: issue.UID,+ Actor: &store.UserMessage{Email: "[email protected]"},+ Action: ActionApprove,+ ConfirmedUpdateTime: &issue.UpdatedAt,+ }+ }++ t.Run("unchanged", func(t *testing.T) {+ _, issue := createPendingDatabaseChangeApproval(ctx, t, stores, []string{"roles/projectOwner"})+ result, err := NewWorkflow(stores).ReviewIssue(ctx, confirmedApproval(issue))+ require.NoError(t, err)+ require.True(t, result.Approved)+ })++ t.Run("changed after the workflow read it", func(t *testing.T) {+ _, issue := createPendingDatabaseChangeApproval(ctx, t, stores, []string{"roles/projectOwner"})+ workflow := NewWorkflow(stores)+ // The edit lands between the workflow's unlocked read and its lock and+ // leaves the approval as it was, so only the confirmed version refuses.+ workflow.beforeCommit = func() {+ title := "drop database"+ _, err := stores.UpdateIssue(ctx, "project-a", issue.UID, &store.UpdateIssueMessage{Title: &title})+ require.NoError(t, err)+ }++ _, err := workflow.ReviewIssue(ctx, confirmedApproval(issue))+ var workflowErr *Error+ require.True(t, errors.As(err, &workflowErr))+ require.Equal(t, ErrorConflict, workflowErr.Code)+ require.Equal(t, ReasonChangedSinceConfirmed, workflowErr.Reason)+ after, err := stores.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, err)+ require.Empty(t, after.Payload.GetApproval().GetApprovers(), "a refused action records no approval")+ })+}+func TestPlanUpdateMakesPendingApprovalActionStale(t *testing.T) {ctx := context.Background()stores := setupWorkflowStore(ctx, t)diff --git a/backend/generated-go/v1/annotation.pb.go b/backend/generated-go/v1/annotation.pb.goindex 98e837a72b..01fae5602e 100644--- a/backend/generated-go/v1/annotation.pb.go+++ b/backend/generated-go/v1/annotation.pb.go@@ -272,11 +272,9 @@ const (// key is sent to. A session that can widen its own ceiling is not bounded// by it.MCPDenialReason_REWRITES_SESSION_BOUNDARY MCPDenialReason = 7- // Decides whether a change or an access request passes its human approval:- // recording the review decision, re-running the finding that sets it and can- // clear the issue outright, or activating an access grant without it. An- // agent composes a change or files a request; it does not decide that for its- // own work.+ // Can let a change or an access request pass its approval without an+ // approver deciding it: re-running the finding that sets the approval, which+ // can clear the issue outright, or activating an access grant directly.MCPDenialReason_DRIVES_THE_APPROVAL_DECISION MCPDenialReason = 8// Administers the workspace rather than doing database work: identity,// credentials, access control, governance policy, billing, workspace anddiff --git a/backend/generated-go/v1/issue_service.pb.go b/backend/generated-go/v1/issue_service.pb.goindex ad8ee1e5ea..e7b7d26cbf 100644--- a/backend/generated-go/v1/issue_service.pb.go+++ b/backend/generated-go/v1/issue_service.pb.go@@ -2980,7 +2980,7 @@ const file_v1_issue_service_proto_rawDesc = "" +"\x16bytebase.com/ReviewRunR\x04name\"F\n" +"\x10RunReviewRequest\x122\n" +"\x04name\x18\x01 \x01(\tB\x1e\xe0A\x02\xfaA\x18\n" +- "\x16bytebase.com/ReviewRunR\x04name2\xfc\x13\n" ++ "\x16bytebase.com/ReviewRunR\x04name2\xf4\x13\n" +"\fIssueService\x12\x84\x01\n" +"\bGetIssue\x12\x1c.bytebase.v1.GetIssueRequest\x1a\x12.bytebase.v1.Issue\"F\xdaA\x04name\x8a\xea0\rbb.issues.get\x90\xea0\x01\xa0\xea0\x01\x82\xd3\xe4\x93\x02 \x12\x1e/v1/{name=projects/*/issues/*}\x12\xa0\x01\n" +"\vCreateIssue\x12\x1f.bytebase.v1.CreateIssueRequest\x1a\x12.bytebase.v1.Issue\"\\\xdaA\fparent,issue\x8a\xea0\x10bb.issues.create\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x02':\x05issue\"\x1e/v1/{parent=projects/*}/issues\x12\x98\x01\n" +@@ -2991,9 +2991,9 @@ const file_v1_issue_service_proto_rawDesc = "" +"\x11ListIssueComments\x12%.bytebase.v1.ListIssueCommentsRequest\x1a&.bytebase.v1.ListIssueCommentsResponse\"`\xdaA\x06parent\x8a\xea0\x15bb.issueComments.list\x90\xea0\x01\xa0\xea0\x01\x82\xd3\xe4\x93\x020\x12./v1/{parent=projects/*/issues/*}/issueComments\x12\xd6\x01\n" +"\x12CreateIssueComment\x12&.bytebase.v1.CreateIssueCommentRequest\x1a\x19.bytebase.v1.IssueComment\"}\xdaA\x14parent,issue_comment\x8a\xea0\x17bb.issueComments.create\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x029:\rissue_comment\"(/v1/{parent=projects/*/issues/*}:comment\x12\xe3\x01\n" +"\x12UpdateIssueComment\x12&.bytebase.v1.UpdateIssueCommentRequest\x1a\x19.bytebase.v1.IssueComment\"\x89\x01\xdaA parent,issue_comment,update_mask\x8a\xea0\x17bb.issueComments.update\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x029:\rissue_comment2(/v1/{parent=projects/*/issues/*}:comment\x12\xd1\x01\n" +- "\x17BatchUpdateIssuesStatus\x12+.bytebase.v1.BatchUpdateIssuesStatusRequest\x1a,.bytebase.v1.BatchUpdateIssuesStatusResponse\"[\x8a\xea0\x10bb.issues.update\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x025:\x01*\"0/v1/{parent=projects/*}/issues:batchUpdateStatus\x12\x87\x01\n" +- "\fApproveIssue\x12 .bytebase.v1.ApproveIssueRequest\x1a\x12.bytebase.v1.Issue\"A\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\b\x82\xd3\xe4\x93\x02+:\x01*\"&/v1/{name=projects/*/issues/*}:approve\x12\x84\x01\n" +- "\vRejectIssue\x12\x1f.bytebase.v1.RejectIssueRequest\x1a\x12.bytebase.v1.Issue\"@\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\b\x82\xd3\xe4\x93\x02*:\x01*\"%/v1/{name=projects/*/issues/*}:reject\x12\x83\x01\n" ++ "\x17BatchUpdateIssuesStatus\x12+.bytebase.v1.BatchUpdateIssuesStatusRequest\x1a,.bytebase.v1.BatchUpdateIssuesStatusResponse\"[\x8a\xea0\x10bb.issues.update\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x025:\x01*\"0/v1/{parent=projects/*}/issues:batchUpdateStatus\x12\x83\x01\n" ++ "\fApproveIssue\x12 .bytebase.v1.ApproveIssueRequest\x1a\x12.bytebase.v1.Issue\"=\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x02+:\x01*\"&/v1/{name=projects/*/issues/*}:approve\x12\x80\x01\n" ++ "\vRejectIssue\x12\x1f.bytebase.v1.RejectIssueRequest\x1a\x12.bytebase.v1.Issue\"<\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x02*:\x01*\"%/v1/{name=projects/*/issues/*}:reject\x12\x83\x01\n" +"\fRequestIssue\x12 .bytebase.v1.RequestIssueRequest\x1a\x12.bytebase.v1.Issue\"=\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x02\x82\xd3\xe4\x93\x02+:\x01*\"&/v1/{name=projects/*/issues/*}:request\x12\x99\x01\n" +"\x12RetryIssueApproval\x12&.bytebase.v1.RetryIssueApprovalRequest\x1a\x12.bytebase.v1.Issue\"G\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\b\x82\xd3\xe4\x93\x021:\x01*\",/v1/{name=projects/*/issues/*}:retryApproval\x12\xa1\x01\n" +"\fGetReviewRun\x12 .bytebase.v1.GetReviewRunRequest\x1a\x16.bytebase.v1.ReviewRun\"W\xdaA\x04name\x8a\xea0\x11bb.reviewRuns.get\x90\xea0\x01\xa0\xea0\x01\x82\xd3\xe4\x93\x02-\x12+/v1/{name=projects/*/issues/*/reviewRuns/*}\x12\xa6\x01\n" +diff --git a/backend/tests/mcp_gate_test.go b/backend/tests/mcp_gate_test.goindex fe14b3f33a..b916737d29 100644--- a/backend/tests/mcp_gate_test.go+++ b/backend/tests/mcp_gate_test.go@@ -6,11 +6,14 @@ import ("encoding/json""fmt""net/http"+ "strings"+ "sync/atomic""testing""time""connectrpc.com/connect""github.com/google/uuid"+ "github.com/modelcontextprotocol/go-sdk/mcp""github.com/stretchr/testify/require""google.golang.org/genproto/googleapis/type/expr""google.golang.org/protobuf/types/known/durationpb"@@ -85,10 +88,11 @@ func TestMCPGateServesAndRefusesByClass(t *testing.T) {"a served, audited MCP call is stored")}-// TestMCPGateRefusesGrantIssues covers, over one live MCP session, the grant-// issues a session may not create and the access request it may file instead,-// which needs a project that allows just-in-time access.-func TestMCPGateRefusesGrantIssues(t *testing.T) {+// TestMCPGrantIssuesAndAccessRequests covers, over one live MCP session, the+// grant issues a session may not create, the access request it may file+// instead (in a project that allows just-in-time access), and deciding that+// request through decide_issue.+func TestMCPGrantIssuesAndAccessRequests(t *testing.T) {t.Parallel()a := require.New(t)ctx := context.Background()@@ -105,7 +109,14 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {// depend on the resolved default.a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))- session := openMCPSession(ctx, t, ctl, ctl.authInterceptor.token)+ // The client confirms every decision it is asked about.+ var asked atomic.Int32+ session := openMCPSessionWithOptions(ctx, t, ctl, ctl.authInterceptor.token, &mcp.ClientOptions{+ ElicitationHandler: func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ asked.Add(1)+ return &mcp.ElicitResult{Action: "accept", Content: map[string]any{"confirm": true}}, nil+ },+ })defer session.Close()grant := callAPIOnSession(ctx, t, session, "IssueService/CreateIssue", map[string]any{@@ -271,6 +282,37 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {a.NoError(err)a.Equal(v1pb.AccessGrant_PENDING, still.Msg.Status)+ // call_api cannot carry a confirmation, so the gate refuses its approval.+ unconfirmed := callAPIOnSession(ctx, t, session, "IssueService/ApproveIssue", map[string]any{"name": pending.Issue})+ a.Equal(http.StatusForbidden, unconfirmed.Status)+ a.Contains(unconfirmed.Error, "decide_issue", "the refusal must name the path that asks the user")++ // The requester approves its own request. The project leaves self-approval+ // off, so the workflow refuses it after the user confirms, as it would in+ // the console, and the tool reports why.+ refused, refusedText := decideIssueOnSession(ctx, t, session, pending.Issue, "approve")+ a.True(refused, refusedText)+ a.Contains(refusedText, "self-approval is not allowed")+ still, err = ctl.accessGrantServiceClient.GetAccessGrant(ctx, connect.NewRequest(&v1pb.GetAccessGrantRequest{Name: pending.Name}))+ a.NoError(err)+ a.Equal(v1pb.AccessGrant_PENDING, still.Msg.Status)++ // With self-approval on, the same confirmed approval goes through: the+ // requester holds the step's role as the project's creator, and the grant+ // starts.+ _, err = ctl.projectServiceClient.UpdateProject(ctx, connect.NewRequest(&v1pb.UpdateProjectRequest{+ Project: &v1pb.Project{Name: projectName, AllowSelfApproval: true},+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"allow_self_approval"}},+ }))+ a.NoError(err)+ failed, approvedText := decideIssueOnSession(ctx, t, session, pending.Issue, "approve")+ a.False(failed, approvedText)+ a.Contains(approvedText, "Approved "+pending.Issue)+ approved, err := ctl.accessGrantServiceClient.GetAccessGrant(ctx, connect.NewRequest(&v1pb.GetAccessGrantRequest{Name: pending.Name}))+ a.NoError(err)+ a.Equal(v1pb.AccessGrant_ACTIVE, approved.Msg.Status)+ a.Equal(int32(2), asked.Load(), "each decision asks the user once")+consoleRequest := func() *v1pb.AccessGrant {granted, err := consoleCreate()a.NoError(err)@@ -315,6 +357,117 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {}}+// A project developer cannot get access grants, but the approval rule may still+// name developers, and the console shows a requester their own grant.+func TestMCPDeveloperApprovesTheirOwnAccessRequest(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl, ctx := startWorkspace(ctx, t)++ project, err := ctl.projectServiceClient.CreateProject(ctx, connect.NewRequest(&v1pb.CreateProjectRequest{+ ProjectId: "mcp-developer-grant",+ Project: &v1pb.Project{Title: "MCP developer grant", AllowSelfApproval: true},+ }))+ a.NoError(err)+ a.NoError(ctl.allowJustInTimeAccess(ctx, project.Msg))+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))+ _, err = ctl.settingServiceClient.UpdateSetting(ctx, connect.NewRequest(&v1pb.UpdateSettingRequest{+ AllowMissing: true,+ Setting: &v1pb.Setting{+ Name: "settings/WORKSPACE_APPROVAL",+ Value: &v1pb.SettingValue{Value: &v1pb.SettingValue_WorkspaceApproval{+ WorkspaceApproval: &v1pb.WorkspaceApprovalSetting{Rules: []*v1pb.WorkspaceApprovalSetting_Rule{{+ Source: v1pb.WorkspaceApprovalSetting_Rule_REQUEST_ACCESS,+ Condition: &expr.Expr{Expression: "true"},+ Template: &v1pb.ApprovalTemplate{Flow: &v1pb.ApprovalFlow{Roles: []string{"roles/projectDeveloper"}}},+ }}},+ }},+ },+ }))+ a.NoError(err)++ pgContainer := sharedPgTarget(t)+ instance, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{+ InstanceId: generateRandomString("inst"),+ Instance: &v1pb.Instance{+ SyncDatabases: &v1pb.SyncDatabases{},+ Title: "MCP developer grant instance",+ Engine: v1pb.Engine_POSTGRES,+ Environment: new("environments/prod"),+ Activation: true,+ DataSources: []*v1pb.DataSource{pgContainer.adminDataSource()},+ },+ }))+ a.NoError(err)+ dbName := generateRandomString("db")+ a.NoError(ctl.createDatabase(ctx, project.Msg, instance.Msg, nil, dbName, ""))++ email, password := "[email protected]", "1024bytebase"+ developer, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{+ User: &v1pb.User{Email: email, Password: password, Title: "Developer"},+ }))+ a.NoError(err)+ _, err = ctl.addMemberToWorkspaceIAM(ctx, developer.Msg.Workspace, "user:"+email, "roles/workspaceMember")+ a.NoError(err)+ policy, err := ctl.projectServiceClient.GetIamPolicy(ctx, connect.NewRequest(&v1pb.GetIamPolicyRequest{Resource: project.Msg.Name}))+ a.NoError(err)+ policy.Msg.Bindings = append(policy.Msg.Bindings, &v1pb.Binding{Role: "roles/projectDeveloper", Members: []string{"user:" + email}})+ _, err = ctl.projectServiceClient.SetIamPolicy(ctx, connect.NewRequest(&v1pb.SetIamPolicyRequest{Resource: project.Msg.Name, Policy: policy.Msg}))+ a.NoError(err)+ login, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{Email: email, Password: password}))+ a.NoError(err)++ var asked atomic.Int32+ session := openMCPSessionWithOptions(ctx, t, ctl, login.Msg.Token, &mcp.ClientOptions{+ ElicitationHandler: func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ asked.Add(1)+ return &mcp.ElicitResult{Action: "accept", Content: map[string]any{"confirm": true}}, nil+ },+ })+ defer session.Close()+ filed := callAPIOnSession(ctx, t, session, "AccessGrantService/CreateAccessGrant", map[string]any{+ "parent": project.Msg.Name,+ "accessGrant": map[string]any{+ "targets": []string{fmt.Sprintf("%s/databases/%s", instance.Msg.Name, dbName)},+ "query": "SELECT 1",+ "reason": "the agent needs one read",+ "ttl": "3600s",+ },+ })+ a.Equal(http.StatusOK, filed.Status, filed.Error)+ var pending v1pb.AccessGrant+ a.NoError(common.ProtojsonUnmarshaler.Unmarshal([]byte(filed.RawResponse), &pending))+ read := callAPIOnSession(ctx, t, session, "AccessGrantService/GetAccessGrant", map[string]any{"name": pending.Name})+ a.Equal(http.StatusForbidden, read.Status, "a project developer cannot get access grants: %s", read.Error)++ failed, text := decideIssueOnSession(ctx, t, session, pending.Issue, "approve")+ a.False(failed, text)+ a.Contains(text, "Approved "+pending.Issue)+ a.Equal(int32(1), asked.Load(), "the user is shown the request and asked once")+ approved, err := ctl.accessGrantServiceClient.GetAccessGrant(ctx, connect.NewRequest(&v1pb.GetAccessGrantRequest{Name: pending.Name}))+ a.NoError(err)+ a.Equal(v1pb.AccessGrant_ACTIVE, approved.Msg.Status)+}++// decideIssueOnSession runs the decide_issue tool and returns whether it+// reported an error, with the text an agent would read.+func decideIssueOnSession(ctx context.Context, t *testing.T, session *mcp.ClientSession, issue, decision string) (bool, string) {+ t.Helper()+ result, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "decide_issue",+ Arguments: map[string]any{"issue": issue, "decision": decision},+ })+ require.NoError(t, err)+ var texts []string+ for _, content := range result.Content {+ if text, ok := content.(*mcp.TextContent); ok {+ texts = append(texts, text.Text)+ }+ }+ return result.IsError, strings.Join(texts, "")+}+// TestMCPCannotRunAnIssuelessRollout pins rejectMCPOriginatedIssuelessRollout// over a live session, and that a console user doing the same is unaffected.func TestMCPCannotRunAnIssuelessRollout(t *testing.T) {diff --git a/backend/tests/mcp_migration_matrix_test.go b/backend/tests/mcp_migration_matrix_test.goindex ebb111cf53..996959049a 100644--- a/backend/tests/mcp_migration_matrix_test.go+++ b/backend/tests/mcp_migration_matrix_test.go@@ -106,7 +106,14 @@ func postMCP(t *testing.T, ctl *controller, bearer string) (int, string) {// holding this bearer would.func openMCPSession(ctx context.Context, t *testing.T, ctl *controller, bearer string) *mcp.ClientSession {t.Helper()- client := mcp.NewClient(&mcp.Implementation{Name: "bb-e2e", Version: "0"}, nil)+ return openMCPSessionWithOptions(ctx, t, ctl, bearer, nil)+}++// openMCPSessionWithOptions is openMCPSession for a client that declares more,+// such as an elicitation handler.+func openMCPSessionWithOptions(ctx context.Context, t *testing.T, ctl *controller, bearer string, opts *mcp.ClientOptions) *mcp.ClientSession {+ t.Helper()+ client := mcp.NewClient(&mcp.Implementation{Name: "bb-e2e", Version: "0"}, opts)session, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: ctl.rootURL + "/mcp",HTTPClient: &http.Client{Transport: &bearerTransport{token: bearer}},diff --git a/docs/design/mcp-capability-ladder.md b/docs/design/mcp-capability-ladder.mdindex 74139b85be..2fc2e0c6eb 100644--- a/docs/design/mcp-capability-ladder.md+++ b/docs/design/mcp-capability-ladder.md@@ -6,7 +6,7 @@ The MCP settings page offers three modes (Disabled, Read-only, Read-write) and done sentence. Since [#21324](https://github.com/bytebase/bytebase/pull/21324) removed the per-modemethod drawer, nothing on the page says what a mode actually serves, and an admin choosing betweenRead-only and Read-write has nothing to compare beyond two sentences. The rule this doc lands on:-**show capabilities, not methods or permissions — one ordered list of ten capability rows in+**show capabilities, not methods or permissions — one ordered list of eleven capability rows inwhich 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@@ -59,7 +59,7 @@ What follows from it:## The rows-Ten rows: four read, six write. Each has a title and a one-line list of sub-items in plain+Eleven rows: four read, seven write. Each has a title and a one-line list of sub-items in plainwords. The right column records which classified methods the row's wording has to cover; it isdocumentation for whoever rereads these rows after a classification change, and never appears inthe product.@@ -71,18 +71,19 @@ the product.| read | Read the change workflow | Issues and comments · Plans and plan checks · Rollouts, task runs and logs · Releases · Rollback previews | 17 READ methods: issue, plan, rollout and release reads || read | Read members, roles and policies | Who holds which role in the workspace and its projects · Groups and their members · Roles and their permissions · Masking rules and exemptions · Rollout, data query, tag and review policies · Access grants, including pending requests | 12 READ methods: `GetIamPolicy` on projects and the workspace, group reads (3), role reads (2), `GetPolicy`, `ListPolicies`, access-grant reads (3, with `SearchMyAccessGrants`) || — | *Read-only stops here* | | 68 methods |-| 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 | Request access grants | Ask for a time-boxed grant to run a specific statement, optionally with results unmasked or exported; the statement must be a read as far as the engine can check it · The grant starts only after a person approves it, and a request that would need no one's approval is refused · A grant applies only where the project allows access grants | 1 WRITE method: `AccessGrantService/CreateAccessGrant` |+| 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. The project's approval policy decides whether a change needs approval | 22 WRITE methods: sheet, plan, issue, release and revision writes, `RequestIssue`, `RunReview`, `DiffSchema`, `DiffMetadata` |+| write | Request access grants | Ask for a time-boxed grant to run a specific statement, optionally with results unmasked or exported; the statement must be a read as far as the engine can check it · The grant starts only after it is approved, and a request that would need no one's approval is refused · A grant applies only where the project allows access grants | 1 WRITE method: `AccessGrantService/CreateAccessGrant` |+| write | Approve or reject issues | Each decision is confirmed in the user's MCP client before it is made · Role requests are decided in the console · The approval rules and the project's self-approval setting apply, as in the console | 2 WRITE methods: `ApproveIssue`, `RejectIssue`, served only through the `decide_issue` tool, which asks the user to confirm each decision and refuses role requests || 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, 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 · Saved queries | 9 WRITE methods: sync, saved-query writes |-| — | *Read-write stops here* | | 105 methods |-| floor | Never, in any mode: approve issues, administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history. | | 114 methods: 36 FORBIDDEN, 78 EXCLUDED |+| — | *Read-write stops here* | | 107 methods |+| floor | Never, in any mode: administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history. | | 112 methods: 34 FORBIDDEN, 78 EXCLUDED |Every row is displayed under every mode — served, or muted with a `—` — and against every engine aworkspace happens to hold, so **every line on this card must be true on both axes: mode and engine.**-That covers the ten rows, and equally the collapsed summary, the card captions and the "Best for"+That covers the eleven 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 theline most admins read and often the only one. Aclaim whose truth depends on the mode names the mode as a condition; a claim whose truth depends on@@ -194,20 +195,31 @@ under that same flag, and an issue whose approval finding produced no template cwith no human acting. The console turns the flag on for new projects; the API default is off. A rowthat said "of an approved change" would therefore promise more than the gate enforces, and thewording an admin reads while choosing Read-write is the wrong place to be generous. What holds-unconditionally is that an agent never approves its own change, because the approval methods are-FORBIDDEN: approving, rejecting and re-checking an issue, and activating an access grant. That is-the half the rows state. Whether MCP-originated rollouts should require-approval regardless of the project flag is a product question tracked separately (BOT-71), not one-this doc decides.--Access requests are the exception, and the request row states the person's approval-unconditionally. An approved access grant is active at once, so an MCP session's request that would-count as approved on creation, with no approval template or one that names no approver, is refused+unconditionally is that no approval decision is made over MCP without a confirmation in the client.+A Read-write session approves or rejects an issue only through the `decide_issue` tool. The tool+decides database changes and access requests. It refuses role requests, because approving one grants+a project role, and role grants stay in the console with the rest of access administration. It asks+the user through MCP form elicitation, inside the same tool call, and acts only on an accepted form+with the box checked. A client that cannot show the form gets the issue's console link. The gate+serves `ApproveIssue` and `RejectIssue` only to a request that carries the confirmation, so+`call_api` is refused. The workflow then decides as it does for a person: the step's role, and the+project's self-approval and last-editor settings. Bytebase records the decision as confirmed in the+client, not as proof that a person clicked: a hook in the user's own client can answer the form, and+that is the user's choice. Re-checking an issue's approval and activating an access grant directly+stay FORBIDDEN, because each can let a request pass with no approver deciding it. That is the half+the rows state. Whether MCP-originated rollouts should require approval regardless of the project+flag is a product question tracked separately (BOT-71), not one this doc decides.++Access requests are the exception, and the request row states the approval unconditionally. An+approved access grant is active at once, so an MCP session's request that would count as approved+on creation, with no approval template or one that names no approver, is refusedbefore any row is written (`refuseUnattendedMCPAccessGrant` in`backend/api/v1/access_grant_service.go`). The finding is saved on the request's issue atcreation, so an approval-rule edit afterwards cannot change it. Every other way a request becomes-active is an approval method above, FORBIDDEN to the session. The person who approves can be the-requester, signed in to the console; the rows promise a person, not a second one.+active goes through an approver: in the console, or through `decide_issue` with a confirmation in+the client. Activating a grant directly stays FORBIDDEN to the session. The approver can be the+requester where the project allows self-approval; the rows promise an approval, not a second+person.The members row shows who holds which role, the groups and their members, each role's permissionsand every policy type, so an agent can tell which people an approval step waits on. Two choices in@@ -228,9 +240,11 @@ pinning the creator, which this row does not touch.### The verb rule-The verb names the row's effect on the customer's databases. *Read*: none. *Propose*: none until a-human approves. *Request*: none until a person approves, and then access to one statement's results,-unmasked or exported if asked for. *Run*: direct. *Export*: data leaves the product. *Manage*:+The verb names the row's effect on the customer's databases. *Read*: none. *Propose*: none until it+is approved. *Request*: none until it is approved, and then access to one statement's results,+unmasked or exported if asked for. *Approve*: none directly; the issue proceeds: a change rolls out+as the project's rollout policy allows, and an access request takes effect. Role requests stay in+the console. *Run*: direct. *Export*: data leaves the product. *Manage*:configuration only, no data path. Within a tier the verb repeats; it changes only where the effectchanges.@@ -240,18 +254,19 @@ One verb for the whole write tier was tried and rejected:change proposals" (nothing reaches a database until approval), "Write rollouts" (not English),"Write database housekeeping" (reads as a data change).- **Change** for every write row: fails for exports and rollouts, and makes "Change proposals" and- "Change data with SQL" read as the same thing — the distinction the FORBIDDEN approval methods- exist to protect.+ "Change data with SQL" read as the same thing — the distinction the approval step exists to+ protect.- **Manage** for every write row: hides the hazard on exports and on SQL.Per row: *Propose* over Create (Create fits the method names but hides that the project's approval-policy may still require a human); *Export* over Read or Download (Read hides the egress hazard,+policy may still require approval); *Export* over Read or Download (Read hides the egress hazard,which is why Export is WRITE-class in the first place); *Manage* over Update or Maintain (Update-reads as a data change, Maintain is vague); *Request* over Propose (a proposal waits for a person+reads as a data change, Maintain is vague); *Request* over Propose (a proposal waits for approvalonly when the project's approval policy says so, a session's request always does, and what an approved request-gives is access to data, not a change). Rollouts and DML/DDL both take *Run* and stay two rows,-because a custom policy will want "run approved rollouts, but no ad-hoc SQL" — the workflow the-product exists for.+gives is access to data, not a change); *Approve* is a row of its own, not a sub-item of Propose,+because deciding someone's proposal or request is a different effect from filing one. Rollouts and+DML/DDL both take *Run* and stay two rows, because a custom policy will want "run approved+rollouts, but no ad-hoc SQL" — the workflow the product exists for.The tier is named once, by the dividers, so no row repeats it in its title.@@ -277,7 +292,7 @@ its tier tag, nothing else. "Show details" reveals the sub-item line for every rthere is one second-level control rather than one per row; per-row expanders were rejected as fiddly. Nomethod names, no permission names, no counts, no link to a method list. The floor is kept as oneshort line because it is what a security-minded admin reads first, and it is what keeps the list-honest about the 114 methods no mode reaches. There is no constants line under the list; the facts+honest about the 112 methods no mode reaches. There is no constants line under the list; the factsit would carry (capped by the user's own permissions, refusals audited) move into the sectiondescription.@@ -418,7 +433,7 @@ under- 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, the change workflow, members, roles and policies; a request carrying anything that cannot be shown to be a read is refused, and nothing is exported".- Read-write: "Read schemas, data, the change workflow, members, roles and policies; propose, request access, run, export and manage".+ Read-write: "Read schemas, data, the change workflow, members, roles and policies; propose, request access, approve, 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."@@ -431,11 +446,16 @@ underis retired everywhere; its content lives in the Read-only summary and in row 2's sub-item.- 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, handle credentials, open an Admin mode session, or read anyone else's query history."- The verbs cover every denial reason except two, `SENDS_DATA_TO_A_THIRD_PARTY` for the reason below- and `REDRAWS_GOVERNANCE_BOUNDARY`, 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+- Floor: "Never, in any mode: administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history."+ "Approve issues" left the floor when approving and rejecting moved to the confirmed tool.+ "Administer the workspace" still holds for role grants, because that tool refuses role requests.+ The verbs cover every denial reason except three: `SENDS_DATA_TO_A_THIRD_PARTY` for the reason+ below, `REDRAWS_GOVERNANCE_BOUNDARY`, and `DRIVES_THE_APPROVAL_DECISION`, whose two remaining+ methods re-check an issue's approval and activate an access grant directly. The verbs 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 theconsole: `GetSavedQuery` reaches SQL shared by a binding, and `searchScope` drops all scoping fora caller holding project-wide `bb.savedQueries.get`. Query history is the one that qualifies,diff --git a/frontend/src/components/mcp/mcpCapabilityRows.ts b/frontend/src/components/mcp/mcpCapabilityRows.tsindex a08c0e9b6d..d885baeeaa 100644--- a/frontend/src/components/mcp/mcpCapabilityRows.ts+++ b/frontend/src/components/mcp/mcpCapabilityRows.ts@@ -22,6 +22,7 @@ export type MCPCapabilityRowId =| "read-access"| "propose"| "request-access"+ | "approve"| "run-rollouts"| "run-statements"| "export"@@ -55,6 +56,7 @@ export const MCP_CAPABILITY_ROWS: readonly MCPCapabilityRow[] = [{ id: "read-access", tier: "read" },{ id: "propose", tier: "write" },{ id: "request-access", tier: "write" },+ { id: "approve", tier: "write" },{ id: "run-rollouts", tier: "write" },{ id: "run-statements", tier: "write" },{ id: "export", tier: "write" },diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex de159b8113..2b60c0b936 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2782,7 +2782,7 @@"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."+ "text": "administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history."},"heading": "{{mode}} allows","hide-details": "Hide details",@@ -2791,6 +2791,10 @@"refused": "Not allowed"},"row": {+ "approve": {+ "details": "Each decision is confirmed in the user's MCP client before it is made · Role requests are decided in the console · The approval rules and the project's self-approval setting apply, as in the console",+ "title": "Approve or reject issues"+ },"export": {"details": "Download results as a file. Data leaves Bytebase.","title": "Export query results"@@ -2800,7 +2804,7 @@"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 approve it.",+ "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. The project's approval policy decides whether a change needs approval.","title": "Propose changes"},"read-access": {@@ -2820,7 +2824,7 @@"title": "Read the change workflow"},"request-access": {- "details": "Ask for a time-boxed grant to run a specific statement, optionally with results unmasked or exported; the statement must be a read as far as the engine can check it · The grant starts only after a person approves it, and a request that would need no one's approval is refused · A grant applies only where the project allows access grants",+ "details": "Ask for a time-boxed grant to run a specific statement, optionally with results unmasked or exported; the statement must be a read as far as the engine can check it · The grant starts only after it is approved, and a request that would need no one's approval is refused · A grant applies only where the project allows access grants","title": "Request access grants"},"run-rollouts": {@@ -2839,7 +2843,7 @@},"summary": {"read-only": "Read schemas, data, the change workflow, members, roles and policies; a request carrying anything that cannot be shown to be a read is refused, and nothing is exported",- "read-write": "Read schemas, data, the change workflow, members, roles and policies; propose, request access, run, export and manage"+ "read-write": "Read schemas, data, the change workflow, members, roles and policies; propose, request access, approve, run, export and manage"},"tier": {"read": "read",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex c184b73d52..27a70cdb8f 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2782,7 +2782,7 @@"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."+ "text": "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",@@ -2791,6 +2791,10 @@"refused": "No permitido"},"row": {+ "approve": {+ "details": "Cada decisión se confirma en el cliente MCP del usuario antes de tomarse · Las solicitudes de rol se deciden en la consola · Se aplican las reglas de aprobación y la configuración de autoaprobación del proyecto, como en la consola",+ "title": "Aprobar o rechazar issues"+ },"export": {"details": "Descargar resultados como archivo. Los datos salen de Bytebase.","title": "Exportar resultados de consulta"@@ -2800,7 +2804,7 @@"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",+ "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. La política de aprobación del proyecto decide si un cambio necesita aprobación","title": "Proponer cambios"},"read-access": {@@ -2820,7 +2824,7 @@"title": "Leer el flujo de cambios"},"request-access": {- "details": "Pedir una concesión con límite de tiempo para ejecutar una sentencia concreta, opcionalmente con resultados sin enmascarar o exportados; la sentencia debe ser una lectura hasta donde el motor pueda comprobarlo · La concesión solo empieza después de que una persona la apruebe, y se rechaza una solicitud que no necesitaría la aprobación de nadie · Una concesión solo se aplica donde el proyecto permite concesiones de acceso",+ "details": "Pedir una concesión con límite de tiempo para ejecutar una sentencia concreta, opcionalmente con resultados sin enmascarar o exportados; la sentencia debe ser una lectura hasta donde el motor pueda comprobarlo · La concesión solo empieza después de ser aprobada, y se rechaza una solicitud que no necesitaría la aprobación de nadie · Una concesión solo se aplica donde el proyecto permite concesiones de acceso","title": "Solicitar concesiones de acceso"},"run-rollouts": {@@ -2839,7 +2843,7 @@},"summary": {"read-only": "Leer esquemas, datos, el flujo de cambios, miembros, roles y políticas; 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, el flujo de cambios, miembros, roles y políticas; proponer, solicitar acceso, ejecutar, exportar y gestionar"+ "read-write": "Leer esquemas, datos, el flujo de cambios, miembros, roles y políticas; proponer, solicitar acceso, aprobar, ejecutar, exportar y gestionar"},"tier": {"read": "lectura",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 93f5f580e2..e3c3744c1f 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2782,7 +2782,7 @@"disabled": "何も許可されません。MCP セッションは接続できません。","floor": {"label": "どのモードでも決してできないこと:",- "text": "Issue の承認、ワークスペースの管理、認証情報の取り扱い、Admin モードのセッションの開始、他人のクエリ履歴の閲覧。"+ "text": "ワークスペースの管理、認証情報の取り扱い、Admin モードのセッションの開始、他人のクエリ履歴の閲覧。"},"heading": "{{mode}} で許可されること","hide-details": "詳細を隠す",@@ -2791,6 +2791,10 @@"refused": "不許可"},"row": {+ "approve": {+ "details": "各判断は、実行される前にユーザーの MCP クライアントで確認されます · ロール申請はコンソールで承認・却下します · 承認ルールとプロジェクトの自己承認設定は、コンソールと同じように適用されます",+ "title": "Issue の承認・却下"+ },"export": {"details": "結果をファイルとしてダウンロードします。データが Bytebase の外に出ます。","title": "クエリ結果をエクスポートする"@@ -2800,7 +2804,7 @@"title": "データベースの運用設定を管理する"},"propose": {- "details": "シートの作成 · Plan と Issue の作成・編集 · プランチェックとレビューの実行 · リリースの作成・削除・復元 · リビジョンの作成・削除 · スキーマ差分の生成。エージェントが自分の変更を承認することはありません。人の承認が必要かどうかはプロジェクトの承認ポリシーが決めます",+ "details": "シートの作成 · Plan と Issue の作成・編集 · プランチェックとレビューの実行 · リリースの作成・削除・復元 · リビジョンの作成・削除 · スキーマ差分の生成。変更に承認が必要かどうかはプロジェクトの承認ポリシーが決めます","title": "変更を提案する"},"read-access": {@@ -2820,7 +2824,7 @@"title": "変更ワークフローの読み取り"},"request-access": {- "details": "特定のステートメントを実行するための期限付きアクセス付与をリクエストします。結果のマスク解除やエクスポートも含められます。エンジンが確認できる範囲で、ステートメントは読み取りでなければなりません · 付与は人が承認した後にのみ有効になり、誰の承認も必要としないリクエストは拒否されます · 付与は、プロジェクトがアクセス付与を許可している場合にのみ適用されます",+ "details": "特定のステートメントを実行するための期限付きアクセス付与をリクエストします。結果のマスク解除やエクスポートも含められます。エンジンが確認できる範囲で、ステートメントは読み取りでなければなりません · 付与は承認された後にのみ有効になり、誰の承認も必要としないリクエストは拒否されます · 付与は、プロジェクトがアクセス付与を許可している場合にのみ適用されます","title": "アクセス付与をリクエストする"},"run-rollouts": {@@ -2839,7 +2843,7 @@},"summary": {"read-only": "スキーマ・データ・変更ワークフロー・メンバー・ロール・ポリシーの読み取り。読み取りだと確認できないものを含むリクエストは拒否され、エクスポートもできません",- "read-write": "スキーマ・データ・変更ワークフロー・メンバー・ロール・ポリシーの読み取り。提案・アクセスのリクエスト・実行・エクスポート・管理"+ "read-write": "スキーマ・データ・変更ワークフロー・メンバー・ロール・ポリシーの読み取り。提案・アクセスのリクエスト・承認・実行・エクスポート・管理"},"tier": {"read": "読み取り",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 69c99bdf7d..e35cae6c73 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2782,7 +2782,7 @@"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."+ "text": "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",@@ -2791,6 +2791,10 @@"refused": "Không được phép"},"row": {+ "approve": {+ "details": "Mỗi quyết định được xác nhận trong ứng dụng MCP của người dùng trước khi được thực hiện · Yêu cầu vai trò được quyết định trên bảng điều khiển · Các quy tắc phê duyệt và thiết lập tự phê duyệt của dự án vẫn áp dụng, như trên bảng điều khiển",+ "title": "Phê duyệt hoặc từ chối Issue"+ },"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"@@ -2800,7 +2804,7 @@"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",+ "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 đồ. Chính sách phê duyệt của dự án quyết định liệu một thay đổi có cần phê duyệt hay không","title": "Đề xuất thay đổi"},"read-access": {@@ -2820,7 +2824,7 @@"title": "Đọc quy trình thay đổi"},"request-access": {- "details": "Xin cấp quyền truy cập có thời hạn để chạy một câu lệnh cụ thể, có thể kèm xem kết quả chưa che hoặc xuất kết quả; câu lệnh phải là lệnh đọc trong phạm vi engine kiểm tra được · Quyền chỉ bắt đầu sau khi một người phê duyệt, và yêu cầu không cần ai phê duyệt sẽ bị từ chối · Quyền chỉ áp dụng khi dự án cho phép cấp quyền truy cập",+ "details": "Xin cấp quyền truy cập có thời hạn để chạy một câu lệnh cụ thể, có thể kèm xem kết quả chưa che hoặc xuất kết quả; câu lệnh phải là lệnh đọc trong phạm vi engine kiểm tra được · Quyền chỉ bắt đầu sau khi được phê duyệt, và yêu cầu không cần ai phê duyệt sẽ bị từ chối · Quyền chỉ áp dụng khi dự án cho phép cấp quyền truy cập","title": "Yêu cầu cấp quyền truy cập"},"run-rollouts": {@@ -2839,7 +2843,7 @@},"summary": {"read-only": "Đọc lược đồ, dữ liệu, quy trình thay đổi, thành viên, vai trò và chính sách; 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, quy trình thay đổi, thành viên, vai trò và chính sách; đề xuất, yêu cầu truy cập, chạy, xuất và quản lý"+ "read-write": "Đọc lược đồ, dữ liệu, quy trình thay đổi, thành viên, vai trò và chính sách; đề xuất, yêu cầu truy cập, phê duyệt, chạy, xuất và quản lý"},"tier": {"read": "đọc",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 7de21b73f0..106840bb13 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2782,7 +2782,7 @@"disabled": "不允许任何操作;MCP 会话无法连接。","floor": {"label": "在任何模式下都不允许:",- "text": "审批工单、管理工作空间、处理凭据、开启 Admin 模式会话、查看他人的查询历史。"+ "text": "管理工作空间、处理凭据、开启 Admin 模式会话、查看他人的查询历史。"},"heading": "{{mode}} 允许","hide-details": "隐藏详情",@@ -2791,6 +2791,10 @@"refused": "不允许"},"row": {+ "approve": {+ "details": "每项决定都会先在用户的 MCP 客户端中确认,然后才会执行 · 角色申请需在控制台中批准或拒绝 · 审批规则和项目的自我审批设置照常适用,与控制台相同",+ "title": "批准或拒绝工单"+ },"export": {"details": "将结果下载为文件。数据会离开 Bytebase。","title": "导出查询结果"@@ -2800,7 +2804,7 @@"title": "管理数据库日常维护"},"propose": {- "details": "创建工作表 · 创建和编辑 Plan 与工单 · 执行计划检查和审核 · 创建、删除和恢复发布 · 创建和删除修订 · 生成模式差异。智能体绝不会审批自己的变更;是否需要人来审批由项目的审批策略决定",+ "details": "创建工作表 · 创建和编辑 Plan 与工单 · 执行计划检查和审核 · 创建、删除和恢复发布 · 创建和删除修订 · 生成模式差异。变更是否需要审批由项目的审批策略决定","title": "提议变更"},"read-access": {@@ -2820,7 +2824,7 @@"title": "读取变更流程"},"request-access": {- "details": "为特定语句申请限时访问授权,可选择查看未脱敏结果或导出结果;在引擎能检查的范围内,该语句必须是读取 · 只有在有人审批后授权才会生效;无需任何人审批的申请会被拒绝 · 授权仅在项目允许访问授权时适用",+ "details": "为特定语句申请限时访问授权,可选择查看未脱敏结果或导出结果;在引擎能检查的范围内,该语句必须是读取 · 只有在获得批准后授权才会生效;无需任何人审批的申请会被拒绝 · 授权仅在项目允许访问授权时适用","title": "申请访问授权"},"run-rollouts": {@@ -2839,7 +2843,7 @@},"summary": {"read-only": "读取模式、数据、变更流程、成员、角色和策略;只要请求中含有无法被确认为读取的内容就会被拒绝,也不能导出",- "read-write": "读取模式、数据、变更流程、成员、角色和策略;提议、申请访问、执行、导出和管理"+ "read-write": "读取模式、数据、变更流程、成员、角色和策略;提议、申请访问、批准、执行、导出和管理"},"tier": {"read": "读取",diff --git a/frontend/src/types/proto-es/v1/annotation_pb.d.ts b/frontend/src/types/proto-es/v1/annotation_pb.d.tsindex 3ead1e3ae2..5d862bde08 100644--- a/frontend/src/types/proto-es/v1/annotation_pb.d.ts+++ b/frontend/src/types/proto-es/v1/annotation_pb.d.ts@@ -249,11 +249,9 @@ export enum MCPDenialReason {REWRITES_SESSION_BOUNDARY = 7,/**- * Decides whether a change or an access request passes its human approval:- * recording the review decision, re-running the finding that sets it and can- * clear the issue outright, or activating an access grant without it. An- * agent composes a change or files a request; it does not decide that for its- * own work.+ * Can let a change or an access request pass its approval without an+ * approver deciding it: re-running the finding that sets the approval, which+ * can clear the issue outright, or activating an access grant directly.** @generated from enum value: DRIVES_THE_APPROVAL_DECISION = 8;*/diff --git a/frontend/src/types/proto-es/v1/issue_service_pb.js b/frontend/src/types/proto-es/v1/issue_service_pb.jsindex 2a66f96cbc..57c7f467a0 100644--- a/frontend/src/types/proto-es/v1/issue_service_pb.js+++ b/frontend/src/types/proto-es/v1/issue_service_pb.js@@ -19,7 +19,7 @@ import { file_v1_review_rule } from "./review_rule_pb";* Describes the file v1/issue_service.proto.*/export const file_v1_issue_service = /*@__PURE__*/- fileDesc("ChZ2MS9pc3N1ZV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJKCg9HZXRJc3N1ZVJlcXVlc3QSKAoEbmFtZRgBIAEoCUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSDQoFZm9yY2UYAiABKAgiagoSQ3JlYXRlSXNzdWVSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBImCgVpc3N1ZRgCIAEoCzISLmJ5dGViYXNlLnYxLklzc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5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_google_type_expr, file_v1_annotation, file_v1_common, file_v1_plan_service, file_v1_review_rule]);+ fileDesc("ChZ2MS9pc3N1ZV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJKCg9HZXRJc3N1ZVJlcXVlc3QSKAoEbmFtZRgBIAEoCUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSDQoFZm9yY2UYAiABKAgiagoSQ3JlYXRlSXNzdWVSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBImCgVpc3N1ZRgCIAEoCzISLmJ5dGViYXNlLnYxLklzc3VlQgPgQQIimQEKEUxpc3RJc3N1ZXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSDQoFcXVlcnkYBSABKAkSEAoIb3JkZXJfYnkYBiABKAkiUQoSTGlzdElzc3Vlc1Jlc3BvbnNlEiIKBmlzc3VlcxgBIAMoCzISLmJ5dGViYXNlLnYxLklzc3VlEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSKCAQoTU2VhcmNoSXNzdWVzUmVxdWVzdBITCgZwYXJlbnQYASABKAlCA+BBAhIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkS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jADqOowCILT5JMCMToBKiIsL3YxL3tuYW1lPXByb2plY3RzLyovaXNzdWVzLyp9OnJldHJ5QXBwcm92YWwSoQEKDEdldFJldmlld1J1bhIgLmJ5dGViYXNlLnYxLkdldFJldmlld1J1blJlcXVlc3QaFi5ieXRlYmFzZS52MS5SZXZpZXdSdW4iV9pBBG5hbWWK6jARYmIucmV2aWV3UnVucy5nZXSQ6jABoOowAYLT5JMCLRIrL3YxL3tuYW1lPXByb2plY3RzLyovaXNzdWVzLyovcmV2aWV3UnVucy8qfRKmAQoJUnVuUmV2aWV3Eh0uYnl0ZWJhc2UudjEuUnVuUmV2aWV3UmVxdWVzdBoWLmJ5dGViYXNlLnYxLlJldmlld1J1biJi2kEEbmFtZYrqMBFiYi5yZXZpZXdSdW5zLnJ1bpDqMAGY6jABoOowAoLT5JMCNDoBKiIvL3YxL3tuYW1lPXByb2plY3RzLyovaXNzdWVzLyovcmV2aWV3UnVucy8qfTpydW5CpwEKD2NvbS5ieXRlYmFzZS52MUIRSXNzdWVTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_google_type_expr, file_v1_annotation, file_v1_common, file_v1_plan_service, file_v1_review_rule]);/*** Describes the message bytebase.v1.GetIssueRequest.diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 3b0c360ccb..c3e17a5a3c 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -889,7 +889,7 @@ already keeps for the wording.| ENDS_MEMBERSHIP | 5 | Destroys the caller's own workspace membership and mints a plain workspace token on the way out. || MINTS_CREDENTIAL_FOR_OTHERS | 6 | Leaves someone holding a principal the caller is not — by issuing its credential, carrying an existing one out to a host the caller named, choosing what will later be trusted to mint one, or redirecting where one gets delivered. || REWRITES_SESSION_BOUNDARY | 7 | Rewrites the workspace configuration that governs the session making the call — the MCP switch itself, the sign-in and SSO settings, the mail relay that carries credential resets, and the AI endpoint the stored API key is sent to. A session that can widen its own ceiling is not bounded by it. |-| DRIVES_THE_APPROVAL_DECISION | 8 | Decides whether a change or an access request passes its human approval: recording the review decision, re-running the finding that sets it and can clear the issue outright, or activating an access grant without it. An agent composes a change or files a request; it does not decide that for its own work. |+| DRIVES_THE_APPROVAL_DECISION | 8 | Can let a change or an access request pass its approval without an approver deciding it: re-running the finding that sets the approval, which can clear the issue outright, or activating an access grant directly. || ADMINISTERS_THE_WORKSPACE | 9 | Administers the workspace rather than doing database work: identity, credentials, access control, governance policy, billing, workspace and instance configuration, project lifecycle, and the operator's own audit trail. || READS_OTHER_USERS_SQL | 10 | Returns SQL that other people wrote. The permission gating it reads as an ordinary list permission, so the exclusion is per method rather than per permission: these methods span the workspace or ignore the per-object sharing that keeps a saved query private. || OPENS_AN_ADMIN_CONNECTION | 11 | Opens an admin-credentialed connection to the customer's database and returns live session state from it — including other sessions' in-flight, unmasked SQL. It shares a plain read permission with sibling methods that only read Bytebase's own store. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 7f23148094..6bc0a31756 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -3447,11 +3447,9 @@ by it.</p></td><tr><td>DRIVES_THE_APPROVAL_DECISION</td><td>8</td>- <td><p>Decides whether a change or an access request passes its human approval:-recording the review decision, re-running the finding that sets it and can-clear the issue outright, or activating an access grant without it. An-agent composes a change or files a request; it does not decide that for its-own work.</p></td>+ <td><p>Can let a change or an access request pass its approval without an+approver deciding it: re-running the finding that sets the approval, which+can clear the issue outright, or activating an access grant directly.</p></td></tr><tr>diff --git a/proto/v1/v1/annotation.proto b/proto/v1/v1/annotation.protoindex 7f7de5b8b4..c7e70fd29b 100644--- a/proto/v1/v1/annotation.proto+++ b/proto/v1/v1/annotation.proto@@ -159,11 +159,9 @@ enum MCPDenialReason {// key is sent to. A session that can widen its own ceiling is not bounded// by it.REWRITES_SESSION_BOUNDARY = 7;- // Decides whether a change or an access request passes its human approval:- // recording the review decision, re-running the finding that sets it and can- // clear the issue outright, or activating an access grant without it. An- // agent composes a change or files a request; it does not decide that for its- // own work.+ // Can let a change or an access request pass its approval without an+ // approver deciding it: re-running the finding that sets the approval, which+ // can clear the issue outright, or activating an access grant directly.DRIVES_THE_APPROVAL_DECISION = 8;// 9-14: EXCLUDED. The method is out because this phase ships two modes anddiff --git a/proto/v1/v1/issue_service.proto b/proto/v1/v1/issue_service.protoindex 90ce663786..ee639f5743 100644--- a/proto/v1/v1/issue_service.proto+++ b/proto/v1/v1/issue_service.proto@@ -149,8 +149,9 @@ service IssueService {};option (bytebase.v1.auth_method) = CUSTOM;option (bytebase.v1.audit) = true;- option (bytebase.v1.mcp_method_class) = FORBIDDEN;- option (bytebase.v1.mcp_denial_reason) = DRIVES_THE_APPROVAL_DECISION;+ // An MCP session reaches it only through the decide_issue tool, after the+ // user confirms the decision in the MCP client. RejectIssue is the same.+ option (bytebase.v1.mcp_method_class) = WRITE;}// Rejects an issue. Access determined by approval flow configuration - caller must be a designated approver for the current approval step.@@ -162,8 +163,7 @@ service IssueService {};option (bytebase.v1.auth_method) = CUSTOM;option (bytebase.v1.audit) = true;- option (bytebase.v1.mcp_method_class) = FORBIDDEN;- option (bytebase.v1.mcp_denial_reason) = DRIVES_THE_APPROVAL_DECISION;+ option (bytebase.v1.mcp_method_class) = WRITE;}// Requests changes on an issue. Access determined by approval flow configuration - caller must be a designated approver for the current approval step.@@ -175,20 +175,12 @@ service IssueService {};option (bytebase.v1.auth_method) = CUSTOM;option (bytebase.v1.audit) = true;- // WRITE, not FORBIDDEN with its two siblings, because it is structurally- // the opposite of them. ApproveIssue and RejectIssue record the review- // decision — an approver role via canReview, the self-approval guard, an- // APPROVED or REJECTED approver appended. This action requires the issue to- // be ALREADY rejected, requires the actor to be the issue CREATOR, never- // calls canReview, and records no decision: it strips the REJECTED- // approvers and returns the issue to PENDING for a fresh human decision- // (component/review/workflow.go applyReviewAction, ActionRequest).- //- // It approves nothing, so refusing it protects nothing the other two do not- // already protect, and it costs the loop propose_database_change exists- // for: while a rejection stands Approve and Reject both hard-fail, so this- // is the ONLY exit from the rejected state. Forbidding it means an agent- // that fixes the SQL a human asked it to fix cannot resubmit.+ // WRITE with no confirmation step: unlike ApproveIssue and RejectIssue, it+ // records no decision. Only the issue's creator can call it, on a rejected+ // issue, and it returns the issue to PENDING for a fresh decision+ // (component/review/workflow.go applyReviewAction, ActionRequest). It is the+ // only way out of the rejected state, so an agent that fixed the SQL+ // resubmits through it.option (bytebase.v1.mcp_method_class) = WRITE;}diff --git a/proto/v1/v1/plan_service.proto b/proto/v1/v1/plan_service.protoindex 86a09e8db9..e651e11ad3 100644--- a/proto/v1/v1/plan_service.proto+++ b/proto/v1/v1/plan_service.proto@@ -50,9 +50,9 @@ service PlanService {option (bytebase.v1.auth_method) = IAM;option (bytebase.v1.audit) = true;// This is the step that produces the issueless plan — it creates a plan- // and links no issue. It stays WRITE and needs no rule of its own: the- // rule the gate PR owes belongs at execution, not here, since a plan that- // is never rolled out changes nothing. See RolloutService/CreateRollout.+ // and links no issue. It stays WRITE and needs no rule of its own: a plan+ // that is never rolled out changes nothing, so the rule sits at execution+ // (rejectMCPOriginatedIssuelessRollout; see RolloutService/CreateRollout).option (bytebase.v1.mcp_method_class) = WRITE;}diff --git a/proto/v1/v1/rollout_service.proto b/proto/v1/v1/rollout_service.protoindex b58b02aac7..7560407f57 100644--- a/proto/v1/v1/rollout_service.proto+++ b/proto/v1/v1/rollout_service.proto@@ -46,37 +46,17 @@ service RolloutService {option (bytebase.v1.auth_method) = CUSTOM;option (bytebase.v1.audit) = true;// WRITE, and it stays WRITE: executing an approved change is what a- // read-write session is for. Two ways a change reaches execution without a- // human approval ride this method, and they get OPPOSITE answers, because- // only one of them is fixable at the MCP layer. Both are stated here- // because the gate PR is the reader who needs them.+ // read-write session is for. Two ways a change reaches execution without+ // an approval ride this method, and they get OPPOSITE answers, because+ // only one of them is fixable at the MCP layer.//- // 1. DELIVERED by the gate PR (1b-2), as rejectMCPOriginatedIssuelessRollout- // in rollout_service.go, on CreateRollout and BatchRunTasks both.- // Both approval checks on this path are- // guarded on a LINKED ISSUE existing (rollout_service.go, and the- // locked re-check in component/review/rollout.go), so a plan created- // without one reaches task creation with no approval whatever- // require_issue_approval says. The rule to implement: on the MCP path,- // refuse CreateRollout and BatchRunTasks when the project sets- // require_issue_approval and the plan has no linked approved issue.- // It keys on the delegated grant, so the console and the GitOps agent- // are unaffected, and it bites on CreateRollout first per the ordering- // trap below. Not because the behavior is a defect — the shipped GitOps Service- // Agent role holds no issue permission at all, so issueless deployment- // is a supported product contract, and READ_WRITE preserves supported- // contracts. Because without the rule the four FORBIDDEN approval- // methods are decorative for the change lane: an agent that cannot- // clear the gate can skip it instead, which is the same end state the- // self-approval guard exists to prevent. Ordering trap: once an- // issueless rollout exists, approval finding refuses outright ("rollout- // already started"), so the rule has to bite before the rollout, not- // after. BOT-71 tracks whether the product should close this for every- // caller; if it does, this rule becomes redundant rather than wrong.+ // 1. A plan with no linked issue, in a project that requires issue+ // approval: refused to MCP sessions on this method and BatchRunTasks by+ // rejectMCPOriginatedIssuelessRollout (rollout_service.go), which+ // states why.//- // 2. The gate PR owes NOTHING here, and must not pretend otherwise. An- // approval binds the plan's specs and its approval_input_version, not- // the set of databases a group target resolves to. This method+ // 2. An approval binds the plan's specs and its approval_input_version,+ // not the set of databases a group target resolves to. This method// re-resolves the group live (rollout_service_task.go), and nothing in// UpdateDatabaseGroup, UpdateDatabase or background schema sync bumps// that version, so databases that join the group after approval execute@@ -142,10 +122,10 @@ service RolloutService {option (bytebase.v1.audit) = true;// WRITE, and the same two cases as CreateRollout reach it — this is the// method that actually starts execution. Its approval check carries the- // identical linked-issue guard, so 1b-2's rule covers this method too- // (rejectMCPOriginatedIssuelessRollout, rollout_service.go); and it runs- // whatever tasks the live group resolution produced, which no MCP rule can- // constrain. Both stated on CreateRollout.+ // identical linked-issue guard, so rejectMCPOriginatedIssuelessRollout+ // (rollout_service.go) refuses here too; and it runs whatever tasks the+ // live group resolution produced, which no MCP rule can constrain. Both+ // stated on CreateRollout.option (bytebase.v1.mcp_method_class) = WRITE;}