search: web_search takes sites, recency and images; the ChatGPT backend gets them as its own fields (LBM_OASIG on X)

The web-search MCP tool gains optional allowed_domains, blocked_domains,
recency_days, images and search_context_size. Codex search (/alpha/search,
codex-rs codex-api search.rs) gets them as the fields web.run has: a
query's domains and recency, image_query for images, settings.filters,
search_context_size, image_settings. Every other searcher is asked the
sites as site:/-site: operators and ignores the rest. Image results read
as pages whose text starts "Image: <url>". Arguments travel in ctx, never
in a request body. Schema text names neither magpie nor a vendor.

Run: real Plus account, curl to /alpha/search with image_query and with
domains+recency+filters: both accepted, image reply shape recorded in
TestImageResultsReadAsPages. New tests (search_scope_test.go) use the
fake backend; go test ./internal/gateway full on mote: only the count
schema tests red (a boolean default), fixed, then -run Search|Codex|
ChatGPT|ImageResults ok; vet linux/windows clean.
Not tried: through a running sandbox magpie end to end; GUI untouched.
This commit is contained in:
yetone
2026-11-12 22:26:45 +08:00
parent 7dbfc9f2fe
commit 59c9887f65
8 changed files with 296 additions and 14 deletions
+16
View File
@@ -1955,6 +1955,22 @@ Covered by `TestVisionEffortPicked`, `TestVisionEffortOnAnthropic`,
`TestSearcherEffortPicked`, `TestSearcherEffortOnGemini`,
`TestSideEffortChecked` and `side-effort.test.cjs`.
## What the web-search MCP server's `web_search` narrows by
Beside `query` and `count`, `web_search` takes `allowed_domains`,
`blocked_domains`, `recency_days`, `images` and `search_context_size`
([`search_mcp.go`](../../internal/gateway/search_mcp.go),
[`searchopts.go`](../../internal/gateway/searchopts.go)). They travel in
ctx (`withScope`), never in a request body. The ChatGPT backend's search
(`codexSearch`) takes them as the fields Codex's web.run has (codex-rs
codex-api `search.rs`): a query's `domains` and `recency`, `image_query`
instead of `search_query` for `images`, `settings.filters`,
`settings.search_context_size` and `settings.image_settings`. Every other
searcher is asked the sites as `site:` and `-site:` operators in the query
(`searchScoped`, at the top of `webSearch`) and ignores the rest. Image
results come back as pages whose text starts "Image: <url>" (`imageSaid`).
`TestSearchScopeReachesCodexSearch`, `TestSearchScopeOperatorsForOtherSearchers`.
## How many results a search is answered with
A search asks its backend for `searchCount(ctx)` pages
+1 -1
View File
@@ -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", nil)
_, err := s.searchMCPRun(r, "latest go", nil, nil)
return err
}
+1
View File
@@ -754,6 +754,7 @@ func (s *Server) webSearch(ctx context.Context, query string) (string, []Hit, er
// is set to (#1522: Codex asked while a "direct" provider served the
// turn dialed chatgpt.com directly)
ctx = netproxy.With(ctx, "")
ctx, query = searchScoped(ctx, query)
if !searchServed() {
return "", nil, errSearchOff
}
+50 -9
View File
@@ -105,7 +105,7 @@ func (s *Server) codexSearchBy(ctx context.Context, p provider.Provider, query s
func (s *Server) codexSearch(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) {
ctx, cancel := context.WithTimeout(s.metered(p.Via(ctx), p, ""), searchTimeout/2)
defer cancel()
q, err := maskedQuery(ctx, query, &p)
q, err := maskedQuery(ctx, unscoped(ctx, query), &p)
if err != nil {
return "", nil, err
}
@@ -115,14 +115,43 @@ func (s *Server) codexSearch(ctx context.Context, p provider.Provider, query str
if model == "" {
model = "gpt-5"
}
sc := scopeOf(ctx)
query1 := map[string]any{"q": q}
settingsBody := map[string]any{
"allowed_callers": []string{"direct"},
"external_web_access": webAccess(ctx),
}
kind := "search_query"
if sc != nil {
if sc.RecencyDays > 0 {
query1["recency"] = sc.RecencyDays
}
if len(sc.Allowed) > 0 {
query1["domains"] = sc.Allowed
}
filters := map[string]any{}
if len(sc.Allowed) > 0 {
filters["allowed_domains"] = sc.Allowed
}
if len(sc.Blocked) > 0 {
filters["blocked_domains"] = sc.Blocked
}
if len(filters) > 0 {
settingsBody["filters"] = filters
}
if sc.Size != "" {
settingsBody["search_context_size"] = sc.Size
}
if sc.Images {
kind = "image_query"
settingsBody["image_settings"] = map[string]any{"max_results": searchCount(ctx), "caption": true}
}
}
body, _ := json.Marshal(map[string]any{
"id": newUUID(),
"model": model,
"commands": map[string]any{"search_query": []map[string]any{{"q": q}}},
"settings": map[string]any{
"allowed_callers": []string{"direct"},
"external_web_access": webAccess(ctx),
},
"id": newUUID(),
"model": model,
"commands": map[string]any{kind: []map[string]any{query1}},
"settings": settingsBody,
"max_output_tokens": codexSearchBudget,
})
who := p.Name + ": "
@@ -202,7 +231,7 @@ func codexPages(output string, out codexSearchReply, n int) []foundPage {
rest = after
}
}
text := rest
text := imageSaid(rest)
if r, ok := byRef[ref]; ok {
title, link = cmp.Or(strings.TrimSpace(r.title), title), r.url
if strings.TrimSpace(text) == "" {
@@ -232,3 +261,15 @@ func dropPrivateUse(r rune) rune {
}
return r
}
// imageSaid sets an image result's text out: the backend gives it as
// "Image URL: <url># <caption>" with no break between the two.
func imageSaid(text string) string {
t := strings.TrimSpace(text)
u, ok := strings.CutPrefix(t, "Image URL:")
if !ok {
return text
}
img, caption, _ := strings.Cut(strings.TrimSpace(u), "# ")
return strings.TrimSpace("Image: " + strings.TrimSpace(img) + "\n" + strings.TrimSpace(caption))
}
+6 -3
View File
@@ -55,7 +55,8 @@ const searchMCPTool = "web_search"
// set (settings.SearchPages).
func searchMCPSchema(n int) string {
return 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"]}`,
`"count":{"type":"integer","minimum":1,"maximum":%d,"default":%d,"description":"How many results to return, 1 to %d (%d when not given)"},`+
searchScopeSchema+`},"required":["query"]}`,
searchHitsMost, n, searchHitsMost, n)
}
@@ -230,6 +231,7 @@ func (s *Server) searchMCPCall(r *http.Request, m mcpMessage) (any, map[string]a
Arguments struct {
Query string `json:"query"`
Count json.RawMessage `json:"count"`
searchArgs
fetchArgs
} `json:"arguments"`
}
@@ -240,7 +242,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), searchCountArg(p.Arguments.Count))
said, err = s.searchMCPRun(r, strings.TrimSpace(p.Arguments.Query), searchCountArg(p.Arguments.Count), p.Arguments.searchArgs.scope())
case fetchMCPTool:
said, err = s.fetchMCPRun(r, p.Arguments.fetchArgs)
default:
@@ -279,7 +281,7 @@ func (e searchMCPError) Error() string { return string(e) }
// held to the calling gateway key's limit, and named in the Routing view
// as the agent's MCP call; for count results when it is given (held to 1
// through searchHitsMost), else the count the user set (searchCount).
func (s *Server) searchMCPRun(r *http.Request, query string, count *int) (string, error) {
func (s *Server) searchMCPRun(r *http.Request, query string, count *int, scope *searchScope) (string, error) {
if query == "" {
return "", searchMCPError("web_search needs a query")
}
@@ -292,6 +294,7 @@ func (s *Server) searchMCPRun(r *http.Request, query string, count *int) (string
if count != nil {
ctx = withSearchCount(ctx, *count)
}
ctx = withScope(ctx, scope)
said, _, err := s.webSearch(ctx, query)
if err != nil {
if r.Context().Err() == nil {
+1 -1
View File
@@ -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", nil)
return s.searchMCPRun(httptest.NewRequest("POST", "/mcp/search", nil), "latest go", nil, nil)
}
// on
+88
View File
@@ -0,0 +1,88 @@
package gateway
import (
"context"
"encoding/json"
"strings"
"testing"
)
// web_search's optional arguments reach the ChatGPT backend's search as its
// own fields (an image search is the image_query command), and any other
// searcher is asked the sites as operators. A real Plus account answered
// an image_query on 2026-11-12 with "<title> (<page>)", a citation mark
// and "Image URL: <url># <caption>".
func TestSearchScopeReachesCodexSearch(t *testing.T) {
codexSignedIn(t)
f := newFakeChatGPT(t)
s := New()
args := searchArgs{AllowedDomains: []string{"https://www.Go.dev/doc", "bad domain"}, BlockedDomains: []string{"spam.example"},
RecencyDays: json.RawMessage(`"30"`), Images: true, ContextSize: "high"}
ctx := withScope(withSearchCount(context.Background(), 4), args.scope())
if _, _, err := s.webSearch(ctx, "go gopher"); err != nil {
t.Fatal(err)
}
_, bodies := f.asked()
q := bodies[0]
cmds := q["commands"].(map[string]any)
if _, ok := cmds["search_query"]; ok {
t.Fatalf("an image search asked for pages: %v", q)
}
iq := cmds["image_query"].([]any)[0].(map[string]any)
set := q["settings"].(map[string]any)
filters := set["filters"].(map[string]any)
if iq["q"] != "go gopher" || iq["recency"] != float64(30) || len(iq["domains"].([]any)) != 1 || iq["domains"].([]any)[0] != "go.dev" ||
filters["blocked_domains"].([]any)[0] != "spam.example" || set["search_context_size"] != "high" ||
set["image_settings"].(map[string]any)["max_results"] != float64(4) {
t.Fatalf("body %v", q)
}
// no arguments: the body is the plain search it was
if _, _, err := s.webSearch(context.Background(), "go gopher"); err != nil {
t.Fatal(err)
}
_, bodies = f.asked()
if _, ok := bodies[0]["commands"].(map[string]any)["search_query"]; !ok || bodies[0]["settings"].(map[string]any)["filters"] != nil {
t.Fatalf("body %v", bodies[0])
}
}
func TestSearchScopeOperatorsForOtherSearchers(t *testing.T) {
args := searchArgs{AllowedDomains: []string{"go.dev", "pkg.go.dev"}, BlockedDomains: []string{"x.com"}}
ctx := withScope(context.Background(), args.scope())
ctx, q := searchScoped(ctx, "gopher")
if q != "gopher (site:go.dev OR site:pkg.go.dev) -site:x.com" || unscoped(ctx, q) != "gopher" {
t.Fatalf("query %q, own %q", q, unscoped(ctx, q))
}
if _, q := searchScoped(context.Background(), "gopher"); q != "gopher" {
t.Fatalf("no scope: %q", q)
}
if (searchArgs{RecencyDays: json.RawMessage(`0`), ContextSize: "huge"}).scope() != nil {
t.Fatal("empty arguments made a scope")
}
}
func TestImageResultsReadAsPages(t *testing.T) {
out := "Bridges | example.com (https://example.com/g)\nciteturn0image0 \nImage URL: https://example.com/a.jpg# Golden Gate Bridge\n\nIt is orange."
pages := codexPages(out, codexSearchReply{}, 5)
if len(pages) != 1 || !strings.HasPrefix(pages[0].Text, "Image: https://example.com/a.jpg Golden Gate Bridge") {
t.Fatalf("%+v", pages)
}
}
func TestSearchMCPSchemaOffersScope(t *testing.T) {
var v struct {
Properties map[string]any `json:"properties"`
}
if err := json.Unmarshal([]byte(searchMCPSchema(5)), &v); err != nil {
t.Fatal(err)
}
for _, k := range []string{"query", "count", "allowed_domains", "blocked_domains", "recency_days", "images", "search_context_size"} {
if v.Properties[k] == nil {
t.Fatalf("no %s in %v", k, v.Properties)
}
}
if strings.Contains(strings.ToLower(searchMCPSchema(5)), "magpie") {
t.Fatal("the schema names magpie")
}
}
+133
View File
@@ -0,0 +1,133 @@
package gateway
import (
"context"
"encoding/json"
"net/url"
"strings"
)
// searchScope is what a web_search call narrows its search by, beyond the
// query: the pages' sites, how recent they are, and images instead of pages.
// The ChatGPT backend's search takes these as its own fields (codex-rs
// codex-api search.rs: a query's domains and recency, image_query,
// settings.filters, settings.search_context_size); any other searcher is
// given the sites as search operators in the query, and ignores the rest.
type searchScope struct {
Allowed, Blocked []string
RecencyDays int
Images bool
Size string // "low", "medium" or "high"
Original string // the query before the operators were added
}
type searchScopeKey struct{}
func scopeOf(ctx context.Context) *searchScope {
s, _ := ctx.Value(searchScopeKey{}).(*searchScope)
return s
}
// withScope is ctx whose search is narrowed by sc; an empty scope leaves it.
func withScope(ctx context.Context, sc *searchScope) context.Context {
if sc == nil {
return ctx
}
return context.WithValue(ctx, searchScopeKey{}, sc)
}
// siteOf is the host a domain argument names: a model may write a URL.
func siteOf(d string) string {
d = strings.TrimSpace(d)
if strings.Contains(d, "://") {
if u, err := url.Parse(d); err == nil {
d = u.Host
}
}
d = strings.TrimPrefix(strings.ToLower(d), "www.")
d, _, _ = strings.Cut(d, "/")
if strings.ContainsAny(d, " \t\"'") {
return ""
}
return d
}
func sitesOf(in []string) []string {
var out []string
for _, d := range in {
if h := siteOf(d); h != "" {
out = append(out, h)
}
if len(out) == 20 {
break
}
}
return out
}
// searchScoped is the query a searcher that has no such fields is asked,
// the sites as operators, and ctx holding the scope for the one that has.
func searchScoped(ctx context.Context, query string) (context.Context, string) {
sc := scopeOf(ctx)
if sc == nil {
return ctx, query
}
sc.Original = query
var b strings.Builder
b.WriteString(query)
if len(sc.Allowed) > 0 {
b.WriteString(" (")
for i, d := range sc.Allowed {
if i > 0 {
b.WriteString(" OR ")
}
b.WriteString("site:" + d)
}
b.WriteString(")")
}
for _, d := range sc.Blocked {
b.WriteString(" -site:" + d)
}
return ctx, b.String()
}
// unscoped is the query as the call wrote it, for a searcher that takes the
// scope as fields.
func unscoped(ctx context.Context, query string) string {
if sc := scopeOf(ctx); sc != nil && sc.Original != "" {
return sc.Original
}
return query
}
// searchArgs are web_search's optional arguments after the query and count.
type searchArgs struct {
AllowedDomains []string `json:"allowed_domains"`
BlockedDomains []string `json:"blocked_domains"`
RecencyDays json.RawMessage `json:"recency_days"`
Images bool `json:"images"`
ContextSize string `json:"search_context_size"`
}
// scope is what the arguments narrow by; nil when they name nothing.
func (a searchArgs) scope() *searchScope {
sc := &searchScope{Allowed: sitesOf(a.AllowedDomains), Blocked: sitesOf(a.BlockedDomains), Images: a.Images}
if n := searchCountArg(a.RecencyDays); n != nil && *n > 0 {
sc.RecencyDays = min(*n, 3650)
}
switch c := strings.ToLower(strings.TrimSpace(a.ContextSize)); c {
case "low", "medium", "high":
sc.Size = c
}
if len(sc.Allowed) == 0 && len(sc.Blocked) == 0 && sc.RecencyDays == 0 && !sc.Images && sc.Size == "" {
return nil
}
return sc
}
// searchScopeSchema is the properties searchMCPSchema adds.
const searchScopeSchema = `"allowed_domains":{"type":"array","items":{"type":"string"},"description":"Only return pages from these sites, e.g. [\"docs.python.org\"]"},` +
`"blocked_domains":{"type":"array","items":{"type":"string"},"description":"Leave out pages from these sites"},` +
`"recency_days":{"type":"integer","minimum":1,"description":"Only pages from the last this many days"},` +
`"images":{"type":"boolean","description":"Search for images instead of pages"},` +
`"search_context_size":{"type":"string","enum":["low","medium","high"],"description":"How much of each page to return"}`