Zum Inhalt springen
Plugins

tooling Plugin

MySQL DB Browser

The `mysql_db_browser` plugin (`plugins/mysql_db_browser/`) lets an operator register connections to arbitrary external MySQL databases and browse/query them in a grid-first, Sequel Pro/TablePlus-style browser. It is a self-contained Rails engine plugin, installed but disabled by default (`default_enabled: false`, `disableable: true`, category `tooling`) and depends on the bundled `credential_store` plugin. In Syrus's plugin architecture, the plugin's own `PluginRecord.enabled` toggle *is* the feature gate — there is no separate `Feature` flag. Every controller action checks `MysqlDbBrowser.enabled?` (the plugin record enabled) and `Current.user.admin?`, so the whole surface is admin-only.

mysql_db_browserQuellcode

MySQL DB Browser

The mysql_db_browser plugin (plugins/mysql_db_browser/) lets an operator register connections to arbitrary external MySQL databases and browse/query them in a grid-first, Sequel Pro/TablePlus-style browser. It is a self-contained Rails engine plugin, installed but disabled by default (default_enabled: false, disableable: true, category tooling) and depends on the bundled credential_store plugin. In Syrus's plugin architecture, the plugin's own PluginRecord.enabled toggle *is* the feature gate — there is no separate Feature flag. Every controller action checks MysqlDbBrowser.enabled? (the plugin record enabled) and Current.user.admin?, so the whole surface is admin-only.

Connections (MysqlConnection)

app/models/mysql_connection.rb stores non-secret metadata: label, host, port, username, an optional default_database, and credential_store_credential_id. New and rotated passwords are written as credential_store records with credential type mysql_db_browser.connection; the DB Browser row keeps only the reference and safe metadata needed for listing and policy decisions. The legacy encrypted credentials JSON column remains as a compatibility fallback for connections created before the credential-store migration, so existing external database access is not stranded. Rotating the password moves that row onto credential-store-backed storage and clears the legacy payload.

Two independent boolean opt-ins, both default false:

  • agentic_access_enabled - opts this specific connection into agentic

access; see Agentic access below.

  • allow_writes - see Read-only guardrails below.

Managed from Admin → DB Browser (/db_browser, admin-only sidebar page, MysqlDbBrowser::SidebarPages) via GET/POST/PATCH/DELETE /api/v1/app/admin/mysql_connections and a connect-test endpoint (POST .../test or .../:id/test, backed by MysqlDbBrowser::ConnectionTester) that never persists a draft connection. The create/edit form also accepts a mysql:// or mysql2:// connection URL and fills label, host, port, username, password, and default database from it before saving through the same API.

Schema browsing

MysqlDbBrowser::SchemaInspector introspects an explicit external Mysql2::Client (built from a brokered credential-store lease, or the legacy encrypted fallback for pre-migration rows) rather than ActiveRecord::Base.connection - it mirrors AdminMysql::Inspector's safe-section/timeout-hint/truncation design but is not tied to Syrus's own database. GET .../mysql_connections/:id/schema lists databases (always including the four MySQL system schemas - information_schema, performance_schema, mysql, sys - flagged via system_schema: true, not special-cased); .../schema/:database/tables lists tables; .../tables/:table returns table info, columns, and indexes. Every section degrades to { available: false, error: { class, message, hint? } } on a MySQL error (most commonly a GRANT denial) instead of failing the whole request.

Content / Query / Live tabs

The DB Browser page (MysqlConnections.tsx) is a dual-mode browser per the Sequel Pro/TablePlus UX: a Browse tab (the schema tree above, with a selected table opening Content - a sortable results grid, the default - and Structure - the columns/indexes view), plus two connection-level tabs, Query and Live.

  • Content - GET .../schema/:database/tables/:table/content builds

