Exposing Supabase Metrics to AI Agents Through a Typed MCP Tool Registry
A typed MCP registry gives agents governed Supabase metrics without raw SQL.

Expose Supabase metrics to AI agents through an MCP server that offers typed tools over governed, pre-calculated metrics. This architecture separates metric definitions from agent reasoning and keeps agents away from production tables. Its reliability comes from combining a stable data contract, upstream calculation, and scoped read-only access.
Why agents querying Supabase directly is an architectural problem, not just a risk
A Supabase agent integration can appear to work until its numbers disagree with the finance team’s report. The SQL executes, and the answer looks plausible. Yet when asked for MRR, it may add up raw subscription rows, skip discounts, double-count trials, or use a different date filter. Without a governed definition, the agent must reconstruct business logic from the schema, which cannot tell it whether its interpretation matches the organization’s accounting rules.
This is an architectural problem. Direct access combines data retrieval with decisions about what the data means. A Survey of AI Agent Protocols identifies the absence of standardized access patterns as a barrier to reliable use of external data. Standardization helps establish the connection, but that connection still needs a defined boundary between retrieving a metric and inventing its calculation.
Supabase’s underlying Postgres database serves transactional workloads, while analytical queries can introduce connection spikes, slow scans, and unpredictable load. More scheduled agents amplify that exposure without resolving the ambiguity in their calculations. Both problems begin at the same boundary, where the agent receives raw data rather than a governed representation prepared for its use.
What MCP actually standardizes and why that matters for data access specifically
MCP gives agents and servers a shared contract for discovering and invoking capabilities. Anthropic open-sourced the protocol in November 2024. It uses JSON-RPC 2.0 and exposes three primitives, which are Tools for callable functions, Resources for readable data, and Prompts for reusable templates. A metrics registry primarily uses Tools because the agent needs to request a defined calculation with defined inputs.
Instead of building a separate connection for every pairing of application and data source, each side implements the protocol. A tool’s input schema says which arguments it accepts, and its description explains when to call it. In a typed metrics registry, the return schema also specifies the response structure, giving the agent a contract.
Authentication remains on the server side of that boundary. Models do not need database credentials in their context. MCP also lets connections stay open across interactions, which helps when a workflow needs several tool calls. However, the protocol does not supply a business definition for MRR or decide which records a caller may read. Those controls belong to the server and the governed data layer.
Why typing and pre-calculation together solve the metric accuracy problem
Typing establishes the shape of a metric, while pre-calculation establishes its meaning. A typed response can guarantee fields for a value, period, and currency without guaranteeing that the value follows the finance team’s definition. If the calculation varies between requests or changes with the underlying table schema, a well-formed response can still contain the wrong answer.
Pre-calculation removes that interpretation from the agent’s task. The exact treatment of discounts in MRR, the date window for churn, and the deduplication rule for active users are encoded upstream. The agent retrieves the result. This creates one place where the upstream definition can be governed and corrected.
The reverse limitation applies to an untyped cached number. A figure without a clear contract leaves the agent guessing whether it is monthly or daily, gross or net, or inclusive of trials. The tool description supplies those semantic distinctions, while the return schema exposes the corresponding fields. A number alone is not a metric contract.
To calculate MRR, a raw SQL tool asks the agent to choose subscription rows, filters, and aggregation logic before interpreting the result. A typed get_mrr() tool returns the governed figure with its period and currency, and every caller gets the result of the same upstream calculation. When the definition changes, the correction belongs in that shared calculation rather than in each agent’s instructions, dashboard query, or report.
How do you structure governed Supabase access through a typed MCP registry?
The implementation follows a layered design, with Supabase/Postgres feeding pre-modeled metrics and an MCP server exposing only the relevant tools. For a team building this pattern, FastMCP provides the Python registration mechanism described here. Each tool should wrap one metric or a group of metrics that belong together, with no way to pass in arbitrary SQL.
In FastMCP, the @mcp.tool() decorator registers the function, and its type hints define the input schema. A representative signature is get_mrr(as_of: date) -> MRRResult, with MRRResult defined as a Pydantic model containing typed fields for period, value, currency, and calculation_method. The docstring becomes the discoverable tool description. It should name MRR, state the governed calculation’s treatment of subscriptions, discounts, and trials, and identify the period requested through as_of.
The same pattern works for database health metrics. Supabase exposes raw observability inputs including pg_stat_statements, active connections relative to max_connections, cache hit ratios, WAL volume, and replication lag. These should feed materialized views or a Parquet export, so an agent’s question does not trigger system-table queries each time. A typed health-check tool can encode active connections past 80% of max_connections as a threshold.
Access restrictions sit below the tool descriptions. The server configuration should use read_only=true with a read-only Postgres user, project_ref=<id> to restrict access to one project and disable account-level tools, and features=<groups> to enable only relevant capabilities. These controls restrict project scope and tool availability. They do not, by themselves, establish row-level authorization, so a server’s suitability for that requirement cannot be inferred from its MCP interface alone.
Scheduled agents then become prompts and schedules over the same registry. The proposed cadence is hourly health checks and performance reviews, daily security reviews, and resource tracking each morning. A query_logs pattern can support error-rate and latency tools through read-only queries over a bounded time window, including aggregation and joins. The registry’s output contract remains narrower than the underlying log query capability.
The context overhead problem that emerges as the registry grows
Loading every tool schema into the agent’s prompt consumes context and makes tool selection harder. Even a moderate server can contribute tens of thousands of tokens when all descriptions and schemas are included. Some providers also limit how many tools an agent can receive in one context.
As a large-ecosystem reference, MCP-Zero: Active Tool Discovery for Autonomous LLM Agents documents comprehensive tool ecosystems exceeding 248.1k tokens under full schema injection. The study demonstrates active discovery, in which an agent requests capabilities as it encounters gaps.
ScaleMCP: Dynamic and Auto-Synchronizing Model Context Protocol Tools for LLM Agents offers a retrieval-based response to the same problem. Its agent first calls a retrieval tool to find relevant tools in an auto-synchronizing index that treats MCP servers as the source of truth. This adds a hop but reduces schema overhead. For a Supabase registry, the practical response is to group business metrics, observability metrics, and security events, then use scoped feature flags or retrieval to load only what the task requires.
Why read-only is necessary but not a complete security answer
Read-only access prevents database writes, but it does not prevent disclosure. A general-purpose read-only SQL executor therefore exposes more information than a tool that returns a defined aggregate. The distinction is between restricting operations and restricting the information made available through them.
The MCP specification defines readOnlyHint and destructiveHint as annotations. It explicitly requires clients to treat annotations from an untrusted server as untrusted. A compromised or replaced server can advertise read-only behavior without providing it. Database permissions must enforce the restriction no matter what the tool’s description says.
Even when read-only access is enforced, the content it returns can carry prompt injection. A support ticket, comment, or profile row can contain customer-controlled instructions intended to redirect the agent after retrieval. If that agent can also read sensitive records, its output becomes a possible exfiltration path. The database remains unchanged throughout the interaction.
Pre-aggregated typed tools remove this particular path through raw customer text. A get_mrr() tool returning a numeric value does not expose the instructions embedded in a support_tickets row. Structs that hold governed values, dates, and server-defined metadata leave far less room for that kind of injection. This is a narrower claim than complete security, because authentication, privilege containment, and the sensitivity of the metrics themselves still require controls.
A metric tool should return only the information it needs for its role, even if a read-only database account can read more. The protocol survey identifies injection resistance and privilege containment as distinct security concerns.
Error accumulation across sequential tool calls and why it reinforces pre-calculation
An imprecise tool response can distort every reasoning step that depends on it. Information Fidelity in Tool-Using LLM Agents: A Martingale Analysis of the Model Context Protocol finds that cumulative distortion grows linearly with bounded deviations in its theoretical framework. The same analysis reports an 80% reduction through semantic weighting and identifies periodic re-grounding as the most effective error-control mechanism. These findings concern sequential tool use within the analysis’s framework.
Pre-calculated metrics provide a structural form of re-grounding. Each call to get_mrr() returns to the governed source rather than deriving a new figure from an earlier agent response. The data layer therefore interrupts one route by which errors propagate. Tools returning raw rows leave aggregation inside the agent workflow, where an imprecise intermediate result can become the basis for later conclusions. For registry design, this reinforces the preference for computed aggregates over agent-side calculation.
What this architecture means for teams that grow beyond a single agent
If agents, dashboards, and reports each calculate the same KPI on their own, they can give different answers that all look right. A governed registry gives them one contract to share. Adding a new agent then means connecting it to existing definitions rather than teaching it to reconstruct the organization’s business logic.
The interface need not remain exclusive to agents. The same metric can support a scheduled tool call, a dashboard, or a Slack report, with the governed layer serving as the common authority. A change to a calculation propagates through that layer to consumers without separate integration work. For founders without a dedicated data team, a pre-modeled registry centralizes definition work that would otherwise spread across queries and spreadsheets, although the definitions still need to be established.
ScaleMCP illustrates how the discovery layer can preserve that consistency as tools change. Its synchronization pipeline uses create, read, update, and delete operations to keep the tool index in step with MCP servers. That mechanism keeps the registry up to date, while metric governance is a separate task. Together, a maintained index and a governed calculation layer let more consumers share the same numbers without making the agent responsible for deciding what those numbers mean.


