#![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;
#[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>,
}
#[derive(Subcommand)]
enum CliCommand {
Login {
identifier: String,
#[arg(env = "ATPROTO_PASSWORD", hide_env_values = true)]
password: Option<String>,
},
}
fn default_plc_hostname() -> Result<String, errors::ConfigError> {
context::plc_hostname(context::env_value)
}
async fn handle_login(identifier: &str, password: Option<String>) -> anyhow::Result<()> {
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())
};
let dns_resolver = HickoryDnsResolver::create_resolver(&dns_nameservers);
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);
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()
),
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,
}
}
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."
);
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(())
}