plugin

package
v0.0.8-20250724 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

plugin.go 插件系统核心文件,基于 hashicorp/go-plugin 实现 提供插件的加载、管理和调用功能

plugin/result.go - 工具调用结果相关类型定义

plugin/tool.go - 工具相关类型定义和工具选项函数

Index

Constants

This section is empty.

Variables

View Source
var HandshakeConfig = plugin.HandshakeConfig{
	ProtocolVersion:  1,
	MagicCookieKey:   "TOOL_PLUGIN",
	MagicCookieValue: "tool_v1.0.0",
}

HandshakeConfig 定义了主程序和插件之间的握手配置 用于确保版本兼容性和安全性

View Source
var PluginMap = map[string]plugin.Plugin{
	"tool": &ToolPlugin{},
}

PluginMap 是插件映射表 定义了可用的插件类型

Functions

func RegisterStructType

func RegisterStructType(structType any)

RegisterStructType 注册自定义结构体类型,用于 RPC 通信 注意:由于客户端现在会自动将结构体转换为map,通常不再需要调用此函数 此函数保留用于特殊情况下需要传递原始结构体的场景 例如:RegisterStructType(MyCustomStruct{}) 将注册 MyCustomStruct 类型

func ServePlugin

func ServePlugin(impl ToolPluginInterface)

ServePlugin 启动插件服务器 这个函数应该在插件的main函数中调用 它会自动注册所有需要的 gob 类型,插件开发者不需要手动注册

Types

type CallToolArgs

type CallToolArgs struct {
	ToolName string         `json:"tool_name"` // 工具名称
	Params   map[string]any `json:"params"`    // 调用参数
}

CallToolArgs 工具调用参数结构体

type CallToolResult

type CallToolResult struct {
	Result
	// Content 工具调用返回的内容数组,可以包含文本、文件或结构体内容
	Content []Content `json:"content"`
	// IsError 表示工具调用是否以错误结束
	// 如果未设置,则假定为 false(调用成功)
	IsError bool `json:"isError,omitempty"`
}

CallToolResult 表示服务器对工具调用的响应

任何来自工具的错误都应该在结果对象内报告,将 `isError` 设置为 true, 而不是作为 MCP 协议级错误响应。否则,LLM 将无法看到发生了错误并自我纠正。

但是,在查找工具时的任何错误、表示服务器不支持工具调用的错误, 或任何其他异常情况,都应该作为 MCP 错误响应报告。

func NewCallToolResult

func NewCallToolResult() *CallToolResult

NewCallToolResult 创建一个新的工具调用结果

func NewErrorResult

func NewErrorResult(errorMessage string) *CallToolResult

NewErrorResult 创建一个表示错误的工具调用结果 errorMessage: 错误信息

func (*CallToolResult) AddAudioContent

func (ctr *CallToolResult) AddAudioContent(data, mimeType string, name ...string) *CallToolResult

AddAudioContent 向结果中添加音频内容(便捷方法)

func (*CallToolResult) AddDocumentContent

func (ctr *CallToolResult) AddDocumentContent(data, mimeType string, name ...string) *CallToolResult

AddDocumentContent 向结果中添加文档内容(便捷方法)

func (*CallToolResult) AddFileContent

func (ctr *CallToolResult) AddFileContent(fileType FileType, data, mimeType string, name ...string) *CallToolResult

AddFileContent 向结果中添加文件内容

func (*CallToolResult) AddImageContent

func (ctr *CallToolResult) AddImageContent(data, mimeType string, name ...string) *CallToolResult

AddImageContent 向结果中添加图片内容(便捷方法)

func (*CallToolResult) AddStructContent

func (ctr *CallToolResult) AddStructContent(data any, name ...string) *CallToolResult

AddStructContent 向结果中添加结构体内容 data 必须是结构化数据类型:自定义结构体、map、slice、array 或指向结构体的指针 如果传入不支持的类型,方法会panic并提供错误信息

func (*CallToolResult) AddTextContent

func (ctr *CallToolResult) AddTextContent(text string, name ...string) *CallToolResult

AddTextContent 向结果中添加文本内容

func (*CallToolResult) AddVideoContent

func (ctr *CallToolResult) AddVideoContent(data, mimeType string, name ...string) *CallToolResult

AddVideoContent 向结果中添加视频内容(便捷方法)

func (*CallToolResult) SetError

func (ctr *CallToolResult) SetError(isError bool) *CallToolResult

SetError 设置工具调用为错误状态

func (*CallToolResult) SetMeta

func (ctr *CallToolResult) SetMeta(key string, value any) *CallToolResult

SetMeta 设置元数据

type Content

type Content interface {
	// GetType 返回内容的类型
	GetType() ContentType
}

Content 定义了工具调用结果中内容的接口 所有内容类型都应该实现此接口

type ContentType

type ContentType string

ContentType 定义内容类型的枚举

const (
	// ContentTypeText 文本内容类型
	ContentTypeText ContentType = "text"
	// ContentTypeFile 文件内容类型(包括图片、音频、文档等所有文件)
	ContentTypeFile ContentType = "file"
	// ContentTypeStruct 结构体内容类型
	ContentTypeStruct ContentType = "struct"
)

type FileContent

type FileContent struct {
	Type     ContentType `json:"type"`           // 内容类型,固定为 "file"
	FileType FileType    `json:"fileType"`       // 文件类型
	Data     string      `json:"data"`           // 文件数据(Base64编码)
	MimeType string      `json:"mimeType"`       // MIME类型
	Name     string      `json:"name,omitempty"` // 文件名称(可选)
	Size     int64       `json:"size,omitempty"` // 文件大小(字节)(可选)

	// 图片特定属性
	Width  int `json:"width,omitempty"`  // 图片宽度(仅图片文件)
	Height int `json:"height,omitempty"` // 图片高度(仅图片文件)

	// 音频/视频特定属性
	Duration float64 `json:"duration,omitempty"` // 音频/视频时长(秒)(仅音频/视频文件)
	Bitrate  int     `json:"bitrate,omitempty"`  // 比特率(仅音频/视频文件)

	// 文档特定属性
	PageCount int    `json:"pageCount,omitempty"` // 页数(仅文档文件)
	Author    string `json:"author,omitempty"`    // 作者(仅文档文件)

	// 通用文件属性
	Encoding string         `json:"encoding,omitempty"` // 文件编码
	Checksum string         `json:"checksum,omitempty"` // 文件校验和
	URL      string         `json:"url,omitempty"`      // 文件URL(可选)
	Metadata map[string]any `json:"metadata,omitempty"` // 额外元数据
}

FileContent 表示文件内容(统一的文件类型,包括图片、音频、文档等)

func NewAudioContent

func NewAudioContent(data, mimeType string, name ...string) FileContent

NewAudioContent 创建新的音频内容(便捷方法)

func NewDocumentContent

func NewDocumentContent(data, mimeType string, name ...string) FileContent

NewDocumentContent 创建新的文档内容(便捷方法)

func NewFileContent

func NewFileContent(fileType FileType, data, mimeType string, name ...string) FileContent

NewFileContent 创建新的文件内容

func NewImageContent

func NewImageContent(data, mimeType string, name ...string) FileContent

NewImageContent 创建新的图片内容(便捷方法)

func NewVideoContent

func NewVideoContent(data, mimeType string, name ...string) FileContent

NewVideoContent 创建新的视频内容(便捷方法)

func (FileContent) GetType

func (fc FileContent) GetType() ContentType

GetType 返回文件内容的类型

func (FileContent) SetDocumentProperties

func (fc FileContent) SetDocumentProperties(pageCount int, author string) FileContent

SetDocumentProperties 设置文档属性

func (FileContent) SetFileMetadata

func (fc FileContent) SetFileMetadata(metadata map[string]any) FileContent

SetFileMetadata 设置文件元数据

func (FileContent) SetFileProperties

func (fc FileContent) SetFileProperties(size int64, encoding, checksum string) FileContent

SetFileProperties 设置通用文件属性

func (FileContent) SetFileURL

func (fc FileContent) SetFileURL(url string) FileContent

SetFileURL 设置文件URL

func (FileContent) SetImageProperties

func (fc FileContent) SetImageProperties(width, height int) FileContent

SetImageProperties 设置图片属性

func (FileContent) SetMediaProperties

func (fc FileContent) SetMediaProperties(duration float64, bitrate int) FileContent

SetMediaProperties 设置媒体属性(音频/视频)

type FileType

type FileType string

FileType 定义文件类型的枚举

const (
	// FileTypeImage 图片文件
	FileTypeImage FileType = "image"
	// FileTypeAudio 音频文件
	FileTypeAudio FileType = "audio"
	// FileTypeVideo 视频文件
	FileTypeVideo FileType = "video"
	// FileTypeDocument 文档文件
	FileTypeDocument FileType = "document"
	// FileTypeArchive 压缩文件
	FileTypeArchive FileType = "archive"
	// FileTypeCode 代码文件
	FileTypeCode FileType = "code"
	// FileTypeData 数据文件
	FileTypeData FileType = "data"
	// FileTypeOther 其他文件
	FileTypeOther FileType = "other"
)

type LoadedPlugin

type LoadedPlugin struct {
	Name     string              // 插件名称
	Path     string              // 插件文件路径
	Client   *plugin.Client      // 插件客户端
	Instance ToolPluginInterface // 插件实例
	Info     PluginInfo          // 插件信息
	Tools    []Tool              // 插件提供的工具
}

LoadedPlugin 已加载的插件信息

type PluginInfo

type PluginInfo struct {
	Name        string `json:"name"`        // 插件名称
	Version     string `json:"version"`     // 插件版本
	Description string `json:"description"` // 插件描述
	Author      string `json:"author"`      // 插件作者
}

PluginInfo 插件基本信息结构体

type PluginManager

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

PluginManager 插件管理器 负责管理所有已加载的插件

func NewPluginManager

func NewPluginManager() *PluginManager

NewPluginManager 创建新的插件管理器

func (*PluginManager) CallTool

func (pm *PluginManager) CallTool(toolName string, params map[string]any) (*CallToolResult, error)

CallTool 调用指定的工具

func (*PluginManager) CallToolWithContext

func (pm *PluginManager) CallToolWithContext(ctx context.Context, toolName string, params map[string]any) (*CallToolResult, error)

CallToolWithContext 带上下文调用指定的工具

func (*PluginManager) CallToolWithStruct

func (pm *PluginManager) CallToolWithStruct(toolName string, params any) (*CallToolResult, error)

CallToolWithStruct 使用结构化参数调用指定的工具 这个方法允许使用强类型参数而不是 map[string]any

func (*PluginManager) CallToolWithStructContext

func (pm *PluginManager) CallToolWithStructContext(ctx context.Context, toolName string, params any) (*CallToolResult, error)

CallToolWithStructContext 使用结构化参数和上下文调用指定的工具 这个方法允许使用结构体参数而不是 map[string]any 同时支持上下文取消和超时

func (*PluginManager) GetPlugin

func (pm *PluginManager) GetPlugin(name string) (*LoadedPlugin, bool)

GetPlugin 获取指定名称的插件

func (*PluginManager) GetPluginByTool

func (pm *PluginManager) GetPluginByTool(toolName string) (*LoadedPlugin, bool)

GetPluginByTool 根据工具名称获取对应的插件

func (*PluginManager) ListPlugins

func (pm *PluginManager) ListPlugins() []*LoadedPlugin

ListPlugins 列出所有已加载的插件

func (*PluginManager) ListTools

func (pm *PluginManager) ListTools() []Tool

ListTools 列出所有可用的工具

func (*PluginManager) LoadAllPlugins

func (pm *PluginManager) LoadAllPlugins(pluginDir string) error

LoadAllPlugins 加载所有扫描到的插件 pluginDir: 插件目录路径

func (*PluginManager) LoadPlugin

func (pm *PluginManager) LoadPlugin(pluginPath string) (*LoadedPlugin, error)

LoadPlugin 加载单个插件 pluginPath: 插件文件路径 返回加载的插件信息

func (*PluginManager) ScanPlugins

func (pm *PluginManager) ScanPlugins(pluginDir string) ([]string, error)

ScanPlugins 扫描指定目录下的所有.tool.plugin文件 pluginDir: 要扫描的插件目录路径 返回找到的插件文件路径列表

func (*PluginManager) Shutdown

func (pm *PluginManager) Shutdown()

Shutdown 关闭所有插件

type PropertyOption

type PropertyOption func(map[string]any)

PropertyOption 是配置Tool输入模式中属性的函数选项类型 它允许使用函数选项模式灵活配置JSON Schema属性

func AdditionalProperties

func AdditionalProperties(schema any) PropertyOption

AdditionalProperties 指定对象中是否允许额外属性 或为额外属性定义模式

func Default

func Default(value any) PropertyOption

Default 设置属性的默认值

func Description

func Description(desc string) PropertyOption

Description 设置属性描述的选项函数

func Enum

func Enum(values ...any) PropertyOption

Enum 设置属性的枚举值

func ExclusiveMaximum

func ExclusiveMaximum(max float64) PropertyOption

ExclusiveMaximum 设置数字的排他最大值

func ExclusiveMinimum

func ExclusiveMinimum(min float64) PropertyOption

ExclusiveMinimum 设置数字的排他最小值

func Format

func Format(format string) PropertyOption

Format 设置字符串的格式(如 email、uri 等)

func Items

func Items(schema any) PropertyOption

Items 定义数组项目的模式 接受任何模式定义以获得最大灵活性

func MaxItems

func MaxItems(max int) PropertyOption

MaxItems 设置数组的最大项目数量

func MaxLength

func MaxLength(max int) PropertyOption

MaxLength 设置字符串的最大长度

func MaxProperties

func MaxProperties(max int) PropertyOption

MaxProperties 设置对象的最大属性数量

func Maximum

func Maximum(max float64) PropertyOption

Maximum 设置数字的最大值

func MinItems

func MinItems(min int) PropertyOption

MinItems 设置数组的最小项目数量

func MinLength

func MinLength(min int) PropertyOption

MinLength 设置字符串的最小长度

func MinProperties

func MinProperties(min int) PropertyOption

MinProperties 设置对象的最小属性数量

func Minimum

func Minimum(min float64) PropertyOption

Minimum 设置数字的最小值

func MultipleOf

func MultipleOf(value float64) PropertyOption

MultipleOf 设置数字必须是指定值的倍数

func Pattern

func Pattern(pattern string) PropertyOption

Pattern 设置字符串的正则表达式模式

func Properties

func Properties(props map[string]any) PropertyOption

Properties 定义对象模式的属性

func PropertyNames

func PropertyNames(schema map[string]any) PropertyOption

PropertyNames 为对象中的属性名称定义模式

func Required

func Required() PropertyOption

Required 标记属性为必需的

func UniqueItems

func UniqueItems(unique bool) PropertyOption

UniqueItems 指定数组项目是否必须唯一

func WithBooleanItems

func WithBooleanItems(opts ...PropertyOption) PropertyOption

WithBooleanItems 配置数组的项目为布尔类型 支持的选项:Description(), Default()

func WithIntegerItems

func WithIntegerItems(opts ...PropertyOption) PropertyOption

WithIntegerItems 配置数组的项目为整数类型

func WithNumberItems

func WithNumberItems(opts ...PropertyOption) PropertyOption

WithNumberItems 配置数组的项目为数字类型 支持的选项:Description(), Default(), Minimum(), Maximum(), MultipleOf()

func WithObjectItems

func WithObjectItems(opts ...PropertyOption) PropertyOption

WithObjectItems 配置数组的项目为对象类型

func WithStringEnumItems

func WithStringEnumItems(values []string) PropertyOption

WithStringEnumItems 配置数组的项目为指定枚举的字符串类型

func WithStringItems

func WithStringItems(opts ...PropertyOption) PropertyOption

WithStringItems 配置数组的项目为字符串类型 支持的选项:Description(), Default(), Enum(), MaxLength(), MinLength(), Pattern() 注意:Required() 等选项对项目模式无效,将被忽略

type Result

type Result struct {
	// Meta 元数据属性由协议保留,允许客户端和服务器向其响应附加额外的元数据
	Meta map[string]any `json:"_meta,omitempty"`
}

Result 表示工具调用的基础结果结构 所有工具调用结果都应该包含这个基础结构

type StructCallToolArgs

type StructCallToolArgs struct {
	ToolName string `json:"tool_name"` // 工具名称
	Params   any    `json:"params"`    // 结构化参数(通常是map[string]any)
}

StructCallToolArgs 支持结构化参数的工具调用参数结构体 注意:由于客户端现在会将结构体转换为map,这个结构体主要用于接口完整性 实际使用中参数会是 map[string]any 类型

type StructContent

type StructContent struct {
	Type   ContentType `json:"type"`             // 内容类型,固定为 "struct"
	Data   any         `json:"data"`             // 结构体数据(可以是任意类型)
	Name   string      `json:"name,omitempty"`   // 结构体名称(可选)
	Schema string      `json:"schema,omitempty"` // 结构体模式定义(可选)
	Format string      `json:"format,omitempty"` // 数据格式(如 json、yaml 等)
}

StructContent 表示结构体内容

func NewStructContent

func NewStructContent(data any, name ...string) StructContent

NewStructContent 创建新的结构体内容 data 必须是结构化数据类型:自定义结构体、map、slice、array 或指向结构体的指针 如果传入不支持的类型,函数会panic并提供错误信息

func (StructContent) GetType

func (sc StructContent) GetType() ContentType

GetType 返回结构体内容的类型

func (StructContent) SetStructFormat

func (sc StructContent) SetStructFormat(format string) StructContent

SetStructFormat 设置结构体数据格式

func (StructContent) SetStructSchema

func (sc StructContent) SetStructSchema(schema string) StructContent

SetStructSchema 设置结构体模式定义

type TextContent

type TextContent struct {
	Type ContentType `json:"type"`           // 内容类型,固定为 "text"
	Text string      `json:"text"`           // 文本内容
	Name string      `json:"name,omitempty"` // 内容名称(可选)
}

TextContent 表示文本内容

func NewTextContent

func NewTextContent(text string, name ...string) TextContent

NewTextContent 创建新的文本内容

func (TextContent) GetType

func (tc TextContent) GetType() ContentType

GetType 返回文本内容的类型

type Tool

type Tool struct {
	Name           string          `json:"name"`         // 工具名称
	Description    string          `json:"description"`  // 工具描述
	InputSchema    ToolInputSchema `json:"input_schema"` // 工具输入参数 与 RawInputSchema 二选一
	RawInputSchema json.RawMessage `json:"-"`            // 工具输入参数的原始JSON Schema 与 InputSchema 二选一
}

Tool 表示一个工具的完整定义 包含工具的名称、描述和输入参数模式

func NewTool

func NewTool(name, description string, options ...ToolOption) *Tool

NewTool 创建一个新的工具实例

type ToolInputSchema

type ToolInputSchema struct {
	Type       string         `json:"type"`                 // 参数类型
	Properties map[string]any `json:"properties,omitempty"` // 参数属性
	Required   []string       `json:"required,omitempty"`   // 参数必填
}

ToolInputSchema 表示工具输入参数的JSON Schema结构

func (*ToolInputSchema) MarshalJSON

func (tis *ToolInputSchema) MarshalJSON() ([]byte, error)

MarshalJSON 自定义ToolInputSchema的JSON序列化方法

type ToolOption

type ToolOption func(*Tool)

ToolOption 是配置Tool的函数选项类型

func WithArray

func WithArray(name string, opts ...PropertyOption) ToolOption

WithArray 添加数组类型属性的选项函数

func WithBoolean

func WithBoolean(name string, opts ...PropertyOption) ToolOption

WithBoolean 添加布尔类型属性的选项函数

func WithDescription

func WithDescription(description string) ToolOption

WithDescription 设置工具描述的选项函数

func WithInteger

func WithInteger(name string, opts ...PropertyOption) ToolOption

WithInteger 添加整数类型属性的选项函数

func WithName

func WithName(name string) ToolOption

WithName 设置工具名称的选项函数

func WithNumber

func WithNumber(name string, opts ...PropertyOption) ToolOption

WithNumber 添加数字类型属性的选项函数

func WithObject

func WithObject(name string, opts ...PropertyOption) ToolOption

WithObject 添加对象类型属性的选项函数

func WithString

func WithString(name string, opts ...PropertyOption) ToolOption

WithString 添加字符串类型属性的选项函数

type ToolPlugin

type ToolPlugin struct {
	Impl ToolPluginInterface // 插件的实际实现
}

ToolPlugin 实现了 hashicorp/go-plugin 的 Plugin 接口 这是插件系统的核心,负责客户端和服务器端的创建

func (ToolPlugin) Client

func (ToolPlugin) Client(b *plugin.MuxBroker, c *rpc.Client) (any, error)

Client 返回插件的RPC客户端实现 这个方法在主程序中被调用,用于与插件通信

func (*ToolPlugin) Server

func (p *ToolPlugin) Server(*plugin.MuxBroker) (any, error)

Server 返回插件的RPC服务器实现 这个方法在插件进程中被调用

type ToolPluginGenericInterface

type ToolPluginGenericInterface interface {
	// 包含基础接口的所有方法
	ToolPluginInterface

	// CallToolWithStruct 使用结构化参数调用指定的工具
	// params 是一个结构体,必须是可序列化的
	CallToolWithStruct(toolName string, params any) (*CallToolResult, error)
}

ToolPluginGenericInterface 定义了支持结构化参数的工具插件接口 这是 ToolPluginInterface 的扩展,允许使用结构化参数

type ToolPluginInterface

type ToolPluginInterface interface {
	// GetTools 获取插件提供的所有工具定义
	GetTools() ([]Tool, error)

	// CallTool 调用指定的工具并返回结果
	// 这是原始的方法,接受 map[string]any 类型的参数
	CallTool(toolName string, params map[string]any) (*CallToolResult, error)

	// GetPluginInfo 获取插件的基本信息
	GetPluginInfo() (PluginInfo, error)
}

ToolPluginInterface 定义了工具插件需要实现的核心接口 这是插件和主程序之间的通信契约

type ToolPluginRPC

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

ToolPluginRPC RPC客户端实现 将接口调用转换为跨进程的RPC调用

func (*ToolPluginRPC) CallTool

func (t *ToolPluginRPC) CallTool(toolName string, params map[string]any) (*CallToolResult, error)

CallTool 实现 ToolPluginInterface 接口的 CallTool 方法

func (*ToolPluginRPC) CallToolWithStruct

func (t *ToolPluginRPC) CallToolWithStruct(toolName string, params any) (*CallToolResult, error)

CallToolWithStruct 实现 ToolPluginGenericInterface 接口的 CallToolWithStruct 方法 使用结构化参数调用工具

func (*ToolPluginRPC) GetPluginInfo

func (t *ToolPluginRPC) GetPluginInfo() (PluginInfo, error)

GetPluginInfo 实现 ToolPluginInterface 接口的 GetPluginInfo 方法

func (*ToolPluginRPC) GetTools

func (t *ToolPluginRPC) GetTools() ([]Tool, error)

GetTools 实现 ToolPluginInterface 接口的 GetTools 方法

type ToolPluginRPCServer

type ToolPluginRPCServer struct {
	Impl ToolPluginInterface // 实际的插件实现
}

ToolPluginRPCServer RPC服务器端实现 接收RPC调用并转发给实际的插件实现

func (*ToolPluginRPCServer) CallTool

func (s *ToolPluginRPCServer) CallTool(args CallToolArgs, resp *CallToolResult) error

CallTool 处理来自客户端的 CallTool RPC 调用

func (*ToolPluginRPCServer) CallToolWithStruct

func (s *ToolPluginRPCServer) CallToolWithStruct(args StructCallToolArgs, resp *CallToolResult) error

CallToolWithStruct 处理来自客户端的 CallToolWithStruct RPC 调用 这个方法处理结构化参数的工具调用 注意:由于客户端已经将结构体转换为map,这个方法现在实际上不会被调用 保留此方法是为了接口完整性

func (*ToolPluginRPCServer) GetPluginInfo

func (s *ToolPluginRPCServer) GetPluginInfo(args any, resp *PluginInfo) error

GetPluginInfo 处理来自客户端的 GetPluginInfo RPC 调用

func (*ToolPluginRPCServer) GetTools

func (s *ToolPluginRPCServer) GetTools(args any, resp *[]Tool) error

GetTools 处理来自客户端的 GetTools RPC 调用

Directories

Path Synopsis
plugin/timetool
plugin/example/plugin/timetool/tool.go
plugin/example/plugin/timetool/tool.go

Jump to

Keyboard shortcuts

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