mcp

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

MCP(Model Context Protocol)客户端(包内说明)

本包用于让 kubectl-qyai 作为 MCP Client 连接一个或多个 MCP Server,并发现/注册它们提供的工具。

本 README 面向包级使用与实现说明;使用方式(面向使用者)请看仓库根目录 README.md 的「远程/自动化:使用 MCP」章节。

功能概览

  • 同时连接多个 MCP Server
  • 支持 stdio(本地进程)与 HTTP(远端服务)两种传输
  • HTTP 服务器可选鉴权(Basic / Bearer / API Key)
  • 自动发现工具列表并注册到工具系统
  • 参数名与类型做通用转换(例如 snake_case → camelCase,按命名做简单类型推断)
  • 同步初始化:在会话开始前尽量把工具准备好

配置文件

默认配置路径:

  • ~/.config/kubectl-qyai/mcp.yaml

你也可以通过环境变量覆盖默认路径:

  • KUBECTL_QYAI_MCP_CONFIG:指定 MCP 配置文件路径

若默认文件不存在,本包会创建一个基础默认配置(具体内容以 pkg/mcp/default_config.yaml 为准)。

配置格式(YAML)
1) 本地(stdio)Server
servers:
  - name: server-name
    command: /path/to/server-binary
    args:
      - --flag1
      - value1
    env:
      ENV_VAR: value
2) 远端(HTTP)Server
servers:
  - name: remote-server
    url: "https://mcp-server.example.com/mcp"
    timeout: 30
    use_streaming: true
    auth:
      type: "bearer"  # basic | bearer | api-key
      token: "${YOUR_ENV_VAR}"  # 从环境变量读取

安全提醒:敏感信息建议用 ${VAR_NAME} 从环境变量读取,不要把明文密钥直接提交到配置文件。

运行与状态输出

当上层启用 MCP Client(例如在模型配置中开启 mcp_client_enabled: true)后,会在启动/初始化阶段连接配置的服务器,并输出连接状态与已发现工具数量(日志级别相关)。

参数转换

为了尽量兼容不同实现,本包会做一些“通用参数转换”:

  • 参数名:snake_case → camelCase
  • 参数类型:根据命名包含 count/limit/max/min/total 等字段尝试转换为数字;根据 is/has/enable 等字段尝试转换为布尔

如果转换失败,会保留原始值。

安全注意事项

  • 连接到 MCP Server 等价于允许它们在本机/网络范围内执行其提供的工具能力。
  • 只连接你信任的 MCP Server。
  • 配置文件默认权限较严格(0600),避免泄露敏感信息。

排障建议

  • 确认配置文件路径正确且 YAML 合法。
  • stdio 类型:确认 command/args 在当前环境可执行。
  • HTTP 类型:确认 url 可访问,鉴权信息正确。
  • 需要更多日志时可提高日志级别(如你的构建启用了相关参数)。

Documentation

Index

Constants

View Source
const (
	// DefaultConnectionTimeout is the timeout for establishing connections to MCP servers
	DefaultConnectionTimeout = 30 * time.Second

	// DefaultVerificationTimeout is the timeout for verifying server connections
	DefaultVerificationTimeout = 10 * time.Second

	// DefaultPingTimeout is the timeout for ping operations
	DefaultPingTimeout = 5 * time.Second

	// DefaultStabilizationDelay is the delay to allow servers to stabilize after connection
	DefaultStabilizationDelay = 2 * time.Second
)

Timeout constants for MCP operations

View Source
const (
	ErrServerConnectionFmt = "connecting to MCP server %q: %w"
	ErrServerCloseFmt      = "closing MCP client %q: %w"
	ErrToolCallFmt         = "calling tool %q: %w"
	ErrPathCheckFmt        = "checking path %q: %w"
)

Error message templates

View Source
const (
	ClientName    = "kubectl-qyai-mcp-client"
	ClientVersion = "1.0.0"
)

Client constants

View Source
const (
	ConfigFilePermissions = 0600
	ConfigDirPermissions  = 0755
)

File permissions

View Source
const (
	// EnvMCPServerPrefix is the prefix for MCP server environment variables
	EnvMCPServerPrefix = "MCP_"
)

Constants for environment variables

Variables

This section is empty.

Functions

func ConvertArgs

func ConvertArgs(args map[string]any) map[string]any

ConvertArgs handles all argument conversions for MCP tools. It transforms keys from snake_case to camelCase and converts values to appropriate types.

func ConvertValue

func ConvertValue(paramName string, value any) any

ConvertValue infers and converts a value to an appropriate type based on the parameter name.

func DefaultConfigPath

func DefaultConfigPath() (string, error)

DefaultConfigPath returns the default path to the MCP config file

func GroupToolsByServer

func GroupToolsByServer(tools map[string][]Tool) map[string]int

GroupToolsByServer groups tools by their server name for easier display

func IsBoolParam

func IsBoolParam(name string) bool

IsBoolParam checks if a parameter name suggests a boolean value.

func IsNumberParam

func IsNumberParam(name string) bool

IsNumberParam checks if a parameter name suggests a numeric value.

func RetryOperation

func RetryOperation(ctx context.Context, config RetryConfig, operation func() error) error

RetryOperation executes an operation with exponential backoff retry

func SanitizeServerName

func SanitizeServerName(name string) string

SanitizeServerName ensures server names are valid identifiers

func SnakeToCamel

func SnakeToCamel(s string) string

SnakeToCamel converts a snake_case string to camelCase.

func ValidateServerConfig

func ValidateServerConfig(config ServerConfig) error

ValidateServerConfig validates a single server configuration

Types

type AuthConfig

type AuthConfig struct {
	Type       string // "none", "basic", "bearer", "api-key"
	Username   string // For basic auth
	Password   string // For basic auth
	Token      string // For bearer auth
	ApiKey     string // For API key auth
	HeaderName string // Custom header name for API key
}

AuthConfig represents authentication options for HTTP MCP servers

type Client

type Client struct {
	// Name is a friendly name for this MCP server connection
	Name string
	// contains filtered or unexported fields
}

Client represents an MCP client that can connect to MCP servers. It is a wrapper around the MCPClient interface for backward compatibility.

func CreateStdioClient

func CreateStdioClient(name, command string, args []string, env map[string]string) *Client

CreateStdioClient creates a new stdio-based MCP client (for backward compatibility).

func NewClient

func NewClient(config ClientConfig) *Client

NewClient creates a new MCP client with the given configuration. This function supports both stdio and HTTP-based MCP servers.

func (*Client) CallTool

func (c *Client) CallTool(ctx context.Context, toolName string, arguments map[string]interface{}) (string, error)

CallTool calls a tool on the MCP server and returns the result as a string. The arguments should be a map of parameter names to values that will be passed to the tool.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection to the MCP server.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect establishes a connection to the MCP server. This delegates to the appropriate implementation (stdio or HTTP).

func (*Client) ListTools

func (c *Client) ListTools(ctx context.Context) ([]Tool, error)

ListTools lists all available tools from the MCP server.

type ClientConfig

type ClientConfig struct {
	// Common fields
	Name string

	// For stdio-based clients
	Command string
	Args    []string
	Env     []string

	// For HTTP-based clients
	URL          string
	Auth         *AuthConfig
	OAuthConfig  *OAuthConfig
	Timeout      int
	UseStreaming bool              // Whether to use streaming HTTP for better performance
	SkipVerify   bool              // Whether to skip TLS certificate verification for HTTPS connections
	Headers      map[string]string // Custom headers to include in HTTP requests

}

ClientConfig contains all configuration options for MCP clients

type Config

type Config struct {
	// Servers is a list of MCP server configurations
	Servers []ServerConfig `yaml:"servers,omitempty"`
}

Config represents the complete MCP client configuration file

func LoadConfig

