The Complete Production SOP: How to Deploy and Run Axum Ergonomic Modular Web Framework for Rust in Autonomous AI Agents
Step-by-step SOP to install and run the Axum, Tokio, Tower, and Hyper framework skill in Codex, Claude Code, and Cursor with zero-drift Rust workflows.
Technical Overview & Architectural Context
Autonomous coding agents frequently encounter compile-time failures when architecting Rust web APIs with Axum. Common pitfalls include attempting to share application state across handlers without implementing Clone or thread-safe Arc pointers, ordering Tower middleware layers incorrectly so that extractors fail silently or early termination occurs, and confusing legacy Hyper 0.14 idioms with modern Axum 0.7 serve primitives. Without strict architectural boundaries, agents frequently output non-compiling extractors, unconstrained generic routes, or misconfigured async runtime bindings. The axum-tokio-tower-hyper-framework skill remedies this by enforcing deterministic SOP boundaries directly into agent context. It constrains LLMs like Claude Code, Codex, Cursor, and Windsurf to validated Rust idioms: utilizing axum::extract::State with strongly-typed application state, chaining Tower TraceLayer and CorsLayer in the exact downstream-to-upstream sequence required by the hyper/tokio stack, and running cargo check validation loops before reporting task completion.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into your agent runtime.
Autonomous agents locate deterministic procedural specifications by resolving files in standard skill directories. For Claude Code, Codex, and Cursor, registering the axum-tokio-tower-hyper-framework skill in your global or project-level `.agents/skills` repository allows the agent to ingest trigger rules, runtime compatibility schemas, and compiler verification rules upon session initialization.
mkdir -p ~/.agents/skills/axum-tokio-tower-hyper-framework && curl -fsSL https://askills.dev/api/skills/axum-tokio-tower-hyper-framework/raw -o ~/.agents/skills/axum-tokio-tower-hyper-framework/SKILL.md---
name: "axum-tokio-tower-hyper-framework"
description: "Build modular, type-safe web APIs in Rust built directly on Tokio, Tower, and Hyper."
metadata:
author: "Tokio"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "create axum router"
- "axum with_state extractor"
- "tower middleware axum"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Axum Ergonomic Modular Web Framework for Rust
Architects APIs with Axum: Router with nested route merging, type-safe extractors (Path, Query, Json, Extension), state management with with_state, Tower middleware layers, and WebSocket upgrades.
## When to Invoke
Invoke this skill whenever you need to:
- create axum router
- axum with_state extractor
- tower middleware axum
## Execution SOP & Rules
1. Create router: let app = Router::new().route('/users', get(list_users).post(create_user)).with_state(state);
2. Extract state and params: async fn get_user(State(state): State<AppState>, Path(id): Path<u64>) -> Result<Json<User>, StatusCode> { ... }.
3. Attach Tower middleware: app.layer(TraceLayer::new_for_http()).
4. Serve with tokio: let listener = tokio::net::TcpListener::bind('0.0.0.0:3000').await?; axum::serve(listener, app).await?;
## Verification Checklist
- Run local linting, syntax validation, and type-checks before reporting completion.
- Ensure all created or modified files adhere to workspace boundaries and avoid uncommitted secrets.
- Verify tests or build commands exit cleanly with return code 0.Symlink your `.agents/skills` directory across IDE roots (`ln -s ~/.agents/skills .cursor/skills`) so Cursor and Windsurf share the exact same version-controlled Rust SOPs without duplicating token overhead.
Do not elevate shell_exec permissions in SKILL.md. Keep execution sandboxed to workspace file mutations; allow cargo checks to trigger through standard IDE language server feedback loops.
Cargo Dependency Configuration & State Architecture
Ensure Cargo.toml contains compatible Axum 0.7, Tokio, and Tower dependencies with correct feature flags.
Axum 0.7 relies on Hyper 1.0 and Tower 0.5. Mismatched crates (e.g., pulling legacy `hyper = "0.14"` alongside `axum = "0.7"`) cause compiler trait incompatibilities in `axum::serve`. Ensure the agent initializes standard dependencies inside `Cargo.toml` before writing handler boilerplate.
cargo add axum tokio --features tokio/full,tokio/macros && cargo add tower tower-http --features tower-http/trace,tower-http/cors && cargo add serde --features serde/derive[dependencies]
axum = { version = "0.7", features = ["macros", "ws"] }
tokio = { version = "1.38", features = ["full"] }
tower = { version = "0.5", features = ["util"] }
tower-http = { version = "0.6", features = ["trace", "cors"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }Instruct the agent to wrap mutable application state in `Arc<RwLock<T>>` or use database connection pools (like `sqlx::Pool`) that natively implement `Clone` to eliminate ownership transfer issues in Axum handlers.
Avoid placing sensitive credentials into default connection strings inside `AppState`. Use `std::env::var` during runtime initialization rather than baking default values into source.
Intent Matching & Router Construction
Trigger deterministic Axum modular router assembly using explicit skill triggers.
Provide high-intent prompts targeting the frontmatter triggers (`create axum router`, `axum with_state extractor`, `tower middleware axum`). This forces the agent to bypass generalized web framework assumptions and apply the strict four-step pattern mandated in the skill SOP.
use axum::{
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
routing::{get, post},
Json,
Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tower_http::trace::TraceLayer;
#[derive(Clone)]
pub struct AppState {
pub db_name: Arc<String>,
}
#[derive(Serialize, Deserialize)]
pub struct User {
pub id: u64,
pub username: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt::init();
let state = AppState {
db_name: Arc::new("production_db".to_string()),
};
let app = Router::new()
.route("/users", get(list_users).post(create_user))
.route("/users/:id", get(get_user))
.layer(TraceLayer::new_for_http())
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
tracing::info!("Server running on port 3000");
axum::serve(listener, app).await?;
Ok(())
}
async fn list_users(State(state): State<AppState>) -> impl IntoResponse {
Json(vec![User { id: 1, username: format!("user_{}", state.db_name) }])
}
async fn create_user(
State(_state): State<AppState>,
Json(payload): Json<User>,
) -> Result<(StatusCode, Json<User>), StatusCode> {
Ok((StatusCode::CREATED, Json(payload)))
}
async fn get_user(
State(_state): State<AppState>,
Path(id): Path<u64>,
) -> Result<Json<User>, StatusCode> {
Ok(Json(User {
id,
username: "alice".to_string(),
}))
}Chain `.layer()` before `.with_state()` or apply `.with_state()` directly to sub-routers before merging them into a root router via `nest()` to avoid type-erasure compile errors.
Notice that Axum 0.7 does not accept `axum::Server::bind`. Attempting to use `axum::Server` will trigger immediate deprecation compilation errors; use `axum::serve(listener, app)` instead.
Verification, Linting & Type-Safety Quality Gate
Execute automated compiler type checks and clippy lints to validate handler signatures before accepting deliverables.
The skill SOP mandates running local syntax validation and build verification before concluding task execution. Because Rust extractors depend on compile-time type inference, `cargo check` and `cargo test` act as the deterministic self-healing loop for the agent.
cargo check --all-targets && cargo clippy -- -D warningsInstruct the agent in your prompt to inspect compile errors using `cargo check --message-format=short` to avoid flooding the context window with verbose rustc diagnostic diagnostics.
Do not let agents bypass compiler checks with `#![allow(unused)]` or unconstrained wildcard imports. Ensure `cargo check` passes with clean return code 0.
Real-World Scenario: Building a Type-Safe REST API for Inventory Items with Axum, Tower Middleware, and Tokio
“Using the axum-tokio-tower-hyper-framework skill, create axum router with routes for inventory items. Include axum with_state extractor to share an Arc<InventoryState>, apply tower middleware axum for HTTP request tracing, and bind the server using Tokio 1.x and modern axum::serve.”
Runtime Troubleshooting & Failure Modes
Root Cause: Occurs when handler function signatures fail Axum extractor rules. Either extractors that consume the request body (such as Json or String) are placed before non-consuming extractors (Path, Query, State), or the return type does not implement `IntoResponse`, or `AppState` does not implement `Clone`.
Ensure `#[derive(Clone)]` is applied to `AppState`. Reorder parameters so consuming extractors (`Json<T>`) are placed LAST in the argument list: `async fn handler(State(state): State<AppState>, Path(id): Path<u64>, Json(body): Json<Payload>) -> impl IntoResponse`.Root Cause: The agent generated obsolete Axum 0.6 syntax. In Axum 0.7 and Hyper 1.0, `axum::Server` was removed in favor of `axum::serve` coupled with a standard `tokio::net::TcpListener`.
Replace `axum::Server::bind(&addr).serve(app.into_make_service()).await` with: `let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?; axum::serve(listener, app).await?;`Frequently Asked Questions (Axum Ergonomic Modular Web Framework for Rust SOP)
Q:Can I use Axum Ergonomic Modular Web Framework for Rust across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification. Runtimes including Codex CLI/Desktop, Claude Code, Cursor, and Windsurf parse the declarative YAML frontmatter and invoke procedural rules deterministically whenever Axum-related keywords or triggers are detected.
Q:How does Axum Ergonomic Modular Web Framework for Rust prevent context window overflow during long agent sessions?
Rather than injecting thousands of tokens of entire Axum documentation into system prompts, the skill provides a tight four-step execution SOP and explicit compiler verification gates. This keeps context usage under 350 tokens while maintaining a 98% first-pass compile success rate.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a Security Score of 98/100. It requires read and workspace-scoped write filesystem permissions to modify Rust source files, but prohibits network access and unconstrained shell execution outside standard workspace build tools.
Ready to equip your autonomous agent with Axum Ergonomic Modular Web Framework for Rust?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.