gomcp

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 10 Imported by: 0 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

gomcp

A typed, opinionated MCP server layer for your Go backend
Coverage Status build status

A Model Context Protocol server for a Go backend, built from typed handlers and served over stateless Streamable HTTP behind a bearer token. A thin, opinionated layer over the official github.com/modelcontextprotocol/go-sdk (v1.8.0): the SDK speaks the protocol, gomcp fixes the choices every backend would otherwise make again — who the caller is, what a failed call shows, and which requests never reach a tool.

The package imports no web framework: Handler returns an http.Handler you mount on whatever router you already run.

Install

go get github.com/diegoclair/gomcp

Requires Go 1.27+.

Quickstart

type GetCardIn struct {
    CardID int64 `json:"cardId" jsonschema:"the card id"`
}

type GetCardOut struct {
    Name       string `json:"name"`
    LimitCents int64  `json:"limitCents"`
}

getCard := gomcp.Tool("fin_get_card", "Returns one card. Amounts are in cents.",
    func(ctx context.Context, in GetCardIn) (GetCardOut, error) {
        return cards.Get(ctx, in.CardID)
    },
    gomcp.ReadOnly(), gomcp.Title("Get card"))

server := gomcp.NewServer("financial-control", version, []gomcp.ToolDef{getCard},
    gomcp.WithPreInvoke(scopeToUser),
    gomcp.WithPostInvoke(audit),
    gomcp.WithErrorPolicy(showOnlyBusinessErrors))

handler, err := gomcp.Handler(server, gomcp.HandlerOptions{
    Verifier: verifyToken,
})

The input schema is inferred from In (with jsonschema: struct tags) and the output schema from Out; the SDK validates the arguments before your handler runs, and the output becomes the result's structuredContent.

Tools and their hints

Option Hint Use it for
ReadOnly() readOnlyHint: true reads, previews
Destructive(false) destructiveHint: false creates that only add, and reads that must state it
Destructive(true) or nothing destructiveHint unset, which MCP reads as true updates that overwrite
Idempotent() idempotentHint: true a create keyed by an idempotency key
OpenWorld(true) openWorldHint: true a tool that reaches a system the caller does not control
Title(s) title the name a client shows

A tool declares openWorldHint: false unless OpenWorld(true) says otherwise. A directory that requires every hint as an explicit boolean gets destructiveHint on a read only from Destructive(false).

Who is calling

Handler requires a Verifier (auth.TokenVerifier). The token it accepts reaches every tool call three ways:

  • Call.Caller in the PreInvoke and PostInvoke hooks;
  • gomcp.Caller(ctx), the full *auth.TokenInfo;
  • gomcp.UserID(ctx), which answers false when there is no identity, so an empty id is never read as a user.

PreInvoke returns the context the handler receives, which is the supported way to scope a call to its user with your own context keys:

func scopeToUser(ctx context.Context, call gomcp.Call) (context.Context, error) {
    if call.Caller == nil {
        return nil, errors.New("unauthenticated")
    }
    return reqctx.WithUserID(ctx, call.Caller.UserID), nil
}

A PreInvoke error rejects the call before the handler runs.

The verifier returns an error wrapping auth.ErrInvalidToken for an unknown or revoked token, which answers 401; any other error answers 500. A TokenInfo without an Expiration is accepted, because a token that never expires is valid for as long as the verifier says so:

func verifyToken(ctx context.Context, token string, _ *http.Request) (*auth.TokenInfo, error) {
    userID, err := tokens.Resolve(ctx, token)
    if errors.Is(err, ErrTokenNotFound) {
        return nil, fmt.Errorf("%w: %v", auth.ErrInvalidToken, err)
    }
    if err != nil {
        return nil, err
    }
    return &auth.TokenInfo{UserID: userID}, nil
}

Server instructions

WithInstructions sets the text a client receives once, in the initialize result: the vocabulary and conventions every tool shares, which no single tool's description should repeat.

Closed sets of values

WithTypeSchemas maps a Go type to the schema every tool input field of that type gets, instead of the inferred one. Give the field a named type and build its enum from the code that owns the values; the SDK then refuses any other value before the handler runs.

type marketplace string

gomcp.NewServer("shop", "v1", tools, gomcp.WithTypeSchemas(map[reflect.Type]*jsonschema.Schema{
	reflect.TypeFor[marketplace](): {Type: "string", Enum: []any{"north", "south"}},
}))

Output schemas that survive a deploy

A client caches each tool's output schema when it connects and validates the result's structuredContent against it. The inferred schema is closed (additionalProperties: false, every non-omitempty field required), so a field added or removed in a deploy is refused by every client connected before it, until it reconnects. WithOpenOutputSchemas publishes the output schemas open at every level, keeping types and descriptions:

gomcp.NewServer("shop", "v1", tools, gomcp.WithOpenOutputSchemas())

What a failed call shows

A handler error becomes a tool result with isError: true, so the model reads it and can correct itself; it is never a protocol error. By default the message is err.Error(). WithErrorPolicy decides what the client reads — typically your business errors as they are and everything else masked:

func showOnlyBusinessErrors(err error) string {
    if appErr, ok := apperr.AsAppError(err); ok && !apperr.IsInternal(err) {
        return appErr.Message()
    }
    return "internal error"
}

PostInvoke always receives the original error, before the policy rewrites it, which is where you log it.

A panic in a tool or in PreInvoke is recovered: it becomes an error wrapping ErrToolPanicked, with its stack, so the call fails and the server keeps serving.

Serving it

Handler serves Streamable HTTP in stateless mode with JSON responses: no Mcp-Session-Id, no session store, each POST stands alone. That is the only mode in which the go-sdk serves protocol 2026-07-28; older clients still negotiate an earlier revision on the same endpoint.

