@apso/cli 0.50.0 → 0.51.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.
- package/README.md +20 -0
- package/dist/commands/generate.js +2 -2
- package/dist/lib/access/rules.json +9 -2
- package/dist/lib/generators/go.js +3 -1
- package/dist/lib/generators/python.js +6 -2
- package/dist/lib/generators/typescript.js +5 -4
- package/dist/lib/guards.d.ts +3 -1
- package/dist/lib/guards.js +4 -5
- package/dist/lib/templates/go/mcp.eta +103 -53
- package/dist/lib/templates/go/middleware/auth.eta +7 -2
- package/dist/lib/templates/guards/guards.module.eta +4 -1
- package/dist/lib/templates/guards/key.guard.eta +66 -14
- package/dist/lib/templates/python/auth.eta +10 -2
- package/dist/lib/templates/python/mcp.eta +83 -39
- package/dist/lib/types/entity.d.ts +4 -3
- package/dist/lib/utils/crud-deps.d.ts +4 -1
- package/dist/lib/utils/crud-deps.js +7 -4
- package/dist/lib/utils/relationships/parse.js +8 -0
- package/dist/lib/utils/template.d.ts +5 -3
- package/dist/lib/utils/template.js +6 -4
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -134,6 +134,26 @@ curl -i -H "x-api-key: $APSO_API_KEY" -H "Prefer: count=exact" "http://localhost
|
|
|
134
134
|
|
|
135
135
|
The full list of what is supported and what is refused is in the `@apso/crud` package, in `docs/DIALECTS.md`. Python and Go services accept this syntax and, for now, the nestjsx syntax as well.
|
|
136
136
|
|
|
137
|
+
## MCP tools on a generated API
|
|
138
|
+
|
|
139
|
+
Add `mcp` to an entity in `.apsorc` and its routes are served as MCP tools. `"mcp": true` exposes read, create, update and delete. A list such as `["read"]` exposes only those.
|
|
140
|
+
|
|
141
|
+
A service has two MCP addresses, in TypeScript, Python and Go:
|
|
142
|
+
|
|
143
|
+
| Address | Who it is for | Credential |
|
|
144
|
+
|---------|---------------|------------|
|
|
145
|
+
| `/mcp/internal` | Your team, agents and scripts | The service's API key in `x-api-key` |
|
|
146
|
+
| `/mcp` | Your app's end users | A token from the sign-in provider in the `auth` block |
|
|
147
|
+
|
|
148
|
+
- `/mcp/internal` exists whenever an entity has `mcp`. It does not need an `auth` block. A caller there is a service caller: every tool, no tenant scope.
|
|
149
|
+
- `/mcp` exists only when `.apsorc` has an `auth` block. A caller there is the signed-in user, under the same scope and permission rules as REST. An API key is not accepted there.
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
claude mcp add --transport http my-api http://localhost:3000/mcp/internal --header "x-api-key: $APSO_API_KEY"
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Set `MCP_RESOURCE_URL` to the public URL of `/mcp` when the service runs behind a proxy. Details are in [docs/access-rules.md](docs/access-rules.md#mcp-addresses).
|
|
156
|
+
|
|
137
157
|
## Commands
|
|
138
158
|
|
|
139
159
|
| Command | Subcommands | Description |
|
|
@@ -278,7 +278,7 @@ class Generate extends base_command_1.default {
|
|
|
278
278
|
if (language === "typescript" && entities.some((entity) => entity.mcp)) {
|
|
279
279
|
const wired = (0, crud_deps_1.ensureMcpWiring)(process.cwd(), rootFolder);
|
|
280
280
|
if (wired.length > 0)
|
|
281
|
-
console.log(`[apso] Set up MCP tools at /mcp (updated ${wired.join(", ")}). Run npm install before building.`);
|
|
281
|
+
console.log(`[apso] Set up MCP tools at /mcp/internal for API keys, and at /mcp for signed-in users when .apsorc has an auth block (updated ${wired.join(", ")}). Run npm install before building.`);
|
|
282
282
|
}
|
|
283
283
|
if ((language === "python" || language === "go") &&
|
|
284
284
|
!entities.some((entity) => entity.mcp)) {
|
|
@@ -290,7 +290,7 @@ class Generate extends base_command_1.default {
|
|
|
290
290
|
entities.some((entity) => entity.mcp)) {
|
|
291
291
|
const wired = (0, crud_deps_1.ensureAppMcpWiring)(process.cwd(), language);
|
|
292
292
|
if (wired.length > 0)
|
|
293
|
-
console.log(`[apso] Set up MCP tools at /mcp (updated ${wired.join(", ")}). ${language === "python"
|
|
293
|
+
console.log(`[apso] Set up MCP tools at /mcp/internal for API keys, and at /mcp for signed-in users when .apsorc has an auth block (updated ${wired.join(", ")}). ${language === "python"
|
|
294
294
|
? "Reinstall the project's dependencies."
|
|
295
295
|
: "Run go mod tidy before building; the MCP SDK needs Go 1.25."}`);
|
|
296
296
|
}
|
|
@@ -160,7 +160,7 @@
|
|
|
160
160
|
{
|
|
161
161
|
"id": "R22",
|
|
162
162
|
"group": "MCP",
|
|
163
|
-
"rule": "When sign-in is configured, every MCP
|
|
163
|
+
"rule": "When sign-in is configured, every request to the external MCP address (`/mcp`) needs a valid token issued for it, including listing tools.",
|
|
164
164
|
"status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
|
|
165
165
|
},
|
|
166
166
|
{
|
|
@@ -194,7 +194,7 @@
|
|
|
194
194
|
{
|
|
195
195
|
"id": "R27",
|
|
196
196
|
"group": "Build time",
|
|
197
|
-
"rule": "A schema that cannot be enforced fails at generate:
|
|
197
|
+
"rule": "A schema that cannot be enforced fails at generate: permissions without sign-in, an unprotected grants entity. A tenant scope whose provider maps no tenant claim does not fail: generate warns, and at run time a token with no tenant gets the \"no tenant\" 403 on tenant-scoped entities, in every language.",
|
|
198
198
|
"status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
|
|
199
199
|
},
|
|
200
200
|
{
|
|
@@ -202,6 +202,13 @@
|
|
|
202
202
|
"group": "Service callers",
|
|
203
203
|
"rule": "The auth entities answer a service caller only. With the `better-auth` provider these are the session, user and membership entities named in the `auth` block, plus Better Auth's other tables. A signed-in user is refused on every one of their routes, no other entity's route loads them through a join or an embed, and `apso generate` refuses `mcp` on them.",
|
|
204
204
|
"status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
|
|
205
|
+
},
|
|
206
|
+
{
|
|
207
|
+
"id": "R29",
|
|
208
|
+
"group": "MCP",
|
|
209
|
+
"rule": "MCP tools have one address per audience. `/mcp/internal` exists whenever an entity has `mcp`, with or without sign-in, and answers service callers only: an API key, or the gateway's service token for a key or an Apso user. A user token is not a credential there. `/mcp` exists only when sign-in is configured and answers signed-in users only: an API key or a service token is not a credential there and does not reach the route a tool calls.",
|
|
210
|
+
"status": { "typescript": "enforced", "python": "enforced", "go": "enforced" },
|
|
211
|
+
"issue": "apsoai/cli#232"
|
|
205
212
|
}
|
|
206
213
|
]
|
|
207
214
|
}
|
|
@@ -703,7 +703,9 @@ ${modelRefs}
|
|
|
703
703
|
}),
|
|
704
704
|
});
|
|
705
705
|
}
|
|
706
|
-
// The
|
|
706
|
+
// The MCP addresses; cmd/main.go mounts them (see ensureGoMcpWiring).
|
|
707
|
+
// The external one, /mcp, is served when there is an issuer to sign in
|
|
708
|
+
// with; /mcp/internal takes the API key.
|
|
707
709
|
if (tools.length > 0)
|
|
708
710
|
files.push({
|
|
709
711
|
path: "routes/mcp.go",
|
|
@@ -579,9 +579,13 @@ ${downStatements || " pass"}
|
|
|
579
579
|
path: "permissions.py",
|
|
580
580
|
content: await this.renderTemplate("./permissions", { permissions }),
|
|
581
581
|
});
|
|
582
|
-
// The
|
|
582
|
+
// The MCP addresses; app/main.py mounts them (see ensurePythonMcpWiring).
|
|
583
|
+
// The external one, /mcp, needs sign-in; /mcp/internal takes the API key.
|
|
583
584
|
if (mcp)
|
|
584
|
-
files.push({
|
|
585
|
+
files.push({
|
|
586
|
+
path: "mcp.py",
|
|
587
|
+
content: await this.renderTemplate("./mcp", { external: Boolean(data.jwt) }),
|
|
588
|
+
});
|
|
585
589
|
return files;
|
|
586
590
|
}
|
|
587
591
|
async generateQueryUtils(_entities, _apiType) {
|
|
@@ -162,8 +162,6 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
|
|
|
162
162
|
bypassRoles: scoped.bypassRoles,
|
|
163
163
|
};
|
|
164
164
|
const mcp = (0, guards_1.mcpOperations)(entity);
|
|
165
|
-
if (mcp.length > 0 && !auth)
|
|
166
|
-
throw new Error(`${entityName}.mcp needs an auth block in .apsorc: MCP tools act as the signed-in caller`);
|
|
167
165
|
const data = {
|
|
168
166
|
svcName,
|
|
169
167
|
ctrlName,
|
|
@@ -382,6 +380,7 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
|
|
|
382
380
|
}
|
|
383
381
|
const scopedEntities = (0, guards_1.getScopedEntities)(entities, relationshipMap);
|
|
384
382
|
const files = [];
|
|
383
|
+
const mcp = entities.some((e) => (0, guards_1.mcpOperations)(e).length > 0);
|
|
385
384
|
const templateData = {
|
|
386
385
|
scopedEntities,
|
|
387
386
|
// Every entity by route: the scope guard checks relations in write bodies.
|
|
@@ -394,8 +393,10 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
|
|
|
394
393
|
authRoutes: (0, guards_1.authEntityRoutes)(entities, auth),
|
|
395
394
|
jwt,
|
|
396
395
|
permissions,
|
|
397
|
-
//
|
|
398
|
-
|
|
396
|
+
// MCP tools are served at /mcp/internal for service callers, and at /mcp
|
|
397
|
+
// for signed-in users when there is sign-in: tokens come from the listed issuers.
|
|
398
|
+
mcp,
|
|
399
|
+
mcpAuth: hasAuth && mcp,
|
|
399
400
|
};
|
|
400
401
|
// The API key check is part of every service.
|
|
401
402
|
files.push({
|
package/dist/lib/guards.d.ts
CHANGED
|
@@ -66,8 +66,10 @@ export declare const authEntityRoutes: (entities: Entity[], auth?: AuthConfig) =
|
|
|
66
66
|
/**
|
|
67
67
|
* An entity's MCP operations and the names its tools get, the same in every
|
|
68
68
|
* language: list_line_items, get_line_item, create_line_item and so on.
|
|
69
|
+
* `mcp` does not need an auth block: without one the tools are served to
|
|
70
|
+
* service callers only. The second argument is no longer read.
|
|
69
71
|
*/
|
|
70
|
-
export declare function mcpToolNames(entity: Entity,
|
|
72
|
+
export declare function mcpToolNames(entity: Entity, _auth?: AuthConfig): {
|
|
71
73
|
mcp: ("create" | "update" | "delete" | "read")[];
|
|
72
74
|
mcpName: string;
|
|
73
75
|
mcpPluralName: string;
|
package/dist/lib/guards.js
CHANGED
|
@@ -183,13 +183,12 @@ exports.authEntityRoutes = authEntityRoutes;
|
|
|
183
183
|
/**
|
|
184
184
|
* An entity's MCP operations and the names its tools get, the same in every
|
|
185
185
|
* language: list_line_items, get_line_item, create_line_item and so on.
|
|
186
|
+
* `mcp` does not need an auth block: without one the tools are served to
|
|
187
|
+
* service callers only. The second argument is no longer read.
|
|
186
188
|
*/
|
|
187
|
-
function mcpToolNames(entity,
|
|
188
|
-
const mcp = mcpOperations(entity);
|
|
189
|
-
if (mcp.length > 0 && !auth)
|
|
190
|
-
throw new Error(`${entity.name}.mcp needs an auth block in .apsorc: MCP tools act as the signed-in caller`);
|
|
189
|
+
function mcpToolNames(entity, _auth) {
|
|
191
190
|
return {
|
|
192
|
-
mcp,
|
|
191
|
+
mcp: mcpOperations(entity),
|
|
193
192
|
mcpName: (0, casing_1.snakeCase)(entity.name),
|
|
194
193
|
mcpPluralName: (0, casing_1.snakeCase)((0, pluralize_1.default)(entity.name)),
|
|
195
194
|
};
|
|
@@ -2,8 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
package routes
|
|
4
4
|
|
|
5
|
-
// MCP tools
|
|
6
|
-
//
|
|
5
|
+
// MCP tools (Streamable HTTP, stateless), served with the official MCP SDK for
|
|
6
|
+
// Go at two addresses, one per audience:
|
|
7
|
+
//
|
|
8
|
+
<% if (it.issuers.length > 0) { %>
|
|
9
|
+
// - /mcp, the external address, for your end users. It takes a signed-in
|
|
10
|
+
// user's token in Authorization: Bearer and nothing else: an API key is
|
|
11
|
+
// not read here.
|
|
12
|
+
<% } else { %>
|
|
13
|
+
// - /mcp, the external address, for your end users, is not served: .apsorc
|
|
14
|
+
// has no auth block to sign them in with.
|
|
15
|
+
<% } %>
|
|
16
|
+
// - /mcp/internal, for your own team, agents and scripts. It takes the
|
|
17
|
+
// service's API key (the same key source as the REST routes) and nothing
|
|
18
|
+
// else: the Authorization header is not read here. The caller is a
|
|
19
|
+
// service caller.
|
|
7
20
|
//
|
|
8
21
|
// A tool is a route. When an agent calls a tool, the request is sent through
|
|
9
22
|
// the Gin engine in memory with the caller's headers, so authentication,
|
|
@@ -14,10 +27,18 @@ package routes
|
|
|
14
27
|
// written here from .apsorc: path and query parameters are top-level
|
|
15
28
|
// arguments, the JSON body is the "body" argument.
|
|
16
29
|
//
|
|
17
|
-
// Every request
|
|
18
|
-
// with no valid credential gets
|
|
19
|
-
|
|
20
|
-
//
|
|
30
|
+
// Every request passes the service's own auth check first, on the credential
|
|
31
|
+
// its address reads. A request with no valid credential gets a 401.
|
|
32
|
+
<% if (it.issuers.length > 0) { %>
|
|
33
|
+
// On /mcp that 401 starts OAuth sign-in in an MCP client, and
|
|
34
|
+
// /.well-known/oauth-protected-resource names the identity provider (RFC 9728).
|
|
35
|
+
<% } %>
|
|
36
|
+
//
|
|
37
|
+
// When APSO_INTERNAL_AUTH_ISSUER is set (the platform sets it), the 401 on
|
|
38
|
+
// /mcp/internal starts an Apso sign-in the same way, and
|
|
39
|
+
// /.well-known/oauth-protected-resource/mcp/internal names that issuer. The
|
|
40
|
+
// platform's gateway turns the Apso token into the service token this service
|
|
41
|
+
// checks.
|
|
21
42
|
//
|
|
22
43
|
// Serve your own route as a tool by calling RegisterMCPTool before MountMCP.
|
|
23
44
|
|
|
@@ -87,8 +108,9 @@ func RegisterMCPTool(t MCPTool) {
|
|
|
87
108
|
}
|
|
88
109
|
|
|
89
110
|
const (
|
|
90
|
-
mcpPath
|
|
91
|
-
|
|
111
|
+
mcpPath = "/mcp"
|
|
112
|
+
mcpInternal = "/internal"
|
|
113
|
+
prmPath = "/.well-known/oauth-protected-resource"
|
|
92
114
|
)
|
|
93
115
|
|
|
94
116
|
// Headers that describe the MCP request itself, not the caller. Everything
|
|
@@ -103,6 +125,7 @@ var mcpNotForwarded = map[string]bool{
|
|
|
103
125
|
"transfer-encoding": true,
|
|
104
126
|
}
|
|
105
127
|
|
|
128
|
+
<% if (it.issuers.length > 0) { %>
|
|
106
129
|
func mcpEnv(name, fallback string) string {
|
|
107
130
|
if v := os.Getenv(name); v != "" {
|
|
108
131
|
return v
|
|
@@ -116,16 +139,18 @@ var mcpIssuers = []string{
|
|
|
116
139
|
mcpEnv(<%~ JSON.stringify(p.env) %>, <%~ JSON.stringify(p.issuer) %>),
|
|
117
140
|
<% }) %>
|
|
118
141
|
}
|
|
142
|
+
<% } %>
|
|
119
143
|
|
|
120
144
|
func mcpFirst(v string) string {
|
|
121
145
|
return strings.TrimSpace(strings.Split(v, ",")[0])
|
|
122
146
|
}
|
|
123
147
|
|
|
124
|
-
// mcpResourceURL is
|
|
125
|
-
//
|
|
126
|
-
|
|
148
|
+
// mcpResourceURL is an MCP address's public URL: from MCP_RESOURCE_URL (the
|
|
149
|
+
// external address; the internal one is that + /internal), else from what the
|
|
150
|
+
// request used. suffix is "" or mcpInternal.
|
|
151
|
+
func mcpResourceURL(c *gin.Context, suffix string) string {
|
|
127
152
|
if v := os.Getenv("MCP_RESOURCE_URL"); v != "" {
|
|
128
|
-
return strings.TrimRight(v, "/")
|
|
153
|
+
return strings.TrimRight(v, "/") + suffix
|
|
129
154
|
}
|
|
130
155
|
proto := mcpFirst(c.GetHeader("X-Forwarded-Proto"))
|
|
131
156
|
if proto == "" {
|
|
@@ -138,13 +163,20 @@ func mcpResourceURL(c *gin.Context) string {
|
|
|
138
163
|
if host == "" {
|
|
139
164
|
host = c.Request.Host
|
|
140
165
|
}
|
|
141
|
-
return proto + "://" + host + mcpPath
|
|
166
|
+
return proto + "://" + host + mcpPath + suffix
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// mcpMetadata is an address's protected resource metadata (RFC 9728).
|
|
170
|
+
type mcpMetadata struct {
|
|
171
|
+
Resource string `json:"resource"`
|
|
172
|
+
AuthorizationServers []string `json:"authorization_servers"`
|
|
173
|
+
BearerMethodsSupported []string `json:"bearer_methods_supported"`
|
|
142
174
|
}
|
|
143
175
|
|
|
144
|
-
func mcpMetadataURL(c *gin.Context) string {
|
|
145
|
-
u, err := url.Parse(mcpResourceURL(c))
|
|
176
|
+
func mcpMetadataURL(c *gin.Context, suffix string) string {
|
|
177
|
+
u, err := url.Parse(mcpResourceURL(c, suffix))
|
|
146
178
|
if err != nil {
|
|
147
|
-
return prmPath + mcpPath
|
|
179
|
+
return prmPath + mcpPath + suffix
|
|
148
180
|
}
|
|
149
181
|
return u.Scheme + "://" + u.Host + prmPath + u.Path
|
|
150
182
|
}
|
|
@@ -240,8 +272,8 @@ func mcpCall(ctx context.Context, engine http.Handler, base string, t MCPTool, r
|
|
|
240
272
|
return mcpText(text, rec.Code >= 400)
|
|
241
273
|
}
|
|
242
274
|
|
|
243
|
-
// MountMCP serves the tools
|
|
244
|
-
//
|
|
275
|
+
// MountMCP serves the tools on the engine. api is the group the routes are
|
|
276
|
+
// registered on. Call it after RegisterAllRoutes.
|
|
245
277
|
func MountMCP(r *gin.Engine, api *gin.RouterGroup) {
|
|
246
278
|
server := mcp.NewServer(&mcp.Implementation{Name: "api", Version: "1.0"}, nil)
|
|
247
279
|
seen := map[string]bool{}
|
|
@@ -266,42 +298,60 @@ func MountMCP(r *gin.Engine, api *gin.RouterGroup) {
|
|
|
266
298
|
&mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true},
|
|
267
299
|
)
|
|
268
300
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
if c.GetHeader("Authorization") != "" {
|
|
281
|
-
challenge += `, error="invalid_token"`
|
|
301
|
+
// serve mounts one address: /mcp (suffix "") or /mcp/internal. ignored is
|
|
302
|
+
// the credential it does not read: a user's token on the internal one, a
|
|
303
|
+
// key on the external one. It is dropped before the auth check, so a
|
|
304
|
+
// tool's route never sees it either.
|
|
305
|
+
serve := func(suffix string, challenge bool, ignored ...string) {
|
|
306
|
+
r.Any(mcpPath+suffix,
|
|
307
|
+
func(c *gin.Context) {
|
|
308
|
+
if c.Request.Method != http.MethodPost {
|
|
309
|
+
c.Header("Allow", http.MethodPost)
|
|
310
|
+
c.AbortWithStatus(http.StatusMethodNotAllowed)
|
|
311
|
+
return
|
|
282
312
|
}
|
|
283
|
-
c.
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
313
|
+
sentToken := c.GetHeader("Authorization") != ""
|
|
314
|
+
for _, name := range ignored {
|
|
315
|
+
c.Request.Header.Del(name)
|
|
316
|
+
}
|
|
317
|
+
// The 401 is what starts sign-in: it points the client at the
|
|
318
|
+
// metadata. Set before the auth check answers, cleared once it passes.
|
|
319
|
+
if challenge {
|
|
320
|
+
value := `Bearer resource_metadata="` + mcpMetadataURL(c, suffix) + `"`
|
|
321
|
+
if sentToken {
|
|
322
|
+
value += `, error="invalid_token"`
|
|
323
|
+
}
|
|
324
|
+
c.Header("WWW-Authenticate", value)
|
|
325
|
+
}
|
|
326
|
+
},
|
|
327
|
+
// The same check every /api route runs, on what is left: only a key
|
|
328
|
+
// can pass on the internal address, only a user's token on the external one.
|
|
329
|
+
middleware.AuthMiddleware(nil),
|
|
330
|
+
func(c *gin.Context) {
|
|
331
|
+
c.Writer.Header().Del("WWW-Authenticate")
|
|
332
|
+
handler.ServeHTTP(c.Writer, c.Request)
|
|
333
|
+
},
|
|
334
|
+
)
|
|
335
|
+
}
|
|
336
|
+
// metadata tells an MCP client where to sign in. Public by design, and
|
|
337
|
+
// readable from a browser-based client on another origin.
|
|
338
|
+
metadata := func(suffix string, issuers []string) gin.HandlerFunc {
|
|
339
|
+
return func(c *gin.Context) {
|
|
340
|
+
c.Header("Access-Control-Allow-Origin", "*")
|
|
341
|
+
c.Header("Cache-Control", "max-age=300")
|
|
342
|
+
c.JSON(http.StatusOK, mcpMetadata{mcpResourceURL(c, suffix), issuers, []string{"header"}})
|
|
343
|
+
}
|
|
344
|
+
}
|
|
293
345
|
|
|
294
|
-
//
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
c.JSON(http.StatusOK, gin.H{
|
|
300
|
-
"resource": mcpResourceURL(c),
|
|
301
|
-
"authorization_servers": mcpIssuers,
|
|
302
|
-
"bearer_methods_supported": []string{"header"},
|
|
303
|
-
})
|
|
346
|
+
// Where an MCP client signs in to Apso for the internal address.
|
|
347
|
+
internalIssuer := os.Getenv("APSO_INTERNAL_AUTH_ISSUER")
|
|
348
|
+
serve(mcpInternal, internalIssuer != "", "Authorization")
|
|
349
|
+
if internalIssuer != "" {
|
|
350
|
+
r.GET(prmPath+mcpPath+mcpInternal, metadata(mcpInternal, []string{internalIssuer}))
|
|
304
351
|
}
|
|
305
|
-
|
|
306
|
-
|
|
352
|
+
<% if (it.issuers.length > 0) { %>
|
|
353
|
+
serve("", true, "x-api-key", "x-apso-service-token")
|
|
354
|
+
r.GET(prmPath, metadata("", mcpIssuers))
|
|
355
|
+
r.GET(prmPath+mcpPath, metadata("", mcpIssuers))
|
|
356
|
+
<% } %>
|
|
307
357
|
}
|
|
@@ -198,8 +198,10 @@ func chooseKeySource() *keySource {
|
|
|
198
198
|
return s
|
|
199
199
|
}
|
|
200
200
|
|
|
201
|
-
// keyID returns the
|
|
202
|
-
//
|
|
201
|
+
// keyID returns the caller from the gateway's token: the key id of sub
|
|
202
|
+
// "apikey:<id>", or sub "user:<id>" as it is, an Apso sign-in the gateway
|
|
203
|
+
// checked (it sends one for /mcp/internal only). It is "" when the token is
|
|
204
|
+
// not valid for this service.
|
|
203
205
|
func (s *keySource) keyID(token string) string {
|
|
204
206
|
if token == "" || s.issuer == "" || s.serviceID == "" {
|
|
205
207
|
return ""
|
|
@@ -218,6 +220,9 @@ func (s *keySource) keyID(token string) string {
|
|
|
218
220
|
if err != nil || !parsed.Valid {
|
|
219
221
|
return ""
|
|
220
222
|
}
|
|
223
|
+
if user, ok := strings.CutPrefix(claims.Subject, "user:"); ok && user != "" {
|
|
224
|
+
return claims.Subject
|
|
225
|
+
}
|
|
221
226
|
id, _ := strings.CutPrefix(claims.Subject, "apikey:")
|
|
222
227
|
if id == claims.Subject {
|
|
223
228
|
return ""
|
|
@@ -7,7 +7,7 @@ import { APP_GUARD } from '@nestjs/core';
|
|
|
7
7
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
8
8
|
import { ScopeGuard } from './scope.guard';
|
|
9
9
|
<% } %>
|
|
10
|
-
import { ApiKeyGuard<% if (it.mcpAuth) { %>, McpAuthProvider<% } %> } from './key.guard';
|
|
10
|
+
import { ApiKeyGuard<% if (it.mcp) { %>, McpInternalAuthProvider<% } %><% if (it.mcpAuth) { %>, McpAuthProvider<% } %> } from './key.guard';
|
|
11
11
|
<% if (it.hasAuth) { %>
|
|
12
12
|
import { AuthGuard } from './auth.guard';
|
|
13
13
|
<% } %>
|
|
@@ -73,6 +73,9 @@ import { <%= entity.name %> } from '../<%= entity.name %>/<%= entity.name %>.ent
|
|
|
73
73
|
<% if (it.hasAuth) { %>
|
|
74
74
|
AuthGuard,
|
|
75
75
|
<% } %>
|
|
76
|
+
<% if (it.mcp) { %>
|
|
77
|
+
McpInternalAuthProvider,
|
|
78
|
+
<% } %>
|
|
76
79
|
<% if (it.mcpAuth) { %>
|
|
77
80
|
McpAuthProvider,
|
|
78
81
|
<% } %>
|
|
@@ -15,6 +15,9 @@
|
|
|
15
15
|
* A caller with a valid key is a service caller (request.auth.serviceId): it
|
|
16
16
|
* may call any route, is not tenant-scoped and skips role permission checks.
|
|
17
17
|
* A request whose key fails is refused, whatever else it carries.
|
|
18
|
+
* The gateway's token names an API key (sub "apikey:<id>") or, for a member
|
|
19
|
+
* of the Apso workspace signed in to /mcp/internal, that user (sub
|
|
20
|
+
* "user:<id>"). Both are service callers.
|
|
18
21
|
*
|
|
19
22
|
* For logging, the guards record who is calling on request.apso.caller and
|
|
20
23
|
* why a request was refused on request.apso.denied.
|
|
@@ -53,7 +56,10 @@ export const Public =
|
|
|
53
56
|
|
|
54
57
|
/** What request.auth holds for a caller that presented a valid API key. */
|
|
55
58
|
export interface ServiceCaller {
|
|
56
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* The key's id: from the platform, or the first 8 hex digits of its SHA-256.
|
|
61
|
+
* For an Apso user the gateway vouches for, "user:<Apso user id>".
|
|
62
|
+
*/
|
|
57
63
|
serviceId: string;
|
|
58
64
|
roles: string[];
|
|
59
65
|
permissions: string[];
|
|
@@ -164,14 +170,31 @@ export class ApiKeyGuard implements CanActivate {
|
|
|
164
170
|
this.refuse(request, NO_SOURCE, 'no key source');
|
|
165
171
|
<% } %>
|
|
166
172
|
}
|
|
167
|
-
<% if (it.
|
|
173
|
+
<% if (it.mcp) { %>
|
|
168
174
|
|
|
169
|
-
/**
|
|
170
|
-
|
|
175
|
+
/**
|
|
176
|
+
* The check on /mcp/internal: service callers only, through the same key
|
|
177
|
+
* source as the REST routes. A user's token is not a credential there.
|
|
178
|
+
*/
|
|
179
|
+
async authenticateInternal(request: any): Promise<unknown> {
|
|
171
180
|
this.requestId(request);
|
|
172
181
|
if (await this.serviceCaller(request)) {
|
|
173
182
|
return request.auth;
|
|
174
183
|
}
|
|
184
|
+
if (this.keys.length > 0 || this.jwks) {
|
|
185
|
+
this.refuse(request, NO_CREDENTIAL, 'no credential');
|
|
186
|
+
}
|
|
187
|
+
this.refuse(request, NO_SOURCE, 'no key source');
|
|
188
|
+
}
|
|
189
|
+
<% } %>
|
|
190
|
+
<% if (it.mcpAuth) { %>
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* The check on /mcp: a signed-in user's token only. An API key or a service
|
|
194
|
+
* token is not a credential there and never makes the caller a service caller.
|
|
195
|
+
*/
|
|
196
|
+
async authenticate(request: any): Promise<unknown> {
|
|
197
|
+
this.requestId(request);
|
|
175
198
|
const auth = await this.authGuard.authenticate(request);
|
|
176
199
|
this.userCaller(request);
|
|
177
200
|
return auth;
|
|
@@ -199,6 +222,8 @@ export class ApiKeyGuard implements CanActivate {
|
|
|
199
222
|
private async serviceCaller(request: any): Promise<boolean> {
|
|
200
223
|
const key = request.headers['x-api-key'];
|
|
201
224
|
let serviceId: string | undefined;
|
|
225
|
+
// Set when the gateway's token names an Apso user instead of a key.
|
|
226
|
+
let userId: string | undefined;
|
|
202
227
|
if (this.keys.length > 0) {
|
|
203
228
|
if (!key) return false;
|
|
204
229
|
const digest = sha256(String(key));
|
|
@@ -209,20 +234,25 @@ export class ApiKeyGuard implements CanActivate {
|
|
|
209
234
|
} else if (this.jwks) {
|
|
210
235
|
const token = request.headers['x-apso-service-token'];
|
|
211
236
|
if (!key && !token) return false;
|
|
212
|
-
|
|
213
|
-
if (!
|
|
237
|
+
const sub = token ? await this.verifyServiceToken(String(token)) : undefined;
|
|
238
|
+
if (!sub) this.refuse(request, NO_SERVICE_TOKEN, 'no valid service token');
|
|
239
|
+
if (sub.startsWith('user:')) userId = sub.slice('user:'.length);
|
|
240
|
+
serviceId = userId ? sub : sub.slice('apikey:'.length);
|
|
214
241
|
} else {
|
|
215
242
|
if (!key) return false;
|
|
216
243
|
this.refuse(request, KEYS_OFF, 'api keys are off');
|
|
217
244
|
}
|
|
218
245
|
const caller: ServiceCaller = { serviceId: serviceId as string, roles: [], permissions: [] };
|
|
219
246
|
request.auth = caller;
|
|
220
|
-
// The key's id, never the key.
|
|
221
|
-
request.apso = { ...request.apso, caller: { type: 'service', keyId: caller.serviceId } };
|
|
247
|
+
// The key's id, never the key. An Apso user the gateway vouches for is logged by user id.
|
|
248
|
+
request.apso = { ...request.apso, caller: { type: 'service', ...(userId ? { userId } : { keyId: caller.serviceId }) } };
|
|
222
249
|
return true;
|
|
223
250
|
}
|
|
224
251
|
|
|
225
|
-
/**
|
|
252
|
+
/**
|
|
253
|
+
* Who the gateway's token names (its sub, "apikey:<key id>" or
|
|
254
|
+
* "user:<Apso user id>"), when the token is valid for this service.
|
|
255
|
+
*/
|
|
226
256
|
private async verifyServiceToken(token: string): Promise<string | undefined> {
|
|
227
257
|
if (!this.jwks || !this.issuer || !this.serviceId) return undefined;
|
|
228
258
|
try {
|
|
@@ -232,8 +262,8 @@ export class ApiKeyGuard implements CanActivate {
|
|
|
232
262
|
algorithms: ['ES256'],
|
|
233
263
|
requiredClaims: ['exp', 'sub'],
|
|
234
264
|
});
|
|
235
|
-
const
|
|
236
|
-
return
|
|
265
|
+
const sub = payload.sub as string;
|
|
266
|
+
return /^(apikey|user):.+$/.test(sub) ? sub : undefined;
|
|
237
267
|
} catch {
|
|
238
268
|
return undefined;
|
|
239
269
|
}
|
|
@@ -262,18 +292,40 @@ export class ApiKeyGuard implements CanActivate {
|
|
|
262
292
|
});
|
|
263
293
|
}
|
|
264
294
|
}
|
|
295
|
+
<% if (it.mcp) { %>
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* The internal MCP address, /mcp/internal, for the service's own team, agents
|
|
299
|
+
* and scripts (@apso/mcp reads this under its MCP_INTERNAL_AUTH token). It
|
|
300
|
+
* takes service callers only. When APSO_INTERNAL_AUTH_ISSUER is set (the Apso
|
|
301
|
+
* platform sets it), a refused client is pointed at Apso sign-in, and the
|
|
302
|
+
* platform's gateway turns that sign-in into a service token.
|
|
303
|
+
*/
|
|
304
|
+
export const McpInternalAuthProvider = {
|
|
305
|
+
provide: 'APSO_MCP_INTERNAL_AUTH',
|
|
306
|
+
inject: [ApiKeyGuard],
|
|
307
|
+
useFactory: (guard: ApiKeyGuard) => ({
|
|
308
|
+
authorizationServers: process.env.APSO_INTERNAL_AUTH_ISSUER ? [process.env.APSO_INTERNAL_AUTH_ISSUER] : [],
|
|
309
|
+
resource: process.env.MCP_RESOURCE_URL ? `${process.env.MCP_RESOURCE_URL.replace(/\/$/, '')}/internal` : undefined,
|
|
310
|
+
ignoredHeaders: ['authorization'],
|
|
311
|
+
verify: (request: any) => guard.authenticateInternal(request),
|
|
312
|
+
}),
|
|
313
|
+
};
|
|
314
|
+
<% } %>
|
|
265
315
|
<% if (it.mcpAuth) { %>
|
|
266
316
|
|
|
267
317
|
/**
|
|
268
|
-
*
|
|
269
|
-
*
|
|
270
|
-
*
|
|
318
|
+
* The external MCP address, /mcp, for the app's end users (@apso/mcp reads
|
|
319
|
+
* this under its MCP_AUTH token). An MCP client that calls it without a valid
|
|
320
|
+
* user token is pointed at the identity provider. A key is ignored there and
|
|
321
|
+
* is not passed on to the route a tool calls.
|
|
271
322
|
*/
|
|
272
323
|
export const McpAuthProvider = {
|
|
273
324
|
provide: 'APSO_MCP_AUTH',
|
|
274
325
|
inject: [ApiKeyGuard],
|
|
275
326
|
useFactory: (guard: ApiKeyGuard) => ({
|
|
276
327
|
...MCP_SIGN_IN,
|
|
328
|
+
ignoredHeaders: ['x-api-key', 'x-apso-service-token'],
|
|
277
329
|
verify: (request: any) => guard.authenticate(request),
|
|
278
330
|
}),
|
|
279
331
|
};
|
|
@@ -284,7 +284,11 @@ def _refuse(request: Request, reason: str) -> NoReturn:
|
|
|
284
284
|
|
|
285
285
|
|
|
286
286
|
def _service_token_key_id(token: str) -> Optional[str]:
|
|
287
|
-
"""
|
|
287
|
+
"""
|
|
288
|
+
The caller from the gateway's token, when the token is valid for this
|
|
289
|
+
service: the key id of sub "apikey:<id>", or sub "user:<id>" as it is, an
|
|
290
|
+
Apso sign-in the gateway checked (it sends one for /mcp/internal only).
|
|
291
|
+
"""
|
|
288
292
|
if not (_SERVICE_JWKS and _SERVICE_ISSUER and _SERVICE_ID):
|
|
289
293
|
return None
|
|
290
294
|
try:
|
|
@@ -300,7 +304,11 @@ def _service_token_key_id(token: str) -> Optional[str]:
|
|
|
300
304
|
except jwt.PyJWTError:
|
|
301
305
|
return None
|
|
302
306
|
sub = payload["sub"]
|
|
303
|
-
|
|
307
|
+
if not isinstance(sub, str):
|
|
308
|
+
return None
|
|
309
|
+
if sub.startswith("user:"):
|
|
310
|
+
return sub if sub != "user:" else None
|
|
311
|
+
return sub[len("apikey:"):] or None if sub.startswith("apikey:") else None
|
|
304
312
|
|
|
305
313
|
|
|
306
314
|
async def _service_caller(request: Request) -> Optional[AuthContext]:
|
|
@@ -1,8 +1,19 @@
|
|
|
1
1
|
<%~ includeFile('./header.eta', it) %>
|
|
2
2
|
|
|
3
3
|
"""
|
|
4
|
-
MCP tools
|
|
5
|
-
|
|
4
|
+
MCP tools (Streamable HTTP, stateless), served with the official MCP SDK for
|
|
5
|
+
Python at two addresses, one per audience:
|
|
6
|
+
|
|
7
|
+
<% if (it.external) { %>
|
|
8
|
+
- /mcp, the external address, for your end users. It takes a signed-in user's
|
|
9
|
+
token in Authorization: Bearer and nothing else: an API key is not read here.
|
|
10
|
+
<% } else { %>
|
|
11
|
+
- /mcp, the external address, for your end users, is not served: .apsorc has
|
|
12
|
+
no auth block to sign them in with.
|
|
13
|
+
<% } %>
|
|
14
|
+
- /mcp/internal, for your own team, agents and scripts. It takes the service's
|
|
15
|
+
API key (the same key source as the REST routes) and nothing else: the
|
|
16
|
+
Authorization header is not read here. The caller is a service caller.
|
|
6
17
|
|
|
7
18
|
A tool is a route. A route is marked with openapi_extra=mcp_tool(...), and its
|
|
8
19
|
input schema comes from its OpenAPI operation: path and query parameters are
|
|
@@ -11,16 +22,25 @@ a tool, the request is sent through this app in memory with the caller's
|
|
|
11
22
|
headers, so authentication, permissions and tenant scoping run exactly as they
|
|
12
23
|
do for a REST caller. Tools never call a service or the database.
|
|
13
24
|
|
|
14
|
-
Every request
|
|
15
|
-
with no valid credential gets
|
|
16
|
-
|
|
17
|
-
|
|
25
|
+
Every request passes the service's own auth check first, on the credential
|
|
26
|
+
its address reads. A request with no valid credential gets a 401.
|
|
27
|
+
<% if (it.external) { %>
|
|
28
|
+
On /mcp that 401 starts OAuth sign-in in an MCP client, and
|
|
29
|
+
/.well-known/oauth-protected-resource names the identity provider (RFC 9728).
|
|
30
|
+
<% } %>
|
|
31
|
+
|
|
32
|
+
When APSO_INTERNAL_AUTH_ISSUER is set (the platform sets it), the 401 on
|
|
33
|
+
/mcp/internal starts an Apso sign-in the same way, and
|
|
34
|
+
/.well-known/oauth-protected-resource/mcp/internal names that issuer. The
|
|
35
|
+
platform's gateway turns the Apso token into the service token this service
|
|
36
|
+
checks.
|
|
18
37
|
|
|
19
38
|
Mark your own routes the same way:
|
|
20
39
|
|
|
21
40
|
@router.post("/{id}/approve", openapi_extra=mcp_tool("approve_invoice", "Approve an invoice."))
|
|
22
41
|
"""
|
|
23
42
|
import json
|
|
43
|
+
import os
|
|
24
44
|
import re
|
|
25
45
|
from contextlib import asynccontextmanager
|
|
26
46
|
from typing import Any, Dict, List, Optional
|
|
@@ -35,11 +55,16 @@ from starlette.requests import Request
|
|
|
35
55
|
from starlette.responses import JSONResponse, Response
|
|
36
56
|
from starlette.routing import Route
|
|
37
57
|
|
|
38
|
-
from .auth import
|
|
58
|
+
from .auth import <% if (it.external) { %>_PROVIDERS, <% } %>require_auth
|
|
39
59
|
|
|
40
60
|
MCP_PATH = "/mcp"
|
|
61
|
+
INTERNAL = "/internal"
|
|
41
62
|
MCP_EXTENSION = "x-mcp-tool"
|
|
42
63
|
PRM_PATH = "/.well-known/oauth-protected-resource"
|
|
64
|
+
# The public URL of the external address; the internal one is this + /internal.
|
|
65
|
+
MCP_RESOURCE = os.getenv("MCP_RESOURCE_URL") or ""
|
|
66
|
+
# Where an MCP client signs in to Apso for the internal address.
|
|
67
|
+
INTERNAL_ISSUER = os.getenv("APSO_INTERNAL_AUTH_ISSUER") or ""
|
|
43
68
|
|
|
44
69
|
# Headers that describe the MCP request itself, not the caller. Everything
|
|
45
70
|
# else (authorization, cookie, x-api-key, ...) is forwarded to the route.
|
|
@@ -184,22 +209,22 @@ async def _call_tool(app: FastAPI, tool: dict, args: Dict[str, Any], caller_head
|
|
|
184
209
|
return _text(response.text or f"HTTP {response.status_code}", response.status_code >= 400)
|
|
185
210
|
|
|
186
211
|
|
|
187
|
-
def _resource_url(request: Request) -> str:
|
|
188
|
-
"""
|
|
212
|
+
def _resource_url(request: Request, suffix: str = "") -> str:
|
|
213
|
+
"""An MCP address's public URL: from MCP_RESOURCE_URL, else from what the request used."""
|
|
189
214
|
if MCP_RESOURCE:
|
|
190
|
-
return MCP_RESOURCE.rstrip("/")
|
|
215
|
+
return MCP_RESOURCE.rstrip("/") + suffix
|
|
191
216
|
proto = request.headers.get("x-forwarded-proto", request.url.scheme).split(",")[0].strip()
|
|
192
217
|
host = request.headers.get("x-forwarded-host", request.headers.get("host", "localhost")).split(",")[0].strip()
|
|
193
|
-
return f"{proto}://{host}{MCP_PATH}"
|
|
218
|
+
return f"{proto}://{host}{MCP_PATH}{suffix}"
|
|
194
219
|
|
|
195
220
|
|
|
196
|
-
def _metadata_url(request: Request) -> str:
|
|
197
|
-
resource = urlsplit(_resource_url(request))
|
|
221
|
+
def _metadata_url(request: Request, suffix: str = "") -> str:
|
|
222
|
+
resource = urlsplit(_resource_url(request, suffix))
|
|
198
223
|
return f"{resource.scheme}://{resource.netloc}{PRM_PATH}{resource.path}"
|
|
199
224
|
|
|
200
225
|
|
|
201
226
|
def mount_mcp(app: FastAPI) -> None:
|
|
202
|
-
"""Serve the routes marked with mcp_tool as MCP tools
|
|
227
|
+
"""Serve the routes marked with mcp_tool as MCP tools. Call it after the routers are included."""
|
|
203
228
|
tools: Dict[str, dict] = {}
|
|
204
229
|
|
|
205
230
|
async def list_tools(ctx: Any, params: Any) -> types.ListToolsResult:
|
|
@@ -228,48 +253,67 @@ def mount_mcp(app: FastAPI) -> None:
|
|
|
228
253
|
manager = StreamableHTTPSessionManager(app=server, stateless=True, json_response=True)
|
|
229
254
|
|
|
230
255
|
class Endpoint:
|
|
256
|
+
"""One MCP address: /mcp (suffix "") or /mcp/internal."""
|
|
257
|
+
|
|
258
|
+
def __init__(self, suffix: str) -> None:
|
|
259
|
+
self.suffix = suffix
|
|
260
|
+
# The credential this address does not read: a user's token on the
|
|
261
|
+
# internal one, a key on the external one. It is dropped before the
|
|
262
|
+
# auth check, so a tool's route never sees it either.
|
|
263
|
+
self.ignored = {b"authorization"} if suffix else {b"x-api-key", b"x-apso-service-token"}
|
|
264
|
+
|
|
231
265
|
async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
|
|
266
|
+
sent_token = any(h[0].lower() == b"authorization" for h in scope["headers"])
|
|
267
|
+
scope = {**scope, "headers": [h for h in scope["headers"] if h[0].lower() not in self.ignored]}
|
|
232
268
|
request = Request(scope, receive)
|
|
233
269
|
if request.method != "POST":
|
|
234
270
|
await Response(status_code=405, headers={"allow": "POST"})(scope, receive, send)
|
|
235
271
|
return
|
|
236
272
|
try:
|
|
237
|
-
# The same check every /api route runs
|
|
273
|
+
# The same check every /api route runs, on what is left: only a
|
|
274
|
+
# key can pass on the internal address, only a user's token on the external one.
|
|
238
275
|
await require_auth(request, Response())
|
|
239
276
|
except HTTPException as e:
|
|
240
277
|
headers = dict(e.headers or {})
|
|
241
|
-
|
|
242
|
-
if e.status_code == 401 and not presents_key:
|
|
278
|
+
if e.status_code == 401 and (INTERNAL_ISSUER or not self.suffix):
|
|
243
279
|
# The 401 is what starts sign-in: it points the client at the metadata.
|
|
244
|
-
challenge = f'Bearer resource_metadata="{_metadata_url(request)}"'
|
|
245
|
-
if
|
|
280
|
+
challenge = f'Bearer resource_metadata="{_metadata_url(request, self.suffix)}"'
|
|
281
|
+
if sent_token:
|
|
246
282
|
challenge += ', error="invalid_token"'
|
|
247
283
|
headers["www-authenticate"] = challenge
|
|
248
284
|
await JSONResponse({"detail": e.detail}, status_code=e.status_code, headers=headers)(scope, receive, send)
|
|
249
285
|
return
|
|
250
286
|
await manager.handle_request(scope, receive, send)
|
|
251
287
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
)
|
|
288
|
+
def metadata(suffix: str, issuers: List[str]) -> Any:
|
|
289
|
+
async def document(request: Request) -> Response:
|
|
290
|
+
# Tells an MCP client where to sign in. Public by design, and readable
|
|
291
|
+
# from a browser-based client on another origin.
|
|
292
|
+
return JSONResponse(
|
|
293
|
+
{
|
|
294
|
+
"resource": _resource_url(request, suffix),
|
|
295
|
+
"authorization_servers": issuers,
|
|
296
|
+
"bearer_methods_supported": ["header"],
|
|
297
|
+
},
|
|
298
|
+
headers={"access-control-allow-origin": "*", "cache-control": "max-age=300"},
|
|
299
|
+
)
|
|
265
300
|
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
301
|
+
return document
|
|
302
|
+
|
|
303
|
+
routes = [Route(MCP_PATH + INTERNAL, endpoint=Endpoint(INTERNAL))]
|
|
304
|
+
if INTERNAL_ISSUER:
|
|
305
|
+
routes.append(Route(PRM_PATH + MCP_PATH + INTERNAL, metadata(INTERNAL, [INTERNAL_ISSUER]), methods=["GET"]))
|
|
306
|
+
<% if (it.external) { %>
|
|
307
|
+
# Every provider's issuer, in .apsorc order. For Better Auth that is its
|
|
308
|
+
# base URL, the issuer of its OAuth access tokens.
|
|
309
|
+
external = metadata("", [p["issuer"] for p in _PROVIDERS])
|
|
310
|
+
routes += [
|
|
311
|
+
Route(MCP_PATH, endpoint=Endpoint("")),
|
|
312
|
+
Route(PRM_PATH, external, methods=["GET"]),
|
|
313
|
+
Route(PRM_PATH + MCP_PATH, external, methods=["GET"]),
|
|
314
|
+
]
|
|
315
|
+
<% } %>
|
|
316
|
+
app.router.routes.extend(routes)
|
|
273
317
|
|
|
274
318
|
inner = app.router.lifespan_context
|
|
275
319
|
|
|
@@ -53,9 +53,10 @@ export interface Entity {
|
|
|
53
53
|
*/
|
|
54
54
|
permissions?: EntityPermissions;
|
|
55
55
|
/**
|
|
56
|
-
* Expose this entity's CRUD routes as MCP tools
|
|
57
|
-
*
|
|
58
|
-
*
|
|
56
|
+
* Expose this entity's CRUD routes as MCP tools. `true` exposes read,
|
|
57
|
+
* create, update and delete; a list exposes only those operations. Off by
|
|
58
|
+
* default. The tools are served to service callers (API key) at
|
|
59
|
+
* /mcp/internal, and to signed-in users at /mcp when `auth` is set.
|
|
59
60
|
* Example: ["read", "create"]
|
|
60
61
|
*/
|
|
61
62
|
mcp?: boolean | PermissionOperation[];
|
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
* option, Content-Range counts and PostgREST OpenAPI parameters, which the
|
|
5
5
|
* generated controllers rely on. The service template declares the same
|
|
6
6
|
* ranges (see TEMPLATE_REFS in ./template.ts); bump both together.
|
|
7
|
+
* @apso/crud-typeorm starts at 1.1.2, where a query that names something
|
|
8
|
+
* other than a column of the entity answers 400, and a request for one row
|
|
9
|
+
* always acts on the row in its URL.
|
|
7
10
|
*
|
|
8
11
|
* @apso/postgrest-request is not imported by generated code. It is listed so
|
|
9
12
|
* a project whose lockfile holds an older copy moves to the one @apso/crud
|
|
@@ -32,7 +35,7 @@ export declare function ensureCrudDeps(projectDir: string): string[];
|
|
|
32
35
|
* @returns {string[]} Names added or raised (empty when nothing changed or no package.json).
|
|
33
36
|
*/
|
|
34
37
|
export declare function addMissingDeps(projectDir: string, deps: Record<string, string>, raise?: boolean): string[];
|
|
35
|
-
/** MCP library the generated controllers import when an entity sets `mcp`. 0.
|
|
38
|
+
/** MCP library the generated controllers import when an entity sets `mcp`. 0.3.0 is the first that serves /mcp/internal next to /mcp. */
|
|
36
39
|
export declare const MCP_DEP: Record<string, string>;
|
|
37
40
|
/**
|
|
38
41
|
* Wire @apso/mcp into a TypeScript project: declare the package and call
|
|
@@ -11,6 +11,9 @@ const path = tslib_1.__importStar(require("path"));
|
|
|
11
11
|
* option, Content-Range counts and PostgREST OpenAPI parameters, which the
|
|
12
12
|
* generated controllers rely on. The service template declares the same
|
|
13
13
|
* ranges (see TEMPLATE_REFS in ./template.ts); bump both together.
|
|
14
|
+
* @apso/crud-typeorm starts at 1.1.2, where a query that names something
|
|
15
|
+
* other than a column of the entity answers 400, and a request for one row
|
|
16
|
+
* always acts on the row in its URL.
|
|
14
17
|
*
|
|
15
18
|
* @apso/postgrest-request is not imported by generated code. It is listed so
|
|
16
19
|
* a project whose lockfile holds an older copy moves to the one @apso/crud
|
|
@@ -20,7 +23,7 @@ exports.APSO_CRUD_DEPS = {
|
|
|
20
23
|
"@apso/crud": "^1.1.0",
|
|
21
24
|
"@apso/crud-core": "^1.1.0",
|
|
22
25
|
"@apso/crud-request": "^1.0.1",
|
|
23
|
-
"@apso/crud-typeorm": "^1.1.
|
|
26
|
+
"@apso/crud-typeorm": "^1.1.2",
|
|
24
27
|
"@apso/postgrest-request": "^1.1.0",
|
|
25
28
|
};
|
|
26
29
|
/**
|
|
@@ -82,8 +85,8 @@ function addMissingDeps(projectDir, deps, raise = false) {
|
|
|
82
85
|
return missing;
|
|
83
86
|
}
|
|
84
87
|
exports.addMissingDeps = addMissingDeps;
|
|
85
|
-
/** MCP library the generated controllers import when an entity sets `mcp`. 0.
|
|
86
|
-
exports.MCP_DEP = { "@apso/mcp": "^0.
|
|
88
|
+
/** MCP library the generated controllers import when an entity sets `mcp`. 0.3.0 is the first that serves /mcp/internal next to /mcp. */
|
|
89
|
+
exports.MCP_DEP = { "@apso/mcp": "^0.3.0" };
|
|
87
90
|
const SWAGGER_SETUP = "SwaggerModule.setup('_docs', app, document);";
|
|
88
91
|
/**
|
|
89
92
|
* Wire @apso/mcp into a TypeScript project: declare the package and call
|
|
@@ -104,7 +107,7 @@ function ensureMcpWiring(projectDir, rootFolder) {
|
|
|
104
107
|
if (!text.includes(SWAGGER_SETUP))
|
|
105
108
|
throw new Error(`mcp in .apsorc: could not add the MCP endpoint to ${relative}. Where your app is configured, import { mountMcp } from '@apso/mcp' and call mountMcp(app, document) after SwaggerModule.createDocument. Without it no tools are served.`);
|
|
106
109
|
fs.writeFileSync(file, "import { mountMcp } from '@apso/mcp';\n" +
|
|
107
|
-
text.replace(SWAGGER_SETUP, `${SWAGGER_SETUP}\n\n // Serve the routes marked with @McpTool as MCP tools
|
|
110
|
+
text.replace(SWAGGER_SETUP, `${SWAGGER_SETUP}\n\n // Serve the routes marked with @McpTool as MCP tools: /mcp/internal for API keys, /mcp for signed-in users.\n mountMcp(app, document);`));
|
|
108
111
|
return [...changed, relative];
|
|
109
112
|
}
|
|
110
113
|
exports.ensureMcpWiring = ensureMcpWiring;
|
|
@@ -572,6 +572,11 @@ function* generateNestedRelationships(entityName, relationshipMap, maxDepth = 4,
|
|
|
572
572
|
const relationships = relationshipMap[entityName];
|
|
573
573
|
if (!relationships)
|
|
574
574
|
return;
|
|
575
|
+
// Two relationships can expose the same property name on this entity (for
|
|
576
|
+
// example two FKs to one table whose inverse sides share a default name).
|
|
577
|
+
// A join path names a property, so emit each name once per level; duplicate
|
|
578
|
+
// keys make the generated controller's join map fail to compile (TS1117).
|
|
579
|
+
const emittedAtLevel = new Set();
|
|
575
580
|
for (const relationship of relationships) {
|
|
576
581
|
const referenceName = (0, exports.getRelationshipName)(relationship);
|
|
577
582
|
const type = relationship.type;
|
|
@@ -611,6 +616,9 @@ function* generateNestedRelationships(entityName, relationshipMap, maxDepth = 4,
|
|
|
611
616
|
continue;
|
|
612
617
|
}
|
|
613
618
|
}
|
|
619
|
+
if (emittedAtLevel.has(formattedName))
|
|
620
|
+
continue;
|
|
621
|
+
emittedAtLevel.add(formattedName);
|
|
614
622
|
// Build the new path
|
|
615
623
|
const newPath = [...path, formattedName];
|
|
616
624
|
// Always yield the join path if it's longer than 1 level
|
|
@@ -3,8 +3,10 @@ export declare const TEMPLATE_REPOS: Record<TargetLanguage, string>;
|
|
|
3
3
|
/**
|
|
4
4
|
* Git ref (tag or branch) to clone for each template. Pinning to a tag makes
|
|
5
5
|
* the CLI-version-to-template pairing explicit instead of a date cutoff on
|
|
6
|
-
* template main. v2.
|
|
7
|
-
*
|
|
6
|
+
* template main. v2.1.2 matches what this CLI generates: @apso/crud ^1.1.0
|
|
7
|
+
* (PostgREST-only), MCP at /mcp, request logging, and the AGENTS.md and
|
|
8
|
+
* CLAUDE.md agent instructions. Move the tag when the template changes in a
|
|
9
|
+
* way new projects need; the Python and Go
|
|
8
10
|
* template repos are untagged and don't carry the dialect work.
|
|
9
11
|
*/
|
|
10
12
|
export declare const TEMPLATE_REFS: Record<TargetLanguage, string>;
|
|
@@ -29,7 +31,7 @@ export declare function ensureDevKey(projectPath: string): string | undefined;
|
|
|
29
31
|
* Stamp the chosen language into the scaffolded `.apsorc`.
|
|
30
32
|
*
|
|
31
33
|
* `apso generate` resolves its target language as flag > .apsorc > prompt.
|
|
32
|
-
* The TypeScript template
|
|
34
|
+
* The TypeScript template ships an `.apsorc` without a
|
|
33
35
|
* `language` field, so a bare `apso generate` right after `apso init` fell
|
|
34
36
|
* through to the interactive prompt — which errors in non-TTY contexts
|
|
35
37
|
* (this is what kept the weekly scaffold-smoke workflow red). Recording the
|
|
@@ -15,12 +15,14 @@ exports.TEMPLATE_REPOS = {
|
|
|
15
15
|
/**
|
|
16
16
|
* Git ref (tag or branch) to clone for each template. Pinning to a tag makes
|
|
17
17
|
* the CLI-version-to-template pairing explicit instead of a date cutoff on
|
|
18
|
-
* template main. v2.
|
|
19
|
-
*
|
|
18
|
+
* template main. v2.1.2 matches what this CLI generates: @apso/crud ^1.1.0
|
|
19
|
+
* (PostgREST-only), MCP at /mcp, request logging, and the AGENTS.md and
|
|
20
|
+
* CLAUDE.md agent instructions. Move the tag when the template changes in a
|
|
21
|
+
* way new projects need; the Python and Go
|
|
20
22
|
* template repos are untagged and don't carry the dialect work.
|
|
21
23
|
*/
|
|
22
24
|
exports.TEMPLATE_REFS = {
|
|
23
|
-
typescript: "v2.
|
|
25
|
+
typescript: "v2.1.2",
|
|
24
26
|
python: "main",
|
|
25
27
|
go: "main",
|
|
26
28
|
};
|
|
@@ -91,7 +93,7 @@ exports.ensureDevKey = ensureDevKey;
|
|
|
91
93
|
* Stamp the chosen language into the scaffolded `.apsorc`.
|
|
92
94
|
*
|
|
93
95
|
* `apso generate` resolves its target language as flag > .apsorc > prompt.
|
|
94
|
-
* The TypeScript template
|
|
96
|
+
* The TypeScript template ships an `.apsorc` without a
|
|
95
97
|
* `language` field, so a bare `apso generate` right after `apso init` fell
|
|
96
98
|
* through to the interactive prompt — which errors in non-TTY contexts
|
|
97
99
|
* (this is what kept the weekly scaffold-smoke workflow red). Recording the
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@apso/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.51.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@apso/cli",
|
|
9
|
-
"version": "0.
|
|
9
|
+
"version": "0.51.0",
|
|
10
10
|
"license": "Apache-2.0",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@apso/schema-tools": "^0.2.2",
|
package/oclif.manifest.json
CHANGED