mcp

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package mcp provides hash-based caching for MCP context server.

Package mcp implements the Model Context Protocol server for TokMan. Provides 24 MCP tools for intelligent context management.

Index

Constants

View Source
const (
	// DefaultMaxSize is the default maximum cache entries.
	DefaultMaxSize = 10000

	// DefaultMaxMemory is the default maximum memory in bytes (100MB).
	DefaultMaxMemory = 100 * 1024 * 1024
)
View Source
const (
	ErrorCodeParseError     = -32700
	ErrorCodeInvalidRequest = -32600
	ErrorCodeMethodNotFound = -32601
	ErrorCodeInvalidParams  = -32602
	ErrorCodeInternalError  = -32603
)

Error codes per MCP spec.

Variables

View Source
var (
	ErrToolNotFound   = fmt.Errorf("tool not found")
	ErrInvalidParams  = fmt.Errorf("invalid parameters")
	ErrFileNotFound   = fmt.Errorf("file not found")
	ErrCacheMiss      = fmt.Errorf("cache miss")
	ErrMemoryNotFound = fmt.Errorf("memory entry not found")
	ErrAlreadyExists  = fmt.Errorf("already exists")
	ErrInternal       = fmt.Errorf("internal error")
)

Error messages.

Functions

func ComputeHash

func ComputeHash(content string) string

ComputeHash computes SHA-256 hash of content.

func ComputeHashShort

func ComputeHashShort(content string) string

ComputeHashShort computes short SHA-256 hash (8 chars).

Types

type Bundle

type Bundle struct {
	ID        string                 `json:"id"`
	Files     []BundleFile           `json:"files"`
	Metadata  map[string]interface{} `json:"metadata"`
	CreatedAt time.Time              `json:"created_at"`
}

Bundle represents a collection of files.

type BundleFile

type BundleFile struct {
	Path     string `json:"path"`
	Hash     string `json:"hash"`
	Content  string `json:"content,omitempty"`
	Size     int    `json:"size"`
	Language string `json:"language"`
}

BundleFile represents a file in a bundle.

type BundleParams

type BundleParams struct {
	Paths    []string `json:"paths"`
	Compress bool     `json:"compress,omitempty"`
}

BundleParams for ctx_bundle tool.

type CacheEntry

type CacheEntry struct {
	Hash      string    `json:"hash"`
	Content   string    `json:"content"`
	FilePath  string    `json:"file_path"`
	Timestamp time.Time `json:"timestamp"`
	Accessed  time.Time `json:"accessed"`
	HitCount  int       `json:"hit_count"`
}

CacheEntry represents a cached file entry.

func (*CacheEntry) IsExpired

func (e *CacheEntry) IsExpired() bool

IsExpired checks if the cache entry is expired (older than 24 hours).

type ContentType

type ContentType string

ContentType represents the detected content type.

const (
	ContentTypeCode     ContentType = "code"
	ContentTypeLog      ContentType = "log"
	ContentTypeJSON     ContentType = "json"
	ContentTypeDiff     ContentType = "diff"
	ContentTypeHTML     ContentType = "html"
	ContentTypeText     ContentType = "text"
	ContentTypeMarkdown ContentType = "markdown"
	ContentTypeUnknown  ContentType = "unknown"
)

type ContextMode

type ContextMode string

ContextMode represents the read mode for ctx_read.

const (
	ModeFull    ContextMode = "full"
	ModeMap     ContextMode = "map"
	ModeOutline ContextMode = "outline"
	ModeSymbols ContextMode = "symbols"
	ModeImports ContextMode = "imports"
	ModeTypes   ContextMode = "types"
	ModeExports ContextMode = "exports"
)

type DeltaParams

type DeltaParams struct {
	Path     string `json:"path"`
	BaseHash string `json:"base_hash,omitempty"`
}

DeltaParams for ctx_delta tool.

type Error

type Error struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

Error represents an MCP error.

type ExecParams

type ExecParams struct {
	Command string   `json:"command"`
	Args    []string `json:"args,omitempty"`
	Timeout int      `json:"timeout,omitempty"`
}

ExecParams for ctx_exec tool.

type FusionContext

type FusionContext struct {
	Content     string                 `json:"content"`
	ContentType ContentType            `json:"content_type"`
	Language    Language               `json:"language"`
	FilePath    string                 `json:"file_path"`
	Hash        string                 `json:"hash"`
	Metadata    map[string]interface{} `json:"metadata"`
	Timestamp   time.Time              `json:"timestamp"`
}

FusionContext carries context through the MCP pipeline. Immutable - each operation returns a new context.

func NewFusionContext

func NewFusionContext(content, filePath string) *FusionContext

NewFusionContext creates a new fusion context.

type GrepParams

type GrepParams struct {
	Path    string `json:"path"`
	Pattern string `json:"pattern"`
	Context int    `json:"context,omitempty"`
}

GrepParams for ctx_grep tool.

type HashCache

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

HashCache provides SHA-256 based content caching with LRU eviction.

func NewHashCache

func NewHashCache(maxSize int, maxMemory int64) *HashCache

NewHashCache creates a new hash cache.

func (*HashCache) BatchGet

func (c *HashCache) BatchGet(hashes []string) map[string]*CacheEntry

BatchGet retrieves multiple entries efficiently.

func (*HashCache) BatchSet

func (c *HashCache) BatchSet(entries []*CacheEntry) error

BatchSet sets multiple entries efficiently.

func (*HashCache) Clear

func (c *HashCache) Clear()

Clear removes all entries.

func (*HashCache) Delete

func (c *HashCache) Delete(hash string) bool

Delete removes an entry by hash.

func (*HashCache) Entries

func (c *HashCache) Entries() []*CacheEntry

Entries returns a snapshot of all cache entries. Use with caution on large caches.

func (*HashCache) Get

func (c *HashCache) Get(hash string) (*CacheEntry, bool)

Get retrieves an entry by hash.

func (*HashCache) GetByContent

func (c *HashCache) GetByContent(content string) (*CacheEntry, bool)

GetByContent retrieves an entry by computing hash of content.

func (*HashCache) GetOrCompute

func (c *HashCache) GetOrCompute(hash string, compute func() (*CacheEntry, error)) (*CacheEntry, error)

GetOrCompute retrieves entry or computes and stores it.

func (*HashCache) InvalidateByPattern

func (c *HashCache) InvalidateByPattern(pattern string) int

InvalidateByPattern removes entries matching a glob pattern.

func (*HashCache) Len

func (c *HashCache) Len() int

Len returns the number of entries.

func (*HashCache) MemoryUsage

func (c *HashCache) MemoryUsage() int64

MemoryUsage returns current memory usage in bytes.

func (*HashCache) Persist

func (c *HashCache) Persist() ([]*CacheEntry, error)

Persist saves cache metadata (not content) for analysis.

func (*HashCache) Resize

func (c *HashCache) Resize(maxSize int, maxMemory int64)

Resize changes the cache size limits.

func (*HashCache) Set

func (c *HashCache) Set(entry *CacheEntry) error

Set adds or updates a cache entry.

func (*HashCache) SetEvictCallback

func (c *HashCache) SetEvictCallback(fn func(entry *CacheEntry))

SetEvictCallback sets a callback for evictions.

func (*HashCache) SetHitCallback

func (c *HashCache) SetHitCallback(fn func(entry *CacheEntry))

SetHitCallback sets a callback for cache hits.

func (*HashCache) Stats

func (c *HashCache) Stats() Stats

Stats returns cache statistics.

func (*HashCache) Touch

func (c *HashCache) Touch(hash string) bool

Touch updates access time for an entry without returning it.

type InitializeResult

type InitializeResult struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ServerCapabilities `json:"capabilities"`
	ServerInfo      ServerInfo         `json:"serverInfo"`
}

InitializeResult represents the initialize response.

type InputSchema

type InputSchema struct {
	Type       string              `json:"type"`
	Properties map[string]Property `json:"properties"`
	Required   []string            `json:"required"`
}

InputSchema represents the JSON schema for tool input.

type Language

type Language string

Language represents the detected programming language.

const (
	LangGo         Language = "go"
	LangRust       Language = "rust"
	LangPython     Language = "python"
	LangJavaScript Language = "javascript"
	LangTypeScript Language = "typescript"
	LangJava       Language = "java"
	LangC          Language = "c"
	LangCpp        Language = "cpp"
	LangRuby       Language = "ruby"
	LangShell      Language = "shell"
	LangUnknown    Language = "unknown"
)

type MemoryEntry

type MemoryEntry struct {
	Key       string    `json:"key"`
	Value     string    `json:"value"`
	Tags      []string  `json:"tags"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

MemoryEntry represents a persistent memory entry.

type Property

type Property struct {
	Type        string   `json:"type"`
	Description string   `json:"description"`
	Enum        []string `json:"enum,omitempty"`
}

Property represents a JSON schema property.

type ReadParams

type ReadParams struct {
	Path string      `json:"path"`
	Mode ContextMode `json:"mode,omitempty"`
}

ReadParams for ctx_read tool.

type RememberParams

type RememberParams struct {
	Key   string   `json:"key"`
	Value string   `json:"value"`
	Tags  []string `json:"tags,omitempty"`
}

RememberParams for ctx_remember tool.

type Request

type Request struct {
	JSONRPC string                 `json:"jsonrpc"`
	ID      interface{}            `json:"id"`
	Method  string                 `json:"method"`
	Params  map[string]interface{} `json:"params"`
}

Request represents an MCP tool call request.

type Response

type Response struct {
	JSONRPC string      `json:"jsonrpc"`
	ID      interface{} `json:"id"`
	Result  interface{} `json:"result,omitempty"`
	Error   *Error      `json:"error,omitempty"`
}

Response represents an MCP tool call response.

type ServerCapabilities

type ServerCapabilities struct {
	Tools *ToolsCapability `json:"tools"`
}

ServerCapabilities represents MCP server capabilities.

type ServerInfo

type ServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

ServerInfo represents server information.

type Stats

type Stats struct {
	TotalEntries int64     `json:"total_entries"`
	TotalSize    int64     `json:"total_size_bytes"`
	HitRate      float64   `json:"hit_rate"`
	HitCount     int64     `json:"hit_count"`
	MissCount    int64     `json:"miss_count"`
	OldestEntry  time.Time `json:"oldest_entry"`
	NewestEntry  time.Time `json:"newest_entry"`
}

Stats represents cache statistics.

type Status

type Status struct {
	Version          string        `json:"version"`
	Uptime           time.Duration `json:"uptime"`
	CacheStats       Stats         `json:"cache_stats"`
	ActiveMode       ContextMode   `json:"active_mode"`
	SessionStart     time.Time     `json:"session_start"`
	TotalCommands    int64         `json:"total_commands"`
	TotalTokensSaved int64         `json:"total_tokens_saved"`
}

Status represents overall MCP server status.

type Tool

type Tool struct {
	Name        string      `json:"name"`
	Description string      `json:"description"`
	InputSchema InputSchema `json:"inputSchema"`
}

Tool represents an MCP tool.

type ToolHandler

type ToolHandler func(ctx context.Context, params map[string]interface{}) (interface{}, error)

ToolHandler is the function signature for tool implementations.

type ToolRegistry

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

ToolRegistry manages available tools.

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates a new tool registry.

func (*ToolRegistry) GetHandler

func (r *ToolRegistry) GetHandler(name string) (ToolHandler, bool)

GetHandler returns a handler by name.

func (*ToolRegistry) GetTool

func (r *ToolRegistry) GetTool(name string) (Tool, bool)

GetTool returns a tool by name.

func (*ToolRegistry) ListTools

func (r *ToolRegistry) ListTools() []Tool

ListTools returns all registered tools.

func (*ToolRegistry) Register

func (r *ToolRegistry) Register(tool Tool, handler ToolHandler)

Register registers a tool and its handler.

type ToolsCapability

type ToolsCapability struct {
	ListChanged bool `json:"listChanged"`
}

ToolsCapability represents tools support.

Directories

Path Synopsis
Package persistence provides SQLite-based persistence for MCP cache.
Package persistence provides SQLite-based persistence for MCP cache.
Package reversible provides compression implementations.
Package reversible provides compression implementations.
Package server provides HTTP and stdio transports for MCP.
Package server provides HTTP and stdio transports for MCP.
Package tools provides the 27 MCP tool implementations.
Package tools provides the 27 MCP tool implementations.

Jump to

Keyboard shortcuts

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