connector

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 35 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 connector implements the Connector/MCP Registry — pre-authenticated OAuth/MCP sessions for runners without implementing auth flows themselves.

Index

Constants

View Source
const (
	MaxMCPRequestBytes    int64 = 1 << 20
	MaxMCPResponseBytes   int64 = 8 << 20
	MaxOAuthResponseBytes int64 = 1 << 20
)
View Source
const ConnectorSessionTTL = 15 * time.Minute

ConnectorSessionTTL is the absolute lifetime of a capability token. Not sliding — a stolen token dies after this window.

View Source
const HeaderConnectorSession = "X-Runkite-Connector-Session"

HeaderConnectorSession is the runner-facing capability token minted by GetSession for MCP connectors and required on POST .../mcp.

View Source
const StaticCredentialSessionTTL = time.Hour

StaticCredentialSessionTTL is the advisory expires_at for api_key/bearer GetSession responses. Remint hint only — does not revoke the underlying secret.

Variables

View Source
var (
	// ErrMCPDispatchBlocked means the evidence callback refused dispatch. It is
	// a local authorization failure, not a failed request to the MCP service.
	ErrMCPDispatchBlocked = errors.New("protected MCP dispatch could not be authorized")
	// ErrMCPResponseUnverified does not mean the tool had no effects.
	ErrMCPResponseUnverified = errors.New("protected MCP response could not be verified")
)
View Source
var (
	ErrTargetRevisionChanged     = errors.New("connector target changed; resubmit the operation for fresh review")
	ErrTargetRevisionUnavailable = errors.New("connector target revision is unavailable")
)
View Source
var DefaultCircuitBreakerConfig = CircuitBreakerConfig{
	FailureThreshold: 5,
	CooldownSeconds:  30,
}

DefaultCircuitBreakerConfig is used when a connector doesn't set its own circuit_breaker config.

View Source
var ErrBodyTooLarge = errors.New("connector body exceeds size limit")

ErrBodyTooLarge is returned before oversized data is forwarded or decoded. A downstream tool may already have executed when its response exceeds a cap; callers must not retry a write tool automatically after this error.

View Source
var ErrDatabaseCredentialsUnavailable = errors.New("database connector credentials unavailable")
View Source
var ErrNotFound = errors.New("connector not found")

ErrNotFound is returned when a connector name is not registered.

View Source
var ErrToolRevisionChanged = errors.New("tool definition changed; fresh review is required")
View Source
var ErrToolRevisionUnavailable = errors.New("tool definition is unavailable")

Functions

func BoundMCPTransport added in v0.7.0

func BoundMCPTransport(ctx context.Context) string

func ExpandEnv

func ExpandEnv(s string) string

ExpandEnv replaces all ${VAR_NAME} occurrences in s with os.Getenv("VAR_NAME").

func ResolveSecretRef

func ResolveSecretRef(ctx context.Context, ref string) (string, error)

ResolveSecretRef fetches a secret for connector auth at GetSession time. Supported schemes:

env:VAR_NAME
file:/absolute/or/relative/path
vault:secret/data/runkite/...#field   (KV v2 JSON data.data)
vault:secret/runkite/...#field        (KV v1 JSON data — no /data/ segment)

Empty ref returns ("", nil). Unknown schemes and Vault paths outside VAULT_ALLOWED_PREFIX (default "secret/data/runkite/") fail closed. Paths are cleaned before the prefix check so `..` cannot escape the allowlist.

func TargetRevisionForConfig added in v0.7.0

func TargetRevisionForConfig(cfg ConnectorConfig) (string, error)

TargetRevisionForConfig fingerprints configured target identity, never a resolved credential or an upstream implementation. Endpoint URLs must not contain credentials. Revision is an operator's nonsecret contract version.

func ValidateTokenExchangeConfig added in v0.8.0

func ValidateTokenExchangeConfig(cfg AuthConfig) error

ValidateTokenExchangeConfig rejects accidental use under another grant and ambiguous/unbounded targets before credentials are fetched or requests sent.

func WithDelegatedSubject added in v0.8.0

func WithDelegatedSubject(ctx context.Context, token string) context.Context

WithDelegatedSubject is a trusted plane hook. HTTP handlers derive this from the assignment's authenticating user, never runner body/header user_context.

