Skip to content

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

fix(mcp)!: correct misleading MCP tool text and name the session's workspace (#21865)

Vincent Huangcb3a96b2c617
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index f366f3ea66..8368722b9a 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -19993,13 +19993,15 @@ components:
automatic:
type: boolean
title: automatic
- description: Whether rollout is automatic without manual approval.
+ description: Whether the environment's rollout tasks start on their own, with no one running them.
roles:
type: array
items:
type: string
title: roles
- description: The roles that can approve rollout execution.
+ description: |-
+ Who can run, skip or cancel the environment's rollout tasks; WORKSPACE_APPROVAL sets approvers.
+ Anyone with bb.taskRuns.create can too.
title: RolloutPolicy
additionalProperties: false
description: Rollout policy configuration.
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
index 563e81c06c..a4a6b2dc91 100644
--- a/backend/api/mcp/server.go
+++ b/backend/api/mcp/server.go
@@ -19,6 +19,7 @@ import (
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/audit"
"github.com/bytebase/bytebase/backend/component/config"
@@ -208,15 +209,18 @@ func negotiateLegacyProtocol(next mcp.MethodHandler) mcp.MethodHandler {
}
// nameSignedInAccount opens the initialize instructions with the session's
-// Bytebase account: clients also show the model other accounts, such as their
-// own sign-in. It goes first, so a client that cuts long instructions keeps it.
+// Bytebase account and workspace: clients also show the model other accounts,
+// such as their own sign-in, and an agent that needs a workspace name should
+// not have to guess one. It goes first, so a client that cuts long
+// instructions keeps it.
func nameSignedInAccount(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
result, err := next(ctx, method, req)
// The SDK refuses a second initialize on a session with a nil result,
// and a panic here would end the process.
if initialized, ok := result.(*mcp.InitializeResult); ok && initialized != nil {
- account := fmt.Sprintf(`This session acts as the Bytebase account %s: every tool call runs with its permissions, and "you" in tool results means it. The user may have other accounts with other emails, such as the client's own sign-in.`, getUserEmail(ctx))
+ account := fmt.Sprintf(`In %s, this session acts as the Bytebase account %s, with its permissions. "You" in tool results means it, not another account such as the client's sign-in.`,
+ common.FormatWorkspace(getWorkspaceID(ctx)), getUserEmail(ctx))
initialized.Instructions = account + "\n\n" + initialized.Instructions
}
return result, err
diff --git a/backend/api/mcp/server_test.go b/backend/api/mcp/server_test.go
index be0db12709..af6f5a78fc 100644
--- a/backend/api/mcp/server_test.go
+++ b/backend/api/mcp/server_test.go
@@ -612,8 +612,8 @@ func listToolsOverRoute(t *testing.T) []*mcp.Tool {
}
func TestInitializeServesInstructions(t *testing.T) {
- const account = `This session acts as the Bytebase account [email protected]: every tool call runs with its permissions, ` +
- `and "you" in tool results means it. The user may have other accounts with other emails, such as the client's own sign-in.`
+ const account = `In workspaces/ws-test, this session acts as the Bytebase account [email protected], with its permissions. ` +
+ `"You" in tool results means it, not another account such as the client's sign-in.`
tools := listToolsOverRoute(t)
for _, row := range []struct {
name string
@@ -670,10 +670,14 @@ func TestServerInstructionsFitClientLimit(t *testing.T) {
// No deliverable address is longer than 254 characters: RFC 5321
// §4.5.3.1.3 caps a path at 256 octets, angle brackets included.
email := strings.Repeat("a", 242) + "@example.com"
+ // Bytebase gives a new workspace a 16-character ID (auth_service.go). A
+ // workspace from before 3.17 keeps its UUID (migration 3.17/0009).
+ workspaceID := "6c86d081-379d-4366-be6f-481425e6f397"
endpoint, _, _ := newProbeServer(t)
- session := connectLegacy(t, endpoint, mintMCPToken(t, email, "client-A", "ws-test", "mcp:read-write", time.Hour), nil)
+ session := connectLegacy(t, endpoint, mintMCPToken(t, email, "client-A", workspaceID, "mcp:read-write", time.Hour), nil)
instructions := session.InitializeResult().Instructions
require.Contains(t, instructions, email)
+ require.Contains(t, instructions, "workspaces/"+workspaceID)
// Claude Code cuts server instructions at 4,096 characters, and before
// v2.1.296 at 2,048 (code.claude.com/docs/en/mcp). Holding the older limit
diff --git a/backend/api/mcp/tool_exemption.go b/backend/api/mcp/tool_exemption.go
index ae7aaaab48..70fe4fa91e 100644
--- a/backend/api/mcp/tool_exemption.go
+++ b/backend/api/mcp/tool_exemption.go
@@ -67,7 +67,7 @@ const grantMaskingExemptionDescription = `Exempt one member from data masking in
| expireTime | No | RFC 3339 time the exemption ends, e.g. "2026-10-27T00:00:00Z"; without it, it does not expire |
| reason | No | Why, recorded with the exemption |
-An exemption is a standing policy change: the member then sees the covered data unmasked in query and export results. For a one-off query, request an access grant instead with request_access_grant.
+An exemption is a standing policy change: the member bypasses the masking that applies to the covered data in query and export results, including masking set up later. It does not set up masking itself. For a one-off query, request an access grant instead with request_access_grant.
The tool adds one exemption and leaves every other entry as it is. For several columns of one table, pass them together in columns, so the user confirms once. It shows the user the member, the scope, the expiry and the effect, and asks them to confirm in a form; it writes only when they accept. A client that cannot show the form gets the project's masking exemption page, to grant it in the Bytebase console instead. Do not ask in chat first: the form is the question.
@@ -463,9 +463,9 @@ func describeExemptionGrant(ctx context.Context, g *exemptionGrant) string {
} else {
lines = append(lines, fmt.Sprintf("Instance %q", g.instanceID), fmt.Sprintf("Database %q, %s", g.databaseName, describeNarrowing(g)))
}
- effect := "Unmasked in query and export results, with no expiry."
+ effect := "Bypasses masking here, with no expiry; adds no masking."
if g.expireTime != "" {
- effect = fmt.Sprintf("Unmasked in query and export results until %q.", g.expireTime)
+ effect = fmt.Sprintf("Bypasses masking here until %q; adds no masking.", g.expireTime)
}
if g.note != "" {
effect += fmt.Sprintf(" Reason: %q", g.note)
@@ -528,7 +528,7 @@ func describeExemptionRevoke(ctx context.Context, input RevokeMaskingExemptionIn
question + "?",
fmt.Sprintf("Project %q", projectID),
condition,
- "Masked again in their results unless another exemption covers the data.",
+ "Ends their bypass of any masking here, unless another exemption covers it.",
}, "\n")
}
diff --git a/backend/api/mcp/tool_exemption_test.go b/backend/api/mcp/tool_exemption_test.go
index 194cd88400..9416b9b9f7 100644
--- a/backend/api/mcp/tool_exemption_test.go
+++ b/backend/api/mcp/tool_exemption_test.go
@@ -158,7 +158,7 @@ func TestGrantMaskingExemptionCreatesTheFirstExemption(t *testing.T) {
`Exempt "user:[email protected]" from masking, as [email protected]?`,
`Instance "prod"`,
`Database "hr", column "salary" in "public"."employee"`,
- `Unmasked in query and export results until "2026-10-27T00:00:00.000Z". Reason: "payroll audit"`,
+ `Bypasses masking here until "2026-10-27T00:00:00.000Z"; adds no masking. Reason: "payroll audit"`,
}, "\n"), user.lastParams(t).Message)
calls := mock.calls()
@@ -293,7 +293,7 @@ func TestGrantMaskingExemptionForEveryDatabaseIsExplicit(t *testing.T) {
`Exempt "user:[email protected]" from masking, as [email protected]?`,
`Project "hr"`,
`Scope: all databases in the project, current and future`,
- `Unmasked in query and export results, with no expiry.`,
+ `Bypasses masking here, with no expiry; adds no masking.`,
}, "\n"), user.lastParams(t).Message)
calls := mock.calls()
require.Len(t, calls, 1)
@@ -504,7 +504,7 @@ func TestRevokeMaskingExemptionRemovesTheMemberFromEveryMatch(t *testing.T) {
`Revoke masking exemption: "user:[email protected]", as [email protected]?`,
`Project "hr"`,
`Condition (2 entries) "(resource.instance_id == \"prod\" && resource.database_name == \"hr\")"`,
- `Masked again in their results unless another exemption covers the data.`,
+ `Ends their bypass of any masking here, unless another exemption covers it.`,
}, "\n"), user.lastParams(t).Message)
calls := mock.calls()
require.Len(t, calls, 1)
@@ -627,7 +627,7 @@ func TestMaskingExemptionFormsShowTheScopeInClaudeCodesDialog(t *testing.T) {
require.True(t, strings.HasPrefix(view[0], fmt.Sprintf("Exempt %q", member)), "a %d-character member shows whole, its project included: %q", len(member), view)
require.Equal(t, fmt.Sprintf("Instance %q", longest), view[1], "the longest instance ID shows whole")
require.True(t, strings.HasPrefix(view[2], `Database "`+longest), "the longest PostgreSQL database name shows whole, and the narrowing after it is cut: %q", view)
- require.True(t, strings.HasPrefix(view[3], "Unmasked in query and export results"), "%q", view)
+ require.True(t, strings.HasPrefix(view[3], "Bypasses masking here"), "%q", view)
west := grantView(&exemptionGrant{member: "user:[email protected]", database: "d", instanceID: "production-analytics-platform-west", databaseName: "hr"}, columns)
east := grantView(&exemptionGrant{member: "user:[email protected]", database: "d", instanceID: "production-analytics-platform-east", databaseName: "hr"}, columns)
@@ -640,7 +640,7 @@ func TestMaskingExemptionFormsShowTheScopeInClaudeCodesDialog(t *testing.T) {
require.Len(t, all, 4, "%q", all)
require.Equal(t, fmt.Sprintf("Project %q", longest), all[1])
require.Equal(t, "Scope: all databases in the project, current and future", all[2])
- require.True(t, strings.HasPrefix(all[3], `Unmasked in query and export results until "2026-10-27T00:00:00.000Z".`), "the expiry shows before the reason is cut: %q", all)
+ require.True(t, strings.HasPrefix(all[3], `Bypasses masking here until "2026-10-27T00:00:00.000Z"; adds no masking.`), "the expiry and the no-setup clause show before the reason is cut: %q", all)
revoke := claudeCodeView(describeExemptionRevoke(ctx, RevokeMaskingExemptionInput{Project: "projects/" + longest, Member: "user:[email protected]", Condition: strings.Repeat("c", 200)}, 3), columns)
require.Len(t, revoke, 4, "%q", revoke)
diff --git a/backend/api/mcp/tool_schema.go b/backend/api/mcp/tool_schema.go
index 9a59807ec6..76438ea90a 100644
--- a/backend/api/mcp/tool_schema.go
+++ b/backend/api/mcp/tool_schema.go
@@ -102,13 +102,13 @@ type SchemaSection struct {
// TableEntry describes a table. Which fields are populated depends on the include level.
type TableEntry struct {
- Name string `json:"name"`
- RowCount int64 `json:"rowCount"`
- ColumnCount int `json:"columnCount,omitempty"` // summary only; in columns/details modes, len(Columns) is the count
- Comment string `json:"comment,omitempty"`
- Columns []ColumnEntry `json:"columns,omitempty"` // columns+
- Indexes []IndexEntry `json:"indexes,omitempty"` // details+
- ForeignKeys []FKEntry `json:"foreignKeys,omitempty"` // details+
+ Name string `json:"name"`
+ RowCountEstimate int64 `json:"rowCountEstimate"` // as the last sync recorded it; can be an estimate (PostgreSQL: pg_class.reltuples)
+ ColumnCount int `json:"columnCount,omitempty"` // summary only; in columns/details modes, len(Columns) is the count
+ Comment string `json:"comment,omitempty"`
+ Columns []ColumnEntry `json:"columns,omitempty"` // columns+
+ Indexes []IndexEntry `json:"indexes,omitempty"` // details+
+ ForeignKeys []FKEntry `json:"foreignKeys,omitempty"` // details+
}
// ColumnEntry describes a single column.
@@ -221,6 +221,7 @@ const getSchemaDescription = `Inspect a Bytebase database's schema.
- For databases with many tables, columns/details modes return up to 200 tables PER SCHEMA.
Use schema= or table= to narrow further.
- Column masking metadata is only returned when table= is set.
+- rowCountEstimate is the row count the last metadata sync recorded. It can be an estimate, and can read 0 for a table that has rows; run a COUNT query when the number matters.
- Requires bb.databases.getSchema permission.`
func (s *Server) registerSchemaTool() {
@@ -553,9 +554,9 @@ func transformSchemas(metadata *databaseMetadata, include string) []SchemaSectio
func buildTableEntry(t *tableMetadata, include string) TableEntry {
rowCount, _ := t.RowCount.Int64()
entry := TableEntry{
- Name: t.Name,
- RowCount: rowCount,
- Comment: t.Comment,
+ Name: t.Name,
+ RowCountEstimate: rowCount,
+ Comment: t.Comment,
}
if include == schemaIncludeSummary {
@@ -659,8 +660,8 @@ func formatSchemaOutput(output *SchemaOutput, include string, warnings []string)
// writeTableHeader writes the single-table header line.
func writeTableHeader(sb *strings.Builder, t *TableDetail) {
- fmt.Fprintf(sb, "Table: %s (%d rows, %d columns, %d indexes, %d foreign keys)\n",
- t.Name, t.RowCount, len(t.Columns), len(t.Indexes), len(t.ForeignKeys))
+ fmt.Fprintf(sb, "Table: %s (row count estimate %d, %d columns, %d indexes, %d foreign keys)\n",
+ t.Name, t.RowCountEstimate, len(t.Columns), len(t.Indexes), len(t.ForeignKeys))
}
// writeSchemasHeader writes the multi-schema overview header lines.
diff --git a/backend/api/mcp/tool_schema_test.go b/backend/api/mcp/tool_schema_test.go
index 00c2705e64..2a7d673a4a 100644
--- a/backend/api/mcp/tool_schema_test.go
+++ b/backend/api/mcp/tool_schema_test.go
@@ -221,7 +221,12 @@ func TestGetSchema_Summary(t *testing.T) {
require.Equal(t, "users", section.Tables[1].Name)
// Summary mode has no column details but includes column count.
require.Equal(t, 2, section.Tables[0].ColumnCount)
- require.Equal(t, int64(182394), section.Tables[0].RowCount)
+ require.Equal(t, int64(182394), section.Tables[0].RowCountEstimate)
+ // Claude Code reads the structured result alone, so the key says it is an estimate.
+ serialized, err := json.Marshal(structured)
+ require.NoError(t, err)
+ require.Contains(t, string(serialized), `"rowCountEstimate":182394`)
+ require.NotContains(t, string(serialized), `"rowCount"`)
require.Empty(t, section.Tables[0].Columns)
// Views sorted alphabetically.
require.Equal(t, []string{"active_users", "recent_orders"}, section.Views)
@@ -381,6 +386,7 @@ func TestGetSchema_TableImpliesDetails(t *testing.T) {
})
require.NoError(t, err)
require.False(t, result.IsError)
+ require.Contains(t, result.Content[0].(*mcpsdk.TextContent).Text, "Table: orders (row count estimate 182394, ")
output, ok := structured.(*SchemaOutput)
require.True(t, ok)
diff --git a/backend/api/mcp/tool_search_test.go b/backend/api/mcp/tool_search_test.go
index 5d5ef3ac82..3cbd61f8f0 100644
--- a/backend/api/mcp/tool_search_test.go
+++ b/backend/api/mcp/tool_search_test.go
@@ -246,6 +246,19 @@ func TestSearchAPISchemaLookupEnum(t *testing.T) {
require.Contains(t, text, "Enum values:")
}
+// Schema mode cuts each description to its first 97 characters, so the part
+// of RolloutPolicy.roles that agents misread has to come first.
+func TestSearchAPIRolloutPolicyNamesWhoApproves(t *testing.T) {
+ profile := &config.Profile{Mode: common.ReleaseModeDev}
+ s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
+ require.NoError(t, err)
+
+ result, _, err := s.handleSearchAPI(context.Background(), nil, SearchInput{Schema: "RolloutPolicy"})
+ require.NoError(t, err)
+ text := result.Content[0].(*mcpsdk.TextContent).Text
+ require.Contains(t, text, `"roles": array<string> // Who can run, skip or cancel the environment's rollout tasks; WORKSPACE_APPROVAL sets approvers.`)
+}
+
func TestSearchAPIProtobufDescriptionTruncation(t *testing.T) {
profile := &config.Profile{Mode: common.ReleaseModeDev}
s, err := newServerWithStore(newTestServerStore(), profile, "test-secret", nil)
diff --git a/backend/generated-go/v1/org_policy_service.pb.go b/backend/generated-go/v1/org_policy_service.pb.go
index 9a0cae0cc4..774949703e 100644
--- a/backend/generated-go/v1/org_policy_service.pb.go
+++ b/backend/generated-go/v1/org_policy_service.pb.go
@@ -812,9 +812,10 @@ func (x *ReviewAIPolicy) GetContent() string {
// Rollout policy configuration.
type RolloutPolicy struct {
state protoimpl.MessageState `protogen:"open.v1"`
- // Whether rollout is automatic without manual approval.
+ // Whether the environment's rollout tasks start on their own, with no one running them.
Automatic bool `protobuf:"varint,1,opt,name=automatic,proto3" json:"automatic,omitempty"`
- // The roles that can approve rollout execution.
+ // Who can run, skip or cancel the environment's rollout tasks; WORKSPACE_APPROVAL sets approvers.
+ // Anyone with bb.taskRuns.create can too.
Roles []string `protobuf:"bytes,2,rep,name=roles,proto3" json:"roles,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
diff --git a/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts b/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts
index e6e34bd4a9..cd27903d1d 100644
--- a/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/org_policy_service_pb.d.ts
@@ -334,14 +334,15 @@ export declare const ReviewAIPolicySchema: GenMessage<ReviewAIPolicy>;
*/
export declare type RolloutPolicy = Message<"bytebase.v1.RolloutPolicy"> & {
/**
- * Whether rollout is automatic without manual approval.
+ * Whether the environment's rollout tasks start on their own, with no one running them.
*
* @generated from field: bool automatic = 1;
*/
automatic: boolean;
/**
- * The roles that can approve rollout execution.
+ * Who can run, skip or cancel the environment's rollout tasks; WORKSPACE_APPROVAL sets approvers.
+ * Anyone with bb.taskRuns.create can too.
*
* @generated from field: repeated string roles = 2;
*/
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index df22515e12..f77cc0990c 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -27492,13 +27492,15 @@ components:
automatic:
type: boolean
title: automatic
- description: Whether rollout is automatic without manual approval.
+ description: Whether the environment's rollout tasks start on their own, with no one running them.
roles:
type: array
items:
type: string
title: roles
- description: The roles that can approve rollout execution.
+ description: |-
+ Who can run, skip or cancel the environment's rollout tasks; WORKSPACE_APPROVAL sets approvers.
+ Anyone with bb.taskRuns.create can too.
title: RolloutPolicy
additionalProperties: false
description: Rollout policy configuration.
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index f558acc203..f5e7255bcf 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -10221,8 +10221,8 @@ Rollout policy configuration.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
-| automatic | [bool](#bool) | | Whether rollout is automatic without manual approval. |
-| roles | [string](#string) | repeated | The roles that can approve rollout execution. |
+| automatic | [bool](#bool) | | Whether the environment&#39;s rollout tasks start on their own, with no one running them. |
+| roles | [string](#string) | repeated | Who can run, skip or cancel the environment&#39;s rollout tasks; WORKSPACE_APPROVAL sets approvers. Anyone with bb.taskRuns.create can too. |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 2bf923e9d3..6a4c9c392a 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -29141,14 +29141,15 @@ configured storage destination such as SharePoint. </p></td>
<td>automatic</td>
<td><a href="#bool">bool</a></td>
<td></td>
- <td><p>Whether rollout is automatic without manual approval. </p></td>
+ <td><p>Whether the environment&#39;s rollout tasks start on their own, with no one running them. </p></td>
</tr>
<tr>
<td>roles</td>
<td><a href="#string">string</a></td>
<td>repeated</td>
- <td><p>The roles that can approve rollout execution. </p></td>
+ <td><p>Who can run, skip or cancel the environment&#39;s rollout tasks; WORKSPACE_APPROVAL sets approvers.
+Anyone with bb.taskRuns.create can too. </p></td>
</tr>
</tbody>
diff --git a/proto/v1/v1/org_policy_service.proto b/proto/v1/v1/org_policy_service.proto
index b1e66b28e5..b9ed5ba2e4 100644
--- a/proto/v1/v1/org_policy_service.proto
+++ b/proto/v1/v1/org_policy_service.proto
@@ -286,9 +286,10 @@ message ReviewAIPolicy {
// Rollout policy configuration.
message RolloutPolicy {
- // Whether rollout is automatic without manual approval.
+ // Whether the environment's rollout tasks start on their own, with no one running them.
bool automatic = 1;
- // The roles that can approve rollout execution.
+ // Who can run, skip or cancel the environment's rollout tasks; WORKSPACE_APPROVAL sets approvers.
+ // Anyone with bb.taskRuns.create can too.
repeated string roles = 2;
}