core

package
v0.2.15 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

core

MCP protocol types and tool-handler APIs.

This package defines the shared types used by both server/ and client/. It has no dependencies on either — only stdlib and encoding/json.

What belongs here

  • JSON-RPC types: Request, Response, Error
  • MCP domain types: ToolDef, ResourceDef, PromptDef, Content, Claims
  • Tool-handler APIs: Sample(), Elicit(), EmitLog(), EmitProgress(), NotifyResourcesChanged()
  • UI metadata types: UIMetadata, UICSPConfig, UIVisibility, AppMIMEType, ToolMeta, ResourceContentMeta
  • Extension types: Extension, ExtensionProvider, RefValidator, ClientExtensionCap, UIExtensionID
  • Context helpers: ClientSupportsExtension(), ClientSupportsUI()
  • Interfaces: Transport, TokenSource, AuthValidator
  • Protocol constants: ServerInfo, ClientInfo, ClientCapabilities

What does NOT belong here

  • Server implementation (Dispatcher, transports, middleware) → server/
  • Client implementation (HTTP transports, reconnection) → client/
  • Auth implementation (JWT, PRM, OAuth) → ext/auth/
  • Anything that imports server/ or client/

Documentation

Index

Constants

View Source
const (
	// Standard JSON-RPC 2.0 error codes — use only for JSON-RPC protocol errors.
	ErrCodeParse          = -32700 // Invalid JSON
	ErrCodeInvalidRequest = -32600 // Not a valid JSON-RPC request
	ErrCodeMethodNotFound = -32601 // Method not found
	ErrCodeInvalidParams  = -32602 // Invalid params
	ErrCodeInternal       = -32603 // Internal JSON-RPC error (marshaling, framework bugs)

	// ErrCodeServerError is the base of the implementation-defined range (-32000 to -32099).
	// Avoid using this directly — prefer the MCP-specific codes below.
	ErrCodeServerError = -32000

	// MCP application error codes — outside the JSON-RPC reserved range.
	// These indicate application-level failures in tool, resource, or prompt handlers.
	ErrCodeToolExecutionError = -31000 // Tool handler returned an error
	ErrCodeResourceError      = -31001 // Resource handler returned an error
	ErrCodePromptError        = -31002 // Prompt handler returned an error
	ErrCodeCompletionError    = -31003 // Completion handler returned an error
)

