agentadapter

package
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 0 Imported by: 0

Documentation

Overview

Package agentadapter implements optional agent-side HTTP adapters that forward MCP traffic to governed MCP Runtime routes.

Index

Constants

View Source
const (
	EnvRuntimeURL      = "MCP_RUNTIME_URL"
	EnvHumanID         = "MCP_RUNTIME_HUMAN_ID"
	EnvAgentID         = "MCP_RUNTIME_AGENT_ID"
	EnvTeamID          = "MCP_RUNTIME_TEAM_ID"
	EnvSessionID       = "MCP_RUNTIME_SESSION_ID"
	EnvHostHeader      = "MCP_RUNTIME_HOST_HEADER"
	EnvListenAddr      = "MCP_RUNTIME_LISTEN_ADDR"
	EnvProtocolVersion = "MCP_RUNTIME_PROTOCOL_VERSION"
	EnvSetXForwarded   = "MCP_RUNTIME_SET_XFF"
	EnvRequestTimeout  = "MCP_RUNTIME_REQUEST_TIMEOUT"
	EnvLogLevel        = "MCP_RUNTIME_LOG_LEVEL"
	EnvAuthHeader      = "MCP_RUNTIME_AUTH_HEADER"
	EnvTLSClientCert   = "MCP_RUNTIME_TLS_CLIENT_CERT"
	EnvTLSClientKey    = "MCP_RUNTIME_TLS_CLIENT_KEY"
	EnvTLSCABundle     = "MCP_RUNTIME_TLS_CA_BUNDLE"
	// EnvTLSInsecureSkipVerify skips upstream TLS certificate verification.
	// Intended for local Kind port-forwards that terminate on Traefik's
	// default self-signed cert (same role as curl -k). Client certificates
	// are still presented when configured.
	EnvTLSInsecureSkipVerify = "MCP_RUNTIME_TLS_INSECURE_SKIP_VERIFY"
	EnvMaxInboundBytes       = "MCP_RUNTIME_MAX_INBOUND_BYTES"

	DefaultListenAddr      = "127.0.0.1:8099"
	DefaultProtocolVersion = "2025-06-18"

	MCPProtocolHeader = "Mcp-Protocol-Version"
	MCPSessionHeader  = "Mcp-Session-Id"
)
View Source
const (

	// DefaultMaxInboundBytes caps the size of inbound JSON-RPC bodies that
	// the proxy buffers for metadata capture. Requests over the cap get a
	// 413 with a JSON-RPC parse-error body so the agent SDK can recover.
	DefaultMaxInboundBytes int64 = 16 << 20
)
View Source
const MetaProtocolVersionKey = "io.modelcontextprotocol/protocolVersion"

MetaProtocolVersionKey carries the per-request MCP protocol version.

Variables

This section is empty.

Functions

func BuildTLSConfig

func BuildTLSConfig(certFile, keyFile, caFile string) (*tls.Config, error)

BuildTLSConfig builds a *tls.Config for outbound runtime connections. certFile and keyFile must both be set (or both empty) for mTLS. caFile, when non-empty, replaces the default system CA pool. insecureSkipVerify mirrors curl -k for local Kind Traefik default certs.

func BuildTLSConfigOptions

func BuildTLSConfigOptions(certFile, keyFile, caFile string, insecureSkipVerify bool) (*tls.Config, error)

BuildTLSConfigOptions is BuildTLSConfig with an explicit insecure-skip-verify switch for local development and Kind E2E port-forwards.

func NewHTTPProxyHandler

func NewHTTPProxyHandler(cfg ProxyConfig) (http.Handler, error)

NewHTTPProxyHandler returns a reverse proxy that forwards MCP HTTP traffic to the configured runtime route. Session identity is carried by the TLS client certificate (and OAuth bearer when the target enables it), not by request headers.

func NewHTTPTransportWithTLS

func NewHTTPTransportWithTLS(cfg *tls.Config) *http.Transport

NewHTTPTransportWithTLS returns an *http.Transport that uses the supplied TLS config while preserving http.DefaultTransport's dial timeouts, keep-alive settings, and ProxyFromEnvironment behaviour.

