Skip to main content

database_mcp_mysql/tools/
list_tables.rs

1//! MCP tool: `list_tables`.
2
3use std::borrow::Cow;
4
5use database_mcp_server::AppError;
6use database_mcp_server::types::{ListTablesRequest, ListTablesResponse};
7use database_mcp_sql::Connection as _;
8use database_mcp_sql::identifier::validate_identifier;
9use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
10use rmcp::model::{ErrorData, ToolAnnotations};
11
12use crate::MysqlHandler;
13
14/// Marker type for the `list_tables` MCP tool.
15pub(crate) struct ListTablesTool;
16
17impl ListTablesTool {
18    const NAME: &'static str = "list_tables";
19    const DESCRIPTION: &'static str = r#"List all tables in a specific database. Requires `database_name` — call `list_databases` first to discover available databases.
20
21<usecase>
22Use when:
23- Exploring a database to find relevant tables
24- Verifying a table exists before querying or inspecting it
25- The user asks what tables are in a database
26</usecase>
27
28<examples>
29✓ "What tables are in the mydb database?" → list_tables(database_name="mydb")
30✓ "Does a users table exist?" → list_tables to check
31✗ "Show me the columns of users" → use get_table_schema instead
32</examples>
33
34<what_it_returns>
35A sorted JSON array of table name strings.
36</what_it_returns>"#;
37}
38
39impl ToolBase for ListTablesTool {
40    type Parameter = ListTablesRequest;
41    type Output = ListTablesResponse;
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 annotations() -> Option<ToolAnnotations> {
53        Some(
54            ToolAnnotations::new()
55                .read_only(true)
56                .destructive(false)
57                .idempotent(true)
58                .open_world(false),
59        )
60    }
61}
62
63impl AsyncTool<MysqlHandler> for ListTablesTool {
64    async fn invoke(handler: &MysqlHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
65        Ok(handler.list_tables(&params).await?)
66    }
67}
68
69impl MysqlHandler {
70    /// Lists all tables in a database.
71    ///
72    /// # Errors
73    ///
74    /// Returns [`AppError`] if the identifier is invalid or the query fails.
75    pub async fn list_tables(&self, request: &ListTablesRequest) -> Result<ListTablesResponse, AppError> {
76        validate_identifier(&request.database_name)?;
77        let sql = format!(
78            "SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = {} ORDER BY TABLE_NAME",
79            self.connection.quote_string(&request.database_name)
80        );
81        let rows = self.connection.fetch(sql.as_str(), None).await?;
82        Ok(ListTablesResponse {
83            tables: rows
84                .iter()
85                .filter_map(|row| row.get("name").and_then(|v| v.as_str().map(String::from)))
86                .collect(),
87        })
88    }
89}