mcp

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package mcp provides a transport-agnostic MCP server builder for go-codex.

Define tools, resources, and prompts declaratively with codec-backed types; register them with a Builder to obtain typed handles. Pass those handles to an MCP adapter (e.g. adapters/mcpgo) to wire them to a running server.

This package does not import any MCP SDK — it is framework-agnostic. The workflow is the same declare → register → handle pattern as api/rest and api/events:

// Layer 1: define codecs
inputCodec  := codex.Struct[CalcInput](...)
outputCodec := codex.Struct[CalcOutput](...)

// Layer 2: declare tools/resources/prompts as values
var calcTool = mcp.NewTool[CalcInput, CalcOutput]("calculate",
    inputCodec, outputCodec,
    mcp.ToolMeta{Description: "Perform arithmetic"},
)

var itemResource = mcp.NewResource[Item]("items://{id}", itemCodec,
    mcp.ResourceMeta{Name: "Item", MimeType: "application/json"},
    mcp.ResourceParam{Name: "id"}.WithCodec(uuidCodec),
)

var summaryPrompt = mcp.NewPrompt("summarize",
    mcp.PromptMeta{Description: "Summarize content"},
    mcp.PromptArg{Name: "content", Required: true},
)

// Register with a builder
b := mcp.NewBuilder(mcp.Info{Name: "My Server", Version: "1.0.0"})
toolHandle, _     := calcTool.Register(b)
resHandle, _      := itemResource.Register(b)
promptHandle, _   := summaryPrompt.Register(b)

// Spec generation (analogous to OpenAPISpec / AsyncAPISpec)
spec, _ := b.MCPSpec()

// Adapter layer (adapters/mcpgo):
// mcpgo.RegisterTool(s, toolHandle, fn, opts)
// mcpgo.RegisterResource(s, resHandle, fn, opts)
// mcpgo.RegisterPrompt(s, promptHandle, fn, opts)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder accumulates registered tools, resources, and prompts. Use NewBuilder to construct one, then pass it to Tool.Register, Resource.Register, and Prompt.Register.

func NewBuilder

func NewBuilder(info Info) *Builder

NewBuilder returns a new Builder with the given server info.

func (*Builder) Info

func (b *Builder) Info() Info

Info returns the server info this builder was created with.

func (*Builder) MCPSpec

func (b *Builder) MCPSpec() (*MCPSpec, error)

MCPSpec returns a static MCP API document listing all registered tools, resources, and prompts with their JSON Schemas.

The returned MCPSpec is analogous to the OpenAPI spec produced by [rest.Builder.OpenAPISpec] and the AsyncAPI spec from [events.Builder.AsyncAPISpec]. It is compatible with the MCP protocol tools/list, resources/list, and prompts/list response format.

Marshal to JSON for documentation, testing, or static analysis:

spec, _ := b.MCPSpec()
data, _ := json.MarshalIndent(spec, "", "  ")

type ErrorPatternOpt added in v0.12.0

type ErrorPatternOpt[E error, B any] struct {
	// contains filtered or unexported fields
}

ErrorPatternOpt is the ToolOpt value returned by ErrorPattern.

func ErrorPattern added in v0.12.0

func ErrorPattern[E error, B any](
	codec codex.Codec[B],
	mapFn ...func(E) (B, error),
) ErrorPatternOpt[E, B]

ErrorPattern declares a codec-backed typed error result for a matched handler error type — the MCP tool analogue of [rest.ErrorPattern] and [events.ErrorChannel]. MCP tool results have no HTTP status/reply topic; the declaration simply says "when the handler returns an error matching E, structure the tool's error result as this typed JSON payload instead of a bare error string."

Two modes, mirroring [rest.ErrorPattern]:

  • Direct: no mapFn provided, E must be assignable to B.
  • Mapped: mapFn(E) produces B.

Matching is type-only via errors.As; the first declared ErrorPattern (in NewTool option order) whose type matches wins — the same deterministic precedence used by REST/events/reqreply.

