Skip to main content

database_mcp_sqlite/tools/
list_tables.rs

1//! MCP tool: `list_tables`.
2
3use std::borrow::Cow;
4use std::sync::Arc;
5
6use database_mcp_server::AppError;
7use database_mcp_server::types::ListTablesResponse;
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::SqliteHandler;
14
15/// Marker type for the `list_tables` MCP tool.
16pub(crate) struct ListTablesTool;
17
18impl ListTablesTool {
19    const NAME: &'static str = "list_tables";
20    const TITLE: &'static str = "List Tables";
21    const DESCRIPTION: &'static str = r#"List all tables in the connected SQLite database. Use this tool to discover what tables are available before using other tools.
22
23<usecase>
24ALWAYS call this tool FIRST when:
25- You need to explore what tables exist in the database
26- You need a table name for get_table_schema or query tools
27- The user asks what data is available
28</usecase>
29
30<examples>
31✓ "What tables are in this database?"
32✓ "Does a users table exist?" → list_tables to check
33✗ "Show me the columns of users" → use get_table_schema instead
34</examples>
35
36<what_it_returns>
37A sorted JSON array of table name strings.
38</what_it_returns>"#;
39}
40
41impl ToolBase for ListTablesTool {
42    type Parameter = ();
43    type Output = ListTablesResponse;
44    type Error = ErrorData;
45
46    fn name() -> Cow<'static, str> {
47        Self::NAME.into()
48    }
49
50    fn title() -> Option<String> {
51        Some(Self::TITLE.into())
52    }
53
54    fn description() -> Option<Cow<'static, str>> {
55        Some(Self::DESCRIPTION.into())
56    }
57
58    fn input_schema() -> Option<Arc<JsonObject>> {
59        None
60    }
61
62    fn annotations() -> Option<ToolAnnotations> {
63        Some(
64            ToolAnnotations::new()
65                .read_only(true)
66                .destructive(false)
67                .idempotent(true)
68                .open_world(false),
69        )
70    }
71}
72
73impl AsyncTool<SqliteHandler> for ListTablesTool {
74    async fn invoke(handler: &SqliteHandler, _params: Self::Parameter) -> Result<Self::Output, Self::Error> {
75        Ok(handler.list_tables().await?)
76    }
77}
78
79impl SqliteHandler {
80    /// Lists all tables in the connected database.
81    ///
82    /// # Errors
83    ///
84    /// Returns [`AppError`] if the query fails.
85    pub async fn list_tables(&self) -> Result<ListTablesResponse, AppError> {
86        let sql = "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name";
87        let rows = self.connection.fetch(sql, None).await?;
88        let tables = rows
89            .iter()
90            .filter_map(|row| row.get("name").and_then(Value::as_str).map(str::to_owned))
91            .collect::<Vec<_>>();
92        Ok(ListTablesResponse { tables })
93    }
94}