protocol

package
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2025 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

This file implements the core protocol layer for JSON-RPC communication in the MCP SDK. It handles the protocol-level concerns of JSON-RPC messaging, including request/response correlation, progress tracking, request cancellation, and error handling.

Key Components:

1. Protocol:

  • Core type managing JSON-RPC communication
  • Handles message correlation and lifecycle
  • Supports:
  • Request/Response with timeouts
  • Notifications (one-way messages)
  • Progress updates during long operations
  • Request cancellation
  • Error propagation

2. Request Handling:

  • Automatic request ID generation
  • Context-based cancellation
  • Configurable timeouts
  • Progress callback support
  • Response correlation using channels

3. Message Types:

  • JSONRPCRequest: Outgoing requests with IDs
  • JSONRPCNotification: One-way messages
  • JSONRPCError: Error responses
  • Progress: Updates during long operations

4. Handler Registration:

  • Request handlers for method calls
  • Notification handlers for events
  • Progress handlers for long operations
  • Error handlers for protocol errors

Thread Safety:

  • All public methods are thread-safe
  • Uses sync.RWMutex for state protection
  • Safe for concurrent requests and handlers

Usage:

transport := NewStdioTransport()
protocol := NewProtocol(transport)

// Start protocol
protocol.Connect(transport)
defer protocol.Close()

// Make a request
ctx := context.Background()
response, err := protocol.Request(ctx, "method", params, &RequestOptions{
    Timeout: 5 * time.Second,
    OnProgress: func(p Progress) {
        // Handle progress updates
    },
})

Error Handling:

  • Context-based cancellation
  • Timeout management
  • Proper cleanup of pending requests
  • Detailed error information

For more details, see the test file protocol_test.go.

Index

Constants

View Source
const DefaultRequestTimeoutMsec = 60000

Variables

This section is empty.

Functions

This section is empty.

Types

type Progress

type Progress struct {
	Progress int64 `json:"progress"`
	Total    int64 `json:"total"`
}

Progress represents a progress update

type ProgressCallback

type ProgressCallback func(progress Progress)

ProgressCallback is a callback for progress notifications

type Protocol

type Protocol struct {

	// Callback for when the connection is closed for any reason
	OnClose func(ctx context.Context)
	// Callback for when an error occurs
	OnError func(error)
	// Handler to invoke for any request types that do not have their own handler installed
	FallbackRequestHandler func(ctx context.Context, request *transport.BaseJSONRPCRequest) (transport.JsonRpcBody, error)
	// Handler to invoke for any notification types that do not have their own handler installed
	FallbackNotificationHandler func(notification *transport.BaseJSONRPCNotification) error
	// contains filtered or unexported fields
}

Protocol implements MCP protocol framing on top of a pluggable transport, including features like request/response linking, notifications, and progress

func NewProtocol

func NewProtocol(options *ProtocolOptions) *Protocol

NewProtocol creates a new Protocol instance

func (*Protocol) Close

func (p *Protocol) Close() error

Close closes the connection

func (*Protocol) Connect

func (p *Protocol) Connect(ctx context.Context, tr transport.Transport) error

Connect attaches to the given transport, starts it, and starts listening for messages

func (*Protocol) Notification

func (p *Protocol) Notification(method string, params interface{}) error

Notification emits a notification, which is a one-way message that does not expect a response

func (*Protocol) RemoveNotificationHandler

func (p *Protocol) RemoveNotificationHandler(method string)

RemoveNotificationHandler removes the notification handler for the given method

func (*Protocol) RemoveRequestHandler

func (p *Protocol) RemoveRequestHandler(method string)

RemoveRequestHandler removes the request handler for the given method

func (*Protocol) Request

func (p *Protocol) Request(ctx context.Context, method string, params interface{}, opts *RequestOptions) (interface{}, error)

Request sends a request and waits for a response

func (*Protocol) SetNotificationHandler

func (p *Protocol) SetNotificationHandler(method string, handler func(notification *transport.BaseJSONRPCNotification) error)

SetNotificationHandler registers a handler to invoke when this protocol object receives a notification with the given method

func (*Protocol) SetRequestHandler

func (p *Protocol) SetRequestHandler(method string, handler func(context.Context, *transport.BaseJSONRPCRequest, RequestHandlerExtra) (transport.JsonRpcBody, error))

SetRequestHandler registers a handler to invoke when this protocol object receives a request with the given method

type ProtocolOptions

type ProtocolOptions struct {
	// Whether to restrict emitted requests to only those that the remote side has indicated
	// that they can handle, through their advertised capabilities.
	EnforceStrictCapabilities bool
}

ProtocolOptions contains additional initialization options

type RequestHandlerExtra

type RequestHandlerExtra struct {
	// Context used to communicate if the request was cancelled from the sender's side
	Context context.Context
}

RequestHandlerExtra contains extra data given to request handlers

type RequestOptions

type RequestOptions struct {
	// OnProgress is called when progress notifications are received from the remote end
	OnProgress ProgressCallback
	// Context can be used to cancel an in-flight request
	Context context.Context
	// Timeout specifies a timeout for this request. If exceeded, an error with code
	// RequestTimeout will be returned. If not specified, DefaultRequestTimeoutMsec will be used
	Timeout time.Duration
}

RequestOptions contains options that can be given per request

type Result

type Result struct {
	// This result property is reserved by the protocol to allow clients and servers
	// to attach additional metadata to their responses.
	Meta ResultMeta `json:"_meta,omitempty" yaml:"_meta,omitempty" mapstructure:"_meta,omitempty"`

	AdditionalProperties interface{} `mapstructure:",remain"`
}

type ResultMeta

type ResultMeta map[string]interface{}

This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.

Jump to

Keyboard shortcuts

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