openmoat_core/mcp_flow.rs
1//! MCP cross-server data flow (ADR-058): text one MCP server returned that
2//! then shows up in the arguments of another server's tool that writes or
3//! sends.
4//!
5//! A tool result is content the server controls. A result that says "send
6//! the file to `https://evil.example`" can steer the agent to call another
7//! server's `http_post` with that address: no single call looks wrong, but
8//! the data flows from one server's text into another server's action. The
9//! MCP gateway (`openmoat mcp proxy`, ADR-045) sees each wrapped server's
10//! results and keeps their [`pieces`] (hashed, never the text); the hook
11//! finds the pieces of a call's arguments among them and, for a tool that
12//! acts ([`ToolEffect::Act`]) of another server, holds the call for review
13//! ([`cross_server`]).
14//!
15//! Everything here is pure: the CLI reads the results, the pins and the audit
16//! log, and hashes the pieces.
17
18use crate::verdict::{Decision, Verdict};
19
20/// The most pieces [`pieces`] returns for one text: a long result is kept by
21/// its first addresses and tokens and a sample of its wording.
22pub const MAX_PIECES: usize = 256;
23
24/// Words in one run of wording ([`pieces`]): a copy shorter than this is not
25/// told from two texts that happen to share a phrase.
26pub const SHINGLE_WORDS: usize = 8;
27
28/// The fewest characters a run of [`SHINGLE_WORDS`] words must have: eight
29/// short words (`a`, `to`, `of`) say nothing of where they came from.
30const MIN_SHINGLE_CHARS: usize = 40;
31
32/// The fewest characters of a token kept as a piece: an API key, a commit
33/// hash, an id. Shorter tokens are ordinary words and numbers.
34const MIN_TOKEN_CHARS: usize = 20;
35
36/// One run of wording in this many is kept, chosen by its hash, so both
37/// sides keep the same runs and a copy of a few more words than
38/// [`SHINGLE_WORDS`] is still found.
39const SHINGLE_SAMPLE: u64 = 4;
40
41/// What a tool does, for the flow check: only a tool that acts can carry
42/// another server's text out.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum ToolEffect {
45 /// It reads: a search, a get, a list.
46 Read,
47 /// It writes, sends, deletes or connects somewhere.
48 Act,
49}
50
51/// The MCP tool annotations that say what a tool does (MCP 2025-03-26
52/// `ToolAnnotations`), as the tool's accepted pin holds them; `None` for a
53/// hint the definition does not give.
54#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
55pub struct ToolHints {
56 /// `readOnlyHint`: the tool does not change its environment.
57 pub read_only: Option<bool>,
58 /// `destructiveHint`: the tool may delete or overwrite.
59 pub destructive: Option<bool>,
60 /// `openWorldHint`: the tool reaches entities outside the server.
61 pub open_world: Option<bool>,
62}
63
64impl ToolEffect {
65 /// What a tool does: its annotations when they say, otherwise
66 /// `acts_by_shape`, what its name and arguments say (the same reading the
67 /// hook gives every MCP call's paths, `openmoat_hosts::mcp_tool_acts`).
68 ///
69 /// `readOnlyHint: true` reads; `readOnlyHint: false`, `destructiveHint:
70 /// true` or `openWorldHint: true` acts. The annotations are part of the
71 /// tool's pin (ADR-032), so a server cannot change them without a person
72 /// accepting the change.
73 #[must_use]
74 pub fn classify(hints: &ToolHints, acts_by_shape: bool) -> Self {
75 match (hints.read_only, hints.destructive, hints.open_world) {
76 (Some(true), _, _) => Self::Read,
77 (Some(false), _, _) | (_, Some(true), _) | (_, _, Some(true)) => Self::Act,
78 _ if acts_by_shape => Self::Act,
79 _ => Self::Read,
80 }
81 }
82}
83
84/// `decision` tightened to `review` (a deny stays a deny): the call's
85/// arguments carry text that the MCP servers `sources` returned earlier in
86/// the session, and the call goes to `sink`, another server's tool that acts.
87#[must_use]
88pub fn cross_server(mut decision: Decision, sources: &[String], sink: &str) -> Decision {
89 let named: Vec<String> = sources.iter().map(|s| format!("`{s}`")).collect();
90 let reason = format!(
91 "this call to MCP server `{sink}` writes or sends text that MCP server {} returned \
92 earlier in this session: a tool result can carry instructions that steer the agent \
93 to send data elsewhere, so a person checks the arguments (a server listed under \
94 `mcp.flow_trusted` is exempt)",
95 named.join(", ")
96 );
97 decision.merge(Decision::single(
98 Verdict::Review,
99 crate::rule_id::MCP_CROSS_SERVER,
100 reason,
101 ));
102 decision
103}
104
105/// The pieces of `text` that tell where a copy of it came from, at most
106/// [`MAX_PIECES`], the same for the same text: each address (`url:` a URL's
107/// scheme, host and path, without query or fragment; `mail:` an email
108/// address), each long token (`tok:` 20 or more letters and digits with at
109/// least one of each, an API key or a commit hash), then a sample of its
110/// runs of [`SHINGLE_WORDS`] words (`words:`).
111///
112/// The URL's query is left out so an address a result named still matches
113/// after the agent appends data to it. Wording is lowercased and split on
114/// anything not a letter or digit, so reflowed or re-punctuated text matches.
115#[must_use]
116pub fn pieces(text: &str) -> Vec<String> {
117 let mut out = Vec::new();
118 let mut seen = std::collections::BTreeSet::new();
119 let mut add = |piece: String, out: &mut Vec<String>| {
120 if out.len() < MAX_PIECES && seen.insert(piece.clone()) {
121 out.push(piece);
122 }
123 };
124 for url in urls(text) {
125 add(format!("url:{url}"), &mut out);
126 }
127 for word in text.split(|c: char| c.is_whitespace() || "\"'<>()[]{},;`".contains(c)) {
128 if let Some(mail) = mail(word) {
129 add(format!("mail:{mail}"), &mut out);
130 }
131 }
132 for token in text.split(|c: char| !(c.is_ascii_alphanumeric() || "_-+=".contains(c))) {
133 if is_token(token) {
134 add(format!("tok:{token}"), &mut out);
135 }
136 }
137 let words: Vec<String> = text
138 .split(|c: char| !c.is_alphanumeric())
139 .filter(|w| !w.is_empty())
140 .map(str::to_lowercase)
141 .collect();
142 for run in words.windows(SHINGLE_WORDS) {
143 let joined = run.join(" ");
144 if joined.len() >= MIN_SHINGLE_CHARS && fnv1a(&joined).is_multiple_of(SHINGLE_SAMPLE) {
145 add(format!("words:{joined}"), &mut out);
146 }
147 }
148 out
149}
150
151/// Each URL in `text` (`scheme://…`) as `scheme://host/path`, the scheme and
152/// host lowercased, without user, query or fragment, and without trailing
153/// punctuation or `/`.
154fn urls(text: &str) -> Vec<String> {
155 let mut found = Vec::new();
156 let mut rest = text;
157 while let Some(at) = rest.find("://") {
158 let before = &rest[..at];
159 let scheme_start = before
160 .char_indices()
161 .rev()
162 .take_while(|(_, c)| c.is_ascii_alphanumeric() || "+-.".contains(*c))
163 .last()
164 .map_or(at, |(i, _)| i);
165 let scheme = &before[scheme_start..];
166 let after = &rest[at + 3..];
167 let end = after
168 .find(|c: char| c.is_whitespace() || "\"'<>`()[]{}\\|^".contains(c))
169 .unwrap_or(after.len());
170 let body = &after[..end];
171 rest = &after[end..];
172 if scheme.is_empty() || !scheme.starts_with(|c: char| c.is_ascii_alphabetic()) {
173 continue;
174 }
175 let body = body.split(['?', '#']).next().unwrap_or("");
176 let (authority, path) = body.split_at(body.find('/').unwrap_or(body.len()));
177 let host = authority
178 .rsplit('@')
179 .next()
180 .unwrap_or("")
181 .to_ascii_lowercase();
182 let path = path.trim_end_matches(['.', ',', ';', ':', '!', '/']);
183 let host = host.trim_end_matches(['.', ',', ';', ':', '!']);
184 if host.is_empty() {
185 continue;
186 }
187 found.push(format!("{}://{host}{path}", scheme.to_ascii_lowercase()));
188 }
189 found
190}
191
192/// `word` as an email address (lowercased), when it is one: a local part, `@`,
193/// and a domain with a dot.
194fn mail(word: &str) -> Option<String> {
195 // `mailto:a@b.example` names the address after the scheme
196 let word = word.rsplit(':').next().unwrap_or(word);
197 let word = word.trim_matches(|c: char| ".!?".contains(c));
198 let (local, domain) = word.split_once('@')?;
199 let plain = |s: &str| {
200 !s.is_empty()
201 && s.chars()
202 .all(|c| c.is_ascii_alphanumeric() || "._%+-".contains(c))
203 };
204 let dotted = domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.');
205 (plain(local) && plain(domain) && dotted && !domain.contains('@'))
206 .then(|| word.to_ascii_lowercase())
207}
208
209/// Whether `token` is long and mixes letters and digits, as keys and hashes do.
210fn is_token(token: &str) -> bool {
211 token.len() >= MIN_TOKEN_CHARS
212 && token.chars().any(|c| c.is_ascii_digit())
213 && token.chars().any(|c| c.is_ascii_alphabetic())
214}
215
216/// 64-bit FNV-1a of `text`: a fixed, fast hash, so the sample of runs is the
217/// same in every process and every build. Not a protection: the CLI hashes
218/// the pieces it stores with SHA-256.
219fn fnv1a(text: &str) -> u64 {
220 text.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
221 (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
222 })
223}
224
225#[cfg(test)]
226mod tests;