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::Connection as _;
9use database_mcp_sql::identifier::validate_identifier;
10use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
11use rmcp::model::{ErrorData, ToolAnnotations};
12use serde_json::{Value, json};
13
14use crate::SqliteHandler;
15use crate::types::GetTableSchemaRequest;
16
17/// Marker type for the `get_table_schema` MCP tool.
18pub(crate) struct GetTableSchemaTool;
19
20impl GetTableSchemaTool {
21    const NAME: &'static str = "get_table_schema";
22    const DESCRIPTION: &'static str = r#"Get column definitions and foreign key relationships for a table. Requires `table_name` — call `list_tables` first.
23
24<usecase>
25ALWAYS call this before writing queries to understand:
26- Column names and data types
27- Which columns are nullable, primary keys, or have defaults
28- Foreign key relationships for writing JOINs
29</usecase>
30
31<examples>
32✓ "What columns does the orders table have?" → get_table_schema(table_name="orders")
33✓ Before writing a SELECT → get_table_schema first to confirm column names
34✓ "How are users and orders related?" → check foreign keys in both tables
35</examples>
36
37<what_it_returns>
38A JSON object with table_name and columns keyed by column name, each containing type, nullable, key, default, and foreign_key info.
39</what_it_returns>"#;
40}
41
42impl ToolBase for GetTableSchemaTool {
43    type Parameter = GetTableSchemaRequest;
44    type Output = TableSchemaResponse;
45    type Error = ErrorData;
46
47    fn name() -> Cow<'static, str> {
48        Self::NAME.into()
49    }
50
51    fn description() -> Option<Cow<'static, str>> {
52        Some(Self::DESCRIPTION.into())
53    }
54
55    fn annotations() -> Option<ToolAnnotations> {
56        Some(
57            ToolAnnotations::new()
58                .read_only(true)
59                .destructive(false)
60                .idempotent(true)
61                .open_world(false),
62        )
63    }
64}
65
66impl AsyncTool<SqliteHandler> for GetTableSchemaTool {
67    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
68        Ok(handler.get_table_schema(&params).await?)
69    }
70}
71
72impl SqliteHandler {
73    /// Returns column definitions with foreign key relationships.
74    ///
75    /// # Errors
76    ///
77    /// Returns [`AppError`] if validation fails or the query errors.
78    pub async fn get_table_schema(&self, request: &GetTableSchemaRequest) -> Result<TableSchemaResponse, AppError> {
79        let table = &request.table_name;
80        validate_identifier(table)?;
81
82        // 1. Get basic schema
83        let pragma_sql = format!("PRAGMA table_info({})", self.connection.quote_identifier(table));
84        let rows = self.connection.fetch(pragma_sql.as_str(), None).await?;
85
86        if rows.is_empty() {
87            return Err(AppError::TableNotFound(table.clone()));
88        }
89
90        let mut columns: HashMap<String, Value> = HashMap::new();
91        for row in &rows {
92            let col_name = row.get("name").and_then(Value::as_str).unwrap_or_default().to_owned();
93            let col_type = row.get("type").and_then(Value::as_str).unwrap_or_default().to_owned();
94            let notnull = row.get("notnull").and_then(Value::as_i64).unwrap_or(0);
95            let default = row.get("dflt_value").and_then(Value::as_str).map(str::to_owned);
96            let pk = row.get("pk").and_then(Value::as_i64).unwrap_or(0);
97            columns.insert(
98                col_name,
99                json!({
100                    "type": col_type,
101                    "nullable": notnull == 0,
102                    "key": if pk > 0 { "PRI" } else { "" },
103                    "default": default,
104                    "extra": Value::Null,
105                    "foreign_key": Value::Null,
106                }),
107            );
108        }
109
110        // 2. Get FK info via PRAGMA
111        let fk_pragma_sql = format!("PRAGMA foreign_key_list({})", self.connection.quote_identifier(table));
112        let fk_rows = self.connection.fetch(fk_pragma_sql.as_str(), None).await?;
113
114        for fk_row in &fk_rows {
115            let from_col = fk_row
116                .get("from")
117                .and_then(Value::as_str)
118                .unwrap_or_default()
119                .to_owned();
120            if let Some(col_info) = columns.get_mut(&from_col)
121                && let Some(obj) = col_info.as_object_mut()
122            {
123                let ref_table = fk_row
124                    .get("table")
125                    .and_then(Value::as_str)
126                    .unwrap_or_default()
127                    .to_owned();
128                let ref_col = fk_row.get("to").and_then(Value::as_str).unwrap_or_default().to_owned();
129                let on_update = fk_row
130                    .get("on_update")
131                    .and_then(Value::as_str)
132                    .unwrap_or_default()
133                    .to_owned();
134                let on_delete = fk_row
135                    .get("on_delete")
136                    .and_then(Value::as_str)
137                    .unwrap_or_default()
138                    .to_owned();
139                obj.insert(
140                    "foreign_key".to_string(),
141                    json!({
142                        "constraint_name": Value::Null,
143                        "referenced_table": ref_table,
144                        "referenced_column": ref_col,
145                        "on_update": on_update,
146                        "on_delete": on_delete,
147                    }),
148                );
149            }
150        }
151
152        Ok(TableSchemaResponse {
153            table_name: table.clone(),
154            columns: json!(columns),
155        })
156    }
157}