warp
Warp Rust web framework using filters. Covers routing, filters, rejection, WebSocket, and TLS. Use for composable, type-safe Rust APIs. USE WHEN: user mentions "warp", "rust filters", "composable rust api", asks about "warp filters", "warp rejection", "filter composition rust", "rust hyper warp", "warp websocket" DO NOT USE FOR: Axum projects - use `axum` instead, Actix-web projects - use `actix-web` instead, Rocket projects - use `rocket` instead, non-Rust backends
What this skill does
# Warp Core Knowledge
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `warp` for comprehensive documentation.
## Basic Setup
```toml
# Cargo.toml
[dependencies]
warp = "0.3"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
```
```rust
use warp::Filter;
#[tokio::main]
async fn main() {
let hello = warp::path::end()
.map(|| "Hello, World!");
warp::serve(hello)
.run(([127, 0, 0, 1], 8080))
.await;
}
```
## Filters
### Path Filters
```rust
use warp::Filter;
// Static path
let index = warp::path::end()
.map(|| "Index");
// Path segment
let users = warp::path("users")
.and(warp::path::end())
.map(|| "Users list");
// Path parameter
let user = warp::path("users")
.and(warp::path::param::<u32>())
.and(warp::path::end())
.map(|id: u32| format!("User {}", id));
// Multiple parameters
let post = warp::path("users")
.and(warp::path::param::<u32>())
.and(warp::path("posts"))
.and(warp::path::param::<u32>())
.and(warp::path::end())
.map(|user_id: u32, post_id: u32| {
format!("User {} Post {}", user_id, post_id)
});
```
### Method Filters
```rust
let get_users = warp::get()
.and(warp::path("users"))
.and(warp::path::end())
.map(|| "Get users");
let create_user = warp::post()
.and(warp::path("users"))
.and(warp::path::end())
.map(|| "Create user");
let update_user = warp::put()
.and(warp::path("users"))
.and(warp::path::param::<u32>())
.and(warp::path::end())
.map(|id: u32| format!("Update user {}", id));
let delete_user = warp::delete()
.and(warp::path("users"))
.and(warp::path::param::<u32>())
.and(warp::path::end())
.map(|id: u32| format!("Delete user {}", id));
// Combine routes
let routes = get_users
.or(create_user)
.or(update_user)
.or(delete_user);
```
### Body Filters
```rust
use serde::{Deserialize, Serialize};
use warp::Filter;
#[derive(Deserialize, Serialize)]
struct CreateUser {
name: String,
email: String,
}
// JSON body
let create_user = warp::post()
.and(warp::path("users"))
.and(warp::body::json::<CreateUser>())
.map(|user: CreateUser| {
warp::reply::json(&user)
});
// With size limit
let create_user_limited = warp::post()
.and(warp::path("users"))
.and(warp::body::content_length_limit(1024 * 16))
.and(warp::body::json::<CreateUser>())
.map(|user: CreateUser| {
warp::reply::json(&user)
});
```
### Query Filters
```rust
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
per_page: Option<u32>,
}
let list_users = warp::get()
.and(warp::path("users"))
.and(warp::query::<Pagination>())
.map(|pagination: Pagination| {
let page = pagination.page.unwrap_or(1);
format!("Page {}", page)
});
```
### Header Filters
```rust
let with_auth = warp::header::<String>("authorization")
.map(|auth: String| format!("Auth: {}", auth));
// Optional header
let with_optional_header = warp::header::optional::<String>("x-custom")
.map(|custom: Option<String>| {
custom.unwrap_or_else(|| "default".to_string())
});
```
## Handlers
### Async Handlers
```rust
async fn list_users_handler() -> Result<impl warp::Reply, warp::Rejection> {
let users = fetch_users().await;
Ok(warp::reply::json(&users))
}
let list_users = warp::get()
.and(warp::path("users"))
.and_then(list_users_handler);
```
### With State
```rust
use std::sync::Arc;
use tokio::sync::Mutex;
struct AppState {
db_pool: PgPool,
counter: Mutex<u32>,
}
fn with_state(
state: Arc<AppState>,
) -> impl Filter<Extract = (Arc<AppState>,), Error = std::convert::Infallible> + Clone {
warp::any().map(move || state.clone())
}
async fn get_count(state: Arc<AppState>) -> Result<impl warp::Reply, warp::Rejection> {
let count = state.counter.lock().await;
Ok(warp::reply::json(&serde_json::json!({ "count": *count })))
}
#[tokio::main]
async fn main() {
let state = Arc::new(AppState {
db_pool: create_pool().await,
counter: Mutex::new(0),
});
let count_route = warp::get()
.and(warp::path("count"))
.and(with_state(state.clone()))
.and_then(get_count);
warp::serve(count_route)
.run(([127, 0, 0, 1], 8080))
.await;
}
```
## Rejections and Error Handling
### Custom Rejection
```rust
use warp::reject::Reject;
#[derive(Debug)]
struct NotFound;
impl Reject for NotFound {}
#[derive(Debug)]
struct Unauthorized;
impl Reject for Unauthorized {}
#[derive(Debug)]
struct BadRequest(String);
impl Reject for BadRequest {}
async fn get_user(id: u32) -> Result<impl warp::Reply, warp::Rejection> {
match find_user(id).await {
Some(user) => Ok(warp::reply::json(&user)),
None => Err(warp::reject::custom(NotFound)),
}
}
```
### Rejection Handler
```rust
use warp::http::StatusCode;
#[derive(Serialize)]
struct ErrorResponse {
error: String,
message: String,
}
async fn handle_rejection(err: warp::Rejection) -> Result<impl warp::Reply, std::convert::Infallible> {
let (code, message) = if err.is_not_found() {
(StatusCode::NOT_FOUND, "Not Found")
} else if let Some(_) = err.find::<NotFound>() {
(StatusCode::NOT_FOUND, "Resource not found")
} else if let Some(_) = err.find::<Unauthorized>() {
(StatusCode::UNAUTHORIZED, "Unauthorized")
} else if let Some(e) = err.find::<BadRequest>() {
(StatusCode::BAD_REQUEST, &e.0 as &str)
} else if let Some(_) = err.find::<warp::reject::MethodNotAllowed>() {
(StatusCode::METHOD_NOT_ALLOWED, "Method not allowed")
} else {
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
};
let json = warp::reply::json(&ErrorResponse {
error: code.to_string(),
message: message.to_string(),
});
Ok(warp::reply::with_status(json, code))
}
// Apply to routes
let routes = get_users
.or(create_user)
.recover(handle_rejection);
```
## WebSocket
```rust
use warp::ws::{Message, WebSocket};
use futures::{StreamExt, SinkExt};
async fn handle_ws(ws: WebSocket) {
let (mut tx, mut rx) = ws.split();
while let Some(result) = rx.next().await {
match result {
Ok(msg) => {
if msg.is_text() {
let text = msg.to_str().unwrap();
let reply = Message::text(format!("Echo: {}", text));
if tx.send(reply).await.is_err() {
break;
}
} else if msg.is_close() {
break;
}
}
Err(e) => {
eprintln!("WebSocket error: {}", e);
break;
}
}
}
}
let ws_route = warp::path("ws")
.and(warp::ws())
.map(|ws: warp::ws::Ws| {
ws.on_upgrade(handle_ws)
});
```
### Broadcast with Channels
```rust
use tokio::sync::broadcast;
async fn handle_ws_broadcast(
ws: WebSocket,
tx: broadcast::Sender<String>,
) {
let mut rx = tx.subscribe();
let (mut ws_tx, mut ws_rx) = ws.split();
// Spawn receiver task
let send_task = tokio::spawn(async move {
while let Ok(msg) = rx.recv().await {
if ws_tx.send(Message::text(msg)).await.is_err() {
break;
}
}
});
// Handle incoming messages
while let Some(result) = ws_rx.next().await {
if let Ok(msg) = result {
if msg.is_text() {
let _ = tx.send(msg.to_str().unwrap().to_string());
}
}
}
send_task.abort();
}
```
## TLS
```rust
#[tokio::main]
async fn main() {
let routes = warp::path::end().map(|| "Hello, TLS!");
warp::serve(routes)
.tls()
.cert_path("cert.pem")
.key_path("key.pem")
.run(([0, 0,Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.