mcpclient

package
v0.0.11-dev Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HeaderSessionID       = "Mcp-Session-Id"
	HeaderLastEventID     = "Last-Event-ID"
	HeaderProtocolVersion = "Mcp-Protocol-Version"
)

Variables

View Source
var Module = fx.Module(
	"mcpclient",
	fx.Provide(
		NewProbeState,
		newMcpClient,
		newStdioCommandTransportFactoryProvider,
		newChannelStdioRuntimeInfoProvider,
		newChannelTransportFactory,
		fx.Annotate(newStreamableTransportProvider, fx.ResultTags(`group:"mcp_transport_providers"`)),
		fx.Annotate(newInjectableTransportProvider, fx.ResultTags(`group:"mcp_transport_providers"`)),
		fx.Annotate(newStdioTransportProvider, fx.ResultTags(`group:"mcp_transport_providers"`)),
	),
	fx.Invoke(probeMcpServer),
)

Functions

func ContextWithResponseDeadlineEnforcement

func ContextWithResponseDeadlineEnforcement(ctx context.Context) context.Context

ContextWithResponseDeadlineEnforcement marks MCP work whose full lifecycle is bounded by a tunnel command response deadline. Legacy commands without response_timeout intentionally remain unmarked.

func FindHeaderValue

func FindHeaderValue(headers http.Header, target string) *string

FindHeaderValue returns the value of a header in case-insensitive fashion. Nil is returned when the header is absent or the map is empty.

func IsAuthRequiredProbeError

func IsAuthRequiredProbeError(err error) bool

IsAuthRequiredProbeError reports whether a probe error indicates that the target MCP server is reachable but requires OAuth or other request authentication before initialize succeeds.

func IsTimeoutProbeError

func IsTimeoutProbeError(err error) bool

func NewProbeHTTPStatusError

func NewProbeHTTPStatusError(statusCode int, cause error) error

NewProbeHTTPStatusError attaches the observed HTTP status to a failed startup probe. It returns cause unchanged when no response status exists.

func NewProbeTimeoutError

func NewProbeTimeoutError(timeout time.Duration, cause error) error

func NewSharedConnectionTransport

func NewSharedConnectionTransport(base mcp.Transport) mcp.Transport

NewSharedConnectionTransport returns a transport wrapper that reuses the same underlying connection across Connect calls.

func SessionIDFromHeaders

func SessionIDFromHeaders(headers http.Header) *string

SessionIDFromHeaders searches the provided headers map for the MCP session identifier and returns it when present.

Types

type ChannelStdioRuntimeInfoProvider

type ChannelStdioRuntimeInfoProvider interface {
	StdioRuntimeInfo(channel types.Channel) (StdioRuntimeInfo, bool)
}

ChannelStdioRuntimeInfoProvider exposes stdio process details per channel.

type ChannelTransportFactory

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

ChannelTransportFactory builds and caches MCP transports for configured channel bindings.

A connector request can arrive on any logical tunnel-service channel. The dispatcher asks this factory for the binding-specific transport, and the factory keeps one cached transport/HTTP client per channel so session headers, proxy selection, mTLS config, and raw-HTTP logging remain stable across requests for that channel.

func (*ChannelTransportFactory) Build

Build returns a cached transport for the requested binding. Concurrent first use of the same channel is collapsed with singleflight so duplicate connector traffic cannot race into multiple stdio child processes or independent HTTP transport wrappers.

func (*ChannelTransportFactory) HTTPClientForBinding

func (f *ChannelTransportFactory) HTTPClientForBinding(binding config.MCPChannelBinding) (*http.Client, error)

HTTPClientForBinding returns the HTTP client used for streamable MCP transports for a binding.

type ForwardingConnection

type ForwardingConnection interface {
	// Write writes a new message to the connection.
	//
	// Write may be called concurrently, as calls or responses may occur
	// concurrently in user code.
	//
	// It returns the downstream HTTP result together with an error (if any)
	// encountered while writing or processing the response. A recognized MCP
	// error returned with a non-success HTTP status is carried in
	// PreservedError and is not returned as a transport error.
	Write(context.Context, http.Header, jsonrpc.Message) (ForwardingWriteResult, error)

	Read(ctx context.Context) (jsonrpc.Message, error)

	// Close closes the connection. It is implicitly called whenever a Read or
	// Write fails.
	//
	// Close may be called multiple times, potentially concurrently.
	Close() error
}

ForwardingConnection extends mcp.Connection with helpers that return the response headers collected from the underlying HTTP transport.

type ForwardingTransport

type ForwardingTransport interface {
	Connect(ctx context.Context) (ForwardingConnection, error)
}

ForwardingTransport decorates an mcp.Transport so callers can attach per-request headers and capture the response headers returned by the MCP server.

func NewForwardingTransport

func NewForwardingTransport(base mcp.Transport) ForwardingTransport

NewForwardingTransport wraps the provided transport with header-forwarding capabilities.

func NewSerializedForwardingTransport

func NewSerializedForwardingTransport(base ForwardingTransport) ForwardingTransport

NewSerializedForwardingTransport wraps a ForwardingTransport so only one request lifecycle is active on the shared underlying connection at a time.

