mcpopenapi

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

mcpopenapi

Go Reference CI

Turn an OpenAPI 3 document into MCP tools over Streamable HTTP, or into portable tool schemas for other runtimes (e.g. OpenAI function calling).

Each operation becomes a tool (operationId). On MCP tools/call, the module rebuilds the HTTP request and forwards it to an in-process http.Handler — no second network hop, no embedded auth. ParseToolSchemas exposes the same OpenAPI→schema mapping without standing up MCP.

Born for tripmap (/mcp), but usable anywhere you already have an OpenAPI-described http.Handler.

Why

OpenAPI is a natural description of an HTTP API; MCP is the native tool surface for Codex / Cursor / ChatGPT. If you already maintain OpenAPI for your API, this bridge avoids hand-writing a parallel tool schema.

Install

go get github.com/yaronf/mcpopenapi@v0.3.0

Dependency: github.com/modelcontextprotocol/go-sdk v1.7+.

Quick start

package main

import (
	"log"
	"net/http"

	"github.com/yaronf/mcpopenapi"
)

func main() {
	api := http.NewServeMux()
	api.HandleFunc("GET /trips", listTrips)
	// …

	mcpHandler, err := mcpopenapi.NewHandler(mcpopenapi.Config{
		Name:         "my-api",
		Version:      "1.0.0",
		Instructions: "Prefer PATCH over full replace. List before edit.",
		OpenAPIYAML:  openAPIBytes, // valid OpenAPI 3 YAML or JSON
		Upstream:     http.StripPrefix("/api", api),
		PathPrefix:   "/api", // only expose these paths as tools
	})
	if err != nil {
		log.Fatal(err)
	}

	// Auth stays at the edge — the module does not implement Bearer/OAuth.
	http.Handle("/mcp", bearerAuth(token, mcpHandler))
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Clients (Codex, Cursor, ChatGPT) connect with Streamable HTTP to https://host/mcp and a Bearer token (or whatever your edge requires).

Mapping rules

OpenAPI MCP tool
operationId Tool name
summary + description Tool description
Path / query / header parameters Top-level input properties
application/json request body Body properties flattened into the same object
text/plain request body Single body string argument
GET / HEAD annotations.readOnlyHint: true
Explicit security: [] Skipped (public ops stay off the tool list)
Missing operationId Skipped

$ref under components/schemas is resolved when building input schemas.

Idempotency-Key

If an operation declares a header parameter named Idempotency-Key, it is optional in the tool schema. When the client omits it, the bridge generates a random key before calling Upstream.

Path filter

Set PathPrefix (e.g. "/api/agent") to expose only that subtree. Useful when the same OpenAPI document also documents /health or other public routes.

Audience filter

Operations may declare an x-audiences list (override the extension key with AudienceKey):

x-audiences: [api, assistant]

When Audience is set on Config / ParseOptions:

Operation Result
Lists the audience Kept
Omits the extension Kept if IncludeUnannotated is true (default); dropped if false
Lists other audiences only Dropped

Audience label strings are chosen by the caller; this module does not define product-specific names.

Transport

NewHandler returns a stateless Streamable HTTP handler (StreamableHTTPOptions.Stateless). Each request is independent; no Mcp-Session-Id bookkeeping. That matches simple tool servers and works well behind load balancers.

Protocol support comes from the official Go MCP SDK (including recent protocol versions such as 2025-11-25 / 2026-07-28 as negotiated by the client).

Auth (deliberately out of scope)

The handler does not check credentials. Mount it behind your own middleware (Bearer, mTLS, etc.). Upstream is typically the internal API mux — already past auth — so tool calls do not re-send the Bearer token in-process.

Config reference

type Config struct {
    Name               string       // MCP serverInfo.name
    Version            string       // MCP serverInfo.version
    Instructions       string       // server-wide guidance (keep first ~512 chars useful)
    OpenAPIYAML        []byte       // OpenAPI 3 document
    Upstream           http.Handler // required; receives reconstructed requests
    PathPrefix         string       // optional path filter
    Audience           string       // optional; filter by x-audiences
    AudienceKey        string       // optional; default "x-audiences"
    IncludeUnannotated *bool        // optional; default true when Audience set
}

Instructions is advertised on initialize. Codex/ChatGPT use it as cross-tool guidance — put workflow constraints there, not only in individual operation descriptions.

Schema-only export

When you need the OpenAPI→tool mapping without MCP (for example OpenAI Responses / Chat Completions function tools):

tools, err := mcpopenapi.ParseToolSchemas(openAPIBytes, "/api/agent")
// tools[i].Name, Description, InputSchema, ReadOnly

// With audience filter (only ops that list "assistant"):
tools, err = mcpopenapi.ParseToolSchemasOpts(openAPIBytes, mcpopenapi.ParseOptions{
    Audience:           "assistant",
    IncludeUnannotated: mcpopenapi.Bool(false),
})

Limitations (v1)

  • Only application/json and text/plain request bodies
  • No cookie / form / multipart mapping
  • No OpenAPI link / callback / webhook support
  • Body property names that collide with path/query params are skipped (path/query win)

Tests

go test ./...

License

MIT

Documentation

Overview

Package mcpopenapi exposes an OpenAPI 3 document as MCP tools over Streamable HTTP, forwarding tools/call to an in-process Upstream handler.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool added in v0.3.0

func Bool(b bool) *bool

Bool returns a pointer to b for ParseOptions / Config fields.

func NewHandler

func NewHandler(cfg Config) (http.Handler, error)

NewHandler builds a Streamable HTTP MCP handler (stateless) whose tools mirror OpenAPI operations.

Types

type Config

type Config struct {
	// Name and Version are advertised in the MCP initialize result.
	Name    string
	Version string
	// Instructions is server-wide guidance for clients (keep the first ~512
	// characters self-contained for Codex/ChatGPT).
	Instructions string
	// OpenAPIYAML is an OpenAPI 3.x document (YAML or JSON).
	OpenAPIYAML []byte
	// Upstream receives reconstructed HTTP requests for each tools/call.
	// Paths match the OpenAPI paths (e.g. /api/agent/trips). Auth is the
	// caller's responsibility (typically edge Bearer around this handler).
	Upstream http.Handler
	// PathPrefix, when non-empty, keeps only operations under that path
	// prefix (e.g. "/api/agent"). Empty means all operations with an
	// operationId except those with explicit empty security.
	PathPrefix string
	// Audience, when non-empty, filters tools by the operation's audience
	// extension (see AudienceKey / IncludeUnannotated).
	Audience string
	// AudienceKey is the OpenAPI extension key for audiences. Empty means
	// "x-audiences".
	AudienceKey string
	// IncludeUnannotated controls operations that omit the audience
	// extension when Audience is set. nil means true (include them).
	IncludeUnannotated *bool
}

Config configures the OpenAPI→MCP bridge.

type ParseOptions added in v0.3.0

type ParseOptions struct {
	// PathPrefix, when non-empty, keeps only that path subtree.
	PathPrefix string
	// Audience, when non-empty, filters by the audience extension on each
	// operation (see AudienceKey).
	Audience string
	// AudienceKey is the OpenAPI extension key listing audiences for an
	// operation. Empty means "x-audiences".
	AudienceKey string
	// IncludeUnannotated controls operations that omit the audience
	// extension when Audience is set. nil means true (include them).
	// Set to false to keep only operations that explicitly list Audience.
	IncludeUnannotated *bool
}

ParseOptions configures OpenAPI→tool schema extraction.

type ToolSchema added in v0.2.0

type ToolSchema struct {
	Name        string
	Description string
	InputSchema map[string]any
	ReadOnly    bool
}

ToolSchema is an OpenAPI-derived tool definition usable by MCP or other tool runtimes (e.g. OpenAI function calling).

func ParseToolSchemas added in v0.2.0

func ParseToolSchemas(openAPIYAML []byte, pathPrefix string) ([]ToolSchema, error)

ParseToolSchemas turns an OpenAPI 3 document into tool schemas (one per operationId). PathPrefix, when non-empty, keeps only that path subtree. Operations with explicit empty security (public) are skipped, matching NewHandler.

func ParseToolSchemasOpts added in v0.3.0

func ParseToolSchemasOpts(openAPIYAML []byte, opts ParseOptions) ([]ToolSchema, error)

ParseToolSchemasOpts is like ParseToolSchemas with audience filtering.

Jump to

Keyboard shortcuts

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