Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(mcp)!: route query_database writes as writes; MCP Export runs only reads (#21706)
Vincent Huang6e5f4558344b
diff --git a/backend/api/auth/mcp_confirmation.go b/backend/api/auth/mcp_confirmation.goindex 3da9e87511..7de1098b9b 100644--- a/backend/api/auth/mcp_confirmation.go+++ b/backend/api/auth/mcp_confirmation.go@@ -8,7 +8,8 @@ import (// 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.+// request changes. query_database attaches one for SQLService/Query without+// asking, until the form that asks lands (BYT-9292).type MCPConfirmedDecision struct {// Procedure is the connect procedure confirmed, such as// /bytebase.v1.IssueService/ApproveIssue.@@ -26,7 +27,7 @@ type MCPConfirmedDecision struct {// set the value; nothing a request carries can.type mcpConfirmedDecisionKey struct{}-// WithMCPConfirmedDecision marks ctx as carrying a decision the user confirmed.+// WithMCPConfirmedDecision marks ctx as carrying decision.func WithMCPConfirmedDecision(ctx context.Context, decision MCPConfirmedDecision) context.Context {return context.WithValue(ctx, mcpConfirmedDecisionKey{}, decision)}diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.goindex ed6c824e72..268fc1998b 100644--- a/backend/api/mcp/tool_query.go+++ b/backend/api/mcp/tool_query.go@@ -12,7 +12,9 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp""github.com/pkg/errors"+ "github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common/permission"+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect")const (@@ -233,7 +235,13 @@ func (s *Server) executeQuery(ctx context.Context, resolved *resolvedDatabase, iif input.Container != "" {body["container"] = input.Container}- resp, err := s.apiRequest(ctx, "/bytebase.v1.SQLService/Query", body)+ // 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,+ })+ resp, err := s.apiRequest(ctx, v1connect.SQLServiceQueryProcedure, body)if err != nil {// The call can end partway through a batch, as when queryTimeout passes.return nil, &toolError{diff --git a/backend/api/v1/mcp_masking.go b/backend/api/v1/mcp_masking.goindex 1b070beadc..c3d0bf1375 100644--- a/backend/api/v1/mcp_masking.go+++ b/backend/api/v1/mcp_masking.go@@ -102,9 +102,8 @@ func refuseMaskedWriteQuery(ctx context.Context, msg any) string {}// refuseMaskedWriteExport guards the same door under another name. Export takes-// a raw statement, and on MySQL it skips validateQueryRequest (sql_service.go)-// and reaches a driver that ExecContexts anything not all-query — so an export-// request writes.+// a raw statement. Its handler refuses an MCP export Bytebase cannot show is a+// read, so this adds the read that carries the placeholder.func refuseMaskedWriteExport(ctx context.Context, msg any) string {request, ok := msg.(*v1pb.ExportRequest)if !ok {diff --git a/backend/api/v1/mcp_sql_clamp.go b/backend/api/v1/mcp_sql_clamp.goindex 2594a4fce6..4d6866e20d 100644--- a/backend/api/v1/mcp_sql_clamp.go+++ b/backend/api/v1/mcp_sql_clamp.go@@ -43,12 +43,22 @@ func mcpReadOnlyClampApplies(ctx context.Context) (bool, error) {return settings.Capability == storepb.MCPSetting_READ_ONLY, nil}-// refuseNonReadOnlyStatement classifies a request fail-closed. Nothing here-// calls base.ValidateSQLForEditor bare: it answers "read-only" for an engine-// with no registered validator, which suits a caller that only routes on the-// verdict and admits every write for one that must refuse a write.+// refuseNonReadOnlyStatement refuses a request nonReadReason does not show to be+// a read.+func refuseNonReadOnlyStatement(engine storepb.Engine, statement string) error {+ if reason := nonReadReason(engine, statement); reason != "" {+ return refuseClampedStatement(reason)+ }+ return nil+}++// nonReadReason classifies a request fail-closed: it says why the request is not+// shown to be a read, or returns "" when every statement the driver would run is+// one. Nothing here calls base.ValidateSQLForEditor bare: it answers "read-only"+// for an engine with no registered validator, which suits a caller that only+// routes on the verdict and admits every write for one that must refuse a write.//-// A statement that returns no data is refused as well as one that is not a+// A statement that returns no data fails as well as one that is not a// read. Every unit of a request runs on one connection, and Postgres applies a// changed default_transaction_read_only to the next transaction, so// "SET default_transaction_read_only = off" followed by a classifier-admitted@@ -60,28 +70,26 @@ func mcpReadOnlyClampApplies(ctx context.Context) (bool, error) {//// Not closed: a structurally-reading statement can still call a function that// rewrites the same setting (set_config, BOT-88).-func refuseNonReadOnlyStatement(engine storepb.Engine, statement string) error {+func nonReadReason(engine storepb.Engine, statement string) string {if !parserbase.HasQueryValidator(engine) {- return refuseClampedStatement(fmt.Sprintf(- "Bytebase has no read-only classifier for %v, so no statement on this engine can be shown to be a read", engine))+ return fmt.Sprintf("Bytebase has no read-only classifier for %v, so no statement on this engine can be shown to be a read", engine)}units := mcpClampUnits(engine, statement)for i, unit := range units {readOnly, allQuery, err := parserbase.ValidateSQLForEditor(engine, unit)if err != nil {- return refuseClampedStatement(fmt.Sprintf(- "%s could not be parsed, so it cannot be shown to be a read: %v", describeClampUnit(i, len(units)), err))+ return fmt.Sprintf("%s could not be parsed, so it cannot be shown to be a read: %v", describeClampUnit(i, len(units)), err)}if !readOnly {- return refuseClampedStatement(fmt.Sprintf("%s is not a read", describeClampUnit(i, len(units))))+ return fmt.Sprintf("%s is not a read", describeClampUnit(i, len(units)))}if !allQuery {- return refuseClampedStatement(fmt.Sprintf(+ return fmt.Sprintf("%s returns no data, so it either rewrites the session it runs on, which can switch off the read-only session the rest of the request depends on, or runs the query to measure it. A read-only ceiling serves statements that only read",- describeClampUnit(i, len(units))))+ describeClampUnit(i, len(units)))}}- return nil+ return ""}// mcpClampUnits splits a request the way queryRetryStopOnError does, includingdiff --git a/backend/api/v1/mcp_sql_write.go b/backend/api/v1/mcp_sql_write.gonew file mode 100644index 0000000000..391da1b7e6--- /dev/null+++ b/backend/api/v1/mcp_sql_write.go@@ -0,0 +1,43 @@+package v1++import (+ "context"++ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/api/auth"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"+ "github.com/bytebase/bytebase/backend/store"+)++// mcpStatementIsRead reports whether a Read-write MCP session may run statement+// as a read. MongoDB and Elasticsearch have no validator, so they use the span+// check access grants use; on other engines with no validator nothing is a read+// (BOT-87).+func mcpStatementIsRead(ctx context.Context, engine storepb.Engine, statement string) bool {+ if shouldClassifyStatementByQuerySpan(engine) {+ read, err := isReadOnlyStatementForAccessGrant(ctx, engine, statement)+ return err == nil && read+ }+ return 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 {+ marker, ok := auth.MCPConfirmedDecisionFromContext(ctx)+ return ok && marker.Procedure == v1connect.SQLServiceQueryProcedure && marker.Resource == database+}++// 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.+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 != "" {+ return picked, nil+ }+ return id, err+}diff --git a/backend/api/v1/mcp_sql_write_test.go b/backend/api/v1/mcp_sql_write_test.gonew file mode 100644index 0000000000..72557a93c9--- /dev/null+++ b/backend/api/v1/mcp_sql_write_test.go@@ -0,0 +1,90 @@+package v1++import (+ "context"+ "testing"++ "connectrpc.com/connect"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/api/auth"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"+ "github.com/bytebase/bytebase/backend/store"+)++func TestMCPStatementIsRead(t *testing.T) {+ for _, row := range []struct {+ name string+ engine storepb.Engine+ statement string+ read bool+ }{+ {name: "a read", engine: storepb.Engine_POSTGRES, statement: "SELECT id FROM employee", read: true},+ {name: "a write", engine: storepb.Engine_POSTGRES, statement: "UPDATE employee SET name = 'x'"},+ {name: "a read and a write", engine: storepb.Engine_POSTGRES, statement: "SELECT id FROM employee; DELETE FROM employee"},+ {name: "a statement that returns no data", engine: storepb.Engine_POSTGRES, statement: "SET search_path TO app"},+ {name: "a statement that does not parse", engine: storepb.Engine_POSTGRES, statement: "SELEC id FROM employee"},+ {name: "a MongoDB read", engine: storepb.Engine_MONGODB, statement: `db.employee.find({})`, read: true},+ {name: "a MongoDB write", engine: storepb.Engine_MONGODB, statement: unclassifiedEngineWrites[storepb.Engine_MONGODB]},+ {name: "an Elasticsearch read", engine: storepb.Engine_ELASTICSEARCH, statement: "GET /employee/_search\n{\"query\":{\"match_all\":{}}}", read: true},+ {name: "an Elasticsearch write", engine: storepb.Engine_ELASTICSEARCH, statement: unclassifiedEngineWrites[storepb.Engine_ELASTICSEARCH]},+ {name: "a Databricks read", engine: storepb.Engine_DATABRICKS, statement: "SELECT 1"},+ } {+ t.Run(row.name, func(t *testing.T) {+ require.Equal(t, row.read, mcpStatementIsRead(context.Background(), row.engine, row.statement))+ })+ }+}++func TestQueryDatabaseRequest(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})+ }+ for _, row := range []struct {+ name string+ ctx context.Context+ marked 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)},+ } {+ t.Run(row.name, func(t *testing.T) {+ require.Equal(t, row.marked, queryDatabaseRequest(row.ctx, database))+ })+ }+}++func TestMCPWriteDataSourceID(t *testing.T) {+ admin := &storepb.DataSource{Id: "admin", Type: storepb.DataSourceType_ADMIN}+ readOnly := &storepb.DataSource{Id: "ro", Type: storepb.DataSourceType_READ_ONLY}+ readOnly2 := &storepb.DataSource{Id: "ro-2", Type: storepb.DataSourceType_READ_ONLY}+ for _, row := range []struct {+ name string+ dataSources []*storepb.DataSource+ picked string+ allowAdmin bool+ want string+ }{+ {name: "the policy allows ADMIN", dataSources: []*storepb.DataSource{admin, readOnly}, picked: "ro", allowAdmin: true, want: "admin"},+ {name: "the policy keeps writes off ADMIN", dataSources: []*storepb.DataSource{admin, readOnly}, picked: "ro", want: "ro"},+ {name: "no read-only data source", dataSources: []*storepb.DataSource{admin}, picked: "admin", want: "admin"},+ {name: "several read-only data sources keep query_database's pick", dataSources: []*storepb.DataSource{admin, readOnly, readOnly2}, picked: "ro-2", want: "ro-2"},+ } {+ t.Run(row.name, func(t *testing.T) {+ instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: storepb.Engine_POSTGRES, DataSources: row.dataSources}}+ got, err := mcpWriteDataSourceID(instance, row.picked, row.allowAdmin)+ require.NoError(t, err)+ require.Equal(t, row.want, got)+ })+ }++ t.Run("several read-only data sources and no pick", func(t *testing.T) {+ instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: storepb.Engine_POSTGRES, DataSources: []*storepb.DataSource{readOnly, readOnly2}}}+ _, err := mcpWriteDataSourceID(instance, "", false)+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))+ })+}diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex bf6bac381c..21b32af050 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -363,7 +363,13 @@ func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryRrequest.Limit,database.ProjectID,)- resolvedDataSourceID, err := resolveDataSourceID(ctx, instance, request.DataSourceId, statement, queryRestriction.AllowAdminDataSource)+ routeAsWrite := !clamped && queryDatabaseRequest(ctx, request.Name) && !mcpStatementIsRead(ctx, instance.Metadata.GetEngine(), statement)+ var resolvedDataSourceID string+ if routeAsWrite {+ resolvedDataSourceID, err = mcpWriteDataSourceID(instance, request.DataSourceId, queryRestriction.AllowAdminDataSource)+ } else {+ resolvedDataSourceID, err = resolveDataSourceID(ctx, instance, request.DataSourceId, statement, queryRestriction.AllowAdminDataSource)+ }if err != nil {return nil, err}@@ -1223,6 +1229,12 @@ func (s *SQLService) Export(ctx context.Context, req *connect.Request[v1pb.Expor// grant via slice order (PR #20491 bot review).accessGrant := s.preCheckAccess(ctx, request.Statement, instance, database, request.Schema, request.GetContainer(), true /* requireExport */)+ // The validation below admits a write on MySQL and on an engine with no+ // validator, and the driver runs it.+ if mcpSession(ctx) && !mcpStatementIsRead(ctx, instance.Metadata.GetEngine(), statement) {+ return nil, permissionDeniedError(ctx, errors.Errorf("an MCP session exports only statements Bytebase can show are reads. %s", mcpConsoleWayOut))+ }+// Validate the request.// New query ACL experience.if instance.Metadata.GetEngine() != storepb.Engine_MYSQL {@@ -2490,7 +2502,15 @@ func resolveDataSourceID(ctx context.Context, instance *store.InstanceMessage, dif dataSourceID != "" {return dataSourceID, nil}+ return routeDataSource(instance, allowAdminDataSource, func() bool {+ return requiresAdminDataSource(ctx, instance.Metadata.GetEngine(), statement)+ })+}++var errMultipleReadOnlyDataSources = errors.New("instance has multiple read-only data sources, please specify data_source_id explicitly")+// routeDataSource picks the data source for a request that names none.+func routeDataSource(instance *store.InstanceMessage, allowAdminDataSource bool, needsAdmin func() bool) (string, error) {var adminDataSourceID stringvar readOnlyDataSourceID stringreadOnlyCount := 0@@ -2505,7 +2525,7 @@ func resolveDataSourceID(ctx context.Context, instance *store.InstanceMessage, d}}- if allowAdminDataSource && adminDataSourceID != "" && requiresAdminDataSource(ctx, instance.Metadata.GetEngine(), statement) {+ if allowAdminDataSource && adminDataSourceID != "" && needsAdmin() {return adminDataSourceID, nil}@@ -2513,7 +2533,7 @@ func resolveDataSourceID(ctx context.Context, instance *store.InstanceMessage, dcase readOnlyCount == 1:return readOnlyDataSourceID, nilcase readOnlyCount > 1:- return "", connect.NewError(connect.CodeFailedPrecondition, errors.New("instance has multiple read-only data sources, please specify data_source_id explicitly"))+ return "", connect.NewError(connect.CodeFailedPrecondition, errMultipleReadOnlyDataSources)case adminDataSourceID != "":return adminDataSourceID, nildefault:diff --git a/backend/tests/mcp_sql_write_test.go b/backend/tests/mcp_sql_write_test.gonew file mode 100644index 0000000000..cf50f46889--- /dev/null+++ b/backend/tests/mcp_sql_write_test.go@@ -0,0 +1,177 @@+package tests++import (+ "context"+ "database/sql"+ "fmt"+ "net/http"+ "strconv"+ "testing"++ "connectrpc.com/connect"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/common"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++// countRows reads a table's row count on the human path, which no MCP check+// applies to.+func countRows(ctx context.Context, t *testing.T, ctl *controller, database, table string) int {+ t.Helper()+ resp, err := ctl.sqlServiceClient.Query(ctx, connect.NewRequest(&v1pb.QueryRequest{+ Name: database,+ Statement: fmt.Sprintf("SELECT count(*) FROM %s", table),+ }))+ require.NoError(t, err)+ require.Len(t, resp.Msg.Results, 1)+ require.Empty(t, resp.Msg.Results[0].Error)+ value := resp.Msg.Results[0].Rows[0].Values[0]+ if s := value.GetStringValue(); s != "" {+ n, err := strconv.Atoi(s)+ require.NoError(t, err)+ return n+ }+ return int(value.GetInt64Value())+}++// An instance with a read-only data source, where the query data policy lets+// writes use ADMIN. query_database sends the read-only data source, and the+// read-only account can only SELECT.+func TestMCPQueryDatabaseRoutesWritesAsWrites(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctl, ctx := startWorkspace(context.Background(), t)++ pg := provisionPgInstance(t)+ _, err := pg.GetDB().Exec("CREATE ROLE mcp_write_ro LOGIN PASSWORD 'mcp_write_ro_password'")+ a.NoError(err)+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{+ InstanceId: generateRandomString("mcp-write"),+ Instance: &v1pb.Instance{+ Title: "MCP write",+ Engine: v1pb.Engine_POSTGRES,+ Environment: new("environments/prod"),+ Activation: true,+ DataSources: []*v1pb.DataSource{pg.adminDataSource()},+ },+ }))+ a.NoError(err)+ const databaseName = "mcpwritedb"+ a.NoError(ctl.createDatabase(ctx, ctl.project, instanceResp.Msg, nil, databaseName, "postgres"))+ database := fmt.Sprintf("%s/databases/%s", instanceResp.Msg.Name, databaseName)+ databaseResp, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{Name: database}))+ a.NoError(err)+ setup, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte(`CREATE TABLE employee(id INT PRIMARY KEY, name TEXT); INSERT INTO employee VALUES (1, 'Bytebase');`)},+ }))+ a.NoError(err)+ a.NoError(ctl.changeDatabase(ctx, ctl.project, databaseResp.Msg, setup.Msg, false))++ grants, err := sql.Open("pgx", fmt.Sprintf("postgresql://postgres:root-password@%s:%s/%s?sslmode=disable", pg.GetHost(), pg.GetPort(), databaseName))+ a.NoError(err)+ defer grants.Close()+ for _, statement := range []string{+ fmt.Sprintf("GRANT CONNECT ON DATABASE %q TO mcp_write_ro", databaseName),+ "GRANT USAGE ON SCHEMA public TO mcp_write_ro",+ "GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_write_ro",+ } {+ _, err = grants.Exec(statement)+ a.NoError(err)+ }+ _, err = ctl.instanceServiceClient.AddDataSource(ctx, connect.NewRequest(&v1pb.AddDataSourceRequest{+ Name: instanceResp.Msg.Name,+ DataSource: &v1pb.DataSource{+ Id: "readonly",+ Type: v1pb.DataSourceType_READ_ONLY,+ Host: pg.GetHost(),+ Port: pg.GetPort(),+ Username: "mcp_write_ro",+ Password: "mcp_write_ro_password",+ },+ }))+ a.NoError(err)+ workspaceID, err := getStore(t, ctl.server).GetWorkspaceID(ctx)+ a.NoError(err)+ _, err = ctl.orgPolicyServiceClient.CreatePolicy(ctx, connect.NewRequest(&v1pb.CreatePolicyRequest{+ Parent: common.FormatWorkspace(workspaceID),+ Policy: &v1pb.Policy{+ Type: v1pb.PolicyType_DATA_QUERY,+ Policy: &v1pb.Policy_QueryDataPolicy{QueryDataPolicy: &v1pb.QueryDataPolicy{AllowAdminDataSource: true}},+ },+ }))+ a.NoError(err)++ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))+ token, _ := mintMCPOAuthToken(t, ctl, ctl.authInterceptor.token)+ session := openMCPSession(ctx, t, ctl, token)+ defer session.Close()++ read := queryDatabaseOnSession(ctx, t, session, databaseName, "SELECT current_user")+ a.False(read.isError, read.text)+ a.Equal([][]any{{"mcp_write_ro"}}, read.output.Rows, "a read keeps the data source query_database sends")++ // A SET returns no data, so the verdict cannot show this request is a read,+ // while the SQL Editor's routing reads it as one.+ const setsTheSession = "SELECT current_user; SET search_path TO public"+ 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{+ "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")++ 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"))+}++// Export skips statement validation on MySQL, and the driver runs a statement+// that returns no rows.+func TestMCPExportRunsOnlyReads(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctl, ctx := startWorkspace(context.Background(), t)+ database, _ := ctl.createTestMySQLDatabase(ctx, t)+ setup, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: ctl.project.Name,+ Sheet: &v1pb.Sheet{Content: []byte(`CREATE TABLE employee(id INT PRIMARY KEY); INSERT INTO employee VALUES (1);`)},+ }))+ a.NoError(err)+ a.NoError(ctl.changeDatabase(ctx, ctl.project, database, setup.Msg, false))++ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))+ token, _ := mintMCPOAuthToken(t, ctl, ctl.authInterceptor.token)+ session := openMCPSession(ctx, t, ctl, token)+ defer session.Close()++ exported := callAPIOnSession(ctx, t, session, "SQLService/Export", map[string]any{+ "name": database.Name,+ "statement": "SELECT id FROM employee",+ "format": "JSON",+ })+ a.Equal(http.StatusOK, exported.Status, "a read exports: %s", exported.Error)++ refused := callAPIOnSession(ctx, t, session, "SQLService/Export", map[string]any{+ "name": database.Name,+ "statement": "INSERT INTO employee VALUES (2)",+ "format": "JSON",+ })+ a.Equal(http.StatusForbidden, refused.Status, "an export must not write: %s", refused.Error)+ a.Contains(refused.Error, "exports only statements Bytebase can show are reads")+ a.Equal(1, countRows(ctx, t, ctl, database.Name, "employee"))++ _, err = ctl.sqlServiceClient.Export(ctx, connect.NewRequest(&v1pb.ExportRequest{+ Name: database.Name,+ Statement: "SET @n = 1; SELECT id FROM employee",+ Format: v1pb.ExportFormat_JSON,+ }))+ a.NoError(err, "the console still exports a request the verdict cannot show is a read")+}diff --git a/docs/design/mcp-capability-ladder.md b/docs/design/mcp-capability-ladder.mdindex df121df21d..59315b36df 100644--- a/docs/design/mcp-capability-ladder.md+++ b/docs/design/mcp-capability-ladder.md@@ -77,7 +77,7 @@ the product.| 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`, which requires the user's own `bb.sql.export` on the data it reads, from a role or a matching export grant |+| 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 || floor | Never, in any mode: administer the workspace, handle credentials, open an Admin mode session, or read anyone else's query history. | | 109 methods: 34 FORBIDDEN, 75 EXCLUDED |@@ -562,13 +562,12 @@ to live in the bound line there (D10), not in a row's sub-items.- A custom access policy. When it comes, the rows become checkboxes, the cards become presetbuttons that select a prefix, and a policy matching no prefix shows a Custom chip; the backend- row table is what the gate would read. The ladder needs no redesign. One precondition before- rows become independently selectable: `SQLService/Export` must be clamped to read statements.- On MySQL it skips statement validation and the driver executes non-query statements, and the- clamp today lives only in `SQLService/Query`. Under the presets Export is served only alongside- the DML/DDL row, so there is no exposure until then. That clamp is an MCP implementation change,- tracked separately from this doc. The same split is why the consent card's Read-write bound names- the operation as well as the engine (the method axis in The rows).+ row table is what the gate would read. The ladder needs no redesign. The one precondition before+ rows become independently selectable is met: `SQLService/Export` runs only statements Bytebase+ can show are reads for an MCP session (`mcp_sql_write.go`). Export needed its own check because+ it skips statement validation on MySQL, and the driver executes non-query statements. The same+ split is why the consent card's Read-write bound names the operation as well as the engine (the+ method axis in The rows).- A docs page listing the methods per row, generated from the inventory. Worth doing; not linkedfrom the card until it exists.- Making the collapsed list findable by the browser's find-in-page. Base UI unmounts a closed panel,diff --git a/docs/design/sql-export-permission.md b/docs/design/sql-export-permission.mdindex 2c18e67e33..658e638431 100644--- a/docs/design/sql-export-permission.md+++ b/docs/design/sql-export-permission.md@@ -170,7 +170,8 @@ validator are an existing exception: on Databricks, a write produces no spans andatabase-level select check through both `Query` and `Export` today(`docs/design/mcp-capability-ladder.md:160`). Under this design `Export` checks `bb.sql.export`there, so an export-only custom role can run such a write through `Export`, as a select role can-today. The read-only clamp on `Export` that the ladder doc tracks closes it for both.+today. For an MCP session, `Export` refuses every statement Bytebase cannot show is a read,+Databricks included (`mcp_sql_write.go`). The console keeps the exception.The CEL input is unchanged: database, schema and table per source column (`sql_service.go:1756`),and the database-level fallback. `hasDatabaseAccessRights` strips the environment condition for