server

package
v1.2.7 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddTool added in v1.2.1

func AddTool[In, Out any](s *Server, tool *protocol.Tool, handler ToolHandlerFor[In, Out])

AddTool adds a tool and type-safe tool handler to the server.

This is a package-level function rather than a method on Server, because Go does not support method-level type parameters. For more information, see the Go generics proposal: https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md#no-parameterized-methods

If the tool's input schema is nil, it is inferred from the In type parameter. Types are inferred from Go types, and property descriptions are read from 'jsonschema' struct tags. Internally, the SDK uses the github.com/invopop/jsonschema package for inference and validation. The In type parameter must be a map or struct so that its inferred JSON Schema has the "object" type required by the specification. As a special case, if the In type is 'any', the tool's input schema is set to an empty object schema value.

If the tool's output schema is nil, and the Out type is not 'any', the output schema is inferred from the Out type parameter, which must also be a map or struct. If the Out type is 'any', the output schema is omitted.

Unlike Server.AddTool, AddTool automatically handles many things and enforces that tools conform to the MCP specification. For detailed automatic behaviors, see the documentation for ToolHandlerFor.

Example:

type Input struct {
    Name string `json:"name" jsonschema:"required,description=User name"`
}
type Output struct {
    Greeting string `json:"greeting" jsonschema:"required,description=Greeting message"`
}

server.AddTool[Input, Output](s, &protocol.Tool{
    Name:        "greet",
    Description: "Greet the user",
}, func(ctx context.Context, req *server.CallToolRequest, input Input) (
    *protocol.CallToolResult, Output, error,
) {
    return nil, Output{Greeting: "Hello, " + input.Name}, nil
})

func ApplySecurityDefaults added in v1.2.7

func ApplySecurityDefaults(s *Server, opts *SecurityDefaultsOptions)

ApplySecurityDefaults applies optional security defaults.

func ErrorResult added in v1.2.1

func ErrorResult(message string, err error) *protocol.CallToolResult

func GetBool added in v1.2.1

func GetBool(req *CallToolRequest, key string, defaultValue bool) bool

func GetFloat added in v1.2.1

func GetFloat(req *CallToolRequest, key string, defaultValue float64) float64

func GetInt added in v1.2.1

func GetInt(req *CallToolRequest, key string, defaultValue int) int

func GetInt64 added in v1.2.1

func GetInt64(req *CallToolRequest, key string, defaultValue int64) int64

func GetMap added in v1.2.1

func GetMap(req *CallToolRequest, key string, defaultValue map[string]interface{}) map[string]interface{}

func GetString added in v1.2.1

func GetString(req *CallToolRequest, key string, defaultValue string) string

func GetStringSlice added in v1.2.1

func GetStringSlice(req *CallToolRequest, key string, defaultValue []string) []string

func ImageResult added in v1.2.1

func ImageResult(data string, mimeType string) *protocol.CallToolResult

func JSONResult added in v1.2.1

func JSONResult(data interface{}) (*protocol.CallToolResult, error)

func MustGetBool added in v1.2.1

func MustGetBool(req *CallToolRequest, key string) (bool, error)

func MustGetInt added in v1.2.1

func MustGetInt(req *CallToolRequest, key string) (int, error)

func MustGetString added in v1.2.1

func MustGetString(req *CallToolRequest, key string) (string, error)

func ResourceResult added in v1.2.1

func ResourceResult(uri, mimeType, text string) *protocol.CallToolResult

func TextResult added in v1.2.1

func TextResult(text string) *protocol.CallToolResult

Types

type AuthValidator added in v1.2.1

type AuthValidator interface {
	Validate(authInfo interface{}, tool string) bool
}

AuthValidator is the authentication validator interface

type CallToolRequest added in v1.2.0

type CallToolRequest struct {
	// Session is the current session
	Session *ServerSession

	// Params are the original parameters
	Params *protocol.CallToolParams
}

CallToolRequest represents a tool call request, allowing tool handlers to send notifications

type Connection added in v1.2.0

type Connection interface {
	// SendNotification sends a notification to the client
	SendNotification(ctx context.Context, method string, params interface{}) error

	// SendRequest sends a request to the client and waits for a response
	SendRequest(ctx context.Context, method string, params interface{}, result interface{}) error

	Close() error

	SessionID() string
}

