publicmcp-tool.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. package controller
  2. import (
  3. "context"
  4. "encoding"
  5. "sync"
  6. "time"
  7. "github.com/bytedance/sonic"
  8. "github.com/labring/aiproxy/core/common"
  9. "github.com/labring/aiproxy/core/common/conv"
  10. "github.com/labring/aiproxy/core/model"
  11. mcpservers "github.com/labring/aiproxy/mcp-servers"
  12. "github.com/mark3labs/mcp-go/client/transport"
  13. "github.com/mark3labs/mcp-go/mcp"
  14. "github.com/redis/go-redis/v9"
  15. log "github.com/sirupsen/logrus"
  16. )
  17. const (
  18. ToolCacheKey = "tool:%s:%d" // mcp_id:updated_at
  19. )
  20. type redisToolSlice []mcp.Tool
  21. var (
  22. _ redis.Scanner = (*redisToolSlice)(nil)
  23. _ encoding.BinaryMarshaler = (*redisToolSlice)(nil)
  24. )
  25. func (r *redisToolSlice) ScanRedis(value string) error {
  26. return sonic.Unmarshal(conv.StringToBytes(value), r)
  27. }
  28. func (r redisToolSlice) MarshalBinary() ([]byte, error) {
  29. return sonic.Marshal(r)
  30. }
  31. type toolCacheMemItem struct {
  32. tools []mcp.Tool
  33. lastUsedAt time.Time
  34. expiresAt time.Time
  35. }
  36. type toolMemoryCache struct {
  37. mu sync.Mutex
  38. items map[string]toolCacheMemItem
  39. cleanStartOnce sync.Once
  40. }
  41. var toolMemCache = &toolMemoryCache{
  42. items: make(map[string]toolCacheMemItem),
  43. }
  44. func getToolCacheKey(mcpID string, updatedAt int64) string {
  45. return common.RedisKeyf(ToolCacheKey, mcpID, updatedAt)
  46. }
  47. func (c *toolMemoryCache) set(key string, tools []mcp.Tool) {
  48. c.startCleanupOnStart()
  49. c.mu.Lock()
  50. defer c.mu.Unlock()
  51. now := time.Now()
  52. c.items[key] = toolCacheMemItem{
  53. tools: tools,
  54. lastUsedAt: now,
  55. expiresAt: now.Add(time.Hour),
  56. }
  57. }
  58. func (c *toolMemoryCache) get(key string) ([]mcp.Tool, bool) {
  59. c.mu.Lock()
  60. defer c.mu.Unlock()
  61. item, exists := c.items[key]
  62. if !exists {
  63. return nil, false
  64. }
  65. now := time.Now()
  66. if now.After(item.lastUsedAt.Add(time.Minute*10)) ||
  67. now.After(item.expiresAt) {
  68. delete(c.items, key)
  69. return nil, false
  70. }
  71. item.lastUsedAt = now
  72. return item.tools, true
  73. }
  74. func (c *toolMemoryCache) cleanup() {
  75. c.mu.Lock()
  76. defer c.mu.Unlock()
  77. now := time.Now()
  78. for key, item := range c.items {
  79. if now.After(item.lastUsedAt.Add(time.Minute*10)) ||
  80. now.After(item.expiresAt) {
  81. delete(c.items, key)
  82. }
  83. }
  84. }
  85. func (c *toolMemoryCache) startCleanupOnStart() {
  86. c.cleanStartOnce.Do(func() {
  87. go func() {
  88. ticker := time.NewTicker(time.Minute * 10)
  89. defer ticker.Stop()
  90. for range ticker.C {
  91. c.cleanup()
  92. }
  93. }()
  94. })
  95. }
  96. func CacheSetTools(mcpID string, updatedAt int64, tools []mcp.Tool) error {
  97. key := getToolCacheKey(mcpID, updatedAt)
  98. if common.RedisEnabled {
  99. redisKey := common.RedisKeyf(ToolCacheKey, mcpID, updatedAt)
  100. pipe := common.RDB.Pipeline()
  101. pipe.HSet(context.Background(), redisKey, tools)
  102. pipe.Expire(context.Background(), redisKey, time.Hour)
  103. _, err := pipe.Exec(context.Background())
  104. return err
  105. }
  106. toolMemCache.set(key, tools)
  107. return nil
  108. }
  109. func CacheGetTools(mcpID string, updatedAt int64) ([]mcp.Tool, bool) {
  110. key := getToolCacheKey(mcpID, updatedAt)
  111. if common.RedisEnabled {
  112. tools := redisToolSlice{}
  113. err := common.RDB.HGetAll(context.Background(), key).Scan(&tools)
  114. if err != nil {
  115. log.Errorf("failed to get tools cache from redis (%s): %v", key, err)
  116. } else {
  117. return tools, true
  118. }
  119. }
  120. item, exists := toolMemCache.get(key)
  121. if exists {
  122. return item, true
  123. }
  124. return nil, false
  125. }
  126. func checkParamsIsFull(params model.Params, reusing map[string]model.ReusingParam) bool {
  127. for key, r := range reusing {
  128. if !r.Required {
  129. continue
  130. }
  131. if params == nil {
  132. return false
  133. }
  134. if v, ok := params[key]; !ok || v == "" {
  135. return false
  136. }
  137. }
  138. return true
  139. }
  140. func getPublicMCPTools(
  141. ctx context.Context,
  142. publicMcp model.PublicMCP,
  143. testConfig model.TestConfig,
  144. params map[string]string,
  145. reusing map[string]model.ReusingParam,
  146. ) (tools []mcp.Tool, err error) {
  147. tools, exists := CacheGetTools(publicMcp.ID, publicMcp.UpdateAt.Unix())
  148. if exists {
  149. return tools, nil
  150. }
  151. defer func() {
  152. if err != nil {
  153. return
  154. }
  155. if err := CacheSetTools(publicMcp.ID, publicMcp.UpdateAt.Unix(), tools); err != nil {
  156. log.Errorf("failed to set tools cache in redis: %v", err)
  157. }
  158. }()
  159. ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
  160. defer cancel()
  161. switch publicMcp.Type {
  162. case model.PublicMCPTypeEmbed:
  163. return getEmbedMCPTools(ctx, publicMcp, testConfig, params, reusing)
  164. case model.PublicMCPTypeOpenAPI:
  165. return getOpenAPIMCPTools(ctx, publicMcp)
  166. case model.PublicMCPTypeProxySSE:
  167. return getProxySSEMCPTools(ctx, publicMcp, testConfig, params, reusing)
  168. case model.PublicMCPTypeProxyStreamable:
  169. return getProxyStreamableMCPTools(ctx, publicMcp, testConfig, params, reusing)
  170. default:
  171. return nil, nil
  172. }
  173. }
  174. func getEmbedMCPTools(
  175. ctx context.Context,
  176. publicMcp model.PublicMCP,
  177. testConfig model.TestConfig,
  178. params map[string]string,
  179. reusing map[string]model.ReusingParam,
  180. ) ([]mcp.Tool, error) {
  181. tools, err := mcpservers.ListTools(ctx, publicMcp.ID)
  182. if err == nil {
  183. return tools, nil
  184. }
  185. if publicMcp.EmbedConfig == nil {
  186. return nil, nil
  187. }
  188. var effectiveParams map[string]string
  189. switch {
  190. case testConfig.Enabled && checkParamsIsFull(testConfig.Params, reusing):
  191. effectiveParams = testConfig.Params
  192. case checkParamsIsFull(params, reusing):
  193. effectiveParams = params
  194. default:
  195. return nil, nil
  196. }
  197. server, err := mcpservers.GetMCPServer(
  198. publicMcp.ID,
  199. publicMcp.EmbedConfig.Init,
  200. effectiveParams,
  201. )
  202. if err != nil {
  203. return nil, err
  204. }
  205. return mcpservers.ListServerTools(ctx, server)
  206. }
  207. func getOpenAPIMCPTools(ctx context.Context, publicMcp model.PublicMCP) ([]mcp.Tool, error) {
  208. if publicMcp.OpenAPIConfig == nil {
  209. return nil, nil
  210. }
  211. server, err := newOpenAPIMCPServer(publicMcp.OpenAPIConfig)
  212. if err != nil {
  213. return nil, err
  214. }
  215. return mcpservers.ListServerTools(ctx, server)
  216. }
  217. func getProxySSEMCPTools(
  218. ctx context.Context,
  219. publicMcp model.PublicMCP,
  220. testConfig model.TestConfig,
  221. params map[string]string,
  222. reusing map[string]model.ReusingParam,
  223. ) ([]mcp.Tool, error) {
  224. if publicMcp.ProxyConfig == nil {
  225. return nil, nil
  226. }
  227. var effectiveParams map[string]string
  228. switch {
  229. case testConfig.Enabled && checkParamsIsFull(testConfig.Params, reusing):
  230. effectiveParams = testConfig.Params
  231. case checkParamsIsFull(params, reusing):
  232. effectiveParams = params
  233. default:
  234. return nil, nil
  235. }
  236. url, headers, err := prepareProxyConfig(
  237. publicMcp.ToPublicMCPCache(),
  238. staticParams(effectiveParams),
  239. )
  240. if err != nil {
  241. return nil, err
  242. }
  243. client, err := transport.NewSSE(url, transport.WithHeaders(headers))
  244. if err != nil {
  245. return nil, err
  246. }
  247. defer client.Close()
  248. if err := client.Start(ctx); err != nil {
  249. return nil, err
  250. }
  251. return mcpservers.ListServerTools(ctx, mcpservers.WrapMCPClient2Server(client))
  252. }
  253. func getProxyStreamableMCPTools(
  254. ctx context.Context,
  255. publicMcp model.PublicMCP,
  256. testConfig model.TestConfig,
  257. params map[string]string,
  258. reusing map[string]model.ReusingParam,
  259. ) ([]mcp.Tool, error) {
  260. if publicMcp.ProxyConfig == nil {
  261. return nil, nil
  262. }
  263. var effectiveParams map[string]string
  264. switch {
  265. case testConfig.Enabled && checkParamsIsFull(testConfig.Params, reusing):
  266. effectiveParams = testConfig.Params
  267. case checkParamsIsFull(params, reusing):
  268. effectiveParams = params
  269. default:
  270. return nil, nil
  271. }
  272. url, headers, err := prepareProxyConfig(
  273. publicMcp.ToPublicMCPCache(),
  274. staticParams(effectiveParams),
  275. )
  276. if err != nil {
  277. return nil, err
  278. }
  279. client, err := transport.NewStreamableHTTP(
  280. url,
  281. transport.WithHTTPHeaders(headers),
  282. )
  283. if err != nil {
  284. return nil, err
  285. }
  286. defer client.Close()
  287. if err := client.Start(ctx); err != nil {
  288. return nil, err
  289. }
  290. return mcpservers.ListServerTools(ctx, mcpservers.WrapMCPClient2Server(client))
  291. }