Skip to main content

reddb_server/mcp/
capability.rs

1//! What an MCP session is allowed to do.
2//!
3//! The MCP server runs every tool as an implicit admin: it is a stdio
4//! process the operator started, so there is no second principal to
5//! authenticate. That is defensible for the *transport*, but it makes the
6//! tool list the entire security boundary — and that list includes
7//! `reddb_query` (arbitrary SQL and DDL), `reddb_drop_collection`,
8//! `reddb_vault_unseal` (returns plaintext secrets) and
9//! `reddb_auth_bootstrap` (returns an admin API key plus the vault
10//! certificate).
11//!
12//! The model driving those tools reads rows, documents and error strings
13//! that other people wrote. Prompt injection in that content therefore
14//! reaches `DROP COLLECTION` and the vault with no confirmation step. The
15//! fix is not to authenticate the model — it is to stop handing every
16//! session the full set by default.
17//!
18//! A session now runs at one of three levels, lowest first:
19//!
20//!   * [`McpCapability::ReadOnly`] (the default) — reads, introspection and
21//!     planning. Nothing that mutates state and nothing that returns a
22//!     credential.
23//!   * [`McpCapability::Write`] (`--allow-write`) — adds inserts, updates,
24//!     deletes, KV and config writes, and DDL.
25//!   * [`McpCapability::Admin`] (`--allow-admin`) — adds the vault and the
26//!     auth tools.
27//!
28//! `reddb_query` takes arbitrary SQL, so its classification cannot come
29//! from the tool name alone; [`statement_capability`] classifies the
30//! statement itself and the query tool checks the result against the
31//! session's level.
32
33use std::fmt;
34
35/// What a session may do, ordered from least to most privileged.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
37pub enum McpCapability {
38    /// Reads and introspection only. The default for every session.
39    #[default]
40    ReadOnly,
41    /// Reads plus data and schema mutation.
42    Write,
43    /// Everything, including the vault and principal management.
44    Admin,
45}
46
47impl McpCapability {
48    /// Resolve the level from the two opt-in flags, highest wins.
49    pub fn from_flags(allow_write: bool, allow_admin: bool) -> Self {
50        if allow_admin {
51            Self::Admin
52        } else if allow_write {
53            Self::Write
54        } else {
55            Self::ReadOnly
56        }
57    }
58
59    /// Whether this level satisfies `required`.
60    pub fn permits(self, required: McpCapability) -> bool {
61        self >= required
62    }
63
64    pub fn as_str(self) -> &'static str {
65        match self {
66            Self::ReadOnly => "read-only",
67            Self::Write => "write",
68            Self::Admin => "admin",
69        }
70    }
71
72    /// The flag an operator would add to reach this level.
73    fn enabling_flag(self) -> &'static str {
74        match self {
75            Self::ReadOnly => "(no flag needed)",
76            Self::Write => "--allow-write",
77            Self::Admin => "--allow-admin",
78        }
79    }
80}
81
82impl fmt::Display for McpCapability {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.write_str(self.as_str())
85    }
86}
87
88/// The level a tool requires. Unknown names are treated as `Admin` so a
89/// tool added later is refused by default rather than silently exposed to
90/// read-only sessions.
91pub fn tool_capability(tool_name: &str) -> McpCapability {
92    match tool_name {
93        // Reads, introspection, planning.
94        "reddb_query"
95        | "reddb.ask"
96        | "reddb_collections"
97        | "reddb_catalog"
98        | "reddb_describe_collection"
99        | "reddb_find_field"
100        | "reddb_kv_get"
101        | "reddb_config_get"
102        | "reddb_config_resolve"
103        | "reddb_search_vector"
104        | "reddb_search_text"
105        | "reddb_health"
106        | "reddb_graph_traverse"
107        | "reddb_graph_shortest_path"
108        | "reddb_graph_centrality"
109        | "reddb_graph_community"
110        | "reddb_graph_components"
111        | "reddb_graph_cycles"
112        | "reddb_graph_clustering"
113        | "reddb_scan"
114        | "reddb_rql_validate"
115        | "reddb_rql_explain"
116        | "reddb_type_of"
117        | "reddb_explain_connection" => McpCapability::ReadOnly,
118
119        // Data and schema mutation.
120        "reddb_insert_row"
121        | "reddb_insert_node"
122        | "reddb_insert_edge"
123        | "reddb_insert_vector"
124        | "reddb_insert_document"
125        | "reddb_kv_set"
126        | "reddb_kv_invalidate_tags"
127        | "reddb_config_put"
128        | "reddb_delete"
129        | "reddb_update"
130        | "reddb_create_collection"
131        | "reddb_drop_collection" => McpCapability::Write,
132
133        // Secrets and principals.
134        "reddb_vault_get"
135        | "reddb_vault_put"
136        | "reddb_vault_reveal"
137        | "reddb_vault_unseal"
138        | "reddb_auth_bootstrap"
139        | "reddb_auth_create_user"
140        | "reddb_auth_login"
141        | "reddb_auth_create_api_key"
142        | "reddb_auth_list_users" => McpCapability::Admin,
143
144        // Default-deny for anything not classified above.
145        _ => McpCapability::Admin,
146    }
147}
148
149/// The level a statement passed to `reddb_query` requires.
150///
151/// `reddb_query` is read-only *as a tool*, but takes arbitrary SQL, so the
152/// statement decides. Classification is deliberately conservative: only a
153/// recognised read verb is `ReadOnly`, anything touching the vault, secrets
154/// or principals is `Admin`, and anything unrecognised is `Write` — a
155/// statement this classifier does not know must not slip through a
156/// read-only session.
157pub fn statement_capability(sql: &str) -> McpCapability {
158    let trimmed = strip_leading_noise(sql);
159    let upper: String = trimmed
160        .chars()
161        .take_while(|c| c.is_ascii_alphanumeric() || c.is_whitespace())
162        .collect::<String>()
163        .to_ascii_uppercase();
164    let mut words = upper.split_whitespace();
165    let first = words.next().unwrap_or("");
166    let second = words.next().unwrap_or("");
167
168    // Vault, secrets and principals are admin regardless of the verb.
169    if matches!(first, "VAULT" | "GRANT" | "REVOKE")
170        || matches!(second, "VAULT" | "SECRET" | "SECRETS" | "USER" | "POLICY")
171        || (first == "SHOW" && matches!(second, "SECRET" | "SECRETS" | "POLICIES" | "USERS"))
172    {
173        return McpCapability::Admin;
174    }
175
176    match first {
177        "SELECT" | "WITH" | "SHOW" | "DESCRIBE" | "DESC" | "EXPLAIN" | "RANK" | "LIST" | "GET"
178        | "HISTORY" => McpCapability::ReadOnly,
179        // `KV GET` reads; every other KV verb writes.
180        "KV" if matches!(second, "GET" | "LIST") => McpCapability::ReadOnly,
181        _ => McpCapability::Write,
182    }
183}
184
185/// Drop leading whitespace and line comments so `-- x\nDROP ...` is
186/// classified on the statement rather than on the comment.
187fn strip_leading_noise(sql: &str) -> &str {
188    let mut rest = sql.trim_start();
189    while let Some(after) = rest.strip_prefix("--") {
190        rest = after
191            .split_once('\n')
192            .map(|(_, tail)| tail)
193            .unwrap_or("")
194            .trim_start();
195    }
196    rest
197}
198
199/// The refusal handed back when a session lacks the level a call needs.
200pub fn refusal(subject: &str, granted: McpCapability, required: McpCapability) -> String {
201    format!(
202        "{subject} requires the `{required}` capability but this MCP session is `{granted}`. \
203         Restart the server with `{}` to enable it.",
204        required.enabling_flag()
205    )
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[test]
213    fn default_session_is_read_only() {
214        assert_eq!(McpCapability::default(), McpCapability::ReadOnly);
215        assert_eq!(
216            McpCapability::from_flags(false, false),
217            McpCapability::ReadOnly
218        );
219        assert_eq!(McpCapability::from_flags(true, false), McpCapability::Write);
220        assert_eq!(McpCapability::from_flags(false, true), McpCapability::Admin);
221        // The stronger flag wins rather than combining into something odd.
222        assert_eq!(McpCapability::from_flags(true, true), McpCapability::Admin);
223    }
224
225    #[test]
226    fn levels_are_ordered_and_inclusive() {
227        assert!(McpCapability::Admin.permits(McpCapability::Write));
228        assert!(McpCapability::Write.permits(McpCapability::ReadOnly));
229        assert!(!McpCapability::ReadOnly.permits(McpCapability::Write));
230        assert!(!McpCapability::Write.permits(McpCapability::Admin));
231    }
232
233    #[test]
234    fn destructive_and_credential_tools_are_not_read_only() {
235        for tool in [
236            "reddb_drop_collection",
237            "reddb_delete",
238            "reddb_update",
239            "reddb_create_collection",
240        ] {
241            assert_eq!(tool_capability(tool), McpCapability::Write, "{tool}");
242        }
243        for tool in [
244            "reddb_vault_reveal",
245            "reddb_vault_unseal",
246            "reddb_vault_get",
247            "reddb_auth_bootstrap",
248            "reddb_auth_create_api_key",
249        ] {
250            assert_eq!(tool_capability(tool), McpCapability::Admin, "{tool}");
251        }
252    }
253
254    #[test]
255    fn both_reveal_forms_require_the_admin_surface() {
256        for sql in [
257            "VAULT REVEAL app.token",
258            "REVEAL VAULT app.token",
259            "UNSEAL VAULT app.token",
260            "VAULT UNSEAL app.token",
261        ] {
262            assert_eq!(statement_capability(sql), McpCapability::Admin, "{sql}");
263        }
264    }
265
266    #[test]
267    fn unknown_tools_default_to_admin() {
268        // A tool added later must be refused by a read-only session until
269        // someone classifies it, not exposed by omission.
270        assert_eq!(tool_capability("reddb_future_tool"), McpCapability::Admin);
271    }
272
273    #[test]
274    fn statement_classification_follows_the_statement_not_the_tool() {
275        assert_eq!(
276            statement_capability("SELECT * FROM users"),
277            McpCapability::ReadOnly
278        );
279        assert_eq!(
280            statement_capability("  \n  select 1"),
281            McpCapability::ReadOnly
282        );
283        for sql in [
284            "DROP TABLE users",
285            "DELETE FROM users",
286            "INSERT INTO users VALUES (1)",
287            "UPDATE users SET a = 1",
288        ] {
289            assert_eq!(statement_capability(sql), McpCapability::Write, "{sql}");
290        }
291        for sql in [
292            "SET SECRET red.secret.ai.openai = 'x'",
293            "CREATE USER bob PASSWORD 'x'",
294            "GRANT SELECT ON t TO bob",
295            "SHOW SECRETS",
296        ] {
297            assert_eq!(statement_capability(sql), McpCapability::Admin, "{sql}");
298        }
299    }
300
301    #[test]
302    fn leading_comments_do_not_hide_the_verb() {
303        // `-- SELECT\nDROP TABLE t` must classify as the DROP, not the
304        // comment: the comment is exactly what an injected prompt controls.
305        assert_eq!(
306            statement_capability("-- SELECT harmless\nDROP TABLE t"),
307            McpCapability::Write
308        );
309    }
310
311    #[test]
312    fn kv_reads_and_writes_are_separated() {
313        assert_eq!(statement_capability("KV GET c.k"), McpCapability::ReadOnly);
314        assert_eq!(
315            statement_capability("KV PUT c.k = 'v'"),
316            McpCapability::Write
317        );
318    }
319}