Skip to main content

dbmcp_postgres/tools/
list_procedures.rs

1//! MCP tool: `listProcedures`.
2
3use std::borrow::Cow;
4
5use dbmcp_server::pagination::Pager;
6use dbmcp_server::types::{ListProceduresRequest, ListProceduresResponse};
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 `listProcedures` MCP tool.
15pub(crate) struct ListProceduresTool;
16
17impl ListProceduresTool {
18    const NAME: &'static str = "listProcedures";
19    const TITLE: &'static str = "List Procedures";
20    const DESCRIPTION: &'static str = r#"List all user-defined procedures in the `public` schema of a database (PostgreSQL 11+).
21
22<usecase>
23Use when:
24- Exploring a database's stored logic
25- Verifying a procedure exists before calling it
26- The user asks what procedures are defined
27</usecase>
28
29<examples>
30✓ "What procedures are in the mydb database?" → listProcedures(database="mydb")
31✓ "Does an archive_user procedure exist?" → listProcedures to check
32✗ "List functions" → use listFunctions instead
33</examples>
34
35<what_it_returns>
36A sorted JSON array of procedure 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 ListProceduresTool {
45    type Parameter = ListProceduresRequest;
46    type Output = ListProceduresResponse;
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 ListProceduresTool {
73    async fn invoke(handler: &PostgresHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
74        handler.list_procedures(params).await
75    }
76}
77
78impl PostgresHandler {
79    /// Lists one page of user-defined procedures 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_procedures(
87        &self,
88        ListProceduresRequest { database, cursor }: ListProceduresRequest,
89    ) -> Result<ListProceduresResponse, 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 p.proname
101            FROM pg_proc p
102            JOIN pg_namespace n ON p.pronamespace = n.oid
103            WHERE n.nspname = 'public' AND p.prokind = 'p'
104            ORDER BY p.proname
105            LIMIT {} OFFSET {}",
106            pager.limit(),
107            pager.offset(),
108        );
109
110        let rows: Vec<String> = self.connection.fetch_scalar(query.as_str(), database).await?;
111        let (procedures, next_cursor) = pager.finalize(rows);
112
113        Ok(ListProceduresResponse {
114            procedures,
115            next_cursor,
116        })
117    }
118}