Row-Level Access Policies and Query Scoping for Supabase-Backed MCP Metric Endpoints

Secure agent access to metrics requires RLS policies and endpoint-level scoping.

· 9 min read
Cover illustration for “Row-Level Access Policies and Query Scoping for Supabase-Backed MCP Metric Endpoints”
MCP Data Infrastructure · October 29, 2026 · 9 min read · 1,949 words

Governed data access for AI agents on Supabase via MCP requires a layered boundary. Agents should get pre-modeled metrics through a single audited MCP server and have no direct access to the production database. Where an endpoint queries Supabase, the caller’s JWT must reach Postgres row-level security policies, while endpoint-level scoping limits the columns, queries, and tools available to the agent.

Why MCP metric endpoints create a new kind of access control problem

MCP turns an agent from a passive reader into an autonomous caller. A tool invocation can execute a query against a live Postgres metrics table, and the agent can repeat that invocation without a person reviewing each request. This changes the consequences of an authorization mistake. A misconfigured endpoint is not just an opportunity for one unintended read, but a repeatable route into data outside the agent’s assigned scope.

Supabase exposes Postgres through PostgREST, so the database authorization context determines what those requests can retrieve. Sending a request through an MCP server does not, on its own, filter rows or stop access across tenants. The effective boundary runs from JWT identity through RLS policy evaluation to the filtered result returned as an MCP resource. Every link must preserve the calling identity’s scope.

What RLS actually does at the Postgres layer, and why that matters for agents

Postgres RLS attaches SQL boolean expressions to a table and applies them as implicit query filters. Each row must pass the applicable policy. For a metrics table with a tenant_id column, a tenant-ownership policy compares that column with the tenant identified in the caller’s JWT. Rows belonging to another tenant are excluded regardless of whether the request originated in an application or an MCP tool.

Enforcement begins with ENABLE ROW LEVEL SECURITY on the table. Without an applicable policy, ordinary API access is denied. FORCE ROW LEVEL SECURITY extends enforcement to table owners, which is relevant when server-side code connects as an owner. It does not turn service-role access into a tenant-scoped path.

Read and write policies perform different jobs. USING filters existing rows for SELECT, UPDATE, and DELETE, while WITH CHECK validates proposed row values for INSERT and UPDATE. Updates need both forms of control, particularly when agents write computed results back to metric tables. Supabase supplies identity through auth.uid(), which reads the JWT’s sub claim, and auth.jwt(), which exposes the claims object. Multiple permissive policies for the same operation combine with OR logic, so a separate broad policy can admit rows that the tenant policy would exclude.

The default-exposure risk that catches Supabase teams by surprise

An exposed table without RLS has no row-level filter to keep tenants apart. Public-schema tables available through the API with an anon or publishable key can expose their rows when RLS is absent, a risk that is easy to miss during development. A successful metric response proves only that the endpoint can retrieve data.

The more dangerous shortcut is initializing the agent-facing Supabase client with the service role key. That key intentionally bypasses RLS for administrative operations. Using it to avoid policy complexity gives agent queries an unfiltered path across the metrics table, including rows belonging to other tenants.

Google Cloud Vertex AI’s “Double Agents” finding from early 2026 illustrates the broader failure category. A compromised agent was able to misuse the default permission scoping for AI service agents to reach cloud resources beyond its intended scope. The connection to Supabase is permissive authorization. Schema audits can expose one part of that risk by joining pg_class to pg_namespace and finding public-schema tables where relrowsecurity = false. The worst signal, however, is silence, because a misconfigured endpoint returns data without an authorization error.

Building the JWT-to-policy scoping chain for a metric endpoint

