Letting an LLM Read MySQL Diagnostics Without Reading Your Data
Content reflects the state as of October 2026. AI tooling and model capabilities in this area change frequently.
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 rawperformance_schematables (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 normalizedDIGEST_TEXTandsystelemetry only, grant onlySELECT ON diag_views.*(neverPROCESS, 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_timeapplies strictly to read-onlySELECTstatements (and is ignored if a stored function modifies data), andCONNECTION_ADMINbypassesread_only = ON.
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.
Four concrete constraints govern MySQL diagnostic boundaries in MySQL 8.0 and 8.4:
DIGEST_TEXTis normalized, butQUERY_SAMPLE_TEXTandSQL_TEXTleak raw literals (TB-2 to TB-3). Inperformance_schema.events_statements_summary_by_digest,DIGEST_TEXTreplaces literals with?(SELECT * FROM users WHERE email = ?). However, MySQL 8.0+ also populatesQUERY_SAMPLE_TEXTin that same table with a raw, un-normalized sample query forEXPLAINanalysis. Similarly,events_statements_current,events_statements_history, andevents_statements_history_longstore rawSQL_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 insideperformance_schema.PROCESSandSHOW_ROUTINEexpose cross-session metadata (TB-2). The globalPROCESSprivilege allows a user to inspect threads executed by all other users viaSHOW PROCESSLISTor Performance Schema processlist tables (note that in MySQL 8.4,INFORMATION_SCHEMA.PROCESSLISTandperformance_schema_show_processlistare deprecated in favor of Performance Schema-backed thread evaluation). Meanwhile,SHOW_ROUTINElets a role view the source code of every stored procedure and function regardless ofDEFINER. GrantingSHOW_ROUTINEto an agent unnecessarily exposes proprietary business logic.read_only = ONdoes not stop privileged roles, andmax_execution_timehas blind spots (TB-2). Whenread_only = ONis set on a replica, accounts holdingCONNECTION_ADMIN(or the deprecatedSUPER) can still execute writes. Furthermore,SET SESSION max_execution_time = 5000only terminates read-onlySELECTstatements; if aSELECTinvokes a stored function with data-modifying side effects,max_execution_timeis ignored.- Heavy
performance_schemajoins 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 bymax_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.
How the Options Compare
| Dimension | Self-Managed MySQL on EC2 | AWS RDS for MySQL | Google Cloud SQL for MySQL |
|---|---|---|---|
| Privilege ceiling | Full root / SYSTEM_USER control; you manage CONNECTION_ADMIN and SUPER (8.0) | Managed rdsadmin; SUPER and FILE are restricted | Managed cloudsqlsuperuser; SUPER and FILE are restricted |
| Authentication | TLS client certs or short-lived Vault dynamic DB roles | AWSAuthenticationPlugin (15-min IAM token over mandatory SSL/TLS) | cloudsql_iam_authentication + IAM Group Auth + Cloud SQL Auth Proxy (--auto-iam-authn) |
| Native telemetry alternative | None 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 options | MySQL Enterprise Audit or community plugins (e.g., Percona/MariaDB audit plugin) | MariaDB Audit Plugin (SERVER_AUDIT) via Option Groups | Cloud Audit Logs / mysql_audit flag |
| Recommended agent path | diag_views SQL schema on read replica | Performance Insights API first; diag_views on replica for deep InnoDB stats | Cloud 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.
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
SELECTon any application database (app.*). - Zero
SELECTon rawperformance_schema.events_statements_currentorevents_statements_history(which contain rawSQL_TEXT). - Zero
SHOW_ROUTINE(prevents reading stored procedure source code). - Zero
CONNECTION_ADMIN,SUPER,SYSTEM_VARIABLES_ADMIN, orRELOAD.
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:
- 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=... */). - Database Layer:
- On EC2, enable MySQL Enterprise Audit or a community audit plugin (such as the Percona or MariaDB audit plugin) filtering
CONNECTandQUERYevents foragent_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 includeQUERYscoped toagent_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.
- On EC2, enable MySQL Enterprise Audit or a community audit plugin (such as the Percona or MariaDB audit plugin) filtering
Attacker and Defender Threat Matrix
| Threat Vector | Trust Boundary Crossed | Attacker Objective (OWASP / ATLAS) | Defender Control (Deterministic) | Verification Signal |
|---|---|---|---|---|
Global SELECT ON *.* shortcut | TB-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 grants | SELECT * FROM app.users fails with SELECT command denied |
QUERY_SAMPLE_TEXT literal leak | TB-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 = 0 | SHOW COLUMNS FROM diag_views.top_statement_digests excludes sample text |
PROCESS + SHOW_ROUTINE exposure | TB-2 (Metadata → Agent) | Read proprietary stored-routine logic or raw PROCESSLIST query literals | Omit SHOW_ROUTINE; scrub INFO column literals in diag_views processlist wrapper | SHOW CREATE PROCEDURE fails with access denied |
CONNECTION_ADMIN bypasses read_only | TB-2 (Role → Primary) | Mutate data or kill production threads despite read_only = ON | Never grant CONNECTION_ADMIN or SUPER; route agent to read replica | SET GLOBAL or KILL fails with Access denied |
Runaway performance_schema scan | TB-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 25 | Query >5s aborts with Query execution was interrupted, maximum statement execution time exceeded |
Unbounded LOAD_FILE / INTO OUTFILE | TB-3 (Engine → Host FS) | Read host files or write exfiltrated data to disk | Never 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.
Runtime Diagnostic Flow
- 01 Auth Caller: The on-call engineer authenticates to the MCP Policy Gateway via OIDC. Because the session will read
DIGEST_TEXTand wait-event strings, the gateway locks the session to a no-egress profile (Post 1). - 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
sysmetrics are required does it open a connection to a read replica. - 03 Bounded Query: The gateway connects as
agent_diag_roover TLS using short-lived IAM auth, setsmax_execution_time = 5000, and invokes parameterized queries againstdiag_viewswithLIMIT 25. - 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 MySQLtrace_id.
Phased Rollout and Rollback Gates
- Phase 1 — Deploy
diag_viewsand Audit Plugin: Create thediag_viewsschema on a staging replica and verify thatQUERY_SAMPLE_TEXTandSQL_TEXTare excluded. Enable MariaDB Audit Plugin (RDS), Cloud Audit Logs (Cloud SQL), or Enterprise/Percona Audit (EC2). Gate:diag_viewsreturns top digests with?placeholders and zero raw literals. Rollback:DROP SCHEMA diag_views. - Phase 2 — Provision
agent_diag_rowith Resource Limits: Createagent_diag_rowithREQUIRE SSL,MAX_QUERIES_PER_HOUR,MAX_USER_CONNECTIONS, andSELECT ON diag_views.*(noPROCESS). Gate: Automated test confirmsSELECTon application schemas andUPDATE/KILLstatements are denied. Rollback:DROP USER 'agent_diag_ro'@'%'. - 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_timecancels synthetic slow queries at 5 seconds. Rollback: Disable the SQL diagnostic tool in the gateway while retaining Cloud API telemetry. - 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_TEXTnormalizes literal values to?, whereasQUERY_SAMPLE_TEXT(added in MySQL 8.0) andevents_statements_current/historySQL_TEXTstore raw query strings.PROCESSgrants visibility into all threads,SHOW_ROUTINEexposes stored routine definitions,CONNECTION_ADMIN(and the deprecatedSUPER) bypassread_only, andmax_execution_timeapplies strictly to read-onlySELECTstatements. - Managed cloud restrictions and IAM auth (Pattern A — Cloud Docs): Both AWS RDS for MySQL (
rdsadmin,AWSAuthenticationPluginwith 15-minute tokens, Performance Insights) and Google Cloud SQL for MySQL (cloudsqlsuperuser,cloudsql_iam_authentication, Cloud SQL Insights) restrictSUPERandFILEwhile offering IAM-authenticated connections and API-first query telemetry.
Where It Breaks
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
SHOW PROCESSLIST leaks inline literals in INFO column | Even without events_statements_history, PROCESS lets agent_diag_ro read currently executing raw SQL in INFO | Test SHOW FULL PROCESSLIST while an unparameterized query runs | Wrap 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 names | DIGEST_TEXT strips literals, not SQL comments (/* [email protected] */) or dynamic identifiers | Regex scan on DIGEST_TEXT in staging finds email/UUID patterns | Strip comments before returning DIGEST_TEXT in the MCP gateway, or set performance_schema_max_digest_sample_age = 0 |
| Replica lags behind primary during an outage | diag_views on a lagging replica misses the live lock contention happening on the primary writer | Replica Seconds_Behind_Master / Replica_SQL_Running_State alerts | Use 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_time | MySQL ignores max_execution_time if a SELECT calls a data-modifying stored function | Long-running query alert exceeds 5s threshold | Grant SELECT only on diag_views.* and sys views; never grant EXECUTE on application functions |
| Audit plugin overhead on high-QPS EC2 instance | Logging every QUERY event for all users degrades throughput | Disk I/O or QPS drop after enabling audit plugin | Scope 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_schemaandsysanswer latency, lock, and index questions without touching user tables. - Block
QUERY_SAMPLE_TEXTand rawSQL_TEXT: Normalization only protectsDIGEST_TEXT; wrapperformance_schemain adiag_viewsschema that omits raw sample columns andINFOtext. - 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, andCONNECTION_ADMIN: Keep the diagnostic role strictly belowread_onlybypasses 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
SELECTor rawperformance_schemaaccess can read customer data and inline PII literals. - Solution: Deploy a
diag_viewsschema exposing normalizedDIGEST_TEXTonly, provision a SSL-requiredagent_diag_rorole with noPROCESSgrant and amax_execution_timecap, and route cloud telemetry through Performance Insights or Cloud SQL Insights. - Proof: Connect as
agent_diag_ro, verifySELECT * FROM app.usersfails with access denied, and verifySELECT * FROM diag_views.top_statement_digests LIMIT 5returns?-normalized digests with zero raw literals. - Action: Audit your MySQL monitoring and AI diagnostic accounts this week, revoke any
SELECT ON *.*orperformance_schema.*grants, and replace them withdiag_viewsplus IAM authentication.