Documentation
¶
Overview ¶
Package mcp implements the Model Context Protocol HTTP endpoint, Skills extension, and SDK DTOs.
Implement SubscriptionRegistry to publish resource changes. Draft clients use subscriptions/listen. For released Streamable HTTP clients, configure one NewSessionStore for the server lifetime and pass it through Handler.Sessions. Its owner returns a stable authenticated principal key, including login session, task, or authorization scope boundaries, never credentials. Authenticate every request before dispatch; a session ID grants no authorization. Handlers and their authorized registries may be request-local while sharing the store. Bind streaming request contexts to the host's login-session expiry and revocation, and recheck changing workspace or role authorization in registries.
Released clients initialize an owner-bound Mcp-Session-Id, subscribe with resources/subscribe, and open a GET with Accept: text/event-stream. Resource discovery activates resource-list notifications. Subscriptions survive stream reconnection; each reconnect invalidates the current subscribed snapshots so clients catch up with resources/read. Clients unsubscribe with resources/unsubscribe and close the session with HTTP DELETE. Disconnected sessions expire after fifteen idle minutes. Streams deliver snapshot invalidations, not a durable event log, so clients read the resource and compare stable item IDs. A resource update never wakes a model by itself; voice clients distinguish passive context from alerts that require a response.
openai/session in request _meta is the client's optional conversation identity, independent of the host login session. Registry.Instructions receives request metadata, and SubscriptionRegistry.SubscribeResourceUpdates receives the complete subscription params. Resource reads, including initial subscription snapshots and deduplication reads, receive the same metadata. Hosts own session validation, bounded retention, authorization, and sessionless fallback.
Index ¶
- Constants
- Variables
- func AddHeaderToProperty(schema *jsonschema.Schema, property, header string)
- func DecodeToolArgument[T any](data json.RawMessage) (T, error)
- func ErrInvalidParams(format string, args ...any) error
- func SchemaFor[T any]() *jsonschema.Schema
- func ValidateToolSchema(schema *jsonschema.Schema) error
- type Annotations
- type CacheScope
- type Capabilities
- type ClientCapabilities
- type ContentBlock
- type ContentType
- type ElicitationCapability
- type ErrorCode
- type ErrorOutput
- type Extensions
- type Handler
- type HeaderParam
- type Icon
- type Implementation
- type JSONRPCError
- type JSONRPCNotification
- type JSONRPCRequest
- type JSONRPCResponse
- type MetaObject
- type Method
- type NotificationMethod
- type OpenAIRequestMeta
- type OpenAIUserLocation
- type PaginatedRequestParams
- type PromptsCapability
- type RawToolResult
- type Registry
- type RequestMeta
- type RequestParams
- type ResourceContent
- type ResourceDescriptor
- type ResourceLink
- type ResourceTemplateDescriptor
- type ResourceTemplatesListResult
- type ResourceTemplatesRegistry
- type ResourceUpdate
- type ResourcesCapability
- type ResourcesListResult
- type ResourcesReadParams
- type ResourcesReadResult
- type ResultType
- type Role
- type SamplingCapability
- type ServerDiscoverResult
- type SessionStore
- type Skill
- type SkillResource
- type SkillsGetParams
- type SkillsGetResult
- type SkillsListResult
- type SkillsRegistry
- type SubscriptionFilter
- type SubscriptionNotificationParams
- type SubscriptionRegistry
- type SubscriptionsInitialStateParams
- type SubscriptionsListenParams
- type TextOutput
- type ToolAnnotations
- type ToolCallResult
- type ToolDescriptor
- type ToolHandler
- type ToolRequest
- type ToolResult
- type ToolSpec
- type ToolsCallParams
- type ToolsCapability
- type ToolsListResult
Constants ¶
const ( // ProtocolVersion is the native MCP protocol version. // // Native support owns server/discover, required per-request _meta, // Mcp-Method/Mcp-Name headers, resultType, ttlMs, and cacheScope. Released // initialize-based versions 2025-06-18 and 2025-11-25 are isolated in // compat.go so their DTOs can be deleted when those clients are no longer // supported. ProtocolVersion = "2026-07-28" // DefaultTTLMS is the default cache lifetime returned by MCP list/read methods. DefaultTTLMS = 10_000 // SkillsExtension identifies the official MCP Skills extension. SkillsExtension = "io.modelcontextprotocol/skills" // OAuthClientCredentialsExtension identifies the official MCP OAuth // Client Credentials extension. Its authorization backend is the OAuth 2.0 // client-credentials grant (RFC 6749 §4.4) in the oauthserver package. OAuthClientCredentialsExtension = "io.modelcontextprotocol/oauth-client-credentials" )
const ToolErrorCodeMetaKey = "com.fghbuild.gomode/errorCode"
ToolErrorCodeMetaKey identifies an application semantic error code on a tool result.
The value is a string from the application's error-code catalog. It is carried in _meta so tool execution errors retain their established content and structuredContent envelopes.
Variables ¶
var SDKAPI = apispec.Config[string]{ Routes: []apispec.Route{ { Name: "mcp", Doc: "Sends a raw MCP JSON-RPC request to the client base URL. The caller supplies required MCP transport headers.", Method: "POST", Path: "", Category: "MCP", Req: reflect.TypeFor[JSONRPCRequest](), Resp: reflect.TypeFor[JSONRPCResponse](), HeadersArg: true, }, }, SDKPackagePaths: map[string]struct{}{ reflect.TypeFor[JSONRPCRequest]().PkgPath(): {}, }, ExtraSeeds: []reflect.Type{ reflect.TypeFor[ServerDiscoverResult](), reflect.TypeFor[PaginatedRequestParams](), reflect.TypeFor[ToolsListResult](), reflect.TypeFor[ToolsCallParams](), reflect.TypeFor[ToolCallResult](), reflect.TypeFor[ResourcesListResult](), reflect.TypeFor[ResourceTemplatesListResult](), reflect.TypeFor[ResourcesReadParams](), reflect.TypeFor[ResourcesReadResult](), reflect.TypeFor[SubscriptionsListenParams](), reflect.TypeFor[JSONRPCNotification](), reflect.TypeFor[SubscriptionNotificationParams](), reflect.TypeFor[SubscriptionsInitialStateParams](), }, DocumentExtraSeeds: true, KotlinPackage: "com.fghbuild.mcp.sdk.v1", APIDocTitle: "MCP API Reference", APIDocIntro: "JSON-RPC MCP endpoint client. Construct clients with the MCP endpoint URL advertised by the service. Requests must include MCP transport headers such as `Mcp-Protocol-Version` and `Mcp-Method`; method-specific requests may also require `Mcp-Name` and `Mcp-Param-*` headers.", ErrorDoc: "MCP errors are JSON-RPC error objects in `JSONRPCResponse.error`. Transport-layer validation failures may use non-2xx HTTP statuses; method-level JSON-RPC errors can still use HTTP 200. Tool execution errors preserve their human-readable content and expose an application semantic code in `result._meta[\"com.fghbuild.gomode/errorCode\"]` when one is available.", SpecialTypes: []apispec.SpecialType{ { Type: reflect.TypeFor[RequestMeta](), TSType: "RequestMeta", KTType: "RequestMeta", SwiftType: "RequestMeta", DocType: "RequestMeta", TSSource: requestMetaTS, KotlinSource: requestMetaKotlin, SwiftSource: requestMetaSwift, Dependencies: []reflect.Type{reflect.TypeFor[Implementation](), reflect.TypeFor[ClientCapabilities](), reflect.TypeFor[OpenAIUserLocation]()}, KotlinSymbols: []string{"RequestMetaSerializer"}, SwiftSymbols: []string{"RequestMetaKey"}, }, { Type: reflect.TypeFor[json.RawMessage](), TSType: "unknown /* json.RawMessage */", KTType: "JsonElement", SwiftType: "JSONValue", DocType: "JSONValue", TSValidate: "%[1]s", }, { Type: reflect.TypeFor[any](), TSType: "unknown", KTType: "JsonElement", SwiftType: "JSONValue", DocType: "JSONValue", TSValidate: "%[1]s", }, { Type: reflect.TypeFor[jsonschema.Schema](), TSType: "unknown /* JSON Schema */", KTType: "JsonElement", SwiftType: "JSONValue", DocType: "JSONSchema", TSValidate: "%[1]s", }, }, ErrorModel: apispec.ClientErrorModel{ TypeName: "JSONRPCResponse", TSCodeExpr: "String(err.error?.code ?? \"UNKNOWN\")", TSMessageExpr: "err.error?.message ?? \"\"", TSDetailsExpr: "undefined", KTCodeExpr: "err.error?.code?.toString() ?: \"UNKNOWN\"", KTMessageExpr: "err.error?.message ?: \"\"", KTDetailsExpr: "null", SwiftCodeExpr: "String(errResp.error?.code ?? 0)", SwiftMessageExpr: "errResp.error?.message ?? \"\"", SwiftDetailsExpr: "nil", }, }
SDKAPI is the SDK generation specification for the MCP API.
Immutable
Functions ¶
func AddHeaderToProperty ¶
func AddHeaderToProperty(schema *jsonschema.Schema, property, header string)
AddHeaderToProperty marks a primitive schema property as mirrored in an MCP parameter header.
func DecodeToolArgument ¶
func DecodeToolArgument[T any](data json.RawMessage) (T, error)
DecodeToolArgument decodes strict JSON tool arguments into T.
func ErrInvalidParams ¶
ErrInvalidParams marks a registry error as client-caused invalid params.
func SchemaFor ¶
func SchemaFor[T any]() *jsonschema.Schema
SchemaFor reflects T into a JSON schema suitable for MCP descriptors.
func ValidateToolSchema ¶
func ValidateToolSchema(schema *jsonschema.Schema) error
ValidateToolSchema reports whether a tool input or output schema is safe to advertise and serve.
It rejects a schema that cannot be encoded for the wire, that requires a property it does not declare, or that mirrors parameter headers in a way the request path rejects (see HeaderParams). Startup and the tool catalog test call it so a malformed catalog fails before a client sees it.
Types ¶
type Annotations ¶
type Annotations struct {
// Audience describes who the data is intended for.
Audience []Role `json:"audience,omitempty"`
// Priority describes importance from 0 to 1, with 1 most important.
Priority *int `json:"priority,omitempty"`
// LastModified is an ISO 8601 timestamp for the last modification time.
LastModified string `json:"lastModified,omitempty"`
}
Annotations provide optional metadata for MCP resources and content.
func (Annotations) IsZero ¶
func (a Annotations) IsZero() bool
IsZero reports whether annotations are absent for json omitzero.
type CacheScope ¶
type CacheScope string
CacheScope describes who may cache an MCP result.
const ( CacheScopePublic CacheScope = "public" CacheScopePrivate CacheScope = "private" )
Cache scope values used by MCP responses.
type Capabilities ¶
type Capabilities struct {
// Experimental contains non-standard capabilities supported by the server.
Experimental Extensions `json:"experimental,omitempty"`
// DeprecatedLogging is present if the server supports sending log messages to the client.
//
// Deprecated as of protocol version 2026-07-28, but still present in that
// schema. This is native 2026-07-28 compatibility, not released-version
// compat.go support; remove it only after the upstream 2026+ schema drops it.
DeprecatedLogging MetaObject `json:"logging,omitempty"`
// Completions is present if the server supports argument completion suggestions.
Completions MetaObject `json:"completions,omitempty"`
// Prompts is present if the server offers prompt templates.
Prompts *PromptsCapability `json:"prompts,omitempty"`
// Resources is present if the server offers resources to read.
Resources ResourcesCapability `json:"resources,omitzero"`
// Tools is present if the server offers tools to call.
Tools ToolsCapability `json:"tools"`
// Extensions contains optional MCP extensions supported by the server.
Extensions Extensions `json:"extensions,omitempty"`
}
Capabilities describes server-supported MCP features.
type ClientCapabilities ¶
type ClientCapabilities struct {
// Experimental contains non-standard capabilities supported by the client.
Experimental Extensions `json:"experimental,omitempty"`
// DeprecatedRoots is present if the client supports listing roots.
//
// Deprecated as of protocol version 2026-07-28, but still present in that
// schema. This is native 2026-07-28 compatibility, not released-version
// compat.go support; remove it only after the upstream 2026+ schema drops it.
DeprecatedRoots MetaObject `json:"roots,omitempty"`
// DeprecatedSampling is present if the client supports server-initiated LLM sampling.
//
// Deprecated as of protocol version 2026-07-28, but still present in that
// schema. This is native 2026-07-28 compatibility, not released-version
// compat.go support; remove it only after the upstream 2026+ schema drops it.
DeprecatedSampling *SamplingCapability `json:"sampling,omitempty"`
// Elicitation is present if the client supports server-initiated user elicitation.
Elicitation *ElicitationCapability `json:"elicitation,omitempty"`
// Extensions contains optional MCP extensions supported by the client.
Extensions Extensions `json:"extensions,omitempty"`
}
ClientCapabilities describes capabilities the client supports for a request.
type ContentBlock ¶
type ContentBlock struct {
Meta MetaObject `json:"_meta,omitempty"`
Icons []Icon `json:"icons,omitempty"`
// Type identifies the content variant.
Type ContentType `json:"type"`
// Name is used by resource_link content.
Name string `json:"name,omitempty"`
// Title is a human-readable display name.
Title string `json:"title,omitempty"`
// Text is the text content for text blocks.
Text string `json:"text,omitempty"`
// Data is base64-encoded data for image and audio blocks.
Data string `json:"data,omitempty"`
// URI identifies resource_link content.
URI string `json:"uri,omitempty"`
// Description helps clients and LLMs understand linked resources.
Description string `json:"description,omitempty"`
// MimeType is required for image and audio content and optional for resources.
MimeType string `json:"mimeType,omitempty"`
// Size is the raw resource size in bytes, if known.
Size int64 `json:"size,omitzero"`
// Resource contains embedded resource contents for resource blocks.
Resource ResourceContent `json:"resource,omitzero"`
// Annotations provide optional client metadata.
Annotations Annotations `json:"annotations,omitzero"`
}
ContentBlock is an MCP content item.
The draft schema models this as a union. Validate checks that only fields for the selected content type are present.
func (*ContentBlock) Validate ¶
func (c *ContentBlock) Validate() error
Validate checks that the content block matches the draft schema variant for its type.
type ContentType ¶
type ContentType string
ContentType identifies the kind of content block in a tool result.
const ( ContentTypeAudio ContentType = "audio" ContentTypeImage ContentType = "image" ContentTypeResource ContentType = "resource" ContentTypeResourceLink ContentType = "resource_link" ContentTypeText ContentType = "text" )
Content type values used by MCP tool results.
type ElicitationCapability ¶
type ElicitationCapability struct {
// Form declares support for form-mode elicitation.
Form MetaObject `json:"form,omitempty"`
// URL declares support for URL-mode elicitation.
URL MetaObject `json:"url,omitempty"`
}
ElicitationCapability describes client elicitation support.
type ErrorCode ¶
type ErrorCode int
ErrorCode is a JSON-RPC error code used by MCP responses.
const ( ParseErrorCode ErrorCode = -32700 InvalidRequestCode ErrorCode = -32600 MethodNotFoundCode ErrorCode = -32601 InvalidParamsCode ErrorCode = -32602 InternalErrorCode ErrorCode = -32603 MissingRequiredClientCapabilityCode ErrorCode = -32003 UnsupportedProtocolVersionCode ErrorCode = -32004 )
JSON-RPC error codes returned by the MCP handler.
type ErrorOutput ¶
type ErrorOutput struct {
Error string `json:"error" jsonschema_description:"Human-readable error message"`
}
ErrorOutput is the standard human-readable tool error payload.
type Extensions ¶
type Extensions map[string]json.RawMessage
Extensions stores namespaced MCP extension payloads.
The draft schema constrains values to JSON objects. RawMessage keeps the DTO forward-compatible; validate extension values before depending on object shape.
type Handler ¶
type Handler struct {
Registry Registry
ServerInfo Implementation
// OAuthClientCredentials advertises the official
// io.modelcontextprotocol/oauth-client-credentials extension in the
// server/discover capabilities (SEP-2133). Set it when the host's
// authorization server accepts OAuth 2.0 client-credentials grants
// (RFC 6749 §4.4), letting machine-to-machine clients skip interactive
// user authorization.
OAuthClientCredentials bool
// Sessions owns released-protocol notification sessions independently of
// request-local registry authorization. Hosts may share it across handlers.
// A nil store keeps released clients stateless.
Sessions *SessionStore
// Log receives request failures and stream diagnostics. It is required.
Log *slog.Logger
}
Handler serves the MCP JSON-RPC HTTP endpoint.
type HeaderParam ¶
HeaderParam maps an MCP input-schema property to a required HTTP header.
func HeaderParams ¶
func HeaderParams(schema *jsonschema.Schema) ([]HeaderParam, error)
HeaderParams returns the parameter headers mirrored by a tool schema, one per property marked with x-mcp-header.
It walks the whole schema, so nested properties, array items, and union branches are included. A malformed marker (wrong type or invalid token) or two properties claiming the same header is an error; ValidateToolSchema surfaces those at startup and in catalog tests.
type Icon ¶
type Icon struct {
// Src is an icon URI, such as an HTTPS URL or data URI.
Src string `json:"src"`
// MimeType overrides a missing or generic source MIME type.
MimeType string `json:"mimeType,omitempty"`
// Sizes lists supported dimensions, such as "48x48" or "any".
Sizes []string `json:"sizes,omitempty"`
// Theme indicates whether the icon targets a light or dark background.
Theme string `json:"theme,omitempty"`
}
Icon describes an optionally-sized icon for UI display.
type Implementation ¶
type Implementation struct {
// Icons contains optional sized icons for UI display.
Icons []Icon `json:"icons,omitempty"`
// Name is the programmatic implementation identifier.
Name string `json:"name"`
// Title is a human-readable display name.
Title string `json:"title,omitempty"`
// Version is the implementation version.
Version string `json:"version"`
// Description explains what this implementation does.
Description string `json:"description,omitempty"`
// WebsiteURL is an optional website for this implementation.
WebsiteURL string `json:"websiteUrl,omitempty"`
}
Implementation describes an MCP client or server implementation.
type JSONRPCError ¶
type JSONRPCError struct {
// Code identifies the error type.
Code ErrorCode `json:"code"`
// Message is a concise single-sentence description of the error.
Message string `json:"message"`
// Data carries sender-defined additional error information.
Data any `json:"data,omitempty"`
}
JSONRPCError is a JSON-RPC error object.
type JSONRPCNotification ¶
type JSONRPCNotification struct {
JSONRPC string `json:"jsonrpc"`
Method NotificationMethod `json:"method"`
Params any `json:"params,omitempty"`
}
JSONRPCNotification is a JSON-RPC notification that does not expect a response.
type JSONRPCRequest ¶
type JSONRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitzero"`
Method Method `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
JSONRPCRequest is a JSON-RPC request that expects a response.
type JSONRPCResponse ¶
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitzero"`
Result any `json:"result,omitempty"`
Error *JSONRPCError `json:"error,omitempty"`
}
JSONRPCResponse is a JSON-RPC response containing either a result or an error.
type MetaObject ¶
MetaObject is metadata attached to MCP interactions.
MCP reserves protocol-level key names. Implementations should use prefixed reverse-DNS keys for their own metadata.
type Method ¶
type Method string
Method is an MCP JSON-RPC method name.
const ( MethodServerDiscover Method = "server/discover" MethodToolsList Method = "tools/list" MethodToolsCall Method = "tools/call" MethodResourcesList Method = "resources/list" MethodResourcesRead Method = "resources/read" MethodResourceTemplatesList Method = "resources/templates/list" MethodSkillsGet Method = "skills/get" MethodSkillsList Method = "skills/list" MethodSubscriptionsListen Method = "subscriptions/listen" )
MCP method names supported by the handler.
type NotificationMethod ¶
type NotificationMethod string
NotificationMethod is an MCP JSON-RPC notification method name.
const ( NotificationMethodSubscriptionsAcknowledged NotificationMethod = "notifications/subscriptions/acknowledged" NotificationMethodSubscriptionsInitialState NotificationMethod = "notifications/subscriptions/initial_state" NotificationMethodResourcesListChanged NotificationMethod = "notifications/resources/list_changed" NotificationMethodResourcesUpdated NotificationMethod = "notifications/resources/updated" )
MCP notification method names sent by the handler.
type OpenAIRequestMeta ¶
type OpenAIRequestMeta struct {
// Locale requests a language and regional convention using a BCP 47 tag,
// such as en-CA or fr-CA.
Locale string `json:"openai/locale,omitempty"`
// Organization carries an anonymized identifier for the caller's ChatGPT
// organization, when the client provides one.
Organization string `json:"openai/organization,omitempty"`
// Session groups tool calls from the same ChatGPT conversation using an
// anonymized conversation identifier.
Session string `json:"openai/session,omitempty"`
// Subject carries an anonymized user identifier for call correlation or
// rate-limit accounting; it is not an authentication credential.
Subject string `json:"openai/subject,omitempty"`
// UserAgent is a best-effort client hint for analytics or presentation;
// it is not a reliable indication of client capabilities.
UserAgent string `json:"openai/userAgent,omitempty"`
// UserLocation is an optional formatting hint supplied by the client.
UserLocation OpenAIUserLocation `json:"openai/userLocation,omitzero"`
}
OpenAIRequestMeta contains OpenAI-specific client metadata extensions. Embedding it in RequestMeta keeps its namespaced fields flat on the wire. These optional, self-reported values do not establish authenticated identity.
Reference: https://developers.openai.com/plugins/reference#_meta-fields-the-client-provides
type OpenAIUserLocation ¶
type OpenAIUserLocation struct {
// Timezone is the caller device's IANA timezone, such as America/Toronto.
Timezone string `json:"timezone,omitempty"`
}
OpenAIUserLocation contains optional client location hints. Only the device's IANA timezone is used; these untrusted hints must not influence authorization.
type PaginatedRequestParams ¶
type PaginatedRequestParams struct {
Meta RequestMeta `json:"_meta"`
// Cursor is an opaque pagination token.
Cursor string `json:"cursor,omitempty"`
}
PaginatedRequestParams contains common request metadata and an optional cursor.
type PromptsCapability ¶
type PromptsCapability struct {
// ListChanged indicates support for prompt list change notifications.
ListChanged bool `json:"listChanged,omitempty"`
}
PromptsCapability describes prompt support advertised by the server.
type RawToolResult ¶
type RawToolResult struct {
Meta MetaObject
Structured any
IsError bool
}
RawToolResult is the transport-neutral output from a tool handler.
type Registry ¶
type Registry interface {
// Instructions returns caller guidance, including conversation-specific
// context from metadata. Meta must be non-nil and must not be modified.
Instructions(ctx context.Context, meta *RequestMeta) (string, error)
Tools(ctx context.Context) ([]ToolDescriptor, error)
// CallTool executes the decoded request. Params must be non-nil and must
// not be modified during the call.
CallTool(ctx context.Context, params *ToolsCallParams) (RawToolResult, error)
ListResources(ctx context.Context, cursor string) (ResourcesListResult, error)
Resources(ctx context.Context) iter.Seq2[ResourceDescriptor, error]
// ReadResource reads the decoded request, including caller metadata. Params
// must be non-nil and must not be modified during the call.
ReadResource(ctx context.Context, params *ResourcesReadParams) (ResourcesReadResult, error)
}
Registry supplies MCP tools, resources, instructions, and subscription invalidations to Handler.
type RequestMeta ¶
type RequestMeta struct {
// ProtocolVersion is the MCP protocol version used for this request.
//
// For HTTP, it must match the MCP-Protocol-Version header.
ProtocolVersion string `json:"io.modelcontextprotocol/protocolVersion"`
// ClientInfo identifies the client software making the request.
ClientInfo Implementation `json:"io.modelcontextprotocol/clientInfo"`
// ClientCapabilities declares client capabilities for this request.
ClientCapabilities ClientCapabilities `json:"io.modelcontextprotocol/clientCapabilities"`
// ProgressToken requests out-of-band progress notifications for this request.
ProgressToken any `json:"progressToken,omitempty"`
// DeprecatedLogLevel requests server log message notifications for this request.
//
// Deprecated as of protocol version 2026-07-28, but still present in that
// schema. This is native 2026-07-28 compatibility, not released-version
// compat.go support; remove it only after the upstream 2026+ schema drops it.
DeprecatedLogLevel string `json:"io.modelcontextprotocol/logLevel,omitempty"`
OpenAIRequestMeta
// Extra preserves forward-compatible metadata fields.
Extra MetaObject `json:"-"`
}
RequestMeta is the metadata object required in MCP request params.
func (RequestMeta) MarshalJSON ¶
func (m RequestMeta) MarshalJSON() ([]byte, error)
MarshalJSON encodes RequestMeta with preserved forward-compatible _meta fields.
func (*RequestMeta) UnmarshalJSON ¶
func (m *RequestMeta) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RequestMeta while preserving forward-compatible _meta fields.
type RequestParams ¶
type RequestParams struct {
Meta RequestMeta `json:"_meta"`
}
RequestParams contains common MCP request metadata.
type ResourceContent ¶
type ResourceContent struct {
Meta MetaObject `json:"_meta,omitempty"`
// URI identifies this resource.
URI string `json:"uri"`
// MimeType is the resource MIME type, if known.
MimeType string `json:"mimeType,omitempty"`
// Text contains textual resource contents.
Text string `json:"text,omitempty"`
// Blob contains base64-encoded binary resource contents.
Blob string `json:"blob,omitempty"`
}
ResourceContent contains resource data returned by resources/read.
func (ResourceContent) IsZero ¶
func (r ResourceContent) IsZero() bool
IsZero reports whether resource content is absent for json omitzero.
func (ResourceContent) Validate ¶
func (r ResourceContent) Validate() error
Validate checks that resource content matches exactly one draft schema variant.
type ResourceDescriptor ¶
type ResourceDescriptor struct {
Meta MetaObject `json:"_meta,omitempty"`
Icons []Icon `json:"icons,omitempty"`
// URI identifies this resource.
URI string `json:"uri"`
// Name is the programmatic resource identifier.
Name string `json:"name"`
// Title is a human-readable display name.
Title string `json:"title,omitempty"`
// Description helps clients and LLMs understand the resource.
Description string `json:"description,omitempty"`
// MimeType is the resource MIME type, if known.
MimeType string `json:"mimeType,omitempty"`
// Annotations provide optional client metadata.
Annotations *Annotations `json:"annotations,omitempty"`
// Size is the raw resource size in bytes, if known.
Size int64 `json:"size,omitzero"`
}
ResourceDescriptor describes a resource the server can read.
type ResourceLink ¶
type ResourceLink struct {
Type ContentType `json:"type"`
Icons []Icon `json:"icons,omitempty"`
// Name is the programmatic resource identifier.
Name string `json:"name"`
// Title is a human-readable display name.
Title string `json:"title,omitempty"`
// URI identifies the resource.
URI string `json:"uri"`
// Description helps clients and LLMs understand the resource.
Description string `json:"description,omitempty"`
// MimeType is the resource MIME type, if known.
MimeType string `json:"mimeType,omitempty"`
// Size is the raw resource size in bytes, if known.
Size int64 `json:"size,omitzero"`
}
ResourceLink identifies an MCP resource referenced from content.
func (ResourceLink) MarshalJSON ¶
func (r ResourceLink) MarshalJSON() ([]byte, error)
MarshalJSON encodes resource links with the schema-required resource_link type.
type ResourceTemplateDescriptor ¶
type ResourceTemplateDescriptor struct {
Meta MetaObject `json:"_meta,omitempty"`
Icons []Icon `json:"icons,omitempty"`
// Name is the programmatic template identifier.
Name string `json:"name"`
// Title is a human-readable display name.
Title string `json:"title,omitempty"`
// URITemplate is an RFC 6570 URI template for constructing resource URIs.
URITemplate string `json:"uriTemplate"`
// Description helps clients and LLMs understand the template.
Description string `json:"description,omitempty"`
// MimeType is the MIME type for matching resources, if uniform.
MimeType string `json:"mimeType,omitempty"`
// Annotations provide optional client metadata.
Annotations *Annotations `json:"annotations,omitempty"`
}
ResourceTemplateDescriptor describes a parameterized MCP resource.
type ResourceTemplatesListResult ¶
type ResourceTemplatesListResult struct {
Meta MetaObject `json:"_meta,omitempty"`
ResultType ResultType `json:"resultType"`
NextCursor string `json:"nextCursor,omitempty"`
ResourceTemplates []ResourceTemplateDescriptor `json:"resourceTemplates"`
TTLMS int `json:"ttlMs"`
CacheScope CacheScope `json:"cacheScope"`
}
ResourceTemplatesListResult is the response payload for resources/templates/list.
type ResourceTemplatesRegistry ¶
type ResourceTemplatesRegistry interface {
ResourceTemplates(ctx context.Context) ([]ResourceTemplateDescriptor, error)
}
ResourceTemplatesRegistry supplies optional host-owned parameterized resources.
type ResourceUpdate ¶
type ResourceUpdate struct {
// KeepAlive requests an SSE heartbeat without a resource notification.
KeepAlive bool
// ResourcesListChanged reports changed descriptor membership or metadata.
ResourcesListChanged bool
// ResourceURIs identify resources invalidated by committed state changes.
ResourceURIs []string
}
ResourceUpdate describes authoritative state invalidations from the registry. Registries own target selection and semantic change detection. Transports never reread resources or enumerate catalogs to validate an invalidation. A queued update may conservatively repeat initial state; it must never be suppressed by inferring request echoes or comparing only a partial content projection.
type ResourcesCapability ¶
type ResourcesCapability struct {
// Subscribe indicates support for subscribing to individual resource updates.
Subscribe bool `json:"subscribe,omitempty"`
// ListChanged indicates support for resource list change notifications.
ListChanged bool `json:"listChanged,omitempty"`
}
ResourcesCapability describes resource support advertised by the server.
type ResourcesListResult ¶
type ResourcesListResult struct {
Meta MetaObject `json:"_meta,omitempty"`
ResultType ResultType `json:"resultType"`
NextCursor string `json:"nextCursor,omitempty"`
Resources []ResourceDescriptor `json:"resources"`
TTLMS int `json:"ttlMs"`
CacheScope CacheScope `json:"cacheScope"`
}
ResourcesListResult is the response payload for resources/list.
type ResourcesReadParams ¶
type ResourcesReadParams struct {
Meta RequestMeta `json:"_meta"`
// InputResponses carries responses to server-initiated requests from a prior input_required result.
InputResponses json.RawMessage `json:"inputResponses,omitempty"`
// RequestState carries opaque state from a prior input_required result.
RequestState string `json:"requestState,omitempty"`
// URI identifies the resource to read.
URI string `json:"uri"`
}
ResourcesReadParams is the request params payload for resources/read.
type ResourcesReadResult ¶
type ResourcesReadResult struct {
Meta MetaObject `json:"_meta,omitempty"`
ResultType ResultType `json:"resultType"`
// Contents contains text or blob resource contents.
Contents []ResourceContent `json:"contents"`
// TTLMS hints how long clients may cache this response in milliseconds.
TTLMS int `json:"ttlMs"`
// CacheScope indicates whether the response may be cached publicly or privately.
CacheScope CacheScope `json:"cacheScope"`
}
ResourcesReadResult is the response payload for resources/read.
func ResourceJSON ¶
func ResourceJSON(uri string, value any) (ResourcesReadResult, error)
ResourceJSON encodes value as a JSON MCP resource read result.
type ResultType ¶
type ResultType string
ResultType describes whether an MCP result is complete or partial.
const (
ResultTypeComplete ResultType = "complete"
)
Result type values used by MCP responses.
type SamplingCapability ¶
type SamplingCapability struct {
// Context declares context inclusion support.
Context MetaObject `json:"context,omitempty"`
// Tools declares tool-use support.
Tools MetaObject `json:"tools,omitempty"`
}
SamplingCapability describes deprecated client sampling support.
type ServerDiscoverResult ¶
type ServerDiscoverResult struct {
ResultType ResultType `json:"resultType"`
// SupportedVersions lists MCP protocol versions supported by this server.
SupportedVersions []string `json:"supportedVersions"`
// Capabilities advertises server features.
Capabilities Capabilities `json:"capabilities"`
// ServerInfo describes the server software implementation.
ServerInfo Implementation `json:"serverInfo"`
// Instructions gives natural-language guidance for using the server effectively.
//
// Clients may include it in an LLM system prompt. It should not duplicate tool
// descriptions.
Instructions string `json:"instructions,omitempty"`
// TTLMS hints how long clients may cache this response in milliseconds.
TTLMS int `json:"ttlMs"`
// CacheScope indicates whether the response may be cached publicly or privately.
CacheScope CacheScope `json:"cacheScope"`
}
ServerDiscoverResult is the result returned for a server/discover request.
type SessionStore ¶
type SessionStore struct {
// contains filtered or unexported fields
}
SessionStore owns bounded released-protocol notification sessions. Share one store across request-local handlers and authenticate every request before calling Handler.HandleMCP. Registry authorization remains request-local.
func NewSessionStore ¶
func NewSessionStore(owner func(context.Context) (string, error)) *SessionStore
NewSessionStore creates a notification-session owner. owner must return a stable, opaque authenticated principal key including its authorization scope, never credentials. It must be non-nil.
type Skill ¶
type Skill struct {
URI string `json:"uri"`
Frontmatter map[string]any `json:"frontmatter"`
Resources []SkillResource `json:"resources"`
}
Skill describes one Agent Skill served through the MCP Skills extension.
type SkillResource ¶
type SkillResource struct {
URI string `json:"uri"`
Digest string `json:"digest"`
Size int64 `json:"size"`
}
SkillResource describes one complete, digest-verified file in a skill.
type SkillsGetParams ¶
type SkillsGetParams struct {
Meta RequestMeta `json:"_meta"`
URI string `json:"uri"`
}
SkillsGetParams identifies a skill by its SKILL.md resource URI.
type SkillsGetResult ¶
type SkillsGetResult struct {
Meta MetaObject `json:"_meta,omitempty"`
ResultType ResultType `json:"resultType"`
Skill Skill `json:"skill"`
TTLMS int `json:"ttlMs"`
CacheScope CacheScope `json:"cacheScope"`
}
SkillsGetResult is the response payload for skills/get.
type SkillsListResult ¶
type SkillsListResult struct {
Meta MetaObject `json:"_meta,omitempty"`
ResultType ResultType `json:"resultType"`
NextCursor string `json:"nextCursor,omitempty"`
Skills []Skill `json:"skills"`
TTLMS int `json:"ttlMs"`
CacheScope CacheScope `json:"cacheScope"`
}
SkillsListResult is the response payload for skills/list.
type SkillsRegistry ¶
type SkillsRegistry interface {
ListSkills(ctx context.Context, cursor string) (SkillsListResult, error)
GetSkill(ctx context.Context, uri string) (SkillsGetResult, error)
}
SkillsRegistry supplies the optional io.modelcontextprotocol/skills extension.
type SubscriptionFilter ¶
type SubscriptionFilter struct {
// ResourcesListChanged requests resource list change notifications.
ResourcesListChanged bool `json:"resourcesListChanged,omitempty"`
// ResourceSubscriptions requests updates for individual resource URIs.
ResourceSubscriptions []string `json:"resourceSubscriptions,omitempty"`
}
SubscriptionFilter describes MCP subscription notifications requested by a client.
type SubscriptionNotificationParams ¶
type SubscriptionNotificationParams struct {
Meta MetaObject `json:"_meta,omitempty"`
// Notifications is the subset of requested notification types the server accepted.
Notifications *SubscriptionFilter `json:"notifications,omitempty"`
// URI identifies an updated resource.
URI string `json:"uri,omitempty"`
}
SubscriptionNotificationParams is the payload for subscription notifications.
type SubscriptionRegistry ¶
type SubscriptionRegistry interface {
// SubscribeResourceUpdates observes the requested filters and caller metadata.
// Params must be non-nil and must not be modified during the subscription.
SubscribeResourceUpdates(ctx context.Context, params *SubscriptionsListenParams) (iter.Seq2[ResourceUpdate, error], error)
}
SubscriptionRegistry supplies optional resource change streams.
type SubscriptionsInitialStateParams ¶
type SubscriptionsInitialStateParams struct {
Meta MetaObject `json:"_meta,omitempty"`
// URI is the subscribed target whose initial state was delivered.
URI string `json:"uri"`
// Contents is the resources/read result for the same target, so a client
// that applies the payload holds the post-subscription state without a
// second read.
Contents []ResourceContent `json:"contents"`
}
SubscriptionsInitialStateParams is the payload for the notifications/subscriptions/initial_state notification.
type SubscriptionsListenParams ¶
type SubscriptionsListenParams struct {
Meta RequestMeta `json:"_meta"`
// Notifications declares notification types the client opts in to.
Notifications SubscriptionFilter `json:"notifications"`
}
SubscriptionsListenParams is the request params payload for subscriptions/listen.
type TextOutput ¶
type TextOutput struct {
Result string `json:"result" jsonschema_description:"Human-readable tool result"`
}
TextOutput is the standard human-readable successful tool payload.
type ToolAnnotations ¶
type ToolAnnotations struct {
// Title is a human-readable title for the tool.
Title string `json:"title,omitempty"`
// ReadOnlyHint indicates the tool does not modify its environment.
ReadOnlyHint bool `json:"readOnlyHint,omitempty"`
// DestructiveHint indicates the tool may perform destructive updates.
DestructiveHint bool `json:"destructiveHint,omitempty"`
// IdempotentHint indicates repeated calls with the same arguments have no additional effect.
IdempotentHint bool `json:"idempotentHint,omitempty"`
// OpenWorldHint indicates the tool may interact with external entities.
OpenWorldHint bool `json:"openWorldHint,omitempty"`
}
ToolAnnotations describe MCP tool behavior hints.
type ToolCallResult ¶
type ToolCallResult struct {
Meta MetaObject `json:"_meta,omitempty"`
ResultType ResultType `json:"resultType"`
// Content is the unstructured result of the tool call.
Content []ContentBlock `json:"content"`
// StructuredContent is optional JSON matching the tool output schema on success.
StructuredContent any `json:"structuredContent,omitempty"`
// IsError indicates the tool call ended in an error visible to the model.
IsError bool `json:"isError,omitempty"`
}
ToolCallResult is the response payload for a tool call.
type ToolDescriptor ¶
type ToolDescriptor struct {
Meta MetaObject `json:"_meta,omitempty"`
Icons []Icon `json:"icons,omitempty"`
// Name is the programmatic tool identifier.
Name string `json:"name"`
// Title is a human-readable display name.
Title string `json:"title,omitempty"`
// Description helps clients and LLMs understand the tool.
Description string `json:"description,omitempty"`
// InputSchema defines the expected JSON object arguments for the tool.
InputSchema *jsonschema.Schema `json:"inputSchema"`
// OutputSchema defines the structuredContent shape for successful results.
OutputSchema *jsonschema.Schema `json:"outputSchema,omitempty"`
// Annotations contains optional tool behavior hints.
Annotations *ToolAnnotations `json:"annotations,omitempty"`
}
ToolDescriptor describes a tool the client can call.
type ToolHandler ¶
type ToolHandler func(context.Context, *ToolsCallParams) (RawToolResult, error)
ToolHandler executes a tool with its complete decoded request parameters. Parameters must be non-nil and must not be modified during the call.
type ToolRequest ¶
type ToolRequest[T any] struct { Params RequestParams Arguments T }
ToolRequest pairs common request metadata with decoded tool arguments. Handlers receive a non-nil pointer and must not modify the request during the call. Only T contributes to the model-visible input schema.
type ToolResult ¶
type ToolResult[T any] struct { Meta MetaObject Structured any IsError bool // contains filtered or unexported fields }
ToolResult carries a tool handler's output. The T type parameter exists only to drive output-schema generation in NewToolSpec (via the [0]T phantom field); it does NOT constrain Structured, which stays any so error paths can substitute a different payload. Concretely, ToolError[T] puts an ErrorOutput in Structured regardless of T, so the emitted structuredContent is not guaranteed to match the advertised outputSchema — IsError signals when it diverges. Treat outputSchema as a hint for success results, not a wire contract.
func TextToolResult ¶
func TextToolResult(message string) ToolResult[TextOutput]
TextToolResult returns a successful text output result.
func ToolError ¶
func ToolError[T any](message string) ToolResult[T]
ToolError returns an MCP tool error result.
func ToolErrorWithMeta ¶
func ToolErrorWithMeta[T any](message string, meta MetaObject) ToolResult[T]
ToolErrorWithMeta returns an MCP tool error result with metadata.
func TypedToolResult ¶
func TypedToolResult[T any](structured T) ToolResult[T]
TypedToolResult returns a successful structured tool result.
type ToolSpec ¶
type ToolSpec struct {
Name string
Title string
Description string
InputSchema *jsonschema.Schema
OutputSchema *jsonschema.Schema
Annotations *ToolAnnotations
Handler ToolHandler
}
ToolSpec describes a server-side tool implementation.
func NewToolSpec ¶
func NewToolSpec[In, Out any](name, title, description string, handler func(context.Context, *ToolRequest[In]) ToolResult[Out]) ToolSpec
NewToolSpec builds a ToolSpec with reflected input and output schemas.
type ToolsCallParams ¶
type ToolsCallParams struct {
Meta RequestMeta `json:"_meta"`
// InputResponses carries responses to server-initiated requests from a prior input_required result.
InputResponses json.RawMessage `json:"inputResponses,omitempty"`
// RequestState carries opaque state from a prior input_required result.
RequestState string `json:"requestState,omitempty"`
// Name identifies the tool to invoke.
Name string `json:"name"`
// Arguments contains tool arguments as a JSON object.
Arguments json.RawMessage `json:"arguments,omitempty"`
}
ToolsCallParams is the request params payload for tools/call.
type ToolsCapability ¶
type ToolsCapability struct {
// ListChanged indicates support for tool list change notifications.
ListChanged bool `json:"listChanged,omitempty"`
}
ToolsCapability describes tool support advertised by the server.
type ToolsListResult ¶
type ToolsListResult struct {
Meta MetaObject `json:"_meta,omitempty"`
ResultType ResultType `json:"resultType"`
NextCursor string `json:"nextCursor,omitempty"`
Tools []ToolDescriptor `json:"tools"`
TTLMS int `json:"ttlMs"`
CacheScope CacheScope `json:"cacheScope"`
}
ToolsListResult is the response payload for tools/list.