mcp

package
v0.8.4 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2025 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package mcp contains protocol data types and constants shared across transports and server capability implementations. It mirrors the wire representation specified by the Model Context Protocol while keeping the surface Go-friendly (exported structs with json tags, string constants for method names and enumerations, helper validation functions).

The package is intentionally free of transport logic: HTTP streaming, stdio, or any future transports import these types but implement their own framing, authentication and session handling. Likewise higher-level server packages (e.g. mcpservice) construct responses using these concrete types and hand them to the engine for JSON-RPC serialization.

Method Names

JSON-RPC method and notification names are enumerated as Method constants (e.g. ToolsListMethod). Using the constants avoids typographical mistakes and ensures a single point of truth if the spec evolves.

Capabilities

ClientCapabilities and ServerCapabilities capture negotiated feature sets. They are thin structs shaped to match the JSON spec. Capability advertising happens during initialize/initializeResult exchanges; transports simply marshal these types.

Pagination

Many list operations use cursor-based pagination. PaginatedRequest and PaginatedResult are embedded in request / result envelopes to keep the core list types clean while offering forward-compatible metadata via BaseMetadata.

Metadata

BaseMetadata allows response producers to attach implementation-defined metadata under the _meta key without inflating every struct with an unused field. Composition (embedding) keeps serialization cost minimal when unset.

Example (tool result construction):

res := &mcp.CallToolResult{
    Content: []mcp.ContentBlock{{Type: mcp.ContentTypeText, Text: "hello"}},
}

Example (progress notification object):

prog := mcp.ProgressNotificationParams{ProgressToken: "op1", Progress: 42, Total: 100}
// engine layer serializes & dispatches

Logging Levels

LoggingLevel values mirror syslog severities defined by the spec. Use IsValidLoggingLevel to validate user-provided values in capability code.

Compatibility

The LatestProtocolVersion constant reflects the most recent protocol date the library targets. Transports negotiate versions at runtime; application code can compare a session's negotiated version with this constant to gate optional behaviors.

Index

Constants

View Source
const (
	ContentTypeText             = "text"
	ContentTypeImage            = "image"
	ContentTypeAudio            = "audio"
	ContentTypeResourceLink     = "resource"
	ContentTypeEmbeddedResource = "embedded-resource"
)

Content type string constants for ContentBlock.Type. These mirror the wire protocol vocabulary and are provided to reduce typos in user code. Keeping them here (instead of in a helper package) ensures a single authoritative source of truth.

View Source
const LatestProtocolVersion = "2025-06-18"

LatestProtocolVersion is the latest version of the protocol.

Variables

This section is empty.

Functions

func IsValidLoggingLevel added in v0.3.0

func IsValidLoggingLevel(level LoggingLevel) bool

IsValidLoggingLevel reports whether the provided level is one of the protocol-defined syslog severities.

Types

type Annotations

type Annotations struct {
	Audience []Role  `json:"audience,omitempty"`
	Priority float64 `json:"priority,omitzero"`
}

Annotations Annotations provide optional routing/prioritization hints.

type BaseMetadata

type BaseMetadata struct {
	Meta map[string]any `json:"_meta,omitempty"`
}

BaseMetadata carries optional metadata for responses.

type CallToolRequestReceived

type CallToolRequestReceived struct {
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments,omitempty"`
}

CallToolRequestReceived is the server-received representation for a tool call.

type CallToolRequestSent

type CallToolRequestSent struct {
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
}

Server-sent versions with structured data for outgoing messages CallToolRequestSent is the server-sent version of a tool call.

type CallToolResult

type CallToolResult struct {
	Content []ContentBlock `json:"content,omitempty"`
	IsError bool           `json:"isError,omitzero"`
	// StructuredContent contains a typed object that conforms to the tool's
	// OutputSchema when provided.
	StructuredContent map[string]any `json:"structuredContent,omitempty"`
	BaseMetadata
}

CallToolResult represents a tool invocation result.

type CancelledNotification

