server

package
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 27, 2025 License: MIT, MIT Imports: 22 Imported by: 0

Documentation

Overview

Code generated by `go generate`. DO NOT EDIT. source: server/internal/gen/hooks.go.tmpl

Code generated by `go generate`. DO NOT EDIT. source: server/internal/gen/request_handler.go.tmpl

Package server provides MCP (Model Context Protocol) server implementations.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Common server errors
	ErrUnsupported      = errors.New("not supported")
	ErrResourceNotFound = errors.New("resource not found")
	ErrPromptNotFound   = errors.New("prompt not found")
	ErrToolNotFound     = errors.New("tool not found")

	// Session-related errors
	ErrSessionNotFound              = errors.New("session not found")
	ErrSessionExists                = errors.New("session already exists")
	ErrSessionNotInitialized        = errors.New("session not properly initialized")
	ErrSessionDoesNotSupportTools   = errors.New("session does not support per-session tools")
	ErrSessionDoesNotSupportLogging = errors.New("session does not support setting logging level")

	// Notification-related errors
	ErrNotificationNotInitialized = errors.New("notification channel not initialized")
	ErrNotificationChannelBlocked = errors.New("notification channel full or blocked")
)

Functions

func NewTestStreamableHTTPServer

func NewTestStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *httptest.Server

NewTestStreamableHTTPServer creates a test server for testing purposes

func ServeStdio

func ServeStdio(server *MCPServer, opts ...StdioOption) error

ServeStdio is a convenience function that creates and starts a StdioServer with os.Stdin and os.Stdout. It sets up signal handling for graceful shutdown on SIGTERM and SIGINT. Returns an error if the server encounters any issues during operation.

Types

type BeforeAnyHookFunc

type BeforeAnyHookFunc func(ctx context.Context, id any, method mcp.MCPMethod, message any)

BeforeAnyHookFunc is a function that is called after the request is parsed but before the method is called.

type ClientSession

type ClientSession interface {
	// Initialize marks session as fully initialized and ready for notifications
	Initialize()
	// Initialized returns if session is ready to accept notifications
	Initialized() bool
	// NotificationChannel provides a channel suitable for sending notifications to client.
	NotificationChannel() chan<- mcp.JSONRPCNotification
	// SessionID is a unique identifier used to track user session.
	SessionID() string
}

ClientSession represents an active session that can be used by MCPServer to interact with client.

func ClientSessionFromContext

func ClientSessionFromContext(ctx context.Context) ClientSession

ClientSessionFromContext retrieves current client notification context from context.

type ErrDynamicPathConfig

type ErrDynamicPathConfig struct {
	Method string
}

ErrDynamicPathConfig is returned when attempting to use static path methods with dynamic path configuration

func (*ErrDynamicPathConfig) Error

func (e *ErrDynamicPathConfig) Error() string

type HTTPContextFunc

type HTTPContextFunc func(ctx context.Context, r *http.Request) context.Context

HTTPContextFunc is a function that takes an existing context and the current request and returns a potentially modified context based on the request content. This can be used to inject context values from headers, for example.

type Hooks

type Hooks struct {
	OnRegisterSession             []OnRegisterSessionHookFunc
	OnUnregisterSession           []OnUnregisterSessionHookFunc
	OnBeforeAny                   []BeforeAnyHookFunc
	OnSuccess                     []OnSuccessHookFunc
	OnError                       []OnErrorHookFunc
	OnRequestInitialization       []OnRequestInitializationFunc
	OnBeforeInitialize            []OnBeforeInitializeFunc
	OnAfterInitialize             []OnAfterInitializeFunc
	OnBeforePing                  []OnBeforePingFunc
	OnAfterPing                   []OnAfterPingFunc
	OnBeforeSetLevel              []OnBeforeSetLevelFunc
	OnAfterSetLevel               []OnAfterSetLevelFunc
	OnBeforeListResources         []OnBeforeListResourcesFunc
	OnAfterListResources          []OnAfterListResourcesFunc
	OnBeforeListResourceTemplates []OnBeforeListResourceTemplatesFunc
	OnAfterListResourceTemplates  []OnAfterListResourceTemplatesFunc
	OnBeforeReadResource          []OnBeforeReadResourceFunc
	OnAfterReadResource           []OnAfterReadResourceFunc
	OnBeforeListPrompts           []OnBeforeListPromptsFunc
	OnAfterListPrompts            []OnAfterListPromptsFunc
	OnBeforeGetPrompt             []OnBeforeGetPromptFunc
	OnAfterGetPrompt              []OnAfterGetPromptFunc
	OnBeforeListTools             []OnBeforeListToolsFunc
	OnAfterListTools              []OnAfterListToolsFunc
	OnBeforeCallTool              []OnBeforeCallToolFunc
	OnAfterCallTool               []OnAfterCallToolFunc
}

func (*Hooks) AddAfterCallTool

func (c *Hooks) AddAfterCallTool(hook OnAfterCallToolFunc)

func (*Hooks) AddAfterGetPrompt

func (c *Hooks) AddAfterGetPrompt(hook OnAfterGetPromptFunc)

func (*Hooks) AddAfterInitialize

func (c *Hooks) AddAfterInitialize(hook OnAfterInitializeFunc)

func (*Hooks) AddAfterListPrompts

func (c *Hooks) AddAfterListPrompts(hook OnAfterListPromptsFunc)

func (*Hooks) AddAfterListResourceTemplates

func (c *Hooks) AddAfterListResourceTemplates(hook OnAfterListResourceTemplatesFunc)

func (*Hooks) AddAfterListResources

func (c *Hooks) AddAfterListResources(hook OnAfterListResourcesFunc)

func (*Hooks) AddAfterListTools

func (c *Hooks) AddAfterListTools(hook OnAfterListToolsFunc)

func (*Hooks) AddAfterPing

func (c *Hooks) AddAfterPing(hook OnAfterPingFunc)

func (*Hooks) AddAfterReadResource

func (c *Hooks) AddAfterReadResource(hook OnAfterReadResourceFunc)

func (*Hooks) AddAfterSetLevel

func (c *Hooks) AddAfterSetLevel(hook OnAfterSetLevelFunc)

func (*Hooks) AddBeforeAny

func (c *Hooks) AddBeforeAny(hook BeforeAnyHookFunc)

func (*Hooks) AddBeforeCallTool

func (c *Hooks) AddBeforeCallTool(hook OnBeforeCallToolFunc)

func (*Hooks) AddBeforeGetPrompt

func (c *Hooks) AddBeforeGetPrompt(hook OnBeforeGetPromptFunc)

func (*Hooks) AddBeforeInitialize

func (c *Hooks) AddBeforeInitialize(hook OnBeforeInitializeFunc)

func (*Hooks) AddBeforeListPrompts

func (c *Hooks) AddBeforeListPrompts(hook OnBeforeListPromptsFunc)

func (*Hooks) AddBeforeListResourceTemplates

func (c *Hooks) AddBeforeListResourceTemplates(hook OnBeforeListResourceTemplatesFunc)

func (*Hooks) AddBeforeListResources

func (c *Hooks) AddBeforeListResources(hook OnBeforeListResourcesFunc)

func (*Hooks) AddBeforeListTools

func (c *Hooks) AddBeforeListTools(hook OnBeforeListToolsFunc)

func (*Hooks) AddBeforePing

func (c *Hooks) AddBeforePing(hook OnBeforePingFunc)

func (*Hooks) AddBeforeReadResource

func (c *Hooks) AddBeforeReadResource(hook OnBeforeReadResourceFunc)

func (*Hooks) AddBeforeSetLevel

func (c *Hooks) AddBeforeSetLevel(hook OnBeforeSetLevelFunc)

func (*Hooks) AddOnError

