Skip to main content

Crate server_less

Crate server_less 

Source
Expand description

Server-less - Composable derive macros for Rust

Server-less takes an impl-first approach: write your Rust methods, and derive macros project them into various protocols (HTTP, CLI, MCP, WebSocket).

§Quick Start

use server_less::prelude::*;

struct UserService {
    // your state
}

#[http]
#[cli(name = "users")]
#[mcp]
#[ws(path = "/ws")]
impl UserService {
    /// Create a new user
    async fn create_user(&self, name: String, email: String) -> Result<User, UserError> {
        // implementation
    }

    /// Get user by ID
    async fn get_user(&self, id: UserId) -> Option<User> {
        // implementation
    }

    /// List all users
    async fn list_users(&self, limit: Option<u32>) -> Vec<User> {
        // implementation
    }
}

This generates:

  • HTTP: POST /users, GET /users/{id}, GET /users (axum router)
  • CLI: users create-user --name X, users get-user <id> (clap)
  • MCP: Tools create_user, get_user, list_users (Model Context Protocol)
  • WebSocket: JSON-RPC methods over WebSocket (axum)

§Available Macros

MacroProtocolGenerated Methods
#[http]HTTP/RESThttp_router(), openapi_spec()
#[cli]Command Linecli_command(), cli_run()
#[mcp]MCPmcp_tools(), mcp_call(), mcp_call_async()
#[ws]WebSocketws_router(), ws_handle_message(), ws_handle_message_async()

§Naming Conventions

Method names infer HTTP methods and CLI subcommand structure:

PrefixHTTPCLI
create_*, add_*POST<cmd> create-*
get_*, fetch_*GET (single)<cmd> get-*
list_*, find_*GET (collection)<cmd> list-*
update_*, set_*PUT<cmd> update-*
delete_*, remove_*DELETE<cmd> delete-*

§Return Types

TypeHTTPCLIMCP/WS
T200 + JSONstdout JSONJSON result
Option<T>200 or 404stdout or exit 1result or null
Result<T, E>200 or errorstdout or stderrresult or error
()204silent{"success": true}
impl Stream<Item=T>SSEN/AN/A

§Async Methods

All macros support async methods:

#[mcp]
impl MyService {
    // Sync method - works with mcp_call() and mcp_call_async()
    pub fn sync_method(&self) -> String { ... }

    // Async method - use mcp_call_async() for proper await
    pub async fn async_method(&self) -> String { ... }
}

// Sync call (errors on async methods)
service.mcp_call("sync_method", json!({}));

// Async call (awaits async methods properly)
service.mcp_call_async("async_method", json!({})).await;

§SSE Streaming (HTTP)

Return impl Stream<Item=T> for Server-Sent Events:

#[http]
impl StreamService {
    // Note: Rust 2024 requires `+ use<>` to avoid lifetime capture
    pub fn stream_events(&self) -> impl Stream<Item = Event> + use<> {
        futures::stream::iter(vec![Event { ... }])
    }
}

§Feature Flags

Enable only what you need:

[dependencies]
server-less = { version = "0.1", default-features = false, features = ["http", "cli"] }

Available features:

  • mcp - MCP macro (no extra deps)
  • http - HTTP macro (requires axum)
  • cli - CLI macro (requires clap)
  • ws - WebSocket macro (requires axum, futures)
  • full - All features (default)

Re-exports§

pub use futures;
pub use async_graphql;
pub use async_graphql_axum;
pub use serde;
pub use serde_json;

Modules§

error
Error handling and protocol-specific error mapping.
extract
Context and parameter extraction types.
prelude
Prelude for convenient imports

Structs§

Context
Protocol-agnostic request context.
ErrorResponse
A generic error response that can be serialized
MethodInfo
Method metadata extracted from an impl block. Used internally by macros but exposed for advanced use cases.
OpenApiBuilder
Builder for composing OpenAPI specs from multiple sources.
OpenApiOperation
An OpenAPI operation (endpoint).
OpenApiParameter
An OpenAPI parameter.
OpenApiPath
An OpenAPI path with its operations.
OpenApiSchema
An OpenAPI schema definition.
ParamInfo
Parameter metadata
SchemaValidationError
Error type for schema validation failures.
WsSender
WebSocket sender for server-push messaging.

Enums§

ErrorCode
Protocol-agnostic error code that maps to HTTP status, gRPC code, CLI exit code, etc.
HttpMethod
HTTP method inferred from function name
OpenApiError
Errors that can occur during OpenAPI composition.

Traits§

IntoErrorCode
Trait for converting errors to protocol-agnostic error codes.

Functions§

infer_path
Infer URL path from method name

Attribute Macros§

asyncapi
Generate AsyncAPI specification for event-driven services.
capnp
Generate Cap’n Proto schema from an impl block.
cli
Generate a CLI application from an impl block.
connect
Generate Connect protocol schema from an impl block.
graphql
Generate GraphQL schema from an impl block using async-graphql.
graphql_enum
Define a GraphQL enum type.
graphql_input
Define a GraphQL input type.
grpc
Generate Protocol Buffers schema from an impl block.
http
Generate HTTP handlers from an impl block.
jsonrpc
Generate JSON-RPC 2.0 handlers over HTTP.
jsonschema
Generate JSON Schema from an impl block.
markdown
Generate Markdown API documentation from an impl block.
mcp
Generate MCP (Model Context Protocol) tools from an impl block.
openapi
Generate OpenAPI specification without HTTP routing.
openrpc
Generate OpenRPC specification for JSON-RPC services.
response
Helper attribute for method-level HTTP response customization.
route
Helper attribute for method-level HTTP route customization.
serve
Coordinate multiple protocol handlers into a single server.
smithy
Generate Smithy IDL schema from an impl block.
thrift
Generate Apache Thrift schema from an impl block.
ws
Generate WebSocket JSON-RPC handlers from an impl block.

Derive Macros§

ServerlessError
Derive macro for error types that implement IntoErrorCode.