mock

package
v5.43.5 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0 Imports: 37 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.

Documentation

Overview

Package mock provides mock MCP server functionality for testing muster components.

This package contains the implementation of mock MCP servers that can be used in test scenarios to simulate external MCP servers with predefined behaviors.

The mock MCP server functionality allows test scenarios to define: - Mock tools with configurable responses - Conditional responses based on input args - Simulated delays and error conditions - Template-based response generation - OAuth 2.1 authentication flows for testing protected servers

Key Components

Server: The main mock MCP server that implements the MCP protocol. It can be configured with a set of tools and their expected behaviors. By default, it uses stdio transport for subprocess communication.

HTTPServer: Wraps a mock MCP server with HTTP transport capabilities. Supports both SSE (Server-Sent Events) and Streamable HTTP transports. Use this for testing URL-based MCP server configurations.

OAuthServer: A mock OAuth 2.1 authorization server for testing OAuth flows. Supports authorization code flow with PKCE, token exchange, refresh tokens, and configurable error simulation. Use this for testing OAuth-protected MCP servers without requiring a real identity provider.

ProtectedMCPServer: An MCP server that requires OAuth authentication. It validates bearer tokens against a mock OAuth server and returns 401 with WWW-Authenticate headers when authentication is required. Tools are only accessible after successful authentication.

ToolHandler: Handles individual tool calls with configurable responses based on input args and conditions.

ToolConfig & ToolResponse: Configuration structures that define how mock tools should behave, including input schemas, response conditions, and template-based response generation.

Supported Transports

The mock package supports three transport types:

  • stdio: Standard input/output for subprocess communication (default)
  • streamable-http: HTTP-based streaming protocol
  • sse: Server-Sent Events protocol

Usage

Mock MCP servers can be used in three ways:

  1. Embedded stdio mock in test scenarios: The test framework automatically starts stdio mock MCP servers based on scenario pre-configuration that includes MCP servers with "tools" in config:

    pre_configuration: mcp_servers: - name: "my-mock" config: tools: - name: "my_tool" ...

  2. Embedded HTTP mock in test scenarios: For URL-based transports, add a "type" field to the config:

    pre_configuration: mcp_servers: - name: "my-http-mock" config: type: "streamable-http" # or "sse" tools: - name: "my_tool" ...

  3. Standalone mock server mode: Use `muster test --mock-mcp-server --mock-config=path/to/config.yaml` to run a standalone mock MCP server for manual testing or external integration.

Configuration Format

Mock MCP servers are configured using YAML files that define the tools and their expected behaviors:

tools:
  - name: example-tool
    description: "An example mock tool"
    input_schema:
      type: object
      properties:
        param1:
          type: string
          default: "default-value"
    responses:
      - condition:
          param1: "special"
        response: "Special response for param1=special"
      - response: "Default response: {{.param1}}"

The responses support Go template syntax and can reference input args. Conditional responses allow different behaviors based on input values.

OAuth Testing

For testing OAuth-protected MCP servers, the package provides a complete mock OAuth 2.1 infrastructure. Configure OAuth in test scenarios as follows:

pre_configuration:
  mock_oauth_servers:
    - name: "test-idp"
      scopes: ["openid", "profile", "mcp:read"]
      auto_approve: true
      pkce_required: true
      token_lifetime: "1h"

  mcp_servers:
    - name: "protected-api"
      config:
        type: "streamable-http"
        oauth:
          required: true
          mock_oauth_server_ref: "test-idp"
          scope: "mcp:read"
        tools:
          - name: "secure_tool"
            description: "A tool requiring authentication"
            responses:
              - response: { "status": "authenticated" }

The mock OAuth server automatically: - Serves OAuth 2.1 metadata at /.well-known/oauth-authorization-server - Handles authorization code flow with PKCE support - Issues and validates access tokens - Returns WWW-Authenticate headers for unauthorized requests

A mock OAuth server can take the profile of a real authorization server (`profile: github | dex | pro`, see Profile): one bundle of that server's quirks -- no discovery document, `scope` or `expires_in` left out of token responses, registration without RFC 7592 management, registrations forgotten on Restart, resources that answer a bare 401 -- instead of one flag per quirk. Individual flags override the bundle.

Integration

This package is designed to work seamlessly with the muster testing framework and supports the same MCP protocol implementation used by real MCP servers. The HTTPServer automatically allocates ports and provides endpoint URLs for muster to connect to during test scenario execution. OAuth servers are automatically started and stopped as part of the test scenario lifecycle.

Index

Constants

View Source
const RefreshedTokenPrefix = "refreshed-"

RefreshedTokenPrefix marks access tokens the mock issued on a refresh_token grant, so scenarios can assert that a client redeemed its refresh token.

Variables

Profiles lists every profile the mock knows.

Functions

func ExtractBearerToken

func ExtractBearerToken(authHeader string) string

ExtractBearerToken extracts a bearer token from an Authorization header

Types

type Advancer

type Advancer interface {
	Advance(d time.Duration)
}

Advancer is a clock that can be moved forward: MockClock and OffsetClock.

type Clock

type Clock interface {
	// Now returns the current time according to this clock
	Now() time.Time
}

Clock provides an interface for time operations to enable testing without relying on real time. This allows tests to simulate token expiry without waiting for actual time to pass.

type HTTPServer

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

HTTPServer wraps a mock MCP server with HTTP transport capabilities. It can serve either SSE or streamable-http transport types.

func NewHTTPServer

func NewHTTPServer(mockServer *Server, transport HTTPTransportType, debug bool) *HTTPServer

NewHTTPServer creates a new HTTP mock server from an existing mock server

func NewHTTPServerFromConfig

func NewHTTPServerFromConfig(configPath string, transport HTTPTransportType, debug bool) (*HTTPServer, error)

NewHTTPServerFromConfig creates a new HTTP mock server from a config file

func (*HTTPServer) AddDynamicTool

func (s *HTTPServer) AddDynamicTool(toolConfig ToolConfig)

AddDynamicTool adds a tool to the running mock server at runtime. This triggers a notifications/tools/list_changed notification to connected clients.

func (*HTTPServer) Endpoint

func (s *HTTPServer) Endpoint() string

Endpoint returns the full endpoint URL for the server

func (*HTTPServer) GetError

func (s *HTTPServer) GetError() error

GetError returns any error that occurred during server operation

func (*HTTPServer) IsRunning

func (s *HTTPServer) IsRunning() bool

IsRunning returns whether the server is currently running

func (*HTTPServer) OutageRemaining

func (s *HTTPServer) OutageRemaining() int

OutageRemaining reports how many requests the current outage still covers.

func (*HTTPServer) Port

func (s *HTTPServer) Port() int

Port returns the port the server is listening on

func (*HTTPServer) Redeploy

func (s *HTTPServer) Redeploy(change ToolSetChange) error

Redeploy replaces the MCP handler behind the listening port with a fresh one, built from the server's tools with change applied: every MCP session the old handler knew is forgotten, and the port never stopped accepting -- a backend pod replaced behind the same Service, by the same image or by one that offers other tools. A client that keeps using its session id is answered 404 ("Invalid session ID") by the new handler, as mcp-go's streamable-HTTP server answers for a session it does not know. A changed tool set announces itself to nobody: the new process has never seen a client's session, so no notifications/tools/list_changed goes out.

func (*HTTPServer) RemoveDynamicTool

func (s *HTTPServer) RemoveDynamicTool(toolName string)

RemoveDynamicTool removes a tool from the running mock server at runtime. This triggers a notifications/tools/list_changed notification to connected clients.

func (*HTTPServer) SetOutage

func (s *HTTPServer) SetOutage(status, requests, retryAfter int, pings bool)

SetOutage makes the server answer its next requests requests with the given HTTP status and serve normally afterwards; requests of 0 ends an outage early. A retryAfter greater than 0 adds a Retry-After header of that many seconds. The server keeps listening, so muster sees an HTTP response, not a refused connection. With pings the orchestrator's health probes are answered with the status too; without, they pass through uncounted.

func (*HTTPServer) Start

func (s *HTTPServer) Start(ctx context.Context) (int, error)

Start starts the HTTP server on a dynamically allocated port. Returns the port number the server is listening on.

func (*HTTPServer) StartOnPort

func (s *HTTPServer) StartOnPort(ctx context.Context, port int) error

StartOnPort starts the HTTP server on a specific port. This is useful when you need to control the port (e.g., for deterministic testing).

func (*HTTPServer) Stop

func (s *HTTPServer) Stop(ctx context.Context) error

Stop gracefully shuts down the HTTP server

func (*HTTPServer) Transport

func (s *HTTPServer) Transport() HTTPTransportType

Transport returns the transport type used by the server

func (*HTTPServer) WaitForReady

func (s *HTTPServer) WaitForReady(ctx context.Context) error

WaitForReady waits for the server to be ready to accept connections

type HTTPTransportType

type HTTPTransportType string

HTTPTransportType represents the type of HTTP transport for mock servers

const (
	// HTTPTransportStreamableHTTP uses streamable HTTP protocol
	HTTPTransportStreamableHTTP HTTPTransportType = "streamable-http"
	// HTTPTransportSSE uses Server-Sent Events protocol
	HTTPTransportSSE HTTPTransportType = "sse"
)

type MCPServerConfig

type MCPServerConfig struct {
	Name   string                 `yaml:"name"`
	Config map[string]interface{} `yaml:"config"`
}

MCPServerConfig is a minimal copy needed for the mock server

type MockClock

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

MockClock implements Clock with a controllable time value. This enables testing time-sensitive operations like token expiry without waiting for real time to pass.

func NewMockClock

func NewMockClock(t time.Time) *MockClock

NewMockClock creates a new mock clock initialized to the given time. If t is zero, the clock is initialized to the current time.

func (*MockClock) Add

func (m *MockClock) Add(d time.Duration)

Add is an alias for Advance for API familiarity.

func (*MockClock) Advance

func (m *MockClock) Advance(d time.Duration)

Advance moves the clock forward by the given duration.

func (*MockClock) Now

func (m *MockClock) Now() time.Time

Now returns the current time according to this mock clock.

func (*MockClock) Set

func (m *MockClock) Set(t time.Time)

Set sets the clock to a specific time.

type OAuthErrorSimulation

type OAuthErrorSimulation struct {
	// TokenEndpointError returns this error from /token
	TokenEndpointError string

	// AuthorizeEndpointDelay adds delay to /authorize
	AuthorizeEndpointDelay time.Duration

	// InvalidGrant rejects all token exchanges
	InvalidGrant bool

	// InvalidToken rejects all token validations
	InvalidToken bool
}

OAuthErrorSimulation allows simulating error conditions

type OAuthServer

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

OAuthServer is a mock OAuth 2.1 authorization server

func NewOAuthServer

func NewOAuthServer(config OAuthServerConfig) *OAuthServer

NewOAuthServer creates a new mock OAuth server

func (*OAuthServer) AddToken

func (s *OAuthServer) AddToken(accessToken, refreshToken, scope, clientID string, expiresAt time.Time)

AddToken directly adds a token to the server (for testing)

func (*OAuthServer) ForgetRegisteredClients

func (s *OAuthServer) ForgetRegisteredClients() int

ForgetRegisteredClients drops every DCR registration, the way an authorization server with an in-memory client store forgets its clients when it restarts. RegistrationCount is unaffected, so scenarios can assert that muster registered again afterwards. Returns how many were forgotten.

func (*OAuthServer) GenerateAuthCode

func (s *OAuthServer) GenerateAuthCode(clientID, redirectURI, scope, state, codeChallenge, codeChallengeMethod, nonce string) string

GenerateAuthCode generates an authorization code for testing This simulates a user completing the OAuth flow

func (*OAuthServer) GenerateAuthCodeWithSubject

func (s *OAuthServer) GenerateAuthCodeWithSubject(clientID, redirectURI, scope, state, codeChallenge, codeChallengeMethod, subject, nonce string) string

GenerateAuthCodeWithSubject generates an authorization code with a custom subject claim. If subject is empty, the default "test-user-123" is used. The nonce, when non-empty, is echoed back in the issued id_token to satisfy OIDC nonce-echo verification.

func (*OAuthServer) GenerateTestToken

func (s *OAuthServer) GenerateTestToken(clientID, scope string) *TokenResponse

GenerateTestToken generates a test access token directly without going through the OAuth flow. This is useful for testing scenarios where the test framework needs to authenticate with muster's OAuth server without implementing the full browser-based OAuth flow.

func (*OAuthServer) GetAuthorizeURL

func (s *OAuthServer) GetAuthorizeURL() string

GetAuthorizeURL returns the authorization endpoint URL

func (*OAuthServer) GetCACertPEM

func (s *OAuthServer) GetCACertPEM() []byte

GetCACertPEM returns the PEM-encoded CA certificate for TLS mode. This can be used by clients to trust the self-signed certificate. Returns nil if the server is not running in TLS mode.

func (*OAuthServer) GetClientID

func (s *OAuthServer) GetClientID() string

GetClientID returns the configured client ID

func (*OAuthServer) GetClock

func (s *OAuthServer) GetClock() Clock

GetClock returns the clock used by this server

func (*OAuthServer) GetIssuerURL

func (s *OAuthServer) GetIssuerURL() string

GetIssuerURL returns the full issuer URL

func (*OAuthServer) GetMetadataURL

func (s *OAuthServer) GetMetadataURL() string

GetMetadataURL returns the OAuth metadata URL

func (*OAuthServer) GetPendingAuthCode

func (s *OAuthServer) GetPendingAuthCode(state string) string

GetPendingAuthCode returns a pending auth code if one exists for the given state

func (*OAuthServer) GetScopes

func (s *OAuthServer) GetScopes() []string

GetScopes returns the accepted scopes for this OAuth server

func (*OAuthServer) GetTokenInfo

func (s *OAuthServer) GetTokenInfo(accessToken string) *issuedToken

GetTokenInfo returns information about a token

func (*OAuthServer) GetTokenURL

func (s *OAuthServer) GetTokenURL() string

GetTokenURL returns the token endpoint URL

func (*OAuthServer) IsRunning

func (s *OAuthServer) IsRunning() bool

IsRunning returns whether the server is currently running

func (*OAuthServer) IsTLS

func (s *OAuthServer) IsTLS() bool

IsTLS returns whether the server is running in TLS mode.

func (*OAuthServer) MintSignedJWT

func (s *OAuthServer) MintSignedJWT(claims map[string]any, typHeader string) (string, error)

MintSignedJWT signs claims into a compact ES256 JWT using the server's signing key. typHeader sets the JWT `typ` header; an empty string omits it (matching Dex ID tokens, which carry no typ). Returns an error when the server was not created with SignTokens enabled.

Missing iss/iat/exp are filled from the server's issuer and token lifetime so callers only need to provide the identity-bearing claims (sub, aud, groups, act).

func (*OAuthServer) Port

func (s *OAuthServer) Port() int

Port returns the port the server is listening on

func (*OAuthServer) RegisteredClientCount

func (s *OAuthServer) RegisteredClientCount() int

RegisteredClientCount returns the number of DCR-registered clients the server currently knows.

func (*OAuthServer) RegistrationCount

