//! `tools/list` and `tools/call`.
//!
//! Tools are returned in a fixed order. The specification asks for a
//! deterministic ordering so clients can cache the list and so a model's
//! prompt cache is not invalidated by a reshuffle; the two blob tools and
//! then `generate_bsky_post` are therefore appended rather than inserted
//! alphabetically.
//!
//! Every tool carries `annotations`. The specification is explicit that they
//! are hints, and that a client "MUST consider tool annotations to be untrusted
//! unless they come from trusted servers" — it does not itself tie them to
//! confirmation prompts. In practice that is what hosts use them for, and a
//! server someone installed is a server they trust, so the values here are
//! load-bearing whatever their formal status.
//!
//! Three tools write: `upload_blob`, which only adds a blob;
//! `generate_bsky_post`, which writes no record but uploads a link card's
//! thumbnail when given an account, so it only adds a blob too; and
//! `invoke_xrpc`, which calls whatever NSID it is given and can therefore
//! delete and overwrite. `invoke_xrpc` is the only one marked
//! `destructiveHint: true`.
//!
//! `download_blob` saves a file, but only into atpmcp's own cache under a
//! name derived from the CID, and the caller cannot choose the destination.
//! That is what keeps it read-only. It took an `output_path` until 0.15.0,
//! which let a model write chosen bytes to any path the user can write
//! without the prompt a writing tool gets; see `tools::blob`.
//!
//! Note that `destructiveHint` **defaults to `true`** and is meaningful only
//! when `readOnlyHint` is `false`. Writing `false` is not a neutral omission,
//! it is opting out of a deliberately pessimistic default — which is how
//! `invoke_xrpc` came to advertise that it made only additive changes while
//! being able to call `com.atproto.repo.deleteRecord`.
pub mod blob;
pub mod bsky;
pub mod core;
pub mod identity;
pub mod lexicon;
#[cfg(test)]
pub mod test_support;
pub mod xrpc;
use std::sync::Arc;
use serde_json::Value;
use crate::context::{Limits, ServerContext};
use crate::proto::serve::RequestCtx;
use crate::proto::{CacheHints, INVALID_PARAMS, JsonRpcResponse, complete};
/// Build a successful tool result.
#[must_use]
pub fn tool_success(text: &str) -> Value {
serde_json::json!({
"content": [{ "type": "text", "text": text }],
"isError": false
})
}
/// Build a failed tool result.
///
/// A tool failure is *not* a JSON-RPC error. It is an ordinary result carrying
/// `isError: true`, because the specification separates "the request was
/// malformed" — which a model cannot fix — from "the operation failed", which
/// it often can.
#[must_use]
pub fn tool_error(text: &str) -> Value {
serde_json::json!({
"content": [{ "type": "text", "text": text }],
"isError": true
})
}
/// Build a successful tool result with structured content.
///
/// The same data is serialized into the text block as well: a tool returning
/// structured content **SHOULD** also return it as text, for clients that do
/// not read `structuredContent`.
#[must_use]
pub fn tool_structured(summary: &str, structured: Value, extra_content: Vec<Value>) -> Value {
let mut content = vec![serde_json::json!({ "type": "text", "text": summary })];
if let Ok(json) = serde_json::to_string(&structured) {
content.push(serde_json::json!({ "type": "text", "text": json }));
}
content.extend(extra_content);
serde_json::json!({
"content": content,
"structuredContent": structured,
"isError": false
})
}
/// An optional whole-number argument.
///
/// `Ok(None)` when it is absent or `null`, the value when it is a non-negative
/// whole number, and a message naming it otherwise. A whole number is JSON
/// Schema's `integer`, which includes a number with a zero fractional part, so
/// `5.0` is `5`: a client that validated against the advertised schema may
/// well send it.
///
/// This replaced `and_then(Value::as_u64)` with a default, which read `"5"`,
/// `5.0` and `-1` as absent. A `count` of any of them became `1`, and a
/// `timestamp_micros` became the current time -- a caller asking for a
/// backdated TID got a present-day one, reported as a success. The blob tools'
/// `max_bytes` had the same defect, and a caller asking for at most 1024 bytes
/// got up to the whole configured ceiling, so it reads through here too.
///
/// # Errors
///
/// A message naming the argument, for anything but a non-negative whole
/// number, `null` or nothing.
pub fn optional_whole_number(arguments: &Value, name: &str) -> Result<Option<u64>, String> {
let refused = || format!("The '{name}' argument must be a non-negative whole number.");
match arguments.get(name) {
None | Some(Value::Null) => Ok(None),
Some(Value::Number(number)) => number
.as_u64()
.or_else(|| {
number
.as_f64()
.filter(|float| {
float.fract() == 0.0 && *float >= 0.0 && *float <= u64::MAX as f64
})
.map(|float| float as u64)
})
.map(Some)
.ok_or_else(refused),
Some(_) => Err(refused()),
}
}
/// The `tools/list` result.
#[must_use]
pub fn list(ctx: &Arc<ServerContext>) -> Value {
complete(
serde_json::json!({ "tools": definitions(&ctx.limits) }),
Some(CacheHints::constant()),
&ctx.server_info,
)
}
/// Dispatch a `tools/call` request.
pub async fn call(
ctx: &Arc<ServerContext>,
rctx: &mut RequestCtx,
params: Option<Value>,
) -> JsonRpcResponse {
let id = rctx.id.clone();
let Some(params) = params else {
return JsonRpcResponse::error(id, INVALID_PARAMS, "Missing params");
};
let Some(name) = params.get("name").and_then(Value::as_str) else {
return JsonRpcResponse::error(id, INVALID_PARAMS, "Missing tool name");
};
let arguments = params.get("arguments").cloned().unwrap_or(Value::Null);
let resolver = ctx.resolver.as_ref();
let payload = match name {
// Test-only hooks. Guarded by `cfg(test)`, so they cannot reach a
// released binary. They exist because panic isolation and head-of-line
// blocking are exactly the properties that regress silently, and
// neither can be exercised without a handler that misbehaves on
// purpose.
#[cfg(test)]
"__test_panic" => panic!("deliberate panic from a test hook"),
#[cfg(test)]
"__test_slow" => {
tokio::select! {
() = rctx.cancel.cancelled() => tool_error("cancelled"),
() = tokio::time::sleep(std::time::Duration::from_millis(300)) => {
tool_success("slow handler finished")
}
}
}
"create_record_cid" => core::create_record_cid(arguments),
"validate_lexicon_schema" => lexicon::validate_lexicon_schema(arguments),
"resolve_handle_to_did" => identity::resolve_handle_to_did(arguments, resolver).await,
"resolve_identity" => identity::resolve_identity(arguments, resolver, &ctx.limits).await,
"parse_facets" => core::parse_facets(arguments, resolver).await,
"get_record" => {
identity::get_record(arguments, resolver, &ctx.request_client, &ctx.limits).await
}
"get_lexicon" => lexicon::get_lexicon(arguments, resolver, &ctx.request_client).await,
"validate_xrpc" => lexicon::validate_xrpc(arguments, resolver, &ctx.request_client).await,
"invoke_xrpc" => {
xrpc::invoke_xrpc(arguments, resolver, &ctx.request_client, &ctx.limits).await
}
"generate_tid" => core::generate_tid(arguments),
"upload_blob" => blob::upload_blob(ctx, rctx, arguments).await,
"download_blob" => blob::download_blob(ctx, rctx, arguments).await,
"generate_bsky_post" => bsky::generate_bsky_post(ctx, rctx, arguments).await,
// An unknown tool is a protocol error, and in this revision that is
// `-32602` rather than the `-32601` an earlier one used.
_ => {
return JsonRpcResponse::error(id, INVALID_PARAMS, format!("Unknown tool: {name}"));
}
};
// `tools/call` is not a cacheable method, so no hints.
JsonRpcResponse::success(id, complete(payload, None, &ctx.server_info))
}
/// Every tool this server exposes, in wire order.
///
/// Takes the limits because two descriptions state a size, and a stated size
/// that ignores configuration is wrong for every deployment that changed it.
/// They were literals -- `16777216` and `262144` -- so a server configured with
/// a 1 MiB ceiling still advertised 16 MiB.
fn definitions(limits: &Limits) -> Value {
let blob_max_upload_bytes = limits.blob_max_upload_bytes;
let blob_max_download_bytes = limits.blob_max_download_bytes;
let blob_max_inline_bytes = limits.blob_max_inline_bytes;
let max_tid_count = core::MAX_TID_COUNT;
let max_timestamp_micros = atproto_record::tid::Tid::MAX_TIMESTAMP_MICROS;
let max_thumb_bytes = bsky::MAX_THUMB_BYTES;
let max_langs = bsky::MAX_LANGS;
let max_gallery = bsky::MAX_GALLERY_ITEMS;
let max_images = bsky::MAX_IMAGES_ITEMS;
let max_media_bytes = bsky::MAX_MEDIA_IMAGE_BYTES;
let image_item = serde_json::json!({
"type": "object",
"properties": {
"path": { "type": "string", "description": "Absolute path to a local image file (e.g. '/Users/alice/Pictures/photo.jpg')." },
"url": { "type": "string", "format": "uri", "description": "An http or https URL to fetch the image from." },
"alt": { "type": "string", "description": "Alt text describing the image, for people who cannot see it. Default ''." }
},
"additionalProperties": false
});
serde_json::json!([
{
"name": "create_record_cid",
"title": "Compute a record CID",
"description": "Serializes a JSON record to deterministic DAG-CBOR, hashes it with SHA-256, and returns a CIDv1 base32 string. Use this when you need to verify record integrity, compare records, or pre-compute CIDs for AT Protocol operations. Returns an error if the record cannot be serialized to DAG-CBOR.",
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": false },
"inputSchema": {
"type": "object",
"properties": {
"record": {
"type": "object",
"description": "The JSON record object to compute a CID for (e.g. {\"$type\": \"app.bsky.feed.post\", \"text\": \"Hello\", \"createdAt\": \"2024-01-01T00:00:00.000Z\"})."
}
},
"required": ["record"],
"additionalProperties": false
}
},
{
"name": "validate_lexicon_schema",
"title": "Validate a lexicon schema",
"description": "Validates an AT Protocol lexicon schema, checking version, NSID, and definition structure. Use this when building or reviewing a Lexicon schema to verify it conforms to the specification before publishing. Returns validation errors describing which fields are invalid or missing.",
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": false },
"inputSchema": {
"type": "object",
"properties": {
"schema": {
"type": "object",
"description": "The lexicon schema object to validate. Must include 'lexicon' (version integer), 'id' (NSID string), and 'defs' (definitions object)."
}
},
"required": ["schema"],
"additionalProperties": false
}
},
{
"name": "resolve_handle_to_did",
"title": "Resolve a handle",
"description": "Resolves an AT Protocol handle (e.g. 'alice.bsky.social') to its DID identifier, and reports whether that DID's document claims the handle back. Use this when you have a user's handle and need their DID for API calls or record lookups. Anyone who controls a domain can point its handle at any DID, so treat the DID as the handle's account only when verified is true. Returns an error if the handle cannot be resolved via DNS or HTTP.",
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": true },
"inputSchema": {
"type": "object",
"properties": {
"handle": {
"type": "string",
"description": "The AT Protocol handle to resolve (e.g. 'alice.bsky.social')."
}
},
"required": ["handle"],
"additionalProperties": false
},
"outputSchema": {
"type": "object",
"properties": {
"did": { "type": "string", "description": "The DID the handle resolved to." },
"handle": { "type": "string", "description": "The handle as resolved: lowercased, without an '@' or 'at://' prefix. Absent when the input was a DID." },
"verified": {
"type": "boolean",
"description": "Whether the DID document lists at://<handle> in alsoKnownAs. Always true for a DID input, which has no handle to confirm."
}
},
"required": ["did", "verified"]
}
},
{
"name": "resolve_identity",
"title": "Resolve a DID document",
"description": "Retrieves the full DID document for a given DID, with optional PLC directory override. Use this when you need to inspect verification methods, service endpoints, or rotation keys for an identity. Returns an error if the DID cannot be resolved or the document is malformed.",
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": true },
"inputSchema": {
"type": "object",
"properties": {
"did": {
"type": "string",
"description": "The DID to resolve (e.g. 'did:plc:ewvi7nxzyoun6zhxrhs64oiz' or 'did:web:example.com')."
},
"plc_directory_hostname": {
"type": "string",
"description": "PLC directory override: a hostname (e.g. 'plc.directory'), or a URL with its scheme (e.g. 'https://plc.directory'). Defaults to the server's configured PLC directory ('plc.directory' unless the operator set PLC_HOSTNAME). A directory other than the configured one must pass the server's host policy: HTTPS, a public DNS name, the default port."
}
},
"required": ["did"],
"additionalProperties": false
}
},
{
"name": "parse_facets",
"title": "Parse rich text facets",
"description": "Extracts rich text facets (mentions, URLs, hashtags) from plain text with UTF-8 byte offsets, resolving mentions to DIDs when possible. Use this when composing a Bluesky post that contains mentions, links, or hashtags to generate the required facets array. Returns an empty array if no facets are found; mentions that do not resolve are omitted.",
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": true },
"inputSchema": {
"type": "object",
"properties": {
"text": {
"type": "string",
"description": "The plain text to parse for facets (e.g. 'Hello @alice.bsky.social check out https://example.com #atproto')."
}
},
"required": ["text"],
"additionalProperties": false
}
},
{
"name": "get_record",
"title": "Fetch a record",
"description": "Retrieves an AT Protocol record by AT-URI, resolving identity and PDS endpoint automatically. Use this when you need to fetch a specific record such as a post, profile, or follow. Returns an error if the AT-URI is malformed, the identity cannot be resolved, or the record does not exist.",
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": true },
"inputSchema": {
"type": "object",
"properties": {
"uri": {
"type": "string",
"description": "The AT-URI of the record to retrieve (e.g. 'at://did:plc:abc123/app.bsky.feed.post/rkey')."
},
"cid": {
"type": "string",
"description": "Optional CID to retrieve a specific version of the record (e.g. 'bafyreig2...')."
},
"plc_directory_hostname": {
"type": "string",
"description": "PLC directory override: a hostname (e.g. 'plc.directory'), or a URL with its scheme (e.g. 'https://plc.directory'). Defaults to the server's configured PLC directory ('plc.directory' unless the operator set PLC_HOSTNAME). A directory other than the configured one must pass the server's host policy: HTTPS, a public DNS name, the default port."
}
},
"required": ["uri"],
"additionalProperties": false
}
},
{
"name": "get_lexicon",
"title": "Fetch a lexicon",
"description": "Retrieves and describes an AT Protocol lexicon schema by NSID, returning its definitions, required fields, and structure. Use this when you need to inspect the schema for a record type or XRPC method before constructing records or API calls. Returns an error if the NSID authority cannot be resolved or the lexicon record is not found.",
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": true },
"inputSchema": {
"type": "object",
"properties": {
"nsid": {
"type": "string",
"description": "The NSID of the lexicon to fetch (e.g. 'app.bsky.feed.post')."
},
"repo": {
"type": "string",
"description": "Optional repository DID or handle for lexicon resolution (e.g. 'did:plc:ewvi7nxzyoun6zhxrhs64oiz'). If omitted, the authority is resolved from the NSID via DNS."
}
},
"required": ["nsid"],
"additionalProperties": false
}
},
{
"name": "validate_xrpc",
"title": "Validate XRPC input",
"description": "Validates XRPC request parameters and body against an AT Protocol lexicon schema, catching missing or invalid input before making a call. Use this before calling invoke_xrpc to verify that your parameters and body conform to the method's lexicon; pass params with the types the lexicon declares (50, not \"50\"), which is what invoke_xrpc takes too. Lexicons referenced by this one are fetched and validated against; any that cannot be resolved are named in the answer, because the parts referencing them were not checked. Returns validation errors listing which fields are invalid or missing.",
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": true },
"inputSchema": {
"type": "object",
"properties": {
"nsid": {
"type": "string",
"description": "The XRPC method NSID (e.g. 'com.atproto.repo.describeRepo')."
},
"params": {
"type": "object",
"description": "Query or procedure parameters to validate, with the types the lexicon declares (e.g. {\"repo\": \"alice.bsky.social\", \"limit\": 50})."
},
"body": {
"type": "object",
"description": "Procedure input body to validate as a JSON object."
},
"repo": {
"type": "string",
"description": "Optional repository DID or handle for lexicon resolution. If omitted, the authority is resolved from the NSID via DNS."
}
},
"required": ["nsid"],
"additionalProperties": false
}
},
{
"name": "invoke_xrpc",
"title": "Invoke an XRPC method",
"description": "Invokes an XRPC method on an AT Protocol service, supporting both queries (GET) and procedures (POST) with optional authentication and proxied requests. Use this when you need to make API calls to a PDS or AppView service. The method is whatever NSID you pass, so this can delete and overwrite: com.atproto.repo.deleteRecord, applyWrites and an overwriting putRecord all go through here. Requires one of endpoint, identity, or auth_handle to determine the target service. This tool sends JSON only; use upload_blob and download_blob for binary payloads. An error response from the service is returned as an error result carrying its HTTP status and body.",
"annotations": { "readOnlyHint": false, "destructiveHint": true, "idempotentHint": false, "openWorldHint": true },
"inputSchema": {
"type": "object",
"properties": {
"nsid": {
"type": "string",
"description": "The XRPC method NSID (e.g. 'com.atproto.repo.describeRepo')."
},
"params": {
"type": "object",
"description": "Query parameters (e.g. {\"repo\": \"alice.bsky.social\", \"limit\": 50}). Use the types the lexicon declares: a boolean, an integer, a string, or an array of those, which is sent as repeated keys. Sent on the URL whether or not there is a body.",
"additionalProperties": {
"anyOf": [
{ "type": "string" },
{ "type": "integer" },
{ "type": "boolean" },
{ "type": "array", "items": { "type": ["string", "integer", "boolean"] } }
]
}
},
"body": {
"type": "object",
"description": "JSON body for POST (procedure) requests. If present, the request is sent as POST; otherwise GET."
},
"endpoint": {
"type": "string",
"description": "Explicit service endpoint URL (e.g. 'https://bsky.network'). One of endpoint, identity, or auth_handle is required. Cannot be combined with auth_handle: an authenticated request always goes to the account's own PDS. Use proxy to reach another service with credentials."
},
"identity": {
"type": "string",
"description": "Handle or DID to resolve for PDS endpoint discovery (e.g. 'alice.bsky.social' or 'did:plc:ewvi7nxzyoun6zhxrhs64oiz'). One of endpoint, identity, or auth_handle is required. Cannot be combined with auth_handle, which resolves its own account's PDS."
},
"auth_handle": {
"type": "string",
"description": "Handle of a stored atpxrpc account for authenticated requests (e.g. 'alice.bsky.social'). Configure credentials via the atpxrpc CLI. If omitted, the request is unauthenticated. The request always goes to this account's own PDS; endpoint and identity are refused alongside it."
},
"proxy": {
"type": "string",
"description": "Service audience for proxied requests in DID#serviceId format (e.g. 'did:web:api.bsky.app#bsky_fg'). Requires auth_handle. The request is sent to the authenticated user's PDS with the atproto-proxy header set to this value, which is how an authenticated call reaches a service other than the account's PDS."
}
},
"required": ["nsid"],
"additionalProperties": false
}
},
{
"name": "generate_tid",
"title": "Generate a TID",
"description": format!("Generates AT Protocol Timestamp Identifiers (TIDs). TIDs are 13-character base32-sortable strings used as record keys. Use this when creating new records that require a TID as the record key (rkey). Returns an error if count is not a whole number from 1 to {max_tid_count}, or timestamp_micros is not a whole number of microseconds from 0 to {max_timestamp_micros}."),
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": false, "openWorldHint": false },
"inputSchema": {
"type": "object",
"properties": {
"count": {
"type": "integer",
"minimum": 1,
"maximum": max_tid_count,
"description": format!("Number of TIDs to generate (default 1, max {max_tid_count}). Example: 5.")
},
"timestamp_micros": {
"type": "integer",
"minimum": 0,
"maximum": max_timestamp_micros,
"description": format!("Specific UNIX timestamp in microseconds, not nanoseconds, to generate from (e.g. 1704067200000000 for 2024-01-01T00:00:00Z); at most {max_timestamp_micros}, the largest a TID can hold. If omitted, uses current time.")
}
},
"additionalProperties": false
}
},
{
"name": "upload_blob",
"title": "Upload a blob",
"description": "Uploads bytes to an authenticated account's PDS via com.atproto.repo.uploadBlob and returns the blob reference to embed in a record. Requires a stored atpxrpc account (auth_handle). Provide exactly one of path or data_base64. The content type is determined from the bytes; content_type is a fallback used only when the bytes are inconclusive, and a disagreement is reported with the sniffed type recorded. The upload always goes to the account's own PDS. Returns an error if the account is unknown, the file cannot be read, the blob exceeds max_bytes, or the PDS refuses the upload.",
"annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": false, "openWorldHint": true },
"inputSchema": {
"type": "object",
"properties": {
"auth_handle": {
"type": "string",
"description": "Handle of a stored atpxrpc account (e.g. 'alice.bsky.social'). Configure credentials via the atpxrpc CLI."
},
"path": {
"type": "string",
"description": "Absolute path to a local file to upload (e.g. '/home/alice/photo.png')."
},
"data_base64": {
"type": "string",
"description": "Base64-encoded bytes to upload, as an alternative to path."
},
"content_type": {
"type": "string",
"description": "MIME type to record on the blob (e.g. 'image/png'). Omit to determine it from the bytes, which is preferred: the recorded type is permanent."
},
"max_bytes": {
"type": "integer",
"minimum": 1,
"description": format!("Refuse uploads larger than this. The server's ceiling is {blob_max_upload_bytes} bytes, and a larger value here does not raise it.")
}
},
"required": ["auth_handle"],
"additionalProperties": false
},
"outputSchema": {
"type": "object",
"properties": {
"blob": {
"type": "object",
"description": "The lexicon blob envelope to embed in a record value.",
"properties": {
"$type": { "const": "blob" },
"ref": {
"type": "object",
"properties": { "$link": { "type": "string" } },
"required": ["$link"]
},
"mimeType": { "type": "string" },
"size": { "type": "integer" }
},
"required": ["$type", "ref", "mimeType", "size"]
},
"uri": { "type": "string", "description": "The atpmcp:// resource URI for the uploaded blob." },
"cid": { "type": "string" },
"size": { "type": "integer" },
"mimeType": { "type": "string" },
"verified": {
"type": "boolean",
"description": "Whether the CID returned by the PDS matches the CID computed locally from the bytes."
}
},
"required": ["blob", "uri", "cid", "size", "mimeType", "verified"]
}
},
{
"name": "download_blob",
"title": "Download a blob",
"description": "Fetches a blob by DID (or handle) and CID from the repository's PDS, verifies the bytes against the CID, and saves them to atpmcp's own blob cache. Returns the saved file's path and a link; the destination cannot be chosen, so move the file with a file tool if it is needed elsewhere. Set inline to true to also return the bytes to the model as base64, which is only appropriate for small blobs. When following a blob reference, pass its size and mimeType as size and mime_type to have them checked too. Returns an error if the identity cannot be resolved, the blob is missing, the bytes do not hash to the requested CID, or the blob is not the size given.",
"annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": true },
"inputSchema": {
"type": "object",
"properties": {
"identity": {
"type": "string",
"description": "Handle or DID of the repository holding the blob (e.g. 'alice.bsky.social')."
},
"cid": {
"type": "string",
"description": "CID of the blob (CIDv1, raw codec, SHA-256; e.g. 'bafkreib2rxk3rh6kzwq...')."
},
"uri": {
"type": "string",
"description": "An atpmcp://public/blob/{did}/{cid} URI, as an alternative to identity + cid."
},
"inline": {
"type": "boolean",
"description": format!("Return the bytes to the model as base64 instead of only a path. Refused above the inline ceiling, which is {blob_max_inline_bytes} bytes.")
},
"max_bytes": {
"type": "integer",
"minimum": 1,
"description": format!("Refuse downloads larger than this. The server's ceiling is {blob_max_download_bytes} bytes, and a larger value here does not raise it.")
},
"size": {
"type": "integer",
"minimum": 1,
"description": "The size from the blob reference being followed. A blob of any other size is refused, and one the reference says is over the ceiling is refused before it is fetched."
},
"mime_type": {
"type": "string",
"minLength": 1,
"description": "The mimeType from the blob reference being followed. Checked against the type the host serves and the bytes, with a disagreement reported in mimeTypeDisagreement, and reported as the blob's type when the host serves only application/octet-stream and the bytes do not say otherwise."
},
"endpoint": {
"type": "string",
"description": "Explicit service endpoint URL, bypassing DID-document resolution (e.g. 'https://pds.example.com')."
}
},
"additionalProperties": false
},
"outputSchema": {
"type": "object",
"properties": {
"uri": { "type": "string" },
"cid": { "type": "string" },
"did": { "type": "string" },
"mimeType": { "type": "string", "description": "The blob's content type: the Content-Type the host served, or the cached copy recorded, unless that is application/octet-stream or missing, which a host may send for any blob. Then it is the mime_type argument unless the bytes are recognised as another type, else the type sniffed from the bytes, else application/octet-stream." },
"mimeTypeDisagreement": { "type": "string", "description": "Present when the mime_type argument disagrees with the type the host served or the type sniffed from the bytes." },
"size": { "type": "integer" },
"path": { "type": "string", "description": "The verified file: an entry in the blob cache named for the CID, or a scratch file in the system temp directory when there is no cache, the blob is larger than its budget, or the cache cannot store it. Either way it exists when the call returns." },
"cached": { "type": "boolean", "description": "Whether the bytes came from the local cache rather than the network." },
"verified": { "type": "boolean", "description": "Whether the bytes hash to the requested CID." }
},
"required": ["uri", "cid", "did", "size", "verified"]
}
},
{
"name": "generate_bsky_post",
"title": "Generate a Bluesky post",
"description": format!("Builds an app.bsky.feed.post record for Bluesky and returns it without publishing it; publish it with invoke_xrpc com.atproto.repo.createRecord (collection app.bsky.feed.post) as the account that should post it. The text is used exactly as given. Facets for mentions, links and hashtags are parsed from it, mentions resolved to DIDs; a mention that does not resolve has no facet. Each *_facet_allow list keeps only the facets of its kind it names, and an absent or empty list keeps them all. embed_external makes an app.bsky.embed.external link card from that page's Open Graph metadata, falling back to its Twitter card metadata and its <title>. With auth_handle, the page's image is uploaded to that account's PDS as the card's thumbnail (so publish as that account), first shrunk to a JPEG that fits when it is over {max_thumb_bytes} bytes, the lexicon's limit. The thumbnail's metadata (EXIF, XMP and the like) is removed unless the server runs with ATPMCP_PRESERVE_EXIF=1. Without auth_handle, or when the image is missing, cannot be fetched or shrunk, or is not an image, the card has no thumbnail and the result says why. gallery (up to {max_gallery} images, an app.bsky.embed.gallery) or images (up to {max_images}, the older app.bsky.embed.images) attaches images from local paths or URLs instead: each is uploaded to auth_handle's PDS (required) with its alt text and aspect ratio, shrunk to a JPEG that fits when it is over {max_media_bytes} bytes and stripped of metadata like the thumbnail, and one that cannot be used fails the call before anything is uploaded. gallery, images and embed_external cannot be combined. shorten_links shows each linked URL in the text shortened, as the Bluesky app does, with the link still going to the full URL. The record is validated against the app.bsky.feed.post lexicon before it is returned. Returns an error if an argument is malformed, the record is invalid (for example a text over 300 graphemes), the page cannot be fetched or is not HTML, an image cannot be used, or an upload fails."),
"annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": false, "openWorldHint": true },
"inputSchema": {
"type": "object",
"properties": {
"text": {
"type": "string",
"description": "The post text, used exactly as given (e.g. 'Hello @alice.bsky.social'). At most 300 graphemes and 3000 bytes."
},
"mention_facet_allow": {
"type": "array",
"items": { "type": "string" },
"description": "Handles whose mentions get facets (e.g. ['@alice.bsky.social']), compared without regard to case, with or without the '@'. Absent or empty keeps every mention."
},
"tag_facet_allow": {
"type": "array",
"items": { "type": "string" },
"description": "Hashtags that get facets (e.g. ['#rust']), compared without regard to case, with or without the '#'. Absent or empty keeps every tag."
},
"link_facet_allow": {
"type": "array",
"items": { "type": "string" },
"description": "Links that get facets, compared exactly with the URL as the text has it (e.g. ['https://example.com/']). Absent or empty keeps every link."
},
"embed_external": {
"type": "string",
"format": "uri",
"description": "A page to attach as a link card (e.g. 'https://example.com/article'). Its title, description and image come from the page."
},
"langs": {
"type": "array",
"items": { "type": "string" },
"maxItems": max_langs,
"default": bsky::DEFAULT_LANGS,
"description": format!("The post's languages as BCP 47 tags, at most {max_langs} (default ['en']). An empty array leaves the field out.")
},
"gallery": {
"type": "array",
"minItems": 1,
"maxItems": max_gallery,
"items": image_item.clone(),
"description": format!("Images for an app.bsky.embed.gallery, in order, each {{\"path\": …}} or {{\"url\": …}} with an optional \"alt\" (e.g. [{{\"path\": \"/Users/alice/Pictures/a.png\", \"alt\": \"A cat\"}}, {{\"url\": \"https://example.com/b.jpg\"}}]). At most {max_gallery}. Needs auth_handle. Cannot be combined with images or embed_external.")
},
"images": {
"type": "array",
"minItems": 1,
"maxItems": max_images,
"items": image_item,
"description": format!("Images for an app.bsky.embed.images, the older image embed, which more clients show: the same items as gallery, at most {max_images}. Needs auth_handle. Cannot be combined with gallery or embed_external.")
},
"shorten_links": {
"type": "boolean",
"default": false,
"description": "Show each linked URL in the text shortened, as the Bluesky app does: https://example.com/a/long/path becomes example.com/a/long/pat... The link still goes to the full URL."
},
"auth_handle": {
"type": "string",
"description": "Handle of a stored atpxrpc account (e.g. 'alice.bsky.social') to upload the link card's thumbnail, or the gallery or images, to. Required with gallery or images."
}
},
"required": ["text"],
"additionalProperties": false
},
"outputSchema": {
"type": "object",
"properties": {
"record": {
"type": "object",
"description": "The app.bsky.feed.post record, ready to pass as createRecord's record."
},
"notes": {
"type": "array",
"items": { "type": "string" },
"description": "What was left out or changed, and why: a mention, link or tag with no facet, a card with no thumbnail, an image with its metadata removed or shrunk to fit, or an image with no alt text."
},
"uploaded": {
"type": "array",
"description": "Present when gallery or images were uploaded: each blob, in order.",
"items": {
"type": "object",
"properties": {
"cid": { "type": "string" },
"uri": { "type": "string" },
"verified": { "type": "boolean" }
},
"required": ["cid", "uri", "verified"]
}
},
"thumbnail": {
"type": "object",
"description": "Present when a thumbnail was uploaded.",
"properties": {
"cid": { "type": "string" },
"uri": { "type": "string", "description": "The atpmcp:// resource URI for the uploaded blob." },
"verified": { "type": "boolean", "description": "Whether the CID returned by the PDS matches the CID computed locally from the bytes." }
},
"required": ["cid", "uri", "verified"]
}
},
"required": ["record", "notes"]
}
}
])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_tool_has_the_required_shape() {
let tools = definitions(&Limits::default());
let tools = tools.as_array().expect("tools is an array");
assert_eq!(tools.len(), 13);
for tool in tools {
let name = tool["name"].as_str().expect("name is a string");
assert!(!name.is_empty(), "tool name must not be empty");
assert!(
name.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.'),
"tool name {name} uses characters outside the permitted set"
);
assert!(tool["title"].is_string(), "{name} has no title");
assert!(tool["description"].is_string(), "{name} has no description");
assert_eq!(
tool["inputSchema"]["type"], "object",
"{name} inputSchema must be an object schema"
);
for hint in [
"readOnlyHint",
"destructiveHint",
"idempotentHint",
"openWorldHint",
] {
assert!(
tool["annotations"][hint].is_boolean(),
"{name} is missing annotation {hint}"
);
}
}
}
#[test]
fn tool_order_is_stable_and_blob_tools_are_appended() {
let tools = definitions(&Limits::default());
let names: Vec<&str> = tools
.as_array()
.unwrap()
.iter()
.map(|tool| tool["name"].as_str().unwrap())
.collect();
assert_eq!(
names,
vec![
"create_record_cid",
"validate_lexicon_schema",
"resolve_handle_to_did",
"resolve_identity",
"parse_facets",
"get_record",
"get_lexicon",
"validate_xrpc",
"invoke_xrpc",
"generate_tid",
"upload_blob",
"download_blob",
"generate_bsky_post",
]
);
}
/// No read-only tool takes a filesystem path.
///
/// A path argument lets the caller point the tool at the user's files, and
/// a read-only tool is one a host may run without asking. `download_blob`
/// had `output_path` and wrote wherever it named: a prompt injection could
/// create a shell startup file with no confirmation. Pinned across every
/// read-only tool, so a path argument added to one of them later fails
/// here rather than reopening that.
#[test]
fn no_read_only_tool_takes_a_filesystem_path() {
let tools = definitions(&Limits::default());
for tool in tools.as_array().unwrap() {
if tool["annotations"]["readOnlyHint"] != true {
continue;
}
let name = tool["name"].as_str().unwrap();
let properties = tool["inputSchema"]["properties"]
.as_object()
.map(|properties| properties.keys().cloned().collect::<Vec<_>>())
.unwrap_or_default();
let paths: Vec<&String> = properties
.iter()
.filter(|property| property.contains("path"))
.collect();
assert!(paths.is_empty(), "{name} is read-only but takes {paths:?}");
}
}
#[test]
fn only_the_writing_tools_are_marked_as_writing() {
let tools = definitions(&Limits::default());
let writers: Vec<&str> = tools
.as_array()
.unwrap()
.iter()
.filter(|tool| tool["annotations"]["readOnlyHint"] == false)
.map(|tool| tool["name"].as_str().unwrap())
.collect();
assert_eq!(
writers,
vec!["invoke_xrpc", "upload_blob", "generate_bsky_post"]
);
}
/// The destructive set, pinned by name.
///
/// `destructiveHint` defaults to `true`, so every `false` here is an
/// explicit opt-out of a pessimistic default, and one of them was wrong:
/// `invoke_xrpc` calls whatever NSID it is handed, including
/// `com.atproto.repo.deleteRecord`, and advertised that it made only
/// additive changes.
///
/// Pinned as a list rather than as one tool's flag, so a tool added later
/// has to decide rather than inherit whatever it was copied from. The
/// companion assertion is that nothing read-only claims to be destructive,
/// which would be a contradiction rather than merely inert.
#[test]
fn only_the_destructive_tools_are_marked_as_destructive() {
let tools = definitions(&Limits::default());
let destructive: Vec<&str> = tools
.as_array()
.unwrap()
.iter()
.filter(|tool| tool["annotations"]["destructiveHint"] == true)
.map(|tool| tool["name"].as_str().unwrap())
.collect();
assert_eq!(destructive, vec!["invoke_xrpc"]);
for tool in tools.as_array().unwrap() {
let name = tool["name"].as_str().unwrap();
if tool["annotations"]["readOnlyHint"] == true {
assert_eq!(
tool["annotations"]["destructiveHint"], false,
"{name} is read-only, so it cannot be destructive"
);
}
}
}
/// A tool that can reach an arbitrary method says so where a model reads.
///
/// The annotation steers the host; the description is what the model sees
/// when it picks a tool. Both should say the same thing.
#[test]
fn invoke_xrpc_says_it_can_delete() {
let tools = definitions(&Limits::default());
let tool = tools
.as_array()
.unwrap()
.iter()
.find(|tool| tool["name"] == "invoke_xrpc")
.expect("invoke_xrpc should be listed");
assert_eq!(tool["annotations"]["destructiveHint"], true);
let description = tool["description"].as_str().expect("a description");
assert!(
description.contains("delete"),
"the description should say the tool can delete: {description}"
);
}
/// What `parse_facets` says about a mention it could not resolve.
///
/// The description used to end "unresolvable mentions are included without
/// a DID", which the tool has never done: it calls
/// `atproto_extras::parse_facets_from_text`, which omits them, and could
/// not do otherwise -- `Mention` has a required `did`, so a mention facet
/// without one is unrepresentable. A model reading the old text would wait
/// for entries that never arrive, and a host would show the user a list of
/// failed mentions that is always empty.
///
/// Pinned on the wording rather than left to review, because this is the
/// exact sentence that drifted.
#[test]
fn parse_facets_says_unresolved_mentions_are_omitted() {
let tools = definitions(&Limits::default());
let tool = tools
.as_array()
.unwrap()
.iter()
.find(|tool| tool["name"] == "parse_facets")
.expect("parse_facets should be listed");
let description = tool["description"].as_str().expect("a description");
assert!(
description.contains("do not resolve are omitted"),
"the description should say unresolved mentions are dropped: {description}"
);
assert!(
!description.contains("without a DID"),
"the description should not promise DID-less mentions: {description}"
);
}
/// `generate_tid` declares the bounds it enforces, so a client that
/// validates arguments can refuse a timestamp in nanoseconds before
/// sending it. The schema gave neither argument a bound.
#[test]
fn generate_tid_declares_its_bounds() {
let tools = definitions(&Limits::default());
let tool = tools
.as_array()
.unwrap()
.iter()
.find(|tool| tool["name"] == "generate_tid")
.expect("generate_tid should be listed");
let properties = &tool["inputSchema"]["properties"];
assert_eq!(properties["count"]["minimum"], 1);
assert_eq!(properties["count"]["maximum"], core::MAX_TID_COUNT);
assert_eq!(properties["timestamp_micros"]["minimum"], 0);
assert_eq!(
properties["timestamp_micros"]["maximum"],
atproto_record::tid::Tid::MAX_TIMESTAMP_MICROS
);
}
/// The blob tools declare that `max_bytes` is at least 1, which they
/// enforce. Nothing above is declared: a larger value is allowed, and
/// capped at the configured ceiling.
#[test]
fn the_blob_tools_declare_a_minimum_max_bytes() {
let tools = definitions(&Limits::default());
for name in ["upload_blob", "download_blob"] {
let tool = tools
.as_array()
.unwrap()
.iter()
.find(|tool| tool["name"] == name)
.expect("listed");
let max_bytes = &tool["inputSchema"]["properties"]["max_bytes"];
assert_eq!(max_bytes["type"], "integer", "{name}");
assert_eq!(max_bytes["minimum"], 1, "{name}");
assert!(max_bytes.get("maximum").is_none(), "{name}");
}
}
#[test]
fn tools_with_structured_output_declare_an_output_schema() {
let tools = definitions(&Limits::default());
for tool in tools.as_array().unwrap() {
let name = tool["name"].as_str().unwrap();
if matches!(
name,
"resolve_handle_to_did" | "upload_blob" | "download_blob" | "generate_bsky_post"
) {
assert_eq!(tool["outputSchema"]["type"], "object", "{name}");
}
}
}
#[test]
fn structured_results_repeat_themselves_as_text() {
let result = tool_structured("done", serde_json::json!({ "cid": "bafkrei" }), vec![]);
assert_eq!(result["isError"], false);
assert_eq!(result["structuredContent"]["cid"], "bafkrei");
let content = result["content"].as_array().unwrap();
assert_eq!(content[0]["text"], "done");
assert!(content[1]["text"].as_str().unwrap().contains("bafkrei"));
}
#[test]
fn tool_errors_are_results_not_protocol_errors() {
let result = tool_error("error-atpmcp-tool-1 something went wrong");
assert_eq!(result["isError"], true);
assert!(
result["content"][0]["text"]
.as_str()
.unwrap()
.starts_with("error-atpmcp-tool-")
);
}
}