func RunHTTPProxy

func RunHTTPProxy(ctx context.Context, cfg ProxyConfig) error

RunHTTPProxy serves the local HTTP adapter until the context is cancelled.

Types

type Identity

type Identity struct {
	HumanID   string
	AgentID   string
	TeamID    string
	SessionID string
}

Identity is the adapter's session subject (human, agent, team, session). It is optional local metadata. Runtime governance identity is the session-bound client certificate (and OAuth bearer when the target enables it), not request headers.

type ProxyConfig

type ProxyConfig struct {
	RuntimeURL *url.URL
	// Identity is optional local metadata. Runtime
	// governance identity is the TLS client certificate, not headers.
	Identity  Identity
	Transport *RuntimeTransport
	// CertificateIdentity confirms that Transport presents a TLS client
	// certificate. The CLI sets it only after loading or enrolling a usable
	// keypair. OAuth-enabled targets additionally require a bearer token.
	CertificateIdentity bool
	HostHeader          string
	ListenAddr          string
	ProtocolVersion     string
	LogLevel            string
	LogWriter           io.Writer
	DisableXForwarded   bool
	// MaxInboundBytes caps the size of JSON-RPC request bodies the proxy
	// buffers when capturing metadata. Zero (or negative) means use
	// DefaultMaxInboundBytes (16 MiB). Over-cap requests respond with 413.
	MaxInboundBytes int64
	// MetricsHandler, when set, is served at /metrics. Typical use: a
	// Prometheus exporter wired to the OTel MeterProvider that backs
	// RuntimeTransport.Meter. Nil → /metrics returns 404.
	MetricsHandler http.Handler
}

ProxyConfig configures the local HTTP reverse-proxy adapter that exposes Streamable HTTP MCP to an agent SDK.

func LoadProxyConfigFromEnv

func LoadProxyConfigFromEnv() (ProxyConfig, error)

LoadProxyConfigFromEnv loads HTTP proxy configuration from environment variables.

func (ProxyConfig) Validate

func (cfg ProxyConfig) Validate() error

Validate requires a runtime URL and a TLS client certificate.

type RuntimeTransport

type RuntimeTransport struct {
	// Base is the underlying round-tripper. nil means http.DefaultTransport.
	// Tests swap in a mock by setting this field.
	Base http.RoundTripper
	// Timeout is the per-request timeout applied to the *http.Client wrapper
	// returned by Client(). Zero means no timeout.
	Timeout time.Duration
	// AuthHeader is a static Authorization header value injected into every
	// outbound request (e.g. "Bearer <token>"). Empty means no header is set.
	AuthHeader string
	// Tracer is an optional OTel tracer. When non-nil, RoundTrip opens one
	// client span per RPC labelled with the JSON-RPC method name.
	Tracer trace.Tracer
	// Meter is an optional OTel meter. When non-nil, RoundTrip records a
	// latency histogram and a denial counter keyed by method name.
	Meter metric.Meter
	// contains filtered or unexported fields
}

RuntimeTransport is the shared outbound HTTP transport used by both the reverse proxy when forwarding to the runtime. It owns every production gate — auth, OTel instrumentation, and method-keyed retry — so both adapters behave identically with a single implementation.

func (*RuntimeTransport) Client

func (t *RuntimeTransport) Client() *http.Client

Client returns an *http.Client whose Transport is this RuntimeTransport. Both adapters route requests through this wrapper so every gate (auth, OTel, retry) applies uniformly.

func (*RuntimeTransport) CloseIdleConnections

func (t *RuntimeTransport) CloseIdleConnections()

CloseIdleConnections drains idle connections on the base round-tripper if it supports the optional interface, matching net/http's contract.

func (*RuntimeTransport) RoundTrip

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

RoundTrip implements http.RoundTripper. Execution order per call:

  1. Start OTel span (if Tracer is set).
  2. Inject Authorization header (if AuthHeader is set).
  3. Execute the request, retrying idempotent methods on gateway errors.
  4. Record OTel latency histogram and denial counter (if Meter is set).
  5. Set span outcome and end it.

Jump to

Keyboard shortcuts

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