transport

package
v0.61.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TransportHTTP           = "http"
	TransportStreamableHTTP = "streamable-http"
	TransportSSE            = "sse"
	TransportStdio          = "stdio"
)
View Source
const MaxRetryAfterDelay = time.Hour

MaxRetryAfterDelay caps how long an upstream-supplied Retry-After may park a server. RFC 7231 puts no ceiling on the value, so a misconfigured (or hostile) upstream could hand us days. An hour is long enough to respect a real vendor rate-limit window and short enough that a bogus hint self-heals without a human having to hit "reconnect".

Variables

View Source
var (
	// GlobalTraceEnabled controls whether HTTP/SSE frame tracing is enabled
	// This can be set by CLI flags or other callers
	GlobalTraceEnabled = false
)

Functions

func CreateHTTPClient

func CreateHTTPClient(cfg *HTTPTransportConfig) (*client.Client, error)

CreateHTTPClient creates a new MCP client using HTTP transport

func CreateSSEClient

func CreateSSEClient(cfg *HTTPTransportConfig) (*client.Client, error)

CreateSSEClient creates a new MCP client using SSE transport

func DetermineTransportType

func DetermineTransportType(serverConfig *config.ServerConfig) string

DetermineTransportType determines the transport type based on URL and config

func EffectiveHeaders added in v0.39.0

func EffectiveHeaders(base map[string]string, brokered *BrokeredAuth) map[string]string

EffectiveHeaders returns the outbound header set for a request, injecting the brokered per-user credential when one is supplied.

The returned map is always a fresh copy — callers must never mutate the server config's header map. When brokered is non-nil, any header in base whose name matches brokered.Header case-insensitively is dropped before the resolved credential is set, so the configured/inbound auth is REPLACED rather than merged or forwarded (FR-017). When brokered is nil, base is returned unchanged (as a copy).

func IsEndpointDeprecatedError

func IsEndpointDeprecatedError(err error) bool

IsEndpointDeprecatedError checks if an error indicates a deprecated endpoint (HTTP 410)

func ParseRetryAfter added in v0.61.0

func ParseRetryAfter(value string, now time.Time) (time.Duration, bool)

ParseRetryAfter parses an RFC 7231 `Retry-After` value — either delta-seconds or an HTTP-date — into a delay relative to now.

ok is false for an absent, malformed, or already-elapsed value; the caller then falls back to its normal exponential backoff.

func TagConnectionContext

func TagConnectionContext(ctx context.Context, source ConnectionSource) context.Context

TagConnectionContext tags a context with the connection source

Types

type BrokeredAuth added in v0.39.0

type BrokeredAuth struct {
	// Header is the outbound header the credential is injected into
	// (default "Authorization").
	Header string
	// Format is the value template; the literal substring "{token}" is replaced
	// with Token (default "Bearer {token}").
	Format string
	// Token is the resolved per-user credential.
	Token string
}

BrokeredAuth carries a per-user resolved upstream credential to inject into an outbound HTTP/SSE request (spec 074, FR-016/FR-017). The server edition's credential broker resolves the per-user token and hands it down as plain data so the edition-neutral transport layer can inject it without importing any server-only package.

Injection REPLACES any inbound or statically-configured header of the same name: the gateway/IdP token is never forwarded to the upstream (FR-017).

func (*BrokeredAuth) HeaderValue added in v0.39.0

func (b *BrokeredAuth) HeaderValue() string

HeaderValue renders the outbound header value from Format, substituting the resolved token for the "{token}" placeholder.

type ConnectionSource

type ConnectionSource string

ConnectionSource identifies the origin of a connection

const (
	// ConnectionSourceTCP identifies connections from TCP listener (browsers, remote clients)
	ConnectionSourceTCP ConnectionSource = "tcp"
	// ConnectionSourceTray identifies connections from tray via Unix socket or named pipe
	ConnectionSourceTray ConnectionSource = "tray"
)

func GetConnectionSource

func GetConnectionSource(ctx context.Context) ConnectionSource

GetConnectionSource retrieves the connection source from context

type ErrEndpointDeprecated

type ErrEndpointDeprecated struct {
	URL            string `json:"url"`
	Message        string `json:"message"`
	MigrationGuide string `json:"migration_guide,omitempty"`
	NewEndpoint    string `json:"new_endpoint,omitempty"`
}

ErrEndpointDeprecated represents a 410 Gone response indicating the endpoint has been deprecated

func NewEndpointDeprecatedError

func NewEndpointDeprecatedError(url, message, migrationGuide, newEndpoint string) *ErrEndpointDeprecated

NewEndpointDeprecatedError creates a new ErrEndpointDeprecated from response details

func (*ErrEndpointDeprecated) Error

func (e *ErrEndpointDeprecated) Error() string

type HTTPError

type HTTPError struct {
	StatusCode int               `json:"status_code"`
	Headers    map[string]string `json:"headers"`
	Body       string            `json:"body"`
	Method     string            `json:"method"`
	URL        string            `json:"url"`
	Err        error             `json:"-"` // Original error
}

HTTPError represents detailed HTTP error information for debugging

func NewHTTPError

func NewHTTPError(statusCode int, body, method, url string, headers map[string]string, originalErr error) *HTTPError

EnhancedHTTPError creates an HTTPError with full context