Diagram: The JWT-to-Row Scoping Chain. Visualizes: Illustrate the end-to-end authorization chain that must stay intact for a governed MCP metric endpoint: Agent → MCP Server (Authorization header with JWT) → PostgREST (decodes JWT, exposes…

The core pattern places the agent’s tenant and role in signed JWT custom claims. Those claims belong in server-controlled app_metadata, where the policy can read them without querying a roles table for every candidate row. The token becomes the scope-bearing credential. The MCP server must pass it as the Authorization header on the Supabase request.

PostgREST decodes the JWT and makes its identity and claims available through auth.uid() and auth.jwt() for the statement. The policy then evaluates those values against the metrics rows. For a table named metrics, the minimal tenant-scoped read policy is CREATE POLICY tenant_metrics_select ON metrics FOR SELECT TO authenticated USING (tenant_id = (auth.jwt() -> 'app_metadata' ->> 'tenant_id')::uuid);. This assumes RLS is enabled on the table. The resulting rows become the MCP resource returned to the agent.

The expression auth.jwt() -> 'app_metadata' ->> 'role' reads a role that the server assigned from the same claims object, so the policy needs no permission-table lookup. An admin role can support a separate policy for cross-tenant reads in internal dashboards. Because permissive policies combine with OR logic, that override is an explicit expansion of access. That override should be kept separate from the ordinary agent scope.

TO authenticated names the database role that the policy applies to and skips checks that anonymous callers do not need. Separate policies for SELECT, INSERT, UPDATE, and DELETE are easier to test and audit as their requirements diverge. For a read-only metric endpoint, a SELECT policy without write policies makes the intended constraint enforceable at the database layer.

Performance failures that make RLS policies dangerous at query time

A logically correct policy can still become operationally unsafe. Repeated agent calls amplify the cost of authentication functions and permission subqueries evaluated for every row. The symptom may be p95 query latency spikes without errors. That degradation creates pressure to remove checks or fall back to service-role access, making policy performance part of keeping the authorization boundary intact.

Simple checks of who owns a row should start as inline policies. For checks based on user identity, (select auth.uid()) allows Postgres to evaluate and reuse the value at statement level. Columns used in policy predicates also need indexes. A tenant filter without an index on tenant_id can force a full table scan, so even a compact expression can become expensive on a large metrics table.

More complex permission logic needs measured optimization. EXPLAIN ANALYZE on production-sized data distinguishes an acceptable inline check from a correlated subquery whose cost grows with the rows examined. Checks involving three or more tables, such as organization membership through org_members, are candidates for a SECURITY DEFINER function whose result can be evaluated once. Reused permission logic or unacceptable query times also justify considering that pattern. Enforcement must hold up under load, and query latency, active connections, and connection pool saturation show whether the endpoint can keep up.

Query scoping beyond RLS: what the policy layer cannot do alone

RLS controls which rows a caller can access. It does not answer which columns the agent needs, which queries it should construct, or whether an aggregation represents the intended metric. Column-level GRANT statements provide another boundary by restricting selectable columns. Internal cost basis, margin, and raw transaction IDs can be kept from a caller who is allowed to see the row that holds them.

A certified KPI view or pre-calculated metrics table gives the agent defined columns and consistent metric meanings. Raw transactional tables leave the agent to assemble its own aggregations, even when RLS correctly filters every row. That freedom produces metric drift when different queries calculate “revenue” from different underlying fields. Pre-modeling therefore constrains interpretation as well as query cost.

An agent’s workflow should receive only the metric endpoints it requires. OWASP LLM Top 10 names this broader category in its 2025 entry LLM06, “Excessive Agency,” covering excessive functionality, permissions, or autonomy. Narrower claims address permissions, while narrower MCP tool definitions reduce available functionality. Neither substitutes for the other.

Atlan’s governed MCP server pattern illustrates query-time governance beyond row filtering. Its access policy engine filters the asset results, and each asset it returns comes with ownership, lineage, and access classifications. For Supabase-backed metrics, this points to a governed data layer that keeps agents away from production tables. Pre-modeled datasets in governed Parquet files, queried through DuckDB and exposed through a single MCP server, provide that separation. Where live Supabase queries remain necessary, JWT-preserving access, tenant RLS, restricted columns, and workflow-specific tools are the criteria for the MCP interface.

Testing RLS policies so misconfiguration cannot reach production

Policy tests must reproduce the role and claims that the agent will actually use. A successful query in the Supabase dashboard SQL Editor does not establish that boundary because its execution context bypasses RLS. Each policy needs a test with an identity that should pass and one that should fail, and the rows returned must match what each test expects.

The client SDK provides one route to that calling context. A transaction-based test provides another by opening a transaction, using set_config to populate request.jwt.claims, and applying SET LOCAL ROLE authenticated. The test then executes an allowed query and checks its rows, followed by a denied query that must return zero rows. Rolling back leaves no test data behind. The role switch and claims must be present together, because either one alone fails to reproduce the agent’s authorization context.

For a metric endpoint, tenant A’s agent must see only tenant A’s rows, and tenant B’s agent must see only tenant B’s rows. Tenant A must also fail to update or delete data when the endpoint is read-only. The anon role should see nothing. A separate service-role test should return all rows, demonstrating the administrative bypass while keeping it outside the agent path.

Negative tests should also check where a caller’s authority comes from. A policy reading role from user_metadata trusts a user-writable value, allowing callers to supply the very privilege the policy is meant to verify. Reading it from server-writable app_metadata avoids that specific escalation path. Tests must also check proposed values in write operations, role bindings, and permission checks that rely on related tables. Reading a policy’s text alone cannot show whether those dependencies deny access when they should.

Observability as the ongoing enforcement layer for metric endpoint security

A tested policy can become ineffective after a schema or workload change. A migration may introduce an exposed table without RLS, while a new query pattern may turn an acceptable permission check into an expensive operation. Visibility must continue after deployment. Query-level observation at the MCP endpoint is also needed to detect an agent calling tools outside its intended scope.

Supabase’s Metrics API is compatible with a monitoring system and provides relevant operational signals, including p50 and p95 query latency, active connections, and connection pool saturation. Slow query identification helps connect degradation to the statements behind an endpoint. A p95 spike warrants investigation for repeated per-row policy work, rather than an assumption that authorization is functioning efficiently because requests still succeed. Connection pressure adds context when autonomous calls accumulate faster than the database can complete them.

Schema exposure needs a deterministic gate as well. Every CI pipeline that touches the schema should run the public-schema detection query for relrowsecurity = false. An empty result is the pass condition. A non-empty result should block deployment so newly exposed tables cannot reach production without the intended row-level boundary.

Streaming paths require attention to their enforcement limits. Supabase Realtime respects RLS for INSERT and UPDATE events, delivering them only for rows the client can select, but RLS is not applied to DELETE events. Correct table policies therefore govern live KPI additions and updates without establishing the same guarantee for deletions. That distinction belongs in verification of the endpoint.

The boundary built by RLS and query scoping is trustworthy only while it is continuously verified. A governed data layer that pre-models metrics and exposes them through a single audited MCP server makes that verification tractable. A patchwork of ad-hoc queries does not.

More in MCP Data Infrastructure