func LoadConfig(path string) (*Config, error)

LoadConfig loads the MCP configuration from the given path and applies environment variable overrides If path is empty, the default config path is used If the file doesn't exist, it creates a default configuration file

func (*Config) Save

func (c *Config) Save(path string) error

Save saves the configuration to the given path using atomic write

func (*Config) ValidateConfig

func (c *Config) ValidateConfig() error

ValidateConfig validates the entire configuration

type FunctionDefinition

type FunctionDefinition interface {
	// Schema returns a representation of the function schema
	Schema() any
}

FunctionDefinition is an interface representing generic function schema definitions This allows the MCP package to create schemas without directly depending on gollm

type MCPClient

type MCPClient interface {
	// Name returns the name of this client
	Name() string

	// Connect establishes a connection to the MCP server
	Connect(ctx context.Context) error

	// Close closes the connection to the MCP server
	Close() error

	// ListTools lists all available tools from the MCP server
	ListTools(ctx context.Context) ([]Tool, error)

	// CallTool calls a tool on the MCP server and returns the result as a string
	CallTool(ctx context.Context, toolName string, arguments map[string]interface{}) (string, error)
	// contains filtered or unexported methods
}

MCPClient defines the common interface for all MCP client implementations

func NewHTTPClient

func NewHTTPClient(config ClientConfig) MCPClient

NewHTTPClient creates a new HTTP-based MCP client

func NewMCPClient

func NewMCPClient(config ClientConfig) (MCPClient, error)

NewMCPClient creates a new MCP client with the appropriate implementation based on the config

func NewStdioClient

func NewStdioClient(config ClientConfig) MCPClient

NewStdioClient creates a new stdio-based MCP client

type MCPStatus

type MCPStatus struct {
	ServerInfoList []ServerConnectionInfo
	TotalServers   int
	ConnectedCount int
	FailedCount    int
	TotalTools     int
	ClientEnabled  bool
}

MCPStatus represents the overall status of MCP servers and tools

type Manager

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

Manager handles MCP client connections and tool discovery

func InitializeManager

func InitializeManager() (*Manager, error)

InitializeManager creates and initializes the MCP manager with configuration loaded from default paths

func NewManager

func NewManager(config *Config) *Manager

NewManager creates a new MCP manager with the given configuration

func (*Manager) Close

func (m *Manager) Close() error

Close closes all MCP client connections

func (*Manager) ConnectAll

func (m *Manager) ConnectAll(ctx context.Context) error

ConnectAll connects to all configured MCP servers

func (*Manager) DiscoverAndConnectServers

func (m *Manager) DiscoverAndConnectServers(ctx context.Context) error

DiscoverAndConnectServers connects to all configured servers with a timeout and stabilization delay

func (*Manager) GetClient

func (m *Manager) GetClient(name string) (*Client, bool)

GetClient returns a connected MCP client by name

func (*Manager) GetStatus

func (m *Manager) GetStatus(ctx context.Context, mcpClientEnabled bool) (*MCPStatus, error)

GetStatus returns status of all MCP servers and their tools

func (*Manager) ListAvailableTools

func (m *Manager) ListAvailableTools(ctx context.Context) (map[string][]Tool, error)

ListAvailableTools returns tools from all connected servers For retries and more robust handling, use RefreshToolDiscovery

func (*Manager) ListClients

func (m *Manager) ListClients() []*Client

ListClients returns a list of all connected MCP clients

func (*Manager) LogConfig

func (m *Manager) LogConfig(mcpConfigPath string) error

LogConfig logs the MCP configuration summary If mcpConfigPath is empty, uses the Manager's existing config

func (*Manager) RefreshToolDiscovery

func (m *Manager) RefreshToolDiscovery(ctx context.Context) (map[string][]Tool, error)

RefreshToolDiscovery discovers tools from all servers with retries

func (*Manager) RegisterTools

func (m *Manager) RegisterTools(ctx context.Context, registerCallback func(serverName string, tool Tool) error) error

RegisterTools discovers and registers tools from all MCP servers using the provided callback The callback function is responsible for creating and registering tool wrappers

func (*Manager) RegisterWithToolSystem

func (m *Manager) RegisterWithToolSystem(ctx context.Context, registerCallback func(serverName string, tool Tool) error) error

RegisterWithToolSystem connects to MCP servers and registers discovered tools with an external tool system using the provided callback function. This simplifies integration with kubectl-qyai's tool system.

type OAuthConfig

type OAuthConfig struct {
	ClientID     string
	ClientSecret string
	TokenURL     string
	AuthURL      string
	Scopes       []string
	RedirectURL  string
}

OAuthConfig represents OAuth configuration for HTTP MCP servers

type RetryConfig

type RetryConfig struct {
	MaxRetries  int
	BaseDelay   time.Duration
	MaxDelay    time.Duration
	Multiplier  float64
	Description string
}

RetryConfig defines retry behavior for MCP operations

func DefaultRetryConfig

func DefaultRetryConfig(description string) RetryConfig

DefaultRetryConfig returns a sensible default retry configuration

type SchemaBuilder

type SchemaBuilder func(tool *Tool) (FunctionDefinition, error)

SchemaBuilder is a function that builds a function definition from a tool

type SchemaProperty

type SchemaProperty interface {
	// Property returns a representation of the schema property
	Property() any
}

SchemaProperty is an interface representing generic schema properties

type ServerConfig

type ServerConfig struct {
	// Name is a friendly name for this MCP server
	Name string `yaml:"name"`
	// Command is the command to execute for stdio-based MCP servers
	Command string `yaml:"command"`
	// Args are the arguments to pass to the command
	Args []string `yaml:"args,omitempty"`
	// Env are the environment variables to set for the command
	Env map[string]string `yaml:"env,omitempty"`
	// URL is the URL for HTTP-based MCP servers
	URL string `yaml:"url,omitempty"`
	// Auth is the authentication configuration for HTTP-based MCP servers
	Auth *AuthConfig `yaml:"auth,omitempty"`
	// OAuthConfig is the OAuth configuration for HTTP-based MCP servers
	OAuthConfig *OAuthConfig `yaml:"oauth,omitempty"`
	// Timeout is the timeout in seconds for HTTP requests
	Timeout int `yaml:"timeout,omitempty"`
	// UseStreaming enables streaming HTTP for better performance
	UseStreaming bool `yaml:"use_streaming,omitempty"`
	// SkipVerify skips TLS certificate verification for HTTPS connections
	SkipVerify bool `yaml:"skip_verify,omitempty"`
}

ServerConfig represents the configuration for a single MCP server

type ServerConnectionInfo

type ServerConnectionInfo struct {
	Name           string
	Command        string
	IsLegacy       bool
	IsConnected    bool
	AvailableTools []Tool
}

ServerConnectionInfo holds connection status for a single MCP server

type Tool

type Tool struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Server      string `json:"server,omitempty"`

	InputSchema *gollm.Schema `json:"inputSchema,omitempty"`
}

Tool represents an MCP tool with optional server information.

func (Tool) AsBasicTool

func (t Tool) AsBasicTool() Tool

AsBasicTool returns the tool without server information (for client.ListTools compatibility).

func (Tool) ID

func (t Tool) ID() string

ID returns a unique identifier for the tool.

func (Tool) IsFromServer

func (t Tool) IsFromServer(server string) bool

IsFromServer checks if the tool belongs to a specific server.

func (Tool) String

func (t Tool) String() string

String returns a human-readable representation of the tool.

func (Tool) WithServer

func (t Tool) WithServer(server string) Tool

WithServer returns a copy of the tool with server information added.

Source Files

  • client.go
  • config.go
  • constants.go
  • http_client.go
  • interfaces.go
  • manager.go
  • stdio_client.go
  • utils.go

Jump to

Keyboard shortcuts

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