use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Mutex, PoisonError};
use std::time::Instant;
use anyhow::{Context as _, Result, bail};
use openmoat_audit::{KnownSecrets, NewEvent, Store, Ticket};
use openmoat_core::rule_id::{
MCP_PROXY, MCP_SERVER_CHANGED, MCP_SERVER_REQUEST, MCP_TOOL_HELD, MCP_UNATTRIBUTED,
};
use openmoat_core::{Action, CompiledPolicy, Decision, Verdict};
use openmoat_hosts::Host;
use serde_json::Value;
use crate::environment::{Snapshot, WithOwnBinary};
use crate::home::Home;
use crate::mcp::names_tool;
use crate::mcp::relay::{Call, Gate, Method};
use crate::realpath::FsPathResolver;
use crate::{context, integrity, secrets};
const AUDIT_HOST: &str = MCP_PROXY;
pub struct Gateway {
home: Home,
server: String,
cwd: PathBuf,
session: String,
host: Option<Host>,
served: Mutex<Option<(String, String)>>,
sent: Mutex<surface::Sent>,
awaiting: Mutex<HashMap<String, Awaiting>>,
}
struct Awaiting {
host: String,
session: String,
action: Action,
cwd: Option<String>,
}
const MAX_AWAITING: usize = 4096;
struct Outcome {
action: Action,
decision: Decision,
ticket: Option<Ticket>,
cwd: Option<String>,
known: KnownSecrets,
}
impl Gateway {
pub fn new(home: Home, server: &str, host: Option<Host>) -> Result<Self> {
Ok(Self {
home,
server: server.to_owned(),
cwd: std::env::current_dir().context("reading the working directory")?,
session: format!(
"mcp-{server}-{}-{}",
std::process::id(),
crate::time::now_ms()
),
host,
served: Mutex::new(None),
sent: Mutex::default(),
awaiting: Mutex::new(HashMap::new()),
})
}
fn await_result(&self, request: &str, ticket: &Ticket, action: Action, cwd: Option<String>) {
let mut awaiting = self.awaiting.lock().unwrap_or_else(PoisonError::into_inner);
if awaiting.len() >= MAX_AWAITING
&& let Some(any) = awaiting.keys().next().cloned()
{
awaiting.remove(&any);
}
awaiting.insert(
request.to_owned(),
Awaiting {
host: ticket.host.clone(),
session: ticket.session_id.clone(),
action,
cwd,
},
);
}
fn name(&self, call: &Call<'_>) -> String {
match call.method {
Method::Tool | Method::Prompt => format!("mcp__{}__{}", self.server, call.name),
Method::Resource => format!("mcp__{}__read_resource", self.server),
}
}
fn decide(&self, call: &Call<'_>, store: &Store) -> Result<Outcome> {
let name = self.name(call);
let none = Value::Null;
let action = match call.method {
Method::Tool => {
openmoat_hosts::mcp_call_action(&name, call.arguments.unwrap_or(&none))?
}
Method::Resource => openmoat_hosts::mcp_resource_action(&self.server, call.name)?,
Method::Prompt => {
let decision = Decision::single(Verdict::Allow, MCP_PROXY, "a prompt, recorded");
return Ok(self.outcome(Action::mcp(name), decision, None, None));
}
};
let ticket = match call.method {
Method::Tool => self.take_ticket(store, call)?,
_ => None,
};
let cwd = match &ticket {
Some(t) => store.get(t.event_id)?.and_then(|e| e.cwd),
None => None,
};
let (decided, known) = self.policy(&action, cwd.as_deref())?;
let decision = match (&ticket, call.method) {
_ if decided.verdict == Verdict::Deny => decided,
(None, Method::Tool) => Decision::single(
Verdict::Deny,
MCP_UNATTRIBUTED,
"OpenMoat's hook made no decision on this exact call (the same tool and \
arguments, within the hour): the host did not run the hook for it, or sent \
other arguments than it checked, so it is not passed on",
),
(Some(t), _) => Decision::single(
Verdict::Allow,
MCP_PROXY,
format!(
"passed to the server: the hook decided `{}` for this call (event {})",
t.verdict, t.event_id.0
),
),
(None, _) => Decision::single(Verdict::Allow, MCP_PROXY, "passed to the server"),
};
Ok(Outcome {
action,
decision,
ticket,
cwd,
known,
})
}
fn take_ticket(&self, store: &Store, call: &Call<'_>) -> Result<Option<Ticket>> {
let arguments = openmoat_hosts::mcp_call_arguments(call.arguments);
let digest = integrity::sha256_hex(arguments.as_bytes());
let (server, tool) = (self.server.as_str(), call.name);
let ours = |t: &Ticket| {
t.host.parse::<Host>().is_ok_and(|host| {
self.host.is_none_or(|own| own == host) && names_tool(host, &t.tool, server, tool)
})
};
let last = self
.served
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone();
let mut taken = None;
if let Some((host, session)) = &last {
taken = store.take_mcp_ticket(&digest, |t| {
ours(t) && &t.host == host && &t.session_id == session
})?;
}
if taken.is_none() {
taken = store.take_mcp_ticket(&digest, ours)?;
}
if let Some(ticket) = &taken {
*self.served.lock().unwrap_or_else(PoisonError::into_inner) =
Some((ticket.host.clone(), ticket.session_id.clone()));
}
Ok(taken)
}
fn policy(&self, action: &Action, cwd: Option<&str>) -> Result<(Decision, KnownSecrets)> {
let verified = integrity::check(&self.home)?;
if let Some(deny) = verified.checked.deny {
return Ok((deny, self.known()));
}
let home = verified.home;
let cwd = cwd.map_or_else(|| self.cwd.clone(), PathBuf::from);
let ctx = context::eval_context(&home, Some(&cwd), None)?;
let policy = crate::repo::effective_policy(&home, &ctx)?;
let compiled = CompiledPolicy::compile(&policy, &ctx)?;
let snapshot = Snapshot::load_in(&home)?;
let programs = WithOwnBinary {
snapshot: &snapshot,
binary: &verified.lock.binary,
};
let known = secrets::known(&policy.secrets, &ctx.home)?;
Ok((
compiled.decide_with(action, &programs, &FsPathResolver),
known,
))
}
fn known(&self) -> KnownSecrets {
let Ok(policy) = self.home.load_policy() else {
return KnownSecrets::default();
};
context::home_spellings()
.and_then(|(home, _)| secrets::known(&policy.secrets, &home))
.unwrap_or_default()
}
fn outcome(
&self,
action: Action,
decision: Decision,
ticket: Option<Ticket>,
cwd: Option<String>,
) -> Outcome {
Outcome {
action,
decision,
ticket,
cwd,
known: self.known(),
}
}
pub fn refused_start(&self, why: &str) -> Result<()> {
let store = self.store()?.with_secrets(self.known());
let name = format!("mcp__{}", self.server);
let decision = Decision::single(Verdict::Deny, MCP_SERVER_CHANGED, why);
store.record(&NewEvent {
host: AUDIT_HOST,
session_id: &self.session,
call_id: None,
cwd: self.cwd.to_str(),
tool: &name,
action: Some(&Action::mcp(name.clone())),
decision: &decision,
latency_us: 0,
})?;
Ok(())
}
fn store(&self) -> Result<Store> {
crate::audit_key::open_existing(&self.home).context("audit log unavailable")
}
fn record(&self, store: Store, tool: &str, outcome: Outcome, started: Instant) -> Result<()> {
let store = store.with_secrets(outcome.known);
let ticket = outcome.ticket.as_ref();
let latency_us = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX);
store.record(&NewEvent {
host: AUDIT_HOST,
session_id: ticket.map_or(self.session.as_str(), |t| t.session_id.as_str()),
call_id: ticket.and_then(|t| t.call_id.as_deref()),
cwd: outcome.cwd.as_deref(),
tool,
action: Some(&outcome.action),
decision: &outcome.decision,
latency_us,
})?;
Ok(())
}
}
impl Gate for Gateway {
fn check(&self, call: &Call<'_>, held: Option<&str>) -> Result<Option<String>> {
let started = Instant::now();
let store = self.store()?;
let name = self.name(call);
let outcome = match held {
Some(why) => self.outcome(
Action::mcp(name.clone()),
Decision::single(Verdict::Deny, MCP_TOOL_HELD, why),
None,
None,
),
None => self.decide(call, &store)?,
};
let refused = match outcome.decision.verdict {
Verdict::Deny => Some(refusal(&outcome.decision)),
_ => None,
};
if let (Some(ticket), None) = (&outcome.ticket, &refused) {
self.credit(ticket, outcome.cwd.as_deref())?;
}
let awaits = match (&outcome.ticket, call.request, &refused) {
(Some(ticket), Some(request), None) => Some((
request,
ticket.clone(),
outcome.action.clone(),
outcome.cwd.clone(),
)),
_ => None,
};
self.record(store, &name, outcome, started)?;
if let Some((request, ticket, action, cwd)) = awaits {
self.await_result(request, &ticket, action, cwd);
}
Ok(refused)
}
fn result(&self, request: &str, result: &Value) -> Result<()> {
let awaiting = self
.awaiting
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(request);
let Some(awaiting) = awaiting else {
return Ok(());
};
let store = self.store()?.with_secrets(self.known());
self.keep(&store, &awaiting, result)
}
fn instructions(&self, text: &str) {
self.keep_instructions(text);
}
fn server_request(&self, method: &str, params: Option<&Value>) -> Result<()> {
let decision = Decision::single(
Verdict::Allow,
MCP_SERVER_REQUEST,
format!("MCP server `{}` asked the agent: {method}", self.server),
);
self.record_request(method, &decision)?;
let text = params.map(crate::mcp::flow::value_text).unwrap_or_default();
self.server_text(method, &text)
}
fn server_refused(&self, method: &str, why: &str) -> Result<()> {
let decision = Decision::single(Verdict::Deny, MCP_SERVER_REQUEST, why);
self.record_request(method, &decision)
}
}
impl Gateway {
fn keep(&self, store: &Store, awaiting: &Awaiting, value: &Value) -> Result<()> {
let pieces = crate::mcp::flow::hashed(crate::mcp::flow::value_pieces(value));
if !pieces.is_empty() {
store
.add_mcp_flow(&awaiting.host, &awaiting.session, &self.server, &pieces)
.context("recording what the tool's result held")?;
}
self.injected(store, awaiting, value)
}
fn injected(&self, store: &Store, awaiting: &Awaiting, result: &Value) -> Result<()> {
let text = crate::mcp::flow::value_text(result);
if text.trim().is_empty() {
return Ok(());
}
let Ok(host) = awaiting.host.parse::<Host>() else {
bail!(
"the hook's decision names no known host (`{}`)",
awaiting.host
);
};
let verified = integrity::check(&self.home)?;
if verified.checked.deny.is_some() {
bail!("the policy lock does not match, so this tool's result is not kept");
}
let home = verified.home;
let cwd = awaiting
.cwd
.as_deref()
.map_or_else(|| self.cwd.clone(), PathBuf::from);
let ctx = context::eval_context(&home, Some(&cwd), None)?;
let policy = crate::repo::effective_policy(&home, &ctx)?;
let compiled = CompiledPolicy::compile(&policy, &ctx)?;
let output = crate::taint::injected::Output {
host,
session: &awaiting.session,
action: &awaiting.action,
cwd: &ctx.cwd,
text: &text,
};
crate::taint::injected::record(&home, store, &compiled, &output)
.context("keeping what the tool's result named")?;
Ok(())
}
}
fn refusal(decision: &Decision) -> String {
let rules = decision.rules.join(", ");
let reasons = decision.reasons.join("; ");
format!("OpenMoat refused this call [{rules}]: {reasons}")
}
mod surface;
#[cfg(test)]
mod tests;