ErrorPattern only applies to errors returned by the application handler function (business logic) — input-decode failures and output-encode failures are different concerns and are not affected by ErrorPattern.

mcp.NewTool[SearchIn, SearchOut]("search", inCodec, outCodec,
    mcp.ErrorPattern[domain.NotFoundError, ErrorPayload](errorPayloadCodec,
        func(e domain.NotFoundError) (ErrorPayload, error) {
            return ErrorPayload{Code: "not_found", Message: e.Error()}, nil
        },
    ),
)

type ErrorPatternResponse added in v0.12.0

type ErrorPatternResponse struct {
	// Body is the JSON-encoded typed error payload.
	Body []byte
	// Value is the typed payload before encoding.
	Value any
}

ErrorPatternResponse is the adapter-ready payload produced by ToolHandle.ErrorResponseFor when a declared ErrorPattern matches.

type Info

type Info struct {
	Name    string
	Version string
}

Info holds the server name and version used in spec generation and adapter construction.

type InvalidResourceParamError

type InvalidResourceParamError struct {
	// Name is the ResourceParam variable name not found in the template.
	Name string
	// URITemplate is the URI template that was checked.
	URITemplate string
}

InvalidResourceParamError is returned by Resource.Register when a ResourceParam entry names a variable that does not appear in the URI template.

Use errors.As to extract the offending name and the URI template:

var paramErr mcp.InvalidResourceParamError
if errors.As(err, &paramErr) {
    log.Printf("ResourceParam %q not in URI template %q", paramErr.Name, paramErr.URITemplate)
}

func (InvalidResourceParamError) Error

func (InvalidResourceParamError) LogValue added in v0.11.0