Connection represents the underlying transport connection

type ErrorCode added in v1.2.1

type ErrorCode string
const (
	// Client Error
	ErrInvalidParams  ErrorCode = "invalid_params"    // Invalid parameter
	ErrNotFound       ErrorCode = "not_found"         // Resource not found
	ErrUnauthorized   ErrorCode = "unauthorized"      // Unauthorized
	ErrForbidden      ErrorCode = "forbidden"         // Access Denied
	ErrConflict       ErrorCode = "conflict"          // Conflict
	ErrTooManyRequest ErrorCode = "too_many_requests" // Too many requests

	// Server error
	ErrInternal       ErrorCode = "internal_error"   // Internal Error
	ErrNotImplemented ErrorCode = "not_implemented"  // Unrealized
	ErrUnavailable    ErrorCode = "unavailable"      // Service Unavailable
	ErrTimeout        ErrorCode = "timeout"          // Timeout
	ErrDependency     ErrorCode = "dependency_error" // Dependency Service Error
)

type ErrorOption added in v1.2.1

type ErrorOption func(*ToolError)

func WithCause added in v1.2.1

func WithCause(cause error) ErrorOption

func WithDetail added in v1.2.1

func WithDetail(key string, value interface{}) ErrorOption

type FixedWindowRateLimiter added in v1.2.7

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

FixedWindowRateLimiter is a simple fixed-window rate limiter (per tool).

func NewFixedWindowRateLimiter added in v1.2.7

func NewFixedWindowRateLimiter(limit int, window time.Duration) *FixedWindowRateLimiter

NewFixedWindowRateLimiter creates a fixed-window rate limiter.

func (*FixedWindowRateLimiter) Allow added in v1.2.7

func (l *FixedWindowRateLimiter) Allow(tool string) bool

Allow implements RateLimiter

type GetPromptRequest added in v1.2.0

type GetPromptRequest struct {
	Session *ServerSession
	Params  *protocol.GetPromptParams
}

type MetricsCollector added in v1.2.1

type MetricsCollector interface {
	RecordToolCall(tool string, duration time.Duration, success bool)
}

MetricsCollector is the metrics collector interface

type Middleware added in v1.2.1

type Middleware func(ToolHandler) ToolHandler

func AuthMiddleware added in v1.2.1

func AuthMiddleware(validator AuthValidator) Middleware

AuthMiddleware is an authentication middleware

func LoggingMiddleware added in v1.2.1

func LoggingMiddleware(logger *slog.Logger) Middleware

LoggingMiddleware is a logging middleware

func MetricsMiddleware added in v1.2.1

func MetricsMiddleware(collector MetricsCollector) Middleware

MetricsMiddleware is a metrics middleware

func RateLimitMiddleware added in v1.2.1

func RateLimitMiddleware(limiter RateLimiter) Middleware

RateLimitMiddleware is a rate limiting middleware

func RecoveryMiddleware added in v1.2.1

func RecoveryMiddleware() Middleware

RecoveryMiddleware is a recovery middleware

func RetryMiddleware added in v1.2.1

func RetryMiddleware(maxRetries int, shouldRetry func(error) bool) Middleware

RetryMiddleware is a retry middleware

func TimeoutMiddleware added in v1.2.1

func TimeoutMiddleware(timeout time.Duration) Middleware

TimeoutMiddleware is a timeout middleware

func ValidationMiddleware added in v1.2.1

func ValidationMiddleware(validator ParamsValidator) Middleware

ValidationMiddleware is a parameter validation middleware

type ParamsValidator added in v1.2.1

type ParamsValidator interface {
	Validate(tool string, arguments map[string]any) error
}

type PromptHandler

type PromptHandler func(ctx context.Context, req *GetPromptRequest) (*protocol.GetPromptResult, error)

type RateLimiter added in v1.2.1

type RateLimiter interface {
	Allow(tool string) bool
}

RateLimiter is the rate limiter interface

type ReadResourceRequest added in v1.2.0

type ReadResourceRequest struct {
	Session *ServerSession
	Params  *protocol.ReadResourceParams
}

