From f872393314e62de074fee832d9ddbef550d521d4 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 15 Nov 2026 23:53:45 -0500 Subject: [PATCH] fix(mcp): preserve structured results and textless tool errors --- internal/mcpclient/client.go | 18 ++++++++++---- internal/mcpclient/result_envelope_test.go | 28 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 internal/mcpclient/result_envelope_test.go diff --git a/internal/mcpclient/client.go b/internal/mcpclient/client.go index b88ad587f..58cdd31af 100644 --- a/internal/mcpclient/client.go +++ b/internal/mcpclient/client.go @@ -91,7 +91,8 @@ type toolCallResult struct { Type string `json:"type"` Text string `json:"text"` } `json:"content"` - IsError bool `json:"isError,omitempty"` + IsError bool `json:"isError,omitempty"` + StructuredContent json.RawMessage `json:"structuredContent,omitempty"` } // CallTool invokes a named MCP tool with the given arguments and returns the @@ -179,16 +180,23 @@ func (c *Client) CallToolContext(ctx context.Context, name string, args map[stri if err := json.Unmarshal(rpcResp.Result, &result); err != nil { return strings.TrimSpace(string(rpcResp.Result)), nil } - if result.IsError && len(result.Content) > 0 { - return "", fmt.Errorf("mcp tool %s: %s", name, result.Content[0].Text) - } var textBlocks []string for _, block := range result.Content { if block.Type == "text" && block.Text != "" { textBlocks = append(textBlocks, block.Text) } } - return strings.Join(textBlocks, "\n"), nil + text := strings.Join(textBlocks, "\n") + if result.IsError { + if text == "" { + text = "tool reported an error without text" + } + return "", fmt.Errorf("mcp tool %s: %s", name, text) + } + if text == "" && len(result.StructuredContent) > 0 { + text = string(result.StructuredContent) + } + return text, nil } type Tool struct { diff --git a/internal/mcpclient/result_envelope_test.go b/internal/mcpclient/result_envelope_test.go new file mode 100644 index 000000000..eddbce62e --- /dev/null +++ b/internal/mcpclient/result_envelope_test.go @@ -0,0 +1,28 @@ +package mcpclient + +import ( + "net/http" + "strings" + "testing" +) + +func TestMCPToolResultEnvelope(t *testing.T) { + t.Run("error without text", func(t *testing.T) { + _, client := newFake(t, func(w http.ResponseWriter, id int64) { + writeJSON(w, `{"jsonrpc":"2.0","id":2,"result":{"isError":true,"content":[]}}`) + }) + out, err := client.CallTool("fixture", nil) + if err == nil || !strings.Contains(err.Error(), "fixture") || out != "" { + t.Fatalf("expected a tool error, got %q, %v", out, err) + } + }) + t.Run("structured result without text", func(t *testing.T) { + _, client := newFake(t, func(w http.ResponseWriter, id int64) { + writeJSON(w, `{"jsonrpc":"2.0","id":2,"result":{"structuredContent":{"count":3}}}`) + }) + out, err := client.CallTool("fixture", nil) + if err != nil || out != `{"count":3}` { + t.Fatalf("expected structured JSON, got %q, %v", out, err) + } + }) +}