Documentation
¶
Overview ¶
Code generated by `go generate`. DO NOT EDIT. source: server/internal/gen/hooks.go.tmpl
Code generated by `go generate`. DO NOT EDIT. source: server/internal/gen/request_handler.go.tmpl
Package server provides MCP (Model Context Protocol) server implementations.
Index ¶
- Variables
- func NewTestServer(server *MCPServer, opts ...SSEOption) *httptest.Server
- func NewTestStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *httptest.Server
- func ServeStdio(server *MCPServer, opts ...StdioOption) error
- type BeforeAnyHookFunc
- type ClientSession
- type CompletionHandlerFunc
- type DynamicBasePathFunc
- type ErrDynamicPathConfig
- type HTTPContextFunc
- type Hooks
- func (c *Hooks) AddAfterCallTool(hook OnAfterCallToolFunc)
- func (c *Hooks) AddAfterComplete(hook OnAfterCompleteFunc)
- func (c *Hooks) AddAfterGetPrompt(hook OnAfterGetPromptFunc)
- func (c *Hooks) AddAfterInitialize(hook OnAfterInitializeFunc)
- func (c *Hooks) AddAfterListPrompts(hook OnAfterListPromptsFunc)
- func (c *Hooks) AddAfterListResourceTemplates(hook OnAfterListResourceTemplatesFunc)
- func (c *Hooks) AddAfterListResources(hook OnAfterListResourcesFunc)
- func (c *Hooks) AddAfterListTools(hook OnAfterListToolsFunc)
- func (c *Hooks) AddAfterPing(hook OnAfterPingFunc)
- func (c *Hooks) AddAfterReadResource(hook OnAfterReadResourceFunc)
- func (c *Hooks) AddAfterSetLevel(hook OnAfterSetLevelFunc)
- func (c *Hooks) AddBeforeAny(hook BeforeAnyHookFunc)
- func (c *Hooks) AddBeforeCallTool(hook OnBeforeCallToolFunc)
- func (c *Hooks) AddBeforeComplete(hook OnBeforeCompleteFunc)
- func (c *Hooks) AddBeforeGetPrompt(hook OnBeforeGetPromptFunc)
- func (c *Hooks) AddBeforeInitialize(hook OnBeforeInitializeFunc)
- func (c *Hooks) AddBeforeListPrompts(hook OnBeforeListPromptsFunc)
- func (c *Hooks) AddBeforeListResourceTemplates(hook OnBeforeListResourceTemplatesFunc)
- func (c *Hooks) AddBeforeListResources(hook OnBeforeListResourcesFunc)
- func (c *Hooks) AddBeforeListTools(hook OnBeforeListToolsFunc)
- func (c *Hooks) AddBeforePing(hook OnBeforePingFunc)
- func (c *Hooks) AddBeforeReadResource(hook OnBeforeReadResourceFunc)
- func (c *Hooks) AddBeforeSetLevel(hook OnBeforeSetLevelFunc)
- func (c *Hooks) AddOnError(hook OnErrorHookFunc)
- func (c *Hooks) AddOnRegisterSession(hook OnRegisterSessionHookFunc)
- func (c *Hooks) AddOnRequestInitialization(hook OnRequestInitializationFunc)
- func (c *Hooks) AddOnSuccess(hook OnSuccessHookFunc)
- func (c *Hooks) AddOnUnregisterSession(hook OnUnregisterSessionHookFunc)
- func (c *Hooks) RegisterSession(ctx context.Context, session ClientSession)
- func (c *Hooks) UnregisterSession(ctx context.Context, session ClientSession)
- type InsecureStatefulSessionIdManager
- type MCPServer
- func (s *MCPServer) AddNotificationHandler(method string, handler NotificationHandlerFunc)
- func (s *MCPServer) AddPrompt(prompt mcp.Prompt, handler PromptHandlerFunc)
- func (s *MCPServer) AddResource(resource mcp.Resource, handler ResourceHandlerFunc)
- func (s *MCPServer) AddResourceTemplate(template mcp.ResourceTemplate, handler ResourceTemplateHandlerFunc)
- func (s *MCPServer) AddSessionTool(sessionID string, tool mcp.Tool, handler ToolHandlerFunc) error
- func (s *MCPServer) AddSessionTools(sessionID string, tools ...ServerTool) error
- func (s *MCPServer) AddTool(tool mcp.Tool, handler ToolHandlerFunc)
- func (s *MCPServer) AddTools(tools ...ServerTool)
- func (s *MCPServer) DeletePrompts(names ...string)
- func (s *MCPServer) DeleteSessionTools(sessionID string, names ...string) error
- func (s *MCPServer) DeleteTools(names ...string)
- func (s *MCPServer) HandleMessage(ctx context.Context, message json.RawMessage) mcp.JSONRPCMessage
- func (s *MCPServer) RegisterSession(ctx context.Context, session ClientSession) error
- func (s *MCPServer) RemoveResource(uri string)
- func (s *MCPServer) SendNotificationToAllClients(method string, params map[string]any)
- func (s *MCPServer) SendNotificationToClient(ctx context.Context, method string, params map[string]any) error
- func (s *MCPServer) SendNotificationToSpecificClient(sessionID string, method string, params map[string]any) error
- func (s *MCPServer) SetTools(tools ...ServerTool)
- func (s *MCPServer) UnregisterSession(ctx context.Context, sessionID string)
- func (s *MCPServer) WithContext(ctx context.Context, session ClientSession) context.Context
- type NotificationHandlerFunc
- type OnAfterCallToolFunc
- type OnAfterCompleteFunc
- type OnAfterGetPromptFunc
- type OnAfterInitializeFunc
- type OnAfterListPromptsFunc
- type OnAfterListResourceTemplatesFunc
- type OnAfterListResourcesFunc
- type OnAfterListToolsFunc
- type OnAfterPingFunc
- type OnAfterReadResourceFunc
- type OnAfterSetLevelFunc
- type OnBeforeCallToolFunc
- type OnBeforeCompleteFunc
- type OnBeforeGetPromptFunc
- type OnBeforeInitializeFunc
- type OnBeforeListPromptsFunc
- type OnBeforeListResourceTemplatesFunc
- type OnBeforeListResourcesFunc
- type OnBeforeListToolsFunc
- type OnBeforePingFunc
- type OnBeforeReadResourceFunc
- type OnBeforeSetLevelFunc
- type OnErrorHookFunc
- type OnRegisterSessionHookFunc
- type OnRequestInitializationFunc
- type OnSuccessHookFunc
- type OnUnregisterSessionHookFunc
- type PromptHandlerFunc
- type ResourceHandlerFunc
- type ResourceTemplateHandlerFunc
- type SSEContextFunc
- type SSEOption
- func WithAppendQueryToMessageEndpoint() SSEOption
- func WithBasePath(basePath string) SSEOptiondeprecated
- func WithBaseURL(baseURL string) SSEOption
- func WithDynamicBasePath(fn DynamicBasePathFunc) SSEOption
- func WithHTTPServer(srv *http.Server) SSEOption
- func WithKeepAlive(keepAlive bool) SSEOption
- func WithKeepAliveInterval(keepAliveInterval time.Duration) SSEOption
- func WithMessageEndpoint(endpoint string) SSEOption
- func WithSSEContextFunc(fn SSEContextFunc) SSEOption
- func WithSSEEndpoint(endpoint string) SSEOption
- func WithStaticBasePath(basePath string) SSEOption
- func WithUseFullURLForMessageEndpoint(useFullURLForMessageEndpoint bool) SSEOption
- type SSEServer
- func (s *SSEServer) CompleteMessageEndpoint() (string, error)
- func (s *SSEServer) CompleteMessagePath() string
- func (s *SSEServer) CompleteSseEndpoint() (string, error)
- func (s *SSEServer) CompleteSsePath() string
- func (s *SSEServer) GetMessageEndpointForClient(r *http.Request, sessionID string) string
- func (s *SSEServer) GetUrlPath(input string) (string, error)
- func (s *SSEServer) MessageHandler() http.Handler
- func (s *SSEServer) SSEHandler() http.Handler
- func (s *SSEServer) SendEventToSession(sessionID string, event any) error
- func (s *SSEServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *SSEServer) Shutdown(ctx context.Context) error
- func (s *SSEServer) Start(addr string) error
- type ServerOption
- func WithCompletion(handler CompletionHandlerFunc) ServerOption
- func WithHooks(hooks *Hooks) ServerOption
- func WithInstructions(instructions string) ServerOption
- func WithLogging() ServerOption
- func WithPaginationLimit(limit int) ServerOption
- func WithPromptCapabilities(listChanged bool) ServerOption
- func WithRecovery() ServerOption
- func WithResourceCapabilities(subscribe, listChanged bool) ServerOption
- func WithToolCapabilities(listChanged bool) ServerOption
- func WithToolFilter(toolFilter ToolFilterFunc) ServerOption
- func WithToolHandlerMiddleware(toolHandlerMiddleware ToolHandlerMiddleware) ServerOption
- type ServerTool
- type SessionIdManager
- type SessionWithClientInfo
- type SessionWithLogging
- type SessionWithTools
- type StatelessSessionIdManager
- type StdioContextFunc
- type StdioOption
- type StdioServer
- type StreamableHTTPOption
- func WithEndpointPath(endpointPath string) StreamableHTTPOption
- func WithHTTPContextFunc(fn HTTPContextFunc) StreamableHTTPOption
- func WithHeartbeatInterval(interval time.Duration) StreamableHTTPOption
- func WithLogger(logger util.Logger) StreamableHTTPOption
- func WithSessionIdManager(manager SessionIdManager) StreamableHTTPOption
- func WithStateLess(stateLess bool) StreamableHTTPOption
- type StreamableHTTPServer
- type ToolFilterFunc
- type ToolHandlerFunc
- type ToolHandlerMiddleware
- type UnparsableMessageError
Constants ¶
This section is empty.
Variables ¶
var ( // Common server errors ErrUnsupported = errors.New("not supported") ErrResourceNotFound = errors.New("resource not found") ErrPromptNotFound = errors.New("prompt not found") ErrToolNotFound = errors.New("tool not found") // Session-related errors ErrSessionNotFound = errors.New("session not found") ErrSessionExists = errors.New("session already exists") ErrSessionNotInitialized = errors.New("session not properly initialized") ErrSessionDoesNotSupportTools = errors.New("session does not support per-session tools") ErrSessionDoesNotSupportLogging = errors.New("session does not support setting logging level") // Notification-related errors ErrNotificationNotInitialized = errors.New("notification channel not initialized") ErrNotificationChannelBlocked = errors.New("notification channel full or blocked") )
Functions ¶
func NewTestServer ¶
NewTestServer creates a test server for testing purposes
func NewTestStreamableHTTPServer ¶
func NewTestStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *httptest.Server
NewTestStreamableHTTPServer creates a test server for testing purposes
func ServeStdio ¶
func ServeStdio(server *MCPServer, opts ...StdioOption) error
ServeStdio is a convenience function that creates and starts a StdioServer with os.Stdin and os.Stdout. It sets up signal handling for graceful shutdown on SIGTERM and SIGINT. Returns an error if the server encounters any issues during operation.
Types ¶
type BeforeAnyHookFunc ¶
BeforeAnyHookFunc is a function that is called after the request is parsed but before the method is called.
type ClientSession ¶
type ClientSession interface { // Initialize marks session as fully initialized and ready for notifications Initialize() // Initialized returns if session is ready to accept notifications Initialized() bool // NotificationChannel provides a channel suitable for sending notifications to client. NotificationChannel() chan<- mcp.JSONRPCNotification // SessionID is a unique identifier used to track user session. SessionID() string }
ClientSession represents an active session that can be used by MCPServer to interact with client.
func ClientSessionFromContext ¶
func ClientSessionFromContext(ctx context.Context) ClientSession
ClientSessionFromContext retrieves current client notification context from context.
type CompletionHandlerFunc ¶
type CompletionHandlerFunc func(ctx context.Context, request mcp.CompleteRequest) (*mcp.CompleteResult, error)
CompletionHandlerFunc handles completion requests.
type DynamicBasePathFunc ¶
DynamicBasePathFunc allows the user to provide a function to generate the base path for a given request and sessionID. This is useful for cases where the base path is not known at the time of SSE server creation, such as when using a reverse proxy or when the base path is dynamically generated. The function should return the base path (e.g., "/mcp/tenant123").
type ErrDynamicPathConfig ¶
type ErrDynamicPathConfig struct {
Method string
}
ErrDynamicPathConfig is returned when attempting to use static path methods with dynamic path configuration
func (*ErrDynamicPathConfig) Error ¶
func (e *ErrDynamicPathConfig) Error() string
type HTTPContextFunc ¶
HTTPContextFunc is a function that takes an existing context and the current request and returns a potentially modified context based on the request content. This can be used to inject context values from headers, for example.
type Hooks ¶
type Hooks struct { OnRegisterSession []OnRegisterSessionHookFunc OnUnregisterSession []OnUnregisterSessionHookFunc OnBeforeAny []BeforeAnyHookFunc OnSuccess []OnSuccessHookFunc OnError []OnErrorHookFunc OnRequestInitialization []OnRequestInitializationFunc OnBeforeInitialize []OnBeforeInitializeFunc OnAfterInitialize []OnAfterInitializeFunc OnBeforePing []OnBeforePingFunc OnAfterPing []OnAfterPingFunc OnBeforeSetLevel []OnBeforeSetLevelFunc OnAfterSetLevel []OnAfterSetLevelFunc OnBeforeListResources []OnBeforeListResourcesFunc OnAfterListResources []OnAfterListResourcesFunc OnBeforeListResourceTemplates []OnBeforeListResourceTemplatesFunc OnAfterListResourceTemplates []OnAfterListResourceTemplatesFunc OnBeforeReadResource []OnBeforeReadResourceFunc OnAfterReadResource []OnAfterReadResourceFunc OnBeforeListPrompts []OnBeforeListPromptsFunc OnAfterListPrompts []OnAfterListPromptsFunc OnBeforeGetPrompt []OnBeforeGetPromptFunc OnAfterGetPrompt []OnAfterGetPromptFunc OnBeforeListTools []OnBeforeListToolsFunc OnAfterListTools []OnAfterListToolsFunc OnBeforeCallTool []OnBeforeCallToolFunc OnAfterCallTool []OnAfterCallToolFunc OnBeforeComplete []OnBeforeCompleteFunc OnAfterComplete []OnAfterCompleteFunc }
func (*Hooks) AddAfterCallTool ¶
func (c *Hooks) AddAfterCallTool(hook OnAfterCallToolFunc)
func (*Hooks) AddAfterComplete ¶
func (c *Hooks) AddAfterComplete(hook OnAfterCompleteFunc)
func (*Hooks) AddAfterGetPrompt ¶
func (c *Hooks) AddAfterGetPrompt(hook OnAfterGetPromptFunc)
func (*Hooks) AddAfterInitialize ¶
func (c *Hooks) AddAfterInitialize(hook OnAfterInitializeFunc)
func (*Hooks) AddAfterListPrompts ¶
func (c *Hooks) AddAfterListPrompts(hook OnAfterListPromptsFunc)
func (*Hooks) AddAfterListResourceTemplates ¶
func (c *Hooks) AddAfterListResourceTemplates(hook OnAfterListResourceTemplatesFunc)
func (*Hooks) AddAfterListResources ¶
func (c *Hooks) AddAfterListResources(hook OnAfterListResourcesFunc)
func (*Hooks) AddAfterListTools ¶
func (c *Hooks) AddAfterListTools(hook OnAfterListToolsFunc)
func (*Hooks) AddAfterPing ¶
func (c *Hooks) AddAfterPing(hook OnAfterPingFunc)
func (*Hooks) AddAfterReadResource ¶
func (c *Hooks) AddAfterReadResource(hook OnAfterReadResourceFunc)
func (*Hooks) AddAfterSetLevel ¶
func (c *Hooks) AddAfterSetLevel(hook OnAfterSetLevelFunc)
func (*Hooks) AddBeforeAny ¶
func (c *Hooks) AddBeforeAny(hook BeforeAnyHookFunc)
func (*Hooks) AddBeforeCallTool ¶
func (c *Hooks) AddBeforeCallTool(hook OnBeforeCallToolFunc)
func (*Hooks) AddBeforeComplete ¶
func (c *Hooks) AddBeforeComplete(hook OnBeforeCompleteFunc)
func (*Hooks) AddBeforeGetPrompt ¶
func (c *Hooks) AddBeforeGetPrompt(hook OnBeforeGetPromptFunc)
func (*Hooks) AddBeforeInitialize ¶
func (c *Hooks) AddBeforeInitialize(hook OnBeforeInitializeFunc)
func (*Hooks) AddBeforeListPrompts ¶
func (c *Hooks) AddBeforeListPrompts(hook OnBeforeListPromptsFunc)
func (*Hooks) AddBeforeListResourceTemplates ¶
func (c *Hooks) AddBeforeListResourceTemplates(hook OnBeforeListResourceTemplatesFunc)
func (*Hooks) AddBeforeListResources ¶
func (c *Hooks) AddBeforeListResources(hook OnBeforeListResourcesFunc)
func (*Hooks) AddBeforeListTools ¶
func (c *Hooks) AddBeforeListTools(hook OnBeforeListToolsFunc)
func (*Hooks) AddBeforePing ¶
func (c *Hooks) AddBeforePing(hook OnBeforePingFunc)
func (*Hooks) AddBeforeReadResource ¶
func (c *Hooks) AddBeforeReadResource(hook OnBeforeReadResourceFunc)
func (*Hooks) AddBeforeSetLevel ¶
func (c *Hooks) AddBeforeSetLevel(hook OnBeforeSetLevelFunc)
func (*Hooks) AddOnError ¶
func (c *Hooks) AddOnError(hook OnErrorHookFunc)
AddOnError registers a hook function that will be called when an error occurs. The error parameter contains the actual error object, which can be interrogated using Go's error handling patterns like errors.Is and errors.As.
Example: ``` // Create a channel to receive errors for testing errChan := make(chan error, 1)
// Register hook to capture and inspect errors hooks := &Hooks{}
hooks.AddOnError(func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) { // For capability-related errors if errors.Is(err, ErrUnsupported) { // Handle capability not supported errChan <- err return } // For parsing errors var parseErr = &UnparsableMessageError{} if errors.As(err, &parseErr) { // Handle unparsable message errors fmt.Printf("Failed to parse %s request: %v\n", parseErr.GetMethod(), parseErr.Unwrap()) errChan <- parseErr return } // For resource/prompt/tool not found errors if errors.Is(err, ErrResourceNotFound) || errors.Is(err, ErrPromptNotFound) || errors.Is(err, ErrToolNotFound) { // Handle not found errors errChan <- err return } // For other errors errChan <- err })
server := NewMCPServer("test-server", "1.0.0", WithHooks(hooks)) ```
func (*Hooks) AddOnRegisterSession ¶
func (c *Hooks) AddOnRegisterSession(hook OnRegisterSessionHookFunc)
func (*Hooks) AddOnRequestInitialization ¶
func (c *Hooks) AddOnRequestInitialization(hook OnRequestInitializationFunc)
func (*Hooks) AddOnSuccess ¶
func (c *Hooks) AddOnSuccess(hook OnSuccessHookFunc)
func (*Hooks) AddOnUnregisterSession ¶
func (c *Hooks) AddOnUnregisterSession(hook OnUnregisterSessionHookFunc)
func (*Hooks) RegisterSession ¶
func (c *Hooks) RegisterSession(ctx context.Context, session ClientSession)
func (*Hooks) UnregisterSession ¶
func (c *Hooks) UnregisterSession(ctx context.Context, session ClientSession)
type InsecureStatefulSessionIdManager ¶
type InsecureStatefulSessionIdManager struct{}
InsecureStatefulSessionIdManager generate id with uuid It won't validate the id indeed, so it could be fake. For more secure session id, use a more complex generator, like a JWT.
func (*InsecureStatefulSessionIdManager) Generate ¶
func (s *InsecureStatefulSessionIdManager) Generate() string
type MCPServer ¶
type MCPServer struct {
// contains filtered or unexported fields
}
MCPServer implements a Model Context Protocol server that can handle various types of requests including resources, prompts, and tools.
func NewMCPServer ¶
func NewMCPServer( name, version string, opts ...ServerOption, ) *MCPServer
NewMCPServer creates a new MCP server instance with the given name, version and options
func ServerFromContext ¶
ServerFromContext retrieves the MCPServer instance from a context
func (*MCPServer) AddNotificationHandler ¶
func (s *MCPServer) AddNotificationHandler( method string, handler NotificationHandlerFunc, )
AddNotificationHandler registers a new handler for incoming notifications
func (*MCPServer) AddPrompt ¶
func (s *MCPServer) AddPrompt(prompt mcp.Prompt, handler PromptHandlerFunc)
AddPrompt registers a new prompt handler with the given name
func (*MCPServer) AddResource ¶
func (s *MCPServer) AddResource( resource mcp.Resource, handler ResourceHandlerFunc, )
AddResource registers a new resource and its handler
func (*MCPServer) AddResourceTemplate ¶
func (s *MCPServer) AddResourceTemplate( template mcp.ResourceTemplate, handler ResourceTemplateHandlerFunc, )
AddResourceTemplate registers a new resource template and its handler
func (*MCPServer) AddSessionTool ¶
AddSessionTool adds a tool for a specific session
func (*MCPServer) AddSessionTools ¶
func (s *MCPServer) AddSessionTools(sessionID string, tools ...ServerTool) error
AddSessionTools adds tools for a specific session
func (*MCPServer) AddTool ¶
func (s *MCPServer) AddTool(tool mcp.Tool, handler ToolHandlerFunc)
AddTool registers a new tool and its handler
func (*MCPServer) AddTools ¶
func (s *MCPServer) AddTools(tools ...ServerTool)
AddTools registers multiple tools at once
func (*MCPServer) DeletePrompts ¶
DeletePrompts removes prompts from the server
func (*MCPServer) DeleteSessionTools ¶
DeleteSessionTools removes tools from a specific session
func (*MCPServer) DeleteTools ¶
DeleteTools removes tools from the server
func (*MCPServer) HandleMessage ¶
func (s *MCPServer) HandleMessage( ctx context.Context, message json.RawMessage, ) mcp.JSONRPCMessage
HandleMessage processes an incoming JSON-RPC message and returns an appropriate response
func (*MCPServer) RegisterSession ¶
func (s *MCPServer) RegisterSession( ctx context.Context, session ClientSession, ) error
RegisterSession saves session that should be notified in case if some server attributes changed.
func (*MCPServer) RemoveResource ¶
RemoveResource removes a resource from the server
func (*MCPServer) SendNotificationToAllClients ¶
SendNotificationToAllClients sends a notification to all the currently active clients.
func (*MCPServer) SendNotificationToClient ¶
func (s *MCPServer) SendNotificationToClient( ctx context.Context, method string, params map[string]any, ) error
SendNotificationToClient sends a notification to the current client
func (*MCPServer) SendNotificationToSpecificClient ¶
func (s *MCPServer) SendNotificationToSpecificClient( sessionID string, method string, params map[string]any, ) error
SendNotificationToSpecificClient sends a notification to a specific client by session ID
func (*MCPServer) SetTools ¶
func (s *MCPServer) SetTools(tools ...ServerTool)
SetTools replaces all existing tools with the provided list
func (*MCPServer) UnregisterSession ¶
UnregisterSession removes from storage session that is shut down.
func (*MCPServer) WithContext ¶
WithContext sets the current client session and returns the provided context
type NotificationHandlerFunc ¶
type NotificationHandlerFunc func(ctx context.Context, notification mcp.JSONRPCNotification)
NotificationHandlerFunc handles incoming notifications.
type OnAfterCallToolFunc ¶
type OnAfterCallToolFunc func(ctx context.Context, id any, message *mcp.CallToolRequest, result *mcp.CallToolResult)
type OnAfterCompleteFunc ¶
type OnAfterCompleteFunc func(ctx context.Context, id any, message *mcp.CompleteRequest, result *mcp.CompleteResult)
type OnAfterGetPromptFunc ¶
type OnAfterGetPromptFunc func(ctx context.Context, id any, message *mcp.GetPromptRequest, result *mcp.GetPromptResult)
type OnAfterInitializeFunc ¶
type OnAfterInitializeFunc func(ctx context.Context, id any, message *mcp.InitializeRequest, result *mcp.InitializeResult)
type OnAfterListPromptsFunc ¶
type OnAfterListPromptsFunc func(ctx context.Context, id any, message *mcp.ListPromptsRequest, result *mcp.ListPromptsResult)
type OnAfterListResourceTemplatesFunc ¶
type OnAfterListResourceTemplatesFunc func(ctx context.Context, id any, message *mcp.ListResourceTemplatesRequest, result *mcp.ListResourceTemplatesResult)
type OnAfterListResourcesFunc ¶
type OnAfterListResourcesFunc func(ctx context.Context, id any, message *mcp.ListResourcesRequest, result *mcp.ListResourcesResult)
type OnAfterListToolsFunc ¶
type OnAfterListToolsFunc func(ctx context.Context, id any, message *mcp.ListToolsRequest, result *mcp.ListToolsResult)
type OnAfterPingFunc ¶
type OnAfterPingFunc func(ctx context.Context, id any, message *mcp.PingRequest, result *mcp.EmptyResult)
type OnAfterReadResourceFunc ¶
type OnAfterReadResourceFunc func(ctx context.Context, id any, message *mcp.ReadResourceRequest, result *mcp.ReadResourceResult)
type OnAfterSetLevelFunc ¶
type OnAfterSetLevelFunc func(ctx context.Context, id any, message *mcp.SetLevelRequest, result *mcp.EmptyResult)
type OnBeforeCallToolFunc ¶
type OnBeforeCallToolFunc func(ctx context.Context, id any, message *mcp.CallToolRequest)
type OnBeforeCompleteFunc ¶
type OnBeforeCompleteFunc func(ctx context.Context, id any, message *mcp.CompleteRequest)
type OnBeforeGetPromptFunc ¶
type OnBeforeGetPromptFunc func(ctx context.Context, id any, message *mcp.GetPromptRequest)
type OnBeforeInitializeFunc ¶
type OnBeforeInitializeFunc func(ctx context.Context, id any, message *mcp.InitializeRequest)
type OnBeforeListPromptsFunc ¶
type OnBeforeListPromptsFunc func(ctx context.Context, id any, message *mcp.ListPromptsRequest)
type OnBeforeListResourceTemplatesFunc ¶
type OnBeforeListResourceTemplatesFunc func(ctx context.Context, id any, message *mcp.ListResourceTemplatesRequest)
type OnBeforeListResourcesFunc ¶
type OnBeforeListResourcesFunc func(ctx context.Context, id any, message *mcp.ListResourcesRequest)
type OnBeforeListToolsFunc ¶
type OnBeforeListToolsFunc func(ctx context.Context, id any, message *mcp.ListToolsRequest)
type OnBeforePingFunc ¶
type OnBeforePingFunc func(ctx context.Context, id any, message *mcp.PingRequest)
type OnBeforeReadResourceFunc ¶
type OnBeforeReadResourceFunc func(ctx context.Context, id any, message *mcp.ReadResourceRequest)
type OnBeforeSetLevelFunc ¶
type OnBeforeSetLevelFunc func(ctx context.Context, id any, message *mcp.SetLevelRequest)
type OnErrorHookFunc ¶
type OnErrorHookFunc func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error)
OnErrorHookFunc is a hook that will be called when an error occurs, either during the request parsing or the method execution.
Example usage: ```
hooks.AddOnError(func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) { // Check for specific error types using errors.Is if errors.Is(err, ErrUnsupported) { // Handle capability not supported errors log.Printf("Capability not supported: %v", err) } // Use errors.As to get specific error types var parseErr = &UnparsableMessageError{} if errors.As(err, &parseErr) { // Access specific methods/fields of the error type log.Printf("Failed to parse message for method %s: %v", parseErr.GetMethod(), parseErr.Unwrap()) // Access the raw message that failed to parse rawMsg := parseErr.GetMessage() } // Check for specific resource/prompt/tool errors switch { case errors.Is(err, ErrResourceNotFound): log.Printf("Resource not found: %v", err) case errors.Is(err, ErrPromptNotFound): log.Printf("Prompt not found: %v", err) case errors.Is(err, ErrToolNotFound): log.Printf("Tool not found: %v", err) } })
type OnRegisterSessionHookFunc ¶
type OnRegisterSessionHookFunc func(ctx context.Context, session ClientSession)
OnRegisterSessionHookFunc is a hook that will be called when a new session is registered.
type OnRequestInitializationFunc ¶
OnRequestInitializationFunc is a function that called before handle diff request method Should any errors arise during func execution, the service will promptly return the corresponding error message.
type OnSuccessHookFunc ¶
type OnSuccessHookFunc func(ctx context.Context, id any, method mcp.MCPMethod, message any, result any)
OnSuccessHookFunc is a hook that will be called after the request successfully generates a result, but before the result is sent to the client.
type OnUnregisterSessionHookFunc ¶
type OnUnregisterSessionHookFunc func(ctx context.Context, session ClientSession)
OnUnregisterSessionHookFunc is a hook that will be called when a session is being unregistered.
type PromptHandlerFunc ¶
type PromptHandlerFunc func(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error)
PromptHandlerFunc handles prompt requests with given arguments.
type ResourceHandlerFunc ¶
type ResourceHandlerFunc func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error)
ResourceHandlerFunc is a function that returns resource contents.
type ResourceTemplateHandlerFunc ¶
type ResourceTemplateHandlerFunc func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error)
ResourceTemplateHandlerFunc is a function that returns a resource template.
type SSEContextFunc ¶
SSEContextFunc is a function that takes an existing context and the current request and returns a potentially modified context based on the request content. This can be used to inject context values from headers, for example.
type SSEOption ¶
type SSEOption func(*SSEServer)
SSEOption defines a function type for configuring SSEServer
func WithAppendQueryToMessageEndpoint ¶
func WithAppendQueryToMessageEndpoint() SSEOption
WithAppendQueryToMessageEndpoint configures the SSE server to append the original request's query parameters to the message endpoint URL that is sent to clients during the SSE connection initialization. This is useful when you need to preserve query parameters from the initial SSE connection request and carry them over to subsequent message requests, maintaining context or authentication details across the communication channel.
func WithBasePath
deprecated
func WithBaseURL ¶
WithBaseURL sets the base URL for the SSE server
func WithDynamicBasePath ¶
func WithDynamicBasePath(fn DynamicBasePathFunc) SSEOption
WithDynamicBasePath accepts a function for generating the base path. This is useful for cases where the base path is not known at the time of SSE server creation, such as when using a reverse proxy or when the server is mounted at a dynamic path.
func WithHTTPServer ¶
WithHTTPServer sets the HTTP server instance
func WithKeepAlive ¶
func WithKeepAliveInterval ¶
func WithMessageEndpoint ¶
WithMessageEndpoint sets the message endpoint path
func WithSSEContextFunc ¶
func WithSSEContextFunc(fn SSEContextFunc) SSEOption
WithSSEContextFunc sets a function that will be called to customise the context to the server using the incoming request.
func WithSSEEndpoint ¶
WithSSEEndpoint sets the SSE endpoint path
func WithStaticBasePath ¶
WithStaticBasePath adds a new option for setting a static base path
func WithUseFullURLForMessageEndpoint ¶
WithUseFullURLForMessageEndpoint controls whether the SSE server returns a complete URL (including baseURL) or just the path portion for the message endpoint. Set to false when clients will concatenate the baseURL themselves to avoid malformed URLs like "http://localhost/mcphttp://localhost/mcp/message".
type SSEServer ¶
type SSEServer struct {
// contains filtered or unexported fields
}
SSEServer implements a Server-Sent Events (SSE) based MCP server. It provides real-time communication capabilities over HTTP using the SSE protocol.
func NewSSEServer ¶
NewSSEServer creates a new SSE server instance with the given MCP server and options.
func (*SSEServer) CompleteMessageEndpoint ¶
func (*SSEServer) CompleteMessagePath ¶
func (*SSEServer) CompleteSseEndpoint ¶
func (*SSEServer) CompleteSsePath ¶
func (*SSEServer) GetMessageEndpointForClient ¶
GetMessageEndpointForClient returns the appropriate message endpoint URL with session ID for the given request. This is the canonical way to compute the message endpoint for a client. It handles both dynamic and static path modes, and honors the WithUseFullURLForMessageEndpoint flag.
func (*SSEServer) MessageHandler ¶
MessageHandler returns an http.Handler for the message endpoint.
This method allows you to mount the message handler at any arbitrary path using your own router (e.g. net/http, gorilla/mux, chi, etc.). It is intended for advanced scenarios where you want to control the routing or support dynamic segments.
IMPORTANT: When using this handler in advanced/dynamic mounting scenarios, you must use the WithDynamicBasePath option to ensure the correct base path is communicated to clients.
Example usage:
// Advanced/dynamic: sseServer := NewSSEServer(mcpServer, WithDynamicBasePath(func(r *http.Request, sessionID string) string { tenant := r.PathValue("tenant") return "/mcp/" + tenant }), WithBaseURL("http://localhost:8080") ) mux.Handle("/mcp/{tenant}/sse", sseServer.SSEHandler()) mux.Handle("/mcp/{tenant}/message", sseServer.MessageHandler())
For non-dynamic cases, use ServeHTTP method instead.
func (*SSEServer) SSEHandler ¶
SSEHandler returns an http.Handler for the SSE endpoint.
This method allows you to mount the SSE handler at any arbitrary path using your own router (e.g. net/http, gorilla/mux, chi, etc.). It is intended for advanced scenarios where you want to control the routing or support dynamic segments.
IMPORTANT: When using this handler in advanced/dynamic mounting scenarios, you must use the WithDynamicBasePath option to ensure the correct base path is communicated to clients.
Example usage:
// Advanced/dynamic: sseServer := NewSSEServer(mcpServer, WithDynamicBasePath(func(r *http.Request, sessionID string) string { tenant := r.PathValue("tenant") return "/mcp/" + tenant }), WithBaseURL("http://localhost:8080") ) mux.Handle("/mcp/{tenant}/sse", sseServer.SSEHandler()) mux.Handle("/mcp/{tenant}/message", sseServer.MessageHandler())
For non-dynamic cases, use ServeHTTP method instead.
func (*SSEServer) SendEventToSession ¶
SendEventToSession sends an event to a specific SSE session identified by sessionID. Returns an error if the session is not found or closed.
func (*SSEServer) ServeHTTP ¶
func (s *SSEServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface.
type ServerOption ¶
type ServerOption func(*MCPServer)
ServerOption is a function that configures an MCPServer.
func WithCompletion ¶
func WithCompletion(handler CompletionHandlerFunc) ServerOption
WithCompletion enables completion capabilities for the server
func WithHooks ¶
func WithHooks(hooks *Hooks) ServerOption
WithHooks allows adding hooks that will be called before or after either [all] requests or before / after specific request methods, or else prior to returning an error to the client.
func WithInstructions ¶
func WithInstructions(instructions string) ServerOption
WithInstructions sets the server instructions for the client returned in the initialize response
func WithLogging ¶
func WithLogging() ServerOption
WithLogging enables logging capabilities for the server
func WithPaginationLimit ¶
func WithPaginationLimit(limit int) ServerOption
WithPaginationLimit sets the pagination limit for the server.
func WithPromptCapabilities ¶
func WithPromptCapabilities(listChanged bool) ServerOption
WithPromptCapabilities configures prompt-related server capabilities
func WithRecovery ¶
func WithRecovery() ServerOption
WithRecovery adds a middleware that recovers from panics in tool handlers.
func WithResourceCapabilities ¶
func WithResourceCapabilities(subscribe, listChanged bool) ServerOption
WithResourceCapabilities configures resource-related server capabilities
func WithToolCapabilities ¶
func WithToolCapabilities(listChanged bool) ServerOption
WithToolCapabilities configures tool-related server capabilities
func WithToolFilter ¶
func WithToolFilter( toolFilter ToolFilterFunc, ) ServerOption
WithToolFilter adds a filter function that will be applied to tools before they are returned in list_tools
func WithToolHandlerMiddleware ¶
func WithToolHandlerMiddleware( toolHandlerMiddleware ToolHandlerMiddleware, ) ServerOption
WithToolHandlerMiddleware allows adding a middleware for the tool handler call chain.
type ServerTool ¶
type ServerTool struct { Tool mcp.Tool Handler ToolHandlerFunc }
ServerTool combines a Tool with its ToolHandlerFunc.
type SessionIdManager ¶
type SessionIdManager interface { Generate() string // Validate checks if a session ID is valid and not terminated. // Returns isTerminated=true if the ID is valid but belongs to a terminated session. // Returns err!=nil if the ID format is invalid or lookup failed. Validate(sessionID string) (isTerminated bool, err error) // Terminate marks a session ID as terminated. // Returns isNotAllowed=true if the server policy prevents client termination. // Returns err!=nil if the ID is invalid or termination failed. Terminate(sessionID string) (isNotAllowed bool, err error) }
type SessionWithClientInfo ¶
type SessionWithClientInfo interface { ClientSession // GetClientInfo returns the client information for this session GetClientInfo() mcp.Implementation // SetClientInfo sets the client information for this session SetClientInfo(clientInfo mcp.Implementation) }
SessionWithClientInfo is an extension of ClientSession that can store client info
type SessionWithLogging ¶
type SessionWithLogging interface { ClientSession // SetLogLevel sets the minimum log level SetLogLevel(level mcp.LoggingLevel) // GetLogLevel retrieves the minimum log level GetLogLevel() mcp.LoggingLevel }
SessionWithLogging is an extension of ClientSession that can receive log message notifications and set log level
type SessionWithTools ¶
type SessionWithTools interface { ClientSession // GetSessionTools returns the tools specific to this session, if any // This method must be thread-safe for concurrent access GetSessionTools() map[string]ServerTool // SetSessionTools sets tools specific to this session // This method must be thread-safe for concurrent access SetSessionTools(tools map[string]ServerTool) }
SessionWithTools is an extension of ClientSession that can store session-specific tool data
type StatelessSessionIdManager ¶
type StatelessSessionIdManager struct{}
StatelessSessionIdManager does nothing, which means it has no session management, which is stateless.
func (*StatelessSessionIdManager) Generate ¶
func (s *StatelessSessionIdManager) Generate() string
type StdioContextFunc ¶
StdioContextFunc is a function that takes an existing context and returns a potentially modified context. This can be used to inject context values from environment variables, for example.
type StdioOption ¶
type StdioOption func(*StdioServer)
StdioOption defines a function type for configuring StdioServer
func WithErrorLogger ¶
func WithErrorLogger(logger *log.Logger) StdioOption
WithErrorLogger sets the error logger for the server
func WithStdioContextFunc ¶
func WithStdioContextFunc(fn StdioContextFunc) StdioOption
WithStdioContextFunc sets a function that will be called to customise the context to the server. Note that the stdio server uses the same context for all requests, so this function will only be called once per server instance.
type StdioServer ¶
type StdioServer struct {
// contains filtered or unexported fields
}
StdioServer wraps a MCPServer and handles stdio communication. It provides a simple way to create command-line MCP servers that communicate via standard input/output streams using JSON-RPC messages.
func NewStdioServer ¶
func NewStdioServer(server *MCPServer) *StdioServer
NewStdioServer creates a new stdio server wrapper around an MCPServer. It initializes the server with a default error logger that discards all output.
func (*StdioServer) Listen ¶
Listen starts listening for JSON-RPC messages on the provided input and writes responses to the provided output. It runs until the context is cancelled or an error occurs. Returns an error if there are issues with reading input or writing output.
func (*StdioServer) SetContextFunc ¶
func (s *StdioServer) SetContextFunc(fn StdioContextFunc)
SetContextFunc sets a function that will be called to customise the context to the server. Note that the stdio server uses the same context for all requests, so this function will only be called once per server instance.
func (*StdioServer) SetErrorLogger ¶
func (s *StdioServer) SetErrorLogger(logger *log.Logger)
SetErrorLogger configures where error messages from the StdioServer are logged. The provided logger will receive all error messages generated during server operation.
type StreamableHTTPOption ¶
type StreamableHTTPOption func(*StreamableHTTPServer)
StreamableHTTPOption defines a function type for configuring StreamableHTTPServer
func WithEndpointPath ¶
func WithEndpointPath(endpointPath string) StreamableHTTPOption
WithEndpointPath sets the endpoint path for the server. The default is "/mcp". It's only works for `Start` method. When used as a http.Handler, it has no effect.
func WithHTTPContextFunc ¶
func WithHTTPContextFunc(fn HTTPContextFunc) StreamableHTTPOption
WithHTTPContextFunc sets a function that will be called to customise the context to the server using the incoming request. This can be used to inject context values from headers, for example.
func WithHeartbeatInterval ¶
func WithHeartbeatInterval(interval time.Duration) StreamableHTTPOption
WithHeartbeatInterval sets the heartbeat interval. Positive interval means the server will send a heartbeat to the client through the GET connection, to keep the connection alive from being closed by the network infrastructure (e.g. gateways). If the client does not establish a GET connection, it has no effect. The default is not to send heartbeats.
func WithLogger ¶
func WithLogger(logger util.Logger) StreamableHTTPOption
WithLogger sets the logger for the server
func WithSessionIdManager ¶
func WithSessionIdManager(manager SessionIdManager) StreamableHTTPOption
WithSessionIdManager sets a custom session id generator for the server. By default, the server will use SimpleStatefulSessionIdGenerator, which generates session ids with uuid, and it's insecure. Notice: it will override the WithStateLess option.
func WithStateLess ¶
func WithStateLess(stateLess bool) StreamableHTTPOption
WithStateLess sets the server to stateless mode. If true, the server will manage no session information. Every request will be treated as a new session. No session id returned to the client. The default is false.
Notice: This is a convenience method. It's identical to set WithSessionIdManager option to StatelessSessionIdManager.
type StreamableHTTPServer ¶
type StreamableHTTPServer struct {
// contains filtered or unexported fields
}
StreamableHTTPServer implements a Streamable-http based MCP server. It communicates with clients over HTTP protocol, supporting both direct HTTP responses, and SSE streams. https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http
Usage:
server := NewStreamableHTTPServer(mcpServer) server.Start(":8080") // The final url for client is http://xxxx:8080/mcp by default
or the server itself can be used as a http.Handler, which is convenient to integrate with existing http servers, or advanced usage:
handler := NewStreamableHTTPServer(mcpServer) http.Handle("/streamable-http", handler) http.ListenAndServe(":8080", nil)
Notice: Except for the GET handlers(listening), the POST handlers(request/notification) will not trigger the session registration. So the methods like `SendNotificationToSpecificClient` or `hooks.onRegisterSession` will not be triggered for POST messages.
The current implementation does not support the following features from the specification:
- Batching of requests/notifications/responses in arrays.
- Stream Resumability
func NewStreamableHTTPServer ¶
func NewStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *StreamableHTTPServer
NewStreamableHTTPServer creates a new streamable-http server instance
func (*StreamableHTTPServer) ServeHTTP ¶
func (s *StreamableHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface.
func (*StreamableHTTPServer) Shutdown ¶
func (s *StreamableHTTPServer) Shutdown(ctx context.Context) error
Shutdown gracefully stops the server, closing all active sessions and shutting down the HTTP server.
func (*StreamableHTTPServer) Start ¶
func (s *StreamableHTTPServer) Start(addr string) error
Start begins serving the http server on the specified address and path (endpointPath). like:
s.Start(":8080")
type ToolFilterFunc ¶
ToolFilterFunc is a function that filters tools based on context, typically using session information.
type ToolHandlerFunc ¶
type ToolHandlerFunc func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)
ToolHandlerFunc handles tool calls with given arguments.
type ToolHandlerMiddleware ¶
type ToolHandlerMiddleware func(ToolHandlerFunc) ToolHandlerFunc
ToolHandlerMiddleware is a middleware function that wraps a ToolHandlerFunc.
type UnparsableMessageError ¶
type UnparsableMessageError struct {
// contains filtered or unexported fields
}
UnparsableMessageError is attached to the RequestError when json.Unmarshal fails on the request.
func (*UnparsableMessageError) Error ¶
func (e *UnparsableMessageError) Error() string
func (*UnparsableMessageError) GetMessage ¶
func (e *UnparsableMessageError) GetMessage() json.RawMessage
func (*UnparsableMessageError) GetMethod ¶
func (e *UnparsableMessageError) GetMethod() mcp.MCPMethod
func (*UnparsableMessageError) Unwrap ¶
func (e *UnparsableMessageError) Unwrap() error