eggsact 1.2.7

Deterministic MCP and in-process utility tools for coding agents
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
use crate::mcp::machine_codes;
use crate::mcp::schemas::ToolResponse;
use crate::tools::helpers::*;
use serde_json::Value;

pub fn validate_regex(args: &Value) -> ToolResponse {
    let pattern = match args.get("pattern") {
        Some(v) => match v.as_str() {
            Some(s) => s,
            None => {
                return ToolResponse::error_with_code(
                    "invalid_arguments",
                    machine_codes::INVALID_ARGUMENTS,
                    &format!("pattern must be a string, got {}", json_type_name(v)),
                    None,
                    Some("validate_regex"),
                )
            }
        },
        None => {
            return ToolResponse::error_with_code(
                "invalid_arguments",
                machine_codes::INVALID_ARGUMENTS,
                "pattern must be a string, got NoneType",
                None,
                Some("validate_regex"),
            )
        }
    };
    let samples = match args.get("samples") {
        Some(Value::Array(arr)) => arr,
        Some(v) => {
            return ToolResponse::error_with_code(
                "invalid_arguments",
                machine_codes::INVALID_ARGUMENTS,
                &format!("samples must be a list, got {}", json_type_name(v)),
                None,
                Some("validate_regex"),
            )
        }
        None => {
            return ToolResponse::error_with_code(
                "invalid_arguments",
                machine_codes::INVALID_ARGUMENTS,
                "samples must be a list, got NoneType",
                None,
                Some("validate_regex"),
            )
        }
    };
    let flags = match args.get("flags") {
        Some(Value::Array(arr)) => {
            // Validate all flags are strings
            let non_str_flags: Vec<usize> = arr
                .iter()
                .enumerate()
                .filter(|(_, v)| !v.is_string())
                .map(|(i, _)| i)
                .collect();
            if !non_str_flags.is_empty() {
                return ToolResponse::error_with_code(
                    "invalid_arguments",
                    machine_codes::INVALID_ARGUMENTS,
                    "All flags must be strings",
                    Some(vec![format!(
                        "Non-string items at indices: {:?}",
                        &non_str_flags[..5.min(non_str_flags.len())]
                    )]),
                    Some("validate_regex"),
                );
            }
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        }
        Some(v) => {
            return ToolResponse::error_with_code(
                "invalid_arguments",
                machine_codes::INVALID_ARGUMENTS,
                &format!("flags must be a list, got {}", json_type_name(v)),
                None,
                Some("validate_regex"),
            )
        }
        None => Vec::new(),
    };
    let ignore_case = args
        .get("ignore_case")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let multiline = args
        .get("multiline")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let dotall = args
        .get("dotall")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let ascii = args.get("ascii").and_then(|v| v.as_bool()).unwrap_or(false);

    if samples.len() > MAX_REGEX_SAMPLES {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!(
                "Number of samples {} exceeds MAX_REGEX_SAMPLES {}",
                samples.len(),
                MAX_REGEX_SAMPLES
            ),
            Some(vec![format!(
                "Maximum {} samples allowed",
                MAX_REGEX_SAMPLES
            )]),
            Some("validate_regex"),
        );
    }

    if pattern.chars().count() > MAX_PATTERN_LENGTH {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!(
                "Pattern length {} exceeds MAX_PATTERN_LENGTH {}",
                pattern.chars().count(),
                MAX_PATTERN_LENGTH
            ),
            Some(vec![format!(
                "Maximum pattern length is {} characters",
                MAX_PATTERN_LENGTH
            )]),
            Some("validate_regex"),
        );
    }

    let mut total_chars: usize = 0;
    let non_str_indices: Vec<usize> = samples
        .iter()
        .enumerate()
        .filter(|(_, v)| !v.is_string())
        .map(|(i, _)| i)
        .collect();
    if !non_str_indices.is_empty() {
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            "All samples must be strings",
            Some(vec![format!(
                "Non-string items at indices: {:?}",
                &non_str_indices[..5.min(non_str_indices.len())]
            )]),
            Some("validate_regex"),
        );
    }
    let long_samples: Vec<usize> = samples
        .iter()
        .enumerate()
        .filter(|(_, v)| {
            v.as_str()
                .is_some_and(|s| s.chars().count() > MAX_REGEX_SAMPLE_LENGTH)
        })
        .map(|(i, _)| i)
        .collect();
    if !long_samples.is_empty() {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!(
                "Sample(s) at indices {:?} exceed MAX_REGEX_SAMPLE_LENGTH {}",
                long_samples, MAX_REGEX_SAMPLE_LENGTH
            ),
            Some(vec![format!(
                "Maximum {} characters per sample",
                MAX_REGEX_SAMPLE_LENGTH
            )]),
            Some("validate_regex"),
        );
    }
    let sample_strs: Vec<String> = samples
        .iter()
        .map(|v| {
            let s = v.as_str().unwrap_or("");
            total_chars += s.chars().count();
            s.to_string()
        })
        .collect();

    if total_chars > MAX_TEXT_LENGTH {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!(
                "Total sample size {} characters exceeds MAX_TEXT_LENGTH {}",
                total_chars, MAX_TEXT_LENGTH
            ),
            Some(vec![format!(
                "Maximum total {} characters across all samples",
                MAX_TEXT_LENGTH
            )]),
            Some("validate_regex"),
        );
    }

    let safety = crate::text::regex_safety_check(pattern);
    if safety.risk == "medium" || safety.risk == "high" {
        return ToolResponse::error_with_code(
            "unsafe_pattern",
            machine_codes::REGEX_UNSAFE,
            &format!(
                "Pattern has {} risk of catastrophic backtracking",
                safety.risk
            ),
            Some(vec![
                "Try a simpler pattern or break it into smaller parts".to_string(),
                "Use the regex_safety_check tool for detailed analysis and suggestions".to_string(),
            ]),
            Some("validate_regex"),
        );
    }

    let flags_clone: Option<Vec<String>> = if flags.is_empty() { None } else { Some(flags) };
    let pattern_owned = pattern.to_string();
    let samples_owned: Vec<String> = sample_strs;
    let refs: Vec<&str> = samples_owned.iter().map(|s| s.as_str()).collect();
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        crate::text::regex_test(
            &pattern_owned,
            &refs,
            flags_clone.as_ref(),
            ignore_case,
            multiline,
            dotall,
            ascii,
        )
    }))
    .unwrap_or_else(|_| crate::text::validate::RegexTestResult {
        valid_pattern: false,
        error: Some("Regex evaluation panicked (possible resource limit)".to_string()),
        results: Vec::new(),
        flags_used: None,
        engine_used: None,
        dialect: None,
        unsupported_features: None,
        execution_error: None,
        policy_allowed: None,
    });

    let flags_used = serde_json::json!({
        "ignore_case": ignore_case,
        "multiline": multiline,
        "dotall": dotall,
        "ascii": ascii,
    });

    let mut result_value = serde_json::json!({
        "valid_pattern": result.valid_pattern,
        "results": result.results,
        "flags_used": flags_used,
    });
    if let Some(ref err) = result.error {
        result_value["error"] = serde_json::json!(err);
    }
    if let Some(ref engine) = result.engine_used {
        result_value["engine_used"] = serde_json::json!(engine);
    }
    if let Some(ref dialect) = result.dialect {
        result_value["dialect"] = serde_json::json!(dialect);
    }
    if let Some(ref unsupported) = result.unsupported_features {
        result_value["unsupported_features"] = serde_json::json!(unsupported);
    }
    if let Some(ref exec_err) = result.execution_error {
        result_value["execution_error"] = serde_json::json!(exec_err);
    }
    if let Some(policy) = result.policy_allowed {
        result_value["policy_allowed"] = serde_json::json!(policy);
    }

    // Emit machine code for unsupported features or ASCII mode
    let mut resp =
        ToolResponse::success(result_value, Some("validate_regex")).with_tool("validate_regex");
    if let Some(ref unsupported) = result.unsupported_features {
        if !unsupported.is_empty() {
            if unsupported.contains(&"ascii_mode".to_string()) {
                resp = resp.with_machine_code(machine_codes::REGEX_ASCII_NOT_SUPPORTED);
            } else {
                resp = resp.with_machine_code(machine_codes::REGEX_UNSUPPORTED_FEATURE);
            }
        }
    }
    resp
}

