registry

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package registry provides client-side components for agents to consume the internal tool registry.

This package is embedded into agent runtimes and provides:

  • RegistryClient interface — abstraction for registry communication
  • GRPCClientAdapter — wraps generated gRPC client to implement RegistryClient
  • Manager — coordinates multiple registry connections and tool discovery

For the server-side registry implementation that runs as a standalone service, see the registry package (github.com/CaliLuke/loom-mcp/registry).

Package registry provides runtime components for managing MCP registry connections, tool discovery, and catalog synchronization.

Package registry provides runtime components for managing MCP registry connections, tool discovery, and catalog synchronization.

Package registry provides runtime components for managing MCP registry connections, tool discovery, and catalog synchronization.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ComputeKeywordRelevance

func ComputeKeywordRelevance(query string, result *SearchResult) float64

ComputeKeywordRelevance computes a simple relevance score for keyword search results. This is used when the registry doesn't provide relevance scores.

func ExtractTraceContext

func ExtractTraceContext(ctx context.Context, header http.Header) context.Context

ExtractTraceContext extracts trace context from HTTP headers.

func InjectTraceContext

func InjectTraceContext(ctx context.Context, header http.Header)

InjectTraceContext injects trace context into HTTP headers for propagation.

Types

type Cache

type Cache interface {
	// Get retrieves a cached toolset schema by key.
	// Returns nil, nil if the key is not found or expired.
	Get(ctx context.Context, key string) (*ToolsetSchema, error)
	// Set stores a toolset schema with the given TTL.
	Set(ctx context.Context, key string, schema *ToolsetSchema, ttl time.Duration) error
	// Delete removes a cached entry.
	Delete(ctx context.Context, key string) error
}

Cache defines the interface for caching toolset schemas.

type FederationConfig

type FederationConfig struct {
	// Include patterns for namespaces to import.
	Include []string
	// Exclude patterns for namespaces to skip.
	Exclude []string
}

FederationConfig holds federation settings for a registry.

type GRPCClientAdapter

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

GRPCClientAdapter wraps a generated gRPC registry client and implements the RegistryClient interface for use with the runtime Manager.

func NewGRPCClientAdapter

func NewGRPCClientAdapter(client registrypb.RegistryClient) *GRPCClientAdapter

NewGRPCClientAdapter creates a new adapter that wraps the generated gRPC client and implements the RegistryClient interface.

func (*GRPCClientAdapter) GetToolset

func (a *GRPCClientAdapter) GetToolset(ctx context.Context, name string) (*ToolsetSchema, error)

GetToolset retrieves the full schema for a specific toolset.

func (*GRPCClientAdapter) ListToolsets

func (a *GRPCClientAdapter) ListToolsets(ctx context.Context) ([]*ToolsetInfo, error)

ListToolsets returns all available toolsets from the registry.

func (*GRPCClientAdapter) Search

func (a *GRPCClientAdapter) Search(ctx context.Context, query string) ([]*SearchResult, error)

Search performs a keyword search on the registry.

type Manager

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

Manager coordinates multiple registry clients, providing unified discovery, search, and caching across all configured registries.

func NewManager

func NewManager(opts ...Option) *Manager

NewManager creates a new registry manager with the given options.

func (*Manager) AddRegistry

func (m *Manager) AddRegistry(name string, client RegistryClient, cfg RegistryConfig)

AddRegistry registers a registry client with the manager.

func (*Manager) DiscoverToolset

func (m *Manager) DiscoverToolset(ctx context.Context, registry, toolset string) (*ToolsetSchema, error)

DiscoverToolset retrieves a toolset schema from the specified registry. It first checks the cache, then falls back to the registry client.

func (*Manager) Search

func (m *Manager) Search(ctx context.Context, query string) ([]*SearchResult, error)

Search performs a search across all registries and merges results. Results are tagged with their origin registry.

func (*Manager) StartSync

func (m *Manager) StartSync(ctx context.Context) error

StartSync starts the background sync loop for all registries. Each registry is synced at its configured SyncInterval.

func (*Manager) StopSync

func (m *Manager) StopSync()

StopSync stops the background sync loop.

