From 70221a84ad92961f77cc1d2d65eb0b111b78999a Mon Sep 17 00:00:00 2001 From: Martin Emde Date: Wed, 2 Jul 2025 19:52:34 -0700 Subject: [PATCH] mcp: render blank text field in TextContent The text field is required. Some clients fail to parse the response if the text field is omitted and a blank text field is allowed. Return the field even when it is blank by removing omitempty. --- mcp/content.go | 14 ++++++++++++-- mcp/content_test.go | 8 ++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/mcp/content.go b/mcp/content.go index ed7f6f99..61111a99 100644 --- a/mcp/content.go +++ b/mcp/content.go @@ -2,6 +2,9 @@ // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. +// TODO(findleyr): update JSON marshalling of all content types to preserve required fields. +// (See [TextContent.MarshalJSON], which handles this for text content). + package mcp import ( @@ -25,12 +28,19 @@ type TextContent struct { } func (c *TextContent) MarshalJSON() ([]byte, error) { - return json.Marshal(&wireContent{ + // Custom wire format to ensure the required "text" field is always included, even when empty. + wire := struct { + Type string `json:"type"` + Text string `json:"text"` + Meta Meta `json:"_meta,omitempty"` + Annotations *Annotations `json:"annotations,omitempty"` + }{ Type: "text", Text: c.Text, Meta: c.Meta, Annotations: c.Annotations, - }) + } + return json.Marshal(wire) } func (c *TextContent) fromWire(wire *wireContent) { diff --git a/mcp/content_test.go b/mcp/content_test.go index 5ee6f66c..8c4e5306 100644 --- a/mcp/content_test.go +++ b/mcp/content_test.go @@ -22,6 +22,14 @@ func TestContent(t *testing.T) { &mcp.TextContent{Text: "hello"}, `{"type":"text","text":"hello"}`, }, + { + &mcp.TextContent{Text: ""}, + `{"type":"text","text":""}`, + }, + { + &mcp.TextContent{}, + `{"type":"text","text":""}`, + }, { &mcp.TextContent{ Text: "hello",