From 073a41a34f3582ee13efa12701cdc8a49b1e75c3 Mon Sep 17 00:00:00 2001 From: "Jaehyup (Jay) Shin" Date: Wed, 28 Oct 2026 20:00:26 -0700 Subject: [PATCH 1/2] node: rank remote tools by intent word overlap Signed-off-by: Jaehyup (Jay) Shin --- internal/node/mcp.go | 4 +- internal/node/mcp_handlers.go | 86 +++++++++-- internal/node/mcp_search_test.go | 182 ++++++++++++++++++++++++ site/content/docs/reference/node-api.md | 14 +- 4 files changed, 275 insertions(+), 11 deletions(-) create mode 100644 internal/node/mcp_search_test.go diff --git a/internal/node/mcp.go b/internal/node/mcp.go index abc538d22..57cd571e0 100644 --- a/internal/node/mcp.go +++ b/internal/node/mcp.go @@ -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. @@ -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. diff --git a/internal/node/mcp_handlers.go b/internal/node/mcp_handlers.go index 39b73bd80..ba62bfa33 100644 --- a/internal/node/mcp_handlers.go +++ b/internal/node/mcp_handlers.go @@ -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" @@ -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."` @@ -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 @@ -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) } @@ -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 +} + // fetchRemoteToolCatalogue gets the remote node's service catalogue, // then opens a separate libp2p stream to each MCP service that can match the // requested filter. diff --git a/internal/node/mcp_search_test.go b/internal/node/mcp_search_test.go new file mode 100644 index 000000000..2286effbc --- /dev/null +++ b/internal/node/mcp_search_test.go @@ -0,0 +1,182 @@ +// 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 ( + "context" + "encoding/json" + "fmt" + "net/http/httptest" + "reflect" + "slices" + "strings" + "testing" + "time" + + "github.com/google/agentmesh/api" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +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_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, wantFirst string + wantCount int + }{ + {"intent with peer", "", "", "review pull request", "review_pr", 2}, + {"bare service", "code-reviewer", "", "review pull request", "review_pr", 2}, + {"namespaced service", "mcp://code-reviewer", "", "review pull request", "review_pr", 2}, + {"exact name wins", "", "add_comment", "review pull request", "add_comment", 1}, + {"denied service stays hidden", "private-review", "", "review pull request", "", 0}, + } { + 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) + } + if len(rows) != tc.wantCount { + t.Fatalf("got %d rows, want %d: %+v", len(rows), tc.wantCount, rows) + } + for _, row := range rows { + 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 len(rows) > 0 && rows[0].ToolName != "mcp://code-reviewer/"+tc.wantFirst { + t.Errorf("first tool = %q, want %q", rows[0].ToolName, tc.wantFirst) + } + }) + } +} + +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) + } +} + +func BenchmarkRankRowsByIntent(b *testing.B) { + for _, size := range []int{100, 1000, 10000} { + b.Run(fmt.Sprint(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") + } + }) + } +} diff --git a/site/content/docs/reference/node-api.md b/site/content/docs/reference/node-api.md index fac8e91ad..ea6151404 100644 --- a/site/content/docs/reference/node-api.md +++ b/site/content/docs/reference/node-api.md @@ -227,13 +227,25 @@ 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 a tool described as "Review a pull request" ahead of an unrelated comment +tool, while still returning both. Use `tool_name` for exact lookups. + ### `describe_remote_tool` | Parameter | Meaning | From 8e12e3a6054cab16914c6408f88e239b3191fcea Mon Sep 17 00:00:00 2001 From: "Jaehyup (Jay) Shin" Date: Sun, 1 Nov 2026 09:20:07 -0800 Subject: [PATCH 2/2] test(node): cover intent ranking review cases 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 --- internal/node/mcp_handlers_test.go | 88 +++++++++++++++++++++++++ internal/node/mcp_search_test.go | 77 ++-------------------- site/content/docs/reference/node-api.md | 8 ++- 3 files changed, 98 insertions(+), 75 deletions(-) diff --git a/internal/node/mcp_handlers_test.go b/internal/node/mcp_handlers_test.go index c24fc8994..168535c0b 100644 --- a/internal/node/mcp_handlers_test.go +++ b/internal/node/mcp_handlers_test.go @@ -23,6 +23,7 @@ import ( "io" "net/http" "net/http/httptest" + "slices" "strings" "sync/atomic" "testing" @@ -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) + } + }) + } +} diff --git a/internal/node/mcp_search_test.go b/internal/node/mcp_search_test.go index 2286effbc..4994245b5 100644 --- a/internal/node/mcp_search_test.go +++ b/internal/node/mcp_search_test.go @@ -15,84 +15,12 @@ package node import ( - "context" - "encoding/json" "fmt" - "net/http/httptest" "reflect" "slices" - "strings" "testing" - "time" - - "github.com/google/agentmesh/api" - "github.com/libp2p/go-libp2p/core/peer" - "github.com/modelcontextprotocol/go-sdk/mcp" ) -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_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, wantFirst string - wantCount int - }{ - {"intent with peer", "", "", "review pull request", "review_pr", 2}, - {"bare service", "code-reviewer", "", "review pull request", "review_pr", 2}, - {"namespaced service", "mcp://code-reviewer", "", "review pull request", "review_pr", 2}, - {"exact name wins", "", "add_comment", "review pull request", "add_comment", 1}, - {"denied service stays hidden", "private-review", "", "review pull request", "", 0}, - } { - 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) - } - if len(rows) != tc.wantCount { - t.Fatalf("got %d rows, want %d: %+v", len(rows), tc.wantCount, rows) - } - for _, row := range rows { - 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 len(rows) > 0 && rows[0].ToolName != "mcp://code-reviewer/"+tc.wantFirst { - t.Errorf("first tool = %q, want %q", rows[0].ToolName, tc.wantFirst) - } - }) - } -} - func TestRankRowsByIntent(t *testing.T) { tests := []struct { name, intent string @@ -161,9 +89,12 @@ func TestRankRowsByIntent_PreservesRows(t *testing.T) { } } +// 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) { for _, size := range []int{100, 1000, 10000} { - b.Run(fmt.Sprint(size), func(b *testing.B) { + b.Run(fmt.Sprintf("rows=%d", size), func(b *testing.B) { catalogue := make([]remoteToolRow, size) for i := range catalogue { catalogue[i] = remoteToolRow{ diff --git a/site/content/docs/reference/node-api.md b/site/content/docs/reference/node-api.md index ea6151404..daf3b4dc7 100644 --- a/site/content/docs/reference/node-api.md +++ b/site/content/docs/reference/node-api.md @@ -243,8 +243,12 @@ 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 a tool described as "Review a pull request" ahead of an unrelated comment -tool, while still returning both. Use `tool_name` for exact lookups. +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`