type MemoryCache

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

MemoryCache is an in-memory cache implementation with TTL support and optional background refresh.

func NewMemoryCache

func NewMemoryCache(opts ...MemoryCacheOption) *MemoryCache

NewMemoryCache creates a new in-memory cache.

func (*MemoryCache) Clear

func (c *MemoryCache) Clear()

Clear removes all cached entries.

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(_ context.Context, key string) error

Delete removes a cached entry.

func (*MemoryCache) Get

func (c *MemoryCache) Get(_ context.Context, key string) (*ToolsetSchema, error)

Get retrieves a cached toolset schema by key. If the entry is approaching expiration (within 20% of TTL), a background refresh is triggered if a refresh function is configured.

func (*MemoryCache) Len

func (c *MemoryCache) Len() int

Len returns the number of entries in the cache.

func (*MemoryCache) Set

func (c *MemoryCache) Set(_ context.Context, key string, schema *ToolsetSchema, ttl time.Duration) error

Set stores a toolset schema with the given TTL.

func (*MemoryCache) StartRefresh

func (c *MemoryCache) StartRefresh(ctx context.Context)

StartRefresh starts the background refresh loop. The loop processes refresh requests and updates cache entries before they expire.

func (*MemoryCache) StopRefresh

func (c *MemoryCache) StopRefresh()

StopRefresh stops the background refresh loop.

type MemoryCacheOption

type MemoryCacheOption func(*MemoryCache)

MemoryCacheOption configures a MemoryCache.

func WithRefreshCooldown

func WithRefreshCooldown(d time.Duration) MemoryCacheOption

WithRefreshCooldown sets the minimum interval between refresh attempts for the same key. Defaults to 10 seconds if not set.

func WithRefreshFunc

func WithRefreshFunc(fn RefreshFunc) MemoryCacheOption

WithRefreshFunc sets the function used to refresh expired entries. When set, the cache will attempt to refresh entries in the background before they expire.

type Observability

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

Observability provides structured logging, metrics, and tracing for registry operations.

func NewObservability

func NewObservability(logger telemetry.Logger, metrics telemetry.Metrics, tracer telemetry.Tracer) *Observability

NewObservability creates a new Observability instance with the given telemetry components.

func (*Observability) EndSpan

func (o *Observability) EndSpan(span telemetry.Span, outcome OperationOutcome, err error)

EndSpan ends a trace span with the operation outcome.

func (*Observability) LogOperation

func (o *Observability) LogOperation(ctx context.Context, event OperationEvent)

LogOperation emits a structured log event for a registry operation.

func (*Observability) RecordCacheMetrics

func (o *Observability) RecordCacheMetrics(registry string, hits, misses int64)

RecordCacheMetrics records cache-specific metrics. This should be called periodically to track cache statistics.

func (*Observability) RecordOperationMetrics

func (o *Observability) RecordOperationMetrics(event OperationEvent)

RecordOperationMetrics records metrics for a registry operation. Metrics recorded:

  • registry.operation.duration: Histogram of operation latency
  • registry.operation.success: Counter of successful operations
  • registry.operation.error: Counter of failed operations
  • registry.cache.hit: Counter of cache hits
  • registry.cache.miss: Counter of cache misses
  • registry.operation.fallback: Counter of fallback to cached data
  • registry.operation.result_count: Gauge of results returned
  • registry.cache.hit_ratio: Gauge of cache hit ratio (computed)

func (*Observability) StartSpan

func (o *Observability) StartSpan(ctx context.Context, operation OperationType, attrs ...attribute.KeyValue) (context.Context, telemetry.Span)

StartSpan starts a new trace span for a registry operation.

type OperationEvent

type OperationEvent struct {
	// Operation is the type of operation performed.
	Operation OperationType
	// Registry is the name of the registry involved.
	Registry string
	// Toolset is the name of the toolset involved (if applicable).
	Toolset string
	// Query is the search query (if applicable).
	Query string
	// Duration is how long the operation took.
	Duration time.Duration
	// Outcome is the result of the operation.
	Outcome OperationOutcome
	// Error is the error message if the operation failed.
	Error string
	// ResultCount is the number of results returned (if applicable).
	ResultCount int
	// CacheKey is the cache key used (if applicable).
	CacheKey string
}

