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 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),
}
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",
}
}
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),
}
}
}
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,
}
}
}
struct Streamable {
http: SharedHttpClient,
url: url::Url,
headers: HeaderMap,
session_id: Option<HeaderValue>,
limits: Limits,
}
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)>>>,
}
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),
});
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 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?;
let result = reply
.result
.ok_or_else(|| McpClientError::Protocol("request received no response".to_string()))?;
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)
}
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> {
self.request(
"tools/call",
serde_json::json!({ "name": name, "arguments": arguments }),
)
.await
}
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()),
};
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) = match outcome {
Ok(result) => (discovered(&result), None),
Err(error) => (evidence_for(&error), Some(error)),
};
match multicast_mcp_protocol::negotiate(standards, &evidence) {
Ok(McpNegotiationDecision::SelectModern(version)) => {
client.standard = version;
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"),
"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 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
}
#[cfg(test)]
pub(crate) mod tests;