openapi_mcpgo

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2026 License: MIT Imports: 16 Imported by: 0

README

openapi-mcpgo

openapi-mcpgo is a Go library that converts OpenAPI specifications into tools for mcp-go. It automatically generates MCP tools from an OpenAPI document, allowing mcp-go servers to expose existing REST APIs with minimal setup.

Create a new OpenAPI specification

import (
    omcpgo "github.com/ninyolittle/openapi-mcpgo"
)

func main () {
    spec, err := omcpgo.NewOpenApiSpec()
}

Options

Load options

This option specifies how to load the OpenAPI specification. You must provide either a file path or a URL; otherwise, an error is returned. Currently, only OpenAPI specifications in JSON format are supported. The following load options are available:

Load from file
spec, err := omcpgo.NewOpenApiSpec(
    omcpgo.LoadFromFile("openapi.json"),
)
Load from URL
spec, err := omcpgo.NewOpenApiSpec(
    omcpgo.LoadFromURL("https://example.com/openapi.json"),
)
Filter options

Filters is used if you dont want to expose all of your API endpoints.

By operation ID

This is the most common filter, and it allows you to specify which operations should be included in the OpenAPI specification based on their operation ID.

Suppose you have the following operations in your OpenAPI specification:

...
"paths": {
"/user": {
    "get": {
    "operationId": "getUser"
    },
    "post": {
    "operationId": "createUser"
    }
}
}

In go, you can filter the OpenAPI specification to include only the getUser and createUser operations by using the FilterByOperationID option:

spec, err := omcpgo.NewOpenApiSpec(
    omcpgo.LoadFromFile("openapi.json"),
    omcpgo.FilterByOperationID([]string{"getUser", "createUser"}),
)
By HTTP method

This filter allows you to specify which operations should be included in the OpenAPI specification based on their HTTP method. For example, if you want to include only the GET and POST operations, you can use the FilterByHTTPMethod option:

NOTE: The HTTP method filter is case-insensitive, so you can use either uppercase or lowercase letters.

spec, err := omcpgo.NewOpenApiSpec(
    omcpgo.LoadFromFile("openapi.json"),
    omcpgo.FilterByHTTPMethod([]string{"GET", "POST"}),
)
By Paths

This filter allows you to specify which operations should be included in the OpenAPI specification based on their path. For example, if you want to include only the operations with the /user and /admin paths, you can use the FilterByPaths option:

spec, err := omcpgo.NewOpenApiSpec(
    omcpgo.LoadFromFile("openapi.json"),
    omcpgo.FilterByPaths([]string{"/user", "/admin"}),
)
By Tags

This filter allows you to specify which operations should be included in the OpenAPI specification based on their tags. For example, if you want to include only the operations with the user and admin tags, you can use the FilterByTags option:

NOTE: The tags filter is in the operation level, so you can use it to filter operations that have specific tags.

Example:

...
"paths": {
    "/access_token": {
        "post": {
            "consumes": [
                "application/x-www-form-urlencoded"
            ],
            "produces": [
                "application/json"
            ],
            "tags": [
                "user"
            ],
        }
    }
}
spec, err := omcpgo.NewOpenApiSpec(
    omcpgo.LoadFromFile("openapi.json"),
    omcpgo.FilterByTags([]string{"user", "admin"}),
)
Modifier options

Modifiers are used to modify the OpenAPI specification after it has been loaded. This can be useful if you want to add additional information to the documentation. These are the available modifiers:

With Host

This modifier allows you to specify the host for the OpenAPI specification. This is useful as this value will be used as host in the URL when calling the API. For example, if you want to set the host to api.example.com, you can use the WithHost option:

spec, err := omcpgo.NewOpenApiSpec(
    omcpgo.LoadFromFile("openapi.json"),
    omcpgo.WithHost("api.example.com"),
)
With URL Builder

This modifier lets you specify a custom URL builder for the OpenAPI specification. The custom URL builder is used to construct request URLs when calling the API, replacing the default URL generation logic. This is useful when the default behavior does not match your API’s URL structure or when additional customization is required. To use a custom URL builder, pass the WithURLBuilder option:

spec, err := omcpgo.NewOpenApiSpec(
    omcpgo.LoadFromFile("openapi.json"),
    omcpgo.WithURLBuilder(func(op *openapi3.Operation, method, scheme, host, basePath string, path string, query string) string {
        // Custom URL building logic here
        base := scheme + "://" + host + basePath + path
            if query != "" {
                base += "?" + query
            }
        return base
    }),
)
With Headers

This modifier allows you to specify custom headers for the OpenAPI specification. This is useful when you want to add additional information to the documentation, such as authentication tokens or other metadata. These values are used every time a request is made. To use custom headers, pass the WithHeaders option:

spec, err := omcpgo.NewOpenApiSpec(
    omcpgo.LoadFromFile("openapi.json"),
    omcpgo.WithHeaders(func (ctx context.Context) map[string]string {
        // Custom header logic here
        return map[string]string{
            "Authorization": "Bearer <token>",
            "X-Custom-Header": "CustomValue",
        }
    }),
)

The ctx parameter allows you to access the request context, which can be useful for retrieving information about the current request or user session when generating headers.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FilterByMethods

func FilterByMethods(methods []string) option

FilterByMethods filters the OpenAPI specification to only include operations that use the specified HTTP methods.

func FilterByOperationIds

func FilterByOperationIds(operationIds []string) option

FilterByOperationIds filters the OpenAPI specification to only include operations with the specified operation IDs.

func FilterByPaths

func FilterByPaths(paths []string) option

FilterByPaths filters the OpenAPI specification to only include paths that match the specified paths.

func FilterByTags

func FilterByTags(tags []string) option

FilterByTags filters the OpenAPI specification to only include operations that have at least one of the specified tags.

func LoadFromFile

func LoadFromFile(path string) option

LoadFromFile loads an OpenAPI specification from a local file and applies it to the OpenApiTools instance.

func LoadFromURL

func LoadFromURL(urlStr string) option

LoadFromURL loads an OpenAPI specification from a URL and applies it to the OpenApiTools instance.

func WithBasePath

func WithBasePath(basePath string) option

WithBasePath allows you to set a custom base path for the OpenApiTools instance.

func WithHeaders

func WithHeaders(provider func(ctx context.Context) (map[string]string, error)) option

WithHeaders allows you to set custom headers for the OpenApiTools instance. This can be useful for adding authentication tokens or other necessary headers when making requests to the API. Example usage:

o := NewOpenApiSpec(
	LoadFromURL("https://example.com/api-docs.json"),
	WithHeaders(func(ctx context.Context) map[string]string {
    	return map[string]string{
    		"Authorization": "Bearer <token>",
    		"Content-Type":  "application/json",
    	}
	}),
)

func WithHost

func WithHost(host string) option

WithHost allows you to set a custom host for the OpenApiTools instance.

func WithUrlBuilder

func WithUrlBuilder(urlBuilder func(operation *openapi2.Operation, method string, scheme, host, basePath, path, query string) string) option

WithUrlBuilder allows you to set a custom URL builder function for the OpenApiTools instance. This can be useful for customizing how URLs are constructed when making requests to the API. Example usage:

o := NewOpenApiSpec(
	LoadFromURL("https://example.com/api-docs.json"),
	WithUrlBuilder(func(scheme, host, basePath, path, query string) string {
		base := scheme + "://" + host + basePath + "/custom" + path
		if query != "" {
			base += "?" + query
		}
		return base
	}),

)

Types

type OpenApiTools

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

func NewOpenApiSpec

func NewOpenApiSpec(opts ...option) (*OpenApiTools, error)

func (*OpenApiTools) GetDoc

func (o *OpenApiTools) GetDoc() *openapi2.T

GetDoc returns the OpenAPI specification document associated with the OpenApiTools instance.

func (*OpenApiTools) PrintOperationIds

func (o *OpenApiTools) PrintOperationIds()

func (*OpenApiTools) RegisterToMcpServer

func (o *OpenApiTools) RegisterToMcpServer(server *server.MCPServer) error

RegisterToMcpServer registers the OpenApiTools instance to the provided MCPServer. It builds the tools from the OpenAPI specification and adds them to the server. If there is an error during the tool building process, it returns the error.

Jump to

Keyboard shortcuts

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