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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Instant;

use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::Command;
use tokio::sync::Mutex;

use crate::cloud_shim::{
    CloudGuardAction, CloudGuardClient, CloudVerifyResponse, MetadataOnlyVerifyRequest,
};
use crate::compactor::{
    compact_text_payload, default_savings_path, format_trial_reminder_notification,
    load_savings_ledger, record_local_savings, render_savings_receipt, CompactionMetrics,
};
use crate::doctor::run_doctor_check;
use crate::error::GuardError;
use crate::license::resolve_cloud_base_url;
use crate::now_epoch_ms;
use crate::policy::{
    extract_sanitized_financial_metadata, is_financial_mcp_tool, GuardPolicy, LocalWireGuard,
};

#[derive(Debug, Clone, Default)]
pub struct McpHeaders {
    pub mcp_method: Option<String>,
    pub mcp_name: Option<String>,
    pub origin: Option<String>,
    pub traceparent: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcErrorPayload {
    pub code: i64,
    pub message: String,
}

#[derive(Debug, Clone)]
pub struct ClientShimState {
    pub session_id: String,
    pub wire_guard: LocalWireGuard,
    pub cloud: Option<CloudGuardClient>,
    pub msg_counter: u64,
    pub pending_notifications: Vec<Value>,
    pub savings_path_override: Option<PathBuf>,
}

impl ClientShimState {
    pub fn active_daily_cap(&self, now_ms: u64) -> u32 {
        self.wire_guard.active_daily_cap(now_ms)
    }

    pub fn push_trial_reminder_from_cloud(&mut self, resp: &CloudVerifyResponse) {
        let Some(stage) = resp.trial_reminder_stage.as_deref() else {
            return;
        };
        let path = self
            .savings_path_override
            .clone()
            .unwrap_or_else(default_savings_path);
        let ledger = load_savings_ledger(&path);
        if let Some((card, notification)) =
            format_trial_reminder_notification(stage, resp.trial_remaining_ms, &ledger)
        {
            eprintln!("[monaa-guard]\n{card}");
            self.pending_notifications.push(notification);
        }
    }
}

/// Validates W3C Trace Context v1 `00-<32hex>-<16hex>-<2hex>` in O(1) without regex allocation.
pub fn validate_w3c_traceparent(tp: &str) -> bool {
    let bytes = tp.trim().as_bytes();
    if bytes.len() != 55 || bytes[2] != b'-' || bytes[35] != b'-' || bytes[52] != b'-' {
        return false;
    }
    if &bytes[0..2] != b"00" {
        return false;
    }
    let trace_id = &bytes[3..35];
    let parent_id = &bytes[36..52];
    let flags = &bytes[53..55];

    let all_lower_hex = |slice: &[u8]| {
        slice
            .iter()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(b))
    };
    let any_nonzero = |slice: &[u8]| slice.iter().any(|&b| b != b'0');

    all_lower_hex(trace_id)
        && any_nonzero(trace_id)
        && all_lower_hex(parent_id)
        && any_nonzero(parent_id)
        && all_lower_hex(flags)
}

fn synthesize_traceparent(now_ms: u64, seq: u64) -> String {
    let digest = Sha256::digest(format!("monaa-guard-trace:{now_ms}:{seq}").as_bytes());
    let mut trace_hex = hex::encode(&digest[0..16]);
    let mut span_hex = hex::encode(&digest[16..24]);
    if trace_hex.chars().all(|c| c == '0') {
        trace_hex = "0123456789abcdef0123456789abcdef".to_string();
    }
    if span_hex.chars().all(|c| c == '0') {
        span_hex = "1122334455667788".to_string();
    }
    format!("00-{trace_hex}-{span_hex}-01")
}