func (c *Hooks) AddOnError(hook OnErrorHookFunc)

AddOnError registers a hook function that will be called when an error occurs. The error parameter contains the actual error object, which can be interrogated using Go's error handling patterns like errors.Is and errors.As.

Example: ``` // Create a channel to receive errors for testing errChan := make(chan error, 1)

// Register hook to capture and inspect errors hooks := &Hooks{}

hooks.AddOnError(func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) {
    // For capability-related errors
    if errors.Is(err, ErrUnsupported) {
        // Handle capability not supported
        errChan <- err
        return
    }

    // For parsing errors
    var parseErr = &UnparsableMessageError{}
    if errors.As(err, &parseErr) {
        // Handle unparsable message errors
        fmt.Printf("Failed to parse %s request: %v\n",
                   parseErr.GetMethod(), parseErr.Unwrap())
        errChan <- parseErr
        return
    }

    // For resource/prompt/tool not found errors
    if errors.Is(err, ErrResourceNotFound) ||
       errors.Is(err, ErrPromptNotFound) ||
       errors.Is(err, ErrToolNotFound) {
        // Handle not found errors
        errChan <- err
        return
    }

    // For other errors
    errChan <- err
})

server := NewMCPServer("test-server", "1.0.0", WithHooks(hooks)) ```

func (*Hooks) AddOnRegisterSession

func (c *Hooks) AddOnRegisterSession(hook OnRegisterSessionHookFunc)

func (*Hooks) AddOnRequestInitialization

func (c *Hooks) AddOnRequestInitialization(hook OnRequestInitializationFunc)

func (*Hooks) AddOnSuccess

func (c *Hooks) AddOnSuccess(hook OnSuccessHookFunc)

func (*Hooks) AddOnUnregisterSession

func (c *Hooks) AddOnUnregisterSession(hook OnUnregisterSessionHookFunc)

func (*Hooks) RegisterSession

func (c *Hooks) RegisterSession(ctx context.Context, session ClientSession)

func (*Hooks) UnregisterSession

func (c *Hooks) UnregisterSession(ctx context.Context, session ClientSession)

type InsecureStatefulSessionIdManager

type InsecureStatefulSessionIdManager struct{}

InsecureStatefulSessionIdManager generate id with uuid It won't validate the id indeed, so it could be fake. For more secure session id, use a more complex generator, like a JWT.

func (*InsecureStatefulSessionIdManager) Generate

func (*InsecureStatefulSessionIdManager) Terminate

func (s *InsecureStatefulSessionIdManager) Terminate(sessionID string) (isNotAllowed bool, err error)

func (*InsecureStatefulSessionIdManager) Validate

func (s *InsecureStatefulSessionIdManager) Validate(sessionID string) (isTerminated bool, err error)

type MCPServer

type MCPServer struct {
	// contains filtered or unexported fields
}

MCPServer implements a Model Context Protocol server that can handle various types of requests including resources, prompts, and tools.

func NewMCPServer

func NewMCPServer(
	name, version string,
	opts ...ServerOption,
) *MCPServer

NewMCPServer creates a new MCP server instance with the given name, version and options

func ServerFromContext

func ServerFromContext(ctx context.Context) *MCPServer

ServerFromContext retrieves the MCPServer instance from a context

func (*MCPServer) AddNotificationHandler

func (s *MCPServer) AddNotificationHandler(
	method string,
	handler NotificationHandlerFunc,
)

AddNotificationHandler registers a new handler for incoming notifications

func (*MCPServer) AddPrompt

func (s *MCPServer) AddPrompt(prompt mcp.Prompt, handler PromptHandlerFunc)

AddPrompt registers a new prompt handler with the given name

func (*MCPServer) AddResource

func (s *MCPServer) AddResource(
	resource mcp.Resource,
	handler ResourceHandlerFunc,
)

AddResource registers a new resource and its handler

func (*MCPServer) AddResourceTemplate

