mcp

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2025 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultResultMultiplier controls over-fetching for post-filtering headroom.
	// We fetch 2x the requested limit to ensure enough results remain after post-filtering.
	DefaultResultMultiplier = 2
)

Variables

This section is empty.

Functions

func AddCortexSearchTool

func AddCortexSearchTool(s *server.MCPServer, searcher ContextSearcher)

AddCortexSearchTool registers the cortex_search tool with an MCP server. This function is composable - it can be combined with other tool registrations.

Types

type ChunkFileMetadata

type ChunkFileMetadata struct {
	Model      string `json:"model"`
	Dimensions int    `json:"dimensions"`
	ChunkType  string `json:"chunk_type"`
	Generated  string `json:"generated"` // time as string
	Version    string `json:"version"`
}

ChunkFileMetadata contains metadata about the chunk file.

type ChunkFileWrapper

type ChunkFileWrapper struct {
	Metadata ChunkFileMetadata `json:"_metadata"`
	Chunks   []*ContextChunk   `json:"chunks"`
}

ChunkFileWrapper represents the chunk file format with metadata.

type ContextChunk

type ContextChunk struct {
	ID        string                 `json:"id"`
	Title     string                 `json:"title"`
	Text      string                 `json:"text"`
	ChunkType string                 `json:"chunk_type,omitempty"`
	Embedding []float32              `json:"embedding,omitempty"` // Excluded via MarshalJSON
	Tags      []string               `json:"tags,omitempty"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt time.Time              `json:"created_at"`
	UpdatedAt time.Time              `json:"updated_at"`
}

ContextChunk represents a searchable chunk of code or documentation. The Embedding field is excluded from JSON serialization to reduce payload size.

func LoadChunks

func LoadChunks(chunksDir string) ([]*ContextChunk, error)

LoadChunks reads and parses all chunk files from the specified directory. It returns all valid chunks and logs warnings for any malformed files.

func (ContextChunk) MarshalJSON

func (c ContextChunk) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling that excludes the Embedding field. This reduces response payload size by ~60% for MCP tool responses.

type ContextSearcher

type ContextSearcher interface {
	// Query executes a semantic search for the given query string.
	// Returns ranked search results based on vector similarity and filters.
	Query(ctx context.Context, query string, options *SearchOptions) ([]*SearchResult, error)

	// Reload reloads the chunk database from the configured directory.
	// Used for hot reload when chunk files are updated.
	Reload(ctx context.Context) error

	// GetMetrics returns current reload operation metrics.
	// Used for monitoring reload health and statistics.
	GetMetrics() MetricsSnapshot

	// Close releases resources held by the searcher.
	Close() error
}

ContextSearcher defines the interface for searching code and documentation chunks. This interface allows different backend implementations (chromem-go, external vector DB, etc.)

func NewChromemSearcher

func NewChromemSearcher(ctx context.Context, config *MCPServerConfig, provider EmbeddingProvider) (ContextSearcher, error)

NewChromemSearcher creates a new ContextSearcher backed by chromem-go. It loads chunks from the configured directory and initializes the vector database.

type CortexSearchRequest

type CortexSearchRequest struct {
	Query        string   `json:"query" jsonschema:"required,description=Natural language search query"`
	Limit        int      `json:"limit,omitempty" jsonschema:"minimum=1,maximum=100,default=15,description=Maximum number of results"`
	Tags         []string `json:"tags,omitempty" jsonschema:"description=Filter by tags (AND logic)"`
	ChunkTypes   []string `json:"chunk_types,omitempty" jsonschema:"description=Filter by chunk type (documentation|symbols|definitions|data)"`
	IncludeStats bool     `json:"include_stats,omitempty" jsonschema:"default=false,description=Include reload metrics in response"`
}

CortexSearchRequest represents the JSON request schema for the cortex_search MCP tool.

type CortexSearchResponse

type CortexSearchResponse struct {
	Results []*SearchResult  `json:"results"`
	Total   int              `json:"total"`
	Metrics *MetricsSnapshot `json:"metrics,omitempty"`
}

CortexSearchResponse represents the JSON response schema for the cortex_search MCP tool.

type EmbeddingProvider

type EmbeddingProvider interface {
	// Embed converts a slice of text strings into their vector representations.
	// The mode parameter specifies whether embeddings are for queries or passages.
	Embed(ctx context.Context, texts []string, mode string) ([][]float32, error)

	// Dimensions returns the dimensionality of the embedding vectors.
	Dimensions() int

	// Close releases any resources held by the provider.
	Close() error
}

EmbeddingProvider defines the interface for generating text embeddings. This is a minimal interface to avoid import cycles with internal/embed.

type EmbeddingServiceConfig

type EmbeddingServiceConfig struct {
	BaseURL string
}

EmbeddingServiceConfig contains embedding provider configuration.

type FileWatcher

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

FileWatcher watches a directory for changes and triggers reload.

func NewFileWatcher

func NewFileWatcher(searcher ContextSearcher, chunksDir string) (*FileWatcher, error)

NewFileWatcher creates a new file watcher for the specified directory.

func (*FileWatcher) Start

func (fw *FileWatcher) Start(ctx context.Context)

Start begins watching for file changes.

func (*FileWatcher) Stop

func (fw *FileWatcher) Stop()

Stop stops the file watcher.

type MCPServer

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

MCPServer manages the MCP server lifecycle.

func NewMCPServer

func NewMCPServer(ctx context.Context, config *MCPServerConfig, provider EmbeddingProvider) (*MCPServer, error)

NewMCPServer creates a new MCP server with the given configuration and embedding provider. The provider is passed in to avoid import cycles.

func (*MCPServer) Close

func (s *MCPServer) Close() error

Close releases all resources.

func (*MCPServer) Serve

func (s *MCPServer) Serve(ctx context.Context) error

Serve starts the MCP server and blocks until shutdown.

type MCPServerConfig

type MCPServerConfig struct {
	ChunksDir        string
	EmbeddingService *EmbeddingServiceConfig
}

MCPServerConfig contains configuration for the MCP server.

func DefaultMCPServerConfig

func DefaultMCPServerConfig() *MCPServerConfig

DefaultMCPServerConfig returns default MCP server configuration.

type MetricsSnapshot

type MetricsSnapshot struct {
	LastReloadTime     time.Time     `json:"last_reload_time"`
	LastReloadDuration time.Duration `json:"last_reload_duration_ms"`
	LastReloadError    string        `json:"last_reload_error,omitempty"`
	TotalReloads       int64         `json:"total_reloads"`
	SuccessfulReloads  int64         `json:"successful_reloads"`
	FailedReloads      int64         `json:"failed_reloads"`
	CurrentChunkCount  int           `json:"current_chunk_count"`
}

MetricsSnapshot is an immutable snapshot of reload metrics at a point in time. It can be safely shared across goroutines without synchronization.

type ReloadMetrics

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

ReloadMetrics tracks reload operation statistics for the MCP server. All methods are thread-safe and can be called concurrently.

func NewReloadMetrics

func NewReloadMetrics() *ReloadMetrics

NewReloadMetrics creates a new ReloadMetrics instance with zero values.

func (*ReloadMetrics) GetMetrics

func (m *ReloadMetrics) GetMetrics() MetricsSnapshot

GetMetrics returns an immutable snapshot of current metrics. The snapshot is independent of the underlying metrics and won't change even if new reloads are recorded.

func (*ReloadMetrics) RecordReload

func (m *ReloadMetrics) RecordReload(duration time.Duration, err error, chunkCount int)

RecordReload records the outcome of a reload operation. It updates all relevant metrics atomically under a write lock.

Parameters:

  • duration: how long the reload operation took
  • err: error if reload failed, nil if successful
  • chunkCount: number of chunks loaded (0 if reload failed)

type SearchOptions

type SearchOptions struct {
	// Limit specifies the maximum number of results to return (1-100)
	Limit int `json:"limit,omitempty"`

	// MinScore filters results below this similarity threshold (0.0-1.0)
	MinScore float64 `json:"min_score,omitempty"`

	// Tags filters results to only include chunks with ALL specified tags (AND logic)
	Tags []string `json:"tags,omitempty"`

	// ChunkTypes filters results by chunk type (documentation, symbols, definitions, data)
	ChunkTypes []string `json:"chunk_types,omitempty"`
}

SearchOptions contains parameters for context search queries.

func DefaultSearchOptions

func DefaultSearchOptions() *SearchOptions

DefaultSearchOptions returns default search options (limit: 15, no filters).

type SearchResult

type SearchResult struct {
	Chunk         *ContextChunk `json:"chunk"`
	CombinedScore float64       `json:"combined_score"`
}

SearchResult represents a single search result with similarity score.

Jump to

Keyboard shortcuts

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