mcpserver

package
v2.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: AGPL-3.0 Imports: 9 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ErrorCodeParseError     = -32700
	ErrorCodeInvalidRequest = -32600
	ErrorCodeMethodNotFound = -32601
	ErrorCodeInvalidParams  = -32602
	ErrorCodeInternalError  = -32603
)

Variables

View Source
var DefaultValidationOptions = ContentValidationOptions{
	MaxTextSize: 1024 * 1024 * 10,
	MaxBlobSize: 1024 * 1024 * 50,
	AllowedMIMETypes: []string{
		"text/plain",
		"text/markdown",
		"text/html",
		"application/json",
		"image/jpeg",
		"image/png",
		"image/gif",
		"image/webp",
	},
}

DefaultValidationOptions provides sensible defaults

View Source
var SupportedProtocolVersions = []string{"1.0"}

Add validation for protocol versions

Functions

This section is empty.

Types

type Annotated

type Annotated struct {
	Audience []Role  `json:"audience,omitempty"`
	Priority float64 `json:"priority,omitempty"`
}

type BaseNotification

type BaseNotification struct {
	Meta map[string]interface{} `json:"_meta,omitempty"`
}

BaseNotification contains common fields for all notifications

type BlobResourceContents

type BlobResourceContents struct {
	URI      string `json:"uri"`
	Blob     []byte `json:"blob"`
	MimeType string `json:"mimeType,omitempty"`
}

type CallToolRequest

type CallToolRequest struct {
	Name      string                 `json:"name"`
	Arguments map[string]interface{} `json:"arguments,omitempty"`
}

type CallToolResult

type CallToolResult struct {
	Content []interface{} `json:"content"` // Can contain TextContent, ImageContent, or EmbeddedResource
	IsError bool          `json:"isError,omitempty"`
}

type CancelledNotification

type CancelledNotification struct {
	BaseNotification
	RequestID string `json:"requestId"`
	Reason    string `json:"reason,omitempty"`
}

CancelledNotification represents a cancellation of a previous request

type ClientCapabilities

type ClientCapabilities struct {
	Roots *struct {
		ListChanged bool `json:"listChanged"`
	} `json:"roots,omitempty"`
	Sampling     *struct{}              `json:"sampling,omitempty"`
	Experimental map[string]interface{} `json:"experimental,omitempty"`
}

ClientCapabilities defines the capabilities supported by the client

type CompleteRequest

type CompleteRequest struct {
	Argument struct {
		Name  string `json:"name"`
		Value string `json:"value"`
	} `json:"argument"`
	Ref interface{} `json:"ref"` // Can be PromptReference or ResourceReference
}

type CompleteResult

type CompleteResult struct {
	Completion struct {
		Values  []string `json:"values"`
		HasMore bool     `json:"hasMore,omitempty"`
		Total   int      `json:"total,omitempty"`
	} `json:"completion"`
}

type ContentValidationOptions

type ContentValidationOptions struct {
	MaxTextSize      int64    // Maximum size for text content in bytes
	MaxBlobSize      int64    // Maximum size for blob content in bytes
	AllowedMIMETypes []string // List of allowed MIME types (empty means all allowed)
}

ContentValidationOptions contains configurable validation rules

type CreateMessageRequest

type CreateMessageRequest struct {
	Messages         []SamplingMessage `json:"messages"`
	MaxTokens        int               `json:"maxTokens"`
	Temperature      float64           `json:"temperature,omitempty"`
	StopSequences    []string          `json:"stopSequences,omitempty"`
	SystemPrompt     string            `json:"systemPrompt,omitempty"`
	IncludeContext   string            `json:"includeContext,omitempty"`
	ModelPreferences ModelPreferences  `json:"modelPreferences,omitempty"`
	Metadata         interface{}       `json:"metadata,omitempty"`
}

type CreateMessageResult

type CreateMessageResult struct {
	Content    interface{} `json:"content"` // Can be TextContent or ImageContent
	Model      string      `json:"model"`
	Role       Role        `json:"role"`
	StopReason string      `json:"stopReason,omitempty"`
}

type EmbeddedResource

type EmbeddedResource struct {
	Type        string      `json:"type"`     // Must be "resource"
	Resource    interface{} `json:"resource"` // Can be TextResourceContents or BlobResourceContents
	Annotations *Annotated  `json:"annotations,omitempty"`
}

type GetPromptRequest

type GetPromptRequest struct {
	Name      string            `json:"name"`
	Arguments map[string]string `json:"arguments,omitempty"`
}

type GetPromptResult

type GetPromptResult struct {
	Messages    []PromptMessage `json:"messages"`
	Description string          `json:"description,omitempty"`
}

type ImageContent

type ImageContent struct {
	Type        string     `json:"type"` // Must be "image"
	Data        []byte     `json:"data"`
	MimeType    string     `json:"mimeType"`
	Annotations *Annotated `json:"annotations,omitempty"`
}

type Implementation

type Implementation struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

Implementation describes the name and version of an MCP implementation

type InitializeResult

type InitializeResult struct {
	ServerInfo      Implementation     `json:"serverInfo"`
	Capabilities    ServerCapabilities `json:"capabilities"`
	ProtocolVersion string             `json:"protocolVersion"`
	Instructions    string             `json:"instructions,omitempty"`
}

Result types

type InitializedNotification

type InitializedNotification struct {
	BaseNotification
}

InitializedNotification represents the client's initialized notification

type JSONRPCError

type JSONRPCError struct {
	JSONRPC string      `json:"jsonrpc"`
	ID      interface{} `json:"id"`
	Error   struct {
		Code    int         `json:"code"`
		Message string      `json:"message"`
		Data    interface{} `json:"data,omitempty"`
	} `json:"error"`
}

JSONRPCError represents a JSON-RPC 2.0 error response

type JSONRPCNotification

type JSONRPCNotification struct {
	JSONRPC string      `json:"jsonrpc"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params"`
}

JSONRPCNotification represents a JSON-RPC 2.0 notification

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      interface{}     `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

JSONRPCRequest represents a JSON-RPC 2.0 request

type JSONRPCResponse

type JSONRPCResponse struct {
	JSONRPC string      `json:"jsonrpc"`
	ID      interface{} `json:"id"`
	Result  interface{} `json:"result"`
}

JSONRPCResponse represents a JSON-RPC 2.0 response

type ListPromptsRequest

type ListPromptsRequest struct {
	Cursor string `json:"cursor,omitempty"`
}

type ListPromptsResult

type ListPromptsResult struct {
	Prompts    []Prompt `json:"prompts"`
	NextCursor string   `json:"nextCursor,omitempty"`
}

type ListResourcesRequest

type ListResourcesRequest struct {
	Cursor string `json:"cursor,omitempty"`
}

Request types

type ListResourcesResult

type ListResourcesResult struct {
	Resources  []Resource `json:"resources"`
	NextCursor string     `json:"nextCursor,omitempty"`
}

type ListToolsRequest

type ListToolsRequest struct {
	Cursor string `json:"cursor,omitempty"`
}

type ListToolsResult

type ListToolsResult struct {
	Tools      []Tool `json:"tools"`
	NextCursor string `json:"nextCursor,omitempty"`
}

type LoggingLevel

type LoggingLevel string
const (
	LoggingLevelEmergency LoggingLevel = "emergency"
	LoggingLevelAlert     LoggingLevel = "alert"
	LoggingLevelCritical  LoggingLevel = "critical"
	LoggingLevelError     LoggingLevel = "error"
	LoggingLevelWarning   LoggingLevel = "warning"
	LoggingLevelNotice    LoggingLevel = "notice"
	LoggingLevelInfo      LoggingLevel = "info"
	LoggingLevelDebug     LoggingLevel = "debug"
)

type LoggingMessageNotification

type LoggingMessageNotification struct {
	BaseNotification
	Level  LoggingLevel `json:"level"`
	Data   interface{}  `json:"data"`
	Logger string       `json:"logger,omitempty"`
}

LoggingMessageNotification represents a logging message from the server

type ModelHint

type ModelHint struct {
	Name string `json:"name,omitempty"`
}

type ModelPreferences

type ModelPreferences struct {
	SpeedPriority        float64     `json:"speedPriority,omitempty"`
	CostPriority         float64     `json:"costPriority,omitempty"`
	IntelligencePriority float64     `json:"intelligencePriority,omitempty"`
	Hints                []ModelHint `json:"hints,omitempty"`
}

Sampling related types

type NotificationHandler

type NotificationHandler func(context.Context, interface{}) error

NotificationHandler is called when the server needs to send a notification to the client

type NotificationSender

type NotificationSender interface {
	SendResourceUpdate(ctx context.Context, uri string) error
	SendResourceListChanged(ctx context.Context) error
	SendPromptListChanged(ctx context.Context) error
	SendToolListChanged(ctx context.Context) error
	SendProgress(ctx context.Context, token string, progress, total float64) error
	SendLoggingMessage(ctx context.Context, level LoggingLevel, data interface{}, logger string) error
}

type NotificationType

type NotificationType string

NotificationType represents all possible notification methods

const (
	NotificationCancelled           NotificationType = "notifications/cancelled"
	NotificationInitialized         NotificationType = "notifications/initialized"
	NotificationProgress            NotificationType = "notifications/progress"
	NotificationResourceListChanged NotificationType = "notifications/resources/list_changed"
	NotificationResourceUpdated     NotificationType = "notifications/resources/updated"
	NotificationPromptListChanged   NotificationType = "notifications/prompts/list_changed"
	NotificationToolListChanged     NotificationType = "notifications/tools/list_changed"
	NotificationLoggingMessage      NotificationType = "notifications/logging/message"
)

type ProgressNotification

type ProgressNotification struct {
	BaseNotification
	Progress      float64 `json:"progress"`
	ProgressToken string  `json:"progressToken"`
	Total         float64 `json:"total,omitempty"`
}

ProgressNotification represents progress on a long-running operation

type Prompt

type Prompt struct {
	Name        string           `json:"name"`
	Description string           `json:"description,omitempty"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

Prompt related types

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

type PromptListChangedNotification

type PromptListChangedNotification struct {
	BaseNotification
}

PromptListChangedNotification represents a change in the prompt list

type PromptMessage

type PromptMessage struct {
	Role    Role        `json:"role"`
	Content interface{} `json:"content"` // Can be TextContent, ImageContent, or EmbeddedResource
}

type PromptReference

type PromptReference struct {
	Type string `json:"type"` // Must be "ref/prompt"
	Name string `json:"name"`
}

type ReadResourceRequest

type ReadResourceRequest struct {
	URI string `json:"uri"`
}

type ReadResourceResult

type ReadResourceResult struct {
	Contents []interface{} `json:"contents"` // Can contain TextResourceContents or BlobResourceContents
}

type RequestError

type RequestError struct {
	Code    int
	Message string
}

func (*RequestError) Error

func (e *RequestError) Error() string

type Resource

type Resource struct {
	Name        string     `json:"name"`
	URI         string     `json:"uri"`
	MimeType    string     `json:"mimeType,omitempty"`
	Description string     `json:"description,omitempty"`
	Annotations *Annotated `json:"annotations,omitempty"`
}

Resource related types

type ResourceListChangedNotification

type ResourceListChangedNotification struct {
	BaseNotification
}

ResourceListChangedNotification represents a change in the resource list

type ResourceReference

type ResourceReference struct {
	Type string `json:"type"` // Must be "ref/resource"
	URI  string `json:"uri"`
}

type ResourceSubscriber

type ResourceSubscriber struct {
	URI      string
	Callback func(string)
}

ResourceSubscriber represents a subscription to resource updates

type ResourceTemplate

type ResourceTemplate struct {
	Name        string     `json:"name"`
	URITemplate string     `json:"uriTemplate"`
	MimeType    string     `json:"mimeType,omitempty"`
	Description string     `json:"description,omitempty"`
	Annotations *Annotated `json:"annotations,omitempty"`
}

type ResourceUpdatedNotification

type ResourceUpdatedNotification struct {
	BaseNotification
	URI string `json:"uri"`
}

ResourceUpdatedNotification represents an update to a specific resource

type Role

type Role string

Common types

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

type SamplingMessage

