Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions internal/node/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const meshInstructions = `This MCP server connects this node to an Agent Mesh: a

The mesh allows you to discover these remote services, list their tools, and call them.
To use these remote services and their tools, the client can use the following flow:
1. find_remote_tools — discover what tools exist across the mesh (returns peer_id + namespaced tool_name + description). Optionally narrow by service_name or peer_id.
1. find_remote_tools — discover what tools exist across the mesh (returns peer_id + namespaced tool_name + description). Optionally narrow by service_name or peer_id; provide intent to rank tools by words in their names and descriptions.
2. describe_remote_tool — fetch a specific tool's input_schema before calling it. Always do this so you know the argument shape.
3. call_remote_tool — invoke it. Pass peer_id, the namespaced tool_name (scheme://service/tool, e.g. 'mcp://code-reviewer/review_pr'), and arguments as a JSON object whose keys match the input_schema.

Expand Down Expand Up @@ -97,7 +97,7 @@ func NewMCPServer(node *AgentMeshNode) *mcp.Server {
// Add the find_remote_tools tool.
mcp.AddTool(mcpServer, &mcp.Tool{
Name: "find_remote_tools",
Description: "Discover MCP tools available on hosted services across the mesh. Returns name + description per tool, plus the provider's declared labels (e.g. region) when known. Optionally narrow by peer_id, service_name, or tool_name (exact tool name; fastest — served from mesh announcements when available). intent is reserved for future ranking and is accepted-but-ignored.",
Description: "Discover MCP tools available on hosted services across the mesh. Returns name + description per tool, plus the provider's declared labels (e.g. region) when known. Optionally narrow by peer_id, service_name, or tool_name (exact tool name; fastest — served from mesh announcements when available). intent ranks by matching words in names and descriptions, retaining nonmatching tools; tool_name takes precedence.",
}, node.handleFindRemoteTools)

// Add the describe_remote_tool tool.
Expand Down
86 changes: 78 additions & 8 deletions internal/node/mcp_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,16 @@
package node

import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"sync"
"time"
"unicode"

"github.com/google/agentmesh/api"
"github.com/libp2p/go-libp2p/core/peer"
Expand Down Expand Up @@ -186,7 +189,7 @@ func (n *AgentMeshNode) handleCallRemoteTool(ctx context.Context, req *mcp.CallT
// FindRemoteToolsParams defines the parameters for the
// find_remote_tools tool.
type FindRemoteToolsParams struct {
Intent string `json:"intent,omitempty" jsonschema:"Natural-language description of what the caller is looking for. Reserved for future semantic ranking; currently accepted but ignored."`
Intent string `json:"intent,omitempty" jsonschema:"Rank tools by matching words in their names and descriptions. Nonmatching tools remain in the results. Ignored when tool_name is set."`
PeerID string `json:"peer_id,omitempty" jsonschema:"Restrict the search to a single peer. Empty means search the whole mesh."`
ServiceName string `json:"service_name,omitempty" jsonschema:"Restrict results to tools whose name starts with this service prefix (e.g. 'code-reviewer'). Empty means no service filter."`
ToolName string `json:"tool_name,omitempty" jsonschema:"Exact (non-namespaced) tool name to locate across the mesh, e.g. 'review_pr'. Empty means list all tools."`
Expand All @@ -212,14 +215,10 @@ type remoteToolRow struct {
// Filtering:
// - If params.ServiceName is set, only tools from that service are returned.
// Bare ("everything") and namespaced ("mcp://everything") forms are equivalent.
// - params.Intent is accepted and logged at debug level, but does not
// filter or rank results in this implementation (placeholder for
// future semantic search).
// - params.ToolName selects an exact tool name, taking precedence over intent.
// - Otherwise params.Intent ranks the authorized results by word overlap in
// names and descriptions, retaining nonmatching tools and error rows.
func (n *AgentMeshNode) handleFindRemoteTools(ctx context.Context, req *mcp.CallToolRequest, params FindRemoteToolsParams) (*mcp.CallToolResult, any, error) {
if params.Intent != "" {
logger.Debugf("[find_remote_tools] intent (ignored): %q", params.Intent)
}

serviceFilter, err := normalizeServiceFilter(params.ServiceName)
if err != nil {
return nil, nil, err
Expand Down Expand Up @@ -264,6 +263,9 @@ func (n *AgentMeshNode) handleFindRemoteTools(ctx context.Context, req *mcp.Call

if params.ToolName != "" {
rows = filterRowsByToolName(rows, params.ToolName)
} else if params.Intent != "" {
rows = rankRowsByIntent(rows, params.Intent)
logger.Debugf("[find_remote_tools] ranked %d rows by intent", len(rows))
}
return marshalToolRows(rows)
}
Expand Down Expand Up @@ -318,6 +320,74 @@ func filterRowsByToolName(rows []remoteToolRow, toolName string) []remoteToolRow
return out
}

// rankRowsByIntent orders an already authorized catalogue by distinct query
// word coverage, then by matches in the service/tool name. This is lexical
// ranking, not semantic search: it neither infers synonyms nor drops results.
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
}
Comment on lines +326 to +389

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.


// fetchRemoteToolCatalogue gets the remote node's service catalogue,
// then opens a separate libp2p stream to each MCP service that can match the
// requested filter.
Expand Down
88 changes: 88 additions & 0 deletions internal/node/mcp_handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync/atomic"
"testing"
Expand Down Expand Up @@ -1261,3 +1262,90 @@ func newPreDiscoverMCPHandler(t *testing.T, tools []*mcp.Tool) http.Handler {
real.ServeHTTP(w, r)
})
}

func TestHandleFindRemoteTools_Intent(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
backend := httptest.NewServer(newFakeMCPHandler(t, []*mcp.Tool{
{Name: "add_comment", Description: "Add a comment", InputSchema: map[string]any{"type": "object"}},
{Name: "review_changes", Description: "Inspect modifications", InputSchema: map[string]any{"type": "object"}},
{Name: "review_pr", Description: "Review a pull request", InputSchema: map[string]any{"type": "object"}},
}))
defer backend.Close()
caller, cleanupCaller := startBareNode(t, ctx)
defer cleanupCaller()
provider, cleanupProvider := startBareNode(t, ctx)
defer cleanupProvider()
_, root := enrollUnderRoot(t, caller, provider)
if err := buildAndSaveCustomBiscuit(caller, root, []string{"mcp://code-reviewer", "system://mesh.catalog"}); err != nil {
t.Fatal(err)
}
if err := caller.Host.Connect(ctx, peer.AddrInfo{ID: provider.Host.ID(), Addrs: provider.Host.Addrs()}); err != nil {
t.Fatal(err)
}
for _, name := range []string{"code-reviewer", "private-review"} {
if err := provider.RegisterService(ctx, &api.RegisterServiceRequest{
Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: name},
Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: backend.URL},
}); err != nil {
t.Fatal(err)
}
}
for _, tc := range []struct {
name, service, exact, intent string
wantTools []string
}{
{
// Only the tool name contains both query words, and it starts
// behind add_comment in the unranked catalogue.
name: "snake_case name matches natural language", intent: "review changes",
wantTools: []string{"review_changes", "review_pr", "add_comment"},
},
{
name: "multi-word coverage outranks single-word match", intent: "review pull request",
wantTools: []string{"review_pr", "review_changes", "add_comment"},
},
{
name: "bare service", service: "code-reviewer", intent: "review pull request",
wantTools: []string{"review_pr", "review_changes", "add_comment"},
},
{
name: "namespaced service", service: "mcp://code-reviewer", intent: "review pull request",
wantTools: []string{"review_pr", "review_changes", "add_comment"},
},
{
name: "exact name wins over conflicting intent", exact: "add_comment", intent: "review pull request",
wantTools: []string{"add_comment"},
},
{
// Intent is a ranking hint, so zero overlap retains all authorized
// tools in deterministic tool-name order rather than hiding them.
name: "no overlap retains catalogue", intent: "weather forecast",
wantTools: []string{"add_comment", "review_changes", "review_pr"},
},
{name: "denied service stays hidden", service: "private-review", intent: "review pull request"},
} {
t.Run(tc.name, func(t *testing.T) {
result, _, err := caller.handleFindRemoteTools(ctx, nil, FindRemoteToolsParams{
PeerID: provider.Host.ID().String(), ServiceName: tc.service, ToolName: tc.exact, Intent: tc.intent,
})
if err != nil {
t.Fatal(err)
}
var rows []remoteToolRow
if err := json.Unmarshal([]byte(result.Content[0].(*mcp.TextContent).Text), &rows); err != nil {
t.Fatal(err)
}
var gotTools []string
for _, row := range rows {
gotTools = append(gotTools, strings.TrimPrefix(row.ToolName, "mcp://code-reviewer/"))
if row.PeerID != provider.Host.ID().String() || !strings.HasPrefix(row.ToolName, "mcp://code-reviewer/") || row.Error != "" {
t.Errorf("unexpected or unauthorized row: %+v", row)
}
}
if !slices.Equal(gotTools, tc.wantTools) {
t.Errorf("tools = %v, want %v", gotTools, tc.wantTools)
}
})
}
}
113 changes: 113 additions & 0 deletions internal/node/mcp_search_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package node

import (
"fmt"
"reflect"
"slices"
"testing"
)

func TestRankRowsByIntent(t *testing.T) {
tests := []struct {
name, intent string
rows []remoteToolRow
want []string
}{
{"coverage before name matches", "review pull request", []remoteToolRow{
{PeerID: "partial", ToolName: "mcp://review/review"},
{PeerID: "full", ToolName: "mcp://tools/check", Description: "Review a pull request"},
}, []string{"full", "partial"}},
{"name breaks coverage tie", "review", []remoteToolRow{
{PeerID: "description", ToolName: "mcp://a/check", Description: "review"},
{PeerID: "name", ToolName: "mcp://z/review"},
}, []string{"name", "description"}},
{"case punctuation and distinct terms", "THE REVIEW_review, pull-request!", []remoteToolRow{
{PeerID: "repetition", ToolName: "mcp://a/review", Description: "review review review review"},
{PeerID: "coverage", ToolName: "mcp://z/review_pr", Description: "Review a pull request"},
}, []string{"coverage", "repetition"}},
{"Unicode words", "문서 요약", []remoteToolRow{
{PeerID: "other", ToolName: "mcp://tools/edit", Description: "문서 편집"},
{PeerID: "match", ToolName: "mcp://tools/summarize", Description: "문서 요약"},
}, []string{"match", "other"}},
{"retain unmatched tools and errors", "review", []remoteToolRow{
{PeerID: "error", ToolName: "mcp://review", Error: "review unavailable"},
{PeerID: "unmatched", ToolName: "mcp://a/list"},
{PeerID: "match", ToolName: "mcp://z/review"},
}, []string{"match", "unmatched", "error"}},
{"sort ties by tool then peer", "missing", []remoteToolRow{
{PeerID: "z", ToolName: "mcp://b/tool"},
{PeerID: "b", ToolName: "mcp://a/tool"},
{PeerID: "a", ToolName: "mcp://a/tool"},
}, []string{"a", "b", "z"}},
{"empty preserves order", "", []remoteToolRow{{PeerID: "z"}, {PeerID: "a"}}, []string{"z", "a"}},
{"whitespace preserves order", " \t\n", []remoteToolRow{{PeerID: "z"}, {PeerID: "a"}}, []string{"z", "a"}},
{"function words preserve order", "the and of to", []remoteToolRow{{PeerID: "z"}, {PeerID: "a"}}, []string{"z", "a"}},
{"empty catalogue", "review", nil, nil},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
rows := rankRowsByIntent(slices.Clone(tc.rows), tc.intent)
var got []string
for _, row := range rows {
got = append(got, row.PeerID)
}
if !slices.Equal(got, tc.want) {
t.Errorf("order = %v, want %v", got, tc.want)
}
})
}
}

func TestRankRowsByIntent_PreservesRows(t *testing.T) {
rows := []remoteToolRow{
{PeerID: "one", ToolName: "mcp://tools/list", Description: "List branches", Labels: map[string]string{"region": "west"}},
{PeerID: "two", ToolName: "mcp://tools/review", Description: "Review code", Labels: map[string]string{"region": "east"}},
{PeerID: "three", ToolName: "mcp://unavailable", Error: "failed to connect"},
}
want := []remoteToolRow{rows[1], rows[0], rows[2]}
got := rankRowsByIntent(rows, "review")
if !reflect.DeepEqual(got, want) {
t.Errorf("ranked rows = %+v, want %+v", got, want)
}
slices.Reverse(got)
if again := rankRowsByIntent(got, "review"); !reflect.DeepEqual(again, want) {
t.Errorf("rank depends on input order: %+v, want %+v", again, want)
}
}

// BenchmarkRankRowsByIntent measures local ranking of synthetic catalogue rows,
// including the input-slice copy needed because ranking reorders it in place.
// It excludes mesh discovery and MCP calls and does not measure search relevance.
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.

for _, size := range []int{100, 1000, 10000} {
b.Run(fmt.Sprintf("rows=%d", size), func(b *testing.B) {
catalogue := make([]remoteToolRow, size)
for i := range catalogue {
catalogue[i] = remoteToolRow{
PeerID: fmt.Sprintf("peer-%d", i),
ToolName: fmt.Sprintf("mcp://code-reviewer/tool_%d", i),
Description: "Review a pull request and report code quality issues",
}
}
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
rankRowsByIntent(slices.Clone(catalogue), "review pull request")
}
})
}
}
18 changes: 17 additions & 1 deletion site/content/docs/reference/node-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,13 +227,29 @@ HTTP and not with `call_remote_tool`.
| `peer_id` | Restrict the search to one peer. |
| `service_name` | Restrict the search to one service, bare (`code-reviewer`) or namespaced (`mcp://code-reviewer`). |
| `tool_name` | Exact tool name to locate across the mesh (`review_pr`). |
| `intent` | Accepted and ignored. Reserved for later use. |
| `intent` | Rank results by words in service/tool names and descriptions. Ignored when `tool_name` is set. |

Returns one row per tool with `peer_id`, `tool_name` (namespaced as
`mcp://service/tool`) and `description`. A peer that could not be
queried appears as a row with an `error` field. The call itself does not
fail.

Intent ranking is lexical: it counts distinct matching words, preferring name
matches when coverage is equal. Matching ignores case, splits punctuation
(including underscores and hyphens), and skips common English function words.
It does not infer synonyms. Ties sort by namespaced tool name, then peer ID.
Nonmatching tools remain after matching tools; error rows remain last. An empty
or function-word-only intent preserves the unranked catalogue order. Peer and
service filters and authorization apply before ranking.

For example, `{"intent":"review pull request","service_name":"code-reviewer"}`
puts `review_pr` ("Review a pull request", three matching words) ahead of
`review_changes` ("Inspect modifications", one matching word in its name),
followed by an unrelated `add_comment` tool. Repeating a word does not increase
its coverage. If no tool matches, all authorized tools are still returned in
tool-name/peer-ID order.
Use `tool_name` for exact lookups.

### `describe_remote_tool`

| Parameter | Meaning |
Expand Down
Loading