type CancelledNotification struct {
	// RequestID matches the JSON-RPC request ID of the in-flight request being cancelled.
	// JSON-RPC permits string or number; we accept both via jsonrpc.RequestID.
	RequestID *jsonrpc.RequestID `json:"requestId"`
	Reason    string             `json:"reason,omitzero"`
}

CancelledNotification informs the peer that a request was canceled.

type ClientCapabilities

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

Capabilities ClientCapabilities advertises client features.

type CompleteArgument

type CompleteArgument struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

CompleteArgument is the item to complete for a resource reference.

type CompleteRequest

type CompleteRequest struct {
	Ref      ResourceReference `json:"ref"`
	Argument CompleteArgument  `json:"argument"`
}

Completion CompleteRequest requests completion suggestions for a reference.

type CompleteResult

type CompleteResult struct {
	Completion Completion `json:"completion"`
	BaseMetadata
}

CompleteResult contains completion suggestions.

type Completion

type Completion struct {
	Values  []string `json:"values"`
	Total   int      `json:"total,omitzero"`
	HasMore bool     `json:"hasMore,omitzero"`
}

Completion contains completion results for a reference.

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"`
	// For TextContent
	Text string `json:"text,omitzero"`
	// For ImageContent and AudioContent
	Data     string `json:"data,omitzero"`
	MimeType string `json:"mimeType,omitzero"`
	// For EmbeddedResource
	Resource *ResourceContents `json:"resource,omitempty"`
	// For ResourceLink
	URI         string `json:"uri,omitzero"`
	Name        string `json:"name,omitzero"`
	Description string `json:"description,omitzero"`
}

Content types ContentBlock is a typed content part of a message.

type CreateMessageRequest

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

Sampling CreateMessageRequest requests a model-generated message.

type CreateMessageResult

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

CreateMessageResult returns a generated message.

type CreateMessageResultReceived

type CreateMessageResultReceived struct {
	Role       Role            `json:"role"`
	Content    json.RawMessage `json:"content"`
	Model      string          `json:"model"`
	StopReason string          `json:"stopReason,omitzero"`
	Meta       json.RawMessage `json:"_meta,omitempty"`
}

CreateMessageResultReceived is the server-received representation for a sampling result.

type ElicitRequest

type ElicitRequest struct {
	Message         string            `json:"message"`
	RequestedSchema ElicitationSchema `json:"requestedSchema"`
}

Elicitation ElicitRequest asks for structured input per schema.

type ElicitResult

type ElicitResult struct {
	Action  string         `json:"action"`
	Content map[string]any `json:"content"`
	BaseMetadata
}

ElicitResult returns schema-conformant values.

type ElicitResultReceived

type ElicitResultReceived struct {
	Values json.RawMessage `json:"values"`
	Meta   json.RawMessage `json:"_meta,omitempty"`
}

ElicitResultReceived contains structured values for elicitation responses.

type ElicitationSchema

type ElicitationSchema struct {
	Type       string                               `json:"type"`
	Properties map[string]PrimitiveSchemaDefinition `json:"properties"`
	Required   []string                             `json:"required,omitempty"`
}

Elicitation ElicitationSchema is a simplified schema for elicitation prompts.

type EmptyResult

type EmptyResult struct {
	BaseMetadata
}

Empty result for operations that don't return data EmptyResult is returned for operations that do not return data.

type GetPromptRequest

type GetPromptRequest struct {
	Name      string                     `json:"name"`
	Arguments map[string]json.RawMessage `json:"arguments,omitempty"`
}

GetPromptRequest requests a prompt definition by name.

type GetPromptRequestReceived

type GetPromptRequestReceived struct {
	Name      string                     `json:"name"`
	Arguments map[string]json.RawMessage `json:"arguments,omitempty"`
}

GetPromptRequestReceived is the server-received representation for prompt retrieval.

type GetPromptRequestSent

type GetPromptRequestSent struct {
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
}

GetPromptRequestSent is the server-sent version of a prompt get.

type GetPromptResult

type GetPromptResult struct {
	Description string          `json:"description,omitzero"`
	Messages    []PromptMessage `json:"messages"`
	BaseMetadata
}

GetPromptResult returns a prompt definition and messages.

type ImplementationInfo

type ImplementationInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	Title   string `json:"title,omitzero"`
}

ImplementationInfo describes the implementation name and version.

type InitializeRequest

type InitializeRequest struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ClientCapabilities `json:"capabilities"`
	ClientInfo      ImplementationInfo `json:"clientInfo"`
}

InitializeRequest starts the MCP initialization handshake.

type InitializeResult

type InitializeResult struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ServerCapabilities `json:"capabilities"`
	ServerInfo      ImplementationInfo `json:"serverInfo"`
	Instructions    string             `json:"instructions,omitzero"`
	BaseMetadata
}

InitializeResult returns negotiated capabilities and server info.

type InitializedNotification

type InitializedNotification struct{}

InitializedNotification signals that initialization completed.

type ListPromptsRequest

type ListPromptsRequest struct {
	PaginatedRequest
}

Prompts ListPromptsRequest requests available prompts.

type ListPromptsResult

type ListPromptsResult struct {
	Prompts []Prompt `json:"prompts"`
	PaginatedResult
	BaseMetadata
}

ListPromptsResult returns available prompts.

type ListResourceTemplatesRequest

type ListResourceTemplatesRequest struct {
	PaginatedRequest
}

ListResourceTemplatesRequest requests resource templates.

type ListResourceTemplatesResult

type ListResourceTemplatesResult struct {
	ResourceTemplates []ResourceTemplate `json:"resourceTemplates"`
	PaginatedResult
	BaseMetadata
}

ListResourceTemplatesResult returns resource templates.

type ListResourcesRequest

type ListResourcesRequest struct {
	PaginatedRequest
}

Resources ListResourcesRequest requests a paginated list of resources.

type ListResourcesResult

type ListResourcesResult struct {
	Resources []Resource `json:"resources"`
	PaginatedResult
	BaseMetadata
}

ListResourcesResult returns a page of resources.

type ListRootsRequest

type ListRootsRequest struct{}

Roots ListRootsRequest requests the root entries.

type ListRootsResult

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

ListRootsResult returns root entries.

type ListRootsResultReceived

type ListRootsResultReceived struct {
	Roots json.RawMessage `json:"roots"`
	Meta  json.RawMessage `json:"_meta,omitempty"`
}

ListRootsResultReceived contains root listing results as raw JSON.

type ListToolsRequest

type ListToolsRequest struct {
	PaginatedRequest
}

Tools ListToolsRequest requests the set of available tools.

type ListToolsResult

type ListToolsResult struct {
	Tools []Tool `json:"tools"`
	PaginatedResult
	BaseMetadata
}

ListToolsResult returns the available tools.

type LoggingLevel

type LoggingLevel string
const (
	// Logging level constants.
	LoggingLevelDebug     LoggingLevel = "debug"
	LoggingLevelInfo      LoggingLevel = "info"
	LoggingLevelNotice    LoggingLevel = "notice"
	LoggingLevelWarning   LoggingLevel = "warning"
	LoggingLevelError     LoggingLevel = "error"
	LoggingLevelCritical  LoggingLevel = "critical"
	LoggingLevelAlert     LoggingLevel = "alert"
	LoggingLevelEmergency LoggingLevel = "emergency"
)

LoggingLevel represents structured log severity.

type LoggingMessageNotification

type LoggingMessageNotification struct {
	Level  LoggingLevel `json:"level"`
	Data   any          `json:"data"`
	Logger string       `json:"logger,omitzero"`
}

LoggingMessageNotification conveys a structured log message.

type Method

type Method string

Method is an MCP method identifier used in JSON-RPC messages.

