mcpguard

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 19 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.

Documentation

Overview

Package mcpguard is the access check in front of an MCP endpoint (Family Hub docs/PLAN.md §5.6), taken from Family Hub's internal/gateway:

  • Guard.Middleware finds the resource of the request path (Guard.MiddlewareFor is told it), checks the bearer access token, the person behind it and the resource switch, answers 401 the way the MCP authorization spec wants it, and puts the caller's core.AccessInfo and core.Person in the request context (AccessFrom, PersonFrom);
  • the helpers an application's MCP handler or proxy uses: the header policy (RequestHeaders, ResponseHeaders), the body cap (ReadBody), the in-flight cap (Guard.Admit, Guard.AdmitAccess), the failure limit for other doors (Guard.Refuse) and the relay of an answer that flushes server-sent events and pings an idle stream (Guard.Relay).

The application keeps what is its own: resolving the resource to something that runs (its 404s go in front of the middleware), MCP session ids, the identity it hands its servers, and its call log.

Index

Constants

View Source
const MaxBodyBytes = 1 << 20

MaxBodyBytes is the largest request body ReadBody takes.

View Source
const Scope = "mcp"

Scope is the OAuth scope of MCP traffic, which a 401 tells the assistant to ask for.

View Source
const SessionHeader = "Mcp-Session-Id"

SessionHeader is the MCP session id (Streamable HTTP, session management). It passes both ways; an application that binds session ids to a grant (Family Hub) unwraps it in the request before RequestHeaders and wraps it in the answer after ResponseHeaders.

Variables

This section is empty.

Functions

func AccessFrom

func AccessFrom(ctx context.Context) (core.AccessInfo, bool)

AccessFrom returns the access of the token that Guard.Middleware let through.

func PersonFrom

func PersonFrom(ctx context.Context) (core.Person, bool)

PersonFrom returns the person behind the token that Guard.Middleware let through, as the store had them then.

func ReadBody

func ReadBody(w http.ResponseWriter, r *http.Request) ([]byte, bool)

ReadBody buffers the request body: 413 above MaxBodyBytes, whether Content-Length says so or the body runs over, 408 when the client takes longer than httpsec.BodyReadTimeout to send it (review GK-17: a call holds its in-flight place while its body comes), and 400 when it cannot be read. ok is false once an answer is written. A body read in full leaves no read deadline behind, so a long answer (an event stream) is not cut.

func RequestHeaders

func RequestHeaders(dst, src http.Header)

RequestHeaders copies to dst the assistant's request headers in src that an MCP server may see: Content-Type, Accept, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID, Mcp-Method, Mcp-Name and every Mcp-Param-<name>.

func ResponseHeaders

func ResponseHeaders(dst, src http.Header)

ResponseHeaders copies to dst the MCP server's answer headers in src that the assistant may see: Content-Type and Mcp-Session-Id.

func SecureHeaders

func SecureHeaders(h http.Header)

SecureHeaders marks an answer as data that no browser should sniff, render or frame, and that no cache may keep: whatever an MCP server sends is served from the application's own origin, and is one family's alone. Middleware sets them on every answer; Relay replaces Cache-Control with "no-cache, no-store" on an event stream. An application calls it itself on the answers it writes in front of the middleware.

Types

type Guard

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

Guard is the access check of the MCP endpoints and the limits they share.

func New

func New(o Options) (*Guard, error)

New returns a Guard.

func (*Guard) Admit

func (g *Guard) Admit(w http.ResponseWriter, a core.AccountID, id core.ResourceID) (release func(), ok bool)

Admit takes a place for a call of account a in resource id among the Options.InFlightPerResource calls that may be inside it at once, or answers 429 with Retry-After. The caller gives the place back with release when the call ends (a second release does nothing). Every door into the same resource admits its calls here (Family Hub: its legacy REST door too), so that they share the places.

Admit counts by account whatever Options.InFlightKey says; a door that knows its caller uses AdmitAccess, which follows it. An application with PerPerson admits every door through AdmitAccess, so that they share the places.

func (*Guard) AdmitAccess added in v0.2.0

func (g *Guard) AdmitAccess(w http.ResponseWriter, info core.AccessInfo) (release func(), ok bool)

AdmitAccess is Admit for the caller the middleware let through (AccessFrom): it takes a place in info.ResourceID for info's account, or for info's person under PerPerson.

func (*Guard) Middleware

func (g *Guard) Middleware(next http.Handler) http.Handler

