Files
magpie/internal/gateway/claude_tui_schema.go
T
yetone a25d3d0815 claude: a JSON schema is answered in the interactive mode, through an answer tool
With the interactive mode on, a request with a JSON schema was refused
with a 400 since v0.1.2592: interactive Claude Code takes --json-schema and does nothing
with it, its StructuredOutput tool being -p's alone. It now runs in the
interactive mode like any other request.

- serveClaudeSubscription compiles the schema (santhosh-tekuri/jsonschema
  v6.0.3, draft-07 unless it says otherwise, as -p reads one; a $ref
  outside the schema is refused, never fetched) and adds an answer tool,
  StructuredOutput or a numbered name apart from the client's tools, with
  the schema as its input schema, through the bridge's MCP server. A
  schema that can't be compiled is a 400 before any run.
- mcpCall checks each call against the schema: one that doesn't fit is
  told why (isError) to be made again, as -p's is; one that fits is kept.
- At the turn's result the kept input is the reply's structured output.
  A turn that ended with no call is told once to call the tool, and
  fails "no answer fitting the schema" if it still doesn't. Neither the
  call nor the words around it reach the client.
- claudePrint no longer lists the schema. The two refusal tests
  (TestClaudeTUIOnRefusesPrint, TestClaudeTUIRefusalIsNoAccountsFault)
  now use the case that is still refused before any run: an image by
  its URL that can't be downloaded (127.0.0.1, which magpie never
  fetches).
- The provider editor's card no longer says -p takes "a JSON schema"
  the interactive mode can't (en, zh-CN, zh-TW, ja, de).
- docs/subsystems/claude-subscription-bridge.md: the refusal list, and
  how a schema is answered.

Run:
- A real run, haiku, the test account in a sandbox HOME, real Claude
  Code 2.1.316 through the helper with --json-schema and a stdio MCP
  server named magpie serving the answer tool and its description: the
  result's structured_output was null (the premise), and the model
  called mcp__magpie__StructuredOutput at once with
  {"color":"Sky blue","hex":"#87CEEB"}, which fits the schema's
  pattern. 7.2s, one turn. Not run: the whole gateway path with a real
  account (the unit tests drive it with Claude Code's real transcript
  rows).
- mote, at this tree (base 14e351378, origin/main just fetched): gofmt,
  go vet (darwin, windows, linux -tags nogui), go mod verify ok;
  go test ./internal/gateway ./internal/claudetui: claudetui ok, gateway
  red in TestCodexPoolSaysTheClientsVersion only, which is #4807 (red in
  a full package run on mote, another test's Codex identity reaches it);
  alone at this tree -count=3 ok. claude-mode 44/44 and i18n-keys 4/4 in
  chromium and webkit.
- Broken by hand: answer() taking every call without checking it made
  TestClaudeTUISchemaAnswer red ("a call that doesn't fit was told
  Answer received.").
2026-11-02 00:35:21 +08:00

107 lines
3.8 KiB
Go

package gateway
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"slices"
"github.com/santhosh-tekuri/jsonschema/v6"
)
// Claude Code's interactive mode takes --json-schema and does nothing with
// it (2.1.316: its StructuredOutput tool is -p's alone), so a request with
// a JSON schema is given an answer tool of magpie's, through the bridge's
// MCP server like the client's tools: its input schema is the request's,
// magpie checks each call against it, and the answer is the input of the
// call that fits, told when the turn's result comes. A call that doesn't
// fit is told why and made again, as -p's is; a turn that ends with no
// call is asked for one once.
// answerToolName is the answer tool's name, unless a client's tool has it.
const answerToolName = "StructuredOutput"
const answerToolDescription = "Use this tool to give your final answer, as its input, in the shape its input schema asks. Call it once, at the end of your work, instead of answering in words."
// answerTool is the tool a request with a schema is answered through, named
// apart from the client's tools.
func answerTool(tools []Tool, schema json.RawMessage) Tool {
name := answerToolName
for n := 2; slices.ContainsFunc(tools, func(t Tool) bool { return t.Name == name }); n++ {
name = fmt.Sprintf("%s%d", answerToolName, n)
}
return Tool{Name: name, Description: answerToolDescription, Schema: cliSchema(schema)}
}
// answerAsk asks a turn that ended without the answer tool for its call.
func answerAsk(name string) string {
return "Give your final answer now by calling the " + name + " tool, with the answer as its input."
}
// noSchemaLoads refuses every $ref outside the schema itself: a schema is
// the caller's, and nothing it names is fetched or read.
type noSchemaLoads struct{}
func (noSchemaLoads) Load(url string) (any, error) {
return nil, fmt.Errorf("the schema refers to %s, outside itself", url)
}
// compileAnswerSchema compiles a request's schema to check the answer
// tool's calls against: as draft-07 without a $schema of its own, as
// Claude Code's -p reads one.
func compileAnswerSchema(raw json.RawMessage) (*jsonschema.Schema, error) {
doc, err := jsonschema.UnmarshalJSON(bytes.NewReader(raw))
if err != nil {
return nil, fmt.Errorf("the JSON schema isn't valid JSON: %v", err)
}
c := jsonschema.NewCompiler()
c.DefaultDraft(jsonschema.Draft7)
c.UseLoader(noSchemaLoads{})
const loc = "magpie:answer.json"
if err := c.AddResource(loc, doc); err != nil {
return nil, fmt.Errorf("the JSON schema can't be used: %v", err)
}
s, err := c.Compile(loc)
if err != nil {
return nil, fmt.Errorf("the JSON schema can't be used: %v", err)
}
return s, nil
}
// answer takes a call of the answer tool: the answer when it fits the
// schema, kept for the turn's result; why not, for the model to call it
// again, when it doesn't.
func (r *subscriptionRun) answer(w http.ResponseWriter, args json.RawMessage) {
r.mu.Lock()
schema := r.answerSchema
r.mu.Unlock()
v, err := jsonschema.UnmarshalJSON(bytes.NewReader(args))
if err == nil {
err = schema.Validate(v)
}
if err != nil {
var ve *jsonschema.ValidationError
why := err.Error()
if errors.As(err, &ve) {
why = ve.Error()
}
writeJSON(w, 200, mcpToolResult{Content: []map[string]any{{"type": "text", "text": "The input doesn't fit the schema: " + why + "\nCall the tool again with input that fits."}}, IsError: true})
return
}
r.mu.Lock()
r.answerArgs = slices.Clone(args)
r.mu.Unlock()
writeJSON(w, 200, mcpToolResult{Content: []map[string]any{{"type": "text", "text": "Answer received."}}})
}
// takeAnswer is the turn's answer, if a call gave one, and forgets it.
func (r *subscriptionRun) takeAnswer() json.RawMessage {
r.mu.Lock()
defer r.mu.Unlock()
a := r.answerArgs
r.answerArgs = nil
return a
}