use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use http::header::{AUTHORIZATION, HeaderMap, HeaderName, HeaderValue};
use serde_json::{Map, Value, json};
use futures::StreamExt as _;
use super::{McpClientError, McpHttpClient, McpToolOutcome, Wire, send, with_deadline};
use crate::mcp::files::{
DownloadTarget, FILES_EXTENSION, FileDigest, FileInput, UploadForm, UploadTarget, encode_base64,
};
pub const DEFAULT_PUT_ATTEMPTS: u32 = 3;
const CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
pub type BoundaryEntropy = Arc<dyn Fn() -> [u8; 16] + Send + Sync>;
#[derive(Clone)]
pub struct McpFileUploadOptions {
pub allowed_hosts: Vec<String>,
pub put_attempts: u32,
pub transfer_timeout: Option<Duration>,
pub boundary_entropy: Option<BoundaryEntropy>,
pub accept_downloads: bool,
}
impl Default for McpFileUploadOptions {
fn default() -> Self {
Self {
allowed_hosts: Vec::new(),
put_attempts: DEFAULT_PUT_ATTEMPTS,
transfer_timeout: None,
boundary_entropy: None,
accept_downloads: false,
}
}
}
impl std::fmt::Debug for McpFileUploadOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("McpFileUploadOptions")
.field("allowed_hosts", &self.allowed_hosts)
.field("put_attempts", &self.put_attempts)
.field("transfer_timeout", &self.transfer_timeout)
.field("boundary_entropy", &self.boundary_entropy.is_some())
.field("accept_downloads", &self.accept_downloads)
.finish()
}
}
impl McpFileUploadOptions {
fn allows(&self, host: &str) -> bool {
self.allowed_hosts
.iter()
.any(|allowed| allowed.eq_ignore_ascii_case(host))
}
}
fn failure(file_id: &str, reason: impl Into<String>) -> McpClientError {
McpClientError::FileUpload {
file_id: file_id.to_string(),
reason: reason.into(),
}
}
struct Located<'a> {
id: String,
name: Option<String>,
mime_type: String,
bytes: &'a [u8],
}
impl McpHttpClient {
pub fn files_max_inline_bytes(&self) -> Option<u64> {
self.files
.as_ref()
.and_then(|settings| settings.get("maxInlineBytes"))
.and_then(Value::as_u64)
}
pub fn files_upload_enabled(&self) -> bool {
self.files
.as_ref()
.is_some_and(|settings| settings.get("upload").is_some_and(Value::is_object))
}
pub async fn call_tool_with_files(
&self,
name: &str,
mut arguments: Map<String, Value>,
files: &HashMap<String, Vec<u8>>,
options: &McpFileUploadOptions,
) -> Result<McpToolOutcome, McpClientError> {
let mut located = Vec::new();
locate(&mut arguments, files, &mut located)?;
for id in files.keys() {
if !located.iter().any(|file| &file.id == id) {
return Err(failure(id, "no argument holds a file with this id"));
}
}
let total: u64 = located.iter().map(|file| file.bytes.len() as u64).sum();
let advertised = self.modern && self.files.is_some();
let limit = if advertised {
self.files_max_inline_bytes().unwrap_or(0)
} else {
u64::MAX
};
if total <= limit {
for file in &located {
if !file.bytes.is_empty() {
set_data(&mut arguments, &file.id, encode_base64(file.bytes));
}
}
let result = self
.call_files(
json!({ "name": name, "arguments": arguments }),
advertised,
options.accept_downloads,
)
.await?;
return self.call_outcome(result).await;
}
if !self.files_upload_enabled() {
let id = located.first().map_or("", |file| file.id.as_str());
return Err(failure(
id,
format!(
"{total} bytes exceed the server's inline limit of {limit}, and the server accepts no uploads"
),
));
}
let first = self
.call_files(
json!({ "name": name, "arguments": arguments }),
true,
options.accept_downloads,
)
.await?;
if first.get("resultType").and_then(Value::as_str) != Some("upload_required") {
return self.call_outcome(first).await;
}
let request_state = match first.get("requestState") {
Some(Value::String(state)) => state.clone(),
_ => {
return Err(McpClientError::Protocol(
"upload_required result has no string requestState".into(),
));
}
};
let uploads = first
.get("uploads")
.and_then(Value::as_array)
.ok_or_else(|| {
McpClientError::Protocol("upload_required result has no uploads array".into())
})?;
let pending: Vec<&Located<'_>> = located
.iter()
.filter(|file| !file.bytes.is_empty())
.collect();
let mut planned = Vec::new();
for raw in uploads {
let target = parse_target(raw)?;
let Some(file) = pending.iter().find(|file| file.id == target.file_id) else {
return Err(McpClientError::Protocol(format!(
"upload_required lists file {} that the call did not send out of band",
target.file_id
)));
};
if planned
.iter()
.any(|(_, done): &(Planned, &Located<'_>)| done.id == file.id)
{
return Err(McpClientError::Protocol(format!(
"upload_required lists file {} more than once",
file.id
)));
}
planned.push((self.plan(&target, options)?, *file));
}
if let Some(missing) = pending
.iter()
.find(|file| !planned.iter().any(|(_, done)| done.id == file.id))
{
return Err(McpClientError::Protocol(format!(
"upload_required does not list file {}",
missing.id
)));
}
for (plan, file) in &planned {
self.transfer(plan, file, options).await?;
}
let retry = self
.call_files(
json!({ "name": name, "arguments": arguments, "requestState": request_state }),
true,
options.accept_downloads,
)
.await?;
if retry.get("resultType").and_then(Value::as_str) == Some("upload_required") {
return Err(McpClientError::Protocol(
"server requested a second upload in one call".into(),
));
}
self.call_outcome(retry).await
}
async fn call_files(
&self,
params: Value,
declare: bool,
download: bool,
) -> Result<Value, McpClientError> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let mut message = self.envelope("tools/call", Some(params), Some(id));
if declare {
declare_files(&mut message, download);
}
let headers = self.protocol_headers(&message, true);
let reply = self.exchange(&message, Some(id), headers).await?;
reply
.result
.ok_or_else(|| McpClientError::Protocol("request received no response".to_string()))
}
fn plan(
&self,
target: &UploadTarget,
options: &McpFileUploadOptions,
) -> Result<Planned, McpClientError> {
let id = target.file_id.as_str();
let Wire::Streamable(wire) = &self.wire else {
return Err(failure(id, "uploads need the Streamable HTTP transport"));
};
let reject = |reason: &str| failure(id, format!("target rejected: {reason}"));
let include = match target.credentials.as_str() {
"include" => true,
"omit" => false,
_ => return Err(reject("credentials must be omit or include")),
};
if let Some(expires_at) = &target.expires_at {
let expires = rfc3339_seconds(expires_at)
.ok_or_else(|| reject("expiresAt is not an RFC 3339 date-time"))?;
if now_seconds() > expires {
return Err(reject("target expired before the transfer started"));
}
}
let method = target.method.as_deref().unwrap_or("PUT");
if !matches!(method, "PUT" | "POST") {
return Err(reject("method must be PUT or POST"));
}
let url = match (&target.url, &target.path) {
(Some(url), None) => {
let url = url::Url::parse(url).map_err(|_| reject("url is not absolute"))?;
let host = url.host_str().unwrap_or_default().to_string();
let bare = host.trim_start_matches('[').trim_end_matches(']');
if !url.username().is_empty() || url.password().is_some() {
return Err(reject("url contains userinfo"));
}
match url.scheme() {
"https" => {}
"http" if options.allows(bare) => {}
_ => return Err(reject("url is not https")),
}
if !globally_reachable(bare) && !options.allows(bare) {
return Err(reject("url host is not globally reachable"));
}
if include && !super::same_origin(&wire.url, &url) {
return Err(reject("include credentials on a url of another origin"));
}
url
}
(None, Some(path)) => {
if !valid_path(path) {
return Err(reject("path is not a sequence of unreserved segments"));
}
let host = wire.url.host_str().unwrap_or_default();
let bare = host.trim_start_matches('[').trim_end_matches(']');
if wire.url.scheme() != "https"
&& !super::is_loopback(&wire.url)
&& !options.allows(bare)
{
return Err(reject(
"path target over http on a non-loopback MCP address",
));
}
resolve_path(&wire.url, path)
}
_ => return Err(reject("exactly one of url and path is required")),
};
let mut headers = HeaderMap::new();
for (name, value) in target.headers.iter().flatten() {
let lower = name.to_ascii_lowercase();
if lower == "authorization" || lower == "cookie" || forbidden_header(&lower) {
return Err(reject(&format!("header {name} is not allowed")));
}
if (target.path.is_some() || include) && routing_header(&lower) {
return Err(reject(&format!(
"header {name} is not allowed on this target"
)));
}
let (Ok(header), Ok(value)) = (
HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(value),
) else {
return Err(reject(&format!("header {name} is not valid")));
};
if value.as_bytes().contains(&0x7f) {
return Err(reject(&format!("header {name} is not valid")));
}
headers.append(header, value);
}
if let Some(form) = &target.form {
if method != "POST" {
return Err(reject("form requires POST"));
}
for name in [
"content-type",
"content-encoding",
"content-range",
"content-digest",
"repr-digest",
] {
if headers.contains_key(name) {
return Err(reject(&format!("form target sets {name}")));
}
}
check_form(form).map_err(|reason| reject(&reason))?;
}
if include && let Some(credential) = wire.headers.get(AUTHORIZATION) {
headers.insert(AUTHORIZATION, credential.clone());
}
Ok(Planned {
url,
method: method.to_string(),
headers,
form: target.form.clone(),
})
}
async fn transfer(
&self,
plan: &Planned,
file: &Located<'_>,
options: &McpFileUploadOptions,
) -> Result<(), McpClientError> {
let (http, limits) = self.http_limits();
let mut headers = plan.headers.clone();
let body = match &plan.form {
Some(form) => {
let boundary = boundary(options).ok_or_else(|| {
failure(
&file.id,
"no boundary entropy on this target; set McpFileUploadOptions::boundary_entropy",
)
})?;
let (content_type, body) = multipart(form, file, &boundary);
headers.insert(
http::header::CONTENT_TYPE,
HeaderValue::from_str(&content_type)
.map_err(|_| failure(&file.id, "invalid multipart content type"))?,
);
body
}
None => file.bytes.to_vec(),
};
let attempts = if plan.method == "PUT" {
options.put_attempts.max(1)
} else {
1
};
let timeout = options.transfer_timeout.or(limits.timeout);
let mut last = String::new();
for _ in 0..attempts {
let outcome = with_deadline(
http,
timeout,
send(http, &plan.method, &plan.url, &headers, Some(body.clone())),
)
.await;
match outcome {
Ok(response) if (200..300).contains(&response.status) => return Ok(()),
Ok(response) if matches!(response.status, 408 | 429 | 500..=599) => {
last = format!("storage answered HTTP {}", response.status);
}
Ok(response) => {
return Err(failure(
&file.id,
format!("storage answered HTTP {}", response.status),
));
}
Err(error) => last = error.to_string(),
}
}
Err(failure(&file.id, last))
}
}
pub const DEFAULT_MAX_DOWNLOADS: usize = 16;
pub const DEFAULT_MAX_DOWNLOAD_BYTES: u64 = 100 * 1024 * 1024;
pub const DEFAULT_MAX_DOWNLOAD_TOTAL_BYTES: u64 = 256 * 1024 * 1024;
#[derive(Debug, Clone)]
pub struct McpFileDownloadOptions {
pub allowed_hosts: Vec<String>,
pub max_files: usize,
pub max_file_bytes: u64,
pub max_total_bytes: u64,
pub transfer_timeout: Option<Duration>,
}
impl Default for McpFileDownloadOptions {
fn default() -> Self {
Self {
allowed_hosts: Vec::new(),
max_files: DEFAULT_MAX_DOWNLOADS,
max_file_bytes: DEFAULT_MAX_DOWNLOAD_BYTES,
max_total_bytes: DEFAULT_MAX_DOWNLOAD_TOTAL_BYTES,
transfer_timeout: None,
}
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct McpDownloadedFile {
pub name: String,
pub mime_type: String,
pub bytes: Vec<u8>,
}
impl std::fmt::Debug for McpDownloadedFile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("McpDownloadedFile")
.field("name", &self.name)
.field("mime_type", &self.mime_type)
.field("size", &self.bytes.len())
.finish()
}
}
impl McpDownloadedFile {
#[cfg(not(target_arch = "wasm32"))]
pub fn save_into(&self, directory: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
use std::io::Write as _;
let path = directory.join(&self.name);
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let mut file = options.open(&path)?;
if let Err(error) = file.write_all(&self.bytes).and_then(|()| file.sync_all()) {
drop(file);
let _ = std::fs::remove_file(&path);
return Err(error);
}
Ok(path)
}
}
fn download_failure(name: &str, reason: impl Into<String>) -> McpClientError {
McpClientError::FileDownload {
name: name.to_string(),
reason: reason.into(),
}
}
struct Fetch {
name: String,
mime_type: String,
size: u64,
digest: Option<String>,
plan: Planned,
}
impl McpHttpClient {
pub async fn download_files(
&self,
result: &Value,
options: &McpFileDownloadOptions,
) -> Result<Vec<McpDownloadedFile>, McpClientError> {
let Some(listed) = result
.get("_meta")
.and_then(|meta| meta.get(FILES_EXTENSION))
.and_then(|files| files.get("downloads"))
else {
return Ok(Vec::new());
};
let listed = listed
.as_array()
.ok_or_else(|| download_failure("", "downloads is not an array"))?;
if listed.len() > options.max_files {
return Err(download_failure(
"",
format!(
"the result offers {} files; the limit is {}",
listed.len(),
options.max_files
),
));
}
let upload_rules = McpFileUploadOptions {
allowed_hosts: options.allowed_hosts.clone(),
..McpFileUploadOptions::default()
};
let mut fetches = Vec::new();
let mut total = 0_u64;
for (index, raw) in listed.iter().enumerate() {
let fallback = format!("download-{}", index + 1);
let target = parse_download(raw, &fallback)?;
let name = target
.name
.as_deref()
.map(safe_base_name)
.unwrap_or(fallback);
if target.size > options.max_file_bytes {
return Err(download_failure(
&name,
format!(
"size {} exceeds the limit of {}",
target.size, options.max_file_bytes
),
));
}
total = total.saturating_add(target.size);
if total > options.max_total_bytes {
return Err(download_failure(
&name,
format!(
"the files exceed the total limit of {}",
options.max_total_bytes
),
));
}
let digest = match target.digest {
Some(digest) if digest.algorithm == "sha-256" => Some(digest.value),
Some(_) => {
return Err(download_failure(
&name,
"target rejected: digest algorithm must be sha-256",
));
}
None => None,
};
let shared = UploadTarget {
file_id: name.clone(),
url: target.url,
path: target.path,
headers: target.headers,
credentials: target.credentials,
expires_at: target.expires_at,
..UploadTarget::default()
};
let mut plan = self
.plan(&shared, &upload_rules)
.map_err(|error| as_download(&name, error))?;
plan.method = "GET".into();
fetches.push(Fetch {
name,
mime_type: target.mime_type,
size: target.size,
digest,
plan,
});
}
let mut files = Vec::with_capacity(fetches.len());
for fetch in fetches {
let bytes = self
.fetch(&fetch, options)
.await
.map_err(|error| as_download(&fetch.name, error))?;
if bytes.len() as u64 != fetch.size {
return Err(download_failure(
&fetch.name,
format!("received {} bytes, not {}", bytes.len(), fetch.size),
));
}
if let Some(expected) = &fetch.digest
&& FileDigest::sha256(&bytes).value != *expected
{
return Err(download_failure(&fetch.name, "digest does not match"));
}
files.push(McpDownloadedFile {
name: fetch.name,
mime_type: fetch.mime_type,
bytes,
});
}
Ok(files)
}
async fn fetch(
&self,
fetch: &Fetch,
options: &McpFileDownloadOptions,
) -> Result<Vec<u8>, McpClientError> {
let (http, limits) = self.http_limits();
let timeout = options.transfer_timeout.or(limits.timeout);
let name = fetch.name.as_str();
with_deadline(http, timeout, async {
let response = send(http, "GET", &fetch.plan.url, &fetch.plan.headers, None).await?;
if response.status != 200 {
return Err(download_failure(
name,
format!("storage answered HTTP {}", response.status),
));
}
if let Some(encoding) = response.header("content-encoding")
&& !encoding.trim().eq_ignore_ascii_case("identity")
{
return Err(download_failure(
name,
format!("content encoding {encoding} is not supported"),
));
}
let mut body = response.body;
let mut bytes = Vec::new();
while let Some(chunk) = body.next().await {
let chunk = chunk.map_err(McpClientError::Transport)?;
if (bytes.len() + chunk.len()) as u64 > fetch.size {
return Err(download_failure(
name,
format!("storage sent more than the declared {} bytes", fetch.size),
));
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
})
.await
}
}
fn as_download(name: &str, error: McpClientError) -> McpClientError {
match error {
McpClientError::FileDownload { .. } => error,
McpClientError::FileUpload { reason, .. } => download_failure(name, reason),
other => download_failure(name, other.to_string()),
}
}
fn parse_download(raw: &Value, fallback: &str) -> Result<DownloadTarget, McpClientError> {
let name = raw.get("name").and_then(Value::as_str).unwrap_or(fallback);
let reject = |reason: String| download_failure(name, format!("target rejected: {reason}"));
let object = raw
.as_object()
.ok_or_else(|| reject("not an object".into()))?;
let mut cleaned = Map::new();
for (key, value) in object {
if value.is_null() {
continue;
}
match key.as_str() {
"name" | "mimeType" | "size" | "url" | "path" | "credentials" | "expiresAt" => {}
"_meta" => continue,
"digest" => {
let valid = value.as_object().is_some_and(|digest| {
digest.iter().all(|(key, value)| {
value.is_null() || matches!(key.as_str(), "algorithm" | "value")
})
});
if !valid {
return Err(reject("digest must hold only algorithm and value".into()));
}
}
"headers" => {
let valid = value
.as_object()
.is_some_and(|headers| headers.values().all(Value::is_string));
if !valid {
return Err(reject("headers must map names to strings".into()));
}
}
other => return Err(reject(format!("unknown member {other}"))),
}
cleaned.insert(key.clone(), value.clone());
}
serde_json::from_value(Value::Object(cleaned)).map_err(|error| reject(error.to_string()))
}
pub fn safe_base_name(name: &str) -> String {
let base = name.rsplit(['/', '\\']).next().unwrap_or_default();
let mut cleaned: String = base
.chars()
.filter(|character| !character.is_control() && *character != ':')
.collect();
let trimmed = cleaned.trim().trim_end_matches('.').to_string();
cleaned = trimmed;
if cleaned.starts_with('.') {
cleaned.replace_range(..1, "_");
}
while cleaned.len() > 255 {
cleaned.pop();
}
if cleaned.is_empty() {
"download".into()
} else {
cleaned
}
}
fn now_seconds() -> i64 {
web_time::SystemTime::now()
.duration_since(web_time::UNIX_EPOCH)
.map_or(0, |elapsed| {
i64::try_from(elapsed.as_secs()).unwrap_or(i64::MAX)
})
}
fn rfc3339_seconds(text: &str) -> Option<i64> {
let bytes = text.as_bytes();
let number = |range: std::ops::Range<usize>| -> Option<i64> {
let part = text.get(range)?;
if part.is_empty() || !part.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
part.parse().ok()
};
if bytes.len() < 20
|| bytes[4] != b'-'
|| bytes[7] != b'-'
|| !matches!(bytes[10], b'T' | b't')
|| bytes[13] != b':'
|| bytes[16] != b':'
{
return None;
}
let (year, month, day) = (number(0..4)?, number(5..7)?, number(8..10)?);
let (hour, minute, second) = (number(11..13)?, number(14..16)?, number(17..19)?);
if !(1..=12).contains(&month)
|| !(1..=31).contains(&day)
|| hour > 23
|| minute > 59
|| second > 60
{
return None;
}
let mut rest = &text[19..];
if let Some(fraction) = rest.strip_prefix('.') {
let digits = fraction.bytes().take_while(u8::is_ascii_digit).count();
if digits == 0 {
return None;
}
rest = &fraction[digits..];
}
let offset = match rest.as_bytes() {
[b'Z' | b'z'] => 0,
[sign @ (b'+' | b'-'), _, _, b':', _, _] => {
let hours: i64 = rest.get(1..3)?.parse().ok()?;
let minutes: i64 = rest.get(4..6)?.parse().ok()?;
if hours > 23 || minutes > 59 {
return None;
}
let offset = hours * 3600 + minutes * 60;
if *sign == b'+' { offset } else { -offset }
}
_ => return None,
};
let shifted = if month <= 2 { year - 1 } else { year };
let era = shifted.div_euclid(400);
let year_of_era = shifted - era * 400;
let month_index = (month + 9) % 12;
let day_of_year = (153 * month_index + 2) / 5 + day - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
let days = era * 146_097 + day_of_era - 719_468;
Some(days * 86_400 + hour * 3600 + minute * 60 + second - offset)
}
struct Planned {
url: url::Url,
method: String,
headers: HeaderMap,
form: Option<UploadForm>,
}
fn locate<'a>(
value: &mut Map<String, Value>,
files: &'a HashMap<String, Vec<u8>>,
found: &mut Vec<Located<'a>>,
) -> Result<(), McpClientError> {
for child in value.values_mut() {
visit(child, files, found)?;
}
Ok(())
}
fn visit<'a>(
value: &mut Value,
files: &'a HashMap<String, Vec<u8>>,
found: &mut Vec<Located<'a>>,
) -> Result<(), McpClientError> {
match value {
Value::Object(object) => {
let id = object.get("id").and_then(Value::as_str).map(str::to_string);
if let (Some(id), true) = (id, object.contains_key("mimeType"))
&& let Some(bytes) = files.get(&id)
{
if found.iter().any(|file| file.id == id) {
return Err(failure(&id, "more than one argument holds this file id"));
}
let file = FileInput::from_value(&Value::Object(object.clone()))
.map_err(|reason| failure(&id, reason))?;
if file.size != bytes.len() as u64 {
return Err(failure(
&id,
format!("size {} does not match {} bytes", file.size, bytes.len()),
));
}
object.remove("data");
found.push(Located {
id,
name: file.name,
mime_type: file.mime_type,
bytes,
});
return Ok(());
}
locate(object, files, found)
}
Value::Array(items) => {
for item in items {
visit(item, files, found)?;
}
Ok(())
}
_ => Ok(()),
}
}
fn set_data(value: &mut Map<String, Value>, id: &str, data: String) -> bool {
fn walk(value: &mut Value, id: &str, data: &str) -> bool {
match value {
Value::Object(object) => {
if object.get("id").and_then(Value::as_str) == Some(id)
&& object.contains_key("mimeType")
{
object.insert("data".into(), Value::String(data.to_string()));
return true;
}
object.values_mut().any(|child| walk(child, id, data))
}
Value::Array(items) => items.iter_mut().any(|item| walk(item, id, data)),
_ => false,
}
}
value.values_mut().any(|child| walk(child, id, &data))
}
fn declare_files(message: &mut Value, download: bool) {
let Some(params) = message.get_mut("params").and_then(Value::as_object_mut) else {
return;
};
let meta = params
.entry("_meta")
.or_insert_with(|| Value::Object(Map::new()));
let Some(meta) = meta.as_object_mut() else {
return;
};
let capabilities = meta
.entry(CLIENT_CAPABILITIES)
.or_insert_with(|| Value::Object(Map::new()));
if !capabilities.is_object() {
*capabilities = Value::Object(Map::new());
}
let Some(capabilities) = capabilities.as_object_mut() else {
return;
};
let extensions = capabilities
.entry("extensions")
.or_insert_with(|| Value::Object(Map::new()));
if !extensions.is_object() {
*extensions = Value::Object(Map::new());
}
if let Some(extensions) = extensions.as_object_mut() {
let settings = if download {
json!({ "upload": {}, "download": {} })
} else {
json!({ "upload": {} })
};
extensions.insert(FILES_EXTENSION.into(), settings);
}
}
fn parse_target(raw: &Value) -> Result<UploadTarget, McpClientError> {
let id = raw
.get("fileId")
.and_then(Value::as_str)
.unwrap_or_default();
let reject = |reason: String| failure(id, format!("target rejected: {reason}"));
let object = raw
.as_object()
.ok_or_else(|| reject("not an object".into()))?;
let mut cleaned = Map::new();
for (key, value) in object {
if value.is_null() {
continue;
}
match key.as_str() {
"fileId" | "url" | "path" | "method" | "credentials" | "expiresAt" | "_meta" => {}
"headers" => {
let valid = value
.as_object()
.is_some_and(|headers| headers.values().all(Value::is_string));
if !valid {
return Err(reject("headers must map names to strings".into()));
}
}
"form" => check_form_shape(value).map_err(reject)?,
other => return Err(reject(format!("unknown member {other}"))),
}
cleaned.insert(key.clone(), value.clone());
}
serde_json::from_value(Value::Object(cleaned)).map_err(|error| reject(error.to_string()))
}
fn check_form_shape(form: &Value) -> Result<(), String> {
let object = form.as_object().ok_or("form is not an object")?;
for (key, value) in object {
match key.as_str() {
"fileField" => {}
"fields" => {
for field in value.as_array().ok_or("form fields is not an array")? {
let field = field.as_object().ok_or("form field is not an object")?;
if let Some(extra) = field.iter().find(|(key, value)| {
!value.is_null() && !matches!(key.as_str(), "name" | "value")
}) {
return Err(format!("unknown form field member {}", extra.0));
}
}
}
_ if value.is_null() => {}
other => return Err(format!("unknown form member {other}")),
}
}
Ok(())
}
fn check_form(form: &UploadForm) -> Result<(), String> {
let bad_name = |name: &str| {
name.is_empty()
|| name
.chars()
.any(|c| c.is_control() || c == '"' || c == '\\')
};
if bad_name(&form.file_field) {
return Err("fileField is empty or contains a forbidden character".into());
}
for field in &form.fields {
if bad_name(&field.name) {
return Err(format!("form field name {:?} is not allowed", field.name));
}
if field.name == form.file_field {
return Err("a form field name equals fileField".into());
}
if field.value.contains(['\r', '\n', '\0']) {
return Err(format!("form field {} has a CR, LF, or NUL", field.name));
}
}
Ok(())
}
fn valid_path(path: &str) -> bool {
let Some(rest) = path.strip_prefix('/') else {
return false;
};
rest.split('/').all(|segment| {
!segment.is_empty()
&& segment != "."
&& segment != ".."
&& segment.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'~' | b'.')
})
})
}
fn resolve_path(mcp: &url::Url, path: &str) -> url::Url {
let mut url = mcp.clone();
let joined = format!("{}{}", mcp.path().trim_end_matches('/'), path);
url.set_path(&joined);
url.set_fragment(None);
url
}
fn forbidden_header(name: &str) -> bool {
matches!(
name,
"accept-charset"
| "accept-encoding"
| "access-control-request-headers"
| "access-control-request-method"
| "connection"
| "content-length"
| "cookie2"
| "date"
| "dnt"
| "expect"
| "host"
| "keep-alive"
| "origin"
| "referer"
| "set-cookie"
| "te"
| "trailer"
| "transfer-encoding"
| "upgrade"
| "via"
| "x-http-method"
| "x-http-method-override"
| "x-method-override"
) || name.starts_with("proxy-")
|| name.starts_with("sec-")
}
fn routing_header(name: &str) -> bool {
matches!(
name,
"forwarded"
| "x-original-url"
| "x-rewrite-url"
| "x-http-method-override"
| "x-http-method"
| "x-method-override"
) || name.starts_with("x-forwarded-")
}
fn globally_reachable(host: &str) -> bool {
let lower = host.to_ascii_lowercase();
if lower == "localhost" || lower.ends_with(".localhost") {
return false;
}
match lower.parse::<IpAddr>() {
Ok(IpAddr::V4(address)) => global_v4(address),
Ok(IpAddr::V6(address)) => global_v6(address),
Err(_) => true,
}
}
fn global_v4(address: Ipv4Addr) -> bool {
let [a, b, c, _] = address.octets();
!(a == 0
|| a == 10
|| a == 127
|| (a == 100 && (64..128).contains(&b))
|| (a == 169 && b == 254)
|| (a == 172 && (16..32).contains(&b))
|| (a == 192 && b == 0 && c == 0)
|| (a == 192 && b == 0 && c == 2)
|| (a == 192 && b == 168)
|| (a == 198 && (b == 18 || b == 19))
|| (a == 198 && b == 51 && c == 100)
|| (a == 203 && b == 0 && c == 113)
|| a >= 224)
}
fn global_v6(address: Ipv6Addr) -> bool {
if let Some(v4) = address.to_ipv4_mapped() {
return global_v4(v4);
}
let segments = address.segments();
!(address.is_unspecified()
|| address.is_loopback()
|| (segments[0] & 0xfe00) == 0xfc00
|| (segments[0] & 0xffc0) == 0xfe80
|| (segments[0] & 0xff00) == 0xff00
|| (segments[0] == 0x2001 && segments[1] == 0x0db8)
|| (segments[0] == 0x2001 && segments[1] < 0x0200)
|| (segments[0] == 0x0064 && segments[1] == 0xff9b)
|| (segments[0] == 0x0100 && segments[1..4] == [0, 0, 0])
|| segments[..6] == [0, 0, 0, 0, 0, 0])
}
fn boundary(options: &McpFileUploadOptions) -> Option<String> {
let bytes = match &options.boundary_entropy {
Some(entropy) => entropy(),
None => native_entropy()?,
};
let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
Some(format!("multicast-{hex}"))
}
#[cfg(not(target_arch = "wasm32"))]
fn native_entropy() -> Option<[u8; 16]> {
use std::hash::{BuildHasher, Hasher};
let mut bytes = [0_u8; 16];
for chunk in bytes.chunks_mut(8) {
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_u64(0);
chunk.copy_from_slice(&hasher.finish().to_le_bytes());
}
Some(bytes)
}
#[cfg(target_arch = "wasm32")]
fn native_entropy() -> Option<[u8; 16]> {
None
}
fn valid_media_type(value: &str) -> bool {
let token = |part: &str| {
!part.is_empty()
&& part
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
};
let mut pieces = value.splitn(2, ';');
let essence = pieces.next().unwrap_or_default().trim();
let Some((kind, subtype)) = essence.split_once('/') else {
return false;
};
let parameters_valid = pieces
.next()
.is_none_or(|rest| !rest.chars().any(|c| c.is_control()));
token(kind) && token(subtype) && parameters_valid
}
fn form_filename(name: Option<&str>) -> String {
let base = name
.and_then(|name| name.rsplit(['/', '\\']).next())
.unwrap_or_default();
let base = if base.is_empty() || base == "." || base == ".." {
"file"
} else {
base
};
base.replace('"', "%22")
.replace('\r', "%0D")
.replace('\n', "%0A")
}
fn multipart(form: &UploadForm, file: &Located<'_>, boundary: &str) -> (String, Vec<u8>) {
let mut body = Vec::new();
for field in &form.fields {
body.extend_from_slice(
format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}\r\n",
field.name, field.value
)
.as_bytes(),
);
}
let mime = if valid_media_type(&file.mime_type) {
file.mime_type.as_str()
} else {
"application/octet-stream"
};
body.extend_from_slice(
format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\nContent-Type: {mime}\r\n\r\n",
form.file_field,
form_filename(file.name.as_deref())
)
.as_bytes(),
);
body.extend_from_slice(file.bytes);
body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
(format!("multipart/form-data; boundary={boundary}"), body)
}
#[cfg(test)]
mod tests;