Documentation
¶
Overview ¶
Package server is a drop-in compatibility shim for github.com/mark3labs/mcp-go/server, reimplemented on top of the official github.com/modelcontextprotocol/go-sdk.
It presents mcp-go's MCPServer API (NewMCPServer, AddTool, AddResource, AddPrompt, the ServerTool/ServerResource/ServerPrompt registration units, the Hooks and per-session interfaces, and the stdio/SSE/Streamable-HTTP transports) while delegating protocol handling to a go-sdk Server. Tools, resources and prompts registered here are converted to their go-sdk equivalents and served by the SDK.
Scope and status ¶
The global registration path (AddTool/AddResource/AddPrompt served over the stdio and HTTP transports) is fully functional and tested. The per-session interfaces (SessionWithTools, SessionWithResources, SessionIdManager) and the Hooks type are implemented for source compatibility, and per-session tool overlays are stored on the session objects. Wiring those overlays into go-sdk's live session lifecycle so that per-session tool *dispatch* matches mcp-go exactly (ToolHive's vMCP projection) is the one area that needs integration validation against ToolHive before this package can fully replace mcp-go for the vMCP server; see the notes on SessionWithTools.
Stability: Alpha.
Index ¶
- func ServeStdio(server *MCPServer, _ ...StdioOption) error
- type ClientSession
- type HTTPContextFunc
- type Hooks
- type MCPServer
- 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 (*MCPServer) RequestElicitation(ctx context.Context, request mcp.ElicitationRequest) (*mcp.ElicitationResult, error)
- func (s *MCPServer) SendNotificationToAllClients(method string, params map[string]any)
- func (s *MCPServer) SetTools(tools ...ServerTool)
- func (*MCPServer) WithContext(ctx context.Context, session ClientSession) context.Context
- type NotificationHandlerFunc
- type OnBeforeCallToolFunc
- type OnBeforeListToolsFunc
- type OnRegisterSessionHookFunc
- type PromptHandlerFunc
- type ResourceHandlerFunc
- type ResourceTemplateHandlerFunc
- type SSEOption
- type SSEServer
- type ServerOption
- func WithHooks(hooks *Hooks) ServerOption
- func WithLogger(logger *slog.Logger) ServerOption
- func WithLogging() ServerOption
- func WithPromptCapabilities(listChanged bool) ServerOption
- func WithResourceCapabilities(subscribe, listChanged bool) ServerOption
- func WithToolCapabilities(listChanged bool) ServerOption
- type ServerPrompt
- type ServerResource
- type ServerResourceTemplate
- type ServerTool
- type SessionIdManager
- type SessionWithResources
- type SessionWithTools
- type StdioOption
- type StreamableHTTPOption
- type StreamableHTTPServer
- type ToolHandlerFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ServeStdio ¶
func ServeStdio(server *MCPServer, _ ...StdioOption) error
ServeStdio runs the MCP server over stdio until the context is done. It mirrors mcp-go's server.ServeStdio.
Types ¶
type ClientSession ¶
type ClientSession interface {
// Initialize marks the session as fully initialized.
Initialize()
// Initialized reports whether the session is ready for notifications.
Initialized() bool
// NotificationChannel provides a channel for sending notifications to the client.
NotificationChannel() chan<- mcp.JSONRPCNotification
// SessionID uniquely identifies the session.
SessionID() string
}
ClientSession represents an active client session. It mirrors mcp-go's server.ClientSession.
func ClientSessionFromContext ¶
func ClientSessionFromContext(ctx context.Context) ClientSession
ClientSessionFromContext returns the ClientSession stored in ctx, or nil.
type HTTPContextFunc ¶
HTTPContextFunc customizes the request context for HTTP transports.
type Hooks ¶
type Hooks struct {
// contains filtered or unexported fields
}
Hooks holds lifecycle callbacks. It mirrors the subset of mcp-go's server.Hooks that ToolHive registers.
func (*Hooks) AddBeforeCallTool ¶
func (c *Hooks) AddBeforeCallTool(hook OnBeforeCallToolFunc)
AddBeforeCallTool registers a before-tools/call hook.
func (*Hooks) AddBeforeListTools ¶
func (c *Hooks) AddBeforeListTools(hook OnBeforeListToolsFunc)
AddBeforeListTools registers a before-tools/list hook.
func (*Hooks) AddOnRegisterSession ¶
func (c *Hooks) AddOnRegisterSession(hook OnRegisterSessionHookFunc)
AddOnRegisterSession registers a session-registration hook.
type MCPServer ¶
type MCPServer struct {
// contains filtered or unexported fields
}
MCPServer is an MCP server backed by the official go-sdk. It mirrors the subset of mcp-go's server.MCPServer that ToolHive uses.
func NewMCPServer ¶
func NewMCPServer(name, version string, opts ...ServerOption) *MCPServer
NewMCPServer creates a new MCP server with the given name and version.
func (*MCPServer) AddPrompt ¶
func (s *MCPServer) AddPrompt(prompt mcp.Prompt, handler PromptHandlerFunc)
AddPrompt registers a prompt and its handler.
func (*MCPServer) AddResource ¶
func (s *MCPServer) AddResource(resource mcp.Resource, handler ResourceHandlerFunc)
AddResource registers a resource and its handler.
func (*MCPServer) AddResourceTemplate ¶
func (s *MCPServer) AddResourceTemplate(template mcp.ResourceTemplate, handler ResourceTemplateHandlerFunc)
AddResourceTemplate registers a resource template and its handler.
func (*MCPServer) AddTool ¶
func (s *MCPServer) AddTool(tool mcp.Tool, handler ToolHandlerFunc)
AddTool registers a tool and its handler.
func (*MCPServer) AddTools ¶
func (s *MCPServer) AddTools(tools ...ServerTool)
AddTools registers multiple tools.
func (*MCPServer) DeleteTools ¶
DeleteTools removes tools by name.
func (*MCPServer) HandleMessage ¶
func (s *MCPServer) HandleMessage(ctx context.Context, message json.RawMessage) mcp.JSONRPCMessage
HandleMessage processes a single incoming JSON-RPC message and returns the appropriate JSON-RPC response (or nil for notifications and server-directed responses). It mirrors mcp-go's server.MCPServer.HandleMessage.
go-sdk backing and limitation: the go-sdk drives its own JSON-RPC loop over a Transport and does not expose a public "handle one raw message" entrypoint. This shim therefore dispatches the message directly against the tools, resources, prompts and their handlers registered on this MCPServer — the same registration state the go-sdk server is built from — so behavior matches mcp-go for the methods ToolHive exercises: initialize, ping, tools/list, tools/call, resources/list, resources/templates/list, resources/read, prompts/list and prompts/get, plus notifications (which return nil). Capability-gated extras that ToolHive does not use over this path (logging setLevel, subscribe/unsubscribe, completion, tasks) return METHOD_NOT_FOUND.
func (*MCPServer) RequestElicitation ¶
func (*MCPServer) RequestElicitation(ctx context.Context, request mcp.ElicitationRequest) (*mcp.ElicitationResult, error)
RequestElicitation sends a server->client elicitation request on the session associated with ctx and returns the user's response. It mirrors mcp-go's (*MCPServer).RequestElicitation.
func (*MCPServer) SendNotificationToAllClients ¶
SendNotificationToAllClients broadcasts a server-initiated notification with the given method and params to every currently connected client session. It mirrors mcp-go's server.MCPServer.SendNotificationToAllClients, which ToolHive's stdio bridge uses to relay upstream notifications downstream.
go-sdk backing and limitation: the go-sdk does not expose a public API to send an arbitrary (method, params) notification on a ServerSession; only typed senders are exported. This method therefore maps the well-known MCP notification methods onto the go-sdk's typed senders:
- notifications/progress -> ServerSession.NotifyProgress
- notifications/message -> ServerSession.Log (delivered only once the client has set a logging level, per the go-sdk/spec behavior)
The list-changed notifications (tools/prompts/resources) are emitted automatically by the go-sdk server when its registered feature set changes, so they cannot be re-broadcast through a public API here; they, and any other unrecognized method, are dropped (logged at debug level). This is the one behavioral gap versus mcp-go's raw channel-based broadcast and is documented rather than silently ignored.
func (*MCPServer) SetTools ¶
func (s *MCPServer) SetTools(tools ...ServerTool)
SetTools replaces the tool set.
func (*MCPServer) WithContext ¶
WithContext stores the given ClientSession in the returned context so that handlers (and ClientSessionFromContext) can recover it. It mirrors mcp-go's server.MCPServer.WithContext, which ToolHive uses to associate a session with a request context (e.g. for per-session tool injection).
type NotificationHandlerFunc ¶
type NotificationHandlerFunc func(ctx context.Context, notification mcp.JSONRPCNotification)
NotificationHandlerFunc handles a client notification.
type OnBeforeCallToolFunc ¶
type OnBeforeCallToolFunc func(ctx context.Context, id any, message *mcp.CallToolRequest)
OnBeforeCallToolFunc runs before a tools/call request is handled.
type OnBeforeListToolsFunc ¶
type OnBeforeListToolsFunc func(ctx context.Context, id any, message *mcp.ListToolsRequest)
OnBeforeListToolsFunc runs before a tools/list request is handled.
type OnRegisterSessionHookFunc ¶
type OnRegisterSessionHookFunc func(ctx context.Context, session ClientSession)
OnRegisterSessionHookFunc runs when a session registers.
type PromptHandlerFunc ¶
type PromptHandlerFunc func(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error)
PromptHandlerFunc handles a prompt get.
type ResourceHandlerFunc ¶
type ResourceHandlerFunc func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error)
ResourceHandlerFunc handles a resource read.
type ResourceTemplateHandlerFunc ¶
type ResourceTemplateHandlerFunc func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error)
ResourceTemplateHandlerFunc handles a templated resource read.
type SSEOption ¶
type SSEOption func(*SSEServer)
SSEOption configures an SSEServer.
func WithMessageEndpoint ¶
WithMessageEndpoint sets the message endpoint path.
func WithSSEEndpoint ¶
WithSSEEndpoint sets the SSE endpoint path.
type SSEServer ¶
type SSEServer struct {
// contains filtered or unexported fields
}
SSEServer serves the MCP server over the (legacy) SSE transport.
func NewSSEServer ¶
NewSSEServer creates an SSE server for the MCP server.
func (*SSEServer) MessageHandler ¶
MessageHandler returns the http.Handler for the message (POST) endpoint. See SSEHandler for the go-sdk backing and the shared-handler limitation.
func (*SSEServer) SSEHandler ¶
SSEHandler returns the http.Handler for the SSE (stream) endpoint. It mirrors mcp-go's SSEServer.SSEHandler, allowing the endpoint to be mounted on a custom router.
go-sdk backing and limitation: the go-sdk serves SSE and message delivery through a single unified handler keyed off the request method and a session query parameter, whereas mcp-go splits them across two paths. Both SSEHandler and MessageHandler therefore return the same underlying go-sdk handler; when mounting them on separate paths, mount both under a common base path so the go-sdk handler can correlate the stream and its message posts.
func (*SSEServer) ServeHTTP ¶
func (s *SSEServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler.
type ServerOption ¶
type ServerOption func(*MCPServer)
ServerOption configures an MCPServer.
func WithLogger ¶
func WithLogger(logger *slog.Logger) ServerOption
WithLogger sets the server logger.
func WithPromptCapabilities ¶
func WithPromptCapabilities(listChanged bool) ServerOption
WithPromptCapabilities declares prompt support.
func WithResourceCapabilities ¶
func WithResourceCapabilities(subscribe, listChanged bool) ServerOption
WithResourceCapabilities declares resource support.
func WithToolCapabilities ¶
func WithToolCapabilities(listChanged bool) ServerOption
WithToolCapabilities declares tool support (listChanged notifications).
type ServerPrompt ¶
type ServerPrompt struct {
Prompt mcp.Prompt
Handler PromptHandlerFunc
}
ServerPrompt pairs a prompt with its handler.
type ServerResource ¶
type ServerResource struct {
Resource mcp.Resource
Handler ResourceHandlerFunc
}
ServerResource pairs a resource with its handler.
type ServerResourceTemplate ¶
type ServerResourceTemplate struct {
Template mcp.ResourceTemplate
Handler ResourceTemplateHandlerFunc
}
ServerResourceTemplate pairs a resource template with its handler.
type ServerTool ¶
type ServerTool struct {
Tool mcp.Tool
Handler ToolHandlerFunc
}
ServerTool pairs a tool with its handler.
type SessionIdManager ¶
type SessionIdManager interface {
// Generate returns a new session ID.
Generate() string
// Validate reports whether a session ID is valid; isTerminated is true if
// the ID is valid but belongs to a terminated session.
Validate(sessionID string) (isTerminated bool, err error)
// Terminate marks a session ID terminated; isNotAllowed is true if policy
// prevents client termination.
Terminate(sessionID string) (isNotAllowed bool, err error)
}
SessionIdManager governs MCP session ID lifecycle. It mirrors mcp-go's server.SessionIdManager so ToolHive's implementation can be supplied via WithSessionIdManager.
type SessionWithResources ¶
type SessionWithResources interface {
ClientSession
// GetSessionResources returns the session's resources. Thread-safe.
GetSessionResources() map[string]ServerResource
// SetSessionResources sets the session's resources. Thread-safe.
SetSessionResources(resources map[string]ServerResource)
}
SessionWithResources is a ClientSession that carries per-session resources.
type SessionWithTools ¶
type SessionWithTools interface {
ClientSession
// GetSessionTools returns the session's tools. Thread-safe.
GetSessionTools() map[string]ServerTool
// SetSessionTools sets the session's tools. Thread-safe.
SetSessionTools(tools map[string]ServerTool)
}
SessionWithTools is a ClientSession that carries per-session tools. ToolHive's vMCP layer uses this to project a per-session tool set.
NOTE: overlays set here are stored and merged when a go-sdk server is built for the session (see MCPServer.buildServer). Making per-session tool changes take effect on an already-connected go-sdk session at runtime (live list_changed dispatch) is the integration point that needs validation against ToolHive's vMCP flow before this shim can fully replace mcp-go there.
type StdioOption ¶
type StdioOption func(*stdioConfig)
StdioOption configures the stdio server (retained for API compatibility).
type StreamableHTTPOption ¶
type StreamableHTTPOption func(*StreamableHTTPServer)
StreamableHTTPOption configures a StreamableHTTPServer.
func WithEndpointPath ¶
func WithEndpointPath(endpointPath string) StreamableHTTPOption
WithEndpointPath sets the HTTP path the server is mounted at.
func WithHTTPContextFunc ¶
func WithHTTPContextFunc(fn HTTPContextFunc) StreamableHTTPOption
WithHTTPContextFunc installs a per-request context customizer.
func WithHeartbeatInterval ¶
func WithHeartbeatInterval(interval time.Duration) StreamableHTTPOption
WithHeartbeatInterval sets the keep-alive ping interval.
func WithSessionIdManager ¶
func WithSessionIdManager(manager SessionIdManager) StreamableHTTPOption
WithSessionIdManager supplies a session ID manager.
NOTE: the go-sdk manages MCP session IDs internally; the supplied manager is retained for API compatibility but does not yet drive the SDK's ID lifecycle.
type StreamableHTTPServer ¶
type StreamableHTTPServer struct {
// contains filtered or unexported fields
}
StreamableHTTPServer serves the MCP server over the Streamable HTTP transport. It implements http.Handler so it can be mounted on an http.ServeMux, and also offers Start/Shutdown for standalone use.
func NewStreamableHTTPServer ¶
func NewStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *StreamableHTTPServer
NewStreamableHTTPServer creates a Streamable HTTP server for the MCP server.
func (*StreamableHTTPServer) ServeHTTP ¶
func (s *StreamableHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler.
func (*StreamableHTTPServer) Shutdown ¶
func (s *StreamableHTTPServer) Shutdown(ctx context.Context) error
Shutdown gracefully stops the HTTP server.
func (*StreamableHTTPServer) Start ¶
func (s *StreamableHTTPServer) Start(addr string) error
Start serves on addr until Shutdown is called.
type ToolHandlerFunc ¶
type ToolHandlerFunc func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)
ToolHandlerFunc handles a tool call. It mirrors mcp-go's type exactly.