database_mcp_postgres/tools/
get_table_schema.rs1use 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_literal, validate_ident};
10use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
11use rmcp::model::{ErrorData, ToolAnnotations};
12use serde_json::{Value, json};
13
14use crate::PostgresHandler;
15
16pub(crate) struct GetTableSchemaTool;
18
19impl GetTableSchemaTool {
20 const NAME: &'static str = "getTableSchema";
21 const TITLE: &'static str = "Get Table Schema";
22 const DESCRIPTION: &'static str = r#"Get column definitions and foreign key relationships for a table. Requires `database` and `table` — call `listDatabases` and `listTables` 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?" → getTableSchema(database="mydb", table="orders")
33✓ Before writing a SELECT → getTableSchema 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 and columns keyed by column name, each containing type, nullable, key, default, and foreignKey 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 title() -> Option<String> {
52 Some(Self::TITLE.into())
53 }
54
55 fn description() -> Option<Cow<'static, str>> {
56 Some(Self::DESCRIPTION.into())
57 }
58
59 fn annotations() -> Option<ToolAnnotations> {
60 Some(
61 ToolAnnotations::new()
62 .read_only(true)
63 .destructive(false)
64 .idempotent(true)
65 .open_world(false),
66 )
67 }
68}
69
70impl AsyncTool<PostgresHandler> for GetTableSchemaTool {
71 async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
72 Ok(handler.get_table_schema(params).await?)
73 }
74}
75
76impl PostgresHandler {
77 #[allow(clippy::too_many_lines)]
83 pub async fn get_table_schema(
84 &self,
85 GetTableSchemaRequest { database, table }: GetTableSchemaRequest,
86 ) -> Result<TableSchemaResponse, SqlError> {
87 validate_ident(&table)?;
88 let db = Some(database.trim()).filter(|s| !s.is_empty());
89 if let Some(name) = &db {
90 validate_ident(name)?;
91 }
92
93 let schema_sql = format!(
95 r"
96 SELECT column_name, data_type, is_nullable, column_default,
97 character_maximum_length
98 FROM information_schema.columns
99 WHERE table_schema = 'public' AND table_name = {}
100 ORDER BY ordinal_position",
101 quote_literal(&table),
102 );
103 let rows = self.connection.fetch_json(&schema_sql, db).await?;
104
105 if rows.is_empty() {
106 return Err(SqlError::TableNotFound(table));
107 }
108
109 let mut columns: HashMap<String, Value> = HashMap::new();
110 for row in &rows {
111 let col_name = row
112 .get("column_name")
113 .and_then(Value::as_str)
114 .unwrap_or_default()
115 .to_owned();
116 let data_type = row
117 .get("data_type")
118 .and_then(Value::as_str)
119 .unwrap_or_default()
120 .to_owned();
121 let nullable = row
122 .get("is_nullable")
123 .and_then(Value::as_str)
124 .unwrap_or_default()
125 .to_owned();
126 let default = row.get("column_default").and_then(Value::as_str).map(str::to_owned);
127 columns.insert(
128 col_name,
129 json!({
130 "type": data_type,
131 "nullable": nullable.to_uppercase() == "YES",
132 "key": Value::Null,
133 "default": default,
134 "extra": Value::Null,
135 "foreignKey": Value::Null,
136 }),
137 );
138 }
139
140 let fk_sql = format!(
142 r"
143 SELECT
144 kcu.column_name,
145 tc.constraint_name,
146 ccu.table_name AS referenced_table,
147 ccu.column_name AS referenced_column,
148 rc.update_rule AS on_update,
149 rc.delete_rule AS on_delete
150 FROM information_schema.table_constraints tc
151 JOIN information_schema.key_column_usage kcu
152 ON tc.constraint_name = kcu.constraint_name
153 AND tc.table_schema = kcu.table_schema
154 JOIN information_schema.constraint_column_usage ccu
155 ON ccu.constraint_name = tc.constraint_name
156 AND ccu.table_schema = tc.table_schema
157 JOIN information_schema.referential_constraints rc
158 ON rc.constraint_name = tc.constraint_name
159 AND rc.constraint_schema = tc.table_schema
160 WHERE tc.constraint_type = 'FOREIGN KEY'
161 AND tc.table_name = {}
162 AND tc.table_schema = 'public'",
163 quote_literal(&table),
164 );
165 let fk_rows = self.connection.fetch_json(&fk_sql, db).await?;
166
167 for fk_row in &fk_rows {
168 let col_name = fk_row
169 .get("column_name")
170 .and_then(Value::as_str)
171 .unwrap_or_default()
172 .to_owned();
173 if let Some(col_info) = columns.get_mut(&col_name)
174 && let Some(obj) = col_info.as_object_mut()
175 {
176 obj.insert(
177 "foreignKey".to_string(),
178 json!({
179 "constraintName": fk_row.get("constraint_name").and_then(Value::as_str),
180 "referencedTable": fk_row.get("referenced_table").and_then(Value::as_str),
181 "referencedColumn": fk_row.get("referenced_column").and_then(Value::as_str),
182 "onUpdate": fk_row.get("on_update").and_then(Value::as_str),
183 "onDelete": fk_row.get("on_delete").and_then(Value::as_str),
184 }),
185 );
186 }
187 }
188
189 Ok(TableSchemaResponse {
190 table,
191 columns: json!(columns),
192 })
193 }
194}