mcapi 0.3.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation

mcapi

Crates.io Documentation CI License MSRV

A unified, clean-room async Rust client for the Minecraft HTTP API ecosystem — covering Mojang / Microsoft Auth, Modrinth, CurseForge, Yggdrasil / authlib-injector, Blessing Skin / CSL, Mod Loaders, BMCLAPI, and Java Runtimes in a single feature-gated crate.

Highlights

  • Modular & Feature-Gated: Enable only the platform modules and TLS backend you need via Cargo features.
  • Shared HttpClient (Arc-backed): Configure connection pooling, User-Agent, timeouts, mirror routing, and retry policies once through McApi (or HttpClient) and clone zero-cost across every client.
  • Unified Error Handling: One #[non_exhaustive] mcapi::Error and mcapi::Result<T> across all modules, with helpers such as status_code(), api_status_error(), is_not_found(), and is_rate_limited(). Public dependency crates (reqwest, url, jiff, uuid, rsa, serde_json) are re-exported under mcapi::reexports so callers never hit version-mismatch errors.
  • Mirror Routing & Strict Credential Isolation: Built-in Mirror::Bmclapi, Mirror::Mcim, Mirror::China, Mirror::Combined, and Mirror::Custom prefix rewriting with multi-candidate fallback to official origins. Authenticated and mutating calls (client.authed(token)) always bypass mirrors so tokens and API keys never leak to third-party hosts.
  • Resilient & Forward-Compatible: Parses Retry-After and X-Ratelimit-* headers, supports opt-in 429/5xx/transport backoff retries with jitter, blocks HTTPS-to-HTTP redirect downgrades, uses forward-compatible Unknown enum variants, and redacts all credentials as [REDACTED] in Debug output.

Installation

Add mcapi with the default feature set (full + tls-aws-lc):

cargo add mcapi
[dependencies]
mcapi = "0.2"

Or pick only the modules and TLS backend you need (for example, a launcher using Mojang, Modrinth, Loaders, and Java Runtimes):

[dependencies]
mcapi = { version = "0.2", default-features = false, features = ["mojang", "modrinth", "loaders", "java", "tls-aws-lc"] }

Quick Start

1. Shared McApi Entry Point

Share one reqwest::Client connection pool, mirror strategy, and retry policy across all platform clients:

use std::time::Duration;

use mcapi::modrinth::models::{Facet, FacetBuilder, ProjectType, SearchQuery};
use mcapi::{McApi, Mirror, ResiliencePolicy};

#[tokio::main]
async fn main() -> mcapi::Result<()> {
    let api = McApi::builder()
        .user_agent("my-launcher/1.0 (contact@example.com)")
        .mirror(Mirror::China)
        .resilience(
            ResiliencePolicy::new()
                .auto_retry_rate_limit(true)
                .retry_5xx(true)
                .fallback_to_official(true),
        )
        .timeout(Duration::from_secs(20))
        .build()?;

    // Mojang Piston Meta
    let manifest = api.mojang().version_manifest().await?;
    println!("Latest Minecraft: {}", manifest.latest.release);

    // Modrinth CNF facet search
    let query = SearchQuery::new()
        .query("sodium")
        .facets(FacetBuilder::new().and(Facet::ProjectType(ProjectType::Mod)))
        .limit(5);
    let results = api.modrinth().search(&query).await?;
    println!("Modrinth hits: {}", results.hits.len());

    // Mod Loaders (Fabric / Quilt / Forge / NeoForge) & Java Runtimes
    let fabric = api.loaders().fabric_loaders_for_mc("1.21.1").await?;
    let adoptium = api.java().adoptium_available_releases().await?;
    println!(
        "Fabric loaders: {}, Adoptium LTS: Java {}",
        fabric.len(),
        adoptium.most_recent_lts
    );

    Ok(())
}

2. Authenticated Operations (client.authed(token))

Public read endpoints live directly on <Platform>Client. Protected and mutating endpoints live on client.authed(token) (Authed<'_>), which sends requests directly to official origins and never routes credentials through mirrors:

use mcapi::mojang::MojangClient;

async fn check_name_change(ms_access_token: &str) -> mcapi::Result<()> {
    let mojang = MojangClient::new()?;
    let session = mojang.login_full_from_ms_token(ms_access_token).await?;

    // Sent directly to official Minecraft Services (bypasses any configured mirror)
    let authed = mojang.authed(&session.minecraft.access_token);
    let name_info = authed.name_change_info().await?;
    println!("Can change name: {}", name_info.name_change_allowed);

    Ok(())
}

3. Custom Mirrors & Keyless CurseForge Mirrors

Combine built-in presets or define custom URL prefix rewrites via Mirror::Custom:

use mcapi::{McApi, Mirror, ResiliencePolicy, RewriteRule};

async fn custom_mirror_example() -> mcapi::Result<()> {
    let mirror = Mirror::Custom(vec![RewriteRule::new(
        "https://api.modrinth.com",
        "https://mirror.example.com/modrinth",
    )]);

    let api = McApi::builder()
        .mirror(mirror)
        .resilience(ResiliencePolicy::new().fallback_to_official(true))
        .build()?;

    let project = api.modrinth().project("sodium").await?;
    println!("Loaded project: {}", project.title);

    Ok(())
}

When using a mirror that rewrites https://api.curseforge.com (such as Mirror::Mcim or Mirror::China), api.curseforge(None) constructs a keyless mirror client (skipping official api.curseforge.com fallback since no key is configured). If an API key is provided via api.curseforge(Some(key)), x-api-key is only attached to direct unrewritten requests targeting base_url (including custom gateways configured via with_base_url) and is never forwarded to Mirror-rewritten hosts.

Mirror Routing

Preset Upstream Coverage
Mirror::Official (default) Official upstream endpoints directly
Mirror::Bmclapi Mojang Piston/Launcher/Assets/Libraries, Fabric, Quilt, Forge, NeoForge, LiteLoader, and authlib-injector via BMCLAPI
Mirror::Mcim Modrinth API/CDN and CurseForge API/CDN via MCIMirror
Mirror::China Zero-allocation preset combining Mirror::Bmclapi + Mirror::Mcim
Mirror::Combined(Vec<Mirror>) Ordered multi-mirror fallback chain (first matching rule wins, falling through candidates on failure)
Mirror::Custom(Vec<RewriteRule>) User-defined segment-boundary URL prefix rewrite rules

Enabling ResiliencePolicy::fallback_to_official(true) automatically falls back to the official origin if a mirror candidate fails with a transport error, HTTP 404, HTTP 5xx, or malformed JSON/XML response.

Feature Flags

Platform Modules

Feature Default Description
full ✅ Enables all standard platform modules (curseforge, modrinth, mojang, yggdrasil, yggdrasil-authlib, blessing, loaders, bmclapi, java); excludes opt-in write/crypto/tracing features
mojang via full Microsoft OAuth2 (Device Code + PKCE) → XBL → XSTS (XErr) → Minecraft login, UUID/session lookup, Minecraft Services, Piston Meta, Launcher Content (news.json, javaPatchNotes.json)
modrinth via full Modrinth v2 REST API (CNF facet search, projects, versions, SHA-1/512 hash lookup & update, tags, statistics, authenticated reads)
modrinth-write ❌ Opt-in Modrinth v2 creator/mutation & multipart upload APIs (create_project, create_version, team/user management, payout withdrawal; enables reqwest/multipart)
curseforge via full CurseForge Core API v1/v2 (search, mods/files, Murmur2 fingerprint / fingerprint_file / fingerprint_reader, Minecraft versions/loaders, keyless mirror mode)
curseforge-cdn-fallback ❌ Opt-in unofficial edge.forgecdn.net fallback URL synthesis (File::edge_download_url) when download_url is omitted (undocumented layout; bypasses author opt-out / ToS risk)
yggdrasil via full Yggdrasil auth/session/profile client and ALI auto-discovery (YggdrasilClient::discover)
yggdrasil-authlib via full authlib-injector build metadata client (AuthlibInjectorClient)
yggdrasil-verify ❌ Opt-in RSA-SHA1 (SHA1withRSA) signature verification (ProfileProperty::verify_signature, GameProfile::decode_and_verify_textures)
blessing via full Blessing Skin v6 REST API (login, skinlib, upload/manage, closet, players) + CustomSkinLoader endpoints
loaders via full Fabric Meta v2, Quilt Meta v3, Forge (Maven XML / Promotions), NeoForge (Maven XML / 1.20.1 legacy), LiteLoader official manifest
bmclapi via full Dedicated BmclapiClient for BMCLAPI Forge, NeoForge, LiteLoader, and OptiFine index endpoints
java via full Mojang Official Java Runtimes (all.json + file manifests), Adoptium Temurin v3, Azul Zulu Metadata v1

Shared & Optional Capabilities

Feature Default Description
http via modules Shared Arc-backed HttpClient, Mirror, ResiliencePolicy, McApi, and McApiBuilder
profile via mojang/yggdrasil Shared ProfileProperty and base64 textures payload decoding
stream ❌ Enables reqwest/stream (Response::bytes_stream); HttpClient::stream + Response::chunk() already work without it
tracing ❌ Opt-in tracing debug/warn instrumentation for outbound requests, retries, and mirror fallback

TLS Backends

Select one TLS backend whenever any HTTP feature is enabled:

Feature Default Backing reqwest Feature
tls-aws-lc ✅ reqwest/rustls (aws-lc-rs)
tls-native ❌ reqwest/native-tls
tls-native-vendored ❌ reqwest/native-tls-vendored
tls-rustls-no-provider ❌ reqwest/rustls-no-provider (supply your own rustls crypto provider)

MSRV

The Minimum Supported Rust Version is 1.88.0 (Rust 2024 edition), verified in CI on every push and pull request.

Contributing

  • Read CONTRIBUTING.md for local setup, offline testing with MockServer, feature-matrix verification commands, and commit conventions.
  • Read AGENTS.md for architecture invariants and coding conventions.
  • See CHANGELOG.md for release history.

License

Dual-licensed under either of:

at your option.