mcp

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2026 License: GPL-3.0 Imports: 30 Imported by: 0

Documentation

Overview

Package mcp provides a simplified MCP server that calls internal packages directly.

This implementation uses the MCP SDK (github.com/modelcontextprotocol/go-sdk/mcp) and registers tools for checkpoint, remediation, repository, troubleshoot, memory, context-folding, conversation, and reflection services. All output is scrubbed for secrets before returning to clients.

See CLAUDE.md for MCP tool descriptions and integration patterns.

Package mcp provides MCP server with metrics instrumentation.

Package mcp provides a simplified MCP server that calls internal packages directly.

This implementation uses the MCP SDK (github.com/modelcontextprotocol/go-sdk/mcp) and calls internal services directly without gRPC overhead.

Package mcp provides value demonstration metrics for contextd.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func StoreReflectionReport added in v0.3.0

func StoreReflectionReport(report *reflection.ReflectionReport, projectPath string) (string, error)

StoreReflectionReport stores a reflection report to disk for later retrieval.

Types

type Config

type Config struct {
	// Name is the server implementation name (default: "contextd-v2")
	Name string

	// Version is the server version (default: "1.0.0")
	Version string

	// Logger for structured logging
	Logger *zap.Logger

	// IgnoreFiles is the list of ignore file names to parse from project root.
	// Default: [".gitignore", ".dockerignore", ".contextdignore"]
	IgnoreFiles []string

	// FallbackExcludes are used when no ignore files are found.
	// Default: [".git/**", "node_modules/**", "vendor/**", "__pycache__/**"]
	FallbackExcludes []string
}

Config configures the MCP server.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns sensible defaults.

type Metrics added in v0.4.0

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

Metrics holds all MCP-related metrics.

func NewMetrics added in v0.4.0

func NewMetrics(logger *zap.Logger) *Metrics

NewMetrics creates a new Metrics instance.

func (*Metrics) DecrementActive added in v0.4.0

func (m *Metrics) DecrementActive(ctx context.Context, toolName string)

DecrementActive decrements the active requests counter.

func (*Metrics) IncrementActive added in v0.4.0

func (m *Metrics) IncrementActive(ctx context.Context, toolName string)

IncrementActive increments the active requests counter.

func (*Metrics) RecordInvocation added in v0.4.0

func (m *Metrics) RecordInvocation(ctx context.Context, toolName string, duration time.Duration, err error)

RecordInvocation records a tool invocation metric.

Labels:

  • tool: The MCP tool name (e.g., "memory_search", "checkpoint_save")

This function records:

  • Invocation count (contextd.mcp.tool.invocations_total)
  • Duration histogram (contextd.mcp.tool.duration_seconds)
  • Error count with reason categorization (contextd.mcp.tool.errors_total)

Usage:

start := time.Now()
result, err := handler.Execute(ctx, params)
metrics.RecordInvocation(ctx, "memory_search", time.Since(start), err)

type SearchResult added in v0.4.0

type SearchResult struct {
	// Tool is the matched tool metadata
	Tool *ToolMetadata

	// Score indicates match quality:
	// 3 = exact name match
	// 2 = name contains query
	// 1 = description or keyword match
	Score int

	// MatchReason explains why this tool matched
	MatchReason string
}

SearchResult represents a tool matched by a search query

type Server

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

Server is a simplified MCP server that calls internal packages directly.

func NewServer

func NewServer(
	cfg *Config,
	checkpointSvc checkpoint.Service,
	remediationSvc remediation.Service,
	repositorySvc *repository.Service,
	troubleshootSvc *troubleshoot.Service,
	reasoningbankSvc *reasoningbank.Service,
	foldingSvc *folding.BranchManager,
	distiller *reasoningbank.Distiller,
	scrubber secrets.Scrubber,
) (*Server, error)

NewServer creates a new MCP server with the given services.

func (*Server) Close

func (s *Server) Close() error

Close closes the server and all services.

func (*Server) Run

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

Run starts the MCP server on the stdio transport.

func (*Server) SetConversationService added in v0.3.0

func (s *Server) SetConversationService(svc conversation.ConversationService)

SetConversationService sets the optional conversation service. Must be called before Run() to enable conversation tools.

type ToolCategory added in v0.4.0

type ToolCategory string

ToolCategory represents the functional category of a tool

const (
	CategoryMemory       ToolCategory = "memory"
	CategoryCheckpoint   ToolCategory = "checkpoint"
	CategoryRemediation  ToolCategory = "remediation"
	CategoryRepository   ToolCategory = "repository"
	CategoryTroubleshoot ToolCategory = "troubleshoot"
	CategoryFolding      ToolCategory = "folding"
	CategoryConversation ToolCategory = "conversation"
	CategoryReflection   ToolCategory = "reflection"
	CategorySearch       ToolCategory = "search"
)

type ToolMetadata added in v0.4.0

type ToolMetadata struct {
	// Name is the unique tool identifier (e.g., "memory_search")
	Name string

	// Description is a human-readable description of what the tool does
	Description string

	// Category groups related tools together
	Category ToolCategory

	// DeferLoading indicates if this tool should be loaded on-demand via tool_search
	// false = always loaded in initial context
	// true = loaded only when discovered via tool_search
	DeferLoading bool

	// Keywords are additional search terms for discovery
	Keywords []string
}

ToolMetadata contains metadata about a registered MCP tool

type ToolRegistry added in v0.4.0

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

ToolRegistry stores and searches tool metadata

func NewToolRegistry added in v0.4.0

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates a new thread-safe tool registry

func (*ToolRegistry) Count added in v0.4.0

func (r *ToolRegistry) Count() int

Count returns the total number of registered tools

func (*ToolRegistry) Get added in v0.4.0

func (r *ToolRegistry) Get(name string) (*ToolMetadata, error)

Get retrieves a tool by name

func (*ToolRegistry) List added in v0.4.0

func (r *ToolRegistry) List() []*ToolMetadata

List returns all registered tools

func (*ToolRegistry) ListByCategory added in v0.4.0

func (r *ToolRegistry) ListByCategory(category ToolCategory) []*ToolMetadata

ListByCategory returns tools filtered by category

func (*ToolRegistry) ListDeferred added in v0.4.0

func (r *ToolRegistry) ListDeferred() []*ToolMetadata

ListDeferred returns tools with DeferLoading=true

func (*ToolRegistry) ListNames added in v0.4.0

func (r *ToolRegistry) ListNames() []string

ListNames returns all registered tool names

func (*ToolRegistry) ListNonDeferred added in v0.4.0

func (r *ToolRegistry) ListNonDeferred() []*ToolMetadata

ListNonDeferred returns tools with DeferLoading=false

func (*ToolRegistry) Register added in v0.4.0

func (r *ToolRegistry) Register(tool *ToolMetadata) error

Register adds a tool to the registry

func (*ToolRegistry) RegisterAll added in v0.4.0

func (r *ToolRegistry) RegisterAll(tools []*ToolMetadata) error

RegisterAll registers multiple tools in a batch. If any tool fails validation, no tools are registered and an error is returned. This method is thread-safe and holds a write lock for the entire operation to prevent race conditions between validation and registration.

func (*ToolRegistry) Search added in v0.4.0

func (r *ToolRegistry) Search(query string) ([]SearchResult, error)

Search finds tools matching the query using regex-compatible patterns. Supports Python re.search() compatible patterns. Returns an error if the query is detected as regex but fails to compile.

func (*ToolRegistry) SearchByCategory added in v0.4.0

func (r *ToolRegistry) SearchByCategory(query string, category ToolCategory) ([]SearchResult, error)

SearchByCategory finds tools matching the query within a specific category

type ValueMetrics added in v0.4.0

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

ValueMetrics tracks business value metrics for contextd. These metrics demonstrate the actual value delivered to users.

func GetValueMetrics added in v0.4.0

func GetValueMetrics(logger *zap.Logger) *ValueMetrics

GetValueMetrics returns the global ValueMetrics instance.

func (*ValueMetrics) RecordCheckpointCreated added in v0.4.0

func (m *ValueMetrics) RecordCheckpointCreated(ctx context.Context, projectID string, autoCreated bool)

RecordCheckpointCreated records a checkpoint creation. Project IDs are hashed before being used as metric labels to prevent enumeration.

func (*ValueMetrics) RecordCheckpointResumed added in v0.4.0

func (m *ValueMetrics) RecordCheckpointResumed(ctx context.Context, projectID string, level string)

RecordCheckpointResumed records a checkpoint resumption. Project IDs are hashed before being used as metric labels to prevent enumeration.

func (*ValueMetrics) RecordMemoryOutcome added in v0.4.0

func (m *ValueMetrics) RecordMemoryOutcome(ctx context.Context, success bool, projectID string)

RecordMemoryOutcome records whether a memory retrieval was successful. Project IDs are hashed before being used as metric labels to prevent enumeration.

func (*ValueMetrics) RecordTokensSaved added in v0.4.0

func (m *ValueMetrics) RecordTokensSaved(ctx context.Context, inputTokens, outputTokens int)

RecordTokensSaved records tokens saved via context compression.

Parameters:

  • inputTokens: Original token count before compression
  • outputTokens: Token count after compression

Behavior:

  • Only records when inputTokens > outputTokens (positive savings)
  • Negative savings (expansion) are silently ignored to avoid skewing metrics
  • Zero or negative inputs are safely handled (no recording)

Usage:

original := countTokens(fullContext)
compressed := countTokens(foldedContext)
valueMetrics.RecordTokensSaved(ctx, original, compressed)

Directories

Path Synopsis
internal/mcp/handlers/memory.go
internal/mcp/handlers/memory.go

Jump to

Keyboard shortcuts

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