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 ServeStdio(server *MCPServer, opts ...StdioOption) error
- type BeforeAnyHookFunc
- type ClientSession
- type GRPCContextFunc
- type GRPCOption
- type GRPCServer
- func (s *GRPCServer) SendMessage(ctx context.Context, msg *mcpgrpc.MCPMessage) (*mcpgrpc.MCPMessage, error)
- func (s *GRPCServer) Shutdown(ctx context.Context) error
- func (s *GRPCServer) Start(addr string) error
- func (s *GRPCServer) StreamMessages(stream mcpgrpc.MCPService_StreamMessagesServer) error
- type Hooks
- func (c *Hooks) AddAfterCallTool(hook OnAfterCallToolFunc)
- 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) AddBeforeAny(hook BeforeAnyHookFunc)
- func (c *Hooks) AddBeforeCallTool(hook OnBeforeCallToolFunc)
- 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) 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 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) AddTool(tool mcp.Tool, handler ToolHandlerFunc)
- func (s *MCPServer) AddTools(tools ...ServerTool)
- 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) 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 OnAfterGetPromptFunc
- type OnAfterInitializeFunc
- type OnAfterListPromptsFunc
- type OnAfterListResourceTemplatesFunc
- type OnAfterListResourcesFunc
- type OnAfterListToolsFunc
- type OnAfterPingFunc
- type OnAfterReadResourceFunc
- type OnBeforeCallToolFunc
- type OnBeforeGetPromptFunc
- type OnBeforeInitializeFunc
- type OnBeforeListPromptsFunc
- type OnBeforeListResourceTemplatesFunc
- type OnBeforeListResourcesFunc
- type OnBeforeListToolsFunc
- type OnBeforePingFunc
- type OnBeforeReadResourceFunc
- type OnErrorHookFunc
- type OnRegisterSessionHookFunc
- type OnRequestInitializationFunc
- type OnSuccessHookFunc
- type OnUnregisterSessionHookFunc
- type PromptHandlerFunc
- type ResourceHandlerFunc
- type ResourceTemplateHandlerFunc
- type SSEContextFunc
- type SSEOption
- func WithBasePath(basePath string) SSEOption
- func WithBaseURL(baseURL string) 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 WithUseFullURLForMessageEndpoint(useFullURLForMessageEndpoint bool) SSEOption
- type SSEServer
- func (s *SSEServer) CompleteMessageEndpoint() string
- func (s *SSEServer) CompleteMessagePath() string
- func (s *SSEServer) CompleteSseEndpoint() string
- func (s *SSEServer) CompleteSsePath() string
- func (s *SSEServer) GetMessageEndpointForClient(sessionID string) string
- func (s *SSEServer) GetUrlPath(input string) (string, error)
- func (s *SSEServer) SendEventToSession(sessionID string, event interface{}) 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 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 WithToolHandlerMiddleware(toolHandlerMiddleware ToolHandlerMiddleware) ServerOption
- type ServerTool
- type StdioContextFunc
- type StdioOption
- type StdioServer
- type ToolHandlerFunc
- type ToolHandlerMiddleware
- type UnparsableMessageError
Constants ¶
This section is empty.
Variables ¶
Functions ¶
func NewTestServer ¶
NewTestServer 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 GRPCContextFunc ¶
GRPCContextFunc is a function that takes an existing context and gRPC metadata and returns a potentially modified context.
type GRPCOption ¶
type GRPCOption func(*GRPCServer)
GRPCOption defines a function type for configuring GRPCServer
func WithGRPCContextFunc ¶
func WithGRPCContextFunc(fn GRPCContextFunc) GRPCOption
WithGRPCContextFunc sets a function that will be called to customize the context from gRPC metadata.
func WithGRPCServer ¶
func WithGRPCServer(srv *grpc.Server) GRPCOption
WithGRPCServer sets a custom gRPC server instance
type GRPCServer ¶
type GRPCServer struct { mcpgrpc.UnimplementedMCPServiceServer // contains filtered or unexported fields }
GRPCServer implements a gRPC based MCP server.
func NewGRPCServer ¶
func NewGRPCServer(server *MCPServer, opts ...GRPCOption) *GRPCServer
NewGRPCServer creates a new gRPC server instance with the given MCP server and options.
func (*GRPCServer) SendMessage ¶
func (s *GRPCServer) SendMessage(ctx context.Context, msg *mcpgrpc.MCPMessage) (*mcpgrpc.MCPMessage, error)
SendMessage implements the SendMessage gRPC method. It handles a single request-response interaction.
func (*GRPCServer) Shutdown ¶
func (s *GRPCServer) Shutdown(ctx context.Context) error
Shutdown gracefully stops the gRPC server, closing all active sessions.
func (*GRPCServer) Start ¶
func (s *GRPCServer) Start(addr string) error
Start begins serving gRPC connections on the specified address.
func (*GRPCServer) StreamMessages ¶
func (s *GRPCServer) StreamMessages(stream mcpgrpc.MCPService_StreamMessagesServer) error
StreamMessages implements the StreamMessages gRPC method. It establishes a bidirectional stream for JSON-RPC messages between client and server.
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 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 }
func (*Hooks) AddAfterCallTool ¶
func (c *Hooks) AddAfterCallTool(hook OnAfterCallToolFunc)
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) AddBeforeAny ¶
func (c *Hooks) AddBeforeAny(hook BeforeAnyHookFunc)
func (*Hooks) AddBeforeCallTool ¶
func (c *Hooks) AddBeforeCallTool(hook OnBeforeCallToolFunc)
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) 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 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) 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) DeleteTools ¶
DeleteTools removes a tool 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) 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 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 OnBeforeCallToolFunc ¶
type OnBeforeCallToolFunc func(ctx context.Context, id any, message *mcp.CallToolRequest)
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 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 WithBasePath ¶
Add a new option for setting base path
func WithBaseURL ¶
WithBaseURL sets the base URL for the SSE server
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
WithContextFunc 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 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 based on the useFullURLForMessageEndpoint configuration.
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 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 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 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
WithContextFunc 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 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