protocol

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2025 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package protocol defines the structures and constants for the Model Context Protocol (MCP).

Package protocol defines the structures and constants for the Model Context Protocol (MCP).

Package protocol defines the structures and constants for the Model Context Protocol (MCP), based on the JSON-RPC 2.0 specification.

Package protocol defines the structures and constants for the Model Context Protocol (MCP).

Package protocol defines the structures and constants for the Model Context Protocol (MCP).

Package protocol defines the structures and constants for the Model Context Protocol (MCP).

Package protocol defines the structures and constants for the Model Context Protocol (MCP).

Index

Constants

View Source
const (
	// CurrentProtocolVersion defines the MCP version this library implementation supports.
	CurrentProtocolVersion = "2025-03-26" // The primary version this server implements
	OldProtocolVersion     = "2024-11-05" // An older version accepted for compatibility

	// Initialization
	MethodInitialize  = "initialize"
	MethodInitialized = "initialized" // Notification

	// Tools
	MethodListTools              = "tools/list"
	MethodCallTool               = "tools/call"
	MethodNotifyToolsListChanged = "notifications/tools/list_changed" // Notification

	// Resources
	MethodListResources              = "resources/list"
	MethodReadResource               = "resources/read"
	MethodSubscribeResource          = "resources/subscribe"                  // Request
	MethodUnsubscribeResource        = "resources/unsubscribe"                // Request (Optional, can use subscribe with empty list)
	MethodNotifyResourcesListChanged = "notifications/resources/list_changed" // Notification
	MethodNotifyResourceUpdated      = "notifications/resources/updated"      // Notification (Renamed from changed)

	// Prompts
	MethodListPrompts              = "prompts/list"
	MethodGetPrompt                = "prompts/get"
	MethodNotifyPromptsListChanged = "notifications/prompts/list_changed" // Notification

	// Logging
	MethodLoggingSetLevel     = "logging/set_level"
	MethodNotificationMessage = "notifications/message" // Note: This is a notification

	// Sampling
	MethodSamplingCreateMessage = "sampling/create_message"

	// Roots
	MethodRootsList              = "roots/list"
	MethodNotifyRootsListChanged = "notifications/roots/list_changed" // Notification

	// Ping
	MethodPing = "ping"

	// Cancellation & Progress (Notifications)
	MethodCancelled = "$/cancelled"
	MethodProgress  = "$/progress"

	// MessageTypeError identifies an Error message (conceptually).
	MessageTypeError = "Error" // This might become irrelevant
)
View Source
const (
	// --- Standard JSON-RPC Error Codes ---
	ErrorCodeParseError     = -32700
	ErrorCodeInvalidRequest = -32600
	ErrorCodeMethodNotFound = -32601
	ErrorCodeInvalidParams  = -32602
	ErrorCodeInternalError  = -32603

	// --- MCP / Implementation-Defined Error Codes (Example Range) ---
	// Using -32000 range for MCP/implementation specific errors
	ErrorCodeMCPHandshakeFailed            = -32000 // Custom code for handshake phase errors (will become Initialize errors)
	ErrorCodeMCPUnsupportedProtocolVersion = -32001 // Custom code for version mismatch
	ErrorCodeMCPInvalidMessage             = -32002 // Custom code for structurally invalid MCP message (before JSON check)
	ErrorCodeMCPInvalidPayload             = -32003 // Custom code for invalid MCP payload structure
	ErrorCodeMCPNotImplemented             = -32004 // Custom code for unimplemented MCP features/methods
	ErrorCodeMCPToolNotFound               = -32010 // Custom code for tool not found
	ErrorCodeMCPInvalidArgument            = -32011 // Custom code for invalid tool arguments
	ErrorCodeMCPToolExecutionError         = -32012 // Custom code for error during tool run
	ErrorCodeMCPAuthenticationFailed       = -32020 // Custom code for auth failure
	ErrorCodeMCPRateLimitExceeded          = -32021 // Custom code for rate limit exceeded
	ErrorCodeMCPSecurityViolation          = -32030 // Custom code for security issues (e.g., sandbox escape)
	ErrorCodeMCPOperationFailed            = -32031 // Custom code for general operation failure (e.g., file IO)
	ErrorCodeMCPResourceNotFound           = -32040 // Placeholder
	ErrorCodeMCPAccessDenied               = -32041 // Placeholder
)

Variables

This section is empty.

Functions

func UnmarshalPayload

func UnmarshalPayload(payload interface{}, target interface{}) error

UnmarshalPayload is a helper function to unmarshal the payload field from a received JSON-RPC params or result field (which is interface{}) into a specific Go struct pointed to by 'target'. It handles the case where the payload might be nil or needs re-marshalling.

Types

type AudioContent

type AudioContent struct {
	Type        string              `json:"type"` // Should always be "audio"
	Data        string              `json:"data"`
	MediaType   string              `json:"mediaType"`
	Annotations *ContentAnnotations `json:"annotations,omitempty"`
}

AudioContent represents audio content.

func (AudioContent) GetType

func (ac AudioContent) GetType() string

type BlobResourceContents

type BlobResourceContents struct {
	ContentType string `json:"contentType"` // e.g., "image/png", "application/octet-stream"
	Blob        string `json:"blob"`        // Base64 encoded string
}

BlobResourceContents holds binary resource content (base64 encoded).

func (BlobResourceContents) GetContentType

func (brc BlobResourceContents) GetContentType() string

type CallToolParams

type CallToolParams struct {
	Name      string                 `json:"name"`
	Arguments map[string]interface{} `json:"arguments,omitempty"`
	Meta      *RequestMeta           `json:"_meta,omitempty"` // Defined in messages.go
}

CallToolParams defines the parameters for a 'tools/call' request.

type CallToolResult

type CallToolResult struct {
	Content []Content    `json:"content"` // Defined in messages.go
	IsError *bool        `json:"isError,omitempty"`
	Meta    *RequestMeta `json:"_meta,omitempty"` // Defined in messages.go
}

CallToolResult defines the result payload for a successful 'tools/call' response.

func (*CallToolResult) UnmarshalJSON

func (r *CallToolResult) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshalling for CallToolResult to handle the Content interface slice.

type CancelledParams

type CancelledParams struct {
	ID interface{} `json:"id"`
}

CancelledParams defines the parameters for the '$/cancelled' notification.

type ClientCapabilities

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

ClientCapabilities describes features the client supports.

type Content

type Content interface {
	GetType() string
}

Content defines the interface for different types of content in results/prompts.

type ContentAnnotations

type ContentAnnotations struct {
	Title    *string  `json:"title,omitempty"`
	Audience []string `json:"audience,omitempty"`
	Priority *float64 `json:"priority,omitempty"`
}

ContentAnnotations defines optional metadata for content parts.

type CreateMessageRequestParams

type CreateMessageRequestParams struct {
	Context     []SamplingMessage `json:"context"`
	Preferences *ModelPreferences `json:"preferences,omitempty"`
}

CreateMessageRequestParams defines parameters for 'sampling/create_message'.

type CreateMessageResult

type CreateMessageResult struct {
	Message   SamplingMessage `json:"message"`
	ModelHint *ModelHint      `json:"modelHint,omitempty"`
}

CreateMessageResult defines the result for 'sampling/create_message'.

type EmbeddedResourceContent

type EmbeddedResourceContent struct {
	Type        string              `json:"type"` // Should always be "resource"
	Resource    Resource            `json:"resource"`
	Annotations *ContentAnnotations `json:"annotations,omitempty"`
}

EmbeddedResourceContent represents an embedded resource.

func (EmbeddedResourceContent) GetType

func (erc EmbeddedResourceContent) GetType() string

type ErrorMessage

type ErrorMessage struct {
	Payload ErrorPayload `json:"error"` // Field name MUST be "error" for JSON-RPC compliance
}

ErrorMessage represents an MCP Error message conceptually. The actual message sent is a JSONRPCResponse with the 'error' field populated.

type ErrorPayload

type ErrorPayload struct {
	Code    int         `json:"code"`           // Numeric error code (JSON-RPC standard or implementation-defined)
	Message string      `json:"message"`        // Short error description
	Data    interface{} `json:"data,omitempty"` // Optional additional error details
}

ErrorPayload defines the structure for the 'error' object within a JSONRPCError response, aligning with the JSON-RPC 2.0 specification used by MCP.

type GetPromptRequestParams

type GetPromptRequestParams struct {
	URI       string                 `json:"uri"`
	Arguments map[string]interface{} `json:"arguments,omitempty"`
}

GetPromptRequestParams defines parameters for 'prompts/get'.

type GetPromptResult

type GetPromptResult struct {
	Prompt Prompt `json:"prompt"`
}

GetPromptResult defines the result for 'prompts/get'.

type ImageContent

type ImageContent struct {
	Type        string              `json:"type"` // Should always be "image"
	Data        string              `json:"data"`
	MediaType   string              `json:"mediaType"`
	Annotations *ContentAnnotations `json:"annotations,omitempty"`
}

ImageContent represents image content.

func (ImageContent) GetType

func (ic ImageContent) GetType() string

type Implementation

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

Implementation describes the name and version of an MCP implementation (client or server).

type InitializeRequestParams

type InitializeRequestParams struct {
	ProtocolVersion  string             `json:"protocolVersion"`
	Capabilities     ClientCapabilities `json:"capabilities"`
	ClientInfo       Implementation     `json:"clientInfo"`
	Trace            *string            `json:"trace,omitempty"`
	WorkspaceFolders []WorkspaceFolder  `json:"workspaceFolders,omitempty"`
}

InitializeRequestParams defines the parameters for the 'initialize' request.

type InitializeResult

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

InitializeResult defines the result payload for a successful 'initialize' response.

type InitializedNotificationParams

type InitializedNotificationParams struct{}

InitializedNotificationParams is the payload for the 'initialized' notification (empty).

type JSONRPCNotification

type JSONRPCNotification struct {
	JSONRPC string      `json:"jsonrpc"`          // MUST be "2.0"
	Method  string      `json:"method"`           // Method name (e.g., "initialized", "notifications/...")
	Params  interface{} `json:"params,omitempty"` // Parameters (struct or array)

}

JSONRPCNotification represents a standard JSON-RPC notification object.

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string      `json:"jsonrpc"`          // MUST be "2.0"
	ID      interface{} `json:"id"`               // Request ID (string, number, or null)
	Method  string      `json:"method"`           // Method name (e.g., "initialize", "tools/call")
	Params  interface{} `json:"params,omitempty"` // Parameters (struct or array)
}

JSONRPCRequest represents a standard JSON-RPC request object.

type JSONRPCResponse

type JSONRPCResponse struct {
	JSONRPC string        `json:"jsonrpc"`          // MUST be "2.0"
	ID      interface{}   `json:"id"`               // MUST be the same as the request ID (or null if error before ID parsing)
	Result  interface{}   `json:"result,omitempty"` // Result object (on success)
	Error   *ErrorPayload `json:"error,omitempty"`  // Error object (on failure)
}

JSONRPCResponse represents a standard JSON-RPC response object.

type ListPromptsRequestParams

type ListPromptsRequestParams struct {
	Filter map[string]interface{} `json:"filter,omitempty"`
	Cursor string                 `json:"cursor,omitempty"`
}

ListPromptsRequestParams defines parameters for 'prompts/list'.

type ListPromptsResult

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

ListPromptsResult defines the result for 'prompts/list'.

type ListResourcesRequestParams

type ListResourcesRequestParams struct {
	Filter map[string]interface{} `json:"filter,omitempty"`
	Cursor string                 `json:"cursor,omitempty"`
}

ListResourcesRequestParams defines parameters for 'resources/list'.

type ListResourcesResult

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

ListResourcesResult defines the result for 'resources/list'.

type ListRootsRequestParams

type ListRootsRequestParams struct{}

ListRootsRequestParams defines parameters for 'roots/list'. (Currently empty)

type ListRootsResult

type ListRootsResult struct {
	Roots []Root `json:"roots"`
}

ListRootsResult defines the result for 'roots/list'.

type ListToolsRequestParams

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

ListToolsRequestParams defines the parameters for a 'tools/list' request.

type ListToolsResult

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

ListToolsResult defines the result payload for a successful 'tools/list' response.

type LoggingLevel

type LoggingLevel string

LoggingLevel defines the possible logging levels.

const (
	LogLevelError LoggingLevel = "error"
	LogLevelWarn  LoggingLevel = "warn"
	LogLevelInfo  LoggingLevel = "info"
	LogLevelDebug LoggingLevel = "debug"
	LogLevelTrace LoggingLevel = "trace"
)

type LoggingMessageParams

type LoggingMessageParams struct {
	Level   LoggingLevel `json:"level"`
	Message string       `json:"message"`
}

LoggingMessageParams defines parameters for 'notifications/message'.

type MCPError

type MCPError struct {
	ErrorPayload
}

MCPError wraps ErrorPayload to implement the error interface. Handlers can return this type to provide specific JSON-RPC error details.

func (*MCPError) Error

func (e *MCPError) Error() string

Error implements the error interface for MCPError.

type ModelHint

type ModelHint struct {
	ModelURI     string  `json:"modelUri"`
	InputTokens  *int    `json:"inputTokens,omitempty"`
	OutputTokens *int    `json:"outputTokens,omitempty"`
	FinishReason *string `json:"finishReason,omitempty"`
}

ModelHint provides information about the model used for a response.

type ModelPreferences

type ModelPreferences struct {
	ModelURI    string   `json:"modelUri,omitempty"`
	Temperature *float64 `json:"temperature,omitempty"`
	TopP        *float64 `json:"topP,omitempty"`
	TopK        *int     `json:"topK,omitempty"`
}

ModelPreferences specifies desired model characteristics.

type ProgressParams

type ProgressParams struct {
	Token   string      `json:"token"`
	Value   interface{} `json:"value"`
	Message *string     `json:"message,omitempty"` // Added for 2025-03-26
}

ProgressParams defines the parameters for the '$/progress' notification.

type Prompt

type Prompt struct {
	URI         string                 `json:"uri"`
	Title       string                 `json:"title,omitempty"`
	Description string                 `json:"description,omitempty"`
	Arguments   []PromptArgument       `json:"arguments,omitempty"`
	Messages    []PromptMessage        `json:"messages"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

Prompt represents a prompt template available from the server.

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Type        string `json:"type"` // e.g., "string", "number", "boolean"
	Required    bool   `json:"required,omitempty"`
}

PromptArgument defines an input parameter for a prompt template.

type PromptMessage

type PromptMessage struct {
	Role    string    `json:"role"`    // e.g., "system", "user", "assistant"
	Content []Content `json:"content"` // Defined in messages.go
}

PromptMessage represents a single message within a prompt sequence.

func (*PromptMessage) UnmarshalJSON

func (pm *PromptMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshalling for PromptMessage to handle the Content interface slice.

type PromptReference

type PromptReference struct {
	URI       string                 `json:"uri"`
	Arguments map[string]interface{} `json:"arguments,omitempty"`
}

PromptReference allows referencing a prompt, potentially with arguments.

type PromptsListChangedParams

type PromptsListChangedParams struct{}

PromptsListChangedParams defines parameters for 'notifications/prompts/list_changed'.

type PropertyDetail

type PropertyDetail struct {
	Type        string        `json:"type"`
	Description string        `json:"description,omitempty"`
	Enum        []interface{} `json:"enum,omitempty"`   // Possible values for the property
	Format      string        `json:"format,omitempty"` // Specific format (e.g., "date-time", "email")
}

PropertyDetail describes a single parameter within a ToolInputSchema.

type ReadResourceRequestParams

type ReadResourceRequestParams struct {
	URI     string `json:"uri"`
	Version string `json:"version,omitempty"`
}

ReadResourceRequestParams defines parameters for 'resources/read'.

type ReadResourceResult

type ReadResourceResult struct {
	Resource Resource         `json:"resource"`
	Contents ResourceContents `json:"contents"` // Actual content (Text or Blob)
}

ReadResourceResult defines the result for 'resources/read'.

type RequestMeta

type RequestMeta struct {
	// Use interface{} to accept string or number, per spec.
	ProgressToken interface{} `json:"progressToken,omitempty"`
}

RequestMeta contains metadata associated with a request, like a progress token.

type Resource

type Resource struct {
	URI         string                 `json:"uri"`                   // Unique identifier (e.g., "file:///path/to/file", "git://...?rev=...")
	Kind        string                 `json:"kind,omitempty"`        // e.g., "file", "git_commit", "api_spec"
	Title       string                 `json:"title,omitempty"`       // Human-readable title
	Description string                 `json:"description,omitempty"` // Longer description
	Version     string                 `json:"version,omitempty"`     // Opaque version string (changes when content changes)
	Metadata    map[string]interface{} `json:"metadata,omitempty"`    // Additional arbitrary metadata
	Size        *int                   `json:"size,omitempty"`        // Optional size in bytes (added in 2025-03-26)
}

Resource represents a piece of context available from the server.

type ResourceContents

type ResourceContents interface {
	GetContentType() string
}

ResourceContents defines the interface for different types of resource content.

type ResourceUpdatedParams

type ResourceUpdatedParams struct {
	Resource Resource `json:"resource"`
}

ResourceUpdatedParams defines parameters for 'notifications/resources/updated'.

type ResourcesListChangedParams

type ResourcesListChangedParams struct{}

ResourcesListChangedParams defines parameters for 'notifications/resources/list_changed'.

type Root

type Root struct {
	URI         string                 `json:"uri"`
	Kind        string                 `json:"kind,omitempty"`
	Title       string                 `json:"title,omitempty"`
	Description string                 `json:"description,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

Root represents a root context or workspace available on the client.

type RootsListChangedParams

type RootsListChangedParams struct{}

RootsListChangedParams defines parameters for 'notifications/roots/list_changed'.

type SamplingMessage

type SamplingMessage struct {
	Role    string    `json:"role"`
	Content []Content `json:"content"`
	Name    *string   `json:"name,omitempty"`
}

SamplingMessage represents a message in the context provided for sampling.

func (*SamplingMessage) UnmarshalJSON

func (sm *SamplingMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshalling for SamplingMessage to handle the Content interface slice.

type ServerCapabilities

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

ServerCapabilities describes features the server supports.

type SetLevelRequestParams

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

SetLevelRequestParams defines parameters for 'logging/set_level'.

type SubscribeResourceParams

type SubscribeResourceParams struct {
	URIs []string `json:"uris"`
}

SubscribeResourceParams defines parameters for 'resources/subscribe'.

type SubscribeResourceResult

type SubscribeResourceResult struct{}

SubscribeResourceResult defines the result for 'resources/subscribe'. (Currently empty)

type TextContent

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

TextContent represents textual content.

func (TextContent) GetType

func (tc TextContent) GetType() string

type TextResourceContents

type TextResourceContents struct {
	ContentType string `json:"contentType"` // e.g., "text/plain", "application/json"
	Content     string `json:"content"`
}

TextResourceContents holds text-based resource content.

func (TextResourceContents) GetContentType

func (trc TextResourceContents) GetContentType() string

type Tool

type Tool struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	InputSchema ToolInputSchema `json:"inputSchema"`
	Annotations ToolAnnotations `json:"annotations,omitempty"`
}

Tool defines a tool offered by the server.

type ToolAnnotations

type ToolAnnotations struct {
	Title           string `json:"title,omitempty"`           // Optional human-readable title for the tool.
	ReadOnlyHint    *bool  `json:"readOnlyHint,omitempty"`    // Use pointer for optional boolean
	DestructiveHint *bool  `json:"destructiveHint,omitempty"` // Use pointer for optional boolean
	IdempotentHint  *bool  `json:"idempotentHint,omitempty"`  // Use pointer for optional boolean
	OpenWorldHint   *bool  `json:"openWorldHint,omitempty"`   // Use pointer for optional boolean
}

ToolAnnotations provides optional hints about tool behavior.

type ToolInputSchema

type ToolInputSchema struct {
	Type       string                    `json:"type"` // Typically "object"
	Properties map[string]PropertyDetail `json:"properties,omitempty"`
	Required   []string                  `json:"required,omitempty"`
}

ToolInputSchema defines the expected input structure for a tool (JSON Schema subset).

type ToolsListChangedParams

type ToolsListChangedParams struct{}

ToolsListChangedParams defines parameters for 'notifications/tools/list_changed'.

type UnsubscribeResourceParams

type UnsubscribeResourceParams struct {
	URIs []string `json:"uris"`
}

UnsubscribeResourceParams defines parameters for 'resources/unsubscribe'.

type UnsubscribeResourceResult

type UnsubscribeResourceResult struct{}

UnsubscribeResourceResult defines the result for 'resources/unsubscribe'. (Currently empty)

type WorkspaceFolder

type WorkspaceFolder struct {
	URI  string `json:"uri"`
	Name string `json:"name"`
}

WorkspaceFolder represents a workspace folder as defined by LSP.

Jump to

Keyboard shortcuts

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