server

package
v0.0.0-...-d52a2f3 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 21 Imported by: 2 modules, 6 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 server contains the *protocol-level* abstractions that make up the “server side” of the Model Context Protocol (MCP).

The MCP specification itself calls this role “server”. Within the code we expose a Handler interface (plus DefaultHandler) to emphasise that this component handles already-decoded JSON-RPC requests, while a separate transport layer (in another module) is responsible for listening on HTTP, stdio, WebSockets, etc.

A Handler typically embeds DefaultHandler and selectively overrides the Operations it needs. The package is intentionally transport-agnostic so it can be reused by different listener implementations.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSamplingNotSupported is returned when the client doesn't support sampling
	ErrSamplingNotSupported = errors.New("client does not support sampling")
	// ErrElicitationNotSupported is returned when the client doesn't support elicitation
	ErrElicitationNotSupported = errors.New("client does not support elicitation")
)

Functions

func RegisterResource

func RegisterResource[I any](registry *Registry, resource schema.Resource, handler func(ctx context.Context, uri string) (*schema.ReadResourceResult, *jsonrpc.Error))

RegisterResource registers a resource using a typed handler that returns a Go struct. The struct will be JSON-marshaled into the ReadResourceResult.Contents field.

func RegisterTool

func RegisterTool[I any, O any](registry *Registry, name, description string, handler func(ctx context.Context, input I) (*schema.CallToolResult, *jsonrpc.Error)) error

RegisterTool derives JSON schemas from the generic I/O types and registers the tool.

Types

type DefaultHandler

type DefaultHandler struct {
	Notifier           transport.Notifier
	Logger             logger.Logger
	Client             client.Operations
	ClientInitialize   *schema.InitializeRequestParams
	Subscription       *syncmap.Map[string, bool]
	ServerCapabilities *schema.ServerCapabilities
	// Configuration for listChanged capabilities
	ToolsListChanged     *bool
	ResourcesListChanged *bool
	PromptsListChanged   *bool
	// SkillsCacheTTL and SkillsCacheScope are the caching hints (ttlMs and
	// cacheScope) that skills/list and skills/get results carry in 2026-07-28.
	// Left unset, clients get no freshness (0 ms) and private scope, so they
	// fetch the metadata again each time they need it.
	SkillsCacheTTL   time.Duration
	SkillsCacheScope schema.CacheableResultCacheScope
	// SkillsDirectoryRead turns resources/directory/read (SEP-2640) on or off
	// for the skills this handler registers. Unset, it is on while every
	// skill is compiled (RegisterStaticSkill) and off once a dynamic skill is
	// registered. Its listings carry the skills cache hints above. See
	// ReadResourceDirectory for what the default lists.
	SkillsDirectoryRead *bool
	*Registry
}

DefaultHandler provides default implementations for server-side methods. You can embed this in your own Handler and register tools/resources via its helper methods.

func NewDefaultHandler

func NewDefaultHandler(notifier transport.Notifier, logger logger.Logger, client client.Operations) *DefaultHandler

NewDefaultHandler creates a new DefaultHandler with initialized registries. You can then call RegisterResource, RegisterTool, etc., on it before running the server.

func (*DefaultHandler) CallTool

CallTool returns method-not-found by default.

func (*DefaultHandler) CanElicit

func (d *DefaultHandler) CanElicit() bool

CanElicit checks if the client supports elicitation

func (*DefaultHandler) CanSample

func (d *DefaultHandler) CanSample() bool

CanSample checks if the client supports sampling

func (*DefaultHandler) Complete

Complete returns method-not-found by default.

func (*DefaultHandler) Discover

func (d *DefaultHandler) Discover(_ context.Context, result *schema.DiscoverResult)

Discover populates July server capabilities without retaining client state.

func (*DefaultHandler) GetElicitationCapability

func (d *DefaultHandler) GetElicitationCapability() *schema.ElicitationCapability

GetElicitationCapability returns the client's elicitation capability, or nil if the client didn't declare one. Per the spec, declaring the capability object means elicitation is supported; its optional "form" and "url" members name the supported modes, and an empty object means form mode only (for compatibility with clients predating modes).

func (*DefaultHandler) GetPrompt

GetPrompt returns the result of a prompt call.

func (*DefaultHandler) GetSamplingCapability

func (d *DefaultHandler) GetSamplingCapability() *schema.SamplingCapability

GetSamplingCapability returns the client's sampling capability, or nil if the client didn't declare one. Per the spec, declaring the capability object means sampling is supported; its optional "tools" member means tool-enabled sampling is supported.

func (*DefaultHandler) GetSkill

func (*DefaultHandler) Implements

func (d *DefaultHandler) Implements(method string) bool

Implements returns true for supported methods.

func (*DefaultHandler) Initialize

Initialize stores the initialization parameters.

func (*DefaultHandler) ListPrompts

ListPrompts lists all registered prompts on this DefaultHandler.

func (*DefaultHandler) ListResourceTemplates

ListResourceTemplates returns method-not-found by default.

func (*DefaultHandler) ListResources

ListResources returns method-not-found by default.

func (*DefaultHandler) ListSkills

func (*DefaultHandler) ListTools

ListTools returns method-not-found by default.

func (*DefaultHandler) OnNotification

func (d *DefaultHandler) OnNotification(ctx context.Context, notification *jsonrpc.Notification)

OnNotification is a no-op by default.

func (*DefaultHandler) ReadResource

ReadResource returns method-not-found by default.

func (*DefaultHandler) ReadResourceDirectory

ReadResourceDirectory lists the direct children of a directory inside a registered skill: the skill root (skill://pdf-processing) or any directory below it (skill://pdf-processing/templates). The listing comes from the resources registered for the skills, so it covers a static skill completely. A dynamic skill's files are listed only if they are registered resources, so a handler with dynamic skills has directory reads off unless it sets SkillsDirectoryRead to true (all its files are registered) or overrides this method.

func (*DefaultHandler) Subscribe

Subscribe adds the URI to the subscription map.

func (*DefaultHandler) SupportsElicitationMode

func (d *DefaultHandler) SupportsElicitationMode(mode string) bool

SupportsElicitationMode checks if the client supports the specified mode

func (*DefaultHandler) Unsubscribe

Unsubscribe removes the URI from the subscription map.

type Handler

type Handler interface {
	Operations

	OnNotification(ctx context.Context, notification *jsonrpc.Notification)

	// Implements checks if the method is implemented.
	Implements(method string) bool
}

Handler represents a protocol implementer.

type NewHandler

type NewHandler func(ctx context.Context, notifier transport.Notifier, logger logger.Logger, client client.Operations) (Handler, error)

NewHandler creates new handler implementer.

func WithDefaultHandler

func WithDefaultHandler(ctx context.Context, options ...Option) NewHandler

type Operations

Operations lists all JSON-RPC methods that an MCP handler may implement.

type Option

type Option func(server *DefaultHandler) error

Option can be supplied to WithDefaultHandler to mutate the handler before use.

type PromptEntry

type PromptEntry struct {
	Handler PromptHandlerFunc
	Prompt  *schema.Prompt
}

PromptEntry holds a handler with its metadata.

type PromptHandlerFunc

type PromptHandlerFunc func(ctx context.Context, request *schema.GetPromptRequestParams) (*schema.GetPromptResult, *jsonrpc.Error)

PromptHandlerFunc defines a function to handle a prompt call.

type Prompts

type Prompts []*PromptEntry

Prompts is a collection of PromptEntry.

type Registry

type Registry struct {
	ToolRegistry             *syncmap.Map[string, *ToolEntry]
	ResourceRegistry         *syncmap.Map[string, *ResourceEntry]
	ResourceTemplateRegistry *syncmap.Map[string, *ResourceTemplateEntry]
	Prompts                  *syncmap.Map[string, *PromptEntry]
	Methods                  *syncmap.Map[string, bool]
	// contains filtered or unexported fields
}

Registry holds registered tools, resources, prompts, etc. for a handler instance.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates and initialises an empty Registry.

func (*Registry) ImplementsSkills

func (r *Registry) ImplementsSkills() bool

func (*Registry) ListRegisteredResourceTemplates

func (d *Registry) ListRegisteredResourceTemplates() []schema.ResourceTemplate

ListRegisteredResourceTemplates returns metadata for all registered resource templates on this handler.

func (*Registry) ListRegisteredResources

func (d *Registry) ListRegisteredResources() []schema.Resource

ListRegisteredResources returns metadata for all registered resources on this handler.

func (*Registry) ListRegisteredSkills

func (r *Registry) ListRegisteredSkills() []schema.Skill

ListRegisteredSkills returns detached metadata only, never fetching content.

func (*Registry) ListRegisteredTools

func (d *Registry) ListRegisteredTools() []schema.Tool

ListRegisteredTools returns metadata for all registered tools.

func (*Registry) ListToolsFor

func (d *Registry) ListToolsFor(ctx context.Context) ([]schema.Tool, error)

ListToolsFor resolves metadata using the current authenticated request context. Errors fail discovery closed; static metadata is never a fallback on denial.

func (*Registry) ReadStaticSkillResource

func (r *Registry) ReadStaticSkillResource(ctx context.Context, request *schema.ReadResourceRequest) (*schema.ReadResourceResult, *jsonrpc.Error, bool)

ReadStaticSkillResource claims the entire sealed root, including misses. This prevents an ordinary resource/template from adding unlisted files afterward.

func (*Registry) RegisterPrompts

func (d *Registry) RegisterPrompts(prompt *schema.Prompt, handler PromptHandlerFunc)

RegisterPrompts registers a prompt on this handler.

func (*Registry) RegisterResource

func (d *Registry) RegisterResource(resource schema.Resource, handler ResourceHandlerFunc) error

RegisterResource registers a resource with metadata and handler on this handler.

func (*Registry) RegisterResourceTemplate

func (d *Registry) RegisterResourceTemplate(template schema.ResourceTemplate, handler ResourceHandlerFunc)

RegisterResourceTemplate registers a resource template on this handler.

func (*Registry) RegisterSkill

func (r *Registry) RegisterSkill(entry schema.Skill) error

func (*Registry) RegisterStaticSkill

func (r *Registry) RegisterStaticSkill(compiled *skillformat.Static) error

RegisterStaticSkill installs compiler-owned readers and inventory together. It never invokes an existing resource handler to infer bytes or completeness.

func (*Registry) RegisterTool

func (d *Registry) RegisterTool(entry *ToolEntry)

RegisterTool adds a prepared ToolEntry to the registry.

func (*Registry) RegisterToolWithSchema

func (d *Registry) RegisterToolWithSchema(name, description string, inputSchema schema.ToolInputSchema, outputSchema *schema.ToolOutputSchema, handler ToolHandlerFunc)

RegisterToolWithSchema registers a tool with an explicit JSON schema.

type ResourceDirectories

type ResourceDirectories interface {
	ReadResourceDirectory(context.Context, *jsonrpc.TypedRequest[*schema.ReadResourceDirectoryRequest]) (*schema.ReadResourceDirectoryResult, *jsonrpc.Error)
}

ResourceDirectories is optional. A handler that implements it serves SEP-2640's resources/directory/read.

type ResourceEntry

type ResourceEntry struct {
	Handler  ResourceHandlerFunc
	Metadata schema.Resource
}

ResourceEntry holds a handler with its metadata.

type ResourceHandlerFunc

type ResourceHandlerFunc func(ctx context.Context, request *schema.ReadResourceRequest) (*schema.ReadResourceResult, *jsonrpc.Error)

ResourceHandlerFunc defines a function to handle a resource read.

type ResourceTemplateEntry

type ResourceTemplateEntry struct {
	Metadata schema.ResourceTemplate
	Handler  ResourceHandlerFunc
}

ResourceTemplateEntry holds metadata for a resource template.

type Skills

Skills is optional so existing ordinary-resource handlers remain compatible.

type ToolEntry

type ToolEntry struct {
	Handler  ToolHandlerFunc
	Metadata schema.Tool
	// MetadataFor resolves caller-specific metadata without mutating the registration.
	MetadataFor func(context.Context) (schema.Tool, error)
}

ToolEntry holds a handler together with its public metadata.

type ToolHandlerFunc

type ToolHandlerFunc func(ctx context.Context, request *schema.CallToolRequest) (*schema.CallToolResult, *jsonrpc.Error)

ToolHandlerFunc defines a function to handle a tool call.

type Tools

type Tools []*ToolEntry

Tools is a collection of ToolEntry

Jump to

Keyboard shortcuts

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