type SamplingMessage struct {
	Role    Role        `json:"role"`
	Content interface{} `json:"content"` // Can be TextContent or ImageContent
}

type Server

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

Server represents an MCP server instance

func NewServer

func NewServer(config ServerConfig) *Server

NewServer creates a new MCP server instance

func (*Server) HandleRequest

func (s *Server) HandleRequest(ctx context.Context, request []byte) ([]byte, error)

HandleRequest processes an incoming JSON-RPC request

func (*Server) NotifyResourceListChanged

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

NotifyResourceListChanged sends a notification that the resource list has changed

func (*Server) NotifyResourceUpdate

func (s *Server) NotifyResourceUpdate(ctx context.Context, uri string)

NotifyResourceUpdate sends a resource update notification to subscribers

func (*Server) SendNotification

func (s *Server) SendNotification(ctx context.Context, notificationType NotificationType, params interface{}) error

func (*Server) SendResourceUpdate

func (s *Server) SendResourceUpdate(ctx context.Context, uri string) error

Implement all notification methods

type ServerCapabilities

type ServerCapabilities struct {
	Logging   *struct{} `json:"logging,omitempty"`
	Resources *struct {
		ListChanged bool `json:"listChanged"`
		Subscribe   bool `json:"subscribe"`
	} `json:"resources,omitempty"`
	Prompts *struct {
		ListChanged bool `json:"listChanged"`
	} `json:"prompts,omitempty"`
	Tools *struct {
		ListChanged bool `json:"listChanged"`
	} `json:"tools,omitempty"`
	Experimental map[string]interface{} `json:"experimental,omitempty"`
}

ServerCapabilities defines the capabilities supported by the server

type ServerConfig

type ServerConfig struct {
	Implementation      Implementation
	Capabilities        ServerCapabilities
	Handler             ServerHandler
	NotificationHandler NotificationHandler
	ValidationOptions   *ContentValidationOptions
}

ServerConfig contains the configuration for a new server

type ServerHandler

type ServerHandler interface {
	// Resource methods
	ListResources(ctx context.Context, cursor string) ([]Resource, string, error)
	ReadResource(ctx context.Context, uri string) ([]interface{}, error)
	SubscribeResource(ctx context.Context, uri string, callback func(string)) error
	UnsubscribeResource(ctx context.Context, uri string) error

	// Prompt methods
	ListPrompts(ctx context.Context, cursor string) ([]Prompt, string, error)
	GetPrompt(ctx context.Context, name string, args map[string]string) (*GetPromptResult, error)

	// Tool methods
	ListTools(ctx context.Context, cursor string) ([]Tool, string, error)
	CallTool(ctx context.Context, name string, args map[string]interface{}) (*CallToolResult, error)

	// Completion method
	Complete(ctx context.Context, req CompleteRequest) (*CompleteResult, error)

	// Sampling method
	CreateMessage(ctx context.Context, req CreateMessageRequest) (*CreateMessageResult, error)
}

ServerHandler defines the interface that must be implemented to provide server functionality

type SetLevelRequest

type SetLevelRequest struct {
	Level LoggingLevel `json:"level"`
}

type SubscribeRequest

type SubscribeRequest struct {
	URI string `json:"uri"`
}

type SubscriptionResponse

type SubscriptionResponse struct {
	SubscriptionID string `json:"subscriptionId"`
}

SubscriptionResponse represents a response to a subscription request

type TextContent

type TextContent struct {
	Type        string     `json:"type"` // Must be "text"
	Text        string     `json:"text"`
	Annotations *Annotated `json:"annotations,omitempty"`
}

Content types

type TextResourceContents

type TextResourceContents struct {
	URI      string `json:"uri"`
	Text     string `json:"text"`
	MimeType string `json:"mimeType,omitempty"`
}

type Tool

type Tool struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	InputSchema map[string]interface{} `json:"inputSchema"`
}

Tool related types

type ToolListChangedNotification

type ToolListChangedNotification struct {
	BaseNotification
}

ToolListChangedNotification represents a change in the tool list

type UnsubscribeRequest

type UnsubscribeRequest struct {
	URI string `json:"uri"`
}

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents an error during validation

func (*ValidationError) Error

func (e *ValidationError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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