pmcp-code-mode 0.5.0

Code Mode validation and execution framework for MCP servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! SQL validation for Code Mode.
//!
//! Parses SQL statements with [`sqlparser`], classifies the statement type
//! (`SELECT`/`INSERT`/`UPDATE`/`DELETE`/DDL), and extracts the tables, columns,
//! and structural metadata that the Cedar policy evaluator needs.
//!
//! Gated behind the `sql-code-mode` feature.

use crate::types::{
    CodeType, Complexity, SecurityAnalysis, SecurityIssue, SecurityIssueType, ValidationError,
};
use sqlparser::ast::{
    AssignmentTarget, Expr, FromTable, GroupByExpr, Join, LimitClause, ObjectName, Query, Select,
    SelectItem, SetExpr, Statement, TableFactor, TableObject, TableWithJoins,
};
use sqlparser::dialect::{Dialect, GenericDialect};
use sqlparser::parser::Parser;
use std::collections::HashSet;

/// High-level category of a SQL statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SqlStatementType {
    /// `SELECT`, `SHOW`, `EXPLAIN`, `DESCRIBE`
    Select,
    /// `INSERT`
    Insert,
    /// `UPDATE`, `MERGE`
    Update,
    /// `DELETE`, `TRUNCATE`
    Delete,
    /// `CREATE`/`ALTER`/`DROP`/`GRANT`/`REVOKE` (DDL/admin)
    Ddl,
    /// Unrecognized or unsupported statement
    Other,
}

impl SqlStatementType {
    /// The canonical uppercase string ("SELECT", "INSERT", etc.) used by
    /// the Cedar schema and [`UnifiedAction::from_sql`](crate::UnifiedAction::from_sql).
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Select => "SELECT",
            Self::Insert => "INSERT",
            Self::Update => "UPDATE",
            Self::Delete => "DELETE",
            Self::Ddl => "DDL",
            Self::Other => "OTHER",
        }
    }

    /// Whether this statement is read-only.
    pub fn is_read_only(&self) -> bool {
        matches!(self, Self::Select)
    }

    /// Whether this statement writes data (INSERT/UPDATE).
    pub fn is_write(&self) -> bool {
        matches!(self, Self::Insert | Self::Update)
    }

    /// Whether this statement deletes data (DELETE/TRUNCATE).
    pub fn is_delete(&self) -> bool {
        matches!(self, Self::Delete)
    }

    /// Whether this statement changes schema or permissions.
    pub fn is_admin(&self) -> bool {
        matches!(self, Self::Ddl)
    }
}

/// Structural information extracted from a parsed SQL statement.
#[derive(Debug, Clone)]
pub struct SqlStatementInfo {
    /// High-level statement category.
    pub statement_type: SqlStatementType,

    /// Raw uppercase verb ("SELECT", "INSERT", "CREATE TABLE", etc.) — used
    /// for explanations. For Cedar entity building use [`Self::statement_type`].
    pub verb: String,

    /// All tables referenced by name (final path segment if qualified).
    pub tables: HashSet<String>,

    /// All columns referenced (where determinable). `*` recorded for wildcards.
    pub columns: HashSet<String>,

    /// Whether the statement has a `WHERE` clause.
    pub has_where: bool,

    /// Whether the statement has a `LIMIT` clause.
    pub has_limit: bool,

    /// Whether the statement has an `ORDER BY` clause.
    pub has_order_by: bool,

    /// Whether the statement includes `GROUP BY` or aggregate functions.
    pub has_aggregation: bool,

    /// Number of `JOIN` clauses across all FROM items.
    pub join_count: u32,

    /// Number of subqueries (naive count of nested SELECTs).
    pub subquery_count: u32,

    /// Row-count estimate: `LIMIT n` when present, otherwise a configurable default.
    pub estimated_rows: u64,

    /// Raw length of the SQL string (characters).
    pub sql_length: usize,
}

/// SQL validator that parses and analyzes SQL statements.
#[derive(Debug, Clone)]
pub struct SqlValidator {
    dialect: DialectBox,
    default_row_estimate: u64,
}

impl Default for SqlValidator {
    fn default() -> Self {
        Self::new()
    }
}

impl SqlValidator {
    /// Create a new SQL validator with the generic ANSI dialect.
    pub fn new() -> Self {
        Self {
            dialect: DialectBox::Generic,
            default_row_estimate: 1000,
        }
    }

    /// Parse SQL and extract statement info.
    ///
    /// Returns an error if the SQL fails to parse, is empty, or contains
    /// multiple statements (SQL Code Mode validates one statement at a time).
    pub fn validate(&self, sql: &str) -> Result<SqlStatementInfo, ValidationError> {
        let trimmed = sql.trim();
        if trimmed.is_empty() {
            return Err(ValidationError::ParseError {
                message: "SQL statement is empty".to_string(),
                line: 1,
                column: 1,
            });
        }

        let statements = Parser::parse_sql(self.dialect.as_dialect(), trimmed).map_err(|e| {
            ValidationError::ParseError {
                message: format!("SQL parse error: {}", e),
                line: 1,
                column: 1,
            }
        })?;

        match statements.len() {
            0 => Err(ValidationError::ParseError {
                message: "SQL contains no statements".to_string(),
                line: 1,
                column: 1,
            }),
            1 => Ok(self.analyze_statement(&statements[0], trimmed)),
            n => Err(ValidationError::ParseError {
                message: format!("SQL Code Mode validates one statement at a time; got {}", n),
                line: 1,
                column: 1,
            }),
        }
    }

    /// Produce a security analysis for the given statement info.
    ///
    /// The issues produced here are warnings only — config-level and
    /// policy-level authorization are enforced separately in
    /// [`ValidationPipeline::validate_sql_query`](crate::ValidationPipeline::validate_sql_query).
    pub fn analyze_security(&self, info: &SqlStatementInfo) -> SecurityAnalysis {
        let mut issues: Vec<SecurityIssue> = Vec::new();

        // UPDATE/DELETE without WHERE affects every row — classify as UnboundedQuery.
        if (info.statement_type.is_write() || info.statement_type.is_delete()) && !info.has_where {
            issues.push(SecurityIssue::new(
                SecurityIssueType::UnboundedQuery,
                format!(
                    "{} statement has no WHERE clause — affects all rows in the table",
                    info.verb
                ),
            ));
        }

        // Pure SELECT without LIMIT is also unbounded.
        if info.statement_type.is_read_only() && !info.has_limit {
            issues.push(SecurityIssue::new(
                SecurityIssueType::UnboundedQuery,
                format!(
                    "{} statement has no LIMIT — result set may be large",
                    info.verb
                ),
            ));
        }

        // Excessive joins or subqueries — complexity signal.
        if info.join_count > 5 {
            issues.push(SecurityIssue::new(
                SecurityIssueType::HighComplexity,
                format!(
                    "Query has {} JOINs, which may be expensive to execute",
                    info.join_count
                ),
            ));
        }
        if info.subquery_count > 3 {
            issues.push(SecurityIssue::new(
                SecurityIssueType::DeepNesting,
                format!("Query has {} nested subqueries", info.subquery_count),
            ));
        }

        let complexity = estimate_complexity(info);

        SecurityAnalysis {
            is_read_only: info.statement_type.is_read_only(),
            tables_accessed: info.tables.clone(),
            fields_accessed: info.columns.clone(),
            has_aggregation: info.has_aggregation,
            has_subqueries: info.subquery_count > 0,
            estimated_complexity: complexity,
            potential_issues: issues,
            estimated_rows: Some(info.estimated_rows),
        }
    }

    /// Map parsed statement info to [`CodeType`].
    pub fn to_code_type(&self, info: &SqlStatementInfo) -> CodeType {
        if info.statement_type.is_read_only() {
            CodeType::SqlQuery
        } else {
            CodeType::SqlMutation
        }
    }

