Skip to content

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

feat(mcp): add request_access_grant and ask Claude Code users before access grants and exemptions (#21643)

Vincent Huang99aa56b6dffd
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
index 56f6c348c9..6089ce75c8 100644
--- a/backend/api/mcp/server.go
+++ b/backend/api/mcp/server.go
@@ -238,9 +238,20 @@ func (s *Server) registerTools() {
s.registerDecideIssueTool()
s.registerSetJustInTimeAccessTool()
s.registerMaskingExemptionTools()
+ s.registerRequestAccessGrantTool()
s.registerReauthorizeTool()
}
+// requiresUserInteraction marks a tool whose every call Claude Code shows its
+// user in a permission prompt, even in auto and bypassPermissions modes and
+// despite allow rules. In dontAsk mode, and through --permission-prompt-tool,
+// Claude Code denies the call instead
+// (https://code.claude.com/docs/en/mcp#require-approval-for-a-specific-tool).
+// Other clients ignore the key.
+func requiresUserInteraction() mcp.Meta {
+ return mcp.Meta{"anthropic/requiresUserInteraction": true}
+}
+
// authMiddleware validates OAuth2 bearer tokens for MCP requests.
//
// On 401, it emits an RFC 9728 / MCP-authorization-spec compliant
diff --git a/backend/api/mcp/tool_access_request.go b/backend/api/mcp/tool_access_request.go
new file mode 100644
index 0000000000..d5058ca311
--- /dev/null
+++ b/backend/api/mcp/tool_access_request.go
@@ -0,0 +1,146 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"
+)
+
+// RequestAccessGrantInput is the input for the request_access_grant tool.
+type RequestAccessGrantInput struct {
+ Database string `json:"database"`
+ Statement string `json:"statement"`
+ Schema string `json:"schema,omitempty"`
+ Container string `json:"container,omitempty"`
+ Unmask bool `json:"unmask,omitempty"`
+ Export bool `json:"export,omitempty"`
+ Reason string `json:"reason"`
+ // An int32 gives the input schema a maximum, so the seconds computed from
+ // it fit in an int64.
+ DurationHours int32 `json:"durationHours"`
+}
+
+// RequestAccessGrantOutput is the output for the request_access_grant tool.
+type RequestAccessGrantOutput struct {
+ AccessGrant string `json:"accessGrant"`
+ Issue string `json:"issue"`
+ DurationHours int32 `json:"durationHours"`
+ Link string `json:"link"`
+}
+
+const requestAccessGrantDescription = `Request an access grant: time-boxed permission to run one read-only statement on one Bytebase database, optionally with results unmasked or exported. A person approves the request in Bytebase before it takes effect.
+
+| Parameter | Required | Description |
+|---------------|----------|-------------|
+| database | Yes | Full database name, as query_database prints it after "Database:", e.g. "projects/hr/instances/prod/databases/hr" |
+| statement | Yes | One read-only statement; the grant applies to this exact statement |
+| schema | No | Default schema for unqualified names; the rerun must pass the same one |
+| container | No | CosmosDB container; the rerun must pass the same one |
+| unmask | No | true to return masked columns unmasked |
+| export | No | true to allow exporting the results |
+| reason | Yes | Why the access is needed; the approver reads it |
+| durationHours | Yes | Hours of access, counted from approval. The SQL Editor offers 1, 4, 24 and 168; the workspace maximum applies |
+
+The project must allow just-in-time access. Check allowJustInTimeAccess with call_api(operationId="ProjectService/GetProject") first; a missing field means off, and set_just_in_time_access turns it on.
+
+Clients such as Claude Code ask the user to approve each call of this tool, so do not ask in chat first. Once the request is approved, rerun the statement unchanged with query_database, with the same schema and container; appliedAccessGrant in its result names the grant that applied. To use an export grant, pass the statement the same way to call_api(operationId="SQLService/Export"); query_database returns at most 1000 rows.`
+
+func (s *Server) registerRequestAccessGrantTool() {
+ mcp.AddTool(s.mcpServer, &mcp.Tool{
+ Name: "request_access_grant",
+ Description: requestAccessGrantDescription,
+ Meta: requiresUserInteraction(),
+ }, s.handleRequestAccessGrant)
+}
+
+func (s *Server) handleRequestAccessGrant(ctx context.Context, _ *mcp.CallToolRequest, input RequestAccessGrantInput) (*mcp.CallToolResult, any, error) {
+ if input.DurationHours < 1 {
+ return formatToolError(&toolError{
+ Code: "INVALID_ARGUMENT",
+ Message: fmt.Sprintf("invalid durationHours %d: it must be at least 1", input.DurationHours),
+ Suggestion: "pass the hours of access the user needs, counted from approval, e.g. 4",
+ }), nil, nil
+ }
+ // The request's parent is the database's project, which the name of a
+ // database on a workspace instance does not carry.
+ var database struct {
+ Project string `json:"project"`
+ }
+ if err := s.readResource(ctx, v1connect.DatabaseServiceGetDatabaseProcedure, input.Database, "get databases", "bb.databases.get", &database); err != nil {
+ return formatToolError(err), nil, nil
+ }
+ resp, err := s.apiRequest(ctx, v1connect.AccessGrantServiceCreateAccessGrantProcedure, accessGrantBody(database.Project, input))
+ if err != nil {
+ return formatToolError(errors.Wrapf(err, "failed to request access to %s", input.Database)), nil, nil
+ }
+ if err := checkAPIResponse(resp, "request access grants", "bb.accessGrants.create"); err != nil {
+ return formatToolError(err), nil, nil
+ }
+ var grant struct {
+ Name string `json:"name"`
+ Issue string `json:"issue"`
+ }
+ if err := json.Unmarshal(resp.Body, &grant); err != nil {
+ return formatToolError(errors.Wrapf(err, "requested access to %s, but the response could not be read", input.Database)), nil, nil
+ }
+ link := s.issueLink(ctx, grant.Issue)
+ output := &RequestAccessGrantOutput{
+ AccessGrant: grant.Name,
+ Issue: grant.Issue,
+ DurationHours: input.DurationHours,
+ Link: link,
+ }
+ return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf(
+ "Requested %s: %s for %s from approval. A person approves it in Bytebase before it takes effect.\nIssue: %s\n%s",
+ grant.Name, describeRequestedAccess(input), hours(input.DurationHours), link, useAfterApproval(input.Export))}}}, output, nil
+}
+
+// useAfterApproval says how to run the statement once the grant applies. Only
+// SQLService/Export uses a grant's export, and query_database caps its rows.
+func useAfterApproval(export bool) string {
+ if export {
+ return fmt.Sprintf(`Once it is approved, pass the statement unchanged, with the same schema and container, to call_api(operationId="SQLService/Export") to export the results, or to query_database to read up to %d rows.`, maxQueryLimit)
+ }
+ return "Once it is approved, rerun the statement unchanged with query_database, with the same schema and container."
+}
+
+func hours(n int32) string {
+ if n == 1 {
+ return "1 hour"
+ }
+ return fmt.Sprintf("%d hours", n)
+}
+
+// accessGrantBody is the CreateAccessGrant request. A ttl, unlike an
+// expire_time, starts when the request is approved.
+func accessGrantBody(project string, input RequestAccessGrantInput) map[string]any {
+ return map[string]any{
+ "parent": project,
+ "accessGrant": map[string]any{
+ "targets": []string{input.Database},
+ "query": input.Statement,
+ "schema": input.Schema,
+ "container": input.Container,
+ "unmask": input.Unmask,
+ "export": input.Export,
+ "reason": input.Reason,
+ "ttl": fmt.Sprintf("%ds", int64(input.DurationHours)*3600),
+ },
+ }
+}
+
+func describeRequestedAccess(input RequestAccessGrantInput) string {
+ access := "run the statement on " + input.Database
+ if input.Unmask {
+ access += ", unmasked"
+ }
+ if input.Export {
+ access += ", with export"
+ }
+ return access
+}
diff --git a/backend/api/mcp/tool_access_request_test.go b/backend/api/mcp/tool_access_request_test.go
new file mode 100644
index 0000000000..0f72dd8232
--- /dev/null
+++ b/backend/api/mcp/tool_access_request_test.go
@@ -0,0 +1,292 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "math"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/labstack/echo/v5"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"
+)
+
+// accessGrantMock is the internal API behind request_access_grant: the
+// database read, and the request, recorded as sent.
+type accessGrantMock struct {
+ mu sync.Mutex
+ // project is the project GetDatabase reports.
+ project string
+ // readStatus and readRefusal, when set, are how GetDatabase is refused.
+ readStatus int
+ readRefusal map[string]any
+ // refusalStatus and refusal, when set, are how the request is refused.
+ refusalStatus int
+ refusal map[string]any
+ reads []string
+ requests []map[string]any
+}
+
+func (m *accessGrantMock) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ reply := func(v any) { _ = json.NewEncoder(w).Encode(v) }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ switch r.URL.Path {
+ case v1connect.DatabaseServiceGetDatabaseProcedure:
+ var body struct {
+ Name string `json:"name"`
+ }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ m.reads = append(m.reads, body.Name)
+ if m.readRefusal != nil {
+ w.WriteHeader(m.readStatus)
+ reply(m.readRefusal)
+ return
+ }
+ reply(map[string]any{"name": body.Name, "project": m.project})
+ case v1connect.AccessGrantServiceCreateAccessGrantProcedure:
+ var body map[string]any
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ m.requests = append(m.requests, body)
+ if m.refusal != nil {
+ w.WriteHeader(m.refusalStatus)
+ reply(m.refusal)
+ return
+ }
+ reply(map[string]any{"name": "projects/hr/accessGrants/g1", "status": "PENDING", "issue": "projects/hr/issues/7"})
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+}
+
+func (m *accessGrantMock) calls() (reads []string, requests []map[string]any) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return append([]string(nil), m.reads...), append([]map[string]any(nil), m.requests...)
+}
+
+func connectToAccessGrantServer(t *testing.T, mock *accessGrantMock) *mcp.ClientSession {
+ 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)
+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-write", time.Hour)
+ return connectLegacy(t, ts.URL+mcpResourcePath, token, nil)
+}
+
+func callRequestAccessGrant(t *testing.T, session *mcp.ClientSession, arguments map[string]any) *mcp.CallToolResult {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ res, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "request_access_grant", Arguments: arguments})
+ require.NoError(t, err)
+ return res
+}
+
+func TestRequestAccessGrantFilesTheRequest(t *testing.T) {
+ mock := &accessGrantMock{project: "projects/hr"}
+ session := connectToAccessGrantServer(t, mock)
+
+ res := callRequestAccessGrant(t, session, map[string]any{
+ "database": "projects/hr/instances/prod/databases/hr",
+ "statement": "SELECT first_name, last_name FROM employee",
+ "schema": "public",
+ "container": "employees",
+ "unmask": true,
+ "export": true,
+ "reason": "Compensation review",
+ "durationHours": 4,
+ })
+ require.False(t, res.IsError, resultText(t, res))
+
+ reads, requests := mock.calls()
+ require.Equal(t, []string{"projects/hr/instances/prod/databases/hr"}, reads)
+ require.Len(t, requests, 1)
+ require.Equal(t, map[string]any{
+ "parent": "projects/hr",
+ "accessGrant": map[string]any{
+ "targets": []any{"projects/hr/instances/prod/databases/hr"},
+ "query": "SELECT first_name, last_name FROM employee",
+ "schema": "public",
+ "container": "employees",
+ "unmask": true,
+ "export": true,
+ "reason": "Compensation review",
+ "ttl": "14400s",
+ },
+ }, requests[0], "the request names the database as given, sends no creator, and asks for a duration that starts at approval")
+
+ require.Equal(t, "Requested projects/hr/accessGrants/g1: run the statement on projects/hr/instances/prod/databases/hr, unmasked, with export for 4 hours from approval. "+
+ "A person approves it in Bytebase before it takes effect.\n"+
+ "Issue: https://bb.example.com/projects/hr/issues/7\n"+
+ `Once it is approved, pass the statement unchanged, with the same schema and container, to call_api(operationId="SQLService/Export") to export the results, or to query_database to read up to 1000 rows.`, resultText(t, res))
+ output, err := json.Marshal(res.StructuredContent)
+ require.NoError(t, err)
+ require.JSONEq(t, `{"accessGrant":"projects/hr/accessGrants/g1","issue":"projects/hr/issues/7",
+ "durationHours":4,"link":"https://bb.example.com/projects/hr/issues/7"}`, string(output))
+}
+
+func TestRequestAccessGrantFilesInTheDatabaseProject(t *testing.T) {
+ mock := &accessGrantMock{project: "projects/finance"}
+ session := connectToAccessGrantServer(t, mock)
+
+ res := callRequestAccessGrant(t, session, map[string]any{
+ "database": "instances/prod/databases/ledger",
+ "statement": "SELECT 1",
+ "unmask": true,
+ "reason": "Quarter close",
+ "durationHours": 1,
+ })
+ require.False(t, res.IsError, resultText(t, res))
+
+ _, requests := mock.calls()
+ require.Len(t, requests, 1)
+ require.Equal(t, "projects/finance", requests[0]["parent"], "a workspace instance's database name carries no project")
+ require.Equal(t, "3600s", requests[0]["accessGrant"].(map[string]any)["ttl"])
+ require.Contains(t, resultText(t, res), "run the statement on instances/prod/databases/ledger, unmasked for 1 hour from approval")
+ require.Contains(t, resultText(t, res), "Once it is approved, rerun the statement unchanged with query_database, with the same schema and container.")
+}
+
+func TestRequestAccessGrantRefusesADurationBeforeAnyCall(t *testing.T) {
+ for name, tt := range map[string]struct {
+ durationHours int64
+ want string
+ }{
+ "no duration": {0, "invalid durationHours 0"},
+ "a negative duration": {-2, "invalid durationHours -2"},
+ "a duration past the input schema's maximum": {math.MaxInt32 + 1, "validating /properties/durationHours: maximum"},
+ } {
+ t.Run(name, func(t *testing.T) {
+ mock := &accessGrantMock{project: "projects/hr"}
+ session := connectToAccessGrantServer(t, mock)
+
+ res := callRequestAccessGrant(t, session, map[string]any{
+ "database": "projects/hr/instances/prod/databases/hr",
+ "statement": "SELECT 1",
+ "reason": "a look",
+ "durationHours": tt.durationHours,
+ })
+ require.True(t, res.IsError)
+ require.Contains(t, resultText(t, res), tt.want)
+ reads, requests := mock.calls()
+ require.Empty(t, reads)
+ require.Empty(t, requests)
+ })
+ }
+}
+
+func TestRequestAccessGrantFilesNothingWhenTheDatabaseReadFails(t *testing.T) {
+ // GetDatabase's own answer to a name that is not a full database name.
+ malformed := `failed to parse "hr_test": invalid request "hr_test"`
+ mock := &accessGrantMock{
+ readStatus: http.StatusBadRequest,
+ readRefusal: map[string]any{"code": "invalid_argument", "message": malformed},
+ }
+ session := connectToAccessGrantServer(t, mock)
+
+ res := callRequestAccessGrant(t, session, map[string]any{
+ "database": "hr_test",
+ "statement": "SELECT 1",
+ "reason": "a look",
+ "durationHours": 4,
+ })
+ require.True(t, res.IsError)
+ require.Contains(t, resultText(t, res), malformed)
+ reads, requests := mock.calls()
+ require.Equal(t, []string{"hr_test"}, reads)
+ require.Empty(t, requests)
+}
+
+func TestRequestAccessGrantPassesPermissionDenialsThrough(t *testing.T) {
+ for name, tt := range map[string]struct {
+ message string
+ suggestion string
+ }{
+ "a request no person would approve": {
+ "/bytebase.v1.AccessGrantService/CreateAccessGrant is not available to MCP sessions for this request because no approval rule requires a person to approve it, " +
+ "so the access would be granted at once with no human step. Ask a workspace admin to give access requests " +
+ "an approval rule that names an approver, or request the access in the Bytebase console.",
+ "",
+ },
+ "a missing permission": {
+ `permission denied for method "/bytebase.v1.AccessGrantService/CreateAccessGrant", user does not have permission "bb.accessGrants.create", extra map[]`,
+ "ask your workspace admin to grant you the bb.accessGrants.create permission",
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ mock := &accessGrantMock{
+ project: "projects/hr",
+ refusalStatus: http.StatusForbidden,
+ refusal: map[string]any{"code": "permission_denied", "message": tt.message},
+ }
+ session := connectToAccessGrantServer(t, mock)
+
+ res := callRequestAccessGrant(t, session, map[string]any{
+ "database": "projects/hr/instances/prod/databases/hr",
+ "statement": "SELECT 1",
+ "reason": "a look",
+ "durationHours": 4,
+ })
+ require.True(t, res.IsError)
+ var denial toolError
+ require.NoError(t, json.Unmarshal([]byte(resultText(t, res)), &denial))
+ require.Equal(t, toolError{Code: "PERMISSION_DENIED", Message: tt.message, Suggestion: tt.suggestion}, denial)
+ })
+ }
+}
+
+func TestRequestAccessGrantReportsTheAPIRefusal(t *testing.T) {
+ jitOff := `just-in-time access is off for project "hr", so an access grant there would not apply; ` +
+ `a project owner can turn on "Allow access grants" in the project settings`
+ mock := &accessGrantMock{
+ project: "projects/hr",
+ refusalStatus: http.StatusBadRequest,
+ refusal: map[string]any{"code": "failed_precondition", "message": jitOff},
+ }
+ session := connectToAccessGrantServer(t, mock)
+
+ res := callRequestAccessGrant(t, session, map[string]any{
+ "database": "projects/hr/instances/prod/databases/hr",
+ "statement": "SELECT 1",
+ "reason": "a look",
+ "durationHours": 4,
+ })
+ require.True(t, res.IsError)
+ require.Contains(t, resultText(t, res), jitOff)
+}
+
+func TestOnlyTheGrantingToolsRequireUserInteraction(t *testing.T) {
+ session := connectToAccessGrantServer(t, &accessGrantMock{})
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ listed, err := session.ListTools(ctx, &mcp.ListToolsParams{})
+ require.NoError(t, err)
+
+ var names, flagged []string
+ for _, tool := range listed.Tools {
+ names = append(names, tool.Name)
+ if required, ok := tool.Meta["anthropic/requiresUserInteraction"].(bool); ok && required {
+ flagged = append(flagged, tool.Name)
+ }
+ }
+ slices.Sort(names)
+ require.Equal(t, []string{
+ "call_api", "decide_issue", "get_schema", "get_skill", "grant_masking_exemption", "propose_database_change",
+ "query_database", "reauthorize", "request_access_grant", "revoke_masking_exemption", "search_api", "set_just_in_time_access",
+ }, names)
+ require.ElementsMatch(t, []string{"request_access_grant", "grant_masking_exemption"}, flagged)
+}
diff --git a/backend/api/mcp/tool_exemption.go b/backend/api/mcp/tool_exemption.go
index cbf7c3f622..ae7aaaab48 100644
--- a/backend/api/mcp/tool_exemption.go
+++ b/backend/api/mcp/tool_exemption.go
@@ -27,15 +27,15 @@ import (
// GrantMaskingExemptionInput is the input for the grant_masking_exemption tool.
type GrantMaskingExemptionInput struct {
- Project string `json:"project"`
- Member string `json:"member"`
- Database string `json:"database,omitempty"`
- AllDatabases bool `json:"allDatabases,omitempty"`
- Schema string `json:"schema,omitempty"`
- Table string `json:"table,omitempty"`
- Column string `json:"column,omitempty"`
- ExpireTime string `json:"expireTime,omitempty"`
- Reason string `json:"reason,omitempty"`
+ Project string `json:"project"`
+ Member string `json:"member"`
+ Database string `json:"database,omitempty"`
+ AllDatabases bool `json:"allDatabases,omitempty"`
+ Schema string `json:"schema,omitempty"`
+ Table string `json:"table,omitempty"`
+ Columns []string `json:"columns,omitempty"`
+ ExpireTime string `json:"expireTime,omitempty"`
+ Reason string `json:"reason,omitempty"`
}
// RevokeMaskingExemptionInput is the input for the revoke_masking_exemption tool.
@@ -53,7 +53,7 @@ type MaskingExemptionOutput struct {
Link string `json:"link"`
}
-const grantMaskingExemptionDescription = `Exempt one member from data masking in a Bytebase project, for one database (optionally one schema, table or column) or for every database in the project. The user confirms the exemption in this client first.
+const grantMaskingExemptionDescription = `Exempt one member from data masking in a Bytebase project, for one database (optionally one schema, table, or columns of one table) or for every database in the project. The user confirms the exemption in this client first.
| Parameter | Required | Description |
|--------------|----------|-------------|
@@ -63,13 +63,13 @@ const grantMaskingExemptionDescription = `Exempt one member from data masking in
| allDatabases | One of | true for every database in the project, current and future |
| schema | No | Narrow to one schema (needs database) |
| table | No | Narrow to one table (needs database) |
-| column | No | Narrow to one column (needs table) |
+| columns | No | Narrow to these columns of the table, e.g. ["first_name", "last_name"] (needs table) |
| 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 (AccessGrantService/CreateAccessGrant).
+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.
-The tool adds one exemption and leaves every other entry as it is. 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.
+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.
The same permissions apply as in the console. This and revoke_masking_exemption are the only ways to change exemptions over MCP; call_api refuses OrgPolicyService/UpdatePolicy.`
@@ -89,6 +89,7 @@ func (s *Server) registerMaskingExemptionTools() {
mcp.AddTool(s.mcpServer, &mcp.Tool{
Name: "grant_masking_exemption",
Description: grantMaskingExemptionDescription,
+ Meta: requiresUserInteraction(),
}, s.handleGrantMaskingExemption)
mcp.AddTool(s.mcpServer, &mcp.Tool{
Name: "revoke_masking_exemption",
@@ -114,9 +115,11 @@ func maskingExemptionPolicyName(project string) string {
// exemptionGrant is a validated grant_masking_exemption request.
type exemptionGrant struct {
- project, member string
- database, instanceID, databaseName string
- schema, table, column, expireTime, note string
+ project, member string
+ database, instanceID, databaseName string
+ schema, table string
+ columns []string
+ expireTime, note string
}
func parseExemptionGrant(input GrantMaskingExemptionInput) (*exemptionGrant, error) {
@@ -132,7 +135,7 @@ func parseExemptionGrant(input GrantMaskingExemptionInput) (*exemptionGrant, err
}
g := &exemptionGrant{
project: input.Project, member: input.Member,
- schema: input.Schema, table: input.Table, column: input.Column, note: input.Reason,
+ schema: input.Schema, table: input.Table, columns: input.Columns, note: input.Reason,
}
switch {
case input.Database != "" && input.AllDatabases:
@@ -148,12 +151,12 @@ func parseExemptionGrant(input GrantMaskingExemptionInput) (*exemptionGrant, err
}
g.database, g.instanceID, g.databaseName = input.Database, instanceID, databaseName
default:
- if input.Schema != "" || input.Table != "" || input.Column != "" {
- return nil, invalid("schema, table and column narrow one database, so they need database", "")
+ if input.Schema != "" || input.Table != "" || len(input.Columns) > 0 {
+ return nil, invalid("schema, table and columns narrow one database, so they need database", "")
}
}
- if input.Column != "" && input.Table == "" {
- return nil, invalid("column needs table", "pass the table the column belongs to")
+ if len(input.Columns) > 0 && input.Table == "" {
+ return nil, invalid("columns need table", "pass the table the columns belong to")
}
if input.ExpireTime != "" {
expireTime, err := time.Parse(time.RFC3339, input.ExpireTime)
@@ -200,12 +203,16 @@ func (g *exemptionGrant) condition() string {
for _, narrowing := range []struct{ attribute, value string }{
{"resource.schema_name", g.schema},
{"resource.table_name", g.table},
- {"resource.column_name", g.column},
} {
if narrowing.value != "" {
scope = append(scope, narrowing.attribute+" == "+strconv.Quote(narrowing.value))
}
}
+ if len(g.columns) == 1 {
+ scope = append(scope, "resource.column_name == "+strconv.Quote(g.columns[0]))
+ } else if len(g.columns) > 1 {
+ scope = append(scope, "resource.column_name in ["+quoteAll(g.columns)+"]")
+ }
parts = append(parts, "("+strings.Join(scope, " && ")+")")
}
return strings.Join(parts, " && ")
@@ -471,12 +478,12 @@ func describeExemptionGrant(ctx context.Context, g *exemptionGrant) string {
// comes before it, where a cut keeps the broader reading.
func describeNarrowing(g *exemptionGrant) string {
switch {
- case g.schema == "" && g.column != "":
- return fmt.Sprintf("any schema, column %q in %q", g.column, g.table)
+ case g.schema == "" && len(g.columns) > 0:
+ return "any schema, " + describeColumns(g.columns, strconv.Quote(g.table))
case g.schema == "" && g.table != "":
return fmt.Sprintf("any schema, table %q", g.table)
- case g.column != "":
- return fmt.Sprintf("column %q in %q.%q", g.column, g.schema, g.table)
+ case len(g.columns) > 0:
+ return describeColumns(g.columns, fmt.Sprintf("%q.%q", g.schema, g.table))
case g.table != "":
return fmt.Sprintf("table %q.%q", g.schema, g.table)
case g.schema != "":
@@ -486,6 +493,15 @@ func describeNarrowing(g *exemptionGrant) string {
}
}
+// describeColumns names the columns in table. Several columns are counted
+// before they are named, so a cut line still shows how many the grant covers.
+func describeColumns(columns []string, table string) string {
+ if len(columns) == 1 {
+ return fmt.Sprintf("column %q in %s", columns[0], table)
+ }
+ return fmt.Sprintf("%d columns in %s: %s", len(columns), table, quoteAll(columns))
+}
+
// describeExemptionRevoke builds the revoke's confirmation message.
func describeExemptionRevoke(ctx context.Context, input RevokeMaskingExemptionInput, matched int) string {
question := fmt.Sprintf("Revoke masking exemption: %q", input.Member)
diff --git a/backend/api/mcp/tool_exemption_test.go b/backend/api/mcp/tool_exemption_test.go
index 441dd23721..194cd88400 100644
--- a/backend/api/mcp/tool_exemption_test.go
+++ b/backend/api/mcp/tool_exemption_test.go
@@ -141,7 +141,7 @@ func writtenExemptions(t *testing.T, call decisionCall) []any {
func salaryGrant() map[string]any {
return map[string]any{
"project": "projects/hr", "member": "user:[email protected]", "database": "instances/prod/databases/hr",
- "schema": "public", "table": "employee", "column": "salary",
+ "schema": "public", "table": "employee", "columns": []string{"salary"},
"expireTime": "2026-10-27T00:00:00Z", "reason": "payroll audit",
}
}
@@ -241,9 +241,10 @@ func TestGrantMaskingExemptionSaysWhenATableIsInAnySchema(t *testing.T) {
arguments map[string]any
want string
}{
- "a table": {map[string]any{"table": "employee"}, `Database "hr", any schema, table "employee"`},
- "a column": {map[string]any{"table": "employee", "column": "salary"}, `Database "hr", any schema, column "salary" in "employee"`},
- "a schema": {map[string]any{"schema": "public"}, `Database "hr", schema "public"`},
+ "a table": {map[string]any{"table": "employee"}, `Database "hr", any schema, table "employee"`},
+ "a column": {map[string]any{"table": "employee", "columns": []string{"salary"}}, `Database "hr", any schema, column "salary" in "employee"`},
+ "two columns": {map[string]any{"table": "employee", "columns": []string{"first_name", "last_name"}}, `Database "hr", any schema, 2 columns in "employee": "first_name", "last_name"`},
+ "a schema": {map[string]any{"schema": "public"}, `Database "hr", schema "public"`},
} {
t.Run(name, func(t *testing.T) {
mock := &policyMock{databaseProject: "projects/hr"}
@@ -260,6 +261,25 @@ func TestGrantMaskingExemptionSaysWhenATableIsInAnySchema(t *testing.T) {
}
}
+func TestGrantMaskingExemptionCoversSeveralColumnsInOneEntry(t *testing.T) {
+ mock := &policyMock{databaseProject: "projects/hr"}
+ user := &asker{answer: confirmAnswer(true)}
+ session := connectToPolicyServer(t, mock, &mcp.ClientOptions{ElicitationHandler: user.handle})
+
+ grant := salaryGrant()
+ grant["columns"] = []string{"first_name", "last_name"}
+ res := callExemptionTool(t, session, "grant_masking_exemption", grant)
+ require.False(t, res.IsError, resultText(t, res))
+ require.Equal(t, int32(1), user.asked.Load())
+ require.Contains(t, user.lastParams(t).Message, "\n"+`Database "hr", 2 columns in "public"."employee": "first_name", "last_name"`+"\n")
+ calls := mock.calls()
+ require.Len(t, calls, 1)
+ require.Equal(t, map[string]any{
+ "expression": `request.time < timestamp("2026-10-27T00:00:00.000Z") && (resource.instance_id == "prod" && resource.database_name == "hr" && resource.schema_name == "public" && resource.table_name == "employee" && resource.column_name in ["first_name", "last_name"])`,
+ "description": "payroll audit",
+ }, writtenExemptions(t, calls[0])[0].(map[string]any)["condition"], "the columns are one entry, in the list form the console writes")
+}
+
func TestGrantMaskingExemptionForEveryDatabaseIsExplicit(t *testing.T) {
mock := &policyMock{}
user := &asker{answer: confirmAnswer(true)}
@@ -308,7 +328,7 @@ func TestGrantMaskingExemptionRefusesBadArguments(t *testing.T) {
"no scope": {base, "needs a scope: database, or allDatabases set to true"},
"both scopes": {with(map[string]any{"database": "instances/prod/databases/hr", "allDatabases": true}), "not both"},
"narrowing without one": {with(map[string]any{"allDatabases": true, "table": "employee"}), "they need database"},
- "column without table": {with(map[string]any{"database": "instances/prod/databases/hr", "column": "salary"}), "column needs table"},
+ "columns without table": {with(map[string]any{"database": "instances/prod/databases/hr", "columns": []string{"salary"}}), "columns need table"},
"a malformed time": {with(map[string]any{"allDatabases": true, "expireTime": "next week"}), "invalid expireTime"},
"a malformed database": {with(map[string]any{"database": "hr"}), "invalid database"},
"no member": {map[string]any{"project": "projects/hr", "member": " ", "allDatabases": true}, "invalid member"},
@@ -371,7 +391,7 @@ func TestMaskingExemptionToolsBindTheAnswerToTheArguments(t *testing.T) {
first := call("grant_masking_exemption", salaryGrant(), nil, "")
require.True(t, first.NeedsInput())
wider := salaryGrant()
- delete(wider, "column")
+ delete(wider, "columns")
stale := call("grant_masking_exemption", wider, accept, first.RequestState)
require.True(t, stale.IsError, resultText(t, stale))
require.Contains(t, resultText(t, stale), "STALE_CONFIRMATION", "an answer resent with a wider scope is not what the user confirmed")
@@ -521,6 +541,10 @@ func TestRevokeMaskingExemptionShowsTheScopeBeforeTheExpiry(t *testing.T) {
`Condition "resource.instance_id == \"prod\" && resource.database_name == \"hr\"", until "2026-10-27T00:00:00.000Z"`,
},
"an expiry only": {`request.time < timestamp("2026-10-27T00:00:00.000Z")`, `Condition "" (all databases), until "2026-10-27T00:00:00.000Z"`},
+ "a column list": {
+ `request.time < timestamp("2026-10-27T00:00:00.000Z") && (resource.table_name == "employee" && resource.column_name in ["first_name", "last_name"])`,
+ `Condition "resource.table_name == \"employee\" && resource.column_name in [\"first_name\", \"last_name\"]", until "2026-10-27T00:00:00.000Z"`,
+ },
"an expiry last": {
`resource.database_name == "hr" && request.time < timestamp("2026-10-27T00:00:00.000Z")`,
`Condition "resource.database_name == \"hr\" && request.time < timestamp(\"2026-10-27T00:00:00.000Z\")"`,
@@ -598,7 +622,7 @@ func TestMaskingExemptionFormsShowTheScopeInClaudeCodesDialog(t *testing.T) {
for _, columns := range []int{80, 120} {
t.Run(fmt.Sprintf("%d columns", columns), func(t *testing.T) {
member := "serviceAccount:[email protected]"
- view := grantView(&exemptionGrant{project: "projects/hr", member: member, database: "d", instanceID: longest, databaseName: longest, table: "t", column: "c"}, columns)
+ view := grantView(&exemptionGrant{project: "projects/hr", member: member, database: "d", instanceID: longest, databaseName: longest, table: "t", columns: []string{"c"}}, columns)
require.Len(t, view, 4, "%q", view)
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")
diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.go
index 628ae5a330..c625d6c0de 100644
--- a/backend/api/mcp/tool_query.go
+++ b/backend/api/mcp/tool_query.go
@@ -81,7 +81,7 @@ query_database(database="employee", instance="projects/hr/instances/prod-pg", st
**Notes:**
- Masked data: masking replaces a value fully (by default "******"), partly (e.g. "**rn**"), or with a hash. maskedColumns in the result names each masked column and why (not reported for MongoDB, CosmosDB or Elasticsearch). A masked value is a placeholder, not a value anything holds, so never write it back and never filter on it. Any statement containing "******" is refused. When showing a partly masked value, wrap it in backticks: "**rn**" renders as bold Markdown.
-- Seeing masked values: the user can ask a project owner for a masking exemption, or, if the project allows just-in-time access, request an access grant with Unmask for this exact statement, schema and container. In a Read-write session, file the request with call_api(operationId="AccessGrantService/CreateAccessGrant"); otherwise the user requests it in the SQL Editor. 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.
+- 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.
`
func (s *Server) registerQueryTool() {
diff --git a/backend/api/v1/masking_evaluator_test.go b/backend/api/v1/masking_evaluator_test.go
index 853ab438c3..1bf2b5fc0c 100644
--- a/backend/api/v1/masking_evaluator_test.go
+++ b/backend/api/v1/masking_evaluator_test.go
@@ -182,6 +182,68 @@ func TestEvalMaskingLevelOfColumn(t *testing.T) {
want: "",
},
+ {
+ description: "Respect An Exception That Lists The Column",
+ databaseMessage: defaultDatabaseMessage,
+ schemaName: "hiring",
+ tableName: "employees",
+ columnName: "salary",
+ columnCatalog: &storepb.ColumnCatalog{
+ Classification: "1-1-1",
+ },
+ maskingRulePolicy: &storepb.MaskingRulePolicy{
+ Rules: []*storepb.MaskingRulePolicy_MaskingRule{
+ {
+ Condition: &expr.Expr{Expression: `resource.classification_level == 2`},
+ SemanticType: "default",
+ },
+ },
+ },
+ filteredMaskingExemptions: []*storepb.MaskingExemptionPolicy_Exemption{
+ {
+ Condition: &expr.Expr{
+ Expression: `(resource.instance_id == "neon-host" && resource.database_name == "bb" && resource.schema_name == "hiring" && resource.table_name == "employees" && resource.column_name in ["bonus", "salary"])`,
+ },
+ Members: []string{"users/1234"},
+ },
+ },
+ dataClassification: defaultClassification,
+ databaseProjectDatabaseClassificationID: defaultProjectDatabaseDataClassificationID,
+
+ want: "",
+ },
+ {
+ description: "An Exception That Lists Other Columns",
+ databaseMessage: defaultDatabaseMessage,
+ schemaName: "hiring",
+ tableName: "employees",
+ columnName: "salary",
+ columnCatalog: &storepb.ColumnCatalog{
+ Classification: "1-1-1",
+ },
+ maskingRulePolicy: &storepb.MaskingRulePolicy{
+ Rules: []*storepb.MaskingRulePolicy_MaskingRule{
+ {
+ Condition: &expr.Expr{Expression: `resource.classification_level == 2`},
+ SemanticType: "default",
+ },
+ },
+ },
+ filteredMaskingExemptions: []*storepb.MaskingExemptionPolicy_Exemption{
+ {
+ Condition: &expr.Expr{
+ Expression: `(resource.instance_id == "neon-host" && resource.database_name == "bb" && resource.schema_name == "hiring" && resource.table_name == "employees" && resource.column_name in ["bonus", "commission"])`,
+ },
+ Members: []string{"users/1234"},
+ },
+ },
+ dataClassification: defaultClassification,
+ databaseProjectDatabaseClassificationID: defaultProjectDatabaseDataClassificationID,
+
+ want: "default",
+ wantAlgorithm: "Full mask",
+ wantClassLevel: 2,
+ },
{
description: "Exemption By Classification Level",
databaseMessage: defaultDatabaseMessage,
diff --git a/backend/api/v1/mcp_gate.go b/backend/api/v1/mcp_gate.go
index 83d8eda346..226f73231a 100644
--- a/backend/api/v1/mcp_gate.go
+++ b/backend/api/v1/mcp_gate.go
@@ -582,7 +582,7 @@ func grantIssueRefusal(issueType v1pb.Issue_Type) (reason, wayOut string) {
case v1pb.Issue_ACCESS_GRANT:
reason = fmt.Sprintf("an ACCESS_GRANT issue is filed by %s, not created directly",
v1connect.AccessGrantServiceCreateAccessGrantProcedure)
- return reason, "Request the access with that method instead"
+ return reason, "Request the access with the request_access_grant tool instead"
default:
return fmt.Sprintf(
"a %v issue completes on creation whenever the workspace approval rule produces no template, "+
diff --git a/backend/api/v1/mcp_gate_test.go b/backend/api/v1/mcp_gate_test.go
index 379dcd70ee..9c463719c3 100644
--- a/backend/api/v1/mcp_gate_test.go
+++ b/backend/api/v1/mcp_gate_test.go
@@ -1248,9 +1248,12 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {
require.True(t, got.dispatched)
})
- for issueType, tt := range map[v1pb.Issue_Type]struct{ wayOut, notWayOut string }{
- v1pb.Issue_ROLE_GRANT: {mcpConsoleWayOut, v1connect.AccessGrantServiceCreateAccessGrantProcedure},
- v1pb.Issue_ACCESS_GRANT: {v1connect.AccessGrantServiceCreateAccessGrantProcedure, mcpConsoleWayOut},
+ for issueType, tt := range map[v1pb.Issue_Type]struct {
+ wayOut []string
+ notWayOut string
+ }{
+ v1pb.Issue_ROLE_GRANT: {[]string{mcpConsoleWayOut}, v1connect.AccessGrantServiceCreateAccessGrantProcedure},
+ v1pb.Issue_ACCESS_GRANT: {[]string{v1connect.AccessGrantServiceCreateAccessGrantProcedure, "request_access_grant"}, mcpConsoleWayOut},
} {
t.Run("CreateIssue refuses "+issueType.String(), func(t *testing.T) {
got := invokeMCPGate(t, readWriteCeiling(), write, v1connect.IssueServiceCreateIssueProcedure,
@@ -1262,7 +1265,9 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {
require.False(t, got.dispatched)
require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(got.err))
require.Contains(t, got.err.Error(), issueType.String())
- require.Contains(t, got.err.Error(), tt.wayOut)
+ for _, wayOut := range tt.wayOut {
+ require.Contains(t, got.err.Error(), wayOut)
+ }
require.NotContains(t, got.err.Error(), tt.notWayOut)
require.True(t, got.auditMarked)
})
@@ -1828,26 +1833,30 @@ func TestRejectMCPOriginatedGrantIssue(t *testing.T) {
ctx context.Context
issueType v1pb.Issue_Type
// wayOut is empty for a creation the guard allows.
- wayOut, notWayOut string
+ wayOut []string
+ notWayOut string
}{
- "an MCP session may not create a role grant": {mcpCtx, v1pb.Issue_ROLE_GRANT, mcpConsoleWayOut, v1connect.AccessGrantServiceCreateAccessGrantProcedure},
- "an MCP session may not create an access grant": {mcpCtx, v1pb.Issue_ACCESS_GRANT, v1connect.AccessGrantServiceCreateAccessGrantProcedure, mcpConsoleWayOut},
- "an MCP session may not create an unknown type": {mcpCtx, v1pb.Issue_Type(9999), mcpConsoleWayOut, v1connect.AccessGrantServiceCreateAccessGrantProcedure},
- "an MCP session composes database changes": {mcpCtx, v1pb.Issue_DATABASE_CHANGE, "", ""},
- "an unset type is left to buildIssueMessage": {mcpCtx, v1pb.Issue_TYPE_UNSPECIFIED, "", ""},
- "the console creates a role grant": {console, v1pb.Issue_ROLE_GRANT, "", ""},
- "a request with no auth context at all": {context.Background(), v1pb.Issue_ROLE_GRANT, "", ""},
+ "an MCP session may not create a role grant": {mcpCtx, v1pb.Issue_ROLE_GRANT, []string{mcpConsoleWayOut}, v1connect.AccessGrantServiceCreateAccessGrantProcedure},
+ "an MCP session may not create an access grant": {mcpCtx, v1pb.Issue_ACCESS_GRANT,
+ []string{v1connect.AccessGrantServiceCreateAccessGrantProcedure, "request_access_grant"}, mcpConsoleWayOut},
+ "an MCP session may not create an unknown type": {mcpCtx, v1pb.Issue_Type(9999), []string{mcpConsoleWayOut}, v1connect.AccessGrantServiceCreateAccessGrantProcedure},
+ "an MCP session composes database changes": {mcpCtx, v1pb.Issue_DATABASE_CHANGE, nil, ""},
+ "an unset type is left to buildIssueMessage": {mcpCtx, v1pb.Issue_TYPE_UNSPECIFIED, nil, ""},
+ "the console creates a role grant": {console, v1pb.Issue_ROLE_GRANT, nil, ""},
+ "a request with no auth context at all": {context.Background(), v1pb.Issue_ROLE_GRANT, nil, ""},
} {
t.Run(name, func(t *testing.T) {
err := rejectMCPOriginatedGrantIssue(tt.ctx, tt.issueType)
- if tt.wayOut == "" {
+ if len(tt.wayOut) == 0 {
require.NoError(t, err, "this guard binds MCP sessions and nothing else")
return
}
require.Error(t, err)
require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
require.Contains(t, err.Error(), tt.issueType.String(), "the denial must name the type it refused")
- require.Contains(t, err.Error(), tt.wayOut)
+ for _, wayOut := range tt.wayOut {
+ require.Contains(t, err.Error(), wayOut)
+ }
require.NotContains(t, err.Error(), tt.notWayOut)
})
}
diff --git a/backend/tests/mcp_access_request_test.go b/backend/tests/mcp_access_request_test.go
new file mode 100644
index 0000000000..710adb7c08
--- /dev/null
+++ b/backend/tests/mcp_access_request_test.go
@@ -0,0 +1,93 @@
+package tests
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/fieldmaskpb"
+
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+func TestMCPRequestsAccessWithTheDedicatedTool(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl, ctx := startWorkspace(ctx, t)
+
+ project, err := ctl.projectServiceClient.CreateProject(ctx, connect.NewRequest(&v1pb.CreateProjectRequest{
+ ProjectId: "mcp-request-tool",
+ Project: &v1pb.Project{Title: "MCP request tool"},
+ }))
+ a.NoError(err)
+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_READ_WRITE))
+ session := openMCPSession(ctx, t, ctl, ctl.authInterceptor.token)
+ defer session.Close()
+
+ pgContainer := sharedPgTarget(t)
+ instance, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{
+ InstanceId: generateRandomString("inst"),
+ Instance: &v1pb.Instance{
+ SyncDatabases: &v1pb.SyncDatabases{},
+ Title: "MCP request tool instance",
+ Engine: v1pb.Engine_POSTGRES,
+ Environment: new("environments/prod"),
+ Activation: true,
+ DataSources: []*v1pb.DataSource{pgContainer.adminDataSource()},
+ },
+ }))
+ a.NoError(err)
+ dbName := generateRandomString("db")
+ a.NoError(ctl.createDatabase(ctx, project.Msg, instance.Msg, nil, dbName, ""))
+ // A database on a workspace instance, whose name carries no project.
+ target := fmt.Sprintf("%s/databases/%s", instance.Msg.Name, dbName)
+ request := map[string]any{
+ "database": target,
+ "statement": "SELECT 1",
+ "schema": "public",
+ "unmask": true,
+ "export": true,
+ "reason": "the agent needs one read",
+ "durationHours": 2,
+ }
+
+ refused, text := callToolOnSession(ctx, t, session, "request_access_grant", map[string]any{
+ "database": dbName,
+ "statement": "SELECT 1",
+ "reason": "the agent needs one read",
+ "durationHours": 2,
+ })
+ a.True(refused, text)
+ a.Contains(text, fmt.Sprintf("failed to parse %q", dbName), "the API refuses a name that is not a full database name")
+
+ refused, text = callToolOnSession(ctx, t, session, "request_access_grant", request)
+ a.True(refused, text)
+ a.Contains(text, `just-in-time access is off for project "mcp-request-tool"`)
+
+ _, err = ctl.projectServiceClient.UpdateProject(ctx, connect.NewRequest(&v1pb.UpdateProjectRequest{
+ Project: &v1pb.Project{Name: project.Msg.Name, AllowJustInTimeAccess: true},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"allow_just_in_time_access"}},
+ }))
+ a.NoError(err)
+
+ failed, text := callToolOnSession(ctx, t, session, "request_access_grant", request)
+ a.False(failed, text)
+ grants, err := ctl.accessGrantServiceClient.ListAccessGrants(ctx, connect.NewRequest(&v1pb.ListAccessGrantsRequest{Parent: project.Msg.Name}))
+ a.NoError(err)
+ a.Len(grants.Msg.AccessGrants, 1)
+ grant := grants.Msg.AccessGrants[0]
+ a.Equal(v1pb.AccessGrant_PENDING, grant.Status)
+ a.Equal([]string{target}, grant.Targets)
+ a.Equal("SELECT 1", grant.Query)
+ a.Equal("public", grant.Schema)
+ a.True(grant.Unmask)
+ a.True(grant.Export)
+ a.Equal("the agent needs one read", grant.Reason)
+ a.Equal(2*time.Hour, grant.GetTtl().AsDuration(), "a ttl starts at approval")
+ a.Contains(text, "Requested "+grant.Name+":")
+ a.Contains(text, grant.Issue)
+}
diff --git a/backend/tests/mcp_gate_test.go b/backend/tests/mcp_gate_test.go
index 859c41bb15..2ad643cd13 100644
--- a/backend/tests/mcp_gate_test.go
+++ b/backend/tests/mcp_gate_test.go
@@ -196,6 +196,7 @@ func TestMCPGrantIssuesAndAccessRequests(t *testing.T) {
a.Equal(http.StatusForbidden, accessGrantIssue.Status)
a.Contains(accessGrantIssue.Error, "AccessGrantService/CreateAccessGrant",
"the refusal must name the method that files the request")
+ a.Contains(accessGrantIssue.Error, "request_access_grant", "and the tool an agent files it with")
a.NotContains(accessGrantIssue.Error, "Bytebase console")
pgContainer := sharedPgTarget(t)
@@ -657,7 +658,7 @@ func TestMCPGrantsAndRevokesAMaskingExemption(t *testing.T) {
failed, granted := callToolOnSession(ctx, t, session, "grant_masking_exemption", map[string]any{
"project": project.Msg.Name, "member": "user:[email protected]", "database": database,
- "table": "employee", "column": "salary", "expireTime": "2099-01-01T00:00:00Z",
+ "table": "employee", "columns": []string{"salary", "bonus"}, "expireTime": "2099-01-01T00:00:00Z",
})
a.False(failed, granted)
policy, err := ctl.orgPolicyServiceClient.GetPolicy(ctx, connect.NewRequest(&v1pb.GetPolicyRequest{Name: policyName}))
@@ -666,7 +667,7 @@ func TestMCPGrantsAndRevokesAMaskingExemption(t *testing.T) {
a.Len(exemptions, 1)
a.Equal([]string{"user:[email protected]"}, exemptions[0].Members)
condition := exemptions[0].GetCondition().GetExpression()
- a.Equal(fmt.Sprintf(`request.time < timestamp("2099-01-01T00:00:00.000Z") && (resource.instance_id == %q && resource.database_name == %q && resource.table_name == "employee" && resource.column_name == "salary")`,
+ a.Equal(fmt.Sprintf(`request.time < timestamp("2099-01-01T00:00:00.000Z") && (resource.instance_id == %q && resource.database_name == %q && resource.table_name == "employee" && resource.column_name in ["salary", "bonus"])`,
strings.TrimPrefix(instance.Msg.Name, "instances/"), dbName), condition)
failed, revoked := callToolOnSession(ctx, t, session, "revoke_masking_exemption", map[string]any{