mcpapi

package
v0.83.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause, AGPL-3.0 Imports: 51 Imported by: 0

README

MCP endpoint and OAuth broker

This package serves the management REST API as a Model Context Protocol server at /api/mcp, and runs an OAuth 2.1 authorization server (the broker) so MCP clients can sign users in without a personal access token. Both are off unless NB_MCP_ENABLED is true.

How tool calls work

  • Every tool maps onto exactly one REST operation: list_peers is GET /api/peers, update_peer is PUT /api/peers/{peer_id}. The catalog is in catalog.go.
  • A tool call is replayed in-process against the API router, so it runs the same handler and permission checks and returns the same JSON as the REST call. A non-2xx response becomes a tool error carrying the status and the API's error body, and a panic in a handler is recovered into a tool error.
  • Input schemas are derived from the generated request types in shared/management/http/api, with path and query arguments added as top-level properties. Arguments are validated against the schema before the request is built, so a misspelled, missing or mistyped field fails the call instead of reaching an update as a zero value. A path argument containing / or \, or . or .., is refused, and so is one that lands the request on another API route, such as routers for get_network.
  • account_id is never taken from the client. Dispatch fills it from the caller's identity (callerBound in catalog.go), so update_account only acts on the account the request is authenticated for.
  • update_* tools have PUT semantics: an omitted field resets. Their descriptions say so, and they are annotated destructive, like the delete tools.
  • The catalog only holds operations the public OpenAPI spec (shared/management/http/api/openapi.yml) documents and does not mark x-cloud-only; openapi_test.go enforces it. Account deletion is left out: a deployment may guard it with middleware on the root router, as NetBird Cloud does for MSP tenants, and in-process dispatch does not pass through that router.

The transport is streamable HTTP in stateless mode with JSON responses. Every JSON-RPC message is its own HTTP request, so each tool call is authenticated, rate limited and metered like the REST call it stands for. JSON-RPC batches are refused with 400, so one request carries at most one tool call. GET and DELETE answer 405.

mcpapi_test.go fails when a tool description or the server instructions name a tool the catalog does not have.

A new public endpoint, one openapi.yml documents without x-cloud-only, needs either a tool in catalog.go or an entry with its reason in notExposed in openapi_test.go, which lists what is left out today and why. The MCP Catalog check (.github/workflows/mcp-catalog.yml) enforces this on pull requests and pushes to main, along with the reverse: every tool is a public operation, and the API router serves it on its own route.

Enabling

Variable Meaning
NB_MCP_ENABLED A true value (strconv.ParseBool) mounts /api/mcp and, when it can start, the broker. Unset, false or unparseable leaves both off; an unparseable value is logged.
NB_MCP_TOOLS Optional comma-separated tool allowlist. Empty exposes the whole catalog. An unknown name stops management at boot.
NB_MCP_OAUTH_KEY Optional secret of at least 32 bytes that seals the broker's codes and tokens. See Keys.
NB_CACHE_REDIS_ADDRESS Management's existing shared cache address. When set, broker grants live there. See Grants.

With NB_API_RATE_LIMITING_ENABLED=true, PAT calls are limited per token by the API middleware and broker-token calls per user with the same limiter settings; over the limit answers 429.

Connecting a client

Clients connect to https://<management>/api/mcp, the scheme and host the dashboard calls the API on, with a personal access token in the Authorization header or through OAuth, which needs only the URL. Setup for users belongs in the NetBird docs.

Accepted credentials
Authorization header Accepted on
Token nbp_... (personal access token) The whole API, /api/mcp included
Bearer <JWT> (dashboard login) The whole API, /api/mcp included
Bearer nbmcp_... (broker access token) Exactly /api/mcp; anywhere else the API authentication rejects it

OAuth broker

Identity providers rarely offer open dynamic client registration or tokens scoped to one MCP server, so management runs its own authorization server under /api/mcp/auth. It registers clients, renders consent, sends the user to the identity provider only to log in, receives that login on its own callback, and issues its own tokens.

The broker starts when NB_MCP_ENABLED is true, a PKCE flow is available (see Identity provider setup), the keys resolve and the grant store is reachable. Otherwise management logs why, /api/mcp accepts PATs and JWTs only, and its 401 carries no pointer to OAuth metadata.

Endpoints

