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);
}
}
}
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")
}
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)?;
}
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);
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(())
}
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()
})
}
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)
}
}
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(¬ice) {
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(¬ice) {
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",
}
}
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))
}
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}"),
)),
}
}
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(())
}