Skip to main content

postgres_mcp/tools/
core.rs

1//! The four core tools: list_databases, execute_query, explain_query and server_info.
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use rmcp::model::{Tool, ToolAnnotations};
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10use tokio_util::sync::CancellationToken;
11
12use super::envelope::{QueryEnvelope, elapsed_ms};
13use super::text;
14use super::{Call, INTERNAL_MAX_ROWS, Runner, Statement, ToolError, Toolset, value_of};
15use crate::gate::{GateOptions, StatementKind};
16use crate::pg::session::RunOutput;
17use crate::pg::wire::{FetchLimits, Field, Truncation};
18use crate::scrub;
19use crate::server::AppState;
20
21/// Time allowed per database for list_databases.
22const PROBE_CAP: Duration = Duration::from_secs(5);
23
24/// Settings that describe how to read data. None can hold credentials; a test checks this list.
25pub const SERVER_INFO_SETTINGS: &[&str] = &[
26    "statement_timeout",
27    "lock_timeout",
28    "idle_in_transaction_session_timeout",
29    "TimeZone",
30    "DateStyle",
31    "IntervalStyle",
32    "search_path",
33    "default_transaction_read_only",
34    "transaction_read_only",
35    "max_connections",
36    "shared_preload_libraries",
37    "logging_collector",
38    "log_destination",
39    "log_directory",
40    "log_filename",
41    "log_min_duration_statement",
42    "log_statement",
43    "track_activity_query_size",
44    "server_encoding",
45    "client_encoding",
46    "max_parallel_workers_per_gather",
47    "work_mem",
48    "wal_level",
49    "max_prepared_transactions",
50    "jit",
51];
52
53const CORE_SQL: &str = "SELECT pg_catalog.current_setting('server_version') AS server_version, \
54    pg_catalog.current_setting('server_version_num')::int AS server_version_num, \
55    pg_catalog.pg_postmaster_start_time()::text AS started_at, \
56    pg_catalog.pg_is_in_recovery() AS in_recovery";
57const DATABASE_SQL: &str = "SELECT pg_catalog.current_database() AS database_name, \
58    pg_catalog.getdatabaseencoding() AS encoding, \
59    pg_catalog.pg_database_size(pg_catalog.current_database()) AS database_size_bytes";
60const ROLE_SQL: &str = "SELECT rolname AS name, rolsuper AS superuser, rolcreaterole AS create_role, \
61    rolcreatedb AS create_db, rolreplication AS replication, rolbypassrls AS bypass_rls, \
62    rolconnlimit AS connection_limit FROM pg_catalog.pg_roles WHERE rolname = pg_catalog.current_user()";
63const MEMBERSHIP_SQL: &str = "WITH RECURSIVE member_of(roleid) AS (\
64    SELECT a.roleid FROM pg_catalog.pg_auth_members a \
65    WHERE a.member = (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname = pg_catalog.current_user()) \
66    UNION SELECT a.roleid FROM pg_catalog.pg_auth_members a JOIN member_of m ON a.member = m.roleid) \
67    SELECT r.rolname AS role_name FROM member_of m JOIN pg_catalog.pg_roles r ON r.oid = m.roleid \
68    ORDER BY r.rolname";
69/// Installed extensions; the schema column is read by the database resource, server_info ignores it.
70pub(crate) const EXTENSIONS_SQL: &str = "SELECT e.extname AS name, e.extversion AS version, \
71    n.nspname::text AS schema, \
72    CASE WHEN a.default_version <> e.extversion THEN a.default_version END AS available_version \
73    FROM pg_catalog.pg_extension e \
74    JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace \
75    LEFT JOIN pg_catalog.pg_available_extensions a ON a.name = e.extname ORDER BY e.extname";
76const TIMESCALE_SQL: &str =
77    "SELECT extversion AS timescaledb FROM pg_catalog.pg_extension WHERE extname = 'timescaledb'";
78const SETTINGS_SQL: &str = "SELECT s.name, pg_catalog.current_setting(s.name) AS setting FROM pg_catalog.pg_settings s WHERE s.name = ANY($1::text[]) ORDER BY s.name";
79/// The role's own search_path; the catalog-only session of SETTINGS_SQL would report pg_catalog.
80const SEARCH_PATH_SQL: &str = "SELECT pg_catalog.current_setting('search_path') AS setting";
81const VERSION_SQL: &str = "SELECT pg_catalog.current_setting('server_version') AS server_version, \
82    pg_catalog.current_setting('server_version_num')::int AS server_version_num";
83
84/// Arguments of list_databases, which takes none.
85#[derive(Debug, Deserialize, JsonSchema)]
86#[serde(deny_unknown_fields)]
87pub struct NoArgs {}
88
89#[derive(Debug, Deserialize, JsonSchema)]
90#[serde(deny_unknown_fields)]
91pub struct ExecuteArgs {
92    pub database: Option<String>,
93    pub sql: String,
94}
95
96#[derive(Debug, Deserialize, JsonSchema)]
97#[serde(deny_unknown_fields)]
98pub struct DatabaseArgs {
99    pub database: Option<String>,
100}
101
102#[derive(Debug, Clone, Copy, Default, Deserialize, JsonSchema)]
103#[serde(rename_all = "lowercase")]
104pub enum ExplainFormat {
105    #[default]
106    Text,
107    Json,
108    Yaml,
109    Xml,
110}
111
112impl ExplainFormat {
113    fn as_str(self) -> &'static str {
114        match self {
115            ExplainFormat::Text => "text",
116            ExplainFormat::Json => "json",
117            ExplainFormat::Yaml => "yaml",
118            ExplainFormat::Xml => "xml",
119        }
120    }
121}
122
123#[derive(Debug, Deserialize, JsonSchema)]
124#[serde(deny_unknown_fields)]
125pub struct ExplainArgs {
126    pub database: Option<String>,
127    pub sql: String,
128    #[serde(default)]
129    pub format: ExplainFormat,
130    #[serde(default)]
131    pub analyze: bool,
132    #[serde(default)]
133    pub buffers: bool,
134    #[serde(default)]
135    pub verbose: bool,
136    #[serde(default)]
137    pub settings: bool,
138    #[serde(default)]
139    pub wal: bool,
140    #[serde(default)]
141    pub memory: bool,
142    #[serde(default)]
143    pub serialize: bool,
144    #[serde(default)]
145    pub generic_plan: bool,
146}
147
148#[derive(Debug, Serialize, JsonSchema)]
149#[serde(rename_all = "camelCase")]
150pub struct ListDatabasesResult {
151    pub databases: Vec<DatabaseStatus>,
152}
153
154#[derive(Debug, Serialize, JsonSchema)]
155#[serde(rename_all = "camelCase")]
156pub struct DatabaseStatus {
157    pub name: String,
158    pub reachable: bool,
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub server_version: Option<String>,
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub server_version_num: Option<u64>,
163    /// Present for reachable databases; null when TimescaleDB is not installed.
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub timescaledb: Option<Option<String>>,
166    #[serde(skip_serializing_if = "Option::is_none")]
167    pub error: Option<String>,
168}
169
170#[derive(Debug, Serialize, JsonSchema)]
171#[serde(rename_all = "camelCase")]
172pub struct ExplainResult {
173    pub database: String,
174    pub format: &'static str,
175    pub plan: Value,
176    pub execution_time_ms: u64,
177}
178
179#[derive(Debug, Serialize, JsonSchema)]
180#[serde(rename_all = "camelCase")]
181pub struct ServerInfoResult {
182    pub database: String,
183    pub version: VersionInfo,
184    pub started_at: String,
185    pub in_recovery: bool,
186    pub database_name: Option<String>,
187    pub encoding: Option<String>,
188    pub database_size_bytes: Option<i64>,
189    pub role: Option<RoleInfo>,
190    pub extensions: Option<Vec<ExtensionInfo>>,
191    pub timescaledb: Option<String>,
192    pub settings: Option<Vec<SettingInfo>>,
193    pub warnings: Vec<String>,
194}
195
196#[derive(Debug, Serialize, JsonSchema)]
197#[serde(rename_all = "camelCase")]
198pub struct VersionInfo {
199    pub full: String,
200    pub number: u64,
201    pub major: u64,
202}
203
204#[derive(Debug, Serialize, JsonSchema)]
205#[serde(rename_all = "camelCase")]
206pub struct RoleInfo {
207    pub name: String,
208    pub superuser: bool,
209    pub create_role: bool,
210    pub create_db: bool,
211    pub replication: bool,
212    pub bypass_rls: bool,
213    pub connection_limit: i64,
214    pub member_of: Vec<String>,
215}
216
217#[derive(Debug, Serialize, JsonSchema)]
218#[serde(rename_all = "camelCase")]
219pub struct ExtensionInfo {
220    pub name: String,
221    pub version: String,
222    #[serde(skip_serializing_if = "Option::is_none")]
223    pub available_version: Option<String>,
224}
225
226#[derive(Debug, Serialize, JsonSchema)]
227#[serde(rename_all = "camelCase")]
228pub struct SettingInfo {
229    pub name: String,
230    pub value: String,
231    #[serde(skip_serializing_if = "Option::is_none")]
232    pub unit: Option<String>,
233}
234
235/// Every core tool with its toolset tag, title, description and schemas.
236pub fn catalog() -> Vec<(Toolset, Tool)> {
237    vec![
238        (
239            Toolset::Core,
240            tool::<NoArgs, ListDatabasesResult>(
241                "list_databases",
242                text::LIST_DATABASES_TITLE,
243                text::LIST_DATABASES,
244                &[],
245            ),
246        ),
247        (
248            Toolset::Core,
249            tool::<ExecuteArgs, QueryEnvelope>(
250                "execute_query",
251                text::EXECUTE_QUERY_TITLE,
252                text::EXECUTE_QUERY,
253                &[
254                    ("database", text::DATABASE_PARAM),
255                    ("sql", text::EXECUTE_QUERY_SQL_PARAM),
256                ],
257            ),
258        ),
259        (
260            Toolset::Core,
261            tool_with_leading::<ExplainArgs, ExplainResult>(
262                "explain_query",
263                text::EXPLAIN_QUERY_TITLE,
264                text::EXPLAIN_QUERY,
265                &[
266                    ("database", text::DATABASE_PARAM),
267                    ("sql", text::EXPLAIN_QUERY_SQL_PARAM),
268                    ("format", text::EXPLAIN_QUERY_FORMAT_PARAM),
269                    ("analyze", text::EXPLAIN_QUERY_ANALYZE_PARAM),
270                    ("buffers", text::EXPLAIN_QUERY_BUFFERS_PARAM),
271                    ("verbose", text::EXPLAIN_QUERY_VERBOSE_PARAM),
272                    ("settings", text::EXPLAIN_QUERY_SETTINGS_PARAM),
273                    ("wal", text::EXPLAIN_QUERY_WAL_PARAM),
274                    ("memory", text::EXPLAIN_QUERY_MEMORY_PARAM),
275                    ("serialize", text::EXPLAIN_QUERY_SERIALIZE_PARAM),
276                    ("generic_plan", text::EXPLAIN_QUERY_GENERIC_PLAN_PARAM),
277                ],
278                &[
279                    "sql",
280                    "format",
281                    "analyze",
282                    "buffers",
283                    "verbose",
284                    "settings",
285                    "wal",
286                    "memory",
287                    "serialize",
288                    "generic_plan",
289                ],
290            ),
291        ),
292        (
293            Toolset::Core,
294            tool::<DatabaseArgs, ServerInfoResult>(
295                "server_info",
296                text::SERVER_INFO_TITLE,
297                text::SERVER_INFO,
298                &[("database", text::DATABASE_PARAM)],
299            ),
300        ),
301    ]
302}
303
304/// Builds one tool: read-only annotations, schemas from the types, and the given property descriptions.
305pub fn tool<I: JsonSchema + 'static, O: JsonSchema + 'static>(
306    name: &'static str,
307    title: &'static str,
308    description: &'static str,
309    docs: &[(&str, &str)],
310) -> Tool {
311    tool_with_leading::<I, O>(name, title, description, docs, &[])
312}
313
314/// Like `tool`, and the descriptions of `leading` come first in their property objects.
315pub fn tool_with_leading<I: JsonSchema + 'static, O: JsonSchema + 'static>(
316    name: &'static str,
317    title: &'static str,
318    description: &'static str,
319    docs: &[(&str, &str)],
320    leading: &[&str],
321) -> Tool {
322    let mut tool = Tool::new(name, description, Arc::new(Map::new()))
323        .with_title(title)
324        .with_annotations(
325            ToolAnnotations::with_title(title)
326                .read_only(true)
327                .destructive(false)
328                .idempotent(true)
329                .open_world(false),
330        )
331        .with_input_schema::<I>()
332        .with_output_schema::<O>();
333    set_descriptions(&mut tool.input_schema, docs, leading);
334    add_redacted_hashes(&mut tool.output_schema);
335    tool
336}
337
338/// Adds the `redactedHashes` count to an output schema: every result carries it.
339fn add_redacted_hashes(schema: &mut Option<Arc<Map<String, Value>>>) {
340    let Some(schema) = schema.as_mut() else {
341        return;
342    };
343    let schema = Arc::make_mut(schema);
344    let count = serde_json::json!({
345        "type": "integer",
346        "minimum": 0,
347        "description": "Number of [redacted password hash] markers in this result."
348    });
349    if let Some(Value::Object(properties)) = schema.get_mut("properties") {
350        properties.insert("redactedHashes".to_owned(), count);
351    }
352    match schema.get_mut("required") {
353        Some(Value::Array(required)) => {
354            if !required.iter().any(|name| name == "redactedHashes") {
355                required.push(Value::from("redactedHashes"));
356            }
357        }
358        _ => {
359            schema.insert(
360                "required".to_owned(),
361                Value::Array(vec![Value::from("redactedHashes")]),
362            );
363        }
364    }
365}
366
367/// Replaces the description of each named property in a generated input schema. A `leading` property
368/// gets its description first in its object, where the published schema has it for these fields.
369fn set_descriptions(schema: &mut Arc<Map<String, Value>>, docs: &[(&str, &str)], leading: &[&str]) {
370    let schema = Arc::make_mut(schema);
371    let Some(Value::Object(properties)) = schema.get_mut("properties") else {
372        return;
373    };
374    for (name, doc) in docs {
375        if let Some(Value::Object(property)) = properties.get_mut(*name) {
376            let text = Value::String((*doc).to_owned());
377            if leading.contains(name) {
378                let rest = std::mem::take(property);
379                property.insert("description".to_owned(), text);
380                for (key, value) in rest {
381                    if key != "description" {
382                        property.insert(key, value);
383                    }
384                }
385            } else {
386                property.insert("description".to_owned(), text);
387            }
388        }
389    }
390}
391
392pub fn failed(error: ToolError, database: Option<String>) -> Call {
393    Call {
394        result: Err(error),
395        database,
396        rows: None,
397        sql: None,
398    }
399}
400
401pub async fn list_databases(state: Arc<AppState>, ct: &CancellationToken) -> Call {
402    let mut probes = tokio::task::JoinSet::new();
403    for (index, db) in state.config.databases.iter().enumerate() {
404        let (state, name, ct) = (state.clone(), db.name.clone(), ct.clone());
405        probes.spawn(scrub::under_counter(scrub::call_counter(), async move {
406            (index, probe(state, name, ct).await)
407        }));
408    }
409    let mut statuses = Vec::with_capacity(state.config.databases.len());
410    while let Some(joined) = probes.join_next().await {
411        match joined {
412            Ok(pair) => statuses.push(pair),
413            Err(error) => {
414                return failed(
415                    ToolError::Internal(format!("database probe failed: {error}")),
416                    None,
417                );
418            }
419        }
420    }
421    statuses.sort_by_key(|(index, _)| *index);
422    let databases = statuses.into_iter().map(|(_, status)| status).collect();
423    Call {
424        result: value_of(&ListDatabasesResult { databases }),
425        database: None,
426        rows: None,
427        sql: None,
428    }
429}
430
431/// One database's reachability, version and TimescaleDB version, capped at PROBE_CAP.
432async fn probe(state: Arc<AppState>, name: String, ct: CancellationToken) -> DatabaseStatus {
433    let sql = "SELECT pg_catalog.current_setting('server_version') AS server_version, \
434        pg_catalog.current_setting('server_version_num')::int AS server_version_num, \
435        (SELECT extversion FROM pg_catalog.pg_extension WHERE extname = 'timescaledb') AS timescaledb";
436    let runner = Runner::new(&state);
437    let outcome = tokio::time::timeout(
438        PROBE_CAP,
439        runner.internal_query(Some(name.as_str()), sql, &[], &ct),
440    )
441    .await;
442    let envelope = match outcome {
443        Ok(Ok(envelope)) => envelope,
444        Ok(Err(error)) => return unreachable_status(name, error.message()),
445        Err(_) => {
446            let message = format!("no answer within {} s", PROBE_CAP.as_secs());
447            return unreachable_status(name, message);
448        }
449    };
450    let Some(row) = envelope.rows.first() else {
451        return unreachable_status(name, "the server returned no row".to_owned());
452    };
453    DatabaseStatus {
454        name,
455        reachable: true,
456        server_version: text_of(row, "server_version"),
457        server_version_num: row.get("server_version_num").and_then(Value::as_u64),
458        timescaledb: Some(text_of(row, "timescaledb")),
459        error: None,
460    }
461}
462
463fn unreachable_status(name: String, error: String) -> DatabaseStatus {
464    DatabaseStatus {
465        name,
466        reachable: false,
467        server_version: None,
468        server_version_num: None,
469        timescaledb: None,
470        error: Some(error),
471    }
472}
473
474pub async fn execute_query(state: &AppState, args: ExecuteArgs, ct: &CancellationToken) -> Call {
475    let result = Runner::new(state)
476        .user_query(args.database.as_deref(), &args.sql, ct)
477        .await;
478    let database = match &result {
479        Ok(envelope) => Some(envelope.database.clone()),
480        Err(_) => state.resolve_name(args.database.as_deref()),
481    };
482    let rows = result.as_ref().ok().map(|envelope| envelope.row_count);
483    Call {
484        result: result.and_then(|envelope| value_of(&envelope)),
485        database,
486        rows,
487        sql: Some(args.sql),
488    }
489}
490
491pub async fn explain_query(state: &AppState, args: ExplainArgs, ct: &CancellationToken) -> Call {
492    let result = explain(state, &args, ct).await;
493    let database = match &result {
494        Ok(explained) => Some(explained.database.clone()),
495        Err(_) => state.resolve_name(args.database.as_deref()),
496    };
497    Call {
498        result: result.and_then(|explained| value_of(&explained)),
499        database,
500        rows: None,
501        sql: Some(args.sql),
502    }
503}
504
505async fn explain(
506    state: &AppState,
507    args: &ExplainArgs,
508    ct: &CancellationToken,
509) -> Result<ExplainResult, ToolError> {
510    // Resolves the database first, so an unknown name is reported before anything else.
511    state.pool(args.database.as_deref())?;
512    let limits = &state.config.limits;
513    let options = GateOptions {
514        allow_placeholders: args.generic_plan,
515        max_sql_bytes: limits.max_sql_bytes,
516    };
517    let accepted = super::check_sql(&args.sql, options).await?;
518    if accepted.kind != StatementKind::Select {
519        return Err(ToolError::Rejected(
520            "Query rejected: explain_query takes a SELECT, WITH, VALUES or TABLE statement."
521                .to_owned(),
522        ));
523    }
524    check_option_combinations(args)?;
525    let runner = Runner::new(state);
526    check_server_versions(&runner, args, ct).await?;
527
528    let prefix = explain_prefix(args);
529    let offset =
530        (!accepted.rewritten).then(|| u32::try_from(prefix.chars().count()).unwrap_or(u32::MAX));
531    let sql = format!("{prefix}{}", accepted.sql);
532    let fetch = FetchLimits {
533        max_rows: INTERNAL_MAX_ROWS,
534        max_bytes: limits.max_response_bytes,
535        max_value_bytes: limits.max_response_bytes,
536    };
537    let (database, output) = if args.generic_plan {
538        runner
539            .internal_generic(args.database.as_deref(), &sql, fetch, offset, ct)
540            .await?
541    } else {
542        let statement = Statement {
543            sql: &sql,
544            params: &[],
545            user_sql: false,
546            fetch,
547            offset,
548            search_path_catalog_only: false,
549        };
550        runner
551            .internal_raw(args.database.as_deref(), statement, ct)
552            .await?
553    };
554    let RunOutput {
555        result, elapsed, ..
556    } = output;
557    if let Some(truncated) = result.truncated {
558        return Err(truncated_plan_error(
559            truncated,
560            INTERNAL_MAX_ROWS,
561            limits.max_response_bytes,
562        ));
563    }
564    let plan = match args.format {
565        ExplainFormat::Json => json_plan(&result.rows)?,
566        _ => text_plan(&result.rows)?,
567    };
568    Ok(ExplainResult {
569        database,
570        format: args.format.as_str(),
571        plan,
572        execution_time_ms: elapsed_ms(elapsed),
573    })
574}
575
576fn check_option_combinations(args: &ExplainArgs) -> Result<(), ToolError> {
577    if args.generic_plan && args.analyze {
578        return Err(ToolError::Rejected(
579            "generic_plan cannot be combined with analyze.".to_owned(),
580        ));
581    }
582    for (name, on) in [("wal", args.wal), ("serialize", args.serialize)] {
583        if on && !args.analyze {
584            return Err(ToolError::Rejected(format!(
585                "Option {name} requires analyze=true."
586            )));
587        }
588    }
589    Ok(())
590}
591
592/// Rejects a requested option the connected server is too old for. Asks the server only when needed.
593async fn check_server_versions(
594    runner: &Runner<'_>,
595    args: &ExplainArgs,
596    ct: &CancellationToken,
597) -> Result<(), ToolError> {
598    let requested = [
599        ("settings", 12_u64, args.settings),
600        ("wal", 13, args.wal),
601        ("generic_plan", 16, args.generic_plan),
602        ("memory", 17, args.memory),
603        ("serialize", 17, args.serialize),
604    ];
605    if !requested.iter().any(|(_, _, on)| *on) {
606        return Ok(());
607    }
608    let envelope = runner
609        .internal_query(args.database.as_deref(), VERSION_SQL, &[], ct)
610        .await?;
611    let row = envelope
612        .rows
613        .first()
614        .ok_or_else(|| ToolError::Internal("the server returned no version".to_owned()))?;
615    let version = text_of(row, "server_version")
616        .ok_or_else(|| ToolError::Internal("the server returned no version".to_owned()))?;
617    let number = row
618        .get("server_version_num")
619        .and_then(Value::as_u64)
620        .ok_or_else(|| ToolError::Internal("the server returned no version number".to_owned()))?;
621    for (name, minimum, on) in requested {
622        if on && number < minimum * 10_000 {
623            return Err(ToolError::Rejected(format!(
624                "Option {name} needs PostgreSQL {minimum} or newer; this server is PostgreSQL {version}."
625            )));
626        }
627    }
628    Ok(())
629}
630
631/// The EXPLAIN keyword and its options, ending in the space before the statement.
632fn explain_prefix(args: &ExplainArgs) -> String {
633    let mut options = vec![format!("FORMAT {}", args.format.as_str())];
634    if args.analyze {
635        options.push("ANALYZE true".to_owned());
636    }
637    let flags = [
638        ("BUFFERS", args.buffers),
639        ("VERBOSE", args.verbose),
640        ("SETTINGS", args.settings),
641        ("WAL", args.wal),
642        ("MEMORY", args.memory),
643        ("GENERIC_PLAN", args.generic_plan),
644    ];
645    options.extend(
646        flags
647            .iter()
648            .filter(|(_, on)| *on)
649            .map(|(name, _)| format!("{name} true")),
650    );
651    // SERIALIZE takes NONE, TEXT or BINARY on PostgreSQL 17 and newer, not a boolean.
652    if args.serialize {
653        options.push("SERIALIZE TEXT".to_owned());
654    }
655    format!("EXPLAIN ({}) ", options.join(", "))
656}
657
658/// The plan's text: each row's first column, joined by newlines.
659fn text_plan(rows: &[Vec<Option<Field>>]) -> Result<Value, ToolError> {
660    let mut lines = Vec::with_capacity(rows.len());
661    for row in rows {
662        if let Some(Some(field)) = row.first() {
663            lines.push(String::from_utf8_lossy(whole(field)?).into_owned());
664        }
665    }
666    Ok(Value::String(lines.join("\n")))
667}
668
669/// The error for a plan cut short: the row cap or the byte budget, whichever tripped.
670fn truncated_plan_error(truncated: Truncation, max_rows: usize, max_bytes: usize) -> ToolError {
671    ToolError::Internal(match truncated {
672        Truncation::Rows => format!(
673            "The plan has more than {max_rows} lines; use format \"json\" or explain a smaller statement."
674        ),
675        Truncation::Bytes => {
676            format!("the plan is larger than MAX_RESPONSE_BYTES ({max_bytes} bytes)")
677        }
678    })
679}
680
681/// The plan as parsed JSON, from the single json value that FORMAT JSON returns.
682fn json_plan(rows: &[Vec<Option<Field>>]) -> Result<Value, ToolError> {
683    let field = rows
684        .first()
685        .and_then(|row| row.first())
686        .and_then(Option::as_ref)
687        .ok_or_else(|| ToolError::Internal("the server returned no plan".to_owned()))?;
688    serde_json::from_slice(whole(field)?)
689        .map_err(|e| ToolError::Internal(format!("the plan is not valid JSON: {e}")))
690}
691
692/// The complete bytes of a field; a cut value is an error, never a partial plan.
693fn whole(field: &Field) -> Result<&[u8], ToolError> {
694    if field.full_len > field.data.len() {
695        return Err(ToolError::Internal(format!(
696            "the plan is larger than MAX_RESPONSE_BYTES ({} bytes)",
697            field.full_len
698        )));
699    }
700    Ok(&field.data[..])
701}
702
703pub async fn server_info(state: &AppState, args: DatabaseArgs, ct: &CancellationToken) -> Call {
704    let result = server_info_of(state, args.database.as_deref(), ct).await;
705    let database = match &result {
706        Ok(info) => Some(info.database.clone()),
707        Err(_) => state.resolve_name(args.database.as_deref()),
708    };
709    Call {
710        result: result.and_then(|info| value_of(&info)),
711        database,
712        rows: None,
713        sql: None,
714    }
715}
716
717async fn server_info_of(
718    state: &AppState,
719    database: Option<&str>,
720    ct: &CancellationToken,
721) -> Result<ServerInfoResult, ToolError> {
722    let runner = Runner::new(state);
723    let core = runner.internal_query(database, CORE_SQL, &[], ct).await?;
724    let row = core
725        .rows
726        .first()
727        .ok_or_else(|| ToolError::Internal("the server returned no version row".to_owned()))?;
728    let number = row
729        .get("server_version_num")
730        .and_then(Value::as_u64)
731        .ok_or_else(|| ToolError::Internal("the server returned no version number".to_owned()))?;
732    let version = VersionInfo {
733        full: text_of(row, "server_version").unwrap_or_default(),
734        number,
735        major: number / 10_000,
736    };
737    let started_at = text_of(row, "started_at").unwrap_or_default();
738    let in_recovery = row
739        .get("in_recovery")
740        .and_then(Value::as_bool)
741        .unwrap_or_default();
742
743    let mut warnings = Vec::new();
744    let db_row = section(
745        &runner,
746        database,
747        DATABASE_SQL,
748        &[],
749        "database",
750        ct,
751        &mut warnings,
752    )
753    .await
754    .and_then(|rows| rows.into_iter().next())
755    .unwrap_or_default();
756    let role = match section(&runner, database, ROLE_SQL, &[], "role", ct, &mut warnings).await {
757        Some(rows) => match rows.first() {
758            Some(attrs) => section(
759                &runner,
760                database,
761                MEMBERSHIP_SQL,
762                &[],
763                "role.memberOf",
764                ct,
765                &mut warnings,
766            )
767            .await
768            .map(|members| RoleInfo {
769                name: text_of(attrs, "name").unwrap_or_default(),
770                superuser: flag(attrs, "superuser"),
771                create_role: flag(attrs, "create_role"),
772                create_db: flag(attrs, "create_db"),
773                replication: flag(attrs, "replication"),
774                bypass_rls: flag(attrs, "bypass_rls"),
775                connection_limit: attrs
776                    .get("connection_limit")
777                    .and_then(Value::as_i64)
778                    .unwrap_or_default(),
779                member_of: members
780                    .iter()
781                    .filter_map(|m| text_of(m, "role_name"))
782                    .collect(),
783            }),
784            None => None,
785        },
786        None => None,
787    };
788    let extensions = section(
789        &runner,
790        database,
791        EXTENSIONS_SQL,
792        &[],
793        "extensions",
794        ct,
795        &mut warnings,
796    )
797    .await
798    .map(|rows| {
799        rows.iter()
800            .map(|r| ExtensionInfo {
801                name: text_of(r, "name").unwrap_or_default(),
802                version: text_of(r, "version").unwrap_or_default(),
803                available_version: text_of(r, "available_version"),
804            })
805            .collect()
806    });
807    let timescaledb = section(
808        &runner,
809        database,
810        TIMESCALE_SQL,
811        &[],
812        "timescaledb",
813        ct,
814        &mut warnings,
815    )
816    .await
817    .and_then(|rows| rows.first().and_then(|r| text_of(r, "timescaledb")));
818    let search_path = match runner.user_query(database, SEARCH_PATH_SQL, ct).await {
819        Ok(envelope) => envelope.rows.first().and_then(|r| text_of(r, "setting")),
820        Err(error) => {
821            warnings.push(format!("settings.search_path: {}", error.message()));
822            None
823        }
824    };
825    let settings_list = format!("{{{}}}", SERVER_INFO_SETTINGS.join(","));
826    let settings = section(
827        &runner,
828        database,
829        SETTINGS_SQL,
830        &[Some(settings_list.as_str())],
831        "settings",
832        ct,
833        &mut warnings,
834    )
835    .await
836    .map(|rows| {
837        rows.iter()
838            .filter_map(|r| {
839                let name = text_of(r, "name").unwrap_or_default();
840                // The catalog-only session reports pg_catalog for search_path: use the role's value or omit it.
841                let value = if name == "search_path" {
842                    search_path.clone()?
843                } else {
844                    text_of(r, "setting").unwrap_or_default()
845                };
846                Some(SettingInfo {
847                    name,
848                    value,
849                    unit: None,
850                })
851            })
852            .collect()
853    });
854
855    Ok(ServerInfoResult {
856        database: core.database,
857        version,
858        started_at,
859        in_recovery,
860        database_name: text_of(&db_row, "database_name"),
861        encoding: text_of(&db_row, "encoding"),
862        database_size_bytes: db_row.get("database_size_bytes").and_then(Value::as_i64),
863        role,
864        extensions,
865        timescaledb,
866        settings,
867        warnings,
868    })
869}
870
871/// Runs one optional sub-query: its rows, or a warning naming the section and nothing else.
872async fn section(
873    runner: &Runner<'_>,
874    database: Option<&str>,
875    sql: &str,
876    params: &[Option<&str>],
877    label: &str,
878    ct: &CancellationToken,
879    warnings: &mut Vec<String>,
880) -> Option<Vec<Map<String, Value>>> {
881    match runner.internal_query(database, sql, params, ct).await {
882        Ok(envelope) => Some(envelope.rows),
883        Err(error) => {
884            warnings.push(format!("{label}: {}", error.message()));
885            None
886        }
887    }
888}
889
890fn text_of(row: &Map<String, Value>, key: &str) -> Option<String> {
891    row.get(key).and_then(Value::as_str).map(str::to_owned)
892}
893
894fn flag(row: &Map<String, Value>, key: &str) -> bool {
895    row.get(key).and_then(Value::as_bool).unwrap_or_default()
896}
897
898#[cfg(test)]
899mod tests {
900    use super::*;
901
902    #[test]
903    fn truncated_plan_names_the_reason_that_tripped() {
904        let rows = truncated_plan_error(Truncation::Rows, 5000, 48_000);
905        assert_eq!(
906            rows.message(),
907            "Internal error: The plan has more than 5000 lines; use format \"json\" or explain a smaller statement."
908        );
909        let bytes = truncated_plan_error(Truncation::Bytes, 5000, 48_000);
910        assert_eq!(
911            bytes.message(),
912            "Internal error: the plan is larger than MAX_RESPONSE_BYTES (48000 bytes)"
913        );
914    }
915}