feat(mcp): 内置 MCP 服务端(streamable-http)
- 新增 backend/internal/router/mcp:MCP 端点 /api/v1/mcp,Bearer/X-MCP-Token/?token 鉴权 - 只读工具:list_apps / list_versions / get_version / simulate_check_update / list_cards / app_stats / list_devices / list_logs - 写工具(mcp.allow_write=true):publish_version / deprecate_version,默认 dry_run, 写操作落 logs 审计 - simulate_check_update 复刻 check-update 判定规则,可预判“同版本号重传不生效” - 导出 app.BuildManifest 复用清单计算口径,避免逻辑漂移 - 构建环境 go 1.21 -> 1.23(mcp-go 要求),Dockerfile 同步 - 文档 docs/mcp.md
This commit is contained in:
+1
-1
@@ -13,7 +13,7 @@ COPY frontend/ ./
|
||||
ENV NODE_OPTIONS="--max-old-space-size=2048"
|
||||
RUN pnpm vite build
|
||||
|
||||
FROM golang:1.21-alpine AS backend-builder
|
||||
FROM golang:1.23-alpine AS backend-builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
+8
-5
@@ -1,14 +1,18 @@
|
||||
module verification-platform-backend
|
||||
|
||||
go 1.21
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/dop251/goja v0.0.0-20260305124333-6a7976c22267
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/go-redis/redis/v8 v8.11.5
|
||||
github.com/golang-jwt/jwt/v5 v5.0.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/mark3labs/mcp-go v0.46.0
|
||||
github.com/spf13/viper v1.17.0
|
||||
golang.org/x/crypto v0.14.0
|
||||
golang.org/x/text v0.20.0
|
||||
gorm.io/driver/mysql v1.5.1
|
||||
gorm.io/gorm v1.30.0
|
||||
)
|
||||
@@ -19,7 +23,6 @@ require (
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dlclark/regexp2 v1.11.4 // indirect
|
||||
github.com/dop251/goja v0.0.0-20260305124333-6a7976c22267 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/fsnotify/fsnotify v1.6.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
@@ -31,8 +34,8 @@ require (
|
||||
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
|
||||
github.com/go-sql-driver/mysql v1.7.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/google/jsonschema-go v0.4.2 // indirect
|
||||
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect
|
||||
github.com/google/uuid v1.5.0 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
@@ -50,18 +53,18 @@ require (
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/spf13/afero v1.10.0 // indirect
|
||||
github.com/spf13/cast v1.5.1 // indirect
|
||||
github.com/spf13/cast v1.7.1 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
go.uber.org/atomic v1.9.0 // indirect
|
||||
go.uber.org/multierr v1.9.0 // indirect
|
||||
golang.org/x/arch v0.3.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
|
||||
golang.org/x/net v0.15.0 // indirect
|
||||
golang.org/x/sys v0.15.0 // indirect
|
||||
golang.org/x/text v0.20.0 // indirect
|
||||
google.golang.org/protobuf v1.31.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
+18
-11
@@ -38,6 +38,8 @@ cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3f
|
||||
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0=
|
||||
github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
|
||||
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
|
||||
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
|
||||
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
|
||||
@@ -72,8 +74,8 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m
|
||||
github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po=
|
||||
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY=
|
||||
github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
|
||||
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
|
||||
@@ -145,9 +147,11 @@ github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
|
||||
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
|
||||
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
|
||||
github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
|
||||
@@ -161,14 +165,12 @@ github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hf
|
||||
github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 h1:4/hN5RUoecvl+RmJRE2YxKWtnnQls6rQjjW5oV7qg2U=
|
||||
github.com/google/pprof v0.0.0-20230207041349-798e818bf904/go.mod h1:uglQLonpP8qtYCYyzA+8c/9qtqgA3qsXGYqCPKARAFg=
|
||||
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
|
||||
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
|
||||
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
|
||||
github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g=
|
||||
@@ -202,6 +204,8 @@ github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
||||
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mark3labs/mcp-go v0.46.0 h1:8KRibF4wcKejbLsHxCA/QBVUr5fQ9nwz/n8lGqmaALo=
|
||||
github.com/mark3labs/mcp-go v0.46.0/go.mod h1:JKTC7R2LLVagkEWK7Kwu7DbmA6iIvnNAod6yrHiQMag=
|
||||
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=
|
||||
@@ -238,8 +242,8 @@ github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9yS
|
||||
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||
github.com/spf13/afero v1.10.0 h1:EaGW2JJh15aKOejeuJ+wpFSHnbd7GE6Wvp3TsNhb6LY=
|
||||
github.com/spf13/afero v1.10.0/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ=
|
||||
github.com/spf13/cast v1.5.1 h1:R+kOtfhWQE6TVQzY+4D7wJLBgkdVasCEFxSUBYBYIlA=
|
||||
github.com/spf13/cast v1.5.1/go.mod h1:b9PdjNptOpzXr7Rq1q9gJML/2cdGQAo69NKzQ10KN48=
|
||||
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
|
||||
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.17.0 h1:I5txKw7MJasPL/BrfkbA0Jyo/oELqVmux4pR/UxOMfI=
|
||||
@@ -255,14 +259,17 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
|
||||
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
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=
|
||||
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
|
||||
@@ -63,6 +63,12 @@ func setDefaults() {
|
||||
viper.SetDefault("redis.password", "")
|
||||
viper.SetDefault("redis.db", "0")
|
||||
|
||||
// MCP(Model Context Protocol)服务端
|
||||
viper.SetDefault("mcp.enabled", false)
|
||||
viper.SetDefault("mcp.path", "/api/v1/mcp")
|
||||
viper.SetDefault("mcp.token", "")
|
||||
viper.SetDefault("mcp.allow_write", false)
|
||||
|
||||
// 日志配置
|
||||
viper.SetDefault("log.level", "info")
|
||||
viper.SetDefault("log.format", "json")
|
||||
|
||||
@@ -83,6 +83,11 @@ func buildVersionManifest(version *model.Version) (files []gin.H, manifestHash s
|
||||
return files, "sha256:" + hex.EncodeToString(hasher.Sum(nil)), version.UpdateType == "full", stored
|
||||
}
|
||||
|
||||
// BuildManifest 导出清单计算口径,供 MCP 等内部调用复用,避免两套逻辑漂移
|
||||
func BuildManifest(version *model.Version) (files []gin.H, manifestHash string, complete, stored bool) {
|
||||
return buildVersionManifest(version)
|
||||
}
|
||||
|
||||
// buildManifestURL 构造清单端点地址,客户端拿它去拉完整文件清单
|
||||
func buildManifestURL(appKey string, versionID uint) string {
|
||||
return fmt.Sprintf("/api/v1/app/%s/versions/manifest?version_id=%d", appKey, versionID)
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"verification-platform-backend/internal/database"
|
||||
"verification-platform-backend/internal/model"
|
||||
"verification-platform-backend/internal/router/app"
|
||||
"verification-platform-backend/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// resolveAppID 支持用 app_key 或 app_id 定位应用
|
||||
func resolveAppID(appKey string, appID int64) (uint, error) {
|
||||
if strings.TrimSpace(appKey) != "" {
|
||||
var a model.Application
|
||||
if err := database.DB.Where("app_key = ?", strings.TrimSpace(appKey)).First(&a).Error; err != nil {
|
||||
return 0, fmt.Errorf("应用不存在: %s", appKey)
|
||||
}
|
||||
return a.ID, nil
|
||||
}
|
||||
if appID > 0 {
|
||||
var a model.Application
|
||||
if err := database.DB.First(&a, appID).Error; err != nil {
|
||||
return 0, fmt.Errorf("应用不存在: %d", appID)
|
||||
}
|
||||
return a.ID, nil
|
||||
}
|
||||
return 0, fmt.Errorf("app_key 与 app_id 至少提供一个")
|
||||
}
|
||||
|
||||
func cleanVersion(v string) string {
|
||||
v = strings.TrimSpace(v)
|
||||
v = strings.TrimPrefix(v, "v")
|
||||
v = strings.TrimPrefix(v, "V")
|
||||
return v
|
||||
}
|
||||
|
||||
// simulateCheckUpdate 复刻 handleAppCheckUpdate 的判定规则,返回客户端实际会收到的结果。
|
||||
// 规则来源:backend/internal/router/app/info.go
|
||||
// 1. 客户端上报版本号 → 按版本号字符串匹配记录(published/superseded,按 id DESC 取第一条)
|
||||
// 2. 与「最高 ID 的已发布版本」比较 ID:只有 latest.ID > matched.ID 才 has_update=true
|
||||
// 3. forced 策略会把比客户端新的 published 版本视为必须更新
|
||||
// 4. 客户端版本号匹配不到 → 走安装器整包兜底
|
||||
func simulateCheckUpdate(appKey, clientVersion string) (gin.H, error) {
|
||||
var a model.Application
|
||||
if err := database.DB.Where("app_key = ?", strings.TrimSpace(appKey)).First(&a).Error; err != nil {
|
||||
return nil, fmt.Errorf("应用不存在: %s", appKey)
|
||||
}
|
||||
if service.GetApplicationDisabledStatus(a.ID) {
|
||||
return nil, fmt.Errorf("该应用已被禁用")
|
||||
}
|
||||
|
||||
var published []model.Version
|
||||
if err := database.DB.
|
||||
Where("application_id = ? AND publish_status = ?", a.ID, "published").
|
||||
Order("id DESC").Preload("Files").Find(&published).Error; err != nil {
|
||||
return nil, fmt.Errorf("获取版本列表失败: %w", err)
|
||||
}
|
||||
|
||||
base := gin.H{"app_key": a.AppKey, "app_name": a.Name, "client_reported_version": clientVersion}
|
||||
if len(published) == 0 {
|
||||
base["has_update"] = false
|
||||
base["reason"] = "该应用没有已发布版本"
|
||||
return base, nil
|
||||
}
|
||||
|
||||
// 安装器模式:客户端没报版本号,直接给最新全量包
|
||||
if strings.TrimSpace(clientVersion) == "" {
|
||||
lv := &published[0]
|
||||
res := packageResult(lv, clientVersion)
|
||||
res["mode"] = "installer_mode(未上报版本号 → 直接下发最新包)"
|
||||
res["has_update"] = true
|
||||
mergeH(base, res)
|
||||
return base, nil
|
||||
}
|
||||
|
||||
var matchable []model.Version
|
||||
if err := database.DB.
|
||||
Where("application_id = ? AND publish_status IN ?", a.ID, []string{"published", "superseded"}).
|
||||
Order("id DESC").Find(&matchable).Error; err != nil {
|
||||
return nil, fmt.Errorf("获取可匹配版本失败: %w", err)
|
||||
}
|
||||
|
||||
var cur *model.Version
|
||||
for i := range matchable {
|
||||
if cleanVersion(matchable[i].Version) == cleanVersion(clientVersion) {
|
||||
cur = &matchable[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 客户端版本号在服务器里匹配不到 → 整包兜底(新代码行为)
|
||||
if cur == nil {
|
||||
lv := &published[0]
|
||||
res := packageResult(lv, clientVersion)
|
||||
res["mode"] = "unknown_client_version(客户端版本号在服务器不存在 → 下发最新整包)"
|
||||
res["has_update"] = true
|
||||
mergeH(base, res)
|
||||
return base, nil
|
||||
}
|
||||
|
||||
base["matched_version_id"] = cur.ID
|
||||
base["matched_version"] = cur.Version
|
||||
base["matched_publish_status"] = cur.PublishStatus
|
||||
|
||||
// 是否存在比客户端更新的 forced 版本
|
||||
var latest *model.Version
|
||||
strategy := ""
|
||||
forcedFound := false
|
||||
for i := range published {
|
||||
if published[i].ID > cur.ID && published[i].UpdateStrategy == "forced" {
|
||||
forcedFound = true
|
||||
if latest == nil || published[i].ID > latest.ID {
|
||||
latest = &published[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
if forcedFound {
|
||||
strategy = "forced"
|
||||
} else {
|
||||
lv := published[0]
|
||||
if lv.ID > cur.ID {
|
||||
latest = &lv
|
||||
strategy = lv.UpdateStrategy
|
||||
}
|
||||
}
|
||||
|
||||
if latest == nil {
|
||||
base["has_update"] = false
|
||||
base["latest_version"] = published[0].Version
|
||||
base["latest_version_id"] = published[0].ID
|
||||
base["reason"] = "服务端判定客户端已是最新:只比较版本记录 ID,同版本号重新上传文件不会触发更新"
|
||||
return base, nil
|
||||
}
|
||||
|
||||
var lvFull model.Version
|
||||
if err := database.DB.Preload("Files").First(&lvFull, latest.ID).Error; err != nil {
|
||||
return nil, fmt.Errorf("读取最新版本失败: %w", err)
|
||||
}
|
||||
|
||||
res := packageResult(&lvFull, clientVersion)
|
||||
res["has_update"] = true
|
||||
res["update_strategy"] = strategy
|
||||
res["mode"] = "update"
|
||||
if latest.Version == cur.Version && latest.ID > cur.ID {
|
||||
res["warning"] = "下发版本号与客户端当前版本号相同但记录 ID 更大:服务端认为需要更新," +
|
||||
"但客户端若按版本号自行判重会跳过下载 —— 这正是“重传没生效”的典型形态"
|
||||
}
|
||||
mergeH(base, res)
|
||||
return base, nil
|
||||
}
|
||||
|
||||
// packageResult 按 handler 的优先级给出下载地址、hash、清单信息
|
||||
func packageResult(v *model.Version, clientVersion string) gin.H {
|
||||
downloadURL := v.FullPackagePath
|
||||
downloadSize := v.FullPackageSize
|
||||
downloadHash := v.FullPackageHash
|
||||
if downloadURL == "" {
|
||||
downloadURL = v.FilePath
|
||||
downloadSize = v.FileSize
|
||||
downloadHash = v.FileHash
|
||||
}
|
||||
|
||||
isPatch := false
|
||||
if v.UpdateType == "patch" && v.BaseVersionID != nil && v.FilePath != "" {
|
||||
// 补丁包地址始终给出;是否可应用取决于客户端当前版本是否等于基础版本,
|
||||
// 精确判定放在 simulateCheckUpdate 里做(这里只表达“这是补丁型版本”)
|
||||
isPatch = true
|
||||
}
|
||||
|
||||
if v.CustomDownloadURL != "" {
|
||||
downloadURL = v.CustomDownloadURL
|
||||
}
|
||||
|
||||
_, manifestHash, complete, stored := app.BuildManifest(v)
|
||||
|
||||
res := gin.H{
|
||||
"latest_version": v.Version,
|
||||
"latest_version_id": v.ID,
|
||||
"publish_status": v.PublishStatus,
|
||||
"update_type": v.UpdateType,
|
||||
"update_strategy": v.UpdateStrategy,
|
||||
"update_method": v.UpdateMethod,
|
||||
"download_url": downloadURL,
|
||||
"file_size": downloadSize,
|
||||
"file_hash": downloadHash,
|
||||
"full_package_url": v.FullPackagePath,
|
||||
"full_package_size": v.FullPackageSize,
|
||||
"full_package_hash": v.FullPackageHash,
|
||||
"patch_url": v.FilePath,
|
||||
"patch_size": v.FileSize,
|
||||
"patch_hash": v.FileHash,
|
||||
"is_patch_delivery": isPatch,
|
||||
"manifest_url": fmt.Sprintf("/api/v1/app/%s/versions/manifest?version_id=%d", v.Application.AppKey, v.ID),
|
||||
"manifest_hash": manifestHash,
|
||||
"manifest_complete": complete,
|
||||
"manifest_content_read": stored,
|
||||
"file_count": len(v.Files),
|
||||
"entry_file": v.EntryFile,
|
||||
"entry_files": v.EntryFiles,
|
||||
"description": v.Description,
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func mergeH(dst, src gin.H) {
|
||||
for k, v := range src {
|
||||
dst[k] = v
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"verification-platform-backend/internal/config"
|
||||
"verification-platform-backend/internal/database"
|
||||
"verification-platform-backend/internal/model"
|
||||
"verification-platform-backend/internal/router/app"
|
||||
"verification-platform-backend/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
sdk "github.com/mark3labs/mcp-go/mcp"
|
||||
mcpserver "github.com/mark3labs/mcp-go/server"
|
||||
)
|
||||
|
||||
const serverInstructions = `verify(网络验证系统)MCP 端点。
|
||||
|
||||
用途:查询应用/版本/卡密/设备/日志,并可(在允许写操作时)发布或废弃版本。
|
||||
|
||||
约定:
|
||||
- 版本更新判定以「客户端上报版本号字符串匹配到的记录 ID」和「最高 ID 的已发布版本 ID」比较为准;
|
||||
同版本号重新上传文件不会触发客户端更新,必须递增版本号。
|
||||
- 所有写操作必须先以 dry_run=true 调用确认影响,再以 dry_run=false 执行。`
|
||||
|
||||
// SetupMCPRoutes 挂载 MCP(streamable-http)端点。
|
||||
// 开关与令牌来自配置:mcp.enabled / mcp.token / mcp.path / mcp.allow_write
|
||||
func SetupMCPRoutes(r *gin.Engine) {
|
||||
if !config.GetBool("mcp.enabled") {
|
||||
return
|
||||
}
|
||||
|
||||
token := config.GetString("mcp.token")
|
||||
if token == "" {
|
||||
log.Printf("[MCP] 已启用但 mcp.token 为空,跳过挂载(避免无鉴权暴露)")
|
||||
return
|
||||
}
|
||||
|
||||
path := config.GetString("mcp.path")
|
||||
if path == "" {
|
||||
path = "/api/v1/mcp"
|
||||
}
|
||||
|
||||
s := mcpserver.NewMCPServer(
|
||||
"verify-mcp",
|
||||
"1.0.0",
|
||||
mcpserver.WithToolCapabilities(false),
|
||||
mcpserver.WithRecovery(),
|
||||
mcpserver.WithInstructions(serverInstructions),
|
||||
)
|
||||
|
||||
registerReadTools(s)
|
||||
if config.GetBool("mcp.allow_write") {
|
||||
registerWriteTools(s)
|
||||
}
|
||||
|
||||
h := mcpserver.NewStreamableHTTPServer(s)
|
||||
r.Any(path, gin.WrapH(auth(token, h)))
|
||||
|
||||
log.Printf("[MCP] 已挂载 %s(写操作: %v)", path, config.GetBool("mcp.allow_write"))
|
||||
}
|
||||
|
||||
// auth 校验 Bearer / X-MCP-Token / ?token=
|
||||
func auth(want string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got := ""
|
||||
if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") {
|
||||
got = strings.TrimSpace(strings.TrimPrefix(h, "Bearer "))
|
||||
}
|
||||
if got == "" {
|
||||
got = r.Header.Get("X-MCP-Token")
|
||||
}
|
||||
if got == "" {
|
||||
got = r.URL.Query().Get("token")
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(got), []byte(want)) != 1 {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func registerReadTools(s *mcpserver.MCPServer) {
|
||||
// ---------- 应用列表 ----------
|
||||
s.AddTool(sdk.NewTool("verify_list_apps",
|
||||
sdk.WithDescription("列出所有应用(id、名称、app_key、状态、心跳配置)。"),
|
||||
sdk.WithReadOnlyHintAnnotation(true),
|
||||
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
var apps []model.Application
|
||||
if err := database.DB.Order("id").Find(&apps).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("查询应用失败", err), nil
|
||||
}
|
||||
out := make([]gin.H, 0, len(apps))
|
||||
for _, a := range apps {
|
||||
out = append(out, gin.H{
|
||||
"id": a.ID, "name": a.Name, "app_key": a.AppKey, "status": a.Status,
|
||||
"max_devices": a.MaxDevices, "heartbeat_interval": a.HeartbeatInterval,
|
||||
})
|
||||
}
|
||||
return sdk.NewToolResultJSON(gin.H{"total": len(out), "apps": out})
|
||||
})
|
||||
|
||||
// ---------- 版本列表 ----------
|
||||
s.AddTool(sdk.NewTool("verify_list_versions",
|
||||
sdk.WithDescription("按应用列出发布版本,含版本号、发布状态、更新类型、文件 hash、编辑时间差。用于排查“同版本号多条记录”“重传不生效”这类问题。"),
|
||||
sdk.WithReadOnlyHintAnnotation(true),
|
||||
sdk.WithString("app_key", sdk.Description("应用 app_key;与 app_id 二选一")),
|
||||
sdk.WithNumber("app_id", sdk.Description("应用 ID;与 app_key 二选一")),
|
||||
sdk.WithString("publish_status", sdk.Description("过滤发布状态:draft/published/deprecated/superseded")),
|
||||
sdk.WithNumber("page", sdk.Description("页码,从 1 开始,默认 1")),
|
||||
sdk.WithNumber("page_size", sdk.Description("每页条数,默认 20,上限 100")),
|
||||
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
appID, err := resolveAppID(req.GetString("app_key", ""), int64(req.GetInt("app_id", 0)))
|
||||
if err != nil {
|
||||
return sdk.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
page := req.GetInt("page", 1)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
size := req.GetInt("page_size", 20)
|
||||
if size < 1 || size > 100 {
|
||||
size = 20
|
||||
}
|
||||
|
||||
q := database.DB.Model(&model.Version{}).Where("application_id = ?", appID)
|
||||
if st := req.GetString("publish_status", ""); st != "" {
|
||||
q = q.Where("publish_status = ?", st)
|
||||
}
|
||||
|
||||
var total int64
|
||||
q.Count(&total)
|
||||
|
||||
var versions []model.Version
|
||||
if err := q.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&versions).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("查询版本失败", err), nil
|
||||
}
|
||||
|
||||
items := make([]gin.H, 0, len(versions))
|
||||
for _, v := range versions {
|
||||
items = append(items, gin.H{
|
||||
"id": v.ID, "version": v.Version,
|
||||
"publish_status": v.PublishStatus, "update_type": v.UpdateType,
|
||||
"update_strategy": v.UpdateStrategy,
|
||||
"file_path": v.FilePath, "file_size": v.FileSize, "file_hash": v.FileHash,
|
||||
"full_package_path": v.FullPackagePath, "full_package_hash": v.FullPackageHash,
|
||||
"base_version_id": v.BaseVersionID,
|
||||
"created_at": v.CreatedAt, "updated_at": v.UpdatedAt,
|
||||
"edit_gap_seconds": int64(v.UpdatedAt.Sub(v.CreatedAt).Seconds()),
|
||||
})
|
||||
}
|
||||
return sdk.NewToolResultJSON(gin.H{
|
||||
"app_id": appID, "total": total, "page": page, "page_size": size, "versions": items,
|
||||
})
|
||||
})
|
||||
|
||||
// ---------- 版本详情(含文件清单与清单指纹) ----------
|
||||
s.AddTool(sdk.NewTool("verify_get_version",
|
||||
sdk.WithDescription("查看单个版本的完整信息,包括文件清单、清单指纹(manifest_hash)、是否已落盘(stored)。"),
|
||||
sdk.WithReadOnlyHintAnnotation(true),
|
||||
sdk.WithNumber("version_id", sdk.Required(), sdk.Description("版本 ID")),
|
||||
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
vid := req.GetInt("version_id", 0)
|
||||
if vid <= 0 {
|
||||
return sdk.NewToolResultError("version_id 必填"), nil
|
||||
}
|
||||
var v model.Version
|
||||
if err := database.DB.Preload("Files").First(&v, vid).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("版本不存在", err), nil
|
||||
}
|
||||
files, manifestHash, complete, stored := app.BuildManifest(&v)
|
||||
return sdk.NewToolResultJSON(gin.H{
|
||||
"id": v.ID, "application_id": v.ApplicationID, "version": v.Version,
|
||||
"publish_status": v.PublishStatus, "update_type": v.UpdateType,
|
||||
"update_strategy": v.UpdateStrategy, "update_method": v.UpdateMethod,
|
||||
"file_path": v.FilePath, "file_size": v.FileSize, "file_hash": v.FileHash,
|
||||
"full_package_path": v.FullPackagePath, "full_package_size": v.FullPackageSize,
|
||||
"full_package_hash": v.FullPackageHash,
|
||||
"base_version_id": v.BaseVersionID, "superseded_by": v.SupersededBy,
|
||||
"entry_file": v.EntryFile, "entry_files": v.EntryFiles,
|
||||
"desktop_shortcut_files": v.DesktopShortcutFiles,
|
||||
"description": v.Description, "changelog": v.Changelog,
|
||||
"manifest_hash": manifestHash, "manifest_complete": complete, "content_stored": stored,
|
||||
"files": files,
|
||||
"created_at": v.CreatedAt, "updated_at": v.UpdatedAt,
|
||||
})
|
||||
})
|
||||
|
||||
// ---------- 模拟客户端检查更新 ----------
|
||||
s.AddTool(sdk.NewTool("verify_simulate_check_update",
|
||||
sdk.WithDescription("模拟客户端调用 check-update,返回该版本客户端实际会收到什么(是否有更新、下发哪个包、清单指纹)。用于验证“客户端会不会真的拿到新文件”。判定规则与线上 handler 一致。"),
|
||||
sdk.WithReadOnlyHintAnnotation(true),
|
||||
sdk.WithString("app_key", sdk.Required(), sdk.Description("应用 app_key")),
|
||||
sdk.WithString("client_version", sdk.Description("客户端当前版本号;留空表示安装器模式(未登记版本)")),
|
||||
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
appKey := strings.TrimSpace(req.GetString("app_key", ""))
|
||||
if appKey == "" {
|
||||
return sdk.NewToolResultError("app_key 必填"), nil
|
||||
}
|
||||
res, err := simulateCheckUpdate(appKey, req.GetString("client_version", ""))
|
||||
if err != nil {
|
||||
return sdk.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
return sdk.NewToolResultJSON(res)
|
||||
})
|
||||
|
||||
// ---------- 卡密 ----------
|
||||
s.AddTool(sdk.NewTool("verify_list_cards",
|
||||
sdk.WithDescription("按应用分页查询卡密(不返回明文以外的敏感字段),可按状态过滤。"),
|
||||
sdk.WithReadOnlyHintAnnotation(true),
|
||||
sdk.WithString("app_key", sdk.Description("应用 app_key;与 app_id 二选一")),
|
||||
sdk.WithNumber("app_id", sdk.Description("应用 ID;与 app_key 二选一")),
|
||||
sdk.WithString("status", sdk.Description("状态:unused/used/expired/disabled")),
|
||||
sdk.WithNumber("page", sdk.Description("页码,默认 1")),
|
||||
sdk.WithNumber("page_size", sdk.Description("每页条数,默认 20,上限 100")),
|
||||
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
appID, err := resolveAppID(req.GetString("app_key", ""), int64(req.GetInt("app_id", 0)))
|
||||
if err != nil {
|
||||
return sdk.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
page := req.GetInt("page", 1)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
size := req.GetInt("page_size", 20)
|
||||
if size < 1 || size > 100 {
|
||||
size = 20
|
||||
}
|
||||
q := database.DB.Model(&model.Card{}).Where("application_id = ?", appID)
|
||||
if st := req.GetString("status", ""); st != "" {
|
||||
q = q.Where("status = ?", st)
|
||||
}
|
||||
var total int64
|
||||
q.Count(&total)
|
||||
var cards []model.Card
|
||||
if err := q.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&cards).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("查询卡密失败", err), nil
|
||||
}
|
||||
items := make([]gin.H, 0, len(cards))
|
||||
for _, c := range cards {
|
||||
items = append(items, gin.H{
|
||||
"id": c.ID, "card_key": c.CardKey, "status": c.Status,
|
||||
"card_type_id": c.CardTypeID, "app_user_id": c.AppUserID,
|
||||
"used_at": c.UsedAt, "expire_at": c.ExpireAt, "created_at": c.CreatedAt,
|
||||
})
|
||||
}
|
||||
return sdk.NewToolResultJSON(gin.H{"app_id": appID, "total": total, "page": page, "cards": items})
|
||||
})
|
||||
|
||||
// ---------- 应用统计 ----------
|
||||
s.AddTool(sdk.NewTool("verify_app_stats",
|
||||
sdk.WithDescription("应用概览:用户数、设备数、在线设备数(按心跳超时判定)、卡密各状态数量、版本数量。"),
|
||||
sdk.WithReadOnlyHintAnnotation(true),
|
||||
sdk.WithString("app_key", sdk.Description("应用 app_key;与 app_id 二选一")),
|
||||
sdk.WithNumber("app_id", sdk.Description("应用 ID;与 app_key 二选一")),
|
||||
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
appID, err := resolveAppID(req.GetString("app_key", ""), int64(req.GetInt("app_id", 0)))
|
||||
if err != nil {
|
||||
return sdk.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
var app model.Application
|
||||
if err := database.DB.First(&app, appID).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("应用不存在", err), nil
|
||||
}
|
||||
var users, devices, versions int64
|
||||
database.DB.Model(&model.AppUser{}).Where("application_id = ?", appID).Count(&users)
|
||||
database.DB.Model(&model.UserDevice{}).Where("application_id = ?", appID).Count(&devices)
|
||||
database.DB.Model(&model.Version{}).Where("application_id = ?", appID).Count(&versions)
|
||||
|
||||
timeout := app.HeartbeatTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = 300
|
||||
}
|
||||
since := time.Now().Add(-time.Duration(timeout) * time.Second)
|
||||
var online int64
|
||||
database.DB.Model(&model.DeviceSession{}).
|
||||
Where("application_id = ? AND last_heartbeat IS NOT NULL AND last_heartbeat > ?", appID, since).
|
||||
Count(&online)
|
||||
|
||||
cardStats := gin.H{}
|
||||
type row struct {
|
||||
Status string
|
||||
Cnt int64
|
||||
}
|
||||
var rows []row
|
||||
database.DB.Model(&model.Card{}).
|
||||
Select("status, count(*) as cnt").
|
||||
Where("application_id = ?", appID).
|
||||
Group("status").Scan(&rows)
|
||||
for _, r := range rows {
|
||||
cardStats[r.Status] = r.Cnt
|
||||
}
|
||||
|
||||
return sdk.NewToolResultJSON(gin.H{
|
||||
"app_id": appID, "name": app.Name, "app_key": app.AppKey, "status": app.Status,
|
||||
"users": users, "devices": devices, "online_devices": online,
|
||||
"versions": versions, "cards": cardStats,
|
||||
"heartbeat_timeout": timeout,
|
||||
})
|
||||
})
|
||||
|
||||
// ---------- 设备 ----------
|
||||
s.AddTool(sdk.NewTool("verify_list_devices",
|
||||
sdk.WithDescription("按应用分页列出设备及最近心跳时间。"),
|
||||
sdk.WithReadOnlyHintAnnotation(true),
|
||||
sdk.WithString("app_key", sdk.Description("应用 app_key;与 app_id 二选一")),
|
||||
sdk.WithNumber("app_id", sdk.Description("应用 ID;与 app_key 二选一")),
|
||||
sdk.WithNumber("page", sdk.Description("页码,默认 1")),
|
||||
sdk.WithNumber("page_size", sdk.Description("每页条数,默认 20,上限 100")),
|
||||
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
appID, err := resolveAppID(req.GetString("app_key", ""), int64(req.GetInt("app_id", 0)))
|
||||
if err != nil {
|
||||
return sdk.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
page := req.GetInt("page", 1)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
size := req.GetInt("page_size", 20)
|
||||
if size < 1 || size > 100 {
|
||||
size = 20
|
||||
}
|
||||
var total int64
|
||||
database.DB.Model(&model.UserDevice{}).Where("application_id = ?", appID).Count(&total)
|
||||
var devices []model.UserDevice
|
||||
if err := database.DB.Where("application_id = ?", appID).
|
||||
Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&devices).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("查询设备失败", err), nil
|
||||
}
|
||||
items := make([]gin.H, 0, len(devices))
|
||||
for _, d := range devices {
|
||||
items = append(items, gin.H{
|
||||
"id": d.ID, "user_id": d.UserID, "device_id": d.DeviceID,
|
||||
"device_name": d.DeviceName, "device_type": d.DeviceType,
|
||||
"status": d.Status, "created_at": d.CreatedAt, "updated_at": d.UpdatedAt,
|
||||
})
|
||||
}
|
||||
return sdk.NewToolResultJSON(gin.H{"app_id": appID, "total": total, "page": page, "devices": items})
|
||||
})
|
||||
|
||||
// ---------- 日志 ----------
|
||||
s.AddTool(sdk.NewTool("verify_list_logs",
|
||||
sdk.WithDescription("查询最近的操作/验证日志。"),
|
||||
sdk.WithReadOnlyHintAnnotation(true),
|
||||
sdk.WithNumber("app_id", sdk.Description("按应用过滤(可选)")),
|
||||
sdk.WithNumber("limit", sdk.Description("返回条数,默认 20,上限 100")),
|
||||
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
limit := req.GetInt("limit", 20)
|
||||
if limit < 1 || limit > 100 {
|
||||
limit = 20
|
||||
}
|
||||
q := database.DB.Model(&model.Log{})
|
||||
if appID := req.GetInt("app_id", 0); appID > 0 {
|
||||
q = q.Where("application_id = ?", appID)
|
||||
}
|
||||
var logs []model.Log
|
||||
if err := q.Order("id DESC").Limit(limit).Find(&logs).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("查询日志失败", err), nil
|
||||
}
|
||||
items := make([]gin.H, 0, len(logs))
|
||||
for _, l := range logs {
|
||||
items = append(items, gin.H{
|
||||
"id": l.ID, "log_type": l.LogType, "action": l.Action,
|
||||
"resource": l.Resource, "resource_id": l.ResourceID,
|
||||
"details": l.Details, "status": l.Status, "level": l.Level,
|
||||
"ip": l.IPAddress, "created_at": l.CreatedAt,
|
||||
})
|
||||
}
|
||||
return sdk.NewToolResultJSON(gin.H{"total": len(items), "logs": items})
|
||||
})
|
||||
}
|
||||
|
||||
func registerWriteTools(s *mcpserver.MCPServer) {
|
||||
// ---------- 发布版本 ----------
|
||||
s.AddTool(sdk.NewTool("verify_publish_version",
|
||||
sdk.WithDescription("发布版本。规则与面板一致:仅 draft/deprecated 可发布;forced 策略会把更早的 published 版本置为 superseded。dry_run=true 只返回将要发生的变化。"),
|
||||
sdk.WithDestructiveHintAnnotation(true),
|
||||
sdk.WithNumber("version_id", sdk.Required(), sdk.Description("版本 ID")),
|
||||
sdk.WithBoolean("dry_run", sdk.Description("true=只预演(默认),false=真正执行")),
|
||||
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
vid := req.GetInt("version_id", 0)
|
||||
dryRun := req.GetBool("dry_run", true)
|
||||
if vid <= 0 {
|
||||
return sdk.NewToolResultError("version_id 必填"), nil
|
||||
}
|
||||
var v model.Version
|
||||
if err := database.DB.First(&v, vid).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("版本不存在", err), nil
|
||||
}
|
||||
if v.PublishStatus != "draft" && v.PublishStatus != "deprecated" {
|
||||
return sdk.NewToolResultError("只能发布草稿或已废弃的版本(当前状态: " + v.PublishStatus + ")"), nil
|
||||
}
|
||||
|
||||
willSupersede := []uint{}
|
||||
if v.UpdateStrategy == "forced" {
|
||||
var ids []uint
|
||||
database.DB.Model(&model.Version{}).
|
||||
Where("application_id = ? AND id < ? AND publish_status = ?", v.ApplicationID, v.ID, "published").
|
||||
Pluck("id", &ids)
|
||||
willSupersede = ids
|
||||
}
|
||||
|
||||
if dryRun {
|
||||
return sdk.NewToolResultJSON(gin.H{
|
||||
"dry_run": true, "version_id": v.ID, "version": v.Version,
|
||||
"from": v.PublishStatus, "to": "published",
|
||||
"will_supersede_version_ids": willSupersede,
|
||||
})
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
v.PublishStatus = "published"
|
||||
v.PublishedAt = &now
|
||||
if err := database.DB.Save(&v).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("发布版本失败", err), nil
|
||||
}
|
||||
if v.UpdateStrategy == "forced" {
|
||||
database.DB.Model(&model.Version{}).
|
||||
Where("application_id = ? AND id < ? AND publish_status = ?", v.ApplicationID, v.ID, "published").
|
||||
Updates(map[string]interface{}{
|
||||
"publish_status": "superseded",
|
||||
"superseded_by": v.ID,
|
||||
"deprecated_at": now,
|
||||
})
|
||||
}
|
||||
auditLog("mcp.publish", &v, "MCP 发布版本")
|
||||
return sdk.NewToolResultJSON(gin.H{
|
||||
"dry_run": false, "version_id": v.ID, "version": v.Version,
|
||||
"publish_status": v.PublishStatus, "published_at": v.PublishedAt,
|
||||
"superseded_version_ids": willSupersede,
|
||||
})
|
||||
})
|
||||
|
||||
// ---------- 废弃版本 ----------
|
||||
s.AddTool(sdk.NewTool("verify_deprecate_version",
|
||||
sdk.WithDescription("废弃已发布版本,并恢复被它取代的版本。dry_run=true 只返回将要发生的变化。"),
|
||||
sdk.WithDestructiveHintAnnotation(true),
|
||||
sdk.WithNumber("version_id", sdk.Required(), sdk.Description("版本 ID")),
|
||||
sdk.WithBoolean("dry_run", sdk.Description("true=只预演(默认),false=真正执行")),
|
||||
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
vid := req.GetInt("version_id", 0)
|
||||
dryRun := req.GetBool("dry_run", true)
|
||||
if vid <= 0 {
|
||||
return sdk.NewToolResultError("version_id 必填"), nil
|
||||
}
|
||||
var v model.Version
|
||||
if err := database.DB.First(&v, vid).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("版本不存在", err), nil
|
||||
}
|
||||
if v.PublishStatus != "published" {
|
||||
return sdk.NewToolResultError("只能废弃已发布的版本(当前状态: " + v.PublishStatus + ")"), nil
|
||||
}
|
||||
var restored []uint
|
||||
database.DB.Model(&model.Version{}).Where("superseded_by = ?", v.ID).Pluck("id", &restored)
|
||||
|
||||
if dryRun {
|
||||
return sdk.NewToolResultJSON(gin.H{
|
||||
"dry_run": true, "version_id": v.ID, "version": v.Version,
|
||||
"from": "published", "to": "deprecated",
|
||||
"will_restore_version_ids": restored,
|
||||
})
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
v.PublishStatus = "deprecated"
|
||||
v.DeprecatedAt = &now
|
||||
if err := database.DB.Save(&v).Error; err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("废弃版本失败", err), nil
|
||||
}
|
||||
database.DB.Model(&model.Version{}).
|
||||
Where("superseded_by = ?", v.ID).
|
||||
Updates(map[string]interface{}{
|
||||
"publish_status": "published",
|
||||
"superseded_by": nil,
|
||||
"deprecated_at": nil,
|
||||
})
|
||||
auditLog("mcp.deprecate", &v, "MCP 废弃版本")
|
||||
return sdk.NewToolResultJSON(gin.H{
|
||||
"dry_run": false, "version_id": v.ID, "version": v.Version,
|
||||
"publish_status": v.PublishStatus, "restored_version_ids": restored,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// auditLog 把 MCP 写操作记进 verify 自己的 logs 表(user_id 留空表示系统/MCP 操作)
|
||||
func auditLog(action string, v *model.Version, details string) {
|
||||
appID := v.ApplicationID
|
||||
vid := v.ID
|
||||
if err := service.CreateLog(service.LogParams{
|
||||
ApplicationID: &appID,
|
||||
LogType: "operation",
|
||||
Action: action,
|
||||
Resource: "version",
|
||||
ResourceID: &vid,
|
||||
Details: details + ": " + v.Version,
|
||||
Status: "success",
|
||||
Level: "info",
|
||||
}); err != nil {
|
||||
log.Printf("[MCP] 审计日志写入失败: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"verification-platform-backend/internal/router/extension"
|
||||
"verification-platform-backend/internal/router/frontend"
|
||||
"verification-platform-backend/internal/router/install"
|
||||
mcprouter "verification-platform-backend/internal/router/mcp"
|
||||
"verification-platform-backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -28,6 +29,9 @@ func SetupRoutes(r *gin.Engine) {
|
||||
|
||||
install.SetupRoutes(r)
|
||||
|
||||
// MCP(streamable-http)端点:由 mcp.enabled / mcp.token 控制
|
||||
mcprouter.SetupMCPRoutes(r)
|
||||
|
||||
frontend.SetupRoutes(r)
|
||||
|
||||
api := r.Group("/api/v1")
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
# MCP(Model Context Protocol)端点
|
||||
|
||||
verify 内置的 MCP 服务端,走 **Streamable HTTP**,默认路径 `/api/v1/mcp`。
|
||||
让 Hermes / Claude 等 MCP 客户端可以直接查应用、版本、卡密、设备、日志,并在允许时发布/废弃版本。
|
||||
|
||||
## 开关与鉴权
|
||||
|
||||
在 `data/config.yaml` 增加(不配 `mcp.token` 时端点不挂载,避免裸奔):
|
||||
|
||||
```yaml
|
||||
mcp:
|
||||
enabled: true
|
||||
path: "/api/v1/mcp"
|
||||
token: "<随机长串>" # openssl rand -hex 32 生成
|
||||
allow_write: false # true 才注册发布/废弃等写工具
|
||||
```
|
||||
|
||||
鉴权(三选一,值必须等于 `mcp.token`):
|
||||
|
||||
- `Authorization: Bearer <token>`
|
||||
- `X-MCP-Token: <token>`
|
||||
- `?token=<token>`
|
||||
|
||||
## 工具清单
|
||||
|
||||
只读(始终可用):
|
||||
|
||||
| 工具 | 作用 |
|
||||
|---|---|
|
||||
| `verify_list_apps` | 应用列表(id / app_key / 状态 / 心跳配置) |
|
||||
| `verify_list_versions` | 按应用分页列版本,含 `edit_gap_seconds`(判断是否被编辑过) |
|
||||
| `verify_get_version` | 单版本详情 + 文件清单 + `manifest_hash` + `content_stored` |
|
||||
| `verify_simulate_check_update` | **模拟客户端 check-update**,直接回答"这个版本的客户端会收到什么" |
|
||||
| `verify_list_cards` | 卡密分页查询 |
|
||||
| `verify_app_stats` | 用户数 / 设备数 / 在线设备数 / 卡密状态分布 / 版本数 |
|
||||
| `verify_list_devices` | 设备分页列表 |
|
||||
| `verify_list_logs` | 最近日志 |
|
||||
|
||||
写操作(需 `mcp.allow_write: true`,默认 `dry_run=true` 只预演):
|
||||
|
||||
| 工具 | 作用 |
|
||||
|---|---|
|
||||
| `verify_publish_version` | 发布 draft/deprecated 版本;forced 策略会 supersede 更早版本 |
|
||||
| `verify_deprecate_version` | 废弃已发布版本并恢复被它取代的版本 |
|
||||
|
||||
写操作会往 `logs` 表写一条审计(`action` 以 `mcp.` 开头)。
|
||||
|
||||
## 为什么要有 `verify_simulate_check_update`
|
||||
|
||||
版本更新判定的规则是「按版本号字符串匹配记录」+「与最高 ID 的已发布版本比较 ID」。
|
||||
这带来一个反直觉后果:**在同一个版本号上重新上传文件,客户端不会被判为需要更新**。
|
||||
`simulate_check_update` 用与线上 handler 相同的规则算出结果,能提前发现"传了新包但客户端不来拿"。
|
||||
|
||||
## 客户端配置示例(Hermes)
|
||||
|
||||
```yaml
|
||||
mcp_servers:
|
||||
verify:
|
||||
url: "https://<面板域名>/api/v1/mcp"
|
||||
headers:
|
||||
Authorization: "Bearer <token>"
|
||||
```
|
||||
|
||||
## 注意
|
||||
|
||||
- 该端点复用准备容器同一条 HTTP 通道,请只在内网或带 TLS 的反代后暴露。
|
||||
- 所有查询都有分页上限(默认 20,最大 100),避免一次拉爆上下文。
|
||||
- 工具实现复用 `app.BuildManifest`,与面板/客户端清单口径一致,避免两套逻辑漂移。
|
||||
Reference in New Issue
Block a user