use axum::http::header;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::io::{BufRead, Write};
use std::sync::Arc;
use crate::discovery::AgentManifest;
pub const MCP_PROTOCOL_VERSION: &str = "2024-11-05";
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JsonRpcRequest {
pub jsonrpc: String,
#[serde(default)]
pub id: Option<Value>,
pub method: String,
#[serde(default)]
pub params: Value,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct JsonRpcError {
pub code: i32,
pub message: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JsonRpcResponse {
pub jsonrpc: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<JsonRpcError>,
}
impl JsonRpcResponse {
pub fn ok(id: Option<Value>, result: Value) -> Self {
Self {
jsonrpc: "2.0".to_string(),
id,
result: Some(result),
error: None,
}
}
pub fn err(id: Option<Value>, code: i32, message: impl Into<String>) -> Self {
Self {
jsonrpc: "2.0".to_string(),
id,
result: None,
error: Some(JsonRpcError {
code,
message: message.into(),
}),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct McpResource {
pub uri: String,
pub name: String,
pub description: String,
#[serde(rename = "mimeType")]
pub mime_type: String,
#[serde(skip_serializing)]
pub route_path: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct McpTool {
pub name: String,
pub description: String,
#[serde(rename = "inputSchema")]
pub input_schema: Value,
#[serde(skip_serializing)]
pub method: String,
#[serde(skip_serializing)]
pub route_path: String,
}
type ToolHandler = Arc<dyn Fn(Value) -> Result<Value, String> + Send + Sync>;
type ResourceHandler = Arc<dyn Fn(&str) -> Result<String, String> + Send + Sync>;
#[derive(Clone)]
pub struct McpServer {
pub server_name: String,
pub server_version: String,
pub resources: Vec<McpResource>,
pub tools: Vec<McpTool>,
tool_handlers: HashMap<String, ToolHandler>,
resource_handlers: HashMap<String, ResourceHandler>,
}
impl McpServer {
pub fn from_manifest(manifest: &AgentManifest) -> Self {
let resources = manifest
.endpoints
.iter()
.filter(|e| e.method.eq_ignore_ascii_case("GET"))
.map(|e| McpResource {
uri: format!("ferrik://{}", e.name),
name: e.name.clone(),
description: e.description.clone(),
mime_type: if e.path.ends_with(".json") {
"application/json".to_string()
} else {
"text/markdown".to_string()
},
route_path: e.path.clone(),
})
.collect();
let tools = manifest
.actions
.iter()
.map(|a| McpTool {
name: a.name.clone(),
description: a.description.clone(),
input_schema: a.input_schema.clone().unwrap_or_else(|| {
json!({
"type": "object",
"properties": {},
"additionalProperties": true
})
}),
method: a.method.clone(),
route_path: a.path.clone(),
})
.collect();
Self {
server_name: manifest.app_name.clone(),
server_version: manifest.version.clone(),
resources,
tools,
tool_handlers: HashMap::new(),
resource_handlers: HashMap::new(),
}
}
pub fn with_tool_handler<F>(mut self, tool_name: impl Into<String>, handler: F) -> Self
where
F: Fn(Value) -> Result<Value, String> + Send + Sync + 'static,
{
self.tool_handlers
.insert(tool_name.into(), Arc::new(handler));
self
}
pub fn with_resource_handler<F>(mut self, uri: impl Into<String>, handler: F) -> Self
where
F: Fn(&str) -> Result<String, String> + Send + Sync + 'static,
{
self.resource_handlers.insert(uri.into(), Arc::new(handler));
self
}
pub fn handle_request(&self, req: JsonRpcRequest) -> JsonRpcResponse {
match req.method.as_str() {
"initialize" => JsonRpcResponse::ok(
req.id,
json!({
"protocolVersion": MCP_PROTOCOL_VERSION,
"capabilities": {
"resources": { "listChanged": false },
"tools": { "listChanged": false }
},
"serverInfo": {
"name": self.server_name,
"version": self.server_version
}
}),
),
"ping" => JsonRpcResponse::ok(req.id, json!({})),
"resources/list" => JsonRpcResponse::ok(
req.id,
json!({ "resources": self.resources }),
),
"resources/read" => self.handle_resource_read(req.id, &req.params),
"tools/list" => JsonRpcResponse::ok(req.id, json!({ "tools": self.tools })),
"tools/call" => self.handle_tool_call(req.id, &req.params),
other => JsonRpcResponse::err(req.id, -32601, format!("Method not found: {}", other)),
}
}
fn handle_resource_read(&self, id: Option<Value>, params: &Value) -> JsonRpcResponse {
let Some(uri) = params.get("uri").and_then(|v| v.as_str()) else {
return JsonRpcResponse::err(id, -32602, "Missing required parameter 'uri'");
};
let Some(resource) = self.resources.iter().find(|r| r.uri == uri) else {
return JsonRpcResponse::err(id, -32002, format!("Resource not found: {}", uri));
};
if let Some(handler) = self.resource_handlers.get(uri) {
return match handler(uri) {
Ok(text) => JsonRpcResponse::ok(
id,
json!({
"contents": [{
"uri": resource.uri,
"mimeType": resource.mime_type,
"text": text
}]
}),
),
Err(err) => JsonRpcResponse::err(id, -32000, err),
};
}
let summary = format!(
"---\nuri: {}\nroute: {}\n---\n\n# {}\n\n{}\n",
resource.uri, resource.route_path, resource.name, resource.description
);
JsonRpcResponse::ok(
id,
json!({
"contents": [{
"uri": resource.uri,
"mimeType": resource.mime_type,
"text": summary
}]
}),
)
}
fn handle_tool_call(&self, id: Option<Value>, params: &Value) -> JsonRpcResponse {
let Some(name) = params.get("name").and_then(|v| v.as_str()) else {
return JsonRpcResponse::err(id, -32602, "Missing required parameter 'name'");
};
let arguments = params
.get("arguments")
.cloned()
.unwrap_or_else(|| json!({}));
let Some(tool) = self.tools.iter().find(|t| t.name == name) else {
return JsonRpcResponse::err(id, -32602, format!("Unknown MCP tool: {}", name));
};
if let Some(handler) = self.tool_handlers.get(name) {
return match handler(arguments) {
Ok(val) => JsonRpcResponse::ok(
id,
json!({
"content": [{
"type": "text",
"text": serde_json::to_string_pretty(&val).unwrap_or_default()
}],
"isError": false
}),
),
Err(err) => JsonRpcResponse::ok(
id,
json!({
"content": [{ "type": "text", "text": err }],
"isError": true
}),
),
};
}
let result_payload = json!({
"tool": tool.name,
"method": tool.method,
"path": tool.route_path,
"arguments": arguments,
"status": "dispatched"
});
JsonRpcResponse::ok(
id,
json!({
"content": [{
"type": "text",
"text": serde_json::to_string_pretty(&result_payload).unwrap_or_default()
}],
"isError": false
}),
)
}
pub fn handle_json_line(&self, line: &str) -> Option<String> {
let trimmed = line.trim();
if trimmed.is_empty() {
return None;
}
let resp = match serde_json::from_str::<JsonRpcRequest>(trimmed) {
Ok(req) => {
if req.id.is_none() && req.method.starts_with("notifications/") {
return None;
}
self.handle_request(req)
}
Err(err) => JsonRpcResponse::err(None, -32700, format!("Parse error: {}", err)),
};
serde_json::to_string(&resp).ok()
}
pub fn serve_io<R: BufRead, W: Write>(&self, reader: R, mut writer: W) -> std::io::Result<()> {
for line in reader.lines() {
let line = line?;
if let Some(out) = self.handle_json_line(&line) {
writeln!(writer, "{}", out)?;
writer.flush()?;
}
}
Ok(())
}
}
pub fn mcp_router<S>(server: McpServer) -> Router<S>
where
S: Clone + Send + Sync + 'static,
{
let post_server = server.clone();
let sse_server = server;
Router::new().route(
"/mcp",
get(move || {
let info = json!({
"endpoint": "/mcp",
"protocolVersion": MCP_PROTOCOL_VERSION,
"server": sse_server.server_name,
"version": sse_server.server_version
});
async move {
let body = format!("event: endpoint\ndata: {}\n\n", info);
(
[(header::CONTENT_TYPE, "text/event-stream; charset=utf-8")],
body,
)
.into_response()
}
})
.post(move |Json(req): Json<JsonRpcRequest>| {
let srv = post_server.clone();
async move { Json(srv.handle_request(req)) }
}),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::discovery::AgentEndpoint;
use crate::response::ActionAffordance;
use crate::testing::TestApp;
use schemars::JsonSchema;
use std::io::Cursor;
#[derive(Serialize, JsonSchema)]
struct CreatePostInput {
title: String,
}
fn sample_server() -> McpServer {
let manifest = AgentManifest::new("blog_app", "0.1.0")
.with_endpoint(AgentEndpoint::new(
"posts",
"GET",
"/posts.ai",
"List all posts",
))
.with_action(ActionAffordance::with_schema::<CreatePostInput>(
"posts_create",
"POST",
"/posts",
"Create a new post",
));
McpServer::from_manifest(&manifest)
.with_resource_handler("ferrik://posts", |_| Ok("# Posts\n\n- Hello".to_string()))
.with_tool_handler("posts_create", |args| {
Ok(json!({ "id": 1, "title": args["title"] }))
})
}
#[test]
fn handles_stdio_json_rpc_lifecycle() {
let server = sample_server();
let input = concat!(
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}\n",
"{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\",\"params\":{}}\n",
"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"resources/list\",\"params\":{}}\n",
"{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"resources/read\",\"params\":{\"uri\":\"ferrik://posts\"}}\n",
"{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/list\",\"params\":{}}\n",
"{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/call\",\"params\":{\"name\":\"posts_create\",\"arguments\":{\"title\":\"AI\"}}}\n",
"{\"jsonrpc\":\"2.0\",\"id\":6,\"method\":\"unknown/method\",\"params\":{}}\n",
"not-json\n"
);
let mut output = Vec::new();
server.serve_io(Cursor::new(input), &mut output).unwrap();
let lines: Vec<String> = String::from_utf8(output)
.unwrap()
.lines()
.map(String::from)
.collect();
assert_eq!(lines.len(), 7);
let init: Value = serde_json::from_str(&lines[0]).unwrap();
assert_eq!(init["result"]["protocolVersion"], MCP_PROTOCOL_VERSION);
let resources: Value = serde_json::from_str(&lines[1]).unwrap();
assert!(resources["result"]["resources"]
.as_array()
.unwrap()
.iter()
.any(|r| r["uri"] == "ferrik://posts"));
let read: Value = serde_json::from_str(&lines[2]).unwrap();
assert!(read["result"]["contents"][0]["text"]
.as_str()
.unwrap()
.contains("# Posts"));
let tools: Value = serde_json::from_str(&lines[3]).unwrap();
assert_eq!(tools["result"]["tools"][0]["name"], "posts_create");
let call: Value = serde_json::from_str(&lines[4]).unwrap();
assert_eq!(call["result"]["isError"], false);
assert!(call["result"]["content"][0]["text"]
.as_str()
.unwrap()
.contains("AI"));
let unknown: Value = serde_json::from_str(&lines[5]).unwrap();
assert_eq!(unknown["error"]["code"], -32601);
let parse_err: Value = serde_json::from_str(&lines[6]).unwrap();
assert_eq!(parse_err["error"]["code"], -32700);
}
#[tokio::test]
async fn mounts_http_and_sse_mcp_endpoint() {
let server = sample_server();
let app = TestApp::spawn_with(move |_db| async move { mcp_router(server) }).await;
app.get_html("/mcp")
.await
.assert_ok()
.assert_header_contains("content-type", "text/event-stream")
.assert_contains("event: endpoint");
let resp: Value = app
.as_agent(&["posts:write"])
.call_mcp_tool("posts_create", json!({ "title": "Remote MCP" }))
.await
.assert_ok()
.json();
assert_eq!(resp["result"]["isError"], false);
assert!(resp["result"]["content"][0]["text"]
.as_str()
.unwrap()
.contains("Remote MCP"));
}
}