func (s *MCPServer) AddResourceTemplate(
	template mcp.ResourceTemplate,
	handler ResourceTemplateHandlerFunc,
)

AddResourceTemplate registers a new resource template and its handler

func (*MCPServer) AddSessionTool

func (s *MCPServer) AddSessionTool(sessionID string, tool mcp.Tool, handler ToolHandlerFunc) error

AddSessionTool adds a tool for a specific session

func (*MCPServer) AddSessionTools

func (s *MCPServer) AddSessionTools(sessionID string, tools ...ServerTool) error

AddSessionTools adds tools for a specific session

func (*MCPServer) AddTool

func (s *MCPServer) AddTool(tool mcp.Tool, handler ToolHandlerFunc)

AddTool registers a new tool and its handler

func (*MCPServer) AddTools

func (s *MCPServer) AddTools(tools ...ServerTool)

AddTools registers multiple tools at once

func (*MCPServer) DeleteSessionTools

func (s *MCPServer) DeleteSessionTools(sessionID string, names ...string) error

DeleteSessionTools removes tools from a specific session

func (*MCPServer) DeleteTools

func (s *MCPServer) DeleteTools(names ...string)

DeleteTools removes a tool from the server

func (*MCPServer) HandleMessage

func (s *MCPServer) HandleMessage(
	ctx context.Context,
	message json.RawMessage,
) mcp.JSONRPCMessage

HandleMessage processes an incoming JSON-RPC message and returns an appropriate response

func (*MCPServer) ListTools

func (s *MCPServer) ListTools() []mcp.Tool

ListTools returns a slice of all registered tools (mcp.Tool)

func (*MCPServer) RegisterSession

func (s *MCPServer) RegisterSession(
	ctx context.Context,
	session ClientSession,
) error

RegisterSession saves session that should be notified in case if some server attributes changed.

func (*MCPServer) RemoveResource

func (s *MCPServer) RemoveResource(uri string)

RemoveResource removes a resource from the server

func (*MCPServer) SendNotificationToAllClients

func (s *MCPServer) SendNotificationToAllClients(
	method string,
	params map[string]any,
)

SendNotificationToAllClients sends a notification to all the currently active clients.

func (*MCPServer) SendNotificationToClient

func (s *MCPServer) SendNotificationToClient(
	ctx context.Context,
	method string,
	params map[string]any,
) error

SendNotificationToClient sends a notification to the current client

func (*MCPServer) SendNotificationToSpecificClient

func (s *MCPServer) SendNotificationToSpecificClient(
	sessionID string,
	method string,
	params map[string]any,
) error

SendNotificationToSpecificClient sends a notification to a specific client by session ID

func (*MCPServer) SetTools

func (s *MCPServer) SetTools(tools ...ServerTool)

SetTools replaces all existing tools with the provided list

func (*MCPServer) UnregisterSession

func (s *MCPServer) UnregisterSession(
	ctx context.Context,
	sessionID string,
)

UnregisterSession removes from storage session that is shut down.

func (*MCPServer) WithContext

func (s *MCPServer) WithContext(
	ctx context.Context,
	session ClientSession,
) context.Context

WithContext sets the current client session and returns the provided context

type NotificationHandlerFunc

type NotificationHandlerFunc func(ctx context.Context, notification mcp.JSONRPCNotification)

NotificationHandlerFunc handles incoming notifications.

type OnAfterCallToolFunc

type OnAfterCallToolFunc func(ctx context.Context, id any, message *mcp.CallToolRequest, result *mcp.CallToolResult)

type OnAfterGetPromptFunc

type OnAfterGetPromptFunc func(ctx context.Context, id any, message *mcp.GetPromptRequest, result *mcp.GetPromptResult)

type OnAfterInitializeFunc

type OnAfterInitializeFunc func(ctx context.Context, id any, message *mcp.InitializeRequest, result *mcp.InitializeResult)

type OnAfterListPromptsFunc

type OnAfterListPromptsFunc func(ctx context.Context, id any, message *mcp.ListPromptsRequest, result *mcp.ListPromptsResult)

type OnAfterListResourceTemplatesFunc

type OnAfterListResourceTemplatesFunc func(ctx context.Context, id any, message *mcp.ListResourceTemplatesRequest, result *mcp.ListResourceTemplatesResult)

type OnAfterListResourcesFunc

type OnAfterListResourcesFunc func(ctx context.Context, id any, message *mcp.ListResourcesRequest, result *mcp.ListResourcesResult)

type OnAfterListToolsFunc

type OnAfterListToolsFunc func(ctx context.Context, id any, message *mcp.ListToolsRequest, result *mcp.ListToolsResult)

type OnAfterPingFunc

type OnAfterPingFunc func(ctx context.Context, id any, message *mcp.PingRequest, result *mcp.EmptyResult)

type OnAfterReadResourceFunc

type OnAfterReadResourceFunc func(ctx context.Context, id any, message *mcp.ReadResourceRequest, result *mcp.ReadResourceResult)

type OnAfterSetLevelFunc

type OnAfterSetLevelFunc func(ctx context.Context, id any, message *mcp.SetLevelRequest, result *mcp.EmptyResult)

type OnBeforeCallToolFunc

type OnBeforeCallToolFunc func(ctx context.Context, id any, message *mcp.CallToolRequest)

type OnBeforeGetPromptFunc

type OnBeforeGetPromptFunc func(ctx context.Context, id any, message *mcp.GetPromptRequest)

type OnBeforeInitializeFunc

type OnBeforeInitializeFunc func(ctx context.Context, id any, message *mcp.InitializeRequest)

type OnBeforeListPromptsFunc

type OnBeforeListPromptsFunc func(ctx context.Context, id any, message *mcp.ListPromptsRequest)

type OnBeforeListResourceTemplatesFunc

type OnBeforeListResourceTemplatesFunc func(ctx context.Context, id any, message *mcp.ListResourceTemplatesRequest)

type OnBeforeListResourcesFunc

type OnBeforeListResourcesFunc func(ctx context.Context, id any, message *mcp.ListResourcesRequest)

type OnBeforeListToolsFunc

type OnBeforeListToolsFunc func(ctx context.Context, id any, message *mcp.ListToolsRequest)

type OnBeforePingFunc

type OnBeforePingFunc func(ctx context.Context, id any, message *mcp.PingRequest)

type OnBeforeReadResourceFunc

type OnBeforeReadResourceFunc func(ctx context.Context, id any, message *mcp.ReadResourceRequest)

type OnBeforeSetLevelFunc

type OnBeforeSetLevelFunc func(ctx context.Context, id any, message *mcp.SetLevelRequest)

type OnErrorHookFunc

type OnErrorHookFunc func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error)

OnErrorHookFunc is a hook that will be called when an error occurs, either during the request parsing or the method execution.

