dbmcp_postgres/tools/
list_views.rs1use 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
13pub(crate) struct ListViewsTool;
15
16impl ListViewsTool {
17 const NAME: &'static str = "listViews";
18 const TITLE: &'static str = "List Views";
19 const DESCRIPTION: &'static str = r#"List user-defined views in the `public` schema, optionally filtered and/or with full metadata. Materialized views and system-schema views are excluded.
20
21<usecase>
22Use when:
23- Auditing views across a database (brief mode, default).
24- Searching for a view by partial name (pass `search`).
25- Inspecting a view's owner, comment, and full SELECT body before querying it (pass `detailed: true`). Detailed mode supersedes ad-hoc `readQuery` against `pg_views` / `pg_class`.
26</usecase>
27
28<parameters>
29- `database` — Database to target. Defaults to the active database.
30- `cursor` — Opaque pagination cursor; echo the prior response's `nextCursor`.
31- `search` — Case-insensitive filter on view names via `ILIKE`. `%` matches any sequence; `_` matches a single character.
32- `detailed` — When `true`, returns full metadata objects keyed by bare view name instead of bare name strings. Default `false`.
33</parameters>
34
35<examples>
36✓ "What views are in mydb?" → listViews(database="mydb")
37✓ "Find the active-users view" → listViews(search="active")
38✓ "What does active_users select?" → listViews(search="active_users", detailed=true)
39✗ "Show me the columns of a view" → use listTables with `detailed: true` instead
40✗ "List materialized views" → use listMaterializedViews
41</examples>
42
43<what_it_returns>
44Brief mode (default): a sorted JSON array of view-name strings, e.g. `["active_orders", "active_users"]`. View names are unique per schema, so no duplicates appear.
45Detailed mode: a JSON object keyed by bare view name; each value carries `schema`, `owner`, `description` (or null when no `COMMENT ON VIEW`), and `definition` (the SELECT body verbatim from `pg_views.definition`, with no `CREATE VIEW` wrapper). The view name is the map key only — it is not repeated inside the value.
46
47Detailed mode deliberately omits column metadata (`columns`), the `name` field (already the key), and view-level options (`security_barrier`, `security_invoker`, `WITH CHECK OPTION`). Column shape is recoverable from the `definition` text or via `listTables(detailed=true)` since Postgres exposes views in `pg_class`.
48</what_it_returns>
49
50<pagination>
51Paginated. Pass the prior response's `nextCursor` as `cursor` to fetch the next page. The `search` filter must stay the same across pages for cursor continuity. Brief and detailed modes share the same `viewname` row order, so a client can switch `detailed` between pages without losing position.
52</pagination>"#;
53}
54
55impl ToolBase for ListViewsTool {
56 type Parameter = ListViewsRequest;
57 type Output = ListViewsResponse;
58 type Error = ErrorData;
59
60 fn name() -> Cow<'static, str> {
61 Self::NAME.into()
62 }
63
64 fn title() -> Option<String> {
65 Some(Self::TITLE.into())
66 }
67
68 fn description() -> Option<Cow<'static, str>> {
69 Some(Self::DESCRIPTION.into())
70 }
71
72 fn annotations() -> Option<ToolAnnotations> {
73 Some(
74 ToolAnnotations::new()
75 .read_only(true)
76 .destructive(false)
77 .idempotent(true)
78 .open_world(false),
79 )
80 }
81}
82
83impl AsyncTool<PostgresHandler> for ListViewsTool {
84 async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
85 handler.list_views(params).await
86 }
87}
88
89const BRIEF_SQL: &str = r"
97 SELECT viewname
98 FROM pg_views
99 WHERE schemaname = 'public'
100 AND ($1::text IS NULL OR viewname ILIKE '%' || $1 || '%')
101 ORDER BY viewname
102 LIMIT $2 OFFSET $3";
103
104const DETAILED_SQL: &str = r"
113 SELECT
114 v.viewname AS name,
115 json_build_object(
116 'schema', v.schemaname,
117 'owner', v.viewowner,
118 'description', pg_catalog.obj_description(c.oid, 'pg_class'),
119 'definition', v.definition
120 ) AS entry
121 FROM pg_views v
122 JOIN pg_namespace n ON n.nspname = v.schemaname
123 JOIN pg_class c ON c.relname = v.viewname AND c.relnamespace = n.oid
124 WHERE v.schemaname = 'public'
125 AND ($1::text IS NULL OR v.viewname ILIKE '%' || $1 || '%')
126 ORDER BY v.viewname
127 LIMIT $2 OFFSET $3";
128
129impl PostgresHandler {
130 pub async fn list_views(
138 &self,
139 ListViewsRequest {
140 database,
141 cursor,
142 search,
143 detailed,
144 }: ListViewsRequest,
145 ) -> Result<ListViewsResponse, ErrorData> {
146 let database = database.as_deref().map(str::trim).filter(|s| !s.is_empty());
147 let pattern = search.as_deref().map(str::trim).filter(|s| !s.is_empty());
148 let pager = Pager::new(cursor, self.config.page_size);
149
150 if detailed {
151 let rows: Vec<(String, sqlx::types::Json<serde_json::Value>)> = self
152 .connection
153 .fetch(
154 sqlx::query(DETAILED_SQL)
155 .bind(pattern)
156 .bind(pager.limit())
157 .bind(pager.offset()),
158 database,
159 )
160 .await?;
161 let (rows, next_cursor) = pager.paginate(rows);
162 return Ok(ListViewsResponse::detailed(
163 rows.into_iter().map(|(key, json)| (key, json.0)).collect(),
164 next_cursor,
165 ));
166 }
167
168 let rows: Vec<String> = self
169 .connection
170 .fetch_scalar(
171 sqlx::query(BRIEF_SQL)
172 .bind(pattern)
173 .bind(pager.limit())
174 .bind(pager.offset()),
175 database,
176 )
177 .await?;
178 let (views, next_cursor) = pager.paginate(rows);
179 Ok(ListViewsResponse::brief(views, next_cursor))
180 }
181}