Documentation
¶
Overview ¶
http_lint.go
Package openapi2mcp transforms OpenAPI 3.x specifications into MCP (Model Context Protocol) tool servers.
This package provides the core functionality to automatically convert any OpenAPI 3.x specification into a fully functional MCP server that can be used by AI agents and LLMs. It handles the complete conversion pipeline: parsing OpenAPI specs, generating MCP tools for each operation, and serving them via stdio or HTTP transports.
Quick Start ¶
// Load an OpenAPI specification
doc, err := openapi2mcp.LoadOpenAPISpec("petstore.yaml")
if err != nil {
log.Fatal(err)
}
// Create and start MCP server
srv := openapi2mcp.NewServer("petstore", doc.Info.Version, doc)
openapi2mcp.ServeStdio(srv) // or ServeHTTP(srv, ":8080")
Authentication Support ¶
The package automatically handles OpenAPI authentication schemes:
- API Keys (header, query, cookie)
- Bearer tokens (OAuth2, JWT)
- Basic authentication
- Custom security schemes
Authentication can be provided via environment variables, command-line flags, or HTTP headers (in HTTP mode).
Advanced Usage ¶
// Extract operations for custom processing
ops := openapi2mcp.ExtractOpenAPIOperations(doc)
// Create server with custom options
srv := mcpserver.NewMCPServer("myapi", "1.0.0")
opts := &ToolGenOptions{
TagFilter: []string{"admin"},
ConfirmDangerousActions: true,
}
openapi2mcp.RegisterOpenAPITools(srv, ops, doc, opts)
Validation and Linting ¶
The package includes comprehensive OpenAPI validation:
// Validate specification issues := openapi2mcp.ValidateOpenAPISpec(doc) // Lint for best practices lintResults := openapi2mcp.LintOpenAPISpec(doc)
Output Formats ¶
All tool responses use structured formats optimized for AI agent consumption, with consistent OutputFormat and OutputType fields for reliable parsing.
For server implementations, see the server package. For core MCP protocol types, see the mcp package.
register.go
schema.go
selftest.go
server.go
spec.go
summary.go
Package openapi2mcp provides functionality for converting OpenAPI specifications to MCP tools. For working with MCP types and tools directly, import github.com/ubermorgenland/openapi-mcp/pkg/mcp/mcp and github.com/ubermorgenland/openapi-mcp/pkg/mcp/server
Index ¶
- func BuildInputSchema(params openapi3.Parameters, requestBody *openapi3.RequestBodyRef) map[string]any
- func BuildInputSchemaWithContext(params openapi3.Parameters, requestBody *openapi3.RequestBodyRef, ...) map[string]any
- func GetMessageURL(addr, basePath, sessionID string) string
- func GetSSEURL(addr, basePath string) string
- func GetStreamableHTTPURL(addr, basePath string) string
- func HandlerForBasePath(server *mcpserver.MCPServer, basePath string) http.Handler
- func HandlerForStreamableHTTP(server *mcpserver.MCPServer, basePath string) http.Handler
- func LoadOpenAPISpec(path string) (*openapi3.T, error)
- func LoadOpenAPISpecFromBytes(data []byte) (*openapi3.T, error)
- func LoadOpenAPISpecFromString(data string) (*openapi3.T, error)
- func NewServer(name, version string, doc *openapi3.T) *mcpserver.MCPServer
- func NewServerWithDatabase(name, version string, doc *openapi3.T, dbSpec *models.OpenAPISpec) *mcpserver.MCPServer
- func NewServerWithOps(name, version string, doc *openapi3.T, ops []OpenAPIOperation) *mcpserver.MCPServer
- func PrintToolSummary(ops []OpenAPIOperation)
- func RegisterOpenAPITools(server *mcpserver.MCPServer, ops []OpenAPIOperation, doc *openapi3.T, ...) []string
- func RegisterOpenAPIToolsRefactored(server *mcpserver.MCPServer, ops []OpenAPIOperation, doc *openapi3.T, ...) []string
- func SelfTestOpenAPIMCP(doc *openapi3.T, toolNames []string) error
- func SelfTestOpenAPIMCPWithOptions(doc *openapi3.T, toolNames []string, detailedSuggestions bool) error
- func ServeHTTP(server *mcpserver.MCPServer, addr string, basePath string) error
- func ServeHTTPLint(addr string, detailedSuggestions bool) error
- func ServeStdio(server *mcpserver.MCPServer) error
- func ServeStreamableHTTP(server *mcpserver.MCPServer, addr string, basePath string) error
- type HTTPLintRequest
- type HTTPLintServer
- type LintIssue
- type LintResult
- type OpenAPIOperation
- type ToolGenOptions
- type ToolRegistrar
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BuildInputSchema ¶
func BuildInputSchema(params openapi3.Parameters, requestBody *openapi3.RequestBodyRef) map[string]any
BuildInputSchema converts OpenAPI parameters and request body schema to a single JSON Schema object for MCP tool input validation. Returns a JSON Schema as a map[string]any. Example usage for BuildInputSchema:
params := ... // openapi3.Parameters from an operation reqBody := ... // *openapi3.RequestBodyRef from an operation schema := openapi2mcp.BuildInputSchema(params, reqBody) // schema is a map[string]any representing the JSON schema for tool input
func BuildInputSchemaWithContext ¶
func BuildInputSchemaWithContext(params openapi3.Parameters, requestBody *openapi3.RequestBodyRef, doc *openapi3.T) map[string]any
BuildInputSchemaWithContext converts OpenAPI parameters and request body schema to a single JSON Schema object for MCP tool input validation with document context. Returns a JSON Schema as a map[string]any.
func GetMessageURL ¶
GetMessageURL returns the URL for sending JSON-RPC requests to the MCP server. addr is the address the server is listening on (e.g., ":8080", "0.0.0.0:8080", "localhost:8080"). basePath is the base HTTP path (e.g., "/mcp"). sessionID should be the session ID received from the SSE endpoint event. Example usage:
url := openapi2mcp.GetMessageURL(":8080", "/custom-base", "session-id-123")
// Returns: "http://localhost:8080/custom-base/message?sessionId=session-id-123"
func GetSSEURL ¶
GetSSEURL returns the URL for establishing an SSE connection to the MCP server. addr is the address the server is listening on (e.g., ":8080", "0.0.0.0:8080", "localhost:8080"). basePath is the base HTTP path (e.g., "/mcp"). Example usage:
url := openapi2mcp.GetSSEURL(":8080", "/custom-base")
// Returns: "http://localhost:8080/custom-base/sse"
func GetStreamableHTTPURL ¶
GetStreamableHTTPURL returns the URL for the Streamable HTTP endpoint of the MCP server. addr is the address the server is listening on (e.g., ":8080", "0.0.0.0:8080", "localhost:8080"). basePath is the base HTTP path (e.g., "/mcp"). Example usage:
url := openapi2mcp.GetStreamableHTTPURL(":8080", "/custom-base")
// Returns: "http://localhost:8080/custom-base"
func HandlerForBasePath ¶
HandlerForBasePath returns an http.Handler that serves the given MCP server at the specified basePath. This is useful for multi-mount HTTP servers, where you want to serve multiple OpenAPI schemas at different URL paths. Example usage:
handler := openapi2mcp.HandlerForBasePath(srv, "/petstore")
mux.Handle("/petstore/", handler)
func HandlerForStreamableHTTP ¶
HandlerForStreamableHTTP returns an http.Handler that serves the given MCP server at the specified basePath using StreamableHTTP. This is useful for multi-mount HTTP servers, where you want to serve multiple OpenAPI schemas at different URL paths. Example usage:
handler := openapi2mcp.HandlerForStreamableHTTP(srv, "/petstore")
mux.Handle("/petstore", handler)
func LoadOpenAPISpec ¶
LoadOpenAPISpec loads and parses an OpenAPI YAML or JSON file from the given path. Returns the parsed OpenAPI document or an error. Example usage for LoadOpenAPISpec:
doc, err := openapi2mcp.LoadOpenAPISpec("petstore.yaml")
if err != nil { log.Fatal(err) }
ops := openapi2mcp.ExtractOpenAPIOperations(doc)
func LoadOpenAPISpecFromBytes ¶
LoadOpenAPISpecFromBytes loads and parses an OpenAPI YAML or JSON spec from a byte slice. Returns the parsed OpenAPI document or an error.
func LoadOpenAPISpecFromString ¶
LoadOpenAPISpecFromString loads and parses an OpenAPI YAML or JSON spec from a string. Returns the parsed OpenAPI document or an error.
func NewServer ¶
NewServer creates a new MCP server, registers all OpenAPI tools, and returns the server. Equivalent to calling RegisterOpenAPITools with all operations from the spec. Example usage for NewServer:
doc, _ := openapi2mcp.LoadOpenAPISpec("petstore.yaml")
srv := openapi2mcp.NewServer("petstore", doc.Info.Version, doc)
openapi2mcp.ServeHTTP(srv, ":8080")
func NewServerWithDatabase ¶
func NewServerWithDatabase(name, version string, doc *openapi3.T, dbSpec *models.OpenAPISpec) *mcpserver.MCPServer
NewServerWithDatabase creates a new MCP server with database spec support for authentication. Example usage:
srv := openapi2mcp.NewServerWithDatabase("weather", doc.Info.Version, doc, dbSpec)
func NewServerWithOps ¶
func NewServerWithOps(name, version string, doc *openapi3.T, ops []OpenAPIOperation) *mcpserver.MCPServer
NewServerWithOps creates a new MCP server, registers the provided OpenAPI operations, and returns the server. Example usage for NewServerWithOps:
doc, _ := openapi2mcp.LoadOpenAPISpec("petstore.yaml")
ops := openapi2mcp.ExtractOpenAPIOperations(doc)
srv := openapi2mcp.NewServerWithOps("petstore", doc.Info.Version, doc, ops)
openapi2mcp.ServeHTTP(srv, ":8080")
func PrintToolSummary ¶
func PrintToolSummary(ops []OpenAPIOperation)
PrintToolSummary prints a human-readable summary of OpenAPI operations that will be converted to MCP tools.
This function analyzes the provided operations and outputs:
- Total number of tools that will be generated
- Breakdown by tags showing operation count per tag
- Overall statistics about the OpenAPI specification
This is useful for debugging and understanding what tools will be generated from an OpenAPI specification before actually starting the MCP server.
Example usage:
doc, _ := openapi2mcp.LoadOpenAPISpec("petstore.yaml")
ops := openapi2mcp.ExtractOpenAPIOperations(doc)
openapi2mcp.PrintToolSummary(ops)
Output example:
Total tools: 12 Tags: pets: 8 store: 3 user: 1
func RegisterOpenAPITools ¶
func RegisterOpenAPITools(server *mcpserver.MCPServer, ops []OpenAPIOperation, doc *openapi3.T, opts *ToolGenOptions, dbSpec *models.OpenAPISpec) []string
TODO: The following 1890-line function should be replaced by RegisterOpenAPIToolsRefactored once all the complex logic is properly extracted into the ToolRegistrar methods. RegisterOpenAPITools creates MCP tools for each provided OpenAPI operation. The handler validates arguments, builds the HTTP request, and returns the HTTP response as the tool result. Returns the list of tool names registered.
func RegisterOpenAPIToolsRefactored ¶
func RegisterOpenAPIToolsRefactored(server *mcpserver.MCPServer, ops []OpenAPIOperation, doc *openapi3.T, opts *ToolGenOptions, dbSpec *models.OpenAPISpec) []string
RegisterOpenAPITools registers each OpenAPI operation as an MCP tool with a real HTTP handler. Also adds tools for externalDocs, info, and describe if present in the OpenAPI spec. RegisterOpenAPIToolsRefactored demonstrates the improved, refactored approach using ToolRegistrar This would replace the 1890-line function below once fully implemented
func SelfTestOpenAPIMCP ¶
SelfTestOpenAPIMCP checks that the generated MCP server matches the OpenAPI contract (basic: all required tools and arguments are present). Returns an error if any required tools or arguments are missing.
func SelfTestOpenAPIMCPWithOptions ¶
func SelfTestOpenAPIMCPWithOptions(doc *openapi3.T, toolNames []string, detailedSuggestions bool) error
SelfTestOpenAPIMCPWithOptions runs the self-test with or without detailed suggestions.
func ServeHTTP ¶
ServeHTTP starts the MCP server using HTTP SSE (wraps mcpserver.NewSSEServer and Start). addr is the address to listen on, e.g. ":8080". basePath is the base HTTP path to mount the MCP server (e.g. "/mcp"). Returns an error if the server fails to start. Example usage for ServeHTTP:
srv, _ := openapi2mcp.NewServer("petstore", "1.0.0", doc)
openapi2mcp.ServeHTTP(srv, ":8080", "/custom-base")
func ServeHTTPLint ¶
ServeHTTPLint starts an HTTP server for linting OpenAPI specs
func ServeStdio ¶
ServeStdio starts the MCP server using stdio (wraps mcpserver.ServeStdio). Returns an error if the server fails to start. Example usage for ServeStdio:
openapi2mcp.ServeStdio(srv)
func ServeStreamableHTTP ¶
ServeStreamableHTTP starts the MCP server using HTTP StreamableHTTP (wraps mcpserver.NewStreamableHTTPServer and Start). addr is the address to listen on, e.g. ":8080". basePath is the base HTTP path to mount the MCP server (e.g. "/mcp"). Returns an error if the server fails to start. Example usage for ServeStreamableHTTP:
srv, _ := openapi2mcp.NewServer("petstore", "1.0.0", doc)
openapi2mcp.ServeStreamableHTTP(srv, ":8080", "/custom-base")
Types ¶
type HTTPLintRequest ¶
type HTTPLintRequest struct {
OpenAPISpec string `json:"openapi_spec"` // The OpenAPI spec as a YAML or JSON string
}
HTTPLintRequest represents the request body for HTTP lint/validate endpoints
type HTTPLintServer ¶
type HTTPLintServer struct {
// contains filtered or unexported fields
}
HTTPLintServer provides HTTP endpoints for OpenAPI validation and linting
func NewHTTPLintServer ¶
func NewHTTPLintServer(detailedSuggestions bool) *HTTPLintServer
NewHTTPLintServer creates a new HTTP lint server
func (*HTTPLintServer) HandleHealth ¶
func (s *HTTPLintServer) HandleHealth(w http.ResponseWriter, r *http.Request)
HandleHealth handles GET requests for health checks
func (*HTTPLintServer) HandleLint ¶
func (s *HTTPLintServer) HandleLint(w http.ResponseWriter, r *http.Request)
HandleLint handles POST requests to lint OpenAPI specs
type LintIssue ¶
type LintIssue struct {
Type string `json:"type"` // "error" or "warning"
Message string `json:"message"` // The main error/warning message
Suggestion string `json:"suggestion"` // Actionable suggestion for fixing the issue
Operation string `json:"operation,omitempty"` // Operation ID where the issue was found
Path string `json:"path,omitempty"` // API path where the issue was found
Method string `json:"method,omitempty"` // HTTP method where the issue was found
Parameter string `json:"parameter,omitempty"` // Parameter name where the issue was found
Field string `json:"field,omitempty"` // Specific field where the issue was found
}
LintIssue represents a single linting issue found in an OpenAPI spec
type LintResult ¶
type LintResult struct {
Success bool `json:"success"` // Whether the linting/validation passed
ErrorCount int `json:"error_count"` // Number of errors found
WarningCount int `json:"warning_count"` // Number of warnings found
Issues []LintIssue `json:"issues"` // List of all issues found
Summary string `json:"summary,omitempty"` // Summary message
}
LintResult represents the result of linting or validating an OpenAPI spec
func LintOpenAPISpec ¶
func LintOpenAPISpec(doc *openapi3.T, detailedSuggestions bool) *LintResult
LintOpenAPISpec performs comprehensive linting and returns structured results
type OpenAPIOperation ¶
type OpenAPIOperation struct {
OperationID string
Summary string
Description string
Path string
Method string
Parameters openapi3.Parameters
RequestBody *openapi3.RequestBodyRef
Tags []string
Security openapi3.SecurityRequirements
}
OpenAPIOperation describes a single OpenAPI operation to be mapped to an MCP tool. It includes the operation's ID, summary, description, HTTP path/method, parameters, request body, and tags.
func ExtractFilteredOpenAPIOperations ¶
func ExtractFilteredOpenAPIOperations(doc *openapi3.T, includeRegex, excludeRegex *regexp.Regexp) []OpenAPIOperation
ExtractFilteredOpenAPIOperations returns only those operations whose description matches includeRegex (if not nil) and does not match excludeRegex (if not nil). Returns a filtered slice of OpenAPIOperation. Example usage for ExtractFilteredOpenAPIOperations:
include := regexp.MustCompile("pets")
filtered := openapi2mcp.ExtractFilteredOpenAPIOperations(doc, include, nil)
func ExtractOpenAPIOperations ¶
func ExtractOpenAPIOperations(doc *openapi3.T) []OpenAPIOperation
ExtractOpenAPIOperations extracts all operations from the OpenAPI spec, merging path-level and operation-level parameters. Returns a slice of OpenAPIOperation describing each operation. Example usage for ExtractOpenAPIOperations:
doc, err := openapi2mcp.LoadOpenAPISpec("petstore.yaml")
if err != nil { log.Fatal(err) }
ops := openapi2mcp.ExtractOpenAPIOperations(doc)
type ToolGenOptions ¶
type ToolGenOptions struct {
NameFormat func(string) string
TagFilter []string
DryRun bool
PrettyPrint bool
Version string
PostProcessSchema func(toolName string, schema map[string]any) map[string]any
ConfirmDangerousActions bool // if true, add confirmation prompt for dangerous actions
}
ToolGenOptions controls tool generation and output for OpenAPI-MCP conversion.
NameFormat: function to format tool names (e.g., strings.ToLower) TagFilter: only include operations with at least one of these tags (if non-empty) DryRun: if true, only print the generated tool schemas, don't register PrettyPrint: if true, pretty-print the output Version: version string to embed in tool annotations PostProcessSchema: optional hook to modify each tool's input schema before registration/output ConfirmDangerousActions: if true (default), require confirmation for PUT/POST/DELETE tools
func(toolName string, schema map[string]any) map[string]any
type ToolRegistrar ¶
type ToolRegistrar struct {
// contains filtered or unexported fields
}
ToolRegistrar encapsulates the logic for registering OpenAPI operations as MCP tools
func NewToolRegistrar ¶
func NewToolRegistrar(server *mcpserver.MCPServer, doc *openapi3.T, opts *ToolGenOptions, dbSpec *models.OpenAPISpec) *ToolRegistrar
NewToolRegistrar creates a new tool registrar instance