func WithExpectedTargetRevision added in v0.7.0

func WithExpectedTargetRevision(ctx context.Context, revision string) context.Context

func WithMCPActionCorrelation added in v0.8.0

func WithMCPActionCorrelation(ctx context.Context, action, lease string) context.Context

WithMCPActionCorrelation is a trusted executor hook. An HTTP client cannot provide these fields; enabling headers is also an operator target setting.

func WithMCPActionTrace added in v0.7.0

func WithMCPActionTrace(ctx context.Context, trace *MCPActionTrace) context.Context

func WithMCPDatabaseCredentials added in v0.7.0

func WithMCPDatabaseCredentials(ctx context.Context, binding, revision, username, password string) (context.Context, error)

WithMCPDatabaseCredentials is a trusted executor hook, not an HTTP header or runner capability. Its values must never be serialized or returned to agents.

Types

type AuthConfig

type AuthConfig struct {
	// TokenExchange opts into constrained RFC 8693 exchange. The issuer still
	// validates subject/actor tokens and enforces target resource policy.
	TokenExchange             *TokenExchangeConfig `json:"token_exchange,omitempty" yaml:"token_exchange,omitempty"`
	AllowInsecureLoopback     bool                 `json:"allow_insecure_loopback,omitempty" yaml:"allow_insecure_loopback,omitempty"`
	CredentialBinding         string               `json:"credential_binding,omitempty" yaml:"credential_binding,omitempty"`
	CredentialBindingRevision string               `json:"-" yaml:"-"`

	Type         string   `json:"type" yaml:"type"` // oauth2_token_exchange, oauth2_client_credentials, api_key, bearer
	Issuer       string   `json:"issuer,omitempty" yaml:"issuer,omitempty"`
	TokenURL     string   `json:"token_url,omitempty" yaml:"token_url,omitempty"`
	ClientID     string   `json:"client_id,omitempty" yaml:"client_id,omitempty"`
	ClientSecret string   `json:"client_secret,omitempty" yaml:"client_secret,omitempty"`
	Scopes       []string `json:"scopes,omitempty" yaml:"scopes,omitempty"`
	APIKey       string   `json:"api_key,omitempty" yaml:"api_key,omitempty"`
	BearerToken  string   `json:"bearer_token,omitempty" yaml:"bearer_token,omitempty"`
	// SecretRef resolves the primary credential at GetSession time
	// (env: / file: / vault:path#field). Do not also set api_key,
	// bearer_token, or client_secret for the same auth type — pick one.
	// The ref string itself is not ${ENV}-expanded.
	SecretRef string `json:"secret_ref,omitempty" yaml:"secret_ref,omitempty"`
}

AuthConfig describes how to authenticate with the external service.

type CachedToken

type CachedToken struct {
	AccessToken  string
	RefreshToken string
	ExpiresAt    time.Time
	InstanceURL  string // for Salesforce-style connectors
}

CachedToken holds an active credential set with its expiry.

type CircuitBreaker

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

CircuitBreaker is a standard 3-state (closed/open/half-open) breaker, one per connector, guarding the actual network call in its token-fetch path. api_key/bearer auth never call Allow/RecordSuccess/RecordFailure -- they don't make network calls, so there's nothing to break on.

closed: calls pass through; consecutive failures are counted. open: calls are rejected immediately (no network attempt) until the

cooldown elapses.

half_open: exactly one trial call is let through after cooldown; success

closes the breaker, failure reopens it (cooldown restarts).

func NewCircuitBreaker

func NewCircuitBreaker(cfg *CircuitBreakerConfig) *CircuitBreaker

NewCircuitBreaker builds a breaker, filling in DefaultCircuitBreakerConfig for any zero-valued fields.

func (*CircuitBreaker) Allow

func (cb *CircuitBreaker) Allow() bool

Allow reports whether a call should be attempted right now. When it returns true for a half-open trial, the caller MUST report the outcome via RecordSuccess/RecordFailure -- that single call is what decides whether the breaker closes or reopens.

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure counts a failure, opening the breaker once the threshold is reached (or immediately, if the failure was the half-open trial call).

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess resets the failure count and closes the breaker if it was trialing in half-open.

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() string