OperationEvent represents a structured log event for registry operations.

type OperationOutcome

type OperationOutcome string

OperationOutcome represents the result of an operation.

const (
	// OutcomeSuccess indicates the operation completed successfully.
	OutcomeSuccess OperationOutcome = "success"
	// OutcomeError indicates the operation failed with an error.
	OutcomeError OperationOutcome = "error"
	// OutcomeCacheHit indicates a cache hit occurred.
	OutcomeCacheHit OperationOutcome = "cache_hit"
	// OutcomeCacheMiss indicates a cache miss occurred.
	OutcomeCacheMiss OperationOutcome = "cache_miss"
	// OutcomeFallback indicates fallback to cached data was used.
	OutcomeFallback OperationOutcome = "fallback"
)

type OperationType

type OperationType string

OperationType identifies the type of registry operation for observability.

const (
	// OpDiscoverToolset is the operation type for toolset discovery.
	OpDiscoverToolset OperationType = "discover_toolset"
	// OpSearch is the operation type for registry search.
	OpSearch OperationType = "search"
	// OpListToolsets is the operation type for listing toolsets.
	OpListToolsets OperationType = "list_toolsets"
	// OpGetToolset is the operation type for getting a single toolset.
	OpGetToolset OperationType = "get_toolset"
	// OpSync is the operation type for registry synchronization.
	OpSync OperationType = "sync"
	// OpRegister is the operation type for adding a registry to the manager.
	OpRegister OperationType = "register"
	// OpCacheGet is the operation type for cache get operations.
	OpCacheGet OperationType = "cache_get"
	// OpCacheSet is the operation type for cache set operations.
	OpCacheSet OperationType = "cache_set"
)

type Option

type Option func(*Manager)

Option configures a Manager.

func WithCache

func WithCache(c Cache) Option

WithCache sets the cache implementation for the manager.

func WithLogger

func WithLogger(l telemetry.Logger) Option

WithLogger sets the logger for the manager.

func WithMetrics

func WithMetrics(met telemetry.Metrics) Option

WithMetrics sets the metrics recorder for the manager.

func WithTracer

func WithTracer(t telemetry.Tracer) Option

WithTracer sets the tracer for the manager.

type RefreshFunc

type RefreshFunc func(ctx context.Context, key string) (*ToolsetSchema, error)

RefreshFunc is called when a cache entry needs to be refreshed. It receives the key and should return the refreshed schema.

type RegistryClient

type RegistryClient interface {
	// ListToolsets returns all available toolsets from the registry.
	ListToolsets(ctx context.Context) ([]*ToolsetInfo, error)
	// GetToolset retrieves the full schema for a specific toolset.
	GetToolset(ctx context.Context, name string) (*ToolsetSchema, error)
	// Search performs a semantic or keyword search on the registry.
	Search(ctx context.Context, query string) ([]*SearchResult, error)
}

RegistryClient defines the interface for registry operations. Generated registry clients implement this interface.

type RegistryConfig

type RegistryConfig struct {
	// SyncInterval specifies how often to refresh the registry catalog.
	SyncInterval time.Duration
	// CacheTTL specifies local cache duration for registry data.
	CacheTTL time.Duration
	// Federation configures external registry import settings.
	Federation *FederationConfig
}

RegistryConfig holds configuration for adding a registry to the manager.

type SearchCapabilities

type SearchCapabilities struct {
	// SemanticSearch indicates if the registry supports semantic/vector search.
	SemanticSearch bool
	// KeywordSearch indicates if the registry supports keyword-based search.
	KeywordSearch bool
	// TagFiltering indicates if the registry supports filtering by tags.
	TagFiltering bool
	// TypeFiltering indicates if the registry supports filtering by type.
	TypeFiltering bool
}

SearchCapabilities describes what search features a registry supports.

type SearchClient

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

SearchClient provides search functionality across registries with semantic search and keyword fallback support.

func NewSearchClient

func NewSearchClient(manager *Manager) *SearchClient

NewSearchClient creates a new search client using the given manager.

func (*SearchClient) Search

func (s *SearchClient) Search(ctx context.Context, query string, opts SearchOptions) ([]*SearchResult, error)

Search performs a search across registries with automatic fallback. If semantic search is preferred and available, it is used first. If semantic search fails or is not supported, keyword search is used as fallback.

type SearchOptions

type SearchOptions struct {
	// Registries limits search to specific registries. If empty, all registries are searched.
	Registries []string
	// Types filters results by type (e.g., "tool", "toolset", "agent").
	Types []string
	// Tags filters results by tags.
	Tags []string
	// MinRelevance filters results below this relevance score (0.0-1.0).
	MinRelevance float64
	// MaxResults limits the number of results returned.
	MaxResults int
	// PreferSemantic indicates whether to prefer semantic search over keyword.
	// When true, keyword search is only used as fallback.
	PreferSemantic bool
}

SearchOptions configures search behavior.

type SearchResult

type SearchResult struct {
	// ID is the unique identifier.
	ID string
	// Name is the human-readable name.
	Name string
	// Description provides details.
	Description string
	// Type indicates the result type (e.g., "tool", "toolset", "agent").
	Type string
	// SchemaRef is a reference to the full schema.
	SchemaRef string
	// RelevanceScore indicates how relevant this result is to the query.
	RelevanceScore float64
	// Tags are metadata tags.
	Tags []string
	// Origin indicates the federation source if applicable.
	Origin string
}

SearchResult contains a single search result from the registry.

func EnhanceResultsWithRelevance

func EnhanceResultsWithRelevance(query string, results []*SearchResult) []*SearchResult

EnhanceResultsWithRelevance adds relevance scores to results that don't have them.

func ParseSearchResults

func ParseSearchResults(results []*SearchResult) []*SearchResult

ParseSearchResults parses search results from a registry response. This helper ensures all required fields are present and properly formatted. Results without an ID are skipped rather than causing an error.

type SemanticSearchClient

type SemanticSearchClient interface {
	RegistryClient
	// SemanticSearch performs a semantic/vector search on the registry.
	SemanticSearch(ctx context.Context, query string, opts SemanticSearchOptions) ([]*SearchResult, error)
	// Capabilities returns the search capabilities of this registry.
	Capabilities() SearchCapabilities
}

SemanticSearchClient extends RegistryClient with semantic search capabilities.

type SemanticSearchOptions

type SemanticSearchOptions struct {
	// Types filters results by type.
	Types []string
	// Tags filters results by tags.
	Tags []string
	// MaxResults limits the number of results.
	MaxResults int
}

SemanticSearchOptions configures semantic search behavior.

type ToolSchema

type ToolSchema struct {
	// Name is the tool identifier.
	Name string
	// Description explains what the tool does.
	Description string
	// Tags are optional metadata tags for discovery and filtering.
	Tags []string
	// PayloadSchema is the JSON Schema for tool input.
	PayloadSchema []byte
	// ResultSchema is the JSON Schema for tool output.
	ResultSchema []byte
	// SidecarSchema is the JSON Schema for tool sidecar (UI-only), when present.
	SidecarSchema []byte
}

ToolSchema contains the schema for a single tool.

type ToolsetInfo

type ToolsetInfo struct {
	// ID is the unique identifier for the toolset.
	ID string
	// Name is the human-readable name.
	Name string
	// Description provides details about the toolset.
	Description string
	// Version is the toolset version.
	Version string
	// Tags are metadata tags for discovery.
	Tags []string
	// Origin indicates the source registry for federated items.
	Origin string
}

ToolsetInfo contains metadata about a toolset available in a registry.

type ToolsetSchema

type ToolsetSchema struct {
	// ID is the unique identifier for the toolset.
	ID string
	// Name is the human-readable name.
	Name string
	// Description provides details about the toolset.
	Description string
	// Version is the toolset version.
	Version string
	// Tools contains the tool definitions.
	Tools []*ToolSchema
	// Origin indicates the source registry for federated items.
	Origin string
}

ToolsetSchema contains the full schema for a toolset including its tools.

Jump to

Keyboard shortcuts

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