Some MCP transports multiplex poorly when several connector calls write to the same long-lived connection and then each reader waits for its own response. The wrapper holds a lifecycle slot from Connect through any streamed notifications until the matching final JSON-RPC response, an error, or Close. Notifications without ids release immediately after the write because no response is legal.

type ForwardingWriteResult

type ForwardingWriteResult struct {
	StatusCode      int
	ResponseHeaders http.Header
	PreservedError  *PreservedMCPError
}

ForwardingWriteResult is the downstream HTTP result observed while writing an MCP message.

type NonProtocolResponseError

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

NonProtocolResponseError is handed to the separate fallback-classification path when a downstream response is not a valid, preservable MCP error.

func (*NonProtocolResponseError) Error

func (e *NonProtocolResponseError) Error() string

func (*NonProtocolResponseError) Kind

Kind returns a bounded reason suitable for classification and tests.

func (*NonProtocolResponseError) Unwrap

func (e *NonProtocolResponseError) Unwrap() error

type NonProtocolResponseKind

type NonProtocolResponseKind string

NonProtocolResponseKind identifies why a downstream non-success response could not be preserved as an MCP JSON-RPC error.

const (
	NonProtocolResponseBodyMissing     NonProtocolResponseKind = "response_body_missing"
	NonProtocolResponseBodyUnreadable  NonProtocolResponseKind = "response_body_unreadable"
	NonProtocolResponseBodyTooLarge    NonProtocolResponseKind = "response_body_too_large"
	NonProtocolResponseMalformedJSON   NonProtocolResponseKind = "malformed_json"
	NonProtocolResponseInvalidMCPError NonProtocolResponseKind = "invalid_mcp_error"
)

type PreservedMCPError

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

PreservedMCPError is a recognized target-owned JSON-RPC error response. Its payload stays opaque so exact code, message, data, and future fields survive the tunnel unchanged.

func NewPreservedMCPError

func NewPreservedMCPError(payload []byte, code int64) *PreservedMCPError

NewPreservedMCPError constructs an opaque preserved response. Normal runtime callers receive these only after forwardingConnection validates the target JSON-RPC response; the constructor also supports alternate ForwardingConnection implementations and focused dispatcher tests.

func (*PreservedMCPError) Code

func (e *PreservedMCPError) Code() int64

Code returns the bounded JSON-RPC error code for safe diagnostics.

func (*PreservedMCPError) Payload

func (e *PreservedMCPError) Payload() []byte

Payload returns a defensive copy of the exact target JSON-RPC payload.

type ProbeHTTPStatusError

type ProbeHTTPStatusError struct {
	StatusCode int
	Cause      error
}

ProbeHTTPStatusError preserves the HTTP response status observed while the startup probe failed, without relying on the SDK's formatted error text.

func (*ProbeHTTPStatusError) Error

func (e *ProbeHTTPStatusError) Error() string

func (*ProbeHTTPStatusError) Unwrap

func (e *ProbeHTTPStatusError) Unwrap() error

type ProbeState

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

ProbeState tracks the result of the one-time startup probe against the main MCP channel.

func NewProbeState

func NewProbeState() *ProbeState

NewProbeState constructs an empty ProbeState.

func (*ProbeState) IsDone

func (p *ProbeState) IsDone() bool

IsDone reports whether the probe has completed.

func (*ProbeState) Set

func (p *ProbeState) Set(err error)

Set records the probe result and signals waiters.

func (*ProbeState) Wait

func (p *ProbeState) Wait(timeout time.Duration) (time.Time, error, bool)

Wait blocks until the probe result is available or the timeout elapses.

func (*ProbeState) WaitUntilDone

func (p *ProbeState) WaitUntilDone(ctx context.Context) error

WaitUntilDone blocks until the startup probe records a result or ctx is canceled.

type ProbeTimeoutError

type ProbeTimeoutError struct {
	Timeout time.Duration
	Cause   error
}

ProbeTimeoutError reports that the startup probe did not complete before the deadline.

func (*ProbeTimeoutError) Error

func (e *ProbeTimeoutError) Error() string

func (*ProbeTimeoutError) Unwrap

func (e *ProbeTimeoutError) Unwrap() error

type SessionTerminatingTransport

type SessionTerminatingTransport interface {
	TerminateSession(ctx context.Context, headers http.Header) (int, http.Header, error)
}

SessionTerminatingTransport can explicitly close an MCP Streamable HTTP session and report the upstream HTTP response returned by the MCP server.

type StdioRuntimeInfo

type StdioRuntimeInfo struct {
	PID     int    `json:"pid,omitempty"`
	Command string `json:"command,omitempty"`
}

StdioRuntimeInfo describes the active stdio MCP process details.

type StdioRuntimeInfoProvider

type StdioRuntimeInfoProvider interface {
	StdioRuntimeInfo() StdioRuntimeInfo
}

StdioRuntimeInfoProvider exposes runtime details for stdio transport.

type TransportBuildParams

type TransportBuildParams struct {
	Config     *config.MCPConfig
	Binding    config.MCPChannelBinding
	HTTPClient *http.Client
}

TransportBuildParams carries shared dependencies for transport construction.

type TransportProvider

type TransportProvider interface {
	Kind() config.MCPTransportKind
	Build(TransportBuildParams) (mcp.Transport, error)
}

TransportProvider constructs an MCP transport for a specific transport kind.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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