    fn analyze_statement(&self, stmt: &Statement, sql: &str) -> SqlStatementInfo {
        let mut info = SqlStatementInfo {
            statement_type: SqlStatementType::Other,
            verb: verb_for(stmt),
            tables: HashSet::new(),
            columns: HashSet::new(),
            has_where: false,
            has_limit: false,
            has_order_by: false,
            has_aggregation: false,
            join_count: 0,
            subquery_count: 0,
            estimated_rows: self.default_row_estimate,
            sql_length: sql.len(),
        };

        match stmt {
            Statement::Query(query) => {
                info.statement_type = SqlStatementType::Select;
                self.analyze_query(query, &mut info);
            },
            Statement::Insert(insert) => {
                info.statement_type = SqlStatementType::Insert;
                if let TableObject::TableName(name) = &insert.table {
                    add_object_name(&mut info.tables, name);
                }
                for col in &insert.columns {
                    info.columns.insert(col.value.clone());
                }
                if let Some(source) = &insert.source {
                    self.analyze_query(source, &mut info);
                }
            },
            Statement::Update(update) => {
                info.statement_type = SqlStatementType::Update;
                self.analyze_table_with_joins(&update.table, &mut info);
                for assignment in &update.assignments {
                    match &assignment.target {
                        AssignmentTarget::ColumnName(name) => {
                            add_object_name(&mut info.columns, name);
                        },
                        AssignmentTarget::Tuple(names) => {
                            for n in names {
                                add_object_name(&mut info.columns, n);
                            }
                        },
                    }
                    self.analyze_expr(&assignment.value, &mut info);
                }
                if let Some(expr) = &update.selection {
                    info.has_where = true;
                    self.analyze_expr(expr, &mut info);
                }
            },
            Statement::Delete(delete) => {
                info.statement_type = SqlStatementType::Delete;
                match &delete.from {
                    FromTable::WithFromKeyword(tables) | FromTable::WithoutKeyword(tables) => {
                        for t in tables {
                            self.analyze_table_with_joins(t, &mut info);
                        }
                    },
                }
                // Multi-table delete names
                for t in &delete.tables {
                    add_object_name(&mut info.tables, t);
                }
                if let Some(expr) = &delete.selection {
                    info.has_where = true;
                    self.analyze_expr(expr, &mut info);
                }
            },
            Statement::Truncate(truncate) => {
                info.statement_type = SqlStatementType::Delete;
                for tn in &truncate.table_names {
                    add_object_name(&mut info.tables, &tn.name);
                }
            },
            Statement::CreateTable(create) => {
                info.statement_type = SqlStatementType::Ddl;
                add_object_name(&mut info.tables, &create.name);
            },
            Statement::AlterTable(alter) => {
                info.statement_type = SqlStatementType::Ddl;
                add_object_name(&mut info.tables, &alter.name);
            },
            Statement::Drop { .. }
            | Statement::CreateIndex(_)
            | Statement::CreateView { .. }
            | Statement::Grant { .. }
            | Statement::Revoke { .. } => {
                info.statement_type = SqlStatementType::Ddl;
            },
            _ => {
                // Unknown statement — leave as Other.
            },
        }

        info
    }

    fn analyze_query(&self, query: &Query, info: &mut SqlStatementInfo) {
        if query.order_by.is_some() {
            info.has_order_by = true;
        }
        if let Some(limit_clause) = &query.limit_clause {
            info.has_limit = true;
            let limit_expr = match limit_clause {
                LimitClause::LimitOffset { limit, .. } => limit.as_ref(),
                LimitClause::OffsetCommaLimit { limit, .. } => Some(limit),
            };
            if let Some(Expr::Value(v)) = limit_expr {
                if let sqlparser::ast::Value::Number(n, _) = &v.value {
                    if let Ok(parsed) = n.parse::<u64>() {
                        info.estimated_rows = parsed;
                    }
                }
            }
        }

        self.analyze_set_expr(&query.body, info);
    }

    fn analyze_set_expr(&self, set_expr: &SetExpr, info: &mut SqlStatementInfo) {
        match set_expr {
            SetExpr::Select(select) => self.analyze_select(select, info),
            SetExpr::Query(inner) => {
                info.subquery_count += 1;
                self.analyze_query(inner, info);
            },
            SetExpr::SetOperation { left, right, .. } => {
                self.analyze_set_expr(left, info);
                self.analyze_set_expr(right, info);
            },
            _ => {},
        }
    }

    fn analyze_select(&self, select: &Select, info: &mut SqlStatementInfo) {
        // Projection columns
        for item in &select.projection {
            match item {
                SelectItem::UnnamedExpr(expr) => self.analyze_expr(expr, info),
                SelectItem::ExprWithAlias { expr, .. } => self.analyze_expr(expr, info),
                SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard(_, _) => {
                    info.columns.insert("*".to_string());
                },
            }
        }

        // FROM tables + joins
        for table in &select.from {
            self.analyze_table_with_joins(table, info);
        }

        // WHERE
        if let Some(expr) = &select.selection {
            info.has_where = true;
            self.analyze_expr(expr, info);
        }

        // GROUP BY / aggregation
        if !group_by_is_empty(&select.group_by) {
            info.has_aggregation = true;
        }
    }

