@apso/cli 0.47.6 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +28 -1
  2. package/dist/commands/dev.d.ts +2 -0
  3. package/dist/commands/dev.js +20 -3
  4. package/dist/commands/generate.js +55 -13
  5. package/dist/commands/mcp/serve.js +24 -41
  6. package/dist/commands/schema/diff.js +3 -4
  7. package/dist/commands/schema/pull.js +13 -11
  8. package/dist/commands/schema/push.js +6 -5
  9. package/dist/commands/schema/validate.d.ts +10 -0
  10. package/dist/commands/schema/validate.js +54 -0
  11. package/dist/commands/test/access.d.ts +11 -0
  12. package/dist/commands/test/access.js +65 -0
  13. package/dist/lib/access/cases.d.ts +120 -0
  14. package/dist/lib/access/cases.js +1163 -0
  15. package/dist/lib/access/index.d.ts +4 -0
  16. package/dist/lib/access/index.js +7 -0
  17. package/dist/lib/access/report.d.ts +75 -0
  18. package/dist/lib/access/report.js +118 -0
  19. package/dist/lib/access/rules.json +207 -0
  20. package/dist/lib/access/run.d.ts +38 -0
  21. package/dist/lib/access/run.js +111 -0
  22. package/dist/lib/access/tokens.d.ts +46 -0
  23. package/dist/lib/access/tokens.js +139 -0
  24. package/dist/lib/api/services.d.ts +10 -7
  25. package/dist/lib/api/services.js +19 -32
  26. package/dist/lib/apsorc-parser.d.ts +1 -1
  27. package/dist/lib/apsorc-parser.js +2 -0
  28. package/dist/lib/ddl/change.js +2 -0
  29. package/dist/lib/ddl/index.d.ts +11 -1
  30. package/dist/lib/ddl/index.js +30 -16
  31. package/dist/lib/ddl/sync.d.ts +25 -0
  32. package/dist/lib/ddl/sync.js +78 -0
  33. package/dist/lib/deploy/server-push.js +3 -1
  34. package/dist/lib/generators/go.d.ts +25 -7
  35. package/dist/lib/generators/go.js +365 -128
  36. package/dist/lib/generators/python.d.ts +9 -3
  37. package/dist/lib/generators/python.js +282 -47
  38. package/dist/lib/generators/typescript.d.ts +3 -5
  39. package/dist/lib/generators/typescript.js +78 -64
  40. package/dist/lib/guards.d.ts +111 -13
  41. package/dist/lib/guards.js +287 -23
  42. package/dist/lib/templates/entities/entity-col-array.eta +1 -1
  43. package/dist/lib/templates/go/dto/dto-col-array.eta +2 -2
  44. package/dist/lib/templates/go/dto/dto-col-date.eta +1 -1
  45. package/dist/lib/templates/go/dto/dto-col-decimal.eta +1 -1
  46. package/dist/lib/templates/go/dto/dto-col-enum.eta +1 -1
  47. package/dist/lib/templates/go/dto/dto-col-float.eta +1 -1
  48. package/dist/lib/templates/go/dto/dto-col-integer.eta +3 -3
  49. package/dist/lib/templates/go/dto/dto-col-numeric.eta +1 -1
  50. package/dist/lib/templates/go/dto/dto-col-string.eta +1 -1
  51. package/dist/lib/templates/go/dto/dto-col-text.eta +1 -1
  52. package/dist/lib/templates/go/dto/dto-col-timestamp.eta +1 -1
  53. package/dist/lib/templates/go/dto/dto-col-timestamptz.eta +1 -1
  54. package/dist/lib/templates/go/dto/dto-col-uuid.eta +1 -1
  55. package/dist/lib/templates/go/dto/dto-col-varchar.eta +1 -1
  56. package/dist/lib/templates/go/dto/dto.eta +17 -18
  57. package/dist/lib/templates/go/handlers/handler.eta +10 -8
  58. package/dist/lib/templates/go/handlers/scope.eta +3 -2
  59. package/dist/lib/templates/go/index-module.eta +10 -5
  60. package/dist/lib/templates/go/mcp.eta +307 -0
  61. package/dist/lib/templates/go/middleware/auth.eta +587 -166
  62. package/dist/lib/templates/go/middleware/permission.eta +174 -0
  63. package/dist/lib/templates/go/models/model.eta +22 -19
  64. package/dist/lib/templates/go/models/schema.eta +72 -0
  65. package/dist/lib/templates/go/services/service.eta +84 -35
  66. package/dist/lib/templates/go/utils/query.eta +68 -7
  67. package/dist/lib/templates/guards/guards.module.eta +37 -29
  68. package/dist/lib/templates/guards/index.eta +4 -0
  69. package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
  70. package/dist/lib/templates/guards/key.guard.eta +280 -0
  71. package/dist/lib/templates/guards/permission.guard.eta +168 -0
  72. package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
  73. package/dist/lib/templates/guards/scope.guard.eta +189 -41
  74. package/dist/lib/templates/python/auth.eta +354 -95
  75. package/dist/lib/templates/python/index-module.eta +7 -7
  76. package/dist/lib/templates/python/mcp.eta +284 -0
  77. package/dist/lib/templates/python/models/init.eta +24 -0
  78. package/dist/lib/templates/python/models/model.eta +30 -61
  79. package/dist/lib/templates/python/permissions.eta +121 -0
  80. package/dist/lib/templates/python/routers/router.eta +39 -1
  81. package/dist/lib/templates/python/schemas/schema-col-array.eta +1 -1
  82. package/dist/lib/templates/python/schemas/schema.eta +27 -14
  83. package/dist/lib/templates/python/services/service.eta +38 -15
  84. package/dist/lib/templates/python/utils/query.eta +52 -25
  85. package/dist/lib/templates/rest/controller-rest.eta +43 -23
  86. package/dist/lib/templates/rest/index-module-rest.eta +0 -4
  87. package/dist/lib/templates/rest/service-rest.eta +3 -44
  88. package/dist/lib/types/auth.d.ts +84 -80
  89. package/dist/lib/types/auth.js +77 -60
  90. package/dist/lib/types/entity.d.ts +17 -9
  91. package/dist/lib/types/entity.js +3 -0
  92. package/dist/lib/types/index.d.ts +2 -2
  93. package/dist/lib/types/index.js +6 -5
  94. package/dist/lib/utils/crud-deps.d.ts +77 -6
  95. package/dist/lib/utils/crud-deps.js +197 -14
  96. package/dist/lib/utils/field.d.ts +12 -0
  97. package/dist/lib/utils/field.js +18 -2
  98. package/dist/lib/utils/schema-convert.d.ts +20 -43
  99. package/dist/lib/utils/schema-convert.js +28 -78
  100. package/dist/lib/utils/template.d.ts +11 -0
  101. package/dist/lib/utils/template.js +36 -1
  102. package/dist/lib/verify/index.d.ts +6 -1
  103. package/dist/lib/verify/index.js +30 -13
  104. package/npm-shrinkwrap.json +2 -2
  105. package/oclif.manifest.json +36 -1
  106. package/package.json +1 -1
  107. package/dist/lib/templates/go/models/model-col-array.eta +0 -1
  108. package/dist/lib/templates/go/models/model-col-boolean.eta +0 -1
  109. package/dist/lib/templates/go/models/model-col-date.eta +0 -1
  110. package/dist/lib/templates/go/models/model-col-decimal.eta +0 -1
  111. package/dist/lib/templates/go/models/model-col-enum.eta +0 -2
  112. package/dist/lib/templates/go/models/model-col-float.eta +0 -1
  113. package/dist/lib/templates/go/models/model-col-integer.eta +0 -1
  114. package/dist/lib/templates/go/models/model-col-json.eta +0 -1
  115. package/dist/lib/templates/go/models/model-col-jsonb.eta +0 -1
  116. package/dist/lib/templates/go/models/model-col-numeric.eta +0 -1
  117. package/dist/lib/templates/go/models/model-col-string.eta +0 -1
  118. package/dist/lib/templates/go/models/model-col-text.eta +0 -1
  119. package/dist/lib/templates/go/models/model-col-timestamp.eta +0 -1
  120. package/dist/lib/templates/go/models/model-col-timestamptz.eta +0 -1
  121. package/dist/lib/templates/go/models/model-col-uuid.eta +0 -1
  122. package/dist/lib/templates/go/models/model-col-varchar.eta +0 -1
  123. package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
  124. package/dist/lib/templates/guards/auth.guard.eta +0 -233
  125. package/dist/lib/templates/python/models/model-col-array.eta +0 -4
  126. package/dist/lib/templates/python/models/model-col-boolean.eta +0 -6
  127. package/dist/lib/templates/python/models/model-col-date.eta +0 -4
  128. package/dist/lib/templates/python/models/model-col-datetime.eta +0 -5
  129. package/dist/lib/templates/python/models/model-col-decimal.eta +0 -4
  130. package/dist/lib/templates/python/models/model-col-enum.eta +0 -16
  131. package/dist/lib/templates/python/models/model-col-float.eta +0 -6
  132. package/dist/lib/templates/python/models/model-col-integer.eta +0 -6
  133. package/dist/lib/templates/python/models/model-col-json.eta +0 -4
  134. package/dist/lib/templates/python/models/model-col-jsonb.eta +0 -4
  135. package/dist/lib/templates/python/models/model-col-numeric.eta +0 -4
  136. package/dist/lib/templates/python/models/model-col-string.eta +0 -6
  137. package/dist/lib/templates/python/models/model-col-text.eta +0 -6
  138. package/dist/lib/templates/python/models/model-col-timestamp.eta +0 -11
  139. package/dist/lib/templates/python/models/model-col-timestamptz.eta +0 -11
  140. package/dist/lib/templates/python/models/model-col-uuid.eta +0 -5
  141. package/dist/lib/templates/python/models/model-col-varchar.eta +0 -6
@@ -4,7 +4,9 @@ package handlers
4
4
 
5
5
  import (
6
6
  "net/http"
7
+ <% if (it.primaryKeyType !== 'uuid') { %>
7
8
  "strconv"
9
+ <% } %>
8
10
 
9
11
  "app/autogen/dto"
10
12
  "app/autogen/services"
@@ -76,13 +78,13 @@ func (h *<%= it.entityName %>Handler) FindAll(c *gin.Context) {
76
78
  if opts.Bare {
77
79
  rows, err := h.service.FindAllBare(c.Request.Context(), opts)
78
80
  if err != nil {
79
- <% if (it.scope) { %>
81
+ <% if (it.scope || it.references) { %>
80
82
  if scopeError(c, err) {
81
83
  return
82
84
  }
83
85
  <% } %>
84
86
  if qe, ok := utils.AsQueryError(err); ok {
85
- c.JSON(http.StatusBadRequest, gin.H{"error": qe.Error()})
87
+ c.JSON(qe.Status(), gin.H{"error": qe.Error()})
86
88
  return
87
89
  }
88
90
  c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
@@ -94,13 +96,13 @@ func (h *<%= it.entityName %>Handler) FindAll(c *gin.Context) {
94
96
 
95
97
  result, err := h.service.FindAll(c.Request.Context(), opts)
96
98
  if err != nil {
97
- <% if (it.scope) { %>
99
+ <% if (it.scope || it.references) { %>
98
100
  if scopeError(c, err) {
99
101
  return
100
102
  }
101
103
  <% } %>
102
104
  if qe, ok := utils.AsQueryError(err); ok {
103
- c.JSON(http.StatusBadRequest, gin.H{"error": qe.Error()})
105
+ c.JSON(qe.Status(), gin.H{"error": qe.Error()})
104
106
  return
105
107
  }
106
108
  c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
@@ -136,7 +138,7 @@ func (h *<%= it.entityName %>Handler) FindOne(c *gin.Context) {
136
138
 
137
139
  result, err := h.service.FindOne(c.Request.Context(), id)
138
140
  if err != nil {
139
- <% if (it.scope) { %>
141
+ <% if (it.scope || it.references) { %>
140
142
  if scopeError(c, err) {
141
143
  return
142
144
  }
@@ -173,7 +175,7 @@ func (h *<%= it.entityName %>Handler) Create(c *gin.Context) {
173
175
 
174
176
  result, err := h.service.Create(c.Request.Context(), &input)
175
177
  if err != nil {
176
- <% if (it.scope) { %>
178
+ <% if (it.scope || it.references) { %>
177
179
  if scopeError(c, err) {
178
180
  return
179
181
  }
@@ -224,7 +226,7 @@ func (h *<%= it.entityName %>Handler) Update(c *gin.Context) {
224
226
 
225
227
  result, err := h.service.Update(c.Request.Context(), id, &input)
226
228
  if err != nil {
227
- <% if (it.scope) { %>
229
+ <% if (it.scope || it.references) { %>
228
230
  if scopeError(c, err) {
229
231
  return
230
232
  }
@@ -261,7 +263,7 @@ func (h *<%= it.entityName %>Handler) Delete(c *gin.Context) {
261
263
  <% } %>
262
264
 
263
265
  if err := h.service.Delete(c.Request.Context(), id); err != nil {
264
- <% if (it.scope) { %>
266
+ <% if (it.scope || it.references) { %>
265
267
  if scopeError(c, err) {
266
268
  return
267
269
  }
@@ -7,15 +7,16 @@ import (
7
7
  "net/http"
8
8
  "strings"
9
9
 
10
+ "app/autogen/middleware"
10
11
  "app/autogen/services"
11
12
  "github.com/gin-gonic/gin"
12
13
  )
13
14
 
14
15
  // scopeError answers a scoped entity's service error: 403 when the caller has
15
- // no tenant, 404 when the row is missing or belongs to another tenant.
16
+ // no tenant or the body names a row it cannot read, 404 when the row is missing or belongs to another tenant.
16
17
  // It reports whether it wrote a response.
17
18
  func scopeError(c *gin.Context, err error) bool {
18
- if errors.Is(err, services.ErrForbidden) {
19
+ if errors.Is(err, services.ErrForbidden) || errors.Is(err, middleware.ErrReference) {
19
20
  c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
20
21
  return true
21
22
  }
@@ -4,19 +4,24 @@ package routes
4
4
 
5
5
  import (
6
6
  <% if (httpEntities.length > 0) { %> "app/autogen/handlers"
7
- <% } %><% if (it.hasAuth) { %> "app/autogen/middleware"
8
- <% } %> "app/autogen/services"
7
+ <% } %> "app/autogen/middleware"
8
+ "app/autogen/models"
9
+ "app/autogen/services"
9
10
  "github.com/gin-gonic/gin"
10
11
  "gorm.io/gorm"
11
12
  )
12
13
 
13
14
  // RegisterAllRoutes registers all entity routes
14
15
  func RegisterAllRoutes(r *gin.RouterGroup, db *gorm.DB) {
15
- <% if (it.hasAuth) { %>
16
- // Every route in this group requires authentication (.apsorc auth).
16
+ models.UseNames(db)
17
+ // Every route in this group needs a valid API key or a signed-in user.
17
18
  r.Use(middleware.AuthMiddleware(db))
18
-
19
+ <% if (it.permissions) { %>
20
+ // Role permissions from .apsorc are checked after authentication.
21
+ r.Use(middleware.PermissionMiddleware(db, r.BasePath()))
19
22
  <% } %>
23
+
24
+
20
25
  <% httpEntities.forEach((entity) => { %>
21
26
  // <%= entity.name %> routes
22
27
  <%= entity.camelName %>Service := services.New<%= entity.name %>Service(db)
@@ -0,0 +1,307 @@
1
+ <%~ includeFile('./header.eta', it) %>
2
+
3
+ package routes
4
+
5
+ // MCP tools at /mcp (Streamable HTTP, stateless), served with the official MCP
6
+ // SDK for Go.
7
+ //
8
+ // A tool is a route. When an agent calls a tool, the request is sent through
9
+ // the Gin engine in memory with the caller's headers, so authentication,
10
+ // permissions and tenant scoping run exactly as they do for a REST caller.
11
+ // Tools never call a service or the database.
12
+ //
13
+ // Gin has no OpenAPI document at run time, so each tool's input schema is
14
+ // written here from .apsorc: path and query parameters are top-level
15
+ // arguments, the JSON body is the "body" argument.
16
+ //
17
+ // Every request to /mcp passes the service's own auth check first. A request
18
+ // with no valid credential gets the 401 that starts OAuth sign-in in an MCP
19
+ // client, and /.well-known/oauth-protected-resource names the identity
20
+ // provider (RFC 9728).
21
+ //
22
+ // Serve your own route as a tool by calling RegisterMCPTool before MountMCP.
23
+
24
+ import (
25
+ "bytes"
26
+ "context"
27
+ "encoding/json"
28
+ "fmt"
29
+ "io"
30
+ "net/http"
31
+ "net/http/httptest"
32
+ "net/url"
33
+ "os"
34
+ "strings"
35
+
36
+ "app/autogen/middleware"
37
+ "github.com/gin-gonic/gin"
38
+ "github.com/modelcontextprotocol/go-sdk/mcp"
39
+ )
40
+
41
+ // MCPTool is a route served as an MCP tool.
42
+ type MCPTool struct {
43
+ Name string
44
+ Description string
45
+ Method string
46
+ // Path is the route under the API group, with :name parameters ("/invoices/:id").
47
+ Path string
48
+ // Query lists the arguments sent as query parameters.
49
+ Query []string
50
+ // InputSchema is the JSON Schema of the arguments, an object: path and
51
+ // query parameters at the top level, the JSON body under "body".
52
+ InputSchema json.RawMessage
53
+ }
54
+
55
+ const mcpListSchema = `{"type":"object","properties":{` +
56
+ `"filter":{"type":"array","items":{"type":"string"},"description":"field||$operator||value, one per condition"},` +
57
+ `"or":{"type":"array","items":{"type":"string"},"description":"field||$operator||value, any of which may match"},` +
58
+ `"sort":{"type":"array","items":{"type":"string"},"description":"field,ASC or field,DESC"},` +
59
+ `"join":{"type":"array","items":{"type":"string"},"description":"relation to load with each row"},` +
60
+ `"fields":{"type":"string","description":"field1,field2"},` +
61
+ `"limit":{"type":"integer","description":"page size"},` +
62
+ `"page":{"type":"integer","description":"page number, from 1"}},"required":[]}`
63
+
64
+ var mcpListQuery = []string{"filter", "or", "sort", "join", "fields", "limit", "page"}
65
+
66
+ // mcpTools holds the operations .apsorc opts in with "mcp".
67
+ var mcpTools = []MCPTool{
68
+ <% it.tools.forEach((tool) => { %>
69
+ {
70
+ Name: <%~ JSON.stringify(tool.name) %>,
71
+ Description: <%~ JSON.stringify(tool.description) %>,
72
+ Method: <%~ JSON.stringify(tool.method) %>,
73
+ Path: <%~ JSON.stringify(tool.path) %>,
74
+ <% if (tool.list) { %>
75
+ Query: mcpListQuery,
76
+ InputSchema: json.RawMessage(mcpListSchema),
77
+ <% } else { %>
78
+ InputSchema: json.RawMessage(<%~ JSON.stringify(tool.schema) %>),
79
+ <% } %>
80
+ },
81
+ <% }) %>
82
+ }
83
+
84
+ // RegisterMCPTool serves one more route as a tool. Call it before MountMCP.
85
+ func RegisterMCPTool(t MCPTool) {
86
+ mcpTools = append(mcpTools, t)
87
+ }
88
+
89
+ const (
90
+ mcpPath = "/mcp"
91
+ prmPath = "/.well-known/oauth-protected-resource"
92
+ )
93
+
94
+ // Headers that describe the MCP request itself, not the caller. Everything
95
+ // else (authorization, cookie, x-api-key, ...) is forwarded to the route.
96
+ var mcpNotForwarded = map[string]bool{
97
+ "accept": true,
98
+ "connection": true,
99
+ "content-length": true,
100
+ "content-type": true,
101
+ "mcp-protocol-version": true,
102
+ "mcp-session-id": true,
103
+ "transfer-encoding": true,
104
+ }
105
+
106
+ func mcpEnv(name, fallback string) string {
107
+ if v := os.Getenv(name); v != "" {
108
+ return v
109
+ }
110
+ return fallback
111
+ }
112
+
113
+ // The identity providers an MCP client can sign the user in with: every token issuer.
114
+ var mcpIssuers = []string{
115
+ <% it.issuers.forEach((p) => { %>
116
+ mcpEnv(<%~ JSON.stringify(p.env) %>, <%~ JSON.stringify(p.issuer) %>),
117
+ <% }) %>
118
+ }
119
+
120
+ func mcpFirst(v string) string {
121
+ return strings.TrimSpace(strings.Split(v, ",")[0])
122
+ }
123
+
124
+ // mcpResourceURL is the MCP endpoint's public URL: MCP_RESOURCE_URL, else
125
+ // what the request used.
126
+ func mcpResourceURL(c *gin.Context) string {
127
+ if v := os.Getenv("MCP_RESOURCE_URL"); v != "" {
128
+ return strings.TrimRight(v, "/")
129
+ }
130
+ proto := mcpFirst(c.GetHeader("X-Forwarded-Proto"))
131
+ if proto == "" {
132
+ proto = "http"
133
+ if c.Request.TLS != nil {
134
+ proto = "https"
135
+ }
136
+ }
137
+ host := mcpFirst(c.GetHeader("X-Forwarded-Host"))
138
+ if host == "" {
139
+ host = c.Request.Host
140
+ }
141
+ return proto + "://" + host + mcpPath
142
+ }
143
+
144
+ func mcpMetadataURL(c *gin.Context) string {
145
+ u, err := url.Parse(mcpResourceURL(c))
146
+ if err != nil {
147
+ return prmPath + mcpPath
148
+ }
149
+ return u.Scheme + "://" + u.Host + prmPath + u.Path
150
+ }
151
+
152
+ func mcpText(text string, isError bool) *mcp.CallToolResult {
153
+ return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: text}}, IsError: isError}
154
+ }
155
+
156
+ func mcpString(v interface{}) string {
157
+ if s, ok := v.(string); ok {
158
+ return s
159
+ }
160
+ return fmt.Sprint(v)
161
+ }
162
+
163
+ // mcpCall sends a tool call through the engine's own HTTP pipeline, in memory.
164
+ func mcpCall(ctx context.Context, engine http.Handler, base string, t MCPTool, req *mcp.CallToolRequest) *mcp.CallToolResult {
165
+ args := map[string]interface{}{}
166
+ if len(req.Params.Arguments) > 0 {
167
+ // Numbers keep their digits: a large id must not turn into 1e+21.
168
+ d := json.NewDecoder(bytes.NewReader(req.Params.Arguments))
169
+ d.UseNumber()
170
+ if err := d.Decode(&args); err != nil {
171
+ return mcpText("Arguments must be a JSON object", true)
172
+ }
173
+ }
174
+
175
+ missing := []string{}
176
+ parts := strings.Split(t.Path, "/")
177
+ for i, p := range parts {
178
+ if !strings.HasPrefix(p, ":") {
179
+ continue
180
+ }
181
+ v, ok := args[p[1:]]
182
+ if !ok || v == nil || v == "" {
183
+ missing = append(missing, p[1:])
184
+ continue
185
+ }
186
+ parts[i] = url.PathEscape(mcpString(v))
187
+ }
188
+ if len(missing) > 0 {
189
+ return mcpText("Missing "+strings.Join(missing, ", "), true)
190
+ }
191
+
192
+ query := url.Values{}
193
+ for _, key := range t.Query {
194
+ switch v := args[key].(type) {
195
+ case nil:
196
+ case []interface{}:
197
+ for _, item := range v {
198
+ query.Add(key, mcpString(item))
199
+ }
200
+ default:
201
+ query.Add(key, mcpString(v))
202
+ }
203
+ }
204
+ target := base + strings.Join(parts, "/")
205
+ if len(query) > 0 {
206
+ target += "?" + query.Encode()
207
+ }
208
+
209
+ var body io.Reader
210
+ if b, ok := args["body"]; ok && b != nil {
211
+ raw, err := json.Marshal(b)
212
+ if err != nil {
213
+ return mcpText("body is not valid JSON", true)
214
+ }
215
+ body = bytes.NewReader(raw)
216
+ }
217
+ httpReq, err := http.NewRequestWithContext(ctx, t.Method, target, body)
218
+ if err != nil {
219
+ return mcpText(err.Error(), true)
220
+ }
221
+ // No caller headers means no credentials, and the route refuses the call.
222
+ if req.Extra != nil {
223
+ for key, values := range req.Extra.Header {
224
+ if !mcpNotForwarded[strings.ToLower(key)] {
225
+ httpReq.Header[key] = values
226
+ }
227
+ }
228
+ }
229
+ httpReq.Header.Set("Accept", "application/json")
230
+ if body != nil {
231
+ httpReq.Header.Set("Content-Type", "application/json")
232
+ }
233
+
234
+ rec := httptest.NewRecorder()
235
+ engine.ServeHTTP(rec, httpReq)
236
+ text := rec.Body.String()
237
+ if text == "" {
238
+ text = fmt.Sprintf("HTTP %d", rec.Code)
239
+ }
240
+ return mcpText(text, rec.Code >= 400)
241
+ }
242
+
243
+ // MountMCP serves the tools at POST /mcp on the engine. api is the group the
244
+ // routes are registered on. Call it after RegisterAllRoutes.
245
+ func MountMCP(r *gin.Engine, api *gin.RouterGroup) {
246
+ server := mcp.NewServer(&mcp.Implementation{Name: "api", Version: "1.0"}, nil)
247
+ seen := map[string]bool{}
248
+ for _, t := range mcpTools {
249
+ t := t
250
+ if seen[t.Name] {
251
+ panic(fmt.Sprintf("MCP tool %s %s: another tool is already named %q", t.Method, t.Path, t.Name))
252
+ }
253
+ seen[t.Name] = true
254
+ destructive := t.Method == http.MethodDelete
255
+ server.AddTool(&mcp.Tool{
256
+ Name: t.Name,
257
+ Description: t.Description,
258
+ InputSchema: t.InputSchema,
259
+ Annotations: &mcp.ToolAnnotations{ReadOnlyHint: t.Method == http.MethodGet, DestructiveHint: &destructive},
260
+ }, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
261
+ return mcpCall(ctx, r, api.BasePath(), t, req), nil
262
+ })
263
+ }
264
+ handler := mcp.NewStreamableHTTPHandler(
265
+ func(*http.Request) *mcp.Server { return server },
266
+ &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true},
267
+ )
268
+
269
+ r.Any(mcpPath,
270
+ func(c *gin.Context) {
271
+ if c.Request.Method != http.MethodPost {
272
+ c.Header("Allow", http.MethodPost)
273
+ c.AbortWithStatus(http.StatusMethodNotAllowed)
274
+ return
275
+ }
276
+ // The 401 is what starts sign-in: it points the client at the
277
+ // metadata. Set before the auth check answers, cleared once it passes.
278
+ if c.GetHeader("x-api-key") == "" && c.GetHeader("x-apso-service-token") == "" {
279
+ challenge := `Bearer resource_metadata="` + mcpMetadataURL(c) + `"`
280
+ if c.GetHeader("Authorization") != "" {
281
+ challenge += `, error="invalid_token"`
282
+ }
283
+ c.Header("WWW-Authenticate", challenge)
284
+ }
285
+ },
286
+ // The same check every /api route runs: API key, then the user's token.
287
+ middleware.AuthMiddleware(nil),
288
+ func(c *gin.Context) {
289
+ c.Writer.Header().Del("WWW-Authenticate")
290
+ handler.ServeHTTP(c.Writer, c.Request)
291
+ },
292
+ )
293
+
294
+ // Tells an MCP client where to sign in. Public by design, and readable
295
+ // from a browser-based client on another origin.
296
+ metadata := func(c *gin.Context) {
297
+ c.Header("Access-Control-Allow-Origin", "*")
298
+ c.Header("Cache-Control", "max-age=300")
299
+ c.JSON(http.StatusOK, gin.H{
300
+ "resource": mcpResourceURL(c),
301
+ "authorization_servers": mcpIssuers,
302
+ "bearer_methods_supported": []string{"header"},
303
+ })
304
+ }
305
+ r.GET(prmPath, metadata)
306
+ r.GET(prmPath+mcpPath, metadata)
307
+ }