Documentation
¶
Overview ¶
Package probe is the Streamable-HTTP MCP client used by the runner (sidecar + MCPServer tool synthesis and dispatch), the operator controllers (MCPServer / SidecarToolbox reachability), and the oap CLI. It is backed by the official MCP Go SDK (see session.go), so it speaks the full session protocol; a bare stateless JSON-RPC POST is rejected by spec-compliant servers.
Streamable-HTTP MCP client backed by the official MCP Go SDK (github.com/modelcontextprotocol/go-sdk). The SDK client speaks the full session protocol (initialize → Mcp-Session-Id → notifications/initialized → requests, plus SSE unwrapping and reconnects), which a hand-rolled stateless JSON-RPC POST does NOT — spec-compliant servers (the MCP go-sdk and TS SDK, e.g. the dedicated-mcp sidecar) reject bare tools/list with "invalid during session initialization". Both the reachability probe (ListTools) and the tool-call dispatcher (CallTool) go through here so every MCP integration — external MCPServers and in-cluster sidecars alike — is session-compliant.
Auth (and OAuth-rotation reauth-on-401) live in a RoundTripper on the injected HTTP client, so the SDK client and the dispatcher's CEL/audit/toolguard middleware stay auth-agnostic.
SessionCache keeps ONE persistent MCP ClientSession per (server URL, credential) for the lifetime of an AgentSession, so server-side per-session state survives across tool calls.
Why this exists: a stateful MCP server (the dedicated-mcp sidecar) keys its per-request selection — which PermissionSystem / cluster this agent picked — by the MCP session id (req.Session.ID()). The plain CallTool opens a fresh session (a new initialize handshake → a new session id) for every tool call and Closes it, so a selection made on one call is invisible to the next: the server answers "no PermissionSystem selected for this session" even though the agent just selected one. Reusing one session per AgentSession fixes that at the source — one selection, one session, many calls.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AllowlistDrift ¶
AllowlistDrift compares the tool names a spec PINS against the ones a server actually serves, and renders the finding.
missing is every pinned name the server does not serve, sorted and deduplicated; it is nil when the pin holds. message is empty in that case, and otherwise names BOTH halves of the finding: the pinned names that are absent, and what the server does offer instead.
Naming what IS served is the whole point of this function. "pinned tools not served: [get_pull_request]" tells a reader that something is wrong and nothing about what to do; the same line with the server's own list beside it usually shows the tool under its new name, which turns a dead end into a one-line spec edit. A server that serves NOTHING is called out in words rather than as an empty list — it usually means the credential was refused, not that the pin is stale, and those want different fixes.
Types ¶
type Annotations ¶
type Annotations struct {
// DestructiveHint: the server says the call may make changes that cannot
// simply be undone.
DestructiveHint bool `json:"destructiveHint,omitempty"`
// ReadOnlyHint: the server says the call changes nothing.
ReadOnlyHint bool `json:"readOnlyHint,omitempty"`
// IdempotentHint: the server says repeating the call has no extra effect.
IdempotentHint bool `json:"idempotentHint,omitempty"`
// OpenWorldHint: the server says the call reaches systems beyond itself.
OpenWorldHint bool `json:"openWorldHint,omitempty"`
// Title is a human-readable label some servers attach; passed
// through for completeness but not used by the validator.
Title string `json:"title,omitempty"`
// SEP-1913 trust + action-security annotations. See
// https://github.com/modelcontextprotocol/modelcontextprotocol/pull/1913
//
// The structured InputMetadata / ReturnMetadata are kept as raw
// JSON because the SEP's nested DataClass shape is still in
// flux — RawMessage round-trips any future shape losslessly.
// MaliciousActivityHint: the server declares it MAY flag malicious
// activity — a capability, not an accusation.
MaliciousActivityHint bool `json:"maliciousActivityHint,omitempty"`
// Attribution is who the server credits the tool's behavior to.
Attribution []string `json:"attribution,omitempty"`
// InputMetadata describes what the call does (outcomes, destination).
InputMetadata json.RawMessage `json:"inputMetadata,omitempty"`
// ReturnMetadata describes where the result comes from (source).
ReturnMetadata json.RawMessage `json:"returnMetadata,omitempty"`
// Visibility is MCP Apps' _meta.ui.visibility: which surfaces the tool
// is exposed to, "model" and/or "app". Recovered from the tool's _meta
// the same way SEP-1913's fields are, one level deeper (nested under
// "ui"). Empty/absent means the server did not assert it — this field
// mirrors the WIRE, so it stays nil rather than being defaulted to a
// non-nil slice; do not default it here.
//
// MCP Apps' own protocol treats an unset value as ambiguous (readable as
// "both"), but no reader in this repo does: this value is copied
// verbatim into mcpspec.Tool.Visibility, whose one consumer,
// pkg/agent/tool/mcp/synthesize.go's exclusive app/model split, treats
// empty/absent the same as ["model"] — model-visible only, never
// browser-callable. A caller reading THIS field directly (bypassing that
// split) must not assume "both"; it must go through synthesize.go's
// routing to get this repo's actual interpretation.
Visibility []string `json:"visibility,omitempty"`
}
Annotations mirrors the MCP protocol's tool annotation hints. Empty fields mean the server did not assert that hint.
type CallOutcome ¶
type CallOutcome struct {
Content []ContentBlock
IsError bool
// Meta is the raw response `_meta` object (SEP-1913 annotations etc.),
// nil when the server emits none. Callers parse the subset they consume.
Meta json.RawMessage
}
CallOutcome is the normalized result of a tools/call.
func CallTool ¶
func CallTool( ctx context.Context, url string, httpClient *http.Client, name string, args any, header, value string, reauth func(context.Context) (string, string, error), ) (*CallOutcome, error)
CallTool opens a session to the MCP server at url, calls tool `name` with `args`, and returns the normalized outcome. header/value are the optional auth header pair (pass "" / "" for none); reauth re-resolves the credential on a 401 (nil = no reauth). httpClient selects the reach path (plain for operator-controlled sidecar/loopback, SSRF-guarded for agent-supplied URLs).
type Client ¶
Client wraps an MCP server URL.
URL is an agent/attacker-influenceable value — it originates from an MCPServer CR's spec.server.url. When HTTP is nil, requests default to the SSRF-guarded safehttp.Client() so a hostile URL cannot reach loopback / link-local / private-network destinations. Only tests, the e2e harness, and operator-controlled reach paths (a sidecar pod IP / loopback, which the guard would correctly refuse) should set HTTP explicitly to a loopback-permitting client.
func (*Client) Initialize ¶
Initialize opens a session (which performs the MCP `initialize` handshake) and returns the server's self-reported identity. Header/value are sent verbatim; pass "" / "" for no auth. A server that omits serverInfo yields zero ServerInfo with nil error (audit metadata only — self-reported).
type ContentBlock ¶
type ContentBlock struct {
Type string // "text" | "image" | "audio" | "resource" | "unknown"
Text string
MIMEType string
Data []byte
URI string
// Resource* carry the embedded resource's own body, populated only for
// "resource" blocks (empty otherwise). Added so the MCP dispatcher can
// intercept mcp-ui / MCP Apps ui:// UI resources — whose document lives in
// Text or Blob and whose CSP lives in ResourceMeta (_meta.ui.csp) — instead
// of flattening them to a bare [resource: URI] placeholder.
ResourceMIMEType string
ResourceText string
ResourceBlob []byte
ResourceMeta json.RawMessage
}
ContentBlock is one normalized block of a tool-call result — the shape the dispatcher renders (mirrors the MCP content variants it handles). Sourced from the SDK's typed Content by contentBlocks so the dispatcher's rendering loop is unchanged by the SDK migration.
type Credential ¶
type Credential struct {
// ID identifies the credential SOURCE and MUST be stable across a rotation
// of Value: it is what decides which cached session this call joins (see
// sessionKey). Empty means no credential.
ID string
// Header is the request header Value is injected under. Empty means no auth
// is sent at all.
Header string
// Value is the credential's presentation for THIS call — the exact bytes
// that go upstream, which is what the caller's per-call authorization gate
// checked. A reused session's transport is set to it before the call.
Value string
// Reauth re-resolves (Header, Value) when the endpoint answers 401, so a
// token rotated out mid-session recovers inside the live session. Nil
// disables the retry.
Reauth func(context.Context) (header, value string, err error)
}
Credential is what a caller presents to an MCP endpoint, together with the identity of the credential it is presenting it FOR.
The package-level CallTool takes the presentation alone as loose arguments, which is all a one-shot session needs. A cached session outlives any single presentation of its credential — a refresh changes Value without changing which credential it is — so SessionCache needs the two separated, and takes them as one value rather than as four more positional arguments.
type HTTPError ¶
type HTTPError struct {
StatusCode int
// Body is the response body, truncated to 512 bytes (with a
// "...(truncated)" marker when truncation occurred).
Body string
}
HTTPError is returned by ListTools when the MCP server responds with a non-2xx status. Callers can use errors.As to distinguish auth failures (401/403) from other server errors when reporting controller conditions.
type ServerInfo ¶
type ServerInfo struct {
// Name is the implementation name the server calls itself.
Name string `json:"name"`
// Version is the implementation version the server reports.
Version string `json:"version"`
}
ServerInfo is the implementation identity a server self-reports in the initialize handshake. Audit metadata only: it is asserted by the server.
type SessionCache ¶
type SessionCache struct {
// contains filtered or unexported fields
}
SessionCache maps a (server URL, credential) pair to its live MCP session. One instance is owned by the runner per AgentSession and Closed when the session ends. It is safe for concurrent use — the runner dispatches tool calls in parallel.
func NewSessionCache ¶
func NewSessionCache() *SessionCache
NewSessionCache returns an empty cache. Sessions are opened lazily on the first CallTool for a given (url, credential) and reused thereafter.
func (*SessionCache) CallTool ¶
func (c *SessionCache) CallTool( ctx context.Context, url string, httpClient *http.Client, name string, args any, cred Credential, ) (*CallOutcome, error)
CallTool calls tool `name` on the MCP server at url over the cache's persistent session for that url AND credential (opening it on first use). See the package CallTool for the auth/reauth/httpClient contract, which is otherwise identical.
A failed call is re-issued ONLY when the server provably did not dispatch it: a 404 on the JSON-RPC POST, which per MCP §2.5.3 is how a server reports that it terminated the session (the sidecar restarted, the server GC'd an idle session). There the session is invalidated, reopened once, and the call retried on the fresh session.
Every other failure is returned as-is, because `cerr != nil` does NOT mean "the tool did not run": the go-sdk returns a Go error for a JSON-RPC *error response* as much as for a transport failure, so re-issuing on any error double-executes tools/call against a server that mutated state and then answered with a protocol error — and these are user-supplied sidecar MCP servers. A call the server answered (2xx) also leaves the session alone; tearing down the persistent session because a tool reported "unknown tool" helps nobody. An undetermined outcome (no response, 5xx, reset) drops the session so the NEXT call reopens, but is not re-issued.
A tool that merely *reports* failure surfaces as CallOutcome.IsError, not a Go error, and never reaches any of this.
func (*SessionCache) Close ¶
func (c *SessionCache) Close() error
Close closes every open session and marks the cache closed. Safe to call once at AgentSession end; subsequent CallTool returns an error rather than opening a new session.
type Tool ¶
type Tool struct {
// Name is the tool's identifier, as tools/call must address it.
Name string `json:"name"`
// Description is the server's own prose. It reaches the model verbatim
// unless a spec overrides it, so it is untrusted prompt text.
Description string `json:"description,omitempty"`
// InputSchema is the tool's declared argument schema. Empty when the
// server advertises none.
InputSchema json.RawMessage `json:"inputSchema,omitempty"`
// OutputSchema is the tool's declared result schema (MCP
// 2025-06-18 revision). Empty when the server does not advertise
// one. Like InputSchema, preserved as raw JSON.
OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
// Annotations are the server's self-asserted hints about the tool.
Annotations Annotations `json:"annotations,omitempty"`
}
Tool is one entry in a tools/list response. InputSchema is preserved as raw JSON so callers can introspect its shape without committing to a JSON Schema parser.