mcp

package
v1.5.5 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package mcp contains the core types and interfaces for the Model Context Protocol.

This package defines the fundamental types used across all MCP specification versions and provides utilities for working with them.

Package mcp provides shared types for the MCP protocol implementation.

Package mcp provides shared types for the MCP protocol implementation.

Index

Constants

View Source
const (
	VersionDraft    = "draft"
	Version20241105 = "2024-11-05"
	Version20250326 = "2025-03-26"
)

Known MCP specification versions

Variables

SupportedVersions is a list of all supported MCP specification versions in order of preference (newest first)

Functions

func CompleteOperation added in v1.5.0

func CompleteOperation(reporter *ProgressReporter, finalMessage string) error

CompleteOperation is a convenience method for completing an operation

func ExtractProgressTokenFromRequest added in v1.5.0

func ExtractProgressTokenFromRequest(requestBytes []byte) (string, error)

ExtractProgressTokenFromRequest extracts a progress token from request metadata This follows the MCP specification pattern where progress tokens are in params._meta.progressToken

func GetCompatibilityMatrix

func GetCompatibilityMatrix() map[string][]string

GetCompatibilityMatrix returns a map showing which versions are compatible with each other

func GetSupportedVersions

func GetSupportedVersions() []string

GetSupportedVersions returns a list of all versions supported by this library

func NormalizeVersion

func NormalizeVersion(version string) string

NormalizeVersion normalizes a version string for comparison

func UpdateOperation added in v1.5.0

func UpdateOperation(reporter *ProgressReporter, completed int, total int, message string) error

UpdateOperation is a convenience method for updating progress with automatic percentage calculation

Types

type ProgressChannel added in v1.5.0

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

ProgressChannel represents a bidirectional communication channel for progress notifications

func NewProgressChannel added in v1.5.0

func NewProgressChannel() *ProgressChannel

NewProgressChannel creates a new progress communication channel

func (*ProgressChannel) Close added in v1.5.0

func (pc *ProgressChannel) Close()

Close deactivates the progress channel and clears all listeners

func (*ProgressChannel) GetListenerCount added in v1.5.0

func (pc *ProgressChannel) GetListenerCount(progressToken string) int

GetListenerCount returns the number of listeners for a specific token

func (*ProgressChannel) GetTotalListenerCount added in v1.5.0

func (pc *ProgressChannel) GetTotalListenerCount() int

GetTotalListenerCount returns the total number of listeners across all tokens

func (*ProgressChannel) IsActive added in v1.5.0

func (pc *ProgressChannel) IsActive() bool

IsActive returns whether the progress channel is active

func (*ProgressChannel) Publish added in v1.5.0

func (pc *ProgressChannel) Publish(notification *ProgressNotification) error

Publish sends a progress notification to all relevant listeners

func (*ProgressChannel) Subscribe added in v1.5.0

func (pc *ProgressChannel) Subscribe(progressToken string, listener ProgressListener)

Subscribe adds a listener for progress notifications with a specific token

func (*ProgressChannel) SubscribeAll added in v1.5.0

func (pc *ProgressChannel) SubscribeAll(listener ProgressListener)

SubscribeAll adds a listener for all progress notifications (use empty string as token)

func (*ProgressChannel) Unsubscribe added in v1.5.0

func (pc *ProgressChannel) Unsubscribe(progressToken string)

Unsubscribe removes all listeners for a specific progress token

type ProgressListener added in v1.5.0

type ProgressListener func(*ProgressNotification) error

ProgressListener represents a function that handles progress notifications

type ProgressNotification added in v1.5.0

type ProgressNotification struct {
	// JSONRPC version (always "2.0")
	JSONRPC string `json:"jsonrpc"`

	// Method is always "notifications/progress"
	Method string `json:"method"`

	// Params contains the progress notification parameters
	Params ProgressNotificationParams `json:"params"`

	// ID is optional for notifications but can be included for tracking
	ID interface{} `json:"id,omitempty"`
	// contains filtered or unexported fields
}

ProgressNotification represents a complete progress notification message This includes the JSON-RPC 2.0 envelope and the progress-specific parameters

func NewProgressNotification added in v1.5.0

func NewProgressNotification(progressToken string, progress float64, total *float64, message string) *ProgressNotification

NewProgressNotification creates a new progress notification message The protocolVersion parameter determines which fields are included (draft, 2024-11-05, 2025-03-26)

func NewProgressNotificationForVersion added in v1.5.0

func NewProgressNotificationForVersion(progressToken string, progress float64, total *float64, message string, protocolVersion string) *ProgressNotification

NewProgressNotificationForVersion creates a new progress notification for a specific protocol version

func (*ProgressNotification) FromJSON added in v1.5.0

func (pn *ProgressNotification) FromJSON(data []byte) error

FromJSON deserializes JSON bytes into a progress notification

func (*ProgressNotification) GetPercentage added in v1.5.0

func (pn *ProgressNotification) GetPercentage() *float64

GetPercentage calculates the percentage completion if total is available

func (*ProgressNotification) GetProtocolVersion added in v1.5.0

func (pn *ProgressNotification) GetProtocolVersion() string

GetProtocolVersion returns the protocol version for this notification

func (*ProgressNotification) IsComplete added in v1.5.0

func (pn *ProgressNotification) IsComplete() bool

IsComplete returns true if the progress indicates completion

func (*ProgressNotification) SetProtocolVersion added in v1.5.0

func (pn *ProgressNotification) SetProtocolVersion(version string)

SetProtocolVersion sets the protocol version for this notification

func (*ProgressNotification) ToJSON added in v1.5.0

func (pn *ProgressNotification) ToJSON() ([]byte, error)

ToJSON serializes the progress notification to JSON bytes This respects the protocol version and excludes unsupported fields

func (*ProgressNotification) Validate added in v1.5.0

func (pn *ProgressNotification) Validate() error

Validate checks if the progress notification is valid according to MCP specifications

func (*ProgressNotification) ValidateProgressIncrease added in v1.5.0

func (pn *ProgressNotification) ValidateProgressIncrease(previousProgress float64) error

ValidateProgressIncrease validates that progress values increase as required by MCP specs

type ProgressNotificationParams added in v1.5.0

type ProgressNotificationParams struct {
	// ProgressToken is a unique identifier for this progress tracking session
	ProgressToken string `json:"progressToken"`

	// Progress is the current progress value (required)
	Progress float64 `json:"progress"`

	// Total is the total expected value (optional, for percentage calculations)
	Total *float64 `json:"total,omitempty"`

	// Message is an optional human-readable progress message
	// Note: Only supported in draft and 2025-03-26 versions, not in 2024-11-05
	Message string `json:"message,omitempty"`
}

ProgressNotificationParams represents the parameters for a progress notification following the MCP JSON-RPC 2.0 specification pattern

type ProgressNotificationSender added in v1.5.0

type ProgressNotificationSender interface {
	SendProgressNotification(progressToken string, progress float64, total *float64, message string) error
}

ProgressNotificationSender is an interface for sending progress notifications This allows the ProgressReporter to work with different server implementations

type ProgressReporter added in v1.5.0

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

ProgressReporter provides a user-friendly API for progress reporting with automatic token management

func NewProgressReporter added in v1.5.0

func NewProgressReporter(config ProgressReporterConfig) *ProgressReporter

NewProgressReporter creates a new ProgressReporter with the given configuration

func NewSimpleProgressReporter added in v1.5.0

func NewSimpleProgressReporter(requestID string, total *float64) *ProgressReporter

NewSimpleProgressReporter creates a basic ProgressReporter with minimal configuration

func NewSimpleProgressReporterForVersion added in v1.5.0

func NewSimpleProgressReporterForVersion(requestID string, total *float64, protocolVersion string) *ProgressReporter

NewSimpleProgressReporterForVersion creates a basic ProgressReporter for a specific protocol version

func StartOperation added in v1.5.0

func StartOperation(requestID string, total *float64, initialMessage string, sender ProgressNotificationSender) *ProgressReporter

StartOperation is a convenience method that creates a reporter and sends an initial notification

func (*ProgressReporter) Cancel added in v1.5.0

func (pr *ProgressReporter) Cancel(message ...string) error

Cancel cancels the progress reporting and deactivates the token

func (*ProgressReporter) Complete added in v1.5.0

func (pr *ProgressReporter) Complete(message ...string) error

Complete marks the progress as completed with an optional final message

func (*ProgressReporter) CreateChild added in v1.5.0

func (pr *ProgressReporter) CreateChild(requestID string, weight float64, total *float64) *ProgressReporter

CreateChild creates a child ProgressReporter for hierarchical progress tracking Note: Simplified version without automatic parent updates to avoid deadlocks

func (*ProgressReporter) GetChildCount added in v1.5.0

func (pr *ProgressReporter) GetChildCount() int

GetChildCount returns the number of child reporters

func (*ProgressReporter) GetChildren added in v1.5.0

func (pr *ProgressReporter) GetChildren() map[string]*ProgressReporter

GetChildren returns a copy of the children map for safe iteration

func (*ProgressReporter) GetDuration added in v1.5.0

func (pr *ProgressReporter) GetDuration() time.Duration

GetDuration returns how long the progress has been running

func (*ProgressReporter) GetPercentage added in v1.5.0

func (pr *ProgressReporter) GetPercentage() *float64

GetPercentage returns the current progress as a percentage (0-100)

func (*ProgressReporter) GetProgress added in v1.5.0

func (pr *ProgressReporter) GetProgress() (current float64, total *float64, message string, isCompleted bool)

GetProgress returns the current progress information

func (*ProgressReporter) GetProtocolVersion added in v1.5.0

func (pr *ProgressReporter) GetProtocolVersion() string

GetProtocolVersion returns the MCP protocol version for this reporter

func (*ProgressReporter) GetRequestID added in v1.5.0

func (pr *ProgressReporter) GetRequestID() string

GetRequestID returns the request ID associated with this reporter

func (*ProgressReporter) GetStatistics added in v1.5.0

func (pr *ProgressReporter) GetStatistics() map[string]interface{}

GetStatistics returns detailed statistics about this progress reporter

func (*ProgressReporter) GetTimeSinceLastUpdate added in v1.5.0

func (pr *ProgressReporter) GetTimeSinceLastUpdate() time.Duration

GetTimeSinceLastUpdate returns how long since the last progress update

func (*ProgressReporter) GetToken added in v1.5.0

func (pr *ProgressReporter) GetToken() string

GetToken returns the progress token for this reporter

func (*ProgressReporter) Increment added in v1.5.0

func (pr *ProgressReporter) Increment(amount float64, message ...string) error

Increment increments the progress by the given amount

func (*ProgressReporter) IsActive added in v1.5.0

func (pr *ProgressReporter) IsActive() bool

IsActive returns whether the progress reporter is active

func (*ProgressReporter) IsCompleted added in v1.5.0

func (pr *ProgressReporter) IsCompleted() bool

IsCompleted returns whether the progress has been completed

func (*ProgressReporter) SetProtocolVersion added in v1.5.0

func (pr *ProgressReporter) SetProtocolVersion(version string)

SetProtocolVersion updates the MCP protocol version for this reporter

func (*ProgressReporter) SetTotal added in v1.5.0

func (pr *ProgressReporter) SetTotal(total float64) error

SetTotal updates the total expected value

func (*ProgressReporter) Update added in v1.5.0

func (pr *ProgressReporter) Update(current float64, message ...string) error

Update updates the progress with a new current value and optional message

type ProgressReporterConfig added in v1.5.0

type ProgressReporterConfig struct {
	// RequestID is the ID of the request this progress is associated with
	RequestID string

	// Total is the expected total value for progress (optional)
	Total *float64

	// InitialMessage is the initial progress message
	InitialMessage string

	// TokenManager is used for token lifecycle management (optional, will create default if nil)
	TokenManager *ProgressTokenManager

	// NotificationSender is used to send progress notifications (optional)
	NotificationSender ProgressNotificationSender

	// Parent is the parent ProgressReporter for hierarchical progress (optional)
	Parent *ProgressReporter

	// ChildWeight is how much this reporter contributes to parent's progress (0.0-1.0, default 1.0)
	ChildWeight float64

	// ProtocolVersion specifies which MCP version to use (draft, 2024-11-05, 2025-03-26)
	ProtocolVersion string
}

ProgressReporterConfig contains configuration options for creating a ProgressReporter

type ProgressToken added in v1.5.0

type ProgressToken struct {
	// Token is the unique string identifier
	Token string

	// RequestID is the ID of the request this progress token is associated with
	RequestID string

	// CreatedAt is when this token was created
	CreatedAt time.Time

	// LastUpdate is when this token was last used for progress reporting
	LastUpdate time.Time

	// IsActive indicates if this token is still active
	IsActive bool

	// LastProgress tracks the last reported progress value to enforce increasing requirement
	LastProgress float64

	// ProtocolVersion tracks which MCP version this token is for
	ProtocolVersion string
}

ProgressToken represents a unique token for tracking progress of long-running operations

type ProgressTokenManager added in v1.5.0

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

ProgressTokenManager manages progress tokens in a thread-safe manner

func NewProgressTokenManager added in v1.5.0

func NewProgressTokenManager() *ProgressTokenManager

NewProgressTokenManager creates a new progress token manager

func (*ProgressTokenManager) CleanupExpiredTokens added in v1.5.0

func (ptm *ProgressTokenManager) CleanupExpiredTokens(expiration time.Duration) int

CleanupExpiredTokens removes tokens that haven't been updated for the specified duration

func (*ProgressTokenManager) DeactivateToken added in v1.5.0

func (ptm *ProgressTokenManager) DeactivateToken(token string) error

DeactivateToken marks a token as inactive (operation completed or cancelled)

func (*ProgressTokenManager) GenerateToken added in v1.5.0

func (ptm *ProgressTokenManager) GenerateToken(requestID string) string

GenerateToken creates a new unique progress token

func (*ProgressTokenManager) GenerateTokenForVersion added in v1.5.0

func (ptm *ProgressTokenManager) GenerateTokenForVersion(requestID string, protocolVersion string) string

GenerateTokenForVersion creates a new unique progress token for a specific protocol version

func (*ProgressTokenManager) GetActiveTokens added in v1.5.0

func (ptm *ProgressTokenManager) GetActiveTokens() []string

GetActiveTokens returns a list of all active progress tokens

func (*ProgressTokenManager) GetLastProgress added in v1.5.0

func (ptm *ProgressTokenManager) GetLastProgress(token string) (float64, error)

GetLastProgress returns the last reported progress value for a token

func (*ProgressTokenManager) GetToken added in v1.5.0

func (ptm *ProgressTokenManager) GetToken(token string) (*ProgressToken, error)

GetToken retrieves a progress token by its string value

func (*ProgressTokenManager) UpdateToken added in v1.5.0

func (ptm *ProgressTokenManager) UpdateToken(token string) error

UpdateToken updates the last update time for a token

func (*ProgressTokenManager) UpdateTokenWithProgress added in v1.5.0

func (ptm *ProgressTokenManager) UpdateTokenWithProgress(token string, progress float64) error

UpdateTokenWithProgress updates the token with a new progress value, validating it increases

func (*ProgressTokenManager) ValidateToken added in v1.5.0

func (ptm *ProgressTokenManager) ValidateToken(token string) bool

ValidateToken checks if a progress token is valid and active

type Prompt added in v1.5.0

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

Prompt represents a prompt template available from an MCP server. This type is used by both client and server implementations for consistency.

type PromptArgument added in v1.5.0

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

PromptArgument represents an argument for a prompt template.

type Resource added in v1.5.0

type Resource struct {
	URI         string                 `json:"uri"`
	Name        string                 `json:"name,omitempty"`
	Description string                 `json:"description,omitempty"`
	MimeType    string                 `json:"mimeType,omitempty"`
	Annotations map[string]interface{} `json:"annotations,omitempty"`
}

Resource represents a resource available from an MCP server. This type is used by both client and server implementations for consistency.

type SpecVersion

type SpecVersion string

SpecVersion represents an MCP specification version

const (
	SpecVersion20241105 SpecVersion = "2024-11-05"
	SpecVersion20250326 SpecVersion = "2025-03-26"
	SpecVersionDraft    SpecVersion = "draft"
)

Supported MCP specification versions

type Tool added in v1.5.0

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

Tool represents a tool available from an MCP server. This type is used by both client and server implementations for consistency.

type VersionAdapter

type VersionAdapter struct {
	FromVersion string
	ToVersion   string
}

VersionAdapter is a placeholder for future version adaptation functionality

func (*VersionAdapter) AdaptMessage

func (a *VersionAdapter) AdaptMessage(message []byte) ([]byte, error)

AdaptMessage is a placeholder for adapting a message from one version to another

type VersionDetector

type VersionDetector struct {
	DefaultVersion string   // Default version to use when none is specified
	Supported      []string // Supported versions in order of preference (newest first)
}

VersionDetector detects and negotiates MCP versions

func NewVersionDetector

func NewVersionDetector() *VersionDetector

NewVersionDetector creates a new version detector with default settings

func (*VersionDetector) DetectVersion

func (d *VersionDetector) DetectVersion(message []byte) (string, error)

DetectVersion determines the appropriate MCP version based on a message

func (*VersionDetector) GetVersionAdapter

func (d *VersionDetector) GetVersionAdapter(fromVersion, toVersion string) (interface{}, error)

GetVersionAdapter returns an adapter for converting between versions This is a placeholder for future version adaptation functionality

func (*VersionDetector) IsVersionCompatible

func (d *VersionDetector) IsVersionCompatible(v1, v2 string) bool

IsVersionCompatible checks if two versions are compatible

func (*VersionDetector) NegotiateVersion

func (d *VersionDetector) NegotiateVersion(clientVersions []string, serverVersions []string) (string, error)

NegotiateVersion handles version negotiation between client and server

func (*VersionDetector) ValidateVersion

func (d *VersionDetector) ValidateVersion(version string) (string, error)

ValidateVersion checks if a version is supported and returns a normalized version string

type VersionSupport

type VersionSupport struct {
	V20241105 bool
	V20250326 bool
	Draft     bool
}

VersionSupport represents which MCP specification versions are supported

func AllVersions

func AllVersions() VersionSupport

AllVersions returns a VersionSupport with all versions enabled

Directories

Path Synopsis
Package draft implements the latest draft version of the MCP specification.
Package draft implements the latest draft version of the MCP specification.
Package v20241105 implements the 2024-11-05 version of the MCP specification.
Package v20241105 implements the 2024-11-05 version of the MCP specification.
Package v20250326 implements the 2025-03-26 version of the MCP specification.
Package v20250326 implements the 2025-03-26 version of the MCP specification.

Jump to

Keyboard shortcuts

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