toolsearch

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package toolsearch is the ranked, cross-server tool index behind the search_tools gateway tool (issue #305). It scores every cached tool against a natural-language query with Okapi BM25 over the tool's server name, tool name, description, title, parameter names and parameter descriptions, optionally fused (Reciprocal Rank Fusion) with the cosine similarity of embeddings when an Embedder is configured.

The index is fed per server (SetServerTools) from the proxy's tool cache and answers queries lock-free from an immutable snapshot, so a refresh of one server never blocks a search.

Index

Constants

View Source
const (
	DefaultK1 = 1.2
	DefaultB  = 0.75
)

Okapi BM25 parameters (issue #305).

View Source
const DefaultK = 5

DefaultK is the number of hits returned when a query asks for none.

View Source
const MaxK = 20

MaxK is the largest number of hits a query can ask for.

View Source
const RRFK = 60

RRFK is the Reciprocal Rank Fusion constant: a document ranked r (1 based) in a list contributes 1/(RRFK+r) to its fused score.

Variables

This section is empty.

Functions

func DefaultSynonyms

func DefaultSynonyms() map[string]string

DefaultSynonyms is the small built-in synonym table.

func Stem

func Stem(w string) string

Stem is a deliberately light English stemmer: on words longer than four characters it strips the first matching suffix of "ing", "ies" (-> "y"), "es", "s" and "ed". It is applied identically to documents and queries, so a crude stem ("messag" for "messages") still matches.

func Tokenize

func Tokenize(text string) []string

Tokenize splits text into search terms: it breaks camelCase boundaries, lowercases, splits on anything that is not a letter or digit (so "_" and "-" separate words too), drops stopwords and applies Stem to each word.

Types

type Config

type Config struct {
	// Synonyms adds query expansions ("k8s": "kubernetes cluster") to the
	// defaults (DefaultSynonyms); an entry with the same key replaces the
	// default one. Each key must be a single word.
	Synonyms map[string]string `yaml:"synonyms,omitempty"`
	// DisableDefaultSynonyms drops the built-in synonym table.
	DisableDefaultSynonyms bool `yaml:"disable_default_synonyms,omitempty"`
	// Hybrid turns on BM25 + embedding ranking. Off by default.
	Hybrid *HybridConfig `yaml:"hybrid,omitempty"`
}

Config is the `tool_search:` block of the proxy config. A nil *Config means BM25 with the default synonyms and no hybrid mode.

func (*Config) HybridEnabled

func (c *Config) HybridEnabled() bool

HybridEnabled reports whether hybrid mode is configured on.

func (*Config) Options

func (c *Config) Options() Options

Options returns the index options for this config (the synonym table).

func (*Config) Validate

func (c *Config) Validate() error

Validate rejects synonym entries that cannot be used and an enabled hybrid block without a valid embedder. A nil receiver is valid.

type Embedder

type Embedder interface {
	Embed(ctx context.Context, text string) ([]float32, error)
}

Embedder turns text into a vector. pkg/cache/embedder's Ollama and OpenAI clients are adapted to it by the caller.

type Hit

type Hit struct {
	Tool  Tool
	Score float64
}

Hit is one search result.

type HybridConfig

type HybridConfig struct {
	Enabled bool `yaml:"enabled"`
	// Embedder selects the embedding provider (ollama or openai), with
	// the same keys as elsewhere in the config.
	Embedder embedder.Config `yaml:"embedder"`
}

HybridConfig is `tool_search.hybrid`.

type Index

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

Index is a BM25 (optionally hybrid) index over the tools of every server. All methods are safe for concurrent use.

func New

func New(opts Options) *Index

New returns an empty index.

func (*Index) EmbedPending

func (ix *Index) EmbedPending(ctx context.Context) (int, error)

EmbedPending embeds every indexed tool without a cached vector and drops the vectors of tools no longer indexed. It stops at the first error. It returns the number of tools embedded. Without hybrid mode it does nothing.

func (*Index) EnableHybrid

func (ix *Index) EnableHybrid(ctx context.Context, emb Embedder)

EnableHybrid turns on hybrid ranking: tool documents are embedded in the background (one goroutine, stopped when ctx ends), their vectors cached by tool-definition hash, and every search fuses the BM25 ranking with the cosine ranking by Reciprocal Rank Fusion. Tools not embedded yet only take part through BM25. Only the first call has an effect.

func (*Index) HybridEnabled

func (ix *Index) HybridEnabled() bool

HybridEnabled reports whether EnableHybrid was called.

func (*Index) Len

func (ix *Index) Len() int

Len returns the number of indexed tools.

func (*Index) RemoveServer

func (ix *Index) RemoveServer(server string)

RemoveServer drops every tool of server from the index.

func (*Index) Search

func (ix *Index) Search(ctx context.Context, q Query) []Hit

Search returns the best hits for q, best first. Ties are broken by server then tool name, so the order is deterministic. With hybrid mode enabled (EnableHybrid), the BM25 ranking is fused with the embedding ranking; if the query cannot be embedded, it falls back to BM25 only.

func (*Index) Servers

func (ix *Index) Servers() []string

Servers returns the names of the indexed servers, sorted.

func (*Index) SetServerTools

func (ix *Index) SetServerTools(server string, tools []Tool)

SetServerTools replaces the indexed tools of one server. Only that server's tools are re-tokenized; the corpus statistics are then rebuilt into a new snapshot that queries pick up atomically.

type Options

type Options struct {
	// Synonyms maps a query word to the words it expands to (e.g.
	// "pr" -> "pull request"). Nil means DefaultSynonyms; use an empty,
	// non-nil map for none.
	Synonyms map[string]string
	// Logger receives the hybrid mode's background errors. Nil means
	// slog.Default().
	Logger *slog.Logger
}

Options configure an Index. The zero value is BM25 with the default synonyms.

type Query

type Query struct {
	Text string
	// K is the number of hits wanted: 0 means DefaultK, and it is capped
	// at MaxK.
	K int
	// Server, when set, restricts the results to that server's tools.
	Server string
	// Exclude, when set, drops the tools it reports before the top K are
	// taken (tool pinning hides tools awaiting approval, #310).
	Exclude func(server, name string) bool
}

Query is one search request.

type Tool

type Tool struct {
	Server      string
	Name        string
	Description string
	InputSchema json.RawMessage
	// Title and ReadOnlyHint come from the MCP tool title / annotations
	// when the upstream server provides them.
	Title        string
	ReadOnlyHint bool
}

Tool is one tool as the index sees it.

Jump to

Keyboard shortcuts

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