mcp

package
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 30 Imported by: ? 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 mcp provides runtime MCP transport callers, normalization helpers, and support utilities used by generated MCP adapters.

Package mcp OAuth helpers (oauth.go) provide protected-resource formatting shared by generated MCP servers and hand-written middleware. Pure formatting and URL canonicalization — no token validation happens here.

Index

Constants

View Source
const (
	// HeaderKeySessionID is the MCP streamable HTTP session header.
	HeaderKeySessionID = "Mcp-Session-Id"

	// HeaderKeyProtocolVersion is the MCP streamable HTTP protocol version header.
	HeaderKeyProtocolVersion = "MCP-Protocol-Version"
)
View Source
const ProtectedResourceMetadataPrefix = "/.well-known/oauth-protected-resource"

ProtectedResourceMetadataPrefix is the RFC 9728 well-known prefix for OAuth 2.0 protected-resource metadata.

Variables

View Source
var (
	// ErrProgressReporterUnavailable is returned when a context cannot send MCP progress notifications.
	ErrProgressReporterUnavailable = errors.New("mcp progress reporter unavailable")
	// ErrProgressTokenUnavailable is returned when the active request did not supply a progress token.
	ErrProgressTokenUnavailable = errors.New("mcp progress token unavailable")
)
View Source
var ErrElicitorUnavailable = errors.New("mcp elicitor unavailable")

ErrElicitorUnavailable is returned when a context has no MCP elicitor.

View Source
var ErrEmptyResourceURL = errors.New("mcp/oauth: cannot derive canonical resource URL")

ErrEmptyResourceURL signals that CanonicalizeResourceURL could not derive a non-empty scheme+host for the request. Callers should treat this as a 400 Bad Request because RFC 9728 requires `resource` to be a fully-qualified URI.

View Source
var ErrInvalidForwardedHeaders = errors.New("mcp/oauth: invalid forwarded identity header")

ErrInvalidForwardedHeaders signals that a forwarded-identity header was present on the request but failed validation (contained control or delimiter characters, or was otherwise unsafe to embed in a URL). Callers that derive the RFC 8707 canonical resource URI from request context should treat this as a 400 Bad Request rather than silently falling back to `r.Host`: a malformed forwarded header signals either a misconfigured proxy or a client probing for injection vectors, and either way the safe response is to reject the request.

Functions

func AllowedResourceNamesFromContext

func AllowedResourceNamesFromContext(ctx context.Context) string

AllowedResourceNamesFromContext returns request-scoped allowed MCP resource names.

func BuildBearerChallenge

func BuildBearerChallenge(resourceMetadataURL, scope string) string

BuildBearerChallenge formats the WWW-Authenticate header value for an OAuth 2.0 Bearer challenge per RFC 6750 §3. resourceMetadataURL is required; scope is appended only when non-empty.

func BuildInvalidTokenChallenge

func BuildInvalidTokenChallenge(resourceMetadataURL, errorDescription string) string

BuildInvalidTokenChallenge formats the WWW-Authenticate header for an RFC 6750 §3 invalid_token response (used for audience mismatches, expired tokens, and revoked tokens). errorDescription is optional and should be a short human-readable string safe to surface to clients.

func CanonicalizeChallengeOrigin

func CanonicalizeChallengeOrigin(r *http.Request, trustProxy bool) string

CanonicalizeChallengeOrigin derives an origin URL suitable for embedding in a WWW-Authenticate `resource_metadata` parameter. Unlike the strict CanonicalizeResourceURL, this function never returns an error: if forwarded headers are malformed (or the caller did not opt into trusting them), it falls back to the request scheme and Host header so the challenge still points at some reachable origin.

This fallback is deliberate and narrow: a challenge is a formatting artifact inside a 401 response, not an identity claim. Emitting a slightly-wrong URL back to a client whose request carried malformed proxy headers is better than emitting nothing. Do not use this function to populate the PRM `resource` field — use CanonicalizeResourceURL there so the request fails loudly on malformed input.

func CanonicalizeResourceURL

func CanonicalizeResourceURL(r *http.Request, trustProxy bool) (string, error)

CanonicalizeResourceURL derives the RFC 8707 canonical resource URI from an incoming request.

When trustProxy is true, the function honors X-Forwarded-Proto and X-Forwarded-Host (and RFC 7239 Forwarded) so the value reflects the client-visible URL behind a trusted reverse proxy; a forwarded header present but malformed is rejected with ErrInvalidForwardedHeaders.

