Documentation
¶
Overview ¶
Package mcp defines the core types and interfaces for the Model Context Protocol (MCP). MCP is a protocol for communication between LLM-powered applications and their supporting services.
Index ¶
- Constants
- Variables
- func DecodeHeaderValue(value string) (string, bool)
- func EncodeHeaderValue(value any) (string, bool)
- func ExtractHeaderName(method MCPMethod, params json.RawMessage) (string, bool)
- func ExtractMap(data map[string]any, key string) map[string]any
- func ExtractString(data map[string]any, key string) string
- func GenerateParamHeaders(tool *Tool, params json.RawMessage) map[string]string
- func GetTextFromContent(content any) string
- func IsHeaderMismatch(err error) bool
- func IsMissingRequiredClientCapability(err error) bool
- func IsModernProtocol(version string) bool
- func IsUnsupportedProtocolVersion(err error) bool
- func IsValidProtocolVersion(version string) bool
- func LegacyProtocolVersions() []string
- func MarshalContent(content Content) ([]byte, error)
- func MethodRequiresNameHeader(method MCPMethod) bool
- func NegotiateLegacyVersion(clientVersion string) string
- func NegotiateMutuallySupportedVersion(supported []string) string
- func NewStructuredToolHandler[TArgs any, TResult any](handler StructuredToolHandlerFunc[TArgs, TResult]) func(ctx context.Context, request CallToolRequest) (*CallToolResult, error)
- func NewTypedToolHandler[T any](handler TypedToolHandlerFunc[T]) func(ctx context.Context, request CallToolRequest) (*CallToolResult, error)
- func ParseArgument(request CallToolRequest, key string, defaultVal any) any
- func ParseBoolean(request CallToolRequest, key string, defaultValue bool) bool
- func ParseFloat32(request CallToolRequest, key string, defaultValue float32) float32
- func ParseFloat64(request CallToolRequest, key string, defaultValue float64) float64
- func ParseInt(request CallToolRequest, key string, defaultValue int) int
- func ParseInt8(request CallToolRequest, key string, defaultValue int8) int8
- func ParseInt16(request CallToolRequest, key string, defaultValue int16) int16
- func ParseInt32(request CallToolRequest, key string, defaultValue int32) int32
- func ParseInt64(request CallToolRequest, key string, defaultValue int64) int64
- func ParseString(request CallToolRequest, key string, defaultValue string) string
- func ParseStringMap(request CallToolRequest, key string, defaultValue map[string]any) map[string]any
- func ParseUInt(request CallToolRequest, key string, defaultValue uint) uint
- func ParseUInt8(request CallToolRequest, key string, defaultValue uint8) uint8
- func ParseUInt16(request CallToolRequest, key string, defaultValue uint16) uint16
- func ParseUInt32(request CallToolRequest, key string, defaultValue uint32) uint32
- func ParseUInt64(request CallToolRequest, key string, defaultValue uint64) uint64
- func RelatedTaskMeta(taskID string) map[string]any
- func RequiresStandardHeaders(protocolVersion string) bool
- func SchemaFor[T any]() map[string]any
- func SchemaForRaw[T any]() (json.RawMessage, error)
- func StandardHeaders(protocolVersion string, method MCPMethod, params json.RawMessage) map[string]string
- func ToBoolPtr(b bool) *bool
- func ToInt64Ptr(i int64) *int64
- func TypeKey[T any]() string
- func ValidateISO8601Timestamp(timestamp string) error
- func ValidateParamHeaderAnnotations(tool *Tool) error
- func ValidateParamHeaders(getHeader func(string) string, tool *Tool, params json.RawMessage) error
- func ValidateStandardHeaders(getHeader func(string) string, protocolVersion string, method MCPMethod, ...) error
- func WarmFor[T any](cache *SchemaCache, key ...string) error
- type Annotated
- type Annotations
- type ArgumentOption
- type AudioContent
- type BlobResourceContents
- type CacheHintSetter
- type CacheScope
- type CacheableResult
- type CallToolParams
- type CallToolRequest
- func (r CallToolRequest) BindArguments(target any) error
- func (r CallToolRequest) GetArguments() map[string]any
- func (r CallToolRequest) GetBool(key string, defaultValue bool) bool
- func (r CallToolRequest) GetBoolSlice(key string, defaultValue []bool) []bool
- func (r CallToolRequest) GetFloat(key string, defaultValue float64) float64
- func (r CallToolRequest) GetFloatSlice(key string, defaultValue []float64) []float64
- func (r CallToolRequest) GetInt(key string, defaultValue int) int
- func (r CallToolRequest) GetIntSlice(key string, defaultValue []int) []int
- func (r CallToolRequest) GetRawArguments() any
- func (r CallToolRequest) GetString(key string, defaultValue string) string
- func (r CallToolRequest) GetStringSlice(key string, defaultValue []string) []string
- func (r CallToolRequest) RequireBool(key string) (bool, error)
- func (r CallToolRequest) RequireBoolSlice(key string) ([]bool, error)
- func (r CallToolRequest) RequireFloat(key string) (float64, error)
- func (r CallToolRequest) RequireFloatSlice(key string) ([]float64, error)
- func (r CallToolRequest) RequireInt(key string) (int, error)
- func (r CallToolRequest) RequireIntSlice(key string) ([]int, error)
- func (r CallToolRequest) RequireString(key string) (string, error)
- func (r CallToolRequest) RequireStringSlice(key string) ([]string, error)
- type CallToolResult
- func FormatNumberResult(value float64) *CallToolResult
- func NewToolResultAudio(text, audioData, mimeType string) *CallToolResult
- func NewToolResultError(text string) *CallToolResult
- func NewToolResultErrorFromErr(text string, err error) *CallToolResult
- func NewToolResultErrorf(format string, a ...any) *CallToolResult
- func NewToolResultImage(text, imageData, mimeType string) *CallToolResult
- func NewToolResultJSON[T any](data T) (*CallToolResult, error)
- func NewToolResultResource(text string, resource ResourceContents) *CallToolResult
- func NewToolResultStructured(structured any, fallbackText string) *CallToolResult
- func NewToolResultStructuredOnly(structured any) *CallToolResult
- func NewToolResultText(text string) *CallToolResult
- func ParseCallToolResult(rawMessage *json.RawMessage) (*CallToolResult, error)
- type CancelTaskParams
- type CancelTaskRequest
- type CancelTaskResult
- type CancelledNotification
- type CancelledNotificationParams
- type ClientCapabilities
- type ClientNotification
- type ClientRequest
- type ClientResult
- type CompleteArgument
- type CompleteContext
- type CompleteParams
- type CompleteRequest
- type CompleteResult
- type Completion
- type Content
- type CreateMessageParams
- type CreateMessageRequest
- type CreateMessageResult
- type CreateTaskResult
- type Cursor
- type DiscoverParams
- type DiscoverRequest
- type DiscoverResult
- type ElicitationCapability
- type ElicitationParams
- type ElicitationRequest
- type ElicitationResponse
- type ElicitationResponseAction
- type ElicitationResult
- type EmbeddedResource
- type EmptyResult
- type GetPromptParams
- type GetPromptRequest
- type GetPromptResult
- type GetTaskParams
- type GetTaskRequest
- type GetTaskResult
- type HeaderMismatchError
- type Icon
- type IconTheme
- type ImageContent
- type Implementation
- type InitializeParams
- type InitializeRequest
- type InitializeResult
- type InitializedNotification
- type InputRequest
- type InputRequests
- type InputRequiredResult
- type InputResponse
- type InputResponses
- type JSONRPCError
- type JSONRPCErrorDetails
- type JSONRPCMessage
- type JSONRPCNotification
- type JSONRPCRequest
- type JSONRPCResponse
- type ListPromptsRequest
- type ListPromptsResult
- type ListResourceTemplatesRequest
- type ListResourceTemplatesResult
- type ListResourcesRequest
- type ListResourcesResult
- type ListRootsParams
- type ListRootsRequest
- type ListRootsResult
- type ListTasksRequest
- type ListTasksResult
- type ListToolsRequest
- type ListToolsResult
- type LoggingLevel
- type LoggingMessageNotification
- type LoggingMessageNotificationParams
- type MCPMethod
- type Meta
- func (m *Meta) ClientCapabilities() *ClientCapabilities
- func (m *Meta) ClientInfo() *Implementation
- func (m *Meta) GetMetaField(key string) any
- func (m *Meta) LogLevel() LoggingLevel
- func (m *Meta) MarshalJSON() ([]byte, error)
- func (m *Meta) ProtocolVersion() string
- func (m *Meta) ServerInfo() *Implementation
- func (m *Meta) SetClientCapabilities(caps ClientCapabilities)
- func (m *Meta) SetClientInfo(info Implementation)
- func (m *Meta) SetLogLevel(level LoggingLevel)
- func (m *Meta) SetMetaField(key string, value any)
- func (m *Meta) SetProtocolVersion(version string)
- func (m *Meta) SetServerInfo(info Implementation)
- func (m *Meta) SetSubscriptionID(id any)
- func (m *Meta) SubscriptionID() any
- func (m *Meta) UnmarshalJSON(data []byte) error
- type MissingRequiredClientCapabilityError
- type ModelHint
- type ModelPreferences
- type MultiRoundTripParams
- type MultiRoundTripResult
- type Named
- type Notification
- type NotificationParams
- type PaginatedParams
- type PaginatedRequest
- type PaginatedResult
- type ParamHeaderBinding
- type Params
- type PingRequest
- type ProgressNotification
- type ProgressNotificationParams
- type ProgressToken
- type Prompt
- type PromptArgument
- type PromptListChangedNotification
- type PromptMessage
- type PromptOption
- type PromptReference
- type PropertyOption
- func AdditionalProperties(schema any) PropertyOption
- func DefaultArray[T any](value []T) PropertyOption
- func DefaultBool(value bool) PropertyOption
- func DefaultNumber[T int | int64 | float64](value T) PropertyOption
- func DefaultString(value string) PropertyOption
- func Description(desc string) PropertyOption
- func Enum(values ...string) PropertyOption
- func Items(schema any) PropertyOption
- func Max[T int | int64 | float64](max T) PropertyOption
- func MaxItems(max int) PropertyOption
- func MaxLength(max int) PropertyOption
- func MaxProperties(max int) PropertyOption
- func Min[T int | int64 | float64](min T) PropertyOption
- func MinItems(min int) PropertyOption
- func MinLength(min int) PropertyOption
- func MinProperties(min int) PropertyOption
- func MultipleOf[T int | int64 | float64](value T) PropertyOption
- func Pattern(pattern string) PropertyOption
- func Properties(props map[string]any) PropertyOption
- func PropertyNames(schema map[string]any) PropertyOption
- func Required() PropertyOption
- func Title(title string) PropertyOption
- func UniqueItems(unique bool) PropertyOption
- func WithBooleanItems(opts ...PropertyOption) PropertyOption
- func WithIntegerItems(opts ...PropertyOption) PropertyOption
- func WithNumberItems(opts ...PropertyOption) PropertyOption
- func WithStringEnumItems(values []string) PropertyOption
- func WithStringItems(opts ...PropertyOption) PropertyOption
- type ReadResourceParams
- type ReadResourceRequest
- type ReadResourceResult
- type Request
- type RequestId
- type RequestParams
- type Resource
- type ResourceContents
- type ResourceLink
- type ResourceListChangedNotification
- type ResourceOption
- func WithAnnotations(audience []Role, priority float64, lastModified string) ResourceOption
- func WithLastModified(timestamp string) ResourceOption
- func WithMIMEType(mimeType string) ResourceOption
- func WithResourceDescription(description string) ResourceOption
- func WithResourceIcons(icons ...Icon) ResourceOption
- func WithResourceSize(size int64) ResourceOption
- func WithResourceTitle(title string) ResourceOption
- type ResourceReference
- type ResourceTemplate
- type ResourceTemplateOption
- func WithTemplateAnnotations(audience []Role, priority float64, lastModified string) ResourceTemplateOption
- func WithTemplateDescription(description string) ResourceTemplateOption
- func WithTemplateIcons(icons ...Icon) ResourceTemplateOption
- func WithTemplateMIMEType(mimeType string) ResourceTemplateOption
- func WithTemplateTitle(title string) ResourceTemplateOption
- type ResourceUpdatedNotification
- type ResourceUpdatedNotificationParams
- type Result
- type ResultMetadata
- type ResultType
- type Role
- type Root
- type RootsListChangedNotification
- type SamplingCapability
- type SamplingMessage
- type SchemaCache
- func (c *SchemaCache) Get(typeName string) (map[string]any, bool)
- func (c *SchemaCache) GetRaw(typeName string) (json.RawMessage, bool)
- func (c *SchemaCache) Has(typeName string) bool
- func (c *SchemaCache) Keys() []string
- func (c *SchemaCache) Len() int
- func (c *SchemaCache) MarshalJSON() ([]byte, error)
- func (c *SchemaCache) Save(path string) error
- func (c *SchemaCache) UnmarshalJSON(data []byte) error
- func (c *SchemaCache) Warm(typeName string, schema map[string]any)
- func (c *SchemaCache) WarmRaw(typeName string, schema json.RawMessage)
- type ServerCapabilities
- type ServerNotification
- type ServerRequest
- type ServerResult
- type SetLevelParams
- type SetLevelRequest
- type StructuredToolHandlerFunc
- type SubscribeParams
- type SubscribeRequest
- type SubscriptionFilter
- type SubscriptionsAcknowledgedNotification
- type SubscriptionsAcknowledgedParams
- type SubscriptionsListenParams
- type SubscriptionsListenRequest
- type SubscriptionsListenResult
- type Task
- type TaskOption
- type TaskParams
- type TaskRequestsCapability
- type TaskResultParams
- type TaskResultRequest
- type TaskResultResult
- type TaskStatus
- type TaskStatusNotification
- type TaskStatusNotificationParams
- type TaskSupport
- type TasksCapability
- type TextContent
- type TextResourceContents
- type Tool
- type ToolAnnotation
- type ToolArgumentsSchema
- type ToolChoice
- type ToolChoiceMode
- type ToolExecution
- type ToolInputSchema
- type ToolListChangedNotification
- type ToolOption
- func WithAny(name string, opts ...PropertyOption) ToolOption
- func WithArray(name string, opts ...PropertyOption) ToolOption
- func WithBoolean(name string, opts ...PropertyOption) ToolOption
- func WithCachedInputSchema[T any](cache *SchemaCache) ToolOption
- func WithCachedInputSchemaKey[T any](cache *SchemaCache, key string) ToolOption
- func WithCachedOutputSchema[T any](cache *SchemaCache) ToolOption
- func WithCachedOutputSchemaKey[T any](cache *SchemaCache, key string) ToolOption
- func WithDeferLoading(deferLoading bool) ToolOption
- func WithDescription(description string) ToolOption
- func WithDestructiveHintAnnotation(value bool) ToolOption
- func WithIdempotentHintAnnotation(value bool) ToolOption
- func WithInputSchema[T any]() ToolOption
- func WithInteger(name string, opts ...PropertyOption) ToolOption
- func WithNumber(name string, opts ...PropertyOption) ToolOption
- func WithObject(name string, opts ...PropertyOption) ToolOption
- func WithOpenWorldHintAnnotation(value bool) ToolOption
- func WithOutputSchema[T any]() ToolOption
- func WithRawInputSchema(schema json.RawMessage) ToolOption
- func WithRawOutputSchema(schema json.RawMessage) ToolOption
- func WithReadOnlyHintAnnotation(value bool) ToolOption
- func WithSchemaAdditionalProperties(schema any) ToolOption
- func WithString(name string, opts ...PropertyOption) ToolOption
- func WithTaskSupport(support TaskSupport) ToolOption
- func WithTitleAnnotation(title string) ToolOption
- func WithToolAnnotation(annotation ToolAnnotation) ToolOption
- func WithToolIcons(icons ...Icon) ToolOption
- func WithToolTitle(title string) ToolOption
- type ToolOutputSchema
- type ToolResultContent
- type ToolUseContent
- type TypedToolHandlerFunc
- type URITemplate
- type URLElicitationRequiredError
- type UnsubscribeParams
- type UnsubscribeRequest
- type UnsupportedProtocolVersionData
- type UnsupportedProtocolVersionError
Constants ¶
const ( ContentTypeText = "text" ContentTypeImage = "image" ContentTypeAudio = "audio" ContentTypeLink = "resource_link" ContentTypeResource = "resource" ContentTypeToolUse = "tool_use" ContentTypeToolResult = "tool_result" ElicitationModeForm = "form" ElicitationModeURL = "url" )
const ( // HeaderProtocolVersion carries the MCP protocol version of a request. HeaderProtocolVersion = "Mcp-Protocol-Version" // HeaderSessionID carries a protocol-level session identifier. // // Removed in protocol version 2026-07-28 (SEP-2567): servers serving that // version ignore it and never mint or echo session IDs. HeaderSessionID = "Mcp-Session-Id" // HeaderLastEventID requests replay of a broken SSE stream. // // Stream resumability was removed in protocol version 2026-07-28 // (SEP-2575): a broken stream loses the in-flight request, and the client // must re-issue it with a new request ID. HeaderLastEventID = "Last-Event-ID" // HeaderMethod mirrors the JSON-RPC method of the request body. HeaderMethod = "Mcp-Method" // HeaderName mirrors params.name (tools/call, prompts/get) or params.uri // (resources/read) from the request body. HeaderName = "Mcp-Name" // HeaderParamPrefix is prepended to the x-mcp-header annotation value to // form the header carrying a tool parameter. HeaderParamPrefix = "Mcp-Param-" )
Standard MCP HTTP header names.
Protocol version 2026-07-28 requires Mcp-Method and Mcp-Name on Streamable HTTP POST requests so that gateways, rate limiters, and WAFs can route and meter on headers instead of parsing JSON bodies (SEP-2243).
const ( // MetaKeyProtocolVersion identifies the MCP protocol version a request is // using. It is required on every request in protocol versions >= 2026-07-28 // and, over HTTP, MUST match the MCP-Protocol-Version header. MetaKeyProtocolVersion = "io.modelcontextprotocol/protocolVersion" // MetaKeyClientInfo identifies the client software making a request. // Clients SHOULD include it on every request. The value is an // [Implementation]. It is self-reported and unverified: servers SHOULD NOT // use it for security decisions. MetaKeyClientInfo = "io.modelcontextprotocol/clientInfo" // MetaKeyClientCapabilities carries the client's capabilities for a single // request. It is required in protocol versions >= 2026-07-28. Servers MUST // NOT infer capabilities from prior requests. The value is a // [ClientCapabilities]. MetaKeyClientCapabilities = "io.modelcontextprotocol/clientCapabilities" // MetaKeyServerInfo identifies the server software producing a result. // Servers SHOULD include it in every result's _meta. The value is an // [Implementation]. MetaKeyServerInfo = "io.modelcontextprotocol/serverInfo" // MetaKeyLogLevel requests notifications/message at or above the given // level for a single request. When absent, servers MUST NOT emit log // notifications for that request. Replaces the logging/setLevel RPC. // // The Logging feature it belongs to is deprecated as of protocol version // 2026-07-28 (SEP-2577), and remains functional for at least twelve // months. Log to stderr or use OpenTelemetry instead. MetaKeyLogLevel = "io.modelcontextprotocol/logLevel" // MetaKeySubscriptionID identifies the subscriptions/listen stream a // notification was delivered on. The value is the JSON-RPC ID of the // subscriptions/listen request that opened the stream. MetaKeySubscriptionID = "io.modelcontextprotocol/subscriptionId" )
Well-known _meta keys defined by protocol version 2026-07-28 (SEP-2575).
These keys carry the information that the initialize handshake used to establish once per session. They are namespaced with the reserved "io.modelcontextprotocol/" prefix.
const ( // PARSE_ERROR indicates invalid JSON was received by the server. PARSE_ERROR = -32700 // INVALID_REQUEST indicates the JSON sent is not a valid Request object. INVALID_REQUEST = -32600 // METHOD_NOT_FOUND indicates the method does not exist/is not available. METHOD_NOT_FOUND = -32601 // INVALID_PARAMS indicates invalid method parameter(s). INVALID_PARAMS = -32602 // INTERNAL_ERROR indicates internal JSON-RPC error. INTERNAL_ERROR = -32603 // REQUEST_INTERRUPTED indicates a request was cancelled or timed out. REQUEST_INTERRUPTED = -32800 )
Standard JSON-RPC error codes
const ( // RESOURCE_NOT_FOUND indicates that the requested resource was not found. // // Protocol version 2026-07-28 aligns this condition with JSON-RPC by using // [INVALID_PARAMS] instead. This code is still emitted to, and accepted // from, peers using an earlier version. RESOURCE_NOT_FOUND = -32002 // URL_ELICITATION_REQUIRED is the error code for when URL elicitation is required. URL_ELICITATION_REQUIRED = -32042 // HEADER_MISMATCH indicates that a standard MCP HTTP header is missing, // malformed, or does not match the corresponding value in the request body // (SEP-2243). HEADER_MISMATCH = -32020 // MISSING_REQUIRED_CLIENT_CAPABILITY indicates the client did not declare a // capability the server requires to serve the request (SEP-2575). MISSING_REQUIRED_CLIENT_CAPABILITY = -32021 // UNSUPPORTED_PROTOCOL_VERSION indicates the server does not implement the // protocol version the request declared (SEP-2575). The error data carries // an [UnsupportedProtocolVersionData]. UNSUPPORTED_PROTOCOL_VERSION = -32022 )
MCP error codes
Protocol version 2026-07-28 partitions the JSON-RPC server-error range: -32000 to -32019 remains implementation-defined (existing SDK usage is grandfathered) and -32020 to -32099 is reserved for the MCP specification.
const ( // ProtocolVersion20260728 introduced the stateless protocol core: no // initialize handshake, no sessions, server/discover, subscriptions/listen, // and multi round-trip requests (SEP-2575, SEP-2322, SEP-2243, SEP-2549). ProtocolVersion20260728 = "2026-07-28" // ProtocolVersion20251125 is the last revision that used the // initialize/initialized handshake. ProtocolVersion20251125 = "2025-11-25" // ProtocolVersion20250618 added the MCP-Protocol-Version header. ProtocolVersion20250618 = "2025-06-18" // ProtocolVersion20250326 introduced the Streamable HTTP transport. ProtocolVersion20250326 = "2025-03-26" // ProtocolVersion20241105 is the original revision, using the deprecated // HTTP+SSE transport. ProtocolVersion20241105 = "2024-11-05" )
Protocol version constants for every MCP revision this SDK understands.
Protocol versions are ISO-8601 dates, so they may be compared lexicographically: a simple string comparison against ProtocolVersion20260728 is enough to distinguish the "modern" (stateless, per-request metadata) era from the "legacy" (initialize-handshake) era.
const JSONRPC_VERSION = "2.0"
JSONRPC_VERSION is the version of JSON-RPC used by MCP.
const LATEST_LEGACY_PROTOCOL_VERSION = ProtocolVersion20251125
LATEST_LEGACY_PROTOCOL_VERSION is the most recent protocol version that still uses the initialize/initialized handshake. It is the highest version that can be negotiated through initialize.
const LATEST_PROTOCOL_VERSION = ProtocolVersion20260728
LATEST_PROTOCOL_VERSION is the most recent version of the MCP protocol supported by this SDK.
const ModelImmediateResponseMetaKey = "io.modelcontextprotocol/model-immediate-response"
ModelImmediateResponseMetaKey is the metadata key for providing an immediate response to the model. Servers can use this optional key in the _meta field of CreateTaskResult to provide a string that should be passed as an immediate tool result to the model while the task continues executing asynchronously in the background.
const RelatedTaskMetaKey = "io.modelcontextprotocol/related-task"
RelatedTaskMetaKey is the metadata key for associating a message with a task.
Variables ¶
var ( // ErrParseError indicates a JSON parsing error (code: PARSE_ERROR). ErrParseError = errors.New("parse error") // ErrInvalidRequest indicates an invalid JSON-RPC request (code: INVALID_REQUEST). ErrInvalidRequest = errors.New("invalid request") // ErrMethodNotFound indicates the requested method does not exist (code: METHOD_NOT_FOUND). ErrMethodNotFound = errors.New("method not found") // ErrInvalidParams indicates invalid method parameters (code: INVALID_PARAMS). ErrInvalidParams = errors.New("invalid params") // ErrInternalError indicates an internal JSON-RPC error (code: INTERNAL_ERROR). ErrInternalError = errors.New("internal error") // ErrRequestInterrupted indicates a request was cancelled or timed out (code: REQUEST_INTERRUPTED). ErrRequestInterrupted = errors.New("request interrupted") // ErrResourceNotFound indicates a requested resource was not found (code: RESOURCE_NOT_FOUND). ErrResourceNotFound = errors.New("resource not found") // ErrEmbeddedResourceMissingVariant indicates an embedded resource has neither text nor blob content. ErrEmbeddedResourceMissingVariant = errors.New("missing text or blob field") // ErrEmbeddedResourceMissingURI indicates an embedded resource content variant has no URI. ErrEmbeddedResourceMissingURI = errors.New("resource uri is missing") )
Sentinel errors for common JSON-RPC error codes.
var ValidProtocolVersions = []string{ ProtocolVersion20260728, ProtocolVersion20251125, ProtocolVersion20250618, ProtocolVersion20250326, ProtocolVersion20241105, }
ValidProtocolVersions lists all known valid MCP protocol versions, in descending order (newest first).
Functions ¶
func DecodeHeaderValue ¶ added in v1.0.0
DecodeHeaderValue decodes a header value that may be wrapped in the =?base64?...?= sentinel. It reports false when the wrapper is present but the payload is not valid Base64.
func EncodeHeaderValue ¶ added in v1.0.0
EncodeHeaderValue converts a tool parameter value to an HTTP header-safe string per the SEP-2243 encoding rules:
- string: used as-is when it is safe ASCII, otherwise Base64 encoded
- int64: decimal representation
- bool: "true" or "false"
Values containing non-ASCII characters, control characters, or leading/trailing whitespace are Base64 encoded with the =?base64?...?= wrapper. It reports false when the value is not a supported primitive.
func ExtractHeaderName ¶ added in v1.0.0
func ExtractHeaderName(method MCPMethod, params json.RawMessage) (string, bool)
ExtractHeaderName returns the value that belongs in the Mcp-Name header for the given method and raw params: params.name for tools/call and prompts/get, params.uri for resources/read. It reports false when the method does not carry a name.
func GenerateParamHeaders ¶ added in v1.0.0
func GenerateParamHeaders(tool *Tool, params json.RawMessage) map[string]string
GenerateParamHeaders returns the Mcp-Param-* headers a client must mirror onto a tools/call request, derived from the tool's x-mcp-header annotations and the raw params of the call.
func GetTextFromContent ¶ added in v0.42.0
GetTextFromContent extracts text from a Content interface that might be a TextContent struct or a map[string]any that was unmarshaled from JSON. This is useful when dealing with content that comes from different transport layers that may handle JSON differently.
This function uses fallback behavior for non-text content - it returns a string representation via fmt.Sprintf for any content that cannot be extracted as text. This is a lossy operation intended for convenience in logging and display scenarios.
For strict type validation, use ParseContent() instead, which returns an error for invalid content.
func IsHeaderMismatch ¶ added in v1.0.0
IsHeaderMismatch checks if an error is a HeaderMismatchError.
func IsMissingRequiredClientCapability ¶ added in v1.0.0
IsMissingRequiredClientCapability checks if an error is a MissingRequiredClientCapabilityError.
func IsModernProtocol ¶ added in v1.0.0
IsModernProtocol reports whether version uses the stateless protocol core introduced in 2026-07-28, where requests carry their protocol version, client identity, and capabilities in _meta rather than establishing a session through initialize.
Unknown future versions that sort after 2026-07-28 are treated as modern, so that this SDK degrades gracefully rather than rejecting them outright.
func IsUnsupportedProtocolVersion ¶ added in v0.35.0
IsUnsupportedProtocolVersion checks if an error is an UnsupportedProtocolVersionError
func IsValidProtocolVersion ¶ added in v1.0.0
IsValidProtocolVersion reports whether version is known to this SDK.
func LegacyProtocolVersions ¶ added in v1.0.0
func LegacyProtocolVersions() []string
LegacyProtocolVersions returns the subset of ValidProtocolVersions that use the initialize handshake.
func MarshalContent ¶ added in v0.34.0
MarshalContent marshals MCP content as JSON.
func MethodRequiresNameHeader ¶ added in v1.0.0
MethodRequiresNameHeader reports whether the Mcp-Name header is required for the given method.
func NegotiateLegacyVersion ¶ added in v1.0.0
NegotiateLegacyVersion returns the protocol version a server should report in an InitializeResult, given the version requested by the client.
The initialize handshake was removed in 2026-07-28, so it can never negotiate that version or later: the result is always capped at LATEST_LEGACY_PROTOCOL_VERSION. Clients reach the modern protocol through server/discover instead.
func NegotiateMutuallySupportedVersion ¶ added in v1.0.0
NegotiateMutuallySupportedVersion returns the highest protocol version present in both ValidProtocolVersions and supported, or "" when the two sets are disjoint.
func NewStructuredToolHandler ¶ added in v0.36.0
func NewStructuredToolHandler[TArgs any, TResult any](handler StructuredToolHandlerFunc[TArgs, TResult]) func(ctx context.Context, request CallToolRequest) (*CallToolResult, error)
NewStructuredToolHandler creates a ToolHandlerFunc that automatically binds arguments to a typed struct and returns structured output. It automatically creates both structured and text content (from the structured output) for backwards compatibility.
func NewTypedToolHandler ¶ added in v0.29.0
func NewTypedToolHandler[T any](handler TypedToolHandlerFunc[T]) func(ctx context.Context, request CallToolRequest) (*CallToolResult, error)
NewTypedToolHandler creates a ToolHandlerFunc that automatically binds arguments to a typed struct
func ParseArgument ¶ added in v0.22.0
func ParseArgument(request CallToolRequest, key string, defaultVal any) any
func ParseBoolean ¶ added in v0.22.0
func ParseBoolean(request CallToolRequest, key string, defaultValue bool) bool
ParseBoolean extracts and converts a boolean parameter from a CallToolRequest. If the key is not found in the Arguments map, the defaultValue is returned. The function uses cast.ToBool for conversion which handles various string representations such as "true", "yes", "1", etc.
func ParseFloat32 ¶ added in v0.22.0
func ParseFloat32(request CallToolRequest, key string, defaultValue float32) float32
ParseFloat32 extracts and converts a float32 parameter from a CallToolRequest.
func ParseFloat64 ¶ added in v0.22.0
func ParseFloat64(request CallToolRequest, key string, defaultValue float64) float64
ParseFloat64 extracts and converts a float64 parameter from a CallToolRequest.
func ParseInt ¶ added in v0.22.0
func ParseInt(request CallToolRequest, key string, defaultValue int) int
ParseInt extracts and converts an int parameter from a CallToolRequest.
func ParseInt8 ¶ added in v0.22.0
func ParseInt8(request CallToolRequest, key string, defaultValue int8) int8
ParseInt8 extracts and converts an int8 parameter from a CallToolRequest.
func ParseInt16 ¶ added in v0.22.0
func ParseInt16(request CallToolRequest, key string, defaultValue int16) int16
ParseInt16 extracts and converts an int16 parameter from a CallToolRequest.
func ParseInt32 ¶ added in v0.22.0
func ParseInt32(request CallToolRequest, key string, defaultValue int32) int32
ParseInt32 extracts and converts an int32 parameter from a CallToolRequest.
func ParseInt64 ¶ added in v0.22.0
func ParseInt64(request CallToolRequest, key string, defaultValue int64) int64
ParseInt64 extracts and converts an int64 parameter from a CallToolRequest. If the key is not found in the Arguments map, the defaultValue is returned.
func ParseString ¶ added in v0.22.0
func ParseString(request CallToolRequest, key string, defaultValue string) string
ParseString extracts and converts a string parameter from a CallToolRequest.
func ParseStringMap ¶ added in v0.22.0
func ParseStringMap(request CallToolRequest, key string, defaultValue map[string]any) map[string]any
ParseStringMap extracts and converts a string map parameter from a CallToolRequest.
func ParseUInt ¶ added in v0.22.0
func ParseUInt(request CallToolRequest, key string, defaultValue uint) uint
ParseUInt extracts and converts an uint parameter from a CallToolRequest.
func ParseUInt8 ¶ added in v0.22.0
func ParseUInt8(request CallToolRequest, key string, defaultValue uint8) uint8
ParseUInt8 extracts and converts an uint8 parameter from a CallToolRequest.
func ParseUInt16 ¶ added in v0.22.0
func ParseUInt16(request CallToolRequest, key string, defaultValue uint16) uint16
ParseUInt16 extracts and converts an uint16 parameter from a CallToolRequest.
func ParseUInt32 ¶ added in v0.22.0
func ParseUInt32(request CallToolRequest, key string, defaultValue uint32) uint32
ParseUInt32 extracts and converts an uint32 parameter from a CallToolRequest.
func ParseUInt64 ¶ added in v0.22.0
func ParseUInt64(request CallToolRequest, key string, defaultValue uint64) uint64
ParseUInt64 extracts and converts an uint64 parameter from a CallToolRequest.
func RelatedTaskMeta ¶ added in v0.44.0
RelatedTaskMeta creates the metadata for associating a message with a task. The returned map contains a "taskId" field with the provided task ID.
func RequiresStandardHeaders ¶ added in v1.0.0
RequiresStandardHeaders reports whether requests using the given protocol version must carry the standard Mcp-Method and Mcp-Name headers.
func SchemaFor ¶ added in v0.51.0
SchemaFor returns the JSON schema generated for the Go type T, formatted as a generic map suitable for SchemaCache.Warm. It returns nil if reflection or marshalling fails. Use SchemaForRaw when an error is desired.
func SchemaForRaw ¶ added in v0.51.0
func SchemaForRaw[T any]() (json.RawMessage, error)
SchemaForRaw returns the JSON schema generated for the Go type T as raw JSON. It is the lower-level building block underlying SchemaFor, WithInputSchema and WithOutputSchema.
func StandardHeaders ¶ added in v1.0.0
func StandardHeaders(protocolVersion string, method MCPMethod, params json.RawMessage) map[string]string
StandardHeaders returns the standard MCP headers a client must set on a Streamable HTTP POST request carrying the given method and params.
It returns nil for protocol versions earlier than 2026-07-28.
func ToInt64Ptr ¶ added in v0.44.0
ToInt64Ptr returns a pointer to the given int64 value
func TypeKey ¶ added in v0.51.0
TypeKey returns the canonical cache key for the Go type T as derived from reflection. The key is the package-qualified type name (e.g. "main.WeatherInput"). Renaming or moving the type will change this key, so callers that need a stable identifier across refactors should pass an explicit key to SchemaCache.Warm and WithCachedInputSchemaKey.
func ValidateISO8601Timestamp ¶ added in v0.44.0
ValidateISO8601Timestamp verifies that timestamp is a valid ISO 8601 timestamp using the RFC3339 layout. An empty string is considered valid. It returns nil when the timestamp is valid, or the parsing error when it is not.
func ValidateParamHeaderAnnotations ¶ added in v1.0.0
ValidateParamHeaderAnnotations checks that every x-mcp-header annotation in the tool's input schema is well formed: applied only to primitive types, a non-empty valid HTTP token, and case-insensitively unique across the whole schema.
Servers MUST reject tool definitions that violate these constraints.
func ValidateParamHeaders ¶ added in v1.0.0
ValidateParamHeaders checks that every Mcp-Param-* header on a tools/call request agrees with the corresponding argument in the request body.
getHeader returns the value of a header, or "" when absent.
func ValidateStandardHeaders ¶ added in v1.0.0
func ValidateStandardHeaders(getHeader func(string) string, protocolVersion string, method MCPMethod, params json.RawMessage) error
ValidateStandardHeaders checks the Mcp-Method and Mcp-Name headers against the method and params of the request body, per SEP-2243.
It is a no-op for protocol versions earlier than 2026-07-28, which did not define these headers. getHeader returns the value of a header, or "" when absent.
func WarmFor ¶ added in v0.51.0
func WarmFor[T any](cache *SchemaCache, key ...string) error
WarmFor computes the schema for T via reflection and stores it in cache. If key is provided, the first non-empty entry is used as the cache key; otherwise TypeKey is used. WarmFor is a no-op when cache is nil. It returns an error only when schema generation itself fails.
Types ¶
type Annotated ¶ added in v0.4.0
type Annotated struct {
Annotations *Annotations `json:"annotations,omitempty"`
}
Annotated is the base for objects that include optional annotations for the client. The client can use annotations to inform how objects are used or displayed
type Annotations ¶
type Annotations struct {
// Describes who the intended customer of this object or data is.
//
// It can include multiple entries to indicate content useful for multiple
// audiences (e.g., `["user", "assistant"]`).
Audience []Role `json:"audience,omitempty"`
// Describes how important this data is for operating the server.
//
// A value of 1 means "most important," and indicates that the data is
// effectively required, while 0 means "least important," and indicates that
// the data is entirely optional.
// Priority ranges from 0.0 to 1.0 (1 = most important, 0 = least important).
Priority *float64 `json:"priority,omitempty"`
// ISO 8601 formatted timestamp (e.g., "2025-01-12T15:00:58Z")
LastModified string `json:"lastModified,omitempty"`
}
func ParseAnnotations ¶ added in v0.41.0
func ParseAnnotations(data map[string]any) *Annotations
ParseAnnotations parses priority, audience, and lastModified fields from the provided map and returns an Annotations struct populated with any valid values found. If data is nil, ParseAnnotations returns nil. Priority is set when a numeric value can be parsed and is stored as a *float64. Audience is populated from string values and includes only RoleUser and RoleAssistant entries. LastModified is set when the value is a string.
type ArgumentOption ¶ added in v0.5.10
type ArgumentOption func(*PromptArgument)
ArgumentOption is a function that configures a PromptArgument. It allows for flexible configuration of prompt arguments using the functional options pattern.
func ArgumentDescription ¶ added in v0.5.10
func ArgumentDescription(desc string) ArgumentOption
ArgumentDescription adds a description to a prompt argument. The description should explain the purpose and expected values of the argument.
func ArgumentTitle ¶ added in v0.54.0
func ArgumentTitle(title string) ArgumentOption
ArgumentTitle sets the optional human-readable display title for a prompt argument. Per the MCP spec, clients should prefer Title over Name for display.
func RequiredArgument ¶ added in v0.5.10
func RequiredArgument() ArgumentOption
RequiredArgument marks an argument as required in the prompt. Required arguments must be provided when getting the prompt.
type AudioContent ¶ added in v0.27.0
type AudioContent struct {
Annotated
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
Type string `json:"type"` // Must be "audio"
// The base64-encoded audio data.
Data string `json:"data"`
// The MIME type of the audio. Different providers may support different audio types.
MIMEType string `json:"mimeType"`
}
AudioContent represents the contents of audio, embedded into a prompt or tool call result. It must have Type set to "audio".
func AsAudioContent ¶ added in v0.27.0
func AsAudioContent(content any) (*AudioContent, bool)
AsAudioContent attempts to cast the given interface to AudioContent
func NewAudioContent ¶ added in v0.27.0
func NewAudioContent(data, mimeType string) AudioContent
NewAudioContent creates audio content.
type BlobResourceContents ¶
type BlobResourceContents struct {
// Raw per‑resource metadata; pass‑through as defined by MCP. Not the same as mcp.Meta.
// Allows _meta to be used for MCP-UI features for example. Does not assume any specific format.
Meta map[string]any `json:"_meta,omitempty"`
// The URI of this resource.
URI string `json:"uri"`
// The MIME type of this resource, if known.
MIMEType string `json:"mimeType,omitempty"`
// A base64-encoded string representing the binary data of the item.
Blob string `json:"blob"`
}
func AsBlobResourceContents ¶ added in v0.5.0
func AsBlobResourceContents(content any) (*BlobResourceContents, bool)
AsBlobResourceContents attempts to cast the given interface to BlobResourceContents
type CacheHintSetter ¶ added in v1.0.0
type CacheHintSetter interface {
SetCacheHints(ttlMs int64, scope CacheScope)
}
CacheHintSetter is implemented by result types that carry the SEP-2549 caching hints through an embedded CacheableResult.
type CacheScope ¶ added in v1.0.0
type CacheScope string
CacheScope indicates the intended scope of a cached response, analogous to the HTTP Cache-Control public and private directives (SEP-2549).
const ( // CacheScopePublic indicates the response contains no user-specific data, // so any client or shared intermediary may cache and reuse it across // authorization contexts. CacheScopePublic CacheScope = "public" // CacheScopePrivate indicates the response may only be cached and reused // within the same authorization context. CacheScopePrivate CacheScope = "private" )
type CacheableResult ¶ added in v1.0.0
type CacheableResult struct {
Result
// TTLMs is a hint indicating how long, in milliseconds, the client may
// cache this response before re-fetching. Semantics are analogous to HTTP
// Cache-Control max-age. Zero means the response should be considered
// immediately stale.
//
// It is a pointer so that an explicit zero can be distinguished from an
// unset value; use [CacheableResult.SetCacheHints] to populate it.
TTLMs *int64 `json:"ttlMs,omitempty"`
// CacheScope controls whether shared intermediaries may cache the
// response.
CacheScope CacheScope `json:"cacheScope,omitempty"`
}
CacheableResult carries the caching hints required on results from tools/list, prompts/list, resources/list, resources/templates/list, resources/read, and server/discover in protocol version 2026-07-28 and later (SEP-2549).
Both fields are omitted when responding to a request that used an earlier protocol version.
func (*CacheableResult) SetCacheHints ¶ added in v1.0.0
func (r *CacheableResult) SetCacheHints(ttlMs int64, scope CacheScope)
SetCacheHints populates the caching hints on the result.
An empty scope defaults to CacheScopePrivate, so a result is never shared across authorization contexts unless the caller asks for it: list and read results are frequently scoped to the caller's identity, and a shared intermediary honouring a public scope would serve one principal's data to another. A nil receiver is a no-op.
func (*CacheableResult) TTL ¶ added in v1.0.0
func (r *CacheableResult) TTL() (int64, bool)
TTL returns the cache freshness hint in milliseconds and whether the server supplied one.
type CallToolParams ¶ added in v0.31.0
type CallToolParams struct {
Name string `json:"name"`
Arguments any `json:"arguments,omitempty"`
Meta *Meta `json:"_meta,omitempty"`
Task *TaskParams `json:"task,omitempty"`
MultiRoundTripParams
// RawArguments preserves the original JSON bytes for arguments when unmarshaled
// from a wire message. This avoids precision loss for integers above 2^53.
RawArguments json.RawMessage `json:"-"`
}
func (CallToolParams) MarshalJSON ¶ added in v0.56.0
func (p CallToolParams) MarshalJSON() ([]byte, error)
MarshalJSON re-emits preserved raw arguments when available.
func (*CallToolParams) UnmarshalJSON ¶ added in v0.56.0
func (p *CallToolParams) UnmarshalJSON(data []byte) error
UnmarshalJSON preserves the original arguments JSON while also populating Arguments.
type CallToolRequest ¶ added in v0.4.0
type CallToolRequest struct {
Request
Header http.Header `json:"-"` // HTTP headers from the original request
Params CallToolParams `json:"params"`
}
CallToolRequest is used by the client to invoke a tool provided by the server.
func (CallToolRequest) BindArguments ¶ added in v0.29.0
func (r CallToolRequest) BindArguments(target any) error
BindArguments unmarshals the Arguments into the provided struct This is useful for working with strongly-typed arguments
func (CallToolRequest) GetArguments ¶ added in v0.29.0
func (r CallToolRequest) GetArguments() map[string]any
GetArguments returns the Arguments as map[string]any for backward compatibility If Arguments is not a map, it returns an empty map
func (CallToolRequest) GetBool ¶ added in v0.29.0
func (r CallToolRequest) GetBool(key string, defaultValue bool) bool
GetBool returns a bool argument by key, or the default value if not found
func (CallToolRequest) GetBoolSlice ¶ added in v0.29.0
func (r CallToolRequest) GetBoolSlice(key string, defaultValue []bool) []bool
GetBoolSlice returns a bool slice argument by key, or the default value if not found
func (CallToolRequest) GetFloat ¶ added in v0.29.0
func (r CallToolRequest) GetFloat(key string, defaultValue float64) float64
GetFloat returns a float64 argument by key, or the default value if not found
func (CallToolRequest) GetFloatSlice ¶ added in v0.29.0
func (r CallToolRequest) GetFloatSlice(key string, defaultValue []float64) []float64
GetFloatSlice returns a float64 slice argument by key, or the default value if not found
func (CallToolRequest) GetInt ¶ added in v0.29.0
func (r CallToolRequest) GetInt(key string, defaultValue int) int
GetInt returns an int argument by key, or the default value if not found
func (CallToolRequest) GetIntSlice ¶ added in v0.29.0
func (r CallToolRequest) GetIntSlice(key string, defaultValue []int) []int
GetIntSlice returns an int slice argument by key, or the default value if not found
func (CallToolRequest) GetRawArguments ¶ added in v0.29.0
func (r CallToolRequest) GetRawArguments() any
GetRawArguments returns the original arguments payload when available. For JSON-RPC requests this is json.RawMessage; otherwise it falls back to Arguments.
func (CallToolRequest) GetString ¶ added in v0.29.0
func (r CallToolRequest) GetString(key string, defaultValue string) string
GetString returns a string argument by key, or the default value if not found
func (CallToolRequest) GetStringSlice ¶ added in v0.29.0
func (r CallToolRequest) GetStringSlice(key string, defaultValue []string) []string
GetStringSlice returns a string slice argument by key, or the default value if not found
func (CallToolRequest) RequireBool ¶ added in v0.29.0
func (r CallToolRequest) RequireBool(key string) (bool, error)
RequireBool returns a bool argument by key, or an error if not found or not convertible to bool
func (CallToolRequest) RequireBoolSlice ¶ added in v0.29.0
func (r CallToolRequest) RequireBoolSlice(key string) ([]bool, error)
RequireBoolSlice returns a bool slice argument by key, or an error if not found or not convertible to bool slice
func (CallToolRequest) RequireFloat ¶ added in v0.29.0
func (r CallToolRequest) RequireFloat(key string) (float64, error)
RequireFloat returns a float64 argument by key, or an error if not found or not convertible to float64
func (CallToolRequest) RequireFloatSlice ¶ added in v0.29.0
func (r CallToolRequest) RequireFloatSlice(key string) ([]float64, error)
RequireFloatSlice returns a float64 slice argument by key, or an error if not found or not convertible to float64 slice
func (CallToolRequest) RequireInt ¶ added in v0.29.0
func (r CallToolRequest) RequireInt(key string) (int, error)
RequireInt returns an int argument by key, or an error if not found or not convertible to int
func (CallToolRequest) RequireIntSlice ¶ added in v0.29.0
func (r CallToolRequest) RequireIntSlice(key string) ([]int, error)
RequireIntSlice returns an int slice argument by key, or an error if not found or not convertible to int slice
func (CallToolRequest) RequireString ¶ added in v0.29.0
func (r CallToolRequest) RequireString(key string) (string, error)
RequireString returns a string argument by key, or an error if not found or not a string
func (CallToolRequest) RequireStringSlice ¶ added in v0.29.0
func (r CallToolRequest) RequireStringSlice(key string) ([]string, error)
RequireStringSlice returns a string slice argument by key, or an error if not found or not convertible to string slice
type CallToolResult ¶
type CallToolResult struct {
Result
MultiRoundTripResult
Content []Content `json:"content"` // Can be TextContent, ImageContent, AudioContent, or EmbeddedResource
// Structured content returned as a JSON object in the structuredContent field of a result.
// For backwards compatibility, a tool that returns structured content SHOULD also return
// functionally equivalent unstructured content.
StructuredContent any `json:"structuredContent,omitempty"`
// RawStructuredContent preserves the original JSON bytes for structuredContent when
// unmarshaled from a wire message.
RawStructuredContent json.RawMessage `json:"-"`
// Whether the tool call ended in an error.
//
// If not set, this is assumed to be false (the call was successful).
IsError bool `json:"isError,omitempty"`
}
CallToolResult is the server's response to a tool call.
Any errors that originate from the tool SHOULD be reported inside the result object, with `isError` set to true, _not_ as an MCP protocol-level error response. Otherwise, the LLM would not be able to see that an error occurred and self-correct.
However, any errors in _finding_ the tool, an error indicating that the server does not support tool calls, or any other exceptional conditions, should be reported as an MCP error response.
func FormatNumberResult ¶ added in v0.5.1
func FormatNumberResult(value float64) *CallToolResult
FormatNumberResult formats a number as a tool result.
func NewToolResultAudio ¶ added in v0.27.0
func NewToolResultAudio(text, audioData, mimeType string) *CallToolResult
NewToolResultAudio creates a new CallToolResult with both text and audio content
func NewToolResultError ¶ added in v0.5.1
func NewToolResultError(text string) *CallToolResult
NewToolResultError creates a new CallToolResult with an error message. Any errors that originate from the tool SHOULD be reported inside the result object.
func NewToolResultErrorFromErr ¶ added in v0.21.0
func NewToolResultErrorFromErr(text string, err error) *CallToolResult
NewToolResultErrorFromErr creates a new CallToolResult with an error message. If an error is provided, its details will be appended to the text message. Any errors that originate from the tool SHOULD be reported inside the result object.
func NewToolResultErrorf ¶ added in v0.32.0
func NewToolResultErrorf(format string, a ...any) *CallToolResult
NewToolResultErrorf creates a new CallToolResult with an error message. The error message is formatted using the fmt package. Any errors that originate from the tool SHOULD be reported inside the result object.
func NewToolResultImage ¶ added in v0.5.1
func NewToolResultImage(text, imageData, mimeType string) *CallToolResult
NewToolResultImage creates a new CallToolResult with both text and image content
func NewToolResultJSON ¶ added in v0.40.0
func NewToolResultJSON[T any](data T) (*CallToolResult, error)
NewToolResultJSON creates a new CallToolResult with a JSON content.
func NewToolResultResource ¶ added in v0.5.1
func NewToolResultResource( text string, resource ResourceContents, ) *CallToolResult
NewToolResultResource creates a new CallToolResult with an embedded resource
func NewToolResultStructured ¶ added in v0.36.0
func NewToolResultStructured(structured any, fallbackText string) *CallToolResult
NewToolResultStructured creates a new CallToolResult with structured content. It includes both the structured content and a text representation for backward compatibility.
func NewToolResultStructuredOnly ¶ added in v0.36.0
func NewToolResultStructuredOnly(structured any) *CallToolResult
NewToolResultStructuredOnly creates a new CallToolResult with structured content and creates a JSON string fallback for backwards compatibility. This is useful when you want to provide structured data without any specific text fallback.
func NewToolResultText ¶ added in v0.5.1
func NewToolResultText(text string) *CallToolResult
NewToolResultText creates a new CallToolResult with a text content
func ParseCallToolResult ¶ added in v0.9.0
func ParseCallToolResult(rawMessage *json.RawMessage) (*CallToolResult, error)
func (CallToolResult) MarshalJSON ¶ added in v0.34.0
func (r CallToolResult) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for CallToolResult
func (*CallToolResult) NeedsInput ¶ added in v1.0.0
func (r *CallToolResult) NeedsInput() bool
NeedsInput reports whether the result asks the client for more input before the original request can complete.
func (*CallToolResult) UnmarshalJSON ¶ added in v0.4.0
func (r *CallToolResult) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for CallToolResult
type CancelTaskParams ¶ added in v0.44.0
type CancelTaskParams struct {
TaskId string `json:"taskId"`
}
type CancelTaskRequest ¶ added in v0.44.0
type CancelTaskRequest struct {
Request
Header http.Header `json:"-"`
Params CancelTaskParams `json:"params"`
}
CancelTaskRequest cancels an in-progress task.
type CancelTaskResult ¶ added in v0.44.0
CancelTaskResult returns the cancelled task state.
func NewCancelTaskResult ¶ added in v0.44.0
func NewCancelTaskResult(task Task) CancelTaskResult
NewCancelTaskResult creates a CancelTaskResult from a Task.
func ParseCancelTaskResult ¶ added in v0.47.0
func ParseCancelTaskResult(rawMessage *json.RawMessage) (*CancelTaskResult, error)
ParseCancelTaskResult parses a JSON message and converts it to a CancelTaskResult.
type CancelledNotification ¶ added in v0.4.0
type CancelledNotification struct {
Notification
Params CancelledNotificationParams `json:"params"`
}
CancelledNotification can be sent by either side to indicate that it is cancelling a previously-issued request.
The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.
This notification indicates that the result will be unused, so any associated processing SHOULD cease.
A client MUST NOT attempt to cancel its `initialize` request.
type CancelledNotificationParams ¶ added in v0.4.0
type CancelledNotificationParams struct {
// The ID of the request to cancel.
//
// This MUST correspond to the ID of a request previously issued
// in the same direction.
RequestId RequestId `json:"requestId"`
// An optional string describing the reason for the cancellation. This MAY
// be logged or presented to the user.
Reason string `json:"reason,omitempty"`
}
type ClientCapabilities ¶
type ClientCapabilities struct {
// Optional, present if the client is advertising extension support.
Extensions map[string]any `json:"extensions,omitempty"`
// Experimental, non-standard capabilities that the client supports.
Experimental map[string]any `json:"experimental,omitempty"`
// Present if the client supports listing roots.
Roots *struct {
// Whether the client supports notifications for changes to the roots list.
ListChanged bool `json:"listChanged,omitempty"`
} `json:"roots,omitempty"`
// Present if the client supports sampling from an LLM.
Sampling *SamplingCapability `json:"sampling,omitempty"`
// Present if the client supports elicitation requests from the server.
Elicitation *ElicitationCapability `json:"elicitation,omitempty"`
// Present if the client supports task-based execution.
Tasks *TasksCapability `json:"tasks,omitempty"`
}
ClientCapabilities represents capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.
type ClientNotification ¶ added in v0.4.0
type ClientNotification any
ClientNotification represents any notification that can be sent from client to server.
type ClientRequest ¶ added in v0.4.0
type ClientRequest any
ClientRequest represents any request that can be sent from client to server.
type ClientResult ¶ added in v0.4.0
type ClientResult any
ClientResult represents any result that can be sent from client to server.
type CompleteArgument ¶
type CompleteArgument struct {
// The name of the argument
Name string `json:"name"`
// The value of the argument to use for completion matching.
Value string `json:"value"`
}
CompleteArgument is an argument to a completion request
type CompleteContext ¶ added in v0.44.0
CompleteContext is the context about already-resolved arguments
type CompleteParams ¶ added in v0.31.0
type CompleteParams struct {
Ref any `json:"ref"` // Can be PromptReference or ResourceReference
Argument CompleteArgument `json:"argument"`
Context CompleteContext `json:"context"`
}
CompleteParams are the parameters for a completion/complete request
func (*CompleteParams) UnmarshalJSON ¶ added in v0.44.0
func (p *CompleteParams) UnmarshalJSON(data []byte) error
type CompleteRequest ¶ added in v0.4.0
type CompleteRequest struct {
Request
Params CompleteParams `json:"params"`
Header http.Header `json:"-"`
}
CompleteRequest is a request from the client to the server, to ask for completion options.
type CompleteResult ¶
type CompleteResult struct {
Result
Completion Completion `json:"completion"`
}
CompleteResult is the server's response to a completion/complete request
type Completion ¶
type Completion struct {
// An array of completion values. Must not exceed 100 items.
Values []string `json:"values"`
// The total number of completion options available. This can exceed the
// number of values actually sent in the response.
Total int `json:"total,omitempty"`
// Indicates whether there are additional completion options beyond those
// provided in the current response, even if the exact total is unknown.
HasMore bool `json:"hasMore,omitempty"`
}
Completion is the server's response to a completion/complete request
type Content ¶
type Content interface {
// contains filtered or unexported methods
}
func ParseContent ¶ added in v0.9.0
ParseContent parses a generic map into a strongly-typed Content value. It extracts annotations and _meta fields from the map and sets them on the returned content type.
func UnmarshalContent ¶ added in v0.34.0
UnmarshalContent implements custom JSON unmarshaling for Content interface
type CreateMessageParams ¶ added in v0.31.0
type CreateMessageParams struct {
Messages []SamplingMessage `json:"messages"`
ModelPreferences *ModelPreferences `json:"modelPreferences,omitempty"`
SystemPrompt string `json:"systemPrompt,omitempty"`
IncludeContext string `json:"includeContext,omitempty"`
Temperature float64 `json:"temperature,omitempty"`
MaxTokens int `json:"maxTokens"`
StopSequences []string `json:"stopSequences,omitempty"`
Metadata any `json:"metadata,omitempty"`
// Tools the model may use during generation.
//
// Per the 2025-11-25 spec, the client MUST return an error if this field
// is provided but ClientCapabilities.Sampling.Tools is not declared.
Tools []Tool `json:"tools,omitempty"`
// ToolChoice controls how the model uses tools during generation.
//
// Per the 2025-11-25 spec, the client MUST return an error if this field
// is provided but ClientCapabilities.Sampling.Tools is not declared.
// When omitted the client defaults to {Mode: ToolChoiceModeAuto}.
ToolChoice *ToolChoice `json:"toolChoice,omitempty"`
}
type CreateMessageRequest ¶ added in v0.4.0
type CreateMessageRequest struct {
Request
CreateMessageParams `json:"params"`
}
CreateMessageRequest is a request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.
type CreateMessageResult ¶ added in v0.4.0
type CreateMessageResult struct {
Result
SamplingMessage
// The name of the model that generated the message.
Model string `json:"model"`
// The reason why sampling stopped, if known.
StopReason string `json:"stopReason,omitempty"`
}
CreateMessageResult is the client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it.
type CreateTaskResult ¶ added in v0.44.0
type CreateTaskResult struct {
Result
Task Task `json:"task"`
Content []Content `json:"-"`
StructuredContent any `json:"-"`
IsError bool `json:"-"`
}
CreateTaskResult is returned immediately when a task-augmented request is accepted. It contains task metadata rather than the actual operation result.
func NewCreateTaskResult ¶ added in v0.44.0
func NewCreateTaskResult(task Task) CreateTaskResult
NewCreateTaskResult creates a CreateTaskResult with the given task.
type Cursor ¶ added in v0.4.0
type Cursor string
Cursor is an opaque token used to represent a cursor for pagination.
type DiscoverParams ¶ added in v1.0.0
type DiscoverParams struct {
// Meta carries the per-request protocol metadata.
Meta *Meta `json:"_meta,omitempty"`
}
DiscoverParams are the parameters of a server/discover request. Like every modern request, the protocol version, client identity, and client capabilities travel in Meta.
type DiscoverRequest ¶ added in v1.0.0
type DiscoverRequest struct {
Request
Header http.Header `json:"-"`
Params DiscoverParams `json:"params,omitzero"`
}
DiscoverRequest is sent by a client to learn a server's supported protocol versions, capabilities, and identity without performing the legacy initialize handshake (SEP-2575).
Servers implementing protocol version 2026-07-28 or later MUST support this method. Clients MAY call it before any other request, or skip it entirely and handle UnsupportedProtocolVersionError inline.
type DiscoverResult ¶ added in v1.0.0
type DiscoverResult struct {
CacheableResult
// SupportedVersions lists the MCP protocol versions this server supports,
// newest first. The client should choose one for subsequent requests.
SupportedVersions []string `json:"supportedVersions"`
// Capabilities describes the server's capabilities.
Capabilities ServerCapabilities `json:"capabilities"`
// Instructions is natural-language guidance describing the server and its
// features, for inclusion in an LLM system prompt.
Instructions string `json:"instructions,omitempty"`
}
DiscoverResult is a server's response to a server/discover request.
type ElicitationCapability ¶ added in v0.44.0
type ElicitationCapability struct {
Form *struct{} `json:"form,omitempty"` // Supports form mode
URL *struct{} `json:"url,omitempty"` // Supports URL mode
}
ElicitationCapability represents the elicitation capabilities of a client or server.
type ElicitationParams ¶ added in v0.40.0
type ElicitationParams struct {
Meta *Meta `json:"_meta,omitempty"`
// Mode specifies the type of elicitation: "form" or "url". Defaults to "form".
Mode string `json:"mode,omitempty"`
// A human-readable message explaining what information is being requested and why.
Message string `json:"message"`
// A JSON Schema defining the expected structure of the user's response.
RequestedSchema any `json:"requestedSchema,omitempty"`
// ElicitationID is a unique identifier for the elicitation request.
ElicitationID string `json:"elicitationId,omitempty"`
// URL is the URL to be opened by the user.
URL string `json:"url,omitempty"`
}
ElicitationParams contains the parameters for an elicitation request.
func (ElicitationParams) Validate ¶ added in v0.44.0
func (p ElicitationParams) Validate() error
Validate checks if the elicitation parameters are valid.
type ElicitationRequest ¶ added in v0.40.0
type ElicitationRequest struct {
Request
Params ElicitationParams `json:"params"`
}
ElicitationRequest is a request from the server to the client to request additional information from the user during an interaction.
type ElicitationResponse ¶ added in v0.40.0
type ElicitationResponse struct {
// Action indicates whether the user accepted, declined, or cancelled.
Action ElicitationResponseAction `json:"action"`
// Content contains the user's response data if they accepted.
// Should conform to the requestedSchema from the ElicitationRequest.
Content any `json:"content,omitempty"`
}
ElicitationResponse represents the user's response to an elicitation request.
type ElicitationResponseAction ¶ added in v0.40.0
type ElicitationResponseAction string
ElicitationResponseAction indicates how the user responded to an elicitation request.
const ( // ElicitationResponseActionAccept indicates the user provided the requested information. ElicitationResponseActionAccept ElicitationResponseAction = "accept" // ElicitationResponseActionDecline indicates the user explicitly declined to provide information. ElicitationResponseActionDecline ElicitationResponseAction = "decline" // ElicitationResponseActionCancel indicates the user cancelled without making a choice. ElicitationResponseActionCancel ElicitationResponseAction = "cancel" )
type ElicitationResult ¶ added in v0.40.0
type ElicitationResult struct {
Result
ElicitationResponse
}
ElicitationResult represents the result of an elicitation request.
type EmbeddedResource ¶
type EmbeddedResource struct {
Annotated
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
Type string `json:"type"`
Resource ResourceContents `json:"resource"`
}
EmbeddedResource represents the contents of a resource, embedded into a prompt or tool call result.
It is up to the client how best to render embedded resources for the benefit of the LLM and/or the user.
func AsEmbeddedResource ¶ added in v0.5.0
func AsEmbeddedResource(content any) (*EmbeddedResource, bool)
AsEmbeddedResource attempts to cast the given interface to EmbeddedResource
func NewEmbeddedResource ¶ added in v0.5.0
func NewEmbeddedResource(resource ResourceContents) EmbeddedResource
NewEmbeddedResource creates an embedded resource.
func (*EmbeddedResource) UnmarshalJSON ¶ added in v0.4.0
func (e *EmbeddedResource) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for EmbeddedResource to handle the nested ResourceContents interface.
type EmptyResult ¶ added in v0.5.0
type EmptyResult Result
EmptyResult represents a response that indicates success but carries no data.
type GetPromptParams ¶ added in v0.31.0
type GetPromptParams struct {
// The name of the prompt or prompt template.
Name string `json:"name"`
// Arguments to use for templating the prompt.
Arguments map[string]string `json:"arguments,omitempty"`
// Meta carries protocol-level metadata (e.g. W3C traceparent, progressToken).
Meta *Meta `json:"_meta,omitempty"`
MultiRoundTripParams
}
GetPromptParams contains parameters for a prompts/get request.
type GetPromptRequest ¶ added in v0.4.0
type GetPromptRequest struct {
Request
Params GetPromptParams `json:"params"`
Header http.Header `json:"-"`
}
GetPromptRequest is used by the client to get a prompt provided by the server.
type GetPromptResult ¶
type GetPromptResult struct {
Result
MultiRoundTripResult
// An optional description for the prompt.
Description string `json:"description,omitempty"`
Messages []PromptMessage `json:"messages"`
}
GetPromptResult is the server's response to a prompts/get request from the client.
func NewGetPromptResult ¶ added in v0.5.1
func NewGetPromptResult( description string, messages []PromptMessage, ) *GetPromptResult
NewGetPromptResult creates a new GetPromptResult
func ParseGetPromptResult ¶ added in v0.9.0
func ParseGetPromptResult(rawMessage *json.RawMessage) (*GetPromptResult, error)
func (*GetPromptResult) NeedsInput ¶ added in v1.0.0
func (r *GetPromptResult) NeedsInput() bool
NeedsInput reports whether the result asks the client for more input before the original request can complete.
type GetTaskParams ¶ added in v0.44.0
type GetTaskParams struct {
TaskId string `json:"taskId"`
}
type GetTaskRequest ¶ added in v0.44.0
type GetTaskRequest struct {
Request
Header http.Header `json:"-"`
Params GetTaskParams `json:"params"`
}
GetTaskRequest retrieves the current status of a task.
type GetTaskResult ¶ added in v0.44.0
GetTaskResult returns the current state of a task.
func NewGetTaskResult ¶ added in v0.44.0
func NewGetTaskResult(task Task) GetTaskResult
NewGetTaskResult creates a GetTaskResult from a Task.
func ParseGetTaskResult ¶ added in v0.47.0
func ParseGetTaskResult(rawMessage *json.RawMessage) (*GetTaskResult, error)
ParseGetTaskResult parses a JSON message and converts it to a GetTaskResult.
type HeaderMismatchError ¶ added in v1.0.0
type HeaderMismatchError struct {
// Header is the offending header name.
Header string
// Reason describes the mismatch.
Reason string
}
HeaderMismatchError is returned when a standard MCP HTTP header is missing, malformed, or disagrees with the corresponding value in the request body (SEP-2243).
func (HeaderMismatchError) Error ¶ added in v1.0.0
func (e HeaderMismatchError) Error() string
func (HeaderMismatchError) Is ¶ added in v1.0.0
func (e HeaderMismatchError) Is(target error) bool
Is implements the errors.Is interface for better error handling.
type Icon ¶ added in v0.44.0
type Icon struct {
// URI pointing to the icon resource (HTTPS URL or data URI)
Src string `json:"src"`
// Optional MIME type (e.g., "image/png", "image/svg+xml")
MIMEType string `json:"mimeType,omitempty"`
// Optional size specifications (e.g., ["48x48"], ["any"] for SVG)
Sizes []string `json:"sizes,omitempty"`
// Theme is an optional specifier for the background theme this icon is designed for.
// Use IconThemeLight for light backgrounds or IconThemeDark for dark backgrounds.
Theme IconTheme `json:"theme,omitempty"`
}
Icon represents a visual identifier for MCP entities.
Security considerations:
- Clients MUST support at least image/png and image/jpeg MIME types
- Clients SHOULD support image/svg+xml and image/webp
- Icons should be treated as untrusted input
- URI scheme validation (HTTPS or data URI only)
- Size/dimension limits to prevent resource exhaustion
type IconTheme ¶ added in v0.54.0
type IconTheme string
IconTheme is the background theme an icon is designed to be displayed on.
type ImageContent ¶
type ImageContent struct {
Annotated
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
Type string `json:"type"` // Must be "image"
// The base64-encoded image data.
Data string `json:"data"`
// The MIME type of the image. Different providers may support different image types.
MIMEType string `json:"mimeType"`
}
ImageContent represents an image provided to or from an LLM. It must have Type set to "image".
func AsImageContent ¶ added in v0.5.0
func AsImageContent(content any) (*ImageContent, bool)
AsImageContent attempts to cast the given interface to ImageContent
func NewImageContent ¶ added in v0.5.0
func NewImageContent(data, mimeType string) ImageContent
NewImageContent creates image content.
type Implementation ¶
type Implementation struct {
Name string `json:"name"`
Version string `json:"version"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
WebsiteURL string `json:"websiteUrl,omitempty"`
// Icons provides visual identifiers for the implementation
Icons []Icon `json:"icons,omitempty"`
}
Implementation describes the name and version of an MCP implementation.
type InitializeParams ¶ added in v0.31.0
type InitializeParams struct {
// The latest version of the Model Context Protocol that the client supports.
// The client MAY decide to support older versions as well.
ProtocolVersion string `json:"protocolVersion"`
Capabilities ClientCapabilities `json:"capabilities"`
ClientInfo Implementation `json:"clientInfo"`
}
type InitializeRequest ¶ added in v0.4.0
type InitializeRequest struct {
Request
Params InitializeParams `json:"params"`
Header http.Header `json:"-"`
}
InitializeRequest is sent from the client to the server when it first connects, asking it to begin initialization.
type InitializeResult ¶
type InitializeResult struct {
Result
// The version of the Model Context Protocol that the server wants to use.
// This may not match the version that the client requested. If the client cannot
// support this version, it MUST disconnect.
ProtocolVersion string `json:"protocolVersion"`
Capabilities ServerCapabilities `json:"capabilities"`
ServerInfo Implementation `json:"serverInfo"`
// Instructions describing how to use the server and its features.
//
// This can be used by clients to improve the LLM's understanding of
// available tools, resources, etc. It can be thought of like a "hint" to the model.
// For example, this information MAY be added to the system prompt.
Instructions string `json:"instructions,omitempty"`
}
InitializeResult is sent after receiving an initialize request from the client.
func NewInitializeResult ¶ added in v0.5.1
func NewInitializeResult( protocolVersion string, capabilities ServerCapabilities, serverInfo Implementation, instructions string, ) *InitializeResult
NewInitializeResult creates a new InitializeResult
type InitializedNotification ¶ added in v0.4.0
type InitializedNotification struct {
Notification
}
InitializedNotification is sent from the client to the server after initialization has finished.
type InputRequest ¶ added in v1.0.0
type InputRequest struct {
// Method is the JSON-RPC method of the embedded request: one of
// [MethodElicitationCreate], [MethodSamplingCreateMessage], or
// [MethodListRoots].
Method MCPMethod `json:"method"`
// Elicitation is set when Method is elicitation/create.
Elicitation *ElicitationParams `json:"-"`
// Sampling is set when Method is sampling/createMessage.
Sampling *CreateMessageParams `json:"-"`
// Roots is set when Method is roots/list. The roots/list request takes no
// parameters, so this is an empty struct used only as a presence marker.
Roots *ListRootsParams `json:"-"`
}
InputRequest is a single server-initiated request embedded in an InputRequiredResult. Exactly one of its fields is populated, selected by the Method field.
func NewElicitationInputRequest ¶ added in v1.0.0
func NewElicitationInputRequest(params ElicitationParams) InputRequest
NewElicitationInputRequest builds an input request asking the client to elicit information from the user.
func NewRootsInputRequest ¶ added in v1.0.0
func NewRootsInputRequest() InputRequest
NewRootsInputRequest builds an input request asking the client for its list of roots.
func NewSamplingInputRequest ¶ added in v1.0.0
func NewSamplingInputRequest(params CreateMessageParams) InputRequest
NewSamplingInputRequest builds an input request asking the client to sample from an LLM.
func (InputRequest) MarshalJSON ¶ added in v1.0.0
func (r InputRequest) MarshalJSON() ([]byte, error)
MarshalJSON encodes the input request as a JSON-RPC request object carrying the method and its parameters.
func (*InputRequest) UnmarshalJSON ¶ added in v1.0.0
func (r *InputRequest) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a JSON-RPC request object into the matching variant.
type InputRequests ¶ added in v1.0.0
type InputRequests map[string]InputRequest
InputRequests maps server-assigned identifiers to the requests a client must fulfil before retrying the original call.
type InputRequiredResult ¶ added in v1.0.0
type InputRequiredResult struct {
Result
MultiRoundTripResult
}
InputRequiredResult is returned by a server to indicate that it needs additional input before it can complete a request.
At least one of InputRequests or RequestState must be present. An empty InputRequests map with a RequestState is a load-shedding signal: the client should retry the request unchanged, echoing the state back.
func NewInputRequiredResult ¶ added in v1.0.0
func NewInputRequiredResult(requests InputRequests, requestState string) *InputRequiredResult
NewInputRequiredResult builds a result asking the client for more input before the request can be completed. requestState is echoed back by the client on retry and may be empty.
func (*InputRequiredResult) NeedsInput ¶ added in v1.0.0
func (r *InputRequiredResult) NeedsInput() bool
NeedsInput reports whether the result asks the client for more input before the original request can complete.
type InputResponse ¶ added in v1.0.0
type InputResponse struct {
// Elicitation answers an elicitation/create input request.
Elicitation *ElicitationResult `json:"-"`
// Sampling answers a sampling/createMessage input request.
Sampling *CreateMessageResult `json:"-"`
// Roots answers a roots/list input request.
Roots *ListRootsResult `json:"-"`
// contains filtered or unexported fields
}
InputResponse is a client's answer to a single InputRequest. Exactly one of its fields is populated, matching the method of the request it answers.
func NewElicitationInputResponse ¶ added in v1.0.0
func NewElicitationInputResponse(result ElicitationResult) InputResponse
NewElicitationInputResponse builds an input response carrying an elicitation result.
func NewRootsInputResponse ¶ added in v1.0.0
func NewRootsInputResponse(result ListRootsResult) InputResponse
NewRootsInputResponse builds an input response carrying a roots list.
func NewSamplingInputResponse ¶ added in v1.0.0
func NewSamplingInputResponse(result CreateMessageResult) InputResponse
NewSamplingInputResponse builds an input response carrying a sampling result.
func (*InputResponse) DecodeFor ¶ added in v1.0.0
func (r *InputResponse) DecodeFor(method MCPMethod) error
DecodeFor resolves the response against the method of the request it answers, populating the matching variant.
func (InputResponse) MarshalJSON ¶ added in v1.0.0
func (r InputResponse) MarshalJSON() ([]byte, error)
MarshalJSON encodes whichever variant is populated.
func (*InputResponse) UnmarshalJSON ¶ added in v1.0.0
func (r *InputResponse) UnmarshalJSON(data []byte) error
UnmarshalJSON stores the raw payload. Input responses are a union whose variant is determined by the method of the corresponding InputRequest, which is not present in the response itself, so decoding into a concrete type is deferred to InputResponse.DecodeFor.
type InputResponses ¶ added in v1.0.0
type InputResponses map[string]InputResponse
InputResponses maps the identifiers from an InputRequests map to the client's answers.
func (InputResponses) DecodeFor ¶ added in v1.0.0
func (r InputResponses) DecodeFor(requests InputRequests) error
DecodeFor resolves every response in the map against the methods of the corresponding requests.
type JSONRPCError ¶ added in v0.4.0
type JSONRPCError struct {
JSONRPC string `json:"jsonrpc"`
ID RequestId `json:"id"`
Error JSONRPCErrorDetails `json:"error"`
}
JSONRPCError represents a non-successful (error) response to a request.
func NewJSONRPCError ¶ added in v0.5.0
func NewJSONRPCError( id RequestId, code int, message string, data any, ) JSONRPCError
NewJSONRPCError creates a new JSONRPCResponse with the given id, code, and message
type JSONRPCErrorDetails ¶ added in v0.41.0
type JSONRPCErrorDetails struct {
// The error type that occurred.
Code int `json:"code"`
// A short description of the error. The message SHOULD be limited
// to a concise single sentence.
Message string `json:"message"`
// Additional information about the error. The value of this member
// is defined by the sender (e.g. detailed error information, nested errors etc.).
Data any `json:"data,omitempty"`
}
JSONRPCErrorDetails represents a JSON-RPC error for Go error handling. This is separate from the JSONRPCError type which represents the full JSON-RPC error response structure.
func NewJSONRPCErrorDetails ¶ added in v0.41.0
func NewJSONRPCErrorDetails(code int, message string, data any) JSONRPCErrorDetails
NewJSONRPCErrorDetails creates a new JSONRPCErrorDetails with the given code, message, and data.
func (*JSONRPCErrorDetails) AsError ¶ added in v0.41.0
func (e *JSONRPCErrorDetails) AsError() error
AsError maps JSONRPCErrorDetails to a Go error. Returns sentinel errors wrapped with custom messages for known codes. Defaults to a generic error with the original message when the code is not mapped.
func (*JSONRPCErrorDetails) UnmarshalJSON ¶ added in v0.50.0
func (e *JSONRPCErrorDetails) UnmarshalJSON(data []byte) error
UnmarshalJSON handles both the standard JSON-RPC error object ({"code": -32600, "message": "..."}) and non-compliant servers that return the error as a plain string (e.g. "cursor_invalid").
type JSONRPCMessage ¶ added in v0.4.0
type JSONRPCMessage any
JSONRPCMessage represents either a JSONRPCRequest, JSONRPCNotification, JSONRPCResponse, or JSONRPCError
type JSONRPCNotification ¶ added in v0.4.0
type JSONRPCNotification struct {
JSONRPC string `json:"jsonrpc"`
Notification
}
JSONRPCNotification represents a notification which does not expect a response.
func NewElicitationCompleteNotification ¶ added in v0.44.0
func NewElicitationCompleteNotification(elicitationID string) JSONRPCNotification
NewElicitationCompleteNotification creates a new elicitation complete notification.
type JSONRPCRequest ¶ added in v0.4.0
type JSONRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
ID RequestId `json:"id"`
Params any `json:"params,omitempty"`
Request
}
JSONRPCRequest represents a request that expects a response.
type JSONRPCResponse ¶ added in v0.4.0
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID RequestId `json:"id"`
Result any `json:"result"`
}
JSONRPCResponse represents a successful (non-error) response to a request.
func NewJSONRPCResponse ¶ added in v0.5.0
func NewJSONRPCResponse(id RequestId, result Result) JSONRPCResponse
NewJSONRPCResponse creates a new JSONRPCResponse with the given id and result. NOTE: This function expects a Result struct, but JSONRPCResponse.Result is typed as `any`. The Result struct wraps the actual result data with optional metadata. For direct result assignment, use NewJSONRPCResultResponse instead.
func NewJSONRPCResultResponse ¶ added in v0.41.0
func NewJSONRPCResultResponse(id RequestId, result any) JSONRPCResponse
NewJSONRPCResultResponse creates a new JSONRPCResponse with the given id and result. This function accepts any type for the result, matching the JSONRPCResponse.Result field type.
type ListPromptsRequest ¶ added in v0.4.0
type ListPromptsRequest struct {
PaginatedRequest
Header http.Header `json:"-"`
}
ListPromptsRequest is sent from the client to request a list of prompts and prompt templates the server has.
type ListPromptsResult ¶
type ListPromptsResult struct {
PaginatedResult
Prompts []Prompt `json:"prompts"`
}
ListPromptsResult is the server's response to a prompts/list request from the client.
func NewListPromptsResult ¶ added in v0.5.1
func NewListPromptsResult( prompts []Prompt, nextCursor Cursor, ) *ListPromptsResult
NewListPromptsResult creates a new ListPromptsResult
type ListResourceTemplatesRequest ¶ added in v0.4.0
type ListResourceTemplatesRequest struct {
PaginatedRequest
Header http.Header `json:"-"`
}
ListResourceTemplatesRequest is sent from the client to request a list of resource templates the server has.
type ListResourceTemplatesResult ¶ added in v0.4.0
type ListResourceTemplatesResult struct {
PaginatedResult
ResourceTemplates []ResourceTemplate `json:"resourceTemplates"`
}
ListResourceTemplatesResult is the server's response to a resources/templates/list request from the client.
func NewListResourceTemplatesResult ¶ added in v0.5.1
func NewListResourceTemplatesResult( templates []ResourceTemplate, nextCursor Cursor, ) *ListResourceTemplatesResult
NewListResourceTemplatesResult creates a new ListResourceTemplatesResult
type ListResourcesRequest ¶ added in v0.4.0
type ListResourcesRequest struct {
PaginatedRequest
Header http.Header `json:"-"`
}
ListResourcesRequest is sent from the client to request a list of resources the server has.
type ListResourcesResult ¶
type ListResourcesResult struct {
PaginatedResult
Resources []Resource `json:"resources"`
}
ListResourcesResult is the server's response to a resources/list request from the client.
func NewListResourcesResult ¶ added in v0.5.1
func NewListResourcesResult( resources []Resource, nextCursor Cursor, ) *ListResourcesResult
NewListResourcesResult creates a new ListResourcesResult
type ListRootsParams ¶ added in v1.0.0
type ListRootsParams struct{}
ListRootsParams are the (empty) parameters of a roots/list request. It exists so that InputRequest can represent a roots/list request uniformly.
type ListRootsRequest ¶ added in v0.4.0
type ListRootsRequest struct {
Request
}
ListRootsRequest is sent from the server to request a list of root URIs from the client. Roots allow servers to ask for specific directories or files to operate on. A common example for roots is providing a set of repositories or directories a server should operate on.
This request is typically used when the server needs to understand the file system structure or access specific locations that the client has permission to read from.
type ListRootsResult ¶ added in v0.4.0
ListRootsResult is the client's response to a roots/list request from the server. This result contains an array of Root objects, each representing a root directory or file that the server can operate on.
type ListTasksRequest ¶ added in v0.44.0
type ListTasksRequest struct {
PaginatedRequest
Header http.Header `json:"-"`
}
ListTasksRequest retrieves a paginated list of tasks.
type ListTasksResult ¶ added in v0.44.0
type ListTasksResult struct {
PaginatedResult
Tasks []Task `json:"tasks"`
}
ListTasksResult returns a list of tasks.
func NewListTasksResult ¶ added in v0.44.0
func NewListTasksResult(tasks []Task) ListTasksResult
NewListTasksResult creates a ListTasksResult with the given tasks.
func ParseListTasksResult ¶ added in v0.47.0
func ParseListTasksResult(rawMessage *json.RawMessage) (*ListTasksResult, error)
ParseListTasksResult parses a JSON message and converts it to a ListTasksResult.
type ListToolsRequest ¶ added in v0.4.0
type ListToolsRequest struct {
PaginatedRequest
Header http.Header `json:"-"`
}
ListToolsRequest is sent from the client to request a list of tools the server has.
type ListToolsResult ¶
type ListToolsResult struct {
PaginatedResult
Tools []Tool `json:"tools"`
}
ListToolsResult is the server's response to a tools/list request from the client.
func NewListToolsResult ¶ added in v0.5.1
func NewListToolsResult(tools []Tool, nextCursor Cursor) *ListToolsResult
NewListToolsResult creates a new ListToolsResult
type LoggingLevel ¶
type LoggingLevel string
LoggingLevel represents the severity of a log message.
These map to syslog message severities, as specified in RFC-5424: https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1
const ( LoggingLevelDebug LoggingLevel = "debug" LoggingLevelInfo LoggingLevel = "info" LoggingLevelNotice LoggingLevel = "notice" LoggingLevelWarning LoggingLevel = "warning" LoggingLevelError LoggingLevel = "error" LoggingLevelCritical LoggingLevel = "critical" LoggingLevelAlert LoggingLevel = "alert" LoggingLevelEmergency LoggingLevel = "emergency" )
func (LoggingLevel) ShouldSendTo ¶ added in v0.34.0
func (l LoggingLevel) ShouldSendTo(minLevel LoggingLevel) bool
type LoggingMessageNotification ¶ added in v0.4.0
type LoggingMessageNotification struct {
Notification
Params LoggingMessageNotificationParams `json:"params"`
}
LoggingMessageNotification is a notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.
func NewLoggingMessageNotification ¶ added in v0.5.0
func NewLoggingMessageNotification( level LoggingLevel, logger string, data any, ) LoggingMessageNotification
NewLoggingMessageNotification creates a logging message notification.
type LoggingMessageNotificationParams ¶ added in v0.4.0
type LoggingMessageNotificationParams struct {
// The severity of this log message.
Level LoggingLevel `json:"level"`
// An optional name of the logger issuing this message.
Logger string `json:"logger,omitempty"`
// The data to be logged, such as a string message or an object. Any JSON
// serializable type is allowed here.
Data any `json:"data"`
}
type MCPMethod ¶ added in v0.16.0
type MCPMethod string
const ( // MethodInitialize initiates connection and negotiates protocol capabilities. // https://modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization // // Removed in protocol version 2026-07-28 (SEP-2575), which carries the // protocol version, client identity, and client capabilities in each // request's _meta instead. Servers reject it on requests declaring that // version or later; use [MethodServerDiscover] there. MethodInitialize MCPMethod = "initialize" // MethodPing verifies connection liveness between client and server. // https://modelcontextprotocol.io/specification/2024-11-05/basic/utilities/ping/ // // Removed in protocol version 2026-07-28 (SEP-2575), where liveness is a // transport concern. Servers reject it on requests declaring that version // or later. MethodPing MCPMethod = "ping" // MethodResourcesList lists all available server resources. // https://modelcontextprotocol.io/specification/2024-11-05/server/resources/ MethodResourcesList MCPMethod = "resources/list" // MethodResourcesTemplatesList provides URI templates for constructing resource URIs. // https://modelcontextprotocol.io/specification/2024-11-05/server/resources/ MethodResourcesTemplatesList MCPMethod = "resources/templates/list" // MethodResourcesRead retrieves content of a specific resource by URI. // https://modelcontextprotocol.io/specification/2024-11-05/server/resources/ MethodResourcesRead MCPMethod = "resources/read" // MethodResourcesSubscribe subscribes the client to updates for a resource. // https://modelcontextprotocol.io/specification/2025-11-25/server/resources // // Removed in protocol version 2026-07-28 (SEP-2575). Use the // ResourceSubscriptions field of a [MethodSubscriptionsListen] request // there. MethodResourcesSubscribe MCPMethod = "resources/subscribe" // MethodResourcesUnsubscribe cancels a previous resources/subscribe request. // https://modelcontextprotocol.io/specification/2025-11-25/server/resources // // Removed in protocol version 2026-07-28 (SEP-2575). Close the // [MethodSubscriptionsListen] stream instead. MethodResourcesUnsubscribe MCPMethod = "resources/unsubscribe" // MethodPromptsList lists all available prompt templates. // https://modelcontextprotocol.io/specification/2024-11-05/server/prompts/ MethodPromptsList MCPMethod = "prompts/list" // MethodPromptsGet retrieves a specific prompt template with filled parameters. // https://modelcontextprotocol.io/specification/2024-11-05/server/prompts/ MethodPromptsGet MCPMethod = "prompts/get" // MethodToolsList lists all available executable tools. // https://modelcontextprotocol.io/specification/2024-11-05/server/tools/ MethodToolsList MCPMethod = "tools/list" // MethodToolsCall invokes a specific tool with provided parameters. // https://modelcontextprotocol.io/specification/2024-11-05/server/tools/ MethodToolsCall MCPMethod = "tools/call" // MethodSetLogLevel configures the minimum log level for client // https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/logging // // Removed in protocol version 2026-07-28 (SEP-2575). Set [MetaKeyLogLevel] // in each request's _meta instead. MethodSetLogLevel MCPMethod = "logging/setLevel" // MethodElicitationCreate requests additional information from the user during interactions. // https://modelcontextprotocol.io/docs/concepts/elicitation MethodElicitationCreate MCPMethod = "elicitation/create" // MethodNotificationElicitationComplete notifies when a URL mode elicitation completes. MethodNotificationElicitationComplete MCPMethod = "notifications/elicitation/complete" // MethodListRoots requests roots list from the client during interactions. // https://modelcontextprotocol.io/specification/2025-06-18/client/roots MethodListRoots MCPMethod = "roots/list" // MethodTasksGet retrieves the current status of a task. // https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks MethodTasksGet MCPMethod = "tasks/get" // MethodTasksList lists all tasks for the current session. // https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks MethodTasksList MCPMethod = "tasks/list" // MethodTasksResult retrieves the result of a completed task. // https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks MethodTasksResult MCPMethod = "tasks/result" // MethodTasksCancel cancels an in-progress task. // https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks MethodTasksCancel MCPMethod = "tasks/cancel" // MethodNotificationInitialized indicates that the client completed initialization. // https://modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization MethodNotificationInitialized MCPMethod = "notifications/initialized" // MethodNotificationCancelled cancels an in-flight request. // https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation MethodNotificationCancelled MCPMethod = "notifications/cancelled" // MethodNotificationProgress reports progress for a long-running request. // https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/progress MethodNotificationProgress MCPMethod = "notifications/progress" // MethodNotificationMessage is a server-pushed log message. // https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/logging MethodNotificationMessage MCPMethod = "notifications/message" // MethodNotificationResourcesListChanged notifies when the list of available resources changes. // https://modelcontextprotocol.io/specification/2025-03-26/server/resources#list-changed-notification MethodNotificationResourcesListChanged = "notifications/resources/list_changed" MethodNotificationResourceUpdated = "notifications/resources/updated" // MethodNotificationPromptsListChanged notifies when the list of available prompt templates changes. // https://modelcontextprotocol.io/specification/2025-03-26/server/prompts#list-changed-notification MethodNotificationPromptsListChanged = "notifications/prompts/list_changed" // MethodNotificationToolsListChanged notifies when the list of available tools changes. // https://modelcontextprotocol.io/specification/2025-06-18/server/tools#list-changed-notification MethodNotificationToolsListChanged = "notifications/tools/list_changed" // MethodNotificationRootsListChanged notifies when the list of available roots changes. // https://modelcontextprotocol.io/specification/2025-06-18/client/roots#root-list-changes MethodNotificationRootsListChanged = "notifications/roots/list_changed" // MethodNotificationTasksStatus notifies when a task's status changes. // https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks MethodNotificationTasksStatus = "notifications/tasks/status" // MethodCompletionComplete returns completion suggestions for a given argument // https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/completion MethodCompletionComplete MCPMethod = "completion/complete" // MethodServerDiscover advertises the server's supported protocol versions, // capabilities, and identity. Servers implementing protocol version // 2026-07-28 or later MUST support it; it replaces the initialize handshake. // https://modelcontextprotocol.io/specification/2026-07-28/server/discover MethodServerDiscover MCPMethod = "server/discover" // MethodSubscriptionsListen opens a long-lived stream for server-to-client // notifications. It replaces the HTTP GET endpoint and the // resources/subscribe and resources/unsubscribe RPCs. // https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http MethodSubscriptionsListen MCPMethod = "subscriptions/listen" // MethodNotificationSubscriptionsAcknowledged reports which subscriptions a // server established in response to a subscriptions/listen request. MethodNotificationSubscriptionsAcknowledged = "notifications/subscriptions/acknowledged" )
const ( // MethodSamplingCreateMessage allows servers to request LLM completions from clients MethodSamplingCreateMessage MCPMethod = "sampling/createMessage" )
type Meta ¶ added in v0.28.0
type Meta struct {
// If specified, the caller is requesting out-of-band progress
// notifications for this request (as represented by
// notifications/progress). The value of this parameter is an
// opaque token that will be attached to any subsequent
// notifications. The receiver is not obligated to provide these
// notifications.
ProgressToken ProgressToken
// AdditionalFields are any fields present in the Meta that are not
// otherwise defined in the protocol.
AdditionalFields map[string]any
}
Meta is metadata attached to a request's parameters. This can include fields formally defined by the protocol or other arbitrary data.
func NewMetaFromMap ¶ added in v0.37.0
func WithModelImmediateResponse ¶ added in v0.44.0
WithModelImmediateResponse creates Meta with an immediate response message for the model. This allows the model to continue processing while the task executes asynchronously. The message parameter is a human-readable string that will be shown to the model.
Example:
return &mcp.CreateTaskResult{
Task: task,
Result: mcp.Result{
Meta: mcp.WithModelImmediateResponse("Processing your request. This may take a few minutes."),
},
}
func WithRelatedTask ¶ added in v0.44.0
WithRelatedTask returns a Meta with the related task ID set. This is useful for associating task results with their originating task.
func (*Meta) ClientCapabilities ¶ added in v1.0.0
func (m *Meta) ClientCapabilities() *ClientCapabilities
ClientCapabilities returns the per-request client capabilities declared in the _meta field, or nil when absent or malformed. See MetaKeyClientCapabilities.
func (*Meta) ClientInfo ¶ added in v1.0.0
func (m *Meta) ClientInfo() *Implementation
ClientInfo returns the client implementation declared in the _meta field, or nil when absent or malformed. See MetaKeyClientInfo.
func (*Meta) GetMetaField ¶ added in v1.0.0
GetMetaField returns the raw value stored under key in m's additional fields, or nil when absent.
func (*Meta) LogLevel ¶ added in v1.0.0
func (m *Meta) LogLevel() LoggingLevel
LogLevel returns the per-request log level declared in the _meta field, or "" when absent. See MetaKeyLogLevel.
func (*Meta) MarshalJSON ¶ added in v0.28.0
func (*Meta) ProtocolVersion ¶ added in v1.0.0
ProtocolVersion returns the protocol version declared in the _meta field, or "" when absent. See MetaKeyProtocolVersion.
func (*Meta) ServerInfo ¶ added in v1.0.0
func (m *Meta) ServerInfo() *Implementation
ServerInfo returns the server implementation declared in the _meta field, or nil when absent or malformed. See MetaKeyServerInfo.
func (*Meta) SetClientCapabilities ¶ added in v1.0.0
func (m *Meta) SetClientCapabilities(caps ClientCapabilities)
SetClientCapabilities records the per-request client capabilities in the _meta field.
func (*Meta) SetClientInfo ¶ added in v1.0.0
func (m *Meta) SetClientInfo(info Implementation)
SetClientInfo records the client implementation in the _meta field.
func (*Meta) SetLogLevel ¶ added in v1.0.0
func (m *Meta) SetLogLevel(level LoggingLevel)
SetLogLevel records the per-request log level in the _meta field.
func (*Meta) SetMetaField ¶ added in v1.0.0
SetMetaField stores value under key in m's additional fields.
func (*Meta) SetProtocolVersion ¶ added in v1.0.0
SetProtocolVersion records the protocol version in the _meta field.
func (*Meta) SetServerInfo ¶ added in v1.0.0
func (m *Meta) SetServerInfo(info Implementation)
SetServerInfo records the server implementation in the _meta field.
func (*Meta) SetSubscriptionID ¶ added in v1.0.0
SetSubscriptionID records the subscription stream identifier in the _meta field.
func (*Meta) SubscriptionID ¶ added in v1.0.0
SubscriptionID returns the subscription stream identifier declared in the _meta field, or nil when absent. See MetaKeySubscriptionID.
func (*Meta) UnmarshalJSON ¶ added in v0.28.0
type MissingRequiredClientCapabilityError ¶ added in v1.0.0
type MissingRequiredClientCapabilityError struct {
// Capability names the missing capability, e.g. "elicitation".
Capability string
}
MissingRequiredClientCapabilityError is returned when a request omits a client capability the server requires to serve it (SEP-2575).
func (MissingRequiredClientCapabilityError) Error ¶ added in v1.0.0
func (e MissingRequiredClientCapabilityError) Error() string
func (MissingRequiredClientCapabilityError) Is ¶ added in v1.0.0
func (e MissingRequiredClientCapabilityError) Is(target error) bool
Is implements the errors.Is interface for better error handling.
type ModelHint ¶ added in v0.4.0
type ModelHint struct {
// A hint for a model name.
//
// The client SHOULD treat this as a substring of a model name; for example:
// - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`
// - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.
// - `claude` should match any Claude model
//
// The client MAY also map the string to a different provider's model name or
// a different model family, as long as it fills a similar niche; for example:
// - `gemini-1.5-flash` could match `claude-3-haiku-20240307`
Name string `json:"name,omitempty"`
}
ModelHint represents hints to use for model selection.
Keys not declared here are currently left unspecified by the spec and are up to the client to interpret.
type ModelPreferences ¶ added in v0.4.0
type ModelPreferences struct {
// Optional hints to use for model selection.
//
// If multiple hints are specified, the client MUST evaluate them in order
// (such that the first match is taken).
//
// The client SHOULD prioritize these hints over the numeric priorities, but
// MAY still use the priorities to select from ambiguous matches.
Hints []ModelHint `json:"hints,omitempty"`
// How much to prioritize cost when selecting a model. A value of 0 means cost
// is not important, while a value of 1 means cost is the most important
// factor.
CostPriority float64 `json:"costPriority,omitempty"`
// How much to prioritize sampling speed (latency) when selecting a model. A
// value of 0 means speed is not important, while a value of 1 means speed is
// the most important factor.
SpeedPriority float64 `json:"speedPriority,omitempty"`
// How much to prioritize intelligence and capabilities when selecting a
// model. A value of 0 means intelligence is not important, while a value of 1
// means intelligence is the most important factor.
IntelligencePriority float64 `json:"intelligencePriority,omitempty"`
}
ModelPreferences represents the server's preferences for model selection, requested of the client during sampling.
Because LLMs can vary along multiple dimensions, choosing the "best" modelis rarely straightforward. Different models excel in different areas—some are faster but less capable, others are more capable but more expensive, and so on. This interface allows servers to express their priorities across multiple dimensions to help clients make an appropriate selection for their use case.
These preferences are always advisory. The client MAY ignore them. It is also up to the client to decide how to interpret these preferences and how to balance them against other considerations.
type MultiRoundTripParams ¶ added in v1.0.0
type MultiRoundTripParams struct {
// InputResponses answers the requests from a previous
// [InputRequiredResult]. Each key present in that result's InputRequests
// map must appear here.
InputResponses InputResponses `json:"inputResponses,omitempty"`
// RequestState echoes back, verbatim, the opaque state from a previous
// [InputRequiredResult].
RequestState string `json:"requestState,omitempty"`
}
MultiRoundTripParams carries the client's answers to a previous InputRequiredResult on a retry of the original request. It is embedded in the params of every request that may take part in a multi round-trip exchange.
type MultiRoundTripResult ¶ added in v1.0.0
type MultiRoundTripResult struct {
// InputRequests are the requests the client must fulfil before retrying.
// Present only when ResultType is [ResultTypeInputRequired].
InputRequests InputRequests `json:"inputRequests,omitempty"`
// RequestState is an opaque token the client must pass back verbatim when
// it retries the original request. Clients MUST NOT interpret it.
RequestState string `json:"requestState,omitempty"`
}
MultiRoundTripResult carries the multi round-trip fields on results that may ask the client for more input before completing. It is embedded in CallToolResult, GetPromptResult, and ReadResourceResult.
type Notification ¶ added in v0.4.0
type Notification struct {
Method string `json:"method"`
Params NotificationParams `json:"params,omitzero"`
}
type NotificationParams ¶ added in v0.4.0
type NotificationParams struct {
// This parameter name is reserved by MCP to allow clients and
// servers to attach additional metadata to their notifications.
Meta map[string]any `json:"_meta,omitempty"`
// Additional fields can be added to this map
AdditionalFields map[string]any `json:"-"`
}
func (NotificationParams) MarshalJSON ¶ added in v0.8.0
func (p NotificationParams) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling
func (*NotificationParams) UnmarshalJSON ¶ added in v0.8.0
func (p *NotificationParams) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling
type PaginatedParams ¶ added in v0.31.0
type PaginatedParams struct {
// An opaque token representing the current pagination position.
// If provided, the server should return results starting after this cursor.
Cursor Cursor `json:"cursor,omitempty"`
// Meta carries protocol-level metadata. PaginatedRequest embeds Request
// and shadows its Params with this type, so Meta must be declared here
// to be marshaled on paginated requests (tools/list, resources/list,
// resources/templates/list, prompts/list, tasks/list).
Meta *Meta `json:"_meta,omitempty"`
}
type PaginatedRequest ¶ added in v0.4.0
type PaginatedRequest struct {
Request
Params PaginatedParams `json:"params,omitzero"`
}
type PaginatedResult ¶ added in v0.4.0
type PaginatedResult struct {
CacheableResult
// An opaque token representing the pagination position after the last
// returned result.
// If present, there may be more results available.
NextCursor Cursor `json:"nextCursor,omitempty"`
}
type ParamHeaderBinding ¶ added in v1.0.0
type ParamHeaderBinding struct {
// Path is the property-name path from the root of the arguments object.
Path []string
// Header is the x-mcp-header annotation value, without the Mcp-Param-
// prefix.
Header string
}
ParamHeaderBinding maps a (possibly nested) input-schema property to the HTTP header it travels in, as declared by an x-mcp-header annotation.
func ExtractParamHeaderBindings ¶ added in v1.0.0
func ExtractParamHeaderBindings(tool *Tool) []ParamHeaderBinding
ExtractParamHeaderBindings returns a binding for every property in the tool's input schema carrying an x-mcp-header annotation, at any nesting depth.
func (ParamHeaderBinding) HeaderName ¶ added in v1.0.0
func (b ParamHeaderBinding) HeaderName() string
HeaderName returns the full HTTP header name for the binding.
type PingRequest ¶ added in v0.4.0
PingRequest represents a ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.
type ProgressNotification ¶ added in v0.4.0
type ProgressNotification struct {
Notification
Params ProgressNotificationParams `json:"params"`
}
ProgressNotification is an out-of-band notification used to inform the receiver of a progress update for a long-running request.
func NewProgressNotification ¶ added in v0.5.0
func NewProgressNotification( token ProgressToken, progress float64, total *float64, message *string, ) ProgressNotification
NewProgressNotification creates a progress notification.
type ProgressNotificationParams ¶ added in v0.4.0
type ProgressNotificationParams struct {
// The progress token which was given in the initial request, used to
// associate this notification with the request that is proceeding.
ProgressToken ProgressToken `json:"progressToken"`
// The progress thus far. This should increase every time progress is made,
// even if the total is unknown.
Progress float64 `json:"progress"`
// Total number of items to process (or total progress required), if known.
Total float64 `json:"total,omitempty"`
// Message related to progress. This should provide relevant human-readable
// progress information.
Message string `json:"message,omitempty"`
}
type ProgressToken ¶ added in v0.4.0
type ProgressToken any
ProgressToken is used to associate progress notifications with the original request.
type Prompt ¶
type Prompt struct {
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
// The name of the prompt or prompt template.
Name string `json:"name"`
// Title is an optional human-readable, UI-friendly display name for the prompt.
// If not provided, clients should fall back to Name.
Title string `json:"title,omitempty"`
// An optional description of what this prompt provides
Description string `json:"description,omitempty"`
// A list of arguments to use for templating the prompt.
// The presence of arguments indicates this is a template prompt.
Arguments []PromptArgument `json:"arguments,omitempty"`
// Icons provides visual identifiers for the prompt
Icons []Icon `json:"icons,omitempty"`
}
Prompt represents a prompt or prompt template that the server offers. If Arguments is non-nil and non-empty, this indicates the prompt is a template that requires argument values to be provided when calling prompts/get. If Arguments is nil or empty, this is a static prompt that takes no arguments.
func NewPrompt ¶ added in v0.5.0
func NewPrompt(name string, opts ...PromptOption) Prompt
NewPrompt creates a new Prompt with the given name and options. The prompt will be configured based on the provided options. Options are applied in order, allowing for flexible prompt configuration.
type PromptArgument ¶
type PromptArgument struct {
// The name of the argument.
Name string `json:"name"`
// Title is an optional human-readable, UI-friendly display name for the argument.
// If not provided, clients should fall back to Name.
Title string `json:"title,omitempty"`
// A human-readable description of the argument.
Description string `json:"description,omitempty"`
// Whether this argument must be provided.
// If true, clients must include this argument when calling prompts/get.
Required bool `json:"required,omitempty"`
}
PromptArgument describes an argument that a prompt template can accept. When a prompt includes arguments, clients must provide values for all required arguments when making a prompts/get request.
type PromptListChangedNotification ¶ added in v0.4.0
type PromptListChangedNotification struct {
Notification
}
PromptListChangedNotification is an optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.
type PromptMessage ¶
type PromptMessage struct {
Role Role `json:"role"`
Content Content `json:"content"` // Can be TextContent, ImageContent, AudioContent or EmbeddedResource
}
PromptMessage describes a message returned as part of a prompt.
This is similar to `SamplingMessage`, but also supports the embedding of resources from the MCP server.
func NewPromptMessage ¶ added in v0.5.0
func NewPromptMessage(role Role, content Content) PromptMessage
NewPromptMessage creates a prompt message.
type PromptOption ¶ added in v0.5.10
type PromptOption func(*Prompt)
PromptOption is a function that configures a Prompt. It provides a flexible way to set various properties of a Prompt using the functional options pattern.
func WithArgument ¶ added in v0.5.10
func WithArgument(name string, opts ...ArgumentOption) PromptOption
WithArgument adds an argument to the prompt's argument list. The argument will be configured based on the provided options.
func WithPromptDescription ¶ added in v0.5.10
func WithPromptDescription(description string) PromptOption
WithPromptDescription adds a description to the Prompt. The description should provide a clear, human-readable explanation of what the prompt does.
func WithPromptIcons ¶ added in v0.44.0
func WithPromptIcons(icons ...Icon) PromptOption
WithPromptIcons adds icons to the Prompt. Icons provide visual identifiers for the prompt.
func WithPromptTitle ¶ added in v0.54.0
func WithPromptTitle(title string) PromptOption
WithPromptTitle sets the optional human-readable display title for the Prompt. Per the MCP spec, clients should prefer Title over Name for display.
type PromptReference ¶
type PromptReference struct {
Type string `json:"type"`
// The name of the prompt or prompt template
Name string `json:"name"`
}
PromptReference identifies a prompt.
type PropertyOption ¶ added in v0.5.1
PropertyOption is a function that configures a property in a Tool's input schema. It allows for flexible configuration of JSON Schema properties using the functional options pattern.
func AdditionalProperties ¶ added in v0.13.0
func AdditionalProperties(schema any) PropertyOption
AdditionalProperties specifies whether additional properties are allowed in the object or defines a schema for additional properties
func DefaultArray ¶ added in v0.21.0
func DefaultArray[T any](value []T) PropertyOption
DefaultArray sets the default value for an array property. This value will be used if the property is not explicitly provided.
func DefaultBool ¶ added in v0.5.1
func DefaultBool(value bool) PropertyOption
DefaultBool sets the default value for a boolean property. This value will be used if the property is not explicitly provided.
func DefaultNumber ¶ added in v0.5.1
func DefaultNumber[T int | int64 | float64](value T) PropertyOption
DefaultNumber sets the default value for a number or integer property. This value will be used if the property is not explicitly provided.
func DefaultString ¶ added in v0.5.1
func DefaultString(value string) PropertyOption
DefaultString sets the default value for a string property. This value will be used if the property is not explicitly provided.
func Description ¶ added in v0.5.1
func Description(desc string) PropertyOption
Description adds a description to a property in the JSON Schema. The description should explain the purpose and expected values of the property.
func Enum ¶ added in v0.5.1
func Enum(values ...string) PropertyOption
Enum specifies a list of allowed values for a string property. The property value must be one of the specified enum values.
func Items ¶ added in v0.13.0
func Items(schema any) PropertyOption
Items defines the schema for array items. Accepts any schema definition for maximum flexibility.
Example:
Items(map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]any{"type": "string"},
"age": map[string]any{"type": "number"},
},
})
For simple types, use ItemsString(), ItemsNumber(), ItemsBoolean() instead.
func Max ¶ added in v0.5.1
func Max[T int | int64 | float64](max T) PropertyOption
Max sets the maximum value for a number or integer property. The number value must not exceed this maximum.
func MaxItems ¶ added in v0.13.0
func MaxItems(max int) PropertyOption
MaxItems sets the maximum number of items for an array
func MaxLength ¶ added in v0.5.1
func MaxLength(max int) PropertyOption
MaxLength sets the maximum length for a string property. The string value must not exceed this length.
func MaxProperties ¶ added in v0.13.0
func MaxProperties(max int) PropertyOption
MaxProperties sets the maximum number of properties for an object
func Min ¶ added in v0.5.1
func Min[T int | int64 | float64](min T) PropertyOption
Min sets the minimum value for a number or integer property. The number value must not be less than this minimum.
func MinItems ¶ added in v0.13.0
func MinItems(min int) PropertyOption
MinItems sets the minimum number of items for an array
func MinLength ¶ added in v0.5.1
func MinLength(min int) PropertyOption
MinLength sets the minimum length for a string property. The string value must be at least this length.
func MinProperties ¶ added in v0.13.0
func MinProperties(min int) PropertyOption
MinProperties sets the minimum number of properties for an object
func MultipleOf ¶ added in v0.5.1
func MultipleOf[T int | int64 | float64](value T) PropertyOption
MultipleOf specifies that a number or integer must be a multiple of the given value. The number value must be divisible by this value.
func Pattern ¶ added in v0.5.1
func Pattern(pattern string) PropertyOption
Pattern sets a regex pattern that a string property must match. The string value must conform to the specified regular expression.
func Properties ¶ added in v0.13.0
func Properties(props map[string]any) PropertyOption
Properties sets the "properties" map for an object schema. The returned PropertyOption stores the provided map under the schema's "properties" key.
func PropertyNames ¶ added in v0.13.0
func PropertyNames(schema map[string]any) PropertyOption
PropertyNames defines a schema for property names in an object
func Required ¶ added in v0.5.1
func Required() PropertyOption
Required marks a property as required in the tool's input schema. Required properties must be provided when using the tool.
func Title ¶ added in v0.5.1
func Title(title string) PropertyOption
Title adds a display-friendly title to a property in the JSON Schema. This title can be used by UI components to show a more readable property name.
func UniqueItems ¶ added in v0.13.0
func UniqueItems(unique bool) PropertyOption
UniqueItems specifies whether array items must be unique
func WithBooleanItems ¶ added in v0.33.0
func WithBooleanItems(opts ...PropertyOption) PropertyOption
WithBooleanItems configures an array's items to be of type boolean.
Supported options: Description(), DefaultBool() Note: Options like Required() are not valid for item schemas and will be ignored.
Examples:
mcp.WithArray("flags", mcp.WithBooleanItems())
mcp.WithArray("permissions", mcp.WithBooleanItems(mcp.Description("User permissions")))
Limitations: Only supports simple boolean arrays. Use Items() for complex objects.
func WithIntegerItems ¶ added in v0.50.0
func WithIntegerItems(opts ...PropertyOption) PropertyOption
WithIntegerItems configures an array's items to be of type integer.
Supported options: Description(), DefaultNumber(), Min(), Max(), MultipleOf() Note: Options like Required() are not valid for item schemas and will be ignored.
Examples:
mcp.WithArray("ids", mcp.WithIntegerItems())
mcp.WithArray("scores", mcp.WithIntegerItems(mcp.Min(0), mcp.Max(100)))
Limitations: Only supports simple integer arrays. Use Items() for complex objects.
func WithNumberItems ¶ added in v0.33.0
func WithNumberItems(opts ...PropertyOption) PropertyOption
WithNumberItems configures an array's items to be of type number.
Supported options: Description(), DefaultNumber(), Min(), Max(), MultipleOf() Note: Options like Required() are not valid for item schemas and will be ignored.
Examples:
mcp.WithArray("scores", mcp.WithNumberItems(mcp.Min(0), mcp.Max(100)))
mcp.WithArray("prices", mcp.WithNumberItems(mcp.Min(0)))
Limitations: Only supports simple number arrays. Use Items() for complex objects.
func WithStringEnumItems ¶ added in v0.33.0
func WithStringEnumItems(values []string) PropertyOption
WithStringEnumItems configures an array's items to be of type string with a specified enum. Example:
mcp.WithArray("priority", mcp.WithStringEnumItems([]string{"low", "medium", "high"}))
Limitations: Only supports string enums. Use WithStringItems(Enum(...)) for more flexibility.
func WithStringItems ¶ added in v0.33.0
func WithStringItems(opts ...PropertyOption) PropertyOption
WithStringItems configures an array's items to be of type string.
Supported options: Description(), DefaultString(), Enum(), MaxLength(), MinLength(), Pattern() Note: Options like Required() are not valid for item schemas and will be ignored.
Examples:
mcp.WithArray("tags", mcp.WithStringItems())
mcp.WithArray("colors", mcp.WithStringItems(mcp.Enum("red", "green", "blue")))
mcp.WithArray("names", mcp.WithStringItems(mcp.MinLength(1), mcp.MaxLength(50)))
Limitations: Only supports simple string arrays. Use Items() for complex objects.
type ReadResourceParams ¶ added in v0.31.0
type ReadResourceParams struct {
// The URI of the resource to read. The URI can use any protocol; it is up
// to the server how to interpret it.
URI string `json:"uri"`
// Arguments to pass to the resource handler
Arguments map[string]any `json:"arguments,omitempty"`
// Meta carries protocol-level metadata (e.g. W3C traceparent, progressToken).
Meta *Meta `json:"_meta,omitempty"`
MultiRoundTripParams
}
type ReadResourceRequest ¶ added in v0.4.0
type ReadResourceRequest struct {
Request
Header http.Header `json:"-"`
Params ReadResourceParams `json:"params"`
}
ReadResourceRequest is sent from the client to the server, to read a specific resource URI.
type ReadResourceResult ¶
type ReadResourceResult struct {
CacheableResult
MultiRoundTripResult
Contents []ResourceContents `json:"contents"` // Can be TextResourceContents or BlobResourceContents
}
ReadResourceResult is the server's response to a resources/read request from the client.
func NewReadResourceResult ¶ added in v0.5.1
func NewReadResourceResult(text string) *ReadResourceResult
NewReadResourceResult creates a new ReadResourceResult with text content
func ParseReadResourceResult ¶ added in v0.10.2
func ParseReadResourceResult(rawMessage *json.RawMessage) (*ReadResourceResult, error)
func (*ReadResourceResult) NeedsInput ¶ added in v1.0.0
func (r *ReadResourceResult) NeedsInput() bool
NeedsInput reports whether the result asks the client for more input before the original request can complete.
type Request ¶ added in v0.4.0
type Request struct {
Method string `json:"method"`
Params RequestParams `json:"params,omitzero"`
}
type RequestId ¶ added in v0.4.0
type RequestId struct {
// contains filtered or unexported fields
}
RequestId is a uniquely identifying ID for a request in JSON-RPC. It can be any JSON-serializable value, typically a number or string.
func NewRequestId ¶ added in v0.28.0
NewRequestId creates a new RequestId with the given value
func (RequestId) MarshalJSON ¶ added in v0.28.0
func (*RequestId) UnmarshalJSON ¶ added in v0.28.0
type RequestParams ¶ added in v0.4.0
type RequestParams struct {
Meta *Meta `json:"_meta,omitempty"`
}
type Resource ¶
type Resource struct {
Annotated
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
// The URI of this resource.
URI string `json:"uri"`
// A human-readable name for this resource.
//
// This can be used by clients to populate UI elements.
Name string `json:"name"`
// Title is an optional human-readable, UI-friendly display name for this resource.
// If not provided, clients should fall back to Name.
Title string `json:"title,omitempty"`
// A description of what this resource represents.
//
// This can be used by clients to improve the LLM's understanding of
// available resources. It can be thought of like a "hint" to the model.
Description string `json:"description,omitempty"`
// The MIME type of this resource, if known.
MIMEType string `json:"mimeType,omitempty"`
// Icons provides visual identifiers for the resource
Icons []Icon `json:"icons,omitempty"`
// Size is the size of the raw resource content, in bytes (i.e., before base64
// encoding or any tokenization), if known. This can be used by hosts to
// display file sizes and estimate context window usage.
//
// A pointer is used so that an explicit zero size remains distinguishable
// from an unset value.
Size *int64 `json:"size,omitempty"`
}
Resource represents a known resource that the server is capable of reading.
func NewResource ¶ added in v0.5.0
func NewResource(uri string, name string, opts ...ResourceOption) Resource
NewResource creates a new Resource with the given URI, name and options. The resource will be configured based on the provided options. Options are applied in order, allowing for flexible resource configuration.
type ResourceContents ¶
type ResourceContents interface {
// contains filtered or unexported methods
}
ResourceContents represents the contents of a specific resource or sub- resource.
func ParseResourceContents ¶ added in v0.10.2
func ParseResourceContents(contentMap map[string]any) (ResourceContents, error)
type ResourceLink ¶ added in v0.33.0
type ResourceLink struct {
Annotated
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
Type string `json:"type"` // Must be "resource_link"
// The URI of the resource.
URI string `json:"uri"`
// The name of the resource.
Name string `json:"name"`
// Title is an optional human-readable, UI-friendly display name for this resource.
// If not provided, clients should fall back to Name.
Title string `json:"title,omitempty"`
// The description of the resource.
Description string `json:"description"`
// The MIME type of the resource.
MIMEType string `json:"mimeType"`
// Size is the size of the raw resource content, in bytes (i.e., before base64
// encoding or any tokenization), if known. This can be used by hosts to
// display file sizes and estimate context window usage.
//
// A pointer is used so that an explicit zero size remains distinguishable
// from an unset value.
Size *int64 `json:"size,omitempty"`
}
ResourceLink represents a link to a resource that the client can access.
func NewResourceLink ¶ added in v0.33.0
func NewResourceLink(uri, name, description, mimeType string) ResourceLink
NewResourceLink creates a resource link.
type ResourceListChangedNotification ¶ added in v0.4.0
type ResourceListChangedNotification struct {
Notification
}
ResourceListChangedNotification is an optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.
type ResourceOption ¶ added in v0.6.0
type ResourceOption func(*Resource)
ResourceOption is a function that configures a Resource. It provides a flexible way to set various properties of a Resource using the functional options pattern.
func WithAnnotations ¶ added in v0.6.0
func WithAnnotations(audience []Role, priority float64, lastModified string) ResourceOption
WithAnnotations returns a ResourceOption that sets the resource's Annotations fields. It initializes Annotations if nil, sets Audience to the provided slice, stores Priority as a pointer to the provided value, and sets LastModified to the provided timestamp.
func WithLastModified ¶ added in v0.44.0
func WithLastModified(timestamp string) ResourceOption
WithLastModified returns a ResourceOption that sets the resource's Annotations.LastModified to the provided timestamp. If the resource's Annotations is nil, it will be initialized. The timestamp is expected to be an ISO 8601 (RFC3339) formatted string (e.g., "2025-01-12T15:00:58Z").
func WithMIMEType ¶ added in v0.6.0
func WithMIMEType(mimeType string) ResourceOption
WithMIMEType sets the MIME type for the Resource. This should indicate the format of the resource's contents.
func WithResourceDescription ¶ added in v0.6.0
func WithResourceDescription(description string) ResourceOption
WithResourceDescription adds a description to the Resource. The description should provide a clear, human-readable explanation of what the resource represents.
func WithResourceIcons ¶ added in v0.44.0
func WithResourceIcons(icons ...Icon) ResourceOption
WithResourceIcons adds icons to the Resource. Icons provide visual identifiers for the resource.
func WithResourceSize ¶ added in v0.54.0
func WithResourceSize(size int64) ResourceOption
WithResourceSize sets the size of the raw resource content in bytes. This is the size before base64 encoding or any tokenization, and is used by hosts to display file sizes and estimate context window usage. Negative values are ignored, since the MCP schema defines size as a byte count which is necessarily non-negative.
func WithResourceTitle ¶ added in v0.54.0
func WithResourceTitle(title string) ResourceOption
WithResourceTitle sets the optional human-readable display title for the Resource. Per the MCP spec, clients should prefer Title over Name for display.
type ResourceReference ¶
type ResourceReference struct {
Type string `json:"type"`
// The URI or URI template of the resource.
URI string `json:"uri"`
}
ResourceReference is a reference to a resource or resource template definition.
type ResourceTemplate ¶ added in v0.4.0
type ResourceTemplate struct {
Annotated
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
// A URI template (according to RFC 6570) that can be used to construct
// resource URIs.
URITemplate *URITemplate `json:"uriTemplate"`
// A human-readable name for the type of resource this template refers to.
//
// This can be used by clients to populate UI elements.
Name string `json:"name"`
// Title is an optional human-readable, UI-friendly display name for this resource template.
// If not provided, clients should fall back to Name.
Title string `json:"title,omitempty"`
// A description of what this template is for.
//
// This can be used by clients to improve the LLM's understanding of
// available resources. It can be thought of like a "hint" to the model.
Description string `json:"description,omitempty"`
// The MIME type for all resources that match this template. This should only
// be included if all resources matching this template have the same type.
MIMEType string `json:"mimeType,omitempty"`
// Icons provides visual identifiers for the resource template
Icons []Icon `json:"icons,omitempty"`
}
ResourceTemplate represents a template description for resources available on the server.
func NewResourceTemplate ¶ added in v0.6.0
func NewResourceTemplate(uriTemplate string, name string, opts ...ResourceTemplateOption) ResourceTemplate
NewResourceTemplate creates a new ResourceTemplate with the given URI template, name and options. The template will be configured based on the provided options. Options are applied in order, allowing for flexible template configuration.
func (ResourceTemplate) GetName ¶ added in v0.27.0
func (rt ResourceTemplate) GetName() string
GetName returns the name of the resourceTemplate.
type ResourceTemplateOption ¶ added in v0.6.0
type ResourceTemplateOption func(*ResourceTemplate)
ResourceTemplateOption is a function that configures a ResourceTemplate. It provides a flexible way to set various properties of a ResourceTemplate using the functional options pattern.
func WithTemplateAnnotations ¶ added in v0.6.0
func WithTemplateAnnotations(audience []Role, priority float64, lastModified string) ResourceTemplateOption
WithTemplateAnnotations returns a ResourceTemplateOption that sets the template's Annotations field, initializing it if nil, and setting Audience, Priority, and LastModified.
func WithTemplateDescription ¶ added in v0.6.0
func WithTemplateDescription(description string) ResourceTemplateOption
WithTemplateDescription adds a description to the ResourceTemplate. The description should provide a clear, human-readable explanation of what resources this template represents.
func WithTemplateIcons ¶ added in v0.44.0
func WithTemplateIcons(icons ...Icon) ResourceTemplateOption
WithTemplateIcons adds icons to the ResourceTemplate. Icons provide visual identifiers for the resource template.
func WithTemplateMIMEType ¶ added in v0.6.0
func WithTemplateMIMEType(mimeType string) ResourceTemplateOption
WithTemplateMIMEType sets the MIME type for the ResourceTemplate. This should only be set if all resources matching this template will have the same type.
func WithTemplateTitle ¶ added in v0.54.0
func WithTemplateTitle(title string) ResourceTemplateOption
WithTemplateTitle sets the optional human-readable display title for the ResourceTemplate. Per the MCP spec, clients should prefer Title over Name for display.
type ResourceUpdatedNotification ¶ added in v0.4.0
type ResourceUpdatedNotification struct {
Notification
Params ResourceUpdatedNotificationParams `json:"params"`
}
ResourceUpdatedNotification is a notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.
type ResourceUpdatedNotificationParams ¶ added in v0.4.0
type ResourceUpdatedNotificationParams struct {
// The URI of the resource that has been updated. This might be a sub-
// resource of the one that the client actually subscribed to.
URI string `json:"uri"`
}
type Result ¶ added in v0.4.0
type Result struct {
// This result property is reserved by the protocol to allow clients and
// servers to attach additional metadata to their responses.
Meta *Meta `json:"_meta,omitempty"`
// ResultType indicates how the client should interpret this result.
//
// Servers implementing protocol version 2026-07-28 or later MUST populate
// it. It is omitted when responding to a request that used an earlier
// protocol version; clients MUST treat an absent value as
// [ResultTypeComplete].
ResultType ResultType `json:"resultType,omitempty"`
}
func (*Result) EnsureResultMeta ¶ added in v1.0.0
EnsureResultMeta returns the result's _meta, allocating it when absent.
func (*Result) GetResultMeta ¶ added in v1.0.0
GetResultMeta returns the result's _meta, which may be nil.
func (*Result) GetResultType ¶ added in v1.0.0
func (r *Result) GetResultType() ResultType
GetResultType returns the recorded result type.
func (*Result) SetResultMeta ¶ added in v1.0.0
SetResultMeta replaces the result's _meta.
func (*Result) SetResultType ¶ added in v1.0.0
func (r *Result) SetResultType(t ResultType)
SetResultType records how the client should interpret the result.
type ResultMetadata ¶ added in v1.0.0
type ResultMetadata interface {
// SetResultType records how the client should interpret the result.
SetResultType(ResultType)
// GetResultType returns the recorded result type.
GetResultType() ResultType
// SetResultMeta replaces the result's _meta.
SetResultMeta(*Meta)
// GetResultMeta returns the result's _meta, which may be nil.
GetResultMeta() *Meta
// EnsureResultMeta returns the result's _meta, allocating it when absent.
EnsureResultMeta() *Meta
}
ResultMetadata is implemented by every MCP result type through its embedded Result. It allows transports and servers to decorate a result generically, without knowing its concrete type.
type ResultType ¶ added in v1.0.0
type ResultType string
ResultType indicates how a client should interpret a result, as introduced by protocol version 2026-07-28 (SEP-2322).
const ( // ResultTypeComplete indicates an ordinary, final result. // // Clients MUST treat a result from an earlier-protocol server that omits // the resultType field as complete. ResultTypeComplete ResultType = "complete" // ResultTypeInputRequired indicates the server needs additional input from // the client before it can finish the request. The client fulfils the // [InputRequiredResult.InputRequests] and retries the original request with // the answers attached. See the multi round-trip request pattern. ResultTypeInputRequired ResultType = "input_required" )
func (ResultType) IsComplete ¶ added in v1.0.0
func (t ResultType) IsComplete() bool
IsComplete reports whether the result type denotes a final result. An empty result type is treated as complete for backwards compatibility with servers implementing protocol versions earlier than 2026-07-28.
type Role ¶
type Role string
Role represents the sender or recipient of messages and data in a conversation.
type Root ¶ added in v0.4.0
type Root struct {
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
// The URI identifying the root. This *must* start with file:// for now.
// This restriction may be relaxed in future versions of the protocol to allow
// other URI schemes.
URI string `json:"uri"`
// An optional name for the root. This can be used to provide a human-readable
// identifier for the root, which may be useful for display purposes or for
// referencing the root in other parts of the application.
Name string `json:"name,omitempty"`
}
Root represents a root directory or file that the server can operate on.
type RootsListChangedNotification ¶ added in v0.4.0
type RootsListChangedNotification struct {
Notification
}
RootsListChangedNotification is a notification from the client to the server, informing it that the list of roots has changed. This notification should be sent whenever the client adds, removes, or modifies any root. The server should then request an updated list of roots using the ListRootsRequest.
type SamplingCapability ¶ added in v0.54.0
type SamplingCapability struct {
// Context, if non-nil, advertises that the client honours the
// CreateMessageParams.IncludeContext field. If a peer does not declare this
// sub-capability, servers SHOULD only use IncludeContext "none" or omit it.
Context *struct{} `json:"context,omitempty"`
// Tools, if non-nil, advertises that the client honours the
// CreateMessageParams.Tools and CreateMessageParams.ToolChoice fields
// (sampling with tools). Servers MUST NOT send those fields unless this
// sub-capability is declared.
Tools *struct{} `json:"tools,omitempty"`
}
SamplingCapability represents the sampling capabilities of a client or server as defined by the 2025-11-25 protocol revision.
A nil pointer means the peer does not support sampling at all. A non-nil but empty value (the zero value) advertises baseline sampling support without the optional context-inclusion or tool-use extensions.
type SamplingMessage ¶ added in v0.4.0
type SamplingMessage struct {
Role Role `json:"role"`
Content any `json:"content"` // Can be TextContent, ImageContent, AudioContent, ToolUseContent or ToolResultContent
}
SamplingMessage describes a message issued to or received from an LLM API.
type SchemaCache ¶ added in v0.51.0
type SchemaCache struct {
// contains filtered or unexported fields
}
SchemaCache stores pre-computed JSON schemas for tool input/output types.
SchemaCache is intended to amortise the cost of JSON-Schema reflection in stateless or serverless deployments (e.g., AWS Lambda, Google Cloud Functions) where servers are reconstructed on every invocation. Schemas can be warmed once at build time, persisted to disk via SchemaCache.Save, and reloaded at start-up via LoadSchemaCache. Cached schemas are then consumed by WithCachedInputSchema and WithCachedOutputSchema in lieu of the reflection performed by WithInputSchema and WithOutputSchema.
SchemaCache is safe for concurrent use by multiple goroutines.
func LoadSchemaCache ¶ added in v0.51.0
func LoadSchemaCache(path string) (*SchemaCache, error)
LoadSchemaCache reads a cache from a file produced by SchemaCache.Save.
func NewSchemaCache ¶ added in v0.51.0
func NewSchemaCache() *SchemaCache
NewSchemaCache creates a new empty SchemaCache.
func (*SchemaCache) Get ¶ added in v0.51.0
func (c *SchemaCache) Get(typeName string) (map[string]any, bool)
Get retrieves a cached schema by type name as a generic map. The second return value reports whether the entry was present.
func (*SchemaCache) GetRaw ¶ added in v0.51.0
func (c *SchemaCache) GetRaw(typeName string) (json.RawMessage, bool)
GetRaw retrieves a cached schema by type name as raw JSON. The returned slice is a copy and may be safely mutated by the caller.
func (*SchemaCache) Has ¶ added in v0.51.0
func (c *SchemaCache) Has(typeName string) bool
Has reports whether a schema is cached under typeName.
func (*SchemaCache) Keys ¶ added in v0.51.0
func (c *SchemaCache) Keys() []string
Keys returns the cached type names in sorted order. The result is a fresh slice and may be modified by the caller.
func (*SchemaCache) Len ¶ added in v0.51.0
func (c *SchemaCache) Len() int
Len returns the number of cached schemas.
func (*SchemaCache) MarshalJSON ¶ added in v0.51.0
func (c *SchemaCache) MarshalJSON() ([]byte, error)
MarshalJSON serialises the cache as a JSON object whose keys are type names and whose values are the cached JSON schemas. Keys are emitted in sorted order so that the encoded form is deterministic and diff-friendly.
func (*SchemaCache) Save ¶ added in v0.51.0
func (c *SchemaCache) Save(path string) error
Save writes the cache to a file as JSON. Parent directories are created if needed. The file is written atomically by writing to a temporary sibling and renaming it into place.
func (*SchemaCache) UnmarshalJSON ¶ added in v0.51.0
func (c *SchemaCache) UnmarshalJSON(data []byte) error
UnmarshalJSON loads a previously serialised cache, replacing any existing contents. The input must be a JSON object whose values are themselves JSON schemas; values are stored verbatim as raw JSON.
func (*SchemaCache) Warm ¶ added in v0.51.0
func (c *SchemaCache) Warm(typeName string, schema map[string]any)
Warm stores the JSON schema for the given type name. Schemas are typically produced by SchemaFor. Passing a nil schema removes any existing entry for typeName.
func (*SchemaCache) WarmRaw ¶ added in v0.51.0
func (c *SchemaCache) WarmRaw(typeName string, schema json.RawMessage)
WarmRaw stores a pre-marshaled JSON schema under the given type name. This avoids an unmarshal/marshal round-trip when callers already hold the schema as raw JSON. Passing a nil or empty schema removes any existing entry for typeName.
type ServerCapabilities ¶
type ServerCapabilities struct {
// Optional, present if the server is advertising extension support.
Extensions map[string]any `json:"extensions,omitempty"`
// Experimental, non-standard capabilities that the server supports.
Experimental map[string]any `json:"experimental,omitempty"`
// Present if the server supports sending log messages to the client.
Logging *struct{} `json:"logging,omitempty"`
// Present if the server offers any prompt templates.
Prompts *struct {
// Whether this server supports notifications for changes to the prompt list.
ListChanged bool `json:"listChanged,omitempty"`
} `json:"prompts,omitempty"`
// Present if the server offers any resources to read.
Resources *struct {
// Whether this server supports subscribing to resource updates.
Subscribe bool `json:"subscribe,omitempty"`
// Whether this server supports notifications for changes to the resource
// list.
ListChanged bool `json:"listChanged,omitempty"`
} `json:"resources,omitempty"`
// Present if the server supports sending sampling requests to clients.
Sampling *SamplingCapability `json:"sampling,omitempty"`
// Present if the server offers any tools to call.
Tools *struct {
// Whether this server supports notifications for changes to the tool list.
ListChanged bool `json:"listChanged,omitempty"`
} `json:"tools,omitempty"`
// Present if the server supports elicitation requests to the client.
Elicitation *ElicitationCapability `json:"elicitation,omitempty"`
// Present if the server supports roots requests to the client.
Roots *struct{} `json:"roots,omitempty"`
// Present if the server supports task-based execution.
Tasks *TasksCapability `json:"tasks,omitempty"`
// Present if the server supports completions requests to the client.
Completions *struct{} `json:"completions,omitempty"`
}
ServerCapabilities represents capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.
type ServerNotification ¶ added in v0.4.0
type ServerNotification any
ServerNotification represents any notification that can be sent from server to client.
type ServerRequest ¶ added in v0.4.0
type ServerRequest any
ServerRequest represents any request that can be sent from server to client.
type ServerResult ¶ added in v0.4.0
type ServerResult any
ServerResult represents any result that can be sent from server to client.
type SetLevelParams ¶ added in v0.31.0
type SetLevelParams struct {
// The level of logging that the client wants to receive from the server.
// The server should send all logs at this level and higher (i.e., more severe) to
// the client as notifications/logging/message.
Level LoggingLevel `json:"level"`
}
type SetLevelRequest ¶ added in v0.4.0
type SetLevelRequest struct {
Request
Params SetLevelParams `json:"params"`
Header http.Header `json:"-"`
}
SetLevelRequest is a request from the client to the server, to enable or adjust logging.
type StructuredToolHandlerFunc ¶ added in v0.36.0
type StructuredToolHandlerFunc[TArgs any, TResult any] func(ctx context.Context, request CallToolRequest, args TArgs) (TResult, error)
StructuredToolHandlerFunc is a function that handles a tool call with typed arguments and returns structured output
type SubscribeParams ¶ added in v0.31.0
type SubscribeParams struct {
// The URI of the resource to subscribe to. The URI can use any protocol; it
// is up to the server how to interpret it.
URI string `json:"uri"`
}
type SubscribeRequest ¶ added in v0.4.0
type SubscribeRequest struct {
Request
Params SubscribeParams `json:"params"`
Header http.Header `json:"-"`
}
SubscribeRequest is sent from the client to request resources/updated notifications from the server whenever a particular resource changes.
type SubscriptionFilter ¶ added in v1.0.0
type SubscriptionFilter struct {
// ToolsListChanged opts in to notifications/tools/list_changed.
ToolsListChanged bool `json:"toolsListChanged,omitempty"`
// PromptsListChanged opts in to notifications/prompts/list_changed.
PromptsListChanged bool `json:"promptsListChanged,omitempty"`
// ResourcesListChanged opts in to notifications/resources/list_changed.
ResourcesListChanged bool `json:"resourcesListChanged,omitempty"`
// ResourceSubscriptions opts in to notifications/resources/updated for the
// listed resource URIs. It replaces the resources/subscribe RPC.
ResourceSubscriptions []string `json:"resourceSubscriptions,omitempty"`
}
SubscriptionFilter is the set of notification types a client opts in to on a subscriptions/listen request. Each type is opt-in: the server MUST NOT send notification types the client has not explicitly requested.
func (SubscriptionFilter) IsEmpty ¶ added in v1.0.0
func (f SubscriptionFilter) IsEmpty() bool
IsEmpty reports whether the filter opts in to nothing.
type SubscriptionsAcknowledgedNotification ¶ added in v1.0.0
type SubscriptionsAcknowledgedNotification struct {
Notification
Params SubscriptionsAcknowledgedParams `json:"params"`
}
SubscriptionsAcknowledgedNotification informs the client which of the requested subscriptions the server actually established. It is the first message delivered on a subscriptions/listen stream.
type SubscriptionsAcknowledgedParams ¶ added in v1.0.0
type SubscriptionsAcknowledgedParams struct {
// Notifications is the subset of the requested filter that the server
// established, after intersecting it with the server's capabilities.
Notifications SubscriptionFilter `json:"notifications"`
// Meta carries [MetaKeySubscriptionID].
Meta map[string]any `json:"_meta,omitempty"`
}
SubscriptionsAcknowledgedParams are the parameters of a notifications/subscriptions/acknowledged notification.
type SubscriptionsListenParams ¶ added in v1.0.0
type SubscriptionsListenParams struct {
// Notifications selects the notification types the client opts in to.
Notifications SubscriptionFilter `json:"notifications"`
// Meta carries the per-request protocol metadata.
Meta *Meta `json:"_meta,omitempty"`
}
SubscriptionsListenParams are the parameters of a subscriptions/listen request.
type SubscriptionsListenRequest ¶ added in v1.0.0
type SubscriptionsListenRequest struct {
Request
Header http.Header `json:"-"`
Params SubscriptionsListenParams `json:"params"`
}
SubscriptionsListenRequest opens a long-lived stream for receiving server-to-client notifications outside the context of a specific request (SEP-2575). It replaces the HTTP GET endpoint and the resources/subscribe and resources/unsubscribe RPCs.
type SubscriptionsListenResult ¶ added in v1.0.0
type SubscriptionsListenResult struct {
Result
}
SubscriptionsListenResult closes a subscriptions/listen stream. Its Meta carries MetaKeySubscriptionID, identifying the stream being closed.
type Task ¶ added in v0.44.0
type Task struct {
// Unique identifier for the task.
TaskId string `json:"taskId"`
// Current state of the task execution.
Status TaskStatus `json:"status"`
// Optional human-readable message describing the current state.
StatusMessage string `json:"statusMessage,omitempty"`
// ISO 8601 timestamp when the task was created.
CreatedAt string `json:"createdAt"`
// ISO 8601 timestamp when the task was last updated.
LastUpdatedAt string `json:"lastUpdatedAt"`
// Time in milliseconds from creation before task may be deleted.
// If null, the task has no expiration.
TTL *int64 `json:"ttl"`
// Suggested time in milliseconds between status checks.
PollInterval *int64 `json:"pollInterval,omitempty"`
}
Task represents the execution state of a request.
func NewTask ¶ added in v0.44.0
func NewTask(taskId string, opts ...TaskOption) Task
NewTask creates a new Task with the given ID and options. The task will be configured based on the provided options. Options are applied in order, allowing for flexible task configuration.
type TaskOption ¶ added in v0.44.0
type TaskOption func(*Task)
TaskOption is a function that configures a Task. It provides a flexible way to set various properties of a Task using the functional options pattern.
func WithTaskCreatedAt ¶ added in v0.44.0
func WithTaskCreatedAt(createdAt string) TaskOption
WithTaskCreatedAt sets a specific creation timestamp for the task. By default, NewTask uses the current time.
func WithTaskPollInterval ¶ added in v0.44.0
func WithTaskPollInterval(intervalMs int64) TaskOption
WithTaskPollInterval sets the suggested polling interval in milliseconds.
func WithTaskStatus ¶ added in v0.44.0
func WithTaskStatus(status TaskStatus) TaskOption
WithTaskStatus sets the status of the task.
func WithTaskStatusMessage ¶ added in v0.44.0
func WithTaskStatusMessage(message string) TaskOption
WithTaskStatusMessage sets a human-readable status message for the task.
func WithTaskTTL ¶ added in v0.44.0
func WithTaskTTL(ttlMs int64) TaskOption
WithTaskTTL sets the time-to-live for the task in milliseconds. After this duration from creation, the task may be deleted.
type TaskParams ¶ added in v0.44.0
type TaskParams struct {
// Requested duration in milliseconds to retain task from creation.
TTL *int64 `json:"ttl,omitempty"`
}
TaskParams represents the task metadata included when augmenting a request.
func NewTaskParams ¶ added in v0.44.0
func NewTaskParams(ttlMs *int64) TaskParams
NewTaskParams creates TaskParams with the given TTL.
type TaskRequestsCapability ¶ added in v0.44.0
type TaskRequestsCapability struct {
// Tool-related capabilities.
Tools *struct {
// Whether tools/call can be augmented with task metadata.
Call *struct{} `json:"call,omitempty"`
} `json:"tools,omitempty"`
// Sampling-related capabilities.
Sampling *struct {
// Whether sampling/createMessage can be augmented with task metadata.
CreateMessage *struct{} `json:"createMessage,omitempty"`
} `json:"sampling,omitempty"`
// Elicitation-related capabilities.
Elicitation *struct {
// Whether elicitation/create can be augmented with task metadata.
Create *struct{} `json:"create,omitempty"`
} `json:"elicitation,omitempty"`
}
TaskRequestsCapability indicates which request types support task augmentation.
type TaskResultParams ¶ added in v0.44.0
type TaskResultParams struct {
TaskId string `json:"taskId"`
}
type TaskResultRequest ¶ added in v0.44.0
type TaskResultRequest struct {
Request
Header http.Header `json:"-"`
Params TaskResultParams `json:"params"`
}
TaskResultRequest retrieves the result of a completed task.
type TaskResultResult ¶ added in v0.44.0
type TaskResultResult struct {
Result
// Tool call result fields (for task-augmented tool calls)
Content []Content `json:"content,omitempty"`
StructuredContent any `json:"structuredContent,omitempty"`
IsError bool `json:"isError,omitempty"`
}
TaskResultResult contains the actual operation result. For task-augmented tool calls, this embeds the CallToolResult fields.
func ParseTaskResultResult ¶ added in v0.47.0
func ParseTaskResultResult(rawMessage *json.RawMessage) (*TaskResultResult, error)
ParseTaskResultResult parses a JSON message and converts it to a TaskResultResult.
type TaskStatus ¶ added in v0.44.0
type TaskStatus string
TaskStatus represents the execution state of a task.
const ( // TaskStatusWorking indicates the request is currently being processed. TaskStatusWorking TaskStatus = "working" // TaskStatusInputRequired indicates the receiver needs input from the requestor. // NOTE: This status is defined by the spec but not yet implemented in this SDK. // The input_required flow requires integration with elicitation which is planned // for a future release. TaskStatusInputRequired TaskStatus = "input_required" // TaskStatusCompleted indicates the request completed successfully. TaskStatusCompleted TaskStatus = "completed" // TaskStatusFailed indicates the request did not complete successfully. TaskStatusFailed TaskStatus = "failed" // TaskStatusCancelled indicates the request was cancelled before completion. TaskStatusCancelled TaskStatus = "cancelled" )
func (TaskStatus) IsTerminal ¶ added in v0.44.0
func (s TaskStatus) IsTerminal() bool
IsTerminal returns true if the task status is terminal (completed, failed, or cancelled).
type TaskStatusNotification ¶ added in v0.44.0
type TaskStatusNotification struct {
Notification
Params TaskStatusNotificationParams `json:"params"`
}
TaskStatusNotification is sent when a task's status changes.
func NewTaskStatusNotification ¶ added in v0.44.0
func NewTaskStatusNotification(task Task) TaskStatusNotification
NewTaskStatusNotification creates a notification for a task status change.
type TaskStatusNotificationParams ¶ added in v0.44.0
type TaskStatusNotificationParams struct {
Task
}
type TaskSupport ¶ added in v0.44.0
type TaskSupport string
TaskSupport indicates how a tool supports task augmentation.
const ( // TaskSupportForbidden means the tool cannot be invoked as a task (default). TaskSupportForbidden TaskSupport = "forbidden" // TaskSupportOptional means the tool can be invoked as a task or normally. TaskSupportOptional TaskSupport = "optional" // TaskSupportRequired means the tool must be invoked as a task. TaskSupportRequired TaskSupport = "required" )
type TasksCapability ¶ added in v0.44.0
type TasksCapability struct {
// Whether the party supports the tasks/list operation.
List *struct{} `json:"list,omitempty"`
// Whether the party supports the tasks/cancel operation.
Cancel *struct{} `json:"cancel,omitempty"`
// Requests that can be augmented with task metadata.
Requests *TaskRequestsCapability `json:"requests,omitempty"`
}
TasksCapability represents the task capabilities that a client or server may support. Tasks enable long-running, asynchronous operations with status polling.
func NewTasksCapability ¶ added in v0.44.0
func NewTasksCapability() *TasksCapability
NewTasksCapability creates a TasksCapability with all operations enabled.
func NewTasksCapabilityWithToolsOnly ¶ added in v0.44.0
func NewTasksCapabilityWithToolsOnly() *TasksCapability
NewTasksCapabilityWithToolsOnly creates a TasksCapability with only tool call support. List and Cancel operations are not enabled with this capability.
type TextContent ¶
type TextContent struct {
Annotated
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
Type string `json:"type"` // Must be "text"
// The text content of the message.
Text string `json:"text"`
}
TextContent represents text provided to or from an LLM. It must have Type set to "text".
func AsTextContent ¶ added in v0.5.0
func AsTextContent(content any) (*TextContent, bool)
AsTextContent attempts to cast the given interface to TextContent
func NewTextContent ¶ added in v0.5.0
func NewTextContent(text string) TextContent
NewTextContent creates text content.
type TextResourceContents ¶
type TextResourceContents struct {
// Raw per‑resource metadata; pass‑through as defined by MCP. Not the same as mcp.Meta.
// Allows _meta to be used for MCP-UI features for example. Does not assume any specific format.
Meta map[string]any `json:"_meta,omitempty"`
// The URI of this resource.
URI string `json:"uri"`
// The MIME type of this resource, if known.
MIMEType string `json:"mimeType,omitempty"`
// The text of the item. This must only be set if the item can actually be
// represented as text (not binary data).
Text string `json:"text"`
}
func AsTextResourceContents ¶ added in v0.5.0
func AsTextResourceContents(content any) (*TextResourceContents, bool)
AsTextResourceContents attempts to cast the given interface to TextResourceContents
type Tool ¶
type Tool struct {
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
// The name of the tool.
Name string `json:"name"`
// Title is an optional human-readable, UI-friendly display name for the tool.
// If not provided, clients should use Annotations.Title (if set) and fall back to Name.
Title string `json:"title,omitempty"`
// A human-readable description of the tool.
Description string `json:"description,omitempty"`
// A JSON Schema object defining the expected parameters for the tool.
InputSchema ToolInputSchema `json:"inputSchema"`
// Alternative to InputSchema - allows arbitrary JSON Schema to be provided
RawInputSchema json.RawMessage `json:"-"` // Hide this from JSON marshaling
// A JSON Schema object defining the expected output returned by the tool .
OutputSchema ToolOutputSchema `json:"outputSchema,omitzero"`
// Optional JSON Schema defining expected output structure
RawOutputSchema json.RawMessage `json:"-"` // Hide this from JSON marshaling
// Optional properties describing tool behavior
Annotations ToolAnnotation `json:"annotations"`
// Support for deferred loading
DeferLoading bool `json:"defer_loading,omitempty"`
// Icons provides visual identifiers for the tool
Icons []Icon `json:"icons,omitempty"`
// Execution describes execution behavior for the tool
Execution *ToolExecution `json:"execution,omitempty"`
}
Tool represents the definition for a tool the client can call.
func NewTool ¶ added in v0.5.0
func NewTool(name string, opts ...ToolOption) Tool
NewTool creates a new Tool with the given name and options. The tool will have an object-type input schema with configurable properties. Options are applied in order, allowing for flexible tool configuration.
func NewToolWithRawSchema ¶ added in v0.10.0
func NewToolWithRawSchema(name, description string, schema json.RawMessage) Tool
NewToolWithRawSchema creates a new Tool with the given name and a raw JSON Schema. This allows for arbitrary JSON Schema to be used for the tool's input schema.
NOTE a Tool built in such a way is incompatible with the ToolOption and runtime errors will result from supplying a ToolOption to a Tool built with this function.
func (Tool) MarshalJSON ¶ added in v0.10.0
MarshalJSON implements the json.Marshaler interface for Tool. It handles marshaling either InputSchema or RawInputSchema based on which is set.
type ToolAnnotation ¶ added in v0.21.0
type ToolAnnotation struct {
// Human-readable title for the tool
Title string `json:"title,omitempty"`
// If true, the tool does not modify its environment
ReadOnlyHint *bool `json:"readOnlyHint,omitempty"`
// If true, the tool may perform destructive updates
DestructiveHint *bool `json:"destructiveHint,omitempty"`
// If true, repeated calls with same args have no additional effect
IdempotentHint *bool `json:"idempotentHint,omitempty"`
// If true, tool interacts with external entities
OpenWorldHint *bool `json:"openWorldHint,omitempty"`
}
type ToolArgumentsSchema ¶ added in v0.39.0
type ToolArgumentsSchema struct {
Defs map[string]any `json:"$defs,omitempty"`
Type string `json:"type"`
Properties map[string]any `json:"properties"`
Required []string `json:"required,omitempty"`
AdditionalProperties any `json:"additionalProperties,omitempty"`
}
ToolArgumentsSchema represents a JSON Schema for tool arguments.
func (ToolArgumentsSchema) MarshalJSON ¶ added in v0.39.0
func (tis ToolArgumentsSchema) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface for ToolArgumentsSchema.
func (*ToolArgumentsSchema) UnmarshalJSON ¶ added in v0.43.2
func (tis *ToolArgumentsSchema) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for ToolArgumentsSchema.
type ToolChoice ¶ added in v0.54.0
type ToolChoice struct {
// Mode controls tool selection. Empty is treated as ToolChoiceModeAuto by
// the client.
Mode ToolChoiceMode `json:"mode,omitempty"`
}
ToolChoice controls tool selection behaviour for a sampling request as defined by the 2025-11-25 protocol revision.
type ToolChoiceMode ¶ added in v0.54.0
type ToolChoiceMode string
ToolChoiceMode controls tool selection behaviour during sampling.
const ( // ToolChoiceModeAuto lets the model decide whether to use tools. This is // the default when ToolChoice is omitted. ToolChoiceModeAuto ToolChoiceMode = "auto" // ToolChoiceModeRequired forces the model to call at least one tool. ToolChoiceModeRequired ToolChoiceMode = "required" // ToolChoiceModeNone disables tool use for this sampling request. ToolChoiceModeNone ToolChoiceMode = "none" )
type ToolExecution ¶ added in v0.44.0
type ToolExecution struct {
// TaskSupport indicates whether the tool supports task augmentation.
TaskSupport TaskSupport `json:"taskSupport,omitempty"`
}
ToolExecution describes execution behavior for a tool.
type ToolInputSchema ¶
type ToolInputSchema ToolArgumentsSchema
ToolInputSchema remains a named type for retro-compatibility, so its JSON methods explicitly forward to ToolArgumentsSchema.
func (ToolInputSchema) MarshalJSON ¶ added in v0.24.1
func (tis ToolInputSchema) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface for ToolInputSchema.
func (*ToolInputSchema) UnmarshalJSON ¶ added in v0.4.0
func (tis *ToolInputSchema) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for ToolInputSchema.
type ToolListChangedNotification ¶ added in v0.4.0
type ToolListChangedNotification struct {
Notification
}
ToolListChangedNotification is an optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.
type ToolOption ¶ added in v0.5.1
type ToolOption func(*Tool)
ToolOption is a function that configures a Tool. It provides a flexible way to set various properties of a Tool using the functional options pattern.
func WithAny ¶ added in v0.42.0
func WithAny(name string, opts ...PropertyOption) ToolOption
WithAny adds an input property named name with no predefined JSON Schema type to the Tool's input schema. The returned ToolOption applies the provided PropertyOption functions to the property's schema, moves a property-level `required` flag into the Tool's InputSchema.Required list if present, and stores the resulting schema under InputSchema.Properties[name].
func WithArray ¶ added in v0.13.0
func WithArray(name string, opts ...PropertyOption) ToolOption
WithArray returns a ToolOption that adds an array-typed property with the given name to a Tool's input schema. It applies provided PropertyOption functions to configure the property's schema, moves a `required` flag from the property schema into the Tool's InputSchema.Required slice when present, and registers the resulting schema under InputSchema.Properties[name].
func WithBoolean ¶ added in v0.5.1
func WithBoolean(name string, opts ...PropertyOption) ToolOption
WithBoolean adds a boolean property to the tool schema. It accepts property options to configure the boolean property's behavior and constraints.
func WithCachedInputSchema ¶ added in v0.51.0
func WithCachedInputSchema[T any](cache *SchemaCache) ToolOption
WithCachedInputSchema is a cache-aware variant of WithInputSchema. It looks up the schema for T in cache using TypeKey; on a miss it falls back to reflection and stores the freshly computed schema back into the cache so that subsequent invocations are served from memory. Passing a nil cache is equivalent to WithInputSchema.
func WithCachedInputSchemaKey ¶ added in v0.51.0
func WithCachedInputSchemaKey[T any](cache *SchemaCache, key string) ToolOption
WithCachedInputSchemaKey is a variant of WithCachedInputSchema that uses an explicit cache key instead of one derived from T's type name. Use this when stability of the key across renames or package moves matters.
An empty key disables the cache entirely for this call: the schema is always reflected fresh and never read from or written to cache. This mirrors WarmFor and prevents distinct types from colliding on a shared empty-string cache slot.
func WithCachedOutputSchema ¶ added in v0.51.0
func WithCachedOutputSchema[T any](cache *SchemaCache) ToolOption
WithCachedOutputSchema is a cache-aware variant of WithOutputSchema. It looks up the schema for T in cache using TypeKey; on a miss it falls back to reflection and stores the freshly computed schema back into the cache. Passing a nil cache is equivalent to WithOutputSchema.
func WithCachedOutputSchemaKey ¶ added in v0.51.0
func WithCachedOutputSchemaKey[T any](cache *SchemaCache, key string) ToolOption
WithCachedOutputSchemaKey is a variant of WithCachedOutputSchema that uses an explicit cache key instead of one derived from T's type name.
An empty key disables the cache entirely for this call: the schema is always reflected fresh and never read from or written to cache. This mirrors WarmFor and prevents distinct types from colliding on a shared empty-string cache slot.
func WithDeferLoading ¶ added in v0.44.0
func WithDeferLoading(deferLoading bool) ToolOption
WithDeferLoading sets the defer_loading flag for the tool. This is used to implement dynamic tool loading/searching patterns.
func WithDescription ¶ added in v0.5.1
func WithDescription(description string) ToolOption
WithDescription adds a description to the Tool. The description should provide a clear, human-readable explanation of what the tool does.
func WithDestructiveHintAnnotation ¶ added in v0.27.0
func WithDestructiveHintAnnotation(value bool) ToolOption
WithDestructiveHintAnnotation sets the DestructiveHint field of the Tool's Annotations. If true, it indicates the tool may perform destructive updates.
func WithIdempotentHintAnnotation ¶ added in v0.27.0
func WithIdempotentHintAnnotation(value bool) ToolOption
WithIdempotentHintAnnotation sets the IdempotentHint field of the Tool's Annotations. If true, it indicates repeated calls with the same arguments have no additional effect.
func WithInputSchema ¶ added in v0.38.0
func WithInputSchema[T any]() ToolOption
WithInputSchema creates a ToolOption that sets the input schema for a tool. It accepts any Go type, usually a struct, and automatically generates a JSON schema from it.
func WithInteger ¶ added in v0.50.0
func WithInteger(name string, opts ...PropertyOption) ToolOption
WithInteger adds an integer property to the tool schema. It accepts property options to configure the integer property's behavior and constraints.
func WithNumber ¶ added in v0.5.1
func WithNumber(name string, opts ...PropertyOption) ToolOption
WithNumber adds a number property to the tool schema. It accepts property options to configure the number property's behavior and constraints.
func WithObject ¶ added in v0.13.0
func WithObject(name string, opts ...PropertyOption) ToolOption
WithObject adds an object property to the tool schema. It accepts property options to configure the object property's behavior and constraints.
func WithOpenWorldHintAnnotation ¶ added in v0.27.0
func WithOpenWorldHintAnnotation(value bool) ToolOption
WithOpenWorldHintAnnotation sets the OpenWorldHint field of the Tool's Annotations. If true, it indicates the tool interacts with external entities.
func WithOutputSchema ¶ added in v0.36.0
func WithOutputSchema[T any]() ToolOption
WithOutputSchema creates a ToolOption that sets the output schema for a tool. It accepts any Go type, usually a struct, and automatically generates a JSON schema from it.
func WithRawInputSchema ¶ added in v0.38.0
func WithRawInputSchema(schema json.RawMessage) ToolOption
WithRawInputSchema sets a raw JSON schema for the tool's input. Use this when you need full control over the schema or when working with complex schemas that can't be generated from Go types. The jsonschema library can handle complex schemas and provides nice extension points, so be sure to check that out before using this.
func WithRawOutputSchema ¶ added in v0.36.0
func WithRawOutputSchema(schema json.RawMessage) ToolOption
WithRawOutputSchema sets a raw JSON schema for the tool's output. Use this when you need full control over the schema or when working with complex schemas that can't be generated from Go types. The jsonschema library can handle complex schemas and provides nice extension points, so be sure to check that out before using this.
func WithReadOnlyHintAnnotation ¶ added in v0.27.0
func WithReadOnlyHintAnnotation(value bool) ToolOption
WithReadOnlyHintAnnotation sets the ReadOnlyHint field of the Tool's Annotations. If true, it indicates the tool does not modify its environment.
func WithSchemaAdditionalProperties ¶ added in v0.44.0
func WithSchemaAdditionalProperties(schema any) ToolOption
WithSchemaAdditionalProperties sets the additionalProperties field on the tool's input schema. It accepts false (disallow extra properties), true (allow any), or a schema map to validate additional properties against.
func WithString ¶ added in v0.5.1
func WithString(name string, opts ...PropertyOption) ToolOption
WithString adds a string property to the tool schema. It accepts property options to configure the string property's behavior and constraints.
func WithTaskSupport ¶ added in v0.44.0
func WithTaskSupport(support TaskSupport) ToolOption
WithTaskSupport sets the task support mode for the tool. It configures whether the tool can be invoked as a task (asynchronously). Valid values are TaskSupportForbidden (default), TaskSupportOptional, or TaskSupportRequired.
func WithTitleAnnotation ¶ added in v0.27.0
func WithTitleAnnotation(title string) ToolOption
WithTitleAnnotation sets the Title field of the Tool's Annotations. It provides a human-readable title for the tool.
func WithToolAnnotation ¶ added in v0.21.0
func WithToolAnnotation(annotation ToolAnnotation) ToolOption
WithToolAnnotation adds optional hints about the Tool.
func WithToolIcons ¶ added in v0.44.0
func WithToolIcons(icons ...Icon) ToolOption
WithToolIcons adds icons to the Tool. Icons provide visual identifiers for the tool.
func WithToolTitle ¶ added in v0.54.0
func WithToolTitle(title string) ToolOption
WithToolTitle sets the optional human-readable display title for the Tool. Per the MCP spec, clients should prefer Title over Annotations.Title and Name for display.
type ToolOutputSchema ¶ added in v0.39.0
type ToolOutputSchema ToolArgumentsSchema
func (ToolOutputSchema) MarshalJSON ¶ added in v0.44.0
func (tis ToolOutputSchema) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface for ToolOutputSchema.
func (*ToolOutputSchema) UnmarshalJSON ¶ added in v0.44.0
func (tis *ToolOutputSchema) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for ToolOutputSchema.
type ToolResultContent ¶ added in v0.49.0
type ToolResultContent struct {
Annotated
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
Type string `json:"type"` // Must be "tool_result"
// ToolUseID is the ID of the tool use this result corresponds to.
// This MUST match the ID from a previous ToolUseContent.
ToolUseID string `json:"toolUseId"`
// Content is the unstructured result content of the tool use.
Content []Content `json:"content"`
// Whether the tool use resulted in an error.
IsError bool `json:"isError,omitempty"`
}
ToolResultContent represents the result of a tool invocation within a sampling message. It must have Type set to "tool_result".
func AsToolResultContent ¶ added in v0.49.0
func AsToolResultContent(content any) (*ToolResultContent, bool)
AsToolResultContent attempts to cast the given interface to ToolResultContent
func NewToolResultContent ¶ added in v0.49.0
func NewToolResultContent(toolUseID string, content []Content, isError bool) ToolResultContent
NewToolResultContent creates a new ToolResultContent with the given tool use ID, content, and error flag.
func (*ToolResultContent) UnmarshalJSON ¶ added in v0.49.0
func (t *ToolResultContent) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for ToolResultContent to handle the nested Content interface slice.
type ToolUseContent ¶ added in v0.49.0
type ToolUseContent struct {
Annotated
// Meta is a metadata object that is reserved by MCP for storing additional information.
Meta *Meta `json:"_meta,omitempty"`
Type string `json:"type"` // Must be "tool_use"
// ID is a unique identifier for this tool use, used to match tool results to their corresponding tool uses.
ID string `json:"id"`
// Name is the name of the tool to call.
Name string `json:"name"`
// Input contains the arguments to pass to the tool, conforming to the tool's input schema.
Input any `json:"input"`
}
ToolUseContent represents a request from the assistant to call a tool within a sampling message. It must have Type set to "tool_use".
func AsToolUseContent ¶ added in v0.49.0
func AsToolUseContent(content any) (*ToolUseContent, bool)
AsToolUseContent attempts to cast the given interface to ToolUseContent
func NewToolUseContent ¶ added in v0.49.0
func NewToolUseContent(id, name string, input any) ToolUseContent
NewToolUseContent creates a new ToolUseContent with the given id, tool name, and input arguments.
type TypedToolHandlerFunc ¶ added in v0.29.0
type TypedToolHandlerFunc[T any] func(ctx context.Context, request CallToolRequest, args T) (*CallToolResult, error)
TypedToolHandlerFunc is a function that handles a tool call with typed arguments
type URITemplate ¶ added in v0.14.1
type URITemplate struct {
*uritemplate.Template
}
func (*URITemplate) MarshalJSON ¶ added in v0.14.1
func (t *URITemplate) MarshalJSON() ([]byte, error)
func (*URITemplate) UnmarshalJSON ¶ added in v0.14.1
func (t *URITemplate) UnmarshalJSON(data []byte) error
type URLElicitationRequiredError ¶ added in v0.44.0
type URLElicitationRequiredError struct {
Elicitations []ElicitationParams `json:"elicitations"`
}
URLElicitationRequiredError is returned when the server requires URL elicitation to proceed.
func (URLElicitationRequiredError) Error ¶ added in v0.44.0
func (e URLElicitationRequiredError) Error() string
func (URLElicitationRequiredError) Is ¶ added in v0.44.0
func (e URLElicitationRequiredError) Is(target error) bool
Is implements the errors.Is interface for better error handling
func (URLElicitationRequiredError) JSONRPCError ¶ added in v0.44.0
func (e URLElicitationRequiredError) JSONRPCError() JSONRPCError
type UnsubscribeParams ¶ added in v0.31.0
type UnsubscribeParams struct {
// The URI of the resource to unsubscribe from.
URI string `json:"uri"`
}
type UnsubscribeRequest ¶ added in v0.4.0
type UnsubscribeRequest struct {
Request
Params UnsubscribeParams `json:"params"`
Header http.Header `json:"-"`
}
UnsubscribeRequest is sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.
type UnsupportedProtocolVersionData ¶ added in v1.0.0
type UnsupportedProtocolVersionData struct {
// Supported lists the protocol versions the server implements.
Supported []string `json:"supported"`
// Requested is the version the rejected request declared.
Requested string `json:"requested"`
}
UnsupportedProtocolVersionData is the JSON payload carried in the data field of an UNSUPPORTED_PROTOCOL_VERSION error.
type UnsupportedProtocolVersionError ¶ added in v0.35.0
type UnsupportedProtocolVersionError struct {
// Version is the protocol version that was rejected.
Version string
// Supported lists the versions the peer does support, when it told us.
Supported []string
}
UnsupportedProtocolVersionError is returned when a peer responds with, or rejects, a protocol version that this side does not support.
func (UnsupportedProtocolVersionError) Error ¶ added in v0.35.0
func (e UnsupportedProtocolVersionError) Error() string
func (UnsupportedProtocolVersionError) Is ¶ added in v0.35.0
func (e UnsupportedProtocolVersionError) Is(target error) bool
Is implements the errors.Is interface for better error handling
func (UnsupportedProtocolVersionError) JSONRPCError ¶ added in v1.0.0
func (e UnsupportedProtocolVersionError) JSONRPCError() JSONRPCError
JSONRPCError renders the error as a JSON-RPC error response body.