Access Control Primitives That Actually Govern What AI Agents Can Ask of Supabase
Four layers of access control work together to safely govern what AI agents can query in Supabase.

Governed data access for AI agents on Supabase via MCP requires four layers working together, namely Row Level Security, narrow Postgres role grants, scoped agent credentials, and proxy-level guardrails. An MCP connection alone is not an access-control perimeter. To serve governed metrics without direct production database access, teams can also serve pre-modeled datasets through MCP, so agents get consistent answers within a set boundary.
Why AI agents make the existing Supabase security model insufficient on its own
Coding agents create tables through SQL rather than the Supabase dashboard, and those tables can enter service without RLS enabled. That distinction creates a gap before the first query runs. An autonomous process can create schema, issue SQL, and act without a human reviewing each operation, while the platform’s defaults were designed for human developers and authenticated end-users.
When agents, scripts, and background jobs use the same connection string, database logs cannot show which agent ran a query. An accessible service-role key compounds the problem because it bypasses row policies entirely. Supabase for Agents names RLS and an MCP server as agent-security primitives, but available features are not a configured stack. The missing work is to bind identity, permissions, row policies, and query interception into one boundary.
Primitive 1: Row Level Security — what it enforces, what it defaults to, and where it silently does nothing
RLS attaches policies to tables and applies them as implicit WHERE clauses to queries. Enabling it is only the first step. Once enabled, its default is deny-all, so policies must grant access before ordinary callers can read or change rows. This is a safe starting state, but teams can mistake activation for a finished configuration and discover the missing policies only when requests fail in production.
USING controls which existing rows a caller can see or modify, while WITH CHECK validates new or changed values on INSERT and UPDATE. SELECT, INSERT, UPDATE, and DELETE each need policies that cover them. Policy composition also changes the result. Any single permissive policy can grant access, while restrictive policies must all pass in addition to at least one permissive policy.
For unauthenticated requests, auth.uid() returns null, so an ownership comparison with user_id does not pass. A null check makes it clear why the request is rejected. Specifying the target role, such as TO authenticated, also avoids unnecessary policy evaluation for anonymous callers and removes ambiguity about whom the policy covers. Policies also need to name the agent-specific roles they cover, since an ownership expression alone cannot do that.
Performance is part of making that boundary usable. Policies evaluate rows, and without an index on the filtered column, typically user_id, Postgres can run a sequential scan that becomes prohibitive at a million rows. The (select auth.uid()) pattern allows the identity value to be evaluated once and cached for reuse across rows. SECURITY DEFINER helpers can improve recursive or multi-table permission checks, but are unnecessary for simple ownership checks. None of these optimizations changes RLS’s scope, which excludes column selection, result-size limits, and requirements that queries contain filters.
Primitive 2: Postgres role grants — table and column-level access as the layer beneath RLS
A grant permits a Postgres role to access a table, while RLS restricts the rows available within that permission. Both layers need explicit configuration. For agents, the recommended pattern is a dedicated role with narrow grants rather than the broad authenticated role or an admin role. Automation tools should never get admin-level roles, because their permissions must have limits whatever queries they generate.
Postgres can grant SELECT on an explicit column list rather than the whole table, preventing access to password hashes, billing details, or internal flags. An agent may legitimately need a customer’s permitted row without needing every field stored in it, so column grants close an exposure that a correct row policy leaves open.
By default, a Postgres view runs with its creator’s rights, which can bypass policies on the underlying tables. On Postgres 15 and higher, security invoker makes the view use the querying role’s rights instead. Attribution needs an equally deliberate choice. A named role for each agent or agent class lets teams trace database activity back to it, while a shared connection string hides who did what when teams look into an incident.
Primitive 3: JWT claims and API key scoping — establishing agent identity before the database sees the query
The service-role key must never appear in client code or an environment an agent can read. It bypasses RLS entirely, so careful row policies offer no protection to requests using it. The anon key exposes the opposite configuration failure. When RLS is off, it can permit read and write access across public-schema tables, making a missing policy boundary especially consequential.
JWT custom claims provide a way to establish the agent’s role before policy evaluation. Storing that role in app_metadata replaces repeated queries to a roles table with a token read by Postgres. This also reduces repeated work during row evaluation. Schema isolation narrows the available surface further, with an MCP or API connection restricted to a schema such as ai_accessible rather than private schemas, the auth schema, or internal configuration.
Supabase MCP Server setup guidance describes OAuth through a browser-based flow as the default authentication method. Personal access tokens are used for CI/CD or other non-interactive scenarios instead. The guidance also describes tokens as scoped by default to specific projects and permissions, rather than automatically inheriting the developer’s full permissions. Those permissions can include schema changes, data access, and project configuration. MCP authentication must therefore be assessed by its actual scope.
Primitive 4: Proxy-level guardrails — intercepting queries that the database cannot judge for intent
A valid identity with correct grants and row policies can still issue an unsafe query. An agent with read access can load every permitted customer record into model context, while one with update access can modify every permitted row if its query lacks a filter. These requests may satisfy database permissions while exceeding the operator’s intended task.
A proxy adds an interception point before execution. It inspects statements travelling to the database and result sets travelling back, allowing rules to block unconstrained UPDATE or DELETE operations, SELECT without LIMIT on sensitive tables, table drops, and other destructive patterns. It can also redact returned values and hold high-impact actions for human approval. By contrast, pgaudit records statements after execution, and IP allowlists verify network origin rather than the safety of commands from an accepted connection.
Logging the agent identity, the data asset, the timestamp, and the entitlement used adds details that RLS alone does not record. A proxy or MCP-layer Data Loss Prevention tool can also enforce attribute-based access control for PII-classified data both when a dataset is registered and at query time. These controls translate parts of the intended operating boundary into enforceable rules on queries and returned data.
Prompt injection as the attack that makes all four primitives necessary simultaneously
Prompt injection can turn permitted data into an instruction channel. Malicious text in a support ticket, comment, or other user-supplied field can persuade an agent to issue queries its operator never requested. The attack has been documented and can be reproduced. Only a minority of documented consumer-agent cases have built-in protections, while builder platforms mostly leave developers to put guardrails in place. The team that deploys the agent is still responsible for setting and enforcing its boundary.
A pivot to a SQL-created table without RLS can expose unrestricted rows, while extraction of an accessible service-role key can bypass policies on protected tables. Broad column privileges allow a widened SELECT list to reveal sensitive fields. Without an intercepting guardrail, a destructive UPDATE or DELETE can execute before human review.
Layering limits what a redirected agent can accomplish. Row policies restrict its records, grants restrict its objects and fields, credential scoping prevents a switch to broader authority, and proxy rules constrain dangerous statement patterns. A successful prompt injection must not be treated as permission to cross any of those boundaries.
How to stack the four primitives into a coherent perimeter rather than four independent checklists

The practical configuration begins by defining a narrow Postgres role for each agent class and granting only the required tables and columns. RLS then limits which rows the agent can use within that object-level scope. The agent’s JWT establishes the role through app_metadata, and the proxy checks requests and responses while recording attributed access. Runtime authentication happens before the query reaches these database checks. The layers must use the same agent identity and permissions so that each enforces the same rules.
To close the coding-agent gap, the recommended pattern is an event trigger that enables RLS when a table is created. New tables then begin in a controlled state. Every public-schema table needs RLS and policy coverage for its operations, including tables created through SQL. Restricting the agent-facing connection to ai_accessible, or an equivalent isolated schema, further removes private tables from its query surface. That isolation means teams have less need to make every private table’s settings fit for agent access.
The minimum viable configuration also excludes admin and service roles from agent execution, removes the service-role key from accessible environments, and limits column privileges to needed fields. Named roles preserve attribution at the agent or agent-class level. The proxy or MCP guardrail must block unconstrained bulk operations and log access with agent identity and timestamp. Together, these requirements define a usable perimeter rather than four separate declarations that security features are enabled.
That perimeter still has a limit in scope. RLS filters rows rather than intent, and context governance extends beyond whether a statement is permitted to execute. Teams are starting to need controls that act before data enters model context, version context bundles, and apply classification labels. The proxy is the closest bridge within this stack, but it addresses those needs only partially. A further question is whether permitted data gives the agent a consistent basis for answering.
How can governed metrics be exposed without letting agents touch production Supabase tables?
Correct access control does not make a metric definition consistent. An agent with permitted read access to production Postgres can still calculate “monthly active users” differently depending on how its question is phrased. A semantic layer addresses that separate problem by defining the data and calculations an agent consumes, rather than merely deciding which raw records it may retrieve.
A governed data layer serves pre-calculated metrics from modeled, Parquet-backed datasets queryable through DuckDB. Exposing those datasets through a single MCP endpoint separates the agent’s question from the production database and gives humans and agents the same metric definitions. In this architecture, the access-control perimeter surrounds the governed layer itself, rather than relying only on policies attached to a live production schema.
For Supabase teams, the pattern keeps Postgres as the data home, uses governed Parquet datasets for analytics, and makes MCP the agent-facing interface. It is a no-ETL approach without a separate warehouse or new infrastructure, intended to provide fast, accurate, inexpensive-to-query context without direct production-query exposure. The four primitives govern what agents may ask, while the modeled data layer governs what the resulting answers mean.


