gateway: find_tools says no tool was found instead of handing over near names

sahuaja3669 on X (tweet 2122928458355319211), on the on-demand router:
it shouldn't pad its answer with tools of a near name that do something
else, and it should say plainly when nothing was found.

Before, find_tools counted any query word found as a substring of a
tool's name or description, stop words and single letters included. "a"
is in nearly every name, so "send an email" against GitHub, filesystem,
Linear, magpie-image and magpie-browser gave five tools in full
(search_code, read_file, write_file, ...) as matches, with nothing saying
they were weak; a query nothing matched did say so.

Now find_tools matches on the query's key words (stop words such as a,
the, to, my left out), each a whole word of the name or description or
the start of one at four letters or more (open/opens, issue/issues; a
non-ASCII word anywhere, as before). A tool is a match only when the
query is its name, or it has two thirds of the key words, one in its
name unless it has them all. When none clears that, the answer says no
tool was found and not to call one that only sounds close, and names
each server with its tool count and up to 8 of its tool names, as what
there is rather than as matches. call_tool's "close to it" for an
unknown name keeps a looser rule (a key word shared with the name,
hubNear), so create_isue still points to create_issue. Cheap and
deterministic: word lists, no model, no index.

The cost: a query in other words than the tool's ("draw an image of a
cat" for generate_image) now finds nothing, and the model reads
generate_image from the server list in the answer, and from find_tools'
description, which already names each server's tools.

Test: TestHubFindNothingClose, on real descriptions from
github-mcp-server, the reference filesystem server, Linear's, and
magpie-image's and magpie-browser's own. Red on the old
hub_ondemand.go: "send an email" matched eight tools or more, five in full.
docs/subsystems/mcp-router.md updated.

Run:
- full go test ./... -count=1 -timeout 45m on mote at 5c32b285d (on
  48fffb60c): every package ok, internal/gateway 1392s.
- full go test ./... -count=1 -timeout 45m on mica at 1acbfcc23 (on
  3e66d25d8), mote over its load: 100 packages ok, three red, none in
  code this touches: internal/dirent's watch tests (red on mica at
  3e66d25d8 alone too, ok on mote; #7031), internal/sessions
  TestWSLStoppedSinceNotOpened (internal/sessions doesn't import
  gateway; red 1 of 4 on mica at 3e66d25d8 alone, ok on mote; filed
  #7089), internal/gateway TestSearchQueueKeepsCodexAlive/progress (ok
  3 of 3 alone; filed #7090).
- at the pushed head 22647c27f (on e199eb9c7): go test ./internal/gateway
  -count=1 -timeout 45m on mica ok (1306s); go vet ./internal/gateway
  for darwin, linux and windows ok; gofmt -l clean.
- rebased onto d2fa7d8d7 to push (four commits: sessions, library, and
  d74754970's system-message placement in gateway, none in the hub);
  there go test ./internal/gateway -run 'Hub|MCP|Search|Message|System'
  ok on mica, go vet ok. 65c9a2e41 there addresses #7089's WSL wait.
Not tried: a real agent driving find_tools against a live router.
This commit is contained in:
yetone
2026-11-18 18:58:55 +08:00
parent d2fa7d8d79
commit 7300be4d01
3 changed files with 261 additions and 31 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ With the Library's switch "MCP router" on (#2679, @minggang123 on X), each agent
| Who keeps their entries | An agent keeps each server's own entry, and `AgentView.Hub` says why: `no-remote` (it reaches no server over HTTP: `mcpFile.supports` refuses the entry, as for Claude Desktop), `taken` (a Library server is itself called magpie), `own` (the agent has an entry called magpie that magpie didn't write; it is left as it is). `on` is an agent given the router's entry. An agent given none of the router's servers has no value. | `hubFor` in `mcp_hub.go`; `AgentView.Hub`, `View.MCPHub`, `View.HubPath` in `sync.go` |
| Serve | `tools/list` lists the tools of the servers ticked for that agent (at `/mcp/magpie/hub`, agent `""`: every server in the Library, ticked for any agent or none, but one turned off, `Server.Hidden`: by its switch, `ServerOn` ([Library](library.md)), or a plugin's server hidden from agents, [Plugin tools](plugin-tools.md)), but those in `DisabledTools`, as `<server>__<tool>`: each part in `[A-Za-z0-9_-]` (other characters `_`), at most 64 characters (`cutName`), `_2`, `_3` on a name two would share. Each tool's description and `inputSchema` go on as the server listed them (an object schema with no properties when it has none). An agent that searches its MCP tools itself is given every tool in full, and its tool search keeps them out of each request: Claude Code (`ENABLE_TOOL_SEARCH`, which magpie turns on, see [agent wiring](agent-wiring.md)), Claude Desktop, Codex (`tool_search` on magpie's catalog), Pi, Droid (which defers every MCP tool to its ToolSearch) and omp (which names each in its catalog by its description's first line) (`hubSearchesItself`, by the agent's id without its `@wsl:<distro>`). So is the address for any other app (agent `""`) and an agent given 10 tools or fewer. Any other agent is given its tools on demand (below). `tools/call` runs one; an unknown name, or another agent's, is error -32602. `initialize` and `ping` are answered; other methods are -32601. Tools only: no resources or prompts. | `hubMCPCall`, `hubNamed` in [`hub_mcp.go`](../../internal/gateway/hub_mcp.go) |
| What it serves | An agent that shows the router as one line, and its tools only once they are searched for, learns from that line alone which servers are behind it (a Pi asked about a GitHub repository cloned it rather than ask the DeepWiki behind the router, told only "The tools of the MCP servers in magpie's Library", 11-01). `initialize`'s `instructions` start with `HubLine`: `Tools of <name> (<what it is for>), …`, every server by name, each one's first clause (`hubClause`) cut at a word to an equal share of 250 characters (`hubLineMax`, Pi's `MAX_SERVER_DESCRIPTION_CHARS`), the short ones whole; names that don't fit are counted (`and N more`). Then, for an agent given several routers to tell them apart (packinggoodsllc_07668: magpies that only share MCP servers), the router's name sentence when it has one (Router name, below), then a line for each server (`hubDetails`): `- <name> (<its title>): <what it is for>. Tools: <tool> (<first clause of its description>), …`, the tools the Library turned off left out and a router's `[<name>] ` dropped; a line too long for its share of the room says its tools by name only, then as many names as fit and `and N more`. The whole is at most 2000 characters (`hubSayMax`, half the 4096 Claude Code keeps), the closing text kept whole. What a server is for is the market's (`serverAbout`): the featured or registry server it is by `serverKey`, whatever it is named, or the featured one it is named after; otherwise the server's own words, its `serverInfo.description` or else its `instructions`' first line (`saysOf`); another magpie's `Tools of a (…), b.` is said with `Tools of` once. Its title is its `serverInfo.title`. These and its tools are what the server last answered to `initialize` and `tools/list` (`noteCard`), kept in `mcp-hub-servers.json` beside settings.json (not in the synced library folder) by server name and `cardKey` (a hash of `hubKey`: an edit or a sign-in since is another server), written through a temporary file only when they change; a router started again describes its servers before running any. A server with no card for it as it is now (`Known` false) is listed by `initialize`, which waits up to 5 s (`hubDescribeWait`) for it. No model writes any of it. Which agents show the instructions, from their installed source (11-02): Claude Code (a `# MCP Server Instructions` message, 4096 characters), Codex (the namespace's description), OpenCode (`<mcp_instructions>`), Gemini CLI (in a trusted folder only), Qwen Code (the opening history), Pi (the first line in its prompt, the whole through codemode); Kimi CLI reads none, and none of them shows `serverInfo.title` to the model. Pi doesn't wait for a codemode server before writing the first prompt (`waitForDirectServers` waits for direct ones), so its instructions miss that prompt; Pi's own mcp.json (`fmtPiNative`) gets the same line as the hub entry's `description`, which Pi shows before connecting (`serverSummary`). It is magpie's on the hub entry only (`mine`), read back to tell a changed list of servers (`Server.about`, `same`), and any other entry's description is the user's. | `HubLine`, `hubAbout`, `hubDetails`, `hubServerLine`, `hubServersFor` in `hub_mcp.go`; `theHub.Servers`, `hubAbouts`, `hubServerFor` in `mcp_hub.go`; `hubServerOf`, `noteCard`, `saysOf` in [`mcp_hub_cards.go`](../../internal/library/mcp_hub_cards.go); `serverAbout` in [`market.go`](../../internal/library/market.go) |
| Tools on demand | An agent with no tool search of its own sends every tool, with its `inputSchema`, on every request (ArvinCharl on X, 11-04: the tools filled the context). Past `hubOnDemandOver` (10) tools, `hubOnDemand` gives it two in their place: `find_tools {query, server?}` scores each tool on the query's words (a word in its router name 3, in its description 1, the whole query in its name 5 more; `hubMatches`) and answers the best 5 with their name, description and `inputSchema`, then up to 15 more by name with their first clause; an empty query, or one nothing matches, names every tool. `find_tools`' description starts with `HubLine` (each server and what it is for: an agent such as omp shows a tool by its description's first line, and some, such as Droid, show no instructions), then how to search, then each server's tools (`hubDetails` within `hubFindSayMax`, 1200 characters; `hubFindSay`): told only how to search, a model asked for a picture searched and stopped (tao5010 on Discord, 11-04). `call_tool {name, arguments}` runs the tool by its router name as `tools/call` finds it (`hubToolNamed`), else the one tool with that name on its server in any case (`hubCallNamed`); `arguments` given as a string holding an object is that object. It runs through the same caller, roots and key limit as `tools/call` (`hubCall`), and its request-log row names the tool that ran (`mcpUse.named`). A name nothing gives is an error naming the close ones. `tools/call` takes both names whatever was listed, and still runs a tool by its own name. `initialize`'s instructions add `Its tools are given on demand: …` (counted from `HubServer.Tools`), and still name each server's tools (`hubDetails`), so the model knows what there is to find. The Library's switch Tools on demand (on by default) turns it off for every agent: `settings.RouterAllTools`, this computer's own (`KeepOwn`), set alone (`SetRouterAllTools`) and kept by the Settings page's save. | `hubOnDemand`, `hubFind`, `hubCallByName` in [`hub_ondemand.go`](../../internal/gateway/hub_ondemand.go); `hubCall` in `hub_mcp.go`; `RouterAllTools`, `SetRouterAllTools` in `settings.go`; `servers/hub-tools` in `gui/library.go`; `View.HubAllTools` in `sync.go` |
| Tools on demand | An agent with no tool search of its own sends every tool, with its `inputSchema`, on every request (ArvinCharl on X, 11-04: the tools filled the context). Past `hubOnDemandOver` (10) tools, `hubOnDemand` gives it two in their place: `find_tools {query, server?}` matches each tool on the query's key words (`hubKeyWords`: stop words such as a, the, to, my and single letters left out), each a whole word of its router name or description, or the start of one at four letters or more (open is opens', issues has issue; a word not in ASCII anywhere in it; `hubWordIn`). A tool is a match only when the query is its name, or it has at least two thirds of the key words, one in its name unless it has them all (`hubMatch.clears`; sahuaja3669 on X, 11-18: a router mustn't hand over a tool of a near name that does something else). Matches are ordered by a word in the name 3, in the description 1, the query as its name first (`hubMatches`); the best 5 come with their name, description and `inputSchema`, then up to 15 more by name with their first clause. An empty query names every tool. A query nothing matches says no tool was found and not to call one that only sounds close, and names each server with its count and up to 8 of its tools (`hubServerCounts`), as what there is, not as matches. Before, any word in any description counted, and "send an email" gave five filesystem and GitHub tools in full. `find_tools`' description starts with `HubLine` (each server and what it is for: an agent such as omp shows a tool by its description's first line, and some, such as Droid, show no instructions), then how to search, then each server's tools (`hubDetails` within `hubFindSayMax`, 1200 characters; `hubFindSay`): told only how to search, a model asked for a picture searched and stopped (tao5010 on Discord, 11-04). `call_tool {name, arguments}` runs the tool by its router name as `tools/call` finds it (`hubToolNamed`), else the one tool with that name on its server in any case (`hubCallNamed`); `arguments` given as a string holding an object is that object. It runs through the same caller, roots and key limit as `tools/call` (`hubCall`), and its request-log row names the tool that ran (`mcpUse.named`). A name nothing gives is an error naming the tools whose names share a key word with it (`hubNear`: create_isue is close to create_issue). `tools/call` takes both names whatever was listed, and still runs a tool by its own name. `initialize`'s instructions add `Its tools are given on demand: …` (counted from `HubServer.Tools`), and still name each server's tools (`hubDetails`), so the model knows what there is to find. The Library's switch Tools on demand (on by default) turns it off for every agent: `settings.RouterAllTools`, this computer's own (`KeepOwn`), set alone (`SetRouterAllTools`) and kept by the Settings page's save. | `hubOnDemand`, `hubFind`, `hubCallByName` in [`hub_ondemand.go`](../../internal/gateway/hub_ondemand.go); `hubCall` in `hub_mcp.go`; `RouterAllTools`, `SetRouterAllTools` in `settings.go`; `servers/hub-tools` in `gui/library.go`; `View.HubAllTools` in `sync.go` |
| Router name | What a router says of itself, for an agent given the same tools by two routers (packinggoodsllc_07668 on Discord: one magpie in China, one in Los Angeles) to pick one. `hubWhere`: the user's words (`settings.RouterNote`, one line, 80 characters at most, `CleanRouterNote`), to every caller; with none, this computer's name (`hostName`) to a caller that isn't `local`, and nothing to one that is (one router at hand; the computer's name stays off its prompts). With a value, `initialize`'s `instructions` say `This router: <name>. …` on their second line (at the end when no server is behind it), `serverInfo.title` is `Magpie MCP hub · <name>`, and each tool's description starts `[<name>] ` (once: a description that starts so already, another magpie's router behind this one, isn't given it again). It is this computer's own (`KeepOwn`): a sync never brings another's. Set in the Library's MCP tab (below) or settings.json; the Settings page's save keeps it (`POST /api/settings`). | `hubWhere` in `hub_mcp.go`; `RouterNote`, `SetRouterNote` in [`settings.go`](../../internal/settings/settings.go); `servers/hub-note` in `gui/library.go`; `View.HubNote`, `View.HubName` in `sync.go` |
| A project's set | A Library project that adds a server the router serves, or turns one off, gives Claude Code and Codex the hub at `/mcp/magpie/hub/<agent>~<key>` (`gateway.HubProjectSep`; key `projectKey`, from the project's folder; [Library](library.md) Projects). `hubServers` gives that address the agent's servers with the project's added and its offs taken out, and each server still runs once for every agent and project. `gateway.HubAgentOf` cuts the key off where only the agent counts (a tool's caller, an on-demand server's agent). | `hubServers`, `projectHubs`, [`project_scope.go`](../../internal/library/project_scope.go) |
| Magpie Image's project | Magpie Image saves into the project of the agent that called it, though one server serves every agent. Its tools are `HubTool.Roots`: for such a call the router answers the POST as an event stream (`mcpExchange`) and asks the agent `roots/list` on it, waiting `hubRootsWait` (3s); Claude Code answers with its folder. An agent that answers no roots, or none (Codex answers `[]`), is given the workspaces the call's `_meta` names (Codex's `x-codex-turn-metadata.workspaces`, keyed by the folder of each git repository it works in, absolute paths only), and failing those the folder of the call's `_meta.threadId` in Codex's sessions (`sessions.CodexThreadCwd`, its rollout's cwd), only with consent to read them; with neither (a folder that isn't a repository, no consent), none. A caller that isn't local gets no roots. The call goes on with `_meta` `magpie/roots` (file URIs, never null) and `magpie/client` (the first word of the agent's User-Agent, e.g. `claude-code/2.1.314`). The image server, seeing `magpie/roots`, saves into the first root, or `~/Pictures/Magpie` with none (never its own folder), draws as `<client> magpie-image/1`, and sends no `magpie/toolCalled` report, since the router's row is the call's: its result's `_meta` `magpie/model` (provider/model) names the model it drew with, for that row (`HubModelMeta`). | `hubRoots`, `hubClient`, `WithHubCaller` in `hub_mcp.go`; [`mcp_ask.go`](../../internal/gateway/mcp_ask.go); `imageMeta` in `mcp_hub.go`; `project`, `rootOf` in [`imagemcp.go`](../../internal/imagemcp/imagemcp.go); [`codex_cwd.go`](../../internal/sessions/codex_cwd.go) |
+111
View File
@@ -0,0 +1,111 @@
package gateway
import (
"encoding/json"
"strings"
"testing"
)
// realHubTools are tools as real MCP servers describe them: GitHub's
// (github-mcp-server), the reference filesystem server's, Linear's, and
// magpie-image's and magpie-browser's own.
func realHubTools() []hubTool {
var ts []HubTool
add := func(server, tool, desc string) {
d, _ := json.Marshal(desc)
n, _ := json.Marshal(tool)
ts = append(ts, HubTool{Server: server, Tool: tool, Spec: map[string]json.RawMessage{
"name": n, "description": d, "inputSchema": json.RawMessage(`{"type":"object","properties":{}}`),
}})
}
add("github", "create_issue", "Create a new issue in a GitHub repository.")
add("github", "list_issues", "List issues in a GitHub repository. For pagination, use the 'endCursor' from the previous response's 'pageInfo' in the 'after' parameter.")
add("github", "search_code", "Fast and precise code search across ALL GitHub repositories using GitHub's native search engine. Best for finding exact symbols, functions, classes, or specific code patterns.")
add("github", "create_pull_request", "Create a new pull request in a GitHub repository.")
add("github", "get_file_contents", "Get the contents of a file or directory from a GitHub repository")
add("filesystem", "read_file", "Read the complete contents of a file from the file system. Handles various text encodings and provides detailed error messages if the file cannot be read. Use this tool when you need to examine the contents of a single file. Only works within allowed directories.")
add("filesystem", "write_file", "Create a new file or completely overwrite an existing file with new content. Use with caution as it will overwrite existing files without warning. Handles text content with proper encoding. Only works within allowed directories.")
add("filesystem", "list_directory", "Get a detailed listing of all files and directories in a specified path. Results clearly distinguish between files and directories with [FILE] and [DIR] prefixes. This tool is essential for understanding directory structure and finding specific files within a directory. Only works within allowed directories.")
add("filesystem", "search_files", "Recursively search for files and directories matching a pattern. Searches through all subdirectories from the starting path. The search is case-insensitive and matches partial names. Returns full paths to all matching items. Great for finding files when you don't know their exact location. Only searches within allowed directories.")
add("linear", "save_issue", "Create or update a Linear issue. If `id` is provided, updates the existing issue; otherwise creates a new one. When creating, `team` is required, and `title` is required unless `template` is set.")
add("linear", "list_issues", "List issues in the user's Linear workspace, including active Triage Intelligence suggestions for issues in triage. For issues assigned to me, use \"me\" as the assignee.")
add("linear", "search_documentation", "Search Linear's product documentation for feature and usage guidance. Returns up to five results with titles, URLs, and content snippets per page.")
add("magpie-image", "generate_image", "Generate an image from a text prompt, or edit/combine images given as reference_images, with the image model set in Magpie. The image is saved as a file in the project (generated-images/ unless path says where) and its path is returned.")
add("magpie-browser", "browser", "Act in the user's own browser. Actions, with the arguments each takes:\ntabs: list them. tab_new [url, background]. navigate [url]. back. forward. reload.\nsnapshot [interactive, ref, maxChars]: the page as an accessibility tree, a ref on each element you can act on.\nclick [ref]. type [ref, text]. screenshot [ref, fullPage, png]. text [maxChars]: the visible text.")
return hubNamed(ts)
}
func findText(t *testing.T, ts []hubTool, args string) string {
t.Helper()
b, _ := json.Marshal(hubFind(ts, json.RawMessage(args), ""))
var r struct {
Content []struct{ Text string }
IsError bool
}
if err := json.Unmarshal(b, &r); err != nil || len(r.Content) == 0 {
t.Fatalf("%v: %s", err, b)
}
return r.Content[0].Text
}
// find_tools gives a tool only when it does what the query asks, and when
// none does it says no tool was found, naming the servers, rather than
// handing over the tools whose names or descriptions share a word or two
// with it. Words of what it is for but in other words ("draw an image
// of a cat") find nothing, and the answer names each server's tools, as
// what there is, so the model can choose generate_image itself
// (sahuaja3669 on X, 11-18: a router mustn't fill its answer with
// a tool of a near name that does something else).
func TestHubFindNothingClose(t *testing.T) {
ts := realHubTools()
for _, q := range []string{"send an email", "search the web", "picture of a cat", "book a flight to Tokyo", "draw an image of a cat", "translate this text to French", "it"} {
if ms := hubMatches(ts, q); len(ms) > 0 {
t.Errorf("%q matched %v", q, hubToolNames(ms))
}
text := findText(t, ts, `{"query":`+jsonString(q)+`}`)
if !strings.HasPrefix(text, "No tool was found for") || strings.Contains(text, "inputSchema") || strings.Contains(text, "__") {
t.Errorf("%q: %s", q, text)
}
for _, s := range []string{"github (5 tools: create_issue, list_issues,", "filesystem (4 tools:", "linear (3 tools:", "magpie-image (1 tool: generate_image)", "magpie-browser (1 tool: browser)"} {
if !strings.Contains(text, s) {
t.Errorf("%q: no %q in %s", q, s, text)
}
}
}
for q, want := range map[string]string{
"generate an image": "magpie-image__generate_image",
"open a page in the browser": "magpie-browser__browser",
"read a file": "filesystem__read_file",
"create a GitHub issue": "github__create_issue",
"open a pull request": "github__create_pull_request",
"list my Linear issues": "linear__list_issues",
"search code": "github__search_code",
"browser": "magpie-browser__browser",
"write_file": "filesystem__write_file",
"列出": "",
} {
ms := hubMatches(ts, q)
if want == "" {
if len(ms) > 0 {
t.Errorf("%q matched %v", q, hubToolNames(ms))
}
continue
}
if len(ms) == 0 || ms[0].name != want {
t.Errorf("%q matched %v, want %s first", q, hubToolNames(ms), want)
}
}
// a match comes with its parameters, and only matches do
text := findText(t, ts, `{"query":"read a file"}`)
if !strings.Contains(text, `"filesystem__read_file"`) || strings.Contains(text, "magpie-browser") || strings.Contains(text, "linear__") {
t.Fatalf("read a file: %s", text)
}
}
func hubToolNames(ts []hubTool) []string {
out := make([]string, len(ts))
for i, t := range ts {
out[i] = t.name
}
return out
}
+149 -30
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"net/http"
"slices"
"strconv"
"strings"
"unicode"
@@ -162,48 +163,164 @@ func hubWords(s string) []string {
return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) })
}
// hubScore is how well t matches query's words: a word in its name
// counts three, in its description one, and the whole query in its name
// five more.
func hubScore(t hubTool, query string, words []string) int {
name := strings.ToLower(t.name)
desc := strings.ToLower(hubDesc(t))
n := 0
for _, w := range words {
switch {
case strings.Contains(name, w):
n += 3
case strings.Contains(desc, w):
n++
// hubStop are words of a query that say nothing of what a tool does.
var hubStop = map[string]bool{
"a": true, "an": true, "the": true, "of": true, "to": true, "for": true, "in": true, "on": true, "at": true,
"by": true, "with": true, "and": true, "or": true, "from": true, "into": true, "is": true, "are": true, "be": true,
"it": true, "its": true, "this": true, "that": true, "my": true, "me": true, "i": true, "you": true, "your": true,
"some": true, "please": true, "tool": true, "tools": true, "can": true, "do": true, "how": true, "what": true,
}
// hubKeyWords are query's words that say what is wanted: hubWords but
// the stop words and single letters, each once.
func hubKeyWords(query string) []string {
var out []string
for _, w := range hubWords(query) {
if hubStop[w] || len(w) < 2 || slices.Contains(out, w) {
continue
}
out = append(out, w)
}
return out
}
// hubWordIn is whether w is one of words, or, for a word of four letters
// or more, the start of one (repo is repository's, open is opens'), or one
// of four letters or more is w's start (issues has issue). A word not in
// ASCII (Chinese has no spaces between words) is anywhere in text.
func hubWordIn(w string, words []string, text string) bool {
for _, r := range w {
if r > unicode.MaxASCII {
return strings.Contains(text, w)
}
}
if q := strings.ToLower(strings.TrimSpace(query)); q != "" && n > 0 && (strings.Contains(name, q) || strings.EqualFold(t.Tool, q)) {
n += 5
for _, x := range words {
if x == w || len(w) >= 4 && strings.HasPrefix(x, w) || len(x) >= 4 && strings.HasPrefix(w, x) {
return true
}
}
return false
}
// hubMatch is how well t matches query: how many of its key words are in
// t's router name (in names) and how many more in its description only.
// exact is the query being t's name, or its own.
type hubMatch struct {
t hubTool
names, descs int
exact bool
}
// hubMatchOf is t's hubMatch for query, with keys its key words.
func hubMatchOf(t hubTool, query string, keys []string) hubMatch {
m := hubMatch{t: t}
q := strings.TrimSpace(query)
m.exact = q != "" && (strings.EqualFold(t.name, q) || strings.EqualFold(t.Tool, q))
name := strings.ToLower(t.name)
desc := strings.ToLower(hubDesc(t))
nw, dw := hubWords(name), hubWords(desc)
for _, w := range keys {
switch {
case hubWordIn(w, nw, name):
m.names++
case hubWordIn(w, dw, desc):
m.descs++
}
}
return m
}
// clears is whether m is a match at all (sahuaja3669 on X, 11-18: a
// router mustn't hand over a tool of a near name that does something
// else): the query is its name, or it has at least two thirds of the
// key words, one of them in its name unless it has them all. A word or
// two of a longer ask, in a description, is not what was asked for.
func (m hubMatch) clears(keys int) bool {
if m.exact {
return true
}
got := m.names + m.descs
return keys > 0 && got*3 >= keys*2 && (m.names > 0 || got == keys)
}
// score orders the matches: the query as a name first, then a word in
// the name counting three and in the description one.
func (m hubMatch) score() int {
n := 3*m.names + m.descs
if m.exact {
n += 100
}
return n
}
// hubMatches are ts best matching query first, those that don't left out.
// hubMatches are ts that match query (hubMatch.clears), best first: none
// when no tool does what it asks.
func hubMatches(ts []hubTool, query string) []hubTool {
words := hubWords(query)
type scored struct {
t hubTool
n int
}
var out []scored
keys := hubKeyWords(query)
var out []hubMatch
for _, t := range ts {
if n := hubScore(t, query, words); n > 0 {
out = append(out, scored{t, n})
if m := hubMatchOf(t, query, keys); m.clears(len(keys)) {
out = append(out, m)
}
}
slices.SortStableFunc(out, func(a, b scored) int { return cmp.Compare(b.n, a.n) })
slices.SortStableFunc(out, func(a, b hubMatch) int { return cmp.Compare(b.score(), a.score()) })
ms := make([]hubTool, len(out))
for i, s := range out {
ms[i] = s.t
for i, m := range out {
ms[i] = m.t
}
return ms
}
// hubNear are ts whose names share a word with name, most first: the
// tools a mistyped name (create_isue) may have meant.
func hubNear(ts []hubTool, name string) []hubTool {
keys := hubKeyWords(name)
var out []hubMatch
for _, t := range ts {
m := hubMatchOf(t, name, keys)
if m.descs = 0; m.names > 0 {
out = append(out, m)
}
}
slices.SortStableFunc(out, func(a, b hubMatch) int { return cmp.Compare(b.score(), a.score()) })
ms := make([]hubTool, len(out))
for i, m := range out {
ms[i] = m.t
}
return ms
}
// hubServersSaid is the most tools hubServerCounts names of a server.
const hubServersSaid = 8
// hubServerCounts name ts' servers, in their order, each with how many
// tools it has and the first hubServersSaid of their own names: what
// there is, said as what there is and not as a match.
func hubServerCounts(ts []hubTool) string {
var names []string
of := map[string][]string{}
for _, t := range ts {
if of[t.Server] == nil {
names = append(names, t.Server)
}
of[t.Server] = append(of[t.Server], t.Tool)
}
parts := make([]string, len(names))
for i, s := range names {
tools := of[s]
n := strconv.Itoa(len(tools)) + " tools"
if len(tools) == 1 {
n = "1 tool"
}
said := strings.Join(tools[:min(len(tools), hubServersSaid)], ", ")
if len(tools) > hubServersSaid {
said += ", …"
}
parts[i] = s + " (" + n + ": " + said + ")"
}
return strings.Join(parts, "; ")
}
// hubOfServer are ts of the server named server, as the user or the hub
// names it, in any case; "" is every tool.
func hubOfServer(ts []hubTool, server string) []hubTool {
@@ -235,7 +352,8 @@ func hubNameLines(ts []hubTool) string {
}
// hubFind answers find_tools: the matches with their parameters, then
// more by name; with no query, or none matching, every tool by name.
// more by name; with no query every tool by name, and with none matching
// that no tool was found, and the servers.
func hubFind(ts []hubTool, args json.RawMessage, where string) any {
var p struct {
Query string `json:"query"`
@@ -254,7 +372,8 @@ func hubFind(ts []hubTool, args json.RawMessage, where string) any {
}
ms := hubMatches(ts, p.Query)
if len(ms) == 0 {
return toolResult("No tool matches \""+p.Query+"\". Every tool, by name:\n"+hubNameLines(ts), false)
return toolResult("No tool was found for \""+p.Query+"\": no tool's name or description has what it asks. Don't call a tool that only sounds close. "+
"The servers and their tools: "+hubServerCounts(ts)+". "+hubFindTool+" with other words, a server or a tool's name looks again.", false)
}
full := ms[:min(len(ms), hubFindFull)]
specs := make([]any, 0, len(full))
@@ -325,7 +444,7 @@ func (s *Server) hubCallByName(r *http.Request, agent string, ts []hubTool, args
t, ok := hubCallNamed(r.Context(), ts, agent, name)
if !ok {
why := "No tool is called " + name + "."
if ms := hubMatches(ts, name); len(ms) > 0 {
if ms := hubNear(ts, name); len(ms) > 0 {
why += " Close to it:\n" + hubNameLines(ms[:min(len(ms), hubFindFull)])
} else {
why += " " + hubFindTool + " gives the tools' names."