Files
magpie/internal/gateway/chat_tool_shape.go
T
yetone 72d6103e28 gateway: a Chat tool in MCP's or another API's shape goes upstream as a Chat function tool (#2622)
jinyue806 (#2622): ZCode sends its tools on /v1/chat/completions in MCP's
shape, {"name","description","inputSchema"}, with no type and no function
object. magpie relayed them as they came, and SenseNova turned every request
with tools away ("field Tools[0].Type invalid, should be set"; a flat
{"type":"function","name":…} got "function cannot be empty"). A missing
type is invalid Chat Completions for every upstream, not SenseNova only, and
the translated routes were broken too: parseChat read no name from such a
tool, so Messages and Responses upstreams were offered a tool named "".

shapeChatTools puts a tool with its name at the top (no type, or type
"function" without a function object) into {"type":"function","function":
{name, description, parameters, strict}}, parameters taken from
parameters, inputSchema or input_schema; other fields stay beside it. It
runs right after liftMessageTools at the same two choke points: handle, for
every Chat body before routing (relay, schema fixers, redaction, plugins),
and parseChat, for a body that never came through handle. A tool that has
its function, a hosted tool (any other type) and one with no name are left
alone, and a request with nothing to shape is relayed byte for byte.

Verified:
- TestChatToolInAnotherShapeIsShaped sends the reporter's curl body with
  each of the four tool shapes from the report through the Chat relay,
  Messages and Responses. With shapeChatTools made a no-op by hand all 12
  subtests FAIL: relayed as {"name":"f","inputSchema":{…}} as it came, and
  translated as {"name":"",…}. TestShapeChatToolsLeavesChatShape (byte for
  byte on Chat-shaped/hosted/nameless tools; strict and cache_control kept)
  FAILs on the same break. Both pass restored.
- gofmt -l: clean. go vet -tags nogui ./... for darwin, linux, windows: ok.
- Full suite at 81313b912 + this change, sandbox HOME, pinned caches:
  set -o pipefail; go test -tags nogui -timeout 45m ./... : 59 packages ok
  (internal/gateway 1134s, internal/provider 548s). 7 packages failed only
  on "no space left on device" while the disk filled mid-run (cli
  TestModelDisableCmd, library TestAgentMCPFiles, sessions
  TestCodexTitleEvidenceBound, settings TestSaveConcurrent, and gui, tui,
  usage which printed PASS but couldn't write testlog.txt). Rerun once
  space was back (30G free): cli, gui, library, sessions, settings, tui,
  usage all ok.
- Rebased onto origin/main a69cd0707 (#2611's chat call ids, chattidy):
  gofmt clean, vet darwin/linux/windows on internal/gateway ok,
  go test -tags nogui -timeout 45m ./internal/gateway ./internal/source:
  ok (gateway 510s). No other package changed between the two bases.
- Not tried against the real SenseNova (no key here); the reporter's own
  table shows {"type":"function","function":{…}} answered 200.

The "inference request is invalid ... reason=unknown retryable=false" text
in the report is not magpie's (no such string in the repo); it is the
client's wrapper of the upstream error, so nothing changed there.
2026-10-17 04:07:25 +08:00

95 lines
2.5 KiB
Go

package gateway
import (
"bytes"
"encoding/json"
"github.com/tidwall/gjson"
)
// A Chat Completions tool is {"type":"function","function":{name,
// description, parameters, strict}}. Some clients send theirs in another
// API's shape on the Chat route: MCP's {"name","description","inputSchema"}
// (ZCode, #2622), Anthropic's input_schema, a bare {"name","parameters"},
// or Responses' flat {"type":"function","name",…}. OpenAI and the strict
// Chat APIs turn every one of those away (SenseNova: "field Tools[0].Type
// invalid, should be set", "function cannot be empty"), and parseChat read
// no name from them, so a translated request offered a tool with none.
// shapeChatTools is a Chat request with each such tool in the Chat shape.
// A tool that already has its function object, a hosted tool (any other
// type), one with no name, and a request that doesn't parse are as they
// came; a tool's other fields stay beside its function.
func shapeChatTools(body []byte) []byte {
if !bytes.Contains(body, []byte(`"tools"`)) {
return body
}
tools := gjson.GetBytes(body, "tools")
if !tools.IsArray() {
return body
}
need := false
for _, t := range tools.Array() {
if unshapedChatTool(t) {
need = true
break
}
}
if !need {
return body
}
var raw []json.RawMessage
if json.Unmarshal([]byte(tools.Raw), &raw) != nil {
return body
}
for i, t := range raw {
if !unshapedChatTool(gjson.ParseBytes(t)) {
continue
}
var m map[string]json.RawMessage
if json.Unmarshal(t, &m) != nil {
continue
}
fn := map[string]json.RawMessage{}
for _, k := range []string{"name", "description", "strict"} {
if v, ok := m[k]; ok {
fn[k] = v
delete(m, k)
}
}
for _, k := range []string{"parameters", "inputSchema", "input_schema"} {
if v, ok := m[k]; ok {
if _, set := fn["parameters"]; !set {
fn["parameters"] = v
}
delete(m, k)
}
}
f, err := marshalPlain(fn)
if err != nil {
continue
}
m["type"] = json.RawMessage(`"function"`)
m["function"] = f
out, err := marshalPlain(m)
if err != nil {
continue
}
raw[i] = out
}
return withFields(body, map[string]any{"tools": raw})
}
// unshapedChatTool is whether t is a function tool with its name at the
// top rather than in a function object.
func unshapedChatTool(t gjson.Result) bool {
if !t.IsObject() || t.Get("function").Exists() {
return false
}
if typ := t.Get("type").String(); typ != "" && typ != "function" {
return false
}
n := t.Get("name")
return n.Type == gjson.String && n.String() != ""
}