package server
Import Path
github.com/mark3labs/mcp-go/server (on go.dev)
Dependency Relation
imports 29 packages, and imported by one package
Involved Source Files
completion.go
constants.go
ctx.go
elicitation.go
errors.go
Code generated by `go generate`. DO NOT EDIT.
source: server/internal/gen/hooks.go.tmpl
http_transport_options.go
inprocess_session.go
Code generated by `go generate`. DO NOT EDIT.
source: server/internal/gen/request_handler.go.tmpl
roots.go
sampling.go
Package server provides MCP (Model Context Protocol) server implementations.
session.go
sse.go
stdio.go
streamable_http.go
task_hooks.go
Package-Level Type Names (total 99)
BeforeAnyHookFunc is a function that is called after the request is
parsed but before the method is called.
func (*Hooks).AddBeforeAny(hook BeforeAnyHookFunc)
ClientSession represents an active session that can be used by MCPServer to interact with client.
Initialize marks session as fully initialized and ready for notifications
Initialized returns if session is ready to accept notifications
NotificationChannel provides a channel suitable for sending notifications to client.
SessionID is a unique identifier used to track user session.
*InProcessSession
SessionWithClientInfo (interface)
SessionWithElicitation (interface)
SessionWithLogging (interface)
SessionWithResources (interface)
SessionWithResourceTemplates (interface)
SessionWithRoots (interface)
SessionWithSampling (interface)
SessionWithStreamableHTTPConfig (interface)
SessionWithTools (interface)
func ClientSessionFromContext(ctx context.Context) ClientSession
func (*Hooks).RegisterSession(ctx context.Context, session ClientSession)
func (*Hooks).UnregisterSession(ctx context.Context, session ClientSession)
func (*MCPServer).RegisterSession(ctx context.Context, session ClientSession) error
func (*MCPServer).RequestURLElicitation(ctx context.Context, session ClientSession, elicitationID string, url string, message string) (*mcp.ElicitationResult, error)
func (*MCPServer).SendElicitationComplete(ctx context.Context, session ClientSession, elicitationID string) error
func (*MCPServer).WithContext(ctx context.Context, session ClientSession) context.Context
DefaultCompletionProvider returns no completions (fallback)
(*DefaultPromptCompletionProvider) CompletePromptArgument(ctx context.Context, promptName string, argument mcp.CompleteArgument, context mcp.CompleteContext) (*mcp.Completion, error)
*DefaultPromptCompletionProvider : PromptCompletionProvider
DefaultResourceCompletionProvider returns no completions (fallback)
(*DefaultResourceCompletionProvider) CompleteResourceArgument(ctx context.Context, uri string, argument mcp.CompleteArgument, context mcp.CompleteContext) (*mcp.Completion, error)
*DefaultResourceCompletionProvider : ResourceCompletionProvider
DefaultSessionIdManagerResolver is a simple resolver that returns the same SessionIdManager for all requests
ResolveSessionIdManager returns the configured SessionIdManager for all requests
*DefaultSessionIdManagerResolver : SessionIdManagerResolver
func NewDefaultSessionIdManagerResolver(manager SessionIdManager) *DefaultSessionIdManagerResolver
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").
func WithDynamicBasePath(fn DynamicBasePathFunc) SSEOption
ElicitationHandler defines the interface for handling elicitation requests from servers.
( ElicitationHandler) Elicit(ctx context.Context, request mcp.ElicitationRequest) (*mcp.ElicitationResult, error)
func NewInProcessSessionWithHandlers(sessionID string, samplingHandler SamplingHandler, elicitationHandler ElicitationHandler, rootsHandler RootsHandler) *InProcessSession
ErrDynamicPathConfig is returned when attempting to use static path methods with dynamic path configuration
Method string
(*ErrDynamicPathConfig) Error() string
*ErrDynamicPathConfig : error
OnAfterCallTool []OnAfterCallToolFunc
OnAfterCancelTask []OnAfterCancelTaskFunc
OnAfterComplete []OnAfterCompleteFunc
OnAfterGetPrompt []OnAfterGetPromptFunc
OnAfterGetTask []OnAfterGetTaskFunc
OnAfterInitialize []OnAfterInitializeFunc
OnAfterListPrompts []OnAfterListPromptsFunc
OnAfterListResourceTemplates []OnAfterListResourceTemplatesFunc
OnAfterListResources []OnAfterListResourcesFunc
OnAfterListTasks []OnAfterListTasksFunc
OnAfterListTools []OnAfterListToolsFunc
OnAfterPing []OnAfterPingFunc
OnAfterReadResource []OnAfterReadResourceFunc
OnAfterSetLevel []OnAfterSetLevelFunc
OnAfterTaskResult []OnAfterTaskResultFunc
OnBeforeAny []BeforeAnyHookFunc
OnBeforeCallTool []OnBeforeCallToolFunc
OnBeforeCancelTask []OnBeforeCancelTaskFunc
OnBeforeComplete []OnBeforeCompleteFunc
OnBeforeGetPrompt []OnBeforeGetPromptFunc
OnBeforeGetTask []OnBeforeGetTaskFunc
OnBeforeInitialize []OnBeforeInitializeFunc
OnBeforeListPrompts []OnBeforeListPromptsFunc
OnBeforeListResourceTemplates []OnBeforeListResourceTemplatesFunc
OnBeforeListResources []OnBeforeListResourcesFunc
OnBeforeListTasks []OnBeforeListTasksFunc
OnBeforeListTools []OnBeforeListToolsFunc
OnBeforePing []OnBeforePingFunc
OnBeforeReadResource []OnBeforeReadResourceFunc
OnBeforeSetLevel []OnBeforeSetLevelFunc
OnBeforeTaskResult []OnBeforeTaskResultFunc
OnError []OnErrorHookFunc
OnRegisterSession []OnRegisterSessionHookFunc
OnRequestInitialization []OnRequestInitializationFunc
OnSuccess []OnSuccessHookFunc
OnUnregisterSession []OnUnregisterSessionHookFunc
(*Hooks) AddAfterCallTool(hook OnAfterCallToolFunc)
(*Hooks) AddAfterCancelTask(hook OnAfterCancelTaskFunc)
(*Hooks) AddAfterComplete(hook OnAfterCompleteFunc)
(*Hooks) AddAfterGetPrompt(hook OnAfterGetPromptFunc)
(*Hooks) AddAfterGetTask(hook OnAfterGetTaskFunc)
(*Hooks) AddAfterInitialize(hook OnAfterInitializeFunc)
(*Hooks) AddAfterListPrompts(hook OnAfterListPromptsFunc)
(*Hooks) AddAfterListResourceTemplates(hook OnAfterListResourceTemplatesFunc)
(*Hooks) AddAfterListResources(hook OnAfterListResourcesFunc)
(*Hooks) AddAfterListTasks(hook OnAfterListTasksFunc)
(*Hooks) AddAfterListTools(hook OnAfterListToolsFunc)
(*Hooks) AddAfterPing(hook OnAfterPingFunc)
(*Hooks) AddAfterReadResource(hook OnAfterReadResourceFunc)
(*Hooks) AddAfterSetLevel(hook OnAfterSetLevelFunc)
(*Hooks) AddAfterTaskResult(hook OnAfterTaskResultFunc)
(*Hooks) AddBeforeAny(hook BeforeAnyHookFunc)
(*Hooks) AddBeforeCallTool(hook OnBeforeCallToolFunc)
(*Hooks) AddBeforeCancelTask(hook OnBeforeCancelTaskFunc)
(*Hooks) AddBeforeComplete(hook OnBeforeCompleteFunc)
(*Hooks) AddBeforeGetPrompt(hook OnBeforeGetPromptFunc)
(*Hooks) AddBeforeGetTask(hook OnBeforeGetTaskFunc)
(*Hooks) AddBeforeInitialize(hook OnBeforeInitializeFunc)
(*Hooks) AddBeforeListPrompts(hook OnBeforeListPromptsFunc)
(*Hooks) AddBeforeListResourceTemplates(hook OnBeforeListResourceTemplatesFunc)
(*Hooks) AddBeforeListResources(hook OnBeforeListResourcesFunc)
(*Hooks) AddBeforeListTasks(hook OnBeforeListTasksFunc)
(*Hooks) AddBeforeListTools(hook OnBeforeListToolsFunc)
(*Hooks) AddBeforePing(hook OnBeforePingFunc)
(*Hooks) AddBeforeReadResource(hook OnBeforeReadResourceFunc)
(*Hooks) AddBeforeSetLevel(hook OnBeforeSetLevelFunc)
(*Hooks) AddBeforeTaskResult(hook OnBeforeTaskResultFunc)
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))
```
(*Hooks) AddOnRegisterSession(hook OnRegisterSessionHookFunc)
(*Hooks) AddOnRequestInitialization(hook OnRequestInitializationFunc)
(*Hooks) AddOnSuccess(hook OnSuccessHookFunc)
(*Hooks) AddOnUnregisterSession(hook OnUnregisterSessionHookFunc)
(*Hooks) RegisterSession(ctx context.Context, session ClientSession)
(*Hooks) UnregisterSession(ctx context.Context, session ClientSession)
func (*MCPServer).GetHooks() *Hooks
func WithHooks(hooks *Hooks) ServerOption
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.
func WithHTTPContextFunc(fn HTTPContextFunc) StreamableHTTPOption
(*InProcessSession) GetClientCapabilities() mcp.ClientCapabilities
(*InProcessSession) GetClientInfo() mcp.Implementation
(*InProcessSession) GetLogLevel() mcp.LoggingLevel
(*InProcessSession) Initialize()
(*InProcessSession) Initialized() bool
ListRoots sends a list roots request to the client and waits for the response.
Returns an error if no roots handler is available.
(*InProcessSession) NotificationChannel() chan<- mcp.JSONRPCNotification
(*InProcessSession) RequestElicitation(ctx context.Context, request mcp.ElicitationRequest) (*mcp.ElicitationResult, error)
(*InProcessSession) RequestSampling(ctx context.Context, request mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error)
(*InProcessSession) SessionID() string
(*InProcessSession) SetClientCapabilities(clientCapabilities mcp.ClientCapabilities)
(*InProcessSession) SetClientInfo(clientInfo mcp.Implementation)
(*InProcessSession) SetLogLevel(level mcp.LoggingLevel)
*InProcessSession : ClientSession
*InProcessSession : RootsHandler
*InProcessSession : SessionWithClientInfo
*InProcessSession : SessionWithElicitation
*InProcessSession : SessionWithLogging
*InProcessSession : SessionWithRoots
*InProcessSession : SessionWithSampling
func NewInProcessSession(sessionID string, samplingHandler SamplingHandler) *InProcessSession
func NewInProcessSessionWithHandlers(sessionID string, samplingHandler SamplingHandler, elicitationHandler ElicitationHandler, rootsHandler RootsHandler) *InProcessSession
InsecureStatefulSessionIdManager generate id with uuid and tracks active sessions.
It validates both format and existence of session IDs.
For more secure session id, use a more complex generator, like a JWT.
(*InsecureStatefulSessionIdManager) Generate() string
(*InsecureStatefulSessionIdManager) Terminate(sessionID string) (isNotAllowed bool, err error)
(*InsecureStatefulSessionIdManager) Validate(sessionID string) (isTerminated bool, err error)
*InsecureStatefulSessionIdManager : SessionIdManager
MCPServer implements a Model Context Protocol server that can handle various types of requests
including resources, prompts, and tools.
AddNotificationHandler registers a new handler for incoming notifications
AddPrompt registers a new prompt handler with the given name
AddPrompts registers multiple prompts at once
AddResource registers a new resource and its handler
AddResourceTemplate registers a new resource template and its handler
AddResourceTemplates registers multiple resource templates at once
AddResources registers multiple resources at once
AddSessionResource adds a resource for a specific session
AddSessionResourceTemplate adds a resource template for a specific session
AddSessionResourceTemplates adds resource templates for a specific session
AddSessionResources adds resources for a specific session
AddSessionTool adds a tool for a specific session
AddSessionTools adds tools for a specific session
AddTaskTool registers a new task tool and its handler
AddTaskTools registers multiple task tools at once
AddTool registers a new tool and its handler
AddTools registers multiple tools at once
DeletePrompts removes prompts from the server
DeleteResources removes resources from the server
DeleteSessionResourceTemplates removes resource templates from a specific session
DeleteSessionResources removes resources from a specific session
DeleteSessionTools removes tools from a specific session
DeleteTools removes tools from the server
EnableSampling enables sampling capabilities for the server.
This allows the server to send sampling requests to clients that support it.
GenerateInProcessSessionID generates a unique session ID for inprocess clients
GetHooks returns the server's current Hooks instance, or nil if no hooks
have been configured. The returned pointer can be used to add additional
hooks via the Add* methods without replacing existing hook registrations.
GetTool retrieves the specified tool
HandleMessage processes an incoming JSON-RPC message and returns an appropriate response
(*MCPServer) ListTools() map[string]*ServerTool
RegisterSession saves session that should be notified in case if some server attributes changed.
RemoveResource removes a resource from the server
RequestElicitation sends an elicitation request to the client.
The client must have declared elicitation capability during initialization.
The session must implement SessionWithElicitation to support this operation.
RequestRoots sends an list roots request to the client.
The client must have declared roots capability during initialization.
The session must implement SessionWithRoots to support this operation.
RequestSampling sends a sampling request to the client.
The client must have declared sampling capability during initialization.
RequestURLElicitation sends a URL mode elicitation request to the client.
This is used when the server needs the user to perform an out-of-band interaction.
SendElicitationComplete sends a notification that a URL mode elicitation has completed
SendElicitationComplete sends a notification that a URL mode elicitation has completed
(*MCPServer) SendLogMessageToClient(ctx context.Context, notification mcp.LoggingMessageNotification) error
(*MCPServer) SendLogMessageToSpecificClient(sessionID string, notification mcp.LoggingMessageNotification) error
SendNotificationToAllClients sends a notification to all the currently active clients.
SendNotificationToClient sends a notification to the current client
SendNotificationToSpecificClient sends a notification to a specific client by session ID
SetPrompts replaces all existing prompts with the provided list
SetResourceTemplates replaces all existing resource templates with the provided list
SetResources replaces all existing resources with the provided list
SetTools replaces all existing tools with the provided list
UnregisterSession removes from storage session that is shut down.
Use adds one or more tool handler middlewares to the server.
Middleware is applied in the order added (outermost first), matching net/http convention.
WithContext sets the current client session and returns the provided context
func NewMCPServer(name, version string, opts ...ServerOption) *MCPServer
func ServerFromContext(ctx context.Context) *MCPServer
func NewSSEServer(server *MCPServer, opts ...SSEOption) *SSEServer
func NewStdioServer(server *MCPServer) *StdioServer
func NewStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *StreamableHTTPServer
func NewTestServer(server *MCPServer, opts ...SSEOption) *httptest.Server
func NewTestStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *httptest.Server
func ServeStdio(server *MCPServer, opts ...StdioOption) error
NotificationHandlerFunc handles incoming notifications.
func (*MCPServer).AddNotificationHandler(method string, handler NotificationHandlerFunc)
func (*Hooks).AddAfterCallTool(hook OnAfterCallToolFunc)
func (*Hooks).AddAfterCancelTask(hook OnAfterCancelTaskFunc)
func (*Hooks).AddAfterComplete(hook OnAfterCompleteFunc)
func (*Hooks).AddAfterGetPrompt(hook OnAfterGetPromptFunc)
func (*Hooks).AddAfterGetTask(hook OnAfterGetTaskFunc)
func (*Hooks).AddAfterInitialize(hook OnAfterInitializeFunc)
func (*Hooks).AddAfterListPrompts(hook OnAfterListPromptsFunc)
func (*Hooks).AddAfterListResources(hook OnAfterListResourcesFunc)
func (*Hooks).AddAfterListResourceTemplates(hook OnAfterListResourceTemplatesFunc)
func (*Hooks).AddAfterListTasks(hook OnAfterListTasksFunc)
func (*Hooks).AddAfterListTools(hook OnAfterListToolsFunc)
func (*Hooks).AddAfterPing(hook OnAfterPingFunc)
func (*Hooks).AddAfterReadResource(hook OnAfterReadResourceFunc)
func (*Hooks).AddAfterSetLevel(hook OnAfterSetLevelFunc)
func (*Hooks).AddAfterTaskResult(hook OnAfterTaskResultFunc)
func (*Hooks).AddBeforeCallTool(hook OnBeforeCallToolFunc)
func (*Hooks).AddBeforeCancelTask(hook OnBeforeCancelTaskFunc)
func (*Hooks).AddBeforeComplete(hook OnBeforeCompleteFunc)
func (*Hooks).AddBeforeGetPrompt(hook OnBeforeGetPromptFunc)
func (*Hooks).AddBeforeGetTask(hook OnBeforeGetTaskFunc)
func (*Hooks).AddBeforeInitialize(hook OnBeforeInitializeFunc)
func (*Hooks).AddBeforeListPrompts(hook OnBeforeListPromptsFunc)
func (*Hooks).AddBeforeListResources(hook OnBeforeListResourcesFunc)
func (*Hooks).AddBeforeListResourceTemplates(hook OnBeforeListResourceTemplatesFunc)
func (*Hooks).AddBeforeListTasks(hook OnBeforeListTasksFunc)
func (*Hooks).AddBeforeListTools(hook OnBeforeListToolsFunc)
func (*Hooks).AddBeforePing(hook OnBeforePingFunc)
func (*Hooks).AddBeforeReadResource(hook OnBeforeReadResourceFunc)
func (*Hooks).AddBeforeSetLevel(hook OnBeforeSetLevelFunc)
func (*Hooks).AddBeforeTaskResult(hook OnBeforeTaskResultFunc)
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)
}
})
func (*Hooks).AddOnError(hook OnErrorHookFunc)
OnRegisterSessionHookFunc is a hook that will be called when a new session is registered.
func (*Hooks).AddOnRegisterSession(hook OnRegisterSessionHookFunc)
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.
func (*Hooks).AddOnRequestInitialization(hook OnRequestInitializationFunc)
OnSuccessHookFunc is a hook that will be called after the request
successfully generates a result, but before the result is sent to the client.
func (*Hooks).AddOnSuccess(hook OnSuccessHookFunc)
OnTaskCancelledHookFunc is called when a task is cancelled.
Use this to track cancellation metrics or clean up resources.
func (*TaskHooks).AddOnTaskCancelled(hook OnTaskCancelledHookFunc)
OnTaskCompletedHookFunc is called when a task completes successfully.
Use this to track completion metrics, record duration, or trigger follow-up actions.
func (*TaskHooks).AddOnTaskCompleted(hook OnTaskCompletedHookFunc)
OnTaskCreatedHookFunc is called when a new task is created.
Use this to track task creation metrics, initialize monitoring, or log task starts.
func (*TaskHooks).AddOnTaskCreated(hook OnTaskCreatedHookFunc)
OnTaskFailedHookFunc is called when a task fails with an error.
Use this to track failure metrics, alert on errors, or log failure details.
func (*TaskHooks).AddOnTaskFailed(hook OnTaskFailedHookFunc)
OnTaskStatusChangedHookFunc is called whenever a task's status changes.
This is a catch-all hook that fires for all status transitions.
Use this for general monitoring or when you need to track all state changes.
func (*TaskHooks).AddOnTaskStatusChanged(hook OnTaskStatusChangedHookFunc)
OnUnregisterSessionHookFunc is a hook that will be called when a session is being unregistered.
func (*Hooks).AddOnUnregisterSession(hook OnUnregisterSessionHookFunc)
CompletePromptArgument provides completions for a prompt argument
*DefaultPromptCompletionProvider
func WithPromptCompletionProvider(provider PromptCompletionProvider) ServerOption
PromptFilterFunc is a function that filters prompts based on context, typically using session information.
func WithPromptFilter(promptFilter PromptFilterFunc) ServerOption
PromptHandlerFunc handles prompt requests with given arguments.
func (*MCPServer).AddPrompt(prompt mcp.Prompt, handler PromptHandlerFunc)
PromptHandlerMiddleware is a middleware function that wraps a PromptHandlerFunc.
func WithPromptHandlerMiddleware(promptHandlerMiddleware PromptHandlerMiddleware) ServerOption
CompleteResourceArgument provides completions for a resource template argument
*DefaultResourceCompletionProvider
func WithResourceCompletionProvider(provider ResourceCompletionProvider) ServerOption
ResourceHandlerFunc is a function that returns resource contents.
func (*MCPServer).AddResource(resource mcp.Resource, handler ResourceHandlerFunc)
func (*MCPServer).AddSessionResource(sessionID string, resource mcp.Resource, handler ResourceHandlerFunc) error
ResourceHandlerMiddleware is a middleware function that wraps a ResourceHandlerFunc.
func WithResourceHandlerMiddleware(resourceHandlerMiddleware ResourceHandlerMiddleware) ServerOption
ResourceTemplateHandlerFunc is a function that returns a resource template.
func (*MCPServer).AddResourceTemplate(template mcp.ResourceTemplate, handler ResourceTemplateHandlerFunc)
func (*MCPServer).AddSessionResourceTemplate(sessionID string, template mcp.ResourceTemplate, handler ResourceTemplateHandlerFunc) error
RootsHandler defines the interface for handling roots list requests from servers.
( RootsHandler) ListRoots(ctx context.Context, request mcp.ListRootsRequest) (*mcp.ListRootsResult, error)
*InProcessSession
SessionWithRoots (interface)
func NewInProcessSessionWithHandlers(sessionID string, samplingHandler SamplingHandler, elicitationHandler ElicitationHandler, rootsHandler RootsHandler) *InProcessSession
SamplingHandler defines the interface for handling sampling requests from servers.
( SamplingHandler) CreateMessage(ctx context.Context, request mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error)
func InProcessSamplingHandlerFromContext(ctx context.Context) SamplingHandler
func NewInProcessSession(sessionID string, samplingHandler SamplingHandler) *InProcessSession
func NewInProcessSessionWithHandlers(sessionID string, samplingHandler SamplingHandler, elicitationHandler ElicitationHandler, rootsHandler RootsHandler) *InProcessSession
func WithInProcessSamplingHandler(ctx context.Context, handler SamplingHandler) context.Context
ServerOption is a function that configures an MCPServer.
func WithCompletions() ServerOption
func WithDescription(description string) ServerOption
func WithElicitation() ServerOption
func WithExperimental(experimental map[string]any) ServerOption
func WithHooks(hooks *Hooks) ServerOption
func WithIcons(icons ...mcp.Icon) ServerOption
func WithInstructions(instructions string) ServerOption
func WithLogging() ServerOption
func WithMaxConcurrentTasks(limit int) ServerOption
func WithPaginationLimit(limit int) ServerOption
func WithPromptCapabilities(listChanged bool) ServerOption
func WithPromptCompletionProvider(provider PromptCompletionProvider) ServerOption
func WithPromptFilter(promptFilter PromptFilterFunc) ServerOption
func WithPromptHandlerMiddleware(promptHandlerMiddleware PromptHandlerMiddleware) ServerOption
func WithRecovery() ServerOption
func WithResourceCapabilities(subscribe, listChanged bool) ServerOption
func WithResourceCompletionProvider(provider ResourceCompletionProvider) ServerOption
func WithResourceHandlerMiddleware(resourceHandlerMiddleware ResourceHandlerMiddleware) ServerOption
func WithResourceRecovery() ServerOption
func WithRoots() ServerOption
func WithTaskCapabilities(list, cancel, toolCallTasks bool) ServerOption
func WithTaskHooks(taskHooks *TaskHooks) ServerOption
func WithTitle(title string) ServerOption
func WithToolCapabilities(listChanged bool) ServerOption
func WithToolFilter(toolFilter ToolFilterFunc) ServerOption
func WithToolHandlerMiddleware(toolHandlerMiddleware ToolHandlerMiddleware) ServerOption
func WithWebsiteURL(websiteURL string) ServerOption
func NewMCPServer(name, version string, opts ...ServerOption) *MCPServer
ServerPrompt combines a Prompt with its handler function.
Handler PromptHandlerFunc
Prompt mcp.Prompt
func (*MCPServer).AddPrompts(prompts ...ServerPrompt)
func (*MCPServer).SetPrompts(prompts ...ServerPrompt)
ServerResource combines a Resource with its handler function.
Handler ResourceHandlerFunc
Resource mcp.Resource
func SessionWithResources.GetSessionResources() map[string]ServerResource
func (*MCPServer).AddResources(resources ...ServerResource)
func (*MCPServer).AddSessionResources(sessionID string, resources ...ServerResource) error
func (*MCPServer).SetResources(resources ...ServerResource)
func SessionWithResources.SetSessionResources(resources map[string]ServerResource)
ServerResourceTemplate combines a ResourceTemplate with its handler function.
Handler ResourceTemplateHandlerFunc
Template mcp.ResourceTemplate
func SessionWithResourceTemplates.GetSessionResourceTemplates() map[string]ServerResourceTemplate
func (*MCPServer).AddResourceTemplates(resourceTemplates ...ServerResourceTemplate)
func (*MCPServer).AddSessionResourceTemplates(sessionID string, templates ...ServerResourceTemplate) error
func (*MCPServer).SetResourceTemplates(templates ...ServerResourceTemplate)
func SessionWithResourceTemplates.SetSessionResourceTemplates(templates map[string]ServerResourceTemplate)
ServerTaskTool combines a Tool with its TaskToolHandlerFunc.
Handler TaskToolHandlerFunc
Tool mcp.Tool
func (*MCPServer).AddTaskTools(taskTools ...ServerTaskTool)
ServerTool combines a Tool with its ToolHandlerFunc.
Handler ToolHandlerFunc
Tool mcp.Tool
func (*MCPServer).GetTool(toolName string) *ServerTool
func (*MCPServer).ListTools() map[string]*ServerTool
func SessionWithTools.GetSessionTools() map[string]ServerTool
func (*MCPServer).AddSessionTools(sessionID string, tools ...ServerTool) error
func (*MCPServer).AddTools(tools ...ServerTool)
func (*MCPServer).SetTools(tools ...ServerTool)
func SessionWithTools.SetSessionTools(tools map[string]ServerTool)
SessionIDGenFunc is a function that produces a session ID for a new SSE connection.
It receives the request context and the HTTP request, and should return a session
identifier (string) or an error.
func WithSessionIDGenerator(fn SessionIDGenFunc) SSEOption
( SessionIdManager) Generate() string
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.
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.
*InsecureStatefulSessionIdManager
*StatelessGeneratingSessionIdManager
*StatelessSessionIdManager
func (*DefaultSessionIdManagerResolver).ResolveSessionIdManager(_ *http.Request) SessionIdManager
func SessionIdManagerResolver.ResolveSessionIdManager(r *http.Request) SessionIdManager
func NewDefaultSessionIdManagerResolver(manager SessionIdManager) *DefaultSessionIdManagerResolver
func WithSessionIdManager(manager SessionIdManager) StreamableHTTPOption
SessionIdManagerResolver resolves a SessionIdManager based on the HTTP request.
Implementations must handle a nil r, which may be passed from non-request
contexts such as the session idle TTL sweeper.
( SessionIdManagerResolver) ResolveSessionIdManager(r *http.Request) SessionIdManager
*DefaultSessionIdManagerResolver
func WithSessionIdManagerResolver(resolver SessionIdManagerResolver) StreamableHTTPOption
SessionWithClientInfo is an extension of ClientSession that can store client info
GetClientCapabilities returns the client capabilities for this session
GetClientInfo returns the client information for this session
Initialize marks session as fully initialized and ready for notifications
Initialized returns if session is ready to accept notifications
NotificationChannel provides a channel suitable for sending notifications to client.
SessionID is a unique identifier used to track user session.
SetClientCapabilities sets the client capabilities for this session
SetClientInfo sets the client information for this session
*InProcessSession
SessionWithClientInfo : ClientSession
SessionWithElicitation is an extension of ClientSession that can send elicitation requests
Initialize marks session as fully initialized and ready for notifications
Initialized returns if session is ready to accept notifications
NotificationChannel provides a channel suitable for sending notifications to client.
RequestElicitation sends an elicitation request to the client and waits for response
SessionID is a unique identifier used to track user session.
*InProcessSession
SessionWithElicitation : ClientSession
SessionWithLogging is an extension of ClientSession that can receive log message notifications and set log level
GetLogLevel retrieves the minimum log level
Initialize marks session as fully initialized and ready for notifications
Initialized returns if session is ready to accept notifications
NotificationChannel provides a channel suitable for sending notifications to client.
SessionID is a unique identifier used to track user session.
SetLogLevel sets the minimum log level
*InProcessSession
SessionWithLogging : ClientSession
SessionWithResources is an extension of ClientSession that can store session-specific resource data
GetSessionResources returns the resources specific to this session, if any
This method must be thread-safe for concurrent access
Initialize marks session as fully initialized and ready for notifications
Initialized returns if session is ready to accept notifications
NotificationChannel provides a channel suitable for sending notifications to client.
SessionID is a unique identifier used to track user session.
SetSessionResources sets resources specific to this session
This method must be thread-safe for concurrent access
SessionWithResources : ClientSession
SessionWithResourceTemplates is an extension of ClientSession that can store session-specific resource template data
GetSessionResourceTemplates returns the resource templates specific to this session, if any
This method must be thread-safe for concurrent access
Initialize marks session as fully initialized and ready for notifications
Initialized returns if session is ready to accept notifications
NotificationChannel provides a channel suitable for sending notifications to client.
SessionID is a unique identifier used to track user session.
SetSessionResourceTemplates sets resource templates specific to this session
This method must be thread-safe for concurrent access
SessionWithResourceTemplates : ClientSession
SessionWithRoots is an extension of ClientSession that can send list roots requests
Initialize marks session as fully initialized and ready for notifications
Initialized returns if session is ready to accept notifications
ListRoots sends an list roots request to the client and waits for response
NotificationChannel provides a channel suitable for sending notifications to client.
SessionID is a unique identifier used to track user session.
*InProcessSession
SessionWithRoots : ClientSession
SessionWithRoots : RootsHandler
SessionWithSampling extends ClientSession to support sampling requests.
Initialize marks session as fully initialized and ready for notifications
Initialized returns if session is ready to accept notifications
NotificationChannel provides a channel suitable for sending notifications to client.
( SessionWithSampling) RequestSampling(ctx context.Context, request mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error)
SessionID is a unique identifier used to track user session.
*InProcessSession
SessionWithSampling : ClientSession
SessionWithStreamableHTTPConfig extends ClientSession to support streamable HTTP transport configurations
Initialize marks session as fully initialized and ready for notifications
Initialized returns if session is ready to accept notifications
NotificationChannel provides a channel suitable for sending notifications to client.
SessionID is a unique identifier used to track user session.
UpgradeToSSEWhenReceiveNotification upgrades the client-server communication to SSE stream when the server
sends notifications to the client
The protocol specification:
- If the server response contains any JSON-RPC notifications, it MUST either:
- Return Content-Type: text/event-stream to initiate an SSE stream, OR
- Return Content-Type: application/json for a single JSON object
- The client MUST support both response types.
Reference: https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#sending-messages-to-the-server
SessionWithStreamableHTTPConfig : ClientSession
SessionWithTools is an extension of ClientSession that can store session-specific tool data
GetSessionTools returns the tools specific to this session, if any
This method must be thread-safe for concurrent access
Initialize marks session as fully initialized and ready for notifications
Initialized returns if session is ready to accept notifications
NotificationChannel provides a channel suitable for sending notifications to client.
SessionID is a unique identifier used to track user session.
SetSessionTools sets tools specific to this session
This method must be thread-safe for concurrent access
SessionWithTools : ClientSession
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.
func WithSSEContextFunc(fn SSEContextFunc) SSEOption
SSEOption defines a function type for configuring SSEServer
func WithAppendQueryToMessageEndpoint() SSEOption
func WithBasePath(basePath string) SSEOption
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 WithSessionIDGenerator(fn SessionIDGenFunc) SSEOption
func WithSSEContextFunc(fn SSEContextFunc) SSEOption
func WithSSEEndpoint(endpoint string) SSEOption
func WithStaticBasePath(basePath string) SSEOption
func WithUseFullURLForMessageEndpoint(useFullURLForMessageEndpoint bool) SSEOption
func NewSSEServer(server *MCPServer, opts ...SSEOption) *SSEServer
func NewTestServer(server *MCPServer, opts ...SSEOption) *httptest.Server
SSEServer implements a Server-Sent Events (SSE) based MCP server.
It provides real-time communication capabilities over HTTP using the SSE protocol.
(*SSEServer) CompleteMessageEndpoint() (string, error)
(*SSEServer) CompleteMessagePath() string
(*SSEServer) CompleteSseEndpoint() (string, error)
(*SSEServer) CompleteSsePath() string
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.
(*SSEServer) GetUrlPath(input string) (string, error)
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.
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.
SendEventToSession sends an event to a specific SSE session identified by sessionID.
Returns an error if the session is not found or closed.
ServeHTTP implements the http.Handler interface.
Shutdown gracefully stops the SSE server, closing all active sessions
and shutting down the HTTP server.
Start begins serving SSE connections on the specified address.
It sets up HTTP handlers for SSE and message endpoints.
*SSEServer : net/http.Handler
func NewSSEServer(server *MCPServer, opts ...SSEOption) *SSEServer
StatelessGeneratingSessionIdManager generates session IDs but doesn't validate them locally.
This allows session IDs to be generated for clients while working across multiple instances.
(*StatelessGeneratingSessionIdManager) Generate() string
(*StatelessGeneratingSessionIdManager) Terminate(sessionID string) (isNotAllowed bool, err error)
(*StatelessGeneratingSessionIdManager) Validate(sessionID string) (isTerminated bool, err error)
*StatelessGeneratingSessionIdManager : SessionIdManager
StatelessSessionIdManager does nothing, which means it has no session management, which is stateless.
(*StatelessSessionIdManager) Generate() string
(*StatelessSessionIdManager) Terminate(sessionID string) (isNotAllowed bool, err error)
(*StatelessSessionIdManager) Validate(sessionID string) (isTerminated bool, err error)
*StatelessSessionIdManager : SessionIdManager
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.
func WithStdioContextFunc(fn StdioContextFunc) StdioOption
func (*StdioServer).SetContextFunc(fn StdioContextFunc)
StdioOption defines a function type for configuring StdioServer
func WithErrorLogger(logger *log.Logger) StdioOption
func WithQueueSize(size int) StdioOption
func WithStdioContextFunc(fn StdioContextFunc) StdioOption
func WithWorkerPoolSize(size int) StdioOption
func ServeStdio(server *MCPServer, opts ...StdioOption) error
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.
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.
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.
SetErrorLogger configures where error messages from the StdioServer are logged.
The provided logger will receive all error messages generated during server operation.
func NewStdioServer(server *MCPServer) *StdioServer
StreamableHTTPOption defines a function type for configuring StreamableHTTPServer
func WithDisableStreaming(disable bool) StreamableHTTPOption
func WithEndpointPath(endpointPath string) StreamableHTTPOption
func WithHeartbeatInterval(interval time.Duration) StreamableHTTPOption
func WithHTTPContextFunc(fn HTTPContextFunc) StreamableHTTPOption
func WithLogger(logger util.Logger) StreamableHTTPOption
func WithSessionIdleTTL(ttl time.Duration) StreamableHTTPOption
func WithSessionIdManager(manager SessionIdManager) StreamableHTTPOption
func WithSessionIdManagerResolver(resolver SessionIdManagerResolver) StreamableHTTPOption
func WithStateful(stateful bool) StreamableHTTPOption
func WithStateLess(stateLess bool) StreamableHTTPOption
func WithStreamableHTTPServer(srv *http.Server) StreamableHTTPOption
func WithTLSCert(certFile, keyFile string) StreamableHTTPOption
func NewStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *StreamableHTTPServer
func NewTestStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *httptest.Server
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:
- Stream Resumability
ServeHTTP implements the http.Handler interface.
Shutdown gracefully stops the server, closing all active sessions
and shutting down the HTTP server.
Start begins serving the http server on the specified address and path
(endpointPath). like:
s.Start(":8080")
*StreamableHTTPServer : net/http.Handler
func NewStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *StreamableHTTPServer
TaskHooks contains lifecycle hooks for task execution.
These hooks enable observability and monitoring of task-augmented tools.
OnTaskCancelled []OnTaskCancelledHookFunc
OnTaskCompleted []OnTaskCompletedHookFunc
OnTaskCreated []OnTaskCreatedHookFunc
OnTaskFailed []OnTaskFailedHookFunc
OnTaskStatusChanged []OnTaskStatusChangedHookFunc
AddOnTaskCancelled registers a hook for task cancellation events.
AddOnTaskCompleted registers a hook for task completion events.
AddOnTaskCreated registers a hook for task creation events.
AddOnTaskFailed registers a hook for task failure events.
AddOnTaskStatusChanged registers a hook for all task status changes.
func WithTaskHooks(taskHooks *TaskHooks) ServerOption
TaskMetrics contains metrics about task execution.
This struct is passed to observability hooks to enable monitoring and analysis.
// When the task completed (nil if not completed)
// When the task was created
// How long the task took (0 if not completed)
// Error if task failed (nil otherwise)
// Session that owns this task
// Current status of the task
// Optional status message
// Unique identifier for the task
// Name of the tool that created the task
TaskToolHandlerFunc handles tool calls that execute asynchronously.
It returns immediately with task creation info; the actual result is
retrieved later via tasks/result.
func (*MCPServer).AddTaskTool(tool mcp.Tool, handler TaskToolHandlerFunc)
ToolFilterFunc is a function that filters tools based on context, typically using session information.
func WithToolFilter(toolFilter ToolFilterFunc) ServerOption
ToolHandlerFunc handles tool calls with given arguments.
func (*MCPServer).AddSessionTool(sessionID string, tool mcp.Tool, handler ToolHandlerFunc) error
func (*MCPServer).AddTool(tool mcp.Tool, handler ToolHandlerFunc)
ToolHandlerMiddleware is a middleware function that wraps a ToolHandlerFunc.
func WithToolHandlerMiddleware(toolHandlerMiddleware ToolHandlerMiddleware) ServerOption
func (*MCPServer).Use(mw ...ToolHandlerMiddleware)
UnparsableMessageError is attached to the RequestError when json.Unmarshal
fails on the request.
(*UnparsableMessageError) Error() string
(*UnparsableMessageError) GetMessage() json.RawMessage
(*UnparsableMessageError) GetMethod() mcp.MCPMethod
(*UnparsableMessageError) Unwrap() error
*UnparsableMessageError : error
*UnparsableMessageError : golang.org/x/xerrors.Wrapper
Package-Level Functions (total 71)
ClientSessionFromContext retrieves current client notification context from context.
GenerateInProcessSessionID generates a unique session ID for inprocess clients
InProcessSamplingHandlerFromContext retrieves the inprocess sampling handler from context
NewDefaultSessionIdManagerResolver creates a new DefaultSessionIdManagerResolver with the given SessionIdManager
func NewInProcessSession(sessionID string, samplingHandler SamplingHandler) *InProcessSession func NewInProcessSessionWithHandlers(sessionID string, samplingHandler SamplingHandler, elicitationHandler ElicitationHandler, rootsHandler RootsHandler) *InProcessSession
NewMCPServer creates a new MCP server instance with the given name, version and options
NewSSEServer creates a new SSE server instance with the given MCP server and options.
NewStdioServer creates a new stdio server wrapper around an MCPServer.
It initializes the server with a default error logger that discards all output.
NewStreamableHTTPServer creates a new streamable-http server instance
NewTestServer creates a test server for testing purposes
NewTestStreamableHTTPServer creates a test server for testing purposes
ServerFromContext retrieves the MCPServer instance from a context
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.
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.
WithBasePath adds a new option for setting a static base path.
Deprecated: Use WithStaticBasePath instead. This will be removed in a future version.
WithBaseURL sets the base URL for the SSE server
WithCompletions enables the completion capability
WithDescription sets the description for the server implementation.
WithDisableStreaming prevents the server from responding to GET requests with
a streaming response. Instead, it will respond with a 405 Method Not Allowed status.
This can be useful in scenarios where streaming is not desired or supported.
The default is false, meaning streaming is enabled.
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.
WithElicitation enables elicitation capabilities for the server
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.
WithErrorLogger sets the error logger for the server
WithExperimental sets experimental, non-standard capabilities on the server.
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.
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.
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.
WithHTTPServer sets the HTTP server instance.
NOTE: When providing a custom HTTP server, you must handle routing yourself
If routing is not set up, the server will start but won't handle any MCP requests.
WithIcons sets the server icons for the implementation metadata returned
during initialization. The icons slice and nested Sizes fields are defensively
copied to prevent external mutation.
WithInProcessSamplingHandler adds a sampling handler to the context for inprocess clients
WithInstructions sets the server instructions for the client returned in the initialize response
func WithKeepAlive(keepAlive bool) SSEOption func WithKeepAliveInterval(keepAliveInterval time.Duration) SSEOption
WithLogger sets the logger for the server
WithLogging enables logging capabilities for the server
WithMaxConcurrentTasks sets a limit on the maximum number of concurrent running tasks.
When this limit is reached, attempts to create new tasks will fail with an error.
If not set (or set to 0), there is no limit on concurrent tasks.
WithMessageEndpoint sets the message endpoint path
WithPaginationLimit sets the pagination limit for the server.
WithPromptCapabilities configures prompt-related server capabilities
WithPromptCompletionProvider sets a custom prompt completion provider
WithPromptFilter adds a filter function that will be applied to prompts before they are returned in list_prompts
WithPromptHandlerMiddleware allows adding a middleware for the
prompt handler call chain.
WithQueueSize sets the size of the tool call queue
WithRecovery adds a middleware that recovers from panics in tool handlers.
WithResourceCapabilities configures resource-related server capabilities
WithResourceCompletionProvider sets a custom resource completion provider
WithResourceHandlerMiddleware allows adding a middleware for the
resource handler call chain.
WithResourceRecovery adds a middleware that recovers from panics in resource handlers.
WithRoots returns a ServerOption that enables the roots capability on the MCPServer
WithSessionIDGenerator sets a custom session ID generator. If fn == nil the call is ignored.
WithSessionIdleTTL sets the idle TTL for per-session transport state.
When enabled, a background sweeper periodically removes entries from
per-session stores (tools, resources, resource templates, log levels,
request IDs) for sessions that have been idle longer than the given
duration. This prevents memory leaks when clients disconnect without
sending a DELETE request. A zero or negative value disables the sweeper
(the default).
WithSessionIdManager sets a custom session id generator for the server.
By default, the server uses StatelessGeneratingSessionIdManager (generates IDs but no local validation).
Note: Options are applied in order; the last one wins. If combined with
WithStateLess or WithSessionIdManagerResolver, whichever is applied last takes effect.
WithSessionIdManagerResolver sets a custom session id manager resolver for the server.
This allows for request-based session id management strategies.
Note: Options are applied in order; the last one wins. If combined with
WithStateLess or WithSessionIdManager, whichever is applied last takes effect.
WithSSEContextFunc sets a function that will be called to customise the context
to the server using the incoming request.
WithSSEEndpoint sets the SSE endpoint path
WithStateful enables stateful session management using InsecureStatefulSessionIdManager.
This requires sticky sessions in multi-instance deployments.
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.
Note: This is a convenience method. It's identical to set WithSessionIdManager option
to StatelessSessionIdManager.
WithStaticBasePath adds a new option for setting a static base path
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.
WithStreamableHTTPServer sets the HTTP server instance for StreamableHTTPServer.
NOTE: When providing a custom HTTP server, you must handle routing yourself
If routing is not set up, the server will start but won't handle any MCP requests.
WithTaskCapabilities configures task-related server capabilities
WithTaskHooks allows adding hooks for task lifecycle events.
Use these hooks to monitor task execution, track metrics, and observe
task-augmented tool behavior.
WithTitle sets the human-readable display title for the server implementation.
WithTLSCert sets the TLS certificate and key files for HTTPS support.
Both certFile and keyFile must be provided to enable TLS.
WithToolCapabilities configures tool-related server capabilities
WithToolFilter adds a filter function that will be applied to tools before they are returned in list_tools
WithToolHandlerMiddleware allows adding a middleware for the
tool handler call chain.
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".
WithWebsiteURL sets the website URL for the server implementation.
WithWorkerPoolSize sets the number of workers for processing tool calls
Package-Level Variables (total 17)
ErrElicitationNotSupported is returned when the session does not support elicitation
ErrNoActiveSession is returned when there is no active session in the context
ErrNoClientSession is returned when there is no active client session in the context
Notification-related errors
ErrRootsNotSupported is returned when the session does not support roots
Session-related errors
var ErrToolNotFound error
Common server errors
Package-Level Constants (total 2)
Common HTTP header constants used across server transports
Common HTTP header constants used across server transports
![]() |
The pages are generated with Golds v0.8.4. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |