use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use futures::StreamExt;
use serde_json::{Value, json};
use web_time::SystemTime;
use super::*;
use crate::cli::Cli;
use crate::command::{CommandContext, CommandDef, CommandHandler};
use crate::mcp::files::{FileStaging, FormField, McpFilesOptions, StagedTarget, file_schema};
use crate::mcp::{
McpDiscovery, McpHttpBody, McpHttpConfig, McpHttpRequest, McpHttpServer, McpRemoteOptions,
McpServeOptions, McpToolFilter,
};
use crate::outbound::{HttpClientError, HttpRequest, HttpResponse};
use crate::output::CommandResult;
const MCP_URL: &str = "http://localhost/mcp";
const KEY: &[u8] = b"0123456789abcdef0123456789abcdef";
#[derive(Default)]
struct Staging {
staged: Mutex<BTreeMap<String, Vec<u8>>>,
issued: AtomicUsize,
form: bool,
}
#[async_trait::async_trait]
impl FileStaging for Staging {
async fn issue(&self, file: &FileInput, _expires: SystemTime) -> Result<StagedTarget, String> {
let handle = format!("{}-{}", file.id, self.issued.fetch_add(1, Ordering::SeqCst));
let mut target = UploadTarget {
url: Some(format!("https://uploads.example/{handle}")),
credentials: "omit".into(),
..UploadTarget::default()
};
if self.form {
target.method = Some("POST".into());
target.form = Some(UploadForm {
fields: vec![
FormField {
name: "key".into(),
value: handle.clone(),
},
FormField {
name: "policy".into(),
value: "p=1; q=\"x\"".into(),
},
],
file_field: "file".into(),
});
}
Ok(StagedTarget { target, handle })
}
async fn confirm(&self, handle: &str, _file: &FileInput) -> Result<Option<Vec<u8>>, String> {
Ok(self.staged.lock().unwrap().get(handle).cloned())
}
async fn consume(&self, _state_id: &str, _expires: SystemTime) -> Result<bool, String> {
Ok(true)
}
}
struct ReadsFile {
runs: Arc<AtomicUsize>,
}
#[async_trait::async_trait]
impl CommandHandler for ReadsFile {
async fn run(&self, ctx: CommandContext) -> CommandResult {
self.runs.fetch_add(1, Ordering::SeqCst);
let text = FileInput::from_value(&ctx.options["upload"])
.and_then(|file| file.bytes())
.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
.unwrap_or_else(|error| format!("error: {error}"));
CommandResult::Ok {
data: json!({ "text": text }),
cta: None,
exit_code: None,
}
}
}
#[derive(Clone, Debug)]
struct Sent {
method: String,
url: String,
headers: Vec<(String, String)>,
body: Vec<u8>,
}
type Override = Box<dyn Fn(&Value) -> Option<Value> + Send + Sync>;
type Download = (Vec<(String, String)>, Vec<Vec<u8>>);
struct Host {
server: McpHttpServer,
staging: Arc<Staging>,
storage: Mutex<Vec<Sent>>,
statuses: Mutex<VecDeque<u16>>,
calls: Mutex<Vec<Value>>,
replace: Mutex<Option<Override>>,
downloads: Mutex<HashMap<String, Download>>,
overread: Arc<AtomicBool>,
}
impl Host {
fn storage(&self) -> Vec<Sent> {
self.storage.lock().unwrap().clone()
}
fn tool_calls(&self) -> Vec<Value> {
self.calls
.lock()
.unwrap()
.iter()
.filter(|message| message["method"] == "tools/call")
.cloned()
.collect()
}
fn store(&self, request: &HttpRequest, body: &[u8]) {
let handle = request
.url
.rsplit('/')
.next()
.unwrap_or_default()
.to_string();
let bytes = if request.method == "POST" {
file_part(request, body)
} else {
body.to_vec()
};
self.staging.staged.lock().unwrap().insert(handle, bytes);
}
}
fn file_part(request: &HttpRequest, body: &[u8]) -> Vec<u8> {
let boundary = header(&request.headers, "content-type")
.and_then(|value| value.split("boundary=").nth(1).map(str::to_string))
.unwrap();
let text = body.to_vec();
let marker = b"filename=";
let at = text
.windows(marker.len())
.position(|w| w == marker)
.unwrap();
let start = at
+ text[at..]
.windows(4)
.position(|w| w == b"\r\n\r\n")
.unwrap()
+ 4;
let end_marker = format!("\r\n--{boundary}--\r\n");
let end = text.len() - end_marker.len();
assert_eq!(&text[end..], end_marker.as_bytes());
text[start..end].to_vec()
}
fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
headers
.iter()
.find(|(key, _)| key.eq_ignore_ascii_case(name))
.map(|(_, value)| value.as_str())
}
#[async_trait::async_trait]
impl crate::outbound::HttpClient for Host {
async fn send(&self, request: HttpRequest) -> Result<HttpResponse, HttpClientError> {
let body = request.body.clone().unwrap_or_default();
if !request.url.starts_with(MCP_URL) {
self.storage.lock().unwrap().push(Sent {
method: request.method.clone(),
url: request.url.clone(),
headers: request.headers.clone(),
body: body.clone(),
});
let status = self.statuses.lock().unwrap().pop_front().unwrap_or(200);
if status == 0 {
return Err(HttpClientError::transport_message("connection reset"));
}
if request.method == "GET" {
let (headers, chunks) = self
.downloads
.lock()
.unwrap()
.get(&request.url)
.cloned()
.unwrap_or_default();
let overread = self.overread.clone();
let tail = futures::stream::once(async move {
overread.store(true, Ordering::SeqCst);
Ok(Vec::new())
});
let body = futures::stream::iter(chunks.into_iter().map(Ok)).chain(tail);
return Ok(HttpResponse {
status,
headers,
body: Box::pin(body),
});
}
if (200..300).contains(&status) {
self.store(&request, &body);
}
return Ok(respond(status, Vec::new(), Vec::new()));
}
let message: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
self.calls.lock().unwrap().push(message.clone());
if let Some(result) = self
.replace
.lock()
.unwrap()
.as_ref()
.and_then(|f| f(&message))
{
let reply = json!({ "jsonrpc": "2.0", "id": message["id"], "result": result });
return Ok(respond(
200,
vec![("content-type".into(), "application/json".into())],
serde_json::to_vec(&reply).unwrap(),
));
}
let mut headers = request.headers.clone();
headers.push(("host".into(), "localhost".into()));
let response = self
.server
.handle(McpHttpRequest {
method: request.method.clone(),
path: "/mcp".into(),
headers,
body,
})
.await;
let bytes = match response.body {
McpHttpBody::Empty => Vec::new(),
McpHttpBody::Full(bytes) => bytes,
McpHttpBody::EventStream(stream) => {
stream.collect::<Vec<_>>().await.concat().into_bytes()
}
};
Ok(respond(response.status, response.headers, bytes))
}
}
fn respond(status: u16, headers: Vec<(String, String)>, body: Vec<u8>) -> HttpResponse {
HttpResponse {
status,
headers,
body: Box::pin(futures::stream::once(async move { Ok(body) })),
}
}
struct Fixture {
host: Arc<Host>,
client: McpHttpClient,
runs: Arc<AtomicUsize>,
}
async fn fixture(staging: bool, form: bool) -> Fixture {
let runs = Arc::new(AtomicUsize::new(0));
let store = Arc::new(Staging {
form,
..Staging::default()
});
let command = CommandDef::build("ingest", ReadsFile { runs: runs.clone() })
.description("Reads an uploaded file")
.mcp_input_schema(json!({
"type": "object",
"properties": { "upload": file_schema(&["text/*"], Some(64), false) },
"required": ["upload"]
}))
.done();
let cli = Cli::create("files").command("ingest", command);
let server = McpHttpServer::new(
&cli,
&McpServeOptions {
tools: McpToolFilter {
discovery: McpDiscovery::Direct,
..Default::default()
},
..McpServeOptions::default()
},
McpHttpConfig {
files: Some(McpFilesOptions {
max_inline_bytes: 32,
staging: staging.then(|| store.clone() as Arc<dyn FileStaging>),
signing_key: KEY.to_vec(),
..McpFilesOptions::default()
}),
..McpHttpConfig::default()
},
)
.unwrap();
let host = Arc::new(Host {
server,
staging: store,
storage: Mutex::default(),
statuses: Mutex::default(),
calls: Mutex::default(),
replace: Mutex::default(),
downloads: Mutex::default(),
overread: Arc::default(),
});
let client = McpHttpClient::connect(
MCP_URL,
&McpRemoteOptions {
auth_token: Some("secret-token".into()),
http_client: Some(host.clone()),
..McpRemoteOptions::default()
},
)
.await
.unwrap();
Fixture { host, client, runs }
}
fn arguments(bytes: &[u8]) -> Map<String, Value> {
let file = FileInput::metadata("doc", Some("notes/a\"b.txt".into()), "text/plain", bytes);
let mut arguments = Map::new();
arguments.insert("upload".into(), serde_json::to_value(file).unwrap());
arguments
}
fn files(bytes: &[u8]) -> HashMap<String, Vec<u8>> {
HashMap::from([("doc".to_string(), bytes.to_vec())])
}
fn text(outcome: McpToolOutcome) -> Value {
let McpToolOutcome::Complete(result) = outcome else {
panic!("expected a complete result");
};
let text = result["content"][0]["text"].as_str().unwrap_or_default();
serde_json::from_str::<Value>(text).unwrap_or(Value::Null)["text"].clone()
}
const LARGE: &[u8] = b"forty bytes of text that exceed the inline";
#[tokio::test]
async fn small_files_travel_inline_without_storage() {
let Fixture { host, client, runs } = fixture(true, false).await;
assert_eq!(client.files_max_inline_bytes(), Some(32));
assert!(client.files_upload_enabled());
let outcome = client
.call_tool_with_files(
"ingest",
arguments(b"hello"),
&files(b"hello"),
&Default::default(),
)
.await
.unwrap();
assert_eq!(text(outcome), "hello");
assert!(host.storage().is_empty());
assert_eq!(runs.load(Ordering::SeqCst), 1);
let calls = host.tool_calls();
assert_eq!(calls.len(), 1);
assert_eq!(
calls[0]["params"]["arguments"]["upload"]["data"],
"aGVsbG8="
);
}
#[tokio::test]
async fn large_files_upload_then_the_call_retries_once() {
let Fixture { host, client, runs } = fixture(true, false).await;
assert!(LARGE.len() > 32);
let outcome = client
.call_tool_with_files(
"ingest",
arguments(LARGE),
&files(LARGE),
&Default::default(),
)
.await
.unwrap();
assert_eq!(text(outcome), String::from_utf8_lossy(LARGE).as_ref());
assert_eq!(runs.load(Ordering::SeqCst), 1);
let storage = host.storage();
assert_eq!(storage.len(), 1);
assert_eq!(storage[0].method, "PUT");
assert!(storage[0].url.starts_with("https://uploads.example/doc-"));
assert_eq!(storage[0].body, LARGE);
assert_eq!(
header(&storage[0].headers, "authorization"),
None,
"credentials omit"
);
assert_eq!(
header(&storage[0].headers, "content-type"),
None,
"headers lists none"
);
let calls = host.tool_calls();
assert_eq!(calls.len(), 2);
let declared = &calls[0]["params"]["_meta"]["io.modelcontextprotocol/clientCapabilities"]["extensions"]
["io.modelcontextprotocol/files"];
assert_eq!(declared, &json!({ "upload": {} }));
assert!(
calls[0]["params"]["arguments"]["upload"]
.get("data")
.is_none()
);
assert_eq!(
calls[0]["params"]["arguments"],
calls[1]["params"]["arguments"]
);
assert_ne!(calls[0]["id"], calls[1]["id"]);
assert!(calls[1]["params"]["requestState"].is_string());
}
#[tokio::test]
async fn a_put_repeats_after_a_server_error_but_a_post_does_not() {
let Fixture { host, client, runs } = fixture(true, false).await;
host.statuses.lock().unwrap().extend([503, 0]);
let outcome = client
.call_tool_with_files(
"ingest",
arguments(LARGE),
&files(LARGE),
&Default::default(),
)
.await
.unwrap();
assert_eq!(text(outcome), String::from_utf8_lossy(LARGE).as_ref());
assert_eq!(host.storage().len(), 3);
assert_eq!(runs.load(Ordering::SeqCst), 1);
let Fixture { host, client, runs } = fixture(true, true).await;
host.statuses.lock().unwrap().push_back(503);
let error = client
.call_tool_with_files(
"ingest",
arguments(LARGE),
&files(LARGE),
&Default::default(),
)
.await
.unwrap_err();
assert_eq!(error.code(), "MCP_FILE_UPLOAD_FAILED", "{error}");
assert_eq!(host.storage().len(), 1);
assert_eq!(
host.tool_calls().len(),
1,
"no retry after a failed transfer"
);
assert_eq!(runs.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn a_redirect_fails_the_transfer_without_following_it() {
let Fixture { host, client, runs } = fixture(true, false).await;
host.statuses.lock().unwrap().push_back(302);
let error = client
.call_tool_with_files(
"ingest",
arguments(LARGE),
&files(LARGE),
&Default::default(),
)
.await
.unwrap_err();
assert_eq!(error.code(), "MCP_FILE_UPLOAD_FAILED");
assert_eq!(host.storage().len(), 1);
assert_eq!(host.tool_calls().len(), 1);
assert_eq!(runs.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn form_targets_send_fields_in_order_then_the_file() {
let Fixture { host, client, runs } = fixture(true, true).await;
let outcome = client
.call_tool_with_files(
"ingest",
arguments(LARGE),
&files(LARGE),
&Default::default(),
)
.await
.unwrap();
assert_eq!(text(outcome), String::from_utf8_lossy(LARGE).as_ref());
assert_eq!(runs.load(Ordering::SeqCst), 1);
let sent = host.storage().remove(0);
assert_eq!(sent.method, "POST");
let content_type = header(&sent.headers, "content-type").unwrap().to_string();
let boundary = content_type
.strip_prefix("multipart/form-data; boundary=multicast-")
.unwrap();
assert_eq!(boundary.len(), 32);
assert!(boundary.bytes().all(|byte| byte.is_ascii_hexdigit()));
let parsed = python_multipart(&content_type, &sent.body);
let handle = sent.url.rsplit('/').next().unwrap();
assert_eq!(
parsed,
json!([
{ "name": "key", "filename": null, "type": "text/plain", "body": handle },
{ "name": "policy", "filename": null, "type": "text/plain", "body": "p=1; q=\"x\"" },
{
"name": "file",
"filename": "a%22b.txt",
"type": "text/plain",
"body": String::from_utf8_lossy(LARGE),
},
])
);
}
fn python_multipart(content_type: &str, body: &[u8]) -> Value {
use std::io::Write;
const SCRIPT: &str = r#"
import email.parser, email.policy, json, sys
data = sys.stdin.buffer.read()
head = ("Content-Type: " + sys.argv[1] + "\r\n\r\n").encode()
message = email.parser.BytesParser(policy=email.policy.HTTP).parsebytes(head + data)
parts = []
for part in message.iter_parts():
disposition = part.get("Content-Disposition")
parts.append({
"name": disposition.params.get("name"),
"filename": disposition.params.get("filename"),
"type": part.get_content_type(),
"body": part.get_payload(decode=True).decode(),
})
print(json.dumps(parts))
"#;
let mut child = std::process::Command::new("python3")
.args(["-I", "-c", SCRIPT, content_type])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.expect("python3 parses the multipart body");
child.stdin.take().unwrap().write_all(body).unwrap();
let output = child.wait_with_output().unwrap();
assert!(output.status.success());
serde_json::from_slice(&output.stdout).unwrap()
}
#[tokio::test]
async fn too_large_files_fail_before_calling_a_server_without_uploads() {
let Fixture { host, client, runs } = fixture(false, false).await;
assert!(!client.files_upload_enabled());
let error = client
.call_tool_with_files(
"ingest",
arguments(LARGE),
&files(LARGE),
&Default::default(),
)
.await
.unwrap_err();
assert_eq!(error.code(), "MCP_FILE_UPLOAD_FAILED");
assert!(host.tool_calls().is_empty());
assert_eq!(runs.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn file_arguments_must_match_their_bytes() {
let Fixture { host, client, .. } = fixture(true, false).await;
let options = McpFileUploadOptions::default();
let wrong_size = client
.call_tool_with_files("ingest", arguments(b"hello"), &files(b"hell"), &options)
.await
.unwrap_err();
assert_eq!(wrong_size.code(), "MCP_FILE_UPLOAD_FAILED");
let mut extra = files(b"hello");
extra.insert("other".into(), b"x".to_vec());
let unmatched = client
.call_tool_with_files("ingest", arguments(b"hello"), &extra, &options)
.await
.unwrap_err();
assert_eq!(unmatched.code(), "MCP_FILE_UPLOAD_FAILED");
let mut twice = arguments(b"hello");
twice.insert("copy".into(), twice["upload"].clone());
let duplicate = client
.call_tool_with_files("ingest", twice, &files(b"hello"), &options)
.await
.unwrap_err();
assert_eq!(duplicate.code(), "MCP_FILE_UPLOAD_FAILED");
assert!(host.tool_calls().is_empty());
}
fn upload_required(uploads: Value) -> Override {
Box::new(move |message| {
(message["method"] == "tools/call").then(
|| json!({ "resultType": "upload_required", "uploads": uploads, "requestState": "s" }),
)
})
}
#[tokio::test]
async fn malformed_upload_requests_fail_before_any_transfer() {
let target = |extra: Value| {
let mut target =
json!({ "fileId": "doc", "url": "https://uploads.example/x", "credentials": "omit" });
target
.as_object_mut()
.unwrap()
.extend(extra.as_object().unwrap().clone());
target
};
for (label, uploads) in [
("unknown member", json!([target(json!({ "priority": 1 }))])),
(
"unknown file",
json!([target(json!({ "fileId": "other" }))]),
),
(
"listed twice",
json!([target(json!({})), target(json!({}))]),
),
("missing file", json!([])),
(
"unknown form member",
json!([target(
json!({ "method": "POST", "form": { "fields": [], "fileField": "f", "x": 1 } })
)]),
),
] {
let Fixture { host, client, runs } = fixture(true, false).await;
*host.replace.lock().unwrap() = Some(upload_required(uploads));
let error = client
.call_tool_with_files(
"ingest",
arguments(LARGE),
&files(LARGE),
&Default::default(),
)
.await
.unwrap_err();
assert!(
matches!(
error.code(),
"MCP_FILE_UPLOAD_FAILED" | "MCP_PROTOCOL_ERROR"
),
"{label}: {error}"
);
assert!(host.storage().is_empty(), "{label}");
assert_eq!(host.tool_calls().len(), 1, "{label}");
assert_eq!(runs.load(Ordering::SeqCst), 0, "{label}");
}
let Fixture { host, client, .. } = fixture(true, false).await;
*host.replace.lock().unwrap() =
Some(upload_required(json!([target(json!({ "headers": null }))])));
let error = client
.call_tool_with_files(
"ingest",
arguments(LARGE),
&files(LARGE),
&Default::default(),
)
.await
.unwrap_err();
assert!(
error.to_string().contains("second upload"),
"a null member is absent: {error}"
);
assert_eq!(host.storage().len(), 1);
assert_eq!(host.tool_calls().len(), 2);
}
fn plan(
client: &McpHttpClient,
target: Value,
options: &McpFileUploadOptions,
) -> Result<Planned, McpClientError> {
let mut target = target;
target
.as_object_mut()
.unwrap()
.entry("fileId")
.or_insert(json!("doc"));
target
.as_object_mut()
.unwrap()
.entry("credentials")
.or_insert(json!("omit"));
client.plan(&parse_target(&target)?, options)
}
#[tokio::test]
async fn targets_that_break_a_client_rule_are_rejected() {
let Fixture { client, .. } = fixture(true, false).await;
let options = McpFileUploadOptions::default();
let url = "https://uploads.example/x";
for (label, target) in [
("http url", json!({ "url": "http://uploads.example/x" })),
("relative url", json!({ "url": "/x" })),
(
"userinfo",
json!({ "url": "https://user:pw@uploads.example/x" }),
),
("private v4", json!({ "url": "https://10.1.2.3/x" })),
("link-local", json!({ "url": "https://169.254.169.254/x" })),
("loopback v6", json!({ "url": "https://[::1]/x" })),
(
"mapped v4",
json!({ "url": "https://[::ffff:192.168.0.1]/x" }),
),
("localhost", json!({ "url": "https://localhost/x" })),
("both", json!({ "url": url, "path": "/x" })),
("neither", json!({})),
("dot segment", json!({ "path": "/a/../b" })),
("empty segment", json!({ "path": "/a//b" })),
("no slash", json!({ "path": "a" })),
("method", json!({ "url": url, "method": "DELETE" })),
(
"credentials",
json!({ "url": url, "credentials": "same-origin" }),
),
(
"include elsewhere",
json!({ "url": url, "credentials": "include" }),
),
(
"authorization",
json!({ "url": url, "headers": { "Authorization": "x" } }),
),
(
"cookie",
json!({ "url": url, "headers": { "cookie": "x" } }),
),
(
"forbidden",
json!({ "url": url, "headers": { "Host": "evil" } }),
),
(
"sec prefix",
json!({ "url": url, "headers": { "Sec-Fetch-Mode": "cors" } }),
),
(
"invalid value",
json!({ "url": url, "headers": { "X-A": "a\nb" } }),
),
(
"invalid name",
json!({ "url": url, "headers": { "X A": "a" } }),
),
(
"routing on path",
json!({ "path": "/up", "headers": { "X-Forwarded-Host": "evil" } }),
),
(
"form put",
json!({ "url": url, "method": "PUT", "form": { "fields": [], "fileField": "f" } }),
),
(
"form content type",
json!({ "url": url, "method": "POST", "headers": { "Content-Type": "a/b" }, "form": { "fields": [], "fileField": "f" } }),
),
(
"empty file field",
json!({ "url": url, "method": "POST", "form": { "fields": [], "fileField": "" } }),
),
(
"quoted field",
json!({ "url": url, "method": "POST", "form": { "fields": [{ "name": "a\"", "value": "v" }], "fileField": "f" } }),
),
(
"field is file",
json!({ "url": url, "method": "POST", "form": { "fields": [{ "name": "f", "value": "v" }], "fileField": "f" } }),
),
(
"field newline",
json!({ "url": url, "method": "POST", "form": { "fields": [{ "name": "a", "value": "v\r\n" }], "fileField": "f" } }),
),
] {
let outcome = plan(&client, target, &options);
assert!(outcome.is_err(), "{label} was accepted");
}
let routed = plan(
&client,
json!({ "url": url, "headers": { "X-Forwarded-Host": "a", "X-Amz-Acl": "private" } }),
&options,
)
.unwrap();
assert_eq!(
routed.headers.len(),
2,
"routing headers pass on an omit url target"
);
let path = plan(
&client,
json!({ "path": "/uploads/a.b-c_d~e", "credentials": "include" }),
&options,
)
.unwrap();
assert_eq!(path.url.as_str(), "http://localhost/mcp/uploads/a.b-c_d~e");
assert_eq!(
path.headers.get("authorization").unwrap(),
"Bearer secret-token"
);
let same = plan(
&client,
json!({ "url": "http://localhost/elsewhere", "credentials": "include" }),
&McpFileUploadOptions {
allowed_hosts: vec!["LOCALHOST".into()],
..McpFileUploadOptions::default()
},
)
.unwrap();
assert_eq!(
same.headers.get("authorization").unwrap(),
"Bearer secret-token"
);
let omitted = plan(&client, json!({ "path": "/up" }), &options).unwrap();
assert!(omitted.headers.get("authorization").is_none());
assert!(plan(&client, json!({ "url": "https://8.8.8.8/x" }), &options).is_ok());
assert!(
plan(
&client,
json!({ "url": "https://[2606:4700::1111]/x" }),
&options
)
.is_ok()
);
}
#[test]
fn multipart_names_and_types_follow_the_encoding_rules() {
assert_eq!(
form_filename(Some("dir/sub\\a\"b\r\n.txt")),
"a%22b%0D%0A.txt"
);
assert_eq!(form_filename(Some("..")), "file");
assert_eq!(form_filename(Some("x/")), "file");
assert_eq!(form_filename(None), "file");
assert!(valid_media_type("text/plain; charset=utf-8"));
assert!(!valid_media_type("text"));
assert!(!valid_media_type("text/pl ain"));
let file = Located {
id: "doc".into(),
name: None,
mime_type: "nonsense".into(),
bytes: b"xy",
};
let form = UploadForm {
fields: vec![],
file_field: "f".into(),
};
let (content_type, body) = multipart(&form, &file, "B");
assert_eq!(content_type, "multipart/form-data; boundary=B");
assert_eq!(
body,
b"--B\r\nContent-Disposition: form-data; name=\"f\"; filename=\"file\"\r\nContent-Type: application/octet-stream\r\n\r\nxy\r\n--B--\r\n"
);
}
const REPORT: &[u8] = b"quarterly report";
fn serve(host: &Host, url: &str, headers: Vec<(String, String)>, chunks: Vec<&[u8]>) {
host.downloads.lock().unwrap().insert(
url.to_string(),
(headers, chunks.into_iter().map(<[u8]>::to_vec).collect()),
);
}
fn offering(targets: Value) -> Value {
json!({
"content": [],
"_meta": { "io.modelcontextprotocol/files": { "downloads": targets } }
})
}
fn target(name: &str, url: &str, bytes: &[u8]) -> Value {
use sha2::Digest as _;
let digest = sha2::Sha256::digest(bytes);
json!({
"name": name,
"mimeType": "text/plain",
"size": bytes.len(),
"digest": { "algorithm": "sha-256", "value": base64url(&digest) },
"url": url,
"credentials": "omit",
})
}
fn base64url(bytes: &[u8]) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut text = String::new();
for chunk in bytes.chunks(3) {
let n = chunk
.iter()
.enumerate()
.fold(0_u32, |n, (i, byte)| n | u32::from(*byte) << (16 - 8 * i));
for i in 0..=chunk.len() {
text.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
}
}
text
}
fn download_options() -> McpFileDownloadOptions {
McpFileDownloadOptions::default()
}
#[tokio::test]
async fn offered_files_download_once_each_with_their_checks() {
let Fixture { host, client, .. } = fixture(false, false).await;
serve(
&host,
"https://files.example/a",
Vec::new(),
vec![b"quarterly", b" report"],
);
serve(&host, "https://files.example/b", Vec::new(), vec![b"hello"]);
let mut unnamed = target("", "https://files.example/b", b"hello");
unnamed.as_object_mut().unwrap().remove("name");
unnamed.as_object_mut().unwrap().remove("digest");
unnamed["_meta"] = json!({ "vendor": true });
let result = offering(json!([
target("../../etc/.profile", "https://files.example/a", REPORT),
unnamed
]));
let files = client
.download_files(&result, &download_options())
.await
.unwrap();
assert_eq!(files.len(), 2);
assert_eq!(files[0].name, "_profile");
assert_eq!(files[0].bytes, REPORT);
assert_eq!(files[0].mime_type, "text/plain");
assert_eq!(files[1].name, "download-2");
assert_eq!(files[1].bytes, b"hello");
let storage = host.storage();
assert_eq!(storage.len(), 2);
assert!(
storage
.iter()
.all(|sent| sent.method == "GET" && sent.body.is_empty())
);
assert!(
storage
.iter()
.all(|sent| header(&sent.headers, "authorization").is_none())
);
assert!(
host.tool_calls().is_empty(),
"downloading never repeats the call"
);
assert!(
client
.download_files(&json!({ "content": [] }), &download_options())
.await
.unwrap()
.is_empty()
);
}
#[tokio::test]
async fn a_body_beyond_its_size_aborts_before_reading_further() {
let Fixture { host, client, .. } = fixture(false, false).await;
serve(
&host,
"https://files.example/a",
Vec::new(),
vec![b"quarterly report!"],
);
let result = offering(json!([target("a.txt", "https://files.example/a", REPORT)]));
let error = client
.download_files(&result, &download_options())
.await
.unwrap_err();
assert_eq!(error.code(), "MCP_FILE_DOWNLOAD_FAILED", "{error}");
assert!(
!host.overread.load(Ordering::SeqCst),
"the transfer stopped at the excess"
);
}
#[tokio::test]
async fn short_or_altered_bytes_are_discarded() {
let Fixture { host, client, .. } = fixture(false, false).await;
serve(
&host,
"https://files.example/short",
Vec::new(),
vec![b"quarterly"],
);
serve(
&host,
"https://files.example/altered",
Vec::new(),
vec![b"QUARTERLY REPORT"],
);
for url in [
"https://files.example/short",
"https://files.example/altered",
] {
let result = offering(json!([target("a.txt", url, REPORT)]));
let error = client
.download_files(&result, &download_options())
.await
.unwrap_err();
assert_eq!(error.code(), "MCP_FILE_DOWNLOAD_FAILED", "{url}: {error}");
}
let wrong = format!("{}A", base64url(&[0; 31]));
let mut forged = target("a.txt", "https://files.example/altered", REPORT);
forged["digest"]["value"] = json!(wrong);
serve(
&host,
"https://files.example/altered",
Vec::new(),
vec![REPORT],
);
let error = client
.download_files(&offering(json!([forged])), &download_options())
.await
.unwrap_err();
assert!(error.to_string().contains("digest"), "{error}");
}
#[tokio::test]
async fn only_a_plain_200_is_accepted_and_never_retried() {
for (status, headers) in [
(302, Vec::new()),
(401, Vec::new()),
(206, Vec::new()),
(
200,
vec![("content-encoding".to_string(), "gzip".to_string())],
),
] {
let Fixture { host, client, .. } = fixture(false, false).await;
host.statuses.lock().unwrap().push_back(status);
serve(&host, "https://files.example/a", headers, vec![REPORT]);
let result = offering(json!([target("a.txt", "https://files.example/a", REPORT)]));
let error = client
.download_files(&result, &download_options())
.await
.unwrap_err();
assert_eq!(
error.code(),
"MCP_FILE_DOWNLOAD_FAILED",
"{status}: {error}"
);
assert_eq!(host.storage().len(), 1, "{status}: one request, no retry");
}
}
#[tokio::test]
async fn every_target_is_checked_before_any_is_fetched() {
let good = target("a.txt", "https://files.example/a", REPORT);
let mut expired = target("b.txt", "https://files.example/b", REPORT);
expired["expiresAt"] = json!("2000-01-01T00:00:00Z");
let mut undated = good.clone();
undated["expiresAt"] = json!("tomorrow");
let mut sha1 = good.clone();
sha1["digest"]["algorithm"] = json!("sha-1");
let mut stranger = good.clone();
stranger["extra"] = json!(1);
let mut private = good.clone();
private["url"] = json!("https://127.0.0.1/a");
let mut plain = good.clone();
plain["url"] = json!("http://files.example/a");
let mut include = good.clone();
include["credentials"] = json!("include");
let mut cookie = good.clone();
cookie["headers"] = json!({ "Cookie": "a=b" });
let mut huge = good.clone();
huge["size"] = json!(DEFAULT_MAX_DOWNLOAD_BYTES + 1);
for bad in [
expired, undated, sha1, stranger, private, plain, include, cookie, huge,
] {
let Fixture { host, client, .. } = fixture(false, false).await;
serve(&host, "https://files.example/a", Vec::new(), vec![REPORT]);
let result = offering(json!([good.clone(), bad.clone()]));
let error = client
.download_files(&result, &download_options())
.await
.unwrap_err();
assert_eq!(error.code(), "MCP_FILE_DOWNLOAD_FAILED", "{bad}: {error}");
assert!(host.storage().is_empty(), "{bad}: nothing fetched");
}
let Fixture { host, client, .. } = fixture(false, false).await;
let many = offering(json!([good.clone(), good.clone(), good.clone()]));
let limited = McpFileDownloadOptions {
max_files: 2,
..download_options()
};
assert!(client.download_files(&many, &limited).await.is_err());
let total = McpFileDownloadOptions {
max_total_bytes: 2 * REPORT.len() as u64,
..download_options()
};
assert!(client.download_files(&many, &total).await.is_err());
assert!(host.storage().is_empty());
}
#[tokio::test]
async fn downloads_are_declared_only_when_accepted() {
for accept in [false, true] {
let Fixture { host, client, .. } = fixture(true, false).await;
let options = McpFileUploadOptions {
accept_downloads: accept,
..Default::default()
};
client
.call_tool_with_files("ingest", arguments(b"hello"), &files(b"hello"), &options)
.await
.unwrap();
let calls = host.tool_calls();
let declared = &calls[0]["params"]["_meta"]["io.modelcontextprotocol/clientCapabilities"]["extensions"]
["io.modelcontextprotocol/files"];
let expected = if accept {
json!({ "upload": {}, "download": {} })
} else {
json!({ "upload": {} })
};
assert_eq!(declared, &expected);
}
}
#[test]
fn untrusted_names_reduce_to_one_safe_component() {
for (name, expected) in [
("report.pdf", "report.pdf"),
("../../etc/passwd", "passwd"),
("C:\\Windows\\evil.exe", "evil.exe"),
(".bashrc", "_bashrc"),
("..", "download"),
("dir/", "download"),
("a\u{0}b\nc", "abc"),
("stream:alt", "streamalt"),
("trailing. ", "trailing"),
] {
assert_eq!(safe_base_name(name), expected, "{name:?}");
}
assert_eq!(safe_base_name(&"é".repeat(200)).len(), 254);
}
#[test]
fn rfc3339_times_parse_to_epoch_seconds() {
for (text, expected) in [
("1970-01-01T00:00:00Z", Some(0)),
("2000-03-01T00:00:00+01:00", Some(951865200)),
("2024-02-29t12:00:00.5z", Some(1709208000)),
("1969-12-31T23:59:59Z", Some(-1)),
("2024-13-01T00:00:00Z", None),
("2024-01-01 00:00:00Z", None),
("2024-01-01T00:00:00", None),
("2024-01-01T00:00:00.Z", None),
] {
assert_eq!(rfc3339_seconds(text), expected, "{text}");
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn saved_files_never_overwrite_and_never_execute() {
let directory = std::env::temp_dir().join(format!(
"multicast-download-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(web_time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir(&directory).unwrap();
let file = McpDownloadedFile {
name: "a.sh".into(),
mime_type: "text/plain".into(),
bytes: REPORT.to_vec(),
};
let path = file.save_into(&directory).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), REPORT);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
}
let again = McpDownloadedFile {
bytes: b"other".to_vec(),
..file.clone()
};
assert_eq!(
again.save_into(&directory).unwrap_err().kind(),
std::io::ErrorKind::AlreadyExists
);
assert_eq!(std::fs::read(&path).unwrap(), REPORT);
std::fs::remove_dir_all(&directory).unwrap();
}