State reports the current state name, for status/debugging endpoints.

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	// FailureThreshold is how many consecutive token-fetch failures open
	// the breaker.
	FailureThreshold int `json:"failure_threshold,omitempty" yaml:"failure_threshold,omitempty"`
	// CooldownSeconds is how long the breaker stays open (rejecting calls
	// immediately, without attempting the network call) before allowing a
	// trial call through.
	CooldownSeconds int `json:"cooldown_seconds,omitempty" yaml:"cooldown_seconds,omitempty"`
}

CircuitBreakerConfig configures per-connector circuit breaking. Absent/zero-valued means DefaultCircuitBreakerConfig is used -- circuit breaking is always on, only its thresholds are tunable, since an unprotected connector taking down run-creation latency for every agent that needs it is never the right default.

type Connector

type Connector struct {
	Name   string
	Config ConnectorConfig
	// contains filtered or unexported fields
}

Connector is a single registered external-service connector.

type ConnectorConfig

type ConnectorConfig struct {
	Auth           AuthConfig            `json:"auth" yaml:"auth"`
	MCP            *MCPConfig            `json:"mcp,omitempty" yaml:"mcp,omitempty"`
	Errors         map[string]string     `json:"errors,omitempty" yaml:"errors,omitempty"`
	Tools          *ToolFilter           `json:"tools,omitempty" yaml:"tools,omitempty"`
	CircuitBreaker *CircuitBreakerConfig `json:"circuit_breaker,omitempty" yaml:"circuit_breaker,omitempty"`
}

ConnectorConfig defines an external service connector (auth, MCP, error mapping, tool filtering).

type ConnectorSession

type ConnectorSession struct {
	Token      string
	Connector  string
	RunID      string
	Generation int64
	TenantID   string
	AgentID    string
	Expires    time.Time
}

ConnectorSession is one short-lived MCP capability for a run.

type ConnectorSessionStore

type ConnectorSessionStore interface {
	Create(connector, runID string, generation int64, tenantID, agentID string) (*ConnectorSession, error)
	Get(token string) *ConnectorSession
	Delete(token string)
	TTL() time.Duration
}

ConnectorSessionStore mints and looks up MCP capability tokens.

func NewRedisConnectorSessionStore

func NewRedisConnectorSessionStore(rdb SessionRedisClient, ttl time.Duration) ConnectorSessionStore

NewRedisConnectorSessionStore shares MCP capability tokens via Redis (auto when REDIS_URL is set). ttl <= 0 uses ConnectorSessionTTL.

type ErrCircuitOpen

type ErrCircuitOpen struct {
	Connector string
}

ErrCircuitOpen is returned by Allow's caller convention: callers check Allow() first and should return this (or wrap it) instead of attempting the call.

func (*ErrCircuitOpen) Error

func (e *ErrCircuitOpen) Error() string

type MCPActionObservation added in v0.7.0

type MCPActionObservation struct {
	DispatchStarted  bool
	ResponseObserved bool
	HTTPStatus       *int
	RPCErrorCode     *int64
	ResponseBytes    *int64
	ResponseKind     string
	ReasonCode       string
}

MCPActionObservation contains only bounded protocol facts. It deliberately excludes request IDs, arguments, credentials, URLs and provider error text.

type MCPActionTrace added in v0.7.0

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

MCPActionTrace is request-local evidence plumbing, not a downstream execution receipt. The callback must commit authorization and intent before returning.

func NewMCPActionTrace added in v0.7.0

func NewMCPActionTrace(before func(context.Context) error) *MCPActionTrace

func (*MCPActionTrace) Snapshot added in v0.7.0

func (t *MCPActionTrace) Snapshot() MCPActionObservation

type MCPConfig

type MCPConfig struct {
	CorrelationHeaders bool `json:"correlation_headers,omitempty" yaml:"correlation_headers,omitempty"`
	PinTools           bool `json:"pin_tools,omitempty" yaml:"pin_tools,omitempty"`

	URL string `json:"url" yaml:"url"`
	// Revision is a nonsecret operator contract version for changes not visible
	// in the endpoint configuration, such as a changed remote implementation.
	Revision string `json:"revision,omitempty" yaml:"revision,omitempty"`
	// Transport defaults to the existing single-POST JSON proxy. The SDK
	// mode negotiates an upstream session for each proxied operation.
	Transport string `json:"transport,omitempty" yaml:"transport,omitempty"` // json or streamable_http
}

MCPConfig points to an MCP server endpoint.

type MCPRequest

type MCPRequest struct {
	ID        json.RawMessage
	Method    string
	Tool      string
	Arguments json.RawMessage
	Body      []byte
}

MCPRequest is the single interpretation used for enforcement and forwarding. Arguments remain raw JSON so application keys retain their spelling and case.

func ParseMCPRequest

func ParseMCPRequest(body []byte) (*MCPRequest, error)

ParseMCPRequest rejects ambiguous reserved keys before creating the bytes that will reach the downstream server. Go struct decoding is case-insensitive and must not be used to authorize an unmodified JSON-RPC envelope.

type MCPSession

type MCPSession struct {
	// URL is a path relative to the control plane's own HTTP base
	// (which the runner already knows -- RUNKITE_HTTP_URL/--http-address),
	// NOT the connector's raw downstream MCP server URL. It points at
	// this control plane's own MCP proxy (mcpproxy.go), which forwards
	// requests to the real server while actually enforcing the tool
	// allow/deny filter (tools/call is gated, tools/list is filtered) --
	// see mcpproxy.go's doc comment for why a proxy is what makes that
	// enforcement real instead of advisory. Was the raw downstream URL
	// before this existed; every caller of this field needed no changes
	// since it was already treated as an opaque endpoint to connect to.
	URL string `json:"url"`
	// Tools is a best-effort preview of what tools/list through URL
	// will return, computed WITHOUT calling the downstream server (see
	// allowedTools' own doc comment for why this can't represent a
	// deny-only filter correctly) -- an agent that needs the accurate,
	// fully-filtered list should call tools/list through URL itself
	// rather than relying on this field alone.
	Tools []string `json:"tools,omitempty"`
}

MCPSession describes a ready-to-use MCP connection.

type MemoryConnectorSessionStore

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

MemoryConnectorSessionStore is the process-local store (no Redis).

func NewMemoryConnectorSessionStore

func NewMemoryConnectorSessionStore(ttl time.Duration) *MemoryConnectorSessionStore

NewMemoryConnectorSessionStore creates an empty memory store. ttl <= 0 uses ConnectorSessionTTL.

func (*MemoryConnectorSessionStore) Create

func (s *MemoryConnectorSessionStore) Create(connectorName, runID string, generation int64, tenantID, agentID string) (*ConnectorSession, error)

func (*MemoryConnectorSessionStore) Delete

func (s *MemoryConnectorSessionStore) Delete(token string)

func (*MemoryConnectorSessionStore) Get

func (*MemoryConnectorSessionStore) TTL

type OAuthEndpointError added in v0.7.0

type OAuthEndpointError struct {
	StatusCode int
	Code       string
}

OAuthEndpointError retains only safe classification from a rejected token request. Provider bodies, descriptions, headers and endpoint URLs are omitted.

func (*OAuthEndpointError) Error added in v0.7.0

func (e *OAuthEndpointError) Error() string

type ProxyMCPResult

type ProxyMCPResult struct {
	Body       []byte
	StatusCode int
}

ProxyMCPResult is a successful proxy outcome: a JSON-RPC response body (which may itself carry a JSON-RPC-level error, e.g. tool-not-allowed or whatever the downstream server returned) and the HTTP status to send it with. Distinct from the error return, which is reserved for transport-level failures this call couldn't even get a JSON-RPC response for (unknown connector, circuit open, downstream unreachable) -- the same split GetSession already uses, so handleProxyMCPRequest in internal/api/server.go can reuse its exact error-handling pattern.

func DeniedRPCResult

func DeniedRPCResult(id json.RawMessage, message string, data map[string]interface{}) (*ProxyMCPResult, error)

DeniedRPCResult builds an HTTP-200 JSON-RPC error (-32000) for a denied tools/call. data is optional (e.g. reason_code from policy). Does not contact the downstream server or the circuit breaker.

type Registry

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

Registry manages connector configurations and session creation.

func NewRegistry

func NewRegistry(configs map[string]ConnectorConfig) *Registry

NewRegistry creates a Registry from a map of connector configs. Environment variables in auth fields are expanded at registration time.

func (*Registry) BindMCPRequestTarget added in v0.7.0

func (r *Registry) BindMCPRequestTarget(ctx context.Context, name string) (context.Context, string, error)

BindMCPRequestTarget pins one request's endpoint, transport, filter and auth configuration before authority is evaluated or consumed. Secret references are still resolved at session time; values never enter the fingerprint.

func (*Registry) BindMCPToolRevision added in v0.7.0

func (r *Registry) BindMCPToolRevision(ctx context.Context, name, tool string, user map[string]interface{}) (context.Context, string, error)

BindMCPToolRevision reads the advertised definition only for an opted-in connector. It does not attest the server implementation or execute a tool.

func (*Registry) BoundCredentialBinding added in v0.7.0

func (r *Registry) BoundCredentialBinding(ctx context.Context, name string) (string, string, error)

func (*Registry) BoundDelegationContract added in v0.8.0

func (r *Registry) BoundDelegationContract(ctx context.Context, name string) (*models.DelegationContract, error)

BoundDelegationContract uses the frozen request target, never live config or fields supplied by an agent. It describes intended exchange constraints.

func (*Registry) BreakerState

func (r *Registry) BreakerState(name string) string

BreakerState reports a connector's circuit breaker state ("closed", "open", "half_open"), for status/debugging endpoints. Returns "" for an unknown connector name.

func (*Registry) Get

func (r *Registry) Get(name string) (*Connector, error)

Get returns a connector by name or ErrNotFound.

func (*Registry) GetSession

func (r *Registry) GetSession(ctx context.Context, name string, userCtx map[string]interface{}) (*SessionResponse, error)

GetSession performs the auth flow for a connector and returns ready-to-use credentials.

func (*Registry) IsToolAllowed

func (r *Registry) IsToolAllowed(name string, tool string) bool

IsToolAllowed checks if a specific tool is permitted for a connector.

func (*Registry) List

func (r *Registry) List() []string

List returns registered connector names in sorted order.

func (*Registry) ProxyMCPRequest

func (r *Registry) ProxyMCPRequest(ctx context.Context, name string, userCtx map[string]interface{}, body []byte) (*ProxyMCPResult, error)

ProxyMCPRequest forwards one JSON-RPC request to a connector's configured downstream MCP server, enforcing its tool allow/deny list at the two points where it actually matters. See this file's own doc comment for the full rationale.

func (*Registry) TargetRevision added in v0.7.0

func (r *Registry) TargetRevision(name string) (string, error)

type SessionRedisClient

type SessionRedisClient interface {
	Get(ctx context.Context, key string) *redis.StringCmd
	Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.StatusCmd
	Del(ctx context.Context, keys ...string) *redis.IntCmd
}

SessionRedisClient is the subset of go-redis used by the Redis store.

type SessionResponse

type SessionResponse struct {
	Credentials map[string]string `json:"credentials"`
	ExpiresAt   string            `json:"expires_at"`
	// SessionToken is a short-lived capability for MCP proxy calls
	// (HeaderConnectorSession). Set by the HTTP session handler for MCP
	// connectors only — not minted during run pre-warm into assignment
	// Context (those would expire in the queue).
	SessionToken string      `json:"session_token,omitempty"`
	MCP          *MCPSession `json:"mcp,omitempty"`
}

SessionResponse is the runner-facing credential payload.

type TokenExchangeConfig added in v0.8.0

type TokenExchangeConfig struct {
	Audiences           []string `json:"audiences,omitempty" yaml:"audiences,omitempty"`
	Resources           []string `json:"resources,omitempty" yaml:"resources,omitempty"`
	ActorTokenSecretRef string   `json:"actor_token_secret_ref,omitempty" yaml:"actor_token_secret_ref,omitempty"`
	ActorID             string   `json:"actor_id,omitempty" yaml:"actor_id,omitempty"`
	MaxTTLSeconds       int64    `json:"max_ttl_seconds,omitempty" yaml:"max_ttl_seconds,omitempty"`
}

TokenExchangeConfig is an operator-owned target and actor contract. It is never populated from tool arguments or user-provided target claims.

type ToolFilter

type ToolFilter struct {
	Allow []string `json:"allow,omitempty" yaml:"allow,omitempty"`
	Deny  []string `json:"deny,omitempty" yaml:"deny,omitempty"`
}

ToolFilter controls which MCP tools a connector exposes.

Jump to

Keyboard shortcuts

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