Skip to content

Commit ba51774

Browse files
authored
fix(cli): preserve MCP call results and structured errors (#1731)
## Description Fix UX audit F4: CLI calls converted content arrays to Go map text and dropped MCP result metadata. CLI now opts into a full MCP result envelope and preserves content, structuredContent, isError, and _meta. Existing REST consumers retain their response shape. Runtime JSON failures remain machine-readable; MCP isError results return nonzero in JSON and pretty output, without a false success message. ## Testing - Reproduced content and metadata loss before the fix. - Full CLI-client package and focused CLI/server/HTTP API tests; core build and `go vet ./cmd/mcpproxy` pass. - Live scratch daemon verified CLI/MCP semantic parity for text+image content, structuredContent, metadata, text errors, empty-content errors and image-first errors. JSON failures parse and exit nonzero. Pretty-mode errors exit nonzero without success text. Ordinary REST remains an array; opted-in REST preserves the envelope. - Independent fresh-context Claude CLI (`claude-fable-5-1`) review: **VERDICT: PASS** at 0035525 after error-envelope, pretty-exit and unreachable-code fixes. - Exact-head `qa-gate`: success. CI must pass before merge. The opt-in `X-MCPProxy-Result-Envelope: 1` compatibility contract is documented in `docs/cli-output-formatting.md`; tool refusal/security classification stays ahead of envelope preservation. Live fixture CLI excerpt (same semantic result as MCP): ```json {"content":[{"type":"text","text":"{\"project\":\"audit-fixture\",\"status\":\"healthy\"}"},{"type":"image","data":"YWJj","mimeType":"image/png"}],"isError":false,"structuredContent":{"count":2,"status":"healthy"},"_meta":{"fixture":"cli-live"}} ``` A fixture `isError: true` returns exit `1` in both JSON and pretty modes.
1 parent 51fd13e commit ba51774

11 files changed

Lines changed: 468 additions & 46 deletions

File tree

‎cmd/mcpproxy/call_cmd.go‎

Lines changed: 71 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"context"
55
"encoding/json"
6+
"errors"
67
"fmt"
78
"os"
89
"strings"
@@ -288,6 +289,17 @@ func outputCallResultPretty(result interface{}) {
288289
fmt.Printf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n")
289290
}
290291

292+
func outputPrettyCallResult(result interface{}, isError bool) error {
293+
if isError {
294+
fmt.Fprintln(os.Stderr, "⚠️ Tool call returned an error.")
295+
outputCallResultPretty(result)
296+
return callResultError{}
297+
}
298+
fmt.Fprintf(os.Stderr, "✅ Tool call completed successfully!\n\n")
299+
outputCallResultPretty(result)
300+
return nil
301+
}
302+
291303
// createLogger creates a zap logger with the specified level
292304
func createLogger(level string) (*zap.Logger, error) {
293305
var zapLevel zap.AtomicLevel
@@ -317,22 +329,33 @@ func createLogger(level string) (*zap.Logger, error) {
317329
}
318330

319331
// runCallToolRead handles the tool-read command (Spec 018)
320-
func runCallToolRead(_ *cobra.Command, _ []string) error {
321-
return runCallToolVariant("call_tool_read", "read")
332+
func runCallToolRead(cmd *cobra.Command, _ []string) error {
333+
return runCallToolVariant(cmd, "call_tool_read", "read")
322334
}
323335

324336
// runCallToolWrite handles the tool-write command (Spec 018)
325-
func runCallToolWrite(_ *cobra.Command, _ []string) error {
326-
return runCallToolVariant("call_tool_write", "write")
337+
func runCallToolWrite(cmd *cobra.Command, _ []string) error {
338+
return runCallToolVariant(cmd, "call_tool_write", "write")
327339
}
328340

329341
// runCallToolDestructive handles the tool-destructive command (Spec 018)
330-
func runCallToolDestructive(_ *cobra.Command, _ []string) error {
331-
return runCallToolVariant("call_tool_destructive", "destructive")
342+
func runCallToolDestructive(cmd *cobra.Command, _ []string) error {
343+
return runCallToolVariant(cmd, "call_tool_destructive", "destructive")
332344
}
333345

334346
// runCallToolVariant is the common implementation for intent-based tool calls
335-
func runCallToolVariant(toolVariant, operationType string) error {
347+
func runCallToolVariant(cmd *cobra.Command, toolVariant, operationType string) (callErr error) {
348+
// Cobra validates required flags before RunE. Runtime failures in JSON mode
349+
// get one machine-readable document on stdout and retain a nonzero exit.
350+
if callOutputFormat == outputFormatJSON {
351+
cmd.SilenceUsage = true
352+
defer func() {
353+
var resultErr callResultError
354+
if callErr != nil && !errors.As(callErr, &resultErr) {
355+
writeCallJSONError(callErr)
356+
}
357+
}()
358+
}
336359
ctx, cancel := context.WithTimeout(context.Background(), callTimeout)
337360
defer cancel()
338361

@@ -391,6 +414,29 @@ func runCallToolVariant(toolVariant, operationType string) error {
391414
return runCallToolVariantStandalone(ctx, toolVariant, variantArgs, globalConfig)
392415
}
393416

417+
// callResultError retains the nonzero process status after a complete MCP
418+
// isError result has already been written to stdout.
419+
type callResultError struct{}
420+
421+
func (callResultError) Error() string { return "tool returned an error result" }
422+
423+
type callDaemonError struct{ cause error }
424+
425+
func (e callDaemonError) Error() string {
426+
return "failed to call tool via daemon: " + formatErrorWithRequestID(e.cause)
427+
}
428+
429+
func (e callDaemonError) Unwrap() error { return e.cause }
430+
431+
func writeCallJSONError(err error) {
432+
structured := output.NewStructuredError(output.ErrCodeOperationFailed, err.Error())
433+
var apiErr *cliclient.APIError
434+
if errors.As(err, &apiErr) && apiErr.RequestID != "" {
435+
structured = structured.WithRequestID(apiErr.RequestID)
436+
}
437+
_ = outputCallResultAsJSON(structured)
438+
}
439+
394440
// runCallToolVariantClientMode calls tool variant via the daemon HTTP API
395441
func runCallToolVariantClientMode(client *cliclient.Client, toolVariant string, args map[string]interface{}, logger *zap.Logger) error {
396442
// Ping daemon to verify connectivity
@@ -416,22 +462,25 @@ func runCallToolVariantClientMode(client *cliclient.Client, toolVariant string,
416462
// For tool variants, we call the variant tool directly
417463
result, err := client.CallTool(callCtx, toolVariant, args)
418464
if err != nil {
419-
// T028: Use cliError to include request_id in error output
420-
return cliError("failed to call tool via daemon", err)
465+
// Keep the API error wrapped so JSON output can retain request_id.
466+
return callDaemonError{cause: err}
421467
}
422468

423469
// Output results based on format
424470
switch callOutputFormat {
425471
case outputFormatJSON:
426-
return outputCallResultAsJSON(result)
472+
if err := outputCallResultAsJSON(result); err != nil {
473+
return err
474+
}
475+
if result.IsError {
476+
return callResultError{}
477+
}
478+
return nil
427479
case outputFormatPretty, "":
428480
fallthrough
429481
default:
430-
fmt.Fprintf(os.Stderr, "✅ Tool call completed successfully!\n\n")
431-
outputCallResultPretty(result)
482+
return outputPrettyCallResult(result, result.IsError)
432483
}
433-
434-
return nil
435484
}
436485

437486
// runCallToolVariantStandalone calls tool variant directly without daemon
@@ -499,13 +548,16 @@ func runCallToolVariantStandalone(ctx context.Context, toolVariant string, args
499548
// Output results based on format
500549
switch callOutputFormat {
501550
case outputFormatJSON:
502-
return outputCallResultAsJSON(result)
551+
if err := outputCallResultAsJSON(result); err != nil {
552+
return err
553+
}
554+
if result.IsError {
555+
return callResultError{}
556+
}
557+
return nil
503558
case outputFormatPretty, "":
504559
fallthrough
505560
default:
506-
fmt.Fprintf(os.Stderr, "✅ Tool call completed successfully!\n\n")
507-
outputCallResultPretty(result)
561+
return outputPrettyCallResult(result, result.IsError)
508562
}
509-
510-
return nil
511563
}
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"io"
6+
"net/http"
7+
"net/http/httptest"
8+
"os"
9+
"strings"
10+
"testing"
11+
12+
"github.com/mark3labs/mcp-go/mcp"
13+
"github.com/smart-mcp-proxy/mcpproxy-go/internal/cli/output"
14+
"github.com/smart-mcp-proxy/mcpproxy-go/internal/cliclient"
15+
"github.com/spf13/cobra"
16+
"github.com/stretchr/testify/require"
17+
"go.uber.org/zap"
18+
)
19+
20+
func TestCallToolJSONFailureIsParseableAndNonzero(t *testing.T) {
21+
oldFormat, oldArgs := callOutputFormat, callJSONArgs
22+
t.Cleanup(func() { callOutputFormat, callJSONArgs = oldFormat, oldArgs })
23+
callOutputFormat, callJSONArgs = "json", "{invalid"
24+
reader, writer, err := os.Pipe()
25+
require.NoError(t, err)
26+
oldStdout := os.Stdout
27+
os.Stdout = writer
28+
t.Cleanup(func() { os.Stdout = oldStdout })
29+
30+
cmd := &cobra.Command{}
31+
callErr := runCallToolVariant(cmd, "call_tool_read", "read")
32+
require.Error(t, callErr)
33+
require.True(t, cmd.SilenceUsage)
34+
require.NoError(t, writer.Close())
35+
bytes, err := io.ReadAll(reader)
36+
require.NoError(t, err)
37+
var got output.StructuredError
38+
require.NoError(t, json.Unmarshal(bytes, &got))
39+
require.Equal(t, output.ErrCodeOperationFailed, got.Code)
40+
require.Contains(t, got.Message, "invalid JSON arguments")
41+
}
42+
43+
func TestCallToolDaemonJSONRetainsResultAndErrorStatus(t *testing.T) {
44+
oldFormat := callOutputFormat
45+
callOutputFormat = "json"
46+
t.Cleanup(func() { callOutputFormat = oldFormat })
47+
for _, tc := range []struct {
48+
name, data string
49+
wantError bool
50+
}{
51+
{"success", `{"content":[{"type":"text","text":"{\"ok\":true}"},{"type":"image","data":"abc","mimeType":"image/png"}],"structuredContent":{"ok":true},"_meta":{"trace":"test"}}`, false},
52+
{"tool error", `{"content":[{"type":"text","text":"denied"}],"isError":true}`, true},
53+
} {
54+
t.Run(tc.name, func(t *testing.T) {
55+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
56+
if r.URL.Path == "/api/v1/status" {
57+
_, _ = w.Write([]byte(`{"status":"ok"}`))
58+
return
59+
}
60+
require.Equal(t, "/api/v1/tools/call", r.URL.Path)
61+
_, _ = w.Write([]byte(`{"success":true,"data":` + tc.data + `}`))
62+
}))
63+
defer srv.Close()
64+
reader, writer, err := os.Pipe()
65+
require.NoError(t, err)
66+
oldStdout := os.Stdout
67+
os.Stdout = writer
68+
defer func() { os.Stdout = oldStdout }()
69+
err = runCallToolVariantClientMode(cliclient.NewClient(srv.URL, nil), "call_tool_read", map[string]interface{}{"name": "fixture:read"}, zap.NewNop())
70+
if tc.wantError {
71+
require.Error(t, err)
72+
} else {
73+
require.NoError(t, err)
74+
}
75+
require.NoError(t, writer.Close())
76+
actual, err := io.ReadAll(reader)
77+
require.NoError(t, err)
78+
var got map[string]interface{}
79+
require.NoError(t, json.Unmarshal(actual, &got))
80+
var want map[string]interface{}
81+
require.NoError(t, json.Unmarshal([]byte(tc.data), &want))
82+
require.Equal(t, want["content"], got["content"])
83+
require.Equal(t, want["structuredContent"], got["structuredContent"])
84+
require.Equal(t, want["_meta"], got["_meta"])
85+
require.Equal(t, tc.wantError, got["isError"])
86+
})
87+
}
88+
}
89+
90+
func TestCallToolJSONErrorRetainsRequestID(t *testing.T) {
91+
reader, writer, err := os.Pipe()
92+
require.NoError(t, err)
93+
oldStdout := os.Stdout
94+
os.Stdout = writer
95+
defer func() { os.Stdout = oldStdout }()
96+
writeCallJSONError(callDaemonError{cause: &cliclient.APIError{Message: "missing server", RequestID: "req-123"}})
97+
require.NoError(t, writer.Close())
98+
bytes, err := io.ReadAll(reader)
99+
require.NoError(t, err)
100+
var got output.StructuredError
101+
require.NoError(t, json.Unmarshal(bytes, &got))
102+
require.Equal(t, "req-123", got.RequestID)
103+
require.Equal(t, output.ErrCodeOperationFailed, got.Code)
104+
}
105+
106+
func TestCallToolDaemonPrettyErrorIsNonzeroWithoutSuccessMessage(t *testing.T) {
107+
oldFormat := callOutputFormat
108+
callOutputFormat = "pretty"
109+
defer func() { callOutputFormat = oldFormat }()
110+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
111+
if r.URL.Path == "/api/v1/status" {
112+
_, _ = w.Write([]byte(`{"status":"ok"}`))
113+
return
114+
}
115+
_, _ = w.Write([]byte(`{"success":true,"data":{"content":[{"type":"text","text":"fixture denied"}],"isError":true}}`))
116+
}))
117+
defer srv.Close()
118+
stdoutReader, stdoutWriter, err := os.Pipe()
119+
require.NoError(t, err)
120+
stderrReader, stderrWriter, err := os.Pipe()
121+
require.NoError(t, err)
122+
oldStdout, oldStderr := os.Stdout, os.Stderr
123+
os.Stdout, os.Stderr = stdoutWriter, stderrWriter
124+
defer func() { os.Stdout, os.Stderr = oldStdout, oldStderr }()
125+
126+
err = runCallToolVariantClientMode(cliclient.NewClient(srv.URL, nil), "call_tool_read", map[string]interface{}{"name": "fixture:fail"}, zap.NewNop())
127+
require.ErrorAs(t, err, new(callResultError))
128+
require.NoError(t, stdoutWriter.Close())
129+
require.NoError(t, stderrWriter.Close())
130+
stdout, err := io.ReadAll(stdoutReader)
131+
require.NoError(t, err)
132+
stderr, err := io.ReadAll(stderrReader)
133+
require.NoError(t, err)
134+
require.True(t, strings.Contains(string(stdout), "fixture denied"))
135+
require.NotContains(t, string(stderr), "completed successfully")
136+
require.Contains(t, string(stderr), "returned an error")
137+
}
138+
139+
func TestStandalonePrettyResultErrorIsNonzero(t *testing.T) {
140+
result := &mcp.CallToolResult{Content: []mcp.Content{mcp.NewTextContent("standalone denied")}, IsError: true}
141+
err := outputPrettyCallResult(result, result.IsError)
142+
require.ErrorAs(t, err, new(callResultError))
143+
}

‎docs/cli-output-formatting.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,20 @@ This enables AI agents to discover available commands and their options programm
144144

145145
## Structured Error Output
146146

147+
For `mcpproxy call tool-read`, `tool-write`, and `tool-destructive -o json`,
148+
stdout contains the MCP result envelope. The CLI sends
149+
`X-MCPProxy-Result-Envelope: 1` to opt into this REST response shape; calls
150+
without that header retain their content-array response. `content` retains its ordered text,
151+
image, audio, or resource blocks; `structuredContent` and `_meta` are included
152+
when supplied by the daemon. Older daemons that return a content array are
153+
normalized to `{ "content": [...], "isError": false }`. An `isError` result
154+
keeps that envelope on stdout and exits nonzero.
155+
156+
Runtime tool-call failures emit one structured error object on stdout with
157+
`code: "OPERATION_FAILED"`, a `message`, and `request_id` when available, and
158+
exit nonzero. Diagnostics may also appear on stderr. Required-flag validation
159+
still follows Cobra's usual usage output.
160+
147161
When using JSON output format, errors include structured information:
148162

149163
```json
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package cliclient_test
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"net/http"
7+
"net/http/httptest"
8+
"testing"
9+
10+
"github.com/smart-mcp-proxy/mcpproxy-go/internal/cliclient"
11+
"github.com/stretchr/testify/require"
12+
)
13+
14+
func TestCallToolPreservesResultShapes(t *testing.T) {
15+
for _, tc := range []struct {
16+
name string
17+
data string
18+
want string
19+
}{
20+
{"legacy content array", `[{"type":"text","text":"{\"ok\":true}"},{"type":"image","data":"abc","mimeType":"image/png"}]`, `{"content":[{"type":"text","text":"{\"ok\":true}"},{"type":"image","data":"abc","mimeType":"image/png"}],"isError":false}`},
21+
{"full result", `{"content":[{"type":"text","text":"hello"}],"structuredContent":{"count":2},"isError":true,"_meta":{"source":"test"}}`, `{"content":[{"type":"text","text":"hello"}],"structuredContent":{"count":2},"isError":true,"_meta":{"source":"test"}}`},
22+
{"structured only", `{"structuredContent":{"count":2}}`, `{"content":[],"structuredContent":{"count":2},"isError":false}`},
23+
} {
24+
t.Run(tc.name, func(t *testing.T) {
25+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
26+
require.Equal(t, "/api/v1/tools/call", r.URL.Path)
27+
require.Equal(t, "1", r.Header.Get("X-MCPProxy-Result-Envelope"))
28+
_, _ = w.Write([]byte(`{"success":true,"data":` + tc.data + `}`))
29+
}))
30+
defer srv.Close()
31+
got, err := cliclient.NewClient(srv.URL, nil).CallTool(context.Background(), "call_tool_read", nil)
32+
require.NoError(t, err)
33+
actual, err := json.Marshal(got)
34+
require.NoError(t, err)
35+
require.JSONEq(t, tc.want, string(actual))
36+
})
37+
}
38+
}

0 commit comments

Comments
 (0)