Documentation
¶
Overview ¶
Package hyperserve provides comprehensive MCP (Model Context Protocol) built-in tools and resources.
This file consolidates all built-in MCP functionality including:
- Developer Tools: For interactive development with AI assistants
- DevOps Resources: For server monitoring and observability
- File Tools: For filesystem operations
- HTTP Tools: For making external requests
- System Resources: For runtime information and metrics
Security Considerations:
- Developer tools should ONLY be enabled in development environments
- DevOps resources expose no sensitive data (TLS keys, auth functions excluded)
- File tools use Go 1.24's os.Root for path traversal protection
- All tools implement proper input validation and error handling
Package hyperserve provides built-in middleware for common HTTP server functionality.
The middleware package includes:
- Request logging with structured output
- Panic recovery to prevent server crashes
- Request metrics collection
- Authentication (Basic, Bearer token, custom)
- Rate limiting per IP address
- Security headers (HSTS, CSP, etc.)
- Request/Response timing
Middleware can be applied globally or to specific routes:
// Global middleware
srv.AddMiddleware("*", hyperserve.RequestLoggerMiddleware)
// Route-specific middleware
srv.AddMiddleware("/api", hyperserve.AuthMiddleware(srv.Options))
// Combine multiple middleware
srv.AddMiddlewareGroup("/admin",
hyperserve.AuthMiddleware(srv.Options),
hyperserve.RateLimitMiddleware(srv),
)
Package hyperserve provides configuration options for the HTTP server.
Configuration follows a hierarchical priority:
- Function parameters (highest priority)
- Environment variables
- Configuration file (options.json)
- Default values (lowest priority)
Environment Variables:
- SERVER_ADDR: Main server address (default ":8080")
- HEALTH_ADDR: Health check server address (default ":8081")
- HS_HARDENED_MODE: Enable security headers (default "false")
- HS_MCP_ENABLED: Enable Model Context Protocol (default "false")
- HS_MCP_ENDPOINT: MCP endpoint path (default "/mcp")
- HS_MCP_DEV: Enable MCP developer tools (default "false")
- HS_MCP_OBSERVABILITY: Enable MCP observability resources (default "false")
- HS_MCP_TRANSPORT: MCP transport type: "http" or "stdio" (default "http")
- HS_CSP_WEB_WORKER_SUPPORT: Enable Web Worker CSP headers (default "false")
- HS_LOG_LEVEL: Set log level (DEBUG, INFO, WARN, ERROR) (default "INFO")
- HS_DEBUG: Enable debug mode and debug logging (default "false")
- HS_SUPPRESS_BANNER: Suppress the HyperServe ASCII banner at startup (default "false")
Example configuration file (options.json):
{
"addr": ":3000",
"tls": true,
"cert_file": "server.crt",
"key_file": "server.key",
"run_health_server": true,
"hardened_mode": true,
"debug_mode": false,
"log_level": "INFO"
}
Package hyperserve provides a lightweight, high-performance HTTP server framework with minimal external dependencies (golang.org/x/time/rate for rate limiting only).
Key Features:
- Zero configuration with sensible defaults
- Built-in middleware for logging, recovery, and metrics
- Graceful shutdown handling
- Health check endpoints for Kubernetes
- Model Context Protocol (MCP) support for AI assistants
- WebSocket support for real-time communication (standard library only)
- TLS/HTTPS support with automatic certificate management
- Rate limiting and authentication
- Template rendering support
- Server-Sent Events (SSE) support
Basic Usage:
srv, err := hyperserve.NewServer()
if err != nil {
log.Fatal(err)
}
srv.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
})
srv.Run() // Blocks until shutdown signal
With Options:
srv, err := hyperserve.NewServer(
hyperserve.WithAddr(":8080"),
hyperserve.WithHealthServer(),
hyperserve.WithTLS("cert.pem", "key.pem"),
hyperserve.WithMCPSupport("MyApp", "1.0.0"),
)
WebSocket Support:
upgrader := hyperserve.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Configure based on your needs
},
}
srv.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("WebSocket upgrade error: %v", err)
return
}
defer conn.Close()
// Handle WebSocket messages
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
break
}
// Echo message back
conn.WriteMessage(messageType, p)
}
})
Index ¶
- Constants
- Variables
- func EnsureTrailingSlash(dir string) string
- func GetVersionInfo() string
- func HealthCheckHandler(w http.ResponseWriter, r *http.Request)
- func IsCloseError(err error, codes ...int) bool
- func IsUnexpectedCloseError(err error, expectedCodes ...int) bool
- func NewStdioTransport(logger *slog.Logger) *stdioTransport
- func NewStdioTransportWithIO(r io.Reader, w io.Writer, logger *slog.Logger) *stdioTransport
- func PanicHandler(w http.ResponseWriter, r *http.Request)
- func RecoveryMiddleware(next http.Handler) http.HandlerFunc
- func RequestLoggerMiddleware(next http.Handler) http.HandlerFunc
- func ResponseTimeMiddleware(next http.Handler) http.HandlerFunc
- func TraceMiddleware(next http.Handler) http.HandlerFunc
- type AuthTokenInjector
- type CalculatorTool
- type CapturedRequest
- type CapturedResponse
- type ConfigResource
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) CloseHandler() func(code int, text string) error
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) PingHandler() func(appData string) error
- func (c *Conn) PongHandler() func(appData string) error
- func (c *Conn) ReadJSON(v interface{}) error
- func (c *Conn) ReadMessage() (messageType int, p []byte, err error)
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) SetCloseHandler(h func(code int, text string) error)
- func (c *Conn) SetPingHandler(h func(appData string) error)
- func (c *Conn) SetPongHandler(h func(appData string) error)
- func (c *Conn) SetReadDeadline(t time.Time) error
- func (c *Conn) SetWriteDeadline(t time.Time) error
- func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error
- func (c *Conn) WriteJSON(v interface{}) error
- func (c *Conn) WriteMessage(messageType int, data []byte) error
- type DataFunc
- type DevGuideTool
- type DiscoveryPolicy
- type FileReadTool
- type HTTPRequestTool
- type Header
- type InterceptableRequest
- type InterceptableResponse
- type Interceptor
- type InterceptorChain
- type InterceptorResponse
- type JSONRPCEngine
- func (engine *JSONRPCEngine) GetRegisteredMethods() []string
- func (engine *JSONRPCEngine) ProcessRequest(requestData []byte) []byte
- func (engine *JSONRPCEngine) ProcessRequestDirect(request *JSONRPCRequest) *JSONRPCResponse
- func (engine *JSONRPCEngine) RegisterMethod(name string, handler JSONRPCMethodHandler)
- type JSONRPCError
- type JSONRPCMethodHandler
- type JSONRPCRequest
- type JSONRPCResponse
- type ListDirectoryTool
- type LogResource
- type LoggingCapability
- type MCPCapabilities
- type MCPClientInfo
- type MCPDiscoveryInfo
- type MCPExtension
- type MCPExtensionBuilder
- func (b *MCPExtensionBuilder) Build() MCPExtension
- func (b *MCPExtensionBuilder) WithConfiguration(fn func(*Server) error) *MCPExtensionBuilder
- func (b *MCPExtensionBuilder) WithDescription(desc string) *MCPExtensionBuilder
- func (b *MCPExtensionBuilder) WithResource(resource MCPResource) *MCPExtensionBuilder
- func (b *MCPExtensionBuilder) WithTool(tool MCPTool) *MCPExtensionBuilder
- type MCPHandler
- func (h *MCPHandler) GetMetrics() map[string]interface{}
- func (h *MCPHandler) GetRegisteredResources() []string
- func (h *MCPHandler) GetRegisteredTools() []string
- func (h *MCPHandler) GetToolByName(name string) (MCPTool, bool)
- func (h *MCPHandler) ProcessRequest(requestData []byte) []byte
- func (h *MCPHandler) ProcessRequestWithTransport(transport MCPTransport) error
- func (h *MCPHandler) RegisterNamespace(name string, configs ...MCPNamespaceConfig) error
- func (h *MCPHandler) RegisterResource(resource MCPResource)
- func (h *MCPHandler) RegisterResourceInNamespace(resource MCPResource, namespace string)
- func (h *MCPHandler) RegisterSSEClient(clientID string) chan *JSONRPCRequest
- func (h *MCPHandler) RegisterTool(tool MCPTool)
- func (h *MCPHandler) RegisterToolInNamespace(tool MCPTool, namespace string)
- func (h *MCPHandler) RunStdioLoop() error
- func (h *MCPHandler) SendSSENotification(clientID string, method string, params interface{}) error
- func (h *MCPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (h *MCPHandler) UnregisterSSEClient(clientID string)
- type MCPInitializeParams
- type MCPInitializeResult
- type MCPMetrics
- type MCPNamespace
- type MCPNamespaceConfig
- type MCPResource
- type MCPResourceContent
- type MCPResourceInfo
- type MCPResourceReadParams
- type MCPServerInfo
- type MCPTool
- type MCPToolCallParams
- type MCPToolInfo
- type MCPToolResult
- type MCPToolWithContext
- type MCPTransport
- type MCPTransportConfig
- type MCPTransportInfo
- type MCPTransportType
- type MetricsResource
- type MiddlewareFunc
- func AuthMiddleware(options *ServerOptions) MiddlewareFunc
- func ChaosMiddleware(options *ServerOptions) MiddlewareFunc
- func HeadersMiddleware(options *ServerOptions) MiddlewareFunc
- func MetricsMiddleware(srv *Server) MiddlewareFunc
- func RateLimitMiddleware(srv *Server) MiddlewareFunc
- func RequestCaptureMiddleware(debuggerTool *RequestDebuggerTool) MiddlewareFunc
- type MiddlewareRegistry
- type MiddlewareStack
- type PoolConfig
- type PoolStats
- type PromptsCapability
- type RateLimitInterceptor
- func (rli *RateLimitInterceptor) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
- func (rli *RateLimitInterceptor) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
- func (rli *RateLimitInterceptor) Name() string
- type RateLimiter
- type RequestDebuggerTool
- func (t *RequestDebuggerTool) CaptureRequest(r *http.Request, responseHeaders map[string][]string, statusCode int, ...)
- func (t *RequestDebuggerTool) Description() string
- func (t *RequestDebuggerTool) Execute(params map[string]interface{}) (interface{}, error)
- func (t *RequestDebuggerTool) Name() string
- func (t *RequestDebuggerTool) Schema() map[string]interface{}
- type RequestLogger
- type ResourceBuilder
- func (b *ResourceBuilder) Build() MCPResource
- func (b *ResourceBuilder) WithDescription(desc string) *ResourceBuilder
- func (b *ResourceBuilder) WithMimeType(mimeType string) *ResourceBuilder
- func (b *ResourceBuilder) WithName(name string) *ResourceBuilder
- func (b *ResourceBuilder) WithRead(fn func() (interface{}, error)) *ResourceBuilder
- type ResourcesCapability
- type ResponseTransformer
- func (rt *ResponseTransformer) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
- func (rt *ResponseTransformer) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
- func (rt *ResponseTransformer) Name() string
- type RouteInspectorTool
- type RouteListResource
- type SSECapability
- type SSEClient
- type SSEManager
- type SSEMessage
- type SamplingCapability
- type Server
- func (srv *Server) AddMiddleware(route string, mw MiddlewareFunc)
- func (srv *Server) AddMiddlewareStack(route string, mw MiddlewareStack)
- func (srv *Server) Handle(pattern string, handlerFunc http.HandlerFunc)
- func (srv *Server) HandleFunc(pattern string, handler http.HandlerFunc)
- func (srv *Server) HandleFuncDynamic(pattern, tmplName string, dataFunc DataFunc) error
- func (srv *Server) HandleStatic(pattern string)
- func (srv *Server) HandleTemplate(pattern, t string, data interface{}) error
- func (srv *Server) MCPEnabled() bool
- func (srv *Server) RegisterDeveloperMCPTools()
- func (srv *Server) RegisterMCPExtension(ext MCPExtension) error
- func (srv *Server) RegisterMCPNamespace(name string, configs ...MCPNamespaceConfig) error
- func (srv *Server) RegisterMCPResource(resource MCPResource) error
- func (srv *Server) RegisterMCPResourceInNamespace(resource MCPResource, namespace string) error
- func (srv *Server) RegisterMCPTool(tool MCPTool) error
- func (srv *Server) RegisterMCPToolInNamespace(tool MCPTool, namespace string) error
- func (srv *Server) RegisterObservabilityMCPResources()
- func (srv *Server) Run() error
- func (srv *Server) Stop() error
- func (srv *Server) WebSocketUpgrader() *Upgrader
- func (srv *Server) WithOutStack(stack MiddlewareStack) error
- type ServerConfigResource
- func (r *ServerConfigResource) Description() string
- func (r *ServerConfigResource) List() ([]string, error)
- func (r *ServerConfigResource) MimeType() string
- func (r *ServerConfigResource) Name() string
- func (r *ServerConfigResource) Read() (interface{}, error)
- func (r *ServerConfigResource) URI() string
- type ServerControlTool
- type ServerHealthResource
- func (r *ServerHealthResource) Description() string
- func (r *ServerHealthResource) List() ([]string, error)
- func (r *ServerHealthResource) MimeType() string
- func (r *ServerHealthResource) Name() string
- func (r *ServerHealthResource) Read() (interface{}, error)
- func (r *ServerHealthResource) URI() string
- type ServerLogResource
- func (r *ServerLogResource) Description() string
- func (r *ServerLogResource) Enabled(ctx context.Context, level slog.Level) bool
- func (r *ServerLogResource) Handle(ctx context.Context, record slog.Record) error
- func (r *ServerLogResource) List() ([]string, error)
- func (r *ServerLogResource) MimeType() string
- func (r *ServerLogResource) Name() string
- func (r *ServerLogResource) Read() (interface{}, error)
- func (r *ServerLogResource) URI() string
- func (r *ServerLogResource) WithAttrs(attrs []slog.Attr) slog.Handler
- func (r *ServerLogResource) WithGroup(name string) slog.Handler
- type ServerOptionFunc
- func WithAddr(addr string) ServerOptionFunc
- func WithAuthTokenValidator(validator func(token string) (bool, error)) ServerOptionFunc
- func WithCSPWebWorkerSupport() ServerOptionFunc
- func WithDebugMode() ServerOptionFunc
- func WithEncryptedClientHello(echKeys ...[]byte) ServerOptionFunc
- func WithFIPSMode() ServerOptionFunc
- func WithHardenedMode() ServerOptionFunc
- func WithHealthServer() ServerOptionFunc
- func WithIdleTimeout(timeout time.Duration) ServerOptionFunc
- func WithLogger(l *slog.Logger) ServerOptionFunc
- func WithLoglevel(level slog.Level) ServerOptionFunc
- func WithMCPBuiltinResources(enabled bool) ServerOptionFunc
- func WithMCPBuiltinTools(enabled bool) ServerOptionFunc
- func WithMCPDiscoveryFilter(filter func(toolName string, r *http.Request) bool) ServerOptionFunc
- func WithMCPDiscoveryPolicy(policy DiscoveryPolicy) ServerOptionFunc
- func WithMCPEndpoint(endpoint string) ServerOptionFunc
- func WithMCPFileToolRoot(rootDir string) ServerOptionFunc
- func WithMCPNamespace(name string, configs ...MCPNamespaceConfig) ServerOptionFunc
- func WithMCPResourcesDisabled() ServerOptionFunc
- func WithMCPServerInfo(name, version string) ServerOptionFunc
- func WithMCPSupport(name, version string, configs ...MCPTransportConfig) ServerOptionFunc
- func WithMCPToolsDisabled() ServerOptionFunc
- func WithRateLimit(limit rateLimit, burst int) ServerOptionFunc
- func WithReadHeaderTimeout(timeout time.Duration) ServerOptionFunc
- func WithReadTimeout(timeout time.Duration) ServerOptionFunc
- func WithSuppressBanner(suppress bool) ServerOptionFunc
- func WithTLS(certFile, keyFile string) ServerOptionFunc
- func WithTemplateDir(dir string) ServerOptionFunc
- func WithTimeouts(readTimeout, writeTimeout, idleTimeout time.Duration) ServerOptionFunc
- func WithWriteTimeout(timeout time.Duration) ServerOptionFunc
- type ServerOptions
- type SimpleResource
- type SimpleTool
- type StreamingLogResource
- type SystemResource
- type ToolBuilder
- func (b *ToolBuilder) Build() MCPTool
- func (b *ToolBuilder) WithDescription(desc string) *ToolBuilder
- func (b *ToolBuilder) WithExecute(fn func(map[string]interface{}) (interface{}, error)) *ToolBuilder
- func (b *ToolBuilder) WithParameter(name, paramType, description string, required bool) *ToolBuilder
- type ToolsCapability
- type Upgrader
- type WebSocketPool
- func (p *WebSocketPool) Close(conn *Conn, reason error) error
- func (p *WebSocketPool) Get(ctx context.Context, endpoint string, upgrader *Upgrader, ...) (*Conn, error)
- func (p *WebSocketPool) GetStats() PoolStats
- func (p *WebSocketPool) Put(conn *Conn) error
- func (p *WebSocketPool) Shutdown(ctx context.Context) error
Constants ¶
const ( ErrorCodeParseError = -32700 ErrorCodeInvalidRequest = -32600 ErrorCodeMethodNotFound = -32601 ErrorCodeInvalidParams = -32602 ErrorCodeInternalError = -32603 )
Standard JSON-RPC error codes
const ( // LevelDebug enables debug-level logging with detailed information LevelDebug = slog.LevelDebug // LevelInfo enables info-level logging for general information LevelInfo = slog.LevelInfo // LevelWarn enables warning-level logging for important but non-critical events LevelWarn = slog.LevelWarn // LevelError enables error-level logging for error conditions only LevelError = slog.LevelError )
Log level constants for server configuration. These wrap slog levels to provide a consistent API while hiding the logging implementation details.
const ( TextMessage = ws.OpcodeText BinaryMessage = ws.OpcodeBinary CloseMessage = ws.OpcodeClose PingMessage = ws.OpcodePing PongMessage = ws.OpcodePong )
WebSocket message types
const ( CloseNormalClosure = ws.CloseNormalClosure CloseGoingAway = ws.CloseGoingAway CloseProtocolError = ws.CloseProtocolError CloseUnsupportedData = ws.CloseUnsupportedData CloseNoStatusReceived = ws.CloseNoStatusReceived CloseAbnormalClosure = ws.CloseAbnormalClosure CloseInvalidFramePayloadData = ws.CloseInvalidFramePayloadData ClosePolicyViolation = ws.ClosePolicyViolation CloseMessageTooBig = ws.CloseMessageTooBig CloseMandatoryExtension = ws.CloseMandatoryExtension CloseInternalServerError = ws.CloseInternalServerError CloseServiceRestart = ws.CloseServiceRestart CloseTryAgainLater = ws.CloseTryAgainLater CloseTLSHandshake = ws.CloseTLSHandshake )
WebSocket close codes
const GlobalMiddlewareRoute = "*"
GlobalMiddlewareRoute is a special route identifier that applies middleware to all routes. Use this constant when registering middleware that should run for every request.
const JSONRPCVersion = "2.0"
JSONRPCVersion is the JSON-RPC 2.0 version identifier
const (
MCPVersion = "2024-11-05"
)
MCP Protocol constants
Variables ¶
var ( Version = "dev" // Version from git tags BuildHash = "unknown" // Git commit hash BuildTime = "unknown" // Build timestamp )
Build information set at compile time using -ldflags
var ( ErrNotWebSocket = ws.ErrNotWebSocket ErrBadHandshake = ws.ErrBadHandshake )
WebSocket errors
Functions ¶
func EnsureTrailingSlash ¶
EnsureTrailingSlash ensures that a directory path ends with a trailing slash. This utility function is used to normalize directory paths for consistent handling.
func GetVersionInfo ¶
func GetVersionInfo() string
GetVersionInfo returns formatted version information
func HealthCheckHandler ¶
func HealthCheckHandler(w http.ResponseWriter, r *http.Request)
HealthCheckHandler returns a 204 No Content status code for basic health checks. This handler can be used as a simple liveness or readiness probe.
func IsCloseError ¶
IsCloseError returns true if the error is a close error with one of the specified codes
func IsUnexpectedCloseError ¶
IsUnexpectedCloseError checks if the error is an unexpected close error
func NewStdioTransport ¶
NewStdioTransport creates a new stdio transport
func NewStdioTransportWithIO ¶
NewStdioTransportWithIO creates a new stdio transport with custom IO
func PanicHandler ¶
func PanicHandler(w http.ResponseWriter, r *http.Request)
PanicHandler simulates a panic situation in a handler to test proper recovery middleware. This handler is intended for testing purposes only and should not be used in production.
func RecoveryMiddleware ¶
func RecoveryMiddleware(next http.Handler) http.HandlerFunc
RecoveryMiddleware returns a middleware function that recovers from panics in request handlers. Catches panics, logs the error, and returns a 500 Internal Server Error response.
func RequestLoggerMiddleware ¶
func RequestLoggerMiddleware(next http.Handler) http.HandlerFunc
RequestLoggerMiddleware returns a middleware function that logs structured request information. It captures and logs:
- Client IP address
- HTTP method and URL path
- Trace ID (if present in X-Trace-ID header)
- Response status code
- Request duration
- Response size in bytes
This middleware is included by default in NewServer(). For high-traffic applications, consider the performance impact of logging.
func ResponseTimeMiddleware ¶
func ResponseTimeMiddleware(next http.Handler) http.HandlerFunc
ResponseTimeMiddleware returns a middleware function that logs only the request duration. This is a lighter alternative to RequestLoggerMiddleware when only timing information is needed.
func TraceMiddleware ¶
func TraceMiddleware(next http.Handler) http.HandlerFunc
TraceMiddleware returns a middleware function that adds trace IDs to requests. Generates unique trace IDs for request tracking and distributed tracing.
Types ¶
type AuthTokenInjector ¶
type AuthTokenInjector struct {
// contains filtered or unexported fields
}
AuthTokenInjector adds authentication tokens to requests
func NewAuthTokenInjector ¶
func NewAuthTokenInjector(provider func(context.Context) (string, error)) *AuthTokenInjector
func (*AuthTokenInjector) InterceptRequest ¶
func (ati *AuthTokenInjector) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
func (*AuthTokenInjector) InterceptResponse ¶
func (ati *AuthTokenInjector) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
func (*AuthTokenInjector) Name ¶
func (ati *AuthTokenInjector) Name() string
type CalculatorTool ¶
type CalculatorTool struct{}
CalculatorTool implements MCPTool for basic mathematical operations
func NewCalculatorTool ¶
func NewCalculatorTool() *CalculatorTool
NewCalculatorTool creates a new calculator tool
func (*CalculatorTool) Description ¶
func (t *CalculatorTool) Description() string
func (*CalculatorTool) Execute ¶
func (t *CalculatorTool) Execute(params map[string]interface{}) (interface{}, error)
func (*CalculatorTool) Name ¶
func (t *CalculatorTool) Name() string
func (*CalculatorTool) Schema ¶
func (t *CalculatorTool) Schema() map[string]interface{}
type CapturedRequest ¶
type CapturedResponse ¶
type ConfigResource ¶
type ConfigResource struct {
// contains filtered or unexported fields
}
ConfigResource implements MCPResource for server configuration access
func NewConfigResource ¶
func NewConfigResource(options *ServerOptions) *ConfigResource
NewConfigResource creates a new configuration resource
func (*ConfigResource) Description ¶
func (r *ConfigResource) Description() string
func (*ConfigResource) List ¶
func (r *ConfigResource) List() ([]string, error)
func (*ConfigResource) MimeType ¶
func (r *ConfigResource) MimeType() string
func (*ConfigResource) Name ¶
func (r *ConfigResource) Name() string
func (*ConfigResource) Read ¶
func (r *ConfigResource) Read() (interface{}, error)
func (*ConfigResource) URI ¶
func (r *ConfigResource) URI() string
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn represents a WebSocket connection
func (*Conn) CloseHandler ¶
CloseHandler returns the current close handler
func (*Conn) PingHandler ¶
PingHandler returns the current ping handler
func (*Conn) PongHandler ¶
PongHandler returns the current pong handler
func (*Conn) ReadMessage ¶
ReadMessage reads a message from the WebSocket connection
func (*Conn) RemoteAddr ¶
RemoteAddr returns the remote network address
func (*Conn) SetCloseHandler ¶
SetCloseHandler sets the handler for close messages
func (*Conn) SetPingHandler ¶
SetPingHandler sets the handler for ping messages
func (*Conn) SetPongHandler ¶
SetPongHandler sets the handler for pong messages
func (*Conn) SetReadDeadline ¶
SetReadDeadline sets the read deadline on the connection
func (*Conn) SetWriteDeadline ¶
SetWriteDeadline sets the write deadline on the connection
func (*Conn) WriteControl ¶
WriteControl writes a control message with the given deadline
type DataFunc ¶
DataFunc is a function type that generates data for template rendering. It receives the current HTTP request and returns data to be passed to the template.
type DevGuideTool ¶
type DevGuideTool struct {
// contains filtered or unexported fields
}
DevGuideTool provides helpful information about available MCP tools
func (*DevGuideTool) Description ¶
func (t *DevGuideTool) Description() string
func (*DevGuideTool) Execute ¶
func (t *DevGuideTool) Execute(params map[string]interface{}) (interface{}, error)
func (*DevGuideTool) Name ¶
func (t *DevGuideTool) Name() string
func (*DevGuideTool) Schema ¶
func (t *DevGuideTool) Schema() map[string]interface{}
type DiscoveryPolicy ¶
type DiscoveryPolicy int
DiscoveryPolicy defines how MCP tools and resources are exposed in discovery endpoints
const ( // DiscoveryPublic shows all discoverable tools/resources (default) DiscoveryPublic DiscoveryPolicy = iota // DiscoveryCount only shows counts, not names DiscoveryCount // DiscoveryAuthenticated shows all if request has valid auth DiscoveryAuthenticated // DiscoveryNone hides all tool/resource information DiscoveryNone )
type FileReadTool ¶
type FileReadTool struct {
// contains filtered or unexported fields
}
FileReadTool implements MCPTool for reading files from the filesystem
func NewFileReadTool ¶
func NewFileReadTool(rootDir string) (*FileReadTool, error)
NewFileReadTool creates a new file read tool with optional root directory restriction
func (*FileReadTool) Description ¶
func (t *FileReadTool) Description() string
func (*FileReadTool) Execute ¶
func (t *FileReadTool) Execute(params map[string]interface{}) (interface{}, error)
func (*FileReadTool) Name ¶
func (t *FileReadTool) Name() string
func (*FileReadTool) Schema ¶
func (t *FileReadTool) Schema() map[string]interface{}
type HTTPRequestTool ¶
type HTTPRequestTool struct {
// contains filtered or unexported fields
}
HTTPRequestTool implements MCPTool for making HTTP requests
func NewHTTPRequestTool ¶
func NewHTTPRequestTool() *HTTPRequestTool
NewHTTPRequestTool creates a new HTTP request tool
func (*HTTPRequestTool) Description ¶
func (t *HTTPRequestTool) Description() string
func (*HTTPRequestTool) Execute ¶
func (t *HTTPRequestTool) Execute(params map[string]interface{}) (interface{}, error)
func (*HTTPRequestTool) Name ¶
func (t *HTTPRequestTool) Name() string
func (*HTTPRequestTool) Schema ¶
func (t *HTTPRequestTool) Schema() map[string]interface{}
type Header ¶
type Header struct {
// contains filtered or unexported fields
}
Header represents an HTTP header key-value pair used in middleware configuration.
type InterceptableRequest ¶
type InterceptableRequest struct {
*http.Request
// Metadata can be used to pass data between interceptors
Metadata map[string]interface{}
// contains filtered or unexported fields
}
InterceptableRequest wraps http.Request with additional functionality
func (*InterceptableRequest) GetBody ¶
func (ir *InterceptableRequest) GetBody() ([]byte, error)
GetBody reads and buffers the request body
func (*InterceptableRequest) SetBody ¶
func (ir *InterceptableRequest) SetBody(body []byte)
SetBody sets a new request body
type InterceptableResponse ¶
type InterceptableResponse struct {
http.ResponseWriter
// Response data that can be modified
StatusCode int
Headers http.Header
Body *bytes.Buffer
// Metadata from the request
Metadata map[string]interface{}
// contains filtered or unexported fields
}
InterceptableResponse wraps http.ResponseWriter with buffering capability
type Interceptor ¶
type Interceptor interface {
// InterceptRequest is called before the request is processed
// It can modify the request or return an early response
InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
// InterceptResponse is called after the response is generated
// It can modify the response before it's sent to the client
InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
// Name returns the name of the interceptor for debugging
Name() string
}
Interceptor defines the interface for request/response interceptors
type InterceptorChain ¶
type InterceptorChain struct {
// contains filtered or unexported fields
}
InterceptorChain manages a chain of request/response interceptors
func NewInterceptorChain ¶
func NewInterceptorChain() *InterceptorChain
NewInterceptorChain creates a new interceptor chain
func (*InterceptorChain) Add ¶
func (ic *InterceptorChain) Add(interceptor Interceptor)
Add adds an interceptor to the chain
func (*InterceptorChain) Remove ¶
func (ic *InterceptorChain) Remove(name string) bool
Remove removes an interceptor by name
func (*InterceptorChain) WrapHandler ¶
func (ic *InterceptorChain) WrapHandler(next http.Handler) http.Handler
WrapHandler wraps an http.Handler with the interceptor chain
type InterceptorResponse ¶
InterceptorResponse allows interceptors to return early responses
type JSONRPCEngine ¶
type JSONRPCEngine struct {
// contains filtered or unexported fields
}
JSONRPCEngine handles JSON-RPC 2.0 request processing
func NewJSONRPCEngine ¶
func NewJSONRPCEngine() *JSONRPCEngine
NewJSONRPCEngine creates a new JSON-RPC engine
func (*JSONRPCEngine) GetRegisteredMethods ¶
func (engine *JSONRPCEngine) GetRegisteredMethods() []string
GetRegisteredMethods returns a list of all registered method names
func (*JSONRPCEngine) ProcessRequest ¶
func (engine *JSONRPCEngine) ProcessRequest(requestData []byte) []byte
ProcessRequest processes a JSON-RPC request and returns a response
func (*JSONRPCEngine) ProcessRequestDirect ¶
func (engine *JSONRPCEngine) ProcessRequestDirect(request *JSONRPCRequest) *JSONRPCResponse
ProcessRequestDirect processes a JSON-RPC request object directly and returns a response object
func (*JSONRPCEngine) RegisterMethod ¶
func (engine *JSONRPCEngine) RegisterMethod(name string, handler JSONRPCMethodHandler)
RegisterMethod registers a method handler with the JSON-RPC engine
type JSONRPCError ¶
type JSONRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
JSONRPCError represents a JSON-RPC 2.0 error object
type JSONRPCMethodHandler ¶
type JSONRPCMethodHandler func(params interface{}) (interface{}, error)
JSONRPCMethodHandler defines the signature for JSON-RPC method handlers
type JSONRPCRequest ¶
type JSONRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params interface{} `json:"params,omitempty"`
ID interface{} `json:"id,omitempty"`
}
JSONRPCRequest represents a JSON-RPC 2.0 request message
type JSONRPCResponse ¶
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
Result interface{} `json:"result,omitempty"`
Error *JSONRPCError `json:"error,omitempty"`
ID interface{} `json:"id"`
}
JSONRPCResponse represents a JSON-RPC 2.0 response message
type ListDirectoryTool ¶
type ListDirectoryTool struct {
// contains filtered or unexported fields
}
ListDirectoryTool implements MCPTool for listing directory contents
func NewListDirectoryTool ¶
func NewListDirectoryTool(rootDir string) (*ListDirectoryTool, error)
NewListDirectoryTool creates a new directory listing tool
func (*ListDirectoryTool) Description ¶
func (t *ListDirectoryTool) Description() string
func (*ListDirectoryTool) Execute ¶
func (t *ListDirectoryTool) Execute(params map[string]interface{}) (interface{}, error)
func (*ListDirectoryTool) Name ¶
func (t *ListDirectoryTool) Name() string
func (*ListDirectoryTool) Schema ¶
func (t *ListDirectoryTool) Schema() map[string]interface{}
type LogResource ¶
type LogResource struct {
// contains filtered or unexported fields
}
LogResource implements MCPResource for recent log entries (if available)
func NewLogResource ¶
func NewLogResource(maxSize int) *LogResource
NewLogResource creates a new log resource with a maximum number of entries
func (*LogResource) AddLogEntry ¶
func (r *LogResource) AddLogEntry(entry string)
AddLogEntry adds a log entry to the resource (called by log handler if implemented)
func (*LogResource) Description ¶
func (r *LogResource) Description() string
func (*LogResource) List ¶
func (r *LogResource) List() ([]string, error)
func (*LogResource) MimeType ¶
func (r *LogResource) MimeType() string
func (*LogResource) Name ¶
func (r *LogResource) Name() string
func (*LogResource) Read ¶
func (r *LogResource) Read() (interface{}, error)
func (*LogResource) URI ¶
func (r *LogResource) URI() string
type LoggingCapability ¶
type LoggingCapability struct{}
LoggingCapability represents the server's logging capability.
type MCPCapabilities ¶
type MCPCapabilities struct {
Experimental map[string]interface{} `json:"experimental,omitempty"`
Logging *LoggingCapability `json:"logging,omitempty"`
Prompts *PromptsCapability `json:"prompts,omitempty"`
Resources *ResourcesCapability `json:"resources,omitempty"`
Tools *ToolsCapability `json:"tools,omitempty"`
Sampling *SamplingCapability `json:"sampling,omitempty"`
SSE *SSECapability `json:"sse,omitempty"`
}
MCPCapabilities represents the server's MCP capabilities
type MCPClientInfo ¶
MCPClientInfo represents MCP client information
type MCPDiscoveryInfo ¶
type MCPDiscoveryInfo struct {
Version string `json:"version"`
Transports []MCPTransportInfo `json:"transports"`
Endpoints map[string]string `json:"endpoints"`
Capabilities map[string]interface{} `json:"capabilities,omitempty"`
}
MCPDiscoveryInfo represents the discovery information for MCP endpoints
type MCPExtension ¶
type MCPExtension interface {
// Name returns the extension name (e.g., "e-commerce", "blog", "analytics")
Name() string
// Description returns a human-readable description
Description() string
// Tools returns the tools provided by this extension
Tools() []MCPTool
// Resources returns the resources provided by this extension
Resources() []MCPResource
// Configure is called with the server instance before registration
// This allows the extension to store server reference if needed
Configure(srv *Server) error
}
MCPExtension represents a collection of MCP tools and resources that can be registered as a group. This makes it easy for applications to package related functionality together.
func ExampleECommerceExtension ¶
func ExampleECommerceExtension() MCPExtension
Example: Creating a custom e-commerce extension
type MCPExtensionBuilder ¶
type MCPExtensionBuilder struct {
// contains filtered or unexported fields
}
MCPExtensionBuilder provides a fluent API for building MCP extensions
func NewMCPExtension ¶
func NewMCPExtension(name string) *MCPExtensionBuilder
NewMCPExtension creates a new extension builder
func (*MCPExtensionBuilder) Build ¶
func (b *MCPExtensionBuilder) Build() MCPExtension
func (*MCPExtensionBuilder) WithConfiguration ¶
func (b *MCPExtensionBuilder) WithConfiguration(fn func(*Server) error) *MCPExtensionBuilder
func (*MCPExtensionBuilder) WithDescription ¶
func (b *MCPExtensionBuilder) WithDescription(desc string) *MCPExtensionBuilder
func (*MCPExtensionBuilder) WithResource ¶
func (b *MCPExtensionBuilder) WithResource(resource MCPResource) *MCPExtensionBuilder
func (*MCPExtensionBuilder) WithTool ¶
func (b *MCPExtensionBuilder) WithTool(tool MCPTool) *MCPExtensionBuilder
type MCPHandler ¶
type MCPHandler struct {
// contains filtered or unexported fields
}
MCPHandler manages MCP protocol communication with multiple namespace support
func NewMCPHandler ¶
func NewMCPHandler(serverInfo MCPServerInfo) *MCPHandler
NewMCPHandler creates a new MCP handler instance
func (*MCPHandler) GetMetrics ¶
func (h *MCPHandler) GetMetrics() map[string]interface{}
GetMetrics returns the current MCP metrics summary
func (*MCPHandler) GetRegisteredResources ¶
func (h *MCPHandler) GetRegisteredResources() []string
GetRegisteredResources returns a list of all registered resource URIs
func (*MCPHandler) GetRegisteredTools ¶
func (h *MCPHandler) GetRegisteredTools() []string
GetRegisteredTools returns a list of all registered tool names
func (*MCPHandler) GetToolByName ¶
func (h *MCPHandler) GetToolByName(name string) (MCPTool, bool)
GetToolByName returns a tool by its name (for discovery filtering)
func (*MCPHandler) ProcessRequest ¶
func (h *MCPHandler) ProcessRequest(requestData []byte) []byte
ProcessRequest processes an MCP request
func (*MCPHandler) ProcessRequestWithTransport ¶
func (h *MCPHandler) ProcessRequestWithTransport(transport MCPTransport) error
ProcessRequestWithTransport processes an MCP request using the provided transport
func (*MCPHandler) RegisterNamespace ¶
func (h *MCPHandler) RegisterNamespace(name string, configs ...MCPNamespaceConfig) error
RegisterNamespace registers an entire namespace with its tools and resources
func (*MCPHandler) RegisterResource ¶
func (h *MCPHandler) RegisterResource(resource MCPResource)
RegisterResource registers an MCP resource without namespace prefixing (for simplicity)
func (*MCPHandler) RegisterResourceInNamespace ¶
func (h *MCPHandler) RegisterResourceInNamespace(resource MCPResource, namespace string)
RegisterResourceInNamespace registers an MCP resource in the specified namespace This always applies namespace prefixing
func (*MCPHandler) RegisterSSEClient ¶
func (h *MCPHandler) RegisterSSEClient(clientID string) chan *JSONRPCRequest
RegisterSSEClient registers a new SSE client for request routing
func (*MCPHandler) RegisterTool ¶
func (h *MCPHandler) RegisterTool(tool MCPTool)
RegisterTool registers an MCP tool without namespace prefixing (for simplicity)
func (*MCPHandler) RegisterToolInNamespace ¶
func (h *MCPHandler) RegisterToolInNamespace(tool MCPTool, namespace string)
RegisterToolInNamespace registers an MCP tool in the specified namespace This always applies namespace prefixing
func (*MCPHandler) RunStdioLoop ¶
func (h *MCPHandler) RunStdioLoop() error
RunStdioLoop runs the MCP handler in stdio mode The loop continues processing requests until EOF is received on stdin. EOF is treated as a normal shutdown signal (e.g., when stdin is closed). This behavior is appropriate for stdio servers which typically run for the lifetime of the parent process.
func (*MCPHandler) SendSSENotification ¶
func (h *MCPHandler) SendSSENotification(clientID string, method string, params interface{}) error
SendSSENotification sends a notification to a specific SSE client
func (*MCPHandler) ServeHTTP ¶
func (h *MCPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface for MCP
func (*MCPHandler) UnregisterSSEClient ¶
func (h *MCPHandler) UnregisterSSEClient(clientID string)
UnregisterSSEClient removes an SSE client
type MCPInitializeParams ¶
type MCPInitializeParams struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities interface{} `json:"capabilities"`
ClientInfo MCPClientInfo `json:"clientInfo"`
}
MCPInitializeParams represents the parameters for the initialize method
type MCPInitializeResult ¶
type MCPInitializeResult struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities MCPCapabilities `json:"capabilities"`
ServerInfo MCPServerInfo `json:"serverInfo"`
}
MCPInitializeResult represents the result of the initialize method
type MCPMetrics ¶
type MCPMetrics struct {
// contains filtered or unexported fields
}
MCPMetrics tracks performance metrics for MCP operations
func (*MCPMetrics) GetMetricsSummary ¶
func (m *MCPMetrics) GetMetricsSummary() map[string]interface{}
GetMetricsSummary returns a summary of collected metrics
type MCPNamespace ¶
type MCPNamespace struct {
Name string
Tools []MCPTool
Resources []MCPResource
}
MCPNamespace represents a named collection of MCP tools and resources
type MCPNamespaceConfig ¶
type MCPNamespaceConfig func(*MCPNamespace)
MCPNamespaceConfig is a function that configures namespace options
func WithNamespaceResources ¶
func WithNamespaceResources(resources ...MCPResource) MCPNamespaceConfig
WithNamespaceResources adds resources to a namespace
func WithNamespaceTools ¶
func WithNamespaceTools(tools ...MCPTool) MCPNamespaceConfig
WithNamespaceTools adds tools to a namespace
type MCPResource ¶
type MCPResource interface {
URI() string
Name() string
Description() string
MimeType() string
Read() (interface{}, error)
List() ([]string, error)
}
MCPResource defines the interface for Model Context Protocol resources.
type MCPResourceContent ¶
type MCPResourceContent struct {
URI string `json:"uri"`
MimeType string `json:"mimeType"`
Text interface{} `json:"text"`
}
MCPResourceContent represents the content of a resource
type MCPResourceInfo ¶
type MCPResourceInfo struct {
URI string `json:"uri"`
Name string `json:"name"`
Description string `json:"description"`
MimeType string `json:"mimeType"`
}
MCPResourceInfo represents information about a resource
type MCPResourceReadParams ¶
type MCPResourceReadParams struct {
URI string `json:"uri"`
}
MCPResourceReadParams represents the parameters for reading a resource
type MCPServerInfo ¶
MCPServerInfo represents MCP server information
type MCPTool ¶
type MCPTool interface {
Name() string
Description() string
Schema() map[string]interface{}
Execute(params map[string]interface{}) (interface{}, error)
}
MCPTool defines the interface for Model Context Protocol tools.
type MCPToolCallParams ¶
type MCPToolCallParams struct {
Name string `json:"name"`
Arguments map[string]interface{} `json:"arguments"`
}
MCPToolCallParams represents the parameters for calling a tool
type MCPToolInfo ¶
type MCPToolInfo struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema map[string]interface{} `json:"inputSchema"`
}
MCPToolInfo represents information about a tool
type MCPToolResult ¶
type MCPToolResult struct {
Content []map[string]interface{} `json:"content"`
}
MCPToolResult represents the result of a tool execution
type MCPToolWithContext ¶
type MCPToolWithContext interface {
MCPTool
ExecuteWithContext(ctx context.Context, params map[string]interface{}) (interface{}, error)
}
MCPToolWithContext is an enhanced interface that supports context for cancellation and timeouts
type MCPTransport ¶
type MCPTransport interface {
// Send sends a JSON-RPC response message
Send(response *JSONRPCResponse) error
// Receive receives a JSON-RPC request message
Receive() (*JSONRPCRequest, error)
// Close closes the transport
Close() error
}
MCPTransport defines the interface for MCP communication transports
type MCPTransportConfig ¶
type MCPTransportConfig func(*mcpTransportOptions)
MCPTransportConfig is a function that configures MCP transport options
func MCPDev ¶
func MCPDev() MCPTransportConfig
MCPDev configures MCP with developer tools for local development. This configuration is designed for AI-assisted development with Claude Code.
⚠️ SECURITY WARNING: Only use in development environments! Enables powerful tools that can restart your server and modify its behavior.
Tools provided:
- mcp__hyperserve__server_control: Restart server, reload config, change log levels, get status
- mcp__hyperserve__route_inspector: List all registered routes and their middleware
- mcp__hyperserve__request_debugger: Capture and replay HTTP requests for debugging
Resources provided:
- logs://server/stream: Real-time log streaming
- routes://server/all: All registered routes with metadata
- requests://debug/recent: Recent requests with full details
Example:
srv, _ := hyperserve.NewServer(
hyperserve.WithMCPSupport("DevServer", "1.0.0", hyperserve.MCPDev()),
)
func MCPObservability ¶
func MCPObservability() MCPTransportConfig
MCPObservability configures MCP with observability resources for production use. This configuration provides read-only access to system state without any dangerous operations: - config://server/current - Server configuration (sanitized, no secrets) - health://server/status - Health metrics and uptime - logs://server/recent - Recent log entries (circular buffer)
Safe for production use - provides observability without control plane access.
Example:
srv, _ := hyperserve.NewServer(
hyperserve.WithMCPSupport("MyApp", "1.0.0", hyperserve.MCPObservability()),
)
func MCPOverHTTP ¶
func MCPOverHTTP(endpoint string) MCPTransportConfig
MCPOverHTTP configures MCP to use HTTP transport with the specified endpoint
func MCPOverSSE ¶
func MCPOverSSE(endpoint string) MCPTransportConfig
MCPOverSSE configures MCP to use SSE transport
func MCPOverStdio ¶
func MCPOverStdio() MCPTransportConfig
MCPOverStdio configures MCP to use stdio transport
type MCPTransportInfo ¶
type MCPTransportInfo struct {
Type string `json:"type"`
Endpoint string `json:"endpoint"`
Description string `json:"description"`
Headers map[string]string `json:"headers,omitempty"`
}
MCPTransportInfo describes available transport mechanisms
type MCPTransportType ¶
type MCPTransportType int
MCPTransportType represents the type of transport for MCP communication
const ( // HTTPTransport represents HTTP-based MCP communication HTTPTransport MCPTransportType = iota // StdioTransport represents stdio-based MCP communication StdioTransport )
type MetricsResource ¶
type MetricsResource struct {
// contains filtered or unexported fields
}
MetricsResource implements MCPResource for server metrics access
func NewMetricsResource ¶
func NewMetricsResource(server *Server) *MetricsResource
NewMetricsResource creates a new metrics resource
func (*MetricsResource) Description ¶
func (r *MetricsResource) Description() string
func (*MetricsResource) List ¶
func (r *MetricsResource) List() ([]string, error)
func (*MetricsResource) MimeType ¶
func (r *MetricsResource) MimeType() string
func (*MetricsResource) Name ¶
func (r *MetricsResource) Name() string
func (*MetricsResource) Read ¶
func (r *MetricsResource) Read() (interface{}, error)
func (*MetricsResource) URI ¶
func (r *MetricsResource) URI() string
type MiddlewareFunc ¶
type MiddlewareFunc func(http.Handler) http.HandlerFunc
MiddlewareFunc is a function type that wraps an http.Handler and returns a new http.HandlerFunc. This is the standard pattern for HTTP middleware in Go.
func AuthMiddleware ¶
func AuthMiddleware(options *ServerOptions) MiddlewareFunc
AuthMiddleware returns a middleware function that validates bearer tokens in the Authorization header. Requires requests to include a valid Bearer token, otherwise returns 401 Unauthorized.
func ChaosMiddleware ¶
func ChaosMiddleware(options *ServerOptions) MiddlewareFunc
ChaosMiddleware returns a middleware handler that simulates random failures for chaos engineering. When chaos mode is enabled, can inject random latency, errors, throttling, and panics. Useful for testing application resilience and error handling.
func HeadersMiddleware ¶
func HeadersMiddleware(options *ServerOptions) MiddlewareFunc
HeadersMiddleware returns a middleware function that adds security headers to responses. Includes headers for XSS protection, content type sniffing prevention, HSTS, CSP, and CORS. Automatically handles CORS preflight requests.
func MetricsMiddleware ¶
func MetricsMiddleware(srv *Server) MiddlewareFunc
MetricsMiddleware returns a middleware function that collects request metrics. It tracks total request count and response times for performance monitoring.
func RateLimitMiddleware ¶
func RateLimitMiddleware(srv *Server) MiddlewareFunc
RateLimitMiddleware returns a middleware function that enforces rate limiting per client IP address. Uses token bucket algorithm with configurable rate limit and burst capacity. Returns 429 Too Many Requests when rate limit is exceeded. Optimized for Go 1.24's Swiss Tables map implementation.
func RequestCaptureMiddleware ¶
func RequestCaptureMiddleware(debuggerTool *RequestDebuggerTool) MiddlewareFunc
RequestCaptureMiddleware creates middleware that captures HTTP requests for debugging
type MiddlewareRegistry ¶
type MiddlewareRegistry struct {
// contains filtered or unexported fields
}
MiddlewareRegistry manages middleware stacks for different routes. It allows route-specific middleware configuration and supports exclusion of specific middleware.
func NewMiddlewareRegistry ¶
func NewMiddlewareRegistry(globalMiddleware MiddlewareStack) *MiddlewareRegistry
NewMiddlewareRegistry creates a new MiddlewareRegistry with optional global middleware. If globalMiddleware is provided, it will be applied to all routes by default.
func (*MiddlewareRegistry) Add ¶
func (mwr *MiddlewareRegistry) Add(route string, middleware MiddlewareStack)
Add registers a MiddlewareStack for a specific route in the registry. Use GlobalMiddlewareRoute ("*") to apply middleware to all routes.
func (*MiddlewareRegistry) Get ¶
func (mwr *MiddlewareRegistry) Get(route string) MiddlewareStack
Get retrieves the MiddlewareStack for a specific route. Returns an empty MiddlewareStack if no middleware is registered for the route.
func (*MiddlewareRegistry) RemoveStack ¶
func (mwr *MiddlewareRegistry) RemoveStack(route string)
RemoveStack removes all middleware for a specific route from the registry. Does nothing if no middleware is registered for the route.
type MiddlewareStack ¶
type MiddlewareStack []MiddlewareFunc
MiddlewareStack is a collection of middleware functions that can be applied to an http.Handler. Middleware in the stack is applied in order, with the first middleware being the outermost.
func DefaultMiddleware ¶
func DefaultMiddleware(server *Server) MiddlewareStack
DefaultMiddleware returns a predefined middleware stack with essential server functionality. Includes metrics collection, request logging, and panic recovery. This middleware is applied by default unless explicitly excluded.
func FileServer ¶
func FileServer(options *ServerOptions) MiddlewareStack
FileServer returns a middleware stack optimized for serving static files. Includes appropriate security headers for file serving.
func SecureAPI ¶
func SecureAPI(srv *Server) MiddlewareStack
SecureAPI returns a middleware stack configured for secure API endpoints. Includes authentication and rate limiting middleware.
func SecureWeb ¶
func SecureWeb(options *ServerOptions) MiddlewareStack
SecureWeb returns a middleware stack configured for secure web endpoints. Includes security headers middleware for web applications.
type PoolConfig ¶
type PoolConfig struct {
// MaxConnectionsPerEndpoint is the maximum number of connections per endpoint
MaxConnectionsPerEndpoint int
// MaxIdleConnections is the maximum number of idle connections per endpoint
MaxIdleConnections int
// IdleTimeout is how long a connection can be idle before being closed
IdleTimeout time.Duration
// HealthCheckInterval is how often to ping connections to check health
HealthCheckInterval time.Duration
// ConnectionTimeout is the timeout for establishing new connections
ConnectionTimeout time.Duration
// EnableCompression enables WebSocket compression
EnableCompression bool
// OnConnectionCreated is called when a new connection is created
OnConnectionCreated func(endpoint string, conn *Conn)
// OnConnectionClosed is called when a connection is closed
OnConnectionClosed func(endpoint string, conn *Conn, reason error)
}
PoolConfig configures the WebSocket connection pool
func DefaultPoolConfig ¶
func DefaultPoolConfig() PoolConfig
DefaultPoolConfig returns a default pool configuration
type PoolStats ¶
type PoolStats struct {
TotalConnections atomic.Int64
ActiveConnections atomic.Int64
IdleConnections atomic.Int64
FailedConnections atomic.Int64
ConnectionsCreated atomic.Int64
ConnectionsReused atomic.Int64
HealthChecksFailed atomic.Int64
}
PoolStats tracks pool statistics
type PromptsCapability ¶
type PromptsCapability struct{}
PromptsCapability represents the server's prompt handling capability.
type RateLimitInterceptor ¶
type RateLimitInterceptor struct {
// contains filtered or unexported fields
}
RateLimitInterceptor enforces rate limits per client
func NewRateLimitInterceptor ¶
func NewRateLimitInterceptor(limiter RateLimiter) *RateLimitInterceptor
func (*RateLimitInterceptor) InterceptRequest ¶
func (rli *RateLimitInterceptor) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
func (*RateLimitInterceptor) InterceptResponse ¶
func (rli *RateLimitInterceptor) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
func (*RateLimitInterceptor) Name ¶
func (rli *RateLimitInterceptor) Name() string
type RateLimiter ¶
RateLimiter interface for rate limiting
type RequestDebuggerTool ¶
type RequestDebuggerTool struct {
// contains filtered or unexported fields
}
RequestDebuggerTool captures and allows replay of requests
func (*RequestDebuggerTool) CaptureRequest ¶
func (t *RequestDebuggerTool) CaptureRequest(r *http.Request, responseHeaders map[string][]string, statusCode int, responseBody string)
CaptureRequest captures an HTTP request and stores it in the debug tool
func (*RequestDebuggerTool) Description ¶
func (t *RequestDebuggerTool) Description() string
func (*RequestDebuggerTool) Execute ¶
func (t *RequestDebuggerTool) Execute(params map[string]interface{}) (interface{}, error)
func (*RequestDebuggerTool) Name ¶
func (t *RequestDebuggerTool) Name() string
func (*RequestDebuggerTool) Schema ¶
func (t *RequestDebuggerTool) Schema() map[string]interface{}
type RequestLogger ¶
type RequestLogger struct {
// contains filtered or unexported fields
}
RequestLogger logs all requests and responses
func NewRequestLogger ¶
func NewRequestLogger(logger func(format string, args ...interface{})) *RequestLogger
func (*RequestLogger) InterceptRequest ¶
func (rl *RequestLogger) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
func (*RequestLogger) InterceptResponse ¶
func (rl *RequestLogger) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
func (*RequestLogger) Name ¶
func (rl *RequestLogger) Name() string
type ResourceBuilder ¶
type ResourceBuilder struct {
// contains filtered or unexported fields
}
ResourceBuilder provides a fluent API for building resources
func NewResource ¶
func NewResource(uri string) *ResourceBuilder
NewResource creates a new resource builder
func (*ResourceBuilder) Build ¶
func (b *ResourceBuilder) Build() MCPResource
func (*ResourceBuilder) WithDescription ¶
func (b *ResourceBuilder) WithDescription(desc string) *ResourceBuilder
func (*ResourceBuilder) WithMimeType ¶
func (b *ResourceBuilder) WithMimeType(mimeType string) *ResourceBuilder
func (*ResourceBuilder) WithName ¶
func (b *ResourceBuilder) WithName(name string) *ResourceBuilder
func (*ResourceBuilder) WithRead ¶
func (b *ResourceBuilder) WithRead(fn func() (interface{}, error)) *ResourceBuilder
type ResourcesCapability ¶
type ResourcesCapability struct {
Subscribe bool `json:"subscribe,omitempty"`
ListChanged bool `json:"listChanged,omitempty"`
}
ResourcesCapability represents the server's resource management capabilities.
type ResponseTransformer ¶
type ResponseTransformer struct {
// contains filtered or unexported fields
}
ResponseTransformer modifies response bodies
func NewResponseTransformer ¶
func NewResponseTransformer(transformer func([]byte, string) ([]byte, error)) *ResponseTransformer
func (*ResponseTransformer) InterceptRequest ¶
func (rt *ResponseTransformer) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
func (*ResponseTransformer) InterceptResponse ¶
func (rt *ResponseTransformer) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
func (*ResponseTransformer) Name ¶
func (rt *ResponseTransformer) Name() string
type RouteInspectorTool ¶
type RouteInspectorTool struct {
// contains filtered or unexported fields
}
RouteInspectorTool provides route introspection for development
func (*RouteInspectorTool) Description ¶
func (t *RouteInspectorTool) Description() string
func (*RouteInspectorTool) Execute ¶
func (t *RouteInspectorTool) Execute(params map[string]interface{}) (interface{}, error)
func (*RouteInspectorTool) Name ¶
func (t *RouteInspectorTool) Name() string
func (*RouteInspectorTool) Schema ¶
func (t *RouteInspectorTool) Schema() map[string]interface{}
type RouteListResource ¶
type RouteListResource struct {
// contains filtered or unexported fields
}
RouteListResource provides detailed route information
func (*RouteListResource) Description ¶
func (r *RouteListResource) Description() string
func (*RouteListResource) List ¶
func (r *RouteListResource) List() ([]string, error)
func (*RouteListResource) MimeType ¶
func (r *RouteListResource) MimeType() string
func (*RouteListResource) Name ¶
func (r *RouteListResource) Name() string
func (*RouteListResource) Read ¶
func (r *RouteListResource) Read() (interface{}, error)
func (*RouteListResource) URI ¶
func (r *RouteListResource) URI() string
type SSECapability ¶
type SSECapability struct {
Enabled bool `json:"enabled"`
Endpoint string `json:"endpoint"`
HeaderRouting bool `json:"headerRouting"`
}
SSECapability represents the server's Server-Sent Events capability.
type SSEClient ¶
type SSEClient struct {
// contains filtered or unexported fields
}
SSEClient represents a connected SSE client
func (*SSEClient) Send ¶
func (c *SSEClient) Send(response *JSONRPCResponse) (err error)
Send sends a JSON-RPC response to the SSE client
func (*SSEClient) SetInitialized ¶
func (c *SSEClient) SetInitialized()
SetInitialized marks the client as initialized
type SSEManager ¶
type SSEManager struct {
// contains filtered or unexported fields
}
SSEManager manages SSE connections for MCP
func NewSSEManager ¶
func NewSSEManager() *SSEManager
NewSSEManager creates a new SSE connection manager
func (*SSEManager) BroadcastToAll ¶
func (m *SSEManager) BroadcastToAll(response *JSONRPCResponse)
BroadcastToAll sends a response to all connected SSE clients
func (*SSEManager) GetClientCount ¶
func (m *SSEManager) GetClientCount() int
GetClientCount returns the number of connected SSE clients
func (*SSEManager) HandleSSE ¶
func (m *SSEManager) HandleSSE(w http.ResponseWriter, r *http.Request, mcpHandler *MCPHandler)
HandleSSE handles SSE connections for MCP
func (*SSEManager) SendToClient ¶
func (m *SSEManager) SendToClient(clientID string, response *JSONRPCResponse) error
SendToClient sends a response to a specific SSE client
type SSEMessage ¶
type SSEMessage struct {
Event string `json:"event"` // Optional: Allows sending multiple event types
Data any `json:"data"` // The actual data payload
}
SSEMessage represents a Server-Sent Events message with an optional event type and data payload. It follows the SSE format with event and data fields that can be sent to clients.
func NewSSEMessage ¶
func NewSSEMessage(data any) *SSEMessage
NewSSEMessage creates a new SSE message with the given data and a default "message" event type. This is a convenience function for creating standard SSE messages.
func (*SSEMessage) String ¶
func (sse *SSEMessage) String() string
String formats the SSE message according to the Server-Sent Events specification. Returns a string in the format "event: <event>\ndata: <data>\n\n".
type SamplingCapability ¶
type SamplingCapability struct{}
SamplingCapability represents the server's sampling capability.
type Server ¶
type Server struct {
Options *ServerOptions
// contains filtered or unexported fields
}
Server represents an HTTP server with built-in middleware support, health checks, template rendering, and various configuration options.
The Server manages both the main HTTP server and an optional health check server. It handles graceful shutdown, request metrics, and can be extended with custom middleware.
Example:
srv, _ := hyperserve.NewServer(
hyperserve.WithAddr(":8080"),
hyperserve.WithHealthServer(),
)
srv.HandleFunc("/api/users", handleUsers)
srv.Run()
func NewServer ¶
func NewServer(opts ...ServerOptionFunc) (*Server, error)
NewServer creates a new instance of the Server with the given options. By default, the server includes request logging, panic recovery, and metrics collection middleware. The server will listen on ":8080" unless configured otherwise.
Options can be provided to customize the server behavior:
srv, err := hyperserve.NewServer(
hyperserve.WithAddr(":3000"),
hyperserve.WithHealthServer(), // Enable health checks on :8081
hyperserve.WithTLS("cert.pem", "key.pem"), // Enable HTTPS
hyperserve.WithRateLimit(100, 200), // 100 req/s, burst of 200
)
Returns an error if any of the options fail to apply.
func (*Server) AddMiddleware ¶
func (srv *Server) AddMiddleware(route string, mw MiddlewareFunc)
AddMiddleware adds a single middleware function to the specified route. Use "*" as the route to apply middleware globally to all routes.
func (*Server) AddMiddlewareStack ¶
func (srv *Server) AddMiddlewareStack(route string, mw MiddlewareStack)
AddMiddlewareStack adds a collection of middleware functions to the specified route. The middleware stack is applied in the order provided.
func (*Server) Handle ¶
func (srv *Server) Handle(pattern string, handlerFunc http.HandlerFunc)
Handle registers the handler function for the given pattern. This is a wrapper around http.ServeMux.Handle that integrates with the server's middleware system. Example usage:
srv.Handle("/static", http.FileServer(http.Dir("./static")))
func (*Server) HandleFunc ¶
func (srv *Server) HandleFunc(pattern string, handler http.HandlerFunc)
HandleFunc registers the handler function for the given pattern. The pattern follows the standard net/http ServeMux patterns:
- "/path" matches exactly
- "/path/" matches the path and any subpaths
- Patterns are matched in order of specificity
Registered handlers automatically benefit from any global middleware (logging, recovery, metrics) plus any route-specific middleware.
Example:
srv.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
users := getUsersFromDB()
json.NewEncoder(w).Encode(users)
})
srv.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "OK")
})
func (*Server) HandleFuncDynamic ¶
HandleFuncDynamic registers a handler that renders templates with dynamic data. The dataFunc is called for each request to generate the data passed to the template. Returns an error if template parsing fails.
func (*Server) HandleStatic ¶
HandleStatic registers a handler for serving static files from the configured static directory. The pattern should typically end with a wildcard (e.g., "/static/"). Uses os.Root for secure file access when available (Go 1.24+).
func (*Server) HandleTemplate ¶
HandleTemplate registers a handler that renders a specific template with static data. Unlike HandleFuncDynamic, the data is provided once at registration time. Returns an error if template parsing fails.
func (*Server) MCPEnabled ¶
MCPEnabled returns true if MCP support is enabled
func (*Server) RegisterDeveloperMCPTools ¶
func (srv *Server) RegisterDeveloperMCPTools()
RegisterDeveloperMCPTools registers all developer tools
func (*Server) RegisterMCPExtension ¶
func (srv *Server) RegisterMCPExtension(ext MCPExtension) error
RegisterMCPExtension registers all tools and resources from an extension
func (*Server) RegisterMCPNamespace ¶
func (srv *Server) RegisterMCPNamespace(name string, configs ...MCPNamespaceConfig) error
RegisterMCPNamespace registers an entire MCP namespace with its tools and resources This must be called after server creation but before Run()
func (*Server) RegisterMCPResource ¶
func (srv *Server) RegisterMCPResource(resource MCPResource) error
RegisterMCPResource registers a custom MCP resource This must be called after server creation but before Run()
func (*Server) RegisterMCPResourceInNamespace ¶
func (srv *Server) RegisterMCPResourceInNamespace(resource MCPResource, namespace string) error
RegisterMCPResourceInNamespace registers a custom MCP resource in the specified namespace This must be called after server creation but before Run()
func (*Server) RegisterMCPTool ¶
RegisterMCPTool registers a custom MCP tool This must be called after server creation but before Run()
func (*Server) RegisterMCPToolInNamespace ¶
RegisterMCPToolInNamespace registers a custom MCP tool in the specified namespace This must be called after server creation but before Run()
func (*Server) RegisterObservabilityMCPResources ¶
func (srv *Server) RegisterObservabilityMCPResources()
RegisterObservabilityMCPResources registers minimal observability resources for production monitoring
func (*Server) Run ¶
Run starts the server and blocks until a shutdown signal is received. It automatically:
- Starts the main HTTP/HTTPS server
- Starts the health check server (if enabled)
- Sets up graceful shutdown on SIGINT/SIGTERM
- Handles cleanup of resources
- Waits for active requests to complete before shutting down
The method will block until the server is shut down, either by signal or error. Returns an error if the server fails to start or encounters a fatal error.
Example:
if err := srv.Run(); err != nil {
log.Fatal("Server failed:", err)
}
func (*Server) WebSocketUpgrader ¶
WebSocketUpgrader returns a WebSocket upgrader that tracks connections in server telemetry. Use this instead of creating a standalone Upgrader to ensure WebSocket connections are counted in the server's request metrics.
func (*Server) WithOutStack ¶
func (srv *Server) WithOutStack(stack MiddlewareStack) error
type ServerConfigResource ¶
type ServerConfigResource struct {
// contains filtered or unexported fields
}
ServerConfigResource provides access to the current server configuration
func NewServerConfigResource ¶
func NewServerConfigResource(srv *Server) *ServerConfigResource
NewServerConfigResource creates a new server configuration resource
func (*ServerConfigResource) Description ¶
func (r *ServerConfigResource) Description() string
Description returns the resource description.
func (*ServerConfigResource) List ¶
func (r *ServerConfigResource) List() ([]string, error)
List returns the available resource URIs.
func (*ServerConfigResource) MimeType ¶
func (r *ServerConfigResource) MimeType() string
MimeType returns the resource MIME type.
func (*ServerConfigResource) Name ¶
func (r *ServerConfigResource) Name() string
Name returns the resource name.
func (*ServerConfigResource) Read ¶
func (r *ServerConfigResource) Read() (interface{}, error)
Read returns the current server configuration.
func (*ServerConfigResource) URI ¶
func (r *ServerConfigResource) URI() string
URI returns the resource URI.
type ServerControlTool ¶
type ServerControlTool struct {
// contains filtered or unexported fields
}
ServerControlTool provides server lifecycle management for development
func (*ServerControlTool) Description ¶
func (t *ServerControlTool) Description() string
func (*ServerControlTool) Execute ¶
func (t *ServerControlTool) Execute(params map[string]interface{}) (interface{}, error)
func (*ServerControlTool) Name ¶
func (t *ServerControlTool) Name() string
func (*ServerControlTool) Schema ¶
func (t *ServerControlTool) Schema() map[string]interface{}
type ServerHealthResource ¶
type ServerHealthResource struct {
// contains filtered or unexported fields
}
ServerHealthResource provides access to server health status
func NewServerHealthResource ¶
func NewServerHealthResource(srv *Server) *ServerHealthResource
NewServerHealthResource creates a new server health resource
func (*ServerHealthResource) Description ¶
func (r *ServerHealthResource) Description() string
Description returns the resource description.
func (*ServerHealthResource) List ¶
func (r *ServerHealthResource) List() ([]string, error)
List returns the available resource URIs.
func (*ServerHealthResource) MimeType ¶
func (r *ServerHealthResource) MimeType() string
MimeType returns the resource MIME type.
func (*ServerHealthResource) Name ¶
func (r *ServerHealthResource) Name() string
Name returns the resource name.
func (*ServerHealthResource) Read ¶
func (r *ServerHealthResource) Read() (interface{}, error)
Read returns the current server health status.
func (*ServerHealthResource) URI ¶
func (r *ServerHealthResource) URI() string
URI returns the resource URI.
type ServerLogResource ¶
type ServerLogResource struct {
// contains filtered or unexported fields
}
ServerLogResource provides access to recent server logs
func NewServerLogResource ¶
func NewServerLogResource(maxSize int) *ServerLogResource
NewServerLogResource creates a new server log resource
func (*ServerLogResource) Description ¶
func (r *ServerLogResource) Description() string
Description returns the resource description.
func (*ServerLogResource) List ¶
func (r *ServerLogResource) List() ([]string, error)
List returns the available resource URIs.
func (*ServerLogResource) MimeType ¶
func (r *ServerLogResource) MimeType() string
MimeType returns the resource MIME type.
func (*ServerLogResource) Name ¶
func (r *ServerLogResource) Name() string
Name returns the resource name.
func (*ServerLogResource) Read ¶
func (r *ServerLogResource) Read() (interface{}, error)
Read returns the recent server logs.
func (*ServerLogResource) URI ¶
func (r *ServerLogResource) URI() string
URI returns the resource URI.
type ServerOptionFunc ¶
ServerOptionFunc is a function type used to configure Server instances. It follows the functional options pattern for flexible server configuration.
func WithAddr ¶
func WithAddr(addr string) ServerOptionFunc
WithAddr sets the address and port for the server to listen on. The address must be in the format "host:port" (e.g., ":8080", "localhost:3000").
func WithAuthTokenValidator ¶
func WithAuthTokenValidator(validator func(token string) (bool, error)) ServerOptionFunc
WithAuthTokenValidator sets the token validator for the server.
func WithCSPWebWorkerSupport ¶
func WithCSPWebWorkerSupport() ServerOptionFunc
WithCSPWebWorkerSupport enables Content Security Policy support for Web Workers using blob: URLs. This is required for modern web applications that use libraries like Tone.js, PDF.js, or other libraries that create Web Workers with blob: URLs for performance optimization. By default, this is disabled for security reasons and must be explicitly enabled.
func WithDebugMode ¶
func WithDebugMode() ServerOptionFunc
WithDebugMode enables debug logging and additional debug features. This is equivalent to WithLoglevel(LevelDebug) plus additional debug information.
func WithEncryptedClientHello ¶
func WithEncryptedClientHello(echKeys ...[]byte) ServerOptionFunc
WithEncryptedClientHello enables Encrypted Client Hello (ECH) for enhanced privacy. ECH encrypts the SNI in TLS handshakes to prevent eavesdropping on the server name.
func WithFIPSMode ¶
func WithFIPSMode() ServerOptionFunc
WithFIPSMode enables FIPS 140-3 compliant mode for government and enterprise deployments. This restricts TLS cipher suites and curves to FIPS-approved algorithms only.
func WithHardenedMode ¶
func WithHardenedMode() ServerOptionFunc
WithHardenedMode enables hardened security mode for enhanced security headers. In hardened mode, the server header is suppressed and additional security measures are applied.
func WithHealthServer ¶
func WithHealthServer() ServerOptionFunc
WithHealthServer enables the health server on a separate port. The health server provides /healthz/, /readyz/, and /livez/ endpoints for monitoring.
func WithIdleTimeout ¶
func WithIdleTimeout(timeout time.Duration) ServerOptionFunc
WithIdleTimeout sets the maximum time to wait for the next request when keep-alives are enabled.
func WithLogger ¶
func WithLogger(l *slog.Logger) ServerOptionFunc
WithLogger replaces the default logger with a custom slog.Logger instance. This allows for custom log formatting, output destinations, and log levels.
func WithLoglevel ¶
func WithLoglevel(level slog.Level) ServerOptionFunc
WithLoglevel sets the global log level for the server. Accepts slog.Level values (LevelDebug, LevelInfo, LevelWarn, LevelError).
func WithMCPBuiltinResources ¶
func WithMCPBuiltinResources(enabled bool) ServerOptionFunc
WithMCPBuiltinResources enables the built-in MCP resources (config, metrics, system info, logs) By default, built-in resources are disabled and must be explicitly enabled
func WithMCPBuiltinTools ¶
func WithMCPBuiltinTools(enabled bool) ServerOptionFunc
WithMCPBuiltinTools enables the built-in MCP tools (read_file, list_directory, http_request, calculator) By default, built-in tools are disabled and must be explicitly enabled
func WithMCPDiscoveryFilter ¶
func WithMCPDiscoveryFilter(filter func(toolName string, r *http.Request) bool) ServerOptionFunc
WithMCPDiscoveryFilter sets a custom filter function for MCP discovery
The filter function receives the tool name and HTTP request, allowing for context-aware filtering based on auth tokens, IP addresses, etc.
Example - Hide admin tools from external requests:
srv, _ := hyperserve.NewServer(
hyperserve.WithMCPDiscoveryFilter(func(toolName string, r *http.Request) bool {
if strings.Contains(toolName, "admin") {
// Only show admin tools to internal IPs
return strings.HasPrefix(r.RemoteAddr, "10.") ||
strings.HasPrefix(r.RemoteAddr, "192.168.")
}
return true
}),
)
Example - RBAC with Bearer token:
srv, _ := hyperserve.NewServer(
hyperserve.WithMCPDiscoveryFilter(func(toolName string, r *http.Request) bool {
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if token == "" {
return !strings.Contains(toolName, "sensitive")
}
// Decode JWT and check claims
claims := decodeJWT(token)
if claims.Role == "admin" {
return true // Admins see everything
}
// Check tool permissions in claims
return claims.HasPermission(toolName)
}),
)
func WithMCPDiscoveryPolicy ¶
func WithMCPDiscoveryPolicy(policy DiscoveryPolicy) ServerOptionFunc
WithMCPDiscoveryPolicy sets the discovery policy for MCP tools and resources
Example:
srv, _ := hyperserve.NewServer(
hyperserve.WithMCPDiscoveryPolicy(hyperserve.DiscoveryCount),
)
func WithMCPEndpoint ¶
func WithMCPEndpoint(endpoint string) ServerOptionFunc
WithMCPEndpoint configures the MCP endpoint path. Default is "/mcp" if not specified.
func WithMCPFileToolRoot ¶
func WithMCPFileToolRoot(rootDir string) ServerOptionFunc
WithMCPFileToolRoot configures a root directory for MCP file operations. If specified, file tools will be restricted to this directory using os.Root for security.
func WithMCPNamespace ¶
func WithMCPNamespace(name string, configs ...MCPNamespaceConfig) ServerOptionFunc
WithMCPNamespace registers an additional MCP namespace with tools and resources. This allows you to logically separate tools by domain within a single server instance. Example: WithMCPNamespace("daw", WithNamespaceTools(playTool, stopTool)) This creates tools accessible as "mcp__daw__play" and "mcp__daw__stop"
func WithMCPResourcesDisabled ¶
func WithMCPResourcesDisabled() ServerOptionFunc
WithMCPResourcesDisabled disables MCP resources. Tools will still be available if enabled. Deprecated: Use WithMCPBuiltinResources(false) instead
func WithMCPServerInfo ¶
func WithMCPServerInfo(name, version string) ServerOptionFunc
WithMCPServerInfo configures the MCP server identification. This information is returned to MCP clients during initialization. Deprecated: Use WithMCPSupport(WithServerInfo(name, version)) instead for a more concise API.
func WithMCPSupport ¶
func WithMCPSupport(name, version string, configs ...MCPTransportConfig) ServerOptionFunc
WithMCPSupport enables MCP (Model Context Protocol) support on the server. This allows AI assistants to connect and use tools/resources provided by the server. Server name and version are required as they identify your server to MCP clients. By default, MCP uses HTTP transport on the "/mcp" endpoint. Example: WithMCPSupport("MyServer", "1.0.0")
func WithMCPToolsDisabled ¶
func WithMCPToolsDisabled() ServerOptionFunc
WithMCPToolsDisabled disables MCP tools. Resources will still be available if enabled. Deprecated: Use WithMCPBuiltinTools(false) instead
func WithRateLimit ¶
func WithRateLimit(limit rateLimit, burst int) ServerOptionFunc
WithRateLimit configures rate limiting for the server. limit: maximum number of requests per second per client IP burst: maximum number of requests that can be made in a short burst
func WithReadHeaderTimeout ¶
func WithReadHeaderTimeout(timeout time.Duration) ServerOptionFunc
WithReadHeaderTimeout sets the amount of time allowed to read request headers. This helps prevent Slowloris attacks.
func WithReadTimeout ¶
func WithReadTimeout(timeout time.Duration) ServerOptionFunc
WithReadTimeout sets the maximum duration for reading the entire request.
func WithSuppressBanner ¶
func WithSuppressBanner(suppress bool) ServerOptionFunc
WithSuppressBanner suppresses the HyperServe ASCII banner at startup. Useful when building white-label products on top of HyperServe.
func WithTLS ¶
func WithTLS(certFile, keyFile string) ServerOptionFunc
WithTLS enables TLS on the server with the specified certificate and key files. Returns a ServerOptionFunc that configures TLS settings and validates file existence.
func WithTemplateDir ¶
func WithTemplateDir(dir string) ServerOptionFunc
WithTemplateDir sets the directory path where HTML templates are located. Templates in this directory can be used with HandleTemplate and HandleFuncDynamic methods. Returns an error if the specified directory does not exist or is not accessible.
func WithTimeouts ¶
func WithTimeouts(readTimeout, writeTimeout, idleTimeout time.Duration) ServerOptionFunc
WithTimeouts configures the HTTP server timeouts. readTimeout: maximum duration for reading the entire request writeTimeout: maximum duration before timing out writes of the response idleTimeout: maximum time to wait for the next request when keep-alives are enabled
func WithWriteTimeout ¶
func WithWriteTimeout(timeout time.Duration) ServerOptionFunc
WithWriteTimeout sets the maximum duration before timing out writes of the response.
type ServerOptions ¶
type ServerOptions struct {
Addr string `json:"addr,omitempty"`
EnableTLS bool `json:"tls,omitempty"`
TLSAddr string `json:"tls_addr,omitempty"`
TLSHealthAddr string `json:"tls_health_addr,omitempty"`
KeyFile string `json:"key_file,omitempty"`
CertFile string `json:"cert_file,omitempty"`
HealthAddr string `json:"health_addr,omitempty"`
RateLimit rateLimit `json:"rate_limit,omitempty"`
Burst int `json:"burst,omitempty"`
ReadTimeout time.Duration `json:"read_timeout,omitempty"`
WriteTimeout time.Duration `json:"write_timeout,omitempty"`
IdleTimeout time.Duration `json:"idle_timeout,omitempty"`
ReadHeaderTimeout time.Duration `json:"read_header_timeout,omitempty"`
StaticDir string `json:"static_dir,omitempty"`
TemplateDir string `json:"template_dir,omitempty"`
RunHealthServer bool `json:"run_health_server,omitempty"`
ChaosMode bool `json:"chaos_mode,omitempty"`
ChaosMaxLatency time.Duration `json:"chaos_max_latency,omitempty"`
ChaosMinLatency time.Duration `json:"chaos_min_latency,omitempty"`
ChaosErrorRate float64 `json:"chaos_error_rate,omitempty"`
ChaosThrottleRate float64 `json:"chaos_throttle_rate,omitempty"`
ChaosPanicRate float64 `json:"chaos_panic_rate,omitempty"`
AuthTokenValidatorFunc func(token string) (bool, error)
FIPSMode bool `json:"fips_mode,omitempty"`
EnableECH bool `json:"enable_ech,omitempty"`
ECHKeys [][]byte `json:"-"` // ECH keys are sensitive, don't serialize
HardenedMode bool `json:"hardened_mode,omitempty"`
// MCP (Model Context Protocol) configuration
MCPEnabled bool `json:"mcp_enabled,omitempty"`
MCPEndpoint string `json:"mcp_endpoint,omitempty"`
MCPServerName string `json:"mcp_server_name,omitempty"`
MCPServerVersion string `json:"mcp_server_version,omitempty"`
MCPToolsEnabled bool `json:"mcp_tools_enabled,omitempty"`
MCPResourcesEnabled bool `json:"mcp_resources_enabled,omitempty"`
MCPFileToolRoot string `json:"mcp_file_tool_root,omitempty"`
MCPLogResourceSize int `json:"mcp_log_resource_size,omitempty"`
MCPTransport MCPTransportType `json:"mcp_transport,omitempty"`
MCPDev bool `json:"mcp_dev,omitempty"`
MCPObservability bool `json:"mcp_observability,omitempty"`
MCPDiscoveryPolicy DiscoveryPolicy `json:"mcp_discovery_policy,omitempty"`
MCPDiscoveryFilter func(toolName string, r *http.Request) bool `json:"-"` // Custom filter function
// CSP (Content Security Policy) configuration
CSPWebWorkerSupport bool `json:"csp_web_worker_support,omitempty"`
// Logging configuration
LogLevel string `json:"log_level,omitempty"`
DebugMode bool `json:"debug_mode,omitempty"`
// Banner configuration
SuppressBanner bool `json:"suppress_banner,omitempty"`
// contains filtered or unexported fields
}
ServerOptions contains all configuration settings for the HTTP server. Options can be set via WithXXX functions when creating a new server, environment variables, or a configuration file.
Zero values are sensible defaults for most applications.
func NewServerOptions ¶
func NewServerOptions() *ServerOptions
NewServerOptions creates a new ServerOptions instance with values loaded in priority order: 1. Environment variables (highest priority) 2. Configuration file (options.json) 3. Default values (lowest priority) Returns a fully initialized ServerOptions struct ready for use.
type SimpleResource ¶
type SimpleResource struct {
URIFunc func() string
NameFunc func() string
DescriptionFunc func() string
MimeTypeFunc func() string
ReadFunc func() (interface{}, error)
ListFunc func() ([]string, error)
}
SimpleResource provides a simple way to create MCP resources
func (*SimpleResource) Description ¶
func (r *SimpleResource) Description() string
func (*SimpleResource) List ¶
func (r *SimpleResource) List() ([]string, error)
func (*SimpleResource) MimeType ¶
func (r *SimpleResource) MimeType() string
func (*SimpleResource) Name ¶
func (r *SimpleResource) Name() string
func (*SimpleResource) Read ¶
func (r *SimpleResource) Read() (interface{}, error)
func (*SimpleResource) URI ¶
func (r *SimpleResource) URI() string
type SimpleTool ¶
type SimpleTool struct {
NameFunc func() string
DescriptionFunc func() string
SchemaFunc func() map[string]interface{}
ExecuteFunc func(map[string]interface{}) (interface{}, error)
}
SimpleTool provides a simple way to create MCP tools without implementing the full interface
func (*SimpleTool) Description ¶
func (t *SimpleTool) Description() string
func (*SimpleTool) Execute ¶
func (t *SimpleTool) Execute(params map[string]interface{}) (interface{}, error)
func (*SimpleTool) Name ¶
func (t *SimpleTool) Name() string
func (*SimpleTool) Schema ¶
func (t *SimpleTool) Schema() map[string]interface{}
type StreamingLogResource ¶
type StreamingLogResource struct {
*ServerLogResource
// contains filtered or unexported fields
}
StreamingLogResource provides real-time log streaming
func (*StreamingLogResource) Description ¶
func (r *StreamingLogResource) Description() string
func (*StreamingLogResource) Name ¶
func (r *StreamingLogResource) Name() string
func (*StreamingLogResource) URI ¶
func (r *StreamingLogResource) URI() string
type SystemResource ¶
type SystemResource struct{}
SystemResource implements MCPResource for system information
func NewSystemResource ¶
func NewSystemResource() *SystemResource
NewSystemResource creates a new system resource
func (*SystemResource) Description ¶
func (r *SystemResource) Description() string
func (*SystemResource) List ¶
func (r *SystemResource) List() ([]string, error)
func (*SystemResource) MimeType ¶
func (r *SystemResource) MimeType() string
func (*SystemResource) Name ¶
func (r *SystemResource) Name() string
func (*SystemResource) Read ¶
func (r *SystemResource) Read() (interface{}, error)
func (*SystemResource) URI ¶
func (r *SystemResource) URI() string
type ToolBuilder ¶
type ToolBuilder struct {
// contains filtered or unexported fields
}
ToolBuilder provides a fluent API for building tools
func (*ToolBuilder) Build ¶
func (b *ToolBuilder) Build() MCPTool
func (*ToolBuilder) WithDescription ¶
func (b *ToolBuilder) WithDescription(desc string) *ToolBuilder
func (*ToolBuilder) WithExecute ¶
func (b *ToolBuilder) WithExecute(fn func(map[string]interface{}) (interface{}, error)) *ToolBuilder
func (*ToolBuilder) WithParameter ¶
func (b *ToolBuilder) WithParameter(name, paramType, description string, required bool) *ToolBuilder
type ToolsCapability ¶
type ToolsCapability struct {
ListChanged bool `json:"listChanged,omitempty"`
}
ToolsCapability represents the server's tool execution capabilities.
type Upgrader ¶
type Upgrader struct {
// CheckOrigin returns true if the request Origin header is acceptable
// If nil, a safe default is used that checks for same-origin requests
CheckOrigin func(r *http.Request) bool
// Subprotocols specifies the server's supported protocols in order of preference
Subprotocols []string
// Error specifies the function for generating HTTP error responses
Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
// MaxMessageSize is the maximum size for a message read from the peer
MaxMessageSize int64
// WriteBufferSize is the size of the write buffer
WriteBufferSize int
// ReadBufferSize is the size of the read buffer
ReadBufferSize int
// HandshakeTimeout specifies the duration for the handshake to complete
HandshakeTimeout time.Duration
// EnableCompression specifies if the server should attempt to negotiate compression
EnableCompression bool
// BeforeUpgrade is called after origin check but before sending upgrade response
// This can be used for authentication, rate limiting, or other pre-upgrade checks
BeforeUpgrade func(w http.ResponseWriter, r *http.Request) error
// AllowedOrigins is a list of allowed origins for CORS
// If empty and CheckOrigin is nil, same-origin policy is enforced
AllowedOrigins []string
// RequireProtocol ensures the client specifies one of the supported subprotocols
RequireProtocol bool
}
Upgrader upgrades HTTP connections to WebSocket connections
type WebSocketPool ¶
type WebSocketPool struct {
// contains filtered or unexported fields
}
WebSocketPool manages a pool of WebSocket connections
func NewWebSocketPool ¶
func NewWebSocketPool(config PoolConfig) *WebSocketPool
NewWebSocketPool creates a new WebSocket connection pool
func (*WebSocketPool) Close ¶
func (p *WebSocketPool) Close(conn *Conn, reason error) error
Close closes a connection and removes it from the pool
func (*WebSocketPool) Get ¶
func (p *WebSocketPool) Get(ctx context.Context, endpoint string, upgrader *Upgrader, w http.ResponseWriter, r *http.Request) (*Conn, error)
Get retrieves a connection from the pool or creates a new one
func (*WebSocketPool) GetStats ¶
func (p *WebSocketPool) GetStats() PoolStats
GetStats returns current pool statistics
func (*WebSocketPool) Put ¶
func (p *WebSocketPool) Put(conn *Conn) error
Put returns a connection to the pool
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
example-server
command
|
|
|
server
command
|
|
|
examples
|
|
|
best-practices
command
Package main demonstrates best practices for using hyperserve.
|
Package main demonstrates best practices for using hyperserve. |
|
chaos
command
|
|
|
complete
command
|
|
|
configuration
command
|
|
|
devops
command
Example demonstrating DevOps features: debug logging and MCP resources
|
Example demonstrating DevOps features: debug logging and MCP resources |
|
enterprise
command
Enterprise example demonstrating FIPS 140-3 compliance and enhanced security features
|
Enterprise example demonstrating FIPS 140-3 compliance and enhanced security features |
|
hello-world
command
|
|
|
htmx-dynamic
command
|
|
|
htmx-stream
command
|
|
|
interceptors
command
|
|
|
json-api
command
|
|
|
mcp-basic
command
Package main demonstrates MCP with Server-Sent Events (SSE) support.
|
Package main demonstrates MCP with Server-Sent Events (SSE) support. |
|
mcp-cli
command
Example: Using command-line flags to configure MCP
|
Example: Using command-line flags to configure MCP |
|
mcp-discovery
command
|
|
|
mcp-extensions
command
Example: Building a custom application with MCP extensions
|
Example: Building a custom application with MCP extensions |
|
mcp-sse/client
command
|
|
|
mcp-sse/server
command
|
|
|
mcp-stdio
command
Package main demonstrates hyperserve's MCP support as a stdio server for Claude Desktop.
|
Package main demonstrates hyperserve's MCP support as a stdio server for Claude Desktop. |
|
middleware-basics
command
|
|
|
static-files
command
|
|
|
web-worker-csp
command
|
|
|
websocket-demo
command
|
|
|
websocket-pool
command
|
|
|
internal
|
|
|
responsewriter
Package responsewriter provides utilities for wrapping http.ResponseWriter while preserving optional interfaces like Hijacker, Flusher, and ReaderFrom.
|
Package responsewriter provides utilities for wrapping http.ResponseWriter while preserving optional interfaces like Hijacker, Flusher, and ReaderFrom. |
|
ws
Package ws provides low-level WebSocket protocol implementation.
|
Package ws provides low-level WebSocket protocol implementation. |