const (
	// Initialization
	InitializeMethod              Method = "initialize"
	InitializedNotificationMethod Method = "notifications/initialized"

	// Tools
	ToolsListMethod                    Method = "tools/list"
	ToolsCallMethod                    Method = "tools/call"
	ToolsListChangedNotificationMethod Method = "notifications/tools/list_changed"

	// Resources
	ResourcesListMethod                    Method = "resources/list"
	ResourcesReadMethod                    Method = "resources/read"
	ResourcesTemplatesListMethod           Method = "resources/templates/list"
	ResourcesSubscribeMethod               Method = "resources/subscribe"
	ResourcesUnsubscribeMethod             Method = "resources/unsubscribe"
	ResourcesListChangedNotificationMethod Method = "notifications/resources/list_changed"
	ResourcesUpdatedNotificationMethod     Method = "notifications/resources/updated"

	// Prompts
	PromptsListMethod                    Method = "prompts/list"
	PromptsGetMethod                     Method = "prompts/get"
	PromptsListChangedNotificationMethod Method = "notifications/prompts/list_changed"

	// Logging
	LoggingSetLevelMethod            Method = "logging/setLevel"
	LoggingMessageNotificationMethod Method = "notifications/message"

	// Sampling
	SamplingCreateMessageMethod Method = "sampling/createMessage"

	// Completion
	CompletionCompleteMethod Method = "completion/complete"

	// Roots
	RootsListMethod                    Method = "roots/list"
	RootsListChangedNotificationMethod Method = "notifications/roots/list_changed"

	// Elicitation
	ElicitationCreateMethod Method = "elicitation/create"

	// General
	PingMethod                  Method = "ping"
	CancelledNotificationMethod Method = "notifications/cancelled"
	ProgressNotificationMethod  Method = "notifications/progress"
)

MCP method names and notifications.

type ModelHint

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

ModelHint supplies model-specific guidance.

type ModelPreferences

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

ModelPreferences encode model selection tradeoffs.

type PaginatedRequest

type PaginatedRequest struct {
	Cursor string `json:"cursor,omitzero"`
}

PaginatedRequest carries a cursor for paginated list requests.

type PaginatedResult

type PaginatedResult struct {
	NextCursor string `json:"nextCursor,omitzero"`
}

PaginatedResult carries a cursor for continuing pagination.

type PingRequest

type PingRequest struct{}

PingRequest is a no-op request used to test connectivity.

type PrimitiveSchemaDefinition

type PrimitiveSchemaDefinition struct {
	Type        string `json:"type"`
	Description string `json:"description,omitzero"`
	// For NumberSchema
	Minimum float64 `json:"minimum,omitzero"`
	Maximum float64 `json:"maximum,omitzero"`
	// For EnumSchema
	Enum []any `json:"enum,omitempty"`
}

PrimitiveSchemaDefinition is a leaf schema node for elicitation.

type ProgressNotificationParams

type ProgressNotificationParams struct {
	ProgressToken ProgressToken `json:"progressToken"`
	Progress      float64       `json:"progress"`
	Total         float64       `json:"total,omitzero"`
}

ProgressNotificationParams conveys progress of a long-running operation.

type ProgressToken

type ProgressToken any // string | number

ProgressToken is an identifier used to correlate progress updates. It may be a string or number.

type Prompt

type Prompt struct {
	Name        string           `json:"name"`
	Description string           `json:"description,omitzero"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

Prompts Prompt describes a named prompt the server can provide.

type PromptArgument

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

PromptArgument describes a single prompt argument.

type PromptListChangedNotification

type PromptListChangedNotification struct{}

PromptListChangedNotification indicates the set of prompts changed.

type PromptMessage

type PromptMessage struct {
	Role    Role           `json:"role"`
	Content []ContentBlock `json:"content"`
}

PromptMessage is a message used in a prompt.

type ReadResourceRequest

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

ReadResourceRequest requests the contents of a resource by URI.

type ReadResourceResult

type ReadResourceResult struct {
	Contents []ResourceContents `json:"contents"`
	BaseMetadata
}

ReadResourceResult returns resource contents.

type Resource

type Resource struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	Description string `json:"description,omitzero"`
	MimeType    string `json:"mimeType,omitzero"`
}

Resources Resource represents an addressable resource.

type ResourceContents

type ResourceContents struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType,omitzero"`
	// For TextResourceContents
	Text string `json:"text,omitzero"`
	// For BlobResourceContents
	Blob string `json:"blob,omitzero"`
}

ResourceContents is the value of a resource read.

type ResourceLink struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	Description string `json:"description,omitzero"`
	MimeType    string `json:"mimeType,omitzero"`
}

ResourceLink references another resource.

type ResourceListChangedNotification

type ResourceListChangedNotification struct{}

ResourceListChangedNotification indicates the set of resources changed.

type ResourceReference

type ResourceReference struct {
	Type string `json:"type"`
	URI  string `json:"uri"`
}

Completion ResourceReference identifies the target of completion.

type ResourceTemplate

type ResourceTemplate struct {
	URITemplate string `json:"uriTemplate"`
	Name        string `json:"name"`
	Description string `json:"description,omitzero"`
	MimeType    string `json:"mimeType,omitzero"`
}

ResourceTemplate describes a template for resource URIs.

type ResourceUpdatedNotification

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

ResourceUpdatedNotification indicates a resource's content changed.

type Role

type Role string

Basic types Role indicates the role of a message author.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

type Root

type Root struct {
	URI  string `json:"uri"`
	Name string `json:"name,omitzero"`
}

Roots Root identifies a workspace root.

type RootsListChangedNotification

type RootsListChangedNotification struct{}

RootsListChangedNotification indicates roots changed.

type SamplingMessage

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

Sampling SamplingMessage is a message used as input to model sampling.

type SchemaProperty

type SchemaProperty struct {
	Type        string                    `json:"type,omitempty"`
	Description string                    `json:"description,omitzero"`
	Items       *SchemaProperty           `json:"items,omitempty"`
	Properties  map[string]SchemaProperty `json:"properties,omitempty"`
	Enum        []any                     `json:"enum,omitempty"`
}

SchemaProperty is a simplified schema node used in tool/elicitation schemas.

type ServerCapabilities

type ServerCapabilities struct {
	Logging *struct{} `json:"logging,omitempty"`
	Prompts *struct {
		ListChanged bool `json:"listChanged"`
	} `json:"prompts,omitempty"`
	Resources *struct {
		ListChanged bool `json:"listChanged"`
		Subscribe   bool `json:"subscribe"`
	} `json:"resources,omitempty"`
	Tools *struct {
		ListChanged bool `json:"listChanged"`
	} `json:"tools,omitempty"`
	Completions *struct{} `json:"completions,omitempty"`
}

ServerCapabilities advertises server features.

type SetLevelRequest

type SetLevelRequest struct {
	Level LoggingLevel `json:"level"`
}

Logging SetLevelRequest sets the server logging level.

type SubscribeRequest

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

SubscribeRequest subscribes to updates for the given URI.

type Tool

type Tool struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	InputSchema ToolInputSchema `json:"inputSchema"`
	// OutputSchema optionally declares the structure of structuredContent
	// in CallToolResult for this tool.
	OutputSchema *ToolOutputSchema `json:"outputSchema,omitempty"`
	// Meta carries arbitrary metadata exposed via the `_meta` field in the MCP spec.
	// Keys must follow the naming constraints described in the spec.
	Meta map[string]any `json:"_meta,omitempty"`
}

Tools Tool describes a callable tool and its input schema.

type ToolAnnotations

type ToolAnnotations struct {
	Audience []Role `json:"audience,omitempty"`
}

ToolAnnotations constrain the intended audience for a tool.

type ToolInputSchema

type ToolInputSchema struct {
	Type                 string                    `json:"type"`
	Properties           map[string]SchemaProperty `json:"properties,omitempty"`
	Required             []string                  `json:"required,omitempty"`
	AdditionalProperties bool                      `json:"additionalProperties,omitzero"`
}

ToolInputSchema is a JSON-schema-like description of tool input.

type ToolListChangedNotification

type ToolListChangedNotification struct{}

ToolListChangedNotification indicates the set of tools changed.

type ToolOutputSchema added in v0.3.0

type ToolOutputSchema struct {
	Type       string                    `json:"type"`
	Properties map[string]SchemaProperty `json:"properties,omitempty"`
	Required   []string                  `json:"required,omitempty"`
}

ToolOutputSchema mirrors ToolInputSchema but omits additionalProperties. The schema must be an object shape.

type UnsubscribeRequest

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

UnsubscribeRequest ends a subscription for the given URI.

Jump to

Keyboard shortcuts

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