Middleware lets a request through to next only with a live access token for the resource of its path. In order:

  • every answer gets SecureHeaders;
  • a path outside Paths is 404;
  • no bearer token is 401 unauthorized;
  • a token that is unknown, dead or for another resource, or whose person is gone, disabled, past their term (core.Person.Active) or in another account, is 401 invalid_token (429 when the client's address has presented too many such tokens, see Refuse; a token the validator knows to be expired or revoked, and a valid token of a person who is gone or not active, are neither counted nor ever 429);
  • an account that may not use the resource now is 403;
  • a failure of the services behind it is 500, logged.

The 401s carry WWW-Authenticate with the resource's protected-resource metadata and Scope. The middleware does not check that the resource exists: an application with several resources answers its own 404 in front of it. next gets a request whose context holds the caller (AccessFrom, PersonFrom); in a framework that keeps its own request (Gin), read it from the *http.Request next is called with.

The resource is the one Paths finds in r.URL.Path as it is (review GK-1). The application must route on that same path, with no cleaning of dot segments or repeated slashes and not on the escaped path, or check that AccessFrom(ctx).ResourceID is the resource it forwards to: a router that cleans /mcp/a/../b into /mcp/b would hand b a request the guard let through with a token for a. MiddlewareFor takes the resource from the application instead, and is the safer choice for a route that serves one resource.

func (*Guard) MiddlewareFor added in v0.2.0

func (g *Guard) MiddlewareFor(id core.ResourceID) func(http.Handler) http.Handler

MiddlewareFor is Middleware for a handler that serves resource id alone, as the application's router decided: the token must be for id, whatever the path says. A request whose path Paths does not find id in (another resource, or none) is 404, so that a router that cleans or unescapes paths can never forward a token for one resource to another (review GK-1). Homie mounts exactly "/mcp" with MiddlewareFor("home") over core.SingleResource.

It panics when Paths cannot serve id (Paths.FromPath(Paths.Path(id)) is not id): a wiring mistake, like a bad ServeMux pattern.

func (*Guard) Refuse

func (g *Guard) Refuse(w http.ResponseWriter, r *http.Request, refusal func())

Refuse answers a credential the application does not know with refusal, unless the client's address has presented FailuresPerAddress such credentials in the last minute: 429 with Retry-After then. Every door of an application that takes credentials calls it on a refusal (Family Hub: its legacy REST door too), so that the failures of all doors count together; a request without a credential is no failure. A valid credential is never limited: the assistants call from shared egress addresses, and junk sent from one of them must not stop every family's connector there.

func (*Guard) Relay

func (g *Guard) Relay(ctx context.Context, w http.ResponseWriter, status int, body io.Reader) error

Relay sends an MCP server's answer to the assistant: status, then body as it comes. The caller has put the headers that pass on w already (ResponseHeaders). An event stream (Content-Type text/event-stream) gets Cache-Control "no-cache, no-store" and X-Accel-Buffering "no", its status and headers go out at once, every chunk is flushed as it arrives, and a stream that stays silent for the ping interval between two events gets ": ping" (Cloudflare cuts an answer that sends nothing for 100 s). Relay returns at the end of body (nil), on a read or write error, or, for an event stream, when ctx ends; ctx is the assistant's request's, so the caller tells a client that went away by ctx.Err(). The caller closes body.

type InFlightKey added in v0.2.0

type InFlightKey int

InFlightKey says who holds the in-flight places of a resource (Options.InFlightKey).

const (
	// PerAccount: every person of an account shares the places (Family Hub, where many families share each
	// resource).
	PerAccount InFlightKey = iota
	// PerPerson: each person has their own places (Homie, where one account is the whole household, guests included,
	// and one person's open event streams must not lock everyone else out).
	PerPerson
)

Holders of in-flight places.

type Options

type Options struct {
	// Site gives PublicURL for resource_metadata and ClientIP for the failure limit; New checks it (Site.Validate).
	// A header mode needs httpsec.PeerGuard trusting only the connector (see there).
	Site      core.Site
	Paths     core.ResourcePaths   // the resource of a request path (Family Hub: core.PerResource{Prefix: "/mcp/"})
	Tokens    core.TokenValidator  // the access tokens (package oauth)
	People    People               // a person who is gone, disabled, past their term or moved makes their tokens worthless
	Resources core.ResourceCatalog // Available: whether the token's account may use the resource now (403)
	// Brand gives the words of the answers' messages (ResourceWord: "module" when empty); nothing else of it is read.
	Brand core.Brand
	// PingInterval is how long an event stream may stay silent before Relay writes ": ping" into it; 0 means 25 s,
	// under Cloudflare's 100 s cut.
	PingInterval time.Duration
	// InFlightPerResource is how many calls may be inside one resource at once for each holder InFlightKey names,
	// open event streams included; 0 means 16.
	InFlightPerResource int
	// InFlightKey is who holds those places: PerAccount (the default, every person of an account shares them) or
	// PerPerson (each person has their own; for an application where one account is a whole household).
	InFlightKey InFlightKey
	// FailuresPerAddress is how many unknown credentials one client address may present a minute (Refuse); 0 means
	// 30.
	FailuresPerAddress int
	Log                *slog.Logger // nil discards
	Clock              core.Clock   // nil is time.Now
}

Options configure a Guard.

type People

type People interface {
	Get(ctx context.Context, id core.PersonID) (core.Person, error)
}

People finds the person behind an access token; store.PersonStore implements it.

Jump to

Keyboard shortcuts

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