Documentation
¶
Index ¶
- Constants
- Variables
- func CreateHTTPClient(cfg *HTTPTransportConfig) (*client.Client, error)
- func CreateSSEClient(cfg *HTTPTransportConfig) (*client.Client, error)
- func DetermineTransportType(serverConfig *config.ServerConfig) string
- func GlobalTraceEnabled() bool
- func IsEndpointDeprecatedError(err error) bool
- func LooksLikeDeprecatedEndpoint(err error) bool
- func MarkDispatched(ctx context.Context)
- func NewCallRecorderTransport(next http.RoundTripper) http.RoundTripper
- func ParseRetryAfter(value string, now time.Time) (time.Duration, bool)
- func SetGlobalTraceEnabled(on bool)
- func SetTraceOutput(w io.Writer) (restore func())
- func TagConnectionContext(ctx context.Context, source ConnectionSource) context.Context
- func WithResponseLimit(ctx context.Context, n int64) context.Context
- type CallRecorder
- type CallRecorderSnapshot
- type ConnectionSource
- type ErrEndpointDeprecated
- type HTTPError
- type HTTPResponseDetails
- type HTTPTransportConfig
- type JSONRPCError
- type ListenEnd
- type ListenEndReason
- type ListenStream
- type ListenStreamOptions
- type LoggingTransport
- type RetryAfterRecorder
- type RetryAfterTransport
Constants ¶
const ( TransportHTTP = "http" TransportStreamableHTTP = "streamable-http" TransportSSE = "sse" TransportStdio = "stdio" )
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 ¶
var ErrResponseTooLarge = errors.New("upstream response exceeds the per-request size limit")
ErrResponseTooLarge is returned by a response body that carried more bytes than the limit the request's context asked for.
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 GlobalTraceEnabled ¶
func GlobalTraceEnabled() bool
GlobalTraceEnabled reports whether HTTP/SSE frame tracing is enabled.
func IsEndpointDeprecatedError ¶
IsEndpointDeprecatedError checks if an error indicates a deprecated endpoint (HTTP 410)
func LooksLikeDeprecatedEndpoint ¶ added in v0.74.0
LooksLikeDeprecatedEndpoint reports whether err says the upstream endpoint was deprecated or removed (HTTP 410 Gone), so reconnecting cannot help. A socket-level failure (refused, reset, unreachable, DNS, timeout) never is, whatever address its text names.
func MarkDispatched ¶ added in v0.71.0
MarkDispatched records that the call was handed to the transport layer. It is a no-op when ctx carries no recorder.
func NewCallRecorderTransport ¶ added in v0.71.0
func NewCallRecorderTransport(next http.RoundTripper) http.RoundTripper
NewCallRecorderTransport wraps next so requests whose ctx carries a CallRecorder fill it.
func ParseRetryAfter ¶ added in v0.61.0
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 SetGlobalTraceEnabled ¶ added in v0.70.0
func SetGlobalTraceEnabled(on bool)
SetGlobalTraceEnabled turns HTTP/SSE frame tracing on or off for transports created afterwards. Set by CLI flags or other callers.
func SetTraceOutput ¶ added in v0.70.0
SetTraceOutput redirects the trace transport's console output to w and returns a function that restores the previous destination. It is safe to call while trace output is being produced.
func TagConnectionContext ¶
func TagConnectionContext(ctx context.Context, source ConnectionSource) context.Context
TagConnectionContext tags a context with the connection source
func WithResponseLimit ¶ added in v0.74.0
WithResponseLimit returns a context that makes the upstream round tripper fail the response body once more than n bytes have been read. Requests without the value are untouched. Only a request of its own (streamable HTTP POST) is bounded: on a shared SSE stream the limit does not apply.
Types ¶
type CallRecorder ¶ added in v0.71.0
type CallRecorder struct {
// contains filtered or unexported fields
}
CallRecorder accumulates the HTTP facts of ONE tool call.
func CallRecorderFrom ¶ added in v0.71.0
func CallRecorderFrom(ctx context.Context) *CallRecorder
CallRecorderFrom returns the recorder on ctx, or nil.
func WithCallRecorder ¶ added in v0.71.0
func WithCallRecorder(ctx context.Context) (context.Context, *CallRecorder)
WithCallRecorder returns a ctx carrying a fresh recorder.
func (*CallRecorder) Snapshot ¶ added in v0.71.0
func (r *CallRecorder) Snapshot() CallRecorderSnapshot
Snapshot returns a copy of the recorder's state. A nil recorder yields the zero snapshot.
type CallRecorderSnapshot ¶ added in v0.71.0
type CallRecorderSnapshot struct {
// Dispatched is true once the call was handed to the mcp-go client
// (MarkDispatched), for every transport, including stdio.
Dispatched bool
// Dispatches is how many times the call was handed to the mcp-go client.
// It is 1 for an ordinary call and 2 when session recovery repeated the
// request on a re-initialized session; 0 when a core-level check (not
// connected, ...) refused it before the hand-off.
Dispatches int
// Requests is the number of HTTP requests that carried the recorder.
Requests int
// Responses is how many of them produced an HTTP response.
Responses int
// LastStatus is the status of the most recent response; 0 if none.
LastStatus int
}
CallRecorderSnapshot is an immutable copy of a recorder's state.
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" // ConnectionSourceStdio identifies the native stdio MCP transport: the // local process that launched mcpproxy, with no listener at all (Spec // 107 T103 — tagged by server.stdioAuthContext so the audit line reports // caller.kind: stdio instead of the TCP default's api_key). ConnectionSourceStdio ConnectionSource = "stdio" )
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) ScrubbedCopy ¶ added in v0.70.0
ScrubbedCopy returns a copy of e with every text field passed through scrub (Spec 112 FR-016: forwarded header values an upstream echoes back must not reach a sink through errors.As). The receiver is not modified.
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
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
// HeaderFunc attaches client headers forwarded per call (Spec 112). It
// reads only the outbound context key that core.Client.CallTool sets, so it
// emits nothing for initialize, list or reconnect traffic. nil means the
// default headerfwd.HeaderFunc over Headers.
HeaderFunc transport.HTTPHeaderFunc
// ForwardNames returns the live forward_headers allowlist of this server.
// The trace transport masks those header names (request and response) even
// when a given request carries no forwarded set (FR-018). May be nil.
ForwardNames func() []string
// Gate is the upstream instance's retirement barrier (Spec 116 PR4,
// FR-024). When set, every branch builds on a gated *http.Transport (its
// dials and connection writes stop when the instance is retired) and the
// returned client's mcp-go transport is wrapped by dialgate.WrapTransport.
// nil keeps the ungated transports (tests, tools outside the daemon).
Gate *dialgate.Gate
}
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
func (*HTTPTransportConfig) NewListenStream ¶ added in v0.74.0
func (cfg *HTTPTransportConfig) NewListenStream(sh *mcptransport.StreamableHTTP, opts ListenStreamOptions) *ListenStream
NewListenStream builds the GET stream for sh, the mcp-go transport this config produced (CreateHTTPClient). The session id is read from sh on every attempt and the bearer comes from sh's own OAuth handler, so the stream authenticates exactly like the transport's POSTs; cfg.Headers are the static headers that transport sends.
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
func (*JSONRPCError) ScrubbedCopy ¶ added in v0.70.0
func (e *JSONRPCError) ScrubbedCopy(scrub func(string) string) error
ScrubbedCopy returns a copy of e with Message, Data and the nested HTTP error scrubbed. Data is scrubbed through its JSON form; if that fails it is dropped rather than kept raw. The receiver is not modified.
type ListenEnd ¶ added in v0.74.0
type ListenEnd struct {
Reason ListenEndReason
// Status is the HTTP status of the refusing response, 0 when none.
Status int
// Detail is a short, credential-free description for one log line.
Detail string
}
ListenEnd is the result of ListenStream.Run.
type ListenEndReason ¶ added in v0.74.0
type ListenEndReason int
ListenEndReason says why ListenStream.Run returned.
const ( // ListenStopped: the context was cancelled (close, reconnect, re-init, // retirement). ListenStopped ListenEndReason = iota // ListenUnsupported: the server refused the GET (405, 400, 406, 401, 403, // another 4xx, or a non-event-stream answer). Polling covers it. ListenUnsupported // ListenSessionTerminated: the server answered 404 for this session. A // session re-initialize or a reconnect starts a new stream. ListenSessionTerminated )
func (ListenEndReason) String ¶ added in v0.74.0
func (r ListenEndReason) String() string
type ListenStream ¶ added in v0.74.0
type ListenStream struct {
// contains filtered or unexported fields
}
ListenStream holds the standalone GET stream of one streamable-HTTP transport. Build it with HTTPTransportConfig.NewListenStream; Run it once.
type ListenStreamOptions ¶ added in v0.74.0
type ListenStreamOptions struct {
// ProtocolVersion is sent as Mcp-Protocol-Version (the negotiated one).
ProtocolVersion string
// OnNotification receives every notification the stream carries. It runs
// on the stream's goroutine and is never called after Run's context ends.
OnNotification func(mcp.JSONRPCNotification)
Logger *zap.Logger
// MinBackoff is the first retry delay after a transient failure and the
// delay before re-opening a stream that ended after being healthy.
MinBackoff time.Duration
// MaxBackoff caps the exponential retry delay.
MaxBackoff time.Duration
// HealthyAfter is how long a stream must stay open for its end to count
// as normal (backoff reset) rather than as a failure.
HealthyAfter time.Duration
}
ListenStreamOptions tunes a ListenStream. Zero durations take the defaults.
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
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
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.