router: find_tools finds tools for a query in Chinese, and names every tool when none matches (Passings_z on X)
Passings_z asked on X (tweet 2123227759409586219) why, with the MCP router's tools on demand, some tools never get used. An agent given find_tools and call_tool that asks in Chinese found none of the tools there were: - hubWords split only at characters that aren't letters or digits, so 帮我截个图 was one word, and hubWordIn looked for it whole in the description, which an English one never has. - hubMatch.clears needs two thirds of the query's key words, so 截图 screenshot failed on a tool named screenshot too: 截图 counted against it. - With nothing matched, the reply named 8 tools a server, so a model had no way to the rest. Now: - hubWords also cuts where a spaceless script (Han, kana, Hangul) meets another (截图screenshot is 截图 and screenshot). A spaceless word is cut at characters that say nothing of a tool (hubStopRunes: 我 帮 个 を …), each piece a key word (帮我截个图 is 截 and 图), found in a text when it is one character there or at least half of its two-character runs are (hubPhraseIn). - Key words are matched against the tool's router name, its server's own name (a server named in Chinese) and its description. - A key word with letters not in ASCII counts only for a tool whose name, server or description has such letters, so 截图 screenshot is screenshot to an English tool. An English query matches what it did. - No match names every tool of each server when that fits in hubSayMax (2000 characters), else 8 a server and that find_tools with an empty query names every tool. A query not in ASCII when no tool has such letters is told the tools are named and described in English. Siblings: hubNear (call_tool's close names) shares hubKeyWords and hubMatchOf, so it takes the same words. The GUI's searches are substring filters (includes), not this tokenizer; nothing to change. find_tools' and call_tool's descriptions and the instructions, the text that goes to the vendor, are unchanged. docs/subsystems/mcp-router.md: Tools on demand says the new matching and the no-match reply. Tests (internal/gateway/hub_find_cjk_test.go): - TestHubFindInChinese: 截图 screenshot, 截图screenshot, 帮我截个图, 截取屏幕, 发消息到群聊, 截屏 (a server named 截屏工具) find their tool first, and not each other's. - TestHubFindNotFoundNamesEveryTool: all 12 of a server named, the English hint, and past the budget the empty-query hint. - TestHubFindEnglishAsBefore: 30 English queries match exactly what they matched at14b6b9555. Run: - Old code (14b6b9555with the new test file, on mica): TestHubFindInChinese FAIL ("截图 screenshot" matched [], "帮我截个图" matched [], 6 of 8), TestHubFindNotFoundNamesEveryTool FAIL (not every tool, no English hint, no empty-query hint), TestHubFindEnglishAsBefore PASS (as it should). New code, at base14b6b9555, on mica (mote's load was over 18): gofmt -l prints nothing; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok. HOME=<temp> go test -tags nogui -timeout 45m ./...: every package ok but agent, dirent, gateway and gui. Each red rerun on mica at the new code and at14b6b9555: - internal/dirent watch tests: red at both (#7031). - TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes: red 3 of 3 at both (#7117). - gateway doneHold.serve "close of closed channel" panic (continuation_test.go:781): #6505, #6690; not seen on the rerun. - TestWSLAgentFolderIsALink (#7150) and TestGatewayModeListsNoOwnSessions (#7064): pass on the rerun at both. The new hub tests and every Hub/HubMCP/HubFind test pass. - Rebased on origin/main7d5db0f29(cli plugin hosts, update hint; no file in common): go build, go vet ./... and go test ./internal/gateway -run 'Hub' run again there: build ok, vet ok, gateway Hub tests ok. - Not tried: a real agent without its own tool search (e.g. OpenCode, Kimi) asking the router in Chinese end to end; the queries tested are my own phrasings against real servers' English descriptions plus invented Chinese ones, not the reporter's own tool list.
This commit is contained in:
@@ -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?}` 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` |
|
||||
| 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, its server's name or its description, or the start of one at four letters or more (open is opens', issues has issue; `hubWordIn`). Chinese, Japanese and Korean have no spaces between words (`hubSpaceless`), so `hubWords` also cuts where such a script meets another (截图screenshot is 截图 and screenshot), and such a word is cut at characters that say nothing of a tool (`hubStopRunes`: 我, 帮, 个, を, …; 帮我截个图 is 截 and 图, `hubSpacelessKeys`), each piece a key word found in a text when it is one character there, or at least half of its two-character runs are (`hubPhraseIn`: 发送飞书消息 has 发送, 飞书 and 消息); another word not in ASCII is anywhere in it. A word not in ASCII counts only for a tool whose name, server or description has a letter not in ASCII (`hubMatchOf`), so 截图 screenshot is screenshot to a tool described in English (Passings_z on X, 11-19: before, 帮我截个图 was one word looked for whole, and 截图 screenshot needed both words, so an agent asking in Chinese found none of the tools there were). A tool is a match only when the query is its name, or it has at least two thirds of the key words that count for it, 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). An English query matches as before (`TestHubFindEnglishAsBefore`). 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 every one of its tools, as what there is, not as matches; past `hubSayMax` (2000 characters) the first 8 of each server's, and that `find_tools` with an empty query names every tool (`hubServerCounts`, `hubNotFound`). A query with letters not in ASCII when no tool has any is told the tools are named and described in English, to look again in English words. 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) |
|
||||
@@ -54,7 +54,7 @@ The gateway can't import the library (the library imports the gateway), so the g
|
||||
go test -tags nogui ./internal/gui -run 'TestHubOpen|TestHubNote|TestHubAllTools'
|
||||
go test -tags nogui ./internal/library -run 'TestHub|TestRunDirect|TestFakeMCPServer|TestCheck|TestPluginTools|TestRemoteMagpieRouter|TestRemoteMagpieMCP|TestCarriedServerIsNoBridge'
|
||||
go test -tags nogui ./internal/settings -run TestRouterNote
|
||||
go test -tags nogui ./internal/gateway -run 'HubMCP|OwnMCPRejects|TestHubLeavesRemoteRouterToARouter|TestInfoSaysMCPHub' -timeout 45m
|
||||
go test -tags nogui ./internal/gateway -run 'HubMCP|HubFind|OwnMCPRejects|TestHubLeavesRemoteRouterToARouter|TestInfoSaysMCPHub' -timeout 45m
|
||||
go test -tags nogui ./internal/provider -run 'TestRemoteHubNoted|TestRemoteSelf'
|
||||
go test -tags nogui ./internal/cli -run TestLibraryMCPHub
|
||||
node --test internal/gui/tests/library-mcp-hub.test.cjs internal/gui/tests/mcp-hub-direct.test.cjs internal/gui/tests/library-mcp-router-note.test.cjs internal/gui/tests/library-mcp-router-tools.test.cjs
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// cjkHubTools are realHubTools with more: a screenshot tool described in
|
||||
// English, two described in Chinese, and one of a server named in Chinese.
|
||||
func cjkHubTools() []hubTool {
|
||||
var ts []HubTool
|
||||
for _, t := range realHubTools() {
|
||||
ts = append(ts, t.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("puppeteer", "puppeteer_screenshot", "Take a screenshot of the current page or a specific element.")
|
||||
add("desktop", "snap", "截取当前屏幕或窗口的截图,保存为 PNG 文件。")
|
||||
add("feishu", "send_message", "发送飞书消息到群聊或个人。")
|
||||
add("截屏工具", "capture", "Capture the whole screen as a PNG.")
|
||||
return hubNamed(ts)
|
||||
}
|
||||
|
||||
// An agent that works in Chinese finds the tools there are (Passings_z on
|
||||
// X, 11-19). Chinese has no spaces, so 帮我截个图 was one word, looked for
|
||||
// whole in English descriptions, and a query of 截图 and screenshot needed
|
||||
// both, so nothing ever matched. A word in Chinese now counts only for a
|
||||
// tool with such letters, and is matched as pieces of it.
|
||||
func TestHubFindInChinese(t *testing.T) {
|
||||
ts := cjkHubTools()
|
||||
for q, want := range map[string]string{
|
||||
"截图 screenshot": "puppeteer__puppeteer_screenshot",
|
||||
"截图screenshot": "puppeteer__puppeteer_screenshot",
|
||||
"take a screenshot 截图": "puppeteer__puppeteer_screenshot",
|
||||
"帮我截个图": "desktop__snap",
|
||||
"截取屏幕": "desktop__snap",
|
||||
"发送飞书消息": "feishu__send_message",
|
||||
"发消息到群聊": "feishu__send_message",
|
||||
"截屏": "截屏工具/capture",
|
||||
} {
|
||||
ms := hubMatches(ts, q)
|
||||
if len(ms) == 0 || ms[0].name != want && ms[0].Server+"/"+ms[0].Tool != want {
|
||||
t.Errorf("%q matched %v, want %s first", q, hubToolNames(ms), want)
|
||||
}
|
||||
}
|
||||
for q, not := range map[string]string{
|
||||
"发送飞书消息": "desktop__snap",
|
||||
"帮我截个图": "feishu__send_message",
|
||||
"截图": "github__create_issue",
|
||||
} {
|
||||
if ms := hubMatches(ts, q); slices.ContainsFunc(ms, func(t hubTool) bool { return t.name == not }) {
|
||||
t.Errorf("%q matched %v", q, hubToolNames(ms))
|
||||
}
|
||||
}
|
||||
// the match comes with its parameters
|
||||
if text := findText(t, ts, `{"query":"截图 screenshot"}`); !strings.Contains(text, `"puppeteer__puppeteer_screenshot"`) || strings.HasPrefix(text, "No tool") {
|
||||
t.Errorf("截图 screenshot: %s", text)
|
||||
}
|
||||
}
|
||||
|
||||
// A query in Chinese that no tool can match, all of them described in
|
||||
// English, says so and names every tool, so the model can look again in
|
||||
// English or pick one; naming eight of a server's, it had no way to the
|
||||
// rest.
|
||||
func TestHubFindNotFoundNamesEveryTool(t *testing.T) {
|
||||
var raw []HubTool
|
||||
for i := range 12 {
|
||||
d, _ := json.Marshal("Does thing " + fmt.Sprint(i) + ".")
|
||||
raw = append(raw, HubTool{Server: "chrome-devtools", Tool: fmt.Sprintf("tool_%d", i), Spec: map[string]json.RawMessage{"description": d}})
|
||||
}
|
||||
ts := hubNamed(raw)
|
||||
text := findText(t, ts, `{"query":"帮我截个图"}`)
|
||||
if !strings.HasPrefix(text, "No tool was found for") || !strings.Contains(text, "chrome-devtools (12 tools: tool_0,") || !strings.Contains(text, "tool_11)") || strings.Contains(text, "…") {
|
||||
t.Errorf("not every tool: %s", text)
|
||||
}
|
||||
if !strings.Contains(text, "described in English") {
|
||||
t.Errorf("no word of English: %s", text)
|
||||
}
|
||||
if text := findText(t, ts, `{"query":"send an email"}`); strings.Contains(text, "described in English") || !strings.Contains(text, "tool_11)") {
|
||||
t.Errorf("send an email: %s", text)
|
||||
}
|
||||
// too many to name: eight a server, and the way to all of them
|
||||
raw = nil
|
||||
for i := range 300 {
|
||||
d, _ := json.Marshal("Does thing.")
|
||||
raw = append(raw, HubTool{Server: "big", Tool: fmt.Sprintf("a_rather_long_tool_name_%d", i), Spec: map[string]json.RawMessage{"description": d}})
|
||||
}
|
||||
text = findText(t, hubNamed(raw), `{"query":"send an email"}`)
|
||||
if !strings.Contains(text, "big (300 tools: a_rather_long_tool_name_0,") || !strings.Contains(text, "…") || !strings.Contains(text, hubFindTool+" with an empty query names every tool") || runeLen(text) > hubSayMax+500 {
|
||||
t.Errorf("300 tools: %s", text)
|
||||
}
|
||||
}
|
||||
|
||||
// What an English query matches is what it matched before words in
|
||||
// Chinese were (results of 14b6b9555).
|
||||
func TestHubFindEnglishAsBefore(t *testing.T) {
|
||||
ts := realHubTools()
|
||||
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", "github__list_issues", "github__create_pull_request", "linear__save_issue"},
|
||||
"open a pull request": {"github__create_pull_request"},
|
||||
"list my Linear issues": {"linear__list_issues", "github__list_issues", "linear__save_issue"},
|
||||
"search code": {"github__search_code"},
|
||||
"browser": {"magpie-browser__browser"},
|
||||
"write_file": {"filesystem__write_file"},
|
||||
"issue": {"github__create_issue", "github__list_issues", "linear__save_issue", "linear__list_issues"},
|
||||
"issues": {"github__create_issue", "github__list_issues", "linear__save_issue", "linear__list_issues"},
|
||||
"search": {"github__search_code", "filesystem__search_files", "linear__search_documentation"},
|
||||
"file": {"github__get_file_contents", "filesystem__read_file", "filesystem__write_file", "filesystem__list_directory", "filesystem__search_files", "magpie-image__generate_image"},
|
||||
"list": {"github__list_issues", "filesystem__list_directory", "linear__list_issues", "magpie-browser__browser"},
|
||||
"create": {"github__create_issue", "github__create_pull_request", "filesystem__write_file", "linear__save_issue"},
|
||||
"repository": {"github__create_issue", "github__list_issues", "github__create_pull_request", "github__get_file_contents"},
|
||||
"directory listing": {"filesystem__list_directory"},
|
||||
"search files in a directory": {"filesystem__list_directory", "filesystem__search_files", "github__get_file_contents"},
|
||||
"Linear documentation": {"linear__search_documentation"},
|
||||
"screenshot": {"magpie-browser__browser"},
|
||||
"take a screenshot": {"magpie-browser__browser"},
|
||||
"github": {"github__create_issue", "github__list_issues", "github__search_code", "github__create_pull_request", "github__get_file_contents"},
|
||||
"linear": {"linear__save_issue", "linear__list_issues", "linear__search_documentation"},
|
||||
"send an email": nil,
|
||||
"create or update": {"linear__save_issue"},
|
||||
"contents of a file": {"github__get_file_contents", "filesystem__read_file", "filesystem__write_file"},
|
||||
"image": {"magpie-image__generate_image"},
|
||||
"pull request": {"github__create_pull_request"},
|
||||
"find files": {"filesystem__list_directory", "filesystem__search_files"},
|
||||
"edit images": {"magpie-image__generate_image"},
|
||||
} {
|
||||
if got := hubToolNames(hubMatches(ts, q)); !slices.Equal(got, want) && !(len(got) == 0 && len(want) == 0) {
|
||||
t.Errorf("%q matched %q, want %q", q, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -176,9 +176,39 @@ func hubDesc(t hubTool) string {
|
||||
}
|
||||
|
||||
// hubWords are s's words, lower case, split at anything not a letter or
|
||||
// digit (create_issue is create and issue).
|
||||
// digit (create_issue is create and issue), and where a script written
|
||||
// without spaces (hubSpaceless) meets one that isn't (截图screenshot is
|
||||
// 截图 and screenshot).
|
||||
func hubWords(s string) []string {
|
||||
return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) })
|
||||
var out []string
|
||||
var b strings.Builder
|
||||
spaceless := false
|
||||
for _, r := range strings.ToLower(s) {
|
||||
if !unicode.IsLetter(r) && !unicode.IsDigit(r) {
|
||||
if b.Len() > 0 {
|
||||
out = append(out, b.String())
|
||||
b.Reset()
|
||||
}
|
||||
continue
|
||||
}
|
||||
if b.Len() > 0 && hubSpaceless(r) != spaceless {
|
||||
out = append(out, b.String())
|
||||
b.Reset()
|
||||
}
|
||||
spaceless = hubSpaceless(r)
|
||||
b.WriteRune(r)
|
||||
}
|
||||
if b.Len() > 0 {
|
||||
out = append(out, b.String())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// hubSpaceless is whether r is of a script written without spaces between
|
||||
// its words: Chinese, Japanese and Korean (whose words carry their
|
||||
// particles).
|
||||
func hubSpaceless(r rune) bool {
|
||||
return unicode.In(r, unicode.Han, unicode.Hiragana, unicode.Katakana, unicode.Hangul)
|
||||
}
|
||||
|
||||
// hubStop are words of a query that say nothing of what a tool does.
|
||||
@@ -189,28 +219,94 @@ var hubStop = map[string]bool{
|
||||
"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 {
|
||||
// hubStopRunes are characters of a spaceless query that say nothing of
|
||||
// what a tool does, where hubSpacelessKeys cuts it: Chinese pronouns,
|
||||
// particles and measure words (帮我截个图 is 截 and 图), and Japanese
|
||||
// particles (スクリーンショットを撮る). Only those that seldom start or
|
||||
// end a word a tool is described with: 请 is in 请求, 地 in 地图, so
|
||||
// neither is one.
|
||||
var hubStopRunes = func() map[rune]bool {
|
||||
m := map[rune]bool{}
|
||||
for _, r := range "我你他她它们的了吗呢吧啊呀么个帮把给这那一をはがのにでとへも" {
|
||||
m[r] = true
|
||||
}
|
||||
return m
|
||||
}()
|
||||
|
||||
// hubSpacelessKeys are the key words of w, a word of a spaceless script:
|
||||
// w cut at hubStopRunes, each piece one key word (帮我截个图 is 截 and 图),
|
||||
// but a lone character that isn't Han (a kana says nothing alone).
|
||||
func hubSpacelessKeys(w string) []string {
|
||||
var out []string
|
||||
for _, w := range hubWords(query) {
|
||||
if hubStop[w] || len(w) < 2 || slices.Contains(out, w) {
|
||||
continue
|
||||
for _, piece := range strings.FieldsFunc(w, func(r rune) bool { return hubStopRunes[r] }) {
|
||||
if rs := []rune(piece); len(rs) > 1 || unicode.Is(unicode.Han, rs[0]) {
|
||||
out = append(out, piece)
|
||||
}
|
||||
out = append(out, w)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// hubPhraseIn is whether w, a key word of a spaceless script, is in text:
|
||||
// a character is, and a longer one has at least half of its runs of two
|
||||
// characters there. Its words aren't known, but 屏幕截图 and 截取屏幕 share
|
||||
// 屏幕, and of 发送飞书消息's five runs, 发送, 飞书 and 消息 are words a
|
||||
// description says and 送飞 and 书消 are not.
|
||||
func hubPhraseIn(w, text string) bool {
|
||||
rs := []rune(w)
|
||||
if len(rs) == 1 {
|
||||
return strings.Contains(text, w)
|
||||
}
|
||||
in := 0
|
||||
for i := 0; i+1 < len(rs); i++ {
|
||||
if strings.Contains(text, string(rs[i:i+2])) {
|
||||
in++
|
||||
}
|
||||
}
|
||||
return in*2 >= len(rs)-1
|
||||
}
|
||||
|
||||
// hubKeyWords are query's words that say what is wanted: hubWords but
|
||||
// the stop words and single letters, a spaceless word as
|
||||
// hubSpacelessKeys, each once.
|
||||
func hubKeyWords(query string) []string {
|
||||
var out []string
|
||||
add := func(w string) {
|
||||
if !slices.Contains(out, w) {
|
||||
out = append(out, w)
|
||||
}
|
||||
}
|
||||
for _, w := range hubWords(query) {
|
||||
if r := []rune(w); hubSpaceless(r[0]) {
|
||||
for _, k := range hubSpacelessKeys(w) {
|
||||
add(k)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if hubStop[w] || len(w) < 2 {
|
||||
continue
|
||||
}
|
||||
add(w)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// hubNonASCII is whether s has a letter not in ASCII (an em dash or a
|
||||
// curly quote in an English description isn't one).
|
||||
func hubNonASCII(s string) bool {
|
||||
return strings.IndexFunc(s, func(r rune) bool { return r > unicode.MaxASCII && unicode.IsLetter(r) }) >= 0
|
||||
}
|
||||
|
||||
// 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.
|
||||
// of four letters or more is w's start (issues has issue). A word of a
|
||||
// spaceless script is as hubPhraseIn finds it; another not in ASCII 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 hubSpaceless([]rune(w)[0]) {
|
||||
return hubPhraseIn(w, text)
|
||||
}
|
||||
if hubNonASCII(w) {
|
||||
return strings.Contains(text, w)
|
||||
}
|
||||
for _, x := range words {
|
||||
if x == w || len(w) >= 4 && strings.HasPrefix(x, w) || len(x) >= 4 && strings.HasPrefix(w, x) {
|
||||
@@ -221,23 +317,33 @@ func hubWordIn(w string, words []string, text string) bool {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// t's router name or its server's (in names) and how many more in its
|
||||
// description only, of keys, the key words that count for t.
|
||||
// exact is the query being t's name, or its own.
|
||||
type hubMatch struct {
|
||||
t hubTool
|
||||
names, descs int
|
||||
exact bool
|
||||
t hubTool
|
||||
names, descs, keys int
|
||||
exact bool
|
||||
}
|
||||
|
||||
// hubMatchOf is t's hubMatch for query, with keys its key words.
|
||||
// hubMatchOf is t's hubMatch for query, with keys its key words. A key
|
||||
// word not in ASCII counts only for a tool whose name, server or
|
||||
// description has such letters: an English description never has 截图,
|
||||
// and a query of 截图 screenshot is screenshot to it (Passings_z on X,
|
||||
// 11-19: an agent asking in Chinese found none of the tools there were).
|
||||
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)
|
||||
name := strings.ToLower(t.name + " " + t.Server)
|
||||
desc := strings.ToLower(hubDesc(t))
|
||||
nw, dw := hubWords(name), hubWords(desc)
|
||||
own := hubNonASCII(name) || hubNonASCII(desc)
|
||||
for _, w := range keys {
|
||||
if !own && hubNonASCII(w) {
|
||||
continue
|
||||
}
|
||||
m.keys++
|
||||
switch {
|
||||
case hubWordIn(w, nw, name):
|
||||
m.names++
|
||||
@@ -251,14 +357,15 @@ func hubMatchOf(t hubTool, query string, keys []string) hubMatch {
|
||||
// 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 {
|
||||
// key words that count for it, 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() bool {
|
||||
if m.exact {
|
||||
return true
|
||||
}
|
||||
got := m.names + m.descs
|
||||
return keys > 0 && got*3 >= keys*2 && (m.names > 0 || got == keys)
|
||||
return m.keys > 0 && got*3 >= m.keys*2 && (m.names > 0 || got == m.keys)
|
||||
}
|
||||
|
||||
// score orders the matches: the query as a name first, then a word in
|
||||
@@ -277,7 +384,7 @@ func hubMatches(ts []hubTool, query string) []hubTool {
|
||||
keys := hubKeyWords(query)
|
||||
var out []hubMatch
|
||||
for _, t := range ts {
|
||||
if m := hubMatchOf(t, query, keys); m.clears(len(keys)) {
|
||||
if m := hubMatchOf(t, query, keys); m.clears() {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
@@ -308,13 +415,17 @@ func hubNear(ts []hubTool, name string) []hubTool {
|
||||
return ms
|
||||
}
|
||||
|
||||
// hubServersSaid is the most tools hubServerCounts names of a server.
|
||||
// hubServersSaid is the most tools hubServerCounts names of a server
|
||||
// when naming them all would be longer than hubSayMax.
|
||||
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 {
|
||||
// tools it has and their own names: what there is, said as what there is
|
||||
// and not as a match. Every tool is named when that is hubSayMax
|
||||
// characters at most, else the first hubServersSaid of each server's, and
|
||||
// all is false. Naming only some, a model looking for one of the others
|
||||
// had no way to it (Passings_z on X, 11-19).
|
||||
func hubServerCounts(ts []hubTool) (said string, all bool) {
|
||||
var names []string
|
||||
of := map[string][]string{}
|
||||
for _, t := range ts {
|
||||
@@ -323,20 +434,48 @@ func hubServerCounts(ts []hubTool) string {
|
||||
}
|
||||
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"
|
||||
say := func(most int) (string, bool) {
|
||||
all := true
|
||||
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), most)], ", ")
|
||||
if len(tools) > most {
|
||||
said += ", …"
|
||||
all = false
|
||||
}
|
||||
parts[i] = s + " (" + n + ": " + said + ")"
|
||||
}
|
||||
said := strings.Join(tools[:min(len(tools), hubServersSaid)], ", ")
|
||||
if len(tools) > hubServersSaid {
|
||||
said += ", …"
|
||||
}
|
||||
parts[i] = s + " (" + n + ": " + said + ")"
|
||||
return strings.Join(parts, "; "), all
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
if said, all := say(len(ts)); runeLen(said) <= hubSayMax {
|
||||
return said, all
|
||||
}
|
||||
return say(hubServersSaid)
|
||||
}
|
||||
|
||||
// hubNotFound is find_tools' answer when no tool matches query: that none
|
||||
// was found, every server with its tools (hubServerCounts), and how to
|
||||
// look again; when the query has words not in ASCII and no tool has such
|
||||
// letters, that the tools are named and described in English, since a
|
||||
// query in another language can match none of them.
|
||||
func hubNotFound(ts []hubTool, query string) string {
|
||||
said, all := hubServerCounts(ts)
|
||||
out := "No tool was found for \"" + 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: " + said + ". "
|
||||
if !all {
|
||||
out += hubFindTool + " with an empty query names every tool. "
|
||||
}
|
||||
if hubNonASCII(query) && !slices.ContainsFunc(ts, func(t hubTool) bool { return hubNonASCII(t.name + " " + t.Server + " " + hubDesc(t)) }) {
|
||||
out += "The tools are named and described in English: " + hubFindTool + " with English words looks again."
|
||||
} else {
|
||||
out += hubFindTool + " with other words, a server or a tool's name looks again."
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// hubOfServer are ts of the server named server, as the user or the hub
|
||||
@@ -390,8 +529,7 @@ func hubFind(ts []hubTool, args json.RawMessage, where string) any {
|
||||
}
|
||||
ms := hubMatches(ts, p.Query)
|
||||
if len(ms) == 0 {
|
||||
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)
|
||||
return toolResult(hubNotFound(ts, p.Query), false)
|
||||
}
|
||||
full := ms[:min(len(ms), hubFindFull)]
|
||||
specs := make([]any, 0, len(full))
|
||||
|
||||
Reference in New Issue
Block a user