internal/mcp: clean up handling of content

Add support for all content types, and formalize the conversion of
content to and from the wire format (as a discriminated union).

Change-Id: I93678ce98c02176a524d2c82425fb1267ad68bf0
Reviewed-on: https://go-review.googlesource.com/c/tools/+/669135
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
Auto-Submit: Robert Findley <rfindley@google.com>
This commit is contained in:
Rob Findley 2025-04-30 14:49:52 +00:00 • committed by Gopher Robot
commit bf608eeeae

View file

@ -7,7 +7,6 @@ package mcp
import (
"context"
"encoding/json"
"errors"
"fmt"
"iter"
"slices"
@ -194,7 +193,7 @@ func (sc *ServerConnection) ListTools(ctx context.Context) ([]protocol.Tool, err
// TODO(jba): make the following true:
// If the provided arguments do not conform to the schema for the given tool,
// the call fails.
func (sc *ServerConnection) CallTool(ctx context.Context, name string, args map[string]any) (_ []Content, err error) {
func (sc *ServerConnection) CallTool(ctx context.Context, name string, args map[string]any) (_ *protocol.CallToolResult, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("calling tool %q: %w", name, err)
@ -218,15 +217,5 @@ func (sc *ServerConnection) CallTool(ctx context.Context, name string, args map[
if err := call(ctx, sc.conn, "tools/call", params, &result); err != nil {
return nil, err
}
content, err := unmarshalContent(result.Content)
if err != nil {
return nil, fmt.Errorf("unmarshaling tool content: %v", err)
}
if result.IsError {
if len(content) != 1 || !is[TextContent](content[0]) {
return nil, errors.New("malformed error content")
}
return nil, errors.New(content[0].(TextContent).Text)
}
return content, nil
return &result, nil
}