protocol

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2025 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MCPVersion     = "2025-06-18"
	JSONRPCVersion = "2.0"

	// 支持的协议版本列表(用于向后兼容性检查)
	MCPVersion2025_03_26 = "2025-03-26"
	MCPVersionLegacy     = "2024-11-05"
)
View Source
const (
	ParseError     = -32700
	InvalidRequest = -32600
	MethodNotFound = -32601
	InvalidParams  = -32602
	InternalError  = -32603
)

JSON-RPC 2.0 标准错误代码

View Source
const (
	ToolNotFound     = -32000 // 工具未找到
	ResourceNotFound = -32002 // 资源未找到
	PromptNotFound   = -32001 // 提示模板未找到
	InvalidTool      = -32003 // 无效工具
	InvalidResource  = -32004 // 无效资源
	InvalidPrompt    = -32005 // 无效提示模板

	ErrorCodeInvalidParams = InvalidParams
)

MCP 特定错误代码

Variables

This section is empty.

Functions

func ContentToJSON

func ContentToJSON(content []Content) ([]json.RawMessage, error)

func GetSupportedVersions

func GetSupportedVersions() []string

GetSupportedVersions 返回所有支持的协议版本

func IDToString

func IDToString(id json.RawMessage) string

IDToString 将 JSON-RPC ID 转换为字符串

func IsVersionSupported

func IsVersionSupported(version string) bool

IsVersionSupported 检查协议版本是否受支持

func StringToID

func StringToID(id string) json.RawMessage

StringToID 将字符串转换为 JSON-RPC ID

func ValidateElicitationAction added in v1.1.1

func ValidateElicitationAction(action string) bool

ValidateElicitationAction validates whether the elicitation action is valid

func ValidateStructuredOutput added in v1.1.0

func ValidateStructuredOutput(data interface{}, schema JSONSchema) error

ValidateStructuredOutput 验证结构化输出是否符合模式

Types

type CallToolParams

type CallToolParams struct {
	Name      string                 `json:"name"`
	Arguments map[string]interface{} `json:"arguments"`
}

type CallToolRequest

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

type CallToolResult

type CallToolResult struct {
	Content           []Content   `json:"content"`
	IsError           bool        `json:"isError,omitempty"`
	StructuredContent interface{} `json:"structuredContent,omitempty"` // MCP 2025-06-18 新增
}

func NewToolResult

func NewToolResult(content []Content, isError bool) *CallToolResult

func NewToolResultError

func NewToolResultError(errorMsg string) *CallToolResult

func NewToolResultText

func NewToolResultText(text string) *CallToolResult

func NewToolResultTextWithStructured

func NewToolResultTextWithStructured(text string, structuredContent interface{}) *CallToolResult

NewToolResultTextWithStructured 创建带有文本和结构化内容的工具结果

func NewToolResultWithStructured

func NewToolResultWithStructured(content []Content, structuredContent interface{}) *CallToolResult

NewToolResultWithStructured 创建带有结构化内容的工具结果 (MCP 2025-06-18)

func (*CallToolResult) UnmarshalJSON

func (ctr *CallToolResult) UnmarshalJSON(data []byte) error

UnmarshalJSON 实现自定义JSON反序列化

type ClientCapabilities

type ClientCapabilities struct {
	Roots        *RootsCapability       `json:"roots,omitempty"`
	Sampling     *SamplingCapability    `json:"sampling,omitempty"`
	Elicitation  *ElicitationCapability `json:"elicitation,omitempty"`
	Experimental map[string]interface{} `json:"experimental,omitempty"`
}

type ClientInfo

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

type Content

type Content interface {
	GetType() ContentType
}

func UnmarshalContent

func UnmarshalContent(data []byte) (Content, error)

type ContentType

type ContentType string
const (
	ContentTypeText  ContentType = "text"
	ContentTypeImage ContentType = "image"
)

type CreateMessageRequest added in v1.1.1

type CreateMessageRequest struct {
	Messages         []SamplingMessage      `json:"messages"`
	ModelPreferences *ModelPreferences      `json:"modelPreferences,omitempty"`
	SystemPrompt     string                 `json:"systemPrompt,omitempty"`
	IncludeContext   IncludeContext         `json:"includeContext,omitempty"`
	Temperature      *float64               `json:"temperature,omitempty"` // 0.0-1.0
	MaxTokens        int                    `json:"maxTokens"`             // 必需
	StopSequences    []string               `json:"stopSequences,omitempty"`
	Metadata         map[string]interface{} `json:"metadata,omitempty"`
}

CreateMessageRequest 创建消息请求 (服务器发起的LLM采样)

func NewCreateMessageRequest added in v1.1.1

func NewCreateMessageRequest(messages []SamplingMessage, maxTokens int) *CreateMessageRequest

NewCreateMessageRequest 创建消息请求

func (*CreateMessageRequest) Validate added in v1.1.1

func (cmr *CreateMessageRequest) Validate() error

Validate 验证创建消息请求

func (*CreateMessageRequest) WithIncludeContext added in v1.1.1

func (cmr *CreateMessageRequest) WithIncludeContext(context IncludeContext) *CreateMessageRequest

WithIncludeContext 设置上下文包含选项

func (*CreateMessageRequest) WithMetadata added in v1.1.1

func (cmr *CreateMessageRequest) WithMetadata(metadata map[string]interface{}) *CreateMessageRequest

WithMetadata 设置元数据

func (*CreateMessageRequest) WithModelPreferences added in v1.1.1

func (cmr *CreateMessageRequest) WithModelPreferences(prefs *ModelPreferences) *CreateMessageRequest

WithModelPreferences 设置模型偏好

func (*CreateMessageRequest) WithStopSequences added in v1.1.1

func (cmr *CreateMessageRequest) WithStopSequences(sequences ...string) *CreateMessageRequest

WithStopSequences 设置停止序列

func (*CreateMessageRequest) WithSystemPrompt added in v1.1.1

func (cmr *CreateMessageRequest) WithSystemPrompt(prompt string) *CreateMessageRequest

WithSystemPrompt 设置系统提示

func (*CreateMessageRequest) WithTemperature added in v1.1.1

func (cmr *CreateMessageRequest) WithTemperature(temp float64) *CreateMessageRequest

WithTemperature 设置温度 (0.0-1.0)

type CreateMessageResult added in v1.1.1

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

CreateMessageResult 创建消息结果

func NewCreateMessageResult added in v1.1.1

func NewCreateMessageResult(role Role, content Content, model string, stopReason StopReason) *CreateMessageResult

NewCreateMessageResult 创建消息结果

type ElicitationAction added in v1.1.1

type ElicitationAction string
const (
	ElicitationActionAccept  ElicitationAction = "accept"
	ElicitationActionDecline ElicitationAction = "decline"
	ElicitationActionCancel  ElicitationAction = "cancel"
)

type ElicitationCapability added in v1.1.1

type ElicitationCapability struct{}

Elicitation 能力声明

type ElicitationCreateParams added in v1.1.1

type ElicitationCreateParams struct {
	Message         string     `json:"message"`
	RequestedSchema JSONSchema `json:"requestedSchema"`
}

func NewElicitationCreateParams added in v1.1.1

func NewElicitationCreateParams(message string, schema JSONSchema) *ElicitationCreateParams

type ElicitationResult added in v1.1.1

type ElicitationResult struct {
	Action  ElicitationAction `json:"action"`
	Content interface{}       `json:"content,omitempty"`
}

func NewElicitationAccept added in v1.1.1

func NewElicitationAccept(content interface{}) *ElicitationResult

func NewElicitationCancel added in v1.1.1

func NewElicitationCancel() *ElicitationResult

func NewElicitationDecline added in v1.1.1

func NewElicitationDecline() *ElicitationResult

func NewElicitationResult added in v1.1.1

func NewElicitationResult(action ElicitationAction, content interface{}) *ElicitationResult

func (*ElicitationResult) IsAccepted added in v1.1.1

func (r *ElicitationResult) IsAccepted() bool

func (*ElicitationResult) IsCancelled added in v1.1.1

func (r *ElicitationResult) IsCancelled() bool

func (*ElicitationResult) IsDeclined added in v1.1.1

func (r *ElicitationResult) IsDeclined() bool

func (*ElicitationResult) MarshalJSON added in v1.1.1

func (r *ElicitationResult) MarshalJSON() ([]byte, error)

func (*ElicitationResult) UnmarshalJSON added in v1.1.1

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

func (*ElicitationResult) Validate added in v1.1.1

func (r *ElicitationResult) Validate() error

type GetPromptParams

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

GetPromptParams 获取提示模板的参数类型

type GetPromptRequest

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

GetPromptRequest prompts/get 请求和响应

type GetPromptResult

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

func NewGetPromptResult

func NewGetPromptResult(description string, messages ...PromptMessage) *GetPromptResult

type ImageContent

type ImageContent struct {
	Type     ContentType `json:"type"`
	Data     string      `json:"data"`
	MimeType string      `json:"mimeType"`
}

func NewImageContent

func NewImageContent(data, mimeType string) ImageContent

func (ImageContent) GetType

func (ic ImageContent) GetType() ContentType

type IncludeContext added in v1.1.1

type IncludeContext string

IncludeContext 上下文包含选项

const (
	IncludeContextNone       IncludeContext = "none"
	IncludeContextThisServer IncludeContext = "thisServer"
	IncludeContextAllServers IncludeContext = "allServers"
)

type InitializeRequest

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

type InitializeResult

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

type JSONRPCError

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

type JSONRPCMessage

type JSONRPCMessage struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id,omitempty"`
	Method  string          `json:"method,omitempty"`
	Params  json.RawMessage `json:"params,omitempty"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *JSONRPCError   `json:"error,omitempty"`
}

func (*JSONRPCMessage) GetIDString

func (m *JSONRPCMessage) GetIDString() string

GetIDString 获取消息ID的字符串表示

func (*JSONRPCMessage) IsNotification

func (m *JSONRPCMessage) IsNotification() bool

IsNotification 检查消息是否为通知(没有ID)

type JSONSchema

type JSONSchema map[string]interface{}

func CreateBooleanElicitationSchema added in v1.1.1

func CreateBooleanElicitationSchema(propertyName, description string, defaultValue *bool, required bool) JSONSchema

CreateBooleanElicitationSchema creates a schema for requesting boolean input

func CreateElicitationSchema added in v1.1.1

func CreateElicitationSchema() JSONSchema

CreateElicitationSchema creates a common elicitation schema

func CreateEnumElicitationSchema added in v1.1.1

func CreateEnumElicitationSchema(propertyName, description string, options []string, optionNames []string, required bool) JSONSchema

CreateEnumElicitationSchema creates a schema for requesting enum selection

func CreateNumberElicitationSchema added in v1.1.1

func CreateNumberElicitationSchema(propertyName, description string, min, max *float64, required bool) JSONSchema

CreateNumberElicitationSchema creates a schema for requesting number input

func CreateStringElicitationSchema added in v1.1.1

func CreateStringElicitationSchema(propertyName, description string, required bool) JSONSchema

CreateStringElicitationSchema creates a schema for requesting string input

type ListPromptsParams

type ListPromptsParams struct {
	Cursor string `json:"cursor,omitempty"`
}

ListPromptsParams 列表提示模板的参数类型

type ListPromptsRequest

type ListPromptsRequest struct {
	Cursor string `json:"cursor,omitempty"`
}

ListPromptsRequest prompts/list 请求和响应

type ListPromptsResult

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

type ListResourceTemplatesRequest

type ListResourceTemplatesRequest struct {
	Cursor string `json:"cursor,omitempty"`
}

ListResourceTemplatesRequest resources/templates/list 请求和响应

type ListResourceTemplatesResult

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

type ListResourcesParams

type ListResourcesParams struct {
	Cursor string `json:"cursor,omitempty"`
}

ListResourcesParams 列表资源的参数类型

type ListResourcesRequest

type ListResourcesRequest struct {
	Cursor string `json:"cursor,omitempty"`
}

ListResourcesRequest resources/list 请求和响应

type ListResourcesResult

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

type ListToolsParams

type ListToolsParams struct {
	Cursor string `json:"cursor,omitempty"`
}

type ListToolsRequest

type ListToolsRequest struct {
	Cursor string `json:"cursor,omitempty"`
}

type ListToolsResult

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

type LoggingCapability

type LoggingCapability struct{}

type MCPError added in v1.1.1

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

MCPError MCP特定错误类型

func NewMCPError added in v1.1.1

func NewMCPError(code int, message string, data interface{}) *MCPError

NewMCPError 创建新的MCP错误

func (*MCPError) Error added in v1.1.1

func (e *MCPError) Error() string

type ModelHint added in v1.1.1

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

ModelHint 模型提示

func NewModelHint added in v1.1.1

func NewModelHint(name string) ModelHint

type ModelPreferences added in v1.1.1

type ModelPreferences struct {
	Hints                []ModelHint `json:"hints,omitempty"`
	CostPriority         *float64    `json:"costPriority,omitempty"`         // 0-1, 成本优先级
	SpeedPriority        *float64    `json:"speedPriority,omitempty"`        // 0-1, 速度优先级
	IntelligencePriority *float64    `json:"intelligencePriority,omitempty"` // 0-1, 智能优先级
}

ModelPreferences 模型偏好设置

func NewModelPreferences added in v1.1.1

func NewModelPreferences() *ModelPreferences

func (*ModelPreferences) Validate added in v1.1.1

func (mp *ModelPreferences) Validate() error

Validate 验证模型偏好设置

func (*ModelPreferences) WithCostPriority added in v1.1.1

func (mp *ModelPreferences) WithCostPriority(priority float64) *ModelPreferences

WithCostPriority 设置成本优先级 (0-1)

func (*ModelPreferences) WithHints added in v1.1.1

func (mp *ModelPreferences) WithHints(hints ...ModelHint) *ModelPreferences

WithHints 设置模型提示

func (*ModelPreferences) WithIntelligencePriority added in v1.1.1

func (mp *ModelPreferences) WithIntelligencePriority(priority float64) *ModelPreferences

WithIntelligencePriority 设置智能优先级 (0-1)

func (*ModelPreferences) WithSpeedPriority added in v1.1.1

func (mp *ModelPreferences) WithSpeedPriority(priority float64) *ModelPreferences

WithSpeedPriority 设置速度优先级 (0-1)

type PaginatedResult

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

type PaginationParams

type PaginationParams struct {
	Cursor string `json:"cursor,omitempty"`
}

type Prompt

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

Prompt 提示模板定义

func NewPrompt

func NewPrompt(name, description string, arguments ...PromptArgument) Prompt

type PromptArgument

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

PromptArgument 提示模板参数

func NewPromptArgument

func NewPromptArgument(name, description string, required bool) PromptArgument

type PromptMessage

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

PromptMessage 提示消息

func NewPromptMessage

func NewPromptMessage(role Role, content Content) PromptMessage

func (*PromptMessage) UnmarshalJSON

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

UnmarshalJSON 实现自定义JSON反序列化

type PromptsCapability

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

type PromptsListChangedNotification

type PromptsListChangedNotification struct{}

PromptsListChangedNotification 提示模板变更通知

type ReadResourceParams

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

ReadResourceParams 读取资源的参数类型

type ReadResourceRequest

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

ReadResourceRequest resources/read 请求和响应

type ReadResourceResult

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

func NewReadResourceResult

func NewReadResourceResult(contents ...ResourceContents) *ReadResourceResult

type Resource

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

Resource 资源定义

func NewResource

func NewResource(uri, name, description, mimeType string) Resource

type ResourceContents

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

ResourceContents 资源内容

func NewBlobResourceContents

func NewBlobResourceContents(uri, blob, mimeType string) ResourceContents

func NewTextResourceContents

func NewTextResourceContents(uri, text string) ResourceContents

type ResourceTemplate

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

type ResourcesCapability

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

type ResourcesListChangedNotification

type ResourcesListChangedNotification struct{}

ResourcesListChangedNotification 资源变更通知

type ResourcesUpdatedNotification

type ResourcesUpdatedNotification struct {
	URI   string `json:"uri"`
	Title string `json:"title,omitempty"` // 2025-06-18 新增:可选的资源标题
}

func NewResourcesUpdatedNotification

func NewResourcesUpdatedNotification(uri string, title ...string) ResourcesUpdatedNotification

NewResourcesUpdatedNotification 创建资源更新通知

type Role

type Role string
const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleSystem    Role = "system"
)

type RootsCapability

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

type SamplingCapability

type SamplingCapability struct{}

type SamplingMessage added in v1.1.1

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

SamplingMessage 采样消息

func NewSamplingMessage added in v1.1.1

func NewSamplingMessage(role Role, content Content) SamplingMessage

type ServerCapabilities

type ServerCapabilities struct {
	Tools        *ToolsCapability       `json:"tools,omitempty"`
	Resources    *ResourcesCapability   `json:"resources,omitempty"`
	Prompts      *PromptsCapability     `json:"prompts,omitempty"`
	Logging      *LoggingCapability     `json:"logging,omitempty"`
	Experimental map[string]interface{} `json:"experimental,omitempty"`
}

type ServerInfo

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

type StopReason added in v1.1.1

type StopReason string
const (
	StopReasonEndTurn      StopReason = "endTurn"
	StopReasonMaxTokens    StopReason = "maxTokens"
	StopReasonStopSequence StopReason = "stopSequence"
	StopReasonToolUse      StopReason = "toolUse"
)

type TextContent

type TextContent struct {
	Type ContentType `json:"type"`
	Text string      `json:"text"`
}

func NewTextContent

func NewTextContent(text string) TextContent

func (TextContent) GetType

func (tc TextContent) GetType() ContentType

type Tool

type Tool struct {
	Name         string     `json:"name"`
	Description  string     `json:"description,omitempty"`
	InputSchema  JSONSchema `json:"inputSchema"`
	OutputSchema JSONSchema `json:"outputSchema,omitempty"` // MCP 2025-06-18 新增
}

func NewTool

func NewTool(name, description string, inputSchema JSONSchema) Tool

func NewToolWithOutput added in v1.1.0

func NewToolWithOutput(name, description string, inputSchema, outputSchema JSONSchema) Tool

NewToolWithOutput 创建带有输出模式的工具 (MCP 2025-06-18)

type ToolList

type ToolList struct {
	Tools []Tool `json:"tools"`
}

type ToolParameter

type ToolParameter struct {
	Name        string     `json:"name"`
	Description string     `json:"description,omitempty"`
	Required    bool       `json:"required,omitempty"`
	Schema      JSONSchema `json:"schema,omitempty"`
}

func BooleanParameter

func BooleanParameter(name, description string, required bool) ToolParameter

func NumberParameter

func NumberParameter(name, description string, required bool) ToolParameter

func ObjectParameter

func ObjectParameter(name, description string, required bool, properties JSONSchema, required_props []string) ToolParameter

func StringParameter

func StringParameter(name, description string, required bool) ToolParameter

type ToolsCapability

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

type ToolsListChangedNotification

type ToolsListChangedNotification struct{}

Jump to

Keyboard shortcuts

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