dbmcp-mysql 0.12.0

MySQL/MariaDB for dbmcp
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! MCP tool: `listTables`.

use std::borrow::Cow;

use dbmcp_server::pagination::{Cursor, Pager};
use dbmcp_sql::Connection as _;
use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
use rmcp::model::{ErrorData, ToolAnnotations};

use crate::MysqlHandler;
use crate::types::{ListTablesResponse, PinnedListTablesRequest, UnpinnedListTablesRequest};

/// Brief-mode SQL: `information_schema.TABLES` filtered to `BASE TABLE` rows.
///
/// `CAST(... AS CHAR)` forces a `VARCHAR` decode — `MySQL` 9 reports
/// `information_schema` text columns as `VARBINARY`, which the `String`
/// decoder rejects. `LOWER(...)` on both sides of `LIKE` makes the match
/// case-insensitive regardless of column collation (`MySQL` 9 reports
/// `TABLE_NAME` as `VARBINARY` — binary collation is case-sensitive).
const BRIEF_SQL: &str = r"
    SELECT CAST(TABLE_NAME AS CHAR)
    FROM information_schema.TABLES
    WHERE TABLE_SCHEMA = ?
      AND TABLE_TYPE = 'BASE TABLE'
      AND (? IS NULL OR LOWER(TABLE_NAME) LIKE LOWER(CONCAT('%', ?, '%')))
    ORDER BY TABLE_NAME
    LIMIT ? OFFSET ?";

