Skip to main content

postgres_mcp/
resources.rs

1//! MCP resources and completions: a summary per database, and the schema and table views the tools return.
2
3use std::collections::HashMap;
4use std::time::Instant;
5
6use rmcp::ErrorData as McpError;
7use rmcp::model::{
8    CompleteRequestParams, CompleteResult, CompletionInfo, ListResourceTemplatesResult,
9    ListResourcesResult, ReadResourceResult, Reference, Resource, ResourceContents,
10    ResourceTemplate,
11};
12use serde_json::{Map, Value, json};
13use tokio_util::sync::CancellationToken;
14
15use crate::audit;
16use crate::scrub;
17use crate::server::AppState;
18use crate::tools::core::{self, DatabaseArgs};
19use crate::tools::schema::NON_SYSTEM;
20use crate::tools::schema::describe::{self, DescribeTableArgs};
21use crate::tools::schema::listing::{self, ListObjectsArgs, ListSchemasArgs};
22use crate::tools::text;
23use crate::tools::{Call, Runner, ToolError};
24
25const SCHEME: &str = "postgres://";
26const JSON_MIME: &str = "application/json";
27const SCHEMA_TEMPLATE: &str = "postgres://{database}/{schema}";
28const TABLE_TEMPLATE: &str = "postgres://{database}/{schema}/{table}";
29
30/// Tables, views, materialized views, foreign tables and partitioned tables of one schema, by name.
31const TABLE_COMPLETION_SQL: &str = "SELECT c.relname::text AS name, pg_catalog.count(*) OVER () AS total \
32    FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
33    WHERE n.nspname::text = $1::text AND c.relkind::text IN ('r', 'p', 'v', 'm', 'f') \
34    AND (pg_catalog.pg_has_role(current_user, 'pg_read_all_data', 'MEMBER') \
35         OR pg_catalog.has_schema_privilege(n.oid, 'USAGE')) \
36    AND pg_catalog.starts_with(pg_catalog.lower(c.relname::text), pg_catalog.lower($2::text)) \
37    ORDER BY c.relname::text COLLATE \"C\" LIMIT 100";
38
39/// The database resource's list entry, one per configured database in configuration order.
40pub fn list(state: &AppState) -> ListResourcesResult {
41    let resources = state
42        .config
43        .databases
44        .iter()
45        .map(|db| {
46            Resource::new(format!("{SCHEME}{}", db.name), db.name.clone())
47                .with_title(format!("{} {}", text::RESOURCE_DATABASE_TITLE, db.name))
48                .with_mime_type(JSON_MIME)
49                .with_description(text::RESOURCE_DATABASE_DESCRIPTION)
50        })
51        .collect();
52    ListResourcesResult::with_all_items(resources)
53}
54
55/// The two resource templates: one schema, and one table or view of a schema.
56pub fn templates() -> ListResourceTemplatesResult {
57    ListResourceTemplatesResult::with_all_items(vec![
58        ResourceTemplate::new(SCHEMA_TEMPLATE, "schema")
59            .with_title(text::RESOURCE_SCHEMA_TITLE)
60            .with_mime_type(JSON_MIME)
61            .with_description(text::RESOURCE_SCHEMA_DESCRIPTION),
62        ResourceTemplate::new(TABLE_TEMPLATE, "table")
63            .with_title(text::RESOURCE_TABLE_TITLE)
64            .with_mime_type(JSON_MIME)
65            .with_description(text::RESOURCE_TABLE_DESCRIPTION),
66    ])
67}
68
69/// The parts of a resource URI, with each name percent-decoded.
70#[derive(Debug, PartialEq)]
71enum Target {
72    Database(String),
73    Schema {
74        database: String,
75        schema: String,
76    },
77    Table {
78        database: String,
79        schema: String,
80        table: String,
81    },
82}
83
84/// Splits a postgres:// URI on its raw slashes, then decodes each name; None for any other shape.
85fn parse(uri: &str) -> Option<Target> {
86    let path = uri.strip_prefix(SCHEME)?;
87    if path.contains(['?', '#']) {
88        return None;
89    }
90    let parts = path
91        .split('/')
92        .map(decode)
93        .collect::<Option<Vec<String>>>()?;
94    if parts.iter().any(String::is_empty) {
95        return None;
96    }
97    match parts.as_slice() {
98        [database] => Some(Target::Database(database.clone())),
99        [database, schema] => Some(Target::Schema {
100            database: database.clone(),
101            schema: schema.clone(),
102        }),
103        [database, schema, table] => Some(Target::Table {
104            database: database.clone(),
105            schema: schema.clone(),
106            table: table.clone(),
107        }),
108        _ => None,
109    }
110}
111
112/// Percent-decodes one URI segment; None for a malformed escape, a NUL byte, or bytes that are not UTF-8.
113fn decode(segment: &str) -> Option<String> {
114    let mut out = Vec::with_capacity(segment.len());
115    let mut bytes = segment.bytes();
116    while let Some(byte) = bytes.next() {
117        if byte != b'%' {
118            out.push(byte);
119            continue;
120        }
121        let high = (bytes.next()? as char).to_digit(16)?;
122        let low = (bytes.next()? as char).to_digit(16)?;
123        out.push(u8::try_from(high * 16 + low).ok()?);
124    }
125    if out.contains(&0) {
126        return None;
127    }
128    String::from_utf8(out).ok()
129}
130
131/// Reads one resource. Each read writes one audit line; an unknown URI shape writes none, as an unknown tool does not.
132pub async fn read(
133    state: &AppState,
134    uri: &str,
135    ct: &CancellationToken,
136) -> Result<ReadResourceResult, McpError> {
137    let Some(target) = parse(uri) else {
138        return Err(McpError::resource_not_found(
139            text::UNKNOWN_RESOURCE_URI,
140            None,
141        ));
142    };
143    let started = Instant::now();
144    let (tool, requested, outcome) = match target {
145        Target::Database(database) => {
146            let outcome = summary(state, &database, ct).await;
147            ("resource:database", database, outcome)
148        }
149        Target::Schema { database, schema } => {
150            let outcome = schema_listing(state, &database, &schema, ct).await;
151            ("resource:schema", database, outcome)
152        }
153        Target::Table {
154            database,
155            schema,
156            table,
157        } => {
158            let outcome = table_definition(state, &database, &schema, &table, ct).await;
159            ("resource:table", database, outcome)
160        }
161    };
162    let ok = outcome.is_ok();
163    let sqlstate = outcome
164        .as_ref()
165        .err()
166        .and_then(ToolError::sqlstate)
167        .map(str::to_owned);
168    // The final pass runs on the value before it is serialized. The count is the markers in the body.
169    let outcome = match outcome {
170        Ok((name, mut value)) => {
171            crate::tools::mask::scrub_and_mask(&mut value, &[], &[]);
172            scrub::set_total(scrub::count_markers(&value));
173            Ok((name, value))
174        }
175        Err(error) => Err(read_error(error)),
176    };
177    let redacted_hashes = scrub::total();
178    let database = match &outcome {
179        Ok((name, _)) => Some(name.clone()),
180        Err(_) => state.resolve_name(Some(&requested)),
181    };
182    audit::record(
183        state.config.audit_log,
184        &audit::Record {
185            tool,
186            database: database.as_deref(),
187            ok,
188            duration: started.elapsed(),
189            rows: None,
190            sqlstate: sqlstate.as_deref(),
191            sql: None,
192            redacted_hashes,
193        },
194    );
195    if redacted_hashes > 0 {
196        tracing::warn!(
197            tool,
198            database = database.as_deref(),
199            count = redacted_hashes,
200            "redaction markers are present in a result"
201        );
202    }
203    match outcome {
204        Ok((_, value)) => {
205            let json = value.to_string();
206            let (text, found) = scrub::scrub_counting(&json);
207            if found > 0 {
208                tracing::warn!(
209                    tool,
210                    count = found,
211                    "output guard replaced text after the main pass"
212                );
213            }
214            let text = text.into_owned();
215            Ok(ReadResourceResult::new(vec![
216                ResourceContents::text(text, scrub::scrub(uri).into_owned())
217                    .with_mime_type(JSON_MIME),
218            ]))
219        }
220        Err(error) => Err(error),
221    }
222}
223
224/// Unknown names are resource-not-found with the tool's text; any other failure is an internal error with its short text.
225fn read_error(error: ToolError) -> McpError {
226    let (text, not_found) = match error {
227        ToolError::Config(message) | ToolError::Rejected(message) => (message, true),
228        other => (other.message(), false),
229    };
230    let (scrubbed, found) = scrub::scrub_counting(&text);
231    scrub::record(found);
232    if not_found {
233        McpError::resource_not_found(scrubbed.into_owned(), None)
234    } else {
235        McpError::internal_error(scrubbed.into_owned(), None)
236    }
237}
238
239/// The database summary: version and TimescaleDB from server_info, schemas from list_schemas, extensions with their schema.
240async fn summary(
241    state: &AppState,
242    database: &str,
243    ct: &CancellationToken,
244) -> Result<(String, Value), ToolError> {
245    let info = core::server_info(
246        state,
247        DatabaseArgs {
248            database: Some(database.to_owned()),
249        },
250        ct,
251    )
252    .await
253    .result?;
254    let schemas = listing::list_schemas(
255        state,
256        ListSchemasArgs {
257            database: Some(database.to_owned()),
258            include_system: false,
259        },
260        ct,
261    )
262    .await
263    .result?;
264    let rows = Runner::new(state)
265        .internal_query(Some(database), core::EXTENSIONS_SQL, &[], ct)
266        .await?
267        .rows;
268    let extensions: Vec<Value> = rows
269        .iter()
270        .map(|row| {
271            json!({
272                "name": row.get("name"),
273                "version": row.get("version"),
274                "schema": row.get("schema"),
275            })
276        })
277        .collect();
278    let value = json!({
279        "database": database,
280        "serverVersion": info["version"]["full"],
281        "serverVersionNum": info["version"]["number"],
282        "timescaledb": info["timescaledb"],
283        "schemas": schemas["schemas"],
284        "extensions": extensions,
285    });
286    Ok((database.to_owned(), value))
287}
288
289/// The list_objects tool's first page for one schema.
290async fn schema_listing(
291    state: &AppState,
292    database: &str,
293    schema: &str,
294    ct: &CancellationToken,
295) -> Result<(String, Value), ToolError> {
296    let args = ListObjectsArgs {
297        database: Some(database.to_owned()),
298        schema: Some(schema.to_owned()),
299        kinds: None,
300        name_like: None,
301        limit: None,
302        cursor: None,
303    };
304    let call: Call = listing::list_objects(state, args, ct).await;
305    Ok((
306        call.database.unwrap_or_else(|| database.to_owned()),
307        call.result?,
308    ))
309}
310
311/// The describe_table tool's result for one table or view.
312async fn table_definition(
313    state: &AppState,
314    database: &str,
315    schema: &str,
316    table: &str,
317    ct: &CancellationToken,
318) -> Result<(String, Value), ToolError> {
319    let args = DescribeTableArgs {
320        database: Some(database.to_owned()),
321        table: table.to_owned(),
322        schema: Some(schema.to_owned()),
323    };
324    let call: Call = describe::describe_table(state, args, ct).await;
325    Ok((
326        call.database.unwrap_or_else(|| database.to_owned()),
327        call.result?,
328    ))
329}
330
331/// Completions for the database, schema and table arguments of the two templates. Any other request,
332/// and any database error, is an empty completion.
333pub async fn complete(
334    state: &AppState,
335    request: CompleteRequestParams,
336    ct: &CancellationToken,
337) -> CompleteResult {
338    let Reference::Resource(reference) = &request.r#ref else {
339        return completion(Vec::new(), 0);
340    };
341    let template = reference.uri.as_str();
342    if template != SCHEMA_TEMPLATE && template != TABLE_TEMPLATE {
343        return completion(Vec::new(), 0);
344    }
345    let prefix = request.argument.value.as_str();
346    let arguments = request
347        .context
348        .as_ref()
349        .and_then(|context| context.arguments.as_ref());
350    let values = match request.argument.name.as_str() {
351        "database" => Some(database_values(state, prefix)),
352        "schema" => schema_values(state, arguments, prefix, ct).await,
353        "table" if template == TABLE_TEMPLATE => table_values(state, arguments, prefix, ct).await,
354        _ => None,
355    };
356    match values {
357        Some((names, total)) => completion(names, total),
358        None => completion(Vec::new(), 0),
359    }
360}
361
362/// A completion of at most the protocol's value limit; `total` is the full number of matches.
363fn completion(values: Vec<String>, total: usize) -> CompleteResult {
364    let cut = total > values.len();
365    let info = if cut {
366        CompletionInfo::with_pagination(values, u32::try_from(total).ok(), true)
367    } else {
368        CompletionInfo::new(values)
369    };
370    CompleteResult::new(info.unwrap_or_default())
371}
372
373/// Configured database names starting with the prefix, case-insensitively, in name order.
374fn database_values(state: &AppState, prefix: &str) -> (Vec<String>, usize) {
375    let wanted = prefix.to_lowercase();
376    let mut names: Vec<String> = state
377        .config
378        .databases
379        .iter()
380        .map(|db| db.name.clone())
381        .filter(|name| name.to_lowercase().starts_with(&wanted))
382        .collect();
383    names.sort();
384    let total = names.len();
385    names.truncate(CompletionInfo::MAX_VALUES);
386    (names, total)
387}
388
389/// The database a schema or table completion reads: the context argument, or the only configured database.
390fn completion_database(
391    state: &AppState,
392    arguments: Option<&HashMap<String, String>>,
393) -> Option<String> {
394    match arguments.and_then(|args| args.get("database")) {
395        Some(name) => Some(name.clone()),
396        None => match state.config.databases.as_slice() {
397            [only] => Some(only.name.clone()),
398            _ => None,
399        },
400    }
401}
402
403/// Schemas starting with the prefix. System schemas are listed only when the prefix starts with pg_ or information_schema.
404async fn schema_values(
405    state: &AppState,
406    arguments: Option<&HashMap<String, String>>,
407    prefix: &str,
408    ct: &CancellationToken,
409) -> Option<(Vec<String>, usize)> {
410    let database = completion_database(state, arguments)?;
411    let lowered = prefix.to_lowercase();
412    let include_system = lowered.starts_with("pg_") || lowered.starts_with("information_schema");
413    let include_system = if include_system { "true" } else { "false" };
414    let rows = Runner::new(state)
415        .internal_query(
416            Some(database.as_str()),
417            &schema_completion_sql(),
418            &[Some(prefix), Some(include_system)],
419            ct,
420        )
421        .await
422        .ok()?
423        .rows;
424    Some(names_and_total(rows))
425}
426
427/// Tables and views of the context schema starting with the prefix; no schema in the context is an empty completion.
428async fn table_values(
429    state: &AppState,
430    arguments: Option<&HashMap<String, String>>,
431    prefix: &str,
432    ct: &CancellationToken,
433) -> Option<(Vec<String>, usize)> {
434    let database = completion_database(state, arguments)?;
435    let schema = arguments.and_then(|args| args.get("schema"))?;
436    let rows = Runner::new(state)
437        .internal_query(
438            Some(database.as_str()),
439            TABLE_COMPLETION_SQL,
440            &[Some(schema.as_str()), Some(prefix)],
441            ct,
442        )
443        .await
444        .ok()?
445        .rows;
446    Some(names_and_total(rows))
447}
448
449/// Schemas the role may see, as list_schemas shows them, starting with $1 case-insensitively; $2 includes system schemas.
450fn schema_completion_sql() -> String {
451    format!(
452        "SELECT n.nspname::text AS name, pg_catalog.count(*) OVER () AS total \
453        FROM pg_catalog.pg_namespace n \
454        WHERE pg_catalog.starts_with(pg_catalog.lower(n.nspname::text), pg_catalog.lower($1::text)) \
455        AND ($2::boolean OR {NON_SYSTEM}) \
456        AND (pg_catalog.pg_has_role(current_user, 'pg_read_all_data', 'MEMBER') \
457             OR pg_catalog.has_schema_privilege(n.oid, 'USAGE')) \
458        ORDER BY n.nspname::text COLLATE \"C\" LIMIT 100"
459    )
460}
461
462/// The names of the returned rows, and the total match count that the first row's window column reports.
463fn names_and_total(rows: Vec<Map<String, Value>>) -> (Vec<String>, usize) {
464    let total = rows
465        .first()
466        .and_then(|row| count_of(row.get("total")))
467        .unwrap_or(0);
468    let names = rows
469        .iter()
470        .filter_map(|row| row.get("name").and_then(Value::as_str).map(str::to_owned))
471        .collect();
472    (names, total)
473}
474
475/// A count as the envelope encodes it: a JSON number, or a string for values past 2^53-1.
476fn count_of(value: Option<&Value>) -> Option<usize> {
477    let number = match value? {
478        Value::Number(n) => n.as_u64()?,
479        Value::String(s) => s.parse::<u64>().ok()?,
480        _ => return None,
481    };
482    usize::try_from(number).ok()
483}
484
485#[cfg(test)]
486mod tests {
487    use super::{Target, decode, parse};
488
489    #[test]
490    fn slashes_split_before_decoding() {
491        assert_eq!(
492            parse("postgres://appdb/shop/a%2Fb"),
493            Some(Target::Table {
494                database: "appdb".into(),
495                schema: "shop".into(),
496                table: "a/b".into(),
497            })
498        );
499    }
500
501    #[test]
502    fn malformed_uris_have_no_target() {
503        for uri in [
504            "postgres://",
505            "postgres://appdb/",
506            "postgres:///shop",
507            "postgres://appdb/a/b/c/d",
508            "postgres://appdb/shop?x=1",
509            "postgres://appdb/shop#frag",
510            "postgres://appdb/%zz",
511            "postgres://appdb/%+1",
512            "postgres://appdb/%ff",
513            "http://appdb",
514        ] {
515            assert_eq!(parse(uri), None, "{uri}");
516        }
517    }
518
519    #[test]
520    fn escapes_decode_to_bytes() {
521        assert_eq!(decode("Odd%2EName").as_deref(), Some("Odd.Name"));
522        assert_eq!(decode("a%20b").as_deref(), Some("a b"));
523        assert_eq!(decode("%C3%A9").as_deref(), Some("é"));
524        assert_eq!(decode("plain+sign").as_deref(), Some("plain+sign"));
525    }
526}