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)!: ask the user before query_database runs a possible write (#21709)
Vincent Huang1a4e96ea01ea
diff --git a/backend/api/auth/mcp_confirmation.go b/backend/api/auth/mcp_confirmation.goindex 7de1098b9b..11988d0602 100644--- a/backend/api/auth/mcp_confirmation.go+++ b/backend/api/auth/mcp_confirmation.go@@ -2,14 +2,16 @@ package authimport ("context"+ "crypto/sha256"+ "encoding/binary""time")// MCPConfirmedDecision is the user's decision, confirmed in their MCP client, to// make one write. The MCP gate serves the procedures that need one only to a// request whose context carries one naming that procedure and the resource the-// request changes. query_database attaches one for SQLService/Query without-// asking, until the form that asks lands (BYT-9292).+// request changes; SQLService/Query checks its own. query_database also+// attaches one, without asking, when the client cannot show the form.type MCPConfirmedDecision struct {// Procedure is the connect procedure confirmed, such as// /bytebase.v1.IssueService/ApproveIssue.@@ -21,6 +23,30 @@ type MCPConfirmedDecision struct {// user confirmed. The review workflow refuses the decision when it no longer// matches.IssueUpdateTime time.Time+ // Digest is, for a SQL request, MCPStatementDigest of the request the user+ // confirmed.+ Digest []byte+}++// MCPConfirmationReason and MCPConfirmationDomain name the ErrorInfo+// SQLService/Query returns for an MCP request that may write and that the user+// has not confirmed. query_database asks the user when it receives one.+const (+ MCPConfirmationReason = "CONFIRMATION_REQUIRED"+ MCPConfirmationDomain = "bytebase.com"+)++// MCPStatementDigest identifies the SQL request a user confirms: the statement+// exactly as sent, the database, the default schema and the CosmosDB container.+// Each field is length prefixed, so no two requests share a digest by moving+// text between fields.+func MCPStatementDigest(statement, database, schema, container string) []byte {+ h := sha256.New()+ for _, field := range []string{statement, database, schema, container} {+ _, _ = h.Write(binary.BigEndian.AppendUint64(nil, uint64(len(field))))+ _, _ = h.Write([]byte(field))+ }+ return h.Sum(nil)}// mcpConfirmedDecisionKey is unexported so that only code in this process candiff --git a/backend/api/auth/mcp_confirmation_test.go b/backend/api/auth/mcp_confirmation_test.gonew file mode 100644index 0000000000..b35a90ab3c--- /dev/null+++ b/backend/api/auth/mcp_confirmation_test.go@@ -0,0 +1,16 @@+package auth++import (+ "testing"++ "github.com/stretchr/testify/require"+)++func TestMCPStatementDigestKeepsTheFieldsApart(t *testing.T) {+ digest := MCPStatementDigest("DELETE FROM t", "instances/a/databases/b", "app", "")+ require.Equal(t, digest, MCPStatementDigest("DELETE FROM t", "instances/a/databases/b", "app", ""))+ require.NotEqual(t, digest, MCPStatementDigest("DELETE FROM t", "instances/a/databases/b", "", ""))+ require.NotEqual(t, digest, MCPStatementDigest("DELETE FROM t", "instances/a/databases/b", "app", "orders"))+ require.NotEqual(t, MCPStatementDigest("DELETE FROM tapp", "", "", ""), MCPStatementDigest("DELETE FROM t", "app", "", ""))+ require.NotEqual(t, MCPStatementDigest("DELETE FROM t", "", "app", ""), MCPStatementDigest("DELETE FROM t", "", "", "app"))+}diff --git a/backend/api/mcp/skills/query.md b/backend/api/mcp/skills/query.mdindex 182d655a99..ffa4aadbaa 100644--- a/backend/api/mcp/skills/query.md+++ b/backend/api/mcp/skills/query.md@@ -1,6 +1,6 @@---name: query-description: Use when running SQL queries, executing SELECT/INSERT/UPDATE/DELETE statements, or fetching data from databases+description: Use when running SQL queries or fetching data from databases---# Execute SQL@@ -61,6 +61,7 @@ Run SQL queries against databases managed by Bytebase.## Notes+- Run a statement that may write, such as INSERT, UPDATE, DELETE or DDL, with the `query_database` tool. `call_api` refuses it.- Query results may contain masked values due to data masking policies. Do not remove or modify masked values.- Full mask: `******`- Partial mask: `**rn**` (only "rn" visible)diff --git a/backend/api/mcp/tool_confirm.go b/backend/api/mcp/tool_confirm.goindex 282d66e355..9de92b1c38 100644--- a/backend/api/mcp/tool_confirm.go+++ b/backend/api/mcp/tool_confirm.go@@ -54,23 +54,28 @@ func canShowConfirmation(req *mcp.CallToolRequest) bool {// elicitDatabaseChoice. A client on the 2026-07-28 protocol answers and echoes// the state itself.func (s *Server) askToConfirm(ctx context.Context, w confirmableWrite, digest []byte, message, title, description string) *mcp.CallToolResult {+ return s.askWithForm(ctx, w, digest, message, map[string]any{+ "type": "object",+ "properties": map[string]any{+ confirmDecisionField: map[string]any{+ "type": "boolean",+ "title": title,+ "description": description,+ },+ },+ "required": []string{confirmDecisionField},+ })+}++// askWithForm is askToConfirm with a form the caller builds.+func (s *Server) askWithForm(ctx context.Context, w confirmableWrite, digest []byte, message string, schema map[string]any) *mcp.CallToolResult {return &mcp.CallToolResult{RequestState: s.signConfirmationState(ctx, w, digest, time.Now()),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": title,- "description": description,- },- },- "required": []string{confirmDecisionField},- },+ Mode: "form",+ Message: message,+ RequestedSchema: schema,},},}@@ -133,22 +138,32 @@ func (r *confirmationReply) staleReason(mismatch string) string {// confirmationOutcome reports whether the answer confirms the write, and if// not, why, in words the result can carry.func confirmationOutcome(response mcp.InputResponse) (bool, string) {+ content, accepted, why := acceptedForm(response)+ if !accepted {+ return false, why+ }+ if confirmed, ok := content[confirmDecisionField].(bool); ok && confirmed {+ return true, ""+ }+ return false, "the form was submitted without the confirmation checked"+}++// acceptedForm returns what an accepted form holds, or why the answer accepts+// nothing.+func acceptedForm(response mcp.InputResponse) (map[string]any, bool, string) {elicited, ok := response.(*mcp.ElicitResult)if !ok || elicited == nil {- return false, "the confirmation answer could not be read"+ return nil, 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"+ return elicited.Content, true, ""case "decline":- return false, "the user declined"+ return nil, false, "the user declined"case "cancel":- return false, "the user cancelled"+ return nil, false, "the user cancelled"default:- return false, fmt.Sprintf("the confirmation answer %q is not one Bytebase acts on", elicited.Action)+ return nil, false, fmt.Sprintf("the confirmation answer %q is not one Bytebase acts on", elicited.Action)}}diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.goindex 268fc1998b..eaeaf74a81 100644--- a/backend/api/mcp/tool_query.go+++ b/backend/api/mcp/tool_query.go@@ -85,6 +85,7 @@ query_database(database="employee", instance="prod-pg", statement="SELECT count(query_database(database="employee", instance="projects/hr/instances/prod-pg", statement="SELECT count(*) FROM orders")**Notes:**+- Show the user the statement each answer came from, so they can check it read what they asked about.- 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 request_access_grant; 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.`@@ -113,17 +114,55 @@ func (s *Server) handleQueryDatabase(ctx context.Context, req *mcp.CallToolRequelimit = maxQueryLimit}+ // An answer that runs nothing is reported before the database is resolved+ // again, which may have changed while the user was asked.+ answeredRun, answerState := false, ""+ if canShowConfirmation(req) {+ if response, state, answered := confirmationAnswer(req); answered {+ if result := unrunAnswer(response); result != nil {+ return result, nil, nil+ }+ answeredRun, answerState = true, state+ }+ }+// Resolve database.resolved, resolveResult := s.resolveTarget(ctx, req, input.Database, input.Instance, input.Project)if resolveResult != nil {+ if answeredRun && len(resolveResult.InputRequests) > 0 {+ return staleRun("the databases that match changed after the user was asked"), nil, nil+ }return resolveResult, nil, nil}+ // A statement Query cannot show is a read runs once the user chooses Run+ // now, or at once when the client cannot show the form.+ confirmation := runConfirmation{database: resolved.resourceName}+ digest := auth.MCPStatementDigest(input.Statement, resolved.resourceName, input.Schema, input.Container)+ var confirmed []byte+ if !canShowConfirmation(req) {+ confirmed = digest+ } else if reply, answered := s.signedReply(ctx, req, confirmation, digest); answered {+ if why := reply.staleReason("the request changed after the user was asked"); why != "" {+ return staleRun(why), nil, nil+ }+ confirmed = digest+ } else if answeredRun && answerState != "" {+ // The answer was signed for another database.+ return staleRun("the database that matches changed after the user was asked"), nil, nil+ }+// Execute query.queryCtx, queryCancel := context.WithTimeout(ctx, queryTimeout)defer queryCancel()- output, err := s.executeQuery(queryCtx, resolved, input, limit)+ output, err := s.executeQuery(queryCtx, resolved, input, limit, confirmed)+ var required *confirmationRequired+ // A confirmed call that Query still refuses reports the refusal: asking+ // again in the same call would send a second form.+ if errors.As(err, &required) && confirmed == nil {+ return s.askToRun(ctx, req, confirmation, digest, input.Statement, input.Container, required), nil, nil+ }if err != nil {var qe *queryErrorif errors.As(err, &qe) {@@ -222,8 +261,9 @@ type queryRow struct {Values []json.RawMessage `json:"values"`}-// executeQuery executes a SQL query against the resolved database.-func (s *Server) executeQuery(ctx context.Context, resolved *resolvedDatabase, input QueryInput, limit int) (*QueryOutput, error) {+// executeQuery executes a SQL query against the resolved database. confirmed is+// the digest the confirmation marker carries, or nil for an unconfirmed request.+func (s *Server) executeQuery(ctx context.Context, resolved *resolvedDatabase, input QueryInput, limit int, confirmed []byte) (*QueryOutput, error) {body := map[string]any{"name": resolved.resourceName,"dataSourceId": resolved.dataSourceID,@@ -235,12 +275,13 @@ func (s *Server) executeQuery(ctx context.Context, resolved *resolvedDatabase, iif input.Container != "" {body["container"] = input.Container}- // Query routes a statement that may write as a write only for a request this- // mark names.- ctx = auth.WithMCPConfirmedDecision(ctx, auth.MCPConfirmedDecision{- Procedure: v1connect.SQLServiceQueryProcedure,- Resource: resolved.resourceName,- })+ if confirmed != nil {+ ctx = auth.WithMCPConfirmedDecision(ctx, auth.MCPConfirmedDecision{+ Procedure: v1connect.SQLServiceQueryProcedure,+ Resource: resolved.resourceName,+ Digest: confirmed,+ })+ }resp, err := s.apiRequest(ctx, v1connect.SQLServiceQueryProcedure, body)if err != nil {// The call can end partway through a batch, as when queryTimeout passes.@@ -251,6 +292,9 @@ func (s *Server) executeQuery(ctx context.Context, resolved *resolvedDatabase, i}}if resp.Status >= 400 {+ if required := confirmationRequiredIn(resp.Body); required != nil {+ return nil, required+ }errMsg := parseError(resp.Body)if errMsg == "" {errMsg = fmt.Sprintf("HTTP %d", resp.Status)diff --git a/backend/api/mcp/tool_query_confirm.go b/backend/api/mcp/tool_query_confirm.gonew file mode 100644index 0000000000..4713e36046--- /dev/null+++ b/backend/api/mcp/tool_query_confirm.go@@ -0,0 +1,231 @@+package mcp++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"+ "unicode"+ "unicode/utf8"++ "connectrpc.com/connect"+ "github.com/modelcontextprotocol/go-sdk/mcp"+ "golang.org/x/text/width"+ "google.golang.org/genproto/googleapis/rpc/errdetails"+ "google.golang.org/protobuf/proto"++ "github.com/bytebase/bytebase/backend/api/auth"+ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"+)++// The choice field of the form that asks before a statement runs, and its+// values.+const (+ runChoiceField = "choice"+ runChoiceRun = "run"+ runChoiceChange = "change"+)++// Claude Code shows four lines of a form's message and cuts each line six+// columns short of the terminal width. A request goes in the message only when+// it fits under the header in lines of at most 70 columns.+const (+ messageLines = 4+ messageLineWidth = 70+)++// runConfirmation is a statement query_database asks the user to run.+type runConfirmation struct {+ database string+}++func (runConfirmation) confirmedProcedure() string { return v1connect.SQLServiceQueryProcedure }++func (c runConfirmation) confirmedResource() string { return c.database }++// confirmationRequired is Query's refusal of a statement that may write and that+// the user has not confirmed, with what the form shows.+type confirmationRequired struct {+ environment string+ schema string+}++func (*confirmationRequired) Error() string {+ return "Bytebase refused this statement's confirmation, so nothing ran; asking the user again will not help"+}++// confirmationRequiredIn returns the refusal body carries, or nil when body is+// another error.+func confirmationRequiredIn(body json.RawMessage) *confirmationRequired {+ var wire struct {+ Details []struct {+ Type string `json:"type"`+ Value string `json:"value"`+ } `json:"details"`+ }+ // A body that is not JSON carries no details.+ _ = json.Unmarshal(body, &wire)+ for _, detail := range wire.Details {+ if detail.Type != "google.rpc.ErrorInfo" {+ continue+ }+ value, err := connect.DecodeBinaryHeader(detail.Value)+ if err != nil {+ continue+ }+ var info errdetails.ErrorInfo+ if proto.Unmarshal(value, &info) != nil || info.GetDomain() != auth.MCPConfirmationDomain || info.GetReason() != auth.MCPConfirmationReason {+ continue+ }+ return &confirmationRequired{environment: info.GetMetadata()["environment"], schema: info.GetMetadata()["schema"]}+ }+ return nil+}++// askToRun returns the form that asks the user to run statement. A call that+// already asked which database to use gets a result that has the agent call+// again instead: an older client answers one form per call.+func (s *Server) askToRun(ctx context.Context, req *mcp.CallToolRequest, confirmation runConfirmation, digest []byte, statement, container string, required *confirmationRequired) *mcp.CallToolResult {+ project, instance, database, err := common.GetDatabaseResourceName(confirmation.database)+ if err != nil {+ return formatToolError(err)+ }+ if _, answered := elicitedDatabaseChoice(req); answered {+ instanceName := instance+ if project != nil {+ instanceName = common.FormatProjectInstance(*project, instance)+ }+ return textResult(fmt.Sprintf(+ "Not run: this statement may write, so the user confirms it in a form, and this call already asked which database to use. "++ "Call query_database again with database %q and instance %q to ask the user.", database, instanceName))+ }+ header := headerLines(required, database, instance, container)+ const runsAtOnce = "Run now runs it at once, with no issue or approval."+ request := strings.Split(strings.TrimSpace(statement), "\n")+ description := runsAtOnce+ if len(header)+len(request) > messageLines || !fitsMessageLines(request) {+ notes := []string{fmt.Sprintf("The request is under the choice (%d characters).", utf8.RuneCountInString(statement)), runsAtOnce}+ request = notes[:min(len(notes), messageLines-len(header))]+ description = statement+ if len(request) < len(notes) {+ description += "\n\n" + runsAtOnce+ }+ }+ message := strings.Join(append(header, request...), "\n")+ return s.askWithForm(ctx, confirmation, digest, message, map[string]any{+ "type": "object",+ "properties": map[string]any{+ runChoiceField: map[string]any{+ "type": "string",+ "title": "Run this request?",+ "description": description,+ "oneOf": []any{+ map[string]any{"const": runChoiceRun, "title": "Run now"},+ map[string]any{"const": runChoiceChange, "title": "Change it in chat"},+ },+ "default": runChoiceRun,+ },+ },+ "required": []string{runChoiceField},+ })+}++// headerLines names where the request runs, the environment before the+// database so a long database name cannot hide it. Names too long for two lines+// go on up to four, whose labels leave room for a 63-character ID or PostgreSQL+// database name in the 74 columns an 80-column terminal shows.+func headerLines(required *confirmationRequired, database, instance, container string) []string {+ where := fmt.Sprintf("Run on database %q,", database)+ if required.environment != "" {+ where = fmt.Sprintf("Run in environment %q on database %q,", required.environment, database)+ }+ scope := fmt.Sprintf("instance %q", instance)+ if required.schema != "" {+ scope += fmt.Sprintf(", schema %q", required.schema)+ }+ if container != "" {+ scope += fmt.Sprintf(", container %q", container)+ }+ if header := []string{where, scope + ":"}; fitsMessageLines(header) {+ return header+ }+ var lines []string+ if required.environment != "" {+ lines = append(lines, fmt.Sprintf("Run in %q:", required.environment))+ }+ lines = append(lines, fmt.Sprintf("Database %q", database), fmt.Sprintf("Instance %q", instance))+ // The schema and the container share a line, so the names never take more+ // than the four lines Claude Code shows.+ var scopes []string+ if required.schema != "" {+ scopes = append(scopes, fmt.Sprintf("schema %q", required.schema))+ }+ if container != "" {+ scopes = append(scopes, fmt.Sprintf("container %q", container))+ }+ if len(scopes) > 0 {+ lines = append(lines, capitalize(strings.Join(scopes, ", ")))+ }+ return lines+}++// fitsMessageLines reports whether every line is at most messageLineWidth+// columns wide.+func fitsMessageLines(lines []string) bool {+ for _, line := range lines {+ if lineColumns(line) > messageLineWidth {+ return false+ }+ }+ return true+}++// lineColumns counts the columns Claude Code gives line: two for a wide+// character, none for a combining mark.+func lineColumns(line string) int {+ columns := 0+ for _, r := range line {+ if unicode.Is(unicode.Mn, r) {+ continue+ }+ columns+++ if kind := width.LookupRune(r).Kind(); kind == width.EastAsianWide || kind == width.EastAsianFullwidth {+ columns+++ }+ }+ return columns+}++// unrunAnswer returns the result for an answer that runs nothing, or nil when+// the user chose Run now. It reads no target or signed state, so a request+// that changed while the user was asked cannot turn a decline into a form.+func unrunAnswer(response mcp.InputResponse) *mcp.CallToolResult {+ content, accepted, why := acceptedForm(response)+ if !accepted {+ return textResult(fmt.Sprintf("Not run: %s, so nothing changed. Do not retry unless the user asks.", why))+ }+ switch content[runChoiceField] {+ case runChoiceRun:+ return nil+ case runChoiceChange:+ return textResult("Not run: the user wants to change this request. Ask them what to change, then call query_database with the revised request.")+ default:+ return textResult("Not run: the answer chose neither option, so nothing changed.")+ }+}++// staleRun reports a Run now answer that no longer fits the request. It asks+// nothing: an older client answers one form per call.+func staleRun(why string) *mcp.CallToolResult {+ return formatToolError(&toolError{+ Code: "STALE_CONFIRMATION",+ Message: fmt.Sprintf("%s, so nothing ran", why),+ Suggestion: "call query_database again to ask the user about the request as it is now",+ })+}++// textResult carries text alone, which a client shows the model whole.+func textResult(text string) *mcp.CallToolResult {+ return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: text}}}+}diff --git a/backend/api/mcp/tool_query_confirm_test.go b/backend/api/mcp/tool_query_confirm_test.gonew file mode 100644index 0000000000..9f377be6dd--- /dev/null+++ b/backend/api/mcp/tool_query_confirm_test.go@@ -0,0 +1,524 @@+package mcp++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"+ "unicode/utf8"++ "connectrpc.com/connect"+ "github.com/labstack/echo/v5"+ "github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/pkg/errors"+ "github.com/stretchr/testify/require"+ "google.golang.org/genproto/googleapis/rpc/errdetails"++ "github.com/bytebase/bytebase/backend/api/auth"+ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/component/config"+)++// queryCall is one SQLService/Query request the confirming mock received.+type queryCall struct {+ Statement string+ Confirmed bool+}++// confirmingQueryMock serves the database list and a Query that refuses an+// INSERT, as SQLService/Query refuses a possible write, until the request+// carries the confirmation of that exact request.+type confirmingQueryMock struct {+ databases http.Handler+ environment string+ // refusesConfirmed has Query refuse an INSERT even when it is confirmed.+ refusesConfirmed bool+ mu sync.Mutex+ queries []queryCall+}++func newConfirmingQueryMock(databases []map[string]any) *confirmingQueryMock {+ return &confirmingQueryMock{databases: mockListDatabases(databases), environment: "prod"}+}++func (m *confirmingQueryMock) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ if !strings.HasSuffix(r.URL.Path, "SQLService/Query") {+ m.mu.Lock()+ databases := m.databases+ m.mu.Unlock()+ databases.ServeHTTP(w, r)+ return+ }+ var body struct {+ Name string `json:"name"`+ Statement string `json:"statement"`+ Schema string `json:"schema"`+ Container string `json:"container"`+ }+ _ = json.NewDecoder(r.Body).Decode(&body)+ marker, marked := auth.MCPConfirmedDecisionFromContext(r.Context())+ confirmed := marked && bytes.Equal(marker.Digest, auth.MCPStatementDigest(body.Statement, body.Name, body.Schema, body.Container))+ m.mu.Lock()+ m.queries = append(m.queries, queryCall{Statement: body.Statement, Confirmed: confirmed})+ m.mu.Unlock()+ if (!confirmed || m.refusesConfirmed) && strings.HasPrefix(body.Statement, "INSERT") {+ _ = connect.NewErrorWriter().Write(w, r, confirmationRequiredError(m.environment, body.Schema))+ return+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(makeQueryResponse([]string{"id"}, []string{"int4"}, [][]any{{"1"}}, "0.001s"))+}++// setDatabases changes the databases the list calls return.+func (m *confirmingQueryMock) setDatabases(databases []map[string]any) {+ m.mu.Lock()+ defer m.mu.Unlock()+ m.databases = mockListDatabases(databases)+}++func (m *confirmingQueryMock) calls() []queryCall {+ m.mu.Lock()+ defer m.mu.Unlock()+ return append([]queryCall(nil), m.queries...)+}++// confirmationRequiredError is SQLService/Query's refusal of an unconfirmed+// possible write.+func confirmationRequiredError(environment, schema string) error {+ err := connect.NewError(connect.CodeFailedPrecondition, errors.New("this statement may write"))+ if detail, detailErr := connect.NewErrorDetail(&errdetails.ErrorInfo{+ Reason: auth.MCPConfirmationReason,+ Domain: auth.MCPConfirmationDomain,+ Metadata: map[string]string{"environment": environment, "schema": schema},+ }); detailErr == nil {+ err.AddDetail(detail)+ }+ return err+}++func employeeDatabase() []map[string]any {+ return []map[string]any{+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr", "POSTGRES", "ds-1"),+ }+}++func newQueryConfirmServer(t *testing.T, mock *confirmingQueryMock) (*Server, string, string) {+ t.Helper()+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}+ s, err := newServerWithStore(newTestServerStore(), profile, revalidationSecret, mock)+ require.NoError(t, err)+ e := echo.New()+ s.RegisterRoutes(e)+ ts := httptest.NewServer(e)+ t.Cleanup(ts.Close)+ return s, ts.URL + mcpResourcePath, mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-write", time.Hour)+}++func runAnswer(choice any) *mcp.ElicitResult {+ return &mcp.ElicitResult{Action: "accept", Content: map[string]any{runChoiceField: choice}}+}++func queryParams(statement string) *mcp.CallToolParams {+ return &mcp.CallToolParams{Name: "query_database", Arguments: map[string]any{"database": "employee_db", "statement": statement}}+}++func callQuery(t *testing.T, session *mcp.ClientSession, params *mcp.CallToolParams) *mcp.CallToolResult {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ res, err := session.CallTool(ctx, params)+ require.NoError(t, err)+ return res+}++func TestQueryDatabaseAsksBeforeAWrite(t *testing.T) {+ for _, row := range []struct {+ name string+ databases []map[string]any+ environment string+ schema string+ container string+ header string+ }{+ {name: "the database's default schema", databases: employeeDatabase(), environment: "prod",+ header: `Run in environment "prod" on database "employee_db",` + "\n" + `instance "prod-pg":`},+ {name: "a named schema", databases: employeeDatabase(), environment: "prod", schema: "app",+ header: `Run in environment "prod" on database "employee_db",` + "\n" + `instance "prod-pg", schema "app":`},+ {name: "a project instance", databases: []map[string]any{+ makeDatabase("projects/hr/instances/prod-pg/databases/employee_db", "projects/hr/instances/prod-pg", "projects/hr", "POSTGRES", "ds-1"),+ }, environment: "prod", header: `Run in environment "prod" on database "employee_db",` + "\n" + `instance "prod-pg":`},+ {name: "no environment", databases: employeeDatabase(),+ header: `Run on database "employee_db",` + "\n" + `instance "prod-pg":`},+ {name: "a CosmosDB container", databases: employeeDatabase(), environment: "prod", container: "orders",+ header: `Run in environment "prod" on database "employee_db",` + "\n" + `instance "prod-pg", container "orders":`},+ } {+ t.Run(row.name, func(t *testing.T) {+ mock := newConfirmingQueryMock(row.databases)+ mock.environment = row.environment+ _, endpoint, token := newQueryConfirmServer(t, mock)+ user := &asker{answer: runAnswer(runChoiceRun)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ const insert = "INSERT INTO employee VALUES (1)"+ arguments := map[string]any{"database": "employee_db", "statement": insert}+ if row.schema != "" {+ arguments["schema"] = row.schema+ }+ if row.container != "" {+ arguments["container"] = row.container+ }+ res := callQuery(t, session, &mcp.CallToolParams{Name: "query_database", Arguments: arguments})+ require.False(t, res.IsError, resultText(t, res))+ require.EqualValues(t, 1, user.asked.Load())+ asked := user.lastParams(t)+ require.Equal(t, row.header+"\n"+insert, asked.Message)+ schema, err := json.Marshal(asked.RequestedSchema)+ require.NoError(t, err)+ require.Contains(t, string(schema), `"default":"run"`)+ require.Contains(t, string(schema), `"oneOf":[{"const":"run","title":"Run now"},{"const":"change","title":"Change it in chat"}]`)+ require.Contains(t, string(schema), `"description":"Run now runs it at once, with no issue or approval."`)+ require.Equal(t, []queryCall{{Statement: insert}, {Statement: insert, Confirmed: true}}, mock.calls())+ })+ }+}++func TestQueryDatabaseRunsNothingUnlessTheUserRuns(t *testing.T) {+ for _, row := range []struct {+ name string+ answer *mcp.ElicitResult+ text string+ }{+ {name: "change it in chat", answer: runAnswer(runChoiceChange),+ text: "Not run: the user wants to change this request. Ask them what to change, then call query_database with the revised request."},+ {name: "decline", answer: &mcp.ElicitResult{Action: "decline"},+ text: "Not run: the user declined, so nothing changed. Do not retry unless the user asks."},+ {name: "cancel", answer: &mcp.ElicitResult{Action: "cancel"},+ text: "Not run: the user cancelled, so nothing changed. Do not retry unless the user asks."},+ } {+ t.Run(row.name, func(t *testing.T) {+ mock := newConfirmingQueryMock(employeeDatabase())+ _, endpoint, token := newQueryConfirmServer(t, mock)+ user := &asker{answer: row.answer}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res := callQuery(t, session, queryParams("INSERT INTO employee VALUES (1)"))+ require.False(t, res.IsError)+ require.Equal(t, row.text, resultText(t, res))+ require.Nil(t, res.StructuredContent, "a client shows text alone to the model whole")+ require.Equal(t, []queryCall{{Statement: "INSERT INTO employee VALUES (1)"}}, mock.calls())+ })+ }+}++func TestQueryDatabaseRunsAtOnceWhenTheClientCannotAsk(t *testing.T) {+ mock := newConfirmingQueryMock(employeeDatabase())+ _, endpoint, token := newQueryConfirmServer(t, mock)+ session := connectLegacy(t, endpoint, token, nil)++ res := callQuery(t, session, queryParams("INSERT INTO employee VALUES (1)"))+ require.False(t, res.IsError, resultText(t, res))+ require.Equal(t, []queryCall{{Statement: "INSERT INTO employee VALUES (1)", Confirmed: true}}, mock.calls())+}++func TestQueryDatabaseDoesNotAskAgainAfterARefusedConfirmation(t *testing.T) {+ mock := newConfirmingQueryMock(employeeDatabase())+ mock.refusesConfirmed = true+ _, endpoint, token := newQueryConfirmServer(t, mock)+ user := &asker{answer: runAnswer(runChoiceRun)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res := callQuery(t, session, queryParams("INSERT INTO employee VALUES (1)"))+ require.True(t, res.IsError)+ require.Equal(t, "Bytebase refused this statement's confirmation, so nothing ran; asking the user again will not help", resultText(t, res))+ require.EqualValues(t, 1, user.asked.Load())+}++func TestQueryDatabaseReadsWithoutAsking(t *testing.T) {+ mock := newConfirmingQueryMock(employeeDatabase())+ _, endpoint, token := newQueryConfirmServer(t, mock)+ user := &asker{answer: runAnswer(runChoiceRun)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res := callQuery(t, session, queryParams("SELECT id FROM employee"))+ require.False(t, res.IsError, resultText(t, res))+ require.Zero(t, user.asked.Load())+ require.Equal(t, []queryCall{{Statement: "SELECT id FROM employee"}}, mock.calls())+}++func TestQueryDatabaseFormFitsClaudeCode(t *testing.T) {+ const header = `Run in environment "prod" on database "employee_db",` + "\n" + `instance "prod-pg":`+ const insert = "INSERT INTO employee VALUES (1, '"+ for _, row := range []struct {+ name string+ statement string+ inMessage bool+ }{+ {name: "a line at the width", statement: insert + strings.Repeat("a", 35) + "')", inMessage: true},+ {name: "a line past the width", statement: insert + strings.Repeat("a", 36) + "')"},+ {name: "two lines at the width", statement: insert + strings.Repeat("a", 35) + "')\n" + insert + "b')", inMessage: true},+ {name: "three lines", statement: "INSERT INTO employee\nVALUES\n(1)"},+ {name: "wide characters past the width", statement: insert + strings.Repeat("名", 18) + "')"},+ {name: "four lines", statement: "INSERT INTO employee (id, name)\nVALUES\n (1, 'Alice'),\n (2, 'Bob')"},+ } {+ t.Run(row.name, func(t *testing.T) {+ mock := newConfirmingQueryMock(employeeDatabase())+ _, endpoint, token := newQueryConfirmServer(t, mock)+ user := &asker{answer: runAnswer(runChoiceChange)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ callQuery(t, session, queryParams(row.statement))+ asked := user.lastParams(t)+ schema, err := json.Marshal(asked.RequestedSchema)+ require.NoError(t, err)+ if row.inMessage {+ require.Equal(t, header+"\n"+row.statement, asked.Message)+ } else {+ require.Equal(t, header+fmt.Sprintf("\nThe request is under the choice (%d characters).", utf8.RuneCountInString(row.statement))++ "\nRun now runs it at once, with no issue or approval.", asked.Message)+ description, err := json.Marshal(row.statement)+ require.NoError(t, err)+ require.Contains(t, string(schema), `"description":`+string(description))+ }+ for _, line := range claudeCodeView(asked.Message, 80) {+ require.NotContains(t, line, "…", "an 80-column terminal cuts a line of the message")+ }+ })+ }+}++func TestQueryDatabaseShowsLongNamesWhole(t *testing.T) {+ // The longest PostgreSQL database name, and the longest resource ID.+ longName := "payroll_" + strings.Repeat("x", 55)+ longEnvironment := "prod-" + strings.Repeat("x", 58)+ const runsAtOnce = "Run now runs it at once, with no issue or approval."+ for _, row := range []struct {+ name string+ database string+ environment string+ schema string+ container string+ statement string+ message []string+ description string+ }{+ {name: "one line left for the request", database: longName, environment: "prod", statement: "INSERT INTO employee VALUES (1)",+ message: []string{`Run in "prod":`, fmt.Sprintf("Database %q", longName), `Instance "prod-pg"`, "INSERT INTO employee VALUES (1)"},+ description: runsAtOnce},+ {name: "a request longer than the line left", database: longName, environment: "prod", statement: "INSERT INTO employee\nVALUES (1)",+ message: []string{`Run in "prod":`, fmt.Sprintf("Database %q", longName), `Instance "prod-pg"`, "The request is under the choice (31 characters)."},+ description: "INSERT INTO employee\nVALUES (1)\n\n" + runsAtOnce},+ {name: "no line left", database: longName, environment: "prod", schema: "app", statement: "INSERT INTO employee VALUES (1)",+ message: []string{`Run in "prod":`, fmt.Sprintf("Database %q", longName), `Instance "prod-pg"`, `Schema "app"`},+ description: "INSERT INTO employee VALUES (1)\n\n" + runsAtOnce},+ {name: "the longest environment ID", database: "employee_db", environment: longEnvironment, statement: "INSERT INTO employee VALUES (1)",+ message: []string{fmt.Sprintf("Run in %q:", longEnvironment), `Database "employee_db"`, `Instance "prod-pg"`, "INSERT INTO employee VALUES (1)"},+ description: runsAtOnce},+ {name: "no environment", database: longName, statement: "INSERT INTO employee VALUES (1)",+ message: []string{fmt.Sprintf("Database %q", longName), `Instance "prod-pg"`, "INSERT INTO employee VALUES (1)"},+ description: runsAtOnce},+ {name: "a schema and a container", database: longName, environment: "prod", schema: "app", container: "orders", statement: "INSERT INTO employee VALUES (1)",+ message: []string{`Run in "prod":`, fmt.Sprintf("Database %q", longName), `Instance "prod-pg"`, `Schema "app", container "orders"`},+ description: "INSERT INTO employee VALUES (1)\n\n" + runsAtOnce},+ } {+ t.Run(row.name, func(t *testing.T) {+ mock := newConfirmingQueryMock([]map[string]any{+ makeDatabase("instances/prod-pg/databases/"+row.database, "instances/prod-pg", "projects/hr", "POSTGRES", "ds-1"),+ })+ mock.environment = row.environment+ _, endpoint, token := newQueryConfirmServer(t, mock)+ user := &asker{answer: runAnswer(runChoiceChange)}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ arguments := map[string]any{"database": row.database, "statement": row.statement}+ if row.schema != "" {+ arguments["schema"] = row.schema+ }+ if row.container != "" {+ arguments["container"] = row.container+ }+ callQuery(t, session, &mcp.CallToolParams{Name: "query_database", Arguments: arguments})+ asked := user.lastParams(t)+ require.Equal(t, strings.Join(row.message, "\n"), asked.Message)+ schema, err := json.Marshal(asked.RequestedSchema)+ require.NoError(t, err)+ description, err := json.Marshal(row.description)+ require.NoError(t, err)+ require.Contains(t, string(schema), `"description":`+string(description))+ for _, line := range claudeCodeView(asked.Message, 80) {+ require.NotContains(t, line, "…", "an 80-column terminal cuts a line of the message")+ }+ })+ }+}++func TestQueryDatabaseAsksOnceACall(t *testing.T) {+ const projectDatabase = "projects/hr/instances/prod-pg/databases/employee_db"+ for _, row := range []struct {+ name string+ databases []map[string]any+ label string+ instance string+ }{+ {name: "a workspace instance", databases: ambiguousDatabases(), label: prodLabel, instance: "prod-pg"},+ {name: "a project instance", databases: []map[string]any{+ makeDatabase(projectDatabase, "projects/hr/instances/prod-pg", "projects/hr", "POSTGRES", "ds-1"),+ makeDatabase("instances/staging-pg/databases/employee_db", "instances/staging-pg", "projects/hr", "POSTGRES", "ds-2"),+ }, label: projectDatabase + " (prod-pg, POSTGRES)", instance: "projects/hr/instances/prod-pg"},+ } {+ t.Run(row.name, func(t *testing.T) {+ mock := newConfirmingQueryMock(row.databases)+ _, endpoint, token := newQueryConfirmServer(t, mock)+ user := &asker{answer: &mcp.ElicitResult{Action: "accept", Content: map[string]any{databaseChoiceField: row.label}}}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ const insert = "INSERT INTO employee VALUES (1)"+ res := callQuery(t, session, queryParams(insert))+ require.False(t, res.IsError)+ require.Equal(t, "Not run: this statement may write, so the user confirms it in a form, and this call already asked which database to use. "++ fmt.Sprintf("Call query_database again with database \"employee_db\" and instance %q to ask the user.", row.instance), resultText(t, res))+ require.EqualValues(t, 1, user.asked.Load())+ require.Equal(t, []queryCall{{Statement: insert}}, mock.calls())++ user.answer = runAnswer(runChoiceChange)+ again := callQuery(t, session, &mcp.CallToolParams{Name: "query_database", Arguments: map[string]any{+ "database": "employee_db", "instance": row.instance, "statement": insert,+ }})+ require.Contains(t, resultText(t, again), "the user wants to change this request")+ require.EqualValues(t, 2, user.asked.Load())+ require.True(t, strings.HasPrefix(user.lastParams(t).Message, `Run in environment "prod" on database "employee_db",`),+ "the call the text names asks to run, not which database: %q", user.lastParams(t).Message)+ })+ }+}++func TestQueryDatabaseReportsATargetThatChangedWhileAsked(t *testing.T) {+ another := ambiguousDatabases()+ moved := []map[string]any{+ makeDatabase("instances/other-pg/databases/employee_db", "instances/other-pg", "projects/hr", "POSTGRES", "ds-3"),+ }+ for _, row := range []struct {+ name string+ databases []map[string]any+ answer *mcp.ElicitResult+ text string+ }{+ {name: "another match, Run now", databases: another, answer: runAnswer(runChoiceRun), text: "STALE_CONFIRMATION"},+ {name: "another match, cancel", databases: another, answer: &mcp.ElicitResult{Action: "cancel"}, text: "Not run: the user cancelled"},+ {name: "a different database, Run now", databases: moved, answer: runAnswer(runChoiceRun), text: "STALE_CONFIRMATION"},+ {name: "a different database, cancel", databases: moved, answer: &mcp.ElicitResult{Action: "cancel"}, text: "Not run: the user cancelled"},+ } {+ t.Run(row.name, func(t *testing.T) {+ mock := newConfirmingQueryMock(employeeDatabase())+ _, endpoint, token := newQueryConfirmServer(t, mock)+ user := &asker{answer: row.answer, whileAsked: func() { mock.setDatabases(row.databases) }}+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{ElicitationHandler: user.handle})++ res := callQuery(t, session, queryParams("INSERT INTO employee VALUES (1)"))+ require.NotEmpty(t, res.Content, "an older client answers one form per call, so a second form leaves the result empty")+ require.Contains(t, resultText(t, res), row.text)+ require.EqualValues(t, 1, user.asked.Load())+ for _, query := range mock.calls() {+ require.False(t, query.Confirmed)+ }+ })+ }+}++func TestQueryDatabaseConfirmationUnderMRTRClient(t *testing.T) {+ mock := newConfirmingQueryMock(employeeDatabase())+ s, _, token := newQueryConfirmServer(t, mock)+ session := connectMRTR(t, mrtrEndpoint(t, s), token)+ call := func(statement string, responses mcp.InputResponseMap, state string) *mcp.CallToolResult {+ params := queryParams(statement)+ params.InputResponses = responses+ params.RequestState = state+ return callQuery(t, session, params)+ }+ const insert = "INSERT INTO employee VALUES (1)"+ run := mcp.InputResponseMap{confirmDecisionRequestID: runAnswer(runChoiceRun)}++ first := call(insert, nil, "")+ require.True(t, first.NeedsInput())+ require.NotEmpty(t, first.RequestState)++ unsigned := call(insert, run, "")+ require.True(t, unsigned.NeedsInput(), "an answer without the request state must be asked again")++ changed := call("INSERT INTO employee VALUES (2)", run, first.RequestState)+ require.True(t, changed.IsError)+ require.Contains(t, resultText(t, changed), "STALE_CONFIRMATION")++ moved := &mcp.CallToolParams{Name: "query_database", Arguments: map[string]any{"database": "employee_db", "statement": insert, "container": "orders"}}+ moved.InputResponses = run+ moved.RequestState = first.RequestState+ require.Contains(t, resultText(t, callQuery(t, session, moved)), "STALE_CONFIRMATION", "a confirmation is for one container")++ unknown := call(insert, mcp.InputResponseMap{confirmDecisionRequestID: runAnswer("skip")}, first.RequestState)+ require.Equal(t, "Not run: the answer chose neither option, so nothing changed.", resultText(t, unknown))++ ran := call(insert, run, first.RequestState)+ require.False(t, ran.IsError, resultText(t, ran))+ require.Equal(t, []queryCall{+ {Statement: insert},+ {Statement: insert},+ {Statement: insert, Confirmed: true},+ }, mock.calls(), "only the answer signed for this request runs it")+}++func TestQueryDatabaseReportsAnAnswerThatRunsNothingBeforeAStaleOne(t *testing.T) {+ mock := newConfirmingQueryMock(employeeDatabase())+ s, _, token := newQueryConfirmServer(t, mock)+ session := connectMRTR(t, mrtrEndpoint(t, s), token)+ const insert = "INSERT INTO employee VALUES (1)"+ const database = "instances/prod-pg/databases/employee_db"+ alice := withOAuth2ClientID(withUserEmail(withWorkspaceID(context.Background(), "ws-test"), "[email protected]"), "client-A")+ old := s.signConfirmationState(alice, runConfirmation{database: database}, auth.MCPStatementDigest(insert, database, "", ""), time.Now().Add(-11*time.Minute))+ call := func(answer *mcp.ElicitResult) *mcp.CallToolResult {+ params := queryParams(insert)+ params.InputResponses = mcp.InputResponseMap{confirmDecisionRequestID: answer}+ params.RequestState = old+ return callQuery(t, session, params)+ }++ declined := call(&mcp.ElicitResult{Action: "decline"})+ require.False(t, declined.IsError, resultText(t, declined))+ require.Contains(t, resultText(t, declined), "Not run: the user declined")+ changed := call(runAnswer(runChoiceChange))+ require.False(t, changed.IsError, resultText(t, changed))+ require.Contains(t, resultText(t, changed), "Not run: the user wants to change this request")+ ran := call(runAnswer(runChoiceRun))+ require.True(t, ran.IsError)+ require.Contains(t, resultText(t, ran), "STALE_CONFIRMATION")+ require.Contains(t, resultText(t, ran), "the user was asked more than 10 minutes ago")+ require.Empty(t, mock.calls())+}++func TestConfirmationRequiredIn(t *testing.T) {+ body := func(err error) json.RawMessage {+ req := httptest.NewRequest(http.MethodPost, "/bytebase.v1.SQLService/Query", nil)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Connect-Protocol-Version", "1")+ recorder := httptest.NewRecorder()+ require.NoError(t, connect.NewErrorWriter().Write(recorder, req, err))+ return recorder.Body.Bytes()+ }+ require.Equal(t, &confirmationRequired{environment: "prod", schema: "app"}, confirmationRequiredIn(body(confirmationRequiredError("prod", "app"))))+ require.Nil(t, confirmationRequiredIn(body(connect.NewError(connect.CodeFailedPrecondition, errors.New("another refusal")))))++ for _, info := range []*errdetails.ErrorInfo{+ {Reason: "OTHER", Domain: auth.MCPConfirmationDomain},+ {Reason: auth.MCPConfirmationReason, Domain: "example.com"},+ } {+ other := connect.NewError(connect.CodeFailedPrecondition, errors.New("another refusal"))+ detail, err := connect.NewErrorDetail(info)+ require.NoError(t, err)+ other.AddDetail(detail)+ require.Nil(t, confirmationRequiredIn(body(other)), "%s from %s", info.GetReason(), info.GetDomain())+ }+}diff --git a/backend/api/mcp/tool_query_test.go b/backend/api/mcp/tool_query_test.goindex 8f2c97f086..d9f22d57ba 100644--- a/backend/api/mcp/tool_query_test.go+++ b/backend/api/mcp/tool_query_test.go@@ -844,7 +844,7 @@ func TestQueryDatabase_Timeout(t *testing.T) {resourceName: "instances/prod-pg/databases/employee_db",dataSourceID: "ds-admin-1",}- _, err := s.executeQuery(ctx, resolved, QueryInput{Statement: "SELECT 1"}, 100)+ _, err := s.executeQuery(ctx, resolved, QueryInput{Statement: "SELECT 1"}, 100, nil)var te *toolErrorrequire.ErrorAs(t, err, &te)require.Equal(t, "QUERY_ERROR", te.Code)diff --git a/backend/api/v1/mcp_sql_write.go b/backend/api/v1/mcp_sql_write.goindex 391da1b7e6..7cd286f815 100644--- a/backend/api/v1/mcp_sql_write.go+++ b/backend/api/v1/mcp_sql_write.go@@ -1,12 +1,16 @@package v1import (+ "bytes""context"+ "connectrpc.com/connect""github.com/pkg/errors"+ "google.golang.org/genproto/googleapis/rpc/errdetails""github.com/bytebase/bytebase/backend/api/auth"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")@@ -23,17 +27,38 @@ func mcpStatementIsRead(ctx context.Context, engine storepb.Engine, statement streturn nonReadReason(engine, statement) == ""}-// queryDatabaseRequest reports whether query_database sent this request to-// database. call_api passes its context on unchanged, so it cannot mark one.-func queryDatabaseRequest(ctx context.Context, database string) bool {+// mcpWriteConfirmed reports whether query_database confirmed this exact request.+// call_api passes its context on unchanged, so it cannot.+func mcpWriteConfirmed(ctx context.Context, request *v1pb.QueryRequest) bool {marker, ok := auth.MCPConfirmedDecisionFromContext(ctx)- return ok && marker.Procedure == v1connect.SQLServiceQueryProcedure && marker.Resource == database+ return ok && marker.Procedure == v1connect.SQLServiceQueryProcedure &&+ bytes.Equal(marker.Digest, auth.MCPStatementDigest(request.Statement, request.Name, request.GetSchema(), request.GetContainer()))}-// mcpWriteDataSourceID routes a query_database request that may write as the SQL-// Editor routes a write that names no data source, since picked is the tool's own-// choice: the first read-only data source, or ADMIN when there is none. It skips-// requiresAdminDataSource, which reads every Databricks statement as a read.+// mcpConfirmationRequired refuses an MCP request that may write and that the+// user has not confirmed. Its ErrorInfo carries what the form shows.+func mcpConfirmationRequired(database *store.DatabaseMessage, schema string) error {+ err := connect.NewError(connect.CodeFailedPrecondition, errors.New(+ "this statement may write, and call_api cannot confirm it: run it with the query_database tool"))+ environment := ""+ if database.EffectiveEnvironmentID != nil {+ environment = *database.EffectiveEnvironmentID+ }+ if detail, detailErr := connect.NewErrorDetail(&errdetails.ErrorInfo{+ Reason: auth.MCPConfirmationReason,+ Domain: auth.MCPConfirmationDomain,+ Metadata: map[string]string{"environment": environment, "schema": schema},+ }); detailErr == nil {+ err.AddDetail(detail)+ }+ return err+}++// mcpWriteDataSourceID routes an MCP request that may write as the SQL Editor+// routes a write that names no data source. Only query_database's requests run,+// and the data source one names is the tool's own choice: the first read-only+// data source, or ADMIN when there is none. It skips requiresAdminDataSource,+// which reads every Databricks statement as a read.func mcpWriteDataSourceID(instance *store.InstanceMessage, picked string, allowAdminDataSource bool) (string, error) {id, err := routeDataSource(instance, allowAdminDataSource, func() bool { return true })if errors.Is(err, errMultipleReadOnlyDataSources) && picked != "" {diff --git a/backend/api/v1/mcp_sql_write_test.go b/backend/api/v1/mcp_sql_write_test.goindex 72557a93c9..ff41dc41d9 100644--- a/backend/api/v1/mcp_sql_write_test.go+++ b/backend/api/v1/mcp_sql_write_test.go@@ -6,9 +6,11 @@ import ("connectrpc.com/connect""github.com/stretchr/testify/require"+ "google.golang.org/genproto/googleapis/rpc/errdetails""github.com/bytebase/bytebase/backend/api/auth"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")@@ -37,23 +39,61 @@ func TestMCPStatementIsRead(t *testing.T) {}}-func TestQueryDatabaseRequest(t *testing.T) {+func TestMCPWriteConfirmed(t *testing.T) {const database = "instances/prod/databases/hr"- mark := func(procedure, resource string) context.Context {- return auth.WithMCPConfirmedDecision(context.Background(), auth.MCPConfirmedDecision{Procedure: procedure, Resource: resource})+ request := &v1pb.QueryRequest{Name: database, Statement: "DELETE FROM employee", Schema: new("app")}+ digest := auth.MCPStatementDigest("DELETE FROM employee", database, "app", "")+ mark := func(procedure, resource string, digest []byte) context.Context {+ return auth.WithMCPConfirmedDecision(context.Background(), auth.MCPConfirmedDecision{Procedure: procedure, Resource: resource, Digest: digest})}for _, row := range []struct {- name string- ctx context.Context- marked bool+ name string+ ctx context.Context+ confirmed bool}{{name: "no mark", ctx: context.Background()},- {name: "query_database's mark", ctx: mark(v1connect.SQLServiceQueryProcedure, database), marked: true},- {name: "a mark for another database", ctx: mark(v1connect.SQLServiceQueryProcedure, "instances/prod/databases/payroll")},- {name: "a mark for another procedure", ctx: mark(v1connect.IssueServiceApproveIssueProcedure, database)},+ {name: "the confirmed request", ctx: mark(v1connect.SQLServiceQueryProcedure, database, digest), confirmed: true},+ {name: "a mark with no digest", ctx: mark(v1connect.SQLServiceQueryProcedure, database, nil)},+ {name: "another statement", ctx: mark(v1connect.SQLServiceQueryProcedure, database, auth.MCPStatementDigest("DELETE FROM salary", database, "app", ""))},+ {name: "another schema", ctx: mark(v1connect.SQLServiceQueryProcedure, database, auth.MCPStatementDigest("DELETE FROM employee", database, "", ""))},+ {name: "another container", ctx: mark(v1connect.SQLServiceQueryProcedure, database, auth.MCPStatementDigest("DELETE FROM employee", database, "app", "orders"))},+ {name: "another database", ctx: mark(v1connect.SQLServiceQueryProcedure, "instances/prod/databases/payroll",+ auth.MCPStatementDigest("DELETE FROM employee", "instances/prod/databases/payroll", "app", ""))},+ {name: "another procedure", ctx: mark(v1connect.IssueServiceApproveIssueProcedure, database, digest)},+ } {+ t.Run(row.name, func(t *testing.T) {+ require.Equal(t, row.confirmed, mcpWriteConfirmed(row.ctx, request))+ })+ }+ t.Run("a request for a container the mark does not name", func(t *testing.T) {+ inContainer := &v1pb.QueryRequest{Name: database, Statement: "DELETE FROM employee", Schema: new("app"), Container: new("orders")}+ require.False(t, mcpWriteConfirmed(mark(v1connect.SQLServiceQueryProcedure, database, digest), inContainer))+ })+}++func TestMCPConfirmationRequired(t *testing.T) {+ for _, row := range []struct {+ name string+ database *store.DatabaseMessage+ metadata map[string]string+ }{+ {name: "an environment", database: &store.DatabaseMessage{EffectiveEnvironmentID: new("prod")}, metadata: map[string]string{"environment": "prod", "schema": "app"}},+ {name: "no environment", database: &store.DatabaseMessage{}, metadata: map[string]string{"environment": "", "schema": "app"}},} {t.Run(row.name, func(t *testing.T) {- require.Equal(t, row.marked, queryDatabaseRequest(row.ctx, database))+ err := mcpConfirmationRequired(row.database, "app")+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))+ require.Contains(t, err.Error(), "query_database")+ var connectErr *connect.Error+ require.ErrorAs(t, err, &connectErr)+ require.Len(t, connectErr.Details(), 1)+ value, valueErr := connectErr.Details()[0].Value()+ require.NoError(t, valueErr)+ info, ok := value.(*errdetails.ErrorInfo)+ require.True(t, ok)+ require.Equal(t, auth.MCPConfirmationReason, info.GetReason())+ require.Equal(t, auth.MCPConfirmationDomain, info.GetDomain())+ require.Equal(t, row.metadata, info.GetMetadata())})}}diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex 04ea398ce5..7391caedd1 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -355,6 +355,12 @@ func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryRreturn nil, err}}+ mcpWrite := !clamped && mcpSession(ctx) && !mcpStatementIsRead(ctx, instance.Metadata.GetEngine(), statement)+ // query_database takes no explain, so an explain of a possible write cannot+ // be confirmed.+ if mcpWrite && request.Explain {+ return nil, permissionDeniedError(ctx, errors.Errorf("an MCP session explains only statements Bytebase can show are reads. %s", mcpConsoleWayOut))+ }queryRestriction := getEffectiveQueryDataPolicy(ctx,@@ -363,9 +369,8 @@ func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryRrequest.Limit,database.ProjectID,)- routeAsWrite := !clamped && queryDatabaseRequest(ctx, request.Name) && !mcpStatementIsRead(ctx, instance.Metadata.GetEngine(), statement)var resolvedDataSourceID string- if routeAsWrite {+ if mcpWrite {resolvedDataSourceID, err = mcpWriteDataSourceID(instance, request.DataSourceId, queryRestriction.AllowAdminDataSource)} else {resolvedDataSourceID, err = resolveDataSourceID(ctx, instance, request.DataSourceId, statement, queryRestriction.AllowAdminDataSource)@@ -378,6 +383,11 @@ func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryRif err != nil {return nil, err}+ // After the data source checks, so a request they refuse is refused before+ // the user is asked.+ if mcpWrite && !mcpWriteConfirmed(ctx, request) {+ return nil, mcpConfirmationRequired(database, request.GetSchema())+ }driver, err := s.dbFactory.GetDataSourceDriver(ctx, instance, dataSource, db.ConnectionContext{DatabaseName: database.DatabaseName,DataShare: database.Metadata.GetDatashare(),diff --git a/backend/tests/mcp_masking_test.go b/backend/tests/mcp_masking_test.goindex 324f367f44..baef2fcb4d 100644--- a/backend/tests/mcp_masking_test.go+++ b/backend/tests/mcp_masking_test.go@@ -562,15 +562,12 @@ func TestMCPMaskedWriteIsRefused(t *testing.T) {a.NoError(err, "the console path must be untouched by the mask guard")a.NotEmpty(created.Msg.Name)- // And the door really is open, which "refused" alone cannot show. A clean- // write through SQLService/Query is the only place in this PR an MCP session- // runs DML end to end, so it is asserted on the stored value, not the status.+ // And the door really is open, which "refused" alone cannot show. An MCP+ // session writes only through query_database, so the clean write goes there+ // and is asserted on the stored value, not the status.const agentWrite = "UPDATE employee SET secret = 'rotated-by-agent' WHERE id = 1"- agentRan := callAPIOnSession(f.ctx, t, f.session, "SQLService/Query", map[string]any{- "name": f.database,- "statement": agentWrite,- })- a.Equal(http.StatusOK, agentRan.Status, "the execution door is open: %s", agentRan.Error)+ agentRan := queryDatabaseOnSession(f.ctx, t, f.session, f.name, agentWrite)+ a.False(agentRan.isError, "the execution door is open: %s", agentRan.text)a.Equal("rotated-by-agent", f.consoleReadsSecret(t),"the agent's write landed, so the refusals above were the guard and not a closed door")}diff --git a/backend/tests/mcp_sql_write_test.go b/backend/tests/mcp_sql_write_test.goindex cf50f46889..f90ec84c54 100644--- a/backend/tests/mcp_sql_write_test.go+++ b/backend/tests/mcp_sql_write_test.go@@ -3,14 +3,22 @@ package testsimport ("context""database/sql"+ "encoding/base64"+ "encoding/json""fmt""net/http""strconv"+ "strings"+ "sync""testing""connectrpc.com/connect"+ "github.com/modelcontextprotocol/go-sdk/mcp""github.com/stretchr/testify/require"+ "google.golang.org/genproto/googleapis/rpc/errdetails"+ "google.golang.org/protobuf/proto"+ "github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1")@@ -118,21 +126,127 @@ func TestMCPQueryDatabaseRoutesWritesAsWrites(t *testing.T) {routed := queryDatabaseOnSession(ctx, t, session, databaseName, setsTheSession)a.False(routed.isError, routed.text)a.Equal([][]any{{"postgres"}}, routed.output.Rows, "the verdict routes the request to ADMIN")- named := callAPIOnSession(ctx, t, session, "SQLService/Query", map[string]any{+ refused := callAPIOnSession(ctx, t, session, "SQLService/Query", map[string]any{"name": database,"dataSourceId": "readonly","statement": setsTheSession,})- a.Equal(http.StatusOK, named.Status, named.Error)- var namedResponse v1pb.QueryResponse- a.NoError(common.ProtojsonUnmarshaler.Unmarshal([]byte(named.RawResponse), &namedResponse))- a.Equal("mcp_write_ro", namedResponse.Results[0].Rows[0].Values[0].GetStringValue(), "call_api keeps the data source it names")+ a.Equal(http.StatusBadRequest, refused.Status, refused.Error)+ a.Equal(auth.MCPConfirmationReason, confirmationErrorInfo(t, refused.RawResponse).GetReason(), "call_api cannot confirm a possible write")written := queryDatabaseOnSession(ctx, t, session, databaseName, "INSERT INTO employee VALUES (2, 'query_database')")a.False(written.isError, "query_database writes on ADMIN, though it sends the read-only data source: %s", written.text)a.Equal(2, countRows(ctx, t, ctl, database, "employee"))}+// confirmationErrorInfo decodes the ErrorInfo a refused request's body carries,+// as query_database does.+func confirmationErrorInfo(t *testing.T, raw string) *errdetails.ErrorInfo {+ t.Helper()+ var body struct {+ Details []struct {+ Type string `json:"type"`+ Value string `json:"value"`+ } `json:"details"`+ }+ require.NoError(t, json.Unmarshal([]byte(raw), &body))+ require.Len(t, body.Details, 1)+ require.Equal(t, "google.rpc.ErrorInfo", body.Details[0].Type)+ value, err := base64.RawStdEncoding.DecodeString(body.Details[0].Value)+ require.NoError(t, err)+ var info errdetails.ErrorInfo+ require.NoError(t, proto.Unmarshal(value, &info))+ return &info+}++// formAnswerer is a client that answers every form the same way and keeps the+// messages it was shown.+type formAnswerer struct {+ answer *mcp.ElicitResult+ mu sync.Mutex+ messages []string+}++func (f *formAnswerer) handle(_ context.Context, req *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.messages = append(f.messages, req.Params.Message)+ return f.answer, nil+}++func (f *formAnswerer) asked() []string {+ f.mu.Lock()+ defer f.mu.Unlock()+ return append([]string(nil), f.messages...)+}++// A Read-write session whose client shows forms: the user's answer decides+// whether a statement Bytebase cannot show is a read runs.+func TestMCPQueryDatabaseAsksBeforeAWrite(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctl, ctx := startWorkspace(context.Background(), t)+ f := setupMCPClampFixture(ctx, t, ctl)+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))+ token, _ := mintMCPOAuthToken(t, ctl, ctl.authInterceptor.token)+ answering := func(answer *mcp.ElicitResult) (*mcp.ClientSession, *formAnswerer) {+ user := &formAnswerer{answer: answer}+ session := openMCPSessionWithOptions(ctx, t, ctl, token, &mcp.ClientOptions{ElicitationHandler: user.handle})+ t.Cleanup(func() { session.Close() })+ return session, user+ }+ const insert = "INSERT INTO employee VALUES (2, 'agent')"++ changing, changeUser := answering(&mcp.ElicitResult{Action: "accept", Content: map[string]any{"choice": "change"}})+ changed := queryDatabaseOnSession(ctx, t, changing, f.name, insert)+ a.False(changed.isError, changed.text)+ a.Contains(changed.text, "Not run: the user wants to change this request")+ a.Len(changeUser.asked(), 1)+ instanceID := strings.Split(f.database, "/")[1]+ a.Equal(fmt.Sprintf("Run in environment \"prod\" on database %q,\ninstance %q:\n%s", f.name, instanceID, insert), changeUser.asked()[0])+ a.Equal(1, f.employeeCount(t))++ declining, _ := answering(&mcp.ElicitResult{Action: "decline"})+ declined := queryDatabaseOnSession(ctx, t, declining, f.name, insert)+ a.Contains(declined.text, "Not run: the user declined")+ a.Equal(1, f.employeeCount(t))++ running, runUser := answering(&mcp.ElicitResult{Action: "accept", Content: map[string]any{"choice": "run"}})+ read := queryDatabaseOnSession(ctx, t, running, f.name, "SELECT name FROM employee")+ a.False(read.isError, read.text)+ a.Empty(runUser.asked(), "a read runs without asking")+ ran := queryDatabaseOnSession(ctx, t, running, f.name, insert)+ a.False(ran.isError, ran.text)+ a.Len(runUser.asked(), 1)+ a.Equal(2, f.employeeCount(t))++ direct := callAPIOnSession(ctx, t, running, "SQLService/Query", map[string]any{+ "name": f.database,+ "statement": "INSERT INTO employee VALUES (3, 'call_api')",+ })+ a.Equal(http.StatusBadRequest, direct.Status, direct.Error)+ a.Contains(direct.Error, "query_database")+ info := confirmationErrorInfo(t, direct.RawResponse)+ a.Equal(auth.MCPConfirmationReason, info.GetReason())+ a.Equal(map[string]string{"environment": "prod", "schema": ""}, info.GetMetadata())+ a.Equal(2, f.employeeCount(t))++ explained := callAPIOnSession(ctx, t, running, "SQLService/Query", map[string]any{+ "name": f.database,+ "statement": "INSERT INTO employee VALUES (4, 'explain')",+ "explain": true,+ })+ a.Equal(http.StatusForbidden, explained.Status, explained.Error)+ a.Contains(explained.Error, "explains only statements Bytebase can show are reads")+ a.Contains(explained.Error, "signed in to the Bytebase console")+ explainedRead := callAPIOnSession(ctx, t, running, "SQLService/Query", map[string]any{+ "name": f.database,+ "statement": "SELECT name FROM employee",+ "explain": true,+ })+ a.Equal(http.StatusOK, explainedRead.Status, explainedRead.Error)+}+// Export skips statement validation on MySQL, and the driver runs a statement// that returns no rows.func TestMCPExportRunsOnlyReads(t *testing.T) {diff --git a/docs/design/mcp-capability-ladder.md b/docs/design/mcp-capability-ladder.mdindex 59315b36df..fa76d9d5d2 100644--- a/docs/design/mcp-capability-ladder.md+++ b/docs/design/mcp-capability-ladder.md@@ -76,7 +76,7 @@ the product.| write | Grant or revoke masking exemptions | Exempt one member from masking for a database, a schema, a table or a column, or for every database in a project, with an optional expiry · Each exemption and each removal is confirmed in the user's MCP client before it is made · Exempted data shows unmasked in query and export results | 1 WRITE method: `OrgPolicyService/UpdatePolicy`, served only through the `grant_masking_exemption` and `revoke_masking_exemption` tools, which ask the user to confirm, then add one exemption entry or remove one member from the entries whose condition matches exactly; other policy types and `CreatePolicy` and `DeletePolicy` stay refused || 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 | 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. A statement Bytebase cannot show is a read runs only through the `query_database` tool, which asks the user to confirm it when the client can show the form (`mcp_sql_write.go`) || write | Export query results | Download results as a file. Data leaves Bytebase | 1 WRITE method: `SQLService/Export`, which requires the user's own `bb.sql.export` on the data it reads, from a role or a matching export grant, and runs only statements Bytebase can show are reads || write | Manage database housekeeping | Sync instances and databases · Saved queries | 9 WRITE methods: sync, saved-query writes || — | *Read-write stops here* | | 111 methods |