mcp

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

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

func AsMCPClientLike added in v1.6.0

func AsMCPClientLike(c *DefaultMCPClient) hosted.MCPClientLike

Types

type ClientOption added in v1.6.0

type ClientOption func(*DefaultMCPClient)

ClientOption configures optional DefaultMCPClient behavior.

func WithToolsChangedHandler added in v1.6.0

func WithToolsChangedHandler(fn ToolsChangedHandler) ClientOption

WithToolsChangedHandler registers a callback for tools/list_changed notifications.

type DefaultMCPClient

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

func NewDefaultMCPClient added in v1.6.0

func NewDefaultMCPClient(transport Transport, logger *zap.Logger, opts ...ClientOption) *DefaultMCPClient

func (*DefaultMCPClient) CallTool

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

func (*DefaultMCPClient) Close added in v1.6.0

func (c *DefaultMCPClient) Close() error

func (*DefaultMCPClient) GetPrompt

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

func (*DefaultMCPClient) Initialize added in v1.6.0

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

func (*DefaultMCPClient) ListPrompts

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

func (*DefaultMCPClient) ListResources

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

func (*DefaultMCPClient) ListTools

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

func (*DefaultMCPClient) ReadResource

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

func (*DefaultMCPClient) RefreshTools added in v1.6.0

func (c *DefaultMCPClient) RefreshTools(ctx context.Context) ([]MCPTool, error)

RefreshTools re-fetches the tool list and invokes the ToolsChangedHandler if registered. Use after receiving a tools/list_changed notification or periodically for polling.

func (*DefaultMCPClient) StartNotificationListener added in v1.6.0

func (c *DefaultMCPClient) StartNotificationListener(ctx context.Context)

StartNotificationListener begins a background goroutine that reads messages from the transport. Notifications (messages with Method but no ID) are dispatched to registered handlers. Call Close() to stop the listener.

Only useful with streaming transports (SSE). For request-response transports, use RefreshTools with polling instead.

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 InProcessTransport added in v1.6.0

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

InProcessTransport implements Transport for direct in-process communication. No network or subprocess overhead; ideal for testing and embedded servers.

Note: This transport is request-response only. Do NOT use it with StartNotificationListener, as the listener would consume request responses.

func NewInProcessTransport added in v1.6.0

func NewInProcessTransport(handler MCPServerHandler, opts ...InProcessTransportOption) *InProcessTransport

NewInProcessTransport creates a transport that routes messages directly to handler.

func (*InProcessTransport) Close added in v1.6.0

func (t *InProcessTransport) Close() error

func (*InProcessTransport) IsAlive added in v1.6.0

func (t *InProcessTransport) IsAlive() bool

func (*InProcessTransport) Receive added in v1.6.0

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

func (*InProcessTransport) Send added in v1.6.0

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

type InProcessTransportOption added in v1.6.0

type InProcessTransportOption func(*InProcessTransport)

InProcessTransportOption configures optional InProcessTransport behavior.

func WithNotificationErrorHandler added in v1.6.0

func WithNotificationErrorHandler(fn func(method string, err error)) InProcessTransportOption

WithNotificationErrorHandler sets a callback for notification handler errors.

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 MCPClientManager added in v1.6.0

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

MCPClientManager manages multiple MCP server connections by name, with health checking and automatic reconnection support.

func NewMCPClientManager added in v1.6.0

func NewMCPClientManager(logger *zap.Logger) *MCPClientManager

NewMCPClientManager creates a new multi-server client manager.

func (*MCPClientManager) CloseAll added in v1.6.0

func (m *MCPClientManager) CloseAll() error

CloseAll shuts down all client connections and stops the health checker.

func (*MCPClientManager) Get added in v1.6.0

func (m *MCPClientManager) Get(name string) (*DefaultMCPClient, error)

Get returns the client for the named server.

func (*MCPClientManager) ListAllTools added in v1.6.0

func (m *MCPClientManager) ListAllTools(ctx context.Context) (map[string][]MCPTool, error)

ListAllTools returns tools from all registered servers.

func (*MCPClientManager) ListServers added in v1.6.0

func (m *MCPClientManager) ListServers() []string

ListServers returns all registered server names.

func (*MCPClientManager) Register added in v1.6.0

func (m *MCPClientManager) Register(ctx context.Context, name string, transport Transport) error

Register adds a named MCP client and initializes it. On success, the manager takes ownership of the transport. On failure, the caller is responsible for closing the transport.

func (*MCPClientManager) RegisterWithFactory added in v1.6.0

func (m *MCPClientManager) RegisterWithFactory(ctx context.Context, name string, transport Transport, factory TransportFactory) error

RegisterWithFactory adds a named MCP client with an optional factory for automatic reconnection.

func (*MCPClientManager) Remove added in v1.6.0

func (m *MCPClientManager) Remove(name string) error

Remove closes and removes the named server connection.

func (*MCPClientManager) StartHealthCheck added in v1.6.0

func (m *MCPClientManager) StartHealthCheck(ctx context.Context, interval time.Duration)

StartHealthCheck launches a background goroutine that periodically checks all client transports and attempts reconnection for unhealthy ones.

type MCPError

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

MCPError MCP 错误

func NewMCPErrorValue added in v1.5.0

func NewMCPErrorValue(code int, message string, data any, cause error) *MCPError

NewMCPErrorValue creates a MCPError value with an optional cause.

func NewMCPInternalError added in v1.5.0

func NewMCPInternalError(err error) *MCPError

NewMCPInternalError creates a standard internal error with causal chain.

func (*MCPError) Error added in v1.5.0

func (e *MCPError) Error() string

Error implements the error interface.

func (*MCPError) Unwrap added in v1.5.0

func (e *MCPError) Unwrap() error

Unwrap exposes the underlying cause for errors.Is/errors.As.

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 MCPServerHandler added in v1.6.0

type MCPServerHandler interface {
	HandleRequest(ctx context.Context, msg *MCPMessage) (*MCPMessage, error)
}

MCPServerHandler processes MCP JSON-RPC requests and returns responses. Implement this interface to create an in-process MCP server.

type MCPTool added in v1.6.0

type MCPTool struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	InputSchema map[string]any `json:"inputSchema"`
}

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
}

func NewSSETransport

func NewSSETransport(baseURL string, opts ...SSETransportOption) *SSETransport

func (*SSETransport) Close

func (s *SSETransport) Close() error

func (*SSETransport) IsAlive added in v1.6.0

func (s *SSETransport) IsAlive() bool

func (*SSETransport) Receive

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

func (*SSETransport) Send

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

type SSETransportOption added in v1.6.0

type SSETransportOption func(*SSETransport)

SSETransportOption configures optional SSETransport settings.

func WithAuthToken added in v1.6.0

func WithAuthToken(token string) SSETransportOption

WithAuthToken sets a Bearer token on all outgoing requests.

func WithSSEHeader added in v1.6.0

func WithSSEHeader(key, value string) SSETransportOption

WithSSEHeader sets a custom header on all outgoing requests.

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
}

func NewStdioTransport

func NewStdioTransport(command string, args ...string) (*StdioTransport, error)

func (*StdioTransport) Close

func (s *StdioTransport) Close() error

func (*StdioTransport) IsAlive added in v1.6.0

func (s *StdioTransport) IsAlive() bool

func (*StdioTransport) Receive

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

func (*StdioTransport) Send

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

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 types.ToolSchema) (ToolDefinition, error)

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

func (*ToolDefinition) ToLLMToolSchema

func (t *ToolDefinition) ToLLMToolSchema() types.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 ToolsChangedHandler added in v1.6.0

type ToolsChangedHandler func(ctx context.Context, tools []MCPTool)

ToolsChangedHandler is called when the server notifies that its tool list has changed.

type Transport

type Transport interface {
	// Send 发送消息
	Send(ctx context.Context, msg *MCPMessage) error
	// Receive 接收消息(阻塞)
	Receive(ctx context.Context) (*MCPMessage, error)
	// Close 关闭传输
	Close() error
	// IsAlive reports whether the transport connection is still active.
	// Implementations that cannot determine liveness should return true.
	IsAlive() bool
}

Transport MCP 传输层接口

type TransportFactory added in v1.6.0

type TransportFactory func() (Transport, error)

TransportFactory creates a new Transport for reconnection.

Jump to

Keyboard shortcuts

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