func (s *OAuthServer) RegistrationCount() int

RegistrationCount returns the number of RFC 7591 registrations served.

func (*OAuthServer) Restart

func (s *OAuthServer) Restart(ctx context.Context) (int, error)

Restart replaces the server behind the port and issuer -- the authorization server's pod replaced behind its Service. Whatever the real server keeps outside its process stays (issued tokens, pending codes, the configured client); with ForgetRegistrationsOnRestart the RFC 7591 registrations go with the old process. The listening socket is kept bound throughout: released, the port would be free for any other socket on the host to take before the new server listens (see retainedListener). Returns how many registrations were forgotten.

func (*OAuthServer) RevokeAllTokens

func (s *OAuthServer) RevokeAllTokens() int

RevokeAllTokens removes all tokens from the server. This is used for testing scenarios where all tokens need to be invalidated. Returns the number of tokens that were revoked.

func (*OAuthServer) RevokeToken

func (s *OAuthServer) RevokeToken(accessToken string) bool

RevokeToken removes a token from the server, making it invalid for future requests. This is used for testing scenarios where a token is revoked server-side but the client still has the token cached locally. Returns true if the token was found and revoked, false if the token didn't exist.

func (*OAuthServer) SetClock

func (s *OAuthServer) SetClock(clock Clock)

SetClock sets the clock used by this server (primarily for testing)

func (*OAuthServer) SetTokenEndpointOutage added in v5.34.9

func (s *OAuthServer) SetTokenEndpointOutage(down bool)

SetTokenEndpointOutage makes the token endpoint answer every request with 503 and an HTML page while down is set -- a gateway in front of an authorization server that does not answer -- and serve normally once it is cleared.

func (*OAuthServer) SetTrustedIssuers

func (s *OAuthServer) SetTrustedIssuers(trustedIssuers map[string]string)

SetTrustedIssuers sets the trusted issuers for RFC 8693 token exchange. This should be called after all OAuth servers are started, so their issuer URLs are known.

func (*OAuthServer) SimulateCallback

func (s *OAuthServer) SimulateCallback(code string) (*TokenResponse, error)

SimulateCallback simulates a user completing OAuth flow This is called by tests to complete authentication without a real browser

func (*OAuthServer) Start

func (s *OAuthServer) Start(ctx context.Context) (int, error)

Start starts the OAuth server on a random available port

func (*OAuthServer) Stop

func (s *OAuthServer) Stop(ctx context.Context) error

Stop stops the OAuth server

func (*OAuthServer) ValidateToken

func (s *OAuthServer) ValidateToken(accessToken string) bool

ValidateToken checks if a token is valid

func (*OAuthServer) WWWAuthenticateHeader

func (s *OAuthServer) WWWAuthenticateHeader() string

WWWAuthenticateHeader returns the WWW-Authenticate header value for this server

func (*OAuthServer) WaitForReady

func (s *OAuthServer) WaitForReady(ctx context.Context) error

WaitForReady waits for the OAuth server to be ready

type OAuthServerConfig