    fn analyze_table_with_joins(&self, item: &TableWithJoins, info: &mut SqlStatementInfo) {
        self.analyze_table_factor(&item.relation, info);
        for join in &item.joins {
            info.join_count += 1;
            self.analyze_join(join, info);
        }
    }

    fn analyze_join(&self, join: &Join, info: &mut SqlStatementInfo) {
        self.analyze_table_factor(&join.relation, info);
    }

    fn analyze_table_factor(&self, factor: &TableFactor, info: &mut SqlStatementInfo) {
        match factor {
            TableFactor::Table { name, .. } => add_object_name(&mut info.tables, name),
            TableFactor::Derived { subquery, .. } => {
                info.subquery_count += 1;
                self.analyze_query(subquery, info);
            },
            TableFactor::NestedJoin {
                table_with_joins, ..
            } => self.analyze_table_with_joins(table_with_joins, info),
            _ => {},
        }
    }

    fn analyze_expr(&self, expr: &Expr, info: &mut SqlStatementInfo) {
        match expr {
            Expr::Identifier(id) => {
                info.columns.insert(id.value.clone());
            },
            Expr::CompoundIdentifier(ids) => {
                if let Some(last) = ids.last() {
                    info.columns.insert(last.value.clone());
                }
            },
            Expr::Subquery(q)
            | Expr::Exists { subquery: q, .. }
            | Expr::InSubquery { subquery: q, .. } => {
                info.subquery_count += 1;
                self.analyze_query(q, info);
            },
            Expr::Function(f) => {
                let name = f.name.to_string().to_uppercase();
                if matches!(
                    name.as_str(),
                    "COUNT" | "SUM" | "AVG" | "MIN" | "MAX" | "ARRAY_AGG" | "STRING_AGG"
                ) {
                    info.has_aggregation = true;
                }
            },
            _ => {},
        }
    }
}

fn estimate_complexity(info: &SqlStatementInfo) -> Complexity {
    let joins = info.join_count;
    let subs = info.subquery_count;
    if joins >= 5 || subs >= 3 {
        Complexity::High
    } else if joins >= 2 || subs >= 1 || info.has_aggregation {
        Complexity::Medium
    } else {
        Complexity::Low
    }
}

fn group_by_is_empty(group_by: &GroupByExpr) -> bool {
    match group_by {
        GroupByExpr::All(_) => true,
        GroupByExpr::Expressions(exprs, _) => exprs.is_empty(),
    }
}

fn add_object_name(out: &mut HashSet<String>, name: &ObjectName) {
    if let Some(last) = name.0.last() {
        out.insert(last.to_string());
    } else {
        out.insert(name.to_string());
    }
}

fn verb_for(stmt: &Statement) -> String {
    match stmt {
        Statement::Query(_) => "SELECT".to_string(),
        Statement::Insert(_) => "INSERT".to_string(),
        Statement::Update { .. } => "UPDATE".to_string(),
        Statement::Delete(_) => "DELETE".to_string(),
        Statement::Truncate { .. } => "TRUNCATE".to_string(),
        Statement::CreateTable(_) => "CREATE TABLE".to_string(),
        Statement::AlterTable { .. } => "ALTER TABLE".to_string(),
        Statement::Drop { .. } => "DROP".to_string(),
        Statement::CreateIndex(_) => "CREATE INDEX".to_string(),
        Statement::CreateView { .. } => "CREATE VIEW".to_string(),
        Statement::Grant { .. } => "GRANT".to_string(),
        Statement::Revoke { .. } => "REVOKE".to_string(),
        other => format!("{:?}", other)
            .split('(')
            .next()
            .unwrap_or("OTHER")
            .to_uppercase(),
    }
}

/// Enum wrapper around concrete dialects so `SqlValidator` stays `Clone` and
/// avoids trait-object gymnastics.
#[derive(Debug, Clone)]
enum DialectBox {
    Generic,
}

impl DialectBox {
    fn as_dialect(&self) -> &dyn Dialect {
        match self {
            Self::Generic => &GenericDialect {},
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn select_simple() {
        let v = SqlValidator::new();
        let info = v.validate("SELECT id, name FROM users").unwrap();
        assert_eq!(info.statement_type, SqlStatementType::Select);
        assert!(info.tables.contains("users"));
        assert!(info.columns.contains("id"));
        assert!(info.columns.contains("name"));
        assert!(!info.has_where);
        assert!(!info.has_limit);
    }

    #[test]
    fn select_with_where_limit_order() {
        let v = SqlValidator::new();
        let info = v
            .validate("SELECT id FROM users WHERE active = 1 ORDER BY id LIMIT 10")
            .unwrap();
        assert!(info.has_where);
        assert!(info.has_limit);
        assert!(info.has_order_by);
        assert_eq!(info.estimated_rows, 10);
    }

    #[test]
    fn select_star() {
        let v = SqlValidator::new();
        let info = v.validate("SELECT * FROM users").unwrap();
        assert!(info.columns.contains("*"));
    }

    #[test]
    fn select_join_and_subquery() {
        let v = SqlValidator::new();
        let info = v
            .validate(
                "SELECT u.id FROM users u JOIN orders o ON u.id = o.user_id \
                 WHERE u.id IN (SELECT id FROM admins)",
            )
            .unwrap();
        assert_eq!(info.join_count, 1);
        assert!(info.subquery_count >= 1);
        assert!(info.tables.contains("users"));
        assert!(info.tables.contains("orders"));
        assert!(info.tables.contains("admins"));
    }

    #[test]
    fn insert_extracts_table_and_columns() {
        let v = SqlValidator::new();
        let info = v
            .validate("INSERT INTO users (id, name) VALUES (1, 'Alice')")
            .unwrap();
        assert_eq!(info.statement_type, SqlStatementType::Insert);
        assert!(info.tables.contains("users"));
        assert!(info.columns.contains("id"));
        assert!(info.columns.contains("name"));
    }

    #[test]
    fn update_without_where_flagged() {
        let v = SqlValidator::new();
        let info = v.validate("UPDATE users SET active = 0").unwrap();
        assert_eq!(info.statement_type, SqlStatementType::Update);
        assert!(!info.has_where);
        let sa = v.analyze_security(&info);
        assert!(sa
            .potential_issues
            .iter()
            .any(|i| i.issue_type == SecurityIssueType::UnboundedQuery));
    }

    #[test]
    fn update_with_where() {
        let v = SqlValidator::new();
        let info = v
            .validate("UPDATE users SET active = 0 WHERE id = 1")
            .unwrap();
        assert_eq!(info.statement_type, SqlStatementType::Update);
        assert!(info.has_where);
        assert!(info.columns.contains("active"));
    }

    #[test]
    fn delete_with_where() {
        let v = SqlValidator::new();
        let info = v.validate("DELETE FROM users WHERE id = 1").unwrap();
        assert_eq!(info.statement_type, SqlStatementType::Delete);
        assert!(info.has_where);
    }

    #[test]
    fn ddl_is_admin() {
        let v = SqlValidator::new();
        let info = v.validate("CREATE TABLE foo (id INT)").unwrap();
        assert_eq!(info.statement_type, SqlStatementType::Ddl);
        assert!(info.statement_type.is_admin());
    }

    #[test]
    fn empty_sql_rejected() {
        let v = SqlValidator::new();
        assert!(matches!(
            v.validate(""),
            Err(ValidationError::ParseError { .. })
        ));
        assert!(matches!(
            v.validate("   "),
            Err(ValidationError::ParseError { .. })
        ));
    }

    #[test]
    fn syntax_error_rejected() {
        let v = SqlValidator::new();
        assert!(matches!(
            v.validate("SELEC id FRM users"),
            Err(ValidationError::ParseError { .. })
        ));
    }

    #[test]
    fn multiple_statements_rejected() {
        let v = SqlValidator::new();
        assert!(matches!(
            v.validate("SELECT 1; SELECT 2"),
            Err(ValidationError::ParseError { .. })
        ));
    }

    #[test]
    fn aggregation_detected() {
        let v = SqlValidator::new();
        let info = v.validate("SELECT COUNT(*) FROM users").unwrap();
        assert!(info.has_aggregation);
    }

    #[test]
    fn group_by_detected() {
        let v = SqlValidator::new();
        let info = v
            .validate("SELECT role, COUNT(*) FROM users GROUP BY role")
            .unwrap();
        assert!(info.has_aggregation);
    }
}