func (*HTTPError) Error

func (e *HTTPError) Error() string

type HTTPResponseDetails

type HTTPResponseDetails struct {
	StatusCode int               `json:"status_code"`
	Headers    map[string]string `json:"headers"`
	Body       string            `json:"body"`
	URL        string            `json:"url"`
	Method     string            `json:"method"`
}

HTTPResponseDetails captures detailed HTTP response information for debugging

type HTTPTransportConfig

type HTTPTransportConfig struct {
	URL         string
	Headers     map[string]string
	OAuthConfig *client.OAuthConfig
	UseOAuth    bool
	// BrokeredAuth, when set, injects a per-user resolved credential into the
	// outbound headers, replacing any configured/inbound auth header (spec 074
	// FR-016/FR-017). It is edition-neutral plain data so the server-edition
	// credential broker can drive injection without this package importing it.
	BrokeredAuth *BrokeredAuth
	TraceEnabled bool // Enable detailed HTTP/SSE frame tracing
	// RetryAfter, when set, receives the `Retry-After` hints observed on this
	// upstream's rate-limited responses (#1040). mcp-go flattens non-2xx
	// responses into strings, so a RoundTripper is the last place the header
	// still exists. nil disables the wrapper entirely (unchanged behaviour).
	RetryAfter *RetryAfterRecorder
}

HTTPTransportConfig holds configuration for HTTP transport

func CreateHTTPTransportConfig

func CreateHTTPTransportConfig(serverConfig *config.ServerConfig, oauthConfig *client.OAuthConfig) *HTTPTransportConfig

CreateHTTPTransportConfig creates an HTTP transport config from server config

type JSONRPCError

type JSONRPCError struct {
	Code      int         `json:"code"`
	Message   string      `json:"message"`
	Data      interface{} `json:"data,omitempty"`
	HTTPError *HTTPError  `json:"http_error,omitempty"`
}

JSONRPCError represents JSON-RPC specific error information

func NewJSONRPCError

func NewJSONRPCError(code int, message string, data interface{}, httpErr *HTTPError) *JSONRPCError

NewJSONRPCError creates a JSONRPCError with optional HTTP context

func (*JSONRPCError) Error

func (e *JSONRPCError) Error() string

type LoggingTransport

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

LoggingTransport wraps http.RoundTripper to log all HTTP traffic including SSE frames

func NewLoggingTransport

func NewLoggingTransport(base http.RoundTripper, logger *zap.Logger) *LoggingTransport

NewLoggingTransport creates a new logging HTTP transport

func (*LoggingTransport) RoundTrip

func (t *LoggingTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper with comprehensive logging

type RetryAfterRecorder added in v0.61.0

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

RetryAfterRecorder captures the rate-limit hints observed on one upstream's HTTP responses.

It exists because mcp-go flattens every non-2xx response into a bare string (`request failed with status %d: %s` in client/transport/streamable_http.go), so by the time a connect error reaches the state machine the `Retry-After` header is gone. The only layer that still holds the *http.Response is the RoundTripper underneath the MCP client — hence RetryAfterTransport below, which feeds this recorder (#1040).

A nil *RetryAfterRecorder is usable and inert, so callers that do not care about rate-limit hints can pass nil everywhere.

func NewRetryAfterRecorder added in v0.61.0

func NewRetryAfterRecorder() *RetryAfterRecorder

NewRetryAfterRecorder returns an empty recorder.

func (*RetryAfterRecorder) Clear added in v0.61.0

func (r *RetryAfterRecorder) Clear()

Clear drops any recorded hint. Called once a connection succeeds so a stale window cannot hold back a later, unrelated reconnect.

func (*RetryAfterRecorder) Deadline added in v0.61.0

func (r *RetryAfterRecorder) Deadline() time.Time

Deadline returns the instant before which no automatic reconnect should be attempted, or the zero time when no hint has been observed.

func (*RetryAfterRecorder) Record added in v0.61.0

func (r *RetryAfterRecorder) Record(now time.Time, delay time.Duration, status int) time.Time

Record notes that the upstream asked us to wait `delay` as of `now`. The delay is clamped to MaxRetryAfterDelay and only ever extends the current park window: a later, shorter hint must not shorten a wait the upstream already asked for. It returns the effective deadline.

func (*RetryAfterRecorder) Status added in v0.61.0

func (r *RetryAfterRecorder) Status() int

Status returns the HTTP status that produced the current deadline (0 when there is none). Used for logging.

type RetryAfterTransport added in v0.61.0

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

RetryAfterTransport is an http.RoundTripper wrapper that records `Retry-After` hints from rate-limited upstream responses into a RetryAfterRecorder. It never alters the request or the response — it only observes the status line and one header, leaving the body untouched for mcp-go to consume.

func NewRetryAfterTransport added in v0.61.0

func NewRetryAfterTransport(base http.RoundTripper, recorder *RetryAfterRecorder, logger *zap.Logger) *RetryAfterTransport

NewRetryAfterTransport wraps base so 429 (and 503-with-a-hint) responses feed recorder. A nil base means http.DefaultTransport; a nil logger is tolerated.

func (*RetryAfterTransport) RoundTrip added in v0.61.0

func (t *RetryAfterTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

Jump to

Keyboard shortcuts

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