type OAuthServerConfig struct {
	// Issuer is the OAuth issuer identifier (e.g., "http://localhost:9999")
	Issuer string

	// AcceptedScopes lists scopes the server will accept
	AcceptedScopes []string

	// TokenLifetime is how long tokens remain valid
	TokenLifetime time.Duration

	// SimulateErrors can be set to simulate various error conditions
	SimulateErrors *OAuthErrorSimulation

	// Debug enables debug logging
	Debug bool

	// PKCERequired enforces PKCE flow
	PKCERequired bool

	// AutoApprove skips user consent in tests
	AutoApprove bool

	// ClientID is the expected OAuth client ID
	ClientID string

	// ClientSecret is the expected OAuth client secret (optional)
	ClientSecret string

	// Clock is the clock to use for time operations (defaults to RealClock)
	// Set this to a MockClock for testing token expiry without waiting
	Clock Clock

	// UseTLS enables HTTPS mode with a self-signed certificate.
	// This is required for testing muster's OAuth server integration,
	// as the Dex provider enforces HTTPS for security.
	UseTLS bool

	// TrustedIssuers maps connector IDs to trusted issuer URLs for RFC 8693 token exchange.
	// When a token exchange request is received with a connector_id, this map is used
	// to look up the trusted issuer and validate the subject token.
	// Key: connector_id, Value: issuer URL
	TrustedIssuers map[string]string

	// SignTokens makes the server generate an EC P-256 signing key and serve a real
	// JWKS, enabling MintSignedJWT to issue ES256-signed tokens that a downstream
	// (e.g. muster's broker) can verify against this server's JWKS. Default false
	// keeps the legacy alg:none ID tokens and empty JWKS used by most scenarios.
	SignTokens bool

	// SupportsCIMD advertises client_id_metadata_document_supported in the
	// AS metadata, signalling that CIMD URLs are accepted as client_id.
	SupportsCIMD bool

	// SupportsDCR advertises a registration_endpoint in the AS metadata and
	// serves RFC 7591 Dynamic Client Registration at /register.
	SupportsDCR bool

	// RequireRegisteredClient makes the token endpoint reject authorization
	// codes issued to client_ids that are neither the configured ClientID
	// nor a DCR-registered client — mimicking DCR-only authorization servers
	// that treat unknown client_ids (e.g. CIMD URLs) as unregistered.
	RequireRegisteredClient bool

	// RejectRegistrationScope makes the registration endpoint reject RFC 7591
	// requests that carry a scope member with invalid_client_metadata —
	// mimicking authorization servers (e.g. Miro's) that reject scopes they
	// don't know instead of ignoring them.
	RejectRegistrationScope bool

	// AuthorizeAcceptsAnyClient makes the authorization endpoint skip its
	// client_id check, so only the token endpoint enforces registration —
	// mimicking authorization servers whose authorize responses reveal
	// nothing about an unknown client. Muster's pre-challenge registration
	// probe then sees a healthy AS and the token endpoint's invalid_client
	// is the only signal that the registration is gone.
	AuthorizeAcceptsAnyClient bool

	// AdvertiseIssParameter advertises
	// authorization_response_iss_parameter_supported in the AS metadata, so a
	// client must refuse an authorization response that carries no RFC 9207
	// `iss` parameter.
	AdvertiseIssParameter bool

	// OmitTokenScope leaves `scope` out of token responses, as Dex does: RFC
	// 6749 §5.1 allows that when the granted scope equals the requested one,
	// and the client has to remember what it asked for.
	OmitTokenScope bool

	// OmitDiscovery serves no RFC 8414 / OIDC discovery document (404 on both
	// well-known paths), as GitHub does: a client has to know the endpoints.
	OmitDiscovery bool

	// OmitTokenExpiry leaves `expires_in` out of token responses, as GitHub
	// does: the access token has no expiry the client could learn.
	OmitTokenExpiry bool

	// OmitRegistrationClientURI leaves registration_client_uri and
	// registration_access_token out of RFC 7591 registration responses, as
	// the MCP TypeScript SDK's authorization server does: the client cannot
	// read its registration back through RFC 7592 and has to probe the
	// authorization endpoint instead.
	OmitRegistrationClientURI bool

	// ForgetRegistrationsOnRestart makes Restart drop every RFC 7591
	// registration, the way an authorization server whose client store lives
	// in memory (pro) loses its clients with the process.
	ForgetRegistrationsOnRestart bool
}

OAuthServerConfig configures the mock OAuth server behavior

type OffsetClock

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

OffsetClock is the system time plus an offset that Advance grows: the clock of a mock authorization server that follows wall time and is moved forward together with muster's own clock by test_advance_clock. Unlike MockClock it does not stand still between advances.

func NewOffsetClock

func NewOffsetClock() *OffsetClock

NewOffsetClock returns a clock at the system time with no offset.

func (*OffsetClock) Advance

func (c *OffsetClock) Advance(d time.Duration)

Advance moves the clock forward by d.

func (*OffsetClock) Now

func (c *OffsetClock) Now() time.Time

Now returns the system time plus the offset.

type PreConfiguration

type PreConfiguration struct {
	MCPServers []MCPServerConfig `yaml:"mcp_servers,omitempty"`
}

PreConfiguration is a minimal copy needed for the mock server

type Profile

type Profile string

Profile names a real authorization server whose behaviour the mock reproduces as one bundle instead of one flag per quirk. A scenario written against a named server selects its profile; a flag set beside the profile overrides the bundle for that flag alone.

const (
	// ProfileGitHub is GitHub's OAuth: no RFC 8414 / OIDC discovery document,
	// no Client ID Metadata Documents and no RFC 7591 registration -- only a
	// client registered out of band; `scope` omitted from the token response;
	// access tokens without an expiry (`expires_in` absent). The resources it
	// protects answer a bare 401 without RFC 9728 metadata and its grants are
	// the person's (grantScope subject), so muster is pinned to it with
	// explicit endpoints.
	ProfileGitHub Profile = "github"

	// ProfileDex is Dex: a discovery document, `scope` omitted from the token
	// response (RFC 6749 §5.1 allows that when the granted scope is the
	// requested one), an id_token with every token, RFC 7591 registration.
	ProfileDex Profile = "dex"

	// ProfilePro is an authorization server built on the MCP TypeScript SDK
	// (pro): a discovery document; RFC 7591 registration whose response
	// carries no registration_client_uri, so there is no RFC 7592 read to
	// check a registration with; a client it does not know answered directly
	// at /authorize with invalid_client instead of a redirect; registrations
	// held in memory and gone when the server restarts.
	ProfilePro Profile = "pro"
)

func ParseProfile

func ParseProfile(name string) (Profile, error)

ParseProfile returns the profile of that name. The empty name is the well-behaved default and is returned as "" without an error.

func (Profile) Apply

func (p Profile) Apply(cfg *OAuthServerConfig)

Apply switches the bundle's authorization-server flags on in cfg; flags the bundle leaves alone keep their value. A flag the bundle switches on cannot be switched off here -- a caller that needs a variation resolves the Bundle against its explicit values instead, as the scenario harness does.

func (Profile) Bundle

func (p Profile) Bundle() ProfileBundle

Bundle returns what the profile switches on; the empty profile switches on nothing.

type ProfileBundle

type ProfileBundle struct {
	// OmitDiscovery serves no RFC 8414 / OIDC discovery document.
	OmitDiscovery bool
	// SupportsDCR advertises and serves RFC 7591 registration.
	SupportsDCR bool
	// RequireRegisteredClient makes the token endpoint refuse client_ids it
	// neither registered nor was configured with.
	RequireRegisteredClient bool
	// OmitTokenScope leaves `scope` out of token responses.
	OmitTokenScope bool
	// OmitTokenExpiry leaves `expires_in` out of token responses.
	OmitTokenExpiry bool
	// OmitRegistrationClientURI leaves registration_client_uri and
	// registration_access_token out of registration responses.
	OmitRegistrationClientURI bool
	// ForgetRegistrationsOnRestart drops every registration on Restart.
	ForgetRegistrationsOnRestart bool

	// ResourceOmitsMetadata: the protected resources answer a bare 401 and
	// serve no /.well-known/oauth-protected-resource document.
	ResourceOmitsMetadata bool
	// GrantScopeSubject: grants are filed under the person (grantScope
	// subject), not the login session.
	GrantScopeSubject bool
	// PinWithEndpoints: muster is pinned to the issuer with explicit
	// authorization and token endpoints, since nothing can be discovered.
	PinWithEndpoints bool
}

ProfileBundle is what a profile switches on. The first group are flags of the mock authorization server (OAuthServerConfig); the second are the defaults for the protected resources that verify tokens from it and for the MCPServer definition that points muster at it. Whatever a bundle leaves false keeps the mock's default: a well-behaved authorization server with a discovery document, `scope` and `expires_in` in every token response, RFC 7592 management for its registrations, and resources that publish RFC 9728 metadata.

type PromptConfig

type PromptConfig struct {
	// Name is the prompt name as the backend server exposes it
	Name string `yaml:"name"`
	// Description describes what the prompt does
	Description string `yaml:"description"`
	// Text is the message body returned when the prompt is fetched
	Text string `yaml:"text"`
}

PromptConfig defines a static MCP prompt served by the mock server.

Prompts exist in the mock so scenarios can exercise the aggregator's prompt paths -- notably that an exposed prompt name carries the server's configured tool prefix rather than its name, so attribution cannot be derived from the name alone.

type ProtectedMCPServer

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

ProtectedMCPServer is a mock MCP server that requires OAuth authentication

func NewProtectedMCPServer

func NewProtectedMCPServer(config ProtectedMCPServerConfig) (*ProtectedMCPServer, error)

NewProtectedMCPServer creates a new OAuth-protected mock MCP server

func (*ProtectedMCPServer) AddDynamicTool

func (s *ProtectedMCPServer) AddDynamicTool(toolConfig ToolConfig)

AddDynamicTool adds a tool to the running protected MCP server at runtime. This triggers a notifications/tools/list_changed notification to connected clients.

func (*ProtectedMCPServer) AuthRequired

func (s *ProtectedMCPServer) AuthRequired() bool

AuthRequired reports whether requests currently need a bearer token.

func (*ProtectedMCPServer) Endpoint

func (s *ProtectedMCPServer) Endpoint() string

Endpoint returns the MCP endpoint URL

func (*ProtectedMCPServer) GetIssuer

func (s *ProtectedMCPServer) GetIssuer() string

GetIssuer returns the OAuth issuer for this server

func (*ProtectedMCPServer) GetName

func (s *ProtectedMCPServer) GetName() string

GetName returns the server name

func (*ProtectedMCPServer) IsRunning

func (s *ProtectedMCPServer) IsRunning() bool

IsRunning returns whether the server is currently running

func (*ProtectedMCPServer) OutageRemaining

func (s *ProtectedMCPServer) OutageRemaining() int

OutageRemaining reports how many requests the current outage still covers.

func (*ProtectedMCPServer) Port

func (s *ProtectedMCPServer) Port() int

Port returns the port the server is listening on

func (*ProtectedMCPServer) Redeploy

func (s *ProtectedMCPServer) Redeploy(change ToolSetChange) error

Redeploy replaces the handler behind the listening port with a fresh one built from the server's tools (configured and added at runtime) with change applied: every MCP session is forgotten while the port keeps accepting, and a changed tool set is announced to nobody, see HTTPServer.Redeploy.

func (*ProtectedMCPServer) Rejections added in v5.31.4

func (s *ProtectedMCPServer) Rejections() (rejected, expired int64)

Rejections returns how many requests the server answered with 401, and how many of them presented a bearer past its exp (JWKS validation only: a token of the mock authorization server is opaque to the backend).

func (*ProtectedMCPServer) RemoveDynamicTool

func (s *ProtectedMCPServer) RemoveDynamicTool(toolName string)

RemoveDynamicTool removes a tool from the running protected MCP server at runtime. This triggers a notifications/tools/list_changed notification to connected clients.

func (*ProtectedMCPServer) SetAuthRequired

func (s *ProtectedMCPServer) SetAuthRequired(required bool)

SetAuthRequired switches the server between answering anonymously and requiring a bearer token (401 with the RFC 9728 challenge). The change applies to the next request; sessions already established stay.