Example usage: ```

hooks.AddOnError(func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) {
  // Check for specific error types using errors.Is
  if errors.Is(err, ErrUnsupported) {
    // Handle capability not supported errors
    log.Printf("Capability not supported: %v", err)
  }

  // Use errors.As to get specific error types
  var parseErr = &UnparsableMessageError{}
  if errors.As(err, &parseErr) {
    // Access specific methods/fields of the error type
    log.Printf("Failed to parse message for method %s: %v",
               parseErr.GetMethod(), parseErr.Unwrap())
    // Access the raw message that failed to parse
    rawMsg := parseErr.GetMessage()
  }

  // Check for specific resource/prompt/tool errors
  switch {
  case errors.Is(err, ErrResourceNotFound):
    log.Printf("Resource not found: %v", err)
  case errors.Is(err, ErrPromptNotFound):
    log.Printf("Prompt not found: %v", err)
  case errors.Is(err, ErrToolNotFound):
    log.Printf("Tool not found: %v", err)
  }
})

type OnRegisterSessionHookFunc

type OnRegisterSessionHookFunc func(ctx context.Context, session ClientSession)

OnRegisterSessionHookFunc is a hook that will be called when a new session is registered.

type OnRequestInitializationFunc

type OnRequestInitializationFunc func(ctx context.Context, id any, message any) error

OnRequestInitializationFunc is a function that called before handle diff request method Should any errors arise during func execution, the service will promptly return the corresponding error message.

type OnSuccessHookFunc

type OnSuccessHookFunc func(ctx context.Context, id any, method mcp.MCPMethod, message any, result any)

OnSuccessHookFunc is a hook that will be called after the request successfully generates a result, but before the result is sent to the client.

type OnUnregisterSessionHookFunc

type OnUnregisterSessionHookFunc func(ctx context.Context, session ClientSession)

OnUnregisterSessionHookFunc is a hook that will be called when a session is being unregistered.

type PromptHandlerFunc

type PromptHandlerFunc func(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error)

PromptHandlerFunc handles prompt requests with given arguments.

type ResourceHandlerFunc

type ResourceHandlerFunc func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error)

ResourceHandlerFunc is a function that returns resource contents.

type ResourceTemplateHandlerFunc

type ResourceTemplateHandlerFunc func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error)

ResourceTemplateHandlerFunc is a function that returns a resource template.

type ServerOption

type ServerOption func(*MCPServer)

ServerOption is a function that configures an MCPServer.

func WithHooks

func WithHooks(hooks *Hooks) ServerOption

WithHooks allows adding hooks that will be called before or after either [all] requests or before / after specific request methods, or else prior to returning an error to the client.

func WithInstructions

func WithInstructions(instructions string) ServerOption

WithInstructions sets the server instructions for the client returned in the initialize response

func WithLogging

func WithLogging() ServerOption

WithLogging enables logging capabilities for the server

func WithPaginationLimit

func WithPaginationLimit(limit int) ServerOption

WithPaginationLimit sets the pagination limit for the server.

func WithPromptCapabilities

func WithPromptCapabilities(listChanged bool) ServerOption

WithPromptCapabilities configures prompt-related server capabilities

func WithRecovery

func WithRecovery() ServerOption

WithRecovery adds a middleware that recovers from panics in tool handlers.

func WithResourceCapabilities

func WithResourceCapabilities(subscribe, listChanged bool) ServerOption

WithResourceCapabilities configures resource-related server capabilities

func WithToolCapabilities

func WithToolCapabilities(listChanged bool) ServerOption

WithToolCapabilities configures tool-related server capabilities

func WithToolFilter

func WithToolFilter(
	toolFilter ToolFilterFunc,
) ServerOption

WithToolFilter adds a filter function that will be applied to tools before they are returned in list_tools

func WithToolHandlerMiddleware

func WithToolHandlerMiddleware(
	toolHandlerMiddleware ToolHandlerMiddleware,
) ServerOption

WithToolHandlerMiddleware allows adding a middleware for the tool handler call chain.

type ServerTool

type ServerTool struct {
	Tool    mcp.Tool
	Handler ToolHandlerFunc
}

ServerTool combines a Tool with its ToolHandlerFunc.

type SessionIdManager

type SessionIdManager interface {
	Generate() string
	// Validate checks if a session ID is valid and not terminated.
	// Returns isTerminated=true if the ID is valid but belongs to a terminated session.
	// Returns err!=nil if the ID format is invalid or lookup failed.
	Validate(sessionID string) (isTerminated bool, err error)
	// Terminate marks a session ID as terminated.
	// Returns isNotAllowed=true if the server policy prevents client termination.
	// Returns err!=nil if the ID is invalid or termination failed.
	Terminate(sessionID string) (isNotAllowed bool, err error)
}

type SessionWithLogging

type SessionWithLogging interface {
	ClientSession
	// SetLogLevel sets the minimum log level
	SetLogLevel(level mcp.LoggingLevel)
	// GetLogLevel retrieves the minimum log level
	GetLogLevel() mcp.LoggingLevel
}

SessionWithLogging is an extension of ClientSession that can receive log message notifications and set log level

type SessionWithTools

type SessionWithTools interface {
	ClientSession
	// GetSessionTools returns the tools specific to this session, if any
	// This method must be thread-safe for concurrent access
	GetSessionTools() map[string]ServerTool
	// SetSessionTools sets tools specific to this session
	// This method must be thread-safe for concurrent access
	SetSessionTools(tools map[string]ServerTool)
}

SessionWithTools is an extension of ClientSession that can store session-specific tool data

type StatelessSessionIdManager

type StatelessSessionIdManager struct{}

StatelessSessionIdManager does nothing, which means it has no session management, which is stateless.

func (*StatelessSessionIdManager) Generate

func (s *StatelessSessionIdManager) Generate() string

func (*StatelessSessionIdManager) Terminate

func (s *StatelessSessionIdManager) Terminate(sessionID string) (isNotAllowed bool, err error)

func (*StatelessSessionIdManager) Validate

func (s *StatelessSessionIdManager) Validate(sessionID string) (isTerminated bool, err error)

type StdioContextFunc

type StdioContextFunc func(ctx context.Context) context.Context

StdioContextFunc is a function that takes an existing context and returns a potentially modified context. This can be used to inject context values from environment variables, for example.

type StdioOption

type StdioOption func(*StdioServer)

StdioOption defines a function type for configuring StdioServer

func WithErrorLogger

func WithErrorLogger(logger *log.Logger) StdioOption

WithErrorLogger sets the error logger for the server

func WithStdioContextFunc

func WithStdioContextFunc(fn StdioContextFunc) StdioOption

WithStdioContextFunc sets a function that will be called to customise the context to the server. Note that the stdio server uses the same context for all requests, so this function will only be called once per server instance.

type StdioServer

type StdioServer struct {
	// contains filtered or unexported fields
}

StdioServer wraps a MCPServer and handles stdio communication. It provides a simple way to create command-line MCP servers that communicate via standard input/output streams using JSON-RPC messages.

func NewStdioServer

func NewStdioServer(server *MCPServer) *StdioServer

NewStdioServer creates a new stdio server wrapper around an MCPServer. It initializes the server with a default error logger that discards all output.

func (*StdioServer) Listen

func (s *StdioServer) Listen(
	ctx context.Context,
	stdin io.Reader,
	stdout io.Writer,
) error

Listen starts listening for JSON-RPC messages on the provided input and writes responses to the provided output. It runs until the context is cancelled or an error occurs. Returns an error if there are issues with reading input or writing output.

func (*StdioServer) SetContextFunc

func (s *StdioServer) SetContextFunc(fn StdioContextFunc)

SetContextFunc sets a function that will be called to customise the context to the server. Note that the stdio server uses the same context for all requests, so this function will only be called once per server instance.

func (*StdioServer) SetErrorLogger

func (s *StdioServer) SetErrorLogger(logger *log.Logger)

SetErrorLogger configures where error messages from the StdioServer are logged. The provided logger will receive all error messages generated during server operation.

type StreamableHTTPOption

type StreamableHTTPOption func(*StreamableHTTPServer)

StreamableHTTPOption defines a function type for configuring StreamableHTTPServer

func WithEndpointPath

func WithEndpointPath(endpointPath string) StreamableHTTPOption

WithEndpointPath sets the endpoint path for the server. The default is "/mcp". It's only works for `Start` method. When used as a http.Handler, it has no effect.

func WithHTTPContextFunc

func WithHTTPContextFunc(fn HTTPContextFunc) StreamableHTTPOption

WithHTTPContextFunc sets a function that will be called to customise the context to the server using the incoming request. This can be used to inject context values from headers, for example.

func WithHeartbeatInterval

func WithHeartbeatInterval(interval time.Duration) StreamableHTTPOption

WithHeartbeatInterval sets the heartbeat interval. Positive interval means the server will send a heartbeat to the client through the GET connection, to keep the connection alive from being closed by the network infrastructure (e.g. gateways). If the client does not establish a GET connection, it has no effect. The default is not to send heartbeats.

func WithLogger

func WithLogger(logger util.Logger) StreamableHTTPOption

WithLogger sets the logger for the server

func WithSessionIdManager

func WithSessionIdManager(manager SessionIdManager) StreamableHTTPOption

WithSessionIdManager sets a custom session id generator for the server. By default, the server will use SimpleStatefulSessionIdGenerator, which generates session ids with uuid, and it's insecure. Notice: it will override the WithStateLess option.

func WithStateLess

func WithStateLess(stateLess bool) StreamableHTTPOption

WithStateLess sets the server to stateless mode. If true, the server will manage no session information. Every request will be treated as a new session. No session id returned to the client. The default is false.

Notice: This is a convenience method. It's identical to set WithSessionIdManager option to StatelessSessionIdManager.

type StreamableHTTPServer

type StreamableHTTPServer struct {
	// contains filtered or unexported fields
}

StreamableHTTPServer implements a Streamable-http based MCP server. It communicates with clients over HTTP protocol, supporting both direct HTTP responses, and SSE streams. https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http

Usage:

server := NewStreamableHTTPServer(mcpServer)
server.Start(":8080") // The final url for client is http://xxxx:8080/mcp by default

or the server itself can be used as a http.Handler, which is convenient to integrate with existing http servers, or advanced usage:

handler := NewStreamableHTTPServer(mcpServer)
http.Handle("/streamable-http", handler)
http.ListenAndServe(":8080", nil)

Notice: Except for the GET handlers(listening), the POST handlers(request/notification) will not trigger the session registration. So the methods like `SendNotificationToSpecificClient` or `hooks.onRegisterSession` will not be triggered for POST messages.

The current implementation does not support the following features from the specification:

  • Batching of requests/notifications/responses in arrays.
  • Stream Resumability

func NewStreamableHTTPServer

func NewStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *StreamableHTTPServer

NewStreamableHTTPServer creates a new streamable-http server instance

func (*StreamableHTTPServer) ServeHTTP

func (s *StreamableHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

func (*StreamableHTTPServer) Shutdown

func (s *StreamableHTTPServer) Shutdown(ctx context.Context) error

Shutdown gracefully stops the server, closing all active sessions and shutting down the HTTP server.

func (*StreamableHTTPServer) Start

func (s *StreamableHTTPServer) Start(addr string) error

Start begins serving the http server on the specified address and path (endpointPath). like:

s.Start(":8080")

type ToolFilterFunc

type ToolFilterFunc func(ctx context.Context, tools []mcp.Tool) []mcp.Tool

ToolFilterFunc is a function that filters tools based on context, typically using session information.

type ToolHandlerFunc

type ToolHandlerFunc func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

ToolHandlerFunc handles tool calls with given arguments.

type ToolHandlerMiddleware

type ToolHandlerMiddleware func(ToolHandlerFunc) ToolHandlerFunc

ToolHandlerMiddleware is a middleware function that wraps a ToolHandlerFunc.

type UnparsableMessageError

type UnparsableMessageError struct {
	// contains filtered or unexported fields
}

UnparsableMessageError is attached to the RequestError when json.Unmarshal fails on the request.

func (*UnparsableMessageError) Error

func (e *UnparsableMessageError) Error() string

func (*UnparsableMessageError) GetMessage

func (e *UnparsableMessageError) GetMessage() json.RawMessage

func (*UnparsableMessageError) GetMethod

func (e *UnparsableMessageError) GetMethod() mcp.MCPMethod

func (*UnparsableMessageError) Unwrap

func (e *UnparsableMessageError) Unwrap() error

Directories

Path Synopsis
internal
gen command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL