use std::collections::HashMap;
use std::time::Duration;
use anyhow::{Context, ensure};
use rig_mcp_server::{McpServer, TemplateVars};
use rmcp::model::{PromptMessage, Role};
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines, ReadHalf, WriteHalf};
use crate::mcp::Add;
const DRAFT: &str = "2026-07-28";
const LEGACY: &str = "2025-11-25";
fn catalog() -> McpServer {
McpServer::new("test")
.tool(Add)
.resource("memo://fixed", "fixed", "text/plain", "static")
.resource_template(
"memo://{id}",
"memo",
"A memo, by its id.",
"text/plain",
|_: TemplateVars| async move { Ok::<_, std::io::Error>("dynamic".to_owned()) },
)
.prompt("hi", "Say hi.", vec![], |_: &HashMap<String, String>| {
vec![PromptMessage::new_text(Role::User, "hi")]
})
}
struct Wire {
lines: Lines<BufReader<ReadHalf<tokio::io::DuplexStream>>>,
writer: WriteHalf<tokio::io::DuplexStream>,
next_id: u64,
}
impl Wire {
fn connect(server: McpServer) -> Self {
let (server_side, client_side) = tokio::io::duplex(64 * 1024);
tokio::spawn(server.serve(server_side));
let (reader, writer) = tokio::io::split(client_side);
Self {
lines: BufReader::new(reader).lines(),
writer,
next_id: 0,
}
}
async fn send(&mut self, message: Value) -> anyhow::Result<()> {
let mut line = message.to_string();
line.push('\n');
self.writer.write_all(line.as_bytes()).await?;
Ok(())
}
async fn request(&mut self, method: &str, params: Value) -> anyhow::Result<Value> {
self.next_id += 1;
let id = self.next_id;
self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))
.await?;
loop {
let line = self
.lines
.next_line()
.await?
.context("server closed the pipe")?;
let message: Value = serde_json::from_str(&line)?;
if message.get("id") != Some(&json!(id)) {
continue;
}
ensure!(message.get("error").is_none(), "{method} failed: {message}");
return message.get("result").cloned().context("no result");
}
}
async fn legacy(&mut self) -> anyhow::Result<()> {
let params = json!({
"protocolVersion": LEGACY,
"capabilities": {},
"clientInfo": {"name": "raw", "version": "0"},
});
self.request("initialize", params).await?;
self.send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}))
.await
}
async fn draft(&mut self, method: &str, params: Value) -> anyhow::Result<Value> {
let meta = json!({
"io.modelcontextprotocol/protocolVersion": DRAFT,
"io.modelcontextprotocol/clientInfo": {"name": "raw", "version": "0"},
"io.modelcontextprotocol/clientCapabilities": {},
});
let mut params = params;
if let Some(object) = params.as_object_mut() {
object.insert("_meta".to_owned(), meta);
}
self.request(method, params).await
}
}
fn hints(result: &Value) -> (Option<&Value>, Option<&Value>) {
(result.get("ttlMs"), result.get("cacheScope"))
}
async fn draft_results(server: McpServer) -> anyhow::Result<Vec<(&'static str, Value)>> {
let mut wire = Wire::connect(server);
Ok(vec![
("tools/list", wire.draft("tools/list", json!({})).await?),
("prompts/list", wire.draft("prompts/list", json!({})).await?),
(
"resources/list",
wire.draft("resources/list", json!({})).await?,
),
(
"resources/templates/list",
wire.draft("resources/templates/list", json!({})).await?,
),
(
"resources/read (static)",
wire.draft("resources/read", json!({"uri": "memo://fixed"}))
.await?,
),
(
"resources/read (template)",
wire.draft("resources/read", json!({"uri": "memo://other"}))
.await?,
),
])
}
#[tokio::test]
async fn draft_clients_get_hints_on_every_catalog_result() -> anyhow::Result<()> {
for (method, result) in draft_results(catalog()).await? {
let (ttl, scope) = hints(&result);
let template = method.ends_with("(template)");
let (want_ttl, want_scope) = if template {
(json!(0), json!("private"))
} else {
(json!(60_000), json!("public"))
};
ensure!(
ttl == Some(&want_ttl),
"{method}: ttlMs {ttl:?} in {result}"
);
ensure!(
scope == Some(&want_scope),
"{method}: cacheScope {scope:?} in {result}"
);
}
Ok(())
}
#[tokio::test]
async fn list_ttl_sets_the_ttl_for_the_fixed_catalog() -> anyhow::Result<()> {
let server = catalog().list_ttl(Duration::from_secs(5));
let mut wire = Wire::connect(server);
let tools = wire.draft("tools/list", json!({})).await?;
ensure!(hints(&tools).0 == Some(&json!(5_000)), "{tools}");
Ok(())
}
#[tokio::test]
async fn bearer_guarded_catalog_is_private() -> anyhow::Result<()> {
let mut wire = Wire::connect(catalog().bearer_token("s3cret"));
let tools = wire.draft("tools/list", json!({})).await?;
ensure!(hints(&tools).1 == Some(&json!("private")), "{tools}");
Ok(())
}
#[tokio::test]
async fn legacy_clients_still_list_and_read_without_hints() -> anyhow::Result<()> {
let mut wire = Wire::connect(catalog());
wire.legacy().await?;
let tools = wire.request("tools/list", json!({})).await?;
let names: Vec<&str> = tools
.get("tools")
.and_then(Value::as_array)
.context("tools array")?
.iter()
.filter_map(|tool| tool.get("name").and_then(Value::as_str))
.collect();
ensure!(names.contains(&"add"), "{tools}");
ensure!(hints(&tools) == (None, None), "{tools}");
let read = wire
.request("resources/read", json!({"uri": "memo://fixed"}))
.await?;
ensure!(hints(&read) == (None, None), "{read}");
let prompts = wire.request("prompts/list", json!({})).await?;
ensure!(hints(&prompts) == (None, None), "{prompts}");
Ok(())
}