When trustProxy is false (the default for a generated server without TrustProxyHeaders() in the DSL), forwarded headers are ignored entirely and the origin is derived from r.Host + r.TLS only. This is the safe default for any server reachable directly by clients: without it, an attacker with direct access controls the PRM `resource` field advertised to clients.

Returns ErrEmptyResourceURL when no scheme+host can be derived. Callers should surface errors as 400 Bad Request rather than emitting a PRM document or challenge URL built from attacker-influenced or unusable inputs.

Operators who cannot vouch for forwarded headers should either leave trustProxy at its default or declare the resource identifier explicitly in the MCP DSL; generated code uses the declared value and does not call this function in the pinned case.

func CoerceQuery

func CoerceQuery(m map[string][]string) map[string]any

CoerceQuery converts a URL query map into a JSON-friendly object. It infers scalar types from values and preserves repeated parameters in input order. It does not coerce "0" or "1" to booleans.

func CoerceQueryTyped added in v2.1.0

func CoerceQueryTyped(m map[string][]string, fields map[string]QueryField) map[string]any

CoerceQueryTyped converts a URL query map into a JSON-friendly object while preserving strings and array shape declared by fields. Other values use the same inference as CoerceQuery. Repeated parameters preserve input order.

func DeniedResourceNamesFromContext

func DeniedResourceNamesFromContext(ctx context.Context) string

DeniedResourceNamesFromContext returns request-scoped denied MCP resource names.

func EncodeJSONToString

func EncodeJSONToString(
	ctx context.Context,
	newEncoder func(context.Context, http.ResponseWriter) goahttp.Encoder,
	v any,
) (string, error)

EncodeJSONToString encodes v into JSON using the provided encoder factory. The factory should produce an Encoder bound to the given ResponseWriter.

func EnsureSessionID

func EnsureSessionID(ctx context.Context) string

EnsureSessionID returns the existing session ID from ctx or creates a new one. When a response writer is present in ctx, the created session ID is emitted on the MCP session header.

func FormatToolError added in v2.1.0

func FormatToolError(err error) string

FormatToolError returns client-safe text for a failed tool result. The public code and recovery hint belong to the complete error's resolved response; independent joined causes cannot supply either field.

func IsInputRequired

func IsInputRequired(err error) bool

IsInputRequired reports whether err asks the active MCP transport to suspend the request until the client supplies additional input.

func IsInvalidClientInput

func IsInvalidClientInput(err error) bool

IsInvalidClientInput reports whether err represents invalid MCP retry input supplied by the client.

func MarshalCanonicalJSON

func MarshalCanonicalJSON(v any) ([]byte, error)

MarshalCanonicalJSON encodes v into JSON using explicit JSON tags when present and otherwise falling back to snake_case field names for exported struct fields.

Contract: - Map keys must be strings (including named string aliases). - Unsupported map key kinds fail fast instead of being silently dropped.

func NewErrorData

func NewErrorData(err error) any

NewErrorData returns client-safe MCP JSON-RPC metadata for err.

func NewSessionID

func NewSessionID() string

NewSessionID generates a transport-agnostic MCP session identifier.

func NewToolInputError added in v2.1.0

func NewToolInputError(err error, defaultCode, defaultRecovery string) error

NewToolInputError adds a tool's repair guidance to an input failure. Explicit response metadata takes precedence over defaults, and shared Loom message ownership determines which text is public. The input error is not modified.

func NormalizeJSONRPCError added in v2.1.0

func NormalizeJSONRPCError(method string, err error) error

NormalizeJSONRPCError converts handler errors into typed JSON-RPC errors. Existing typed errors pass through unchanged. Untyped initialize errors are invalid parameters because the SDK uses them for duplicate initialization. All unknown errors fail closed as internal errors without exposing details.

func ProgressTokenFromContext

func ProgressTokenFromContext(ctx context.Context) (any, bool)

ProgressTokenFromContext returns the active MCP request's progress token.

func ProjectedToolCallMetaFromContext added in v2.1.0

func ProjectedToolCallMetaFromContext(ctx context.Context) (agentruntime.ToolCallMeta, bool)

ProjectedToolCallMetaFromContext returns verified metadata for a projected MCP tool call. The boolean is false when the application did not install it.

