MySQL’s performance_schema and sys views answer most latency, lock, and index-efficiency questions without touching application tables—provided you block the raw literal columns that quietly cache customer PII.

TL;DR

  • Problem: Many teams grant SELECT ON *.* for “read-only monitoring,” or expose raw performance_schema tables (QUERY_SAMPLE_TEXT, SQL_TEXT) that store un-normalized literals containing PII and indirect prompt injections.
  • Answer: Create a dedicated diagnostics schema (diag_views) exposing normalized DIGEST_TEXT and sys telemetry only, grant only SELECT ON diag_views.* (never PROCESS, which exposes other sessions’ raw SQL) with zero application table grants, and prefer managed telemetry APIs (RDS Performance Insights / Cloud SQL Insights) where available.
  • Watch out: max_execution_time applies strictly to read-only SELECT statements (and is ignored if a stored function modifies data), and CONNECTION_ADMIN bypasses read_only = ON.

Expose performance_schema and sys views without exposing user data

Situation

On-call engineers increasingly pair LLM agents with MySQL MCP servers to triage production incidents: identifying top-latency queries, finding unindexed table scans, inspecting InnoDB lock waits, and checking buffer-pool pressure. Unlike application agents that query tenant data (Post 4), a database diagnostic agent has no operational reason to read a single row from users, orders, or payments.

Yet in practice, diagnostic agents frequently receive GRANT SELECT ON *.* because operators equate “read-only” with “safe.” That shortcut violates least privilege and expands the lethal trifecta (Post 1). Even worse, teams that correctly avoid granting SELECT on application schemas often grant SELECT ON performance_schema.* without realizing that MySQL 8.0 and 8.4 store raw, un-normalized SQL strings—including inline email addresses, tokens, and user-submitted text—inside specific columns and history tables.

Across self-managed MySQL on EC2, AWS RDS for MySQL, and Google Cloud SQL for MySQL, the diagnostic surface and privilege ceiling differ meaningfully, requiring a clear boundary between telemetry and data.

The Problem

Separating MySQL diagnostics from user data fails when teams overlook where MySQL stores query text, how privileges interact with read_only, and how managed clouds restrict administrative grants.

MySQL diagnostics cross three boundaries where literals leak PII

Four concrete constraints govern MySQL diagnostic boundaries in MySQL 8.0 and 8.4:

  1. DIGEST_TEXT is normalized, but QUERY_SAMPLE_TEXT and SQL_TEXT leak raw literals (TB-2 to TB-3). In performance_schema.events_statements_summary_by_digest, DIGEST_TEXT replaces literals with ? (SELECT * FROM users WHERE email = ?). However, MySQL 8.0+ also populates QUERY_SAMPLE_TEXT in that same table with a raw, un-normalized sample query for EXPLAIN analysis. Similarly, events_statements_current, events_statements_history, and events_statements_history_long store raw SQL_TEXT. If any upstream service builds SQL with inline string literals instead of prepared statements, those columns cache customer PII—and potential indirect prompt injection payloads—directly inside performance_schema.
  2. PROCESS and SHOW_ROUTINE expose cross-session metadata (TB-2). The global PROCESS privilege allows a user to inspect threads executed by all other users via SHOW PROCESSLIST or Performance Schema processlist tables (note that in MySQL 8.4, INFORMATION_SCHEMA.PROCESSLIST and performance_schema_show_processlist are deprecated in favor of Performance Schema-backed thread evaluation). Meanwhile, SHOW_ROUTINE lets a role view the source code of every stored procedure and function regardless of DEFINER. Granting SHOW_ROUTINE to an agent unnecessarily exposes proprietary business logic.
  3. read_only = ON does not stop privileged roles, and max_execution_time has blind spots (TB-2). When read_only = ON is set on a replica, accounts holding CONNECTION_ADMIN (or the deprecated SUPER) can still execute writes. Furthermore, SET SESSION max_execution_time = 5000 only terminates read-only SELECT statements; if a SELECT invokes a stored function with data-modifying side effects, max_execution_time is ignored.
  4. Heavy performance_schema joins can contend with production traffic. Querying unindexed memory or lock tables under high concurrency adds mutex overhead on the MySQL server unless queries are bounded by max_execution_time, LIMIT, and per-user resource quotas (MAX_QUERIES_PER_HOUR).

