publicmcp.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. package model
  2. import (
  3. "errors"
  4. "net/url"
  5. "regexp"
  6. "time"
  7. "github.com/bytedance/sonic"
  8. "github.com/labring/aiproxy/core/common"
  9. log "github.com/sirupsen/logrus"
  10. "gorm.io/gorm"
  11. )
  12. type PublicMCPStatus int
  13. const (
  14. PublicMCPStatusEnabled PublicMCPStatus = iota + 1
  15. PublicMCPStatusDisabled
  16. )
  17. const (
  18. ErrPublicMCPNotFound = "public mcp"
  19. ErrMCPReusingParamNotFound = "mcp reusing param"
  20. )
  21. type PublicMCPType string
  22. const (
  23. PublicMCPTypeProxySSE PublicMCPType = "mcp_proxy_sse"
  24. PublicMCPTypeProxyStreamable PublicMCPType = "mcp_proxy_streamable"
  25. PublicMCPTypeDocs PublicMCPType = "mcp_docs" // read only
  26. PublicMCPTypeOpenAPI PublicMCPType = "mcp_openapi"
  27. PublicMCPTypeEmbed PublicMCPType = "mcp_embed"
  28. )
  29. type ParamType string
  30. const (
  31. ParamTypeHeader ParamType = "header"
  32. ParamTypeQuery ParamType = "query"
  33. )
  34. type ReusingParam struct {
  35. Name string `json:"name"`
  36. Description string `json:"description"`
  37. Type ParamType `json:"type"`
  38. Required bool `json:"required"`
  39. }
  40. type MCPPrice struct {
  41. DefaultToolsCallPrice float64 `json:"default_tools_call_price"`
  42. ToolsCallPrices map[string]float64 `json:"tools_call_prices" gorm:"serializer:fastjson;type:text"`
  43. }
  44. type PublicMCPProxyConfig struct {
  45. URL string `json:"url"`
  46. Querys map[string]string `json:"querys"`
  47. Headers map[string]string `json:"headers"`
  48. ReusingParams map[string]ReusingParam `json:"reusing_params"`
  49. }
  50. type PublicMCPReusingParam struct {
  51. MCPID string `gorm:"primaryKey" json:"mcp_id"`
  52. GroupID string `gorm:"primaryKey" json:"group_id"`
  53. CreatedAt time.Time `gorm:"index" json:"created_at"`
  54. UpdateAt time.Time `gorm:"index" json:"update_at"`
  55. Group *Group `gorm:"foreignKey:GroupID" json:"-"`
  56. ReusingParams map[string]string `gorm:"serializer:fastjson;type:text" json:"reusing_params"`
  57. }
  58. func (p *PublicMCPReusingParam) BeforeCreate(_ *gorm.DB) (err error) {
  59. if p.MCPID == "" {
  60. return errors.New("mcp id is empty")
  61. }
  62. if p.GroupID == "" {
  63. return errors.New("group is empty")
  64. }
  65. return
  66. }
  67. func (p *PublicMCPReusingParam) MarshalJSON() ([]byte, error) {
  68. type Alias PublicMCPReusingParam
  69. a := &struct {
  70. *Alias
  71. CreatedAt int64 `json:"created_at"`
  72. UpdateAt int64 `json:"update_at"`
  73. }{
  74. Alias: (*Alias)(p),
  75. CreatedAt: p.CreatedAt.UnixMilli(),
  76. UpdateAt: p.UpdateAt.UnixMilli(),
  77. }
  78. return sonic.Marshal(a)
  79. }
  80. type MCPOpenAPIConfig struct {
  81. OpenAPISpec string `json:"openapi_spec"`
  82. OpenAPIContent string `json:"openapi_content,omitempty"`
  83. V2 bool `json:"v2"`
  84. ServerAddr string `json:"server_addr,omitempty"`
  85. Authorization string `json:"authorization,omitempty"`
  86. }
  87. type MCPEmbeddingReusingConfig struct {
  88. Name string `json:"name"`
  89. Description string `json:"description"`
  90. Required bool `json:"required"`
  91. }
  92. type MCPEmbeddingConfig struct {
  93. Init map[string]string `json:"init"`
  94. Reusing map[string]MCPEmbeddingReusingConfig `json:"reusing"`
  95. }
  96. var validateMCPIDRegex = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
  97. func validateMCPID(id string) error {
  98. if id == "" {
  99. return errors.New("mcp id is empty")
  100. }
  101. if !validateMCPIDRegex.MatchString(id) {
  102. return errors.New("mcp id is invalid")
  103. }
  104. return nil
  105. }
  106. type PublicMCP struct {
  107. ID string `gorm:"primaryKey" json:"id"`
  108. Status PublicMCPStatus `gorm:"index;default:1" json:"status"`
  109. CreatedAt time.Time `gorm:"index,autoCreateTime" json:"created_at"`
  110. UpdateAt time.Time `gorm:"index,autoUpdateTime" json:"update_at"`
  111. PublicMCPReusingParams []PublicMCPReusingParam `gorm:"foreignKey:MCPID" json:"-"`
  112. Name string ` json:"name"`
  113. Type PublicMCPType `gorm:"index" json:"type"`
  114. RepoURL string ` json:"repo_url"`
  115. ReadmeURL string ` json:"readme_url"`
  116. Readme string `gorm:"type:text" json:"readme"`
  117. Tags []string `gorm:"serializer:fastjson;type:text" json:"tags,omitempty"`
  118. LogoURL string ` json:"logo_url"`
  119. Price MCPPrice `gorm:"embedded" json:"price"`
  120. ProxyConfig *PublicMCPProxyConfig `gorm:"serializer:fastjson;type:text" json:"proxy_config,omitempty"`
  121. OpenAPIConfig *MCPOpenAPIConfig `gorm:"serializer:fastjson;type:text" json:"openapi_config,omitempty"`
  122. EmbedConfig *MCPEmbeddingConfig `gorm:"serializer:fastjson;type:text" json:"embed_config,omitempty"`
  123. }
  124. func (p *PublicMCP) BeforeCreate(_ *gorm.DB) error {
  125. if err := validateMCPID(p.ID); err != nil {
  126. return err
  127. }
  128. if p.Status == 0 {
  129. p.Status = PublicMCPStatusEnabled
  130. }
  131. return nil
  132. }
  133. func (p *PublicMCP) BeforeSave(_ *gorm.DB) error {
  134. if p.OpenAPIConfig != nil {
  135. config := p.OpenAPIConfig
  136. if config.OpenAPISpec != "" {
  137. return validateHTTPURL(config.OpenAPISpec)
  138. }
  139. if config.OpenAPIContent != "" {
  140. return nil
  141. }
  142. return errors.New("openapi spec and content is empty")
  143. }
  144. if p.ProxyConfig != nil {
  145. config := p.ProxyConfig
  146. return validateHTTPURL(config.URL)
  147. }
  148. return nil
  149. }
  150. func validateHTTPURL(str string) error {
  151. if str == "" {
  152. return errors.New("url is empty")
  153. }
  154. u, err := url.Parse(str)
  155. if err != nil {
  156. return err
  157. }
  158. if u.Scheme != "http" && u.Scheme != "https" {
  159. return errors.New("url scheme not support")
  160. }
  161. return nil
  162. }
  163. func (p *PublicMCP) BeforeDelete(tx *gorm.DB) (err error) {
  164. return tx.Model(&PublicMCPReusingParam{}).
  165. Where("mcp_id = ?", p.ID).
  166. Delete(&PublicMCPReusingParam{}).
  167. Error
  168. }
  169. // CreatePublicMCP creates a new MCP
  170. func CreatePublicMCP(mcp *PublicMCP) error {
  171. err := DB.Create(mcp).Error
  172. if err != nil && errors.Is(err, gorm.ErrDuplicatedKey) {
  173. return errors.New("mcp server already exist")
  174. }
  175. return err
  176. }
  177. func SavePublicMCP(mcp *PublicMCP) (err error) {
  178. defer func() {
  179. if err == nil {
  180. if err := CacheDeletePublicMCP(mcp.ID); err != nil {
  181. log.Error("cache delete public mcp error: " + err.Error())
  182. }
  183. }
  184. }()
  185. return DB.Save(mcp).Error
  186. }
  187. // UpdatePublicMCP updates an existing MCP
  188. func UpdatePublicMCP(mcp *PublicMCP) (err error) {
  189. defer func() {
  190. if err == nil {
  191. if err := CacheDeletePublicMCP(mcp.ID); err != nil {
  192. log.Error("cache delete public mcp error: " + err.Error())
  193. }
  194. }
  195. }()
  196. selects := []string{
  197. "repo_url",
  198. "readme",
  199. "readme_url",
  200. "tags",
  201. "author",
  202. "logo_url",
  203. "proxy_config",
  204. "openapi_config",
  205. "embed_config",
  206. }
  207. if mcp.Status != 0 {
  208. selects = append(selects, "status")
  209. }
  210. if mcp.Name != "" {
  211. selects = append(selects, "name")
  212. }
  213. if mcp.Type != "" {
  214. selects = append(selects, "type")
  215. }
  216. if mcp.Price.DefaultToolsCallPrice != 0 ||
  217. len(mcp.Price.ToolsCallPrices) != 0 {
  218. selects = append(selects, "price")
  219. }
  220. result := DB.
  221. Select(selects).
  222. Where("id = ?", mcp.ID).
  223. Updates(mcp)
  224. return HandleUpdateResult(result, ErrPublicMCPNotFound)
  225. }
  226. func UpdatePublicMCPStatus(id string, status PublicMCPStatus) (err error) {
  227. defer func() {
  228. if err == nil {
  229. if err := CacheUpdatePublicMCPStatus(id, status); err != nil {
  230. log.Error("cache update public mcp status error: " + err.Error())
  231. }
  232. }
  233. }()
  234. result := DB.Model(&PublicMCP{}).Where("id = ?", id).Update("status", status)
  235. return HandleUpdateResult(result, ErrPublicMCPNotFound)
  236. }
  237. // DeletePublicMCP deletes an MCP by ID
  238. func DeletePublicMCP(id string) (err error) {
  239. defer func() {
  240. if err == nil {
  241. if err := CacheDeletePublicMCP(id); err != nil {
  242. log.Error("cache delete public mcp error: " + err.Error())
  243. }
  244. }
  245. }()
  246. if id == "" {
  247. return errors.New("MCP id is empty")
  248. }
  249. result := DB.Delete(&PublicMCP{ID: id})
  250. return HandleUpdateResult(result, ErrPublicMCPNotFound)
  251. }
  252. // GetPublicMCPByID retrieves an MCP by ID
  253. func GetPublicMCPByID(id string) (PublicMCP, error) {
  254. var mcp PublicMCP
  255. if id == "" {
  256. return mcp, errors.New("MCP id is empty")
  257. }
  258. err := DB.Where("id = ?", id).First(&mcp).Error
  259. return mcp, HandleNotFound(err, ErrPublicMCPNotFound)
  260. }
  261. // GetPublicMCPs retrieves MCPs with pagination and filtering
  262. func GetPublicMCPs(
  263. page, perPage int,
  264. mcpType PublicMCPType,
  265. keyword string,
  266. status PublicMCPStatus,
  267. ) (mcps []PublicMCP, total int64, err error) {
  268. tx := DB.Model(&PublicMCP{})
  269. if mcpType != "" {
  270. tx = tx.Where("type = ?", mcpType)
  271. }
  272. if keyword != "" {
  273. keyword = "%" + keyword + "%"
  274. if common.UsingPostgreSQL {
  275. tx = tx.Where(
  276. "name ILIKE ? OR author ILIKE ? OR tags ILIKE ? OR id ILIKE ?",
  277. keyword,
  278. keyword,
  279. keyword,
  280. keyword,
  281. )
  282. } else {
  283. tx = tx.Where("name LIKE ? OR author LIKE ? OR tags LIKE ? OR id LIKE ?", keyword, keyword, keyword, keyword)
  284. }
  285. }
  286. if status != 0 {
  287. tx = tx.Where("status = ?", status)
  288. }
  289. err = tx.Count(&total).Error
  290. if err != nil {
  291. return nil, 0, err
  292. }
  293. if total <= 0 {
  294. return nil, 0, nil
  295. }
  296. limit, offset := toLimitOffset(page, perPage)
  297. err = tx.
  298. Limit(limit).
  299. Offset(offset).
  300. Find(&mcps).
  301. Error
  302. return mcps, total, err
  303. }
  304. func GetAllPublicMCPs(status PublicMCPStatus) ([]PublicMCP, error) {
  305. var mcps []PublicMCP
  306. tx := DB.Model(&PublicMCP{})
  307. if status != 0 {
  308. tx = tx.Where("status = ?", status)
  309. }
  310. err := tx.Find(&mcps).Error
  311. return mcps, err
  312. }
  313. func GetPublicMCPsEnabled(ids []string) ([]string, error) {
  314. var mcpIDs []string
  315. err := DB.Model(&PublicMCP{}).
  316. Select("id").
  317. Where("id IN (?) AND status = ?", ids, PublicMCPStatusEnabled).
  318. Pluck("id", &mcpIDs).
  319. Error
  320. if err != nil {
  321. return nil, err
  322. }
  323. return mcpIDs, nil
  324. }
  325. func SavePublicMCPReusingParam(param *PublicMCPReusingParam) (err error) {
  326. defer func() {
  327. if err == nil {
  328. if err := CacheDeletePublicMCPReusingParam(param.MCPID, param.GroupID); err != nil {
  329. log.Error("cache delete public mcp reusing param error: " + err.Error())
  330. }
  331. }
  332. }()
  333. return DB.Save(param).Error
  334. }
  335. // UpdatePublicMCPReusingParam updates an existing GroupMCPReusingParam
  336. func UpdatePublicMCPReusingParam(param *PublicMCPReusingParam) (err error) {
  337. defer func() {
  338. if err == nil {
  339. if err := CacheDeletePublicMCPReusingParam(param.MCPID, param.GroupID); err != nil {
  340. log.Error("cache delete public mcp reusing param error: " + err.Error())
  341. }
  342. }
  343. }()
  344. result := DB.
  345. Select([]string{
  346. "reusing_params",
  347. }).
  348. Where("mcp_id = ? AND group_id = ?", param.MCPID, param.GroupID).
  349. Updates(param)
  350. return HandleUpdateResult(result, ErrMCPReusingParamNotFound)
  351. }
  352. // DeletePublicMCPReusingParam deletes a GroupMCPReusingParam
  353. func DeletePublicMCPReusingParam(mcpID, groupID string) (err error) {
  354. defer func() {
  355. if err == nil {
  356. if err := CacheDeletePublicMCPReusingParam(mcpID, groupID); err != nil {
  357. log.Error("cache delete public mcp reusing param error: " + err.Error())
  358. }
  359. }
  360. }()
  361. if mcpID == "" || groupID == "" {
  362. return errors.New("MCP ID or Group ID is empty")
  363. }
  364. result := DB.
  365. Where("mcp_id = ? AND group_id = ?", mcpID, groupID).
  366. Delete(&PublicMCPReusingParam{})
  367. return HandleUpdateResult(result, ErrMCPReusingParamNotFound)
  368. }
  369. // GetPublicMCPReusingParam retrieves a GroupMCPReusingParam by MCP ID and Group ID
  370. func GetPublicMCPReusingParam(mcpID, groupID string) (*PublicMCPReusingParam, error) {
  371. if mcpID == "" || groupID == "" {
  372. return nil, errors.New("MCP ID or Group ID is empty")
  373. }
  374. var param PublicMCPReusingParam
  375. err := DB.Where("mcp_id = ? AND group_id = ?", mcpID, groupID).First(&param).Error
  376. return &param, HandleNotFound(err, ErrMCPReusingParamNotFound)
  377. }