func ProtectedResourceMetadataPath

func ProtectedResourceMetadataPath(mountPath string) string

ProtectedResourceMetadataPath returns the RFC 9728 §3.1 path-suffixed metadata path for a server mounted at mountPath. The root alias "/.well-known/oauth-protected-resource" is produced when mountPath is empty or "/".

func ReportProgress

func ReportProgress(ctx context.Context, update ProgressUpdate) error

ReportProgress sends an update using the reporter and request token stored in ctx.

func RequestHeadersFromContext

func RequestHeadersFromContext(ctx context.Context) http.Header

RequestHeadersFromContext returns request-scoped MCP headers from ctx.

func ResponseWriterFromContext

func ResponseWriterFromContext(ctx context.Context) http.ResponseWriter

ResponseWriterFromContext returns the active HTTP response writer from ctx.

func SafeError added in v2.1.0

func SafeError(err error, defaultCode, fallbackMessage string) error

SafeError converts a handler failure into a public named error. An explicit remedy may override the fallback message; diagnostic text remains private. Protocol control-flow errors pass through unchanged. An unnamed failure uses defaultCode; HTTP status interfaces do not declare MCP error names.

func SessionIDFromContext

func SessionIDFromContext(ctx context.Context) string

SessionIDFromContext returns the MCP session ID stored in ctx.

func StreamableHTTPNegotiation added in v2.1.0

func StreamableHTTPNegotiation(next http.Handler, jsonResponse bool) http.Handler

StreamableHTTPNegotiation checks that a POST request accepts the configured response type before it enters the official MCP SDK handler.

func ToolCallErrorFromResponse

func ToolCallErrorFromResponse(textParts []string, fallbackResult any) error

ToolCallErrorFromResponse converts an MCP isError content payload into a Go error while preserving the compact text message when present.

func UnmarshalCanonicalJSON

func UnmarshalCanonicalJSON(data []byte, dst any) error

UnmarshalCanonicalJSON decodes JSON into dst using explicit JSON tags when present and otherwise matching snake_case keys to exported struct fields.

func WithAllowedResourceNames

func WithAllowedResourceNames(ctx context.Context, names string) context.Context

WithAllowedResourceNames stores request-scoped allowed MCP resource names in ctx.

func WithDeniedResourceNames

func WithDeniedResourceNames(ctx context.Context, names string) context.Context

WithDeniedResourceNames stores request-scoped denied MCP resource names in ctx.

func WithElicitor

func WithElicitor(ctx context.Context, elicitor Elicitor) context.Context

WithElicitor stores an MCP elicitor in ctx.

func WithOAuthChallenge

func WithOAuthChallenge(handler http.Handler, mountPath string, challenge ChallengeBuilder) http.Handler

WithOAuthChallenge wraps a handler so that 401 responses missing a resource_metadata-carrying WWW-Authenticate header are augmented with the spec-compliant challenge built by challenge. Responses that already include resource_metadata are left untouched so consumer middleware can still override the default.

func WithProgressReporter

func WithProgressReporter(ctx context.Context, reporter ProgressReporter) context.Context

WithProgressReporter stores an MCP progress reporter in ctx.

func WithProgressToken

func WithProgressToken(ctx context.Context, token any) context.Context

WithProgressToken stores the active MCP request's progress token in ctx.

func WithProjectedToolCallMeta added in v2.1.0

func WithProjectedToolCallMeta(ctx context.Context, meta agentruntime.ToolCallMeta) context.Context

WithProjectedToolCallMeta stores verified application-owned metadata used to populate Inject fields on projected MCP tools. Authentication middleware must validate the request before its RequestContext callback calls this function.

func WithRequestHeaders

func WithRequestHeaders(ctx context.Context, headers http.Header) context.Context

WithRequestHeaders stores request-scoped MCP headers in ctx.

func WithResponseWriter

func WithResponseWriter(ctx context.Context, w http.ResponseWriter) context.Context

WithResponseWriter stores the active HTTP response writer in ctx.

func WithSessionID

func WithSessionID(ctx context.Context, sessionID string) context.Context

WithSessionID stores the MCP session ID in ctx.

func WriteInvalidToken

func WriteInvalidToken(w http.ResponseWriter, resourceMetadataURL, errorDescription string)

WriteInvalidToken writes a 401 response with the invalid_token Bearer challenge. Consumers call this from a verifier wrapper when a decoded token carries the wrong audience, is expired, or is revoked.

func WriteUnauthorized

func WriteUnauthorized(w http.ResponseWriter, resourceMetadataURL, scope string)

WriteUnauthorized writes a spec-compliant 401 response with a Bearer challenge. The resource_metadata parameter points the client at the Protected Resource Metadata document; scope is the space-delimited list of scopes the server advertises. When scope is empty the scope parameter is omitted entirely (RFC 6750 does not require it).

Types

type CallRequest

type CallRequest struct {
	// Suite identifies the MCP toolset (server name) associated with the tool.
	Suite string
	// Tool is the MCP-local tool identifier (without the suite prefix).
	Tool string
	// Payload is the JSON-encoded tool arguments produced by the runtime.
	Payload jsontext.Value
}

CallRequest describes the toolset/tool invocation issued by the runtime.

type CallResponse

type CallResponse struct {
	// Result is the JSON payload returned by the MCP server.
	Result jsontext.Value
	// Structured carries the full structured MCP content payload, including text
	// items that may also contribute to Result.
	Structured jsontext.Value
}

CallResponse captures the MCP tool result returned by the caller.

func NormalizeToolCallResponse

func NormalizeToolCallResponse(textParts []string, structured any, fallbackResult any) (CallResponse, error)

NormalizeToolCallResponse converts raw text parts and structured content into the canonical CallResponse representation used by MCP callers.

Text parts are concatenated in order. If the combined text is valid JSON, it becomes Result directly; otherwise it is marshaled as a JSON string. If no text is present, fallbackResult is marshaled into Result. Structured is marshaled into Structured when non-nil.

type Caller

type Caller interface {
	CallTool(ctx context.Context, req CallRequest) (CallResponse, error)
}

Caller invokes MCP tools on behalf of the runtime-generated adapters. It is implemented by transport-specific clients (stdio, HTTP streaming, etc.).

type CallerFunc

type CallerFunc func(ctx context.Context, req CallRequest) (CallResponse, error)

CallerFunc adapts a function to implement Caller.

func (CallerFunc) CallTool

func (f CallerFunc) CallTool(ctx context.Context, req CallRequest) (CallResponse, error)

CallTool implements Caller.

type ChallengeBuilder

type ChallengeBuilder func(r *http.Request, mountPath string) string

ChallengeBuilder formats a WWW-Authenticate header value for a request against the server mounted at mountPath. Generated packages export OAuthChallengeHeader matching this signature.

type ElicitRequest

type ElicitRequest struct {
	Mode            string
	Message         string
	RequestedSchema any
	URL             string
	ElicitationID   string
}

ElicitRequest describes a server-to-client MCP elicitation request.

type ElicitResult

type ElicitResult struct {
	Action  string
	Content map[string]any
}

ElicitResult describes the client's response to an elicitation request.

func Elicit

func Elicit(ctx context.Context, req ElicitRequest) (*ElicitResult, error)

Elicit requests user input through the MCP elicitor stored in ctx.

type Elicitor

type Elicitor interface {
	Elicit(context.Context, ElicitRequest) (*ElicitResult, error)
}

Elicitor requests user input from an MCP client.

func ElicitorFromContext

func ElicitorFromContext(ctx context.Context) (Elicitor, bool)

ElicitorFromContext returns the MCP elicitor stored in ctx.

type ErrorData

type ErrorData struct {
	Name      string            `json:"name,omitempty"`
	Temporary bool              `json:"temporary,omitempty"`
	Timeout   bool              `json:"timeout,omitempty"`
	Fault     bool              `json:"fault,omitempty"`
	Remedy    *loom.ErrorRemedy `json:"remedy,omitempty"`
}

ErrorData is the client-safe metadata included with MCP JSON-RPC errors. It intentionally omits Loom service error instance IDs.

type HTTPOptions

type HTTPOptions struct {
	Endpoint      string
	Client        *http.Client
	ClientName    string
	ClientVersion string
	InitTimeout   time.Duration
	// UserAgent sets HTTP identity independently from MCP ClientName/ClientVersion.
	// Empty uses loom-mcp/<library version>, or loom-mcp/dev for local builds.
	UserAgent string
	// ElicitationHandler handles server requests for user input over streamable
	// HTTP or SSE. Nil leaves elicitation unsupported. The handler owns user
	// interaction and consent.
	ElicitationHandler func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error)
}

HTTPOptions configures the HTTP Caller.

type InputRequiredError

type InputRequiredError interface {
	error
	InputRequired()
}

InputRequiredError marks control-flow errors that ask an MCP transport to return an input-required result instead of reporting a tool failure.

type InvalidClientInputError

type InvalidClientInputError interface {
	error
	InvalidClientInput()
}

InvalidClientInputError marks malformed MCP retry state or responses that transports must report as protocol errors rather than tool failures.

type ProgressReporter

type ProgressReporter interface {
	ReportProgress(context.Context, any, ProgressUpdate) error
}

ProgressReporter sends progress notifications to an MCP client.

func ProgressReporterFromContext

func ProgressReporterFromContext(ctx context.Context) (ProgressReporter, bool)

ProgressReporterFromContext returns the MCP progress reporter stored in ctx.

type ProgressUpdate

type ProgressUpdate struct {
	Progress float64
	Total    float64
	Message  string
}

ProgressUpdate describes one MCP progress notification.

type QueryField added in v2.1.0

type QueryField struct {
	String        bool
	Unsigned      bool
	Float         bool
	Repeated      bool
	Bits          int
	DefaultValues []string
}

QueryField describes the query shape declared by a resource payload schema.

type SessionCaller

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

SessionCaller implements Caller by wrapping an MCP SDK ClientSession. It is used by transport-specific callers (stdio, HTTP, SSE) to unify tool invocation.

func NewHTTPCaller

func NewHTTPCaller(ctx context.Context, opts HTTPOptions) (*SessionCaller, error)

NewHTTPCaller creates an HTTP-based Caller and performs MCP initialize handshake.

func NewSSECaller

func NewSSECaller(ctx context.Context, opts HTTPOptions) (*SessionCaller, error)

NewSSECaller creates an SSE-based Caller and performs the MCP initialize handshake.

func NewSessionCaller

func NewSessionCaller(session *mcp.ClientSession, cancel context.CancelFunc) *SessionCaller

NewSessionCaller returns a new SessionCaller wrapping the provided SDK session.

func NewStdioCaller

func NewStdioCaller(ctx context.Context, opts StdioOptions) (*SessionCaller, error)

NewStdioCaller launches the target command using CommandTransport, performs the MCP initialize handshake via Client.Connect, and returns a Caller that wraps the resulting ClientSession.

func (*SessionCaller) CallTool

func (c *SessionCaller) CallTool(ctx context.Context, req CallRequest) (CallResponse, error)

CallTool invokes tools/call over the transport using the SDK session.

func (*SessionCaller) Close

func (c *SessionCaller) Close() error

Close terminates the session and releases resources.

type StdioOptions

type StdioOptions struct {
	Command       string
	Args          []string
	Env           []string
	Dir           string
	ClientName    string
	ClientVersion string
	InitTimeout   time.Duration
	// MaxLineLength limits inbound JSON-RPC frames in bytes. Zero uses the SDK
	// default (16 MiB); a negative value disables the limit.
	MaxLineLength int
	// ElicitationHandler handles server requests for user input. Nil leaves
	// elicitation unsupported. The handler owns user interaction and consent.
	ElicitationHandler func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error)
}

StdioOptions configures the stdio-based MCP caller.

type ToolCallError

type ToolCallError struct {
	Message string
}

ToolCallError reports a remote MCP tool failure that was returned as an isError tool result rather than a transport/protocol error.

func (*ToolCallError) Error

func (e *ToolCallError) Error() string

Directories

Path Synopsis
Package retry defines shared types and helpers for producing standardized retryable errors and compact repair prompts used across generated clients.
Package retry defines shared types and helpers for producing standardized retryable errors and compact repair prompts used across generated clients.
Package sdkbridge owns service-independent wiring for official SDK-backed MCP servers.
Package sdkbridge owns service-independent wiring for official SDK-backed MCP servers.
Package sdkclient adapts an official MCP SDK server session to loom-mcp's transport-neutral server-to-client runtime contracts.
Package sdkclient adapts an official MCP SDK server session to loom-mcp's transport-neutral server-to-client runtime contracts.
Package skills exposes agent skill directories as MCP resources.
Package skills exposes agent skill directories as MCP resources.

Jump to

Keyboard shortcuts

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