mcpwrapper

package
v0.0.0-...-f971134 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package mcpwrapper provides a wrapper around the MCP SDK server to simplify transport configuration and provide a consistent interface for both stdio and HTTP transports.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Server

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

func New

func New(server *mcpSDK.Server, opts ...WrapperOption) *Server

New wraps an SDK server with optional configuration. The transport can be configured using WithTransport option. HTTP options default to stateful + SSE, override with WithHTTPOptions().

func NewInMemoryServer

func NewInMemoryServer(server *mcpSDK.Server, opts ...WrapperOption) (*Server, *mcpSDK.InMemoryTransport)

NewInMemoryServer creates a server with in-memory transport for testing. Returns both the wrapped server and the client transport for connecting test clients. HTTP options default to stateful + SSE, override with WithHTTPOptions().

func (*Server) AddPrompt

func (s *Server) AddPrompt(prompt *mcpSDK.Prompt, handler mcpSDK.PromptHandler)

AddPrompt registers a prompt with the server

func (*Server) AddResource

func (s *Server) AddResource(resource *mcpSDK.Resource, handler mcpSDK.ResourceHandler)

AddResource registers a resource with the server

func (*Server) AddResourceTemplate

func (s *Server) AddResourceTemplate(template *mcpSDK.ResourceTemplate, handler mcpSDK.ResourceHandler)

AddResourceTemplate registers a resource template with the server

func (*Server) AddTool

func (s *Server) AddTool(tool *mcpSDK.Tool, handler mcpSDK.ToolHandler)

AddTool registers a tool with the server

func (*Server) GetTransport

func (s *Server) GetTransport() mcpSDK.Transport

GetTransport returns the currently configured transport for the server. Returns nil if no transport has been set.

This is useful for advanced use cases where access to the underlying transport is needed, such as integrating with external MCP client libraries.

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run starts the MCP server with the configured transport. If no transport was set via WithTransport(), defaults to StdioTransport.

func (*Server) ServeHTTP

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

ServeHTTP implements http.Handler for Streamable HTTP transport. Creates a StreamableHTTPHandler using the server's configured HTTP options.

func (*Server) Unwrap

func (s *Server) Unwrap() any

Unwrap returns the underlying SDK server for advanced usage

type ServerOption

type ServerOption func(*mcpSDK.ServerOptions)

ServerOption is a functional option for configuring mcp.ServerOptions.

func WithCapabilityPrompts

func WithCapabilityPrompts() ServerOption

WithCapabilityPrompts advertises the prompts capability during initialization, even if no prompts have been registered.

Example:

mcp.WithCapabilityPrompts()

func WithCapabilityResources

func WithCapabilityResources() ServerOption

WithCapabilityResources advertises the resources capability during initialization, even if no resources have been registered.

Example:

mcp.WithCapabilityResources()

func WithCapabilityTools

func WithCapabilityTools() ServerOption

WithCapabilityTools advertises the tools capability during initialization, even if no tools have been registered.

Example:

mcp.WithCapabilityTools()

func WithCompletionHandler

func WithCompletionHandler(handler func(context.Context, *mcpSDK.CompleteRequest) (*mcpSDK.CompleteResult, error)) ServerOption

WithCompletionHandler sets a handler called when "completion/complete" is received.

Example:

mcp.WithCompletionHandler(func(ctx context.Context, req *mcp.CompleteRequest) (*mcp.CompleteResult, error) {
    return &mcp.CompleteResult{Completion: completions}, nil
})

func WithInitializedHandler

func WithInitializedHandler(handler func(context.Context, *mcpSDK.InitializedRequest)) ServerOption

WithInitializedHandler sets a handler called when "notifications/initialized" is received.

Example:

mcp.WithInitializedHandler(func(ctx context.Context, req *mcp.InitializedRequest) {
    log.Println("Client initialized")
})

func WithInstructions

func WithInstructions(instructions string) ServerOption

WithInstructions sets optional instructions for connected clients.

Example:

mcp.WithInstructions("Use this server for data processing tasks")

func WithKeepAlive

func WithKeepAlive(duration time.Duration) ServerOption

WithKeepAlive sets the interval for regular "ping" requests.

If the peer fails to respond to pings originating from the keepalive check, the session is automatically closed.

Example:

mcp.WithKeepAlive(30 * time.Second)

func WithPageSize

func WithPageSize(pageSize int) ServerOption

WithPageSize sets the maximum number of items to return in a single page for list methods (e.g., ListTools).

If zero, defaults to the SDK's DefaultPageSize.

Example:

mcp.WithPageSize(50)

func WithProgressNotificationHandler

func WithProgressNotificationHandler(handler func(context.Context, *mcpSDK.ProgressNotificationServerRequest)) ServerOption

WithProgressNotificationHandler sets a handler called when "notifications/progress" is received.

Example:

mcp.WithProgressNotificationHandler(func(ctx context.Context, req *mcp.ProgressNotificationServerRequest) {
    log.Printf("Progress: %v\n", req)
})

func WithRootsListChangedHandler

func WithRootsListChangedHandler(handler func(context.Context, *mcpSDK.RootsListChangedRequest)) ServerOption

WithRootsListChangedHandler sets a handler called when "notifications/roots/list_changed" is received.

Example:

mcp.WithRootsListChangedHandler(func(ctx context.Context, req *mcp.RootsListChangedRequest) {
    log.Println("Roots list changed")
})

func WithServerLogger

func WithServerLogger(logger *slog.Logger) ServerOption

WithServerLogger sets the logger for server-side MCP protocol operations.

The logger receives events about internal server activity including connection lifecycle, message routing, protocol errors, and session management. Log output goes to your logging backend, NOT to the MCP client.

For logging that is visible to LLMs and MCP clients, use session.LogInfo(), session.LogWarning(), or session.LogError() in your tool handlers instead.

If not set, the SDK uses a discard logger (no output).

Example:

logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
    Level: slog.LevelDebug,
}))
mcp.WithServerLogger(logger)

func WithSessionIDGenerator

func WithSessionIDGenerator(generator func() string) ServerOption

WithSessionIDGenerator provides a custom function for generating session IDs.

Session IDs should be globally unique across the scope of the server, which may span multiple processes in the case of distributed servers.

As a special case, if the function returns an empty string, the Mcp-Session-Id header will not be set.

Example:

mcp.WithSessionIDGenerator(func() string {
    return uuid.New().String()
})

func WithSubscribeHandler

func WithSubscribeHandler(handler func(context.Context, *mcpSDK.SubscribeRequest) error) ServerOption

WithSubscribeHandler sets a handler called when a client session subscribes to a resource.

Example:

mcp.WithSubscribeHandler(func(ctx context.Context, req *mcp.SubscribeRequest) error {
    log.Printf("Client subscribed to: %s\n", req.Params.URI)
    return nil
})

func WithUnsubscribeHandler

func WithUnsubscribeHandler(handler func(context.Context, *mcpSDK.UnsubscribeRequest) error) ServerOption

WithUnsubscribeHandler sets a handler called when a client session unsubscribes from a resource.

Example:

mcp.WithUnsubscribeHandler(func(ctx context.Context, req *mcp.UnsubscribeRequest) error {
    log.Printf("Client unsubscribed from: %s\n", req.Params.URI)
    return nil
})

type TransportOptionStreamableHTTP

type TransportOptionStreamableHTTP func(*mcpSDK.StreamableHTTPOptions) error

TransportOptionStreamableHTTP is a functional option for configuring mcp.StreamableHTTPOptions.

func WithEventStore

func WithEventStore(store mcpSDK.EventStore) TransportOptionStreamableHTTP

WithEventStore enables SSE stream resumption using the provided EventStore.

Stream resumption allows clients with flaky connections (mobile, unreliable networks) to reconnect and continue receiving events from where they left off. The EventStore persists events for each session's streams.

By default (nil), stream resumption is disabled and events are only delivered once in real-time.

Use mcp.NewMemoryEventStore(nil) for single-server deployments. For multi-instance servers, implement a distributed EventStore using Redis, etcd, or similar.

Example:

eventStore := mcp.NewMemoryEventStore(nil)
mcp.WithEventStore(eventStore)

func WithHTTPLogger

func WithHTTPLogger(logger *slog.Logger) TransportOptionStreamableHTTP

WithHTTPLogger sets the logger for HTTP transport operations.

The logger receives events about HTTP transport activity including SSE stream lifecycle, session management, and HTTP request handling.

This is separate from server-side logging (WithServerLogger). You can set different loggers for server protocol events vs HTTP transport events.

If not set, the SDK uses a discard logger (no output).

Example:

logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
    Level: slog.LevelInfo,
}))
mcp.WithHTTPLogger(logger)

func WithHTTPSessionTimeout

func WithHTTPSessionTimeout(timeout time.Duration) TransportOptionStreamableHTTP

WithHTTPSessionTimeout sets the idle timeout for HTTP sessions.

When set, inactive sessions (no POST requests) are automatically closed after the specified duration to prevent resource leaks. The timeout is paused during active requests.

A zero value (default) means sessions never timeout.

Example:

mcp.WithHTTPSessionTimeout(5 * time.Minute)

func WithJSONResponse

func WithJSONResponse() TransportOptionStreamableHTTP

WithJSONResponse returns application/json instead of text/event-stream.

Per MCP spec §2.1.5, this causes streamable responses to return JSON rather than server-sent events.

Example:

mcp.WithJSONResponse()

func WithStateless

func WithStateless() TransportOptionStreamableHTTP

WithStateless makes the server stateless (no session validation).

A stateless server does not validate the Mcp-Session-Id header, and uses a temporary session with default initialization parameters. Any server->client request is rejected immediately as there's no way for the client to respond.

Example:

mcp.WithStateless()

type WrapperOption

type WrapperOption func(*Server)

WrapperOption configures a Server wrapper

func WithHTTPOptions

func WithHTTPOptions(opts *mcpSDK.StreamableHTTPOptions) WrapperOption

WithHTTPOptions sets custom HTTP transport options for the wrapper

func WithTransport

func WithTransport(transport mcpSDK.Transport) WrapperOption

WithTransport sets the transport for the wrapper

Jump to

Keyboard shortcuts

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