How do you let an LLM agent diagnose MySQL performance bottlenecks across EC2, RDS, and Cloud SQL without exposing application tables, raw query literals, or primary stability?

Options Considered: EC2 vs. AWS RDS vs. Google Cloud SQL

Before writing grants, compare what each MySQL deployment model exposes and restricts.

EC2, RDS, and Cloud SQL differ on privileges and telemetry APIs

How the Options Compare

DimensionSelf-Managed MySQL on EC2AWS RDS for MySQLGoogle Cloud SQL for MySQL
Privilege ceilingFull root / SYSTEM_USER control; you manage CONNECTION_ADMIN and SUPER (8.0)Managed rdsadmin; SUPER and FILE are restrictedManaged cloudsqlsuperuser; SUPER and FILE are restricted
AuthenticationTLS client certs or short-lived Vault dynamic DB rolesAWSAuthenticationPlugin (15-min IAM token over mandatory SSL/TLS)cloudsql_iam_authentication + IAM Group Auth + Cloud SQL Auth Proxy (--auto-iam-authn)
Native telemetry alternativeNone built-in (direct performance_schema / sys SQL only)RDS Performance Insights (AAS, wait events, IAM-scoped SQL text dimension)Cloud SQL Insights (query insights, execution plans, wait events via Cloud IAM)
Audit optionsMySQL Enterprise Audit or community plugins (e.g., Percona/MariaDB audit plugin)MariaDB Audit Plugin (SERVER_AUDIT) via Option GroupsCloud Audit Logs / mysql_audit flag
Recommended agent pathdiag_views SQL schema on read replicaPerformance Insights API first; diag_views on replica for deep InnoDB statsCloud SQL Insights API first; diag_views on replica for deep InnoDB stats

On AWS RDS and Google Cloud SQL, prefer querying Performance Insights or Cloud SQL Insights via read-only cloud IAM permissions before opening a direct SQL connection to the database. Managed telemetry APIs let you strip raw SQL text at the IAM policy layer without running SQL queries against the instance’s performance_schema. When an agent does need live InnoDB lock graphs or sys views not exposed by the cloud API, connect strictly to a read replica using a curated diag_views schema. On self-managed EC2 instances—where no managed Insights API exists—diag_views combined with an OS-isolated replica and scoped audit plugin provides the same deterministic boundary without granting SELECT on user tables.

Curated Diagnostic Views and Audit Architecture

The target architecture places a deterministic Telemetry Gateway between the agent and MySQL, backed by a dedicated diag_views schema that exposes DIGEST_TEXT and aggregate wait metrics while physically omitting QUERY_SAMPLE_TEXT and SQL_TEXT.

Sanitized diagnostic views keep MySQL user data unreachable

Exact Grants for a Diagnostics-Only MySQL Account

Instead of granting SELECT ON performance_schema.*, create a wrapper schema diag_views owned by a restricted admin role (SQL SECURITY DEFINER) that projects only safe columns, then grant SELECT on diag_views.* and sys.* (where safe) to agent_diag_ro. In MySQL 8.0/8.4, pair this with per-account resource limits and a read-only replica target:

-- 1. Curated view omitting QUERY_SAMPLE_TEXT to prevent PII literal leaks
CREATE SCHEMA IF NOT EXISTS diag_views;

CREATE OR REPLACE SQL SECURITY DEFINER
VIEW diag_views.top_statement_digests AS
SELECT
  SCHEMA_NAME,
  DIGEST,
  DIGEST_TEXT,
  COUNT_STAR,
  ROUND(SUM_TIMER_WAIT / 1e12, 3) AS total_latency_sec,
  SUM_ROWS_EXAMINED,
  SUM_ROWS_SENT,
  SUM_NO_INDEX_USED
FROM performance_schema.events_statements_summary_by_digest
WHERE DIGEST_TEXT IS NOT NULL;

-- Active threads without the statement text (omits PROCESSLIST_INFO, where raw SQL appears)
CREATE OR REPLACE SQL SECURITY DEFINER
VIEW diag_views.active_threads AS
SELECT THREAD_ID, PROCESSLIST_ID, PROCESSLIST_USER, PROCESSLIST_DB,
       PROCESSLIST_COMMAND, PROCESSLIST_TIME, PROCESSLIST_STATE
FROM performance_schema.threads
WHERE TYPE = 'FOREGROUND';

-- 2. Narrow diagnostics-only account (RDS IAM example; use cloudsql IAM on GCP)
CREATE USER 'agent_diag_ro'@'%'
  IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'
  REQUIRE SSL
  WITH MAX_QUERIES_PER_HOUR 600
       MAX_USER_CONNECTIONS 5;

-- Deliberately NO `GRANT PROCESS`: that privilege exposes every session's current SQL text.
-- Active threads come from the diag_views.active_threads wrapper above instead.
GRANT SELECT ON diag_views.* TO 'agent_diag_ro'@'%';
GRANT SELECT ON sys.schema_unused_indexes TO 'agent_diag_ro'@'%';
GRANT SELECT ON sys.innodb_lock_waits TO 'agent_diag_ro'@'%';

Notice what is explicitly absent from those grants:

  • Zero SELECT on any application database (app.*).
  • Zero SELECT on raw performance_schema.events_statements_current or events_statements_history (which contain raw SQL_TEXT).
  • Zero SHOW_ROUTINE (prevents reading stored procedure source code).
  • Zero CONNECTION_ADMIN, SUPER, SYSTEM_VARIABLES_ADMIN, or RELOAD.

At session start, the MCP Telemetry Gateway executes SET SESSION max_execution_time = 5000; so no diagnostic query can run longer than 5 seconds. Because diag_views.top_statement_digests is created with SQL SECURITY DEFINER, MySQL evaluates the underlying performance_schema read using the restricted view owner’s privileges while agent_diag_ro only sees the projected columns—meaning the agent can never query QUERY_SAMPLE_TEXT or events_statements_history directly. As a second layer on self-managed EC2 or parameter-group-controlled instances, setting performance_schema_max_digest_sample_age = 0 disables retention of raw sample queries altogether, while monitoring max_digest_length prevents long multi-join statements from truncating before their normalized structure is useful.

For authentication, AWS RDS for MySQL maps 'agent_diag_ro'@'%' to AWSAuthenticationPlugin with mandatory SSL/TLS and a 15-minute SigV4 token, so the gateway must generate a fresh token whenever opening a new physical connection. Google Cloud SQL for MySQL supports both individual IAM service accounts (cloudsql_iam_authentication) and IAM Group Authentication via Google Workspace or Cloud Identity groups—letting platform teams grant diag_views access to an on-call engineering group and rely on the Cloud SQL Auth Proxy (--auto-iam-authn) for automatic OAuth2 token refresh and encrypted tunneling. On self-managed EC2, pair short-lived TLS client certificates or HashiCorp Vault dynamic database roles with REQUIRE SSL so no static MySQL password ever sits on the MCP server host.

Audit Design Across EC2, RDS, and Cloud SQL

Every diagnostic call must be attributable from the human caller down to the MySQL query, regardless of whether the database runs on EC2, AWS RDS, or Google Cloud SQL. Without correlated logging, an incident responder cannot distinguish a legitimate on-call investigation from an injected query triggered by a poisoned ticket or log line:

  1. Gateway Layer: Log the OIDC caller principal, MCP tool name, target instance ID, and a unique trace_id (passed as a MySQL query comment /* trace_id=... */).
  2. Database Layer:
    • On EC2, enable MySQL Enterprise Audit or a community audit plugin (such as the Percona or MariaDB audit plugin) filtering CONNECT and QUERY events for agent_diag_ro.
    • On AWS RDS, attach an Option Group with MARIADB_AUDIT_PLUGIN (SERVER_AUDIT_EVENTS = 'CONNECT,QUERY_DCL,QUERY_DDL,QUERY_DML_NO_SELECT', or include QUERY scoped to agent_diag_ro) and stream logs to CloudWatch Logs.
    • On Google Cloud SQL, enable the cloudsql_mysql_audit / audit logging flag to ship connection and query audit records to Cloud Logging.

Attacker and Defender Threat Matrix

