Row-Level Security Enforcement for AI Agents Querying Supabase Through an MCP Analytics Server
Safe agent access to Supabase takes scoped roles, not RLS alone.

For AI agents that query Supabase through an MCP analytics server, Row-Level Security holds only when the credentials, the way queries are built, and the data made available all enforce the same boundaries. The safer architecture exposes pre-modeled, governed analytics datasets through MCP rather than giving agents direct access to production tables. RLS is still essential, but it also needs limits on database privileges, controls on how tools run, and a way to audit each query.
Why RLS alone is not a complete security model for AI agents querying Supabase
A poisoned support ticket instructed an agent to SELECT from integration_tokens and INSERT the results back into the visible ticket thread. The attacker then read the secrets in the support UI. No zero-day or MCP server compromise was involved. Supabase’s account says a development credential had more privileges than it needed and was still in use when the agent gained access to production data.
The incident exposes the gap between enabling a policy and enforcing it. A table can have RLS enabled while the credential executing a query bypasses every policy on it. Even where policies apply, they govern permitted database access. Permission is not proof of legitimate intent.
How MCP sits between an AI agent and your Supabase database
An MCP server sits between the AI client and the database resource. The client may use Claude, GPT, or Gemini, while the resource is Supabase or Postgres. The server holds credentials and executes tool calls. In this analytics architecture, it also translates agent requests into database queries and determines which capabilities the agent can invoke.
That separation keeps the connection string or key out of the LLM’s context. The model gets tool descriptions and structured results instead. But a hidden credential still has the same authority. A supabase_query tool respects RLS only when the role presented to Postgres is subject to those policies.
The protocol exposes capabilities through tools, resources, and prompts, but those interfaces do not establish database permissions. The June 2025 MCP revision formalized servers as OAuth resource servers. The July 2026 specification’s removal of the initialize handshake makes the protocol stateless. These changes affect how the protocol works and handles authentication, while developers still have to enforce the rules in the database.
The credential choice that determines whether RLS fires at all
The service_role key bypasses all Row Level Security policies unconditionally. The anon key operates within those policies. This is the decisive credential distinction for agent sessions. A server using service_role does not gain row isolation merely because its target tables have RLS enabled.
The MCP server documentation reserves the service role key for schema migrations and administrative tasks, placing agent sessions that interact with user data outside its intended scope. The practical rule is therefore direct. Use the anon key or a dedicated least-privilege role, never service_role, for those sessions. For production analytics workloads, a dedicated read-only role scoped to the required tables and schemas is the stricter recommended pattern.
Credential selection must change before development convenience becomes production exposure. The documented incident took that same path, as a service role credential stayed in use beyond development. Credential maintenance also requires a separate decision. Rotate service role keys at least quarterly, or immediately if exposure is suspected, instead of leaving the initial configuration in place for good.
What RLS governs and what it cannot touch
RLS governs row-level access for SELECT, INSERT, UPDATE, and DELETE. It determines which rows a permitted operation can affect. DDL commands such as DROP TABLE or ALTER TABLE are governed by the connecting role’s Postgres privileges, which allow a role authorized to perform them to destroy schemas even where row policies apply.
The boundary is between rows and operations. RLS supplies multi-tenant isolation by limiting the rows a user or agent can access, while role privileges restrict what that connection can do at all. For agent connections, those privileges must exclude DROP, ALTER, and TRUNCATE. Both controls must be set up with care because each does a job the other cannot do.
This distinction also limits what “read-only” should mean in an agent design. Restricting the agent’s instructions to analytics is not a database permission. A SELECT-only role establishes that restriction at the database boundary, where an unexpected tool request cannot turn a stated preference into write or schema authority.
How prompt injection defeats RLS enforcement at the query construction layer
The support-ticket attack crossed a different boundary before it reached Postgres. Text the attacker controlled entered the agent’s context as ticket content, then became instructions for later tool calls. The ticket spelled out the steps to take, first reading integration_tokens and then posting its contents in the thread.
The credential already permitted the requested access. The attack therefore redirected an authorized connection. This is the “lethal trifecta” of private-data access, autonomous tool use, and untrusted content in the prompt. A support ticket, form submission, or comment field can supply that content without giving the attacker control of the MCP server.
Correctly scoped credentials reduce the reachable data, but they do not establish the purpose of every query. An agent may still be redirected toward permitted rows that its legitimate task did not require. The structural weakness is the LLM’s inability to reliably distinguish trusted instructions from imperative text embedded in user data.
The MCPTox benchmark, identified as arXiv:2508.14925, tested tool poisoning across 20 LLM agents. It found that more capable models are often more susceptible because the attack exploits precise instruction-following. Greater model capability still requires an enforcement boundary, and the finding supports only a qualified relationship between capability and susceptibility.
MCP also has no message signing, no standard way to identify each agent, and no way to detect tampering with tool definitions. OAuth 2.1 authenticates the client or user, but does not convey agent identity or delegation chains. Frameworks that fetch tools at runtime inherit those gaps. RLS can reject an unauthorized row request, but it cannot protect against every harmful request from a correctly credentialed, misdirected agent.
Defense-in-depth controls that make RLS enforcement actually hold
Give an analytics agent a SELECT-only role scoped to an isolated schema such as ai_accessible, with private and auth schemas outside its view. Writes require a separate approval decision. Grant them only after testing the specific operations, confirming their RLS policies, and enabling audit logging.
At the schema layer, restrict privileges directly in Postgres rather than relying on tool descriptions to discourage destructive commands. Keep agent roles from using DROP, ALTER, and TRUNCATE. Schema isolation then narrows the agent’s reachable surface. A misdirected query cannot read a sensitive table that the connecting role has no authority to access.
At the query and content layer, preprocess user-controlled text to flag or strip imperative commands before it reaches an agent with SQL privileges. Keep manual approval turned on for each tool call. Supabase warns against “Always Approve” settings and visibility attacks involving tool calls rendered off-screen. Its testing also found that wrapping results with instructions not to follow embedded commands is insufficient by itself.
At the output layer, treat agent-generated content as untrusted before any write to a data store. Validate that proposed writes do not include content sourced from sensitive tables. Blocking INSERT removes the primary exfiltration channel used in the ticket incident. Output validation addresses publication of data, which is distinct from permission to read it.
At the environment layer, Supabase recommends development databases, staging environments, branched databases, or obfuscated or anonymized datasets. Environment choice limits what a failure can expose. Teams controlling the full stack, including the LLM, can also consider CaMeL, or CApabilities for MachinE Learning, to separate untrusted data from control and data flows.
How can AI agents query governed Supabase metrics without touching production tables?
A pre-modeled analytics layer gives agents a governed view of the data in place of access to the production database itself. The agent queries pre-calculated datasets in a read-optimized format, with sensitive tables excluded from its reachable surface. Credential management, query filtering, and output controls no longer have to compensate for exposing the full operational database.
The architectural preference is a governed analytics layer, followed by a narrowly isolated read-only schema where direct querying is necessary. Broad access to production tables creates the greatest enforcement burden. The relevant MCP server criteria are therefore concrete, including scoped credentials, a restricted dataset surface, consistent metric definitions, and query-level auditability. Protocol compatibility alone does not establish any of those properties.
Headless analytics separates metric definitions from the interfaces that consume them. ARR, churn, and CAC are defined once in a centralized layer and exposed through MCP or an API. A dashboard, Slack report, and AI agent then all use the same pre-approved business logic. Repeatable queries return consistent, predefined results rather than requiring the model to construct its own business math.
Restricting an agent to receiving a pre-calculated metric result keeps authorship of the underlying definition in the centralized layer, providing both analytical and protective constraints. Supabase’s agents solution page presents RLS as a governance primitive for tenant boundaries. A governed analytics layer built on Postgres extends that primitive without requiring the agent to touch production schemas.
Observability: knowing when enforcement is working and when it is not
Correct configuration is not the same as confirmed enforcement. Without query-level visibility, a wrong credential, unexpected schema access, or misdirected request can remain invisible until damage occurs. Database metrics taken as a whole cannot reliably tell what agents do apart from ordinary application traffic. A connection spike or slow query needs context before it indicates an agent-specific problem.
Client-side trace propagation supplies that context by correlating agent calls with API Gateway and Edge Function logs under a shared trace_id. This makes agent activity auditable at the query level. Monitor active connections and connection pool saturation because agent workloads can spike both. Query latency and slow queries can also reveal a misdirected request touching unindexed tables.
Log all MCP queries and alert on unexpected table access instead of watching only for signs of poor performance. A SELECT on integration_tokens by the MCP role should trigger an immediate alert.
Supabase’s agents solution page connects RLS, database audit logs, and SOC 2 Type II certification in its governance stack. In the implementation, permissions set the limits and traces show what actually happens. Neither substitutes for the other. Enforcement and observability are both required.
A practical enforcement checklist for Supabase teams building agent analytics
For credentials, give the MCP server its own least-privilege role and keep service_role out of sessions that work with user data. Default to SELECT-only access. Add per-table writes only after operation-specific RLS tests and audit logging are in place, and set service role key rotation to at least quarterly, with immediate rotation upon suspected exposure.
For schema configuration, isolate accessible data in a governed schema such as ai_accessible and exclude private and auth schemas. Deny schema-destructive operations through Postgres privileges. Index tenant-id columns on frequently queried tables because indexing, rather than RLS overhead, is the dominant query-performance lever.
For query handling, preprocess user-controlled input before it reaches the SQL-capable agent. Require manual approval of tool calls. Keep “Always Approve” disabled and validate all model output before writing it to a data store.
When deploying, choose development, staging, or branched databases instead of production unless every preceding layer has extremely strict controls. Choose governed datasets when analytics need data from production. Enable audit logging on every reachable table, alert on queries outside the expected schema, and correlate traces to separate agent traffic from application traffic.


