Skip to main content

database_mcp_mysql/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::common::schema_for_empty_input;
10use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
11use rmcp::model::{ErrorData, JsonObject, ToolAnnotations};
12
13use crate::MysqlHandler;
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 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.
21
22<usecase>
23ALWAYS call this tool FIRST when:
24- You need to explore what databases exist on the server
25- You need a database name for list_tables, get_table_schema, or query tools
26- The user asks what data is available
27</usecase>
28
29<examples>
30✓ "What databases are on this server?"
31✓ "Show me what's available" → call list_databases first
32</examples>
33
34<what_it_returns>
35A sorted JSON array of database name strings.
36</what_it_returns>"#;
37}
38
39impl ToolBase for ListDatabasesTool {
40    type Parameter = ();
41    type Output = ListDatabasesResponse;
42    type Error = ErrorData;
43
44    fn name() -> Cow<'static, str> {
45        Self::NAME.into()
46    }
47
48    fn description() -> Option<Cow<'static, str>> {
49        Some(Self::DESCRIPTION.into())
50    }
51
52    fn input_schema() -> Option<Arc<JsonObject>> {
53        Some(schema_for_empty_input())
54    }
55
56    fn annotations() -> Option<ToolAnnotations> {
57        Some(
58            ToolAnnotations::new()
59                .read_only(true)
60                .destructive(false)
61                .idempotent(true)
62                .open_world(false),
63        )
64    }
65}
66
67impl AsyncTool<MysqlHandler> for ListDatabasesTool {
68    async fn invoke(handler: &MysqlHandler, _params: Self::Parameter) -> Result<Self::Output, Self::Error> {
69        Ok(handler.list_databases().await?)
70    }
71}
72
73impl MysqlHandler {
74    /// Lists all accessible databases.
75    ///
76    /// # Errors
77    ///
78    /// Returns [`AppError`] if the query fails.
79    pub async fn list_databases(&self) -> Result<ListDatabasesResponse, AppError> {
80        let sql = "SELECT SCHEMA_NAME AS name FROM information_schema.SCHEMATA ORDER BY SCHEMA_NAME";
81        let rows = self.connection.fetch(sql, None).await?;
82        Ok(ListDatabasesResponse {
83            databases: rows
84                .iter()
85                .filter_map(|row| row.get("name").and_then(|v| v.as_str().map(String::from)))
86                .collect(),
87        })
88    }
89}