pub fn regex_safety_check_tool(args: &Value) -> ToolResponse {
    let pattern = match args.get("pattern").and_then(|v| v.as_str()) {
        Some(s) => s,
        None => {
            return ToolResponse::error_with_code(
                "invalid_arguments",
                machine_codes::INVALID_ARGUMENTS,
                "Missing 'pattern' parameter",
                None,
                Some("regex_safety_check"),
            )
        }
    };

    if pattern.chars().count() > MAX_PATTERN_LENGTH {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!("Pattern exceeds {} chars", MAX_PATTERN_LENGTH),
            Some(vec![format!(
                "Maximum pattern length is {} characters",
                MAX_PATTERN_LENGTH
            )]),
            Some("regex_safety_check"),
        );
    }

    let result = crate::text::regex_safety::regex_safety_check(pattern);
    let risk = result.risk.clone();
    let findings_list = result.findings.clone();
    let pattern_length = pattern.chars().count();

    let finding_severity = match risk.as_str() {
        "high" => "error",
        "medium" => "warn",
        _ => "info",
    };
    let envelope_findings: Vec<serde_json::Value> = findings_list
        .iter()
        .map(|f| {
            serde_json::json!({
                "code": f.kind.to_uppercase(),
                "severity": finding_severity,
                "message": f.message.clone(),
                "details": {"pattern_length": pattern_length}
            })
        })
        .collect();

    let machine_code = if risk == "medium" || risk == "high" {
        Some(machine_codes::REGEX_UNSAFE.to_string())
    } else {
        None
    };

    let mut resp = ToolResponse::success(
        serde_json::json!({
            "valid_pattern": result.valid_pattern,
            "risk": result.risk,
            "findings": result.findings,
        }),
        Some("regex_safety_check"),
    )
    .with_tool("regex_safety_check");

    if !envelope_findings.is_empty() {
        resp = resp.with_findings(envelope_findings);
    }
    if let Some(ref code) = machine_code {
        resp = resp.with_machine_code(code);
    }
    resp
}

