1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use super::audit::{AuditEvent, AuditLog};
use super::jsonrpc::JsonRpcRequest;
use super::policy::{make_deny_response, McpPolicy, PolicyDecision, PolicyState};
use std::{
collections::HashMap,
io::{self, BufRead, BufReader, Write},
process::{Child, Command, Stdio},
sync::{Arc, Mutex},
thread,
};
#[derive(Clone, Debug, Default)]
pub struct ProxyConfig {
pub dry_run: bool,
pub verbose: bool,
pub audit_log_path: Option<std::path::PathBuf>,
pub server_id: String,
}
pub struct McpProxy {
child: Child,
policy: McpPolicy,
config: ProxyConfig,
/// Cache of tool identities discovered during tools/list
identity_cache: Arc<Mutex<HashMap<String, super::identity::ToolIdentity>>>,
}
impl Drop for McpProxy {
fn drop(&mut self) {
// Best-effort cleanup
let _ = self.child.kill();
}
}
impl McpProxy {
pub fn spawn(
command: &str,
args: &[String],
policy: McpPolicy,
config: ProxyConfig,
) -> io::Result<Self> {
let child = Command::new(command)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit()) // protocol blijft op stdout
.spawn()?;
Ok(Self {
child,
policy,
config,
identity_cache: Arc::new(Mutex::new(HashMap::new())),
})
}
pub fn run(mut self) -> io::Result<i32> {
let mut child_stdin = self.child.stdin.take().expect("child stdin");
let child_stdout = self.child.stdout.take().expect("child stdout");
let stdout = Arc::new(Mutex::new(io::stdout()));
let policy = self.policy.clone();
let config = self.config.clone();
let identity_cache_a = self.identity_cache.clone();
let identity_cache_b = self.identity_cache.clone();
// Thread A: server -> client passthrough
let stdout_a = stdout.clone();
let t_server_to_client = thread::spawn(move || -> io::Result<()> {
let mut reader = BufReader::new(child_stdout);
let mut line = String::new();
while reader.read_line(&mut line)? > 0 {
let mut processed_line = line.clone();
// Phase 9: Compute Identities on tools/list response
if let Ok(mut v) = serde_json::from_str::<serde_json::Value>(&line) {
if let Some(result) = v.get_mut("result") {
if let Some(tools) = result.get_mut("tools").and_then(|t| t.as_array_mut())
{
for tool in tools {
let name = tool
.get("name")
.and_then(|n| n.as_str())
.unwrap_or("unknown");
let description = tool
.get("description")
.and_then(|d| d.as_str())
.map(|s| s.to_string());
let input_schema = tool
.get("inputSchema")
.or_else(|| tool.get("input_schema"))
.cloned();
let identity = super::identity::ToolIdentity::new(
&config.server_id,
name,
&input_schema,
&description,
);
// Cache for runtime verification
let mut cache = identity_cache_a.lock().unwrap();
cache.insert(name.to_string(), identity.clone());
// Augment the response with the computed identity for downstream/logging
tool.as_object_mut().and_then(|m| {
m.insert(
"tool_identity".to_string(),
serde_json::to_value(&identity).unwrap(),
)
});
}
processed_line =
serde_json::to_string(&v).unwrap_or(line.clone()) + "\n";
}
}
}
let mut out = stdout_a
.lock()
.map_err(|e| io::Error::other(e.to_string()))?;
out.write_all(processed_line.as_bytes())?;
out.flush()?;
line.clear();
}
Ok(())
});
// Thread B: client -> server passthrough with Policy Check
let stdout_b = stdout.clone();
let t_client_to_server = thread::spawn(move || -> io::Result<()> {
let stdin = io::stdin();
let mut reader = stdin.lock();
let mut line = String::new();
let mut state = PolicyState::default();
let mut audit_log = AuditLog::new(config.audit_log_path.as_deref());
while reader.read_line(&mut line)? > 0 {
// 1. Try Parse as MCP Request
match serde_json::from_str::<JsonRpcRequest>(&line) {
Ok(req) => {
// 2. Check Policy with Identity (Phase 9)
let runtime_id = if req.is_tool_call() {
let name = req.tool_params().map(|p| p.name).unwrap_or_default();
let cache = identity_cache_b.lock().unwrap();
cache.get(&name).cloned()
} else {
None
};
match policy.evaluate(
&req.tool_params().map(|p| p.name).unwrap_or_default(),
&req.tool_params()
.map(|p| p.arguments)
.unwrap_or(serde_json::Value::Null),
&mut state,
runtime_id.as_ref(),
) {
PolicyDecision::Allow => {
Self::handle_allow(&req, &mut audit_log, config.verbose);
}
PolicyDecision::AllowWithWarning { tool, code, reason } => {
// Log warning about allowing a tool invocation with issues
if config.verbose {
eprintln!(
"[assay] WARNING: Allowing tool '{}' with warning (code: {}, reason: {}).",
tool,
code,
reason
);
}
audit_log.log(&AuditEvent {
timestamp: chrono::Utc::now().to_rfc3339(),
decision: "allow_with_warning".to_string(),
tool: Some(tool.clone()),
reason: Some(reason.clone()),
request_id: req.id.clone(),
agentic: None,
});
// Then proceed as a normal allow
Self::handle_allow(&req, &mut audit_log, false);
// false = don't double log ALLOW
}
PolicyDecision::Deny {
tool,
code: _,
reason,
contract,
} => {
// Log Decision
let decision_str =
if config.dry_run { "would_deny" } else { "deny" };
if config.verbose {
eprintln!(
"[assay] {} {} (reason: {})",
decision_str.to_uppercase(),
tool,
reason
);
}
audit_log.log(&AuditEvent {
timestamp: chrono::Utc::now().to_rfc3339(),
decision: decision_str.to_string(),
tool: Some(tool.clone()),
reason: Some(reason.clone()),
request_id: req.id.clone(),
agentic: Some(contract.clone()),
});
if config.dry_run {
// DRY RUN: Forward anyway
// Fallthrough to forward logic below
} else {
// BLOCK: Send error response
let id = req.id.unwrap_or(serde_json::Value::Null);
let response_json = make_deny_response(
id,
"Content blocked by policy",
contract,
);
let mut out = stdout_b
.lock()
.map_err(|e| io::Error::other(e.to_string()))?;
out.write_all(response_json.as_bytes())?;
out.flush()?;
line.clear();
continue; // Skip forwarding
}
}
}
}
Err(_) => {
// Hardening: Suspicious Unparsable JSON
let trimmed = line.trim();
if trimmed.starts_with('{')
&& (trimmed.contains("\"method\"")
|| trimmed.contains("\"params\"")
|| trimmed.contains("\"tool\""))
{
eprintln!("[assay] WARNING: Suspicious unparsable JSON, forwarding anyway (potential bypass attempt?): {:.60}...", trimmed);
}
}
}
// 3. Forward
child_stdin.write_all(line.as_bytes())?;
child_stdin.flush()?;
line.clear();
}
Ok(())
});
// Wacht tot client->server eindigt (stdin closed)
t_client_to_server
.join()
.map_err(|_| io::Error::other("client->server thread panicked"))??;
// Server->client thread kan nog even lopen; join best-effort
let _ = t_server_to_client.join();
// Wacht op child exit
let status = self.child.wait()?;
Ok(status.code().unwrap_or(1))
}
fn handle_allow(req: &JsonRpcRequest, audit_log: &mut AuditLog, verbose: bool) {
if verbose && req.is_tool_call() {
let tool = req
.tool_params()
.map(|p| p.name)
.unwrap_or_else(|| "unknown".to_string());
eprintln!("[assay] ALLOW {}", tool);
}
if req.is_tool_call() {
let tool = req.tool_params().map(|p| p.name);
audit_log.log(&AuditEvent {
timestamp: chrono::Utc::now().to_rfc3339(),
decision: "allow".to_string(),
tool,
reason: None,
request_id: req.id.clone(),
agentic: None,
});
}
}
}