upstreamclient

package
v1.0.310 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package upstreamclient is the bounded, Model-A upstream MCP client for the Gateway capability (PR-11). It reuses the PR-1 kernel (internal/mcp/jsonrpc + internal/mcp/protocol + internal/mcp/session) for the upstream-server-facing leg — there is NO second permissive decoder — and the PR-7 destination controls (internal/mcp/inspection/destination) for SSRF classification, resolve→connect DNS pinning, connect-time peer verification, and redirect rejection.

It speaks ONLY remote Streamable HTTP, ONLY the admitted V1 methods (initialize, notifications/initialized, ping, notifications/cancelled, tools/list, tools/call), and ONLY the supported protocol versions (2025-11-25 / 2025-06-18). No batch, no legacy SSE, no automatic downgrade, no arbitrary/extension methods, no server-originated sampling/elicitation. The upstream endpoint comes ONLY from the registered server record — never a request-supplied URL. No client token is ever forwarded upstream.

Index

Constants

View Source
const AttemptHeader = "Mcp-Culvert-Attempt-Id"

AttemptHeader carries the Culvert-minted attempt identity to the upstream so an independent recording witness can attribute each received invocation to exactly one authorized attempt. It is non-secret by construction: it names an attempt, it does not authorize one.

Variables

This section is empty.

Functions

func Admitted

func Admitted(method string) bool

Admitted reports whether method is in the V1 upstream set.

func MarkNeverSentForTest added in v1.0.218

func MarkNeverSentForTest(err error) error

MarkNeverSentForTest exposes the never-sent marker to tests in other packages, so an executor-side double can reproduce the exact error shape the production client produces when a call is refused before any leg begins. It is a test seam only: production marking happens inside Call and roundTrip, where the evidence lives.

func MarkResponseObservedForTest added in v1.0.218

func MarkResponseObservedForTest(err error) error

MarkResponseObservedForTest is the mirror seam: it produces the exact error shape the production client returns when the PEER ANSWERED but the answer was unusable — a non-200, an unreadable body, undecodable bytes. Without it an executor-side double cannot reproduce the case at all, because a bare error stays at the conservative may_have_been_sent and every predicate that distinguishes "the peer failed" from "we never heard back" reads the same on both. That gap let a health-detector defect ship: a gate written with a bare error passed against the defective predicate AND the fixed one, proving nothing (Codex round 5). Test seam only; production marking happens in markLegFacts.

func NegotiateVersion

func NegotiateVersion(serverSelected protocol.Version) (protocol.Version, error)

NegotiateVersion returns the version to offer upstream (the primary), and validates a server-selected version is supported (no downgrade to a rejected era). It reuses the protocol package's version rules.

func ResponseObserved added in v1.0.218

func ResponseObserved(err error) bool

ResponseObserved reports whether a failed Call nevertheless observed a response from the peer — a non-200 status, an unreadable body, or bytes that would not decode. It is the difference between "the invocation may have reached the peer" and "it demonstrably did", and it is an INCREASE in knowledge only: an error this returns false for keeps whatever uncertainty the caller already had.

The unwrapped Reason is preserved, so mcperr classification is unaffected.

func SendNeverStarted added in v1.0.218

func SendNeverStarted(err error) bool

SendNeverStarted reports whether a failed Call provably never put request bytes on a connection. Like ResponseObserved it is an INCREASE in knowledge only: an error this returns false for keeps whatever uncertainty the caller already had, so a caller that has not been taught about this fact — or a test double that returns a bare error — stays at the conservative may_have_been_sent.

It is the ONLY way definitely_not_sent becomes reachable from inside Call, and the evidence has to be that strong: it is the strongest claim in the send-state lattice and the one an operator would act on by re-running the invocation.

Types

type CallOptions

type CallOptions struct {
	// Idempotent marks a read-only call that MAY be retried on a transport-ambiguous
	// pre-response failure. A write/destructive tools/call MUST leave this false.
	Idempotent bool
	// WireID is the independent upstream-leg JSON-RPC id (never assumed equal to the
	// client-leg id). Empty ⇒ the client assigns one.
	WireID string
	// AuthHeader is the OPTIONAL upstream Authorization header value — the
	// broker-materialized credential for the APPROVED SERVER (e.g. "Bearer <token>").
	// It is NEVER the client's own token (the client token is never forwarded); it is
	// set only from inside the broker materialization callback and lives only for the
	// duration of the request.
	AuthHeader string
	// PreSend, when non-nil, is the caller's authority predicate, re-asked at every point on this
	// path where an unbounded wait has just ended and nothing has yet been written. A non-nil error
	// aborts that leg with no request bytes on any connection.
	//
	// IT EXISTS BECAUSE THE WAITS HERE ARE UNBOUNDED. The executor's boundary guards (tool drift,
	// rollout authority, emergency kill) run immediately before Call, and the code there said
	// nothing sits between them and the send — true of that function, false of this one. A kill, a
	// demotion, a scope withdrawal or an approval revocation can land, return successfully, and the
	// waiting request then sends anyway (Codex P1, PR #1370, rounds 4 and 6).
	//
	// TWO SITES, covering different phases, neither able to stand in for the other:
	//
	//	roundTrip, before client.Do  — after `pool.acquire` (which ends only when ANOTHER request
	//	                               finishes) and after DNS resolution.
	//	pinnedDialTLS, after the TLS handshake — after the TCP connect and the handshake, with the
	//	                               connection established and nothing written.
	//
	// Neither substitutes for the other because they BRACKET DIFFERENT PHASES: the pool wait and
	// the DNS lookup are already behind the first site and the dialer never sees them, while the
	// connect and the handshake are still ahead of it and only the dialer can sit after them.
	//
	// Both run PER LEG: a retry is a second physical send, and re-sending on the strength of a
	// check made before an earlier leg is the same defect one loop iteration over. The dialer site
	// reaches every leg because each leg builds its OWN transport and releases its idle connections
	// when it ends (see roundTrip), so no leg can inherit a connection another leg opened.
	//
	// It is deliberately OPAQUE: this package learns nothing about generations, scopes, approvals
	// or kill state — it runs a predicate the executor owns and reports the error verbatim.
	//
	// IT MUST BE A PURE PREDICATE: ITS LIFETIME IS NOT Call's. The dialer site runs on whatever
	// goroutine net/http dials on (Transport.queueForDial -> go dialConnFor), and that goroutine
	// is not joined to the request: when the caller's context is cancelled while a dial is in
	// flight — a client disconnect, a request timeout — getConn returns at once and Call unwinds,
	// while the dial goroutine completes its handshake and calls this hook. So the hook may run
	// CONCURRENTLY with, and FINISH AFTER, Call's return (pinned by
	// TestPreSend_MayStillBeRunningAfterCallReturns).
	//
	// A caller must therefore NOT write anything it intends to read back after Call returns.
	// Captured variables are a data race; synchronising them removes the race and still is not a
	// hand-off, because a late hook can write after the only reader has gone. There is no need
	// for one: a refusal that GOVERNED the leg comes back as Call's own error, verbatim
	// (roundTrip returns it directly; the dialer site rides out through preSendRefusalErr), and
	// an error that reached the caller's goroutine happened-before the caller reads it. Put
	// everything the verdict needs to be diagnosed ON the error.
	PreSend func() error
	// AttemptID names the ONE potential physical tool invocation this call carries
	// (review §5). It is emitted as a request header so the controlled recording
	// upstream can attribute each received invocation to exactly one authorized
	// attempt — the correlation an independent witness needs to answer "did Culvert
	// cause exactly the effects it authorized?". It is non-secret, and empty for
	// lifecycle/discovery traffic, which carries no attempt.
	AttemptID string
}

CallOptions carry per-call knobs.

type Client

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

Client is the bounded upstream MCP client. It is safe for concurrent use; each server gets an independent bounded pool/queue/in-flight budget.

func New