pub fn regex_finditer_tool(args: &Value) -> ToolResponse {
    let budget_ctx = crate::mcp::budget::for_handler(crate::mcp::budget::ToolBudget::MODERATE);

    let pattern = match _require_str(args, "pattern", "regex_finditer") {
        Ok(s) => s,
        Err(e) => return *e,
    };
    let text = match _require_str(args, "text", "regex_finditer") {
        Ok(s) => s,
        Err(e) => return *e,
    };
    let flags = match args.get("flags") {
        Some(Value::Array(arr)) => {
            let non_str_flags: Vec<usize> = arr
                .iter()
                .enumerate()
                .filter(|(_, v)| !v.is_string())
                .map(|(i, _)| i)
                .collect();
            if !non_str_flags.is_empty() {
                return ToolResponse::error_with_code(
                    "invalid_arguments",
                    machine_codes::INVALID_ARGUMENTS,
                    "All flags must be strings",
                    Some(vec![format!(
                        "Non-string items at indices: {:?}",
                        &non_str_flags[..5.min(non_str_flags.len())]
                    )]),
                    Some("regex_finditer"),
                );
            }
            Some(
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect::<Vec<_>>(),
            )
        }
        Some(v) => {
            return ToolResponse::error_with_code(
                "invalid_arguments",
                machine_codes::INVALID_ARGUMENTS,
                &format!("flags must be a list, got {}", json_type_name(v)),
                None,
                Some("regex_finditer"),
            )
        }
        None => None,
    };
    let max_matches = args
        .get("max_matches")
        .and_then(|v| v.as_u64())
        .unwrap_or(MAX_MATCHES_REGEX as u64) as usize;
    if max_matches < 1 {
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            &format!("max_matches must be at least 1, got {}", max_matches),
            Some(vec!["Set max_matches to 1 or higher".to_string()]),
            Some("regex_finditer"),
        );
    }
    if max_matches > MAX_MATCHES_HARD_CAP {
        return ToolResponse::error_with_code(
            "invalid_arguments",
            machine_codes::INVALID_ARGUMENTS,
            &format!(
                "max_matches {} exceeds maximum of {}",
                max_matches, MAX_MATCHES_HARD_CAP
            ),
            Some(vec![format!(
                "Set max_matches to {} or lower",
                MAX_MATCHES_HARD_CAP
            )]),
            Some("regex_finditer"),
        );
    }
    let max_matches = max_matches.min(MAX_MATCHES_HARD_CAP);
    let include_line_column = args
        .get("include_line_column")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    let include_groups = args
        .get("include_groups")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);

    let byte_len = text.len();
    if byte_len > MAX_TEXT_LENGTH {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!("Text exceeds {} bytes", MAX_TEXT_LENGTH),
            Some(vec![format!(
                "Maximum input length is {} bytes",
                MAX_TEXT_LENGTH
            )]),
            Some("regex_finditer"),
        );
    }

    if pattern.chars().count() > MAX_PATTERN_LENGTH {
        return ToolResponse::error_with_code(
            "input_too_large",
            machine_codes::INPUT_TOO_LARGE,
            &format!(
                "Pattern length {} exceeds MAX_PATTERN_LENGTH {}",
                pattern.chars().count(),
                MAX_PATTERN_LENGTH
            ),
            Some(vec![format!(
                "Maximum pattern length is {} characters",
                MAX_PATTERN_LENGTH
            )]),
            Some("regex_finditer"),
        );
    }

    if budget_ctx.should_stop() {
        return budget_ctx.check_should_stop("regex_finditer").unwrap_err();
    }

    let safety = crate::text::regex_safety_check(pattern);
    if safety.risk == "medium" || safety.risk == "high" {
        return ToolResponse::error_with_code(
            "unsafe_pattern",
            machine_codes::REGEX_UNSAFE,
            &format!(
                "Pattern has {} risk of catastrophic backtracking",
                safety.risk
            ),
            Some(vec![
                "Try a simpler pattern or break it into smaller parts".to_string(),
                "Use the regex_safety_check tool for detailed analysis and suggestions".to_string(),
            ]),
            Some("regex_finditer"),
        );
    }

    let pattern_owned = pattern.to_string();
    let text_owned = text.to_string();
    let flags_owned: Option<Vec<String>> = flags;
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        crate::text::validate::regex_finditer(
            &pattern_owned,
            &text_owned,
            flags_owned.as_ref(),
            max_matches,
            include_line_column,
            include_groups,
        )
    }))
    .unwrap_or_else(|_| crate::text::validate::RegexFindIterResult {
        valid_pattern: false,
        error: Some("Regex evaluation panicked (possible resource limit)".to_string()),
        matches: Vec::new(),
        truncated: false,
        match_count: 0,
        engine_used: None,
        dialect: None,
        unsupported_features: None,
        execution_error: None,
        policy_allowed: None,
    });

    if budget_ctx.should_stop() {
        return budget_ctx.check_should_stop("regex_finditer").unwrap_err();
    }

    let matches: Vec<serde_json::Value> = result
        .matches
        .iter()
        .map(|m| {
            let mut obj = serde_json::json!({
                "match": m.m,
                "span": m.span,
                "groups": m.groups,
                "groupdict": m.group_dict,
            });
            if let (Some(line), Some(column)) = (m.line, m.column) {
                obj["line"] = serde_json::json!(line);
                obj["column"] = serde_json::json!(column);
            }
            obj
        })
        .collect();

    let mut resp = ToolResponse::success(
        serde_json::json!({
            "valid_pattern": result.valid_pattern,
            "matches": matches,
            "truncated": result.truncated,
            "match_count": result.match_count,
            "error": result.error,
            "engine_used": result.engine_used,
            "dialect": result.dialect,
            "unsupported_features": result.unsupported_features,
            "execution_error": result.execution_error,
            "policy_allowed": result.policy_allowed,
        }),
        Some("regex_finditer"),
    )
    .with_tool("regex_finditer");

    // Emit REGEX_UNSUPPORTED_FEATURE for unsupported dialect constructs
    if let Some(ref unsupported) = result.unsupported_features {
        if !unsupported.is_empty() {
            resp = resp.with_machine_code(machine_codes::REGEX_UNSUPPORTED_FEATURE);
        }
    }
    // Emit INTERNAL_ERROR for runtime execution errors
    if resp
        .result
        .as_ref()
        .and_then(|r| r.get("execution_error"))
        .is_some_and(|v| !v.is_null())
        && resp.machine_code.is_none()
    {
        resp = resp.with_machine_code(machine_codes::INTERNAL_ERROR);
    }
    resp
}