Files
magpie/internal/gateway/namespace_test.go
T
yetone 224304ab08 codex: third-party and group models get Codex's tool search, so the first request no longer carries every MCP and ChatGPT-app tool's schema (#258: 190K tokens before the first word on a magpie model, ~26K on Codex's own)
Codex sends every MCP tool's full schema inline in `tools` unless the model's catalog entry says supports_search_tool (core/src/tools/spec_plan.rs search_tool_enabled; mcp_tool_exposure.rs Deferred vs Direct); its own gpt-5.5/5.6 entries say so, magpie's generic entries didn't, so with a ChatGPT sign-in's apps a turn began at ~190K tokens. The generic entries now set supports_search_tool: true; base_instructions, the context window and the rest are as they were, and code mode and Responses Lite stay off. The gateway serves the search to models that don't know it: for a model it translates for (Chat, Anthropic…), the client-run tool_search is offered as a function, earlier tool_search_call/tool_search_output become a call and its result ("These tools are now available to call: …"), the tools found are offered after those sent (once, namespaces merged), and a call to it goes back to Codex as the tool_search_call Codex runs, streamed or not. A request relayed to another Responses API (not the ChatGPT backend, which runs it as sent) is rewritten the same way, the found tools' defer_loading dropped, and its stream line by line (toolsearch.go). Measured with codex exec in a sandbox HOME against a fake Responses backend and a fake MCP server with 150 tools: the first request's body went from 307,198 to 23,580 bytes. Tested with toolsearch_test.go (translated, streamed and rendered, end to end through a Chat fake and a relayed Responses fake, merging, the stream split mid-line) and TestCodexCatalogToolSearch (search on, prompt, context window and the other fields unchanged). go vet, go build -tags nogui (and GOOS=linux, GOOS=windows) and go test -tags nogui ./... pass. Not tried with real Gemini/antigravity calling the search, real ChatGPT apps, or real third-party Responses providers; a non-streamed relayed reply isn't rewritten (Codex always streams).
2026-09-30 10:49:28 +08:00

141 lines
4.9 KiB
Go

package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Codex offers some tools inside a namespace — spawn_agent is
// collaboration's — and names the namespace beside the tool in its calls.
const namespacedTools = `"tools":[
{"type":"function","name":"exec_command","parameters":{"type":"object"}},
{"type":"namespace","name":"collaboration","description":"Tools in the collaboration namespace.","tools":[
{"type":"function","name":"spawn_agent","description":"Spawns an agent.","parameters":{"type":"object","properties":{"message":{"type":"string"}}}},
{"type":"custom","name":"freeform","description":"no JSON schema"}
]}
]`
func TestNamespacedToolsOffered(t *testing.T) {
r, err := parseResponses([]byte(`{"model":"m","input":"hi",` + namespacedTools + `}`))
if err != nil {
t.Fatal(err)
}
var names []string
for _, tl := range r.Tools {
names = append(names, tl.Name)
}
if got := strings.Join(names, ","); got != "exec_command,collaboration__spawn_agent" {
t.Fatalf("tools = %s", got)
}
if r.Tools[1].Description != "Spawns an agent." || !strings.Contains(string(r.Tools[1].Schema), "message") {
t.Fatalf("spawn_agent lost its description or schema: %+v", r.Tools[1])
}
if q := r.Namespaced["collaboration__spawn_agent"]; q != (nsTool{Namespace: "collaboration", Name: "spawn_agent"}) {
t.Fatalf("namespaced = %+v", r.Namespaced)
}
if _, ok := r.Namespaced["exec_command"]; ok {
t.Fatal("a top-level tool was put in a namespace")
}
}
func TestNamespacedCallInHistory(t *testing.T) {
r, err := parseResponses([]byte(`{"model":"m",` + namespacedTools + `,"input":[
{"type":"message","role":"user","content":"go"},
{"type":"function_call","call_id":"c1","name":"spawn_agent","namespace":"collaboration","arguments":"{}"},
{"type":"function_call_output","call_id":"c1","output":"ok"}]}`))
if err != nil {
t.Fatal(err)
}
var call *Part
for i := range r.Messages {
for j := range r.Messages[i].Parts {
if p := &r.Messages[i].Parts[j]; p.Kind == ToolCall {
call = p
}
}
}
if call == nil || call.Name != "collaboration__spawn_agent" {
t.Fatalf("history call = %+v", call)
}
}
func TestLongNamespacedNamesFit(t *testing.T) {
ns := "mcp__" + strings.Repeat("a", 60)
body := `{"model":"m","input":"hi","tools":[{"type":"namespace","name":"` + ns + `","tools":[
{"type":"function","name":"` + strings.Repeat("b", 40) + `1"},
{"type":"function","name":"` + strings.Repeat("b", 40) + `2"}]}]}`
r, err := parseResponses([]byte(body))
if err != nil {
t.Fatal(err)
}
if len(r.Tools) != 2 || r.Tools[0].Name == r.Tools[1].Name {
t.Fatalf("tools = %+v", r.Tools)
}
for i, tl := range r.Tools {
if len(tl.Name) > 64 {
t.Fatalf("%q is longer than 64", tl.Name)
}
if q := r.Namespaced[tl.Name]; q.Namespace != ns || !strings.HasSuffix(q.Name, string(rune('1'+i))) {
t.Fatalf("%q maps to %+v", tl.Name, q)
}
}
}
func namespacedReq() *Request {
return &Request{Model: "m", Namespaced: map[string]nsTool{"collaboration__spawn_agent": {Namespace: "collaboration", Name: "spawn_agent"}}}
}
func TestNamespacedCallStreamed(t *testing.T) {
rec := httptest.NewRecorder()
enc := encoder(provider.Responses, newSSEWriter(rec), namespacedReq())
enc.event(Event{Kind: KToolStart, ID: "c1", Name: "collaboration__spawn_agent"})
enc.event(Event{Kind: KToolArgs, Text: `{"message":"x"}`})
enc.event(Event{Kind: KToolStart, ID: "c2", Name: "exec_command"})
enc.event(Event{Kind: KToolArgs, Text: `{}`})
enc.finish()
var done []map[string]any
for _, line := range strings.Split(rec.Body.String(), "\n") {
data, ok := strings.CutPrefix(line, "data: ")
if !ok {
continue
}
var m map[string]any
if json.Unmarshal([]byte(data), &m) == nil && (m["type"] == "response.output_item.added" || m["type"] == "response.output_item.done") {
done = append(done, m["item"].(map[string]any))
}
}
if len(done) != 4 {
t.Fatalf("items = %v", done)
}
for _, it := range done {
switch it["call_id"] {
case "c1":
if enc, ok := it["encrypted_function_args"].([]any); !ok || len(enc) != 0 || it["name"] != "spawn_agent" || it["namespace"] != "collaboration" {
t.Fatalf("namespaced call = %v", it)
}
case "c2":
_, sealed := it["encrypted_function_args"]
if _, has := it["namespace"]; has || sealed || it["name"] != "exec_command" {
t.Fatalf("top-level call = %v", it)
}
}
}
}
func TestNamespacedCallRendered(t *testing.T) {
res := Result{Parts: []Part{{Kind: ToolCall, ID: "c1", Name: "collaboration__spawn_agent", Args: json.RawMessage(`{}`)}}}
var out struct {
Output []map[string]any `json:"output"`
}
if err := json.Unmarshal(render(provider.Responses, res, namespacedReq()), &out); err != nil {
t.Fatal(err)
}
if len(out.Output) != 1 || out.Output[0]["name"] != "spawn_agent" || out.Output[0]["namespace"] != "collaboration" {
t.Fatalf("output = %v", out.Output)
}
}