client: Honor IsError and extract JSON from tool text
CI / Test and build (pull_request) Successful in 14s
CI / Test and build (pull_request) Successful in 14s
Fold Jerry dump into toolJSON: TrimSpace IsError text, concat JSON via rawJSON, and unit tests mirroring IsError=true / StructuredContent=null / Text=`end must be after start` / GetError=nil.
This commit is contained in:
+20
-12
@@ -100,18 +100,18 @@ func toolJSON(res *mcp.CallToolResult) (json.RawMessage, error) {
|
||||
if res == nil {
|
||||
return nil, fmt.Errorf("empty tool result")
|
||||
}
|
||||
// GetError is only set by SetError on the server; the err field is not marshaled to clients.
|
||||
// GetError is set by SetError on the server; the err field is not marshaled to clients.
|
||||
if err := res.GetError(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
texts, types := collectTextAndTypes(res)
|
||||
concat := strings.Join(texts, "")
|
||||
// IsError is the client-visible soft-fail flag; error text lives in Content.
|
||||
if res.IsError {
|
||||
if concat == "" {
|
||||
return nil, fmt.Errorf("tool error")
|
||||
msg := strings.TrimSpace(concat)
|
||||
if msg == "" {
|
||||
msg = "tool error"
|
||||
}
|
||||
return nil, fmt.Errorf("%s", concat)
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
if res.StructuredContent != nil {
|
||||
b, err := json.Marshal(res.StructuredContent)
|
||||
@@ -121,16 +121,16 @@ func toolJSON(res *mcp.CallToolResult) (json.RawMessage, error) {
|
||||
return json.RawMessage(b), nil
|
||||
}
|
||||
for _, t := range texts {
|
||||
if json.Valid([]byte(t)) {
|
||||
return json.RawMessage(t), nil
|
||||
if raw, ok := rawJSON(t); ok {
|
||||
return raw, nil
|
||||
}
|
||||
}
|
||||
if raw, ok := rawJSON(concat); ok {
|
||||
return raw, nil
|
||||
}
|
||||
if concat == "" {
|
||||
return json.RawMessage(`{}`), nil
|
||||
}
|
||||
if json.Valid([]byte(concat)) {
|
||||
return json.RawMessage(concat), nil
|
||||
}
|
||||
if raw := extractFirstJSON(concat); raw != nil {
|
||||
return raw, nil
|
||||
}
|
||||
@@ -138,8 +138,16 @@ func toolJSON(res *mcp.CallToolResult) (json.RawMessage, error) {
|
||||
if res.StructuredContent != nil {
|
||||
structured = "present"
|
||||
}
|
||||
return nil, fmt.Errorf("non-json tool result (isError=%v types=[%s] structured=%s textLen=%d prefix=%q)",
|
||||
res.IsError, strings.Join(types, " "), structured, utf8.RuneCountInString(concat), runePrefix(concat, 80))
|
||||
return nil, fmt.Errorf("non-json tool result (isError=%v types=%v structured=%s textLen=%d prefix=%q)",
|
||||
res.IsError, types, structured, utf8.RuneCountInString(concat), runePrefix(concat, 80))
|
||||
}
|
||||
|
||||
func rawJSON(s string) (json.RawMessage, bool) {
|
||||
b := []byte(s)
|
||||
if !json.Valid(b) {
|
||||
return nil, false
|
||||
}
|
||||
return json.RawMessage(b), true
|
||||
}
|
||||
|
||||
func collectTextAndTypes(res *mcp.CallToolResult) (texts, types []string) {
|
||||
|
||||
Reference in New Issue
Block a user