Skip to main content

database_mcp_postgres/tools/
list_databases.rs

1//! MCP tool: `list_databases`.
2
3use std::borrow::Cow;
4use std::sync::Arc;
5
6use database_mcp_server::AppError;
7use database_mcp_server::types::ListDatabasesResponse;
8use database_mcp_sql::Connection as _;
9use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
10use rmcp::model::{ErrorData, JsonObject, ToolAnnotations};
11use serde_json::Value;
12
13use crate::PostgresHandler;
14
15/// Marker type for the `list_databases` MCP tool.
16pub(crate) struct ListDatabasesTool;
17
18impl ListDatabasesTool {
19    const NAME: &'static str = "list_databases";
20    const TITLE: &'static str = "List Databases";
21    const DESCRIPTION: &'static str = r#"List all accessible databases on the connected server. Use this tool to discover what databases are available before using other tools.
22
23<usecase>
24ALWAYS call this tool FIRST when:
25- You need to explore what databases exist on the server
26- You need a database name for list_tables, get_table_schema, or query tools
27- The user asks what data is available
28</usecase>
29
30<examples>
31✓ "What databases are on this server?"
32✓ "Show me what's available" → call list_databases first
33</examples>
34
35<what_it_returns>
36A sorted JSON array of database name strings.
37</what_it_returns>"#;
38}
39
40impl ToolBase for ListDatabasesTool {
41    type Parameter = ();
42    type Output = ListDatabasesResponse;
43    type Error = ErrorData;
44
45    fn name() -> Cow<'static, str> {
46        Self::NAME.into()
47    }
48
49    fn title() -> Option<String> {
50        Some(Self::TITLE.into())
51    }
52
53    fn description() -> Option<Cow<'static, str>> {
54        Some(Self::DESCRIPTION.into())
55    }
56
57    fn input_schema() -> Option<Arc<JsonObject>> {
58        None
59    }
60
61    fn annotations() -> Option<ToolAnnotations> {
62        Some(
63            ToolAnnotations::new()
64                .read_only(true)
65                .destructive(false)
66                .idempotent(true)
67                .open_world(false),
68        )
69    }
70}
71
72impl AsyncTool<PostgresHandler> for ListDatabasesTool {
73    async fn invoke(handler: &PostgresHandler, _params: Self::Parameter) -> Result<Self::Output, Self::Error> {
74        Ok(handler.list_databases().await?)
75    }
76}
77
78impl PostgresHandler {
79    /// Lists all accessible databases.
80    ///
81    /// Uses the default pool intentionally — `pg_database` is a server-wide
82    /// catalog that returns all databases regardless of which database the
83    /// connection targets.
84    ///
85    /// # Errors
86    ///
87    /// Returns [`AppError`] if the query fails.
88    pub async fn list_databases(&self) -> Result<ListDatabasesResponse, AppError> {
89        let sql = "SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname";
90        let rows = self.connection.fetch(sql, None).await?;
91        Ok(ListDatabasesResponse {
92            databases: rows
93                .iter()
94                .filter_map(|r| r.get("datname").and_then(Value::as_str).map(str::to_owned))
95                .collect(),
96        })
97    }
98}