registry.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package registry
  15. import (
  16. "fmt"
  17. "sync"
  18. "github.com/mark3labs/mcp-go/mcp"
  19. "github.com/mark3labs/mcp-go/server"
  20. "yunion.io/x/log"
  21. )
  22. type Registry struct {
  23. mu sync.RWMutex
  24. tools map[string]*ToolRegistration
  25. mcpServer *server.MCPServer
  26. initialized bool
  27. }
  28. type ToolRegistration struct {
  29. Tool mcp.Tool
  30. Handler server.ToolHandlerFunc
  31. }
  32. func NewRegistry() *Registry {
  33. return &Registry{
  34. tools: make(map[string]*ToolRegistration),
  35. }
  36. }
  37. // Initialize 使用MCP服务器初始化注册中心
  38. func (r *Registry) Initialize(mcpServer *server.MCPServer) error {
  39. r.mu.Lock()
  40. defer r.mu.Unlock()
  41. if r.initialized {
  42. return fmt.Errorf("Fail to init register ")
  43. }
  44. r.mcpServer = mcpServer
  45. // 将所有已注册的工具添加到MCP服务器
  46. for _, registration := range r.tools {
  47. r.mcpServer.AddTool(registration.Tool, registration.Handler)
  48. }
  49. r.initialized = true
  50. return nil
  51. }
  52. // RegisterTool 注册单个工具
  53. func (r *Registry) RegisterTool(toolName string, tool mcp.Tool, handler server.ToolHandlerFunc) error {
  54. r.mu.Lock()
  55. defer r.mu.Unlock()
  56. if _, exists := r.tools[toolName]; exists {
  57. return fmt.Errorf("Tool already register: '%s' ", toolName)
  58. }
  59. registration := &ToolRegistration{
  60. Tool: tool,
  61. Handler: handler,
  62. }
  63. r.tools[toolName] = registration
  64. log.Infof("Tool register successfully: %s", toolName)
  65. // 如果MCP服务器已设置,立即注册到服务器
  66. if r.mcpServer != nil {
  67. r.mcpServer.AddTool(tool, handler)
  68. }
  69. return nil
  70. }