OpenRouter API Client Library
A production-ready Rust client for the OpenRouter API with comprehensive security, ergonomic design, and extensive testing. The library uses a type‑state builder pattern for compile-time configuration validation, ensuring robust and secure API interactions.
Features
🏗️ Architecture & Safety
- Type‑State Builder Pattern: Compile-time configuration validation ensures all required settings are provided before making requests
- Secure Memory Management: API keys are automatically zeroed on drop using the
zeroize
crate for enhanced security - Comprehensive Error Handling: Centralized error management with safe error message redaction to prevent sensitive data leakage
- Modular Organization: Clean separation of concerns across modules for models, API endpoints, types, and utilities
🚀 Ergonomic API Design
- Convenient Constructors: Quick setup with
from_api_key()
,from_env()
,quick()
, andproduction()
methods - Flexible Configuration: Fluent builder pattern with timeout, retry, and header configuration
- Environment Integration: Automatic API key loading from
OPENROUTER_API_KEY
orOR_API_KEY
environment variables
🔒 Security & Reliability
- Memory Safety: Secure API key handling with automatic memory zeroing
- Response Redaction: Automatic sanitization of error messages to prevent sensitive data exposure
- Streaming Safety: Buffer limits and backpressure handling for streaming responses
- Input Validation: Comprehensive validation of requests and parameters
🌐 OpenRouter API Support
- Chat Completions: Full support for OpenRouter's chat completion API with streaming
- Text Completions: Traditional text completion endpoint with customizable parameters
- Tool Calling: Define and invoke function tools with proper validation
- Structured Outputs: JSON Schema validation for structured response formats
- Web Search: Type-safe web search API integration
- Provider Preferences: Configure model routing, fallbacks, and provider selection
📡 Model Context Protocol (MCP)
- MCP Client: Full JSON-RPC client implementation for the Model Context Protocol
- Resource Access: Retrieve resources from MCP servers
- Tool Invocation: Execute tools provided by MCP servers
- Context Integration: Seamless context sharing between applications and LLMs
🧪 Quality & Testing
- 100% Test Coverage: Comprehensive unit and integration test suite
- CI/CD Pipeline: Automated quality gates with formatting, linting, security audits, and documentation checks
- Production Ready: Extensive error handling, retry logic, and timeout management
Getting Started
Installation
Add the following to your project's Cargo.toml
:
# With optional tracing support for better error logging
Available Features:
rustls
(default): Use rustls for TLSnative-tls
: Use system TLStracing
: Enhanced error logging with tracing support
Ensure that you have Rust installed (tested with Rust v1.83.0) and that you're using Cargo for building and testing.
Quick Start Examples
Simple Chat Completion
use ;
use ;
async
Production Configuration
use ;
async
Custom Configuration
use ;
use Duration;
async
Provider Preferences Example
use ;
use ;
use ;
use json;
async
Model Context Protocol (MCP) Client Example
use ;
use ;
async
Text Completion Example
use ;
use CompletionRequest;
use json;
async
Streaming Chat Example
use ;
use ;
use StreamExt;
use Write;
async
Model Context Protocol (MCP) Client
The library includes a client implementation for the Model Context Protocol, which is an open protocol that standardizes how applications provide context to LLMs.
Key features of the MCP client include:
- JSON-RPC Communication: Implements the JSON-RPC 2.0 protocol for MCP
- Resource Access: Retrieve resources from MCP servers
- Tool Invocation: Call tools provided by MCP servers
- Prompt Execution: Execute prompts on MCP servers
- Server Capabilities: Discover and leverage server capabilities
- Proper Authentication: Handle initialization and authentication flows
// Create an MCP client connected to a server
let client = new?;
// Initialize with client capabilities
let server_capabilities = client.initialize.await?;
// Access resources from the server
let resource = client.get_resource.await?;
See the Model Context Protocol specification for more details.
Implementation Status
This is a production-ready library with comprehensive functionality:
✅ Core Features (Completed)
- Client Framework: Type‑state builder pattern with compile‑time validation
- Security: Secure API key handling with memory zeroing and error redaction
- Chat Completions: Full OpenRouter chat API support with streaming
- Text Completions: Traditional text completion endpoint
- Web Search: Integrated web search capabilities
- Tool Calling: Function calling with validation
- Structured Outputs: JSON Schema validation
- Provider Preferences: Model routing and fallback configuration
- Model Context Protocol: Complete MCP client implementation
✅ Quality Infrastructure (Completed)
- 100% Test Coverage: 80+ comprehensive unit and integration tests
- Security Auditing: Automated security vulnerability scanning
- CI/CD Pipeline: GitHub Actions with quality gates
- Documentation: Complete API documentation with examples
- Developer Experience: Contributing guidelines, issue templates, PR templates
✅ Ergonomic Improvements (Completed)
- Convenience Constructors:
from_env()
,from_api_key()
,production()
,quick()
- Flexible Configuration: Timeout, retry, and header management
- Error Handling: Comprehensive error types with context
- Memory Safety: Automatic sensitive data cleanup
🔄 Future Enhancements
- Models Listing: Endpoint to list available models
- Credits API: Account credit and usage tracking
- Performance Optimizations: Connection pooling and caching
- Extended MCP Features: Additional MCP protocol capabilities
Contributing
Contributions are welcome! Please open an issue or submit a pull request with your ideas or fixes. Follow the code style guidelines and ensure that all tests pass.
License
Distributed under either the MIT license or the Apache License, Version 2.0. See LICENSE for details.
OpenRouter API Rust Crate Documentation
Version: 0.1.6 • License: MIT / Apache‑2.0
The openrouter_api
crate is a comprehensive client for interacting with the OpenRouter API and Model Context Protocol servers. It provides strongly‑typed endpoints for chat completions, text completions, web search, and MCP connections. The crate is built using asynchronous Rust and leverages advanced patterns for safe and flexible API usage.
Table of Contents
- Core Concepts
- Installation
- Architecture & Module Overview
- Client Setup & Type‑State Pattern
- API Endpoints
- Error Handling
- Best Practices
- Examples
- Additional Resources
Core Concepts
-
Type‑State Client Configuration: The client is built using a type‑state pattern to ensure that required parameters are set before making any API calls.
-
Provider Preferences: Strongly-typed configuration for model routing, fallbacks, and provider selection.
-
Asynchronous Streaming: Support for streaming responses via asynchronous streams.
-
Model Context Protocol: Client implementation for connecting to MCP servers to access resources, tools, and prompts.
-
Error Handling & Validation: Comprehensive error handling with detailed context and validation utilities.
Architecture & Module Overview
The crate is organized into several modules:
client
: Type-state client implementation with builder patternapi
: API endpoint implementations (chat, completions, web search, etc.)models
: Domain models for structured outputs, provider preferences, toolstypes
: Type definitions for requests and responsesmcp
: Model Context Protocol client implementationerror
: Centralized error handlingutils
: Utility functions and helpers
Client Setup & Type‑State Pattern
// Quick setup (recommended for most use cases)
let client = from_env?;
// Production setup with optimized settings
let client = production?;
// Full control with type-state pattern
let client = new
.with_base_url?
.with_timeout
.with_http_referer
.with_api_key?;
API Endpoints
Chat Completions
// Basic chat completion
let response = client.chat?.chat_completion.await?;
Tool Calling
// Define a function tool
let weather_tool = Function ;
// Make a request with tool calling enabled
let response = client.chat?.chat_completion.await?;
Model Context Protocol
// Create an MCP client
let mcp_client = new?;
// Initialize with client capabilities
let server_capabilities = mcp_client.initialize.await?;
// Access a resource from the MCP server
let resource = mcp_client.get_resource.await?;
Error Handling
match client.chat?.chat_completion.await
Best Practices
-
Use the Type‑State Pattern: Let the compiler ensure your client is properly configured.
-
Set Appropriate Timeouts & Headers: Configure reasonable timeouts and identify your application.
-
Handle Errors Appropriately: Implement proper error handling for each error type.
-
Use Provider Preferences: Configure provider routing for optimal model selection.
-
Secure Your API Keys: Store keys in environment variables or secure storage.