database_mcp_postgres/tools/
get_table_schema.rs1use std::borrow::Cow;
4use std::collections::HashMap;
5
6use database_mcp_server::AppError;
7use database_mcp_server::types::{GetTableSchemaRequest, 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::PostgresHandler;
15
16pub(crate) struct GetTableSchemaTool;
18
19impl GetTableSchemaTool {
20 const NAME: &'static str = "get_table_schema";
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_name` and `table_name` — call `list_databases` and `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(database_name="mydb", 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 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(¶ms).await?)
73 }
74}
75
76impl PostgresHandler {
77 pub async fn get_table_schema(&self, request: &GetTableSchemaRequest) -> Result<TableSchemaResponse, AppError> {
83 let table = &request.table_name;
84 validate_identifier(table)?;
85 let db = if request.database_name.is_empty() {
86 None
87 } else {
88 Some(request.database_name.as_str())
89 };
90
91 let schema_sql = format!(
93 "SELECT column_name, data_type, is_nullable, column_default, \
94 character_maximum_length \
95 FROM information_schema.columns \
96 WHERE table_schema = 'public' AND table_name = '{table}' \
97 ORDER BY ordinal_position"
98 );
99 let rows = self.connection.fetch(&schema_sql, db).await?;
100
101 if rows.is_empty() {
102 return Err(AppError::TableNotFound(table.clone()));
103 }
104
105 let mut columns: HashMap<String, Value> = HashMap::new();
106 for row in &rows {
107 let col_name = row
108 .get("column_name")
109 .and_then(Value::as_str)
110 .unwrap_or_default()
111 .to_owned();
112 let data_type = row
113 .get("data_type")
114 .and_then(Value::as_str)
115 .unwrap_or_default()
116 .to_owned();
117 let nullable = row
118 .get("is_nullable")
119 .and_then(Value::as_str)
120 .unwrap_or_default()
121 .to_owned();
122 let default = row.get("column_default").and_then(Value::as_str).map(str::to_owned);
123 columns.insert(
124 col_name,
125 json!({
126 "type": data_type,
127 "nullable": nullable.to_uppercase() == "YES",
128 "key": Value::Null,
129 "default": default,
130 "extra": Value::Null,
131 "foreign_key": Value::Null,
132 }),
133 );
134 }
135
136 let fk_sql = format!(
138 "SELECT \
139 kcu.column_name, \
140 tc.constraint_name, \
141 ccu.table_name AS referenced_table, \
142 ccu.column_name AS referenced_column, \
143 rc.update_rule AS on_update, \
144 rc.delete_rule AS on_delete \
145 FROM information_schema.table_constraints tc \
146 JOIN information_schema.key_column_usage kcu \
147 ON tc.constraint_name = kcu.constraint_name \
148 AND tc.table_schema = kcu.table_schema \
149 JOIN information_schema.constraint_column_usage ccu \
150 ON ccu.constraint_name = tc.constraint_name \
151 AND ccu.table_schema = tc.table_schema \
152 JOIN information_schema.referential_constraints rc \
153 ON rc.constraint_name = tc.constraint_name \
154 AND rc.constraint_schema = tc.table_schema \
155 WHERE tc.constraint_type = 'FOREIGN KEY' \
156 AND tc.table_name = '{table}' \
157 AND tc.table_schema = 'public'"
158 );
159 let fk_rows = self.connection.fetch(&fk_sql, db).await?;
160
161 for fk_row in &fk_rows {
162 let col_name = fk_row
163 .get("column_name")
164 .and_then(Value::as_str)
165 .unwrap_or_default()
166 .to_owned();
167 if let Some(col_info) = columns.get_mut(&col_name)
168 && let Some(obj) = col_info.as_object_mut()
169 {
170 obj.insert(
171 "foreign_key".to_string(),
172 json!({
173 "constraint_name": fk_row.get("constraint_name").and_then(Value::as_str),
174 "referenced_table": fk_row.get("referenced_table").and_then(Value::as_str),
175 "referenced_column": fk_row.get("referenced_column").and_then(Value::as_str),
176 "on_update": fk_row.get("on_update").and_then(Value::as_str),
177 "on_delete": fk_row.get("on_delete").and_then(Value::as_str),
178 }),
179 );
180 }
181 }
182
183 Ok(TableSchemaResponse {
184 table_name: table.clone(),
185 columns: json!(columns),
186 })
187 }
188}