Skip to main content

dbmcp_postgres/tools/
list_views.rs

1//! MCP tool: `listViews`.
2
3use std::borrow::Cow;
4
5use dbmcp_server::pagination::Pager;
6use dbmcp_sql::Connection as _;
7use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
8use rmcp::model::{ErrorData, ToolAnnotations};
9
10use crate::PostgresHandler;
11use crate::types::{ListViewsRequest, ListViewsResponse};
12
13/// Marker type for the `listViews` MCP tool.
14pub(crate) struct ListViewsTool;
15
16impl ListViewsTool {
17    const NAME: &'static str = "listViews";
18    const TITLE: &'static str = "List Views";
19    const DESCRIPTION: &'static str = include_str!("../../assets/tools/list_views.md");
20}
21
22impl ToolBase for ListViewsTool {
23    type Parameter = ListViewsRequest;
24    type Output = ListViewsResponse;
25    type Error = ErrorData;
26
27    fn name() -> Cow<'static, str> {
28        Self::NAME.into()
29    }
30
31    fn title() -> Option<String> {
32        Some(Self::TITLE.into())
33    }
34
35    fn description() -> Option<Cow<'static, str>> {
36        Some(Self::DESCRIPTION.into())
37    }
38
39    fn annotations() -> Option<ToolAnnotations> {
40        Some(
41            ToolAnnotations::new()
42                .read_only(true)
43                .destructive(false)
44                .idempotent(true)
45                .open_world(false),
46        )
47    }
48}
49
50impl AsyncTool<PostgresHandler> for ListViewsTool {
51    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
52        handler.list_views(params).await
53    }
54}
55
56/// Brief-mode SQL: `pg_views` scan with `ILIKE` filter on view name.
57///
58/// `pg_views` already excludes materialized views (those live in `pg_matviews`),
59/// and `schemaname = 'public'` keeps system-schema views out. The
60/// `($1::text IS NULL OR ...)` trinary lets one statement cover both filtered
61/// and unfiltered cases. View names are unique per schema (Postgres enforces
62/// this), so `viewname` alone is a stable sort key — no tiebreaker needed.
63const BRIEF_SQL: &str = r"
64    SELECT viewname
65    FROM pg_views
66    WHERE schemaname = 'public'
67      AND ($1::text IS NULL OR viewname ILIKE '%' || $1 || '%')
68    ORDER BY viewname
69    LIMIT $2 OFFSET $3";
70
71/// Detailed-mode SQL: per-view `json_build_object` projection.
72///
73/// `pg_views` excludes materialized views. The `pg_namespace` + `pg_class`
74/// joins anchor the relation OID needed by `obj_description`. Postgres defers
75/// SELECT-list evaluation past `LIMIT`, so `obj_description` only runs for the
76/// page's rows — never the full schema. `pg_views.viewowner` is already a role
77/// name, so no `pg_roles` join is needed. View names are unique per schema, so
78/// `viewname` alone is a stable sort key.
79const DETAILED_SQL: &str = r"
80    SELECT
81        v.viewname AS name,
82        json_build_object(
83            'schema',      v.schemaname,
84            'owner',       v.viewowner,
85            'description', pg_catalog.obj_description(c.oid, 'pg_class'),
86            'definition',  v.definition
87        ) AS entry
88    FROM pg_views v
89    JOIN pg_namespace n ON n.nspname = v.schemaname
90    JOIN pg_class     c ON c.relname = v.viewname AND c.relnamespace = n.oid
91    WHERE v.schemaname = 'public'
92      AND ($1::text IS NULL OR v.viewname ILIKE '%' || $1 || '%')
93    ORDER BY v.viewname
94    LIMIT $2 OFFSET $3";
95
96impl PostgresHandler {
97    /// Lists one page of user-defined views, optionally filtered and/or detailed.
98    ///
99    /// # Errors
100    ///
101    /// Returns [`ErrorData`] with code `-32602` if `cursor` is malformed,
102    /// or an internal-error [`ErrorData`] if `database` is invalid
103    /// or the underlying query fails.
104    pub async fn list_views(
105        &self,
106        ListViewsRequest {
107            database,
108            cursor,
109            search,
110            detailed,
111        }: ListViewsRequest,
112    ) -> Result<ListViewsResponse, ErrorData> {
113        let database = database.as_deref().map(str::trim).filter(|s| !s.is_empty());
114        let pattern = search.as_deref().map(str::trim).filter(|s| !s.is_empty());
115        let pager = Pager::new(cursor, self.config.page_size);
116
117        if detailed {
118            let rows: Vec<(String, sqlx::types::Json<serde_json::Value>)> = self
119                .connection
120                .fetch(
121                    sqlx::query(DETAILED_SQL)
122                        .bind(pattern)
123                        .bind(pager.limit())
124                        .bind(pager.offset()),
125                    database,
126                )
127                .await?;
128            let (rows, next_cursor) = pager.paginate(rows);
129            return Ok(ListViewsResponse::detailed(
130                rows.into_iter().map(|(key, json)| (key, json.0)).collect(),
131                next_cursor,
132            ));
133        }
134
135        let rows: Vec<String> = self
136            .connection
137            .fetch_scalar(
138                sqlx::query(BRIEF_SQL)
139                    .bind(pattern)
140                    .bind(pager.limit())
141                    .bind(pager.offset()),
142                database,
143            )
144            .await?;
145        let (views, next_cursor) = pager.paginate(rows);
146        Ok(ListViewsResponse::brief(views, next_cursor))
147    }
148}