Skip to main content

database_mcp_mysql/tools/
get_table_schema.rs

1//! MCP tool: `getTableSchema`.
2
3use std::borrow::Cow;
4use std::collections::HashMap;
5
6use database_mcp_server::types::{GetTableSchemaRequest, TableSchemaResponse};
7use database_mcp_sql::Connection as _;
8use database_mcp_sql::SqlError;
9use database_mcp_sql::sanitize::{quote_ident, quote_literal, validate_ident};
10use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
11use rmcp::model::{ErrorData, ToolAnnotations};
12use serde_json::{Value, json};
13use sqlparser::dialect::MySqlDialect;
14
15use crate::MysqlHandler;
16
17/// Marker type for the `getTableSchema` MCP tool.
18pub(crate) struct GetTableSchemaTool;
19
20impl GetTableSchemaTool {
21    const NAME: &'static str = "getTableSchema";
22    const TITLE: &'static str = "Get Table Schema";
23    const DESCRIPTION: &'static str = r#"Get column definitions and foreign key relationships for a table. Requires `database` and `table` — call `listDatabases` and `listTables` first.
24
25<usecase>
26ALWAYS call this before writing queries to understand:
27- Column names and data types
28- Which columns are nullable, primary keys, or have defaults
29- Foreign key relationships for writing JOINs
30</usecase>
31
32<examples>
33✓ "What columns does the orders table have?" → getTableSchema(database="mydb", table="orders")
34✓ Before writing a SELECT → getTableSchema first to confirm column names
35✓ "How are users and orders related?" → check foreign keys in both tables
36</examples>
37
38<what_it_returns>
39A JSON object with table and columns keyed by column name, each containing type, nullable, key, default, and foreignKey info.
40</what_it_returns>"#;
41}
42
43impl ToolBase for GetTableSchemaTool {
44    type Parameter = GetTableSchemaRequest;
45    type Output = TableSchemaResponse;
46    type Error = ErrorData;
47
48    fn name() -> Cow<'static, str> {
49        Self::NAME.into()
50    }
51
52    fn title() -> Option<String> {
53        Some(Self::TITLE.into())
54    }
55
56    fn description() -> Option<Cow<'static, str>> {
57        Some(Self::DESCRIPTION.into())
58    }
59
60    fn annotations() -> Option<ToolAnnotations> {
61        Some(
62            ToolAnnotations::new()
63                .read_only(true)
64                .destructive(false)
65                .idempotent(true)
66                .open_world(false),
67        )
68    }
69}
70
71impl AsyncTool<MysqlHandler> for GetTableSchemaTool {
72    async fn invoke(handler: &MysqlHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
73        Ok(handler.get_table_schema(params).await?)
74    }
75}
76
77impl MysqlHandler {
78    /// Returns column definitions with foreign key relationships.
79    ///
80    /// # Errors
81    ///
82    /// Returns [`SqlError`] if validation fails or the query errors.
83    pub async fn get_table_schema(
84        &self,
85        GetTableSchemaRequest { database, table }: GetTableSchemaRequest,
86    ) -> Result<TableSchemaResponse, SqlError> {
87        validate_ident(&database)?;
88        validate_ident(&table)?;
89
90        // 1. Get basic schema
91        let describe_sql = format!(
92            "DESCRIBE {}.{}",
93            quote_ident(&database, &MySqlDialect {}),
94            quote_ident(&table, &MySqlDialect {}),
95        );
96        let schema_rows = self.connection.fetch_json(describe_sql.as_str(), None).await?;
97
98        if schema_rows.is_empty() {
99            return Err(SqlError::TableNotFound(format!("{database}.{table}")));
100        }
101
102        let mut columns: HashMap<String, Value> = HashMap::new();
103        for row in &schema_rows {
104            if let Some(col_name) = row.get("Field").and_then(|v| v.as_str()) {
105                columns.insert(
106                    col_name.to_string(),
107                    json!({
108                        "type": row.get("Type").unwrap_or(&Value::Null),
109                        "nullable": row.get("Null").and_then(|v| v.as_str()).is_some_and(|s| s.to_uppercase() == "YES"),
110                        "key": row.get("Key").unwrap_or(&Value::Null),
111                        "default": row.get("Default").unwrap_or(&Value::Null),
112                        "extra": row.get("Extra").unwrap_or(&Value::Null),
113                        "foreignKey": Value::Null,
114                    }),
115                );
116            }
117        }
118
119        // 2. Get FK relationships
120        let fk_sql = format!(
121            r"
122            SELECT
123                kcu.COLUMN_NAME as column_name,
124                kcu.CONSTRAINT_NAME as constraint_name,
125                kcu.REFERENCED_TABLE_NAME as referenced_table,
126                kcu.REFERENCED_COLUMN_NAME as referenced_column,
127                rc.UPDATE_RULE as on_update,
128                rc.DELETE_RULE as on_delete
129            FROM information_schema.KEY_COLUMN_USAGE kcu
130            INNER JOIN information_schema.REFERENTIAL_CONSTRAINTS rc
131                ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
132                AND kcu.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA
133            WHERE kcu.TABLE_SCHEMA = {}
134              AND kcu.TABLE_NAME = {}
135              AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
136            ORDER BY kcu.CONSTRAINT_NAME, kcu.ORDINAL_POSITION",
137            quote_literal(&database),
138            quote_literal(&table),
139        );
140
141        let fk_rows = self.connection.fetch_json(fk_sql.as_str(), None).await?;
142
143        for fk_row in &fk_rows {
144            if let Some(col_name) = fk_row.get("column_name").and_then(|v| v.as_str())
145                && let Some(col_info) = columns.get_mut(col_name)
146                && let Some(obj) = col_info.as_object_mut()
147            {
148                obj.insert(
149                    "foreignKey".to_string(),
150                    json!({
151                        "constraintName": fk_row.get("constraint_name"),
152                        "referencedTable": fk_row.get("referenced_table"),
153                        "referencedColumn": fk_row.get("referenced_column"),
154                        "onUpdate": fk_row.get("on_update"),
155                        "onDelete": fk_row.get("on_delete"),
156                    }),
157                );
158            }
159        }
160
161        Ok(TableSchemaResponse {
162            table,
163            columns: json!(columns),
164        })
165    }
166}