/// Detailed-mode SQL: per-table `JSON_OBJECT` projection over a CTE chain.
///
/// Bind order: `database`, `pattern`, `pattern`, `limit`, `offset`, `database`.
/// `MySQL`/`MariaDB` lack `QUOTE_IDENT`; backtick-quoting is inlined per identifier.
/// `MySQL` 9 rejects inline `ORDER BY` in `JSON_ARRAYAGG`. `CAST(... AS JSON)` is
/// avoided because `MariaDB` rejects it (its `JSON` type is a `LONGTEXT` alias,
/// not a CAST target); `JSON_EXTRACT(text, '$')` re-parses to JSON on both.
/// `JSON_QUOTE` inside `GROUP_CONCAT` returns empty on `MySQL` 9 (`information_schema`
/// text columns are `VARBINARY`-typed), so column names are wrapped via plain
/// `CONCAT('"', x, '"')` — safe because identifiers cannot contain `"` or `\`.
/// JSON booleans are produced via `JSON_EXTRACT(IF(cond, 'true', 'false'), '$')`.
/// The `triggers_info` CTE renders the `DEFINER` clause in canonical
/// `SHOW CREATE TRIGGER` form with each component backtick-quoted. The
/// `DEFINER` column stores `user@host` unquoted and `user` may itself
/// contain `@` (e.g. `'foo@bar'@'localhost'`), so the host is the
/// segment after the **last** `@` (`SUBSTRING_INDEX(..., '@', -1)`) and the
/// user is everything before it (`LEFT(..., LENGTH - host_len - 1)`), with
/// embedded backticks doubled in both components.
const DETAILED_SQL: &str = r#"
WITH table_info AS (
    SELECT
        t.TABLE_SCHEMA AS table_schema,
        t.TABLE_NAME   AS table_name,
        NULLIF(t.TABLE_COMMENT, '') AS table_comment
    FROM information_schema.TABLES t
    WHERE t.TABLE_SCHEMA = ?
      AND t.TABLE_TYPE   = 'BASE TABLE'
      AND (? IS NULL OR LOWER(t.TABLE_NAME) LIKE LOWER(CONCAT('%', ?, '%')))
    ORDER BY t.TABLE_NAME
    LIMIT ? OFFSET ?
),
partitions_info AS (
    SELECT
        p.TABLE_SCHEMA,
        p.TABLE_NAME,
        MAX(p.PARTITION_METHOD IS NOT NULL) AS has_partitions
    FROM information_schema.PARTITIONS p
    WHERE p.TABLE_SCHEMA = ?
    GROUP BY p.TABLE_SCHEMA, p.TABLE_NAME
),
columns_info AS (
    SELECT
        c.TABLE_SCHEMA,
        c.TABLE_NAME,
        c.COLUMN_NAME      AS column_name,
        c.COLUMN_TYPE      AS data_type,
        c.ORDINAL_POSITION AS ordinal_position,
        (c.IS_NULLABLE = 'YES') AS nullable,
        IF(c.EXTRA LIKE '%GENERATED%', c.GENERATION_EXPRESSION, c.COLUMN_DEFAULT) AS column_default,
        NULLIF(c.COLUMN_COMMENT, '') AS column_comment
    FROM information_schema.COLUMNS c
    JOIN table_info ti
      ON ti.table_schema = c.TABLE_SCHEMA
     AND ti.table_name   = c.TABLE_NAME
),
constraints_info AS (
    SELECT
        tc.TABLE_SCHEMA,
        tc.TABLE_NAME,
        tc.CONSTRAINT_NAME AS name,
        tc.CONSTRAINT_TYPE AS type,
        JSON_EXTRACT(CONCAT('[', IFNULL(GROUP_CONCAT(CONCAT('"', kcu.COLUMN_NAME, '"') ORDER BY kcu.ORDINAL_POSITION SEPARATOR ','), ''), ']'), '$') AS columns,
        CONCAT(
            IF(tc.CONSTRAINT_TYPE = 'PRIMARY KEY', 'PRIMARY KEY (', 'UNIQUE ('),
            GROUP_CONCAT(
                CONCAT('`', REPLACE(kcu.COLUMN_NAME, '`', '``'), '`')
                ORDER BY kcu.ORDINAL_POSITION SEPARATOR ', '
            ),
            ')'
        ) AS definition,
        CAST(NULL AS CHAR)  AS referenced_table,
        CAST(NULL AS CHAR)  AS referenced_columns
    FROM information_schema.TABLE_CONSTRAINTS tc
    JOIN information_schema.KEY_COLUMN_USAGE kcu
      ON kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
     AND kcu.CONSTRAINT_NAME   = tc.CONSTRAINT_NAME
     AND kcu.TABLE_SCHEMA      = tc.TABLE_SCHEMA
     AND kcu.TABLE_NAME        = tc.TABLE_NAME
    JOIN table_info ti
      ON ti.table_schema = tc.TABLE_SCHEMA
     AND ti.table_name   = tc.TABLE_NAME
    WHERE tc.CONSTRAINT_TYPE IN ('PRIMARY KEY', 'UNIQUE')
    GROUP BY tc.TABLE_SCHEMA, tc.TABLE_NAME, tc.CONSTRAINT_NAME, tc.CONSTRAINT_TYPE
    UNION ALL
    SELECT
        tc.TABLE_SCHEMA,
        tc.TABLE_NAME,
        tc.CONSTRAINT_NAME AS name,
        'FOREIGN KEY'      AS type,
        JSON_EXTRACT(CONCAT('[', IFNULL(GROUP_CONCAT(CONCAT('"', kcu.COLUMN_NAME, '"') ORDER BY kcu.ORDINAL_POSITION SEPARATOR ','), ''), ']'), '$') AS columns,
        CONCAT(
            'FOREIGN KEY (',
            GROUP_CONCAT(
                CONCAT('`', REPLACE(kcu.COLUMN_NAME, '`', '``'), '`')
                ORDER BY kcu.ORDINAL_POSITION SEPARATOR ', '
            ),
            ') REFERENCES ',
            CONCAT('`', REPLACE(MAX(kcu.REFERENCED_TABLE_NAME), '`', '``'), '`'),
            '(',
            GROUP_CONCAT(
                CONCAT('`', REPLACE(kcu.REFERENCED_COLUMN_NAME, '`', '``'), '`')
                ORDER BY kcu.ORDINAL_POSITION SEPARATOR ', '
            ),
            ') ON UPDATE ', MAX(rc.UPDATE_RULE),
            ' ON DELETE ',  MAX(rc.DELETE_RULE)
        ) AS definition,
        MAX(kcu.REFERENCED_TABLE_NAME) AS referenced_table,
        JSON_EXTRACT(CONCAT('[', IFNULL(GROUP_CONCAT(CONCAT('"', kcu.REFERENCED_COLUMN_NAME, '"') ORDER BY kcu.ORDINAL_POSITION SEPARATOR ','), ''), ']'), '$') AS referenced_columns
    FROM information_schema.TABLE_CONSTRAINTS tc
    JOIN information_schema.KEY_COLUMN_USAGE kcu
      ON kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
     AND kcu.CONSTRAINT_NAME   = tc.CONSTRAINT_NAME
     AND kcu.TABLE_SCHEMA      = tc.TABLE_SCHEMA
     AND kcu.TABLE_NAME        = tc.TABLE_NAME
    JOIN information_schema.REFERENTIAL_CONSTRAINTS rc
      ON rc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
     AND rc.CONSTRAINT_NAME   = tc.CONSTRAINT_NAME
    JOIN table_info ti
      ON ti.table_schema = tc.TABLE_SCHEMA
     AND ti.table_name   = tc.TABLE_NAME
    WHERE tc.CONSTRAINT_TYPE = 'FOREIGN KEY'
    GROUP BY tc.TABLE_SCHEMA, tc.TABLE_NAME, tc.CONSTRAINT_NAME
    UNION ALL
    SELECT
        cc.CONSTRAINT_SCHEMA AS TABLE_SCHEMA,
        tc.TABLE_NAME,
        cc.CONSTRAINT_NAME   AS name,
        'CHECK'              AS type,
        JSON_ARRAY()         AS columns,
        cc.CHECK_CLAUSE      AS definition,
        CAST(NULL AS CHAR)   AS referenced_table,
        CAST(NULL AS CHAR)   AS referenced_columns
    FROM information_schema.CHECK_CONSTRAINTS cc
    JOIN information_schema.TABLE_CONSTRAINTS tc
      ON tc.CONSTRAINT_SCHEMA = cc.CONSTRAINT_SCHEMA
     AND tc.CONSTRAINT_NAME   = cc.CONSTRAINT_NAME
    JOIN table_info ti
      ON ti.table_schema = tc.TABLE_SCHEMA
     AND ti.table_name   = tc.TABLE_NAME
),
indexes_info AS (
    SELECT
        s.TABLE_SCHEMA,
        s.TABLE_NAME,
        s.INDEX_NAME AS index_name,
        GROUP_CONCAT(
            CASE
                WHEN s.SUB_PART IS NOT NULL THEN CONCAT('`', REPLACE(s.COLUMN_NAME, '`', '``'), '`', '(', s.SUB_PART, ')')
                ELSE CONCAT('`', REPLACE(s.COLUMN_NAME, '`', '``'), '`')
            END
            ORDER BY s.SEQ_IN_INDEX SEPARATOR ', '
        ) AS definition_cols,
        JSON_EXTRACT(CONCAT('[', IFNULL(GROUP_CONCAT(CONCAT('"', s.COLUMN_NAME, '"') ORDER BY s.SEQ_IN_INDEX SEPARATOR ','), ''), ']'), '$') AS columns,
        (MIN(s.NON_UNIQUE) = 0)        AS is_unique,
        (s.INDEX_NAME = 'PRIMARY')     AS is_primary,
        LOWER(MIN(s.INDEX_TYPE))       AS method,
        MIN(s.INDEX_TYPE)              AS index_type_raw
    FROM information_schema.STATISTICS s
    JOIN table_info ti
      ON ti.table_schema = s.TABLE_SCHEMA
     AND ti.table_name   = s.TABLE_NAME
    GROUP BY s.TABLE_SCHEMA, s.TABLE_NAME, s.INDEX_NAME
),
triggers_info AS (
    SELECT
        tr.EVENT_OBJECT_SCHEMA AS TABLE_SCHEMA,
        tr.EVENT_OBJECT_TABLE  AS TABLE_NAME,
        tr.TRIGGER_NAME        AS trigger_name,
        CONCAT(
            'CREATE DEFINER=`',
            REPLACE(LEFT(tr.DEFINER, LENGTH(tr.DEFINER) - LENGTH(SUBSTRING_INDEX(tr.DEFINER, '@', -1)) - 1), '`', '``'),
            '`@`',
            REPLACE(SUBSTRING_INDEX(tr.DEFINER, '@', -1), '`', '``'),
            '`',
            ' TRIGGER ', '`', REPLACE(tr.TRIGGER_NAME, '`', '``'), '`',
            ' ', tr.ACTION_TIMING, ' ', tr.EVENT_MANIPULATION,
            ' ON ',
            '`', REPLACE(tr.EVENT_OBJECT_SCHEMA, '`', '``'), '`',
            '.',
            '`', REPLACE(tr.EVENT_OBJECT_TABLE, '`', '``'), '`',
            ' FOR EACH ROW ', tr.ACTION_STATEMENT
        ) AS definition
    FROM information_schema.TRIGGERS tr
    JOIN table_info ti
      ON ti.table_schema = tr.EVENT_OBJECT_SCHEMA
     AND ti.table_name   = tr.EVENT_OBJECT_TABLE
)
SELECT
    CAST(ti.table_name AS CHAR) AS name,
    JSON_OBJECT(
        'schema',  ti.table_schema,
        'kind',    IF(COALESCE(pi.has_partitions, FALSE), 'PARTITIONED_TABLE', 'TABLE'),
        'owner',   NULL,
        'comment', ti.table_comment,
        'columns', COALESCE((
            SELECT JSON_ARRAYAGG(JSON_OBJECT(
                'name',            ci.column_name,
                'dataType',        ci.data_type,
                'ordinalPosition', ci.ordinal_position,
                'nullable',        JSON_EXTRACT(IF(ci.nullable = 1, 'true', 'false'), '$'),
                'default',         ci.column_default,
                'comment',         ci.column_comment
            ))
            FROM columns_info ci
            WHERE ci.TABLE_SCHEMA = ti.table_schema AND ci.TABLE_NAME = ti.table_name
        ), JSON_ARRAY()),
        'constraints', COALESCE((
            SELECT JSON_ARRAYAGG(JSON_OBJECT(
                'name',              co.name,
                'type',              co.type,
                'columns',           JSON_EXTRACT(co.columns, '$'),
                'definition',        co.definition,
                'referencedTable',   co.referenced_table,
                'referencedColumns', JSON_EXTRACT(co.referenced_columns, '$')
            ))
            FROM constraints_info co
            WHERE co.TABLE_SCHEMA = ti.table_schema AND co.TABLE_NAME = ti.table_name
        ), JSON_ARRAY()),
        'indexes', COALESCE((
            SELECT JSON_ARRAYAGG(JSON_OBJECT(
                'name',       ii.index_name,
                'columns',    JSON_EXTRACT(ii.columns, '$'),
                'unique',     JSON_EXTRACT(IF(ii.is_unique = 1, 'true', 'false'), '$'),
                'primary',    JSON_EXTRACT(IF(ii.is_primary = 1, 'true', 'false'), '$'),
                'method',     ii.method,
                'definition', IF(ii.is_primary = 1,
                    CONCAT('PRIMARY KEY (', ii.definition_cols, ') USING ', ii.index_type_raw),
                    CONCAT(
                        'CREATE ',
                        CASE
                            WHEN ii.is_unique = 1                THEN 'UNIQUE '
                            WHEN ii.index_type_raw = 'FULLTEXT'  THEN 'FULLTEXT '
                            WHEN ii.index_type_raw = 'SPATIAL'   THEN 'SPATIAL '
                            ELSE ''
                        END,
                        'INDEX ', '`', REPLACE(ii.index_name, '`', '``'), '`',
                        ' ON ',
                        '`', REPLACE(ti.table_schema, '`', '``'), '`',
                        '.',
                        '`', REPLACE(ti.table_name, '`', '``'), '`',
                        '(', ii.definition_cols, ') USING ', ii.index_type_raw
                    )
                )
            ))
            FROM indexes_info ii
            WHERE ii.TABLE_SCHEMA = ti.table_schema AND ii.TABLE_NAME = ti.table_name
        ), JSON_ARRAY()),
        'triggers', COALESCE((
            SELECT JSON_ARRAYAGG(JSON_OBJECT(
                'name',       tri.trigger_name,
                'definition', tri.definition,
                'enabled',    JSON_EXTRACT('true', '$')
            ))
            FROM triggers_info tri
            WHERE tri.TABLE_SCHEMA = ti.table_schema AND tri.TABLE_NAME = ti.table_name
        ), JSON_ARRAY())
    ) AS entry
