-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Add MCP Server Code generation #2115
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Asafrose
wants to merge
13
commits into
oapi-codegen:main
Choose a base branch
from
Asafrose:add-mcp-server-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
e2b8aef to
2c094d7
Compare
|
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
|
- MCP SDK should not be in importMapping as it has no external OpenAPI refs - The mcp import is automatically added when templates use mcp.* types - This fixes 'mcp.PathToRawSpec undefined' errors when mcp-server is used with other server types
- MCP types (mcp.Tool, mcp.CallToolRequest, etc.) are used in templates - These references don't trigger automatic import detection - Explicitly add mcp import via AdditionalImports to fix compilation errors
…mports - Removed AdditionalImports approach which was causing issues - Added import blocks directly in mcp-interface.tmpl, mcp-register.tmpl, and strict-mcp.tmpl - Each MCP template now includes its own import statement for github.com/modelcontextprotocol/go-sdk/mcp
- Removed import blocks from mcp-interface.tmpl, mcp-register.tmpl, and strict-mcp.tmpl - Added MCP import to main imports.tmpl following the pattern of other framework imports - This fixes the issue where MCP imports were being duplicated in generated code - MCP import is now included unconditionally, consistent with other framework imports
- Changed MCP schema constants from backtick to quoted strings - Added proper escaping for backslashes and quotes in JSON schemas - Fixes Go formatter issues with multiline backtick strings containing \n - Verified MCP example compiles and works correctly
…plate - Fixed logic to only generate StrictServerInterface when no other server has - Only generate for MCP when it's the sole server type - Removed unused mcp-server.tmpl template that was causing confusion - This fixes duplicate type declarations when using MCP with other servers
Adds support for filtering which operations are included in MCP server generation using the x-mcp OpenAPI extension field. Key features: - New mcp-inclusion-mode configuration field with three modes: - "include" (default): Include operations by default unless x-mcp is false - "exclude": Exclude operations by default unless x-mcp is true - "explicit": Require explicit x-mcp field on all operations - Operations can use x-mcp: true/false to control inclusion - Validation ensures only valid modes are used 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
The MCPHandlerInterface was being generated with all operations instead of only the filtered ones, causing a mismatch where the interface required methods for operations that were never registered as tools. Fixed by passing filteredOps to the interface template instead of ops. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Added tests for: - getXMCPExtension: Tests retrieving x-mcp extension values including true, false, missing, nil spec, and non-boolean values - filterOperationsForMCP: Tests all three inclusion modes (include, exclude, explicit) with various combinations of operations Test coverage includes: - Include mode: includes by default, excludes only x-mcp: false - Exclude mode: excludes by default, includes only x-mcp: true - Explicit mode: requires x-mcp on all operations, errors if missing - Edge cases: empty string defaults to include, invalid mode errors All 10 test cases pass successfully. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Added github.com/modelcontextprotocol/go-sdk dependency required for MCP server generation functionality. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Added MCPInclusionMode enum type for better type safety: - MCPInclusionModeInclude: Include by default (default mode) - MCPInclusionModeExclude: Exclude by default - MCPInclusionModeExplicit: Require explicit x-mcp on all operations Benefits: - Compile-time type checking instead of runtime validation - Clear constants prevent typos - Better IDE autocomplete support - Follows pattern used elsewhere in codebase (e.g., NameNormalizerFunction) Updated: - Configuration field from string to MCPInclusionMode type - All function signatures to use the enum type - Tests to use enum constants instead of string literals - Validation logic to check against enum constants All tests pass successfully. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
2c094d7 to
b7c3eb6
Compare
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Add MCP (Model Context Protocol) Server Code Generation
This PR adds comprehensive support for generating MCP servers from OpenAPI specifications, enabling AI agents to interact with APIs through the Model Context Protocol.
Overview
The Model Context Protocol (MCP) allows AI systems to expose tools and resources in a standardized way. This implementation generates MCP server code from OpenAPI specs, automatically converting REST API operations into MCP tools with proper JSON schemas.
Key Features
1. MCP Server Generation
mcp-server: truegeneration optionMCPHandlerInterfacewith methods for each operationRegisterMCPTools()function to register tools with MCP serverstrict-servermode via adapter pattern2. Operation Filtering with x-mcp Extension
x-mcpboolean extensionmcp-inclusion-modeconfiguration:include(default): Include operations by default, exclude only withx-mcp: falseexclude: Exclude operations by default, include only withx-mcp: trueexplicit: Require explicitx-mcpfield on all operations (errors if missing)3. Structured Input/Output Schemas
path: Path parametersquery: Query parametersheader: Header parameterscookie: Cookie parametersbody: Request body (JSON)Configuration
Basic Configuration
With Operation Filtering
OpenAPI Extension
Generated Code
MCPHandlerInterface
Tool Registration
Strict Mode Integration
When using
strict-server: true, an adapter is generated:Implementation Details
Files Added/Modified
pkg/codegen/mcp.go: Core MCP generation logic (~460 lines)MCPInclusionModeenum type for type-safe filtering modesfilterOperationsForMCP()- Filters operations based on x-mcp extensionGenerateMCPServer()- Generates MCP interface and registrationoperationToMCPTool()- Converts OpenAPI operations to MCP toolsbuildMCPInputSchema()- Builds structured input JSON schemasbuildMCPOutputSchema()- Extracts output schemas from responsespkg/codegen/mcp_test.go: Comprehensive test suite (~490 lines)pkg/codegen/templates/mcp/: Go templates for code generationmcp-interface.tmpl- MCPHandlerInterface generationmcp-register.tmpl- Tool registration functionpkg/codegen/templates/strict/strict-mcp.tmpl: Strict mode adapterpkg/codegen/configuration.go: Configuration updatesMCPInclusionModefield toOutputOptionspkg/codegen/operations.go: Strict server interface logicStrictServerInterfacegeneration when using MCP with other serversexamples/mcp-server/: Complete working examplego.mod: Added MCP SDK dependencygithub.com/modelcontextprotocol/go-sdk v1.1.0Key Technical Decisions
Quoted strings for JSON schemas: Uses quoted strings with proper escaping instead of backticks to avoid Go formatter issues with long lines
Filtering before generation: Operations are filtered before generating interfaces and registration code, ensuring consistency
Enum type for inclusion mode: Uses
MCPInclusionModetyped enum for compile-time safety instead of string literalsStrict server pattern compatibility: MCP can be used standalone or with strict-server mode via adapter
No duplicate interfaces: When using MCP with other servers,
StrictServerInterfaceis only generated onceTesting
All changes are fully tested:
Example Usage
1. Generate MCP Server Code
oapi-codegen -config cfg.yaml api.yaml > server.gen.go2. Implement the Interface
3. Register Tools
Breaking Changes
None. This is a purely additive feature that doesn't affect existing generation modes.
Migration Guide
No migration needed for existing users. To adopt MCP server generation:
mcp-server: trueto your configgo get github.com/modelcontextprotocol/go-sdk/mcpMCPHandlerInterfaceDocumentation
examples/mcp-server/with complete working exampleRelated Links
Checklist
This PR enables oapi-codegen users to seamlessly expose their OpenAPI-defined APIs as MCP tools, making them accessible to AI agents and LLM applications with minimal effort.