Documentation
¶
Overview ¶
Package aggregator provides capability aggregation for Virtual MCP Server.
This package discovers backend MCP servers, queries their capabilities, resolves naming conflicts, and merges them into a unified view. The aggregation process has three stages: query, conflict resolution, and merging.
Package aggregator provides capability aggregation for Virtual MCP Server.
This file contains the factory function for creating conflict resolvers and shared helper functions used by multiple resolver implementations.
Package aggregator provides platform-specific backend discovery implementations.
This file contains:
- Unified backend discoverer implementation (works with both CLI and Kubernetes)
- Factory function to create BackendDiscoverer based on runtime environment
- WorkloadDiscoverer interface and implementations are in pkg/vmcp/workloads
The BackendDiscoverer interface is defined in aggregator.go.
Package aggregator provides capability aggregation for Virtual MCP Server.
Index ¶
- Variables
- type AggregatedCapabilities
- type AggregationMetadata
- type Aggregator
- type BackendCapabilities
- type BackendDiscoverer
- func NewBackendDiscoverer(ctx context.Context, groupsManager groups.Manager, ...) (BackendDiscoverer, error)
- func NewUnifiedBackendDiscoverer(workloadsManager workloads.Discoverer, groupsManager groups.Manager, ...) BackendDiscoverer
- func NewUnifiedBackendDiscovererWithStaticBackends(staticBackends []config.StaticBackendConfig, ...) BackendDiscoverer
- type CacheInvalidator
- type ConflictResolver
- type ManualConflictResolver
- type Option
- type PrefixConflictResolver
- type PriorityConflictResolver
- type ResolvedCapabilities
- type ResolvedPrompt
- type ResolvedTool
- type ToolFilter
- type ToolOverride
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNoBackendsFound indicates no backends were discovered. ErrNoBackendsFound = fmt.Errorf("no backends found in group") // ErrNoBackendCapabilities indicates that no backend's capabilities could // be queried: every backend aggregated failed discovery. A backend that is // pending (needs the caller to connect an upstream provider) counts as // having answered, so a set of only pending backends does not return it. ErrNoBackendCapabilities = fmt.Errorf("no backends returned capabilities") // ErrBackendQueryFailed indicates a backend query failed. ErrBackendQueryFailed = fmt.Errorf("failed to query backend capabilities") // ErrUnresolvedConflicts indicates conflicts exist without resolution. ErrUnresolvedConflicts = fmt.Errorf("unresolved capability name conflicts") // ErrInvalidConflictStrategy indicates an unknown conflict resolution strategy. ErrInvalidConflictStrategy = fmt.Errorf("invalid conflict resolution strategy") )
Common aggregation errors.
Functions ¶
This section is empty.
Types ¶
type AggregatedCapabilities ¶
type AggregatedCapabilities struct {
// Tools are the aggregated backend tools (ready to expose to clients),
// sorted by name for deterministic ordering.
Tools []vmcp.Tool
// CompositeTools are the composite workflow tools defined in vMCP configuration.
// These are separate from backend tools and orchestrate multi-step workflows.
CompositeTools []vmcp.Tool
// Resources are the aggregated resources.
Resources []vmcp.Resource
// ResourceTemplates are the aggregated resource templates.
ResourceTemplates []vmcp.ResourceTemplate
// Prompts are the aggregated prompts.
Prompts []vmcp.Prompt
// SupportsLogging indicates if logging is supported.
SupportsLogging bool
// SupportsSampling indicates if sampling is supported.
SupportsSampling bool
// RoutingTable maps capabilities to their backend targets.
RoutingTable *vmcp.RoutingTable
// Metadata contains aggregation statistics and info.
Metadata *AggregationMetadata
// "prompts/list") whose listing failed transiently on that backend, so the
// backend's items of that kind are missing from this view although the
// backend was aggregated. It is set by AggregateCapabilities; a backend
// with every list available, or that failed discovery, has no entry, and
// an Aggregator that does not report it leaves it nil.
UnavailableLists map[string][]string
// Pending maps a backend ID to the authorization it needs. A backend
// listed here answered with no capabilities because the caller has not
// connected the upstream provider, so it contributes nothing to this view.
// It is for consumers that need to know which backends are waiting for the
// user to connect a provider. It is filled before admission, so a consumer
// must filter it by admission before exposing it to a caller. A pending
// backend is never in UnavailableLists. When sign-in tools are on
// (SignInNames non-nil), a view with a non-empty Pending describes one
// caller at one moment and must not be cached. It is nil when no backend
// is pending.
Pending map[string]*authtypes.DelegatedAuthRequiredError
// SignInNames maps the ID of every backend in the view, pending or not, to
// the name of its sign-in tool, except that a name several backends share
// is recorded for its owner only (see WithSignInTools). A backend that
// failed discovery is in it but not in Pending. Those names are reserved:
// no backend tool is advertised under one. A nil map means sign-in tools are off
// (WithSignInTools not set); the core relies on that.
SignInNames map[string]string
}
AggregatedCapabilities is the final unified view of all backend capabilities. This is what gets exposed to MCP clients via tools/list, resources/list, prompts/list.
type AggregationMetadata ¶
type AggregationMetadata struct {
// BackendCount is the number of backends aggregated.
BackendCount int
// ToolCount is the total number of tools.
ToolCount int
// ResourceCount is the total number of resources.
ResourceCount int
// ResourceTemplateCount is the total number of resource templates.
ResourceTemplateCount int
// PromptCount is the total number of prompts.
PromptCount int
// ConflictStrategy is the strategy used for conflict resolution.
ConflictStrategy vmcp.ConflictResolutionStrategy
}
AggregationMetadata contains information about the aggregation process.
type Aggregator ¶
type Aggregator interface {
// QueryCapabilities queries a backend for its MCP capabilities.
// Returns the raw capabilities (tools, resources, prompts) from the backend.
// A backend that is pending (the caller has not connected the upstream
// provider it needs) returns capabilities with only Pending set and a nil
// error.
QueryCapabilities(ctx context.Context, backend vmcp.Backend) (*BackendCapabilities, error)
// QueryAllCapabilities queries all backends for their capabilities in parallel.
// Handles backend failures gracefully (logs and continues with remaining backends).
// A pending backend counts as having answered. When no backend's capabilities
// could be queried, it returns an error wrapping ErrNoBackendCapabilities.
QueryAllCapabilities(ctx context.Context, backends []vmcp.Backend) (map[string]*BackendCapabilities, error)
// ResolveConflicts applies conflict resolution strategy to handle
// duplicate capability names across backends.
ResolveConflicts(ctx context.Context, capabilities map[string]*BackendCapabilities) (*ResolvedCapabilities, error)
// MergeCapabilities creates the final unified capability view and routing table.
// Uses the backend registry to populate full BackendTarget information for routing.
MergeCapabilities(
ctx context.Context,
resolved *ResolvedCapabilities,
registry vmcp.BackendRegistry,
) (*AggregatedCapabilities, error)
// AggregateCapabilities is a convenience method that performs the full aggregation pipeline:
// 1. Query all backends
// 2. Resolve conflicts
// 3. Merge into final view
// A pending backend counts as having answered. When no backend's capabilities
// could be queried, it returns an error wrapping ErrNoBackendCapabilities.
AggregateCapabilities(ctx context.Context, backends []vmcp.Backend) (*AggregatedCapabilities, error)
}
Aggregator aggregates capabilities from discovered backends into a unified view. This is the core of the virtual MCP server's capability management.
The aggregation process has three stages:
- Query: Fetch capabilities from each backend
- Conflict Resolution: Handle duplicate tool/resource/prompt names
- Merging: Create final unified capability view and routing table
func NewCachingAggregator ¶ added in v0.30.1
func NewCachingAggregator(next Aggregator, ttl time.Duration) Aggregator
NewCachingAggregator wraps next so AggregateCapabilities results are memoized per identity for ttl, backed by a size-bounded LRU, with concurrent misses for the same key sharing one backend sweep. A ttl <= 0 disables caching (next is returned unwrapped) so a misconfiguration cannot silently serve permanently-stale capabilities. A nil next is returned as-is so the downstream nil-aggregator validation (core.New) still fires rather than being masked by a non-nil wrapper.
core.New does not install this cache; only server.New wraps the configured aggregator with it. Embedders that build the core with core.New and serve it themselves must wrap their aggregator with NewCachingAggregator to get caching and burst deduplication, and must only do so if their aggregator's result depends on nothing in the context beyond the cache key inputs (the session binding, platform user ID, forwarded headers and backend IDs). The cache and the shared sweep hand one caller's result to every other caller with the same key. That rules out three kinds of aggregator:
- one whose result varies with the identity's tokens, which are not in the key;
- one that relies on side effects of running during the call, such as recording names in the context, because a hit or a joined sweep skips them (bypass the cache for those calls);
- one whose caller checks the returned view against a per-call value in the context. Run that check outside the cache, so it also covers hits and joined sweeps.
The core finds the cache through the aggregator type it was given (see CacheInvalidator), so a decorator placed around this one must forward InvalidateAll.
func NewDefaultAggregator ¶
func NewDefaultAggregator( backendClient vmcp.BackendClient, conflictResolver ConflictResolver, aggregationConfig *config.AggregationConfig, tracerProvider trace.TracerProvider, opts ...Option, ) Aggregator
NewDefaultAggregator creates a new default aggregator implementation. conflictResolver handles tool name conflicts across backends. aggregationConfig specifies aggregation settings including tool filtering/overrides, excludeAllTools, and defaultToolVisibility. tracerProvider is used to create a tracer for distributed tracing (pass nil for no tracing). opts enable optional behavior such as WithSignInTools.
type BackendCapabilities ¶
type BackendCapabilities struct {
// BackendID identifies the source backend.
BackendID string
// Tools are the tools exposed by this backend.
Tools []vmcp.Tool
// Resources are the resources exposed by this backend.
Resources []vmcp.Resource
// ResourceTemplates are the resource templates exposed by this backend.
ResourceTemplates []vmcp.ResourceTemplate
// Prompts are the prompts exposed by this backend.
Prompts []vmcp.Prompt
// SupportsLogging indicates if the backend supports MCP logging.
SupportsLogging bool
// SupportsSampling indicates if the backend supports MCP sampling.
SupportsSampling bool
// transiently; see vmcp.CapabilityList.UnavailableLists.
UnavailableLists []string
// Pending is non-nil when this backend answered with no capabilities
// because the caller has not yet connected the upstream provider it needs.
// It is nil otherwise.
Pending *authtypes.DelegatedAuthRequiredError
}
BackendCapabilities contains the raw capabilities from a single backend.
type BackendDiscoverer ¶
type BackendDiscoverer interface {
// Discover finds all backend workloads in the specified group.
// Returns only healthy/running backends.
// Results are always sorted alphabetically by backend name to ensure deterministic ordering.
// The groupRef format is platform-specific (group name for CLI, MCPGroup name for K8s).
Discover(ctx context.Context, groupRef string) ([]vmcp.Backend, error)
}
BackendDiscoverer discovers backend MCP server workloads. This abstraction enables different discovery mechanisms for CLI (Docker/Podman) and Kubernetes (Pods/Services).
func NewBackendDiscoverer ¶ added in v0.6.6
func NewBackendDiscoverer( ctx context.Context, groupsManager groups.Manager, authConfig *config.OutgoingAuthConfig, ) (BackendDiscoverer, error)
NewBackendDiscoverer creates a unified BackendDiscoverer based on the runtime environment. It automatically detects whether to use CLI (Docker/Podman) or Kubernetes workloads and creates the appropriate WorkloadDiscoverer implementation.
Parameters:
- ctx: Context for creating managers
- groupsManager: Manager for group operations (must already be initialized)
- authConfig: Outgoing authentication configuration for discovered backends
Returns:
- BackendDiscoverer: A unified discoverer that works with both CLI and Kubernetes workloads
- error: If manager creation fails
func NewUnifiedBackendDiscoverer ¶ added in v0.6.6
func NewUnifiedBackendDiscoverer( workloadsManager workloads.Discoverer, groupsManager groups.Manager, authConfig *config.OutgoingAuthConfig, ) BackendDiscoverer
NewUnifiedBackendDiscoverer creates a unified backend discoverer that works with both CLI and Kubernetes workloads through the WorkloadDiscoverer interface.
The authConfig parameter configures authentication for discovered backends. If nil, backends will have no authentication configured.
func NewUnifiedBackendDiscovererWithStaticBackends ¶ added in v0.8.0
func NewUnifiedBackendDiscovererWithStaticBackends( staticBackends []config.StaticBackendConfig, authConfig *config.OutgoingAuthConfig, groupRef string, headerForwardByBackend map[string]*vmcp.HeaderForwardConfig, ) BackendDiscoverer
NewUnifiedBackendDiscovererWithStaticBackends creates a backend discoverer for static mode with pre-configured backends, eliminating the need for K8s API access.
headerForwardByBackend carries per-backend HeaderForwardConfig (keyed by backend name) constructed at startup from the operator-emitted env vars. Pass nil when no entry in the group declares headerForward — the discoverer will simply leave Backend.HeaderForward nil for every backend.
type CacheInvalidator ¶ added in v0.41.0
type CacheInvalidator interface {
// InvalidateAll purges every cached AggregateCapabilities entry so the next
// call for any identity re-sweeps the backends.
InvalidateAll()
}
CacheInvalidator is optionally implemented by an Aggregator that memoizes AggregateCapabilities results (see cachingAggregator). It lets a caller force a re-sweep of all cached entries after learning, out of band, that backend capabilities changed — e.g. a persistent backend connection observing notifications/tools/list_changed (#5748) — rather than waiting out the TTL.
InvalidateAll purges the ENTIRE cache (every identity's entry), not just the backend that changed: the cache has no per-backend index, and coarse invalidation briefly de-optimizes other identities' cached views rather than leaving any identity looking at stale capabilities. Callers that type-assert an Aggregator to this interface must handle the case where it is not implemented (a non-caching or differently-implemented Aggregator) — see core.coreVMCP.InvalidateCapabilityCache for the WARN-log fallback.
type ConflictResolver ¶
type ConflictResolver interface {
// ResolveToolConflicts resolves tool name conflicts using the configured strategy.
ResolveToolConflicts(ctx context.Context, tools map[string][]vmcp.Tool) (map[string]*ResolvedTool, error)
}
ConflictResolver handles tool name conflicts across backends.
func NewConflictResolver ¶ added in v0.5.2
func NewConflictResolver(aggregationConfig *config.AggregationConfig) (ConflictResolver, error)
NewConflictResolver creates the appropriate conflict resolver based on configuration.
type ManualConflictResolver ¶ added in v0.5.2
type ManualConflictResolver struct {
// Overrides maps (backendID, originalToolName) to the resolved configuration.
// Key format: "backendID:toolName"
Overrides map[string]*config.ToolOverride
}
ManualConflictResolver implements manual conflict resolution. It requires explicit overrides for ALL conflicts and fails startup if any are unresolved.
func NewManualConflictResolver ¶ added in v0.5.2
func NewManualConflictResolver(workloadConfigs []*config.WorkloadToolConfig) (*ManualConflictResolver, error)
NewManualConflictResolver creates a new manual conflict resolver. Note: This resolver validates that overrides don't create NEW conflicts. If two tools are both overridden to the same name, ResolveToolConflicts will return an error ("collision after override").
func (*ManualConflictResolver) ResolveToolConflicts ¶ added in v0.5.2
func (r *ManualConflictResolver) ResolveToolConflicts( _ context.Context, toolsByBackend map[string][]vmcp.Tool, ) (map[string]*ResolvedTool, error)
ResolveToolConflicts applies manual conflict resolution with validation. Returns an error if any conflicts exist without explicit overrides.
type Option ¶ added in v0.72.0
type Option func(*defaultAggregator)
Option configures optional behavior of the default aggregator.
func WithSignInTools ¶ added in v0.72.0
WithSignInTools makes the aggregator advertise a sign-in tool for each backend that is pending upstream authorization, and record the sign-in tool name of every aggregated backend in AggregatedCapabilities.SignInNames. It is meant for embedders; vMCP does not enable it itself. Without it, a pending backend contributes nothing to the view.
name returns the sign-in tool name for a backend ID. A nil name selects the default: the aggregator's own prefix format applied to "sign_in" under the prefix strategy (for example github_sign_in), and "<backend ID>_sign_in" under the priority and manual strategies. An embedder that prefixes backend tools itself passes a function so its sign-in names stay consistent with that prefix.
Every recorded sign-in name is reserved: a backend tool with the same advertised name is not listed or routed. AggregateCapabilities reserves the name of every backend in the current view, including one whose discovery failed in this round, so a stale client calling that name cannot reach another operation. A backend the health monitor filters out is not in the view, so its name is not reserved while it is unhealthy. An embedder that drives QueryAllCapabilities, ResolveConflicts and MergeCapabilities itself reserves only the backends that answered, because ResolveConflicts sees nothing else.
When several backends map to the same name, none of them gets a sign-in tool or a SignInNames entry for it, but the name stays reserved. A name that is not 1-128 characters of letters, digits, underscore, dot and hyphen is skipped: its backend gets no sign-in tool and nothing is reserved.
type PrefixConflictResolver ¶ added in v0.5.2
type PrefixConflictResolver struct {
// PrefixFormat defines how to format the prefix.
// Supported placeholders:
// {workload} - just the workload name
// {workload}_ - workload with underscore
// {workload}. - workload with dot
// Can also be a custom static prefix like "backend_"
PrefixFormat string
}
PrefixConflictResolver implements automatic tool name prefixing to resolve conflicts. All tools are prefixed with their workload identifier according to a configurable format.
func NewPrefixConflictResolver ¶ added in v0.5.2
func NewPrefixConflictResolver(prefixFormat string) *PrefixConflictResolver
NewPrefixConflictResolver creates a new prefix-based conflict resolver.
func (*PrefixConflictResolver) ResolveToolConflicts ¶ added in v0.5.2
func (r *PrefixConflictResolver) ResolveToolConflicts( _ context.Context, toolsByBackend map[string][]vmcp.Tool, ) (map[string]*ResolvedTool, error)
ResolveToolConflicts applies prefix strategy to all tools. Returns a map of resolved tool names to ResolvedTool structs.
type PriorityConflictResolver ¶ added in v0.5.2
type PriorityConflictResolver struct {
// PriorityOrder defines the priority of backends (first has highest priority).
PriorityOrder []string
// contains filtered or unexported fields
}
PriorityConflictResolver implements priority-based conflict resolution. When every conflicting backend is listed in the priority order, the first backend in that order wins and lower-priority tools are dropped.
When any conflicting backend is absent from the priority list, all candidates in that conflict are dropped because the conflict cannot be safely ranked. Dropping preserves the fail-closed policy invariant: a renamed loser would be advertised under a name that existing name-scoped forbid policies do not cover.
func NewPriorityConflictResolver ¶ added in v0.5.2
func NewPriorityConflictResolver(priorityOrder []string) (*PriorityConflictResolver, error)
NewPriorityConflictResolver creates a new priority-based conflict resolver.
func (*PriorityConflictResolver) ResolveToolConflicts ¶ added in v0.5.2
func (r *PriorityConflictResolver) ResolveToolConflicts( _ context.Context, toolsByBackend map[string][]vmcp.Tool, ) (map[string]*ResolvedTool, error)
ResolveToolConflicts applies priority strategy to resolve conflicts. Returns a map of resolved tool names to ResolvedTool structs.
type ResolvedCapabilities ¶
type ResolvedCapabilities struct {
// Tools are the conflict-resolved tools.
// Map key is the resolved tool name, value contains original name and backend.
Tools map[string]*ResolvedTool
// Resources are de-duplicated by URI: a URI advertised by multiple backends
// appears once, from the backend earliest in sorted-backend-ID order. URIs
// are locators the client passes back verbatim, so they are never rewritten.
// See resolveResourceConflicts.
Resources []vmcp.Resource
// ResourceTemplates are de-duplicated by URI template string, with the same
// locator-identity policy as Resources. See resolveResourceTemplateConflicts.
ResourceTemplates []vmcp.ResourceTemplate
// Prompts are conflict-resolved by name: by default every prompt is
// renamed to its backend-prefixed form; under the priority strategy,
// backends listed in priorityOrder keep their bare names. Either way the
// advertised name is a pure function of the aggregation config and
// (backendID, name) — it never shifts with group membership. See
// resolvePromptConflicts.
Prompts []ResolvedPrompt
// SupportsLogging is true if any backend supports logging.
SupportsLogging bool
// SupportsSampling is true if any backend supports sampling.
SupportsSampling bool
// SignInNames maps each reserved backend ID to its sign-in tool name.
// A nil map means sign-in tools are off (WithSignInTools not set); the core
// relies on that. It is carried onto AggregatedCapabilities by
// MergeCapabilities.
SignInNames map[string]string
// Pending maps a backend ID to the authorization it needs, for each queried
// backend that answered with no capabilities because the caller has not
// connected the upstream provider. It is for consumers that need to know
// which backends are waiting for the user to connect a provider. It is
// filled before admission, so a consumer must filter it by admission before
// exposing it to a caller. It is nil when no backend is pending and is
// carried onto AggregatedCapabilities by MergeCapabilities.
Pending map[string]*authtypes.DelegatedAuthRequiredError
}
ResolvedCapabilities contains capabilities after conflict resolution. Every capability identity (tool name, resource URI, resource template string, prompt name) is unique within its list.
type ResolvedPrompt ¶ added in v0.41.0
type ResolvedPrompt struct {
vmcp.Prompt
// OriginalName is the prompt's name in the backend (equal to Name only
// for priority-listed backends; otherwise Name is the backend-prefixed
// form).
OriginalName string
}
ResolvedPrompt represents a prompt after conflict resolution. The embedded Prompt is the advertised form: Name holds the resolved (client-visible) name. OriginalName is the name the backend itself uses; prompts/get and completion requests are translated back to it via BackendTarget.GetBackendCapabilityName, exactly like renamed tools.
type ResolvedTool ¶
type ResolvedTool struct {
// ResolvedName is the final name exposed to clients (after conflict resolution).
ResolvedName string
// OriginalName is the tool's name in the backend.
OriginalName string
// Title is an optional human-readable display name for the tool.
Title string
// Description is the tool description (may be overridden).
Description string
// InputSchema is the JSON Schema for parameters.
InputSchema map[string]any
// OutputSchema is the JSON Schema for tool output (optional).
OutputSchema map[string]any
// Annotations describes behavioral hints for the tool (optional).
Annotations *vmcp.ToolAnnotations
// BackendID identifies the backend providing this tool.
BackendID string
// ConflictResolutionApplied indicates which strategy was used.
ConflictResolutionApplied vmcp.ConflictResolutionStrategy
// SignIn is carried to vmcp.Tool.SignIn. Set only by vMCP itself, never
// from backend data.
SignIn *vmcp.SignInMarker
}
ResolvedTool represents a tool after conflict resolution.
type ToolFilter ¶
type ToolFilter interface {
// FilterTools returns only the tools that should be included.
FilterTools(ctx context.Context, tools []vmcp.Tool) ([]vmcp.Tool, error)
}
ToolFilter filters tools from a backend based on configuration. This reuses ToolHive's existing mcp.WithToolsFilter() middleware.
type ToolOverride ¶
type ToolOverride interface {
// ApplyOverrides modifies tool names and descriptions.
ApplyOverrides(ctx context.Context, tools []vmcp.Tool) ([]vmcp.Tool, error)
}
ToolOverride applies renames and description updates to tools. This reuses ToolHive's existing mcp.WithToolsOverride() middleware.