Threat VectorTrust Boundary CrossedAttacker Objective (OWASP / ATLAS)Defender Control (Deterministic)Verification Signal
Global SELECT ON *.* shortcutTB-2 → TB-3 (Agent → Data)Read customer PII tables via diagnostic SQL tool (Collection)Grant SELECT only on diag_views.* and specific sys views; 0 app grantsSELECT * FROM app.users fails with SELECT command denied
QUERY_SAMPLE_TEXT literal leakTB-3 (Telemetry → Model)Extract inline PII or plant indirect prompt injection in sample query (LLM01)Omit QUERY_SAMPLE_TEXT and SQL_TEXT from diag_views; set max_digest_sample_age = 0SHOW COLUMNS FROM diag_views.top_statement_digests excludes sample text
PROCESS + SHOW_ROUTINE exposureTB-2 (Metadata → Agent)Read proprietary stored-routine logic or raw PROCESSLIST query literalsOmit SHOW_ROUTINE; scrub INFO column literals in diag_views processlist wrapperSHOW CREATE PROCEDURE fails with access denied
CONNECTION_ADMIN bypasses read_onlyTB-2 (Role → Primary)Mutate data or kill production threads despite read_only = ONNever grant CONNECTION_ADMIN or SUPER; route agent to read replicaSET GLOBAL or KILL fails with Access denied
Runaway performance_schema scanTB-2 → TB-3 (Query → CPU)Exhaust DB CPU or connection slots via unbounded diagnostic queries (Impact)SET SESSION max_execution_time = 5000 + MAX_USER_CONNECTIONS 5 + LIMIT 25Query >5s aborts with Query execution was interrupted, maximum statement execution time exceeded
Unbounded LOAD_FILE / INTO OUTFILETB-3 (Engine → Host FS)Read host files or write exfiltrated data to diskNever grant FILE privilege (blocked by default on RDS/Cloud SQL; omitted on EC2)SELECT LOAD_FILE('/etc/passwd') fails with Access denied

How It Rolls Out

A deterministic four-step flow ensures the LLM sees aggregate performance signals while customer data and raw literals stay unreachable.

Collect normalized digests without touching raw query literals

Runtime Diagnostic Flow

  1. 01 Auth Caller: The on-call engineer authenticates to the MCP Policy Gateway via OIDC. Because the session will read DIGEST_TEXT and wait-event strings, the gateway locks the session to a no-egress profile (Post 1).
  2. 02 Route Telemetry: For RDS and Cloud SQL instances, the gateway queries Performance Insights or Cloud SQL Insights first. Only when deeper InnoDB lock or sys metrics are required does it open a connection to a read replica.
  3. 03 Bounded Query: The gateway connects as agent_diag_ro over TLS using short-lived IAM auth, sets max_execution_time = 5000, and invokes parameterized queries against diag_views with LIMIT 25.
  4. 04 Return and Audit: The gateway returns normalized DIGEST_TEXT (? placeholders) and latency counters to the LLM, while emitting a correlated audit record linking the OIDC caller to the MySQL trace_id.

Phased Rollout and Rollback Gates

  1. Phase 1 — Deploy diag_views and Audit Plugin: Create the diag_views schema on a staging replica and verify that QUERY_SAMPLE_TEXT and SQL_TEXT are excluded. Enable MariaDB Audit Plugin (RDS), Cloud Audit Logs (Cloud SQL), or Enterprise/Percona Audit (EC2). Gate: diag_views returns top digests with ? placeholders and zero raw literals. Rollback: DROP SCHEMA diag_views.
  2. Phase 2 — Provision agent_diag_ro with Resource Limits: Create agent_diag_ro with REQUIRE SSL, MAX_QUERIES_PER_HOUR, MAX_USER_CONNECTIONS, and SELECT ON diag_views.* (no PROCESS). Gate: Automated test confirms SELECT on application schemas and UPDATE/KILL statements are denied. Rollback: DROP USER 'agent_diag_ro'@'%'.
  3. Phase 3 — Enable Cloud Telemetry APIs and Gateway Routing: Wire RDS Performance Insights or Cloud SQL Insights tools into the MCP Policy Gateway and point SQL-level diagnostic tools exclusively to read-replica endpoints. Gate: Zero diagnostic queries hit the primary writer; max_execution_time cancels synthetic slow queries at 5 seconds. Rollback: Disable the SQL diagnostic tool in the gateway while retaining Cloud API telemetry.
  4. Phase 4 — Decommission Legacy Broad Monitoring Accounts: Rotate and remove any legacy SELECT ON *.* credentials used by AI scripts or chatbots. Gate: Audit logs show zero active sessions using broad monitoring passwords. Rollback: N/A (legacy credential retirement).

In Practice

