Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/docs/features/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Features include:
- [RFC 7386](https://www.rfc-editor.org/rfc/rfc7386) JSON Merge Patch
- [RFC 6902](https://www.rfc-editor.org/rfc/rfc6902) JSON Patch
- [Shorthand](https://github.com/danielgtaylor/shorthand) patches
- Optional [MCP](mcp.md) server exposing operations as tools for LLM clients
- Annotated Go types for input and output models
- Generates JSON Schema from Go types
- Static typing for path/query/header params, bodies, response headers, etc.
Expand Down
87 changes: 87 additions & 0 deletions docs/docs/features/mcp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
---
description: Expose operations as Model Context Protocol (MCP) tools for LLM clients.
---

# Model Context Protocol (MCP)

## MCP { .hidden }

The [`mcp`](https://pkg.go.dev/github.com/danielgtaylor/huma/v2/mcp) package exposes your operations as [Model Context Protocol](https://modelcontextprotocol.io/) tools, so LLM clients like Claude or ChatGPT can call them. Each tool call is sent back through your API's router as a normal request, so validation, middleware, and auth all apply exactly as they do for any other client.

```go title="code.go"
import "github.com/danielgtaylor/huma/v2/mcp"

// ...

// Attach before registering operations, and register against the returned API.
api, _ = mcp.Attach(api, mcp.Options{})

// Opt an operation in as a tool.
huma.Get(api, "/greeting/{name}", greet, mcp.Tool())
```

MCP is now served at `POST /mcp`. Tool arguments are generated from the operation's parameters and request body, and the tool name defaults to the operation ID.

!!! info "Hidden Operations"

Operations registered against the returned API can be exposed even when `Hidden`, which keeps them out of the OpenAPI document. This is why `Attach` should be called first.

## Choosing Tools

Nothing is exposed unless you opt in. Use `mcp.Tool()` with `huma.Get`, `huma.Post`, etc., or `mcp.WithTool(op)` with `huma.Register`. Both accept `mcp.WithName` and `mcp.WithDescription` to override the defaults.

To expose everything instead, set `ExposeVisible` and/or `ExposeHidden` in the options, and opt individual operations out with `mcp.Exclude()`, or `mcp.WithExclude(op)` with `huma.Register`. Keep in mind that any operation added later becomes a tool too. Streaming (SSE) operations and ones whose request body is not JSON are skipped, since they can't work as tool calls.

## Authentication

The `Authorization` header from the MCP request is forwarded onto each tool call, so your existing auth middleware already protects every tool. What the package adds is discovery, so a client can find out where to sign in:

- `ProtectedResource` serves [OAuth 2.0 Protected Resource Metadata](https://www.rfc-editor.org/rfc/rfc9728) naming your authorization server.
- `server.SetChallenge(ctx)` sets a `WWW-Authenticate` header pointing at it. Call it from your middleware before writing a `401`.

Huma never validates or issues tokens; that stays with your middleware and authorization server, as described in [OAuth 2.0 & JWT](../how-to/oauth2-jwt.md).

```go title="code.go" hl_lines="2-7 17"
api, server := mcp.Attach(api, mcp.Options{
PublicURL: "https://api.example.com",
ProtectedResource: &mcp.ProtectedResourceMetadata{
AuthorizationServers: []string{"https://auth.example.com"},
},
// Require auth on the MCP endpoint itself.
Security: []map[string][]string{{"bearer": {}}},
})

api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
if len(ctx.Operation().Security) == 0 {
next(ctx)
return
}

if !validToken(ctx.Header("Authorization")) {
server.SetChallenge(ctx)
huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized")
return
}

next(ctx)
})
```

!!! warning "Token Audience"

Your middleware **must** reject tokens that were not issued for this API's MCP endpoint (`PublicURL` plus the MCP path), otherwise a token minted for another service could be used to call your tools. Set `PublicURL` in production, as the default derives it from the client-controlled `Host` header.

Use `Filter` to hide tools a caller can't use, e.g. admin tools for regular users. It only affects which tools are offered; each call still runs through the operation's own middleware.

See the [mcp-auth example](https://github.com/danielgtaylor/huma/tree/main/examples/mcp-auth) for a full runnable version.

## Dive Deeper

- Reference
- [`mcp.Attach`](https://pkg.go.dev/github.com/danielgtaylor/huma/v2/mcp#Attach)
- [`mcp.Options`](https://pkg.go.dev/github.com/danielgtaylor/huma/v2/mcp#Options)
- [`mcp.Tool`](https://pkg.go.dev/github.com/danielgtaylor/huma/v2/mcp#Tool)
- [`mcp.Server.SetChallenge`](https://pkg.go.dev/github.com/danielgtaylor/huma/v2/mcp#Server.SetChallenge)
- External Links
- [Model Context Protocol](https://modelcontextprotocol.io/)
- [MCP Authorization](https://modelcontextprotocol.io/specification/latest/basic/authorization)
1 change: 1 addition & 0 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ nav:
- "Extra Packages":
- "Auto PATCH Operations": features/auto-patch.md
- "Conditional Requests": features/conditional-requests.md
- "Model Context Protocol (MCP)": features/mcp.md
- "Server Sent Events (SSE)": features/server-sent-events-sse.md
- "Test Utilities": features/test-utilities.md
- "Clients":
Expand Down
170 changes: 170 additions & 0 deletions examples/mcp-auth/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
// This example shows how to serve an authenticated MCP server, so a connector
// like ChatGPT or Claude can discover how to authenticate and then call your
// operations as tools.
//
// Huma serves the discovery metadata and challenges unauthenticated requests.
// Issuing tokens is your authorization server's job, and verifying them is your
// middleware's: see verifyToken below.
//
// # Discovery, which must work before the client has a token.
// curl localhost:8888/.well-known/oauth-protected-resource/mcp
//
// # No token: 401 pointing at that document.
// curl -i -X POST localhost:8888/mcp -d '{"jsonrpc":"2.0","id":1,"method":"ping"}'
//
// # List and call tools.
// curl -X POST localhost:8888/mcp -H 'Authorization: Bearer demo-token' \
// -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
//
// curl -X POST localhost:8888/mcp -H 'Authorization: Bearer demo-token' \
// -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"greet","arguments":{"name":"world"}}}'
package main

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

"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humachi"
"github.com/danielgtaylor/huma/v2/humacli"
"github.com/danielgtaylor/huma/v2/mcp"
"github.com/go-chi/chi/v5"
)

// Options for the CLI.
type Options struct {
AuthServerURL string `doc:"Issuer URL of the authorization server" default:"http://localhost:9000"`

Port int `doc:"Port to listen on" default:"8888"`

// Set this in production. The resource identifier built from it is what clients
// bind token audience to, so it must not come from the request's Host header.
PublicURL string `doc:"Public base URL of this API" default:"http://localhost:8888"`
}

type userKey struct{}

type claims struct {
Audience []string
Subject string
}

// verifyToken stands in for your own verification: a JWKS-backed JWT parse, an
// introspection call, or a database lookup. It must report the audience.
func verifyToken(_ context.Context, token string) (*claims, error) {
if token != "demo-token" {
return nil, errors.New("unknown token")
}

return &claims{Subject: "user-1", Audience: []string{"http://localhost:8888/mcp"}}, nil
}

type GreetingInput struct {
Name string `path:"name" maxLength:"30" example:"world"`
}

type GreetingOutput struct {
Body struct {
For string `json:"for" doc:"Authenticated user the greeting was for"`
Message string `json:"message" doc:"Greeting message"`
}
}

func main() {
cli := humacli.New(func(hooks humacli.Hooks, options *Options) {
router := chi.NewMux()
api := humachi.New(router, huma.DefaultConfig("Greeting API", "1.0.0"))

resource := options.PublicURL + "/mcp"

// Register operations against the returned API, or Hidden ones will not
// become tools.
api, server := mcp.Attach(api, mcp.Options{
Name: "greeting",
Version: "1.0.0",
PublicURL: options.PublicURL,
ProtectedResource: &mcp.ProtectedResourceMetadata{
AuthorizationServers: []string{options.AuthServerURL},
ScopesSupported: []string{"mcp"},
ResourceName: "Greeting API",
},
Security: []map[string][]string{{"bearer": {"mcp"}}},
AllowedOrigins: []string{options.PublicURL},
ExposeVisible: true,
})

// Authenticates the MCP transport and every operation with a Security
// requirement. The challenge tells connectors where to sign in.
api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
if len(ctx.Operation().Security) == 0 {
next(ctx)
return
}

c, err := verifyToken(ctx.Context(), strings.TrimPrefix(ctx.Header("Authorization"), "Bearer "))
// Required: a token issued for another service must not drive these
// tools. Huma cannot check this, as it never inspects tokens.
if err != nil || !slices.Contains(c.Audience, resource) {
server.SetChallenge(ctx)
_ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized")
return
}

next(huma.WithContext(ctx, context.WithValue(ctx.Context(), userKey{}, c.Subject)))
})

huma.Register(api, mcp.WithTool(huma.Operation{
OperationID: "get-greeting",
Summary: "Greet a user by name",
Method: http.MethodGet,
Path: "/greeting/{name}",
Security: []map[string][]string{{"bearer": {"mcp"}}},
}, mcp.WithName("greet")), func(ctx context.Context, in *GreetingInput) (*GreetingOutput, error) {
out := &GreetingOutput{}
out.Body.Message = "Hello, " + in.Name
out.Body.For, _ = ctx.Value(userKey{}).(string)

return out, nil
})

// Hidden keeps an operation out of the OpenAPI document. Marking it with
// WithTool still exposes it as a tool.
huma.Register(api, mcp.WithTool(huma.Operation{
OperationID: "reset",
Summary: "Reset the service",
Method: http.MethodPost,
Path: "/admin/reset",
Security: []map[string][]string{{"bearer": {"mcp"}}},
Hidden: true,
}, mcp.WithName("admin_reset")), func(ctx context.Context, _ *struct{}) (*GreetingOutput, error) {
out := &GreetingOutput{}
out.Body.Message = "reset"
out.Body.For, _ = ctx.Value(userKey{}).(string)

return out, nil
})

s := http.Server{
Addr: fmt.Sprintf(":%d", options.Port),
Handler: router,
}

hooks.OnStart(func() {
fmt.Printf("MCP on %s/mcp, try Bearer demo-token\n", options.PublicURL)
s.ListenAndServe()
})

hooks.OnStop(func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
s.Shutdown(ctx)
})
})

cli.Run()
}
Loading
Loading