TurboMCP Macros
Zero-boilerplate procedural macros for ergonomic MCP server development with automatic schema generation and compile-time validation.
Overview
turbomcp-macros
provides the procedural macros that make TurboMCP development effortless. These macros eliminate boilerplate code while providing compile-time validation, automatic schema generation, and type-safe parameter handling.
Key Features
🎯 Zero Boilerplate Design
- Automatic registration - Tools and resources registered automatically
- Schema generation - JSON schemas generated from Rust types
- Parameter extraction - Type-safe parameter conversion and validation
- Error handling - Automatic error type conversion and propagation
- Ergonomic Macros -
elicit!
for user input, seamless Context API delegation
✅ Compile-Time Validation
- Type checking - Parameter types validated at compile time
- Schema validation - Generated schemas validated for correctness
- IDE support - Full IntelliSense and error reporting
- Macro hygiene - Proper variable scoping and name collision prevention
📋 Automatic Schema Generation
- JSON Schema - Complete JSON Schema generation from Rust types
- Parameter documentation - Extract documentation from function signatures
- Type introspection - Deep analysis of parameter and return types
- Schema caching - Efficient schema generation and reuse
🔍 Context Injection
- Flexible positioning - Context parameter can appear anywhere in function signature
- Send-safe - Proper Send/Sync bounds for async context
- Type safety - Compile-time validation of context usage
- Optional context - Functions can opt-in or out of context injection
Architecture
┌─────────────────────────────────────────────┐
│ TurboMCP Macros │
├─────────────────────────────────────────────┤
│ Procedural Macro Processing │
│ ├── #[server] trait implementation │
│ ├── #[tool] function registration │
│ ├── #[resource] handler registration │
│ └── #[prompt] template registration │
├─────────────────────────────────────────────┤
│ Schema Generation Engine │
│ ├── Type introspection │
│ ├── JSON Schema creation │
│ ├── Parameter validation │
│ └── Documentation extraction │
├─────────────────────────────────────────────┤
│ Code Generation │
│ ├── Handler registration code │
│ ├── Parameter extraction logic │
│ ├── Error conversion helpers │
│ └── Schema metadata functions │
├─────────────────────────────────────────────┤
│ Compile-Time Validation │
│ ├── Type compatibility checking │
│ ├── Parameter validation │
│ ├── Context injection validation │
│ └── Schema correctness verification │
└─────────────────────────────────────────────┘
Core Macros
MCP 2025-06-18 Enhanced Macros (v1.1.0)
New macros for the latest MCP protocol features:
elicit!
- Elegant User Input (NEW)
use *;
use ElicitationSchema;
async
#[elicitation]
- Attribute-based Elicitation
async
#[completion]
- Intelligent Autocompletion
async
#[template]
- Resource Templates
async
#[ping]
- Health Monitoring
async
#[server]
- Server Implementation
Automatically implements the MCP server trait for a struct:
use *;
;
// Generated code includes:
// - Automatic trait implementation
// - Handler registration
// - Schema generation
// - Transport integration
Generated Capabilities:
- Automatic
MCP
trait implementation - Handler registry setup with all annotated functions
- Schema generation for all tools/resources/prompts
- Transport method implementations (
run_stdio
,run_http
, etc.)
#[tool]
- Tool Registration
Transforms functions into MCP tools with automatic parameter handling:
async
Generated Features:
- JSON Schema with parameter descriptions
- Type-safe parameter extraction from JSON
- Optional parameter handling
- Context injection (can appear anywhere in signature)
- Automatic error conversion
- Tool metadata functions
#[resource]
- Resource Registration
Creates URI template-based resource handlers:
async
URI Template Features:
- Automatic URI pattern matching
- Path parameter extraction
- Query parameter support
- URI validation
- Resource metadata generation
#[prompt]
- Prompt Template Registration
Creates prompt templates with parameter substitution:
async
Advanced Features
Context Injection
The Context
parameter can appear anywhere in the function signature:
// Context first
async
// Context in middle
async
// Context last
async
// No context
async
Parameter Descriptions
Use the #[description]
attribute for rich parameter documentation:
async
Generated Schema:
Custom Types and Schema Generation
The macros automatically generate schemas for custom types:
async
Helper Macros
elicit!
- Ergonomic Elicitation Macro (NEW)
The elicit!
macro provides elegant server-initiated user input:
use *;
use ElicitationSchema;
// Build schema with type safety
let schema = new
.add_string_property
.add_boolean_property;
// Clean, simple macro call
let result = elicit!.await?;
Key Benefits:
- Zero Protocol Complexity - Handles all MCP elicitation protocol details
- Type Safe - Compile-time validation of context and schema
- Ergonomic - Simple 3-parameter syntax:
(context, message, schema)
- Error Handling - Automatic error conversion and propagation
Error Handling Macros
Ergonomic error creation macros:
use *;
async
async
Metadata Access
The macros generate metadata access functions:
;
// Generated metadata functions
let = example_tool_metadata;
assert_eq!;
assert_eq!;
// schema contains the complete JSON Schema
// Test the generated function directly
let result = MyServer.test_tool_call.await?;
Macro Attributes
Tool Attributes
Attribute | Description | Example |
---|---|---|
#[description] |
Parameter description | #[description("User ID")] |
#[default] |
Default value for optional parameters | #[default(10)] |
#[allowed] |
Allowed string values (enum) | #[allowed("read", "write")] |
#[range] |
Numeric range validation | #[range(0, 100)] |
#[pattern] |
Regex pattern validation | #[pattern(r"^\d{3}-\d{2}-\d{4}$")] |
Resource Attributes
Attribute | Description | Example |
---|---|---|
URI template | Resource URI pattern | #[resource("file://{path}")] |
#[mime_type] |
Content MIME type | #[mime_type("text/plain")] |
#[binary] |
Binary resource flag | #[binary(true)] |
Generated Code Examples
Tool Registration
Input:
async
Generated (simplified):
// Metadata function
// Handler registration
async
// Direct test function
pub async
IDE Integration
The macros provide excellent IDE support:
- IntelliSense - Full auto-completion for generated functions
- Error highlighting - Compile-time error detection
- Type information - Hover information for generated code
- Go to definition - Navigate to macro-generated implementations
- Refactoring support - Safe renaming and extraction
Testing Support
The macros generate testing utilities:
Performance
The macros generate efficient code:
- Zero runtime overhead - All processing happens at compile time
- Optimized registration - Efficient handler lookup and dispatch
- Schema caching - Schemas generated once and reused
- Minimal allocations - Smart parameter extraction with minimal copying
Development
Building
# Build macros crate
# Test macro expansion
# Run macro tests
Debugging Macros
# See expanded macro code
# Debug specific macro
RUST_LOG=debug
Related Crates
- turbomcp - Main framework (uses these macros)
- turbomcp-core - Core types and utilities
- turbomcp-server - Server framework
- turbomcp-protocol - MCP protocol implementation
External Resources
- The Rust Reference - Procedural Macros - Rust macro documentation
- JSON Schema Specification - Schema format specification
- serde Documentation - Serialization framework used by macros
License
Licensed under the MIT License.
Part of the TurboMCP high-performance Rust SDK for the Model Context Protocol.