Enforcing Governed Data Access for AI Agents Through Postgres Roles and MCP Tool Contracts
Postgres roles limit what agents read, and MCP contracts limit what they ask.

To govern data access for AI agents on Supabase, two layers are needed: Postgres roles that limit which data agents can read and MCP tool contracts that limit what they can ask for. Agents should access the database only through named operations exposed by an MCP server. For analytical workloads, a governed copy keeps agent queries off production, but it needs its own access rules because production row-level security does not follow data when it is exported.
Why MCP's missing access control model makes database-level governance unavoidable
MCP is often explained through the analogy of a standard connector. It provides a common connection between systems, but a standard connector does not decide which data a connected device may read. Anthropic created MCP and announced it on November 25, 2024, giving agents a standardized interface to databases, file systems, and APIs. That interface solves an integration problem. Its tools, resources, and prompts describe available actions, data, and templates without supplying the organization’s data access policy.
Whatever role-based access control governs an agent must be built or bought by the organization deploying it. Without that work, the effective policy becomes whatever the service account behind the tool permits. A tool described as doing little can still use a connection with broad privileges. Governance needs an enforcement point beneath the protocol, where the permissions apply regardless of how a request was phrased.
What Postgres role-based access control actually enforces, and what it does not
Postgres is that enforcement point, using GRANT, row-level security, and column-level permissions. The recommended baseline is a dedicated login role for each agent, with neither superuser privileges nor BYPASSRLS, and SELECT granted only on needed columns. Role-level statement and connection timeouts bound resource use. Separate roles also preserve attribution and allow one agent’s access to be revoked without affecting others.
Standard RLS exempts the table owner from row policies, so enabling RLS alone does not establish the intended boundary for a connection using the owning role. FORCE ROW LEVEL SECURITY closes that owner exemption on every table the agent can reach. It does not replace the restricted role.
Read-only configuration also contains less visible gaps. The default_transaction_read_only and statement_timeout settings establish only the session’s default behavior. A SECURITY DEFINER function introduces another path because it executes with its definer’s privileges. An otherwise read-only role can still trigger writes through an accessible function. Effective restrictions therefore depend on grants and function access.
Even when RLS enforces a policy correctly, the inputs to that policy must be trusted. If an agent can influence app.tenant_id through a tool argument, prompt injection can turn a permitted request into access under the wrong tenant context. Postgres may then enforce the policy exactly as written while using an attacker-influenced identity value.
What an MCP tool contract governs that Postgres permissions cannot
An MCP tool contract governs the request before it becomes a query. It defines which operations exist, which parameters they accept, which values come from verified context, and which result shapes they return. Postgres permissions answer which rows and columns are readable. The contract answers which questions the agent can ask. A bounded operation exposes a narrower capability than a general-purpose database query tool, even when both use the same restricted role.
The connection setup must obtain tenant context from the verified token, never from a tool argument supplied by the model. This separates a request’s subject from its authority. The agent may supply the analytical parameters it is allowed to use without choosing whose identity is used to evaluate them. The same distinction applies to role selection, which must follow verified identity.
Contracts also govern the meaning of returned data. A column called revenue_usd does not explain whether the business uses ARR, gross revenue, or net revenue for a particular question. An explicit metric definition removes that choice from the model. When dashboards, reports, and agents consume the same governed definition, their calculations share a source. The contract exposes that definition instead of inviting the agent to invent business math.
This is application-layer control, but definition differs from filtering. A filter tries to reject an unacceptable request, while a bounded contract establishes the permitted operation and its inputs in advance. That explicit surface makes the intended behavior auditable. Fan et al.’s martingale analysis of MCP agents found linear growth in cumulative distortion across sequential tool calls and substantial reductions from semantic weighting of responses. The finding supports giving a model governed meaning before it starts to interpret results.
How the two layers interact to close the gaps neither covers alone
The layers form a system when identity binds them together. The MCP layer opens a database connection under a restricted role selected from the verified session identity. It sets tenant context from the verified token before executing a query. Postgres then applies GRANT and RLS independently of the tool’s description. The contract constrains the available request, while the database constrains what execution can reach.
Each layer protects against a different failure. A contract that excludes agent-supplied tenant context blocks the prompt-injection path before query execution. If another contract check fails, a database role with the right restrictions still limits access under its RLS policy. That second protection works only if the tenant context stays trusted. A policy that uses a session variable controlled by the model cannot serve as an independent safeguard.
Connection limits set for each role keep an agent from holding too many database connections, while controls in the tool can handle multiple agents hitting rate limits at reset. Limits on result shapes help keep large result sets from using up memory. These controls govern different parts of the request path. Database permissions alone do not define a bounded response, and a bounded response alone does not limit connection use.
Audit joins the two views of an operation. Tool-call records show what the agent requested, while database query logs show what executed. OpenTelemetry traces link those records from invocation through execution, so governance can be tracked along the whole path. Neither view is complete on its own. Together, they distinguish an overly broad request from overly broad execution and make the boundary inspectable.
How to let AI agents query Supabase data without direct production access
Supabase supports the database side through native Postgres RLS. Its policies place row filtering in the database rather than duplicating substantial permission logic across applications. Analytical agents, however, need not query that production instance. Pre-modeled metrics can live in governed Parquet datasets queried through DuckDB and exposed by a single MCP server. This provides analytical separation without requiring a separate warehouse or dedicated data team.
The copy becomes a separate enforcement boundary. Production RLS remains on Supabase, but its policies do not follow data into Parquet. The analytical datasets need their own access rules, and the MCP server must give consistent access to permitted datasets, metric definitions, and scheduled reports.
Server choice depends on the workload as well as protocol compatibility. The Supabase MCP server is a concrete option for operational observability, covering health, security, performance, and resources. Its query_logs tool provides structured access to logs across API, Auth, Storage, Edge Functions, and Postgres. Supabase’s performance monitoring agent connects using project_ref and read_only=true. It observes long-running sessions, query execution-time regressions, and Performance Advisor findings without creating indexes, rewriting queries, or canceling sessions.
Governed business analytics requires a different scope from operational monitoring. The relevant MCP server must expose bounded metric operations, enforce the analytical copy’s permissions, and support consistent auditability. For B2B SaaS teams, the minimum metric set includes CAC, LTV, monthly churn, ARR, and gross margin. Each needs clear calculation logic that both people and agents use. An observability tool’s read-only setting does not, by itself, provide those business definitions.
Even with analytical separation, teams still need to see how production is running. Instrumentation should cover database CPU and memory usage, active connections, connection pool saturation, query latency, slow queries, replication lag, WAL growth, and storage usage from day one. Supabase Studio’s built-in tiles are too coarse to diagnose connection spikes or replication lag at scale. Those measurements reveal pressure that permission checks do not.
What breaks when teams skip one layer or implement both incorrectly
The first common failure is a mismatch between policy and credentials. A shared admin connection with BYPASSRLS renders row policies ineffective, regardless of how carefully those policies were written. It also collapses agent attribution into one account. A contract in front of that connection leaves security dependent on application correctness. One injection or logic error can reach everything the underlying role permits.
A model allowed to read revenue_usd still lacks the business definition needed to interpret it correctly. RLS cannot distinguish a valid metric calculation from a plausible but incorrect one. Read-only access also leaves room to infer sensitive facts from permitted columns.
Read-only roles may still reach privileged functions, and unbounded connection use can degrade production for human users. In Supabase analytical architectures, another version of the same error is assuming an exported dataset retains production RLS. Diagnosing these failures requires locating where each restriction actually executes. A control that exists only in a tool description or on the source database cannot protect an ungoverned copy.
RLS alone can suffice for simple read-only cases. That narrower claim does not cover metric semantics, privileged function access, or workload limits. Adding these controls later also creates more audit work, especially when existing application queries assume no row filtering. Early governance avoids making those assumptions part of the application’s behavior. Completeness here means closing identifiable gaps.
Building the governance layer in practice without leaving gaps in the sequence
This work should start before the MCP server is opened to agents. Create one dedicated login role per agent without superuser privileges or BYPASSRLS, scope SELECT to required columns, and set connection and statement timeouts. Enable FORCE ROW LEVEL SECURITY on reachable tables. Audit accessible SECURITY DEFINER functions and revoke or rewrite those that can write. Verify that tenant context comes only from the verified session token.
Next, separate analytical work from production query paths. For Supabase teams, pre-modeled Parquet datasets queried through DuckDB provide the governed copy described above. Define ARR, churn, CAC, LTV, and gross margin once in the data layer with explicit calculation logic. Apply the copy’s access rules independently of production RLS.
The contract can then name bounded operations. “Get monthly churn for the authenticated tenant’s account” defines a more precise capability than “query the database.” The parameters accepted from an agent must be kept separate from the values supplied through verified context. Metric definitions and synonyms belong in contract metadata so that the agent receives governed semantics with the data. Finalizing this surface before granting access prevents an open-ended query capability from becoming the default.
MCP tool-call logs and Postgres query logs should connect through OpenTelemetry traces, with corresponding auditability for the analytical path. Fan et al.’s research recommends re-grounding at intervals during multi-step interactions to help control errors. Pre-calculated, versioned metrics give agents a stable reference for that purpose.


