Skip to content

node: rank remote tools by intent word overlap - #832

Open
shin0343 wants to merge 2 commits into
google:mainfrom
shin0343:feat/intent-tool-ranking
Open

shin0343 wants to merge 2 commits into
google:mainfrom
shin0343:feat/intent-tool-ranking

Conversation

@shin0343

@shin0343 shin0343 commented Oct 29, 2026 •

Copy link
Copy Markdown

find_remote_tools currently accepts intent without 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_name lookups 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_Intent now lives in internal/node/mcp_handlers_test.go and 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.
  • The snake_case case requires a match from the name and a change from the original catalogue order; its description cannot supply the match.
  • The benchmark labels its catalogue row counts and documents that it includes the slice copy and local ranking, excludes network discovery, and does not measure relevance.

Validation on Linux/arm64 with Go 1.27.3 after merging upstream main 1fae868e:

  • The updated handler regression fails four ranking assertions on unchanged main. Exact-name, zero-overlap, and denied-service controls pass there.
  • Focused discovery/ranking tests and all seven final handler cases pass with -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.
  • Local ranking benchmark (100 / 1,000 / 10,000 rows): about 86.8 µs / 826 µs / 7.83 ms per operation on this four-vCPU VM. At 1,000 rows it reports 1,196,146 B/op and 9,005 allocs/op. These are synthetic local-cost measurements, not mesh latency or retrieval-quality results.

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.

@shin0343
shin0343 requested a review from aojea as a code owner October 29, 2026 06:00
@google-cla

google-cla Bot commented Oct 29, 2026

Copy link
Copy Markdown

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +328 to +391
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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:

  1. Tokenizing the query/intent once and mapping each query term to a unique bit index (0 to 63).
  2. Iterating over the words in each row's name and description, and using a uint64 bitmask 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
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@shin0343
shin0343 force-pushed the feat/intent-tool-ranking branch from f325499 to c45521c Compare October 29, 2026 15:30
@aojea

aojea commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator

do we have a better algorithm for intent matching ? or some better explanation why this is better?

}
}

func BenchmarkRankRowsByIntent(b *testing.B) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what are those results?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@aojea

aojea commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator

@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 cmp, slices, strings, and unicode from the standard library that you can adapt:

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 internal/node/mcp_handlers_test.go covering:

  • snake_case tool name matching against a natural-language intent
  • tool_name + intent set together (verifying exact match still wins)
  • Multi-word intent ranking a higher-overlap tool above a single-word match
  • No-match behavior when intent has zero overlap with available tools

@shin0343

shin0343 commented Nov 1, 2026

Copy link
Copy Markdown
Author

@aojea Thanks, agreed on keeping this entirely in the Go standard library.

The improvement over the existing behavior is that intent currently has no effect; this gives callers a deterministic lexical ordering. I am not claiming that it is the best retrieval algorithm or that the benchmark establishes relevance quality. Distinct word coverage comes first, with name matches breaking equal-coverage ties: for review pull request, review_pr covers all three words, review_changes covers one, and add_comment covers none. Repeated words cannot inflate the score.

I moved and expanded TestHandleFindRemoteTools_Intent into internal/node/mcp_handlers_test.go to assert the complete returned tool order for all four requested cases:

  • snake_case name matching natural language, with a description that cannot supply the match;
  • tool_name taking precedence over a conflicting intent;
  • multi-word coverage ranking above a single-word match;
  • zero-overlap behavior.

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 intent a ranking hint: a lexical miss cannot hide a usable tool. Diagnostics are retained too.

The revised tests fail four ranking assertions on today's main (1fae868e), while exact-name, no-match and denied-service controls already pass there. All seven handler cases and the ranking unit tests pass on this branch with -race. I also updated the API example and explained that the benchmark measures local ranking cost, not search accuracy.

Pushed in fd2716f2, after merging current main. make, make test (874 passed, 10 SDK-environment skips), make lint (zero issues), and make e2e-test (32/32) all pass on Linux/arm64 with Go 1.27.3.

@aojea

aojea commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator

@HosniBelfeki it seems we added a flaky test

=== RUN TestCallMCPTool_ProviderNotGrantedIsNotRetried
2026-11-01T17:23:38.118Z ERROR agentmesh-node node/service_registry.go:296 [ServiceRegistry] Announcing SERVICE_TYPE_MCP/code-reviewer by name: no attached router to ask
2026-11-01T17:23:38.118Z ERROR agentmesh-node node/service_registry.go:305 [ServiceRegistry] Announcing SERVICE_TYPE_MCP/code-reviewer by type: no attached router to ask
2026-11-01T17:23:39.100Z ERROR agentmesh-node node/service_registry.go:296 [ServiceRegistry] Announcing SERVICE_TYPE_MCP/code-reviewer by name: no attached router to ask
2026-11-01T17:23:39.100Z ERROR agentmesh-node node/service_registry.go:305 [ServiceRegistry] Announcing SERVICE_TYPE_MCP/code-reviewer by type: no attached router to ask
2026-11-01T17:23:40.102Z ERROR agentmesh-node node/service_registry.go:296 [ServiceRegistry] Announcing SERVICE_TYPE_MCP/code-reviewer by name: no attached router to ask
2026-11-01T17:23:40.103Z ERROR agentmesh-node node/service_registry.go:305 [ServiceRegistry] Announcing SERVICE_TYPE_MCP/code-reviewer by type: no attached router to ask
mcp_handlers_test.go:666: CallMCPTool over the facts limit = context canceled during retry: context deadline exceeded, want an error wrapping datalog: world runtime limit: too many facts and not provider not granted the service
--- FAIL: TestCallMCPTool_ProviderNotGrantedIsNotRetried (17.83s)

do you mind fixing it?

@HosniBelfeki

Copy link
Copy Markdown
Contributor

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: authorizerFactLimitRules parses 1100 rules one by one, and biscuit-go builds a new parser on every call, about 12s under -race inside the test's 15s context. #845 builds the same rules without the parser, so the authorizer does exactly the same work; under stress it went from 20 of 20 failures to 406 runs with none.

@aojea

aojea commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

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>
@shin0343
shin0343 force-pushed the feat/intent-tool-ranking branch from fd2716f to 8e12e3a Compare November 28, 2026 16:49
@shin0343

Copy link
Copy Markdown
Author

Thanks for the review, @aojea. I rebased onto main at b7822393, resolved the MCP handler conflicts, and pushed the rebased branch at 8e12e3a6. The rebase includes #845.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants