use std::sync::Arc;
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;
use crate::tools::{self, dispatch::Session, dispatch::ToolError};
pub const INSTRUCTIONS: &str = "\
MemFork gives you branchable memory: store and recall things, and — the part \
that matters — fork the whole of memory before a risky step, then merge it if \
the attempt worked or discard it if it did not. Forking costs the same whatever \
memory holds, so fork freely: it is cheaper than being careful. Writes on a \
fork are invisible to the branch you came from until you merge, and discarding \
leaves that branch exactly as it was. You can also read memory as it was at any \
earlier point.
What you store is kept on disk and is still there next time, so memory you \
write in one session is memory you can recall in the next. Other clients can \
be using the same memory at the same time, and will see what you write; each \
of you keeps your own current branch, so switching branches never moves \
anybody else.";
pub fn tool_list() -> Vec<Tool> {
tools::all()
.into_iter()
.map(|t| Tool::new(t.name, t.description, Arc::new(t.schema)).with_title(t.title))
.collect()
}
#[derive(Debug, Clone)]
pub struct MemforkServer {
session: Arc<Session>,
}
impl MemforkServer {
pub fn new(session: Arc<Session>) -> Self {
MemforkServer { session }
}
}
impl ServerHandler for MemforkServer {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
.with_server_info(
Implementation::new("memfork", env!("CARGO_PKG_VERSION"))
.with_title("MemFork — branchable agent memory"),
)
.with_instructions(INSTRUCTIONS)
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
Ok(ListToolsResult::with_all_items(tool_list()))
}
async fn call_tool(
&self,
request: CallToolRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
let args = request.arguments.unwrap_or_default();
match self.session.call(&request.name, &args) {
Ok(value) => Ok(CallToolResult::structured(value).into()),
Err(e @ (ToolError::UnknownTool(_) | ToolError::BadArguments(_))) => {
Err(ErrorData::invalid_params(e.to_string(), None))
}
Err(e @ ToolError::Engine(_)) => Ok(CallToolResult::structured_error(json!({
"error": e.to_string(),
"tool": request.name,
}))
.into()),
}
}
}
pub async fn serve_stdio(session: Arc<Session>) -> Result<(), String> {
let service = MemforkServer::new(session)
.serve(rmcp::transport::stdio())
.await
.map_err(|e| format!("cannot start the MCP server: {e}"))?;
service
.waiting()
.await
.map_err(|e| format!("the MCP server stopped with an error: {e}"))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_registry_tool_is_offered_with_its_schema() {
let listed = tool_list();
let registry = tools::all();
assert_eq!(listed.len(), registry.len());
for (tool, def) in listed.iter().zip(®istry) {
assert_eq!(tool.name, def.name);
assert_eq!(tool.description.as_deref(), Some(def.description.as_str()));
assert_eq!(
tool.input_schema.as_ref(),
&def.schema,
"the server altered the schema of {}",
def.name
);
}
}
#[test]
fn the_instructions_describe_what_this_build_actually_does() {
let lower = INSTRUCTIONS.to_ascii_lowercase();
assert!(lower.contains("kept on disk"), "{INSTRUCTIONS}");
assert!(lower.contains("still there next time"), "{INSTRUCTIONS}");
assert!(
!lower.contains("nothing is written to disk"),
"the instructions still claim nothing is persisted"
);
assert!(
lower.contains("other clients can be using the same memory"),
"the instructions do not mention sharing: {INSTRUCTIONS}"
);
assert!(
!lower.contains("start a second copy") && !lower.contains("one process owns"),
"the instructions still describe the single-process behaviour that \
the daemon replaced"
);
}
#[test]
fn the_instructions_name_no_vendor() {
const VENDORS: &[&str] = &[
"claude",
"anthropic",
"openai",
"gpt",
"gemini",
"grok",
"cursor",
"codex",
];
let lower = INSTRUCTIONS.to_ascii_lowercase();
for v in VENDORS {
assert!(!lower.contains(v), "instructions mention `{v}`");
}
}
}