/// Enforces open-standard MCP 2026-07-28 wire checks & forwards metadata-only hashes to cloud when Pro cert is present.
pub async fn inspect_outbound_request(
    state: &mut ClientShimState,
    headers: &McpHeaders,
    body: &mut Value,
    now_ms: u64,
) -> Result<(), GuardError> {
    let origin = headers
        .origin
        .as_deref()
        .or_else(|| body.pointer("/params/_meta/origin").and_then(Value::as_str));
    state.wire_guard.validate_origin(origin)?;

    let method = body
        .get("method")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .ok_or_else(|| GuardError::Schema("JSON-RPC request missing method".to_string()))?
        .to_string();

    let meta_method = body
        .pointer("/params/_meta/mcp_method")
        .and_then(Value::as_str)
        .map(str::trim);
    if let Some(expected_method) = headers.mcp_method.as_deref().map(str::trim).or(meta_method) {
        if expected_method != method {
            return Err(GuardError::MethodMismatch(format!(
                "Mcp-Method `{expected_method}` does not match body method `{method}`"
            )));
        }
    }

    if method == "tools/call" {
        let tool_name = body
            .pointer("/params/name")
            .and_then(Value::as_str)
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| GuardError::Schema("tools/call missing params.name".to_string()))?
            .to_string();

        let meta_name = body
            .pointer("/params/_meta/mcp_name")
            .and_then(Value::as_str)
            .map(str::trim);
        if let Some(expected_name) = headers.mcp_name.as_deref().map(str::trim).or(meta_name) {
            if expected_name != tool_name {
                return Err(GuardError::MethodMismatch(format!(
                    "Mcp-Name `{expected_name}` does not match params.name `{tool_name}`"
                )));
            }
        }

        let args = body
            .pointer("/params/arguments")
            .cloned()
            .unwrap_or_else(|| Value::Object(Map::new()));

        if let Some(params) = body.get("params") {
            state.wire_guard.scan_params_self_protection(params, 0)?;
        }

        // Local wire checks always run cleanly first (self-protection + dangerous patterns)
        let enforce_local_cap = state.cloud.is_none();
        state
            .wire_guard
            .evaluate_local_wire(now_ms, &tool_name, &args, enforce_local_cap)?;

        let financial_metadata = extract_sanitized_financial_metadata(&tool_name, &args);
        let is_financial = financial_metadata.is_some() || is_financial_mcp_tool(&tool_name);

        // When MONAA_LICENSE_CERT is configured, forward strictly metadata (tool_name + SHA-256 args hash + sanitized balance metadata ONLY!)
        if let Some(cloud_client) = state.cloud.clone() {
            let meta_req = MetadataOnlyVerifyRequest {
                session_id: state.session_id.clone(),
                action: CloudGuardAction::ToolsCall,
                tools_list: None,
                tool_name: Some(tool_name),
                args_sha256: Some(CloudGuardClient::hash_args_metadata(&args)),
                financial_metadata,
            };
            match cloud_client.canonicalize_and_verify(meta_req).await {
                Ok(resp) => {
                    state.push_trial_reminder_from_cloud(&resp);
                }
                Err(GuardError::AccountCapExceeded(reason)) => {
                    return Err(GuardError::AccountCapExceeded(reason));
                }
                Err(GuardError::CloudRugPull(reason)) => {
                    return Err(GuardError::CloudRugPull(reason));
                }
                Err(GuardError::License(msg)) => {
                    if is_financial {
                        return Err(GuardError::AccountCapExceeded(msg));
                    }
                    eprintln!(
                        "[monaa-guard] 7-day cloud trial inactive ({msg}); continuing on 100% unlimited free local compactor & 27 us wire shield. {}",
                        crate::license::UPGRADE_CTA_MESSAGE
                    );
                }
                Err(err) => return Err(err),
            }
        } else if is_financial {
            return Err(GuardError::AccountCapExceeded(
                "Financial/exchange MCP calls require cloud $5,000 multi-asset cap verification via MONAA_LICENSE_CERT; accounts >$5,000 use https://monaa.dev".to_string(),
            ));
        }
    }

    let existing_tp = headers.traceparent.clone().or_else(|| {
        body.pointer("/params/_meta/traceparent")
            .and_then(Value::as_str)
            .map(str::to_string)
    });

    let valid_tp = match existing_tp {
        Some(tp) => {
            if !validate_w3c_traceparent(&tp) {
                return Err(GuardError::TraceInvalid(format!(
                    "malformed W3C traceparent `{tp}`"
                )));
            }
            tp
        }
        None => {
            state.msg_counter = state.msg_counter.saturating_add(1);
            synthesize_traceparent(now_ms, state.msg_counter)
        }
    };

    if let Some(root_obj) = body.as_object_mut() {
        let params_entry = root_obj
            .entry("params")
            .or_insert_with(|| Value::Object(Map::new()));
        if let Some(params_obj) = params_entry.as_object_mut() {
            let meta_entry = params_obj
                .entry("_meta")
                .or_insert_with(|| Value::Object(Map::new()));
            if let Some(meta_obj) = meta_entry.as_object_mut() {
                meta_obj.insert("traceparent".to_string(), Value::String(valid_tp));
            }
        }
    }

    Ok(())
}

/// Compacts verbose upstream responses locally (`0` cloud calls) and, for `tools/list`, forwards tool schema metadata to closed-source cloud when Pro/Trial cert is configured.
pub async fn inspect_upstream_response(
    state: &mut ClientShimState,
    body: &mut Value,
) -> Result<(), GuardError> {
    let compact_metrics = crate::compactor::compact_upstream_response(body);
    if compact_metrics.raw_bytes > 0 {
        let savings_path = crate::compactor::default_savings_path();
        let _ = crate::compactor::record_local_savings(
            &savings_path,
            &compact_metrics,
            crate::now_epoch_ms(),
        );
    }

    if body.pointer("/result/tools").is_none() && body.get("tools").is_none() {
        return Ok(());
    }

    if let Some(cloud_client) = state.cloud.clone() {
        let meta_req = MetadataOnlyVerifyRequest {
            session_id: state.session_id.clone(),
            action: CloudGuardAction::ToolsList,
            tools_list: Some(body.clone()),
            tool_name: None,
            args_sha256: None,
            financial_metadata: None,
        };
        match cloud_client.canonicalize_and_verify(meta_req).await {
            Ok(resp) => {
                if let Some(canonical_val) = resp.canonical_tools_json.clone() {
                    *body = canonical_val;
                }
                state.push_trial_reminder_from_cloud(&resp);
                if resp.renewal_warning && resp.trial_reminder_stage.is_none() {
                    eprintln!(
                        "[monaa-guard] renewal reminder: {} (manual top-up within 5 days)",
                        resp.renewal_url.clone().unwrap_or_default()
                    );
                }
            }
            Err(GuardError::CloudRugPull(reason)) => {
                return Err(GuardError::CloudRugPull(reason));
            }
            Err(GuardError::License(msg)) => {
                eprintln!(
                    "[monaa-guard] cloud M-PrefixLock KV canonicalizer inactive ({msg}); continuing on 100% unlimited free local compactor + stdio. {}",
                    crate::license::UPGRADE_CTA_MESSAGE
                );
            }
            Err(err) => return Err(err),
        }
    }

    Ok(())
}

fn jsonrpc_error_line(id: Value, err: &GuardError) -> String {
    let payload = json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": {
            "code": err.rpc_code(),
            "message": err.to_string(),
        }
    });
    serde_json::to_string(&payload).unwrap_or_else(|_| {
        "{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-32603,\"message\":\"internal error\"}}"
            .to_string()
    })
}

/// Formats blocked client MCP calls: Free 12-call cap emits clean MCP `isError: true` upgrade prompt.
pub fn format_blocked_client_response(id: Value, err: &GuardError) -> String {
    if let GuardError::FreeQuotaExceeded(msg) = err {
        let payload = json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": {
                "isError": true,
                "content": [{
                    "type": "text",
                    "text": msg,
                }]
            }
        });
        serde_json::to_string(&payload).unwrap_or_else(|_| jsonrpc_error_line(Value::Null, err))
    } else {
        jsonrpc_error_line(id, err)
    }
}

/// Thin transparent MCP 2026-07-28 stdio proxy wrapper (`0` stdout pollution; logs strictly to `stderr`).
pub async fn run_stdio_proxy(upstream_cmd: &str, state: ClientShimState) -> Result<(), GuardError> {
    eprintln!("[monaa-guard] starting thin MCP 2026-07-28 stdio client shim");

    #[cfg(windows)]
    let mut child_cmd = {
        let mut cmd = Command::new("cmd");
        cmd.args(["/C", upstream_cmd]);
        cmd
    };
    #[cfg(not(windows))]
    let mut child_cmd = {
        let mut cmd = Command::new("sh");
        cmd.args(["-c", upstream_cmd]);
        cmd
    };

    let mut child = child_cmd
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()?;

    let mut child_stdin = child
        .stdin
        .take()
        .ok_or_else(|| GuardError::Config("failed opening child stdin".to_string()))?;
    let child_stdout = child
        .stdout
        .take()
        .ok_or_else(|| GuardError::Config("failed opening child stdout".to_string()))?;

    let shared_state = Arc::new(Mutex::new(state));
    let parent_stdout = Arc::new(Mutex::new(tokio::io::stdout()));

    let state_out = Arc::clone(&shared_state);
    let stdout_for_resp = Arc::clone(&parent_stdout);
    let upstream_reader = tokio::spawn(async move {
        let mut lines = BufReader::new(child_stdout).lines();
        while let Ok(Some(line)) = lines.next_line().await {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }
            match serde_json::from_str::<Value>(trimmed) {
                Ok(mut val) => {
                    let mut guard = state_out.lock().await;
                    match inspect_upstream_response(&mut guard, &mut val).await {
                        Ok(()) => {
                            let notices: Vec<Value> =
                                std::mem::take(&mut guard.pending_notifications);
                            drop(guard);
                            if let Ok(serialized) = serde_json::to_string(&val) {
                                let mut out = stdout_for_resp.lock().await;
                                let _ = out.write_all(serialized.as_bytes()).await;
                                let _ = out.write_all(b"\n").await;
                                for notice in notices {
                                    if let Ok(n_str) = serde_json::to_string(&notice) {
                                        let _ = out.write_all(n_str.as_bytes()).await;
                                        let _ = out.write_all(b"\n").await;
                                    }
                                }
                                let _ = out.flush().await;
                            }
                        }
                        Err(err) => {
                            let id = val.get("id").cloned().unwrap_or(Value::Null);
                            eprintln!("[monaa-guard] blocked upstream response: {err}");
                            drop(guard);
                            let err_line = jsonrpc_error_line(id, &err);
                            let mut out = stdout_for_resp.lock().await;
                            let _ = out.write_all(err_line.as_bytes()).await;
                            let _ = out.write_all(b"\n").await;
                            let _ = out.flush().await;
                        }
                    }
                }
                Err(e) => {
                    eprintln!("[monaa-guard] dropped non-JSON upstream stdout line: {e}");
                }
            }
        }
    });

    let mut stdin_lines = BufReader::new(tokio::io::stdin()).lines();
    while let Ok(Some(line)) = stdin_lines.next_line().await {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let mut val: Value = match serde_json::from_str(trimmed) {
            Ok(v) => v,
            Err(e) => {
                eprintln!("[monaa-guard] rejected malformed client JSON-RPC: {e}");
                continue;
            }
        };

        let mut guard = shared_state.lock().await;
        match inspect_outbound_request(&mut guard, &McpHeaders::default(), &mut val, now_epoch_ms())
            .await
        {
            Ok(()) => {
                let notices: Vec<Value> = std::mem::take(&mut guard.pending_notifications);
                drop(guard);
                let serialized = serde_json::to_string(&val)
                    .map_err(|e| GuardError::Schema(format!("re-encode error: {e}")))?;
                child_stdin.write_all(serialized.as_bytes()).await?;
                child_stdin.write_all(b"\n").await?;
                child_stdin.flush().await?;
                if !notices.is_empty() {
                    let mut out = parent_stdout.lock().await;
                    for notice in notices {
                        if let Ok(n_str) = serde_json::to_string(&notice) {
                            let _ = out.write_all(n_str.as_bytes()).await;
                            let _ = out.write_all(b"\n").await;
                        }
                    }
                    let _ = out.flush().await;
                }
            }
            Err(err) => {
                let id = val.get("id").cloned().unwrap_or(Value::Null);
                eprintln!("[monaa-guard] blocked client request: {err}");
                drop(guard);
                let err_line = format_blocked_client_response(id, &err);
                let mut out = parent_stdout.lock().await;
                out.write_all(err_line.as_bytes()).await?;
                out.write_all(b"\n").await?;
                out.flush().await?;
            }
        }
    }

    drop(child_stdin);
    let _ = upstream_reader.await;
    let _ = child.wait().await;
    Ok(())
}

