Skip to content

Conversation

kargnas
Copy link
Member

@kargnas kargnas commented Aug 8, 2025

… specs

  • Add command to generate MCP tools from Swagger 2.0 and OpenAPI 3.0 specifications
  • Support both local files and remote URLs as input sources
  • Parse endpoints and generate tool classes with HTTP client implementation
  • Handle authentication (Bearer tokens, API keys)
  • Auto-register generated tools in configuration
  • Include comprehensive test fixtures for Swagger/OpenAPI formats
  • Document new command with usage examples in README

This enables rapid integration of external APIs by automatically converting their Swagger/OpenAPI documentation into functional MCP tools.

🤖 Generated with Claude Code

… specs

- Add command to generate MCP tools from Swagger 2.0 and OpenAPI 3.0 specifications
- Support both local files and remote URLs as input sources
- Parse endpoints and generate tool classes with HTTP client implementation
- Handle authentication (Bearer tokens, API keys)
- Auto-register generated tools in configuration
- Include comprehensive test fixtures for Swagger/OpenAPI formats
- Document new command with usage examples in README

This enables rapid integration of external APIs by automatically converting
their Swagger/OpenAPI documentation into functional MCP tools.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

This comment was marked as outdated.

kargnas and others added 3 commits August 8, 2025 23:14
…1.4.0)

Introduces powerful automatic tool generation from any Swagger/OpenAPI specification,
dramatically reducing time needed to integrate external APIs.

Major features:
- SwaggerParser: Supports OpenAPI 3.x and Swagger 2.0 formats
- SwaggerToMcpConverter: Converts API endpoints to MCP tool parameters
- MakeSwaggerMcpToolCommand: Interactive CLI with endpoint selection
- Smart naming: Detects hash-like operationIds and uses path-based naming
- Authentication support: API Key, Bearer Token, OAuth2 generation
- API testing: Validates connectivity before tool generation
- Endpoint grouping: By tags, path prefixes, or individual selection
- Comprehensive test coverage for naming conversion and parsing logic

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
…erator

Extends the Swagger/OpenAPI generator to support creating both MCP Tools and Resources:
- Add resource generation mode with smart type selection (GET → Resource, others → Tool)
- Implement programmatic stub system for dynamic class generation
- Add comprehensive resource generation tests
- Update documentation to reflect dual generation capability
- Enhance command UI with type selection workflow

Allows users to generate read-only Resources for data endpoints alongside action-oriented Tools.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Copy link
Contributor

claude bot commented Aug 8, 2025

Claude finished @kargnas's task —— View job


Code Review Complete ✅

I've thoroughly reviewed the PR that adds automatic MCP tool and resource generation from Swagger/OpenAPI specifications. This is a significant and well-implemented feature that dramatically simplifies API integration. Here's my comprehensive analysis:

Todo List

  • Read and analyze all changed files
  • Review code quality and best practices
  • Check for security vulnerabilities
  • Assess performance considerations
  • Evaluate test coverage
  • Provide comprehensive feedback

🔍 Overall Assessment

This is an excellent feature implementation that adds substantial value to the Laravel MCP Server package. The automatic generation of MCP tools and resources from Swagger/OpenAPI specs will save developers significant time when integrating external APIs.

Key Strengths:

  • Clean, well-structured architecture
  • Comprehensive format support (OpenAPI 3.x and Swagger 2.0)
  • Dual generation modes (Tools and Resources)
  • Smart naming with hash detection
  • Interactive CLI experience
  • Good error handling and validation
  • Extensive test coverage

🚀 New Features Implemented

Primary Command: MakeSwaggerMcpToolCommand

  • Interactive endpoint selection with grouping options (tag, path, individual)
  • Smart defaults for non-interactive mode
  • API connection testing before generation
  • Dual generation modes: Tools vs Resources
  • Authentication configuration support
  • Progress tracking with detailed feedback

Core Parser: SwaggerParser

  • Handles both OpenAPI 3.x and Swagger 2.0 specifications
  • Supports URL and file sources
  • Comprehensive endpoint extraction with parameters, request bodies, and responses
  • Security scheme parsing
  • Reference resolution for $ref elements

Converter: SwaggerToMcpConverter

  • Generates both tools and resources from endpoints
  • Smart class naming with hash detection
  • Authentication logic generation
  • HTTP client integration with retry logic
  • Input validation and error handling

Enhanced Make Commands

  • Added programmatic generation support to existing commands
  • Automatic registration in configuration
  • Dynamic stub templating system

Code Quality Highlights

Excellent Architecture

  • Clear separation of concerns between parsing, conversion, and generation
  • Consistent use of Laravel conventions
  • Proper dependency injection and service instantiation
  • Well-organized command structure

Smart Naming Logic

The hash detection feature (SwaggerToMcpConverter:57-58) is particularly clever:

$useOperationId = !empty($endpoint['operationId']) 
    && !preg_match('/^[a-f0-9]{32}$/i', $endpoint['operationId']);

Comprehensive Test Coverage

  • Unit tests for core parsing functionality
  • Naming conversion test coverage
  • Resource generation tests
  • Real-world test fixtures

Good User Experience

  • Interactive prompts with smart defaults
  • Progress indicators and detailed feedback
  • Helpful error messages and guidance
  • Automatic configuration updates

⚠️ Areas for Improvement

1. Security Considerations (Medium Priority)

URL Validation Issue in SwaggerParser:25:

if (Str::startsWith($source, ['http://', 'https://'])) {

Recommendation: Add more restrictive URL validation to prevent SSRF:

if (filter_var($source, FILTER_VALIDATE_URL) && 
    in_array(parse_url($source)['scheme'] ?? '', ['http', 'https'])) {

2. Error Handling Consistency

The generated tools use different error handling patterns than existing tools. In SwaggerToMcpConverter:279-284, validation errors return arrays instead of throwing JsonRpcErrorException:

Current:

if ($validator->fails()) {
    return [
        'error' => 'Validation failed',
        'errors' => $validator->errors()->toArray(),
    ];
}

Should be:

if ($validator->fails()) {
    throw new JsonRpcErrorException(
        message: 'Validation failed: ' . $validator->errors()->first(),
        code: JsonRpcErrorCode::INVALID_REQUEST
    );
}

3. Performance Optimizations

HTTP Configuration in SwaggerToMcpConverter:380:

  • Hardcoded timeout values should be configurable
  • Consider connection pooling for high-volume usage
  • Add request caching for repeated spec fetches

4. Code Structure

Large Methods: The generateHttpRequest() method (376-423) could be broken into smaller, more focused methods for better maintainability.


🧪 Test Coverage Assessment

Strong Coverage:

  • ✅ Core parsing functionality
  • ✅ Naming conventions and edge cases
  • ✅ Resource generation
  • ✅ Hash detection logic
  • ✅ Authentication configuration

Potential Gaps:

  • Integration tests for the full command workflow
  • Error scenario testing (network failures, malformed specs)
  • Security testing for URL validation
  • Generated tool functionality verification

💡 Notable Implementation Details

Smart Path-to-Class Conversion

The convertPathToStudly() method (470-491) elegantly handles various naming conventions:

// Converts /lol/{region}/server-stats → LolRegionServerStats
$processed[] = Str::studly($segment);

Template-Based Generation

The programmatic stub system enables dynamic code generation while maintaining clean separation between templates and logic.

Automatic Registration

Generated components are automatically registered in the configuration, reducing manual setup steps.


🔧 Recommendations

High Priority:

  1. Strengthen URL validation to prevent potential SSRF attacks
  2. Standardize error handling to use JsonRpcErrorException consistently
  3. Add integration tests for the complete generation workflow

Medium Priority:

  1. Make HTTP timeouts configurable
  2. Add request retry configuration
  3. Refactor large methods for better maintainability

Low Priority:

  1. Add YAML support (noted as future enhancement)
  2. Enhanced authentication schemes (OAuth2 flows)
  3. Custom template support for organizations

🎯 Conclusion

This is a high-quality implementation that significantly enhances the package's capabilities. The feature is well-designed, thoroughly tested, and provides excellent developer experience.

Recommendation: Approve with minor fixes for the URL validation and error handling consistency issues.

The implementation demonstrates excellent software engineering practices and will provide substantial value to users integrating external APIs into their MCP servers.


Files Reviewed:

  • MakeSwaggerMcpToolCommand.php (688 lines) - Main command implementation
  • SwaggerParser.php (381 lines) - API specification parsing
  • SwaggerToMcpConverter.php (724 lines) - Conversion logic
  • Enhanced make commands with programmatic support
  • Comprehensive test suite with real fixtures
  • Updated README with extensive documentation

@kargnas
Copy link
Member Author

kargnas commented Aug 8, 2025

@claude Implement the improvement #1, #2, #3 (only for the hardcoded timeout), #4

Copy link
Contributor

claude bot commented Aug 8, 2025

Claude finished @kargnas's task —— View job


Todo List

✅ Implementation Complete

I've successfully implemented all four improvements from my previous code review:

Improvement #1: URL Validation Security

  • Added isValidUrl() method in SwaggerParser.php
  • Implements proper URL validation with filter_var() and scheme checking
  • Prevents SSRF attacks by ensuring only HTTP/HTTPS URLs are allowed
  • Includes comments for additional security measures that could be added

Improvement #2: Standardized Error Handling

  • Updated generated tool code in SwaggerToMcpConverter.php
  • Replaced error arrays with proper JsonRpcErrorException throwing
  • Fixed constructor syntax to match actual exception class
  • Uses appropriate error codes (INVALID_PARAMS, INTERNAL_ERROR)

Improvement #3: Configurable HTTP Timeouts

  • Added $httpTimeout property with default value of 30 seconds
  • Added setHttpTimeout() method for configuration
  • Replaced hardcoded timeout values in both tool and resource generation
  • Maintains backward compatibility with sensible defaults

Improvement #4: Method Refactoring

  • Broke down large generateHttpRequest() method into focused methods:
    • generateHttpClientSetup(): HTTP client configuration
    • generateQueryParametersCode(): Query parameter handling
    • generateHttpMethodCall(): HTTP method execution using modern match syntax
  • Improved maintainability and readability
  • Each method has a single responsibility

Changes Summary

  • Files modified: 2
  • Lines added: +102, Lines removed: -47
  • Commit: f0ea9cf - "feat: implement security and maintainability improvements"
  • Security: Enhanced with URL validation to prevent SSRF
  • Maintainability: Better code organization with smaller, focused methods
  • Flexibility: Configurable timeouts for different deployment scenarios

The implementation maintains full backward compatibility while significantly improving security, error handling, configurability, and code maintainability.


claude bot and others added 2 commits August 8, 2025 17:16
- Add URL validation to prevent SSRF attacks in SwaggerParser
- Standardize error handling to use JsonRpcErrorException
- Make HTTP timeouts configurable instead of hardcoded
- Refactor generateHttpRequest() method into smaller focused methods

Co-authored-by: Sangrak Choi <kargnas@users.noreply.github.com>
@kargnas kargnas merged commit e76e24c into master Aug 8, 2025
1 check passed
@kargnas kargnas deleted the feat/swagger-generator branch August 8, 2025 17:21
@opgginc opgginc deleted a comment from claude bot Aug 8, 2025
@opgginc opgginc deleted a comment from claude bot Aug 8, 2025
@opgginc opgginc deleted a comment from claude bot Aug 8, 2025
@opgginc opgginc deleted a comment from claude bot Aug 8, 2025
@opgginc opgginc deleted a comment from claude bot Aug 8, 2025
@opgginc opgginc deleted a comment from claude bot Aug 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant