openapi2mcp

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2025 License: MIT Imports: 19 Imported by: 1

README

openapi-mcp

openapi-mcp

Expose any OpenAPI 3.x API as a robust, agent-friendly MCP tool server in seconds!

Go Version Build Status License GoDoc


openapi-mcp transforms any OpenAPI 3.x specification into a powerful, AI-friendly MCP (Model Context Protocol) tool server. In seconds, it validates your OpenAPI spec, generates MCP tools for each operation, and starts serving through stdio or HTTP with structured, machine-readable output.

📋 Table of Contents

✨ Features

  • Instant API to MCP Conversion: Parses any OpenAPI 3.x YAML/JSON spec and generates MCP tools
  • Multiple Transport Options: Supports stdio (default) and HTTP server modes
  • Complete Parameter Support: Path, query, header, cookie, and body parameters
  • Authentication: API key, Bearer token, Basic auth, and OAuth2 support
  • Structured Output: All responses have consistent, well-structured formats with type information
  • Validation & Linting: Comprehensive OpenAPI validation and linting with actionable suggestions
    • validate command for critical issues (missing operationIds, schema errors)
    • lint command for best practices (summaries, descriptions, tags, parameter recommendations)
  • Safety Features: Confirmation required for dangerous operations (PUT/POST/DELETE)
  • Documentation: Built-in documentation generation in Markdown or HTML
  • AI-Optimized: Unique features specifically designed to enhance AI agent interactions:
    • Consistent output structures with OutputFormat and OutputType for reliable parsing
    • Rich machine-readable schema information with constraints and examples
    • Streamlined, agent-friendly response format with minimal verbosity
    • Intelligent error messages with suggestions for correction
    • Automatic handling of authentication, pagination, and complex data structures
  • Interactive Client: Includes an MCP client with readline support and command history
  • Flexible Configuration: Environment variables or command-line flags
  • CI/Testing Support: Summary options, exit codes, and dry-run mode

🤖 AI Agent Integration

openapi-mcp is designed for seamless integration with AI coding agents, LLMs, and automation tools with unique features that set it apart from other API-to-tool converters:

  • Structured JSON Responses: Every response includes OutputFormat and OutputType fields for consistent parsing
  • Rich Schema Information: All tools provide detailed parameter constraints and examples that help AI agents understand API requirements
  • Actionable Error Messages: Validation errors include detailed information and suggestions that guide agents toward correct usage
  • Safety Confirmations: Standardized confirmation workflow for dangerous operations prevents unintended consequences
  • Self-Describing API: The describe tool provides complete, machine-readable documentation for all operations
  • Minimal Verbosity: No redundant warnings or messages to confuse agents—outputs are optimized for machine consumption
  • Smart Parameter Handling: Automatic conversion between OpenAPI parameter types and MCP tool parameters
  • Contextual Examples: Every tool includes context-aware examples based on the OpenAPI specification
  • Intelligent Default Values: Sensible defaults are provided whenever possible to simplify API usage

🔧 Installation

Prerequisites
  • Go 1.21+
  • An OpenAPI 3.x YAML or JSON specification file
Build from Source
# Clone the repository
git clone <repo-url>
cd openapi-mcp

# Build the binaries
make

# This will create:
# - bin/openapi-mcp (main tool)
# - bin/mcp-client (interactive client)

⚡ Quick Start

1. Run the MCP Server
# Basic usage (stdio mode)
bin/openapi-mcp examples/fastly-openapi-mcp.yaml

# With API key
API_KEY=your_api_key bin/openapi-mcp examples/fastly-openapi-mcp.yaml

# As HTTP server
bin/openapi-mcp --http=:8080 examples/fastly-openapi-mcp.yaml

# Override base URL
bin/openapi-mcp --base-url=https://api.example.com examples/fastly-openapi-mcp.yaml
2. Use the Interactive Client
# Start the client (connects to openapi-mcp via stdio)
bin/mcp-client bin/openapi-mcp examples/fastly-openapi-mcp.yaml

# Client commands
mcp> list                              # List available tools
mcp> schema <tool-name>                # Show tool schema
mcp> call <tool-name> {arg1: value1}   # Call a tool with arguments
mcp> describe                          # Get full API documentation

🔒 Authentication

openapi-mcp supports all standard OpenAPI authentication methods via command-line flags, environment variables, or HTTP headers:

Command-Line Flags & Environment Variables
# API Key authentication
bin/openapi-mcp --api-key=your_api_key examples/fastly-openapi-mcp.yaml
# or use environment variable
API_KEY=your_api_key bin/openapi-mcp examples/fastly-openapi-mcp.yaml

# Bearer token / OAuth2
bin/openapi-mcp --bearer-token=your_token examples/fastly-openapi-mcp.yaml
# or use environment variable
BEARER_TOKEN=your_token bin/openapi-mcp examples/fastly-openapi-mcp.yaml

# Basic authentication
bin/openapi-mcp --basic-auth=username:password examples/fastly-openapi-mcp.yaml
# or use environment variable
BASIC_AUTH=username:password bin/openapi-mcp examples/fastly-openapi-mcp.yaml
HTTP Header Authentication (HTTP Mode Only)

When using HTTP mode (--http=:8080), you can provide authentication via HTTP headers in your requests:

# API Key via headers
curl -H "X-API-Key: your_api_key" http://localhost:8080/mcp -d '...'
curl -H "Api-Key: your_api_key" http://localhost:8080/mcp -d '...'

# Bearer token
curl -H "Authorization: Bearer your_token" http://localhost:8080/mcp -d '...'

# Basic authentication
curl -H "Authorization: Basic base64_credentials" http://localhost:8080/mcp -d '...'

Supported Authentication Headers:

  • X-API-Key or Api-Key - for API key authentication
  • Authorization: Bearer <token> - for OAuth2/Bearer token authentication
  • Authorization: Basic <credentials> - for Basic authentication

Authentication is automatically applied to the appropriate endpoints as defined in your OpenAPI spec. HTTP header authentication takes precedence over environment variables for the duration of each request.

When using HTTP mode, openapi-mcp serves a StreamableHTTP-based MCP server by default. For developers building HTTP clients, the package provides convenient URL helper functions:

import "github.com/jedisct1/openapi-mcp/pkg/openapi2mcp"

// Get the Streamable HTTP endpoint URL
streamableURL := openapi2mcp.GetStreamableHTTPURL(":8080", "/mcp")
// Returns: "http://localhost:8080/mcp"

// For SSE mode (when using --http-transport=sse), you can use:
sseURL := openapi2mcp.GetSSEURL(":8080", "/mcp")
// Returns: "http://localhost:8080/mcp/sse"

messageURL := openapi2mcp.GetMessageURL(":8080", "/mcp", sessionID)
// Returns: "http://localhost:8080/mcp/message?sessionId=<sessionID>"

StreamableHTTP Client Connection Flow:

  1. Send POST requests to the Streamable HTTP endpoint for requests/notifications
  2. Send GET requests to the same endpoint to listen for notifications
  3. Send DELETE requests to terminate the session

Example with curl:

# Step 1: Initialize the session
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26"}}'

# The response will include a Mcp-Session-Id header

# Step 2: Send JSON-RPC requests
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -H "Mcp-Session-Id: <session-id>" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'

# Step 3: Listen for notifications
curl -N http://localhost:8080/mcp \
  -H "Mcp-Session-Id: <session-id>"

SSE Client Connection Flow (when using --http-transport=sse):

  1. Connect to the SSE endpoint to establish a persistent connection
  2. Receive an endpoint event containing the session ID
  3. Send JSON-RPC requests to the message endpoint using the session ID
  4. Receive responses and notifications via the SSE stream

Example with curl (SSE mode):

# Step 1: Connect to SSE endpoint (keep connection open)
curl -N http://localhost:8080/mcp/sse

# Output: event: endpoint
#         data: /mcp/message?sessionId=<session-id>

# Step 2: Send JSON-RPC requests (in another terminal)
curl -X POST http://localhost:8080/mcp/message?sessionId=<session-id> \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

🛠️ Usage Examples

Integration with AI Code Editors

You can easily integrate openapi-mcp with AI code editors that support MCP tools, such as Roo Code:

{
    "fastly": {
        "command": "/opt/bin/openapi-mcp",
        "args": [
            "-api-key",
            "YOUR_API_KEY",
            "/opt/etc/openapi/fastly-openapi-mcp.yaml"
        ]
    }
}

Add this configuration to your editor's MCP tools configuration to provide AI assistants with direct access to the API. The assistant can then discover and use the API operations without additional setup.

OpenAPI Validation and Linting

openapi-mcp includes powerful OpenAPI validation and linting capabilities to help you improve your API specifications:

# Validate OpenAPI spec and check for critical issues
bin/openapi-mcp validate examples/fastly-openapi-mcp.yaml

# Comprehensive linting with detailed suggestions
bin/openapi-mcp lint examples/fastly-openapi-mcp.yaml

# Start HTTP validation service
bin/openapi-mcp --http=:8080 validate

# Start HTTP linting service
bin/openapi-mcp --http=:8080 lint

The validate command performs essential checks:

  • Missing operationId fields (required for MCP tool generation)
  • Schema validation errors
  • Basic structural issues

The lint command provides comprehensive analysis with suggestions for:

  • Missing summaries and descriptions
  • Untagged operations
  • Parameter naming and type recommendations
  • Security scheme validation
  • Best practices for API design

Both commands exit with non-zero status codes when issues are found, making them perfect for CI/CD pipelines.

HTTP API for Validation and Linting

Both validate and lint commands can be run as HTTP services using the --http flag, allowing you to validate OpenAPI specs via REST API. Note that these endpoints are only available when using the validate or lint commands, not during normal MCP server operation:

# Start validation HTTP service
bin/openapi-mcp --http=:8080 validate

# Start linting HTTP service
bin/openapi-mcp --http=:8080 lint

API Endpoints:

  • POST /validate - Validate OpenAPI specs for critical issues
  • POST /lint - Comprehensive linting with detailed suggestions
  • GET /health - Health check endpoint

Request Format:

{
  "openapi_spec": "openapi: 3.0.0\ninfo:\n  title: My API\n  version: 1.0.0\npaths: {}"
}

Response Format:

{
  "success": false,
  "error_count": 1,
  "warning_count": 2,
  "issues": [
    {
      "type": "error",
      "message": "Operation missing operationId",
      "suggestion": "Add an operationId field",
      "operation": "GET_/users",
      "path": "/users",
      "method": "GET"
    }
  ],
  "summary": "OpenAPI linting completed with issues: 1 errors, 2 warnings."
}

Example Usage:

curl -X POST http://localhost:8080/lint \
  -H "Content-Type: application/json" \
  -d '{"openapi_spec": "..."}'
Dry Run (Preview Tools as JSON)
bin/openapi-mcp --dry-run examples/fastly-openapi-mcp.yaml
Generate Documentation
bin/openapi-mcp --doc=tools.md examples/fastly-openapi-mcp.yaml
Filter Operations by Tag, Description, or Function List
bin/openapi-mcp filter --tag=admin examples/fastly-openapi-mcp.yaml
bin/openapi-mcp filter --include-desc-regex="user|account" examples/fastly-openapi-mcp.yaml
bin/openapi-mcp filter --exclude-desc-regex="deprecated" examples/fastly-openapi-mcp.yaml
bin/openapi-mcp filter --function-list-file=funcs.txt examples/fastly-openapi-mcp.yaml

You can use --function-list-file=funcs.txt to restrict the output to only the operations whose operationId is listed (one per line) in the given file. This filter is applied after tag and description filters.

Print Summary
bin/openapi-mcp --summary --dry-run examples/fastly-openapi-mcp.yaml
Post-Process Schema with External Command
bin/openapi-mcp --doc=tools.md --post-hook-cmd='jq . | tee /tmp/filtered.json' examples/fastly-openapi-mcp.yaml
Disable Confirmation for Dangerous Actions
bin/openapi-mcp --no-confirm-dangerous examples/fastly-openapi-mcp.yaml

🎮 Command-Line Options

Commands
Command Description
validate <spec> Validate OpenAPI spec and report critical issues (missing operationIds, schema errors)
lint <spec> Comprehensive linting with detailed suggestions for best practices
filter <spec> Output a filtered list of operations as JSON, applying --tag, --include-desc-regex, --exclude-desc-regex, and --function-list-file (no server)
Flags
Flag Environment Variable Description
--api-key API_KEY API key for authentication
--bearer-token BEARER_TOKEN Bearer token for Authorization header
--basic-auth BASIC_AUTH Basic auth credentials (user:pass)
--base-url OPENAPI_BASE_URL Override base URL for HTTP calls
--http - Serve MCP over HTTP instead of stdio
--tag OPENAPI_TAG Only include operations with this tag
--include-desc-regex INCLUDE_DESC_REGEX Only include APIs matching regex
--exclude-desc-regex EXCLUDE_DESC_REGEX Exclude APIs matching regex
--dry-run - Print tool schemas as JSON and exit
--summary - Print operation count summary
--doc - Generate documentation file
--doc-format - Documentation format (markdown or html)
--post-hook-cmd - Command to post-process schema JSON
--no-confirm-dangerous - Disable confirmation for dangerous actions
--extended - Enable human-friendly output (default is agent-friendly)
--function-list-file - Only include operations whose operationId is listed (one per line) in the given file (for filter command)

📚 Library Usage

openapi-mcp can be imported as a Go module in your projects:

