mcp

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package mcp 实现 Anthropic Model Context Protocol (MCP) 规范。

本包提供 MCP 服务端与客户端的完整实现,包括资源管理、 工具定义、Prompt 模板以及 stdio/WebSocket 双传输层, 支持心跳重连与指数退避。

Index

Constants

View Source
const (
	ErrorCodeParseError     = -32700
	ErrorCodeInvalidRequest = -32600
	ErrorCodeMethodNotFound = -32601
	ErrorCodeInvalidParams  = -32602
	ErrorCodeInternalError  = -32603
)

标准错误码

View Source
const MCPVersion = "2024-11-05"

MCPVersion MCP 协议版本

Variables

This section is empty.

Functions

This section is empty.

Types

type DefaultMCPClient

type DefaultMCPClient struct {
	// contains filtered or unexported fields
}

DefaultMCPClient MCP 客户端默认实现

func NewMCPClient

func NewMCPClient(reader io.Reader, writer io.Writer, logger *zap.Logger) *DefaultMCPClient

NewMCPClient 创建 MCP 客户端(兼容旧接口,使用 StdioTransport)

func NewMCPClientWithTransport

func NewMCPClientWithTransport(transport Transport, logger *zap.Logger) *DefaultMCPClient

NewMCPClientWithTransport 使用指定传输层创建客户端

func NewSSEClient

func NewSSEClient(endpoint string, logger *zap.Logger) *DefaultMCPClient

NewSSEClient 创建 SSE 客户端

func NewWebSocketClient

func NewWebSocketClient(url string, logger *zap.Logger) *DefaultMCPClient

NewWebSocketClient 创建 WebSocket 客户端

func (*DefaultMCPClient) BatchCallTools

func (c *DefaultMCPClient) BatchCallTools(ctx context.Context, calls []ToolCall) ([]any, error)

BatchCallTools 批量调用工具

func (*DefaultMCPClient) CallTool

func (c *DefaultMCPClient) CallTool(ctx context.Context, name string, args map[string]any) (any, error)

CallTool 调用工具

func (*DefaultMCPClient) Connect

func (c *DefaultMCPClient) Connect(ctx context.Context, serverURL string) error

Connect 连接到 MCP 服务器(含 initialize 握手)

func (*DefaultMCPClient) Disconnect

func (c *DefaultMCPClient) Disconnect(ctx context.Context) error

Disconnect 断开连接

func (*DefaultMCPClient) GetPrompt

func (c *DefaultMCPClient) GetPrompt(ctx context.Context, name string, vars map[string]string) (string, error)

GetPrompt 获取提示词

func (*DefaultMCPClient) GetServerInfo

func (c *DefaultMCPClient) GetServerInfo(ctx context.Context) (*ServerInfo, error)

GetServerInfo 获取服务器信息

func (*DefaultMCPClient) IsConnected

func (c *DefaultMCPClient) IsConnected() bool

IsConnected 检查是否已连接

func (*DefaultMCPClient) ListPrompts

func (c *DefaultMCPClient) ListPrompts(ctx context.Context) ([]PromptTemplate, error)

ListPrompts 列出提示词模板

func (*DefaultMCPClient) ListResources

func (c *DefaultMCPClient) ListResources(ctx context.Context) ([]Resource, error)

ListResources 列出资源

func (*DefaultMCPClient) ListTools

func (c *DefaultMCPClient) ListTools(ctx context.Context) ([]ToolDefinition, error)

ListTools 列出工具

func (*DefaultMCPClient) ReadResource

func (c *DefaultMCPClient) ReadResource(ctx context.Context, uri string) (*Resource, error)

ReadResource 读取资源

func (*DefaultMCPClient) Start

func (c *DefaultMCPClient) Start(ctx context.Context) error

Start 启动客户端消息循环(兼容旧接口,内部调用 messageLoop)

func (*DefaultMCPClient) SubscribeResource

func (c *DefaultMCPClient) SubscribeResource(ctx context.Context, uri string) (<-chan Resource, error)

SubscribeResource 订阅资源更新

func (*DefaultMCPClient) UnsubscribeResource

func (c *DefaultMCPClient) UnsubscribeResource(ctx context.Context, uri string) error

UnsubscribeResource 取消订阅资源

type DefaultMCPServer

type DefaultMCPServer struct {
	// contains filtered or unexported fields
}

DefaultMCPServer 默认 MCP 服务器实现

func NewMCPServer

func NewMCPServer(name, version string, logger *zap.Logger) *DefaultMCPServer

NewMCPServer 创建 MCP 服务器

func (*DefaultMCPServer) CallTool

func (s *DefaultMCPServer) CallTool(ctx context.Context, name string, args map[string]any) (any, error)

CallTool 调用工具(带 30 秒超时控制)

func (*DefaultMCPServer) Close

func (s *DefaultMCPServer) Close() error

Close 关闭服务器

func (*DefaultMCPServer) DeleteResource

func (s *DefaultMCPServer) DeleteResource(uri string) error

DeleteResource 删除资源

func (*DefaultMCPServer) GetPrompt

func (s *DefaultMCPServer) GetPrompt(ctx context.Context, name string, vars map[string]string) (string, error)

GetPrompt 获取渲染后的提示词

func (*DefaultMCPServer) GetResource

func (s *DefaultMCPServer) GetResource(ctx context.Context, uri string) (*Resource, error)

GetResource 获取资源

func (*DefaultMCPServer) GetServerInfo

func (s *DefaultMCPServer) GetServerInfo() ServerInfo

GetServerInfo 获取服务器信息

func (*DefaultMCPServer) HandleMessage added in v1.0.0

func (s *DefaultMCPServer) HandleMessage(ctx context.Context, msg *MCPMessage) (*MCPMessage, error)

HandleMessage dispatches an incoming JSON-RPC 2.0 request to the appropriate server method and returns a JSON-RPC 2.0 response. Notifications (messages without an ID) return nil response and nil error.

func (*DefaultMCPServer) ListPrompts

func (s *DefaultMCPServer) ListPrompts(ctx context.Context) ([]PromptTemplate, error)

ListPrompts 列出所有提示词模板

func (*DefaultMCPServer) ListResources

func (s *DefaultMCPServer) ListResources(ctx context.Context) ([]Resource, error)

ListResources 列出所有资源

func (*DefaultMCPServer) ListTools

func (s *DefaultMCPServer) ListTools(ctx context.Context) ([]ToolDefinition, error)

ListTools 列出所有工具

func (*DefaultMCPServer) RegisterPrompt

func (s *DefaultMCPServer) RegisterPrompt(prompt *PromptTemplate) error

RegisterPrompt 注册提示词模板

func (*DefaultMCPServer) RegisterResource

func (s *DefaultMCPServer) RegisterResource(resource *Resource) error

RegisterResource 注册资源

func (*DefaultMCPServer) RegisterTool

func (s *DefaultMCPServer) RegisterTool(tool *ToolDefinition, handler ToolHandler) error

RegisterTool 注册工具

func (*DefaultMCPServer) Serve added in v1.0.0

func (s *DefaultMCPServer) Serve(ctx context.Context, transport Transport) error

Serve runs the MCP server message loop over the given transport. It receives messages, dispatches them via HandleMessage, and sends responses back. The loop exits when the context is cancelled or the transport returns an error.

func (*DefaultMCPServer) SetLogLevel

func (s *DefaultMCPServer) SetLogLevel(level string) error

SetLogLevel 设置日志级别

func (*DefaultMCPServer) SubscribeResource

func (s *DefaultMCPServer) SubscribeResource(ctx context.Context, uri string) (<-chan Resource, error)

SubscribeResource 订阅资源更新

func (*DefaultMCPServer) UnregisterPrompt

func (s *DefaultMCPServer) UnregisterPrompt(name string) error

UnregisterPrompt 注销提示词模板

func (*DefaultMCPServer) UnregisterTool

func (s *DefaultMCPServer) UnregisterTool(name string) error

UnregisterTool 注销工具

func (*DefaultMCPServer) UpdateResource

func (s *DefaultMCPServer) UpdateResource(resource *Resource) error

UpdateResource 更新资源

type MCPClient

type MCPClient interface {
	// 连接管理
	Connect(ctx context.Context, serverURL string) error
	Disconnect(ctx context.Context) error
	IsConnected() bool

	// 服务器交互
	GetServerInfo(ctx context.Context) (*ServerInfo, error)

	// 资源操作
	ListResources(ctx context.Context) ([]Resource, error)
	ReadResource(ctx context.Context, uri string) (*Resource, error)

	// 工具操作
	ListTools(ctx context.Context) ([]ToolDefinition, error)
	CallTool(ctx context.Context, name string, args map[string]any) (any, error)

	// 提示词操作
	ListPrompts(ctx context.Context) ([]PromptTemplate, error)
	GetPrompt(ctx context.Context, name string, vars map[string]string) (string, error)
}

MCPClient MCP 客户端接口

type MCPError

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

MCPError MCP 错误

type MCPHandler

type MCPHandler struct {
	// contains filtered or unexported fields
}

MCPHandler HTTP 处理器,将 MCP 服务器暴露为 HTTP 端点

func NewMCPHandler

func NewMCPHandler(server *DefaultMCPServer, logger *zap.Logger) *MCPHandler

NewMCPHandler 创建 MCP HTTP 处理器

func (*MCPHandler) ServeHTTP

func (h *MCPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP 实现 http.Handler

type MCPMessage

type MCPMessage struct {
	JSONRPC string         `json:"jsonrpc"`
	ID      any            `json:"id,omitempty"`
	Method  string         `json:"method,omitempty"`
	Params  map[string]any `json:"params,omitempty"`
	Result  any            `json:"result,omitempty"`
	Error   *MCPError      `json:"error,omitempty"`
}

MCPMessage MCP 消息(JSON-RPC 2.0)

func NewMCPError

func NewMCPError(id any, code int, message string, data any) *MCPMessage

NewMCPError 创建 MCP 错误响应

func NewMCPRequest

func NewMCPRequest(id any, method string, params map[string]any) *MCPMessage

NewMCPRequest 创建 MCP 请求

func NewMCPResponse

func NewMCPResponse(id any, result any) *MCPMessage

NewMCPResponse 创建 MCP 响应

func (*MCPMessage) MarshalJSON

func (m *MCPMessage) MarshalJSON() ([]byte, error)

MarshalJSON 自定义 JSON 序列化

type MCPServer

type MCPServer interface {
	// 服务器信息
	GetServerInfo() ServerInfo

	// 资源管理
	ListResources(ctx context.Context) ([]Resource, error)
	GetResource(ctx context.Context, uri string) (*Resource, error)
	SubscribeResource(ctx context.Context, uri string) (<-chan Resource, error)

	// 工具管理
	ListTools(ctx context.Context) ([]ToolDefinition, error)
	CallTool(ctx context.Context, name string, args map[string]any) (any, error)

	// 提示词管理
	ListPrompts(ctx context.Context) ([]PromptTemplate, error)
	GetPrompt(ctx context.Context, name string, vars map[string]string) (string, error)

	// 日志
	SetLogLevel(level string) error
}

MCPServer MCP 服务器接口

type PromptExample

type PromptExample struct {
	Variables map[string]string `json:"variables"`
	Output    string            `json:"output"`
}

PromptExample 提示词示例

type PromptTemplate

type PromptTemplate struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Template    string          `json:"template"`
	Variables   []string        `json:"variables"`
	Examples    []PromptExample `json:"examples,omitempty"`
	Metadata    map[string]any  `json:"metadata,omitempty"`
}

PromptTemplate MCP 提示词模板

func (*PromptTemplate) RenderPrompt

func (p *PromptTemplate) RenderPrompt(vars map[string]string) (string, error)

RenderPrompt 渲染提示词模板

func (*PromptTemplate) Validate

func (p *PromptTemplate) Validate() error

ValidatePromptTemplate 验证提示词模板

type Resource

type Resource struct {
	URI         string         `json:"uri"`         // 资源 URI
	Name        string         `json:"name"`        // 资源名称
	Description string         `json:"description"` // 资源描述
	Type        ResourceType   `json:"type"`        // 资源类型
	MimeType    string         `json:"mimeType"`    // MIME 类型
	Content     any            `json:"content"`     // 资源内容
	Metadata    map[string]any `json:"metadata"`    // 元数据
	Size        int64          `json:"size"`        // 资源大小(字节)
	CreatedAt   time.Time      `json:"createdAt"`   // 创建时间
	UpdatedAt   time.Time      `json:"updatedAt"`   // 更新时间
}

Resource MCP 资源

func (*Resource) Validate

func (r *Resource) Validate() error

ValidateResource 验证资源

type ResourceType

type ResourceType string

ResourceType 资源类型

const (
	ResourceTypeText   ResourceType = "text"
	ResourceTypeImage  ResourceType = "image"
	ResourceTypeFile   ResourceType = "file"
	ResourceTypeData   ResourceType = "data"
	ResourceTypeStream ResourceType = "stream"
)

type SSETransport

type SSETransport struct {
	// contains filtered or unexported fields
}

SSETransport SSE 传输,GET /sse 接收事件,POST /message 发送

func NewSSETransport

func NewSSETransport(endpoint string, logger *zap.Logger) *SSETransport

NewSSETransport 创建 SSE 传输

func (*SSETransport) Close

func (t *SSETransport) Close() error

Close 关闭 SSE 传输

func (*SSETransport) Connect

func (t *SSETransport) Connect(ctx context.Context) error

Connect 建立 SSE 连接(GET /sse)

func (*SSETransport) Receive

func (t *SSETransport) Receive(ctx context.Context) (*MCPMessage, error)

Receive 从 SSE 事件通道接收消息

func (*SSETransport) Send

func (t *SSETransport) Send(ctx context.Context, msg *MCPMessage) error

Send 通过 POST /message 发送消息

type ServerCapabilities

type ServerCapabilities struct {
	Resources bool `json:"resources"`
	Tools     bool `json:"tools"`
	Prompts   bool `json:"prompts"`
	Logging   bool `json:"logging"`
	Sampling  bool `json:"sampling"`
}

ServerCapabilities 服务器能力

type ServerInfo

type ServerInfo struct {
	Name            string             `json:"name"`
	Version         string             `json:"version"`
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ServerCapabilities `json:"capabilities"`
	Metadata        map[string]any     `json:"metadata,omitempty"`
}

ServerInfo 服务器信息

type StdioTransport

type StdioTransport struct {
	// contains filtered or unexported fields
}

StdioTransport 基于 bufio.Reader/io.Writer 的 stdio 传输

func NewStdioTransport

func NewStdioTransport(reader io.Reader, writer io.Writer, logger *zap.Logger) *StdioTransport

NewStdioTransport 创建 stdio 传输

func (*StdioTransport) Close

func (t *StdioTransport) Close() error

Close 关闭 stdio 传输(无操作)

func (*StdioTransport) Receive

func (t *StdioTransport) Receive(ctx context.Context) (*MCPMessage, error)

Receive 接收消息(读取 Content-Length 头 + JSON body)

func (*StdioTransport) Send

func (t *StdioTransport) Send(ctx context.Context, msg *MCPMessage) error

Send 发送消息(Content-Length 头 + JSON body)

type ToolCall

type ToolCall struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
}

ToolCall 工具调用(复用 protocol.go 中的定义)

type ToolDefinition

type ToolDefinition struct {
	Name         string         `json:"name"`
	Description  string         `json:"description"`
	InputSchema  map[string]any `json:"inputSchema"` // JSON Schema
	OutputSchema map[string]any `json:"outputSchema,omitempty"`
	Metadata     map[string]any `json:"metadata,omitempty"`
}

ToolDefinition MCP 工具定义

func FromLLMToolSchema

func FromLLMToolSchema(schema llm.ToolSchema) (ToolDefinition, error)

FromLLMToolSchema 从 LLM 工具 Schema 创建 MCP 工具定义

func (*ToolDefinition) ToLLMToolSchema

func (t *ToolDefinition) ToLLMToolSchema() llm.ToolSchema

ToLLMToolSchema 将 MCP 工具定义转换为 LLM 工具 Schema

func (*ToolDefinition) Validate

func (t *ToolDefinition) Validate() error

ValidateToolDefinition 验证工具定义

type ToolHandler

type ToolHandler func(ctx context.Context, args map[string]any) (any, error)

ToolHandler 工具处理函数

type Transport

type Transport interface {
	// Send 发送消息
	Send(ctx context.Context, msg *MCPMessage) error
	// Receive 接收消息(阻塞)
	Receive(ctx context.Context) (*MCPMessage, error)
	// Close 关闭传输
	Close() error
}

Transport MCP 传输层接口

type WSState

type WSState string

WSState represents the connection state of a WebSocket transport.

const (
	WSStateDisconnected WSState = "disconnected"
	WSStateConnecting   WSState = "connecting"
	WSStateConnected    WSState = "connected"
	WSStateReconnecting WSState = "reconnecting"
	WSStateFailed       WSState = "failed"
	WSStateClosed       WSState = "closed"
)

type WSTransportConfig

type WSTransportConfig struct {
	HeartbeatInterval time.Duration // Interval between heartbeat pings (default 30s)
	HeartbeatTimeout  time.Duration // Max time without a pong before considering dead (default 10s)
	MaxReconnects     int           // Maximum reconnection attempts (default 5, 0 = no reconnect)
	ReconnectDelay    time.Duration // Base delay for exponential backoff (default 1s)
	MaxBackoff        time.Duration // Maximum backoff duration (default 30s)
	BackoffMultiplier float64       // Backoff multiplier (default 2.0)
	ReconnectEnabled  bool          // Whether auto-reconnect is enabled (default true)
	EnableHeartbeat   bool          // Whether to enable heartbeat (default true)
	Subprotocols      []string      // WebSocket subprotocols (default ["mcp"])
	SendBufferSize    int           // Outbound message buffer size during reconnect (default 64)
}

WSTransportConfig configures the WebSocket transport behavior.

func DefaultWSTransportConfig

func DefaultWSTransportConfig() WSTransportConfig

DefaultWSTransportConfig returns a WSTransportConfig with sensible defaults.

type WebSocketTransport

type WebSocketTransport struct {
	// contains filtered or unexported fields
}

WebSocketTransport implements MCP Transport over WebSocket with heartbeat, exponential-backoff reconnection, and connection state callbacks.

func NewWebSocketTransport

func NewWebSocketTransport(url string, logger *zap.Logger) *WebSocketTransport

NewWebSocketTransport creates a WebSocket transport with default configuration. This preserves backward compatibility with the original constructor.

func NewWebSocketTransportWithConfig

func NewWebSocketTransportWithConfig(url string, config WSTransportConfig, logger *zap.Logger) *WebSocketTransport

NewWebSocketTransportWithConfig creates a WebSocket transport with custom configuration.

func (*WebSocketTransport) Close

func (t *WebSocketTransport) Close() error

Close shuts down the transport, stopping the heartbeat goroutine and closing the underlying WebSocket connection.

func (*WebSocketTransport) Connect

func (t *WebSocketTransport) Connect(ctx context.Context) error

Connect establishes the WebSocket connection and starts the heartbeat goroutine.

func (*WebSocketTransport) IsConnected

func (t *WebSocketTransport) IsConnected() bool

IsConnected returns true when the transport has an active connection.

func (*WebSocketTransport) OnStateChange

func (t *WebSocketTransport) OnStateChange(fn func(WSState))

OnStateChange registers a callback invoked whenever the connection state changes.

func (*WebSocketTransport) Receive

func (t *WebSocketTransport) Receive(ctx context.Context) (*MCPMessage, error)

Receive reads the next JSON-RPC message from the WebSocket connection. If the received message is a heartbeat pong (method "pong"), it updates lastHeartbeat and reads the next message instead. On read errors, it attempts reconnection if enabled before returning the error.

func (*WebSocketTransport) Send

func (t *WebSocketTransport) Send(ctx context.Context, msg *MCPMessage) error

Send writes a JSON-RPC message over the WebSocket connection. The write is mutex-protected to be safe for concurrent callers. If the write fails and reconnect is enabled, it attempts to reconnect and retries the send once. Messages are buffered during reconnection.

func (*WebSocketTransport) State

func (t *WebSocketTransport) State() WSState

State returns the current connection state.

Jump to

Keyboard shortcuts

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