~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

Every method as an MCP tool and a CLI command, from its lexicon

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:commands
.knotless/workflows/gates.yml+2−2
@@ -19,6 +19,6 @@ steps:
- name: test
run: cargo test
- name: build
run: cargo build --release -p pds-server
run: cargo build --release -p pds
- name: harness
run: cd harness && PATH=/opt/node/bin:$PATH node gates.mjs compare
run: cd harness && PATH=/opt/node/bin:$PATH node gates.mjs compare commands
.knotless/review.md+3−2
@@ -1,7 +1,8 @@
This repository builds a PDS from specifications: agents build `crates/` from `spec/`, and `harness/` checks it against the reference PDS. Check that:
- Every change in behaviour is in `spec/` (`SLICE.md` or a lexicon) as well as in the code, and the README says what is built, not how it came to be built.
- Every change in behaviour is in `spec/` (`SLICE.md`, `COMMANDS.md` or a lexicon) as well as in the code, and the README says what is built, not how it came to be built.
- A harness change makes a check stricter or fixes it, and never loosens one so that a server passes. A new check says what it compares, and with what.
- Server code takes nothing from the reference PDS's or an SDK's source, and adds no atproto crates.
- Server code takes nothing from the reference PDS's or an SDK's source, and adds no atproto or MCP crates.
- Each conformance check excused in `harness/conformance.yaml` gives a reason that the suite's source supports.
Leave out formatting.
crates/pds/src/main.rsnew+20−0
@@ -0,0 +1,20 @@
//! `pds`: `pds serve` runs the server; anything else is the CLI, calling a running one.
const SERVE_HELP: &str = "Usage: pds serve\n\n\
Run the server, configured by its environment: PDS_PORT, PDS_DID, PDS_HANDLE,\n\
PDS_PASSWORD, PDS_SIGNING_KEY_HEX and PDS_DATA_DIR.\n";
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.first().map(String::as_str) != Some("serve") {
std::process::exit(pds_cli::run(&args));
}
match args.get(1).map(String::as_str) {
None => pds_server::run(),
Some("--help" | "-h") => print!("{SERVE_HELP}"),
Some(a) => {
eprint!("pds: pds serve takes no argument {a:?}\n\n{SERVE_HELP}");
std::process::exit(2);
}
}
}
crates/pds/Cargo.tomlnew+9−0
@@ -0,0 +1,9 @@
[package]
name = "pds"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
pds-cli.workspace = true
pds-server.workspace = true
crates/pds-cli/src/lib.rsnew+365−0
@@ -0,0 +1,365 @@
//! The CLI: each method the server serves as a command, `pds <group> <command>
//! [flags]`, calling the server at `PDS_URL` over XRPC (`spec/COMMANDS.md`).
//!
//! Exit statuses: 0 for the method's answer, 1 for an error it answers, 2 for
//! a usage error (no call made), 3 for a server that cannot be reached.
use pds_lexicon::{Arg, JSON, Kind, Method, Type};
use serde_json::{Map, Value as Json, json};
use std::io::{Read, Write};
const USAGE: u8 = 2;
const UNREACHABLE: u8 = 3;
/// Why a command stopped short of its method's answer.
enum Stop {
/// A usage error, saying what was wrong.
Usage(String),
/// The server could not be reached, and why.
Unreachable(String),
}
/// Run the CLI with its arguments (without the program's name); answers its exit status.
pub fn run(args: &[String]) -> i32 {
let code = match command(args) {
Ok(code) => code,
Err(Stop::Usage(why)) => {
eprintln!("pds: {why}");
USAGE
}
Err(Stop::Unreachable(why)) => {
eprintln!("pds: {why}");
UNREACHABLE
}
};
i32::from(code)
}
fn is_help(a: &str) -> bool {
a == "--help" || a == "-h"
}
fn usage<T>(why: impl Into<String>) -> Result<T, Stop> {
Err(Stop::Usage(why.into()))
}
fn command(args: &[String]) -> Result<u8, Stop> {
let Some(group) = args.first() else {
print!("{}", top_help());
return Ok(0);
};
if is_help(group) {
print!("{}", top_help());
return Ok(0);
}
if !pds_lexicon::groups().contains(&group.as_str()) {
return usage(format!("no group {group}; `pds --help` lists them"));
}
let Some(name) = args.get(1) else { return usage(format!("pds {group} needs a command\n\n{}", group_help(group))) };
if is_help(name) {
print!("{}", group_help(group));
return Ok(0);
}
let Some(m) = pds_lexicon::by_command(group, name) else {
return usage(format!("pds {group} has no command {name}; `pds {group} --help` lists them"));
};
let Some(args) = parse(m, &args[2..])? else {
print!("{}", command_help(m));
return Ok(0);
};
call(m, args)
}
fn top_help() -> String {
let mut out = String::from(
"pds: an atproto PDS, and a command for each of its methods.\n\n\
Usage:\n \
pds serve run the server, configured by its environment\n \
pds <group> <command> [flags] call a method of the server at PDS_URL, with the token PDS_TOKEN if set\n \
pds <group> --help list a group's commands\n \
pds <group> <command> --help list a command's flags\n\n\
Groups:\n",
);
for g in pds_lexicon::groups() {
out.push_str(&format!(" {g}\n"));
for (name, m) in commands(g) {
out.push_str(&format!(" {name:<20} {}\n", m.description.as_deref().unwrap_or("")));
}
}
out
}
fn commands(group: &str) -> Vec<(String, &'static Method)> {
pds_lexicon::methods().iter().filter(|m| m.group == group).filter_map(|m| Some((m.command()?, m))).collect()
}
fn group_help(group: &str) -> String {
let mut out = format!("Usage: pds {group} <command> [flags]\n\nCommands:\n");
for (name, m) in commands(group) {
out.push_str(&format!(" {name:<20} {}\n", m.description.as_deref().unwrap_or("")));
}
out
}
fn command_help(m: &Method) -> String {
let mut out = format!("Usage: pds {} {} [flags]\n", m.group, m.command().unwrap_or_default());
if let Some(d) = &m.description {
out.push_str(&format!("\n{d}\n"));
}
if m.args.is_empty() {
out.push_str("\nIt takes no flags.\n");
return out;
}
out.push_str("\nFlags:\n");
for a in &m.args {
let flag = format!("--{} {}", a.flag(), a.ty.placeholder());
let mut about = String::new();
if a.needed() {
about.push_str("(required) ");
}
about.push_str(a.description.as_deref().unwrap_or(""));
if a.names_account() {
about.push_str(if about.is_empty() { "Left out, the account's DID." } else { " Left out, the account's DID." });
}
out.push_str(&format!(" {flag:<32} {}\n", about.trim_end()));
}
out.push_str("\nA <json> flag takes JSON; given `-`, it reads the JSON from standard input.\n");
out
}
/// A command's flags as its method's arguments, or None if they ask for help.
fn parse(m: &Method, flags: &[String]) -> Result<Option<Map<String, Json>>, Stop> {
let mut values = Map::new();
let mut stdin_read = false;
let mut i = 0;
while i < flags.len() {
let a = &flags[i];
i += 1;
if is_help(a) {
return Ok(None);
}
let Some(flag) = a.strip_prefix("--") else { return usage(format!("unexpected argument {a:?}: flags are --name value")) };
let (name, inline) = match flag.split_once('=') {
Some((n, v)) => (n, Some(v.to_string())),
None => (flag, None),
};
let Some(arg) = m.args.iter().find(|x| x.flag() == name) else {
return usage(format!("pds {} {} takes no flag --{name}", m.group, m.command().unwrap_or_default()));
};
if values.contains_key(&arg.name) {
return usage(format!("--{name} is given twice"));
}
let text = match inline {
Some(v) => Some(v),
None if arg.ty == Type::Boolean => match flags.get(i).map(String::as_str) {
Some(v @ ("true" | "false")) => {
i += 1;
Some(v.to_string())
}
_ => None,
},
None => match flags.get(i) {
Some(v) => {
i += 1;
Some(v.clone())
}
None => return usage(format!("--{name} needs a value")),
},
};
let value = value(arg, text, &mut stdin_read)?;
values.insert(arg.name.clone(), value);
}
let missing: Vec<String> = m.args.iter().filter(|a| a.needed() && !values.contains_key(&a.name)).map(|a| format!("--{}", a.flag())).collect();
if !missing.is_empty() {
return usage(format!("pds {} {} needs {}", m.group, m.command().unwrap_or_default(), missing.join(", ")));
}
Ok(Some(values))
}
/// A flag's value, from its text (None for a bare boolean flag).
fn value(arg: &Arg, text: Option<String>, stdin_read: &mut bool) -> Result<Json, Stop> {
let flag = arg.flag();
let Some(text) = text else { return Ok(Json::Bool(true)) };
match arg.ty {
Type::String => Ok(Json::String(text)),
Type::Integer => match text.parse::<i64>() {
Ok(n) if text.trim_start_matches('-').bytes().all(|b| b.is_ascii_digit()) => Ok(json!(n)),
_ => usage(format!("--{flag} takes an integer, not {text:?}")),
},
Type::Boolean => match text.as_str() {
"true" => Ok(Json::Bool(true)),
"false" => Ok(Json::Bool(false)),
_ => usage(format!("--{flag} takes true or false, not {text:?}")),
},
Type::Array | Type::Object | Type::Unknown => {
let text = if text == "-" {
if *stdin_read {
return usage("only one flag can read standard input");
}
*stdin_read = true;
let mut s = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut s) {
return usage(format!("--{flag}: cannot read standard input: {e}"));
}
s
} else {
text
};
match serde_json::from_str::<Json>(&text) {
Ok(Json::Null) => usage(format!("--{flag} cannot be null")),
Ok(v) => Ok(v),
Err(e) => usage(format!("--{flag} takes JSON: {e}")),
}
}
}
}
/// A query parameter's text, as XRPC takes it.
fn param_text(v: &Json) -> String {
match v {
Json::String(s) => s.clone(),
other => other.to_string(),
}
}
struct Server {
url: String,
token: Option<String>,
http: reqwest::blocking::Client,
}
impl Server {
fn send(&self, nsid: &str, kind: Kind, args: &Map<String, Json>) -> Result<reqwest::blocking::Response, Stop> {
let url = format!("{}/xrpc/{nsid}", self.url);
let mut req = match kind {
Kind::Procedure => self.http.post(&url).header("content-type", JSON).body(Json::Object(args.clone()).to_string()),
_ => {
let mut params = Vec::new();
for (k, v) in args {
match v {
Json::Array(items) => params.extend(items.iter().map(|i| (k.as_str(), param_text(i)))),
v => params.push((k.as_str(), param_text(v))),
}
}
self.http.get(&url).query(&params)
}
};
if let Some(t) = &self.token {
req = req.bearer_auth(t);
}
req.send().map_err(|e| Stop::Unreachable(format!("cannot reach {}: {e}", self.url)))
}
/// The account's DID: the token's, else the one the server describes itself with.
fn account(&self) -> Result<Result<String, (u16, Json)>, Stop> {
if self.token.is_some() {
let (status, body) = answer(self.send("com.atproto.server.getSession", Kind::Query, &Map::new())?, &self.url)?;
if let (200, Some(did)) = (status, body["did"].as_str()) {
return Ok(Ok(did.to_string()));
}
}
let (status, body) = answer(self.send("com.atproto.server.describeServer", Kind::Query, &Map::new())?, &self.url)?;
match (status, body["did"].as_str()) {
(200, Some(did)) => Ok(Ok(did.to_string())),
_ => Ok(Err((status, body))),
}
}
}
/// A JSON answer's status and body.
fn answer(res: reqwest::blocking::Response, url: &str) -> Result<(u16, Json), Stop> {
let status = res.status().as_u16();
let bytes = res.bytes().map_err(|e| Stop::Unreachable(format!("cannot read the answer of {url}: {e}")))?;
Ok((status, serde_json::from_slice(&bytes).unwrap_or_else(|_| Json::String(String::from_utf8_lossy(&bytes).into_owned()))))
}
fn print_line(v: &Json) {
let mut out = std::io::stdout().lock();
let _ = writeln!(out, "{v}");
}
/// Print an error the server answered, as `{status, error, message}`.
fn print_error(status: u16, body: &Json) -> u8 {
let reason = reqwest::StatusCode::from_u16(status).ok().and_then(|s| s.canonical_reason()).unwrap_or("Error");
let error = body["error"].as_str().unwrap_or(reason);
let message = match (&body["message"], body) {
(Json::String(m), _) => m.clone(),
(_, Json::String(text)) => text.clone(),
_ => reason.to_string(),
};
print_line(&json!({ "status": status, "error": error, "message": message }));
1
}
fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> {
let Ok(url) = std::env::var("PDS_URL") else { return Err(Stop::Unreachable("PDS_URL is not set: it is the server's URL".into())) };
let http = reqwest::blocking::Client::builder().no_proxy().build().map_err(|e| Stop::Unreachable(e.to_string()))?;
let server = Server { url: url.trim_end_matches('/').to_string(), token: std::env::var("PDS_TOKEN").ok().filter(|t| !t.is_empty()), http };
if m.args.iter().any(|a| a.names_account() && !args.contains_key(&a.name)) {
let did = match server.account()? {
Ok(did) => did,
Err((status, body)) => return Ok(print_error(status, &body)),
};
for a in m.args.iter().filter(|a| a.names_account()) {
args.entry(a.name.clone()).or_insert_with(|| json!(did));
}
}
let res = server.send(&m.nsid, m.kind, &args)?;
if !res.status().is_success() || m.output.as_deref() == Some(JSON) {
let (status, body) = answer(res, &server.url)?;
if !(200..300).contains(&status) {
return Ok(print_error(status, &body));
}
print_line(&body);
return Ok(0);
}
let bytes = res.bytes().map_err(|e| Stop::Unreachable(format!("cannot read the answer of {}: {e}", server.url)))?;
let mut out = std::io::stdout().lock();
let _ = out.write_all(&bytes);
let _ = out.flush();
Ok(0)
}
#[cfg(test)]
mod tests {
use super::*;
fn flags(nsid: &str, argv: &[&str]) -> Result<Option<Map<String, Json>>, String> {
let argv: Vec<String> = argv.iter().map(|a| a.to_string()).collect();
parse(pds_lexicon::method(nsid).unwrap(), &argv).map_err(|e| match e {
Stop::Usage(why) | Stop::Unreachable(why) => why,
})
}
#[test]
fn flag_values() {
let list = "com.atproto.repo.listRecords";
let got = flags(list, &["--collection", "a.b.c", "--limit", "5", "--reverse"]).unwrap().unwrap();
assert_eq!(Json::Object(got), json!({ "collection": "a.b.c", "limit": 5, "reverse": true }));
let got = flags(list, &["--collection=a.b.c", "--reverse", "false", "--cursor", "--x"]).unwrap().unwrap();
assert_eq!(Json::Object(got), json!({ "collection": "a.b.c", "reverse": false, "cursor": "--x" }));
let put = flags("com.atproto.repo.putRecord", &["--collection", "a.b.c", "--rkey", "-", "--record", r#"{"n":1}"#]).unwrap().unwrap();
assert_eq!(Json::Object(put), json!({ "collection": "a.b.c", "rkey": "-", "record": { "n": 1 } }));
assert_eq!(flags(list, &["--collection", "a.b.c", "--help"]).unwrap(), None);
}
#[test]
fn usage_errors() {
let list = "com.atproto.repo.listRecords";
for argv in [
&["--collection", "a.b.c", "--no-such-flag", "x"][..],
&["--limit", "5"],
&["--collection", "a.b.c", "--limit", "five"],
&["--collection", "a.b.c", "--limit", "1.5"],
&["--collection", "a.b.c", "--reverse=yes"],
&["--collection", "a.b.c", "--collection", "d.e.f"],
&["--collection"],
&["a.b.c"],
] {
assert!(flags(list, argv).is_err(), "{argv:?}");
}
let create = "com.atproto.repo.createRecord";
assert!(flags(create, &["--collection", "a.b.c", "--record", "null"]).is_err());
assert!(flags(create, &["--collection", "a.b.c", "--record", "{"]).is_err());
}
}
crates/pds-cli/Cargo.tomlnew+10−0
@@ -0,0 +1,10 @@
[package]
name = "pds-cli"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
pds-lexicon.workspace = true
reqwest.workspace = true
serde_json.workspace = true
crates/pds-lexicon/src/lib.rsnew+333−0
@@ -0,0 +1,333 @@
//! The methods the server serves, read from their lexicons in `spec/lexicons`,
//! and the MCP tool and CLI command each one is (`spec/COMMANDS.md`).
use serde_json::{Map, Value as Json, json};
use std::sync::LazyLock;
include!(concat!(env!("OUT_DIR"), "/lexicons.rs"));
/// The encoding of a JSON answer.
pub const JSON: &str = "application/json";
/// What kind of method a lexicon defines.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
Query,
Procedure,
Subscription,
}
/// The type of an argument's value: `String`, `Integer` and `Boolean` are
/// written as text on the command line, the rest as JSON.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Type {
String,
Integer,
Boolean,
Array,
/// An `object`, `ref` or `union`, or another type whose JSON is an object.
Object,
Unknown,
}
impl Type {
/// How a command's help names the value of a flag of this type.
pub fn placeholder(self) -> &'static str {
match self {
Type::String => "<string>",
Type::Integer => "<integer>",
Type::Boolean => "[true|false]",
Type::Array | Type::Object | Type::Unknown => "<json>",
}
}
}
/// One argument of a method: a query parameter or an input property.
#[derive(Debug)]
pub struct Arg {
/// As the lexicon names it, and as the method's MCP tool takes it.
pub name: String,
pub ty: Type,
/// Whether the lexicon requires it.
pub required: bool,
pub description: Option<String>,
/// The JSON Schema of its value in the method's MCP tool's `inputSchema`.
pub schema: Json,
}
impl Arg {
/// Whether it names the account, and so may be left out for the account's DID.
pub fn names_account(&self) -> bool {
self.name == "repo" || self.name == "did"
}
/// Whether the method's MCP tool and CLI command require it.
pub fn needed(&self) -> bool {
self.required && !self.names_account()
}
/// Its CLI flag, without the leading `--`.
pub fn flag(&self) -> String {
split_case(&self.name, '-')
}
}
/// One method the server serves.
#[derive(Debug)]
pub struct Method {
pub nsid: String,
/// The NSID's second-to-last segment.
pub group: String,
/// The NSID's last segment, as written.
pub name: String,
pub kind: Kind,
pub description: Option<String>,
/// Its parameters (a query's or a subscription's) or its input's properties
/// (a procedure's), by name.
pub args: Vec<Arg>,
/// The encoding of its answer, if it has one.
pub output: Option<String>,
}
impl Method {
/// Its MCP tool's name, if it has a tool: every method whose answer is JSON.
pub fn tool(&self) -> Option<String> {
(self.kind != Kind::Subscription && self.output.as_deref() == Some(JSON))
.then(|| format!("{}_{}", self.group, split_case(&self.name, '_')))
}
/// Its CLI command's name within its group, if it has one: every method but a subscription.
pub fn command(&self) -> Option<String> {
(self.kind != Kind::Subscription).then(|| split_case(&self.name, '-'))
}
pub fn arg(&self, name: &str) -> Option<&Arg> {
self.args.iter().find(|a| a.name == name)
}
/// Its MCP tool's `inputSchema`.
pub fn input_schema(&self) -> Json {
let properties: Map<String, Json> = self.args.iter().map(|a| (a.name.clone(), a.schema.clone())).collect();
let required: Vec<&str> = self.args.iter().filter(|a| a.needed()).map(|a| a.name.as_str()).collect();
json!({ "type": "object", "properties": properties, "required": required })
}
/// Its MCP tool's annotations: a query only reads; a procedure writes, and
/// destroys if it may delete or replace a record.
pub fn annotations(&self) -> Option<Json> {
match self.kind {
Kind::Query => Some(json!({ "readOnlyHint": true })),
Kind::Procedure => Some(json!({ "readOnlyHint": false, "destructiveHint": DESTRUCTIVE.contains(&self.nsid.as_str()) })),
Kind::Subscription => None,
}
}
}
/// The procedures that may delete or replace a record, as `spec/COMMANDS.md`
/// lists them: their lexicons cannot say so.
const DESTRUCTIVE: &[&str] = &["com.atproto.repo.deleteRecord", "com.atproto.repo.putRecord", "com.atproto.repo.applyWrites"];
/// `createRecord` as `create_record` (with `_`) or `create-record` (with `-`).
pub fn split_case(name: &str, sep: char) -> String {
let mut out = String::with_capacity(name.len() + 4);
for c in name.chars() {
if c.is_ascii_uppercase() {
if !out.is_empty() {
out.push(sep);
}
out.push(c.to_ascii_lowercase());
} else {
out.push(c);
}
}
out
}
/// Every method the server serves, in NSID order.
pub fn methods() -> &'static [Method] {
static METHODS: LazyLock<Vec<Method>> = LazyLock::new(load);
&METHODS
}
/// The method of an NSID.
pub fn method(nsid: &str) -> Option<&'static Method> {
methods().iter().find(|m| m.nsid == nsid)
}
/// The method whose MCP tool has this name.
pub fn by_tool(name: &str) -> Option<&'static Method> {
methods().iter().find(|m| m.tool().as_deref() == Some(name))
}
/// The method of a CLI command.
pub fn by_command(group: &str, command: &str) -> Option<&'static Method> {
methods().iter().find(|m| m.group == group && m.command().as_deref() == Some(command))
}
/// The groups with at least one CLI command, in order.
pub fn groups() -> Vec<&'static str> {
let mut gs: Vec<&str> = methods().iter().filter(|m| m.command().is_some()).map(|m| m.group.as_str()).collect();
gs.sort();
gs.dedup();
gs
}
fn load() -> Vec<Method> {
let mut methods: Vec<Method> =
LEXICONS.iter().filter_map(|t| read_method(&serde_json::from_str(t).expect("lexicon JSON"))).collect();
methods.sort_by(|a, b| a.nsid.cmp(&b.nsid));
for (i, m) in methods.iter().enumerate() {
if methods[..i].iter().any(|o| o.group == m.group && o.name == m.name) {
panic!("two methods are {} {}", m.group, m.name);
}
}
methods
}
fn read_method(doc: &Json) -> Option<Method> {
let nsid = doc["id"].as_str()?.to_string();
let main = &doc["defs"]["main"];
let kind = match main["type"].as_str()? {
"query" => Kind::Query,
"procedure" => Kind::Procedure,
"subscription" => Kind::Subscription,
_ => return None,
};
let mut segments = nsid.rsplit('.');
let name = segments.next()?.to_string();
let group = segments.next()?.to_string();
let object = match kind {
Kind::Procedure => main["input"]["schema"].clone(),
_ => main["parameters"].clone(),
};
let required: Vec<&str> = object["required"].as_array().map(|r| r.iter().filter_map(Json::as_str).collect()).unwrap_or_default();
let args = object["properties"]
.as_object()
.map(|props| {
props
.iter()
.map(|(n, p)| {
let ty = type_of(p);
Arg {
name: n.clone(),
ty,
required: required.contains(&n.as_str()),
description: p["description"].as_str().map(str::to_string),
schema: schema_of(p, ty),
}
})
.collect()
})
.unwrap_or_default();
Some(Method {
nsid,
group,
name,
kind,
description: main["description"].as_str().map(str::to_string),
args,
output: main["output"]["encoding"].as_str().map(str::to_string),
})
}
fn type_of(p: &Json) -> Type {
match p["type"].as_str() {
Some("string") => Type::String,
Some("integer") => Type::Integer,
Some("boolean") => Type::Boolean,
Some("array") => Type::Array,
Some("unknown") => Type::Unknown,
_ => Type::Object,
}
}
fn schema_of(p: &Json, ty: Type) -> Json {
let mut s = Map::new();
match ty {
Type::String => {
s.insert("type".into(), json!("string"));
}
Type::Integer => {
s.insert("type".into(), json!("integer"));
}
Type::Boolean => {
s.insert("type".into(), json!("boolean"));
}
Type::Array => {
s.insert("type".into(), json!("array"));
let items = &p["items"];
if items.is_object() {
s.insert("items".into(), schema_of(items, type_of(items)));
}
}
Type::Object => {
s.insert("type".into(), json!("object"));
}
Type::Unknown => {}
}
if matches!(ty, Type::String | Type::Integer) {
for (from, to) in [("minimum", "minimum"), ("maximum", "maximum"), ("maxLength", "maxLength"), ("enum", "enum")] {
if let Some(v) = p.get(from) {
s.insert(to.into(), v.clone());
}
}
}
if let Some(d) = p["description"].as_str() {
s.insert("description".into(), json!(d));
}
Json::Object(s)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names() {
let m = method("com.atproto.repo.createRecord").unwrap();
assert_eq!((m.group.as_str(), m.name.as_str()), ("repo", "createRecord"));
assert_eq!(m.tool().as_deref(), Some("repo_create_record"));
assert_eq!(m.command().as_deref(), Some("create-record"));
assert_eq!(m.arg("swapCommit").unwrap().flag(), "swap-commit");
assert_eq!(by_command("repo", "create-record").unwrap().nsid, m.nsid);
assert_eq!(by_tool("repo_create_record").unwrap().nsid, m.nsid);
}
#[test]
fn which_methods() {
let get_repo = method("com.atproto.sync.getRepo").unwrap();
assert_eq!((get_repo.tool(), get_repo.command().as_deref()), (None, Some("get-repo")));
let sub = method("com.atproto.sync.subscribeRepos").unwrap();
assert_eq!((sub.tool(), sub.command()), (None, None));
let tools: Vec<String> = methods().iter().filter_map(Method::tool).collect();
assert_eq!(tools.len(), 11, "{tools:?}");
assert_eq!(groups(), ["repo", "server", "sync"]);
assert!(method("com.atproto.repo.defs").is_none());
}
#[test]
fn input_schema() {
let m = method("com.atproto.repo.listRecords").unwrap();
let s = m.input_schema();
assert_eq!(s["required"], json!(["collection"]));
assert_eq!(s["properties"]["limit"]["type"], "integer");
assert_eq!(s["properties"]["limit"]["minimum"], 1);
assert_eq!(s["properties"]["limit"]["maximum"], 100);
assert_eq!(s["properties"]["reverse"]["type"], "boolean");
assert_eq!(m.annotations(), Some(json!({ "readOnlyHint": true })));
let w = method("com.atproto.repo.applyWrites").unwrap().input_schema();
assert_eq!(w["properties"]["writes"]["type"], "array");
assert_eq!(w["properties"]["writes"]["items"]["type"], "object");
let c = method("com.atproto.repo.createRecord").unwrap().input_schema();
assert!(c["properties"]["record"].get("type").is_none());
assert_eq!(c["properties"]["rkey"]["maxLength"], 512);
let hints = |nsid: &str| method(nsid).unwrap().annotations();
for nsid in ["com.atproto.repo.deleteRecord", "com.atproto.repo.putRecord", "com.atproto.repo.applyWrites"] {
assert_eq!(hints(nsid), Some(json!({ "readOnlyHint": false, "destructiveHint": true })), "{nsid}");
}
for nsid in ["com.atproto.repo.createRecord", "com.atproto.server.createSession"] {
assert_eq!(hints(nsid), Some(json!({ "readOnlyHint": false, "destructiveHint": false })), "{nsid}");
}
assert_eq!(hints("com.atproto.sync.subscribeRepos"), None);
}
}
crates/pds-lexicon/build.rsnew+33−0
@@ -0,0 +1,33 @@
//! Embeds every lexicon under `spec/lexicons`, so that the methods the server
//! serves, and their MCP tools and CLI commands, follow the lexicons there.
use std::path::{Path, PathBuf};
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())) {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, out);
} else if path.extension().is_some_and(|e| e == "json") {
out.push(path);
}
}
}
fn main() {
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let root = manifest.join("../../spec/lexicons").canonicalize().expect("spec/lexicons");
println!("cargo:rerun-if-changed={}", root.display());
let mut files = Vec::new();
walk(&root, &mut files);
files.sort();
let mut src = String::from("/// Every lexicon under `spec/lexicons`, as its JSON text, in path order.\npub static LEXICONS: &[&str] = &[\n");
for f in &files {
// Directories are watched by their mtime, which a changed file does not touch.
println!("cargo:rerun-if-changed={}", f.display());
src.push_str(&format!(" include_str!({:?}),\n", f.display().to_string()));
}
src.push_str("];\n");
let out = PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("lexicons.rs");
std::fs::write(out, src).unwrap();
}
crates/pds-lexicon/Cargo.tomlnew+8−0
@@ -0,0 +1,8 @@
[package]
name = "pds-lexicon"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
serde_json.workspace = true
crates/pds-server/src/main.rs → crates/pds-server/src/lib.rsrenamed+21−9
@@ -1,4 +1,7 @@
//! The PDS: XRPC, the firehose, and the MCP endpoint whose tools are its methods.
mod events;
mod mcp;
use axum::{
Router,
@@ -51,18 +54,31 @@ fn token(prefix: &str) -> String {
format!("{prefix}.{}", hex::encode(b))
}
#[tokio::main]
async fn main() {
/// Run the server, configured by the environment as `spec/SLICE.md` says, until it is killed.
pub fn run() {
let var = |n: &str| std::env::var(n).unwrap_or_else(|_| panic!("{n} is not set"));
let key = k256::ecdsa::SigningKey::from_slice(&hex::decode(var("PDS_SIGNING_KEY_HEX")).expect("hex key")).expect("key");
let did = var("PDS_DID");
let port = var("PDS_PORT").parse::<u16>().expect("port");
let server = Server::open(FsPath::new(&var("PDS_DATA_DIR")), did, var("PDS_HANDLE"), var("PDS_PASSWORD"), key);
let app = Router::new()
.route("/xrpc/com.atproto.sync.subscribeRepos", get(events::subscribe))
.route("/xrpc/{nsid}", any(handle))
.route("/mcp", any(mcp::endpoint))
.with_state(Arc::new(Mutex::new(server)));
let listener = tokio::net::TcpListener::bind(("127.0.0.1", var("PDS_PORT").parse::<u16>().expect("port"))).await.unwrap();
axum::serve(listener, app).await.unwrap();
tokio::runtime::Runtime::new().unwrap().block_on(async {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
axum::serve(listener, app).await.unwrap();
});
}
/// The bearer token a request's `Authorization` header carries.
fn bearer(headers: &HeaderMap) -> Option<String> {
headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.map(str::to_string)
}
async fn handle(
@@ -73,11 +89,7 @@ async fn handle(
Query(params): Query<Vec<(String, String)>>,
body: Bytes,
) -> Response {
let bearer = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.map(str::to_string);
let bearer = bearer(&headers);
let result = locked(&st, |s| serve(s, &nsid, &method, &params, &body, bearer)).await;
match result {
Ok(Resp::Json(j)) => (StatusCode::OK, [(header::CONTENT_TYPE, "application/json")], j.to_string()).into_response(),
crates/pds-server/src/mcp.rsnew+295−0
crates/pds-server/Cargo.toml+2−0
harness/compare.mjs+292−5
harness/conformance.mjsnew+71−0
harness/conformance.yamlnew+16−0
harness/gates.mjs+17−9
harness/package-lock.json+1214−2
1216 lines changed: not loaded until asked for.
harness/package.json+3−1
spec/COMMANDS.mdnew+131−0
spec/SLICE.md+5−3
AGENTS.md+6−4
Cargo.lock+854−8
862 lines changed: not loaded until asked for.
Cargo.toml+4−0
Justfile+7−7
README.md+35−6