fn negotiate_protocol_version(params: Option<&Value>) -> &'static str {
    let requested = params
        .and_then(|p| p.get("protocolVersion"))
        .and_then(Value::as_str)
        .unwrap_or("");
    match requested {
        "2026-07-28" => "2026-07-28",
        "2025-11-25" => "2025-11-25",
        "2025-06-18" => "2025-06-18",
        "2025-03-26" => "2025-03-26",
        "2024-11-05" => "2024-11-05",
        _ => "2026-07-28",
    }
}

/// Returns standalone MCP 2026-07-28 tool definitions exposed by `monaa-guard mcp`.
pub fn standalone_mcp_tools() -> Vec<Value> {
    let ro_annotations = json!({
        "readOnlyHint": true,
        "destructiveHint": false,
        "idempotentHint": true,
        "openWorldHint": false
    });
    vec![
        json!({
            "name": "monaa_check_command_safety",
            "title": "Check Command & Path Safety",
            "description": "Evaluate a proposed shell command or file path against MONAA wire security rules (blocks .env reads, rm -rf, symlink escapes, and self-protection tampering in <50 us).",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "tool_name": {
                        "type": "string",
                        "description": "Tool name to check (e.g. bash, shell, read_file, write_file)."
                    },
                    "command": {
                        "type": "string",
                        "description": "Optional shell command string to evaluate."
                    },
                    "path": {
                        "type": "string",
                        "description": "Optional file or directory path to evaluate."
                    }
                },
                "required": ["tool_name"],
                "additionalProperties": false
            },
            "annotations": ro_annotations
        }),
        json!({
            "name": "monaa_compact_payload",
            "title": "Compact Tool Payload Locally",
            "description": "Deterministically compacts verbose tool output by stripping node_modules, target, .git bloat, redundant whitespace, and loop echoes locally (40%-65% typical savings, 0 cloud calls).",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "payload": {
                        "type": "string",
                        "description": "Raw text or tool output payload to compact locally."
                    },
                    "record_savings": {
                        "type": "boolean",
                        "description": "Set true to add these token savings into the local savings ledger."
                    }
                },
                "required": ["payload"],
                "additionalProperties": false
            },
            "annotations": ro_annotations
        }),
        json!({
            "name": "monaa_savings_report",
            "title": "Local Token Savings Report",
            "description": "Return cumulative local compaction metrics, tokens saved, reduction percentage, and estimated USD savings from the local SavingsLedger.",
            "inputSchema": {
                "type": "object",
                "properties": {},
                "additionalProperties": false
            },
            "annotations": ro_annotations
        }),
        json!({
            "name": "monaa_doctor",
            "title": "Wire Latency & BYOK Custody Audit",
            "description": "Benchmark local wire firewall latency percentiles (p50/p99 us) and verify 100% local BYOK key custody (0 outbound LLM keys transmitted).",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "iterations": {
                        "type": "integer",
                        "minimum": 100,
                        "maximum": 10000,
                        "description": "Number of benchmark iterations (default 1000)."
                    }
                },
                "additionalProperties": false
            },
            "annotations": ro_annotations
        }),
        json!({
            "name": "monaa_inspect_policy",
            "title": "Inspect Active Policy & Compactor Status",
            "description": "Read-only inspection of active public MONAA wire firewall rules (blocked secret-path patterns, blocked destructive command patterns, allowed localhost/IDE origins) and local payload compactor status (0 internal secrets exposed).",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "section": {
                        "type": "string",
                        "enum": ["all", "firewall", "allowlist", "compactor"],
                        "default": "all",
                        "description": "Policy section to inspect (`all`, `firewall`, `allowlist`, or `compactor`)."
                    }
                },
                "additionalProperties": false
            },
            "annotations": ro_annotations
        }),
    ]
}

fn jsonrpc_err_val(id: Value, code: i64, message: &str) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": {
            "code": code,
            "message": message
        }
    })
}

fn tool_ok(id: Value, structured: Value) -> Value {
    let text = serde_json::to_string_pretty(&structured).unwrap_or_else(|_| "{}".to_string());
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "result": {
            "content": [{
                "type": "text",
                "text": text
            }],
            "structuredContent": structured,
            "isError": false
        }
    })
}

fn call_check_command_safety(wire_guard: &mut LocalWireGuard, id: Value, args: &Value) -> Value {
    let Some(tool_name) = args
        .get("tool_name")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|s| !s.is_empty())
    else {
        return jsonrpc_err_val(
            id,
            -32602,
            "monaa_check_command_safety requires non-empty `tool_name`",
        );
    };

    let mut check_args = Map::new();
    if let Some(cmd) = args.get("command").and_then(Value::as_str) {
        check_args.insert("cmd".to_string(), Value::String(cmd.to_string()));
    }
    if let Some(path) = args.get("path").and_then(Value::as_str) {
        check_args.insert("path".to_string(), Value::String(path.to_string()));
    }
    let args_val = Value::Object(check_args);

    let start = Instant::now();
    let check_res = wire_guard
        .scan_params_self_protection(&args_val, 0)
        .and_then(|()| wire_guard.evaluate_local_wire(now_epoch_ms(), tool_name, &args_val, false));
    let latency_us = u64::try_from(start.elapsed().as_nanos())
        .unwrap_or(u64::MAX)
        .div_ceil(1_000)
        .max(1);

    let payload = match check_res {
        Ok(()) => json!({
            "allowed": true,
            "decision": "ALLOW",
            "rpc_code": 0,
            "tool_name": tool_name,
            "latency_us": latency_us,
            "reason": "Passed local MONAA wire policy checks."
        }),
        Err(err) => json!({
            "allowed": false,
            "decision": "BLOCK",
            "rpc_code": err.rpc_code(),
            "tool_name": tool_name,
            "latency_us": latency_us,
            "reason": err.to_string()
        }),
    };
    tool_ok(id, payload)
}

fn call_compact_payload(id: Value, args: &Value) -> Value {
    let Some(raw) = args.get("payload").and_then(Value::as_str) else {
        return jsonrpc_err_val(
            id,
            -32602,
            "monaa_compact_payload requires string `payload`",
        );
    };
    let raw_bytes = u64::try_from(raw.len()).unwrap_or(u64::MAX);
    let (compacted, bloat_lines_stripped, loop_echoes_collapsed) = compact_text_payload(raw);
    let compacted_bytes = u64::try_from(compacted.len()).unwrap_or(raw_bytes);
    let bytes_saved = raw_bytes.saturating_sub(compacted_bytes);
    let tokens_saved = bytes_saved.div_ceil(4);

    if args.get("record_savings").and_then(Value::as_bool) == Some(true) && raw_bytes > 0 {
        let metrics = CompactionMetrics {
            raw_bytes,
            compacted_bytes,
            bytes_saved,
            tokens_saved,
            bloat_lines_stripped,
            loop_echoes_collapsed,
        };
        let path = default_savings_path();
        let _ = record_local_savings(&path, &metrics, now_epoch_ms());
    }

    tool_ok(
        id,
        json!({
            "compacted": compacted,
            "raw_bytes": raw_bytes,
            "compacted_bytes": compacted_bytes,
            "bytes_saved": bytes_saved,
            "tokens_saved": tokens_saved,
            "bloat_lines_stripped": bloat_lines_stripped,
            "loop_echoes_collapsed": loop_echoes_collapsed
        }),
    )
}

fn call_savings_report(id: Value) -> Value {
    let path = default_savings_path();
    let ledger = load_savings_ledger(&path);
    let receipt = render_savings_receipt(&ledger);
    tool_ok(
        id,
        json!({
            "savings_path": path.display().to_string(),
            "responses_compacted": ledger.responses_compacted,
            "total_raw_bytes": ledger.total_raw_bytes,
            "total_compacted_bytes": ledger.total_compacted_bytes,
            "total_bytes_saved": ledger.total_bytes_saved,
            "total_tokens_saved": ledger.total_tokens_saved,
            "total_bloat_lines_stripped": ledger.total_bloat_lines_stripped,
            "total_loop_echoes_collapsed": ledger.total_loop_echoes_collapsed,
            "reduction_percent": receipt.reduction_percent,
            "local_usd_display": receipt.local_usd_display,
            "cloud_extra_usd_display": receipt.cloud_extra_usd_display,
            "terminal_card": receipt.terminal_card
        }),
    )
}

fn call_doctor(id: Value, args: &Value) -> Value {
    let iters = args
        .get("iterations")
        .and_then(Value::as_u64)
        .and_then(|n| usize::try_from(n).ok())
        .map(|n| n.clamp(100, 10_000))
        .unwrap_or(1_000);
    let cloud_base = resolve_cloud_base_url();
    let report = run_doctor_check(
        iters,
        cloud_base,
        "100% unlimited free local token compactor + 27 us wire shield (0 outbound LLM keys)"
            .to_string(),
    );
    let report_val = serde_json::to_value(report).unwrap_or_else(|_| json!({}));
    tool_ok(id, report_val)
}

fn call_inspect_policy(wire_guard: &LocalWireGuard, id: Value, args: &Value) -> Value {
    let section = match args.get("section") {
        None | Some(Value::Null) => "all",
        Some(Value::String(s)) => s.trim(),
        Some(_) => {
            return jsonrpc_err_val(
                id,
                -32602,
                "monaa_inspect_policy `section` must be a string",
            );
        }
    };
    if !matches!(section, "all" | "firewall" | "allowlist" | "compactor") {
        return jsonrpc_err_val(
            id,
            -32602,
            "monaa_inspect_policy `section` must be one of: all, firewall, allowlist, compactor",
        );
    }

    let policy_source = if std::path::Path::new("monaa-guard.toml").exists() {
        "monaa-guard.toml"
    } else {
        "built_in_defaults"
    };
    let savings_path = default_savings_path();
    let ledger = load_savings_ledger(&savings_path);

    let mut payload = Map::new();
    payload.insert("section".to_string(), json!(section));
    payload.insert("policy_source".to_string(), json!(policy_source));
    payload.insert("byok_key_custody_local_only".to_string(), json!(true));
    payload.insert("outbound_llm_keys_transmitted".to_string(), json!(0));

    if matches!(section, "all" | "firewall") {
        payload.insert(
            "firewall".to_string(),
            json!({
                "blocked_path_patterns": wire_guard.policy.blocked_path_patterns,
                "blocked_command_patterns": wire_guard.policy.blocked_command_patterns,
                "blocked_rpc_codes": {
                    "origin_or_header_mismatch": -32020,
                    "schema_rug_pull": -32021,
                    "dangerous_command_or_secret_path": -32022,
                    "account_notional_cap": -32023
                },
                "self_protection_enabled": true
            }),
        );
    }
    if matches!(section, "all" | "allowlist") {
        let cap_mode = if wire_guard.policy.free_daily_call_cap == u32::MAX {
            "unlimited"
        } else {
            "custom"
        };
        payload.insert(
            "allowlist".to_string(),
            json!({
                "allowed_origins": wire_guard.policy.allowed_origins,
                "free_daily_call_cap_mode": cap_mode,
                "free_daily_call_cap": wire_guard.policy.free_daily_call_cap
            }),
        );
    }
    if matches!(section, "all" | "compactor") {
        payload.insert(
            "compactor".to_string(),
            json!({
                "enabled": true,
                "unlimited_free_local": true,
                "loop_echo_dedup": true,
                "bloat_categories": [
                    "node_modules",
                    "target/debug",
                    "target/release",
                    ".git",
                    "__pycache__",
                    ".next",
                    ".venv"
                ],
                "savings_ledger_path": savings_path.display().to_string(),
                "responses_compacted": ledger.responses_compacted
            }),
        );
    }

    tool_ok(id, Value::Object(payload))
}

