use std::sync::Arc;
use http_body_util::{BodyExt, Full};
use hyper::body::Bytes;
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use rmcp::model::{
CallToolRequestParams, CallToolResponse, CallToolResult, Implementation, ListToolsResult,
PaginatedRequestParams, ServerCapabilities, ServerConfig, Tool,
};
use rmcp::service::RequestContext;
use rmcp::{ErrorData, RoleServer, ServerHandler, ServiceExt};
use serde_json::{json, Value as Json};
use tokio::sync::Mutex;
use crate::persist::Endpoint;
const PROTOCOL_VERSION: &str = "2025-06-18";
const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
#[derive(Debug, Clone, thiserror::Error)]
pub enum UpstreamError {
#[error("cannot reach the MemFork daemon at {url}: {reason}")]
Unreachable {
url: String,
reason: String,
},
#[error("the MemFork daemon answered unexpectedly: {0}")]
Unusable(String),
#[error("{message}")]
Rpc {
code: i64,
message: String,
},
}
impl UpstreamError {
pub fn is_disconnect(&self) -> bool {
matches!(self, UpstreamError::Unreachable { .. })
}
}
#[derive(Debug)]
pub struct Upstream {
url: String,
token: String,
http: Client<hyper_util::client::legacy::connect::HttpConnector, Full<Bytes>>,
session: Mutex<Option<String>>,
next_id: std::sync::atomic::AtomicI64,
}
impl Upstream {
pub async fn connect(endpoint: &Endpoint) -> Result<Self, UpstreamError> {
let port = endpoint
.port
.ok_or_else(|| UpstreamError::Unusable("the endpoint file names no port".to_owned()))?;
let token = endpoint.token.clone().ok_or_else(|| {
UpstreamError::Unusable("the endpoint file carries no token".to_owned())
})?;
let upstream = Upstream {
url: format!("http://127.0.0.1:{port}{}", crate::serve::MCP_PATH),
token,
http: Client::builder(TokioExecutor::new()).build_http(),
session: Mutex::new(None),
next_id: std::sync::atomic::AtomicI64::new(1),
};
upstream.initialize().await?;
Ok(upstream)
}
async fn initialize(&self) -> Result<(), UpstreamError> {
let result = self
.request(
"initialize",
json!({
"protocolVersion": PROTOCOL_VERSION,
"capabilities": {},
"clientInfo": { "name": "memfork-proxy", "version": crate::VERSION },
}),
)
.await?;
let _ = result;
self.notify("notifications/initialized", json!({})).await
}
pub async fn list_tools(&self) -> Result<Vec<Tool>, UpstreamError> {
let result = self.request("tools/list", json!({})).await?;
let tools = result
.get("tools")
.cloned()
.ok_or_else(|| UpstreamError::Unusable("no tools in the answer".to_owned()))?;
serde_json::from_value(tools)
.map_err(|e| UpstreamError::Unusable(format!("the tool list did not parse: {e}")))
}
pub async fn call_tool(&self, params: &CallToolRequestParams) -> Result<Json, UpstreamError> {
let payload = serde_json::to_value(params)
.map_err(|e| UpstreamError::Unusable(format!("cannot encode the call: {e}")))?;
self.request("tools/call", payload).await
}
async fn notify(&self, method: &str, params: Json) -> Result<(), UpstreamError> {
let body = json!({ "jsonrpc": "2.0", "method": method, "params": params });
self.post(&body).await.map(|_| ())
}
async fn request(&self, method: &str, params: Json) -> Result<Json, UpstreamError> {
let id = self
.next_id
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let body = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
let text = self.post(&body).await?;
let message = parse_message(&text)?;
if let Some(error) = message.get("error") {
return Err(UpstreamError::Rpc {
code: error.get("code").and_then(Json::as_i64).unwrap_or(0),
message: error
.get("message")
.and_then(Json::as_str)
.unwrap_or("the daemon reported an error")
.to_owned(),
});
}
message
.get("result")
.cloned()
.ok_or_else(|| UpstreamError::Unusable(format!("no result in {text}")))
}
async fn post(&self, body: &Json) -> Result<String, UpstreamError> {
let unreachable = |reason: String| UpstreamError::Unreachable {
url: self.url.clone(),
reason,
};
let mut builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(&self.url)
.header(hyper::header::CONTENT_TYPE, "application/json")
.header(hyper::header::ACCEPT, "application/json, text/event-stream")
.header(
hyper::header::AUTHORIZATION,
format!("Bearer {}", self.token),
)
.header("MCP-Protocol-Version", PROTOCOL_VERSION);
if let Some(session) = self.session.lock().await.as_ref() {
builder = builder.header("Mcp-Session-Id", session);
}
let request = builder
.body(Full::new(Bytes::from(body.to_string())))
.map_err(|e| unreachable(format!("cannot build the request: {e}")))?;
let response = tokio::time::timeout(REQUEST_TIMEOUT, self.http.request(request))
.await
.map_err(|_| unreachable("it did not answer in time".to_owned()))?
.map_err(|e| unreachable(e.to_string()))?;
if let Some(session) = response
.headers()
.get("Mcp-Session-Id")
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
{
*self.session.lock().await = Some(session);
}
let status = response.status();
let collected = response
.into_body()
.collect()
.await
.map_err(|e| unreachable(format!("the answer could not be read: {e}")))?;
let text = String::from_utf8_lossy(&collected.to_bytes()).into_owned();
if status == hyper::StatusCode::UNAUTHORIZED {
return Err(UpstreamError::Unusable(
"the daemon rejected our token; it may have been restarted".to_owned(),
));
}
if !status.is_success() {
return Err(UpstreamError::Unusable(format!("HTTP {status}: {text}")));
}
Ok(text)
}
}
fn parse_message(text: &str) -> Result<Json, UpstreamError> {
let trimmed = text.trim_start();
if trimmed.starts_with('{') {
return serde_json::from_str(trimmed)
.map_err(|e| UpstreamError::Unusable(format!("the answer did not parse: {e}")));
}
for line in text.lines() {
if let Some(payload) = line.strip_prefix("data:") {
let payload = payload.trim();
if payload.is_empty() {
continue;
}
return serde_json::from_str(payload).map_err(|e| {
UpstreamError::Unusable(format!("an event-stream payload did not parse: {e}"))
});
}
}
Err(UpstreamError::Unusable(format!(
"the answer was neither JSON nor an event stream: {}",
text.chars().take(200).collect::<String>()
)))
}
pub type Reconnect =
Arc<dyn Fn() -> futures::future::BoxFuture<'static, Result<Upstream, String>> + Send + Sync>;
#[derive(Clone)]
pub struct Proxy {
upstream: Arc<tokio::sync::RwLock<Option<Arc<Upstream>>>>,
connect: Reconnect,
}
impl std::fmt::Debug for Proxy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Proxy").finish_non_exhaustive()
}
}
impl Proxy {
pub fn new(connect: Reconnect) -> Self {
Proxy {
upstream: Arc::new(tokio::sync::RwLock::new(None)),
connect,
}
}
async fn current(&self) -> Result<Arc<Upstream>, String> {
if let Some(existing) = self.upstream.read().await.clone() {
return Ok(existing);
}
let mut slot = self.upstream.write().await;
if let Some(existing) = slot.clone() {
return Ok(existing);
}
let fresh = Arc::new((self.connect)().await?);
*slot = Some(Arc::clone(&fresh));
Ok(fresh)
}
async fn reconnect(&self) -> Result<Arc<Upstream>, String> {
let mut slot = self.upstream.write().await;
let fresh = Arc::new((self.connect)().await?);
*slot = Some(Arc::clone(&fresh));
Ok(fresh)
}
async fn with_retry<T, F>(&self, operation: F) -> Result<T, ErrorData>
where
F: for<'a> Fn(&'a Upstream) -> futures::future::BoxFuture<'a, Result<T, UpstreamError>>,
{
let first = self.current().await.map_err(|why| {
ErrorData::internal_error(
format!(
"the MemFork daemon could not be started: {why}. \
Run `memfork doctor` to see the state of the data directory."
),
None,
)
})?;
match operation(&first).await {
Ok(value) => return Ok(value),
Err(e) if !e.is_disconnect() => return Err(as_mcp_error(&e)),
Err(_) => {}
}
let fresh = self.reconnect().await.map_err(|why| {
ErrorData::internal_error(
format!(
"the MemFork daemon stopped and could not be restarted: {why}. \
Run `memfork doctor` to see the state of the data directory."
),
None,
)
})?;
operation(&fresh).await.map_err(|e| {
ErrorData::internal_error(
format!(
"the MemFork daemon stopped, was restarted, and still could not \
be reached: {e}"
),
None,
)
})
}
}
fn as_mcp_error(e: &UpstreamError) -> ErrorData {
match e {
UpstreamError::Rpc { code, message } => {
ErrorData::new(rmcp::model::ErrorCode(*code as i32), message.clone(), None)
}
other => ErrorData::internal_error(other.to_string(), None),
}
}
impl ServerHandler for Proxy {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
.with_server_info(
Implementation::new("memfork", crate::VERSION)
.with_title("MemFork — branchable agent memory"),
)
.with_instructions(crate::mcp::INSTRUCTIONS)
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
Ok(ListToolsResult::with_all_items(crate::mcp::tool_list()))
}
async fn call_tool(
&self,
request: CallToolRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
let params = request.clone();
let raw = self
.with_retry(move |up| {
let params = params.clone();
Box::pin(async move { up.call_tool(¶ms).await })
})
.await?;
match serde_json::from_value::<CallToolResult>(raw.clone()) {
Ok(result) => Ok(result.into()),
Err(_) => Ok(CallToolResult::structured(raw).into()),
}
}
}
pub async fn serve_stdio(proxy: Proxy) -> Result<(), String> {
let service = proxy
.serve(rmcp::transport::stdio())
.await
.map_err(|e| format!("cannot start the MCP proxy: {e}"))?;
service
.waiting()
.await
.map_err(|e| format!("the MCP proxy stopped with an error: {e}"))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_plain_json_answer_parses() {
let message =
parse_message(r#"{"jsonrpc":"2.0","id":1,"result":{"ok":true}}"#).expect("parsed");
assert_eq!(message["result"]["ok"], true);
}
#[test]
fn an_event_stream_answer_parses() {
let body =
"event: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"ok\":true}}\n\n";
let message = parse_message(body).expect("parsed");
assert_eq!(message["result"]["ok"], true);
}
#[test]
fn something_that_is_neither_is_reported_rather_than_guessed_at() {
let err = parse_message("<html>not this</html>").expect_err("refused");
assert!(err.to_string().contains("neither JSON nor an event stream"));
}
#[test]
fn only_a_transport_failure_counts_as_the_daemon_going_away() {
assert!(UpstreamError::Unreachable {
url: "http://127.0.0.1:1/mcp".to_owned(),
reason: "refused".to_owned(),
}
.is_disconnect());
assert!(!UpstreamError::Rpc {
code: -32602,
message: "bad arguments".to_owned(),
}
.is_disconnect());
assert!(!UpstreamError::Unusable("odd".to_owned()).is_disconnect());
}
}