mirror of
https://github.com/APIParkLab/APIPark.git
synced 2026-06-14 20:41:15 +08:00
Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b54e12950 | |||
| ea32fb1cd6 | |||
| 6ee1996e6f | |||
| fdac169bda | |||
| 3026e24bab | |||
| 1a9b916bab | |||
| 5f40d5092c | |||
| b949939816 | |||
| ef1ccb81a9 | |||
| 8fba1911ad | |||
| 96e2e6ad51 | |||
| 0525c51a8f | |||
| 47950d9a2b | |||
| 4caa19586e | |||
| 8eba1ea898 | |||
| 17bd63b27e | |||
| 88d890107e | |||
| c1c5eaa84e | |||
| 388cd7660d | |||
| 3df303abc3 | |||
| 96d92e2323 | |||
| ba6342d207 | |||
| 5b38b2f78a | |||
| d5f2578a3f | |||
| a8d39b021c | |||
| 4b58534cb6 | |||
| 63f5a552c8 | |||
| 28ad364352 | |||
| 853c04337d | |||
| 902c64903c | |||
| 2f314e0e64 | |||
| 9879506c30 | |||
| 6dabd5d31b | |||
| 997e9292a2 | |||
| 76ae5287eb | |||
| c9c88116a8 |
@@ -0,0 +1,50 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="356px" height="48px" viewBox="0 0 356 48" enable-background="new 0 0 356 48" xml:space="preserve"> <image id="image0" width="356" height="48" x="0" y="0"
|
||||
xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWQAAAAwCAMAAAARrfBHAAAAIGNIUk0AAHomAACAhAAA+gAAAIDo
|
||||
AAB1MAAA6mAAADqYAAAXcJy6UTwAAAEmUExURQAAACBAQCAwQCoqQEBAQICAgCQ3SSoqVTMzTBwo
|
||||
OB0mOR0pORsoOBAgQBwoOB0qOhwpOR4oOxgoOBsqNR4pORwoOh0pOR0pOR4qOh0qOSAoOB0pOR0p
|
||||
OR0xOx4qOh0pOR4pNxspOR0pOR0pOBwoOhslNR0qORwpOhwpOR0oOBwoOCAqNRslOh4qOCAwQB0p
|
||||
OB4qOR0oOhwqOR4pOR0pOB0oOiYzQB0oOB0qOiAqQBwpOR4pOSoqOR0oOBgoOBwoOBwpOSAwQBwp
|
||||
OiAgQCAoOB0pORwqOSMuOh0qOB0pOSArNSQuQB0pOCAlOiIqOx0oOBwqORslOhsoOB0pOREhQB0q
|
||||
OR4nOR4nOSAwQBwoOCAlOiArNe9PIX65Ax0pOQOk7vu2BP///6G4x94AAABcdFJOUwAAAAAAAAAA
|
||||
AEBQUGAQgJ+QXyAwb4De73/vIN+vAc/+cHC/oH8w7s/PYL8wMIAQv++fz3CwngGgTwGvjwFhIUGP
|
||||
Ec4QIb4BAWDuMQG+MAHAzjFhURGvcXABvjEw0iVpWQAAAAFiS0dEYbKwTIYAAAAJcEhZcwAAFiUA
|
||||
ABYlAUlSJPAAAAAHdElNRQfpCBUKLDZRNHdnAAAHQ0lEQVR42u2Z+X/TNhTABW1hSm3HMV7b2FlT
|
||||
nIY27QhJuccOWLuDneweY9P2//8V03t6uhyXuUkIsI/fDxDL0tPTV++QXMYaaaSRRurKnxXC2F8V
|
||||
8rotfYulgbwCaSCvQBrIK5AG8gqkgbwCaSCvQBrIK5AG8gqkgTyfXOKt+p0XgrwZBMEF5qopIY/a
|
||||
7biTLK5Jmhdw83RNPoV+B57KmdI5Zrr8rhBbYd3ei0BOhJTt2lPVlJ2uUNJeFDNH+8xjJJ8y930r
|
||||
p5l6F57pvV0h+rxu70Ug76GF15eKOCyEkXzBKBmgFoOiDHnfzrQ9vKDqy1LZjaxu70UgK0colgr5
|
||||
AFR2e73DudZeZV98DuQRvDyKowF0yy8aj2uj6Lh25wUgv09usMx8Ad7V7cCvrJhn7a5sgi4nn5Ug
|
||||
y4AXI/w1WHo8Lg8y2DZy7Eu4FUhyQ87JE92GMIgQIgtbadQqJUPI8l0NAijftMN5mrpJUOqxw3WP
|
||||
qBX69u05+cKHPJZPt+jnRIgpNQ+DyEwTSrUhaE3AdN2KP9cT07ARyh5OfZUHjzTyTF0EsgyzEzax
|
||||
+SKyOU5E6r1aRWYbpon8J4dGqm+FhznSXHHYRJUtGB4kGPt5R+9G4RVHp8dtl+Kdcck+Cxm0arIS
|
||||
mIp9rtTmO+oJdghiK2A9Mxb84C67d18WPny+TAvZItOupP7zYpA5OnFsLa8FGROgdJKDyppTeBxg
|
||||
ZUM1/LY+CCiGiX4UeUKQb+omXS0hyDqgUeeLUrqALSwFUsfY39YrnAqEzE3EytjoP7CQH5pC3UfT
|
||||
4GxHzztLgDxAm7n1vVGhZEIhWgVZ7vJh8QFjj6DopMFg4p8BbQiDBLg+HJ5DiUKMCQWRmAbBQNdd
|
||||
+f+BOJr2aAvNhoWo43olZKTTdsMak1UUpLu0mXgEFN2ieMBsxMphW8xA/hAW0o1TsASOdGsfgQVp
|
||||
kObuEW9+yJgtcPbca9/X2KsgizzTy8E+kBJMfvBCmKnKGqlW1Smmw8JI16wR7afukeXK+WmKOyrf
|
||||
FpWQs5wYmstIoc2L1dZzYT0opgqvsoWGvP4xJAY55tIn8sdjtvFEKv30VL44kz8+Y4vKJkajmt11
|
||||
h2twuNe7MAs501GQm5XbPdId/cfMuOeYsnRu9qJQ1E2PPeX8TGcL7dAVkFk20JGtCkNCI9Q8AaUL
|
||||
6qzzxUh5KEH+PNYO+0UPPBwcuY9zAPX+wueuAZnM3aOoypbKHSohn6heMiCLDOVL9wyY+bocT55a
|
||||
f8qwpN1WwwdKpenBDWQN1+aLMmTZe6ATeYfcZqjU7qIdVhkz+QJZGsiQkZ86CgH6llLxFeZuJX9X
|
||||
CGP/VIjP2J6AJu7V1fHWSsiUcYUnQ1epky64hUxpNcCw4d7ovBJyoptsvpiFDLaNeqiF+4UbB3Ph
|
||||
3xdlChljVjCQv5ZL+sbR9rBwVfT1Ds0LeeRZZEx5ZIHUh2yzjZ/gIfYf0BHuopD3vD7ZuZAZpY3i
|
||||
vyB/iw+blA4I8neTVwrZ02ZifN+N95dAlrZ9HxjxD23cmyPzMrW6W0Aaic3oViXk3LPv5ssgY/ba
|
||||
Vu+tUbwEWaV/uR/PmO/Jz0qQ89mFzQk58X2RjmFQ9PJTB/KJWbkPeRcr/6xsmqpJwXKL9qiwmzDE
|
||||
mPWvwWXIV3/w7TuZhXzfKQawmypMvE3wIUO+gCV0HMiYk1GLugJCTn7KZmROyLp2g5jzhVP0iKQ6
|
||||
1Q5mIMdmX44D7txGxuCAdIjHC0eHIG+b+p8rzUR91OJhCTIE6b2BLTsYwnwG8p4wx7Nkgtswti0p
|
||||
qvUhw+sdrYIgw8e4fkfP8oyt/ahPG+tJahc2J2T3asa1px045An+QcJCyNMlyFy9on0pOY+8IYRh
|
||||
hrdVJIfnZOiN18Qp4drR3acOZDw4BSqMtUe98xPB8yEDM7EDNvCchsPtEO+L+2ohPmTKkGoFBHnj
|
||||
idyfp0O66N1Vz1tS6cbPv+jD3NyQE+Fezeja9siJz1saGMjhDGTcgLwdtbv+vpSqj0o96sbXLXrQ
|
||||
WUUKBEkeR4UuarhCCxmvBndJIy58ewYyzZTn+KkB1cLNSBRRXFDAlCCrWtpxIbMrv0Jb0Ybth+/L
|
||||
eOMTvSgGrY8X8+Q9j02kcmRRgowkBXxWm4Ws3wn3wofym1VypNI7DiflXfUhJzN17Qbc/H4vQXaz
|
||||
hQKij2huzrUmiFypPZ6YBn0FcCCP8W3oQcaEQZa0/Gfx3FSn+SDvevZSvpiBzPBrw1HGKiCz0aEC
|
||||
OfM3nIxuCOYNQh7j9exIfygfqw8Z3edoRRmymy3oyhtXnC643rno1MztNpQg4wKnduPUV7g1Wshz
|
||||
Un31D/qS55TmeY9wNeX4+PTcd5msx9Vvjzl3xlEgnPq9r77g/MX5ymsKfPvOyi21/6ykZD3zLdk4
|
||||
Let4xZCXIaUvGm+hNJBXIA3kFcibD3n9rIH8ymX9rCiK0evmtJC8+ZD/B9JAXoE0kFcgDeQVSAO5
|
||||
kUYaaeQNkX8BdcAtjNRFbWoAAAAldEVYdGRhdGU6Y3JlYXRlADIwMjUtMDgtMjFUMTA6NDQ6NTMr
|
||||
MDA6MDBp1auWAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDI1LTA4LTIxVDEwOjQ0OjUzKzAwOjAwGIgT
|
||||
KgAAACh0RVh0ZGF0ZTp0aW1lc3RhbXAAMjAyNS0wOC0yMVQxMDo0NDo1NCswMDowMIo6DHsAAAAA
|
||||
SUVORK5CYII=" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.1 KiB |
@@ -0,0 +1,8 @@
|
||||
<svg width="21" height="22" viewBox="0 0 21 22" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g id="Microsoft">
|
||||
<rect id="Rectangle 1010" y="0.5" width="10" height="10" fill="#EF4F21"/>
|
||||
<rect id="Rectangle 1012" y="11.5" width="10" height="10" fill="#03A4EE"/>
|
||||
<rect id="Rectangle 1011" x="11" y="0.5" width="10" height="10" fill="#7EB903"/>
|
||||
<rect id="Rectangle 1013" x="11" y="11.5" width="10" height="10" fill="#FBB604"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 439 B |
@@ -0,0 +1,40 @@
|
||||
provider: azure_openai
|
||||
label:
|
||||
en_US: Azure OpenAI
|
||||
icon_small:
|
||||
en_US: icon_s_en.svg
|
||||
icon_large:
|
||||
en_US: icon_l_en.svg
|
||||
background: "#E3F0FF"
|
||||
help:
|
||||
title:
|
||||
en_US: Get your API key from Azure
|
||||
zh_Hans: 从 Azure 获取 API Key
|
||||
url:
|
||||
en_US: https://azure.microsoft.com/en-us/products/ai-services/openai-service
|
||||
supported_model_types:
|
||||
- llm
|
||||
configurate_methods:
|
||||
- customizable-model
|
||||
provider_credential_schema:
|
||||
credential_form_schemas:
|
||||
- variable: api_key
|
||||
label:
|
||||
en_US: API Key
|
||||
type: secret-input
|
||||
required: true
|
||||
placeholder:
|
||||
zh_Hans: 在此输入您的 API Key
|
||||
en_US: Enter your API Key
|
||||
- variable: base_url
|
||||
type: text-input
|
||||
required: true
|
||||
placeholder:
|
||||
zh_Hans: 在此输入您的 Base URL
|
||||
en_US: Enter your Base URL
|
||||
- variable: api_version
|
||||
label:
|
||||
en_US: '2024-02-01'
|
||||
type: text-input
|
||||
required: true
|
||||
address: https://docs-test-001.openai.azure.com/
|
||||
@@ -113,9 +113,13 @@ func (i *imlAPIController) Edit(ctx *gin.Context, serviceId string, apiId string
|
||||
if input.AiModel.Type != "local" {
|
||||
provider = input.AiModel.Provider
|
||||
}
|
||||
modelName := input.AiModel.Name
|
||||
if modelName == "" {
|
||||
modelName = input.AiModel.Id
|
||||
}
|
||||
proxy.Plugins["ai_formatter"] = api.PluginSetting{
|
||||
Config: plugin_model.ConfigType{
|
||||
"model": input.AiModel.Name,
|
||||
"model": modelName,
|
||||
"provider": provider,
|
||||
"config": input.AiModel.Config,
|
||||
},
|
||||
|
||||
+159
-173
@@ -6,6 +6,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/APIParkLab/APIPark/module/service"
|
||||
|
||||
application_authorization "github.com/APIParkLab/APIPark/module/application-authorization"
|
||||
|
||||
mcp_server "github.com/APIParkLab/APIPark/mcp-server"
|
||||
@@ -13,203 +15,168 @@ import (
|
||||
"github.com/APIParkLab/APIPark/module/system"
|
||||
"github.com/eolinker/go-common/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
mcp2 "github.com/mark3labs/mcp-go/mcp"
|
||||
"github.com/mark3labs/mcp-go/server"
|
||||
)
|
||||
|
||||
var _ IMcpController = (*imlMcpController)(nil)
|
||||
|
||||
type imlMcpController struct {
|
||||
settingModule system.ISettingModule `autowired:""`
|
||||
authorizationModule application_authorization.IAuthorizationModule `autowired:""`
|
||||
mcpModule mcp.IMcpModule `autowired:""`
|
||||
sessionKeys sync.Map
|
||||
server map[string]http.Handler
|
||||
openServer http.Handler
|
||||
settingModule system.ISettingModule `autowired:""`
|
||||
authorizationModule application_authorization.IAuthorizationModule `autowired:""`
|
||||
appModule service.IAppModule `autowired:""`
|
||||
mcpModule mcp.IMcpModule `autowired:""`
|
||||
sessionKeys sync.Map
|
||||
sseServers map[string]http.Handler
|
||||
openSseServer http.Handler
|
||||
openStreamableServer http.Handler
|
||||
}
|
||||
|
||||
var mcpDefaultConfig = `{
|
||||
"mcpServers": {
|
||||
"%s": {
|
||||
"url": "%s"
|
||||
}
|
||||
}
|
||||
func (i *imlMcpController) AppMCPHandle(ctx *gin.Context) {
|
||||
appId := ctx.Param("app")
|
||||
if appId == "" {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": "invalid app id", "success": "fail"})
|
||||
return
|
||||
}
|
||||
cfg := i.settingModule.Get(ctx)
|
||||
req := ctx.Request.WithContext(utils.SetGatewayInvoke(ctx.Request.Context(), cfg.InvokeAddress))
|
||||
req = req.WithContext(utils.SetLabel(req.Context(), "app", appId))
|
||||
paths := strings.Split(req.URL.Path, "/")
|
||||
req.URL.Path = fmt.Sprintf("/api/v1/%s/%s", mcp_server.GlobalBasePath, paths[len(paths)-1])
|
||||
locale := utils.I18n(ctx)
|
||||
if v, ok := i.sseServers[locale]; ok {
|
||||
v.ServeHTTP(ctx.Writer, req)
|
||||
return
|
||||
}
|
||||
|
||||
i.sseServers[languageEnUs].ServeHTTP(ctx.Writer, req)
|
||||
}
|
||||
|
||||
func (i *imlMcpController) AppHandleSSE(ctx *gin.Context) {
|
||||
apikey := ctx.Request.URL.Query().Get("apikey")
|
||||
appId := ctx.Param("app")
|
||||
if appId == "" {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": "invalid app id", "success": "fail"})
|
||||
return
|
||||
}
|
||||
ok, err := i.authorizationModule.CheckAPIKeyAuthorizationByApp(ctx, appId, apikey)
|
||||
if err != nil {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": err.Error(), "success": "fail"})
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": "invalid apikey", "success": "fail"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Request.URL.Path = fmt.Sprintf("/openapi/v1/%s/sse", mcp_server.GlobalBasePath)
|
||||
i.handleSSE(ctx, i.openSseServer, SessionInfo{
|
||||
Apikey: apikey,
|
||||
App: appId,
|
||||
})
|
||||
}
|
||||
|
||||
func (i *imlMcpController) AppHandleMessage(ctx *gin.Context) {
|
||||
appId := ctx.Param("app")
|
||||
if appId == "" {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": "invalid app id", "success": "fail"})
|
||||
return
|
||||
}
|
||||
ctx.Request.URL.Path = fmt.Sprintf("/openapi/v1/%s/message", mcp_server.GlobalBasePath)
|
||||
//ctx.Request = ctx.Request.WithContext(utils.SetLabel(ctx.Request.Context(), "app", appId))
|
||||
i.handleMessage(ctx, i.openSseServer)
|
||||
}
|
||||
|
||||
func (i *imlMcpController) AppHandleStreamHTTP(ctx *gin.Context) {
|
||||
apikey := ctx.Request.Header.Get("Authorization")
|
||||
apikey = strings.TrimPrefix(apikey, "Bearer ")
|
||||
if apikey == "" {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": "invalid apikey", "success": "fail"})
|
||||
return
|
||||
}
|
||||
appId := ctx.Request.Header.Get("X-Application-Id")
|
||||
if appId == "" {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": "invalid app id", "success": "fail"})
|
||||
return
|
||||
}
|
||||
cfg := i.settingModule.Get(ctx)
|
||||
req := ctx.Request.WithContext(utils.SetGatewayInvoke(ctx.Request.Context(), cfg.InvokeAddress))
|
||||
|
||||
req = req.WithContext(utils.SetLabel(req.Context(), "apikey", apikey))
|
||||
req = req.WithContext(utils.SetLabel(req.Context(), "app", appId))
|
||||
req.URL.Path = mcp_server.OpenGlobalMCPPath
|
||||
i.openStreamableServer.ServeHTTP(ctx.Writer, req)
|
||||
}
|
||||
|
||||
func (i *imlMcpController) AppMCPConfig(ctx *gin.Context, appId string) (string, error) {
|
||||
cfg := i.settingModule.Get(ctx)
|
||||
if cfg.SitePrefix == "" {
|
||||
return "", fmt.Errorf("site prefix is empty")
|
||||
}
|
||||
appInfo, err := i.appModule.GetApp(ctx, appId)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("get app info error: %v", err)
|
||||
}
|
||||
|
||||
return mcp_server.NewMCPConfig(
|
||||
mcp_server.TransportTypeStreamableHTTP,
|
||||
fmt.Sprintf("%s%s", strings.TrimSuffix(cfg.SitePrefix, "/"), mcp_server.OpenAppMCPPath),
|
||||
map[string]string{
|
||||
"Authorization": "Bearer {your_api_key}",
|
||||
"X-Application-Id": appId,
|
||||
},
|
||||
nil,
|
||||
).ToString(appInfo.Name), nil
|
||||
}
|
||||
`
|
||||
|
||||
func (i *imlMcpController) GlobalMCPConfig(ctx *gin.Context) (string, error) {
|
||||
cfg := i.settingModule.Get(ctx)
|
||||
if cfg.SitePrefix == "" {
|
||||
return "", fmt.Errorf("site prefix is empty")
|
||||
}
|
||||
return fmt.Sprintf(mcpDefaultConfig, "APIPark-MCP-Server", fmt.Sprintf("%s/openapi/v1/%s/sse?apikey={your_api_key}", strings.TrimSuffix(cfg.SitePrefix, "/"), mcp_server.GlobalBasePath)), nil
|
||||
}
|
||||
|
||||
func (i *imlMcpController) generateZhCNMCPServer() *server.MCPServer {
|
||||
s := server.NewMCPServer("APIPark MCP Server", "1.0.0", server.WithLogging())
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"service_list",
|
||||
mcp2.WithDescription("此工具用于获取 APIPark 中已注册服务的列表。每个服务包含其唯一标识(service ID)、名称、描述及包含的 API 列表等关键信息。支持通过关键词进行模糊搜索,以便快速缩小查找范围。在获得某个服务的 ID 后,可以调用 openapi_document 工具来获取该服务的 OpenAPI 文档,以便后续调用其提供的 API 接口。"),
|
||||
mcp2.WithString("keyword", mcp2.Description("关键词,用于模糊搜索服务")),
|
||||
),
|
||||
i.mcpModule.Services,
|
||||
)
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"openapi_document",
|
||||
mcp2.WithDescription("此工具用于获取指定服务的 OpenAPI 接口文档。返回内容支持 OpenAPI v3 与 v2 两种规范格式。通过传入服务 ID,可以查看该服务的所有 API 定义、参数结构、请求方式等详细信息,为后续构造请求做准备。"),
|
||||
mcp2.WithString("service", mcp2.Description("服务的唯一标识 ID")),
|
||||
),
|
||||
i.mcpModule.APIs,
|
||||
)
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"invoke_api",
|
||||
mcp2.WithDescription("此工具用于直接调用指定的 API 接口。调用前需根据该接口的 OpenAPI 文档构造必要的请求参数,如请求路径、方法、查询参数、请求头、请求体等。调用过程中无需传递认证信息,例如请求头中的 Authorization 字段不需要提供。"),
|
||||
mcp2.WithString("path", mcp2.Description("API 请求路径"), mcp2.Required()),
|
||||
mcp2.WithString("method", mcp2.Description("API 请求方法,例如 GET、POST、PUT"), mcp2.Required()),
|
||||
mcp2.WithString("content-type", mcp2.Description("请求的 Content-Type 类型。如果方法为 POST、PUT 或 PATCH,则必须指定该字段。")),
|
||||
mcp2.WithObject("query", mcp2.Description("请求的查询参数,类型为 map[string]string")),
|
||||
mcp2.WithObject("header", mcp2.Description("请求的头部参数,类型为 map[string]string")),
|
||||
mcp2.WithString("body", mcp2.Description("请求体内容,通常为 JSON 字符串")),
|
||||
),
|
||||
i.mcpModule.Invoke,
|
||||
)
|
||||
return s
|
||||
}
|
||||
|
||||
func (i *imlMcpController) generateZhTWMCPServer() *server.MCPServer {
|
||||
s := server.NewMCPServer("APIPark MCP Server", "1.0.0", server.WithLogging())
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"service_list",
|
||||
mcp2.WithDescription("此工具用於獲取 APIPark 中已註冊服務的清單。每個服務包含其唯一識別碼(service ID)、名稱、描述以及該服務所包含的 API 列表。支援關鍵字模糊搜尋,可快速縮小查詢範圍。獲取到服務 ID 後,可使用 openapi_document 工具來查詢該服務對應的 OpenAPI 文件,為後續 API 呼叫做準備。"),
|
||||
mcp2.WithString("keyword", mcp2.Description("關鍵字,用於模糊搜尋服務")),
|
||||
),
|
||||
i.mcpModule.Services,
|
||||
)
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"openapi_document",
|
||||
mcp2.WithDescription("此工具用於查詢指定服務的 OpenAPI 文件。返回的格式支援 OpenAPI v3 與 v2 標準。透過輸入服務 ID,可查閱該服務所有 API 的定義、參數結構、請求方式等細節,有助於後續構造 API 呼叫請求。"),
|
||||
mcp2.WithString("service", mcp2.Description("欲查詢的服務唯一識別碼")),
|
||||
),
|
||||
i.mcpModule.APIs,
|
||||
)
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"invoke_api",
|
||||
mcp2.WithDescription("此工具可直接發送 API 請求。在呼叫此工具之前,需根據該 API 的 OpenAPI 文件構造所需的請求參數,如請求路徑、方法、查詢參數、標頭、主體等。使用此工具時不需傳送任何認證資訊,例如 Authorization 標頭可省略。"),
|
||||
mcp2.WithString("path", mcp2.Description("API 的請求路徑"), mcp2.Required()),
|
||||
mcp2.WithString("method", mcp2.Description("API 的請求方法,例如 GET、POST、PUT"), mcp2.Required()),
|
||||
mcp2.WithString("content-type", mcp2.Description("請求的 Content-Type。若方法為 POST、PUT 或 PATCH,則必須指定")),
|
||||
mcp2.WithObject("query", mcp2.Description("請求的查詢參數,類型為 map[string]string")),
|
||||
mcp2.WithObject("header", mcp2.Description("請求的標頭,類型為 map[string]string")),
|
||||
mcp2.WithString("body", mcp2.Description("請求主體內容,通常為 JSON 字串")),
|
||||
),
|
||||
i.mcpModule.Invoke,
|
||||
)
|
||||
return s
|
||||
}
|
||||
|
||||
func (i *imlMcpController) generateEnMCPServer() *server.MCPServer {
|
||||
s := server.NewMCPServer("APIPark MCP Server", "1.0.0", server.WithLogging())
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"service_list",
|
||||
mcp2.WithDescription("This tool can retrieve a list of registered services on APIPark, including key information such as service ID, name, description, and API list within the service. Support keyword search to quickly narrow down the search scope. After obtaining the service ID, you can use this ID to call the tool openapi_document to obtain the openapi document of the service for the corresponding service, preparing for subsequent API calls."),
|
||||
mcp2.WithString("keyword", mcp2.Description("Keyword for fuzzy search")),
|
||||
),
|
||||
i.mcpModule.Services,
|
||||
)
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"openapi_document",
|
||||
mcp2.WithDescription("This tool returns the openAPI documentation for the corresponding service. The format supports the specifications of OpenAPI v3 and OpenAPI v2."),
|
||||
mcp2.WithString("service", mcp2.Description("Service ID")),
|
||||
),
|
||||
i.mcpModule.APIs,
|
||||
)
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"invoke_api",
|
||||
mcp2.WithDescription("This tool can directly make API calls. Before calling this tool, it is necessary to construct relevant parameters based on the corresponding API's openAPI documentation, including query, header, body, method, path, and other parameters. By using this tool, no authentication related information needs to be transmitted, that is, no request header Authorization needs to be transmitted."),
|
||||
mcp2.WithString("path", mcp2.Description("API path"), mcp2.Required()),
|
||||
mcp2.WithString("method", mcp2.Description("API method"), mcp2.Required()),
|
||||
mcp2.WithString("content-type", mcp2.Description("API Request Content-Type. If method is POST,PUT,PATCH, it must be set. If not set, it will be ignored.")),
|
||||
mcp2.WithObject("query", mcp2.Description("API Request query,param type is map[string]string")),
|
||||
mcp2.WithObject("header", mcp2.Description("API Request header,param type is map[string]string")),
|
||||
mcp2.WithString("body", mcp2.Description("API Request body")),
|
||||
),
|
||||
i.mcpModule.Invoke,
|
||||
)
|
||||
return s
|
||||
}
|
||||
|
||||
func (i *imlMcpController) generateJPMCPServer() *server.MCPServer {
|
||||
s := server.NewMCPServer("APIPark MCP Server", "1.0.0", server.WithLogging())
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"service_list",
|
||||
mcp2.WithDescription("このツールは、APIPark に登録されているサービスの一覧を取得するためのものです。各サービスには、サービスID、名称、説明、およびそのサービスに含まれるAPI一覧といった重要な情報が含まれます。キーワードによるあいまい検索が可能で、目的のサービスを素早く絞り込むことができます。取得したサービスIDを使用して openapi_document ツールを呼び出すことで、そのサービスの OpenAPI ドキュメントを取得でき、APIの利用準備が整います。"),
|
||||
mcp2.WithString("keyword", mcp2.Description("キーワード。サービスをあいまい検索するための文字列")),
|
||||
),
|
||||
i.mcpModule.Services,
|
||||
)
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"openapi_document",
|
||||
mcp2.WithDescription("指定されたサービスの OpenAPI ドキュメントを取得するためのツールです。OpenAPI v3 および v2 のフォーマットに対応しています。このドキュメントを使用することで、APIのエンドポイント、リクエスト方法、パラメータなどの詳細を確認でき、API呼び出しの準備に役立ちます。"),
|
||||
mcp2.WithString("service", mcp2.Description("対象のサービスID")),
|
||||
),
|
||||
i.mcpModule.APIs,
|
||||
)
|
||||
s.AddTool(
|
||||
mcp2.NewTool(
|
||||
"invoke_api",
|
||||
mcp2.WithDescription("このツールは、指定された API を直接呼び出すためのものです。呼び出し前に、OpenAPI ドキュメントに基づいて必要なパラメータ(パス、メソッド、クエリ、ヘッダー、ボディなど)を構築する必要があります。呼び出し時に認証情報(例:Authorization ヘッダー)を送信する必要はありません。"),
|
||||
mcp2.WithString("path", mcp2.Description("API のリクエストパス"), mcp2.Required()),
|
||||
mcp2.WithString("method", mcp2.Description("HTTPメソッド(GET、POST、PUTなど)。"), mcp2.Required()),
|
||||
mcp2.WithString("content-type", mcp2.Description("リクエストの Content-Type。メソッドが POST、PUT、PATCH の場合に必須。")),
|
||||
mcp2.WithObject("query", mcp2.Description("リクエストのクエリパラメータ。型は map[string]string")),
|
||||
mcp2.WithObject("header", mcp2.Description("リクエストヘッダー。型は map[string]string")),
|
||||
mcp2.WithString("body", mcp2.Description("リクエストボディ。通常はJSON文字列")),
|
||||
),
|
||||
i.mcpModule.Invoke,
|
||||
)
|
||||
return s
|
||||
return mcp_server.NewMCPConfig(
|
||||
mcp_server.TransportTypeStreamableHTTP,
|
||||
fmt.Sprintf("%s%s", strings.TrimSuffix(cfg.SitePrefix, "/"), mcp_server.OpenGlobalMCPPath),
|
||||
map[string]string{
|
||||
"Authorization": "Bearer {your_api_key}",
|
||||
},
|
||||
nil,
|
||||
).ToString("APIPark-MCP-Server"), nil
|
||||
}
|
||||
|
||||
func (i *imlMcpController) OnComplete() {
|
||||
i.server = make(map[string]http.Handler)
|
||||
enSer := i.generateEnMCPServer()
|
||||
i.server["en-US"] = server.NewSSEServer(enSer, server.WithBasePath(fmt.Sprintf("/api/v1/%s", mcp_server.GlobalBasePath)))
|
||||
i.server["zh-CN"] = server.NewSSEServer(i.generateZhCNMCPServer(), server.WithBasePath(fmt.Sprintf("/api/v1/%s", mcp_server.GlobalBasePath)))
|
||||
i.server["zh-TW"] = server.NewSSEServer(i.generateZhTWMCPServer(), server.WithBasePath(fmt.Sprintf("/api/v1/%s", mcp_server.GlobalBasePath)))
|
||||
i.server["ja-JP"] = server.NewSSEServer(i.generateJPMCPServer(), server.WithBasePath(fmt.Sprintf("/api/v1/%s", mcp_server.GlobalBasePath)))
|
||||
|
||||
i.openServer = server.NewSSEServer(enSer, server.WithBasePath(fmt.Sprintf("/openapi/v1/%s", strings.Trim(mcp_server.GlobalBasePath, "/"))))
|
||||
|
||||
i.sseServers = make(map[string]http.Handler)
|
||||
for language, tools := range mcpToolsByLanguage {
|
||||
s := server.NewMCPServer("APIPark MCP Server", "1.0.0", server.WithLogging())
|
||||
s.AddTool(tools[ToolServiceList], i.mcpModule.Services)
|
||||
s.AddTool(tools[ToolOpenAPIDocument], i.mcpModule.APIs)
|
||||
s.AddTool(tools[ToolInvokeAPI], i.mcpModule.Invoke)
|
||||
i.sseServers[language] = server.NewSSEServer(s, server.WithStaticBasePath(fmt.Sprintf("/api/v1/%s", mcp_server.GlobalBasePath)))
|
||||
if language == languageEnUs {
|
||||
i.openSseServer = server.NewSSEServer(s, server.WithStaticBasePath(fmt.Sprintf("/openapi/v1/%s", strings.Trim(mcp_server.GlobalBasePath, "/"))))
|
||||
i.openStreamableServer = server.NewStreamableHTTPServer(s, server.WithEndpointPath(mcp_server.OpenGlobalMCPPath))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (i *imlMcpController) GlobalMCPHandle(ctx *gin.Context) {
|
||||
cfg := i.settingModule.Get(ctx)
|
||||
req := ctx.Request.WithContext(utils.SetGatewayInvoke(ctx.Request.Context(), cfg.InvokeAddress))
|
||||
locale := utils.I18n(ctx)
|
||||
if v, ok := i.server[locale]; ok {
|
||||
if v, ok := i.sseServers[locale]; ok {
|
||||
v.ServeHTTP(ctx.Writer, req)
|
||||
return
|
||||
}
|
||||
i.server["en-US"].ServeHTTP(ctx.Writer, req)
|
||||
i.sseServers[languageEnUs].ServeHTTP(ctx.Writer, req)
|
||||
}
|
||||
|
||||
func (i *imlMcpController) GlobalHandleSSE(ctx *gin.Context) {
|
||||
apikey := ctx.Request.URL.Query().Get("apikey")
|
||||
i.handleSSE(ctx, i.openServer, apikey)
|
||||
i.handleSSE(ctx, i.openSseServer, SessionInfo{
|
||||
Apikey: apikey,
|
||||
})
|
||||
}
|
||||
|
||||
func (i *imlMcpController) handleSSE(ctx *gin.Context, server http.Handler, apikey string) {
|
||||
func (i *imlMcpController) handleSSE(ctx *gin.Context, server http.Handler, sIn SessionInfo) {
|
||||
|
||||
writer := &ResponseWriter{
|
||||
Writer: ctx.Writer,
|
||||
@@ -223,14 +190,23 @@ func (i *imlMcpController) handleSSE(ctx *gin.Context, server http.Handler, apik
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
i.sessionKeys.Store(sessionId, apikey)
|
||||
i.sessionKeys.Store(sessionId, sIn)
|
||||
}()
|
||||
server.ServeHTTP(writer, ctx.Request)
|
||||
i.sessionKeys.Delete(sessionId)
|
||||
}
|
||||
|
||||
func (i *imlMcpController) GlobalHandleMessage(ctx *gin.Context) {
|
||||
i.handleMessage(ctx, i.openServer)
|
||||
i.handleMessage(ctx, i.openSseServer)
|
||||
}
|
||||
|
||||
func (i *imlMcpController) GlobalHandleStreamHTTP(ctx *gin.Context) {
|
||||
apikey := ctx.Request.Header.Get("Authorization")
|
||||
apikey = strings.TrimPrefix(apikey, "Bearer ")
|
||||
cfg := i.settingModule.Get(ctx)
|
||||
req := ctx.Request.WithContext(utils.SetGatewayInvoke(ctx.Request.Context(), cfg.InvokeAddress))
|
||||
req = req.WithContext(utils.SetLabel(req.Context(), "apikey", apikey))
|
||||
i.openStreamableServer.ServeHTTP(ctx.Writer, req)
|
||||
}
|
||||
|
||||
func (i *imlMcpController) MCPHandle(ctx *gin.Context) {
|
||||
@@ -247,7 +223,7 @@ func (i *imlMcpController) ServiceHandleSSE(ctx *gin.Context) {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": "invalid service id", "success": "fail"})
|
||||
return
|
||||
}
|
||||
ok, err := i.authorizationModule.CheckAPIKeyAuthorization(ctx, serviceId, apikey)
|
||||
ok, err := i.authorizationModule.CheckAPIKeyAuthorizationByService(ctx, serviceId, apikey)
|
||||
if err != nil {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": err.Error(), "success": "fail"})
|
||||
return
|
||||
@@ -257,7 +233,9 @@ func (i *imlMcpController) ServiceHandleSSE(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
i.handleSSE(ctx, mcp_server.DefaultMCPServer(), apikey)
|
||||
i.handleSSE(ctx, mcp_server.DefaultMCPServer(), SessionInfo{
|
||||
Apikey: apikey,
|
||||
})
|
||||
}
|
||||
|
||||
func (i *imlMcpController) ServiceHandleMessage(ctx *gin.Context) {
|
||||
@@ -265,13 +243,14 @@ func (i *imlMcpController) ServiceHandleMessage(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
func (i *imlMcpController) ServiceHandleStreamHTTP(ctx *gin.Context) {
|
||||
apikey := ctx.Request.URL.Query().Get("apikey")
|
||||
serviceId := ctx.Param("serviceId")
|
||||
apikey := ctx.Request.Header.Get("Authorization")
|
||||
serviceId := ctx.Request.Header.Get("X-Service-Id")
|
||||
if serviceId == "" {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": "invalid service id", "success": "fail"})
|
||||
return
|
||||
}
|
||||
ok, err := i.authorizationModule.CheckAPIKeyAuthorization(ctx, serviceId, apikey)
|
||||
apikey = strings.TrimPrefix(apikey, "Bearer ")
|
||||
ok, err := i.authorizationModule.CheckAPIKeyAuthorizationByService(ctx, serviceId, apikey)
|
||||
if err != nil {
|
||||
ctx.AbortWithStatusJSON(403, gin.H{"code": -1, "msg": err.Error(), "success": "fail"})
|
||||
return
|
||||
@@ -288,13 +267,20 @@ func (i *imlMcpController) ServiceHandleStreamHTTP(ctx *gin.Context) {
|
||||
|
||||
func (i *imlMcpController) handleMessage(ctx *gin.Context, server http.Handler) {
|
||||
sessionId := ctx.Request.URL.Query().Get("sessionId")
|
||||
apikey, ok := i.sessionKeys.Load(sessionId)
|
||||
params, ok := i.sessionKeys.Load(sessionId)
|
||||
if !ok {
|
||||
ctx.String(403, "sessionId not found")
|
||||
return
|
||||
}
|
||||
ps, ok := params.(SessionInfo)
|
||||
cfg := i.settingModule.Get(ctx)
|
||||
req := ctx.Request.WithContext(utils.SetGatewayInvoke(ctx.Request.Context(), cfg.InvokeAddress))
|
||||
req = req.WithContext(utils.SetLabel(req.Context(), "apikey", apikey.(string)))
|
||||
req = req.WithContext(utils.SetLabel(req.Context(), "apikey", ps.Apikey))
|
||||
req = req.WithContext(utils.SetLabel(req.Context(), "app", ps.App))
|
||||
server.ServeHTTP(ctx.Writer, req)
|
||||
}
|
||||
|
||||
type SessionInfo struct {
|
||||
Apikey string
|
||||
App string
|
||||
}
|
||||
|
||||
+11
-1
@@ -9,12 +9,22 @@ import (
|
||||
|
||||
type IMcpController interface {
|
||||
MCPHandle(ctx *gin.Context)
|
||||
|
||||
GlobalMCPHandle(ctx *gin.Context)
|
||||
GlobalHandleSSE(ctx *gin.Context)
|
||||
GlobalHandleMessage(ctx *gin.Context)
|
||||
GlobalHandleStreamHTTP(ctx *gin.Context)
|
||||
GlobalMCPConfig(ctx *gin.Context) (string, error)
|
||||
|
||||
AppMCPHandle(ctx *gin.Context)
|
||||
AppHandleSSE(ctx *gin.Context)
|
||||
AppHandleMessage(ctx *gin.Context)
|
||||
AppHandleStreamHTTP(ctx *gin.Context)
|
||||
AppMCPConfig(ctx *gin.Context, appId string) (string, error)
|
||||
|
||||
ServiceHandleSSE(ctx *gin.Context)
|
||||
ServiceHandleMessage(ctx *gin.Context)
|
||||
GlobalMCPConfig(ctx *gin.Context) (string, error)
|
||||
|
||||
ServiceHandleStreamHTTP(ctx *gin.Context)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package mcp
|
||||
|
||||
import "github.com/mark3labs/mcp-go/mcp"
|
||||
|
||||
const (
|
||||
ToolServiceList = "service_list"
|
||||
ToolOpenAPIDocument = "openapi_document"
|
||||
ToolInvokeAPI = "invoke_api"
|
||||
|
||||
languageZhCN = "zh-CN"
|
||||
languageZhTW = "zh-TW"
|
||||
languageEnUs = "en-US"
|
||||
languageJaJp = "ja-JP"
|
||||
)
|
||||
|
||||
var mcpToolsByLanguage = map[string]map[string]mcp.Tool{
|
||||
languageZhCN: toolsZhCN,
|
||||
languageZhTW: toolsZhTW,
|
||||
languageEnUs: toolsEnUs,
|
||||
languageJaJp: toolsJaJp,
|
||||
}
|
||||
|
||||
var toolsZhTW = map[string]mcp.Tool{
|
||||
ToolServiceList: mcp.NewTool(
|
||||
ToolServiceList,
|
||||
mcp.WithDescription("此工具用於獲取 APIPark 中已註冊服務的列表。每個服務包含其唯一標識(service ID)、名稱、描述及包含的 API 列表等關鍵信息。支持通過關鍵詞進行模糊搜索,以便快速縮小查找範圍。在獲得某個服務的 ID 後,可以調用 openapi_document 工具來獲取該服務的 OpenAPI 文檔,以便後續調用其提供的 API 接口。"),
|
||||
mcp.WithString("keyword", mcp.Description("關鍵詞,用於模糊搜索服務"))),
|
||||
ToolOpenAPIDocument: mcp.NewTool(
|
||||
ToolOpenAPIDocument,
|
||||
mcp.WithDescription("此工具用於獲取 APIPark 中服務的 OpenAPI 文檔。"),
|
||||
mcp.WithString("service_id", mcp.Description("服務 ID"))),
|
||||
ToolInvokeAPI: mcp.NewTool(
|
||||
ToolInvokeAPI,
|
||||
mcp.WithDescription("此工具可直接發送 API 請求。在調用此工具之前,需要根據該 API 的 OpenAPI 文檔構造所需的請求參數,如請求路徑、方法、查詢參數、頭部信息、主體內容等。使用此工具時不需要傳遞任何認證信息,例如 Authorization 頭部可以省略。"),
|
||||
mcp.WithString("path", mcp.Description("API 的請求路徑"), mcp.Required()),
|
||||
mcp.WithString("method", mcp.Description("API 的請求方法,例如 GET、POST、PUT"), mcp.Required()),
|
||||
mcp.WithString("content-type", mcp.Description("請求的 Content-Type。若方法為 POST、PUT 或 PATCH,則必須指定")),
|
||||
mcp.WithObject("query", mcp.Description("請求的查詢參數,類型為 map[string]string")),
|
||||
mcp.WithObject("header", mcp.Description("請求的頭部,類型為 map[string]string")),
|
||||
mcp.WithString("body", mcp.Description("請求主體內容,通常為 JSON 字符串")),
|
||||
),
|
||||
}
|
||||
|
||||
var toolsZhCN = map[string]mcp.Tool{
|
||||
ToolServiceList: mcp.NewTool(
|
||||
ToolServiceList,
|
||||
mcp.WithDescription("此工具用于获取 APIPark 中已注册服务的列表。每个服务包含其唯一标识(service ID)、名称、描述及包含的 API 列表等关键信息。支持通过关键词进行模糊搜索,以便快速缩小查找范围。在获得某个服务的 ID 后,可以调用 openapi_document 工具来获取该服务的 OpenAPI 文档,以便后续调用其提供的 API 接口。"),
|
||||
mcp.WithString("keyword", mcp.Description("关键词,用于模糊搜索服务"))),
|
||||
ToolOpenAPIDocument: mcp.NewTool(
|
||||
ToolOpenAPIDocument, mcp.WithDescription("此工具用于查询指定服务的 OpenAPI 文档。返回的格式支持 OpenAPI v3 和 v2 标准。通过输入服务 ID,可以查看该服务所有 API 的定义、参数结构、请求方式等详细信息,为后续构造 API 调用请求做准备。"),
|
||||
mcp.WithString("service", mcp.Description("欲查询的服务唯一标识")),
|
||||
),
|
||||
ToolInvokeAPI: mcp.NewTool(ToolInvokeAPI,
|
||||
mcp.WithDescription("此工具可直接发送 API 请求。在调用此工具之前,需要根据该 API 的 OpenAPI 文档构造所需的请求参数,如请求路径、方法、查询参数、头部信息、主体内容等。使用此工具时不需要传递任何认证信息,例如 Authorization 头部可以省略。"),
|
||||
mcp.WithString("path", mcp.Description("API 的请求路径"), mcp.Required()),
|
||||
mcp.WithString("method", mcp.Description("API 的请求方法,例如 GET、POST、PUT"), mcp.Required()),
|
||||
mcp.WithString("content-type", mcp.Description("请求的 Content-Type。若方法为 POST、PUT 或 PATCH,则必须指定")),
|
||||
mcp.WithObject("query", mcp.Description("请求的查询参数,类型为 map[string]string")),
|
||||
mcp.WithObject("header", mcp.Description("请求的头部,类型为 map[string]string")),
|
||||
mcp.WithString("body", mcp.Description("请求主体内容,通常为 JSON 字符串")),
|
||||
),
|
||||
}
|
||||
|
||||
var toolsEnUs = map[string]mcp.Tool{
|
||||
ToolServiceList: mcp.NewTool(
|
||||
ToolServiceList,
|
||||
mcp.WithDescription("This tool is used to retrieve a list of registered services in APIPark. Each service includes its unique identifier (service ID), name, description, and a list of APIs it contains. It supports fuzzy searching by keyword for quick narrowing down of results. After obtaining a service ID, you can use the openapi_document tool to get the OpenAPI documentation for that service, which is necessary for invoking its APIs."),
|
||||
mcp.WithString("keyword", mcp.Description("Keyword for fuzzy search of services"))),
|
||||
ToolOpenAPIDocument: mcp.NewTool(
|
||||
ToolOpenAPIDocument,
|
||||
mcp.WithDescription("This tool is used to query the OpenAPI documentation of a specified service. The returned format supports both OpenAPI v3 and v2 standards. By entering the service ID, you can view detailed information about all APIs of that service, including definitions, parameter structures, request methods, etc., which prepares you for subsequent API calls."),
|
||||
mcp.WithString("service", mcp.Description("Unique identifier of the service to query"))),
|
||||
ToolInvokeAPI: mcp.NewTool(
|
||||
ToolInvokeAPI,
|
||||
mcp.WithDescription("This tool can directly send API requests. Before using this tool, you need to construct the required request parameters based on the OpenAPI documentation of the API, such as request path, method, query parameters, header information, body content, etc. No authentication information like Authorization header is required when using this tool."),
|
||||
mcp.WithString("path", mcp.Description("API request path"), mcp.Required()),
|
||||
mcp.WithString("method", mcp.Description("API request method, e.g., GET, POST, PUT"), mcp.Required()),
|
||||
mcp.WithString("content-type", mcp.Description("Content-Type of the request. Must be specified if method is POST, PUT, or PATCH")),
|
||||
mcp.WithObject("query", mcp.Description("Query parameters of the request, type map[string]string")),
|
||||
mcp.WithObject("header", mcp.Description("Header information of the request, type map[string]string")),
|
||||
mcp.WithString("body", mcp.Description("Body content of the request, usually in JSON string")),
|
||||
),
|
||||
}
|
||||
|
||||
var toolsJaJp = map[string]mcp.Tool{
|
||||
ToolServiceList: mcp.NewTool(
|
||||
ToolServiceList,
|
||||
mcp.WithDescription("このツールは、APIParkに登録されているサービスのリストを取得するために使用されます。各サービスには、ユニークな識別子(サービスID)、名前、説明、および含まれるAPIのリストが含まれています。キーワードによるあいまい検索をサポートしており、結果を迅速に絞り込むことができます。サービスIDを取得した後は、openapi_documentツールを使用してそのサービスのOpenAPIドキュメントを取得し、そのAPIを呼び出す準備をします。"),
|
||||
mcp.WithString("keyword", mcp.Description("サービスをあいまい検索するためのキーワード"))),
|
||||
ToolOpenAPIDocument: mcp.NewTool(
|
||||
ToolOpenAPIDocument,
|
||||
mcp.WithDescription("このツールは、指定されたサービスのOpenAPIドキュメントを照会するために使用されます。返される形式は、OpenAPI v3およびv2標準の両方をサポートしています。サービスIDを入力することで、そのサービスのすべてのAPIに関する詳細情報(定義、パラメータ構造、リクエスト方法など)を表示し、後続のAPI呼び出しの準備をします。"),
|
||||
mcp.WithString("service", mcp.Description("照会するサービスのユニークな識別子"))),
|
||||
ToolInvokeAPI: mcp.NewTool(
|
||||
ToolInvokeAPI,
|
||||
mcp.WithDescription("このツールは、APIリクエストを直接送信できます。このツールを使用する前に、APIのOpenAPIドキュメントに基づいて、必要なリクエストパラメータ(リクエストパス、メソッド、クエリパラメータ、ヘッダー情報、ボディコンテンツなど)を構築する必要があります。このツールを使用する際には、Authorizationヘッダーなどの認証情報は必要ありません。"),
|
||||
mcp.WithString("path", mcp.Description("APIのリクエストパス"), mcp.Required()),
|
||||
mcp.WithString("method", mcp.Description("APIのリクエストメソッド(例:GET、POST、PUT)"), mcp.Required()),
|
||||
mcp.WithString("content-type", mcp.Description("リクエストのContent-Type。メソッドがPOST、PUT、またはPATCHの場合は必須です")),
|
||||
mcp.WithObject("query", mcp.Description("リクエストのクエリパラメータ、タイプはmap[string]string")),
|
||||
mcp.WithObject("header", mcp.Description("リクエストのヘッダー、タイプはmap[string]string")),
|
||||
mcp.WithString("body", mcp.Description("リクエストのボディコンテンツ、通常はJSON文字列")),
|
||||
),
|
||||
}
|
||||
+16
-10
@@ -520,16 +520,21 @@ func (i *imlServiceController) createAIService(ctx *gin.Context, teamID string,
|
||||
modelId := ""
|
||||
modelCfg := ""
|
||||
modelType := "online"
|
||||
if input.Model != nil {
|
||||
modelId = *input.Model
|
||||
}
|
||||
if *input.Provider == ai_provider_local.ProviderLocal {
|
||||
modelType = "local"
|
||||
list, err := i.aiLocalModel.SimpleList(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if modelId == "" {
|
||||
list, err := i.aiLocalModel.SimpleList(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
return nil, fmt.Errorf("no local model")
|
||||
}
|
||||
modelId = list[0].Id
|
||||
}
|
||||
if len(list) == 0 {
|
||||
return nil, fmt.Errorf("no local model")
|
||||
}
|
||||
modelId = list[0].Id
|
||||
modelCfg = ai_provider_local.LocalConfig
|
||||
} else {
|
||||
pv, err := i.providerModule.Provider(ctx, *input.Provider)
|
||||
@@ -540,14 +545,15 @@ func (i *imlServiceController) createAIService(ctx *gin.Context, teamID string,
|
||||
if !has {
|
||||
return nil, fmt.Errorf("provider not found")
|
||||
}
|
||||
m, has := p.GetModel(pv.DefaultLLM)
|
||||
if modelId == "" {
|
||||
modelId = pv.DefaultLLM
|
||||
}
|
||||
m, has := p.GetModel(modelId)
|
||||
if !has {
|
||||
return nil, fmt.Errorf("model %s not found", pv.DefaultLLM)
|
||||
}
|
||||
//modelId = m.ID()
|
||||
modelId = m.Name()
|
||||
modelCfg = m.DefaultConfig()
|
||||
|
||||
}
|
||||
|
||||
var info *service_dto.Service
|
||||
|
||||
@@ -16,7 +16,7 @@ type IAPIKeyController interface {
|
||||
Search(ctx *gin.Context, keyword string) ([]*system_apikey_dto.Item, error)
|
||||
SimpleList(ctx *gin.Context) ([]*system_apikey_dto.SimpleItem, error)
|
||||
MyAPIKeys(ctx *gin.Context) ([]*system_apikey_dto.SimpleItem, error)
|
||||
MyAPIKeysByService(ctx *gin.Context, serviceId string) ([]*system_apikey_dto.AuthorizationItem, error)
|
||||
MyAPIKeysByService(ctx *gin.Context, serviceId string, appId string) ([]*system_apikey_dto.AuthorizationItem, error)
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -12,8 +12,14 @@ type imlAPIKeyController struct {
|
||||
apikeyModule system_apikey.IAPIKeyModule `autowired:""`
|
||||
}
|
||||
|
||||
func (i *imlAPIKeyController) MyAPIKeysByService(ctx *gin.Context, serviceId string) ([]*system_apikey_dto.AuthorizationItem, error) {
|
||||
return i.apikeyModule.MyAPIKeysByService(ctx, serviceId)
|
||||
func (i *imlAPIKeyController) MyAPIKeysByService(ctx *gin.Context, serviceId string, appId string) ([]*system_apikey_dto.AuthorizationItem, error) {
|
||||
if serviceId != "" {
|
||||
return i.apikeyModule.MyAPIKeysByService(ctx, serviceId)
|
||||
}
|
||||
if appId != "" {
|
||||
return i.apikeyModule.MyAPIKeysByApp(ctx, appId)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (i *imlAPIKeyController) MyAPIKeys(ctx *gin.Context) ([]*system_apikey_dto.SimpleItem, error) {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"description": "",
|
||||
"scripts": {
|
||||
"test": "jest",
|
||||
"build": "set NODE_OPTIONS=--max-old-space-size=8192 && lerna run build --scope=core --stream --verbose ",
|
||||
"build": "set NODE_OPTIONS=--max-old-space-size=4096 && lerna run build --scope=core --stream --verbose ",
|
||||
"serve": "lerna run preview --parallel",
|
||||
"serve:remotes": "lerna run serve --scope=remote --parallel",
|
||||
"dev": "lerna run dev --scope=core --stream",
|
||||
|
||||
@@ -19,7 +19,7 @@ export type MemberTableListItem = {
|
||||
enable:boolean
|
||||
departmentId:string
|
||||
roles:EntityItem[]
|
||||
from: string
|
||||
form: string
|
||||
};
|
||||
|
||||
export type AddToDepartmentProps = {
|
||||
@@ -41,7 +41,7 @@ export type MemberDropdownModalFieldType = {
|
||||
|
||||
export type MemberDropdownModalProps = {
|
||||
type:'addDep'|'addChild'|'addMember'|'editMember'|'rename'
|
||||
entity?:(MemberTableListItem & {departmentIds:string[]}) | ({id?:string, departmentIds?:string[],name?:string,from?:string})
|
||||
entity?:(MemberTableListItem & {departmentIds:string[]}) | ({id?:string, departmentIds?:string[],name?:string,form?:string})
|
||||
selectedMemberGroupId?:string
|
||||
}
|
||||
|
||||
|
||||
@@ -93,11 +93,6 @@ const Login: FC = () => {
|
||||
const code = query.get('code')
|
||||
if (code) {
|
||||
feishuLogin(code)
|
||||
setSpinning(false)
|
||||
return
|
||||
}
|
||||
if (isInFeishuClient() && feishu) {
|
||||
openFeishuLogin(feishu.config.client_id)
|
||||
}
|
||||
setSpinning(false)
|
||||
}
|
||||
@@ -166,25 +161,10 @@ const Login: FC = () => {
|
||||
fetchLogin({ username: 'guest', password: '12345678' })
|
||||
}
|
||||
|
||||
const isInFeishuClient = () => {
|
||||
// 方法1:检查User-Agent
|
||||
const ua = navigator.userAgent.toLowerCase();
|
||||
const isLark = ua.includes('lark') || ua.includes('feishu');
|
||||
|
||||
// 方法2:检查全局对象
|
||||
const hasSDK = typeof window.h5sdk !== 'undefined' || typeof window.tt !== 'undefined';
|
||||
|
||||
// 方法3:检查URL参数
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const hasFeishuParams = params.has('from') || params.has('required_launch_ability');
|
||||
|
||||
return isLark || hasSDK || hasFeishuParams;
|
||||
}
|
||||
|
||||
// 打开飞书授权页面
|
||||
const openFeishuLogin = (id?: string) => {
|
||||
const openFeishuLogin = () => {
|
||||
const href = window.location.origin + window.location.pathname
|
||||
const authUrl = `https://accounts.feishu.cn/open-apis/authen/v1/authorize?client_id=${id || feishuAppId}&redirect_uri=${href}`
|
||||
const authUrl = `https://accounts.feishu.cn/open-apis/authen/v1/authorize?client_id=${feishuAppId}&redirect_uri=${href}`
|
||||
localStorage.setItem('feishuCallbackUrl', href)
|
||||
window.location.href = authUrl
|
||||
}
|
||||
@@ -356,7 +336,7 @@ const Login: FC = () => {
|
||||
loading={loading}
|
||||
className="h-[40px] w-full inline-flex justify-center items-center"
|
||||
type="default"
|
||||
onClick={() => openFeishuLogin(feishuAppId)}
|
||||
onClick={openFeishuLogin}
|
||||
>
|
||||
<img className="h-[30px]" src={FeishuLogo} />
|
||||
{$t('飞书授权登录')}
|
||||
|
||||
@@ -14,7 +14,8 @@ export const MemberDropdownModal = forwardRef<MemberDropdownModalHandle,MemberDr
|
||||
const {fetchData} = useFetch()
|
||||
const [departmentList, setDepartmentList] = useState<DepartmentListItem[]>([])
|
||||
const { state } = useGlobalContext()
|
||||
const [disableEditMemberData] = useState<boolean>(entity?.from === 'feishu')
|
||||
const [disableEditMemberData] = useState<boolean>(entity?.form !== 'self-build')
|
||||
|
||||
const save:()=>Promise<boolean | string> = ()=>{
|
||||
let url:string
|
||||
let method:string
|
||||
|
||||
@@ -95,15 +95,14 @@ const AddToDepartment = forwardRef<AddToDepartmentHandle, AddToDepartmentProps>(
|
||||
treeData?.map((x: DataNode) => ({
|
||||
...x,
|
||||
name: $t((x as unknown as { name: string }).name),
|
||||
checkable: false, // 根节点不可选中
|
||||
children: x.children?.map(y => ({ ...y, checkable: true })) // 子节点可以选中
|
||||
checkable: false,
|
||||
children: x.children?.map(y => ({ ...y, checkable: false }))
|
||||
})),
|
||||
[state.language, treeData]
|
||||
)
|
||||
|
||||
const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
|
||||
const selectedIds = Array.isArray(checkedKeys) ? checkedKeys : checkedKeys.checked || []
|
||||
setSelectedKeys(selectedIds)
|
||||
const onCheck: TreeProps['onCheck'] = (checkedKeys: string[]) => {
|
||||
setSelectedKeys(checkedKeys.checked)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -154,12 +153,11 @@ const MemberList = () => {
|
||||
const [tableHttpReload, setTableHttpReload] = useState(true)
|
||||
const [tableListDataSource, setTableListDataSource] = useState<MemberTableListItem[]>([])
|
||||
const pageListRef = useRef<ActionType>(null)
|
||||
const { topGroupId, selectedDepartmentIds, refreshGroup, refreshTableCount } = useOutletContext<{
|
||||
const { topGroupId, selectedDepartmentIds, refreshGroup } = useOutletContext<{
|
||||
topGroupId: string
|
||||
departmentList: DepartmentListItem[]
|
||||
selectedDepartmentIds: string[]
|
||||
refreshGroup: () => void
|
||||
refreshTableCount: number
|
||||
}>()
|
||||
const AddMemberRef = useRef<MemberDropdownModalHandle>(null)
|
||||
const EditMemberRef = useRef<MemberDropdownModalHandle>(null)
|
||||
@@ -398,7 +396,7 @@ const MemberList = () => {
|
||||
width: 600,
|
||||
okText: $t('确认'),
|
||||
okButtonProps: {
|
||||
disabled: isActionAllowed(type) || (type === 'editMember' && entity?.from === 'feishu')
|
||||
disabled: isActionAllowed(type) || (type === 'editMember' && entity?.form !== 'self-build')
|
||||
},
|
||||
cancelText: $t('取消'),
|
||||
closable: true,
|
||||
@@ -417,13 +415,6 @@ const MemberList = () => {
|
||||
getDepartmentList()
|
||||
}, [])
|
||||
|
||||
// 监听外部刷新触发器
|
||||
useEffect(() => {
|
||||
if (refreshTableCount > 0) {
|
||||
manualReloadTable()
|
||||
}
|
||||
}, [refreshTableCount])
|
||||
|
||||
const getDepartmentList = async () => {
|
||||
setDepartmentValueEnum([])
|
||||
const { code, data, msg } = await fetchData<BasicResponse<{ department: DepartmentListItem }>>(
|
||||
|
||||
@@ -36,11 +36,6 @@ const MemberPage = ()=>{
|
||||
const [selectedDepartmentId, setSelectedDepartmentId] = useState<string>('-1')
|
||||
const {accessData,state} = useGlobalContext()
|
||||
const [refreshMemberCount, setRefreshMemberCount] = useState<number>(0)
|
||||
const [refreshTableCount, setRefreshTableCount] = useState<number>(0)
|
||||
|
||||
const refreshMemberTable = () => {
|
||||
setRefreshTableCount(prev => prev + 1)
|
||||
}
|
||||
const onSearchWordChange = (e:string)=>{
|
||||
setSearchWord(e || '')
|
||||
}
|
||||
@@ -95,7 +90,7 @@ const MemberPage = ()=>{
|
||||
case 'addChild':
|
||||
return AddChildRef.current?.save().then((res)=>{if(res === true)getDepartmentList()})
|
||||
case 'addMember':
|
||||
return AddMemberRef.current?.save().then((res)=>{if(res === true){getDepartmentList();setRefreshMemberCount(pre=>pre+1);refreshMemberTable()}})
|
||||
return AddMemberRef.current?.save().then((res)=>{if(res === true){getDepartmentList();setRefreshMemberCount(pre=>pre+1)}})
|
||||
case 'rename':
|
||||
return RenameRef.current?.save().then((res)=>{if(res === true)getDepartmentList()})
|
||||
case 'delete':
|
||||
@@ -267,7 +262,7 @@ const MemberPage = ()=>{
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 p-btnbase pr-PAGE_INSIDE_X overflow-x-hidden">
|
||||
<Outlet context={{refreshMemberCount, selectedDepartmentIds,refreshGroup:()=>getDepartmentList(), refreshTableCount}}/>
|
||||
<Outlet context={{refreshMemberCount, selectedDepartmentIds,refreshGroup:()=>getDepartmentList()}}/>
|
||||
</div>
|
||||
</div>
|
||||
</InsidePage>);
|
||||
|
||||
@@ -20,7 +20,7 @@ export default function ManagementInsidePage() {
|
||||
const { message } = App.useApp()
|
||||
const { fetchData } = useFetch()
|
||||
const { setBreadcrumb } = useBreadcrumb()
|
||||
const [activeMenu, setActiveMenu] = useState<string>('authorization')
|
||||
const [activeMenu, setActiveMenu] = useState<string>('service')
|
||||
const { appId, teamId } = useParams<RouterParams>()
|
||||
const navigateTo = useNavigate()
|
||||
const currentUrl = useLocation().pathname
|
||||
@@ -56,7 +56,7 @@ export default function ManagementInsidePage() {
|
||||
}, [accessData, accessInit, TENANT_MANAGEMENT_APP_MENU])
|
||||
|
||||
useEffect(() => {
|
||||
setActiveMenu(currentUrl.split('/').pop() || 'authorization')
|
||||
setActiveMenu(currentUrl.split('/').pop() || 'service')
|
||||
}, [currentUrl])
|
||||
|
||||
const onMenuClick: MenuProps['onClick'] = (node) => {
|
||||
|
||||
@@ -336,7 +336,7 @@ export default function ServiceHubManagement() {
|
||||
setTableSearchWord={setTableSearchWord}
|
||||
editApp={(row: ServiceHubAppListItem) => {
|
||||
setAppName(row.name)
|
||||
navigateTo(`/consumer/${row.team.id}/inside/${row.id}/authorization`)
|
||||
navigateTo(`/consumer/${row.team.id}/inside/${row.id}/service`)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package auth
|
||||
|
||||
func init() {
|
||||
b := NewAKSK()
|
||||
Register(b.Name(), b)
|
||||
}
|
||||
|
||||
func NewAKSK() *AKSK {
|
||||
return &AKSK{}
|
||||
}
|
||||
|
||||
type AKSK struct {
|
||||
}
|
||||
|
||||
func (a *AKSK) Name() string {
|
||||
return "aksk"
|
||||
}
|
||||
|
||||
func (a *AKSK) ToPattern(cfg map[string]interface{}) interface{} {
|
||||
result := make(map[string]interface{})
|
||||
result["ak"] = cfg["ak"]
|
||||
result["sk"] = cfg["sk"]
|
||||
return result
|
||||
}
|
||||
|
||||
func (a *AKSK) ToConfig(cfg map[string]interface{}) interface{} {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package auth
|
||||
|
||||
func init() {
|
||||
b := NewJWT()
|
||||
Register(b.Name(), b)
|
||||
}
|
||||
|
||||
func NewJWT() *JWT {
|
||||
return &JWT{}
|
||||
}
|
||||
|
||||
type JWT struct {
|
||||
}
|
||||
|
||||
func (J *JWT) Name() string {
|
||||
return "jwt"
|
||||
}
|
||||
|
||||
func (J *JWT) ToPattern(cfg map[string]interface{}) interface{} {
|
||||
result := make(map[string]interface{})
|
||||
result["username"] = cfg["user"]
|
||||
return result
|
||||
}
|
||||
|
||||
func (J *JWT) ToConfig(cfg map[string]interface{}) interface{} {
|
||||
result := make(map[string]interface{})
|
||||
result["iss"] = cfg["iss"]
|
||||
result["algorithm"] = cfg["algorithm"]
|
||||
result["secret"] = cfg["secret"]
|
||||
result["rsa_public_key"] = cfg["publicKey"]
|
||||
result["path"] = cfg["userPath"]
|
||||
result["claims_to_verify"] = cfg["claimsToVerify"]
|
||||
result["signature_is_base_64"] = cfg["signatureIsBase64"]
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package auth
|
||||
|
||||
func init() {
|
||||
b := NewOAuth2()
|
||||
Register(b.Name(), b)
|
||||
}
|
||||
|
||||
func NewOAuth2() *OAuth2 {
|
||||
return &OAuth2{}
|
||||
}
|
||||
|
||||
type OAuth2 struct {
|
||||
}
|
||||
|
||||
func (o *OAuth2) Name() string {
|
||||
return "oauth2"
|
||||
}
|
||||
func (o *OAuth2) ToPattern(cfg map[string]interface{}) interface{} {
|
||||
result := make(map[string]interface{})
|
||||
result["client_id"] = cfg["client_id"]
|
||||
result["client_secret"] = cfg["client_secret"]
|
||||
result["client_type"] = cfg["client_type"]
|
||||
result["hash_secret"] = cfg["hash_secret"]
|
||||
result["redirect_urls"] = cfg["redirect_urls"]
|
||||
return result
|
||||
}
|
||||
func (o *OAuth2) ToConfig(cfg map[string]interface{}) interface{} {
|
||||
return nil
|
||||
}
|
||||
@@ -5,7 +5,7 @@ go 1.23.4
|
||||
toolchain go1.23.6
|
||||
|
||||
require (
|
||||
github.com/eolinker/ap-account v1.0.15
|
||||
github.com/eolinker/ap-account v1.0.18
|
||||
github.com/eolinker/eosc v0.18.3
|
||||
github.com/eolinker/go-common v1.1.7
|
||||
github.com/gabriel-vasile/mimetype v1.4.4
|
||||
@@ -15,7 +15,7 @@ require (
|
||||
github.com/go-sql-driver/mysql v1.7.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/influxdata/influxdb-client-go/v2 v2.14.0
|
||||
github.com/mark3labs/mcp-go v0.33.0
|
||||
github.com/mark3labs/mcp-go v0.42.0-beta.3
|
||||
github.com/mitchellh/mapstructure v1.5.0
|
||||
github.com/nsqio/go-nsq v1.1.0
|
||||
github.com/ollama/ollama v0.5.8
|
||||
@@ -27,6 +27,8 @@ require (
|
||||
|
||||
require (
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/buger/jsonparser v1.1.1 // indirect
|
||||
github.com/bytedance/sonic v1.11.6 // indirect
|
||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
@@ -46,6 +48,7 @@ require (
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/gorilla/websocket v1.4.2 // indirect
|
||||
github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839 // indirect
|
||||
github.com/invopop/jsonschema v0.13.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
@@ -67,6 +70,7 @@ require (
|
||||
github.com/spf13/cast v1.7.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.5.13 // indirect
|
||||
go.uber.org/atomic v1.7.0 // indirect
|
||||
@@ -87,6 +91,4 @@ require (
|
||||
//)
|
||||
|
||||
//replace github.com/eolinker/ap-account => ../../eolinker/ap-account
|
||||
|
||||
//
|
||||
//replace github.com/eolinker/go-common => ../../eolinker/go-common
|
||||
|
||||
@@ -2,6 +2,8 @@ github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2
|
||||
github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk=
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ=
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
|
||||
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
||||
github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w=
|
||||
@@ -9,6 +11,8 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
|
||||
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
@@ -28,8 +32,8 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
|
||||
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
|
||||
github.com/eolinker/ap-account v1.0.15 h1:n6DJeL6RHZ8eLlZUcY2U3H4d/GPaA5oelAx3R0E6yL8=
|
||||
github.com/eolinker/ap-account v1.0.15/go.mod h1:zm/Ivs6waJ/M/nEszhpPmM6g50y/MKO+5eABFAdeD0g=
|
||||
github.com/eolinker/ap-account v1.0.18 h1:YgDHoUmAdofPmaGhOQx+vj3+uhsv486kD3KLU/JKmBs=
|
||||
github.com/eolinker/ap-account v1.0.18/go.mod h1:zm/Ivs6waJ/M/nEszhpPmM6g50y/MKO+5eABFAdeD0g=
|
||||
github.com/eolinker/eosc v0.18.3 h1:3IK5HkAPnJRfLbQ0FR7kWsZr6Y/OiqqGazvN1q2BL5A=
|
||||
github.com/eolinker/eosc v0.18.3/go.mod h1:O9PQQXFCpB6fjHf+oFt/LN6EOAv779ItbMixMKCfTfk=
|
||||
github.com/eolinker/go-common v1.1.7 h1:bi7wDmlCYQGjS3k8Bz/o+Mo9aMJAzmPsBLXWurxPfwk=
|
||||
@@ -80,6 +84,8 @@ github.com/influxdata/influxdb-client-go/v2 v2.14.0 h1:AjbBfJuq+QoaXNcrova8smSjw
|
||||
github.com/influxdata/influxdb-client-go/v2 v2.14.0/go.mod h1:Ahpm3QXKMJslpXl3IftVLVezreAUtBOTZssDrjZEFHI=
|
||||
github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839 h1:W9WBk7wlPfJLvMCdtV4zPulc4uCPrlywQOmbFOhgQNU=
|
||||
github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839/go.mod h1:xaLFMmpvUxqXtVkUJfg9QmT88cDaCJ3ZKgdZ78oO8Qo=
|
||||
github.com/invopop/jsonschema v0.13.0 h1:KvpoAJWEjR3uD9Kbm2HWJmqsEaHt8lBUpd0qHcIi21E=
|
||||
github.com/invopop/jsonschema v0.13.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
@@ -101,8 +107,8 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mark3labs/mcp-go v0.33.0 h1:naxhjnTIs/tyPZmWUZFuG0lDmdA6sUyYGGf3gsHvTCc=
|
||||
github.com/mark3labs/mcp-go v0.33.0/go.mod h1:rXqOudj/djTORU/ThxYx8fqEVj/5pvTuuebQ2RC7uk4=
|
||||
github.com/mark3labs/mcp-go v0.42.0-beta.3 h1:nmOg1HFgSOgy0bZkAQ+E6qVpPMPmE8hIkM0BO94Ks9k=
|
||||
github.com/mark3labs/mcp-go v0.42.0-beta.3/go.mod h1:YnJfOL382MIWDx1kMY+2zsRHU/q78dBg9aFb8W6Thdw=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
@@ -159,6 +165,8 @@ github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65E
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/urfave/cli v1.22.16 h1:MH0k6uJxdwdeWQTwhSO42Pwr4YLrNLwBtg1MRgTqPdQ=
|
||||
github.com/urfave/cli v1.22.16/go.mod h1:EeJR6BKodywf4zciqrdw6hpCPk68JO9z5LazXZMn5Po=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.5.13 h1:RVZSAnWWWiI5IrYAXjQorajncORbS0zI48LQlE2kQWg=
|
||||
|
||||
@@ -4,6 +4,7 @@ package main
|
||||
import (
|
||||
_ "github.com/APIParkLab/APIPark/frontend"
|
||||
_ "github.com/APIParkLab/APIPark/gateway/apinto"
|
||||
_ "github.com/APIParkLab/APIPark/login_driver/feishu"
|
||||
_ "github.com/APIParkLab/APIPark/plugins/core"
|
||||
_ "github.com/APIParkLab/APIPark/plugins/openapi"
|
||||
_ "github.com/APIParkLab/APIPark/plugins/permit"
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package feishu
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
client = http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
)
|
||||
|
||||
func SendRequest[T any](uri string, method string, header http.Header, query url.Values, body []byte) (*T, error) {
|
||||
if uri == "" {
|
||||
return nil, fmt.Errorf("invalid URL")
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(method, uri, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if query != nil {
|
||||
req.URL.RawQuery = query.Encode()
|
||||
}
|
||||
|
||||
if header != nil {
|
||||
req.Header = header
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := new(T)
|
||||
err = json.Unmarshal(respBody, result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("status code error: %d, response: %s", resp.StatusCode, respBody)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package feishu
|
||||
|
||||
type UserTokenResponse struct {
|
||||
Code int `json:"code"`
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
RefreshTokenExpiresIn int `json:"refresh_token_expires_in"`
|
||||
TokenType string `json:"token_type"`
|
||||
Scope string `json:"scope"`
|
||||
Error string `json:"error"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
|
||||
type UserInfoResponse struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data UserInfo `json:"data"`
|
||||
}
|
||||
|
||||
type UserInfo struct {
|
||||
Name string `json:"name"`
|
||||
OpenID string `json:"open_id"`
|
||||
UnionId string `json:"union_id"`
|
||||
Email string `json:"email"`
|
||||
Mobile string `json:"mobile"`
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package feishu
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/eolinker/go-common/autowire"
|
||||
|
||||
"github.com/eolinker/ap-account/service/role"
|
||||
"github.com/eolinker/ap-account/service/user"
|
||||
|
||||
"github.com/eolinker/go-common/utils"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/eolinker/ap-account/service/account"
|
||||
|
||||
"github.com/eolinker/ap-account/auth_driver"
|
||||
)
|
||||
|
||||
const (
|
||||
name = "feishu"
|
||||
title = "飞书"
|
||||
getTokenUri = "https://open.feishu.cn/open-apis/authen/v2/oauth/token"
|
||||
getUserInfoUri = "https://open.feishu.cn/open-apis/authen/v1/user_info"
|
||||
)
|
||||
|
||||
var _ auth_driver.IDriver = (*Driver)(nil)
|
||||
|
||||
func init() {
|
||||
d := &Driver{}
|
||||
|
||||
auth_driver.Register(name, d)
|
||||
}
|
||||
|
||||
type Driver struct {
|
||||
isInit bool
|
||||
accountService account.IAccountService `autowired:""`
|
||||
userService user.IUserService `autowired:""`
|
||||
roleService role.IRoleService `autowired:""`
|
||||
roleMemberService role.IRoleMemberService `autowired:""`
|
||||
}
|
||||
|
||||
func (d *Driver) Init() {
|
||||
if d.isInit {
|
||||
return
|
||||
}
|
||||
autowire.Autowired(&d.accountService)
|
||||
autowire.Autowired(&d.userService)
|
||||
autowire.Autowired(&d.roleService)
|
||||
autowire.Autowired(&d.roleMemberService)
|
||||
d.isInit = true
|
||||
}
|
||||
|
||||
func (d *Driver) FilterConfig(config map[string]string) {
|
||||
delete(config, "client_secret")
|
||||
}
|
||||
|
||||
func (d *Driver) Name() string {
|
||||
return name
|
||||
}
|
||||
|
||||
func (d *Driver) Title() string {
|
||||
return title
|
||||
}
|
||||
|
||||
func (d *Driver) ThirdLogin(ctx context.Context, args map[string]string) (string, error) {
|
||||
code, ok := args["code"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("missing code parameter")
|
||||
}
|
||||
clientId, ok := args["client_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("missing client_id parameter")
|
||||
}
|
||||
clientSecret, ok := args["client_secret"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("missing client_secret parameter")
|
||||
}
|
||||
redirectUri, ok := args["redirect_uri"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("missing redirect_uri parameter")
|
||||
}
|
||||
u, err := url.Parse(redirectUri)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid redirect_uri parameter")
|
||||
}
|
||||
query := u.Query()
|
||||
query.Del("code")
|
||||
redirectUri = fmt.Sprintf("%s://%s%s", u.Scheme, u.Host, u.Path)
|
||||
if len(query) > 0 {
|
||||
redirectUri = fmt.Sprintf("%s?%s", redirectUri, query.Encode())
|
||||
}
|
||||
tokenResp, err := getUserToken(code, redirectUri, clientId, clientSecret)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
userInfoResp, err := getUserInfo(tokenResp.TokenType, tokenResp.AccessToken)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
userId := userInfoResp.Data.UnionId
|
||||
username := userInfoResp.Data.Name
|
||||
email := userInfoResp.Data.Email
|
||||
mobile := userInfoResp.Data.Mobile
|
||||
info, err := d.accountService.GetIdentifier(ctx, name, userId)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return "", err
|
||||
}
|
||||
uId := uuid.NewString()
|
||||
|
||||
err = d.accountService.Save(ctx, name, uId, userId, utils.Md5(fmt.Sprintf("%s%s", uId, userId)))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, err = d.userService.Create(ctx, uId, username, email, mobile, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
r, err := d.roleService.GetDefaultRole(ctx, role.SystemTarget())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
err = d.roleMemberService.Add(ctx, &role.AddMember{
|
||||
Role: r.Id,
|
||||
User: uId,
|
||||
Target: role.SystemTarget(),
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return uId, nil
|
||||
}
|
||||
_, err = d.userService.Update(ctx, info.Uid, &username, &email, &mobile)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return info.Uid, nil
|
||||
}
|
||||
|
||||
func getUserToken(code string, redirectUri, clientId string, clientSecret string) (*UserTokenResponse, error) {
|
||||
headers := http.Header{}
|
||||
headers.Set("Content-Type", "application/json")
|
||||
//body := url.Values{}
|
||||
//body.Set("grant_type", "authorization_code")
|
||||
//body.Set("code", code)
|
||||
//body.Set("client_id", clientId)
|
||||
//body.Set("client_secret", clientSecret)
|
||||
//body.Set("redirect_uri", redirectUri)
|
||||
body := map[string]string{
|
||||
"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"client_id": clientId,
|
||||
"client_secret": clientSecret,
|
||||
"redirect_uri": redirectUri,
|
||||
}
|
||||
bodyByte, _ := json.Marshal(body)
|
||||
resp, err := SendRequest[UserTokenResponse](getTokenUri, http.MethodPost, headers, nil, bodyByte)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get user token: %w", err)
|
||||
}
|
||||
if resp.Code != 0 {
|
||||
return nil, fmt.Errorf("failed to get user token: %s", resp.ErrorDescription)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func getUserInfo(tokenType string, token string) (*UserInfoResponse, error) {
|
||||
headers := http.Header{}
|
||||
headers.Set("Content-Type", "application/json")
|
||||
switch tokenType {
|
||||
case "Bearer":
|
||||
headers.Set("Authorization", fmt.Sprintf("Bearer %s", token))
|
||||
}
|
||||
resp, err := SendRequest[UserInfoResponse](getUserInfoUri, http.MethodGet, headers, nil, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get user info: %w", err)
|
||||
}
|
||||
if resp.Code != 0 {
|
||||
return nil, fmt.Errorf("failed to get user info: %s", resp.Msg)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (d *Driver) Delete(ctx context.Context, ids ...string) error {
|
||||
return d.accountService.OnRemoveUsers(ctx, ids...)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package mcp_server
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type TransportType string
|
||||
|
||||
const (
|
||||
TransportTypeStreamableHTTP TransportType = "streamable-http"
|
||||
TransportTypeSSE TransportType = "sse"
|
||||
)
|
||||
|
||||
func NewMCPConfig(typ TransportType, url string, headers map[string]string, alwaysAllow []string) *MCPConfig {
|
||||
return &MCPConfig{
|
||||
Type: typ,
|
||||
URL: url,
|
||||
Headers: headers,
|
||||
AlwaysAllow: alwaysAllow,
|
||||
}
|
||||
}
|
||||
|
||||
type MCPConfig struct {
|
||||
Type TransportType `json:"type"`
|
||||
URL string `json:"url"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
AlwaysAllow []string `json:"alwaysAllow,omitempty"`
|
||||
}
|
||||
|
||||
func (c *MCPConfig) ToString(name string) string {
|
||||
m := map[string]interface{}{
|
||||
"mcpServers": map[string]interface{}{
|
||||
name: c,
|
||||
},
|
||||
}
|
||||
data, _ := json.MarshalIndent(m, "", "\t")
|
||||
return string(data)
|
||||
}
|
||||
+25
-6
@@ -16,6 +16,11 @@ var (
|
||||
mcpServer = NewServer()
|
||||
ServiceBasePath = "mcp/service"
|
||||
GlobalBasePath = "mcp/global"
|
||||
AppBasePath = "mcp/app"
|
||||
|
||||
OpenGlobalMCPPath = "/openapi/v1/global/mcp"
|
||||
OpenAppMCPPath = "/openapi/v1/app/mcp"
|
||||
OpenServiceMCPPath = "/openapi/v1/service/mcp"
|
||||
)
|
||||
|
||||
func NewServer() *Server {
|
||||
@@ -60,7 +65,7 @@ func (s *Server) Set(id string, ser *server.MCPServer) {
|
||||
}
|
||||
tmp.handlers["api-sse"] = server.NewSSEServer(ser, server.WithStaticBasePath(fmt.Sprintf("/api/v1/%s/%s", ServiceBasePath, id)))
|
||||
tmp.handlers["openapi-sse"] = server.NewSSEServer(ser, server.WithStaticBasePath(fmt.Sprintf("/openapi/v1/%s/%s", ServiceBasePath, id)))
|
||||
tmp.handlers["openapi-stream"] = server.NewStreamableHTTPServer(ser, server.WithEndpointPath(fmt.Sprintf("/openapi/v1/%s/%s/mcp", ServiceBasePath, id)))
|
||||
tmp.handlers["openapi-stream"] = server.NewStreamableHTTPServer(ser, server.WithEndpointPath(OpenServiceMCPPath))
|
||||
s.servers[id] = tmp
|
||||
|
||||
}
|
||||
@@ -90,12 +95,23 @@ func (s *Server) Get(id string) (*Handler, bool) {
|
||||
}
|
||||
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
sid, err := genPath(r.URL.Path)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte(err.Error()))
|
||||
return
|
||||
var sid string
|
||||
if r.URL.Path == OpenServiceMCPPath {
|
||||
sid = r.Header.Get("X-Service-Id")
|
||||
if sid == "" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
id, err := genPath(r.URL.Path)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte(err.Error()))
|
||||
return
|
||||
}
|
||||
sid = id
|
||||
}
|
||||
|
||||
ser, has := s.Get(sid)
|
||||
if has {
|
||||
ser.ServeHTTP(w, r)
|
||||
@@ -155,6 +171,9 @@ func SetServerByOpenapi(sid, name, version, content string) error {
|
||||
toolOptions = append(toolOptions, mcp.WithDescription(a.Description))
|
||||
params := make(map[string]*Param)
|
||||
for _, v := range a.Params {
|
||||
if v.In == "header" && v.Name == "Authorization" {
|
||||
continue
|
||||
}
|
||||
params[v.Name] = NewParam(Position(v.In), v.Required, v.Description)
|
||||
options := make([]mcp.PropertyOption, 0, 2)
|
||||
if v.Required {
|
||||
|
||||
+15
-11
@@ -128,17 +128,19 @@ func (i *imlProviderModelModule) DeleteProviderModel(ctx *gin.Context, provider
|
||||
if err := i.providerModelService.Delete(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
err = i.syncGateway(ctx, cluster.DefaultClusterID, []*gateway.DynamicRelease{
|
||||
{
|
||||
BasicItem: &gateway.BasicItem{
|
||||
ID: fmt.Sprintf("%s#%s", provider, modelInfo.Name),
|
||||
Resource: "ai-model",
|
||||
if p.GetModelConfig().AccessConfigurationStatus {
|
||||
err = i.syncGateway(ctx, cluster.DefaultClusterID, []*gateway.DynamicRelease{
|
||||
{
|
||||
BasicItem: &gateway.BasicItem{
|
||||
ID: fmt.Sprintf("%s$%s", provider, modelInfo.Name),
|
||||
Resource: "ai-model",
|
||||
},
|
||||
Attr: nil,
|
||||
},
|
||||
Attr: nil,
|
||||
},
|
||||
}, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
p.RemoveModel(id)
|
||||
@@ -200,7 +202,9 @@ func (i *imlProviderModelModule) AddProviderModel(ctx *gin.Context, provider str
|
||||
}
|
||||
|
||||
func newModel(provider string, model string, config string) *gateway.DynamicRelease {
|
||||
|
||||
if config == "" {
|
||||
config = "{}"
|
||||
}
|
||||
return &gateway.DynamicRelease{
|
||||
BasicItem: &gateway.BasicItem{
|
||||
ID: fmt.Sprintf("%s$%s", provider, model),
|
||||
|
||||
@@ -6,11 +6,11 @@ import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
|
||||
auth_driver "github.com/APIParkLab/APIPark/module/application-authorization/auth-driver"
|
||||
|
||||
|
||||
"github.com/eolinker/go-common/utils"
|
||||
|
||||
|
||||
application_authorization_dto "github.com/APIParkLab/APIPark/module/application-authorization/dto"
|
||||
)
|
||||
|
||||
@@ -26,12 +26,12 @@ type Config struct {
|
||||
Iss string `json:"iss"`
|
||||
Algorithm string `json:"algorithm"`
|
||||
Secret string `json:"secret"`
|
||||
PublicKey string `json:"public_key"`
|
||||
PublicKey string `json:"publicKey"`
|
||||
User string `json:"user"`
|
||||
UserPath string `json:"user_path"`
|
||||
ClaimsToVerify []string `json:"claims_to_verify"`
|
||||
UserPath string `json:"userPath"`
|
||||
ClaimsToVerify []string `json:"claimsToVerify"`
|
||||
Label map[string]string `json:"label"`
|
||||
SignatureIsBase64 bool `json:"signature_is_base64"`
|
||||
SignatureIsBase64 bool `json:"signatureIsBase64"`
|
||||
}
|
||||
|
||||
func (cfg *Config) ID() string {
|
||||
@@ -46,7 +46,7 @@ func (cfg *Config) ID() string {
|
||||
for _, claim := range cfg.ClaimsToVerify {
|
||||
builder.WriteString(strings.TrimSpace(claim))
|
||||
}
|
||||
|
||||
|
||||
case "RS256", "RS384", "RS512", "ES256", "ES384", "ES512":
|
||||
builder.WriteString(strings.TrimSpace(cfg.Iss))
|
||||
builder.WriteString(strings.TrimSpace(cfg.PublicKey))
|
||||
@@ -81,7 +81,7 @@ func (cfg *Config) Valid() ([]byte, error) {
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupport algorithm")
|
||||
}
|
||||
|
||||
|
||||
//校验 校验字段
|
||||
for _, claim := range cfg.ClaimsToVerify {
|
||||
switch claim {
|
||||
@@ -94,7 +94,7 @@ func (cfg *Config) Valid() ([]byte, error) {
|
||||
}
|
||||
|
||||
func (cfg *Config) Detail() []application_authorization_dto.DetailItem {
|
||||
|
||||
|
||||
items := []application_authorization_dto.DetailItem{
|
||||
{Key: "Iss", Value: cfg.Iss},
|
||||
{Key: "签名算法", Value: cfg.Algorithm},
|
||||
@@ -102,7 +102,7 @@ func (cfg *Config) Detail() []application_authorization_dto.DetailItem {
|
||||
{Key: "用户名JsonPath", Value: cfg.UserPath},
|
||||
{Key: "校验字段", Value: strings.Join(cfg.ClaimsToVerify, ",")},
|
||||
}
|
||||
|
||||
|
||||
switch cfg.Algorithm {
|
||||
case "HS256", "HS384", "HS512":
|
||||
items = append(items, application_authorization_dto.DetailItem{Key: "Secret", Value: cfg.Secret})
|
||||
@@ -110,10 +110,10 @@ func (cfg *Config) Detail() []application_authorization_dto.DetailItem {
|
||||
if cfg.SignatureIsBase64 {
|
||||
base64 = "true"
|
||||
}
|
||||
items = append(items, application_authorization_dto.DetailItem{Key: "Secret", Value: base64})
|
||||
items = append(items, application_authorization_dto.DetailItem{Key: "SignatureIsBase64", Value: base64})
|
||||
default:
|
||||
items = append(items, application_authorization_dto.DetailItem{Key: "RSA公钥", Value: cfg.PublicKey})
|
||||
}
|
||||
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
@@ -33,7 +33,8 @@ type IAuthorizationModule interface {
|
||||
// Info 获取项目鉴权详情
|
||||
Info(ctx context.Context, appId string, aid string) (*application_authorization_dto.Authorization, error)
|
||||
|
||||
CheckAPIKeyAuthorization(ctx context.Context, serviceId string, apikey string) (bool, error)
|
||||
CheckAPIKeyAuthorizationByService(ctx context.Context, serviceId string, apikey string) (bool, error)
|
||||
CheckAPIKeyAuthorizationByApp(ctx context.Context, appId string, apikey string) (bool, error)
|
||||
|
||||
//ExportAll(ctx context.Context) ([]*application_authorization_dto.ExportAuthorization, error)
|
||||
}
|
||||
|
||||
@@ -44,7 +44,27 @@ type imlAuthorizationModule struct {
|
||||
transaction store.ITransaction `autowired:""`
|
||||
}
|
||||
|
||||
func (i *imlAuthorizationModule) CheckAPIKeyAuthorization(ctx context.Context, serviceId string, apikey string) (bool, error) {
|
||||
func (i *imlAuthorizationModule) CheckAPIKeyAuthorizationByApp(ctx context.Context, appId string, apikey string) (bool, error) {
|
||||
authorizations, err := i.authorizationService.ListByApp(ctx, appId)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, a := range authorizations {
|
||||
if a.Type != "apikey" {
|
||||
continue
|
||||
}
|
||||
cfg := make(map[string]interface{})
|
||||
if a.Config != "" {
|
||||
json.Unmarshal([]byte(a.Config), &cfg)
|
||||
}
|
||||
if cfg["apikey"] == apikey {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (i *imlAuthorizationModule) CheckAPIKeyAuthorizationByService(ctx context.Context, serviceId string, apikey string) (bool, error) {
|
||||
list, err := i.subscribeService.ListBySubscribeStatus(ctx, serviceId, subscribe.ApplyStatusSubscribe)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -199,19 +219,19 @@ func (i *imlAuthorizationModule) initGateway(ctx context.Context, partitionId st
|
||||
return clientDriver.Application().Online(ctx, applications...)
|
||||
}
|
||||
|
||||
func (i *imlAuthorizationModule) online(ctx context.Context, s *service.Service) error {
|
||||
clusters, err := i.clusterService.List(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(clusters) < 1 {
|
||||
return nil
|
||||
}
|
||||
func (i *imlAuthorizationModule) getApplicationRelease(ctx context.Context, s *service.Service) (*gateway.ApplicationRelease, error) {
|
||||
authorizations, err := i.authorizationService.ListByApp(ctx, s.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
app := &gateway.ApplicationRelease{
|
||||
if len(authorizations) < 1 {
|
||||
return &gateway.ApplicationRelease{
|
||||
BasicItem: &gateway.BasicItem{
|
||||
ID: s.Id,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
return &gateway.ApplicationRelease{
|
||||
BasicItem: &gateway.BasicItem{
|
||||
ID: s.Id,
|
||||
Description: s.Description,
|
||||
@@ -236,10 +256,40 @@ func (i *imlAuthorizationModule) online(ctx context.Context, s *service.Service)
|
||||
},
|
||||
}
|
||||
}),
|
||||
}, nil
|
||||
}
|
||||
func (i *imlAuthorizationModule) doOffline(ctx context.Context, clusterId string, app *gateway.ApplicationRelease) error {
|
||||
client, err := i.clusterService.GatewayClient(ctx, clusterId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = client.Close(ctx)
|
||||
}()
|
||||
return client.Application().Offline(ctx, app)
|
||||
}
|
||||
|
||||
func (i *imlAuthorizationModule) online(ctx context.Context, s *service.Service) error {
|
||||
clusters, err := i.clusterService.List(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(clusters) < 1 {
|
||||
return nil
|
||||
}
|
||||
release, err := i.getApplicationRelease(ctx, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range clusters {
|
||||
err := i.doOnline(ctx, c.Uuid, app)
|
||||
if len(release.Authorizations) < 1 {
|
||||
err = i.doOffline(ctx, c.Uuid, release)
|
||||
if err != nil {
|
||||
log.Warnf("service authorization offline for cluster[%s] %v", c.Name, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
err = i.doOnline(ctx, c.Uuid, release)
|
||||
if err != nil {
|
||||
log.Warnf("service authorization online for cluster[%s] %v", c.Name, err)
|
||||
}
|
||||
@@ -355,7 +405,7 @@ func (i *imlAuthorizationModule) EditAuthorization(ctx context.Context, appId st
|
||||
}
|
||||
|
||||
func (i *imlAuthorizationModule) DeleteAuthorization(ctx context.Context, pid string, aid string) error {
|
||||
_, err := i.serviceService.Get(ctx, pid)
|
||||
s, err := i.serviceService.Get(ctx, pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -365,35 +415,11 @@ func (i *imlAuthorizationModule) DeleteAuthorization(ctx context.Context, pid st
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
clusters, err := i.clusterService.List(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
app := &gateway.ApplicationRelease{
|
||||
BasicItem: &gateway.BasicItem{
|
||||
ID: pid,
|
||||
},
|
||||
}
|
||||
for _, c := range clusters {
|
||||
err := i.doOffline(ctx, c.Uuid, app)
|
||||
if err != nil {
|
||||
log.Warnf("service authorization offline for cluster[%s] %v", c.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
return i.online(ctx, s)
|
||||
})
|
||||
}
|
||||
func (i *imlAuthorizationModule) doOffline(ctx context.Context, clusterId string, app *gateway.ApplicationRelease) error {
|
||||
client, err := i.clusterService.GatewayClient(ctx, clusterId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = client.Close(ctx)
|
||||
}()
|
||||
return client.Application().Offline(ctx, app)
|
||||
|
||||
}
|
||||
func (i *imlAuthorizationModule) Authorizations(ctx context.Context, pid string) ([]*application_authorization_dto.AuthorizationItem, error) {
|
||||
_, err := i.serviceService.Get(ctx, pid)
|
||||
if err != nil {
|
||||
|
||||
+11
-13
@@ -9,10 +9,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
service_overview "github.com/APIParkLab/APIPark/service/service-overview"
|
||||
|
||||
mcp_server "github.com/APIParkLab/APIPark/mcp-server"
|
||||
|
||||
service_overview "github.com/APIParkLab/APIPark/service/service-overview"
|
||||
|
||||
"github.com/APIParkLab/APIPark/module/monitor/driver"
|
||||
|
||||
"github.com/APIParkLab/APIPark/service/monitor"
|
||||
@@ -326,15 +326,6 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal
|
||||
})
|
||||
}
|
||||
|
||||
var mcpDefaultConfig = `{
|
||||
"mcpServers": {
|
||||
"%s": {
|
||||
"url": "%s"
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*catalogue_dto.ServiceDetail, error) {
|
||||
// 获取服务的基本信息
|
||||
s, err := i.serviceService.Get(ctx, sid)
|
||||
@@ -400,8 +391,15 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca
|
||||
mcpAccessConfig := ""
|
||||
if s.EnableMCP {
|
||||
if sitePrefix != "" {
|
||||
mcpAccessAddress = fmt.Sprintf("%s/openapi/v1/%s/%s/sse?apikey={your_api_key}", strings.TrimSuffix(sitePrefix, "/"), mcp_server.ServiceBasePath, s.Id)
|
||||
mcpAccessConfig = fmt.Sprintf(mcpDefaultConfig, fmt.Sprintf("APIPark/%s", s.Name), mcpAccessAddress)
|
||||
mcpAccessConfig = mcp_server.NewMCPConfig(
|
||||
mcp_server.TransportTypeStreamableHTTP,
|
||||
fmt.Sprintf("%s/openapi/v1/service/mcp", strings.TrimSuffix(sitePrefix, "/")),
|
||||
map[string]string{
|
||||
"Authorization": "Bearer {your_api_key}",
|
||||
"X-Service-Id": s.Id,
|
||||
},
|
||||
nil,
|
||||
).ToString(fmt.Sprintf("APIPark/%s", s.Name))
|
||||
}
|
||||
}
|
||||
invokeMap, err := i.ProviderStatistics(ctx, time.Now().Add(-24*30*time.Hour), time.Now(), s.Id)
|
||||
|
||||
+77
-105
@@ -46,18 +46,43 @@ type imlMcpModule struct {
|
||||
releaseService release.IReleaseService `autowired:""`
|
||||
}
|
||||
|
||||
func (i *imlMcpModule) subscribeServiceIds(ctx context.Context, appId string) ([]string, error) {
|
||||
subscribes, err := i.subscriberService.SubscriptionsByApplication(ctx, appId)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get subscriber error: %w,app id is %s", err, appId)
|
||||
}
|
||||
serviceIds := utils.SliceToSlice(subscribes, func(s *subscribe.Subscribe) string {
|
||||
return s.Service
|
||||
}, func(s *subscribe.Subscribe) bool {
|
||||
return s.ApplyStatus == subscribe.ApplyStatusSubscribe
|
||||
})
|
||||
if len(serviceIds) == 0 {
|
||||
return nil, fmt.Errorf("no subscriber found,app id is %s", appId)
|
||||
}
|
||||
return serviceIds, nil
|
||||
}
|
||||
|
||||
func (i *imlMcpModule) Services(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
|
||||
keyword, _ := req.GetArguments()["keyword"].(string)
|
||||
list, err := i.serviceService.Search(ctx, keyword, map[string]interface{}{
|
||||
appId := utils.Label(ctx, "app")
|
||||
condition := map[string]interface{}{
|
||||
"as_server": true,
|
||||
}, "update_at desc")
|
||||
}
|
||||
if appId != "" {
|
||||
serviceIds, err := i.subscribeServiceIds(ctx, appId)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get subscriber service ids error: %w,app id is %s", err, appId)
|
||||
}
|
||||
condition["uuid"] = serviceIds
|
||||
}
|
||||
|
||||
list, err := i.serviceService.Search(ctx, keyword, condition, "update_at desc")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("search service error: %w", err)
|
||||
}
|
||||
if len(list) == 0 {
|
||||
list, err = i.serviceService.Search(ctx, "", map[string]interface{}{
|
||||
"as_server": true,
|
||||
}, "update_at desc")
|
||||
list, err = i.serviceService.Search(ctx, "", condition, "update_at desc")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("search service error: %w", err)
|
||||
}
|
||||
@@ -115,120 +140,61 @@ func (i *imlMcpModule) Services(ctx context.Context, req mcp.CallToolRequest) (*
|
||||
|
||||
}
|
||||
|
||||
//func (i *imlMcpModule) Apps(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
// keyword := req.GetArguments()["keyword"].(string)
|
||||
// condition := make(map[string]interface{})
|
||||
// condition["as_app"] = true
|
||||
// list, err := i.serviceService.Search(ctx, keyword, condition, "update_at desc")
|
||||
// if err != nil {
|
||||
// return nil, fmt.Errorf("search service error: %w", err)
|
||||
// }
|
||||
// if len(list) == 0 {
|
||||
// list, err = i.serviceService.Search(ctx, "", condition, "update_at desc")
|
||||
// if err != nil {
|
||||
// return nil, fmt.Errorf("search service error: %w", err)
|
||||
// }
|
||||
// }
|
||||
// data, _ := json.Marshal(utils.SliceToSlice(list, func(s *service.Service) *mcp_dto.App {
|
||||
// return &mcp_dto.App{
|
||||
// Id: s.Id,
|
||||
// Name: s.Name,
|
||||
// Description: s.Name,
|
||||
// CreateTime: s.CreateTime,
|
||||
// UpdateTime: s.UpdateTime,
|
||||
// }
|
||||
// }))
|
||||
// return mcp.NewToolResultText(string(data)), nil
|
||||
//}
|
||||
|
||||
func (i *imlMcpModule) APIs(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
serviceId, _ := req.GetArguments()["service"].(string)
|
||||
serviceIds := make([]string, 0, 1)
|
||||
if serviceId == "" {
|
||||
serviceIds = append(serviceIds, serviceId)
|
||||
return nil, fmt.Errorf("service id is empty")
|
||||
}
|
||||
serviceList, err := i.serviceService.ServiceList(ctx)
|
||||
s, err := i.serviceService.Get(ctx, serviceId)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get service list error: %w", err)
|
||||
return nil, fmt.Errorf("get service error: %w,service id is %s", err, serviceId)
|
||||
}
|
||||
appId := utils.Label(ctx, "app")
|
||||
if appId != "" {
|
||||
subscribers, err := i.subscriberService.ListByApplication(ctx, serviceId, appId)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get subscriber error: %w,app id is %s", err, appId)
|
||||
}
|
||||
if len(subscribers) < 1 || subscribers[0].ApplyStatus != subscribe.ApplyStatusSubscribe {
|
||||
return nil, fmt.Errorf("no subscriber found,app id is %s", appId)
|
||||
}
|
||||
}
|
||||
result := make([]*mcp_dto.ServiceAPI, 0, len(serviceList))
|
||||
|
||||
for _, s := range serviceList {
|
||||
serviceRelease, err := i.releaseService.GetRunning(ctx, s.Id)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("get service release error: %w,service id is %s", err, s.Id)
|
||||
}
|
||||
continue
|
||||
serviceRelease, err := i.releaseService.GetRunning(ctx, serviceId)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("get service release error: %w,service id is %s", err, s.Id)
|
||||
}
|
||||
_, _, apiDocRelease, _, _, err := i.releaseService.GetReleaseInfos(ctx, serviceRelease.UUID)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("get service release info error: %w,service id is %s", err, s.Id)
|
||||
}
|
||||
continue
|
||||
return nil, fmt.Errorf("no service found,service id is %s", serviceId)
|
||||
}
|
||||
_, _, apiDocRelease, _, _, err := i.releaseService.GetReleaseInfos(ctx, serviceRelease.UUID)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("get service release info error: %w,service id is %s", err, s.Id)
|
||||
}
|
||||
commit, err := i.apiDocService.GetDocCommit(ctx, apiDocRelease.Commit)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("get api doc release error: %w,service id is %s", err, s.Id)
|
||||
}
|
||||
continue
|
||||
return nil, fmt.Errorf("no service found,service id is %s", serviceId)
|
||||
}
|
||||
commit, err := i.apiDocService.GetDocCommit(ctx, apiDocRelease.Commit)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("get api doc release error: %w,service id is %s", err, s.Id)
|
||||
}
|
||||
T, err := openapi3Loader.LoadFromData([]byte(commit.Data.Content))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load openapi3 error: %w,service id is %s", err, s.Id)
|
||||
}
|
||||
result = append(result, &mcp_dto.ServiceAPI{
|
||||
ServiceID: s.Id,
|
||||
ServiceName: s.Name,
|
||||
APIDoc: T,
|
||||
})
|
||||
return nil, fmt.Errorf("no service found,service id is %s", serviceId)
|
||||
}
|
||||
T, err := openapi3Loader.LoadFromData([]byte(commit.Data.Content))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load openapi3 error: %w,service id is %s", err, s.Id)
|
||||
}
|
||||
|
||||
result := &mcp_dto.ServiceAPI{
|
||||
ServiceID: serviceId,
|
||||
ServiceName: s.Name,
|
||||
APIDoc: T,
|
||||
}
|
||||
data, _ := json.Marshal(result)
|
||||
return mcp.NewToolResultText(string(data)), nil
|
||||
}
|
||||
|
||||
//func (i *imlMcpModule) SubscriberAuthorizations(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
// serviceId, ok := req.GetArguments()["service"].(string)
|
||||
// if !ok {
|
||||
// return nil, fmt.Errorf("service id is required")
|
||||
// }
|
||||
// subscribes, err := i.subscriberService.Subscribers(ctx, serviceId, subscribe.ApplyStatusSubscribe)
|
||||
// if err != nil {
|
||||
// return nil, fmt.Errorf("get subscriber error: %w,service id is %s", err, serviceId)
|
||||
// }
|
||||
// appIds := utils.SliceToSlice(subscribes, func(s *subscribe.Subscribe) string {
|
||||
// return s.Application
|
||||
// })
|
||||
// if len(appIds) == 0 {
|
||||
// return nil, fmt.Errorf("no subscriber found,service id is %s", serviceId)
|
||||
// }
|
||||
// list, err := i.appAuthorizationService.ListByApp(ctx, appIds...)
|
||||
// if err != nil {
|
||||
// return nil, fmt.Errorf("get app authorization error: %w,app ids is %s", err, appIds)
|
||||
// }
|
||||
// result := utils.SliceToSlice(list, func(a *application_authorization.Authorization) *mcp_dto.AppAuthorization {
|
||||
// return &mcp_dto.AppAuthorization{
|
||||
// Id: a.UUID,
|
||||
// Name: a.Name,
|
||||
// position: a.position,
|
||||
// TokenName: a.TokenName,
|
||||
// Config: a.Config,
|
||||
// }
|
||||
// }, func(a *application_authorization.Authorization) bool {
|
||||
// if a.Type != "apikey" {
|
||||
// return false
|
||||
// }
|
||||
// if a.ExpireTime != 0 && a.ExpireTime < time.Now().Unix() {
|
||||
// return false
|
||||
// }
|
||||
// return true
|
||||
// })
|
||||
// data, _ := json.Marshal(result)
|
||||
// return mcp.NewToolResultText(string(data)), nil
|
||||
//}
|
||||
|
||||
var (
|
||||
client = &http.Client{}
|
||||
)
|
||||
@@ -309,8 +275,14 @@ func (i *imlMcpModule) Invoke(ctx context.Context, req mcp.CallToolRequest) (*mc
|
||||
request.Header = headerParam
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
apikey := utils.Label(ctx, "apikey")
|
||||
|
||||
if apikey != "" {
|
||||
request.Header.Set("Authorization", utils.Md5(apikey))
|
||||
appId := utils.Label(ctx, "app")
|
||||
if appId == "" {
|
||||
request.Header.Set("Authorization", utils.Md5(apikey))
|
||||
} else {
|
||||
request.Header.Set("Authorization", apikey)
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := client.Do(request)
|
||||
|
||||
@@ -12,13 +12,7 @@ import (
|
||||
type IMcpModule interface {
|
||||
// Services 获取服务列表
|
||||
Services(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)
|
||||
// Apps 获取应用列表
|
||||
//Apps(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)
|
||||
// APIs 获取API列表
|
||||
APIs(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)
|
||||
|
||||
// SubscriberAuthorizations 获取订阅者授权
|
||||
//SubscriberAuthorizations(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)
|
||||
Invoke(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)
|
||||
}
|
||||
|
||||
|
||||
+47
-34
@@ -185,6 +185,41 @@ func (i *imlPublishModule) getProjectRelease(ctx context.Context, projectID stri
|
||||
Id: projectID,
|
||||
Version: version,
|
||||
}
|
||||
upstreamProxyHeaders := make([]*gateway.ProxyHeader, 0)
|
||||
var upstreamRelease *gateway.UpstreamRelease
|
||||
if len(upstreamCommitIds) > 0 {
|
||||
upstreamCommits, err := i.upstreamService.ListCommit(ctx, upstreamCommitIds...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range upstreamCommits {
|
||||
upstreamRelease = &gateway.UpstreamRelease{
|
||||
BasicItem: &gateway.BasicItem{
|
||||
ID: c.Target,
|
||||
Version: version,
|
||||
MatchLabels: map[string]string{
|
||||
"serviceId": projectID,
|
||||
},
|
||||
},
|
||||
PassHost: c.Data.PassHost,
|
||||
Scheme: c.Data.Scheme,
|
||||
Balance: c.Data.Balance,
|
||||
Timeout: c.Data.Timeout,
|
||||
Nodes: utils.SliceToSlice(c.Data.Nodes, func(n *upstream.NodeConfig) string {
|
||||
return fmt.Sprintf("%s weight=%d", n.Address, n.Weight)
|
||||
}),
|
||||
}
|
||||
|
||||
upstreamProxyHeaders = utils.SliceToSlice(c.Data.ProxyHeaders, func(n *upstream.ProxyHeader) *gateway.ProxyHeader {
|
||||
return &gateway.ProxyHeader{
|
||||
Key: n.Key,
|
||||
Value: n.Value,
|
||||
Opt: n.OptType,
|
||||
}
|
||||
})
|
||||
}
|
||||
r.Upstream = upstreamRelease
|
||||
}
|
||||
apis := make([]*gateway.ApiRelease, 0, len(apiInfos))
|
||||
hasUpstream := len(upstreamCommitIds) > 0
|
||||
for _, a := range apiInfos {
|
||||
@@ -221,38 +256,15 @@ func (i *imlPublishModule) getProjectRelease(ctx context.Context, projectID stri
|
||||
Opt: h.OptType,
|
||||
}
|
||||
})
|
||||
apiInfo.ProxyHeaders = append(apiInfo.ProxyHeaders, upstreamProxyHeaders...)
|
||||
|
||||
apiInfo.Retry = proxy.Retry
|
||||
apiInfo.Timeout = proxy.Timeout
|
||||
}
|
||||
apis = append(apis, apiInfo)
|
||||
}
|
||||
r.Apis = apis
|
||||
var upstreamRelease *gateway.UpstreamRelease
|
||||
if len(upstreamCommitIds) > 0 {
|
||||
upstreamCommits, err := i.upstreamService.ListCommit(ctx, upstreamCommitIds...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range upstreamCommits {
|
||||
upstreamRelease = &gateway.UpstreamRelease{
|
||||
BasicItem: &gateway.BasicItem{
|
||||
ID: c.Target,
|
||||
Version: version,
|
||||
MatchLabels: map[string]string{
|
||||
"serviceId": projectID,
|
||||
},
|
||||
},
|
||||
PassHost: c.Data.PassHost,
|
||||
Scheme: c.Data.Scheme,
|
||||
Balance: c.Data.Balance,
|
||||
Timeout: c.Data.Timeout,
|
||||
Nodes: utils.SliceToSlice(c.Data.Nodes, func(n *upstream.NodeConfig) string {
|
||||
return fmt.Sprintf("%s weight=%d", n.Address, n.Weight)
|
||||
}),
|
||||
}
|
||||
}
|
||||
r.Upstream = upstreamRelease
|
||||
}
|
||||
|
||||
if len(strategyCommitIds) > 0 {
|
||||
strategyCommits, err := i.strategyService.ListStrategyCommit(ctx, strategyCommitIds...)
|
||||
if err != nil {
|
||||
@@ -603,21 +615,22 @@ func (i *imlPublishModule) Publish(ctx context.Context, serviceId string, id str
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.EnableMCP {
|
||||
err = i.updateMCPServer(ctx, serviceId, info.Name, flow.Version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
apidocCommit, err := i.apiDocService.LatestDocCommit(ctx, serviceId)
|
||||
|
||||
apiDocCommit, err := i.apiDocService.LatestDocCommit(ctx, serviceId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
isReleased := true
|
||||
i.serviceOverviewService.Update(ctx, serviceId, &service_overview.Update{
|
||||
ReleaseApiCount: &apidocCommit.Data.APICount,
|
||||
ReleaseApiCount: &apiDocCommit.Data.APICount,
|
||||
IsReleased: &isReleased,
|
||||
})
|
||||
if info.EnableMCP {
|
||||
err = mcp_server.SetServerByOpenapi(serviceId, info.Name, flow.Version, apiDocCommit.Data.Content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return i.publishService.SetStatus(ctx, serviceId, id, status)
|
||||
})
|
||||
|
||||
@@ -236,6 +236,10 @@ func (i *imlServiceModule) AILogs(ctx context.Context, serviceId string, start i
|
||||
return nil, 0, err
|
||||
}
|
||||
return utils.SliceToSlice(list, func(s *log_service.Item) *service_dto.AILogItem {
|
||||
var tokenPerSecond int64 = 0
|
||||
if s.ResponseTime > 0 {
|
||||
tokenPerSecond = s.TotalToken * 1000 / s.ResponseTime
|
||||
}
|
||||
item := &service_dto.AILogItem{
|
||||
Id: s.ID,
|
||||
API: auto.UUID(s.API),
|
||||
@@ -243,7 +247,7 @@ func (i *imlServiceModule) AILogs(ctx context.Context, serviceId string, start i
|
||||
LogTime: auto.TimeLabel(s.RecordTime),
|
||||
Ip: s.RemoteIP,
|
||||
Token: s.TotalToken,
|
||||
TokenPerSecond: s.TotalToken * 1000 / s.ResponseTime,
|
||||
TokenPerSecond: tokenPerSecond,
|
||||
Consumer: auto.UUID(s.Consumer),
|
||||
Provider: auto.UUID(s.AIProvider),
|
||||
Model: s.AIModel,
|
||||
|
||||
@@ -41,6 +41,46 @@ type imlAPIKeyModule struct {
|
||||
transaction store.ITransaction `autowired:""`
|
||||
}
|
||||
|
||||
func (i *imlAPIKeyModule) MyAPIKeysByApp(ctx context.Context, appId string) ([]*system_apikey_dto.AuthorizationItem, error) {
|
||||
appInfo, err := i.serviceService.Get(ctx, appId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
auths, err := i.applicationAuthorizationService.ListByApp(ctx, appId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make(map[string]*system_apikey_dto.AuthorizationItem)
|
||||
for _, a := range auths {
|
||||
if a.Type != "apikey" {
|
||||
continue
|
||||
}
|
||||
|
||||
m := make(map[string]string)
|
||||
json.Unmarshal([]byte(a.Config), &m)
|
||||
if m["apikey"] == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := result[appInfo.Id]; !ok {
|
||||
result[appInfo.Id] = &system_apikey_dto.AuthorizationItem{
|
||||
Id: appInfo.Id,
|
||||
Name: appInfo.Name,
|
||||
Apikeys: []system_apikey_dto.SimpleItem{},
|
||||
}
|
||||
}
|
||||
result[appInfo.Id].Apikeys = append(result[appInfo.Id].Apikeys, system_apikey_dto.SimpleItem{
|
||||
Id: a.UUID,
|
||||
Name: a.Name,
|
||||
Value: m["apikey"],
|
||||
Expired: a.ExpireTime,
|
||||
})
|
||||
|
||||
}
|
||||
return utils.MapToSlice(result, func(k string, t *system_apikey_dto.AuthorizationItem) *system_apikey_dto.AuthorizationItem {
|
||||
return t
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (i *imlAPIKeyModule) MyAPIKeysByService(ctx context.Context, serviceId string) ([]*system_apikey_dto.AuthorizationItem, error) {
|
||||
list, err := i.subscribeService.ListBySubscribeStatus(ctx, serviceId, subscribe.ApplyStatusSubscribe)
|
||||
if err != nil {
|
||||
|
||||
@@ -19,6 +19,7 @@ type IAPIKeyModule interface {
|
||||
SimpleList(ctx context.Context) ([]*system_apikey_dto.SimpleItem, error)
|
||||
MyAPIKeys(ctx context.Context) ([]*system_apikey_dto.SimpleItem, error)
|
||||
MyAPIKeysByService(ctx context.Context, serviceId string) ([]*system_apikey_dto.AuthorizationItem, error)
|
||||
MyAPIKeysByApp(ctx context.Context, appId string) ([]*system_apikey_dto.AuthorizationItem, error)
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -15,15 +15,26 @@ func (p *plugin) mcpAPIs() []pm3.Api {
|
||||
serviceMessagePath := fmt.Sprintf("/api/v1/%s/:serviceId/message", mcp_server.ServiceBasePath)
|
||||
globalSSEPath := fmt.Sprintf("/api/v1/%s/sse", mcp_server.GlobalBasePath)
|
||||
globalMessagePath := fmt.Sprintf("/api/v1/%s/message", mcp_server.GlobalBasePath)
|
||||
appSSEPath := fmt.Sprintf("/api/v1/%s/sse", mcp_server.AppBasePath)
|
||||
appMessagePath := fmt.Sprintf("/api/v1/%s/message", mcp_server.AppBasePath)
|
||||
globalMcpPath := fmt.Sprintf("/api/v1/%s/mcp", mcp_server.GlobalBasePath)
|
||||
appMcpPath := fmt.Sprintf("/api/v1/%s/mcp", mcp_server.AppBasePath)
|
||||
ignore.IgnorePath("login", http.MethodGet, serviceSSEPath)
|
||||
ignore.IgnorePath("login", http.MethodPost, serviceMessagePath)
|
||||
ignore.IgnorePath("login", http.MethodGet, globalSSEPath)
|
||||
ignore.IgnorePath("login", http.MethodPost, globalMessagePath)
|
||||
ignore.IgnorePath("login", http.MethodGet, appSSEPath)
|
||||
ignore.IgnorePath("login", http.MethodPost, appMessagePath)
|
||||
ignore.IgnorePath("login", http.MethodGet, globalMcpPath)
|
||||
ignore.IgnorePath("login", http.MethodGet, appMcpPath)
|
||||
return []pm3.Api{
|
||||
pm3.CreateApiSimple(http.MethodGet, serviceSSEPath, p.mcpController.MCPHandle),
|
||||
pm3.CreateApiSimple(http.MethodPost, serviceMessagePath, p.mcpController.MCPHandle),
|
||||
pm3.CreateApiSimple(http.MethodGet, globalSSEPath, p.mcpController.GlobalMCPHandle),
|
||||
pm3.CreateApiSimple(http.MethodPost, globalMessagePath, p.mcpController.GlobalMCPHandle),
|
||||
pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/global/mcp/config", []string{"context"}, []string{"config"}, p.mcpController.GlobalMCPConfig),
|
||||
pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/app/mcp/config", []string{"context", "query:app"}, []string{"config"}, p.mcpController.AppMCPConfig),
|
||||
pm3.CreateApiSimple(http.MethodGet, fmt.Sprintf("/api/v1/%s/:app/sse", mcp_server.AppBasePath), p.mcpController.AppMCPHandle),
|
||||
pm3.CreateApiSimple(http.MethodPost, fmt.Sprintf("/api/v1/%s/:app/message", mcp_server.AppBasePath), p.mcpController.AppMCPHandle),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ func (p *plugin) systemApikeyApis() []pm3.Api {
|
||||
pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/system/apikey", []string{"context", "query:apikey"}, nil, p.systemAPIKeyController.Delete),
|
||||
pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/apikeys", []string{"context", "query:keyword"}, []string{"apikeys"}, p.systemAPIKeyController.Search),
|
||||
pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my/apikeys", []string{"context"}, []string{"apikeys"}, p.systemAPIKeyController.MyAPIKeys),
|
||||
pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my/app/apikeys", []string{"context", "query:service"}, []string{"apps"}, p.systemAPIKeyController.MyAPIKeysByService),
|
||||
pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my/app/apikeys", []string{"context", "query:service", "query:app"}, []string{"apps"}, p.systemAPIKeyController.MyAPIKeysByService),
|
||||
pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/system/apikeys", []string{"context"}, []string{"apikeys"}, p.systemAPIKeyController.SimpleList),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@ func (o *openapiCheck) Handler(ginCtx *gin.Context) {
|
||||
}
|
||||
authorization = apikey
|
||||
}
|
||||
authorization = strings.TrimPrefix(authorization, "Bearer ")
|
||||
if authorization == o.apikey {
|
||||
return
|
||||
}
|
||||
|
||||
+36
-11
@@ -5,33 +5,58 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/eolinker/go-common/ignore"
|
||||
|
||||
mcp_server "github.com/APIParkLab/APIPark/mcp-server"
|
||||
"github.com/eolinker/go-common/ignore"
|
||||
"github.com/eolinker/go-common/pm3"
|
||||
)
|
||||
|
||||
func (p *plugin) mcpAPIs() []pm3.Api {
|
||||
globalSSEPath := fmt.Sprintf("/openapi/v1/%s/sse", strings.Trim(mcp_server.GlobalBasePath, "/"))
|
||||
globalMessagePath := fmt.Sprintf("/openapi/v1/%s/message", strings.Trim(mcp_server.GlobalBasePath, "/"))
|
||||
serviceMessagePath := fmt.Sprintf("/openapi/v1/%s/:serviceId/message", strings.Trim(mcp_server.ServiceBasePath, "/"))
|
||||
|
||||
appSSEPath := fmt.Sprintf("/openapi/v1/%s/:app/sse", strings.Trim(mcp_server.AppBasePath, "/"))
|
||||
appMessagePath := fmt.Sprintf("/openapi/v1/%s/:app/message", strings.Trim(mcp_server.AppBasePath, "/"))
|
||||
|
||||
serviceSSEPath := fmt.Sprintf("/openapi/v1/%s/:serviceId/sse", strings.Trim(mcp_server.ServiceBasePath, "/"))
|
||||
serviceStreamablePath := fmt.Sprintf("/openapi/v1/%s/:serviceId/mcp", strings.Trim(mcp_server.ServiceBasePath, "/"))
|
||||
serviceMessagePath := fmt.Sprintf("/openapi/v1/%s/:serviceId/message", strings.Trim(mcp_server.ServiceBasePath, "/"))
|
||||
//serviceStreamablePath := fmt.Sprintf("/openapi/v1/%s/:serviceId/mcp", strings.Trim(mcp_server.ServiceBasePath, "/"))
|
||||
|
||||
ignore.IgnorePath("openapi", http.MethodPost, globalMessagePath)
|
||||
//ignore.IgnorePath("openapi", http.MethodGet, globalSSEPath)
|
||||
ignore.IgnorePath("openapi", http.MethodPost, appMessagePath)
|
||||
ignore.IgnorePath("openapi", http.MethodGet, appSSEPath)
|
||||
ignore.IgnorePath("openapi", http.MethodGet, serviceSSEPath)
|
||||
ignore.IgnorePath("openapi", http.MethodPost, serviceMessagePath)
|
||||
ignore.IgnorePath("openapi", http.MethodGet, serviceStreamablePath)
|
||||
ignore.IgnorePath("openapi", http.MethodPost, serviceStreamablePath)
|
||||
ignore.IgnorePath("openapi", http.MethodDelete, serviceStreamablePath)
|
||||
|
||||
ignore.IgnorePath("openapi", http.MethodGet, mcp_server.OpenAppMCPPath)
|
||||
ignore.IgnorePath("openapi", http.MethodPost, mcp_server.OpenAppMCPPath)
|
||||
ignore.IgnorePath("openapi", http.MethodDelete, mcp_server.OpenAppMCPPath)
|
||||
|
||||
ignore.IgnorePath("openapi", http.MethodGet, mcp_server.OpenServiceMCPPath)
|
||||
ignore.IgnorePath("openapi", http.MethodPost, mcp_server.OpenServiceMCPPath)
|
||||
ignore.IgnorePath("openapi", http.MethodDelete, mcp_server.OpenServiceMCPPath)
|
||||
|
||||
return []pm3.Api{
|
||||
pm3.CreateApiSimple(http.MethodGet, fmt.Sprintf("/openapi/v1/%s/sse", strings.Trim(mcp_server.GlobalBasePath, "/")), p.mcpController.GlobalHandleSSE),
|
||||
pm3.CreateApiSimple(http.MethodGet, globalSSEPath, p.mcpController.GlobalHandleSSE),
|
||||
pm3.CreateApiSimple(http.MethodPost, globalMessagePath, p.mcpController.GlobalHandleMessage),
|
||||
|
||||
pm3.CreateApiSimple(http.MethodGet, appSSEPath, p.mcpController.AppHandleSSE),
|
||||
pm3.CreateApiSimple(http.MethodPost, appMessagePath, p.mcpController.AppHandleMessage),
|
||||
|
||||
pm3.CreateApiSimple(http.MethodGet, serviceSSEPath, p.mcpController.ServiceHandleSSE),
|
||||
pm3.CreateApiSimple(http.MethodPost, serviceMessagePath, p.mcpController.ServiceHandleMessage),
|
||||
|
||||
pm3.CreateApiSimple(http.MethodPost, serviceStreamablePath, p.mcpController.ServiceHandleStreamHTTP),
|
||||
pm3.CreateApiSimple(http.MethodDelete, serviceStreamablePath, p.mcpController.ServiceHandleStreamHTTP),
|
||||
pm3.CreateApiSimple(http.MethodGet, serviceStreamablePath, p.mcpController.ServiceHandleStreamHTTP),
|
||||
pm3.CreateApiSimple(http.MethodGet, mcp_server.OpenGlobalMCPPath, p.mcpController.GlobalHandleStreamHTTP),
|
||||
pm3.CreateApiSimple(http.MethodPost, mcp_server.OpenGlobalMCPPath, p.mcpController.GlobalHandleStreamHTTP),
|
||||
pm3.CreateApiSimple(http.MethodDelete, mcp_server.OpenGlobalMCPPath, p.mcpController.GlobalHandleStreamHTTP),
|
||||
|
||||
pm3.CreateApiSimple(http.MethodGet, mcp_server.OpenAppMCPPath, p.mcpController.AppHandleStreamHTTP),
|
||||
pm3.CreateApiSimple(http.MethodPost, mcp_server.OpenAppMCPPath, p.mcpController.AppHandleStreamHTTP),
|
||||
pm3.CreateApiSimple(http.MethodDelete, mcp_server.OpenAppMCPPath, p.mcpController.AppHandleStreamHTTP),
|
||||
|
||||
pm3.CreateApiSimple(http.MethodPost, mcp_server.OpenServiceMCPPath, p.mcpController.ServiceHandleStreamHTTP),
|
||||
pm3.CreateApiSimple(http.MethodDelete, mcp_server.OpenServiceMCPPath, p.mcpController.ServiceHandleStreamHTTP),
|
||||
pm3.CreateApiSimple(http.MethodGet, mcp_server.OpenServiceMCPPath, p.mcpController.ServiceHandleStreamHTTP),
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -131,6 +131,16 @@ system:
|
||||
value: 'manager'
|
||||
dependents:
|
||||
- system.settings.ai_api.view
|
||||
- name: login
|
||||
value: 'login'
|
||||
children:
|
||||
- name: view
|
||||
value: 'view'
|
||||
guest_allow: true
|
||||
- name: manager
|
||||
value: 'manager'
|
||||
dependents:
|
||||
- system.settings.login.view
|
||||
- name: ai log
|
||||
value: 'ai_log'
|
||||
children:
|
||||
@@ -294,6 +304,17 @@ team:
|
||||
value: 'manager_subscribed_services'
|
||||
dependents:
|
||||
- team.consumer.subscription.manager_subscribed_services
|
||||
- name: mcp
|
||||
cname: MCP
|
||||
value: 'mcp'
|
||||
children:
|
||||
- name: view
|
||||
value: 'view'
|
||||
guest_allow: true
|
||||
- name: manager
|
||||
value: 'manager'
|
||||
dependents:
|
||||
- team.consumer.mcp.view
|
||||
- name: authorization
|
||||
value: 'authorization'
|
||||
children:
|
||||
|
||||
@@ -26,6 +26,8 @@ system:
|
||||
- system.settings.general.view
|
||||
- system.settings.log_configuration.manager
|
||||
- system.settings.log_configuration.view
|
||||
- system.settings.login.manager
|
||||
- system.settings.login.view
|
||||
- system.settings.mcp.view
|
||||
- system.settings.mcp.manager
|
||||
- system.settings.role.view
|
||||
@@ -69,6 +71,8 @@ system:
|
||||
- system.settings.general.view
|
||||
- system.settings.log_configuration.manager
|
||||
- system.settings.log_configuration.view
|
||||
- system.settings.login.manager
|
||||
- system.settings.login.view
|
||||
- system.settings.ssl_certificate.manager
|
||||
- system.settings.ssl_certificate.view
|
||||
- system.settings.strategy.view
|
||||
@@ -88,6 +92,8 @@ team:
|
||||
permits:
|
||||
- team.consumer.authorization.manager
|
||||
- team.consumer.authorization.view
|
||||
- team.consumer.mcp.manager
|
||||
- team.consumer.mcp.view
|
||||
- team.consumer.subscription.manager_subscribed_services
|
||||
- team.consumer.subscription.subscribe
|
||||
- team.consumer.subscription.view_subscribed_service
|
||||
@@ -161,6 +167,8 @@ team:
|
||||
permits:
|
||||
- team.consumer.authorization.manager
|
||||
- team.consumer.authorization.view
|
||||
- team.consumer.mcp.manager
|
||||
- team.consumer.mcp.view
|
||||
- team.consumer.subscription.manager_subscribed_services
|
||||
- team.consumer.subscription.subscribe
|
||||
- team.consumer.subscription.view_subscribed_service
|
||||
@@ -172,9 +180,10 @@ team:
|
||||
- name: consumer developer
|
||||
value: consumer_developer
|
||||
permits:
|
||||
- team.consumer.application.manager
|
||||
- team.consumer.authorization.manager
|
||||
- team.consumer.authorization.view
|
||||
- team.consumer.mcp.manager
|
||||
- team.consumer.mcp.view
|
||||
- team.consumer.subscription.subscribe
|
||||
- team.consumer.subscription.view_subscribed_service
|
||||
- team.team.consumer.view
|
||||
|
||||
@@ -22,7 +22,7 @@ echo "login qiniu..."
|
||||
qshell account ${AccessKey} ${SecretKey} ${QINIU_NAME}
|
||||
|
||||
echo "qshell rput ${QINIU_BUCKET} \"${APP}/images/${Tar}\" ${Tar}"
|
||||
qshell rput ${QINIU_BUCKET} "${APP}/images/${Tar}" ${Tar}
|
||||
qshell rput --overwrite ${QINIU_BUCKET} "${APP}/images/${Tar}" ${Tar}
|
||||
|
||||
rm -f ${Tar}
|
||||
docker rmi -f ${ImageName}:${Version}
|
||||
@@ -58,11 +58,12 @@ func (s *imlServiceGetSoftDelete[T, E]) List(ctx context.Context, uuids ...strin
|
||||
return utils.SliceToSlice(list, s.toModelHandler), nil
|
||||
}
|
||||
func (s *imlServiceGetSoftDelete[T, E]) Search(ctx context.Context, keyword string, condition map[string]interface{}, sortRule ...string) ([]*T, error) {
|
||||
if condition == nil {
|
||||
condition = make(map[string]interface{})
|
||||
w := make(map[string]interface{})
|
||||
for k, v := range condition {
|
||||
w[k] = v
|
||||
}
|
||||
condition[SoftDeleteField] = false
|
||||
ps, err := s.store.Search(ctx, keyword, condition, sortRule...)
|
||||
w[SoftDeleteField] = false
|
||||
ps, err := s.store.Search(ctx, keyword, w, sortRule...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -70,11 +71,12 @@ func (s *imlServiceGetSoftDelete[T, E]) Search(ctx context.Context, keyword stri
|
||||
}
|
||||
|
||||
func (s *imlServiceGetSoftDelete[T, E]) SearchByPage(ctx context.Context, keyword string, condition map[string]interface{}, page int, pageSize int, sortRule ...string) ([]*T, int64, error) {
|
||||
if condition == nil {
|
||||
condition = make(map[string]interface{})
|
||||
w := make(map[string]interface{})
|
||||
for k, v := range condition {
|
||||
w[k] = v
|
||||
}
|
||||
condition[SoftDeleteField] = false
|
||||
ps, total, err := s.store.SearchByPage(ctx, keyword, condition, page, pageSize, sortRule...)
|
||||
w[SoftDeleteField] = false
|
||||
ps, total, err := s.store.SearchByPage(ctx, keyword, w, page, pageSize, sortRule...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
@@ -71,7 +71,11 @@ func (s *imlServiceGet[T, E]) List(ctx context.Context, uuids ...string) ([]*T,
|
||||
return utils.SliceToSlice(list, s.toModelHandler), nil
|
||||
}
|
||||
func (s *imlServiceGet[T, E]) Search(ctx context.Context, keyword string, condition map[string]interface{}, sortRule ...string) ([]*T, error) {
|
||||
ps, err := s.store.Search(ctx, keyword, condition, sortRule...)
|
||||
w := make(map[string]interface{})
|
||||
for k, v := range condition {
|
||||
w[k] = v
|
||||
}
|
||||
ps, err := s.store.Search(ctx, keyword, w, sortRule...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -79,7 +83,11 @@ func (s *imlServiceGet[T, E]) Search(ctx context.Context, keyword string, condit
|
||||
}
|
||||
|
||||
func (s *imlServiceGet[T, E]) SearchByPage(ctx context.Context, keyword string, condition map[string]interface{}, page int, pageSize int, sortRule ...string) ([]*T, int64, error) {
|
||||
ps, total, err := s.store.SearchByPage(ctx, keyword, condition, page, pageSize, sortRule...)
|
||||
w := make(map[string]interface{})
|
||||
for k, v := range condition {
|
||||
w[k] = v
|
||||
}
|
||||
ps, total, err := s.store.SearchByPage(ctx, keyword, w, page, pageSize, sortRule...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
@@ -3,10 +3,11 @@ package commit
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/eolinker/go-common/utils"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/eolinker/go-common/utils"
|
||||
|
||||
"github.com/eolinker/go-common/store"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
Reference in New Issue
Block a user