From 5666cb0490148921b1e8a9d9cfd70b6266b5cee7 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 6 Nov 2026 00:31:10 +0800 Subject: [PATCH] search MCP: web_search takes a count, 6 by default, 1 to 20 (treeman) The web search MCP server's web_search always gave 6 results: searchHits was both what a search API (a plugin's included) was asked for and where its pages were cut. It now takes an optional count, described in its input schema (integer, minimum 1, maximum 20, default 6). A number or a number in a string is taken, floored; below 1 is held to 1, above 20 to 20 (Brave and Tavily take no more than 20); null or a non-number is the default 6. The tool's description is unchanged, and the web_search magpie offers models on vendor requests keeps its schema (no count). The count rides the search's context (withSearchCount/searchCount), so every backend reads it: plugin search APIs by key and signed-in (the count handed to the hook and the pages cut), Tavily max_results, Brave count, Exa numResults, Firecrawl limit, DeepSeek count, Volcengine Count, You.com count (all three routes), Yuanbao Search's Cnt (the fewest of 10/20/... that covers it), SearXNG (cut only), Kimi Code's limit, GLM's search MCP and Codex's backend search (cut only, neither takes a count), WorkBuddy (its client's 5 unless more than 6 is asked). A searcher model's search is prose and has no count. Run (mote): go test -run 'Search|Codex|Kimi|GLM|WorkBuddy|Plugin' ./internal/gateway ok; -race of the new tests and TestSearchMCP* ok; go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of the package ok; gofmt -l empty. Broken by hand: searchCount ignoring the count went red in both new tests (plugin asked for 6, said 6, every vendor asked 6); withSearchCount without the clamp went red for 50, 0 and -3. Not tried: a real search API or plugin with count > 6; the full suite runs after the push. --- internal/gateway/budget_plugin_test.go | 2 +- internal/gateway/search_api.go | 73 +++++++---- internal/gateway/search_archive.go | 4 +- internal/gateway/search_codex.go | 6 +- internal/gateway/search_codex_test.go | 2 +- internal/gateway/search_count_test.go | 165 +++++++++++++++++++++++++ internal/gateway/search_glm.go | 5 +- internal/gateway/search_kimi.go | 4 +- internal/gateway/search_mcp.go | 49 +++++++- internal/gateway/search_plugin_test.go | 2 +- internal/gateway/search_signin.go | 7 +- internal/gateway/search_workbuddy.go | 10 +- 12 files changed, 283 insertions(+), 46 deletions(-) create mode 100644 internal/gateway/search_count_test.go diff --git a/internal/gateway/budget_plugin_test.go b/internal/gateway/budget_plugin_test.go index 65d171330..cf68899dc 100644 --- a/internal/gateway/budget_plugin_test.go +++ b/internal/gateway/budget_plugin_test.go @@ -44,7 +44,7 @@ func TestKeyLimitsOnAndOff(t *testing.T) { capped := access.Identity{KeyID: keys[0].ID, KeyName: "Capped", Limit: &access.Limit{Period: "day", Tokens: 700}} mcp := func() error { r := httptest.NewRequest("POST", SearchMCPPath, nil).WithContext(access.WithIdentity(t.Context(), capped)) - _, err := s.searchMCPRun(r, "latest go") + _, err := s.searchMCPRun(r, "latest go", nil) return err } diff --git a/internal/gateway/search_api.go b/internal/gateway/search_api.go index d2c26a8b1..4e0423f81 100644 --- a/internal/gateway/search_api.go +++ b/internal/gateway/search_api.go @@ -28,8 +28,30 @@ import ( // model as it came, each page's title, address and what it says, with no // model asked to read it first. -// searchHits is how many pages a search API is asked for. -const searchHits = 6 +// searchHits is how many pages a search API is asked for when the search +// names no count, and searchHitsMost the most one may name (web_search's +// count): Brave and Tavily take no more than 20. +const ( + searchHits = 6 + searchHitsMost = 20 +) + +type searchCountKey struct{} + +// withSearchCount is ctx with the search in it asking for n pages, held +// to 1 through searchHitsMost. +func withSearchCount(ctx context.Context, n int) context.Context { + return context.WithValue(ctx, searchCountKey{}, min(max(n, 1), searchHitsMost)) +} + +// searchCount is how many pages the search in ctx asks for: the count it +// named (withSearchCount), else searchHits. +func searchCount(ctx context.Context) int { + if n, ok := ctx.Value(searchCountKey{}).(int); ok { + return n + } + return searchHits +} // pageText is the most of a page's text a hit carries. const pageText = 1500 @@ -272,6 +294,7 @@ func (s *Server) askSearchAPI(ctx context.Context, a provider.SearchAPI, query s if v, ok := provider.SearchVendorOf(a.Vendor); ok && v.Plugin != "" { return s.askPluginSearch(ctx, a, v, query) } + n := searchCount(ctx) var r *http.Request var err error var sent []byte @@ -288,32 +311,32 @@ func (s *Server) askSearchAPI(ctx context.Context, a provider.SearchAPI, query s get := func(path string, q url.Values) { getAt(a.Base()+path, q) } switch a.Vendor { case "tavily": - post("/search", map[string]any{"query": query, "max_results": searchHits, "search_depth": "basic"}) + post("/search", map[string]any{"query": query, "max_results": n, "search_depth": "basic"}) case "brave": - get("/res/v1/web/search", url.Values{"q": {query}, "count": {fmt.Sprint(searchHits)}}) + get("/res/v1/web/search", url.Values{"q": {query}, "count": {fmt.Sprint(n)}}) case "exa": - post("/search", map[string]any{"query": query, "numResults": searchHits, + post("/search", map[string]any{"query": query, "numResults": n, "contents": map[string]any{"text": map[string]any{"maxCharacters": pageText}}}) case "firecrawl": - post("/v2/search", map[string]any{"query": query, "limit": searchHits}) + post("/v2/search", map[string]any{"query": query, "limit": n}) case "deepseek": // DeepSeek's Search API takes a query of 1 to 128 characters // (api-docs.deepseek.com/guides/search); its page text is its // summary, so need_content is left false - post("/v1/tools/search", map[string]any{"query": firstRunes(query, deepseekQueryMax), "count": searchHits}) + post("/v1/tools/search", map[string]any{"query": firstRunes(query, deepseekQueryMax), "count": n}) case "volcengine": // Doubao Search Custom (volcengine.com/docs/87772/2272953): a // query of 1 to 100 characters, web pages only, and only those // with a URL (NeedUrl leaves out its 火山如意 cards, which have none) post("/search_api/web_search", map[string]any{"Query": firstRunes(query, volcQueryMax), "SearchType": "web", - "Count": searchHits, "Filter": map[string]any{"NeedUrl": true}}) + "Count": n, "Filter": map[string]any{"NeedUrl": true}}) case "wsa": // Tencent Cloud's Yuanbao Search by its service API key // (cloud.tencent.com/document/product/1806/130615): Cnt is one of // 10/20/30/40/50 (cloud.tencent.com/document/api/1806/121811), and - // a smaller one is turned away, so the fewest, cut to searchHits - // below - post("/SearchPro", map[string]any{"Query": query, "Cnt": wsaCnt}) + // a smaller one is turned away, so the fewest that covers n, cut + // to n below + post("/SearchPro", map[string]any{"Query": query, "Cnt": wsaCntFor(n)}) case "searxng": get("/search", url.Values{"q": {query}, "format": {"json"}}) case "you": @@ -321,11 +344,11 @@ func (s *Server) askSearchAPI(ctx context.Context, a provider.SearchAPI, query s // at an address of the user's own when one is set switch { case a.Key != "": - post("/v1/search", map[string]any{"query": query, "count": searchHits}) + post("/v1/search", map[string]any{"query": query, "count": n}) case a.URL != "": - get("/v1/agents/search", url.Values{"query": {query}, "count": {fmt.Sprint(searchHits)}}) + get("/v1/agents/search", url.Values{"query": {query}, "count": {fmt.Sprint(n)}}) default: - getAt(provider.YouFreeSearch, url.Values{"query": {query}, "count": {fmt.Sprint(searchHits)}}) + getAt(provider.YouFreeSearch, url.Values{"query": {query}, "count": {fmt.Sprint(n)}}) } default: return nil, fmt.Errorf("magpie can't ask %q", a.Vendor) @@ -414,8 +437,8 @@ func (s *Server) askSearchAPI(ctx context.Context, a provider.SearchAPI, query s if err != nil { return nil, fmt.Errorf("unexpected reply: %w", err) } - if len(pages) > searchHits { - pages = pages[:searchHits] + if len(pages) > n { + pages = pages[:n] } return pages, nil } @@ -430,8 +453,9 @@ var runPluginSearch = plugin.RunSearch // row in the request log; and with the query apiSearch masked. What it // found is cut and cleaned as a built-in's pages are. func (s *Server) askPluginSearch(ctx context.Context, a provider.SearchAPI, v provider.SearchVendor, query string) ([]foundPage, error) { - got, err := runPluginSearch(ctx, v.Plugin, v.PluginID, query, searchHits, a.Key, a.Base()) - notePluginSearch(ctx, v.Plugin, pluginSearchAsked(v, query, a.Base(), a.Key, ""), got, err) + n := searchCount(ctx) + got, err := runPluginSearch(ctx, v.Plugin, v.PluginID, query, n, a.Key, a.Base()) + notePluginSearch(ctx, v.Plugin, pluginSearchAsked(v, query, n, a.Base(), a.Key, ""), got, err) if err != nil { var r plugin.SearchRefused if errors.As(err, &r) { @@ -452,12 +476,12 @@ func (s *Server) askPluginSearch(ctx context.Context, a provider.SearchAPI, v pr } return nil, err } - return pluginPages(got), nil + return pluginPages(got, n), nil } // pluginPages are the pages a plugin's search found, cut and cleaned as a -// built-in's are. -func pluginPages(got []plugin.SearchPage) []foundPage { +// built-in's are, at most n. +func pluginPages(got []plugin.SearchPage, n int) []foundPage { var pages []foundPage for _, r := range got { if r.URL == "" { @@ -468,7 +492,7 @@ func pluginPages(got []plugin.SearchPage) []foundPage { title = r.URL } pages = append(pages, foundPage{Title: title, URL: r.URL, Text: clipText(searchPlain(r.Text), pageText), Age: r.Age}) - if len(pages) == searchHits { + if len(pages) == n { break } } @@ -629,8 +653,9 @@ func readVolcSearch(b []byte) ([]foundPage, error) { return pages, nil } -// wsaCnt is the Cnt Yuanbao Search is asked for: the fewest it takes. -const wsaCnt = 10 +// wsaCntFor is the Cnt Yuanbao Search is asked for to find n pages: the +// fewest of the 10/20/30/40/50 it takes that covers n. +func wsaCntFor(n int) int { return min(max((n+9)/10*10, 10), 50) } // wsaSearchError is the status a Yuanbao Search (Tencent Cloud) reply // stands for, and its error's words. Tencent Cloud answers 200 whenever diff --git a/internal/gateway/search_archive.go b/internal/gateway/search_archive.go index 578194b94..78a48ad5a 100644 --- a/internal/gateway/search_archive.go +++ b/internal/gateway/search_archive.go @@ -128,8 +128,8 @@ func notePluginSearch(ctx context.Context, spec string, asked map[string]any, go // pluginSearchAsked is what magpie hands a plugin's search hook, as its // archive says it: the provider, the query, how many pages, the address // set (when one is) and the key masked or the account it signs in as. -func pluginSearchAsked(v provider.SearchVendor, query, at, key, account string) map[string]any { - m := map[string]any{"hook": "search", "provider": v.PluginID, "query": query, "count": searchHits} +func pluginSearchAsked(v provider.SearchVendor, query string, count int, at, key, account string) map[string]any { + m := map[string]any{"hook": "search", "provider": v.PluginID, "query": query, "count": count} if at != "" { m["url"] = at } diff --git a/internal/gateway/search_codex.go b/internal/gateway/search_codex.go index 5bd0a05e6..88bd8b7c5 100644 --- a/internal/gateway/search_codex.go +++ b/internal/gateway/search_codex.go @@ -160,7 +160,7 @@ func (s *Server) codexSearch(ctx context.Context, p provider.Provider, query str if err := json.Unmarshal(b, &out); err != nil || out.Output == nil { return "", nil, fmt.Errorf("%sunexpected reply: %s", who, provider.APIError(b, res.Status)) } - pages := codexPages(*out.Output, out) + pages := codexPages(*out.Output, out, searchCount(ctx)) if len(pages) == 0 { return "", nil, fmt.Errorf("%s%w", who, errFoundNothing) } @@ -174,7 +174,7 @@ func (s *Server) codexSearch(ctx context.Context, p provider.Provider, query str // then what the page says, and a rule of 80 dashes before the next. The // results name each page's title and address by its ref_id, which the // mark carries. -func codexPages(output string, out codexSearchReply) []foundPage { +func codexPages(output string, out codexSearchReply, n int) []foundPage { type result struct{ title, url, snippet string } byRef := map[string]result{} for _, x := range out.Results { @@ -217,7 +217,7 @@ func codexPages(output string, out codexSearchReply) []foundPage { title = link } pages = append(pages, foundPage{Title: title, URL: link, Text: clipText(searchPlain(strings.Map(dropPrivateUse, text)), pageText)}) - if len(pages) == searchHits { + if len(pages) == n { break } } diff --git a/internal/gateway/search_codex_test.go b/internal/gateway/search_codex_test.go index 24a06f804..bda33ab07 100644 --- a/internal/gateway/search_codex_test.go +++ b/internal/gateway/search_codex_test.go @@ -207,7 +207,7 @@ func TestCodexPagesRead(t *testing.T) { "Bare (https://example.com/a)\njust text" var reply codexSearchReply json.Unmarshal([]byte(`{"results":[{"ref_id":"turn0search0","title":"The Go Programming Language","url":"https://go.dev/"}]}`), &reply) - pages := codexPages(out, reply) + pages := codexPages(out, reply, searchHits) if len(pages) != 2 || pages[0].Title != "The Go Programming Language" || pages[0].URL != "https://go.dev/" || !strings.Contains(pages[0].Text, "Build simple software.") || strings.Contains(pages[0].Text, "wordlim") || pages[1].URL != "https://example.com/a" || pages[1].Text != "just text" { diff --git a/internal/gateway/search_count_test.go b/internal/gateway/search_count_test.go new file mode 100644 index 000000000..5f1ad3123 --- /dev/null +++ b/internal/gateway/search_count_test.go @@ -0,0 +1,165 @@ +package gateway + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" +) + +// web_search on the MCP server takes a count (treeman on Discord): how +// many results, 6 when not given, held to 1 through 20. The plugin's +// search API is asked for that many and the tool says that many, though +// the API found more. +func TestSearchMCPCount(t *testing.T) { + fresh(t) + const spec = "@acme/opencode-mojeek-search@1.0.0" + plugged(t, spec, false) + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "mojeek-search:mojeek", Key: "good-key-0003"}); err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var counts []int + old := runPluginSearch + t.Cleanup(func() { runPluginSearch = old }) + runPluginSearch = func(_ context.Context, _, _, _ string, count int, _, _ string) ([]plugin.SearchPage, error) { + mu.Lock() + counts = append(counts, count) + mu.Unlock() + var pages []plugin.SearchPage + for i := range 30 { // more than any count, as an API may give + pages = append(pages, plugin.SearchPage{Title: fmt.Sprint("page ", i), URL: fmt.Sprintf("https://ex.test/%d", i), Text: "text"}) + } + return pages, nil + } + h := lanGuard(New().Handler()) + const here = "127.0.0.1:50000" + + var list struct { + Result struct { + Tools []struct { + Name string + InputSchema struct { + Properties map[string]struct { + Type string + Minimum, Maximum int + Default int + } + Required []string + } + } + } + } + if err := json.Unmarshal(mcpPost(h, here, `{"jsonrpc":"2.0","id":2,"method":"tools/list"}`).Body.Bytes(), &list); err != nil { + t.Fatal(err) + } + c := list.Result.Tools[0].InputSchema.Properties["count"] + if list.Result.Tools[0].Name != "web_search" || c.Type != "integer" || c.Minimum != 1 || c.Maximum != 20 || c.Default != 6 || + len(list.Result.Tools[0].InputSchema.Required) != 1 { + t.Fatalf("web_search's schema: %+v", list.Result.Tools[0]) + } + + for _, tc := range []struct { + arg string // the count as the call writes it, "" for none + want int + }{ + {"", 6}, + {`12`, 12}, + {`20`, 20}, + {`50`, 20}, + {`0`, 1}, + {`-3`, 1}, + {`"8"`, 8}, + {`9.7`, 9}, + {`"many"`, 6}, + {`null`, 6}, + } { + args := `{"query":"latest go"}` + if tc.arg != "" { + args = `{"query":"latest go","count":` + tc.arg + `}` + } + mu.Lock() + counts = nil + mu.Unlock() + m := readMCP(t, mcpPost(h, here, `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"web_search","arguments":`+args+`}}`)) + if m.Error != nil || m.Result.IsError || len(m.Result.Content) != 1 { + t.Fatalf("count %s: %+v", tc.arg, m) + } + said := m.Result.Content[0].Text + if n := strings.Count(said, " — https://ex.test/"); n != tc.want { + t.Errorf("count %s: said %d results, want %d", tc.arg, n, tc.want) + } + mu.Lock() + if len(counts) != 1 || counts[0] != tc.want { + t.Errorf("count %s: the plugin was asked for %v, want %d", tc.arg, counts, tc.want) + } + mu.Unlock() + } +} + +// Every built-in search API, and a Kimi Code plan's search service, is +// asked for the count the search names, in its own field. +func TestSearchCountReachesEveryAPI(t *testing.T) { + fresh(t) + var mu sync.Mutex + var last string + f := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + last = r.URL.RawQuery + " " + string(b) + mu.Unlock() + io.WriteString(w, `{}`) + })) + t.Cleanup(f.Close) + s := New() + ctx := withSearchCount(context.Background(), 12) + for _, c := range []struct{ vendor, want string }{ + {"tavily", `"max_results":12`}, + {"brave", "count=12"}, + {"exa", `"numResults":12`}, + {"firecrawl", `"limit":12`}, + {"deepseek", `"count":12`}, + {"volcengine", `"Count":12`}, + {"wsa", `"Cnt":20`}, + {"you", `"count":12`}, + } { + s.askSearchAPI(ctx, provider.SearchAPI{Vendor: c.vendor, Key: "k", URL: f.URL}, "latest go") + mu.Lock() + if !strings.Contains(last, c.want) { + t.Errorf("%s was asked %q, not %s", c.vendor, last, c.want) + } + mu.Unlock() + } + s.askSearchAPI(withSearchCount(context.Background(), 3), provider.SearchAPI{Vendor: "wsa", Key: "k", URL: f.URL}, "q") + mu.Lock() + if !strings.Contains(last, `"Cnt":10`) { + t.Errorf("Yuanbao Search for 3 was asked %q, not its fewest, 10", last) + } + mu.Unlock() + + kimi := newKimiPlan(t) + plan := provider.Provider{ID: "kimi", Name: "Kimi Code", Preset: "kimi-code-cn", Key: "sk-kimi", + Chat: kimi.URL + "/coding/v1", Models: []string{"kimi-for-coding"}} + for _, n := range []int{0, 12} { + ctx := context.Background() + want := "| 6,false,30" + if n > 0 { + ctx, want = withSearchCount(ctx, n), fmt.Sprint("| ", n, ",false,30") + } + s.kimiSearch(ctx, plan, "latest go") + kimi.mu.Lock() + got := kimi.searched[len(kimi.searched)-1] + kimi.mu.Unlock() + if !strings.HasSuffix(got, want) { + t.Errorf("Kimi Code's search asked %q, want limit %d", got, n) + } + } +} diff --git a/internal/gateway/search_glm.go b/internal/gateway/search_glm.go index 92ddc9ce7..759e1e430 100644 --- a/internal/gateway/search_glm.go +++ b/internal/gateway/search_glm.go @@ -120,10 +120,11 @@ func (s *Server) glmSearchKey(ctx context.Context, p provider.Provider, query st return nil, errors.New(c.masked(clipText(cmp.Or(strings.Join(texts, " "), "the search tool failed"), 500))) } var pages []foundPage + n := searchCount(ctx) for _, t := range texts { pages = append(pages, readGLMSearch(t)...) - if len(pages) >= searchHits { - pages = pages[:searchHits] + if len(pages) >= n { + pages = pages[:n] break } } diff --git a/internal/gateway/search_kimi.go b/internal/gateway/search_kimi.go index 72b5c0b4d..a3e08e15e 100644 --- a/internal/gateway/search_kimi.go +++ b/internal/gateway/search_kimi.go @@ -137,7 +137,7 @@ func (s *Server) kimiSearch(ctx context.Context, p provider.Provider, query stri if err != nil { return "", nil, err } - body, _ := json.Marshal(map[string]any{"text_query": q, "limit": searchHits, "enable_page_crawling": false, "timeout_seconds": 30}) + body, _ := json.Marshal(map[string]any{"text_query": q, "limit": searchCount(ctx), "enable_page_crawling": false, "timeout_seconds": 30}) r, err := http.NewRequestWithContext(ctx, http.MethodPost, provider.KimiCodeSearch(p), bytes.NewReader(body)) if err != nil { return "", nil, err @@ -188,7 +188,7 @@ func (s *Server) kimiSearch(ctx context.Context, p provider.Provider, query stri text = x.Snippet } pages = append(pages, foundPage{Title: title, URL: x.URL, Text: clipText(searchPlain(text), pageText), Age: x.Date}) - if len(pages) == searchHits { + if len(pages) == searchCount(ctx) { break } } diff --git a/internal/gateway/search_mcp.go b/internal/gateway/search_mcp.go index 2c2b9aa28..d1ba7fa29 100644 --- a/internal/gateway/search_mcp.go +++ b/internal/gateway/search_mcp.go @@ -5,10 +5,13 @@ import ( "context" "encoding/json" "errors" + "fmt" "io" "log" + "math" "net/http" "slices" + "strconv" "strings" "github.com/yetone/magpie/internal/access" @@ -45,6 +48,37 @@ var searchMCPVersions = []string{"2025-06-18", "2025-03-26", "2024-11-05"} const searchMCPTool = "web_search" +// searchMCPSchema is web_search's input: the query, and how many results +// (searchHits when not given, held to 1 through searchHitsMost). +var searchMCPSchema = fmt.Sprintf(`{"type":"object","properties":{"query":{"type":"string","description":"What to search for"},`+ + `"count":{"type":"integer","minimum":1,"maximum":%d,"default":%d,"description":"How many results to return, 1 to %d (%d when not given)"}},"required":["query"]}`, + searchHitsMost, searchHits, searchHitsMost, searchHits) + +// searchCountArg is the count a web_search call names: a number, or a +// number in a string, as a model may write it; nil when it names none, or +// something that isn't a number, which is searched for as if not given. +func searchCountArg(raw json.RawMessage) *int { + if t := bytes.TrimSpace(raw); len(t) == 0 || bytes.Equal(t, []byte("null")) { + return nil + } + var f float64 + if json.Unmarshal(raw, &f) != nil { + var s string + if json.Unmarshal(raw, &s) != nil { + return nil + } + var err error + if f, err = strconv.ParseFloat(strings.TrimSpace(s), 64); err != nil { + return nil + } + } + if math.IsNaN(f) || math.IsInf(f, 0) { + return nil + } + n := int(max(min(f, 1e6), -1e6)) + return &n +} + type mcpMessage struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id,omitempty"` @@ -171,14 +205,15 @@ func (s *Server) searchMCPCall(r *http.Request, m mcpMessage) (any, map[string]a "name": searchMCPTool, "title": "Web search", "description": t.Description, - "inputSchema": t.Schema, + "inputSchema": json.RawMessage(searchMCPSchema), "annotations": map[string]any{"readOnlyHint": true, "openWorldHint": true}, }, fetchTool()}}, nil case "tools/call": var p struct { Name string `json:"name"` Arguments struct { - Query string `json:"query"` + Query string `json:"query"` + Count json.RawMessage `json:"count"` fetchArgs } `json:"arguments"` } @@ -189,7 +224,7 @@ func (s *Server) searchMCPCall(r *http.Request, m mcpMessage) (any, map[string]a var err error switch p.Name { case searchMCPTool: - said, err = s.searchMCPRun(r, strings.TrimSpace(p.Arguments.Query)) + said, err = s.searchMCPRun(r, strings.TrimSpace(p.Arguments.Query), searchCountArg(p.Arguments.Count)) case fetchMCPTool: said, err = s.fetchMCPRun(r, p.Arguments.fetchArgs) default: @@ -226,8 +261,9 @@ func (e searchMCPError) Error() string { return string(e) } // searchMCPRun searches for the query as a model's web_search would be: // held to the calling gateway key's limit, and named in the Routing view -// as the agent's MCP call. -func (s *Server) searchMCPRun(r *http.Request, query string) (string, error) { +// as the agent's MCP call; for count results when it is given (held to 1 +// through searchHitsMost), else searchHits. +func (s *Server) searchMCPRun(r *http.Request, query string, count *int) (string, error) { if query == "" { return "", searchMCPError("web_search needs a query") } @@ -237,6 +273,9 @@ func (s *Server) searchMCPRun(r *http.Request, query string) (string, error) { } defer release() ctx := context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, MCP: true}) + if count != nil { + ctx = withSearchCount(ctx, *count) + } said, _, err := s.webSearch(ctx, query) if err != nil { if r.Context().Err() == nil { diff --git a/internal/gateway/search_plugin_test.go b/internal/gateway/search_plugin_test.go index 453905f50..e0a6be355 100644 --- a/internal/gateway/search_plugin_test.go +++ b/internal/gateway/search_plugin_test.go @@ -61,7 +61,7 @@ func TestSearchOnAndOff(t *testing.T) { return sent } mcp := func() (string, error) { - return s.searchMCPRun(httptest.NewRequest("POST", "/mcp/search", nil), "latest go") + return s.searchMCPRun(httptest.NewRequest("POST", "/mcp/search", nil), "latest go", nil) } // on diff --git a/internal/gateway/search_signin.go b/internal/gateway/search_signin.go index 70782932c..d791a7024 100644 --- a/internal/gateway/search_signin.go +++ b/internal/gateway/search_signin.go @@ -88,8 +88,9 @@ func SearchAccountsOn(p provider.Provider) int { return len(accountsOn(p, "")) } // askPluginSearchAs is askPluginSearch as one account of the provider the // API signs in to. func (s *Server) askPluginSearchAs(ctx context.Context, v provider.SearchVendor, p provider.Provider, query string) ([]foundPage, error) { - got, err := runPluginSearchAs(ctx, v.Plugin, v.PluginID, query, searchHits, p.PluginAccountKey()) - notePluginSearch(ctx, v.Plugin, pluginSearchAsked(v, query, "", "", p.Account.User), got, err) + n := searchCount(ctx) + got, err := runPluginSearchAs(ctx, v.Plugin, v.PluginID, query, n, p.PluginAccountKey()) + notePluginSearch(ctx, v.Plugin, pluginSearchAsked(v, query, n, "", "", p.Account.User), got, err) if err != nil { var r plugin.SearchRefused if errors.As(err, &r) { @@ -103,5 +104,5 @@ func (s *Server) askPluginSearchAs(ctx context.Context, v provider.SearchVendor, } return nil, err } - return pluginPages(got), nil + return pluginPages(got, n), nil } diff --git a/internal/gateway/search_workbuddy.go b/internal/gateway/search_workbuddy.go index c34ceef75..42388393a 100644 --- a/internal/gateway/search_workbuddy.go +++ b/internal/gateway/search_workbuddy.go @@ -59,7 +59,13 @@ func (s *Server) wbSearch(ctx context.Context, p provider.Provider, query string if err != nil { return "", nil, err } - body, _ := json.Marshal(map[string]any{"query": q, "type": "text2text", "max_results": wbSearchResults}) + // as many as its client asks for, unless the search named more + n := searchCount(ctx) + ask := wbSearchResults + if n > searchHits { + ask = n + } + body, _ := json.Marshal(map[string]any{"query": q, "type": "text2text", "max_results": ask}) r, err := http.NewRequestWithContext(ctx, http.MethodPost, origin+wbSearchPath, bytes.NewReader(body)) if err != nil { return "", nil, err @@ -114,7 +120,7 @@ func (s *Server) wbSearch(ctx context.Context, p provider.Provider, query string } title := cmp.Or(searchPlain(x.Title), searchPlain(x.Site), x.URL) pages = append(pages, foundPage{Title: title, URL: x.URL, Text: clipText(searchPlain(x.Snippet), pageText)}) - if len(pages) == searchHits { + if len(pages) == n { break } }