Skip to content

MCP components

Server-side components for mysql-mcp-server, designed in its RFC 0001. They are opt-in and separate from MyVector: MYVECTOR_BUILD_MCP=ON ./scripts/build-component-<ver>-docker.sh builds component_mcp_guard.so next to the MyVector component.

Component Status Servers
component_mcp_guard Phase 2: identity, read-only and schema enforcement, time limit, error log, status variables MySQL 8.4, 9.7, 26.10
mysql_mcp SQL tool pack (sql/mcp/) 1.0.0 MySQL 8.0 to 26.10, MariaDB 11.4, 12.3
component_mcp Phase 4 spike (not for production): an MCP endpoint inside mysqld MySQL 26.10

Maintainer: @askdba owns the C++ code of these components (RFC 0001 §10). .github/CODEOWNERS routes reviews of src/mcp/, sql/mcp/ and the MCP scripts to them.

component_mcp_guard

Enforces a policy on the sessions of mysql-mcp-server, inside mysqld, so a client cannot widen it. Grants stay the primary control (MCP accounts should be SELECT-only); the guard covers what grants cannot express: a kill switch, read-only even when an account has write grants, and schema limits for accounts with global SELECT.

Install

-- copy component_mcp_guard.so into @@plugin_dir first: the build for this server's
-- exact release (a build for another patch release, even 8.4.8 on 8.4.11, can crash it)
INSTALL COMPONENT 'file://component_mcp_guard';
GRANT MCP_ADMIN ON *.* TO 'dba'@'%';          -- who may change mcp.* settings
GRANT MCP_USER  ON *.* TO 'mcp'@'%';          -- the account mysql-mcp-server uses
GRANT EXECUTE   ON mysql_mcp.* TO 'mcp'@'%';  -- if the SQL tool pack is installed

The guard requires component_reference_cache (loaded by the server at startup from plugin_dir, part of every MySQL package): event tracking reaches components through it, so without it the guard would load but see no statements. It fails closed instead: INSTALL COMPONENT fails with error 3534 ("Cannot satisfy dependency for service 'reference_caching_channel'"), and component_mcp, which requires the guard, cannot be installed either. At a restart, the server's persisted-component loader logs a component that fails to load and starts anyway, so if the cache is missing then, the guard is not loaded: component_mcp is not either, but plain logins of MCP_USER accounts are then governed by their grants alone. Grant MCP accounts only what they may do without the guard, and after a restart check that the guard is loaded: SHOW STATUS LIKE 'mcp.%' returns its status variables only then. Installing the cache later (INSTALL COMPONENT) satisfies the requirement but does not repair event tracking, which the server sets up at startup: the guard then loads and sees nothing. component_mcp checks for that itself: before its first call as an MCP_USER account (the only sessions the guard counts and restricts) it reads the guard's mcp.statements_total twice in the call's session, and if the count does not rise it refuses the call (error 1290, "component_mcp_guard receives no statements") until the server is restarted with the cache.

UNINSTALL COMPONENT 'file://component_mcp_guard' removes the privileges, variables and status variables. Grants of MCP_USER and MCP_ADMIN stay in the grant tables until revoked.

Docker images (mysql-mcp)

ghcr.io/askdba/mysql-mcp:<8.4|9.7|26.10> (amd64, arm64; also tagged with the exact release, such as 8.4.13) is the official mysql image of the release the component was built for, with component_mcp_guard and the mysql_mcp SQL tool pack. It is separate from the MyVector images. On first start, with an empty data directory, it installs both, grants MCP_ADMIN to the root accounts, and reads these settings:

Variable Effect
MYSQL_MCP_USER, MYSQL_MCP_PASSWORD Create this account (host %; a plain name of up to 32 characters from A-Z a-z 0-9 _ . -) for mysql-mcp-server, with MCP_USER, EXECUTE on mysql_mcp and SELECT, SHOW VIEW on the databases below.
MYSQL_MCP_DATABASES Comma-separated databases the account may read. The default is MYSQL_DATABASE.
MYSQL_MCP_ALLOWED_SCHEMAS Persisted as mcp.allowed_schemas.
MYSQL_MCP_MAX_EXECUTION_TIME_MS Persisted as mcp.max_execution_time_ms.

The other settings keep their defaults (read-only on). The settings are checked before the data directory is initialized, and a container with an invalid combination does not start. Once the data directory exists they are not used or checked again. For example, MYSQL_MCP_USER must differ from MYSQL_USER (or the user in MYSQL_USER_FILE), because the official entrypoint gives that account all privileges on MYSQL_DATABASE. The health check asks mysqld for the port it uses (command line and option files, as mysqld resolves them) and pings it without logging in as root. The official image's own variables (MYSQL_ROOT_PASSWORD, MYSQL_DATABASE, ...) work as usual.

docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=secret -e MYSQL_DATABASE=shop \
  -e MYSQL_MCP_USER=mcp -e MYSQL_MCP_PASSWORD=mcp-secret ghcr.io/askdba/mysql-mcp:9.7
MYSQL_DSN='mcp:mcp-secret@tcp(127.0.0.1:3306)/shop' mysql-mcp-server

The images are built and published with MyVector releases (docker-publish.yml). scripts/test-mysql-mcp-image.sh <image> tests the first-start setup, and CI (integration-scripts.yml, job mcp-guard) runs it on each version.

MCP sessions

A session is an MCP session when its account holds MCP_USER and not MCP_ADMIN. This is decided at connect and at COM_CHANGE_USER, from privileges only; connection attributes and statement comments cannot change it.

  • MCP_ADMIN holders are never guarded. After the component is installed, GRANT ALL ON *.* includes both privileges, so an administrator granted that way is not put under the guard.
  • Privilege changes take effect at the next connection. A session's status is decided once (at connect, at COM_CHANGE_USER, or at its first statement if neither was seen) and kept. Sessions connected when MCP_USER / MCP_ADMIN is granted or revoked keep their previous status; disconnect them (KILL CONNECTION) or have the client reconnect after such a change. Sessions already connected when the component is installed are classified at their next statement.
  • Grant MCP_USER to the account itself; a role activated later with SET ROLE is not considered.
  • Sessions opened by components. A component can run SQL as an account through the command services: a "local" session that impersonates the account, as component_mcp (RFC 0001 Phase 4) and component_mysql_rest_service do. Such a session raises no connection event the guard can use, and it starts unaudited: the guard receives no events for it until the component emits MYSQL_AUDIT_CONNECTION_CONNECT for the session's THD, which turns auditing on. The guard then classifies the session from its privileges at its first statement. (The CONNECT callback runs on the component's thread, where the session is not current, so the guard does not classify it there.)
  • The server starts these sessions unaudited: no statement or connection event reaches any audit consumer, the guard included.
  • A component that runs SQL for MCP accounts must therefore emit MYSQL_AUDIT_CONNECTION_CONNECT for the session's THD after connecting (mysql_audit_api_connection), and ..._DISCONNECT before closing. The CONNECT event turns auditing on.
  • component_mcp does this. A component that doesn't runs its SQL unseen by the guard and by audit log plugins.
  • scripts/test-mcp-guard.sh checks both cases with a test-only component (src/mcp/guard/test/component_mcp_session_probe.cc).

Settings

Variable Default Effect on MCP sessions
mcp.enabled ON OFF refuses new MCP connections and every statement of existing ones (kill switch).
mcp.read_only ON Only reads, whatever the account's grants (below).
mcp.deny_system_schemas ON No table access in mysql and sys. information_schema and performance_schema stay readable (the tools use them; grants govern them).
mcp.allowed_schemas empty Comma-separated schemas whose tables MCP sessions may access; blank means all. A value with no names in it, such as ,, allows none. Names are compared exactly, or case-insensitively when lower_case_table_names is 1 or 2. The system schemas above are governed by mcp.deny_system_schemas, and mysql_mcp is always allowed.
mcp.max_execution_time_ms 0 Time limit for their SELECT statements, which they cannot raise; 0 turns the guard's limit off (the server's own max_execution_time default still applies) (below).
mcp.log_denials ON Write refusals to the error log, at most 10 lines a minute (below).
mcp.tool_calls_history_size 1000 Tool calls kept in performance_schema.mcp_tool_calls (below); 0 keeps none. Read-only: set it at startup or in INSTALL COMPONENT ... SET.

SET GLOBAL and SET PERSIST of mcp.* need MCP_ADMIN on top of SYSTEM_VARIABLES_ADMIN. Persisted values load at startup as usual. Values given in INSTALL COMPONENT ... SET are taken from the installer.

What mcp.read_only allows

Statements are classified by the server's sql_command, so the decision does not depend on parsing. Allowed:

  • SELECT (including EXPLAIN), every SHOW, DO, USE, HELP, CHECK, CHECKSUM, HANDLER reads, KILL, transaction control (BEGIN, COMMIT, ROLLBACK, savepoints), SIGNAL/RESIGNAL, GET DIAGNOSTICS, UNLOCK TABLES.
  • SET of session and user variables.
  • CALL into the tool pack: CALL mysql_mcp.<routine>(...), schema-qualified.
  • PREPARE, EXECUTE, DEALLOCATE PREPARE: the executed statement raises its own event and is checked as itself. Statements sent as binary-protocol prepared statements (as the Go driver does) are checked the same way.

Denied: everything else, including any sql_command a future server adds. Four cases also look at the statement text, after string literals and comments are removed (executable comments /*! ... */ and /*M! ... */ count as code). Where a string ends depends on sql_mode (NO_BACKSLASH_ESCAPES), which a session may change, so the text is read both with and without backslash escapes, and a statement is denied if either reading finds one of these:

  • SELECT ... INTO OUTFILE / INTO DUMPFILE.
  • Locking reads: FOR UPDATE, FOR SHARE, LOCK IN SHARE MODE.
  • SET GLOBAL, SET PERSIST, SET PERSIST_ONLY, @@global., @@persist..
  • CALL of anything outside mysql_mcp, or an unqualified CALL.

Table access events catch writes the statement class cannot see, for example a stored function that inserts, called from a SELECT.

Because of the double reading, a SELECT whose string literal contains a backslash-escaped quote followed by text such as FOR UPDATE ('it\'s FOR UPDATE') is denied even though it only reads. Write such a literal with a doubled quote ('it''s FOR UPDATE') instead.

CALL is allowed for any routine in the mysql_mcp schema, not only the tool pack's. Keep only the tool pack in mysql_mcp (it is installed and dropped as a whole).

Time limit (mcp.max_execution_time_ms)

When an MCP session connects, the guard sets its session max_execution_time to mcp.max_execution_time_ms, so its SELECT statements stop after that many milliseconds (error 3024). The session may lower it, but not raise it. These are refused with error 1290 naming mcp.max_execution_time_ms:

  • SET [SESSION] max_execution_time (or @@max_execution_time) to 0, above the limit, or to anything but a literal (DEFAULT, an expression, a variable).
  • The optimizer hints MAX_EXECUTION_TIME(n) and SET_VAR(max_execution_time = n) with such a value.

A changed limit reaches connected MCP sessions at their next statement, and the limit is applied again after COM_CHANGE_USER and COM_RESET_CONNECTION, which reset session variables. On 9.0 and later the guard reads the MCP session's max_execution_time at each of its statements and sets the limit when the value is 0 or above it (a value the session lowered stays), so it subscribes to no command events, which every client's commands would pay for. On 8.4, which cannot read a session variable from a component, it catches COM_RESET_CONNECTION through command events, and a changed limit replaces the session's value even when the session had lowered it. Setting it back to 0 leaves their current session value as it is.

As with the server's own max_execution_time, the limit covers top-level read-only SELECT statements. MySQL ignores it inside stored programs, so CALL mysql_mcp.* tool-pack calls are not limited. Those run catalog queries on information_schema. If they must be limited too, revoke EXECUTE on mysql_mcp from the MCP account: mysql-mcp-server then falls back to its own SQL, whose SELECTs the limit covers.

Error log (mcp.log_denials)

Each refusal is written as a warning, with the setting, the connection id and the start of the statement (up to 256 bytes, string literals replaced by '?', line breaks by spaces) or the table:

[Warning] [MY-011071] [mcp_guard] mcp_guard: refused by mcp.read_only: MCP connection 11: INSERT INTO d.t VALUES (1)

At most 10 lines are written per minute; the number left out is reported with the next line after the minute. String literals are redacted, but numbers and identifiers are kept; turn mcp.log_denials off if even those must not reach the error log.

Audit log

Each refusal is also emitted as an audit message (the mysql_audit_api_message service, subclass MYSQL_AUDIT_MESSAGE_INTERNAL), so an audit log plugin or component that records message events records it, whatever mcp.log_denials says. The component is mcp_guard, the producer component_mcp_guard and the message refused, with these keys:

Key Value
option the setting that refused it, as in the error
connection_id the connection (a number)
statement the statement with string literals redacted as in the error log, or read db.table / write db.table
tool, request_id the tool call, when the statement is labeled (next section)

performance_schema.mcp_tool_calls

mysql-mcp-server starts every statement of a tool call with a label, /* mcp:tool=<tool> req=<request id> */. For MCP sessions the guard groups labeled statements into one row per tool call (one request id on one connection), keeping the latest mcp.tool_calls_history_size calls:

Column Meaning
CONNECTION_ID the connection
ACCOUNT the session's account, user@host as granted
TOOL, REQUEST_ID from the label
STATEMENTS labeled top-level statements of the call
ERRORS those that failed, refusals included
DENIED refusals by the guard
LATENCY_US total time of the statements, in microseconds
FIRST_SEEN, LAST_SEEN first statement start and last statement end
SELECT TOOL, COUNT(*) AS calls, SUM(DENIED) AS denied, SUM(LATENCY_US) / 1000 AS ms
FROM performance_schema.mcp_tool_calls GROUP BY TOOL ORDER BY ms DESC;

The table is read-only and lives in memory: it is empty after a restart or reinstall. The label only attributes statements; who is an MCP session is decided by MCP_USER, so labels from other accounts are ignored, and a session can write any label it likes (the account column is the trusted one). The label must be at the very start of the statement, which the mysql client keeps only with --comments.

Errors

A denial fails the statement with error 1290 (ER_OPTION_PREVENTS_STATEMENT), the server's own read_only error, naming the setting:

ERROR 1290 (HY000): The MySQL server is running with the mcp.read_only option so it cannot execute this statement

The option is mcp.read_only, mcp.deny_system_schemas, mcp.allowed_schemas or mcp.enabled. A SET of mcp.* without MCP_ADMIN fails with error 1227 (ER_SPECIFIC_ACCESS_DENIED_ERROR).

Status variables

Variable Meaning
mcp.sessions_connected MCP sessions now connected
mcp.statements_total Statements started by MCP sessions (nested statements of stored programs not counted)
mcp.statements_denied Statements refused by the statement checks (mcp.read_only, mcp.enabled), including refused connections
mcp.table_access_denied Statements refused by a table access (mcp.allowed_schemas, mcp.deny_system_schemas, a write under mcp.read_only seen only at table level). Add both counters for all refusals