func (*ProtectedMCPServer) SetOutage

func (s *ProtectedMCPServer) SetOutage(status, requests, retryAfter int, pings bool)

SetOutage makes the server answer its next requests requests with the given HTTP status -- before the OAuth middleware, so no 401 challenge is sent -- and serve normally afterwards; requests of 0 ends an outage early. A retryAfter greater than 0 adds a Retry-After header of that many seconds. With pings the orchestrator's health probes are answered with the status too.

func (*ProtectedMCPServer) Start

func (s *ProtectedMCPServer) Start(ctx context.Context) (int, error)

Start starts the protected MCP server on a random available port

func (*ProtectedMCPServer) StartOnPort

func (s *ProtectedMCPServer) StartOnPort(ctx context.Context, port int) error

StartOnPort starts the protected MCP server on a specific port. It lets a scenario bring a server back on the port muster already knows it by after a Stop, so the MCPServer definition keeps pointing at a live endpoint.

func (*ProtectedMCPServer) Stop

func (s *ProtectedMCPServer) Stop(ctx context.Context) error

Stop stops the protected MCP server

func (*ProtectedMCPServer) WaitForReady

func (s *ProtectedMCPServer) WaitForReady(ctx context.Context) error

WaitForReady waits for the server to be ready to accept connections

type ProtectedMCPServerConfig

type ProtectedMCPServerConfig struct {
	// Name is the name of this MCP server
	Name string

	// OAuthServer is the mock OAuth server to validate tokens against
	OAuthServer *OAuthServer

	// Issuer is the expected token issuer (used for WWW-Authenticate header)
	Issuer string

	// RequiredScope is the OAuth scope required to access this server
	RequiredScope string

	// OmitResourceMetadata makes the server publish no RFC 9728 metadata:
	// the 401 challenge carries no resource_metadata pointer and
	// /.well-known/oauth-protected-resource is not served. The aggregator
	// then learns the authorization server only from an operator pin
	// (spec.auth.authorizationServer), the shape of a backend that does not
	// implement resource metadata.
	OmitResourceMetadata bool

	// AdvertisedIssuer, when set, is the authorization server the RFC 9728
	// metadata and the 401 challenge name instead of the one tokens are
	// validated against: a backend that accepts tokens from an authorization
	// server other than the one it advertises.
	AdvertisedIssuer string

	// Tools are the tools to expose when authenticated
	Tools []ToolConfig

	// Transport is the HTTP transport type (sse or streamable-http)
	Transport HTTPTransportType

	// TrustJWKSURL, when set, switches token validation from the mock OAuth
	// server's opaque-token check to JWT signature verification against this
	// JWKS endpoint (the trusted issuer's JWKS, a dex stand-in). This is how
	// a backend proves it accepts a forwarded IdP-issued token end-to-end.
	TrustJWKSURL string

	// TrustJWKSRootCAs verifies the TLS certificate of the TrustJWKSURL
	// endpoint (mock issuers serve TLS with a test CA). nil keeps the
	// system pool.
	TrustJWKSRootCAs *x509.CertPool

	// ExpectedAudience is the aud value the minted token must carry when
	// TrustJWKSURL is set. Empty accepts any audience.
	ExpectedAudience string

	// ExpectedIssuer is the iss value the minted token must carry when
	// TrustJWKSURL is set. Empty accepts any issuer.
	ExpectedIssuer string

	// StartAnonymous makes the server accept every request without a token
	// until SetAuthRequired(true): the old, anonymous pod of a backend that
	// is being rolled over to OAuth. While anonymous it publishes no RFC 9728
	// metadata either.
	StartAnonymous bool

	// ConnectDelay holds every initialize request for this long before the
	// server answers it: a backend that is slow to connect, so a scenario can
	// prove what the aggregator does while a session's connect to it is still
	// in flight.
	ConnectDelay time.Duration

	// Debug enables debug logging
	Debug bool
}

ProtectedMCPServerConfig configures an OAuth-protected mock MCP server

type RealClock

type RealClock struct{}

RealClock implements Clock using the actual system time.

func (RealClock) Now

func (RealClock) Now() time.Time

Now returns the current time.

type ResourceConfig

type ResourceConfig struct {
	// URI is the resource identifier, e.g. "board://schema"
	URI string `yaml:"uri"`
	// Name is the human-readable resource name
	Name string `yaml:"name"`
	// Description describes what the resource holds
	Description string `yaml:"description"`
	// MIMEType of the resource contents, defaulting to text/plain
	MIMEType string `yaml:"mime_type"`
	// Text is the resource body returned on read
	Text string `yaml:"text"`
}

ResourceConfig defines a static MCP resource served by the mock server.

Resources exist in the mock so scenarios can exercise the aggregator's resource paths -- notably that a URI carrying a scheme is exposed unprefixed, which lets two servers advertise the same URI.

type Server

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

Server represents a mock MCP server for testing

func NewServerFromFile

func NewServerFromFile(configPath string, debug bool) (*Server, error)

NewServerFromFile creates a new mock MCP server from a configuration file

func (*Server) AddDynamicTool

