Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: tools turned off with none declared reach a plugin as tool_choice none (#3110)

yetone19527ca8dd8a
diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md
index f08b93796..9e48115a0 100644
--- a/docs/subsystems/provider-plugins.md
+++ b/docs/subsystems/provider-plugins.md
@@ -70,6 +70,8 @@ A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api relay, sa
A plugin says which service tiers its vendor serves a model at with `serviceTiers` on the model (#2514): ids such as `"priority"` and `"ultrafast"`, or objects with an `id`. The host keeps the ids (`tiersOf` in `host.js`, into `plugin.Model.ServiceTiers`), `pluginCatalog` puts them on the catalog model's `Tiers`, and [`CodexTiers`](../../internal/provider/codex_models.go) offers them to Codex, as `codexcat` names them (`priority` is Fast). In [`forwardTranslated`](../../internal/gateway/gateway.go) a request translated to the plugin's Chat or Responses keeps its `service_tier` (`Request.OwnTier`) only when it is among the model's tiers (`provider.PluginTiers`); a request relayed in its own protocol was sent as the client wrote it before, and still is. A model served at `priority` on its Chat or Responses API has fast mode ([`CanFast`](../../internal/provider/groupfast.go), via `pluginTierOn`), whichever plugin it is: it can be a group's fast member or an agent's fast pick, and it can be picked Ultrafast when it is served at `ultrafast` too (`UltraOn`). Fast mode in Claude's words (speed `"fast"`, or a fast pick from an agent on Claude's API) reaches the plugin as tier `priority`, or as `ultrafast` for an Ultrafast pick, when the model is served at that tier (Lovest on Discord). Cursor's `fast` flag and `-fast` siblings still give Cursor's plugin fast mode as before.
+A request translated to a plugin's Responses API that turned tools off with no tools declared (Chat's `tool_choice: "none"`, Anthropic's `{"type":"none"}`, Gemini's `functionCallingConfig.mode` `NONE`) reaches the plugin's `fetch` with `tool_choice: "none"` and no `tools` (#3110). Before, it went without a `tool_choice`, the same as a request with no preference, so a plugin that adds a server-side tool of its own (Grok's `x_search`, magpie-community/plugins#263) couldn't respect it. [`buildResponses`](../../internal/gateway/responses.go) keeps the `"none"`, and [`forwardTranslated`](../../internal/gateway/gateway.go) leaves a lone `tool_choice` out for every upstream that isn't a plugin, and for xAI and Copilot (`refusesLoneToolChoice`, #378), so what a vendor is sent is unchanged. The plugin knows whether its vendor takes it. Grok's Responses backend doesn't: the Grok plugin's bodies are shaped by `grokPluginBody`, which keeps the lone `"none"` that `grokBody` drops for the built-in, and the plugin leaves it out before its request goes to Grok (0.1.18, the mover's `min`). Chat, Anthropic and Gemini requests still carry no tool choice beside no tools, which OpenAI's Chat refuses ("'tool_choice' is only allowed when 'tools' are specified"). `TestToolsOffWithoutToolsReachesPlugin`, `TestToolsOffWithoutToolsNotSentToVendor`, `TestToolsOffWithoutToolsLeftOutForXAI` and `TestToolsOffWithoutToolsPerBuilder` in [`tool_choice_none_test.go`](../../internal/gateway/tool_choice_none_test.go), and `TestGrokPluginBodyKeepsLoneNone`, cover it.
+
## A plugin's decision API
A plugin can serve TypeSafe's System One for its provider (#1514). Its `config` hook sets `decide: true` on the provider, and `decides: true` on a model that answers questions rather than a conversation, in the `config` hook or on the `models` hook's list. The host passes both through (`plugin.Provider.Decide`, `plugin.Model.Decides`). [`pluginProvider`](../../internal/provider/plugins.go) then sets the provider's `Decide` to `plugin://<id>/v1`, its own base: `pluginFetch` sends nowhere but the loader's host, so a decision address of the plugin's own couldn't be reached. `AskSystemOne` and the gateway's classifier post `/v1/systemone` with `Provider.Do`, which reaches the loader's `fetch` as `{baseURL}/systemone` with the account's sign-in.
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index ee54c162e..67445569e 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -4229,7 +4229,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
// 400: Codex's compaction summary goes without its tools (#378).
// Anywhere else it goes as asked, which a relay checking Codex's
// shape wants (#292).
- if p.Host() == "api.x.ai" || p.Account != nil && p.Account.Agent == "copilot" {
+ if refusesLoneToolChoice(p) {
body = withoutLoneToolChoice(body)
}
case provider.Chat:
@@ -5176,6 +5176,14 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
if to == provider.Chat && (p.IsBedrock() || p.IsAzure()) {
body = asCompletionTokens(body)
}
+ if to == provider.Responses && (!p.IsPlugin() || refusesLoneToolChoice(p)) {
+ // the "none" buildResponses keeps for a request that turned
+ // tools off with none declared goes to a plugin alone, which
+ // reads it before adding a tool of its own (#3110), and knows
+ // whether its vendor takes it. A vendor was never sent it, and
+ // xAI turns it away (#378)
+ body = withoutLoneToolChoice(body)
+ }
if to == provider.Chat && req.WebSearch && p.IsRemoteMagpie() {
// the other magpie searches for it (search_remote.go)
body = withFields(body, map[string]any{"web_search_options": map[string]any{}})
@@ -6733,6 +6741,13 @@ func withoutFields(body []byte, fields ...string) []byte {
return out
}
+// refusesLoneToolChoice is whether p's Responses API turns away a
+// tool_choice with no tools beside it: xAI's, and Copilot's /responses in
+// front of it for Grok (#378).
+func refusesLoneToolChoice(p provider.Provider) bool {
+ return p.Host() == "api.x.ai" || p.Account != nil && p.Account.Agent == "copilot"
+}
+
// withoutLoneToolChoice leaves out a tool_choice sent with no tools; with
// none to choose from it says nothing.
func withoutLoneToolChoice(body []byte) []byte {
diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go
index fe494c915..714bd51ee 100644
--- a/internal/gateway/responses.go
+++ b/internal/gateway/responses.go
@@ -1282,6 +1282,14 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {
if r.Parallel != nil {
out["parallel_tool_calls"] = *r.Parallel
}
+ } else if r.ToolChoice == "none" {
+ // tools turned off with none declared (Chat's "none", Anthropic's
+ // {"type":"none"}, Gemini's NONE) still says so here, as a
+ // Responses client's own request would, for a provider plugin that
+ // adds a server-side tool (Grok's x_search) to tell it from no
+ // choice (#3110). Only a plugin is sent it (the gateway leaves it
+ // out for a vendor, which has no use for it: xAI turns it away).
+ out["tool_choice"] = "none"
}
if len(include) > 0 {
out["include"] = include
diff --git a/internal/gateway/tool_choice_none_test.go b/internal/gateway/tool_choice_none_test.go
new file mode 100644
index 000000000..75a1e8d4f
--- /dev/null
+++ b/internal/gateway/tool_choice_none_test.go
@@ -0,0 +1,161 @@
+package gateway
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// toolsOffNoTools is the same ask, tools off with none declared, in each
+// client protocol magpie translates to Responses.
+var toolsOffNoTools = []struct{ name, path, body string }{
+ {"chat", "/v1/chat/completions", `{"model":"fake/m1","stream":false,"tool_choice":"none","messages":[{"role":"user","content":"hi"}]}`},
+ {"anthropic", "/v1/messages", `{"model":"fake/m1","max_tokens":64,"tool_choice":{"type":"none"},"messages":[{"role":"user","content":"hi"}]}`},
+ {"gemini", "/v1beta/models/fake/m1:generateContent", `{"toolConfig":{"functionCallingConfig":{"mode":"NONE"}},"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`},
+}
+
+var noneReply = sse(
+ `data: {"type":"response.created","response":{"id":"resp_n","status":"in_progress","output":[]}}`,
+ `data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"item_id":"m1","delta":"OK"}`,
+ `data: {"type":"response.completed","response":{"id":"resp_n","status":"completed","output":[]}}`)
+
+// #3110: a Chat, Anthropic or Gemini request that turned tools off, with
+// no tools, reaches a provider plugin on Responses still saying "none",
+// so a plugin adding a server-side tool (Grok's x_search) can tell it
+// from no choice. The plugin knows whether its vendor takes it.
+func TestToolsOffWithoutToolsReachesPlugin(t *testing.T) {
+ var mu sync.Mutex
+ var sent []map[string]any
+ pid := besideFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ var q map[string]any
+ json.Unmarshal(b, &q)
+ mu.Lock()
+ sent = append(sent, q)
+ mu.Unlock()
+ w.Header().Set("Content-Type", "text/event-stream")
+ io.WriteString(w, noneReply)
+ }))
+ for _, c := range toolsOffNoTools {
+ t.Run(c.name, func(t *testing.T) {
+ mu.Lock()
+ sent = nil
+ mu.Unlock()
+ path := strings.Replace(c.path, "fake/m1", pid+"/fake-resp", 1)
+ body := strings.Replace(c.body, "fake/m1", pid+"/fake-resp", 1)
+ rec := httptest.NewRecorder()
+ New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
+ if rec.Code != 200 {
+ t.Fatalf("%d %s", rec.Code, rec.Body)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if len(sent) != 1 {
+ t.Fatalf("asked %d times", len(sent))
+ }
+ if sent[0]["tool_choice"] != "none" {
+ t.Errorf("tool_choice = %v, want \"none\"; the plugin got %v", sent[0]["tool_choice"], sent[0])
+ }
+ if tools, _ := sent[0]["tools"].([]any); len(tools) > 0 {
+ t.Errorf("tools added: %v", sent[0])
+ }
+ })
+ }
+}
+
+// A vendor's Responses API is sent no tool_choice beside no tools, as
+// before #3110: it has no use for one, and some turn it away.
+func TestToolsOffWithoutToolsNotSentToVendor(t *testing.T) {
+ for _, c := range toolsOffNoTools {
+ t.Run(c.name, func(t *testing.T) {
+ f := &fake{t: t, reply: noneReply}
+ setup(t, provider.Responses, f)
+ code, out := post(t, c.path, c.body)
+ if code != 200 || strings.Contains(string(f.got), `"tool_choice"`) {
+ t.Errorf("%d %s\nupstream got %s", code, out, f.got)
+ }
+ })
+ }
+}
+
+// xAI turns away a tool_choice with no tools beside it (#378), so the
+// "none" #3110 keeps is left out there even past the vendor rule above.
+func TestToolsOffWithoutToolsLeftOutForXAI(t *testing.T) {
+ for _, c := range toolsOffNoTools {
+ t.Run(c.name, func(t *testing.T) {
+ f := &fake{t: t, reply: noneReply}
+ f.refuse = func(body []byte) (int, string) {
+ var q map[string]any
+ json.Unmarshal(body, &q)
+ if tools, _ := q["tools"].([]any); len(tools) == 0 && q["tool_choice"] != nil {
+ return 400, `{"code":"Client specified an invalid argument","error":"Invalid request content: A tool_choice was set on the request but no tools were specified."}`
+ }
+ return 0, ""
+ }
+ setup(t, provider.Responses, f)
+ if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: "http://api.x.ai/v1"}); err != nil {
+ t.Fatal(err)
+ }
+ up := httptest.NewServer(f)
+ t.Cleanup(up.Close)
+ s := New()
+ addr := strings.TrimPrefix(up.URL, "http://")
+ s.client = &http.Client{Transport: &http.Transport{DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, addr)
+ }}}
+ rec := httptest.NewRecorder()
+ s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", c.path, strings.NewReader(c.body)))
+ if rec.Code != 200 || strings.Contains(string(f.got), `"tool_choice"`) {
+ t.Errorf("%d %s\nxAI got %s", rec.Code, rec.Body.String(), f.got)
+ }
+ })
+ }
+}
+
+// Each builder, given tools off and none declared: Responses says "none";
+// Chat (OpenAI: "'tool_choice' is only allowed when 'tools' are
+// specified"), Anthropic, Gemini and Code Assist send no tool choice at
+// all, as before #3110.
+func TestToolsOffWithoutToolsPerBuilder(t *testing.T) {
+ r := &Request{Model: "m", ToolChoice: "none", Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}}}}
+ gem, err := buildGemini(r, "upstream")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range []struct {
+ name string
+ body []byte
+ want any
+ }{
+ {"responses", buildResponses(r, "upstream", "api.openai.com", false), "none"},
+ {"chat", buildChat(r, "upstream", "api.openai.com", false), nil},
+ {"anthropic", buildAnthropic(r, "upstream"), nil},
+ {"gemini", gem, nil},
+ {"codeassist", buildCodeAssist(r, "upstream", "gemini"), nil},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ var q map[string]any
+ if err := json.Unmarshal(c.body, &q); err != nil {
+ t.Fatalf("%v: %s", err, c.body)
+ }
+ if q["tool_choice"] != c.want || q["tools"] != nil || strings.Contains(string(c.body), "toolConfig") {
+ t.Errorf("tool_choice = %v, want %v: %s", q["tool_choice"], c.want, c.body)
+ }
+ })
+ }
+ // a choice other than none, with no tools, still goes unsaid
+ for _, choice := range []string{"", "auto"} {
+ r.ToolChoice = choice
+ if b := buildResponses(r, "upstream", "api.openai.com", false); strings.Contains(string(b), `"tool_choice"`) {
+ t.Errorf("%q: %s", choice, b)
+ }
+ }
+}
diff --git a/internal/provider/grok.go b/internal/provider/grok.go
index 1ab7843e2..2923f6c31 100644
--- a/internal/provider/grok.go
+++ b/internal/provider/grok.go
@@ -180,7 +180,16 @@ var grokTools = map[string]bool{"function": true, "web_search": true, "x_search"
// agent_message (a subagent's task, or its reply in the lead's history),
// which the backend turns away with 422 "unknown item type", goes as the
// user's message, its sender and recipient said first (grokAgentMessage).
-func grokBody(body []byte) []byte {
+func grokBody(body []byte) []byte { return grokShaped(body, false) }
+
+// grokPluginBody is grokBody for the Grok plugin, but a tool_choice "none"
+// with no tools stays: a request that turned tools off says so to the
+// plugin, which reads it before adding a tool of its own (x_search) and
+// leaves a lone tool_choice out before the request goes to Grok
+// (@magpie-community/opencode-grok-auth 0.1.18, #3110).
+func grokPluginBody(body []byte) []byte { return grokShaped(body, true) }
+
+func grokShaped(body []byte, keepNone bool) []byte {
if !bytes.Contains(body, []byte(`"tools"`)) && !bytes.Contains(body, []byte(`"reasoning"`)) && !bytes.Contains(body, []byte(`"tool_choice"`)) && !bytes.Contains(body, []byte(`"namespace"`)) && !bytes.Contains(body, []byte(`"agent_message"`)) {
return body
}
@@ -228,7 +237,7 @@ func grokBody(body []byte) []byte {
}
}
}
- if tools, _ := m["tools"].([]any); len(tools) == 0 {
+ if tools, _ := m["tools"].([]any); len(tools) == 0 && !(keepNone && m["tool_choice"] == "none") {
if _, ok := m["tool_choice"]; ok {
delete(m, "tool_choice")
dirty = true
diff --git a/internal/provider/grok_test.go b/internal/provider/grok_test.go
index 14b15504c..b74619a39 100644
--- a/internal/provider/grok_test.go
+++ b/internal/provider/grok_test.go
@@ -92,6 +92,33 @@ func TestGrokBodyDropsLoneToolChoice(t *testing.T) {
}
}
+// The Grok plugin is handed a lone tool_choice "none" (#3110): it reads it
+// before adding x_search, and leaves it out before Grok. Any other lone
+// tool_choice still goes, and the built-in, which is Grok's last stop,
+// sends no lone "none" either.
+func TestGrokPluginBodyKeepsLoneNone(t *testing.T) {
+ for _, in := range []string{
+ `{"model":"grok-4.7","tool_choice":"none","input":[]}`,
+ `{"model":"grok-4.7","tools":[],"tool_choice":"none","input":[]}`,
+ `{"model":"grok-4.7","tools":[{"type":"custom","name":"apply_patch"}],"tool_choice":"none","input":[]}`,
+ } {
+ if got := string(grokPluginBody([]byte(in))); !strings.Contains(got, `"tool_choice":"none"`) {
+ t.Errorf("plugin: %s\n-> %s", in, got)
+ }
+ if got := string(grokBody([]byte(in))); strings.Contains(got, "tool_choice") {
+ t.Errorf("built-in: %s\n-> %s", in, got)
+ }
+ }
+ for _, in := range []string{
+ `{"model":"grok-4.7","tool_choice":"auto","input":[]}`,
+ `{"model":"grok-4.7","tool_choice":{"type":"none"},"input":[]}`,
+ } {
+ if got := string(grokPluginBody([]byte(in))); strings.Contains(got, "tool_choice") {
+ t.Errorf("plugin: %s\n-> %s", in, got)
+ }
+ }
+}
+
// Codex's reasoning, handed back with a null content, is sent without it.
func TestGrokBodyDropsNullReasoningContent(t *testing.T) {
in := []byte(`{"input":[{"type":"reasoning","id":"rs_1","summary":[],"content":null,"encrypted_content":"a+b/c="},{"type":"message","role":"user","content":"hi"}]}`)
diff --git a/internal/provider/migrate_side.go b/internal/provider/migrate_side.go
index 12831d6bd..659184014 100644
--- a/internal/provider/migrate_side.go
+++ b/internal/provider/migrate_side.go
@@ -97,7 +97,7 @@ func init() {
// names, as the built-in does: the homes stay where they are.
movers["grok"] = &mover{
pkg: "@magpie-community/opencode-grok-auth",
- min: "0.1.17", // the sign-in page opens once, where Grok Build opened it and magpie again (andyfmyth on X); a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; grok-4.7's reasoning levels; a token Grok refuses early reads as expired; the sign-in renewed ahead of time through auth.refresh; a 429 shows a spent Rate limit window until it lifts; a login with no link says why; a tool whose parameters are a root union goes as a plain object (#1271); a plain Codex agent_message (a subagent's task or reply) goes as the user's message, not refused with 422 "unknown item type", a sealed one as it came (plugins#61); a model Grok lists at two windows is offered at each, grok-4.7@500k sent with x-grok-context-window (plugins#83); a window offered without a k (grok-4.7@131072) goes as that window, not as a model named so (#1679); a sign-in without Grok Build names GROK_BIN_DIR (#2223); a sign-in with no email (an X account) is kept by its xAI user id, GROK_AUTH_PATH no longer takes it elsewhere, and a login that leaves none says where it looked
+ min: "0.1.18", // the sign-in page opens once, where Grok Build opened it and magpie again (andyfmyth on X); a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; grok-4.7's reasoning levels; a token Grok refuses early reads as expired; the sign-in renewed ahead of time through auth.refresh; a 429 shows a spent Rate limit window until it lifts; a login with no link says why; a tool whose parameters are a root union goes as a plain object (#1271); a plain Codex agent_message (a subagent's task or reply) goes as the user's message, not refused with 422 "unknown item type", a sealed one as it came (plugins#61); a model Grok lists at two windows is offered at each, grok-4.7@500k sent with x-grok-context-window (plugins#83); a window offered without a k (grok-4.7@131072) goes as that window, not as a model named so (#1679); a sign-in without Grok Build names GROK_BIN_DIR (#2223); a sign-in with no email (an X account) is kept by its xAI user id, GROK_AUTH_PATH no longer takes it elsewhere, and a login that leaves none says where it looked; a tool_choice with no tools beside it, which magpie hands the plugin as "none" when a client turned tools off (#3110), is left out before Grok
agents: []string{"grok"},
out: func() ([]Moving, error) {
var out []Moving
diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go
index 26142b507..96c6df7ec 100644
--- a/internal/provider/plugins.go
+++ b/internal/provider/plugins.go
@@ -342,8 +342,9 @@ func pluginProvider(pp plugin.Provider, l pluginLogin) Provider {
// Codex's namespaced tools go to Grok flat, as the built-in sends
// them (#404): the plugin's own rewrite would leave them out; and
// a plain agent_message goes as the user's message, as the plugin
- // itself sends it from 0.1.11
- a.body = grokBody
+ // itself sends it from 0.1.11. A lone tool_choice "none" stays,
+ // for the plugin to read (grokPluginBody, #3110)
+ a.body = grokPluginBody
}
if pp.ID == "zed" {
// an OpenAI model's request as Zed's cloud reads it: Codex's