mcp

package
v2.41.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package mcp exposes Huma operations as Model Context Protocol (MCP) tools.

It is an optional add-on: importing it has no effect on a Huma API until you call Attach. Operations opt in to being exposed as tools via the Tool operation modifier, so nothing is exposed to an MCP client unless you say so.

router := chi.NewMux()
api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0"))

huma.Get(api, "/greeting/{name}", greetingHandler, mcp.Tool())

mcp.Attach(api, mcp.Options{Name: "my-api", Version: "1.0.0"})
// MCP is now served over Streamable HTTP at /mcp.

Tool calls are executed by round-tripping through the API's router, so all of Huma's request parsing, validation, middleware, and response marshalling are reused unchanged.

Authorization

Because tool calls re-enter the API through its own router, authentication is whatever your existing middleware already does, enforced per operation, and identical whether the caller is curl or an MCP client. Nothing here needs to understand your tokens.

It only implements the resource-server half of MCP authorization: discovery metadata (RFC 9728), Server.SetChallenge, and forwarding the caller's credentials. Point ProtectedResourceMetadata.AuthorizationServers at whatever issues your tokens.

One rule this package cannot enforce for you: your middleware MUST reject tokens that were not issued for this resource. Accepting a token minted for another audience makes the server a confused deputy, letting a token intended for some other service drive these tools.

Index

Examples

Constants

View Source
const ProtocolVersion = "2026-07-28"

ProtocolVersion is the latest MCP protocol revision this package implements: the stateless revision, where every request carries its protocol version and client capabilities in _meta.

Clients of earlier, handshake-based revisions are served too. A request is handled under the stateless revision when it declares a version in _meta, or names one in the MCP-Protocol-Version header that no handshake-based revision uses; anything else is handled as the handshake-based revision negotiated by initialize.

Variables

This section is empty.

Functions

func Exclude

func Exclude() func(o *huma.Operation)

Exclude marks a Huma operation to never be exposed as an MCP tool. It is only meaningful when Options.ExposeVisible or Options.ExposeHidden is set; in the default opt-in mode, operations are already excluded unless marked with Tool.

func Tool

func Tool(opts ...ToolOption) func(o *huma.Operation)

Tool marks a Huma operation to be exposed as an MCP tool. Pass it as a trailing operation handler to huma.Get, huma.Post, etc., or apply it to a huma.Operation before calling huma.Register. Streaming (SSE) operations and ones whose request body is not JSON are never exposed, since they cannot work as tool calls.

huma.Post(api, "/things", createThing, mcp.Tool())
huma.Get(api, "/things/{id}", getThing, mcp.Tool(mcp.WithName("get_thing")))

func WithExclude

func WithExclude(op huma.Operation) huma.Operation

WithExclude returns a copy of op marked with Exclude, for use with huma.Register like WithTool.

func WithTool

func WithTool(op huma.Operation, opts ...ToolOption) huma.Operation

WithTool returns a copy of op marked as an MCP tool. Use it with huma.Register, which (unlike huma.Get, huma.Post, etc.) takes an operation value directly and does not accept trailing operation modifiers:

huma.Register(api, mcp.WithTool(huma.Operation{
	OperationID: "create-ticket",
	Method:      http.MethodPost,
	Path:        "/tickets",
	// ...
}), createTicketHandler)

It is equivalent to applying Tool(opts...) to the operation.

Types

type Options

