mcp: propertly validate against JSON, independent of Go values

Our validation logic was avoiding double-unmarshalling as much as
possible, by parsing before validation and validating the Go type.

This only works if the Go type has the same structure as its JSON
representation, which may not be the case in the presence of types with
custom MarshalJSON or UnmarshalJSON methods (such as time.Time).

But even if the Go type doesn't use any custom marshalling, validation
is broken, because we can't differentiate zero values from missing
values.

Bite the bullet and use double-unmarshalling for both input and output
schemas. Coincidentally, this fixes three bugs:
- We were accepting case-insensitive JSON keys, since we parsed first,
  even though they should have been rejected. A number of tests were
  wrong.
- Defaults were overriding present-yet-zero values, as noted in an
  incorrect test case.
- When "arguments" was missing, validation wasn't performed, no defaults
  were applied, and unmarshalling failed even if all properties were
  optional.

First unmarshalling to map[string]any allows us to fix all these bugs.
Unfortunately, it means a 3x increase in the number of reflection
operations (we need to unmarshal, apply defaults and validate,
re-marshal with the defaults, and then unmarshal into the Go type).
However, this is not likely to be a significant overhead, and we can
always optimize in the future.

Update github.com/google/jsonschema-go to pick up necessary improvements
supporting this change.

Additionally, fix the error codes for invalid tool parameters, to be
consistent with other SDKs (Invalid Params: -32602).

Fixes #447
Fixes #449
Updates #450
This commit is contained in:
Rob Findley 2025-09-11 19:48:09 +00:00 • committed by Robert Findley
commit 9f1b8646bd

View file

@ -189,7 +189,6 @@ func (s *Server) AddTool(t *Tool, h ToolHandler) {
func() bool { s.tools.add(st); return true })
}
// TODO(v0.3.0): test
func toolForErr[In, Out any](t *Tool, h ToolHandlerFor[In, Out]) (*Tool, ToolHandler, error) {
tt := *t
@ -221,11 +220,23 @@ func toolForErr[In, Out any](t *Tool, h ToolHandlerFor[In, Out]) (*Tool, ToolHan
}
th := func(ctx context.Context, req *CallToolRequest) (*CallToolResult, error) {
var input json.RawMessage
if req.Params.Arguments != nil {
input = req.Params.Arguments
}
// Validate input and apply defaults.
var err error
input, err = applySchema(input, inputResolved)
if err != nil {
// TODO(#450): should this be considered a tool error? (and similar below)
return nil, fmt.Errorf("%w: validating \"arguments\": %v", jsonrpc2.ErrInvalidParams, err)
}
// Unmarshal and validate args.
var in In
if req.Params.Arguments != nil {
if err := unmarshalSchema(req.Params.Arguments, inputResolved, &in); err != nil {
return nil, err
if input != nil {
if err := json.Unmarshal(input, &in); err != nil {
return nil, fmt.Errorf("%w: %v", jsonrpc2.ErrInvalidParams, err)
}
}
@ -241,22 +252,15 @@ func toolForErr[In, Out any](t *Tool, h ToolHandlerFor[In, Out]) (*Tool, ToolHan
return nil, wireErr
}
// For regular errors, embed them in the tool result as per MCP spec
return &CallToolResult{
Content: []Content{&TextContent{Text: err.Error()}},
IsError: true,
}, nil
}
// Validate output schema, if any.
// Skip if out is nil: we've removed "null" from the output schema, so nil won't validate.
if v := reflect.ValueOf(out); v.Kind() == reflect.Pointer && v.IsNil() {
} else if err := validateSchema(outputResolved, &out); err != nil {
return nil, fmt.Errorf("tool output: %w", err)
var errRes CallToolResult
errRes.setError(err)
return &errRes, nil
}
if res == nil {
res = &CallToolResult{}
}
// Marshal the output and put the RawMessage in the StructuredContent field.
var outval any = out
if elemZero != nil {
@ -272,7 +276,16 @@ func toolForErr[In, Out any](t *Tool, h ToolHandlerFor[In, Out]) (*Tool, ToolHan
if err != nil {
return nil, fmt.Errorf("marshaling output: %w", err)
}
res.StructuredContent = json.RawMessage(outbytes) // avoid a second marshal over the wire
outJSON := json.RawMessage(outbytes)
// Validate the output JSON, and apply defaults.
//
// We validate against the JSON, rather than the output value, as
// some types may have custom JSON marshalling (issue #447).
outJSON, err = applySchema(outJSON, outputResolved)
if err != nil {
return nil, fmt.Errorf("validating tool output: %w", err)
}
res.StructuredContent = outJSON // avoid a second marshal over the wire
// If the Content field isn't being used, return the serialized JSON in a
// TextContent block, as the spec suggests: