mcpservice

package
v0.8.4 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2025 License: MIT Imports: 24 Imported by: 1

Documentation

Overview

Package mcpserver defines the capability interfaces that an MCP Server implementation exposes to the Streaming HTTP handler in this repository.

The handler discovers capabilities at runtime on a per-session basis, and translates method calls on these interfaces into MCP JSON-RPC messages as defined by the MCP specification (see docs/mcp.md). Implementations may be static (same capabilities for all sessions) or dynamic (vary by session) but MUST be safe for concurrent use and respect the provided context for cancellation and deadlines.

Conventions used throughout this package:

  • Capability discovery methods return (cap, ok, err). A false ok indicates that the capability is not supported for the given session; err should be reserved for transient or internal failures while determining support.
  • All methods accept a context.Context which MUST be honored for cancellation. Implementations should return promptly when the context is canceled or its deadline is exceeded.
  • The sessions.Session value is the unit of isolation. Implementations SHOULD treat it as the boundary for authorization, tenancy and resource visibility.
  • Pagination uses the Page[T] type in this package; a nil cursor requests the first page. Implementations SHOULD populate NextCursor when more data is available.

Package mcpservice provides the public server capability layer for MCP. It defines capability interfaces (tools, resources, prompts, logging, completions) plus composable helpers for building either static (predefined) or dynamic (per-session) implementations. Transports (streaming HTTP, stdio) depend on this package to discover what a server supports for a negotiated session and translate JSON-RPC method calls into interface invocations.

Relationship to Other Packages

mcp         -> raw protocol types (requests/results, enums)
mcpservice  -> capability interfaces & helpers
sessions    -> session abstraction + host persistence
streaminghttp / stdio -> transport binding using an Engine internally

Capability Discovery

The ServerCapabilities interface is the root entry point: transports call getters (e.g. GetToolsCapability) per session to obtain concrete capability values. Each getter returns (cap, ok, err) allowing a server to omit capabilities or fail transiently without forcing a global shape.

Static vs Dynamic Implementations

Static helpers (ToolsContainer, ResourcesContainer, PromptsContainer) manage an internal thread-safe set and optionally emit change notifications. Dynamic helpers (NewDynamicTools, NewDynamicResources, NewDynamicPrompts) accept functional options representing custom list/read/call logic; they’re ideal for multi-tenant or data-driven servers.

Summary (Capabilities vs Helpers):

Capability   | Static Container          | Dynamic Builder
-------------|---------------------------|-----------------------------
Tools        | ToolsContainer            | NewDynamicTools(...options)
Resources    | ResourcesContainer / FS   | NewDynamicResources(...)
Prompts      | PromptsContainer          | NewDynamicPrompts(...)
Logging      | NewSlogLevelVarLogging    | (implement interface)
Completions  | (implement interface)     | (implement interface)

Pagination

All list operations return a Page[T] with an optional NextCursor. Static containers use in-memory slices; dynamic implementations decide their own cursor encoding. A nil cursor requests the first page.

Change Notifications

Containers embed a ChangeNotifier and expose it through GetListChangedCapability so transports can advertise listChanged support. Dynamic variants opt-in by providing a ChangeSubscriber via option.

Progress Reporting

Long-running tool handlers can retrieve a ProgressReporter (transport bound) from context using ReportProgress helper functions (see progress.go) while streaming partial textual results through ToolResponseWriter.

Examples

Static tools + dynamic resources illustrating mixed mode:

// Static echo tool
type EchoArgs struct { Message string `json:"message"` }
tools := mcpservice.NewToolsContainer(
    mcpservice.TypedTool[EchoArgs](
        mcp.Tool{
            Name: "echo",
            Description: "Echo a message back",
            InputSchema: mcp.ToolInputSchema{Type: "object", Properties: map[string]mcp.SchemaProperty{
                "message": {Type: "string"},
            }, Required: []string{"message"}},
        },
        func(ctx context.Context, s sessions.Session, a EchoArgs) (*mcp.CallToolResult, error) {
            return mcpservice.TextResult(a.Message), nil
        },
    ),
)

// Dynamic per-session resources (user-scoped)
dynRes := func(ctx context.Context, s sessions.Session) (mcpservice.ResourcesCapability, bool, error) {
    return mcpservice.NewDynamicResources(
        mcpservice.WithResourcesListFunc(func(ctx context.Context, _ sessions.Session, c *string) (mcpservice.Page[mcp.Resource], error) {
            uri := "res://user/"+s.UserID()+"/profile"
            return mcpservice.NewPage([]mcp.Resource{{URI: uri, Name: "profile"}}), nil
        }),
        mcpservice.WithResourcesReadFunc(func(ctx context.Context, _ sessions.Session, uri string) ([]mcp.ResourceContents, error) {
            if !strings.Contains(uri, s.UserID()) { return nil, fmt.Errorf("not found") }
            return []mcp.ResourceContents{{URI: uri, Text: "dynamic content"}}, nil
        }),
    ), true, nil
}

server := mcpservice.NewServer(
    mcpservice.WithServerInfo(mcp.ImplementationInfo{Name: "example", Version: "0.1.0"}),
    mcpservice.WithToolsCapability(tools),
    mcpservice.WithResourcesProvider(dynRes),
)

Implementing a custom capability: write a struct satisfying the interface (e.g. ToolsCapability) and return it from the corresponding getter option.

Error Semantics (selector table):

Context cancellation / deadline -> return ctx.Err()
Not found                       -> wrap / return descriptive error (transport relays message)
Validation issues               -> return error; transport surfaces JSON-RPC error
Internal unexpected             -> return error; log at call site

The package avoids opinionated error types; callers can wrap errors with additional context. Transports treat all non-nil errors as JSON-RPC errors.

Package mcpservice exposes composable building blocks for implementing the MCP server side. Capabilities (resources, tools, prompts, etc.) are surfaced through minimal provider interfaces that can be satisfied by either a static singleton value, a container type that also acts as its own provider, or a small closure performing per-session selection.

The unified provider pattern keeps the option surface tight (only one WithXCapability per capability) while supporting:

  • Static constants: use the StaticX helper (e.g. StaticProtocolVersion("2025-06-18"))
  • Self-providing containers: pass *ToolsContainer / *ResourcesContainer directly
  • Dynamic logic: supply an XProviderFunc that inspects session metadata

Providers return (value, ok, error). ok == false means “capability absent”. An empty value with ok == true is still advertised (e.g. empty tools list).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrFinalized is returned when attempting to write after Result() was called.
	ErrFinalized = errors.New("result already finalized")
)
View Source
var ErrInvalidLoggingLevel = errors.New("invalid logging level")

ErrInvalidLoggingLevel indicates the provided level is not one of the protocol-defined LoggingLevel values.

Functions

func Errorf

func Errorf(format string, a ...any) *mcp.CallToolResult

Errorf returns an error CallToolResult with a single text block and IsError=true.

func JSONMessages added in v0.2.0

func JSONMessages(msgs []mcp.PromptMessage) json.RawMessage

JSON helper for building prompt messages easily

func NewDynamicResources added in v0.5.0

func NewDynamicResources(opts ...DynamicResourcesOption) *dynamicResources

func ReportProgress added in v0.3.0

func ReportProgress(ctx context.Context, progress, total float64) bool

ReportProgress is a convenience helper that looks up a ProgressReporter from context and reports the provided values. It returns true if a reporter was present and the call was attempted, and false if no reporter was found. Any transport error is ignored here; use ProgressFrom(ctx) directly for full control.

func TextResult

func TextResult(s string) *mcp.CallToolResult

TextResult is a small helper to build a text CallToolResult.

func WithProgressReporter added in v0.3.0

func WithProgressReporter(ctx context.Context, pr ProgressReporter) context.Context

WithProgressReporter returns a new context carrying the provided reporter.

Types

type CallToolFunc

type CallToolFunc func(ctx context.Context, session sessions.Session, req *mcp.CallToolRequestReceived) (*mcp.CallToolResult, error)

CallToolFunc executes a tool invocation.

type CancelSubscription

type CancelSubscription func(ctx context.Context) error

CancelSubscription cancels an active subscription. It MUST be idempotent and safe to call multiple times. Implementations may return an error for logging or diagnostics; callers should treat cancellation as best-effort.

type ChangeNotifier

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

ChangeNotifier provides a simple in-process pub-sub for change events. It is used by static containers and capabilities to signal that a list has changed so that listChanged notifications can be sent to clients.

func (*ChangeNotifier) Close

func (cn *ChangeNotifier) Close()

func (*ChangeNotifier) Notify

func (cn *ChangeNotifier) Notify(ctx context.Context) error

Notify triggers a notification to all registered listeners that a set of resources has been invalidated or has changed. It returns nil always; the error return exists only for future expansion (e.g. context-based cancellation semantics). Callers may safely ignore the returned error.

func (*ChangeNotifier) Subscriber

func (cn *ChangeNotifier) Subscriber() <-chan struct{}

Subscriber returns a channel that receives a signal whenever Notify is called. The returned channel is buffered with capacity 1 to avoid blocking callers.

type ChangeSubscriber

type ChangeSubscriber interface {
	Subscriber() <-chan struct{}
}

type CompletionsCapability added in v0.3.0

type CompletionsCapability interface {
	// Complete returns completion suggestions for the provided request.
	Complete(ctx context.Context, session sessions.Session, req *mcp.CompleteRequest) (*mcp.CompleteResult, error)
}

CompletionsCapability enables argument autocompletion suggestions for prompts and resource template arguments. Implementations SHOULD validate the reference and argument values and return suggestions consistent with the MCP spec. Implementations MUST be safe for concurrent use.

type CompletionsCapabilityProvider added in v0.6.0

type CompletionsCapabilityProvider interface {
	ProvideCompletions(ctx context.Context, session sessions.Session) (CompletionsCapability, bool, error)
}

CompletionsCapabilityProvider yields the (experimental) completions capability.

func StaticCompletions added in v0.6.0

type CompletionsCapabilityProviderFunc added in v0.6.0

type CompletionsCapabilityProviderFunc func(ctx context.Context, session sessions.Session) (CompletionsCapability, bool, error)

func (CompletionsCapabilityProviderFunc) ProvideCompletions added in v0.6.0

type ContainerOption added in v0.8.0

type ContainerOption func(*resourcesContainerConfig)

func WithPageSize

func WithPageSize(n int) ContainerOption

WithPageSize sets initial pagination size. Values <1 ignored (default 50).

type ContentVariant added in v0.8.0

type ContentVariant struct {
	Text     string
	Blob     []byte
	MimeType string
}

ContentVariant represents one textual or binary variant of a resource. Text and Blob are mutually exclusive; if both are populated Text takes precedence. MimeType overrides the parent Resource.MimeType when non-empty.

func BlobVariant added in v0.8.0

func BlobVariant(data []byte, mime string) ContentVariant

func TextVariant added in v0.8.0

func TextVariant(text string, mime ...string) ContentVariant

type DynamicPromptsOption added in v0.5.0

type DynamicPromptsOption func(*dynamicPrompts)

func WithPromptsChangeSubscriber added in v0.5.0

func WithPromptsChangeSubscriber(sub ChangeSubscriber) DynamicPromptsOption

func WithPromptsGetFunc added in v0.5.0

func WithPromptsGetFunc(fn GetPromptFunc) DynamicPromptsOption

func WithPromptsListFunc added in v0.5.0

func WithPromptsListFunc(fn ListPromptsFunc) DynamicPromptsOption

type DynamicResourcesOption added in v0.5.0

type DynamicResourcesOption func(*dynamicResources)

func WithResourcesChangeSubscriber added in v0.5.0

func WithResourcesChangeSubscriber(sub ChangeSubscriber) DynamicResourcesOption

func WithResourcesListFunc added in v0.5.0

func WithResourcesListFunc(fn ListResourcesFunc) DynamicResourcesOption

func WithResourcesListTemplatesFunc added in v0.5.0

func WithResourcesListTemplatesFunc(fn ListResourceTemplatesFunc) DynamicResourcesOption

func WithResourcesReadFunc added in v0.5.0

func WithResourcesReadFunc(fn ReadResourceFunc) DynamicResourcesOption

func WithResourcesSubscriptionCapability added in v0.5.0

func WithResourcesSubscriptionCapability(cap ResourceSubscriptionCapability) DynamicResourcesOption

type DynamicToolsOption added in v0.5.0

type DynamicToolsOption func(*dynamicTools)

DynamicToolsOption configures a dynamically implemented tools capability.

func WithToolsCallFn added in v0.5.0

func WithToolsCallFn(fn CallToolFunc) DynamicToolsOption

WithToolsCallFn sets the call function for a dynamic tools capability.

func WithToolsChangeSubscriber added in v0.5.0

func WithToolsChangeSubscriber(sub ChangeSubscriber) DynamicToolsOption

WithToolsChangeSubscriber wires a ChangeSubscriber for listChanged notifications.

func WithToolsListFn added in v0.5.0

func WithToolsListFn(fn ListToolsFunc) DynamicToolsOption

WithToolsListFn sets the listing function for a dynamic tools capability.

type FSOption

type FSOption func(*FSResources)

FSOption configures FSResources.

func WithBaseURI

func WithBaseURI(base string) FSOption

WithBaseURI sets the URI prefix used in Resource.URI, e.g. "fs://workspace". Defaults to "fs://".

func WithFS

func WithFS(f fs.FS) FSOption

WithFS provides a generic fs.FS (e.g., embed.FS). Parent traversal is rejected and symlinks are not followed.

func WithFSPageSize

func WithFSPageSize(n int) FSOption

WithFSPageSize sets the paging page size. Defaults to 50.

func WithOSDir

func WithOSDir(root string) FSOption

WithOSDir sets the root to an OS directory. The path must exist. Symlinks are resolved and reads are constrained to the resolved root.

func WithPolling

func WithPolling(interval time.Duration) FSOption

WithPolling enables list-changed notifications using naive polling at the provided interval. Polling starts lazily on the first Register call and stops when its context is canceled. Defaults to disabled.

func WithUpdateDebounce

func WithUpdateDebounce(d time.Duration) FSOption

WithUpdateDebounce configures the per-URI update debounce interval. Set to 0 to disable debouncing.

type FSResources

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

FSResources provides a concrete ResourcesCapability over a restricted slice of a filesystem. It can wrap either an os dir (preferred when you need to defend against symlink escape) or an arbitrary fs.FS (such as embed.FS).

Security: When configured with an OS directory root, FSResources prevents traversal outside the configured root, even through symlinks. When configured with a generic fs.FS, symlinks are not followed and parent traversal is rejected.

func NewFSResources

func NewFSResources(opts ...FSOption) *FSResources

NewFSResources constructs a filesystem-backed resources capability.

func (*FSResources) GetListChangedCapability

func (r *FSResources) GetListChangedCapability(ctx context.Context, _ sessions.Session) (ResourceListChangedCapability, bool, error)

GetListChangedCapability implements ResourcesCapability. When polling is configured, we expose a listChanged capability powered by ChangeNotifier.

func (*FSResources) GetSubscriptionCapability

func (r *FSResources) GetSubscriptionCapability(ctx context.Context, _ sessions.Session) (ResourceSubscriptionCapability, bool, error)

GetSubscriptionCapability implements ResourcesCapability. This filesystem implementation does not support per-URI subscriptions.

func (*FSResources) ListResourceTemplates

func (r *FSResources) ListResourceTemplates(ctx context.Context, _ sessions.Session, cursor *string) (Page[mcp.ResourceTemplate], error)

ListResourceTemplates implements ResourcesCapability.

func (*FSResources) ListResources

func (r *FSResources) ListResources(ctx context.Context, _ sessions.Session, cursor *string) (Page[mcp.Resource], error)

ListResources implements ResourcesCapability.

func (*FSResources) ProvideResources added in v0.6.0

func (r *FSResources) ProvideResources(ctx context.Context, session sessions.Session) (ResourcesCapability, bool, error)

ProvideResources allows *FSResources to satisfy ResourcesCapabilityProvider.

func (*FSResources) ReadResource

func (r *FSResources) ReadResource(ctx context.Context, _ sessions.Session, uri string) ([]mcp.ResourceContents, error)

ReadResource implements ResourcesCapability.

func (*FSResources) SubscriberForURI

func (r *FSResources) SubscriberForURI(uri string) <-chan struct{}

SubscriberForURI exposes a change subscriber channel for the given URI. It is used by the HTTP handler to bridge server-local update signals to client-facing notifications. Safe for concurrent use.

type GetPromptFunc added in v0.2.0

type GetPromptFunc func(ctx context.Context, session sessions.Session, req *mcp.GetPromptRequestReceived) (*mcp.GetPromptResult, error)

type InstructionsProvider added in v0.6.0

type InstructionsProvider interface {
	ProvideInstructions(ctx context.Context, session sessions.Session) (string, bool, error)
}

InstructionsProvider supplies optional human-readable instructions returned in initialize. Return ok=false to omit the field.

func StaticInstructions added in v0.6.0

func StaticInstructions(s string) InstructionsProvider

type InstructionsProviderFunc added in v0.6.0

type InstructionsProviderFunc func(ctx context.Context, session sessions.Session) (string, bool, error)

func (InstructionsProviderFunc) ProvideInstructions added in v0.6.0

func (f InstructionsProviderFunc) ProvideInstructions(ctx context.Context, s sessions.Session) (string, bool, error)

type ListPromptsFunc added in v0.2.0

type ListPromptsFunc func(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.Prompt], error)

type ListResourceTemplatesFunc

type ListResourceTemplatesFunc func(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.ResourceTemplate], error)

type ListResourcesFunc

type ListResourcesFunc func(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.Resource], error)

type ListToolsFunc

type ListToolsFunc func(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.Tool], error)

ListToolsFunc returns a (possibly paginated) page of tools for the session. The function MUST honor the context for cancellation.

type LoggingCapability added in v0.3.0

type LoggingCapability interface {
	// SetLevel updates the server's logging level. Implementations decide scope
	// (process-wide vs session-specific) and mapping to underlying logger(s).
	SetLevel(ctx context.Context, session sessions.Session, level mcp.LoggingLevel) error
}

LoggingCapability allows the client to adjust the server's logging level for the session or process depending on implementation. Implementations should be thread-safe and return quickly; expensive work should be done asynchronously.

func NewSlogLevelVarLogging added in v0.3.0

func NewSlogLevelVarLogging(lv *slog.LevelVar) LoggingCapability

NewSlogLevelVarLogging returns a LoggingCapability that maps MCP LoggingLevel to a provided slog.LevelVar. This adjusts process-wide slog level when used with handlers created from the same LevelVar.

type LoggingCapabilityProvider added in v0.6.0

type LoggingCapabilityProvider interface {
	ProvideLogging(ctx context.Context, session sessions.Session) (LoggingCapability, bool, error)
}

LoggingCapabilityProvider yields logging/setLevel support.

func StaticLogging added in v0.6.0

type LoggingCapabilityProviderFunc added in v0.6.0

type LoggingCapabilityProviderFunc func(ctx context.Context, session sessions.Session) (LoggingCapability, bool, error)

func (LoggingCapabilityProviderFunc) ProvideLogging added in v0.6.0

type NotifyPromptsListChangedFunc added in v0.2.0

type NotifyPromptsListChangedFunc func(ctx context.Context, session sessions.Session)

NotifyPromptsListChangedFunc is invoked when the server's prompt list changes for the session (additions, removals, or metadata changes). Implementations MAY coalesce rapid changes and deliver fewer callbacks.

type NotifyResourceChangeFunc

type NotifyResourceChangeFunc func(ctx context.Context, session sessions.Session, uri string)

NotifyResourceChangeFunc is invoked to signal that the server's resource set has changed for the session. The uri argument SHOULD refer to the resource whose presence or metadata changed. When multiple changes occur or the exact resource is unknown, implementations MAY pass the empty string to indicate a general list change.

type NotifyResourceUpdatedFunc added in v0.4.0

type NotifyResourceUpdatedFunc func(ctx context.Context, uri string)

NotifyResourceUpdatedFunc is invoked by a provider to signal that a specific resource URI's contents have been updated for the given session's view. The Engine provides this to the provider during Subscribe and is responsible for forwarding the event to the per-session client stream.

type NotifyToolsListChangedFunc

type NotifyToolsListChangedFunc func(ctx context.Context, session sessions.Session)

NotifyToolsListChangedFunc is invoked when the server's tool list changes for the session (additions, removals, or metadata changes). Implementations MAY coalesce rapid changes and deliver fewer callbacks.

type Page

type Page[T any] struct {
	Items      []T
	NextCursor *string
}

Page represents a single page of results with an optional cursor for fetching the next page. It is a generic helper intended for server capability methods that return paginated data.

Items is never nil; NewPage normalizes nil input to an empty slice for ergonomics at call sites.

func NewPage

func NewPage[T any](items []T, opts ...PageOption[T]) Page[T]

NewPage constructs a Page with the provided items and optional configuration options. If items is nil, it will be replaced with an empty slice.

type PageOption

type PageOption[T any] func(*Page[T])

PageOption configures a Page constructed via NewPage.

func WithNextCursor

func WithNextCursor[T any](cursor string) PageOption[T]

WithNextCursor sets the next cursor on the Page to indicate that more results are available.

type ProgressReporter added in v0.3.0

type ProgressReporter interface {
	// Report emits a progress update. Implementations should treat values as
	// opaque and simply forward to the client; server code is responsible for
	// selecting meaningful scales for progress and total. total may be zero or
	// omitted depending on transport implementation.
	Report(ctx context.Context, progress, total float64) error
}

ProgressReporter is a minimal interface for reporting progress of a long-running operation. Implementations are transport-specific and injected into the context by the transport handlers. Server code can retrieve it from context and call Report to emit notifications/progress to the client correlated to the current request.

func ProgressFrom added in v0.3.0

func ProgressFrom(ctx context.Context) (ProgressReporter, bool)

ProgressFrom retrieves a ProgressReporter from the context if present.

type PromptHandler added in v0.2.0

type PromptHandler func(ctx context.Context, session sessions.Session, req *mcp.GetPromptRequestReceived) (*mcp.GetPromptResult, error)

PromptHandler handles a prompt get request to produce messages.

type PromptListChangedCapability added in v0.2.0

type PromptListChangedCapability interface {
	Register(ctx context.Context, session sessions.Session, fn NotifyPromptsListChangedFunc) (ok bool, err error)
}

PromptListChangedCapability provides prompts list-changed notifications support. Register should be idempotent for the same (session, fn) pair and respect ctx cancellation to stop delivering callbacks.

type PromptsCapability added in v0.2.0

type PromptsCapability interface {
	// ListPrompts returns a (possibly paginated) list of prompts available to the session.
	// A nil cursor requests the first page. When more results are available,
	// Page.NextCursor SHOULD be set.
	ListPrompts(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.Prompt], error)

	// GetPrompt returns the prompt definition/messages for the given name and arguments.
	GetPrompt(ctx context.Context, session sessions.Session, req *mcp.GetPromptRequestReceived) (*mcp.GetPromptResult, error)

	// GetListChangedCapability returns an optional capability that, when present,
	// allows the handler to register a callback to be invoked when the prompt list
	// changes. If ok is false, list-changed notifications are not supported.
	// The server will use the return value to decide if it advertises the
	// "listChanged" capability for prompts.
	GetListChangedCapability(ctx context.Context, session sessions.Session) (cap PromptListChangedCapability, ok bool, err error)
}

PromptsCapability defines the server's prompts surface area. Implementations may be static or dynamic per session. All methods MUST be safe for concurrent use.

func NewDynamicPrompts added in v0.5.0

func NewDynamicPrompts(opts ...DynamicPromptsOption) PromptsCapability

type PromptsCapabilityProvider added in v0.6.0

type PromptsCapabilityProvider interface {
	ProvidePrompts(ctx context.Context, session sessions.Session) (PromptsCapability, bool, error)
}

PromptsCapabilityProvider yields a PromptsCapability (named prompt templates).

func StaticPrompts added in v0.2.0

type PromptsCapabilityProviderFunc added in v0.6.0

type PromptsCapabilityProviderFunc func(ctx context.Context, session sessions.Session) (PromptsCapability, bool, error)

func (PromptsCapabilityProviderFunc) ProvidePrompts added in v0.6.0

type PromptsContainer added in v0.5.0

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

PromptsContainer owns a mutable, threadsafe set of prompt descriptors and handlers. It allows simple servers to advertise a fixed (but updatable) set of prompts and have the server dispatch get requests automatically.

PromptsContainer also embeds a ChangeNotifier and implements ChangeSubscriber to automatically expose listChanged support.

func NewPromptsContainer added in v0.5.0

func NewPromptsContainer(defs ...StaticPrompt) *PromptsContainer

NewPromptsContainer constructs a new PromptsContainer with the given definitions.

func (*PromptsContainer) Add added in v0.5.0

Add registers a new prompt if it doesn't duplicate an existing name. Returns true if added.

func (*PromptsContainer) Get added in v0.5.0

Get dispatches a prompt get to the named handler if present.

func (*PromptsContainer) GetListChangedCapability added in v0.5.0

func (sp *PromptsContainer) GetListChangedCapability(ctx context.Context, session sessions.Session) (PromptListChangedCapability, bool, error)

GetListChangedCapability implements PromptsCapability for PromptsContainer

func (*PromptsContainer) GetPrompt added in v0.5.0

GetPrompt implements PromptsCapability for PromptsContainer

func (*PromptsContainer) ListPrompts added in v0.5.0

func (sp *PromptsContainer) ListPrompts(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.Prompt], error)

ListPrompts implements PromptsCapability for PromptsContainer

func (*PromptsContainer) ProvidePrompts added in v0.6.0

func (sp *PromptsContainer) ProvidePrompts(ctx context.Context, session sessions.Session) (PromptsCapability, bool, error)

ProvidePrompts implements PromptsCapabilityProvider for the static container. Always reports present (ok=true).

func (*PromptsContainer) Remove added in v0.5.0

func (sp *PromptsContainer) Remove(_ context.Context, name string) bool

Remove removes a prompt by name. Returns true if removed.

func (*PromptsContainer) Replace added in v0.5.0

func (sp *PromptsContainer) Replace(_ context.Context, defs ...StaticPrompt)

Replace atomically replaces the entire prompt set.

func (*PromptsContainer) SetPageSize added in v0.5.0

func (sp *PromptsContainer) SetPageSize(n int)

SetPageSize sets the pagination size for ListPrompts.

func (*PromptsContainer) Snapshot added in v0.5.0

func (sp *PromptsContainer) Snapshot() []mcp.Prompt

Snapshot returns a copy of the current prompt descriptors.

func (*PromptsContainer) Subscriber added in v0.5.0

func (sp *PromptsContainer) Subscriber() <-chan struct{}

Subscriber implements ChangeSubscriber by returning a per-subscriber channel that receives a signal whenever the prompt set changes.

type ProtocolVersionProvider added in v0.6.0

type ProtocolVersionProvider interface {
	ProvideProtocolVersion(ctx context.Context, session sessions.Session) (string, bool, error)
}

ProtocolVersionProvider yields a preferred protocol version. Session is currently unused but retained for symmetry / future evolution.

func StaticProtocolVersion added in v0.6.0

func StaticProtocolVersion(v string) ProtocolVersionProvider

type ProtocolVersionProviderFunc added in v0.6.0

type ProtocolVersionProviderFunc func(ctx context.Context, session sessions.Session) (string, bool, error)

Session currently unused but retained for symmetry / future needs.

func (ProtocolVersionProviderFunc) ProvideProtocolVersion added in v0.6.0

func (f ProtocolVersionProviderFunc) ProvideProtocolVersion(ctx context.Context, s sessions.Session) (string, bool, error)

type ReadResourceFunc

type ReadResourceFunc func(ctx context.Context, session sessions.Session, uri string) ([]mcp.ResourceContents, error)

type Resource added in v0.8.0

type Resource struct {
	URI      string
	Name     string
	Desc     string
	MimeType string
	Variants []ContentVariant
}

Resource models a static resource's metadata and its content variants. Each element in Variants is mapped to a distinct mcp.ResourceContents when read. A resource may have zero variants (allowing metadata-only listing) and can later be Upserted with content.

func BlobResource added in v0.8.0

func BlobResource(uri string, blob []byte, mime string, opts ...ResourceOption) Resource

func ResourceWithVariants added in v0.8.0

func ResourceWithVariants(uri string, variants []ContentVariant, opts ...ResourceOption) Resource

func TextResource added in v0.8.0

func TextResource(uri, text string, opts ...ResourceOption) Resource

type ResourceListChangedCapability

type ResourceListChangedCapability interface {
	Register(ctx context.Context, session sessions.Session, fn NotifyResourceChangeFunc) (ok bool, err error)
}

ResourceListChangedCapability provides list-changed notifications support. Register should be idempotent for the same (session, fn) pair and respect ctx cancellation to stop delivering callbacks.

type ResourceOption added in v0.8.0

type ResourceOption func(*Resource)

func WithDescription added in v0.8.0

func WithDescription(desc string) ResourceOption

func WithMimeType added in v0.8.0

func WithMimeType(mime string) ResourceOption

func WithName added in v0.8.0

func WithName(name string) ResourceOption

func WithVariants added in v0.8.0

func WithVariants(vs ...ContentVariant) ResourceOption

type ResourceSubscriptionCapability

type ResourceSubscriptionCapability interface {
	// Subscribe begins delivering updates for the given resource URI to the
	// client associated with the session. Implementations MUST be idempotent
	// for duplicate calls on the same (session, uri) pair. The provided emit
	// function MUST be called by the provider each time the resource is
	// updated. The returned CancelSubscription is invoked by the Engine on
	// explicit unsubscribe or session end.
	Subscribe(ctx context.Context, session sessions.Session, uri string, emit NotifyResourceUpdatedFunc) (CancelSubscription, error)
}

ResourceSubscriptionCapability enables opt-in support for resource subscriptions. Subscribe should be thread-safe and return quickly; heavy work should be done asynchronously where possible. The returned cancel func will be invoked by the library on explicit unsubscribe or session close. Cancel will be called at-least-once and MAY be called multiple times.

type ResourceTemplate added in v0.8.0

type ResourceTemplate struct {
	URITemplate string
	Name        string
	Desc        string
	MimeType    string
}

ResourceTemplate mirrors the MCP resource template shape while remaining decoupled from the wire types.

func NewTemplate added in v0.8.0

func NewTemplate(uriTemplate string, opts ...TemplateOption) ResourceTemplate

type ResourcesCapability

type ResourcesCapability interface {
	// ListResources returns a (possibly paginated) list of resources available to the session.
	//
	// A nil cursor requests the first page. When more results are available,
	// Page.NextCursor SHOULD be set. See Page[T] for details.
	ListResources(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.Resource], error)

	// ListResourceTemplates returns a (possibly paginated) list of resource templates.
	//
	// A nil cursor requests the first page. When more results are available,
	// Page.NextCursor SHOULD be set.
	ListResourceTemplates(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.ResourceTemplate], error)

	// ReadResource returns the contents for a specific resource URI.
	//
	// Implementations SHOULD return mcp.Content values appropriate for the
	// resource (e.g., text, references). Unknown URIs SHOULD result in a
	// descriptive error that the handler can surface to the client.
	ReadResource(ctx context.Context, session sessions.Session, uri string) ([]mcp.ResourceContents, error)

	// GetSubscriptionCapability returns an optional capability for managing
	// per-session resource subscriptions. If ok is false, subscriptions are not supported.
	// The server will use the return value to decide if it advertises the "subscribe" capability.
	//
	// The returned value MUST be safe for concurrent use. Subscribe/Unsubscribe
	// MUST be idempotent with respect to duplicate calls for the same
	// (session, uri) pair.
	GetSubscriptionCapability(ctx context.Context, session sessions.Session) (cap ResourceSubscriptionCapability, ok bool, err error)

	// GetListChangedCapability returns an optional capability that, when present,
	// allows the handler to register a callback to be invoked when the resource
	// list changes (additions, removals, or metadata changes). If ok is false,
	// list-changed notifications are not supported.
	// The server will use the return value to decide if it advertises the
	// "listChanged" capability.
	GetListChangedCapability(ctx context.Context, session sessions.Session) (cap ResourceListChangedCapability, ok bool, err error)
}

ResourcesCapability defines the basic resource operations supported by the server. Implementations may be static (the same for every session) or dynamic (vary by session). All methods MUST be safe for concurrent use.

type ResourcesCapabilityProvider added in v0.6.0

type ResourcesCapabilityProvider interface {
	ProvideResources(ctx context.Context, session sessions.Session) (ResourcesCapability, bool, error)
}

ResourcesCapabilityProvider yields a ResourcesCapability (list/read). Use a provider func for per-session ACL or tenant scoping.

type ResourcesCapabilityProviderFunc added in v0.6.0

type ResourcesCapabilityProviderFunc func(ctx context.Context, session sessions.Session) (ResourcesCapability, bool, error)

func (ResourcesCapabilityProviderFunc) ProvideResources added in v0.6.0

type ResourcesContainer added in v0.5.0

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

ResourcesContainer owns a static, in-memory collection of resources and templates with subscription support and change notifications. CRUD methods are synchronous and do not take contexts; capability methods (List*/Read*) adapt to context-aware interfaces required by the engine.

func NewResourcesContainer added in v0.5.0

func NewResourcesContainer(opts ...ContainerOption) *ResourcesContainer

NewResourcesContainer constructs an empty container.

func (*ResourcesContainer) AddResource added in v0.5.0

func (rc *ResourcesContainer) AddResource(r Resource) bool

AddResource adds a new resource; returns true if newly added.

func (*ResourcesContainer) AddTemplate added in v0.8.0

func (rc *ResourcesContainer) AddTemplate(t ResourceTemplate) bool

AddTemplate adds a template; returns true if new.

func (*ResourcesContainer) GetListChangedCapability added in v0.5.0

func (rc *ResourcesContainer) GetListChangedCapability(ctx context.Context, session sessions.Session) (ResourceListChangedCapability, bool, error)

GetListChangedCapability wires list changed notifications via the container's notifier.

func (*ResourcesContainer) GetSubscriptionCapability added in v0.5.0

func (rc *ResourcesContainer) GetSubscriptionCapability(ctx context.Context, session sessions.Session) (ResourceSubscriptionCapability, bool, error)

GetSubscriptionCapability intentionally returns (nil,false); engine synthesizes subscription support using UpdatedChan & ListChangedChan when it detects this container type (avoids duplicate subscription state across layers).

func (*ResourcesContainer) HasResource added in v0.5.0

func (rc *ResourcesContainer) HasResource(uri string) bool

HasResource reports whether a resource URI exists.

func (*ResourcesContainer) ListChangedChan added in v0.8.0

func (rc *ResourcesContainer) ListChangedChan() <-chan struct{}

ListChangedChan returns a channel signaled when resources/templates set changes.

func (*ResourcesContainer) ListResourceTemplates added in v0.5.0

func (rc *ResourcesContainer) ListResourceTemplates(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.ResourceTemplate], error)

ListResourceTemplates paginates over templates.

func (*ResourcesContainer) ListResources added in v0.5.0

func (rc *ResourcesContainer) ListResources(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.Resource], error)

ListResources paginates over static resources.

func (*ResourcesContainer) ProvideResources added in v0.6.0

func (rc *ResourcesContainer) ProvideResources(ctx context.Context, session sessions.Session) (ResourcesCapability, bool, error)

ProvideResources implements ResourcesCapabilityProvider (self-providing static capability).

func (*ResourcesContainer) Read added in v0.8.0

func (rc *ResourcesContainer) Read(uri string) ([]ContentVariant, bool)

Read returns a defensive copy of the resource's content variants.

func (*ResourcesContainer) ReadResource added in v0.5.0

func (rc *ResourcesContainer) ReadResource(ctx context.Context, session sessions.Session, uri string) ([]mcp.ResourceContents, error)

ReadResource returns contents variants for a URI translated to wire types.

func (*ResourcesContainer) RemoveResource added in v0.5.0

func (rc *ResourcesContainer) RemoveResource(uri string) bool

RemoveResource removes a resource by URI.

func (*ResourcesContainer) RemoveTemplate added in v0.8.0

func (rc *ResourcesContainer) RemoveTemplate(uriTemplate string) bool

RemoveTemplate removes a template by uriTemplate.

func (*ResourcesContainer) ReplaceResources added in v0.5.0

func (rc *ResourcesContainer) ReplaceResources(resources []Resource) (removed []string)

ReplaceResources atomically replaces the entire resource set. Returns URIs removed.

func (*ResourcesContainer) ReplaceTemplates added in v0.5.0

func (rc *ResourcesContainer) ReplaceTemplates(ts []ResourceTemplate)

ReplaceTemplates atomically replaces templates.

func (*ResourcesContainer) SetPageSize added in v0.5.0

func (rc *ResourcesContainer) SetPageSize(n int)

SetPageSize adjusts pagination size (ignored if n<1).

func (*ResourcesContainer) SnapshotResources added in v0.5.0

func (rc *ResourcesContainer) SnapshotResources() []Resource

SnapshotResources returns a copy of current resources.

func (*ResourcesContainer) SnapshotTemplates added in v0.5.0

func (rc *ResourcesContainer) SnapshotTemplates() []ResourceTemplate

SnapshotTemplates returns a copy of current templates.

func (*ResourcesContainer) UpdatedChan added in v0.8.0

func (rc *ResourcesContainer) UpdatedChan(uri string) <-chan struct{}

UpdatedChan returns a channel signaled when URI content/metadata changes.

func (*ResourcesContainer) UpsertResource added in v0.8.0

func (rc *ResourcesContainer) UpsertResource(r Resource) (created bool)

UpsertResource inserts or updates a resource. Returns true if created. Emits listChanged if created or metadata (Name/Desc/MimeType) changed. Emits per-URI updated only if variants changed.

type ServerCapabilities

type ServerCapabilities interface {
	// GetServerInfo returns static implementation information about the server
	// that is surfaced in initialize results (name, version, etc.).
	//
	// This method MAY be called multiple times and SHOULD be inexpensive.
	// Return an error only for unexpected failures; the handler will translate
	// it to an MCP error.
	GetServerInfo(ctx context.Context, session sessions.Session) (mcp.ImplementationInfo, error)

	// GetPreferredProtocolVersion returns the server's preferred MCP protocol version
	// for this session. If ok is false, the handler should fall back to the client's
	// requested version.
	GetPreferredProtocolVersion(ctx context.Context) (version string, ok bool, err error)

	// GetInstructions returns optional human-readable instructions that should be
	// surfaced to the client during initialization. If ok is false, no instructions
	// will be included in the initialize result.
	GetInstructions(ctx context.Context, session sessions.Session) (instructions string, ok bool, err error)

	// GetResourcesCapability returns the resources capability for the session.
	// If ok is false, the server does not support resources for this session
	// and the handler will not advertise resources support.
	//
	// Implementations may return a session-scoped value. The returned value
	// MUST be safe for concurrent use.
	GetResourcesCapability(ctx context.Context, session sessions.Session) (cap ResourcesCapability, ok bool, err error)

	// GetToolsCapability returns the tools capability if supported by the server
	// for the given session. If ok is false, the handler will not advertise tool
	// support in the server capabilities.
	//
	// Implementations may return a session-scoped value. The returned value
	// MUST be safe for concurrent use.
	GetToolsCapability(ctx context.Context, session sessions.Session) (cap ToolsCapability, ok bool, err error)

	// GetPromptsCapability returns the prompts capability if supported by the server
	// for the given session. If ok is false, the handler will not advertise prompt
	// support in the server capabilities.
	//
	// Implementations may return a session-scoped value. The returned value
	// MUST be safe for concurrent use.
	GetPromptsCapability(ctx context.Context, session sessions.Session) (cap PromptsCapability, ok bool, err error)

	// GetLoggingCapability returns the logging capability if supported by the server
	// for the given session. If ok is false, the handler will not advertise logging
	// support in the server capabilities.
	//
	// Implementations may return a session-scoped value. The returned value
	// MUST be safe for concurrent use.
	GetLoggingCapability(ctx context.Context, session sessions.Session) (cap LoggingCapability, ok bool, err error)

	// GetCompletionsCapability returns the completions capability if supported by the server
	// for the given session. If ok is false, the handler will not advertise completions
	// support in the server capabilities.
	//
	// Implementations may return a session-scoped value. The returned value
	// MUST be safe for concurrent use.
	GetCompletionsCapability(ctx context.Context, session sessions.Session) (cap CompletionsCapability, ok bool, err error)
}

func NewServer

func NewServer(opts ...ServerOption) ServerCapabilities

NewServer builds a ServerCapabilities using functional options. Options allow configuring static fields or per-session providers for info, protocol preference, instructions, resources and tools.

type ServerInfoOption added in v0.6.0

type ServerInfoOption func(*mcp.ImplementationInfo)

Static helper constructors (ergonomic wrappers) ServerInfoOption configures optional fields on the server's implementation info.

func WithServerInfoTitle added in v0.6.0

func WithServerInfoTitle(title string) ServerInfoOption

WithServerInfoTitle sets the optional human friendly title.

type ServerInfoProvider added in v0.6.0

type ServerInfoProvider interface {
	ProvideServerInfo(ctx context.Context, session sessions.Session) (mcp.ImplementationInfo, bool, error)
}

ServerInfoProvider yields implementation metadata. Typically static; use a function provider only if you need tenant‑specific branding.

func StaticServerInfo added in v0.6.0

func StaticServerInfo(name, version string, opts ...ServerInfoOption) ServerInfoProvider

StaticServerInfo returns a provider that always supplies the same implementation info. Use WithServerInfoTitle for an optional human friendly title.

type ServerInfoProviderFunc added in v0.6.0

type ServerInfoProviderFunc func(ctx context.Context, session sessions.Session) (mcp.ImplementationInfo, bool, error)

func (ServerInfoProviderFunc) ProvideServerInfo added in v0.6.0

type ServerOption

type ServerOption func(*server)

ServerOption configures a concrete ServerCapabilities implementation.

func WithCompletionsCapability added in v0.3.0

func WithCompletionsCapability(p CompletionsCapabilityProvider) ServerOption

WithCompletionsCapability wires the completions capability provider.

func WithInstructions

func WithInstructions(p InstructionsProvider) ServerOption

WithInstructions sets a provider for human-readable instructions returned during initialize.

func WithLoggingCapability added in v0.3.0

func WithLoggingCapability(p LoggingCapabilityProvider) ServerOption

WithLoggingCapability wires the logging capability provider.

func WithPromptsCapability added in v0.2.0

func WithPromptsCapability(p PromptsCapabilityProvider) ServerOption

WithPromptsCapability wires the prompts capability provider.

func WithProtocolVersion added in v0.6.0

func WithProtocolVersion(p ProtocolVersionProvider) ServerOption

WithProtocolVersion sets a provider for the preferred protocol version.

func WithResourcesCapability

func WithResourcesCapability(p ResourcesCapabilityProvider) ServerOption

WithResourcesCapability wires the resources capability provider.

func WithServerInfo

func WithServerInfo(p ServerInfoProvider) ServerOption

WithServerInfo sets a provider for server info (usually StaticServerInfo).

func WithToolsCapability

func WithToolsCapability(p ToolsCapabilityProvider) ServerOption

WithToolsCapability wires the tools capability provider.

type StaticPrompt added in v0.2.0

type StaticPrompt struct {
	Descriptor mcp.Prompt
	Handler    PromptHandler
}

StaticPrompt pairs a prompt descriptor with a handler that can materialize it.

type StaticTool

type StaticTool struct {
	Descriptor mcp.Tool
	Handler    ToolHandler
}

StaticTool pairs an MCP tool descriptor with its handler.

func NewTool

func NewTool[A any](name string, fn func(ctx context.Context, session sessions.Session, w ToolResponseWriter, r *ToolRequest[A]) error, opts ...ToolOption) StaticTool

NewToolWithWriter constructs a StaticTool using a typed input struct and a writer-based handler shape. It keeps the current typed-input decoding logic and enforces the writer path for composing results. NewTool constructs a writer-based tool with typed input A and a ToolRequest container.

func NewToolWithOutput added in v0.3.0

func NewToolWithOutput[A, O any](name string, fn func(ctx context.Context, session sessions.Session, w ToolResponseWriterTyped[O], r *ToolRequest[A]) error, opts ...ToolOption) StaticTool

NewTool constructs a StaticTool from a typed args struct A. It: - Reflects a JSON Schema from A using invopop/jsonschema - Down-converts it to MCP's simplified ToolInputSchema - Builds the tool descriptor with the provided name and options - Wraps the handler with runtime JSON decoding (rejecting unknown fields by default) NewToolWithOutput constructs a typed-input, typed-output tool.

func TypedTool

func TypedTool[A any](desc mcp.Tool, fn func(ctx context.Context, session sessions.Session, args A) (*mcp.CallToolResult, error)) StaticTool

TypedTool wraps a strongly typed args function into a StaticTool. It unmarshals req.Arguments into A and invokes fn.

type TemplateOption added in v0.8.0

type TemplateOption func(*ResourceTemplate)

func WithTemplateDescription added in v0.8.0

func WithTemplateDescription(desc string) TemplateOption

func WithTemplateMimeType added in v0.8.0

func WithTemplateMimeType(mime string) TemplateOption

func WithTemplateName added in v0.8.0

func WithTemplateName(name string) TemplateOption

type ToolHandler

type ToolHandler func(ctx context.Context, session sessions.Session, req *mcp.CallToolRequestReceived) (*mcp.CallToolResult, error)

ToolHandler is the function signature used to handle a tool invocation.

type ToolListChangedCapability

type ToolListChangedCapability interface {
	Register(ctx context.Context, session sessions.Session, fn NotifyToolsListChangedFunc) (ok bool, err error)
}

ToolListChangedCapability provides tools list-changed notifications support. Register should be idempotent for the same (session, fn) pair and respect ctx cancellation to stop delivering callbacks.

type ToolOption

type ToolOption func(*toolConfig)

ToolOption configures NewTool behavior.

func WithToolAllowAdditionalProperties

func WithToolAllowAdditionalProperties(allow bool) ToolOption

WithToolAllowAdditionalProperties controls whether unknown fields are allowed. When false (default), the generated schema sets additionalProperties=false and runtime decoding rejects unknown fields.

func WithToolDescription

func WithToolDescription(desc string) ToolOption

WithToolDescription sets the tool description used in listings.

func WithToolMeta added in v0.7.7

func WithToolMeta(meta map[string]any) ToolOption

WithToolMeta attaches arbitrary metadata to the tool descriptor that will be surfaced under the `_meta` field when the tool is listed. Multiple invocations merge keys (later values overwrite earlier ones). A nil or empty map is ignored. The map is shallow-copied at option application time so the caller can mutate their original without affecting the descriptor.

type ToolRequest added in v0.3.0

type ToolRequest[A any] struct {
	// contains filtered or unexported fields
}

ToolRequest is the container for tool call input and request metadata. It is generic over the typed argument struct A.

func (*ToolRequest[A]) Args added in v0.3.0

func (r *ToolRequest[A]) Args() A

func (*ToolRequest[A]) Name added in v0.3.0

func (r *ToolRequest[A]) Name() string

func (*ToolRequest[A]) RawArguments added in v0.3.0

func (r *ToolRequest[A]) RawArguments() json.RawMessage

type ToolResponseWriter added in v0.3.0

type ToolResponseWriter interface {
	AppendText(text string) error
	AppendBlocks(blocks ...mcp.ContentBlock) error
	SetError(isError bool)
	SetMeta(key string, v any)
	SendProgress(progress, total float64) error
	// Result finalizes and returns the accumulated result. It is idempotent.
	Result() *mcp.CallToolResult
}

ToolResponseWriter allows a tool handler to incrementally compose a CallToolResult while optionally emitting progress notifications.

Notes: - It is concurrency-safe for use within a single request. - Writes after finalization (Result) are ignored and return ErrFinalized. - All mutating methods check ctx.Done() and return the context error promptly. - SendProgress delegates to the ambient ProgressReporter when present; it is a no-op otherwise.

type ToolResponseWriterTyped added in v0.3.0

type ToolResponseWriterTyped[O any] interface {
	ToolResponseWriter
	SetStructured(v O)
}

ToolResponseWriterTyped extends ToolResponseWriter for typed output tools. It allows setting a structuredContent value of type O.

type ToolsCapability

type ToolsCapability interface {
	// ListTools returns a (possibly paginated) list of tools available to the session.
	// A nil cursor requests the first page. When more results are available,
	// Page.NextCursor SHOULD be set.
	ListTools(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.Tool], error)

	// CallTool invokes a named tool with the provided request payload.
	// Implementations SHOULD validate inputs and return structured MCP errors
	// when appropriate. Calls MUST be isolated per session.
	CallTool(ctx context.Context, session sessions.Session, req *mcp.CallToolRequestReceived) (*mcp.CallToolResult, error)

	// GetListChangedCapability returns an optional capability that, when present,
	// allows the handler to register a callback to be invoked when the tool list
	// changes. If ok is false, list-changed notifications are not supported.
	// The server will use the return value to decide if it advertises the
	// "listChanged" capability for tools.
	GetListChangedCapability(ctx context.Context, session sessions.Session) (cap ToolListChangedCapability, ok bool, err error)
}

ToolsCapability defines the server's tools surface area. Implementations may be static or dynamic per session. All methods MUST be safe for concurrent use.

func NewDynamicTools added in v0.5.0

func NewDynamicTools(opts ...DynamicToolsOption) ToolsCapability

NewDynamicTools builds a dynamic tools capability from option functions. If listFn is nil, ListTools returns an empty page. If callFn is nil, tool calls result in a not-found error. changeSub enables listChanged notifications.

type ToolsCapabilityProvider added in v0.6.0

type ToolsCapabilityProvider interface {
	ProvideTools(ctx context.Context, session sessions.Session) (ToolsCapability, bool, error)
}

ToolsCapabilityProvider yields a ToolsCapability (list + invoke). ok=false suppresses the entire capability.

type ToolsCapabilityProviderFunc added in v0.6.0

type ToolsCapabilityProviderFunc func(ctx context.Context, session sessions.Session) (ToolsCapability, bool, error)

func (ToolsCapabilityProviderFunc) ProvideTools added in v0.6.0

type ToolsContainer added in v0.5.0

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

ToolsContainer owns a mutable, threadsafe set of tool descriptors and handlers. It is intended for simple servers that want to advertise a collection of tools and have the server dispatch calls automatically.

ToolsContainer also embeds a ChangeNotifier and implements ChangeSubscriber to allow the tools capability to automatically expose listChanged support.

func NewToolsContainer added in v0.5.0

func NewToolsContainer(defs ...StaticTool) *ToolsContainer

NewToolsContainer constructs a new ToolsContainer with the given tool definitions.

func (*ToolsContainer) Add added in v0.5.0

func (st *ToolsContainer) Add(_ context.Context, def StaticTool) bool

Add registers a new tool if it doesn't duplicate an existing name. Returns true if added.

func (*ToolsContainer) Call added in v0.5.0

Call dispatches a request to the named tool if present.

func (*ToolsContainer) CallTool added in v0.5.0

CallTool implements ToolsCapability for static tools (delegates to Call).

func (*ToolsContainer) GetListChangedCapability added in v0.5.0

func (st *ToolsContainer) GetListChangedCapability(ctx context.Context, session sessions.Session) (ToolListChangedCapability, bool, error)

GetListChangedCapability always returns support for listChanged in static mode.

func (*ToolsContainer) ListTools added in v0.5.0

func (st *ToolsContainer) ListTools(ctx context.Context, session sessions.Session, cursor *string) (Page[mcp.Tool], error)

ListTools implements ToolsCapability (static mode with internal pagination).

func (*ToolsContainer) ProvideTools added in v0.6.0

func (st *ToolsContainer) ProvideTools(ctx context.Context, session sessions.Session) (ToolsCapability, bool, error)

ProvideTools makes *ToolsContainer satisfy ToolsCapabilityProvider. It always returns itself as the ToolsCapability with ok=true (present) even if it has zero tools; an empty container is a present-but-empty capability rather than an absent one.

func (*ToolsContainer) Remove added in v0.5.0

func (st *ToolsContainer) Remove(_ context.Context, name string) bool

Remove removes a tool by name. Returns true if removed.

func (*ToolsContainer) Replace added in v0.5.0

func (st *ToolsContainer) Replace(_ context.Context, defs ...StaticTool)

Replace atomically replaces the entire tool set.

func (*ToolsContainer) SetPageSize added in v0.5.0

func (st *ToolsContainer) SetPageSize(n int)

SetPageSize sets the pagination size used by ListTools for static tools. A non-positive value is ignored.

func (*ToolsContainer) Snapshot added in v0.5.0

func (st *ToolsContainer) Snapshot() []mcp.Tool

Snapshot returns a copy of the current tool descriptors.

func (*ToolsContainer) Subscriber added in v0.5.0

func (st *ToolsContainer) Subscriber() <-chan struct{}

Subscriber implements ChangeSubscriber by returning a per-subscriber channel that receives a signal whenever the tool set changes.

Jump to

Keyboard shortcuts

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