← Về thư mục
OpenAPI Utilities
This directory contains the OpenAPI integration utilities for FastMCP.
Architecture Overview
The implementation follows a stateless request building strategy using openapi-core for high-performance, per-request HTTP request construction, eliminating startup latency while maintaining robust OpenAPI compliance.
Core Components
director.py - RequestDirector for stateless HTTP request building
parser.py - OpenAPI spec parsing and route extraction with pre-calculated schemas
schemas.py - Schema processing with parameter mapping for collision handling
models.py - Enhanced data models with pre-calculated fields for performance
formatters.py - Response formatting and processing utilities
Key Architecture Principles
1. Stateless Request Building
- Uses
openapi-core library for robust OpenAPI parameter serialization
- Builds HTTP requests on-demand with zero startup latency
- Offloads OpenAPI compliance to a well-tested library without code generation overhead
2. Pre-calculated Optimization
- Schema Pre-calculation: Combined schemas calculated once during parsing
- Parameter Mapping: Collision resolution mapping calculated upfront
- Zero Runtime Overhead: All complex processing done during initialization
- No Code Generation: Eliminates 100-200ms startup latency
- Serverless Friendly: Ideal for cold-start environments
- Minimal Dependencies: Uses lightweight
openapi-core instead of full client generation
Data Flow
Initialization Process
OpenAPI Spec → Parser → HTTPRoute with Pre-calculated Fields → RequestDirector + SchemaPath
- Input: Raw OpenAPI specification (dict)
- Parsing: Extract operations to
HTTPRoute models
- Pre-calculation: Generate combined schemas and parameter maps during parsing
- Director Setup: Create
RequestDirector with SchemaPath for request building
Request Processing
MCP Tool Call → RequestDirector.build() → httpx.Request → HTTP Response → Structured Output
- Tool Invocation: FastMCP receives tool call with parameters
- Request Building: RequestDirector builds HTTP request using parameter map
- Parameter Handling: openapi-core handles all OpenAPI serialization rules
- Response Processing: Parse response into structured format with proper error handling
Key Features
- Zero startup latency - no code generation required
- Stateless request building scales infinitely
- Uses proven
openapi-core library for OpenAPI compliance
- Perfect for serverless and cold-start environments
2. Comprehensive Parameter Support
- Parameter Collisions: Intelligent collision resolution with suffixing
- DeepObject Style: Full support for deepObject parameters with explode=true/false
- Complex Schemas: Handles nested objects, arrays, and all OpenAPI types
- Pre-calculated Mapping: Parameter location mapping done upfront for performance
3. Enhanced Error Handling
- HTTP status code mapping to MCP errors
- Structured error responses with detailed information
- Graceful handling of network timeouts and connection errors
- Proper error context preservation
4. Advanced Schema Processing
- Pre-calculated Schemas: Combined parameter and body schemas calculated once
- Collision-aware: Automatically handles parameter name collisions
- Type Safety: Full Pydantic model validation
- Performance: Zero runtime schema processing overhead
Component Integration
Server Components (/server/openapi/)
OpenAPITool - Simplified tool implementation using RequestDirector
OpenAPIResource - Resource implementation with RequestDirector
OpenAPIResourceTemplate - Resource template with RequestDirector support
FastMCPOpenAPI - Main server class with stateless request building
RequestDirector Integration
All components use the same RequestDirector approach:
- Consistent parameter handling across all component types
- Uniform error handling and response processing
- Simplified architecture without fallback complexity
- High performance for all operation types
Usage Examples
Basic Server Setup
import httpx
from fastmcp.server.openapi import FastMCPOpenAPI
# OpenAPI spec (can be loaded from file/URL)
openapi_spec = {...}
# Create HTTP client
async with httpx.AsyncClient() as client:
# Create server with stateless request building
server = FastMCPOpenAPI(
openapi_spec=openapi_spec,
client=client,
name="My API Server"
)
# Server automatically creates RequestDirector and pre-calculates schemas
Direct RequestDirector Usage
from fastmcp.utilities.openapi.director import RequestDirector
from jsonschema_path import SchemaPath
# Create RequestDirector manually
spec = SchemaPath.from_dict(openapi_spec)
director = RequestDirector(spec)
# Build HTTP request
request = director.build(route, flat_arguments, base_url)
# Execute with httpx
async with httpx.AsyncClient() as client:
response = await client.send(request)
Testing Strategy
Tests are located in /tests/server/openapi/:
Test Categories
- Core Functionality
-
test_server.py - Server initialization and RequestDirector integration
-
OpenAPI Features
test_parameter_collisions.py - Parameter name collision handling
test_deepobject_style.py - DeepObject parameter style support
test_openapi_features.py - General OpenAPI feature compliance
Testing Philosophy
- Real Objects: Use real HTTPRoute models and OpenAPI specifications
- Minimal Mocking: Only mock external HTTP endpoints
- Performance Focus: Test that initialization is fast and stateless
- Behavioral Testing: Verify OpenAPI compliance without implementation details
Future Enhancements
Planned Features
- Response Streaming: Handle streaming API responses
- Enhanced Authentication: More auth provider integrations
- Advanced Metrics: Detailed request/response monitoring
- Schema Validation: Enhanced input/output validation
- Batch Operations: Optimized multi-operation requests
- Schema Caching: More aggressive schema pre-calculation
- Memory Optimization: Further reduce memory footprint
- Request Batching: Smart batching for bulk operations
- Connection Optimization: Enhanced connection pooling strategies
Troubleshooting
Common Issues
- RequestDirector Initialization Fails
- Check OpenAPI spec validity with
jsonschema-path
- Verify spec format is correct JSON/YAML
-
Ensure all required OpenAPI fields are present
-
Parameter Mapping Issues
- Check parameter collision resolution in debug logs
- Verify parameter names match OpenAPI spec exactly
-
Review pre-calculated parameter map in HTTPRoute
-
Request Building Errors
- Check network connectivity to target API
- Verify base URL configuration
- Review parameter validation and type mismatches
Debugging
- Enable debug logging:
logger.setLevel(logging.DEBUG)
- Check RequestDirector initialization logs
- Review parameter mapping in HTTPRoute models
- Monitor request building and API response patterns
Dependencies
openapi-core - OpenAPI specification processing and validation
httpx - HTTP client library
pydantic - Data validation and serialization
urllib.parse - URL building and manipulation