openapi2mcp

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 26, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

http_lint.go

Package openapi2mcp provides functions to expose OpenAPI operations as MCP tools and servers. It enables loading OpenAPI specs, generating MCP tool schemas, and running MCP servers that proxy real HTTP calls.

register.go

schema.go

selftest.go

server.go

spec.go

summary.go

Package openapi2mcp provides type aliases and helpers for working with MCP tools and properties. These aliases and helpers make it easier to construct and configure tools using the MCP protocol.

Index

Constants

This section is empty.

Variables

View Source
var Properties = struct {
	WithString           func(name string, opts ...mcp.PropertyOption) mcp.ToolOption
	WithNumber           func(name string, opts ...mcp.PropertyOption) mcp.ToolOption
	WithBoolean          func(name string, opts ...mcp.PropertyOption) mcp.ToolOption
	WithObject           func(name string, opts ...mcp.PropertyOption) mcp.ToolOption
	WithArray            func(name string, opts ...mcp.PropertyOption) mcp.ToolOption
	Description          func(description string) mcp.PropertyOption
	Required             func() mcp.PropertyOption
	Enum                 func(values ...string) mcp.PropertyOption
	DefaultString        func(value string) mcp.PropertyOption
	DefaultNumber        func(value float64) mcp.PropertyOption
	DefaultBool          func(value bool) mcp.PropertyOption
	DefaultArray         func(value []any) mcp.PropertyOption
	MaxLength            func(max int) mcp.PropertyOption
	MinLength            func(min int) mcp.PropertyOption
	Pattern              func(pattern string) mcp.PropertyOption
	Max                  func(max float64) mcp.PropertyOption
	Min                  func(min float64) mcp.PropertyOption
	MultipleOf           func(value float64) mcp.PropertyOption
	Properties           func(props map[string]any) mcp.PropertyOption
	AdditionalProperties func(schema any) mcp.PropertyOption
	MinProperties        func(min int) mcp.PropertyOption
	MaxProperties        func(max int) mcp.PropertyOption
	PropertyNames        func(schema map[string]any) mcp.PropertyOption
	Items                func(schema any) mcp.PropertyOption
	MinItems             func(min int) mcp.PropertyOption
	MaxItems             func(max int) mcp.PropertyOption
	UniqueItems          func(unique bool) mcp.PropertyOption
}{
	WithString:           mcp.WithString,
	WithNumber:           mcp.WithNumber,
	WithBoolean:          mcp.WithBoolean,
	WithObject:           mcp.WithObject,
	WithArray:            mcp.WithArray,
	Description:          mcp.Description,
	Required:             mcp.Required,
	Enum:                 mcp.Enum,
	DefaultString:        mcp.DefaultString,
	DefaultNumber:        mcp.DefaultNumber,
	DefaultBool:          mcp.DefaultBool,
	DefaultArray:         mcp.DefaultArray[any],
	MaxLength:            mcp.MaxLength,
	MinLength:            mcp.MinLength,
	Pattern:              mcp.Pattern,
	Max:                  mcp.Max,
	Min:                  mcp.Min,
	MultipleOf:           mcp.MultipleOf,
	Properties:           mcp.Properties,
	AdditionalProperties: mcp.AdditionalProperties,
	MinProperties:        mcp.MinProperties,
	MaxProperties:        mcp.MaxProperties,
	PropertyNames:        mcp.PropertyNames,
	Items:                mcp.Items,
	MinItems:             mcp.MinItems,
	MaxItems:             mcp.MaxItems,
	UniqueItems:          mcp.UniqueItems,
}

Properties provides functions for configuring tool properties. These are convenient wrappers around the core MCP property construction functions.

View Source
var Tools = struct {
	New                           func(name string, opts ...mcp.ToolOption) mcp.Tool
	NewWithRawSchema              func(name, description string, schema json.RawMessage) mcp.Tool
	WithDescription               func(description string) mcp.ToolOption
	WithToolAnnotation            func(annotation mcp.ToolAnnotation) mcp.ToolOption
	WithTitleAnnotation           func(title string) mcp.ToolOption
	WithReadOnlyHintAnnotation    func(value bool) mcp.ToolOption
	WithDestructiveHintAnnotation func(value bool) mcp.ToolOption
	WithIdempotentHintAnnotation  func(value bool) mcp.ToolOption
	WithOpenWorldHintAnnotation   func(value bool) mcp.ToolOption
}{
	New:                           mcp.NewTool,
	NewWithRawSchema:              mcp.NewToolWithRawSchema,
	WithDescription:               mcp.WithDescription,
	WithToolAnnotation:            mcp.WithToolAnnotation,
	WithTitleAnnotation:           mcp.WithTitleAnnotation,
	WithReadOnlyHintAnnotation:    mcp.WithReadOnlyHintAnnotation,
	WithDestructiveHintAnnotation: mcp.WithDestructiveHintAnnotation,
	WithIdempotentHintAnnotation:  mcp.WithIdempotentHintAnnotation,
	WithOpenWorldHintAnnotation:   mcp.WithOpenWorldHintAnnotation,
}

