database_mcp_postgres/tools/
list_databases.rs1use std::borrow::Cow;
4use std::sync::Arc;
5
6use database_mcp_server::AppError;
7use database_mcp_server::types::ListDatabasesResponse;
8use database_mcp_sql::timeout::execute_with_timeout;
9use rmcp::handler::server::common::schema_for_empty_input;
10use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
11use rmcp::model::{ErrorData, JsonObject, ToolAnnotations};
12
13use crate::PostgresHandler;
14
15pub(crate) struct ListDatabasesTool;
17
18impl ListDatabasesTool {
19 const NAME: &'static str = "list_databases";
20 const DESCRIPTION: &'static str = "List all accessible databases on the connected database server.\nCall this first to discover available database names.";
21}
22
23impl ToolBase for ListDatabasesTool {
24 type Parameter = ();
25 type Output = ListDatabasesResponse;
26 type Error = ErrorData;
27
28 fn name() -> Cow<'static, str> {
29 Self::NAME.into()
30 }
31
32 fn description() -> Option<Cow<'static, str>> {
33 Some(Self::DESCRIPTION.into())
34 }
35
36 fn input_schema() -> Option<Arc<JsonObject>> {
37 Some(schema_for_empty_input())
38 }
39
40 fn annotations() -> Option<ToolAnnotations> {
41 Some(
42 ToolAnnotations::new()
43 .read_only(true)
44 .destructive(false)
45 .idempotent(true)
46 .open_world(false),
47 )
48 }
49}
50
51impl AsyncTool<PostgresHandler> for ListDatabasesTool {
52 async fn invoke(handler: &PostgresHandler, _params: Self::Parameter) -> Result<Self::Output, Self::Error> {
53 Ok(handler.list_databases().await?)
54 }
55}
56
57impl PostgresHandler {
58 pub async fn list_databases(&self) -> Result<ListDatabasesResponse, AppError> {
68 let pool = self.get_pool(None).await?;
69 let sql = "SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname";
70 let rows: Vec<(String,)> =
71 execute_with_timeout(self.config.query_timeout, sql, sqlx::query_as(sql).fetch_all(&pool)).await?;
72 Ok(ListDatabasesResponse {
73 databases: rows.into_iter().map(|r| r.0).collect(),
74 })
75 }
76}