Skip to main content

postgres_mcp/tools/
schema.rs

1//! Schema introspection: list_schemas, list_objects, describe_table, describe_function, search_schema and get_privileges.
2
3pub(crate) mod describe;
4pub(crate) mod listing;
5mod privileges;
6mod search;
7
8use std::future::Future;
9
10use rmcp::ErrorData as McpError;
11use rmcp::model::Tool;
12use serde::Serialize;
13use serde_json::{Map, Value};
14use tokio_util::sync::CancellationToken;
15
16use super::core::tool;
17use super::envelope;
18use super::{
19    Call, INTERNAL_MAX_ROWS, Runner, Statement, ToolError, Toolset, parse_args, text, value_of,
20};
21use crate::config::Limits;
22use crate::pg::wire::FetchLimits;
23use crate::server::AppState;
24
25const MIB: usize = 1_048_576;
26const DEFAULT_LIMIT: i64 = 100;
27const MAX_LIMIT: i64 = 500;
28
29/// Predicate on n.nspname: false for catalogs, TimescaleDB internals and temporary schemas.
30pub(crate) const NON_SYSTEM: &str = "NOT (n.nspname IN ('pg_catalog', 'information_schema', 'pg_toast', \
31    'timescaledb_information', 'timescaledb_experimental', 'toolkit_experimental') \
32    OR n.nspname::text ~ '^(pg_temp_|pg_toast_temp_|_timescaledb_)')";
33
34/// A column's type as format_type renders it, minus the `public.` prefix that the role's search_path
35/// used to hide. Needs the pg_attribute alias `a`.
36const COLUMN_TYPE_SQL: &str = "CASE WHEN pg_catalog.left(pg_catalog.format_type(a.atttypid, a.atttypmod), 7) = 'public.' \
37    THEN pg_catalog.substr(pg_catalog.format_type(a.atttypid, a.atttypmod), 8) \
38    ELSE pg_catalog.format_type(a.atttypid, a.atttypmod) END";
39
40const INCLUDE_SYSTEM_PARAM: &str =
41    "Also list system schemas such as pg_catalog and information_schema. Default false.";
42const KINDS_PARAM: &str = "Kinds to include: table, partitioned_table, view, materialized_view, foreign_table, sequence, function, procedure, type. Default: all except function, procedure and type.";
43const NAME_LIKE_PARAM: &str = "Case-insensitive substring the object name must contain.";
44const TABLE_PARAM: &str = "Table, view or materialized view name; either bare (then give schema, or it is searched in every non-system schema) or as schema.name.";
45const TABLE_SCHEMA_PARAM: &str =
46    "Schema of the table. Optional when the name is unique or schema-qualified.";
47const FUNCTION_PARAM: &str = "Function or procedure name, bare or as schema.name.";
48const FUNCTION_SCHEMA_PARAM: &str = "Schema of the function. Optional.";
49const QUERY_PARAM: &str = "Text to look for in names and comments, at least 2 characters. Case-insensitive substring; no wildcards.";
50const SEARCH_KINDS_PARAM: &str = "Limit to: table, view, column, function. Default: all.";
51
52/// The six schema tools with their toolset tag.
53pub fn catalog() -> Vec<(Toolset, Tool)> {
54    vec![
55        (
56            Toolset::Schema,
57            tool::<listing::ListSchemasArgs, listing::ListSchemasResult>(
58                "list_schemas",
59                text::LIST_SCHEMAS_TITLE,
60                text::LIST_SCHEMAS,
61                &[
62                    ("database", text::DATABASE_PARAM),
63                    ("include_system", INCLUDE_SYSTEM_PARAM),
64                ],
65            ),
66        ),
67        (
68            Toolset::Schema,
69            tool::<listing::ListObjectsArgs, listing::ListObjectsResult>(
70                "list_objects",
71                text::LIST_OBJECTS_TITLE,
72                text::LIST_OBJECTS,
73                &[
74                    ("database", text::DATABASE_PARAM),
75                    ("schema", text::SCHEMA_PARAM),
76                    ("kinds", KINDS_PARAM),
77                    ("name_like", NAME_LIKE_PARAM),
78                    ("limit", text::LIMIT_PARAM),
79                    ("cursor", text::CURSOR_PARAM),
80                ],
81            ),
82        ),
83        (
84            Toolset::Schema,
85            tool::<describe::DescribeTableArgs, describe::DescribeTableResult>(
86                "describe_table",
87                text::DESCRIBE_TABLE_TITLE,
88                text::DESCRIBE_TABLE,
89                &[
90                    ("database", text::DATABASE_PARAM),
91                    ("table", TABLE_PARAM),
92                    ("schema", TABLE_SCHEMA_PARAM),
93                ],
94            ),
95        ),
96        (
97            Toolset::Schema,
98            tool::<describe::DescribeFunctionArgs, describe::DescribeFunctionResult>(
99                "describe_function",
100                text::DESCRIBE_FUNCTION_TITLE,
101                text::DESCRIBE_FUNCTION,
102                &[
103                    ("database", text::DATABASE_PARAM),
104                    ("function", FUNCTION_PARAM),
105                    ("schema", FUNCTION_SCHEMA_PARAM),
106                ],
107            ),
108        ),
109        (
110            Toolset::Schema,
111            tool::<search::SearchSchemaArgs, search::SearchSchemaResult>(
112                "search_schema",
113                text::SEARCH_SCHEMA_TITLE,
114                text::SEARCH_SCHEMA,
115                &[
116                    ("database", text::DATABASE_PARAM),
117                    ("query", QUERY_PARAM),
118                    ("schema", text::SCHEMA_PARAM),
119                    ("kinds", SEARCH_KINDS_PARAM),
120                    ("limit", text::LIMIT_PARAM),
121                    ("cursor", text::CURSOR_PARAM),
122                ],
123            ),
124        ),
125        (
126            Toolset::Schema,
127            tool::<privileges::GetPrivilegesArgs, privileges::GetPrivilegesResult>(
128                "get_privileges",
129                text::GET_PRIVILEGES_TITLE,
130                text::GET_PRIVILEGES,
131                &[("database", text::DATABASE_PARAM)],
132            ),
133        ),
134    ]
135}
136
137/// Runs the named tool, or returns None when the name is not one of this module's tools.
138pub async fn dispatch(
139    state: &AppState,
140    name: &str,
141    args: Value,
142    ct: &CancellationToken,
143) -> Option<Result<Call, McpError>> {
144    match name {
145        "list_schemas" => {
146            run(parse_args::<listing::ListSchemasArgs>(args), |a| {
147                listing::list_schemas(state, a, ct)
148            })
149            .await
150        }
151        "list_objects" => {
152            run(parse_args::<listing::ListObjectsArgs>(args), |a| {
153                listing::list_objects(state, a, ct)
154            })
155            .await
156        }
157        "describe_table" => {
158            run(parse_args::<describe::DescribeTableArgs>(args), |a| {
159                describe::describe_table(state, a, ct)
160            })
161            .await
162        }
163        "describe_function" => {
164            run(parse_args::<describe::DescribeFunctionArgs>(args), |a| {
165                describe::describe_function(state, a, ct)
166            })
167            .await
168        }
169        "search_schema" => {
170            run(parse_args::<search::SearchSchemaArgs>(args), |a| {
171                search::search_schema(state, a, ct)
172            })
173            .await
174        }
175        "get_privileges" => {
176            run(parse_args::<privileges::GetPrivilegesArgs>(args), |a| {
177                privileges::get_privileges(state, a, ct)
178            })
179            .await
180        }
181        _ => None,
182    }
183}
184
185/// Runs one tool once its arguments parsed; bad arguments are a protocol error.
186async fn run<A, F, Fut>(parsed: Result<A, McpError>, call: F) -> Option<Result<Call, McpError>>
187where
188    F: FnOnce(A) -> Fut,
189    Fut: Future<Output = Call>,
190{
191    match parsed {
192        Ok(args) => Some(Ok(call(args).await)),
193        Err(error) => Some(Err(error)),
194    }
195}
196
197/// The client-facing call: the value with the database it ran on, or the error with the requested name.
198fn finish<T: Serialize>(
199    state: &AppState,
200    requested: Option<&str>,
201    outcome: Result<(String, T), ToolError>,
202) -> Call {
203    match outcome {
204        Ok((database, value)) => Call {
205            result: value_of(&value),
206            database: Some(database),
207            rows: None,
208            sql: None,
209        },
210        Err(error) => Call {
211            result: Err(error),
212            database: state.resolve_name(requested),
213            rows: None,
214            sql: None,
215        },
216    }
217}
218
219/// Runs one internal query with the large value limits. A cut row set or value is an error, never a partial result.
220async fn run_rows(
221    state: &AppState,
222    database: Option<&str>,
223    sql: &str,
224    params: &[Option<&str>],
225    ct: &CancellationToken,
226) -> Result<(String, Vec<Map<String, Value>>), ToolError> {
227    let statement = Statement {
228        sql,
229        params,
230        user_sql: false,
231        fetch: FetchLimits {
232            max_rows: INTERNAL_MAX_ROWS,
233            max_bytes: 8 * MIB,
234            max_value_bytes: MIB,
235        },
236        offset: Some(0),
237        search_path_catalog_only: true,
238    };
239    let (name, output) = Runner::new(state)
240        .internal_raw(database, statement, ct)
241        .await?;
242    let limits = Limits {
243        max_value_bytes: MIB,
244        ..state.config.limits.clone()
245    };
246    let envelope = envelope::build(&name, output, &limits, false);
247    if envelope.truncated || envelope.truncated_values > 0 {
248        return Err(ToolError::Internal(
249            "a catalog result is larger than the response limit".to_owned(),
250        ));
251    }
252    Ok((name, envelope.rows))
253}
254
255/// Runs one section query. On failure the section is None and its message goes under `<name>Error`.
256async fn section(
257    state: &AppState,
258    database: Option<&str>,
259    sql: &str,
260    params: &[Option<&str>],
261    ct: &CancellationToken,
262    errors: &mut Map<String, Value>,
263    name: &str,
264) -> Option<Value> {
265    match run_value(state, database, sql, params, ct).await {
266        Ok((_, value)) => Some(value),
267        Err(error) => {
268            errors.insert(format!("{name}Error"), Value::String(error.message()));
269            None
270        }
271    }
272}
273
274/// Runs a query whose first row holds one value in column `v`; null when it returns no row.
275async fn run_value(
276    state: &AppState,
277    database: Option<&str>,
278    sql: &str,
279    params: &[Option<&str>],
280    ct: &CancellationToken,
281) -> Result<(String, Value), ToolError> {
282    let (name, rows) = run_rows(state, database, sql, params, ct).await?;
283    let value = rows
284        .into_iter()
285        .next()
286        .and_then(|mut row| row.remove("v"))
287        .unwrap_or(Value::Null);
288    Ok((name, value))
289}
290
291/// The page size and the offset of the first row, from the paging arguments.
292fn page(limit: Option<i64>, cursor: Option<&str>) -> Result<(i64, i64), ToolError> {
293    let limit = match limit {
294        None => DEFAULT_LIMIT,
295        Some(n) if (1..=MAX_LIMIT).contains(&n) => n,
296        Some(_) => {
297            return Err(ToolError::Rejected(format!(
298                "limit must be between 1 and {MAX_LIMIT}."
299            )));
300        }
301    };
302    let offset = match cursor {
303        None => 0,
304        Some(raw) => parse_cursor(raw)?,
305    };
306    Ok((limit, offset))
307}
308
309/// Reads an opaque cursor of the form o:<offset>.
310fn parse_cursor(raw: &str) -> Result<i64, ToolError> {
311    let invalid = || ToolError::Rejected("Invalid cursor.".to_owned());
312    let digits = raw
313        .strip_prefix("o:")
314        .filter(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
315        .ok_or_else(invalid)?;
316    digits.parse::<i64>().map_err(|_| invalid())
317}
318
319/// The first `limit` rows, and the cursor of the next page when one more row exists.
320fn take_page<T>(mut rows: Vec<T>, limit: i64, offset: i64) -> (Vec<T>, Option<String>) {
321    let size = usize::try_from(limit).unwrap_or(usize::MAX);
322    if rows.len() > size {
323        rows.truncate(size);
324        (rows, Some(format!("o:{}", offset.saturating_add(limit))))
325    } else {
326        (rows, None)
327    }
328}
329
330/// Each requested kind must be one of `valid`; the error names them all.
331fn check_kinds(kinds: &[String], valid: &[&str]) -> Result<(), ToolError> {
332    for kind in kinds {
333        if !valid.contains(&kind.as_str()) {
334            return Err(ToolError::Rejected(format!(
335                "Unknown kind \"{kind}\". Valid kinds: {}.",
336                valid.join(", ")
337            )));
338        }
339    }
340    Ok(())
341}
342
343/// Escapes LIKE metacharacters so the text matches literally.
344fn like_escape(raw: &str) -> String {
345    let mut out = String::with_capacity(raw.len());
346    for ch in raw.chars() {
347        if matches!(ch, '\\' | '%' | '_') {
348            out.push('\\');
349        }
350        out.push(ch);
351    }
352    out
353}
354
355/// A case-insensitive substring pattern for ILIKE.
356fn contains_pattern(raw: &str) -> String {
357    format!("%{}%", like_escape(raw))
358}