fix(anthropic): improve MCP tool message handling and error resilience

修复Anthropic协议中MCP工具消息处理问题,增强错误恢复能力:
- 改进MessageContent的JSON解析,支持原始JSON数据保留
- 移除对空内容的过滤,避免丢失MCP工具消息
- 增加详细调试日志,便于问题排查
- 优化错误响应处理,保留响应体信息
- 修复路由转发时可能的数据丢失问题

fix(anthropic): improve MCP tool message handling and error resilience
- Enhance MessageContent JSON parsing to preserve raw JSON data
- Remove empty content filtering to prevent MCP tool message loss
- Add detailed debug logging for troubleshooting
- Optimize error response handling with response body preservation
- Fix potential data loss during routing

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Deadwalk
2025-09-30 08:29:38 +08:00
parent a587ac145a
commit bfadc4e2e0
2 changed files with 58 additions and 32 deletions

View File

@@ -36,6 +36,12 @@ type MessageContent struct {
// UnmarshalJSON implements json.Unmarshaler to handle both string and array formats
func (m *MessageContent) UnmarshalJSON(data []byte) error {
// Skip empty data or null
if len(data) == 0 || string(data) == "null" {
m.value = ""
return nil
}
// Try to unmarshal as string first
var str string
if err := json.Unmarshal(data, &str); err == nil {
@@ -50,6 +56,14 @@ func (m *MessageContent) UnmarshalJSON(data []byte) error {
return nil
}
// For routing purposes, store raw JSON if we can't parse it
// This ensures we don't lose any data during forwarding
var raw json.RawMessage
if err := json.Unmarshal(data, &raw); err == nil {
m.value = raw
return nil
}
return fmt.Errorf("message content must be either a string or an array of content blocks")
}
@@ -73,6 +87,14 @@ func (m MessageContent) ToContentArray() []Content {
}}
case []Content:
return v
case json.RawMessage:
// Try to parse raw JSON as Content array
var arr []Content
if err := json.Unmarshal(v, &arr); err == nil {
return arr
}
// If that fails, return empty array to avoid breaking the routing
return []Content{}
default:
return []Content{}
}