type Options struct {
	// AllowedOrigins lists exact Origin values allowed on the transport, guarding
	// against DNS rebinding; others get 403. Requests without an Origin are
	// allowed. Empty allows any; set it whenever ForwardHeaders includes "Cookie".
	AllowedOrigins []string

	// ExposeHidden exposes every Hidden operation unless marked with [Exclude].
	// Operations added later are exposed too; pair it with Filter to offer each
	// caller only the tools it can use.
	//
	// Neither expose flag covers the MCP transport or Huma's docs and schema
	// routes.
	ExposeHidden bool

	// ExposeVisible exposes every non-hidden operation unless marked with
	// [Exclude]. Operations added later are exposed too.
	ExposeVisible bool

	// Filter, if set, decides per request which tools the caller can see and
	// call. It receives the incoming MCP request's context, carrying whatever
	// your middleware attached (such as the authenticated user), and the
	// operation behind the tool. A tool it rejects is left out of tools/list and
	// reported as unknown by tools/call, so a caller is only offered what it can
	// use, e.g. admin tools for admins.
	//
	// It narrows what is offered; it is not the authorization boundary. Every
	// tool call still runs through the operation's own middleware.
	Filter func(ctx context.Context, op *huma.Operation) bool

	// ForwardHeaders lists request header names copied from the incoming MCP
	// request onto each internal tool-execution request. This is how a caller's
	// credentials reach the operation's own middleware (which re-runs during the
	// tool call and enforces auth per operation). Defaults to
	// {"Authorization"}. Set to a non-nil empty slice to forward nothing.
	// Header parameters named here are not tool arguments, so the caller's value
	// is always the one sent.
	//
	// Cookie is not forwarded by default: browsers attach it on their own, so any
	// page that can reach this endpoint could run tools as the visitor. Set
	// AllowedOrigins if you add it.
	ForwardHeaders []string

	// Instructions is optional guidance returned to clients during
	// initialization describing how to use the exposed tools.
	Instructions string

	// Name of the MCP server, reported to clients during initialization. If
	// empty, the API's OpenAPI title is used.
	Name string

	// Path is the HTTP route for the Streamable HTTP transport. Defaults to
	// "/mcp".
	Path string

	// ProtectedResource, if set, is served at ResourceMetadataPath (RFC 9728) and
	// referenced by [Server.SetChallenge]. No tokens are validated or issued.
	ProtectedResource *ProtectedResourceMetadata

	// PublicURL is the external base URL (e.g. "https://api.example.com") used in
	// resource metadata and challenges. Set it in production: otherwise it comes
	// from the client-controlled Host header, which clients bind token audience to.
	PublicURL string

	// ResourceMetadataPath is the route at which ProtectedResource is served.
	// Defaults to "/.well-known/oauth-protected-resource" followed by Path, where
	// RFC 9728 looks for it when PublicURL has no path. The endpoint is public
	// (no Security), as required for discovery.
	ResourceMetadataPath string

	// Security is set on the transport operation so middleware keyed on
	// Operation().Security protects the MCP endpoint itself. Tools keep their own
	// auth.
	Security []map[string][]string

	// Version of the MCP server, reported to clients during initialization. If
	// empty, the API's OpenAPI version is used.
	Version string
}

Options configures an MCP server attached to a Huma API.

type ProtectedResourceMetadata

