Skip to main content

database_mcp_postgres/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 rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
9use rmcp::model::{ErrorData, ToolAnnotations};
10use serde_json::Value;
11
12use crate::PostgresHandler;
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 TITLE: &'static str = "List Tables";
20    const DESCRIPTION: &'static str = r#"List all tables in a specific database. Requires `database_name` — call `list_databases` first to discover available databases.
21
22<usecase>
23Use when:
24- Exploring a database to find relevant tables
25- Verifying a table exists before querying or inspecting it
26- The user asks what tables are in a database
27</usecase>
28
29<examples>
30✓ "What tables are in the mydb database?" → list_tables(database_name="mydb")
31✓ "Does a users table exist?" → list_tables to check
32✗ "Show me the columns of users" → use get_table_schema instead
33</examples>
34
35<what_it_returns>
36A sorted JSON array of table name strings.
37</what_it_returns>"#;
38}
39
40impl ToolBase for ListTablesTool {
41    type Parameter = ListTablesRequest;
42    type Output = ListTablesResponse;
43    type Error = ErrorData;
44
45    fn name() -> Cow<'static, str> {
46        Self::NAME.into()
47    }
48
49    fn title() -> Option<String> {
50        Some(Self::TITLE.into())
51    }
52
53    fn description() -> Option<Cow<'static, str>> {
54        Some(Self::DESCRIPTION.into())
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 ListTablesTool {
69    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
70        Ok(handler.list_tables(&params).await?)
71    }
72}
73
74impl PostgresHandler {
75    /// Lists all tables in a database.
76    ///
77    /// # Errors
78    ///
79    /// Returns [`AppError`] if the identifier is invalid or the query fails.
80    pub async fn list_tables(&self, request: &ListTablesRequest) -> Result<ListTablesResponse, AppError> {
81        let db = if request.database_name.is_empty() {
82            None
83        } else {
84            Some(request.database_name.as_str())
85        };
86        let sql = "SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename";
87        let rows = self.connection.fetch(sql, db).await?;
88        Ok(ListTablesResponse {
89            tables: rows
90                .iter()
91                .filter_map(|r| r.get("tablename").and_then(Value::as_str).map(str::to_owned))
92                .collect(),
93        })
94    }
95}