mcp

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package mcp 把外部 MCP(Model Context Protocol)服务提供的工具接入 gobrave 的 工具框架(从 opencode internal/llm/agent/mcp-tools.go 迁移)。

与 opencode 的差异:

  • 工具不再实现 opencode 的 tools.BaseTool,而是直接实现 gobrave 的 tool.Tool, 因此能被 tool.Registry / ToolRunner 统一调度(权限门禁、事件流都复用);
  • 配置不再读取 opencode 的全局 config,而是由调用方显式传入 Server 列表;
  • 不再把工具缓存在包级变量里,改为 Manager 实例持有缓存,便于测试与多实例。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Discover

func Discover(ctx context.Context, servers map[string]Server) []tool.Tool

Discover 连接各 MCP 服务并列出其工具。

单个服务连接 / 列工具失败只记录日志并跳过,不会让整个发现流程失败。

func EnvSlice

func EnvSlice(env map[string]string) []string

EnvSlice 把 env map 转换为 KEY=VALUE 切片(按 key 排序,保证结果稳定)。

func ServersFromConfig

func ServersFromConfig(cfg *config.MCPConfig) map[string]Server

ServersFromConfig 把 mcp 配置段转换为 Server 表。

总开关关闭、未配置服务或单个服务 enabled=false 时跳过该服务。 Normalize 会在写入配置前补齐 type 并校验必填项,这里仍做一次兜底推断, 以兼容直接构造配置结构体的调用方(如测试)。

Types

type MCPServer

type MCPServer struct {
	// Name 是配置中的服务名,工具名会被拼成 <server>_<tool>。
	Name string
	// Config 是该服务的连接配置。
	Config Server
	// Tool 是发现的工具定义。
	Tool mcp.Tool
}

MCPServer 是一个 MCP 工具对应的服务端连接。

type Manager

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

Manager 持有 MCP 工具发现结果(懒加载 + 进程内缓存)。

配置在构造时固定;如需热更新配置,请重新创建 Manager。

func NewManager

func NewManager(servers map[string]Server) *Manager

NewManager 创建 MCP 工具管理器。

func (*Manager) Tools

func (m *Manager) Tools(ctx context.Context) []tool.Tool

Tools 返回 MCP 工具(首次调用时发现并缓存)。

type Server

type Server struct {
	// Type 是传输类型:stdio / sse。
	Type Type
	// Command / Args / Env 仅 stdio 使用。
	Command string
	Args    []string
	Env     []string
	// URL / Headers 仅 sse 使用。
	URL     string
	Headers map[string]string
}

Server 是一个 MCP 服务的连接配置。

type Tool

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

Tool 实现 tool.Tool:每次执行时新建连接 → initialize → CallTool → 关闭。

之所以不常驻连接,是为了避免 stdio 子进程长期存活、以及 SSE 连接掉线后的 重连状态管理;MCP 服务本身通常启动很快(与 opencode 行为一致)。

func (*Tool) Definition

func (t *Tool) Definition() tool.Definition

Definition 实现 tool.Tool。

func (*Tool) Execute

func (t *Tool) Execute(ctx context.Context, args json.RawMessage) (any, error)

Execute 实现 tool.Tool:连接服务 → initialize → 调用工具 → 返回文本结果。

type Type

type Type string

Type 是 MCP 服务的传输类型。

const (
	// TypeStdio 通过子进程 stdin/stdout 通信。
	TypeStdio Type = "stdio"
	// TypeSSE 通过 HTTP SSE 通信。
	TypeSSE Type = "sse"
)

Jump to

Keyboard shortcuts

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