-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmcp.rs
More file actions
861 lines (839 loc) · 29.8 KB
/
Copy pathmcp.rs
File metadata and controls
861 lines (839 loc) · 29.8 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! MCP client primitives. The dispatcher owns when this module is loaded/called.
//! This module deliberately keeps transport, protocol bounds, and safety policy
//! independent of the model/tool schema.
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Duration};
use thiserror::Error;
use tokio::{
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
process::{Child, ChildStdin, ChildStdout, Command},
sync::Mutex,
time::timeout,
};
use tokio_util::sync::CancellationToken;
const DEFAULT_MAX_BYTES: usize = 4 * 1024 * 1024;
const MAX_TOOL_ARGUMENT_BYTES: usize = 256 * 1024;
const MAX_SURFACE_RESULT_BYTES: usize = 1024 * 1024;
const SECRET_NAMES: &[&str] = &[
"key",
"token",
"secret",
"password",
"passwd",
"credential",
"auth",
];
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "transport", rename_all = "lowercase")]
pub enum TransportConfig {
Stdio {
command: String,
#[serde(default)]
args: Vec<String>,
#[serde(default)]
env: HashMap<String, String>,
#[serde(default)]
cwd: Option<PathBuf>,
},
Http {
url: String,
#[serde(default)]
headers: HashMap<String, String>,
},
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct McpConfig {
pub name: String,
#[serde(flatten)]
pub transport: TransportConfig,
#[serde(default = "default_timeout")]
pub timeout_ms: u64,
#[serde(default = "default_max_bytes")]
pub max_bytes: usize,
}
fn default_timeout() -> u64 {
30_000
}
fn default_max_bytes() -> usize {
DEFAULT_MAX_BYTES
}
impl McpConfig {
/// UI-safe view: transport target only, never env/headers.
pub fn public_view(&self) -> Value {
match &self.transport {
TransportConfig::Stdio {
command, args, env, ..
} => json!({
"name": self.name,
"transport": "stdio",
"command": command,
"args": args,
"timeout_ms": self.timeout_ms,
"has_env": !env.is_empty(),
}),
TransportConfig::Http { url, headers } => json!({
"name": self.name,
"transport": "http",
"url": url,
"timeout_ms": self.timeout_ms,
"has_headers": !headers.is_empty(),
}),
}
}
}
pub fn public_list(servers: &[McpConfig]) -> Vec<Value> {
servers.iter().map(McpConfig::public_view).collect()
}
/// Insert or replace by name. Keep env/headers/cwd/max_bytes from the existing
/// row when the incoming payload omits them (web UI never sends secrets).
pub fn upsert_server(servers: &mut Vec<McpConfig>, mut next: McpConfig) {
if let Some(existing) = servers.iter().find(|s| s.name == next.name) {
next.max_bytes = existing.max_bytes;
match (&mut next.transport, &existing.transport) {
(
TransportConfig::Stdio { env, cwd, .. },
TransportConfig::Stdio {
env: old_env,
cwd: old_cwd,
..
},
) => {
if env.is_empty() {
*env = old_env.clone();
}
if cwd.is_none() {
*cwd = old_cwd.clone();
}
}
(
TransportConfig::Http { headers, .. },
TransportConfig::Http {
headers: old_headers,
..
},
) => {
if headers.is_empty() {
*headers = old_headers.clone();
}
}
_ => {}
}
if let Some(slot) = servers.iter_mut().find(|s| s.name == next.name) {
*slot = next;
return;
}
}
servers.push(next);
}
#[derive(Debug, Error)]
pub enum McpError {
#[error("MCP transport: {0}")]
Transport(String),
#[error("MCP protocol error {code}: {message}")]
Remote {
code: i64,
message: String,
data: Option<Value>,
},
#[error("MCP response exceeded {0} bytes")]
TooLarge(usize),
#[error("MCP request timed out")]
Timeout,
#[error("MCP request cancelled")]
Cancelled,
#[error("invalid MCP response: {0}")]
Invalid(String),
}
#[derive(Debug, Error)]
pub enum McpSurfaceError {
#[error("invalid mcp tool arguments: {0}")]
InvalidArguments(String),
#[error("MCP server '{0}' is not configured in trusted user config")]
AbsentServer(String),
#[error(transparent)]
Client(#[from] McpError),
}
/// Execute the model-facing MCP surface using only a named, trusted config entry.
/// Transport details never come from tool arguments.
pub async fn execute(
servers: &[McpConfig],
args: &Value,
cancel: &CancellationToken,
) -> Result<Value, McpSurfaceError> {
let obj = args
.as_object()
.ok_or_else(|| McpSurfaceError::InvalidArguments("expected an object".to_string()))?;
const ALLOWED: &[&str] = &["action", "server", "tool", "arguments"];
if let Some(key) = obj.keys().find(|key| !ALLOWED.contains(&key.as_str())) {
return Err(McpSurfaceError::InvalidArguments(format!(
"unsupported field '{key}'; transport command, env, headers, and URL are config-only"
)));
}
if servers.is_empty() {
return Err(McpSurfaceError::AbsentServer(
"no MCP servers are configured; add trusted user config under `mcp_servers`, then retry".into(),
));
}
let action = obj
.get("action")
.and_then(Value::as_str)
.ok_or_else(|| McpSurfaceError::InvalidArguments("missing string 'action'".into()))?;
if !matches!(action, "list" | "call") {
return Err(McpSurfaceError::InvalidArguments(
"action must be 'list' or 'call'".into(),
));
}
let server_name = obj
.get("server")
.and_then(Value::as_str)
.filter(|name| !name.trim().is_empty())
.ok_or_else(|| McpSurfaceError::InvalidArguments("missing non-empty 'server'".into()))?;
let configured = servers
.iter()
.find(|server| server.name == server_name)
.cloned()
.ok_or_else(|| McpSurfaceError::AbsentServer(server_name.to_string()))?;
let mut configured = configured;
configured.max_bytes = configured.max_bytes.min(MAX_SURFACE_RESULT_BYTES);
let mut client = McpClient::connect(configured).await?;
// Always tear down the stdio child — success used to leak processes
// (CORE_REVIEW MCP process leak).
let result = match action {
"list" => {
if obj.contains_key("tool") || obj.contains_key("arguments") {
Err(McpSurfaceError::InvalidArguments(
"list accepts only action and server".into(),
))
} else {
client
.list_tools(Some(cancel))
.await
.map(|tools| json!({ "tools": tools }))
.map_err(Into::into)
}
}
"call" => {
let tool = match obj
.get("tool")
.and_then(Value::as_str)
.filter(|name| !name.trim().is_empty())
{
Some(t) => t,
None => {
let _ = client.shutdown().await;
return Err(McpSurfaceError::InvalidArguments(
"call requires non-empty 'tool'".into(),
));
}
};
let arguments = obj.get("arguments").cloned().unwrap_or_else(|| json!({}));
if !arguments.is_object() {
let _ = client.shutdown().await;
return Err(McpSurfaceError::InvalidArguments(
"'arguments' must be an object".into(),
));
}
let argument_bytes = serde_json::to_vec(&arguments)
.map_err(|e| McpSurfaceError::InvalidArguments(e.to_string()))?
.len();
if argument_bytes > MAX_TOOL_ARGUMENT_BYTES {
let _ = client.shutdown().await;
return Err(McpSurfaceError::InvalidArguments(format!(
"arguments exceed {MAX_TOOL_ARGUMENT_BYTES} bytes"
)));
}
client
.call_tool(tool, arguments, Some(cancel))
.await
.map_err(Into::into)
}
_ => unreachable!(),
};
let _ = client.shutdown().await;
result
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct McpTool {
pub name: String,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub input_schema: Value,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InitializeResult {
#[serde(default)]
pub protocol_version: Option<String>,
#[serde(default)]
pub capabilities: Value,
#[serde(default)]
pub server_info: Value,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ApprovalClass {
ReadOnly,
Mutating,
Destructive,
}
/// Split `writeFile` / `delete_file` / `s3PutObject` into lowercase tokens.
/// Non-alphanumerics, camelCase, and letter/digit boundaries all split.
fn classify_tokens(blob: &str) -> std::collections::HashSet<String> {
let mut out = std::collections::HashSet::new();
for raw in blob.split(|c: char| !c.is_ascii_alphanumeric()) {
if raw.is_empty() {
continue;
}
out.insert(raw.to_ascii_lowercase());
let mut cur = String::new();
let mut prev: Option<char> = None;
for ch in raw.chars() {
let split = match prev {
Some(p) if !cur.is_empty() => {
(p.is_ascii_lowercase() && ch.is_ascii_uppercase())
|| (p.is_ascii_digit() && ch.is_ascii_alphabetic())
|| (p.is_ascii_alphabetic() && ch.is_ascii_digit())
}
_ => false,
};
if split {
out.insert(cur.to_ascii_lowercase());
cur.clear();
}
cur.push(ch);
prev = Some(ch);
}
if !cur.is_empty() {
out.insert(cur.to_ascii_lowercase());
}
}
out
}
fn tokens_hit(toks: &std::collections::HashSet<String>, keys: &[&str]) -> bool {
keys.iter().any(|k| toks.contains(*k))
}
/// Conservative classification: remote tools are never silently treated as safe.
///
/// - Destructive/mutating verbs in the *name* (camelCase/snake_case-aware) always win.
/// - Description/args may only *raise* risk, and only for true action words
/// (`delete`/`write`/`exec`/…). Generic English/API verbs (`call`, `run`,
/// `post`, `put`, …) are name-only so “Call this to list…” / “Get post by id”
/// cannot flip a list/get tool to Destructive.
/// - READONLY is name-only: untrusted prose cannot launder an unknown or
/// mutating name into ReadOnly.
/// - Unknown / unmatched names fail closed to Destructive.
pub fn classify_tool(name: &str, description: Option<&str>, args: &Value) -> ApprovalClass {
// True action words: honored on name *and* description/args (raise-only).
const DESTRUCTIVE: &[&str] = &[
"delete", "destroy", "drop", "remove", "write", "exec", "shell", "publish", "transfer",
"commit", "push", "rm", "unlink", "kill", "truncate",
];
// Common in *descriptions* / JSON schemas (“Call this to list”, HTTP
// method enums). Only the tool name may treat these as Destructive.
const NAME_ONLY_DESTRUCTIVE: &[&str] = &[
"call", "run", "execute", "invoke", "apply", "post", "put", "patch", "send",
];
const MUTATING: &[&str] = &[
"create", "update", "edit", "modify", "move", "install", "set", "upload",
];
const READONLY: &[&str] = &[
"read", "get", "list", "fetch", "search", "show", "describe", "status", "find",
];
let name_toks = classify_tokens(name);
let desc_toks = classify_tokens(&format!("{} {}", description.unwrap_or_default(), args));
let name_readonly = tokens_hit(&name_toks, READONLY);
if tokens_hit(&name_toks, DESTRUCTIVE) || tokens_hit(&desc_toks, DESTRUCTIVE) {
ApprovalClass::Destructive
} else if tokens_hit(&name_toks, NAME_ONLY_DESTRUCTIVE) && !name_readonly {
ApprovalClass::Destructive
} else if tokens_hit(&name_toks, MUTATING) || tokens_hit(&desc_toks, MUTATING) {
ApprovalClass::Mutating
} else if name_readonly {
ApprovalClass::ReadOnly
} else {
ApprovalClass::Destructive
}
}
/// Approval class for the built-in `mcp` surface tool at **approval time**.
///
/// - `action=list` → always ReadOnly (discovery only)
/// - `action=call` → reclassify via [`classify_tool`] on the remote tool name /
/// description / arguments (CORE_REVIEW Wave 5 — no more blanket Destructive
/// for every call, and no silent ReadOnly for mutators)
/// - anything else → Destructive (fail closed)
pub fn surface_approval_class(args: &Value) -> ApprovalClass {
match args.get("action").and_then(Value::as_str).unwrap_or("") {
"list" => ApprovalClass::ReadOnly,
"call" => {
let tool = args.get("tool").and_then(Value::as_str).unwrap_or("");
let description = args.get("description").and_then(Value::as_str);
let call_args = args.get("arguments").cloned().unwrap_or_else(|| json!({}));
classify_tool(tool, description, &call_args)
}
_ => ApprovalClass::Destructive,
}
}
/// Remove likely secrets before exposing a configured environment to a child.
pub fn filter_environment(env: &HashMap<String, String>) -> HashMap<String, String> {
env.iter()
.filter(|(k, _)| {
let l = k.to_ascii_lowercase();
!SECRET_NAMES.iter().any(|x| l.contains(x))
})
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}
struct StdioTransport {
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
}
enum Transport {
Stdio(Arc<Mutex<StdioTransport>>),
Http {
client: reqwest::Client,
url: String,
headers: HashMap<String, String>,
},
}
pub struct McpClient {
transport: Transport,
next_id: u64,
max_bytes: usize,
timeout: Duration,
initialized: bool,
}
impl McpClient {
pub async fn connect(config: McpConfig) -> Result<Self, McpError> {
let max_bytes = config.max_bytes.min(64 * 1024 * 1024).max(1024);
let transport = match config.transport {
TransportConfig::Stdio {
command,
args,
env,
cwd,
} => {
let mut c = Command::new(command);
c.args(args);
c.env_clear();
c.envs(filter_environment(&env));
if let Some(d) = cwd {
c.current_dir(d);
}
let mut child = c
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|e| McpError::Transport(e.to_string()))?;
let stdin = child
.stdin
.take()
.ok_or_else(|| McpError::Transport("missing stdin".into()))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| McpError::Transport("missing stdout".into()))?;
Transport::Stdio(Arc::new(Mutex::new(StdioTransport {
child,
stdin,
stdout: BufReader::new(stdout),
})))
}
TransportConfig::Http { url, headers } => Transport::Http {
client: reqwest::Client::new(),
url,
headers,
},
};
let mut c = Self {
transport,
next_id: 1,
max_bytes,
timeout: Duration::from_millis(config.timeout_ms.clamp(100, 300_000)),
initialized: false,
};
c.initialize().await?;
Ok(c)
}
async fn request(
&mut self,
method: &str,
params: Value,
cancel: Option<&CancellationToken>,
) -> Result<Value, McpError> {
let id = self.next_id;
self.next_id += 1;
let req = json!({"jsonrpc":"2.0","id":id,"method":method,"params":params});
let fut = async {
match &self.transport {
Transport::Http {
client,
url,
headers,
} => {
let mut r = client.post(url).json(&req);
for (k, v) in headers {
r = r.header(k, v);
}
let b = r
.send()
.await
.map_err(|e| McpError::Transport(e.to_string()))?
.bytes()
.await
.map_err(|e| McpError::Transport(e.to_string()))?;
if b.len() > self.max_bytes {
return Err(McpError::TooLarge(self.max_bytes));
}
serde_json::from_slice(&b).map_err(|e| McpError::Invalid(e.to_string()))
}
Transport::Stdio(t) => {
let mut t = t.lock().await;
let bytes = serde_json::to_vec(&req).unwrap();
t.stdin
.write_all(format!("Content-Length: {}\r\n\r\n", bytes.len()).as_bytes())
.await
.map_err(|e| McpError::Transport(e.to_string()))?;
t.stdin
.write_all(&bytes)
.await
.map_err(|e| McpError::Transport(e.to_string()))?;
t.stdin
.flush()
.await
.map_err(|e| McpError::Transport(e.to_string()))?;
read_message(&mut t.stdout, self.max_bytes).await
}
}
};
let v = if let Some(tok) = cancel {
tokio::select! { _=tok.cancelled()=>Err(McpError::Cancelled), x=timeout(self.timeout,fut)=>x.map_err(|_|McpError::Timeout).and_then(|x|x) }
} else {
timeout(self.timeout, fut)
.await
.map_err(|_| McpError::Timeout)
.and_then(|x| x)
}?;
if let Some(e) = v.get("error") {
return Err(McpError::Remote {
code: e.get("code").and_then(Value::as_i64).unwrap_or(-1),
message: e
.get("message")
.and_then(Value::as_str)
.unwrap_or("unknown")
.into(),
data: e.get("data").cloned(),
});
}
v.get("result")
.cloned()
.ok_or_else(|| McpError::Invalid("missing result".into()))
}
pub async fn initialize(&mut self) -> Result<InitializeResult, McpError> {
let v=self.request("initialize",json!({"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"catalyst-code","version":"0.2"}}),None).await?;
let r: InitializeResult =
serde_json::from_value(v).map_err(|e| McpError::Invalid(e.to_string()))?;
let _ = self.notify("notifications/initialized", json!({})).await;
self.initialized = true;
Ok(r)
}
async fn notify(&self, method: &str, params: Value) -> Result<(), McpError> {
if let Transport::Stdio(t) = &self.transport {
let mut t = t.lock().await;
let b = serde_json::to_vec(&json!({"jsonrpc":"2.0","method":method,"params":params}))
.unwrap();
t.stdin
.write_all(format!("Content-Length: {}\r\n\r\n", b.len()).as_bytes())
.await
.map_err(|e| McpError::Transport(e.to_string()))?;
t.stdin
.write_all(&b)
.await
.map_err(|e| McpError::Transport(e.to_string()))?;
t.stdin
.flush()
.await
.map_err(|e| McpError::Transport(e.to_string()))?;
}
Ok(())
}
pub async fn list_tools(
&mut self,
cancel: Option<&CancellationToken>,
) -> Result<Vec<McpTool>, McpError> {
let v = self.request("tools/list", json!({}), cancel).await?;
serde_json::from_value(v.get("tools").cloned().unwrap_or_else(|| json!([])))
.map_err(|e| McpError::Invalid(e.to_string()))
}
pub async fn call_tool(
&mut self,
name: &str,
arguments: Value,
cancel: Option<&CancellationToken>,
) -> Result<Value, McpError> {
self.request(
"tools/call",
json!({"name":name,"arguments":arguments}),
cancel,
)
.await
}
pub async fn shutdown(&mut self) -> Result<(), McpError> {
let _ = self.notify("notifications/cancelled", json!({})).await;
if let Transport::Stdio(t) = &self.transport {
let mut t = t.lock().await;
t.child
.kill()
.await
.map_err(|e| McpError::Transport(e.to_string()))?;
}
Ok(())
}
}
async fn read_message(r: &mut BufReader<ChildStdout>, max: usize) -> Result<Value, McpError> {
let mut len = None;
let mut line = String::new();
loop {
line.clear();
if r.read_line(&mut line)
.await
.map_err(|e| McpError::Transport(e.to_string()))?
== 0
{
return Err(McpError::Transport("server closed stdout".into()));
}
if line == "\r\n" || line == "\n" {
break;
}
if let Some(v) = line.strip_prefix("Content-Length:") {
len = Some(
v.trim()
.parse::<usize>()
.map_err(|_| McpError::Invalid("bad content length".into()))?,
);
}
}
let n = len.ok_or_else(|| McpError::Invalid("missing content length".into()))?;
if n > max {
return Err(McpError::TooLarge(max));
}
let mut b = vec![0; n];
r.read_exact(&mut b)
.await
.map_err(|e| McpError::Transport(e.to_string()))?;
serde_json::from_slice(&b).map_err(|e| McpError::Invalid(e.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn secrets_filtered() {
let e = HashMap::from([
("PATH".into(), "x".into()),
("API_TOKEN".into(), "y".into()),
]);
assert!(filter_environment(&e).contains_key("PATH"));
assert!(!filter_environment(&e).contains_key("API_TOKEN"));
}
#[test]
fn conservative_approval() {
assert_eq!(
classify_tool("read", None, &json!({})),
ApprovalClass::ReadOnly
);
assert_eq!(
classify_tool("delete_file", None, &json!({})),
ApprovalClass::Destructive
);
assert_eq!(
classify_tool("create_issue", None, &json!({})),
ApprovalClass::Mutating
);
// Unknown names fail closed (not ReadOnly).
assert_eq!(
classify_tool("frobnicate", None, &json!({})),
ApprovalClass::Destructive
);
// camelCase mutators are not laundered by a read-only description.
assert_eq!(
classify_tool("writeFile", Some("Read and list file contents"), &json!({})),
ApprovalClass::Destructive
);
assert_eq!(
classify_tool("deleteFile", Some("Get status"), &json!({})),
ApprovalClass::Destructive
);
// Prose "Call this to list…" must not flip a list/get tool to Destructive.
assert_eq!(
classify_tool(
"list_issues",
Some("Call this to list GitHub issues"),
&json!({})
),
ApprovalClass::ReadOnly
);
}
#[test]
fn classify_tool_advisor_prose_and_camelcase_cases() {
// Ordinary list/get tools stay ReadOnly even when the description or
// JSON schema blob uses instruction/API verbs.
assert_eq!(
classify_tool("list_dir", Some("Call this to list files"), &json!({})),
ApprovalClass::ReadOnly
);
assert_eq!(
classify_tool("list_files", Some("Call this to list files"), &json!({})),
ApprovalClass::ReadOnly
);
assert_eq!(
classify_tool(
"get_post",
Some("Get post by id. Run a search if missing."),
&json!({"method": "GET", "description": "call this to fetch a post"})
),
ApprovalClass::ReadOnly
);
// camelCase mutators / RCE stay Destructive; prose cannot launder them.
assert_eq!(
classify_tool("writeFile", Some("Get path and persist"), &json!({})),
ApprovalClass::Destructive
);
assert_eq!(
classify_tool("executeCode", Some("Show snippet output"), &json!({})),
ApprovalClass::Destructive
);
assert_eq!(
classify_tool("deleteItems", Some("List of ids"), &json!({})),
ApprovalClass::Destructive
);
assert_eq!(
classify_tool("readFile", None, &json!({})),
ApprovalClass::ReadOnly
);
// Compound names still see the write token.
assert_eq!(
classify_tool("read_write_status", None, &json!({})),
ApprovalClass::Destructive
);
// Unknown names fail closed.
assert_eq!(
classify_tool("frobnicate", Some("Get status"), &json!({})),
ApprovalClass::Destructive
);
}
#[test]
fn surface_approval_list_stays_readonly() {
assert_eq!(
surface_approval_class(&json!({"action": "list", "server": "fs"})),
ApprovalClass::ReadOnly
);
}
#[test]
fn surface_approval_call_reclassifies_remote_tool() {
// Read-like remote tool → ReadOnly at approval (not blanket Destructive).
assert_eq!(
surface_approval_class(&json!({
"action": "call",
"server": "fs",
"tool": "read_file",
"arguments": {"path": "README.md"}
})),
ApprovalClass::ReadOnly
);
// Mutating remote tool → Mutating.
assert_eq!(
surface_approval_class(&json!({
"action": "call",
"server": "fs",
"tool": "create_file",
"arguments": {"path": "x"}
})),
ApprovalClass::Mutating
);
// Destructive remote tool → Destructive.
assert_eq!(
surface_approval_class(&json!({
"action": "call",
"server": "fs",
"tool": "delete_file",
"arguments": {"path": "x"}
})),
ApprovalClass::Destructive
);
// Description can tip classification when the name is neutral.
assert_eq!(
surface_approval_class(&json!({
"action": "call",
"server": "fs",
"tool": "run",
"description": "execute shell command",
"arguments": {}
})),
ApprovalClass::Destructive
);
// Unknown action fails closed.
assert_eq!(
surface_approval_class(&json!({"action": "weird"})),
ApprovalClass::Destructive
);
}
#[tokio::test]
async fn surface_rejects_transport_in_model_args() {
let token = CancellationToken::new();
let err = execute(
&[],
&json!({"action":"list","server":"x","command":"rm"}),
&token,
)
.await
.unwrap_err();
assert!(err.to_string().contains("config-only"));
}
#[tokio::test]
async fn surface_reports_absent_server_before_connecting() {
let token = CancellationToken::new();
let err = execute(&[], &json!({"action":"list","server":"missing"}), &token)
.await
.unwrap_err();
assert!(err.to_string().contains("not configured"));
}
#[test]
fn upsert_preserves_env_and_headers() {
let mut servers = vec![McpConfig {
name: "gh".into(),
transport: TransportConfig::Stdio {
command: "npx".into(),
args: vec!["-y".into(), "old".into()],
env: [("TOKEN".into(), "secret".into())].into_iter().collect(),
cwd: None,
},
timeout_ms: 30_000,
max_bytes: 99,
}];
upsert_server(
&mut servers,
McpConfig {
name: "gh".into(),
transport: TransportConfig::Stdio {
command: "npx".into(),
args: vec!["-y".into(), "new".into()],
env: Default::default(),
cwd: None,
},
timeout_ms: 10_000,
max_bytes: 4 * 1024 * 1024,
},
);
assert_eq!(servers.len(), 1);
match &servers[0].transport {
TransportConfig::Stdio { args, env, .. } => {
assert_eq!(args, &vec!["-y".to_string(), "new".to_string()]);
assert_eq!(env.get("TOKEN").map(String::as_str), Some("secret"));
}
other => panic!("{other:?}"),
}
assert_eq!(servers[0].max_bytes, 99);
}
}