FROM table_info ti
LEFT JOIN partitions_info pi
  ON pi.TABLE_SCHEMA = ti.table_schema
 AND pi.TABLE_NAME   = ti.table_name
ORDER BY ti.table_name"#;

const NAME: &str = "listTables";
const TITLE: &str = "List Tables";
const DESCRIPTION_PINNED: &str = include_str!("../../assets/tools/list_tables/pinned.md");
const DESCRIPTION_UNPINNED: &str = include_str!("../../assets/tools/list_tables/unpinned.md");

fn annotations() -> ToolAnnotations {
    ToolAnnotations::new()
        .read_only(true)
        .destructive(false)
        .idempotent(true)
        .open_world(false)
}

/// Marker type for the `listTables` MCP tool (pinned variant — no `database` field).
pub(crate) struct PinnedListTablesTool;

impl ToolBase for PinnedListTablesTool {
    type Parameter = PinnedListTablesRequest;
    type Output = ListTablesResponse;
    type Error = ErrorData;

    fn name() -> Cow<'static, str> {
        NAME.into()
    }

    fn title() -> Option<String> {
        Some(TITLE.into())
    }

    fn description() -> Option<Cow<'static, str>> {
        Some(DESCRIPTION_PINNED.into())
    }

    fn annotations() -> Option<ToolAnnotations> {
        Some(annotations())
    }
}

impl AsyncTool<MysqlHandler> for PinnedListTablesTool {
    async fn invoke(handler: &MysqlHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
        handler
            .list_tables(None, params.cursor, params.search, params.detailed)
            .await
    }
}

/// Marker type for the `listTables` MCP tool (unpinned variant — carries `database`).
pub(crate) struct UnpinnedListTablesTool;

impl ToolBase for UnpinnedListTablesTool {
    type Parameter = UnpinnedListTablesRequest;
    type Output = ListTablesResponse;
    type Error = ErrorData;

    fn name() -> Cow<'static, str> {
        NAME.into()
    }

    fn title() -> Option<String> {
        Some(TITLE.into())
    }

    fn description() -> Option<Cow<'static, str>> {
        Some(DESCRIPTION_UNPINNED.into())
    }

    fn annotations() -> Option<ToolAnnotations> {
        Some(annotations())
    }
}

impl AsyncTool<MysqlHandler> for UnpinnedListTablesTool {
    async fn invoke(handler: &MysqlHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
        handler
            .list_tables(
                params.database,
                params.inner.cursor,
                params.inner.search,
                params.inner.detailed,
            )
            .await
    }
}

impl MysqlHandler {
    /// Lists one page of tables in a database, optionally filtered and/or detailed.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorData`] with code `-32602` if `cursor` is malformed, or an
    /// internal-error [`ErrorData`] if `database` is invalid or the underlying
    /// query fails.
    pub async fn list_tables(
        &self,
        database: Option<String>,
        cursor: Option<Cursor>,
        search: Option<String>,
        detailed: bool,
    ) -> Result<ListTablesResponse, ErrorData> {
        let database = database
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| self.connection.default_database_name());

        let pattern = search.as_deref().map(str::trim).filter(|s| !s.is_empty());
        let pager = Pager::new(cursor, self.config.page_size);

        if detailed {
            let rows: Vec<(String, sqlx::types::Json<serde_json::Value>)> = self
                .connection
                .fetch(
                    sqlx::query(DETAILED_SQL)
                        .bind(database)
                        .bind(pattern)
                        .bind(pattern)
                        .bind(pager.limit())
                        .bind(pager.offset())
                        .bind(database),
                    None,
                )
                .await?;
            let (rows, next_cursor) = pager.paginate(rows);
            return Ok(ListTablesResponse::detailed(
                rows.into_iter().map(|(name, json)| (name, json.0)).collect(),
                next_cursor,
            ));
        }

        let rows: Vec<String> = self
            .connection
            .fetch_scalar(
                sqlx::query(BRIEF_SQL)
                    .bind(database)
                    .bind(pattern)
                    .bind(pattern)
                    .bind(pager.limit())
                    .bind(pager.offset()),
                None,
            )
            .await?;
        let (tables, next_cursor) = pager.paginate(rows);
        Ok(ListTablesResponse::brief(tables, next_cursor))
    }
}