Tools provides functions for creating and configuring MCP tools. These are convenient wrappers around the core MCP tool construction functions.

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 LoadOpenAPISpec

func LoadOpenAPISpec(path string) (*openapi3.T, error)

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

func LoadOpenAPISpecFromBytes(data []byte) (*openapi3.T, error)

LoadOpenAPISpecFromBytes loads and parses an OpenAPI YAML or JSON spec from a byte slice. Returns the parsed OpenAPI document or an error.

func LoadOpenAPISpecFromString

func LoadOpenAPISpecFromString(data string) (*openapi3.T, error)

LoadOpenAPISpecFromString loads and parses an OpenAPI YAML or JSON spec from a string. Returns the parsed OpenAPI document or an error.

func NewServer

func NewServer(name, version string, doc *openapi3.T) *mcpserver.MCPServer

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 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 summary of the generated tools (count, tags, etc).

func RegisterExtraTool

func RegisterExtraTool(server *mcpserver.MCPServer, tool mcp.Tool, handler mcpserver.ToolHandlerFunc)

RegisterExtraTool registers an additional custom MCP tool and its handler with the server.

func RegisterOpenAPITools

func RegisterOpenAPITools(server *mcpserver.MCPServer, ops []OpenAPIOperation, doc *openapi3.T, opts *ToolGenOptions) []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. 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 SelfTestOpenAPIMCP

func SelfTestOpenAPIMCP(doc *openapi3.T, toolNames []string) error

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 added in v0.2.0

func SelfTestOpenAPIMCPWithOptions(doc *openapi3.T, toolNames []string, detailedSuggestions bool) error

SelfTestOpenAPIMCPWithOptions runs the self-test with or without detailed suggestions.

func ServeHTTP

func ServeHTTP(server *mcpserver.MCPServer, addr string) error

ServeHTTP starts the MCP server using HTTP (wraps mcpserver.NewStreamableHTTPServer and http.ListenAndServe). addr is the address to listen on, e.g. ":8080". 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")

func ServeHTTPLint added in v0.2.0

func ServeHTTPLint(addr string, detailedSuggestions bool) error

ServeHTTPLint starts an HTTP server for linting OpenAPI specs

func ServeStdio

func ServeStdio(server *mcpserver.MCPServer) error

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)

Types

type HTTPLintRequest added in v0.2.0

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 added in v0.2.0

type HTTPLintServer struct {
	// contains filtered or unexported fields
}

HTTPLintServer provides HTTP endpoints for OpenAPI validation and linting

func NewHTTPLintServer added in v0.2.0

func NewHTTPLintServer(detailedSuggestions bool) *HTTPLintServer

NewHTTPLintServer creates a new HTTP lint server

func (*HTTPLintServer) HandleHealth added in v0.2.0

func (s *HTTPLintServer) HandleHealth(w http.ResponseWriter, r *http.Request)

HandleHealth handles GET requests for health checks

func (*HTTPLintServer) HandleLint added in v0.2.0

func (s *HTTPLintServer) HandleLint(w http.ResponseWriter, r *http.Request)

HandleLint handles POST requests to lint OpenAPI specs

type LintIssue added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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 PropertyOption

type PropertyOption = mcp.PropertyOption

PropertyOption is an alias for mcp.PropertyOption, a function that configures a property in a Tool's input schema.

type Tool

type Tool = mcp.Tool

Tool is an alias for mcp.Tool, representing the definition of an MCP tool.

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 ToolHandlerFunc

type ToolHandlerFunc = mcpserver.ToolHandlerFunc

ToolHandlerFunc is an alias for mcpserver.ToolHandlerFunc, a function that handles tool calls.

type ToolOption

type ToolOption = mcp.ToolOption

ToolOption is an alias for mcp.ToolOption, a function that configures a Tool.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL