tool.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Package kit 是 fwh-agent-mcp 的工具框架:工具定义、参数辅助、统一结果与中间件。
  2. //
  3. // 设计见 docs/ai-assistant-agentserver/agent-mcp.md 第 3 节。工具不感知调用者:
  4. // 没有 userId / sessionId 参数,也不记录调用人。
  5. package kit
  6. import (
  7. "context"
  8. "strings"
  9. "github.com/mark3labs/mcp-go/mcp"
  10. "github.com/mark3labs/mcp-go/server"
  11. )
  12. // Meta 工具的静态信息,供注册表与约束测试使用。
  13. type Meta struct {
  14. Name string
  15. Title string
  16. Description string
  17. ReadOnly bool
  18. }
  19. // IsExport 导出类工具(*_export)使用更长的超时并以 CSV 资源返回。
  20. func (m Meta) IsExport() bool {
  21. return strings.HasSuffix(m.Name, "_export")
  22. }
  23. // Registrar 可注册到 MCPServer 的工具。
  24. type Registrar interface {
  25. Meta() Meta
  26. Tool() mcp.Tool
  27. Register(s *server.MCPServer)
  28. }
  29. // Def 一个类型化工具的定义。T 为参数结构体,schema 由 mcp.WithInputSchema[T] 生成:
  30. // `jsonschema:"..."` 标签即字段描述,没有 omitempty 的字段为必填;枚举与取值范围写进描述并在 Handler 中校验。
  31. type Def[T any] struct {
  32. Name string // <领域>_<动作>,小写下划线,≤ 40 字符
  33. Title string // 中文短标题(审批卡片与后台显示)
  34. Description string // 用途、适用场景、返回字段与单位
  35. ReadOnly bool
  36. Handler func(ctx context.Context, args T) (*mcp.CallToolResult, error)
  37. }
  38. func (d Def[T]) Meta() Meta {
  39. return Meta{Name: d.Name, Title: d.Title, Description: d.Description, ReadOnly: d.ReadOnly}
  40. }
  41. func (d Def[T]) Tool() mcp.Tool {
  42. return mcp.NewTool(d.Name,
  43. mcp.WithDescription(d.Description),
  44. mcp.WithInputSchema[T](),
  45. mcp.WithTitleAnnotation(d.Title),
  46. mcp.WithReadOnlyHintAnnotation(d.ReadOnly),
  47. mcp.WithDestructiveHintAnnotation(false),
  48. mcp.WithIdempotentHintAnnotation(d.ReadOnly),
  49. mcp.WithOpenWorldHintAnnotation(false),
  50. )
  51. }
  52. func (d Def[T]) Register(s *server.MCPServer) {
  53. s.AddTool(d.Tool(), mcp.NewTypedToolHandler(func(ctx context.Context, _ mcp.CallToolRequest, args T) (*mcp.CallToolResult, error) {
  54. return d.Handler(ctx, args)
  55. }))
  56. }
  57. // NoArgs 无参数工具的参数类型。
  58. type NoArgs struct{}