A database tool can be technically read-only and still expose sensitive rows, overload a primary instance, or let one application team inspect another team’s systems.

TL;DR

  • Problem: Deploying a shared Model Context Protocol (MCP) server with a broadly privileged service account or trusting readOnlyHint tool labels turns AI diagnostics into a cross-project data leak and primary-load hazard.
  • Answer: Enforce caller-scoped IAM database identities, PostgreSQL role-level timeouts (statement_timeout, lock_timeout) and SELECT-only grants on read replicas, parameterized tools.yaml queries, and human-in-the-loop (HITL) approval for all mutations.
  • Watch out: MCP readOnlyHint annotations are explicitly untrusted metadata, LIMIT 100 does not prevent a multi-million-row sequential scan, and PostgreSQL’s default_transaction_read_only can be overridden in-session unless write privileges are revoked.

Every call needs an enforceable boundary

Situation

A shared database platform can give engineers a consistent way to discover instances, inspect health metrics, investigate slow queries, and verify backup readiness. Model Context Protocol (MCP) standardizes how an AI client discovers and invokes those tools through a structured JSON-RPC interface. Yet the model, the MCP server, the cloud identity used by the tool, and the PostgreSQL role executing the query remain four separate security boundaries.

Google documents a Cloud SQL remote MCP service with distinct toolsets spanning read-only and administrative operations, alongside self-hosted options such as Google’s open-source MCP Toolbox for Databases. The availability of a managed or self-hosted MCP endpoint does not automatically make it safe for production customer data. Platform teams must decide how caller identity propagates, which tables and views are reachable, how query work is bounded, and where human approval is mandatory.

The Problem

A shared MCP server running every tool call under a single broadly privileged service account becomes an immediate cross-project escalation path. Worse, security teams frequently assume that restricting an agent to “read-only” SQL eliminates operational risk, overlooking four concrete failure modes.

Constraint 1: Untrusted MCP metadata and prompt injection. Per MCP security guidance, tool annotations such as readOnlyHint are advisory hints that clients must treat as untrusted metadata. Furthermore, tools/list descriptions and retrieved database content—such as user-entered comments, error logs, or pg_stat_activity query strings—sit inside the model’s context window. A malicious or compromised row can embed instructions that coerce the model into invoking another permitted tool or exfiltrating sensitive fields.

Constraint 2: LIMIT does not bound database CPU or I/O. Wrapping an arbitrary AI-generated query with LIMIT 100 does not stop PostgreSQL from performing a full sequential scan, a multi-gigabyte hash join, or an unindexed ORDER BY sort across millions of rows before returning the first 100 results. Without server-side statement_timeout, lock_timeout, and target isolation (routing diagnostics to read replicas or Cloud Monitoring APIs rather than the write primary), a single diagnostic prompt can trigger primary latency spikes.

Constraint 3: default_transaction_read_only is not an access control. Setting default_transaction_read_only = ON on a PostgreSQL role prevents accidental INSERT, UPDATE, or DELETE statements by default, but a session can override it with SET TRANSACTION READ WRITE unless the role’s actual table and schema write privileges are revoked. Real read-only enforcement requires explicit SELECT grants limited to approved schemas and views, excluding PII tables and sensitive system views.

Constraint 4: Audit attribution and log secret leakage. When an MCP server pools connections under one static database user, pgAudit and Cloud SQL logs lose the identity of the human engineer who triggered the query. Conversely, logging raw SQL query text and full result payloads into centralized observability pipelines copies credentials, bind parameters, and customer PII into secondary storage with weaker access controls.

Read-only labels fail without identity, query, and injection boundaries

How can a database platform make AI-assisted diagnostics fast and useful without converting a shared MCP server into a shared production credential?

Options Considered

Platform teams adopting MCP for database operations typically evaluate four architectural patterns.

OptionIdentity & ScopeQuery & Load SafetyChange ControlPrimary Rejection or Selection Reason
Shared SA + Arbitrary SQLSingle broad service accountUnbounded ad-hoc SQLMixed read/write toolsRejected: cross-project data exposure and primary scan risk
Autonomous Admin MCPBroad cloud IAM permissionsCan alter flags, IAM, failoverAgent-driven mutationsRejected: prompt injection or hallucination can cause outage
Cloud SQL Remote MCPCaller IAM DB auth + Data APIBounded by IAM DB user grantsSeparate admin toolsetsViable when IAM DB roles and project IAM are strictly scoped
Parameterized MCP Toolbox + HITLCaller OIDC/IAM + read-only DB roleFixed SQL templates + timeoutsMandatory human approvalRecommended for strict row, schema, and workload governance

Running a shared MCP server with one high-privilege service account and an arbitrary run_sql tool is the fastest prototype to build, and the fastest way to fail a security review. Because the server accepts a project or instance name from the prompt, any user who can reach the MCP endpoint can enumerate sibling projects unless the server implements an independent authorization engine.

Granting an autonomous agent access to administrative MCP tools—such as modifying database flags, rotating IAM bindings, or triggering failovers—violates change-management boundaries. Even if the model intends to fix an incident, an injected instruction or misdiagnosed lock chain can turn a slow query into a multi-minute failover outage.

Google’s Cloud SQL remote MCP server enforces a concrete baseline for execute_sql_readonly: it requires the Cloud SQL Data API, IAM database authentication, and an IAM database user, executing queries strictly under that database user’s PostgreSQL privileges. This works well for teams that already maintain granular per-user IAM database roles and want zero proxy infrastructure to manage.

For stricter environments, a self-hosted MCP Toolbox for Databases paired with a policy gateway provides the strongest control. By pointing sources at a read replica with a database role that holds only SELECT grants, and exposing parameterized postgres-sql tools in tools.yaml, the platform eliminates arbitrary SQL generation while enforcing caller-scoped OIDC/IAM checks and requiring an out-of-band HITL approval token for any state-changing operation.

Scoped caller identity and parameterized tools beat shared SQL proxies

Put Identity and Policy Around Every Tool Call

A governed MCP architecture places four enforceable control planes around every diagnostic and operational request.

Governed MCP architecture enforces policy before and inside PostgreSQL

Preserve the caller’s authorization boundary

Every tool invocation must resolve to an authenticated caller principal, an authorized Google Cloud project and instance, and a narrowly scoped database identity. Never trust a project_id or instance_id string supplied in the LLM prompt as authorization. Either propagate the caller’s OAuth/IAM credential directly (as in Cloud SQL’s IAM database authentication model) or validate the caller’s group membership against an explicit resource allowlist before issuing a short-lived token. When using a policy gateway in front of MCP Toolbox, map each caller group to a distinct PostgreSQL role rather than collapsing all engineers onto one shared reader role; otherwise, pg_stat_activity and pgAudit cannot distinguish which team ran a query. Deny requests immediately when ownership or scope cannot be verified.

Start with bounded, parameterized tools

Begin with non-row diagnostic tools—instance inventory, backup and PITR status, Cloud Monitoring CPU/connection metrics, and flag configuration—before exposing SQL execution. When SQL diagnostics are required, prefer parameterized tools.yaml definitions with readOnly: true over open-ended SQL tools:

kind: source
name: orders-replica-ro
type: cloud-sql-postgres
project: ${GCP_PROJECT_ID}
region: us-central1
instance: orders-prod-replica
database: orders
# Read-only is enforced by the database role and replica, not by a source flag (see the role settings below)
---
kind: tool
name: inspect_active_locks
type: postgres-sql
source: orders-replica-ro
description: "List active PostgreSQL lock waits exceeding 1 second."
statement: |
  SELECT pid, state, wait_event_type, wait_event, now() - query_start AS duration
  FROM pg_stat_activity
  WHERE wait_event_type = 'Lock' AND now() - query_start > interval '1 second'
  ORDER BY duration DESC LIMIT 25;

On the PostgreSQL side, harden the diagnostic role itself so timeouts and read-only defaults apply automatically to every new session:

ALTER ROLE "[email protected]" SET default_transaction_read_only = ON;
ALTER ROLE "[email protected]" SET statement_timeout = '30s';
ALTER ROLE "[email protected]" SET lock_timeout = '5s';

Verify role configuration via SELECT rolname, rolconfig FROM pg_roles, and grant SELECT only on approved diagnostic views or non-PII tables. Remember that ALTER ROLE ... SET takes effect on the next new connection, not on already-open pooled sessions.

Treat tool output as untrusted input

Assume that any text returned from pg_stat_activity, application log tables, or row comments could contain prompt-injection payloads. The AI client must treat tool outputs strictly as data, never as authority to invoke additional tools or elevate scope. Minimize returned columns before they reach the model context, and verify your model provider’s data-retention and zero-training settings before sending production telemetry.

In the audit pipeline, record the caller principal, tool name, target instance, authorization decision, and execution outcome. Redact query bind parameters and row payloads from audit logs, and enforce a bounded retention window so diagnostic traces do not become a shadow database.

Keep changes behind an explicit workflow

Separate diagnostic recommendations from database mutations cleanly. If an agent identifies a missing index, a connection-pool saturation issue, or a flag change, it can draft a Terraform pull request or a parameterized change proposal—never execute ALTER SYSTEM or gcloud sql instances patch autonomously. Bind any human approval to the exact target instance, operation, and parameters (for example, by hashing the approved payload and verifying the hash at execution time) so an approved action cannot be replayed against a different resource or altered between review and execution. Record both the original diagnostic session ID and the approver’s identity in the change audit log.

How It Rolls Out

Rolling out governed database MCP tools should follow four progressive stages, each gated by concrete verification tests and an instant rollback switch.

Roll out MCP tools from metadata inventory to bounded SQL and HITL

Stage 1: Inventory and telemetry tools only

Deploy MCP tools that query Cloud SQL Admin API metadata, backup status, and Cloud Monitoring time series. Zero PostgreSQL connections or row-level data are exposed. Verify that engineers can only list instances in projects where they hold explicit IAM viewer permissions.

Stage 2: Bounded SQL against read replicas

Enable parameterized read-only SQL tools (or Cloud SQL’s execute_sql_readonly) targeting read replicas rather than the write primary. Enforce IAM database authentication, statement_timeout = '30s', lock_timeout = '5s', and SELECT-only grants on non-PII schemas. Confirm via pg_roles and pg_stat_activity that the caller’s mapped IAM identity appears in PostgreSQL logs.

Stage 3: Adversarial staging acceptance suite

Before onboarding production teams, run six mandatory negative tests in staging:

  1. Cross-project enumeration attempt using a prompt-supplied project ID.
  2. Query targeting a restricted PII schema using a valid diagnostic IAM role.
  3. Deliberately expensive CROSS JOIN or unindexed sort to verify statement_timeout cancellation.
  4. Oversized result set to verify row/byte truncation before hitting the model context.
  5. Table row containing an embedded prompt-injection string instructing the agent to call another tool.
  6. Request to modify a database flag or IAM role without an HITL approval token.

Every denial must happen at the enforcing layer (IAM, gateway, or PostgreSQL), not merely because the LLM politely declined.

Stage 4: Bound HITL change workflows

Introduce change-proposal tools (such as opening a Git PR for Terraform or SQL migrations) only after Stages 1–3 pass audit review. Rollback at any stage is immediate and non-disruptive: disable the MCP server endpoint or revoke the diagnostic IAM database role without affecting live application traffic.

In Practice

Google’s Cloud SQL MCP reference documentation provides a clear, testable enforcement boundary: execute_sql_readonly requires Data API access and IAM database authentication, and it executes SQL statements using the privileges of the authenticated IAM database user. Platform teams can verify this behavior directly in staging by running the exact same prompt under two different IAM identities—one granted SELECT on orders_summary and one denied—and confirming PostgreSQL returns permission denied for the second identity.

Similarly, Google’s MCP Toolbox for Databases shows how parameterized postgres-sql tools eliminate ad-hoc SQL generation. Combined with PostgreSQL’s documented ALTER ROLE behavior—where default_transaction_read_only, statement_timeout, and lock_timeout apply at session startup—teams can enforce defense-in-depth at the database engine itself rather than relying on LLM prompt instructions.

Where It Breaks

ConditionBreaks howDetectMitigate
Shared service account used by MCP serverPrompt-supplied project ID exposes sibling teams’ DBsAudit log shows one SA for all callersPropagate caller OIDC/IAM identity; enforce project allowlist
Trusting readOnlyHint as a security controlUnverified server or tool poisoning triggers writes/leaksTool metadata audit failsEnforce SELECT-only PostgreSQL grants on a read replica
LIMIT 100 on unindexed diagnostic queryFull table scan saturates primary CPU/IOPSpg_stat_activity shows long active scanRoute to replica; set statement_timeout = '30s' on role
default_transaction_read_only without REVOKESession runs SET TRANSACTION READ WRITEUnexpected write error or mutationGrant SELECT only; revoke INSERT/UPDATE/DELETE/DDL
Tool output contains prompt injectionAgent attempts unauthorized follow-up tool callUnexpected tool-call sequence in traceTreat outputs as untrusted data; gate mutations with HITL
Approval token not bound to exact payloadApproved flag change runs against wrong instanceAudit mismatch between approval and targetBind HITL signature to project, instance, and operation hash
Caller identity dropped at MCP proxypgAudit records generic proxy user onlyIncident trace cannot identify human actorUse per-caller IAM DB auth and propagate correlation ID
Raw SQL binds and rows written to logsSecrets or PII leak into observability indexLog DLP scan flags sensitive patternsRedact query parameters and payloads; bound log retention

Ungoverned MCP tools fail via shared credentials, heavy reads, and injection

Key Takeaways

  • Never treat a “read-only” tool name or MCP readOnlyHint annotation as an authorization boundary; enforce security in IAM, PostgreSQL grants, and server-side timeouts.
  • Eliminate shared high-privilege service accounts in MCP servers; propagate caller identity (via IAM database authentication or scoped OIDC tokens) so every query maps to an accountable principal.
  • Protect write primaries by routing diagnostic MCP tools to read replicas or Cloud Monitoring APIs and setting statement_timeout and lock_timeout at the PostgreSQL role level.
  • Prefer parameterized tools.yaml queries over arbitrary SQL execution, and revoke all write privileges rather than relying solely on default_transaction_read_only = ON.
  • Treat all retrieved database rows, comments, and query strings as untrusted input, and require a payload-bound human-in-the-loop workflow for every infrastructure or schema change.

What to Do Next

  • Problem: Identify the top recurring database diagnostic questions and classify which require metadata only versus row-level SQL access.
  • Solution: Deploy caller-scoped inventory tools first, followed by parameterized read-only SQL tools targeting replicas with IAM DB auth and role-level timeouts.
  • Proof: Pass all six adversarial staging tests—cross-project enumeration, denied schema, expensive scan timeout, output truncation, prompt injection, and unapproved mutation—with denials enforced outside the LLM.
  • Action: Configure ALTER ROLE ... SET statement_timeout and SELECT-only grants for your diagnostic IAM roles, and assign owners for MCP policy, audit redaction, and tool versioning this week.

Sources to Verify