Standard JSON-RPC 2.0 error codes (https://www.jsonrpc.org/specification#error_object).

Reserved ranges:

-32700           Parse error (invalid JSON)
-32600           Invalid Request (not a valid JSON-RPC request)
-32601           Method not found
-32602           Invalid params
-32603           Internal error
-32000 to -32099 Server error (implementation-defined)
View Source
const AppMIMEType = "text/html;profile=mcp-app"

AppMIMEType is the MIME type for MCP App HTML resources. This profile parameter distinguishes MCP App HTML from regular HTML — hosts use it to decide whether to render in a sandboxed iframe.

View Source
const DefaultContentChunkMethod = "notifications/tools/content_chunk"

DefaultContentChunkMethod is the default notification method for streaming tool content. This is an mcpkit extension — not yet standardized in MCP spec. Override per-server via server.WithContentChunkMethod(method).

View Source
const StreamableHTTPAccept = "application/json, text/event-stream"

StreamableHTTPAccept is the Accept header value for Streamable HTTP requests. Per MCP spec: clients MUST include both application/json and text/event-stream.

View Source
const UIExtensionID = "io.modelcontextprotocol/ui"

UIExtensionID is the extension identifier for MCP Apps. Used in initialize handshake for both server advertisement and client capability declaration.

Variables

View Source
var ErrElicitationNotSupported = errors.New("client does not support elicitation")

Sentinel errors for elicitation.

View Source
var ErrNoRequestFunc = errors.New("server-to-client requests not available in this context")

ErrNoRequestFunc is returned when Sample() or Elicit() is called outside a session context where server-to-client requests are not available (e.g., no transport wired, or stateless mode).

View Source
var ErrSamplingNotSupported = errors.New("client does not support sampling")

Sentinel errors for sampling.

Functions

func AllowedRoots added in v0.1.26

func AllowedRoots(ctx context.Context) []string

AllowedRoots returns the current enforced roots for the session, or nil if no roots enforcement is configured. The returned slice is the snapshot from the allowed-roots function — it may change on the next call if client roots update.

func ClientSupportsExtension

func ClientSupportsExtension(ctx context.Context, extensionID string) bool

ClientSupportsExtension checks whether the connected client declared support for the given extension ID during the initialize handshake. Returns false if no session context is present or the client did not advertise the extension.

Usage in a tool handler:

if core.ClientSupportsExtension(ctx, "io.modelcontextprotocol/ui") {
    // client can render MCP Apps
}

func ClientSupportsUI

func ClientSupportsUI(ctx context.Context) bool

ClientSupportsUI checks whether the connected client declared support for the MCP Apps extension during the initialize handshake. Tool handlers can use this to decide whether to include UI-specific content or fall back to text-only.

func ContentChunkMethodFromContext added in v0.1.17

func ContentChunkMethodFromContext(ctx context.Context) string

ContentChunkMethodFromContext returns the configured content chunk method, or DefaultContentChunkMethod if not set.

func ContextWithSession

func ContextWithSession(ctx context.Context, notify NotifyFunc, request RequestFunc, logLevel *atomic.Pointer[LogLevel], clientCaps *ClientCapabilities, claims *Claims) context.Context

ContextWithSession returns a context carrying the session's notification state, request sender, client capabilities, and authenticated claims. Exported for use by the server sub-package; tool handlers should use EmitLog, Sample, Elicit, AuthClaims instead.

func DetachFromClient added in v0.1.25

func DetachFromClient(ctx context.Context) context.Context

DetachFromClient returns a context that preserves all session state (EmitLog, EmitSSERetry, Sample, Elicit, AuthClaims, etc.) but is NOT cancelled when the client's HTTP request context is cancelled. Use this in a tool handler that needs to continue processing after the client disconnects — e.g., long-running computations where the result is delivered via EventStore replay on reconnection.

Under the hood, this calls context.WithoutCancel (Go 1.21+), which copies all context Values but strips the parent's Done channel and any inherited deadlines/timeouts.

Important caveats:

  • Any per-tool timeout (ToolDef.Timeout, WithToolTimeout) set by the server is inherited BEFORE the handler runs. DetachFromClient strips it. If the handler needs a deadline, add one explicitly: ctx = core.DetachFromClient(ctx) ctx, cancel := context.WithTimeout(ctx, 1*time.Hour) defer cancel()

  • Session idle timeouts (WithSessionTimeout) may reap the session while the detached tool is still running if the client doesn't reconnect within the idle window. Combine with a generous WithSSEGracePeriod to keep the session alive long enough.

  • Notifications (EmitLog, EmitSSERetry) emitted after the client disconnects are buffered in the EventStore (if configured) and replayed on reconnection. Without an EventStore, they are dropped.

  • The tool's final ToolResult is still serialized as an SSE event via emitSSEEvent — if the client has disconnected but the session is alive (grace period), the event lands in the store and is replayed.

Example:

func longRunningTool(ctx context.Context, req core.ToolRequest) (core.ToolResult, error) {
    // Hint the client to reconnect in 5 minutes
    core.EmitSSERetry(ctx, 5*time.Minute)

    // Detach: tool keeps running even if the client drops the connection
    ctx = core.DetachFromClient(ctx)

    // Long computation — ctx.Done() no longer fires on client disconnect
    result := doExpensiveWork(ctx)

    return core.TextResult(result), nil
}

func EmitContent added in v0.1.17

func EmitContent(ctx context.Context, requestID json.RawMessage, content Content)

EmitContent sends a partial content block to the client during tool execution. Each call emits a notification via the session's notify function, delivered as an SSE event on streaming transports.

On non-streaming transports (JSON response path), the notification is silently dropped — the final ToolResult is the only response.

The tool's final ToolResult should contain the complete aggregated content. Streaming chunks are a preview for responsive UX; the final result is authoritative.

Example:

func myTool(ctx context.Context, req core.ToolRequest) (core.ToolResult, error) {
    core.EmitContent(ctx, req.RequestID, core.Content{Type: "text", Text: "Step 1..."})
    // ... work ...
    core.EmitContent(ctx, req.RequestID, core.Content{Type: "text", Text: "Step 2..."})
    return core.TextResult("Complete"), nil
}

func EmitLog

func EmitLog(ctx context.Context, level LogLevel, logger string, data any)

EmitLog sends a notifications/message to the connected client if the session's log level allows it. Safe to call even if no session context is present (no-op).

level is the severity of the message. logger is an optional logger name (typically the tool or subsystem name). data is the log payload (string, map, etc.).

Usage in a tool handler:

func myHandler(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
    mcpkit.EmitLog(ctx, mcpkit.LogInfo, "my-tool", "processing started")
    // ... do work ...
    return mcpkit.TextResult("done"), nil
}

func EmitProgress

func EmitProgress(ctx context.Context, token any, progress, total float64, message string)

EmitProgress sends a notifications/progress to the connected client. Safe to call even if no session context is present or if token is nil (both are no-ops).

token is the ProgressToken from the ToolRequest — pass req.ProgressToken directly. progress is the current progress value, total is the expected total (0 for indeterminate). message is an optional human-readable status string.

Usage in a tool handler:

func myHandler(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
    mcpkit.EmitProgress(ctx, req.ProgressToken, 0, 100, "starting")
    // ... do work ...
    mcpkit.EmitProgress(ctx, req.ProgressToken, 50, 100, "halfway")
    // ... more work ...
    mcpkit.EmitProgress(ctx, req.ProgressToken, 100, 100, "done")
    return mcpkit.TextResult("complete"), nil
}

func EmitSSERetry added in v0.1.23

func EmitSSERetry(ctx context.Context, retryAfter time.Duration) error

EmitSSERetry emits an SSE "retry:" hint to the connected client on the current session's SSE stream. The retryAfter duration is rounded down to whole milliseconds and sent to the client as the next reconnection delay.

No-op on non-SSE transports (stdio, in-process, Streamable HTTP responses that chose the JSON path over SSE). Returns nil in all cases — callers don't need to branch on transport type.

Non-positive durations are dropped (no hint emitted). The servicekit writer additionally drops zero/negative retry values to prevent "reconnect immediately" thundering herds.

Thread safety: safe to call from any goroutine spawned by the handler. Delivery is asynchronous — the function returns as soon as the message is enqueued on the SSE hub writer.

Usage in a tool handler:

func longRunningTool(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
    // Tell the client to back off for 30s before reconnecting if the
    // connection drops. The tool continues running regardless.
    mcpkit.EmitSSERetry(ctx, 30*time.Second)

    // ...do long work...

    return mcpkit.TextResult("done"), nil
}

func FileURIToPath added in v0.1.26

func FileURIToPath(uri string) string

FileURIToPath converts a file:// URI to a local filesystem path. Returns the path portion with the "file://" prefix stripped. Returns the input unchanged if it doesn't have a file:// prefix. Used by the server dispatch layer to convert client-provided root URIs to paths for IsPathAllowed.

func HasScope

func HasScope(ctx context.Context, scope string) bool

HasScope checks if the context's authenticated claims include the given scope. Returns false if no claims are present.

func IsJSONRPCResponse

func IsJSONRPCResponse(data []byte) bool

isJSONRPCResponse detects whether raw JSON is a JSON-RPC response (not a request). A response has an "id" field and either "result" or "error", but no "method" field. Used by transports to route incoming client messages that are responses to server-to-client requests (sampling/createMessage, elicitation/create).

func IsPathAllowed added in v0.1.26

func IsPathAllowed(ctx context.Context, path string) bool

IsPathAllowed reports whether the given file path falls within at least one of the session's enforced roots. Returns true if:

  • No session context is present (bare context, no sandbox)
  • No allowed-roots function is installed (no WithAllowedRoots, no client roots)
  • The allowed-roots function returns nil (no restriction)

Returns false if the allowed-roots function returns a non-nil empty slice (explicit "nothing allowed") or the path doesn't match any root.

Path matching uses cleaned, directory-prefix semantics: "/workspace" allows "/workspace/src/main.go" but NOT "/workspace-other/y". Both the root and the path are cleaned via filepath.Clean before comparison.

func IsTemplateURI added in v0.2.4

func IsTemplateURI(uri string) bool

IsTemplateURI reports whether uri is a valid RFC 6570 URI template with at least one variable expression.

func MarshalNotification

func MarshalNotification(method string, params any) (json.RawMessage, error)

MarshalNotification builds a JSON-RPC notification (no id field). Exported for use by the server transport sub-package.

func Notify

func Notify(ctx context.Context, method string, params any) bool

Notify sends an arbitrary server-to-client JSON-RPC notification. Returns false if no notification sender is available in the context. This is the low-level API; prefer EmitLog for logging notifications.

func NotifyResourceUpdated added in v0.1.28

func NotifyResourceUpdated(ctx context.Context, uri string)

NotifyResourceUpdated sends a notifications/resources/updated to all sessions subscribed to the given resource URI. This is the handler-facing wrapper around Server.NotifyResourceUpdated — it routes through the subscription registry to fan out across sessions, not just the caller's session.

No-op if subscriptions are not enabled or no session context is present. Uses the existing MCP spec subscription mechanism (exact URI match); no wildcard or pattern extensions.

Usage in a tool handler:

func updateWidget(ctx context.Context, req core.ToolRequest) (core.ToolResult, error) {
    db.UpdateWidget(args.ID, args.Name)
    core.NotifyResourceUpdated(ctx, "widgets/" + args.ID)
    return core.TextResult("updated"), nil
}

func NotifyResourcesChanged

func NotifyResourcesChanged(ctx context.Context)

NotifyResourcesChanged sends a notifications/resources/list_changed notification to the connected client, signaling that the set of available resources has changed. MCP App tool handlers should call this after mutating state that affects the UI resource, so clients know to re-fetch resources/list.

Note: this notifies the CURRENT session only (via sc.notify). For targeted fan-out to all sessions subscribed to a specific resource URI, use NotifyResourceUpdated(ctx, uri) instead.

Safe to call even if no session context is present (no-op).

func ParseWWWAuthenticate

func ParseWWWAuthenticate(header string) (resourceMetadata string, scopes []string, err error)

ParseWWWAuthenticate extracts the resource_metadata URL and scopes from a WWW-Authenticate: Bearer header value. Used by MCP clients to discover the PRM endpoint after receiving a 401, and to parse required scopes from a 403 insufficient_scope response.

Per MCP spec (2025-11-25): clients MUST use resource_metadata from WWW-Authenticate when present.

func SetAllowedRoots added in v0.1.26

func SetAllowedRoots(ctx context.Context, fn func() []string) context.Context

SetAllowedRoots installs an allowed-roots supplier on the session stored in ctx. Exported for the server dispatch layer to wire in the computed root set during session setup. Must be called AFTER ContextWithSession.

func SetNotifyResourceUpdated added in v0.1.28

func SetNotifyResourceUpdated(ctx context.Context, fn func(uri string)) context.Context

SetNotifyResourceUpdated installs the resource-updated fan-out function on the session context. Exported for the server dispatch layer to wire the subscription registry's notify method. Must be called AFTER ContextWithSession.

func SetSSERetryHint added in v0.1.23

func SetSSERetryHint(ctx context.Context, fn func(ms int)) context.Context

SetSSERetryHint installs a retry-hint emitter on the session stored in ctx. Exported for the server transport layer to wire in an SSE-capable emitter during session setup. Non-SSE transports omit this call and EmitSSERetry becomes a silent no-op for handlers running under that transport.

Must be called AFTER ContextWithSession has populated the session context. Returns ctx unchanged if no session context is present (in which case the setter has nothing to attach to).

Idempotent: calling twice overwrites the previous emitter. Intended to be called exactly once per session during transport setup.

func URITemplateVars added in v0.2.4

func URITemplateVars(uri string) []string

URITemplateVars parses uri as an RFC 6570 URI template and returns the variable names it contains. Returns nil when uri is not a valid template or contains no variables (i.e. is a concrete URI).

func WithContentChunkMethod added in v0.1.17

func WithContentChunkMethod(ctx context.Context, method string) context.Context

WithContentChunkMethod returns a context with a custom notification method for streaming content chunks. Used by the server to plumb the configured method name through to EmitContent calls in tool handlers.

Types

type AuthError

type AuthError struct {
	Code            int
	Message         string
	WWWAuthenticate string // optional WWW-Authenticate header value
}

AuthError is returned when authentication fails.

func (*AuthError) Error

func (e *AuthError) Error() string

type AuthValidator

type AuthValidator interface {
	Validate(r *http.Request) error
}

AuthValidator validates an HTTP request and returns claims on success.

type BaseContext added in v0.2.0

type BaseContext struct {
	context.Context
	// contains filtered or unexported fields
}

BaseContext provides typed access to session capabilities shared by all MCP handler types (tools, resources, prompts, completions). It embeds context.Context so stdlib functions (Done(), Deadline(), WithTimeout) work transparently.

All methods are safe to call even when the underlying capability is unavailable (e.g., EmitLog on a transport without logging is a no-op).

func FromContext added in v0.2.0

func FromContext(ctx context.Context) BaseContext

FromContext returns a BaseContext for the given context.Context. This is the bridge for code using the free-function API — existing free functions like EmitLog(ctx, ...) delegate to FromContext(ctx).EmitLog(...).

Always returns a usable BaseContext (never nil). Methods become no-ops when no session state is present.

func (BaseContext) AllowedRoots added in v0.2.0

func (bc BaseContext) AllowedRoots() []string

AllowedRoots returns the current enforced roots for the session.

func (BaseContext) AuthClaims added in v0.2.0

func (bc BaseContext) AuthClaims() *Claims

AuthClaims returns the authenticated identity, or nil if unavailable.

func (BaseContext) ClientSupportsExtension added in v0.2.0

func (bc BaseContext) ClientSupportsExtension(extensionID string) bool

ClientSupportsExtension checks whether the client declared support for the given extension ID during initialize.

func (BaseContext) ClientSupportsUI added in v0.2.0

func (bc BaseContext) ClientSupportsUI() bool

ClientSupportsUI checks whether the client declared MCP Apps support.

func (BaseContext) DetachFromClient added in v0.2.0

func (bc BaseContext) DetachFromClient() BaseContext

DetachFromClient returns a BaseContext that preserves session state but is NOT cancelled when the client disconnects. See core.DetachFromClient.

func (BaseContext) Elicit added in v0.2.0

Elicit sends an elicitation/create request to the connected client.

func (BaseContext) EmitLog added in v0.2.0

func (bc BaseContext) EmitLog(level LogLevel, logger string, data any)

EmitLog sends a log notification at the given severity level.

func (BaseContext) EmitSSERetry added in v0.2.0

func (bc BaseContext) EmitSSERetry(retryAfter time.Duration) error

EmitSSERetry emits an SSE "retry:" hint to the connected client.

func (BaseContext) HasScope added in v0.2.0

func (bc BaseContext) HasScope(scope string) bool

HasScope checks if the authenticated claims include the given scope.

func (BaseContext) IsPathAllowed added in v0.2.0

func (bc BaseContext) IsPathAllowed(path string) bool

IsPathAllowed reports whether the given file path falls within the session's enforced roots.

func (BaseContext) Notify added in v0.2.0

func (bc BaseContext) Notify(method string, params any) bool

Notify sends an arbitrary server-to-client JSON-RPC notification. Returns false if no notification sender is available.

func (BaseContext) NotifyResourceUpdated added in v0.2.0

func (bc BaseContext) NotifyResourceUpdated(uri string)

NotifyResourceUpdated sends a notifications/resources/updated to all sessions subscribed to the given URI.

func (BaseContext) NotifyResourcesChanged added in v0.2.0

func (bc BaseContext) NotifyResourcesChanged()

NotifyResourcesChanged sends a notifications/resources/list_changed to the current session.

func (BaseContext) Sample added in v0.2.0

Sample sends a sampling/createMessage request to the connected client.

type Claims

type Claims struct {
	// Subject is the authenticated principal (user ID or client ID).
	Subject string `json:"sub"`

	// Issuer identifies the authorization server that issued the token.
	Issuer string `json:"iss"`

	// Audience lists the intended recipients of the token (RFC 8707).
	Audience []string `json:"aud"`

	// Scopes lists the granted scopes.
	Scopes []string `json:"scope"`

	// Extra holds additional claims not covered by the standard fields.
	Extra map[string]any `json:"extra,omitempty"`
}

Claims holds the authenticated identity extracted from a validated request. Populated by AuthValidators that also implement ClaimsProvider.

func AuthClaims

func AuthClaims(ctx context.Context) *Claims

AuthClaims returns the authenticated identity from the context, or nil if no auth was configured or the validator does not provide claims.

Usage in a tool handler:

func myHandler(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
    claims := mcpkit.AuthClaims(ctx)
    if claims != nil {
        log.Printf("called by %s", claims.Subject)
    }
    // ...
}

type ClaimsProvider

type ClaimsProvider interface {
	Claims(r *http.Request) *Claims
}

ClaimsProvider is an optional interface for AuthValidators that can extract identity claims from a validated request. Called only after Validate succeeds.

Validators that only perform pass/fail checks (like bearerTokenValidator) do not need to implement this interface.

type ClientCapabilities

type ClientCapabilities struct {
	Sampling    *struct{} `json:"sampling,omitempty"`
	Roots       *RootsCap `json:"roots,omitempty"`
	Elicitation *struct{} `json:"elicitation,omitempty"`

	// Extensions maps extension IDs to the client's capability declaration
	// for that extension. Sent during initialize to advertise extension support.
	Extensions map[string]ClientExtensionCap `json:"extensions,omitempty"`
}

ClientCapabilities describes features the client supports.

type ClientExtensionCap

type ClientExtensionCap struct {
	// MIMETypes lists content types the client supports for this extension.
	MIMETypes []string `json:"mimeTypes,omitempty"`
}

ClientExtensionCap describes a client's support for a specific extension. The contents are extension-specific; MCP Apps uses MIMETypes to declare which app content types the client can render.

type ClientInfo

type ClientInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

ClientInfo identifies an MCP client from the initialize request.

type CompletionArgument

type CompletionArgument struct {
	// Name is the argument name being completed.
	Name string `json:"name"`

	// Value is the partial input the user has typed so far.
	Value string `json:"value"`
}

CompletionArgument describes the argument being completed and the partial input so far.

type CompletionCompleteResult

type CompletionCompleteResult struct {
	Completion CompletionResult `json:"completion"`
}

CompletionCompleteResult is the typed result for completion/complete responses.

type CompletionHandler

type CompletionHandler func(ctx PromptContext, ref CompletionRef, arg CompletionArgument) (CompletionResult, error)

CompletionHandler provides autocompletion suggestions for a specific reference. ref identifies the prompt or resource being completed, arg contains the argument name and partial value. Return matching suggestions.

type CompletionRef

type CompletionRef struct {
	// Type is "ref/prompt" for prompt argument completion or "ref/resource" for resource URI completion.
	Type string `json:"type"`

	// Name is the prompt name (when Type is "ref/prompt").
	Name string `json:"name,omitempty"`

	// URI is the resource URI template (when Type is "ref/resource").
	URI string `json:"uri,omitempty"`
}

CompletionRef identifies what is being completed — a prompt argument or resource URI.

type CompletionResult

type CompletionResult struct {
	// Values is the list of completion suggestions.
	Values []string `json:"values"`

	// Total is the total number of available completions (may be larger than len(Values)).
	Total int `json:"total,omitempty"`

	// HasMore indicates there are additional completions beyond what was returned.
	HasMore bool `json:"hasMore"`
}

CompletionResult is the server's response with completion suggestions.

type Content

type Content struct {
	Type     string           `json:"type"`
	Text     string           `json:"text,omitempty"`
	MimeType string           `json:"mimeType,omitempty"`
	Data     string           `json:"data,omitempty"`
	Resource *ResourceContent `json:"resource,omitempty"`
}

Content is a single content item in a tool result. Supports text, image, audio, and embedded resource types per MCP spec.

func (*Content) UnmarshalJSON added in v0.1.21

func (c *Content) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a Content, tolerating an array-form `resource` field from peers that confuse EmbeddedResource (single) with ReadResourceResult (array). The first array element wins. See #81 for cardinality rationale.

type ContentChunk added in v0.1.17

type ContentChunk struct {
	// RequestID links the chunk to the original tools/call request.
	RequestID json.RawMessage `json:"requestId"`

	// Content is the partial content block.
	Content Content `json:"content"`
}

ContentChunk is the notification payload for a streaming content block. Sent during tool execution to deliver partial results incrementally.

type CreateMessageRequest

type CreateMessageRequest struct {
	Messages         []SamplingMessage `json:"messages"`
	SystemPrompt     string            `json:"systemPrompt,omitempty"`
	IncludeContext   string            `json:"includeContext,omitempty"` // "none", "thisServer", "allServers"
	Temperature      *float64          `json:"temperature,omitempty"`
	MaxTokens        int               `json:"maxTokens"`
	ModelPreferences *ModelPreferences `json:"modelPreferences,omitempty"`
	StopSequences    []string          `json:"stopSequences,omitempty"`
	Metadata         map[string]any    `json:"metadata,omitempty"`
	Meta             *SamplingMeta     `json:"_meta,omitempty"`
}

CreateMessageRequest is the params for a sampling/createMessage server-to-client request. The server sends this to ask the client to perform LLM inference.

type CreateMessageResult

type CreateMessageResult struct {
	Model      string  `json:"model"`
	StopReason string  `json:"stopReason,omitempty"`
	Role       string  `json:"role"`
	Content    Content `json:"content"`
}

CreateMessageResult is the client's response to a sampling/createMessage request.

func Sample

Sample sends a sampling/createMessage request to the connected client and blocks until the client responds with an LLM inference result.

Returns ErrNoRequestFunc if called outside a session context (e.g., no transport). Returns ErrSamplingNotSupported if the client did not declare sampling capability. Returns context.DeadlineExceeded if the context expires before the client responds.

Usage in a tool handler:

func myHandler(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
    result, err := mcpkit.Sample(ctx, mcpkit.CreateMessageRequest{
        Messages:  []mcpkit.SamplingMessage{{Role: "user", Content: mcpkit.Content{Type: "text", Text: "summarize this"}}},
        MaxTokens: 1000,
    })
    if err != nil {
        return mcpkit.ErrorResult(err.Error()), nil
    }
    return mcpkit.TextResult(result.Content.Text), nil
}

func (*CreateMessageResult) UnmarshalJSON added in v0.1.21

func (r *CreateMessageResult) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a CreateMessageResult, tolerating an array-form `content` field (first element wins) from peers that emit the array shape. See #81.

type DisplayMode added in v0.1.29

type DisplayMode string

DisplayMode represents an iframe display mode for MCP Apps.

const (
	// DisplayModeInline renders the app inline within the host UI.
	DisplayModeInline DisplayMode = "inline"

	// DisplayModeFullscreen renders the app in a fullscreen overlay.
	DisplayModeFullscreen DisplayMode = "fullscreen"

	// DisplayModePIP renders the app in a picture-in-picture window.
	DisplayModePIP DisplayMode = "pip"
)

type ElicitationMeta added in v0.1.29

type ElicitationMeta struct {
	// UI contains MCP Apps presentation metadata.
	// When set, the host can render a UI resource during input collection
	// instead of falling back to the default schema-driven form.
	UI *UIMetadata `json:"ui,omitempty"`
}

ElicitationMeta holds protocol-level metadata for an elicitation request. Serialized as "_meta" in the elicitation/create params.

type ElicitationRequest

type ElicitationRequest struct {
	Message         string           `json:"message"`
	RequestedSchema json.RawMessage  `json:"requestedSchema,omitempty"`
	Meta            *ElicitationMeta `json:"_meta,omitempty"`
}

ElicitationRequest is the params for an elicitation/create server-to-client request. The server sends this to ask the client to collect structured user input.

type ElicitationResult

type ElicitationResult struct {
	Action  string         `json:"action"` // "accept", "decline", or "cancel"
	Content map[string]any `json:"content,omitempty"`
}

ElicitationResult is the client's response to an elicitation/create request.

func Elicit

Elicit sends an elicitation/create request to the connected client and blocks until the client responds with user input.

Returns ErrNoRequestFunc if called outside a session context (e.g., no transport). Returns ErrElicitationNotSupported if the client did not declare elicitation capability. Returns context.DeadlineExceeded if the context expires before the client responds.

Usage in a tool handler:

func myHandler(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
    result, err := mcpkit.Elicit(ctx, mcpkit.ElicitationRequest{
        Message: "Which database should I connect to?",
        RequestedSchema: json.RawMessage(`{
            "type": "object",
            "properties": {"database": {"type": "string", "enum": ["prod", "staging", "dev"]}}
        }`),
    })
    if err != nil {
        return mcpkit.ErrorResult(err.Error()), nil
    }
    if result.Action != "accept" {
        return mcpkit.TextResult("User declined"), nil
    }
    return mcpkit.TextResult(fmt.Sprintf("Selected: %v", result.Content["database"])), nil
}

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

Error is a JSON-RPC 2.0 error object.

type Extension

type Extension struct {
	// ID is the extension identifier (e.g., "io.mcpkit/auth").
	ID string `json:"id"`

	// SpecVersion is the version of the spec this extension implements.
	SpecVersion string `json:"specVersion"`

	// Stability indicates the maturity of this extension.
	Stability Stability `json:"stability"`

	// Config holds extension-specific configuration, if any.
	Config map[string]any `json:"config,omitempty"`
}

Extension describes a protocol extension with maturity metadata. Extensions are advertised in the initialize response under capabilities.extensions.

type ExtensionCapability

type ExtensionCapability struct {
	SpecVersion string `json:"specVersion"`
	Stability   string `json:"stability"`
}

ExtensionCapability describes a server extension's metadata in the initialize response capabilities.

type ExtensionProvider

type ExtensionProvider interface {
	Extension() Extension
}

ExtensionProvider is implemented by sub-modules to declare their extension. This is how mcpkit/auth registers itself without the core module knowing about auth.

type InitializeResult

type InitializeResult struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ServerCapabilities `json:"capabilities"`
	ServerInfo      ServerInfo         `json:"serverInfo"`
}

