use super::*;
#[test]
fn sse_parser_joins_data_lines_across_chunks_and_line_endings() {
let mut parser = SseParser::default();
parser.push(b": comment\r\nevent: mess").unwrap();
assert_eq!(parser.next_event(), None);
parser
.push(b"age\r\ndata: {\"a\":\r\ndata:1}\r\n\r\ndata: second\n\n")
.unwrap();
assert_eq!(
parser.next_event(),
Some(SseEvent {
event: Some("message".to_string()),
data: "{\"a\":\n1}".to_string(),
})
);
assert_eq!(
parser.next_event(),
Some(SseEvent {
event: None,
data: "second".to_string(),
})
);
assert_eq!(parser.next_event(), None);
}
#[test]
fn sse_parser_waits_for_the_byte_after_a_trailing_carriage_return() {
let mut parser = SseParser::default();
parser.push(b"data: x\r").unwrap();
assert_eq!(parser.next_event(), None);
parser.push(b"\n\r\n").unwrap();
assert_eq!(
parser.next_event().map(|event| event.data),
Some("x".into())
);
}
#[test]
fn accumulated_sse_data_lines_share_the_buffer_limit() {
let mut parser = SseParser {
limit: 40,
..SseParser::default()
};
for _ in 0..3 {
parser.push(b"data: abcdefgh\n").unwrap();
assert!(parser.next_event().is_none());
}
let error = parser.push(b"data: abcdefgh\n").unwrap_err();
assert_eq!(error.code(), "HTTP_BODY_TOO_LARGE");
let mut parser = SseParser {
limit: 32,
..SseParser::default()
};
for _ in 0..4 {
parser.push(b"data: ok\n\n").unwrap();
assert_eq!(parser.next_event().unwrap().data, "ok");
}
}
#[test]
fn header_values_outside_visible_ascii_are_base64_wrapped() {
assert_eq!(encode_header_value("echo_tool"), "echo_tool");
assert_eq!(encode_header_value(" padded"), "=?base64?IHBhZGRlZA==?=");
assert_eq!(encode_header_value("é"), "=?base64?w6k=?=");
assert_eq!(base64(b"Man"), "TWFu");
assert_eq!(base64(b"Ma"), "TWE=");
}
#[test]
fn responses_are_matched_by_id_in_batches_and_stringified_ids() {
let batch = serde_json::json!([
{ "jsonrpc": "2.0", "method": "notifications/message", "params": {} },
{ "jsonrpc": "2.0", "id": 6, "result": { "other": true } },
{ "jsonrpc": "2.0", "id": "7", "result": { "mine": true } }
]);
assert_eq!(
find_response(&batch, 7).unwrap().unwrap(),
serde_json::json!({ "mine": true })
);
let error = serde_json::json!({
"jsonrpc": "2.0",
"id": 7,
"error": { "code": -32602, "message": "bad", "data": { "field": "x" } }
});
assert_eq!(
find_response(&error, 7).unwrap().unwrap_err().to_string(),
"Mcp error: -32602: bad({\"field\":\"x\"})"
);
assert!(find_response(&error, 8).is_none());
}
#[test]
fn unsafe_param_header_annotations_drop_the_tool() {
let tool = |annotation: Value| {
serde_json::json!({
"name": "t",
"inputSchema": { "type": "object", "properties": { "p": annotation } }
})
};
assert_eq!(
param_header_annotations(&tool(
serde_json::json!({ "type": "string", "x-mcp-header": "Region" })
)),
Some(vec![("p".to_string(), "Region".to_string())])
);
assert_eq!(
param_header_annotations(&tool(
serde_json::json!({ "type": "object", "x-mcp-header": "Region" })
)),
None
);
assert_eq!(
param_header_annotations(&tool(
serde_json::json!({ "type": "string", "x-mcp-header": "" })
)),
None
);
}
#[cfg(feature = "http")]
pub(crate) async fn run_command(def: &crate::command::CommandDef, options: Value) -> Value {
let ctx = crate::command::CommandContext {
agent: true,
args: Value::Object(Map::new()),
env: Value::Object(Map::new()),
display_name: def.name.clone(),
globals: Value::Object(Map::new()),
options,
mcp: None,
request: None,
format: crate::output::Format::Json,
format_explicit: false,
name: def.name.clone(),
vars: Value::Object(Map::new()),
version: None,
};
match def.handler.run(ctx).await {
crate::output::CommandResult::Ok {
data,
cta,
exit_code,
} => serde_json::json!({
"ok": data,
"cta": serde_json::to_value(cta).unwrap(),
"exit_code": exit_code,
}),
crate::output::CommandResult::Error {
code,
message,
retryable,
exit_code,
cta,
} => serde_json::json!({
"error": code,
"message": message,
"retryable": retryable,
"exit_code": exit_code,
"cta": serde_json::to_value(cta).unwrap(),
}),
_ => panic!("a remote command returned a stream"),
}
}
#[cfg(feature = "http")]
pub(crate) fn describe(
commands: &std::collections::BTreeMap<String, crate::command::CommandDef>,
) -> Value {
Value::Object(
commands
.iter()
.map(|(key, def)| {
(
key.clone(),
serde_json::json!({
"name": def.name,
"description": def.description,
"output_schema": def.output_schema,
"args_fields": def.args_fields.iter().map(|field| format!("{field:?}")).collect::<Vec<_>>(),
"options_fields": def.options_fields.iter().map(|field| format!("{field:?}")).collect::<Vec<_>>(),
"env_fields": def.env_fields.len(),
"raw": def.raw,
"hidden": def.hidden,
}),
)
})
.collect(),
)
}
#[cfg(feature = "http")]
async fn within<T>(future: impl std::future::Future<Output = T>) -> T {
tokio::time::timeout(std::time::Duration::from_secs(30), future)
.await
.expect("MCP exchange timed out")
}
#[cfg(feature = "http")]
mod live {
use std::sync::{Arc, RwLock};
use serde_json::json;
use super::*;
use crate::command::{CommandDef, McpAnnotations, McpCommandOptions, McpResultContent};
use crate::mcp::{McpDiscovery, McpServeOptions, McpToolFilter};
use crate::output::{CommandResult, CtaBlock, CtaEntry};
use crate::schema::{FieldMeta, FieldType, to_kebab};
const STANDARDS: [&str; 5] = [
"2024-11-05",
"2025-03-26",
"2025-06-18",
"2025-11-25",
"2026-07-28",
];
fn field(name: &'static str, field_type: FieldType, required: bool) -> FieldMeta {
FieldMeta {
name,
cli_name: to_kebab(name),
description: Some("A parity field"),
field_type,
required,
default: None,
alias: None,
deprecated: false,
env_name: None,
}
}
fn cta() -> CtaBlock {
CtaBlock {
commands: vec![CtaEntry::Simple("parity fail".to_string())],
description: None,
}
}
struct Profile;
#[async_trait::async_trait]
impl crate::command::CommandHandler for Profile {
async fn run(&self, ctx: crate::command::CommandContext) -> CommandResult {
CommandResult::Ok {
data: json!({
"greeting": format!("hello {}", ctx.options["name"].as_str().unwrap_or("?")),
"count": ctx.options["count"],
"tags": ctx.options["tags"],
}),
cta: Some(cta()),
exit_code: None,
}
}
}
struct Fail;
#[async_trait::async_trait]
impl crate::command::CommandHandler for Fail {
async fn run(&self, _ctx: crate::command::CommandContext) -> CommandResult {
CommandResult::Error {
code: "DENIED".to_string(),
message: "access denied".to_string(),
retryable: false,
exit_code: Some(3),
cta: Some(cta()),
}
}
}
struct Visualize;
#[async_trait::async_trait]
impl crate::command::CommandHandler for Visualize {
async fn run(&self, _ctx: crate::command::CommandContext) -> CommandResult {
CommandResult::Ok {
data: json!({ "preview": { "data": "aW1hZ2U=", "mimeType": "image/png" } }),
cta: None,
exit_code: None,
}
}
}
fn fixture_cli(discovery: McpDiscovery, with_ghost: bool) -> crate::cli::Cli {
let mut profile = CommandDef::build("profile", Profile)
.description("Greet a profile")
.done();
profile.options_fields = vec![
field("name", FieldType::String, true),
field("count", FieldType::Number, false),
field("loud", FieldType::Boolean, false),
field("tags", FieldType::Array(Box::new(FieldType::String)), false),
];
profile.output_schema = Some(json!({
"type": "object",
"properties": {
"greeting": { "type": "string" },
"count": { "type": "number" },
"tags": { "type": "array" }
}
}));
let fail = CommandDef::build("fail", Fail)
.description("Always fails")
.done();
let visualize = CommandDef::build("visualize", Visualize)
.description("Render a preview")
.mcp(McpCommandOptions {
annotations: Some(McpAnnotations {
read_only_hint: Some(true),
..Default::default()
}),
result_content: vec![McpResultContent::Image {
data_pointer: "/preview/data".to_string(),
mime_type_pointer: "/preview/mimeType".to_string(),
}],
..Default::default()
})
.done();
let mut cli = crate::cli::Cli::create("parity")
.mcp(McpServeOptions {
tools: McpToolFilter {
discovery,
..Default::default()
},
..Default::default()
})
.command("profile", profile)
.command("fail", fail)
.command("visualize", visualize);
if with_ghost {
cli = cli.command(
"ghost",
CommandDef::build("ghost", Visualize)
.description("Removed after projection")
.done(),
);
}
cli
}
fn router(cli: &crate::cli::Cli) -> axum::Router {
axum::Router::new().nest_service("/mcp", crate::mcp::http_service(cli).unwrap())
}
async fn serve_swappable(
initial: axum::Router,
) -> (
std::net::SocketAddr,
Arc<RwLock<axum::Router>>,
tokio::task::JoinHandle<()>,
) {
let current = Arc::new(RwLock::new(initial));
let state = Arc::clone(¤t);
let app = axum::Router::new().fallback(move |request: axum::extract::Request| {
let router = state.read().expect("router lock").clone();
async move {
tower::ServiceExt::oneshot(router, request)
.await
.expect("router is infallible")
}
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
(address, current, server)
}
fn only(standard: &str) -> McpRemoteOptions {
McpRemoteOptions {
standards: McpStandardSet::from_versions([McpVersion::from(standard)]).unwrap(),
..McpRemoteOptions::default()
}
}
struct RouterClient {
router: Arc<RwLock<axum::Router>>,
requests: Arc<std::sync::atomic::AtomicUsize>,
}
#[async_trait::async_trait]
impl crate::outbound::HttpClient for RouterClient {
async fn send(&self, request: HttpRequest) -> Result<HttpResponse, HttpClientError> {
self.requests
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let url = url::Url::parse(&request.url).map_err(HttpClientError::transport)?;
let mut builder = axum::http::Request::builder()
.method(request.method.as_str())
.uri(&url[url::Position::BeforePath..])
.header(
"host",
format!(
"{}:{}",
url.host_str().unwrap_or_default(),
url.port_or_known_default().unwrap_or_default()
),
);
for (name, value) in &request.headers {
builder = builder.header(name.as_str(), value.as_str());
}
let request = builder
.body(axum::body::Body::from(request.body.unwrap_or_default()))
.map_err(HttpClientError::transport)?;
let router = self.router.read().expect("router lock").clone();
let response = tower::ServiceExt::oneshot(router, request)
.await
.unwrap_or_else(|never| match never {});
let status = response.status().as_u16();
let headers = response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_string(),
value.to_str().unwrap_or_default().to_string(),
)
})
.collect();
let body = response.into_body().into_data_stream().map(|chunk| {
chunk
.map(|bytes| bytes.to_vec())
.map_err(HttpClientError::transport)
});
Ok(HttpResponse {
status,
headers,
body: Box::pin(body),
})
}
}
#[tokio::test]
async fn portable_client_matches_rmcp_for_every_standard_and_discovery_mode() {
let forwarded = parity_cases(false).await;
assert_eq!(forwarded, 0);
}
#[tokio::test]
async fn portable_client_through_a_host_contract_matches_rmcp() {
let forwarded = parity_cases(true).await;
assert!(forwarded > 0, "the host client was never called");
}
async fn parity_cases(through_contract: bool) -> usize {
let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let calls = [
(
"profile",
json!({ "name": "Ada", "count": 3, "loud": true, "tags": ["x", "y"] }),
),
("profile", json!({})),
("profile", json!({ "name": "Ada", "count": "many" })),
("profile", json!({ "name": "Ada", "unknown": 1 })),
("fail", json!({})),
("visualize", json!({})),
];
let mut cases = 0;
for discovery in [McpDiscovery::Direct, McpDiscovery::Progressive] {
for standard in STANDARDS.iter().copied().chain(["all"]) {
let options = if standard == "all" {
McpRemoteOptions::default()
} else {
only(standard)
};
let label = format!("{discovery:?} {standard}");
let (address, current, server) =
serve_swappable(router(&fixture_cli(discovery, true))).await;
let url = format!("http://{address}/mcp");
let native = within(crate::mcp::remote_commands_with(url.clone(), &options))
.await
.unwrap_or_else(|error| panic!("{label}: rmcp projection failed: {error}"));
let portable_options = if through_contract {
McpRemoteOptions {
http_client: Some(Arc::new(RouterClient {
router: Arc::clone(¤t),
requests: Arc::clone(&requests),
})),
..options.clone()
}
} else {
options.clone()
};
let client = within(McpHttpClient::connect(&url, &portable_options))
.await
.unwrap_or_else(|error| panic!("{label}: portable connect failed: {error}"));
let expected_standard = if standard == "all" {
"2026-07-28"
} else {
standard
};
assert_eq!(client.standard().as_str(), expected_standard, "{label}");
let portable = within(crate::mcp::remote_commands_from_client(client))
.await
.unwrap();
assert_eq!(
native.keys().map(String::as_str).collect::<Vec<_>>(),
["fail", "ghost", "profile", "visualize"],
"{label}"
);
assert_eq!(describe(&portable), describe(&native), "{label}");
let mut outcomes = Vec::new();
for (tool, arguments) in &calls {
let expected = within(run_command(&native[*tool], arguments.clone())).await;
let actual = within(run_command(&portable[*tool], arguments.clone())).await;
assert_eq!(actual, expected, "{label}: {tool} {arguments}");
outcomes.push(expected);
}
assert_eq!(outcomes[0]["ok"]["greeting"], "hello Ada", "{label}");
assert!(outcomes[1]["error"].is_string(), "{label}: {}", outcomes[1]);
assert!(outcomes[4]["error"].is_string(), "{label}: {}", outcomes[4]);
assert_eq!(outcomes[5]["ok"]["preview"]["mimeType"], "image/png");
*current.write().unwrap() = router(&fixture_cli(discovery, false));
let expected = within(run_command(&native["ghost"], json!({}))).await;
let actual = within(run_command(&portable["ghost"], json!({}))).await;
assert_eq!(actual, expected, "{label}: unknown tool");
assert!(expected["error"].is_string(), "{label}: {expected}");
server.abort();
cases += 1;
}
}
assert_eq!(cases, 12);
requests.load(std::sync::atomic::Ordering::SeqCst)
}
#[test]
fn a_missing_host_client_keeps_its_code_through_the_mcp_client_error() {
let error =
McpClientError::Transport(HttpClientError::required("McpRemoteOptions::http_client"));
assert_eq!(error.code(), "HTTP_CLIENT_REQUIRED");
assert!(!error.retryable());
let crate::errors::Error::Multicast(error) = crate::errors::Error::from(error) else {
panic!("expected a coded error");
};
assert_eq!(error.code, "HTTP_CLIENT_REQUIRED");
assert!(
error
.hint
.as_deref()
.is_some_and(|hint| hint.contains("McpRemoteOptions::http_client"))
);
}
#[derive(Clone, Default)]
struct LegacyHttpFixture {
methods: Arc<std::sync::Mutex<Vec<String>>>,
}
async fn legacy_http_post(
axum::extract::State(state): axum::extract::State<LegacyHttpFixture>,
headers: axum::http::HeaderMap,
body: String,
) -> axum::response::Response {
use axum::http::StatusCode;
use axum::response::IntoResponse;
let message: Value = serde_json::from_str(&body).unwrap();
let method = message["method"].as_str().unwrap_or_default().to_string();
state.methods.lock().unwrap().push(method.clone());
let header = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
if header("authorization") != Some("Bearer good") {
return (
StatusCode::UNAUTHORIZED,
[("www-authenticate", "Bearer realm=\"fixture\"")],
"",
)
.into_response();
}
if !matches!(method.as_str(), "initialize" | "server/discover")
&& (header("mcp-session-id") != Some("session-abc")
|| header("mcp-protocol-version") != Some("2025-06-18"))
{
return (
StatusCode::BAD_REQUEST,
"missing session or protocol version",
)
.into_response();
}
let Some(id) = message.get("id").cloned() else {
return StatusCode::ACCEPTED.into_response();
};
let reply = |result: Value| json!({ "jsonrpc": "2.0", "id": id, "result": result });
match method.as_str() {
"initialize" => (
[("mcp-session-id", "session-abc")],
axum::Json(reply(json!({
"protocolVersion": "2025-06-18",
"capabilities": { "tools": {} },
"serverInfo": { "name": "legacy-http", "version": "1.0.0" }
}))),
)
.into_response(),
"tools/list" => {
let notification = json!({
"jsonrpc": "2.0",
"method": "notifications/message",
"params": { "level": "info", "data": "listing" }
});
let response = reply(json!({
"tools": [{
"name": "echo",
"description": "Echo text",
"inputSchema": {
"type": "object",
"properties": { "text": { "type": "string", "description": "Text" } },
"required": ["text"]
}
}]
}));
(
[("content-type", "text/event-stream")],
format!(
"event: message\ndata: {notification}\n\nevent: message\ndata: {response}\n\n"
),
)
.into_response()
}
"tools/call" => {
let arguments = message["params"]["arguments"].clone();
axum::Json(reply(json!({
"content": [{ "type": "text", "text": arguments.to_string() }],
"isError": false,
"structuredContent": { "echo": arguments }
})))
.into_response()
}
_ => axum::Json(json!({
"jsonrpc": "2.0",
"id": id,
"error": { "code": -32601, "message": "Method not found" }
}))
.into_response(),
}
}
async fn serve_legacy_http() -> (String, LegacyHttpFixture, tokio::task::JoinHandle<()>) {
let state = LegacyHttpFixture::default();
let app = axum::Router::new()
.route("/mcp", axum::routing::post(legacy_http_post))
.with_state(state.clone());
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
(format!("http://{address}/mcp"), state, server)
}
fn take_methods(state: &LegacyHttpFixture) -> Vec<String> {
std::mem::take(&mut *state.methods.lock().unwrap())
}
#[tokio::test]
async fn modern_preference_falls_back_to_a_legacy_only_server_like_rmcp() {
let (url, state, server) = serve_legacy_http().await;
let options = McpRemoteOptions::bearer("good");
let native = within(crate::mcp::remote_commands_with(url.clone(), &options))
.await
.unwrap();
let native_call = within(run_command(&native["echo"], json!({ "text": "hi" }))).await;
let native_methods = take_methods(&state);
let client = within(McpHttpClient::connect(&url, &options))
.await
.unwrap();
assert_eq!(client.standard().as_str(), "2025-06-18");
assert_eq!(client.session_id(), Some("session-abc"));
let portable = within(crate::mcp::remote_commands_from_client(client))
.await
.unwrap();
let portable_call = within(run_command(&portable["echo"], json!({ "text": "hi" }))).await;
let portable_methods = take_methods(&state);
assert_eq!(
&native_methods[..3],
["server/discover", "initialize", "notifications/initialized"]
);
assert_eq!(
portable_methods,
[
"server/discover",
"initialize",
"notifications/initialized",
"tools/list",
"tools/call"
]
);
assert_eq!(describe(&portable), describe(&native));
assert_eq!(portable_call, native_call);
assert_eq!(native_call["ok"], json!({ "echo": { "text": "hi" } }));
server.abort();
}
#[tokio::test]
async fn authentication_failure_during_discovery_fails_closed_without_fallback() {
let (url, state, server) = serve_legacy_http().await;
let options = McpRemoteOptions::bearer("bad");
let native = within(crate::mcp::remote_commands_with(url.clone(), &options)).await;
assert!(native.is_err());
assert_eq!(take_methods(&state), ["server/discover"]);
let error = within(McpHttpClient::connect(&url, &options))
.await
.unwrap_err();
assert_eq!(take_methods(&state), ["server/discover"]);
assert!(matches!(
&error,
McpClientError::Unauthorized { status: 401, www_authenticate: Some(challenge) }
if challenge == "Bearer realm=\"fixture\""
));
let error = crate::errors::Error::from(error);
let crate::errors::Error::Multicast(error) = error else {
panic!("expected a coded error");
};
assert_eq!(error.code, "MCP_UNAUTHORIZED");
assert!(error.hint.is_some());
assert!(!error.retryable);
server.abort();
}
#[tokio::test]
async fn a_modern_only_client_does_not_fall_back_to_a_legacy_server() {
let (url, state, server) = serve_legacy_http().await;
let options = McpRemoteOptions {
standards: McpStandardSet::modern_only(),
..McpRemoteOptions::bearer("good")
};
let native = within(crate::mcp::remote_commands_with(url.clone(), &options)).await;
assert!(native.is_err());
assert_eq!(take_methods(&state), ["server/discover"]);
let error = within(McpHttpClient::connect(&url, &options))
.await
.unwrap_err();
assert_eq!(take_methods(&state), ["server/discover"]);
assert_eq!(error.code(), "MCP_NEGOTIATION_FAILED");
server.abort();
}
#[tokio::test]
async fn reserved_and_malformed_headers_are_rejected_before_connecting() {
let error = McpHttpClient::connect(
"http://127.0.0.1:1/mcp",
&McpRemoteOptions {
headers: vec![("Accept".to_string(), "text/plain".to_string())],
..McpRemoteOptions::default()
},
)
.await
.unwrap_err();
assert_eq!(error.code(), "INVALID_HEADER");
let error = McpHttpClient::connect(
"http://127.0.0.1:1/mcp",
&McpRemoteOptions {
headers: vec![("bad name".to_string(), "v".to_string())],
..McpRemoteOptions::default()
},
)
.await
.unwrap_err();
assert!(error.to_string().contains("bad name"), "{error}");
let error = McpHttpClient::connect("ftp://example.test/mcp", &McpRemoteOptions::default())
.await
.unwrap_err();
assert_eq!(error.code(), "MCP_INVALID_URL");
let error = McpHttpClient::connect("http://127.0.0.1:1/mcp", &McpRemoteOptions::default())
.await
.unwrap_err();
assert_eq!(error.code(), "MCP_TRANSPORT_ERROR");
assert!(error.retryable());
}
struct MethodLog {
inner: RouterClient,
methods: Arc<std::sync::Mutex<Vec<String>>>,
}
#[async_trait::async_trait]
impl crate::outbound::HttpClient for MethodLog {
async fn send(&self, request: HttpRequest) -> Result<HttpResponse, HttpClientError> {
if let Some(method) = request
.body
.as_deref()
.and_then(|body| serde_json::from_slice::<Value>(body).ok())
.and_then(|body| body["method"].as_str().map(ToString::to_string))
{
self.methods.lock().unwrap().push(method);
}
self.inner.send(request).await
}
fn sleep(&self, duration: std::time::Duration) -> Option<crate::outbound::Sleep> {
Some(Box::pin(tokio::time::sleep(duration)))
}
}
struct Slow;
#[async_trait::async_trait]
impl crate::command::CommandHandler for Slow {
async fn run(&self, ctx: crate::command::CommandContext) -> CommandResult {
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
CommandResult::Ok {
data: json!({ "greeting": format!("hello {}", ctx.options["name"].as_str().unwrap_or("?")) }),
cta: None,
exit_code: None,
}
}
}
#[tokio::test]
async fn the_client_follows_tasks_and_reads_skills_from_our_own_server() {
let mut slow = CommandDef::build("slow", Slow)
.description("Greet someone slowly")
.mcp(McpCommandOptions {
task: crate::command::McpTaskSupport::Allowed,
..Default::default()
})
.done();
slow.options_fields = vec![field("name", FieldType::String, true)];
let cli = crate::cli::Cli::create("own")
.description("A greeting CLI")
.mcp(McpServeOptions {
tools: McpToolFilter {
discovery: McpDiscovery::Direct,
..Default::default()
},
..Default::default()
})
.command("slow", slow);
let own = crate::mcp::McpHttpServer::from_cli(
&cli,
crate::mcp::McpHttpConfig {
task_spawner: Some(crate::mcp::McpTaskSpawner::tokio()),
..Default::default()
},
)
.unwrap();
let (address, current, server) = serve_swappable(crate::http::mcp_router(own)).await;
let methods = Arc::new(std::sync::Mutex::new(Vec::new()));
let options = McpRemoteOptions {
http_client: Some(Arc::new(MethodLog {
inner: RouterClient {
router: Arc::clone(¤t),
requests: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
},
methods: Arc::clone(&methods),
})),
..McpRemoteOptions::default()
};
let client = within(McpHttpClient::connect(
&format!("http://{address}/mcp"),
&options,
))
.await
.unwrap();
assert!(client.tasks_enabled());
assert!(client.skills_enabled());
let mut arguments = Map::new();
arguments.insert("name".to_string(), json!("Ada"));
let result = within(client.call_tool("slow", arguments)).await.unwrap();
assert_eq!(result["isError"], false, "{result}");
assert_eq!(
result["content"][0]["text"], r#"{"greeting":"hello Ada"}"#,
"{result}"
);
let seen = methods.lock().unwrap().clone();
let call = seen.iter().position(|m| m == "tools/call").expect("a call");
assert!(
seen[call + 1..].iter().any(|m| m == "tasks/get"),
"the call ran as a task: {seen:?}"
);
let skills = within(client.list_skills()).await.unwrap();
let skill = skills
.iter()
.find(|skill| skill.name == "own-slow")
.unwrap_or_else(|| panic!("{:?}", skills.iter().map(|s| &s.name).collect::<Vec<_>>()));
let text = within(client.read_skill_file(skill, &skill.uri))
.await
.unwrap();
assert!(text.starts_with("---\n"), "{text}");
assert!(text.contains("name: own-slow"), "{text}");
server.abort();
}
}
#[cfg(feature = "http")]
mod hostile {
use std::sync::Arc;
use std::time::Duration;
use serde_json::json;
use super::*;
use crate::outbound::{HttpClient, Sleep};
type Respond = dyn Fn(&str, Value) -> HttpResponse + Send + Sync;
struct Scripted {
respond: Box<Respond>,
}
#[async_trait::async_trait]
impl HttpClient for Scripted {
async fn send(&self, request: HttpRequest) -> Result<HttpResponse, HttpClientError> {
let message = request
.body
.as_deref()
.and_then(|body| serde_json::from_slice(body).ok())
.unwrap_or(Value::Null);
Ok((self.respond)(&request.method, message))
}
fn sleep(&self, duration: Duration) -> Option<Sleep> {
Some(Box::pin(tokio::time::sleep(duration)))
}
}
fn scripted(
standard: &str,
respond: impl Fn(&str, Value) -> HttpResponse + Send + Sync + 'static,
) -> McpRemoteOptions {
McpRemoteOptions {
standards: McpStandardSet::from_versions([McpVersion::from(standard)]).unwrap(),
http_client: Some(Arc::new(Scripted {
respond: Box::new(respond),
})),
..McpRemoteOptions::default()
}
}
fn result(message: &Value, result: Value) -> Value {
json!({ "jsonrpc": "2.0", "id": message["id"], "result": result })
}
fn json_reply(message: &Value, value: Value) -> HttpResponse {
HttpResponse::from_bytes(
200,
vec![("content-type".to_string(), JSON.to_string())],
serde_json::to_vec(&result(message, value)).unwrap(),
)
}
fn initialized(standard: &str) -> Value {
json!({
"protocolVersion": standard,
"capabilities": { "tools": {} },
"serverInfo": { "name": "hostile", "version": "1.0.0" }
})
}
fn lifecycle(message: &Value) -> Option<HttpResponse> {
match message["method"].as_str() {
Some("initialize") => Some(json_reply(message, initialized("2025-06-18"))),
Some(method) if method.starts_with("notifications/") => {
Some(HttpResponse::from_bytes(202, Vec::new(), Vec::new()))
}
_ => None,
}
}
fn tool(name: &str) -> Value {
json!({ "name": name, "inputSchema": { "type": "object", "properties": {} } })
}
fn endless(status: u16, content_type: &str, chunk: &'static [u8]) -> HttpResponse {
let body = futures::stream::unfold((), move |()| async move {
tokio::time::sleep(Duration::from_millis(1)).await;
Some((Ok(chunk.to_vec()), ()))
});
HttpResponse {
status,
headers: vec![("content-type".to_string(), content_type.to_string())],
body: Box::pin(body),
}
}
const FILLER: &[u8] = &[b' '; 1024];
const KEEPALIVE: &[u8] = b": keepalive\n\n";
async fn bounded<T>(future: impl std::future::Future<Output = T>) -> T {
tokio::time::timeout(Duration::from_secs(10), future)
.await
.expect("a hostile server hung the client")
}
fn legacy_sse() -> McpRemoteOptions {
let (events, stream) = futures::channel::mpsc::unbounded::<Vec<u8>>();
events
.unbounded_send(b"event: endpoint\ndata: /messages\n\n".to_vec())
.unwrap();
let keepalive = events.clone();
tokio::spawn(async move {
while keepalive.unbounded_send(KEEPALIVE.to_vec()).is_ok() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
});
let stream = std::sync::Mutex::new(Some(stream));
scripted("2024-11-05", move |method, message| {
if method == "GET" {
let body = stream.lock().unwrap().take().expect("one event stream");
return HttpResponse {
status: 200,
headers: vec![("content-type".to_string(), EVENT_STREAM.to_string())],
body: Box::pin(body.map(Ok)),
};
}
let answer = |value: Value| {
let event = format!("event: message\ndata: {}\n\n", result(&message, value));
let _ = events.unbounded_send(event.into_bytes());
};
match (
message["method"].as_str(),
message["params"]["name"].as_str(),
) {
(Some("initialize"), _) => answer(initialized("2024-11-05")),
(Some("tools/call"), Some("hang")) => {}
(Some("tools/call"), Some("huge")) => return endless(500, JSON, FILLER),
(Some("tools/call"), _) => {
answer(json!({ "content": [{ "type": "text", "text": "ok" }] }))
}
_ => {}
}
HttpResponse::from_bytes(202, Vec::new(), Vec::new())
})
}
#[tokio::test]
async fn endless_response_bodies_stop_at_the_cap_with_a_coded_error() {
let options = McpRemoteOptions {
max_response_bytes: 64 * 1024,
..scripted("2025-06-18", |_, message| {
if let Some(reply) = lifecycle(&message) {
return reply;
}
match message["params"]["name"].as_str() {
Some("error") => endless(500, JSON, FILLER),
_ => endless(200, JSON, FILLER),
}
})
};
let client = bounded(McpHttpClient::connect("http://hostile.test/mcp", &options))
.await
.unwrap();
for tool in ["json", "error"] {
let error = bounded(client.call_tool(tool, Map::new()))
.await
.unwrap_err();
assert_eq!(error.code(), "HTTP_BODY_TOO_LARGE", "{tool}: {error}");
assert!(!error.retryable(), "{tool}");
}
let options = McpRemoteOptions {
max_response_bytes: 64 * 1024,
..legacy_sse()
};
let client = bounded(McpHttpClient::connect_legacy_sse(
"http://127.0.0.1:9/sse",
&options,
))
.await
.unwrap();
let error = bounded(client.call_tool("huge", Map::new()))
.await
.unwrap_err();
assert_eq!(error.code(), "HTTP_BODY_TOO_LARGE", "legacy: {error}");
}
#[tokio::test]
async fn a_hung_request_times_out_and_releases_the_legacy_event_stream() {
let timeout = Some(Duration::from_millis(200));
let options = McpRemoteOptions {
request_timeout: timeout,
..scripted("2025-06-18", |_, message| {
lifecycle(&message).unwrap_or_else(|| endless(200, EVENT_STREAM, KEEPALIVE))
})
};
let client = bounded(McpHttpClient::connect("http://hostile.test/mcp", &options))
.await
.unwrap();
let error = bounded(client.call_tool("hang", Map::new()))
.await
.unwrap_err();
assert_eq!(error.code(), "MCP_TIMEOUT", "{error}");
assert!(error.retryable());
let options = McpRemoteOptions {
request_timeout: timeout,
..legacy_sse()
};
let client = bounded(McpHttpClient::connect_legacy_sse(
"http://127.0.0.1:9/sse",
&options,
))
.await
.unwrap();
let (hung, answered) = bounded(async {
tokio::join!(client.call_tool("hang", Map::new()), async {
tokio::time::sleep(Duration::from_millis(50)).await;
client.call_tool("echo", Map::new()).await
})
})
.await;
let hung = hung.unwrap_err();
assert_eq!(hung.code(), "MCP_TIMEOUT", "{hung}");
assert!(hung.retryable());
assert_eq!(answered.unwrap()["content"][0]["text"], "ok");
}
#[tokio::test]
async fn ever_advancing_tool_listings_stop_at_the_page_and_tool_caps() {
let paging = scripted("2025-06-18", |_, message| {
if let Some(reply) = lifecycle(&message) {
return reply;
}
let page = message["params"]["cursor"]
.as_str()
.and_then(|cursor| cursor.parse::<u64>().ok())
.unwrap_or(0);
json_reply(
&message,
json!({ "tools": [tool(&format!("t{page}"))], "nextCursor": (page + 1).to_string() }),
)
});
let client = bounded(McpHttpClient::connect("http://hostile.test/mcp", &paging))
.await
.unwrap();
let error = bounded(client.list_tools()).await.unwrap_err();
assert_eq!(error.code(), "MCP_TOOL_LIMIT_EXCEEDED", "{error}");
assert!(!error.retryable());
let crowded = scripted("2025-06-18", |_, message| {
if let Some(reply) = lifecycle(&message) {
return reply;
}
let tools = (0..=crate::mcp::MAX_REMOTE_TOOLS)
.map(|index| tool(&format!("t{index}")))
.collect::<Vec<_>>();
json_reply(&message, json!({ "tools": tools }))
});
let client = bounded(McpHttpClient::connect("http://hostile.test/mcp", &crowded))
.await
.unwrap();
let error = bounded(client.list_tools()).await.unwrap_err();
assert_eq!(error.code(), "MCP_TOOL_LIMIT_EXCEEDED", "{error}");
let catalog = scripted("2025-06-18", |_, message| {
if let Some(reply) = lifecycle(&message) {
return reply;
}
let structured = |value: Value| json!({ "content": [], "structuredContent": value });
match (
message["method"].as_str(),
message["params"]["name"].as_str(),
) {
(Some("tools/list"), _) => json_reply(
&message,
json!({ "tools": [
tool("search_tools"),
tool("get_tool_details"),
tool("call_read_tool"),
tool("call_write_tool"),
] }),
),
(_, Some("search_tools")) => {
let offset = message["params"]["arguments"]["offset"]
.as_u64()
.unwrap_or(0);
json_reply(
&message,
structured(json!({
"tools": [{ "name": format!("x{offset}") }],
"nextOffset": offset + 1
})),
)
}
_ => {
let name = message["params"]["arguments"]["name"]
.as_str()
.unwrap_or("x");
json_reply(&message, structured(tool(name)))
}
}
});
let client = bounded(McpHttpClient::connect("http://hostile.test/mcp", &catalog))
.await
.unwrap();
match bounded(crate::mcp::remote_commands_from_client(client)).await {
Err(crate::errors::Error::Multicast(error)) => {
assert_eq!(error.code, "MCP_TOOL_LIMIT_EXCEEDED", "{}", error.message);
assert!(!error.retryable);
}
Err(other) => panic!("expected a coded error, got {other}"),
Ok(commands) => panic!("expected a failure, got {} commands", commands.len()),
}
}
#[tokio::test]
async fn empty_advancing_pages_stop_at_an_independent_256_page_boundary() {
for progressive in [false, true] {
let observed = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counter = std::sync::Arc::clone(&observed);
let options = scripted("2025-06-18", move |_, message| {
if let Some(reply) = lifecycle(&message) {
return reply;
}
if progressive && message["method"] == "tools/list" {
return json_reply(
&message,
json!({ "tools": [
tool("search_tools"), tool("get_tool_details"),
tool("call_read_tool"), tool("call_write_tool")
] }),
);
}
let page = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
assert!(page <= 256, "requested a 257th empty catalog page");
if progressive {
assert_eq!(message["params"]["name"], "search_tools");
json_reply(
&message,
json!({ "content": [], "structuredContent": {
"tools": [], "nextOffset": page
} }),
)
} else {
json_reply(
&message,
json!({ "tools": [], "nextCursor": page.to_string() }),
)
}
});
let client = bounded(McpHttpClient::connect("http://hostile.test/mcp", &options))
.await
.unwrap();
if progressive {
match bounded(crate::mcp::remote_commands_from_client(client)).await {
Err(crate::errors::Error::Multicast(error)) => {
assert_eq!(error.code, "MCP_TOOL_LIMIT_EXCEEDED")
}
Err(other) => panic!("expected a coded limit, got {other}"),
Ok(_) => panic!("expected a catalog limit"),
}
} else {
assert_eq!(
bounded(client.list_tools()).await.unwrap_err().code(),
"MCP_TOOL_LIMIT_EXCEEDED"
);
}
assert_eq!(observed.load(std::sync::atomic::Ordering::SeqCst), 256);
}
}
#[tokio::test(start_paused = true)]
async fn a_legacy_request_deadline_includes_waiting_for_the_stream_lock() {
let options = McpRemoteOptions {
request_timeout: Some(Duration::from_millis(200)),
..legacy_sse()
};
let client = McpHttpClient::connect_legacy_sse("http://127.0.0.1:9/sse", &options)
.await
.unwrap();
let Wire::LegacySse(wire) = &client.wire else {
panic!("legacy client expected");
};
let held = wire.events.lock().await;
let error = bounded(client.call_tool("echo", Map::new()))
.await
.unwrap_err();
assert_eq!(error.code(), "MCP_TIMEOUT");
assert!(error.retryable());
drop(held);
assert_eq!(
client.call_tool("echo", Map::new()).await.unwrap()["content"][0]["text"],
"ok"
);
}
struct SlowCatalog {
inner: SharedHttpClient,
}
#[async_trait::async_trait]
impl crate::outbound::HttpClient for SlowCatalog {
async fn send(&self, request: HttpRequest) -> Result<HttpResponse, HttpClientError> {
let message: Value =
serde_json::from_slice(request.body.as_deref().unwrap_or_default()).unwrap();
if message["method"] == "tools/list" || message["params"]["name"] == "search_tools" {
tokio::time::sleep(Duration::from_millis(30)).await;
}
self.inner.send(request).await
}
fn sleep(&self, duration: Duration) -> Option<crate::outbound::Sleep> {
self.inner.sleep(duration)
}
}
#[tokio::test(start_paused = true)]
async fn whole_catalog_deadlines_do_not_restart_for_each_answered_page() {
for progressive in [false, true] {
let mut options = scripted("2025-06-18", move |_, message| {
if let Some(reply) = lifecycle(&message) {
return reply;
}
if progressive && message["method"] == "tools/list" {
return json_reply(
&message,
json!({ "tools": [
tool("search_tools"), tool("get_tool_details"),
tool("call_read_tool"), tool("call_write_tool")
] }),
);
}
if progressive {
let offset = message["params"]["arguments"]["offset"]
.as_u64()
.unwrap_or(0);
json_reply(
&message,
json!({ "content": [], "structuredContent": {
"tools": [], "nextOffset": offset + 1
} }),
)
} else {
let page = message["params"]["cursor"]
.as_str()
.unwrap_or("0")
.parse::<u64>()
.unwrap();
json_reply(
&message,
json!({ "tools": [], "nextCursor": (page + 1).to_string() }),
)
}
});
options.request_timeout = Some(Duration::from_millis(50));
options.http_client = Some(std::sync::Arc::new(SlowCatalog {
inner: options.http_client.take().unwrap(),
}));
let client = McpHttpClient::connect("http://hostile.test/mcp", &options)
.await
.unwrap();
if progressive {
match bounded(crate::mcp::remote_commands_from_client(client)).await {
Err(crate::errors::Error::Multicast(error)) => {
assert_eq!(error.code, "MCP_TIMEOUT")
}
Err(other) => panic!("expected a coded timeout, got {other}"),
Ok(_) => panic!("expected a whole catalog deadline"),
}
} else {
assert_eq!(
bounded(client.list_tools()).await.unwrap_err().code(),
"MCP_TIMEOUT"
);
}
}
}
#[tokio::test]
async fn a_rejected_tool_call_keeps_its_code_and_is_not_retryable() {
let options = scripted("2025-06-18", |_, message| {
if let Some(reply) = lifecycle(&message) {
return reply;
}
match message["method"].as_str() {
Some("tools/list") => json_reply(&message, json!({ "tools": [tool("echo")] })),
_ => HttpResponse::from_bytes(
401,
vec![("www-authenticate".to_string(), "Bearer".to_string())],
Vec::new(),
),
}
});
let client = bounded(McpHttpClient::connect("http://hostile.test/mcp", &options))
.await
.unwrap();
let commands = bounded(crate::mcp::remote_commands_from_client(client))
.await
.unwrap();
let outcome = bounded(run_command(&commands["echo"], json!({}))).await;
assert_eq!(outcome["error"], "MCP_UNAUTHORIZED", "{outcome}");
assert_eq!(outcome["retryable"], false, "{outcome}");
assert_eq!(outcome["exit_code"], 1, "{outcome}");
assert_eq!(
outcome["message"],
"MCP server rejected the credentials with HTTP 401"
);
}
#[tokio::test]
async fn a_configured_protocol_version_header_is_rejected_like_other_reserved_headers() {
let error = McpHttpClient::connect(
"http://127.0.0.1:1/mcp",
&McpRemoteOptions {
headers: vec![("Mcp-Protocol-Version".to_string(), "2025-06-18".to_string())],
..McpRemoteOptions::default()
},
)
.await
.unwrap_err();
assert_eq!(error.code(), "INVALID_HEADER", "{error}");
assert!(
error.to_string().contains("mcp-protocol-version"),
"{error}"
);
}
mod remote_tasks {
use std::sync::Mutex;
use super::*;
type Log = Arc<Mutex<Vec<Value>>>;
fn error_reply(message: &Value, code: i64) -> HttpResponse {
HttpResponse::from_bytes(
200,
vec![("content-type".to_string(), JSON.to_string())],
serde_json::to_vec(&json!({
"jsonrpc": "2.0", "id": message["id"],
"error": { "code": code, "message": "unknown task" }
}))
.unwrap(),
)
}
fn task(status: &str) -> Value {
json!({
"taskId": "t-1", "status": status, "pollIntervalMs": 10,
"createdAt": "2026-11-24T00:00:00Z", "lastUpdatedAt": "2026-11-24T00:00:00Z",
"ttlMs": 60_000
})
}
fn complete(mut value: Value) -> Value {
value["resultType"] = json!("complete");
value
}
fn text(value: &str) -> Value {
json!({ "content": [{ "type": "text", "text": value }], "isError": false })
}
fn server(advertise: bool, gets: Vec<Option<Value>>) -> (McpRemoteOptions, Log) {
let log: Log = Arc::default();
let seen = Arc::clone(&log);
let gets = Mutex::new(gets);
let options = scripted("2026-07-28", move |_, message| {
seen.lock().unwrap().push(message.clone());
match message["method"].as_str() {
Some("server/discover") => {
let extensions = if advertise {
json!({ (TASKS_EXTENSION): {} })
} else {
json!({})
};
json_reply(
&message,
json!({
"resultType": "complete",
"supportedVersions": ["2026-07-28"],
"capabilities": { "tools": {}, "extensions": extensions },
"serverInfo": { "name": "tasks", "version": "1.0.0" }
}),
)
}
Some("tools/call") => {
let mut started = task("working");
started["resultType"] = json!("task");
json_reply(&message, started)
}
Some("tasks/get") => {
let mut gets = gets.lock().unwrap();
let next = if gets.len() > 1 {
gets.remove(0)
} else {
gets[0].clone()
};
match next {
Some(task) => json_reply(&message, complete(task)),
None => error_reply(&message, INVALID_PARAMS),
}
}
_ => json_reply(&message, json!({ "resultType": "complete" })),
}
});
(options, log)
}
fn methods(log: &Log) -> Vec<String> {
log.lock()
.unwrap()
.iter()
.filter_map(|message| message["method"].as_str().map(ToString::to_string))
.collect()
}
async fn connect(options: &McpRemoteOptions) -> McpHttpClient {
bounded(McpHttpClient::connect("http://hostile.test/mcp", options))
.await
.unwrap()
}
fn finished(status: &str, extra: Value) -> Option<Value> {
let mut value = task(status);
value
.as_object_mut()
.unwrap()
.extend(extra.as_object().unwrap().clone());
Some(value)
}
#[tokio::test]
async fn a_task_is_polled_until_it_completes() {
let (options, log) = server(
true,
vec![
Some(task("working")),
finished("completed", json!({ "result": text("done") })),
],
);
let client = connect(&options).await;
assert!(client.tasks_enabled());
let result = bounded(client.call_tool("slow", Map::new())).await.unwrap();
assert_eq!(result, text("done"));
assert_eq!(
methods(&log),
["server/discover", "tools/call", "tasks/get", "tasks/get"]
);
let call = log.lock().unwrap()[1].clone();
assert_eq!(
call["params"]["_meta"]["io.modelcontextprotocol/clientCapabilities"]["extensions"]
["io.modelcontextprotocol/tasks"],
json!({})
);
}
#[tokio::test]
async fn failed_and_cancelled_tasks_keep_their_own_codes() {
for (status, code) in [
("failed", "MCP_TASK_FAILED"),
("cancelled", "MCP_TASK_CANCELLED"),
] {
let error = json!({ "code": -32603, "message": "boom" });
let (options, _) = server(true, vec![finished(status, json!({ "error": error }))]);
let client = connect(&options).await;
let failure = bounded(client.call_tool("slow", Map::new()))
.await
.unwrap_err();
assert_eq!(failure.code(), code, "{failure}");
assert!(!failure.retryable(), "{status}");
}
}
#[tokio::test]
async fn an_unknown_task_is_retried_until_the_lost_window_ends() {
let (options, log) = server(true, vec![None]);
let mut client = connect(&options).await;
client.task_lost_after = Duration::from_millis(30);
let failure = bounded(client.call_tool("slow", Map::new()))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_TASK_LOST", "{failure}");
let gets = methods(&log).iter().filter(|m| *m == "tasks/get").count();
assert_eq!(gets, 4, "polls at 0, 10, 20, and 30 ms of unknown");
assert!(!methods(&log).contains(&"tasks/cancel".to_string()));
}
#[tokio::test]
async fn a_task_that_reappears_within_the_window_completes() {
let (options, _) = server(
true,
vec![
None,
finished("completed", json!({ "result": text("back") })),
],
);
let client = connect(&options).await;
let result = bounded(client.call_tool("slow", Map::new())).await.unwrap();
assert_eq!(result, text("back"));
}
#[tokio::test]
async fn input_requests_are_returned_and_answered_once() {
let requests = json!({ "q": { "method": "elicitation/create", "params": {} } });
let (options, log) = server(
true,
vec![
finished("input_required", json!({ "inputRequests": requests })),
finished("completed", json!({ "result": text("answered") })),
],
);
let client = connect(&options).await;
let outcome = bounded(client.call_tool_outcome("ask", Map::new()))
.await
.unwrap();
assert_eq!(
outcome,
McpToolOutcome::InputRequired {
task_id: "t-1".to_string(),
input_requests: requests,
}
);
let answers = json!({ "q": { "action": "accept", "content": {} } });
let outcome = bounded(client.resume_task("t-1", answers.clone()))
.await
.unwrap();
assert_eq!(outcome, McpToolOutcome::Complete(text("answered")));
let update = log
.lock()
.unwrap()
.iter()
.find(|message| message["method"] == "tasks/update")
.cloned()
.expect("an update was sent");
assert_eq!(update["params"]["taskId"], "t-1");
assert_eq!(update["params"]["inputResponses"], answers);
let sent = methods(&log).len();
let replay = bounded(client.resume_task("t-1", answers))
.await
.unwrap_err();
assert_eq!(replay.code(), "MCP_PROTOCOL_ERROR", "{replay}");
assert_eq!(methods(&log).len(), sent, "a replay sends nothing");
}
#[tokio::test]
async fn a_plain_call_cancels_a_task_that_needs_input() {
let (options, log) = server(
true,
vec![finished("input_required", json!({ "inputRequests": {} }))],
);
let client = connect(&options).await;
let failure = bounded(client.call_tool("ask", Map::new()))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_TASK_INPUT_REQUIRED", "{failure}");
assert_eq!(methods(&log).last().unwrap(), "tasks/cancel");
}
#[tokio::test]
async fn without_an_advertised_extension_the_client_does_not_opt_in() {
let (options, log) = server(false, vec![Some(task("working"))]);
let client = connect(&options).await;
assert!(!client.tasks_enabled());
let failure = bounded(client.call_tool("slow", Map::new()))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_PROTOCOL_ERROR", "{failure}");
let call = log.lock().unwrap()[1].clone();
assert!(
call.pointer("/params/_meta/io.modelcontextprotocol~1clientCapabilities/extensions/io.modelcontextprotocol~1tasks")
.is_none(),
"{call}"
);
assert!(!methods(&log).contains(&"tasks/get".to_string()));
}
#[tokio::test]
async fn dropping_a_followed_call_cancels_the_task() {
let (options, log) = server(true, vec![Some(task("working"))]);
let client = connect(&options).await;
let call = client.call_tool("slow", Map::new());
assert!(
tokio::time::timeout(Duration::from_millis(50), call)
.await
.is_err(),
"the task never finishes"
);
bounded(async {
while !methods(&log).contains(&"tasks/cancel".to_string()) {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await;
let cancel = log
.lock()
.unwrap()
.iter()
.find(|message| message["method"] == "tasks/cancel")
.cloned()
.unwrap();
assert_eq!(cancel["params"]["taskId"], "t-1");
}
#[tokio::test]
async fn a_dropped_call_hands_its_cancel_to_the_host_detach() {
let (options, log) = server(true, vec![Some(task("working"))]);
let held = Arc::new(std::sync::Mutex::new(Vec::new()));
let host = held.clone();
let options = McpRemoteOptions {
detach: Some(Arc::new(move |run| host.lock().unwrap().push(run))),
..options
};
let client = connect(&options).await;
let call = client.call_tool("slow", Map::new());
assert!(
tokio::time::timeout(Duration::from_millis(50), call)
.await
.is_err(),
"the task never finishes"
);
let runs = std::mem::take(&mut *held.lock().unwrap());
assert_eq!(runs.len(), 1, "the host received the cancel");
assert!(!methods(&log).contains(&"tasks/cancel".to_string()));
for run in runs {
bounded(run).await;
}
let cancel = log
.lock()
.unwrap()
.iter()
.find(|message| message["method"] == "tasks/cancel")
.cloned()
.expect("the host ran the cancel");
assert_eq!(cancel["params"]["taskId"], "t-1");
}
}
mod remote_skills {
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use super::*;
const SKILL_MD: &str = "---\nname: code-review\ndescription: Review code using the team's checklist.\n---\n\n# Code review\n\nRead `references/checklist.md`, then review the diff.\n";
const SKILL_DIGEST: &str =
"sha256:d2489d6c182e8df9c178563ff9f2eac7998a0c1bb1278c52a7fd5306e4259160";
const CHECKLIST: &str =
"# Review checklist\n\nCheck correctness, tests, and compatibility.\n";
const CHECKLIST_DIGEST: &str =
"sha256:dbab2de7bf7db9cc95cb6ce681c3690b26184db39f75b958a0287ca6d9e24e20";
const CHECKLIST_URI: &str = "skill://code-review/references/checklist.md";
type Log = Arc<Mutex<Vec<Value>>>;
fn entry() -> Value {
json!({
"uri": "skill://code-review/SKILL.md",
"frontmatter": {
"name": "code-review",
"description": "Review code using the team's checklist."
},
"resources": [
{ "uri": "skill://code-review/SKILL.md", "digest": SKILL_DIGEST, "size": 149 },
{ "uri": CHECKLIST_URI, "digest": CHECKLIST_DIGEST, "size": 65 }
]
})
}
fn server(
advertise: bool,
pages: Vec<Vec<Value>>,
files: Vec<(&'static str, String)>,
) -> (McpRemoteOptions, Log) {
let log: Log = Arc::default();
let seen = Arc::clone(&log);
let options = scripted("2026-07-28", move |_, message| {
seen.lock().unwrap().push(message.clone());
match message["method"].as_str() {
Some("server/discover") => {
let extensions = if advertise {
json!({ (crate::mcp::SKILLS_EXTENSION): { "directoryRead": true } })
} else {
json!({})
};
json_reply(
&message,
json!({
"resultType": "complete",
"supportedVersions": ["2026-07-28"],
"capabilities": { "resources": {}, "extensions": extensions },
"serverInfo": { "name": "skills", "version": "1.0.0" }
}),
)
}
Some("skills/list") => {
let index = message["params"]["cursor"]
.as_str()
.map_or(0, |cursor| cursor.parse::<usize>().unwrap());
let mut page = json!({ "resultType": "complete", "skills": pages[index] });
if index + 1 < pages.len() {
page["nextCursor"] = json!((index + 1).to_string());
}
json_reply(&message, page)
}
Some("resources/read") => {
let uri = message["params"]["uri"].as_str().unwrap();
let served = &files.iter().find(|(file, _)| *file == uri).unwrap().1;
let content = match served.strip_prefix("blob:") {
Some(blob) => {
json!({ "uri": uri, "mimeType": "image/png", "blob": blob })
}
None => {
json!({ "uri": uri, "mimeType": "text/markdown", "text": served })
}
};
json_reply(
&message,
json!({ "resultType": "complete", "contents": [content] }),
)
}
other => panic!("unexpected request {other:?}"),
}
});
let mut options = options;
options.skill_directory = Some(fresh_directory());
(options, log)
}
fn fresh_directory() -> std::path::PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
let directory = std::env::temp_dir().join(format!(
"multicast-remote-skills-{}-{}",
std::process::id(),
SEQUENCE.fetch_add(1, Ordering::SeqCst)
));
let _ = std::fs::remove_dir_all(&directory);
directory
}
fn genuine() -> Vec<(&'static str, String)> {
vec![
("skill://code-review/SKILL.md", SKILL_MD.to_string()),
(CHECKLIST_URI, CHECKLIST.to_string()),
]
}
fn count(log: &Log, method: &str) -> usize {
log.lock()
.unwrap()
.iter()
.filter(|message| message["method"] == method)
.count()
}
async fn connect(options: &McpRemoteOptions) -> McpHttpClient {
bounded(McpHttpClient::connect("http://hostile.test/mcp", options))
.await
.unwrap()
}
async fn listed(pages: Vec<Vec<Value>>) -> Result<Vec<RemoteSkill>, McpClientError> {
let (options, _) = server(true, pages, genuine());
let client = connect(&options).await;
bounded(client.list_skills()).await
}
#[tokio::test]
async fn every_page_is_listed_and_files_are_read_on_demand() {
let other = json!({
"uri": "skill://live-data/SKILL.md",
"frontmatter": { "name": "live-data" },
"resources": "dynamic"
});
let (options, log) = server(true, vec![vec![other], vec![entry()]], genuine());
let client = connect(&options).await;
assert!(client.skills_enabled());
let skills = bounded(client.list_skills()).await.unwrap();
assert_eq!(count(&log, "skills/list"), 2);
assert_eq!(count(&log, "resources/read"), 0, "nothing is prefetched");
assert_eq!(
skills
.iter()
.map(|skill| skill.name.as_str())
.collect::<Vec<_>>(),
["code-review"],
"a dynamic skill is left out"
);
let skill = &skills[0];
assert_eq!(
skill.files[1],
RemoteSkillFile {
uri: CHECKLIST_URI.to_string(),
digest: CHECKLIST_DIGEST.to_string(),
size: 65,
}
);
let text = bounded(client.read_skill_file(skill, CHECKLIST_URI))
.await
.unwrap();
assert_eq!(text, CHECKLIST);
assert_eq!(count(&log, "resources/read"), 1);
let text = bounded(client.read_skill_file(skill, &skill.uri))
.await
.unwrap();
assert_eq!(text, SKILL_MD);
}
#[tokio::test]
async fn altered_files_fail_the_integrity_check() {
let same_size = CHECKLIST.replace("tests", "TESTS");
let longer = format!("{CHECKLIST}!");
for (uri, served) in [(CHECKLIST_URI, same_size), (CHECKLIST_URI, longer)] {
let mut files = genuine();
files[1] = (uri, served);
let (options, _) = server(true, vec![vec![entry()]], files);
let client = connect(&options).await;
let skill = &bounded(client.list_skills()).await.unwrap()[0];
let failure = bounded(client.read_skill_file(skill, uri))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_SKILL_INTEGRITY", "{failure}");
}
}
const LOGO_URI: &str = "skill://code-review/assets/logo.png";
const LOGO_BYTES: [u8; 8] = [0x89, 0x50, 0x4e, 0x47, 0x00, 0x01, 0x02, 0xff];
const LOGO_BLOB: &str = "iVBORwABAv8=";
const LOGO_DIGEST: &str =
"sha256:5ec770aa8b97e5faafa2f01dcab2aed7d090c5685a47c4bc90db867b9bf6c3a4";
fn with_logo(blob: &str) -> (Value, Vec<(&'static str, String)>) {
let mut listed = entry();
listed["resources"]
.as_array_mut()
.unwrap()
.push(json!({ "uri": LOGO_URI, "digest": LOGO_DIGEST, "size": 8 }));
let mut files = genuine();
files.push((LOGO_URI, format!("blob:{blob}")));
(listed, files)
}
#[tokio::test]
async fn binary_files_are_read_as_checked_bytes() {
let (listed, files) = with_logo(LOGO_BLOB);
let (options, _) = server(true, vec![vec![listed]], files);
let client = connect(&options).await;
let skill = &bounded(client.list_skills()).await.unwrap()[0];
let bytes = bounded(client.read_skill_file_bytes(skill, LOGO_URI))
.await
.unwrap();
assert_eq!(bytes, LOGO_BYTES);
let text = bounded(client.read_skill_file_bytes(skill, CHECKLIST_URI))
.await
.unwrap();
assert_eq!(text, CHECKLIST.as_bytes(), "text files read as bytes too");
let failure = bounded(client.read_skill_file(skill, LOGO_URI))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_PROTOCOL_ERROR", "{failure}");
}
#[tokio::test]
async fn altered_or_malformed_blobs_fail_the_integrity_check() {
for blob in ["iVBORwABAv4=", "iVBORwABAv9="] {
let (listed, files) = with_logo(blob);
let (options, _) = server(true, vec![vec![listed]], files);
let client = connect(&options).await;
let skill = &bounded(client.list_skills()).await.unwrap()[0];
let failure = bounded(client.read_skill_file_bytes(skill, LOGO_URI))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_SKILL_INTEGRITY", "{blob}: {failure}");
}
}
#[derive(Default)]
struct MemoryCache {
entries: Mutex<std::collections::BTreeMap<String, Vec<u8>>>,
puts: AtomicUsize,
}
impl McpSkillCache for MemoryCache {
fn get(&self, digest: &str) -> Option<Vec<u8>> {
self.entries.lock().unwrap().get(digest).cloned()
}
fn put(&self, digest: &str, bytes: &[u8]) -> Result<(), String> {
self.puts.fetch_add(1, Ordering::SeqCst);
self.entries
.lock()
.unwrap()
.insert(digest.to_string(), bytes.to_vec());
Ok(())
}
}
#[tokio::test]
async fn a_cached_file_is_read_once_and_then_served_without_a_request() {
let (options, log) = server(true, vec![vec![entry()]], genuine());
let client = connect(&options).await;
let skill = &bounded(client.list_skills()).await.unwrap()[0];
let cache = MemoryCache::default();
for _ in 0..3 {
let bytes = bounded(client.read_skill_file_cached(skill, CHECKLIST_URI, &cache))
.await
.unwrap();
assert_eq!(bytes, CHECKLIST.as_bytes());
}
assert_eq!(
count(&log, "resources/read"),
1,
"only the first read is sent"
);
assert_eq!(cache.puts.load(Ordering::SeqCst), 1);
let failure = bounded(client.read_skill_file_cached(
skill,
"skill://code-review/unlisted.md",
&cache,
))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_PROTOCOL_ERROR", "{failure}");
assert_eq!(
count(&log, "resources/read"),
1,
"an unlisted file sends nothing"
);
}
#[tokio::test]
async fn a_cached_copy_that_fails_the_manifest_is_read_again() {
let (options, log) = server(true, vec![vec![entry()]], genuine());
let client = connect(&options).await;
let skill = &bounded(client.list_skills()).await.unwrap()[0];
let cache = MemoryCache::default();
let altered_skill_md = SKILL_MD.replace("team's", "TEAM'S");
cache.entries.lock().unwrap().extend([
(
CHECKLIST_DIGEST.to_string(),
CHECKLIST.replace("tests", "TESTS").into_bytes(),
),
(SKILL_DIGEST.to_string(), altered_skill_md.into_bytes()),
]);
let bytes = bounded(client.read_skill_file_cached(skill, CHECKLIST_URI, &cache))
.await
.unwrap();
assert_eq!(bytes, CHECKLIST.as_bytes());
let bytes = bounded(client.read_skill_file_cached(skill, &skill.uri, &cache))
.await
.unwrap();
assert_eq!(bytes, SKILL_MD.as_bytes());
assert_eq!(count(&log, "resources/read"), 2);
assert_eq!(
cache.entries.lock().unwrap().get(CHECKLIST_DIGEST).unwrap(),
CHECKLIST.as_bytes(),
"the verified bytes replace the corrupt copy"
);
}
#[tokio::test]
async fn a_failed_read_is_not_cached() {
let mut files = genuine();
files[1].1 = CHECKLIST.replace("tests", "TESTS");
let (options, _) = server(true, vec![vec![entry()]], files);
let client = connect(&options).await;
let skill = &bounded(client.list_skills()).await.unwrap()[0];
let cache = MemoryCache::default();
let failure = bounded(client.read_skill_file_cached(skill, CHECKLIST_URI, &cache))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_SKILL_INTEGRITY", "{failure}");
assert_eq!(cache.puts.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn an_approval_covers_only_the_manifest_it_was_given() {
let (options, _) = server(true, vec![vec![entry()]], genuine());
let client = connect(&options).await;
let skill = bounded(client.list_skills()).await.unwrap().remove(0);
let approval = skill.approve();
assert!(approval.covers(&skill));
let mut reordered = skill.clone();
reordered.files.reverse();
assert!(
approval.covers(&reordered),
"file order is not part of approval"
);
let stored: ApprovedSkill =
serde_json::from_value(serde_json::to_value(&approval).unwrap()).unwrap();
assert!(stored.covers(&skill), "a stored approval still applies");
let mut changes: Vec<(&str, RemoteSkill)> = Vec::new();
let mut digest = skill.clone();
digest.files[1].digest = SKILL_DIGEST.to_string();
changes.push(("a changed digest", digest));
let mut size = skill.clone();
size.files[1].size += 1;
changes.push(("a changed size", size));
let mut added = skill.clone();
added.files.push(RemoteSkillFile {
uri: "skill://code-review/scripts/run.sh".to_string(),
digest: CHECKLIST_DIGEST.to_string(),
size: 65,
});
changes.push(("an added file", added));
let mut removed = skill.clone();
removed.files.pop();
changes.push(("a removed file", removed));
let mut description = skill.clone();
description
.frontmatter
.insert("description".to_string(), json!("Run any script."));
changes.push(("a changed description", description));
for (change, changed) in changes {
assert!(!approval.covers(&changed), "{change} needs a new approval");
}
}
#[test]
fn the_directory_cache_stores_only_matching_bytes() {
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
let directory = std::env::temp_dir().join(format!(
"multicast-skill-cache-{}-{}",
std::process::id(),
SEQUENCE.fetch_add(1, Ordering::SeqCst)
));
let _ = std::fs::remove_dir_all(&directory);
let cache = McpSkillDirectoryCache::open(&directory).unwrap();
assert_eq!(cache.get(CHECKLIST_DIGEST), None);
assert!(cache.put(CHECKLIST_DIGEST, b"other bytes").is_err());
assert!(cache.put("sha256:../escape", CHECKLIST.as_bytes()).is_err());
assert!(cache.put("md5:abc", CHECKLIST.as_bytes()).is_err());
cache.put(CHECKLIST_DIGEST, CHECKLIST.as_bytes()).unwrap();
assert_eq!(cache.get(CHECKLIST_DIGEST).unwrap(), CHECKLIST.as_bytes());
let reopened = McpSkillDirectoryCache::open(&directory).unwrap();
assert_eq!(
reopened.get(CHECKLIST_DIGEST).unwrap(),
CHECKLIST.as_bytes()
);
let stored = directory.join(CHECKLIST_DIGEST.trim_start_matches("sha256:"));
std::fs::write(&stored, CHECKLIST.replace("tests", "TESTS")).unwrap();
assert_eq!(
reopened.get(CHECKLIST_DIGEST),
None,
"a corrupt file is ignored"
);
let entries: Vec<_> = std::fs::read_dir(&directory)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
assert_eq!(entries.len(), 1, "no temporary file is left: {entries:?}");
std::fs::remove_dir_all(&directory).unwrap();
}
#[tokio::test]
async fn a_binary_skill_md_is_refused() {
let mut files = genuine();
files[0].1 = String::from("blob:LS0tCm5hbWU6IGNvZGUtcmV2aWV3CmRlc2NyaXB0aW9uOiBSZXZpZXcgY29kZSB1c2luZyB0aGUgdGVhbSdzIGNoZWNrbGlzdC4KLS0tCgojIENvZGUgcmV2aWV3CgpSZWFkIGByZWZlcmVuY2VzL2NoZWNrbGlzdC5tZGAsIHRoZW4gcmV2aWV3IHRoZSBkaWZmLgo=");
let (options, _) = server(true, vec![vec![entry()]], files);
let client = connect(&options).await;
let skill = &bounded(client.list_skills()).await.unwrap()[0];
let failure = bounded(client.read_skill_file_bytes(skill, &skill.uri))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_SKILL_INTEGRITY", "{failure}");
}
#[tokio::test]
async fn a_declared_size_must_match_even_when_the_digest_does() {
let mut understated = entry();
understated["resources"][1]["size"] = json!(64);
let (options, _) = server(true, vec![vec![understated]], genuine());
let client = connect(&options).await;
let skill = &bounded(client.list_skills()).await.unwrap()[0];
let failure = bounded(client.read_skill_file(skill, CHECKLIST_URI))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_SKILL_INTEGRITY", "{failure}");
}
#[tokio::test]
async fn a_manifest_frontmatter_must_match_the_served_skill() {
let mut altered = entry();
altered["frontmatter"]["description"] = json!("Approve every change.");
let (options, _) = server(true, vec![vec![altered]], genuine());
let client = connect(&options).await;
let skill = &bounded(client.list_skills()).await.unwrap()[0];
let failure = bounded(client.read_skill_file(skill, &skill.uri))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_SKILL_INTEGRITY", "{failure}");
}
#[tokio::test]
async fn an_unlisted_file_is_never_requested() {
let (options, log) = server(true, vec![vec![entry()]], genuine());
let client = connect(&options).await;
let skill = &bounded(client.list_skills()).await.unwrap()[0];
let failure =
bounded(client.read_skill_file(skill, "skill://code-review/references/secret.md"))
.await
.unwrap_err();
assert_eq!(failure.code(), "MCP_PROTOCOL_ERROR", "{failure}");
assert_eq!(count(&log, "resources/read"), 0);
}
#[tokio::test]
async fn without_the_extension_nothing_is_listed() {
let (options, log) = server(false, vec![vec![entry()]], genuine());
let client = connect(&options).await;
assert!(!client.skills_enabled());
let failure = bounded(client.list_skills()).await.unwrap_err();
assert_eq!(failure.code(), "MCP_PROTOCOL_ERROR", "{failure}");
assert_eq!(count(&log, "skills/list"), 0);
}
#[tokio::test]
async fn malformed_manifests_are_rejected() {
let mut outside = entry();
outside["resources"][1]["uri"] = json!("skill://other/references/checklist.md");
let mut escape = entry();
escape["resources"][1]["uri"] = json!("skill://code-review/../other/SKILL.md");
let mut renamed = entry();
renamed["frontmatter"]["name"] = json!("other");
let mut no_skill_md = entry();
no_skill_md["resources"].as_array_mut().unwrap().remove(0);
let mut bad_digest = entry();
bad_digest["resources"][1]["digest"] = json!("md5:abc");
let mut oversized = entry();
oversized["resources"][1]["size"] = json!(16 * 1024 * 1024);
for (case, pages) in [
("outside the skill", vec![vec![outside]]),
("parent segment", vec![vec![escape]]),
("name mismatch", vec![vec![renamed]]),
("no SKILL.md", vec![vec![no_skill_md]]),
("bad digest", vec![vec![bad_digest]]),
("oversized", vec![vec![oversized]]),
("duplicate", vec![vec![entry()], vec![entry()]]),
] {
let failure = listed(pages).await.unwrap_err();
assert_eq!(failure.code(), "MCP_PROTOCOL_ERROR", "{case}: {failure}");
}
assert_eq!(listed(vec![vec![entry()]]).await.unwrap().len(), 1);
}
#[tokio::test]
async fn skill_requests_carry_their_uri_as_the_name_header() {
let (options, _) = server(true, vec![vec![entry()]], genuine());
let client = connect(&options).await;
for method in ["skills/get", "resources/directory/read"] {
let message = json!({
"jsonrpc": "2.0", "id": 1, "method": method,
"params": { "uri": "skill://code-review/SKILL.md" }
});
let headers = client.protocol_headers(&message, true);
assert_eq!(
headers
.get("mcp-name")
.and_then(|value| value.to_str().ok()),
Some("skill://code-review/SKILL.md"),
"{method}"
);
}
}
async fn run_cli(options: &McpRemoteOptions, argv: &[&str]) -> (Option<i32>, String) {
let cli = crate::cli::Cli::create("docs").remote_mcp_skills_with(
"skills",
"http://hostile.test/mcp",
None,
options,
);
let mut output = Vec::new();
let mut args = vec!["skills".to_string()];
args.extend(argv.iter().map(ToString::to_string));
args.extend(["--format".to_string(), "json".to_string()]);
let code = bounded(cli.serve_to(args, &mut output, false))
.await
.unwrap();
(code, String::from_utf8(output).unwrap())
}
#[tokio::test]
async fn the_skills_commands_list_and_show_checked_files() {
let (options, log) = server(true, vec![vec![entry()]], genuine());
let cli = crate::cli::Cli::create("docs").remote_mcp_skills_with(
"skills",
"http://hostile.test/mcp",
None,
&options,
);
drop(cli);
assert!(log.lock().unwrap().is_empty(), "mounting makes no request");
let (code, output) = run_cli(&options, &["list"]).await;
assert_eq!(code, None, "{output}");
let listed: Value = serde_json::from_str(&output).unwrap();
assert_eq!(
listed,
json!([{
"name": "code-review",
"description": "Review code using the team's checklist.",
"uri": "skill://code-review/SKILL.md",
"files": ["skill://code-review/SKILL.md", CHECKLIST_URI],
"approval": "none"
}])
);
assert_eq!(count(&log, "resources/read"), 0);
let (code, output) = run_cli(&options, &["show", "code-review"]).await;
assert_eq!(code, None, "{output}");
assert_eq!(
serde_json::from_str::<Value>(&output).unwrap(),
json!(SKILL_MD)
);
let (code, output) = run_cli(
&options,
&["show", "code-review", "--file", "references/checklist.md"],
)
.await;
assert_eq!(code, None, "{output}");
assert_eq!(
serde_json::from_str::<Value>(&output).unwrap(),
json!(CHECKLIST)
);
assert_eq!(count(&log, "resources/read"), 2);
let (code, output) = run_cli(
&options,
&["show", "code-review", "--file", "references/checklist.md"],
)
.await;
assert_eq!(code, None, "{output}");
assert_eq!(
serde_json::from_str::<Value>(&output).unwrap(),
json!(CHECKLIST)
);
assert_eq!(
count(&log, "resources/read"),
2,
"a cached file is not read again"
);
}
fn approval_of(output: &str) -> Value {
let listed: Value = serde_json::from_str(output).unwrap();
listed[0]["approval"].clone()
}
#[tokio::test]
async fn the_approve_command_records_the_checked_manifest() {
let (options, log) = server(true, vec![vec![entry()]], genuine());
let (code, output) = run_cli(&options, &["approve", "code-review"]).await;
assert_eq!(code, None, "{output}");
assert_eq!(
serde_json::from_str::<Value>(&output).unwrap(),
json!({
"name": "code-review",
"approval": "approved",
"files": ["skill://code-review/SKILL.md", CHECKLIST_URI]
})
);
assert_eq!(
count(&log, "resources/read"),
2,
"approval reads every file"
);
let (_, output) = run_cli(&options, &["list"]).await;
assert_eq!(approval_of(&output), json!("approved"));
let mut changed = entry();
let altered = CHECKLIST.replace("tests", "TESTS");
{
use sha2::Digest;
let digest = sha2::Sha256::digest(altered.as_bytes())
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
let files = changed["resources"].as_array_mut().unwrap();
let checklist = files
.iter_mut()
.find(|file| file["uri"] == CHECKLIST_URI)
.unwrap();
checklist["digest"] = json!(format!("sha256:{digest}"));
checklist["size"] = json!(altered.len());
}
let (mut other, _) = server(true, vec![vec![changed]], genuine());
other.skill_directory = options.skill_directory.clone();
let (_, output) = run_cli(&other, &["list"]).await;
assert_eq!(approval_of(&output), json!("changed"));
let (stranger, _) = server(true, vec![vec![entry()]], genuine());
let mut stranger = stranger;
stranger.skill_directory = options.skill_directory.clone();
let cli = crate::cli::Cli::create("docs").remote_mcp_skills_with(
"skills",
"http://other.test/mcp",
None,
&stranger,
);
let mut output = Vec::new();
let code = bounded(
cli.serve_to(
["skills", "list", "--format", "json"]
.map(String::from)
.to_vec(),
&mut output,
false,
),
)
.await
.unwrap();
let output = String::from_utf8(output).unwrap();
assert_eq!(code, None, "{output}");
assert_eq!(approval_of(&output), json!("none"));
let approvals = options.skill_directory.clone().unwrap().join("approvals");
let stored = std::fs::read_dir(&approvals)
.unwrap()
.map(|entry| entry.unwrap().path())
.collect::<Vec<_>>();
assert_eq!(stored.len(), 1, "{stored:?}");
let copied = {
use sha2::Digest;
let name = sha2::Sha256::digest(b"http://other.test/mcp")
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
approvals.join(format!("{name}.json"))
};
std::fs::copy(&stored[0], &copied).unwrap();
let cli = crate::cli::Cli::create("docs").remote_mcp_skills_with(
"skills",
"http://other.test/mcp",
None,
&stranger,
);
let mut output = Vec::new();
let code = bounded(
cli.serve_to(
["skills", "list", "--format", "json"]
.map(String::from)
.to_vec(),
&mut output,
false,
),
)
.await
.unwrap();
let output = String::from_utf8(output).unwrap();
assert_eq!(code, None, "{output}");
assert_eq!(approval_of(&output), json!("none"), "a copied approval");
}
#[tokio::test]
async fn the_approve_command_refuses_altered_files() {
let mut files = genuine();
files[1].1 = CHECKLIST.replace("tests", "TESTS");
let (options, _) = server(true, vec![vec![entry()]], files);
let (code, output) = run_cli(&options, &["approve", "code-review"]).await;
assert_eq!(code, Some(1), "{output}");
assert!(output.contains("MCP_SKILL_INTEGRITY"), "{output}");
let (_, output) = run_cli(&options, &["list"]).await;
assert_eq!(approval_of(&output), json!("none"));
}
#[tokio::test]
async fn the_show_command_refuses_altered_unknown_and_unlisted_files() {
let mut files = genuine();
files[1].1 = CHECKLIST.replace("tests", "TESTS");
let (options, log) = server(true, vec![vec![entry()]], files);
let (code, output) = run_cli(
&options,
&["show", "code-review", "--file", "references/checklist.md"],
)
.await;
assert_eq!(code, Some(1), "{output}");
assert!(output.contains("MCP_SKILL_INTEGRITY"), "{output}");
let (code, output) = run_cli(&options, &["show", "missing"]).await;
assert_eq!(code, Some(1), "{output}");
assert!(output.contains("MCP_SKILL_NOT_FOUND"), "{output}");
let reads = count(&log, "resources/read");
let (code, output) = run_cli(
&options,
&["show", "code-review", "--file", "../other/SKILL.md"],
)
.await;
assert_eq!(code, Some(1), "{output}");
assert_eq!(
count(&log, "resources/read"),
reads,
"an unlisted file is never requested"
);
}
#[tokio::test]
async fn the_skills_commands_without_the_extension() {
let (options, log) = server(false, vec![vec![entry()]], genuine());
let (code, output) = run_cli(&options, &["list"]).await;
assert_eq!(code, None, "{output}");
assert_eq!(serde_json::from_str::<Value>(&output).unwrap(), json!([]));
let (code, output) = run_cli(&options, &["show", "code-review"]).await;
assert_eq!(code, Some(1), "{output}");
assert_eq!(count(&log, "skills/list"), 0);
}
}
}