Skip to content

Construct a result

Use Go 1.27.1 or later in this checkout. The module has not been released, so run its examples locally with go test -run '^Example' ./... rather than depending on a published version.

A result contains ordered content and an optional structured JSON value:

result, err := mcp.NewResult(
    []mcp.Content{mcp.Text("Selected candidate")},
    mcp.WithStructured(json.RawMessage(`{"id":9007199254740993}`)),
)
if err != nil {
    return err
}
raw, present := result.Structured()
fmt.Println(present, string(raw))
// true {"id":9007199254740993}

Import encoding/json, fmt and gitlab.com/phpboyscout/go/mcp. The complete runnable version is ExampleNewResult in example_test.go.

WithStructured copies its argument immediately. Changing that buffer afterward cannot alter the option or result. Structured returns a fresh copy, and the boolean distinguishes no structured value from an explicit JSON null. JSON objects, arrays, scalars and null are accepted; malformed JSON and duplicate object member names are rejected.

For a Go value that has not already been encoded, use JSONResult(value, content...). It marshals once and does not add duplicate text content. TextResult(text) stays unstructured even when the text looks like JSON. NewResult(nil) is an intentional empty result; an unconstructed Result{} is not suitable for later invocation.

For an application failure, supply a message that is safe for the caller:

failure := mcp.NewFailure(mcp.FailureReadFailed, "Preview temporarily unavailable", cause)

Error and Message expose only the safe message. The host can still use errors.Is and errors.As to inspect the private cause. Retryable is true for busy and read-failed codes; callers decide whether an explicit retry is appropriate. Nothing in the value layer performs a retry.