Skip to content

Commit 0507b87

Browse files
committed
Add error handling for JSON marshaling in mcp-go
1 parent 5f9887b commit 0507b87

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

contrib/mark3labs/mcp-go/mcpgo.go

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,16 @@ func NewToolHandlerMiddleware() server.ToolHandlerMiddleware {
4646

4747
result, err := next(ctx, request)
4848

49-
inputJSON, _ := json.Marshal(request)
49+
inputJSON, marshalErr := json.Marshal(request)
50+
if marshalErr != nil {
51+
instr.Logger().Warn("mcp-go: failed to marshal tool request: %v", marshalErr)
52+
}
5053
var outputText string
5154
if result != nil {
52-
resultJSON, _ := json.Marshal(result)
55+
resultJSON, marshalErr := json.Marshal(result)
56+
if marshalErr != nil {
57+
instr.Logger().Warn("mcp-go: failed to marshal tool result: %v", marshalErr)
58+
}
5359
outputText = string(resultJSON)
5460
}
5561

@@ -93,7 +99,10 @@ func (h *hooks) onError(ctx context.Context, id any, method mcp.MCPMethod, messa
9399
if !ok {
94100
return
95101
}
96-
inputJSON, _ := json.Marshal(message)
102+
inputJSON, marshalErr := json.Marshal(message)
103+
if marshalErr != nil {
104+
instr.Logger().Warn("mcp-go: failed to marshal error message: %v", marshalErr)
105+
}
97106
if annotator, ok := span.(textIOAnnotator); ok {
98107
annotator.AnnotateTextIO(string(inputJSON), err.Error())
99108
}
@@ -109,8 +118,14 @@ func finishSpanWithIO[Req any, Res any](h *hooks, id any, request Req, result Re
109118
if !ok {
110119
return
111120
}
112-
inputJSON, _ := json.Marshal(request)
113-
resultJSON, _ := json.Marshal(result)
121+
inputJSON, marshalErr := json.Marshal(request)
122+
if marshalErr != nil {
123+
instr.Logger().Warn("mcp-go: failed to marshal request: %v", marshalErr)
124+
}
125+
resultJSON, marshalErr := json.Marshal(result)
126+
if marshalErr != nil {
127+
instr.Logger().Warn("mcp-go: failed to marshal result: %v", marshalErr)
128+
}
114129
outputText := string(resultJSON)
115130

116131
if annotator, ok := span.(textIOAnnotator); ok {

0 commit comments

Comments
 (0)