func (e InvalidResourceParamError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

type MCPSpec

type MCPSpec struct {
	Name      string         `json:"name"`
	Version   string         `json:"version"`
	Tools     []ToolSpec     `json:"tools,omitempty"`
	Resources []ResourceSpec `json:"resources,omitempty"`
	Prompts   []PromptSpec   `json:"prompts,omitempty"`
}

MCPSpec is the static MCP API document produced by Builder.MCPSpec. It lists all registered tools, resources, and prompts with their schemas, and is compatible with the MCP protocol's list responses.

type MissingPromptArgError

type MissingPromptArgError struct {
	Name string
}

MissingPromptArgError is returned by PromptHandle.ValidateArgs when a required argument is absent from the provided args map.

Use errors.As to extract the missing argument name:

var me mcp.MissingPromptArgError
if errors.As(err, &me) {
    log.Printf("required prompt arg %q was not provided", me.Name)
}

func (MissingPromptArgError) Error

func (e MissingPromptArgError) Error() string

func (MissingPromptArgError) LogValue added in v0.11.0

func (e MissingPromptArgError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

type MissingResourceVarError

type MissingResourceVarError struct {
	Name string // the variable name (without braces) that had no value
}

MissingResourceVarError is returned by ResourceHandle.BuildURI when a {varName} placeholder in the URI template has no corresponding entry in the vars map.

Use errors.As to extract the missing variable name:

var missingErr mcp.MissingResourceVarError
if errors.As(err, &missingErr) {
    log.Printf("caller forgot to supply URI variable {%s}", missingErr.Name)
}

func (MissingResourceVarError) Error

func (e MissingResourceVarError) Error() string

func (MissingResourceVarError) LogValue added in v0.11.0

func (e MissingResourceVarError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

type Prompt

type Prompt struct {
	// contains filtered or unexported fields
}

Prompt is the declarative prompt descriptor. Construct with NewPrompt; register with Prompt.Register. Unlike Tool and Resource, Prompt has no generic type parameter because MCP prompt arguments are always string-valued (map[string]string).

func NewPrompt

func NewPrompt(name string, opts ...PromptOpt) Prompt

NewPrompt returns a declarative prompt descriptor. Call Prompt.Register to obtain a PromptHandle.

Use PromptMeta to provide documentation and PromptArg entries to declare the expected arguments with optional validation:

mcp.NewPrompt("summarize",
    mcp.PromptMeta{Description: "Summarize content"},
    mcp.PromptArg{Name: "content", Required: true},
    mcp.PromptArg{Name: "style"}.WithCodec(styleCodec),
)

func (Prompt) Register

func (p Prompt) Register(b *Builder) (*PromptHandle, error)

Register validates the prompt declaration and returns a PromptHandle. Returns an error if the prompt name is empty or already registered.

type PromptArg

type PromptArg struct {
	// Name is the argument name.
	Name string
	// Description is shown in the spec for this argument.
	Description string
	// Required, when true, causes [PromptHandle.ValidateArgs] to return
	// [MissingPromptArgError] when the argument is absent.
	Required bool
	// Codec, when non-nil, validates the argument value at
	// [PromptHandle.ValidateArgs] time.
	// Use [PromptArg.WithCodec] to set it without the address-of pattern.
	Codec *codex.Codec[string]
}

PromptArg describes a named argument for a prompt. Arguments are always string-valued in the MCP protocol. Use PromptArg.WithCodec to attach a string codec for runtime validation.

PromptArg implements PromptOpt.

func (PromptArg) WithCodec

func (a PromptArg) WithCodec(c codex.Codec[string]) PromptArg

WithCodec sets the validation codec and returns the updated PromptArg. Use this instead of setting Codec directly:

mcp.PromptArg{Name: "style", Required: false}.WithCodec(styleCodec)

type PromptArgError

type PromptArgError struct {
	// Name is the argument name.
	Name string
	// Err is the underlying codec constraint error.
	Err error
}

PromptArgError is returned by PromptHandle.ValidateArgs when an argument fails its registered codec constraint.

Use errors.As to extract the argument name and underlying error:

var pe mcp.PromptArgError
if errors.As(err, &pe) {
    log.Printf("prompt arg %q failed: %v", pe.Name, pe.Err)
}

func (PromptArgError) Error

func (e PromptArgError) Error() string

func (PromptArgError) LogValue added in v0.11.0

func (e PromptArgError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (PromptArgError) Unwrap

func (e PromptArgError) Unwrap() error

type PromptArgSpec

type PromptArgSpec struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

PromptArgSpec describes one argument of a prompt in MCPSpec.

type PromptHandle

type PromptHandle struct {
	// Name is the prompt name as registered with the Builder.
	Name string
	// Description is the human-readable prompt description.
	Description string
	// Tags are arbitrary labels for this prompt.
	Tags []string
	// Args is the ordered list of declared prompt arguments.
	// The MCP adapter uses this to populate the prompt's argument list in
	// the spec and to validate incoming arguments.
	Args []PromptArg
}

PromptHandle is returned by Prompt.Register. It carries the declared argument metadata and the PromptHandle.ValidateArgs helper.

func (*PromptHandle) ValidateArgs

func (h *PromptHandle) ValidateArgs(argsMap map[string]string) error

ValidateArgs validates the provided args map against the declared PromptArg definitions: required args must be present, and args with a non-nil Codec are validated against it.

A present-but-empty string is treated as a valid value and passed to the codec; the codec decides whether "" is acceptable. Only a missing key triggers MissingPromptArgError for required args.

Returns MissingPromptArgError for absent required args; PromptArgError for codec failures.

type PromptMeta

type PromptMeta struct {
	// Description is a human-readable description of what the prompt does.
	Description string
	// Tags are arbitrary labels for this prompt for categorisation.
	Tags []string
}

PromptMeta holds prompt-level documentation metadata. Pass it directly to NewPrompt as a variadic option.

PromptMeta implements PromptOpt.

type PromptOpt

type PromptOpt interface {
	// contains filtered or unexported methods
}

PromptOpt is the sealed interface for NewPrompt options.

The following types implement PromptOpt:

  • PromptMeta — prompt-level metadata (description)
  • PromptArg — named argument with optional codec and required flag

type PromptSpec

type PromptSpec struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Tags        []string        `json:"tags,omitempty"`
	Args        []PromptArgSpec `json:"arguments,omitempty"`
}

PromptSpec is the spec entry for a single prompt in MCPSpec.

type Resource

type Resource[T any] struct {
	// contains filtered or unexported fields
}

Resource[T] is the declarative resource descriptor. Construct with NewResource; register with Resource.Register.

func NewResource

func NewResource[T any](uriTemplate string, codec codex.Codec[T], opts ...ResourceOpt) Resource[T]

NewResource returns a declarative resource descriptor. uriTemplate may contain {varName} placeholders (e.g. "items://{id}"). Call Resource.Register to obtain a ResourceHandle.

codec validates the value returned by the resource handler before it is serialised as resource content.

func (Resource[T]) Register

func (r Resource[T]) Register(b *Builder) (*ResourceHandle[T], error)

Register validates the resource declaration and returns a ResourceHandle. Returns an error if the URI template is empty or unknown {varName} placeholders are found in uriParams that do not appear in the template.

type ResourceEncodeError

type ResourceEncodeError struct {
	// URI is the resource URI template.
	URI string
	// Err is the underlying codec validation or marshal error.
	Err error
}

ResourceEncodeError is returned by ResourceHandle.Encode when the resource value fails codec validation or cannot be marshalled.

Use errors.As to extract the URI template and underlying error:

var ree mcp.ResourceEncodeError
if errors.As(err, &ree) {
    log.Printf("resource %s: encode failed: %v", ree.URI, ree.Err)
}

func (ResourceEncodeError) Error

func (e ResourceEncodeError) Error() string

func (ResourceEncodeError) LogValue added in v0.11.0

func (e ResourceEncodeError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (ResourceEncodeError) Unwrap

func (e ResourceEncodeError) Unwrap() error

type ResourceHandle

type ResourceHandle[T any] struct {
	// URITemplate is the registered URI template (may contain {varName} placeholders).
	URITemplate string
	// Name is the short display name for this resource.
	Name string
	// Description is the human-readable resource description.
	Description string
	// MimeType is the content type of this resource.
	MimeType string
	// Tags are arbitrary labels for this resource.
	Tags []string

	// Encode validates v via the codec and marshals it to JSON bytes.
	// Errors are wrapped as [ResourceEncodeError].
	Encode func(v T) ([]byte, error)
	// contains filtered or unexported fields
}

ResourceHandle[T] is returned by Resource.Register. It provides:

func (*ResourceHandle[T]) BuildURI

func (h *ResourceHandle[T]) BuildURI(vars map[string]string) (string, error)

BuildURI substitutes {varName} placeholders in ResourceHandle.URITemplate with the values provided in vars, validating each against its registered codec.

All template variables must be present in vars; missing variables return a MissingResourceVarError. Values are validated before substitution; codec failures return a ResourceParamError. Keys in vars that do not appear in the template are silently ignored.

Example:

uri, err := itemResource.BuildURI(map[string]string{"id": "abc-123"})
// uri = "items://abc-123"

func (*ResourceHandle[T]) ExtractURIVars added in v0.12.0

func (h *ResourceHandle[T]) ExtractURIVars(uri string) (map[string]string, error)

ExtractURIVars is the inverse of ResourceHandle.BuildURI: it matches a concrete, received URI against ResourceHandle.URITemplate and returns the extracted {varName} placeholder values, ALREADY validated against every registered ResourceParam codec via ResourceHandle.ValidateURIVars — one call replaces "parse the URI yourself" + "remember to call ValidateURIVars yourself" (adapters/mcpgo.ResourceHandler calls this automatically; see [mcpgo.ResourceVarsHandlerFunc]).

Returns ResourceURIMismatchError if uri does not match the template's structure (wrong number of segments, or a literal segment does not match). Returns ResourceParamError/MissingResourceVarError if an extracted variable fails its registered codec (via ResourceHandle.ValidateURIVars).

Example:

vars, err := itemResource.ExtractURIVars("items://abc-123")
// vars["id"] == "abc-123"

func (*ResourceHandle[T]) ValidateURIVars

func (h *ResourceHandle[T]) ValidateURIVars(vars map[string]string) error

ValidateURIVars validates extracted URI variable values against registered ResourceParam codecs. Call this after extracting vars from a received URI to ensure each variable satisfies its codec constraints.

Returns ResourceParamError for the first variable that fails its codec. Variables without a registered codec are skipped.

type ResourceMeta

type ResourceMeta struct {
	// Name is a short human-readable name for this resource (e.g. "User Profile").
	Name string
	// Description is a human-readable description of what this resource represents.
	Description string
	// MimeType is the MIME type of the resource content (e.g. "application/json").
	MimeType string
	// Tags are arbitrary labels for this resource for categorisation.
	Tags []string
}

ResourceMeta holds resource-level documentation metadata. Pass it directly to NewResource as a variadic option.

ResourceMeta implements ResourceOpt.

type ResourceOpt

type ResourceOpt interface {
	// contains filtered or unexported methods
}

ResourceOpt is the sealed interface for NewResource options.

The following types implement ResourceOpt:

  • ResourceMeta — resource-level metadata (name, description, mimeType)
  • ResourceParam — URI template variable with optional codec

type ResourceParam

type ResourceParam struct {
	// Name is the variable name (without braces) as it appears in the URI template.
	Name string
	// Description is shown in the spec for this parameter.
	Description string
	// Codec validates URI parameter values at [ResourceHandle.ValidateURIVars]
	// and [ResourceHandle.BuildURI] time. Nil means no runtime validation.
	Codec *codex.Codec[string]
}

ResourceParam describes a {varName} placeholder in a resource URI template. It optionally carries a codec for runtime validation of the variable value.

ResourceParam implements ResourceOpt.

func (ResourceParam) WithCodec

func (p ResourceParam) WithCodec(c codex.Codec[string]) ResourceParam

WithCodec sets the validation codec and returns the updated ResourceParam. Use this instead of setting Codec directly to avoid the address-of pattern:

mcp.ResourceParam{Name: "id"}.WithCodec(uuidCodec)

type ResourceParamError

type ResourceParamError struct {
	Name  string // variable name without braces
	Value string // the value that failed validation
	Err   error  // the underlying constraint or codec error
}

ResourceParamError is returned by ResourceHandle.BuildURI or ResourceHandle.ValidateURIVars when a URI variable fails its registered codec constraint.

Use errors.As to extract the failing variable name and value:

var paramErr mcp.ResourceParamError
if errors.As(err, &paramErr) {
    log.Printf("bad value %q for {%s}: %v", paramErr.Value, paramErr.Name, paramErr.Err)
}

func (ResourceParamError) Error

func (e ResourceParamError) Error() string

func (ResourceParamError) LogValue added in v0.11.0

func (e ResourceParamError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (ResourceParamError) Unwrap

func (e ResourceParamError) Unwrap() error

type ResourceSpec

type ResourceSpec struct {
	URITemplate string   `json:"uriTemplate"`
	Name        string   `json:"name,omitempty"`
	Description string   `json:"description,omitempty"`
	MimeType    string   `json:"mimeType,omitempty"`
	Tags        []string `json:"tags,omitempty"`
}

ResourceSpec is the spec entry for a single resource in MCPSpec.

type ResourceURIMismatchError added in v0.12.0

type ResourceURIMismatchError struct {
	Template string // the resource's URI template (e.g. "items://{id}")
	URI      string // the received concrete URI (e.g. "items://abc-123/extra")
}

ResourceURIMismatchError is returned by ResourceHandle.ExtractURIVars when a received URI does not match the structure of the resource's URI template (wrong number of segments, or a literal segment does not match). Mirrors adapters/mqtt5.TopicMismatchError/adapters/mqtt.TopicMismatchError/ ports.FilePathMismatchError exactly.

Use errors.As to inspect the mismatched URI:

var mm mcp.ResourceURIMismatchError
if errors.As(err, &mm) {
    log.Printf("URI %q does not match template %q", mm.URI, mm.Template)
}

func (ResourceURIMismatchError) Error added in v0.12.0

func (e ResourceURIMismatchError) Error() string

func (ResourceURIMismatchError) LogValue added in v0.12.0

func (e ResourceURIMismatchError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

type Tool

type Tool[In, Out any] struct {
	// contains filtered or unexported fields
}

Tool[In, Out] is the declarative tool descriptor. Construct with NewTool; register with Tool.Register. A Tool value can be stored as a package-level variable and registered with multiple builders.

func NewTool

func NewTool[In, Out any](name string, inputCodec codex.Codec[In], outputCodec codex.Codec[Out], opts ...ToolOpt) Tool[In, Out]

NewTool returns a declarative tool descriptor that encodes and decodes via inputCodec and outputCodec respectively. Call Tool.Register to obtain a ToolHandle for use with an adapter.

name must be non-empty. inputCodec drives input validation and the JSON Schema shown to MCP clients. outputCodec validates handler output before it is serialised into the tool result.

Example
package main

import (
	"fmt"

	apimcp "github.com/DaniDeer/go-codex/api/mcp"
	"github.com/DaniDeer/go-codex/codex"
	"github.com/DaniDeer/go-codex/validate"
)

func main() {
	type SearchReq struct{ Query string }
	type SearchResp struct{ Count int }

	reqCodec := codex.Struct[SearchReq](
		codex.RequiredField("query", codex.String().Refine(validate.NonEmptyString),
			func(r SearchReq) string { return r.Query },
			func(r *SearchReq, v string) { r.Query = v },
		),
	)
	respCodec := codex.Struct[SearchResp](
		codex.RequiredField("count", codex.Int(),
			func(r SearchResp) int { return r.Count },
			func(r *SearchResp, v int) { r.Count = v },
		),
	)

	// Declare the tool as a value — define once, register anywhere.
	searchTool := apimcp.NewTool[SearchReq, SearchResp]("search",
		reqCodec, respCodec,
		apimcp.ToolMeta{Description: "Search the knowledge base."},
	)

	b := apimcp.NewBuilder(apimcp.Info{Name: "My Server", Version: "1.0.0"})
	handle, err := searchTool.Register(b)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	// Decode tool arguments — validated against codec constraints.
	req, err := handle.Decode(map[string]any{"query": "go-codex"})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(req.Query)

	// Missing required field returns a typed error.
	_, err = handle.Decode(map[string]any{})
	fmt.Println(err != nil)
}
Output:
go-codex
true

func (Tool[In, Out]) ClientHandle added in v0.11.0

func (t Tool[In, Out]) ClientHandle() (*ToolHandle[In, Out], error)

ClientHandle returns a ToolHandle without registering with a Builder. No duplicate-name check and no spec registration occur.

Use ClientHandle when only the codec-backed Decode/Encode helpers and rendered schemas are needed (no MCP spec document), or when constructing a tool handle outside of a Builder-managed registration flow.

Mirrors [rest.Route.ClientHandle], [events.Channel.ClientHandle], and [reqreply.Route.ClientHandle].

func (Tool[In, Out]) Register

func (t Tool[In, Out]) Register(b *Builder) (*ToolHandle[In, Out], error)

Register validates the tool declaration, renders the input/output JSON Schemas, and returns a ToolHandle. Returns an error if the tool name is empty or already registered with b.

type ToolHandle

type ToolHandle[In, Out any] struct {
	// Name is the tool name as registered with the Builder.
	Name string
	// Description is the human-readable tool description.
	Description string
	// Tags are arbitrary labels for this tool.
	Tags []string
	// InputSchema is the JSON Schema derived from the input codec.
	// The MCP adapter sets this on the tool descriptor shown to clients.
	InputSchema json.RawMessage
	// OutputSchema is the JSON Schema derived from the output codec.
	// May be nil when the output codec has no schema (e.g. codex.Any()).
	OutputSchema json.RawMessage

	// Decode deserialises and validates args (the intermediate map[string]any
	// decoded from the MCP call's JSON arguments) into In.
	// All codec Refine constraints run automatically.
	// Errors are wrapped as [ToolInputError].
	Decode func(args any) (In, error)

	// Encode validates out via the output codec and marshals it to JSON bytes
	// for inclusion in the MCP tool result.
	// Errors are wrapped as [ToolOutputError].
	Encode func(out Out) ([]byte, error)
	// contains filtered or unexported fields
}

ToolHandle[In, Out] is returned by Tool.Register. It provides:

  • Typed ToolHandle.Decode and ToolHandle.Encode helpers backed by the declared codecs.
  • Rendered JSON Schemas for use by the MCP adapter.
  • Metadata (Name, Description, Tags) for spec generation.

func (*ToolHandle[In, Out]) ErrorResponseFor added in v0.12.0

func (h *ToolHandle[In, Out]) ErrorResponseFor(err error) (ErrorPatternResponse, bool, error)

ErrorResponseFor returns the first declared ErrorPattern match for err (matching via errors.As, in declaration order), or (ErrorPatternResponse{}, false, nil) when none match.

A non-nil third return value indicates the matched pattern's mapping or encoding failed — callers should treat this as a terminal error for that pattern (do not fall through to other patterns).

type ToolInputError

type ToolInputError struct {
	// Name is the tool name as registered with the Builder.
	Name string
	// Err is the underlying codec validation or decode error.
	Err error
}

ToolInputError is returned by ToolHandle.Decode when the incoming arguments fail codec validation or cannot be decoded into the input type. Use errors.As to extract the name and underlying error:

var tie mcp.ToolInputError
if errors.As(err, &tie) {
    log.Printf("tool %s: bad input: %v", tie.Name, tie.Err)
}

func (ToolInputError) Error

func (e ToolInputError) Error() string

func (ToolInputError) LogValue added in v0.11.0

func (e ToolInputError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (ToolInputError) Unwrap

func (e ToolInputError) Unwrap() error

type ToolMeta

type ToolMeta struct {
	// Description is a human-readable description of what the tool does.
	// Shown to LLM clients to help them decide when to call the tool.
	Description string
	// Tags are arbitrary labels attached to the tool for categorisation.
	Tags []string
}

ToolMeta holds tool-level documentation metadata. Pass it directly to NewTool as a variadic option.

ToolMeta implements ToolOpt.

type ToolOpt

type ToolOpt interface {
	// contains filtered or unexported methods
}

ToolOpt is the sealed interface for NewTool options.

The following types implement ToolOpt:

  • ToolMeta — tool-level documentation (description, tags)
  • ErrorPattern — codec-backed typed error result for a matched handler error

type ToolOutputError

type ToolOutputError struct {
	// Name is the tool name as registered with the Builder.
	Name string
	// Err is the underlying codec validation or marshal error.
	Err error
}

ToolOutputError is returned by ToolHandle.Encode when the handler's return value fails codec validation or cannot be marshalled to JSON. This indicates a server-side contract violation — the handler returned data that does not satisfy the declared output codec constraints.

Use errors.As to extract the tool name and underlying error:

var toe mcp.ToolOutputError
if errors.As(err, &toe) {
    log.Printf("tool %s: bad output: %v", toe.Name, toe.Err)
}

func (ToolOutputError) Error

func (e ToolOutputError) Error() string

func (ToolOutputError) LogValue added in v0.11.0

func (e ToolOutputError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (ToolOutputError) Unwrap

func (e ToolOutputError) Unwrap() error

type ToolSpec

type ToolSpec struct {
	Name         string          `json:"name"`
	Description  string          `json:"description,omitempty"`
	Tags         []string        `json:"tags,omitempty"`
	InputSchema  json.RawMessage `json:"inputSchema,omitempty"`
	OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
}

ToolSpec is the spec entry for a single tool in MCPSpec.

Jump to

Keyboard shortcuts

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