server

package
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: May 12, 2025 License: MIT Imports: 31 Imported by: 1

Documentation

Index

Constants

View Source
const ServerVersion = "0.1.0" // Define server version constant

Variables

This section is empty.

Functions

func Assistant added in v0.1.11

func Assistant(msg string) protocol.PromptMessage

func NewStdioSession added in v0.1.11

func NewStdioSession(connectionID string, writer io.Writer, logger types.Logger, transport *stdio.StdioTransport) *stdioSession

NewStdioSession creates a new stdioSession instance.

func System added in v0.1.11

func System(msg string) protocol.PromptMessage

Define helper functions for prompt messages Note: "system" role is not valid according to MCP schemas - only "user" and "assistant" are allowed

func Text added in v0.1.11

func Text(msg string) protocol.Content

Text creates a protocol.Content of type text.

func User added in v0.1.11

func User(msg string) protocol.PromptMessage

Types

type Context added in v0.1.11

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

Context provides access to server capabilities within tool and resource handlers. It also embeds context.Context for cancellation.

func NewContext added in v0.1.11

func NewContext(parentCtx context.Context, requestID string, session types.ClientSession, progressToken interface{}, srv *Server) *Context

NewContext creates a new Context instance for a request. It requires a parent context (e.g., from context.WithCancel).

func (*Context) CallTool added in v0.1.11

func (c *Context) CallTool(toolName string, input interface{}) (json.RawMessage, *protocol.ToolError, error)

CallTool sends a 'tools/call' request to the client and waits for the result. This allows a server-side tool to invoke a client-side tool. Input is marshalled to JSON. Returns the raw JSON output from the client tool and any tool execution error reported by the client.

func (*Context) CreateMessage added in v0.1.11

CreateMessage sends a sampling/createMessage request to the connected client and waits for a response. This allows server-side logic (e.g., a tool) to request an LLM completion via the client.

func (*Context) Debug added in v0.1.11

func (c *Context) Debug(message string)

Debug sends a debug level log message.

func (*Context) Error added in v0.1.11

func (c *Context) Error(message string)

Error sends an error level log message.

func (*Context) Info added in v0.1.11

func (c *Context) Info(message string)

Info sends an info level log message.

func (*Context) Log added in v0.1.11

func (c *Context) Log(level string, message string)

Log sends a log message to the client.

func (*Context) ReadResource added in v0.1.11

func (c *Context) ReadResource(uri string) (protocol.ResourceContents, error)

ReadResource reads a resource from the server's registry.

func (*Context) ReportProgress added in v0.1.11

func (c *Context) ReportProgress(message string, current, total int)

ReportProgress reports the progress of a long-running operation.

func (*Context) Warning added in v0.1.11

func (c *Context) Warning(message string)

Warning sends a warning level log message.

type DuplicateHandling added in v0.1.11

type DuplicateHandling int

DuplicateHandling defines how to handle duplicate resource registrations

const (
	// DuplicateError returns an error when attempting to register a duplicate resource
	DuplicateError DuplicateHandling = iota
	// DuplicateReplace replaces the existing resource with the new one
	DuplicateReplace
	// DuplicateIgnore ignores the new resource and keeps the existing one
	DuplicateIgnore
	// DuplicateWarn logs a warning but replaces the existing resource
	DuplicateWarn
)

type Hooks added in v0.1.11

type Hooks struct {
}

Hooks holds slices of different hook functions.

func NewHooks added in v0.1.11

func NewHooks() *Hooks

NewHooks creates a new Hooks instance.

type LifecycleHandler added in v0.1.11

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

LifecycleHandler provides methods for handling MCP lifecycle messages.

func NewLifecycleHandler added in v0.1.11

func NewLifecycleHandler(srv *Server) *LifecycleHandler

NewLifecycleHandler creates a new LifecycleHandler instance.

func (*LifecycleHandler) ExitHandler added in v0.1.11

func (h *LifecycleHandler) ExitHandler()

ExitHandler handles the 'exit' notification.

func (*LifecycleHandler) InitializeHandler added in v0.1.11

InitializeHandler handles the 'initialize' request. It performs version negotiation and returns server capabilities. It now also returns the negotiated client capabilities.

func (*LifecycleHandler) InitializedHandler added in v0.1.11

func (h *LifecycleHandler) InitializedHandler()

InitializedHandler handles the 'initialized' notification.

func (*LifecycleHandler) ShutdownHandler added in v0.1.11

func (h *LifecycleHandler) ShutdownHandler() error

ShutdownHandler handles the 'shutdown' request.

type MessageHandler added in v0.1.11

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

MessageHandler handles incoming and outgoing MCP messages.

func NewMessageHandler added in v0.1.11

func NewMessageHandler(srv *Server) *MessageHandler

NewMessageHandler creates a new MessageHandler instance.

func (*MessageHandler) AddCancelFuncForTest added in v0.1.11

func (mh *MessageHandler) AddCancelFuncForTest(requestID string, cancel context.CancelFunc)

AddCancelFuncForTest adds a cancel function to the active cancels map for testing. WARNING: Use only in tests. Does not reflect the actual request handling flow.

func (*MessageHandler) GetCancelFuncForTest added in v0.1.11

func (mh *MessageHandler) GetCancelFuncForTest(requestID string) (context.CancelFunc, bool)

GetCancelFuncForTest retrieves a cancel function from the active cancels map for testing. WARNING: Use only in tests.

func (*MessageHandler) HandleMessage added in v0.1.11

func (mh *MessageHandler) HandleMessage(session types.ClientSession, message []byte) error

HandleMessage processes an incoming JSON-RPC message for a specific session. It unmarshals the message, dispatches it to the appropriate handler, and sends a response if necessary.

func (*MessageHandler) RegisterNotificationHandler added in v0.1.11

func (mh *MessageHandler) RegisterNotificationHandler(method string, handler func(params json.RawMessage))

func (*MessageHandler) SendLoggingMessage added in v0.1.11

func (mh *MessageHandler) SendLoggingMessage(level protocol.LoggingLevel, message string, logger *string, data interface{})

SendLoggingMessage sends a notifications/message notification to all connected clients. This is used by the server to send log messages to the client. TODO: Implement filtering based on client logging level preferences.

func (*MessageHandler) SendNotificationToConnections added in v0.1.11

func (mh *MessageHandler) SendNotificationToConnections(connectionIDs []string, notif *protocol.JSONRPCNotification)

SendNotificationToConnections sends a JSON-RPC notification to multiple connection IDs.

func (*MessageHandler) SendProgress added in v0.1.11

func (mh *MessageHandler) SendProgress(connectionID string, token interface{}, value interface{})

SendProgress sends a $/progress notification to a specific connection. token is the progress token from the request's _meta field. value is the progress data payload.

type Registry added in v0.1.11

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

Registry holds the registered tools, resources, and prompts.

func NewRegistry added in v0.1.11

func NewRegistry() *Registry

NewRegistry creates a new Registry instance.

func (*Registry) AddPrompt added in v0.1.11

func (r *Registry) AddPrompt(prompt protocol.Prompt) *Registry

AddPrompt registers a new prompt with the registry.

func (*Registry) AddResourceTemplate added in v0.1.11

func (r *Registry) AddResourceTemplate(uriPattern string, handlerFn any) error

AddResourceTemplate is a backward compatibility wrapper for RegisterResourceTemplate. It maintains the old signature for compatibility with existing code. DEPRECATED: Use Resource(uri, WithHandler(handlerFn)) instead.

func (*Registry) AddRoot added in v0.1.11

func (r *Registry) AddRoot(root protocol.Root) *Registry

AddRoot registers a new root with the registry.

func (*Registry) GetPrompt added in v0.1.11

func (r *Registry) GetPrompt(uri string) (protocol.Prompt, bool)

GetPrompt retrieves a specific prompt by its URI.

func (*Registry) GetPrompts added in v0.1.11

func (r *Registry) GetPrompts() []protocol.Prompt

GetPrompts returns a slice of all registered prompts.

func (*Registry) GetRegisteredResource added in v0.1.11

func (r *Registry) GetRegisteredResource(uri string) (*registeredResource, bool)

GetRegisteredResource retrieves the internal registered resource by its URI. This is primarily for internal use to access the resource config.

func (*Registry) GetResource added in v0.1.11

func (r *Registry) GetResource(uri string) (protocol.Resource, bool)

GetResource retrieves a resource by its URI. It currently only checks static resources registered via the new API.

func (*Registry) GetToolHandler added in v0.1.11

func (r *Registry) GetToolHandler(name string) (func(ctx *Context, rawArgs json.RawMessage) (interface{}, error), bool)

GetToolHandler retrieves the wrapper handler for a registered tool. This wrapper handles argument parsing/validation and calls the original function. It now accepts a pre-created Context instance.

func (*Registry) GetTools added in v0.1.11

func (r *Registry) GetTools() []protocol.Tool

GetTools returns a slice of all registered tools (protocol.Tool definition).

func (*Registry) RegisterResource added in v0.1.11

func (r *Registry) RegisterResource(resource protocol.Resource) *Registry

RegisterResource registers a new resource with the registry. DEPRECATED: Use Resource(uri, WithTextContent(...)) or Resource(uri, WithFileContent(...)) instead.

func (*Registry) RegisterResourceTemplate added in v0.1.11

func (r *Registry) RegisterResourceTemplate(uriPattern string, config resourceConfig) error

RegisterResourceTemplate registers a new resource template handler based on the provided config. It parses the URI pattern, validates the handler signature using reflection, and stores the information for later matching and invocation. Handler signature must be func(ctx types.Context, [param1 Type1, ...]) (ResultType, error).

func (*Registry) RegisterStaticResource added in v0.1.11

func (r *Registry) RegisterStaticResource(uri string, config resourceConfig) error

RegisterStaticResource registers a new static resource based on the provided config.

func (*Registry) RemovePrompt added in v0.1.11

func (r *Registry) RemovePrompt(name string) *Registry

RemovePrompt removes a prompt from the registry by name.

func (*Registry) RemoveRoot added in v0.1.11

func (r *Registry) RemoveRoot(root protocol.Root) *Registry

RemoveRoot removes a root from the registry.

func (*Registry) RemoveTool added in v0.1.11

func (r *Registry) RemoveTool(name string) *Registry

RemoveTool removes a tool from the registry.

func (*Registry) ResourceRegistry added in v0.1.11

func (r *Registry) ResourceRegistry() map[string]protocol.Resource

ResourceRegistry returns the map of registered resources (static ones). Note: This currently only returns static resources registered via the new API. Templates are handled separately.

func (*Registry) SetPromptChangedCallback added in v0.1.11

func (r *Registry) SetPromptChangedCallback(callback func())

SetPromptChangedCallback sets the callback function to be called when prompts change.

func (*Registry) SetResourceChangedCallback added in v0.1.11

func (r *Registry) SetResourceChangedCallback(callback func(uri string))

SetResourceChangedCallback sets the callback function to be called when resources change.

func (*Registry) SetToolChangedCallback added in v0.1.11

func (r *Registry) SetToolChangedCallback(callback func())

SetToolChangedCallback sets the callback function to be called when tools change.

func (*Registry) TemplateRegistry added in v0.1.11

func (r *Registry) TemplateRegistry() map[string]*resourceTemplateInfo

TemplateRegistry returns the map of registered resource templates.

func (*Registry) Tool added in v0.1.11

func (r *Registry) Tool(
	name, desc string,
	fn any,
) *Registry

Tool registers a new tool with the registry (non-generic method). The fn parameter should be a function with signature func(Context, Args) (Ret, error). This method stores the tool information and handler.

type ResourceDetails added in v0.1.11

type ResourceDetails struct {
	URI         string
	Kind        string
	Name        string
	Description string
}

ResourceDetails holds the details for adding a resource.

type ResourceOption added in v0.1.11

type ResourceOption func(*resourceConfig)

ResourceOption is a function type that modifies a resourceConfig.

func WithAnnotations added in v0.1.11

func WithAnnotations(annotations map[string]any) ResourceOption

WithAnnotations adds custom annotations to the resource/template metadata.

func WithAsync added in v0.1.11

func WithAsync(progressTemplate string) ResourceOption

WithAsync marks a resource handler as asynchronous. Async handlers will be executed in a separate goroutine and can report progress.

func WithBinaryContent added in v0.1.11

func WithBinaryContent(data []byte) ResourceOption

WithBinaryContent specifies static binary content for a resource.

func WithContentTypeInference added in v0.1.11

func WithContentTypeInference(enabled bool) ResourceOption

WithContentTypeInference enables or disables automatic content type inference. When enabled (default), the system will try to infer the content type based on file extensions, content patterns, etc.

func WithCustomKey added in v0.1.11

func WithCustomKey(key string) ResourceOption

WithCustomKey sets a custom key to identify this resource in the registry. By default, the URI is used as the key.

func WithDefaultParamValue added in v0.1.11

func WithDefaultParamValue(paramName string, defaultValue interface{}) ResourceOption

WithDefaultParamValue sets a default value for a template parameter. If the parameter is not provided in the URI or is empty, this default value will be used.

func WithDescription added in v0.1.11

func WithDescription(description string) ResourceOption

WithDescription sets a custom description for the resource/template.

func WithDirectoryListing added in v0.1.11

func WithDirectoryListing(dirPath string) ResourceOption

WithDirectoryListing specifies that the resource should provide a listing of files in a local directory.

func WithDuplicateHandling added in v0.1.11

func WithDuplicateHandling(handling DuplicateHandling) ResourceOption

WithDuplicateHandling sets how to handle duplicate resource registrations

func WithFileContent added in v0.1.11

func WithFileContent(filePath string) ResourceOption

WithFileContent specifies that the resource content should be read from a local file path when requested.

func WithHandler added in v0.1.11

func WithHandler(handlerFn any) ResourceOption

WithHandler specifies the handler function for a dynamic resource or resource template.

func WithMimeType added in v0.1.11

func WithMimeType(mimeType string) ResourceOption

WithMimeType explicitly sets the MIME type for the resource/template.

func WithMultipleURIs added in v0.1.11

func WithMultipleURIs(additionalURIs ...string) ResourceOption

WithMultipleURIs registers the same resource under multiple URI patterns. This allows a single resource to be accessible via different URI patterns.

func WithName added in v0.1.11

func WithName(name string) ResourceOption

WithName sets a custom human-readable name for the resource/template.

func WithReturnTypeConversion added in v0.1.11

func WithReturnTypeConversion(converter func(interface{}) ([]protocol.ResourceContents, error)) ResourceOption

WithReturnTypeConversion configures how return values from resource handlers are converted to ResourceContents. This is useful for custom type conversions.

func WithTags added in v0.1.11

func WithTags(tags ...string) ResourceOption

WithTags adds categorization tags to the resource/template.

func WithTextContent added in v0.1.11

func WithTextContent(text string) ResourceOption

WithTextContent specifies static text content for a resource.

func WithURLContent added in v0.1.11

func WithURLContent(url string) ResourceOption

WithURLContent specifies that the resource content should be fetched from an HTTP(S) URL when requested.

func WithWildcardParam added in v0.1.11

func WithWildcardParam(paramName string) ResourceOption

WithWildcardParam enables a wildcard parameter in a resource template. This allows a parameter to match multiple path segments like `/docs/{path*}/edit` which would match `/docs/a/b/c/edit` and extract path="a/b/c". Note: The wildcard syntax is already supported in the wilduri library.

type RootDetails added in v0.1.11

type RootDetails struct {
	URI         string
	Kind        string
	Name        string
	Description string
}

RootDetails holds the details for adding a root.

type Server

type Server struct {
	*Hooks // Embed Hooks struct

	// Transport Management
	TransportManager *TransportManager

	// State Management
	Registry            *Registry
	SubscriptionManager *SubscriptionManager
	MessageHandler      *MessageHandler

	// Capability Flags (reflect server implementation status)
	ImplementsResourceSubscription bool
	ImplementsResourceListChanged  bool
	ImplementsPromptListChanged    bool
	ImplementsToolListChanged      bool
	ImplementsLogging              bool
	ImplementsCompletions          bool // Tracks if completion/complete (V2024) is implemented
	ImplementsSampling             bool // Tracks if sampling/createMessage (V2025) can be sent
	ImplementsAuthorization        bool
	// contains filtered or unexported fields
}

Server represents the main MCP server instance.

func NewServer

func NewServer(name string) *Server

NewServer creates a new Server instance.

func (*Server) AsSSE added in v0.1.11

func (s *Server) AsSSE(addr string, basePath string) *Server

AsSSE configures the server to use Server-Sent Events as its transport.

func (*Server) AsStdio added in v0.1.11

func (s *Server) AsStdio() *Server

AsStdio configures the server to use standard I/O as its transport.

func (*Server) AsWebsocket added in v0.1.11

func (s *Server) AsWebsocket(addr string, path string) *Server

AsWebsocket configures the server to use WebSocket as its transport.

func (*Server) Close added in v0.1.11

func (s *Server) Close() error

Close gracefully shuts down the server.

func (*Server) NotifyResourceUpdated

func (s *Server) NotifyResourceUpdated(uri string)

NotifyResourceUpdated triggers a resource update notification for subscribers.

func (*Server) Prompt added in v0.1.11

func (s *Server) Prompt(name, description string, messages ...protocol.PromptMessage) *Server

Prompt registers a new prompt with the server's registry.

func (*Server) Resource added in v0.1.11

func (s *Server) Resource(uri string, options ...ResourceOption) *Server

Resource registers a new static resource or dynamic resource template with the server's registry. It uses a flexible options pattern for configuration.

Example:

server.Resource("/static/data.txt", WithTextContent("Hello"), WithMimeType("text/plain"))
server.Resource("/api/users/{id}", WithHandler(getUserHandler), WithDescription("Fetches user data"))

func (*Server) Root added in v0.1.11

func (s *Server) Root(root protocol.Root) *Server

Root registers a new root with the server's registry.

func (*Server) Run added in v0.1.11

func (s *Server) Run() error

Run starts the configured transport(s) and blocks until the server is closed.

func (*Server) Tool added in v0.1.11

func (s *Server) Tool(
	name, desc string,
	fn any,
) *Server

Tool registers a new tool with the server's registry. The fn parameter should be a function with a single struct argument and returns (any, error).

type SubscriptionManager added in v0.1.11

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

SubscriptionManager manages resource subscriptions for client connections.

func NewSubscriptionManager added in v0.1.11

func NewSubscriptionManager() *SubscriptionManager

NewSubscriptionManager creates a new SubscriptionManager.

func (*SubscriptionManager) GetSubscribedConnectionIDs added in v0.1.11

func (sm *SubscriptionManager) GetSubscribedConnectionIDs(uri string) []string

GetSubscribedConnectionIDs returns a list of connection IDs subscribed to a resource URI.

func (*SubscriptionManager) IsSubscribed added in v0.1.11

func (sm *SubscriptionManager) IsSubscribed(uri string, connectionID string) bool

IsSubscribed checks if a specific connection ID is subscribed to a given URI.

func (*SubscriptionManager) Subscribe added in v0.1.11

func (sm *SubscriptionManager) Subscribe(uri, connectionID string)

Subscribe adds a subscription for a given connection ID to a resource URI.

func (*SubscriptionManager) Unsubscribe added in v0.1.11

func (sm *SubscriptionManager) Unsubscribe(uri, connectionID string)

Unsubscribe removes a subscription for a given connection ID from a resource URI.

func (*SubscriptionManager) UnsubscribeAll added in v0.1.11

func (sm *SubscriptionManager) UnsubscribeAll(connectionID string)

UnsubscribeAll removes all subscriptions for a given connection ID.

type TransportManager added in v0.1.11

type TransportManager struct {

	// Map to store active client sessions (sessionID -> session)
	Sessions map[string]types.ClientSession
	// Add a map to store capabilities per session ID
	Capabilities map[string]*protocol.ClientCapabilities
	// contains filtered or unexported fields
}

TransportManager handles the server's transport mechanisms.

func NewTransportManager added in v0.1.11

func NewTransportManager() *TransportManager

NewTransportManager creates a new TransportManager.

func (*TransportManager) AsSSE added in v0.1.11

func (tm *TransportManager) AsSSE(s *Server, addr string, basePath string) *Server

AsSSE configures the server to use Server-Sent Events as its transport.

func (*TransportManager) AsStdio added in v0.1.11

func (tm *TransportManager) AsStdio(s *Server) *Server

AsStdio configures the server to use standard I/O as its transport.

func (*TransportManager) AsWebsocket added in v0.1.11

func (tm *TransportManager) AsWebsocket(s *Server, addr string, path string) *Server

AsWebsocket configures the server to use WebSocket as its transport.

func (*TransportManager) GetAllSessionIDs added in v0.1.11

func (tm *TransportManager) GetAllSessionIDs() []string

GetAllSessionIDs returns a slice of all active session IDs.

func (*TransportManager) GetSession added in v0.1.11

GetSession retrieves a client session by its ID. It now also returns the client's capabilities.

func (*TransportManager) RegisterSession added in v0.1.11

func (tm *TransportManager) RegisterSession(session types.ClientSession, caps *protocol.ClientCapabilities)

RegisterSession adds a new client session to the manager.

func (*TransportManager) RemoveSession added in v0.1.11

func (tm *TransportManager) RemoveSession(sessionID string)

RemoveSession removes a client session from the manager.

func (*TransportManager) Run added in v0.1.11

func (tm *TransportManager) Run(s *Server) error

Run starts the selected transport.

func (*TransportManager) SendMessage deprecated added in v0.1.11

func (tm *TransportManager) SendMessage(sessionID string, message []byte) error

Deprecated: SendMessage sends a raw message to a specific connection ID. Prefer using session.SendResponse or session.SendNotification.

func (*TransportManager) Shutdown added in v0.1.11

func (tm *TransportManager) Shutdown()

Shutdown signals the transport manager to stop accepting new connections.

type TransportType added in v0.1.11

type TransportType int

TransportType represents the type of transport.

const (
	TransportNone TransportType = iota
	TransportStdio
	TransportWebsocket
	TransportSSE
)

Jump to

Keyboard shortcuts

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