Skip to main content

database_mcp_sqlite/tools/
get_table_schema.rs

1//! MCP tool: `get_table_schema`.
2
3use std::borrow::Cow;
4use std::collections::HashMap;
5
6use database_mcp_server::AppError;
7use database_mcp_server::types::TableSchemaResponse;
8use database_mcp_sql::identifier::validate_identifier;
9use database_mcp_sql::timeout::execute_with_timeout;
10use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
11use rmcp::model::{ErrorData, ToolAnnotations};
12use serde_json::{Value, json};
13use sqlx::Row;
14use sqlx::sqlite::SqliteRow;
15
16use crate::SqliteHandler;
17use crate::types::GetTableSchemaRequest;
18
19/// Marker type for the `get_table_schema` MCP tool.
20pub(crate) struct GetTableSchemaTool;
21
22impl GetTableSchemaTool {
23    const NAME: &'static str = "get_table_schema";
24    const DESCRIPTION: &'static str =
25        "Get column definitions (type, nullable, key, default) and foreign key\nrelationships for a table.";
26}
27
28impl ToolBase for GetTableSchemaTool {
29    type Parameter = GetTableSchemaRequest;
30    type Output = TableSchemaResponse;
31    type Error = ErrorData;
32
33    fn name() -> Cow<'static, str> {
34        Self::NAME.into()
35    }
36
37    fn description() -> Option<Cow<'static, str>> {
38        Some(Self::DESCRIPTION.into())
39    }
40
41    fn annotations() -> Option<ToolAnnotations> {
42        Some(
43            ToolAnnotations::new()
44                .read_only(true)
45                .destructive(false)
46                .idempotent(true)
47                .open_world(false),
48        )
49    }
50}
51
52impl AsyncTool<SqliteHandler> for GetTableSchemaTool {
53    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
54        Ok(handler.get_table_schema(&params).await?)
55    }
56}
57
58impl SqliteHandler {
59    /// Returns column definitions with foreign key relationships.
60    ///
61    /// # Errors
62    ///
63    /// Returns [`AppError`] if validation fails or the query errors.
64    pub async fn get_table_schema(&self, request: &GetTableSchemaRequest) -> Result<TableSchemaResponse, AppError> {
65        let table = &request.table_name;
66        validate_identifier(table)?;
67
68        // 1. Get basic schema
69        let pragma_sql = format!("PRAGMA table_info({})", Self::quote_identifier(table));
70        let rows: Vec<SqliteRow> = execute_with_timeout(
71            self.config.query_timeout,
72            &pragma_sql,
73            sqlx::query(&pragma_sql).fetch_all(&self.pool),
74        )
75        .await?;
76
77        if rows.is_empty() {
78            return Err(AppError::TableNotFound(table.clone()));
79        }
80
81        let mut columns: HashMap<String, Value> = HashMap::new();
82        for row in &rows {
83            let col_name: String = row.try_get("name").unwrap_or_default();
84            let col_type: String = row.try_get("type").unwrap_or_default();
85            let notnull: i32 = row.try_get("notnull").unwrap_or(0);
86            let default: Option<String> = row.try_get("dflt_value").ok();
87            let pk: i32 = row.try_get("pk").unwrap_or(0);
88            columns.insert(
89                col_name,
90                json!({
91                    "type": col_type,
92                    "nullable": notnull == 0,
93                    "key": if pk > 0 { "PRI" } else { "" },
94                    "default": default,
95                    "extra": Value::Null,
96                    "foreign_key": Value::Null,
97                }),
98            );
99        }
100
101        // 2. Get FK info via PRAGMA
102        let fk_pragma_sql = format!("PRAGMA foreign_key_list({})", Self::quote_identifier(table));
103        let fk_rows: Vec<SqliteRow> = execute_with_timeout(
104            self.config.query_timeout,
105            &fk_pragma_sql,
106            sqlx::query(&fk_pragma_sql).fetch_all(&self.pool),
107        )
108        .await?;
109
110        for fk_row in &fk_rows {
111            let from_col: String = fk_row.try_get("from").unwrap_or_default();
112            if let Some(col_info) = columns.get_mut(&from_col)
113                && let Some(obj) = col_info.as_object_mut()
114            {
115                let ref_table: String = fk_row.try_get("table").unwrap_or_default();
116                let ref_col: String = fk_row.try_get("to").unwrap_or_default();
117                let on_update: String = fk_row.try_get("on_update").unwrap_or_default();
118                let on_delete: String = fk_row.try_get("on_delete").unwrap_or_default();
119                obj.insert(
120                    "foreign_key".to_string(),
121                    json!({
122                        "constraint_name": Value::Null,
123                        "referenced_table": ref_table,
124                        "referenced_column": ref_col,
125                        "on_update": on_update,
126                        "on_delete": on_delete,
127                    }),
128                );
129            }
130        }
131
132        Ok(TableSchemaResponse {
133            table_name: table.clone(),
134            columns: json!(columns),
135        })
136    }
137}