Skip to main content

database_mcp_sqlite/tools/
list_tables.rs

1//! MCP tool: `listTables`.
2
3use std::borrow::Cow;
4use std::sync::Arc;
5
6use database_mcp_server::pagination::Pager;
7use database_mcp_server::types::ListTablesResponse;
8
9use database_mcp_sql::Connection as _;
10use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
11use rmcp::model::{ErrorData, JsonObject, ToolAnnotations};
12
13use crate::SqliteHandler;
14use crate::types::ListTablesRequest;
15
16/// Marker type for the `listTables` MCP tool.
17pub(crate) struct ListTablesTool;
18
19impl ListTablesTool {
20    const NAME: &'static str = "listTables";
21    const TITLE: &'static str = "List Tables";
22    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.
23
24<usecase>
25ALWAYS call this tool FIRST when:
26- You need to explore what tables exist in the database
27- You need a table name for getTableSchema or query tools
28- The user asks what data is available
29</usecase>
30
31<examples>
32✓ "What tables are in this database?"
33✓ "Does a users table exist?" → listTables to check
34✗ "Show me the columns of users" → use getTableSchema instead
35</examples>
36
37<what_it_returns>
38A sorted JSON array of table name strings.
39</what_it_returns>
40
41<pagination>
42Paginated. Pass the prior response's `nextCursor` as `cursor` to fetch the next page.
43</pagination>"#;
44}
45
46impl ToolBase for ListTablesTool {
47    type Parameter = ListTablesRequest;
48    type Output = ListTablesResponse;
49    type Error = ErrorData;
50
51    fn name() -> Cow<'static, str> {
52        Self::NAME.into()
53    }
54
55    fn title() -> Option<String> {
56        Some(Self::TITLE.into())
57    }
58
59    fn description() -> Option<Cow<'static, str>> {
60        Some(Self::DESCRIPTION.into())
61    }
62
63    fn input_schema() -> Option<Arc<JsonObject>> {
64        None
65    }
66
67    fn annotations() -> Option<ToolAnnotations> {
68        Some(
69            ToolAnnotations::new()
70                .read_only(true)
71                .destructive(false)
72                .idempotent(true)
73                .open_world(false),
74        )
75    }
76}
77
78impl AsyncTool<SqliteHandler> for ListTablesTool {
79    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
80        handler.list_tables(params).await
81    }
82}
83
84impl SqliteHandler {
85    /// Lists one page of tables in the connected database.
86    ///
87    /// # Errors
88    ///
89    /// Returns [`ErrorData`] with code `-32602` if `cursor` is malformed,
90    /// or an internal-error [`ErrorData`] if the underlying query fails.
91    pub async fn list_tables(
92        &self,
93        ListTablesRequest { cursor }: ListTablesRequest,
94    ) -> Result<ListTablesResponse, ErrorData> {
95        let pager = Pager::new(cursor, self.config.page_size);
96        let query = format!(
97            r"
98            SELECT name
99            FROM sqlite_master
100            WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
101            ORDER BY name
102            LIMIT {} OFFSET {}",
103            pager.limit(),
104            pager.offset(),
105        );
106
107        let rows: Vec<String> = self.connection.fetch_scalar(query.as_str(), None).await?;
108        let (tables, next_cursor) = pager.finalize(rows);
109
110        Ok(ListTablesResponse { tables, next_cursor })
111    }
112}