InitializeResult is the typed result for the initialize response.

type LogLevel

type LogLevel int

LogLevel represents MCP log severity levels (syslog-based, ascending severity). Used with logging/setLevel to control the minimum level of log notifications sent to the client, and with EmitLog to specify the severity of a message.

const (
	LogDebug     LogLevel = iota // debug: detailed debugging information
	LogInfo                      // info: general informational messages
	LogNotice                    // notice: normal but significant events
	LogWarning                   // warning: warning conditions
	LogError                     // error: error conditions
	LogCritical                  // critical: critical conditions
	LogAlert                     // alert: action must be taken immediately
	LogEmergency                 // emergency: system is unusable
)

func ParseLogLevel

func ParseLogLevel(s string) (LogLevel, bool)

ParseLogLevel converts a string to a LogLevel. Returns the level and true on success, or (LogDebug, false) for unknown strings.

func (LogLevel) String

func (l LogLevel) String() string

String returns the MCP wire name for the log level.

type LogMessage

type LogMessage struct {
	Level  string `json:"level"`
	Logger string `json:"logger,omitempty"`
	Data   any    `json:"data"`
}

LogMessage is the params payload for a notifications/message notification.

type ModelHint

type ModelHint struct {
	Name string `json:"name,omitempty"`
}

ModelHint provides hints about which model the server prefers for sampling.

