Skip to main content

dbmcp_postgres/tools/
list_materialized_views.rs

1//! MCP tool: `listMaterializedViews`.
2
3use std::borrow::Cow;
4
5use dbmcp_server::pagination::Pager;
6use dbmcp_server::types::{ListMaterializedViewsRequest, ListMaterializedViewsResponse};
7use dbmcp_sql::Connection as _;
8use dbmcp_sql::sanitize::validate_ident;
9use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
10use rmcp::model::{ErrorData, ToolAnnotations};
11
12use crate::PostgresHandler;
13
14/// Marker type for the `listMaterializedViews` MCP tool.
15pub(crate) struct ListMaterializedViewsTool;
16
17impl ListMaterializedViewsTool {
18    const NAME: &'static str = "listMaterializedViews";
19    const TITLE: &'static str = "List Materialized Views";
20    const DESCRIPTION: &'static str = r#"List all materialized views in the `public` schema of a PostgreSQL database. Unlike regular views, materialized views store their results physically and must be refreshed explicitly.
21
22<usecase>
23Use when:
24- Exploring a database for stored aggregates that may be stale
25- Auditing which materialized views require refresh scheduling
26- The user asks what materialized views exist
27</usecase>
28
29<examples>
30✓ "What materialized views are in mydb?" → listMaterializedViews(database="mydb")
31✓ "Does an mv_recent_orders materialized view exist?" → listMaterializedViews to check
32✗ "List regular views" → use listViews instead
33</examples>
34
35<what_it_returns>
36A sorted JSON array of materialized-view name strings.
37</what_it_returns>
38
39<pagination>
40Paginated. Pass the prior response's `nextCursor` as `cursor` to fetch the next page.
41</pagination>"#;
42}
43
44impl ToolBase for ListMaterializedViewsTool {
45    type Parameter = ListMaterializedViewsRequest;
46    type Output = ListMaterializedViewsResponse;
47    type Error = ErrorData;
48
49    fn name() -> Cow<'static, str> {
50        Self::NAME.into()
51    }
52
53    fn title() -> Option<String> {
54        Some(Self::TITLE.into())
55    }
56
57    fn description() -> Option<Cow<'static, str>> {
58        Some(Self::DESCRIPTION.into())
59    }
60
61    fn annotations() -> Option<ToolAnnotations> {
62        Some(
63            ToolAnnotations::new()
64                .read_only(true)
65                .destructive(false)
66                .idempotent(true)
67                .open_world(false),
68        )
69    }
70}
71
72impl AsyncTool<PostgresHandler> for ListMaterializedViewsTool {
73    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
74        handler.list_materialized_views(params).await
75    }
76}
77
78impl PostgresHandler {
79    /// Lists one page of materialized views in the `public` schema.
80    ///
81    /// # Errors
82    ///
83    /// Returns [`ErrorData`] with code `-32602` if `cursor` is malformed,
84    /// or an internal-error [`ErrorData`] if `database` is invalid
85    /// or the underlying query fails.
86    pub async fn list_materialized_views(
87        &self,
88        ListMaterializedViewsRequest { database, cursor }: ListMaterializedViewsRequest,
89    ) -> Result<ListMaterializedViewsResponse, ErrorData> {
90        let database = database
91            .as_deref()
92            .map(str::trim)
93            .filter(|s| !s.is_empty())
94            .map(validate_ident)
95            .transpose()?;
96
97        let pager = Pager::new(cursor, self.config.page_size);
98        let query = format!(
99            r"
100            SELECT matviewname
101            FROM pg_matviews
102            WHERE schemaname = 'public'
103            ORDER BY matviewname
104            LIMIT {} OFFSET {}",
105            pager.limit(),
106            pager.offset(),
107        );
108
109        let rows: Vec<String> = self.connection.fetch_scalar(query.as_str(), database).await?;
110        let (materialized_views, next_cursor) = pager.finalize(rows);
111
112        Ok(ListMaterializedViewsResponse {
113            materialized_views,
114            next_cursor,
115        })
116    }
117}