Skip to main content

postgres_mcp/tools/monitor/
mod.rs

1//! Monitoring tools: sessions and locks, statement statistics, cumulative statistics, table usage and replication.
2
3mod activity;
4mod replication;
5mod statements;
6mod stats;
7mod tables;
8
9use rmcp::ErrorData as McpError;
10use rmcp::model::Tool;
11use serde_json::{Map, Value};
12use tokio_util::sync::CancellationToken;
13
14use super::core::{failed, tool};
15use super::envelope::{self, QueryEnvelope};
16use super::mask::mask;
17use super::{Call, INTERNAL_MAX_ROWS, Runner, Statement, ToolError, Toolset, parse_args, text};
18use crate::config::Limits;
19use crate::pg::wire::FetchLimits;
20use crate::server::AppState;
21
22/// Per-value and per-response byte limits for monitoring queries that return long text or jsonb.
23const WIDE_VALUE_BYTES: usize = 1_048_576;
24const WIDE_RESPONSE_BYTES: usize = 8 * 1_048_576;
25/// PostgreSQL's placeholder for another role's statement text.
26const HIDDEN_TEXT: &str = "<insufficient privilege>";
27const VISIBILITY_SQL: &str = "SELECT pg_catalog.current_user()::text AS role, \
28    pg_catalog.pg_has_role(pg_catalog.current_user(), 'pg_read_all_stats', 'USAGE') AS visible";
29
30/// Monitoring tools with their toolset tag.
31pub fn catalog() -> Vec<(Toolset, Tool)> {
32    vec![
33        (
34            Toolset::Monitor,
35            tool::<activity::ListActivityArgs, activity::ListActivityResult>(
36                "list_activity",
37                text::LIST_ACTIVITY_TITLE,
38                text::LIST_ACTIVITY,
39                &[
40                    ("database", text::DATABASE_PARAM),
41                    ("state", text::LIST_ACTIVITY_STATE_PARAM),
42                    ("min_duration_ms", text::LIST_ACTIVITY_MIN_DURATION_MS_PARAM),
43                    ("user", text::LIST_ACTIVITY_USER_PARAM),
44                    ("all_databases", text::LIST_ACTIVITY_ALL_DATABASES_PARAM),
45                    ("only_blocked", text::LIST_ACTIVITY_ONLY_BLOCKED_PARAM),
46                    (
47                        "include_background",
48                        text::LIST_ACTIVITY_INCLUDE_BACKGROUND_PARAM,
49                    ),
50                    ("query_chars", text::LIST_ACTIVITY_QUERY_CHARS_PARAM),
51                    ("limit", text::LIMIT_PARAM),
52                ],
53            ),
54        ),
55        (
56            Toolset::Monitor,
57            tool::<statements::QueryStatsArgs, statements::QueryStatsResult>(
58                "query_stats",
59                text::QUERY_STATS_TITLE,
60                text::QUERY_STATS,
61                &[
62                    ("database", text::DATABASE_PARAM),
63                    ("order_by", text::QUERY_STATS_ORDER_BY_PARAM),
64                    ("min_calls", text::QUERY_STATS_MIN_CALLS_PARAM),
65                    ("contains", text::QUERY_STATS_CONTAINS_PARAM),
66                    ("all_databases", text::QUERY_STATS_ALL_DATABASES_PARAM),
67                    ("query_chars", text::QUERY_STATS_QUERY_CHARS_PARAM),
68                    ("limit", text::QUERY_STATS_LIMIT_PARAM),
69                ],
70            ),
71        ),
72        (
73            Toolset::Monitor,
74            tool::<stats::DatabaseStatsArgs, stats::DatabaseStatsResult>(
75                "database_stats",
76                text::DATABASE_STATS_TITLE,
77                text::DATABASE_STATS,
78                &[
79                    ("database", text::DATABASE_PARAM),
80                    ("sections", text::DATABASE_STATS_SECTIONS_PARAM),
81                ],
82            ),
83        ),
84        (
85            Toolset::Monitor,
86            tool::<tables::TableStatsArgs, tables::TableStatsResult>(
87                "table_stats",
88                text::TABLE_STATS_TITLE,
89                text::TABLE_STATS,
90                &[
91                    ("database", text::DATABASE_PARAM),
92                    ("schema", text::SCHEMA_PARAM),
93                    ("table", text::TABLE_STATS_TABLE_PARAM),
94                    ("order_by", text::TABLE_STATS_ORDER_BY_PARAM),
95                    ("include_indexes", text::TABLE_STATS_INCLUDE_INDEXES_PARAM),
96                    ("unused_indexes", text::TABLE_STATS_UNUSED_INDEXES_PARAM),
97                    ("limit", text::LIMIT_PARAM),
98                    ("cursor", text::CURSOR_PARAM),
99                ],
100            ),
101        ),
102        (
103            Toolset::Monitor,
104            tool::<replication::ReplicationArgs, replication::ReplicationResult>(
105                "replication_status",
106                text::REPLICATION_STATUS_TITLE,
107                text::REPLICATION_STATUS,
108                &[("database", text::DATABASE_PARAM)],
109            ),
110        ),
111    ]
112}
113
114/// Runs the named tool, or returns None when the name is not one of this module's tools.
115pub async fn dispatch(
116    state: &AppState,
117    name: &str,
118    args: Value,
119    ct: &CancellationToken,
120) -> Option<Result<Call, McpError>> {
121    let call = match name {
122        "list_activity" => match parse_args(args) {
123            Ok(args) => activity::list_activity(state, args, ct).await,
124            Err(error) => return Some(Err(error)),
125        },
126        "query_stats" => match parse_args(args) {
127            Ok(args) => statements::query_stats(state, args, ct).await,
128            Err(error) => return Some(Err(error)),
129        },
130        "database_stats" => match parse_args(args) {
131            Ok(args) => stats::database_stats(state, args, ct).await,
132            Err(error) => return Some(Err(error)),
133        },
134        "table_stats" => match parse_args(args) {
135            Ok(args) => tables::table_stats(state, args, ct).await,
136            Err(error) => return Some(Err(error)),
137        },
138        "replication_status" => match parse_args(args) {
139            Ok(args) => replication::replication_status(state, args, ct).await,
140            Err(error) => return Some(Err(error)),
141        },
142        _ => return None,
143    };
144    Some(Ok(call))
145}
146
147/// Runs internal SQL with the wide value and response limits and encodes its rows.
148pub async fn wide_rows(
149    state: &AppState,
150    database: Option<&str>,
151    sql: &str,
152    params: &[Option<&str>],
153    ct: &CancellationToken,
154) -> Result<QueryEnvelope, ToolError> {
155    let statement = Statement {
156        sql,
157        params,
158        user_sql: false,
159        fetch: FetchLimits {
160            max_rows: INTERNAL_MAX_ROWS,
161            max_bytes: WIDE_RESPONSE_BYTES,
162            max_value_bytes: WIDE_VALUE_BYTES,
163        },
164        offset: Some(0),
165        search_path_catalog_only: true,
166    };
167    let (name, output) = Runner::new(state)
168        .internal_raw(database, statement, ct)
169        .await?;
170    let limits = Limits {
171        max_value_bytes: WIDE_VALUE_BYTES,
172        ..state.config.limits.clone()
173    };
174    let envelope = envelope::build(&name, output, &limits, false);
175    if envelope.truncated {
176        return Err(ToolError::Internal(
177            "the monitoring result is larger than MAX_RESPONSE_BYTES".to_owned(),
178        ));
179    }
180    Ok(envelope)
181}
182
183/// Whether the connected role may read other sessions' statement text, and the role's name.
184pub struct Visibility {
185    pub role: String,
186    pub visible: bool,
187}
188
189pub async fn text_visibility(
190    state: &AppState,
191    database: Option<&str>,
192    ct: &CancellationToken,
193) -> Result<Visibility, ToolError> {
194    let envelope = wide_rows(state, database, VISIBILITY_SQL, &[], ct).await?;
195    let row = envelope
196        .rows
197        .first()
198        .ok_or_else(|| ToolError::Internal("the server returned no role row".to_owned()))?;
199    Ok(Visibility {
200        role: row
201            .get("role")
202            .and_then(Value::as_str)
203            .unwrap_or_default()
204            .to_owned(),
205        visible: flag_of(row, "visible"),
206    })
207}
208
209/// The note that explains hidden statement text and how to show it.
210pub fn hidden_text_note(role: &str) -> String {
211    format!("Query text of other users is hidden: GRANT pg_read_all_stats TO {role};")
212}
213
214/// Maps PostgreSQL's placeholder for another role's statement text to None.
215pub fn visible_text(raw: Option<&str>) -> Option<&str> {
216    match raw {
217        Some(HIDDEN_TEXT) => None,
218        other => other,
219    }
220}
221
222/// The first `limit` characters of the text, and whether any were cut.
223pub fn cut_chars(text: &str, limit: usize) -> (String, bool) {
224    match text.char_indices().nth(limit) {
225        Some((index, _)) => {
226            let end = crate::scrub::cut_index(text.as_bytes(), index);
227            (text[..end].to_owned(), true)
228        }
229        None => (text.to_owned(), false),
230    }
231}
232
233/// Sets a row's `query` to its visible text, masked for secrets, cut to `chars`; `queryTruncated` says whether it was cut.
234pub fn shape_query(row: &mut Map<String, Value>, chars: usize) {
235    let (text, truncated) = match visible_text(row.get("query").and_then(Value::as_str)) {
236        Some(full) => {
237            let (cut, was_cut) = cut_chars(&mask(&crate::scrub::scrub_tail(full)), chars);
238            (Value::String(cut), was_cut)
239        }
240        None => (Value::Null, false),
241    };
242    row.insert("query".to_owned(), text);
243    row.insert("queryTruncated".to_owned(), Value::Bool(truncated));
244}
245
246/// An optional integer argument with its default, checked against an inclusive range.
247pub fn bounded(
248    name: &str,
249    value: Option<i64>,
250    default: i64,
251    min: i64,
252    max: i64,
253) -> Result<i64, ToolError> {
254    let value = value.unwrap_or(default);
255    if (min..=max).contains(&value) {
256        Ok(value)
257    } else {
258        Err(ToolError::Rejected(format!(
259            "{name} must be between {min} and {max}."
260        )))
261    }
262}
263
264/// An optional boolean argument; absent means false.
265pub fn flag(value: Option<bool>) -> bool {
266    value.unwrap_or(false)
267}
268
269pub fn bool_text(value: bool) -> &'static str {
270    if value { "true" } else { "false" }
271}
272
273/// Reads a boolean column of a row; absent or null means false.
274pub fn flag_of(row: &Map<String, Value>, key: &str) -> bool {
275    row.get(key).and_then(Value::as_bool).unwrap_or(false)
276}
277
278/// A snake_case column name as a camelCase result key.
279pub fn camel(name: &str) -> String {
280    let mut out = String::with_capacity(name.len());
281    let mut upper = false;
282    for ch in name.chars() {
283        if ch == '_' {
284            upper = true;
285        } else if upper {
286            out.extend(ch.to_uppercase());
287            upper = false;
288        } else {
289            out.push(ch);
290        }
291    }
292    out
293}
294
295/// The candidate columns that the relation has on this server, in candidate order.
296pub async fn present_columns(
297    state: &AppState,
298    database: Option<&str>,
299    relation: &str,
300    candidates: &[&str],
301    ct: &CancellationToken,
302) -> Result<Vec<String>, ToolError> {
303    let list = format!("{{{}}}", candidates.join(","));
304    let sql = "SELECT a.attname::text AS name FROM pg_catalog.pg_attribute a \
305        WHERE a.attrelid = pg_catalog.to_regclass($1::text) AND a.attnum > 0 \
306        AND NOT a.attisdropped AND a.attname = ANY($2::text[])";
307    let envelope = wide_rows(
308        state,
309        database,
310        sql,
311        &[Some(relation), Some(list.as_str())],
312        ct,
313    )
314    .await?;
315    let names: Vec<String> = envelope
316        .rows
317        .iter()
318        .filter_map(|row| row.get("name").and_then(Value::as_str).map(str::to_owned))
319        .collect();
320    Ok(candidates
321        .iter()
322        .filter(|candidate| names.iter().any(|name| name == *candidate))
323        .map(|candidate| (*candidate).to_owned())
324        .collect())
325}
326
327/// `alias.column AS "camelCase"` for each column; byte counts are cast to bigint.
328pub fn select_items(alias: &str, columns: &[String]) -> String {
329    columns
330        .iter()
331        .map(|column| {
332            let cast = if column.ends_with("_bytes") {
333                "::bigint"
334            } else {
335                ""
336            };
337            format!("{alias}.{column}{cast} AS \"{}\"", camel(column))
338        })
339        .collect::<Vec<_>>()
340        .join(", ")
341}
342
343/// The offset encoded in an `o:<offset>` cursor; absent means the first page.
344pub fn parse_offset(cursor: Option<&str>) -> Result<i64, ToolError> {
345    let Some(text) = cursor else {
346        return Ok(0);
347    };
348    text.strip_prefix("o:")
349        .filter(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
350        .and_then(|digits| digits.parse::<i64>().ok())
351        .ok_or_else(|| ToolError::Rejected("Invalid cursor.".to_owned()))
352}
353
354/// The cursor for the page after the one that starts at `offset`.
355pub fn next_cursor(offset: i64, limit: i64) -> String {
356    format!("o:{}", offset.saturating_add(limit))
357}
358
359/// The first row of a result as an object; an empty object when there is none.
360pub fn first_object(rows: Vec<Map<String, Value>>) -> Map<String, Value> {
361    rows.into_iter().next().unwrap_or_default()
362}
363
364/// Ends a tool call with a failure that names its database when it is known.
365pub fn fail(error: ToolError, state: &AppState, database: Option<&str>) -> Call {
366    failed(error, state.resolve_name(database))
367}