Requests are checked in this order:

  1. Origin. A request carrying an Origin header not listed in HandlerOptions.AllowedOrigins answers 403. Same-host is not enough: a page under DNS rebinding shares your Host. A request without Origin, as a non-browser client sends, passes to the next check.
  2. Bearer. No token, or one the verifier rejects, answers 401 with WWW-Authenticate. Set ResourceMetadataURL to announce the RFC 9728 document in that header.
  3. Host on loopback. The go-sdk refuses with 403 a request that reached a loopback listener under a non-loopback Host.
Echo v5
e.Any("/mcp", echo.WrapHandler(handler))
Behind a tunnel

A tunnel (cloudflared, ngrok) forwards a public Host to your loopback listener, which the DNS-rebinding guard refuses with 403. Behind one, set HandlerOptions.DisableLocalhostProtection: true; the bearer and the Origin allowlist still apply.

Protected resource metadata (RFC 9728)

An OAuth client discovers the authorization server from the document the WWW-Authenticate header points to. Serve it with the go-sdk's handler on the same URL you put in ResourceMetadataURL:

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

e.GET("/.well-known/oauth-protected-resource/mcp", echo.WrapHandler(
    auth.ProtectedResourceMetadataHandler(&oauthex.ProtectedResourceMetadata{
        Resource:             resource,
        AuthorizationServers: []string{"https://api.example.com"},
    })))

handler, err := gomcp.Handler(server, gomcp.HandlerOptions{
    Verifier:            verifyToken,
    ResourceMetadataURL: "https://api.example.com/.well-known/oauth-protected-resource/mcp",
})

Connecting Claude Code

claude mcp add --transport http financial-control http://localhost:5000/mcp \
  --header "Authorization: Bearer fcm_..."

License

MIT — see LICENSE.

Documentation

Overview

Package gomcp builds a Model Context Protocol server from typed Go handlers and serves it over stateless Streamable HTTP behind a bearer token.

Index

Constants

This section is empty.

Variables

View Source
var ErrToolPanicked = errors.New("gomcp: tool panicked")

Wraps the error a tool's panic becomes; PostInvoke and the ErrorPolicy receive it, and the client reads a tool error while the server keeps serving.

Functions

func Caller

func Caller(ctx context.Context) *auth.TokenInfo

Nil outside a tool call that carried a verified bearer token.

func Handler

func Handler(server *mcp.Server, opts HandlerOptions) (http.Handler, error)

A token without an expiration is accepted: whether it is still valid is the Verifier's answer.

func NewServer

func NewServer(name, version string, tools []ToolDef, opts ...Option) *mcp.Server

NewServer panics on a duplicate tool name or a type whose schema cannot be inferred, both of which are wiring mistakes caught at boot.

func UserID

func UserID(ctx context.Context) (string, bool)

False when there is no token or its UserID is empty, so a missing identity is never read as a user.

Types

type Call

type Call struct {
	Tool   string
	Input  any
	Caller *auth.TokenInfo
}

Caller is nil when the transport carried no bearer token.

type ErrorPolicy

type ErrorPolicy func(err error) string

type HandlerOptions

type HandlerOptions struct {
	// Must wrap auth.ErrInvalidToken for a rejected token; any other error answers 500.
	Verifier auth.TokenVerifier
	// Full origins (scheme://host[:port]); a request carrying any other Origin gets 403.
	AllowedOrigins      []string
	ResourceMetadataURL string
	// Required behind a tunnel that forwards a public Host to a loopback listener.
	DisableLocalhostProtection bool
}

type Option

type Option func(*config)

func WithErrorPolicy

func WithErrorPolicy(policy ErrorPolicy) Option

The default shows the client err.Error().

func WithInstructions added in v0.2.0

func WithInstructions(instructions string) Option

Sent once in the initialize result, for what no single tool's description can carry.

func WithOpenOutputSchemas added in v0.3.0

func WithOpenOutputSchemas() Option

Publishes every typed tool's output schema with no required field and no closed object, so a client that cached it before a deploy still accepts an output that gained or lost a field.

func WithPostInvoke

func WithPostInvoke(hook PostInvoke) Option

func WithPreInvoke

func WithPreInvoke(hook PreInvoke) Option

func WithTypeSchemas added in v0.2.0

func WithTypeSchemas(schemas map[reflect.Type]*jsonschema.Schema) Option

Lets a closed set of values the caller owns reach the client as an enum on every input field of that type, which the SDK then enforces before the handler runs.

type PostInvoke

type PostInvoke func(ctx context.Context, call Call, output any, err error)

Receives the handler's own error, before the ErrorPolicy rewrites it.

type PreInvoke

type PreInvoke func(ctx context.Context, call Call) (context.Context, error)

The context returned is the one the handler receives; an error rejects the call before the handler runs.

type ToolDef

type ToolDef interface {
	// contains filtered or unexported methods
}

func Tool

func Tool[In, Out any](name, description string, handler func(ctx context.Context, in In) (Out, error), opts ...ToolOption) ToolDef

A tool declares a closed world unless OpenWorld says otherwise.

type ToolOption

type ToolOption func(*mcp.ToolAnnotations)

func Destructive

func Destructive(destructive bool) ToolOption

Destructive is meaningful only on a tool that is not ReadOnly; MCP assumes true when it is never set.

func Idempotent

func Idempotent() ToolOption

func OpenWorld added in v0.4.0

func OpenWorld(openWorld bool) ToolOption

OpenWorld(true) marks a tool that reaches a system the caller does not control; without it the world is closed.

func ReadOnly

func ReadOnly() ToolOption

func Title

func Title(title string) ToolOption

Jump to

Keyboard shortcuts

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