I have not tested every MySQL 8.0 and 8.4 minor patch across all three cloud providers personally, so every control in this design is derived from official MySQL, AWS, and Google Cloud documentation:

  • MySQL 8.0/8.4 privileges and Performance Schema behavior (Pattern A — Reference Manual): Per the MySQL Reference Manual, DIGEST_TEXT normalizes literal values to ?, whereas QUERY_SAMPLE_TEXT (added in MySQL 8.0) and events_statements_current/history SQL_TEXT store raw query strings. PROCESS grants visibility into all threads, SHOW_ROUTINE exposes stored routine definitions, CONNECTION_ADMIN (and the deprecated SUPER) bypass read_only, and max_execution_time applies strictly to read-only SELECT statements.
  • Managed cloud restrictions and IAM auth (Pattern A — Cloud Docs): Both AWS RDS for MySQL (rdsadmin, AWSAuthenticationPlugin with 15-minute tokens, Performance Insights) and Google Cloud SQL for MySQL (cloudsqlsuperuser, cloudsql_iam_authentication, Cloud SQL Insights) restrict SUPER and FILE while offering IAM-authenticated connections and API-first query telemetry.

Where It Breaks

Leaky MySQL grants expose PII via raw literals and broad schemas

ConditionBreaks HowDetectMitigate
SHOW PROCESSLIST leaks inline literals in INFO columnEven without events_statements_history, PROCESS lets agent_diag_ro read currently executing raw SQL in INFOTest SHOW FULL PROCESSLIST while an unparameterized query runsWrap performance_schema.processlist in diag_views omitting the INFO column (or redacting it), rather than letting the agent run raw SHOW PROCESSLIST
Application embeds PII in SQL comments or table namesDIGEST_TEXT strips literals, not SQL comments (/* [email protected] */) or dynamic identifiersRegex scan on DIGEST_TEXT in staging finds email/UUID patternsStrip comments before returning DIGEST_TEXT in the MCP gateway, or set performance_schema_max_digest_sample_age = 0
Replica lags behind primary during an outagediag_views on a lagging replica misses the live lock contention happening on the primary writerReplica Seconds_Behind_Master / Replica_SQL_Running_State alertsUse RDS Performance Insights or Cloud SQL Insights APIs (which read primary telemetry out-of-band) for primary-writer incidents
Stored function inside SELECT bypasses max_execution_timeMySQL ignores max_execution_time if a SELECT calls a data-modifying stored functionLong-running query alert exceeds 5s thresholdGrant SELECT only on diag_views.* and sys views; never grant EXECUTE on application functions
Audit plugin overhead on high-QPS EC2 instanceLogging every QUERY event for all users degrades throughputDisk I/O or QPS drop after enabling audit pluginScope audit logging strictly to agent_diag_ro (SERVER_AUDIT_INCL_USERS or Enterprise Audit filter) rather than logging all application traffic

Key Takeaways

  • Never grant SELECT ON *.* to a diagnostic agent: performance_schema and sys answer latency, lock, and index questions without touching user tables.
  • Block QUERY_SAMPLE_TEXT and raw SQL_TEXT: Normalization only protects DIGEST_TEXT; wrap performance_schema in a diag_views schema that omits raw sample columns and INFO text.
  • Use managed telemetry APIs first: On AWS RDS and Google Cloud SQL, query Performance Insights or Cloud SQL Insights over IAM before opening direct SQL connections.
  • Omit SHOW_ROUTINE, FILE, and CONNECTION_ADMIN: Keep the diagnostic role strictly below read_only bypasses and stored-routine source exposure.
  • Bound every query in MySQL and the gateway: Combine SET SESSION max_execution_time, MAX_QUERIES_PER_HOUR, MAX_USER_CONNECTIONS, and read-replica routing.

What to Do Next

  • Problem: Diagnostic LLM agents granted broad SELECT or raw performance_schema access can read customer data and inline PII literals.
  • Solution: Deploy a diag_views schema exposing normalized DIGEST_TEXT only, provision a SSL-required agent_diag_ro role with no PROCESS grant and a max_execution_time cap, and route cloud telemetry through Performance Insights or Cloud SQL Insights.
  • Proof: Connect as agent_diag_ro, verify SELECT * FROM app.users fails with access denied, and verify SELECT * FROM diag_views.top_statement_digests LIMIT 5 returns ?-normalized digests with zero raw literals.
  • Action: Audit your MySQL monitoring and AI diagnostic accounts this week, revoke any SELECT ON *.* or performance_schema.* grants, and replace them with diag_views plus IAM authentication.