atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
//! AT Protocol MCP server.
//!
//! A Model Context Protocol server speaking **MCP 2026-07-28** over stdio. It
//! exposes AT Protocol identity, record, lexicon, XRPC and blob operations as
//! tools, and AT Protocol blobs as readable resources.
//!
//! # This server requires MCP 2026-07-28
//!
//! That revision removed the `initialize` handshake and made the protocol
//! stateless: every request carries its own protocol version and client
//! capabilities in `_meta`, and `server/discover` replaces the handshake. A
//! client speaking an earlier revision **will not work**, and is answered with
//! an error naming the version this server implements rather than left to
//! guess. Clients that have not migrated should pin `atpmcp` 0.14.5: the last
//! 0.14 release, and the last that answers an earlier revision.
//!
//! # Transport
//!
//! - stdin: newline-delimited JSON-RPC 2.0 messages
//! - stdout: newline-delimited JSON-RPC 2.0 responses and notifications,
//!   written by exactly one task
//! - stderr: tracing output. The Logging feature is deprecated in this
//!   revision and stderr is the migration it names for stdio servers.
//!
//! Requests are handled concurrently. That is not an optimisation: a serial
//! loop cannot receive a cancellation while it is working, and cannot hold a
//! `subscriptions/listen` stream open at all. See the `proto::serve` module.
//!
//! # Tools
//!
//! - `create_record_cid` — Compute the DAG-CBOR CID for a JSON record
//! - `validate_lexicon_schema` — Validate a lexicon schema object
//! - `resolve_handle_to_did` — Resolve an AT Protocol handle to a DID, and check the DID claims it
//! - `resolve_identity` — Resolve a DID to its full DID document
//! - `parse_facets` — Parse rich text facets from plain text
//! - `get_record` — Retrieve an AT Protocol record by AT-URI
//! - `get_lexicon` — Fetch a lexicon schema record by NSID
//! - `validate_xrpc` — Validate XRPC parameters against a lexicon schema
//! - `invoke_xrpc` — Make a JSON XRPC request to an AT Protocol service
//! - `generate_tid` — Generate AT Protocol Timestamp Identifiers
//! - `upload_blob` — Upload bytes to an account's PDS
//! - `download_blob` — Fetch and verify a blob by DID and CID
//!
//! # Resources
//!
//! - `atpmcp://public/blob/{did}/{cid}` — a blob, fetched from the
//!   repository's PDS, verified against its CID, and cached

// stdout is the protocol stream. A stray `println!` corrupts it in a way that
// is very hard to diagnose from the client side, so it is a compile error.
#![deny(clippy::print_stdout)]

use atpxrpc::accounts;
mod blob;
mod cache;
mod context;
mod errors;
mod host_policy;
mod image_metadata;
mod mime;
mod proto;
mod resources;
mod thumbnail;
mod tools;

use std::io::Write;
use std::sync::Arc;

use atproto_client::com::atproto::server::create_session;
use atproto_identity::resolve::{HickoryDnsResolver, InnerIdentityResolver};
use clap::{Parser, Subcommand};
use secrecy::{ExposeSecret, SecretString};
use tracing_subscriber::EnvFilter;

use crate::cache::BlobCache;
use crate::context::Limits;

/// Command-line interface for atpmcp.
///
/// When invoked without a subcommand, atpmcp runs as an MCP server over stdio.
#[derive(Parser)]
#[command(
    name = "atpmcp",
    version,
    about = "AT Protocol MCP server, speaking MCP 2026-07-28 over stdio",
    long_about = "AT Protocol MCP server (defaults to serving MCP over stdio).\n\n\
                  This server implements MCP 2026-07-28 only. That revision removed the \
                  initialize handshake, so clients speaking an earlier revision cannot use it.",
    args_conflicts_with_subcommands = true
)]
struct Cli {
    #[command(subcommand)]
    command: Option<CliCommand>,
}

/// Subcommands supported by the atpmcp binary.
#[derive(Subcommand)]
enum CliCommand {
    // This text is rendered by `--help`, so it says what a user needs and
    // nothing about its own history: it used to name
    // `~/.config/atpxrpc/config.json` unconditionally, which is the path on
    // one of the three platforms, and said nothing about plaintext.
    /// Log in with a handle and app password, storing the session in the
    /// account store shared with atpxrpc.
    ///
    /// The store is `ATPXRPC_CONFIG` when set, and otherwise
    /// `<config dir>/atpxrpc/config.json`: `~/.config` on Linux,
    /// `~/Library/Application Support` on macOS, `%APPDATA%` on Windows. The
    /// command prints the resolved path when it finishes.
    ///
    /// It holds credentials in plaintext: the app password, the access token
    /// and the refresh token.
    ///
    /// Environment: `ATPROTO_PASSWORD` supplies the app password rather than
    /// prompting, and `PLC_HOSTNAME` names the PLC directory to resolve the
    /// handle through (default `plc.directory`). `DNS_NAMESERVERS` names the
    /// nameservers to resolve a handle with (default: the system's).
    /// `ATPMCP_ALLOW_INSECURE_ENDPOINTS=1`
    /// accepts a PDS endpoint the policy would refuse, such as a local
    /// development server's `http://localhost:4800`, and a name that resolves
    /// to a loopback or private address.
    Login {
        /// Handle or DID to authenticate as.
        identifier: String,
        /// App password (prompted securely if not provided).
        // See the same argument in `atpxrpc`: without `hide_env_values`,
        // `--help` prints the password itself.
        #[arg(env = "ATPROTO_PASSWORD", hide_env_values = true)]
        password: Option<String>,
    },
}

/// The PLC directory hostname this process resolves `did:plc` subjects
/// against by default.
///
/// Reads `PLC_HOSTNAME`, falling back to the public directory -- the same
/// variable and default every other CLI in this workspace reads. Unlike
/// theirs, a value no request URL can be built from stops this process
/// before it serves or logs in; see [`context::plc_hostname`]. This is the
/// process-wide default; a `resolve_identity` or `get_record` call can still
/// ask for a different directory per call via its `plc_directory_hostname`
/// argument (see `tools::identity::resolver_override`), which takes
/// precedence over this one.
///
/// # Errors
///
/// [`errors::ConfigError::NotAPlcDirectory`].
fn default_plc_hostname() -> Result<String, errors::ConfigError> {
    context::plc_hostname(context::env_value)
}

/// Handles the `login` subcommand.
///
/// Resolves the identifier to a PDS endpoint, creates a session via the
/// `com.atproto.server.createSession` XRPC procedure, and upserts the
/// resulting account into the shared atpxrpc config file.
async fn handle_login(identifier: &str, password: Option<String>) -> anyhow::Result<()> {
    // Before the password prompt, so an unusable directory or nameserver is
    // not reported only after the user has typed a password for nothing.
    let plc_hostname = default_plc_hostname()?;
    let dns_nameservers = context::dns_nameservers(context::env_value)?;

    let password = if let Some(password) = password {
        SecretString::new(password.into())
    } else {
        eprint!("Enter app password: ");
        std::io::stderr().flush()?;
        let entered = rpassword::read_password()?;
        if entered.is_empty() {
            anyhow::bail!("Password cannot be empty");
        }
        SecretString::new(entered.into())
    };

    // Never panics: without a readable system configuration, a handle is
    // refused with an error saying to set DNS_NAMESERVERS, and a DID needs
    // no DNS.
    let dns_resolver = HickoryDnsResolver::create_resolver(&dns_nameservers);
    // The same two clients the server uses. `createSession` carries the app
    // password, and a redirect -- a 307 especially, which sends the body again
    // -- would hand it to wherever the PDS pointed, `http://` included.
    //
    // `login` is a command the operator runs, not a tool a model can call, so
    // the waiver applies here as it does to the tools' explicit `endpoint`
    // argument -- and as it does for `atpxrpc login`, which writes the same
    // store. Read alone, and through the server's own parser, because `login`
    // returns before the rest of the configuration is read, and a value that is
    // neither on nor off is refused here as it is there. Read before the
    // clients are built, because it also lifts their address guard.
    let waived = context::parse_waiver(
        "ATPMCP_ALLOW_INSECURE_ENDPOINTS",
        context::env_value("ATPMCP_ALLOW_INSECURE_ENDPOINTS").as_deref(),
    )?;
    let guard = context::AddressGuard::for_config(waived, &plc_hostname);
    let request_client = context::request_client(&guard)?;
    let resolver = InnerIdentityResolver {
        dns_resolver: Arc::new(dns_resolver),
        http_client: context::identity_client(&guard)?,
        plc_hostname,
    };

    eprintln!("Resolving {identifier}...");
    let document = resolver.resolve(identifier).await?;
    let did = document.id.clone();
    let pds_endpoint =
        host_policy::pds_endpoint(&document, waived).map_err(|unusable| match unusable {
            host_policy::PdsEndpointUnusable::NoneNamed => {
                anyhow::anyhow!("The DID document for {did} names no PDS endpoint")
            }
            host_policy::PdsEndpointUnusable::Refused { endpoint, reason } => anyhow::anyhow!(
                "The DID document for {did} names the PDS endpoint {endpoint}, which the \
                 endpoint policy refuses ({reason}). Set ATPMCP_ALLOW_INSECURE_ENDPOINTS=1 \
                 to log in to it anyway, as for a local development server"
            ),
        })?;
    let handle = document
        .handles()
        .map(|handle| handle.to_string())
        .unwrap_or_else(|| identifier.to_string());
    eprintln!("Resolved to {did} ({pds_endpoint})");

    eprintln!("Creating session...");
    let session = create_session(
        &request_client,
        &pds_endpoint,
        identifier,
        password.expose_secret(),
        None,
    )
    .await?;

    let account = accounts::Account {
        handle: handle.clone(),
        did: session.did.clone(),
        pds_endpoint: pds_endpoint.clone(),
        app_password: password.expose_secret().to_string(),
        access_jwt: session.access_jwt,
        refresh_jwt: session.refresh_jwt,
    };

    accounts::upsert_account(account)?;

    eprintln!("Logged in as {handle} ({})", session.did);

    // Where it went, resolved rather than described. A path printed here is
    // right on every platform and cannot drift from the code, which is what
    // the documentation did: it named the Linux location unconditionally.
    match accounts::config_path() {
        Ok(path) => eprintln!(
            "Stored in {} -- in plaintext: the app password, the access token \
             and the refresh token. Delete the file to revoke this machine's copy.",
            path.display()
        ),
        // The account was written, so a path that cannot be rendered now is
        // worth saying rather than swallowing, but it is not a login failure.
        Err(error) => eprintln!(
            "Stored in the shared atpxrpc account store, in plaintext \
             (could not resolve its path to print it: {error})"
        ),
    }

    Ok(())
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
        .with_writer(std::io::stderr)
        .with_ansi(false)
        .init();

    if let Some(command) = cli.command {
        match command {
            CliCommand::Login {
                identifier,
                password,
            } => return handle_login(&identifier, password).await,
        }
    }

    // Configuration is read before anything starts, and a value the server
    // cannot use stops it here with the variable named: an MCP host usually
    // keeps a server's stderr out of sight, so a warning would go unseen.
    let limits = Limits::from_env()?;
    let cache = Arc::new(BlobCache::from_env()?);
    let plc_hostname = default_plc_hostname()?;
    let dns_nameservers = context::dns_nameservers(context::env_value)?;

    tracing::info!(
        version = env!("CARGO_PKG_VERSION"),
        protocol = proto::PROTOCOL_VERSION,
        "Starting atpmcp MCP server."
    );

    // Built here and shared, and it does not stop the server when there is
    // no system DNS configuration to read, as in a scratch container. Most
    // tools need no DNS -- a CID, a TID, a schema, a did:plc -- and refusing
    // to start would take every one of them away over the few that resolve a
    // handle. Those are answered with an error saying to set DNS_NAMESERVERS,
    // in the tool result the caller reads, which an MCP host shows where it
    // hides a server's stderr; the resolver also logs a warning here. A
    // malformed DNS_NAMESERVERS is configuration, and was refused above.
    // On unless ATPMCP_ALLOW_INSECURE_ENDPOINTS is set; ServerContext::new
    // builds the same guard for the request and blob clients from the same
    // two values.
    let guard = context::AddressGuard::for_config(limits.allow_insecure_endpoints, &plc_hostname);
    if !guard.is_guarded() {
        tracing::warn!(
            "ATPMCP_ALLOW_INSECURE_ENDPOINTS is set: no client checks the addresses it connects to."
        );
    }
    let resolver = Arc::new(InnerIdentityResolver {
        dns_resolver: Arc::new(HickoryDnsResolver::create_resolver(&dns_nameservers)),
        http_client: context::identity_client(&guard)?,
        plc_hostname,
    });
    if cache.is_enabled() {
        tracing::info!(
            directory = ?cache.dir(),
            "Blob cache enabled."
        );
    } else {
        tracing::info!("Blob cache disabled; every read will fetch.");
    }
    cache.sweep().await;

    proto::serve::serve(
        tokio::io::stdin(),
        tokio::io::stdout(),
        resolver,
        cache,
        limits,
    )
    .await?;

    tracing::info!("atpmcp stopped.");
    Ok(())
}