reddb_server/mcp/
capability.rs1use std::fmt;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
37pub enum McpCapability {
38 #[default]
40 ReadOnly,
41 Write,
43 Admin,
45}
46
47impl McpCapability {
48 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 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 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
88pub fn tool_capability(tool_name: &str) -> McpCapability {
92 match tool_name {
93 "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 "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 "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 _ => McpCapability::Admin,
146 }
147}
148
149pub 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 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" if matches!(second, "GET" | "LIST") => McpCapability::ReadOnly,
181 _ => McpCapability::Write,
182 }
183}
184
185fn 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
199pub 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 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 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 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}