use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use futures::StreamExt;
use http::header::{ACCEPT, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
use multicast_mcp_protocol::{
McpClientMetadata, McpLifecycleFamily, McpNegotiationDecision, McpNegotiationError,
McpNegotiationEvidence, McpStandardSet, McpVersion, McpWireCodecKind,
};
use serde_json::{Map, Value};
use crate::mcp::{MAX_REMOTE_TOOL_PAGES, MAX_REMOTE_TOOLS, McpRemoteOptions};
use crate::outbound::{
HttpBody, HttpClientError, HttpRequest, HttpResponse, Redirects, SharedHttpClient,
};
const HEADER_SESSION_ID: &str = "mcp-session-id";
const HEADER_PROTOCOL_VERSION: &str = "mcp-protocol-version";
const HEADER_METHOD: &str = "mcp-method";
const HEADER_NAME: &str = "mcp-name";
const HEADER_PARAM_PREFIX: &str = "mcp-param-";
const EVENT_STREAM: &str = "text/event-stream";
const JSON: &str = "application/json";
const METHOD_NOT_FOUND: i64 = -32601;
const INVALID_PARAMS: i64 = -32602;
const TASKS_EXTENSION: &str = "io.modelcontextprotocol/tasks";
const DEFAULT_TASK_POLL: Duration = Duration::from_secs(2);
const MIN_TASK_POLL: Duration = Duration::from_millis(10);
const MAX_TASK_POLL: Duration = Duration::from_secs(60);
const TASK_LOST_AFTER: Duration = Duration::from_secs(5 * 60);
const MAX_EVENT_BYTES: usize = 16 * 1024 * 1024;
#[derive(Debug)]
#[non_exhaustive]
pub enum McpClientError {
InvalidHeader(String),
InvalidUrl(String),
Transport(HttpClientError),
Unauthorized {
status: u16,
www_authenticate: Option<String>,
},
SessionExpired,
Http {
status: u16,
body: String,
},
JsonRpc {
code: i64,
message: String,
data: Option<Value>,
},
Protocol(String),
Negotiation(McpNegotiationError),
Timeout {
after: Duration,
},
ToolLimit(String),
TaskFailed {
task_id: String,
error: Value,
},
TaskCancelled {
task_id: String,
},
TaskLost {
task_id: String,
},
TaskInputRequired {
task_id: String,
},
SkillIntegrity {
uri: String,
reason: String,
},
FileUpload {
file_id: String,
reason: String,
},
FileDownload {
name: String,
reason: String,
},
}
impl McpClientError {
pub fn code(&self) -> &'static str {
match self {
Self::InvalidHeader(_) => "INVALID_HEADER",
Self::InvalidUrl(_) => "MCP_INVALID_URL",
Self::Transport(HttpClientError::Transport { .. }) => "MCP_TRANSPORT_ERROR",
Self::Transport(error) => error.code(),
Self::Unauthorized { .. } => "MCP_UNAUTHORIZED",
Self::SessionExpired => "MCP_SESSION_EXPIRED",
Self::Http { .. } => "MCP_HTTP_ERROR",
Self::JsonRpc { .. } => "MCP_JSONRPC_ERROR",
Self::Protocol(_) => "MCP_PROTOCOL_ERROR",
Self::Negotiation(_) => "MCP_NEGOTIATION_FAILED",
Self::Timeout { .. } => "MCP_TIMEOUT",
Self::ToolLimit(_) => "MCP_TOOL_LIMIT_EXCEEDED",
Self::TaskFailed { .. } => "MCP_TASK_FAILED",
Self::TaskCancelled { .. } => "MCP_TASK_CANCELLED",
Self::TaskLost { .. } => "MCP_TASK_LOST",
Self::TaskInputRequired { .. } => "MCP_TASK_INPUT_REQUIRED",
Self::SkillIntegrity { .. } => "MCP_SKILL_INTEGRITY",
Self::FileUpload { .. } => "MCP_FILE_UPLOAD_FAILED",
Self::FileDownload { .. } => "MCP_FILE_DOWNLOAD_FAILED",
}
}
pub fn retryable(&self) -> bool {
match self {
Self::Transport(error) => error.retryable(),
Self::SessionExpired | Self::Timeout { .. } => true,
Self::Http { status, .. } => *status >= 500,
_ => false,
}
}
fn hint(&self) -> Option<String> {
match self {
Self::Unauthorized { .. } => {
Some("Check the bearer token or the configured Authorization header".to_string())
}
Self::Negotiation(_) => Some(
"Enable an MCP standard the server supports in McpRemoteOptions::standards"
.to_string(),
),
Self::Transport(error) => error.hint(),
Self::Timeout { .. } => Some(
"Retry, or raise McpRemoteOptions::request_timeout for a slow server".to_string(),
),
_ => None,
}
}
}
impl std::fmt::Display for McpClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidHeader(message) | Self::InvalidUrl(message) => f.write_str(message),
Self::Transport(error) => write!(f, "MCP request failed: {error}"),
Self::Unauthorized { status, .. } => {
write!(f, "MCP server rejected the credentials with HTTP {status}")
}
Self::SessionExpired => f.write_str("MCP server discarded the session"),
Self::Http { status, body } => write!(f, "HTTP {status}: {body}"),
Self::JsonRpc {
code,
message,
data,
} => {
write!(f, "Mcp error: {code}: {message}")?;
if let Some(data) = data {
write!(f, "({data})")?;
}
Ok(())
}
Self::Protocol(message) => write!(f, "MCP protocol error: {message}"),
Self::Negotiation(error) => write!(f, "{error}"),
Self::Timeout { after } => write!(
f,
"MCP server did not answer within {} ms",
after.as_millis()
),
Self::ToolLimit(message) => f.write_str(message),
Self::TaskFailed { task_id, error } => {
let message = error
.get("message")
.and_then(Value::as_str)
.unwrap_or("no message");
write!(f, "MCP task {task_id} failed: {message}")
}
Self::TaskCancelled { task_id } => write!(f, "MCP task {task_id} was cancelled"),
Self::TaskLost { task_id } => write!(
f,
"MCP server no longer recognizes task {task_id}; whether it ran is unknown"
),
Self::TaskInputRequired { task_id } => {
write!(f, "MCP task {task_id} requires input")
}
Self::SkillIntegrity { uri, reason } => {
write!(
f,
"MCP skill file {uri} does not match its manifest: {reason}"
)
}
Self::FileUpload { file_id, reason } => write!(
f,
"MCP file {file_id} could not be uploaded, so the tool did not run: {reason}"
),
Self::FileDownload { name, reason } => {
write!(f, "MCP file {name} could not be downloaded: {reason}")
}
}
}
}
impl std::error::Error for McpClientError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Transport(error) => Some(error),
Self::Negotiation(error) => Some(error),
_ => None,
}
}
}
impl From<McpClientError> for crate::errors::Error {
fn from(error: McpClientError) -> Self {
crate::errors::Error::Multicast(crate::errors::MulticastError {
message: error.to_string(),
code: error.code().to_string(),
hint: error.hint(),
retryable: error.retryable(),
exit_code: None,
cause: Some(Box::new(error)),
})
}
}
fn http_client(options: &McpRemoteOptions) -> Result<SharedHttpClient, McpClientError> {
crate::outbound::resolve(
options.http_client.as_ref(),
"McpRemoteOptions::http_client",
Redirects::Refuse,
)
.map_err(McpClientError::Transport)
}
pub(crate) fn header_pairs(headers: &HeaderMap) -> Vec<(String, String)> {
headers
.iter()
.map(|(name, value)| {
(
name.as_str().to_string(),
String::from_utf8_lossy(value.as_bytes()).into_owned(),
)
})
.collect()
}
async fn send(
http: &SharedHttpClient,
method: &str,
url: &url::Url,
headers: &HeaderMap,
body: Option<Vec<u8>>,
) -> Result<HttpResponse, McpClientError> {
let request = HttpRequest {
method: method.to_string(),
url: url.to_string(),
headers: header_pairs(headers),
body,
};
http.send(request).await.map_err(McpClientError::Transport)
}
async fn with_deadline<T>(
http: &SharedHttpClient,
timeout: Option<Duration>,
work: impl std::future::Future<Output = Result<T, McpClientError>>,
) -> Result<T, McpClientError> {
let Some((after, timer)) =
timeout.and_then(|after| http.sleep(after).map(|timer| (after, timer)))
else {
return work.await;
};
let work = std::pin::pin!(work);
match futures::future::select(work, timer).await {
futures::future::Either::Left((outcome, _)) => outcome,
futures::future::Either::Right(((), _)) => Err(McpClientError::Timeout { after }),
}
}
async fn error_body(response: HttpResponse, limit: usize) -> Result<String, McpClientError> {
match response.text_limited(limit).await {
Ok(body) => Ok(body),
Err(error @ HttpClientError::BodyTooLarge { .. }) => Err(McpClientError::Transport(error)),
Err(_) => Ok(String::new()),
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(crate) struct SseEvent {
pub(crate) event: Option<String>,
pub(crate) data: String,
}
#[derive(Debug)]
pub(crate) struct SseParser {
buffer: Vec<u8>,
event: Option<String>,
data: Vec<String>,
data_bytes: usize,
limit: usize,
}
impl Default for SseParser {
fn default() -> Self {
Self {
buffer: Vec::new(),
event: None,
data: Vec::new(),
data_bytes: 0,
limit: MAX_EVENT_BYTES,
}
}
}
impl SseParser {
pub(crate) fn push(&mut self, bytes: &[u8]) -> Result<(), McpClientError> {
if bytes.len()
> self
.limit
.saturating_sub(self.buffer.len().saturating_add(self.data_bytes))
{
return Err(McpClientError::Transport(HttpClientError::BodyTooLarge {
limit: self.limit,
}));
}
self.buffer.extend_from_slice(bytes);
Ok(())
}
pub(crate) fn next_event(&mut self) -> Option<SseEvent> {
loop {
let end = self
.buffer
.iter()
.position(|byte| *byte == b'\n' || *byte == b'\r')?;
let mut consumed = end + 1;
if self.buffer[end] == b'\r' {
match self.buffer.get(end + 1) {
Some(b'\n') => consumed += 1,
None => return None,
Some(_) => {}
}
}
let line = String::from_utf8_lossy(&self.buffer[..end]).into_owned();
self.buffer.drain(..consumed);
if line.is_empty() {
if self.data.is_empty() {
self.event = None;
continue;
}
let event = SseEvent {
event: self.event.take(),
data: self.data.join("\n"),
};
self.data.clear();
self.data_bytes = 0;
return Some(event);
}
if line.starts_with(':') {
continue;
}
let (field, value) = match line.split_once(':') {
Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)),
None => (line.as_str(), ""),
};
match field {
"event" => self.event = Some(value.to_string()),
"data" => {
self.data_bytes = self.data_bytes.saturating_add(value.len() + 1);
self.data.push(value.to_string());
}
_ => {}
}
}
}
}
struct EventReader {
stream: HttpBody,
parser: SseParser,
}
impl EventReader {
fn new(response: HttpResponse, limit: usize) -> Self {
Self {
stream: response.body,
parser: SseParser {
limit,
..SseParser::default()
},
}
}
async fn next(&mut self) -> Result<Option<SseEvent>, McpClientError> {
loop {
if let Some(event) = self.parser.next_event() {
return Ok(Some(event));
}
match self.stream.next().await {
Some(Ok(bytes)) => self.parser.push(&bytes)?,
Some(Err(error)) => return Err(McpClientError::Transport(error)),
None => return Ok(None),
}
}
}
async fn response(&mut self, id: u64) -> Result<Value, McpClientError> {
loop {
let Some(event) = self.next().await? else {
return Err(McpClientError::Protocol(
"event stream ended before the response arrived".to_string(),
));
};
if event.event.as_deref().is_some_and(|name| name != "message")
|| event.data.trim().is_empty()
{
continue;
}
let message: Value = serde_json::from_str(&event.data).map_err(|error| {
McpClientError::Protocol(format!("event data is not JSON: {error}"))
})?;
if let Some(outcome) = find_response(&message, id) {
return outcome;
}
}
}
}
fn id_matches(value: Option<&Value>, id: u64) -> bool {
match value {
Some(Value::Number(number)) => number.as_u64() == Some(id),
Some(Value::String(text)) => *text == id.to_string(),
_ => false,
}
}
fn jsonrpc_error(error: &Value) -> McpClientError {
McpClientError::JsonRpc {
code: error
.get("code")
.and_then(Value::as_i64)
.unwrap_or_default(),
message: error
.get("message")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
data: error.get("data").cloned(),
}
}
fn find_response(message: &Value, id: u64) -> Option<Result<Value, McpClientError>> {
if let Some(batch) = message.as_array() {
return batch.iter().find_map(|message| find_response(message, id));
}
if message.get("method").is_some() || !id_matches(message.get("id"), id) {
return None;
}
if let Some(error) = message.get("error") {
return Some(Err(jsonrpc_error(error)));
}
Some(match message.get("result") {
Some(result) => Ok(result.clone()),
None => Err(McpClientError::Protocol(
"response has neither result nor error".to_string(),
)),
})
}
struct Reply {
result: Option<Value>,
session_id: Option<String>,
}
#[derive(Debug, Clone, Copy)]
struct Limits {
timeout: Option<Duration>,
max_body: usize,
}
impl Limits {
fn new(options: &McpRemoteOptions) -> Self {
Self {
timeout: options.request_timeout,
max_body: options.max_response_bytes,
}
}
}
#[derive(Clone)]
struct Streamable {
http: SharedHttpClient,
url: url::Url,
headers: HeaderMap,
session_id: Option<HeaderValue>,
limits: Limits,
detach: Option<crate::mcp::McpDetach>,
}
impl Streamable {
async fn exchange(
&self,
message: &Value,
id: Option<u64>,
protocol_headers: HeaderMap,
) -> Result<Reply, McpClientError> {
with_deadline(
&self.http,
self.limits.timeout,
self.exchange_unbounded(message, id, protocol_headers),
)
.await
}
async fn exchange_unbounded(
&self,
message: &Value,
id: Option<u64>,
protocol_headers: HeaderMap,
) -> Result<Reply, McpClientError> {
let body = serde_json::to_vec(message)
.map_err(|error| McpClientError::Protocol(error.to_string()))?;
let mut headers = self.headers.clone();
headers.extend(protocol_headers);
headers.append(
ACCEPT,
HeaderValue::from_static("text/event-stream, application/json"),
);
headers.append(CONTENT_TYPE, HeaderValue::from_static(JSON));
if let Some(session_id) = &self.session_id {
headers.append(HEADER_SESSION_ID, session_id.clone());
}
let response = send(&self.http, "POST", &self.url, &headers, Some(body)).await?;
let status = response.status;
rejected_credentials(&response)?;
if matches!(status, 202 | 204) {
return accepted(id, None);
}
if status == 404 && self.session_id.is_some() {
return Err(McpClientError::SessionExpired);
}
let content_type = header_text(&response, CONTENT_TYPE.as_str());
let session_id = header_text(&response, HEADER_SESSION_ID);
let is_json = content_type
.as_deref()
.is_some_and(|value| value.starts_with(JSON));
if !response.is_success() {
let body = error_body(response, self.limits.max_body).await?;
if is_json
&& let Ok(message) = serde_json::from_str::<Value>(&body)
&& let Some(error) = message.get("error")
{
return Err(jsonrpc_error(error));
}
return Err(McpClientError::Http { status, body });
}
if content_type
.as_deref()
.is_some_and(|value| value.starts_with(EVENT_STREAM))
{
let Some(id) = id else {
return Ok(Reply {
result: None,
session_id,
});
};
let result = EventReader::new(response, self.limits.max_body)
.response(id)
.await?;
return Ok(Reply {
result: Some(result),
session_id,
});
}
if !is_json {
return Err(McpClientError::Protocol(format!(
"unexpected response content type {}",
content_type.as_deref().unwrap_or("<none>")
)));
}
let bytes = response
.bytes_limited(self.limits.max_body)
.await
.map_err(McpClientError::Transport)?;
let (Some(id), Ok(message)) = (id, serde_json::from_slice::<Value>(&bytes)) else {
return accepted(id, session_id);
};
match find_response(&message, id) {
Some(outcome) => outcome.map(|result| Reply {
result: Some(result),
session_id,
}),
None if message.get("id").is_none_or(Value::is_null) => Err(message
.get("error")
.map(jsonrpc_error)
.unwrap_or_else(|| McpClientError::Protocol("response has no id".to_string()))),
None => Err(McpClientError::Protocol(
"response id does not match the request".to_string(),
)),
}
}
}
fn accepted(id: Option<u64>, session_id: Option<String>) -> Result<Reply, McpClientError> {
if id.is_some() {
return Err(McpClientError::Protocol(
"server accepted a request without answering it".to_string(),
));
}
Ok(Reply {
result: None,
session_id,
})
}
fn rejected_credentials(response: &HttpResponse) -> Result<(), McpClientError> {
let status = response.status;
if matches!(status, 401 | 403) {
return Err(McpClientError::Unauthorized {
status,
www_authenticate: header_text(response, "www-authenticate"),
});
}
Ok(())
}
fn header_text(response: &HttpResponse, name: &str) -> Option<String> {
response.header(name).map(ToString::to_string)
}
struct LegacySse {
http: SharedHttpClient,
endpoint: url::Url,
headers: HeaderMap,
events: futures::lock::Mutex<EventReader>,
limits: Limits,
}
impl LegacySse {
async fn exchange(
&self,
message: &Value,
id: Option<u64>,
protocol_headers: HeaderMap,
) -> Result<Reply, McpClientError> {
with_deadline(&self.http, self.limits.timeout, async {
let mut events = self.events.lock().await;
self.exchange_held(&mut events, message, id, protocol_headers)
.await
})
.await
}
async fn exchange_held(
&self,
events: &mut EventReader,
message: &Value,
id: Option<u64>,
protocol_headers: HeaderMap,
) -> Result<Reply, McpClientError> {
let body = serde_json::to_vec(message)
.map_err(|error| McpClientError::Protocol(error.to_string()))?;
let mut headers = self.headers.clone();
headers.extend(protocol_headers);
headers.append(ACCEPT, HeaderValue::from_static(JSON));
headers.append(CONTENT_TYPE, HeaderValue::from_static(JSON));
let response = send(&self.http, "POST", &self.endpoint, &headers, Some(body)).await?;
rejected_credentials(&response)?;
if !response.is_success() {
let status = response.status;
return Err(McpClientError::Http {
status,
body: error_body(response, self.limits.max_body).await?,
});
}
drop(response);
let result = match id {
Some(id) => Some(events.response(id).await?),
None => None,
};
Ok(Reply {
result,
session_id: None,
})
}
}
enum Wire {
Streamable(Streamable),
LegacySse(LegacySse),
}
pub(crate) fn resolve_endpoint(
configured: &url::Url,
value: &str,
) -> Result<url::Url, McpClientError> {
let endpoint = configured
.join(value)
.map_err(|error| McpClientError::Protocol(format!("endpoint event is invalid: {error}")))?;
if !matches!(endpoint.scheme(), "http" | "https") {
return Err(McpClientError::Protocol(
"endpoint event must contain an HTTP or HTTPS URL".to_string(),
));
}
if !endpoint.username().is_empty()
|| endpoint.password().is_some()
|| endpoint.fragment().is_some()
{
return Err(McpClientError::Protocol(
"endpoint event URL must not contain user information or a fragment".to_string(),
));
}
if endpoint.scheme() == "http" && !is_loopback(&endpoint) {
return Err(McpClientError::Protocol(
"non-loopback endpoint event URLs must use HTTPS".to_string(),
));
}
Ok(endpoint)
}
fn is_loopback(url: &url::Url) -> bool {
let Some(host) = url.host_str() else {
return false;
};
let host = host.trim_start_matches('[').trim_end_matches(']');
host.eq_ignore_ascii_case("localhost")
|| host
.parse::<std::net::IpAddr>()
.is_ok_and(|address| address.is_loopback())
}
pub(crate) fn same_origin(configured: &url::Url, endpoint: &url::Url) -> bool {
configured.scheme() == endpoint.scheme()
&& configured.host_str() == endpoint.host_str()
&& configured.port_or_known_default() == endpoint.port_or_known_default()
}
pub(crate) fn client_safe_headers(mut headers: HeaderMap) -> HeaderMap {
headers.remove(ACCEPT);
headers.remove(CONTENT_TYPE);
headers
}
pub struct McpHttpClient {
open_telemetry: bool,
wire: Wire,
standard: McpVersion,
modern: bool,
metadata: McpClientMetadata,
next_id: AtomicU64,
param_headers: std::sync::Mutex<HashMap<String, Vec<(String, String)>>>,
tasks: bool,
skills: bool,
#[cfg_attr(not(feature = "mcp-files"), allow(dead_code))]
files: Option<Value>,
pending_tasks: std::sync::Mutex<std::collections::HashSet<String>>,
pub(crate) task_lost_after: Duration,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum McpToolOutcome {
Complete(Value),
InputRequired {
task_id: String,
input_requests: Value,
},
}
impl std::fmt::Debug for McpHttpClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("McpHttpClient")
.field("standard", &self.standard)
.field("session_id", &self.session_id())
.finish_non_exhaustive()
}
}
impl McpHttpClient {
pub async fn connect(url: &str, options: &McpRemoteOptions) -> Result<Self, McpClientError> {
let url = parse_url(url)?;
let headers = configured_headers(options)?;
for reserved in [
ACCEPT,
CONTENT_TYPE,
HeaderName::from_static(HEADER_SESSION_ID),
HeaderName::from_static(HEADER_PROTOCOL_VERSION),
] {
if headers.contains_key(&reserved) {
return Err(McpClientError::InvalidHeader(format!(
"`{reserved}` is set by the MCP transport and cannot be configured"
)));
}
}
let wire = Wire::Streamable(Streamable {
http: http_client(options)?,
url,
headers,
session_id: None,
limits: Limits::new(options),
detach: options.detach.clone(),
});
Self::negotiate(wire, &options.standards, options.open_telemetry).await
}
pub async fn connect_legacy_sse(
url: &str,
options: &McpRemoteOptions,
) -> Result<Self, McpClientError> {
let configured = parse_url(url)?;
let headers = client_safe_headers(configured_headers(options)?);
let http = http_client(options)?;
let limits = Limits::new(options);
let (endpoint, events) = with_deadline(
&http,
limits.timeout,
open_legacy_stream(&http, &configured, &headers, limits),
)
.await?;
let headers = if same_origin(&configured, &endpoint) {
headers
} else {
HeaderMap::new()
};
let wire = Wire::LegacySse(LegacySse {
http,
endpoint,
headers,
events: futures::lock::Mutex::new(events),
limits,
});
Self::negotiate(wire, &options.standards, options.open_telemetry).await
}
}
async fn open_legacy_stream(
http: &SharedHttpClient,
configured: &url::Url,
headers: &HeaderMap,
limits: Limits,
) -> Result<(url::Url, EventReader), McpClientError> {
let mut request_headers = headers.clone();
request_headers.append(ACCEPT, HeaderValue::from_static(EVENT_STREAM));
let response = send(http, "GET", configured, &request_headers, None).await?;
rejected_credentials(&response)?;
if !response.is_success() {
let status = response.status;
return Err(McpClientError::Http {
status,
body: error_body(response, limits.max_body).await?,
});
}
let content_type = header_text(&response, CONTENT_TYPE.as_str());
if !content_type
.as_deref()
.and_then(|value| value.split(';').next())
.is_some_and(|value| value.trim().eq_ignore_ascii_case(EVENT_STREAM))
{
return Err(McpClientError::Protocol(
"SSE endpoint did not return text/event-stream".to_string(),
));
}
let mut events = EventReader::new(response, limits.max_body);
let endpoint = loop {
let Some(event) = events.next().await? else {
return Err(McpClientError::Protocol(
"SSE endpoint closed before its endpoint event".to_string(),
));
};
if event.event.as_deref() == Some("endpoint") {
break resolve_endpoint(configured, event.data.trim())?;
}
};
Ok((endpoint, events))
}
impl McpHttpClient {
pub fn standard(&self) -> &McpVersion {
&self.standard
}
pub fn session_id(&self) -> Option<&str> {
match &self.wire {
Wire::Streamable(wire) => wire
.session_id
.as_ref()
.and_then(|value| value.to_str().ok()),
Wire::LegacySse(_) => None,
}
}
pub async fn request(&self, method: &str, params: Value) -> Result<Value, McpClientError> {
let result = self.request_any(method, params).await?;
if self.modern
&& let Some(kind) = result.get("resultType").and_then(Value::as_str)
&& kind != "complete"
{
return Err(McpClientError::Protocol(format!(
"result type `{kind}` is not supported by this client"
)));
}
Ok(result)
}
async fn request_any(&self, method: &str, params: Value) -> Result<Value, McpClientError> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let message = self.envelope(method, Some(params), Some(id));
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()))
}
pub async fn list_tools(&self) -> Result<Vec<Value>, McpClientError> {
let (http, limits) = self.http_limits();
with_deadline(http, limits.timeout, self.list_tools_unbounded()).await
}
pub(crate) fn deadline(&self) -> Option<(Duration, crate::outbound::Sleep)> {
let (http, limits) = self.http_limits();
limits
.timeout
.and_then(|after| http.sleep(after).map(|timer| (after, timer)))
}
fn http_limits(&self) -> (&SharedHttpClient, Limits) {
match &self.wire {
Wire::Streamable(wire) => (&wire.http, wire.limits),
Wire::LegacySse(wire) => (&wire.http, wire.limits),
}
}
async fn list_tools_unbounded(&self) -> Result<Vec<Value>, McpClientError> {
let mut tools = Vec::new();
let mut cursor: Option<String> = None;
let mut pages = 0_usize;
loop {
pages += 1;
let params = match &cursor {
Some(cursor) => serde_json::json!({ "cursor": cursor }),
None => Value::Object(Map::new()),
};
let result = self.request("tools/list", params).await?;
let page = result
.get("tools")
.and_then(Value::as_array)
.ok_or_else(|| {
McpClientError::Protocol("tools/list result has no tools array".to_string())
})?;
for tool in page {
if tools.len() >= MAX_REMOTE_TOOLS {
return Err(McpClientError::ToolLimit(format!(
"tools/list returned more than {MAX_REMOTE_TOOLS} tools"
)));
}
if self.modern {
let Some(annotations) = param_header_annotations(tool) else {
continue;
};
if let (Some(name), Ok(mut cache)) = (
tool.get("name").and_then(Value::as_str),
self.param_headers.lock(),
) {
cache.insert(name.to_string(), annotations);
}
}
tools.push(tool.clone());
}
match result.get("nextCursor").and_then(Value::as_str) {
Some(next) if cursor.as_deref() == Some(next) => {
return Err(McpClientError::Protocol(
"tools/list returned a non-advancing cursor".to_string(),
));
}
Some(_) if pages >= MAX_REMOTE_TOOL_PAGES => {
return Err(McpClientError::ToolLimit(format!(
"tools/list returned more than {MAX_REMOTE_TOOL_PAGES} pages"
)));
}
Some(next) => cursor = Some(next.to_string()),
None => return Ok(tools),
}
}
}
pub async fn call_tool(
&self,
name: &str,
arguments: Map<String, Value>,
) -> Result<Value, McpClientError> {
match self.call_tool_outcome(name, arguments).await? {
McpToolOutcome::Complete(result) => Ok(result),
McpToolOutcome::InputRequired { task_id, .. } => {
self.pending_tasks().remove(&task_id);
let _ = self
.request("tasks/cancel", serde_json::json!({ "taskId": task_id }))
.await;
Err(McpClientError::TaskInputRequired { task_id })
}
}
}
pub async fn call_tool_outcome(
&self,
name: &str,
arguments: Map<String, Value>,
) -> Result<McpToolOutcome, McpClientError> {
let result = self
.request_any(
"tools/call",
serde_json::json!({ "name": name, "arguments": arguments }),
)
.await?;
self.call_outcome(result).await
}
async fn call_outcome(&self, result: Value) -> Result<McpToolOutcome, McpClientError> {
if !self.modern {
return Ok(McpToolOutcome::Complete(result));
}
match result.get("resultType").and_then(Value::as_str) {
None | Some("complete") => Ok(McpToolOutcome::Complete(result)),
Some("task") if self.tasks => self.follow_task(result, false).await,
Some("task") => Err(McpClientError::Protocol(
"server returned a task although this client did not opt into tasks".to_string(),
)),
Some(kind) => Err(McpClientError::Protocol(format!(
"result type `{kind}` is not supported by this client"
))),
}
}
pub fn tasks_enabled(&self) -> bool {
self.tasks
}
pub async fn resume_task(
&self,
task_id: &str,
input_responses: Value,
) -> Result<McpToolOutcome, McpClientError> {
if !self.pending_tasks().contains(task_id) {
return Err(McpClientError::Protocol(format!(
"task {task_id} is not waiting for input from this client"
)));
}
self.request(
"tasks/update",
serde_json::json!({ "taskId": task_id, "inputResponses": input_responses }),
)
.await?;
self.pending_tasks().remove(task_id);
self.follow_task(
serde_json::json!({ "taskId": task_id, "status": "working" }),
true,
)
.await
}
fn pending_tasks(&self) -> std::sync::MutexGuard<'_, std::collections::HashSet<String>> {
self.pending_tasks
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
async fn follow_task(
&self,
mut task: Value,
immediate: bool,
) -> Result<McpToolOutcome, McpClientError> {
let task_id = task
.get("taskId")
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
.ok_or_else(|| McpClientError::Protocol("task result has no taskId".to_string()))?
.to_string();
let (http, _) = self.http_limits();
let mut guard = CancelOnDrop::new(self, &task_id);
let mut fetch_now = immediate || task_status(&task) != Some("working");
let mut unknown_for = Duration::ZERO;
loop {
let interval = poll_interval(&task);
if !fetch_now {
let timer = http.sleep(interval).ok_or_else(|| {
McpClientError::Protocol("following a task needs a host timer".to_string())
})?;
timer.await;
}
fetch_now = false;
match self
.request("tasks/get", serde_json::json!({ "taskId": task_id }))
.await
{
Ok(next) => {
unknown_for = Duration::ZERO;
task = next;
}
Err(McpClientError::JsonRpc {
code: INVALID_PARAMS,
..
}) => {
if unknown_for >= self.task_lost_after {
guard.disarm();
return Err(McpClientError::TaskLost { task_id });
}
unknown_for += interval;
continue;
}
Err(error) => {
guard.disarm();
return Err(error);
}
}
let outcome = match task_status(&task) {
Some("working") => continue,
Some("completed") => task
.get("result")
.cloned()
.map(McpToolOutcome::Complete)
.ok_or_else(|| {
McpClientError::Protocol("completed task has no result".to_string())
}),
Some("failed") => Err(McpClientError::TaskFailed {
task_id: task_id.clone(),
error: task.get("error").cloned().unwrap_or(Value::Null),
}),
Some("cancelled") => Err(McpClientError::TaskCancelled {
task_id: task_id.clone(),
}),
Some("input_required") => {
self.pending_tasks().insert(task_id.clone());
Ok(McpToolOutcome::InputRequired {
task_id: task_id.clone(),
input_requests: task
.get("inputRequests")
.cloned()
.unwrap_or_else(|| Value::Object(Map::new())),
})
}
other => Err(McpClientError::Protocol(format!(
"task status {other:?} is not recognized"
))),
};
guard.disarm();
return outcome;
}
}
async fn negotiate(
wire: Wire,
standards: &McpStandardSet,
open_telemetry: bool,
) -> Result<Self, McpClientError> {
let lifecycle = |version: &McpVersion| {
multicast_mcp_protocol::standards::known_standard(version)
.map(|standard| standard.lifecycle())
};
let versions = standards.versions();
let first_modern = versions
.iter()
.find(|version| lifecycle(version) == Some(McpLifecycleFamily::Modern))
.cloned();
let mut client = Self {
open_telemetry,
wire,
standard: versions[0].clone(),
modern: false,
metadata: McpClientMetadata::new(
"multicast",
env!("CARGO_PKG_VERSION"),
Value::Object(Map::new()),
),
next_id: AtomicU64::new(0),
param_headers: std::sync::Mutex::new(HashMap::new()),
tasks: false,
skills: false,
files: None,
pending_tasks: std::sync::Mutex::new(std::collections::HashSet::new()),
task_lost_after: TASK_LOST_AFTER,
};
let Some(mut candidate) = first_modern else {
let legacy = versions[0].clone();
client.initialize(legacy, standards).await?;
return Ok(client);
};
let mut attempted: Vec<McpVersion> = Vec::new();
loop {
attempted.push(candidate.clone());
client.standard = candidate.clone();
client.modern = true;
let outcome = client
.request("server/discover", Value::Object(Map::new()))
.await;
let (evidence, failure, discovery) = match outcome {
Ok(result) => (discovered(&result), None, Some(result)),
Err(error) => (evidence_for(&error), Some(error), None),
};
match multicast_mcp_protocol::negotiate(standards, &evidence) {
Ok(McpNegotiationDecision::SelectModern(version)) => {
client.standard = version;
let advertised = discovery
.as_ref()
.and_then(|result| result.pointer("/capabilities/extensions"))
.and_then(|extensions| extensions.get(TASKS_EXTENSION))
.is_some();
client.skills = discovery
.as_ref()
.and_then(|result| result.pointer("/capabilities/extensions"))
.and_then(|extensions| extensions.get(crate::mcp::SKILLS_EXTENSION))
.is_some();
client.files = discovery
.as_ref()
.and_then(|result| result.pointer("/capabilities/extensions"))
.and_then(|extensions| extensions.get("io.modelcontextprotocol/files"))
.cloned();
let (http, _) = client.http_limits();
if advertised && http.sleep(Duration::ZERO).is_some() {
client.tasks = true;
client.metadata.capabilities =
serde_json::json!({ "extensions": { (TASKS_EXTENSION): {} } });
}
return Ok(client);
}
Ok(McpNegotiationDecision::RetryModern(version)) => {
if attempted.iter().filter(|tried| **tried == version).count() >= 2 {
return Err(McpClientError::Negotiation(
McpNegotiationError::NoCommonStandard,
));
}
candidate = version;
}
Ok(McpNegotiationDecision::FallBackLegacy(version)) => {
client.modern = false;
client.initialize(version, standards).await?;
return Ok(client);
}
Err(McpNegotiationError::FailedClosed(reason)) => {
return Err(failure.unwrap_or_else(|| {
McpClientError::Protocol(format!("server/discover failed: {reason}"))
}));
}
Err(error) => return Err(McpClientError::Negotiation(error)),
}
}
}
async fn initialize(
&mut self,
version: McpVersion,
standards: &McpStandardSet,
) -> Result<(), McpClientError> {
self.modern = false;
self.standard = version.clone();
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let message = self.envelope(
"initialize",
Some(serde_json::json!({
"protocolVersion": version,
"capabilities": self.metadata.capabilities,
"clientInfo": {
"name": self.metadata.name,
"version": self.metadata.version,
},
})),
Some(id),
);
let headers = self.protocol_headers(&message, false);
let reply = self.exchange(&message, Some(id), headers).await?;
let result = reply.result.unwrap_or(Value::Null);
let negotiated = result
.get("protocolVersion")
.and_then(Value::as_str)
.map(McpVersion::from)
.ok_or_else(|| {
McpClientError::Protocol("initialize result has no protocolVersion".to_string())
})?;
let legacy = multicast_mcp_protocol::standards::known_standard(&negotiated)
.is_some_and(|standard| standard.lifecycle() == McpLifecycleFamily::Legacy);
if !legacy || !standards.versions().contains(&negotiated) {
return Err(McpClientError::Negotiation(
McpNegotiationError::NoCommonStandard,
));
}
self.standard = negotiated;
if let (Wire::Streamable(wire), Some(session_id)) = (&mut self.wire, reply.session_id) {
wire.session_id = Some(HeaderValue::from_str(&session_id).map_err(|_| {
McpClientError::Protocol("Mcp-Session-Id is not a valid header value".to_string())
})?);
}
let notification = self.envelope("notifications/initialized", None, None);
let headers = self.protocol_headers(¬ification, true);
self.exchange(¬ification, None, headers).await?;
Ok(())
}
async fn exchange(
&self,
message: &Value,
id: Option<u64>,
headers: HeaderMap,
) -> Result<Reply, McpClientError> {
use opentelemetry::trace::FutureExt;
let mut operation = crate::telemetry::Operation::mcp_client(
self.open_telemetry,
message["method"].as_str().unwrap_or("_OTHER"),
message.get("params"),
Some(self.standard.as_str()),
);
let mut message = message.clone();
let mut meta = message
.pointer("/params/_meta")
.cloned()
.unwrap_or(Value::Null);
operation.inject(&mut meta);
if !meta.is_null() {
if message.get("params").is_none() {
message["params"] = Value::Object(Map::new());
}
if message["params"].is_object() {
message["params"]["_meta"] = meta;
}
}
let result = async {
match &self.wire {
Wire::Streamable(wire) => wire.exchange(&message, id, headers).await,
Wire::LegacySse(wire) => wire.exchange(&message, id, headers).await,
}
}
.with_context(operation.context())
.await;
match &result {
Ok(reply) => match &reply.result {
Some(result) => operation.finish_result(result),
None => operation.finish(),
},
Err(McpClientError::JsonRpc { code, .. }) => operation.rpc_error(*code),
Err(
McpClientError::Http { status, .. } | McpClientError::Unauthorized { status, .. },
) => operation.fail(status.to_string()),
Err(error) => operation.fail(error.code()),
}
result
}
fn envelope(&self, method: &str, params: Option<Value>, id: Option<u64>) -> Value {
let mut message = Map::new();
message.insert("jsonrpc".to_string(), Value::from("2.0"));
if let Some(id) = id {
message.insert("id".to_string(), Value::from(id));
}
message.insert("method".to_string(), Value::from(method));
if let Some(params) = params {
message.insert("params".to_string(), params);
}
let message = Value::Object(message);
if self.modern && id.is_some() {
multicast_mcp_protocol::codec(McpWireCodecKind::Modern).project_outbound_request(
&self.standard,
&self.metadata,
message,
)
} else {
message
}
}
fn protocol_headers(&self, message: &Value, negotiated: bool) -> HeaderMap {
let mut headers = HeaderMap::new();
let mut push = |name: &str, value: &str| {
if let (Ok(name), Ok(value)) = (
HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(value),
) {
headers.insert(name, value);
}
};
if negotiated {
push(HEADER_PROTOCOL_VERSION, self.standard.as_str());
}
if !self.modern {
return headers;
}
let Some(method) = message.get("method").and_then(Value::as_str) else {
return headers;
};
push(HEADER_METHOD, method);
let params = message.get("params");
let name_key = match method {
"tools/call" | "prompts/get" => Some("name"),
"resources/read" | "resources/subscribe" | "resources/unsubscribe" => Some("uri"),
"skills/get" | "resources/directory/read" => Some("uri"),
"tasks/get" | "tasks/update" | "tasks/cancel" => Some("taskId"),
_ => None,
};
let name = name_key
.and_then(|key| params.and_then(|params| params.get(key)))
.and_then(Value::as_str);
if let Some(name) = name {
push(HEADER_NAME, &encode_header_value(name));
}
if method == "tools/call"
&& let (Some(name), Some(arguments)) =
(name, params.and_then(|params| params.get("arguments")))
&& let Ok(cache) = self.param_headers.lock()
&& let Some(annotations) = cache.get(name)
{
for (property, header) in annotations {
let value = match arguments.get(property) {
Some(Value::String(text)) => text.clone(),
Some(Value::Bool(flag)) => flag.to_string(),
Some(Value::Number(number)) => number.to_string(),
_ => continue,
};
push(
&format!("{HEADER_PARAM_PREFIX}{header}"),
&encode_header_value(&value),
);
}
}
headers
}
}
fn task_status(task: &Value) -> Option<&str> {
task.get("status").and_then(Value::as_str)
}
fn poll_interval(task: &Value) -> Duration {
task.get("pollIntervalMs")
.and_then(Value::as_u64)
.map_or(DEFAULT_TASK_POLL, Duration::from_millis)
.clamp(MIN_TASK_POLL, MAX_TASK_POLL)
}
struct CancelOnDrop {
pending: Option<(Streamable, Value, u64, HeaderMap)>,
}
impl CancelOnDrop {
fn new(client: &McpHttpClient, task_id: &str) -> Self {
let pending = match &client.wire {
Wire::Streamable(wire)
if wire.detach.is_some() || cfg!(not(target_arch = "wasm32")) =>
{
let id = client.next_id.fetch_add(1, Ordering::Relaxed);
let message = client.envelope(
"tasks/cancel",
Some(serde_json::json!({ "taskId": task_id })),
Some(id),
);
let headers = client.protocol_headers(&message, true);
Some((wire.clone(), message, id, headers))
}
_ => None,
};
Self { pending }
}
fn disarm(&mut self) {
self.pending = None;
}
}
impl Drop for CancelOnDrop {
fn drop(&mut self) {
let Some((wire, message, id, headers)) = self.pending.take() else {
return;
};
let detach = wire.detach.clone();
let send = Box::pin(async move {
let _ = wire.exchange(&message, Some(id), headers).await;
});
if let Some(detach) = detach {
detach(send);
} else {
#[cfg(not(target_arch = "wasm32"))]
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn(send);
}
}
}
}
fn parse_url(url: &str) -> Result<url::Url, McpClientError> {
let parsed = url::Url::parse(url).map_err(|error| {
McpClientError::InvalidUrl(format!("`{url}` is not a valid URL: {error}"))
})?;
if !matches!(parsed.scheme(), "http" | "https") {
return Err(McpClientError::InvalidUrl(format!(
"`{url}` is not an HTTP or HTTPS URL"
)));
}
Ok(parsed)
}
fn configured_headers(options: &McpRemoteOptions) -> Result<HeaderMap, McpClientError> {
let mut headers = HeaderMap::with_capacity(options.headers.len() + 1);
for (name, value) in &options.headers {
let header = HeaderName::try_from(name.as_str()).map_err(|_| {
McpClientError::InvalidHeader(format!("`{name}` is not a valid header name"))
})?;
let value = HeaderValue::from_str(value).map_err(|_| {
McpClientError::InvalidHeader(format!("the value for header `{name}` is not valid"))
})?;
headers.insert(header, value);
}
if let Some(token) = &options.auth_token {
let mut value = HeaderValue::from_str(&format!("Bearer {token}")).map_err(|_| {
McpClientError::InvalidHeader(
"the bearer token is not a valid header value".to_string(),
)
})?;
value.set_sensitive(true);
headers.insert(http::header::AUTHORIZATION, value);
}
Ok(headers)
}
fn discovered(result: &Value) -> McpNegotiationEvidence {
let supported = result
.get("supportedVersions")
.and_then(Value::as_array)
.map(|versions| {
versions
.iter()
.filter_map(Value::as_str)
.map(McpVersion::from)
.collect::<Vec<_>>()
});
match supported {
Some(supported) => McpNegotiationEvidence::Discovered { supported },
None => McpNegotiationEvidence::InvalidModernResponse,
}
}
fn evidence_for(error: &McpClientError) -> McpNegotiationEvidence {
match error {
McpClientError::JsonRpc { code, data, .. }
if *code
== i64::from(multicast_mcp_protocol::standards::UNSUPPORTED_PROTOCOL_VERSION) =>
{
McpNegotiationEvidence::UnsupportedVersion {
supported: data
.as_ref()
.and_then(|data| data.get("supported"))
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(McpVersion::from)
.collect(),
}
}
McpClientError::JsonRpc { code, .. } if *code == METHOD_NOT_FOUND => {
McpNegotiationEvidence::HttpBadRequestUnrecognized
}
McpClientError::Unauthorized { .. } => McpNegotiationEvidence::AuthenticationFailure,
McpClientError::Http { status, .. } if *status >= 500 => {
McpNegotiationEvidence::ServerFailure
}
McpClientError::Transport(_) | McpClientError::Timeout { .. } => {
McpNegotiationEvidence::TransportFailure
}
_ => McpNegotiationEvidence::InvalidModernResponse,
}
}
fn param_header_annotations(tool: &Value) -> Option<Vec<(String, String)>> {
let Some(properties) = tool
.pointer("/inputSchema/properties")
.and_then(Value::as_object)
else {
return Some(Vec::new());
};
let mut annotations = Vec::new();
let mut seen = std::collections::HashSet::new();
for (property, schema) in properties {
if has_nested_annotation(schema) {
return None;
}
let Some(header) = schema.get("x-mcp-header") else {
continue;
};
let header = header.as_str()?;
let token = !header.is_empty()
&& header
.chars()
.all(|c| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c));
let primitive = matches!(
schema.get("type").and_then(Value::as_str),
Some("string" | "integer" | "boolean")
);
if !token || !primitive || !seen.insert(header.to_ascii_lowercase()) {
return None;
}
annotations.push((property.clone(), header.to_string()));
}
Some(annotations)
}
fn has_nested_annotation(schema: &Value) -> bool {
schema
.get("properties")
.and_then(Value::as_object)
.is_some_and(|nested| {
nested
.values()
.any(|value| value.get("x-mcp-header").is_some() || has_nested_annotation(value))
})
}
fn encode_header_value(value: &str) -> String {
let needs_encoding = !value.is_empty()
&& (value.starts_with([' ', '\t'])
|| value.ends_with([' ', '\t'])
|| value.chars().any(|c| !(' '..='~').contains(&c))
|| (value.starts_with("=?base64?") && value.ends_with("?=")));
if needs_encoding {
format!("=?base64?{}?=", base64(value.as_bytes()))
} else {
value.to_string()
}
}
fn base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let triple = (u32::from(chunk[0]) << 16)
| (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
| u32::from(*chunk.get(2).unwrap_or(&0));
for index in 0..4 {
if index <= chunk.len() {
out.push(char::from(
ALPHABET[(triple >> (18 - 6 * index)) as usize & 63],
));
} else {
out.push('=');
}
}
}
out
}
mod skills;
#[cfg(not(target_arch = "wasm32"))]
pub use skills::McpSkillDirectoryCache;
pub use skills::{ApprovedSkill, MAX_REMOTE_SKILLS, McpSkillCache, RemoteSkill, RemoteSkillFile};
#[cfg(feature = "mcp-files")]
mod files;
#[cfg(feature = "mcp-files")]
pub use files::{
BoundaryEntropy, DEFAULT_MAX_DOWNLOAD_BYTES, DEFAULT_MAX_DOWNLOAD_TOTAL_BYTES,
DEFAULT_MAX_DOWNLOADS, DEFAULT_PUT_ATTEMPTS, McpDownloadedFile, McpFileDownloadOptions,
McpFileUploadOptions, safe_base_name,
};
#[cfg(test)]
pub(crate) mod tests;