/// Handles one JSON-RPC 2.0 request for standalone `monaa-guard mcp`; returns `None` for notifications.
pub fn handle_standalone_mcp_request(
    wire_guard: &mut LocalWireGuard,
    req: &Value,
) -> Option<Value> {
    let method = req.get("method").and_then(Value::as_str).unwrap_or("");
    let id_opt = req.get("id").cloned();

    if method.starts_with("notifications/") || id_opt.is_none() {
        return None;
    }
    let id = id_opt.unwrap_or(Value::Null);

    match method {
        "initialize" => Some(json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": {
                "protocolVersion": negotiate_protocol_version(req.get("params")),
                "capabilities": {
                    "tools": {
                        "listChanged": false
                    }
                },
                "serverInfo": {
                    "name": "monaa-guard",
                    "title": "MONAA Guard",
                    "version": env!("CARGO_PKG_VERSION")
                },
                "instructions": "Local Pure-Rust MCP firewall & payload compactor (`#![forbid(unsafe_code)]`, 100% BYOK, 0 outbound LLM API keys)."
            }
        })),
        "ping" => Some(json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": {}
        })),
        "tools/list" => Some(json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": {
                "tools": standalone_mcp_tools()
            }
        })),
        "tools/call" => {
            let Some(tool_name) = req.pointer("/params/name").and_then(Value::as_str) else {
                return Some(jsonrpc_err_val(
                    id,
                    -32602,
                    "tools/call missing params.name",
                ));
            };
            let args = req
                .pointer("/params/arguments")
                .cloned()
                .unwrap_or_else(|| Value::Object(Map::new()));
            let resp = match tool_name {
                "monaa_check_command_safety" => call_check_command_safety(wire_guard, id, &args),
                "monaa_compact_payload" => call_compact_payload(id, &args),
                "monaa_savings_report" => call_savings_report(id),
                "monaa_doctor" => call_doctor(id, &args),
                "monaa_inspect_policy" => call_inspect_policy(wire_guard, id, &args),
                other => jsonrpc_err_val(id, -32602, &format!("Unknown tool: {other}")),
            };
            Some(resp)
        }
        other => Some(jsonrpc_err_val(
            id,
            -32601,
            &format!("Method not found: {other}"),
        )),
    }
}

/// Runs standalone MCP `2026-07-28` stdio JSON-RPC 2.0 server (`ENTRYPOINT` + default Docker `CMD ["mcp"]`).
pub async fn run_standalone_mcp_server() -> Result<(), GuardError> {
    eprintln!("[monaa-guard] starting standalone MCP 2026-07-28 stdio server");
    let policy =
        GuardPolicy::load_or_default(&PathBuf::from("monaa-guard.toml")).unwrap_or_default();
    let mut wire_guard = LocalWireGuard::new(policy, now_epoch_ms());

    let mut stdin_lines = BufReader::new(tokio::io::stdin()).lines();
    let mut stdout = tokio::io::stdout();

    while let Ok(Some(line)) = stdin_lines.next_line().await {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let req: Value = match serde_json::from_str(trimmed) {
            Ok(v) => v,
            Err(e) => {
                let err_resp = jsonrpc_err_val(Value::Null, -32700, &format!("Parse error: {e}"));
                if let Ok(line_out) = serde_json::to_string(&err_resp) {
                    stdout.write_all(line_out.as_bytes()).await?;
                    stdout.write_all(b"\n").await?;
                    stdout.flush().await?;
                }
                continue;
            }
        };

        if let Some(resp) = handle_standalone_mcp_request(&mut wire_guard, &req) {
            let line_out = serde_json::to_string(&resp)
                .map_err(|e| GuardError::Schema(format!("response encode error: {e}")))?;
            stdout.write_all(line_out.as_bytes()).await?;
            stdout.write_all(b"\n").await?;
            stdout.flush().await?;
        }
    }

    Ok(())
}