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

pds xrpc makes any call; MCP tools' titles and hints say what they do

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:cli/xrpc-and-tool-hints
crates/pds-cli/src/lib.rs+30−6
@@ -1,14 +1,17 @@
//! 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`);
//! and the routes no lexicon makes a command of (`OWN`): the admin's reads,
//! the routes no lexicon makes a command of (`OWN`): the admin's reads,
//! `pds admin logs` and `pds admin stats`, calling `/xrpc/_logs` and
//! `/xrpc/_stats`, and the account's OAuth routes, the group `oauth`.
//! `/xrpc/_stats`, and the account's OAuth routes, the group `oauth`; and
//! `pds xrpc`, any call by its name (`xrpc`).
//!
//! 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.
#![forbid(unsafe_code)]
mod xrpc;
use pds_lexicon::{Arg, JSON, Kind, Method, Type};
use serde_json::{Map, Value as Json, json};
use std::io::{Read, Write};
@@ -58,6 +61,9 @@ fn command(args: &[String]) -> Result<u8, Stop> {
print!("{}", top_help());
return Ok(0);
}
if group == xrpc::COMMAND {
return xrpc::run(&args[1..]);
}
if !groups().contains(&group.as_str()) {
return usage(format!("no group {group}; `pds --help` lists them"));
}
@@ -231,7 +237,8 @@ fn top_help() -> String {
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\
pds <group> <command> --help list a command's flags\n \
pds xrpc <kind> <name> [args] call any method or route of the server by its name; `pds xrpc --help` says how\n\n\
Groups:\n",
);
for g in groups() {
@@ -535,13 +542,30 @@ impl Server {
/// Send `req` with the token, or else the admin's `Basic` auth.
fn with_auth(
&self,
mut req: reqwest::blocking::RequestBuilder,
req: reqwest::blocking::RequestBuilder,
) -> Result<reqwest::blocking::Response, Stop> {
self.sent(self.authorized(req))
}
/// `req` with the token, or else the admin's `Basic` auth, if either is set.
fn authorized(
&self,
req: reqwest::blocking::RequestBuilder,
) -> reqwest::blocking::RequestBuilder {
if let Some(t) = &self.token {
req = req.bearer_auth(t);
req.bearer_auth(t)
} else if let Some(password) = &self.admin {
req = req.basic_auth("admin", Some(password));
req.basic_auth("admin", Some(password))
} else {
req
}
}
/// Send `req`, its answer or why the server could not be reached.
fn sent(
&self,
req: reqwest::blocking::RequestBuilder,
) -> Result<reqwest::blocking::Response, Stop> {
req.send()
.map_err(|e| Stop::Unreachable(format!("cannot reach {}: {e}", self.url)))
}
crates/pds-cli/src/xrpc.rsnew+457−0
457 lines changed: not loaded until asked for.
crates/pds-lexicon/src/lib.rs+109−25
@@ -151,29 +151,71 @@ impl Method {
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.
/// Its MCP tool's `title`: its command's name in words, then its group
/// (`spec/COMMANDS.md`, "Names").
pub fn title(&self) -> String {
title(&self.group, &split_case(&self.name, '-'))
}
/// Its MCP tool's annotations, by what it does (`spec/COMMANDS.md`,
/// "Hints"): a query only reads, but for those that sign a token for the
/// account; a procedure writes, and destroys unless it only adds.
pub fn annotations(&self) -> Option<Json> {
let nsid = self.nsid.as_str();
match self.kind {
Kind::Query if SIGNS.contains(&nsid) => {
Some(json!({ "readOnlyHint": false, "destructiveHint": false }))
}
Kind::Query => Some(json!({ "readOnlyHint": true })),
Kind::Procedure => Some(
json!({ "readOnlyHint": false, "destructiveHint": DESTRUCTIVE.contains(&self.nsid.as_str()) }),
),
Kind::Procedure => {
Some(json!({ "readOnlyHint": false, "destructiveHint": !ADDITIVE.contains(&nsid) }))
}
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",
"com.atproto.space.deleteRecord",
"com.atproto.space.putRecord",
"com.atproto.space.applyWrites",
"com.atproto.space.clearRecords",
/// A tool's `title` from its command's group and kebab-case name:
/// `create-record` of `repo` as `Create record (repo)`.
pub fn title(group: &str, command: &str) -> String {
let mut words = command.replace('-', " ");
if let Some(first) = words.get_mut(..1) {
first.make_ascii_uppercase();
}
format!("{words} ({group})")
}
/// The queries that sign a token for the account, and so are no mere reads,
/// as `spec/COMMANDS.md`, "Hints", lists them.
const SIGNS: &[&str] = &[
"com.atproto.server.getServiceAuth",
"com.atproto.space.getDelegationToken",
];
/// The procedures that only add, as `spec/COMMANDS.md`, "Hints", lists
/// them: every other may delete, replace or end something, and so a
/// procedure the server comes to serve is destructive until it is listed.
const ADDITIVE: &[&str] = &[
"com.atproto.server.createAccount",
"com.atproto.server.createSession",
"com.atproto.server.createAppPassword",
"com.atproto.server.createInviteCode",
"com.atproto.server.createInviteCodes",
"com.atproto.server.requestEmailConfirmation",
"com.atproto.server.confirmEmail",
"com.atproto.server.requestEmailUpdate",
"com.atproto.server.requestPasswordReset",
"com.atproto.server.requestAccountDelete",
"com.atproto.server.activateAccount",
"com.atproto.identity.requestPlcOperationSignature",
"com.atproto.identity.signPlcOperation",
"com.atproto.repo.createRecord",
"app.bsky.notification.registerPush",
"com.atproto.space.createSpace",
"com.atproto.space.createRecord",
"com.atproto.space.getSpaceCredential",
"com.atproto.space.notifyWrite",
"com.atproto.space.registerNotify",
];
/// `createRecord` as `create_record` (with `_`) or `create-record` (with `-`).
@@ -248,6 +290,10 @@ fn load() -> Vec<Method> {
{
panic!("two methods are {} {}", m.group, m.name);
}
// `pds xrpc` is the CLI's own command (`spec/COMMANDS.md`, "Names").
if m.group == "xrpc" {
panic!("{} is of the group xrpc", m.nsid);
}
}
methods
}
@@ -978,34 +1024,72 @@ mod tests {
let create = method("com.atproto.server.createAccount").unwrap();
assert!(!create.arg("did").unwrap().names_account());
assert_eq!(create.input_schema()["required"], json!(["handle"]));
}
/// Hints by what a method does (`spec/COMMANDS.md`, "Hints"): a query
/// reads but for the two that sign a token; a procedure destroys
/// unless it is listed as only adding.
#[test]
fn hints() {
let hints = |nsid: &str| method(nsid).unwrap().annotations();
let destroys = Some(json!({ "readOnlyHint": false, "destructiveHint": true }));
let adds = Some(json!({ "readOnlyHint": false, "destructiveHint": false }));
for nsid in [
"com.atproto.repo.deleteRecord",
"com.atproto.repo.putRecord",
"com.atproto.repo.applyWrites",
"com.atproto.space.deleteRecord",
"com.atproto.space.putRecord",
"com.atproto.space.applyWrites",
"com.atproto.space.clearRecords",
"com.atproto.memberspace.putMember",
"com.atproto.server.deleteSession",
"com.atproto.identity.updateHandle",
"app.bsky.actor.putPreferences",
] {
assert_eq!(
hints(nsid),
Some(json!({ "readOnlyHint": false, "destructiveHint": true })),
"{nsid}"
);
assert_eq!(hints(nsid), destroys, "{nsid}");
}
for nsid in [
"com.atproto.repo.createRecord",
"com.atproto.server.createSession",
"com.atproto.space.createRecord",
"com.atproto.server.getServiceAuth",
"com.atproto.space.getDelegationToken",
] {
assert_eq!(hints(nsid), adds, "{nsid}");
}
assert_eq!(
hints("com.atproto.repo.listRecords"),
Some(json!({ "readOnlyHint": true }))
);
assert_eq!(hints("com.atproto.sync.subscribeRepos"), None);
// Each listed is a method served, of the kind its list is for.
for nsid in ADDITIVE {
assert_eq!(
hints(nsid),
Some(json!({ "readOnlyHint": false, "destructiveHint": false })),
method(nsid).map(|m| m.kind),
Some(Kind::Procedure),
"{nsid}"
);
}
assert_eq!(hints("com.atproto.sync.subscribeRepos"), None);
for nsid in SIGNS {
assert_eq!(method(nsid).map(|m| m.kind), Some(Kind::Query), "{nsid}");
}
}
/// A tool's title is its command's name in words, then its group
/// (`spec/COMMANDS.md`, "Names"); no group is `xrpc`.
#[test]
fn titles() {
let title_of = |nsid: &str| method(nsid).unwrap().title();
assert_eq!(
title_of("com.atproto.identity.getRecommendedDidCredentials"),
"Get recommended did credentials (identity)"
);
assert_eq!(
title_of("com.atproto.repo.createRecord"),
"Create record (repo)"
);
assert_eq!(title("admin", "logs"), "Logs (admin)");
assert_eq!(title("oauth", "revoke-session"), "Revoke session (oauth)");
assert!(!groups().contains(&"xrpc"));
}
#[test]
crates/pds-server/src/oauth/account.rs+3−0
@@ -116,8 +116,11 @@ impl Route {
json!({ "readOnlyHint": false, "destructiveHint": true }),
)
};
// Its command's name, as `revoke-session` of `oauth_revoke_session`.
let command = r.tool()["oauth_".len()..].replace('_', "-");
json!({
"name": r.tool(),
"title": pds_lexicon::title("oauth", &command),
"description": r.description(),
"inputSchema": schema,
"annotations": annotations,
crates/pds-server/src/ops/admin.rs+2−0
@@ -49,6 +49,7 @@ impl Read {
[
json!({
"name": "admin_logs",
"title": pds_lexicon::title("admin", "logs"),
"description": "As the admin, the lines the server logged and kept in PDS_LOG_DIR, oldest first: the last of those of a trace, a message, a route, a level and above, or a time. Needs the admin's Basic auth.",
"inputSchema": {
"type": "object",
@@ -66,6 +67,7 @@ impl Read {
}),
json!({
"name": "admin_stats",
"title": pds_lexicon::title("admin", "stats"),
"description": "As the admin, what the server counted since it started: its requests by route and status with their mean times, the requests it made, its syncs, its accounts and its firehose. Needs the admin's Basic auth.",
"inputSchema": { "type": "object", "properties": {}, "required": [] },
"annotations": { "readOnlyHint": true },
crates/pds-server/src/space_credentials/tests.rs+11−3
@@ -1702,20 +1702,28 @@ async fn credentials_are_refused_for_an_authority_not_active() {
#[test]
fn the_methods_are_tools() {
for (nsid, tool) in [
// Hints by what each does (`spec/COMMANDS.md`, "Hints"): the delegation
// token is signed, the credential only added, and a revocation ends one.
for (nsid, tool, destroys) in [
(
"com.atproto.space.getDelegationToken",
"space_get_delegation_token",
false,
),
(
"com.atproto.space.getSpaceCredential",
"space_get_space_credential",
false,
),
(NOTIFY, "space_notify_credential_revoked"),
(NOTIFY, "space_notify_credential_revoked", true),
] {
let m = pds_lexicon::method(nsid).unwrap();
assert_eq!(m.tool().as_deref(), Some(tool));
assert_ne!(m.annotations().unwrap()["destructiveHint"], json!(true));
assert_eq!(
m.annotations(),
Some(json!({ "readOnlyHint": false, "destructiveHint": destroys })),
"{nsid}"
);
assert!(handler(nsid).is_some());
}
}
crates/pds-server/src/space_notify/tests.rs+14−11
@@ -1809,22 +1809,25 @@ async fn service_auth_pays_before_fetching() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The four methods are tools, none destructive.
/// The four methods are tools: a read, two that only add, and an
/// unregistration, which ends one (`spec/COMMANDS.md`, "Hints").
#[test]
fn tools() {
for (nsid, tool) in [
(NOTIFY_WRITE, "space_notify_write"),
(LIST, "space_list_repos"),
(REGISTER, "space_register_notify"),
(UNREGISTER, "space_unregister_notify"),
let writes =
|destroys: bool| Some(json!({ "readOnlyHint": false, "destructiveHint": destroys }));
for (nsid, tool, hints) in [
(NOTIFY_WRITE, "space_notify_write", writes(false)),
(
LIST,
"space_list_repos",
Some(json!({ "readOnlyHint": true })),
),
(REGISTER, "space_register_notify", writes(false)),
(UNREGISTER, "space_unregister_notify", writes(true)),
] {
let m = pds_lexicon::method(nsid).unwrap();
assert_eq!(m.tool().as_deref(), Some(tool));
assert_ne!(
m.annotations().unwrap()["destructiveHint"],
json!(true),
"{nsid}"
);
assert_eq!(m.annotations(), hints, "{nsid}");
}
}
crates/pds-server/src/mcp.rs+41−1
@@ -583,7 +583,8 @@ fn tools() -> Vec<Json> {
.iter()
.filter_map(|m| {
let name = m.tool()?;
let mut tool = json!({ "name": name, "inputSchema": m.input_schema() });
let mut tool =
json!({ "name": name, "title": m.title(), "inputSchema": m.input_schema() });
if let Some(d) = &m.description {
tool["description"] = json!(d);
}
@@ -999,6 +1000,45 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// Every tool has a title by the rule of `spec/COMMANDS.md`, "Names",
/// and its hints as "Hints" gives them, by what it does.
#[test]
fn titles_and_hints() {
let all = tools();
let of = |name: &str| {
all.iter()
.find(|t| t["name"] == name)
.unwrap_or_else(|| panic!("no tool {name}"))
};
assert!(all.iter().all(|t| t["title"].is_string()));
for (name, title) in [
(
"identity_get_recommended_did_credentials",
"Get recommended did credentials (identity)",
),
("repo_create_record", "Create record (repo)"),
("admin_logs", "Logs (admin)"),
("admin_stats", "Stats (admin)"),
("oauth_sessions", "Sessions (oauth)"),
("oauth_revoke_session", "Revoke session (oauth)"),
("oauth_devices", "Devices (oauth)"),
("oauth_revoke_device", "Revoke device (oauth)"),
] {
assert_eq!(of(name)["title"], title, "{name}");
}
let adds = json!({ "readOnlyHint": false, "destructiveHint": false });
let destroys = json!({ "readOnlyHint": false, "destructiveHint": true });
for (name, hints) in [
("server_get_service_auth", &adds),
("repo_create_record", &adds),
("repo_delete_record", &destroys),
("memberspace_put_member", &destroys),
("repo_list_records", &json!({ "readOnlyHint": true })),
] {
assert_eq!(&of(name)["annotations"], hints, "{name}");
}
}
#[test]
fn header_values() {
assert_eq!(
docs/guide/calling.md+17−0
@@ -80,6 +80,18 @@ PDS_URL=$OLD PDS_TOKEN=$OLD_TOKEN pds sync get-repo --did "$DID" \
| PDS_URL=$NEW PDS_TOKEN=$NEW_TOKEN pds repo import-repo
```
`pds xrpc` makes any call by name, with `goat xrpc`'s arguments
([COMMANDS.md](../../spec/COMMANDS.md#any-call)): `k==v` a query
parameter, `k=v` a string property of the body, `k:=json` any other,
`Name:value` a header, and `-` standard input as the body. It reaches
what has no command, as a method the server forwards to the AppView, and
checks nothing before sending:
```sh
pds xrpc query app.bsky.actor.getProfile actor==atproto.com
pds xrpc procedure com.atproto.repo.createRecord repo=alice.test collection=com.example.note 'record:={"text":"hi"}'
```
## MCP
`POST /mcp` is an MCP endpoint over Streamable HTTP, with tools only
@@ -92,6 +104,11 @@ It takes `Authorization: Bearer <token>`: the tokens XRPC takes, an MCP
client's OAuth access token, or the admin's `Basic`. Every tool is listed
to every caller, with a token or without.
Each tool has a `title` and says what it does in its annotations
([COMMANDS.md](../../spec/COMMANDS.md#hints)): a read is `readOnlyHint`,
and a call that may delete, replace or end something is `destructiveHint`,
so that a client asks before those and not before a read or a new record.
## Connect an AI app
An MCP client such as Claude signs in by OAuth, as MCP's authorization
docs/guide/comparing.md+8−4
@@ -86,10 +86,14 @@ node compare.mjs --steps 400 --seed 31 --commands -- ../target/release/pds serve
node conformance.mjs -- ../target/release/pds serve
```
`--commands` sends some of its requests through the MCP tool or the CLI
command instead of XRPC, in any of the three MCP revisions, held to the
reference as the rest are. It first checks every tool's schema and every
command's flags against the lexicons, and each legacy revision's handshake
`--commands` sends some of its requests through the MCP tool, the CLI
command, or `pds xrpc` instead of XRPC, in any of the three MCP revisions,
held to the reference as the rest are; `pds xrpc` gets each argument in
the forms the request allows, `==`, `=`, `:=`, an `@path` file, and `-`
with a `Content-Type:` header. It first checks every tool's title, schema
and hints, every command's flags against the lexicons, each legacy
revision's handshake, `pds xrpc` on the server's own routes and a
forwarded method, and its usage errors
([COMMANDS.md](../../spec/COMMANDS.md#how-it-is-checked)).
`conformance.mjs` runs MCP's conformance suite against the endpoint, for
`2026-07-28` and `2025-11-25`.
harness/checks/blobs.mjs+4−3
@@ -17,7 +17,7 @@ import { cand, ref } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
import { own } from '../lib/server.mjs'
import { accounts, cids, didOf, exists, nextBatch, noteCommit, noteWrite, tokenOf } from '../lib/state.mjs'
import { runCli } from '../lib/via.mjs'
import { runCli, viaXrpc } from '../lib/via.mjs'
import { both, normalize, shown, xrpc } from '../lib/xrpc.mjs'
/// The collection the records with blob refs are in.
@@ -181,10 +181,11 @@ async function sniffs(bytes, want) {
/// uploadBlob on one side: `bytes` with `type` as Content-Type (none if
/// undefined), `token` an account or a string, sent chunked if asked. With
/// --commands, some of the server's go through `pds repo upload-blob`
/// (spec/COMMANDS.md, "Answers").
/// (spec/COMMANDS.md, "Answers"), or through `pds xrpc` with the bytes as
/// `-` and a `Content-Type:` header (spec/COMMANDS.md, "Any call").
export async function uploadOn(side, { bytes, type, token, chunked }) {
const t = token && typeof token === 'object' ? tokenOf(side, token) : token
if (COMMANDS && side === cand && type && !chunked && token && typeof token === 'object' && bytes.length < 100_000 && chance(0.3)) return uploadByCommand(type, t, bytes)
if (COMMANDS && side === cand && type && !chunked && token && typeof token === 'object' && bytes.length < 100_000 && chance(0.3)) return chance(0.5) ? uploadByCommand(type, t, bytes) : viaXrpc(UPLOAD, { bytes, contentType: type, token: t })
const headers = {}
if (type !== undefined) headers['content-type'] = type
if (t) headers.authorization = `Bearer ${t}`
harness/checks/commands.mjs+164−34
harness/lib/via.mjs+182−18
harness/lib/xrpc.mjs+5−5
spec/COMMANDS.md+108−14
spec/SPACES-CREDENTIALS.md+5−2
spec/SPACES-SYNC.md+4−1