SELECT * FROM \db\.\table\ [WHERE ...] ORDER BY ... LIMIT n+1 OFFSET m server-side and returns it alongside a filter_schema (MysqlDbBrowser::FilterSchemaBuilder, derived from the table's introspected columns: MySQL type -> bucket -> operator set - tinyint(1) -> boolean, other numerics -> number, date/datetime/timestamp/time/year -> date, enum -> enum with parsed allowed values, everything else -> string) so the frontend can drive the existing FilterBar component (app/frontend/components/FilterBar.tsx) with no new filter-chip UI. MysqlDbBrowser::FilterTreeSqlCompiler compiles the FilterBar FilterTree (decoded from the q param via Filters::QueryParam.decode / Filters::Ast.parse - the same wire format every other FilterBar consumer uses) into a WHERE fragment, escaping every value through the same Mysql2::Client that runs the query and quoting identifiers with doubled backticks. Pagination is Prev/Next only (an exact COUNT(*) on an arbitrary external table could be an unbounded full scan, which would defeat the row-limit/timeout guardrails); has_more is derived by requesting per_page + 1 rows.

  • Query - a raw SQL editor running through POST .../mysql_connections/:id/query

(body { mysql_query: { sql } }).

  • Live - the same raw-SQL endpoint with three canned, `refetchInterval:

10_000 statements generalizing AdminMysql.tsx's process-list/global-status/ statement-summary views (built for Syrus's own database) to any connection: SELECT

  • FROM information_schema.PROCESSLIST, SELECT ... FROM

performance_schema.global_status, SELECT ... FROM performance_schema.events_statements_summary_by_digest`. The statement summary includes total and average latency, execution count, rows examined, and normalized sample SQL. These are ordinary SELECTs against schemas the schema explorer already treats as browsable, so no bespoke diagnostics controller/service was needed.

Query builder

The Query Builder sub-tab (alongside Content/Structure for a selected table) is a Metabase-notebook-style no-code sequence of steps that compiles to SQL and runs through the same guardrailed executor as Content/Query, rendering into the same results grid. Steps:

  • Table - a picker (the button[aria-haspopup=listbox] +

div[role=listbox] dropdown pattern from ChatModeSelector/ ChatModelSelector in Compose.tsx, generalized into MysqlPickerDropdown.tsx) defaulting to the table selected in the schema tree, changeable to any table in the same database.

  • Columns or Summarize - either a raw column checklist (unchecked =

SELECT *), or an aggregate/group-by summary: repeatable {function, column, alias} rows (count/sum/avg/min/max, count additionally accepts *) plus a group-by column checklist.

  • Join - optional, single join, picked from the base table's foreign

keys as surfaced by the schema explorer (SchemaInspector#table's new foreign_keys section - see below) rather than a free-form table+column picker. Selecting a relationship (either its outgoing or incoming direction) fills in the join table and both join columns; inner/left is a separate toggle (left by default).

  • Filter - FilterBar, exactly like the Content tab, driven by a

filter_schema the server derives from the base table's columns (and the joined table's, qualified table.column, when a join is present) via FilterSchemaBuilder.build(columns, table_prefix:).

  • Sort - a column (or, in Summarize mode, a group-by column or

aggregation alias) plus direction.

  • Limit - 1-500, default 100.

GET .../mysql_connections/:id/schema/:database/query_builder?spec=<json>&q=<filter> (MysqlQueryController#query_builder) parses the JSON spec, fetches real column lists for the base table (and join table, if any) via SchemaInspector, and hands both to MysqlDbBrowser::QueryBuilderCompiler, which validates every table/column/ aggregation-function/join-type/sort reference against that real schema before compiling a single SELECT (raising InvalidSpec, rendered as 422 invalid_spec, on anything unrecognized) - identifiers are still quoted through SqlIdentifier.quote (shared with FilterTreeSqlCompiler and the Content tab's raw SELECT builder; now dot-aware, so table.column refs quote each segment independently) so nothing can break out of identifier position even if validation were somehow bypassed. The selected database qualifies every table and column reference in the generated statement, including joins and FilterBar predicates, so execution never depends on the connection's default database. Column references throughout the spec (columns, aggregations[].column, group_by, join.from_column/join.to_column, sort.column) are always "table.column" qualified strings - the frontend always knows which table a picker belongs to, so the compiler has one column-resolution code path regardless of whether a join is present. The endpoint is auto-run (declarative useQuery, keyed on the JSON-stringified spec plus the q filter param) the same way the Content tab is - there is no manual "Run" step - so the filter step's filter_schema is available as soon as a valid table/column selection exists, before the operator has added any filter. The response includes the compiled statement (already part of QueryExecutor's result payload), rendered read-only above the results grid so the operator can see exactly what ran.

SchemaInspector#table's new foreign_keys section returns both directions symmetrically: {constraint_name, direction, from_table, from_column, to_table, to_column}, where from_table/from_column is always the FK-holding side and to_table/to_column is what it references, regardless of whether the row is "outgoing" (this table holds the FK) or "incoming" (another table's FK points back at this one). The Structure tab renders this alongside Columns/Indexes; the query builder's join step filters it to rows touching the currently selected table and derives the join spec from whichever side isn't that table.

Agentic access

Coworkers are deny-by-default. The plugin declares the mysql.read grant beside its gated tool set; owners choose one of their agentic-access-enabled connections as the grant scope. Without that grant no MySQL tools are advertised. With it, all five tools below are visible, but connection listing and every direct lookup are restricted to the selected connection. Coworker queries remain read-only even when that connection has allow_writes enabled, and each schema/query audit records both the owner user and coworker identity.

Each MysqlConnection carries its own agentic_access_enabled opt-in (surfaced as a checkbox on the connection create/edit form, default false), independent of the plugin's own enable/disable toggle. When set, that specific connection becomes queryable by workflow and chat agents through five MCP tools exposed via mcp_tool_set/chat_mcp_tool_set (MysqlDbBrowser::WorkflowToolSet / MysqlDbBrowser::ChatToolSet, plugins/mysql_db_browser/app/services/mysql_db_browser/{workflow,chat}_tool_set.rb):

  • mysql_db_browser_list_connections - lists agentic-enabled DB Browser

connections using safe metadata only: id, label, default_database, agentic_access_enabled, allow_writes, created_at, and updated_at. It deliberately omits host, port, username, credentials, and password presence. Connections outside the caller's credential scope are omitted. Agents should call this first to discover the correct mysql_connection_id before using any schema or query tool.

  • mysql_db_browser_list_databases / mysql_db_browser_list_tables /

mysql_db_browser_describe_table - thin MCP wrappers around SchemaInspector#databases/#tables/#table, the same schema-browse path the UI uses.

  • mysql_db_browser_execute_query - runs a statement through

QueryExecutor#execute, the same guardrailed path as the Query/Content tabs (see Read-only guardrails and audit log below) - read-only unless the connection also has allow_writes, and every attempt is recorded to MysqlQueryAudit with the acting agent's user.

For production debugging, common Syrus event tables are browser_error_events for client-side failures, backend_exception_events for server exceptions, and performance_log_events for timed backend work. Start with narrow time ranges and selective columns; the coworker query path enforces the normal row limit and statement timeout.

Gating is per-connection and credential scope. New connections default to the creator's user scope; administrators may explicitly choose user, repository, team, or instance scope from the connection form. Existing credential-backed connections keep their instance scope until an administrator narrows them. Legacy rows whose password still lives on MysqlConnection are shown as legacy in the UI and are usable by administrators only; re-entering the password in Edit migrates the secret into Credential Store and applies the selected scope.

This is a deliberate departure from AdminMysql::WorkflowToolSet/ChatToolSet (which gate on McpToolPolicy.syrus_repository?/chat_session.user.admin?, since those tools only ever touch Syrus's own database). There is no framework hook to resolve an individual tool call's params from available_for?/ available_for_context? - those are only checked once, at MCP manifest-build time, before any call happens (see Mcp::Sidecar.plugin_tools_for / .plugin_workflow_tools_for). So available_for?/available_for_context? only decide whether the tool set appears in the manifest at all (plugin enabled, WORKFLOW_IMPLEMENT role for workflow runs, and at least one configured MysqlConnection so an agent can inspect safe connection metadata); the actual per-connection authorization happens inside each tool's own #call, via MysqlDbBrowser::AgenticAccess.connection!(id) - it resolves the mysql_connection_id named in that call's params and raises unless that specific row has agentic_access_enabled: true and the backing credential's scope policy accepts the caller. Repository scope also requires the repository to be present in the run/chat token's allowed repository IDs. An unusable connection is reported exactly like a missing connection, mirroring Mcp::Tools::AuthorizationSupport's find_job!/find_run! pattern for first-party tools. AgenticAccess.connection!/.connection_with_write_access! delegate their gating logic to the shared Syrus::Host::AgenticConnection concern, which K8sCluster::AgenticAccess also extends - see the K8s Cluster docs' Agentic write-access gating section for the parallel shape.

The plugin also publishes canonical permission metadata for operator-managed rules. It distinguishes connection, database, table, query, schema, and administrative resource scopes. Metadata reads are medium-risk and may be delegated for an invocation, chat session, Job, or permanently, since they only read. Query execution splits on what the SQL is: SQL that classifies as read-only may be granted permanently, per connection, while every other form keeps an invocation-only ceiling. SQL classification separates reads, data writes, schema changes, and administrative effects. Unknown, compound, executable-comment, and CTE forms fall back to the query descriptor's critical maximum risk, so they are never covered by a read grant. Because a rule is matched against the *classified* operation, a standing read grant cannot be widened by sending different SQL - a write simply classifies as a different operation and asks again. Permission fingerprints normalize SQL whitespace, while displayed authorization arguments replace the SQL text entirely. The mysql_read_only and mysql_query_operator presets are recommendations only and create no authority until an operator reviews and confirms them.

Read-only guardrails and audit log

MysqlDbBrowser::QueryExecutor is the single execution path for both the Query tab and the Content tab (the latter via #execute_select, which yields the connected client so the caller can build the final SQL with the same escaper before running it). Guardrails, mirroring AdminMysql::Inspector:

  • Credential access. Credential-store-backed rows acquire the MySQL

password through CredentialStore::Broker for admin UI schema browsing, table content, raw queries, password testing, and workflow/chat MCP tools. Broker lease events record admin/workflow/chat credential access without writing password material to API responses, MCP transcripts, query audit rows, or logs. Legacy encrypted rows are still read directly only until an operator rotates the password.

  • Read-only by default. A statement is accepted unmodified only if it is

a read query or safe diagnostic/metadata statement: SELECT, SHOW, DESCRIBE/DESC, or EXPLAIN for SELECT/CTE/table/DML plans. A WITH statement is not automatically read-only: QueryExecutor parses past the CTE definition(s) - comment/quote-aware, balanced-paren matching, handling ordinary MySQL block and line comments, an optional column list, and RECURSIVE - to find the terminal statement after them, and only treats it as read-only when that terminal statement is SELECT/TABLE; a MySQL 8 CTE like WITH x AS (...) UPDATE .../ DELETE .../INSERT ... requires write access despite the leading WITH. A WITH statement Syrus can't parse is treated as not read-only, erring toward requiring write access rather than assuming safety. MySQL executable comments (/*! ... */) outside strings and inert comments are likewise treated as potentially mutating and require write access; their contents are SQL on matching server versions, not comments the classifier can safely skip. EXPLAIN ANALYZE is allowed only for read statements because MySQL executes the statement while collecting runtime plan data, including applying the terminal-statement check to WITH queries. Statements accepted as reads are also executed inside START TRANSACTION READ ONLY and rolled back, providing a server-side backstop for the classifier. Anything else is rejected with 403 write_not_allowed unless the connection's allow_writes is true. The check runs before opening a connection, via an explicit MysqlDbBrowser::AgenticAccess.connection_with_write_access!(connection) call rather than QueryExecutor inlining an allow_writes? check itself - the same shared-concern gate K8sCluster::AgenticAccess.cluster_with_write_access! uses, applied to the connection ExecuteQueryTool already resolved via .connection! rather than re-resolving by id.

  • SELECT ... INTO OUTFILE/DUMPFILE is always rejected, even on a

connection with allow_writes enabled. It's classified read-only by the grammar above (it doesn't touch table data), but it writes an arbitrary file to the MySQL server's filesystem when the connected user has the FILE privilege - outside this console's read-only-by-default safe envelope. Rejected with FilesystemWriteNotAllowed, audited as a failed attempt, before any write-access check runs.

  • Statement-timeout hint - literal SELECT statements get

SELECT /*+ MAX_EXECUTION_TIME(5000) */ ... prepended (skipped for WITH CTEs, since the hint must immediately follow SELECT).

  • Row-limit clamping - SELECTs stream (stream: true, cache_rows: false)

and stop after limit + 1 rows (abandon_results! on early stop) rather than buffering an entire result set, reporting truncated: true when hit.

  • Value truncation - string cell values over 2,000 bytes are cut with

String#safe_byteslice (never raw byteslice, per the UTF-8 truncation convention) and suffixed with … as each row streams in. Retained result data is also capped at 1 MB across all rows.

  • Structured GRANT-error hints - a query-time Mysql2::Error (bad SQL,

missing privileges, timeout) doesn't raise; it comes back as { available: false, error: { class, message, hint? } } with a 200, so the Query/Content tabs can show it inline. A connection-time failure (bad host/credentials) raises Unavailable, rendered as 502 connection_unavailable.

  • Audit log - every query and schema-inspection statement, successful,

rejected, or failed, is recorded to MysqlQueryAudit (mysql_connection, user, statement, read_only, success, row_count, error_message, duration_ms). A pending row is persisted before MySQL executes and then updated with the outcome. Audit creation failures stop execution, and stored statements and error messages are safely bounded to their audit columns' 65,535-byte capacity. Coworker connection discovery and requests refused before SQL execution are recorded as synthetic MCP tool call statements so every coworker tool call retains the coworker identity even when there is no database statement.