@apso/cli 0.50.1 → 0.52.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 +5 -4
- package/dist/commands/mcp/serve.js +3 -2
- package/dist/lib/access/rules.json +9 -2
- package/dist/lib/apsorc-parser.d.ts +13 -1
- package/dist/lib/apsorc-parser.js +40 -1
- package/dist/lib/generators/go.js +3 -1
- package/dist/lib/generators/python.js +6 -2
- package/dist/lib/generators/typescript.d.ts +2 -1
- package/dist/lib/generators/typescript.js +13 -8
- 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/templates/rest/controller-rest.eta +9 -2
- package/dist/lib/templates/rest/index-module-rest.eta +4 -0
- package/dist/lib/types/entity.d.ts +4 -3
- package/dist/lib/types/generator.d.ts +16 -0
- package/dist/lib/types/index.d.ts +1 -1
- package/dist/lib/utils/crud-deps.d.ts +4 -3
- package/dist/lib/utils/crud-deps.js +7 -6
- package/dist/lib/utils/template.d.ts +1 -1
- package/dist/lib/utils/template.js +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
|
@@ -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
|
|
|
@@ -49,9 +49,13 @@ const skipScope = (req: any) => {
|
|
|
49
49
|
replace: <%= it.entityName %>Update,
|
|
50
50
|
},
|
|
51
51
|
validation: false,
|
|
52
|
+
<% if (it.dialects.length === 1 && it.dialects[0] === 'postgrest') { %>
|
|
52
53
|
// List queries are PostgREST syntax only (?status=eq.open&select=id,name&order=id.desc).
|
|
53
54
|
// A nestjsx parameter (filter, join, sort, s, fields, page, per_page, cache) gets a 400.
|
|
54
|
-
|
|
55
|
+
<% } else { %>
|
|
56
|
+
// Query syntaxes accepted, from .apsorc "query.dialects".
|
|
57
|
+
<% } %>
|
|
58
|
+
dialects: [<%~ it.dialectList %>],
|
|
55
59
|
params: {
|
|
56
60
|
id: {
|
|
57
61
|
field: 'id',
|
|
@@ -63,7 +67,10 @@ const skipScope = (req: any) => {
|
|
|
63
67
|
// The default page: a list with no limit returns at most this many
|
|
64
68
|
// rows. When more exist the answer is a 206 and its Content-Range
|
|
65
69
|
// header has the total (0-24/42). The largest limit is 100.
|
|
66
|
-
limit:
|
|
70
|
+
limit: <%= it.limit %>,
|
|
71
|
+
<% if (it.alwaysPaginate) { %>
|
|
72
|
+
alwaysPaginate: true,
|
|
73
|
+
<% } %>
|
|
67
74
|
<% if (it.associations.length) { %>
|
|
68
75
|
join: {
|
|
69
76
|
<% it.associations.forEach((assoc) => { %>
|
|
@@ -3,11 +3,15 @@
|
|
|
3
3
|
<% it.entities.forEach((entity) => { %>
|
|
4
4
|
import {<%= entity.name %>Module} from './<%= entity.name %>/<%= entity.name %>.module'
|
|
5
5
|
<%}) %>
|
|
6
|
+
<% if (it.guards) { %>
|
|
6
7
|
import { GuardsModule } from './guards/guards.module'
|
|
8
|
+
<% } %>
|
|
7
9
|
|
|
8
10
|
export default [
|
|
9
11
|
<% it.entities.forEach((entity) => { %>
|
|
10
12
|
<%= entity.name %>Module,
|
|
11
13
|
<%}) %>
|
|
14
|
+
<% if (it.guards) { %>
|
|
12
15
|
GuardsModule,
|
|
16
|
+
<% } %>
|
|
13
17
|
]
|
|
@@ -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[];
|
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
import { Entity } from "./entity";
|
|
2
2
|
import { AuthConfig } from "./auth";
|
|
3
3
|
import { RelationshipMap, Relationship } from "./relationship";
|
|
4
|
+
/**
|
|
5
|
+
* .apsorc `query` (TypeScript REST only): how the generated list routes read a
|
|
6
|
+
* request. Leave it out for the defaults. An app whose clients already send
|
|
7
|
+
* nestjsx queries keeps them working with `"dialects": ["nestjsx", "postgrest"]`.
|
|
8
|
+
*/
|
|
9
|
+
export interface QueryConfig {
|
|
10
|
+
/** Query syntaxes the list routes accept. Default `["postgrest"]`. */
|
|
11
|
+
dialects?: Array<"postgrest" | "nestjsx">;
|
|
12
|
+
/** Rows a list returns when the request names no limit. Default 25. */
|
|
13
|
+
limit?: number;
|
|
14
|
+
/** Answer every list with a page object instead of an array. Default false. */
|
|
15
|
+
alwaysPaginate?: boolean;
|
|
16
|
+
}
|
|
4
17
|
/**
|
|
5
18
|
* Supported target languages for code generation
|
|
6
19
|
*/
|
|
@@ -158,6 +171,8 @@ export interface ControllerGenerationOptions extends EntityGenerationOptions {
|
|
|
158
171
|
* caller's tenant
|
|
159
172
|
*/
|
|
160
173
|
auth?: AuthConfig;
|
|
174
|
+
/** The .apsorc `query` settings for list routes */
|
|
175
|
+
query?: QueryConfig;
|
|
161
176
|
}
|
|
162
177
|
/**
|
|
163
178
|
* Options for generating services
|
|
@@ -260,6 +275,7 @@ export interface LanguageGenerator {
|
|
|
260
275
|
emitEvents?: boolean;
|
|
261
276
|
http?: boolean;
|
|
262
277
|
auth?: AuthConfig;
|
|
278
|
+
guards?: boolean;
|
|
263
279
|
}): Promise<GeneratedFile[]>;
|
|
264
280
|
/**
|
|
265
281
|
* Generate guard files (auth, scope, etc.)
|
|
@@ -4,4 +4,4 @@ export { Index } from "./indices";
|
|
|
4
4
|
export { JSONValue } from "./json";
|
|
5
5
|
export { RelationshipType, Association, ApsorcRelationship, Relationship, RelationshipForTemplate, RelationshipMap, } from "./relationship";
|
|
6
6
|
export { AuthProviderType, BaseAuthConfig, DbSessionAuthConfig, JwtConfig, JwtClaimsMapping, JwtAuthConfig, AuthConfig, AuthProviderConfig, AuthContext, DB_SESSION_AUTH_DEFAULTS, JWT_AUTH_DEFAULTS, isDbSessionAuth, BetterAuthConfig, assertSignInProvider, ResolvedJwtAuth, resolveJwtAuth, authProviders, resolveJwtProviders, } from "./auth";
|
|
7
|
-
export { TargetLanguage, GeneratedFile, ValidationResult, PythonLanguageConfig, GoLanguageConfig, TypeScriptLanguageConfig, LanguageConfig, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, LanguageGenerator, GeneratorFactory, GeneratorRegistry, } from "./generator";
|
|
7
|
+
export { TargetLanguage, QueryConfig, GeneratedFile, ValidationResult, PythonLanguageConfig, GoLanguageConfig, TypeScriptLanguageConfig, LanguageConfig, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, LanguageGenerator, GeneratorFactory, GeneratorRegistry, } from "./generator";
|
|
@@ -4,8 +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.
|
|
8
|
-
*
|
|
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.
|
|
9
10
|
*
|
|
10
11
|
* @apso/postgrest-request is not imported by generated code. It is listed so
|
|
11
12
|
* a project whose lockfile holds an older copy moves to the one @apso/crud
|
|
@@ -34,7 +35,7 @@ export declare function ensureCrudDeps(projectDir: string): string[];
|
|
|
34
35
|
* @returns {string[]} Names added or raised (empty when nothing changed or no package.json).
|
|
35
36
|
*/
|
|
36
37
|
export declare function addMissingDeps(projectDir: string, deps: Record<string, string>, raise?: boolean): string[];
|
|
37
|
-
/** 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. */
|
|
38
39
|
export declare const MCP_DEP: Record<string, string>;
|
|
39
40
|
/**
|
|
40
41
|
* Wire @apso/mcp into a TypeScript project: declare the package and call
|
|
@@ -11,8 +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.
|
|
15
|
-
*
|
|
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.
|
|
16
17
|
*
|
|
17
18
|
* @apso/postgrest-request is not imported by generated code. It is listed so
|
|
18
19
|
* a project whose lockfile holds an older copy moves to the one @apso/crud
|
|
@@ -22,7 +23,7 @@ exports.APSO_CRUD_DEPS = {
|
|
|
22
23
|
"@apso/crud": "^1.1.0",
|
|
23
24
|
"@apso/crud-core": "^1.1.0",
|
|
24
25
|
"@apso/crud-request": "^1.0.1",
|
|
25
|
-
"@apso/crud-typeorm": "^1.1.
|
|
26
|
+
"@apso/crud-typeorm": "^1.1.2",
|
|
26
27
|
"@apso/postgrest-request": "^1.1.0",
|
|
27
28
|
};
|
|
28
29
|
/**
|
|
@@ -84,8 +85,8 @@ function addMissingDeps(projectDir, deps, raise = false) {
|
|
|
84
85
|
return missing;
|
|
85
86
|
}
|
|
86
87
|
exports.addMissingDeps = addMissingDeps;
|
|
87
|
-
/** MCP library the generated controllers import when an entity sets `mcp`. 0.
|
|
88
|
-
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" };
|
|
89
90
|
const SWAGGER_SETUP = "SwaggerModule.setup('_docs', app, document);";
|
|
90
91
|
/**
|
|
91
92
|
* Wire @apso/mcp into a TypeScript project: declare the package and call
|
|
@@ -106,7 +107,7 @@ function ensureMcpWiring(projectDir, rootFolder) {
|
|
|
106
107
|
if (!text.includes(SWAGGER_SETUP))
|
|
107
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.`);
|
|
108
109
|
fs.writeFileSync(file, "import { mountMcp } from '@apso/mcp';\n" +
|
|
109
|
-
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);`));
|
|
110
111
|
return [...changed, relative];
|
|
111
112
|
}
|
|
112
113
|
exports.ensureMcpWiring = ensureMcpWiring;
|
|
@@ -3,7 +3,7 @@ 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.1.
|
|
6
|
+
* template main. v2.1.2 matches what this CLI generates: @apso/crud ^1.1.0
|
|
7
7
|
* (PostgREST-only), MCP at /mcp, request logging, and the AGENTS.md and
|
|
8
8
|
* CLAUDE.md agent instructions. Move the tag when the template changes in a
|
|
9
9
|
* way new projects need; the Python and Go
|
|
@@ -15,14 +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.1.
|
|
18
|
+
* template main. v2.1.2 matches what this CLI generates: @apso/crud ^1.1.0
|
|
19
19
|
* (PostgREST-only), MCP at /mcp, request logging, and the AGENTS.md and
|
|
20
20
|
* CLAUDE.md agent instructions. Move the tag when the template changes in a
|
|
21
21
|
* way new projects need; the Python and Go
|
|
22
22
|
* template repos are untagged and don't carry the dialect work.
|
|
23
23
|
*/
|
|
24
24
|
exports.TEMPLATE_REFS = {
|
|
25
|
-
typescript: "v2.1.
|
|
25
|
+
typescript: "v2.1.2",
|
|
26
26
|
python: "main",
|
|
27
27
|
go: "main",
|
|
28
28
|
};
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@apso/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.52.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.52.0",
|
|
10
10
|
"license": "Apache-2.0",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@apso/schema-tools": "^0.2.2",
|
package/oclif.manifest.json
CHANGED