The MCP endpoint is POST /api/mcp. The authorization server's endpoints sit under /api/mcp/auth. Three discovery documents are served at the root, where clients look first; Reverse proxy covers the forms under /api.

  • /.well-known/oauth-protected-resource/api/mcp (RFC 9728)
  • /.well-known/oauth-authorization-server/api/mcp/auth (RFC 8414)
  • /.well-known/openid-configuration/api/mcp/auth

Everything but /api/mcp bypasses the API authentication and its rate limiter. The issuer is <base>/api/mcp/auth and the resource <base>/api/mcp, where <base> comes from the embedded IdP's issuer or else the request; see Reverse proxy.

The flow
  1. Discovery and registration. A call to /api/mcp without a valid credential gets 401 with an RFC 9728 resource_metadata pointer. Registration is open and stores nothing: the client ID seals the redirect URIs and the name, and never expires. Only https redirect URIs, or http on a loopback host, are kept.
  2. Authorize. redirect_uri must match a registered one exactly, or on any port for loopback http (RFC 8252 section 7.3), and PKCE S256 is required. A malformed request is redirected as an OAuth error only to a loopback client; an https client gets an error page, since open registration would otherwise make this an open redirector.
  3. Consent. The page names the client and the host the code goes to; write access is an unticked checkbox, offered when the client asked for mcp:write or no scope, so a connection stays read-only unless the user opts in. The request is sealed into the form and bound to the browser by the consent cookie, a post from another origin (by Sec-Fetch-Site) gets 403, and the page is unframeable and arms the approve button only after pointer or keyboard input.
  4. Login. Approve sends the user to the identity provider with the broker's own PKCE verifier, state and callback; the client's challenge, state and redirect URI never reach it, and no prompt=login is sent. The callback validates the returned token like a dashboard login, JWT group restrictions included, requires a user of that account who is neither blocked nor pending approval, and discards the identity provider's token.
  5. Token. A code lasts 2 minutes and redeems once, for the client ID, redirect_uri, PKCE verifier and resource it was issued to. A second redemption also revokes the session the first one started (OAuth 2.1 section 4.1.3).
  6. Calling /api/mcp. AuthMiddleware checks a broker token itself: unexpired, issued for this <base>/api/mcp, and its grant still there. The user is reloaded on every call and must still exist, be neither blocked nor pending approval, belong to the same account, and not have been created more than a minute after the session began. A refused token answers 401 with the challenge; a grant or user store outage answers 503. The call runs as that user with the granted scopes; without mcp:write, tools that change data return a tool error.
Sessions and refresh

A code redemption starts a session that ends 30 days later; refreshing never moves that end. Access tokens last 1 hour and never outlive the session. Refresh tokens rotate on each use (OAuth 2.1 section 4.3.1):

  • For 10 seconds after a rotation, the replaced and the new token both get the current tokens without another rotation, so a refresh burst cannot chain rotations.
  • Each refresh is one atomic step on the grant (a Lua script in Redis, a mutex in memory), so racing refreshes rotate once and a revocation cannot interleave.
  • Any older refresh token is a replay: it is refused and the whole session is revoked.
  • When the grant store or the user store cannot answer, token requests and MCP calls get 503 instead of an error that makes the client sign in again. A rotation whose reply was lost may still have landed: a retry within 10 seconds gets its result, a later one presents the replaced token and is a replay.
Sealed values

Client IDs, codes, tokens and the consent and login state are JSON sealed with AES-256-GCM, with the purpose bound as associated data so one kind cannot be replayed as another. Client IDs start with nbmcpc_, codes with nbmcpk_, access tokens with nbmcp_ and refresh tokens with nbmcpr_, which secret scanners can match. Codes and tokens carry the user ID, account ID, a SHA-256 fingerprint of the client ID, the resource and the scopes, never the identity provider's token.

Grants

A grant is the record of one login, created when its code is redeemed. Grants live in Redis at NB_CACHE_REDIS_ADDRESS (or the legacy NB_IDP_CACHE_REDIS_ADDRESS) on a connection of the broker's own, else in the management process. If Redis is configured but unreachable at boot, the broker does not start. Keys start with mcp-oauth:, and deleting mcp-oauth:session:* ends every session.

Management running as more than one instance needs Redis. The in-memory store suits a single instance, and a restart signs every MCP client out. Losing the store never lets a token through; while it is unavailable, PATs keep working.

Keys

Sealing keys are derived with HKDF-SHA256:

Seals Secret, first one set wins
Codes, tokens, consent and login state NB_MCP_OAUTH_KEY, the datastore encryption key
Client IDs The datastore encryption key, NB_MCP_OAUTH_KEY

Every instance serving the same host needs the same secrets. Changing NB_MCP_OAUTH_KEY signs every MCP client out at once; client IDs survive, so clients sign in again with the registration they have. Removing it falls back to the datastore key, which revives unexpired tokens sealed with that key. A value shorter than 32 bytes keeps the broker from starting rather than falling back. Generate one with openssl rand -base64 32.

The management command saves a generated datastore key to its config file as DataStoreEncryptionKey; the combined server generates one per start unless server.store.encryptionKey is set. Persist it.

Cookies

The consent cookie (SameSite=Strict) ties the consent form to the browser, and the login cookie (Lax, since the identity provider returns the user with a cross-site navigation) carries the login state to the callback. Both are HttpOnly, last 10 minutes and are cleared once used. Over https they are __Host- cookies, which a sibling subdomain cannot plant; over plain http they lack that protection. Names are fixed, so a second connection started before the first finishes ends the first on an error page.

Revocation model
To cut off Do Takes effect
One connection The client calls the revocation endpoint with either token; a client_id, when sent, must match Next MCP call and refresh
One user on every client Block or remove the user in NetBird, or move them to another account Next MCP call and refresh
Every MCP client of every user Change NB_MCP_OAUTH_KEY Once every instance restarts with it
A user disabled at the identity provider or removed from JWT allow groups Nothing, or block the user in NetBird for immediate effect Next login, at most 30 days later

A stolen access token gives the user's API access through /api/mcp, within its scopes, for at most 1 hour. A stolen refresh token works until the thief and the client refresh more than 10 seconds apart: the later of the two presents a replaced token, which is a replay and revokes the session for both. A stolen code is useless without the client's PKCE verifier.

Activity log

The broker records three events in the account the user signed in to, with that user as initiator and target: mcp.session.start when a code redemption starts a session, mcp.session.revoke when the revocation endpoint ends one that still existed, and mcp.session.replay when a replayed refresh token or a second redemption of a code revokes one. A replay that finds the session already ended records nothing. For a code that gap is at most its 2 minutes, and the sign-out or replay that ended the session is already in the log. Meta holds:

  • access: read or read and write, the scopes the user approved. The user's role still limits what the session can do.
  • client_name, when the request carries the client ID: the name the client registered, with control characters and characters that render as nothing removed. It proves nothing.
  • redirect_host, on the two events a code redemption records.
Security notes
  • Consent is asked on every authorization. The client name is self-chosen and proves nothing; the redirect host tells the user where the code goes.
  • Unauthenticated endpoints take no credential. A value the broker did not seal is refused when it fails to decrypt, before any store, database or identity provider call, and registration stores nothing. Anyone can mint the login cookie the callback takes, though, and each callback stores a marker and may call the identity provider, so the callback is limited to 30 per minute per client address. The address comes from X-Forwarded-For only when the request arrives from one of ReverseProxy.TrustedHTTPProxies; otherwise everyone behind the proxy shares one budget. TrustedHTTPProxiesCount is not used: trusting the header by position lets a client that reaches management directly choose its own address. List the proxy in TrustedHTTPProxies for a budget per client.
  • Forwarded headers are trusted from any caller when the base URL comes from the request. See Reverse proxy.

Identity provider setup

Embedded IdP (Dex). Nothing to configure. The broker logs users in with the netbird-cli public client via PKCE. EmbeddedIdPConfig.ToYAMLConfig (management/server/idp/embedded.go) adds <base>/api/mcp/auth/callback (MCPCallbackPath) to the redirect URIs of Dex's dashboard and CLI clients, and BaseServer.mcpBaseURL uses the same <base>: the issuer without its /oauth2 suffix. The issuer must have the form <scheme>://<host>/oauth2 with no trailing slash, as the getting-started setup writes it, or the broker does not start and logs why. MCP clients must connect at that host, since the resource metadata and the accepted resource name it.

External IdP. The broker uses the PKCEAuthorizationFlow block in management.json, the one netbird up SSO login uses. It reads ClientID, AuthorizationEndpoint and TokenEndpoint (all required), Scope, Audience, UseIDToken, and ClientSecret when the client is confidential. RedirectURLs and LoginFlag are not used. Add https://<management>/api/mcp/auth/callback to that application's allowed redirect URIs, once for every host MCP clients use. The code exchange goes through golang.org/x/oauth2 as in netbird up, so a secret is sent in HTTP Basic or the form, whichever the provider takes, and the token is checked with the validator an agent's SSO login goes through. A flow that works for netbird up works here once the callback is allowed, unless the provider requires the client certificate agents can present (ClientCertPath): the broker presents none.

Reverse proxy

  • Only /api and /oauth2 (the embedded IdP) need to reach management. The challenge points to the resource metadata under /api, and the server metadata is also served at /api/mcp/auth/.well-known/openid-configuration, the last form MCP clients try. Clients validate that form as OpenID provider metadata, so it also carries jwks_uri (an empty key set at /api/mcp/auth/jwks), subject_types_supported and id_token_signing_alg_values_supported.
  • Clients try the root /.well-known/... forms first. The NetBird dashboard image answers unknown paths with 404, so clients move on to the /api form. A proxy or frontend that answers them with 200 and HTML stops some clients there: route the three root documents to management in that case.
  • With the embedded IdP, <base> comes from its issuer and forwarding headers are ignored. Without it, <base> takes its scheme from TLS or X-Forwarded-Proto and its host from X-Forwarded-Host or Host (first list entry), and the issuer, resource, callback and cookie security follow. The proxy must set or overwrite both headers; omitting X-Forwarded-Proto: https yields an http:// callback the identity provider rejects.
  • A proxy on the same host may connect over 127.0.0.1 and forward the public Host. The MCP SDK's DNS rebinding check would refuse that with 403, so it is off: every call carries its credential in a header, which a rebound page cannot obtain.

Tenant URLs

/api/mcp?account=<account id> is accepted; the challenge, the resource metadata and the accepted resource values repeat the query (RFC 9728 section 3.3), while tokens bind to host and path only, so one sign-in serves every account URL. A deployment can add a middleware that switches the request to that account when the caller may manage it. Either way requireTenant (server.go) answers 403 unless the request ended up on that account, so tools never silently run against the caller's own account, and 400 for an unparseable query, an empty account or a key such as Account. This repository has no switching middleware, so only the caller's own account ID passes.

Self-hosted metrics

mcpMetrics (management/internals/server/mcp.go) adds these properties to the anonymous self-hosted metrics, which --disable-anonymous-metrics (or disableAnonymousMetrics in the combined server config) turns off:

Property Meaning
mcp_enabled NB_MCP_ENABLED is true
mcp_oauth_enabled The broker is running
mcp_tool_calls_last_day Tool calls, those returning a tool error included, in the current hour and the 23 before
mcp_active_users_last_day Distinct users who made those calls

Usage (usage.go) counts in memory per process in hourly buckets, so a restart resets it and each instance reports its own. User IDs are kept only to count them and are never reported.

Wiring

management/internals/server/mcp.go builds the broker and mounts the endpoint (MCPBroker, mcpBaseURL, registerMCPEndpoints, mcpMetrics). In boot.go, Router installs ChallengeMiddleware and wraps the auth middleware, the last element of BuildMiddleware, with AuthMiddleware; APIHandler mounts everything in its http_mcp block.

Tests

go test ./management/internals/modules/mcpapi/...
go test -run MCP ./management/internals/server/
go test -tags integration -run MCP ./management/server/http/testing/integration/
go test -tags e2e -timeout 25m -v ./e2e/mcp/...

The server test boots BaseServer with the embedded IdP and signs in through Dex. The integration test runs tool calls against the real handlers and store with two accounts and checks that no tool reads or changes the other one. The e2e suite runs the combined server with only NB_MCP_ENABLED=true and drives a PAT session and the full OAuth login through Dex.

Documentation

Overview

Package mcpapi serves the management REST API as a Model Context Protocol server, together with the OAuth 2.1 authorization server MCP clients sign in with.

Every tool maps onto one REST operation and is executed by replaying the call in-process against the API router, so a tool call and the matching HTTP request run the same handler, the same permission checks and return the same JSON. The endpoint is mounted behind the API authentication middleware and takes the caller identity from the request context.

Index

Constants

View Source
const (
	// EnvEnabled switches the MCP endpoint and its authorization server on. They are off
	// unless it is set to a true value.
	EnvEnabled = "NB_MCP_ENABLED"

	// Path is where the MCP endpoint is mounted, relative to the API router.
	Path = "/mcp"
)
View Source
const EnvOAuthKey = "NB_MCP_OAUTH_KEY"

EnvOAuthKey, when set, is the secret the broker seals codes and tokens with, in place of the datastore encryption key. Changing it signs every MCP client out at once. Instances serving the same domain must share it.

View Source
const (
	// EnvTools is a comma-separated allowlist of tool names. Empty exposes the whole catalog.
	EnvTools = "NB_MCP_TOOLS"
)
View Source
const (

	// ProtectedResourcePath serves the RFC 9728 protected resource metadata for the MCP
	// endpoint. MCP clients read it to learn which authorization server issues tokens.
	ProtectedResourcePath = "/.well-known/oauth-protected-resource" + apiPrefix + Path
)

Variables

This section is empty.

Functions

func EnabledByEnv

func EnabledByEnv() bool

EnabledByEnv reports whether NB_MCP_ENABLED asks for the endpoint. An unparseable value is logged and treated as off.

func FlowClientSecret

func FlowClientSecret(cfg *nbconfig.Config, provider idp.OAuthConfigProvider) string

FlowClientSecret returns the client secret of the configured PKCE flow, for identity providers whose client is confidential. The embedded IdP's client is public.

func RegisterEndpoints

func RegisterEndpoints(router, api *mux.Router, opts Options) error

RegisterEndpoints mounts the MCP endpoint on router and serves every selected tool by dispatching to api, the REST API router. router must sit behind the API authentication middleware: tool calls take the caller identity from the request context and refuse to run without one.

Types

type Accounts

type Accounts interface {
	GetAccountIDFromUserAuth(ctx context.Context, userAuth auth.UserAuth) (string, string, error)
	SyncUserJWTGroups(ctx context.Context, userAuth auth.UserAuth) error
	GetUserFromUserAuth(ctx context.Context, userAuth auth.UserAuth) (*types.User, error)
	GetUserByID(ctx context.Context, id string) (*types.User, error)
	StoreEvent(ctx context.Context, initiatorID, targetID, accountID string, activityID activity.ActivityDescriber, meta map[string]any)
}

Accounts resolves the NetBird user behind a login, re-checks it on every MCP call and records sign-ins in the activity log. The account manager satisfies it.

type Broker

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

Broker is the OAuth 2.1 authorization server for the MCP endpoint, in the shape remote MCP vendors use: management renders its own consent, sends the user to the identity provider only to log in, receives that login on its own callback, and issues its own tokens, bound to the MCP endpoint and re-checked against the user on every call.

func NewBroker

func NewBroker(cfg BrokerConfig) (*Broker, error)

NewBroker validates the configuration and builds the broker.

func (*Broker) AuthMiddleware

func (b *Broker) AuthMiddleware(apiAuth mux.MiddlewareFunc) mux.MiddlewareFunc

AuthMiddleware wraps the API auth middleware so the MCP endpoint also accepts the broker's access tokens. Every other credential, and a broker token presented anywhere but the MCP endpoint, goes to apiAuth, which rejects what it does not know.

func (*Broker) ChallengeMiddleware

func (b *Broker) ChallengeMiddleware() mux.MiddlewareFunc

ChallengeMiddleware adds the RFC 9728 pointer to the protected resource metadata when a call to the MCP endpoint is refused with 401. The API auth middleware writes that 401 itself, so this has to sit outside it on the root router. Other paths are untouched.

func (*Broker) Close

func (b *Broker) Close()

Close stops the callback rate limiter and closes the grant store's connection. It is safe to call more than once.

func (*Broker) RegisterEndpoints

func (b *Broker) RegisterEndpoints(root, api *mux.Router) error

RegisterEndpoints mounts the discovery documents and the authorization server. Everything here is reached before the client holds a token, so all of it bypasses the API auth.

type BrokerConfig

type BrokerConfig struct {
	// Flow is the PKCE flow of the identity provider users log in with.
	Flow *FlowConfig
	// ClientSecret is sent to the identity provider's token endpoint when its client is confidential.
	ClientSecret string
	// Secrets seal everything the broker issues; see ResolveSecrets.
	Secrets Secrets
	// Grants holds the sessions; see NewGrantStore.
	Grants   GrantStore
	Identity Identity
	Accounts Accounts
	// Limiter is optional.
	Limiter Limiter
	// TrustedProxies are the reverse proxies whose X-Forwarded-For the callback's rate limit
	// believes. Without them every request counts against the address it came from.
	TrustedProxies []netip.Prefix
	// BaseURL is the scheme and host clients reach management at, such as
	// https://netbird.example.com. Empty takes them from each request and its forwarding
	// headers. Set it when the deployment knows its URL: the issuer, the resource and the
	// callback registered at the identity provider then match it whatever the proxy sends.
	BaseURL string
}

BrokerConfig configures the MCP authorization server.

type FlowConfig

type FlowConfig struct {
	ClientID              string
	Audience              string
	AuthorizationEndpoint string
	TokenEndpoint         string
	Scope                 string
	// UseIDToken forwards the ID token instead of the access token for validation, for
	// identity providers whose access tokens are not JWTs.
	UseIDToken bool
}

FlowConfig is the identity provider's PKCE flow the broker logs users in with: the same client and endpoints agents use for an SSO login.

func FlowFromConfig

func FlowFromConfig(cfg *nbconfig.Config, provider idp.OAuthConfigProvider) *FlowConfig

FlowFromConfig picks the flow the way the gRPC handler does: the embedded IdP wins when it is enabled, otherwise the configured PKCE flow is used. It returns nil when neither is available.

type GrantStore

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

GrantStore keeps the grants and the single-use markers of codes and logins. Each method is one atomic step, so a revocation and a rotation of the same grant cannot interleave, and two instances cannot rotate one refresh token two ways.

func NewGrantStore

func NewGrantStore(ctx context.Context, redisURL string) (GrantStore, error)

NewGrantStore keeps the grants in Redis at redisURL, the address management's shared cache uses, or in this process when redisURL is empty, which suits a single instance only.

type Identity

type Identity interface {
	ValidateAndParseToken(ctx context.Context, value string) (auth.UserAuth, *jwt.Token, error)
	EnsureUserAccessByJWTGroups(ctx context.Context, userAuth auth.UserAuth, token *jwt.Token) (auth.UserAuth, error)
}

Identity validates the token the identity provider returns after login. The API's auth manager satisfies it.

type Limiter

type Limiter interface {
	Allow(key string) bool
}

Limiter rate limits MCP calls per user. The API rate limiter satisfies it.

type Options

type Options struct {
	// Tools restricts the exposed tools to these names. Empty exposes the whole catalog.
	Tools []string
	// Usage counts tool calls for the self-hosted metrics. Nil counts nothing.
	Usage *Usage
}

Options configure which tools the endpoint exposes.

func OptionsFromEnv

func OptionsFromEnv() Options

OptionsFromEnv reads the tool allowlist from NB_MCP_TOOLS.

type Route

type Route struct {
	Tool   string
	Method string
	// Path carries the tool's path arguments in braces, e.g. "/api/peers/{peer_id}".
	Path string
}

Route is the REST operation behind one tool.

func Routes

func Routes() []Route

Routes lists the REST operation behind every tool in the catalog, so a deployment can check the catalog against the routes its API router serves.

type Secrets

type Secrets struct {
	Tokens        []byte
	Registrations []byte
}

Secrets are the keys the broker seals with. Tokens seals codes, tokens and the browser state of a login; Registrations seals client ids. They differ so that changing NB_MCP_OAUTH_KEY signs every client out without unregistering it: a client id carries no authority, and a client that keeps its id can always sign in again.

func ResolveSecrets

func ResolveSecrets(dataStoreKey string) (Secrets, error)

ResolveSecrets picks the broker's keys. Tokens use NB_MCP_OAUTH_KEY when set, else the datastore encryption key; registrations use the datastore key when there is one. Without either a random key is generated, which only works for a single instance and invalidates every MCP login and registration on restart. A NB_MCP_OAUTH_KEY shorter than 32 bytes is an error rather than a reason to fall back: falling back would revive the tokens the operator meant to revoke by setting it.

type Usage

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

Usage counts MCP tool calls and the users making them over the last day, in hourly buckets, for the self-hosted metrics. It keeps user IDs only to count them and never reports them.

func NewUsage

func NewUsage() *Usage

NewUsage returns an empty usage counter.

func (*Usage) LastDay

func (u *Usage) LastDay(now time.Time) (calls, users int)

LastDay returns the tool calls and the distinct users that made them in the hour of now and the 23 hours before it.

Jump to

Keyboard shortcuts

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