Skip to content

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

feat(mcp): correlated auditing for MCP-originated calls, ACL denials audited (P1a PR 5b) (#21125)

Vincent Huang25df63a6f7c6
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index be1fe8035d..e798973617 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -8794,6 +8794,13 @@ components:
title: request_metadata
description: Metadata about the request context.
$ref: '#/components/schemas/bytebase.v1.RequestMetadata'
+ mcpDelegation:
+ title: mcp_delegation
+ description: |-
+ 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.
+ $ref: '#/components/schemas/bytebase.v1.MCPDelegation'
title: AuditLog
additionalProperties: false
description: Audit log entry recording system activity or API call.
@@ -14887,6 +14894,42 @@ components:
title: LogoutRequest
additionalProperties: false
description: Request to logout current user session.
+ bytebase.v1.MCPDelegation:
+ type: object
+ properties:
+ scope:
+ type: string
+ title: scope
+ description: |-
+ The OAuth2 grant's consented scope, e.g. "mcp:read-only".
+ Empty when the grant recorded no scope.
+ resource:
+ type: string
+ title: resource
+ description: |-
+ The grant's stored MCP resource URI.
+ Empty for pre-grant legacy sessions.
+ clientId:
+ type: string
+ title: client_id
+ description: |-
+ The OAuth2 client the grant was consented to.
+ Empty for legacy web-session tokens at /mcp.
+ correlationId:
+ type: string
+ title: correlation_id
+ description: |-
+ 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.
+ title: MCPDelegation
+ additionalProperties: false
+ description: |-
+ Provenance of a call that reached the API through the MCP (Model Context
+ Protocol) server's delegated credential. The values are copied verbatim from
+ the verified credential's grant state; empty fields record that the grant
+ stored nothing (legacy sessions), never a resolved or synthesized value.
bytebase.v1.MaskingExemptionPolicy:
type: object
properties:
diff --git a/backend/api/v1/acl.go b/backend/api/v1/acl.go
index f7cff88428..e611ccbd61 100644
--- a/backend/api/v1/acl.go
+++ b/backend/api/v1/acl.go
@@ -3,6 +3,7 @@ package v1
import (
"context"
"regexp"
+ "slices"
"strings"
"connectrpc.com/connect"
@@ -145,15 +146,19 @@ func (in *ACLInterceptor) doACLCheck(ctx context.Context, request any, fullMetho
if err != nil {
return resourceResolutionConnectError(err)
}
- authContext.Resources = resources
- // Workspace isolation: verify all resources belong to the caller's workspace.
- // Project, instance, and database ownership is already validated in
- // populateRawResources via workspace-filtered store lookups. Here we validate
- // workspace resources.
+ // Workspace isolation: verify all resources belong to the caller's
+ // workspace BEFORE publishing them on the AuthContext. Project, instance,
+ // and database ownership is already validated in populateRawResources via
+ // workspace-filtered store lookups; here we validate workspace resources.
+ // Publishing only validated entries matters on the internal MCP chain,
+ // where the audit interceptor runs outside ACL and derives a denied row's
+ // parents from Resources — an entry that failed this check must never
+ // become an audit parent (the denial would be filed under the foreign
+ // workspace the request named, not under the caller).
// Runs after authentication so unauthenticated requests get 401 first,
// preventing resource existence probing.
- for _, resource := range authContext.Resources {
+ for _, resource := range resources {
switch resource.Type {
case common.ResourceTypeWorkspace:
if resource.ID != workspaceID {
@@ -162,6 +167,7 @@ func (in *ACLInterceptor) doACLCheck(ctx context.Context, request any, fullMetho
default:
}
}
+ authContext.Resources = resources
ok, extra, err := doIAMPermissionCheck(ctx, in.iamManager, fullMethod, user, authContext)
if err != nil {
@@ -236,12 +242,7 @@ func hasPath(fieldMask *fieldmaskpb.FieldMask, want string) bool {
if fieldMask == nil {
return false
}
- for _, path := range fieldMask.Paths {
- if path == want {
- return true
- }
- }
- return false
+ return slices.Contains(fieldMask.Paths, want)
}
func doIAMPermissionCheck(ctx context.Context, iamManager *iam.Manager, fullMethod string, user *store.UserMessage, authContext *common.AuthContext) (bool, []string, error) {
diff --git a/backend/api/v1/audit.go b/backend/api/v1/audit.go
index 222318c704..1b8ce37842 100644
--- a/backend/api/v1/audit.go
+++ b/backend/api/v1/audit.go
@@ -235,15 +235,27 @@ func (in *AuditInterceptor) createAuditLog(ctx context.Context, e *auditEntry) e
parent string
auditWorkspaceID string
}
+ // One row per DISTINCT parent: batch requests repeat the same resource
+ // once per item, and since ACL-denied internal-chain calls are audited
+ // too, an unprivileged caller reaches this fan-out — duplicates would let
+ // one denied batch call naming N items write N identical rows.
var parents []auditParent
+ seenParent := make(map[string]bool)
+ appendParent := func(ap auditParent) {
+ if seenParent[ap.parent] {
+ return
+ }
+ seenParent[ap.parent] = true
+ parents = append(parents, ap)
+ }
for _, authResource := range authContext.Resources {
switch authResource.Type {
case common.ResourceTypeProject:
- parents = append(parents, auditParent{
+ appendParent(auditParent{
parent: common.FormatProject(authResource.ID),
})
case common.ResourceTypeWorkspace:
- parents = append(parents, auditParent{
+ appendParent(auditParent{
parent: common.FormatWorkspace(authResource.ID),
auditWorkspaceID: authResource.ID,
})
@@ -301,6 +313,7 @@ func (in *AuditInterceptor) createAuditLog(ctx context.Context, e *auditEntry) e
Latency: durationpb.New(e.latency),
ServiceData: e.serviceData,
RequestMetadata: requestMetadata,
+ McpDelegation: mcpDelegationFromAuthContext(authContext),
}
// Resolve workspace for audit log.
workspaceIDForAudit := ap.auditWorkspaceID
@@ -324,6 +337,24 @@ func (in *AuditInterceptor) createAuditLog(ctx context.Context, e *auditEntry) e
return nil
}
+// mcpDelegationFromAuthContext copies the delegated MCP grant state onto the
+// audit row, verbatim: empty grant values (legacy sessions) are recorded
+// empty, never resolved to a synthetic label. A nil return — every
+// public-chain request — leaves the row without MCP fields; presence of the
+// message is the MCP-origin marker.
+func mcpDelegationFromAuthContext(authContext *common.AuthContext) *storepb.MCPDelegation {
+ g := authContext.DelegatedGrant
+ if g == nil {
+ return nil
+ }
+ return &storepb.MCPDelegation{
+ Scope: g.Scope,
+ Resource: g.Resource,
+ ClientId: g.ClientID,
+ CorrelationId: g.CorrelationID,
+ }
+}
+
// 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.
@@ -371,6 +402,8 @@ func logAuditToStdout(ctx context.Context, p *storepb.AuditLog) {
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 != "" {
@@ -394,6 +427,31 @@ func logAuditToStdout(ctx context.Context, p *storepb.AuditLog) {
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) string {
if request == nil || reflect.ValueOf(request).IsNil() {
return ""
diff --git a/backend/api/v1/audit_log_service.go b/backend/api/v1/audit_log_service.go
index c40f94f856..03ab41e0f6 100644
--- a/backend/api/v1/audit_log_service.go
+++ b/backend/api/v1/audit_log_service.go
@@ -164,17 +164,33 @@ func convertToAuditLogs(auditLogs []*store.AuditLog) []*v1pb.AuditLog {
func convertToAuditLog(l *store.AuditLog) *v1pb.AuditLog {
return &v1pb.AuditLog{
- Name: fmt.Sprintf("%s/%s%s", l.Payload.Parent, common.AuditLogPrefix, l.ResourceID),
- CreateTime: timestamppb.New(l.CreatedAt),
- User: l.Payload.User,
- Method: l.Payload.Method,
- Severity: convertToAuditLogSeverity(l.Payload.Severity),
- Resource: l.Payload.Resource,
- Request: l.Payload.Request,
- Response: l.Payload.Response,
- Status: l.Payload.Status,
- Latency: l.Payload.Latency,
- ServiceData: l.Payload.ServiceData,
+ Name: fmt.Sprintf("%s/%s%s", l.Payload.Parent, common.AuditLogPrefix, l.ResourceID),
+ CreateTime: timestamppb.New(l.CreatedAt),
+ User: l.Payload.User,
+ Method: l.Payload.Method,
+ Severity: convertToAuditLogSeverity(l.Payload.Severity),
+ Resource: l.Payload.Resource,
+ Request: l.Payload.Request,
+ Response: l.Payload.Response,
+ Status: l.Payload.Status,
+ Latency: l.Payload.Latency,
+ ServiceData: l.Payload.ServiceData,
+ McpDelegation: convertToMCPDelegation(l.Payload.McpDelegation),
+ }
+}
+
+// convertToMCPDelegation surfaces the stored MCP provenance on the public
+// AuditLog. Preserving nil is load-bearing: presence of the message is the
+// MCP-origin marker operators read.
+func convertToMCPDelegation(d *storepb.MCPDelegation) *v1pb.MCPDelegation {
+ if d == nil {
+ return nil
+ }
+ return &v1pb.MCPDelegation{
+ Scope: d.Scope,
+ Resource: d.Resource,
+ ClientId: d.ClientId,
+ CorrelationId: d.CorrelationId,
}
}
diff --git a/backend/api/v1/audit_mcp_provenance_test.go b/backend/api/v1/audit_mcp_provenance_test.go
new file mode 100644
index 0000000000..87d18420e6
--- /dev/null
+++ b/backend/api/v1/audit_mcp_provenance_test.go
@@ -0,0 +1,271 @@
+package v1
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "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/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+
+ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
+)
+
+const auditTestWorkspace = "ws-audit"
+
+// specRequest overrides a request's Spec so the interceptors see a full
+// procedure name — connect.NewRequest alone leaves it empty.
+type specRequest struct {
+ connect.AnyRequest
+ procedure string
+}
+
+func (r *specRequest) Spec() connect.Spec {
+ return connect.Spec{Procedure: r.procedure}
+}
+
+// newAuditLiveStore boots a migrated store with one workspace, so
+// CreateAuditLog has a real parent row to write under.
+func newAuditLiveStore(t *testing.T) *store.Store {
+ 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, fmt.Sprintf(
+ `INSERT INTO workspace (resource_id) VALUES ('%s')`, auditTestWorkspace))
+ 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)
+ return st
+}
+
+func auditTestUser() *store.UserMessage {
+ return &store.UserMessage{
+ ID: 1,
+ Email: "[email protected]",
+ Type: storepb.PrincipalType_END_USER,
+ }
+}
+
+func newAuditTestContext(authCtx *common.AuthContext) context.Context {
+ ctx := context.WithValue(context.Background(), common.AuthContextKey, authCtx)
+ ctx = context.WithValue(ctx, common.UserContextKey, auditTestUser())
+ ctx = context.WithValue(ctx, common.WorkspaceIDContextKey, auditTestWorkspace)
+ return ctx
+}
+
+// findRowsByCorrelation returns the workspace's audit rows whose MCP
+// delegation carries the given correlation ID.
+func findRowsByCorrelation(t *testing.T, st *store.Store, correlationID string) []*store.AuditLog {
+ t.Helper()
+ rows, err := st.SearchAuditLogs(context.Background(), &store.AuditLogFind{
+ Workspace: auditTestWorkspace,
+ })
+ require.NoError(t, err)
+ var matched []*store.AuditLog
+ for _, row := range rows {
+ if row.Payload.GetMcpDelegation().GetCorrelationId() == correlationID {
+ matched = append(matched, row)
+ }
+ }
+ return matched
+}
+
+// TestAuditRowCarriesMCPDelegationProvenance pins P1a PR 5b's provenance
+// contract at the store level: an audited call that arrived with a delegated
+// MCP credential (AuthContext.DelegatedGrant non-nil) writes its grant state
+// verbatim onto the audit row, empty values preserved as empty; a public-chain
+// call (nil grant) writes a row with no MCP fields at all.
+func TestAuditRowCarriesMCPDelegationProvenance(t *testing.T) {
+ st := newAuditLiveStore(t)
+ in := NewAuditInterceptor(st, "test-secret", &config.Profile{})
+
+ invoke := func(t *testing.T, grant *common.DelegatedGrant) {
+ t.Helper()
+ authCtx := &common.AuthContext{
+ Audit: true,
+ AuthMethod: common.AuthMethodIAM,
+ Resources: []*common.Resource{{Type: common.ResourceTypeWorkspace, ID: auditTestWorkspace}},
+ DelegatedGrant: grant,
+ }
+ next := func(_ context.Context, _ connect.AnyRequest) (connect.AnyResponse, error) {
+ return connect.NewResponse(&v1pb.QueryResponse{}), nil
+ }
+ req := &specRequest{
+ AnyRequest: connect.NewRequest(&v1pb.QueryRequest{Name: "instances/i/databases/d"}),
+ procedure: "/bytebase.v1.SQLService/Query",
+ }
+ _, err := in.WrapUnary(next)(newAuditTestContext(authCtx), req)
+ require.NoError(t, err)
+ }
+
+ t.Run("a consented grant is stamped verbatim", func(t *testing.T) {
+ invoke(t, &common.DelegatedGrant{
+ Scope: "mcp:read-only",
+ Resource: "https://bb.example.com/mcp",
+ ClientID: "client-A",
+ CorrelationID: "corr-full",
+ })
+ rows := findRowsByCorrelation(t, st, "corr-full")
+ require.Len(t, rows, 1, "an audited internal-chain call must produce exactly one provenance-carrying row")
+ got := rows[0].Payload.GetMcpDelegation()
+ require.Equal(t, "mcp:read-only", got.GetScope())
+ require.Equal(t, "https://bb.example.com/mcp", got.GetResource())
+ require.Equal(t, "client-A", got.GetClientId())
+ })
+
+ t.Run("a legacy empty grant still marks MCP origin, empty stays empty", func(t *testing.T) {
+ invoke(t, &common.DelegatedGrant{CorrelationID: "corr-legacy"})
+ rows := findRowsByCorrelation(t, st, "corr-legacy")
+ require.Len(t, rows, 1)
+ got := rows[0].Payload.GetMcpDelegation()
+ require.NotNil(t, got, "presence of the delegation message is the MCP-origin marker, even for empty legacy grants")
+ require.Empty(t, got.GetScope(), "an empty grant scope must be recorded empty, never resolved to a label")
+ require.Empty(t, got.GetResource())
+ require.Empty(t, got.GetClientId())
+ })
+
+ t.Run("a public-chain row carries no MCP fields", func(t *testing.T) {
+ invoke(t, nil)
+ rows, err := st.SearchAuditLogs(context.Background(), &store.AuditLogFind{
+ Workspace: auditTestWorkspace,
+ })
+ require.NoError(t, err)
+ var publicRows []*store.AuditLog
+ for _, row := range rows {
+ if row.Payload.GetMcpDelegation() == nil {
+ publicRows = append(publicRows, row)
+ }
+ }
+ require.Len(t, publicRows, 1, "the nil-grant call must produce exactly one row without MCP provenance")
+ })
+}
+
+// TestAuditParentsDeduplicated pins that createAuditLog writes ONE row per
+// distinct parent. Batch requests repeat the same project resource once per
+// item, and since PR 5b routes ACL-denied internal-chain calls through the
+// audit interceptor, an unprivileged caller reaches this fan-out — without
+// dedup, a single denied batch call naming N items would write N identical
+// rows.
+func TestAuditParentsDeduplicated(t *testing.T) {
+ st := newAuditLiveStore(t)
+ in := NewAuditInterceptor(st, "test-secret", &config.Profile{})
+
+ authCtx := &common.AuthContext{
+ Audit: true,
+ AuthMethod: common.AuthMethodIAM,
+ Resources: []*common.Resource{
+ {Type: common.ResourceTypeProject, ID: "proj-batch"},
+ {Type: common.ResourceTypeProject, ID: "proj-batch"},
+ {Type: common.ResourceTypeProject, ID: "proj-batch"},
+ {Type: common.ResourceTypeWorkspace, ID: auditTestWorkspace},
+ },
+ DelegatedGrant: &common.DelegatedGrant{CorrelationID: "corr-dedup"},
+ }
+ next := func(_ context.Context, _ connect.AnyRequest) (connect.AnyResponse, error) {
+ return connect.NewResponse(&v1pb.QueryResponse{}), nil
+ }
+ req := &specRequest{
+ AnyRequest: connect.NewRequest(&v1pb.QueryRequest{Name: "instances/i/databases/d"}),
+ procedure: "/bytebase.v1.SQLService/Query",
+ }
+ _, err := in.WrapUnary(next)(newAuditTestContext(authCtx), req)
+ require.NoError(t, err)
+
+ rows := findRowsByCorrelation(t, st, "corr-dedup")
+ var parents []string
+ for _, row := range rows {
+ parents = append(parents, row.Payload.Parent)
+ }
+ require.ElementsMatch(t,
+ []string{common.FormatProject("proj-batch"), "workspaces/" + auditTestWorkspace},
+ parents,
+ "one audit row per DISTINCT parent — repeated batch resources must not multiply rows")
+}
+
+// TestInternalChainAuditRecordsACLDenial pins PR 5b's denial-audit mechanism:
+// with the audit interceptor wrapped OUTSIDE the ACL interceptor (the internal
+// MCP chain's order), an ACL denial produces an audit row carrying the
+// provenance and the denied status; a method whose annotation opts out of
+// auditing stays silent for permitted and denied calls alike.
+func TestInternalChainAuditRecordsACLDenial(t *testing.T) {
+ st := newAuditLiveStore(t)
+ auditIn := NewAuditInterceptor(st, "test-secret", &config.Profile{})
+ aclIn := NewACLInterceptor(st, "test-secret", nil /* iamManager: unreached on these paths */, &config.Profile{})
+
+ invoke := func(t *testing.T, audited bool, correlationID, resource string) (handlerReached bool, rerr error) {
+ t.Helper()
+ authCtx := &common.AuthContext{
+ Audit: audited,
+ AuthMethod: common.AuthMethodCustom,
+ DelegatedGrant: &common.DelegatedGrant{
+ Scope: "mcp:read-only",
+ Resource: "https://bb.example.com/mcp",
+ ClientID: "client-A",
+ CorrelationID: correlationID,
+ },
+ }
+ handler := func(_ context.Context, _ connect.AnyRequest) (connect.AnyResponse, error) {
+ handlerReached = true
+ return connect.NewResponse(&v1pb.IamPolicy{}), nil
+ }
+ // The internal chain's order: audit outside, ACL inside.
+ chain := auditIn.WrapUnary(aclIn.WrapUnary(handler))
+ req := &specRequest{
+ AnyRequest: connect.NewRequest(&v1pb.SetIamPolicyRequest{Resource: resource}),
+ procedure: "/bytebase.v1.WorkspaceService/SetIamPolicy",
+ }
+ _, rerr = chain(newAuditTestContext(authCtx), req)
+ return handlerReached, rerr
+ }
+
+ t.Run("an ACL denial produces a provenance-carrying denied row", func(t *testing.T) {
+ handlerReached, err := invoke(t, true, "corr-denied", "workspaces/other-ws")
+ require.Error(t, err)
+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
+ require.False(t, handlerReached, "the denial must come from the ACL interceptor, not the handler")
+
+ rows := findRowsByCorrelation(t, st, "corr-denied")
+ require.Len(t, rows, 1, "an ACL-denied internal-chain call must still produce an audit row")
+ row := rows[0].Payload
+ require.Equal(t, "workspaces/"+auditTestWorkspace, row.Parent,
+ "a denied cross-workspace attempt must be audited under the CALLER's workspace, never the foreign one it named")
+ require.Equal(t, "/bytebase.v1.WorkspaceService/SetIamPolicy", row.Method)
+ require.Equal(t, common.FormatUserEmail(auditTestUser().Email), row.User)
+ require.NotNil(t, row.Status, "the row must reflect the denial")
+ require.Equal(t, int32(connect.CodePermissionDenied), row.Status.Code)
+ require.Equal(t, "mcp:read-only", row.GetMcpDelegation().GetScope())
+ })
+
+ t.Run("a method opted out of auditing stays silent for denials too", func(t *testing.T) {
+ _, err := invoke(t, false, "corr-optout", "workspaces/other-ws")
+ require.Error(t, err)
+ require.Empty(t, findRowsByCorrelation(t, st, "corr-optout"),
+ "audit opt-out must behave consistently for permitted and denied calls")
+ })
+
+ t.Run("a permitted call is audited exactly once", func(t *testing.T) {
+ handlerReached, err := invoke(t, true, "corr-permitted", "workspaces/"+auditTestWorkspace)
+ require.NoError(t, err)
+ require.True(t, handlerReached)
+
+ rows := findRowsByCorrelation(t, st, "corr-permitted")
+ require.Len(t, rows, 1)
+ require.Nil(t, rows[0].Payload.Status, "a permitted call keeps its success status")
+ })
+}
diff --git a/backend/api/v1/audit_test.go b/backend/api/v1/audit_test.go
index 87aee9a1b2..8db596fd68 100644
--- a/backend/api/v1/audit_test.go
+++ b/backend/api/v1/audit_test.go
@@ -104,6 +104,33 @@ func TestLogAuditToStdoutFormat(t *testing.T) {
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"])
}
// TestAuditRedactsCredentials covers the request/response redactors that
diff --git a/backend/generated-go/store/audit_log.pb.go b/backend/generated-go/store/audit_log.pb.go
index 652629e112..a8c2e1832b 100644
--- a/backend/generated-go/store/audit_log.pb.go
+++ b/backend/generated-go/store/audit_log.pb.go
@@ -118,8 +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"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ // 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.
+ McpDelegation *MCPDelegation `protobuf:"bytes,12,opt,name=mcp_delegation,json=mcpDelegation,proto3" json:"mcp_delegation,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *AuditLog) Reset() {
@@ -229,6 +233,13 @@ func (x *AuditLog) GetRequestMetadata() *RequestMetadata {
return nil
}
+func (x *AuditLog) GetMcpDelegation() *MCPDelegation {
+ if x != nil {
+ return x.McpDelegation
+ }
+ return nil
+}
+
// Metadata about the request.
type RequestMetadata struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -285,11 +296,93 @@ func (x *RequestMetadata) GetCallerSuppliedUserAgent() string {
return ""
}
+// Provenance of a call that reached the API through the MCP (Model Context
+// Protocol) server's delegated credential. The values are copied verbatim from
+// the verified credential's grant state; empty fields record that the grant
+// stored nothing (legacy sessions), never a resolved or synthesized value.
+type MCPDelegation struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The OAuth2 grant's consented scope, e.g. "mcp:read-only".
+ // Empty when the grant recorded no scope.
+ Scope string `protobuf:"bytes,1,opt,name=scope,proto3" json:"scope,omitempty"`
+ // The grant's stored MCP resource URI.
+ // Empty for pre-grant legacy sessions.
+ Resource string `protobuf:"bytes,2,opt,name=resource,proto3" json:"resource,omitempty"`
+ // The OAuth2 client the grant was consented to.
+ // Empty for legacy web-session tokens at /mcp.
+ ClientId string `protobuf:"bytes,3,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"`
+ // 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.
+ CorrelationId string `protobuf:"bytes,4,opt,name=correlation_id,json=correlationId,proto3" json:"correlation_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *MCPDelegation) Reset() {
+ *x = MCPDelegation{}
+ mi := &file_store_audit_log_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *MCPDelegation) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MCPDelegation) ProtoMessage() {}
+
+func (x *MCPDelegation) ProtoReflect() protoreflect.Message {
+ mi := &file_store_audit_log_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 MCPDelegation.ProtoReflect.Descriptor instead.
+func (*MCPDelegation) Descriptor() ([]byte, []int) {
+ return file_store_audit_log_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *MCPDelegation) GetScope() string {
+ if x != nil {
+ return x.Scope
+ }
+ return ""
+}
+
+func (x *MCPDelegation) GetResource() string {
+ if x != nil {
+ return x.Resource
+ }
+ return ""
+}
+
+func (x *MCPDelegation) GetClientId() string {
+ if x != nil {
+ return x.ClientId
+ }
+ return ""
+}
+
+func (x *MCPDelegation) GetCorrelationId() string {
+ if x != nil {
+ return x.CorrelationId
+ }
+ return ""
+}
+
var File_store_audit_log_proto protoreflect.FileDescriptor
const file_store_audit_log_proto_rawDesc = "" +
"\n" +
- "\x15store/audit_log.proto\x12\x0ebytebase.store\x1a\x19google/protobuf/any.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x17google/rpc/status.proto\"\xcd\x04\n" +
+ "\x15store/audit_log.proto\x12\x0ebytebase.store\x1a\x19google/protobuf/any.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x17google/rpc/status.proto\"\x93\x05\n" +
"\bAuditLog\x12\x16\n" +
"\x06parent\x18\x01 \x01(\tR\x06parent\x12\x16\n" +
"\x06method\x18\x02 \x01(\tR\x06method\x12\x1a\n" +
@@ -302,7 +395,8 @@ const file_store_audit_log_proto_rawDesc = "" +
"\alatency\x18\t \x01(\v2\x19.google.protobuf.DurationR\alatency\x127\n" +
"\fservice_data\x18\n" +
" \x01(\v2\x14.google.protobuf.AnyR\vserviceData\x12J\n" +
- "\x10request_metadata\x18\v \x01(\v2\x1f.bytebase.store.RequestMetadataR\x0frequestMetadata\"\x85\x01\n" +
+ "\x10request_metadata\x18\v \x01(\v2\x1f.bytebase.store.RequestMetadataR\x0frequestMetadata\x12D\n" +
+ "\x0emcp_delegation\x18\f \x01(\v2\x1d.bytebase.store.MCPDelegationR\rmcpDelegation\"\x85\x01\n" +
"\bSeverity\x12\x18\n" +
"\x14SEVERITY_UNSPECIFIED\x10\x00\x12\t\n" +
"\x05DEBUG\x10\x01\x12\b\n" +
@@ -316,7 +410,12 @@ const file_store_audit_log_proto_rawDesc = "" +
"\tEMERGENCY\x10\b\"k\n" +
"\x0fRequestMetadata\x12\x1b\n" +
"\tcaller_ip\x18\x01 \x01(\tR\bcallerIp\x12;\n" +
- "\x1acaller_supplied_user_agent\x18\x02 \x01(\tR\x17callerSuppliedUserAgentB\x90\x01\n" +
+ "\x1acaller_supplied_user_agent\x18\x02 \x01(\tR\x17callerSuppliedUserAgent\"\x85\x01\n" +
+ "\rMCPDelegation\x12\x14\n" +
+ "\x05scope\x18\x01 \x01(\tR\x05scope\x12\x1a\n" +
+ "\bresource\x18\x02 \x01(\tR\bresource\x12\x1b\n" +
+ "\tclient_id\x18\x03 \x01(\tR\bclientId\x12%\n" +
+ "\x0ecorrelation_id\x18\x04 \x01(\tR\rcorrelationIdB\x90\x01\n" +
"\x12com.bytebase.storeB\rAuditLogProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"
var (
@@ -332,26 +431,28 @@ func file_store_audit_log_proto_rawDescGZIP() []byte {
}
var file_store_audit_log_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
-var file_store_audit_log_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
+var file_store_audit_log_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_store_audit_log_proto_goTypes = []any{
(AuditLog_Severity)(0), // 0: bytebase.store.AuditLog.Severity
(*AuditLog)(nil), // 1: bytebase.store.AuditLog
(*RequestMetadata)(nil), // 2: bytebase.store.RequestMetadata
- (*status.Status)(nil), // 3: google.rpc.Status
- (*durationpb.Duration)(nil), // 4: google.protobuf.Duration
- (*anypb.Any)(nil), // 5: google.protobuf.Any
+ (*MCPDelegation)(nil), // 3: bytebase.store.MCPDelegation
+ (*status.Status)(nil), // 4: google.rpc.Status
+ (*durationpb.Duration)(nil), // 5: google.protobuf.Duration
+ (*anypb.Any)(nil), // 6: google.protobuf.Any
}
var file_store_audit_log_proto_depIdxs = []int32{
0, // 0: bytebase.store.AuditLog.severity:type_name -> bytebase.store.AuditLog.Severity
- 3, // 1: bytebase.store.AuditLog.status:type_name -> google.rpc.Status
- 4, // 2: bytebase.store.AuditLog.latency:type_name -> google.protobuf.Duration
- 5, // 3: bytebase.store.AuditLog.service_data:type_name -> google.protobuf.Any
+ 4, // 1: bytebase.store.AuditLog.status:type_name -> google.rpc.Status
+ 5, // 2: bytebase.store.AuditLog.latency:type_name -> google.protobuf.Duration
+ 6, // 3: bytebase.store.AuditLog.service_data:type_name -> google.protobuf.Any
2, // 4: bytebase.store.AuditLog.request_metadata:type_name -> bytebase.store.RequestMetadata
- 5, // [5:5] is the sub-list for method output_type
- 5, // [5:5] is the sub-list for method input_type
- 5, // [5:5] is the sub-list for extension type_name
- 5, // [5:5] is the sub-list for extension extendee
- 0, // [0:5] is the sub-list for field type_name
+ 3, // 5: bytebase.store.AuditLog.mcp_delegation:type_name -> bytebase.store.MCPDelegation
+ 6, // [6:6] is the sub-list for method output_type
+ 6, // [6:6] is the sub-list for method input_type
+ 6, // [6:6] is the sub-list for extension type_name
+ 6, // [6:6] is the sub-list for extension extendee
+ 0, // [0:6] is the sub-list for field type_name
}
func init() { file_store_audit_log_proto_init() }
@@ -365,7 +466,7 @@ func file_store_audit_log_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_audit_log_proto_rawDesc), len(file_store_audit_log_proto_rawDesc)),
NumEnums: 1,
- NumMessages: 2,
+ NumMessages: 3,
NumExtensions: 0,
NumServices: 0,
},
diff --git a/backend/generated-go/store/audit_log_equal.pb.go b/backend/generated-go/store/audit_log_equal.pb.go
index 88bf2d2f71..d17f6d036f 100644
--- a/backend/generated-go/store/audit_log_equal.pb.go
+++ b/backend/generated-go/store/audit_log_equal.pb.go
@@ -50,6 +50,9 @@ func (x *AuditLog) Equal(y *AuditLog) bool {
if !x.RequestMetadata.Equal(y.RequestMetadata) {
return false
}
+ if !x.McpDelegation.Equal(y.McpDelegation) {
+ return false
+ }
return true
}
@@ -68,3 +71,25 @@ func (x *RequestMetadata) Equal(y *RequestMetadata) bool {
}
return true
}
+
+func (x *MCPDelegation) Equal(y *MCPDelegation) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Scope != y.Scope {
+ return false
+ }
+ if x.Resource != y.Resource {
+ return false
+ }
+ if x.ClientId != y.ClientId {
+ return false
+ }
+ if x.CorrelationId != y.CorrelationId {
+ return false
+ }
+ return true
+}
diff --git a/backend/generated-go/v1/audit_log_service.pb.go b/backend/generated-go/v1/audit_log_service.pb.go
index 53c9e94ba7..9b8f03300e 100644
--- a/backend/generated-go/v1/audit_log_service.pb.go
+++ b/backend/generated-go/v1/audit_log_service.pb.go
@@ -450,8 +450,12 @@ type AuditLog struct {
ServiceData *anypb.Any `protobuf:"bytes,11,opt,name=service_data,json=serviceData,proto3" json:"service_data,omitempty"`
// Metadata about the request context.
RequestMetadata *RequestMetadata `protobuf:"bytes,12,opt,name=request_metadata,json=requestMetadata,proto3" json:"request_metadata,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ // 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.
+ McpDelegation *MCPDelegation `protobuf:"bytes,13,opt,name=mcp_delegation,json=mcpDelegation,proto3" json:"mcp_delegation,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *AuditLog) Reset() {
@@ -568,6 +572,13 @@ func (x *AuditLog) GetRequestMetadata() *RequestMetadata {
return nil
}
+func (x *AuditLog) GetMcpDelegation() *MCPDelegation {
+ if x != nil {
+ return x.McpDelegation
+ }
+ return nil
+}
+
// Additional audit data specific to certain operations.
type AuditData struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -670,6 +681,88 @@ func (x *RequestMetadata) GetCallerSuppliedUserAgent() string {
return ""
}
+// Provenance of a call that reached the API through the MCP (Model Context
+// Protocol) server's delegated credential. The values are copied verbatim from
+// the verified credential's grant state; empty fields record that the grant
+// stored nothing (legacy sessions), never a resolved or synthesized value.
+type MCPDelegation struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The OAuth2 grant's consented scope, e.g. "mcp:read-only".
+ // Empty when the grant recorded no scope.
+ Scope string `protobuf:"bytes,1,opt,name=scope,proto3" json:"scope,omitempty"`
+ // The grant's stored MCP resource URI.
+ // Empty for pre-grant legacy sessions.
+ Resource string `protobuf:"bytes,2,opt,name=resource,proto3" json:"resource,omitempty"`
+ // The OAuth2 client the grant was consented to.
+ // Empty for legacy web-session tokens at /mcp.
+ ClientId string `protobuf:"bytes,3,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"`
+ // 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.
+ CorrelationId string `protobuf:"bytes,4,opt,name=correlation_id,json=correlationId,proto3" json:"correlation_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *MCPDelegation) Reset() {
+ *x = MCPDelegation{}
+ mi := &file_v1_audit_log_service_proto_msgTypes[7]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *MCPDelegation) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MCPDelegation) ProtoMessage() {}
+
+func (x *MCPDelegation) ProtoReflect() protoreflect.Message {
+ mi := &file_v1_audit_log_service_proto_msgTypes[7]
+ 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 MCPDelegation.ProtoReflect.Descriptor instead.
+func (*MCPDelegation) Descriptor() ([]byte, []int) {
+ return file_v1_audit_log_service_proto_rawDescGZIP(), []int{7}
+}
+
+func (x *MCPDelegation) GetScope() string {
+ if x != nil {
+ return x.Scope
+ }
+ return ""
+}
+
+func (x *MCPDelegation) GetResource() string {
+ if x != nil {
+ return x.Resource
+ }
+ return ""
+}
+
+func (x *MCPDelegation) GetClientId() string {
+ if x != nil {
+ return x.ClientId
+ }
+ return ""
+}
+
+func (x *MCPDelegation) GetCorrelationId() string {
+ if x != nil {
+ return x.CorrelationId
+ }
+ return ""
+}
+
var File_v1_audit_log_service_proto protoreflect.FileDescriptor
const file_v1_audit_log_service_proto_rawDesc = "" +
@@ -696,7 +789,7 @@ const file_v1_audit_log_service_proto_rawDesc = "" +
"page_token\x18\x06 \x01(\tR\tpageToken\"[\n" +
"\x17ExportAuditLogsResponse\x12\x18\n" +
"\acontent\x18\x01 \x01(\fR\acontent\x12&\n" +
- "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\x8a\x05\n" +
+ "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\xd2\x05\n" +
"\bAuditLog\x12\x17\n" +
"\x04name\x18\x01 \x01(\tB\x03\xe0A\x03R\x04name\x12@\n" +
"\vcreate_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampB\x03\xe0A\x03R\n" +
@@ -711,7 +804,8 @@ const file_v1_audit_log_service_proto_rawDesc = "" +
"\alatency\x18\n" +
" \x01(\v2\x19.google.protobuf.DurationR\alatency\x127\n" +
"\fservice_data\x18\v \x01(\v2\x14.google.protobuf.AnyR\vserviceData\x12G\n" +
- "\x10request_metadata\x18\f \x01(\v2\x1c.bytebase.v1.RequestMetadataR\x0frequestMetadata\"\x85\x01\n" +
+ "\x10request_metadata\x18\f \x01(\v2\x1c.bytebase.v1.RequestMetadataR\x0frequestMetadata\x12F\n" +
+ "\x0emcp_delegation\x18\r \x01(\v2\x1a.bytebase.v1.MCPDelegationB\x03\xe0A\x03R\rmcpDelegation\"\x85\x01\n" +
"\bSeverity\x12\x18\n" +
"\x14SEVERITY_UNSPECIFIED\x10\x00\x12\t\n" +
"\x05DEBUG\x10\x01\x12\b\n" +
@@ -727,7 +821,12 @@ const file_v1_audit_log_service_proto_rawDesc = "" +
"\fpolicy_delta\x18\x01 \x01(\v2\x18.bytebase.v1.PolicyDeltaR\vpolicyDelta\"k\n" +
"\x0fRequestMetadata\x12\x1b\n" +
"\tcaller_ip\x18\x01 \x01(\tR\bcallerIp\x12;\n" +
- "\x1acaller_supplied_user_agent\x18\x02 \x01(\tR\x17callerSuppliedUserAgent2\xa5\x03\n" +
+ "\x1acaller_supplied_user_agent\x18\x02 \x01(\tR\x17callerSuppliedUserAgent\"\x85\x01\n" +
+ "\rMCPDelegation\x12\x14\n" +
+ "\x05scope\x18\x01 \x01(\tR\x05scope\x12\x1a\n" +
+ "\bresource\x18\x02 \x01(\tR\bresource\x12\x1b\n" +
+ "\tclient_id\x18\x03 \x01(\tR\bclientId\x12%\n" +
+ "\x0ecorrelation_id\x18\x04 \x01(\tR\rcorrelationId2\xa5\x03\n" +
"\x0fAuditLogService\x12\xc7\x01\n" +
"\x0fSearchAuditLogs\x12#.bytebase.v1.SearchAuditLogsRequest\x1a$.bytebase.v1.SearchAuditLogsResponse\"i\x8a\xea0\x13bb.auditLogs.search\x90\xea0\x01\x82\xd3\xe4\x93\x02H:\x01*Z\x19:\x01*\"\x14/v1/auditLogs:search\"(/v1/{parent=projects/*}/auditLogs:search\x12\xc7\x01\n" +
"\x0fExportAuditLogs\x12#.bytebase.v1.ExportAuditLogsRequest\x1a$.bytebase.v1.ExportAuditLogsResponse\"i\x8a\xea0\x13bb.auditLogs.export\x90\xea0\x01\x82\xd3\xe4\x93\x02H:\x01*Z\x19:\x01*\"\x14/v1/auditLogs:export\"(/v1/{parent=projects/*}/auditLogs:exportB\xaa\x01\n" +
@@ -746,7 +845,7 @@ func file_v1_audit_log_service_proto_rawDescGZIP() []byte {
}
var file_v1_audit_log_service_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
-var file_v1_audit_log_service_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
+var file_v1_audit_log_service_proto_msgTypes = make([]protoimpl.MessageInfo, 8)
var file_v1_audit_log_service_proto_goTypes = []any{
(AuditLog_Severity)(0), // 0: bytebase.v1.AuditLog.Severity
(*SearchAuditLogsRequest)(nil), // 1: bytebase.v1.SearchAuditLogsRequest
@@ -756,32 +855,34 @@ var file_v1_audit_log_service_proto_goTypes = []any{
(*AuditLog)(nil), // 5: bytebase.v1.AuditLog
(*AuditData)(nil), // 6: bytebase.v1.AuditData
(*RequestMetadata)(nil), // 7: bytebase.v1.RequestMetadata
- (ExportFormat)(0), // 8: bytebase.v1.ExportFormat
- (*timestamppb.Timestamp)(nil), // 9: google.protobuf.Timestamp
- (*status.Status)(nil), // 10: google.rpc.Status
- (*durationpb.Duration)(nil), // 11: google.protobuf.Duration
- (*anypb.Any)(nil), // 12: google.protobuf.Any
- (*PolicyDelta)(nil), // 13: bytebase.v1.PolicyDelta
+ (*MCPDelegation)(nil), // 8: bytebase.v1.MCPDelegation
+ (ExportFormat)(0), // 9: bytebase.v1.ExportFormat
+ (*timestamppb.Timestamp)(nil), // 10: google.protobuf.Timestamp
+ (*status.Status)(nil), // 11: google.rpc.Status
+ (*durationpb.Duration)(nil), // 12: google.protobuf.Duration
+ (*anypb.Any)(nil), // 13: google.protobuf.Any
+ (*PolicyDelta)(nil), // 14: bytebase.v1.PolicyDelta
}
var file_v1_audit_log_service_proto_depIdxs = []int32{
5, // 0: bytebase.v1.SearchAuditLogsResponse.audit_logs:type_name -> bytebase.v1.AuditLog
- 8, // 1: bytebase.v1.ExportAuditLogsRequest.format:type_name -> bytebase.v1.ExportFormat
- 9, // 2: bytebase.v1.AuditLog.create_time:type_name -> google.protobuf.Timestamp
+ 9, // 1: bytebase.v1.ExportAuditLogsRequest.format:type_name -> bytebase.v1.ExportFormat
+ 10, // 2: bytebase.v1.AuditLog.create_time:type_name -> google.protobuf.Timestamp
0, // 3: bytebase.v1.AuditLog.severity:type_name -> bytebase.v1.AuditLog.Severity
- 10, // 4: bytebase.v1.AuditLog.status:type_name -> google.rpc.Status
- 11, // 5: bytebase.v1.AuditLog.latency:type_name -> google.protobuf.Duration
- 12, // 6: bytebase.v1.AuditLog.service_data:type_name -> google.protobuf.Any
+ 11, // 4: bytebase.v1.AuditLog.status:type_name -> google.rpc.Status
+ 12, // 5: bytebase.v1.AuditLog.latency:type_name -> google.protobuf.Duration
+ 13, // 6: bytebase.v1.AuditLog.service_data:type_name -> google.protobuf.Any
7, // 7: bytebase.v1.AuditLog.request_metadata:type_name -> bytebase.v1.RequestMetadata
- 13, // 8: bytebase.v1.AuditData.policy_delta:type_name -> bytebase.v1.PolicyDelta
- 1, // 9: bytebase.v1.AuditLogService.SearchAuditLogs:input_type -> bytebase.v1.SearchAuditLogsRequest
- 3, // 10: bytebase.v1.AuditLogService.ExportAuditLogs:input_type -> bytebase.v1.ExportAuditLogsRequest
- 2, // 11: bytebase.v1.AuditLogService.SearchAuditLogs:output_type -> bytebase.v1.SearchAuditLogsResponse
- 4, // 12: bytebase.v1.AuditLogService.ExportAuditLogs:output_type -> bytebase.v1.ExportAuditLogsResponse
- 11, // [11:13] is the sub-list for method output_type
- 9, // [9:11] is the sub-list for method input_type
- 9, // [9:9] is the sub-list for extension type_name
- 9, // [9:9] is the sub-list for extension extendee
- 0, // [0:9] is the sub-list for field type_name
+ 8, // 8: bytebase.v1.AuditLog.mcp_delegation:type_name -> bytebase.v1.MCPDelegation
+ 14, // 9: bytebase.v1.AuditData.policy_delta:type_name -> bytebase.v1.PolicyDelta
+ 1, // 10: bytebase.v1.AuditLogService.SearchAuditLogs:input_type -> bytebase.v1.SearchAuditLogsRequest
+ 3, // 11: bytebase.v1.AuditLogService.ExportAuditLogs:input_type -> bytebase.v1.ExportAuditLogsRequest
+ 2, // 12: bytebase.v1.AuditLogService.SearchAuditLogs:output_type -> bytebase.v1.SearchAuditLogsResponse
+ 4, // 13: bytebase.v1.AuditLogService.ExportAuditLogs:output_type -> bytebase.v1.ExportAuditLogsResponse
+ 12, // [12:14] is the sub-list for method output_type
+ 10, // [10:12] is the sub-list for method input_type
+ 10, // [10:10] is the sub-list for extension type_name
+ 10, // [10:10] is the sub-list for extension extendee
+ 0, // [0:10] is the sub-list for field type_name
}
func init() { file_v1_audit_log_service_proto_init() }
@@ -798,7 +899,7 @@ func file_v1_audit_log_service_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_audit_log_service_proto_rawDesc), len(file_v1_audit_log_service_proto_rawDesc)),
NumEnums: 1,
- NumMessages: 7,
+ NumMessages: 8,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/backend/generated-go/v1/audit_log_service_equal.pb.go b/backend/generated-go/v1/audit_log_service_equal.pb.go
index de0ee09d71..909668a965 100644
--- a/backend/generated-go/v1/audit_log_service_equal.pb.go
+++ b/backend/generated-go/v1/audit_log_service_equal.pb.go
@@ -143,6 +143,9 @@ func (x *AuditLog) Equal(y *AuditLog) bool {
if !x.RequestMetadata.Equal(y.RequestMetadata) {
return false
}
+ if !x.McpDelegation.Equal(y.McpDelegation) {
+ return false
+ }
return true
}
@@ -174,3 +177,25 @@ func (x *RequestMetadata) Equal(y *RequestMetadata) bool {
}
return true
}
+
+func (x *MCPDelegation) Equal(y *MCPDelegation) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.Scope != y.Scope {
+ return false
+ }
+ if x.Resource != y.Resource {
+ return false
+ }
+ if x.ClientId != y.ClientId {
+ return false
+ }
+ if x.CorrelationId != y.CorrelationId {
+ return false
+ }
+ return true
+}
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index b2a1c71324..ebb92ab204 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -194,16 +194,23 @@ func configureGrpcRouters(
// interceptor that accepts ONLY the delegated credential minted at the /mcp
// boundary. It is reachable exclusively through the in-memory transport
// handed to the MCP server — never bound to a listener, so the internal
- // credential never touches a socket. ACL and audit run exactly as on the
- // public chain: the credential carries identity + grant state, while
- // authorization is re-resolved live per request.
+ // credential never touches a socket. ACL runs exactly as on the public
+ // chain: the credential carries identity + grant state, while authorization
+ // is re-resolved live per request.
+ //
+ // Unlike the public chain, audit sits OUTSIDE ACL (first-listed interceptor
+ // is outermost, so listing audit before ACL wraps it): an ACL denial must
+ // still produce an audit row, because a denied MCP call is exactly the
+ // event an operator investigating an agent needs to see. Methods whose
+ // annotation opts out of auditing stay unaudited for permitted and denied
+ // calls alike (needAudit gates both).
internalHandlerOpts := connect.WithHandlerOptions(
connect.WithRecover(onPanic),
connect.WithInterceptors(
validateInterceptor,
auth.NewInternalMCPAuthInterceptor(stores, secret, profile),
- apiv1.NewACLInterceptor(stores, secret, iamManager, profile),
apiv1.NewAuditInterceptor(stores, secret, profile),
+ apiv1.NewACLInterceptor(stores, secret, iamManager, profile),
),
)
internalMCPMux := http.NewServeMux()
diff --git a/backend/tests/mcp_audit_provenance_test.go b/backend/tests/mcp_audit_provenance_test.go
new file mode 100644
index 0000000000..230fc97f8a
--- /dev/null
+++ b/backend/tests/mcp_audit_provenance_test.go
@@ -0,0 +1,178 @@
+package tests
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/stretchr/testify/require"
+
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+// TestMCPAuditProvenance is the P1a PR 5b operator-story e2e: a workspace
+// member's MCP session — real OAuth grant, real /mcp session — makes one
+// permitted call and one call the ACL interceptor denies, and an operator
+// investigating the agent sees BOTH through the v1 audit-log API, each row
+// carrying the delegation provenance (grant scope and resource verbatim,
+// client ID, session correlation ID), the denial with its denied status.
+// Before this PR the denied call vanished entirely (ACL returned before the
+// audit interceptor on the internal chain) and no row carried MCP provenance.
+func TestMCPAuditProvenance(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)
+
+ // A plain workspace member drives the MCP session, so an IAM-gated admin
+ // action is genuinely denied by the ACL interceptor, not the handler.
+ const memberEmail = "[email protected]"
+ const memberPassword = "1024bytebase"
+ memberResp, err := ctl.userServiceClient.CreateUser(ctx, connect.NewRequest(&v1pb.CreateUserRequest{
+ User: &v1pb.User{
+ Title: "agent driver",
+ Email: memberEmail,
+ Password: memberPassword,
+ },
+ }))
+ a.NoError(err)
+ _, err = ctl.addMemberToWorkspaceIAM(ctx, memberResp.Msg.Workspace, "user:"+memberEmail, "roles/workspaceMember")
+ a.NoError(err)
+
+ memberLogin, err := ctl.authServiceClient.Login(ctx, connect.NewRequest(&v1pb.LoginRequest{
+ Email: memberEmail,
+ Password: memberPassword,
+ }))
+ a.NoError(err)
+ workspace := memberLogin.Msg.GetUser().GetWorkspace()
+ a.NotEmpty(workspace)
+
+ // The member consents a real OAuth grant; every audit row the session
+ // produces must carry this grant's stored scope and resource verbatim.
+ mcpToken, clientID := mintMCPOAuthToken(t, ctl, memberLogin.Msg.Token)
+
+ client := mcp.NewClient(&mcp.Implementation{Name: "bb-e2e", Version: "0"}, nil)
+ session, err := client.Connect(ctx, &mcp.StreamableClientTransport{
+ Endpoint: ctl.rootURL + "/mcp",
+ HTTPClient: &http.Client{Transport: &bearerTransport{token: mcpToken}},
+ }, nil)
+ a.NoError(err)
+ defer session.Close()
+
+ callAPI := func(operationID string, body map[string]any) int {
+ result, err := session.CallTool(ctx, &mcp.CallToolParams{
+ Name: "call_api",
+ Arguments: map[string]any{"operationId": operationID, "body": body},
+ })
+ a.NoError(err)
+ raw, err := json.Marshal(result.StructuredContent)
+ a.NoError(err)
+ var out struct {
+ Status int `json:"status"`
+ Error string `json:"error"`
+ }
+ a.NoError(json.Unmarshal(raw, &out))
+ return out.Status
+ }
+
+ // Permitted audited call: the member updates their own title.
+ a.Equal(http.StatusOK, callAPI("UserService/UpdateUser", map[string]any{
+ "user": map[string]any{"name": "users/" + memberEmail, "title": "agent driver (updated)"},
+ "updateMask": "title",
+ }))
+
+ // Denied audited call: creating a user needs bb.users.create, which a
+ // workspace member does not hold — the ACL interceptor refuses it.
+ a.Equal(http.StatusForbidden, callAPI("UserService/CreateUser", map[string]any{
+ "user": map[string]any{"email": "[email protected]", "title": "sneaky", "password": memberPassword},
+ }))
+
+ // The operator's view: both calls surface through the v1 audit-log read
+ // API, attributed to the member.
+ searchMemberRows := func(method string) []*v1pb.AuditLog {
+ resp, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{
+ Parent: workspace,
+ Filter: `method == "` + method + `"`,
+ OrderBy: "create_time desc",
+ }))
+ a.NoError(err)
+ var rows []*v1pb.AuditLog
+ for _, l := range resp.Msg.AuditLogs {
+ if l.User == "users/"+memberEmail {
+ rows = append(rows, l)
+ }
+ }
+ return rows
+ }
+
+ permittedRows := searchMemberRows("/bytebase.v1.UserService/UpdateUser")
+ a.Len(permittedRows, 1, "the permitted MCP call must produce exactly one audit row")
+ permitted := permittedRows[0]
+ a.Nil(permitted.Status, "the permitted call's row keeps its success status")
+ a.NotNil(permitted.McpDelegation, "the permitted row must be marked MCP-originated")
+ a.Equal("mcp:read-only", permitted.McpDelegation.Scope, "the grant scope must be recorded verbatim")
+ a.Equal(ctl.rootURL+"/mcp", permitted.McpDelegation.Resource, "the grant resource must be recorded verbatim")
+ a.Equal(clientID, permitted.McpDelegation.ClientId)
+ a.NotEmpty(permitted.McpDelegation.CorrelationId)
+
+ deniedRows := searchMemberRows("/bytebase.v1.UserService/CreateUser")
+ a.Len(deniedRows, 1, "an ACL-denied MCP call must still produce an audit row — it is exactly the event an operator investigating an agent needs")
+ denied := deniedRows[0]
+ a.NotNil(denied.Status, "the denied row must reflect the denial")
+ a.Equal(int32(connect.CodePermissionDenied), denied.Status.Code)
+ a.NotNil(denied.McpDelegation)
+ a.Equal("mcp:read-only", denied.McpDelegation.Scope)
+ a.Equal(ctl.rootURL+"/mcp", denied.McpDelegation.Resource)
+ a.Equal(clientID, denied.McpDelegation.ClientId)
+ a.Equal(permitted.McpDelegation.CorrelationId, denied.McpDelegation.CorrelationId,
+ "one MCP session carries one correlation ID across all of its tool calls")
+
+ // A denial on a project-scoped resource keeps its true project parent —
+ // the denied probe must show up for that project's auditors. (Only
+ // UNVALIDATED resources — the workspace-mismatch arm — fall back to the
+ // caller's workspace; an IAM denial's resources passed workspace-scoped
+ // validation.)
+ projects, err := ctl.projectServiceClient.ListProjects(ctx, connect.NewRequest(&v1pb.ListProjectsRequest{}))
+ a.NoError(err)
+ a.NotEmpty(projects.Msg.Projects)
+ projectName := projects.Msg.Projects[0].Name
+ a.Equal(http.StatusForbidden, callAPI("ProjectService/SetIamPolicy", map[string]any{
+ "resource": projectName,
+ "policy": map[string]any{"bindings": []any{}},
+ }))
+ projectDenied, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{
+ Parent: projectName,
+ Filter: `method == "/bytebase.v1.ProjectService/SetIamPolicy"`,
+ }))
+ a.NoError(err)
+ a.Len(projectDenied.Msg.AuditLogs, 1, "the project-scoped denial must be audited under the project it targeted")
+ projectRow := projectDenied.Msg.AuditLogs[0]
+ a.True(strings.HasPrefix(projectRow.Name, projectName+"/auditLogs/"))
+ a.Equal("users/"+memberEmail, projectRow.User)
+ a.Equal(int32(connect.CodePermissionDenied), projectRow.Status.GetCode())
+ a.Equal(permitted.McpDelegation.CorrelationId, projectRow.McpDelegation.GetCorrelationId())
+
+ // Public-chain rows are untouched: the admin's direct v1 CreateUser (the
+ // member's own creation, same audited method as the denial) carries no
+ // MCP fields.
+ adminRows, err := ctl.auditLogServiceClient.SearchAuditLogs(ctx, connect.NewRequest(&v1pb.SearchAuditLogsRequest{
+ Parent: workspace,
+ Filter: `method == "/bytebase.v1.UserService/CreateUser"`,
+ }))
+ a.NoError(err)
+ var adminCreates int
+ for _, row := range adminRows.Msg.AuditLogs {
+ if row.User == ctl.principalName {
+ adminCreates++
+ a.Nil(row.McpDelegation, "a public-chain row must never carry MCP provenance")
+ }
+ }
+ a.Positive(adminCreates, "the admin's public-chain CreateUser must have been audited")
+}
diff --git a/backend/tests/mcp_token_boundary_test.go b/backend/tests/mcp_token_boundary_test.go
index 2cad5884b0..61cbb6a2bb 100644
--- a/backend/tests/mcp_token_boundary_test.go
+++ b/backend/tests/mcp_token_boundary_test.go
@@ -24,8 +24,10 @@ import (
// mintMCPOAuthToken runs the full OAuth2 flow a real MCP client performs
// against the live server — RFC 7591 dynamic client registration, PKCE
-// consent, code exchange — and returns the resource-bound access token.
-func mintMCPOAuthToken(t *testing.T, ctl *controller) string {
+// consent, code exchange — and returns the resource-bound access token plus
+// the registered client ID. consentBearer is the token of the user granting
+// consent; the minted token is bound to that principal.
+func mintMCPOAuthToken(t *testing.T, ctl *controller, consentBearer string) (string, string) {
t.Helper()
httpClient := &http.Client{}
redirectURI := "http://localhost/cb"
@@ -56,7 +58,7 @@ func mintMCPOAuthToken(t *testing.T, ctl *controller) string {
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)
+ req.Header.Set("Authorization", "Bearer "+consentBearer)
consentResp, err := httpClient.Do(req)
require.NoError(t, err)
defer consentResp.Body.Close()
@@ -91,7 +93,7 @@ func mintMCPOAuthToken(t *testing.T, ctl *controller) string {
}
require.NoError(t, json.Unmarshal(tokenBody, &token))
require.NotEmpty(t, token.AccessToken)
- return token.AccessToken
+ return token.AccessToken, reg.ClientID
}
// TestMCPTokenIsRejectedOnGeneralAPI is the P1a PR 5 boundary e2e: a real
@@ -112,7 +114,7 @@ func TestMCPTokenIsRejectedOnGeneralAPI(t *testing.T) {
a.NoError(err)
defer ctl.Close(ctx)
- mcpToken := mintMCPOAuthToken(t, ctl)
+ mcpToken, _ := mintMCPOAuthToken(t, ctl, ctl.authInterceptor.token)
client := mcp.NewClient(&mcp.Implementation{Name: "bb-e2e", Version: "0"}, nil)
session, err := client.Connect(ctx, &mcp.StreamableClientTransport{
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 d28b1efc19..bfbb60fc33 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
@@ -294,6 +294,15 @@ export declare type AuditLog = Message<"bytebase.v1.AuditLog"> & {
* @generated from field: bytebase.v1.RequestMetadata request_metadata = 12;
*/
requestMetadata?: RequestMetadata | undefined;
+
+ /**
+ * 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.
+ *
+ * @generated from field: bytebase.v1.MCPDelegation mcp_delegation = 13;
+ */
+ mcpDelegation?: MCPDelegation | undefined;
};
/**
@@ -425,6 +434,56 @@ export declare type RequestMetadata = Message<"bytebase.v1.RequestMetadata"> & {
*/
export declare const RequestMetadataSchema: GenMessage<RequestMetadata>;
+/**
+ * Provenance of a call that reached the API through the MCP (Model Context
+ * Protocol) server's delegated credential. The values are copied verbatim from
+ * the verified credential's grant state; empty fields record that the grant
+ * stored nothing (legacy sessions), never a resolved or synthesized value.
+ *
+ * @generated from message bytebase.v1.MCPDelegation
+ */
+export declare type MCPDelegation = Message<"bytebase.v1.MCPDelegation"> & {
+ /**
+ * The OAuth2 grant's consented scope, e.g. "mcp:read-only".
+ * Empty when the grant recorded no scope.
+ *
+ * @generated from field: string scope = 1;
+ */
+ scope: string;
+
+ /**
+ * The grant's stored MCP resource URI.
+ * Empty for pre-grant legacy sessions.
+ *
+ * @generated from field: string resource = 2;
+ */
+ resource: string;
+
+ /**
+ * The OAuth2 client the grant was consented to.
+ * Empty for legacy web-session tokens at /mcp.
+ *
+ * @generated from field: string client_id = 3;
+ */
+ clientId: 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.
+ *
+ * @generated from field: string correlation_id = 4;
+ */
+ correlationId: string;
+};
+
+/**
+ * Describes the message bytebase.v1.MCPDelegation.
+ * Use `create(MCPDelegationSchema)` to create a new message.
+ */
+export declare const MCPDelegationSchema: GenMessage<MCPDelegation>;
+
/**
* AuditLogService manages audit logs for system activities and API calls.
*
diff --git a/frontend/src/types/proto-es/v1/audit_log_service_pb.js b/frontend/src/types/proto-es/v1/audit_log_service_pb.js
index 897dd4356a..3fe537ba81 100644
--- a/frontend/src/types/proto-es/v1/audit_log_service_pb.js
+++ b/frontend/src/types/proto-es/v1/audit_log_service_pb.js
@@ -16,7 +16,7 @@ import { file_v1_iam_policy } from "./iam_policy_pb";
* Describes the file v1/audit_log_service.proto.
*/
export const file_v1_audit_log_service = /*@__PURE__*/
- fileDesc("Chp2MS9hdWRpdF9sb2dfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEikAEKFlNlYXJjaEF1ZGl0TG9nc1JlcXVlc3QSLQoGcGFyZW50GAUgASgJQh3gQQL6QRcSFWJ5dGViYXNlLmNvbS9BdWRpdExvZxIOCgZmaWx0ZXIYASABKAkSEAoIb3JkZXJfYnkYAiABKAkSEQoJcGFnZV9zaXplGAMgASgFEhIKCnBhZ2VfdG9rZW4YBCABKAkiXQoXU2VhcmNoQXVkaXRMb2dzUmVzcG9uc2USKQoKYXVkaXRfbG9ncxgBIAMoCzIVLmJ5dGViYXNlLnYxLkF1ZGl0TG9nEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSK7AQoWRXhwb3J0QXVkaXRMb2dzUmVxdWVzdBItCgZwYXJlbnQYBCABKAlCHeBBAvpBFxIVYnl0ZWJhc2UuY29tL0F1ZGl0TG9nEg4KBmZpbHRlchgBIAEoCRIQCghvcmRlcl9ieRgCIAEoCRIpCgZmb3JtYXQYAyABKA4yGS5ieXRlYmFzZS52MS5FeHBvcnRGb3JtYXQSEQoJcGFnZV9zaXplGAUgASgFEhIKCnBhZ2VfdG9rZW4YBiABKAkiQwoXRXhwb3J0QXVkaXRMb2dzUmVzcG9uc2USDwoHY29udGVudBgBIAEoDBIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkilAQKCEF1ZGl0TG9nEhEKBG5hbWUYASABKAlCA+BBAxI0CgtjcmVhdGVfdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxIMCgR1c2VyGAMgASgJEg4KBm1ldGhvZBgEIAEoCRIwCghzZXZlcml0eRgFIAEoDjIeLmJ5dGViYXNlLnYxLkF1ZGl0TG9nLlNldmVyaXR5EhAKCHJlc291cmNlGAYgASgJEg8KB3JlcXVlc3QYByABKAkSEAoIcmVzcG9uc2UYCCABKAkSIgoGc3RhdHVzGAkgASgLMhIuZ29vZ2xlLnJwYy5TdGF0dXMSKgoHbGF0ZW5jeRgKIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbhIqCgxzZXJ2aWNlX2RhdGEYCyABKAsyFC5nb29nbGUucHJvdG9idWYuQW55EjYKEHJlcXVlc3RfbWV0YWRhdGEYDCABKAsyHC5ieXRlYmFzZS52MS5SZXF1ZXN0TWV0YWRhdGEihQEKCFNldmVyaXR5EhgKFFNFVkVSSVRZX1VOU1BFQ0lGSUVEEAASCQoFREVCVUcQARIICgRJTkZPEAISCgoGTk9USUNFEAMSCwoHV0FSTklORxAEEgkKBUVSUk9SEAUSDAoIQ1JJVElDQUwQBhIJCgVBTEVSVBAHEg0KCUVNRVJHRU5DWRAIIjsKCUF1ZGl0RGF0YRIuCgxwb2xpY3lfZGVsdGEYASABKAsyGC5ieXRlYmFzZS52MS5Qb2xpY3lEZWx0YSJICg9SZXF1ZXN0TWV0YWRhdGESEQoJY2FsbGVyX2lwGAEgASgJEiIKGmNhbGxlcl9zdXBwbGllZF91c2VyX2FnZW50GAIgASgJMqUDCg9BdWRpdExvZ1NlcnZpY2USxwEKD1NlYXJjaEF1ZGl0TG9ncxIjLmJ5dGViYXNlLnYxLlNlYXJjaEF1ZGl0TG9nc1JlcXVlc3QaJC5ieXRlYmFzZS52MS5TZWFyY2hBdWRpdExvZ3NSZXNwb25zZSJpiuowE2JiLmF1ZGl0TG9ncy5zZWFyY2iQ6jABgtPkkwJIOgEqWhk6ASoiFC92MS9hdWRpdExvZ3M6c2VhcmNoIigvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9hdWRpdExvZ3M6c2VhcmNoEscBCg9FeHBvcnRBdWRpdExvZ3MSIy5ieXRlYmFzZS52MS5FeHBvcnRBdWRpdExvZ3NSZXF1ZXN0GiQuYnl0ZWJhc2UudjEuRXhwb3J0QXVkaXRMb2dzUmVzcG9uc2UiaYrqMBNiYi5hdWRpdExvZ3MuZXhwb3J0kOowAYLT5JMCSDoBKloZOgEqIhQvdjEvYXVkaXRMb2dzOmV4cG9ydCIoL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vYXVkaXRMb2dzOmV4cG9ydEKqAQoPY29tLmJ5dGViYXNlLnYxQhRBdWRpdExvZ1NlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_any, file_google_protobuf_duration, file_google_protobuf_timestamp, file_google_rpc_status, file_v1_annotation, file_v1_common, file_v1_iam_policy]);
+ fileDesc("Chp2MS9hdWRpdF9sb2dfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEikAEKFlNlYXJjaEF1ZGl0TG9nc1JlcXVlc3QSLQoGcGFyZW50GAUgASgJQh3gQQL6QRcSFWJ5dGViYXNlLmNvbS9BdWRpdExvZxIOCgZmaWx0ZXIYASABKAkSEAoIb3JkZXJfYnkYAiABKAkSEQoJcGFnZV9zaXplGAMgASgFEhIKCnBhZ2VfdG9rZW4YBCABKAkiXQoXU2VhcmNoQXVkaXRMb2dzUmVzcG9uc2USKQoKYXVkaXRfbG9ncxgBIAMoCzIVLmJ5dGViYXNlLnYxLkF1ZGl0TG9nEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSK7AQoWRXhwb3J0QXVkaXRMb2dzUmVxdWVzdBItCgZwYXJlbnQYBCABKAlCHeBBAvpBFxIVYnl0ZWJhc2UuY29tL0F1ZGl0TG9nEg4KBmZpbHRlchgBIAEoCRIQCghvcmRlcl9ieRgCIAEoCRIpCgZmb3JtYXQYAyABKA4yGS5ieXRlYmFzZS52MS5FeHBvcnRGb3JtYXQSEQoJcGFnZV9zaXplGAUgASgFEhIKCnBhZ2VfdG9rZW4YBiABKAkiQwoXRXhwb3J0QXVkaXRMb2dzUmVzcG9uc2USDwoHY29udGVudBgBIAEoDBIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkizQQKCEF1ZGl0TG9nEhEKBG5hbWUYASABKAlCA+BBAxI0CgtjcmVhdGVfdGltZRgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxIMCgR1c2VyGAMgASgJEg4KBm1ldGhvZBgEIAEoCRIwCghzZXZlcml0eRgFIAEoDjIeLmJ5dGViYXNlLnYxLkF1ZGl0TG9nLlNldmVyaXR5EhAKCHJlc291cmNlGAYgASgJEg8KB3JlcXVlc3QYByABKAkSEAoIcmVzcG9uc2UYCCABKAkSIgoGc3RhdHVzGAkgASgLMhIuZ29vZ2xlLnJwYy5TdGF0dXMSKgoHbGF0ZW5jeRgKIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbhIqCgxzZXJ2aWNlX2RhdGEYCyABKAsyFC5nb29nbGUucHJvdG9idWYuQW55EjYKEHJlcXVlc3RfbWV0YWRhdGEYDCABKAsyHC5ieXRlYmFzZS52MS5SZXF1ZXN0TWV0YWRhdGESNwoObWNwX2RlbGVnYXRpb24YDSABKAsyGi5ieXRlYmFzZS52MS5NQ1BEZWxlZ2F0aW9uQgPgQQMihQEKCFNldmVyaXR5EhgKFFNFVkVSSVRZX1VOU1BFQ0lGSUVEEAASCQoFREVCVUcQARIICgRJTkZPEAISCgoGTk9USUNFEAMSCwoHV0FSTklORxAEEgkKBUVSUk9SEAUSDAoIQ1JJVElDQUwQBhIJCgVBTEVSVBAHEg0KCUVNRVJHRU5DWRAIIjsKCUF1ZGl0RGF0YRIuCgxwb2xpY3lfZGVsdGEYASABKAsyGC5ieXRlYmFzZS52MS5Qb2xpY3lEZWx0YSJICg9SZXF1ZXN0TWV0YWRhdGESEQoJY2FsbGVyX2lwGAEgASgJEiIKGmNhbGxlcl9zdXBwbGllZF91c2VyX2FnZW50GAIgASgJIlsKDU1DUERlbGVnYXRpb24SDQoFc2NvcGUYASABKAkSEAoIcmVzb3VyY2UYAiABKAkSEQoJY2xpZW50X2lkGAMgASgJEhYKDmNvcnJlbGF0aW9uX2lkGAQgASgJMqUDCg9BdWRpdExvZ1NlcnZpY2USxwEKD1NlYXJjaEF1ZGl0TG9ncxIjLmJ5dGViYXNlLnYxLlNlYXJjaEF1ZGl0TG9nc1JlcXVlc3QaJC5ieXRlYmFzZS52MS5TZWFyY2hBdWRpdExvZ3NSZXNwb25zZSJpiuowE2JiLmF1ZGl0TG9ncy5zZWFyY2iQ6jABgtPkkwJIOgEqWhk6ASoiFC92MS9hdWRpdExvZ3M6c2VhcmNoIigvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9hdWRpdExvZ3M6c2VhcmNoEscBCg9FeHBvcnRBdWRpdExvZ3MSIy5ieXRlYmFzZS52MS5FeHBvcnRBdWRpdExvZ3NSZXF1ZXN0GiQuYnl0ZWJhc2UudjEuRXhwb3J0QXVkaXRMb2dzUmVzcG9uc2UiaYrqMBNiYi5hdWRpdExvZ3MuZXhwb3J0kOowAYLT5JMCSDoBKloZOgEqIhQvdjEvYXVkaXRMb2dzOmV4cG9ydCIoL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vYXVkaXRMb2dzOmV4cG9ydEKqAQoPY29tLmJ5dGViYXNlLnYxQhRBdWRpdExvZ1NlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_any, file_google_protobuf_duration, file_google_protobuf_timestamp, file_google_rpc_status, file_v1_annotation, file_v1_common, file_v1_iam_policy]);
/**
* Describes the message bytebase.v1.SearchAuditLogsRequest.
@@ -81,6 +81,13 @@ export const AuditDataSchema = /*@__PURE__*/
export const RequestMetadataSchema = /*@__PURE__*/
messageDesc(file_v1_audit_log_service, 6);
+/**
+ * Describes the message bytebase.v1.MCPDelegation.
+ * Use `create(MCPDelegationSchema)` to create a new message.
+ */
+export const MCPDelegationSchema = /*@__PURE__*/
+ messageDesc(file_v1_audit_log_service, 7);
+
/**
* AuditLogService manages audit logs for system activities and API calls.
*
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index b337ded76a..1f587ffca9 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -19716,6 +19716,14 @@ components:
title: request_metadata
description: Metadata about the request context.
$ref: '#/components/schemas/bytebase.v1.RequestMetadata'
+ mcpDelegation:
+ title: mcp_delegation
+ description: |-
+ 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.
+ readOnly: true
+ $ref: '#/components/schemas/bytebase.v1.MCPDelegation'
title: AuditLog
additionalProperties: false
description: Audit log entry recording system activity or API call.
@@ -26111,6 +26119,42 @@ components:
title: LogoutRequest
additionalProperties: false
description: Request to logout current user session.
+ bytebase.v1.MCPDelegation:
+ type: object
+ properties:
+ scope:
+ type: string
+ title: scope
+ description: |-
+ The OAuth2 grant's consented scope, e.g. "mcp:read-only".
+ Empty when the grant recorded no scope.
+ resource:
+ type: string
+ title: resource
+ description: |-
+ The grant's stored MCP resource URI.
+ Empty for pre-grant legacy sessions.
+ clientId:
+ type: string
+ title: client_id
+ description: |-
+ The OAuth2 client the grant was consented to.
+ Empty for legacy web-session tokens at /mcp.
+ correlationId:
+ type: string
+ title: correlation_id
+ description: |-
+ 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.
+ title: MCPDelegation
+ additionalProperties: false
+ description: |-
+ Provenance of a call that reached the API through the MCP (Model Context
+ Protocol) server's delegated credential. The values are copied verbatim from
+ the verified credential's grant state; empty fields record that the grant
+ stored nothing (legacy sessions), never a resolved or synthesized value.
bytebase.v1.MaskingExemptionPolicy:
type: object
properties:
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 6ba2be9ddf..a10e1a44bd 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -37,6 +37,7 @@
- [store/audit_log.proto](#store_audit_log-proto)
- [AuditLog](#bytebase-store-AuditLog)
+ - [MCPDelegation](#bytebase-store-MCPDelegation)
- [RequestMetadata](#bytebase-store-RequestMetadata)
- [AuditLog.Severity](#bytebase-store-AuditLog-Severity)
@@ -841,6 +842,28 @@ 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. |
+
+
+
+
+
+
+<a name="bytebase-store-MCPDelegation"></a>
+
+### MCPDelegation
+Provenance of a call that reached the API through the MCP (Model Context
+Protocol) server&#39;s delegated credential. The values are copied verbatim from
+the verified credential&#39;s grant state; empty fields record that the grant
+stored nothing (legacy sessions), never a resolved or synthesized value.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| 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. |
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index 2d80ff76aa..b399f317d4 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -306,6 +306,10 @@
<a href="#bytebase.store.AuditLog"><span class="badge">M</span>AuditLog</a>
</li>
+ <li>
+ <a href="#bytebase.store.MCPDelegation"><span class="badge">M</span>MCPDelegation</a>
+ </li>
+
<li>
<a href="#bytebase.store.RequestMetadata"><span class="badge">M</span>RequestMetadata</a>
</li>
@@ -2909,6 +2913,66 @@ Some fields are omitted because they are too large or contain sensitive informat
<td><p>Metadata about the operation. </p></td>
</tr>
+ <tr>
+ <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>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
+ <h3 id="bytebase.store.MCPDelegation">MCPDelegation</h3>
+ <p>Provenance of a call that reached the API through the MCP (Model Context</p><p>Protocol) server's delegated credential. The values are copied verbatim from</p><p>the verified credential's grant state; empty fields record that the grant</p><p>stored nothing (legacy sessions), never a resolved or synthesized value.</p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>scope</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The OAuth2 grant&#39;s consented scope, e.g. &#34;mcp:read-only&#34;.
+Empty when the grant recorded no scope. </p></td>
+ </tr>
+
+ <tr>
+ <td>resource</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The grant&#39;s stored MCP resource URI.
+Empty for pre-grant legacy sessions. </p></td>
+ </tr>
+
+ <tr>
+ <td>client_id</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The OAuth2 client the grant was consented to.
+Empty for legacy web-session tokens at /mcp. </p></td>
+ </tr>
+
+ <tr>
+ <td>correlation_id</td>
+ <td><a href="#string">string</a></td>
+ <td></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>
+ </tr>
+
</tbody>
</table>
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index abb6da1ddb..49598787ae 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -291,6 +291,7 @@
- [AuditLog](#bytebase-v1-AuditLog)
- [ExportAuditLogsRequest](#bytebase-v1-ExportAuditLogsRequest)
- [ExportAuditLogsResponse](#bytebase-v1-ExportAuditLogsResponse)
+ - [MCPDelegation](#bytebase-v1-MCPDelegation)
- [RequestMetadata](#bytebase-v1-RequestMetadata)
- [SearchAuditLogsRequest](#bytebase-v1-SearchAuditLogsRequest)
- [SearchAuditLogsResponse](#bytebase-v1-SearchAuditLogsResponse)
@@ -5104,6 +5105,7 @@ Audit log entry recording system activity or API call.
| latency | [google.protobuf.Duration](#google-protobuf-Duration) | | The duration of the operation. |
| service_data | [google.protobuf.Any](#google-protobuf-Any) | | Service-specific metadata about the request, response, and activities. |
| request_metadata | [RequestMetadata](#bytebase-v1-RequestMetadata) | | Metadata about the request context. |
+| mcp_delegation | [MCPDelegation](#bytebase-v1-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. |
@@ -5146,6 +5148,27 @@ Response message for exporting audit logs.
+<a name="bytebase-v1-MCPDelegation"></a>
+
+### MCPDelegation
+Provenance of a call that reached the API through the MCP (Model Context
+Protocol) server&#39;s delegated credential. The values are copied verbatim from
+the verified credential&#39;s grant state; empty fields record that the grant
+stored nothing (legacy sessions), never a resolved or synthesized value.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| 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. |
+
+
+
+
+
+
<a name="bytebase-v1-RequestMetadata"></a>
### RequestMetadata
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 4d81453641..71909a969b 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -1282,6 +1282,10 @@
<a href="#bytebase.v1.ExportAuditLogsResponse"><span class="badge">M</span>ExportAuditLogsResponse</a>
</li>
+ <li>
+ <a href="#bytebase.v1.MCPDelegation"><span class="badge">M</span>MCPDelegation</a>
+ </li>
+
<li>
<a href="#bytebase.v1.RequestMetadata"><span class="badge">M</span>RequestMetadata</a>
</li>
@@ -14710,6 +14714,15 @@ Some fields may be omitted if they are too large or contain sensitive informatio
<td><p>Metadata about the request context. </p></td>
</tr>
+ <tr>
+ <td>mcp_delegation</td>
+ <td><a href="#bytebase.v1.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>
+ </tr>
+
</tbody>
</table>
@@ -14818,6 +14831,57 @@ to retrieve the next page of log entities. </p></td>
+ <h3 id="bytebase.v1.MCPDelegation">MCPDelegation</h3>
+ <p>Provenance of a call that reached the API through the MCP (Model Context</p><p>Protocol) server's delegated credential. The values are copied verbatim from</p><p>the verified credential's grant state; empty fields record that the grant</p><p>stored nothing (legacy sessions), never a resolved or synthesized value.</p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>scope</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The OAuth2 grant&#39;s consented scope, e.g. &#34;mcp:read-only&#34;.
+Empty when the grant recorded no scope. </p></td>
+ </tr>
+
+ <tr>
+ <td>resource</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The grant&#39;s stored MCP resource URI.
+Empty for pre-grant legacy sessions. </p></td>
+ </tr>
+
+ <tr>
+ <td>client_id</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>The OAuth2 client the grant was consented to.
+Empty for legacy web-session tokens at /mcp. </p></td>
+ </tr>
+
+ <tr>
+ <td>correlation_id</td>
+ <td><a href="#string">string</a></td>
+ <td></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>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
<h3 id="bytebase.v1.RequestMetadata">RequestMetadata</h3>
<p>Metadata about the incoming request.</p>
diff --git a/proto/store/store/audit_log.proto b/proto/store/store/audit_log.proto
index dcdd0553b8..15316a6519 100644
--- a/proto/store/store/audit_log.proto
+++ b/proto/store/store/audit_log.proto
@@ -45,6 +45,11 @@ 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.
+ MCPDelegation mcp_delegation = 12;
+
enum Severity {
SEVERITY_UNSPECIFIED = 0;
DEBUG = 1;
@@ -67,3 +72,27 @@ message RequestMetadata {
// This information is not authenticated and should be treated accordingly.
string caller_supplied_user_agent = 2;
}
+
+// Provenance of a call that reached the API through the MCP (Model Context
+// Protocol) server's delegated credential. The values are copied verbatim from
+// the verified credential's grant state; empty fields record that the grant
+// stored nothing (legacy sessions), never a resolved or synthesized value.
+message MCPDelegation {
+ // The OAuth2 grant's consented scope, e.g. "mcp:read-only".
+ // Empty when the grant recorded no scope.
+ string scope = 1;
+
+ // The grant's stored MCP resource URI.
+ // Empty for pre-grant legacy sessions.
+ string resource = 2;
+
+ // The OAuth2 client the grant was consented to.
+ // Empty for legacy web-session tokens at /mcp.
+ string client_id = 3;
+
+ // 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.
+ string correlation_id = 4;
+}
diff --git a/proto/v1/v1/audit_log_service.proto b/proto/v1/v1/audit_log_service.proto
index fe6aaabc04..69c5c5af35 100644
--- a/proto/v1/v1/audit_log_service.proto
+++ b/proto/v1/v1/audit_log_service.proto
@@ -186,6 +186,11 @@ message AuditLog {
// Metadata about the request context.
RequestMetadata request_metadata = 12;
+ // 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.
+ MCPDelegation mcp_delegation = 13 [(google.api.field_behavior) = OUTPUT_ONLY];
+
// Severity level for audit log entries.
enum Severity {
// Unspecified severity level.
@@ -224,3 +229,27 @@ message RequestMetadata {
// This is supplied by the client and is not authenticated.
string caller_supplied_user_agent = 2;
}
+
+// Provenance of a call that reached the API through the MCP (Model Context
+// Protocol) server's delegated credential. The values are copied verbatim from
+// the verified credential's grant state; empty fields record that the grant
+// stored nothing (legacy sessions), never a resolved or synthesized value.
+message MCPDelegation {
+ // The OAuth2 grant's consented scope, e.g. "mcp:read-only".
+ // Empty when the grant recorded no scope.
+ string scope = 1;
+
+ // The grant's stored MCP resource URI.
+ // Empty for pre-grant legacy sessions.
+ string resource = 2;
+
+ // The OAuth2 client the grant was consented to.
+ // Empty for legacy web-session tokens at /mcp.
+ string client_id = 3;
+
+ // 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.
+ string correlation_id = 4;
+}