use axum::body::Body;
use axum::http::{header, HeaderMap, Method, Request, StatusCode};
use axum::response::IntoResponse;
use axum::routing::get;
use axum::{Json, Router};
use http_body_util::BodyExt;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::io::{BufRead, Write};
use std::sync::Arc;
use tower::ServiceExt;
use crate::auth::{extract_raw_api_key, hash_agent_key, AgentKeyStore, AgentPrincipal};
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: Some(id.unwrap_or(Value::Null)),
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>,
key_store: Option<Arc<dyn AgentKeyStore>>,
require_auth: bool,
}
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": false
})
}),
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(),
key_store: None,
require_auth: false,
}
}
pub fn with_key_store(mut self, store: Arc<dyn AgentKeyStore>) -> Self {
self.key_store = Some(store);
self.require_auth = true;
self
}
pub fn with_auth_required(mut self, required: bool) -> Self {
self.require_auth = required;
self
}
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),
};
}
JsonRpcResponse::err(
id,
-32002,
format!(
"No handler or HTTP router registered for MCP resource '{}'",
resource.uri
),
)
}
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
}),
),
};
}
JsonRpcResponse::err(
id,
-32601,
format!(
"No handler or HTTP router registered for MCP tool '{}'",
tool.name
),
)
}
async fn authenticate(&self, headers: &HeaderMap) -> Result<Option<AgentPrincipal>, JsonRpcError> {
if !self.require_auth && self.key_store.is_none() {
return Ok(None);
}
let Some(raw_key) = extract_raw_api_key(headers) else {
return Err(JsonRpcError {
code: -32001,
message: "Unauthorized: valid Agent API key required".to_string(),
});
};
let Some(store) = &self.key_store else {
return Err(JsonRpcError {
code: -32001,
message: "Unauthorized: AgentKeyStore is not configured on MCP server".to_string(),
});
};
let key_hash = hash_agent_key(&raw_key);
match store.resolve_by_hash(&key_hash).await {
Ok(Some(principal)) => Ok(Some(principal)),
Ok(None) => Err(JsonRpcError {
code: -32001,
message: "Unauthorized: invalid or revoked Agent API key".to_string(),
}),
Err(err) => Err(JsonRpcError {
code: -32001,
message: format!("Unauthorized: {}", err.public_message()),
}),
}
}
pub async fn handle_http_request(
&self,
req: JsonRpcRequest,
headers: &HeaderMap,
app_router: Option<Router>,
) -> JsonRpcResponse {
let principal = match self.authenticate(headers).await {
Ok(p) => p,
Err(err) => return JsonRpcResponse::err(req.id, err.code, err.message),
};
match req.method.as_str() {
"tools/call" => {
let Some(name) = req.params.get("name").and_then(|v| v.as_str()) else {
return JsonRpcResponse::err(req.id, -32602, "Missing required parameter 'name'");
};
let Some(tool) = self.tools.iter().find(|t| t.name == name) else {
return JsonRpcResponse::err(
req.id,
-32602,
format!("Unknown MCP tool: {}", name),
);
};
if let Some(agent) = &principal {
let resource_scope = route_resource_scope(&tool.route_path, "write");
let allowed = agent.has_scope(&tool.name)
|| resource_scope
.as_deref()
.is_some_and(|s| agent.has_scope(s));
if !allowed {
return JsonRpcResponse::err(
req.id,
-32001,
format!(
"Forbidden: agent '{}' lacks scope for tool '{}'",
agent.name, tool.name
),
);
}
}
if self.tool_handlers.contains_key(name) {
return self.handle_tool_call(req.id, &req.params);
}
let Some(router) = app_router else {
return self.handle_tool_call(req.id, &req.params);
};
let arguments = req
.params
.get("arguments")
.cloned()
.unwrap_or_else(|| json!({}));
proxy_tool_call(req.id, tool, arguments, headers, router).await
}
"resources/read" => {
let Some(uri) = req.params.get("uri").and_then(|v| v.as_str()) else {
return JsonRpcResponse::err(req.id, -32602, "Missing required parameter 'uri'");
};
let Some(resource) = self.resources.iter().find(|r| r.uri == uri) else {
return JsonRpcResponse::err(
req.id,
-32002,
format!("Resource not found: {}", uri),
);
};
if let Some(agent) = &principal {
let resource_scope = route_resource_scope(&resource.route_path, "read");
let allowed = agent.has_scope(&resource.name)
|| resource_scope
.as_deref()
.is_some_and(|s| agent.has_scope(s));
if !allowed {
return JsonRpcResponse::err(
req.id,
-32001,
format!(
"Forbidden: agent '{}' lacks scope for resource '{}'",
agent.name, resource.uri
),
);
}
}
if self.resource_handlers.contains_key(uri) {
return self.handle_resource_read(req.id, &req.params);
}
let Some(router) = app_router else {
return self.handle_resource_read(req.id, &req.params);
};
proxy_resource_read(req.id, resource, headers, router).await
}
_ => self.handle_request(req),
}
}
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(())
}
}
fn route_resource_scope(route_path: &str, action: &str) -> Option<String> {
let trimmed = route_path.trim_start_matches('/');
let seg = trimmed.split('/').next()?;
let seg = seg
.strip_suffix(".ai")
.or_else(|| seg.strip_suffix(".json"))
.or_else(|| seg.strip_suffix(".html"))
.unwrap_or(seg);
if seg.is_empty() || seg == "ai" {
return None;
}
Some(format!("{}:{}", seg, action))
}
fn substitute_path_params(route_path: &str, arguments: &mut Value) -> Result<String, String> {
let mut resolved = route_path.to_string();
let mut start = 0;
while let Some(open) = resolved[start..].find('{') {
let abs_open = start + open;
let Some(close) = resolved[abs_open..].find('}') else {
break;
};
let abs_close = abs_open + close;
let param_name = resolved[abs_open + 1..abs_close].to_string();
let val = arguments
.as_object_mut()
.and_then(|map| map.remove(¶m_name))
.ok_or_else(|| format!("Missing required path parameter '{}'", param_name))?;
let val_str = match val {
Value::String(s) => s,
Value::Number(n) => n.to_string(),
Value::Bool(b) => b.to_string(),
other => other.to_string(),
};
resolved.replace_range(abs_open..=abs_close, &val_str);
start = abs_open + val_str.len();
}
Ok(resolved)
}
async fn proxy_tool_call(
id: Option<Value>,
tool: &McpTool,
mut arguments: Value,
incoming_headers: &HeaderMap,
router: Router,
) -> JsonRpcResponse {
let path = match substitute_path_params(&tool.route_path, &mut arguments) {
Ok(p) => p,
Err(err) => return JsonRpcResponse::err(id, -32602, err),
};
let method = match Method::from_bytes(tool.method.as_bytes()) {
Ok(m) => m,
Err(_) => {
return JsonRpcResponse::err(
id,
-32603,
format!("Invalid HTTP method '{}'", tool.method),
)
}
};
let mut builder = Request::builder()
.method(method.clone())
.uri(&path)
.header(header::ACCEPT, "application/json");
if let Some(auth) = incoming_headers.get(header::AUTHORIZATION) {
builder = builder.header(header::AUTHORIZATION, auth);
}
if let Some(key) = incoming_headers.get("x-agent-key") {
builder = builder.header("x-agent-key", key);
}
let body = if matches!(method, Method::POST | Method::PUT | Method::PATCH) {
builder = builder.header(header::CONTENT_TYPE, "application/json");
let bytes = serde_json::to_vec(&arguments).unwrap_or_default();
Body::from(bytes)
} else {
Body::empty()
};
let req = match builder.body(body) {
Ok(r) => r,
Err(err) => {
return JsonRpcResponse::err(id, -32603, format!("Failed to build request: {}", err))
}
};
let resp = match router.oneshot(req).await {
Ok(r) => r,
Err(err) => {
return JsonRpcResponse::err(id, -32603, format!("Failed to dispatch tool: {}", err))
}
};
let status = resp.status();
let bytes = resp
.into_body()
.collect()
.await
.map(|c| c.to_bytes())
.unwrap_or_default();
let text = String::from_utf8_lossy(&bytes).to_string();
JsonRpcResponse::ok(
id,
json!({
"content": [{
"type": "text",
"text": text
}],
"isError": !status.is_success()
}),
)
}
async fn proxy_resource_read(
id: Option<Value>,
resource: &McpResource,
incoming_headers: &HeaderMap,
router: Router,
) -> JsonRpcResponse {
let mut builder = Request::builder()
.method(Method::GET)
.uri(&resource.route_path)
.header(header::ACCEPT, &resource.mime_type);
if let Some(auth) = incoming_headers.get(header::AUTHORIZATION) {
builder = builder.header(header::AUTHORIZATION, auth);
}
if let Some(key) = incoming_headers.get("x-agent-key") {
builder = builder.header("x-agent-key", key);
}
let req = match builder.body(Body::empty()) {
Ok(r) => r,
Err(err) => {
return JsonRpcResponse::err(id, -32603, format!("Failed to build request: {}", err))
}
};
let resp = match router.oneshot(req).await {
Ok(r) => r,
Err(err) => {
return JsonRpcResponse::err(id, -32603, format!("Failed to read resource: {}", err))
}
};
let status = resp.status();
let bytes = resp
.into_body()
.collect()
.await
.map(|c| c.to_bytes())
.unwrap_or_default();
let text = String::from_utf8_lossy(&bytes).to_string();
if !status.is_success() {
return JsonRpcResponse::err(
id,
-32002,
format!("Resource request failed with HTTP {}: {}", status.as_u16(), text),
);
}
JsonRpcResponse::ok(
id,
json!({
"contents": [{
"uri": resource.uri,
"mimeType": resource.mime_type,
"text": text
}]
}),
)
}
pub fn mount_mcp(app_router: Router, server: McpServer) -> Router {
let post_server = server.clone();
let sse_server = server;
let proxy_router = app_router.clone();
let mcp = Router::new().route(
"/mcp",
get(move |headers: HeaderMap| {
let srv = sse_server.clone();
async move {
if let Err(err) = srv.authenticate(&headers).await {
return (
StatusCode::UNAUTHORIZED,
Json(JsonRpcResponse::err(None, err.code, err.message)),
)
.into_response();
}
let info = json!({
"endpoint": "/mcp",
"protocolVersion": MCP_PROTOCOL_VERSION,
"server": srv.server_name,
"version": srv.server_version
});
let body = format!("event: endpoint\ndata: {}\n\n", info);
(
[(header::CONTENT_TYPE, "text/event-stream; charset=utf-8")],
body,
)
.into_response()
}
})
.post(move |headers: HeaderMap, Json(req): Json<JsonRpcRequest>| {
let srv = post_server.clone();
let router = proxy_router.clone();
async move { Json(srv.handle_http_request(req, &headers, Some(router)).await) }
}),
);
app_router.merge(mcp)
}
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 |headers: HeaderMap| {
let srv = sse_server.clone();
async move {
if let Err(err) = srv.authenticate(&headers).await {
return (
StatusCode::UNAUTHORIZED,
Json(JsonRpcResponse::err(None, err.code, err.message)),
)
.into_response();
}
let info = json!({
"endpoint": "/mcp",
"protocolVersion": MCP_PROTOCOL_VERSION,
"server": srv.server_name,
"version": srv.server_version
});
let body = format!("event: endpoint\ndata: {}\n\n", info);
(
[(header::CONTENT_TYPE, "text/event-stream; charset=utf-8")],
body,
)
.into_response()
}
})
.post(move |headers: HeaderMap, Json(req): Json<JsonRpcRequest>| {
let srv = post_server.clone();
async move { Json(srv.handle_http_request(req, &headers, None).await) }
}),
)
}
#[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"));
}
}