Documentation
¶
Index ¶
- Constants
- func EnsureTrailingSlash(dir string) string
- func HealthCheckHandler(w http.ResponseWriter, r *http.Request)
- 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 CalculatorTool
- type ConfigResource
- type DataFunc
- type FileReadTool
- type HTTPRequestTool
- type Header
- 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 MCPHandler
- func (h *MCPHandler) GetMetrics() map[string]interface{}
- func (h *MCPHandler) ProcessRequest(requestData []byte) []byte
- func (h *MCPHandler) ProcessRequestWithTransport(transport MCPTransport) error
- func (h *MCPHandler) RegisterResource(resource MCPResource)
- func (h *MCPHandler) RegisterTool(tool MCPTool)
- func (h *MCPHandler) RunStdioLoop() error
- func (h *MCPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type MCPInitializeParams
- type MCPInitializeResult
- type MCPMetrics
- 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 MCPTransportType
- type MetricsResource
- type MiddlewareFunc
- type MiddlewareRegistry
- type MiddlewareStack
- type PromptsCapability
- type ResourcesCapability
- 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) RegisterMCPResource(resource MCPResource) error
- func (srv *Server) RegisterMCPTool(tool MCPTool) error
- func (srv *Server) Run() error
- func (srv *Server) Stop() error
- func (srv *Server) WithOutStack(stack MiddlewareStack) error
- type ServerOptionFunc
- func WithAddr(addr string) ServerOptionFunc
- func WithAuthTokenValidator(validator func(token string) (bool, error)) ServerOptionFunc
- func WithEncryptedClientHello(echKeys ...[]byte) ServerOptionFunc
- func WithFIPSMode() ServerOptionFunc
- func WithHardenedMode() ServerOptionFunc
- func WithHealthServer() ServerOptionFunc
- func WithLogger(l *slog.Logger) ServerOptionFunc
- func WithLoglevel(level slog.Level) ServerOptionFunc
- func WithMCPBuiltinResources(enabled bool) ServerOptionFunc
- func WithMCPBuiltinTools(enabled bool) ServerOptionFunc
- func WithMCPEndpoint(endpoint string) ServerOptionFunc
- func WithMCPFileToolRoot(rootDir string) ServerOptionFunc
- func WithMCPResourcesDisabled() ServerOptionFunc
- func WithMCPServerInfo(name, version string) ServerOptionFunc
- func WithMCPSupport(configs ...MCPTransportConfig) ServerOptionFunc
- func WithMCPToolsDisabled() ServerOptionFunc
- func WithRateLimit(limit rateLimit, burst int) ServerOptionFunc
- func WithTLS(certFile, keyFile string) ServerOptionFunc
- func WithTemplateDir(dir string) ServerOptionFunc
- func WithTimeouts(readTimeout, writeTimeout, idleTimeout time.Duration) ServerOptionFunc
- type ServerOptions
- type SystemResource
- type ToolsCapability
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 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
const (
// Version is the current version of hyperserve
Version = "v0.9.4"
)
Environment management variable names
Variables ¶
This section is empty.
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 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 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 detailed request information. Logs IP address, method, URL, trace ID, status code, and request duration. Use with caution as it may impact server performance.
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 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 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 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 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 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 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"`
}
MCPCapabilities represents the server's MCP capabilities
type MCPClientInfo ¶
MCPClientInfo represents MCP client information
type MCPHandler ¶
type MCPHandler struct {
// contains filtered or unexported fields
}
MCPHandler manages MCP protocol communication
func NewMCPHandler ¶
func NewMCPHandler(serverInfo MCPServerInfo) *MCPHandler
NewMCPHandler creates a new MCP handler instance
func (*MCPHandler) GetMetrics ¶ added in v0.9.2
func (h *MCPHandler) GetMetrics() map[string]interface{}
GetMetrics returns the current MCP metrics summary
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) RegisterResource ¶
func (h *MCPHandler) RegisterResource(resource MCPResource)
RegisterResource registers an MCP resource
func (*MCPHandler) RegisterTool ¶
func (h *MCPHandler) RegisterTool(tool MCPTool)
RegisterTool registers an MCP tool
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) ServeHTTP ¶
func (h *MCPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface for MCP
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 ¶ added in v0.9.2
type MCPMetrics struct {
// contains filtered or unexported fields
}
MCPMetrics tracks performance metrics for MCP operations
func (*MCPMetrics) GetMetricsSummary ¶ added in v0.9.2
func (m *MCPMetrics) GetMetricsSummary() map[string]interface{}
GetMetricsSummary returns a summary of collected metrics
type MCPResource ¶
type MCPResource interface {
URI() string
Name() string
Description() string
MimeType() string
Read() (interface{}, error)
List() ([]string, error)
}
MCP Resource interface defines the contract for MCP 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)
}
MCP Tool interface defines the contract for MCP 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 ¶ added in v0.9.2
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 MCPOverHTTP ¶
func MCPOverHTTP(endpoint string) MCPTransportConfig
MCPOverHTTP configures MCP to use HTTP transport with the specified endpoint
func MCPOverStdio ¶
func MCPOverStdio() MCPTransportConfig
MCPOverStdio configures MCP to use stdio transport
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.
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 PromptsCapability ¶
type PromptsCapability struct{}
type ResourcesCapability ¶
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{}
type Server ¶
type Server struct {
Options *ServerOptions
// contains filtered or unexported fields
}
Server represents an HTTP server that can handle requests and responses. It provides middleware support, health checks, template rendering, and various configuration options.
func NewServer ¶
func NewServer(opts ...ServerOptionFunc) (*Server, error)
NewServer creates a new instance of the Server with the given options. It initializes the server with default middleware and applies all provided ServerOptionFunc options. 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. This is a wrapper around http.ServeMux.HandleFunc that integrates with the server's middleware system. Example usage:
srv.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, world!")
})
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) 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) RegisterMCPTool ¶
RegisterMCPTool registers a custom MCP tool This must be called after server creation but before Run()
func (*Server) Run ¶
Run starts the server and listens for incoming requests. It sets up TLS if enabled, starts the health server if configured, and handles graceful shutdown. Returns an error if the server fails to start or encounters an error during operation.
func (*Server) WithOutStack ¶
func (srv *Server) WithOutStack(stack MiddlewareStack) error
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 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 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 ¶ added in v0.9.3
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 ¶ added in v0.9.3
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 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 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.
func WithMCPSupport ¶
func WithMCPSupport(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. By default, MCP uses HTTP transport on the "/mcp" endpoint. Pass MCPOverHTTP() or MCPOverStdio() to configure the transport.
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 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
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"`
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"`
// contains filtered or unexported fields
}
ServerOptions contains all configuration settings for the HTTP server. Options are loaded from environment variables, configuration files, and defaults in that priority order.
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 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 ToolsCapability ¶
type ToolsCapability struct {
ListChanged bool `json:"listChanged,omitempty"`
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
auth
command
Example of how to use the auth package of Hyperserve
|
Example of how to use the auth package of Hyperserve |
|
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
|
|
|
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
|
|
|
json-api
command
|
|
|
mcp
command
Package main demonstrates hyperserve's Model Context Protocol (MCP) support.
|
Package main demonstrates hyperserve's Model Context Protocol (MCP) support. |
|
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
|
|
|
go
module
|