type ModelPreferences

type ModelPreferences struct {
	Hints                []ModelHint `json:"hints,omitempty"`
	CostPriority         *float64    `json:"costPriority,omitempty"`
	SpeedPriority        *float64    `json:"speedPriority,omitempty"`
	IntelligencePriority *float64    `json:"intelligencePriority,omitempty"`
}

ModelPreferences describes the server's preferences for model selection when the client performs LLM sampling.

type NotificationHandler

type NotificationHandler func(method string, params []byte)

NotificationHandler receives server-to-client notifications (logging, progress, resource updates). Used by tests to verify notification delivery.

type NotifyFunc

type NotifyFunc func(method string, params any)

NotifyFunc sends a server-to-client JSON-RPC notification. method is the notification method (e.g., "notifications/message"). params will be JSON-marshaled as the notification's params field. This type is reusable for all server→client notifications (logging, progress, etc.).

type PingResult

type PingResult struct{}

PingResult is the typed result for ping responses. Currently empty per spec, but typed to allow future extension.

type ProgressNotification

type ProgressNotification struct {
	// ProgressToken is the token from the request's _meta.progressToken field.
	// It links this notification to the original request.
	ProgressToken any `json:"progressToken"`

	// Progress is the current progress value (e.g., bytes processed, items completed).
	Progress float64 `json:"progress"`

	// Total is the expected total value. Zero means indeterminate progress.
	Total float64 `json:"total,omitempty"`

	// Message is an optional human-readable status message.
	Message string `json:"message,omitempty"`
}

ProgressNotification is the params payload for a notifications/progress notification. Servers send this during long-running operations to report progress to the client. The ProgressToken must match the token from the client's original request _meta.

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`

	// Schema is an optional JSON Schema describing the expected value shape
	// for this argument. Mirrors ToolDef.InputSchema: typically a
	// map[string]any with "type", "enum", "minimum", etc. Arbitrary JSON
	// Schema keywords ($ref, $defs, additionalProperties, ...) are preserved
	// as-is through registration, serialization, and client deserialization.
	//
	// Enforced server-side: when set, the dispatcher validates incoming
	// argument values against the schema before invoking the handler and
	// returns -32602 Invalid Params with a structured errors list on
	// failure (#184). Arguments without a Schema bypass validation.
	// Use server.WithSchemaValidation(false) to opt out of call-time
	// validation if you prefer to validate in the handler.
	Schema any `json:"schema,omitempty"`
}

PromptArgument describes a single argument to a prompt.

type PromptContext added in v0.2.0

type PromptContext struct {
	BaseContext
}

PromptContext is the context passed to PromptHandler and CompletionHandler functions. It embeds BaseContext with no additional methods.

func NewPromptContext added in v0.2.0

func NewPromptContext(ctx context.Context) PromptContext

NewPromptContext constructs a PromptContext from a standard context.Context.

func (PromptContext) DetachFromClient added in v0.2.0

func (pc PromptContext) DetachFromClient() PromptContext

DetachFromClient returns a PromptContext that preserves session state but is NOT cancelled when the client disconnects.

type PromptDef

type PromptDef struct {
	// Name is the prompt identifier used in prompts/get.
	Name string `json:"name"`

	// Title is an optional display title.
	Title string `json:"title,omitempty"`

	// Description explains what this prompt does.
	Description string `json:"description,omitempty"`

	// Arguments defines the parameters this prompt accepts.
	Arguments []PromptArgument `json:"arguments,omitempty"`

	// Annotations holds optional metadata for this prompt.
	Annotations map[string]any `json:"annotations,omitempty"`

	// Timeout is a per-prompt execution timeout. Not serialized to clients.
	Timeout time.Duration `json:"-"`
}

PromptDef describes a prompt exposed via MCP.

type PromptHandler

type PromptHandler func(ctx PromptContext, req PromptRequest) (PromptResult, error)

PromptHandler generates prompt messages, optionally using arguments.

type PromptMessage

type PromptMessage struct {
	Role    string  `json:"role"`
	Content Content `json:"content"` // reuses Content from tool.go
}

PromptMessage is a single message in a prompt result.

func (*PromptMessage) UnmarshalJSON added in v0.1.21

func (m *PromptMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a PromptMessage, tolerating an array-form `content` field from peers that emit the array shape by mistake. First element wins. See #81.

type PromptRequest

type PromptRequest struct {
	Name      string
	Arguments map[string]any
}

PromptRequest is the validated input passed to a PromptHandler.

Arguments holds the decoded JSON values from the prompts/get request, keyed by argument name. Values retain their JSON types after decode: strings stay as string, numbers become float64, booleans stay bool, objects become map[string]any, arrays become []any. Handlers type-assert as needed. This shape mirrors how tool handlers receive ToolRequest.Arguments (raw JSON), but pre-decoded for ergonomic access — a prompt argument count is tiny, so eager decode is fine. See #87.

type PromptResult

type PromptResult struct {
	Description string          `json:"description,omitempty"`
	Messages    []PromptMessage `json:"messages"`
}

PromptResult is the response from a prompt handler.

type PromptsCap

type PromptsCap struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

PromptsCap describes the server's prompts capability.

type PromptsListResult

type PromptsListResult struct {
	Prompts    []PromptDef `json:"prompts"`
	NextCursor string      `json:"nextCursor,omitempty"`
}

PromptsListResult is the typed result for prompts/list responses.

type RefValidator

type RefValidator interface {
	ValidateRefs(tools []ToolDef, resourceURIs []string, templateURIs []string) []string
}

RefValidator is an optional interface that ExtensionProviders can implement to validate tool-to-resource references at server startup. The server calls ValidateRefs for each extension that implements this interface, passing all registered tools and the URIs of registered resources and templates. Returns a list of human-readable warning messages (empty if all refs resolve).

type Request

type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

Request is a JSON-RPC 2.0 request envelope.

func (*Request) IsNotification

func (r *Request) IsNotification() bool

IsNotification returns true if this request has no ID (JSON-RPC notification).

type RequestFunc

type RequestFunc func(ctx context.Context, method string, params any) (json.RawMessage, error)

RequestFunc sends a server-to-client JSON-RPC request and blocks until the client sends a response. method is the JSON-RPC method (e.g., "sampling/createMessage"). params will be JSON-marshaled as the request's params field. Returns the raw JSON result on success, or an error on timeout, transport failure, or JSON-RPC error from the client.

type ResourceContent

type ResourceContent struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType,omitempty"`
	Text     string `json:"text,omitempty"`
	Blob     string `json:"blob,omitempty"`
}