package main

import (
        "github.com/jedisct1/openapi-mcp/pkg/openapi2mcp"
)

func main() {
        // Load OpenAPI spec
        doc, err := openapi2mcp.LoadOpenAPISpec("openapi.yaml")
        if err != nil {
                panic(err)
        }

        // Create MCP server
        srv := openapi2mcp.NewServer("myapi", doc.Info.Version, doc)

        // Serve over HTTP
        if err := openapi2mcp.ServeHTTP(srv, ":8080"); err != nil {
                panic(err)
        }

        // Or serve over stdio
        // if err := openapi2mcp.ServeStdio(srv); err != nil {
        //    panic(err)
        // }
}

See GoDoc for complete API documentation.

📊 Output Structure

All tool results include consistent structure for machine readability:

{
  "OutputFormat": "structured",
  "OutputType": "json",
  "type": "api_response",
  "data": {
    // API-specific response data
  },
  "metadata": {
    "status_code": 200,
    "headers": {
      // Response headers
    }
  }
}

For errors, you'll receive:

{
  "OutputFormat": "structured",
  "OutputType": "json",
  "type": "error",
  "error": {
    "code": "validation_error",
    "message": "Invalid parameter",
    "details": {
      "field": "username",
      "reason": "required field missing"
    },
    "suggestions": [
      "Provide a username parameter"
    ]
  }
}

🛡️ Safety Features

For any operation that performs a PUT, POST, or DELETE, openapi-mcp requires confirmation:

{
  "type": "confirmation_request",
  "confirmation_required": true,
  "message": "This action is irreversible. Proceed?",
  "action": "delete_resource"
}

To proceed, retry the call with:

{
  "original_parameters": {},
  "__confirmed": true
}

This confirmation workflow can be disabled with --no-confirm-dangerous.

📝 Documentation Generation

Generate comprehensive documentation for all tools:

# Markdown documentation
bin/openapi-mcp --doc=tools.md examples/fastly-openapi-mcp.yaml

# HTML documentation
bin/openapi-mcp --doc=tools.html --doc-format=html examples/fastly-openapi-mcp.yaml

The documentation includes:

  • Complete tool schemas with parameter types, constraints, and descriptions
  • Example calls for each tool
  • Response formats and examples
  • Authentication requirements

🙌 Contributing

Contributions are welcome! Please open an issue or pull request on GitHub.

  1. Fork the repository
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Run tests (go test ./...)
  5. Push to the branch (git push origin my-new-feature)
  6. Create a new Pull Request

📄 License

This project is licensed under the MIT License.

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 functionality for converting OpenAPI specifications to MCP tools.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildInputSchema

func BuildInputSchema(params openapi3.Parameters, requestBody *openapi3.RequestBodyRef) jsonschema.Schema

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 jsonschema.Schema. Example usage for BuildInputSchema:

params := ... // openapi3.Parameters from an operation
reqBody := ... // *openapi3.RequestBodyRef from an operation
schema := openapi2mcp.BuildInputSchema(params, reqBody)
// schema is a jsonschema.Schema representing the JSON schema for tool input

func GetMessageURL

func GetMessageURL(addr, basePath, sessionID string) string

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

func GetSSEURL(addr, basePath string) string

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

func GetStreamableHTTPURL(addr, basePath string) string

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

func HandlerForBasePath(server *mcp.Server, basePath string) http.Handler

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

func HandlerForStreamableHTTP(server *mcp.Server, basePath string) http.Handler

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

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) *mcp.Server

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) *mcp.Server

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 RegisterOpenAPITools

func RegisterOpenAPITools(server *mcp.Server, 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 SchemaToMap

func SchemaToMap(schema jsonschema.Schema) map[string]any

SchemaToMap converts a jsonschema.Schema to map[string]any for backward compatibility

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

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 *mcp.Server, addr string, basePath string) error

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

func ServeHTTPLint(addr string, detailedSuggestions bool) error

ServeHTTPLint starts an HTTP server for linting OpenAPI specs

func ServeStdio

func ServeStdio(server *mcp.Server) 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)

func ServeStreamableHTTP

func ServeStreamableHTTP(server *mcp.Server, addr string, basePath string) error

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 jsonschema.Schema) jsonschema.Schema
	ConfirmDangerousActions bool // if true, add confirmation prompt for dangerous actions
	RequestHandler          func(req *http.Request) (*http.Response, error)
}

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 jsonschema.Schema) jsonschema.Schema

Directories

Path Synopsis
cmd
openapi-mcp command
doc.go
doc.go

Jump to

Keyboard shortcuts

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