Skip to main content

postgres_mcp/tools/
mod.rs

1//! MCP tool layer: error texts, the shared query runner, the tool catalog and the rmcp server handler.
2
3pub mod core;
4pub mod envelope;
5pub mod logs;
6pub mod mask;
7pub mod monitor;
8pub mod schema;
9// text.rs is committed unformatted and must not be edited; rustfmt leaves it alone.
10#[rustfmt::skip]
11pub mod text;
12pub mod timescale;
13
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use rmcp::model::{
18    CallToolRequestParams, CallToolResponse, CallToolResult, CompleteRequestMethod,
19    CompleteRequestParams, CompleteResult, CompletionInfo, ContentBlock, Implementation,
20    ListResourceTemplatesRequestMethod, ListResourceTemplatesResult, ListResourcesRequestMethod,
21    ListResourcesResult, ListToolsResult, PaginatedRequestParams, ReadResourceRequestMethod,
22    ReadResourceRequestParams, ReadResourceResponse, ResourcesCapability, ServerCapabilities,
23    ServerConfig, Tool,
24};
25use rmcp::service::RequestContext;
26use rmcp::{ErrorData as McpError, RoleServer, ServerHandler};
27use serde::Serialize;
28use serde::de::DeserializeOwned;
29use serde_json::Value;
30use tokio_util::sync::CancellationToken;
31
32use crate::audit;
33use crate::config::{DatabaseConfig, Toolsets};
34use crate::gate::{self, Accepted, GateOptions, StatementKind};
35use crate::pg::pool::Pool;
36use crate::pg::session::{
37    RunError, RunOutput, SessionSettings, run_readonly, run_readonly_explain_generic,
38};
39use crate::pg::wire::{DbError, FetchLimits};
40use crate::resources;
41use crate::scrub;
42use crate::server::AppState;
43use envelope::QueryEnvelope;
44
45/// How long a call waits for a free pooled connection.
46const POOL_WAIT: Duration = Duration::from_secs(10);
47/// Row cap for internal queries, which the server never returns in full to a client.
48const INTERNAL_MAX_ROWS: usize = 5_000;
49
50/// Tool groups; a tool is listed and callable only when its group is enabled in the config.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Toolset {
53    Core,
54    Schema,
55    Monitor,
56    Logs,
57    Timescale,
58}
59
60impl Toolset {
61    pub fn enabled(self, toolsets: &Toolsets) -> bool {
62        match self {
63            Toolset::Core => true,
64            Toolset::Schema => toolsets.schema,
65            Toolset::Monitor => toolsets.monitor,
66            Toolset::Logs => toolsets.logs,
67            Toolset::Timescale => toolsets.timescale,
68        }
69    }
70}
71
72/// Why a tool call failed. `message` is the exact text the client receives.
73#[derive(Debug)]
74pub enum ToolError {
75    /// Configuration or database lookup failure, shown verbatim.
76    Config(String),
77    /// Gate or server refusal, shown as its full text.
78    Rejected(String),
79    /// PostgreSQL error; its position is already relative to the submitted SQL.
80    Db(Box<DbError>),
81    Timeout(u64),
82    Cancelled,
83    Unavailable {
84        database: String,
85        message: String,
86    },
87    Internal(String),
88}
89
90impl ToolError {
91    pub fn message(&self) -> String {
92        match self {
93            ToolError::Config(text) | ToolError::Rejected(text) => text.clone(),
94            ToolError::Db(e) => db_message(e),
95            ToolError::Timeout(ms) => format!(
96                "The query exceeded the {ms} ms time limit and was cancelled on the server. Narrow it with WHERE, LIMIT or an aggregate."
97            ),
98            ToolError::Cancelled => "The request was cancelled.".to_owned(),
99            ToolError::Unavailable { database, message } => {
100                format!("Database \"{database}\" is unavailable: {message}")
101            }
102            ToolError::Internal(message) => format!("Internal error: {message}"),
103        }
104    }
105
106    pub fn sqlstate(&self) -> Option<&str> {
107        match self {
108            ToolError::Db(e) => Some(e.code.as_str()),
109            _ => None,
110        }
111    }
112
113    /// Maps a session error; `offset` is the length of any SQL prefix added before the submitted text.
114    pub fn from_run(error: RunError, database: &str, offset: Option<u32>) -> ToolError {
115        match error {
116            RunError::Refused(message) => ToolError::Rejected(refusal_text(&message)),
117            RunError::Db(mut e) => {
118                // Without an offset the text was rewritten, so the parser's position no longer matches the caller's text.
119                e.position = offset.and_then(|offset| {
120                    e.position
121                        .and_then(|p| p.checked_sub(offset))
122                        .filter(|p| *p > 0)
123                });
124                ToolError::Db(Box::new(e))
125            }
126            RunError::Timeout(ms) => ToolError::Timeout(ms),
127            RunError::Cancelled => ToolError::Cancelled,
128            RunError::Unavailable(message) => ToolError::Unavailable {
129                database: database.to_owned(),
130                message,
131            },
132            RunError::Internal(message) => ToolError::Internal(message),
133        }
134    }
135}
136
137fn db_message(e: &DbError) -> String {
138    let mut text = format!("PostgreSQL error {}: {}", e.code, e.message);
139    if let Some(detail) = &e.detail {
140        text.push_str(" Detail: ");
141        text.push_str(detail);
142    }
143    if let Some(hint) = &e.hint {
144        text.push_str(" Hint: ");
145        text.push_str(hint);
146    }
147    if let Some(position) = e.position {
148        text.push_str(&format!(" Position: {position}"));
149    }
150    text
151}
152
153fn refusal_text(message: &str) -> String {
154    if message == "statement does not return rows" {
155        "Query rejected: only statements that return rows can run here.".to_owned()
156    } else {
157        format!("Query rejected: {message}.")
158    }
159}
160
161/// One SQL execution: the text, its bind values, whether it is user SQL and its fetch limits.
162pub struct Statement<'a> {
163    pub sql: &'a str,
164    pub params: &'a [Option<&'a str>],
165    pub user_sql: bool,
166    pub fetch: FetchLimits,
167    /// Characters the runner prepended to the submitted SQL, subtracted from error positions; None when the
168    /// submitted text was rewritten and no position can be reported.
169    pub offset: Option<u32>,
170    /// True when the server's own catalog SQL runs; false for user SQL, which keeps the role's search_path.
171    pub search_path_catalog_only: bool,
172}
173
174/// Gates SQL on a blocking thread, since a long parse must not stall the runtime; a rejection is a tool error.
175pub async fn check_sql(sql: &str, options: GateOptions) -> Result<Accepted, ToolError> {
176    let sql = sql.to_owned();
177    let outcome = tokio::task::spawn_blocking(move || gate::check(&sql, &options))
178        .await
179        .map_err(|_| ToolError::Internal("the SQL check did not complete".to_owned()))?;
180    outcome.map_err(|r| ToolError::Rejected(format!("Query rejected: {}", r.message)))
181}
182
183/// Runs SQL for the tools: user SQL through the gate, internal SQL without it.
184pub struct Runner<'a> {
185    state: &'a AppState,
186}
187
188impl<'a> Runner<'a> {
189    pub fn new(state: &'a AppState) -> Runner<'a> {
190        Runner { state }
191    }
192
193    /// Gates the SQL, runs it read-only and encodes the rows.
194    pub async fn user_query(
195        &self,
196        database: Option<&str>,
197        sql: &str,
198        ct: &CancellationToken,
199    ) -> Result<QueryEnvelope, ToolError> {
200        let limits = &self.state.config.limits;
201        let (db, pool) = self.state.pool(database)?;
202        let options = GateOptions {
203            allow_placeholders: false,
204            max_sql_bytes: limits.max_sql_bytes,
205        };
206        let accepted = check_sql(sql, options).await?;
207        let statement = Statement {
208            sql: &accepted.sql,
209            params: &[],
210            user_sql: true,
211            fetch: user_fetch(limits.max_rows, self.state),
212            offset: (!accepted.rewritten).then_some(0),
213            search_path_catalog_only: false,
214        };
215        let output = run(db, &pool, statement, ct).await?;
216        Ok(envelope::build(
217            &db.name,
218            output,
219            limits,
220            hides_secret_rows(&accepted),
221        ))
222    }
223
224    /// Runs internal SQL (no gate) and encodes the rows.
225    pub async fn internal_query(
226        &self,
227        database: Option<&str>,
228        sql: &str,
229        params: &[Option<&str>],
230        ct: &CancellationToken,
231    ) -> Result<QueryEnvelope, ToolError> {
232        let statement = Statement {
233            sql,
234            params,
235            user_sql: false,
236            fetch: user_fetch(INTERNAL_MAX_ROWS, self.state),
237            offset: Some(0),
238            search_path_catalog_only: true,
239        };
240        let (name, output) = self.internal_raw(database, statement, ct).await?;
241        Ok(envelope::build(
242            &name,
243            output,
244            &self.state.config.limits,
245            false,
246        ))
247    }
248
249    /// Runs internal SQL and returns the database name with the raw output.
250    pub async fn internal_raw(
251        &self,
252        database: Option<&str>,
253        statement: Statement<'_>,
254        ct: &CancellationToken,
255    ) -> Result<(String, RunOutput), ToolError> {
256        let (db, pool) = self.state.pool(database)?;
257        let output = run(db, &pool, statement, ct).await?;
258        Ok((db.name.clone(), output))
259    }
260
261    /// Runs a generic-plan EXPLAIN text through the simple protocol behind the server-side preflight.
262    pub async fn internal_generic(
263        &self,
264        database: Option<&str>,
265        sql: &str,
266        fetch: FetchLimits,
267        offset: Option<u32>,
268        ct: &CancellationToken,
269    ) -> Result<(String, RunOutput), ToolError> {
270        let (db, pool) = self.state.pool(database)?;
271        let settings = session_settings(db, fetch, false);
272        let output = run_readonly_explain_generic(&pool, sql, &settings, ct)
273            .await
274            .map_err(|e| ToolError::from_run(e, &db.name, offset))?;
275        Ok((db.name.clone(), output))
276    }
277}
278
279fn user_fetch(max_rows: usize, state: &AppState) -> FetchLimits {
280    FetchLimits {
281        max_rows,
282        max_bytes: state.config.limits.max_response_bytes,
283        max_value_bytes: state.config.limits.max_value_bytes,
284    }
285}
286
287fn session_settings(
288    db: &DatabaseConfig,
289    fetch: FetchLimits,
290    search_path_catalog_only: bool,
291) -> SessionSettings {
292    SessionSettings {
293        statement_timeout_ms: db.statement_timeout_ms,
294        lock_timeout_ms: db.lock_timeout_ms,
295        fetch,
296        pool_wait: POOL_WAIT,
297        search_path_catalog_only,
298    }
299}
300
301async fn run(
302    db: &DatabaseConfig,
303    pool: &Pool,
304    statement: Statement<'_>,
305    ct: &CancellationToken,
306) -> Result<RunOutput, ToolError> {
307    let settings = session_settings(db, statement.fetch, statement.search_path_catalog_only);
308    run_readonly(
309        pool,
310        statement.sql,
311        statement.params,
312        statement.user_sql,
313        &settings,
314        ct,
315    )
316    .await
317    .map_err(|e| ToolError::from_run(e, &db.name, statement.offset))
318}
319
320/// `SHOW ALL` is the only statement whose rows are filtered.
321fn hides_secret_rows(accepted: &Accepted) -> bool {
322    matches!(&accepted.kind, StatementKind::Show { name } if name == "all")
323}
324
325/// One tool call's outcome, with what the audit line needs.
326pub struct Call {
327    pub result: Result<Value, ToolError>,
328    pub database: Option<String>,
329    pub rows: Option<usize>,
330    /// The SQL text, used only to compute the audit digest.
331    pub sql: Option<String>,
332}
333
334/// Serializes a successful result.
335pub fn value_of<T: Serialize>(value: &T) -> Result<Value, ToolError> {
336    serde_json::to_value(value).map_err(|e| ToolError::Internal(e.to_string()))
337}
338
339/// The server handler: lists the enabled tools and dispatches calls.
340#[derive(Clone)]
341pub struct PgMcp {
342    state: Arc<AppState>,
343    tools: Arc<Vec<Tool>>,
344}
345
346impl PgMcp {
347    pub fn new(state: Arc<AppState>) -> PgMcp {
348        let tools = core::catalog()
349            .into_iter()
350            .chain(schema::catalog())
351            .chain(monitor::catalog())
352            .chain(logs::catalog())
353            .chain(timescale::catalog())
354            .filter(|(set, _)| set.enabled(&state.config.toolsets))
355            .map(|(_, tool)| tool)
356            .collect();
357        PgMcp {
358            state,
359            tools: Arc::new(tools),
360        }
361    }
362}
363
364pub fn parse_args<T: DeserializeOwned>(args: Value) -> Result<T, McpError> {
365    serde_json::from_value(args).map_err(|e| {
366        let message = format!("invalid arguments: {e}");
367        McpError::invalid_params(scrub::scrub(&message).into_owned(), None)
368    })
369}
370
371/// The final pass over a tool result: hashes are replaced, string values are masked, and `redactedHashes` is the
372/// number of markers in the result, which the call's counter takes too.
373fn scrubbed(mut value: Value, tool: &str) -> Value {
374    // The columns get the hash scrubber only: the envelope masked their names once, and a second PASSWORD pass
375    // could move a name away from its row key.
376    let names = if tool == "execute_query" {
377        value.get_mut("columns").map(|columns| {
378            scrub::scrub_value(columns);
379            std::mem::take(columns)
380        })
381    } else {
382        None
383    };
384    mask::scrub_and_mask(&mut value, pre_masked(tool), statement_text(tool));
385    if let Some(names) = names {
386        value["columns"] = names;
387    }
388    let total = scrub::count_markers(&value);
389    scrub::set_total(total);
390    if let Some(object) = value.as_object_mut() {
391        object.insert("redactedHashes".to_owned(), Value::from(total));
392    }
393    value
394}
395
396/// Scrubs and masks a completion result, keys included, by round-tripping it through its JSON form.
397fn scrub_completion(result: CompleteResult) -> CompleteResult {
398    let Ok(mut value) = serde_json::to_value(&result) else {
399        return CompleteResult::new(CompletionInfo::default());
400    };
401    mask::scrub_and_mask(&mut value, &[], &[]);
402    scrub::set_total(scrub::count_markers(&value));
403    serde_json::from_value(value).unwrap_or_else(|_| CompleteResult::new(CompletionInfo::default()))
404}
405
406/// The client-facing success shape: structured content and the same JSON as one text block.
407/// The value must come from `scrubbed`; the text block is scrubbed again as a guard.
408fn success(tool: &str, value: Value) -> CallToolResult {
409    let json = value.to_string();
410    let (text, found) = scrub::scrub_counting(&json);
411    if found > 0 {
412        tracing::warn!(
413            tool,
414            count = found,
415            "output guard replaced text after the main pass"
416        );
417    }
418    let text = text.into_owned();
419    let mut result = CallToolResult::success(vec![ContentBlock::text(text)]);
420    result.structured_content = Some(value);
421    result
422}
423
424impl PgMcp {
425    /// Resources and completions follow the schema toolset.
426    fn resources_enabled(&self) -> bool {
427        Toolset::Schema.enabled(&self.state.config.toolsets)
428    }
429}
430
431impl ServerHandler for PgMcp {
432    fn get_info(&self) -> ServerConfig {
433        let names: Vec<String> = self
434            .state
435            .config
436            .databases
437            .iter()
438            .map(|d| d.name.clone())
439            .collect();
440        let mut capabilities = ServerCapabilities::builder().enable_tools().build();
441        if self.resources_enabled() {
442            capabilities.resources = Some(ResourcesCapability::default());
443            capabilities.completions = Some(serde_json::Map::new());
444        }
445        ServerConfig::new(capabilities)
446            .with_server_info(Implementation::new(
447                "postgres-mcp",
448                env!("CARGO_PKG_VERSION"),
449            ))
450            .with_instructions(text::server_instructions(&names))
451    }
452
453    async fn list_resources(
454        &self,
455        _request: Option<PaginatedRequestParams>,
456        _context: RequestContext<RoleServer>,
457    ) -> Result<ListResourcesResult, McpError> {
458        if !self.resources_enabled() {
459            return Err(McpError::method_not_found::<ListResourcesRequestMethod>());
460        }
461        Ok(resources::list(&self.state))
462    }
463
464    async fn list_resource_templates(
465        &self,
466        _request: Option<PaginatedRequestParams>,
467        _context: RequestContext<RoleServer>,
468    ) -> Result<ListResourceTemplatesResult, McpError> {
469        if !self.resources_enabled() {
470            return Err(McpError::method_not_found::<
471                ListResourceTemplatesRequestMethod,
472            >());
473        }
474        Ok(resources::templates())
475    }
476
477    async fn read_resource(
478        &self,
479        request: ReadResourceRequestParams,
480        context: RequestContext<RoleServer>,
481    ) -> Result<ReadResourceResponse, McpError> {
482        if !self.resources_enabled() {
483            return Err(McpError::method_not_found::<ReadResourceRequestMethod>());
484        }
485        scrub::counted(resources::read(&self.state, &request.uri, &context.ct))
486            .await
487            .0
488            .map(ReadResourceResponse::from)
489    }
490
491    async fn complete(
492        &self,
493        request: CompleteRequestParams,
494        context: RequestContext<RoleServer>,
495    ) -> Result<CompleteResult, McpError> {
496        if !self.resources_enabled() {
497            return Err(McpError::method_not_found::<CompleteRequestMethod>());
498        }
499        let started = Instant::now();
500        let (result, redacted_hashes) = scrub::counted(async {
501            let result = resources::complete(&self.state, request, &context.ct).await;
502            scrub_completion(result)
503        })
504        .await;
505        audit::record(
506            self.state.config.audit_log,
507            &audit::Record {
508                tool: "completion",
509                database: None,
510                ok: true,
511                duration: started.elapsed(),
512                rows: None,
513                sqlstate: None,
514                sql: None,
515                redacted_hashes,
516            },
517        );
518        if redacted_hashes > 0 {
519            tracing::warn!(
520                tool = "completion",
521                count = redacted_hashes,
522                "redaction markers are present in a result"
523            );
524        }
525        Ok(result)
526    }
527
528    async fn list_tools(
529        &self,
530        _request: Option<PaginatedRequestParams>,
531        _context: RequestContext<RoleServer>,
532    ) -> Result<ListToolsResult, McpError> {
533        Ok(ListToolsResult::with_all_items(self.tools.as_ref().clone()))
534    }
535
536    async fn call_tool(
537        &self,
538        request: CallToolRequestParams,
539        context: RequestContext<RoleServer>,
540    ) -> Result<CallToolResponse, McpError> {
541        let name = request.name.to_string();
542        if !self.tools.iter().any(|t| t.name.as_ref() == name) {
543            return Err(McpError::invalid_params(
544                scrub::scrub(&format!("unknown tool: {name}")).into_owned(),
545                None,
546            ));
547        }
548        let args = Value::Object(request.arguments.unwrap_or_default());
549        let started = Instant::now();
550        let (run, redacted_hashes) =
551            scrub::counted(self.run_tool(&name, args, context.ct.clone())).await;
552        let run = run?;
553        audit::record(
554            self.state.config.audit_log,
555            &audit::Record {
556                tool: &name,
557                database: run.database.as_deref(),
558                ok: run.ok,
559                duration: started.elapsed(),
560                rows: run.rows,
561                sqlstate: run.sqlstate.as_deref(),
562                sql: run.sql.as_deref(),
563                redacted_hashes,
564            },
565        );
566        if redacted_hashes > 0 {
567            tracing::warn!(
568                tool = %name,
569                database = run.database.as_deref(),
570                count = redacted_hashes,
571                "redaction markers are present in a result"
572            );
573        }
574        Ok(CallToolResponse::from(run.result))
575    }
576}
577
578/// The keys whose text the tool masked before its own cut or filter, so the final pass leaves them alone.
579fn pre_masked(tool: &str) -> &'static [&'static str] {
580    match tool {
581        "list_activity" | "query_stats" => &["query"],
582        "read_server_log" => &["message", "detail", "statement", "context"],
583        _ => &[],
584    }
585}
586
587/// The keys of statement text, which also lose a hash cut short at their end.
588fn statement_text(tool: &str) -> &'static [&'static str] {
589    match tool {
590        "list_activity" | "query_stats" => &["query"],
591        _ => &[],
592    }
593}
594
595/// What the audit line and the client need from one tool call.
596struct ToolRun {
597    result: CallToolResult,
598    ok: bool,
599    database: Option<String>,
600    rows: Option<usize>,
601    sqlstate: Option<String>,
602    sql: Option<String>,
603}
604
605impl PgMcp {
606    /// Runs one tool and builds its scrubbed result. Its replacements are counted by the call that wraps it.
607    async fn run_tool(
608        &self,
609        name: &str,
610        args: Value,
611        ct: CancellationToken,
612    ) -> Result<ToolRun, McpError> {
613        let state = &self.state;
614        let call = match name {
615            "list_databases" => {
616                let _: core::NoArgs = parse_args(args)?;
617                core::list_databases(state.clone(), &ct).await
618            }
619            "execute_query" => core::execute_query(state, parse_args(args)?, &ct).await,
620            "explain_query" => core::explain_query(state, parse_args(args)?, &ct).await,
621            "server_info" => core::server_info(state, parse_args(args)?, &ct).await,
622            _ => {
623                let routed = match schema::dispatch(state, name, args.clone(), &ct).await {
624                    Some(call) => Some(call),
625                    None => match monitor::dispatch(state, name, args.clone(), &ct).await {
626                        Some(call) => Some(call),
627                        None => match logs::dispatch(state, name, args.clone(), &ct).await {
628                            Some(call) => Some(call),
629                            None => timescale::dispatch(state, name, args, &ct).await,
630                        },
631                    },
632                };
633                match routed {
634                    Some(call) => call?,
635                    None => {
636                        return Err(McpError::invalid_params(
637                            scrub::scrub(&format!("unknown tool: {name}")).into_owned(),
638                            None,
639                        ));
640                    }
641                }
642            }
643        };
644        let ok = call.result.is_ok();
645        let sqlstate = call
646            .result
647            .as_ref()
648            .err()
649            .and_then(ToolError::sqlstate)
650            .map(str::to_owned);
651        let result = match call.result {
652            Ok(value) => {
653                let value = scrubbed(value, name);
654                success(name, value)
655            }
656            Err(error) => {
657                let text = error.message();
658                let (message, count) = scrub::scrub_counting(&text);
659                scrub::record(count);
660                CallToolResult::error(vec![ContentBlock::text(message.into_owned())])
661            }
662        };
663        Ok(ToolRun {
664            result,
665            ok,
666            database: call.database,
667            rows: call.rows,
668            sqlstate,
669            sql: call.sql,
670        })
671    }
672}