ResourceContent is an embedded resource reference in a tool result.

type ResourceContentMeta

type ResourceContentMeta struct {
	// UI contains MCP Apps presentation metadata.
	UI *UIMetadata `json:"ui,omitempty"`
}

ResourceContentMeta holds per-content metadata in resources/read responses. Takes precedence over the resource-level metadata from resources/list.

type ResourceContext added in v0.2.0

type ResourceContext struct {
	BaseContext
}

ResourceContext is the context passed to ResourceHandler and TemplateHandler functions. It embeds BaseContext with no additional methods — resources don't support progress or content streaming.

func NewResourceContext added in v0.2.0

func NewResourceContext(ctx context.Context) ResourceContext

NewResourceContext constructs a ResourceContext from a standard context.Context.

func (ResourceContext) DetachFromClient added in v0.2.0

func (rc ResourceContext) DetachFromClient() ResourceContext

DetachFromClient returns a ResourceContext that preserves session state but is NOT cancelled when the client disconnects.

type ResourceDef

type ResourceDef struct {
	// URI uniquely identifies this resource.
	URI string `json:"uri"`

	// Name is a human-readable short name.
	Name string `json:"name"`

	// Title is an optional display title.
	Title string `json:"title,omitempty"`

	// Description explains what this resource provides.
	Description string `json:"description,omitempty"`

	// MimeType is the MIME type of the resource content.
	MimeType string `json:"mimeType,omitempty"`

	// Annotations holds optional metadata for this resource.
	Annotations map[string]any `json:"annotations,omitempty"`

	// Timeout is a per-resource execution timeout. Not serialized to clients.
	Timeout time.Duration `json:"-"`
}

ResourceDef describes a resource exposed via MCP.

type ResourceHandler

type ResourceHandler func(ctx ResourceContext, req ResourceRequest) (ResourceResult, error)

ResourceHandler reads a resource by URI.

type ResourceReadContent

type ResourceReadContent struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType,omitempty"`
	Text     string `json:"text,omitempty"`
	Blob     string `json:"blob,omitempty"`

	// Meta holds per-content metadata (e.g., UI overrides).
	// Takes precedence over the resource-level _meta from resources/list.
	Meta *ResourceContentMeta `json:"_meta,omitempty"`
}

ResourceReadContent is a single content item returned by resources/read. Either Text or Blob is set, not both.

type ResourceRequest

type ResourceRequest struct {
	URI string
}

ResourceRequest is the validated input passed to a ResourceHandler.

type ResourceResult

type ResourceResult struct {
	Contents []ResourceReadContent `json:"contents"`
}

ResourceResult is the response from a resource handler.

func (*ResourceResult) UnmarshalJSON added in v0.1.21

func (r *ResourceResult) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a ResourceResult, tolerating a single-object `contents` form from peers that emit a bare object instead of the spec-canonical array. Single objects are wrapped into a 1-element slice. See #81.

type ResourceTemplate

type ResourceTemplate struct {
	// URITemplate is an RFC 6570 URI template (e.g., "file:///{path}").
	// This serves as the unique identifier for the template in the registry —
	// registering a template with the same URI template string overwrites the
	// previous registration.
	URITemplate string `json:"uriTemplate"`

	// Name is a human-readable short name.
	Name string `json:"name"`

	// Title is an optional display title.
	Title string `json:"title,omitempty"`

	// Description explains what this template provides.
	Description string `json:"description,omitempty"`

	// MimeType is the default MIME type for resources matching this template.
	MimeType string `json:"mimeType,omitempty"`

	// Annotations holds optional metadata for this template.
	Annotations map[string]any `json:"annotations,omitempty"`

	// Timeout is a per-template execution timeout. Not serialized to clients.
	Timeout time.Duration `json:"-"`
}

ResourceTemplate describes a parameterized resource URI template.

type ResourceTemplatesListResult

type ResourceTemplatesListResult struct {
	ResourceTemplates []ResourceTemplate `json:"resourceTemplates"`
	NextCursor        string             `json:"nextCursor,omitempty"`
}

ResourceTemplatesListResult is the typed result for resources/templates/list responses.

type ResourceUpdatedNotification

type ResourceUpdatedNotification struct {
	URI string `json:"uri"`
}

ResourceUpdatedNotification is the params payload for notifications/resources/updated. Sent by the server to subscribed clients when a resource's content has changed.

type ResourcesCap

type ResourcesCap struct {
	Subscribe   bool `json:"subscribe,omitempty"`
	ListChanged bool `json:"listChanged,omitempty"`
}

ResourcesCap describes the server's resources capability.

type ResourcesListResult

type ResourcesListResult struct {
	Resources  []ResourceDef `json:"resources"`
	NextCursor string        `json:"nextCursor,omitempty"`
}

ResourcesListResult is the typed result for resources/list responses.

type Response

type Response struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *Error          `json:"error,omitempty"`
}

Response is a JSON-RPC 2.0 response.

func NewErrorResponse

func NewErrorResponse(id json.RawMessage, code int, message string) *Response

NewErrorResponse creates an error response for the given request ID.

func NewErrorResponseWithData

func NewErrorResponseWithData(id json.RawMessage, code int, message string, data any) *Response

NewErrorResponseWithData creates an error response with additional structured data. Used for protocol errors that carry machine-readable context (e.g., supported versions).

func NewResponse

func NewResponse(id json.RawMessage, result any) *Response

NewResponse creates a success response for the given request ID.

type Root added in v0.1.18

type Root struct {
	// URI is the root's location (e.g., "file:///home/user/project").
	URI string `json:"uri"`

	// Name is an optional human-readable label for this root.
	Name string `json:"name,omitempty"`
}

Root represents a filesystem root provided by the client. Roots inform the server about available directories for tool execution.

type RootsCap

type RootsCap struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

RootsCap describes the client's roots capability.

type RootsListResult added in v0.1.18

type RootsListResult struct {
	Roots []Root `json:"roots"`
}

RootsListResult is the response to a roots/list server-to-client request.

type SamplingMessage

type SamplingMessage struct {
	Role    string  `json:"role"`
	Content Content `json:"content"`
}

SamplingMessage is a single message in a sampling/createMessage request.

func (*SamplingMessage) UnmarshalJSON added in v0.1.21

func (m *SamplingMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a SamplingMessage, tolerating an array-form `content` field (first element wins). The spec currently specifies single-content for SamplingMessage; widening to multi-part is tracked by #141 and will reuse this hook by switching to decodeContentSlice. See #81.

type SamplingMeta added in v0.1.29

type SamplingMeta struct {
	// UI contains MCP Apps presentation metadata.
	// When set, the host can associate the sampling request with a UI resource.
	UI *UIMetadata `json:"ui,omitempty"`
}

SamplingMeta holds protocol-level metadata for a sampling request. Serialized as "_meta" in the sampling/createMessage params.

type ScopeAwareTokenSource

type ScopeAwareTokenSource interface {
	TokenSource
	// TokenForScopes invalidates the cached token and triggers a new
	// authorization flow with the given scopes merged into the existing set.
	TokenForScopes(scopes []string) (string, error)
}

ScopeAwareTokenSource extends TokenSource with scope step-up capability. When the server returns 403 with required scopes in the WWW-Authenticate header, the client transport calls TokenForScopes to re-authenticate with broader permissions.

Implementations that support interactive re-auth (like OAuthTokenSource) should implement this interface. Static tokens and implementations that cannot acquire new scopes need not implement it — the transport will return a ClientAuthError instead of retrying.

type ServerCapabilities

type ServerCapabilities struct {
	Tools       *ToolsCap                      `json:"tools,omitempty"`
	Resources   *ResourcesCap                  `json:"resources,omitempty"`
	Prompts     *PromptsCap                    `json:"prompts,omitempty"`
	Logging     *struct{}                      `json:"logging,omitempty"`
	Completions *struct{}                      `json:"completions,omitempty"`
	Extensions  map[string]ExtensionCapability `json:"extensions,omitempty"`
}

ServerCapabilities describes the features the server supports, returned in the initialize response.

type ServerInfo

type ServerInfo struct {
	Name         string `json:"name"`
	Version      string `json:"version"`
	Title        string `json:"title,omitempty"`
	Description  string `json:"description,omitempty"`
	Instructions string `json:"instructions,omitempty"`
	WebsiteURL   string `json:"websiteUrl,omitempty"`
}

ServerInfo identifies an MCP server in the initialize response.

type ServerRequestHandler

type ServerRequestHandler func(ctx context.Context, req *Request) *Response

ServerRequestHandler handles server-to-client JSON-RPC requests (sampling, elicitation). The client registers this on the transport so the server can send requests during tool execution and receive responses.

type Stability

type Stability string

Stability represents the maturity level of an extension.

const (
	// Experimental indicates the extension is in development and may change.
	Experimental Stability = "experimental"
	// Stable indicates the extension is production-ready.
	Stable Stability = "stable"
	// Deprecated indicates the extension will be removed in a future version.
	Deprecated Stability = "deprecated"
)

type TemplateHandler

type TemplateHandler func(ctx ResourceContext, uri string, params map[string]string) (ResourceResult, error)

TemplateHandler reads a resource matched by a URI template. The uri parameter is the full resolved URI, params contains the extracted template variables.

type TokenSource

type TokenSource interface {
	// Token returns a valid access token, refreshing if necessary.
	Token() (string, error)
}

TokenSource provides access tokens for the MCP client. Simple implementations return a static token; OAuth implementations handle the full flow including discovery, browser auth, and refresh.

type ToolContext added in v0.2.0

type ToolContext struct {
	BaseContext
}

ToolContext is the context passed to ToolHandler functions. It embeds BaseContext and adds tool-specific methods (EmitProgress, EmitContent).

func NewToolContext added in v0.2.0

func NewToolContext(ctx context.Context) ToolContext

NewToolContext constructs a ToolContext from a standard context.Context. Called by the dispatch layer before invoking tool handlers.

func (ToolContext) DetachFromClient added in v0.2.0

func (tc ToolContext) DetachFromClient() ToolContext

DetachFromClient returns a ToolContext that preserves session state but is NOT cancelled when the client disconnects.

func (ToolContext) EmitContent added in v0.2.0

func (tc ToolContext) EmitContent(requestID json.RawMessage, content Content)

EmitContent sends a partial content block to the client during tool execution. On non-streaming transports, the notification is silently dropped.

func (ToolContext) EmitProgress added in v0.2.0

func (tc ToolContext) EmitProgress(token any, progress, total float64, message string)

EmitProgress sends a notifications/progress to the connected client. No-op if token is nil.

type ToolDef

type ToolDef struct {
	// Name is the tool identifier used in tools/call.
	Name string `json:"name"`

	// Description is a human-readable summary of what the tool does.
	Description string `json:"description"`

	// InputSchema is the JSON Schema for the tool's arguments.
	// Typically a map[string]any with "type": "object", "properties": {...}, "required": [...].
	// Arbitrary JSON Schema fields (e.g. "$schema", "$defs", "$ref",
	// "additionalProperties") are preserved as-is through registration,
	// serialization, and client-side deserialization.
	InputSchema any `json:"inputSchema"`

	// OutputSchema is an optional JSON Schema for the tool's structuredContent output.
	// When present, the tool SHOULD return StructuredContent matching this schema.
	// Per MCP spec: enables clients to validate and process tool output programmatically.
	OutputSchema any `json:"outputSchema,omitempty"`

	// Annotations holds optional metadata for this tool.
	// Convention: {"experimental": true} marks experimental tools.
	Annotations map[string]any `json:"annotations,omitempty"`

	// Meta holds protocol-level metadata (e.g., UI presentation hints).
	// Serialized as "_meta" in the tools/list response.
	Meta *ToolMeta `json:"_meta,omitempty"`

	// Timeout is a per-tool execution timeout. If set, overrides the
	// server-wide WithToolTimeout for this tool. Not serialized to clients.
	Timeout time.Duration `json:"-"`
}

ToolDef describes a tool exposed via MCP.

type ToolHandler

type ToolHandler func(ctx ToolContext, req ToolRequest) (ToolResult, error)

ToolHandler is the function signature for tool implementations. The ToolContext provides typed access to session capabilities (EmitLog, EmitProgress, EmitContent, Sample, Elicit, etc.) with IDE discoverability.

type ToolMeta

type ToolMeta struct {
	// UI contains MCP Apps presentation metadata.
	UI *UIMetadata `json:"ui,omitempty"`
}

ToolMeta holds protocol-level metadata for a tool definition. Serialized as "_meta" in the tools/list response.

type ToolRequest

type ToolRequest struct {
	// Name of the tool being called.
	Name string

	// Arguments is the raw JSON arguments from the tools/call params.
	Arguments json.RawMessage

	// RequestID is the JSON-RPC request ID.
	RequestID json.RawMessage

	// ProgressToken is the token from the request's _meta.progressToken field.
	// Nil if the client did not request progress reporting. Pass this to
	// EmitProgress to send notifications/progress notifications.
	ProgressToken any
}

ToolRequest is the validated input passed to a ToolHandler.

func (*ToolRequest) Bind

func (r *ToolRequest) Bind(v any) error

Bind unmarshals the tool arguments into the provided struct.

type ToolResult

type ToolResult struct {
	// Content is the list of content items to return.
	Content []Content `json:"content"`

	// IsError indicates the tool execution failed (but the JSON-RPC call itself succeeded).
	IsError bool `json:"isError,omitempty"`

	// StructuredContent holds optional structured data for the tool result.
	// When the tool has an OutputSchema, this field carries typed data matching
	// that schema. On error (IsError=true), it can carry structured error details.
	// Per MCP spec: "If outputSchema is present, structuredContent SHOULD be included."
	StructuredContent any `json:"structuredContent,omitempty"`

	// Meta holds optional result metadata (e.g., pagination cursor).
	Meta *ToolResultMeta `json:"_meta,omitempty"`
}

ToolResult is the response from a tool handler.

func ErrorResult

func ErrorResult(text string) ToolResult

ErrorResult creates a ToolResult marked as an error with the given message.

func StructuredError

func StructuredError(text string, data any) ToolResult

StructuredError creates a ToolResult marked as an error with both text and structured error data. Use this to return machine-readable error details alongside a human-readable error message.

func StructuredResult

func StructuredResult(text string, data any) ToolResult

StructuredResult creates a ToolResult with both text content and structured data. Use this when the tool has an OutputSchema — structuredContent carries typed data matching the schema, while content provides a human-readable summary.

func TextResult

func TextResult(text string) ToolResult

TextResult creates a ToolResult with a single text content item.

func (*ToolResult) UnmarshalJSON added in v0.1.21

func (r *ToolResult) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a ToolResult, tolerating a single-object `content` form from peers that haven't caught up to the array-form spec. Single objects are wrapped into a 1-element slice. See #81.

type ToolResultMeta added in v0.1.18

type ToolResultMeta struct {
	// NextCursor is a pagination cursor for fetching the next page.
	// Empty when there are no more pages.
	NextCursor string `json:"nextCursor,omitempty"`
}

ToolResultMeta carries optional metadata on a tool result.

type ToolsCap

type ToolsCap struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

ToolsCap describes the server's tools capability.

type ToolsListResult

type ToolsListResult struct {
	Tools      []ToolDef `json:"tools"`
	NextCursor string    `json:"nextCursor,omitempty"`
}

ToolsListResult is the typed result for tools/list responses.

type Transport

type Transport interface {
	// Connect establishes the transport (e.g., SSE handshake, session creation).
	Connect(ctx context.Context) error

	// Call sends a JSON-RPC request and returns the response.
	Call(ctx context.Context, req *Request) (*Response, error)

	// Notify sends a JSON-RPC notification (no response expected).
	Notify(ctx context.Context, req *Request) error

	// Close shuts down the transport.
	Close() error

	// SessionID returns the transport's session identifier (empty if none).
	SessionID() string
}

Transport is the minimal interface for client-server communication. Both HTTP transports and the in-process transport satisfy this interface. The client package consumes it; the server package provides implementations.

type UICSPConfig

type UICSPConfig struct {
	// ConnectDomains → CSP connect-src (fetch, XHR, WebSocket targets).
	ConnectDomains []string `json:"connectDomains,omitempty"`

	// ResourceDomains → CSP script-src, style-src, img-src, font-src, media-src.
	ResourceDomains []string `json:"resourceDomains,omitempty"`

	// FrameDomains → CSP frame-src (nested iframes).
	FrameDomains []string `json:"frameDomains,omitempty"`

	// BaseUriDomains → CSP base-uri.
	BaseUriDomains []string `json:"baseUriDomains,omitempty"`
}

UICSPConfig declares external domains for Content-Security-Policy construction. Hosts use these declarations when sandboxing MCP App iframes.

type UIMetadata

type UIMetadata struct {
	// ResourceUri points to a ui:// resource containing the HTML to render.
	// Required for tools that want inline UI rendering.
	ResourceUri string `json:"resourceUri,omitempty"`

	// Visibility controls who can see/call this tool.
	// Default (nil): host applies its own default (typically ["model", "app"]).
	Visibility []UIVisibility `json:"visibility,omitempty"`

	// CSP declares external domains the app needs to load resources from.
	// Hosts construct Content-Security-Policy from these declarations.
	CSP *UICSPConfig `json:"csp,omitempty"`

	// Permissions lists browser capabilities the app requests
	// (e.g., "camera", "microphone", "geolocation", "clipboardWrite").
	Permissions []string `json:"permissions,omitempty"`

	// PrefersBorder hints whether the host should draw a visible border.
	// nil = host decides, true = border, false = no border.
	PrefersBorder *bool `json:"prefersBorder,omitempty"`

	// Domain requests a dedicated sandbox origin for the app.
	// Format is host-dependent (e.g., "myapp" → myapp.claudemcpcontent.com).
	Domain string `json:"domain,omitempty"`

	// SupportedDisplayModes declares which display modes this app can render in.
	// Nil means the host decides. Hosts use this to offer mode switching UI.
	SupportedDisplayModes []DisplayMode `json:"supportedDisplayModes,omitempty"`
}

UIMetadata describes UI presentation metadata for tools and resources. Serialized as the "_meta.ui" object in tools/list and resources/read responses. Part of the MCP Apps extension (io.modelcontextprotocol/ui).

type UIVisibility

type UIVisibility string

UIVisibility controls tool access scope in the MCP Apps extension.

const (
	// UIVisibilityModel means the tool appears in tools/list for the LLM.
	UIVisibilityModel UIVisibility = "model"

	// UIVisibilityApp means the tool is callable by apps from the same server.
	UIVisibilityApp UIVisibility = "app"
)

Jump to

Keyboard shortcuts

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