Skip to main content

micromegas/servers/mcp/
read_only.rs

1use datafusion::sql::sqlparser::ast::{
2    Expr, ObjectName, ObjectNamePart, Query, SetExpr, Statement, TableFactor, Visit, Visitor,
3};
4use datafusion::sql::sqlparser::dialect::GenericDialect;
5use datafusion::sql::sqlparser::parser::Parser;
6use micromegas_analytics::lakehouse::view_definition::MUTATING_FUNCTIONS;
7use std::ops::ControlFlow;
8
9/// Admin-only read functions. They are not mutating, but no admin feature is reachable through
10/// MCP; the admin/non-admin comparison test keeps this list complete.
11pub const ADMIN_ONLY_READ_FUNCTIONS: &[&str] = &[
12    "list_query_denials",
13    "list_view_set_definitions",
14    "check_view_merge",
15];
16
17/// Whether `name` (compared case-insensitively) is a function the MCP layer refuses to call.
18pub fn is_denied_function(name: &str) -> bool {
19    let lower = name.to_ascii_lowercase();
20    MUTATING_FUNCTIONS.contains(&lower.as_str())
21        || ADMIN_ONLY_READ_FUNCTIONS.contains(&lower.as_str())
22}
23
24struct Checker;
25
26fn check_name(name: &ObjectName) -> ControlFlow<String> {
27    for part in &name.0 {
28        match part {
29            ObjectNamePart::Identifier(ident) => {
30                if is_denied_function(&ident.value) {
31                    return ControlFlow::Break(format!(
32                        "function '{}' is not available through MCP",
33                        ident.value
34                    ));
35                }
36            }
37            ObjectNamePart::Function(_) => {
38                return ControlFlow::Break("computed object names are not allowed".to_string());
39            }
40        }
41    }
42    ControlFlow::Continue(())
43}
44
45fn check_set_expr(body: &SetExpr) -> ControlFlow<String> {
46    match body {
47        SetExpr::Insert(_) | SetExpr::Update(_) | SetExpr::Delete(_) | SetExpr::Merge(_) => {
48            ControlFlow::Break("only read-only SELECT queries are allowed".to_string())
49        }
50        _ => ControlFlow::Continue(()),
51    }
52}
53
54impl Visitor for Checker {
55    type Break = String;
56
57    fn pre_visit_query(&mut self, query: &Query) -> ControlFlow<Self::Break> {
58        check_set_expr(&query.body)
59    }
60
61    fn pre_visit_relation(&mut self, relation: &ObjectName) -> ControlFlow<Self::Break> {
62        check_name(relation)
63    }
64
65    fn pre_visit_table_factor(&mut self, table_factor: &TableFactor) -> ControlFlow<Self::Break> {
66        match table_factor {
67            TableFactor::Table { name, .. } | TableFactor::Function { name, .. } => {
68                check_name(name)
69            }
70            _ => ControlFlow::Continue(()),
71        }
72    }
73
74    fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<Self::Break> {
75        if let Expr::Function(func) = expr {
76            return check_name(&func.name);
77        }
78        ControlFlow::Continue(())
79    }
80}
81
82/// Accepts a single read-only `SELECT`-style query and rejects everything else: other statement
83/// kinds, several statements, and calls to mutating or admin-only functions anywhere in the query.
84pub fn check_read_only(sql: &str) -> Result<(), String> {
85    let statements = Parser::parse_sql(&GenericDialect {}, sql)
86        .map_err(|e| format!("could not parse SQL: {e}"))?;
87    let [statement] = statements.as_slice() else {
88        return Err("exactly one statement is allowed".to_string());
89    };
90    if !matches!(statement, Statement::Query(_)) {
91        return Err("only a single read-only SELECT query is allowed".to_string());
92    }
93    match statement.visit(&mut Checker) {
94        ControlFlow::Break(reason) => Err(reason),
95        ControlFlow::Continue(()) => Ok(()),
96    }
97}