type ResourceHandler

type ResourceHandler func(ctx context.Context, req *ReadResourceRequest) (*protocol.ReadResourceResult, error)

type SecurityDefaultsOptions added in v1.2.7

type SecurityDefaultsOptions struct {
	Timeout          time.Duration
	RateLimit        int
	RateWindow       time.Duration
	Tokens           []string
	DisableTimeout   bool
	DisableRateLimit bool
}

SecurityDefaultsOptions provides one-click security defaults.

type Server

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

Server represents an MCP server instance that can serve one or more MCP sessions

func NewServer

func NewServer(impl *protocol.ServerInfo, opts *ServerOptions) *Server

func (*Server) AddPrompt added in v1.2.0

func (s *Server) AddPrompt(p *protocol.Prompt, h PromptHandler)

func (*Server) AddResource added in v1.2.0

func (s *Server) AddResource(r *protocol.Resource, h ResourceHandler)

func (*Server) AddResourceTemplate added in v1.2.0

func (s *Server) AddResourceTemplate(t *protocol.ResourceTemplate, h ResourceHandler)

func (*Server) AddTool added in v1.2.0

func (s *Server) AddTool(t *protocol.Tool, h ToolHandler)

AddTool adds a tool to the server, or replaces a tool with the same name (low-level API). The Tool parameter must not be modified after this call.

The tool's input schema must be non-nil and have type "object". For tools that accept no input or any input, set [Tool.InputSchema] to `{"type": "object"}` using your preferred library or `json.RawMessage`.

If [Tool.OutputSchema] exists, it must also have type "object".

When the handler is invoked as part of a CallTool request, req.Params.Arguments will be json.RawMessage.

It is the caller's responsibility to deserialize arguments and validate them against the input schema.

It is the caller's responsibility to validate the result against the output schema (if any).

It is the caller's responsibility to set the Content, StructuredContent, and IsError fields of the result.

Most users should use the top-level function AddTool, which handles all these responsibilities.

func (*Server) Connect added in v1.2.0

Connect connects the MCP server via the given transport and starts processing messages.

It returns a connection object that can be used to terminate the connection (using Close) or wait for the client to terminate (using Wait).

func (*Server) HandleMessage

func (s *Server) HandleMessage(ctx context.Context, msg *protocol.JSONRPCMessage) (*protocol.JSONRPCMessage, error)

HandleMessage implements the SSE Handler interface (for backward compatibility)

func (*Server) NotifyResourceUpdated added in v1.2.2

func (s *Server) NotifyResourceUpdated(uri string)

NotifyResourceUpdated notifies all sessions subscribed to the specified resource that it has been updated. Only clients that have previously called resources/subscribe to subscribe to this URI will receive the notification.

func (*Server) NotifyTaskStatus added in v1.2.5

func (s *Server) NotifyTaskStatus(task *protocol.Task)

NotifyTaskStatus sends a task status notification to all sessions (MCP 2025-11-25)

func (*Server) RemovePrompt added in v1.2.0

func (s *Server) RemovePrompt(name string)

func (*Server) RemoveResource added in v1.2.0

func (s *Server) RemoveResource(uri string)

func (*Server) RemoveResourceTemplate added in v1.2.0

func (s *Server) RemoveResourceTemplate(uriTemplate string)

func (*Server) RemoveTask added in v1.2.5

func (s *Server) RemoveTask(taskID string)

RemoveTask removes a task from the server's internal storage (MCP 2025-11-25)

func (*Server) RemoveTool added in v1.2.0

func (s *Server) RemoveTool(name string)

func (*Server) Run added in v1.2.0

func (s *Server) Run(ctx context.Context, t transport.Transport) error

Run runs the server on the given transport. This is a convenience method for handling a single session (or one session at a time).

Run blocks until the client terminates the connection or the provided context is cancelled. If the context is cancelled, Run will close the connection.

func (*Server) SetTaskResult added in v1.2.5

func (s *Server) SetTaskResult(taskID string, result any) error

SetTaskResult sets the result for a task (MCP 2025-11-25)

func (*Server) StoreTask added in v1.2.5

func (s *Server) StoreTask(task *protocol.Task, result any)

StoreTask stores a task in the server's internal storage (MCP 2025-11-25)

func (*Server) UpdateTask added in v1.2.5

func (s *Server) UpdateTask(taskID string, status protocol.TaskStatus, statusMessage string) error

UpdateTask updates a task in the server's internal storage (MCP 2025-11-25)

func (*Server) Use added in v1.2.1

func (s *Server) Use(middleware ...Middleware)

Use adds middleware to the Server. Middleware is executed in the order added (onion model).

type ServerOptions added in v1.2.0

type ServerOptions struct {
	// Optional client instructions
	Instructions string

	// Initialized handler function
	InitializedHandler func(context.Context, *ServerSession)

	// Progress notification handler function
	ProgressNotificationHandler func(context.Context, *ServerSession, *protocol.ProgressNotificationParams)

	// Elicitation complete notification handler (MCP 2025-11-25)
	ElicitationCompleteHandler func(context.Context, *ServerSession, *protocol.ElicitationCompleteNotificationParams)

	// Completion handler function
	CompletionHandler func(context.Context, *protocol.CompleteRequest) (*protocol.CompleteResult, error)

	// Logging level setting handler function
	LoggingSetLevelHandler func(context.Context, *ServerSession, protocol.LoggingLevel) error

	// Resource subscribe/unsubscribe handler functions
	SubscribeHandler   func(context.Context, *protocol.SubscribeParams) error
	UnsubscribeHandler func(context.Context, *protocol.UnsubscribeParams) error

	// KeepAlive defines the interval for periodic "ping" requests
	// If the peer fails to respond to a keepalive ping, the session will be closed automatically
	KeepAlive time.Duration

	// Tasks capability options (MCP 2025-11-25)
	TasksEnabled bool // Enable tasks support

	// TaskGetHandler handles tasks/get requests (MCP 2025-11-25)
	TaskGetHandler func(context.Context, *protocol.GetTaskParams) (*protocol.GetTaskResult, error)

	// TaskListHandler handles tasks/list requests (MCP 2025-11-25)
	TaskListHandler func(context.Context, *protocol.ListTasksParams) (*protocol.ListTasksResult, error)

	// TaskCancelHandler handles tasks/cancel requests (MCP 2025-11-25)
	TaskCancelHandler func(context.Context, *protocol.CancelTaskParams) (*protocol.CancelTaskResult, error)

	// TaskResultHandler handles tasks/result requests (MCP 2025-11-25)
	// Returns the original request's result type (e.g., *CallToolResult)
	TaskResultHandler func(context.Context, *protocol.TaskResultParams) (interface{}, error)
}

type ServerSession added in v1.2.0

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

ServerSession represents a server session, one ServerSession per client connection

func (*ServerSession) Close added in v1.2.0

func (ss *ServerSession) Close() error

func (*ServerSession) CreateMessage added in v1.2.0

CreateMessage sends a sampling request to the client

func (*ServerSession) Elicit added in v1.2.0

Elicit sends an elicitation request to the client, requesting user input

func (*ServerSession) ID added in v1.2.0

func (ss *ServerSession) ID() string

func (*ServerSession) InitializeParams added in v1.2.0

func (ss *ServerSession) InitializeParams() *protocol.InitializeParams

InitializeParams returns the initialization parameters

func (*ServerSession) ListRoots added in v1.2.0

func (ss *ServerSession) ListRoots(ctx context.Context) (*protocol.ListRootsResult, error)

ListRoots lists the client's root directories

func (*ServerSession) Log added in v1.2.0

Log sends a log message to the client

func (*ServerSession) NotifyProgress added in v1.2.0

func (ss *ServerSession) NotifyProgress(ctx context.Context, params *protocol.ProgressNotificationParams) error

NotifyProgress sends a progress notification to the client

func (*ServerSession) Ping added in v1.2.0

func (ss *ServerSession) Ping(ctx context.Context) error

Ping sends a ping request to the client

func (*ServerSession) Wait added in v1.2.0

func (ss *ServerSession) Wait() error

Wait waits for the session to end and returns the error that caused it to end

type ServerSessionOptions added in v1.2.0

type ServerSessionOptions struct {
	State *ServerSessionState
	// contains filtered or unexported fields
}

