use anyhow::{Context as _, Result};
use openmoat_audit::Store;
use openmoat_core::mcp_flow::{self, ToolEffect, ToolHints};
use openmoat_core::{Action, Decision, Policy, Verdict};
use openmoat_hosts::Host;
use serde_json::Value;
use crate::home::Home;
use crate::integrity::sha256_hex;
use crate::mcp::tools;
const MAX_TEXT_BYTES: usize = 1 << 20;
const HASH_HEX_CHARS: usize = 32;
pub fn value_pieces(value: &Value) -> Vec<String> {
mcp_flow::pieces(&value_text(value))
}
pub fn value_text(value: &Value) -> String {
let mut text = String::new();
let mut pending = vec![value];
while let Some(value) = pending.pop() {
if text.len() >= MAX_TEXT_BYTES {
break;
}
match value {
Value::String(s) => {
let room = MAX_TEXT_BYTES - text.len();
let cut = (0..=room.min(s.len()))
.rev()
.find(|&i| s.is_char_boundary(i))
.unwrap_or(0);
text.push_str(&s[..cut]);
text.push('\n');
}
Value::Array(items) => pending.extend(items.iter().rev()),
Value::Object(map) => pending.extend(map.values().rev()),
_ => {}
}
}
text
}
pub fn hashed(pieces: Vec<String>) -> Vec<String> {
pieces
.into_iter()
.map(|piece| {
let digest = sha256_hex(format!("openmoat-mcp-flow\0{piece}").as_bytes());
digest[..HASH_HEX_CHARS].to_owned()
})
.collect()
}
pub struct Sink<'a> {
pub home: &'a Home,
pub store: &'a Store,
pub host: Host,
pub session: &'a str,
pub action: &'a Action,
pub arguments: Option<&'a str>,
pub policy: &'a Policy,
}
pub fn checked(sink: &Sink<'_>, decision: Decision) -> Result<Decision> {
let (Action::McpTool { name, .. }, Some(arguments)) = (sink.action, sink.arguments) else {
return Ok(decision);
};
if decision.verdict == Verdict::Deny {
return Ok(decision);
}
let trusted = sink.policy.mcp_flow_trusted();
if trusted.iter().any(|t| super::tool_of(sink.host, name, t)) {
return Ok(decision);
}
let arguments: Value =
serde_json::from_str(arguments).context("reading the MCP call's arguments")?;
let pieces = hashed(value_pieces(&arguments));
if pieces.is_empty() {
return Ok(decision);
}
let sources: Vec<String> = sink
.store
.mcp_flow_sources(sink.host.id(), sink.session, &pieces)
.context("reading this session's MCP tool results from the audit log")?
.into_iter()
.filter(|server| !super::tool_of(sink.host, name, server) && !trusted.contains(server))
.collect();
if sources.is_empty() {
return Ok(decision);
}
let pinned = pinned_tool(sink.home, sink.host, name)?;
let hints = pinned.as_ref().map_or_else(ToolHints::default, |p| p.hints);
let by_shape = openmoat_hosts::mcp_tool_acts(name, sink.action);
if ToolEffect::classify(&hints, by_shape) == ToolEffect::Read {
return Ok(decision);
}
let server = pinned.map_or_else(|| server_of(name).to_owned(), |p| p.server);
Ok(mcp_flow::cross_server(decision, &sources, &server))
}
struct Pinned {
server: String,
hints: ToolHints,
}
fn pinned_tool(home: &Home, host: Host, name: &str) -> Result<Option<Pinned>> {
let mut server_only = None;
for (_, pins) in tools::all(home)? {
if !super::tool_of(host, name, &pins.server) {
continue;
}
let tool = pins
.tools
.iter()
.find(|(tool, _)| super::names_tool(host, name, &pins.server, tool));
if let Some((_, pin)) = tool {
return Ok(Some(Pinned {
server: pins.server.clone(),
hints: hints(&pin.annotations),
}));
}
server_only.get_or_insert(Pinned {
server: pins.server,
hints: ToolHints::default(),
});
}
Ok(server_only)
}
fn hints(annotations: &Value) -> ToolHints {
let hint = |key: &str| annotations.get(key).and_then(Value::as_bool);
ToolHints {
read_only: hint("readOnlyHint"),
destructive: hint("destructiveHint"),
open_world: hint("openWorldHint"),
}
}
fn server_of(name: &str) -> &str {
name.strip_prefix("mcp__")
.and_then(|rest| rest.split("__").next())
.filter(|server| !server.is_empty())
.unwrap_or(name)
}
#[cfg(test)]
mod tests;