use std::collections::HashSet;
use std::sync::PoisonError;
use anyhow::{Context as _, Result, bail};
use openmoat_audit::{NewEvent, Ticket};
use openmoat_core::rule_id::MCP_SERVER_TEXT;
use openmoat_core::{Action, Decision, Verdict};
use serde_json::Value;
use super::{AUDIT_HOST, Awaiting, Gateway};
const MAX_QUEUED: usize = 64;
#[derive(Default)]
pub(super) struct Sent {
instructions: Option<String>,
credited: HashSet<(String, String)>,
queued: Vec<(String, String)>,
}
impl Gateway {
pub(super) fn keep_instructions(&self, text: &str) {
let mut sent = self.sent.lock().unwrap_or_else(PoisonError::into_inner);
sent.instructions = Some(text.to_owned()).filter(|t| !t.trim().is_empty());
sent.credited.clear();
}
pub(super) fn credit(&self, ticket: &Ticket, cwd: Option<&str>) -> Result<()> {
let key = (ticket.host.clone(), ticket.session_id.clone());
let whose = (ticket.host.as_str(), ticket.session_id.as_str());
let text = {
let sent = self.sent.lock().unwrap_or_else(PoisonError::into_inner);
if sent.credited.contains(&key) {
return Ok(());
}
sent.instructions.clone()
};
if let Some(text) = text {
self.untrusted(whose, cwd, "initialize", &text)
.context("keeping the MCP server's instructions for this session")?;
}
let queued = std::mem::take(
&mut self
.sent
.lock()
.unwrap_or_else(PoisonError::into_inner)
.queued,
);
for (method, text) in queued {
self.untrusted(whose, cwd, &method, &text)
.context("keeping the MCP server's request for this session")?;
}
self.sent
.lock()
.unwrap_or_else(PoisonError::into_inner)
.credited
.insert(key);
Ok(())
}
pub(super) fn server_text(&self, method: &str, text: &str) -> Result<()> {
if text.trim().is_empty() {
return Ok(());
}
let served = self
.served
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone();
let Some((host, session)) = served else {
let mut sent = self.sent.lock().unwrap_or_else(PoisonError::into_inner);
if sent.queued.len() >= MAX_QUEUED {
bail!("too many requests from the server before any session used it");
}
sent.queued.push((method.to_owned(), text.to_owned()));
return Ok(());
};
self.untrusted((&host, &session), None, method, text)
.context("keeping the MCP server's request for the session it serves")
}
pub(super) fn record_request(&self, method: &str, decision: &Decision) -> Result<()> {
let store = self.store()?.with_secrets(self.known());
let served = self
.served
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone();
let session = served.map_or_else(|| self.session.clone(), |(_, s)| s);
store.record(&NewEvent {
host: AUDIT_HOST,
session_id: &session,
call_id: None,
cwd: None,
tool: method,
action: None,
decision,
latency_us: 0,
})?;
Ok(())
}
fn untrusted(
&self,
(host, session): (&str, &str),
cwd: Option<&str>,
what: &str,
text: &str,
) -> Result<()> {
let name = format!("mcp__{}__{what}", self.server);
let action = Action::mcp(name.clone());
let store = self.store()?.with_secrets(self.known());
let decision = Decision::single(
Verdict::Allow,
MCP_SERVER_TEXT,
format!(
"MCP server `{}` sent the agent text outside a tool result ({what}), which \
marks the session untrusted (recorded by {AUDIT_HOST})",
self.server
),
);
store.record(&NewEvent {
host,
session_id: session,
call_id: None,
cwd,
tool: &name,
action: Some(&action),
decision: &decision,
latency_us: 0,
})?;
let awaiting = Awaiting {
host: host.to_owned(),
session: session.to_owned(),
action,
cwd: cwd.map(str::to_owned),
};
self.keep(&store, &awaiting, &Value::String(text.to_owned()))
}
}