@apso/cli 0.48.0 → 0.49.1

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 (82) 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 +49 -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/deploy/server-push.js +3 -1
  29. package/dist/lib/generators/go.d.ts +13 -1
  30. package/dist/lib/generators/go.js +144 -33
  31. package/dist/lib/generators/python.d.ts +3 -3
  32. package/dist/lib/generators/python.js +48 -24
  33. package/dist/lib/generators/typescript.d.ts +3 -5
  34. package/dist/lib/generators/typescript.js +78 -64
  35. package/dist/lib/guards.d.ts +111 -13
  36. package/dist/lib/guards.js +287 -23
  37. package/dist/lib/templates/go/handlers/handler.eta +8 -8
  38. package/dist/lib/templates/go/handlers/scope.eta +3 -2
  39. package/dist/lib/templates/go/index-module.eta +8 -5
  40. package/dist/lib/templates/go/mcp.eta +307 -0
  41. package/dist/lib/templates/go/middleware/auth.eta +587 -166
  42. package/dist/lib/templates/go/middleware/permission.eta +174 -0
  43. package/dist/lib/templates/go/services/service.eta +37 -16
  44. package/dist/lib/templates/go/utils/query.eta +37 -2
  45. package/dist/lib/templates/guards/guards.module.eta +37 -29
  46. package/dist/lib/templates/guards/index.eta +4 -0
  47. package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
  48. package/dist/lib/templates/guards/key.guard.eta +280 -0
  49. package/dist/lib/templates/guards/permission.guard.eta +168 -0
  50. package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
  51. package/dist/lib/templates/guards/scope.guard.eta +189 -41
  52. package/dist/lib/templates/python/auth.eta +354 -95
  53. package/dist/lib/templates/python/index-module.eta +7 -7
  54. package/dist/lib/templates/python/mcp.eta +284 -0
  55. package/dist/lib/templates/python/models/model.eta +6 -5
  56. package/dist/lib/templates/python/permissions.eta +121 -0
  57. package/dist/lib/templates/python/routers/router.eta +39 -1
  58. package/dist/lib/templates/python/schemas/schema.eta +18 -5
  59. package/dist/lib/templates/python/services/service.eta +38 -15
  60. package/dist/lib/templates/python/utils/query.eta +52 -25
  61. package/dist/lib/templates/rest/controller-rest.eta +43 -23
  62. package/dist/lib/templates/rest/index-module-rest.eta +0 -4
  63. package/dist/lib/templates/rest/service-rest.eta +3 -44
  64. package/dist/lib/types/auth.d.ts +84 -80
  65. package/dist/lib/types/auth.js +77 -60
  66. package/dist/lib/types/entity.d.ts +17 -9
  67. package/dist/lib/types/entity.js +3 -0
  68. package/dist/lib/types/index.d.ts +2 -2
  69. package/dist/lib/types/index.js +6 -5
  70. package/dist/lib/utils/crud-deps.d.ts +77 -6
  71. package/dist/lib/utils/crud-deps.js +197 -14
  72. package/dist/lib/utils/schema-convert.d.ts +20 -43
  73. package/dist/lib/utils/schema-convert.js +28 -78
  74. package/dist/lib/utils/template.d.ts +11 -0
  75. package/dist/lib/utils/template.js +36 -1
  76. package/dist/lib/verify/index.d.ts +6 -1
  77. package/dist/lib/verify/index.js +30 -13
  78. package/npm-shrinkwrap.json +2 -2
  79. package/oclif.manifest.json +36 -1
  80. package/package.json +1 -1
  81. package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
  82. package/dist/lib/templates/guards/auth.guard.eta +0 -233
@@ -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
+ }