Skip to main content

postgres_mcp/tools/
timescale.rs

1//! TimescaleDB tools: hypertables, continuous aggregates and background jobs, read from timescaledb_information and the extension's functions.
2
3pub mod caggs;
4pub mod hypertables;
5pub mod jobs;
6pub mod parse;
7pub mod probe;
8
9use rmcp::ErrorData as McpError;
10use rmcp::model::Tool;
11use serde_json::{Map, Value};
12use tokio_util::sync::CancellationToken;
13
14use super::core::{tool, tool_with_leading};
15use super::envelope::{self, QueryEnvelope};
16use super::text;
17use super::{Call, INTERNAL_MAX_ROWS, Runner, Statement, ToolError, Toolset, parse_args};
18use crate::pg::wire::FetchLimits;
19use crate::server::AppState;
20
21/// Rows per page when the caller gives no limit.
22const DEFAULT_LIMIT: usize = 100;
23/// Chunks per page of describe_hypertable when the caller gives no chunk_limit.
24const DEFAULT_CHUNK_LIMIT: usize = 20;
25/// Largest single value a catalog query may return; a longer value is an error, never a cut.
26const MAX_VALUE_BYTES: usize = 1_048_576;
27/// Largest response a catalog query may return.
28const MAX_RESPONSE_BYTES: usize = 8 * 1_048_576;
29
30const DIMENSION_COLUMNS: &[&str] = &[
31    "hypertable_schema",
32    "hypertable_name",
33    "dimension_number",
34    "dimension_type",
35    "column_name",
36    "column_type",
37    "time_interval",
38    "integer_interval",
39    "num_partitions",
40];
41const CHUNK_COLUMNS: &[&str] = &[
42    "hypertable_schema",
43    "hypertable_name",
44    "chunk_schema",
45    "chunk_name",
46    "range_start",
47    "range_end",
48    "range_start_integer",
49    "range_end_integer",
50];
51const CAGG_COLUMNS: &[&str] = &[
52    "view_schema",
53    "view_name",
54    "view_owner",
55    "hypertable_schema",
56    "hypertable_name",
57    "materialized_only",
58    "view_definition",
59    "materialization_hypertable_schema",
60    "materialization_hypertable_name",
61];
62const JOB_COLUMNS: &[&str] = &[
63    "job_id",
64    "application_name",
65    "schedule_interval",
66    "max_runtime",
67    "max_retries",
68    "retry_period",
69    "proc_schema",
70    "proc_name",
71    "owner",
72    "scheduled",
73    "config",
74    "next_start",
75    "hypertable_schema",
76    "hypertable_name",
77];
78const JOB_STATS_COLUMNS: &[&str] = &[
79    "job_id",
80    "last_run_started_at",
81    "last_successful_finish",
82    "last_run_status",
83    "last_run_duration",
84    "total_runs",
85    "total_successes",
86    "total_failures",
87];
88const HISTORY_COLUMNS: &[&str] = &[
89    "id",
90    "job_id",
91    "succeeded",
92    "proc_schema",
93    "proc_name",
94    "pid",
95    "start_time",
96    "finish_time",
97    "sqlerrcode",
98    "err_message",
99];
100const ERRORS_COLUMNS: &[&str] = &[
101    "job_id",
102    "proc_schema",
103    "proc_name",
104    "pid",
105    "start_time",
106    "finish_time",
107    "sqlerrcode",
108    "err_message",
109];
110/// SQL that finds the oid of one relation by schema and name.
111const RELATION_OID_SQL: &str = "SELECT c.oid FROM pg_catalog.pg_class c \
112    JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
113    WHERE n.nspname = $1::text AND c.relname = $2::text";
114
115/// The four TimescaleDB tools with their toolset tag.
116pub fn catalog() -> Vec<(Toolset, Tool)> {
117    vec![
118        (
119            Toolset::Timescale,
120            tool::<hypertables::ListArgs, hypertables::ListResult>(
121                "list_hypertables",
122                text::LIST_HYPERTABLES_TITLE,
123                text::LIST_HYPERTABLES,
124                &[
125                    ("database", text::DATABASE_PARAM),
126                    ("schema", text::SCHEMA_PARAM),
127                    ("limit", text::LIMIT_PARAM),
128                    ("cursor", text::CURSOR_PARAM),
129                ],
130            ),
131        ),
132        (
133            Toolset::Timescale,
134            tool_with_leading::<hypertables::DescribeArgs, hypertables::DescribeResult>(
135                "describe_hypertable",
136                text::DESCRIBE_HYPERTABLE_TITLE,
137                text::DESCRIBE_HYPERTABLE,
138                &[
139                    ("database", text::DATABASE_PARAM),
140                    ("hypertable", text::DESCRIBE_HYPERTABLE_HYPERTABLE_PARAM),
141                    ("schema", text::DESCRIBE_HYPERTABLE_SCHEMA_PARAM),
142                    ("chunk_limit", text::DESCRIBE_HYPERTABLE_CHUNK_LIMIT_PARAM),
143                    ("chunk_cursor", text::DESCRIBE_HYPERTABLE_CHUNK_CURSOR_PARAM),
144                ],
145                &["hypertable", "schema", "chunk_limit", "chunk_cursor"],
146            ),
147        ),
148        (
149            Toolset::Timescale,
150            tool::<caggs::ListArgs, caggs::ListResult>(
151                "list_continuous_aggregates",
152                text::LIST_CAGGS_TITLE,
153                text::LIST_CAGGS,
154                &[
155                    ("database", text::DATABASE_PARAM),
156                    ("schema", text::SCHEMA_PARAM),
157                    ("limit", text::LIMIT_PARAM),
158                    ("cursor", text::CURSOR_PARAM),
159                ],
160            ),
161        ),
162        (
163            Toolset::Timescale,
164            tool_with_leading::<jobs::ListArgs, jobs::ListResult>(
165                "list_jobs",
166                text::LIST_JOBS_TITLE,
167                text::LIST_JOBS,
168                &[
169                    ("database", text::DATABASE_PARAM),
170                    ("job_id", text::LIST_JOBS_JOB_ID_PARAM),
171                    ("history", text::LIST_JOBS_HISTORY_PARAM),
172                    ("only_failures", text::LIST_JOBS_ONLY_FAILURES_PARAM),
173                    ("limit", text::LIMIT_PARAM),
174                    ("cursor", text::CURSOR_PARAM),
175                ],
176                &["job_id", "history", "only_failures"],
177            ),
178        ),
179    ]
180}
181
182/// Runs the named tool, or returns None when the name is not one of this module's tools.
183pub async fn dispatch(
184    state: &AppState,
185    name: &str,
186    args: Value,
187    ct: &CancellationToken,
188) -> Option<Result<Call, McpError>> {
189    let call = match name {
190        "list_hypertables" => match parse_args(args) {
191            Ok(args) => hypertables::list(state, args, ct).await,
192            Err(error) => return Some(Err(error)),
193        },
194        "describe_hypertable" => match parse_args(args) {
195            Ok(args) => hypertables::describe(state, args, ct).await,
196            Err(error) => return Some(Err(error)),
197        },
198        "list_continuous_aggregates" => match parse_args(args) {
199            Ok(args) => caggs::list(state, args, ct).await,
200            Err(error) => return Some(Err(error)),
201        },
202        "list_jobs" => match parse_args(args) {
203            Ok(args) => jobs::list(state, args, ct).await,
204            Err(error) => return Some(Err(error)),
205        },
206        _ => return None,
207    };
208    Some(Ok(call))
209}
210
211/// Runs catalog SQL with the catalog limits. A result cut by a limit is an error, never a partial list.
212async fn query(
213    state: &AppState,
214    database: Option<&str>,
215    sql: &str,
216    params: &[Option<&str>],
217    ct: &CancellationToken,
218) -> Result<QueryEnvelope, ToolError> {
219    let statement = Statement {
220        sql,
221        params,
222        user_sql: false,
223        fetch: FetchLimits {
224            max_rows: INTERNAL_MAX_ROWS,
225            max_bytes: MAX_RESPONSE_BYTES,
226            max_value_bytes: MAX_VALUE_BYTES,
227        },
228        offset: Some(0),
229        search_path_catalog_only: true,
230    };
231    let (name, output) = Runner::new(state)
232        .internal_raw(database, statement, ct)
233        .await?;
234    let mut limits = state.config.limits.clone();
235    limits.max_value_bytes = MAX_VALUE_BYTES;
236    let envelope = envelope::build(&name, output, &limits, false);
237    if envelope.truncated || envelope.truncated_values > 0 {
238        return Err(ToolError::Internal(
239            "a TimescaleDB catalog result exceeds the response limits".to_owned(),
240        ));
241    }
242    Ok(envelope)
243}
244
245/// Runs one optional section: its rows, or None and a warning naming the section. Cancellation stays an error.
246async fn section(
247    state: &AppState,
248    database: Option<&str>,
249    sql: &str,
250    params: &[Option<&str>],
251    label: &str,
252    ct: &CancellationToken,
253    warnings: &mut Vec<String>,
254) -> Result<Option<Vec<Map<String, Value>>>, ToolError> {
255    match query(state, database, sql, params, ct).await {
256        Ok(envelope) => Ok(Some(envelope.rows)),
257        Err(error @ ToolError::Cancelled) => Err(error),
258        Err(error) => {
259            warnings.push(format!("{label}: {}", error.message()));
260            Ok(None)
261        }
262    }
263}
264
265/// A section that needs view columns: its rows, or a warning when this TimescaleDB version lacks one.
266#[allow(clippy::too_many_arguments)]
267async fn checked_section(
268    state: &AppState,
269    database: Option<&str>,
270    features: &probe::Features,
271    needs: &[(&str, &[&str])],
272    sql: &str,
273    params: &[Option<&str>],
274    label: &str,
275    ct: &CancellationToken,
276    warnings: &mut Vec<String>,
277) -> Result<Option<Vec<Map<String, Value>>>, ToolError> {
278    for (view, columns) in needs {
279        if let Err(error) = features.require(view, columns) {
280            warnings.push(format!("{label}: {}", error.message()));
281            return Ok(None);
282        }
283    }
284    section(state, database, sql, params, label, ct, warnings).await
285}
286
287/// Adds one value per relation of the rows (keyed by schema and name) from a guarded call.
288/// A failing call leaves the value null and adds a warning; other rows are unaffected.
289async fn add_per_relation(
290    state: &AppState,
291    database: &str,
292    rows: &mut [Map<String, Value>],
293    key: &str,
294    function: &str,
295    ct: &CancellationToken,
296    warnings: &mut Vec<String>,
297) -> Result<(), ToolError> {
298    let sql = format!(
299        "SELECT {function}(c.oid) AS value FROM pg_catalog.pg_class c \
300         JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
301         WHERE n.nspname = $1::text AND c.relname = $2::text"
302    );
303    for row in rows.iter_mut() {
304        let (Some(schema), Some(name)) = (text_of(row, "schema"), text_of(row, "name")) else {
305            continue;
306        };
307        let label = format!("{schema}.{name} {key}");
308        let params = [Some(schema.as_str()), Some(name.as_str())];
309        let found = section(state, Some(database), &sql, &params, &label, ct, warnings).await?;
310        let value = first_row(found)
311            .and_then(|found| found.get("value").cloned())
312            .unwrap_or(Value::Null);
313        row.insert(key.to_owned(), value);
314    }
315    Ok(())
316}
317
318/// The first row of a section that ran and returned one.
319fn first_row(rows: Option<Vec<Map<String, Value>>>) -> Option<Map<String, Value>> {
320    rows?.into_iter().next()
321}
322
323/// A cell of a row, or null when the row or the cell is absent.
324fn cell(row: &Option<Map<String, Value>>, key: &str) -> Value {
325    row.as_ref()
326        .and_then(|row| row.get(key).cloned())
327        .unwrap_or(Value::Null)
328}
329
330/// The text of a cell, when it is a string.
331fn text_of(row: &Map<String, Value>, key: &str) -> Option<String> {
332    row.get(key).and_then(Value::as_str).map(str::to_owned)
333}
334
335/// Says that a catalog function is missing from this TimescaleDB version.
336fn unavailable(warnings: &mut Vec<String>, function: &str) {
337    warnings.push(format!(
338        "{function} is not available in this TimescaleDB version."
339    ));
340}
341
342/// One page of a paged list: how many rows it holds and where it starts.
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
344pub struct Page {
345    pub limit: usize,
346    pub offset: usize,
347}
348
349impl Page {
350    /// Reads limit and cursor; `name` is the limit's argument name in its error text.
351    pub fn new(
352        limit: Option<i64>,
353        default: usize,
354        name: &str,
355        cursor: Option<&str>,
356    ) -> Result<Page, ToolError> {
357        let limit = match limit {
358            None => default,
359            Some(value) if (1..=500).contains(&value) => value as usize,
360            Some(_) => {
361                return Err(ToolError::Rejected(format!(
362                    "{name} must be between 1 and 500."
363                )));
364            }
365        };
366        let offset = match cursor {
367            None => 0,
368            Some(text) => text
369                .strip_prefix("o:")
370                .and_then(|number| number.parse::<u32>().ok())
371                .map(|number| number as usize)
372                .ok_or_else(|| ToolError::Rejected("Invalid cursor.".to_owned()))?,
373        };
374        Ok(Page { limit, offset })
375    }
376
377    /// The SQL window: one row more than the page, so that a next page is known to exist.
378    fn window(&self) -> String {
379        format!("LIMIT {} OFFSET {}", self.limit + 1, self.offset)
380    }
381
382    /// Drops the extra row and returns the cursor of the next page when there is one.
383    pub fn trim(&self, rows: &mut Vec<Map<String, Value>>) -> Option<String> {
384        if rows.len() > self.limit {
385            rows.truncate(self.limit);
386            Some(format!("o:{}", self.offset.saturating_add(self.limit)))
387        } else {
388            None
389        }
390    }
391}
392
393/// The policy kind of a job row: columnstore, retention, reorder or refresh for the internal policy procedures, else custom.
394fn job_kind_sql(alias: &str) -> String {
395    format!(
396        "CASE WHEN {alias}.proc_schema::text = '_timescaledb_functions' THEN CASE {alias}.proc_name::text \
397         WHEN 'policy_compression' THEN 'columnstore' WHEN 'policy_recompression' THEN 'columnstore' \
398         WHEN 'policy_retention' THEN 'retention' WHEN 'policy_reorder' THEN 'reorder' \
399         WHEN 'policy_refresh_continuous_aggregate' THEN 'refresh' ELSE 'custom' END ELSE 'custom' END"
400    )
401}