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::Connection as _;
9use rmcp::handler::server::common::schema_for_empty_input;
10use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
11use rmcp::model::{ErrorData, JsonObject, ToolAnnotations};
12use serde_json::Value;
13
14use crate::PostgresHandler;
15
16pub(crate) struct ListDatabasesTool;
18
19impl ListDatabasesTool {
20 const NAME: &'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 description() -> Option<Cow<'static, str>> {
50 Some(Self::DESCRIPTION.into())
51 }
52
53 fn input_schema() -> Option<Arc<JsonObject>> {
54 Some(schema_for_empty_input())
55 }
56
57 fn annotations() -> Option<ToolAnnotations> {
58 Some(
59 ToolAnnotations::new()
60 .read_only(true)
61 .destructive(false)
62 .idempotent(true)
63 .open_world(false),
64 )
65 }
66}
67
68impl AsyncTool<PostgresHandler> for ListDatabasesTool {
69 async fn invoke(handler: &PostgresHandler, _params: Self::Parameter) -> Result<Self::Output, Self::Error> {
70 Ok(handler.list_databases().await?)
71 }
72}
73
74impl PostgresHandler {
75 pub async fn list_databases(&self) -> Result<ListDatabasesResponse, AppError> {
85 let sql = "SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname";
86 let rows = self.connection.fetch(sql, None).await?;
87 Ok(ListDatabasesResponse {
88 databases: rows
89 .iter()
90 .filter_map(|r| r.get("datname").and_then(Value::as_str).map(str::to_owned))
91 .collect(),
92 })
93 }
94}