Documentation
¶
Index ¶
- Constants
- Variables
- func ActiveKeys(secrets []Secret, now time.Time) [][]byte
- func ArgumentsToFilter(args map[string]any) models.Filter
- func CanonicalJSON(v any) ([]byte, error)
- func CanonicalizeJSON(raw []byte) ([]byte, error)
- func ClassifyRequestError(err error) string
- func DecodeSecret(secret string) ([]byte, error)
- func DeriveSubscriptionID(tenantID, url, name string, args json.RawMessage) string
- func EventEnvelope(event *models.Event) ([]byte, error)
- func FormatRefreshBefore(expiresAt *time.Time) *string
- func GrantTTL(req TTLRequest, now time.Time) *time.Time
- func HostPort(u *url.URL) string
- func MessageID(envelopeType string) string
- func NewChallenge() string
- func NormalizeCallbackURL(raw string) (*url.URL, string, error)
- func SetHeaders(h http.Header, msgID, subscriptionID string, ts time.Time, body []byte, ...) error
- func Sign(msgID string, ts time.Time, body []byte, keys [][]byte) string
- func ValidSubscriptionID(id string) bool
- func VerificationEnvelope(challenge string) []byte
- type Error
- type Kind
- type RedisVerificationStore
- func (s *RedisVerificationStore) CountAttempt(ctx context.Context, tenantID string, window int64) (int64, error)
- func (s *RedisVerificationStore) CountFailure(ctx context.Context, tenantID, hostport string, window int64) error
- func (s *RedisVerificationStore) FailureCount(ctx context.Context, tenantID, hostport string, window int64) (int64, error)
- func (s *RedisVerificationStore) MarkVerified(ctx context.Context, tenantID, url string, ttl time.Duration) error
- func (s *RedisVerificationStore) PurgeTenant(ctx context.Context, tenantID string) error
- func (s *RedisVerificationStore) Verified(ctx context.Context, tenantID, url string) (bool, error)
- type Secret
- type SubscribeParams
- type TTLKind
- type TTLRequest
- type UnsubscribeParams
- type VerificationStore
- type Verifier
- type VerifierConfig
- type VerifyRequest
Constants ¶
const ( // MaxEnvelopeBytes is the largest body the mcp destination sends; larger // events fail as payload_too_large without a request. MaxEnvelopeBytes = 256 << 10 // MaxSubscriptionIDBytes caps destination IDs of the mcp type. MaxSubscriptionIDBytes = 128 // EnvelopeVerification is the type of the verification control envelope. EnvelopeVerification = "verification" )
const ( // Fields named by invalid_params. FieldURL = "config.url" FieldSecret = "credentials.secret" // invalid_params reasons. ReasonInvalidSecret = "invalid_secret" ReasonInvalidURL = "invalid_url" ReasonHTTPSRequired = "https_required" ReasonAddressNotAllowed = "address_not_allowed" ReasonRequired = "required" ReasonInvalidType = "invalid_type" ReasonInvalid = "invalid" ReasonTooLarge = "too_large" // callback_endpoint_error reasons: the fixed lastError categories. ReasonConnectionRefused = "connection_refused" ReasonTimeout = "timeout" ReasonTLSError = "tls_error" ReasonChallengeFailed = "challenge_failed" // not_found kinds. NotFoundEvent = "event" NotFoundSubscription = "subscription" // resource_exhausted limits. LimitVerificationRate = "verification_rate" )
Reasons and other fixed data values. Data never carries resolved addresses or raw endpoint responses, only fixed values and names from the client's own request (a field path, the unsupported delivery mode).
const ( FieldParams = "params" FieldName = "name" FieldArguments = "arguments" FieldDelivery = "delivery" FieldDeliveryMode = "delivery.mode" FieldTTLMs = "ttlMs" )
invalid_params fields.
const ( SecretPrefix = "whsec_" MinSecretBytes = 24 MaxSecretBytes = 64 )
const ( HeaderContentType = "Content-Type" HeaderWebhookID = "webhook-id" HeaderWebhookTimestamp = "webhook-timestamp" HeaderWebhookSignature = "webhook-signature" HeaderSubscriptionID = "X-MCP-Subscription-Id" )
Delivery headers. MCP deliveries and verification challenges carry exactly these (plus the client's User-Agent), spelled as here: SetHeaders writes them without http.Header's canonicalization (Webhook-Id, X-Mcp-Subscription-Id), and HTTP/1.1 sends map keys as they are. Receivers match header names case-insensitively, so http.Header.Get works on a received request; on a header map SetHeaders filled, read these keys directly.
const ( DefaultVerificationTTL = 24 * time.Hour DefaultVerificationRateLimit = 10 // uncached attempts per tenant per minute DefaultVerificationFailureLimit = 120 // failed challenges per (tenant, host) per minute DefaultVerificationMaxInFlight = 64 // concurrent challenges per process DefaultVerificationTimeout = 10 * time.Second // MaxChallengeResponseBytes caps how much of a challenge response is read. MaxChallengeResponseBytes = 64 << 10 )
Verifier defaults.
const DefaultSubscriptionTTL = 24 * time.Hour
DefaultSubscriptionTTL is the lifetime granted when a request has no ttlMs.
const MaxCallbackURLBytes = 2048
MaxCallbackURLBytes caps callback URLs, before and after normalization.
const SubscriptionIDPrefix = "sub_"
Variables ¶
var ( // ErrInvalidEventData: the event data is not one JSON value. ErrInvalidEventData = errors.New("mcpevents: event data is not valid JSON") // ErrEnvelopeTooLarge: the envelope would exceed MaxEnvelopeBytes. ErrEnvelopeTooLarge = errors.New("mcpevents: envelope exceeds the size limit") )
var ErrNoSigningKey = errors.New("mcpevents: no valid signing secret")
ErrNoSigningKey is returned when no secret is valid at signing time.
Functions ¶
func ActiveKeys ¶
ActiveKeys returns the keys of secrets still valid at now, in order: a secret stops signing at its InvalidAt. Empty keys are skipped.
func ArgumentsToFilter ¶
ArgumentsToFilter maps subscription arguments to the destination filter. Each argument matches the event data field of the same name by equality, so the result is {"data": {name: value}}. Empty arguments mean no filter (nil).
args must already have passed the event's inputSchema, which only offers scalar values. The result shares nothing with args.
func CanonicalJSON ¶
CanonicalJSON serializes v as JSON with object keys sorted at every level, byte-identical to the MCP Events guide's canonicalJson (JSON.stringify per value):
- keys sort by UTF-16 code units, as JavaScript's Array.prototype.sort;
- strings escape only `"`, `\` and controls below U+0020 (U+2028/U+2029 and HTML characters stay raw); invalid UTF-8 becomes U+FFFD;
- numbers format as ECMAScript Number::toString (-0 is "0"); NaN and infinities are an error, since JSON input can't produce them.
Supported values: nil, bool, string, float64/float32, integers (converted to float64, as JavaScript would), json.Number, json.RawMessage, map[string]any and []any. Anything else round-trips through encoding/json first.
func CanonicalizeJSON ¶
CanonicalizeJSON parses raw strictly (duplicate keys rejected) and returns its canonical form.
func ClassifyRequestError ¶
ClassifyRequestError maps an HTTP client error to a lastError category: timeout, tls_error, or connection_refused for everything else (refused, reset, DNS, unreachable, and the address guard's rejections, whose details must not reach the client).
func DecodeSecret ¶
func DeriveSubscriptionID ¶
func DeriveSubscriptionID(tenantID, url, name string, args json.RawMessage) string
DeriveSubscriptionID returns "sub_" and the hex of the first 16 bytes of the SHA-256 of the canonical JSON {arguments, name, tenant, url}. The tenant is the subscriber, so two tenants never share an ID. args must already be canonical JSON (empty means {}) and url normalized.
func EventEnvelope ¶
EventEnvelope serializes the MCP event body {"eventId","name","timestamp","data","cursor":null}: eventId is the event ID, name the topic, timestamp the event time in RFC 3339 UTC (nanosecond precision when present), data the event data spliced in unchanged (bytes, key order and number spelling preserved; empty data is null). Every string is JSON-encoded, so an event ID or topic can't inject members. The result is what gets signed and sent.
func FormatRefreshBefore ¶
FormatRefreshBefore renders a grant as RFC 3339 UTC truncated to seconds, never later than the real expiry, or nil for no expiry.
func GrantTTL ¶
func GrantTTL(req TTLRequest, now time.Time) *time.Time
GrantTTL returns the expiry granted for a requested ttlMs, truncated to milliseconds, or nil for no expiry:
- absent: now + DefaultSubscriptionTTL;
- a number: exactly that many whole milliseconds from now; zero or less expires now;
- null: no expiry.
A number beyond the year 9999 is granted until then.
func HostPort ¶
HostPort returns u's host and port with the scheme default filled in, the form the per-host limiters key on ("example.com:443", "[::1]:8443").
func NewChallenge ¶
func NewChallenge() string
NewChallenge returns a fresh challenge: 24 random bytes, base64url.
func NormalizeCallbackURL ¶
NormalizeCallbackURL parses an absolute http or https callback URL and returns it in normalized form, both parsed and serialized (u.String() equals the string). The verification cache and the verification rate limits are keyed on the string, so every spelling of one endpoint must normalize the same way:
- scheme lowercased; only http and https (https-only is decided by the mcp destination, since allowlisted addresses may use http);
- host: one trailing dot removed, IDNA ToASCII (UTS #46 lookup profile: lowercase, NFC, STD3 rules); a host that ends in a numeric label must be a dotted-decimal IPv4 address; IP literals in netip's canonical form, IPv4-mapped IPv6 unmapped, IPv6 bracketed, zones rejected;
- port: decimal, 1..65535, leading zeros dropped, the scheme's default port removed;
- path: dot segments removed and characters outside the WHATWG path set percent-encoded (plus "|"), as WHATWG URL does; empty path is "/";
- query: kept, with the WHATWG special-query set percent-encoded;
- userinfo, fragments, backslashes, whitespace and control characters are rejected; so is anything over MaxCallbackURLBytes.
Failures are invalid_params {field: "config.url", reason: invalid_url | https_required}.
func SetHeaders ¶
func SetHeaders(h http.Header, msgID, subscriptionID string, ts time.Time, body []byte, keys [][]byte) error
SetHeaders sets the delivery headers on h for body: Content-Type, webhook-id, webhook-timestamp (ts, Unix seconds), webhook-signature (every key) and X-MCP-Subscription-Id, under the exact keys of the Header* constants, replacing any other spelling of them. It returns ErrNoSigningKey for no keys.
func Sign ¶
Sign returns the Standard Webhooks signature header value: one "v1,<base64 HMAC-SHA256(key, msgID.unix(ts).body)>" per key, space separated, in key order. It returns "" for no keys.
func ValidSubscriptionID ¶
ValidSubscriptionID reports whether id can be a subscription ID, which goes out as the X-MCP-Subscription-Id header: 1 to MaxSubscriptionIDBytes bytes of [A-Za-z0-9_-].
func VerificationEnvelope ¶
VerificationEnvelope serializes {"type":"verification","challenge":...}.
Types ¶
type Error ¶
Error is an MCP-level failure. Build it with the constructors below so Data keeps its fixed shape. Data also feeds validation errors and logs; only the keys in wireData reach MCP clients.
func CallbackEndpointError ¶
CallbackEndpointError reports a failed verification: data {reason}, one of the fixed lastError categories.
func InvalidParams ¶
InvalidParams reports a statically invalid request: data {field, reason}.
func ResourceExhausted ¶
ResourceExhausted reports a limit: data {limit, max?, retryAfterMs?}; max and retryAfter are omitted when not positive.
func Unsupported ¶
Unsupported reports a feature the server doesn't offer: data {feature, value}.
type RedisVerificationStore ¶
type RedisVerificationStore struct {
// contains filtered or unexported fields
}
RedisVerificationStore is the Redis VerificationStore. Every key is single-key (cluster safe) and carries the deployment prefix:
[<dep>:]mcp:verified:<sha256(tenant, url)> (TTL: cache TTL) [<dep>:]mcp:verified_index:<sha256(tenant)> (zset of verified keys by expiry) [<dep>:]mcp:challenge_rate:<sha256(tenant)>:<minute> (TTL: 2m) [<dep>:]mcp:challenge_fail:<sha256(tenant, host:port)>:<minute> (TTL: 2m)
Hashing (of length-prefixed parts) keeps attacker-chosen strings out of key names and bounds their length.
func NewRedisVerificationStore ¶
func NewRedisVerificationStore(client redis.Cmdable, deploymentID string) *RedisVerificationStore
NewRedisVerificationStore returns a store on client; deploymentID ("" for none) prefixes every key.
func (*RedisVerificationStore) CountAttempt ¶
func (*RedisVerificationStore) CountFailure ¶
func (*RedisVerificationStore) FailureCount ¶
func (*RedisVerificationStore) MarkVerified ¶
func (*RedisVerificationStore) PurgeTenant ¶
func (s *RedisVerificationStore) PurgeTenant(ctx context.Context, tenantID string) error
type Secret ¶
Secret is one signing key: the current secret (InvalidAt nil) or, during rotation, the previous one until InvalidAt.
type SubscribeParams ¶
type SubscribeParams struct {
Name string
// Arguments is the canonical JSON of the arguments object ({} when omitted).
Arguments json.RawMessage
// URL is the normalized callback URL.
URL string
Secret string
TTL TTLRequest
}
SubscribeParams is a parsed events/subscribe params object.
func ParseSubscribeParams ¶
func ParseSubscribeParams(raw json.RawMessage) (*SubscribeParams, error)
ParseSubscribeParams parses events/subscribe params. Unknown fields (cursor, maxAgeMs, _meta, ...) are ignored. Keys match exactly and duplicate keys are rejected, so the params read the same here as in the MCP server that forwards them. Failures are *Error invalid_params.
type TTLRequest ¶
type TTLRequest struct {
Kind TTLKind
// Ms is the suggested lifetime when Kind is TTLFinite; a value beyond
// float64 range arrives as ±math.MaxFloat64.
Ms float64
}
TTLRequest is the parsed ttlMs.
type UnsubscribeParams ¶
type UnsubscribeParams struct {
Name string
Arguments json.RawMessage
URL string
}
UnsubscribeParams is a parsed events/unsubscribe params object.
func ParseUnsubscribeParams ¶
func ParseUnsubscribeParams(raw json.RawMessage) (*UnsubscribeParams, error)
ParseUnsubscribeParams parses events/unsubscribe params: name, arguments and delivery.url, with the same rules as subscribe.
type VerificationStore ¶
type VerificationStore interface {
// Verified reports whether (tenant, url) passed a challenge
// within the cache TTL.
Verified(ctx context.Context, tenantID, url string) (bool, error)
// MarkVerified caches a passed challenge for ttl.
MarkVerified(ctx context.Context, tenantID, url string, ttl time.Duration) error
// PurgeTenant drops every cache entry of tenantID.
PurgeTenant(ctx context.Context, tenantID string) error
// CountAttempt counts one uncached verification attempt by tenantID
// in window and returns the window's total.
CountAttempt(ctx context.Context, tenantID string, window int64) (int64, error)
// FailureCount returns the failed challenges of tenantID to hostport in
// window.
FailureCount(ctx context.Context, tenantID, hostport string, window int64) (int64, error)
// CountFailure counts one failed challenge of tenantID to hostport in
// window.
CountFailure(ctx context.Context, tenantID, hostport string, window int64) error
}
VerificationStore holds verification state shared by every API replica: the per-(tenant, url) cache and the per-minute counters behind the verification limits. Windows are Unix minutes.
type Verifier ¶
type Verifier struct {
// contains filtered or unexported fields
}
Verifier runs MCP Events endpoint verification: a signed verification envelope whose challenge the endpoint must echo, cached per (tenant, url).
func NewVerifier ¶
func NewVerifier(cfg VerifierConfig) (*Verifier, error)
NewVerifier returns a Verifier; Client and Store are required.
func (*Verifier) PurgeTenant ¶
PurgeTenant drops everything the verifier cached for tenantID.
func (*Verifier) Verified ¶
Verified reports whether (tenant, url) is in the verification cache, without sending anything.
func (*Verifier) Verify ¶
func (v *Verifier) Verify(ctx context.Context, req VerifyRequest) error
Verify returns nil when (tenant, url) passed a challenge within the TTL or passes one now. Limits are checked before anything is sent. Errors are *Error (invalid_params, resource_exhausted, callback_endpoint_error) except store failures, a done ctx and a malformed SubscriptionID, which are plain errors.
type VerifierConfig ¶
type VerifierConfig struct {
// Client sends challenges. It must be the SSRF-guarded client deliveries
// use (address checks at dial time, no redirects, no environment proxy).
Client *http.Client
Store VerificationStore
// TTL is how long a passed challenge is cached.
TTL time.Duration
// RateLimit caps uncached attempts per tenant per minute.
RateLimit int
// FailureLimit caps failed challenges per (tenant, host:port) per minute,
// so a tenant can't use Outpost to probe a host.
FailureLimit int
// Exempt reports hosts (the URL's hostname, IP literals unbracketed)
// that skip the failure limit, such as allowlisted ones.
Exempt func(host string) bool
// MaxInFlight caps concurrent challenges in this process.
MaxInFlight int
// Timeout bounds one challenge, response included.
Timeout time.Duration
Logger *logging.Logger
// Now is the clock (tests).
Now func() time.Time
}
VerifierConfig configures a Verifier. Zero values take the defaults above; a negative RateLimit or FailureLimit disables that limit (other settings can't be disabled: non-positive means the default).
type VerifyRequest ¶
type VerifyRequest struct {
TenantID string
// URL is the callback URL; it is normalized again here, so cache and
// rate-limit keys never depend on the caller's spelling.
URL string
// SubscriptionID goes out as X-MCP-Subscription-Id.
SubscriptionID string
// Secrets sign the challenge, like a delivery.
Secrets []Secret
}
VerifyRequest identifies the (tenant, url) to verify.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
mcptest
|
|
|
mcpcatalog
Package mcpcatalog reads, samples and compares event catalogs: the events/list result of an MCP Events server or a file holding one.
|
Package mcpcatalog reads, samples and compares event catalogs: the events/list result of an MCP Events server or a file holding one. |
|
mcpcheck
Package mcpcheck runs a conformance flow against an MCP Events server that offers webhook delivery and reports one result per rule.
|
Package mcpcheck runs a conformance flow against an MCP Events server that offers webhook delivery and reports one result per rule. |
|
mcpreceiver
Package mcpreceiver is a reference receiver for MCP Events webhook deliveries.
|
Package mcpreceiver is a reference receiver for MCP Events webhook deliveries. |
|
mcpserver
Package mcpserver is a reference MCP Events server in front of Outpost's /mcp/* REST routes.
|
Package mcpserver is a reference MCP Events server in front of Outpost's /mcp/* REST routes. |