func New(cfg Config, kernelLim limits.Limits) (*Client, error)

New constructs a Client. It fails closed on an invalid config.

func (*Client) Call

func (c *Client) Call(ctx context.Context, target Target, method string, params json.RawMessage, opts CallOptions) (*Response, error)

Call executes a single admitted upstream method against target and returns the decoded response. It fails closed with a classified, sanitized error; it never leaks a raw network error or forwards a client token.

type Config

type Config struct {
	Limits           Limits
	Resolver         destination.Resolver
	Policy           destination.Policy
	InspectionLimits limits.InspectionLimits
	Identity         IdentityVerifier
	RootCAs          *x509.CertPool // nil ⇒ system roots
	Clock            func() time.Time
}

Config wires a Client. Resolver, Policy, and InspectionLimits are the PR-7 destination controls; Identity verifies the pinned TLS identity.

type IdentityVerifier

type IdentityVerifier interface {
	// VerifyIdentity returns nil ONLY when the peer's verified TLS state matches the
	// pinned identity exactly. An empty pinnedIdentity means "standard chain +
	// hostname verification already applies" and this returns nil.
	VerifyIdentity(state tls.ConnectionState, pinnedIdentity string) error
}

IdentityVerifier verifies a connected upstream peer's TLS identity against the server record's pinned identity. It is injected so a private-CA / self-signed internal MCP server can be pinned without a public chain.

type LimitConfig

type LimitConfig struct {
	MaxConnsPerServer int           // bounded per-server connection pool
	MaxQueuePerServer int           // bounded per-server request queue
	MaxInFlight       int           // bounded concurrent upstream calls per server
	MaxResponseBytes  int           // response header+body byte ceiling
	MaxRedirects      int           // redirect hops (0 ⇒ redirects rejected outright)
	ConnectTimeout    time.Duration // dial timeout
	TLSTimeout        time.Duration // TLS handshake timeout
	RequestTimeout    time.Duration // whole-request deadline
	PinTTL            time.Duration // resolve→connect pin lifetime
	MaxReadRetries    int           // bounded retry budget for idempotent reads
	// RetryMode interprets MaxReadRetries. Zero (RetryDefault) keeps the historical
	// fill-with-default behavior; RetryDisabled means exactly one physical attempt.
	RetryMode RetryMode
}

LimitConfig bounds every upstream resource. Zero in a field means the safe default.

type Limits

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

Limits is the immutable validated bounds set.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the safe default bounds.

func NewLimits

func NewLimits(c LimitConfig) (Limits, error)

NewLimits validates and freezes a bounds set, filling zero fields with defaults.

func RetryFreeLimits added in v1.0.218

func RetryFreeLimits(base LimitConfig) (Limits, error)

RetryFreeLimits returns bounds identical to base but with transport retries EXPLICITLY disabled. This is the First-Canary upstream client shape: one reservation, one attempt, at most one side-effect-bearing physical invocation.

func (Limits) ConnectTimeout

func (l Limits) ConnectTimeout() time.Duration

ConnectTimeout returns the dial timeout.

func (Limits) MaxConnsPerServer

func (l Limits) MaxConnsPerServer() int

MaxConnsPerServer returns the per-server connection pool bound.

func (Limits) MaxInFlight

func (l Limits) MaxInFlight() int

MaxInFlight returns the per-server in-flight bound.

func (Limits) MaxQueuePerServer

func (l Limits) MaxQueuePerServer() int

MaxQueuePerServer returns the per-server queue bound.

func (Limits) MaxReadRetries

func (l Limits) MaxReadRetries() int

MaxReadRetries returns the idempotent-read retry budget.

func (Limits) MaxRedirects

func (l Limits) MaxRedirects() int

MaxRedirects returns the redirect-hop bound (0 ⇒ reject redirects).

func (Limits) MaxResponseBytes

func (l Limits) MaxResponseBytes() int

MaxResponseBytes returns the response byte ceiling.

func (Limits) PinTTL

func (l Limits) PinTTL() time.Duration

PinTTL returns the resolve→connect pin lifetime.

func (Limits) RequestTimeout

func (l Limits) RequestTimeout() time.Duration

RequestTimeout returns the whole-request deadline.

func (Limits) RetriesDisabled added in v1.0.218

func (l Limits) RetriesDisabled() bool

RetriesDisabled reports whether this client performs exactly one physical attempt per Call. Call consults it BEFORE any idempotency/pre-response test, so no failure classification can reintroduce a second side-effect-bearing send.

func (Limits) TLSTimeout

func (l Limits) TLSTimeout() time.Duration

TLSTimeout returns the TLS handshake timeout.

func (Limits) Valid

func (l Limits) Valid() bool

Valid reports whether the limits were constructed.

type MethodClass added in v1.0.218

type MethodClass uint8

MethodClass partitions the admitted upstream methods by whether invoking them can cause a tool side effect at the peer.

const (
	// ClassUnknown is an unrecognized method. It is deliberately NOT exempt: see
	// SideEffectBearing.
	ClassUnknown MethodClass = iota
	// ClassLifecycle is MCP session/protocol traffic — it establishes or tears down
	// a session and invokes no tool.
	ClassLifecycle
	// ClassDiscovery enumerates the peer's tools. It reads a catalog; it invokes no
	// tool.
	ClassDiscovery
	// ClassToolInvocation is the ONLY class that can cause a tool side effect, and
	// therefore the only class that consumes a Canary execution reservation.
	ClassToolInvocation
)

func ClassifyMethod added in v1.0.218

func ClassifyMethod(method string) MethodClass

ClassifyMethod maps an upstream method to its class. The mapping is a closed allowlist over the admitted V1 method set; every other string is ClassUnknown.

func (MethodClass) SideEffectBearing added in v1.0.218

func (c MethodClass) SideEffectBearing() bool

SideEffectBearing reports whether an invocation of this class must be counted against the Canary execution budget and carry an attempt identity.

ClassUnknown answers TRUE. That is the fail-closed direction and it is the whole point of the predicate: a method nobody classified must never be cheaper than one that was. Exemption is granted only to classes positively known to invoke no tool.

func (MethodClass) String added in v1.0.218

func (c MethodClass) String() string

String returns the stable machine string used in evidence and witness records.

type Response

type Response struct {
	ID     jsonrpc.ID
	Result json.RawMessage
	Error  *jsonrpc.ErrorObject
	// RawBytes is the exact bounded response body (for downstream inspection/DLP).
	RawBytes []byte
}

Response is the decoded, admitted upstream JSON-RPC response.

type RetryMode added in v1.0.218

type RetryMode uint8

RetryMode selects how MaxReadRetries is INTERPRETED. It exists because the historical encoding could not express "no transport retries" at all: zero means "use the safe default" (2) and negatives are rejected, so every configuration — including a deliberately retry-free one — got a retrying client.

That ambiguity is a security property, not a style question. The First Controlled Canary requires that ONE accepted execution reservation produce AT MOST ONE physical side-effect-bearing tool invocation; a transport that may silently re-send an idempotent read turns one authorized effect into up to three, and the emergency kill is not re-read between those attempts. The mode is therefore explicit and closed: no magic sentinel, no overloaded zero.

const (
	// RetryDefault is the zero value and preserves the historical behavior for
	// every existing caller: MaxReadRetries==0 fills with the safe default.
	RetryDefault RetryMode = iota
	// RetryDisabled performs EXACTLY ONE physical attempt per Call, whatever the
	// method's idempotency or the failure's pre-response classification. Setting a
	// non-zero MaxReadRetries alongside it is a contradiction and fails closed.
	RetryDisabled
)

type Target

type Target struct {
	ServerID       string
	Endpoint       string // https URL from the registered record
	PinnedIdentity string // TLS identity to verify (empty ⇒ standard verification)
}

Target identifies the upstream server. Endpoint and PinnedIdentity come ONLY from the registered server record — never from a request.

Jump to

Keyboard shortcuts

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