Documentation
¶
Overview ¶
Package api provides the central API layer for muster's Service Locator Pattern.
This package serves as the single point of communication between all muster packages, preventing direct inter-package dependencies and enabling clean architectural separation. All service functionality is accessed through handler interfaces registered with this central API layer.
Service Locator Pattern ¶
The API package implements the core Service Locator Pattern that is **mandatory** for all inter-package communication in muster:
**Handler Interfaces** - Define contracts for each service capability (ServiceRegistryHandler, ServiceManagerHandler, AggregatorHandler, etc.)
**API Implementations** - Thin wrappers that delegate to registered handlers (direct handler access through Get* functions)
**Handler Registry** - Central registry for handler implementations with thread-safe registration and access
**Adapter Pattern** - Service packages provide adapters that implement handler interfaces and register with the API layer
This architecture ensures: - **Zero circular dependencies** (API doesn't import internal packages) - **Clean separation of concerns** between packages - **Enhanced testability** through handler mocking - **Runtime flexibility** in handler registration - **Independent package development** and refactoring
Handler Interfaces ¶
## Core Service Handlers
- **ServiceRegistryHandler**: Unified service registry access and discovery
- **ServiceManagerHandler**: Service lifecycle management for all service types
- **AggregatorHandler**: Tool execution and MCP server aggregation
- **ConfigHandler**: Configuration management and runtime settings
## Specialized Handlers
- **MCPServerManagerHandler**: MCP server definition and process management
- **WorkflowHandler**: Multi-step workflow execution and orchestration
Core Operations ¶
The API layer provides unified access to all muster functionality:
## Service Management
- Service registry operations (register, get, list services)
- Service lifecycle management (start, stop, restart)
- Service state monitoring and health checking
## MCP Server Management
- MCP server definition management (create, update, delete, validate)
- MCP server lifecycle management and health monitoring
- Tool aggregation, namespace management, and conflict resolution
- Dynamic MCP server registration and tool discovery
## Workflow Management
- Workflow definition management (create, update, delete, validate)
- Multi-step workflow execution with arg templating
- Conditional logic and step dependency management
- Tool integration for workflow steps with error handling
- Workflow input schema validation and documentation generation
## Tool Provider System
- Tool provider registration and discovery
- Tool metadata management and arg validation
- Tool execution abstraction for different implementation types
- Automatic tool aggregation and namespace management
## Request/Response Handling
- Structured request types for all operations (Create, Update, Validate patterns)
- Type-safe arg parsing and validation using ParseRequest
- Comprehensive error handling with contextual information
Tool Update Events ¶
The API layer provides a centralized event system for tool availability changes:
// Subscribe to tool updates
api.SubscribeToToolUpdates(mySubscriber)
// Publish tool update events
event := api.ToolUpdateEvent{
Type: "server_registered",
ServerName: "kubernetes",
Tools: []string{"kubectl_get_pods", "kubectl_describe"},
Timestamp: time.Now(),
}
api.PublishToolUpdateEvent(event)
Event types include:
- "server_registered": New MCP server registration
- "server_deregistered": MCP server removal
- "tools_updated": Tool availability changes
This enables managers to automatically refresh availability when the tool landscape changes, supporting real-time reactivity throughout the system.
API Registration Pattern ¶
**Critical**: All packages must follow the registration pattern:
**Implement Handler Interface** in adapter pattern: ```go type ServiceAdapter struct { service *MyService }
func (a *ServiceAdapter) SomeOperation(ctx context.Context) error { return a.service.performOperation(ctx) } ```
**Register with API Layer**: ```go func (a *ServiceAdapter) Register() { api.RegisterMyServiceHandler(a) } ```
**Access through API Layer** (never direct imports): ```go handler := api.GetMyServiceHandler() if handler != nil { handler.SomeOperation(ctx) } ```
Example Usage ¶
## Service Registration (Service Package)
// Service adapter implements handler interface
type RegistryAdapter struct {
registry *ServiceRegistry
}
func (r *RegistryAdapter) GetService(ctx context.Context, name string) (*ServiceInfo, error) {
return r.registry.Get(name)
}
func (r *RegistryAdapter) Register() {
api.RegisterServiceRegistry(r)
}
## Tool Provider Registration
type MyToolProvider struct {
tools []ToolMetadata
}
func (p *MyToolProvider) GetTools() []ToolMetadata {
return p.tools
}
func (p *MyToolProvider) ExecuteTool(ctx context.Context, toolName string, args map[string]interface{}) (*CallToolResult, error) {
// Implementation specific logic
return &CallToolResult{Content: []interface{}{result}, IsError: false}, nil
}
## API Usage (Consumer Package)
// Access through API layer (correct approach)
serviceManager := api.GetServiceManager()
if serviceManager != nil {
err := serviceManager.StartService(ctx, "my-service")
}
// Execute workflows through convenience functions
result, err := api.ExecuteWorkflow(ctx, "deploy-app", args)
Workflow Integration ¶
The API provides convenient functions for workflow operations:
// Get workflow information and input schemas workflows := api.GetWorkflowInfo()
Health Check System ¶
The API defines standardized health checking for all components:
// Health status constants
const (
HealthUnknown = "unknown" // Status cannot be determined
HealthHealthy = "healthy" // Operating normally
HealthDegraded = "degraded" // Some issues but functional
HealthUnhealthy = "unhealthy" // Significant issues
HealthChecking = "checking" // Health check in progress
)
// Health check configuration
config := HealthCheckConfig{
Enabled: true,
Interval: 30 * time.Second,
FailureThreshold: 3,
SuccessThreshold: 1,
}
Orchestrator Integration ¶
The API provides orchestrator functionality for unified service operations:
// List all services with unified status orchestrator := api.GetOrchestrator() services, err := orchestrator.ListServices(ctx)
Thread Safety ¶
All API components are fully thread-safe:
- Handler registry uses mutex protection for registration/access
- Concurrent handler registration and access operations
- Thread-safe API method execution across all handlers
- Safe concurrent service operations and state management
- Tool update event broadcasting with goroutine safety
- Request parsing and validation thread safety
Error Handling ¶
The API layer provides structured error handling:
- Handler availability checking with nil safety
- Service validation with detailed error messages
- Tool execution error propagation with context preservation
- Workflow execution error handling
- Request parsing validation with field-level error reporting
- Comprehensive error context and recovery mechanisms
Performance Characteristics ¶
The Service Locator Pattern provides:
- **Minimal overhead**: Thin delegation layer to handlers
- **Lazy initialization**: Handlers registered as needed during startup
- **Concurrent access**: No bottlenecks in handler access patterns
- **Memory efficiency**: Single handler instances shared across requests
- **Event efficiency**: Asynchronous tool update broadcasting
- **Request efficiency**: JSON-based parsing with minimal allocations
Testing Support ¶
The API package provides testing utilities:
- **Handler isolation**: Independent handler registration per test
- **Event testing**: Tool update event validation and mocking
- **Request validation testing**: ParseRequest error scenario testing
Design Principles ¶
1. **Single Point of Truth**: All inter-package communication through API 2. **No Direct Dependencies**: Packages never import each other directly 3. **Interface Segregation**: Small, focused handler interfaces 4. **Dependency Inversion**: Depend on abstractions, not implementations 5. **Open/Closed Principle**: Easy to extend with new handlers 6. **Event-Driven Architecture**: Reactive updates through tool events 7. **Type Safety**: Strong typing through request/response structures 8. **Validation by Default**: All requests validated before processing
**Critical Rule**: ALL inter-package communication MUST go through this API layer. Direct imports between internal packages are **forbidden** and violate the core architectural principle.
Index ¶
- Constants
- Variables
- func AgentDisplayNameOfContext(ctx context.Context) string
- func AgentOfContext(ctx context.Context) string
- func AgentReasonFromContext(ctx context.Context) string
- func ApplyTagsAnnotation(annotations map[string]string, tags *[]string) map[string]string
- func ApplyTagsUpdate(annotations map[string]string, tags *[]string) (map[string]string, error)
- func ApprovalBindingKey(identity SignInIdentity, sessionID, agent string, target ApprovalTarget, ...) string
- func ApprovalPresets() []string
- func ApprovalSchemaProblem(ctx context.Context) string
- func AuditApproval(ctx context.Context, action string, attrs ...slog.Attr)
- func AuthoringWarnings(wf *Workflow) []string
- func AuthorizationServerDigest(as *MCPServerAuthAuthorizationServer) string
- func CallerKind(ctx context.Context, sessionID string) string
- func CallerMeta(ctx context.Context) map[string]any
- func CapAgentDisplayName(name string) string
- func ClearLoginIDToken(h OAuthHandler, sessionID, issuer string)
- func ClearTokenByIssuerForUser(h OAuthHandler, sessionID, userID, issuer string)
- func CollectRequiredAudiences(ctx context.Context) ([]string, error)
- func ContextWithToolApprovalHeader(ctx context.Context, value string) context.Context
- func CoreFloorTools() []string
- func CoreSafeTools() []string
- func DeprecatedFieldAliases(args map[string]interface{}) []string
- func ForgetSubjectGrant(h OAuthHandler, userID, issuer string)
- func GetSessionIDFromContext(ctx context.Context) string
- func GetSubjectFromContext(ctx context.Context) string
- func GovernanceRoles() []string
- func InputSchemaFromArgs(args []ArgMetadata) mcp.ToolInputSchema
- func IsActiveState(state ServiceState) bool
- func IsActorSession(sessionID string) bool
- func IsAgentCaller(kind string) bool
- func IsAuthRequiredError(err error) bool
- func IsDownState(state ServiceState) bool
- func IsForwardedSession(sessionID string) bool
- func IsMusterCaller(ctx context.Context) bool
- func IsNotFound(err error) bool
- func IsOrganizationPrincipalSession(sessionID string) bool
- func IsSignInRefused(err error) bool
- func IsTenantIssuerKey(key string) bool
- func IsTenantMCPServerKey(key string) bool
- func IssuerKey(namespace, issuer string) string
- func IssuerSubjectScoped(h OAuthHandler, issuer string) bool
- func IssuerURL(key string) string
- func LoginSessionForIDToken(h OAuthHandler, idToken string) string
- func MCPServerEventKey(event EventResult, musterNamespace string) (string, bool)
- func MCPServerExposedPrefix(key, toolPrefix string) string
- func MCPServerKey(namespace, name, musterNamespace string) string
- func MCPServerObject(key, musterNamespace string) (namespace, name string)
- func MCPToolAnnotation(a *ToolAnnotations) mcp.ToolAnnotation
- func MergeRoleFloors(configured map[string][]string) map[string][]string
- func NewTokenExchangeCredentialsError(ref *ClientCredentialsSecretRef, defaultNamespace string, err error) error
- func NotVisible(err error) error
- func OutputEnabled(output *bool, store bool) bool
- func ParseRequest[T any](args map[string]interface{}, request *T) error
- func ParseTags(raw string) []string
- func PostLoginRedirectAllowed(raw string) bool
- func PresetSelects(ctx context.Context, preset string, t AgentTarget) bool
- func PrincipalAudienceNotAllowed(audience, serverURL string) error
- func PrincipalAudienceRefusal(audience, serverURL string) error
- func PublishToolUpdateEvent(event ToolUpdateEvent)
- func RegisterAggregator(h AggregatorHandler)
- func RegisterApprovalStore(s ApprovalStore)
- func RegisterAuthHandler(h AuthHandler)
- func RegisterBrowserIdentity(b BrowserIdentity)
- func RegisterConfigHandler(h ConfigHandler)
- func RegisterDelegationExchange(h DelegationExchange)
- func RegisterEventManager(h EventManagerHandler)
- func RegisterGovernance(g Governance)
- func RegisterHandoffRedeemer(r HandoffRedeemer)
- func RegisterMCPServerManager(h MCPServerManagerHandler)
- func RegisterMCPServerVisibility(h MCPServerVisibilityHandler)
- func RegisterMetaTools(h MetaToolsHandler)
- func RegisterMetaToolsDataProvider(p MetaToolsDataProvider)
- func RegisterOAuthHandler(h OAuthHandler)
- func RegisterOrganizationPrincipals(h OrganizationPrincipalHandler)
- func RegisterPresetSelector(s PresetSelector)
- func RegisterProcedureRunTools(p ToolProvider)
- func RegisterReconcileManager(h ReconcileManagerHandler)
- func RegisterSecretCredentialsHandler(h SecretCredentialsHandler)
- func RegisterSensitiveToolArgs(tool string, args []ArgMetadata)
- func RegisterServerToolResolver(r ServerToolResolver)
- func RegisterServiceManager(h ServiceManagerHandler)
- func RegisterServiceRegistry(h ServiceRegistryHandler)
- func RegisterSessionSubjectResolver(r SessionSubjectResolver)
- func RegisterToolsetGate(g ToolsetGate)
- func RegisterWorkflow(h WorkflowHandler)
- func RelayedExtensions(extensions map[string]any) map[string]any
- func ReportMCPServerTokenExchange(name string, err error)
- func ReportingAsAgent(ctx context.Context) bool
- func ResolveRequestMeta(requestMeta, meta map[string]string) (map[string]string, error)
- func SensitiveToolArgs(tool string) []string
- func ServerIssuerKey(serverKey, issuer string) string
- func ServerTools(ctx context.Context, server string) ([]mcp.Tool, bool)
- func SetToolApproval(tool *mcp.Tool, approval ToolApproval)
- func ShadowingServer(namespace, musterNamespace string, servers []MCPServerInfo) (string, bool)
- func SignInCheckRefusal(ctx context.Context) error
- func SignInPrompt(ctx context.Context) bool
- func SplitIssuerKey(key string) (namespace, issuer string)
- func SplitMCPServerKey(key string) (namespace, name string)
- func StoreLoginIDToken(h OAuthHandler, sessionID, userID, issuer, idToken string, expiresAt time.Time)
- func SubscribeToToolUpdates(subscriber ToolUpdateSubscriber)
- func ToolsetServers(ctx context.Context) (admits func(server string) bool, scoped bool, err error)
- func ToolsetShows(ctx context.Context) (shows func(server string) bool, scoped bool)
- func ToolsetShowsCore(ctx context.Context) bool
- func UnregisterAuthHandler(h AuthHandler) bool
- func UpdateMCPServerState(name string, state ServiceState, health HealthStatus, err error) error
- func ValidateAuthorizationServer(auth *MCPServerAuth) error
- func ValidateForwardIdentity(auth *MCPServerAuth) error
- func ValidateGrantScope(auth *MCPServerAuth) error
- func ValidateHeadersFrom(serverType string, headersFrom []MCPServerHeaderFrom) error
- func ValidateLoopsPagingAndJQ(wf *Workflow, checkJQ func(program string) error) error
- func ValidateNoInlineCredential(serverType, rawURL string, headers, env map[string]string, kubernetesMode bool) error
- func ValidateNotShadowed(ctx context.Context, namespace, musterNamespace string, ...) error
- func ValidatePrincipalAudience(serverType string, auth *MCPServerAuth) error
- func ValidateProgress(timeout int, progress *MCPServerProgress) error
- func ValidateProviderApps(auth *MCPServerAuth) error
- func ValidateRequestMeta(serverType string, auth *MCPServerAuth, requestMeta map[string]string) error
- func ValidateResourceName(name string) error
- func ValidateSecretNamespaces(serverNamespace, musterNamespace string, auth *MCPServerAuth) error
- func ValidateServerNamespace(namespace, musterNamespace string, family *MCPServerFamily, ...) error
- func ValidateSigV4(serverType string, auth *MCPServerAuth) error
- func ValidateStdioAllowed(serverType string, kubernetesMode bool) error
- func ValidateTags(tags []string) error
- func ValidateTagsUpdate(tags, stored []string) error
- func WithAgentApproval(ctx context.Context, a *AgentApproval) context.Context
- func WithAgentReason(ctx context.Context, reason string) context.Context
- func WithCallerMeta(ctx context.Context, entries map[string]any) (context.Context, error)
- func WithDelegatedCaller(ctx context.Context, caller DelegatedCaller) context.Context
- func WithMusterCaller(ctx context.Context) context.Context
- func WithOrganizationPrincipal(ctx context.Context, p OrganizationPrincipal) context.Context
- func WithSessionID(ctx context.Context, sessionID string) context.Context
- func WithSessionToolMemo(ctx context.Context) context.Context
- func WithSignInIdentity(ctx context.Context, identity SignInIdentity) context.Context
- func WithSignInPrompt(ctx context.Context) context.Context
- func WithSubject(ctx context.Context, subject string) context.Context
- func WithoutReportingApproval(ctx context.Context) context.Context
- func WorkflowNameOf(name string) string
- func WorkflowStepTools(wf *Workflow) []string
- type AgentApproval
- type AgentApprovalEntry
- type AgentApprovalGrant
- type AgentTarget
- type AggregatorHandler
- type ApprovalArgument
- type ApprovalChange
- type ApprovalDisplay
- type ApprovalLimitError
- type ApprovalPageFlow
- type ApprovalRequest
- type ApprovalStep
- type ApprovalStore
- type ApprovalTarget
- type Arg
- type ArgDefinition
- type ArgMetadata
- type ArgType
- type AuthChallenge
- type AuthChallengeParams
- type AuthCompletionCallback
- type AuthHandler
- type AuthInfo
- type AuthStatus
- type AuthorizationServerConflictChecker
- type AuthorizationServerDescriptionChecker
- type BrowserIdentity
- type CallToolResult
- type CallerAuthenticationError
- type ClientCredentials
- type ClientCredentialsSecretRef
- type ConfigAPI
- type ConfigHandler
- type ConfigurableService
- type CreateWorkflowRequest
- type DelegatedCaller
- type DelegationExchange
- type EventData
- type EventManagerHandler
- type EventPoller
- type EventQueryOptions
- type EventQueryResult
- type EventResult
- type GetWorkflowExecutionRequest
- type Governance
- func (g Governance) CoreEntry(tool string) (ToolApproval, bool)
- func (g Governance) Governed() bool
- func (g Governance) ModeName() string
- func (g Governance) NamesServer(server string) bool
- func (g Governance) RoleFloorsOf(role string) []string
- func (g Governance) Roles() []string
- func (g Governance) ServerEntry(server, tool string) (approval ToolApproval, applies, refused bool)
- func (g Governance) UnmatchedSafe(server string, tools []string) []string
- func (g Governance) Validate() error
- type GovernedServer
- type GrantReleaser
- type HandoffRedeemer
- type HealthStatus
- type InvalidTagsError
- type IssuerPin
- type IssuerPinner
- type ListWorkflowExecutionsRequest
- type ListWorkflowExecutionsResponse
- type LoginTokenMirror
- type MCPServer
- type MCPServerApproval
- type MCPServerApprovalSchema
- type MCPServerAuth
- func (a *MCPServerAuth) CanAuthenticateInteractively() bool
- func (a *MCPServerAuth) DiscoversSubjectScopedIssuer() bool
- func (a *MCPServerAuth) ForwardsIdentity() bool
- func (a *MCPServerAuth) ReceivesProviderApps() bool
- func (a *MCPServerAuth) RequiresUserSignIn() bool
- func (a *MCPServerAuth) ServesOrganizationPrincipal() bool
- func (a *MCPServerAuth) SubjectScoped() bool
- func (a *MCPServerAuth) UsesSessionAuth() bool
- type MCPServerAuthAuthorizationServer
- type MCPServerClientCredentials
- type MCPServerConnectorAdmin
- type MCPServerCreateRequest
- type MCPServerDetectRequest
- type MCPServerFamily
- type MCPServerHeaderFrom
- type MCPServerInfo
- type MCPServerLastObserved
- type MCPServerLifecycleAsCaller
- type MCPServerManagerHandler
- type MCPServerProgress
- type MCPServerSigV4
- type MCPServerType
- type MCPServerUpdateRequest
- type MCPServerValidateRequest
- type MCPServerValueSource
- type MCPServerVisibilityHandler
- type MetaToolsDataProvider
- type MetaToolsHandler
- type MusterVisibilityHandler
- type NotFoundError
- type OAuthHandler
- type OAuthToken
- type ObjectReference
- type OperationDefinition
- type OrchestratorAPI
- type OrganizationPrincipal
- type OrganizationPrincipalCallRefusal
- type OrganizationPrincipalHandler
- type OrganizationPrincipalRefusal
- type PendingAuthRegistration
- type PinnedLoginMirror
- type PostLoginRedirects
- type PresetSelector
- type PrincipalServerToolResolver
- type PromptOrigin
- type ReconcileManagerHandler
- type ReconcileOverview
- type ReconcileStatusInfo
- type ReconcileStatusSummary
- type ResolvedTokenExchangeConfig
- type ResourceOrigin
- type SchemaProperty
- type SecretCredentialsHandler
- type SecretOwner
- type ServerAuthInfo
- type ServerTool
- type ServerToolLister
- type ServerToolResolver
- type ServerVisibility
- func AllServersVisible() ServerVisibility
- func CallerVisibility(ctx context.Context) ServerVisibility
- func NoServerVisible(reason string) ServerVisibility
- func NoServerVisibleWithError(reason error) ServerVisibility
- func ServersOfNamespacesVisible(musterNamespace string, namespaces []string) ServerVisibility
- type ServiceInfo
- type ServiceListResponse
- type ServiceManagerHandler
- type ServiceRegistryHandler
- type ServiceState
- type ServiceStateChangedEvent
- type ServiceStatus
- type ServiceType
- type SessionSubjectResolver
- type SessionToolMemo
- type SignInCheckError
- type SignInHandoff
- type SignInIdentity
- type StateUpdater
- type SubjectContextKey
- type SubjectGrantForgetter
- type SubjectGrantHandler
- type TenantIssuerForgetter
- type TokenEndpointProber
- type TokenEndpointUnavailableError
- type TokenExchangeConfig
- type TokenExchangeCredentialsError
- type TokenExchangeDelegation
- type TokenExchangeFailureClass
- type TokenExchangeOutcomeRecorder
- type ToolAnnotations
- type ToolApproval
- func ApplyAgentSetting(admin ToolApproval, setting, entry string, granted bool) ToolApproval
- func BuiltinApproval(exposedName string) (ToolApproval, bool)
- func KeepExplanation(final, decided ToolApproval) ToolApproval
- func ResolveConnectorApproval(approval *MCPServerApproval, tool string) ToolApproval
- func StrictestApproval(approvals ...ToolApproval) ToolApproval
- func ToolApprovalOf(tool mcp.Tool) (ToolApproval, bool)
- type ToolCaller
- type ToolChecker
- type ToolMetadata
- type ToolProvider
- type ToolUpdateEvent
- type ToolUpdateSubscriber
- type ToolsetGate
- type ToolsetServerScope
- type Workflow
- type WorkflowCondition
- type WorkflowConditionExpectation
- type WorkflowCreateRequest
- type WorkflowExecution
- type WorkflowExecutionStatus
- type WorkflowExecutionStep
- type WorkflowExecutionSummary
- type WorkflowForEach
- type WorkflowHandler
- type WorkflowInputSchema
- type WorkflowPaginate
- type WorkflowStep
- type WorkflowSubStep
- type WorkflowUpdateRequest
- type WorkflowValidateRequest
Constants ¶
const ( // ApprovalSourceAgent is an agent entry (or the list's default) that is // stricter than the connector's setting. ApprovalSourceAgent = "agent" // ApprovalSourceAgentException is an agent's granted Allow over the // connector's Ask. ApprovalSourceAgentException = "agent-exception" )
Where an effective approval comes from, when an agent's settings decided it.
const ( MaxAgentApprovalEntries = 128 MaxAgentApprovalGrants = 256 )
Bounds on the approval settings a binding or a reporting call carries.
const ( AgentTargetTool = "tool" AgentTargetWorkflow = "workflow" AgentTargetCore = "core" )
Target kinds of AgentTarget.
const ( ApprovalAllow = "Allow" ApprovalAsk = "Ask" ApprovalBlock = "Block" )
The values of an MCPServer's spec.approval, as they are written: rule and a tool entry take Allow, Ask or Block. They are case-sensitive.
const ( // ApprovalSettingAllow runs the call. ApprovalSettingAllow = "allow" // ApprovalSettingAsk asks a person to confirm the exact call first. ApprovalSettingAsk = "ask" // ApprovalSettingBlock hides the tool and refuses calls to it. ApprovalSettingBlock = "block" )
The effective approval of a tool, as the meta-tools report it.
const ( // ApprovalSourceTool is the tool's own entry in spec.approval.tools. ApprovalSourceTool = "tool" // ApprovalSourceConnector is the server's spec.approval.rule (or its // absence on a server that has spec.approval); a rule Block hides every // tool without its own entry. ApprovalSourceConnector = "connector" // ApprovalSourceUnreviewed is a tool of a server without spec.approval, // or a tool no server owns: Allow, until someone reviews it. ApprovalSourceUnreviewed = "unreviewed" // ApprovalSourceBuiltin is a tool muster always asks for, whoever calls // it: its own server configuration. ApprovalSourceBuiltin = "builtin" // be read; it is reported as Ask, never as Allow. ApprovalSourceUnavailable = "unavailable" )
Where an effective approval comes from.
const ( // ApprovalPresetRecommended: rule Ask, each tool annotated readOnlyHint // true Allow, every other tool Ask. ApprovalPresetRecommended = "recommended" // ApprovalPresetAllowAll: rule Allow, every tool Allow. ApprovalPresetAllowAll = "allow-all" // ApprovalPresetAskAll: rule Ask, every tool Ask. ApprovalPresetAskAll = "ask-all" )
The presets a person picks from when they review a server's tools. Each expands, once, into explicit settings (ExpandApprovalPreset); none is stored or evaluated later.
const ( // HandoffKindApproval is the approval page of one request; the target // is the request's id. HandoffKindApproval = "approval" // HandoffKindSignIn is the OAuth proxy start of one connector sign-in; // the target is the digest of its state. HandoffKindSignIn = "sign_in" )
The pages a handoff is bound to.
const ( ApprovalStatusPending = "pending" ApprovalStatusApproved = "approved" ApprovalStatusDeclined = "declined" )
The decision states of an approval request.
const ( // ApprovalTargetTool is a tool of a registered MCP server. ApprovalTargetTool = "tool" // ApprovalTargetCore is one of muster's own core tools. ApprovalTargetCore = "core" // ApprovalTargetWorkflow is a workflow run, approved once up front. ApprovalTargetWorkflow = "workflow" )
The kinds of target an approval binds.
const ( // CallerKindPerson is a person acting directly with their own bearer // (the portal backend, a person's own client). CallerKindPerson = "person bearer" // CallerKindActor is a Session sandbox calling with its actor JWT. CallerKindActor = "actor JWT" // CallerKindDelegated is a caller presenting a delegated token whose // act claim names the party acting for the person. CallerKindDelegated = "delegated" )
The kinds of caller, as the audit records them. Only agent callers are asked by the floors and the governance entries; the admin settings ask every caller.
const ( // ApprovalLimitPerson is the cap on one person's pending requests, // across all their sessions and agents. ApprovalLimitPerson = "person" // ApprovalLimitSession is the cap on one person's pending requests in // one muster session. ApprovalLimitSession = "session" )
The caps on pending requests an ApprovalLimitError names.
const ( // AuthMsgAlreadyConnected indicates the user already has an active session connection // to the specific server they're trying to authenticate to. AuthMsgAlreadyConnected = "Already Connected" // AuthMsgSuccessfullyConnected indicates a successful connection was established, // either through SSO (Token Forwarding/Exchange) or direct authentication. AuthMsgSuccessfullyConnected = "Successfully connected" // AuthMsgAlreadyAuthenticated is an alternative marker for existing authentication. AuthMsgAlreadyAuthenticated = "already authenticated" )
Auth tool response message markers. These constants define the standard message prefixes/markers used in auth tool responses. They enable consistent detection of connection status across CLI and aggregator components.
IMPORTANT: When modifying these values, ensure both the message generation (auth_tools.go) and message detection (auth_helpers.go) code remain synchronized.
const ( GovernanceTrusted = "trusted" GovernanceGoverned = "governed" )
The governance modes. Trusted applies the floors only; Governed also asks agent callers before every tool of a governed server that is not on that server's safe list, and before every core tool that is not one of muster's own reads.
const ( GovernanceRoleAgentManager = "agentManager" GovernanceRoleConnectorManager = "connectorManager" GovernanceRoleSessionManager = "sessionManager" GovernanceRoleModelManager = "modelManager" GovernanceRoleClusterManager = "clusterManager" GovernanceRoleVMManager = "vmManager" GovernanceRoleWorkspaceManager = "workspaceManager" GovernanceRoleToolchainManager = "toolchainManager" GovernanceRoleSkillManager = "skillManager" GovernanceRoleInfrastructure = "infrastructure" )
The built-in roles a governed server may have. A role names the floors that hold on that server in both modes; a governed server without a role has no floors, only the governed default. The configuration can declare more roles, and add floors to any role, with governance.roleFloors.
const ( SchemaKeyType = "type" SchemaKeyDescription = "description" SchemaKeyProperties = "properties" SchemaKeyItems = "items" SchemaKeyRequired = "required" SchemaKeyDefault = "default" SchemaKeyEnum = "enum" SchemaKeyAdditionalProperties = "additionalProperties" SchemaKeyPattern = "pattern" SchemaKeyMaxLength = "maxLength" SchemaKeyMaxItems = "maxItems" SchemaKeyUniqueItems = "uniqueItems" )
JSON Schema specification keys used when building MCP/OpenAPI-style schemas as map[string]any. These are wire-format strings: renaming them would break the protocol.
const ( FieldName = "name" FieldStatus = "status" FieldState = "state" FieldHealth = "health" FieldCommand = "command" FieldArgs = "args" FieldTools = "tools" FieldSteps = "steps" FieldError = "error" FieldDescription = "description" FieldSuccess = "success" FieldMessage = "message" FieldServer = "server" FieldMimeType = "mimeType" FieldExecutionID = "execution_id" FieldInput = "input" FieldInputSchema = "inputSchema" FieldOutputSchema = "outputSchema" FieldTitle = "title" FieldURI = "uri" FieldLabel = "label" FieldID = "id" )
Field names used as keys when emitting muster API responses through untyped map[string]any (status payloads, tool results, mock responses).
const ( // OrganizationPrincipalCallNeedsPerson refuses a call that needs a // person: a core tool that signs a person in or out or changes muster's // own configuration, or a server reached with a person's sign-in, // identity or grants. OrganizationPrincipalCallNeedsPerson = "needs-person" // OrganizationPrincipalCallOutsideToolset refuses a call outside the // toolset bound to the principal, or one muster cannot check against it. OrganizationPrincipalCallOutsideToolset = "outside-toolset" // OrganizationPrincipalCallAudienceNotAllowed refuses a server whose URL // the platform has not approved for its audience. OrganizationPrincipalCallAudienceNotAllowed = "principal-audience-not-allowed" )
The kinds of OrganizationPrincipalCallRefusal.
const ( ProcedureRunStart = "procedure_run_start" ProcedureRunCancel = "procedure_run_cancel" ProcedureRunSignal = "procedure_run_signal" ProcedureRunGet = "procedure_run_get" ProcedureRunList = "procedure_run_list" )
const ( ResourceTypeService = "service" ResourceTypeServices = "services" ResourceTypeMCPServer = "mcpserver" ResourceTypeMCPServers = "mcpservers" ResourceTypeWorkflow = "workflow" ResourceTypeWorkflows = "workflows" ResourceTypeWorkflowExecution = "workflow-execution" ResourceTypeWorkflowExecutions = "workflow-executions" // Response-only wrapper keys. These match the JSON shape emitted by the // muster API; they differ from the singular CLI forms above (e.g. the // API returns "mcpServers" camelCase, while the CLI accepts "mcpserver"). ResponseKeyMCPServer = "mcpServer" ResponseKeyMCPServers = "mcpServers" ResponseKeyServiceClass = "serviceClass" ResponseKeyServiceClasses = "serviceClasses" ResponseKeyExecutions = "executions" // MCP primitive aliases recognised at the CLI surface. Singular and // plural both resolve to the singular canonical form. MCPPrimitiveTool = "tool" MCPPrimitiveTools = "tools" MCPPrimitiveResource = "resource" MCPPrimitiveResources = "resources" MCPPrimitivePrompt = "prompt" MCPPrimitivePrompts = "prompts" )
Resource-type identifiers used by the muster CLI and exposed as keys in list/get JSON responses. Each kind has a singular form (CLI argument, detail-response key) and a plural form (list-response wrapper key).
const ( SecretFieldHeadersFrom = "spec.headersFrom" SecretFieldAuthorizationServer = "spec.auth.authorizationServer.clientCredentialsSecretRef" //nolint:gosec // G101: a field path, not a credential SecretFieldTokenExchange = "spec.auth.tokenExchange.clientCredentialsSecretRef" //nolint:gosec // G101: a field path, not a credential )
Fields of an MCPServer spec that name a Secret, for log and error messages.
const ( // ServiceDataConsecutiveFailures is an int: connection failures in a row. ServiceDataConsecutiveFailures = "consecutiveFailures" // ServiceDataLastAttempt is a time.Time: when the last attempt was made. ServiceDataLastAttempt = "lastAttempt" // ServiceDataNextRetryAfter is a time.Time: when the next attempt is due. // Absent while no retry is scheduled. ServiceDataNextRetryAfter = "nextRetryAfter" // ServiceDataLastFailureHTTPStatus is an int: the HTTP status the endpoint // answered the last failed attempt with. Absent when the failure carried // no HTTP response (connection refused, DNS, timeout) or the last attempt // succeeded. ServiceDataLastFailureHTTPStatus = "lastFailureHTTPStatus" )
Keys of the reconnect schedule a remote MCPServer service publishes through ServiceInfo.GetServiceData. The orchestrator's retry loop decides on ServiceDataNextRetryAfter whether an attempt is due, and the reconciler mirrors all four into the MCPServer CR status so `kubectl get mcpserver` shows why the last attempt failed and when muster looks again.
const ( // ServiceDataFailureReason is a string: the class of the failure the // service is in (a TokenExchangeFailureClass, // FailureReasonAuthorizationServerConflict or // FailureReasonPrincipalAudienceNotAllowed), present only while the // state is Failed for a reason other than the endpoint itself. ServiceDataFailureReason = "failureReason" // ServiceDataLastTokenExchangeSucceededAt is a time.Time: when a caller's // token was last exchanged successfully for this server. Absent until the // first successful exchange since the process started. ServiceDataLastTokenExchangeSucceededAt = "lastTokenExchangeSucceededAt" )
Keys an MCPServer service served per session (auth.forwardToken, auth.tokenExchange) publishes through ServiceInfo.GetServiceData. The reconciler writes them into the CR's Ready condition so an operator can read why a server is Awaiting Session or Failed without the logs.
const ( // DefaultLoopVariable is the name a forEach binds its item to when it // declares no `as`. DefaultLoopVariable = "item" // MaxForEachParallelism bounds forEach.parallelism. A nested loop runs // inside each outer iteration, so the calls in flight at once are at most // the outer parallelism times the inner one. MaxForEachParallelism = 50 // DefaultPaginateMaxPages is paginate.maxPages when a step declares none. DefaultPaginateMaxPages = 10 // MaxPaginateMaxPages bounds paginate.maxPages. MaxPaginateMaxPages = 1000 )
Bounds and defaults of a forEach loop and of a paginated tool step.
const AWSRegionRequestMetaKey = "AWS_REGION"
AWSRegionRequestMetaKey is the `_meta` key the AWS-hosted MCP server reads the region it operates in from. Without it the server runs every call in us-east-1, whatever region the endpoint is in.
const ActorSessionPrefix = "actor-"
ActorSessionPrefix starts the ID of the muster session of a caller that authenticated with a Session sandbox's actor JWT.
const AgentDefaultEntry = "default"
AgentDefaultEntry names the list's default where an entry is named.
const ApprovalSourceGovernance = "governance"
ApprovalSourceGovernance is a call the governance mode makes ask for agent callers.
const AuthorizationServerAnnotation = "muster.giantswarm.io/authorization-server"
AuthorizationServerAnnotation records, on a Secret muster writes for an MCPServer's client, the AuthorizationServerDigest of the authorization server it was written for.
const ClientProtocolVersion = "2025-11-25"
ClientProtocolVersion is the MCP revision the agent's client to a muster instance asks for when it does not answer URL elicitations itself (the stdio bridge, the REPL, `muster auth`), the BDD test client's default, and the revision the transport detection probe asks for. The aggregator's clients to downstream servers ask for 2026-07-28 and fall back per server (internal/mcpserver client_protocol.go).
It is deliberately not mcp.LATEST_PROTOCOL_VERSION: that constant moves with the SDK, and on mcp-go v1 it becomes 2026-07-28, which the initialize handshake cannot negotiate. Changing eras is a reviewed change, not a dependency bump.
const DefaultProgressMaxDurationSeconds = 3600
DefaultProgressMaxDurationSeconds is spec.progress.maxDuration when a definition sets none, and its largest value. A call that runs longer belongs in an MCP task, not a request held open on progress.
const DisplayNameAnnotation = "ui.giantswarm.io/display-name"
DisplayNameAnnotation holds an MCPServer's human-friendly name, shown by UIs in place of metadata.name. The key is shared with the developer portal and the other Agent Platform resources.
const FailureReasonAuthorizationServerConflict = "AuthorizationServerConflict"
FailureReasonAuthorizationServerConflict is the ServiceDataFailureReason of a server Failed with ErrAuthorizationServerConflict, and the reason of its Ready condition.
const FailureReasonPrincipalAudienceNotAllowed = "PrincipalAudienceNotAllowed"
FailureReasonPrincipalAudienceNotAllowed is the ServiceDataFailureReason of a server Failed with ErrPrincipalAudienceNotAllowed, and the reason of its Ready condition.
const GrantScopeSession = "session"
GrantScopeSession is the default grant scope: a token is bound to the login session that obtained it.
const GrantScopeSubject = "subject"
GrantScopeSubject is the MCPServerAuthAuthorizationServer.GrantScope value that files tokens under the user's identity so later sessions reuse them.
const IdempotencyKeyRequestMetaKey = "giantswarm.io/idempotency-key"
IdempotencyKeyRequestMetaKey is the `_meta` key of a tool call that names the effect it is meant to make once: a caller that repeats a call -- a retry after a transient error, the repeat after a crash between the call and its checkpoint -- sends the same value again, and a tool that honours keys answers the repeat without making the effect twice. The prefix is the one muster's own `_meta` keys carry (giantswarm.io/interrupted).
const MCPServerAuthTypeOAuth = "oauth"
MCPServerAuthTypeOAuth is the MCPServerAuth.Type value that selects OAuth 2.0/OIDC authentication.
const MCPServerAuthTypeSigV4 = "sigv4"
MCPServerAuthTypeSigV4 is the MCPServerAuth.Type value that selects AWS Signature Version 4 request signing.
const MaxAgentDisplayName = 80
MaxAgentDisplayName is the most runes of an agent's display name muster keeps; a longer one is cut.
const MaxAgentReasonRunes = 500
MaxAgentReasonRunes bounds the reason an agent gives with a call.
const MaxTagLength = 63
MaxTagLength is the longest tag accepted, in characters.
const MaxTags = 50
MaxTags is the most tags a write accepts, as for agents and skills in the developer portal.
const MaxTimeoutSeconds = 300
MaxTimeoutSeconds is the largest spec.timeout muster applies, the CRD's Maximum. A definition that never went through the CRD's validation (a filesystem-mode file, an older CRD) can hold a larger value.
const MetaKeyApproval = "muster.giantswarm.io/approval"
MetaKeyApproval is the mcp.Tool._meta.AdditionalFields key under which the aggregator records a tool's effective approval for the caller of one listing. Like the origin key it is an in-process annotation the meta-tools project into their own response field; it is never sent as _meta.
const MetaKeyLabels = "muster.giantswarm.io/labels"
MetaKeyLabels is the mcp.Tool._meta.AdditionalFields key under which muster stashes a tool's discovery labels (currently sourced from Workflow CRD labels). It is read in-process by the discovery tier (filter_tools) and is never surfaced by list_tools / describe_tool, so existing callers are unaffected.
const MultiRoundTripProtocolVersion = "2026-07-28"
MultiRoundTripProtocolVersion is the MCP revision supporting input_required results and retries with inputResponses and requestState. Clients answering URL elicitations request it and fall back to ClientProtocolVersion when the server does not support multi round-trip requests.
const OrganizationPrincipalSubjectPrefix = "client:"
OrganizationPrincipalSubjectPrefix marks the subject of an organization principal: "client:<Dex client ID>". No person's subject has it: a person's is the opaque sub Dex issues or the claim a trusted issuer maps.
const ProviderAppFlowPrefix = "app:"
ProviderAppFlowPrefix marks a provider App's sign-in in an OAuth flow's server name ("app:<name>"), where a server's sign-in carries the server's name. No MCPServer name contains a colon.
const RedactedValue = "[redacted]"
RedactedValue replaces a sensitive value in a record muster keeps.
const RegisteredByAnnotation = "ui.giantswarm.io/registered-by"
RegisteredByAnnotation records the authenticated subject that registered an MCPServer. Stamped server-side on create so attribution cannot be spoofed or omitted by clients (issue #1021). The key is shared with the developer portal.
const RegisteredByEmailAnnotation = "ui.giantswarm.io/registered-by-email"
RegisteredByEmailAnnotation records the email claim of the authenticated identity that registered an MCPServer, when the token carried one. Display metadata only — RegisteredByAnnotation holds the stable identifier (issue #1048). The key is shared with the developer portal.
const ServiceDataCreatedAt = "createdAt"
ServiceDataCreatedAt is the service data key of an MCPServer service's creation time (MCPServer.CreatedAt), absent in filesystem mode.
const ServiceDataHealthCheckFailures = "consecutiveHealthCheckFailures"
ServiceDataHealthCheckFailures is an int an MCPServer service publishes through ServiceInfo.GetServiceData: health probes that failed in a row against a connected server. Reset by a passing probe, a successful start or a stop. Shown by core_service_status; not part of the reconnect schedule above and not mirrored into the CR status.
const ServiceDataProtocolVersion = "protocolVersion"
ServiceDataProtocolVersion is the GetServiceData key under which an MCP server service reports the revision its backend answered with. Both core_service_status (via ServiceStatus.Metadata) and core_mcpserver_get (via MCPServerInfo.ProtocolVersion) read it from here.
const ServiceDataUID = "uid"
ServiceDataUID is the service data key of an MCPServer service's Kubernetes UID (MCPServer.UID), absent in filesystem mode.
const TagPattern = `^[a-z0-9]+(-[a-z0-9]+)*$`
TagPattern is the form of a single tag.
const TagsAnnotation = "ui.giantswarm.io/tags"
TagsAnnotation holds the free-form tags of an MCPServer or Workflow, comma-joined (e.g. "triage,kubernetes"). The key and the tag form are shared with the developer portal and the other Agent Platform resources (agents, skills), whose frontend parses them with parseTags in ui-react.
const TagsArgDescription = "Up to 50 unique tags (ui.giantswarm.io/tags): a-z0-9 words joined by single hyphens, max 63 chars"
TagsArgDescription describes the tags argument of the MCPServer and Workflow create and validate tools.
const TagsUpdateArgDescription = "" /* 135-byte string literal not displayed */
TagsUpdateArgDescription describes the tags argument of the MCPServer and Workflow update tools.
const ToolApprovalHeader = "X-Muster-Tool-Approval"
ToolApprovalHeader carries an agent's approval settings on the requests its runtime sends through its own RemoteMCPServer (the agent chart renders it beside X-Muster-Toolset): "<selector>=<Setting>,...[,default=<Setting>]". It carries no grants, so it can only make tools stricter than their connector's settings, and it applies only where no Session binding with an approval sender's settings does (Sessions not started through agent-manager).
const ValueSourceTypeSecret = "Secret"
ValueSourceTypeSecret is the only MCPServerValueSource.Type.
Variables ¶
var ( // ErrApprovalNotFound is a request that does not exist or expired. ErrApprovalNotFound = errors.New("approval request not found or expired") // ErrApprovalDecided is a decision on a request already decided. ErrApprovalDecided = errors.New("approval request already decided") // ErrApprovalLimit is a request beyond the caps on pending requests. ErrApprovalLimit = errors.New("too many pending approval requests") )
Errors of the approval store.
var ( // NewWorkflowNotFoundError creates a workflow not found error. // // Args: // - name: The name of the workflow that was not found // // Returns: // - *NotFoundError: A NotFoundError for the specified workflow NewWorkflowNotFoundError = func(name string) *NotFoundError { return NewNotFoundError("workflow", name) } // NewServiceNotFoundError creates a service not found error. // // Args: // - name: The name of the service that was not found // // Returns: // - *NotFoundError: A NotFoundError for the specified service NewServiceNotFoundError = func(name string) *NotFoundError { return NewNotFoundError("service", name) } // NewMCPServerNotFoundError creates an MCP server not found error. // // Args: // - name: The name of the MCP server that was not found // // Returns: // - *NotFoundError: A NotFoundError for the specified MCP server NewMCPServerNotFoundError = func(name string) *NotFoundError { return NewNotFoundError("MCP server", name) } // NewToolNotFoundError creates a tool not found error. // // Args: // - name: The name of the tool that was not found // // Returns: // - *NotFoundError: A NotFoundError for the specified tool NewToolNotFoundError = func(name string) *NotFoundError { return NewNotFoundError("tool", name) } // NewResourceNotFoundError creates a resource not found error. // // Args: // - name: The name of the resource that was not found // // Returns: // - *NotFoundError: A NotFoundError for the specified resource NewResourceNotFoundError = func(name string) *NotFoundError { return NewNotFoundError("resource", name) } // NewPromptNotFoundError creates a prompt not found error. // // Args: // - name: The name of the prompt that was not found // // Returns: // - *NotFoundError: A NotFoundError for the specified prompt NewPromptNotFoundError = func(name string) *NotFoundError { return NewNotFoundError("prompt", name) } )
Specific NotFoundError constructors for each resource type. These provide convenient, type-specific error creation with consistent naming.
var ( // ErrOrchestratorNotRegistered indicates the orchestrator handler is not registered ErrOrchestratorNotRegistered = errors.New("orchestrator handler not registered") // ErrMCPServiceNotRegistered indicates the MCP service handler is not registered ErrMCPServiceNotRegistered = errors.New("MCP service handler not registered") // ErrPortForwardNotRegistered indicates the port forward handler is not registered ErrPortForwardNotRegistered = errors.New("port forward handler not registered") // ErrK8sServiceNotRegistered indicates the Kubernetes service handler is not registered ErrK8sServiceNotRegistered = errors.New("K8s service handler not registered") // ErrConfigServiceNotRegistered indicates the config service handler is not registered ErrConfigServiceNotRegistered = errors.New("config service handler not registered") // ErrWorkflowNotRegistered indicates the workflow handler is not registered ErrWorkflowNotRegistered = errors.New("workflow handler not registered") // ErrAggregatorNotRegistered indicates the aggregator handler is not registered ErrAggregatorNotRegistered = errors.New("aggregator handler not registered") // Legacy workflow error (deprecated - use NewWorkflowNotFoundError instead) // This error is maintained for backward compatibility but should not be used in new code. // // Deprecated: Use NewWorkflowNotFoundError(name) instead for better error context. ErrWorkflowNotFound = errors.New("workflow not found") // ErrServerAlreadyRegistered is returned when a server is registered in the aggregator // registry more than once. Callers in retry loops should treat this as a no-op. ErrServerAlreadyRegistered = errors.New("server already registered") )
Common errors for API operations. These predefined errors provide consistent error reporting for common failure scenarios related to handler registration in the Service Locator Pattern.
var ErrAuthorizationServerConflict = errors.New("another MCPServer describes this authorization server differently")
ErrAuthorizationServerConflict marks an MCPServer whose description of its authorization server is not the one pinned under its issuer key: an older MCPServer of its namespace describes the same issuer differently.
var ErrCredentialInDefinition = errors.New("an MCPServer definition holds no credential")
ErrCredentialInDefinition reports a credential written into an MCPServer definition, which everyone who can read the server can read.
var ErrIdentityOutsideNamespace = errors.New("an MCPServer outside muster's namespace gets no identity from muster")
ErrIdentityOutsideNamespace reports a server outside muster's namespace that asks muster for an identity: the person's token, muster's own signature, a family or an audience in the login.
var ErrNoMCPServerManager = errors.New("MCPServer manager not registered")
ErrNoMCPServerManager reports that no MCPServer manager is registered yet, so the set of required audiences is unknown rather than empty.
var ErrNotOrganizationPrincipal = errors.New("not an organization principal's token")
ErrNotOrganizationPrincipal is OrganizationPrincipalHandler.Authenticate's answer to a bearer that is no Dex client's own token: the request goes on to the authentication of people.
var ErrNotVisible = errors.New("the caller may not see the tool's server")
ErrNotVisible is in the chain of the error for a tool that exists but whose server the caller may not see.
var ErrOrganizationPrincipalConfiguration = errors.New("organization principal Dex configuration")
ErrOrganizationPrincipalConfiguration marks a Dex endpoint or address policy that prevents muster from verifying a principal until configuration changes.
ErrOrganizationPrincipalUnavailable marks a transient failure reaching Dex for discovery, signing keys or a token. The caller can retry.
var ErrPrincipalAudienceNotAllowed = errors.New("not in aggregator.oauth.server.principalAudiences")
ErrPrincipalAudienceNotAllowed is the class of a server whose spec.auth.principalAudience muster may not send to its URL (OrganizationPrincipalHandler.AudienceRefusal): muster obtains no token for it, connects to it for no one, and the server is Failed with the refusal.
var ErrSecretNotOwned = errors.New("the Secret is not owned by the MCPServer")
ErrSecretNotOwned reports a Secret with the name core_mcpserver_create generates for a server's client that the server does not own: muster reads such a Secret only with an ownerReference to the MCPServer's UID.
var ErrSecretOtherAuthorizationServer = errors.New("the Secret holds a client stored for another authorization server")
ErrSecretOtherAuthorizationServer reports a Secret with a generated client name that muster wrote for another authorization server than the one the MCPServer's spec now names: its issuer or an endpoint changed after the client was stored, so the client is not sent there.
var ErrSecretOutsideNamespace = errors.New("an MCPServer outside muster's namespace reads Secrets of its own namespace only")
ErrSecretOutsideNamespace reports a Secret reference of a server outside muster's namespace that names another namespace than the server's own.
var ErrSecretProtected = errors.New("muster never reads this Secret for an MCPServer")
ErrSecretProtected reports a Secret no MCPServer may read: one of muster's own (secretBinding.protectedSecrets), or one of a type that never holds a connector credential (Helm release, TLS, service-account token, ...).
var ErrSecretReferencePolicyInactive = errors.New("the MCPServer Secret reference policy is not in force")
ErrSecretReferencePolicyInactive reports that muster reads no Secret for an MCPServer: the admission policy that admits an MCPServer only when its writer may get the Secrets it names is not in force.
var ErrShadowedServer = errors.New("an MCPServer outside muster's namespace may not share its exposed names with a server in muster's namespace")
ErrShadowedServer reports a server outside muster's namespace whose exposed names a server in muster's namespace can take (ShadowingServer).
var ErrStdioNotAllowedInKubernetesMode = errors.New(
`type "stdio" is not supported in Kubernetes mode: a stdio server is started as a subprocess of the muster pod. ` +
`Run the MCP server as its own workload and register it with type "streamable-http" or "sse". ` +
`stdio stays available when muster runs as a local CLI (filesystem mode)`)
ErrStdioNotAllowedInKubernetesMode reports a "stdio" MCPServer submitted to a muster running in Kubernetes mode. A stdio server is started as a subprocess of the muster process, so accepting one in a deployed aggregator would turn "may write MCPServer resources" into "may execute code in the muster pod as muster's ServiceAccount" (issue #1067). The capability is removed rather than narrowed to a command allowlist: the pod image ships muster, not a fleet of MCP server binaries, and in-cluster servers are reached over HTTP.
Functions ¶
func AgentDisplayNameOfContext ¶ added in v5.67.0
AgentDisplayNameOfContext returns the bound agent's display name of a request, "" when it has none (or the agent itself is unknown).
func AgentOfContext ¶ added in v5.67.0
AgentOfContext returns the bound agent (<namespace>/<name>) of a request, "" when it carries none or only reporting settings.
func AgentReasonFromContext ¶ added in v5.67.0
AgentReasonFromContext returns the reason the caller gave with the call.
func ApplyTagsAnnotation ¶ added in v5.56.0
ApplyTagsAnnotation applies a write's tags to annotations and returns the result, allocating the map when needed. Replace semantics: nil keeps the annotation, an empty list removes it, and any other list replaces it, comma-joined in order. Callers validate tags first: a create with ValidateTags, an update through ApplyTagsUpdate.
func ApplyTagsUpdate ¶ added in v5.56.0
ApplyTagsUpdate checks an update's tags with ValidateTagsUpdate against the tags stored in annotations and applies them with ApplyTagsAnnotation. A refusal is an *InvalidTagsError; annotations are then returned unchanged.
func ApprovalBindingKey ¶ added in v5.67.0
func ApprovalBindingKey(identity SignInIdentity, sessionID, agent string, target ApprovalTarget, argumentsHash string) string
ApprovalBindingKey returns the binding key of a call.
func ApprovalPresets ¶ added in v5.67.0
func ApprovalPresets() []string
ApprovalPresets returns the preset names ExpandApprovalPreset accepts.
func ApprovalSchemaProblem ¶ added in v5.67.0
ApprovalSchemaProblem returns why approval settings cannot be trusted, "" when they can (or without a manager offering the check).
func AuditApproval ¶ added in v5.67.0
AuditApproval records one audit event of approval: a request, a decision, a use, a refusal (Block, governance, an unavailable prerequisite) or a change of a connector's settings. Every event names who acted in full -- the issuer and the raw subject, and the caller kind with its evidence -- and the governance mode; callers add the approval id, the target, the arguments' hash and, for a change, the settings old and new as structured values, so no free-form name can forge another field. The one helper keeps every approval event in the same shape.
func AuthoringWarnings ¶
AuthoringWarnings returns non-fatal authoring lint messages for a workflow. Each string is a complete, log-ready sentence describing the workflow itself (the caller prefixes it with the workflow name). It is the single source of truth shared by the structured create/validate path and the CRD reconciler so the same nudge is emitted regardless of how a workflow is authored. Returns an empty slice when there is nothing to warn about.
func AuthorizationServerDigest ¶ added in v5.60.0
func AuthorizationServerDigest(as *MCPServerAuthAuthorizationServer) string
AuthorizationServerDigest identifies where a client of an authorization server is sent: its issuer (and so the endpoints discovered from it) and its pinned authorization, token and revocation endpoints. "" for nil.
func CallerKind ¶ added in v5.67.0
CallerKind returns the kind of caller the request carries, with its evidence: an actor session, a delegated token, or else a person's bearer.
func CallerMeta ¶ added in v5.67.0
CallerMeta returns the request-scoped application metadata carried by ctx.
func CapAgentDisplayName ¶ added in v5.67.0
CapAgentDisplayName trims a display name and cuts it to MaxAgentDisplayName runes.
func ClearLoginIDToken ¶ added in v5.46.0
func ClearLoginIDToken(h OAuthHandler, sessionID, issuer string)
ClearLoginIDToken removes the session's login ID token through the handler's mirror, when it keeps one.
func ClearTokenByIssuerForUser ¶
func ClearTokenByIssuerForUser(h OAuthHandler, sessionID, userID, issuer string)
ClearTokenByIssuerForUser clears with the subject-scoped extension when the handler supports it and the user is known, and behaves like ClearTokenByIssuer otherwise.
func CollectRequiredAudiences ¶
CollectRequiredAudiences collects all unique required audiences from MCPServers that are sent the session's ID token: forwardToken: true, or forwardIdentity: true next to a pinned authorization server. This is used to determine which cross-client audiences to request from Dex during OAuth authentication.
When users authenticate to muster, the OAuth flow requests tokens with these audiences, allowing the tokens to be forwarded to downstream MCPServers that require specific audience claims (e.g., Kubernetes OIDC authentication).
An error means the set is unknown, which is not the same as no MCPServer needing an audience. A caller that mints a token from the result must not treat the two alike: the audience is fixed at the authorization request, and no refresh repairs a token minted without one.
Returns:
- []string: Unique list of required audiences from all SSO-enabled MCPServers
- error: ErrNoMCPServerManager before the manager registers, or the list error
Thread-safe: Yes, uses registered MCPServerManager which is thread-safe.
Example:
audiences, err := api.CollectRequiredAudiences(ctx) // Returns: ["dex-k8s-authenticator", "another-audience"]
func ContextWithToolApprovalHeader ¶ added in v5.67.0
ContextWithToolApprovalHeader applies a request's ToolApprovalHeader to ctx unless ctx already carries settings (a Session binding's). An empty value applies nothing; one that cannot be parsed makes every tool ask.
func CoreFloorTools ¶ added in v5.67.0
func CoreFloorTools() []string
CoreFloorTools returns muster's own floor tools.
func CoreSafeTools ¶ added in v5.67.0
func CoreSafeTools() []string
CoreSafeTools returns muster's own tools agents call unasked on Governed.
func DeprecatedFieldAliases ¶ added in v5.34.11
DeprecatedFieldAliases lists every deprecated snake_case field a structured workflow definition (the create/validate/update arguments) still uses, each qualified by its step and naming the replacement, so the caller can warn about them.
func ForgetSubjectGrant ¶ added in v5.57.0
func ForgetSubjectGrant(h OAuthHandler, userID, issuer string)
ForgetSubjectGrant drops the person's grant for the issuer when the handler supports it; a no-op otherwise.
func GetSessionIDFromContext ¶
GetSessionIDFromContext extracts the session ID from context. Returns the session ID if found, or empty string if not present.
func GetSubjectFromContext ¶
GetSubjectFromContext extracts the authenticated user's subject from context. Returns the subject if found, or empty string if not present.
func GovernanceRoles ¶ added in v5.67.0
func GovernanceRoles() []string
GovernanceRoles lists the built-in roles.
func InputSchemaFromArgs ¶
func InputSchemaFromArgs(args []ArgMetadata) mcp.ToolInputSchema
InputSchemaFromArgs converts a tool's argument metadata to the MCP input schema advertised for it. It is the one place the internal argument representation becomes JSON Schema, shared by every server that exposes a ToolProvider's tools over MCP: the aggregator for its meta-tools and core tools, and the local agent when it re-exposes the aggregator's meta-tools.
An argument with a detailed Schema keeps it (the Description overrides the schema's own when set); otherwise the schema is derived from Type. A Default is copied into the property and Required arguments are listed as such.
func IsActiveState ¶
func IsActiveState(state ServiceState) bool
IsActiveState returns true if the given state indicates the service is actively running and operational. This includes both StateRunning (for local stdio servers) and StateConnected (for remote servers).
Use this helper when checking if a service is available for use, rather than checking for StateRunning directly, to properly handle remote servers.
func IsActorSession ¶ added in v5.55.0
IsActorSession reports whether a muster session is an actor's: it holds copies of a person's login, never a login of its own.
func IsAgentCaller ¶ added in v5.67.0
IsAgentCaller reports whether the caller kind is an agent's.
func IsAuthRequiredError ¶
IsAuthRequiredError checks if an error wraps an auth-required error. This uses Go's structural typing via errors.As to match any error type that implements the AuthRequired() bool marker method, allowing the reconciler to detect auth-required states without importing mcpserver.
func IsDownState ¶
func IsDownState(state ServiceState) bool
IsDownState returns true if the given state means the service is not running and not on its way up — the states from which an explicit start request must actively start the service. Transitional states (starting, connecting, retrying), StateAuthRequired and StateAwaitingSession are not down: acting on them would interrupt an in-flight start or a reachable server that is connected per session.
func IsForwardedSession ¶ added in v5.55.0
IsForwardedSession reports whether a muster session was opened for a token a client forwarded, so muster holds no refresh token of its own for it.
func IsMusterCaller ¶ added in v5.67.0
IsMusterCaller reports whether ctx is marked by WithMusterCaller.
func IsNotFound ¶
IsNotFound checks if an error is a NotFoundError using error unwrapping. This function provides a type-safe way to check for not found conditions in error handling code, supporting wrapped errors.
Args:
- err: The error to check
Returns:
- bool: true if the error is or wraps a NotFoundError, false otherwise
Example:
if api.IsNotFound(err) {
return nil // the resource is gone, nothing to act on
}
func IsOrganizationPrincipalSession ¶ added in v5.67.0
IsOrganizationPrincipalSession reports whether sessionID is an organization principal's session.
func IsSignInRefused ¶ added in v5.60.0
IsSignInRefused reports whether err is muster's refusal of a server's sign-in, which no retry or login fixes until its spec or its Secret changes: its client Secret is refused (ErrSecretProtected, ErrSecretNotOwned, ErrSecretOtherAuthorizationServer), the Secret reference policy is not in force, or another MCPServer describes its authorization server differently (ErrAuthorizationServerConflict).
func IsTenantIssuerKey ¶ added in v5.47.0
IsTenantIssuerKey reports whether a key from IssuerKey belongs to a server outside muster's namespace.
func IsTenantMCPServerKey ¶ added in v5.47.0
IsTenantMCPServerKey reports whether a key names a server outside muster's namespace.
func IssuerKey ¶ added in v5.47.0
IssuerKey returns the key muster files a server's OAuth state under: the person's tokens and subject grants, the pin and its metadata, the client registration and the flow's state. A server in muster's namespace (empty namespace, see SplitMCPServerKey) keeps the plain issuer as its key, so nothing stored before changes. A server outside it gets "ns:<namespace>:<issuer>", so its sign-in shares nothing with muster's own servers or with another namespace that names the same issuer.
The plain issuer is used only where muster calls the network: IssuerURL.
A plain issuer that already reads as a key of another namespace is no issuer: a server of muster's namespace whose own metadata names "ns:org-a:https://..." gets "", so it can never reach org-a's sign-ins.
func IssuerSubjectScoped ¶
func IssuerSubjectScoped(h OAuthHandler, issuer string) bool
IssuerSubjectScoped reports whether the handler files grants from the issuer under the person. False for a handler without subject-scoped grants.
func IssuerURL ¶ added in v5.47.0
IssuerURL returns the plain issuer of a key from IssuerKey: the value muster discovers metadata at and compares an authorization response with.
func LoginSessionForIDToken ¶ added in v5.55.0
func LoginSessionForIDToken(h OAuthHandler, idToken string) string
LoginSessionForIDToken returns, through the handler's mirror, the session that filed idToken as its login ID token, or "".
func MCPServerEventKey ¶ added in v5.58.0
func MCPServerEventKey(event EventResult, musterNamespace string) (string, bool)
MCPServerEventKey returns the key of the MCPServer an event is about, and false for an event about anything else. An event without a namespace is about a server of musterNamespace.
func MCPServerExposedPrefix ¶ added in v5.47.0
MCPServerExposedPrefix returns the prefix of the exposed names of a server (without the muster prefix): its toolPrefix, or its name when it has none, and for a server outside muster's namespace its namespace in front of that, also when its name is unique. For example "org-a_github" for the server github in org-a, so its tool create_issue is x_org-a_github_create_issue.
func MCPServerKey ¶ added in v5.47.0
MCPServerKey returns the key muster registers, exposes and stores a server under. A server in muster's namespace, or one without a namespace, keeps its bare name (in filesystem mode every server does: the caller passes no namespace there), so no tool name, toolset, workflow, skill or stored sign-in changes. A server outside muster's namespace always carries its namespace: "<namespace>/<name>".
func MCPServerObject ¶ added in v5.47.0
MCPServerObject returns the namespace and the name of the MCPServer object a key names. musterNamespace is the namespace of a bare key.
func MCPToolAnnotation ¶ added in v5.50.0
func MCPToolAnnotation(a *ToolAnnotations) mcp.ToolAnnotation
MCPToolAnnotation projects a provider's declared annotations onto the MCP shape. Nil declares none: every hint stays unset.
func MergeRoleFloors ¶ added in v5.67.0
MergeRoleFloors returns the effective floor table: the built-in floors with the configured ones added, role by role. It is a union: nothing in the configuration removes or shrinks a built-in floor. A configured role that is not built in becomes a role a governed server may have.
func NewTokenExchangeCredentialsError ¶ added in v5.28.0
func NewTokenExchangeCredentialsError(ref *ClientCredentialsSecretRef, defaultNamespace string, err error) error
NewTokenExchangeCredentialsError wraps err as a credentials-loading failure for the Secret ref, resolved against defaultNamespace.
func NotVisible ¶ added in v5.67.0
NotVisible marks err as the error for a tool whose server the caller may not see. Its text stays err's; errors.Is(err, ErrNotVisible) holds.
func OutputEnabled ¶
OutputEnabled resolves the effective "include in returned result" flag for a step from its Output pointer and the deprecated Store alias. Output takes precedence when set; otherwise Store is used for backwards compatibility.
func ParseRequest ¶
ParseRequest converts a map[string]interface{} to a typed request struct. This uses JSON marshaling/unmarshaling for type conversion and validation, providing strict arg checking and type safety.
The function validates that no unknown args are present and performs basic type validation according to the target struct's field types and tags.
Args:
- args: The input arguments to parse and validate
- request: Pointer to the target request struct to populate
Returns:
- error: Validation error if arguments are invalid or contain unknown fields
Example:
var req WorkflowCreateRequest
args := map[string]interface{}{
"name": "deploy",
"steps": []interface{}{...},
}
err := ParseRequest(args, &req)
if err != nil {
return fmt.Errorf("invalid request: %w", err)
}
func ParseTags ¶ added in v5.56.0
ParseTags reads a TagsAnnotation value: it splits on commas, trims and lowercases each entry, and drops entries that are not valid tags and repeats. It does not enforce MaxTags. It never fails, so a malformed annotation set by hand does not break a read. It returns nil when no valid tag remains.
func PostLoginRedirectAllowed ¶ added in v5.67.0
PostLoginRedirectAllowed reports whether raw is an allowed return; false without an OAuth handler offering the check (no allowlist, no return).
func PresetSelects ¶ added in v5.67.0
func PresetSelects(ctx context.Context, preset string, t AgentTarget) bool
PresetSelects resolves a preset: entry; without a registered selector a preset selects nothing.
func PrincipalAudienceNotAllowed ¶ added in v5.67.0
PrincipalAudienceNotAllowed is the refusal of a server whose principalAudience muster may not send to serverURL.
func PrincipalAudienceRefusal ¶ added in v5.67.0
PrincipalAudienceRefusal returns why muster may not send an organization principal's token for audience to the MCP server at serverURL (OrganizationPrincipalHandler.AudienceRefusal). Without organization principals nothing is listed.
func PublishToolUpdateEvent ¶
func PublishToolUpdateEvent(event ToolUpdateEvent)
PublishToolUpdateEvent publishes a tool update event to all registered subscribers. This function is used to notify components about changes in tool availability, such as when MCP servers are registered/deregistered or their tools change.
The event is delivered asynchronously to all subscribers. Each subscriber receives the event in a separate goroutine to prevent blocking, ensuring that slow or failing subscribers don't affect other subscribers or the publisher.
Args:
- event: ToolUpdateEvent containing details about the tool update
Thread-safe: Yes, subscriber list is safely copied before notification.
Note: Each subscriber is notified in a separate goroutine to prevent blocking. Panics in subscriber callbacks are recovered and logged as errors.
Example:
event := api.ToolUpdateEvent{
Type: "server_registered",
ServerName: "kubernetes",
Tools: []string{"kubectl_get_pods", "kubectl_describe"},
Timestamp: time.Now(),
}
api.PublishToolUpdateEvent(event)
func RegisterAggregator ¶
func RegisterAggregator(h AggregatorHandler)
RegisterAggregator registers the aggregator handler implementation. This handler provides tool execution and MCP server aggregation functionality, serving as the central component for unified tool access across multiple MCP servers.
The registration is thread-safe and should be called during system initialization. Only one aggregator handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: AggregatorHandler implementation that manages tool execution and MCP server coordination
Thread-safe: Yes, protected by handlerMutex.
Example:
adapter := &aggregator.Adapter{aggregator: myAggregator}
api.RegisterAggregator(adapter)
func RegisterApprovalStore ¶ added in v5.67.0
func RegisterApprovalStore(s ApprovalStore)
RegisterApprovalStore registers the approval store; nil unregisters it. muster registers one only when its shared store is on Valkey.
func RegisterAuthHandler ¶
func RegisterAuthHandler(h AuthHandler)
RegisterAuthHandler registers the auth handler implementation. This handler provides OAuth authentication for CLI commands and agent clients.
The registration is thread-safe and should be called during system initialization. Only one auth handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: AuthHandler implementation that manages OAuth operations
Thread-safe: Yes, protected by handlerMutex.
Example:
adapter := cli.NewAuthAdapter() api.RegisterAuthHandler(adapter)
func RegisterBrowserIdentity ¶ added in v5.52.30
func RegisterBrowserIdentity(b BrowserIdentity)
RegisterBrowserIdentity registers the browser identity check.
func RegisterConfigHandler ¶
func RegisterConfigHandler(h ConfigHandler)
RegisterConfigHandler registers the configuration handler implementation. This handler provides runtime configuration management functionality, including configuration retrieval, updates, and persistence operations.
The registration is thread-safe and should be called during system initialization. Only one configuration handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: ConfigHandler implementation that manages configuration operations
Thread-safe: Yes, protected by handlerMutex.
Example:
adapter := &config.Adapter{manager: myConfigManager}
api.RegisterConfigHandler(adapter)
func RegisterDelegationExchange ¶ added in v5.58.0
func RegisterDelegationExchange(h DelegationExchange)
RegisterDelegationExchange registers the DelegationExchange implementation; nil unregisters it.
func RegisterEventManager ¶
func RegisterEventManager(h EventManagerHandler)
RegisterEventManager registers the event manager handler implementation. This handler provides Kubernetes Event generation functionality for CRD lifecycle operations, automatically adapting to both Kubernetes and filesystem modes through the unified client.
The registration is thread-safe and should be called during system initialization. Only one event manager handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: EventManagerHandler implementation that manages event generation operations
Thread-safe: Yes, protected by handlerMutex.
Example:
adapter := events.NewAdapter(musterClient) adapter.Register()
func RegisterGovernance ¶ added in v5.67.0
func RegisterGovernance(g Governance)
RegisterGovernance records the governance configuration muster started with. It is called once at start.
func RegisterHandoffRedeemer ¶ added in v5.67.0
func RegisterHandoffRedeemer(r HandoffRedeemer)
RegisterHandoffRedeemer registers the redeemer; nil unregisters it.
func RegisterMCPServerManager ¶
func RegisterMCPServerManager(h MCPServerManagerHandler)
RegisterMCPServerManager registers the MCP server manager handler implementation. This handler provides MCP server definition management and lifecycle operations, enabling the management of MCP servers that provide tools to the aggregator.
The registration is thread-safe and should be called during system initialization. Only one MCP server manager handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: MCPServerManagerHandler implementation that manages MCP server operations
Thread-safe: Yes, protected by handlerMutex.
Example:
adapter := mcpserver.NewAdapter(configPath) adapter.Register()
func RegisterMCPServerVisibility ¶ added in v5.47.0
func RegisterMCPServerVisibility(h MCPServerVisibilityHandler)
RegisterMCPServerVisibility registers the visibility handler; nil removes it.
func RegisterMetaTools ¶
func RegisterMetaTools(h MetaToolsHandler)
RegisterMetaTools registers the meta-tools handler implementation. This handler provides server-side meta-tool functionality for AI assistants, enabling tool discovery, execution, and resource/prompt access.
The registration is thread-safe and should be called during system initialization. Only one meta-tools handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: MetaToolsHandler implementation that manages meta-tool operations
Thread-safe: Yes, protected by handlerMutex.
Example:
adapter := metatools.NewAdapter() adapter.Register()
func RegisterMetaToolsDataProvider ¶
func RegisterMetaToolsDataProvider(p MetaToolsDataProvider)
RegisterMetaToolsDataProvider registers the data provider for meta-tools. This is typically the aggregator, which provides access to all tools, resources, and prompts from connected MCP servers.
The registration is thread-safe and should be called during system initialization after the aggregator is created but before the metatools adapter is wired up.
Args:
- p: MetaToolsDataProvider implementation (typically the aggregator)
Thread-safe: Yes, protected by handlerMutex.
func RegisterOAuthHandler ¶
func RegisterOAuthHandler(h OAuthHandler)
RegisterOAuthHandler registers the OAuth handler implementation. This handler provides OAuth proxy functionality for remote MCP server authentication.
The registration is thread-safe and should be called during system initialization. Only one OAuth handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: OAuthHandler implementation that manages OAuth operations
Thread-safe: Yes, protected by oauthMutex.
func RegisterOrganizationPrincipals ¶ added in v5.67.0
func RegisterOrganizationPrincipals(h OrganizationPrincipalHandler)
RegisterOrganizationPrincipals registers the organization principal handler; nil removes it. Without one muster accepts no organization principal.
func RegisterPresetSelector ¶ added in v5.67.0
func RegisterPresetSelector(s PresetSelector)
RegisterPresetSelector registers how preset: entries are resolved (the meta-tools adapter, which holds the presets).
func RegisterProcedureRunTools ¶ added in v5.67.0
func RegisterProcedureRunTools(p ToolProvider)
func RegisterReconcileManager ¶
func RegisterReconcileManager(h ReconcileManagerHandler)
RegisterReconcileManager registers the reconcile manager handler implementation. This handler provides reconciliation status and control functionality, enabling automatic synchronization of resource definitions with running services.
The registration is thread-safe and should be called during system initialization. Only one reconcile manager handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: ReconcileManagerHandler implementation that manages reconciliation operations
Thread-safe: Yes, protected by handlerMutex.
func RegisterSecretCredentialsHandler ¶
func RegisterSecretCredentialsHandler(h SecretCredentialsHandler)
RegisterSecretCredentialsHandler registers the secret credentials handler implementation. This handler loads OAuth client credentials from Kubernetes secrets.
The registration is thread-safe and should be called during system initialization. Only one handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: SecretCredentialsHandler implementation
Thread-safe: Yes, protected by secretCredentialsMutex.
func RegisterSensitiveToolArgs ¶ added in v5.60.0
func RegisterSensitiveToolArgs(tool string, args []ArgMetadata)
RegisterSensitiveToolArgs records which arguments of an exposed tool are sensitive. The aggregator registers the core tools as it exposes them.
func RegisterServerToolResolver ¶ added in v5.67.0
func RegisterServerToolResolver(r ServerToolResolver)
RegisterServerToolResolver registers the server tool resolver; nil unregisters it.
func RegisterServiceManager ¶
func RegisterServiceManager(h ServiceManagerHandler)
RegisterServiceManager registers the service manager handler implementation. This handler provides lifecycle management for the static services registered in the orchestrator's service registry.
The registration is thread-safe and should be called during system initialization. Only one service manager handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: ServiceManagerHandler implementation that manages service lifecycle operations
Thread-safe: Yes, protected by handlerMutex.
Example:
adapter := &services.ManagerAdapter{manager: myManager}
api.RegisterServiceManager(adapter)
func RegisterServiceRegistry ¶
func RegisterServiceRegistry(h ServiceRegistryHandler)
RegisterServiceRegistry registers the service registry handler implementation. This handler provides access to all registered services in the system.
The registration is thread-safe and should be called during system initialization. Only one service registry handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: ServiceRegistryHandler implementation that manages service discovery and information
Thread-safe: Yes, protected by handlerMutex.
Example:
adapter := &myservice.RegistryAdapter{registry: myRegistry}
api.RegisterServiceRegistry(adapter)
func RegisterSessionSubjectResolver ¶ added in v5.63.0
func RegisterSessionSubjectResolver(r SessionSubjectResolver)
RegisterSessionSubjectResolver registers the session subject resolver.
func RegisterToolsetGate ¶ added in v5.67.0
func RegisterToolsetGate(g ToolsetGate)
RegisterToolsetGate registers the toolset gate; nil removes it.
func RegisterWorkflow ¶
func RegisterWorkflow(h WorkflowHandler)
RegisterWorkflow registers the workflow handler implementation. This handler provides workflow definition management and execution functionality, allowing components to define and execute multi-step processes through the system.
The registration is thread-safe and should be called during system initialization. Only one workflow handler can be registered at a time; subsequent registrations will replace the previous handler.
Args:
- h: WorkflowHandler implementation that manages workflow operations
Thread-safe: Yes, protected by handlerMutex.
Example:
adapter := workflow.NewAdapter(toolCaller, toolChecker) adapter.Register()
func RelayedExtensions ¶ added in v5.67.0
RelayedExtensions keeps application extension declarations with valid identifiers and settings objects. MCP-owned extensions need their own routing behavior and are not advertised by this metadata relay.
func ReportMCPServerTokenExchange ¶ added in v5.28.0
ReportMCPServerTokenExchange tells the named MCPServer service how a per-user token exchange ended (err nil: it succeeded). Best-effort: a server the registry does not know, or whose service does not record outcomes, is skipped without error, as UpdateMCPServerState does.
func ReportingAsAgent ¶ added in v5.67.0
ReportingAsAgent reports whether a listing reports for an agent's settings passed to it (filter_tools agentTools): floors and governance are then reported as for an agent caller.
func ResolveRequestMeta ¶ added in v5.67.0
ResolveRequestMeta returns requestMeta, or meta when only the deprecated field is set. Setting both is refused rather than merged, so a definition never carries two sources for the same entry.
func SensitiveToolArgs ¶ added in v5.60.0
SensitiveToolArgs returns the sensitive arguments of an exposed tool.
func ServerIssuerKey ¶ added in v5.47.0
ServerIssuerKey is IssuerKey for a server key from MCPServerKey.
func ServerTools ¶ added in v5.67.0
ServerTools lists a server's own tools through the registered aggregator; false when it cannot.
func SetToolApproval ¶ added in v5.67.0
func SetToolApproval(tool *mcp.Tool, approval ToolApproval)
SetToolApproval records the effective approval on tool. The tool's _meta is cloned before it is written to: exposed tools share the Meta pointer of the tools the registry keeps.
func ShadowingServer ¶ added in v5.58.0
func ShadowingServer(namespace, musterNamespace string, servers []MCPServerInfo) (string, bool)
ShadowingServer returns the first, by name, of the servers of muster's namespace (or without a namespace) among servers whose exposed names can equal those of a server in namespace. Every exposed name of a server in namespace starts with "<namespace>_" (MCPServerExposedPrefix), and a namespace name holds no '_', so a server of muster's namespace can take one only when its exposed prefix (its toolPrefix, else its name) or its family name is namespace or starts with "<namespace>_". The server of muster's namespace wins: the caller refuses the servers of namespace, whatever the order in which the servers appear.
func SignInCheckRefusal ¶ added in v5.62.10
SignInCheckRefusal returns the registered check's refusal of a sign-in for the request's identity, nil when it can pass or no check is registered.
func SignInPrompt ¶ added in v5.67.0
SignInPrompt reports whether the request was marked by WithSignInPrompt.
func SplitIssuerKey ¶ added in v5.47.0
SplitIssuerKey returns the namespace and the plain issuer of a key from IssuerKey. The namespace is empty for a key of muster's namespace.
func SplitMCPServerKey ¶ added in v5.47.0
SplitMCPServerKey returns the namespace and the name of a key from MCPServerKey. The namespace is empty for a server of muster's namespace.
func StoreLoginIDToken ¶
func StoreLoginIDToken(h OAuthHandler, sessionID, userID, issuer, idToken string, expiresAt time.Time)
StoreLoginIDToken files the login ID token through the handler's mirror when it keeps one, and as the session's plain token for the issuer otherwise.
func SubscribeToToolUpdates ¶
func SubscribeToToolUpdates(subscriber ToolUpdateSubscriber)
SubscribeToToolUpdates allows components to subscribe to tool availability change events. Subscribers will receive notifications when tools are added, removed, or updated across MCP servers. This enables components to react to changes in the tool landscape in real-time.
The subscription is thread-safe and can be called from any goroutine. Subscriber callbacks are executed in separate goroutines to prevent blocking the event publishing mechanism.
Args:
- subscriber: ToolUpdateSubscriber that will receive tool update notifications
Thread-safe: Yes, protected by toolUpdateMutex.
Note: Subscriber callbacks are executed asynchronously and should not block. Panics in subscriber callbacks are recovered and logged as errors.
Example:
type MySubscriber struct{}
func (s *MySubscriber) OnToolsUpdated(event api.ToolUpdateEvent) {
fmt.Printf("Tools updated: %s\n", event.Type)
}
subscriber := &MySubscriber{}
api.SubscribeToToolUpdates(subscriber)
func ToolsetServers ¶ added in v5.58.0
ToolsetServers answers ToolsetServerScope through the registered meta-tools handler; without one no toolset narrows the request.
func ToolsetShows ¶ added in v5.58.0
ToolsetShows returns whether the toolsets bounding the request admit a server, and whether any toolset bounds it: every server for a request no toolset bounds, none when the toolset cannot be resolved.
func ToolsetShowsCore ¶ added in v5.58.0
ToolsetShowsCore reports whether the toolsets bounding the request show muster's own services: always for a request no toolset bounds, when they resolve at least one core tool otherwise, and never when the toolset cannot be resolved.
func UnregisterAuthHandler ¶
func UnregisterAuthHandler(h AuthHandler) bool
UnregisterAuthHandler clears the registration if and only if h is the currently registered handler, and reports whether it did.
The compare and the clear happen under one write lock. A plain GetAuthHandler-then-RegisterAuthHandler(nil) pair would be two separate acquisitions, letting a concurrent registration slip in between and be erased by a handler that is no longer current.
Args:
- h: the handler expected to be registered
Returns:
- bool: true if h was registered and the registration was cleared
Thread-safe: Yes, protected by handlerMutex.
func UpdateMCPServerState ¶
func UpdateMCPServerState(name string, state ServiceState, health HealthStatus, err error) error
UpdateMCPServerState updates the state of an MCPServer service. This is used when external events (such as SSO authentication success) need to update the service state. The function retrieves the service from the registry, checks if it implements StateUpdater, and updates its state.
This function is typically called by the aggregator when: - SSO token forwarding succeeds for a session - SSO token exchange succeeds for a session - the server's last authenticated session connection is lost
A state that actually changes reaches the CRD status through the service's state-change event and the reconciler's StateChangeBridge, like every other state change. Nothing else is triggered here: a session connecting to a server that is already Connected -- the common case, every session's SSO fan-out -- changes nothing and must cost no reconcile pass and no status write. Until issue #1290 this function queued a reconcile unconditionally, one pass and one status write per server per session start.
Args:
- name: The name of the MCPServer service to update
- state: The new service state (typically StateConnected for SSO success)
- health: The new health status (typically HealthHealthy for SSO success)
- err: Optional error to associate with the state (typically nil for success)
Returns:
- error: Error if the service doesn't exist, doesn't support state updates, or update fails
Thread-safe: Yes, operations are synchronized appropriately.
Example:
// Update MCPServer state after SSO token forwarding succeeds
if err := api.UpdateMCPServerState("gazelle-mcp-kubernetes", api.StateConnected, api.HealthHealthy, nil); err != nil {
logging.Warn("SSO", "Failed to update MCPServer state: %v", err)
}
func ValidateAuthorizationServer ¶ added in v5.27.0
func ValidateAuthorizationServer(auth *MCPServerAuth) error
ValidateAuthorizationServer checks the parts of spec.auth.authorizationServer the CRD's own rules express as CEL, for the paths that do not go through the API server (filesystem mode, core_mcpserver_validate): expectedIssuer makes sense only on a pin with explicit endpoints -- without them muster discovers the authorization server and compares against the issuer it publishes.
func ValidateForwardIdentity ¶ added in v5.31.0
func ValidateForwardIdentity(auth *MCPServerAuth) error
ValidateForwardIdentity reports whether spec.auth.forwardIdentity is usable with the rest of the auth configuration: it adds the session's ID token to the grant of a pinned authorization server, so it needs type "oauth" and an authorizationServer pin.
The CRD states the same rule in CEL, which only runs in Kubernetes mode. This is the definition filesystem mode and core_mcpserver_validate run; keep the two in step, as ValidateSigV4 does.
func ValidateGrantScope ¶ added in v5.57.0
func ValidateGrantScope(auth *MCPServerAuth) error
ValidateGrantScope checks spec.auth.grantScope as the CRD's CEL rules do, for the paths that do not go through the API server (filesystem mode, core_mcpserver_validate): one of "session" and "subject"; "subject" only with auth type oauth and never next to forwardToken or tokenExchange (which obtain no grant of their own; "session", the default, is accepted on any server); and not disagreeing with spec.auth.authorizationServer.grantScope.
func ValidateHeadersFrom ¶ added in v5.41.0
func ValidateHeadersFrom(serverType string, headersFrom []MCPServerHeaderFrom) error
ValidateHeadersFrom reports a spec.headersFrom that the CRD schema would refuse: an entry on a stdio server, an entry without a header name, a Secret name or key, or with a type other than Secret, or two entries whose header names differ only in case.
func ValidateLoopsPagingAndJQ ¶ added in v5.50.0
ValidateLoopsPagingAndJQ checks the options a fleet-wide scan is built from, in every step of the workflow: a forEach nests one level and only inside a top-level forEach body, a nested loop's variable does not shadow the outer one, its body's ids do not collide with the outer body's, parallelism and paginate.maxPages are within bounds, paginate is set on tool steps only, and every jq program compiles (checkJQ reports why one does not). It is shared by the structured create/validate path and the CRD reconciler, so a definition is held to the same rules however it is authored.
func ValidateNoInlineCredential ¶ added in v5.41.0
func ValidateNoInlineCredential(serverType, rawURL string, headers, env map[string]string, kubernetesMode bool) error
ValidateNoInlineCredential reports a credential written into a server's definition: env on a remote server (env reaches only a stdio process) in every mode, and in Kubernetes mode a value in an Authorization, Proxy-Authorization, Cookie or X-API-Key header (in any case) or a user name or password in the URL. In Kubernetes mode everyone who can read the MCPServer can read the definition, so a credential belongs in a Secret that spec.headersFrom refers to. Filesystem mode has no Secret reader, and its definition is a file of the person who runs muster, so it keeps its headers.
The CRD states the same rules in CEL, which only runs at admission. This is the check the reconciler and core_mcpserver_* run where muster loads a server; keep the two in step.
func ValidateNotShadowed ¶ added in v5.58.0
func ValidateNotShadowed(ctx context.Context, namespace, musterNamespace string, list func(context.Context) ([]MCPServerInfo, error)) error
ValidateNotShadowed refuses a server of namespace when a server of muster's namespace among the served ones (list) can take its exposed names (ShadowingServer). It answers nil for a server of muster's namespace.
func ValidatePrincipalAudience ¶ added in v5.67.0
func ValidatePrincipalAudience(serverType string, auth *MCPServerAuth) error
ValidatePrincipalAudience reports whether spec.auth.principalAudience is usable with the rest of the server's configuration. The server is reached over streamable-http with the principal's token in Authorization, so it takes no person's sign-in, token or grants (type none, and no forwardToken, forwardIdentity, tokenExchange, authorizationServer, providerApps or requiredAudiences), and no muster signature (sigv4). The audience is one Dex client ID, as the scope audience:server:client_id:<audience> takes it: letters, digits, '-' and '_'.
The CRD states the same rules in CEL; keep the two in step.
func ValidateProgress ¶ added in v5.40.0
func ValidateProgress(timeout int, progress *MCPServerProgress) error
ValidateProgress reports whether spec.progress is usable with spec.timeout: progress.maxDuration unset, or between the timeout and DefaultProgressMaxDurationSeconds.
The CRD states the same rule in CEL, which only runs in Kubernetes mode.
func ValidateProviderApps ¶ added in v5.48.0
func ValidateProviderApps(auth *MCPServerAuth) error
ValidateProviderApps reports whether spec.auth.providerApps is usable with the rest of the auth configuration: the App tokens ride on a connection made as the person, so it needs forwardToken or forwardIdentity.
The CRD states the same rule in CEL; keep the two in step.
func ValidateRequestMeta ¶ added in v5.67.0
func ValidateRequestMeta(serverType string, auth *MCPServerAuth, requestMeta map[string]string) error
ValidateRequestMeta reports whether requestMeta is usable with the given server type and auth.
The entries are added by an HTTP round tripper, so a stdio server would accept the map and drop it. A dropped or missing entry fails nowhere: the AWS-hosted backend falls back to us-east-1 and answers about the wrong region. That silence is why both cases are refused here rather than left to the connect attempt.
The CRD states the same rules in CEL, which only runs in Kubernetes mode. Keep the two in step, as ValidateSigV4 and ValidateStdioAllowed do.
func ValidateResourceName ¶
ValidateResourceName rejects entity names that are unsafe to use as a file path segment or as a field in a line-oriented log.
The name comes straight from a caller-controlled tool argument. In filesystem mode it is joined into a file path, and filepath.Join collapses ".." segments, so without this a name like "../../evil" or "/etc/x" writes and reads arbitrary *.yaml files outside the config directory. Control characters are rejected for the same reason a separator is: a newline in a name forges an extra record in the legacy events.log, which parseLegacyEventLine then returns as a genuine-looking event.
The name must therefore be a single path segment made of printable runes: no path separators, no control characters, and not a "." / ".." reference. Character policy beyond that (e.g. DNS-1123) is intentionally left to the higher layers and to Kubernetes admission; filesystem mode accepts names such as "special-chars-workflow_123" that Kubernetes would reject.
func ValidateSecretNamespaces ¶ added in v5.41.0
func ValidateSecretNamespaces(serverNamespace, musterNamespace string, auth *MCPServerAuth) error
ValidateSecretNamespaces reports a Secret reference that would make muster read a Secret outside the namespace of a server that is not in muster's own namespace: the clientCredentialsSecretRef of auth.tokenExchange or of an auth.authorizationServer pin. Such a server could otherwise have a Secret of muster's namespace sent to a host it names. A server in muster's namespace, or one without a namespace (filesystem mode), keeps today's references. spec.headersFrom has no namespace field, so it always reads the server's own.
func ValidateServerNamespace ¶ added in v5.47.0
func ValidateServerNamespace(namespace, musterNamespace string, family *MCPServerFamily, auth *MCPServerAuth) error
ValidateServerNamespace reports a server that its namespace does not allow. Outside muster's namespace a server gets no identity from muster: requiredAudiences, forwardToken, forwardIdentity, tokenExchange, family and auth.type sigv4 are refused, so it adds no audience to any login, receives no person's token except through its own sign-in, signs nothing as muster and joins no family. principalAudience is allowed: it sends the server the token of its namespace's own organization principal, never a person's or muster's.
func ValidateSigV4 ¶
func ValidateSigV4(serverType string, auth *MCPServerAuth) error
ValidateSigV4 reports whether an auth configuration that selects SigV4 is usable with the given server type, and returns nil for every other auth type.
The CRD states the same rules in CEL, but CEL only runs in Kubernetes mode. This function is the definition that also holds in filesystem mode, so admission and client construction share it instead of restating it — the same arrangement ValidateStdioAllowed uses. Keep the two in step: a rule that lives only in CEL is a rule a filesystem-mode muster does not enforce.
func ValidateStdioAllowed ¶
ValidateStdioAllowed reports whether a server type may run in the current mode, returning ErrStdioNotAllowedInKubernetesMode for stdio in Kubernetes mode and nil otherwise.
Callers pass the mode they already hold — client.IsKubernetesMode() for the tool handlers and reconciler, the flag plumbed down from it for the orchestrator and the service — so admission, reconciliation, and process start share one definition of the policy instead of three.
func ValidateTags ¶ added in v5.56.0
ValidateTags checks tags as a create receives them: each matches ^[a-z0-9]+(-[a-z0-9]+)*$, is at most MaxTagLength characters, and appears once, and there are at most MaxTags of them. It does not normalise; the caller sends tags in their stored form.
func ValidateTagsUpdate ¶ added in v5.56.0
ValidateTagsUpdate checks the tags an update sends against the resource's stored ones (ParseTags of its annotation): as ValidateTags, except that more than MaxTags pass when none of them is new. A list set past the limit by hand or GitOps can be sent back unchanged or shortened; only adding to it is refused, as in the developer portal.
func WithAgentApproval ¶ added in v5.67.0
func WithAgentApproval(ctx context.Context, a *AgentApproval) context.Context
WithAgentApproval returns ctx carrying an agent's approval settings.
func WithAgentReason ¶ added in v5.67.0
WithAgentReason returns ctx carrying the reason the caller gave with a call (call_tool's reason argument).
func WithCallerMeta ¶ added in v5.67.0
WithCallerMeta carries the current tool call's application metadata. Values are opaque and are never used as credentials.
func WithDelegatedCaller ¶ added in v5.58.0
func WithDelegatedCaller(ctx context.Context, caller DelegatedCaller) context.Context
WithDelegatedCaller returns a context marking the request as a delegated caller's.
func WithMusterCaller ¶ added in v5.67.0
WithMusterCaller marks ctx as muster calling as itself: the durable-run controller's calls in muster's own namespace. Such a call carries no ID token. CallerVisibility resolves it to the servers of muster's own namespace and no other, so muster's own work never reaches another namespace's servers.
func WithOrganizationPrincipal ¶ added in v5.67.0
func WithOrganizationPrincipal(ctx context.Context, p OrganizationPrincipal) context.Context
WithOrganizationPrincipal returns a context marking the request as the principal's.
func WithSessionID ¶
WithSessionID returns a new context with the session ID set.
func WithSessionToolMemo ¶
WithSessionToolMemo returns a context carrying an empty SessionToolMemo. It is idempotent: if the context already carries a memo, the same context is returned unchanged so nested scopes share one cache.
func WithSignInIdentity ¶ added in v5.52.30
func WithSignInIdentity(ctx context.Context, identity SignInIdentity) context.Context
WithSignInIdentity returns a context carrying the request's sign-in identity.
func WithSignInPrompt ¶ added in v5.67.0
WithSignInPrompt returns a context marking the request as one whose client shows a sign-in link to the person directly: the client declared URL mode elicitation and the caller is an agent acting for the person. muster then answers an agent's search for the tools of a server awaiting the person's sign-in with that sign-in, as it answers a call of such a tool, instead of leaving the agent to tell the person to sign in somewhere.
func WithSubject ¶
WithSubject returns a new context with the authenticated user's subject set.
func WithoutReportingApproval ¶ added in v5.67.0
WithoutReportingApproval returns ctx without settings that were passed for reporting only, so they never decide a call.
func WorkflowNameOf ¶ added in v5.67.0
WorkflowNameOf returns the workflow an exposed name runs (workflow_X, core_workflow_X), "" for any other name.
func WorkflowStepTools ¶
WorkflowStepTools returns, in discovery order and deduplicated, every tool name a workflow's steps reference: top-level step tools, condition tools, the tools of forEach and parallel sub-steps (a nested forEach's included), and onFailure handler tools. Nested workflow_<name> steps are returned as such; callers that need transitive resolution descend into them.
Types ¶
type AgentApproval ¶ added in v5.67.0
type AgentApproval struct {
// Agent is the agent, <namespace>/<name>, where known.
Agent string `json:"agent,omitempty"`
// AgentDisplayName is the name people know the agent by, where its
// sender bound one (at most MaxAgentDisplayName runes); "" falls back to
// Agent. Never taken from the agent's own requests.
AgentDisplayName string `json:"agentDisplayName,omitempty"`
Entries []AgentApprovalEntry `json:"entries,omitempty"`
Default string `json:"default,omitempty"`
Grants []AgentApprovalGrant `json:"grants,omitempty"`
// Reporting marks settings passed to a listing to report what an
// agent would see; they never decide a call.
Reporting bool `json:"-"`
}
AgentApproval is an agent's approval settings as one request sees them.
func AgentApprovalFromContext ¶ added in v5.67.0
func AgentApprovalFromContext(ctx context.Context) *AgentApproval
AgentApprovalFromContext returns the agent's approval settings the request carries, nil without.
func ParseToolApprovalHeader ¶ added in v5.67.0
func ParseToolApprovalHeader(value string) (*AgentApproval, error)
ParseToolApprovalHeader parses a ToolApprovalHeader value. A value that cannot be parsed is an error; the caller then applies a default Ask (fail closed).
func (*AgentApproval) Decide ¶ added in v5.67.0
func (a *AgentApproval) Decide(ctx context.Context, t AgentTarget) (setting, entry string)
Decide returns the agent setting for the target and the entry that decided it: the most specific entry selecting it (tool: over workflow: over server: over preset:), the strictest of equally specific ones, else the default. Both are empty when nothing applies.
func (*AgentApproval) Granted ¶ added in v5.67.0
func (a *AgentApproval) Granted(entry, server, uid, original string) (AgentApprovalGrant, bool)
Granted returns the grant that lifts the entry's Allow for the server's own tool original on the server with the given UID, if any: a grant names the tools it covers, so one without tools lifts nothing.
func (*AgentApproval) Validate ¶ added in v5.67.0
func (a *AgentApproval) Validate() error
Validate checks the settings' shape: selectors in the toolset grammar, each once, values Allow, Ask or Block, grants naming an Allow entry (or an allowing default) and a server.
type AgentApprovalEntry ¶ added in v5.67.0
AgentApprovalEntry is one entry of an agent's tool list with its setting.
type AgentApprovalGrant ¶ added in v5.67.0
type AgentApprovalGrant struct {
Entry string `json:"entry"`
Server string `json:"server"`
UID string `json:"uid"`
Tools []string `json:"tools,omitempty"`
}
AgentApprovalGrant marks an entry's Allow as granted on one connector: the MCPServer's server key and its UID (a recreated server has another), for the tools (the server's own names) it covered when the connector admin granted it. A tool that starts asking later is not covered: its admin never saw it lifted.
func (AgentApprovalGrant) Key ¶ added in v5.67.0
func (g AgentApprovalGrant) Key() string
Key identifies a grant mark with what it covers: entry, server, UID and the tools, in any order.
type AgentTarget ¶ added in v5.67.0
type AgentTarget struct {
// Kind is "tool", "workflow" or "core".
Kind string
// Server is the member server's key; Family the family's name, if any.
Server, Family string
// Original is the server's own name of the tool.
Original string
// Exposed is the tool's exposed name (x_..., core_..., workflow_...).
Exposed string
// Aliases are other names the tool is exposed or was called under (a
// family member's per-server name, the name the call used); a tool:
// entry naming any of them selects the tool.
Aliases []string
// Workflow is the workflow's name.
Workflow string
// Tool is the exposed tool, for preset rules; nil when unknown.
Tool *mcp.Tool
// ResolveTool maps an exposed name to the server and the server's own
// name, so a tool: entry selects the dispatch target whatever alias it
// names. nil compares names only.
ResolveTool func(name string) (server, original string, ok bool)
}
AgentTarget is what an agent entry is matched against: a server's tool (one member of a family), a workflow, or a core tool.
type AggregatorHandler ¶
type AggregatorHandler interface {
// GetServiceData returns runtime data and configuration information about the aggregator service.
// This includes connection details, registered servers, and operational metrics.
//
// Returns:
// - map[string]interface{}: Service-specific data and metadata
GetServiceData() map[string]interface{}
// GetEndpoint returns the network endpoint where the aggregator is accessible.
// This is typically used for client connections and service discovery.
//
// Returns:
// - string: The network endpoint (e.g., "localhost" or IP address)
GetEndpoint() string
// GetPort returns the network port where the aggregator is listening.
// This is used in conjunction with GetEndpoint for complete connection information.
//
// Returns:
// - int: The port number where the aggregator service is accessible
GetPort() int
// CallTool executes a tool through the aggregator and returns a structured result.
// This method provides the primary interface for external tool execution with
// result formatting suitable for API responses.
//
// Args:
// - ctx: Context for request cancellation and timeout control
// - toolName: The name of the tool to execute
// - args: Arguments to pass to the tool as key-value pairs
//
// Returns:
// - *CallToolResult: Structured result containing tool output and metadata
// - error: nil on success, or an error if the tool call fails
CallTool(ctx context.Context, toolName string, args map[string]interface{}) (*CallToolResult, error)
// CallToolInternal executes a tool and returns the raw MCP result.
// This method is used internally by workflow and other subsystems that need
// direct access to the underlying MCP tool result format.
//
// Args:
// - ctx: Context for request cancellation and timeout control
// - toolName: The name of the tool to execute
// - args: Arguments to pass to the tool as key-value pairs
//
// Returns:
// - *mcp.CallToolResult: Raw MCP tool result
// - error: nil on success, or an error if the tool call fails
CallToolInternal(ctx context.Context, toolName string, args map[string]interface{}) (*mcp.CallToolResult, error)
// IsToolAvailable checks whether a specific tool is currently available for execution.
// This is used for validation before attempting tool calls.
//
// Args:
// - toolName: The name of the tool to check
//
// Returns:
// - bool: true if the tool is available, false otherwise
IsToolAvailable(toolName string) bool
// MissingToolsForSession returns, from toolNames, the subset that is not
// available for the calling session. Unlike IsToolAvailable, it resolves
// SSO / auth-protected family tools against the session's accessible tool
// set (the per-subject capabilities in the CapabilityStore), so availability
// does not depend on whether the session called list_tools first. The
// session tool set is resolved once, so checking many tools is cheap.
//
// Args:
// - ctx: Context carrying the session identity
// - toolNames: The names of the tools to check
//
// Returns:
// - []string: The deduplicated, input-ordered tool names that are unavailable
MissingToolsForSession(ctx context.Context, toolNames []string) []string
// GetAvailableTools returns a list of all currently available tool names.
// This is used for tool discovery and validation.
//
// Returns:
// - []string: Slice of available tool names (empty if no tools available)
GetAvailableTools() []string
// ServerHasTools reports whether the server registered under name (its
// key, see MCPServerKey) lists at least one tool in the registry. It
// decides on the registry entry, not on a tool name, so it holds whatever
// prefix the server's tools are exposed under. A server that waits for a
// sign-in lists none.
ServerHasTools(name string) bool
// UpdateCapabilities triggers a refresh of the aggregator's capability information.
// This should be called when MCP servers are added, removed, or their tools change.
UpdateCapabilities()
// RegisterServerPendingAuth registers a server that requires OAuth
// authentication before its tools can be exposed. Per ADR-008, no
// synthetic authentication tools are created — users authenticate via
// core_auth_login.
//
// AuthConfig within registration may be nil; in either case the server
// is flagged as requiring per-session authentication.
RegisterServerPendingAuth(registration PendingAuthRegistration) error
// DeregisterServer removes a server from the aggregator, along with its
// cached capabilities, per-session auth state and pooled connections.
//
// Deregistration is otherwise driven by service state-change events, which
// deliberately leave servers in auth_required state registered so a server
// waiting for OAuth keeps its pending-auth entry. Removing the service
// itself therefore has to say so explicitly.
//
// Returns an error if the server is not registered.
DeregisterServer(name string) error
}
AggregatorHandler provides aggregator-specific functionality for managing MCP server tools It acts as the central coordinator for tool availability, execution, and tool management across all registered MCP servers.
func GetAggregator ¶
func GetAggregator() AggregatorHandler
GetAggregator returns the registered aggregator handler. This provides access to tool execution and MCP server aggregation functionality.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- AggregatorHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
Example:
aggregator := api.GetAggregator()
if aggregator == nil {
return fmt.Errorf("aggregator not available")
}
result, err := aggregator.CallTool(ctx, "my-tool", args)
type ApprovalArgument ¶ added in v5.67.0
type ApprovalArgument struct {
Key string `json:"key"`
Label string `json:"label"`
// Value is the value in canonical JSON (a string quoted).
Value string `json:"value"`
// Type is the value's JSON type (string, number, boolean, null, object,
// array), shown beside it; empty for values that are not arguments.
Type string `json:"type,omitempty"`
}
ApprovalArgument is one labelled value shown on the approval page.
type ApprovalChange ¶ added in v5.67.0
type ApprovalChange struct {
Field string `json:"field"`
Old string `json:"old"`
New string `json:"new"`
}
ApprovalChange is one field an edit changes, old to new.
type ApprovalDisplay ¶ added in v5.67.0
type ApprovalDisplay struct {
// Message is the plain-words summary the elicitation carries.
Message string `json:"message"`
// Title is the tool's MCP title, or its name made readable.
Title string `json:"title"`
// Connector names the server, its display name when it has one.
Connector string `json:"connector,omitempty"`
// ChangesData is true for a tool not annotated read-only.
ChangesData bool `json:"changesData,omitempty"`
// Arguments are the call's canonical arguments, labelled.
Arguments []ApprovalArgument `json:"arguments,omitempty"`
// Changes are the fields an edit changes, when muster could read the
// current object; empty when it could not (the arguments are shown).
Changes []ApprovalChange `json:"changes,omitempty"`
// Preset lists the per-tool settings a preset expands to.
Preset []ApprovalArgument `json:"preset,omitempty"`
// Steps are a workflow's steps, the asking ones marked.
Steps []ApprovalStep `json:"steps,omitempty"`
// Setting and Source say why the call asks.
Setting string `json:"setting"`
Source string `json:"source"`
// AgentSays is the reason an agent caller gave with the call
// (call_tool's reason); shown, never bound or used to decide.
AgentSays string `json:"agentSays,omitempty"`
}
ApprovalDisplay is what the approval page shows, worked out by muster from the target's own definition when the request is created: never words an agent chose.
type ApprovalLimitError ¶ added in v5.67.0
type ApprovalLimitError struct {
// Scope is ApprovalLimitPerson or ApprovalLimitSession.
Scope string
// Limit is the cap's size.
Limit int
}
ApprovalLimitError is a request refused by a cap; it matches ErrApprovalLimit.
func (*ApprovalLimitError) Error ¶ added in v5.67.0
func (e *ApprovalLimitError) Error() string
func (*ApprovalLimitError) Is ¶ added in v5.67.0
func (e *ApprovalLimitError) Is(target error) bool
Is makes an ApprovalLimitError match ErrApprovalLimit.
type ApprovalPageFlow ¶ added in v5.67.0
type ApprovalPageFlow struct {
// State is the OAuth state of the identity sign-in in flight: the
// callback's state must equal it. It correlates the callback with this
// browser's flow only; it is not the OIDC nonce claim, which the identity
// provider's ID token carries.
// The JSON name stays "nonce" so flows in flight survive a rollout.
State string `json:"nonce"`
// Identity is who signed in in this browser, once the sign-in returned.
Identity SignInIdentity `json:"identity"`
// Token is the anti-forgery token the decision form carries.
Token string `json:"token"`
// Redirect is the allowlisted return the client asked for, used only
// after a decision.
Redirect string `json:"redirect,omitempty"`
}
ApprovalPageFlow is the approval page's state for one browser and one request: the sign-in that tells muster who is in the browser, the anti-forgery token of the decision form and the return the person's client asked for. It is kept per browser, never on the request, so one person's return cannot be swapped for another's.
type ApprovalRequest ¶ added in v5.67.0
type ApprovalRequest struct {
// ID is the random, unguessable id in the approval page's URL.
ID string `json:"id"`
// ElicitationID is the elicitation's own random id, distinct from ID, the
// one the page's return carries.
ElicitationID string `json:"elicitationId"`
// Identity is the person the call was made for (issuer and raw sub):
// only a browser signed in as them may decide.
Identity SignInIdentity `json:"identity"`
// SessionID is the muster session the call came from (an actor's
// session for a Session sandbox).
SessionID string `json:"sessionId"`
// RequesterName is the person's name or email from their token, shown
// to another person who opens the link; empty when the token has none.
RequesterName string `json:"requesterName,omitempty"`
// Agent names the calling agent where muster knows it.
Agent string `json:"agent,omitempty"`
// AgentDisplayName is the agent's display name from its sender-bound
// binding, "" when it has none. Not part of the binding key.
AgentDisplayName string `json:"agentDisplayName,omitempty"`
// CallerKind is the caller's kind and its evidence.
CallerKind string `json:"callerKind"`
Target ApprovalTarget `json:"target"`
// Arguments are the RFC 8785 canonical form of the arguments muster
// dispatches; ArgumentsHash is their SHA-256.
Arguments string `json:"arguments"`
ArgumentsHash string `json:"argumentsHash"`
Display ApprovalDisplay `json:"display"`
CreatedAt time.Time `json:"createdAt"`
ExpiresAt time.Time `json:"expiresAt"`
// Status, DecidedBy and DecidedAt are filled when the store reports the
// decision; they are not stored with the request.
Status string `json:"-"`
DecidedBy SignInIdentity `json:"-"`
}
ApprovalRequest is a pending approval: bound to the person and Session the call came from, the resolved target and the canonical arguments, single use and expiring.
func (*ApprovalRequest) BindingKey ¶ added in v5.67.0
func (r *ApprovalRequest) BindingKey() string
BindingKey is the hash of everything the approval is bound to: identity, Session and agent, target and canonical arguments. A retry runs only an approval with the same key.
type ApprovalStep ¶ added in v5.67.0
type ApprovalStep struct {
ID string `json:"id"`
Label string `json:"label"`
Tool string `json:"tool"`
Asks bool `json:"asks,omitempty"`
// Workflow names the nested workflow the step belongs to, empty for a
// step of the workflow being approved.
Workflow string `json:"workflow,omitempty"`
// Arguments are the step's arguments as the definition builds them
// (templates shown as written).
Arguments []ApprovalArgument `json:"arguments,omitempty"`
}
ApprovalStep is one step of a workflow on the approval page.
type ApprovalStore ¶ added in v5.67.0
type ApprovalStore interface {
// Create stores a pending request, unless one with the same binding is
// still pending or decided, which is returned instead (an identical call
// reuses its link). It refuses with ErrApprovalLimit beyond the caps.
Create(ctx context.Context, request *ApprovalRequest) (*ApprovalRequest, error)
// Find returns the request bound to bindingKey with its status, without
// consuming it; ErrApprovalNotFound when there is none.
Find(ctx context.Context, bindingKey string) (*ApprovalRequest, error)
// Consume atomically takes the decision of the request bound to
// bindingKey and removes the request: of concurrent retries exactly one
// gets it. A request not decided yet is returned pending and kept;
// ErrApprovalNotFound when there is none.
Consume(ctx context.Context, bindingKey string) (*ApprovalRequest, error)
// Get returns the request by its id with its status.
Get(ctx context.Context, id string) (*ApprovalRequest, error)
// Decide records the decision on a pending request, once.
Decide(ctx context.Context, id string, approve bool, by SignInIdentity) error
// Ping reports whether the store can be reached now.
Ping(ctx context.Context) error
// PutFlow, GetFlow and DeleteFlow keep the page's browser flows.
PutFlow(ctx context.Context, key string, flow ApprovalPageFlow, ttl time.Duration) error
GetFlow(ctx context.Context, key string) (*ApprovalPageFlow, error)
DeleteFlow(ctx context.Context, key string) error
// PutHandoff keeps a sign-in handoff by the digest of its ticket, never
// the ticket itself. TakeHandoff returns it and removes it in one step,
// so of concurrent redemptions exactly one gets it; ErrApprovalNotFound
// when there is none (unknown, expired or used).
PutHandoff(ctx context.Context, key string, handoff SignInHandoff, ttl time.Duration) error
TakeHandoff(ctx context.Context, key string) (*SignInHandoff, error)
}
ApprovalStore keeps approval requests, their decisions and the page's browser flows. Implementations shared by replicas (Valkey) make an approval decided on one replica usable on another; every operation fails rather than guesses when the store is unavailable.
func GetApprovalStore ¶ added in v5.67.0
func GetApprovalStore() ApprovalStore
GetApprovalStore returns the registered approval store, nil without one.
type ApprovalTarget ¶ added in v5.67.0
type ApprovalTarget struct {
Kind string `json:"kind"`
// Server is the server key of the owning MCPServer (a family call: the
// selected member); empty for core tools and workflows.
Server string `json:"server,omitempty"`
// UID and Generation identify the MCPServer or workflow object, so a
// replaced or changed definition no longer matches; empty and zero in
// filesystem mode.
UID string `json:"uid,omitempty"`
Generation int64 `json:"generation,omitempty"`
// Name is the server's own tool name, the core tool's name, or the
// workflow's name.
Name string `json:"name"`
// Exposed is the name the tool is exposed under, for display only; it is
// not part of the binding.
Exposed string `json:"exposed,omitempty"`
// Definition is the hash of a workflow's definition (inputs, steps,
// cleanup steps): a changed definition is a different target.
Definition string `json:"definition,omitempty"`
}
ApprovalTarget is what a call dispatches to, never the name the client sent: the owning MCPServer and its own tool name, one of muster's core tools, or a workflow and its definition.
type Arg ¶
type Arg struct {
// Type specifies the expected data type (string, number, boolean, object, array)
Type string `yaml:"type" json:"type"`
// Required indicates whether this argument must be provided
Required bool `yaml:"required" json:"required"`
// Description provides human-readable documentation for the argument
Description string `yaml:"description" json:"description"`
// Default specifies the default value used when the argument is not provided.
// Only applicable when Required is false.
Default interface{} `yaml:"default,omitempty" json:"default,omitempty"`
}
Arg defines an argument for operations and workflows. This provides a standardized way to define input validation and documentation for both workflow inputs and operation arguments.
type ArgDefinition ¶
type ArgDefinition struct {
// Type specifies the expected data type for this arg.
// Valid types are "string", "integer", "boolean", and "number".
Type string `yaml:"type" json:"type"`
// Required indicates whether this arg must be provided by the caller.
Required bool `yaml:"required" json:"required"`
// Default provides a default value to use if the arg is not provided.
// The default value must match the specified Type.
Default any `yaml:"default,omitempty" json:"default,omitempty"`
// Description provides human-readable documentation for this arg.
Description string `yaml:"description,omitempty" json:"description,omitempty"`
}
ArgDefinition defines validation rules and metadata for a single tool/workflow argument. It specifies the expected type, whether the argument is required, an optional default value, and a human-readable description used for documentation and schema generation.
type ArgMetadata ¶
type ArgMetadata struct {
// Name is the argument identifier used in tool calls
Name string
// Type specifies the expected argument type for validation.
Type ArgType
// Required indicates whether this argument must be provided in tool calls
Required bool
// Description provides human-readable documentation for this argument,
// explaining its purpose and expected format
Description string
// Default specifies the default value used when the argument is not provided.
// Only used when Required is false. Must match the specified Type.
Default any
// Schema provides detailed JSON Schema definition for complex types.
// When specified, this takes precedence over the basic Type field for
// generating detailed MCP schemas. This is particularly useful for:
// - Object types that need property definitions and validation rules
// - Array types that need item type specifications
// - Advanced validation constraints (patterns, ranges, etc.)
//
// For simple types (string, number, boolean), this field can be omitted
// and the basic Type field will be used.
Schema map[string]any `json:"schema,omitempty"`
// Sensitive marks a write-only argument, such as a secret the tool
// stores: its schema says writeOnly, and a workflow execution record
// never holds an input passed into it (SensitiveToolArgs).
Sensitive bool
}
ArgMetadata describes a single argument for a tool. This is used for validation, documentation, and UI generation for tool arguments in various interfaces.
Argument metadata enables automatic validation of tool calls and helps generate helpful error messages when arguments are invalid.
func TagsArg ¶ added in v5.56.0
func TagsArg() ArgMetadata
TagsArg declares the tags argument of the MCPServer and Workflow create and validate tools, with ValidateTags' rules in its JSON Schema. A fresh value per call, so tools share no schema map.
func TagsUpdateArg ¶ added in v5.56.0
func TagsUpdateArg() ArgMetadata
TagsUpdateArg declares the tags argument of the MCPServer and Workflow update tools. Its schema leaves out maxItems: ValidateTagsUpdate lets an update send back more than MaxTags stored tags.
type ArgType ¶
type ArgType string
ArgType is the JSON-Schema-style type of an ArgMetadata. The valid set is closed; using any other value is a programmer error.
type AuthChallenge ¶
type AuthChallenge struct {
// Status indicates this is an auth required response.
Status string `json:"status"` // "auth_required"
// AuthURL is the OAuth authorization URL the user should visit.
AuthURL string `json:"auth_url"`
// ServerName is the name of the MCP server requiring authentication.
ServerName string `json:"server_name,omitempty"`
// Message is a human-readable description of why auth is needed.
Message string `json:"message,omitempty"`
// ClientIDMethod reports how muster identifies itself to the
// authorization server for this flow: "cimd" (AS advertises CIMD
// support), "dcr" (RFC 7591 registered credentials), "cimd-fallback"
// (neither advertised — the AS may reject the sign-in), or "dcr-failed"
// (the AS rejected muster's registration; the CIMD URL is sent anyway).
ClientIDMethod string `json:"client_id_method,omitempty"`
}
AuthChallenge represents an authentication challenge returned when a remote MCP server requires OAuth authentication.
type AuthChallengeParams ¶
type AuthChallengeParams struct {
// SessionID links the OAuth flow to the caller's login session.
SessionID string
// UserID is the authenticated user's identity (sub claim).
UserID string
// ServerName is the MCP server that requires authentication.
ServerName string
// Issuer is the authorization server the flow runs against.
Issuer string
// Resource is the canonical URI of the MCP server the token is for. It
// goes on the authorization request and on the token request (RFC 8707).
Resource string
// Scope is the space-separated scope list to request.
Scope string
// ResetClientRegistration discards muster's stored RFC 7591 client
// registration with the issuer before the flow starts, forcing a fresh
// registration. For authorization servers that refuse muster's stored
// client_id in a way the automatic checks cannot see.
ResetClientRegistration bool
}
AuthChallengeParams carries the per-flow values an authentication challenge is built from. The fields are grouped in a struct because they are all strings: a transposed pair, such as resource and scope, would fail only at the authorization server.
type AuthCompletionCallback ¶
type AuthCompletionCallback func(ctx context.Context, sessionID, userID, serverName, accessToken string) error
AuthCompletionCallback is called after successful OAuth authentication. The aggregator registers this callback to establish session connections when users authenticate to MCP servers via the browser OAuth flow.
Args:
- ctx: Context for the operation
- sessionID: The session ID (token family) that authenticated
- userID: The user's identity (sub claim)
- serverName: The name of the MCP server that was authenticated to
- accessToken: The access token to use for the connection
Returns an error if the connection could not be established.
type AuthHandler ¶
type AuthHandler interface {
// CheckAuthRequired probes the endpoint to determine if OAuth is required.
// Returns true if 401 was received and OAuth flow should be initiated.
CheckAuthRequired(ctx context.Context, endpoint string) (bool, error)
// HasCredentials reports whether usable credentials exist for the
// endpoint: either a non-expired access token or an expired token with
// a refresh token that the mcp-go transport can use for automatic
// refresh.
HasCredentials(endpoint string) bool
// GetBearerToken returns a valid Bearer token for the endpoint.
// Returns an error if not authenticated.
GetBearerToken(endpoint string) (string, error)
// GetAccessToken returns the access token for the endpoint without the
// Bearer prefix, for handing to another client. Returns an error if not
// authenticated.
GetAccessToken(endpoint string) (string, error)
// Login initiates the OAuth flow for the given endpoint.
// Opens browser and waits for callback completion.
Login(ctx context.Context, endpoint string) error
// LoginWithIssuer initiates the OAuth flow for the given endpoint with a known issuer.
// This is used when the issuer URL is already known (e.g., from a WWW-Authenticate header).
LoginWithIssuer(ctx context.Context, endpoint, issuerURL string) error
// Logout clears stored tokens for the endpoint.
Logout(endpoint string) error
// LogoutAll clears all stored tokens.
LogoutAll() error
// GetStatus returns authentication status for all known endpoints.
GetStatus() []AuthStatus
// GetStatusForEndpoint returns authentication status for a specific endpoint.
GetStatusForEndpoint(endpoint string) *AuthStatus
// InvalidateCache removes any cached state for the given endpoint.
// This forces the next status or token lookup to read fresh data from
// the persistent store. Call this after an external mechanism (e.g.
// mcp-go's transport) may have refreshed a token outside of this handler.
InvalidateCache(endpoint string)
// Relogin runs the interactive OAuth flow for the endpoint although a
// valid session may be stored, replacing the stored token -- and with it
// the OIDC ID token -- when the flow completes. The stored session stays
// untouched until then, so a failed or abandoned flow costs nothing.
Relogin(ctx context.Context, endpoint string) error
// GetIDToken returns the stored OIDC ID token for the endpoint. Returns
// an error when no session is stored or the session carries no ID token.
// The token is returned as stored; callers judge its exp claim.
GetIDToken(endpoint string) (string, error)
// Close cleans up any resources held by the auth handler.
Close() error
}
AuthHandler provides OAuth authentication for CLI and agent clients. This interface abstracts authentication operations, enabling consistent auth handling across all CLI commands while maintaining testability.
Following the project's service locator pattern, this interface is defined in the API layer and implemented by adapters in consuming packages.
func GetAuthHandler ¶
func GetAuthHandler() AuthHandler
GetAuthHandler returns the registered auth handler. This provides access to OAuth authentication functionality.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- AuthHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
Example:
handler := api.GetAuthHandler()
if handler == nil {
return fmt.Errorf("auth handler not available")
}
if err := handler.Login(ctx, endpoint); err != nil {
return fmt.Errorf("login failed: %w", err)
}
func GetOrRegisterAuthHandler ¶
func GetOrRegisterAuthHandler(newHandler func() (AuthHandler, error)) (AuthHandler, error)
GetOrRegisterAuthHandler returns the registered auth handler, constructing and registering one via newHandler if none is present yet.
The check, the construction, and the publish all happen under a single write lock, so concurrent callers run newHandler exactly once and every caller observes the same handler. Spelling this as separate GetAuthHandler / RegisterAuthHandler calls leaves the composite operation racy even though each individual call is synchronized: racing callers each build their own handler, the last publish wins, and the losers are orphaned without Close().
IMPORTANT: newHandler runs while handlerMutex is held, so it must not do anything that takes that mutex again -- sync.RWMutex is not reentrant, so the call self-deadlocks. That rules out api.GetXxx/RegisterXxx for the registries handlerMutex covers (this file, handlers.go and metatools.go -- the oauth and secret-credentials registries have their own mutexes and are safe), and, less obviously, closing the handler on a late error: an AuthHandler whose Close unregisters itself, as cli.AuthAdapter's does, takes handlerMutex to do it. Construct in the factory and nothing else; return the error and let the caller decide.
Args:
- newHandler: factory invoked only when no handler is registered
Returns:
- AuthHandler: the registered handler, never nil on success
- error: the factory's error, or an error if the factory returned nil
Thread-safe: Yes, protected by handlerMutex.
func SwapAuthHandler ¶
func SwapAuthHandler(h AuthHandler) AuthHandler
SwapAuthHandler atomically installs h and returns the handler it displaced.
This is the primitive tests should use to isolate themselves from the process-global registry. RegisterAuthHandler(nil) clobbers rather than restores: a test that resets to nil destroys whatever the enclosing test or package had registered. Capture the previous value instead:
prev := api.SwapAuthHandler(mock)
t.Cleanup(func() { api.SwapAuthHandler(prev) })
Args:
- h: AuthHandler to install; nil clears the registration
Returns:
- AuthHandler: the handler that was registered before this call, or nil
Thread-safe: Yes, protected by handlerMutex.
type AuthInfo ¶
type AuthInfo struct {
// Issuer is the OAuth issuer URL (from WWW-Authenticate realm)
Issuer string `json:"issuer,omitempty"`
// Scope is the OAuth scope required by the server
Scope string `json:"scope,omitempty"`
// ResourceMetadataURL is the URL to fetch OAuth metadata (MCP-specific)
ResourceMetadataURL string `json:"resource_metadata_url,omitempty"`
// Resource is the canonical URI the server declares for itself in its
// RFC 9728 metadata. It is the RFC 8707 `resource` value muster sends on
// authorization and token requests for this server.
Resource string `json:"resource,omitempty"`
}
AuthInfo contains OAuth authentication information extracted from a 401 response during MCP server initialization.
type AuthStatus ¶
type AuthStatus struct {
// Endpoint is the URL of the authenticated endpoint.
Endpoint string
// Authenticated indicates whether there is a valid token.
Authenticated bool
// ExpiresAt is when the current token expires.
ExpiresAt time.Time
// IssuerURL is the OAuth issuer that issued this token.
IssuerURL string
// Subject is the authenticated user's subject (sub) claim from the token.
// This is typically a unique user identifier.
Subject string
// Email is the authenticated user's email address (if available in the token).
Email string
// HasRefreshToken indicates whether a refresh token is available for this endpoint.
// If false, the token cannot be refreshed and will require re-authentication when it expires.
HasRefreshToken bool
// RefreshExpiresAt is the estimated time when the refresh token (session) expires.
// This represents the muster-side refresh token expiry, calculated from the token's
// creation time plus the configured refresh token TTL. The actual session may end
// earlier if the upstream provider (e.g., Dex) has a shorter absolute lifetime.
RefreshExpiresAt time.Time
// IDTokenExpiresAt is the exp claim of the stored OIDC ID token; zero when
// the session carries no ID token or the token has no exp. A refresh
// renews it only once the access token has expired, so this can lie in
// the past while Authenticated is true.
IDTokenExpiresAt time.Time
// Error is non-empty if the auth check failed.
Error string
}
AuthStatus represents authentication state for a single endpoint.
type AuthorizationServerConflictChecker ¶ added in v5.53.1
type AuthorizationServerConflictChecker interface {
// AuthorizationServerConflict returns an error wrapping
// ErrAuthorizationServerConflict, naming the MCPServer whose description
// is used, when the named server describes its authorization server
// differently; nil otherwise.
AuthorizationServerConflict(serverName string) error
}
AuthorizationServerConflictChecker is implemented by an AggregatorHandler that knows which MCPServer's description is pinned under each issuer key.
type AuthorizationServerDescriptionChecker ¶ added in v5.60.0
type AuthorizationServerDescriptionChecker interface {
// DescriptionConflict returns an error wrapping
// ErrAuthorizationServerConflict, naming the other MCPServer, when an
// MCPServer with this key (MCPServerKey) and auth would describe its
// issuer key differently from another MCPServer that pins under it; nil
// otherwise, and nil when previous (the server's auth before an update,
// nil on create) already pins the same description. newClient says the
// write stores a client of its own, which no other MCPServer or provider
// App shares.
DescriptionConflict(key string, previous, auth *MCPServerAuth, newClient bool) error
}
AuthorizationServerDescriptionChecker is implemented by an AggregatorHandler that can tell, before an MCPServer is written, whether its description of its authorization server would conflict with another MCPServer's under the same issuer key (the comparison the pin makes).
type BrowserIdentity ¶ added in v5.52.30
type BrowserIdentity interface {
// SignInURL returns the provider URL the browser is sent to. The browser
// comes back to returnURL, on the issuer's origin, with code and state.
// codeChallenge is the S256 challenge of the verifier Subject is given.
// expected is the identity the sign-in must yield; the browser is sent to
// its login method when the provider has several.
SignInURL(ctx context.Context, returnURL *url.URL, state, codeChallenge string, expected SignInIdentity) (string, error)
// CheckRefusal returns a *SignInCheckError when no browser can pass the
// check for a link issued to expected, nil when one can. A sign-in that
// would end in such a check is refused before any link exists.
CheckRefusal(expected SignInIdentity) error
// Identity redeems the code returnURL received and returns who signed in.
Identity(ctx context.Context, returnURL *url.URL, code, codeVerifier string) (SignInIdentity, error)
}
BrowserIdentity signs the browser in to muster's identity provider to learn who is in it, granting nothing. The OAuth proxy start endpoint uses it to make sure the person completing a sign-in to a server is the person the sign-in was started for (MCP URL mode elicitation: the server must bind the elicitation to the user who completes it).
It is registered when muster runs its own OAuth server. Without one no session has a person to compare against, and no check is made.
func GetBrowserIdentity ¶ added in v5.52.30
func GetBrowserIdentity() BrowserIdentity
GetBrowserIdentity returns the registered browser identity check, or nil when muster runs no OAuth server.
type CallToolResult ¶
type CallToolResult struct {
// Content contains the actual result data from the tool execution.
// Can be strings, objects, or any other JSON-serializable data.
//
// For successful executions: contains the tool's output data
// For errors: contains error messages and diagnostic information
Content []any `json:"content"`
// IsError indicates whether the tool execution resulted in an error.
// true: The execution failed and Content contains error information
// false: The execution succeeded and Content contains the result data
IsError bool `json:"isError,omitempty"`
// StructuredContent optionally carries a machine-readable representation
// of the result, mapped to the MCP structuredContent field. It is always
// returned alongside Content, never instead of it, so text-only consumers
// keep working.
StructuredContent any `json:"structuredContent,omitempty"`
// Meta optionally carries entries for the MCP result's _meta field.
Meta map[string]any `json:"_meta,omitempty"`
}
CallToolResult represents the result of a tool execution or capability call. This standardized result format is used across all tool calling interfaces to provide consistent response handling throughout the muster system.
The result can represent either successful execution (IsError=false) or failure conditions (IsError=true), with Content containing the appropriate response data or error information.
func HandleErrorWithPrefix ¶
func HandleErrorWithPrefix(err error, prefix string) *CallToolResult
HandleErrorWithPrefix creates an appropriate CallToolResult with a custom prefix. This function is similar to HandleError but allows customizing the error message prefix for more specific error context.
Args:
- err: The error to handle and format
- prefix: Custom prefix to prepend to the error message
Returns:
- *CallToolResult: A CallToolResult with prefixed error information and IsError set to true
Example:
if err != nil {
return api.HandleErrorWithPrefix(err, "Failed to create service")
}
func InvalidTagsErrorResult ¶ added in v5.56.0
func InvalidTagsErrorResult(err error) *CallToolResult
InvalidTagsErrorResult is the tool error for an InvalidTagsError in err's chain, as ApplyTagsUpdate returns it, and nil for any other error.
func InvalidTagsResult ¶ added in v5.56.0
func InvalidTagsResult(tags *[]string) *CallToolResult
InvalidTagsResult refuses a create's or validate's tags that fail ValidateTags with a tool error. It returns nil when tags is nil (omitted) or valid.
func InvalidTagsUpdateResult ¶ added in v5.56.0
func InvalidTagsUpdateResult(tags *[]string) *CallToolResult
InvalidTagsUpdateResult refuses an update's tags early, before the stored tags are read, when they fail ValidateTagsUpdate whatever is stored: a malformed or repeated tag. The limit needs the stored tags and is left to ApplyTagsUpdate. It returns nil when tags is nil (omitted) or passes.
type CallerAuthenticationError ¶ added in v5.67.0
type CallerAuthenticationError struct {
Message string
}
CallerAuthenticationError means the caller's token cannot authenticate at a service muster needs to authorize the call.
func (*CallerAuthenticationError) Error ¶ added in v5.67.0
func (e *CallerAuthenticationError) Error() string
type ClientCredentials ¶
type ClientCredentials struct {
// ClientID is the OAuth client ID.
ClientID string
// ClientSecret is the OAuth client secret.
ClientSecret string
}
ClientCredentials contains OAuth client credentials loaded from a secret.
type ClientCredentialsSecretRef ¶
type ClientCredentialsSecretRef struct {
// Name is the name of the Kubernetes Secret.
// Required.
Name string `yaml:"name" json:"name"`
// Namespace is the Kubernetes namespace where the secret is located.
// If not specified, defaults to the MCPServer's namespace.
Namespace string `yaml:"namespace,omitempty" json:"namespace,omitempty"`
// ClientIDKey is the key in the secret data that contains the client ID.
// Defaults to "client-id" if not specified.
ClientIDKey string `yaml:"clientIdKey,omitempty" json:"clientIdKey,omitempty"`
// ClientSecretKey is the key in the secret data that contains the client secret.
// Defaults to "client-secret" if not specified.
ClientSecretKey string `yaml:"clientSecretKey,omitempty" json:"clientSecretKey,omitempty"`
}
ClientCredentialsSecretRef references a Kubernetes Secret containing OAuth client credentials for token exchange authentication.
type ConfigAPI ¶
type ConfigAPI interface {
// GetConfig returns the entire muster configuration including all sections.
// This provides access to the complete configuration state for comprehensive
// configuration management scenarios.
//
// Args:
// - ctx: Context for the operation, including cancellation and timeout
//
// Returns:
// - *config.MusterConfig: The complete system configuration
// - error: Error if configuration cannot be retrieved or parsed
//
// Example:
//
// cfg, err := configAPI.GetConfig(ctx)
// if err != nil {
// return fmt.Errorf("configuration unavailable: %w", err)
// }
// fmt.Printf("System listening on port: %d\n", cfg.Aggregator.Port)
GetConfig(ctx context.Context) (*config.MusterConfig, error)
// GetAggregatorConfig returns only the aggregator configuration section.
// This is useful when only aggregator-specific settings are needed,
// avoiding the overhead of retrieving the entire configuration.
//
// Args:
// - ctx: Context for the operation
//
// Returns:
// - *config.AggregatorConfig: The aggregator configuration section
// - error: Error if configuration cannot be retrieved
//
// Example:
//
// aggConfig, err := configAPI.GetAggregatorConfig(ctx)
// if err != nil {
// return err
// }
// fmt.Printf("Aggregator endpoint: %s:%d\n", aggConfig.Host, aggConfig.Port)
GetAggregatorConfig(ctx context.Context) (*config.AggregatorConfig, error)
// UpdateAggregatorConfig updates the aggregator configuration section.
// Changes take effect immediately but are not persisted until SaveConfig is called.
//
// Args:
// - ctx: Context for the operation
// - aggregator: The new aggregator configuration to apply
//
// Returns:
// - error: Error if the update fails or configuration is invalid
//
// Note: Changes are not persisted to disk until SaveConfig is called.
//
// Example:
//
// aggConfig.Port = 9090
// err := configAPI.UpdateAggregatorConfig(ctx, aggConfig)
// if err != nil {
// return fmt.Errorf("failed to update aggregator config: %w", err)
// }
// // Don't forget to save!
// err = configAPI.SaveConfig(ctx)
UpdateAggregatorConfig(ctx context.Context, aggregator config.AggregatorConfig) error
// SaveConfig persists the current in-memory configuration to disk.
// This makes all pending configuration changes permanent and updates
// the configuration files on disk.
//
// Args:
// - ctx: Context for the operation
//
// Returns:
// - error: Error if the configuration cannot be saved to disk
//
// Note: This operation is atomic - either all changes are saved or none are.
//
// Example:
//
// // After making configuration changes...
// err := configAPI.SaveConfig(ctx)
// if err != nil {
// return fmt.Errorf("failed to persist configuration: %w", err)
// }
// fmt.Println("Configuration saved successfully")
SaveConfig(ctx context.Context) error
// ReloadConfig reloads the configuration from disk, discarding any unsaved changes.
// This is useful for reverting to the last saved configuration state or
// picking up external changes to configuration files.
//
// Args:
// - ctx: Context for the operation
//
// Returns:
// - error: Error if the configuration cannot be reloaded from disk
//
// Warning: This operation discards all unsaved in-memory changes.
//
// Example:
//
// // Revert to last saved configuration
// err := configAPI.ReloadConfig(ctx)
// if err != nil {
// return fmt.Errorf("failed to reload configuration: %w", err)
// }
// fmt.Println("Configuration reloaded from disk")
ReloadConfig(ctx context.Context) error
}
ConfigServiceAPI defines the interface for managing configuration at runtime. This interface provides a higher-level abstraction over the ConfigHandler for configuration management operations, including retrieval, updates, and persistence.
The ConfigServiceAPI is designed for direct use by components that need configuration management capabilities, while ConfigHandler is used in the Service Locator Pattern.
Example usage:
configAPI := api.NewConfigServiceAPI()
// Get current configuration
cfg, err := configAPI.GetConfig(ctx)
if err != nil {
return fmt.Errorf("failed to get config: %w", err)
}
// Update aggregator settings
cfg.Aggregator.Port = 8080
err = configAPI.UpdateAggregatorConfig(ctx, cfg.Aggregator)
if err != nil {
return fmt.Errorf("failed to update config: %w", err)
}
// Persist changes to disk
err = configAPI.SaveConfig(ctx)
if err != nil {
return fmt.Errorf("failed to save config: %w", err)
}
func NewConfigServiceAPI ¶
func NewConfigServiceAPI() ConfigAPI
NewConfigServiceAPI creates a new ConfigServiceAPI instance. This function returns a ready-to-use configuration API that delegates operations to the registered ConfigHandler.
Returns:
- ConfigAPI: A new configuration API instance
Note: The returned API will only work if a ConfigHandler has been registered through the Service Locator Pattern. Operations will fail with appropriate error messages if no handler is available.
Example:
configAPI := api.NewConfigServiceAPI() // Use the API for configuration operations...
type ConfigHandler ¶
type ConfigHandler interface {
// GetConfig returns the entire system configuration.
// This provides access to all configuration sections including
// aggregator settings, global settings, and any other configured components.
//
// Args:
// - ctx: Context for the operation, including cancellation and timeout
//
// Returns:
// - *config.MusterConfig: The complete system configuration
// - error: Error if configuration cannot be retrieved or is corrupted
//
// Example:
//
// cfg, err := handler.GetConfig(ctx)
// if err != nil {
// return fmt.Errorf("configuration error: %w", err)
// }
// // Access any configuration section
// fmt.Printf("System has %d MCP servers configured\n", len(cfg.MCPServers))
GetConfig(ctx context.Context) (*config.MusterConfig, error)
// GetAggregatorConfig returns the aggregator-specific configuration section.
// This method is optimized for cases where only aggregator settings are needed.
//
// Args:
// - ctx: Context for the operation
//
// Returns:
// - *config.AggregatorConfig: The aggregator configuration
// - error: Error if configuration cannot be retrieved
GetAggregatorConfig(ctx context.Context) (*config.AggregatorConfig, error)
// UpdateAggregatorConfig updates the aggregator configuration section.
// The new configuration is validated before being applied to ensure system stability.
//
// Args:
// - ctx: Context for the operation
// - aggregator: The new aggregator configuration to apply
//
// Returns:
// - error: Error if the update fails, validation fails, or configuration is invalid
//
// Note: Changes are applied immediately but not persisted until SaveConfig is called.
UpdateAggregatorConfig(ctx context.Context, aggregator config.AggregatorConfig) error
// SaveConfig persists the current configuration to disk.
// This operation is atomic - either all changes are saved successfully
// or no changes are made to the persistent storage.
//
// Args:
// - ctx: Context for the operation
//
// Returns:
// - error: Error if the configuration cannot be saved, disk is full, or permissions are insufficient
//
// Example:
//
// err := handler.SaveConfig(ctx)
// if err != nil {
// return fmt.Errorf("configuration persistence failed: %w", err)
// }
SaveConfig(ctx context.Context) error
// ReloadConfig reloads the configuration from disk, discarding any unsaved changes.
// This is useful for reverting to the last known good configuration or
// picking up external configuration changes.
//
// Args:
// - ctx: Context for the operation
//
// Returns:
// - error: Error if the configuration cannot be reloaded, files are corrupted, or parsing fails
//
// Warning: This operation discards all unsaved in-memory configuration changes.
ReloadConfig(ctx context.Context) error
// ToolProvider integration for exposing configuration management as discoverable MCP tools.
// This allows configuration operations to be invoked through the standard
// tool discovery and execution mechanisms, enabling external configuration management.
ToolProvider
}
ConfigHandler provides configuration management functionality within the Service Locator Pattern. This handler is the primary interface for runtime configuration management, including configuration retrieval, updates, and persistence operations.
The ConfigHandler abstracts the underlying configuration storage and management, allowing components to manage configuration without knowing the specific implementation details of how configuration is stored or processed.
Key features: - Runtime configuration updates without system restart - Atomic configuration persistence to prevent partial updates - Configuration validation to ensure system stability - Section-specific access for performance optimization
Thread-safety: All methods are safe for concurrent use.
func GetConfigHandler ¶
func GetConfigHandler() ConfigHandler
GetConfigHandler returns the registered configuration handler. This provides access to runtime configuration management functionality.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- ConfigHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
Example:
configHandler := api.GetConfigHandler()
if configHandler == nil {
return fmt.Errorf("config handler not available")
}
config, err := configHandler.GetConfig(ctx)
type ConfigurableService ¶
type ConfigurableService interface {
ServiceInfo
// ConfigurationChanged returns true if the new configuration differs from
// the current one in a way that requires a restart. The service owns this
// comparison logic because it has typed access to its configuration struct.
//
// Args:
// - newConfig: The new configuration to compare against (type depends on service implementation)
//
// Returns:
// - bool: true if the configuration has changed and a restart is needed
ConfigurationChanged(newConfig interface{}) bool
// UpdateConfiguration updates the service's internal configuration.
// This should be called before restarting a service when its definition changes.
//
// Args:
// - config: The new configuration (type depends on service implementation)
//
// Returns:
// - error: Error if the configuration is invalid or update fails
UpdateConfiguration(config interface{}) error
}
ConfigurableService extends ServiceInfo with the ability to detect configuration changes and update configuration at runtime. Services implement this interface to allow reconcilers to determine whether a restart is needed and to apply new configuration before restarting.
Methods accept interface{} instead of a concrete type (e.g. *MCPServer) so that the interface remains generic across different service kinds. Each implementation performs a type assertion internally.
type CreateWorkflowRequest ¶
type CreateWorkflowRequest struct {
// Name is the unique identifier for the new workflow
Name string `yaml:"name" json:"name"`
// Description provides human-readable documentation for the workflow
Description string `yaml:"description,omitempty" json:"description,omitempty"`
// Args defines the expected input arguments for workflow execution
Args map[string]ArgDefinition `yaml:"args,omitempty" json:"args,omitempty"`
// Steps defines the sequence of operations to be performed during workflow execution
Steps []WorkflowStep `yaml:"steps" json:"steps"`
}
CreateWorkflowRequest represents a request to create a new workflow. This is used for API-based workflow creation with validation and structured input.
type DelegatedCaller ¶ added in v5.58.0
type DelegatedCaller struct {
// Token is the validated inbound bearer.
Token string
// Issuer and Subject are the token's iss and raw sub.
Issuer string
Subject string
// ActorIssuer and ActorChain name the acting parties, the current actor
// (outermost act) first.
ActorIssuer string
ActorChain []string
// Toolset is the selector list the token's scope claim granted.
Toolset []string
}
DelegatedCaller is a caller that presented a delegated token: a token from a trusted issuer whose sub names a person and whose act claim names the party acting for that person (RFC 8693 §4.1). The token is muster's credential for the call only: it is exchanged for backend tokens and never forwarded.
func DelegatedCallerFromContext ¶ added in v5.58.0
func DelegatedCallerFromContext(ctx context.Context) (DelegatedCaller, bool)
DelegatedCallerFromContext returns the delegated caller of the request, and false when the request is not a delegated caller's.
type DelegationExchange ¶ added in v5.58.0
type DelegationExchange interface {
DelegationExchangeConfig(caller DelegatedCaller) (TokenExchangeConfig, error)
}
DelegationExchange resolves the RFC 8693 exchange muster runs for a delegated caller at the Dex that issued the caller's token, for a token of muster's choosing (the Kubernetes API server's, for instance): the token endpoint, muster's Dex client, and muster's workload token as actor. The caller sets Delegation.Audience.
func GetDelegationExchange ¶ added in v5.58.0
func GetDelegationExchange() DelegationExchange
GetDelegationExchange returns the registered DelegationExchange, nil when none is.
type EventData ¶
type EventData struct {
// Operation is the operation that triggered the event (e.g., "create", "update", "delete").
Operation string
// Error contains error information for failure events.
Error string
// Duration is the duration of an operation (for execution events).
Duration time.Duration
// StepCount is the number of steps in a workflow definition or execution.
StepCount int
// StepID is the ID of the workflow step involved in the event.
StepID string
// StepTool is the tool used in the workflow step.
StepTool string
// ConditionResult is the result of step condition evaluation.
ConditionResult string
// ExecutionID is the unique identifier for a workflow execution.
ExecutionID string
// ToolNames contains the list of tools (for tool-availability events).
ToolNames []string
// AllowFailure indicates whether a failed step is allowed to fail.
AllowFailure bool
}
EventData carries structured, contextual fields used by the event message templates so that rendered messages include meaningful detail (errors, step counts, durations, execution IDs, ...).
The Name and Namespace of the involved object are taken from the ObjectReference passed to CreateEventWithData and do not need to be set here.
type EventManagerHandler ¶
type EventManagerHandler interface {
// CreateEventWithData creates an event for a specific object reference,
// carrying structured EventData so the message templates can render
// contextual detail (error strings, step counts, durations, ...).
//
// The human-readable message is rendered from the reason's template using
// the supplied data; the event type (Normal/Warning) is derived from the
// reason — callers do not pass a message or type.
//
// Args:
// - ctx: Context for the operation, including cancellation and timeout
// - objectRef: Reference to the object this event relates to (provides Name/Namespace/Kind)
// - reason: Machine-readable reason matching a known event reason (e.g., "MCPServerCreated")
// - data: Structured contextual data for message templating
//
// Returns:
// - error: Error if event creation fails
//
// Example:
//
// objectRef := ObjectReference{
// Kind: "MCPServer",
// Name: "github-server",
// Namespace: "default",
// }
// err := handler.CreateEventWithData(ctx, objectRef, "MCPServerCreated", EventData{})
CreateEventWithData(ctx context.Context, objectRef ObjectReference, reason string, data EventData) error
// DefaultNamespace returns the namespace muster CRDs live in (derived from
// muster configuration). Callers that emit events for runtime objects
// without an explicit namespace should use this so events are associated
// with the CRD in the correct namespace rather than orphaned in "default".
DefaultNamespace() string
// QueryEvents retrieves events based on the provided filtering options.
// This method works with both Kubernetes and filesystem modes:
// - Kubernetes mode: Queries the native Kubernetes Events API
// - Filesystem mode: Parses stored event files
//
// Args:
// - ctx: Context for the operation
// - options: Filtering options for the event query
//
// Returns:
// - *EventQueryResult: Query result containing matching events
// - error: Error if query fails
//
// Example:
//
// options := EventQueryOptions{
// ResourceType: "MCPServer",
// Namespace: "default",
// Limit: 50,
// }
// result, err := handler.QueryEvents(ctx, options)
QueryEvents(ctx context.Context, options EventQueryOptions) (*EventQueryResult, error)
// WatchEvents returns a channel that emits muster events matching the given
// options as they occur. It is the streaming counterpart to QueryEvents and
// backs `muster events --follow`: in Kubernetes mode it is driven by a
// native Kubernetes watch on the Events API; in filesystem mode by an
// fsnotify watch on the on-disk event log. No timer polling is involved.
//
// The returned channel is closed when ctx is cancelled or the underlying
// watch terminates. Callers must drain or cancel to avoid leaking the
// backing watch.
//
// Args:
// - ctx: Context controlling the lifetime of the watch
// - options: Filtering options applied to streamed events
//
// Returns:
// - <-chan EventResult: Channel emitting matching events as they occur
// - error: Error if the watch could not be established
WatchEvents(ctx context.Context, options EventQueryOptions) (<-chan EventResult, error)
// IsKubernetesMode returns true if the event manager is using Kubernetes mode.
// This can be useful for components that need to adapt their behavior
// based on the deployment environment.
//
// Returns:
// - bool: true if using Kubernetes mode, false if using filesystem mode
//
// Example:
//
// if handler.IsKubernetesMode() {
// // Can access events via kubectl get events
// } else {
// // Events are logged to console and events.log
// }
IsKubernetesMode() bool
}
EventManagerHandler provides Kubernetes Event generation functionality for muster CRD lifecycle operations and service management.
This interface abstracts the event generation system, allowing components to create events without knowing the specific implementation details of how events are stored or delivered (Kubernetes Events API vs filesystem logging).
The handler automatically adapts to the current client mode:
- Kubernetes mode: Creates actual Kubernetes Events API objects
- Filesystem mode: Logs events to console and events.log file
Key features: - Unified event generation across both Kubernetes and filesystem modes - Dynamic message templating with contextual data - Automatic event type classification (Normal vs Warning) - Support for both CRD objects and synthetic references
Thread-safety: All methods are safe for concurrent use.
func GetEventManager ¶
func GetEventManager() EventManagerHandler
GetEventManager returns the registered event manager handler. This provides access to Kubernetes Event generation functionality for CRD lifecycle operations.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- EventManagerHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
Example:
eventManager := api.GetEventManager()
if eventManager == nil {
return fmt.Errorf("event manager not available")
}
err := eventManager.CreateEventWithData(ctx, objectRef, "MCPServerCreated", EventData{})
type EventPoller ¶ added in v5.67.0
type EventPoller interface {
PollEvents(ctx context.Context, server, name string, args map[string]any, cursor string) (map[string]any, error)
}
EventPoller is the events/poll extension of an organization-visible MCP server. The aggregator authorizes the principal against the source server.
type EventQueryOptions ¶
type EventQueryOptions struct {
// ResourceType filters events by object kind (MCPServer, Workflow)
ResourceType string `json:"resourceType,omitempty"`
// ResourceName filters events by object name
ResourceName string `json:"resourceName,omitempty"`
// Namespace filters events by namespace
Namespace string `json:"namespace,omitempty"`
// EventType filters by event type (Normal, Warning)
EventType string `json:"eventType,omitempty"`
// Since filters events that occurred after this time
Since *time.Time `json:"since,omitempty"`
// Until filters events that occurred before this time
Until *time.Time `json:"until,omitempty"`
// Limit restricts the number of events returned
Limit int `json:"limit,omitempty"`
}
EventQueryOptions represents filtering options for event queries.
type EventQueryResult ¶
type EventQueryResult struct {
// Events is the list of events matching the query
Events []EventResult `json:"events"`
// TotalCount is the total number of events (before limit is applied)
TotalCount int `json:"totalCount"`
}
EventQueryResult represents the result of an event query.
type EventResult ¶
type EventResult struct {
// Timestamp when the event occurred
Timestamp time.Time `json:"timestamp"`
// Namespace of the involved object
Namespace string `json:"namespace"`
// InvolvedObject information
InvolvedObject ObjectReference `json:"involvedObject"`
// Reason for the event
Reason string `json:"reason"`
// Message describing the event
Message string `json:"message"`
// Type of event (Normal, Warning)
Type string `json:"type"`
// Source component that generated the event
Source string `json:"source"`
// Count for how many times this event occurred (Kubernetes mode)
Count int32 `json:"count,omitempty"`
}
EventResult represents a single event result.
type GetWorkflowExecutionRequest ¶
type GetWorkflowExecutionRequest struct {
// ExecutionID is the unique identifier of the execution to retrieve
ExecutionID string `json:"execution_id"`
// IncludeSteps controls whether detailed step information is included (default: true)
IncludeSteps bool `json:"include_steps,omitempty"`
// StepID specifies a specific step to retrieve (optional, returns only that step)
StepID string `json:"step_id,omitempty"`
}
GetWorkflowExecutionRequest represents a request to get detailed information about a specific workflow execution.
This request structure enables flexible querying of execution details with options to include/exclude step information and retrieve specific step results.
type Governance ¶ added in v5.67.0
type Governance struct {
// Mode is GovernanceTrusted or GovernanceGoverned.
Mode string
// Servers are the governed servers.
Servers []GovernedServer
// Readable is false when muster started without a readable
// configuration: the governed default applies then.
Readable bool
// RoleFloors is the effective floor table (MergeRoleFloors); nil means
// the built-in floors.
RoleFloors map[string][]string
}
Governance is muster's governance configuration: the mode and the governed servers. It is read once at start and never changed while muster runs.
func GetGovernance ¶ added in v5.67.0
func GetGovernance() Governance
GetGovernance returns a copy of the governance configuration. Before RegisterGovernance it is the unreadable configuration, so the governed default applies.
func (Governance) CoreEntry ¶ added in v5.67.0
func (g Governance) CoreEntry(tool string) (ToolApproval, bool)
CoreEntry returns the approval governance gives an agent caller's call of one of muster's core tools: a floor asks in both modes; on Governed every core tool that is not one of muster's reads asks too.
func (Governance) Governed ¶ added in v5.67.0
func (g Governance) Governed() bool
Governed reports whether the governed default applies: the mode says so, or the configuration could not be read.
func (Governance) ModeName ¶ added in v5.67.0
func (g Governance) ModeName() string
ModeName is the mode clients are shown: governed whenever the governed default applies (also for an unreadable configuration), else trusted.
func (Governance) NamesServer ¶ added in v5.67.0
func (g Governance) NamesServer(server string) bool
NamesServer reports whether the configuration governs server.
func (Governance) RoleFloorsOf ¶ added in v5.67.0
func (g Governance) RoleFloorsOf(role string) []string
RoleFloorsOf returns the floor tool names of a role.
func (Governance) Roles ¶ added in v5.67.0
func (g Governance) Roles() []string
Roles returns the roles a governed server may have: the built-in ones and those the floor table declares.
func (Governance) ServerEntry ¶ added in v5.67.0
func (g Governance) ServerEntry(server, tool string) (approval ToolApproval, applies, refused bool)
ServerEntry returns the approval governance gives an agent caller's call of the server's own tool name:
- on a governed server, a floor of its role asks in both modes; on Governed every other tool asks too unless it is on the server's safe list, so a tool the server adds or renames later asks until someone lists it (default-deny);
- on any other server nothing applies, except for a floor's name: while no governed server holds the floor's role it is refused (refused true), since muster cannot tell the role's real server from a look-alike; once one does, it asks on Governed (an unnamed second instance fails closed) and follows the server's own settings on Trusted. Generic names that are no floor are never touched.
func (Governance) UnmatchedSafe ¶ added in v5.67.0
func (g Governance) UnmatchedSafe(server string, tools []string) []string
UnmatchedSafe returns the safe-list entries of a governed server that name none of the tools it lists: a typo or a renamed tool, which then asks (fail closed) but should be fixed.
func (Governance) Validate ¶ added in v5.67.0
func (g Governance) Validate() error
Validate refuses a configuration muster cannot enforce as written: a server named twice or without a key, a role neither built in nor declared in the floor table, a declared role or floor without a name, or a floor of any role on a safe list (a floor asks; listing it as safe would read as if it did not).
type GovernedServer ¶ added in v5.67.0
GovernedServer is a server the governance configuration names: its server key, its role (which floors hold on it), and its safe list -- the tool names agents call on it unasked on Governed.
type GrantReleaser ¶
type GrantReleaser interface {
// SubjectGrantForRelease returns the person's grant for the issuer,
// refreshed when it has expired or is about to, or nil when the person
// holds none (or the refresh token was rejected and the grant removed).
SubjectGrantForRelease(ctx context.Context, userID, issuer string) *OAuthToken
}
GrantReleaser is implemented by an OAuthHandler that can hand a person's subject-scoped grant to a trusted relying party: the token broker's grant targets (tokenExchangeBroker.targets.<audience>.grantIssuer) call it with the Dex subject a confidential client's exchange request was validated to and the issuer the grant was filed under. The handler refreshes the grant first when it is due. Kept separate from SubjectGrantHandler so the test doubles of that interface need not grow with it.
type HandoffRedeemer ¶ added in v5.67.0
type HandoffRedeemer func(ctx context.Context, ticket, kind, target string, want SignInIdentity) (SignInHandoff, bool)
HandoffRedeemer redeems a ticket for a page: the handoff and true when the ticket exists, is unused and unexpired, and is bound to kind and target and to the person want. The ticket is used up whatever the answer.
type HealthStatus ¶
type HealthStatus string
HealthStatus represents the health status of a service, capability, or other component. This standardized status is used across all muster components for consistent health reporting.
Health status provides a unified way to represent component operational state, enabling consistent monitoring and alerting across the entire system.
const ( // HealthUnknown indicates the health status cannot be determined. // This is the default state when no health check has been performed. HealthUnknown HealthStatus = "unknown" // HealthHealthy indicates the component is operating normally. // All health checks are passing and the component is fully functional. HealthHealthy HealthStatus = "healthy" // HealthDegraded indicates the component has some issues but is still functional. // Some non-critical features may be impaired but core functionality works. HealthDegraded HealthStatus = "degraded" // HealthUnhealthy indicates the component has significant issues. // Core functionality may be impaired and manual intervention may be required. HealthUnhealthy HealthStatus = "unhealthy" // HealthChecking indicates a health check is currently in progress. // This is a transient state during health check execution. HealthChecking HealthStatus = "checking" )
type InvalidTagsError ¶ added in v5.56.0
type InvalidTagsError struct{ Err error }
InvalidTagsError is a write's tags refused by ValidateTags or ValidateTagsUpdate.
func (*InvalidTagsError) Error ¶ added in v5.56.0
func (e *InvalidTagsError) Error() string
func (*InvalidTagsError) Unwrap ¶ added in v5.56.0
func (e *InvalidTagsError) Unwrap() error
type IssuerPin ¶
type IssuerPin struct {
// DescriptionKey identifies the MCPServer description that placed the
// pin; opaque to the OAuth handler, which only stores it with the pin.
DescriptionKey string
AuthorizationEndpoint string
TokenEndpoint string
// ExpectedIssuer is the issuer identifier the authorization server puts in
// the RFC 9207 iss parameter when it differs from the pinned identity;
// empty when the identity itself is expected.
ExpectedIssuer string
ClientID string
ClientSecret string
SubjectScoped bool
// RevocationEndpoint is the RFC 7009 endpoint a disconnect revokes a
// subject-scoped grant at instead of the metadata's; empty for that.
RevocationEndpoint string
}
IssuerPin is an operator's description of an authorization server beyond what muster can discover: the endpoints of an AS without an RFC 8414 document, a client registered with it out of band, and whether its grants belong to the person rather than to one login session. It is what MCPServer spec.auth.authorizationServer carries, with the client credentials resolved from their Secret.
type IssuerPinner ¶
type IssuerPinner interface {
// PinIssuer records the pin for an issuer; calling it again replaces the
// previous pin (a rotated client secret takes effect that way).
PinIssuer(issuer string, pin IssuerPin)
// UnpinIssuer forgets the pin for an issuer -- client, grant scope and
// pinned endpoints alike -- so the next flow against it discovers the
// authorization server again. Called when no MCPServer describes the
// issuer any more, or before a changed description is recorded; a pin
// nobody owns would otherwise outlive its MCPServer until a restart.
UnpinIssuer(issuer string)
// PinnedDescriptionKey returns the IssuerPin.DescriptionKey of the pin
// recorded for an issuer; false without a pin.
PinnedDescriptionKey(issuer string) (string, bool)
}
IssuerPinner is implemented by an OAuthHandler that accepts operator pins for authorization servers. Kept separate from OAuthHandler so the many test doubles of that interface need not grow with it.
type ListWorkflowExecutionsRequest ¶
type ListWorkflowExecutionsRequest struct {
// WorkflowName filters executions to only those from the specified workflow (optional)
WorkflowName string `json:"workflow_name,omitempty"`
// Status filters executions to only those with the specified status (optional)
Status WorkflowExecutionStatus `json:"status,omitempty"`
// Limit is the maximum number of executions to return (default: 50, max: 1000)
Limit int `json:"limit,omitempty"`
// Offset is the number of executions to skip for pagination (default: 0)
Offset int `json:"offset,omitempty"`
}
ListWorkflowExecutionsRequest represents a request to list workflow executions with optional filtering and pagination args.
This request structure enables efficient querying of execution history with support for filtering by workflow name and status, plus pagination for handling large execution datasets.
type ListWorkflowExecutionsResponse ¶
type ListWorkflowExecutionsResponse struct {
// Executions contains the list of execution records (summary information only)
Executions []WorkflowExecutionSummary `json:"executions"`
// Total is the total number of executions matching the filter criteria
Total int `json:"total"`
// Limit is the maximum number of executions returned in this response
Limit int `json:"limit"`
// Offset is the number of executions skipped in this response
Offset int `json:"offset"`
// HasMore indicates whether there are more executions available
HasMore bool `json:"has_more"`
}
ListWorkflowExecutionsResponse represents the response from listing workflow executions. This provides paginated execution results with metadata for navigation.
The response includes both the execution data and pagination metadata to enable efficient client-side handling of large execution datasets.
type LoginTokenMirror ¶
type LoginTokenMirror interface {
// StoreLoginIDToken records the session's login ID token under the
// issuer without touching any grant from that issuer.
StoreLoginIDToken(sessionID, userID, issuer, idToken string, expiresAt time.Time)
// LoginIDToken returns the session's login ID token for the issuer, or
// nil when none is recorded or it expired.
LoginIDToken(sessionID, issuer string) *OAuthToken
}
LoginTokenMirror is implemented by an OAuthHandler that keeps the ID token of the person's login at muster -- the credential SSO token forwarding hands to backends that trust muster's IdP -- apart from the per-server grants the OAuth proxy obtains. Both can come from the same issuer: an MCPServer may pin muster's own IdP as its authorization server. Filed under one key, the mirror of the login token, written on every request that carries an externally issued bearer, overwrote the grant and the server's tools failed with "no valid token available" right after a successful sign-in (giantswarm/muster#1174).
type MCPServer ¶
type MCPServer struct {
// Name is the unique identifier for this MCP server instance.
// This name is used for registration, lookup, and management operations.
// It is the server's key (MCPServerKey): the object's name in muster's
// namespace, "<namespace>/<name>" outside it.
Name string `yaml:"name" json:"name"`
// Namespace is the Kubernetes namespace of the MCPServer resource this
// definition was read from. It is the default namespace for every Secret
// the definition references (clientCredentialsSecretRef) and the namespace
// the server's Kubernetes events are filed under. Empty in filesystem mode.
// Runtime information taken from the resource's metadata, not persisted.
Namespace string `yaml:"-" json:"-"`
// UID is the Kubernetes UID of the MCPServer resource. A server outside
// muster's namespace is told apart from an earlier one of the same name
// (a namespace deleted and created again) by it, so it never gets that
// one's sign-ins. Empty in filesystem mode. Runtime information taken
// from the resource's metadata, not persisted.
UID string `yaml:"-" json:"-"`
// CreatedAt is the creation time of the MCPServer resource. Of the servers
// that describe one authorization server differently, the oldest one's
// description is used. Zero in filesystem mode. Runtime information taken
// from the resource's metadata, not persisted.
CreatedAt time.Time `yaml:"-" json:"-"`
// Type specifies how this MCP server should be executed.
// Supported values: "stdio" for local processes, "streamable-http" for HTTP-based servers, "sse" for Server-Sent Events
Type MCPServerType `yaml:"type" json:"type"`
// ToolPrefix is an optional prefix that will be prepended to all tool names
// provided by this MCP server. This helps avoid naming conflicts when multiple
// servers provide tools with similar names.
ToolPrefix string `yaml:"toolPrefix,omitempty" json:"toolPrefix,omitempty"`
// Family declares that this MCP server is an instance of a family of
// equivalent servers. When set, the aggregator exposes tools as
// {musterPrefix}_{family.name}_{toolName} with a required parameter named
// by family.instanceArg.
Family *MCPServerFamily `yaml:"family,omitempty" json:"family,omitempty"`
// AutoStart determines whether this MCP server should be automatically started
// when the muster system initializes or when dependencies become available.
AutoStart bool `yaml:"autoStart,omitempty" json:"autoStart,omitempty"`
// Command specifies the executable path for stdio type servers.
// This field is required when Type is "stdio".
Command string `yaml:"command,omitempty" json:"command,omitempty"`
// Args specifies the command line arguments for stdio type servers.
// This field is only available when Type is "stdio".
Args []string `yaml:"args,omitempty" json:"args,omitempty"`
// URL is the endpoint where the remote MCP server can be reached
// This field is required when Type is "streamable-http" or "sse".
// Examples: http://mcp-server:8080/mcp, https://api.example.com/mcp
URL string `yaml:"url,omitempty" json:"url,omitempty"`
// Env contains environment variables to set for a stdio server's process
// when it is started. Refused on a remote server (ValidateNoInlineCredential).
Env map[string]string `yaml:"env,omitempty" json:"env,omitempty"`
// Headers contains HTTP headers to send with requests to remote MCP servers.
// This field is only relevant when Type is "streamable-http" or "sse".
Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`
// HeadersFrom lists HTTP headers whose values muster reads from a Secret
// in the server's own namespace when it connects. Only the references are
// here: the values live in the connection's client alone.
HeadersFrom []MCPServerHeaderFrom `yaml:"headersFrom,omitempty" json:"headersFrom,omitempty"`
// RequestMeta contains entries added to the `params._meta` object of every
// outbound JSON-RPC request that carries `params`. Remote types only; see
// ValidateRequestMeta and the v1alpha1 CRD field of the same name.
RequestMeta map[string]string `yaml:"requestMeta,omitempty" json:"requestMeta,omitempty"`
// Auth configures authentication behavior for this MCP server.
// This is only relevant for remote servers (streamable-http or sse).
Auth *MCPServerAuth `yaml:"auth,omitempty" json:"auth,omitempty"`
// Timeout bounds every operation on the server in seconds -- each
// request, a tool call included, for every type; for a remote server also
// the connect and the health probe (default 30).
Timeout int `yaml:"timeout,omitempty" json:"timeout,omitempty"`
// Progress configures how progress the server reports on a tool call
// affects that call's budget (see ProgressMaxDuration).
Progress *MCPServerProgress `yaml:"progress,omitempty" json:"progress,omitempty"`
// Error contains any error message from the most recent server operation.
// This is runtime information and not persisted to YAML files.
Error string `json:"error,omitempty" yaml:"-"`
// Description provides a human-readable description of this MCP server's purpose.
// This is runtime information populated from server metadata and not persisted to YAML.
Description string `json:"description,omitempty" yaml:"-"`
}
MCPServer represents a single MCP (Model Context Protocol) server definition and runtime state. It consolidates MCPServerDefinition, MCPServerInfo, and MCPServerConfig into a unified type that can be used for both configuration persistence (YAML) and API responses (JSON).
MCP servers provide tools and capabilities to the muster system through the aggregator. They are configured as stdio processes or remote HTTP endpoints with their own specific configuration requirements and runtime characteristics.
func (*MCPServer) OperationTimeout ¶ added in v5.53.2
OperationTimeout is spec.timeout as muster applies it to every operation on the server: defaultTimeoutSeconds when unset, MaxTimeoutSeconds when larger. clamped reports that spec.timeout was cut down to MaxTimeoutSeconds.
func (*MCPServer) ProgressMaxDuration ¶ added in v5.40.0
ProgressMaxDuration is how long progress may keep a tool call on the server going: spec.progress.maxDuration, DefaultProgressMaxDurationSeconds when unset.
type MCPServerApproval ¶ added in v5.67.0
type MCPServerApproval struct {
Rule string `yaml:"rule,omitempty" json:"rule,omitempty"`
Tools map[string]string `yaml:"tools,omitempty" json:"tools,omitempty"`
}
MCPServerApproval is a server's spec.approval: the rule a tool without its own entry follows, and the tools' own entries, keyed by the server's own tool name. The values are kept as written, so a value the CRD would refuse (a definition read from a file, an object written before the CRD knew the field) still reaches resolution, which counts it as Ask.
func ExpandApprovalPreset ¶ added in v5.67.0
func ExpandApprovalPreset(preset string, tools []mcp.Tool) (*MCPServerApproval, error)
ExpandApprovalPreset expands a preset into explicit settings for the given tools, the server's own tools as it lists them now (their own names). The result depends on the annotations only at this moment: it is stored as it is, and a tool the server adds later follows its rule.
type MCPServerApprovalSchema ¶ added in v5.67.0
type MCPServerApprovalSchema interface {
// ApprovalSchemaProblem returns "" when the CRD knows spec.approval, else
// why muster cannot trust approval settings.
ApprovalSchemaProblem(ctx context.Context) string
}
MCPServerApprovalSchema is the optional capability of the registered MCPServer manager that tells whether approval settings can be trusted: the served MCPServer CRD knows spec.approval. A CRD that does not prunes the field on every write, so a connector's Ask and Block would silently run.
type MCPServerAuth ¶
type MCPServerAuth struct {
// Type specifies the authentication type.
// Supported values:
// - "oauth": OAuth 2.0/OIDC authentication
// - "none": No authentication
// - "sigv4": AWS Signature Version 4 request signing, see SigV4
Type string `yaml:"type,omitempty" json:"type,omitempty"`
// GrantScope is "session" (default) or "subject": whom the grant of the
// server's OAuth sign-in belongs to, for whichever authorization server
// the server uses -- the one discovered through RFC 9728 or the one
// pinned in AuthorizationServer. See SubjectScoped, ValidateGrantScope
// and the v1alpha1 CRD field of the same name.
GrantScope string `yaml:"grantScope,omitempty" json:"grantScope,omitempty"`
// ForwardToken enables SSO via Token Forwarding.
// When true, muster forwards its own ID token (obtained when user authenticated
// TO muster) to this downstream server. The downstream server must be configured
// to trust muster's OAuth client ID in its TrustedAudiences configuration.
//
// Use ForwardToken when:
// - Muster itself is OAuth-protected (oauth_server enabled)
// - The downstream server trusts muster as an identity relay
// - You want users to authenticate once to muster for all downstream access
ForwardToken bool `yaml:"forwardToken,omitempty" json:"forwardToken,omitempty"`
// ForwardIdentity sends the session's upstream ID token -- the token
// ForwardToken would put in Authorization -- in the X-Muster-Id-Token
// header (pkg/oauth.HeaderMusterIDToken) on every request, next to the
// pinned grant Authorization keeps carrying. Only valid with Type "oauth"
// and AuthorizationServer set (ValidateForwardIdentity). The forwarded
// token is not audience-scoped to the server, as with ForwardToken. See
// the v1alpha1 CRD field of the same name for full semantics.
ForwardIdentity bool `yaml:"forwardIdentity,omitempty" json:"forwardIdentity,omitempty"`
// ProviderApps names the provider Apps whose grants the server receives,
// one X-Muster-Grant-<app> header per App the person granted. Needs
// ForwardToken or ForwardIdentity (ValidateProviderApps). See the v1alpha1
// CRD field of the same name.
ProviderApps []string `yaml:"providerApps,omitempty" json:"providerApps,omitempty"`
// RequiredAudiences specifies additional audience(s) that the SSO token should contain.
// This is used with both Token Forwarding and Token Exchange SSO methods.
//
// When the downstream server requires tokens with specific audiences (e.g., Kubernetes
// OIDC authentication), specify them here:
// requiredAudiences:
// - "dex-k8s-authenticator"
//
// For Token Forwarding (forwardToken: true) and Identity Forwarding
// (forwardIdentity: true):
// - At session initialization, muster collects all requiredAudiences from MCPServers
// - These are requested from muster's IdP using cross-client scopes
// - The resulting multi-audience ID token is forwarded to downstream servers
//
// For Token Exchange (tokenExchange.enabled: true):
// - The audiences are appended as cross-client scopes to the token exchange request
// - The remote IdP issues a token containing the requested audiences
RequiredAudiences []string `yaml:"requiredAudiences,omitempty" json:"requiredAudiences,omitempty"`
// TokenExchange enables SSO via RFC 8693 Token Exchange for cross-cluster SSO.
// When configured, muster exchanges its local token for a token valid on the
// remote cluster's Identity Provider (e.g., Dex).
//
// Use TokenExchange when:
// - The remote cluster has its own Dex instance
// - The remote Dex is configured with an OIDC connector for muster's Dex
// - You need a token issued by the remote cluster's IdP (not just forwarded)
//
// Token exchange takes precedence over ForwardToken if both are configured.
TokenExchange *TokenExchangeConfig `yaml:"tokenExchange,omitempty" json:"tokenExchange,omitempty"`
// AuthorizationServer pins the OAuth issuer when the MCP server does not
// publish RFC 9728 Protected Resource Metadata. See the v1alpha1 CRD field
// of the same name for full semantics. When set, muster's per-server OAuth
// login flow skips PRM probing and uses these values directly.
AuthorizationServer *MCPServerAuthAuthorizationServer `yaml:"authorizationServer,omitempty" json:"authorizationServer,omitempty"`
// SigV4 configures AWS Signature Version 4 request signing. Required when
// Type is MCPServerAuthTypeSigV4, and rejected otherwise. See the v1alpha1
// CRD field of the same name for full semantics.
SigV4 *MCPServerSigV4 `yaml:"sigv4,omitempty" json:"sigv4,omitempty"`
// PrincipalAudience is the server's Dex client ID: muster reaches the
// server only as the organization principal of its namespace, sending the
// principal's Dex ID token for this audience, and refuses every other
// caller. See ServesOrganizationPrincipal, ValidatePrincipalAudience and
// the v1alpha1 CRD field of the same name.
PrincipalAudience string `yaml:"principalAudience,omitempty" json:"principalAudience,omitempty"`
}
MCPServerAuth configures authentication behavior for an MCP server.
Muster supports two distinct authentication mechanisms:
SSO Token Forwarding: Muster forwards its own ID token to downstream servers. Enable with ForwardToken: true. Requires downstream to trust muster's client ID.
SSO Token Exchange (RFC 8693): Muster exchanges its token for one valid on the remote cluster's Dex. Enable with TokenExchange config. Requires the remote Dex to have an OIDC connector configured for the local cluster's Dex.
A server pinned to its own authorization server can additionally receive the session's ID token next to that grant: ForwardIdentity.
A server that serves an organization's principal and no person sets PrincipalAudience: muster reaches it only as the organization principal of its namespace, with the principal's Dex token for that audience.
AWS SigV4 (Type: MCPServerAuthTypeSigV4) is not one of them: it signs as muster's own machine identity rather than relaying the caller's, so it uses the shared global client instead of the session-scoped machinery.
func (*MCPServerAuth) CanAuthenticateInteractively ¶
func (a *MCPServerAuth) CanAuthenticateInteractively() bool
CanAuthenticateInteractively reports whether a 401 from a server with this auth configuration can be resolved by a user completing a login flow.
It is false for a machine identity: the credential is muster's own, so there is no user to send to an authorization server and no pending-auth state to reach. A 401 from such a server is an ordinary connect failure — the region, the assumed role or its policy is wrong — and every consumer of the auth-required signal has to agree on that, or the CR reports "Auth Required" while the aggregator refuses to register it.
A nil receiver means no auth is configured, which is the OAuth-capable default: a 401 from an unconfigured server is what triggers discovery.
func (*MCPServerAuth) DiscoversSubjectScopedIssuer ¶ added in v5.57.0
func (a *MCPServerAuth) DiscoversSubjectScopedIssuer() bool
DiscoversSubjectScopedIssuer reports whether the server files its grants under the person for an authorization server it does not pin: auth type oauth, spec.auth.grantScope "subject" and no spec.auth.authorizationServer.issuer. muster learns that issuer from the server's RFC 9728 metadata and makes it subject-scoped once it knows it. False for a configuration ValidateGrantScope refuses.
func (*MCPServerAuth) ForwardsIdentity ¶ added in v5.31.0
func (a *MCPServerAuth) ForwardsIdentity() bool
ForwardsIdentity reports whether the server receives the session's upstream ID token in the X-Muster-Id-Token header next to its pinned grant: the field is set on the one configuration it is valid for (ValidateForwardIdentity). A configuration that fails the validation never sends the token, whichever path let it through.
func (*MCPServerAuth) ReceivesProviderApps ¶ added in v5.48.0
func (a *MCPServerAuth) ReceivesProviderApps() bool
ReceivesProviderApps reports whether the server receives the person's App tokens: it names Apps and passes ValidateProviderApps.
func (*MCPServerAuth) RequiresUserSignIn ¶ added in v5.67.0
func (a *MCPServerAuth) RequiresUserSignIn() bool
RequiresUserSignIn reports whether the configuration alone says that a person signs in before the server can be used: OAuth with a pinned authorization server, reached with a grant of the person's own rather than with the caller's forwarded identity (UsesSessionAuth).
Like UsesSessionAuth, this must not be inferred from how the backend answered a connection probe. Some backends (Google's remote MCP servers among them) answer initialize and tools/list without a token and refuse only the tool calls: a token-less shared client would list every tool and fail every call with 401, while the server never asked anyone to sign in.
A bare Type "oauth" without AuthorizationServer is not enough: muster learns its authorization server from the 401 and RFC 9728 metadata, so a backend that answers anonymously stays usable anonymously.
func (*MCPServerAuth) ServesOrganizationPrincipal ¶ added in v5.67.0
func (a *MCPServerAuth) ServesOrganizationPrincipal() bool
ServesOrganizationPrincipal reports whether the server serves the organization principal of its namespace and no one else (spec.auth.principalAudience): muster reaches it only on the principal's own connection, with the principal's Dex token for the server's audience, and refuses every other caller, a person included.
func (*MCPServerAuth) SubjectScoped ¶ added in v5.57.0
func (a *MCPServerAuth) SubjectScoped() bool
SubjectScoped reports whether the grants of the server's OAuth sign-in belong to the person rather than to one login session: spec.auth.grantScope or spec.auth.authorizationServer.grantScope is "subject", in a configuration ValidateGrantScope accepts. A configuration it refuses -- the two disagreeing, subject without type oauth or next to forwardToken or tokenExchange -- stays inert whichever path let it through (filesystem definitions are not validated), so it is session-scoped.
func (*MCPServerAuth) UsesSessionAuth ¶
func (a *MCPServerAuth) UsesSessionAuth() bool
UsesSessionAuth reports whether the server is reached with the caller's own identity — SSO token forwarding, RFC 8693 token exchange or the organization principal's token (PrincipalAudience) — so every session opens its own connection and no shared, global client may exist for it.
This is a property of the configuration alone. It must not be inferred from how the backend answered a connection probe: a backend that still accepts an anonymous initialize (for example the old pod during a rollover to an OAuth-protected release) would otherwise be handed a token-less global client that fails with 401 as soon as the protected pod takes over (issue #1135).
type MCPServerAuthAuthorizationServer ¶
type MCPServerAuthAuthorizationServer struct {
// Issuer is the OAuth 2.0 / OIDC issuer URL: the authorization server the
// sign-in runs against and the key the session's grants are filed under,
// taking precedence over the one the endpoint's RFC 9728 metadata names.
// Normalized form: HTTPS, no trailing slash, no fragment, no query.
Issuer string `yaml:"issuer" json:"issuer"`
// Scopes is the OAuth scope parameter value (RFC 6749 §3.3 wire format:
// space-separated scope tokens).
Scopes string `yaml:"scopes,omitempty" json:"scopes,omitempty"`
// AuthorizationEndpoint and TokenEndpoint describe an authorization server
// without RFC 8414 / OIDC discovery (GitHub). Both or neither; when set,
// muster performs no discovery for Issuer and assumes S256 PKCE. See the
// v1alpha1 CRD field of the same name.
AuthorizationEndpoint string `yaml:"authorizationEndpoint,omitempty" json:"authorizationEndpoint,omitempty"`
TokenEndpoint string `yaml:"tokenEndpoint,omitempty" json:"tokenEndpoint,omitempty"`
// ExpectedIssuer is the issuer identifier the authorization server puts in
// the RFC 9207 `iss` parameter when that differs from Issuer, which stays
// the grant key. Only with pinned endpoints. See the v1alpha1 CRD field.
ExpectedIssuer string `yaml:"expectedIssuer,omitempty" json:"expectedIssuer,omitempty"`
// RevocationEndpoint is the RFC 7009 endpoint a disconnect revokes a
// subject-scoped grant at, in place of the metadata's revocation_endpoint.
// See the v1alpha1 CRD field.
RevocationEndpoint string `yaml:"revocationEndpoint,omitempty" json:"revocationEndpoint,omitempty"`
// ClientCredentialsSecretRef references the Secret holding a client
// registered with this authorization server out of band; muster then uses
// it instead of CIMD or dynamic registration. See the v1alpha1 CRD field.
ClientCredentialsSecretRef *ClientCredentialsSecretRef `yaml:"clientCredentialsSecretRef,omitempty" json:"clientCredentialsSecretRef,omitempty"`
// GrantScope is "session" (default) or "subject": whether a token from
// this authorization server is bound to the login session that obtained
// it or reused by every session of the same person. See the v1alpha1 CRD
// field.
GrantScope string `yaml:"grantScope,omitempty" json:"grantScope,omitempty"`
}
MCPServerAuthAuthorizationServer pins the OAuth authorization server for an MCP server when RFC 9728 PRM discovery is unavailable.
func (*MCPServerAuthAuthorizationServer) HasPinnedEndpoints ¶
func (a *MCPServerAuthAuthorizationServer) HasPinnedEndpoints() bool
HasPinnedEndpoints reports whether the authorization server is described by explicit endpoints instead of discoverable metadata.
func (*MCPServerAuthAuthorizationServer) SubjectScoped ¶
func (a *MCPServerAuthAuthorizationServer) SubjectScoped() bool
SubjectScoped reports whether tokens from this authorization server belong to the person rather than to one login session.
type MCPServerClientCredentials ¶ added in v5.60.0
type MCPServerClientCredentials struct {
ClientID string `json:"clientId"`
ClientSecret string `json:"clientSecret"`
}
MCPServerClientCredentials is an OAuth client a caller hands core_mcpserver_create or core_mcpserver_update for spec.auth.authorizationServer. muster writes it to a Secret and never returns, logs or formats it: String and GoString redact it.
func (MCPServerClientCredentials) GoString ¶ added in v5.60.0
func (MCPServerClientCredentials) GoString() string
GoString redacts the credentials.
func (MCPServerClientCredentials) String ¶ added in v5.60.0
func (MCPServerClientCredentials) String() string
String redacts the credentials.
type MCPServerConnectorAdmin ¶ added in v5.67.0
type MCPServerConnectorAdmin interface {
// IsConnectorAdmin reports whether the caller carried by ctx may update
// the MCPServer with the given key (api.MCPServerKey).
IsConnectorAdmin(ctx context.Context, serverKey string) (bool, error)
}
MCPServerConnectorAdmin is the optional capability of the registered MCPServer manager that tells whether the caller is a connector admin of a server: whoever may update MCPServers in its namespace, the same check the write itself is subject to. The meta-tools report it so a client can offer the settings only to those who may change them.
type MCPServerCreateRequest ¶
type MCPServerCreateRequest struct {
// Name is the unique identifier for the MCP server (required).
Name string `json:"name" validate:"required"`
// Type specifies the MCP server type (required).
// Valid values: "stdio", "streamable-http", "sse"
Type string `json:"type" validate:"required"`
// ToolPrefix is prepended to all tool names from this server to avoid conflicts.
// Optional; if not specified, tools are exposed with their original names.
ToolPrefix string `json:"toolPrefix,omitempty"`
// Family declares that this MCP server is an instance of a family of
// equivalent servers, sharing exposed tool names with siblings.
Family *MCPServerFamily `json:"family,omitempty"`
// DisplayName is the human-friendly name UIs show for the server, stored
// trimmed in the DisplayNameAnnotation. Optional; blank sets no annotation.
DisplayName string `json:"displayName,omitempty"`
// Tags are stored comma-joined in the TagsAnnotation. Optional; each must
// pass ValidateTags. An empty list sets no annotation.
Tags []string `json:"tags,omitempty"`
// Description for the MCP server
Description string `json:"description,omitempty"`
// AutoStart determines whether this MCP server should be automatically started
AutoStart bool `json:"autoStart,omitempty"`
// Command specifies the executable path for stdio type servers.
// This field is required when Type is "stdio".
Command string `json:"command,omitempty"`
// Args specifies the command line arguments for stdio type servers.
// This field is only available when Type is "stdio".
Args []string `json:"args,omitempty"`
// URL is the endpoint where the remote MCP server can be reached
// This field is required when Type is "streamable-http" or "sse".
URL string `json:"url,omitempty"`
// Env contains environment variables to set for the MCP server.
Env map[string]string `json:"env,omitempty"`
// Headers contains HTTP headers to send with requests to remote MCP servers.
// This field is only relevant when Type is "streamable-http" or "sse".
Headers map[string]string `json:"headers,omitempty"`
// HeadersFrom lists headers whose values muster reads from a Secret in
// the server's own namespace when it connects.
HeadersFrom []MCPServerHeaderFrom `json:"headersFrom,omitempty"`
// RequestMeta contains entries added to the `params._meta` object of every
// outbound JSON-RPC request that carries `params`.
RequestMeta map[string]string `json:"requestMeta,omitempty"`
// Meta is the former name of RequestMeta, still accepted from callers and
// written as RequestMeta. Setting both is refused.
Meta map[string]string `json:"meta,omitempty"`
// Timeout bounds every operation on the server in seconds, a tool call
// included, for every type (default 30)
Timeout int `json:"timeout,omitempty"`
// Progress configures how progress the server reports on a tool call
// affects that call's budget.
Progress *MCPServerProgress `json:"progress,omitempty"`
// Auth configures authentication behavior for this MCP server.
// This is only relevant for remote servers (streamable-http or sse).
Auth *MCPServerAuth `json:"auth,omitempty"`
// ClientCredentials is the client of auth.authorizationServer, written
// as the caller to a Secret owned by the server. Write-only.
ClientCredentials *MCPServerClientCredentials `json:"clientCredentials,omitempty"`
}
type MCPServerDetectRequest ¶
type MCPServerDetectRequest struct {
// URL is the endpoint to probe (required).
URL string `json:"url" validate:"required"`
// Headers contains HTTP headers to send with the probe requests,
// mirroring the headers the registered server would be configured with.
Headers map[string]string `json:"headers,omitempty"`
// Timeout bounds the whole detection run in seconds (default 10).
Timeout int `json:"timeout,omitempty"`
}
MCPServerDetectRequest represents a request to probe a remote MCP server URL and detect which transport (streamable-http or sse) it speaks.
type MCPServerFamily ¶
type MCPServerFamily struct {
// Name is the family identifier shared across instances.
Name string `yaml:"name" json:"name"`
// InstanceArg names the required parameter callers use to select which
// family member handles the tool call.
InstanceArg string `yaml:"instanceArg" json:"instanceArg"`
}
MCPServerFamily groups equivalent MCP server instances under a shared exposed surface. Name and InstanceArg are both required when set.
type MCPServerHeaderFrom ¶ added in v5.41.0
type MCPServerHeaderFrom struct {
// Name is the HTTP header name.
Name string `yaml:"name" json:"name"`
// ValueFrom names the Secret key that holds the value.
ValueFrom MCPServerValueSource `yaml:"valueFrom" json:"valueFrom"`
}
MCPServerHeaderFrom is an HTTP header whose value muster reads from a Secret in the server's own namespace when it connects (spec.headersFrom). It carries the reference only: the value never enters a definition.
type MCPServerInfo ¶
type MCPServerInfo struct {
// Name is the unique identifier for this MCP server instance.
Name string `json:"name"`
// Namespace is the Kubernetes namespace of the MCPServer resource.
// Empty in filesystem mode.
Namespace string `json:"namespace,omitempty"`
// Key is what muster registers, exposes and stores a server outside
// muster's namespace under (MCPServerKey): "<namespace>/<name>". It is
// empty for a server of muster's namespace and in filesystem mode, whose
// key is its name. The MCPServer manager sets it; use ServerKey. The
// core_service_*, core_mcpserver_get and core_auth_* tools take the key.
Key string `json:"key,omitempty"`
// UID is the Kubernetes UID of the MCPServer resource (see
// MCPServer.UID). Empty in filesystem mode.
UID string `json:"-"`
// Generation is the MCPServer resource's metadata.generation: an approval
// binds it, so a connector changed since asks again, and
// core_mcpserver_set_approval takes it as expectedGeneration to refuse a
// write over a change made since the caller read it. Zero in filesystem
// mode.
Generation int64 `json:"generation,omitempty"`
// CreatedAt is the creation time of the MCPServer resource (see
// MCPServer.CreatedAt). Zero in filesystem mode.
CreatedAt time.Time `json:"-"`
// Labels mirrors the MCPServer resource's metadata.labels in both storage
// modes. Toolset presets select servers by label (label: rules, #1168) —
// notably agent-platform.giantswarm.io/tool-group — and read this live.
Labels map[string]string `json:"labels,omitempty"`
// Type indicates the execution model for this server (stdio, streamable-http, or sse).
Type string `json:"type"`
// DisplayName is the server's human-friendly name, read from the
// DisplayNameAnnotation. Empty when the annotation is not set.
DisplayName string `json:"displayName,omitempty"`
// Tags are the server's free-form tags, read from the TagsAnnotation with
// ParseTags (malformed entries dropped). Empty when none are set.
Tags []string `json:"tags,omitempty"`
// Description provides a human-readable description of the server's purpose and capabilities.
Description string `json:"description,omitempty"`
// AutoStart determines whether this MCP server should be automatically started
AutoStart bool `json:"autoStart,omitempty"`
// Suspended declares the desired lifecycle state of this server's service.
// When true, the reconciler stops the service and refuses to start it
// until the field is set back to false (issue #1055).
Suspended bool `json:"suspended,omitempty"`
// RestartRequestedAt requests a one-shot restart of this server's service.
// The reconciler acts only when it differs from LastRestartedAt.
RestartRequestedAt *time.Time `json:"restartRequestedAt,omitempty"`
// LastRestartedAt mirrors the RestartRequestedAt value most recently
// processed by the reconciler (from the CR status).
LastRestartedAt *time.Time `json:"lastRestartedAt,omitempty"`
// Command specifies the executable path for stdio type servers.
Command string `json:"command,omitempty"`
// Args specifies the command line arguments for stdio type servers.
Args []string `json:"args,omitempty"`
// URL is the endpoint where the remote MCP server can be reached
URL string `json:"url,omitempty"`
// Env contains environment variables to set for the MCP server.
Env map[string]string `json:"env,omitempty"`
// Headers contains HTTP headers to send with requests to remote MCP servers.
Headers map[string]string `json:"headers,omitempty"`
// HeadersFrom lists headers whose values muster reads from a Secret when
// it connects; references only.
HeadersFrom []MCPServerHeaderFrom `json:"headersFrom,omitempty"`
// RequestMeta contains entries added to the `params._meta` object of every
// outbound JSON-RPC request that carries `params`.
RequestMeta map[string]string `json:"requestMeta,omitempty"`
// Auth configures authentication behavior for this MCP server.
Auth *MCPServerAuth `json:"auth,omitempty"`
// Timeout bounds every operation on the server in seconds -- each
// request, a tool call included, for every type; for a remote server also
// the connect and the health probe (default 30).
Timeout int `json:"timeout,omitempty"`
// Progress configures how progress the server reports on a tool call
// affects that call's budget.
Progress *MCPServerProgress `json:"progress,omitempty"`
// Approval is the server's spec.approval: per tool, whether a call runs,
// asks first or is refused. Nil when the server has none (every tool
// Allow, not reviewed).
Approval *MCPServerApproval `json:"approval,omitempty"`
// ToolPrefix is an optional prefix for tool names.
ToolPrefix string `json:"toolPrefix,omitempty"`
// Family declares that this MCP server is an instance of a family of
// equivalent servers, sharing exposed tool names with siblings.
Family *MCPServerFamily `json:"family,omitempty"`
// Error contains any error message from recent server operations.
// This field is populated if the server is in an error state.
Error string `json:"error,omitempty"`
// State represents the high-level infrastructure state of the MCP server.
// This is the primary status indicator.
// Possible values for stdio servers: Running, Starting, Stopped, Failed
// Possible values for remote servers: Connected, Connecting, Disconnected, Failed
// Note: State reflects infrastructure availability only. Per-user session state
// (auth status, connection status) is tracked in the Session Registry.
State string `json:"state,omitempty"`
// ProtocolVersion is the MCP revision this backend answered with during the
// handshake. It can be older than ClientProtocolVersion: a backend that
// supports only an earlier revision answers with that one. Empty when the
// server has no connected client.
ProtocolVersion string `json:"protocolVersion,omitempty"`
// StatusMessage provides a user-friendly, actionable message about the server's status.
// This field is populated based on the server's state and error information.
// Examples:
// - "Server is running normally"
// - "Authentication required - run: muster auth login --server <name>"
// - "Cannot reach server - check network connectivity"
// - "Certificate error - verify TLS configuration"
StatusMessage string `json:"statusMessage,omitempty"`
// ConsecutiveFailures tracks the number of consecutive connection failures.
// Used for exponential backoff and to identify unreachable servers.
ConsecutiveFailures int `json:"consecutiveFailures,omitempty"`
// LastAttempt indicates when the last connection attempt was made.
LastAttempt *time.Time `json:"lastAttempt,omitempty"`
// NextRetryAfter indicates the earliest time when the next retry should be attempted.
NextRetryAfter *time.Time `json:"nextRetryAfter,omitempty"`
// LastFailureHTTPStatus is the HTTP status the endpoint answered the most
// recent failed connection attempt with (e.g. 504 from a gateway in front
// of the server). 0 when the failure carried no HTTP response or the last
// attempt succeeded.
LastFailureHTTPStatus int `json:"lastFailureHTTPStatus,omitempty"`
// SessionStatus represents the per-user session connection status.
// This is only populated when the request includes a session context.
// Possible values: connected, disconnected, pending_auth, failed
// Empty if no session context is available.
SessionStatus string `json:"sessionStatus,omitempty"`
// SessionAuth represents the per-user authentication status for this server.
// This is only populated when the request includes a session context.
// Possible values: authenticated, auth_required, token_expired, unknown
// Empty if no session context is available or auth is not required.
SessionAuth string `json:"sessionAuth,omitempty"`
// ToolsCount is the number of tools available from this server for the current session.
// This is session-specific as OAuth-protected servers may expose different tools
// based on user permissions.
ToolsCount int `json:"toolsCount,omitempty"`
// ResourcesCount is the number of resources available from this server for
// the current session, session-specific for the same reason as ToolsCount.
ResourcesCount int `json:"resourcesCount,omitempty"`
// PromptsCount is the number of prompts available from this server for the
// current session, session-specific for the same reason as ToolsCount.
PromptsCount int `json:"promptsCount,omitempty"`
// ConnectedAt indicates when the current session connected to this server.
// Only populated if there is an active session connection.
ConnectedAt *time.Time `json:"connectedAt,omitempty"`
// RegisteredBy is the authenticated subject that registered this server,
// read from the RegisteredByAnnotation. Empty when the server was created
// without an authenticated context (e.g. GitOps-applied CRs).
RegisteredBy string `json:"registeredBy,omitempty"`
// RegisteredByEmail is the email claim of the identity that registered
// this server, read from the RegisteredByEmailAnnotation. Display metadata
// only — RegisteredBy is the stable identifier. Empty when the token
// carried no email claim.
RegisteredByEmail string `json:"registeredByEmail,omitempty"`
}
MCPServerInfo contains consolidated MCP server information for API responses. This type is used when returning server information through the API, providing a flattened view of server configuration and runtime state that is convenient for clients and user interfaces.
func LastObservedMCPServer ¶ added in v5.67.0
func LastObservedMCPServer(key string) (*MCPServerInfo, time.Time, bool)
LastObservedMCPServer returns the registered manager's last observed definition of a server; ok is false without a manager offering it.
func LastObservedMCPServers ¶ added in v5.67.0
func LastObservedMCPServers() ([]MCPServerInfo, time.Time, bool)
LastObservedMCPServers returns the registered manager's last observed definitions of all servers; ok is false without a manager offering them or while it observed none.
func (MCPServerInfo) ServerKey ¶ added in v5.47.0
func (i MCPServerInfo) ServerKey() string
ServerKey returns the key muster registers the server's service under: Key, or Name when the manager set no key (a server of muster's namespace).
func (MCPServerInfo) ToMCPServer ¶
func (i MCPServerInfo) ToMCPServer() *MCPServer
ToMCPServer converts the API/reconciler view of a server into the service-layer configuration struct.
One definition on purpose. The orchestrator's registration path and the reconciler's update path both need this conversion, they cannot import each other, and while each kept its own copy a new spec field reached the service through one path and was silently dropped by the other.
type MCPServerLastObserved ¶ added in v5.67.0
type MCPServerLastObserved interface {
// LastObservedMCPServer returns the last definition read of the server
// key names and when it was read; ok is false for a server never read,
// or one read as deleted since.
LastObservedMCPServer(key string) (info *MCPServerInfo, observedAt time.Time, ok bool)
// LastObservedMCPServers returns the last definition of every server
// read and not since read as deleted, and when the oldest was read; ok
// is false when none was.
LastObservedMCPServers() (infos []MCPServerInfo, oldest time.Time, ok bool)
}
MCPServerLastObserved is the optional capability of an MCPServer manager that remembers the last definition of each server it read from its definition source (the reconciler's reads on every watch event and resync, and every live read since). A server the source reported deleted is forgotten.
type MCPServerLifecycleAsCaller ¶
type MCPServerLifecycleAsCaller interface {
StartMCPServerAsCaller(ctx context.Context, name string) (result *CallToolResult, handled bool, err error)
StopMCPServerAsCaller(ctx context.Context, name string) (result *CallToolResult, handled bool, err error)
RestartMCPServerAsCaller(ctx context.Context, name string) (result *CallToolResult, handled bool, err error)
}
MCPServerLifecycleAsCaller is the optional capability the registered MCPServer manager gains when writes-as-caller is enabled (issue #1057): lifecycle actions on MCPServer-backed services become CR spec writes performed with the caller's own identity — authorized by k8s RBAC and audited by the apiserver — instead of orchestrator mutations with muster's privilege. handled=false means the caller must fall back to the imperative path (flag off, or the name is a non-MCPServer service such as muster's own aggregator); it is always accompanied by a nil result and a nil error.
The implementing adapter pins this interface at compile time so a signature drift cannot silently fail the type assertion and reopen the privileged imperative path.
type MCPServerManagerHandler ¶
type MCPServerManagerHandler interface {
// ListMCPServers returns information about all registered MCP servers.
// This includes both configuration and runtime state information for each server.
//
// An error means the set could not be read. That is not the same as an
// empty set, and a caller must not treat it as one.
//
// Returns:
// - []MCPServerInfo: Slice of server information (empty if no servers exist)
// - error: nil on success, or an error if the servers could not be listed
ListMCPServers(ctx context.Context) ([]MCPServerInfo, error)
// GetMCPServer retrieves detailed information about a specific MCP server.
// This includes both configuration and runtime state for the requested server.
//
// The read reaches the definition source, so the caller's context bounds it.
//
// Args:
// - name: The unique name of the MCP server to retrieve
//
// Returns:
// - *MCPServerInfo: Server information, or nil if server not found
// - error: nil on success, or an error if the server could not be retrieved
GetMCPServer(ctx context.Context, name string) (*MCPServerInfo, error)
// ToolProvider interface for exposing MCP server management tools.
// This allows MCP server operations to be performed through the aggregator
// tool system, enabling programmatic and user-driven server management.
ToolProvider
}
MCPServerManagerHandler defines the interface for MCP server management operations. This interface provides the core functionality for managing MCP server lifecycle, configuration, and tool availability. It also implements the ToolProvider interface to expose MCP server management capabilities as tools that can be called through the aggregator.
func GetMCPServerManager ¶
func GetMCPServerManager() MCPServerManagerHandler
GetMCPServerManager returns the registered MCP server manager handler. This provides access to MCP server definition management and lifecycle operations.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- MCPServerManagerHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
Example:
manager := api.GetMCPServerManager()
if manager == nil {
return fmt.Errorf("MCP server manager not available")
}
servers, err := manager.ListMCPServers(ctx)
type MCPServerProgress ¶ added in v5.40.0
type MCPServerProgress struct {
// MaxDuration bounds, in seconds, a tool call kept going by progress:
// up to it, each progress notification of a call whose caller asked for
// progress restarts Timeout. Zero means
// DefaultProgressMaxDurationSeconds.
MaxDuration int `yaml:"maxDuration,omitempty" json:"maxDuration,omitempty"`
}
MCPServerProgress configures how progress the server reports on a tool call affects that call's budget.
type MCPServerSigV4 ¶
type MCPServerSigV4 struct {
// Region is the SigV4 signing region.
Region string `yaml:"region" json:"region"`
// Service is the SigV4 signing service name.
Service string `yaml:"service,omitempty" json:"service,omitempty"`
// RoleARN is the role assumed before signing, if any.
RoleARN string `yaml:"roleArn,omitempty" json:"roleArn,omitempty"`
}
MCPServerSigV4 configures AWS Signature Version 4 signing for an MCP server. See the v1alpha1 CRD type of the same name for full semantics.
type MCPServerType ¶
type MCPServerType string
MCPServerType defines the execution model for an MCP server. This determines how the server process is managed and what configuration options are available for server deployment.
const ( // MCPServerTypeStdio indicates that the MCP server should be run as a local process. // Stdio servers are started using the configured command and arguments, // with communication typically happening over stdin/stdout. MCPServerTypeStdio MCPServerType = "stdio" // MCPServerTypeStreamableHTTP indicates that the MCP server should be accessed via HTTP. // StreamableHTTP servers are accessed via HTTP/HTTPS endpoints with streaming support. MCPServerTypeStreamableHTTP MCPServerType = "streamable-http" // MCPServerTypeSSE indicates that the MCP server should be accessed via Server-Sent Events. // SSE servers are accessed via HTTP/HTTPS endpoints using Server-Sent Events for communication. MCPServerTypeSSE MCPServerType = "sse" )
func (MCPServerType) IsRemote ¶
func (t MCPServerType) IsRemote() bool
IsRemote returns true if the server type is a remote (HTTP-based) server. Remote servers use connected/disconnected states rather than running/stopped.
type MCPServerUpdateRequest ¶
type MCPServerUpdateRequest struct {
// Name of the MCP server to update (required).
Name string `json:"name" validate:"required"`
// Type can be changed, but may require significant reconfiguration.
Type string `json:"type" validate:"required"`
// ToolPrefix can be updated, affecting tool naming.
ToolPrefix string `json:"toolPrefix,omitempty"`
// Family declares that this MCP server is an instance of a family of
// equivalent servers, sharing exposed tool names with siblings.
Family *MCPServerFamily `json:"family,omitempty"`
// DisplayName sets the DisplayNameAnnotation, trimmed. Tri-state: omitting
// it keeps the current annotation, a blank value removes it.
DisplayName *string `json:"displayName,omitempty"`
// Tags replace the TagsAnnotation. Tri-state: omitting them keeps the
// current tags, an empty list removes them.
Tags *[]string `json:"tags,omitempty"`
// Description for the MCP server
Description string `json:"description,omitempty"`
// AutoStart determines whether this MCP server should be automatically
// started. Tri-state: omitting it keeps the current value.
AutoStart *bool `json:"autoStart,omitempty"`
// Command specifies the executable path for stdio type servers.
Command string `json:"command,omitempty"`
// Args specifies the command line arguments for stdio type servers.
Args []string `json:"args,omitempty"`
// URL is the endpoint where the remote MCP server can be reached
URL string `json:"url,omitempty"`
// Env contains environment variables to set for the MCP server.
Env map[string]string `json:"env,omitempty"`
// Headers contains HTTP headers to send with requests to remote MCP servers.
Headers map[string]string `json:"headers,omitempty"`
// HeadersFrom lists headers whose values muster reads from a Secret in
// the server's own namespace when it connects.
HeadersFrom []MCPServerHeaderFrom `json:"headersFrom,omitempty"`
// RequestMeta contains entries added to the `params._meta` object of every
// outbound JSON-RPC request that carries `params`.
RequestMeta map[string]string `json:"requestMeta,omitempty"`
// Meta is the former name of RequestMeta, still accepted from callers and
// written as RequestMeta. Setting both is refused.
Meta map[string]string `json:"meta,omitempty"`
// Timeout bounds every operation on the server in seconds, a tool call
// included, for every type (default 30)
Timeout int `json:"timeout,omitempty"`
// Progress configures how progress the server reports on a tool call
// affects that call's budget.
Progress *MCPServerProgress `json:"progress,omitempty"`
// Auth configures authentication behavior for this MCP server.
Auth *MCPServerAuth `json:"auth,omitempty"`
// ClientCredentials replaces the client of auth.authorizationServer: a
// new Secret owned by the server, written as the caller. Write-only.
ClientCredentials *MCPServerClientCredentials `json:"clientCredentials,omitempty"`
// ClearClientCredentials drops the client stored with ClientCredentials:
// the generated client Secret reference goes, auth.authorizationServer
// stays. Not with ClientCredentials or an explicit reference.
ClearClientCredentials bool `json:"clearClientCredentials,omitempty"`
// Suspended declares the desired lifecycle state of the server's service.
// Tri-state: omitting it keeps the current value, so an unrelated update
// (description, headers) does not silently resume a server that was
// stopped through the CR-driven core_service_stop (issue #1057).
Suspended *bool `json:"suspended,omitempty"`
// RestartRequestedAt requests a one-shot restart of the server's service
// (RFC 3339 timestamp). Only applied when set (issue #1055).
RestartRequestedAt *time.Time `json:"restartRequestedAt,omitempty"`
}
MCPServerUpdateRequest represents a request to update an existing MCP server definition. All fields except Name can be modified. Changes may require server restart.
type MCPServerValidateRequest ¶
type MCPServerValidateRequest struct {
// Name for validation (required).
Name string `json:"name" validate:"required"`
// Type for validation (required).
Type string `json:"type" validate:"required"`
// ToolPrefix for validation.
ToolPrefix string `json:"toolPrefix,omitempty"`
// Family for validation.
Family *MCPServerFamily `json:"family,omitempty"`
// AutoStart determines whether this MCP server should be automatically started
AutoStart bool `json:"autoStart,omitempty"`
// Command specifies the executable path for stdio type servers.
Command string `json:"command,omitempty"`
// Args specifies the command line arguments for stdio type servers.
Args []string `json:"args,omitempty"`
// URL is the endpoint where the remote MCP server can be reached
URL string `json:"url,omitempty"`
// Env contains environment variables to set for the MCP server.
Env map[string]string `json:"env,omitempty"`
// Headers contains HTTP headers to send with requests to remote MCP servers.
Headers map[string]string `json:"headers,omitempty"`
// HeadersFrom lists headers whose values muster reads from a Secret in
// the server's own namespace when it connects.
HeadersFrom []MCPServerHeaderFrom `json:"headersFrom,omitempty"`
// RequestMeta contains entries added to the `params._meta` object of every
// outbound JSON-RPC request that carries `params`.
RequestMeta map[string]string `json:"requestMeta,omitempty"`
// Meta is the former name of RequestMeta, still accepted from callers and
// written as RequestMeta. Setting both is refused.
Meta map[string]string `json:"meta,omitempty"`
// Timeout bounds every operation on the server in seconds, a tool call
// included, for every type (default 30)
Timeout int `json:"timeout,omitempty"`
// Progress configures how progress the server reports on a tool call
// affects that call's budget.
Progress *MCPServerProgress `json:"progress,omitempty"`
// DisplayName for validation, as on create.
DisplayName string `json:"displayName,omitempty"`
// Tags for validation, as on create.
Tags []string `json:"tags,omitempty"`
// Description for validation and documentation.
Description string `json:"description,omitempty"`
// Auth configures authentication behavior for this MCP server.
Auth *MCPServerAuth `json:"auth,omitempty"`
}
MCPServerValidateRequest represents a request to validate an MCP server definition without creating it. Validates configuration consistency and tool availability.
type MCPServerValueSource ¶ added in v5.41.0
type MCPServerValueSource struct {
// Type is the kind of object that holds the value; only "Secret".
Type string `yaml:"type" json:"type"`
// Name is the name of the Secret.
Name string `yaml:"name" json:"name"`
// Key is the key in the Secret's data.
Key string `yaml:"key" json:"key"`
}
MCPServerValueSource names a key of a Secret in the server's own namespace. It has no namespace field on purpose.
type MCPServerVisibilityHandler ¶ added in v5.47.0
type MCPServerVisibilityHandler interface {
// CallerVisibility returns the view of the caller whose ID token ctx
// carries. It fails closed: no token, or a token the API server does not
// accept, sees no server.
CallerVisibility(ctx context.Context) ServerVisibility
// LoginAudience is the audience muster's own login must ask for, so the
// API server accepts the session's ID token.
LoginAudience() string
}
MCPServerVisibilityHandler answers which MCP servers the caller of a request may see. It is registered only when muster serves MCPServer objects of every namespace (mcpServerNamespaceSelector); without it every caller sees every server, as before.
func GetMCPServerVisibility ¶ added in v5.47.0
func GetMCPServerVisibility() MCPServerVisibilityHandler
GetMCPServerVisibility returns the registered visibility handler, or nil.
type MetaToolsDataProvider ¶
type MetaToolsDataProvider interface {
// ListToolsForContext returns all available tools for the current session context.
// The returned tools are session-aware based on authentication state.
//
// Args:
// - ctx: Context containing session information
//
// Returns:
// - []mcp.Tool: List of available tools for the session
ListToolsForContext(ctx context.Context) []mcp.Tool
// CallToolInternal executes a tool by name with the provided arguments.
// This bypasses the MCP protocol layer and calls tools directly.
//
// Args:
// - ctx: Context for the operation
// - name: Name of the tool to execute
// - args: Arguments to pass to the tool
//
// Returns:
// - *mcp.CallToolResult: The result of the tool execution
// - error: Error if execution fails
CallToolInternal(ctx context.Context, name string, args map[string]interface{}) (*mcp.CallToolResult, error)
// ListResourcesForContext returns all available resources for the current session context.
// The returned resources are session-aware based on authentication state.
//
// Args:
// - ctx: Context containing session information
//
// Returns:
// - []ResourceOrigin: Available resources for the session, each tagged with its source server
ListResourcesForContext(ctx context.Context) []ResourceOrigin
// ReadResource retrieves the contents of a resource by URI.
//
// Args:
// - ctx: Context for the operation
// - uri: URI of the resource to retrieve
//
// Returns:
// - *mcp.ReadResourceResult: The resource contents
// - error: Error if retrieval fails
ReadResource(ctx context.Context, uri, serverName string) (*mcp.ReadResourceResult, error)
// ListPromptsForContext returns all available prompts for the current session context.
// The returned prompts are session-aware based on authentication state.
//
// Args:
// - ctx: Context containing session information
//
// Returns:
// - []PromptOrigin: Available prompts for the session, each tagged with its source server
ListPromptsForContext(ctx context.Context) []PromptOrigin
// GetPrompt executes a prompt with the provided arguments.
//
// Args:
// - ctx: Context for the operation
// - name: Name of the prompt to execute
// - args: Arguments to pass to the prompt (as string values)
//
// Returns:
// - *mcp.GetPromptResult: The prompt result with messages
// - error: Error if execution fails
GetPrompt(ctx context.Context, name string, args map[string]string) (*mcp.GetPromptResult, error)
// ListServersRequiringAuth returns a list of servers that require authentication
// for the current session. This enables the list_tools meta-tool to inform users
// about servers that are available but require authentication before their tools
// become visible.
//
// Args:
// - ctx: Context containing session information
//
// Returns:
// - []ServerAuthInfo: List of servers requiring authentication
ListServersRequiringAuth(ctx context.Context) []ServerAuthInfo
// SignedOutOwnerOf returns the server awaiting the session's sign-in
// that a call to the exposed tool name with args would be routed to: the
// member a family call's instance argument selects, else the server whose
// tool prefix is the longest the name carries. ok is false when that
// server is not awaiting sign-in or no single server owns the name.
SignedOutOwnerOf(ctx context.Context, name string, args map[string]any) (owner ServerAuthInfo, ok bool)
// AnswerSignIn starts the session's sign-in to the server and runs no
// tool. It returns the auth_required challenge with the sign-in link, or
// connected when a stored grant connected the session without a
// browser; the caller then makes the call it was answering as any other.
AnswerSignIn(ctx context.Context, server string) (result *mcp.CallToolResult, connected bool, err error)
}
MetaToolsDataProvider provides data access for meta-tools. This interface is implemented by the aggregator and used by the metatools adapter to access tools, resources, and prompts from the aggregated servers.
The interface is designed to support session-scoped visibility, where different sessions may see different tools based on their authentication state (OAuth). Context is used to pass session information for proper scoping.
func GetMetaToolsDataProvider ¶
func GetMetaToolsDataProvider() MetaToolsDataProvider
GetMetaToolsDataProvider returns the registered meta-tools data provider. This provides access to the underlying data layer (typically the aggregator) for listing and accessing tools, resources, and prompts.
Returns nil if no provider has been registered yet.
Returns:
- MetaToolsDataProvider: The registered provider, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
type MetaToolsHandler ¶
type MetaToolsHandler interface {
// ListTools returns all available tools for the current session.
// The returned tools are session-aware based on authentication state.
//
// Args:
// - ctx: Context containing session information
//
// Returns:
// - []mcp.Tool: List of available tools
// - error: Error if listing fails
ListTools(ctx context.Context) ([]mcp.Tool, error)
// CallTool executes a tool by name with the provided arguments.
// This is the primary interface for tool execution through meta-tools.
//
// Args:
// - ctx: Context for the operation
// - name: Name of the tool to execute
// - args: Arguments to pass to the tool
//
// Returns:
// - *mcp.CallToolResult: The result of the tool execution
// - error: Error if execution fails
CallTool(ctx context.Context, name string, args map[string]interface{}) (*mcp.CallToolResult, error)
// ListResources returns all available resources for the current session.
// The returned resources are session-aware based on authentication state.
//
// Args:
// - ctx: Context containing session information
//
// Returns:
// - []mcp.Resource: List of available resources
// - error: Error if listing fails
ListResources(ctx context.Context) ([]ResourceOrigin, error)
// GetResource retrieves the contents of a resource by URI.
//
// Args:
// - ctx: Context for the operation
// - uri: URI of the resource to retrieve
//
// Returns:
// - *mcp.ReadResourceResult: The resource contents
// - error: Error if retrieval fails
GetResource(ctx context.Context, uri, serverName string) (*mcp.ReadResourceResult, error)
// ListPrompts returns all available prompts for the current session.
// The returned prompts are session-aware based on authentication state.
//
// Args:
// - ctx: Context containing session information
//
// Returns:
// - []mcp.Prompt: List of available prompts
// - error: Error if listing fails
ListPrompts(ctx context.Context) ([]PromptOrigin, error)
// GetPrompt executes a prompt with the provided arguments.
//
// Args:
// - ctx: Context for the operation
// - name: Name of the prompt to execute
// - args: Arguments to pass to the prompt (as string values)
//
// Returns:
// - *mcp.GetPromptResult: The prompt result with messages
// - error: Error if execution fails
GetPrompt(ctx context.Context, name string, args map[string]string) (*mcp.GetPromptResult, error)
// ListServersRequiringAuth returns a list of servers that require authentication
// for the current session. This enables the list_tools meta-tool to inform users
// about servers that are available but require authentication.
//
// Args:
// - ctx: Context containing session information
//
// Returns:
// - []ServerAuthInfo: List of servers requiring authentication
ListServersRequiringAuth(ctx context.Context) []ServerAuthInfo
// SignedOutOwnerOf returns the server awaiting the session's sign-in
// that a call to the exposed tool name with args would be routed to.
SignedOutOwnerOf(ctx context.Context, name string, args map[string]any) (owner ServerAuthInfo, ok bool)
// AnswerSignIn starts the session's sign-in to the server and runs no
// tool: the auth_required challenge, or connected when a stored grant
// connected the session.
AnswerSignIn(ctx context.Context, server string) (result *mcp.CallToolResult, connected bool, err error)
}
MetaToolsHandler provides server-side meta-tool functionality for AI assistants. It enables tool discovery, execution, and resource/prompt access through a unified interface that can be used by the metatools package.
The handler provides the data access layer that the metatools package handlers use to retrieve and manipulate tools, resources, and prompts. It abstracts the underlying aggregator implementation, following the API service locator pattern.
This interface will be implemented by the aggregator or a dedicated adapter in a future integration issue.
func GetMetaTools ¶
func GetMetaTools() MetaToolsHandler
GetMetaTools returns the registered meta-tools handler. This provides access to server-side meta-tool functionality for tool discovery, execution, and resource/prompt access.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- MetaToolsHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
Example:
metaToolsHandler := api.GetMetaTools()
if metaToolsHandler == nil {
return fmt.Errorf("meta-tools handler not available")
}
tools, err := metaToolsHandler.ListTools(ctx)
type MusterVisibilityHandler ¶ added in v5.67.0
type MusterVisibilityHandler interface {
// MusterVisibility is the view of muster calling as itself: the servers
// of muster's own namespace.
MusterVisibility() ServerVisibility
}
MusterVisibilityHandler is implemented by an MCPServerVisibilityHandler that knows which servers muster itself may see. A handler without it gives muster no server: the view fails closed.
type NotFoundError ¶
type NotFoundError struct {
// ResourceType categorizes the type of resource that was not found
// (e.g., "workflow", "service", "MCP server")
ResourceType string
// ResourceName is the specific identifier of the resource that was not found
ResourceName string
// Message provides a custom error message if the default format is insufficient
Message string
}
NotFoundError represents a resource not found error with contextual information. This standardized error type provides consistent error handling across all API operations for cases where requested resources don't exist in the system.
The error includes resource type and name for precise error reporting and supports custom error messages for specific use cases.
func NewNotFoundError ¶
func NewNotFoundError(resourceType, resourceName string) *NotFoundError
NewNotFoundError creates a new NotFoundError with the specified resource type and name. This is the standard way to create not found errors throughout the API.
Args:
- resourceType: The category of resource (e.g., "workflow", "service")
- resourceName: The specific identifier of the resource
Returns:
- *NotFoundError: A new NotFoundError instance
Example:
return api.NewNotFoundError("workflow", "deploy-app")
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
Error implements the error interface for NotFoundError. Returns either the custom message if provided, or a formatted default message using the resource type and name.
Returns:
- string: The error message describing the not found condition
type OAuthHandler ¶
type OAuthHandler interface {
// IsEnabled returns whether OAuth proxy functionality is active.
IsEnabled() bool
// GetToken retrieves a valid token for the given session and server.
// Returns nil if no valid token exists.
GetToken(sessionID, serverName string) *OAuthToken
// GetTokenByIssuer retrieves a valid token for the given session and issuer.
// This is used for SSO when we have the issuer from a 401 response.
GetTokenByIssuer(sessionID, issuer string) *OAuthToken
// GetFullTokenByIssuer retrieves the full token (including ID token if available)
// for the given session and issuer. Returns nil if no valid token exists.
// The IDToken field may be empty if the token was obtained without an ID token.
GetFullTokenByIssuer(sessionID, issuer string) *OAuthToken
// FindTokenWithIDToken searches for any token in the session that has an ID token.
// This is used as a fallback when the muster issuer is not explicitly configured.
// Returns the first token found with an ID token, or nil if none exists.
FindTokenWithIDToken(sessionID string) *OAuthToken
// StoreToken persists a token for the given session and issuer.
// The userID is stored alongside for reverse-lookup (e.g., "sign out everywhere").
// This is the write path used by mcp-go's transport.TokenStore.SaveToken()
// after a successful token refresh.
StoreToken(sessionID, userID, issuer string, token *OAuthToken)
// ClearTokenByIssuer removes all tokens for a given session and issuer.
// This is used to clear invalid/expired tokens before requesting fresh authentication.
ClearTokenByIssuer(sessionID, issuer string)
// DeleteTokensByUser removes all downstream tokens for a given user across all sessions.
// This is used during "sign out everywhere" to clear all server-side token state.
DeleteTokensByUser(userID string)
// DeleteTokensBySession removes all downstream tokens for a given session.
// This is used during per-session logout via token family revocation.
DeleteTokensBySession(sessionID string)
// CreateAuthChallenge creates an authentication challenge for a 401 response.
// Returns the challenge containing the auth URL for the user to visit.
CreateAuthChallenge(ctx context.Context, params AuthChallengeParams) (*AuthChallenge, error)
// GetClientCredentialsForIssuer returns the client_id and client_secret
// the OAuth flows use against the given issuer (the CIMD URL, or
// DCR-issued credentials), without triggering a new registration. Used
// to configure transport-level token refresh so it presents the same
// client identification the token was issued under.
GetClientCredentialsForIssuer(ctx context.Context, issuer string) (clientID, clientSecret string)
// SignInFinished reports whether the OAuth callback of the sign-in a
// challenge's start URL names ran to its end for the session, whatever
// its outcome. It reads state shared by every replica.
SignInFinished(ctx context.Context, sessionID, startURL string) bool
// GetHTTPHandler returns the HTTP handler for OAuth callback endpoints.
GetHTTPHandler() http.Handler
// GetCallbackPath returns the configured callback path (e.g., "/oauth/proxy/callback").
GetCallbackPath() string
// GetStartPath returns the path of the OAuth proxy start endpoint
// (e.g., "/oauth/proxy/start"), which auth challenges point the browser at.
GetStartPath() string
// GetStartHandler returns the HTTP handler for the OAuth proxy start endpoint.
GetStartHandler() http.HandlerFunc
// GetCIMDPath returns the path for serving the CIMD (e.g., "/.well-known/oauth-client.json").
GetCIMDPath() string
// ShouldServeCIMD returns true if muster should serve its own CIMD.
ShouldServeCIMD() bool
// GetCIMDHandler returns the HTTP handler for serving the CIMD.
GetCIMDHandler() http.HandlerFunc
// RegisterServer registers OAuth configuration for a remote MCP server.
RegisterServer(serverName, issuer, scope string)
// SetAuthCompletionCallback sets the callback to be called after successful authentication.
// The aggregator uses this to establish session connections after browser OAuth completes.
SetAuthCompletionCallback(callback AuthCompletionCallback)
// ExchangeTokenForRemoteCluster exchanges a local token for one valid on a remote cluster.
// This implements RFC 8693 Token Exchange for cross-cluster SSO scenarios.
//
// Args:
// - ctx: Context for the operation
// - localToken: The local ID token to exchange
// - userID: The user's unique identifier (from validated JWT 'sub' claim)
// - config: Token exchange configuration for the remote cluster
//
// Returns the exchanged access token, or an error if exchange fails.
ExchangeTokenForRemoteCluster(ctx context.Context, localToken, userID string, config *TokenExchangeConfig) (string, error)
// Stop stops the OAuth handler and cleans up resources.
Stop()
}
OAuthHandler defines the interface for OAuth proxy functionality. This handler manages OAuth authentication flows for remote MCP servers, including token storage, authentication challenges, and callback handling.
The OAuth handler acts as a proxy, managing OAuth flows on behalf of users without exposing sensitive tokens to the Muster Agent.
Session-scoped methods use sessionID (token family ID) for per-login isolation. User-scoped methods use userID (sub claim) for bulk operations across sessions.
func GetOAuthHandler ¶
func GetOAuthHandler() OAuthHandler
GetOAuthHandler returns the registered OAuth handler. This provides access to OAuth proxy functionality for remote MCP server authentication.
Returns nil if no handler has been registered yet or if OAuth is disabled. Callers should always check for nil before using the returned handler.
Returns:
- OAuthHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by oauthMutex read lock.
type OAuthToken ¶
type OAuthToken struct {
// AccessToken is the bearer token used for authorization.
AccessToken string `json:"access_token"`
// TokenType is typically "Bearer".
TokenType string `json:"token_type"`
// RefreshToken is used to obtain new access tokens.
// Required by mcp-go's transport layer for automatic token refresh.
RefreshToken string `json:"refresh_token,omitempty"`
// ExpiresAt is the calculated expiration timestamp.
// Required by mcp-go's transport layer to decide when to refresh.
ExpiresAt time.Time `json:"expires_at,omitempty"`
// Scope is the granted scope(s).
Scope string `json:"scope,omitempty"`
// IDToken is the OIDC ID token (if available).
// Used for SSO token forwarding to downstream MCP servers.
IDToken string `json:"id_token,omitempty"`
// Issuer is the token issuer (Identity Provider URL).
// Used for SSO detection and token forwarding.
Issuer string `json:"issuer,omitempty"`
// Resource is the RFC 8707 resource the grant was requested for (the
// MCP server it is bound to); empty when none was recorded.
Resource string `json:"resource,omitempty"`
}
OAuthToken represents an OAuth access token for use by handlers.
func FullTokenByIssuerForUser ¶
func FullTokenByIssuerForUser(h OAuthHandler, sessionID, userID, issuer string) *OAuthToken
FullTokenByIssuerForUser looks a token up with the subject-scoped fallback when the handler supports it and the user is known, and behaves like GetFullTokenByIssuer otherwise.
func LoginIDToken ¶
func LoginIDToken(h OAuthHandler, sessionID, issuer string) *OAuthToken
LoginIDToken reads the login ID token through the handler's mirror when it keeps one, falling back to the session's token for the issuer: the entry an earlier muster wrote, still in the store until the session's next request or login rewrites it.
func SessionLoginIDToken ¶ added in v5.55.0
func SessionLoginIDToken(h OAuthHandler, sessionID, issuer string) *OAuthToken
SessionLoginIDToken returns the session's own live login ID token for the issuer through the handler's mirror, or nil. Unlike LoginIDToken it never falls back to the session's plain token for the issuer, which can be a grant minted for another client.
type ObjectReference ¶
type ObjectReference struct {
// APIVersion is the API version of the object (e.g., "muster.giantswarm.io/v1alpha1")
APIVersion string `json:"apiVersion,omitempty"`
// Kind is the kind of the object (e.g., "MCPServer", "Workflow")
Kind string `json:"kind"`
// Name is the name of the object
Name string `json:"name"`
// Namespace is the namespace of the object (required for namespaced objects)
Namespace string `json:"namespace"`
// UID is the unique identifier of the object (optional, helps with precision)
UID string `json:"uid,omitempty"`
}
ObjectReference represents a reference to a Kubernetes object for event creation. This structure is used to identify the object that an event relates to.
type OperationDefinition ¶
type OperationDefinition struct {
// Description provides human-readable documentation for the operation's purpose
Description string `yaml:"description" json:"description"`
// Args defines the input arguments accepted by this operation.
// Used for validation and documentation generation.
Args map[string]Arg `yaml:"args" json:"args"`
// Requires lists the tools or capabilities that must be available for this operation.
// This is used for availability checking and dependency validation.
Requires []string `yaml:"requires" json:"requires"`
}
OperationDefinition defines an operation that can be performed within a workflow. Operations represent discrete actions that can be invoked, with their own argument requirements and execution logic (either direct workflow calls or references).
type OrchestratorAPI ¶
type OrchestratorAPI interface {
// StartService initiates the startup process for the specified service.
// It returns an error if the service cannot be started or if the service manager
// is not available.
//
// Args:
// - name: The unique name of the service to start
//
// Returns:
// - error: nil on success, or an error describing why the service could not be started
StartService(name string) error
// StopService initiates the shutdown process for the specified service.
// It returns an error if the service cannot be stopped or if the service manager
// is not available.
//
// Args:
// - name: The unique name of the service to stop
//
// Returns:
// - error: nil on success, or an error describing why the service could not be stopped
StopService(name string) error
// RemoveService stops the specified service and removes it from the service
// registry. This is used when the service's definition is deleted, so that a
// later re-create with the same name is treated as a fresh service.
//
// Args:
// - name: The unique name of the service to remove
//
// Returns:
// - error: nil on success, or an error describing why the service could not be removed
RemoveService(name string) error
// RestartService performs a stop followed by a start operation on the specified service.
// This is equivalent to calling StopService followed by StartService, but may be
// implemented more efficiently by the underlying service manager.
//
// Args:
// - name: The unique name of the service to restart
//
// Returns:
// - error: nil on success, or an error describing why the service could not be restarted
RestartService(name string) error
// GetServiceStatus retrieves the current status and metadata for a specific service.
// The returned ServiceStatus includes state, health, error information, and metadata.
//
// Args:
// - name: The unique name of the service to query
//
// Returns:
// - *ServiceStatus: Current status of the service, or nil if service not found
// - error: nil on success, or an error if the service could not be found or queried
GetServiceStatus(name string) (*ServiceStatus, error)
// GetAllServices returns the status of all registered services in the system.
// This provides a snapshot of the current state of all services managed by
// the orchestrator.
//
// Returns:
// - []ServiceStatus: Slice containing status of all services (empty if none exist)
GetAllServices() []ServiceStatus
// SubscribeToStateChanges returns a channel that receives service state change events.
// Clients can listen to this channel to be notified when any service changes state.
// The channel will be closed if the service manager becomes unavailable.
//
// Returns:
// - <-chan ServiceStateChangedEvent: Read-only channel for receiving state change events
SubscribeToStateChanges() <-chan ServiceStateChangedEvent
}
OrchestratorAPI defines the interface for orchestrating service lifecycle management. It provides methods to start, stop, restart services, check their status, and subscribe to state change events. The orchestrator acts as a high-level controller that coordinates service operations through the underlying service management infrastructure.
func NewOrchestratorAPI ¶
func NewOrchestratorAPI() OrchestratorAPI
NewOrchestratorAPI creates a new orchestrator API instance. The returned instance uses the API service locator pattern to access service management functionality without direct coupling to implementations.
Returns:
- OrchestratorAPI: A new orchestrator API instance
type OrganizationPrincipal ¶ added in v5.67.0
type OrganizationPrincipal struct {
// Organization is the organization's name.
Organization string
// Namespace is the organization's namespace: the principal sees the MCP
// servers of this namespace and no other.
Namespace string
// ClientID is the Dex client the principal authenticates as.
ClientID string
// Issuer is the Dex issuer that signs the principal's tokens.
Issuer string
// Toolset is the selector list bound to every request of the principal:
// a request header can narrow it and never widen it.
Toolset []string
// MusterNamespace is muster's own namespace, the namespace of a server
// whose key carries none (MCPServerKey).
MusterNamespace string
}
OrganizationPrincipal is the identity an organization's triggers and runs act as: a confidential Dex client of its own, with the client_credentials grant, that muster accepts for the organization's namespace and toolset only. It is a machine subject: no person signs in as it, so muster refuses it every tool and action that needs a person (a sign-in, a server reached with the caller's identity, a change to muster's own configuration).
func OrganizationPrincipalFromContext ¶ added in v5.67.0
func OrganizationPrincipalFromContext(ctx context.Context) (OrganizationPrincipal, bool)
OrganizationPrincipalFromContext returns the organization principal of the request, and false when a person (or nobody) makes it.
func (OrganizationPrincipal) SessionID ¶ added in v5.67.0
func (p OrganizationPrincipal) SessionID() string
SessionID is the principal's muster session: one per issuer and client, the same on every replica and for every token the client obtains, so its tokens renewing at Dex keep the session.
func (OrganizationPrincipal) Subject ¶ added in v5.67.0
func (p OrganizationPrincipal) Subject() string
Subject is the principal's subject, "client:<client ID>": what audit lines and the dispatch log name, and what any per-subject state is keyed on.
func (OrganizationPrincipal) Visibility ¶ added in v5.67.0
func (p OrganizationPrincipal) Visibility() ServerVisibility
Visibility is what the principal sees of the MCP servers: those of its namespace, nothing else. It does not ask the Kubernetes API: muster's configuration binds the principal to its namespace.
type OrganizationPrincipalCallRefusal ¶ added in v5.67.0
OrganizationPrincipalCallRefusal is the refusal of a call made as an organization principal (CallToolInternal), before anything runs. Kind says which principal policy refused the call. The call fails the same until muster's configuration or the toolset changes. Reason is the text the caller gets.
func (*OrganizationPrincipalCallRefusal) Error ¶ added in v5.67.0
func (e *OrganizationPrincipalCallRefusal) Error() string
func (*OrganizationPrincipalCallRefusal) Is ¶ added in v5.67.0
func (e *OrganizationPrincipalCallRefusal) Is(target error) bool
Is preserves the allowlist error for callers checking the cause of a refusal.
type OrganizationPrincipalHandler ¶ added in v5.67.0
type OrganizationPrincipalHandler interface {
// Authenticate recognizes a bearer as an organization principal's own
// token, verifies it (signature by the issuer's keys, iss, aud naming the
// client, exp) and returns ctx as the principal (ContextAs) with the
// token's expiry. A bearer that is no Dex client's own token gets
// ErrNotOrganizationPrincipal, a client's own token muster does not
// accept an *OrganizationPrincipalRefusal, and a token that does not
// verify any other error, with the principal it claims to be for the
// audit line (never to act as).
Authenticate(ctx context.Context, bearer string) (context.Context, OrganizationPrincipal, error)
// PrincipalOf returns the principal of the organization whose namespace
// is namespace, and false when no organization principal is configured
// for it.
PrincipalOf(namespace string) (OrganizationPrincipal, bool)
// ActAs returns ctx as the principal of the organization whose namespace
// is namespace, for muster's own work in that organization (a trigger's
// poll, a run's step). A tool call made with it (CallToolInternal) runs as
// the principal: within its namespace and its toolset, refused where a
// person is needed, with "client:<id>" in the dispatch log.
//
// It holds a token the principal obtained at Dex with its client Secret
// (client_credentials), verified like an inbound one, and obtains a new
// one before it expires, so a run is not bounded by one token's lifetime.
// No person's token is involved. It fails when no principal is configured
// for namespace, its Secret is not set or not readable, or Dex refuses
// (ErrOrganizationPrincipalUnavailable when Dex does not answer). A call
// made with it that the principal may not make fails with an
// *OrganizationPrincipalCallRefusal.
ActAs(ctx context.Context, namespace string) (context.Context, error)
// TokenFor returns the ID token of the principal of the organization
// whose namespace is namespace, for audience: a tool server's Dex client
// ID (spec.auth.principalAudience). muster obtains it at Dex with the
// client Secret, client_credentials and the scope
// "openid audience:server:client_id:<audience>", holds it to the rules of
// a token it receives, requires its aud to name audience, and renews it as
// ActAs's. Dex issues it with aud [audience, client], azp the client and
// sub Dex's encoding of the client, and only when audience's client lists
// the principal's client in trustedPeers.
//
// serverURL is the MCP server the token is for: TokenFor refuses, before
// it asks Dex, an audience AudienceRefusal does not let muster send there.
// It fails as ActAs does otherwise (ErrOrganizationPrincipalUnavailable
// when Dex does not answer).
TokenFor(ctx context.Context, namespace, audience, serverURL string) (string, error)
// AudienceRefusal returns why muster may not send a principal's token
// for audience to the MCP server at serverURL, and nil when
// aggregator.oauth.server.principalAudiences lists serverURL for
// audience. Whoever writes MCPServers in an organization's namespace
// chooses an MCPServer's principalAudience and URL; the platform chooses
// the list, so a writer cannot direct the principal's token to a URL of
// their own. The refusal wraps ErrPrincipalAudienceNotAllowed.
AudienceRefusal(audience, serverURL string) error
}
OrganizationPrincipalHandler is the organization principal: it accepts the principal's tokens and gives the context an organization's triggers and runs act in.
func GetOrganizationPrincipals ¶ added in v5.67.0
func GetOrganizationPrincipals() OrganizationPrincipalHandler
GetOrganizationPrincipals returns the registered organization principal handler, or nil.
type OrganizationPrincipalRefusal ¶ added in v5.67.0
OrganizationPrincipalRefusal is Authenticate's answer to a client's own token that muster does not accept: one of a client no organization names, or a token issued to a principal's client for anyone but the client itself. Reason says which, without token material.
func (*OrganizationPrincipalRefusal) Error ¶ added in v5.67.0
func (e *OrganizationPrincipalRefusal) Error() string
type PendingAuthRegistration ¶
type PendingAuthRegistration struct {
// Name is the unique identifier for the server within the aggregator.
Name string
// Namespace is the Kubernetes namespace of the MCPServer resource. It is
// the default namespace for the server's Secret references and the
// namespace its events are filed under. Empty in filesystem mode.
Namespace string
// UID is the Kubernetes UID of the MCPServer resource (MCPServer.UID).
// Empty in filesystem mode.
UID string
// CreatedAt is the creation time of the MCPServer resource
// (MCPServer.CreatedAt). Zero in filesystem mode.
CreatedAt time.Time
// URL is the remote server endpoint.
URL string
// ToolPrefix is the per-server tool prefix used when Family is empty.
ToolPrefix string
// Family declares that this server is an instance of a family of
// equivalent servers. When set, tools are exposed as
// {musterPrefix}_{family.name}_{toolName} with a required parameter
// named by family.instanceArg.
Family *MCPServerFamily
// AuthInfo carries the OAuth metadata returned in the 401 response.
AuthInfo *AuthInfo
// AuthConfig describes how to forward or exchange tokens, when set.
AuthConfig *MCPServerAuth
// RequestMeta carries MCPServer.RequestMeta to the session-scoped clients.
// A pending-auth server serves its tool calls from a per-session client the
// aggregator builds, not from the one the client factory built, so the
// entries have to travel with the registration or spec.requestMeta would
// stop applying the moment a server needs a login.
RequestMeta map[string]string
// Timeout is the server's spec.timeout, the budget every operation on a
// per-session client runs under; zero means the client's default. It
// travels with the registration for the same reason RequestMeta does.
Timeout time.Duration
// MaxCallDuration is the server's spec.progress.maxDuration, how long progress
// may keep a tool call on a per-session client going. It travels with the
// registration for the same reason Timeout does.
MaxCallDuration time.Duration
// Headers carries MCPServer.Headers to the per-session clients: the HTTP
// headers the definition sends with every request to the server (a
// toolset selector, for one). They travel with the registration for the
// same reason RequestMeta does. A session's Authorization header is its own
// credential, never an entry of the definition.
Headers map[string]string
// HeadersFrom carries MCPServer.HeadersFrom, the references of headers
// whose values a per-session client reads from a Secret when it connects.
// The values never travel with the registration.
HeadersFrom []MCPServerHeaderFrom
}
PendingAuthRegistration describes a remote MCP server that responded with HTTP 401 during initialisation: muster knows where it is and how to authenticate against it, but no tools can be exposed until the user authenticates.
type PinnedLoginMirror ¶ added in v5.55.0
type PinnedLoginMirror interface {
// LoginSessionForIDToken returns the session that filed idToken as its
// login ID token, or "" when none did. A login family is preferred over a
// forwarded session that filed the same token.
LoginSessionForIDToken(idToken string) string
// ClearLoginIDToken removes the session's login ID token for the issuer.
ClearLoginIDToken(sessionID, issuer string)
}
PinnedLoginMirror is implemented by a LoginTokenMirror that records which session filed each login ID token. A Session binding pins its actor to the login of the session its bind request came from: the bearer of that request is a login ID token muster filed for that session, either one muster obtained at its own sign-in (a login family) or one a client forwarded to muster.
type PostLoginRedirects ¶ added in v5.67.0
PostLoginRedirects is the optional capability of the registered OAuth handler that checks a browser return against the operator's oauth.mcpClient.postLoginRedirectAllowlist, the one check every muster page that sends a browser back to a client uses.
type PresetSelector ¶ added in v5.67.0
type PresetSelector func(ctx context.Context, preset string, t AgentTarget) bool
PresetSelector reports whether a toolset preset selects a target.
type PrincipalServerToolResolver ¶ added in v5.67.0
type PrincipalServerToolResolver interface {
// ResolvePrincipalServerTool returns the tool of server, in the
// namespace of the organization principal of ctx (as ActAs returns it),
// with its annotations as the server lists it to that principal, and
// whether it does. It is false when ctx acts as no organization
// principal, when the server does not serve one or may not serve this
// one, and when the principal's listing cannot be had or does not name
// the tool.
ResolvePrincipalServerTool(ctx context.Context, server, tool string) (ServerTool, bool)
}
PrincipalServerToolResolver is implemented by a ServerToolResolver that also finds the tools of a server that serves the organization principal (spec.auth.principalAudience). Such a server requires per-session authentication, so ResolveServerTool answers it with SessionAuth only: its tools and their annotations are known on the principal's own connection.
type PromptOrigin ¶
PromptOrigin pairs an aggregated prompt with the server exposing it.
A prompt name is prefixed, but with the server's *configured* tool prefix (spec.toolPrefix) rather than its name -- a server named "mcp-pro" with prefix "pro" exposes "x_pro_<name>". Deriving the source server by matching the server name against the exposed name therefore fails for every server whose prefix differs from its name, which is the common case. Carry the attribution explicitly instead, as ResourceOrigin does.
type ReconcileManagerHandler ¶
type ReconcileManagerHandler interface {
// IsRunning returns whether the reconciliation manager is active.
IsRunning() bool
// GetQueueLength returns the current number of items in the reconciliation queue.
GetQueueLength() int
// GetStatus returns the reconciliation status for a specific resource.
GetStatus(resourceType, name, namespace string) (*ReconcileStatusInfo, bool)
// GetAllStatuses returns all reconciliation statuses.
GetAllStatuses() []ReconcileStatusInfo
// GetWatchMode returns the current watch mode (kubernetes/filesystem).
GetWatchMode() string
// GetEnabledResourceTypes returns the list of resource types with reconciliation enabled.
GetEnabledResourceTypes() []string
}
ReconcileManagerHandler provides access to reconciliation status and control. This handler enables monitoring and manual triggering of reconciliation operations for resources managed by the reconciliation system.
The reconciliation system ensures that resource definitions (CRDs or YAML files) are automatically synchronized with running services.
func GetReconcileManager ¶
func GetReconcileManager() ReconcileManagerHandler
GetReconcileManager returns the registered reconcile manager handler. This provides access to reconciliation status and control functionality.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- ReconcileManagerHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
type ReconcileOverview ¶
type ReconcileOverview struct {
// Running indicates whether the reconciliation system is active.
Running bool `json:"running"`
// WatchMode is the current mode (kubernetes or filesystem).
WatchMode string `json:"watch_mode"`
// QueueLength is the current number of items awaiting reconciliation.
QueueLength int `json:"queue_length"`
// EnabledResourceTypes lists the resource types being watched.
EnabledResourceTypes []string `json:"enabled_resource_types"`
// StatusSummary provides counts by state.
StatusSummary ReconcileStatusSummary `json:"status_summary"`
}
ReconcileOverview provides a summary of the reconciliation system status.
type ReconcileStatusInfo ¶
type ReconcileStatusInfo struct {
// ResourceType is the type of the resource (MCPServer, Workflow).
ResourceType string `json:"resource_type"`
// Name is the name of the resource.
Name string `json:"name"`
// Namespace is the Kubernetes namespace (empty for filesystem mode).
Namespace string `json:"namespace,omitempty"`
// LastReconcileTime is when the resource was last successfully reconciled.
LastReconcileTime *string `json:"last_reconcile_time,omitempty"`
// LastError is the most recent error, if any.
LastError string `json:"last_error,omitempty"`
// RetryCount is the number of retry attempts.
RetryCount int `json:"retry_count"`
// State describes the current reconciliation state (Pending, Reconciling, Synced, Error, Failed).
State string `json:"state"`
}
ReconcileStatusInfo represents the reconciliation status for a resource. This is exposed via the API for observability.
type ReconcileStatusSummary ¶
type ReconcileStatusSummary struct {
// Total is the total number of tracked resources.
Total int `json:"total"`
// Synced is the count of successfully synced resources.
Synced int `json:"synced"`
// Pending is the count of resources awaiting reconciliation.
Pending int `json:"pending"`
// Reconciling is the count of resources currently being reconciled.
Reconciling int `json:"reconciling"`
// Error is the count of resources that failed but may be retried.
Error int `json:"error"`
// Failed is the count of resources that failed permanently.
Failed int `json:"failed"`
}
ReconcileStatusSummary provides aggregate counts of reconciliation states.
type ResolvedTokenExchangeConfig ¶
type ResolvedTokenExchangeConfig struct {
TokenExchangeConfig
}
ResolvedTokenExchangeConfig is a TokenExchangeConfig that carries the per-connection runtime state. It is only produced by WithResolvedRuntime, so a function that needs the resolved credentials and audience scopes can require this type and the shared spec-only registry definition cannot be passed by mistake (the bug class fixed in #944).
type ResourceOrigin ¶
ResourceOrigin pairs an aggregated resource with the server exposing it.
Tool and prompt names carry an "x_<server>_" prefix that identifies their origin, but resource URIs do not: ExposedResourceURI passes any URI with a scheme through unchanged, and MCP resource URIs always have one. Callers listing aggregated resources therefore cannot recover the source server from the URI alone, and two servers may legitimately expose the same URI. This type carries the attribution alongside the resource instead of encoding it into the identifier.
type SchemaProperty ¶
type SchemaProperty struct {
// Type specifies the JSON schema type for validation.
// Valid values: "string", "number", "boolean", "object", "array"
Type string `yaml:"type" json:"type"`
// Description provides human-readable documentation for this property,
// explaining its purpose and expected format
Description string `yaml:"description" json:"description"`
// Default specifies the default value used when the property is not provided.
// Must be compatible with the specified Type.
Default any `yaml:"default,omitempty" json:"default,omitempty"`
}
SchemaProperty defines a single property in a JSON schema. This is used for input validation and documentation in workflows and capabilities, providing structured arg definition and validation rules.
Schema properties enable automatic validation of inputs and help generate helpful error messages and documentation for users.
type SecretCredentialsHandler ¶
type SecretCredentialsHandler interface {
// LoadClientCredentialsForConfig loads OAuth client credentials from a
// Secret muster's configuration names (broker targets and clients,
// provider Apps). No Secret is refused.
//
// The secret should contain clientIdKey (default "client-id") and
// clientSecretKey (default "client-secret"). defaultNamespace is used
// when secretRef names none.
LoadClientCredentialsForConfig(ctx context.Context, secretRef *ClientCredentialsSecretRef, defaultNamespace string) (*ClientCredentials, error)
// LoadMCPServerClientCredentials loads OAuth client credentials from a
// Secret the MCPServer owner names in field (SecretField*). A protected
// Secret is refused and nothing is returned. A reference without a
// namespace resolves to owner.Namespace.
LoadMCPServerClientCredentials(ctx context.Context, owner SecretOwner, field string, secretRef *ClientCredentialsSecretRef) (*ClientCredentials, error)
// LoadMCPServerSecretKey loads raw bytes for a single named key from a
// Secret the MCPServer owner names in field, with the refusals of
// LoadMCPServerClientCredentials. Callers are responsible for not
// logging the returned value. ClientIDKey/ClientSecretKey of secretRef
// are ignored.
LoadMCPServerSecretKey(ctx context.Context, owner SecretOwner, field string, secretRef *ClientCredentialsSecretRef, key string) ([]byte, error)
}
SecretCredentialsHandler defines the interface for loading OAuth client credentials and other values from Kubernetes secrets.
A read on behalf of an MCPServer -- a Secret its spec names -- goes through the methods that take a SecretOwner: they never read one of muster's own (secretBinding) or one of a reserved type. LoadClientCredentialsForConfig is for Secrets muster's own configuration names and must never be called with a reference taken from an MCPServer.
Thread-safe: All methods must be safe for concurrent use.
func GetSecretCredentialsHandler ¶
func GetSecretCredentialsHandler() SecretCredentialsHandler
GetSecretCredentialsHandler returns the registered secret credentials handler.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- SecretCredentialsHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by secretCredentialsMutex read lock.
type SecretOwner ¶ added in v5.53.1
type SecretOwner struct {
// Name is the MCPServer object's name (not its key).
Name string
// Namespace is the MCPServer's namespace, the default namespace of its
// Secret references. Empty in filesystem mode ("default").
Namespace string
// UID is the MCPServer's UID, which tells a recreated MCPServer apart.
UID string
// AuthorizationServer is the AuthorizationServerDigest of the
// authorization server a client read for spec.auth.authorizationServer
// is sent to. Set by the readers of that field.
AuthorizationServer string
}
SecretOwner is the MCPServer whose spec names a Secret, for the refusals and warnings of a read on its behalf.
func MCPServerSecretOwner ¶ added in v5.53.1
func MCPServerSecretOwner(key, namespace, uid string) SecretOwner
MCPServerSecretOwner returns the owner of a server's Secret references from its key (MCPServerKey), namespace and UID.
func (SecretOwner) ForAuthorizationServer ¶ added in v5.60.0
func (o SecretOwner) ForAuthorizationServer(as *MCPServerAuthAuthorizationServer) SecretOwner
ForAuthorizationServer returns the owner of a read of the client of as.
func (SecretOwner) String ¶ added in v5.53.1
func (o SecretOwner) String() string
String returns "<namespace>/<name>".
type ServerAuthInfo ¶
type ServerAuthInfo struct {
// Name is the server name (e.g., "kubernetes", "github")
Name string `json:"name"`
// Status is the current auth status (typically "auth_required")
Status string `json:"status"`
// AuthTool is the tool to use for authentication ("core_auth_login");
// empty when the sign-in cannot pass for the caller's session.
AuthTool string `json:"auth_tool,omitempty"`
// Error says why the caller's session cannot sign in to the server,
// worded for the person; set exactly when AuthTool is empty.
Error string `json:"error,omitempty"`
// ToolPrefix is the exposed prefix of the server's tools (x_<server>_,
// or x_<family>_ for a member of a family whose tools are grouped), so a
// caller can tell which tool names the sign-in would unlock before the
// tools are listed.
ToolPrefix string `json:"tool_prefix,omitempty"`
// Family is the family the server's tools are grouped under; a call to
// one selects the server with the family's instance argument.
Family string `json:"family,omitempty"`
}
ServerAuthInfo contains information about a server requiring authentication. This is used to inform users which servers need authentication via core_auth_login.
type ServerTool ¶ added in v5.67.0
type ServerTool struct {
// Exposed is the name muster exposes the tool under, the name
// AggregatorHandler.CallToolInternal takes.
Exposed string
// ReadOnly is the tool's readOnlyHint annotation: true only when the
// server declares that the tool does not modify its environment.
ReadOnly bool
// SessionAuth is true when the server requires per-session
// authentication (such as a person's sign-in), so muster lists no
// shared tools for it. ResolveServerTool returns ok=false alongside
// SessionAuth=true and Exposed set to the server's exposed tool name,
// so an organization principal's call can reach CallToolInternal and
// receive the permanent needs-person refusal. A server that serves the
// organization principal lists its tools to the principal instead
// (PrincipalServerToolResolver).
SessionAuth bool
// Builtin is true for a tool muster serves itself (muster.list_runs),
// whose annotations muster declares and so trusts in a dry run.
Builtin bool
// DestructiveHint is the tool's destructiveHint annotation; nil defaults
// to true per the MCP specification.
DestructiveHint *bool
// IdempotentHint is the tool's idempotentHint annotation; nil defaults to
// false per the MCP specification.
IdempotentHint *bool
}
ServerTool is a downstream server's tool as the aggregator exposes it.
func (ServerTool) IsDestructive ¶ added in v5.67.0
func (t ServerTool) IsDestructive() bool
IsDestructive reports the tool's effective destructiveHint, defaulting to true when omitted per the MCP specification.
func (ServerTool) IsIdempotent ¶ added in v5.67.0
func (t ServerTool) IsIdempotent() bool
IsIdempotent reports the tool's effective idempotentHint, defaulting to false when omitted per the MCP specification.
type ServerToolLister ¶ added in v5.67.0
type ServerToolLister interface {
ServerTools(ctx context.Context, server string) ([]mcp.Tool, bool)
}
ServerToolLister is the optional capability of the registered aggregator that lists a server's tools as the server names them, for the caller: what a preset expands from when a connector's approval is set.
type ServerToolResolver ¶ added in v5.67.0
type ServerToolResolver interface {
// ResolveServerTool returns the server's tool in namespace, and whether
// muster currently serves it. An empty namespace names muster's own
// namespace.
ResolveServerTool(namespace, server, tool string) (ServerTool, bool)
}
ServerToolResolver finds a tool by its namespace, server name and tool name, as a definition names it (<MCPServer>.<tool>), for callers that act outside a user session: the durable-run controller.
func GetServerToolResolver ¶ added in v5.67.0
func GetServerToolResolver() ServerToolResolver
GetServerToolResolver returns the registered resolver, or nil when no aggregator runs.
type ServerVisibility ¶ added in v5.47.0
type ServerVisibility struct {
// Reason says why the caller sees no server at all (a session without a
// token, a token the API server does not accept), and that the person must
// sign in again. Empty when the caller sees what RBAC allows.
Reason string
// contains filtered or unexported fields
}
ServerVisibility is what the caller of one request may see of the MCP servers: the servers of every namespace in which Kubernetes RBAC lets the caller list mcpservers.muster.giantswarm.io (agent-permissions D9). The zero value sees every server; that is the view when muster serves only its own namespace (no MCPServerVisibilityHandler is registered).
func AllServersVisible ¶ added in v5.47.0
func AllServersVisible() ServerVisibility
AllServersVisible is the view of a caller who sees every server.
func CallerVisibility ¶ added in v5.47.0
func CallerVisibility(ctx context.Context) ServerVisibility
CallerVisibility returns the view of the caller of ctx: every server when no visibility handler is registered. An organization principal sees the servers of its namespace, whether or not a handler is registered; muster calling as itself (WithMusterCaller) sees the servers of its own namespace.
func NoServerVisible ¶ added in v5.47.0
func NoServerVisible(reason string) ServerVisibility
NoServerVisible is the view of a caller who sees no server, for reason.
func NoServerVisibleWithError ¶ added in v5.67.0
func NoServerVisibleWithError(reason error) ServerVisibility
NoServerVisibleWithError preserves a refusal's classification next to its text.
func ServersOfNamespacesVisible ¶ added in v5.47.0
func ServersOfNamespacesVisible(musterNamespace string, namespaces []string) ServerVisibility
ServersOfNamespacesVisible is the view of a caller who may list the servers of the given namespaces. musterNamespace is the namespace of a server whose key carries none (MCPServerKey).
func (ServerVisibility) Err ¶ added in v5.67.0
func (v ServerVisibility) Err() error
Err is the cause of a view that cannot authorize the caller.
func (ServerVisibility) Restricted ¶ added in v5.47.0
func (v ServerVisibility) Restricted() bool
Restricted reports whether the view hides any server.
func (ServerVisibility) Sees ¶ added in v5.47.0
func (v ServerVisibility) Sees(serverKey string) bool
Sees reports whether the caller may see the server with the given key.
func (ServerVisibility) SeesEvent ¶ added in v5.47.0
func (v ServerVisibility) SeesEvent(event EventResult) bool
SeesEvent reports whether the caller may see an event: an event about an MCPServer only when the caller sees the servers of its namespace.
type ServiceInfo ¶
type ServiceInfo interface {
// GetName returns the unique name/identifier of the service
GetName() string
// GetType returns the service type (e.g., TypeMCPServer, TypeAggregator)
GetType() ServiceType
// GetState returns the current operational state of the service
GetState() ServiceState
// GetHealth returns the current health status of the service
GetHealth() HealthStatus
// GetLastError returns the last error encountered by the service, or nil if none
GetLastError() error
// GetServiceData returns additional metadata and runtime information about the service
GetServiceData() map[string]interface{}
}
ServiceInfo provides information about a service instance. This interface defines the contract for accessing service metadata and state.
All service implementations must provide this interface to be managed by the service registry and orchestrator.
type ServiceListResponse ¶
type ServiceListResponse struct {
// Services contains the list of service status information
Services []ServiceStatus `json:"services"`
}
ServiceListResponse represents a list of services in API responses. This is used by endpoints that return multiple service status information.
type ServiceManagerHandler ¶
type ServiceManagerHandler interface {
// StartService starts a service by name.
StartService(name string) error
// StopService stops a running service by name.
StopService(name string) error
// RestartService restarts a service by name (stop followed by start).
RestartService(name string) error
// RemoveService stops a service and removes it from the service registry.
// Used when a service definition is deleted, so a later re-create with
// the same name is treated as a fresh service.
RemoveService(name string) error
// GetServiceStatus returns the current status of a service.
GetServiceStatus(name string) (*ServiceStatus, error)
// GetAllServices returns the status of all services in the system.
GetAllServices() []ServiceStatus
// SubscribeToStateChanges returns a channel for receiving service state change events.
// The returned channel should be consumed to prevent blocking the event system.
SubscribeToStateChanges() <-chan ServiceStateChangedEvent
// ToolProvider integration for exposing service management as MCP tools.
ToolProvider
}
ServiceManagerHandler provides lifecycle management for static services (the aggregator and per-MCPServer wrappers) registered in the orchestrator's service registry. This is the primary interface for service operations in the Service Locator Pattern.
func GetServiceManager ¶
func GetServiceManager() ServiceManagerHandler
GetServiceManager returns the registered service manager handler. This provides access to lifecycle management for the static services registered in the orchestrator's service registry.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- ServiceManagerHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
Example:
manager := api.GetServiceManager()
if manager == nil {
return fmt.Errorf("service manager not available")
}
err := manager.StartService("my-service")
type ServiceRegistryHandler ¶
type ServiceRegistryHandler interface {
// Get retrieves a service by name from the registry.
//
// Args:
// - name: The unique name of the service to retrieve
//
// Returns:
// - ServiceInfo: The service information if found
// - bool: true if the service exists, false otherwise
Get(name string) (ServiceInfo, bool)
// GetAll returns all services currently registered in the system.
//
// Returns:
// - []ServiceInfo: List of all registered services (both static and dynamic)
GetAll() []ServiceInfo
// GetByType returns all services of a specific type.
//
// Args:
// - serviceType: The type of services to retrieve (e.g., TypeMCPServer)
//
// Returns:
// - []ServiceInfo: List of services matching the specified type
GetByType(serviceType ServiceType) []ServiceInfo
}
ServiceRegistryHandler provides access to registered services in the system. This handler implements the service discovery aspect of the Service Locator Pattern, allowing components to find and access service information without direct coupling.
func GetServiceRegistry ¶
func GetServiceRegistry() ServiceRegistryHandler
GetServiceRegistry returns the registered service registry handler. This provides access to the service discovery and information interface.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- ServiceRegistryHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
Example:
registry := api.GetServiceRegistry()
if registry == nil {
return fmt.Errorf("service registry not available")
}
services := registry.GetAll()
type ServiceState ¶
type ServiceState string
ServiceState represents the current operational state of a service. This provides a standardized way to track service lifecycle across all service types.
const ( // StateStopped indicates the service is not running StateStopped ServiceState = "stopped" // StateStarting indicates the service is in the process of starting up StateStarting ServiceState = "starting" // StateRunning indicates the service is running and operational StateRunning ServiceState = "running" // StateStopping indicates the service is in the process of shutting down StateStopping ServiceState = "stopping" // StateError indicates the service encountered an error and may not be functional StateError ServiceState = "error" // StateFailed indicates the service failed to start or operate correctly StateFailed ServiceState = "failed" // StateUnknown indicates the service state cannot be determined StateUnknown ServiceState = "unknown" // StateWaiting indicates the service is waiting for dependencies or resources StateWaiting ServiceState = "waiting" // StateRetrying indicates the service is retrying a failed operation StateRetrying ServiceState = "retrying" // StateUnreachable indicates the service endpoint cannot be reached after multiple attempts. // This state is used for remote MCP servers (streamable-http, sse) that fail to connect // due to network issues, DNS failures, or decommissioned endpoints. // Servers in this state will use exponential backoff for retry attempts. StateUnreachable ServiceState = "unreachable" // StateAuthRequired indicates the service requires OAuth authentication before connecting. // This state is used for remote MCP servers that returned a 401 Unauthorized response // during initialization, indicating they support OAuth and require authentication. // Users should run `muster auth login --server <name>` to authenticate. // // This is distinct from StateUnreachable: // - StateAuthRequired: Server is reachable but requires authentication // - StateUnreachable: Server cannot be reached (network/connectivity issue) StateAuthRequired ServiceState = "auth_required" // StateAwaitingSession indicates a remote MCP server that is served per // session with the caller's own identity (auth.forwardToken or // auth.tokenExchange) and currently has no session connected. muster's // own token-less probe reached the endpoint, so the server is up; it // holds no connection of its own because every connection belongs to a // session. There is no login to run: the caller's Dex token is forwarded // or exchanged when a session uses the server. // // This is distinct from StateAuthRequired, which names a server a person // signs in to through muster (core_auth_login) before it connects, and // from StateFailed, which for such a server means its endpoint does not // answer or its token exchange is broken for every caller (credentials // Secret missing, token endpoint down, wrong client secret, unknown // connector). StateAwaitingSession ServiceState = "awaiting_session" // StateConnected indicates the service is connected and authenticated. // This is an alias for StateRunning for semantic clarity with remote servers. // For remote MCP servers, "connected" is more intuitive than "running" since // the server itself is running remotely - we are just connected to it. StateConnected ServiceState = "connected" // StateDisconnected indicates the service was previously connected but is now disconnected. // This state is used for remote MCP servers that were successfully connected but // the connection was lost (session ended, server restart, etc.). StateDisconnected ServiceState = "disconnected" )
type ServiceStateChangedEvent ¶
type ServiceStateChangedEvent struct {
// Name is the unique identifier of the service that changed state
Name string `json:"name"`
// ServiceType indicates the type of service (e.g., "MCPServer", "Aggregator")
ServiceType string `json:"service_type"`
// OldState is the previous state before the transition
OldState string `json:"old_state"`
// NewState is the current state after the transition
NewState string `json:"new_state"`
// Health is the current health status of the service
Health string `json:"health"`
// Error contains error information if the state change was due to an error
Error error `json:"error,omitempty"`
// Timestamp indicates when the state change occurred
Timestamp time.Time `json:"timestamp"`
}
ServiceStateChangedEvent represents a service state transition event. These events are published whenever a service changes state, allowing components to react to service lifecycle changes.
type ServiceStatus ¶
type ServiceStatus struct {
// Name is the unique identifier of the service
Name string `json:"name"`
// ServiceType indicates the type of service (e.g., "MCPServer", "Aggregator")
ServiceType string `json:"service_type"`
// State is the current operational state of the service
State ServiceState `json:"state"`
// Health is the current health status of the service
Health HealthStatus `json:"health"`
// Error contains error information if the service is in an error state
Error string `json:"error,omitempty"`
// Metadata contains additional runtime information about the service
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ServiceStatus represents the current status of a service for API responses. This is a simplified view of service information suitable for status queries and monitoring dashboards.
type ServiceType ¶
type ServiceType string
ServiceType represents the type/category of a service. This classification helps with service organization and type-specific operations.
const ( // TypeMCPServer represents MCP (Model Context Protocol) server services TypeMCPServer ServiceType = "MCPServer" // TypeAggregator represents aggregator services that coordinate multiple MCP servers TypeAggregator ServiceType = "Aggregator" )
type SessionSubjectResolver ¶ added in v5.63.0
type SessionSubjectResolver interface {
// SessionSubject validates bearer as muster's MCP endpoint does for an
// externally issued token and returns the session subject it yields.
SessionSubject(ctx context.Context, bearer string) (string, error)
}
SessionSubjectResolver names the subject an MCP request presenting a bearer muster did not issue is served as: the subject the person's grants are filed under when that request signs in to a server. The token broker releases a grant by it, so a grant is released by the same identity it was filed under.
func GetSessionSubjectResolver ¶ added in v5.63.0
func GetSessionSubjectResolver() SessionSubjectResolver
GetSessionSubjectResolver returns the registered resolver, or nil when muster runs no OAuth server.
type SessionToolMemo ¶
type SessionToolMemo struct {
// contains filtered or unexported fields
}
SessionToolMemo caches a session's resolved accessible-tool set for the duration of a single request, so callers that perform many per-item availability checks (e.g. listing N workflows) rebuild the session tool set at most once instead of once per item.
The accessible-tool set is identical for every item in one list request, yet resolving it is expensive (a full rebuild across all backend MCP servers). Without the memo, a workflow list of N entries rebuilds it N times — the O(workflows) blow-up that made /api/muster/workflows take ~30 s.
func SessionToolMemoFromContext ¶
func SessionToolMemoFromContext(ctx context.Context) *SessionToolMemo
SessionToolMemoFromContext returns the SessionToolMemo carried by ctx, or nil when none is present. Callers outside a memo-scoped request get nil and keep their per-call behavior.
func (*SessionToolMemo) Resolve ¶
func (m *SessionToolMemo) Resolve(build func() map[string]struct{}) map[string]struct{}
Resolve returns the cached session tool set, invoking build exactly once to populate it on first use. Subsequent calls return the cached set without calling build again. Safe for concurrent use.
type SignInCheckError ¶ added in v5.62.10
type SignInCheckError struct {
Reason string
}
SignInCheckError says the sign-in check cannot pass for a session, so muster issues no sign-in link for it. Reason is worded for the person.
func (*SignInCheckError) Error ¶ added in v5.62.10
func (e *SignInCheckError) Error() string
type SignInHandoff ¶ added in v5.67.0
type SignInHandoff struct {
Kind string `json:"kind"`
Target string `json:"target"`
Identity SignInIdentity `json:"identity"`
// Name is how the person is named for people by a verified identifier
// (the verified email, else subject at issuer, marked for invisible and
// bidi characters), from the client's bearer when the ticket was issued;
// shown on the connector sign-in's confirmation.
Name string `json:"name,omitempty"`
}
SignInHandoff is what muster keeps of a ticket: the page it is bound to and the person it was issued to.
func RedeemHandoff ¶ added in v5.67.0
func RedeemHandoff(ctx context.Context, ticket, kind, target string, want SignInIdentity) (SignInHandoff, bool)
RedeemHandoff redeems a ticket with the registered redeemer; false without one.
type SignInIdentity ¶ added in v5.52.30
SignInIdentity is the person a request was authenticated as at an identity provider: the issuer and its raw sub claim, together the only stable identifier of a person (OIDC Core §5.7). It differs from the session subject when a trusted issuer maps the subject from another claim.
func SignInIdentityFromContext ¶ added in v5.52.30
func SignInIdentityFromContext(ctx context.Context) SignInIdentity
SignInIdentityFromContext returns the request's sign-in identity; the zero value when the request carries none.
type StateUpdater ¶
type StateUpdater interface {
// UpdateState updates the service's operational state.
//
// Args:
// - state: The new service state
// - health: The new health status
// - err: Optional error associated with the state change
UpdateState(state ServiceState, health HealthStatus, err error)
}
StateUpdater is an optional interface for services that allow external state updates. This is used to update service state when external events occur, such as SSO authentication succeeding at the session level.
Not all services implement this interface; callers should type-assert before use.
type SubjectContextKey ¶
type SubjectContextKey struct{}
SubjectContextKey is the context key for storing the authenticated user's subject claim. This is set by the OAuth middleware after token validation and used by downstream handlers for user identity.
type SubjectGrantForgetter ¶ added in v5.57.0
type SubjectGrantForgetter interface {
// ForgetSubjectGrant revokes the person's grant for the issuer at the
// authorization server, where it can, and removes muster's copy filed
// under the person; the sessions' own copies stay.
ForgetSubjectGrant(userID, issuer string)
}
SubjectGrantForgetter is implemented by an OAuthHandler that can drop the person's grant filed under an issuer whatever the issuer's pin says now. Kept separate from SubjectGrantHandler so its test doubles need not grow.
type SubjectGrantHandler ¶
type SubjectGrantHandler interface {
// GetFullTokenByIssuerForUser is GetFullTokenByIssuer plus the
// subject-scoped fallback for the user.
GetFullTokenByIssuerForUser(sessionID, userID, issuer string) *OAuthToken
// ClearTokenByIssuerForUser is ClearTokenByIssuer plus, for a
// subject-scoped issuer, the removal of the person's grant.
ClearTokenByIssuerForUser(sessionID, userID, issuer string)
// IssuerSubjectScoped reports whether grants from the issuer belong to
// the person rather than to one login session (an operator pinned it
// with grantScope: subject). Signing out of such an issuer is signing
// the person out, whichever server the request names.
IssuerSubjectScoped(issuer string) bool
}
SubjectGrantHandler is implemented by an OAuthHandler that files subject-scoped grants under the person's identity in addition to the session, so lookups can fall back to them.
type TenantIssuerForgetter ¶ added in v5.48.0
type TenantIssuerForgetter interface {
// ForgetTenantIssuers removes the state filed under issuerKeys, or under
// every issuer key of the namespace when issuerKeys is empty. An empty
// namespace (muster's own) forgets nothing.
ForgetTenantIssuers(ctx context.Context, namespace string, issuerKeys []string) error
}
TenantIssuerForgetter is implemented by an OAuthHandler whose stored state can be forgotten per organization namespace: the people's tokens and subject grants, the client registrations and the flows in progress filed under the namespace's issuer keys (IssuerKey). Kept separate from OAuthHandler for the same reason as IssuerPinner.
type TokenEndpointProber ¶ added in v5.34.9
type TokenEndpointProber interface {
ProbeTokenEndpoint(ctx context.Context, config *TokenExchangeConfig) error
}
TokenEndpointProber is implemented by the OAuth handler when it can check, without a caller, that a token exchange's token endpoint answers. It returns the error the endpoint's answer produced, classified like an exchange's (ClassifyTokenExchangeError): TokenExchangeFailureNone means the authorization server answered and only a caller's token is missing.
type TokenEndpointUnavailableError ¶ added in v5.34.9
type TokenEndpointUnavailableError struct {
// Endpoint is the probed token endpoint URL.
}
TokenEndpointUnavailableError reports that a probe of a token exchange's token endpoint got no answer from the authorization server: a transport failure, a 5xx, or a non-OAuth answer from something in front of it. The server is Failed for it and the probe is repeated on the reconnect backoff, unlike an OAuth error, which stays until something changes.
func (*TokenEndpointUnavailableError) Error ¶ added in v5.34.9
func (e *TokenEndpointUnavailableError) Error() string
func (*TokenEndpointUnavailableError) Unwrap ¶ added in v5.34.9
func (e *TokenEndpointUnavailableError) Unwrap() error
type TokenExchangeConfig ¶
type TokenExchangeConfig struct {
// Enabled determines whether token exchange should be attempted.
// Default: false
Enabled bool `yaml:"enabled,omitempty" json:"enabled,omitempty"`
// DexTokenEndpoint is the URL used to connect to the remote cluster's Dex token endpoint.
// This may differ from the issuer URL when access goes through a proxy.
// Required when Enabled is true.
// Example: https://dex.cluster-b.example.com/token (direct)
// Example: https://dex-cluster.proxy.example.com/token (via proxy)
DexTokenEndpoint string `yaml:"dexTokenEndpoint,omitempty" json:"dexTokenEndpoint,omitempty"`
// ExpectedIssuer is the expected issuer URL in the exchanged token's "iss" claim.
// This should match the remote Dex's configured issuer URL.
// When access goes through a proxy, this differs from DexTokenEndpoint.
// If not specified, the issuer is derived from DexTokenEndpoint (backward compatible).
// Example: https://dex.cluster-b.example.com
ExpectedIssuer string `yaml:"expectedIssuer,omitempty" json:"expectedIssuer,omitempty"`
// ConnectorID is the ID of the OIDC connector on the remote Dex that
// trusts the local cluster's Dex, sent as connector_id. Required for a
// person's exchange. A delegated caller's exchange sends none: it goes to
// the Dex that issued the delegated token, which verifies it itself.
// Example: "cluster-a-dex"
ConnectorID string `yaml:"connectorId,omitempty" json:"connectorId,omitempty"`
// Scopes are the scopes to request for the exchanged token.
// Default: "openid profile email groups"
Scopes string `yaml:"scopes,omitempty" json:"scopes,omitempty"`
// ClientCredentialsSecretRef references a Kubernetes Secret containing
// client credentials for authenticating with the remote Dex's token endpoint.
// This is required when the remote Dex requires client authentication for
// token exchange (RFC 8693).
ClientCredentialsSecretRef *ClientCredentialsSecretRef `yaml:"clientCredentialsSecretRef,omitempty" json:"clientCredentialsSecretRef,omitempty"`
// ClientID is the resolved client ID from the secret (populated at runtime).
// This field is not persisted and is populated when loading credentials.
ClientID string `yaml:"-" json:"-"`
// ClientSecret is the resolved client secret from the secret (populated at runtime).
// This field is not persisted and is populated when loading credentials.
ClientSecret string `yaml:"-" json:"-"`
// Delegation, set at runtime for a delegated caller, makes the exchange
// an RFC 8693 delegation with muster as the actor. Not persisted.
Delegation *TokenExchangeDelegation `yaml:"-" json:"-"`
}
TokenExchangeConfig configures RFC 8693 Token Exchange for cross-cluster SSO. This enables muster to exchange its local token for a token valid on a remote cluster's Identity Provider (typically Dex).
The remote Dex must be configured with an OIDC connector that trusts the local cluster's Dex. For example:
# On remote cluster's Dex (cluster-b)
connectors:
- type: oidc
id: cluster-a-dex
name: "Cluster A"
config:
issuer: https://dex.cluster-a.example.com
getUserInfo: true
insecureEnableGroups: true
func (TokenExchangeConfig) SpecOnly ¶
func (c TokenExchangeConfig) SpecOnly() TokenExchangeConfig
SpecOnly returns a copy of the config with the runtime-resolved fields cleared, so spec-derived fields can be compared against a definition freshly rebuilt from the CR (where those fields are always empty — they are tagged json:"-" yaml:"-").
func (TokenExchangeConfig) WithResolvedRuntime ¶
func (c TokenExchangeConfig) WithResolvedRuntime(clientID, clientSecret string, requiredAudiences []string) (ResolvedTokenExchangeConfig, error)
WithResolvedRuntime returns a copy of the config carrying the per-connection runtime state: the resolved client credentials and, when requiredAudiences is non-empty, the appended cross-client audience scopes. The value receiver guarantees the receiver (shared with the registry definition) is never mutated.
On an audience-scope formatting error the credential-populated copy is returned (without audiences) together with the error, so callers can log and continue.
type TokenExchangeCredentialsError ¶ added in v5.28.0
type TokenExchangeCredentialsError struct {
// Secret is the "namespace/name" of the referenced Secret.
Secret string
Err error
}
TokenExchangeCredentialsError reports that the client credentials for a token exchange could not be loaded: the referenced Secret does not exist, is not readable or lacks the configured keys. It is typed so the failure is classified by what it is, not by the text of a Kubernetes API error.
func (*TokenExchangeCredentialsError) Error ¶ added in v5.28.0
func (e *TokenExchangeCredentialsError) Error() string
func (*TokenExchangeCredentialsError) Unwrap ¶ added in v5.28.0
func (e *TokenExchangeCredentialsError) Unwrap() error
type TokenExchangeDelegation ¶ added in v5.58.0
type TokenExchangeDelegation struct {
// ActorToken is muster's own workload token, sent as actor_token.
ActorToken string
// Audience is the Dex client ID of the backend, sent as audience. Empty
// sends none.
Audience string
}
TokenExchangeDelegation is the runtime part of a token exchange for a delegated caller. The subject token is the caller's delegated access token, issued by the Dex the exchange goes to, so no connector_id is sent (RFC 8693 §2.1 parameters only).
type TokenExchangeFailureClass ¶ added in v5.28.0
type TokenExchangeFailureClass string
TokenExchangeFailureClass names why a per-user RFC 8693 token exchange failed in a way that is the server's, not one caller's. It doubles as the reason of the MCPServer's Ready condition while the server is Failed for it.
A failure that is specific to the caller's own token -- invalid_grant, an expired subject token, a rejected audience -- has no class: it is reported on the session and never changes the server's state.
const ( // TokenExchangeFailureNone: the failure is the caller's, not the server's. TokenExchangeFailureNone TokenExchangeFailureClass = "" // TokenExchangeFailureCredentials: the client credentials are wrong or // cannot be loaded -- the referenced Secret is missing or lacks the keys, // or the authorization server answered invalid_client. TokenExchangeFailureCredentials TokenExchangeFailureClass = "TokenExchangeCredentials" // TokenExchangeFailureEndpoint: the token endpoint did not answer (DNS, // connection refused, TLS, timeout) or answered with a server error. TokenExchangeFailureEndpoint TokenExchangeFailureClass = "TokenExchangeEndpoint" // TokenExchangeFailureConnector: the authorization server does not know // the configured connector. TokenExchangeFailureConnector TokenExchangeFailureClass = "TokenExchangeConnector" )
func ClassifyTokenExchangeError ¶ added in v5.28.0
func ClassifyTokenExchangeError(err error) TokenExchangeFailureClass
ClassifyTokenExchangeError decides whether a failed token exchange is the server's (every caller fails the same way) or the caller's.
A refusal by the token endpoint (oidc.TokenExchangeError) is classified by its status and OAuth error code. Other errors come from before the request left muster, such as the exchange client's own connector validation, and are matched by their text. Anything else the authorization server says about the request is about the subject token, which is the caller's.
type TokenExchangeOutcomeRecorder ¶ added in v5.28.0
type TokenExchangeOutcomeRecorder interface {
// RecordTokenExchangeOutcome records one exchange: err is nil when it
// succeeded.
RecordTokenExchangeOutcome(err error)
}
TokenExchangeOutcomeRecorder is implemented by an MCPServer service that is served per session through RFC 8693 token exchange. The aggregator reports every exchange it performs for a caller through ReportMCPServerTokenExchange; the service turns a failure that is the server's into its Failed state and a success back out of it.
type ToolAnnotations ¶
type ToolAnnotations struct {
// ReadOnlyHint is true when the tool changes nothing: it lists, gets,
// validates or probes.
ReadOnlyHint *bool
// DestructiveHint is true when a write may change or remove what exists
// (update, delete, stop); false for purely additive writes (create).
DestructiveHint *bool
// IdempotentHint is true when repeating the call with the same arguments
// has no further effect.
IdempotentHint *bool
// OpenWorldHint is true when the tool reaches beyond muster and its
// cluster (an authorization server, a remote MCP server URL).
OpenWorldHint *bool
}
ToolAnnotations are the MCP tool annotations a tool provider declares for one of its tools. A nil hint is not sent, like a server that did not set it; the constructors below set every hint so a core tool's classification is always explicit.
func ReadOnlyAnnotations ¶
func ReadOnlyAnnotations() *ToolAnnotations
ReadOnlyAnnotations declares a tool that reads without changing anything: readOnlyHint true, destructiveHint false, idempotentHint true, openWorldHint false.
func WriteAnnotations ¶
func WriteAnnotations(destructive, idempotent bool) *ToolAnnotations
WriteAnnotations declares a tool that changes muster's state: readOnlyHint false, destructiveHint and idempotentHint as given, openWorldHint false.
func (*ToolAnnotations) OpenWorld ¶
func (a *ToolAnnotations) OpenWorld(open bool) *ToolAnnotations
OpenWorld returns a copy of the annotations with openWorldHint set.
type ToolApproval ¶ added in v5.67.0
type ToolApproval struct {
Setting string `json:"setting"`
Source string `json:"source"`
New bool `json:"new,omitempty"`
// (no shared store on Valkey, no browser sign-in, no public URL, no
// person on the request): calls to it are refused until it is fixed.
Unavailable string `json:"unavailable,omitempty"`
// Entry is the agent entry that decided the agent setting ("default"
// for the list's default); empty when no agent setting applies.
Entry string `json:"entry,omitempty"`
// Admin is the connector's own setting, reported beside Entry.
Admin *ToolApproval `json:"admin,omitempty"`
// Grant names the grant mark (entry@server) that lifted the
// connector's Ask, for the audit; never reported.
Grant string `json:"-"`
}
ToolApproval is a tool's effective approval for one caller: the setting, where it comes from, and whether the tool is new (it has no entry of its own on a server that has approval settings, so it follows the rule).
func ApplyAgentSetting ¶ added in v5.67.0
func ApplyAgentSetting(admin ToolApproval, setting, entry string, granted bool) ToolApproval
ApplyAgentSetting combines the admin setting with an agent setting (as written, "" for none): an admin Block holds; an agent Block blocks; a granted Allow over an admin Ask of a connector (its tool entry or rule) allows; otherwise the stricter holds, ties keeping the admin's source. entry is reported with the admin setting beside it.
func BuiltinApproval ¶ added in v5.67.0
func BuiltinApproval(exposedName string) (ToolApproval, bool)
BuiltinApproval returns the built-in approval of the exposed tool name, if muster sets one itself.
func KeepExplanation ¶ added in v5.67.0
func KeepExplanation(final, decided ToolApproval) ToolApproval
KeepExplanation returns final, the approval after floors and governance, with the agent explanation of decided (the approval before them): the deciding entry and the connector's own setting stay reported when a floor or the governed default is what decides. A grant mark is kept only when it is still what lets the call run.
func ResolveConnectorApproval ¶ added in v5.67.0
func ResolveConnectorApproval(approval *MCPServerApproval, tool string) ToolApproval
ResolveConnectorApproval returns the admin setting of the server's tool named tool (the server's own name): the tool's entry, else the server's rule, else Allow. Without approval settings the tool is Allow and not reviewed. A value other than Allow, Ask or Block counts as Ask; a rule Block blocks every tool without its own entry, new tools included.
func StrictestApproval ¶ added in v5.67.0
func StrictestApproval(approvals ...ToolApproval) ToolApproval
StrictestApproval returns the strictest of the approvals, Block over Ask over Allow; of equally strict ones, the first. No approval is the zero value.
func ToolApprovalOf ¶ added in v5.67.0
func ToolApprovalOf(tool mcp.Tool) (ToolApproval, bool)
ToolApprovalOf returns the effective approval recorded on tool, if any.
type ToolCaller ¶
type ToolCaller struct{}
ToolCaller implements tool calling interfaces using the API layer. It serves as an adapter that allows different subsystems (e.g. workflows) to call tools through the aggregator without directly coupling to the aggregator implementation. This follows the service locator pattern to maintain architectural boundaries.
It exposes only tool execution (CallTool / CallToolInternal). Tool-availability checks live on ToolChecker; consumers that need them depend on ToolChecker directly.
func NewToolCaller ¶
func NewToolCaller() *ToolCaller
NewToolCaller creates a new API-based tool caller instance. The returned ToolCaller uses the API service locator pattern to access aggregator functionality without direct coupling to implementations.
Returns:
- *ToolCaller: A new tool caller instance
func (*ToolCaller) CallTool ¶
func (atc *ToolCaller) CallTool(ctx context.Context, toolName string, args map[string]interface{}) (map[string]interface{}, error)
CallTool implements the ToolCaller interface by delegating to the aggregator handler. It provides a standardized way to execute tools with proper error handling and result formatting. The method converts the aggregator's result format to the format expected by the workflow system.
func (*ToolCaller) CallToolInternal ¶
func (atc *ToolCaller) CallToolInternal(ctx context.Context, toolName string, args map[string]interface{}) (*mcp.CallToolResult, error)
CallToolInternal implements the workflow ToolCaller interface by delegating to the aggregator handler. This method provides direct access to the raw MCP tool result format, which is used by workflow execution and other internal subsystems that need unmodified tool results.
type ToolChecker ¶
type ToolChecker struct{}
ToolChecker implements config.ToolAvailabilityChecker using the API layer. It provides a way for the configuration system to validate tool availability without direct coupling to the aggregator implementation.
func NewToolChecker ¶
func NewToolChecker() *ToolChecker
NewToolChecker creates a new API-based tool checker instance. The returned ToolChecker uses the API service locator pattern to access aggregator functionality for tool availability checking.
Returns:
- *ToolChecker: A new tool checker instance
func (*ToolChecker) GetAvailableTools ¶
func (atc *ToolChecker) GetAvailableTools() []string
GetAvailableTools returns all available tools using the aggregator API handler. This method enables the config package to perform comprehensive tool availability checks and provide detailed validation feedback.
func (*ToolChecker) IsToolAvailable ¶
func (atc *ToolChecker) IsToolAvailable(toolName string) bool
IsToolAvailable checks if a tool is available using the aggregator API handler. This method provides the config package with a way to validate tool availability during configuration loading and validation without creating tight coupling.
func (*ToolChecker) MissingToolsForSession ¶
func (atc *ToolChecker) MissingToolsForSession(ctx context.Context, toolNames []string) []string
MissingToolsForSession returns the subset of toolNames that is unavailable for the calling session, using the aggregator API handler. This lets consumers validate availability of SSO family tools without depending on a prior list_tools call in the session. When the aggregator is unavailable, all requested tools are reported missing.
type ToolMetadata ¶
type ToolMetadata struct {
// Name is the unique identifier for the tool (e.g., "workflow_list", "auth_login")
// Must be unique within the scope of the tool provider
Name string
// Description provides human-readable documentation about what the tool does
// and how to use it effectively
Description string
// Args defines the input arguments accepted by this tool,
// including validation rules and documentation
Args []ArgMetadata
// Labels carries free-form facets used by the discovery tier (filter_tools)
// to scope a lookup to a labelled subset of tools. For workflow execution
// tools these are propagated from the Workflow CRD's metadata.labels. They
// are not part of the MCP tool schema and do not appear in list_tools /
// describe_tool output.
Labels map[string]string
// Annotations are the MCP tool annotations (readOnlyHint, destructiveHint,
// idempotentHint, openWorldHint) the provider declares for the tool. They
// are forwarded verbatim on the exposed tool, so the meta-tools report
// them like a downstream server's and the built-in read-only toolset
// preset selects the read-only tools. Nil declares none.
Annotations *ToolAnnotations
// StepTools lists, for a workflow execution tool, the tools its steps
// call (step tools, condition tools, nested workflow_<name> tools). The
// aggregator derives the workflow's readOnlyHint from the hints of these
// tools in the caller's catalogue, so a listing needs no further lookup
// of the workflow definition. Empty for every other tool.
StepTools []string
}
ToolMetadata describes a tool that can be exposed through the MCP protocol. This metadata is used for tool discovery, documentation generation, and argument validation during tool execution.
Tools are the primary mechanism for exposing functionality through muster, allowing workflows, capabilities, and other components to be discoverable and executable through the standard MCP protocol.
type ToolProvider ¶
type ToolProvider interface {
// GetTools returns metadata for all tools this provider offers.
// This is used for tool discovery and documentation generation.
//
// The returned metadata should be stable and consistent across calls,
// as it's used for caching and tool registration purposes.
//
// Returns:
// - []ToolMetadata: List of all tools provided by this component
//
// Example:
//
// func (p *MyProvider) GetTools() []ToolMetadata {
// return []ToolMetadata{
// {
// Name: "my_operation",
// Description: "Performs my custom operation",
// Args: []ArgMetadata{
// {
// Name: "input",
// Type: "string",
// Required: true,
// Description: "Input data for processing",
// },
// },
// },
// }
// }
GetTools() []ToolMetadata
// ExecuteTool executes a specific tool by name with the provided arguments.
// This is the main entry point for tool execution and must handle
// arg validation, execution logic, and result formatting.
//
// Args:
// - ctx: Context for the operation, including cancellation and timeout
// - toolName: The name of the tool to execute (must match a tool from GetTools)
// - args: Arguments for the tool execution, should be validated against tool metadata
//
// Returns:
// - *CallToolResult: The result of the tool execution
// - error: Error if the tool doesn't exist or execution fails
//
// Example:
//
// func (p *MyProvider) ExecuteTool(ctx context.Context, toolName string, args map[string]any) (*CallToolResult, error) {
// switch toolName {
// case "my_operation":
// input, ok := args["input"].(string)
// if !ok {
// return &CallToolResult{
// Content: []any{"input arg must be a string"},
// IsError: true,
// }, nil
// }
// // Perform operation
// result := processInput(input)
// return &CallToolResult{
// Content: []any{result},
// IsError: false,
// }, nil
// default:
// return nil, fmt.Errorf("unknown tool: %s", toolName)
// }
// }
ExecuteTool(ctx context.Context, toolName string, args map[string]any) (*CallToolResult, error)
}
ToolProvider interface defines the contract for components that can provide tools to the MCP ecosystem. This interface is implemented by workflow and other tool-providing packages.
Components implementing this interface can expose their functionality as MCP tools that can be discovered and executed through the aggregator, making them available to external clients and internal orchestration.
All tool providers must implement both tool discovery (GetTools) and execution (ExecuteTool) to participate in the tool ecosystem.
func GetProcedureRunTools ¶ added in v5.67.0
func GetProcedureRunTools() ToolProvider
type ToolUpdateEvent ¶
type ToolUpdateEvent struct {
// Type specifies the kind of tool update event.
// Valid values: "server_registered", "server_deregistered", "tools_updated"
Type string `json:"type"`
// ServerName identifies the MCP server that triggered this event
ServerName string `json:"server_name"`
// Tools contains the list of tool names affected by this event.
// For "server_registered": all tools provided by the server
// For "server_deregistered": all tools that were removed
// For "tools_updated": the current complete tool list
Tools []string `json:"tools"`
// Timestamp records when this event occurred
Timestamp time.Time `json:"timestamp"`
// Error contains error information if the event represents a failure condition.
// Only populated for error events, empty for successful operations.
Error string `json:"error,omitempty"`
}
ToolUpdateEvent represents a tool availability change event in the MCP ecosystem. These events are published when MCP servers are registered/deregistered or when their available tools change, allowing components to react to tool availability changes.
Events are delivered asynchronously through the tool update subscription system, enabling real-time reactivity to changes in the tool landscape.
Example event types:
- "server_registered": A new MCP server has been registered
- "server_deregistered": An MCP server has been removed
- "tools_updated": Tools available from a server have changed
type ToolUpdateSubscriber ¶
type ToolUpdateSubscriber interface {
// OnToolsUpdated is called when tool availability changes in the system.
// Implementations should be non-blocking as this is called from goroutines.
//
// This method will be called for various tool availability events:
// - MCP server registration/deregistration
// - Changes in available tools from existing servers
// - Tool configuration updates
//
// Args:
// - event: ToolUpdateEvent containing details about what changed
//
// Note: This method is called asynchronously and should not block.
// Panics in this method are recovered and logged as errors.
//
// Example:
//
// func (s *MySubscriber) OnToolsUpdated(event api.ToolUpdateEvent) {
// switch event.Type {
// case "server_registered":
// log.Printf("New server %s registered with %d tools",
// event.ServerName, len(event.Tools))
// s.refreshCapabilities()
// case "server_deregistered":
// log.Printf("Server %s deregistered", event.ServerName)
// s.markToolsUnavailable(event.Tools)
// case "tools_updated":
// log.Printf("Tools updated for server %s", event.ServerName)
// s.updateToolCache(event.ServerName, event.Tools)
// }
// }
OnToolsUpdated(event ToolUpdateEvent)
}
ToolUpdateSubscriber interface defines the contract for components that want to receive notifications about tool availability changes.
Components implementing this interface can react to changes in the tool landscape, such as updating their own availability status, refreshing cached tool lists, or triggering recalculation of dependent functionality.
Subscribers are called asynchronously and should implement non-blocking operations to prevent affecting the overall system performance.
type ToolsetGate ¶ added in v5.67.0
type ToolsetGate interface {
// RefuseOutsideToolset returns the refusal of a call to name with args
// that falls outside a toolset bounding ctx's request, and nil for a call
// inside them or a request no toolset bounds.
RefuseOutsideToolset(ctx context.Context, name string, args map[string]any) error
}
ToolsetGate checks a tool call against the toolsets that bound its request (the toolset bound to the session and the request's X-Muster-Toolset header), the check call_tool makes. The aggregator asks it for the calls it dispatches for an organization principal that did not come through call_tool, such as a workflow's steps: the principal's toolset bounds every call made as the principal, not only the ones it names itself.
func GetToolsetGate ¶ added in v5.67.0
func GetToolsetGate() ToolsetGate
GetToolsetGate returns the registered toolset gate, or nil.
type ToolsetServerScope ¶ added in v5.58.0
type ToolsetServerScope interface {
// ToolsetServers returns, for a request bounded by a toolset, whether a
// server is admitted. scoped is false for a request no toolset bounds. An
// error means the toolset could not be resolved; callers admit nothing.
ToolsetServers(ctx context.Context) (admits func(server string) bool, scoped bool, err error)
// ToolsetCoreTools reports, for a request bounded by a toolset, whether
// the toolsets resolve at least one of muster's core tools. scoped and
// err are as for ToolsetServers.
ToolsetCoreTools(ctx context.Context) (resolves bool, scoped bool, err error)
}
ToolsetServerScope is implemented by the meta-tools handler: it tells which MCP servers the toolsets bounding a request admit, so server listings show no server whose tools the request cannot reach.
type Workflow ¶
type Workflow struct {
// Name is the unique identifier for this workflow
Name string `yaml:"name" json:"name"`
// Description provides human-readable documentation for the workflow's purpose
Description string `yaml:"description" json:"description"`
// Labels mirrors the Workflow CRD's metadata.labels. They are exposed as
// discovery facets on the workflow's execution tool so a client can scope a
// tool lookup to a labelled subset (e.g. by category) instead of dumping the
// whole catalogue.
Labels map[string]string `yaml:"labels,omitempty" json:"labels,omitempty"`
// Tags are the workflow's free-form tags, kept in the Workflow CR's
// TagsAnnotation. Read with ParseTags, so malformed entries are dropped.
Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"`
// Args defines the validation rules and metadata for workflow execution arguments.
// These definitions are used to validate arguments when executing workflows
// and to provide documentation for the workflow execution API.
Args map[string]ArgDefinition `yaml:"args,omitempty" json:"args,omitempty"`
// Steps defines the sequence of operations to be performed during workflow execution.
// Each step represents a tool call with its arguments and processing logic.
Steps []WorkflowStep `yaml:"steps" json:"steps"`
// OnFailure defines best-effort cleanup/rollback steps run when the workflow
// fails on a step that does not allow failure. Their own failures are tolerated.
OnFailure []WorkflowSubStep `yaml:"onFailure,omitempty" json:"onFailure,omitempty"`
// Output is an optional output template that shapes the returned document.
// It is rendered once after the steps complete, against .input / .results /
// .vars, and replaces the default response. Each leaf is a Go-template/sprig
// expression and JSON structure is preserved. When nil, the default response
// is returned.
Output map[string]interface{} `yaml:"output,omitempty" json:"output,omitempty"`
// Available indicates whether this workflow is currently available for execution
Available bool `json:"available,omitempty" yaml:"-"`
// CreatedAt indicates when this workflow was created
CreatedAt time.Time `yaml:"createdAt,omitempty" json:"createdAt"`
// LastModified indicates when this workflow was last updated
LastModified time.Time `yaml:"lastModified,omitempty" json:"lastModified"`
}
Workflow represents a single workflow definition and runtime state. This consolidates WorkflowDefinition, WorkflowInfo, and WorkflowConfig into one type to provide a unified view of workflow information across configuration and runtime contexts.
Workflows define multi-step processes that can be executed by the system, orchestrating tool calls, arg templating, and conditional logic. They provide a way to compose complex operations from simpler tool calls.
type WorkflowCondition ¶
type WorkflowCondition struct {
// Template is a boolean Go-template gate. When set, the step executes only
// if the template renders to a truthy value (e.g. "{{ eq .input.env \"production\" }}").
// Mutually exclusive with Tool/FromStep; when present, Expect/ExpectNot are ignored.
Template string `yaml:"template,omitempty" json:"template,omitempty"`
// Tool specifies the name of the tool to execute for condition evaluation.
// Must correspond to an available tool in the aggregator.
// Optional when FromStep or Template is used.
Tool string `yaml:"tool,omitempty" json:"tool,omitempty"`
// Args provides the arguments to pass to the condition tool.
// Can include templated values that are resolved at runtime.
Args map[string]interface{} `yaml:"args,omitempty" json:"args,omitempty"`
// FromStep specifies the step ID to reference for condition evaluation.
// When specified, the condition evaluates against the result of the referenced step
// instead of executing a new tool call.
FromStep string `yaml:"fromStep,omitempty" json:"fromStep,omitempty"`
// Expect defines the expected result for the condition to be considered true.
// If the condition tool result matches these expectations, the step will execute.
// If not, the step will be skipped.
Expect WorkflowConditionExpectation `yaml:"expect,omitempty" json:"expect,omitempty"`
// ExpectNot defines the negated expected result for the condition to be considered true.
// If the condition tool result does NOT match these expectations, the step will execute.
// If it matches, the step will be skipped.
ExpectNot WorkflowConditionExpectation `yaml:"expectNot,omitempty" json:"expectNot,omitempty"`
}
WorkflowCondition defines a condition that determines whether a workflow step should execute. Conditions allow for dynamic workflow execution based on runtime state evaluation.
func (*WorkflowCondition) UnmarshalJSON ¶ added in v5.34.11
func (c *WorkflowCondition) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a condition strictly, accepting the deprecated aliases.
type WorkflowConditionExpectation ¶
type WorkflowConditionExpectation struct {
// Success indicates whether the condition tool should succeed (true) or fail (false)
// for the condition to be met.
Success bool `yaml:"success" json:"success"`
// JsonPath defines optional JSON path expressions that must match specific values
// in the condition tool's response. All specified paths must match for the condition
// to be considered true. This allows for content-based condition validation beyond
// just success/failure status.
JsonPath map[string]interface{} `yaml:"jsonPath,omitempty" json:"jsonPath,omitempty"`
}
WorkflowConditionExpectation defines what result is expected from a condition tool for the condition to be considered true.
func (*WorkflowConditionExpectation) UnmarshalJSON ¶ added in v5.34.11
func (e *WorkflowConditionExpectation) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes an expectation strictly, accepting the deprecated aliases.
type WorkflowCreateRequest ¶
type WorkflowCreateRequest struct {
// Name is the unique identifier for the workflow (required).
// Must be unique across all workflows in the system.
Name string `json:"name" validate:"required"`
// Version indicates the workflow version for compatibility tracking.
// Recommended to use semantic versioning.
Version string `json:"version,omitempty"`
// Description provides human-readable documentation for the workflow.
// Should explain the workflow's purpose and expected outcomes.
Description string `json:"description,omitempty"`
// Tags are stored comma-joined in the Workflow's TagsAnnotation. Optional;
// each must pass ValidateTags. An empty list sets no annotation.
Tags []string `json:"tags,omitempty"`
// Args defines the expected input arguments for workflow execution.
// Used for arg validation and documentation generation.
// If not specified, the workflow accepts any args.
Args map[string]ArgDefinition `json:"args,omitempty"`
// Steps defines the sequence of operations to perform (required).
// Each step executes a tool with specified arguments and processing logic.
// Must contain at least one step for a valid workflow.
Steps []WorkflowStep `json:"steps" validate:"required"`
// OnFailure defines best-effort cleanup/rollback steps run when the workflow
// fails on a step that does not allow failure. Their own failures are tolerated.
OnFailure []WorkflowSubStep `json:"onFailure,omitempty"`
// Output is an optional output template that shapes the returned document.
Output map[string]interface{} `json:"output,omitempty"`
}
WorkflowCreateRequest represents a request to create a new workflow definition. Workflows define multi-step processes that orchestrate tool calls with arg templating and conditional logic.
Example:
request := WorkflowCreateRequest{
Name: "deploy-service",
Description: "Deploy a service to production",
Args: map[string]ArgDefinition{
"service_name": {
Type: "string",
Required: true,
Description: "Name of the service to deploy",
},
},
Steps: []WorkflowStep{
{
ID: "build",
Tool: "docker_build",
Args: map[string]interface{}{
"name": "{{service_name}}",
},
},
},
}
type WorkflowExecution ¶
type WorkflowExecution struct {
// ExecutionID is the unique identifier for this execution (UUID v4)
ExecutionID string `json:"execution_id"`
// WorkflowName is the name of the workflow that was executed
WorkflowName string `json:"workflow_name"`
// Status indicates the current state of the execution
Status WorkflowExecutionStatus `json:"status"`
// StartedAt is the timestamp when the execution began
StartedAt time.Time `json:"started_at"`
// CompletedAt is the timestamp when the execution finished (nil if still running)
CompletedAt *time.Time `json:"completed_at,omitempty"`
// DurationMs is the total execution duration in milliseconds
DurationMs int64 `json:"duration_ms"`
// Input contains the original arguments passed to the workflow
Input map[string]any `json:"input"`
// Result contains the final result of the workflow execution (nil if failed or in progress)
Result any `json:"result,omitempty"`
// Error contains error information if the execution failed (nil if successful)
Error *string `json:"error,omitempty"`
// Steps contains detailed information about each step execution
Steps []WorkflowExecutionStep `json:"steps"`
// Truncated indicates that oversized payloads (the workflow/step Input
// and/or Result fields) were bounded before the record was persisted, so the
// stored record stays well within the backend's per-object size limit (e.g.
// etcd in Kubernetes mode). When true, the omitted payloads were replaced
// with a marker.
Truncated bool `json:"truncated,omitempty"`
}
WorkflowExecution represents a complete workflow execution record. This provides comprehensive information about a workflow execution including timing, results, errors, and detailed step-by-step execution information.
Workflow executions are automatically tracked when workflows are executed via the workflow_<name> tools, enabling debugging, auditing, and monitoring.
type WorkflowExecutionStatus ¶
type WorkflowExecutionStatus string
WorkflowExecutionStatus represents the status of a workflow execution
const ( // WorkflowExecutionInProgress indicates the execution is currently running WorkflowExecutionInProgress WorkflowExecutionStatus = "inprogress" // WorkflowExecutionCompleted indicates the execution finished successfully WorkflowExecutionCompleted WorkflowExecutionStatus = "completed" // WorkflowExecutionFailed indicates the execution failed with an error WorkflowExecutionFailed WorkflowExecutionStatus = "failed" )
type WorkflowExecutionStep ¶
type WorkflowExecutionStep struct {
// StepID is the unique identifier for this step within the workflow
StepID string `json:"step_id"`
// Tool is the name of the tool that was executed for this step
Tool string `json:"tool"`
// Status indicates the current state of the step execution
Status WorkflowExecutionStatus `json:"status"`
// StartedAt is the timestamp when the step execution began
StartedAt time.Time `json:"started_at"`
// CompletedAt is the timestamp when the step execution finished (nil if still running)
CompletedAt *time.Time `json:"completed_at,omitempty"`
// DurationMs is the step execution duration in milliseconds
DurationMs int64 `json:"duration_ms"`
// Input contains the resolved arguments passed to the tool for this step
Input map[string]any `json:"input"`
// Result contains the result returned by the tool execution (nil if failed or in progress)
Result any `json:"result,omitempty"`
// Error contains error information if the step failed (nil if successful)
Error *string `json:"error,omitempty"`
// StoredAs is the variable name where the step result was stored (from workflow definition)
StoredAs string `json:"stored_as,omitempty"`
}
WorkflowExecutionStep represents a single step execution within a workflow. This provides detailed information about individual step execution including timing, arguments, results, and any errors that occurred.
Step execution information enables granular debugging and understanding of workflow execution flow and data transformation.
type WorkflowExecutionSummary ¶
type WorkflowExecutionSummary struct {
// ExecutionID is the unique identifier for this execution
ExecutionID string `json:"execution_id"`
// WorkflowName is the name of the workflow that was executed
WorkflowName string `json:"workflow_name"`
// Status indicates the current state of the execution
Status WorkflowExecutionStatus `json:"status"`
// StartedAt is the timestamp when the execution began
StartedAt time.Time `json:"started_at"`
// CompletedAt is the timestamp when the execution finished (nil if still running)
CompletedAt *time.Time `json:"completed_at,omitempty"`
// DurationMs is the total execution duration in milliseconds
DurationMs int64 `json:"duration_ms"`
// StepCount is the total number of steps in the workflow
StepCount int `json:"step_count"`
// Error contains error information if the execution failed (nil if successful)
Error *string `json:"error,omitempty"`
}
WorkflowExecutionSummary represents a summary of a workflow execution for use in list responses. This contains essential information without the detailed step execution data to optimize performance.
Summary information is sufficient for most listing and overview use cases, with detailed information available via GetWorkflowExecution.
type WorkflowForEach ¶
type WorkflowForEach struct {
// Items is a template expression that must resolve to an array,
// e.g. "{{ .input.clusters }}".
Items string `yaml:"items" json:"items"`
// As is the loop variable name made available to the body as
// "{{ .vars.<as> }}". Defaults to "item".
As string `yaml:"as,omitempty" json:"as,omitempty"`
// Parallelism is how many iterations may run at once, 1 to
// MaxForEachParallelism. Unset (0) runs them one after another.
Parallelism int `yaml:"parallelism,omitempty" json:"parallelism,omitempty"`
// Steps is the body executed for each item.
Steps []WorkflowSubStep `yaml:"steps" json:"steps"`
}
WorkflowForEach describes a loop over a list of items. The body is a list of sub-steps executed once per item; in a top-level forEach a body sub-step may itself be a forEach, one level deep.
func (*WorkflowForEach) LoopVariable ¶ added in v5.50.0
func (f *WorkflowForEach) LoopVariable() string
LoopVariable is the name the loop's current item is bound to.
type WorkflowHandler ¶
type WorkflowHandler interface {
// ExecuteWorkflow executes a workflow with the provided arguments.
// This is the primary method for invoking workflow functionality.
//
// Args:
// - ctx: Context for the operation, including cancellation and timeout
// - workflowName: The name of the workflow to execute
// - args: Arguments for the workflow execution, validated against input schema
//
// Returns:
// - *CallToolResult: The result of the workflow execution
// - error: Error if the workflow doesn't exist or execution fails
//
// Example:
//
// result, err := handler.ExecuteWorkflow(ctx, "deploy-service", map[string]interface{}{
// "service_name": "my-api",
// "environment": "production",
// "replicas": 3,
// })
ExecuteWorkflow(ctx context.Context, workflowName string, args map[string]interface{}) (*CallToolResult, error)
// ListWorkflowExecutions returns paginated list of workflow executions with optional filtering.
// This enables users to view execution history and track workflow usage patterns.
//
// Args:
// - ctx: Context for the operation, including cancellation and timeout
// - req: Request args for filtering, pagination, and sorting
//
// Returns:
// - *ListWorkflowExecutionsResponse: Paginated list of execution records
// - error: Error if the request is invalid or operation fails
ListWorkflowExecutions(ctx context.Context, req *ListWorkflowExecutionsRequest) (*ListWorkflowExecutionsResponse, error)
// GetWorkflowExecution returns detailed information about a specific workflow execution.
// This enables users to examine execution results, step details, and debug failed executions.
//
// Args:
// - ctx: Context for the operation, including cancellation and timeout
// - req: Request args specifying execution ID and optional filtering
//
// Returns:
// - *WorkflowExecution: Complete execution record with step details
// - error: Error if the execution doesn't exist or operation fails
GetWorkflowExecution(ctx context.Context, req *GetWorkflowExecutionRequest) (*WorkflowExecution, error)
// GetWorkflows returns information about all available workflows in the system.
// This includes both static workflow definitions and runtime availability status.
//
// Returns:
// - []Workflow: List of all workflow definitions with runtime information
GetWorkflows() []Workflow
// GetWorkflow returns detailed information about a specific workflow.
// This provides comprehensive information including steps, input schema, and metadata.
//
// Args:
// - name: The name of the workflow to retrieve
//
// Returns:
// - *Workflow: Detailed workflow information including definition and runtime state
// - error: Error if the workflow doesn't exist
GetWorkflow(name string) (*Workflow, error)
// ValidateWorkflowFromStructured validates a workflow definition without creating it.
// This is useful for validation during workflow development and testing.
//
// Args:
// - args: Workflow definition args to validate
//
// Returns:
// - error: Error if the workflow definition is invalid
ValidateWorkflowFromStructured(args map[string]interface{}) error
// ToolProvider integration for exposing workflows as discoverable MCP tools.
// This allows workflows to be discovered and executed through the standard
// tool discovery and execution mechanisms.
ToolProvider
}
WorkflowHandler defines the interface for workflow operations within the Service Locator Pattern. This handler provides the primary interface for workflow management, execution, and discovery.
The handler abstracts workflow complexity behind a simple interface, allowing components to execute multi-step processes without knowing the underlying orchestration details. It integrates with the ToolProvider interface to expose workflows as discoverable MCP tools.
func GetWorkflow ¶
func GetWorkflow() WorkflowHandler
GetWorkflow returns the registered workflow handler. This provides access to workflow definition management and execution functionality.
Returns nil if no handler has been registered yet. Callers should always check for nil before using the returned handler.
Returns:
- WorkflowHandler: The registered handler, or nil if not registered
Thread-safe: Yes, protected by handlerMutex read lock.
Example:
workflow := api.GetWorkflow()
if workflow == nil {
return fmt.Errorf("workflow handler not available")
}
result, err := workflow.ExecuteWorkflow(ctx, "deploy-app", args)
type WorkflowInputSchema ¶
type WorkflowInputSchema struct {
// Type specifies the overall schema type (typically "object" for workflow inputs)
Type string `yaml:"type" json:"type"`
// Args defines the individual input arguments and their schemas.
// Each property corresponds to a workflow input argument.
Args map[string]SchemaProperty `yaml:"args" json:"args"`
// Required lists the argument names that must be provided for workflow execution
Required []string `yaml:"required,omitempty" json:"required,omitempty"`
}
WorkflowInputSchema defines the input argument schema for a workflow. This provides structured validation and documentation for workflow inputs, following JSON Schema conventions for argument definition.
DEPRECATED: Use Args map[string]ArgDefinition instead
type WorkflowPaginate ¶ added in v5.50.0
type WorkflowPaginate struct {
// ItemsField is where a page's list is. Defaults to "items".
ItemsField string `yaml:"itemsField,omitempty" json:"itemsField,omitempty"`
// TokenField is where a page's next-page token is. Defaults to "continue".
TokenField string `yaml:"tokenField,omitempty" json:"tokenField,omitempty"`
// TokenArg is the tool argument the token is passed in. Defaults to
// "continue".
TokenArg string `yaml:"tokenArg,omitempty" json:"tokenArg,omitempty"`
// MaxPages bounds the pages fetched, 1 to MaxPaginateMaxPages. Defaults
// to DefaultPaginateMaxPages.
MaxPages int `yaml:"maxPages,omitempty" json:"maxPages,omitempty"`
}
WorkflowPaginate describes how a tool step follows the tool's pages: it passes the token found at TokenField back as the TokenArg argument until the token is empty or MaxPages pages were fetched, and concatenates the list found at ItemsField. Field names may be dotted paths ("data.next").
type WorkflowStep ¶
type WorkflowStep struct {
// ID is a unique identifier for this step within the workflow.
// Used for step referencing, error reporting, and execution flow control.
ID string `yaml:"id" json:"id"`
// Condition defines an optional condition that determines whether this step should execute.
// If specified, the condition tool is executed first. If the condition is not met,
// the step is skipped and marked as "skipped" in the execution results.
Condition *WorkflowCondition `yaml:"condition,omitempty" json:"condition,omitempty"`
// Tool specifies the name of the tool to execute for this step.
// Must correspond to an available tool in the aggregator.
Tool string `yaml:"tool" json:"tool"`
// Args provides the arguments to pass to the tool.
// Can include templated values that are resolved at runtime using previous step results.
Args map[string]interface{} `yaml:"args,omitempty" json:"args,omitempty"`
// Paginate makes a tool step follow the tool's next-page token and store
// every page's items as one list. Only valid with Tool.
Paginate *WorkflowPaginate `yaml:"paginate,omitempty" json:"paginate,omitempty"`
// JQ is a jq program that reshapes the step's result before it is stored:
// the tool's result for a tool step, the per-iteration records for a
// forEach step. Later steps, the output template and the step record see
// only what it yields.
JQ string `yaml:"jq,omitempty" json:"jq,omitempty"`
// ForEach executes a body of sub-steps once per item of a list.
// Mutually exclusive with Tool and Parallel.
ForEach *WorkflowForEach `yaml:"forEach,omitempty" json:"forEach,omitempty"`
// Parallel executes a group of sub-steps concurrently.
// Mutually exclusive with Tool and ForEach.
Parallel []WorkflowSubStep `yaml:"parallel,omitempty" json:"parallel,omitempty"`
// AllowFailure indicates whether this step is allowed to fail without failing the workflow.
// When true, step failures are recorded but the workflow continues execution.
// The step result will be available for subsequent step conditions to reference.
AllowFailure bool `yaml:"allowFailure,omitempty" json:"allowFailure,omitempty"`
// Output indicates whether this step's result is included in the workflow's
// returned document. Every step result is always referenceable by later steps
// regardless of this flag; Output only controls visibility in the returned
// result. When nil, the deprecated Store flag is used as a fallback.
Output *bool `yaml:"output,omitempty" json:"output,omitempty"`
// Store is a deprecated alias for Output, kept for backwards compatibility.
// Referencing a step result no longer requires Store; it now only affects
// result visibility. Prefer Output.
Store bool `yaml:"store,omitempty" json:"store,omitempty"`
// Description provides human-readable documentation for this step's purpose
Description string `yaml:"description,omitempty" json:"description,omitempty"`
}
WorkflowStep defines a single step in a workflow execution. Each step represents a tool call with its arguments, result processing, and conditional execution logic.
func (*WorkflowStep) UnmarshalJSON ¶ added in v5.34.11
func (s *WorkflowStep) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a step strictly, accepting the deprecated aliases.
type WorkflowSubStep ¶
type WorkflowSubStep struct {
// ID is a unique identifier for this sub-step.
ID string `yaml:"id" json:"id"`
// Condition defines an optional condition that determines whether this sub-step should execute.
Condition *WorkflowCondition `yaml:"condition,omitempty" json:"condition,omitempty"`
// Tool specifies the name of the tool to execute. Mutually exclusive with
// ForEach.
Tool string `yaml:"tool,omitempty" json:"tool,omitempty"`
// Args provides the arguments to pass to the tool (supports templating).
Args map[string]interface{} `yaml:"args,omitempty" json:"args,omitempty"`
// ForEach makes this sub-step a nested loop. Only valid in a top-level
// forEach body; mutually exclusive with Tool.
ForEach *WorkflowForEach `yaml:"forEach,omitempty" json:"forEach,omitempty"`
// Paginate makes a tool sub-step follow the tool's pages (see
// WorkflowStep.Paginate).
Paginate *WorkflowPaginate `yaml:"paginate,omitempty" json:"paginate,omitempty"`
// JQ reshapes the sub-step's result before it is stored (see
// WorkflowStep.JQ).
JQ string `yaml:"jq,omitempty" json:"jq,omitempty"`
// AllowFailure indicates whether this sub-step is allowed to fail without failing execution.
AllowFailure bool `yaml:"allowFailure,omitempty" json:"allowFailure,omitempty"`
// Output indicates whether this sub-step's result is included in the
// workflow's returned document. The result is always referenceable by later
// steps regardless of this flag. When nil, the deprecated Store flag is used
// as a fallback.
Output *bool `yaml:"output,omitempty" json:"output,omitempty"`
// Store is a deprecated alias for Output, kept for backwards compatibility.
// Prefer Output.
Store bool `yaml:"store,omitempty" json:"store,omitempty"`
// Description provides human-readable documentation for this sub-step's purpose.
Description string `yaml:"description,omitempty" json:"description,omitempty"`
}
WorkflowSubStep is a tool-call step used inside forEach bodies, parallel groups, and onFailure handlers. Inside a top-level forEach body it may instead be a forEach of its own (ForEach), whose sub-steps are tool calls.
func (*WorkflowSubStep) UnmarshalJSON ¶ added in v5.34.11
func (s *WorkflowSubStep) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a sub-step strictly, accepting the deprecated aliases.
type WorkflowUpdateRequest ¶
type WorkflowUpdateRequest struct {
// Name of the workflow to update (required).
Name string `json:"name" validate:"required"`
// Version can be updated to reflect changes.
Version string `json:"version,omitempty"`
// Description can be updated to improve documentation.
Description string `json:"description,omitempty"`
// Tags replace the TagsAnnotation. Tri-state: omitting them keeps the
// current tags, an empty list removes them.
Tags *[]string `json:"tags,omitempty"`
// Args can be modified to change arg requirements.
// Changes may affect existing callers of this workflow.
Args map[string]ArgDefinition `json:"args,omitempty"`
// Steps can be added, modified, or reordered.
// Changes affect workflow execution behavior.
Steps []WorkflowStep `json:"steps,omitempty"`
// OnFailure defines best-effort cleanup/rollback steps run when the workflow
// fails on a step that does not allow failure. Their own failures are tolerated.
OnFailure []WorkflowSubStep `json:"onFailure,omitempty"`
// Output is an optional output template that shapes the returned document.
Output map[string]interface{} `json:"output,omitempty"`
}
WorkflowUpdateRequest represents a request to update an existing workflow definition. This allows modification of workflow steps, input args, and metadata.
type WorkflowValidateRequest ¶
type WorkflowValidateRequest struct {
// Name for validation (required).
Name string `json:"name" validate:"required"`
// Version for validation.
Version string `json:"version,omitempty"`
// Description for validation.
Description string `json:"description,omitempty"`
// Tags for validation, as on create.
Tags []string `json:"tags,omitempty"`
// Args for validation.
Args map[string]ArgDefinition `json:"args,omitempty"`
// Steps for validation (required). All referenced tools will be checked for availability.
Steps []WorkflowStep `json:"steps" validate:"required"`
// OnFailure defines best-effort cleanup/rollback steps run when the workflow
// fails on a step that does not allow failure. Their own failures are tolerated.
OnFailure []WorkflowSubStep `json:"onFailure,omitempty"`
// Output is an optional output template that shapes the returned document.
Output map[string]interface{} `json:"output,omitempty"`
}
WorkflowValidateRequest represents a request to validate a workflow definition without creating it. Validates step configuration, tool availability, and arg schemas.
Source Files
¶
- agent_approval.go
- aggregator.go
- approval.go
- approval_audit.go
- approval_handoff.go
- approval_request.go
- auth_handler.go
- auth_messages.go
- browser_identity.go
- caller_authentication.go
- caller_meta.go
- config.go
- constants.go
- delegated_caller.go
- doc.go
- errors.go
- event_poller.go
- events.go
- governance.go
- handlers.go
- json_keys.go
- login_token.go
- mcp_schema.go
- mcpserver.go
- mcpserver_credentials.go
- mcpserver_grant_scope.go
- mcpserver_namespace.go
- mcpserver_principal_audience.go
- mcpserver_user_signin.go
- mcpserver_visibility.go
- metatools.go
- muster_caller.go
- oauth.go
- oauth_issuer_key.go
- orchestrator.go
- organization_principal.go
- procedure_runs.go
- protocol.go
- request_meta.go
- requests.go
- resource_name.go
- resource_types.go
- secret_binding.go
- secret_credentials.go
- sensitive_args.go
- server_tool_resolver.go
- service.go
- session_subject.go
- session_tool_cache.go
- sessions.go
- sign_in_prompt.go
- tags.go
- token_exchange.go
- token_exchange_outcome.go
- toolset_gate.go
- types.go
- workflow.go
- workflow_aliases.go
- workflow_loops.go
- workflow_tools.go