monaa-guard 0.1.0

Open-source Apache-2.0 Pure-Rust MCP 2026-07-28 wire firewall, local token compactor, and BYOK shim
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
use std::fs::{self, OpenOptions};
use std::io::Write;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Component, Path, PathBuf};

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::error::GuardError;

/// Launch promo cutoff: 2026-12-31T23:59:59Z (`1_798_761_599_000` ms UTC).
pub const PROMO_EXPIRES_AT_MS: u64 = 1_798_761_599_000;
pub const PROMO_DAILY_CALL_CAP: u32 = u32::MAX;
pub const STANDARD_DAILY_CALL_CAP: u32 = u32::MAX;
pub const FREE_DAILY_CALL_CAP: u32 = u32::MAX;
pub const MAX_FREE_UPSTREAM_SERVERS: usize = usize::MAX;
const MS_PER_DAY: u64 = 86_400_000;

/// Free local stdio wire checks & payload compaction are 100% unlimited forever (no daily call caps).
pub fn free_daily_call_cap(_now_ms: u64) -> u32 {
    u32::MAX
}

pub fn default_daily_quota_path() -> PathBuf {
    if let Some(home) = std::env::var_os("HOME")
        .filter(|h| !h.is_empty())
        .or_else(|| std::env::var_os("USERPROFILE").filter(|h| !h.is_empty()))
    {
        return PathBuf::from(home)
            .join(".monaa-guard")
            .join("daily_quota.json");
    }
    PathBuf::from(".monaa-guard").join("daily_quota.json")
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GuardPolicy {
    pub free_daily_call_cap: u32,
    pub allowed_origins: Vec<String>,
    pub blocked_path_patterns: Vec<String>,
    pub blocked_command_patterns: Vec<String>,
    pub usage_file_path: PathBuf,
}

impl Default for GuardPolicy {
    fn default() -> Self {
        Self {
            free_daily_call_cap: FREE_DAILY_CALL_CAP,
            allowed_origins: vec![
                "http://localhost".to_string(),
                "http://127.0.0.1".to_string(),
                "vscode-webview://".to_string(),
                "cursor://".to_string(),
            ],
            blocked_path_patterns: vec![
                ".env".to_string(),
                "id_rsa".to_string(),
                ".pem".to_string(),
                ".aws/credentials".to_string(),
                "/etc/shadow".to_string(),
            ],
            blocked_command_patterns: vec![
                "rm -rf".to_string(),
                "rm -fr".to_string(),
                "sudo ".to_string(),
                "mkfs".to_string(),
                "dd if=".to_string(),
            ],
            usage_file_path: default_daily_quota_path(),
        }
    }
}

impl GuardPolicy {
    pub fn load_or_default(path: &Path) -> Result<Self, GuardError> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let raw = fs::read_to_string(path)?;
        toml::from_str::<Self>(&raw)
            .map_err(|e| GuardError::Config(format!("invalid monaa-guard.toml: {e}")))
    }

    pub fn to_toml_string(&self) -> Result<String, GuardError> {
        toml::to_string_pretty(self)
            .map_err(|e| GuardError::Config(format!("failed serializing monaa-guard.toml: {e}")))
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct DailyUsageRecord {
    utc_day: u64,
    calls_today: u32,
    #[serde(default)]
    max_seen_utc_ms: u64,
}

#[derive(Debug, Clone)]
pub struct LocalWireGuard {
    pub policy: GuardPolicy,
    pub utc_day: u64,
    pub calls_today: u32,
    pub max_seen_utc_ms: u64,
}

impl LocalWireGuard {
    fn read_record(path: &Path) -> Option<DailyUsageRecord> {
        fs::read_to_string(path)
            .ok()
            .and_then(|raw| serde_json::from_str::<DailyUsageRecord>(&raw).ok())
    }

    pub fn new(policy: GuardPolicy, now_ms: u64) -> Self {
        let saved = Self::read_record(&policy.usage_file_path);
        let max_seen_utc_ms = saved
            .as_ref()
            .map_or(now_ms, |rec| now_ms.max(rec.max_seen_utc_ms));
        let utc_day = max_seen_utc_ms / MS_PER_DAY;
        let calls_today = match saved {
            Some(rec) if rec.utc_day == utc_day => rec.calls_today,
            _ => 0,
        };
        Self {
            policy,
            utc_day,
            calls_today,
            max_seen_utc_ms,
        }
    }

    pub fn active_daily_cap(&self, now_ms: u64) -> u32 {
        let effective_now = now_ms.max(self.max_seen_utc_ms);
        free_daily_call_cap(effective_now)
    }

    pub fn validate_origin(&self, origin: Option<&str>) -> Result<(), GuardError> {
        let Some(raw) = origin.map(str::trim).filter(|s| !s.is_empty()) else {
            return Ok(());
        };
        let lower = raw.to_ascii_lowercase();
        let allowed = self
            .policy
            .allowed_origins
            .iter()
            .any(|prefix| lower.starts_with(&prefix.to_ascii_lowercase()));
        if !allowed {
            return Err(GuardError::PolicyDenied(format!(
                "disallowed Origin `{raw}` blocked by local MCP wire policy"
            )));
        }
        Ok(())
    }

    /// Runs public wire checks and records monotonic UTC usage telemetry (unlimited free local calls).
    pub fn evaluate_local_wire(
        &mut self,
        now_ms: u64,
        tool_name: &str,
        args_json: &Value,
        enforce_free_cap: bool,
    ) -> Result<(), GuardError> {
        let tool_lower = tool_name.to_ascii_lowercase();
        let mut has_monaa_or_internal = self_protect_check_raw(&tool_lower, tool_name, true)?;
        let mut has_re_tool = contains_re_tool_token(&tool_lower);

        let disk_max =
            Self::read_record(&self.policy.usage_file_path).map_or(0, |r| r.max_seen_utc_ms);
        let effective_now_ms = now_ms.max(self.max_seen_utc_ms).max(disk_max);
        let advanced_past_cutoff =
            self.max_seen_utc_ms <= PROMO_EXPIRES_AT_MS && effective_now_ms > PROMO_EXPIRES_AT_MS;
        self.max_seen_utc_ms = effective_now_ms;

        let day = effective_now_ms / MS_PER_DAY;
        if day > self.utc_day {
            self.utc_day = day;
            self.calls_today = 0;
        } else if advanced_past_cutoff {
            let _ = self.persist_daily_usage();
        }

        self.check_text_safety(tool_name)?;
        self.scan_json_leaves_with_signals(
            args_json,
            0,
            &mut has_re_tool,
            &mut has_monaa_or_internal,
        )?;
        if has_re_tool && has_monaa_or_internal {
            return Err(GuardError::PolicyDenied(
                "SelfProtectionBlock: binary disassembly/MITM tool targeting MONAA asset is prohibited".to_string(),
            ));
        }

        if enforce_free_cap {
            self.calls_today = self.calls_today.saturating_add(1);
            self.persist_daily_usage()?;
        }

        Ok(())
    }

    pub fn scan_params_self_protection(
        &self,
        params: &Value,
        depth: usize,
    ) -> Result<(), GuardError> {
        if depth > 16 {
            return Err(GuardError::PolicyDenied(
                "parameter nesting depth exceeded".to_string(),
            ));
        }
        match params {
            Value::String(s) => check_self_protection_text(s),
            Value::Array(items) => {
                for item in items {
                    self.scan_params_self_protection(item, depth.saturating_add(1))?;
                }
                Ok(())
            }
            Value::Object(map) => {
                for (k, val) in map {
                    if matches!(
                        k.as_str(),
                        "origin" | "mcp_method" | "mcp_name" | "traceparent"
                    ) {
                        continue;
                    }
                    check_self_protection_text(k)?;
                    self.scan_params_self_protection(val, depth.saturating_add(1))?;
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }

    fn persist_daily_usage(&self) -> Result<(), GuardError> {
        if let Some(parent) = self.policy.usage_file_path.parent() {
            if !parent.as_os_str().is_empty() {
                fs::create_dir_all(parent)?;
            }
        }
        let rec = DailyUsageRecord {
            utc_day: self.utc_day,
            calls_today: self.calls_today,
            max_seen_utc_ms: self.max_seen_utc_ms,
        };
        let bytes = serde_json::to_vec(&rec)
            .map_err(|e| GuardError::Config(format!("usage encode error: {e}")))?;
        let mut f = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&self.policy.usage_file_path)?;

        #[cfg(unix)]
        {
            if let Ok(meta) = f.metadata() {
                let mut perms = meta.permissions();
                if (perms.mode() & 0o777) != 0o600 {
                    perms.set_mode(0o600);
                    let _ = fs::set_permissions(&self.policy.usage_file_path, perms);
                }
            }
        }

        f.write_all(&bytes)?;
        f.flush()?;
        f.sync_all()?;
        Ok(())
    }

    fn scan_json_leaves_with_signals(
        &self,
        value: &Value,
        depth: usize,
        has_re_tool: &mut bool,
        has_monaa_or_internal: &mut bool,
    ) -> Result<(), GuardError> {
        if depth > 16 {
            return Err(GuardError::PolicyDenied(
                "argument nesting depth exceeded".to_string(),
            ));
        }
        match value {
            Value::String(s) => {
                self.check_text_safety(s)?;
                let lower = s.to_ascii_lowercase();
                if contains_re_tool_token(&lower) {
                    *has_re_tool = true;
                }
                if self_protect_check_raw(&lower, s, false)? {
                    *has_monaa_or_internal = true;
                }
                Ok(())
            }
            Value::Array(items) => {
                for item in items {
                    self.scan_json_leaves_with_signals(
                        item,
                        depth.saturating_add(1),
                        has_re_tool,
                        has_monaa_or_internal,
                    )?;
                }
                Ok(())
            }
            Value::Object(map) => {
                for val in map.values() {
                    self.scan_json_leaves_with_signals(
                        val,
                        depth.saturating_add(1),
                        has_re_tool,
                        has_monaa_or_internal,
                    )?;
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }

    fn check_text_safety(&self, raw: &str) -> Result<(), GuardError> {
        check_self_protection_text(raw)?;
        let lower = raw.to_ascii_lowercase();
        for pat in &self.policy.blocked_command_patterns {
            if !pat.is_empty() && lower.contains(&pat.to_ascii_lowercase()) {
                return Err(GuardError::PolicyDenied(format!(
                    "blocked dangerous command pattern `{pat}`"
                )));
            }
        }
        for pat in &self.policy.blocked_path_patterns {
            if !pat.is_empty() && lower.contains(&pat.to_ascii_lowercase()) {
                return Err(GuardError::PolicyDenied(format!(
                    "blocked sensitive secret path pattern `{pat}`"
                )));
            }
        }
        Ok(())
    }
}

const SELF_PROTECTED_IDENTIFIERS: &[&str] = &[
    "monaa-billing",
    "monaa-mcp",
    "monaa-saas-cloud",
    "theaihumanizer",
    "1:3:1 cadence",
    "monaa_license_cert",
    ".monaa-guard",
    "daily_quota.json",
    "license.json",
];

const RE_TOOLS: &[&str] = &[
    "objdump",
    "otool",
    "nm",
    "strings",
    "radare2",
    "r2",
    "ghidra",
    "ida",
    "lldb",
    "gdb",
    "dtrace",
    "strace",
    "frida",
    "mitmproxy",
    "tcpdump",
    "wireshark",
];

fn contains_re_tool_token(lower: &str) -> bool {
    for raw_tok in lower.split(|c: char| {
        c.is_whitespace()
            || matches!(
                c,
                ';' | '|' | '&' | '(' | ')' | '"' | '\'' | '=' | '<' | '>' | ','
            )
    }) {
        let base = raw_tok
            .trim()
            .rsplit(['/', '\\'])
            .next()
            .unwrap_or("")
            .trim_end_matches(".exe");
        if RE_TOOLS.contains(&base) {
            return true;
        }
    }
    false
}

fn self_protect_check_raw(lower: &str, raw: &str, _is_tool_name: bool) -> Result<bool, GuardError> {
    for ident in SELF_PROTECTED_IDENTIFIERS {
        if lower.contains(ident) {
            return Err(GuardError::PolicyDenied(format!(
                "SelfProtectionBlock: targeting protected MONAA asset `{ident}` is prohibited"
            )));
        }
    }

    // Resolve symlink / traversal paths targeting monaa* binaries or .monaa* state files.
    check_path_candidates_self_protection(raw)?;

    let mentions_monaa = lower.contains("monaa")
        || lower.contains("monaa-guard")
        || lower.contains("monaa.tech")
        || lower.contains("monaa.dev");
    Ok(mentions_monaa)
}

/// Validates user ideas and untrusted arguments against MONAA self-targeting, RE tools, and symlink/traversal escapes.
pub fn check_self_protection_text(raw: &str) -> Result<(), GuardError> {
    let lower = raw.to_ascii_lowercase();
    let mentions_monaa = self_protect_check_raw(&lower, raw, false)?;
    if contains_re_tool_token(&lower) && mentions_monaa {
        return Err(GuardError::PolicyDenied(
            "SelfProtectionBlock: reverse-engineering or MITM tool targeting MONAA asset is prohibited".to_string(),
        ));
    }
    Ok(())
}

/// Validates `monaa-guard init` prototype ideas: permits normal workflow references while blocking clone/RE ideas targeting MONAA assets.
pub fn check_init_idea_protection(raw: &str) -> Result<(), GuardError> {
    check_self_protection_text(raw)?;
    let lower = raw.to_ascii_lowercase();
    let mentions_monaa = lower.contains("monaa")
        || lower.contains("monaa-guard")
        || lower.contains("monaa.tech")
        || lower.contains("monaa.dev");
    if mentions_monaa {
        const CLONE_INTENTS: &[&str] = &[
            "clone",
            "replica",
            "replicate",
            "reverse",
            "extract",
            "dump",
            "scrape",
            "bypass",
            "crack",
            "decompile",
            "disassemble",
            "internals",
            "steal",
            "spoof",
            "forge",
        ];
        if CLONE_INTENTS.iter().any(|kw| lower.contains(kw)) {
            return Err(GuardError::PolicyDenied(
                "SelfProtectionBlock: cloning or extracting protected MONAA assets is prohibited"
                    .to_string(),
            ));
        }
    }
    Ok(())
}

/// Validates a filesystem target path via symlink and ancestor canonicalization against `.monaa*` / `monaa*` binaries.
pub fn check_canonical_path_protection(target: &Path) -> Result<(), GuardError> {
    let raw_str = target.to_string_lossy();
    check_single_path_candidate(&raw_str)
}

fn check_path_candidates_self_protection(raw: &str) -> Result<(), GuardError> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Ok(());
    }
    if (!trimmed.contains(char::is_whitespace) || fs::symlink_metadata(trimmed).is_ok())
        && !looks_like_http_url(trimmed)
    {
        check_single_path_candidate(trimmed)?;
    }
    for tok in raw.split(|c: char| {
        c.is_whitespace()
            || matches!(
                c,
                ';' | '|' | '&' | '(' | ')' | '[' | ']' | '=' | '<' | '>' | ','
            )
    }) {
        let cleaned = tok
            .trim()
            .trim_matches(['"', '\'', '(', ')', '[', ']', '`']);
        if cleaned.is_empty() || cleaned == trimmed {
            continue;
        }
        check_single_path_candidate(cleaned)?;
    }
    Ok(())
}

fn looks_like_http_url(s: &str) -> bool {
    let clean = s.trim_start_matches(['(', '[', '"', '\'', '`']);
    clean.starts_with("http://") || clean.starts_with("https://")
}

fn normalize_lexical(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for comp in path.components() {
        match comp {
            Component::Prefix(p) => out.push(p.as_os_str()),
            Component::RootDir => out.push(Component::RootDir.as_os_str()),
            Component::CurDir => {}
            Component::ParentDir => {
                if !out.pop() {
                    out.push("..");
                }
            }
            Component::Normal(s) => out.push(s),
        }
    }
    out
}

fn is_protected_resolved_path(path: &Path, explicit_abs_sym_or_trav: bool) -> bool {
    for comp in path.components() {
        if let Component::Normal(seg) = comp {
            let s = seg.to_string_lossy().to_ascii_lowercase();
            if s == ".monaa"
                || s == ".monaa-guard"
                || s == "monaa-billing"
                || s == "monaa-saas-cloud"
                || s == "monaa-mcp"
                || s == "daily_quota.json"
                || s == "license.json"
            {
                return true;
            }
        }
    }

    if !path.is_dir() {
        if let Some(fname) = path.file_name().and_then(|f| f.to_str()) {
            let lower_name = fname.to_ascii_lowercase();
            if lower_name.starts_with("monaa") {
                return true;
            }
        }
    }

    if explicit_abs_sym_or_trav {
        let joined = path.to_string_lossy().to_ascii_lowercase();
        if joined.contains("/monaa-billing")
            || joined.contains("/monaa-saas-cloud")
            || joined.contains("/monaa-mcp")
            || joined.contains("/.monaa")
            || (!path.is_dir() && joined.contains("/monaa-guard"))
        {
            return true;
        }
    }
    false
}

fn check_single_path_candidate(candidate: &str) -> Result<(), GuardError> {
    if candidate.is_empty() || looks_like_http_url(candidate) {
        return Ok(());
    }
    let looks_path = candidate.contains('/')
        || candidate.contains('\\')
        || candidate.starts_with('.')
        || fs::symlink_metadata(candidate).is_ok();
    if !looks_path {
        return Ok(());
    }

    let path = Path::new(candidate);
    let has_abs_or_trav = candidate.starts_with('/') || candidate.contains("..");
    let norm = normalize_lexical(path);
    if is_protected_resolved_path(&norm, has_abs_or_trav) {
        return Err(GuardError::PolicyDenied(format!(
            "SelfProtectionBlock: path traversal into protected MONAA path `{candidate}` blocked"
        )));
    }

    if let Ok(meta) = fs::symlink_metadata(path) {
        let is_sym = meta.file_type().is_symlink();
        if let Ok(canon) = fs::canonicalize(path) {
            if is_protected_resolved_path(&canon, is_sym || has_abs_or_trav) {
                return Err(GuardError::PolicyDenied(format!(
                    "SelfProtectionBlock: symlink/canonical path target `{candidate}` resolves to protected MONAA asset"
                )));
            }
        } else if is_sym {
            if let Ok(link_target) = fs::read_link(path) {
                let resolved_link = if link_target.is_relative() {
                    normalize_lexical(
                        &path
                            .parent()
                            .unwrap_or_else(|| Path::new("."))
                            .join(&link_target),
                    )
                } else {
                    normalize_lexical(&link_target)
                };
                if is_protected_resolved_path(&resolved_link, true) {
                    return Err(GuardError::PolicyDenied(format!(
                        "SelfProtectionBlock: symlink `{candidate}` points to protected MONAA asset"
                    )));
                }
            }
        }
        return Ok(());
    }

    // Resolve deepest existing ancestor (catches `symlink_dir/subfile` or `a/../.monaa-guard/x`).
    let mut suffix_rev: Vec<std::ffi::OsString> = Vec::new();
    let mut probe = path;
    while let (Some(parent), Some(name)) = (probe.parent(), probe.file_name()) {
        suffix_rev.push(name.to_os_string());
        if !parent.as_os_str().is_empty() {
            if let Ok(meta) = fs::symlink_metadata(parent) {
                let anc_sym = meta.file_type().is_symlink();
                if let Ok(mut resolved) = fs::canonicalize(parent) {
                    for seg in suffix_rev.iter().rev() {
                        resolved.push(seg);
                    }
                    let normalized = normalize_lexical(&resolved);
                    if is_protected_resolved_path(&normalized, anc_sym || has_abs_or_trav) {
                        return Err(GuardError::PolicyDenied(format!(
                            "SelfProtectionBlock: ancestor symlink/traversal `{candidate}` resolves to protected MONAA asset"
                        )));
                    }
                }
                break;
            }
        }
        probe = parent;
    }

    Ok(())
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetBalanceMetadata {
    pub asset_symbol: String,
    pub balance_fixed: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FinancialCallMetadata {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asset_symbol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contract_symbol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_qty_fixed: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quote_notional_fixed: Option<String>,
    #[serde(default)]
    pub balances: Vec<AssetBalanceMetadata>,
}

/// Identifies financial/exchange/order MCP tools gated by the closed-source `$5,000` multi-asset USD cap.
pub fn is_financial_mcp_tool(tool_name: &str) -> bool {
    let lower = tool_name.trim().to_ascii_lowercase();
    if lower.contains("fapi") || lower.contains("dapi") {
        return true;
    }
    let mut tokens: Vec<String> = Vec::new();
    let mut current = String::new();
    let mut prev_lower = false;
    for ch in tool_name.chars() {
        if !ch.is_ascii_alphanumeric() {
            if !current.is_empty() {
                tokens.push(current.to_ascii_lowercase());
                current.clear();
            }
            prev_lower = false;
            continue;
        }
        if ch.is_ascii_uppercase() && prev_lower && !current.is_empty() {
            tokens.push(current.to_ascii_lowercase());
            current.clear();
        }
        prev_lower = ch.is_ascii_lowercase() || ch.is_ascii_digit();
        current.push(ch);
    }
    if !current.is_empty() {
        tokens.push(current.to_ascii_lowercase());
    }
    tokens.iter().any(|tok| {
        matches!(
            tok.as_str(),
            "order"
                | "orders"
                | "trade"
                | "trades"
                | "swap"
                | "swaps"
                | "future"
                | "futures"
                | "dapi"
                | "fapi"
                | "spot"
                | "margin"
                | "withdraw"
                | "withdrawal"
        )
    })
}

fn sanitize_ticker(raw: &str) -> Option<String> {
    let upper = raw.trim().to_ascii_uppercase();
    if !upper.is_empty()
        && upper.len() <= 32
        && upper
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
    {
        Some(upper)
    } else {
        None
    }
}

fn sanitize_decimal_str(val: &Value) -> Option<String> {
    let raw = match val {
        Value::String(s) => s.trim().to_string(),
        Value::Number(n) => n.to_string(),
        _ => return None,
    };
    if raw.is_empty() || raw.len() > 48 || raw.starts_with('-') || raw.starts_with('+') {
        return None;
    }
    let mut dots = 0usize;
    let mut digits = 0usize;
    for ch in raw.bytes() {
        if ch == b'.' {
            dots += 1;
        } else if ch.is_ascii_digit() {
            digits += 1;
        } else {
            return None;
        }
    }
    if dots <= 1 && digits > 0 {
        Some(raw)
    } else {
        None
    }
}

fn pick_sanitized_ticker(map: &serde_json::Map<String, Value>, keys: &[&str]) -> Option<String> {
    for k in keys {
        if let Some(s) = map
            .get(*k)
            .and_then(Value::as_str)
            .and_then(sanitize_ticker)
        {
            return Some(s);
        }
    }
    None
}

fn pick_sanitized_decimal(map: &serde_json::Map<String, Value>, keys: &[&str]) -> Option<String> {
    for k in keys {
        if let Some(s) = map.get(*k).and_then(sanitize_decimal_str) {
            return Some(s);
        }
    }
    None
}

fn extract_balances_into(val: &Value, out: &mut Vec<AssetBalanceMetadata>) {
    match val {
        Value::Object(map) => {
            if let Some(sym) =
                pick_sanitized_ticker(map, &["asset_symbol", "asset", "coin", "currency"])
            {
                if let Some(bal) = pick_sanitized_decimal(
                    map,
                    &[
                        "balance_fixed",
                        "marginBalance",
                        "margin_balance",
                        "walletBalance",
                        "wallet_balance",
                        "balance",
                        "free",
                        "available",
                        "equity",
                    ],
                ) {
                    out.push(AssetBalanceMetadata {
                        asset_symbol: sym,
                        balance_fixed: bal,
                    });
                }
                return;
            }
            for (k, v) in map {
                if let (Some(sym), Some(bal)) = (sanitize_ticker(k), sanitize_decimal_str(v)) {
                    out.push(AssetBalanceMetadata {
                        asset_symbol: sym,
                        balance_fixed: bal,
                    });
                }
            }
        }
        Value::Array(items) => {
            for item in items {
                extract_balances_into(item, out);
            }
        }
        _ => {}
    }
}

/// Extracts strictly sanitized `(asset_symbol, balance_fixed, order_qty_fixed, contract_symbol)` metadata
/// from financial MCP calls (`0` exchange API keys, secrets, or signatures ever copied or forwarded).
pub fn extract_sanitized_financial_metadata(
    tool_name: &str,
    args: &Value,
) -> Option<FinancialCallMetadata> {
    if !is_financial_mcp_tool(tool_name) {
        return None;
    }
    let Some(map) = args.as_object() else {
        return Some(FinancialCallMetadata::default());
    };

    let contract_symbol = pick_sanitized_ticker(
        map,
        &["contract_symbol", "symbol", "pair", "instrument", "market"],
    );
    let asset_symbol = pick_sanitized_ticker(
        map,
        &[
            "asset_symbol",
            "marginAsset",
            "margin_asset",
            "collateral",
            "asset",
            "baseAsset",
            "base_asset",
            "coin",
        ],
    );
    let order_qty_fixed = pick_sanitized_decimal(
        map,
        &[
            "order_qty_fixed",
            "quantity",
            "qty",
            "orderQty",
            "contracts",
            "amount",
        ],
    );
    let quote_notional_fixed = pick_sanitized_decimal(
        map,
        &[
            "quote_notional_fixed",
            "quoteOrderQty",
            "quote_order_qty",
            "notional",
        ],
    );

    let mut balances: Vec<AssetBalanceMetadata> = Vec::new();
    for k in [
        "balances",
        "account_balances",
        "margin_balances",
        "wallet",
        "assets",
    ] {
        if let Some(bal_val) = map.get(k) {
            extract_balances_into(bal_val, &mut balances);
        }
    }
    if balances.is_empty() {
        if let (Some(sym), Some(bal)) = (
            asset_symbol.as_ref(),
            pick_sanitized_decimal(
                map,
                &[
                    "balance_fixed",
                    "marginBalance",
                    "margin_balance",
                    "walletBalance",
                    "balance",
                    "equity",
                ],
            ),
        ) {
            balances.push(AssetBalanceMetadata {
                asset_symbol: sym.clone(),
                balance_fixed: bal,
            });
        }
    }
    balances.sort_by(|a, b| a.asset_symbol.cmp(&b.asset_symbol));

    Some(FinancialCallMetadata {
        asset_symbol,
        contract_symbol,
        order_qty_fixed,
        quote_notional_fixed,
        balances,
    })
}