pforge-codegen
Code generation engine for pforge - converts YAML configuration into optimized Rust code.
Features
- YAML → Rust: Transform declarative configuration into type-safe Rust code
- Handler Registry: Generate optimized handler registration code
- Schema Generation: Automatic JSON Schema generation for tool parameters
- Type Safety: Compile-time validation of generated code
- Zero Runtime Cost: All code generation happens at build time
- Optimized Output: Clean, idiomatic Rust code with minimal overhead
Installation
Usage
Generate from Configuration
use generate_server;
use ForgeConfig;
let config: ForgeConfig = from_str?;
// Generate Rust code
let generated_code = generate_server?;
// Write to file
write?;
What Gets Generated
For this YAML configuration:
forge:
name: calculator
version: 0.1.0
tools:
- type: native
name: add
description: "Add two numbers"
handler:
path: handlers::add_handler
params:
a:
b:
The codegen generates:
// Handler registration
// JSON Schema for parameters
// Server initialization
pub async
Code Generation Pipeline
- Parse Configuration: Load and validate YAML using
pforge-config - AST Generation: Build Rust Abstract Syntax Tree
- Optimization: Apply compiler optimizations
- Code Emission: Generate clean, formatted Rust code
Generated Components
Handler Registration
Generates optimized registry initialization:
let mut registry = new;
registry.register?;
registry.register?;
Type Definitions
Creates type-safe parameter structs:
Schema Generation
Automatic JSON Schema for MCP protocol:
Transport Setup
Generates transport-specific initialization:
// For stdio transport
start_stdio_server.await?;
// For SSE transport
start_sse_server.await?;
// For WebSocket transport
start_ws_server.await?;
CLI Integration
The code generator is used by pforge-cli during the build process:
# Automatically runs codegen
# Or explicitly
Advanced Usage
Custom Templates
Provide custom code generation templates:
use ;
let config = CodegenConfig ;
let code = generate_with_config?;
Inline Handlers
Generate handlers with inline logic:
tools:
- type: native
name: echo
description: "Echo input"
handler:
inline: |
Ok(json!({ "output": params["input"] }))
params:
input:
Generates:
Generated Code Quality
All generated code follows Rust best practices:
- ✅ Formatted: Uses
rustfmtfor consistent style - ✅ Clippy Clean: Passes
clippywith no warnings - ✅ Type Safe: Full type inference and checking
- ✅ Documented: Includes doc comments from YAML descriptions
- ✅ Optimized: Dead code elimination and inlining hints
Performance
The code generator is designed for fast build times:
- < 10ms for typical configurations (< 10 tools)
- < 100ms for large configurations (100+ tools)
- Incremental: Only regenerates when configuration changes
Documentation
License
MIT