type ProtectedResourceMetadata struct {
	// Resource is the protected resource identifier (a URL). If empty, it is
	// derived per request from the request scheme + host and the MCP path (or
	// [Options.PublicURL] when set).
	Resource string `json:"resource,omitempty"`

	// AuthorizationServers lists the issuer identifier URLs of the authorization
	// servers that can issue tokens for this resource.
	AuthorizationServers []string `json:"authorization_servers,omitempty"`

	// JWKSURI is the URL of the resource server's JSON Web Key Set, if any.
	JWKSURI string `json:"jwks_uri,omitempty"`

	// ScopesSupported lists the OAuth scopes recognized by this resource.
	ScopesSupported []string `json:"scopes_supported,omitempty"`

	// BearerMethodsSupported lists how a bearer token may be presented, e.g.
	// "header". Defaults to {"header"} when served if left empty.
	BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`

	// ResourceName is a human-readable name for the resource.
	ResourceName string `json:"resource_name,omitempty"`

	// ResourceDocumentation is a URL with human-readable documentation.
	ResourceDocumentation string `json:"resource_documentation,omitempty"`

	// Extensions holds any additional metadata fields to include verbatim,
	// keeping the document open to registry parameters this struct does not name.
	Extensions map[string]any `json:"-"`
}

ProtectedResourceMetadata is the OAuth 2.0 Protected Resource Metadata document (RFC 9728) advertised by an MCP server so that clients such as ChatGPT and Claude connectors can discover which authorization server(s) to use.

type Server

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

Server is an MCP server backed by a set of Huma operations. Create one with Attach. It is safe for concurrent use.

func Attach

func Attach(api huma.API, opts Options) (huma.API, *Server)

Attach wires an MCP server onto an existing Huma API and returns a drop-in replacement API to register operations against, plus the Server.

Register operations against the returned API (not the original) so they can be exposed as MCP tools. Because it intercepts operation registration via huma.OperationDocumenter, it captures Hidden operations too, which never appear in the OpenAPI document:

api := humachi.New(router, config)
api, server := mcp.Attach(api, mcp.Options{Name: "my-api", Version: "1.0.0"})

huma.Get(api, "/admin/reset", resetHandler, mcp.Tool(), func(o *huma.Operation) {
	o.Hidden = true // hidden from docs, still callable as an MCP tool
})

Documented operations registered against the original API are still found; Hidden ones are not. api must be the root API, not a huma.Group: create groups from the API Attach returns.

Attach registers the Streamable HTTP transport (see Options.Path).

Example
package main

import (
	"context"
	"net/http"

	"github.com/danielgtaylor/huma/v2"
	"github.com/danielgtaylor/huma/v2/adapters/humago"
	"github.com/danielgtaylor/huma/v2/mcp"
)

func main() {
	mux := http.NewServeMux()
	api := humago.New(mux, huma.DefaultConfig("Greeting API", "1.0.0"))

	// Attach returns a drop-in API to register against; reassign so all
	// subsequent registrations flow through it (this is what lets Hidden
	// operations be exposed as tools). It also serves MCP over Streamable HTTP
	// at /mcp alongside the normal REST API.
	api, _ = mcp.Attach(api, mcp.Options{Name: "greeting", Version: "1.0.0"})

	type input struct {
		Name string `path:"name"`
	}
	type output struct {
		Body struct {
			Message string `json:"message"`
		}
	}

	// Opt this operation in as an MCP tool with mcp.Tool().
	huma.Get(api, "/greeting/{name}", func(_ context.Context, in *input) (*output, error) {
		out := &output{}
		out.Body.Message = "Hello, " + in.Name
		return out, nil
	}, mcp.Tool())

	// http.ListenAndServe(":8888", mux)
}

func (*Server) SetChallenge

func (s *Server) SetChallenge(ctx huma.Context)

SetChallenge sets an RFC 9728 WWW-Authenticate header pointing at the resource metadata document, so connectors can begin their OAuth flow. Call it from your auth middleware before writing the 401 as usual:

server.SetChallenge(ctx)
huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized")

Without Options.ProtectedResource the challenge is a bare "Bearer", which gives a connector nothing to discover.

Example
package main

import (
	"context"
	"errors"
	"net/http"
	"slices"
	"strings"

	"github.com/danielgtaylor/huma/v2"
	"github.com/danielgtaylor/huma/v2/adapters/humago"
	"github.com/danielgtaylor/huma/v2/mcp"
)

func main() {
	mux := http.NewServeMux()
	api := humago.New(mux, huma.DefaultConfig("Greeting API", "1.0.0"))

	const resource = "https://api.example.com/mcp"

	api, server := mcp.Attach(api, mcp.Options{
		Name:    "greeting",
		Version: "1.0.0",

		// Set in production: the resource identifier is what clients bind token
		// audience to, so it must not be derived from a client-supplied Host.
		PublicURL: "https://api.example.com",

		// Advertise where tokens come from, so connectors can run the OAuth flow
		// themselves. Serving that flow is the authorization server's job, not this
		// package's.
		ProtectedResource: &mcp.ProtectedResourceMetadata{
			AuthorizationServers: []string{"https://auth.example.com"},
			ScopesSupported:      []string{"mcp"},
		},

		// Required if you add "Cookie" to ForwardHeaders, and good practice anyway.
		AllowedOrigins: []string{"https://app.example.com"},
	})

	// Your own auth middleware. A 401 with the challenge lets connectors discover
	// the authorization server and sign in.
	api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
		claims, err := verifyToken(ctx.Context(), strings.TrimPrefix(ctx.Header("Authorization"), "Bearer "))
		// Reject tokens minted for anything other than this resource, otherwise a
		// token issued for another service could drive these tools.
		if err != nil || !slices.Contains(claims.Audience, resource) {
			server.SetChallenge(ctx)
			_ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized")
			return
		}

		next(huma.WithContext(ctx, context.WithValue(ctx.Context(), userIDKey{}, claims.Subject)))
	})

	type input struct {
		Name string `path:"name"`
	}
	type output struct {
		Body struct {
			Message string `json:"message"`
		}
	}

	huma.Get(api, "/greeting/{name}", func(ctx context.Context, in *input) (*output, error) {
		// ctx carries whatever the validate function attached.
		out := &output{}
		out.Body.Message = "Hello, " + in.Name
		return out, nil
	}, mcp.Tool())

	// http.ListenAndServe(":8888", mux)
}

type userIDKey struct{}

type tokenClaims struct {
	Audience []string
	Subject  string
}

// verifyToken stands in for whatever verifies your tokens, e.g. a JWKS-backed JWT
// parser or an introspection call.
func verifyToken(_ context.Context, token string) (*tokenClaims, error) {
	if token == "" {
		return nil, errors.New("empty token")
	}

	return &tokenClaims{Subject: "user-1", Audience: []string{"https://api.example.com/mcp"}}, nil
}

type ToolOption

type ToolOption func(*toolConfig)

ToolOption customizes how a single operation is exposed as an MCP tool.

func WithDescription

func WithDescription(description string) ToolOption

WithDescription overrides the tool description. By default the operation summary and description are combined.

func WithName

func WithName(name string) ToolOption

WithName overrides the tool name. By default the operation ID is used (sanitized to the MCP tool-name character set).

Jump to

Keyboard shortcuts

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