type ServerSessionState added in v1.2.0

type ServerSessionState struct {
	// InitializeParams are the parameters from the initialize request
	InitializeParams *protocol.InitializeParams

	// InitializedParams are the parameters from notifications/initialized
	InitializedParams *protocol.InitializedParams

	// LogLevel is the logging level
	LogLevel protocol.LoggingLevel
}

ServerSessionState represents session state

type TokenAuthValidator added in v1.2.7

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

TokenAuthValidator is a simple token validator based on req.Params.Meta["auth"].

func NewTokenAuthValidator added in v1.2.7

func NewTokenAuthValidator(tokens []string) *TokenAuthValidator

NewTokenAuthValidator creates a token validator.

func (*TokenAuthValidator) Validate added in v1.2.7

func (v *TokenAuthValidator) Validate(authInfo interface{}, tool string) bool

Validate implements AuthValidator

type ToolError added in v1.2.1

type ToolError struct {
	Code    ErrorCode
	Message string
	Details map[string]interface{}
	Cause   error
}

func ConflictError added in v1.2.1

func ConflictError(message string, opts ...ErrorOption) *ToolError

func DependencyError added in v1.2.1

func DependencyError(service string, err error, opts ...ErrorOption) *ToolError

func ForbiddenError added in v1.2.1

func ForbiddenError(message string, opts ...ErrorOption) *ToolError

func InternalError added in v1.2.1

func InternalError(message string, opts ...ErrorOption) *ToolError

func InvalidParamsError added in v1.2.1

func InvalidParamsError(message string, opts ...ErrorOption) *ToolError

func NewToolError added in v1.2.1

func NewToolError(code ErrorCode, message string, opts ...ErrorOption) *ToolError

func NotFoundError added in v1.2.1

func NotFoundError(resource string, opts ...ErrorOption) *ToolError

func NotImplementedError added in v1.2.1

func NotImplementedError(message string, opts ...ErrorOption) *ToolError

func TimeoutError added in v1.2.1

func TimeoutError(message string, opts ...ErrorOption) *ToolError

func UnauthorizedError added in v1.2.1

func UnauthorizedError(message string, opts ...ErrorOption) *ToolError

func UnavailableError added in v1.2.1

func UnavailableError(message string, opts ...ErrorOption) *ToolError

func (*ToolError) Error added in v1.2.1

func (e *ToolError) Error() string

Error Implement the error interface

func (*ToolError) ToResult added in v1.2.1

func (e *ToolError) ToResult() *protocol.CallToolResult

func (*ToolError) Unwrap added in v1.2.1

func (e *ToolError) Unwrap() error

Unwrap Implement errors.Unwrap

type ToolHandler

type ToolHandler func(ctx context.Context, req *CallToolRequest) (*protocol.CallToolResult, error)

ToolHandler is a tool handler function. It receives a CallToolRequest and can send notifications via req.Session.

type ToolHandlerFor added in v1.2.1

type ToolHandlerFor[In, Out any] func(
	ctx context.Context,
	req *CallToolRequest,
	input In,
) (result *protocol.CallToolResult, output Out, err error)

ToolHandlerFor is a type-safe handler function for tools/call requests.

Unlike ToolHandler, ToolHandlerFor provides many out-of-the-box features, and enforces that tools conform to the MCP specification:

  • The In type provides a default input schema for the tool (can be overridden in AddTool)
  • Input values are automatically deserialized from req.Params.Arguments
  • Input values are automatically validated against their schema, and invalid inputs are rejected before reaching the handler
  • If the Out type is not [any], it provides a default output schema for the tool (can also be overridden)
  • The Out value is used to populate result.StructuredContent
  • If [CallToolResult.Content] is not set, it is populated with the JSON content of the output
  • Error results are treated as tool errors rather than protocol errors, so they are wrapped in CallToolResult.Content, and the IsError flag is set

Therefore, most users can completely ignore the CallToolRequest parameter and [CallToolResult] return value. In fact, if you only care about returning an output value or error, returning a nil CallToolResult is allowed. Valid results are automatically populated as described above.

Use AddTool to add a ToolHandlerFor to a server.

Jump to

Keyboard shortcuts

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