toolcodec

package
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package toolcodec holds the encodings between protobuf messages, connect errors and the JSON of MCP tool calls: arguments, results and tool errors, each in both directions.

Index

Constants

View Source
const DefaultMaxRecursionDepth = 3

DefaultMaxRecursionDepth is the number of times a recursive message type is expanded in a generated schema before it is replaced with a JSON-string placeholder. EncodeMessage uses the same value so the JSON it emits matches the schema the model was given. The toolschema package mirrors this constant.

View Source
const DiscriminatorKey = "which"

DiscriminatorKey is the property name of the oneof discriminator emitted in the nested wrapper object. It carries the protojson name of the field that is set within the oneof. The toolschema package mirrors this constant when rendering schemas, and DecodeArguments/EncodeMessage read and write it at runtime.

Variables

This section is empty.

Functions

func DecodeArguments

func DecodeArguments(md protoreflect.MessageDescriptor, args map[string]any) error

DecodeArguments rewrites model-supplied tool-call arguments in place so that protojson can unmarshal them into a proto message. It is the inverse of the two schema shapes the generator emits that protojson does not understand:

  • oneof discriminated wrappers: a oneof renders as a nested object {"which":"<member>", "<member>":<value>, ...}. This lifts the named member to its native sibling key so protojson sees a normal oneof.
  • recursion-depth placeholders: a message nested beyond MaxRecursionDepth renders as a JSON-string. This parses that string back to an object.

Everything else passes straight through to protojson untouched. Errors are phrased to be model-readable: a failed tool call is returned to the model for one-turn self-correction, so the message names the fix.

func DecodeResult

func DecodeResult(result json.RawMessage, msg proto.Message) error

DecodeResult unmarshals the JSON of a successful tool result, as written by EncodeMessage, into msg: it is the inverse of EncodeMessage, for clients. Oneof wrappers and recursion-depth placeholders are rewritten as in DecodeArguments. Unlike arguments, a result is not written by a model, so a string in a google.protobuf.Value stays a string. Unknown fields are ignored, as connect's JSON codec does.

func EncodeMessage

func EncodeMessage(msg proto.Message) (json.RawMessage, error)

EncodeMessage marshals a proto message to the model-facing JSON shape: it runs protojson, then rewraps each set oneof into its discriminated object and stringifies any subtree nested beyond DefaultMaxRecursionDepth so the output matches the tool's generated output schema. It is the encode-side inverse of DecodeArguments.

func HandleError

func HandleError(err error) (*mcpserver.CallToolResult, error)

HandleError converts an RPC error into a structured MCP tool error result: a JSON object with the error "code", "message" and, for connect errors carrying them, "details" (each rendered as protojson with an "@type").

It reveals exactly what connect-go's own server transports put on the wire for a handler error (see connecthttp's scrubHandlerError), so a server served as MCP discloses no more than it does over Connect, gRPC or gRPC-Web:

  • A locally authored *connect.Error anywhere in err's chain supplies the code, message and details. Text added by wrapping it (fmt.Errorf("...: %w", cerr)) and its WithCause cause are not shown.
  • A remote *connect.Error (one decoded from a peer, e.g. returned by a connect client) is reported as INTERNAL without a message: a peer's verdict is not the handler's own.
  • context.Canceled is CANCELED and context.DeadlineExceeded (or os.ErrDeadlineExceeded) is DEADLINE_EXCEEDED, without a message.
  • Any other error is UNKNOWN without a message.

Return connect.NewError(code, msg) to tell the model something; keep internals in err or in WithCause for logging.

func ParseError

func ParseError(text string) (*connect.Error, error)

ParseError parses the text of a tool error result written by HandleError back into the connect error it describes: it is the inverse of HandleError, for clients. The error has exactly the code, message and details in text and, being a peer's verdict, is marked remote. Text that is not such a tool error (not JSON, no known code, an unreadable detail) is reported with the second return value; nothing is assumed in its place.

func UnmarshalArguments

func UnmarshalArguments(args map[string]any, msg proto.Message) error

UnmarshalArguments unmarshals tool-call arguments, already rewritten by DecodeArguments, into msg. A failure is returned as an *ArgumentsError.

When a single field is to blame, the error names that field, the JSON shape it expects, and the shape that was sent.

Types

type ArgumentsError

type ArgumentsError struct {
	// Field is the path of the offending field as named in the tool's input
	// schema, e.g. "page_size" or "items[2].name". It is empty when no single
	// field is to blame.
	Field string
	// Description says what is wrong: with Field when it is set (e.g. `must
	// be an integer, but got the string "ten".`), otherwise with the
	// arguments as a whole.
	Description string
}

ArgumentsError is the reason tool-call arguments could not be decoded into the request message. Its Error text is phrased for the model, so it can see what was wrong and call the tool again with corrected arguments.

Use ConnectError to report it like any other failed call: as an INVALID_ARGUMENT connect error rendered by HandleError.

func (*ArgumentsError) ConnectError

func (e *ArgumentsError) ConnectError() *connect.Error

ConnectError returns e as an INVALID_ARGUMENT connect error with e's text as its message. When a single field is to blame, the error carries a google.rpc.BadRequest detail with one field violation for it.

func (*ArgumentsError) Error

func (e *ArgumentsError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL