Repository navigation
Conversation
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
There was a problem hiding this comment.
Code Review
This pull request implements lexical ranking for the find_remote_tools MCP tool based on the intent parameter, matching words in tool names and descriptions while filtering out common English stop words. It includes comprehensive unit tests, benchmarks, and updated documentation. The review feedback suggests a valuable performance optimization in rankRowsByIntent to avoid map allocations inside the loop by tokenizing the query once and using a bitmask for matching, which significantly reduces GC pressure and CPU overhead for large catalogues.
| func rankRowsByIntent(rows []remoteToolRow, intent string) []remoteToolRow { | ||
| query := toolSearchTerms(intent) | ||
| if len(query) == 0 { | ||
| return rows | ||
| } | ||
| type rankedRow struct { | ||
| row remoteToolRow | ||
| coverage, nameMatches int | ||
| } | ||
| ranked := make([]rankedRow, len(rows)) | ||
| for i, row := range rows { | ||
| ranked[i].row = row | ||
| if row.Error != "" { | ||
| // Preserve diagnostics, after all actual tools. | ||
| ranked[i].coverage = -1 | ||
| continue | ||
| } | ||
| names := toolSearchTerms(strings.TrimPrefix(row.ToolName, api.MCPServicePrefix)) | ||
| description := toolSearchTerms(row.Description) | ||
| for term := range query { | ||
| _, inName := names[term] | ||
| _, inDescription := description[term] | ||
| if inName || inDescription { | ||
| ranked[i].coverage++ | ||
| } | ||
| if inName { | ||
| ranked[i].nameMatches++ | ||
| } | ||
| } | ||
| } | ||
| slices.SortFunc(ranked, func(a, b rankedRow) int { | ||
| if c := cmp.Compare(b.coverage, a.coverage); c != 0 { | ||
| return c | ||
| } | ||
| if c := cmp.Compare(b.nameMatches, a.nameMatches); c != 0 { | ||
| return c | ||
| } | ||
| if c := strings.Compare(a.row.ToolName, b.row.ToolName); c != 0 { | ||
| return c | ||
| } | ||
| return strings.Compare(a.row.PeerID, b.row.PeerID) | ||
| }) | ||
| for i, entry := range ranked { | ||
| rows[i] = entry.row | ||
| } | ||
| return rows | ||
| } | ||
|
|
||
| // toolSearchTerms splits case-insensitive Unicode words at punctuation (including | ||
| // snake_case and hyphenated names), ignoring common English function words. | ||
| func toolSearchTerms(text string) map[string]struct{} { | ||
| words := strings.FieldsFunc(strings.ToLower(text), func(r rune) bool { | ||
| return !unicode.IsLetter(r) && !unicode.IsNumber(r) | ||
| }) | ||
| terms := make(map[string]struct{}, len(words)) | ||
| for _, word := range words { | ||
| switch word { | ||
| case "a", "an", "and", "as", "at", "be", "by", "for", "from", "in", "is", "it", "of", "on", "or", "that", "the", "this", "to", "with": | ||
| continue | ||
| } | ||
| terms[word] = struct{}{} | ||
| } | ||
| return terms | ||
| } |
There was a problem hiding this comment.
Performance Optimization: Avoid Map Allocations in Search Loop
In the current implementation of rankRowsByIntent, toolSearchTerms is called twice for every row in the catalogue (once for the tool name and once for the description). Each call to toolSearchTerms allocates a new map and a slice of strings. For a large catalogue (e.g., 1,000 or 10,000 rows), this results in tens of thousands of heap allocations, leading to high GC pressure and CPU overhead.
We can optimize this by:
- Tokenizing the query/intent once and mapping each query term to a unique bit index (0 to 63).
- Iterating over the words in each row's name and description, and using a
uint64bitmask to track matched query terms.
This completely eliminates map allocations inside the loop, significantly improving performance and reducing memory usage.
func rankRowsByIntent(rows []remoteToolRow, intent string) []remoteToolRow {
queryTerms := toolSearchTermsList(intent)
if len(queryTerms) == 0 {
return rows
}
queryMap := make(map[string]int, len(queryTerms))
for i, term := range queryTerms {
queryMap[term] = i
}
type rankedRow struct {
row remoteToolRow
coverage, nameMatches int
}
ranked := make([]rankedRow, len(rows))
for i, row := range rows {
ranked[i].row = row
if row.Error != "" {
// Preserve diagnostics, after all actual tools.
ranked[i].coverage = -1
continue
}
var matchedBits uint64
var nameMatchedBits uint64
forEachWord(strings.TrimPrefix(row.ToolName, api.MCPServicePrefix), func(w string) {
if idx, ok := queryMap[w]; ok && idx < 64 {
mask := uint64(1) << idx
if (nameMatchedBits & mask) == 0 {
nameMatchedBits |= mask
ranked[i].nameMatches++
}
if (matchedBits & mask) == 0 {
matchedBits |= mask
ranked[i].coverage++
}
}
})
forEachWord(row.Description, func(w string) {
if idx, ok := queryMap[w]; ok && idx < 64 {
mask := uint64(1) << idx
if (matchedBits & mask) == 0 {
matchedBits |= mask
ranked[i].coverage++
}
}
})
}
slices.SortFunc(ranked, func(a, b rankedRow) int {
if c := cmp.Compare(b.coverage, a.coverage); c != 0 {
return c
}
if c := cmp.Compare(b.nameMatches, a.nameMatches); c != 0 {
return c
}
if c := strings.Compare(a.row.ToolName, b.row.ToolName); c != 0 {
return c
}
return strings.Compare(a.row.PeerID, b.row.PeerID)
})
for i, entry := range ranked {
rows[i] = entry.row
}
return rows
}
func toolSearchTermsList(text string) []string {
words := strings.FieldsFunc(strings.ToLower(text), func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsNumber(r)
})
var terms []string
seen := make(map[string]struct{}, len(words))
for _, word := range words {
if isStopWord(word) {
continue
}
if _, ok := seen[word]; !ok {
seen[word] = struct{}{}
terms = append(terms, word)
}
}
return terms
}
func forEachWord(text string, f func(string)) {
words := strings.FieldsFunc(strings.ToLower(text), func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsNumber(r)
})
for _, word := range words {
if !isStopWord(word) {
f(word)
}
}
}
func isStopWord(word string) bool {
switch word {
case "a", "an", "and", "as", "at", "be", "by", "for", "from", "in", "is", "it", "of", "on", "or", "that", "the", "this", "to", "with":
return true
}
return false
}There was a problem hiding this comment.
Thanks for the concrete optimization suggestion. The allocation cost is visible in BenchmarkRankRowsByIntent -benchmem: on the current four-vCPU Linux/arm64 VM, 1,000 rows take about 826 µs / 1.20 MB / 9,005 allocations per operation, and 10,000 rows take about 7.83 ms / 11.93 MB / 90,005 allocations (including the input-slice copy).
I am keeping the straightforward term-set implementation for this baseline and recording those costs for comparison. The proposed uint64 path would silently ignore meaningful query terms beyond the first 64, so adopting it would need an unbounded fallback and regression coverage for longer intents. The current implementation has no 64-term cutoff. The benchmark now explicitly identifies its row counts and makes clear that it measures local cost, not retrieval quality.
f325499 to
c45521c
Compare
|
do we have a better algorithm for intent matching ? or some better explanation why this is better? |
| } | ||
| } | ||
|
|
||
| func BenchmarkRankRowsByIntent(b *testing.B) { |
There was a problem hiding this comment.
These are synthetic catalogue sizes (100, 1,000 and 10,000 remoteToolRow values), not search-quality results. Each benchmark iteration copies that catalogue and ranks it for review pull request. It excludes mesh discovery and MCP network calls.
I added an explicit benchmark comment and renamed the subcases to rows=100, rows=1000 and rows=10000. A fresh run on the four-vCPU Linux/arm64 validation VM with Go 1.27.3 reports approximately 86.8 µs, 826 µs and 7.83 ms per operation respectively; -benchmem also reports allocations. These numbers describe local cost only. The handler regression tests, rather than this benchmark, show the behavioral difference from main.
|
@shin0343 it seems this is correct, we want to keep this in Go standard library without adding external dependencies. Here is a reference pattern using only package node
import (
"cmp"
"slices"
"strings"
"unicode"
)
type ToolCandidate struct {
PeerID string
ServiceName string
Name string
Description string
}
// tokenize splits snake_case, kebab-case, and prose into lowercase alphanumeric tokens.
func tokenize(s string) []string {
return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsNumber(r)
})
}
var stopWords = map[string]struct{}{
"a": {}, "an": {}, "the": {}, "to": {}, "for": {}, "in": {},
"of": {}, "on": {}, "with": {}, "and": {}, "or": {}, "by": {},
"is": {}, "that": {}, "from": {}, "tool": {}, "find": {},
}
// scoreIntentOverlap returns a lexical overlap score (> 0 means at least one meaningful match).
func scoreIntentOverlap(intentTokens []string, toolName, toolDesc string) int {
nameTokens := make(map[string]struct{})
for _, t := range tokenize(toolName) {
nameTokens[t] = struct{}{}
}
descTokens := make(map[string]struct{})
for _, t := range tokenize(toolDesc) {
descTokens[t] = struct{}{}
}
lowerName := strings.ToLower(toolName)
lowerDesc := strings.ToLower(toolDesc)
score := 0
for _, q := range intentTokens {
// Exact token match in tool name carries the highest weight
if _, ok := nameTokens[q]; ok {
score += 3
continue
}
// Exact token match in description
if _, ok := descTokens[q]; ok {
score += 2
continue
}
// Prefix/substring fallback (e.g., "deploy" matching "deployment")
if len(q) >= 3 && (strings.Contains(lowerName, q) || strings.Contains(lowerDesc, q)) {
score += 1
}
}
return score
}
func RankRemoteToolsByIntent(tools []ToolCandidate, intent string) []ToolCandidate {
rawTokens := tokenize(intent)
if len(rawTokens) == 0 {
return tools
}
// Deduplicate query tokens and filter stop words
seen := make(map[string]struct{}, len(rawTokens))
intentTokens := make([]string, 0, len(rawTokens))
for _, t := range rawTokens {
if _, isStop := stopWords[t]; isStop {
continue
}
if _, exists := seen[t]; !exists {
seen[t] = struct{}{}
intentTokens = append(intentTokens, t)
}
}
// Fallback if the query consisted entirely of stop words
if len(intentTokens) == 0 {
intentTokens = rawTokens
}
type scoredTool struct {
tool ToolCandidate
score int
}
var matched []scoredTool
for _, t := range tools {
if s := scoreIntentOverlap(intentTokens, t.Name, t.Description); s > 0 {
matched = append(matched, scoredTool{tool: t, score: s})
}
}
// Sort descending by score; preserve original order on ties
slices.SortStableFunc(matched, func(a, b scoredTool) int {
return cmp.Compare(b.score, a.score)
})
result := make([]ToolCandidate, len(matched))
for i, m := range matched {
result[i] = m.tool
}
return result
}Could we also add a table-driven test in
|
|
@aojea Thanks, agreed on keeping this entirely in the Go standard library. The improvement over the existing behavior is that I moved and expanded
The existing peer/service-filter and authorization checks remain covered. Unlike the filtering step in the reference sketch, zero overlap retains the authorized catalogue in tool-name/peer-ID order. This keeps The revised tests fail four ranking assertions on today's main ( Pushed in |
|
@HosniBelfeki it seems we added a flaky test
do you mind fixing it? |
|
Sorry about that, and thanks for the log. The flake is in the test helper I added in #842, not in the code under test: |
|
Thanks for addressing the test cases and clarifying the benchmark and zero-overlap behavior — keeping zero-overlap as a ranking hint rather than filtering tools out makes sense. The code, tests, and docs look good to me. Please rebase onto current main to resolve the conflicts in internal/node/mcp_handlers.go and internal/node/mcp_handlers_test.go and re-run CI (which also picks up the #845 test-flake fix), and I'll approve and merge once green. |
Signed-off-by: Jaehyup (Jay) Shin <jshin4@scu.edu>
Assert complete handler ordering for natural-language snake_case names, conflicting exact-name lookups, multi-word overlap, and no matches. Preserve peer/service and authorization controls. Clarify benchmark scope and API examples. Signed-off-by: Jaehyup (Jay) Shin <jshin4@scu.edu>
fd2716f to
8e12e3a
Compare
|
Thanks for the review, @aojea. I rebased onto All 16 checks that ran passed. That includes the full Go test suite (including the #845 regression and the intent-ranking cases), lint, and the Bats, Kind, and Android E2E jobs. GitHub reports the PR is mergeable. CI results |
find_remote_toolscurrently acceptsintentwithout using it. This adds a Go-standard-library lexical baseline: distinct query-word coverage in service/tool names and descriptions, then name matches, with deterministic tool-name/peer-ID ties. No dependencies, flags, or protocol changes.Ranking runs after authorized discovery and peer/service filtering. Exact
tool_namelookups take precedence. Nonmatching tools, labels, and diagnostic rows are retained. Empty/function-word-only queries preserve the unranked order; zero-overlap queries return the authorized catalogue in deterministic order. Raw intent text is no longer logged.Related to #313. This is keyword ranking without synonym inference or embeddings; no broader semantic-retrieval quality claim is made. The API reference shows the three-word versus one-word ordering and documents the no-match behavior.
Review follow-up:
TestHandleFindRemoteTools_Intentnow lives ininternal/node/mcp_handlers_test.goand checks complete tool order for snake_case natural-language matching, exact-name precedence, multi-word coverage, and zero overlap. Peer/service filters and authorization hiding remain covered.Validation on Linux/arm64 with Go 1.27.3 after merging upstream main
1fae868e:-race; unit cases cover Unicode/punctuation, duplicate terms, deterministic ties, and retained metadata/errors.make: pass.make test: 874 top-level tests passed, 10 SDK tests skipped because their JavaScript/Python SDK environments are not installed.make lint: pass, including formatting, both Helm charts, golangci-lint v2.14.0 (zero issues), and deadcode.make e2e-test: all 32 Bats scenarios pass, including the remote tool discovery/call/describe scenarios.Google CLA passed before this follow-up; the new commit uses the same CLA-associated author and DCO identity. Upstream checks will validate the new head after push.
AI assistance: implemented with Codex, with independent read-only code/documentation review.