Skip to content

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

feat(mcp): audit the two MCP doors that sit outside the API, and filter for them (P1b 1b-5a) (#21221)

Vincent Huangc26eb3d8b59e
diff --git a/backend/api/auth/mcp_ceiling.go b/backend/api/auth/mcp_ceiling.go
new file mode 100644
index 0000000000..29af971d9d
--- /dev/null
+++ b/backend/api/auth/mcp_ceiling.go
@@ -0,0 +1,102 @@
+package auth
+
+import (
+ "github.com/pkg/errors"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// MCPCeilingVerdict is what a read of a workspace's MCP capability ceiling
+// means to a caller deciding whether to proceed. Every reader of the setting
+// decides from it and says so with Refusal — the consent, the token endpoint,
+// the /mcp connection gate, the per-request gate, and the mode-contents read —
+// so no two can disagree about a workspace or describe it two ways.
+type MCPCeilingVerdict int
+
+// Each value names what an admin would have to do about it, which is what the
+// doors turn into a sentence.
+const (
+ // The ceiling admits work; which work is decided per method and per statement.
+ MCPCeilingServes MCPCeilingVerdict = iota
+ // An admin turned MCP off. Raising the ceiling fixes it.
+ MCPCeilingDisabled
+ // The stored value is one this build cannot interpret — a mistyped enum
+ // name, a wrong-typed row. An admin has to write the setting again.
+ MCPCeilingUnreadable
+ // The value parsed but no mode this build has serves it: the reserved 2, or
+ // a ceiling a newer release wrote. An admin has to choose a known value.
+ MCPCeilingUnserved
+ // The read itself failed. The only one of these a retry may fix.
+ MCPCeilingUnavailable
+)
+
+// IsPolicy reports whether the verdict is a decision about the workspace, which
+// is what makes a refusal an audited outcome.
+func (v MCPCeilingVerdict) IsPolicy() bool {
+ switch v {
+ case MCPCeilingDisabled, MCPCeilingUnreadable, MCPCeilingUnserved:
+ return true
+ default:
+ return false
+ }
+}
+
+// ClassifyMCPCeiling turns the result of store.GetMCPSettingsUncached into the
+// verdict its caller acts on. Everything this build cannot act on refuses; what
+// the split decides is the message and the audit row. A value nobody can
+// interpret never succeeds on retry; an outage may.
+func ClassifyMCPCeiling(capability storepb.MCPSetting_Capability, err error) MCPCeilingVerdict {
+ if err != nil {
+ if errors.Is(err, store.ErrMCPCapabilityUnreadable) {
+ return MCPCeilingUnreadable
+ }
+ return MCPCeilingUnavailable
+ }
+ if capability == storepb.MCPSetting_DISABLED {
+ return MCPCeilingDisabled
+ }
+ if !MCPCeilingServesAnything(capability) {
+ return MCPCeilingUnserved
+ }
+ return MCPCeilingServes
+}
+
+// Refusal is what a door tells the caller it is refusing: what is wrong with
+// this workspace's ceiling, and what an admin does about it. Empty for
+// MCPCeilingServes, which refuses nothing.
+//
+// Door-neutral on purpose. Each door used to keep its own copy ending in "so
+// the connection fails closed" / "so authorization fails closed", and the
+// copies drifted — the token endpoint borrowed the consent's clause, so a
+// refused refresh told the client that no client could be authorized. Which
+// door refused is already carried by the status, the page, and the audit row's
+// method, so the sentence does not say it again.
+//
+// Lowercase and unterminated: every door but the consent page composes this
+// into a larger error, and that page ends the sentence itself.
+func (v MCPCeilingVerdict) Refusal() string {
+ switch v {
+ case MCPCeilingDisabled:
+ return "a workspace admin has turned MCP access off for this workspace. " +
+ "Ask them to raise the MCP ceiling in the workspace settings"
+ case MCPCeilingUnreadable:
+ return "this workspace's stored MCP capability ceiling is not one this build understands. " +
+ "Ask a workspace admin to set the MCP ceiling again in the workspace settings"
+ case MCPCeilingUnserved:
+ return "this workspace's stored MCP capability ceiling is not one this build serves. " +
+ "Ask a workspace admin to set the MCP ceiling to a supported value in the workspace settings"
+ case MCPCeilingUnavailable:
+ return "this workspace's MCP capability ceiling could not be read. " +
+ "Retry shortly; if it persists, ask a workspace admin to check the workspace settings"
+ default:
+ return ""
+ }
+}
+
+// PolicyMCPCeilingVerdicts is every verdict that is a decision about the
+// workspace rather than an outage, which is what decides whether a refusal is
+// recorded. Refusal covers the outage too; this list does not.
+func PolicyMCPCeilingVerdicts() []MCPCeilingVerdict {
+ return []MCPCeilingVerdict{MCPCeilingDisabled, MCPCeilingUnreadable, MCPCeilingUnserved}
+}
diff --git a/backend/api/auth/mcp_ceiling_test.go b/backend/api/auth/mcp_ceiling_test.go
new file mode 100644
index 0000000000..d69f259f12
--- /dev/null
+++ b/backend/api/auth/mcp_ceiling_test.go
@@ -0,0 +1,135 @@
+package auth
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// TestClassifyMCPCeiling pins the one split three doors depend on.
+//
+// The line that matters is between a stored value and a failed read. A value
+// nobody can interpret never succeeds on retry, so telling a client to retry is
+// a lie; a read that failed is an outage, so blaming an admin is a lie the
+// other way. Everything this build cannot act on refuses either way, which is
+// what makes the distinction about the message and the audit row rather than
+// about access.
+func TestClassifyMCPCeiling(t *testing.T) {
+ unreadable := errors.Wrapf(store.ErrMCPCapabilityUnreadable, "READ_ONLYY is not a value this build understands")
+
+ tests := []struct {
+ name string
+ capability storepb.MCPSetting_Capability
+ err error
+ want MCPCeilingVerdict
+ policy bool
+ }{
+ {"read-write serves", storepb.MCPSetting_READ_WRITE, nil, MCPCeilingServes, false},
+ {"read-only serves", storepb.MCPSetting_READ_ONLY, nil, MCPCeilingServes, false},
+ {"disabled", storepb.MCPSetting_DISABLED, nil, MCPCeilingDisabled, true},
+ {"the reserved number", storepb.MCPSetting_Capability(2), nil, MCPCeilingUnserved, true},
+ {"a value from a newer build", storepb.MCPSetting_Capability(99), nil, MCPCeilingUnserved, true},
+ // The store resolves an absent setting to READ_WRITE and an explicit
+ // unset to the unreadable error, so a zero value arriving here was
+ // resolved by nobody.
+ {"nobody resolved it", storepb.MCPSetting_CAPABILITY_UNSPECIFIED, nil, MCPCeilingUnserved, true},
+ {"a stored value nobody can read", storepb.MCPSetting_CAPABILITY_UNSPECIFIED, unreadable, MCPCeilingUnreadable, true},
+ // The error wins over the value, whatever the value happens to be.
+ {"an unreadable value that parsed to something", storepb.MCPSetting_READ_WRITE, unreadable, MCPCeilingUnreadable, true},
+ {"the read failed", storepb.MCPSetting_CAPABILITY_UNSPECIFIED, errors.New("connection refused"), MCPCeilingUnavailable, false},
+ {"the read failed on a permissive workspace", storepb.MCPSetting_READ_WRITE, errors.New("connection refused"), MCPCeilingUnavailable, false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := ClassifyMCPCeiling(tt.capability, tt.err)
+ require.Equal(t, tt.want, got)
+ require.Equal(t, tt.policy, got.IsPolicy())
+ })
+ }
+}
+
+// TestMCPCeilingVerdictAdmissionMatchesTheServesPredicate holds the classifier
+// against the predicate the serving table already pins: exactly one verdict may
+// admit work, and it must be the one MCPCeilingServesAnything agrees with over
+// the whole enum. A mode that starts or stops serving a class cannot leave one
+// of them stale.
+func TestMCPCeilingVerdictAdmissionMatchesTheServesPredicate(t *testing.T) {
+ values := storepb.MCPSetting_Capability(0).Descriptor().Values()
+ for i := range values.Len() {
+ capability := storepb.MCPSetting_Capability(values.Get(i).Number())
+ admits := ClassifyMCPCeiling(capability, nil) == MCPCeilingServes
+ require.Equal(t, MCPCeilingServesAnything(capability), admits,
+ "%v must admit work in exactly one of the two", capability)
+ }
+}
+
+// TestPolicyVerdictsAreExactlyTheAuditedOnes holds the list every door renders
+// wording from against the predicate that decides whether a refusal is
+// recorded. A verdict in one and not the other would either be refused with no
+// sentence or audited as a decision nobody made.
+func TestPolicyVerdictsAreExactlyTheAuditedOnes(t *testing.T) {
+ policy := map[MCPCeilingVerdict]bool{}
+ for _, v := range PolicyMCPCeilingVerdicts() {
+ require.True(t, v.IsPolicy(), "%v is listed as policy but does not report as one", v)
+ policy[v] = true
+ }
+ for _, v := range []MCPCeilingVerdict{
+ MCPCeilingServes, MCPCeilingDisabled, MCPCeilingUnreadable, MCPCeilingUnserved, MCPCeilingUnavailable,
+ } {
+ require.Equal(t, v.IsPolicy(), policy[v], "%v disagrees between the list and the predicate", v)
+ }
+}
+
+// TestEveryVerdictThatRefusesHasWording holds the one wording table against the
+// verdicts that reach a caller. It replaces a per-door version of this check
+// that each door carried: while the sentences were per-door, coverage was all a
+// lint could hold them to — the wording itself was free to drift, and it did.
+//
+// The list spans all five values, not PolicyMCPCeilingVerdicts, because an
+// outage is refused too and its sentence is the one nobody would otherwise
+// exercise. Only Serves is silent.
+func TestEveryVerdictThatRefusesHasWording(t *testing.T) {
+ for _, v := range []MCPCeilingVerdict{
+ MCPCeilingDisabled, MCPCeilingUnreadable, MCPCeilingUnserved, MCPCeilingUnavailable,
+ } {
+ refusal := v.Refusal()
+ require.NotEmpty(t, refusal, "%v reaches a caller and must say what is wrong", v)
+
+ // Composed into a larger error at every door but the consent page, so
+ // it starts lowercase and ends unterminated.
+ require.Equal(t, strings.ToLower(refusal[:1]), refusal[:1],
+ "%v: a door prefixes this, so it must not start a sentence", v)
+ require.NotEqual(t, ".", refusal[len(refusal)-1:],
+ "%v: the consent page terminates it; the others compose it", v)
+
+ // Every refusal names the remedy, not only the fault. A denial an
+ // operator cannot act on is the failure this series exists to fix.
+ require.Contains(t, refusal, "workspace settings", "%v must name where the fix is", v)
+ }
+
+ require.Empty(t, MCPCeilingServes.Refusal(), "serving refuses nothing")
+}
+
+// TestRefusalsDistinguishTheThreeStoredStates pins that the three policy
+// verdicts do not collapse into one message. They have different fixes — turn
+// MCP back on, rewrite a value nobody can read, choose a value this build
+// serves — and a door that said "disabled" for all three would send two of them
+// to the wrong control.
+func TestRefusalsDistinguishTheThreeStoredStates(t *testing.T) {
+ seen := map[string]MCPCeilingVerdict{}
+ for _, v := range PolicyMCPCeilingVerdicts() {
+ refusal := v.Refusal()
+ if other, dup := seen[refusal]; dup {
+ require.Failf(t, "verdicts share wording", "%v and %v say the same thing", other, v)
+ }
+ seen[refusal] = v
+ }
+ require.Contains(t, MCPCeilingDisabled.Refusal(), "turned MCP access off")
+ require.Contains(t, MCPCeilingUnreadable.Refusal(), "not one this build understands")
+ require.Contains(t, MCPCeilingUnserved.Refusal(), "not one this build serves")
+}
diff --git a/backend/api/mcp/connection_audit.go b/backend/api/mcp/connection_audit.go
new file mode 100644
index 0000000000..ea51476f1c
--- /dev/null
+++ b/backend/api/mcp/connection_audit.go
@@ -0,0 +1,72 @@
+package mcp
+
+import (
+ "log/slog"
+ "net/http"
+
+ "github.com/labstack/echo/v5"
+ spb "google.golang.org/genproto/googleapis/rpc/status"
+ "google.golang.org/grpc/codes"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+// refuseByCeiling holds a verified token against the workspace's MCP capability
+// ceiling. It returns nil to admit the request, or the HTTP error to refuse it
+// with, recording a row first when the refusal is a verdict about the
+// workspace. auth.ClassifyMCPCeiling makes that call, so this door and the
+// per-request gate cannot disagree about one workspace.
+func (s *Server) refuseByCeiling(c *echo.Context, delegated auth.DelegatedMCPCredential) error {
+ ctx := c.Request().Context()
+ settings, err := s.store.GetMCPSettingsUncached(ctx, delegated.WorkspaceID)
+ verdict := auth.ClassifyMCPCeiling(settings.Capability, err)
+ if verdict == auth.MCPCeilingServes {
+ return nil
+ }
+ if !verdict.IsPolicy() {
+ slog.Error("failed to read the MCP capability ceiling; cannot admit the session", log.BBError(err))
+ return echo.NewHTTPError(http.StatusServiceUnavailable, verdict.Refusal())
+ }
+ if err != nil {
+ slog.Warn("the stored MCP capability ceiling cannot be interpreted; refusing the connection",
+ slog.String("workspace", delegated.WorkspaceID), log.BBError(err))
+ }
+ return s.refuseConnection(c, delegated, verdict.Refusal())
+}
+
+// refuseConnection records the refusal and returns the 403 to answer with.
+//
+// The row is written here because this refusal happens in echo middleware,
+// before any RPC: neither connect chain ever sees it, so no interceptor would
+// write it.
+func (s *Server) refuseConnection(c *echo.Context, delegated auth.DelegatedMCPCredential, reason string) error {
+ row := &storepb.AuditLog{
+ Parent: common.FormatWorkspace(delegated.WorkspaceID),
+ Method: common.AuditMethodMCPSessionAuthorize,
+ Resource: common.FormatWorkspace(delegated.WorkspaceID),
+ Severity: storepb.AuditLog_INFO,
+ User: common.FormatUserEmail(delegated.Principal),
+ Status: &spb.Status{
+ Code: int32(codes.PermissionDenied),
+ Message: reason,
+ },
+ RequestMetadata: common.RequestMetadataFromHTTP(c.Request()),
+ // The grant this token carries, and no correlation ID. That field is
+ // session-scoped, and this refusal is decided before the SDK resolves a
+ // session: an initial connection has none, and a mid-session refusal
+ // cannot reach the ID the session already writes under. The per-request
+ // value minted here would read as a session ID that correlates exactly
+ // one row.
+ McpDelegation: &storepb.MCPDelegation{
+ Scope: delegated.Scope,
+ Resource: delegated.Resource,
+ ClientId: delegated.ClientID,
+ },
+ }
+ common.RecordOutOfBandAudit(c.Request().Context(), s.store,
+ s.profile.RuntimeEnableAuditLogStdout.Load(), delegated.WorkspaceID, row)
+ return echo.NewHTTPError(http.StatusForbidden, reason)
+}
diff --git a/backend/api/mcp/connection_audit_test.go b/backend/api/mcp/connection_audit_test.go
new file mode 100644
index 0000000000..81c4add1b7
--- /dev/null
+++ b/backend/api/mcp/connection_audit_test.go
@@ -0,0 +1,316 @@
+package mcp
+
+import (
+ "bytes"
+ "context"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/labstack/echo/v5"
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/config"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// TestMCPConnectionDenialEmission pins which refusals at /mcp become audit rows
+// and which do not.
+//
+// The line is what an operator can act on. A ceiling that refuses the workspace
+// is a decision somebody made and somebody else has to change, and it is
+// invisible everywhere else: the refusal happens in echo middleware, so neither
+// connect chain audits it, and the session it refused never existed to leave
+// any other trace. A rejected credential is not that. Tokens expire and get
+// replaced constantly, by design, and a row per expiry would bury the denials
+// this exists to surface under ordinary churn — while telling an operator
+// nothing they can do anything about.
+//
+// The refusal comes first either way. The row is best effort; the 403 is not.
+func TestMCPConnectionDenialEmission(t *testing.T) {
+ const secret = "test-secret-key"
+
+ newServer := func(t *testing.T, st serverStore) *Server {
+ t.Helper()
+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}
+ srv, err := newServerWithStore(st, profile, secret, nil)
+ require.NoError(t, err)
+ return srv
+ }
+
+ connect := func(t *testing.T, srv *Server, token string) int {
+ t.Helper()
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("User-Agent", "TestAgent/1.0")
+ req.Header.Set(common.HeaderRealIP, "10.0.1.50")
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+ handler := srv.authMiddleware(func(c *echo.Context) error {
+ return c.String(http.StatusOK, "success")
+ })
+ if err := handler(c); err != nil {
+ echo.DefaultHTTPErrorHandler(true)(c, err)
+ }
+ return rec.Code
+ }
+
+ t.Run("a ceiling that refuses the workspace writes one row", func(t *testing.T) {
+ st := newTestServerStore()
+ st.capability = storepb.MCPSetting_DISABLED
+ srv := newServer(t, st)
+
+ require.Equal(t, http.StatusForbidden, connect(t, srv, mcpToken(t, secret, tokenOptions{})))
+
+ require.Len(t, st.auditRows, 1)
+ row := st.auditRows[0]
+ require.Equal(t, common.AuditMethodMCPSessionAuthorize, row.Method)
+ require.Equal(t, "workspaces/ws-test", row.Parent)
+ require.Equal(t, "workspaces/ws-test", row.Resource)
+ require.Equal(t, "users/[email protected]", row.User)
+ require.EqualValues(t, 7, row.Status.GetCode(), "PermissionDenied")
+ require.Contains(t, row.Status.GetMessage(), "turned MCP access off")
+ require.Equal(t, "10.0.1.50", row.RequestMetadata.GetCallerIp())
+ require.Equal(t, "TestAgent/1.0", row.RequestMetadata.GetCallerSuppliedUserAgent())
+
+ // The marker, so the row answers `mcp == true` and wears the MCP badge
+ // alongside the calls a session that got in would have made.
+ require.NotNil(t, row.McpDelegation, "a denial at the MCP door is an MCP row")
+ // But no correlation ID. It is session-scoped and this refusal is
+ // decided before the SDK resolves a session, so any value here would be
+ // a session ID that names one row — and a mid-session refusal would get
+ // one different from the rows that session already wrote, hiding the
+ // denial from the pivot an operator would use to find it.
+ require.Empty(t, row.McpDelegation.GetCorrelationId())
+ })
+
+ t.Run("an unreadable ceiling writes a row that names the typo, not the policy", func(t *testing.T) {
+ st := newTestServerStore()
+ st.capabilityErr = errors.Wrapf(store.ErrMCPCapabilityUnreadable, "READ_ONLYY is not a value this build understands")
+ srv := newServer(t, st)
+
+ require.Equal(t, http.StatusForbidden, connect(t, srv, mcpToken(t, secret, tokenOptions{})))
+
+ require.Len(t, st.auditRows, 1)
+ require.Contains(t, st.auditRows[0].Status.GetMessage(), "not one this build understands",
+ "an admin fixes a broken stored value by rewriting it, not by turning MCP back on")
+ })
+
+ t.Run("a ceiling this build does not serve writes its own row", func(t *testing.T) {
+ st := newTestServerStore()
+ // The reserved number 2, or a ceiling a newer release wrote.
+ st.capability = storepb.MCPSetting_Capability(2)
+ srv := newServer(t, st)
+
+ require.Equal(t, http.StatusForbidden, connect(t, srv, mcpToken(t, secret, tokenOptions{})))
+
+ require.Len(t, st.auditRows, 1)
+ require.Contains(t, st.auditRows[0].Status.GetMessage(), "not one this build serves")
+ })
+
+ t.Run("a failed ceiling read is an outage, not a denial", func(t *testing.T) {
+ st := newTestServerStore()
+ st.capabilityErr = errors.New("connection refused")
+ srv := newServer(t, st)
+
+ require.Equal(t, http.StatusServiceUnavailable, connect(t, srv, mcpToken(t, secret, tokenOptions{})))
+ require.Empty(t, st.auditRows,
+ "recording an outage as a policy denial would put a decision in the log that nobody made")
+ })
+
+ t.Run("credential-lifecycle refusals write nothing", func(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ token string
+ }{
+ {"expired", mcpToken(t, secret, tokenOptions{expired: true})},
+ {"signed with the wrong secret", mcpToken(t, "not-the-secret", tokenOptions{})},
+ {"no workspace claim", mcpToken(t, secret, tokenOptions{noWorkspace: true})},
+ {"audience bound elsewhere", mcpToken(t, secret, tokenOptions{audience: "https://other.example.com/mcp"})},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ st := newTestServerStore()
+ st.capability = storepb.MCPSetting_DISABLED
+ srv := newServer(t, st)
+
+ require.Equal(t, http.StatusUnauthorized, connect(t, srv, tc.token))
+ require.Empty(t, st.auditRows, "token churn is not a denial an operator acts on")
+ })
+ }
+ })
+
+ t.Run("an admitted connection writes nothing", func(t *testing.T) {
+ st := newTestServerStore()
+ srv := newServer(t, st)
+
+ require.Equal(t, http.StatusOK, connect(t, srv, mcpToken(t, secret, tokenOptions{})))
+ require.Empty(t, st.auditRows,
+ "the interceptor audits what an admitted session then does; this gate only records refusals")
+ })
+
+ t.Run("the row carries the whole grant, not just its presence", func(t *testing.T) {
+ const resource = "https://bb.example.com/mcp"
+ st := newTestServerStore()
+ st.capability = storepb.MCPSetting_DISABLED
+ srv := newServer(t, st)
+
+ token := mcpToken(t, secret, tokenOptions{
+ audience: resource,
+ clientID: "client-A",
+ scope: "mcp:read-only",
+ mcpTokenUse: true,
+ })
+ require.Equal(t, http.StatusForbidden, connect(t, srv, token))
+
+ require.Len(t, st.auditRows, 1)
+ grant := st.auditRows[0].McpDelegation
+ require.Equal(t, "client-A", grant.GetClientId())
+ require.Equal(t, "mcp:read-only", grant.GetScope())
+ require.Equal(t, resource, grant.GetResource())
+ })
+
+ t.Run("the row survives a client that hung up on its own refusal", func(t *testing.T) {
+ st := newTestServerStore()
+ st.capability = storepb.MCPSetting_DISABLED
+ srv := newServer(t, st)
+
+ e := echo.New()
+ req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{}`))
+ ctx, cancel := context.WithCancel(req.Context())
+ cancel()
+ req = req.WithContext(ctx)
+ req.Header.Set("Authorization", "Bearer "+mcpToken(t, secret, tokenOptions{}))
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+ handler := srv.authMiddleware(func(c *echo.Context) error { return c.String(http.StatusOK, "success") })
+ if err := handler(c); err != nil {
+ echo.DefaultHTTPErrorHandler(true)(c, err)
+ }
+
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Len(t, st.auditRows, 1)
+ require.NoError(t, st.writeCtxErr,
+ "the write must not inherit the cancellation it is recording")
+ require.True(t, st.writeCtxHasDeadline,
+ "detaching from the request drops its deadline too, and this write is on the "+
+ "synchronous path of a refusal already decided — an unbounded insert holds the 403 open")
+ })
+
+ t.Run("every refused request writes its own row", func(t *testing.T) {
+ st := newTestServerStore()
+ st.capability = storepb.MCPSetting_DISABLED
+ srv := newServer(t, st)
+ token := mcpToken(t, secret, tokenOptions{})
+
+ for range 3 {
+ require.Equal(t, http.StatusForbidden, connect(t, srv, token))
+ }
+ require.Len(t, st.auditRows, 3,
+ "/mcp is Streamable HTTP, so this gate is per request; nothing collapses repeats")
+ })
+
+ t.Run("the stdout mirror runs even when the row cannot be persisted", func(t *testing.T) {
+ st := newTestServerStore()
+ st.capability = storepb.MCPSetting_DISABLED
+ st.auditErr = errors.New("audit_log insert failed")
+ srv := newServer(t, st)
+ srv.profile.RuntimeEnableAuditLogStdout.Store(true)
+
+ var buf bytes.Buffer
+ prev := slog.Default()
+ t.Cleanup(func() { slog.SetDefault(prev) })
+ slog.SetDefault(slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelInfo})))
+
+ require.Equal(t, http.StatusForbidden, connect(t, srv, mcpToken(t, secret, tokenOptions{})))
+ require.Contains(t, buf.String(), `"log_type":"audit"`,
+ "a database failure is exactly when the stream is the surface that still works")
+ require.Contains(t, buf.String(), common.AuditMethodMCPSessionAuthorize)
+ })
+
+ t.Run("a failed write does not admit the connection", func(t *testing.T) {
+ st := newTestServerStore()
+ st.capability = storepb.MCPSetting_DISABLED
+ st.auditErr = errors.New("audit_log insert failed")
+ srv := newServer(t, st)
+
+ require.Equal(t, http.StatusForbidden, connect(t, srv, mcpToken(t, secret, tokenOptions{})),
+ "an audit row that cannot be written must never turn a refusal into an admission")
+ })
+}
+
+type tokenOptions struct {
+ expired bool
+ noWorkspace bool
+ audience string
+ clientID string
+ scope string
+ mcpTokenUse bool
+}
+
+// mcpToken mints the bearer a client presents at /mcp, with one thing wrong at
+// a time.
+func mcpToken(t *testing.T, secret string, opts tokenOptions) string {
+ t.Helper()
+ audience := any(auth.OAuth2AccessTokenAudience)
+ if opts.audience != "" {
+ audience = opts.audience
+ }
+ expiry := time.Now().Add(time.Hour)
+ if opts.expired {
+ expiry = time.Now().Add(-time.Hour)
+ }
+ claims := jwt.MapClaims{
+ "iss": "bytebase",
+ "sub": "[email protected]",
+ "aud": audience,
+ "exp": expiry.Unix(),
+ "iat": time.Now().Add(-2 * time.Hour).Unix(),
+ }
+ if !opts.noWorkspace {
+ claims["workspace_id"] = "ws-test"
+ }
+ if opts.clientID != "" {
+ claims["client_id"] = opts.clientID
+ }
+ if opts.scope != "" {
+ claims["scope"] = opts.scope
+ }
+ if opts.mcpTokenUse {
+ claims["token_use"] = auth.TokenUseMCP
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+ token.Header["kid"] = "v1"
+ tokenStr, err := token.SignedString([]byte(secret))
+ require.NoError(t, err)
+ return tokenStr
+}
+
+// TestCeilingRefusalsAreRecognizedAsPolicy runs the real IsPolicyRefusal over
+// the ceiling refusals that can reach a tool, rather than restating its phrase
+// list somewhere it would drift.
+//
+// Only these two reach it. A 403 is what the predicate is consulted for, and
+// the per-request gate answers CodePermissionDenied for exactly these; an
+// outage answers CodeUnavailable, and DISABLED is refused at this door before
+// any tool call and by the serving table at the per-request one. A refusal it
+// stops recognizing gets "request a project role" appended — advice that cannot
+// lift a workspace setting.
+func TestCeilingRefusalsAreRecognizedAsPolicy(t *testing.T) {
+ for _, verdict := range []auth.MCPCeilingVerdict{
+ auth.MCPCeilingUnreadable,
+ auth.MCPCeilingUnserved,
+ } {
+ require.True(t, IsPolicyRefusal(verdict.Refusal()),
+ "%v reaches a tool as a 403 and must carry its own way out", verdict)
+ }
+}
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index 5793316010..82084ab932 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -7766,6 +7766,52 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/bytebase.v1.IamPolicy'
+ /bytebase.v1.WorkspaceService/GetMCPInfo:
+ post:
+ tags:
+ - bytebase.v1.WorkspaceService
+ summary: |-
+ Gets what MCP (Model Context Protocol) does in this workspace: the
+ capability ceiling in force, what each ceiling serves, and the per-engine
+ facts a read-only session depends on. The workspace is resolved from the
+ authenticated session.
+ description: |-
+ Served to MCP sessions. An agent asking what it may do here is the point:
+ the response says nothing a session's own denials do not already say, one
+ refusal at a time, and knowing it up front is what stops the agent
+ planning work the ceiling was never going to serve.
+
+ Permissions required: None (authentication required)
+ operationId: bytebase.v1.WorkspaceService.GetMCPInfo
+ parameters:
+ - name: Connect-Protocol-Version
+ in: header
+ required: true
+ schema:
+ $ref: '#/components/schemas/connect-protocol-version'
+ - name: Connect-Timeout-Ms
+ in: header
+ schema:
+ $ref: '#/components/schemas/connect-timeout-header'
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.GetMCPInfoRequest'
+ required: true
+ responses:
+ default:
+ description: Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/connect.error'
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.MCPInfo'
/bytebase.v1.WorkspaceService/GetWorkspace:
post:
tags:
@@ -12302,6 +12348,10 @@ components:
description: If set to true, bypass cache and fetch the latest data.
title: GetIssueRequest
additionalProperties: false
+ bytebase.v1.GetMCPInfoRequest:
+ type: object
+ title: GetMCPInfoRequest
+ additionalProperties: false
bytebase.v1.GetPaymentInfoRequest:
type: object
title: GetPaymentInfoRequest
@@ -15001,6 +15051,21 @@ components:
title: LogoutRequest
additionalProperties: false
description: Request to logout current user session.
+ bytebase.v1.MCPCapabilityMode:
+ type: object
+ properties:
+ capability:
+ title: capability
+ $ref: '#/components/schemas/bytebase.v1.MCPSetting.Capability'
+ servedClasses:
+ type: array
+ items:
+ $ref: '#/components/schemas/bytebase.v1.MCPMethodClass'
+ title: served_classes
+ description: Empty means the ceiling serves nothing, which is what DISABLED is.
+ title: MCPCapabilityMode
+ additionalProperties: false
+ description: MCPCapabilityMode is one ceiling and the method classes it serves.
bytebase.v1.MCPDelegation:
type: object
properties:
@@ -15073,6 +15138,161 @@ components:
that contradicts its class. Neither is expressible now, and the one check
left — the reason belongs to the class it is used on — is a table the gate
already keeps for the wording.
+ bytebase.v1.MCPEngineEnforcement:
+ type: object
+ properties:
+ engine:
+ title: engine
+ $ref: '#/components/schemas/bytebase.v1.Engine'
+ readOnlyDepth:
+ title: read_only_depth
+ $ref: '#/components/schemas/bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth'
+ masking:
+ title: masking
+ $ref: '#/components/schemas/bytebase.v1.MCPEngineEnforcement.Masking'
+ note:
+ type: string
+ title: note
+ description: |-
+ Where the answers above are the floor rather than the whole story. Empty
+ for most engines.
+ title: MCPEngineEnforcement
+ additionalProperties: false
+ description: |-
+ MCPEngineEnforcement is what the read-only ceiling and the masking toggle
+ reach on one database engine.
+ bytebase.v1.MCPEngineEnforcement.Masking:
+ type: string
+ title: Masking
+ enum:
+ - MASKING_UNSPECIFIED
+ - NONE
+ - COLUMN
+ - DOCUMENT
+ description: |-
+ How Bytebase masks results on this engine, which is what decides whether
+ ignoring masking exemptions changes anything here.
+ bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth:
+ type: string
+ title: ReadOnlyDepth
+ enum:
+ - READ_ONLY_DEPTH_UNSPECIFIED
+ - UNSUPPORTED
+ - STATEMENT
+ - STATEMENT_AND_SESSION
+ description: How much of a read-only ceiling this engine can be held to.
+ bytebase.v1.MCPInfo:
+ type: object
+ properties:
+ workspace:
+ type: string
+ title: workspace
+ description: |-
+ The workspace this describes. Format: workspaces/{workspace}. Not this
+ message's own resource name — MCPInfo is not a named resource and there is
+ nothing to get it by.
+ capability:
+ title: capability
+ description: |-
+ The ceiling in force for this workspace. A workspace that never configured
+ MCP resolves to READ_WRITE.
+ $ref: '#/components/schemas/bytebase.v1.MCPSetting.Capability'
+ modes:
+ type: array
+ items:
+ $ref: '#/components/schemas/bytebase.v1.MCPCapabilityMode'
+ title: modes
+ description: |-
+ What each ceiling serves, including the one in force, so an admin can
+ compare the choices rather than only read the current answer.
+ methods:
+ type: array
+ items:
+ $ref: '#/components/schemas/bytebase.v1.MCPMethod'
+ title: methods
+ description: |-
+ Every API method some ceiling serves. A mode serves a method when the
+ method's class is one of that mode's served_classes, which is the ceiling
+ rule the gate evaluates. Methods no ceiling serves are absent.
+
+ Being listed is necessary, not sufficient. The caller still needs the
+ permission, and two further rules narrow what a served method does: a
+ handful of methods are refused on the shape of the request (an issue that
+ would grant a permission, a rollout that skips approval), and under
+ READ_ONLY every statement SQLService/Query runs must classify as a read.
+ engines:
+ type: array
+ items:
+ $ref: '#/components/schemas/bytebase.v1.MCPEngineEnforcement'
+ title: engines
+ description: |-
+ What a read-only session and the masking toggle actually reach, per engine.
+ Both are engine-conditional in ways the ceiling alone does not show.
+ ignoreMaskingExemptions:
+ type: boolean
+ title: ignore_masking_exemptions
+ description: |-
+ Whether this workspace stops applying the caller's own unmasking
+ provisioning to MCP requests. It decides which branch of each engine's
+ masking state a caller is in, and no other API tells an MCP session:
+ SettingService/GetSetting is served by no ceiling.
+ dataMaskingAvailable:
+ type: boolean
+ title: data_masking_available
+ description: |-
+ Whether data masking is licensed for this workspace. When false nothing is
+ masked whatever an engine supports, so the masking states below describe a
+ mechanism that does not run. Licensing can also be set per instance, so a
+ true here is the workspace answer, not a promise about every instance.
+ title: MCPInfo
+ additionalProperties: false
+ description: |-
+ MCPInfo is what MCP does in this workspace: the ceiling in force, what each
+ ceiling serves, and the per-engine facts a read-only session depends on.
+
+ Everything here is resolved when the request is served, never from a stored
+ copy: the method list comes off the compiled API descriptors and the engine
+ answers off the code that enforces them, so a build whose rules changed
+ cannot describe the rules of the build before it.
+ bytebase.v1.MCPMethod:
+ type: object
+ properties:
+ method:
+ type: string
+ title: method
+ description: |-
+ The method as an audit entry names it, so a denial can be found by it.
+ Example: /bytebase.v1.SQLService/Query
+ operationId:
+ type: string
+ title: operation_id
+ description: |-
+ The same method as call_api takes it.
+ Example: bytebase.v1.SQLService.Query
+ class:
+ title: class
+ $ref: '#/components/schemas/bytebase.v1.MCPMethodClass'
+ permission:
+ type: string
+ title: permission
+ description: |-
+ The IAM permission the method declares. The ceiling never grants: a session
+ may call a served method only where the person it acts for could.
+
+ Empty means the method declares no permission, which is NOT the same as
+ needing none — a method that authorizes inside its handler declares nothing
+ here. auth_method says which case an empty value is.
+ authMethod:
+ title: auth_method
+ description: |-
+ How the method authorizes. IAM means the permission above is the primary
+ rule, though not always the only one — an update carrying allow_missing
+ additionally requires the matching create permission. CUSTOM means the
+ handler decides and the permission field is silent.
+ $ref: '#/components/schemas/bytebase.v1.AuthMethod'
+ title: MCPMethod
+ additionalProperties: false
+ description: MCPMethod is one API method an MCP session can reach, and what decides it.
bytebase.v1.MCPMethodClass:
type: string
title: MCPMethodClass
@@ -18194,16 +18414,21 @@ components:
The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
Supported filter:
- - method: the API name, can be found in the docs, should start with "/bytebase.v1." prefix. For example "/bytebase.v1.UserService/CreateUser". Support "==" operator.
+ - method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
+ - resource: the resource the entry is about, support "==" operator.
- severity: support "==" operator, check Severity enum in AuditLog message for values.
- user: the actor, should in "users/{email}" format, support "==" operator.
- create_time: support ">=" and "<=" operator.
+ - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
+ - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
For example:
- filter = "method == '/bytebase.v1.SQLService/Query'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
+ - filter = "mcp == true"
+ - filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
orderBy:
type: string
title: order_by
diff --git a/backend/api/mcp/openapi_index.go b/backend/api/mcp/openapi_index.go
index 0f51e04547..aeac20fa43 100644
--- a/backend/api/mcp/openapi_index.go
+++ b/backend/api/mcp/openapi_index.go
@@ -75,7 +75,7 @@ type OpenAPIIndex struct {
// hiddenEndpoints holds every endpoint no MCP capability ceiling serves —
// FORBIDDEN and EXCLUDED alike — resolvable through byOperation so a
// direct call still gets the gate's actionable denial, but reachable by no
- // discovery path. That is 121 of the 209 classified RPCs, and 13 services
+ // discovery path. That is 114 of the 211 classified RPCs, and 13 services
// whose every method is refused leave Services() entirely.
hiddenEndpoints []EndpointInfo
byOperation map[string]*EndpointInfo
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
index cfbe4737be..c5dfd03676 100644
--- a/backend/api/mcp/server.go
+++ b/backend/api/mcp/server.go
@@ -5,7 +5,6 @@ import (
"context"
"fmt"
"log/slog"
- "net"
"net/http"
"strings"
"sync"
@@ -20,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/config"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
@@ -53,6 +53,10 @@ type serverStore interface {
GetWorkspaceProfileSetting(context.Context, string) (*storepb.WorkspaceProfileSetting, error)
GetMCPSettingsUncached(context.Context, string) (store.MCPSettings, error)
DeleteOAuth2RefreshTokensByUserAndClient(context.Context, string, string) error
+ // CreateAuditLog records the connection denials this package emits itself.
+ // They happen in echo middleware, outside both connect chains, so the audit
+ // interceptor never sees them.
+ CreateAuditLog(context.Context, string, *storepb.AuditLog) error
}
// NewServer creates a new MCP server. internalAPI is the internal API handler
@@ -132,6 +136,12 @@ func newServerWithStore(stores serverStore, profile *config.Profile, secret stri
}
// registerTools registers all MCP tools.
+//
+// The list is not filtered by the workspace's ceiling (BOT-89), and cannot be:
+// the SDK builds it once at session start while the ceiling is read per
+// request, so a filtered list would be a promise made under whatever the
+// ceiling was at connect time and would go stale the moment an admin changed
+// it. Revisit only if the SDK grows a way to revise a live session's tool list.
func (s *Server) registerTools() {
s.registerSearchTool()
s.registerCallTool()
@@ -205,25 +215,6 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return s.unauthorized(c, "invalid token: audience mismatch")
}
- // Enforce the workspace MCP capability ceiling before dispatching to any
- // tool. DISABLED rejects the connection outright; READ_ONLY admits it,
- // and what a read-only session may then do is decided per method by the
- // gate on the internal chain and per statement by the SQL clamp in
- // SQLService/Query. Read live so an admin change takes effect on the
- // next request without re-issuing tokens.
- capability, err := s.mcpCapability(c.Request().Context(), workspaceID)
- if err != nil {
- // Infra failure reading the policy, not a verdict on the
- // workspace: a 403 here would tell the operator their admin
- // disabled MCP. 503 says retry, and the session still does not
- // proceed.
- slog.Error("failed to read the MCP capability ceiling; cannot admit the session", log.BBError(err))
- return echo.NewHTTPError(http.StatusServiceUnavailable, "cannot read the MCP policy; retry shortly")
- }
- if !mcpConnectionAllowed(capability) {
- return echo.NewHTTPError(http.StatusForbidden, "MCP access is disabled for this workspace by policy")
- }
-
// Establish the delegated identity that carries this request's principal
// and grant state onto the private in-memory transport. The inbound
// bearer stops at this boundary: internal API requests mint their own
@@ -232,6 +223,9 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// (common.DelegatedGrant documents the empty-state semantics; P1b
// resolves them). Identity only, no roles: downstream authorization
// re-resolves live exactly as for a public request.
+ //
+ // Built before the ceiling is read so a refused request carries the same
+ // provenance an admitted one does.
delegated := auth.DelegatedMCPCredential{
Principal: sub,
WorkspaceID: workspaceID,
@@ -241,6 +235,16 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
Resource: grantResource(claims, aud),
}
+ // Enforce the workspace MCP capability ceiling before dispatching to any
+ // tool. DISABLED rejects the connection outright; READ_ONLY admits it,
+ // and what a read-only session may then do is decided per method by the
+ // gate on the internal chain and per statement by the SQL clamp in
+ // SQLService/Query. Read live so an admin change takes effect on the
+ // next request without re-issuing tokens.
+ if refusal := s.refuseByCeiling(c, delegated); refusal != nil {
+ return refusal
+ }
+
// Store access token and workspace ID in request context for MCP tools.
ctx := c.Request().Context()
ctx = withAccessToken(ctx, tokenStr)
@@ -251,8 +255,8 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// Normalize the resolved address onto the request so the per-request
// path sees it too: receiving middleware gets each request's headers,
// but never its peer address.
- resolvedIP := callerIP(c.Request())
- c.Request().Header.Set(headerRealIP, resolvedIP)
+ resolvedIP := common.CallerIP(c.Request())
+ c.Request().Header.Set(common.HeaderRealIP, resolvedIP)
ctx = withCallerIP(ctx, resolvedIP)
ctx = withSessionBinding(ctx, sessionBinding{
fingerprint: sessionFingerprint(delegated),
@@ -270,12 +274,6 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// the same name in the oauth2 package, which stores that URI on the grant).
const mcpResourcePath = "/mcp"
-// Caller-IP headers, in the precedence the audit interceptor reads them.
-const (
- headerRealIP = "X-Real-IP"
- headerForwardedFor = "X-Forwarded-For"
-)
-
// RegisterRoutes registers the MCP server routes with Echo.
func (s *Server) RegisterRoutes(e *echo.Echo) {
// MCP Streamable HTTP endpoint with authentication
@@ -404,7 +402,7 @@ func sessionFingerprint(identity auth.DelegatedMCPCredential) string {
func liveRequestMetadata(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
if extra := req.GetExtra(); extra != nil && extra.Header != nil {
- if ip := headerCallerIP(extra.Header); ip != "" {
+ if ip := common.CallerIPFromHeaders(extra.Header); ip != "" {
ctx = withCallerIP(ctx, ip)
}
if token, err := auth.GetTokenFromHeaders(extra.Header); err == nil && token != "" {
@@ -415,34 +413,6 @@ func liveRequestMetadata(next mcp.MethodHandler) mcp.MethodHandler {
}
}
-// headerCallerIP reads the caller IP from request headers, in the order the
-// audit interceptor applies: the proxy-set single IP first, then the standard
-// forwarding chain.
-func headerCallerIP(header http.Header) string {
- if ip := header.Get(headerRealIP); ip != "" {
- return ip
- }
- return header.Get(headerForwardedFor)
-}
-
-// callerIP resolves who made this /mcp request: the forwarding headers if
-// present, otherwise the peer address, whose port is dropped so the value reads
-// as an IP either way. Same precedence the audit interceptor applies to a
-// request that reaches the v1 API directly.
-//
-// The forwarding headers are client-controllable, exactly as they are on that
-// direct path. Reading them preserves the existing trust model rather than
-// introducing one.
-func callerIP(r *http.Request) string {
- if ip := headerCallerIP(r.Header); ip != "" {
- return ip
- }
- if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
- return host
- }
- return r.RemoteAddr
-}
-
// bearerExpiry reads the inbound token's expiry. The JWT parse upstream has
// already rejected expired and malformed tokens, so this only re-surfaces the
// value for the SDK, which requires a non-zero future expiration.
@@ -587,57 +557,6 @@ func (s *Server) unauthorized(c *echo.Context, errDescription string) error {
return echo.NewHTTPError(http.StatusUnauthorized, errDescription)
}
-// mcpConnectionAllowed reports whether an MCP connection may proceed: a ceiling
-// that serves some method class opens a session, one that serves none does not.
-//
-// The rule lives in auth.MCPCeilingServesAnything so this gate and the
-// per-method serving table cannot state the same policy twice; a lint holds the
-// two against each other over the whole enum.
-//
-// UNSPECIFIED is refused rather than read as "never configured":
-// store.GetMCPSettingsUncached already resolves an unset ceiling to
-// READ_WRITE, so a zero value arriving here was resolved by nobody.
-func mcpConnectionAllowed(capability storepb.MCPSetting_Capability) bool {
- return auth.MCPCeilingServesAnything(capability)
-}
-
-// mcpCapability resolves the workspace's effective MCP capability ceiling for
-// the connection gate. A stored value this build cannot interpret — a mistyped
-// enum name, a wrong-typed row — resolves to DISABLED, so the connection is
-// refused and the operator is told the policy is the problem, which is true:
-// no retry fixes it, an admin has to. A read that FAILED returns an error
-// instead, because "your workspace disabled MCP" is a lie during a database
-// blip; the caller answers 503 and the client retries, exactly as it already
-// does when the token audience cannot be resolved.
-//
-// Either way the session does not proceed. The request gate on the internal
-// chain makes the same split on the same two errors — the connection and the
-// per-method gate must never disagree about a workspace's ceiling, nor about
-// which kind of failure the operator is looking at.
-//
-// The resolution itself lives in the store, uncached. Bypassing the setting
-// cache is what makes the kill switch a kill switch: the cache has no TTL and
-// only in-process writes refresh it, so a profile cached as unset would keep
-// admitting MCP after the ceiling was flipped out of band.
-func (s *Server) mcpCapability(ctx context.Context, workspaceID string) (storepb.MCPSetting_Capability, error) {
- settings, err := s.store.GetMCPSettingsUncached(ctx, workspaceID)
- if err != nil {
- if errors.Is(err, store.ErrMCPCapabilityUnreadable) {
- slog.Warn("the stored MCP capability ceiling cannot be interpreted; refusing the connection",
- slog.String("workspace", workspaceID), log.BBError(err))
- return storepb.MCPSetting_DISABLED, nil
- }
- // DISABLED rather than UNSPECIFIED, even though the error is what the
- // caller acts on. UNSPECIFIED is the zero value and means "nobody
- // resolved this"; DISABLED is a decision. mcpConnectionAllowed refuses
- // both, so nothing turns on it today — the point is that the value
- // stays safe to read on its own, in case a later caller logs the error
- // and carries on.
- return storepb.MCPSetting_DISABLED, err
- }
- return settings.Capability, nil
-}
-
// buildResourceMetadataURL returns the absolute URL of the protected resource
// metadata document for the /mcp endpoint. The `/mcp` path suffix matters:
// RFC 9728 §3.3 requires the document's `resource` field to match the resource
diff --git a/backend/api/mcp/server_killswitch_test.go b/backend/api/mcp/server_killswitch_test.go
index 911dc1d9fb..75cc39acea 100644
--- a/backend/api/mcp/server_killswitch_test.go
+++ b/backend/api/mcp/server_killswitch_test.go
@@ -24,9 +24,12 @@ import (
_ "github.com/bytebase/bytebase/backend/plugin/db/pg"
)
-// TestMCPConnectionAllowed pins the connection-level gate: READ_WRITE and
-// READ_ONLY admit a connection, and everything else fails closed — DISABLED,
-// unknown stored values such as the reserved number 2, and the zero value.
+// TestMCPConnectionAllowed pins the rule the connection gate decides from:
+// READ_WRITE and READ_ONLY admit a connection, and everything else fails
+// closed — DISABLED, unknown stored values such as the reserved number 2, and
+// the zero value. The gate reaches it through auth.ClassifyMCPCeiling, which
+// TestMCPCeilingVerdictAdmissionMatchesTheServesPredicate holds against this
+// same predicate over the whole enum.
//
// READ_ONLY is admitted from the cutover, once the SQL clamp made a read-only
// session one that cannot write. What it may then do is decided per method by
@@ -50,7 +53,7 @@ func TestMCPConnectionAllowed(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.capability.String(), func(t *testing.T) {
- require.Equal(t, tt.allowed, mcpConnectionAllowed(tt.capability))
+ require.Equal(t, tt.allowed, auth.MCPCeilingServesAnything(tt.capability))
})
}
}
@@ -297,10 +300,10 @@ func TestMCPCeilingStoredValueFailsClosed(t *testing.T) {
srv, err := NewServer(s, profile, secret, nil)
require.NoError(t, err)
- // The connection verdict alone cannot separate "the ceiling parsed as
- // READ_ONLY" from "the ceiling could not be read", because mcpCapability
- // maps any error to DISABLED and both refuse. So the resolver is asserted
- // directly, on every workspace at once.
+ // The connection's STATUS alone cannot separate "the ceiling parsed as
+ // DISABLED" from "the ceiling could not be read": both are policy and both
+ // answer 403. Its wording does, and TestMCPConnectionDenialEmission pins
+ // that. The resolver is asserted directly here, on every workspace at once.
//
// That doubles as the composite-primary-key check the setting table needs.
// It is keyed (workspace, name), and GetMCPSettingsUncached is a new
@@ -308,10 +311,9 @@ func TestMCPCeilingStoredValueFailsClosed(t *testing.T) {
// return whichever row the scan reached first and apply one tenant's MCP
// ceiling to every other tenant — a kill switch answering for the wrong
// workspace. Every workspace below sits in this one database and must still
- // resolve to its own stored value; the ws-readonly row
- // must resolve as itself rather than as a fail-closed error, which is what
- // separates "the ceiling says read-only" from "the ceiling could not be
- // read" now that both no longer answer the same way at the connection.
+ // resolve to its own stored value; the ws-readonly row must resolve as
+ // itself rather than as a fail-closed error, which is what separates "the
+ // ceiling says read-only" from "the ceiling could not be read".
for workspace, want := range map[string]storepb.MCPSetting_Capability{
"ws-readonly": storepb.MCPSetting_READ_ONLY,
"ws-open": storepb.MCPSetting_READ_WRITE,
diff --git a/backend/api/mcp/store_test.go b/backend/api/mcp/store_test.go
index 1f548921bf..161c618882 100644
--- a/backend/api/mcp/store_test.go
+++ b/backend/api/mcp/store_test.go
@@ -12,6 +12,17 @@ type testServerStore struct {
workspaceProfile *storepb.WorkspaceProfileSetting
capability storepb.MCPSetting_Capability
capabilityErr error
+
+ // auditRows collects what the connection gate recorded, so a test can
+ // assert on the row a denial wrote without a database.
+ auditRows []*storepb.AuditLog
+ auditErr error
+ // writeCtxErr is the write context's error at the moment of the write,
+ // which is what shows the row survives a client that hung up.
+ writeCtxErr error
+ // writeCtxHasDeadline shows the detached write is still bounded: dropping
+ // the request's cancellation also drops its deadline.
+ writeCtxHasDeadline bool
}
func newTestServerStore() *testServerStore {
@@ -37,3 +48,13 @@ func (s *testServerStore) GetMCPSettingsUncached(context.Context, string) (store
func (*testServerStore) DeleteOAuth2RefreshTokensByUserAndClient(context.Context, string, string) error {
return nil
}
+
+func (s *testServerStore) CreateAuditLog(ctx context.Context, _ string, payload *storepb.AuditLog) error {
+ s.writeCtxErr = ctx.Err()
+ _, s.writeCtxHasDeadline = ctx.Deadline()
+ if s.auditErr != nil {
+ return s.auditErr
+ }
+ s.auditRows = append(s.auditRows, payload)
+ return nil
+}
diff --git a/backend/api/mcp/tool_change.go b/backend/api/mcp/tool_change.go
index 220a188122..f520cdb9ca 100644
--- a/backend/api/mcp/tool_change.go
+++ b/backend/api/mcp/tool_change.go
@@ -151,7 +151,8 @@ propose_database_change(database="app", sql="UPDATE orders SET status='shipped'
- Plan checks run automatically; results included in response when available.
- Requires bb.sheets.create, bb.plans.create, bb.issues.create permissions.
- If createRollout=true but policy gates aren't satisfied, returns success with rolloutCreated=false and a reason.
-- Masked data: a masked column reads back as "******". That is a placeholder, not a value anything holds. Any change containing it is refused, because writing it back would overwrite the real value. Ask a human to make the change in the Bytebase console instead.`
+- Masked data: a masked column reads back as "******". That is a placeholder, not a value anything holds. Any change containing it is refused, because writing it back would overwrite the real value. Ask a human to make the change in the Bytebase console instead.
+- Workspace ceiling: the workspace's MCP policy decides whether changes are served at all, and under a read-only ceiling this tool is refused before anything is created. Read it with call_api(operationId="bytebase.v1.WorkspaceService.GetMCPInfo") before planning a change.`
func (s *Server) registerChangeTool() {
mcp.AddTool(s.mcpServer, &mcp.Tool{
diff --git a/backend/api/mcp/tool_http.go b/backend/api/mcp/tool_http.go
index 9c72dd84c9..710da9fbb2 100644
--- a/backend/api/mcp/tool_http.go
+++ b/backend/api/mcp/tool_http.go
@@ -13,6 +13,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/common/stacktrace"
)
@@ -69,7 +70,7 @@ func (s *Server) apiRequest(ctx context.Context, path string, body any) (*apiRes
// no peer address to fall back to, so without this the origin of every
// MCP-originated action would be blank.
if ip := getCallerIP(ctx); ip != "" {
- httpReq.Header.Set(headerRealIP, ip)
+ httpReq.Header.Set(common.HeaderRealIP, ip)
}
// Mint the credential for this call. Per call, not per session: see
diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.go
index 8e16d0bc1b..c9c7fd4e93 100644
--- a/backend/api/mcp/tool_query.go
+++ b/backend/api/mcp/tool_query.go
@@ -58,7 +58,8 @@ query_database(database="employee_db", statement="SELECT * FROM users LIMIT 10")
query_database(database="employee", instance="prod-pg", statement="SELECT count(*) FROM orders")
**Notes:**
-- Masked data: a masked column reads back as "******". That is a placeholder, not a value anything holds, so never write it back and never filter on it. Any statement containing it is refused.`
+- Masked data: a masked column reads back as "******". That is a placeholder, not a value anything holds, so never write it back and never filter on it. Any statement containing it is refused.
+- Workspace ceiling: the workspace's MCP policy decides what is served here, and under a read-only ceiling any statement that is not a read is refused whole. Read it with call_api(operationId="bytebase.v1.WorkspaceService.GetMCPInfo") — it also reports how deeply read-only is enforced on each engine.`
func (s *Server) registerQueryTool() {
mcp.AddTool(s.mcpServer, &mcp.Tool{
diff --git a/backend/api/oauth2/authorize.go b/backend/api/oauth2/authorize.go
index ba967674c2..f2dbc0021a 100644
--- a/backend/api/oauth2/authorize.go
+++ b/backend/api/oauth2/authorize.go
@@ -140,6 +140,19 @@ func (s *Service) handleAuthorizePost(c *echo.Context) error {
return oauth2ErrorRedirect(c, redirectURI, state, failure.code, failure.description)
}
+ // Every grant this server issues is an MCP grant, so a workspace whose MCP
+ // ceiling serves nothing must not be handed one.
+ refused, err := s.refuseConsentByCeiling(c, consentAttempt{
+ user: consenting,
+ clientID: clientID,
+ params: params,
+ redirectURI: redirectURI,
+ state: state,
+ })
+ if refused {
+ return err
+ }
+
code, err := generateAuthCode()
if err != nil {
return oauth2ErrorRedirect(c, redirectURI, state, "server_error", "failed to generate code")
diff --git a/backend/api/oauth2/consent_audit.go b/backend/api/oauth2/consent_audit.go
new file mode 100644
index 0000000000..395da15777
--- /dev/null
+++ b/backend/api/oauth2/consent_audit.go
@@ -0,0 +1,153 @@
+package oauth2
+
+import (
+ "context"
+ "html"
+ "log/slog"
+ "net/http"
+ "strings"
+
+ "github.com/labstack/echo/v5"
+ spb "google.golang.org/genproto/googleapis/rpc/status"
+ "google.golang.org/grpc/codes"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// One heading per way the workspace's MCP policy refuses a consent. Only the
+// heading is local: it is page copy, this is its one consumer, and the three
+// states have different fixes, so a heading naming the wrong one is the part a
+// hurried reader acts on. The sentence under it is the verdict's own
+// (auth.MCPCeilingVerdict.Refusal), shared with every other door.
+var consentHeadings = map[auth.MCPCeilingVerdict]string{
+ auth.MCPCeilingDisabled: "MCP access is turned off",
+ auth.MCPCeilingUnreadable: "This workspace's MCP setting cannot be read",
+ auth.MCPCeilingUnserved: "This workspace's MCP setting is not one this version supports",
+}
+
+// consentAttempt is the consent a ceiling check may refuse: who is consenting,
+// which client asked, what was asked for, and where the client waits.
+type consentAttempt struct {
+ user consentingUser
+ clientID string
+ params grantParams
+ redirectURI string
+ state string
+}
+
+// mcpCeilingReader is the whole of what the ceiling check needs from the store.
+// *store.Store satisfies it; a test supplies its own, which is what lets the
+// outage arm be exercised — a real store cannot be made to fail a single read.
+type mcpCeilingReader interface {
+ GetMCPSettingsUncached(ctx context.Context, workspace string) (store.MCPSettings, error)
+}
+
+// refuseConsentByCeiling holds a consent about to be granted against the
+// workspace's MCP capability ceiling. The bool reports whether it has already
+// written the response, which is what the caller must branch on: echo's c.HTML
+// returns a nil error when it succeeds, so a nil error cannot mean the consent
+// may proceed. Reading it that way issues an authorization code underneath the
+// refusal page.
+//
+// It runs after the grant parameters are validated, not before, so the audit
+// row records the resource and scope that were asked for and a malformed
+// request still gets the error about itself.
+//
+// auth.ClassifyMCPCeiling decides, so this door and the /mcp gate cannot
+// disagree about one workspace — and a token minted under a ceiling that serves
+// nothing would be a credential for a door that will refuse it.
+func (s *Service) refuseConsentByCeiling(c *echo.Context, attempt consentAttempt) (bool, error) {
+ ctx := c.Request().Context()
+ settings, err := s.mcpCeiling.GetMCPSettingsUncached(ctx, attempt.user.workspaceID)
+ verdict := auth.ClassifyMCPCeiling(settings.Capability, err)
+ if verdict == auth.MCPCeilingServes {
+ return false, nil
+ }
+ if !verdict.IsPolicy() {
+ // An outage, not a verdict: telling the user their admin disabled MCP
+ // during a database blip sends them to an admin with nothing to fix.
+ slog.Error("failed to read the MCP capability ceiling; cannot grant the consent", log.BBError(err))
+ return true, oauth2ErrorRedirect(c, attempt.redirectURI, attempt.state, "temporarily_unavailable",
+ verdict.Refusal())
+ }
+ if err != nil {
+ slog.Warn("the stored MCP capability ceiling cannot be interpreted; refusing the consent",
+ slog.String("workspace", attempt.user.workspaceID), log.BBError(err))
+ }
+ return true, s.refuseConsent(c, attempt, verdict)
+}
+
+// refuseConsent records the refusal and renders the page the user sees.
+//
+// A page rather than the usual error redirect: the redirect hands the failure
+// to the MCP client, and no client knows what to ask an admin for. Nothing was
+// connected, so there is nothing to resume; the link back is there for a user
+// who wants their client told.
+//
+// The row is written here for the same reason the connection gate writes its
+// own: this route is echo, so no interceptor sees it.
+func (s *Service) refuseConsent(c *echo.Context, attempt consentAttempt, verdict auth.MCPCeilingVerdict) error {
+ row := &storepb.AuditLog{
+ Parent: common.FormatWorkspace(attempt.user.workspaceID),
+ Method: common.AuditMethodMCPConsentApprove,
+ Resource: common.FormatWorkspace(attempt.user.workspaceID),
+ Severity: storepb.AuditLog_INFO,
+ User: common.FormatUserEmail(attempt.user.email),
+ Status: &spb.Status{
+ Code: int32(codes.PermissionDenied),
+ Message: verdict.Refusal(),
+ },
+ RequestMetadata: common.RequestMetadataFromHTTP(c.Request()),
+ // The MCP provenance this flow has: the client asking, and the
+ // resource and scope it asked for. No correlation ID — that is minted
+ // at /mcp, and this attempt never got there.
+ McpDelegation: &storepb.MCPDelegation{
+ Scope: attempt.params.scope,
+ Resource: attempt.params.resource,
+ ClientId: attempt.clientID,
+ },
+ }
+ common.RecordOutOfBandAudit(c.Request().Context(), s.store,
+ s.profile.RuntimeEnableAuditLogStdout.Load(), attempt.user.workspaceID, row)
+ return c.HTML(http.StatusForbidden, consentRefusedHTML(verdict, attempt.redirectURI, attempt.state))
+}
+
+// consentRefusedHTML renders the refusal. Inline styles only: the global CSP
+// allows inline style and blocks inline script, so the page carries no
+// behavior.
+func consentRefusedHTML(verdict auth.MCPCeilingVerdict, redirectURI, state string) string {
+ heading := html.EscapeString(consentHeadings[verdict])
+ page := `<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>` + heading + `</title>
+</head>
+<body style="font-family: system-ui, sans-serif; max-width: 32rem; margin: 4rem auto; padding: 0 1rem; line-height: 1.5;">
+<h1 style="font-size: 1.25rem;">` + heading + `</h1>
+<p>` + html.EscapeString(asSentence(verdict.Refusal())) + `</p>
+<p>Nothing was connected.</p>`
+ if back, err := oauth2ErrorRedirectURL(redirectURI, state, "access_denied",
+ "the workspace MCP policy refused this authorization"); err == nil {
+ page += `
+<p><a href="` + html.EscapeString(back) + `">Return to the application</a></p>`
+ }
+ return page + `
+</body>
+</html>`
+}
+
+// asSentence renders a shared refusal as page prose. The shared form is
+// lowercase and unterminated so every other door can compose it into a larger
+// error; this is the one door that shows it on its own.
+func asSentence(refusal string) string {
+ if refusal == "" {
+ return ""
+ }
+ return strings.ToUpper(refusal[:1]) + refusal[1:] + "."
+}
diff --git a/backend/api/oauth2/consent_ceiling_test.go b/backend/api/oauth2/consent_ceiling_test.go
new file mode 100644
index 0000000000..1b96fa6d06
--- /dev/null
+++ b/backend/api/oauth2/consent_ceiling_test.go
@@ -0,0 +1,421 @@
+package oauth2
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/labstack/echo/v5"
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+
+ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
+)
+
+// TestConsentCeiling pins the ceiling check this flow did not have.
+//
+// Before it, the authorization flow knew nothing about the MCP ceiling: a user
+// in a workspace with MCP turned off approved the consent, was issued a real
+// authorization code, exchanged it for a real token, and only learned at /mcp
+// that the door refuses them. The credential outlived the misunderstanding,
+// and nothing recorded that anyone had tried.
+//
+// Two halves, and they are separable on purpose. The refusal is the
+// enforcement and does not depend on the row; the row is what an operator
+// sees and does not change the verdict. Removing the write leaves every
+// refusal assertion below green and fails only the row assertions.
+func TestConsentCeiling(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES
+ ('ws-disabled'), ('ws-readonly'), ('ws-unset'), ('ws-typo'), ('ws-reserved');
+ INSERT INTO principal (name, email, password_hash) VALUES ('demo', '[email protected]', 'unused');
+ INSERT INTO oauth2_client (client_id, workspace, client_secret_hash, config)
+ VALUES ('client-A', NULL, 'unused-hash', '{"clientName":"test","redirectUris":["http://localhost/cb"],"grantTypes":["authorization_code","refresh_token"],"tokenEndpointAuthMethod":"none"}'::jsonb);
+ INSERT INTO setting (name, workspace, value) VALUES
+ ('MCP', 'ws-disabled', '{"capability":"DISABLED"}'),
+ ('MCP', 'ws-readonly', '{"capability":"READ_ONLY"}'),
+ ('MCP', 'ws-typo', '{"capability":"READ_ONLYY"}'),
+ ('MCP', 'ws-reserved', '{"capability":2}');
+ `)
+ require.NoError(t, err)
+
+ pgURL := fmt.Sprintf(
+ "host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort(),
+ )
+ st, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+
+ s := newTestService(st, "https://bb.example.com")
+
+ auditRows := func(t *testing.T, workspace string) []*store.AuditLog {
+ t.Helper()
+ logs, err := st.SearchAuditLogs(ctx, &store.AuditLogFind{Workspace: workspace})
+ require.NoError(t, err)
+ return logs
+ }
+
+ t.Run("a disabled workspace refuses the consent and records the attempt", func(t *testing.T) {
+ rec := consentTo(t, s, "ws-disabled")
+
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ body := rec.Body.String()
+ require.Contains(t, body, "MCP access is turned off")
+ require.Contains(t, body, "turned MCP access off for this workspace")
+ require.Contains(t, body, "<title>MCP access is turned off</title>")
+ require.Contains(t, body, "in the workspace settings", "the page names what to ask an admin for")
+ require.NotContains(t, body, "code=", "no authorization code may be issued")
+
+ // Against the table, not only the page: a refusal that rendered but
+ // still wrote a code would leave a usable credential behind.
+ var codes int
+ require.NoError(t, db.QueryRowContext(ctx,
+ `SELECT count(*) FROM oauth2_authorization_code`).Scan(&codes))
+ require.Zero(t, codes, "a refused consent must persist no authorization code")
+
+ rows := auditRows(t, "ws-disabled")
+ require.Len(t, rows, 1)
+ row := rows[0].Payload
+ require.Equal(t, "/bytebase.mcp.Consent/Approve", row.GetMethod())
+ require.Equal(t, "workspaces/ws-disabled", row.GetParent())
+ require.Equal(t, "users/[email protected]", row.GetUser())
+ require.EqualValues(t, 7, row.GetStatus().GetCode(), "PermissionDenied")
+ require.Contains(t, row.GetStatus().GetMessage(), "turned MCP access off")
+
+ // The MCP marker, so `mcp == true` finds this alongside the
+ // connection denial the same user would have hit next.
+ require.NotNil(t, row.GetMcpDelegation())
+ require.Equal(t, testClientID, row.GetMcpDelegation().GetClientId())
+ require.Equal(t, "mcp:read-only", row.GetMcpDelegation().GetScope())
+ require.Equal(t, testResource, row.GetMcpDelegation().GetResource())
+ require.Empty(t, row.GetMcpDelegation().GetCorrelationId(),
+ "a consent never reached the /mcp boundary that mints one")
+ })
+
+ t.Run("a stored ceiling nobody can read is refused as a typo, not as policy", func(t *testing.T) {
+ rec := consentTo(t, s, "ws-typo")
+
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Contains(t, rec.Body.String(), "not one this build understands")
+ // The heading follows the verdict: a stored value nobody can read is
+ // not "an admin turned MCP off", and the heading is what a hurried
+ // reader acts on.
+ require.Contains(t, rec.Body.String(), "MCP setting cannot be read")
+ require.NotContains(t, rec.Body.String(), "MCP access is turned off")
+
+ rows := auditRows(t, "ws-typo")
+ require.Len(t, rows, 1)
+ require.Contains(t, rows[0].Payload.GetStatus().GetMessage(), "not one this build understands")
+ })
+
+ t.Run("a ceiling this build does not serve is refused too", func(t *testing.T) {
+ rec := consentTo(t, s, "ws-reserved")
+
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Contains(t, rec.Body.String(), "not one this build serves")
+ require.Contains(t, rec.Body.String(), "not one this version supports")
+ require.NotContains(t, rec.Body.String(), "MCP access is turned off")
+ require.Len(t, auditRows(t, "ws-reserved"), 1)
+ })
+
+ t.Run("a serving ceiling consents and records nothing", func(t *testing.T) {
+ for _, workspace := range []string{"ws-readonly", "ws-unset"} {
+ t.Run(workspace, func(t *testing.T) {
+ rec := consentTo(t, s, workspace)
+
+ require.Equal(t, http.StatusOK, rec.Code)
+ redirect := redirectTargetOf(t, rec.Body.String())
+ require.Empty(t, redirect.Query().Get("error"))
+ require.NotEmpty(t, redirect.Query().Get("code"))
+
+ require.Empty(t, auditRows(t, workspace),
+ "this gate records refusals; a granted consent is the token endpoint's story")
+ })
+ }
+ })
+}
+
+// TestConsentCeilingRefusalIsNotAWideningPath pins that the refusal cannot be
+// walked around by asking for a different scope: the ceiling decides whether
+// any grant is issued at all, before the requested mode is considered.
+func TestConsentCeilingRefusalIsNotAWideningPath(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('ws-disabled');
+ INSERT INTO principal (name, email, password_hash) VALUES ('demo', '[email protected]', 'unused');
+ INSERT INTO oauth2_client (client_id, workspace, client_secret_hash, config)
+ VALUES ('client-A', NULL, 'unused-hash', '{"clientName":"test","redirectUris":["http://localhost/cb"],"grantTypes":["authorization_code","refresh_token"],"tokenEndpointAuthMethod":"none"}'::jsonb);
+ INSERT INTO setting (name, workspace, value) VALUES ('MCP', 'ws-disabled', '{"capability":"DISABLED"}');
+ `)
+ require.NoError(t, err)
+
+ pgURL := fmt.Sprintf(
+ "host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort(),
+ )
+ st, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+ s := newTestService(st, "https://bb.example.com")
+
+ for _, scope := range []string{"mcp:read-only", "mcp:read-write", ""} {
+ rec := consentTo(t, s, "ws-disabled", url.Values{"scope": {scope}})
+ require.Equal(t, http.StatusForbidden, rec.Code, "scope %q", scope)
+ }
+ logs, err := st.SearchAuditLogs(ctx, &store.AuditLogFind{Workspace: "ws-disabled"})
+ require.NoError(t, err)
+ require.Len(t, logs, 3, "every attempt is recorded, not just the first")
+}
+
+// consentTo posts an approved consent form as a user whose session is in the
+// given workspace, and returns the raw response so a caller can read either the
+// refusal page or the meta-refresh carrying the code.
+func consentTo(t *testing.T, s *Service, workspaceID string, extra ...url.Values) *httptest.ResponseRecorder {
+ t.Helper()
+
+ challenge := sha256.Sum256([]byte(testCodeVerifier))
+ form := url.Values{
+ "client_id": {testClientID},
+ "redirect_uri": {testRedirectURI},
+ "state": {"state-1"},
+ "code_challenge": {base64.RawURLEncoding.EncodeToString(challenge[:])},
+ "code_challenge_method": {"S256"},
+ "action": {"allow"},
+ "resource": {testResource},
+ "scope": {"mcp:read-only"},
+ }
+ for _, values := range extra {
+ for name, value := range values {
+ form[name] = value
+ }
+ }
+
+ sessionToken, err := auth.GenerateAccessToken(testUserEmail, workspaceID, testSecret, time.Hour)
+ require.NoError(t, err)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/oauth2/authorize", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Authorization", "Bearer "+sessionToken)
+ rec := httptest.NewRecorder()
+
+ e := echo.New()
+ s.RegisterRoutes(e)
+ e.ServeHTTP(rec, req)
+ return rec
+}
+
+// TestConsentCeilingOutageIsNotARefusal pins the arm a real store cannot be
+// asked to take: the ceiling read itself fails.
+//
+// It is the one exit that returns a nil error while having written a response,
+// which is the exact shape this flow already got wrong once — a caller reading
+// the nil as "may proceed" mints an authorization code underneath a 200 the
+// client reads as an error. And it must not read as a refusal: telling a user
+// their admin disabled MCP during a database blip sends them to an admin with
+// nothing to fix.
+func TestConsentCeilingOutageIsNotARefusal(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('ws-outage');
+ INSERT INTO principal (name, email, password_hash) VALUES ('demo', '[email protected]', 'unused');
+ INSERT INTO oauth2_client (client_id, workspace, client_secret_hash, config)
+ VALUES ('client-A', NULL, 'unused-hash', '{"clientName":"test","redirectUris":["http://localhost/cb"],"grantTypes":["authorization_code","refresh_token"],"tokenEndpointAuthMethod":"none"}'::jsonb);
+ `)
+ require.NoError(t, err)
+
+ pgURL := fmt.Sprintf(
+ "host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort(),
+ )
+ st, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+
+ s := newTestService(st, "https://bb.example.com")
+ s.mcpCeiling = failingCeilingReader{err: errors.New("connection refused")}
+
+ rec := consentTo(t, s, "ws-outage")
+
+ // The client is told to retry, in its own vocabulary, and gets no code.
+ require.Equal(t, http.StatusOK, rec.Code, "an error redirect is a 200 carrying the error")
+ redirect := redirectTargetOf(t, rec.Body.String())
+ require.Equal(t, "temporarily_unavailable", redirect.Query().Get("error"))
+ require.Empty(t, redirect.Query().Get("code"), "an outage must not mint a credential either")
+
+ var codes int
+ require.NoError(t, db.QueryRowContext(ctx, `SELECT count(*) FROM oauth2_authorization_code`).Scan(&codes))
+ require.Zero(t, codes)
+
+ logs, err := st.SearchAuditLogs(ctx, &store.AuditLogFind{Workspace: "ws-outage"})
+ require.NoError(t, err)
+ require.Empty(t, logs, "an outage recorded as a policy denial is a decision nobody made")
+}
+
+// failingCeilingReader is a ceiling read that fails, which is what a real store
+// cannot be made to do for one call.
+type failingCeilingReader struct{ err error }
+
+func (f failingCeilingReader) GetMCPSettingsUncached(context.Context, string) (store.MCPSettings, error) {
+ return store.MCPSettings{}, f.err
+}
+
+// TestTokenIssuanceRechecksTheCeiling pins the half a consent-time check alone
+// would miss.
+//
+// The consent decision is captured once and reused at every later issuance: an
+// authorization code outlives the consent by ten minutes and a refresh token by
+// thirty days, so a grant consented while MCP was on keeps minting access
+// tokens long after an admin turns MCP off. The workspace membership check on
+// this endpoint exists for the same reason, and says so in its own comment.
+func TestTokenIssuanceRechecksTheCeiling(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('ws-test');
+ INSERT INTO principal (name, email, password_hash) VALUES ('demo', '[email protected]', 'unused');
+ INSERT INTO oauth2_client (client_id, workspace, client_secret_hash, config)
+ VALUES ('client-A', NULL, 'unused-hash', '{"clientName":"test","redirectUris":["http://localhost/cb"],"grantTypes":["authorization_code","refresh_token"],"tokenEndpointAuthMethod":"none"}'::jsonb);
+ `)
+ require.NoError(t, err)
+
+ pgURL := fmt.Sprintf(
+ "host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort(),
+ )
+ st, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+ s := newTestService(st, "https://bb.example.com")
+
+ // Consent while MCP is on, so the grant is genuine and only the ceiling
+ // moves underneath it.
+ code := consentOK(t, s, url.Values{"resource": {testResource}, "scope": {"mcp:read-only"}})
+ tokens := tokenOK(t, s, url.Values{
+ "grant_type": {"authorization_code"},
+ "code": {code},
+ "redirect_uri": {testRedirectURI},
+ "code_verifier": {testCodeVerifier},
+ "client_id": {testClientID},
+ })
+ require.NotEmpty(t, tokens.RefreshToken)
+
+ _, err = db.ExecContext(ctx,
+ `INSERT INTO setting (name, workspace, value) VALUES ('MCP', 'ws-test', '{"capability":"DISABLED"}')`)
+ require.NoError(t, err)
+
+ refresh := func() *httptest.ResponseRecorder {
+ return postToken(t, s, url.Values{
+ "grant_type": {"refresh_token"},
+ "refresh_token": {tokens.RefreshToken},
+ "client_id": {testClientID},
+ })
+ }
+
+ // The refusal must read as reversible, not as a dead grant. invalid_grant
+ // is what legacyGrantFailure uses to make a compliant client discard the
+ // credential and rerun the OAuth flow — exactly what this path retains the
+ // credential to avoid — so a ceiling refusal must not borrow it.
+ t.Run("a refresh stops re-issuing, retryably", func(t *testing.T) {
+ rec := refresh()
+ require.Equal(t, http.StatusServiceUnavailable, rec.Code, rec.Body.String())
+ require.Equal(t, "temporarily_unavailable", errorCode(t, rec))
+ require.NotEqual(t, "invalid_grant", errorCode(t, rec),
+ "a compliant client discards the grant on invalid_grant, and this one must keep it")
+ require.Contains(t, errorDescription(t, rec), "turned MCP access off")
+ })
+
+ // The refusal must not burn the credential it refuses. The ceiling is a
+ // toggle, and its own message tells the user raising it restores service —
+ // so an hour of MCP being off must not cost every client its refresh token
+ // and force a fresh interactive consent. The consume is single-use and
+ // irreversible, so this only holds while the check runs before it.
+ t.Run("the refused refresh survives the policy being reversed", func(t *testing.T) {
+ var left int
+ require.NoError(t, db.QueryRowContext(ctx,
+ `SELECT count(*) FROM oauth2_refresh_token`).Scan(&left))
+ require.Equal(t, 1, left, "a refused refresh must not consume the token")
+
+ _, err := db.ExecContext(ctx,
+ `UPDATE setting SET value = '{"capability":"READ_WRITE"}' WHERE workspace = 'ws-test' AND name = 'MCP'`)
+ require.NoError(t, err)
+
+ rec := refresh()
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+
+ // Put it back so the subtest below still meets a refusing ceiling.
+ _, err = db.ExecContext(ctx,
+ `UPDATE setting SET value = '{"capability":"DISABLED"}' WHERE workspace = 'ws-test' AND name = 'MCP'`)
+ require.NoError(t, err)
+ })
+
+ t.Run("an unexchanged code stops exchanging, and is not burned either", func(t *testing.T) {
+ // A code minted before the ceiling moved. The consent that produced it
+ // was allowed; the exchange is not.
+ s.mcpCeiling = servingCeilingReader{}
+ fresh := consentOK(t, s, url.Values{"resource": {testResource}, "scope": {"mcp:read-only"}})
+ s.mcpCeiling = st
+
+ exchange := func() *httptest.ResponseRecorder {
+ return postToken(t, s, url.Values{
+ "grant_type": {"authorization_code"},
+ "code": {fresh},
+ "redirect_uri": {testRedirectURI},
+ "code_verifier": {testCodeVerifier},
+ "client_id": {testClientID},
+ })
+ }
+
+ rec := exchange()
+ require.Equal(t, http.StatusServiceUnavailable, rec.Code, rec.Body.String())
+ require.Equal(t, "temporarily_unavailable", errorCode(t, rec))
+
+ var left int
+ require.NoError(t, db.QueryRowContext(ctx,
+ `SELECT count(*) FROM oauth2_authorization_code`).Scan(&left))
+ require.Equal(t, 1, left, "a refused exchange must not consume the code")
+
+ _, err := db.ExecContext(ctx,
+ `UPDATE setting SET value = '{"capability":"READ_WRITE"}' WHERE workspace = 'ws-test' AND name = 'MCP'`)
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, exchange().Code, "the same code exchanges once the ceiling is raised")
+ })
+}
+
+// servingCeilingReader lets a consent through so the test can mint a grant that
+// the live ceiling would now refuse.
+type servingCeilingReader struct{}
+
+func (servingCeilingReader) GetMCPSettingsUncached(context.Context, string) (store.MCPSettings, error) {
+ return store.MCPSettings{Capability: storepb.MCPSetting_READ_WRITE}, nil
+}
diff --git a/backend/api/oauth2/oauth2.go b/backend/api/oauth2/oauth2.go
index 6ed9e03789..ea5f51ac8e 100644
--- a/backend/api/oauth2/oauth2.go
+++ b/backend/api/oauth2/oauth2.go
@@ -49,13 +49,17 @@ type Service struct {
store *store.Store
profile *config.Profile
secret string
+
+ // mcpCeiling is narrowed to an interface so a test can make the read fail.
+ mcpCeiling mcpCeilingReader
}
-func NewService(store *store.Store, profile *config.Profile, secret string) *Service {
+func NewService(stores *store.Store, profile *config.Profile, secret string) *Service {
return &Service{
- store: store,
- profile: profile,
- secret: secret,
+ store: stores,
+ profile: profile,
+ secret: secret,
+ mcpCeiling: stores,
}
}
@@ -244,11 +248,24 @@ func oauth2Error(c *echo.Context, statusCode int, errorCode, description string)
}
func oauth2ErrorRedirect(c *echo.Context, redirectURI, state, errorCode, description string) error {
- u, err := url.Parse(redirectURI)
+ target, err := oauth2ErrorRedirectURL(redirectURI, state, errorCode, description)
if err != nil {
slog.Error("failed to parse redirect URI for OAuth2 error redirect", slog.String("redirectURI", redirectURI), log.BBError(err))
return oauth2Error(c, http.StatusInternalServerError, errorCode, description)
}
+ // Return HTML page that redirects to callback URL
+ // This avoids CSP form-action restrictions
+ return c.HTML(http.StatusOK, buildRedirectHTML(target))
+}
+
+// oauth2ErrorRedirectURL builds the client callback carrying an RFC 6749 error.
+// Split out so a refusal that renders its own page can still offer the link
+// back, rather than deciding between telling the user and telling the client.
+func oauth2ErrorRedirectURL(redirectURI, state, errorCode, description string) (string, error) {
+ u, err := url.Parse(redirectURI)
+ if err != nil {
+ return "", err
+ }
q := u.Query()
q.Set("error", errorCode)
q.Set("error_description", description)
@@ -256,9 +273,7 @@ func oauth2ErrorRedirect(c *echo.Context, redirectURI, state, errorCode, descrip
q.Set("state", state)
}
u.RawQuery = q.Encode()
- // Return HTML page that redirects to callback URL
- // This avoids CSP form-action restrictions
- return c.HTML(http.StatusOK, buildRedirectHTML(u.String()))
+ return u.String(), nil
}
// buildRedirectHTML creates an HTML page that redirects to the given URL.
diff --git a/backend/api/oauth2/token.go b/backend/api/oauth2/token.go
index 09bab32b41..b8b2d6a594 100644
--- a/backend/api/oauth2/token.go
+++ b/backend/api/oauth2/token.go
@@ -126,6 +126,10 @@ func (s *Service) handleAuthorizationCodeGrant(c *echo.Context, client *store.OA
return tokenFailure(c, failure)
}
+ if failure := s.refuseIssuanceByCeiling(ctx, grantWorkspace(authCode.Workspace, client.Workspace)); failure != nil {
+ return tokenFailure(c, failure)
+ }
+
// Consume the code after all validations pass. This atomic delete is the
// single-use gate: PKCE is verified above so a failed verifier never burns
// the code, and concurrent redemptions race here so only the caller that
@@ -235,12 +239,17 @@ func legacyGrantFailure() *oauth2Failure {
}
// tokenFailure renders a helper's refusal as an RFC 6749 token-endpoint error.
-// server_error is the only 500-class code these helpers produce; every other
-// code is a client error.
+// Two codes are not client errors and must not answer 4xx, which is what tells
+// a client to stop and re-authorize: server_error is a fault, and
+// temporarily_unavailable is a policy state an admin reverses.
func tokenFailure(c *echo.Context, failure *oauth2Failure) error {
status := http.StatusBadRequest
- if failure.code == "server_error" {
+ switch failure.code {
+ case "server_error":
status = http.StatusInternalServerError
+ case "temporarily_unavailable":
+ status = http.StatusServiceUnavailable
+ default:
}
return oauth2Error(c, status, failure.code, failure.description)
}
@@ -259,6 +268,10 @@ func (s *Service) handleRefreshTokenGrant(c *echo.Context, client *store.OAuth2C
}
tokenHash := auth.HashToken(req.RefreshToken)
+ if failure := s.refuseIssuanceByCeiling(ctx, grantWorkspace(refreshToken.Workspace, client.Workspace)); failure != nil {
+ return tokenFailure(c, failure)
+ }
+
// Consume the refresh token after validations pass. This atomic delete is
// the single-use rotation gate: concurrent refreshes race here so only the
// caller that actually claims the row issues a new pair. A consume failure
@@ -417,6 +430,57 @@ func resolveBoundWorkspace(ctx context.Context, resolver workspaceResolver, saas
return workspaceID, nil
}
+// grantWorkspace is the workspace a stored grant is bound to: the one recorded
+// on it, or the legacy client's backfilled workspace. It is resolveBoundWorkspace's
+// first two lines, without the membership check — the ceiling is a property of
+// the workspace, and asking who the user is comes later.
+func grantWorkspace(issuedWorkspace, clientWorkspace string) string {
+ if issuedWorkspace != "" {
+ return issuedWorkspace
+ }
+ return clientWorkspace
+}
+
+// refuseIssuanceByCeiling holds a grant about to be exchanged against the
+// workspace's MCP capability ceiling, and reports why it refused, or nil to
+// proceed. It returns an *oauth2Failure rather than rendering: a helper that
+// renders returns whatever c.JSON returns, which is nil when it succeeds, so
+// its caller cannot tell "refused" from "carry on" — and here carrying on
+// issues the token underneath the refusal.
+//
+// It runs BEFORE the single-use consume, for the reason PKCE does: a refusal
+// must not burn the credential it refuses. The ceiling is a toggle an admin
+// flips back, so consuming first would turn an hour of MCP being off into every
+// client permanently losing its refresh token — and the message it returns
+// says raising the ceiling restores service, which would then be false.
+// Membership is different and stays after the consume: losing it is a one-way
+// revocation where killing the grant is the point.
+//
+// No audit row: this endpoint is machine-to-machine, and the two doors a person
+// and a session meet carry the record.
+func (s *Service) refuseIssuanceByCeiling(ctx context.Context, workspaceID string) *oauth2Failure {
+ if workspaceID == "" {
+ // An unbound legacy grant. resolveBoundWorkspace refuses it after the
+ // consume with the error that names the real problem.
+ return nil
+ }
+ settings, err := s.mcpCeiling.GetMCPSettingsUncached(ctx, workspaceID)
+ switch verdict := auth.ClassifyMCPCeiling(settings.Capability, err); {
+ case verdict == auth.MCPCeilingServes:
+ return nil
+ case verdict.IsPolicy():
+ // NOT invalid_grant: a compliant client discards the grant on it (see
+ // legacyGrantFailure, which uses it for that), and this credential is
+ // deliberately kept so an admin can toggle the ceiling back.
+ // temporarily_unavailable is outside RFC 6749 §5.2, which enumerates
+ // ways the request or the grant is wrong; this is neither.
+ return &oauth2Failure{code: "temporarily_unavailable", description: verdict.Refusal()}
+ default:
+ slog.Error("failed to read the MCP capability ceiling; cannot issue a token", log.BBError(err))
+ return &oauth2Failure{code: "server_error", description: verdict.Refusal()}
+ }
+}
+
// issueTokens issues a new OAuth2 access token (and refresh token, when the
// grant supports it) for the given consented grant. Everything in the grant is
// sourced from the authorization code or refresh token being exchanged, not from
diff --git a/backend/api/v1/audit.go b/backend/api/v1/audit.go
index 7deeaddbb9..58c4cb41e2 100644
--- a/backend/api/v1/audit.go
+++ b/backend/api/v1/audit.go
@@ -29,10 +29,6 @@ import (
)
const (
- // maxAuditPayloadChars is the maximum characters for request/response payloads in stdout logs.
- // Set to 100KB (102400 chars) to match AWS CloudTrail industry standard for audit logs.
- maxAuditPayloadChars = 102400
-
// unencodablePayload stands in for a payload protojson refused, so the row
// records that something was there and could not be written down.
unencodablePayload = `{"_bytebase":"payload could not be encoded"}`
@@ -405,7 +401,7 @@ func (in *AuditInterceptor) createAuditLog(ctx context.Context, e *auditEntry) e
// Log audit event to stdout using slog (if enabled)
if in.profile.RuntimeEnableAuditLogStdout.Load() {
- logAuditToStdout(ctx, p)
+ common.LogAuditToStdout(ctx, p)
}
}
@@ -430,103 +426,6 @@ func mcpDelegationFromAuthContext(authContext *common.AuthContext) *storepb.MCPD
}
}
-// logAuditToStdout writes audit log events to stdout using Go's standard slog library.
-// Output format is controlled by the global slog handler (JSON in production, text in dev).
-// Logs include a "log_type": "audit" field to distinguish from application logs.
-// This is a best-effort operation - errors are not returned to avoid failing the audit flow.
-func logAuditToStdout(ctx context.Context, p *storepb.AuditLog) {
- attrs := []slog.Attr{
- slog.String("log_type", "audit"),
- slog.String("parent", p.Parent),
- slog.String("method", p.Method),
- }
-
- if p.Resource != "" {
- attrs = append(attrs, slog.String("resource", p.Resource))
- }
- if p.User != "" {
- attrs = append(attrs, slog.String("user", p.User))
- }
-
- if p.Status != nil {
- attrs = append(attrs, slog.Int("status_code", int(p.Status.Code)))
- if p.Status.Message != "" {
- attrs = append(attrs, slog.String("status_message", p.Status.Message))
- }
- }
-
- if p.Latency != nil {
- attrs = append(attrs,
- slog.Int64("latency_ms", p.Latency.AsDuration().Milliseconds()),
- )
- }
-
- if p.RequestMetadata != nil {
- if p.RequestMetadata.CallerIp != "" {
- attrs = append(attrs, slog.String("client_ip", p.RequestMetadata.CallerIp))
- }
- if p.RequestMetadata.CallerSuppliedUserAgent != "" {
- attrs = append(attrs, slog.String("user_agent", p.RequestMetadata.CallerSuppliedUserAgent))
- }
- }
-
- // Include audit severity as an attribute (not as slog level)
- // Audit logs are always logged at INFO level - they represent business events, not system health
- // The severity field helps categorize the audit event itself
- if p.Severity != storepb.AuditLog_SEVERITY_UNSPECIFIED {
- attrs = append(attrs, slog.String("severity", p.Severity.String()))
- }
-
- attrs = append(attrs, mcpDelegationAttrs(p.McpDelegation)...)
-
- // Include request payload (truncated to 100KB for log manageability)
- // Request is already redacted for sensitive data by marshalAuditPayload()
- if p.Request != "" {
- request := p.Request
- if truncated, wasTruncated := common.TruncateString(p.Request, maxAuditPayloadChars); wasTruncated {
- request = truncated + "...[truncated]"
- }
- attrs = append(attrs, slog.String("request", request))
- }
-
- // Include response payload (truncated to 100KB for log manageability)
- // Response is already redacted for sensitive data by marshalAuditPayload()
- if p.Response != "" {
- response := p.Response
- if truncated, wasTruncated := common.TruncateString(p.Response, maxAuditPayloadChars); wasTruncated {
- response = truncated + "...[truncated]"
- }
- attrs = append(attrs, slog.String("response", response))
- }
-
- slog.LogAttrs(ctx, slog.LevelInfo, p.Method, attrs...)
-}
-
-// mcpDelegationAttrs renders the MCP provenance for stdout audit lines:
-// "mcp": true marks the row as MCP-originated even when the grant fields are
-// empty (legacy sessions); the correlation ID is what operators pivot on to
-// reassemble an agent session.
-func mcpDelegationAttrs(d *storepb.MCPDelegation) []slog.Attr {
- if d == nil {
- return nil
- }
- attrs := []slog.Attr{
- slog.Bool("mcp", true),
- // Minted for every session, legacy included — never empty.
- slog.String("mcp_correlation_id", d.CorrelationId),
- }
- if d.Scope != "" {
- attrs = append(attrs, slog.String("mcp_scope", d.Scope))
- }
- if d.Resource != "" {
- attrs = append(attrs, slog.String("mcp_resource", d.Resource))
- }
- if d.ClientId != "" {
- attrs = append(attrs, slog.String("mcp_client_id", d.ClientId))
- }
- return attrs
-}
-
func getRequestResource(request any, method string) string {
if request == nil || reflect.ValueOf(request).IsNil() {
return ""
@@ -625,22 +524,15 @@ func needAudit(ctx context.Context) bool {
// getRequestMetadataFromHeaders extracts request metadata from HTTP headers for ConnectRPC.
func getRequestMetadataFromHeaders(headers http.Header, peerAddr string) *storepb.RequestMetadata {
- userAgent := headers.Get("User-Agent")
- // Extract caller IP with fallback chain:
- // 1. X-Real-IP (set by reverse proxy, most trustworthy single IP)
- // 2. X-Forwarded-For (standard but can contain client-spoofed data)
- // 3. Peer address from ConnectRPC (direct connection fallback)
- callerIP := headers.Get("X-Real-IP")
- if callerIP == "" {
- callerIP = headers.Get("X-Forwarded-For")
- }
+ // The forwarding headers first, then the peer address ConnectRPC reports
+ // for a direct connection.
+ callerIP := common.CallerIPFromHeaders(headers)
if callerIP == "" {
- callerIP = peerAddr
+ callerIP = common.StripPort(peerAddr)
}
-
return &storepb.RequestMetadata{
CallerIp: callerIP,
- CallerSuppliedUserAgent: userAgent,
+ CallerSuppliedUserAgent: headers.Get("User-Agent"),
}
}
diff --git a/backend/api/v1/audit_redact_inventory_test.go b/backend/api/v1/audit_redact_inventory_test.go
index b19bdb6327..94a5cef213 100644
--- a/backend/api/v1/audit_redact_inventory_test.go
+++ b/backend/api/v1/audit_redact_inventory_test.go
@@ -680,6 +680,11 @@ var auditRecordedFields = []string{
"bytebase.v1.MCPDelegation.correlation_id",
"bytebase.v1.MCPDelegation.resource",
"bytebase.v1.MCPDelegation.scope",
+ "bytebase.v1.MCPEngineEnforcement.note",
+ "bytebase.v1.MCPInfo.workspace",
+ "bytebase.v1.MCPMethod.method",
+ "bytebase.v1.MCPMethod.operation_id",
+ "bytebase.v1.MCPMethod.permission",
"bytebase.v1.MaskingExemptionPolicy.Exemption.members",
"bytebase.v1.MaskingReason.algorithm",
"bytebase.v1.MaskingReason.context",
diff --git a/backend/api/v1/audit_test.go b/backend/api/v1/audit_test.go
index ef3dc9df33..f7c1d23fa6 100644
--- a/backend/api/v1/audit_test.go
+++ b/backend/api/v1/audit_test.go
@@ -1,140 +1,21 @@
package v1
import (
- "bytes"
"context"
- "encoding/json"
"errors"
- "log/slog"
"net/http"
"testing"
"connectrpc.com/connect"
"github.com/stretchr/testify/require"
- spb "google.golang.org/genproto/googleapis/rpc/status"
- "google.golang.org/protobuf/types/known/durationpb"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/component/config"
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"
"github.com/bytebase/bytebase/backend/store"
)
-// TestLogAuditToStdoutFormat is a contract test for the structured JSON fields
-// emitted to stdout when audit log stdout is enabled. Operators run commands
-// like `docker logs <container> | grep '"log_type":"audit"'` — changes to
-// these keys or their values are breaking for downstream log pipelines.
-func TestLogAuditToStdoutFormat(t *testing.T) {
- a := require.New(t)
-
- // Redirect slog default to a JSON handler writing into a buffer so the
- // test can inspect the exact structured payload.
- prev := slog.Default()
- t.Cleanup(func() { slog.SetDefault(prev) })
-
- var buf bytes.Buffer
- slog.SetDefault(slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{
- Level: slog.LevelInfo,
- })))
-
- p := &storepb.AuditLog{
- Parent: "workspaces/ws-abc",
- Method: "/bytebase.v1.AuthService/Login",
- Resource: "[email protected]",
- Severity: storepb.AuditLog_INFO,
- User: "users/[email protected]",
- Request: `{"email":"[email protected]","web":true}`,
- Response: `{"user":{"name":"users/[email protected]","email":"[email protected]"}}`,
- Status: &spb.Status{Code: 0, Message: ""},
- Latency: durationpb.New(123_000_000), // 123ms
- RequestMetadata: &storepb.RequestMetadata{
- CallerIp: "10.0.1.50",
- CallerSuppliedUserAgent: "TestAgent/1.0",
- },
- }
-
- logAuditToStdout(context.Background(), p)
-
- // Every line the handler wrote is an independent JSON object.
- lines := bytes.Split(bytes.TrimSpace(buf.Bytes()), []byte{'\n'})
- a.Len(lines, 1, "logAuditToStdout must emit exactly one JSON record")
-
- var got map[string]any
- a.NoError(json.Unmarshal(lines[0], &got),
- "stdout record must be valid JSON: %s", string(lines[0]))
-
- // Keys the customer explicitly greps for — these form our public contract.
- // If any of these assertions need to change, it's a breaking change for
- // everyone consuming audit stdout logs.
- a.Equal("audit", got["log_type"], `log_type=="audit" is how operators filter audit lines from application logs`)
- a.Equal("workspaces/ws-abc", got["parent"])
- a.Equal("/bytebase.v1.AuthService/Login", got["method"])
- a.Equal("[email protected]", got["resource"])
- a.Equal("users/[email protected]", got["user"])
- a.Equal("INFO", got["severity"])
- a.Equal("10.0.1.50", got["client_ip"])
- a.Equal("TestAgent/1.0", got["user_agent"])
- a.Equal(float64(123), got["latency_ms"], "latency must be exposed in milliseconds")
- a.Equal(`{"email":"[email protected]","web":true}`, got["request"],
- "request payload must be emitted verbatim (already redacted upstream)")
- a.Equal(`{"user":{"name":"users/[email protected]","email":"[email protected]"}}`, got["response"])
-
- // Status code 0 (OK) should be reported explicitly so downstream pipelines
- // can distinguish successful from failed calls.
- a.Equal(float64(0), got["status_code"])
-
- // slog standard fields — keep them stable too.
- a.Equal("INFO", got["level"])
- a.Equal("/bytebase.v1.AuthService/Login", got["msg"],
- "slog msg is set to the method so operators can read the log without parsing")
-
- // Error status round-trip: a failed call must emit status_code and status_message.
- buf.Reset()
- p2 := &storepb.AuditLog{
- Parent: "workspaces/ws-abc",
- Method: "/bytebase.v1.AuthService/Login",
- Severity: storepb.AuditLog_INFO,
- Status: &spb.Status{Code: 16, Message: "invalid email or password"}, // UNAUTHENTICATED
- Latency: durationpb.New(5_000_000),
- }
- logAuditToStdout(context.Background(), p2)
-
- var failed map[string]any
- a.NoError(json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &failed))
- a.Equal(float64(16), failed["status_code"], "failed call must carry status_code")
- a.Equal("invalid email or password", failed["status_message"],
- "failed call must carry status_message")
-
- // MCP-delegated calls carry their provenance in stdout too, so operators
- // tailing container logs can trace an agent session without the API.
- a.NotContains(got, "mcp_correlation_id",
- "non-MCP rows must not emit MCP keys")
- buf.Reset()
- p3 := &storepb.AuditLog{
- Parent: "workspaces/ws-abc",
- Method: "/bytebase.v1.SQLService/Query",
- Severity: storepb.AuditLog_INFO,
- McpDelegation: &storepb.MCPDelegation{
- Scope: "mcp:read-only",
- Resource: "https://bb.example.com/mcp",
- ClientId: "client-A",
- CorrelationId: "corr-42",
- },
- }
- logAuditToStdout(context.Background(), p3)
-
- var delegated map[string]any
- a.NoError(json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &delegated))
- a.Equal(true, delegated["mcp"], `mcp==true is how operators filter MCP-originated rows`)
- a.Equal("corr-42", delegated["mcp_correlation_id"],
- "the session correlation ID is the key operators pivot on")
- a.Equal("mcp:read-only", delegated["mcp_scope"])
- a.Equal("https://bb.example.com/mcp", delegated["mcp_resource"])
- a.Equal("client-A", delegated["mcp_client_id"])
-}
-
func TestFailedLoginWithoutWorkspaceIsSkipped(t *testing.T) {
ctx := context.WithValue(context.Background(), common.AuthContextKey, &common.AuthContext{Audit: true})
st := newAuditLiveStore(t)
diff --git a/backend/api/v1/mcp_gate.go b/backend/api/v1/mcp_gate.go
index 294c3ab9ca..8df77e61c0 100644
--- a/backend/api/v1/mcp_gate.go
+++ b/backend/api/v1/mcp_gate.go
@@ -10,6 +10,7 @@ import (
"connectrpc.com/connect"
"github.com/pkg/errors"
+ "github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
@@ -465,34 +466,46 @@ func (in *internalMCPGateInterceptor) refuseByCeiling(ctx context.Context, proce
// never set a ceiling and reports everything it cannot make sense of as an
// error.
settings, err := in.store.GetMCPSettingsUncached(ctx, workspaceID)
- if err != nil {
- // The agent gets no detail either way: the error text can carry the
- // workspace's storage state. What it does get is the right KIND of
- // answer, because the two failures are opposites for a client. A
- // stored value this build cannot interpret will never succeed on
- // retry — an admin has to rewrite it — so it is a policy refusal and
- // an audited one. A read that failed is an outage, so it is
- // retryable and is not a verdict about the caller. The /mcp
- // connection gate splits the same two the same way.
+
+ // auth.ClassifyMCPCeiling decides, so this gate, the /mcp connection gate,
+ // the consent and the token endpoint cannot disagree about a workspace —
+ // which is what MCPCeilingVerdict says of itself, and was not true while
+ // this door mirrored the split by hand.
+ //
+ // The agent gets no storage detail either way: the shared sentence names
+ // the state and the remedy, never the error. What it does get is the right
+ // KIND of answer, because the two failures are opposites for a client. A
+ // stored value this build cannot interpret never succeeds on retry — an
+ // admin has to rewrite it — so it is a policy refusal and an audited one.
+ // A read that failed is an outage: retryable, and not a verdict about the
+ // caller.
+ //
+ // DISABLED is deliberately NOT decided here. It reaches the serving table
+ // below, which holds an explicit empty list for it, so a mode that serves
+ // nothing reads as an ordinary per-method denial naming the class — the
+ // more useful answer at a per-method door than a workspace-level sentence.
+ switch verdict := auth.ClassifyMCPCeiling(settings.Capability, err); verdict {
+ case auth.MCPCeilingServes, auth.MCPCeilingDisabled:
+ case auth.MCPCeilingUnavailable:
slog.Warn("failed to resolve the MCP capability ceiling; refusing the request",
slog.String("method", procedure), slog.String("workspace", workspaceID), log.BBError(err))
- if errors.Is(err, store.ErrMCPCapabilityUnreadable) {
- return settings, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(
- "%s is refused: this workspace's stored MCP capability ceiling is not one this build understands, "+
- "so the request fails closed. Ask a workspace admin to set the MCP ceiling again in the workspace settings",
- procedure))
- }
return settings, false, connect.NewError(connect.CodeUnavailable, errors.Errorf(
- "%s is refused: this workspace's MCP capability ceiling could not be read, so the request fails closed. "+
- "Retry shortly; if it persists, a workspace admin must check the workspace MCP settings",
- procedure))
+ "%s is refused: %s", procedure, verdict.Refusal()))
+ default:
+ slog.Warn("the MCP capability ceiling refuses this request",
+ slog.String("method", procedure), slog.String("workspace", workspaceID), log.BBError(err))
+ return settings, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(
+ "%s is refused: %s", procedure, verdict.Refusal()))
}
+
served, known := mcpServingClasses[settings.Capability]
if !known {
+ // Unreachable: a capability no mode serves is MCPCeilingUnserved, which
+ // the switch above already refused. Kept because the serving table and
+ // the classifier are two statements of one rule, and this is what a
+ // caller gets if they ever part company.
return settings, true, connect.NewError(connect.CodePermissionDenied, errors.Errorf(
- "%s is refused: this workspace's stored MCP capability ceiling %v is not one this build serves. "+
- "Ask a workspace admin to set the MCP ceiling to a supported value in the workspace settings",
- procedure, settings.Capability))
+ "%s is refused: %s", procedure, auth.MCPCeilingUnserved.Refusal()))
}
if slices.Contains(served, class) {
return settings, false, nil
diff --git a/backend/api/v1/mcp_info.go b/backend/api/v1/mcp_info.go
new file mode 100644
index 0000000000..a53ebb537b
--- /dev/null
+++ b/backend/api/v1/mcp_info.go
@@ -0,0 +1,245 @@
+package v1
+
+import (
+ "cmp"
+ "context"
+ "log/slog"
+ "slices"
+ "strings"
+
+ "connectrpc.com/connect"
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/reflect/protoregistry"
+ "google.golang.org/protobuf/types/descriptorpb"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// GetMCPInfo reports what MCP does in this workspace.
+//
+// Everything is resolved when the request is served. The method list comes off
+// the compiled descriptors — the same place the gate reads a method's class —
+// and the engine answers off the code that enforces them, so this cannot
+// describe rules the build does not run. A stored list would drift silently:
+// the first sign would be an admin acting on a mode that no longer means what
+// the page said.
+func (s *WorkspaceService) GetMCPInfo(ctx context.Context, _ *connect.Request[v1pb.GetMCPInfoRequest]) (*connect.Response[v1pb.MCPInfo], error) {
+ workspaceID := common.GetWorkspaceIDFromContext(ctx)
+ if workspaceID == "" {
+ return nil, connect.NewError(connect.CodeInternal, errors.New("no workspace on the request"))
+ }
+ settings, err := s.mcpSettingsForInfo(ctx, workspaceID)
+ // Every verdict is decided here, not only the read failures. DISABLED is
+ // the one refusing ceiling this still answers under, deliberately: an admin
+ // looking at a workspace with MCP off is exactly who needs to see what the
+ // other modes contain. A ceiling this build does not serve is different —
+ // reporting it as "in force" would describe a state the build does not run,
+ // beside a modes list with no row for it.
+ switch verdict := auth.ClassifyMCPCeiling(settings.Capability, err); verdict {
+ case auth.MCPCeilingServes, auth.MCPCeilingDisabled:
+ case auth.MCPCeilingUnreadable, auth.MCPCeilingUnserved:
+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.New(verdict.Refusal()))
+ default:
+ // The store error stays in the log. This method is served to MCP
+ // sessions and the tool layer renders a connect message into what the
+ // model reads, so a driver error text would leave the metadata
+ // database's shape in an agent's context.
+ slog.Error("failed to read the MCP setting", slog.String("workspace", workspaceID), log.BBError(err))
+ return nil, connect.NewError(connect.CodeUnavailable, errors.New(verdict.Refusal()))
+ }
+
+ return connect.NewResponse(&v1pb.MCPInfo{
+ Workspace: common.FormatWorkspace(workspaceID),
+ Capability: convertToV1MCPCapability(settings.Capability),
+ Modes: mcpCapabilityModes(),
+ Methods: mcpServedMethods(protoregistry.GlobalFiles),
+ Engines: mcpEngineEnforcement(),
+ IgnoreMaskingExemptions: settings.IgnoreMaskingExemptions,
+ DataMaskingAvailable: s.licenseService.IsFeatureEnabled(ctx, workspaceID, v1pb.PlanFeature_FEATURE_DATA_MASKING) == nil,
+ }), nil
+}
+
+// mcpSettingsForInfo returns the MCP settings this request is answered from.
+//
+// On the internal MCP chain the gate already resolved them and stamped them on
+// the context; reading again could answer with a ceiling the request was not
+// admitted under, which is the rule mcp_gate.go states and the clamp and the
+// masking check both follow. Off that chain — the console, an admin opening the
+// settings page — nothing is stamped and the store is read.
+func (s *WorkspaceService) mcpSettingsForInfo(ctx context.Context, workspaceID string) (store.MCPSettings, error) {
+ if settings, ok := mcpSettingsFromContext(ctx); ok {
+ return settings, nil
+ }
+ return s.store.GetMCPSettingsUncached(ctx, workspaceID)
+}
+
+// mcpCapabilityModes renders the serving table the gate evaluates, one row per
+// ceiling. It reads mcpServingClasses rather than restating it, so a mode that
+// starts or stops serving a class cannot leave this stale.
+func mcpCapabilityModes() []*v1pb.MCPCapabilityMode {
+ modes := make([]*v1pb.MCPCapabilityMode, 0, len(mcpServingClasses))
+ for capability, served := range mcpServingClasses {
+ modes = append(modes, &v1pb.MCPCapabilityMode{
+ Capability: convertToV1MCPCapability(capability),
+ // Cloned: the response must not hand out the slice the gate
+ // evaluates against on every request.
+ ServedClasses: slices.Clone(served),
+ })
+ }
+ slices.SortFunc(modes, func(a, b *v1pb.MCPCapabilityMode) int { return cmp.Compare(a.Capability, b.Capability) })
+ return modes
+}
+
+// fileRanger is the descriptor set to resolve classifications from.
+// *protoregistry.Files satisfies it; a test supplies its own, which is what
+// lets "the response follows the descriptors" be shown rather than asserted.
+type fileRanger interface {
+ RangeFiles(func(protoreflect.FileDescriptor) bool)
+}
+
+// mcpServedMethods reads every bytebase.v1 RPC's classification off the
+// descriptors and returns the ones some ceiling serves, sorted by procedure.
+//
+// Methods no ceiling serves are left out: the response answers "what can be
+// done here", and an agent handed the refused list would have to be told
+// separately that those entries are not offers.
+func mcpServedMethods(files fileRanger) []*v1pb.MCPMethod {
+ var methods []*v1pb.MCPMethod
+ files.RangeFiles(func(fd protoreflect.FileDescriptor) bool {
+ if fd.Package() != "bytebase.v1" {
+ return true
+ }
+ services := fd.Services()
+ for i := range services.Len() {
+ sd := services.Get(i)
+ descriptors := sd.Methods()
+ for j := range descriptors.Len() {
+ md := descriptors.Get(j)
+ options, ok := md.Options().(*descriptorpb.MethodOptions)
+ if !ok {
+ continue
+ }
+ class, ok := proto.GetExtension(options, v1pb.E_McpMethodClass).(v1pb.MCPMethodClass)
+ if !ok {
+ // A malformed annotation is not a classification. CI
+ // rejects one, and no ceiling serves what it resolves to.
+ continue
+ }
+ if auth.MCPClassIsRefused(class) {
+ continue
+ }
+ method := &v1pb.MCPMethod{
+ Method: "/" + string(sd.FullName()) + "/" + string(md.Name()),
+ OperationId: string(sd.FullName()) + "." + string(md.Name()),
+ Class: class,
+ }
+ if permission, ok := proto.GetExtension(options, v1pb.E_Permission).(string); ok {
+ method.Permission = permission
+ }
+ if authMethod, ok := proto.GetExtension(options, v1pb.E_AuthMethod).(v1pb.AuthMethod); ok {
+ method.AuthMethod = authMethod
+ }
+ methods = append(methods, method)
+ }
+ }
+ return true
+ })
+ slices.SortFunc(methods, func(a, b *v1pb.MCPMethod) int { return strings.Compare(a.Method, b.Method) })
+ return methods
+}
+
+// mcpEngineEnforcement answers, per engine, how deep a read-only ceiling goes
+// and whether masking reaches anything — the two facts the ceiling alone does
+// not show. Every engine the build knows appears, in declaration order.
+func mcpEngineEnforcement() []*v1pb.MCPEngineEnforcement {
+ values := storepb.Engine(0).Descriptor().Values()
+ engines := make([]*v1pb.MCPEngineEnforcement, 0, values.Len())
+ for i := range values.Len() {
+ engine := storepb.Engine(values.Get(i).Number())
+ if engine == storepb.Engine_ENGINE_UNSPECIFIED {
+ continue
+ }
+ engines = append(engines, &v1pb.MCPEngineEnforcement{
+ Engine: convertToEngine(engine),
+ ReadOnlyDepth: mcpReadOnlyDepth(engine),
+ Masking: mcpMaskingSupport(engine),
+ Note: mcpEngineNote(engine),
+ })
+ }
+ return engines
+}
+
+// mcpReadOnlyDepth reports how much of a read-only ceiling this engine can be
+// held to.
+//
+// The classifier half is asked, not mirrored: parserbase.HasQueryValidator is
+// the same registry the clamp consults, so an engine that gains or loses a
+// validator moves here on the same commit.
+func mcpReadOnlyDepth(engine storepb.Engine) v1pb.MCPEngineEnforcement_ReadOnlyDepth {
+ if !parserbase.HasQueryValidator(engine) {
+ return v1pb.MCPEngineEnforcement_UNSUPPORTED
+ }
+ if readOnlyDriverSession(engine) {
+ return v1pb.MCPEngineEnforcement_STATEMENT_AND_SESSION
+ }
+ return v1pb.MCPEngineEnforcement_STATEMENT
+}
+
+// readOnlyDriverSession reports whether this engine's driver always turns
+// ConnectionContext.ReadOnly into a read-only database session, by setting
+// default_transaction_read_only on the connection it opens. Two always do:
+// postgres and cockroachdb. Redshift does too, but only outside a datashare
+// database, which cannot run a read-only transaction — that is per database,
+// off its metadata, and this answer is per engine, so redshift is reported at
+// its floor and its note carries the rest (plugin/db/pg, /cockroachdb,
+// /redshift).
+//
+// It mirrors the drivers rather than asking them, because a driver reports this
+// by acting on a flag when a connection is opened and no connection exists
+// here. A driver that starts honoring the flag without a row here understates
+// its own depth, which is the safe way for this to be wrong.
+func readOnlyDriverSession(engine storepb.Engine) bool {
+ switch engine {
+ case storepb.Engine_POSTGRES, storepb.Engine_COCKROACHDB:
+ return true
+ default:
+ return false
+ }
+}
+
+// mcpMaskingSupport reports how Bytebase masks results on this engine, which is
+// what decides whether ignoring masking exemptions changes anything.
+//
+// Document first, because that is the order the query path checks them
+// (sql_service.go): an engine with a document masker never reaches the column
+// masker. Exemptions are a column-masking mechanism — the document masker's
+// interface carries neither the user nor their exemptions — so on a document
+// engine the toggle has nothing to suppress (BOT-95).
+func mcpMaskingSupport(engine storepb.Engine) v1pb.MCPEngineEnforcement_Masking {
+ switch {
+ case getDocumentMasker(engine) != nil:
+ return v1pb.MCPEngineEnforcement_DOCUMENT
+ case common.EngineSupportMasking(engine):
+ return v1pb.MCPEngineEnforcement_COLUMN
+ default:
+ return v1pb.MCPEngineEnforcement_NONE
+ }
+}
+
+// mcpEngineNote carries the cases where a per-engine answer is the floor rather
+// than the whole story.
+func mcpEngineNote(engine storepb.Engine) string {
+ if engine == storepb.Engine_REDSHIFT {
+ return "Outside a datashare database the driver also opens the session read-only. " +
+ "A datashare database cannot run a read-only transaction, so there it is statement classification alone."
+ }
+ return ""
+}
diff --git a/backend/api/v1/mcp_info_test.go b/backend/api/v1/mcp_info_test.go
new file mode 100644
index 0000000000..7a3d14ca4f
--- /dev/null
+++ b/backend/api/v1/mcp_info_test.go
@@ -0,0 +1,440 @@
+package v1
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protodesc"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/reflect/protoregistry"
+ "google.golang.org/protobuf/types/descriptorpb"
+
+ "github.com/bytebase/bytebase/backend/api/auth"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/enterprise"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/migrator"
+ parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+// TestMCPInfoResolvesMethodsLive shows that the served-method list follows the
+// descriptors rather than any copy of them: the same resolver, run over two
+// descriptor sets differing only in one method's mcp_method_class annotation,
+// answers differently.
+//
+// This is the property the API exists for. A stored or hand-kept list would
+// pass every assertion below on the day it was written and drift silently
+// afterwards, and the first sign would be an admin choosing a mode from a page
+// that described the build before this one.
+func TestMCPInfoResolvesMethodsLive(t *testing.T) {
+ asRead := mcpServedMethods(descriptorsClassifying(t, v1pb.MCPMethodClass_READ))
+ require.Len(t, asRead, 1)
+ require.Equal(t, "/bytebase.v1.LiveResolutionService/Probe", asRead[0].Method)
+ require.Equal(t, v1pb.MCPMethodClass_READ, asRead[0].Class)
+ require.Equal(t, "bb.probes.get", asRead[0].Permission)
+
+ asWrite := mcpServedMethods(descriptorsClassifying(t, v1pb.MCPMethodClass_WRITE))
+ require.Len(t, asWrite, 1)
+ require.Equal(t, v1pb.MCPMethodClass_WRITE, asWrite[0].Class,
+ "the response must move when the annotation moves")
+
+ // A refused class leaves the method out entirely: the response answers what
+ // can be done, so a refused entry would read as an offer.
+ for _, class := range []v1pb.MCPMethodClass{
+ v1pb.MCPMethodClass_FORBIDDEN,
+ v1pb.MCPMethodClass_EXCLUDED,
+ v1pb.MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED,
+ } {
+ require.Empty(t, mcpServedMethods(descriptorsClassifying(t, class)),
+ "%v is served by no ceiling", class)
+ }
+}
+
+// descriptorsClassifying builds a descriptor set holding one bytebase.v1
+// service with one method carrying the given classification. The file is
+// compiled the same way the real ones are, so the resolver reads a real
+// annotation off a real descriptor, not a stand-in for one.
+func descriptorsClassifying(t *testing.T, class v1pb.MCPMethodClass) *protoregistry.Files {
+ t.Helper()
+
+ options := &descriptorpb.MethodOptions{}
+ proto.SetExtension(options, v1pb.E_McpMethodClass, class)
+ proto.SetExtension(options, v1pb.E_Permission, "bb.probes.get")
+ if class == v1pb.MCPMethodClass_FORBIDDEN || class == v1pb.MCPMethodClass_EXCLUDED {
+ // The build's own lint requires a reason on a refused method; keep the
+ // synthetic file consistent with that rule.
+ proto.SetExtension(options, v1pb.E_McpDenialReason, v1pb.MCPDenialReason_ADMINISTERS_THE_WORKSPACE)
+ }
+
+ probe := &descriptorpb.FileDescriptorProto{
+ Name: proto.String("test/live_resolution.proto"),
+ Package: proto.String("bytebase.v1"),
+ Syntax: proto.String("proto3"),
+ Dependency: []string{
+ "v1/annotation.proto",
+ },
+ MessageType: []*descriptorpb.DescriptorProto{
+ {Name: proto.String("ProbeRequest")},
+ {Name: proto.String("ProbeResponse")},
+ },
+ Service: []*descriptorpb.ServiceDescriptorProto{{
+ Name: proto.String("LiveResolutionService"),
+ Method: []*descriptorpb.MethodDescriptorProto{{
+ Name: proto.String("Probe"),
+ InputType: proto.String(".bytebase.v1.ProbeRequest"),
+ OutputType: proto.String(".bytebase.v1.ProbeResponse"),
+ Options: options,
+ }},
+ }},
+ }
+
+ set := &descriptorpb.FileDescriptorSet{File: append(fileAndDependencies(t, "v1/annotation.proto"), probe)}
+ files, err := protodesc.NewFiles(set)
+ require.NoError(t, err)
+ return files
+}
+
+// fileAndDependencies returns the given compiled file and everything it imports,
+// dependencies first, as descriptor protos.
+func fileAndDependencies(t *testing.T, path string) []*descriptorpb.FileDescriptorProto {
+ t.Helper()
+ seen := map[string]bool{}
+ var out []*descriptorpb.FileDescriptorProto
+ var walk func(fd protoreflect.FileDescriptor)
+ walk = func(fd protoreflect.FileDescriptor) {
+ if seen[fd.Path()] {
+ return
+ }
+ seen[fd.Path()] = true
+ imports := fd.Imports()
+ for i := range imports.Len() {
+ walk(imports.Get(i).FileDescriptor)
+ }
+ out = append(out, protodesc.ToFileDescriptorProto(fd))
+ }
+ fd, err := protoregistry.GlobalFiles.FindFileByPath(path)
+ require.NoError(t, err)
+ walk(fd)
+ return out
+}
+
+// TestMCPInfoServedMethodsMatchTheServingTable holds the real response against
+// the gate's own serving table: every method it lists must be one some ceiling
+// serves, and every method the annotations classify as served must be listed.
+func TestMCPInfoServedMethodsMatchTheServingTable(t *testing.T) {
+ methods := mcpServedMethods(protoregistry.GlobalFiles)
+ require.NotEmpty(t, methods)
+
+ listed := map[string]v1pb.MCPMethodClass{}
+ for _, m := range methods {
+ require.False(t, auth.MCPClassIsRefused(m.Class),
+ "%s is %v, which no ceiling serves, so it must not be advertised", m.Method, m.Class)
+ listed[m.Method] = m.Class
+ }
+
+ byMethod := map[string]*v1pb.MCPMethod{}
+ for _, m := range methods {
+ byMethod[m.Method] = m
+ }
+ for _, row := range mcpClassificationsFromDescriptors(t) {
+ if auth.MCPClassIsRefused(row.class) {
+ require.NotContains(t, listed, row.procedure)
+ continue
+ }
+ require.Equal(t, row.class, listed[row.procedure],
+ "%s is classified %v and must be listed as such", row.procedure, row.class)
+ // The permission is the part an agent acts on to predict a denial, so
+ // it is checked on every real method, not only on a synthetic one.
+ require.Equal(t, row.permission, byMethod[row.procedure].Permission,
+ "%s must report the permission its descriptor declares", row.procedure)
+ }
+
+ // The order is the response's contract: protoregistry's RangeFiles order is
+ // unspecified, so without the sort the list would flap between requests.
+ for range 4 {
+ next := mcpServedMethods(protoregistry.GlobalFiles)
+ require.Len(t, next, len(methods))
+ for i := range methods {
+ require.Equal(t, methods[i].Method, next[i].Method, "method order must be stable")
+ }
+ }
+}
+
+// TestMCPInfoModesMatchTheServingTable pins that the modes the response
+// describes are the gate's, not a second copy of them.
+func TestMCPInfoModesMatchTheServingTable(t *testing.T) {
+ modes := mcpCapabilityModes()
+ require.Len(t, modes, len(mcpServingClasses))
+
+ got := map[storepb.MCPSetting_Capability][]v1pb.MCPMethodClass{}
+ for _, mode := range modes {
+ capability := convertToStoreMCPCapability(mode.Capability)
+ _, known := mcpServingClasses[capability]
+ require.True(t, known, "%v is not a ceiling the gate decides about", mode.Capability)
+ got[capability] = mode.ServedClasses
+ }
+
+ // Spelled out rather than compared against the table, so flipping what a
+ // mode serves fails here instead of agreeing with itself.
+ require.Empty(t, got[storepb.MCPSetting_DISABLED])
+ require.Equal(t, []v1pb.MCPMethodClass{v1pb.MCPMethodClass_READ}, got[storepb.MCPSetting_READ_ONLY])
+ require.Equal(t,
+ []v1pb.MCPMethodClass{v1pb.MCPMethodClass_READ, v1pb.MCPMethodClass_WRITE},
+ got[storepb.MCPSetting_READ_WRITE])
+
+ // And not the gate's own slice: a response that aliases the serving table
+ // lets anything downstream write into the ceiling.
+ for _, mode := range modes {
+ served := mcpServingClasses[convertToStoreMCPCapability(mode.Capability)]
+ if len(served) > 0 && len(mode.ServedClasses) > 0 {
+ require.NotSame(t, &served[0], &mode.ServedClasses[0],
+ "%v hands out the table the gate evaluates", mode.Capability)
+ }
+ }
+
+ // The order is the response's contract: Go randomizes map iteration, so
+ // without the sort every request would return a different one.
+ for range 8 {
+ next := mcpCapabilityModes()
+ require.Len(t, next, len(modes))
+ for i := range modes {
+ require.Equal(t, modes[i].Capability, next[i].Capability, "mode order must be stable")
+ }
+ }
+}
+
+// TestMCPInfoReadOnlyDepthMirrorsTheDrivers holds the reported depth against
+// the two things that decide it.
+//
+// The classifier half is asked, not mirrored: HasQueryValidator is the registry
+// the clamp itself consults, so an engine gaining or losing a validator moves
+// here on the same commit and this test follows it.
+//
+// The session half cannot be asked — a driver reports it by acting on a flag
+// when a connection opens, and none exists here — so readOnlyDriverSession
+// mirrors the drivers by hand. What this pins is that mcpReadOnlyDepth reports
+// that table faithfully, NOT that the table matches the drivers: a fourth
+// driver that starts honoring the flag leaves both unchanged and this green.
+// Nothing in a unit test can catch that; the safe direction is that an
+// unmirrored driver understates its own depth rather than overstating it.
+func TestMCPInfoReadOnlyDepthMirrorsTheDrivers(t *testing.T) {
+ // readOnlyDriverSession's table, restated so an unmirrored edit to it fails.
+ sessionDepth := map[storepb.Engine]bool{
+ storepb.Engine_POSTGRES: true,
+ storepb.Engine_COCKROACHDB: true,
+ }
+
+ values := storepb.Engine(0).Descriptor().Values()
+ for i := range values.Len() {
+ engine := storepb.Engine(values.Get(i).Number())
+ if engine == storepb.Engine_ENGINE_UNSPECIFIED {
+ continue
+ }
+ got := mcpReadOnlyDepth(engine)
+ switch {
+ case !parserbase.HasQueryValidator(engine):
+ require.Equal(t, v1pb.MCPEngineEnforcement_UNSUPPORTED, got,
+ "%v has no read-only classifier, so a read-only session is refused every statement", engine)
+ case sessionDepth[engine]:
+ require.Equal(t, v1pb.MCPEngineEnforcement_STATEMENT_AND_SESSION, got, "%v", engine)
+ default:
+ require.Equal(t, v1pb.MCPEngineEnforcement_STATEMENT, got, "%v", engine)
+ }
+ }
+
+ require.NotEmpty(t, mcpEngineNote(storepb.Engine_REDSHIFT),
+ "redshift's floor is only honest with the datashare exception said out loud")
+}
+
+// TestMCPInfoMaskingMirrorsTheMaskers holds the three masking states against
+// the two functions the query path branches on.
+//
+// It does not pin the branch ORDER, and cannot: it also pins that the two
+// predicates are disjoint, which is what makes the order unobservable. That
+// disjointness is the real invariant — an engine in both sets would make
+// document-first the only correct order, and the assertion below is what would
+// catch one appearing.
+//
+// The third state is the one worth having: a document engine masks, so it is
+// not "no masking", but the document masker's interface carries neither the
+// user nor their exemptions, so ignoring exemptions changes nothing there
+// (BOT-95). Collapsing it into either neighbour would overclaim.
+func TestMCPInfoMaskingMirrorsTheMaskers(t *testing.T) {
+ values := storepb.Engine(0).Descriptor().Values()
+ var column, document, none int
+ for i := range values.Len() {
+ engine := storepb.Engine(values.Get(i).Number())
+ if engine == storepb.Engine_ENGINE_UNSPECIFIED {
+ continue
+ }
+ got := mcpMaskingSupport(engine)
+ switch {
+ case getDocumentMasker(engine) != nil:
+ require.Equal(t, v1pb.MCPEngineEnforcement_DOCUMENT, got, "%v", engine)
+ require.False(t, common.EngineSupportMasking(engine),
+ "%v routes to the document masker, so the column masker is never reached", engine)
+ document++
+ case common.EngineSupportMasking(engine):
+ require.Equal(t, v1pb.MCPEngineEnforcement_COLUMN, got, "%v", engine)
+ column++
+ default:
+ require.Equal(t, v1pb.MCPEngineEnforcement_NONE, got, "%v", engine)
+ none++
+ }
+ }
+ require.Equal(t, 3, document, "cosmosdb, mongodb, elasticsearch")
+ require.NotZero(t, column)
+ require.NotZero(t, none)
+}
+
+// TestMCPInfoCoversEveryEngine pins that the response leaves no engine out: an
+// admin choosing read-only must not have to guess about the one engine the
+// table skipped.
+func TestMCPInfoCoversEveryEngine(t *testing.T) {
+ engines := mcpEngineEnforcement()
+ values := storepb.Engine(0).Descriptor().Values()
+ require.Len(t, engines, values.Len()-1, "every engine but the unspecified zero value")
+
+ seen := map[v1pb.Engine]bool{}
+ for _, e := range engines {
+ require.NotEqual(t, v1pb.Engine_ENGINE_UNSPECIFIED, e.Engine,
+ "an engine the v1 converter does not know would report as unspecified")
+ require.False(t, seen[e.Engine], "%v listed twice", e.Engine)
+ seen[e.Engine] = true
+ }
+}
+
+// TestGetMCPInfoHandler drives the RPC itself, which the helper tests above
+// cannot: they each hand mcpServedMethods a descriptor source, so nothing they
+// assert pins that the handler passes the real registry rather than a cached or
+// stored set — the one property this API exists to guarantee. They also leave
+// every error branch unexercised.
+func TestGetMCPInfoHandler(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+ require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))
+
+ pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort())
+ stores, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, stores.Close()) })
+
+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")
+ require.NoError(t, err)
+ service := NewWorkspaceService(stores, nil, &config.Profile{}, licenseService, nil)
+
+ const workspaceID = "mcp-info-handler"
+ _, err = stores.CreateWorkspace(ctx, &store.WorkspaceMessage{
+ ResourceID: workspaceID,
+ Payload: &storepb.WorkspacePayload{Title: "MCP info handler"},
+ require.NoError(t, err)
+
+ get := func(ctx context.Context) (*v1pb.MCPInfo, error) {
+ resp, err := service.GetMCPInfo(ctx, connect.NewRequest(&v1pb.GetMCPInfoRequest{}))
+ if err != nil {
+ return nil, err
+ }
+ return resp.Msg, nil
+ }
+ workspaceCtx := func() context.Context {
+ return context.WithValue(ctx, common.WorkspaceIDContextKey, workspaceID)
+ }
+ setCeiling := func(t *testing.T, value string) {
+ t.Helper()
+ _, err := container.GetDB().ExecContext(ctx, `
+ INSERT INTO setting (name, workspace, value) VALUES ('MCP', $1, $2)
+ ON CONFLICT (workspace, name) DO UPDATE SET value = EXCLUDED.value`,
+ workspaceID, value)
+ require.NoError(t, err)
+ }
+
+ t.Run("a workspace that never configured MCP", func(t *testing.T) {
+ info, err := get(workspaceCtx())
+ require.NoError(t, err)
+ require.Equal(t, "workspaces/"+workspaceID, info.Workspace)
+ require.Equal(t, v1pb.MCPSetting_READ_WRITE, info.Capability)
+ require.False(t, info.IgnoreMaskingExemptions)
+
+ // The list is the live registry's, not a fixture: every entry must be a
+ // method this build actually compiled, and the count must match what
+ // the descriptors classify as served right now.
+ require.Equal(t, len(mcpServedMethods(protoregistry.GlobalFiles)), len(info.Methods))
+ byMethod := map[string]*v1pb.MCPMethod{}
+ for _, m := range info.Methods {
+ byMethod[m.Method] = m
+ }
+ query := byMethod["/bytebase.v1.SQLService/Query"]
+ require.NotNil(t, query, "the handler must resolve from the compiled descriptors")
+ require.Equal(t, "bytebase.v1.SQLService.Query", query.OperationId)
+ require.NotContains(t, byMethod, "/bytebase.v1.AuthService/Login",
+ "a FORBIDDEN method must never be advertised as reachable")
+
+ require.Len(t, info.Modes, 3)
+ require.NotEmpty(t, info.Engines)
+ })
+
+ t.Run("the toggle reaches the response", func(t *testing.T) {
+ setCeiling(t, `{"capability":"READ_ONLY","ignoreMaskingExemptions":true}`)
+ info, err := get(workspaceCtx())
+ require.NoError(t, err)
+ require.Equal(t, v1pb.MCPSetting_READ_ONLY, info.Capability)
+ require.True(t, info.IgnoreMaskingExemptions,
+ "every masking state is written in terms of this, so withholding it leaves the table unusable")
+ })
+
+ t.Run("a disabled workspace is still answered", func(t *testing.T) {
+ setCeiling(t, `{"capability":"DISABLED"}`)
+ info, err := get(workspaceCtx())
+ require.NoError(t, err)
+ require.Equal(t, v1pb.MCPSetting_DISABLED, info.Capability)
+ require.NotEmpty(t, info.Modes,
+ "an admin with MCP off is exactly who needs to see what the other modes contain")
+ })
+
+ t.Run("a ceiling this build cannot read fails closed", func(t *testing.T) {
+ setCeiling(t, `{"capability":"READ_ONLYY"}`)
+ _, err := get(workspaceCtx())
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+ require.Contains(t, err.Error(), "not one this build understands")
+ })
+
+ t.Run("a ceiling this build does not serve fails closed", func(t *testing.T) {
+ // The reserved 2, or a value a newer release wrote. It parses, so
+ // nothing but the verdict catches it.
+ setCeiling(t, `{"capability":2}`)
+ _, err := get(workspaceCtx())
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+ require.Contains(t, err.Error(), "not one this build serves")
+ })
+
+ t.Run("the gate's resolution wins over a second read", func(t *testing.T) {
+ // The stored ceiling still says DISABLED below; the gate admitted this
+ // request under READ_ONLY. Answering from the store would report a
+ // ceiling the request was not admitted under.
+ setCeiling(t, `{"capability":"DISABLED"}`)
+ stamped := withMCPSettings(workspaceCtx(), store.MCPSettings{
+ Capability: storepb.MCPSetting_READ_ONLY,
+ IgnoreMaskingExemptions: true,
+ })
+ info, err := get(stamped)
+ require.NoError(t, err)
+ require.Equal(t, v1pb.MCPSetting_READ_ONLY, info.Capability)
+ require.True(t, info.IgnoreMaskingExemptions)
+ })
+
+ t.Run("no workspace on the request", func(t *testing.T) {
+ _, err := get(ctx)
+ require.Equal(t, connect.CodeInternal, connect.CodeOf(err))
+ })
+}
diff --git a/backend/api/v1/setting_service_converter.go b/backend/api/v1/setting_service_converter.go
index c2b5434ca6..9e614e04b8 100644
--- a/backend/api/v1/setting_service_converter.go
+++ b/backend/api/v1/setting_service_converter.go
@@ -384,12 +384,18 @@ func convertToStoreMCPCapability(c v1pb.MCPSetting_Capability) storepb.MCPSettin
return storepb.MCPSetting_Capability(c)
}
+// convertToV1MCPCapability crosses the two Capability enums the other way, by
+// number. Same pin.
+func convertToV1MCPCapability(c storepb.MCPSetting_Capability) v1pb.MCPSetting_Capability {
+ return v1pb.MCPSetting_Capability(c)
+}
+
func convertToMCPSetting(s *storepb.MCPSetting) *v1pb.MCPSetting {
if s == nil {
return nil
}
return &v1pb.MCPSetting{
- Capability: v1pb.MCPSetting_Capability(s.Capability),
+ Capability: convertToV1MCPCapability(s.Capability),
IgnoreMaskingExemptions: s.IgnoreMaskingExemptions,
}
}
diff --git a/backend/api/v1/testdata/mcp_method_classification.md b/backend/api/v1/testdata/mcp_method_classification.md
index cb98283b4f..2d771f2cbc 100644
--- a/backend/api/v1/testdata/mcp_method_classification.md
+++ b/backend/api/v1/testdata/mcp_method_classification.md
@@ -16,12 +16,12 @@ served by no ceiling.
| Class | Methods | Meaning |
|---|---|---|
-| READ | 56 | served to a read-only session and above |
+| READ | 57 | served to a read-only session and above |
| WRITE | 40 | served to a read-write session only |
| EXCLUDED | 86 | served by no ceiling this phase ships |
| FORBIDDEN | 28 | never served, whatever the ceiling |
| MCP_METHOD_CLASS_UNSPECIFIED | 0 | unclassified — CI rejects this, and the gate refuses it |
-| **total** | **210** | |
+| **total** | **211** | |
| Method | Class | Reason | Permission |
|---|---|---|---|
@@ -229,6 +229,7 @@ served by no ceiling.
| WorkloadIdentityService/UpdateWorkloadIdentity | FORBIDDEN | MINTS_CREDENTIAL_FOR_OTHERS | bb.workloadIdentities.update |
| WorkspaceService/DeleteWorkspace | FORBIDDEN | ENDS_MEMBERSHIP | bb.workspaces.delete |
| WorkspaceService/GetIamPolicy | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.workspaces.getIamPolicy |
+| WorkspaceService/GetMCPInfo | READ | — | — |
| WorkspaceService/GetWorkspace | READ | — | — |
| WorkspaceService/LeaveWorkspace | FORBIDDEN | ENDS_MEMBERSHIP | — |
| WorkspaceService/ListWorkspaces | READ | — | — |
diff --git a/backend/common/audit.go b/backend/common/audit.go
new file mode 100644
index 0000000000..f95a8d43b5
--- /dev/null
+++ b/backend/common/audit.go
@@ -0,0 +1,224 @@
+package common
+
+import (
+ "context"
+ "log/slog"
+ "net"
+ "net/http"
+ "time"
+
+ "github.com/bytebase/bytebase/backend/common/log"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+// Audit method names for the two MCP doors that are not v1 RPCs. The
+// interceptor names a row by the connect procedure it wrapped, so every
+// consumer of AuditLog.method is shaped for "/<package>.<Service>/<Method>";
+// these keep that shape without claiming a name in bytebase.v1, which is the
+// surface the protos define and where the next reader would go looking for a
+// descriptor. component/recovery already names its rows the same way, under
+// bytebase.cli. The method part names what was ATTEMPTED — the row's status
+// carries the verdict, exactly as for an RPC that ACL refused.
+const (
+ // AuditMethodMCPSessionAuthorize is a bearer token presented at /mcp and
+ // held against the workspace ceiling. Per REQUEST, not per session: /mcp is
+ // Streamable HTTP, so a client polling a workspace that refuses it writes a
+ // row per poll. Nothing collapses repeats. Retention bounds the volume; if
+ // that stops being enough, collapse on the session fingerprint the
+ // middleware already computes for an admitted request.
+ AuditMethodMCPSessionAuthorize = "/bytebase.mcp.Session/Authorize"
+ // AuditMethodMCPConsentApprove is a user approving an MCP OAuth2 consent.
+ AuditMethodMCPConsentApprove = "/bytebase.mcp.Consent/Approve"
+)
+
+// AuditLogWriter is the one store method a door outside the connect chains
+// needs to record its own denial.
+type AuditLogWriter interface {
+ CreateAuditLog(ctx context.Context, workspace string, payload *storepb.AuditLog) error
+}
+
+// RecordOutOfBandAudit writes a row for a refusal no interceptor sees, and
+// mirrors it to stdout when that is enabled.
+//
+// Best effort by design: an audit row that cannot be written must never turn a
+// refusal into an admission, so the caller gets no error to act on. The stdout
+// mirror does NOT depend on the insert — a metadata-database failure is when
+// losing the row from both surfaces would matter most.
+func RecordOutOfBandAudit(ctx context.Context, writer AuditLogWriter, mirrorToStdout bool, workspace string, row *storepb.AuditLog) {
+ // WithoutCancel so the row survives a client hanging up on its own refusal,
+ // bounded because WithoutCancel drops the request deadline too. Both
+ // callers write on the synchronous path of a refusal already decided, so an
+ // unbounded insert holds the user's answer open.
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), outOfBandAuditTimeout)
+ defer cancel()
+
+ // Before the insert, not after: the stream is the surface that still works
+ // when the metadata database does not, so it must not queue behind it.
+ if mirrorToStdout {
+ LogAuditToStdout(ctx, row)
+ }
+ if err := writer.CreateAuditLog(ctx, workspace, row); err != nil {
+ slog.Warn("failed to record a policy denial",
+ slog.String("workspace", workspace), slog.String("method", row.GetMethod()), log.BBError(err))
+ }
+}
+
+// outOfBandAuditTimeout bounds a detached audit write. Long enough that an
+// ordinary insert never trips it, short enough that a stalled metadata database
+// delays a refusal by seconds rather than indefinitely.
+const outOfBandAuditTimeout = 5 * time.Second
+
+// maxAuditPayloadChars is the maximum characters for request/response payloads in stdout logs.
+// Set to 100KB (102400 chars) to match AWS CloudTrail industry standard for audit logs.
+const maxAuditPayloadChars = 102400
+
+// LogAuditToStdout writes audit log events to stdout using Go's standard slog library.
+// Output format is controlled by the global slog handler (JSON in production, text in dev).
+// Logs include a "log_type": "audit" field to distinguish from application logs.
+// This is a best-effort operation - errors are not returned to avoid failing the audit flow.
+//
+// Every writer in the server process calls this when stdout audit is enabled:
+// the stream is a mirror of the table, and a row only one of them carries is a
+// row an operator reading the other cannot see. The recovery CLI
+// (component/recovery) is the exception — it writes without a profile to read
+// the flag from.
+func LogAuditToStdout(ctx context.Context, p *storepb.AuditLog) {
+ attrs := []slog.Attr{
+ slog.String("log_type", "audit"),
+ slog.String("parent", p.Parent),
+ slog.String("method", p.Method),
+ }
+
+ if p.Resource != "" {
+ attrs = append(attrs, slog.String("resource", p.Resource))
+ }
+ if p.User != "" {
+ attrs = append(attrs, slog.String("user", p.User))
+ }
+
+ if p.Status != nil {
+ attrs = append(attrs, slog.Int("status_code", int(p.Status.Code)))
+ if p.Status.Message != "" {
+ attrs = append(attrs, slog.String("status_message", p.Status.Message))
+ }
+ }
+
+ if p.Latency != nil {
+ attrs = append(attrs,
+ slog.Int64("latency_ms", p.Latency.AsDuration().Milliseconds()),
+ )
+ }
+
+ if p.RequestMetadata != nil {
+ if p.RequestMetadata.CallerIp != "" {
+ attrs = append(attrs, slog.String("client_ip", p.RequestMetadata.CallerIp))
+ }
+ if p.RequestMetadata.CallerSuppliedUserAgent != "" {
+ attrs = append(attrs, slog.String("user_agent", p.RequestMetadata.CallerSuppliedUserAgent))
+ }
+ }
+
+ // Include audit severity as an attribute (not as slog level)
+ // Audit logs are always logged at INFO level - they represent business events, not system health
+ // The severity field helps categorize the audit event itself
+ if p.Severity != storepb.AuditLog_SEVERITY_UNSPECIFIED {
+ attrs = append(attrs, slog.String("severity", p.Severity.String()))
+ }
+
+ attrs = append(attrs, mcpDelegationAttrs(p.McpDelegation)...)
+
+ // Include request payload (truncated to 100KB for log manageability)
+ // Request is already redacted for sensitive data by getRequestString()
+ if p.Request != "" {
+ request := p.Request
+ if truncated, wasTruncated := TruncateString(p.Request, maxAuditPayloadChars); wasTruncated {
+ request = truncated + "...[truncated]"
+ }
+ attrs = append(attrs, slog.String("request", request))
+ }
+
+ // Include response payload (truncated to 100KB for log manageability)
+ // Response is already redacted for sensitive data by getResponseString()
+ if p.Response != "" {
+ response := p.Response
+ if truncated, wasTruncated := TruncateString(p.Response, maxAuditPayloadChars); wasTruncated {
+ response = truncated + "...[truncated]"
+ }
+ attrs = append(attrs, slog.String("response", response))
+ }
+
+ slog.LogAttrs(ctx, slog.LevelInfo, p.Method, attrs...)
+}
+
+// mcpDelegationAttrs renders the MCP provenance for stdout audit lines:
+// "mcp": true marks the row as MCP-originated even when the grant fields are
+// empty (legacy sessions); the correlation ID is what operators pivot on to
+// reassemble an agent session.
+func mcpDelegationAttrs(d *storepb.MCPDelegation) []slog.Attr {
+ if d == nil {
+ return nil
+ }
+ attrs := []slog.Attr{
+ slog.Bool("mcp", true),
+ // Minted for every session, legacy included. Empty only on a consent
+ // entry, which never reached the /mcp boundary that mints it.
+ slog.String("mcp_correlation_id", d.CorrelationId),
+ }
+ if d.Scope != "" {
+ attrs = append(attrs, slog.String("mcp_scope", d.Scope))
+ }
+ if d.Resource != "" {
+ attrs = append(attrs, slog.String("mcp_resource", d.Resource))
+ }
+ if d.ClientId != "" {
+ attrs = append(attrs, slog.String("mcp_client_id", d.ClientId))
+ }
+ return attrs
+}
+
+// Caller-IP headers, in the precedence every audit path reads them: X-Real-IP
+// is what a reverse proxy sets and is a single value, X-Forwarded-For is the
+// standard one and can carry a client-supplied list. Both are
+// client-controllable on a direct connection.
+const (
+ HeaderRealIP = "X-Real-IP"
+ headerForwardedFor = "X-Forwarded-For"
+)
+
+// CallerIPFromHeaders reads the caller IP out of the forwarding headers, or ""
+// when neither is set.
+func CallerIPFromHeaders(header http.Header) string {
+ if ip := header.Get(HeaderRealIP); ip != "" {
+ return ip
+ }
+ return header.Get(headerForwardedFor)
+}
+
+// CallerIP resolves who made an HTTP request: the forwarding headers if
+// present, otherwise the peer address.
+func CallerIP(r *http.Request) string {
+ if ip := CallerIPFromHeaders(r.Header); ip != "" {
+ return ip
+ }
+ return StripPort(r.RemoteAddr)
+}
+
+// StripPort drops the port from a peer address so one audit column holds one
+// shape. A forwarding header carries a bare IP; a peer address carries
+// host:port, and storing both spellings of "who called" makes the column
+// unusable for grouping.
+func StripPort(addr string) string {
+ if host, _, err := net.SplitHostPort(addr); err == nil {
+ return host
+ }
+ return addr
+}
+
+// RequestMetadataFromHTTP renders the audit row's request metadata for a caller
+// that arrived over plain HTTP rather than over a connect chain.
+func RequestMetadataFromHTTP(r *http.Request) *storepb.RequestMetadata {
+ return &storepb.RequestMetadata{
+ CallerIp: CallerIP(r),
+ CallerSuppliedUserAgent: r.Header.Get("User-Agent"),
+ }
+}
diff --git a/backend/common/audit_test.go b/backend/common/audit_test.go
new file mode 100644
index 0000000000..52b4f06536
--- /dev/null
+++ b/backend/common/audit_test.go
@@ -0,0 +1,129 @@
+//nolint:revive
+package common
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "log/slog"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ spb "google.golang.org/genproto/googleapis/rpc/status"
+ "google.golang.org/protobuf/types/known/durationpb"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+// TestLogAuditToStdoutFormat is a contract test for the structured JSON fields
+// emitted to stdout when audit log stdout is enabled. Operators run commands
+// like `docker logs <container> | grep '"log_type":"audit"'` — changes to
+// these keys or their values are breaking for downstream log pipelines.
+func TestLogAuditToStdoutFormat(t *testing.T) {
+ a := require.New(t)
+
+ // Redirect slog default to a JSON handler writing into a buffer so the
+ // test can inspect the exact structured payload.
+ prev := slog.Default()
+ t.Cleanup(func() { slog.SetDefault(prev) })
+
+ var buf bytes.Buffer
+ slog.SetDefault(slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{
+ Level: slog.LevelInfo,
+ })))
+
+ p := &storepb.AuditLog{
+ Parent: "workspaces/ws-abc",
+ Method: "/bytebase.v1.AuthService/Login",
+ Resource: "[email protected]",
+ Severity: storepb.AuditLog_INFO,
+ User: "users/[email protected]",
+ Request: `{"email":"[email protected]","web":true}`,
+ Response: `{"user":{"name":"users/[email protected]","email":"[email protected]"}}`,
+ Status: &spb.Status{Code: 0, Message: ""},
+ Latency: durationpb.New(123_000_000), // 123ms
+ RequestMetadata: &storepb.RequestMetadata{
+ CallerIp: "10.0.1.50",
+ CallerSuppliedUserAgent: "TestAgent/1.0",
+ },
+ }
+
+ LogAuditToStdout(context.Background(), p)
+
+ // Every line the handler wrote is an independent JSON object.
+ lines := bytes.Split(bytes.TrimSpace(buf.Bytes()), []byte{'\n'})
+ a.Len(lines, 1, "LogAuditToStdout must emit exactly one JSON record")
+
+ var got map[string]any
+ a.NoError(json.Unmarshal(lines[0], &got),
+ "stdout record must be valid JSON: %s", string(lines[0]))
+
+ // Keys the customer explicitly greps for — these form our public contract.
+ // If any of these assertions need to change, it's a breaking change for
+ // everyone consuming audit stdout logs.
+ a.Equal("audit", got["log_type"], `log_type=="audit" is how operators filter audit lines from application logs`)
+ a.Equal("workspaces/ws-abc", got["parent"])
+ a.Equal("/bytebase.v1.AuthService/Login", got["method"])
+ a.Equal("[email protected]", got["resource"])
+ a.Equal("users/[email protected]", got["user"])
+ a.Equal("INFO", got["severity"])
+ a.Equal("10.0.1.50", got["client_ip"])
+ a.Equal("TestAgent/1.0", got["user_agent"])
+ a.Equal(float64(123), got["latency_ms"], "latency must be exposed in milliseconds")
+ a.Equal(`{"email":"[email protected]","web":true}`, got["request"],
+ "request payload must be emitted verbatim (already redacted upstream)")
+ a.Equal(`{"user":{"name":"users/[email protected]","email":"[email protected]"}}`, got["response"])
+
+ // Status code 0 (OK) should be reported explicitly so downstream pipelines
+ // can distinguish successful from failed calls.
+ a.Equal(float64(0), got["status_code"])
+
+ // slog standard fields — keep them stable too.
+ a.Equal("INFO", got["level"])
+ a.Equal("/bytebase.v1.AuthService/Login", got["msg"],
+ "slog msg is set to the method so operators can read the log without parsing")
+
+ // Error status round-trip: a failed call must emit status_code and status_message.
+ buf.Reset()
+ p2 := &storepb.AuditLog{
+ Parent: "workspaces/ws-abc",
+ Method: "/bytebase.v1.AuthService/Login",
+ Severity: storepb.AuditLog_INFO,
+ Status: &spb.Status{Code: 16, Message: "invalid email or password"}, // UNAUTHENTICATED
+ Latency: durationpb.New(5_000_000),
+ }
+ LogAuditToStdout(context.Background(), p2)
+
+ var failed map[string]any
+ a.NoError(json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &failed))
+ a.Equal(float64(16), failed["status_code"], "failed call must carry status_code")
+ a.Equal("invalid email or password", failed["status_message"],
+ "failed call must carry status_message")
+
+ // MCP-delegated calls carry their provenance in stdout too, so operators
+ // tailing container logs can trace an agent session without the API.
+ a.NotContains(got, "mcp_correlation_id",
+ "non-MCP rows must not emit MCP keys")
+ buf.Reset()
+ p3 := &storepb.AuditLog{
+ Parent: "workspaces/ws-abc",
+ Method: "/bytebase.v1.SQLService/Query",
+ Severity: storepb.AuditLog_INFO,
+ McpDelegation: &storepb.MCPDelegation{
+ Scope: "mcp:read-only",
+ Resource: "https://bb.example.com/mcp",
+ ClientId: "client-A",
+ CorrelationId: "corr-42",
+ },
+ }
+ LogAuditToStdout(context.Background(), p3)
+
+ var delegated map[string]any
+ a.NoError(json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &delegated))
+ a.Equal(true, delegated["mcp"], `mcp==true is how operators filter MCP-originated rows`)
+ a.Equal("corr-42", delegated["mcp_correlation_id"],
+ "the session correlation ID is the key operators pivot on")
+ a.Equal("mcp:read-only", delegated["mcp_scope"])
+ a.Equal("https://bb.example.com/mcp", delegated["mcp_resource"])
+ a.Equal("client-A", delegated["mcp_client_id"])
+}
diff --git a/backend/generated-go/store/audit_log.pb.go b/backend/generated-go/store/audit_log.pb.go
index fb7b5c4686..ee142008c1 100644
--- a/backend/generated-go/store/audit_log.pb.go
+++ b/backend/generated-go/store/audit_log.pb.go
@@ -118,9 +118,12 @@ type AuditLog struct {
ServiceData *anypb.Any `protobuf:"bytes,10,opt,name=service_data,json=serviceData,proto3" json:"service_data,omitempty"`
// Metadata about the operation.
RequestMetadata *RequestMetadata `protobuf:"bytes,11,opt,name=request_metadata,json=requestMetadata,proto3" json:"request_metadata,omitempty"`
- // MCP delegation provenance. Present exactly when the audited call arrived
- // through the MCP server's delegated credential; never set for public API
- // calls. Presence of this message is the MCP-origin marker.
+ // MCP delegation provenance. Present exactly when the entry belongs to MCP:
+ // the audited call arrived through the MCP server's delegated credential, or
+ // it is one of the two MCP doors that sit outside the API — the /mcp
+ // connection gate and the OAuth2 consent that mints the credential it checks.
+ // Never set for public API calls. Presence of this message is the MCP-origin
+ // marker.
McpDelegation *MCPDelegation `protobuf:"bytes,12,opt,name=mcp_delegation,json=mcpDelegation,proto3" json:"mcp_delegation,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -315,6 +318,12 @@ type MCPDelegation struct {
// boundary and session-scoped: the MCP SDK hands tool handlers the
// initialize-time context, so one MCP session carries one correlation ID
// across all of its tool calls.
+ //
+ // Empty on the entries that belong to no session — a refused consent, which
+ // never reached that boundary, and a refused connection, which is decided
+ // before the SDK resolves a session. Filling those with a fresh value would
+ // read as a session ID that correlates exactly one row, and a mid-session
+ // refusal would get an ID different from the rows the session already wrote.
CorrelationId string `protobuf:"bytes,4,opt,name=correlation_id,json=correlationId,proto3" json:"correlation_id,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
diff --git a/backend/generated-go/v1/audit_log_service.pb.go b/backend/generated-go/v1/audit_log_service.pb.go
index a89f9f8cf5..a897d55bdd 100644
--- a/backend/generated-go/v1/audit_log_service.pb.go
+++ b/backend/generated-go/v1/audit_log_service.pb.go
@@ -111,16 +111,21 @@ type SearchAuditLogsRequest struct {
// The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
//
// Supported filter:
- // - method: the API name, can be found in the docs, should start with "/bytebase.v1." prefix. For example "/bytebase.v1.UserService/CreateUser". Support "==" operator.
+ // - method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
+ // - resource: the resource the entry is about, support "==" operator.
// - severity: support "==" operator, check Severity enum in AuditLog message for values.
// - user: the actor, should in "users/{email}" format, support "==" operator.
// - create_time: support ">=" and "<=" operator.
+ // - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
+ // - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
//
// For example:
// - filter = "method == '/bytebase.v1.SQLService/Query'"
// - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
// - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
// - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
+ // - filter = "mcp == true"
+ // - filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
Filter string `protobuf:"bytes,1,opt,name=filter,proto3" json:"filter,omitempty"`
// The order by of the log.
// Only support order by create_time. The default sorting order is ascending.
diff --git a/backend/generated-go/v1/v1connect/workspace_service.connect.go b/backend/generated-go/v1/v1connect/workspace_service.connect.go
index ad4cf7e22d..d5e78d7db7 100644
--- a/backend/generated-go/v1/v1connect/workspace_service.connect.go
+++ b/backend/generated-go/v1/v1connect/workspace_service.connect.go
@@ -54,6 +54,9 @@ const (
// WorkspaceServiceSetIamPolicyProcedure is the fully-qualified name of the WorkspaceService's
// SetIamPolicy RPC.
WorkspaceServiceSetIamPolicyProcedure = "/bytebase.v1.WorkspaceService/SetIamPolicy"
+ // WorkspaceServiceGetMCPInfoProcedure is the fully-qualified name of the WorkspaceService's
+ // GetMCPInfo RPC.
+ WorkspaceServiceGetMCPInfoProcedure = "/bytebase.v1.WorkspaceService/GetMCPInfo"
// WorkspaceServiceRotateDirectorySyncTokenProcedure is the fully-qualified name of the
// WorkspaceService's RotateDirectorySyncToken RPC.
WorkspaceServiceRotateDirectorySyncTokenProcedure = "/bytebase.v1.WorkspaceService/RotateDirectorySyncToken"
@@ -85,6 +88,18 @@ type WorkspaceServiceClient interface {
// Sets IAM policy for the workspace.
// Permissions required: bb.workspaces.setIamPolicy
SetIamPolicy(context.Context, *connect.Request[v1.SetIamPolicyRequest]) (*connect.Response[v1.IamPolicy], error)
+ // Gets what MCP (Model Context Protocol) does in this workspace: the
+ // capability ceiling in force, what each ceiling serves, and the per-engine
+ // facts a read-only session depends on. The workspace is resolved from the
+ // authenticated session.
+ //
+ // Served to MCP sessions. An agent asking what it may do here is the point:
+ // the response says nothing a session's own denials do not already say, one
+ // refusal at a time, and knowing it up front is what stops the agent
+ // planning work the ceiling was never going to serve.
+ //
+ // Permissions required: None (authentication required)
+ GetMCPInfo(context.Context, *connect.Request[v1.GetMCPInfoRequest]) (*connect.Response[v1.MCPInfo], error)
// Mints a new directory sync (SCIM) token, immediately invalidating the
// previous one. The plaintext token is returned exactly once and cannot be
// retrieved afterwards; only its hash is stored. Callers that lose it must
@@ -146,6 +161,12 @@ func NewWorkspaceServiceClient(httpClient connect.HTTPClient, baseURL string, op
connect.WithSchema(workspaceServiceMethods.ByName("SetIamPolicy")),
connect.WithClientOptions(opts...),
),
+ getMCPInfo: connect.NewClient[v1.GetMCPInfoRequest, v1.MCPInfo](
+ httpClient,
+ baseURL+WorkspaceServiceGetMCPInfoProcedure,
+ connect.WithSchema(workspaceServiceMethods.ByName("GetMCPInfo")),
+ connect.WithClientOptions(opts...),
+ ),
rotateDirectorySyncToken: connect.NewClient[v1.RotateDirectorySyncTokenRequest, v1.RotateDirectorySyncTokenResponse](
httpClient,
baseURL+WorkspaceServiceRotateDirectorySyncTokenProcedure,
@@ -164,6 +185,7 @@ type workspaceServiceClient struct {
deleteWorkspace *connect.Client[v1.DeleteWorkspaceRequest, v1.LoginResponse]
leaveWorkspace *connect.Client[v1.LeaveWorkspaceRequest, v1.LoginResponse]
setIamPolicy *connect.Client[v1.SetIamPolicyRequest, v1.IamPolicy]
+ getMCPInfo *connect.Client[v1.GetMCPInfoRequest, v1.MCPInfo]
rotateDirectorySyncToken *connect.Client[v1.RotateDirectorySyncTokenRequest, v1.RotateDirectorySyncTokenResponse]
}
@@ -202,6 +224,11 @@ func (c *workspaceServiceClient) SetIamPolicy(ctx context.Context, req *connect.
return c.setIamPolicy.CallUnary(ctx, req)
}
+// GetMCPInfo calls bytebase.v1.WorkspaceService.GetMCPInfo.
+func (c *workspaceServiceClient) GetMCPInfo(ctx context.Context, req *connect.Request[v1.GetMCPInfoRequest]) (*connect.Response[v1.MCPInfo], error) {
+ return c.getMCPInfo.CallUnary(ctx, req)
+}
+
// RotateDirectorySyncToken calls bytebase.v1.WorkspaceService.RotateDirectorySyncToken.
func (c *workspaceServiceClient) RotateDirectorySyncToken(ctx context.Context, req *connect.Request[v1.RotateDirectorySyncTokenRequest]) (*connect.Response[v1.RotateDirectorySyncTokenResponse], error) {
return c.rotateDirectorySyncToken.CallUnary(ctx, req)
@@ -233,6 +260,18 @@ type WorkspaceServiceHandler interface {
// Sets IAM policy for the workspace.
// Permissions required: bb.workspaces.setIamPolicy
SetIamPolicy(context.Context, *connect.Request[v1.SetIamPolicyRequest]) (*connect.Response[v1.IamPolicy], error)
+ // Gets what MCP (Model Context Protocol) does in this workspace: the
+ // capability ceiling in force, what each ceiling serves, and the per-engine
+ // facts a read-only session depends on. The workspace is resolved from the
+ // authenticated session.
+ //
+ // Served to MCP sessions. An agent asking what it may do here is the point:
+ // the response says nothing a session's own denials do not already say, one
+ // refusal at a time, and knowing it up front is what stops the agent
+ // planning work the ceiling was never going to serve.
+ //
+ // Permissions required: None (authentication required)
+ GetMCPInfo(context.Context, *connect.Request[v1.GetMCPInfoRequest]) (*connect.Response[v1.MCPInfo], error)
// Mints a new directory sync (SCIM) token, immediately invalidating the
// previous one. The plaintext token is returned exactly once and cannot be
// retrieved afterwards; only its hash is stored. Callers that lose it must
@@ -290,6 +329,12 @@ func NewWorkspaceServiceHandler(svc WorkspaceServiceHandler, opts ...connect.Han
connect.WithSchema(workspaceServiceMethods.ByName("SetIamPolicy")),
connect.WithHandlerOptions(opts...),
)
+ workspaceServiceGetMCPInfoHandler := connect.NewUnaryHandler(
+ WorkspaceServiceGetMCPInfoProcedure,
+ svc.GetMCPInfo,
+ connect.WithSchema(workspaceServiceMethods.ByName("GetMCPInfo")),
+ connect.WithHandlerOptions(opts...),
+ )
workspaceServiceRotateDirectorySyncTokenHandler := connect.NewUnaryHandler(
WorkspaceServiceRotateDirectorySyncTokenProcedure,
svc.RotateDirectorySyncToken,
@@ -312,6 +357,8 @@ func NewWorkspaceServiceHandler(svc WorkspaceServiceHandler, opts ...connect.Han
workspaceServiceLeaveWorkspaceHandler.ServeHTTP(w, r)
case WorkspaceServiceSetIamPolicyProcedure:
workspaceServiceSetIamPolicyHandler.ServeHTTP(w, r)
+ case WorkspaceServiceGetMCPInfoProcedure:
+ workspaceServiceGetMCPInfoHandler.ServeHTTP(w, r)
case WorkspaceServiceRotateDirectorySyncTokenProcedure:
workspaceServiceRotateDirectorySyncTokenHandler.ServeHTTP(w, r)
default:
@@ -351,6 +398,10 @@ func (UnimplementedWorkspaceServiceHandler) SetIamPolicy(context.Context, *conne
return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.WorkspaceService.SetIamPolicy is not implemented"))
}
+func (UnimplementedWorkspaceServiceHandler) GetMCPInfo(context.Context, *connect.Request[v1.GetMCPInfoRequest]) (*connect.Response[v1.MCPInfo], error) {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.WorkspaceService.GetMCPInfo is not implemented"))
+}
+
func (UnimplementedWorkspaceServiceHandler) RotateDirectorySyncToken(context.Context, *connect.Request[v1.RotateDirectorySyncTokenRequest]) (*connect.Response[v1.RotateDirectorySyncTokenResponse], error) {
return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.WorkspaceService.RotateDirectorySyncToken is not implemented"))
}
diff --git a/backend/generated-go/v1/workspace_service.pb.go b/backend/generated-go/v1/workspace_service.pb.go
index 99c9e0d151..6a4e6f2f0d 100644
--- a/backend/generated-go/v1/workspace_service.pb.go
+++ b/backend/generated-go/v1/workspace_service.pb.go
@@ -23,6 +23,508 @@ const (
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
+// How much of a read-only ceiling this engine can be held to.
+type MCPEngineEnforcement_ReadOnlyDepth int32
+
+const (
+ MCPEngineEnforcement_READ_ONLY_DEPTH_UNSPECIFIED MCPEngineEnforcement_ReadOnlyDepth = 0
+ // Bytebase has no read-only classifier for this engine, so a read-only
+ // session is refused every statement on it, including a plain SELECT.
+ MCPEngineEnforcement_UNSUPPORTED MCPEngineEnforcement_ReadOnlyDepth = 1
+ // Every statement is classified before it runs and a request holding one
+ // that is not a read is refused whole. Nothing below that: the driver does
+ // not open a read-only database session, except where the note says
+ // otherwise.
+ MCPEngineEnforcement_STATEMENT MCPEngineEnforcement_ReadOnlyDepth = 2
+ // Statement classification, and the driver opens the database session
+ // read-only as well, so the engine refuses most writes the classifier
+ // missed. Not a proof: a statement that classifies as a read can still call
+ // a function that switches the session setting back off.
+ MCPEngineEnforcement_STATEMENT_AND_SESSION MCPEngineEnforcement_ReadOnlyDepth = 3
+)
+
+// Enum value maps for MCPEngineEnforcement_ReadOnlyDepth.
+var (
+ MCPEngineEnforcement_ReadOnlyDepth_name = map[int32]string{
+ 0: "READ_ONLY_DEPTH_UNSPECIFIED",
+ 1: "UNSUPPORTED",
+ 2: "STATEMENT",
+ 3: "STATEMENT_AND_SESSION",
+ }
+ MCPEngineEnforcement_ReadOnlyDepth_value = map[string]int32{
+ "READ_ONLY_DEPTH_UNSPECIFIED": 0,
+ "UNSUPPORTED": 1,
+ "STATEMENT": 2,
+ "STATEMENT_AND_SESSION": 3,
+ }
+)
+
+func (x MCPEngineEnforcement_ReadOnlyDepth) Enum() *MCPEngineEnforcement_ReadOnlyDepth {
+ p := new(MCPEngineEnforcement_ReadOnlyDepth)
+ *p = x
+ return p
+}
+
+func (x MCPEngineEnforcement_ReadOnlyDepth) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (MCPEngineEnforcement_ReadOnlyDepth) Descriptor() protoreflect.EnumDescriptor {
+ return file_v1_workspace_service_proto_enumTypes[0].Descriptor()
+}
+
+func (MCPEngineEnforcement_ReadOnlyDepth) Type() protoreflect.EnumType {
+ return &file_v1_workspace_service_proto_enumTypes[0]
+}
+
+func (x MCPEngineEnforcement_ReadOnlyDepth) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use MCPEngineEnforcement_ReadOnlyDepth.Descriptor instead.
+func (MCPEngineEnforcement_ReadOnlyDepth) EnumDescriptor() ([]byte, []int) {
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{4, 0}
+}
+
+// How Bytebase masks results on this engine, which is what decides whether
+// ignoring masking exemptions changes anything here.
+type MCPEngineEnforcement_Masking int32
+
+const (
+ MCPEngineEnforcement_MASKING_UNSPECIFIED MCPEngineEnforcement_Masking = 0
+ // Bytebase does not mask on this engine. Nothing narrows what a session
+ // reads, and ignoring masking exemptions does nothing.
+ MCPEngineEnforcement_NONE MCPEngineEnforcement_Masking = 1
+ // Column masking. A masking policy substitutes values in query results,
+ // and the exemptions granted to the caller are what let them see the real
+ // value — which is what ignoring exemptions suppresses.
+ MCPEngineEnforcement_COLUMN MCPEngineEnforcement_Masking = 2
+ // Document masking. Results are masked, but exemptions are never consulted
+ // on this path, so ignoring them changes nothing here either.
+ MCPEngineEnforcement_DOCUMENT MCPEngineEnforcement_Masking = 3
+)
+
+// Enum value maps for MCPEngineEnforcement_Masking.
+var (
+ MCPEngineEnforcement_Masking_name = map[int32]string{
+ 0: "MASKING_UNSPECIFIED",
+ 1: "NONE",
+ 2: "COLUMN",
+ 3: "DOCUMENT",
+ }
+ MCPEngineEnforcement_Masking_value = map[string]int32{
+ "MASKING_UNSPECIFIED": 0,
+ "NONE": 1,
+ "COLUMN": 2,
+ "DOCUMENT": 3,
+ }
+)
+
+func (x MCPEngineEnforcement_Masking) Enum() *MCPEngineEnforcement_Masking {
+ p := new(MCPEngineEnforcement_Masking)
+ *p = x
+ return p
+}
+
+func (x MCPEngineEnforcement_Masking) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (MCPEngineEnforcement_Masking) Descriptor() protoreflect.EnumDescriptor {
+ return file_v1_workspace_service_proto_enumTypes[1].Descriptor()
+}
+
+func (MCPEngineEnforcement_Masking) Type() protoreflect.EnumType {
+ return &file_v1_workspace_service_proto_enumTypes[1]
+}
+
+func (x MCPEngineEnforcement_Masking) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use MCPEngineEnforcement_Masking.Descriptor instead.
+func (MCPEngineEnforcement_Masking) EnumDescriptor() ([]byte, []int) {
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{4, 1}
+}
+
+type GetMCPInfoRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *GetMCPInfoRequest) Reset() {
+ *x = GetMCPInfoRequest{}
+ mi := &file_v1_workspace_service_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *GetMCPInfoRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*GetMCPInfoRequest) ProtoMessage() {}
+
+func (x *GetMCPInfoRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_workspace_service_proto_msgTypes[0]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use GetMCPInfoRequest.ProtoReflect.Descriptor instead.
+func (*GetMCPInfoRequest) Descriptor() ([]byte, []int) {
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{0}
+}
+
+// MCPInfo is what MCP does in this workspace: the ceiling in force, what each
+// ceiling serves, and the per-engine facts a read-only session depends on.
+//
+// Everything here is resolved when the request is served, never from a stored
+// copy: the method list comes off the compiled API descriptors and the engine
+// answers off the code that enforces them, so a build whose rules changed
+// cannot describe the rules of the build before it.
+type MCPInfo struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The workspace this describes. Format: workspaces/{workspace}. Not this
+ // message's own resource name — MCPInfo is not a named resource and there is
+ // nothing to get it by.
+ Workspace string `protobuf:"bytes,1,opt,name=workspace,proto3" json:"workspace,omitempty"`
+ // The ceiling in force for this workspace. A workspace that never configured
+ // MCP resolves to READ_WRITE.
+ Capability MCPSetting_Capability `protobuf:"varint,2,opt,name=capability,proto3,enum=bytebase.v1.MCPSetting_Capability" json:"capability,omitempty"`
+ // What each ceiling serves, including the one in force, so an admin can
+ // compare the choices rather than only read the current answer.
+ Modes []*MCPCapabilityMode `protobuf:"bytes,3,rep,name=modes,proto3" json:"modes,omitempty"`
+ // Every API method some ceiling serves. A mode serves a method when the
+ // method's class is one of that mode's served_classes, which is the ceiling
+ // rule the gate evaluates. Methods no ceiling serves are absent.
+ //
+ // Being listed is necessary, not sufficient. The caller still needs the
+ // permission, and two further rules narrow what a served method does: a
+ // handful of methods are refused on the shape of the request (an issue that
+ // would grant a permission, a rollout that skips approval), and under
+ // READ_ONLY every statement SQLService/Query runs must classify as a read.
+ Methods []*MCPMethod `protobuf:"bytes,4,rep,name=methods,proto3" json:"methods,omitempty"`
+ // What a read-only session and the masking toggle actually reach, per engine.
+ // Both are engine-conditional in ways the ceiling alone does not show.
+ Engines []*MCPEngineEnforcement `protobuf:"bytes,5,rep,name=engines,proto3" json:"engines,omitempty"`
+ // Whether this workspace stops applying the caller's own unmasking
+ // provisioning to MCP requests. It decides which branch of each engine's
+ // masking state a caller is in, and no other API tells an MCP session:
+ // SettingService/GetSetting is served by no ceiling.
+ IgnoreMaskingExemptions bool `protobuf:"varint,6,opt,name=ignore_masking_exemptions,json=ignoreMaskingExemptions,proto3" json:"ignore_masking_exemptions,omitempty"`
+ // Whether data masking is licensed for this workspace. When false nothing is
+ // masked whatever an engine supports, so the masking states below describe a
+ // mechanism that does not run. Licensing can also be set per instance, so a
+ // true here is the workspace answer, not a promise about every instance.
+ DataMaskingAvailable bool `protobuf:"varint,7,opt,name=data_masking_available,json=dataMaskingAvailable,proto3" json:"data_masking_available,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *MCPInfo) Reset() {
+ *x = MCPInfo{}
+ mi := &file_v1_workspace_service_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *MCPInfo) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MCPInfo) ProtoMessage() {}
+
+func (x *MCPInfo) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_workspace_service_proto_msgTypes[1]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use MCPInfo.ProtoReflect.Descriptor instead.
+func (*MCPInfo) Descriptor() ([]byte, []int) {
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *MCPInfo) GetWorkspace() string {
+ if x != nil {
+ return x.Workspace
+ }
+ return ""
+}
+
+func (x *MCPInfo) GetCapability() MCPSetting_Capability {
+ if x != nil {
+ return x.Capability
+ }
+ return MCPSetting_CAPABILITY_UNSPECIFIED
+}
+
+func (x *MCPInfo) GetModes() []*MCPCapabilityMode {
+ if x != nil {
+ return x.Modes
+ }
+ return nil
+}
+
+func (x *MCPInfo) GetMethods() []*MCPMethod {
+ if x != nil {
+ return x.Methods
+ }
+ return nil
+}
+
+func (x *MCPInfo) GetEngines() []*MCPEngineEnforcement {
+ if x != nil {
+ return x.Engines
+ }
+ return nil
+}
+
+func (x *MCPInfo) GetIgnoreMaskingExemptions() bool {
+ if x != nil {
+ return x.IgnoreMaskingExemptions
+ }
+ return false
+}
+
+func (x *MCPInfo) GetDataMaskingAvailable() bool {
+ if x != nil {
+ return x.DataMaskingAvailable
+ }
+ return false
+}
+
+// MCPCapabilityMode is one ceiling and the method classes it serves.
+type MCPCapabilityMode struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Capability MCPSetting_Capability `protobuf:"varint,1,opt,name=capability,proto3,enum=bytebase.v1.MCPSetting_Capability" json:"capability,omitempty"`
+ // Empty means the ceiling serves nothing, which is what DISABLED is.
+ ServedClasses []MCPMethodClass `protobuf:"varint,2,rep,packed,name=served_classes,json=servedClasses,proto3,enum=bytebase.v1.MCPMethodClass" json:"served_classes,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *MCPCapabilityMode) Reset() {
+ *x = MCPCapabilityMode{}
+ mi := &file_v1_workspace_service_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *MCPCapabilityMode) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MCPCapabilityMode) ProtoMessage() {}
+
+func (x *MCPCapabilityMode) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_workspace_service_proto_msgTypes[2]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use MCPCapabilityMode.ProtoReflect.Descriptor instead.
+func (*MCPCapabilityMode) Descriptor() ([]byte, []int) {
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *MCPCapabilityMode) GetCapability() MCPSetting_Capability {
+ if x != nil {
+ return x.Capability
+ }
+ return MCPSetting_CAPABILITY_UNSPECIFIED
+}
+
+func (x *MCPCapabilityMode) GetServedClasses() []MCPMethodClass {
+ if x != nil {
+ return x.ServedClasses
+ }
+ return nil
+}
+
+// MCPMethod is one API method an MCP session can reach, and what decides it.
+type MCPMethod struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The method as an audit entry names it, so a denial can be found by it.
+ // Example: /bytebase.v1.SQLService/Query
+ Method string `protobuf:"bytes,1,opt,name=method,proto3" json:"method,omitempty"`
+ // The same method as call_api takes it.
+ // Example: bytebase.v1.SQLService.Query
+ OperationId string `protobuf:"bytes,4,opt,name=operation_id,json=operationId,proto3" json:"operation_id,omitempty"`
+ Class MCPMethodClass `protobuf:"varint,2,opt,name=class,proto3,enum=bytebase.v1.MCPMethodClass" json:"class,omitempty"`
+ // The IAM permission the method declares. The ceiling never grants: a session
+ // may call a served method only where the person it acts for could.
+ //
+ // Empty means the method declares no permission, which is NOT the same as
+ // needing none — a method that authorizes inside its handler declares nothing
+ // here. auth_method says which case an empty value is.
+ Permission string `protobuf:"bytes,3,opt,name=permission,proto3" json:"permission,omitempty"`
+ // How the method authorizes. IAM means the permission above is the primary
+ // rule, though not always the only one — an update carrying allow_missing
+ // additionally requires the matching create permission. CUSTOM means the
+ // handler decides and the permission field is silent.
+ AuthMethod AuthMethod `protobuf:"varint,5,opt,name=auth_method,json=authMethod,proto3,enum=bytebase.v1.AuthMethod" json:"auth_method,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *MCPMethod) Reset() {
+ *x = MCPMethod{}
+ mi := &file_v1_workspace_service_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *MCPMethod) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MCPMethod) ProtoMessage() {}
+
+func (x *MCPMethod) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_workspace_service_proto_msgTypes[3]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use MCPMethod.ProtoReflect.Descriptor instead.
+func (*MCPMethod) Descriptor() ([]byte, []int) {
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *MCPMethod) GetMethod() string {
+ if x != nil {
+ return x.Method
+ }
+ return ""
+}
+
+func (x *MCPMethod) GetOperationId() string {
+ if x != nil {
+ return x.OperationId
+ }
+ return ""
+}
+
+func (x *MCPMethod) GetClass() MCPMethodClass {
+ if x != nil {
+ return x.Class
+ }
+ return MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED
+}
+
+func (x *MCPMethod) GetPermission() string {
+ if x != nil {
+ return x.Permission
+ }
+ return ""
+}
+
+func (x *MCPMethod) GetAuthMethod() AuthMethod {
+ if x != nil {
+ return x.AuthMethod
+ }
+ return AuthMethod_AUTH_METHOD_UNSPECIFIED
+}
+
+// MCPEngineEnforcement is what the read-only ceiling and the masking toggle
+// reach on one database engine.
+type MCPEngineEnforcement struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Engine Engine `protobuf:"varint,1,opt,name=engine,proto3,enum=bytebase.v1.Engine" json:"engine,omitempty"`
+ ReadOnlyDepth MCPEngineEnforcement_ReadOnlyDepth `protobuf:"varint,2,opt,name=read_only_depth,json=readOnlyDepth,proto3,enum=bytebase.v1.MCPEngineEnforcement_ReadOnlyDepth" json:"read_only_depth,omitempty"`
+ Masking MCPEngineEnforcement_Masking `protobuf:"varint,3,opt,name=masking,proto3,enum=bytebase.v1.MCPEngineEnforcement_Masking" json:"masking,omitempty"`
+ // Where the answers above are the floor rather than the whole story. Empty
+ // for most engines.
+ Note string `protobuf:"bytes,4,opt,name=note,proto3" json:"note,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *MCPEngineEnforcement) Reset() {
+ *x = MCPEngineEnforcement{}
+ mi := &file_v1_workspace_service_proto_msgTypes[4]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *MCPEngineEnforcement) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MCPEngineEnforcement) ProtoMessage() {}
+
+func (x *MCPEngineEnforcement) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_workspace_service_proto_msgTypes[4]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use MCPEngineEnforcement.ProtoReflect.Descriptor instead.
+func (*MCPEngineEnforcement) Descriptor() ([]byte, []int) {
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *MCPEngineEnforcement) GetEngine() Engine {
+ if x != nil {
+ return x.Engine
+ }
+ return Engine_ENGINE_UNSPECIFIED
+}
+
+func (x *MCPEngineEnforcement) GetReadOnlyDepth() MCPEngineEnforcement_ReadOnlyDepth {
+ if x != nil {
+ return x.ReadOnlyDepth
+ }
+ return MCPEngineEnforcement_READ_ONLY_DEPTH_UNSPECIFIED
+}
+
+func (x *MCPEngineEnforcement) GetMasking() MCPEngineEnforcement_Masking {
+ if x != nil {
+ return x.Masking
+ }
+ return MCPEngineEnforcement_MASKING_UNSPECIFIED
+}
+
+func (x *MCPEngineEnforcement) GetNote() string {
+ if x != nil {
+ return x.Note
+ }
+ return ""
+}
+
type RotateDirectorySyncTokenRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The workspace whose directory sync token is rotated.
@@ -34,7 +536,7 @@ type RotateDirectorySyncTokenRequest struct {
func (x *RotateDirectorySyncTokenRequest) Reset() {
*x = RotateDirectorySyncTokenRequest{}
- mi := &file_v1_workspace_service_proto_msgTypes[0]
+ mi := &file_v1_workspace_service_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -46,7 +548,7 @@ func (x *RotateDirectorySyncTokenRequest) String() string {
func (*RotateDirectorySyncTokenRequest) ProtoMessage() {}
func (x *RotateDirectorySyncTokenRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_workspace_service_proto_msgTypes[0]
+ mi := &file_v1_workspace_service_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -59,7 +561,7 @@ func (x *RotateDirectorySyncTokenRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RotateDirectorySyncTokenRequest.ProtoReflect.Descriptor instead.
func (*RotateDirectorySyncTokenRequest) Descriptor() ([]byte, []int) {
- return file_v1_workspace_service_proto_rawDescGZIP(), []int{0}
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{5}
}
func (x *RotateDirectorySyncTokenRequest) GetName() string {
@@ -79,7 +581,7 @@ type RotateDirectorySyncTokenResponse struct {
func (x *RotateDirectorySyncTokenResponse) Reset() {
*x = RotateDirectorySyncTokenResponse{}
- mi := &file_v1_workspace_service_proto_msgTypes[1]
+ mi := &file_v1_workspace_service_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -91,7 +593,7 @@ func (x *RotateDirectorySyncTokenResponse) String() string {
func (*RotateDirectorySyncTokenResponse) ProtoMessage() {}
func (x *RotateDirectorySyncTokenResponse) ProtoReflect() protoreflect.Message {
- mi := &file_v1_workspace_service_proto_msgTypes[1]
+ mi := &file_v1_workspace_service_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -104,7 +606,7 @@ func (x *RotateDirectorySyncTokenResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use RotateDirectorySyncTokenResponse.ProtoReflect.Descriptor instead.
func (*RotateDirectorySyncTokenResponse) Descriptor() ([]byte, []int) {
- return file_v1_workspace_service_proto_rawDescGZIP(), []int{1}
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{6}
}
func (x *RotateDirectorySyncTokenResponse) GetToken() string {
@@ -122,7 +624,7 @@ type ListWorkspacesRequest struct {
func (x *ListWorkspacesRequest) Reset() {
*x = ListWorkspacesRequest{}
- mi := &file_v1_workspace_service_proto_msgTypes[2]
+ mi := &file_v1_workspace_service_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -134,7 +636,7 @@ func (x *ListWorkspacesRequest) String() string {
func (*ListWorkspacesRequest) ProtoMessage() {}
func (x *ListWorkspacesRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_workspace_service_proto_msgTypes[2]
+ mi := &file_v1_workspace_service_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -147,7 +649,7 @@ func (x *ListWorkspacesRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use ListWorkspacesRequest.ProtoReflect.Descriptor instead.
func (*ListWorkspacesRequest) Descriptor() ([]byte, []int) {
- return file_v1_workspace_service_proto_rawDescGZIP(), []int{2}
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{7}
}
type ListWorkspacesResponse struct {
@@ -159,7 +661,7 @@ type ListWorkspacesResponse struct {
func (x *ListWorkspacesResponse) Reset() {
*x = ListWorkspacesResponse{}
- mi := &file_v1_workspace_service_proto_msgTypes[3]
+ mi := &file_v1_workspace_service_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -171,7 +673,7 @@ func (x *ListWorkspacesResponse) String() string {
func (*ListWorkspacesResponse) ProtoMessage() {}
func (x *ListWorkspacesResponse) ProtoReflect() protoreflect.Message {
- mi := &file_v1_workspace_service_proto_msgTypes[3]
+ mi := &file_v1_workspace_service_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -184,7 +686,7 @@ func (x *ListWorkspacesResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use ListWorkspacesResponse.ProtoReflect.Descriptor instead.
func (*ListWorkspacesResponse) Descriptor() ([]byte, []int) {
- return file_v1_workspace_service_proto_rawDescGZIP(), []int{3}
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{8}
}
func (x *ListWorkspacesResponse) GetWorkspaces() []*Workspace {
@@ -205,7 +707,7 @@ type GetWorkspaceRequest struct {
func (x *GetWorkspaceRequest) Reset() {
*x = GetWorkspaceRequest{}
- mi := &file_v1_workspace_service_proto_msgTypes[4]
+ mi := &file_v1_workspace_service_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -217,7 +719,7 @@ func (x *GetWorkspaceRequest) String() string {
func (*GetWorkspaceRequest) ProtoMessage() {}
func (x *GetWorkspaceRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_workspace_service_proto_msgTypes[4]
+ mi := &file_v1_workspace_service_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -230,7 +732,7 @@ func (x *GetWorkspaceRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use GetWorkspaceRequest.ProtoReflect.Descriptor instead.
func (*GetWorkspaceRequest) Descriptor() ([]byte, []int) {
- return file_v1_workspace_service_proto_rawDescGZIP(), []int{4}
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{9}
}
func (x *GetWorkspaceRequest) GetName() string {
@@ -253,7 +755,7 @@ type Workspace struct {
func (x *Workspace) Reset() {
*x = Workspace{}
- mi := &file_v1_workspace_service_proto_msgTypes[5]
+ mi := &file_v1_workspace_service_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -265,7 +767,7 @@ func (x *Workspace) String() string {
func (*Workspace) ProtoMessage() {}
func (x *Workspace) ProtoReflect() protoreflect.Message {
- mi := &file_v1_workspace_service_proto_msgTypes[5]
+ mi := &file_v1_workspace_service_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -278,7 +780,7 @@ func (x *Workspace) ProtoReflect() protoreflect.Message {
// Deprecated: Use Workspace.ProtoReflect.Descriptor instead.
func (*Workspace) Descriptor() ([]byte, []int) {
- return file_v1_workspace_service_proto_rawDescGZIP(), []int{5}
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{10}
}
func (x *Workspace) GetName() string {
@@ -312,7 +814,7 @@ type DeleteWorkspaceRequest struct {
func (x *DeleteWorkspaceRequest) Reset() {
*x = DeleteWorkspaceRequest{}
- mi := &file_v1_workspace_service_proto_msgTypes[6]
+ mi := &file_v1_workspace_service_proto_msgTypes[11]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -324,7 +826,7 @@ func (x *DeleteWorkspaceRequest) String() string {
func (*DeleteWorkspaceRequest) ProtoMessage() {}
func (x *DeleteWorkspaceRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_workspace_service_proto_msgTypes[6]
+ mi := &file_v1_workspace_service_proto_msgTypes[11]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -337,7 +839,7 @@ func (x *DeleteWorkspaceRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use DeleteWorkspaceRequest.ProtoReflect.Descriptor instead.
func (*DeleteWorkspaceRequest) Descriptor() ([]byte, []int) {
- return file_v1_workspace_service_proto_rawDescGZIP(), []int{6}
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{11}
}
func (x *DeleteWorkspaceRequest) GetName() string {
@@ -357,7 +859,7 @@ type UpdateWorkspaceRequest struct {
func (x *UpdateWorkspaceRequest) Reset() {
*x = UpdateWorkspaceRequest{}
- mi := &file_v1_workspace_service_proto_msgTypes[7]
+ mi := &file_v1_workspace_service_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -369,7 +871,7 @@ func (x *UpdateWorkspaceRequest) String() string {
func (*UpdateWorkspaceRequest) ProtoMessage() {}
func (x *UpdateWorkspaceRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_workspace_service_proto_msgTypes[7]
+ mi := &file_v1_workspace_service_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -382,7 +884,7 @@ func (x *UpdateWorkspaceRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use UpdateWorkspaceRequest.ProtoReflect.Descriptor instead.
func (*UpdateWorkspaceRequest) Descriptor() ([]byte, []int) {
- return file_v1_workspace_service_proto_rawDescGZIP(), []int{7}
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{12}
}
func (x *UpdateWorkspaceRequest) GetWorkspace() *Workspace {
@@ -409,7 +911,7 @@ type LeaveWorkspaceRequest struct {
func (x *LeaveWorkspaceRequest) Reset() {
*x = LeaveWorkspaceRequest{}
- mi := &file_v1_workspace_service_proto_msgTypes[8]
+ mi := &file_v1_workspace_service_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -421,7 +923,7 @@ func (x *LeaveWorkspaceRequest) String() string {
func (*LeaveWorkspaceRequest) ProtoMessage() {}
func (x *LeaveWorkspaceRequest) ProtoReflect() protoreflect.Message {
- mi := &file_v1_workspace_service_proto_msgTypes[8]
+ mi := &file_v1_workspace_service_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -434,7 +936,7 @@ func (x *LeaveWorkspaceRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use LeaveWorkspaceRequest.ProtoReflect.Descriptor instead.
func (*LeaveWorkspaceRequest) Descriptor() ([]byte, []int) {
- return file_v1_workspace_service_proto_rawDescGZIP(), []int{8}
+ return file_v1_workspace_service_proto_rawDescGZIP(), []int{13}
}
func (x *LeaveWorkspaceRequest) GetName() string {
@@ -448,7 +950,48 @@ var File_v1_workspace_service_proto protoreflect.FileDescriptor
const file_v1_workspace_service_proto_rawDesc = "" +
"\n" +
- "\x1av1/workspace_service.proto\x12\vbytebase.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a google/protobuf/field_mask.proto\x1a\x13v1/annotation.proto\x1a\x15v1/auth_service.proto\x1a\x13v1/iam_policy.proto\"U\n" +
+ "\x1av1/workspace_service.proto\x12\vbytebase.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a google/protobuf/field_mask.proto\x1a\x13v1/annotation.proto\x1a\x15v1/auth_service.proto\x1a\x0fv1/common.proto\x1a\x13v1/iam_policy.proto\x1a\x18v1/setting_service.proto\"\x13\n" +
+ "\x11GetMCPInfoRequest\"\xa5\x03\n" +
+ "\aMCPInfo\x12!\n" +
+ "\tworkspace\x18\x01 \x01(\tB\x03\xe0A\x03R\tworkspace\x12G\n" +
+ "\n" +
+ "capability\x18\x02 \x01(\x0e2\".bytebase.v1.MCPSetting.CapabilityB\x03\xe0A\x03R\n" +
+ "capability\x129\n" +
+ "\x05modes\x18\x03 \x03(\v2\x1e.bytebase.v1.MCPCapabilityModeB\x03\xe0A\x03R\x05modes\x125\n" +
+ "\amethods\x18\x04 \x03(\v2\x16.bytebase.v1.MCPMethodB\x03\xe0A\x03R\amethods\x12@\n" +
+ "\aengines\x18\x05 \x03(\v2!.bytebase.v1.MCPEngineEnforcementB\x03\xe0A\x03R\aengines\x12?\n" +
+ "\x19ignore_masking_exemptions\x18\x06 \x01(\bB\x03\xe0A\x03R\x17ignoreMaskingExemptions\x129\n" +
+ "\x16data_masking_available\x18\a \x01(\bB\x03\xe0A\x03R\x14dataMaskingAvailable\"\x9b\x01\n" +
+ "\x11MCPCapabilityMode\x12B\n" +
+ "\n" +
+ "capability\x18\x01 \x01(\x0e2\".bytebase.v1.MCPSetting.CapabilityR\n" +
+ "capability\x12B\n" +
+ "\x0eserved_classes\x18\x02 \x03(\x0e2\x1b.bytebase.v1.MCPMethodClassR\rservedClasses\"\xd3\x01\n" +
+ "\tMCPMethod\x12\x16\n" +
+ "\x06method\x18\x01 \x01(\tR\x06method\x12!\n" +
+ "\foperation_id\x18\x04 \x01(\tR\voperationId\x121\n" +
+ "\x05class\x18\x02 \x01(\x0e2\x1b.bytebase.v1.MCPMethodClassR\x05class\x12\x1e\n" +
+ "\n" +
+ "permission\x18\x03 \x01(\tR\n" +
+ "permission\x128\n" +
+ "\vauth_method\x18\x05 \x01(\x0e2\x17.bytebase.v1.AuthMethodR\n" +
+ "authMethod\"\xaa\x03\n" +
+ "\x14MCPEngineEnforcement\x12+\n" +
+ "\x06engine\x18\x01 \x01(\x0e2\x13.bytebase.v1.EngineR\x06engine\x12W\n" +
+ "\x0fread_only_depth\x18\x02 \x01(\x0e2/.bytebase.v1.MCPEngineEnforcement.ReadOnlyDepthR\rreadOnlyDepth\x12C\n" +
+ "\amasking\x18\x03 \x01(\x0e2).bytebase.v1.MCPEngineEnforcement.MaskingR\amasking\x12\x12\n" +
+ "\x04note\x18\x04 \x01(\tR\x04note\"k\n" +
+ "\rReadOnlyDepth\x12\x1f\n" +
+ "\x1bREAD_ONLY_DEPTH_UNSPECIFIED\x10\x00\x12\x0f\n" +
+ "\vUNSUPPORTED\x10\x01\x12\r\n" +
+ "\tSTATEMENT\x10\x02\x12\x19\n" +
+ "\x15STATEMENT_AND_SESSION\x10\x03\"F\n" +
+ "\aMasking\x12\x17\n" +
+ "\x13MASKING_UNSPECIFIED\x10\x00\x12\b\n" +
+ "\x04NONE\x10\x01\x12\n" +
+ "\n" +
+ "\x06COLUMN\x10\x02\x12\f\n" +
+ "\bDOCUMENT\x10\x03\"U\n" +
"\x1fRotateDirectorySyncTokenRequest\x122\n" +
"\x04name\x18\x01 \x01(\tB\x1e\xe0A\x02\xfaA\x18\n" +
"\x16bytebase.com/WorkspaceR\x04name\"A\n" +
@@ -472,8 +1015,7 @@ const file_v1_workspace_service_proto_rawDesc = "" +
"\vupdate_mask\x18\x02 \x01(\v2\x1a.google.protobuf.FieldMaskR\n" +
"updateMask\"0\n" +
"\x15LeaveWorkspaceRequest\x12\x17\n" +
- "\x04name\x18\x01 \x01(\tB\x03\xe0A\x02R\x04name2\x9f\n" +
- "\n" +
+ "\x04name\x18\x01 \x01(\tB\x03\xe0A\x02R\x04name2\x80\v\n" +
"\x10WorkspaceService\x12q\n" +
"\fGetWorkspace\x12 .bytebase.v1.GetWorkspaceRequest\x1a\x16.bytebase.v1.Workspace\"'\x80\xea0\x01\xa0\xea0\x01\x82\xd3\xe4\x93\x02\x19\x12\x17/v1/{name=workspaces/*}\x12y\n" +
"\x0eListWorkspaces\x12\".bytebase.v1.ListWorkspacesRequest\x1a#.bytebase.v1.ListWorkspacesResponse\"\x1e\x90\xea0\x02\xa0\xea0\x01\x82\xd3\xe4\x93\x02\x10\x12\x0e/v1/workspaces\x12\xa4\x01\n" +
@@ -481,7 +1023,9 @@ const file_v1_workspace_service_proto_rawDesc = "" +
"\fGetIamPolicy\x12 .bytebase.v1.GetIamPolicyRequest\x1a\x16.bytebase.v1.IamPolicy\"Z\x8a\xea0\x1abb.workspaces.getIamPolicy\x90\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02*\x12(/v1/{resource=workspaces/*}:getIamPolicy\x12\x9b\x01\n" +
"\x0fDeleteWorkspace\x12#.bytebase.v1.DeleteWorkspaceRequest\x1a\x1a.bytebase.v1.LoginResponse\"G\x8a\xea0\x14bb.workspaces.delete\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x05\x82\xd3\xe4\x93\x02\x19*\x17/v1/{name=workspaces/*}\x12\x8a\x01\n" +
"\x0eLeaveWorkspace\x12\".bytebase.v1.LeaveWorkspaceRequest\x1a\x1a.bytebase.v1.LoginResponse\"8\x90\xea0\x02\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x05\x82\xd3\xe4\x93\x02\":\x01*\"\x1d/v1/{name=workspaces/*}:leave\x12\xab\x01\n" +
- "\fSetIamPolicy\x12 .bytebase.v1.SetIamPolicyRequest\x1a\x16.bytebase.v1.IamPolicy\"a\x8a\xea0\x1abb.workspaces.setIamPolicy\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02-:\x01*\"(/v1/{resource=workspaces/*}:setIamPolicy\x12\xf5\x01\n" +
+ "\fSetIamPolicy\x12 .bytebase.v1.SetIamPolicyRequest\x1a\x16.bytebase.v1.IamPolicy\"a\x8a\xea0\x1abb.workspaces.setIamPolicy\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02-:\x01*\"(/v1/{resource=workspaces/*}:setIamPolicy\x12_\n" +
+ "\n" +
+ "GetMCPInfo\x12\x1e.bytebase.v1.GetMCPInfoRequest\x1a\x14.bytebase.v1.MCPInfo\"\x1b\xdaA\x00\xa0\xea0\x01\x82\xd3\xe4\x93\x02\x0e\x12\f/v1/mcp/info\x12\xf5\x01\n" +
"\x18RotateDirectorySyncToken\x12,.bytebase.v1.RotateDirectorySyncTokenRequest\x1a-.bytebase.v1.RotateDirectorySyncTokenResponse\"|\xdaA\x04name\x8a\xea0&bb.workspaces.rotateDirectorySyncToken\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x03\xa8\xea0\x06\x82\xd3\xe4\x93\x025:\x01*\"0/v1/{name=workspaces/*}:rotateDirectorySyncTokenB\xab\x01\n" +
"\x0fcom.bytebase.v1B\x15WorkspaceServiceProtoP\x01Z4github.com/bytebase/bytebase/backend/generated-go/v1\xa2\x02\x03BXX\xaa\x02\vBytebase.V1\xca\x02\vBytebase\\V1\xe2\x02\x17Bytebase\\V1\\GPBMetadata\xea\x02\fBytebase::V1b\x06proto3"
@@ -497,48 +1041,73 @@ func file_v1_workspace_service_proto_rawDescGZIP() []byte {
return file_v1_workspace_service_proto_rawDescData
}
-var file_v1_workspace_service_proto_msgTypes = make([]protoimpl.MessageInfo, 9)
+var file_v1_workspace_service_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
+var file_v1_workspace_service_proto_msgTypes = make([]protoimpl.MessageInfo, 14)
var file_v1_workspace_service_proto_goTypes = []any{
- (*RotateDirectorySyncTokenRequest)(nil), // 0: bytebase.v1.RotateDirectorySyncTokenRequest
- (*RotateDirectorySyncTokenResponse)(nil), // 1: bytebase.v1.RotateDirectorySyncTokenResponse
- (*ListWorkspacesRequest)(nil), // 2: bytebase.v1.ListWorkspacesRequest
- (*ListWorkspacesResponse)(nil), // 3: bytebase.v1.ListWorkspacesResponse
- (*GetWorkspaceRequest)(nil), // 4: bytebase.v1.GetWorkspaceRequest
- (*Workspace)(nil), // 5: bytebase.v1.Workspace
- (*DeleteWorkspaceRequest)(nil), // 6: bytebase.v1.DeleteWorkspaceRequest
- (*UpdateWorkspaceRequest)(nil), // 7: bytebase.v1.UpdateWorkspaceRequest
- (*LeaveWorkspaceRequest)(nil), // 8: bytebase.v1.LeaveWorkspaceRequest
- (*fieldmaskpb.FieldMask)(nil), // 9: google.protobuf.FieldMask
- (*GetIamPolicyRequest)(nil), // 10: bytebase.v1.GetIamPolicyRequest
- (*SetIamPolicyRequest)(nil), // 11: bytebase.v1.SetIamPolicyRequest
- (*IamPolicy)(nil), // 12: bytebase.v1.IamPolicy
- (*LoginResponse)(nil), // 13: bytebase.v1.LoginResponse
+ (MCPEngineEnforcement_ReadOnlyDepth)(0), // 0: bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth
+ (MCPEngineEnforcement_Masking)(0), // 1: bytebase.v1.MCPEngineEnforcement.Masking
+ (*GetMCPInfoRequest)(nil), // 2: bytebase.v1.GetMCPInfoRequest
+ (*MCPInfo)(nil), // 3: bytebase.v1.MCPInfo
+ (*MCPCapabilityMode)(nil), // 4: bytebase.v1.MCPCapabilityMode
+ (*MCPMethod)(nil), // 5: bytebase.v1.MCPMethod
+ (*MCPEngineEnforcement)(nil), // 6: bytebase.v1.MCPEngineEnforcement
+ (*RotateDirectorySyncTokenRequest)(nil), // 7: bytebase.v1.RotateDirectorySyncTokenRequest
+ (*RotateDirectorySyncTokenResponse)(nil), // 8: bytebase.v1.RotateDirectorySyncTokenResponse
+ (*ListWorkspacesRequest)(nil), // 9: bytebase.v1.ListWorkspacesRequest
+ (*ListWorkspacesResponse)(nil), // 10: bytebase.v1.ListWorkspacesResponse
+ (*GetWorkspaceRequest)(nil), // 11: bytebase.v1.GetWorkspaceRequest
+ (*Workspace)(nil), // 12: bytebase.v1.Workspace
+ (*DeleteWorkspaceRequest)(nil), // 13: bytebase.v1.DeleteWorkspaceRequest
+ (*UpdateWorkspaceRequest)(nil), // 14: bytebase.v1.UpdateWorkspaceRequest
+ (*LeaveWorkspaceRequest)(nil), // 15: bytebase.v1.LeaveWorkspaceRequest
+ (MCPSetting_Capability)(0), // 16: bytebase.v1.MCPSetting.Capability
+ (MCPMethodClass)(0), // 17: bytebase.v1.MCPMethodClass
+ (AuthMethod)(0), // 18: bytebase.v1.AuthMethod
+ (Engine)(0), // 19: bytebase.v1.Engine
+ (*fieldmaskpb.FieldMask)(nil), // 20: google.protobuf.FieldMask
+ (*GetIamPolicyRequest)(nil), // 21: bytebase.v1.GetIamPolicyRequest
+ (*SetIamPolicyRequest)(nil), // 22: bytebase.v1.SetIamPolicyRequest
+ (*IamPolicy)(nil), // 23: bytebase.v1.IamPolicy
+ (*LoginResponse)(nil), // 24: bytebase.v1.LoginResponse
}
var file_v1_workspace_service_proto_depIdxs = []int32{
- 5, // 0: bytebase.v1.ListWorkspacesResponse.workspaces:type_name -> bytebase.v1.Workspace
- 5, // 1: bytebase.v1.UpdateWorkspaceRequest.workspace:type_name -> bytebase.v1.Workspace
- 9, // 2: bytebase.v1.UpdateWorkspaceRequest.update_mask:type_name -> google.protobuf.FieldMask
- 4, // 3: bytebase.v1.WorkspaceService.GetWorkspace:input_type -> bytebase.v1.GetWorkspaceRequest
- 2, // 4: bytebase.v1.WorkspaceService.ListWorkspaces:input_type -> bytebase.v1.ListWorkspacesRequest
- 7, // 5: bytebase.v1.WorkspaceService.UpdateWorkspace:input_type -> bytebase.v1.UpdateWorkspaceRequest
- 10, // 6: bytebase.v1.WorkspaceService.GetIamPolicy:input_type -> bytebase.v1.GetIamPolicyRequest
- 6, // 7: bytebase.v1.WorkspaceService.DeleteWorkspace:input_type -> bytebase.v1.DeleteWorkspaceRequest
- 8, // 8: bytebase.v1.WorkspaceService.LeaveWorkspace:input_type -> bytebase.v1.LeaveWorkspaceRequest
- 11, // 9: bytebase.v1.WorkspaceService.SetIamPolicy:input_type -> bytebase.v1.SetIamPolicyRequest
- 0, // 10: bytebase.v1.WorkspaceService.RotateDirectorySyncToken:input_type -> bytebase.v1.RotateDirectorySyncTokenRequest
- 5, // 11: bytebase.v1.WorkspaceService.GetWorkspace:output_type -> bytebase.v1.Workspace
- 3, // 12: bytebase.v1.WorkspaceService.ListWorkspaces:output_type -> bytebase.v1.ListWorkspacesResponse
- 5, // 13: bytebase.v1.WorkspaceService.UpdateWorkspace:output_type -> bytebase.v1.Workspace
- 12, // 14: bytebase.v1.WorkspaceService.GetIamPolicy:output_type -> bytebase.v1.IamPolicy
- 13, // 15: bytebase.v1.WorkspaceService.DeleteWorkspace:output_type -> bytebase.v1.LoginResponse
- 13, // 16: bytebase.v1.WorkspaceService.LeaveWorkspace:output_type -> bytebase.v1.LoginResponse
- 12, // 17: bytebase.v1.WorkspaceService.SetIamPolicy:output_type -> bytebase.v1.IamPolicy
- 1, // 18: bytebase.v1.WorkspaceService.RotateDirectorySyncToken:output_type -> bytebase.v1.RotateDirectorySyncTokenResponse
- 11, // [11:19] is the sub-list for method output_type
- 3, // [3:11] is the sub-list for method input_type
- 3, // [3:3] is the sub-list for extension type_name
- 3, // [3:3] is the sub-list for extension extendee
- 0, // [0:3] is the sub-list for field type_name
+ 16, // 0: bytebase.v1.MCPInfo.capability:type_name -> bytebase.v1.MCPSetting.Capability
+ 4, // 1: bytebase.v1.MCPInfo.modes:type_name -> bytebase.v1.MCPCapabilityMode
+ 5, // 2: bytebase.v1.MCPInfo.methods:type_name -> bytebase.v1.MCPMethod
+ 6, // 3: bytebase.v1.MCPInfo.engines:type_name -> bytebase.v1.MCPEngineEnforcement
+ 16, // 4: bytebase.v1.MCPCapabilityMode.capability:type_name -> bytebase.v1.MCPSetting.Capability
+ 17, // 5: bytebase.v1.MCPCapabilityMode.served_classes:type_name -> bytebase.v1.MCPMethodClass
+ 17, // 6: bytebase.v1.MCPMethod.class:type_name -> bytebase.v1.MCPMethodClass
+ 18, // 7: bytebase.v1.MCPMethod.auth_method:type_name -> bytebase.v1.AuthMethod
+ 19, // 8: bytebase.v1.MCPEngineEnforcement.engine:type_name -> bytebase.v1.Engine
+ 0, // 9: bytebase.v1.MCPEngineEnforcement.read_only_depth:type_name -> bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth
+ 1, // 10: bytebase.v1.MCPEngineEnforcement.masking:type_name -> bytebase.v1.MCPEngineEnforcement.Masking
+ 12, // 11: bytebase.v1.ListWorkspacesResponse.workspaces:type_name -> bytebase.v1.Workspace
+ 12, // 12: bytebase.v1.UpdateWorkspaceRequest.workspace:type_name -> bytebase.v1.Workspace
+ 20, // 13: bytebase.v1.UpdateWorkspaceRequest.update_mask:type_name -> google.protobuf.FieldMask
+ 11, // 14: bytebase.v1.WorkspaceService.GetWorkspace:input_type -> bytebase.v1.GetWorkspaceRequest
+ 9, // 15: bytebase.v1.WorkspaceService.ListWorkspaces:input_type -> bytebase.v1.ListWorkspacesRequest
+ 14, // 16: bytebase.v1.WorkspaceService.UpdateWorkspace:input_type -> bytebase.v1.UpdateWorkspaceRequest
+ 21, // 17: bytebase.v1.WorkspaceService.GetIamPolicy:input_type -> bytebase.v1.GetIamPolicyRequest
+ 13, // 18: bytebase.v1.WorkspaceService.DeleteWorkspace:input_type -> bytebase.v1.DeleteWorkspaceRequest
+ 15, // 19: bytebase.v1.WorkspaceService.LeaveWorkspace:input_type -> bytebase.v1.LeaveWorkspaceRequest
+ 22, // 20: bytebase.v1.WorkspaceService.SetIamPolicy:input_type -> bytebase.v1.SetIamPolicyRequest
+ 2, // 21: bytebase.v1.WorkspaceService.GetMCPInfo:input_type -> bytebase.v1.GetMCPInfoRequest
+ 7, // 22: bytebase.v1.WorkspaceService.RotateDirectorySyncToken:input_type -> bytebase.v1.RotateDirectorySyncTokenRequest
+ 12, // 23: bytebase.v1.WorkspaceService.GetWorkspace:output_type -> bytebase.v1.Workspace
+ 10, // 24: bytebase.v1.WorkspaceService.ListWorkspaces:output_type -> bytebase.v1.ListWorkspacesResponse
+ 12, // 25: bytebase.v1.WorkspaceService.UpdateWorkspace:output_type -> bytebase.v1.Workspace
+ 23, // 26: bytebase.v1.WorkspaceService.GetIamPolicy:output_type -> bytebase.v1.IamPolicy
+ 24, // 27: bytebase.v1.WorkspaceService.DeleteWorkspace:output_type -> bytebase.v1.LoginResponse
+ 24, // 28: bytebase.v1.WorkspaceService.LeaveWorkspace:output_type -> bytebase.v1.LoginResponse
+ 23, // 29: bytebase.v1.WorkspaceService.SetIamPolicy:output_type -> bytebase.v1.IamPolicy
+ 3, // 30: bytebase.v1.WorkspaceService.GetMCPInfo:output_type -> bytebase.v1.MCPInfo
+ 8, // 31: bytebase.v1.WorkspaceService.RotateDirectorySyncToken:output_type -> bytebase.v1.RotateDirectorySyncTokenResponse
+ 23, // [23:32] is the sub-list for method output_type
+ 14, // [14:23] is the sub-list for method input_type
+ 14, // [14:14] is the sub-list for extension type_name
+ 14, // [14:14] is the sub-list for extension extendee
+ 0, // [0:14] is the sub-list for field type_name
}
func init() { file_v1_workspace_service_proto_init() }
@@ -548,19 +1117,22 @@ func file_v1_workspace_service_proto_init() {
}
file_v1_annotation_proto_init()
file_v1_auth_service_proto_init()
+ file_v1_common_proto_init()
file_v1_iam_policy_proto_init()
+ file_v1_setting_service_proto_init()
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_workspace_service_proto_rawDesc), len(file_v1_workspace_service_proto_rawDesc)),
- NumEnums: 0,
- NumMessages: 9,
+ NumEnums: 2,
+ NumMessages: 14,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_v1_workspace_service_proto_goTypes,
DependencyIndexes: file_v1_workspace_service_proto_depIdxs,
+ EnumInfos: file_v1_workspace_service_proto_enumTypes,
MessageInfos: file_v1_workspace_service_proto_msgTypes,
}.Build()
File_v1_workspace_service_proto = out.File
diff --git a/backend/generated-go/v1/workspace_service.pb.gw.go b/backend/generated-go/v1/workspace_service.pb.gw.go
index 3cd9057274..3960cd4956 100644
--- a/backend/generated-go/v1/workspace_service.pb.gw.go
+++ b/backend/generated-go/v1/workspace_service.pb.gw.go
@@ -308,6 +308,27 @@ func local_request_WorkspaceService_SetIamPolicy_0(ctx context.Context, marshale
return msg, metadata, err
}
+func request_WorkspaceService_GetMCPInfo_0(ctx context.Context, marshaler runtime.Marshaler, client WorkspaceServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq GetMCPInfoRequest
+ metadata runtime.ServerMetadata
+ )
+ if req.Body != nil {
+ _, _ = io.Copy(io.Discard, req.Body)
+ }
+ msg, err := client.GetMCPInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_WorkspaceService_GetMCPInfo_0(ctx context.Context, marshaler runtime.Marshaler, server WorkspaceServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq GetMCPInfoRequest
+ metadata runtime.ServerMetadata
+ )
+ msg, err := server.GetMCPInfo(ctx, &protoReq)
+ return msg, metadata, err
+}
+
func request_WorkspaceService_RotateDirectorySyncToken_0(ctx context.Context, marshaler runtime.Marshaler, client WorkspaceServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var (
protoReq RotateDirectorySyncTokenRequest
@@ -499,6 +520,26 @@ func RegisterWorkspaceServiceHandlerServer(ctx context.Context, mux *runtime.Ser
}
forward_WorkspaceService_SetIamPolicy_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodGet, pattern_WorkspaceService_GetMCPInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ var stream runtime.ServerTransportStream
+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.WorkspaceService/GetMCPInfo", runtime.WithHTTPPathPattern("/v1/mcp/info"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_WorkspaceService_GetMCPInfo_0(annotatedContext, inboundMarshaler, server, req, pathParams)
+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_WorkspaceService_GetMCPInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
mux.Handle(http.MethodPost, pattern_WorkspaceService_RotateDirectorySyncToken_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
@@ -678,6 +719,23 @@ func RegisterWorkspaceServiceHandlerClient(ctx context.Context, mux *runtime.Ser
}
forward_WorkspaceService_SetIamPolicy_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodGet, pattern_WorkspaceService_GetMCPInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.WorkspaceService/GetMCPInfo", runtime.WithHTTPPathPattern("/v1/mcp/info"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_WorkspaceService_GetMCPInfo_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_WorkspaceService_GetMCPInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
mux.Handle(http.MethodPost, pattern_WorkspaceService_RotateDirectorySyncToken_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
@@ -706,6 +764,7 @@ var (
pattern_WorkspaceService_DeleteWorkspace_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "workspaces", "name"}, ""))
pattern_WorkspaceService_LeaveWorkspace_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "workspaces", "name"}, "leave"))
pattern_WorkspaceService_SetIamPolicy_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "workspaces", "resource"}, "setIamPolicy"))
+ pattern_WorkspaceService_GetMCPInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "mcp", "info"}, ""))
pattern_WorkspaceService_RotateDirectorySyncToken_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 2, 5, 2}, []string{"v1", "workspaces", "name"}, "rotateDirectorySyncToken"))
)
@@ -717,5 +776,6 @@ var (
forward_WorkspaceService_DeleteWorkspace_0 = runtime.ForwardResponseMessage
forward_WorkspaceService_LeaveWorkspace_0 = runtime.ForwardResponseMessage
forward_WorkspaceService_SetIamPolicy_0 = runtime.ForwardResponseMessage
+ forward_WorkspaceService_GetMCPInfo_0 = runtime.ForwardResponseMessage
forward_WorkspaceService_RotateDirectorySyncToken_0 = runtime.ForwardResponseMessage
)
diff --git a/backend/generated-go/v1/workspace_service_equal.pb.go b/backend/generated-go/v1/workspace_service_equal.pb.go
index 331ff3293e..f7f95ff316 100644
--- a/backend/generated-go/v1/workspace_service_equal.pb.go
+++ b/backend/generated-go/v1/workspace_service_equal.pb.go
@@ -8,6 +8,130 @@ import (
fieldmaskpb "google.golang.org/protobuf/types/known/fieldmaskpb"
)
+func (x *GetMCPInfoRequest) Equal(y *GetMCPInfoRequest) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ return true
+}
+
+func (x *MCPInfo) Equal(y *MCPInfo) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Workspace != y.Workspace {
+ return false
+ }
+ if x.Capability != y.Capability {
+ return false
+ }
+ if len(x.Modes) != len(y.Modes) {
+ return false
+ }
+ for i := 0; i < len(x.Modes); i++ {
+ if !x.Modes[i].Equal(y.Modes[i]) {
+ return false
+ }
+ }
+ if len(x.Methods) != len(y.Methods) {
+ return false
+ }
+ for i := 0; i < len(x.Methods); i++ {
+ if !x.Methods[i].Equal(y.Methods[i]) {
+ return false
+ }
+ }
+ if len(x.Engines) != len(y.Engines) {
+ return false
+ }
+ for i := 0; i < len(x.Engines); i++ {
+ if !x.Engines[i].Equal(y.Engines[i]) {
+ return false
+ }
+ }
+ if x.IgnoreMaskingExemptions != y.IgnoreMaskingExemptions {
+ return false
+ }
+ if x.DataMaskingAvailable != y.DataMaskingAvailable {
+ return false
+ }
+ return true
+}
+
+func (x *MCPCapabilityMode) Equal(y *MCPCapabilityMode) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Capability != y.Capability {
+ return false
+ }
+ if len(x.ServedClasses) != len(y.ServedClasses) {
+ return false
+ }
+ for i := 0; i < len(x.ServedClasses); i++ {
+ if x.ServedClasses[i] != y.ServedClasses[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func (x *MCPMethod) Equal(y *MCPMethod) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Method != y.Method {
+ return false
+ }
+ if x.OperationId != y.OperationId {
+ return false
+ }
+ if x.Class != y.Class {
+ return false
+ }
+ if x.Permission != y.Permission {
+ return false
+ }
+ if x.AuthMethod != y.AuthMethod {
+ return false
+ }
+ return true
+}
+
+func (x *MCPEngineEnforcement) Equal(y *MCPEngineEnforcement) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Engine != y.Engine {
+ return false
+ }
+ if x.ReadOnlyDepth != y.ReadOnlyDepth {
+ return false
+ }
+ if x.Masking != y.Masking {
+ return false
+ }
+ if x.Note != y.Note {
+ return false
+ }
+ return true
+}
+
func (x *RotateDirectorySyncTokenRequest) Equal(y *RotateDirectorySyncTokenRequest) bool {
if x == y {
return true
diff --git a/backend/generated-go/v1/workspace_service_grpc.pb.go b/backend/generated-go/v1/workspace_service_grpc.pb.go
index ea339d6178..31e827368e 100644
--- a/backend/generated-go/v1/workspace_service_grpc.pb.go
+++ b/backend/generated-go/v1/workspace_service_grpc.pb.go
@@ -26,6 +26,7 @@ const (
WorkspaceService_DeleteWorkspace_FullMethodName = "/bytebase.v1.WorkspaceService/DeleteWorkspace"
WorkspaceService_LeaveWorkspace_FullMethodName = "/bytebase.v1.WorkspaceService/LeaveWorkspace"
WorkspaceService_SetIamPolicy_FullMethodName = "/bytebase.v1.WorkspaceService/SetIamPolicy"
+ WorkspaceService_GetMCPInfo_FullMethodName = "/bytebase.v1.WorkspaceService/GetMCPInfo"
WorkspaceService_RotateDirectorySyncToken_FullMethodName = "/bytebase.v1.WorkspaceService/RotateDirectorySyncToken"
)
@@ -59,6 +60,18 @@ type WorkspaceServiceClient interface {
// Sets IAM policy for the workspace.
// Permissions required: bb.workspaces.setIamPolicy
SetIamPolicy(ctx context.Context, in *SetIamPolicyRequest, opts ...grpc.CallOption) (*IamPolicy, error)
+ // Gets what MCP (Model Context Protocol) does in this workspace: the
+ // capability ceiling in force, what each ceiling serves, and the per-engine
+ // facts a read-only session depends on. The workspace is resolved from the
+ // authenticated session.
+ //
+ // Served to MCP sessions. An agent asking what it may do here is the point:
+ // the response says nothing a session's own denials do not already say, one
+ // refusal at a time, and knowing it up front is what stops the agent
+ // planning work the ceiling was never going to serve.
+ //
+ // Permissions required: None (authentication required)
+ GetMCPInfo(ctx context.Context, in *GetMCPInfoRequest, opts ...grpc.CallOption) (*MCPInfo, error)
// Mints a new directory sync (SCIM) token, immediately invalidating the
// previous one. The plaintext token is returned exactly once and cannot be
// retrieved afterwards; only its hash is stored. Callers that lose it must
@@ -145,6 +158,16 @@ func (c *workspaceServiceClient) SetIamPolicy(ctx context.Context, in *SetIamPol
return out, nil
}
+func (c *workspaceServiceClient) GetMCPInfo(ctx context.Context, in *GetMCPInfoRequest, opts ...grpc.CallOption) (*MCPInfo, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(MCPInfo)
+ err := c.cc.Invoke(ctx, WorkspaceService_GetMCPInfo_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
func (c *workspaceServiceClient) RotateDirectorySyncToken(ctx context.Context, in *RotateDirectorySyncTokenRequest, opts ...grpc.CallOption) (*RotateDirectorySyncTokenResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RotateDirectorySyncTokenResponse)
@@ -185,6 +208,18 @@ type WorkspaceServiceServer interface {
// Sets IAM policy for the workspace.
// Permissions required: bb.workspaces.setIamPolicy
SetIamPolicy(context.Context, *SetIamPolicyRequest) (*IamPolicy, error)
+ // Gets what MCP (Model Context Protocol) does in this workspace: the
+ // capability ceiling in force, what each ceiling serves, and the per-engine
+ // facts a read-only session depends on. The workspace is resolved from the
+ // authenticated session.
+ //
+ // Served to MCP sessions. An agent asking what it may do here is the point:
+ // the response says nothing a session's own denials do not already say, one
+ // refusal at a time, and knowing it up front is what stops the agent
+ // planning work the ceiling was never going to serve.
+ //
+ // Permissions required: None (authentication required)
+ GetMCPInfo(context.Context, *GetMCPInfoRequest) (*MCPInfo, error)
// Mints a new directory sync (SCIM) token, immediately invalidating the
// previous one. The plaintext token is returned exactly once and cannot be
// retrieved afterwards; only its hash is stored. Callers that lose it must
@@ -222,6 +257,9 @@ func (UnimplementedWorkspaceServiceServer) LeaveWorkspace(context.Context, *Leav
func (UnimplementedWorkspaceServiceServer) SetIamPolicy(context.Context, *SetIamPolicyRequest) (*IamPolicy, error) {
return nil, status.Error(codes.Unimplemented, "method SetIamPolicy not implemented")
}
+func (UnimplementedWorkspaceServiceServer) GetMCPInfo(context.Context, *GetMCPInfoRequest) (*MCPInfo, error) {
+ return nil, status.Error(codes.Unimplemented, "method GetMCPInfo not implemented")
+}
func (UnimplementedWorkspaceServiceServer) RotateDirectorySyncToken(context.Context, *RotateDirectorySyncTokenRequest) (*RotateDirectorySyncTokenResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RotateDirectorySyncToken not implemented")
}
@@ -372,6 +410,24 @@ func _WorkspaceService_SetIamPolicy_Handler(srv interface{}, ctx context.Context
return interceptor(ctx, in, info, handler)
}
+func _WorkspaceService_GetMCPInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetMCPInfoRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(WorkspaceServiceServer).GetMCPInfo(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: WorkspaceService_GetMCPInfo_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(WorkspaceServiceServer).GetMCPInfo(ctx, req.(*GetMCPInfoRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
func _WorkspaceService_RotateDirectorySyncToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RotateDirectorySyncTokenRequest)
if err := dec(in); err != nil {
@@ -425,6 +481,10 @@ var WorkspaceService_ServiceDesc = grpc.ServiceDesc{
MethodName: "SetIamPolicy",
Handler: _WorkspaceService_SetIamPolicy_Handler,
},
+ {
+ MethodName: "GetMCPInfo",
+ Handler: _WorkspaceService_GetMCPInfo_Handler,
+ },
{
MethodName: "RotateDirectorySyncToken",
Handler: _WorkspaceService_RotateDirectorySyncToken_Handler,
diff --git a/backend/store/audit_log.go b/backend/store/audit_log.go
index ef6fed6477..41a534fe96 100644
--- a/backend/store/audit_log.go
+++ b/backend/store/audit_log.go
@@ -129,6 +129,54 @@ func (s *Store) SearchAuditLogs(ctx context.Context, find *AuditLogFind) ([]*Aud
return logs, nil
}
+// auditLogEqualsFilter turns one `variable == "literal"` clause of the audit
+// search grammar into its SQL predicate.
+//
+// The payload is protojson, so its keys are camelCase and a filter name is not
+// always the key it reads. The four plain columns keep the historical rule that
+// the name IS the key; the two MCP filters do not, because the provenance they
+// read lives on a nested message (AuditLog.mcp_delegation, marshalled as
+// "mcpDelegation").
+func auditLogEqualsFilter(variable string, rawValue any) (*qb.Query, error) {
+ // The variable decides the literal's type, so an unknown key is reported as
+ // one whatever it was compared against.
+ switch variable {
+ case "mcp":
+ // A real boolean, like every other boolean filter key in this codebase
+ // (saved_query.starred, database.exclude_unassigned).
+ mcp, ok := rawValue.(bool)
+ if !ok {
+ return nil, errors.Errorf("invalid mcp value %v, expect true or false", rawValue)
+ }
+ // Presence of the mcpDelegation message is the MCP-origin marker, and
+ // the whole of it: the audit interceptor sets that message exactly for
+ // calls carrying the delegated credential, and leaves it off every
+ // public-chain call (proto/store/store/audit_log.proto). Its fields are
+ // empty for a legacy session, so no field of it can stand in for the
+ // test.
+ //
+ // `??` is qb's escape for a literal question mark, which is what the
+ // JSONB key-exists operator is; a bare ? is qb's bind placeholder.
+ if mcp {
+ return qb.Q().Space("payload ?? 'mcpDelegation'"), nil
+ }
+ return qb.Q().Space("NOT (payload ?? 'mcpDelegation')"), nil
+
+ case "resource", "method", "user", "severity", "mcp_correlation_id":
+ value, ok := rawValue.(string)
+ if !ok {
+ return nil, errors.Errorf("expect string, got %T, hint: filter literals should be string", rawValue)
+ }
+ if variable == "mcp_correlation_id" {
+ return qb.Q().Space("payload->'mcpDelegation'->>'correlationId' = ?", value), nil
+ }
+ return qb.Q().Space(fmt.Sprintf("payload->>'%s' = ?", variable), value), nil
+
+ default:
+ return nil, errors.Errorf("unknown variable %s", variable)
+ }
+}
+
func GetSearchAuditLogsFilter(filter string) (*qb.Query, error) {
if filter == "" {
return nil, nil
@@ -171,16 +219,7 @@ func GetSearchAuditLogsFilter(filter string) (*qb.Query, error) {
return qb.Q().Space("(?)", q), nil
case celoperators.Equals:
variable, rawValue := getVariableAndValueFromExpr(expr)
- value, ok := rawValue.(string)
- if !ok {
- return nil, errors.Errorf("expect string, got %T, hint: filter literals should be string", rawValue)
- }
- switch variable {
- case "resource", "method", "user", "severity":
- default:
- return nil, errors.Errorf("unknown variable %s", variable)
- }
- return qb.Q().Space(fmt.Sprintf("payload->>'%s' = ?", variable), value), nil
+ return auditLogEqualsFilter(variable, rawValue)
case celoperators.GreaterEquals, celoperators.LessEquals:
variable, rawValue := getVariableAndValueFromExpr(expr)
diff --git a/backend/store/audit_log_mcp_filter_test.go b/backend/store/audit_log_mcp_filter_test.go
new file mode 100644
index 0000000000..4a0077a44d
--- /dev/null
+++ b/backend/store/audit_log_mcp_filter_test.go
@@ -0,0 +1,138 @@
+package store_test
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+
+ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
+)
+
+// TestSearchAuditLogsMCPFilters drives the two MCP filters end to end against a
+// real Postgres, because both of the things that can be wrong about them are
+// invisible to a SQL-shape assertion.
+//
+// The first is the key spelling: the payload is protojson, so the MCP
+// provenance is stored under "mcpDelegation", not the proto field name
+// mcp_delegation, and a filter naming the wrong one returns zero rows and no
+// error. The second is the escape: the JSONB key-exists operator is a question
+// mark, which is also qb's bind placeholder, so a predicate that reaches
+// Postgres with one question mark instead of two is a parameter count error
+// rather than a query.
+func TestSearchAuditLogsMCPFilters(t *testing.T) {
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+
+ _, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-test')`)
+ require.NoError(t, err)
+
+ pgURL := fmt.Sprintf(
+ "host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort(),
+ )
+ s, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+
+ rows := []*storepb.AuditLog{
+ {
+ Parent: "workspaces/ws-test",
+ Method: "/bytebase.v1.SQLService/Query",
+ Resource: "instances/i/databases/d",
+ McpDelegation: &storepb.MCPDelegation{
+ ClientId: "client-A",
+ CorrelationId: "session-one",
+ },
+ },
+ {
+ Parent: "workspaces/ws-test",
+ Method: "/bytebase.v1.DatabaseService/ListDatabases",
+ McpDelegation: &storepb.MCPDelegation{
+ ClientId: "client-A",
+ CorrelationId: "session-one",
+ },
+ },
+ {
+ Parent: "workspaces/ws-test",
+ Method: "/bytebase.v1.SQLService/Query",
+ McpDelegation: &storepb.MCPDelegation{
+ ClientId: "client-B",
+ CorrelationId: "session-two",
+ },
+ },
+ {
+ // A legacy MCP session: the marker is present, every field of it
+ // is empty. No field value can stand in for the presence test.
+ Parent: "workspaces/ws-test",
+ Method: "/bytebase.v1.SQLService/Query",
+ McpDelegation: &storepb.MCPDelegation{},
+ },
+ {
+ // The console. No marker at all.
+ Parent: "workspaces/ws-test",
+ Method: "/bytebase.v1.SQLService/Query",
+ },
+ }
+ for _, row := range rows {
+ require.NoError(t, s.CreateAuditLog(ctx, "ws-test", row))
+ }
+
+ search := func(t *testing.T, filter string) []*store.AuditLog {
+ t.Helper()
+ q, err := store.GetSearchAuditLogsFilter(filter)
+ require.NoError(t, err)
+ logs, err := s.SearchAuditLogs(ctx, &store.AuditLogFind{Workspace: "ws-test", FilterQ: q})
+ require.NoError(t, err)
+ return logs
+ }
+
+ t.Run("mcp == true returns every MCP row and only those", func(t *testing.T) {
+ got := search(t, "mcp == true")
+ require.Len(t, got, 4, "the four rows carrying the marker, including the empty-field legacy one")
+ for _, log := range got {
+ require.NotNil(t, log.Payload.GetMcpDelegation(),
+ "a row without the marker must not answer the MCP filter")
+ }
+ })
+
+ t.Run("mcp == false returns the rest", func(t *testing.T) {
+ got := search(t, "mcp == false")
+ require.Len(t, got, 1)
+ require.Nil(t, got[0].Payload.GetMcpDelegation())
+ })
+
+ t.Run("the correlation filter returns one session's rows", func(t *testing.T) {
+ got := search(t, `mcp_correlation_id == "session-one"`)
+ require.Len(t, got, 2)
+ for _, log := range got {
+ require.Equal(t, "session-one", log.Payload.GetMcpDelegation().GetCorrelationId())
+ }
+ })
+
+ t.Run("the MCP filters compose with the existing ones", func(t *testing.T) {
+ got := search(t, `mcp == true && method == "/bytebase.v1.SQLService/Query"`)
+ require.Len(t, got, 3)
+ })
+
+ t.Run("an unknown key still errors", func(t *testing.T) {
+ _, err := store.GetSearchAuditLogsFilter(`mcp_client_id == "client-A"`)
+ require.ErrorContains(t, err, "unknown variable mcp_client_id")
+ })
+
+ t.Run("mcp is a boolean, not a string", func(t *testing.T) {
+ // Every other boolean filter key in the codebase takes a real CEL
+ // boolean and says so on a mismatch; this one must not be the outlier.
+ _, err := store.GetSearchAuditLogsFilter(`mcp == "true"`)
+ require.ErrorContains(t, err, "expect true or false")
+ })
+}
diff --git a/backend/tests/mcp_denial_audit_test.go b/backend/tests/mcp_denial_audit_test.go
new file mode 100644
index 0000000000..45d826f529
--- /dev/null
+++ b/backend/tests/mcp_denial_audit_test.go
@@ -0,0 +1,142 @@
+package tests
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+// TestMCPPolicyDenialsReachTheAuditPage drives both echo-route denials against
+// a live server and reads them back through the audit API an operator uses.
+//
+// It is here rather than in a package test because the halves are wired
+// separately and only compose on a running server: the /mcp middleware and the
+// OAuth2 consent handler each write their own row, the interceptor that writes
+// every other row never sees either, and the filters that find them are the
+// store's. A unit test of any one piece passes while the operator's view stays
+// empty.
+func TestMCPPolicyDenialsReachTheAuditPage(t *testing.T) {
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ ctx, err := ctl.StartServerWithExternalPg(ctx)
+ a.NoError(err)
+ defer ctl.Close(ctx)
+
+ workspace, err := ctl.workspaceServiceClient.GetWorkspace(ctx, connect.NewRequest(&v1pb.GetWorkspaceRequest{
+ Name: "workspaces/-",
+ }))
+ a.NoError(err)
+
+ searchMCP := func(filter string) []*v1pb.AuditLog {
+ resp, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{
+ Parent: workspace.Msg.Name,
+ Filter: filter,
+ OrderBy: "create_time desc",
+ }))
+ a.NoError(err)
+ return resp.Msg.AuditLogs
+ }
+
+ // A session that connects first, so the denial below is the ceiling and
+ // nothing else about this token.
+ mcpToken, clientID := mintMCPOAuthToken(t, ctl, ctl.authInterceptor.token)
+ status, body := postMCP(t, ctl, mcpToken)
+ a.Equal(http.StatusOK, status, "control: the ceiling admits this session; %s", body)
+ a.Empty(searchMCP(`method == "/bytebase.mcp.Session/Authorize"`),
+ "an admitted connection writes no row")
+
+ a.NoError(ctl.setMCPCapability(ctx, v1pb.MCPSetting_DISABLED))
+
+ status, body = postMCP(t, ctl, mcpToken)
+ a.Equal(http.StatusForbidden, status, "the ceiling refuses the next request; %s", body)
+
+ connectionRows := searchMCP(`method == "/bytebase.mcp.Session/Authorize"`)
+ a.Len(connectionRows, 1, "the refused connection is on the audit page")
+ connection := connectionRows[0]
+ a.Equal(ctl.principalName, connection.User)
+ a.NotNil(connection.Status)
+ a.Contains(connection.Status.Message, "turned MCP access off")
+ a.NotNil(connection.McpDelegation, "the row wears the MCP badge")
+ a.Equal(clientID, connection.McpDelegation.ClientId)
+ a.Empty(connection.McpDelegation.CorrelationId,
+ "the ceiling refuses before the SDK resolves a session, so there is no session ID to record")
+
+ // The same workspace now refuses a NEW authorization too, and that refusal
+ // is a second row. Without it an operator sees an agent stop connecting and
+ // cannot tell a client that gave up from one that was never let in.
+ consentRefused := consentUnderDisabledCeiling(t, ctl)
+ a.Equal(http.StatusForbidden, consentRefused)
+
+ consentRows := searchMCP(`method == "/bytebase.mcp.Consent/Approve"`)
+ a.Len(consentRows, 1, "the refused consent is on the audit page too")
+ a.Contains(consentRows[0].Status.GetMessage(), "turned MCP access off")
+ a.Empty(consentRows[0].McpDelegation.GetCorrelationId(),
+ "a consent never reached the boundary that mints one")
+
+ // The operator's two filters, through the read API they are used from.
+ a.Len(searchMCP("mcp == true"), 2,
+ "both denials answer the MCP filter; nothing else in this workspace does")
+
+ // The correlation key parses and runs here; what it selects is pinned
+ // against real session IDs in TestSearchAuditLogsMCPFilters. Neither denial
+ // belongs to a session, so neither answers it — which is the point: an
+ // operator pivoting on a session must not be handed rows that were never
+ // part of one.
+ a.Empty(searchMCP(`mcp_correlation_id == "any-session"`))
+}
+
+// consentUnderDisabledCeiling registers a fresh MCP client and posts an
+// approved consent form, returning the HTTP status the authorize handler
+// answered with. It is the first half of mintMCPOAuthToken's flow, stopped
+// where a refused consent stops it.
+func consentUnderDisabledCeiling(t *testing.T, ctl *controller) int {
+ t.Helper()
+ httpClient := &http.Client{}
+
+ resp, err := httpClient.Post(ctl.rootURL+"/api/oauth2/register", "application/json",
+ strings.NewReader(`{"client_name":"bb-e2e-refused","redirect_uris":["http://localhost/cb"],"grant_types":["authorization_code"],"token_endpoint_auth_method":"none"}`))
+ require.NoError(t, err)
+ defer resp.Body.Close()
+ var reg struct {
+ ClientID string `json:"client_id"`
+ }
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&reg))
+ require.NotEmpty(t, reg.ClientID)
+
+ verifier := "e2eVerifier_e2eVerifier_e2eVerifier_e2eVerifier"
+ challenge := sha256.Sum256([]byte(verifier))
+ form := url.Values{
+ "client_id": {reg.ClientID},
+ "redirect_uri": {"http://localhost/cb"},
+ "state": {"e2e-state"},
+ "code_challenge": {base64.RawURLEncoding.EncodeToString(challenge[:])},
+ "code_challenge_method": {"S256"},
+ "action": {"allow"},
+ "resource": {ctl.rootURL + "/mcp"},
+ "scope": {"mcp:read-only"},
+ }
+ req, err := http.NewRequest(http.MethodPost, ctl.rootURL+"/api/oauth2/authorize", strings.NewReader(form.Encode()))
+ require.NoError(t, err)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Authorization", "Bearer "+ctl.authInterceptor.token)
+ consentResp, err := httpClient.Do(req)
+ require.NoError(t, err)
+ defer consentResp.Body.Close()
+ body, err := io.ReadAll(consentResp.Body)
+ require.NoError(t, err)
+ require.NotContains(t, string(body), "code=", "a refused consent must issue no authorization code")
+ return consentResp.StatusCode
+}
diff --git a/backend/tests/mcp_migration_matrix_test.go b/backend/tests/mcp_migration_matrix_test.go
index ae8b279cce..ff90a23df1 100644
--- a/backend/tests/mcp_migration_matrix_test.go
+++ b/backend/tests/mcp_migration_matrix_test.go
@@ -344,7 +344,11 @@ func TestMCPMigrationCeilingLookupFailureFailsClosed(t *testing.T) {
status, body = postMCP(t, ctl, mcpToken)
a.Equal(http.StatusForbidden, status,
"a ceiling that cannot be read must fail closed, not fall back to permitting MCP; %s", body)
- a.Contains(body, "MCP access is disabled")
+ // Not the disabled wording. An admin turning MCP off and an admin leaving a
+ // value nobody can parse are different problems with different fixes, and
+ // the refusal is the only place the difference reaches anyone.
+ a.Contains(body, "not one this build understands")
+ a.NotContains(body, "turned MCP access off")
// Restoring the row proves the refusal was the unreadable policy and
// nothing else: the very same token opens a session again.
@@ -391,7 +395,7 @@ func TestMCPMigrationTightenedCeilingBitesLiveSession(t *testing.T) {
status, body := postMCP(t, ctl, mcpToken)
a.Equal(http.StatusForbidden, status,
"the same bearer must be refused on its next request after the ceiling tightens; %s", body)
- a.Contains(body, "MCP access is disabled")
+ a.Contains(body, "turned MCP access off")
_, err = session.CallTool(ctx, &mcp.CallToolParams{
Name: "call_api",
diff --git a/frontend/src/components/AuditLogTable.tsx b/frontend/src/components/AuditLogTable.tsx
index 6ad8bb7dc3..4cc0fb0466 100644
--- a/frontend/src/components/AuditLogTable.tsx
+++ b/frontend/src/components/AuditLogTable.tsx
@@ -255,12 +255,14 @@ function McpProvenanceDetail({
);
}
-// AuditLogActorCell renders the acting user, badged when the call reached the
-// API through the MCP server's delegated credential. Presence of
-// `mcpDelegation` is the marker — never read its values to decide MCP-ness.
-// Only `correlationId` is minted for every session; `scope`, `resource`, and
-// `clientId` are grant state that a legacy or scope-omitting session leaves
-// empty, so no field value is a sound proxy for MCP origin.
+// AuditLogActorCell renders the acting user, badged when the entry belongs to
+// MCP: a call that reached the API through the MCP server's delegated
+// credential, or one of the two MCP doors outside the API — the /mcp gate and
+// the OAuth2 consent. Presence of `mcpDelegation` is the marker — never read
+// its values to decide MCP-ness. Every field of it can be empty: `scope`,
+// `resource`, and `clientId` are grant state a legacy or scope-omitting session
+// leaves unset, and `correlationId` is minted at /mcp, so a consent entry has
+// none.
function AuditLogActorCell({ log }: Readonly<{ log: AuditLog }>) {
const { t } = useTranslation();
const email = extractUserEmail(log.user);
diff --git a/frontend/src/types/proto-es/v1/audit_log_service_pb.d.ts b/frontend/src/types/proto-es/v1/audit_log_service_pb.d.ts
index bfbb60fc33..2649447770 100644
--- a/frontend/src/types/proto-es/v1/audit_log_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/audit_log_service_pb.d.ts
@@ -30,16 +30,21 @@ export declare type SearchAuditLogsRequest = Message<"bytebase.v1.SearchAuditLog
* The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
*
* Supported filter:
- * - method: the API name, can be found in the docs, should start with "/bytebase.v1." prefix. For example "/bytebase.v1.UserService/CreateUser". Support "==" operator.
+ * - method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
+ * - resource: the resource the entry is about, support "==" operator.
* - severity: support "==" operator, check Severity enum in AuditLog message for values.
* - user: the actor, should in "users/{email}" format, support "==" operator.
* - create_time: support ">=" and "<=" operator.
+ * - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
+ * - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
*
* For example:
* - filter = "method == '/bytebase.v1.SQLService/Query'"
* - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
* - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
* - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
+ * - filter = "mcp == true"
+ * - filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
*
* @generated from field: string filter = 1;
*/
diff --git a/frontend/src/types/proto-es/v1/workspace_service_pb.d.ts b/frontend/src/types/proto-es/v1/workspace_service_pb.d.ts
index a887316eb6..c13474df28 100644
--- a/frontend/src/types/proto-es/v1/workspace_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/workspace_service_pb.d.ts
@@ -2,8 +2,11 @@
// @generated from file v1/workspace_service.proto (package bytebase.v1, syntax proto3)
/* eslint-disable */
-import type { GenFile, GenMessage, GenService } from "@bufbuild/protobuf/codegenv2";
+import type { GenEnum, GenFile, GenMessage, GenService } from "@bufbuild/protobuf/codegenv2";
import type { Message } from "@bufbuild/protobuf";
+import type { MCPSetting_Capability } from "./setting_service_pb";
+import type { AuthMethod, MCPMethodClass } from "./annotation_pb";
+import type { Engine } from "./common_pb";
import type { FieldMask } from "@bufbuild/protobuf/wkt";
import type { GetIamPolicyRequestSchema, IamPolicySchema, SetIamPolicyRequestSchema } from "./iam_policy_pb";
import type { LoginResponseSchema } from "./auth_service_pb";
@@ -13,6 +16,311 @@ import type { LoginResponseSchema } from "./auth_service_pb";
*/
export declare const file_v1_workspace_service: GenFile;
+/**
+ * @generated from message bytebase.v1.GetMCPInfoRequest
+ */
+export declare type GetMCPInfoRequest = Message<"bytebase.v1.GetMCPInfoRequest"> & {
+};
+
+/**
+ * Describes the message bytebase.v1.GetMCPInfoRequest.
+ * Use `create(GetMCPInfoRequestSchema)` to create a new message.
+ */
+export declare const GetMCPInfoRequestSchema: GenMessage<GetMCPInfoRequest>;
+
+/**
+ * MCPInfo is what MCP does in this workspace: the ceiling in force, what each
+ * ceiling serves, and the per-engine facts a read-only session depends on.
+ *
+ * Everything here is resolved when the request is served, never from a stored
+ * copy: the method list comes off the compiled API descriptors and the engine
+ * answers off the code that enforces them, so a build whose rules changed
+ * cannot describe the rules of the build before it.
+ *
+ * @generated from message bytebase.v1.MCPInfo
+ */
+export declare type MCPInfo = Message<"bytebase.v1.MCPInfo"> & {
+ /**
+ * The workspace this describes. Format: workspaces/{workspace}. Not this
+ * message's own resource name — MCPInfo is not a named resource and there is
+ * nothing to get it by.
+ *
+ * @generated from field: string workspace = 1;
+ */
+ workspace: string;
+
+ /**
+ * The ceiling in force for this workspace. A workspace that never configured
+ * MCP resolves to READ_WRITE.
+ *
+ * @generated from field: bytebase.v1.MCPSetting.Capability capability = 2;
+ */
+ capability: MCPSetting_Capability;
+
+ /**
+ * What each ceiling serves, including the one in force, so an admin can
+ * compare the choices rather than only read the current answer.
+ *
+ * @generated from field: repeated bytebase.v1.MCPCapabilityMode modes = 3;
+ */
+ modes: MCPCapabilityMode[];
+
+ /**
+ * Every API method some ceiling serves. A mode serves a method when the
+ * method's class is one of that mode's served_classes, which is the ceiling
+ * rule the gate evaluates. Methods no ceiling serves are absent.
+ *
+ * Being listed is necessary, not sufficient. The caller still needs the
+ * permission, and two further rules narrow what a served method does: a
+ * handful of methods are refused on the shape of the request (an issue that
+ * would grant a permission, a rollout that skips approval), and under
+ * READ_ONLY every statement SQLService/Query runs must classify as a read.
+ *
+ * @generated from field: repeated bytebase.v1.MCPMethod methods = 4;
+ */
+ methods: MCPMethod[];
+
+ /**
+ * What a read-only session and the masking toggle actually reach, per engine.
+ * Both are engine-conditional in ways the ceiling alone does not show.
+ *
+ * @generated from field: repeated bytebase.v1.MCPEngineEnforcement engines = 5;
+ */
+ engines: MCPEngineEnforcement[];
+
+ /**
+ * Whether this workspace stops applying the caller's own unmasking
+ * provisioning to MCP requests. It decides which branch of each engine's
+ * masking state a caller is in, and no other API tells an MCP session:
+ * SettingService/GetSetting is served by no ceiling.
+ *
+ * @generated from field: bool ignore_masking_exemptions = 6;
+ */
+ ignoreMaskingExemptions: boolean;
+
+ /**
+ * Whether data masking is licensed for this workspace. When false nothing is
+ * masked whatever an engine supports, so the masking states below describe a
+ * mechanism that does not run. Licensing can also be set per instance, so a
+ * true here is the workspace answer, not a promise about every instance.
+ *
+ * @generated from field: bool data_masking_available = 7;
+ */
+ dataMaskingAvailable: boolean;
+};
+
+/**
+ * Describes the message bytebase.v1.MCPInfo.
+ * Use `create(MCPInfoSchema)` to create a new message.
+ */
+export declare const MCPInfoSchema: GenMessage<MCPInfo>;
+
+/**
+ * MCPCapabilityMode is one ceiling and the method classes it serves.
+ *
+ * @generated from message bytebase.v1.MCPCapabilityMode
+ */
+export declare type MCPCapabilityMode = Message<"bytebase.v1.MCPCapabilityMode"> & {
+ /**
+ * @generated from field: bytebase.v1.MCPSetting.Capability capability = 1;
+ */
+ capability: MCPSetting_Capability;
+
+ /**
+ * Empty means the ceiling serves nothing, which is what DISABLED is.
+ *
+ * @generated from field: repeated bytebase.v1.MCPMethodClass served_classes = 2;
+ */
+ servedClasses: MCPMethodClass[];
+};
+
+/**
+ * Describes the message bytebase.v1.MCPCapabilityMode.
+ * Use `create(MCPCapabilityModeSchema)` to create a new message.
+ */
+export declare const MCPCapabilityModeSchema: GenMessage<MCPCapabilityMode>;
+
+/**
+ * MCPMethod is one API method an MCP session can reach, and what decides it.
+ *
+ * @generated from message bytebase.v1.MCPMethod
+ */
+export declare type MCPMethod = Message<"bytebase.v1.MCPMethod"> & {
+ /**
+ * The method as an audit entry names it, so a denial can be found by it.
+ * Example: /bytebase.v1.SQLService/Query
+ *
+ * @generated from field: string method = 1;
+ */
+ method: string;
+
+ /**
+ * The same method as call_api takes it.
+ * Example: bytebase.v1.SQLService.Query
+ *
+ * @generated from field: string operation_id = 4;
+ */
+ operationId: string;
+
+ /**
+ * @generated from field: bytebase.v1.MCPMethodClass class = 2;
+ */
+ class: MCPMethodClass;
+
+ /**
+ * The IAM permission the method declares. The ceiling never grants: a session
+ * may call a served method only where the person it acts for could.
+ *
+ * Empty means the method declares no permission, which is NOT the same as
+ * needing none — a method that authorizes inside its handler declares nothing
+ * here. auth_method says which case an empty value is.
+ *
+ * @generated from field: string permission = 3;
+ */
+ permission: string;
+
+ /**
+ * How the method authorizes. IAM means the permission above is the primary
+ * rule, though not always the only one — an update carrying allow_missing
+ * additionally requires the matching create permission. CUSTOM means the
+ * handler decides and the permission field is silent.
+ *
+ * @generated from field: bytebase.v1.AuthMethod auth_method = 5;
+ */
+ authMethod: AuthMethod;
+};
+
+/**
+ * Describes the message bytebase.v1.MCPMethod.
+ * Use `create(MCPMethodSchema)` to create a new message.
+ */
+export declare const MCPMethodSchema: GenMessage<MCPMethod>;
+
+/**
+ * MCPEngineEnforcement is what the read-only ceiling and the masking toggle
+ * reach on one database engine.
+ *
+ * @generated from message bytebase.v1.MCPEngineEnforcement
+ */
+export declare type MCPEngineEnforcement = Message<"bytebase.v1.MCPEngineEnforcement"> & {
+ /**
+ * @generated from field: bytebase.v1.Engine engine = 1;
+ */
+ engine: Engine;
+
+ /**
+ * @generated from field: bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth read_only_depth = 2;
+ */
+ readOnlyDepth: MCPEngineEnforcement_ReadOnlyDepth;
+
+ /**
+ * @generated from field: bytebase.v1.MCPEngineEnforcement.Masking masking = 3;
+ */
+ masking: MCPEngineEnforcement_Masking;
+
+ /**
+ * Where the answers above are the floor rather than the whole story. Empty
+ * for most engines.
+ *
+ * @generated from field: string note = 4;
+ */
+ note: string;
+};
+
+/**
+ * Describes the message bytebase.v1.MCPEngineEnforcement.
+ * Use `create(MCPEngineEnforcementSchema)` to create a new message.
+ */
+export declare const MCPEngineEnforcementSchema: GenMessage<MCPEngineEnforcement>;
+
+/**
+ * How much of a read-only ceiling this engine can be held to.
+ *
+ * @generated from enum bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth
+ */
+export enum MCPEngineEnforcement_ReadOnlyDepth {
+ /**
+ * @generated from enum value: READ_ONLY_DEPTH_UNSPECIFIED = 0;
+ */
+ READ_ONLY_DEPTH_UNSPECIFIED = 0,
+
+ /**
+ * Bytebase has no read-only classifier for this engine, so a read-only
+ * session is refused every statement on it, including a plain SELECT.
+ *
+ * @generated from enum value: UNSUPPORTED = 1;
+ */
+ UNSUPPORTED = 1,
+
+ /**
+ * Every statement is classified before it runs and a request holding one
+ * that is not a read is refused whole. Nothing below that: the driver does
+ * not open a read-only database session, except where the note says
+ * otherwise.
+ *
+ * @generated from enum value: STATEMENT = 2;
+ */
+ STATEMENT = 2,
+
+ /**
+ * Statement classification, and the driver opens the database session
+ * read-only as well, so the engine refuses most writes the classifier
+ * missed. Not a proof: a statement that classifies as a read can still call
+ * a function that switches the session setting back off.
+ *
+ * @generated from enum value: STATEMENT_AND_SESSION = 3;
+ */
+ STATEMENT_AND_SESSION = 3,
+}
+
+/**
+ * Describes the enum bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth.
+ */
+export declare const MCPEngineEnforcement_ReadOnlyDepthSchema: GenEnum<MCPEngineEnforcement_ReadOnlyDepth>;
+
+/**
+ * How Bytebase masks results on this engine, which is what decides whether
+ * ignoring masking exemptions changes anything here.
+ *
+ * @generated from enum bytebase.v1.MCPEngineEnforcement.Masking
+ */
+export enum MCPEngineEnforcement_Masking {
+ /**
+ * @generated from enum value: MASKING_UNSPECIFIED = 0;
+ */
+ MASKING_UNSPECIFIED = 0,
+
+ /**
+ * Bytebase does not mask on this engine. Nothing narrows what a session
+ * reads, and ignoring masking exemptions does nothing.
+ *
+ * @generated from enum value: NONE = 1;
+ */
+ NONE = 1,
+
+ /**
+ * Column masking. A masking policy substitutes values in query results,
+ * and the exemptions granted to the caller are what let them see the real
+ * value — which is what ignoring exemptions suppresses.
+ *
+ * @generated from enum value: COLUMN = 2;
+ */
+ COLUMN = 2,
+
+ /**
+ * Document masking. Results are masked, but exemptions are never consulted
+ * on this path, so ignoring them changes nothing here either.
+ *
+ * @generated from enum value: DOCUMENT = 3;
+ */
+ DOCUMENT = 3,
+}
+
+/**
+ * Describes the enum bytebase.v1.MCPEngineEnforcement.Masking.
+ */
+export declare const MCPEngineEnforcement_MaskingSchema: GenEnum<MCPEngineEnforcement_Masking>;
+
/**
* @generated from message bytebase.v1.RotateDirectorySyncTokenRequest
*/
@@ -270,6 +578,26 @@ export declare const WorkspaceService: GenService<{
input: typeof SetIamPolicyRequestSchema;
output: typeof IamPolicySchema;
},
+ /**
+ * Gets what MCP (Model Context Protocol) does in this workspace: the
+ * capability ceiling in force, what each ceiling serves, and the per-engine
+ * facts a read-only session depends on. The workspace is resolved from the
+ * authenticated session.
+ *
+ * Served to MCP sessions. An agent asking what it may do here is the point:
+ * the response says nothing a session's own denials do not already say, one
+ * refusal at a time, and knowing it up front is what stops the agent
+ * planning work the ceiling was never going to serve.
+ *
+ * Permissions required: None (authentication required)
+ *
+ * @generated from rpc bytebase.v1.WorkspaceService.GetMCPInfo
+ */
+ getMCPInfo: {
+ methodKind: "unary";
+ input: typeof GetMCPInfoRequestSchema;
+ output: typeof MCPInfoSchema;
+ },
/**
* Mints a new directory sync (SCIM) token, immediately invalidating the
* previous one. The plaintext token is returned exactly once and cannot be
diff --git a/frontend/src/types/proto-es/v1/workspace_service_pb.js b/frontend/src/types/proto-es/v1/workspace_service_pb.js
index 198f680e57..006792ecdc 100644
--- a/frontend/src/types/proto-es/v1/workspace_service_pb.js
+++ b/frontend/src/types/proto-es/v1/workspace_service_pb.js
@@ -2,7 +2,7 @@
// @generated from file v1/workspace_service.proto (package bytebase.v1, syntax proto3)
/* eslint-disable */
-import { fileDesc, messageDesc, serviceDesc } from "@bufbuild/protobuf/codegenv2";
+import { enumDesc, fileDesc, messageDesc, serviceDesc, tsEnum } from "@bufbuild/protobuf/codegenv2";
import { file_google_api_annotations } from "../google/api/annotations_pb";
import { file_google_api_client } from "../google/api/client_pb";
import { file_google_api_field_behavior } from "../google/api/field_behavior_pb";
@@ -10,76 +10,142 @@ import { file_google_api_resource } from "../google/api/resource_pb";
import { file_google_protobuf_field_mask } from "@bufbuild/protobuf/wkt";
import { file_v1_annotation } from "./annotation_pb";
import { file_v1_auth_service } from "./auth_service_pb";
+import { file_v1_common } from "./common_pb";
import { file_v1_iam_policy } from "./iam_policy_pb";
+import { file_v1_setting_service } from "./setting_service_pb";
/**
* Describes the file v1/workspace_service.proto.
*/
export const file_v1_workspace_service = /*@__PURE__*/
- fileDesc("Chp2MS93b3Jrc3BhY2Vfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiTwofUm90YXRlRGlyZWN0b3J5U3luY1Rva2VuUmVxdWVzdBIsCgRuYW1lGAEgASgJQh7gQQL6QRgKFmJ5dGViYXNlLmNvbS9Xb3Jrc3BhY2UiOgogUm90YXRlRGlyZWN0b3J5U3luY1Rva2VuUmVzcG9uc2USFgoFdG9rZW4YASABKAlCB+BBA9DqMAEiFwoVTGlzdFdvcmtzcGFjZXNSZXF1ZXN0IkQKFkxpc3RXb3Jrc3BhY2VzUmVzcG9uc2USKgoKd29ya3NwYWNlcxgBIAMoCzIWLmJ5dGViYXNlLnYxLldvcmtzcGFjZSIjChNHZXRXb3Jrc3BhY2VSZXF1ZXN0EgwKBG5hbWUYASABKAkiNgoJV29ya3NwYWNlEgwKBG5hbWUYASABKAkSDQoFdGl0bGUYAiABKAkSDAoEbG9nbxgDIAEoCSIrChZEZWxldGVXb3Jrc3BhY2VSZXF1ZXN0EhEKBG5hbWUYASABKAlCA+BBAiJ5ChZVcGRhdGVXb3Jrc3BhY2VSZXF1ZXN0Ei4KCXdvcmtzcGFjZRgBIAEoCzIWLmJ5dGViYXNlLnYxLldvcmtzcGFjZUID4EECEi8KC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzayIqChVMZWF2ZVdvcmtzcGFjZVJlcXVlc3QSEQoEbmFtZRgBIAEoCUID4EECMp8KChBXb3Jrc3BhY2VTZXJ2aWNlEnEKDEdldFdvcmtzcGFjZRIgLmJ5dGViYXNlLnYxLkdldFdvcmtzcGFjZVJlcXVlc3QaFi5ieXRlYmFzZS52MS5Xb3Jrc3BhY2UiJ4DqMAGg6jABgtPkkwIZEhcvdjEve25hbWU9d29ya3NwYWNlcy8qfRJ5Cg5MaXN0V29ya3NwYWNlcxIiLmJ5dGViYXNlLnYxLkxpc3RXb3Jrc3BhY2VzUmVxdWVzdBojLmJ5dGViYXNlLnYxLkxpc3RXb3Jrc3BhY2VzUmVzcG9uc2UiHpDqMAKg6jABgtPkkwIQEg4vdjEvd29ya3NwYWNlcxKkAQoPVXBkYXRlV29ya3NwYWNlEiMuYnl0ZWJhc2UudjEuVXBkYXRlV29ya3NwYWNlUmVxdWVzdBoWLmJ5dGViYXNlLnYxLldvcmtzcGFjZSJUiuowFGJiLndvcmtzcGFjZXMudXBkYXRlkOowAZjqMAGg6jAEqOowCYLT5JMCJjoBKjIhL3YxL3t3b3Jrc3BhY2UubmFtZT13b3Jrc3BhY2VzLyp9EqQBCgxHZXRJYW1Qb2xpY3kSIC5ieXRlYmFzZS52MS5HZXRJYW1Qb2xpY3lSZXF1ZXN0GhYuYnl0ZWJhc2UudjEuSWFtUG9saWN5IlqK6jAaYmIud29ya3NwYWNlcy5nZXRJYW1Qb2xpY3mQ6jABoOowBKjqMAmC0+STAioSKC92MS97cmVzb3VyY2U9d29ya3NwYWNlcy8qfTpnZXRJYW1Qb2xpY3kSmwEKD0RlbGV0ZVdvcmtzcGFjZRIjLmJ5dGViYXNlLnYxLkRlbGV0ZVdvcmtzcGFjZVJlcXVlc3QaGi5ieXRlYmFzZS52MS5Mb2dpblJlc3BvbnNlIkeK6jAUYmIud29ya3NwYWNlcy5kZWxldGWQ6jABmOowAaDqMAOo6jAFgtPkkwIZKhcvdjEve25hbWU9d29ya3NwYWNlcy8qfRKKAQoOTGVhdmVXb3Jrc3BhY2USIi5ieXRlYmFzZS52MS5MZWF2ZVdvcmtzcGFjZVJlcXVlc3QaGi5ieXRlYmFzZS52MS5Mb2dpblJlc3BvbnNlIjiQ6jACmOowAaDqMAOo6jAFgtPkkwIiOgEqIh0vdjEve25hbWU9d29ya3NwYWNlcy8qfTpsZWF2ZRKrAQoMU2V0SWFtUG9saWN5EiAuYnl0ZWJhc2UudjEuU2V0SWFtUG9saWN5UmVxdWVzdBoWLmJ5dGViYXNlLnYxLklhbVBvbGljeSJhiuowGmJiLndvcmtzcGFjZXMuc2V0SWFtUG9saWN5kOowAZjqMAGg6jAEqOowCYLT5JMCLToBKiIoL3YxL3tyZXNvdXJjZT13b3Jrc3BhY2VzLyp9OnNldElhbVBvbGljeRL1AQoYUm90YXRlRGlyZWN0b3J5U3luY1Rva2VuEiwuYnl0ZWJhc2UudjEuUm90YXRlRGlyZWN0b3J5U3luY1Rva2VuUmVxdWVzdBotLmJ5dGViYXNlLnYxLlJvdGF0ZURpcmVjdG9yeVN5bmNUb2tlblJlc3BvbnNlInzaQQRuYW1liuowJmJiLndvcmtzcGFjZXMucm90YXRlRGlyZWN0b3J5U3luY1Rva2VukOowAZjqMAGg6jADqOowBoLT5JMCNToBKiIwL3YxL3tuYW1lPXdvcmtzcGFjZXMvKn06cm90YXRlRGlyZWN0b3J5U3luY1Rva2VuQqsBCg9jb20uYnl0ZWJhc2UudjFCFVdvcmtzcGFjZVNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_field_mask, file_v1_annotation, file_v1_auth_service, file_v1_iam_policy]);
+ fileDesc("Chp2MS93b3Jrc3BhY2Vfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiEwoRR2V0TUNQSW5mb1JlcXVlc3QixgIKB01DUEluZm8SFgoJd29ya3NwYWNlGAEgASgJQgPgQQMSOwoKY2FwYWJpbGl0eRgCIAEoDjIiLmJ5dGViYXNlLnYxLk1DUFNldHRpbmcuQ2FwYWJpbGl0eUID4EEDEjIKBW1vZGVzGAMgAygLMh4uYnl0ZWJhc2UudjEuTUNQQ2FwYWJpbGl0eU1vZGVCA+BBAxIsCgdtZXRob2RzGAQgAygLMhYuYnl0ZWJhc2UudjEuTUNQTWV0aG9kQgPgQQMSNwoHZW5naW5lcxgFIAMoCzIhLmJ5dGViYXNlLnYxLk1DUEVuZ2luZUVuZm9yY2VtZW50QgPgQQMSJgoZaWdub3JlX21hc2tpbmdfZXhlbXB0aW9ucxgGIAEoCEID4EEDEiMKFmRhdGFfbWFza2luZ19hdmFpbGFibGUYByABKAhCA+BBAyKAAQoRTUNQQ2FwYWJpbGl0eU1vZGUSNgoKY2FwYWJpbGl0eRgBIAEoDjIiLmJ5dGViYXNlLnYxLk1DUFNldHRpbmcuQ2FwYWJpbGl0eRIzCg5zZXJ2ZWRfY2xhc3NlcxgCIAMoDjIbLmJ5dGViYXNlLnYxLk1DUE1ldGhvZENsYXNzIp8BCglNQ1BNZXRob2QSDgoGbWV0aG9kGAEgASgJEhQKDG9wZXJhdGlvbl9pZBgEIAEoCRIqCgVjbGFzcxgCIAEoDjIbLmJ5dGViYXNlLnYxLk1DUE1ldGhvZENsYXNzEhIKCnBlcm1pc3Npb24YAyABKAkSLAoLYXV0aF9tZXRob2QYBSABKA4yFy5ieXRlYmFzZS52MS5BdXRoTWV0aG9kIoQDChRNQ1BFbmdpbmVFbmZvcmNlbWVudBIjCgZlbmdpbmUYASABKA4yEy5ieXRlYmFzZS52MS5FbmdpbmUSSAoPcmVhZF9vbmx5X2RlcHRoGAIgASgOMi8uYnl0ZWJhc2UudjEuTUNQRW5naW5lRW5mb3JjZW1lbnQuUmVhZE9ubHlEZXB0aBI6CgdtYXNraW5nGAMgASgOMikuYnl0ZWJhc2UudjEuTUNQRW5naW5lRW5mb3JjZW1lbnQuTWFza2luZxIMCgRub3RlGAQgASgJImsKDVJlYWRPbmx5RGVwdGgSHwobUkVBRF9PTkxZX0RFUFRIX1VOU1BFQ0lGSUVEEAASDwoLVU5TVVBQT1JURUQQARINCglTVEFURU1FTlQQAhIZChVTVEFURU1FTlRfQU5EX1NFU1NJT04QAyJGCgdNYXNraW5nEhcKE01BU0tJTkdfVU5TUEVDSUZJRUQQABIICgROT05FEAESCgoGQ09MVU1OEAISDAoIRE9DVU1FTlQQAyJPCh9Sb3RhdGVEaXJlY3RvcnlTeW5jVG9rZW5SZXF1ZXN0EiwKBG5hbWUYASABKAlCHuBBAvpBGAoWYnl0ZWJhc2UuY29tL1dvcmtzcGFjZSI6CiBSb3RhdGVEaXJlY3RvcnlTeW5jVG9rZW5SZXNwb25zZRIWCgV0b2tlbhgBIAEoCUIH4EED0OowASIXChVMaXN0V29ya3NwYWNlc1JlcXVlc3QiRAoWTGlzdFdvcmtzcGFjZXNSZXNwb25zZRIqCgp3b3Jrc3BhY2VzGAEgAygLMhYuYnl0ZWJhc2UudjEuV29ya3NwYWNlIiMKE0dldFdvcmtzcGFjZVJlcXVlc3QSDAoEbmFtZRgBIAEoCSI2CglXb3Jrc3BhY2USDAoEbmFtZRgBIAEoCRINCgV0aXRsZRgCIAEoCRIMCgRsb2dvGAMgASgJIisKFkRlbGV0ZVdvcmtzcGFjZVJlcXVlc3QSEQoEbmFtZRgBIAEoCUID4EECInkKFlVwZGF0ZVdvcmtzcGFjZVJlcXVlc3QSLgoJd29ya3NwYWNlGAEgASgLMhYuYnl0ZWJhc2UudjEuV29ya3NwYWNlQgPgQQISLwoLdXBkYXRlX21hc2sYAiABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrIioKFUxlYXZlV29ya3NwYWNlUmVxdWVzdBIRCgRuYW1lGAEgASgJQgPgQQIygAsKEFdvcmtzcGFjZVNlcnZpY2UScQoMR2V0V29ya3NwYWNlEiAuYnl0ZWJhc2UudjEuR2V0V29ya3NwYWNlUmVxdWVzdBoWLmJ5dGViYXNlLnYxLldvcmtzcGFjZSIngOowAaDqMAGC0+STAhkSFy92MS97bmFtZT13b3Jrc3BhY2VzLyp9EnkKDkxpc3RXb3Jrc3BhY2VzEiIuYnl0ZWJhc2UudjEuTGlzdFdvcmtzcGFjZXNSZXF1ZXN0GiMuYnl0ZWJhc2UudjEuTGlzdFdvcmtzcGFjZXNSZXNwb25zZSIekOowAqDqMAGC0+STAhASDi92MS93b3Jrc3BhY2VzEqQBCg9VcGRhdGVXb3Jrc3BhY2USIy5ieXRlYmFzZS52MS5VcGRhdGVXb3Jrc3BhY2VSZXF1ZXN0GhYuYnl0ZWJhc2UudjEuV29ya3NwYWNlIlSK6jAUYmIud29ya3NwYWNlcy51cGRhdGWQ6jABmOowAaDqMASo6jAJgtPkkwImOgEqMiEvdjEve3dvcmtzcGFjZS5uYW1lPXdvcmtzcGFjZXMvKn0SpAEKDEdldElhbVBvbGljeRIgLmJ5dGViYXNlLnYxLkdldElhbVBvbGljeVJlcXVlc3QaFi5ieXRlYmFzZS52MS5JYW1Qb2xpY3kiWorqMBpiYi53b3Jrc3BhY2VzLmdldElhbVBvbGljeZDqMAGg6jAEqOowCYLT5JMCKhIoL3YxL3tyZXNvdXJjZT13b3Jrc3BhY2VzLyp9OmdldElhbVBvbGljeRKbAQoPRGVsZXRlV29ya3NwYWNlEiMuYnl0ZWJhc2UudjEuRGVsZXRlV29ya3NwYWNlUmVxdWVzdBoaLmJ5dGViYXNlLnYxLkxvZ2luUmVzcG9uc2UiR4rqMBRiYi53b3Jrc3BhY2VzLmRlbGV0ZZDqMAGY6jABoOowA6jqMAWC0+STAhkqFy92MS97bmFtZT13b3Jrc3BhY2VzLyp9EooBCg5MZWF2ZVdvcmtzcGFjZRIiLmJ5dGViYXNlLnYxLkxlYXZlV29ya3NwYWNlUmVxdWVzdBoaLmJ5dGViYXNlLnYxLkxvZ2luUmVzcG9uc2UiOJDqMAKY6jABoOowA6jqMAWC0+STAiI6ASoiHS92MS97bmFtZT13b3Jrc3BhY2VzLyp9OmxlYXZlEqsBCgxTZXRJYW1Qb2xpY3kSIC5ieXRlYmFzZS52MS5TZXRJYW1Qb2xpY3lSZXF1ZXN0GhYuYnl0ZWJhc2UudjEuSWFtUG9saWN5ImGK6jAaYmIud29ya3NwYWNlcy5zZXRJYW1Qb2xpY3mQ6jABmOowAaDqMASo6jAJgtPkkwItOgEqIigvdjEve3Jlc291cmNlPXdvcmtzcGFjZXMvKn06c2V0SWFtUG9saWN5El8KCkdldE1DUEluZm8SHi5ieXRlYmFzZS52MS5HZXRNQ1BJbmZvUmVxdWVzdBoULmJ5dGViYXNlLnYxLk1DUEluZm8iG9pBAKDqMAGC0+STAg4SDC92MS9tY3AvaW5mbxL1AQoYUm90YXRlRGlyZWN0b3J5U3luY1Rva2VuEiwuYnl0ZWJhc2UudjEuUm90YXRlRGlyZWN0b3J5U3luY1Rva2VuUmVxdWVzdBotLmJ5dGViYXNlLnYxLlJvdGF0ZURpcmVjdG9yeVN5bmNUb2tlblJlc3BvbnNlInzaQQRuYW1liuowJmJiLndvcmtzcGFjZXMucm90YXRlRGlyZWN0b3J5U3luY1Rva2VukOowAZjqMAGg6jADqOowBoLT5JMCNToBKiIwL3YxL3tuYW1lPXdvcmtzcGFjZXMvKn06cm90YXRlRGlyZWN0b3J5U3luY1Rva2VuQqsBCg9jb20uYnl0ZWJhc2UudjFCFVdvcmtzcGFjZVNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_field_mask, file_v1_annotation, file_v1_auth_service, file_v1_common, file_v1_iam_policy, file_v1_setting_service]);
+
+/**
+ * Describes the message bytebase.v1.GetMCPInfoRequest.
+ * Use `create(GetMCPInfoRequestSchema)` to create a new message.
+ */
+export const GetMCPInfoRequestSchema = /*@__PURE__*/
+ messageDesc(file_v1_workspace_service, 0);
+
+/**
+ * Describes the message bytebase.v1.MCPInfo.
+ * Use `create(MCPInfoSchema)` to create a new message.
+ */
+export const MCPInfoSchema = /*@__PURE__*/
+ messageDesc(file_v1_workspace_service, 1);
+
+/**
+ * Describes the message bytebase.v1.MCPCapabilityMode.
+ * Use `create(MCPCapabilityModeSchema)` to create a new message.
+ */
+export const MCPCapabilityModeSchema = /*@__PURE__*/
+ messageDesc(file_v1_workspace_service, 2);
+
+/**
+ * Describes the message bytebase.v1.MCPMethod.
+ * Use `create(MCPMethodSchema)` to create a new message.
+ */
+export const MCPMethodSchema = /*@__PURE__*/
+ messageDesc(file_v1_workspace_service, 3);
+
+/**
+ * Describes the message bytebase.v1.MCPEngineEnforcement.
+ * Use `create(MCPEngineEnforcementSchema)` to create a new message.
+ */
+export const MCPEngineEnforcementSchema = /*@__PURE__*/
+ messageDesc(file_v1_workspace_service, 4);
+
+/**
+ * Describes the enum bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth.
+ */
+export const MCPEngineEnforcement_ReadOnlyDepthSchema = /*@__PURE__*/
+ enumDesc(file_v1_workspace_service, 4, 0);
+
+/**
+ * How much of a read-only ceiling this engine can be held to.
+ *
+ * @generated from enum bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth
+ */
+export const MCPEngineEnforcement_ReadOnlyDepth = /*@__PURE__*/
+ tsEnum(MCPEngineEnforcement_ReadOnlyDepthSchema);
+
+/**
+ * Describes the enum bytebase.v1.MCPEngineEnforcement.Masking.
+ */
+export const MCPEngineEnforcement_MaskingSchema = /*@__PURE__*/
+ enumDesc(file_v1_workspace_service, 4, 1);
+
+/**
+ * How Bytebase masks results on this engine, which is what decides whether
+ * ignoring masking exemptions changes anything here.
+ *
+ * @generated from enum bytebase.v1.MCPEngineEnforcement.Masking
+ */
+export const MCPEngineEnforcement_Masking = /*@__PURE__*/
+ tsEnum(MCPEngineEnforcement_MaskingSchema);
/**
* Describes the message bytebase.v1.RotateDirectorySyncTokenRequest.
* Use `create(RotateDirectorySyncTokenRequestSchema)` to create a new message.
*/
export const RotateDirectorySyncTokenRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_workspace_service, 0);
+ messageDesc(file_v1_workspace_service, 5);
/**
* Describes the message bytebase.v1.RotateDirectorySyncTokenResponse.
* Use `create(RotateDirectorySyncTokenResponseSchema)` to create a new message.
*/
export const RotateDirectorySyncTokenResponseSchema = /*@__PURE__*/
- messageDesc(file_v1_workspace_service, 1);
+ messageDesc(file_v1_workspace_service, 6);
/**
* Describes the message bytebase.v1.ListWorkspacesRequest.
* Use `create(ListWorkspacesRequestSchema)` to create a new message.
*/
export const ListWorkspacesRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_workspace_service, 2);
+ messageDesc(file_v1_workspace_service, 7);
/**
* Describes the message bytebase.v1.ListWorkspacesResponse.
* Use `create(ListWorkspacesResponseSchema)` to create a new message.
*/
export const ListWorkspacesResponseSchema = /*@__PURE__*/
- messageDesc(file_v1_workspace_service, 3);
+ messageDesc(file_v1_workspace_service, 8);
/**
* Describes the message bytebase.v1.GetWorkspaceRequest.
* Use `create(GetWorkspaceRequestSchema)` to create a new message.
*/
export const GetWorkspaceRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_workspace_service, 4);
+ messageDesc(file_v1_workspace_service, 9);
/**
* Describes the message bytebase.v1.Workspace.
* Use `create(WorkspaceSchema)` to create a new message.
*/
export const WorkspaceSchema = /*@__PURE__*/
- messageDesc(file_v1_workspace_service, 5);
+ messageDesc(file_v1_workspace_service, 10);
/**
* Describes the message bytebase.v1.DeleteWorkspaceRequest.
* Use `create(DeleteWorkspaceRequestSchema)` to create a new message.
*/
export const DeleteWorkspaceRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_workspace_service, 6);
+ messageDesc(file_v1_workspace_service, 11);
/**
* Describes the message bytebase.v1.UpdateWorkspaceRequest.
* Use `create(UpdateWorkspaceRequestSchema)` to create a new message.
*/
export const UpdateWorkspaceRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_workspace_service, 7);
+ messageDesc(file_v1_workspace_service, 12);
/**
* Describes the message bytebase.v1.LeaveWorkspaceRequest.
* Use `create(LeaveWorkspaceRequestSchema)` to create a new message.
*/
export const LeaveWorkspaceRequestSchema = /*@__PURE__*/
- messageDesc(file_v1_workspace_service, 8);
+ messageDesc(file_v1_workspace_service, 13);
/**
* WorkspaceService manages workspace-level operations and profile.
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index df18f71c98..1d18260fa2 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -5443,6 +5443,30 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/bytebase.v1.BatchUpdateInstancesResponse'
+ /v1/mcp/info:
+ get:
+ tags:
+ - WorkspaceService
+ summary: |-
+ Gets what MCP (Model Context Protocol) does in this workspace: the
+ capability ceiling in force, what each ceiling serves, and the per-engine
+ facts a read-only session depends on. The workspace is resolved from the
+ authenticated session.
+ description: |-
+ Served to MCP sessions. An agent asking what it may do here is the point:
+ the response says nothing a session's own denials do not already say, one
+ refusal at a time, and knowing it up front is what stops the agent
+ planning work the ceiling was never going to serve.
+
+ Permissions required: None (authentication required)
+ operationId: WorkspaceService_GetMCPInfo
+ responses:
+ "200":
+ description: Success
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/bytebase.v1.MCPInfo'
/v1/projects:
get:
tags:
@@ -6180,16 +6204,21 @@ paths:
The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
Supported filter:
- - method: the API name, can be found in the docs, should start with "/bytebase.v1." prefix. For example "/bytebase.v1.UserService/CreateUser". Support "==" operator.
+ - method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
+ - resource: the resource the entry is about, support "==" operator.
- severity: support "==" operator, check Severity enum in AuditLog message for values.
- user: the actor, should in "users/{email}" format, support "==" operator.
- create_time: support ">=" and "<=" operator.
+ - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
+ - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
For example:
- filter = "method == '/bytebase.v1.SQLService/Query'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
+ - filter = "mcp == true"
+ - filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
orderBy:
type: string
title: order_by
@@ -23185,6 +23214,10 @@ components:
required:
- name
additionalProperties: false
+ bytebase.v1.GetMCPInfoRequest:
+ type: object
+ title: GetMCPInfoRequest
+ additionalProperties: false
bytebase.v1.GetPaymentInfoRequest:
type: object
title: GetPaymentInfoRequest
@@ -25979,6 +26012,21 @@ components:
title: LogoutRequest
additionalProperties: false
description: Request to logout current user session.
+ bytebase.v1.MCPCapabilityMode:
+ type: object
+ properties:
+ capability:
+ title: capability
+ $ref: '#/components/schemas/bytebase.v1.MCPSetting.Capability'
+ servedClasses:
+ type: array
+ items:
+ $ref: '#/components/schemas/bytebase.v1.MCPMethodClass'
+ title: served_classes
+ description: Empty means the ceiling serves nothing, which is what DISABLED is.
+ title: MCPCapabilityMode
+ additionalProperties: false
+ description: MCPCapabilityMode is one ceiling and the method classes it serves.
bytebase.v1.MCPDelegation:
type: object
properties:
@@ -26051,6 +26099,168 @@ components:
that contradicts its class. Neither is expressible now, and the one check
left — the reason belongs to the class it is used on — is a table the gate
already keeps for the wording.
+ bytebase.v1.MCPEngineEnforcement:
+ type: object
+ properties:
+ engine:
+ title: engine
+ $ref: '#/components/schemas/bytebase.v1.Engine'
+ readOnlyDepth:
+ title: read_only_depth
+ $ref: '#/components/schemas/bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth'
+ masking:
+ title: masking
+ $ref: '#/components/schemas/bytebase.v1.MCPEngineEnforcement.Masking'
+ note:
+ type: string
+ title: note
+ description: |-
+ Where the answers above are the floor rather than the whole story. Empty
+ for most engines.
+ title: MCPEngineEnforcement
+ additionalProperties: false
+ description: |-
+ MCPEngineEnforcement is what the read-only ceiling and the masking toggle
+ reach on one database engine.
+ bytebase.v1.MCPEngineEnforcement.Masking:
+ type: string
+ title: Masking
+ enum:
+ - MASKING_UNSPECIFIED
+ - NONE
+ - COLUMN
+ - DOCUMENT
+ description: |-
+ How Bytebase masks results on this engine, which is what decides whether
+ ignoring masking exemptions changes anything here.
+ bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth:
+ type: string
+ title: ReadOnlyDepth
+ enum:
+ - READ_ONLY_DEPTH_UNSPECIFIED
+ - UNSUPPORTED
+ - STATEMENT
+ - STATEMENT_AND_SESSION
+ description: How much of a read-only ceiling this engine can be held to.
+ bytebase.v1.MCPInfo:
+ type: object
+ properties:
+ workspace:
+ type: string
+ title: workspace
+ description: |-
+ The workspace this describes. Format: workspaces/{workspace}. Not this
+ message's own resource name — MCPInfo is not a named resource and there is
+ nothing to get it by.
+ readOnly: true
+ capability:
+ title: capability
+ description: |-
+ The ceiling in force for this workspace. A workspace that never configured
+ MCP resolves to READ_WRITE.
+ readOnly: true
+ $ref: '#/components/schemas/bytebase.v1.MCPSetting.Capability'
+ modes:
+ type: array
+ items:
+ $ref: '#/components/schemas/bytebase.v1.MCPCapabilityMode'
+ title: modes
+ description: |-
+ What each ceiling serves, including the one in force, so an admin can
+ compare the choices rather than only read the current answer.
+ readOnly: true
+ methods:
+ type: array
+ items:
+ $ref: '#/components/schemas/bytebase.v1.MCPMethod'
+ title: methods
+ description: |-
+ Every API method some ceiling serves. A mode serves a method when the
+ method's class is one of that mode's served_classes, which is the ceiling
+ rule the gate evaluates. Methods no ceiling serves are absent.
+
+ Being listed is necessary, not sufficient. The caller still needs the
+ permission, and two further rules narrow what a served method does: a
+ handful of methods are refused on the shape of the request (an issue that
+ would grant a permission, a rollout that skips approval), and under
+ READ_ONLY every statement SQLService/Query runs must classify as a read.
+ readOnly: true
+ engines:
+ type: array
+ items:
+ $ref: '#/components/schemas/bytebase.v1.MCPEngineEnforcement'
+ title: engines
+ description: |-
+ What a read-only session and the masking toggle actually reach, per engine.
+ Both are engine-conditional in ways the ceiling alone does not show.
+ readOnly: true
+ ignoreMaskingExemptions:
+ type: boolean
+ title: ignore_masking_exemptions
+ description: |-
+ Whether this workspace stops applying the caller's own unmasking
+ provisioning to MCP requests. It decides which branch of each engine's
+ masking state a caller is in, and no other API tells an MCP session:
+ SettingService/GetSetting is served by no ceiling.
+ readOnly: true
+ dataMaskingAvailable:
+ type: boolean
+ title: data_masking_available
+ description: |-
+ Whether data masking is licensed for this workspace. When false nothing is
+ masked whatever an engine supports, so the masking states below describe a
+ mechanism that does not run. Licensing can also be set per instance, so a
+ true here is the workspace answer, not a promise about every instance.
+ readOnly: true
+ title: MCPInfo
+ additionalProperties: false
+ description: |-
+ MCPInfo is what MCP does in this workspace: the ceiling in force, what each
+ ceiling serves, and the per-engine facts a read-only session depends on.
+
+ Everything here is resolved when the request is served, never from a stored
+ copy: the method list comes off the compiled API descriptors and the engine
+ answers off the code that enforces them, so a build whose rules changed
+ cannot describe the rules of the build before it.
+ bytebase.v1.MCPMethod:
+ type: object
+ properties:
+ method:
+ type: string
+ title: method
+ description: |-
+ The method as an audit entry names it, so a denial can be found by it.
+ Example: /bytebase.v1.SQLService/Query
+ operationId:
+ type: string
+ title: operation_id
+ description: |-
+ The same method as call_api takes it.
+ Example: bytebase.v1.SQLService.Query
+ class:
+ title: class
+ $ref: '#/components/schemas/bytebase.v1.MCPMethodClass'
+ permission:
+ type: string
+ title: permission
+ description: |-
+ The IAM permission the method declares. The ceiling never grants: a session
+ may call a served method only where the person it acts for could.
+
+ Empty means the method declares no permission, which is NOT the same as
+ needing none — a method that authorizes inside its handler declares nothing
+ here. auth_method says which case an empty value is.
+ authMethod:
+ title: auth_method
+ description: |-
+ How the method authorizes. IAM means the permission above is the primary
+ rule, though not always the only one — an update carrying allow_missing
+ additionally requires the matching create permission. CUSTOM means the
+ handler decides and the permission field is silent.
+ $ref: '#/components/schemas/bytebase.v1.AuthMethod'
+ title: MCPMethod
+ additionalProperties: false
+ description: MCPMethod is one API method an MCP session can reach, and what decides it.
bytebase.v1.MCPMethodClass:
type: string
title: MCPMethodClass
@@ -29258,16 +29468,21 @@ components:
The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
Supported filter:
- - method: the API name, can be found in the docs, should start with "/bytebase.v1." prefix. For example "/bytebase.v1.UserService/CreateUser". Support "==" operator.
+ - method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
+ - resource: the resource the entry is about, support "==" operator.
- severity: support "==" operator, check Severity enum in AuditLog message for values.
- user: the actor, should in "users/{email}" format, support "==" operator.
- create_time: support ">=" and "<=" operator.
+ - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
+ - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
For example:
- filter = "method == '/bytebase.v1.SQLService/Query'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
- filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
+ - filter = "mcp == true"
+ - filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
orderBy:
type: string
title: order_by
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index b19b7d739c..97e2afa32a 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -846,7 +846,7 @@ Status represents the approver&#39;s decision state.
| latency | [google.protobuf.Duration](#google-protobuf-Duration) | | The latency of the RPC. |
| service_data | [google.protobuf.Any](#google-protobuf-Any) | | The service-specific data about the request, response, and other activities. |
| request_metadata | [RequestMetadata](#bytebase-store-RequestMetadata) | | Metadata about the operation. |
-| mcp_delegation | [MCPDelegation](#bytebase-store-MCPDelegation) | | MCP delegation provenance. Present exactly when the audited call arrived through the MCP server&#39;s delegated credential; never set for public API calls. Presence of this message is the MCP-origin marker. |
+| mcp_delegation | [MCPDelegation](#bytebase-store-MCPDelegation) | | MCP delegation provenance. Present exactly when the entry belongs to MCP: the audited call arrived through the MCP server&#39;s delegated credential, or it is one of the two MCP doors that sit outside the API — the /mcp connection gate and the OAuth2 consent that mints the credential it checks. Never set for public API calls. Presence of this message is the MCP-origin marker. |
@@ -867,7 +867,9 @@ stored nothing (legacy sessions), never a resolved or synthesized value.
| scope | [string](#string) | | The OAuth2 grant&#39;s consented scope, e.g. &#34;mcp:read-only&#34;. Empty when the grant recorded no scope. |
| resource | [string](#string) | | The grant&#39;s stored MCP resource URI. Empty for pre-grant legacy sessions. |
| client_id | [string](#string) | | The OAuth2 client the grant was consented to. Empty for legacy web-session tokens at /mcp. |
-| correlation_id | [string](#string) | | Correlates the audit rows an MCP session produces. Minted at the /mcp boundary and session-scoped: the MCP SDK hands tool handlers the initialize-time context, so one MCP session carries one correlation ID across all of its tool calls. |
+| correlation_id | [string](#string) | | Correlates the audit rows an MCP session produces. Minted at the /mcp boundary and session-scoped: the MCP SDK hands tool handlers the initialize-time context, so one MCP session carries one correlation ID across all of its tool calls.
+
+Empty on the entries that belong to no session — a refused consent, which never reached that boundary, and a refused connection, which is decided before the SDK resolves a session. Filling those with a fresh value would read as a session ID that correlates exactly one row, and a mid-session refusal would get an ID different from the rows the session already wrote. |
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index b1d8463a1d..df23476d83 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -2929,9 +2929,12 @@ Some fields are omitted because they are too large or contain sensitive informat
<td>mcp_delegation</td>
<td><a href="#bytebase.store.MCPDelegation">MCPDelegation</a></td>
<td></td>
- <td><p>MCP delegation provenance. Present exactly when the audited call arrived
-through the MCP server&#39;s delegated credential; never set for public API
-calls. Presence of this message is the MCP-origin marker. </p></td>
+ <td><p>MCP delegation provenance. Present exactly when the entry belongs to MCP:
+the audited call arrived through the MCP server&#39;s delegated credential, or
+it is one of the two MCP doors that sit outside the API — the /mcp
+connection gate and the OAuth2 consent that mints the credential it checks.
+Never set for public API calls. Presence of this message is the MCP-origin
+marker. </p></td>
</tr>
</tbody>
@@ -2982,7 +2985,13 @@ Empty for legacy web-session tokens at /mcp. </p></td>
<td><p>Correlates the audit rows an MCP session produces. Minted at the /mcp
boundary and session-scoped: the MCP SDK hands tool handlers the
initialize-time context, so one MCP session carries one correlation ID
-across all of its tool calls. </p></td>
+across all of its tool calls.
+
+Empty on the entries that belong to no session — a refused consent, which
+never reached that boundary, and a refused connection, which is decided
+before the SDK resolves a session. Filling those with a fresh value would
+read as a session ID that correlates exactly one row, and a mid-session
+refusal would get an ID different from the rows the session already wrote. </p></td>
</tr>
</tbody>
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index bb1d3c1c2e..32c7b1fece 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -778,15 +778,23 @@
- [v1/workspace_service.proto](#v1_workspace_service-proto)
- [DeleteWorkspaceRequest](#bytebase-v1-DeleteWorkspaceRequest)
+ - [GetMCPInfoRequest](#bytebase-v1-GetMCPInfoRequest)
- [GetWorkspaceRequest](#bytebase-v1-GetWorkspaceRequest)
- [LeaveWorkspaceRequest](#bytebase-v1-LeaveWorkspaceRequest)
- [ListWorkspacesRequest](#bytebase-v1-ListWorkspacesRequest)
- [ListWorkspacesResponse](#bytebase-v1-ListWorkspacesResponse)
+ - [MCPCapabilityMode](#bytebase-v1-MCPCapabilityMode)
+ - [MCPEngineEnforcement](#bytebase-v1-MCPEngineEnforcement)
+ - [MCPInfo](#bytebase-v1-MCPInfo)
+ - [MCPMethod](#bytebase-v1-MCPMethod)
- [RotateDirectorySyncTokenRequest](#bytebase-v1-RotateDirectorySyncTokenRequest)
- [RotateDirectorySyncTokenResponse](#bytebase-v1-RotateDirectorySyncTokenResponse)
- [UpdateWorkspaceRequest](#bytebase-v1-UpdateWorkspaceRequest)
- [Workspace](#bytebase-v1-Workspace)
+ - [MCPEngineEnforcement.Masking](#bytebase-v1-MCPEngineEnforcement-Masking)
+ - [MCPEngineEnforcement.ReadOnlyDepth](#bytebase-v1-MCPEngineEnforcement-ReadOnlyDepth)
+
- [WorkspaceService](#bytebase-v1-WorkspaceService)
- [Scalar Value Types](#scalar-value-types)
@@ -1907,9 +1915,9 @@ Request message for searching audit logs.
| parent | [string](#string) | | |
| filter | [string](#string) | | The filter of the log. It should be a valid CEL expression. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
-Supported filter: - method: the API name, can be found in the docs, should start with &#34;/bytebase.v1.&#34; prefix. For example &#34;/bytebase.v1.UserService/CreateUser&#34;. Support &#34;==&#34; operator. - severity: support &#34;==&#34; operator, check Severity enum in AuditLog message for values. - user: the actor, should in &#34;users/{email}&#34; format, support &#34;==&#34; operator. - create_time: support &#34;&gt;=&#34; and &#34;&lt;=&#34; operator.
+Supported filter: - method: the API name, can be found in the docs. Usually &#34;/bytebase.v1.…&#34;, for example &#34;/bytebase.v1.UserService/CreateUser&#34;; entries written outside the v1 API carry their own prefix, such as &#34;/bytebase.mcp.Session/Authorize&#34; or &#34;/bytebase.cli.Recovery/ResetUserPassword&#34;. Support &#34;==&#34; operator. - resource: the resource the entry is about, support &#34;==&#34; operator. - severity: support &#34;==&#34; operator, check Severity enum in AuditLog message for values. - user: the actor, should in &#34;users/{email}&#34; format, support &#34;==&#34; operator. - create_time: support &#34;&gt;=&#34; and &#34;&lt;=&#34; operator. - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support &#34;==&#34; operator. - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry&#39;s mcp_delegation.correlation_id. Support &#34;==&#34; operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
-For example: - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; user == &#39;users/[email protected]&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; create_time &lt;= &#39;2021-01-01T00:00:00Z&#39; &amp;&amp; create_time &gt;= &#39;2020-01-01T00:00:00Z&#39;&#34; |
+For example: - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; user == &#39;users/[email protected]&#39;&#34; - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; create_time &lt;= &#39;2021-01-01T00:00:00Z&#39; &amp;&amp; create_time &gt;= &#39;2020-01-01T00:00:00Z&#39;&#34; - filter = &#34;mcp == true&#34; - filter = &#34;mcp_correlation_id == &#39;0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60&#39;&#34; |
| order_by | [string](#string) | | The order by of the log. Only support order by create_time. The default sorting order is ascending. For example: - order_by = &#34;create_time asc&#34; - order_by = &#34;create_time desc&#34; |
| page_size | [int32](#int32) | | The maximum number of logs to return. The service may return fewer than this value. If unspecified, at most 10 log entries will be returned. The maximum value is 5000; values above 5000 will be coerced to 5000. |
| page_token | [string](#string) | | A page token, received from a previous `SearchLogs` call. Provide this to retrieve the subsequent page. |
@@ -12552,6 +12560,16 @@ WorkloadIdentityService manages workload identities for external CI/CD integrati
+<a name="bytebase-v1-GetMCPInfoRequest"></a>
+
+### GetMCPInfoRequest
+
+
+
+
+
+
+
<a name="bytebase-v1-GetWorkspaceRequest"></a>
### GetWorkspaceRequest
@@ -12607,6 +12625,91 @@ WorkloadIdentityService manages workload identities for external CI/CD integrati
+<a name="bytebase-v1-MCPCapabilityMode"></a>
+
+### MCPCapabilityMode
+MCPCapabilityMode is one ceiling and the method classes it serves.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| capability | [MCPSetting.Capability](#bytebase-v1-MCPSetting-Capability) | | |
+| served_classes | [MCPMethodClass](#bytebase-v1-MCPMethodClass) | repeated | Empty means the ceiling serves nothing, which is what DISABLED is. |
+
+
+
+
+
+
+<a name="bytebase-v1-MCPEngineEnforcement"></a>
+
+### MCPEngineEnforcement
+MCPEngineEnforcement is what the read-only ceiling and the masking toggle
+reach on one database engine.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| engine | [Engine](#bytebase-v1-Engine) | | |
+| read_only_depth | [MCPEngineEnforcement.ReadOnlyDepth](#bytebase-v1-MCPEngineEnforcement-ReadOnlyDepth) | | |
+| masking | [MCPEngineEnforcement.Masking](#bytebase-v1-MCPEngineEnforcement-Masking) | | |
+| note | [string](#string) | | Where the answers above are the floor rather than the whole story. Empty for most engines. |
+
+
+
+
+
+
+<a name="bytebase-v1-MCPInfo"></a>
+
+### MCPInfo
+MCPInfo is what MCP does in this workspace: the ceiling in force, what each
+ceiling serves, and the per-engine facts a read-only session depends on.
+
+Everything here is resolved when the request is served, never from a stored
+copy: the method list comes off the compiled API descriptors and the engine
+answers off the code that enforces them, so a build whose rules changed
+cannot describe the rules of the build before it.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| workspace | [string](#string) | | The workspace this describes. Format: workspaces/{workspace}. Not this message&#39;s own resource name — MCPInfo is not a named resource and there is nothing to get it by. |
+| capability | [MCPSetting.Capability](#bytebase-v1-MCPSetting-Capability) | | The ceiling in force for this workspace. A workspace that never configured MCP resolves to READ_WRITE. |
+| modes | [MCPCapabilityMode](#bytebase-v1-MCPCapabilityMode) | repeated | What each ceiling serves, including the one in force, so an admin can compare the choices rather than only read the current answer. |
+| methods | [MCPMethod](#bytebase-v1-MCPMethod) | repeated | Every API method some ceiling serves. A mode serves a method when the method&#39;s class is one of that mode&#39;s served_classes, which is the ceiling rule the gate evaluates. Methods no ceiling serves are absent.
+
+Being listed is necessary, not sufficient. The caller still needs the permission, and two further rules narrow what a served method does: a handful of methods are refused on the shape of the request (an issue that would grant a permission, a rollout that skips approval), and under READ_ONLY every statement SQLService/Query runs must classify as a read. |
+| engines | [MCPEngineEnforcement](#bytebase-v1-MCPEngineEnforcement) | repeated | What a read-only session and the masking toggle actually reach, per engine. Both are engine-conditional in ways the ceiling alone does not show. |
+| ignore_masking_exemptions | [bool](#bool) | | Whether this workspace stops applying the caller&#39;s own unmasking provisioning to MCP requests. It decides which branch of each engine&#39;s masking state a caller is in, and no other API tells an MCP session: SettingService/GetSetting is served by no ceiling. |
+| data_masking_available | [bool](#bool) | | Whether data masking is licensed for this workspace. When false nothing is masked whatever an engine supports, so the masking states below describe a mechanism that does not run. Licensing can also be set per instance, so a true here is the workspace answer, not a promise about every instance. |
+
+
+
+
+
+
+<a name="bytebase-v1-MCPMethod"></a>
+
+### MCPMethod
+MCPMethod is one API method an MCP session can reach, and what decides it.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| method | [string](#string) | | The method as an audit entry names it, so a denial can be found by it. Example: /bytebase.v1.SQLService/Query |
+| operation_id | [string](#string) | | The same method as call_api takes it. Example: bytebase.v1.SQLService.Query |
+| class | [MCPMethodClass](#bytebase-v1-MCPMethodClass) | | |
+| permission | [string](#string) | | The IAM permission the method declares. The ceiling never grants: a session may call a served method only where the person it acts for could.
+
+Empty means the method declares no permission, which is NOT the same as needing none — a method that authorizes inside its handler declares nothing here. auth_method says which case an empty value is. |
+| auth_method | [AuthMethod](#bytebase-v1-AuthMethod) | | How the method authorizes. IAM means the permission above is the primary rule, though not always the only one — an update carrying allow_missing additionally requires the matching create permission. CUSTOM means the handler decides and the permission field is silent. |
+
+
+
+
+
+
<a name="bytebase-v1-RotateDirectorySyncTokenRequest"></a>
### RotateDirectorySyncTokenRequest
@@ -12671,6 +12774,35 @@ WorkloadIdentityService manages workload identities for external CI/CD integrati
+
+<a name="bytebase-v1-MCPEngineEnforcement-Masking"></a>
+
+### MCPEngineEnforcement.Masking
+How Bytebase masks results on this engine, which is what decides whether
+ignoring masking exemptions changes anything here.
+
+| Name | Number | Description |
+| ---- | ------ | ----------- |
+| MASKING_UNSPECIFIED | 0 | |
+| NONE | 1 | Bytebase does not mask on this engine. Nothing narrows what a session reads, and ignoring masking exemptions does nothing. |
+| COLUMN | 2 | Column masking. A masking policy substitutes values in query results, and the exemptions granted to the caller are what let them see the real value — which is what ignoring exemptions suppresses. |
+| DOCUMENT | 3 | Document masking. Results are masked, but exemptions are never consulted on this path, so ignoring them changes nothing here either. |
+
+
+
+<a name="bytebase-v1-MCPEngineEnforcement-ReadOnlyDepth"></a>
+
+### MCPEngineEnforcement.ReadOnlyDepth
+How much of a read-only ceiling this engine can be held to.
+
+| Name | Number | Description |
+| ---- | ------ | ----------- |
+| READ_ONLY_DEPTH_UNSPECIFIED | 0 | |
+| UNSUPPORTED | 1 | Bytebase has no read-only classifier for this engine, so a read-only session is refused every statement on it, including a plain SELECT. |
+| STATEMENT | 2 | Every statement is classified before it runs and a request holding one that is not a read is refused whole. Nothing below that: the driver does not open a read-only database session, except where the note says otherwise. |
+| STATEMENT_AND_SESSION | 3 | Statement classification, and the driver opens the database session read-only as well, so the engine refuses most writes the classifier missed. Not a proof: a statement that classifies as a read can still call a function that switches the session setting back off. |
+
+
@@ -12690,6 +12822,11 @@ WorkspaceService manages workspace-level operations and profile.
| DeleteWorkspace | [DeleteWorkspaceRequest](#bytebase-v1-DeleteWorkspaceRequest) | [LoginResponse](#bytebase-v1-LoginResponse) | Deletes a workspace. SaaS only. Cancels any active subscription and soft-deletes the workspace so all associated data becomes inaccessible. Requires workspace admin permission. |
| LeaveWorkspace | [LeaveWorkspaceRequest](#bytebase-v1-LeaveWorkspaceRequest) | [LoginResponse](#bytebase-v1-LoginResponse) | Removes the calling user from a workspace and switches to the next available workspace. Available to any workspace member. Fails if the caller is the last workspace admin. |
| SetIamPolicy | [SetIamPolicyRequest](#bytebase-v1-SetIamPolicyRequest) | [IamPolicy](#bytebase-v1-IamPolicy) | Sets IAM policy for the workspace. Permissions required: bb.workspaces.setIamPolicy |
+| GetMCPInfo | [GetMCPInfoRequest](#bytebase-v1-GetMCPInfoRequest) | [MCPInfo](#bytebase-v1-MCPInfo) | Gets what MCP (Model Context Protocol) does in this workspace: the capability ceiling in force, what each ceiling serves, and the per-engine facts a read-only session depends on. The workspace is resolved from the authenticated session.
+
+Served to MCP sessions. An agent asking what it may do here is the point: the response says nothing a session&#39;s own denials do not already say, one refusal at a time, and knowing it up front is what stops the agent planning work the ceiling was never going to serve.
+
+Permissions required: None (authentication required) |
| RotateDirectorySyncToken | [RotateDirectorySyncTokenRequest](#bytebase-v1-RotateDirectorySyncTokenRequest) | [RotateDirectorySyncTokenResponse](#bytebase-v1-RotateDirectorySyncTokenResponse) | Mints a new directory sync (SCIM) token, immediately invalidating the previous one. The plaintext token is returned exactly once and cannot be retrieved afterwards; only its hash is stored. Callers that lose it must rotate again and update their identity provider. Permissions required: bb.workspaces.rotateDirectorySyncToken |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index b000df4310..e82482d72c 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -3139,6 +3139,10 @@
<a href="#bytebase.v1.DeleteWorkspaceRequest"><span class="badge">M</span>DeleteWorkspaceRequest</a>
</li>
+ <li>
+ <a href="#bytebase.v1.GetMCPInfoRequest"><span class="badge">M</span>GetMCPInfoRequest</a>
+ </li>
+
<li>
<a href="#bytebase.v1.GetWorkspaceRequest"><span class="badge">M</span>GetWorkspaceRequest</a>
</li>
@@ -3155,6 +3159,22 @@
<a href="#bytebase.v1.ListWorkspacesResponse"><span class="badge">M</span>ListWorkspacesResponse</a>
</li>
+ <li>
+ <a href="#bytebase.v1.MCPCapabilityMode"><span class="badge">M</span>MCPCapabilityMode</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.v1.MCPEngineEnforcement"><span class="badge">M</span>MCPEngineEnforcement</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.v1.MCPInfo"><span class="badge">M</span>MCPInfo</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.v1.MCPMethod"><span class="badge">M</span>MCPMethod</a>
+ </li>
+
<li>
<a href="#bytebase.v1.RotateDirectorySyncTokenRequest"><span class="badge">M</span>RotateDirectorySyncTokenRequest</a>
</li>
@@ -3172,6 +3192,14 @@
</li>
+ <li>
+ <a href="#bytebase.v1.MCPEngineEnforcement.Masking"><span class="badge">E</span>MCPEngineEnforcement.Masking</a>
+ </li>
+
+ <li>
+ <a href="#bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth"><span class="badge">E</span>MCPEngineEnforcement.ReadOnlyDepth</a>
+ </li>
+
<li>
@@ -6217,16 +6245,21 @@ This is supplied by the client and is not authenticated. </p></td>
The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
Supported filter:
-- method: the API name, can be found in the docs, should start with &#34;/bytebase.v1.&#34; prefix. For example &#34;/bytebase.v1.UserService/CreateUser&#34;. Support &#34;==&#34; operator.
+- method: the API name, can be found in the docs. Usually &#34;/bytebase.v1.…&#34;, for example &#34;/bytebase.v1.UserService/CreateUser&#34;; entries written outside the v1 API carry their own prefix, such as &#34;/bytebase.mcp.Session/Authorize&#34; or &#34;/bytebase.cli.Recovery/ResetUserPassword&#34;. Support &#34;==&#34; operator.
+- resource: the resource the entry is about, support &#34;==&#34; operator.
- severity: support &#34;==&#34; operator, check Severity enum in AuditLog message for values.
- user: the actor, should in &#34;users/{email}&#34; format, support &#34;==&#34; operator.
- create_time: support &#34;&gt;=&#34; and &#34;&lt;=&#34; operator.
+- mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support &#34;==&#34; operator.
+- mcp_correlation_id: the MCP session an entry belongs to, taken from an entry&#39;s mcp_delegation.correlation_id. Support &#34;==&#34; operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
For example:
- filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39;&#34;
- filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39;&#34;
- filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; user == &#39;users/[email protected]&#39;&#34;
- - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; create_time &lt;= &#39;2021-01-01T00:00:00Z&#39; &amp;&amp; create_time &gt;= &#39;2020-01-01T00:00:00Z&#39;&#34; </p></td>
+ - filter = &#34;method == &#39;/bytebase.v1.SQLService/Query&#39; &amp;&amp; severity == &#39;ERROR&#39; &amp;&amp; create_time &lt;= &#39;2021-01-01T00:00:00Z&#39; &amp;&amp; create_time &gt;= &#39;2020-01-01T00:00:00Z&#39;&#34;
+ - filter = &#34;mcp == true&#34;
+ - filter = &#34;mcp_correlation_id == &#39;0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60&#39;&#34; </p></td>
</tr>
<tr>
@@ -35699,6 +35732,13 @@ Permissions required: bb.workloadIdentities.undelete</p></td>
+ <h3 id="bytebase.v1.GetMCPInfoRequest">GetMCPInfoRequest</h3>
+ <p></p>
+
+
+
+
+
<h3 id="bytebase.v1.GetWorkspaceRequest">GetWorkspaceRequest</h3>
<p></p>
@@ -35779,6 +35819,230 @@ Use &#34;workspaces/-&#34; to get the current/default workspace. </p></td>
+ <h3 id="bytebase.v1.MCPCapabilityMode">MCPCapabilityMode</h3>
+ <p>MCPCapabilityMode is one ceiling and the method classes it serves.</p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>capability</td>
+ <td><a href="#bytebase.v1.MCPSetting.Capability">MCPSetting.Capability</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>served_classes</td>
+ <td><a href="#bytebase.v1.MCPMethodClass">MCPMethodClass</a></td>
+ <td>repeated</td>
+ <td><p>Empty means the ceiling serves nothing, which is what DISABLED is. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
+ <h3 id="bytebase.v1.MCPEngineEnforcement">MCPEngineEnforcement</h3>
+ <p>MCPEngineEnforcement is what the read-only ceiling and the masking toggle</p><p>reach on one database engine.</p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>engine</td>
+ <td><a href="#bytebase.v1.Engine">Engine</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>read_only_depth</td>
+ <td><a href="#bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth">MCPEngineEnforcement.ReadOnlyDepth</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>masking</td>
+ <td><a href="#bytebase.v1.MCPEngineEnforcement.Masking">MCPEngineEnforcement.Masking</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>note</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>Where the answers above are the floor rather than the whole story. Empty
+for most engines. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
+ <h3 id="bytebase.v1.MCPInfo">MCPInfo</h3>
+ <p>MCPInfo is what MCP does in this workspace: the ceiling in force, what each</p><p>ceiling serves, and the per-engine facts a read-only session depends on.</p><p>Everything here is resolved when the request is served, never from a stored</p><p>copy: the method list comes off the compiled API descriptors and the engine</p><p>answers off the code that enforces them, so a build whose rules changed</p><p>cannot describe the rules of the build before it.</p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>workspace</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The workspace this describes. Format: workspaces/{workspace}. Not this
+message&#39;s own resource name — MCPInfo is not a named resource and there is
+nothing to get it by. </p></td>
+ </tr>
+
+ <tr>
+ <td>capability</td>
+ <td><a href="#bytebase.v1.MCPSetting.Capability">MCPSetting.Capability</a></td>
+ <td></td>
+ <td><p>The ceiling in force for this workspace. A workspace that never configured
+MCP resolves to READ_WRITE. </p></td>
+ </tr>
+
+ <tr>
+ <td>modes</td>
+ <td><a href="#bytebase.v1.MCPCapabilityMode">MCPCapabilityMode</a></td>
+ <td>repeated</td>
+ <td><p>What each ceiling serves, including the one in force, so an admin can
+compare the choices rather than only read the current answer. </p></td>
+ </tr>
+
+ <tr>
+ <td>methods</td>
+ <td><a href="#bytebase.v1.MCPMethod">MCPMethod</a></td>
+ <td>repeated</td>
+ <td><p>Every API method some ceiling serves. A mode serves a method when the
+method&#39;s class is one of that mode&#39;s served_classes, which is the ceiling
+rule the gate evaluates. Methods no ceiling serves are absent.
+
+Being listed is necessary, not sufficient. The caller still needs the
+permission, and two further rules narrow what a served method does: a
+handful of methods are refused on the shape of the request (an issue that
+would grant a permission, a rollout that skips approval), and under
+READ_ONLY every statement SQLService/Query runs must classify as a read. </p></td>
+ </tr>
+
+ <tr>
+ <td>engines</td>
+ <td><a href="#bytebase.v1.MCPEngineEnforcement">MCPEngineEnforcement</a></td>
+ <td>repeated</td>
+ <td><p>What a read-only session and the masking toggle actually reach, per engine.
+Both are engine-conditional in ways the ceiling alone does not show. </p></td>
+ </tr>
+
+ <tr>
+ <td>ignore_masking_exemptions</td>
+ <td><a href="#bool">bool</a></td>
+ <td></td>
+ <td><p>Whether this workspace stops applying the caller&#39;s own unmasking
+provisioning to MCP requests. It decides which branch of each engine&#39;s
+masking state a caller is in, and no other API tells an MCP session:
+SettingService/GetSetting is served by no ceiling. </p></td>
+ </tr>
+
+ <tr>
+ <td>data_masking_available</td>
+ <td><a href="#bool">bool</a></td>
+ <td></td>
+ <td><p>Whether data masking is licensed for this workspace. When false nothing is
+masked whatever an engine supports, so the masking states below describe a
+mechanism that does not run. Licensing can also be set per instance, so a
+true here is the workspace answer, not a promise about every instance. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
+ <h3 id="bytebase.v1.MCPMethod">MCPMethod</h3>
+ <p>MCPMethod is one API method an MCP session can reach, and what decides it.</p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>method</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The method as an audit entry names it, so a denial can be found by it.
+Example: /bytebase.v1.SQLService/Query </p></td>
+ </tr>
+
+ <tr>
+ <td>operation_id</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The same method as call_api takes it.
+Example: bytebase.v1.SQLService.Query </p></td>
+ </tr>
+
+ <tr>
+ <td>class</td>
+ <td><a href="#bytebase.v1.MCPMethodClass">MCPMethodClass</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ <tr>
+ <td>permission</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The IAM permission the method declares. The ceiling never grants: a session
+may call a served method only where the person it acts for could.
+
+Empty means the method declares no permission, which is NOT the same as
+needing none — a method that authorizes inside its handler declares nothing
+here. auth_method says which case an empty value is. </p></td>
+ </tr>
+
+ <tr>
+ <td>auth_method</td>
+ <td><a href="#bytebase.v1.AuthMethod">AuthMethod</a></td>
+ <td></td>
+ <td><p>How the method authorizes. IAM means the permission above is the primary
+rule, though not always the only one — an update carrying allow_missing
+additionally requires the matching create permission. CUSTOM means the
+handler decides and the permission field is silent. </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
<h3 id="bytebase.v1.RotateDirectorySyncTokenRequest">RotateDirectorySyncTokenRequest</h3>
<p></p>
@@ -35899,6 +36163,87 @@ Format: workspaces/{workspace} </p></td>
+ <h3 id="bytebase.v1.MCPEngineEnforcement.Masking">MCPEngineEnforcement.Masking</h3>
+ <p>How Bytebase masks results on this engine, which is what decides whether</p><p>ignoring masking exemptions changes anything here.</p>
+ <table class="enum-table">
+ <thead>
+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>MASKING_UNSPECIFIED</td>
+ <td>0</td>
+ <td><p></p></td>
+ </tr>
+
+ <tr>
+ <td>NONE</td>
+ <td>1</td>
+ <td><p>Bytebase does not mask on this engine. Nothing narrows what a session
+reads, and ignoring masking exemptions does nothing.</p></td>
+ </tr>
+
+ <tr>
+ <td>COLUMN</td>
+ <td>2</td>
+ <td><p>Column masking. A masking policy substitutes values in query results,
+and the exemptions granted to the caller are what let them see the real
+value — which is what ignoring exemptions suppresses.</p></td>
+ </tr>
+
+ <tr>
+ <td>DOCUMENT</td>
+ <td>3</td>
+ <td><p>Document masking. Results are masked, but exemptions are never consulted
+on this path, so ignoring them changes nothing here either.</p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+ <h3 id="bytebase.v1.MCPEngineEnforcement.ReadOnlyDepth">MCPEngineEnforcement.ReadOnlyDepth</h3>
+ <p>How much of a read-only ceiling this engine can be held to.</p>
+ <table class="enum-table">
+ <thead>
+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>READ_ONLY_DEPTH_UNSPECIFIED</td>
+ <td>0</td>
+ <td><p></p></td>
+ </tr>
+
+ <tr>
+ <td>UNSUPPORTED</td>
+ <td>1</td>
+ <td><p>Bytebase has no read-only classifier for this engine, so a read-only
+session is refused every statement on it, including a plain SELECT.</p></td>
+ </tr>
+
+ <tr>
+ <td>STATEMENT</td>
+ <td>2</td>
+ <td><p>Every statement is classified before it runs and a request holding one
+that is not a read is refused whole. Nothing below that: the driver does
+not open a read-only database session, except where the note says
+otherwise.</p></td>
+ </tr>
+
+ <tr>
+ <td>STATEMENT_AND_SESSION</td>
+ <td>3</td>
+ <td><p>Statement classification, and the driver opens the database session
+read-only as well, so the engine refuses most writes the classifier
+missed. Not a proof: a statement that classifies as a read can still call
+a function that switches the session setting back off.</p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
@@ -35970,6 +36315,23 @@ caller is the last workspace admin.</p></td>
Permissions required: bb.workspaces.setIamPolicy</p></td>
</tr>
+ <tr>
+ <td>GetMCPInfo</td>
+ <td><a href="#bytebase.v1.GetMCPInfoRequest">GetMCPInfoRequest</a></td>
+ <td><a href="#bytebase.v1.MCPInfo">MCPInfo</a></td>
+ <td><p>Gets what MCP (Model Context Protocol) does in this workspace: the
+capability ceiling in force, what each ceiling serves, and the per-engine
+facts a read-only session depends on. The workspace is resolved from the
+authenticated session.
+
+Served to MCP sessions. An agent asking what it may do here is the point:
+the response says nothing a session&#39;s own denials do not already say, one
+refusal at a time, and knowing it up front is what stops the agent
+planning work the ceiling was never going to serve.
+
+Permissions required: None (authentication required)</p></td>
+ </tr>
+
<tr>
<td>RotateDirectorySyncToken</td>
<td><a href="#bytebase.v1.RotateDirectorySyncTokenRequest">RotateDirectorySyncTokenRequest</a></td>
@@ -36071,6 +36433,16 @@ Permissions required: bb.workspaces.rotateDirectorySyncToken</p></td>
+ <tr>
+ <td>GetMCPInfo</td>
+ <td>GET</td>
+ <td>/v1/mcp/info</td>
+ <td></td>
+ </tr>
+
+
+
+
<tr>
<td>RotateDirectorySyncToken</td>
<td>POST</td>
diff --git a/proto/store/store/audit_log.proto b/proto/store/store/audit_log.proto
index 15316a6519..2a1da37311 100644
--- a/proto/store/store/audit_log.proto
+++ b/proto/store/store/audit_log.proto
@@ -45,9 +45,12 @@ message AuditLog {
// Metadata about the operation.
RequestMetadata request_metadata = 11;
- // MCP delegation provenance. Present exactly when the audited call arrived
- // through the MCP server's delegated credential; never set for public API
- // calls. Presence of this message is the MCP-origin marker.
+ // MCP delegation provenance. Present exactly when the entry belongs to MCP:
+ // the audited call arrived through the MCP server's delegated credential, or
+ // it is one of the two MCP doors that sit outside the API — the /mcp
+ // connection gate and the OAuth2 consent that mints the credential it checks.
+ // Never set for public API calls. Presence of this message is the MCP-origin
+ // marker.
MCPDelegation mcp_delegation = 12;
enum Severity {
@@ -94,5 +97,11 @@ message MCPDelegation {
// boundary and session-scoped: the MCP SDK hands tool handlers the
// initialize-time context, so one MCP session carries one correlation ID
// across all of its tool calls.
+ //
+ // Empty on the entries that belong to no session — a refused consent, which
+ // never reached that boundary, and a refused connection, which is decided
+ // before the SDK resolves a session. Filling those with a fresh value would
+ // read as a session ID that correlates exactly one row, and a mid-session
+ // refusal would get an ID different from the rows the session already wrote.
string correlation_id = 4;
}
diff --git a/proto/v1/v1/audit_log_service.proto b/proto/v1/v1/audit_log_service.proto
index 28d6609fe3..7bf1926171 100644
--- a/proto/v1/v1/audit_log_service.proto
+++ b/proto/v1/v1/audit_log_service.proto
@@ -64,16 +64,21 @@ message SearchAuditLogsRequest {
// The syntax and semantics of CEL are documented at https://github.com/google/cel-spec
//
// Supported filter:
- // - method: the API name, can be found in the docs, should start with "/bytebase.v1." prefix. For example "/bytebase.v1.UserService/CreateUser". Support "==" operator.
+ // - method: the API name, can be found in the docs. Usually "/bytebase.v1.…", for example "/bytebase.v1.UserService/CreateUser"; entries written outside the v1 API carry their own prefix, such as "/bytebase.mcp.Session/Authorize" or "/bytebase.cli.Recovery/ResetUserPassword". Support "==" operator.
+ // - resource: the resource the entry is about, support "==" operator.
// - severity: support "==" operator, check Severity enum in AuditLog message for values.
// - user: the actor, should in "users/{email}" format, support "==" operator.
// - create_time: support ">=" and "<=" operator.
+ // - mcp: true selects the entries MCP produced, false the rest. A boolean, not a string. Support "==" operator.
+ // - mcp_correlation_id: the MCP session an entry belongs to, taken from an entry's mcp_delegation.correlation_id. Support "==" operator. Entries MCP produced outside a session — a refused connection or consent — carry none and match no value here.
//
// For example:
// - filter = "method == '/bytebase.v1.SQLService/Query'"
// - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR'"
// - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && user == 'users/[email protected]'"
// - filter = "method == '/bytebase.v1.SQLService/Query' && severity == 'ERROR' && create_time <= '2021-01-01T00:00:00Z' && create_time >= '2020-01-01T00:00:00Z'"
+ // - filter = "mcp == true"
+ // - filter = "mcp_correlation_id == '0b7f1a3c-1d2e-4f56-8a90-1b2c3d4e5f60'"
string filter = 1;
// The order by of the log.
diff --git a/proto/v1/v1/workspace_service.proto b/proto/v1/v1/workspace_service.proto
index b64543d790..a4d69c102c 100644
--- a/proto/v1/v1/workspace_service.proto
+++ b/proto/v1/v1/workspace_service.proto
@@ -9,7 +9,9 @@ import "google/api/resource.proto";
import "google/protobuf/field_mask.proto";
import "v1/annotation.proto";
import "v1/auth_service.proto";
+import "v1/common.proto";
import "v1/iam_policy.proto";
+import "v1/setting_service.proto";
option go_package = "github.com/bytebase/bytebase/backend/generated-go/v1";
@@ -96,6 +98,23 @@ service WorkspaceService {
option (bytebase.v1.mcp_denial_reason) = ADMINISTERS_THE_WORKSPACE;
}
+ // Gets what MCP (Model Context Protocol) does in this workspace: the
+ // capability ceiling in force, what each ceiling serves, and the per-engine
+ // facts a read-only session depends on. The workspace is resolved from the
+ // authenticated session.
+ //
+ // Served to MCP sessions. An agent asking what it may do here is the point:
+ // the response says nothing a session's own denials do not already say, one
+ // refusal at a time, and knowing it up front is what stops the agent
+ // planning work the ceiling was never going to serve.
+ //
+ // Permissions required: None (authentication required)
+ rpc GetMCPInfo(GetMCPInfoRequest) returns (MCPInfo) {
+ option (google.api.http) = {get: "/v1/mcp/info"};
+ option (google.api.method_signature) = "";
+ option (bytebase.v1.mcp_method_class) = READ;
+ }
+
// Mints a new directory sync (SCIM) token, immediately invalidating the
// previous one. The plaintext token is returned exactly once and cannot be
// retrieved afterwards; only its hash is stored. Callers that lose it must
@@ -115,6 +134,146 @@ service WorkspaceService {
}
}
+message GetMCPInfoRequest {}
+
+// MCPInfo is what MCP does in this workspace: the ceiling in force, what each
+// ceiling serves, and the per-engine facts a read-only session depends on.
+//
+// Everything here is resolved when the request is served, never from a stored
+// copy: the method list comes off the compiled API descriptors and the engine
+// answers off the code that enforces them, so a build whose rules changed
+// cannot describe the rules of the build before it.
+message MCPInfo {
+ // The workspace this describes. Format: workspaces/{workspace}. Not this
+ // message's own resource name — MCPInfo is not a named resource and there is
+ // nothing to get it by.
+ string workspace = 1 [(google.api.field_behavior) = OUTPUT_ONLY];
+
+ // The ceiling in force for this workspace. A workspace that never configured
+ // MCP resolves to READ_WRITE.
+ MCPSetting.Capability capability = 2 [(google.api.field_behavior) = OUTPUT_ONLY];
+
+ // What each ceiling serves, including the one in force, so an admin can
+ // compare the choices rather than only read the current answer.
+ repeated MCPCapabilityMode modes = 3 [(google.api.field_behavior) = OUTPUT_ONLY];
+
+ // Every API method some ceiling serves. A mode serves a method when the
+ // method's class is one of that mode's served_classes, which is the ceiling
+ // rule the gate evaluates. Methods no ceiling serves are absent.
+ //
+ // Being listed is necessary, not sufficient. The caller still needs the
+ // permission, and two further rules narrow what a served method does: a
+ // handful of methods are refused on the shape of the request (an issue that
+ // would grant a permission, a rollout that skips approval), and under
+ // READ_ONLY every statement SQLService/Query runs must classify as a read.
+ repeated MCPMethod methods = 4 [(google.api.field_behavior) = OUTPUT_ONLY];
+
+ // What a read-only session and the masking toggle actually reach, per engine.
+ // Both are engine-conditional in ways the ceiling alone does not show.
+ repeated MCPEngineEnforcement engines = 5 [(google.api.field_behavior) = OUTPUT_ONLY];
+
+ // Whether this workspace stops applying the caller's own unmasking
+ // provisioning to MCP requests. It decides which branch of each engine's
+ // masking state a caller is in, and no other API tells an MCP session:
+ // SettingService/GetSetting is served by no ceiling.
+ bool ignore_masking_exemptions = 6 [(google.api.field_behavior) = OUTPUT_ONLY];
+
+ // Whether data masking is licensed for this workspace. When false nothing is
+ // masked whatever an engine supports, so the masking states below describe a
+ // mechanism that does not run. Licensing can also be set per instance, so a
+ // true here is the workspace answer, not a promise about every instance.
+ bool data_masking_available = 7 [(google.api.field_behavior) = OUTPUT_ONLY];
+}
+
+// MCPCapabilityMode is one ceiling and the method classes it serves.
+message MCPCapabilityMode {
+ MCPSetting.Capability capability = 1;
+
+ // Empty means the ceiling serves nothing, which is what DISABLED is.
+ repeated MCPMethodClass served_classes = 2;
+}
+
+// MCPMethod is one API method an MCP session can reach, and what decides it.
+message MCPMethod {
+ // The method as an audit entry names it, so a denial can be found by it.
+ // Example: /bytebase.v1.SQLService/Query
+ string method = 1;
+
+ // The same method as call_api takes it.
+ // Example: bytebase.v1.SQLService.Query
+ string operation_id = 4;
+
+ MCPMethodClass class = 2;
+
+ // The IAM permission the method declares. The ceiling never grants: a session
+ // may call a served method only where the person it acts for could.
+ //
+ // Empty means the method declares no permission, which is NOT the same as
+ // needing none — a method that authorizes inside its handler declares nothing
+ // here. auth_method says which case an empty value is.
+ string permission = 3;
+
+ // How the method authorizes. IAM means the permission above is the primary
+ // rule, though not always the only one — an update carrying allow_missing
+ // additionally requires the matching create permission. CUSTOM means the
+ // handler decides and the permission field is silent.
+ AuthMethod auth_method = 5;
+}
+
+// MCPEngineEnforcement is what the read-only ceiling and the masking toggle
+// reach on one database engine.
+message MCPEngineEnforcement {
+ // How much of a read-only ceiling this engine can be held to.
+ enum ReadOnlyDepth {
+ READ_ONLY_DEPTH_UNSPECIFIED = 0;
+
+ // Bytebase has no read-only classifier for this engine, so a read-only
+ // session is refused every statement on it, including a plain SELECT.
+ UNSUPPORTED = 1;
+
+ // Every statement is classified before it runs and a request holding one
+ // that is not a read is refused whole. Nothing below that: the driver does
+ // not open a read-only database session, except where the note says
+ // otherwise.
+ STATEMENT = 2;
+
+ // Statement classification, and the driver opens the database session
+ // read-only as well, so the engine refuses most writes the classifier
+ // missed. Not a proof: a statement that classifies as a read can still call
+ // a function that switches the session setting back off.
+ STATEMENT_AND_SESSION = 3;
+ }
+
+ // How Bytebase masks results on this engine, which is what decides whether
+ // ignoring masking exemptions changes anything here.
+ enum Masking {
+ MASKING_UNSPECIFIED = 0;
+
+ // Bytebase does not mask on this engine. Nothing narrows what a session
+ // reads, and ignoring masking exemptions does nothing.
+ NONE = 1;
+
+ // Column masking. A masking policy substitutes values in query results,
+ // and the exemptions granted to the caller are what let them see the real
+ // value — which is what ignoring exemptions suppresses.
+ COLUMN = 2;
+
+ // Document masking. Results are masked, but exemptions are never consulted
+ // on this path, so ignoring them changes nothing here either.
+ DOCUMENT = 3;
+ }
+
+ Engine engine = 1;
+
+ ReadOnlyDepth read_only_depth = 2;
+
+ Masking masking = 3;
+
+ // Where the answers above are the floor rather than the whole story. Empty
+ // for most engines.
+ string note = 4;
+}
+
message RotateDirectorySyncTokenRequest {
// The workspace whose directory sync token is rotated.
// Format: workspaces/{workspace}