use std::io::Write;
use std::path::{Path, PathBuf};
use rmcp::{
handler::server::wrapper::Json, handler::server::wrapper::Parameters,
handler::server::ServerHandler, model::*, prompt_handler, tool, tool_handler, tool_router,
ErrorData as McpError,
};
use serde::Serialize;
use deedar::{Client, Walk};
use crate::args::*;
const SCHEME: &str = "deed";
const TEXT: &str = "text/plain";
const RESOURCE_TTL_MS: u64 = 0;
#[derive(Clone)]
pub struct DeedarServer {
url: String,
seat: Option<PathBuf>,
}
enum Access {
Read,
Write,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct DeedRow {
pub id: String,
pub kind: String,
pub name: String,
pub paths: Vec<String>,
pub sources: Vec<String>,
pub agent: String,
pub digest: String,
pub body: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct HeadRow {
pub size: usize,
pub root: String,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct AuditRow {
pub clean: bool,
pub logged: usize,
pub missing: Vec<String>,
pub unlogged: Vec<String>,
pub backfill_settles_it: bool,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct HandoverRow {
pub proven: Vec<String>,
pub head: Option<HeadRow>,
pub head_signer: Option<String>,
pub head_accepted: bool,
pub bridged_from: Option<usize>,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
#[serde(untagged)]
pub enum CurrentResult {
One(DeedRow),
Many(CurrentTips),
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct CurrentTips {
pub deeds: Vec<DeedRow>,
pub note: CurrentNote,
}
#[derive(Debug, Clone, Copy, Serialize, schemars::JsonSchema)]
pub enum CurrentNote {
#[serde(rename = "fork")]
Fork,
#[serde(rename = "cycle")]
Cycle,
}
fn row(deed: &deed::Deed) -> DeedRow {
DeedRow {
id: deed.id.to_string(),
kind: deed.kind.token().to_string(),
name: deed.name.clone(),
paths: deed.paths.iter().map(|p| p.display().to_string()).collect(),
sources: deed.sources.iter().map(source_text).collect(),
agent: deed.produced_by.agent_id.clone(),
digest: deedar::deed_digest(deed),
body: serde_json::to_value(&deed.body).unwrap_or(serde_json::Value::Null),
}
}
fn rows_for(client: &mut Client, ids: &[deed::DeedId]) -> Result<Vec<DeedRow>, McpError> {
let mut out = Vec::with_capacity(ids.len());
for id in ids {
out.push(row(&client.get(id).map_err(bad)?));
}
Ok(out)
}
fn source_text(source: &deed::Source) -> String {
match source {
deed::Source::Deed(id) => format!("deed:{id}"),
deed::Source::Path(path) => format!("path:{}", path.display()),
deed::Source::Url(url) => format!("url:{url}"),
}
}
fn missing_seat(dir: &Path) -> McpError {
let path = dir.display();
McpError::internal_error(
format!(
"DEEDAR_URL is unset and there is no store at {path}; \
`export DEEDAR_URL=file://{path}` or `deedar --url file://{path}`"
),
None,
)
}
fn bad(e: impl std::fmt::Display) -> McpError {
McpError::internal_error(format!("{e}"), None)
}
fn tool_failure(
client: &mut Client,
raw: &str,
asked: Option<&deed::DeedId>,
err: deed::Error,
) -> McpError {
let about_argument = match &err {
deed::Error::InvalidId(_) => true,
deed::Error::NotFound(missing) => {
missing == raw || asked.is_some_and(|id| id.as_str() == missing)
}
_ => false,
};
if about_argument {
return match deedar::explain_accession(client, raw, "deedar_list", "deedar_get") {
Ok(text) => McpError::invalid_params(text, None),
Err(failed) => bad(failed),
};
}
if matches!(err, deed::Error::NotFound(_)) {
McpError::invalid_params(err.to_string(), None)
} else {
bad(err)
}
}
fn resolve_arg(client: &mut Client, raw: &str) -> Result<deed::DeedId, McpError> {
match client.resolve(raw) {
Ok(id) => Ok(id),
Err(e) => Err(tool_failure(client, raw, None, e)),
}
}
#[tool_router]
impl DeedarServer {
pub fn from_env() -> anyhow::Result<Self> {
if let Some(url) = std::env::var("DEEDAR_URL").ok().filter(|u| !u.is_empty()) {
return Ok(Self { url, seat: None });
}
let dir = deedar::default_store().ok_or_else(|| {
anyhow::anyhow!("DEEDAR_URL is unset and so are XDG_DATA_HOME and HOME")
})?;
Ok(Self {
url: format!("file://{}", dir.display()),
seat: Some(dir),
})
}
#[cfg(test)]
#[must_use]
pub fn at(url: impl Into<String>) -> Self {
Self {
url: url.into(),
seat: None,
}
}
fn open(&self, access: Access) -> Result<(Client, Option<String>), McpError> {
let create = match &self.seat {
Some(dir) if !dir.is_dir() => {
if matches!(access, Access::Write) && !dir.exists() {
Some(dir.clone())
} else {
return Err(missing_seat(dir));
}
}
_ => None,
};
let client = Client::open(&self.url).map_err(bad)?;
let created = create.map(|dir| {
let line = format!("deedar: created the store at {}", dir.display());
eprintln!("{line}");
let _ = std::io::stderr().flush();
line
});
Ok((client, created))
}
#[tool(
description = "One deed by accession, or by a `sha256:` of the deed or of one of its product paths. A deed is frozen: what this returns for an accession does not change.",
annotations(title = "Read a deed", read_only_hint = true, open_world_hint = false)
)]
async fn deedar_get(
&self,
Parameters(args): Parameters<IdArgs>,
) -> Result<Json<DeedRow>, McpError> {
let (mut client, _) = self.open(Access::Read)?;
let id = resolve_arg(&mut client, &args.id)?;
let deed = match client.get(&id) {
Ok(deed) => deed,
Err(e) => return Err(tool_failure(&mut client, &args.id, Some(&id), e)),
};
Ok(Json(row(&deed)))
}
#[tool(
description = "Deeds the store serves, in accession order. kind and agent match exactly; text is a case-insensitive substring of the name or of a body's excerpt, title, subject, step text or url. Omit every argument for the whole shelf.",
annotations(title = "List deeds", read_only_hint = true, open_world_hint = false)
)]
async fn deedar_list(
&self,
Parameters(args): Parameters<ListArgs>,
) -> Result<Json<Vec<DeedRow>>, McpError> {
let (mut client, _) = self.open(Access::Read)?;
let kind = match args.kind.as_deref() {
Some(raw) => Some(deed::Kind::parse(raw).map_err(bad)?),
None => None,
};
let rows = client
.find(&deedar::Filter {
kind,
agent: args.agent,
text: args.text,
})
.map_err(bad)?;
Ok(Json(rows.iter().map(row).collect()))
}
#[tool(
description = "The deed and every input it was made from: its sources that are deeds, and theirs, walked back to the leaves. Use this to see what a product stands on. Whether a citation is still the tip is deedar_current's question, not this one's.",
annotations(
title = "Follow the sources",
read_only_hint = true,
open_world_hint = false
)
)]
async fn deedar_trail(
&self,
Parameters(args): Parameters<IdArgs>,
) -> Result<Json<Vec<DeedRow>>, McpError> {
let (mut client, _) = self.open(Access::Read)?;
let id = resolve_arg(&mut client, &args.id)?;
let rows = match client.trail(&id) {
Ok(rows) => rows,
Err(e) => return Err(tool_failure(&mut client, &args.id, Some(&id), e)),
};
Ok(Json(rows.iter().map(row).collect()))
}
#[tool(
description = "The deed that supersedes this one, or this one when nothing does. A fork or a cycle is every current deed in accession order, with a note of which, and the call succeeds. A citation that is not the tip is stale, and this is how a caller finds out without reading the chain.",
annotations(
title = "The current deed",
read_only_hint = true,
open_world_hint = false
)
)]
async fn deedar_current(
&self,
Parameters(args): Parameters<IdArgs>,
) -> Result<Json<CurrentResult>, McpError> {
let (mut client, _) = self.open(Access::Read)?;
let id = resolve_arg(&mut client, &args.id)?;
let answer = match client.current_walk(&id).map_err(bad)? {
Walk::Tip(tip) => {
let deed = match client.get(&tip) {
Ok(deed) => deed,
Err(e) => return Err(tool_failure(&mut client, &args.id, Some(&id), e)),
};
CurrentResult::One(row(&deed))
}
Walk::Fork(ids) => CurrentResult::Many(CurrentTips {
deeds: rows_for(&mut client, &ids)?,
note: CurrentNote::Fork,
}),
Walk::Cycle(ids) => CurrentResult::Many(CurrentTips {
deeds: rows_for(&mut client, &ids)?,
note: CurrentNote::Cycle,
}),
};
Ok(Json(answer))
}
#[tool(
description = "Whether the store still holds evidence for a deed, and what it says: who produced it and when.",
annotations(
title = "Evidence for a deed",
read_only_hint = true,
open_world_hint = false
)
)]
async fn deedar_evidence(
&self,
Parameters(args): Parameters<IdArgs>,
) -> Result<CallToolResult, McpError> {
let (mut client, _) = self.open(Access::Read)?;
let id = resolve_arg(&mut client, &args.id)?;
let ev = match client.evidence(&id) {
Ok(ev) => ev,
Err(e) => return Err(tool_failure(&mut client, &args.id, Some(&id), e)),
};
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"id={} producedBy={} {} time={}\n",
ev.deed_id,
ev.produced_by.agent_id,
ev.produced_by.activity_id.as_deref().unwrap_or("-"),
ev.unix_time
))]))
}
#[tool(
description = "The append-only log's head: how many deeds it covers and the Merkle root over them. Keep this between visits; a later head that does not extend it means the store rewrote what it already published.",
annotations(title = "The log head", read_only_hint = true, open_world_hint = false)
)]
async fn deedar_log_head(&self) -> Result<Json<HeadRow>, McpError> {
let (client, _) = self.open(Access::Read)?;
let head = client.log_head().map_err(bad)?;
Ok(Json(HeadRow {
size: head.size,
root: head.root,
}))
}
#[tool(
description = "Whether the store answers for what it logged, and logged what it serves. A deed that is logged and no longer served is the tampering the log exists to catch; a deed served and never logged is a store behind its log, which backfilling settles.",
annotations(
title = "Audit the log",
read_only_hint = true,
open_world_hint = false
)
)]
async fn deedar_log_audit(&self) -> Result<Json<AuditRow>, McpError> {
let (client, _) = self.open(Access::Read)?;
let audit = client.log_audit().map_err(bad)?;
Ok(Json(AuditRow {
clean: audit.is_clean(),
logged: audit.logged,
missing: audit
.missing
.iter()
.map(|m| format!("{}: {}", m.id, m.why))
.collect(),
unlogged: audit.unlogged.clone(),
backfill_settles_it: audit.backfill_settles_it(),
}))
}
#[tool(
description = "Write deeds into a directory with the proof they were logged here first, which is what a handover carries. Takes the accessions a satchel names.",
annotations(
title = "Export deeds",
read_only_hint = false,
destructive_hint = false,
idempotent_hint = true,
open_world_hint = false
)
)]
async fn deedar_export(
&self,
Parameters(args): Parameters<ExportArgs>,
) -> Result<CallToolResult, McpError> {
let (mut client, created) = self.open(Access::Write)?;
let into = PathBuf::from(&args.into);
let resolved: Vec<(String, deed::Result<deed::DeedId>)> = args
.accessions
.iter()
.map(|raw| (raw.clone(), client.resolve(raw)))
.collect();
let exporter = client
.exporter()
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
let mut wrote = 0usize;
let mut refused = Vec::new();
for (raw, id) in resolved {
match id.and_then(|id| exporter.export(&id, &into)) {
Ok(files) => wrote += files.len(),
Err(e) => refused.push(format!("{raw}: {e}")),
}
}
if refused.is_empty() {
let mut text = String::new();
if let Some(line) = created {
text.push_str(&line);
text.push('\n');
}
text.push_str(&format!(
"exported {} deeds, {wrote} files\n",
args.accessions.len()
));
return Ok(CallToolResult::success(vec![ContentBlock::text(text)]));
}
Err(McpError::internal_error(refused.join("\n"), None))
}
#[tool(
description = "Check deeds somebody else handed over: that each one's bytes match the digest its log entry recorded, and that its path reaches the head the bag names. Needs no store, because a receiver holds a bag and no log. Answers with the head to record for next time; pass that back as a bridge file in `since` to also check the sender's log only grew.",
annotations(
title = "Check a handover",
read_only_hint = true,
open_world_hint = false
)
)]
async fn deedar_check(
&self,
Parameters(args): Parameters<CheckArgs>,
) -> Result<Json<HandoverRow>, McpError> {
let mut bridged_from = None;
if let Some(path) = &args.since {
let text = std::fs::read_to_string(path)
.map_err(|_| McpError::invalid_params(format!("no bridge at {path}"), None))?;
let bridge = deedar::Bridge::parse(&text)
.map_err(|e| McpError::invalid_params(e.to_string(), None))?;
bridge
.check()
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
bridged_from = Some(bridge.from.size);
}
let accept = deedar::store_dir(&self.url)
.ok()
.and_then(|dir| deedar::Policy::read(&dir).ok())
.map(|policy| policy.signers)
.unwrap_or_default();
let done = deedar::check_handover(&PathBuf::from(&args.dir), &accept)
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
Ok(Json(HandoverRow {
proven: done.proven,
head: done.head.map(|head| HeadRow {
size: head.size,
root: head.root,
}),
head_signer: done.head_signer.map(|signer| deedar::log::hex(&signer)),
head_accepted: done.head_accepted,
bridged_from,
}))
}
#[tool(
description = "The record joining a head a reader already holds to this log's own, so they can tell a log that grew from one that was rewritten. Give it the size the reader recorded from an earlier handover.",
annotations(
title = "Bridge to an earlier head",
read_only_hint = true,
open_world_hint = false
)
)]
async fn deedar_log_bridge(
&self,
Parameters(args): Parameters<BridgeArgs>,
) -> Result<CallToolResult, McpError> {
let (client, _) = self.open(Access::Read)?;
let bridge = client
.bridge(args.from)
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
Ok(CallToolResult::success(vec![ContentBlock::text(
bridge.render(),
)]))
}
}
#[tool_handler]
#[prompt_handler(router = Self::prompt_router())]
impl ServerHandler for DeedarServer {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_tools()
.enable_resources()
.enable_prompts()
.build(),
)
.with_server_info(Implementation::new("deedar", env!("CARGO_PKG_VERSION")))
.with_instructions(
"A deed is what a unit of work produced, frozen, and its accession is the \
identifier that crosses the tracker, the pack and this store. Read one at \
deed://<accession>. Ask whether a citation is still the tip with the current \
verb rather than assuming. Ask whether the store still answers for what it \
published with the audit, which is a different question from whether a deed \
reads.",
)
}
async fn list_resource_templates(
&self,
_request: Option<PaginatedRequestParams>,
_context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<ListResourceTemplatesResult, McpError> {
let mut template =
ResourceTemplate::new(format!("{SCHEME}://{{accession}}"), "deed".to_string());
template.title = Some("One deed".to_string());
template.description =
Some("A deed by accession, rendered as the store prints it.".to_string());
template.mime_type = Some(TEXT.to_string());
Ok(ListResourceTemplatesResult::with_all_items(vec![template])
.with_ttl_ms(RESOURCE_TTL_MS)
.with_cache_scope(CacheScope::Private))
}
async fn read_resource(
&self,
request: ReadResourceRequestParams,
_context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<ReadResourceResponse, McpError> {
let uri = request.uri.clone();
let accession = uri
.strip_prefix(&format!("{SCHEME}://"))
.filter(|rest| !rest.is_empty())
.ok_or_else(|| {
McpError::resource_not_found(format!("not a {SCHEME} uri: {uri}"), None)
})?;
let (mut client, _) = self.open(Access::Read)?;
let id = client
.resolve(accession)
.map_err(|e| McpError::resource_not_found(format!("{e}"), None))?;
let deed = client
.get(&id)
.map_err(|e| McpError::resource_not_found(format!("{e}"), None))?;
let text = serde_json::to_string_pretty(&row(&deed)).map_err(bad)?;
Ok(
ReadResourceResult::new(vec![ResourceContents::TextResourceContents {
uri,
mime_type: Some(TEXT.to_string()),
text,
meta: None,
}])
.with_ttl_ms(RESOURCE_TTL_MS)
.with_cache_scope(CacheScope::Private)
.into(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use deed::{Body, DeedId};
use deedar::CreateRequest;
use std::time::{SystemTime, UNIX_EPOCH};
fn store() -> String {
static NTH: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let n = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("time")
.as_nanos();
let nth = NTH.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("deedar-mcp-{}-{n}-{nth}", std::process::id()));
std::fs::create_dir_all(&dir).expect("mkdir");
format!("file://{}", dir.display())
}
fn quote(url: &str, id: &str, excerpt: &str) {
let mut client = Client::open(url).expect("open");
client
.create(CreateRequest {
id: Some(DeedId::parse(id).expect("id")),
name: id.into(),
sources: Vec::new(),
agent_id: "reader".into(),
activity_id: None,
grants: Vec::new(),
body: Body::Quote {
edition: "https://example.invalid/a".into(),
start: 0,
end: excerpt.len() as u64,
excerpt: excerpt.into(),
urls: vec!["https://example.invalid/a".into()],
},
supersedes: None,
})
.expect("create");
}
#[test]
fn the_surface_is_reads_and_one_export() {
let tools = DeedarServer::tool_router().list_all();
assert!(tools.len() >= 7, "{} tools", tools.len());
let mut writers = Vec::new();
for tool in &tools {
let hints = tool
.annotations
.as_ref()
.unwrap_or_else(|| panic!("{} carries no annotations", tool.name));
assert_eq!(
hints.open_world_hint,
Some(false),
"{} claims an open world",
tool.name
);
match hints.read_only_hint {
Some(true) => {}
Some(false) => {
writers.push(tool.name.to_string());
assert!(hints.destructive_hint.is_some(), "{}", tool.name);
assert!(hints.idempotent_hint.is_some(), "{}", tool.name);
}
None => panic!("{} does not say whether it writes", tool.name),
}
}
assert_eq!(writers, vec!["deedar_export".to_string()], "{writers:?}");
}
#[tokio::test]
async fn a_deed_reads_back_flattened() {
let url = store();
quote(&url, "deed-quote-one", "what was said");
let server = DeedarServer::at(&url);
let got = server
.deedar_get(Parameters(IdArgs {
id: "deed-quote-one".into(),
}))
.await
.expect("reads");
assert_eq!(got.0.id, "deed-quote-one");
assert_eq!(got.0.kind, "quote");
assert!(got.0.digest.starts_with("sha256:"), "{}", got.0.digest);
let by_digest = server
.deedar_get(Parameters(IdArgs {
id: got.0.digest.clone(),
}))
.await
.expect("reads by digest");
assert_eq!(by_digest.0.id, got.0.id);
}
#[tokio::test]
async fn the_audit_tells_a_clean_store_from_one_behind_its_log() {
let url = store();
quote(&url, "deed-quote-two", "logged as it was written");
let server = DeedarServer::at(&url);
let clean = server.deedar_log_audit().await.expect("audits");
assert!(clean.0.clean, "{:?}", clean.0);
assert_eq!(clean.0.logged, 1);
let dir = deedar::store_dir(&url).expect("dir");
std::fs::remove_file(dir.join("log")).expect("remove");
let behind = server.deedar_log_audit().await.expect("audits");
assert!(!behind.0.clean, "{:?}", behind.0);
assert!(behind.0.missing.is_empty(), "{:?}", behind.0);
assert_eq!(behind.0.unlogged.len(), 1, "{:?}", behind.0);
assert!(behind.0.backfill_settles_it, "{:?}", behind.0);
}
}