func (s *Server) AddDynamicTool(toolConfig ToolConfig)

AddDynamicTool adds a tool to the running MCP server at runtime. The mcp-go library automatically sends a notifications/tools/list_changed notification to all connected clients.

func (*Server) RemoveDynamicTool

func (s *Server) RemoveDynamicTool(toolName string)

RemoveDynamicTool removes a tool from the running MCP server at runtime. The mcp-go library automatically sends a notifications/tools/list_changed notification to all connected clients.

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start starts the mock MCP server using stdio transport

type TestScenario

type TestScenario struct {
	PreConfiguration *PreConfiguration `yaml:"pre_configuration,omitempty"`
}

TestScenario is needed for loadServerConfig function - importing from parent would cause circular dependency This is a minimal copy of the required fields

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token,omitempty"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in,omitempty"`
	Scope        string `json:"scope,omitempty"`
	IDToken      string `json:"id_token,omitempty"`
}

TokenResponse is the OAuth token response

type ToolAnnotationsConfig

type ToolAnnotationsConfig struct {
	ReadOnlyHint    *bool `yaml:"read_only_hint,omitempty"`
	DestructiveHint *bool `yaml:"destructive_hint,omitempty"`
	IdempotentHint  *bool `yaml:"idempotent_hint,omitempty"`
	OpenWorldHint   *bool `yaml:"open_world_hint,omitempty"`
}

ToolAnnotationsConfig mirrors mcp.ToolAnnotation with the hints a mock tool may declare. A hint that is not set is not sent, like a real server.

func (*ToolAnnotationsConfig) Apply

func (a *ToolAnnotationsConfig) Apply(tool *mcp.Tool)

Apply sets the configured hints on tool.

type ToolConfig

type ToolConfig struct {
	// Name is the unique identifier for the tool
	Name string `yaml:"name"`
	// Description describes what the tool does
	Description string `yaml:"description"`
	// InputSchema defines the expected input schema (JSON Schema)
	InputSchema map[string]interface{} `yaml:"input_schema"`
	// Responses defines possible responses for this tool
	Responses []ToolResponse `yaml:"responses"`
	// EchoToken makes the tool return the bearer token it was invoked with and
	// its decoded claims (sub, act, groups, aud, iss). Used to assert that a
	// downstream backend accepts a broker-minted token end-to-end.
	EchoToken bool `yaml:"echo_token,omitempty"`
	// EchoHandshake makes the tool return the protocolVersion and client name
	// the connecting MCP client sent in its initialize request, alongside the
	// configured response. Used to assert the protocol revision muster's
	// outbound client negotiates with a downstream server.
	EchoHandshake bool `yaml:"echo_handshake,omitempty"`

	// EchoHeaders names request headers the tool reports back, as
	// `received_headers` next to its response: what the backend saw on the
	// HTTP request that carried the call, so a scenario can assert the
	// definition's spec.headers reach it on a session's connection. A header
	// that carries a JWT is also reported decoded, as
	// `received_header_claims.<name>` (sub, iss, aud; signature unchecked).
	EchoHeaders []string `yaml:"echo_headers,omitempty"`
	// Annotations are the MCP tool annotations the mock declares, so scenarios
	// can exercise what muster does with a downstream server's read-only /
	// destructive hints (annotation forwarding, the read-only toolset preset).
	Annotations *ToolAnnotationsConfig `yaml:"annotations,omitempty"`
}

ToolConfig defines configuration for a mock tool

type ToolHandler

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

ToolHandler handles mock tool calls with configurable responses

func NewToolHandler

func NewToolHandler(config ToolConfig, templateEngine *template.Engine, debug bool) *ToolHandler

NewToolHandler creates a new mock tool handler

func (*ToolHandler) GetDescription

func (h *ToolHandler) GetDescription() string

GetDescription returns the tool description

func (*ToolHandler) GetName

func (h *ToolHandler) GetName() string

GetName returns the tool name

func (*ToolHandler) HandleCall

func (h *ToolHandler) HandleCall(args map[string]interface{}) (interface{}, error)

HandleCall processes a tool call and returns the configured response

type ToolResponse

type ToolResponse struct {
	// Condition defines arg matching for this response (optional)
	// If empty, this response is used as a fallback
	Condition map[string]interface{} `yaml:"condition,omitempty"`
	// Response is the response data to return
	Response interface{} `yaml:"response,omitempty"`
	// Error is the error message to return instead of response
	Error string `yaml:"error,omitempty"`
	// Delay simulates response latency (e.g., "2s", "500ms")
	Delay string `yaml:"delay,omitempty"`
}

ToolResponse defines a conditional response for a mock tool

type ToolSetChange added in v5.29.0

type ToolSetChange struct {
	Add    []ToolConfig
	Remove []string
}

ToolSetChange is what a redeployed backend offers differently from the process it replaces: the tools its new image adds (one of a name already served replaces it) and the names it no longer serves. The zero value is a redeploy that keeps the tool set.

func (ToolSetChange) Summary added in v5.29.0

func (c ToolSetChange) Summary() string

Summary describes the change for a message: "tools kept", or the added and removed names as "tools changed: +report -probe".

Jump to

Keyboard shortcuts

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