Limits

  • mcp.allowed_schemas limits table access, not catalog metadata: information_schema and SHOW still list what the account's grants allow.
  • With mcp.deny_system_schemas = ON, mysql-mcp-server's opt-in slow_query_log tool (which reads mysql.slow_log) is denied.
  • The schema rules apply to a statement's base tables. A view in an allowed schema over a table in another schema (or in mysql) is denied, nested views included. A view in another schema whose base tables are all allowed is allowed.
  • Stored functions and triggers: their reads are not checked by the schema rules. Their statements run on tables the calling statement has already locked, so the server raises no table access event for them. For example, with mcp.allowed_schemas = 'd1', SELECT d1.f() returns data from d2 if d1.f() reads d2. Writes inside them are still refused by mcp.read_only (a nested statement check), and stored procedures are not affected (CALL is limited to mysql_mcp under mcp.read_only, and a procedure's statements raise their own events). Control this with grants: don't give MCP accounts EXECUTE on schemas with functions that read data they must not see. A SQL SECURITY INVOKER function runs with the account's own grants, but mcp.allowed_schemas doesn't limit it. Triggers need no EXECUTE: they run, with their definer's privileges, when a statement writes their table. Under mcp.read_only (the default) MCP sessions cannot write, so no trigger runs for them. If you turn mcp.read_only off, don't give MCP accounts write grants on tables whose triggers read data outside the account's allowed schemas, and review trigger definers. scripts/test-mcp-guard.sh keeps a check that shows this, so a server change is noticed (#247).
  • A multi-statement packet is checked statement by statement: each statement in it raises its own events.
  • Statements whose table reads raise no table access events are refused while mcp.deny_system_schemas is on (the default) or mcp.allowed_schemas is set. The server raises table access events only for SELECT, data changes, ANALYZE and HANDLER READ, so these statements would otherwise read any table unseen: a subquery in SET, DO, a CALL argument or SHOW ... WHERE, and CHECK TABLE / CHECKSUM TABLE. Read through SELECT instead (SELECT ... INTO @x). The refusal names the schema rule in effect. SET, SHOW and CALL without subqueries are unaffected.
  • With lower_case_table_names 1 or 2, the system schema names are compared case-insensitively, as the server compares them.

Tests

scripts/test-mcp-guard.sh <mysql-tag> <artifact-dir> runs install, restart, persistence, uninstall and the enforcement cases, the tool-call table and its labels, views, multi-statement packets, statements without table access events, sessions opened by components and the parity table below against the official image (123 checks, including a lower_case_table_names=1 server), and src/mcp/guard/test_mcp_guard_policy.cc unit-tests the classification and the SQL scanner. CI (integration-scripts.yml, job mcp-guard) runs both on MySQL 8.4.11, 9.7.2 and 26.10.0.

Parity with mysql-mcp-server (RFC 0001 §5.2 item 7): sql/mcp/guard-parity.tsv lists statements a run_query call might send, with the verdict of mysql-mcp-server's validator (go) and of the guard under the default settings (guard). Every row where they differ says why. The test checks the guard column, sending each statement as one packet. mysql-mcp-server vendors the file and checks the go column. Both reject every write and locking read. The guard allows a few things the validator does not (session SET, information_schema, CALL mysql_mcp.*) and catches what text checks cannot (a write inside a function called from SELECT).

Overhead on non-MCP traffic

RFC 0001 §10 asks for "guard overhead under 1% p99 on non-MCP traffic". scripts/bench-mcp-guard.sh <mysql-image> <artifact-dir> [pairs] [rounds] [seconds] [threads] measures it with sysbench, run as an account without MCP_USER:

  • Fresh server pairs. Each pair is two servers from the official image with the same data: one never has the guard, the other has it installed before the data is loaded. Runs alternate between them in ABBA order (the idle one paused), and the result is the median, over pairs, of each pair's overhead. A server instance's speed varies from start to start by more than 1%. Installing and then uninstalling the guard on one server does not work either, because the server does not return to its pre-install cost.
  • Per run: TPS, average latency, p99 (from sysbench's histogram, since the printed percentile is too coarse below a millisecond; its buckets are about 1.8% apart, so a smaller p99 change is reported as not resolvable, and the script exits 1 only when p99 moves by a bucket or more), server CPU per transaction (cgroup), and, when sudo -n perf works, instructions retired by mysqld per transaction. Instruction counts are almost independent of cache, clock and neighbour load, so they show small per-statement costs that timing hides on a shared host.

Measured on MySQL 26.10.0, aarch64 (16 cores, a shared host), oltp_point_select (the cheapest statement, so the worst case for a per-statement cost):

Component Instructions per transaction
no-op component, same five event subscriptions as the guard +2.6%
guard before #276 +3.2%
guard with #276 (no command events on 9.0+) +2.3%
no-op, query events only / command events only / table-access events only +1.05% / +1.03% / +0.43%

Most of the cost is MySQL's event-tracking dispatch for the event classes the guard needs (query, table access), not guard code, which adds about 0.6%. With oltp_read_write (many statements per transaction) the guard costs about 2.6% CPU per transaction and under 1% TPS. Status of the criterion: p99 medians are within noise on this host (single pairs vary by ±5–15%), so p99 cannot be resolved to 1% here, and the point-select CPU cost (about 2.3%) is above 1%. Deciding it needs a dedicated amd64 host and a load client that records exact per-query latencies, as sysbench's histogram cannot resolve a 1% p99 change (#256).

Why the guard does not subscribe only while MCP sessions are connected

Most of the remaining cost is MySQL's event dispatch, which every statement pays as long as some component subscribes to query and table-access events. Subscribing only while MCP sessions are connected was investigated on MySQL 26.10.0 and rejected:

  • No in-place toggle. The server builds its event channels privately (g_event_channels in mysqld), so a component cannot reach their ignore lists. Registering a service implementation at runtime does not notify the channels, so sessions never see it.
  • Loading a separate consumer component works, through the public mysql_dynamic_loader service, even from inside a connection-event callback. Sessions already connected start (and, after an unload, stop) paying the dispatch cost.
  • Unloading it is not safe. From inside an event callback, mysqld crashed (SIGSEGV): the unload notification flushes the calling session's reference caches while its own dispatch is iterating them. From outside a callback, the unload races with busy sessions that still hold cached references: it can fail with error 3540 (a service unregistration failed during the unload), which can leave the component partly unregistered. Neither is acceptable for a security component.
  • The gain would be limited anyway. While any MCP session is connected, all traffic pays, and the server builds each event's data (including the query text) before the consumer filters subclasses, so a consumer cannot make its own subscriptions cheaper.

The guard therefore keeps static subscriptions. A lower cost would need a server change, for example letting consumers declare the subclasses they want so the server skips building events no one reads, or a per-session subscription.

component_mcp (Phase 4 spike)

An MCP Streamable HTTP endpoint (JSON-RPC 2.0 over POST /mcp) inside mysqld. It runs on MySQL Router's HTTP server, the libraries component_mysql_rest_service links (RFC 0001 §5.3). This is the Phase 4 build spike and is not for production. It is limited to the following:

  • Network and auth: 127.0.0.1 by default. Plain HTTP is allowed only on loopback: with mcp_http.bind_address set to any other address the install fails unless mcp_http.ssl_cert and mcp_http.ssl_key are set, and then the endpoint serves HTTPS (TLS 1.2+, Router's TLS context). Bearer tokens map to accounts: one token in mcp_http.token_sha256 (to mcp_http.account), and any number in the token table mysql.mcp_tokens (below).
  • Known limit off loopback: Router's HTTP server has no handshake or idle timeout, and it counts connections before authentication. A client that opens 64 connections and sends nothing (not even a TLS handshake) blocks others until they close. Off loopback, allow only trusted clients to reach the port (firewall), or put a proxy that enforces timeouts in front. Tracked in #269.
  • localhost binds 127.0.0.1, so a resolver mapping the name elsewhere cannot expose plain HTTP.
  • Tools: the six core tools of RFC 0001 §3, with mysql-mcp-server's names and arguments:
  • list_databases, list_tables (database) and describe_table (database, table) call the mysql_mcp tool pack. Arguments are passed as hex literals (CONVERT(X'...' USING utf8mb4)), so they are never parsed as SQL and need no escaping under any sql_mode.
  • run_query (sql) runs one statement.
  • ping runs SELECT 1 and returns {"success", "latency_ms", "message"}; like mysql-mcp-server, a failure is a result with success: false, not a tool error.
  • server_info returns one object: version, server_engine, version_comment, current_user, current_database, character_set, collation, max_connections (as strings; current_database is "", as in mysql-mcp-server, since each call's session has no default database). mysql-mcp-server's extra fields (uptime, health, guard settings) are not ported.
  • Results: run_query returns at most 1000 rows and 4 MB of serialized rows (escapes counted), as {"rows": [{"col": value, ...}], "truncated": true|false}. A value is a JSON string, null, or {"base64": "..."} when its bytes are not valid UTF-8 (binary data). The session's sql_select_limit stops the server at 1001 rows for statements without their own LIMIT.
  • Bounded consumer: for statements with their own LIMIT, the server's default command-service consumer would collect every row while the statement runs. component_mcp sessions select its own row and value consumer services (mysql_text_consumer_*_v1.mcp), which pass rows on to the default consumer until the statement has produced 1001 rows or 4 MiB of values. Later rows are dropped as they arrive, and a row that crosses the byte budget is never half stored. The statement still runs to its end; mcp.max_execution_time_ms, when set, bounds its time. The budget also counts what the default consumer keeps per row and per cell (a pointer each, NULL cells included), so wide results of NULLs are bounded too. The status variables mcp_http.last_rows_retained, mcp_http.last_bytes_retained and mcp_http.last_rows_stored (the row count the default consumer handed over, observed independently) report what it kept for the last statement an endpoint call ran: 1001 rows for SELECT ... LIMIT 1000000, 4 rows for 1 MB values, 65 rows for 8000 NULL columns.
  • Exact account only: a call runs only if the session's privileges come from exactly the account its token maps to. Impersonation matches the grant tables like a login, so if user@host does not exist, a wider entry such as user@'%' (other grants, perhaps no MCP_USER) could otherwise stand in for it. A mismatch fails the call with error 1045 before any statement runs. The token-table reader session is checked the same way.
  • Privileged accounts refused: a call whose token maps to an account with SUPER, SYSTEM_USER or MCP_ADMIN fails with error 1227 before any statement runs, whichever token source mapped it (RFC 0001 §7.4). Such accounts are not restricted by the guard (only MCP_USER accounts are) and could undo it, so impersonating them would make a token a server administrator. Map tokens to MCP_USER accounts.
  • Locked accounts: a call for an account with ACCOUNT LOCK fails with error 3118 (Access denied for user '...'@'...'. Account is locked.) before any statement runs. Impersonation skips the login checks, so the endpoint reads the lock from the session's security context (account_locked, set by the account lookup at connect). It checks on every call, so ACCOUNT LOCK takes effect on the next one.

Build and install

It links the Router HTTP libraries, so it is built in the MySQL 26.10 source tree, like MRS:

MYVECTOR_BUILD_MCP=ON MYVECTOR_BUILD_MCP_ENDPOINT=ON \
  ./scripts/build-component-26.10-docker.sh mysql-26.10.0 dist/mcp-26.10.0

Use a random token and hash it outside MySQL, so the plaintext never appears in statement text (general and slow logs, audit logs, performance_schema history):

MCP_TOKEN=$(openssl rand -hex 32)
printf '%s' "$MCP_TOKEN" | sha256sum | cut -d' ' -f1
INSTALL COMPONENT 'file://component_mcp_guard';   -- required: install refuses without it
INSTALL COMPONENT 'file://component_mcp'
  SET GLOBAL mcp_http.port = 33480,
      GLOBAL mcp_http.account = 'mcp@%',
      GLOBAL mcp_http.token_sha256 = '<hex digest from above>';

Across restarts. The settings are read-only and SET GLOBAL values last only until the server restarts. The component itself is reloaded at startup, but with default settings: loopback, plain HTTP, no mcp_http.account and no mcp_http.token_sha256. The single token then gets 401, but tokens in mysql.mcp_tokens keep working: a restart is not a way to cut access, DELETE the rows (or let them expire) for that. To keep a configuration (verified on 26.10.0):

  • Install with SET PERSIST for every setting except the token: INSTALL COMPONENT 'file://component_mcp' SET PERSIST mcp_http.port = 33480, PERSIST mcp_http.account = 'mcp@%', PERSIST mcp_http.bind_address = '0.0.0.0', PERSIST mcp_http.ssl_cert = '...', PERSIST mcp_http.ssl_key = '...', GLOBAL mcp_http.token_sha256 = '...'. The persisted values are in mysqld-auto.cnf, see performance_schema.persisted_variables.
  • mcp_http.token_sha256 cannot be persisted (NOPERSIST, error 1238 with SET PERSIST), so the hash is not written next to the other settings. Put it in an option file read by mysqld, readable only by the mysqld user: [mysqld] loose-mcp_http.token_sha256 = <hex digest>. In the official images that is a file in /etc/mysql/conf.d/.
  • A non-loopback HTTPS setup persisted without ssl_cert / ssl_key cannot come back as plain HTTP off loopback: without TLS files the component refuses a non-loopback address, and without a persisted bind_address it listens on 127.0.0.1.

component_mcp requires the guard's query consumer (event_tracking_query.mcp_guard). The server therefore refuses to install it without component_mcp_guard, and refuses to uninstall the guard while it is installed. The guard is what enforces the policy on its sessions.

Variable Meaning
mcp_http.port TCP port (read-only, default 33480)
mcp_http.bind_address Listen address (read-only, default 127.0.0.1). Other than a loopback address (127.0.0.0/8, ::1, localhost), it requires TLS: the install fails without mcp_http.ssl_cert and mcp_http.ssl_key
mcp_http.ssl_cert, mcp_http.ssl_key PEM certificate and private key files, readable by mysqld (read-only). Set both to serve HTTPS. With neither, the endpoint serves plain HTTP, which is allowed only on loopback; the server's own server-cert.pem / server-key.pem work
mcp_http.threads I/O worker threads (read-only, default 4, 1 to 64). Each serves one call at a time, so this many calls run at once; connections are assigned to the workers in turn
mcp_http.max_sessions_per_account Concurrent endpoint sessions per account (read-only, default 4, 1 to 1024). A call over the cap fails with error 1203. The server's max_user_connections does not apply to these sessions
mcp_http.session_timeout_minutes Idle minutes after which an Mcp-Session-Id expires (read-only, default 30, 1 to 1440)
mcp_http.query_timeout_seconds Seconds a tool call's statement may run before it is stopped (read-only, default 30 as mysql-mcp-server's MYSQL_QUERY_TIMEOUT_SECONDS, 1 to 86400). The call then fails with error 1317, "stopped after mcp_http.query_timeout_seconds"
mcp_http.account The account (user@host) the mcp_http.token_sha256 token maps to (read-only). Tokens in mysql.mcp_tokens carry their own account
mcp_http.token_sha256 Hex SHA-256 of the bearer token (read-only, not persisted, sensitive: readable only with SENSITIVE_VARIABLES_OBSERVER). A request whose token matches neither it nor a valid row of mysql.mcp_tokens gets 401
mcp_http.allowed_origins Comma-separated Origin values accepted (read-only, default none; exact match, ASCII case-insensitive, spaces around commas ignored). Against DNS rebinding, as the MCP transport spec requires: a request that has an Origin header not in the list gets 403, before the token is checked. Requests without Origin (non-browser clients) are not affected. Add a browser-based client's origin here, e.g. http://localhost:6274 for MCP Inspector. For a listed origin the endpoint also handles CORS: it answers the browser's OPTIONS preflight (204, allowing POST with Authorization, Content-Type, Mcp-Session-Id and MCP-Protocol-Version, cached 10 minutes) without the token, and every reply carries Access-Control-Allow-Origin for it, so the page can connect directly
mcp_http.mask_columns Comma-separated patterns (read-only, default none; trimmed of Unicode whitespace). A result column whose name contains one, case-insensitive for any Unicode text, has every non-NULL value replaced by ********. These are the rules of mysql-mcp-server's MYSQL_MCP_MASK_COLUMNS, so the same setting gives the same output. Like there, it matches result column names: an alias (SELECT password AS p) is not masked, so use grants or views for data an account must not see

Token table

src/mcp/endpoint/mcp_tokens.sql, run once by an administrator, creates:

  • mysql.mcp_tokens: token_sha256 (lowercase hex SHA-256 of the token, the primary key), account (user@host), expires_at (server time, NULL for no expiry), comment, created_at;
  • 'mysql.mcp'@'localhost': a locked account whose only grant is SELECT on that table. The endpoint impersonates it to look tokens up, as MRS does for its metadata. Nobody can log in as it. The name is reserved: the script drops and recreates the account, removing any grants, role grants and proxy grants a pre-existing account of that name had (DROP USER leaves proxy grants that name the account as proxied, so the script deletes those rows from mysql.proxies_priv). DROP USER does not end open sessions, so if such an account was ever used to log in, KILL its sessions first. The script is safe to run again (the table is kept).

A request's token is hashed and checked against mcp_http.token_sha256 first (to mcp_http.account), then looked up in the table. A missing or expired row gets 401. Requests share a snapshot of the table's unexpired rows, read again once it is a second old, so INSERT issues a token and DELETE (or a past expires_at) revokes it within a second, and a flood of requests (unknown tokens included) reads the table at most once a second. The read's statement text is fixed and the hash is compared in the endpoint, in constant time, so no token hash reaches the general log, the processlist or performance_schema's statement history (those readers need not have access to the table). The mapped account then runs the call as usual: the guard's policy for MCP_USER accounts, the ACCOUNT LOCK check, the per-account session cap.

INSERT INTO mysql.mcp_tokens (token_sha256, account, expires_at, comment)
VALUES ('<hex SHA-256 of the token>', 'mcp@%', NOW() + INTERVAL 90 DAY, 'claude desktop');
DELETE FROM mysql.mcp_tokens WHERE token_sha256 = '<hex SHA-256 of the token>';  -- revoke

A token whose hash is also set as mcp_http.token_sha256 is accepted through that setting first, so deleting its row does not revoke it: use different tokens for the two, or reinstall the component without that setting.

Hash the token outside MySQL (printf %s "$TOKEN" | sha256sum): SHA2('<token>', 256) works too but puts the token in the statement text. The table is in the mysql schema and holds only hashes. MCP sessions cannot read it while mcp.deny_system_schemas is on (the default): the guard then denies them the mysql schema, whatever mcp.allowed_schemas lists (system schemas are checked first). With it off, nothing in the guard denies the table. There is no rule specific to the token table, so keep mcp.deny_system_schemas on and do not grant MCP accounts privileges on the mysql schema. Ordinary accounts have no grants there. Each request that is not the mcp_http.token_sha256 token, including a wrong token, costs one primary-key lookup in a short session (bounded by mcp_http.threads and max_connections).

Streamable HTTP

The endpoint serves both eras of the MCP Streamable HTTP transport on the same URL: the session-based revisions, as mysql-mcp-server's default (stateful) transport does, and the stateless revision 2026-07-28 (below).

  • Protocol versions: 2026-07-28, 2025-11-25, 2025-06-18, 2025-03-26 and 2024-11-05. initialize keeps the client's version when it is one of the session-based ones, and otherwise answers with 2025-11-25 (initialize does not exist in 2026-07-28). A request whose MCP-Protocol-Version header names any other version gets 400 before its body is read, with JSON-RPC error -32022 (UnsupportedProtocolVersion) whose data lists the supported versions and the one requested.
  • Sessions: initialize returns an Mcp-Session-Id (128 random bits, hex), bound to the account its token maps to. A request carrying the header must name a live session of the same account: unknown or expired, 404 (the client initializes again); another account's, 403. DELETE /mcp with the header ends the session (204; without it, 400). A session expires after mcp_http.session_timeout_minutes idle (default 30, as mysql-mcp-server), and at most 4096 are kept. Each account keeps at most 64: a new one replaces that account's least recently used session. When the table is full of other accounts' live sessions, initialize gets 503 instead of evicting them, so one token holder cannot end other accounts' sessions. A session id is not a credential: every request still needs its bearer token, and a request without a session id is served on its own.
  • Requests: POST with Content-Type: application/json (else 415) and an Accept listing application/json and text/event-stream (wildcards count; else 400), as the Go SDK checks. A body whose arrays and objects nest more than 64 levels deep gets JSON-RPC -32700 before it is parsed (rapidjson is recursive, so deeper nesting could overflow the I/O thread's stack). Replies are JSON (application/json), never an SSE stream. GET gets 405: the endpoint sends no requests or notifications of its own, so it offers no server-to-client stream.
  • Browsers: for an allowed Origin, the preflight allows POST and DELETE and the MCP headers (MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name), and replies expose Mcp-Session-Id.

The stateless revision 2026-07-28

In MCP 2026-07-28 (SEP-2575) there is no handshake and no session: every request carries its protocol version and client capabilities in _meta (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities, optionally io.modelcontextprotocol/clientInfo), and HTTP headers mirror the body. The component was already stateless per call (each tool call runs in its own impersonated session), so nothing about how calls run changes. A request is in this era when its _meta names a protocol version or its MCP-Protocol-Version header is 2026-07-28; a session-era version named consistently in both is served as that era, as the Go SDK does.

  • Methods: server/discover (the supported versions, newest first, and the tools capability), tools/list and tools/call. Every result has resultType: "complete" and the server's identity in _meta (io.modelcontextprotocol/serverInfo); server/discover and tools/list also carry the cache hints ttlMs (one hour) and cacheScope: "public" (the tool list is the same for every account). Other methods, initialize and ping included, get 404 with JSON-RPC -32601.
  • Validation, each a 400 with a JSON-RPC error (so that clients probing the era recognize a 2026-07-28 server):
  • no MCP-Protocol-Version header, or one that differs from the _meta version: -32020 (header mismatch);
  • no _meta version, no clientCapabilities object, or a malformed clientInfo: -32602;
  • no Mcp-Method header or one that differs from the method, and for tools/call no Mcp-Name header or one that differs from the tool name: -32020;
  • a jsonrpc member other than "2.0", or a request id that is not a string or an integer: -32600.
  • Errors: an unknown tool is JSON-RPC -32602 (Unknown tool: ...); a tool that fails, or a statement the guard refuses, is a result with isError: true, as in the session era.
  • No sessions: no Mcp-Session-Id is issued, and one sent with a 2026-07-28 request is ignored. DELETE with the 2026-07-28 header gets 405 and ends no session. Replies are JSON; the endpoint never sends notifications, so it needs no subscriptions/listen stream, and it ignores io.modelcontextprotocol/logLevel. Tool arguments carry no x-mcp-header annotations, so there are no Mcp-Param-* headers to check.

How a tool call runs

Each tools/call opens a "local" command-service session that impersonates the account the bearer token maps to (mcp_http.account for the mcp_http.token_sha256 token, the row's account for a table token), with no password, on one of the endpoint's I/O threads. It runs one statement for the tool: CALL mysql_mcp.list_databases(), CALL mysql_mcp.list_tables(...), CALL mysql_mcp.describe_table(...), the run_query SQL, SELECT 1 for ping, or the server information SELECT for server_info, then closes the session. Neither CLIENT_MULTI_STATEMENTS nor anything similar is set, so a; b is a parse error.

Time limit. Calls run on the endpoint's I/O threads, so a statement that never ends (SELECT SLEEP(1e20), DO SLEEP(...), a lock wait) would hold its thread, and the connections queued on it, for good. RFC 0001 §10 fuzzing made the whole endpoint refuse connections that way. Each call's statement is therefore watched. Past mcp_http.query_timeout_seconds a session of the same account runs KILL QUERY on it (an account may always kill its own statements), whatever kind of statement it is, and the call fails with error 1317. A slow call still holds its I/O thread until then, so other calls queued on that thread wait.

The guard enforces its policy on these sessions only because of two things, both checked by scripts/test-mcp-endpoint.sh:

  • The endpoint emits MYSQL_AUDIT_CONNECTION_CONNECT for each session. The server starts such sessions unaudited, so without this event no statement event would reach the guard.
  • The guard classifies a session at its first statement. Such a session raises no connection event the guard could use.

So an account with MCP_USER is read-only through the endpoint, and its schema rules and time limit apply. An account without it is not treated as an MCP session.

Facts recorded for Phase 5:

  • Locked accounts: impersonation skips the login checks, so a locked account (ACCOUNT LOCK) can be impersonated. The endpoint checks account_locked itself (done in Phase 5, above).
  • Connection limits: max_user_connections is not enforced for these sessions, so the endpoint has its own per-account cap (mcp_http.max_sessions_per_account, Phase 5). They count against max_connections, and by default the command service lets them exceed it; the endpoint turns that off (MYSQL_COMMAND_BYPASS_MAX_CONNECTIONS, 26.10), so a call fails with error 1040 when the server is full.
  • Auth backends: Router's http_auth_realm / http_auth_backend support Basic auth only, so the endpoint checks bearer tokens itself (SHA-256, constant-time compare).

Spike measurements (MySQL 26.10.0, arm64, 16 cores)

component_mcp component_mysql_rest_service
Build of the one target, fresh tree (after a 36 s configure) 95 s 265 s
.so size 3.1 MB 21 MB
Threads added to mysqld (one I/O worker, the spike) 3, released on uninstall —

Tests

scripts/test-mcp-endpoint.sh <mysql-image> <artifact-dir> installs the guard, the tool pack and component_mcp on the official image, then checks:

  • bearer auth, initialize, notifications/initialized, tools/list and the JSON-RPC errors;
  • both tools, and that run_query runs as the mapped account;
  • the result bounds: replies cut at 1000 rows or 4 MB, and the bounded consumer (peak RSS for LIMIT 1000000 and for 1 MB rows, 8000 NULL columns, NULL-only rows, errors raised after some rows or past the bound);
  • that through the endpoint an MCP_USER account's write and a mysql read are refused by the guard, and a multi-statement is a parse error;
  • that nothing is written and no session leaks;
  • that remapped to an account without MCP_USER, the same write is not restricted.

scripts/test-mcp-conformance.sh <mysql-image> <artifact-dir> is the conformance check of RFC 0001 §10 ("against at least two clients"). It drives the endpoint with two independent MCP clients over Streamable HTTP, each pinned and run in its own container:

  • MCP Inspector's CLI (@modelcontextprotocol/inspector): tools/list, tools/call (run_query, describe_table), a refused statement as a tool error, a wrong token failing to connect. The same calls run again with --protocol-era modern, which pins 2026-07-28 and does not fall back (against a server without it, the CLI fails with "the server did not offer pinned protocol version 2026-07-28 via server/discover"), and once with --protocol-era auto;
  • the official Python SDK client (mcp, scripts/mcp-conformance/sdk_client.py), in both eras. A full session (initialize at 2025-11-25, tools/list with annotations, tool calls, a guard refusal, ping, close), and the transport as the SDK uses it: it records every HTTP exchange and checks that later requests carry Mcp-Session-Id and MCP-Protocol-Version, that closing ends the session with DELETE (204), and that the SDK's optional GET stream request gets 405. Then 2026-07-28: server/discover (version, supported versions, cache hints, serverInfo), tools/list, tool calls and a guard refusal, checking on the wire that every request is a POST answered 200, carries the version in _meta and the header, Mcp-Method and (for tools/call) Mcp-Name matching the body, and that no session id is sent or issued.

Both run in the mcp-endpoint CI job after the endpoint test.

CI (integration-scripts.yml, job mcp-endpoint) builds and runs it on 26.10.0.