Skip to main content

dbmcp_sqlite/tools/
list_triggers.rs

1//! MCP tool: `listTriggers`.
2
3use std::borrow::Cow;
4
5use dbmcp_server::pagination::Pager;
6use dbmcp_server::types::ListTriggersResponse;
7
8use dbmcp_sql::Connection as _;
9use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
10use rmcp::model::{ErrorData, ToolAnnotations};
11
12use crate::SqliteHandler;
13use crate::types::ListTriggersRequest;
14
15/// Marker type for the `listTriggers` MCP tool.
16pub(crate) struct ListTriggersTool;
17
18impl ListTriggersTool {
19    const NAME: &'static str = "listTriggers";
20    const TITLE: &'static str = "List Triggers";
21    const DESCRIPTION: &'static str = r#"List triggers in the connected SQLite database, optionally filtered and/or with full metadata.
22
23<usecase>
24Use when:
25- Auditing trigger coverage across a database (brief mode, default).
26- Searching for a trigger by partial name (pass `search`).
27- Inspecting a trigger's table and full `CREATE TRIGGER` text before reasoning about side-effects (pass `detailed: true`). Detailed mode supersedes ad-hoc `readQuery` against `sqlite_schema`.
28</usecase>
29
30<parameters>
31- `cursor` — Opaque pagination cursor; echo the prior response's `nextCursor`.
32- `search` — Case-insensitive filter on trigger names via `LIKE` (SQLite's `LIKE` is ASCII-case-insensitive by default). `%` matches any sequence; `_` matches a single character.
33- `detailed` — When `true`, returns full metadata objects keyed by trigger name instead of bare name strings. Default `false`.
34</parameters>
35
36<examples>
37✓ "What triggers are in this database?" → listTriggers()
38✓ "Find the audit triggers" → listTriggers(search="audit")
39✓ "What does orders_audit_after_insert do?" → listTriggers(search="orders_audit_after_insert", detailed=true)
40✗ "Show me a trigger's body" → use detailed mode; the `definition` field carries the full `CREATE TRIGGER` text
41</examples>
42
43<what_it_returns>
44Brief mode (default): a sorted JSON array of trigger-name strings, e.g. `["customers_audit_after_insert", "orders_audit_after_insert"]`.
45Detailed mode: a JSON object keyed by trigger name; each value carries exactly three fields — `schema` (always `"main"`), `table` (`sqlite_schema.tbl_name` — may be a view name for `INSTEAD OF` triggers), and `definition` (the original `CREATE TRIGGER` text from `sqlite_schema.sql`, byte-for-byte). Internal `sqlite_*` triggers are excluded.
46The detailed payload deliberately diverges from the Postgres and MySQL/MariaDB `listTriggers` detailed payloads — `timing`, `events`, `activationLevel`, `status`, `functionName`, `sqlMode`, `characterSetClient`, `collationConnection`, `databaseCollation`, and `created` are absent. SQLite's catalogue does not expose those concepts as columns, and this tool deliberately avoids parsing the stored DDL to derive them; clients that need the timing or event keyword can read it off the prefix of `definition`.
47Triggers whose stored `sqlite_schema.sql` is `NULL` (rare; produced by extension-generated rows or hand-edited catalogues) are silently omitted from detailed mode but still listed by name in brief mode.
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.
52</pagination>"#;
53}
54
55impl ToolBase for ListTriggersTool {
56    type Parameter = ListTriggersRequest;
57    type Output = ListTriggersResponse;
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<SqliteHandler> for ListTriggersTool {
84    async fn invoke(handler: &SqliteHandler, params: Self::Parameter) -> Result<Self::Output, Self::Error> {
85        handler.list_triggers(params).await
86    }
87}
88
89/// Brief-mode SQL: name-only column with optional case-insensitive `LIKE` filter.
90///
91/// `SQLite`'s `LIKE` operator is case-insensitive for ASCII by default and
92/// `dbmcp` does not toggle the `case_sensitive_like` PRAGMA, so a bare
93/// `LIKE` already matches case-insensitively. (A `COLLATE NOCASE` clause on
94/// the right-hand pattern would be a no-op — `LIKE` does not honor RHS
95/// collation; see <https://www.sqlite.org/lang_expr.html>.) User-facing
96/// `LIKE` wildcards (`%`, `_`) in `?1` flow straight through.
97const BRIEF_SQL: &str = r"
98    SELECT name
99    FROM sqlite_schema
100    WHERE type = 'trigger'
101      AND name NOT LIKE 'sqlite_%'
102      AND (?1 IS NULL OR name LIKE '%' || ?1 || '%')
103    ORDER BY name
104    LIMIT ?2 OFFSET ?3";
105
106/// Detailed-mode SQL: single SELECT projecting `(name, json_object(...))`.
107///
108/// `'main'` is hard-coded in the projection — `sqlite_schema` here is the
109/// `main` schema's catalogue, the only one the connection helper opens.
110/// `AND sql IS NOT NULL` enforces the homogeneous-shape contract: rows whose
111/// stored `CREATE TRIGGER` text is `NULL` (extension-generated, hand-edited)
112/// are silently omitted from detailed pages. Brief mode does not filter on
113/// `sql` so those triggers are still discoverable by name. `SQLite` trigger
114/// names are unique within a database, so `ORDER BY name` is sufficient
115/// for stable pagination — no secondary tie-breaker needed.
116const DETAILED_SQL: &str = r"
117    SELECT
118        name,
119        json_object(
120            'schema',     'main',
121            'table',      tbl_name,
122            'definition', sql
123        ) AS entry
124    FROM sqlite_schema
125    WHERE type = 'trigger'
126      AND name NOT LIKE 'sqlite_%'
127      AND sql IS NOT NULL
128      AND (?1 IS NULL OR name LIKE '%' || ?1 || '%')
129    ORDER BY name
130    LIMIT ?2 OFFSET ?3";
131
132impl SqliteHandler {
133    /// Lists one page of triggers in the connected database, optionally filtered and/or detailed.
134    ///
135    /// # Errors
136    ///
137    /// Returns [`ErrorData`] with code `-32602` if `cursor` is malformed,
138    /// or an internal-error [`ErrorData`] if the underlying query fails.
139    pub async fn list_triggers(
140        &self,
141        ListTriggersRequest {
142            cursor,
143            search,
144            detailed,
145        }: ListTriggersRequest,
146    ) -> Result<ListTriggersResponse, ErrorData> {
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                    None,
159                )
160                .await?;
161            let (rows, next_cursor) = pager.paginate(rows);
162            return Ok(ListTriggersResponse::detailed(
163                rows.into_iter().map(|(name, json)| (name, 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                None,
176            )
177            .await?;
178        let (triggers, next_cursor) = pager.paginate(rows);
179        Ok(ListTriggersResponse::brief(triggers, next_cursor))
180    }
181}