@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,284 @@
1
+ <%~ includeFile('./header.eta', it) %>
2
+
3
+ """
4
+ MCP tools at /mcp (Streamable HTTP, stateless), served with the official MCP
5
+ SDK for Python.
6
+
7
+ A tool is a route. A route is marked with openapi_extra=mcp_tool(...), and its
8
+ input schema comes from its OpenAPI operation: path and query parameters are
9
+ top-level arguments, the JSON body is the "body" argument. When an agent calls
10
+ a tool, the request is sent through this app in memory with the caller's
11
+ headers, so authentication, permissions and tenant scoping run exactly as they
12
+ do for a REST caller. Tools never call a service or the database.
13
+
14
+ Every request to /mcp passes the service's own auth check first. A request
15
+ with no valid credential gets the 401 that starts OAuth sign-in in an MCP
16
+ client, and /.well-known/oauth-protected-resource names the identity provider
17
+ (RFC 9728).
18
+
19
+ Mark your own routes the same way:
20
+
21
+ @router.post("/{id}/approve", openapi_extra=mcp_tool("approve_invoice", "Approve an invoice."))
22
+ """
23
+ import json
24
+ import re
25
+ from contextlib import asynccontextmanager
26
+ from typing import Any, Dict, List, Optional
27
+ from urllib.parse import quote, urlsplit
28
+
29
+ import httpx
30
+ from fastapi import FastAPI, HTTPException
31
+ from mcp import types
32
+ from mcp.server.lowlevel import Server
33
+ from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
34
+ from starlette.requests import Request
35
+ from starlette.responses import JSONResponse, Response
36
+ from starlette.routing import Route
37
+
38
+ from .auth import MCP_RESOURCE, _PROVIDERS, require_auth
39
+
40
+ MCP_PATH = "/mcp"
41
+ MCP_EXTENSION = "x-mcp-tool"
42
+ PRM_PATH = "/.well-known/oauth-protected-resource"
43
+
44
+ # Headers that describe the MCP request itself, not the caller. Everything
45
+ # else (authorization, cookie, x-api-key, ...) is forwarded to the route.
46
+ NOT_FORWARDED = {
47
+ "accept",
48
+ "connection",
49
+ "content-length",
50
+ "content-type",
51
+ "mcp-protocol-version",
52
+ "mcp-session-id",
53
+ "transfer-encoding",
54
+ }
55
+
56
+ _strings = {"type": "array", "items": {"type": "string"}}
57
+ # The generated list routes read these from the query string.
58
+ LIST_PARAMETERS = [
59
+ {"name": "filter", "in": "query", "schema": _strings, "description": "field||$operator||value, one per condition"},
60
+ {"name": "or", "in": "query", "schema": _strings, "description": "field||$operator||value, any of which may match"},
61
+ {"name": "sort", "in": "query", "schema": _strings, "description": "field,ASC or field,DESC"},
62
+ {"name": "join", "in": "query", "schema": _strings, "description": "relation to load with each row"},
63
+ {"name": "fields", "in": "query", "schema": {"type": "string"}, "description": "field1,field2"},
64
+ {"name": "limit", "in": "query", "schema": {"type": "integer"}, "description": "page size"},
65
+ {"name": "page", "in": "query", "schema": {"type": "integer"}, "description": "page number, from 1"},
66
+ ]
67
+
68
+
69
+ def mcp_tool(name: str, description: str, parameters: Optional[List[dict]] = None) -> dict:
70
+ """The openapi_extra that marks a route as an MCP tool."""
71
+ extra: Dict[str, Any] = {MCP_EXTENSION: {"name": name, "description": description}}
72
+ if parameters:
73
+ extra["parameters"] = parameters
74
+ return extra
75
+
76
+
77
+ def _inline(document: dict, node: Any, seen: tuple = ()) -> Any:
78
+ """Replace every $ref with the schema it points to; MCP clients get one self-contained schema."""
79
+ if isinstance(node, list):
80
+ return [_inline(document, item, seen) for item in node]
81
+ if not isinstance(node, dict):
82
+ return node
83
+ ref = node.get("$ref")
84
+ if isinstance(ref, str):
85
+ name = ref.split("/")[-1]
86
+ # ponytail: a self-referencing schema is cut to "any object" where it repeats.
87
+ if name in seen:
88
+ return {"type": "object"}
89
+ return _inline(document, document.get("components", {}).get("schemas", {}).get(name, {}), (*seen, name))
90
+ return {key: _inline(document, value, seen) for key, value in node.items()}
91
+
92
+
93
+ def tools_from_document(document: dict) -> List[dict]:
94
+ """Build the tool list from the routes marked with mcp_tool in an OpenAPI document."""
95
+ tools: List[dict] = []
96
+ for path, item in (document.get("paths") or {}).items():
97
+ for method in ("get", "post", "put", "patch", "delete"):
98
+ operation = item.get(method) or {}
99
+ options = operation.get(MCP_EXTENSION)
100
+ if not options:
101
+ continue
102
+ route = f"{method.upper()} {path}"
103
+ name = options.get("name") or operation.get("operationId") or ""
104
+ if not re.fullmatch(r"[\w-]{1,64}", name):
105
+ raise RuntimeError(f'mcp_tool on {route}: name "{name}" must be 1-64 letters, digits, _ or -')
106
+ if any(tool["name"] == name for tool in tools):
107
+ raise RuntimeError(f'mcp_tool on {route}: another tool is already named "{name}"')
108
+
109
+ properties: Dict[str, Any] = {}
110
+ required: List[str] = []
111
+ query: List[str] = []
112
+ for parameter in [*(item.get("parameters") or []), *(operation.get("parameters") or [])]:
113
+ if parameter.get("in") not in ("path", "query"):
114
+ continue
115
+ schema = _inline(document, parameter.get("schema") or {})
116
+ if parameter.get("description"):
117
+ schema = {**schema, "description": parameter["description"]}
118
+ properties[parameter["name"]] = schema
119
+ if parameter["in"] == "query":
120
+ query.append(parameter["name"])
121
+ if parameter["in"] == "path" or parameter.get("required"):
122
+ required.append(parameter["name"])
123
+ body = (operation.get("requestBody") or {}).get("content", {}).get("application/json", {}).get("schema")
124
+ if body is not None:
125
+ properties["body"] = _inline(document, body)
126
+ if operation["requestBody"].get("required"):
127
+ required.append("body")
128
+
129
+ tools.append(
130
+ {
131
+ "name": name,
132
+ "description": options.get("description") or operation.get("summary") or route,
133
+ "method": method.upper(),
134
+ "path": path,
135
+ "query": query,
136
+ "inputSchema": {"type": "object", "properties": properties, "required": required},
137
+ "readOnly": method == "get",
138
+ "destructive": options.get("destructive", method == "delete"),
139
+ }
140
+ )
141
+ return tools
142
+
143
+
144
+ def _text(value: str, is_error: bool) -> types.CallToolResult:
145
+ return types.CallToolResult(content=[types.TextContent(type="text", text=value)], is_error=is_error)
146
+
147
+
148
+ async def _call_tool(app: FastAPI, tool: dict, args: Dict[str, Any], caller_headers: Any) -> types.CallToolResult:
149
+ """Send the tool call through the app's own HTTP pipeline, in memory."""
150
+ missing: List[str] = []
151
+
152
+ def fill(match: "re.Match[str]") -> str:
153
+ value = args.get(match.group(1))
154
+ if value in (None, ""):
155
+ missing.append(match.group(1))
156
+ return quote(str(value), safe="")
157
+
158
+ path = re.sub(r"\{(\w+)\}", fill, tool["path"])
159
+ if missing:
160
+ return _text(f"Missing {', '.join(missing)}", True)
161
+
162
+ params = []
163
+ for key in tool["query"]:
164
+ value = args.get(key)
165
+ if value is None:
166
+ continue
167
+ for item in value if isinstance(value, list) else [value]:
168
+ params.append((key, str(item).lower() if isinstance(item, bool) else str(item)))
169
+
170
+ headers = {"accept": "application/json"}
171
+ for key, value in caller_headers.items():
172
+ if key.lower() not in NOT_FORWARDED:
173
+ headers[key] = value
174
+
175
+ transport = httpx.ASGITransport(app=app, raise_app_exceptions=False)
176
+ async with httpx.AsyncClient(transport=transport, base_url="http://mcp.internal") as client:
177
+ response = await client.request(
178
+ tool["method"],
179
+ path,
180
+ params=params,
181
+ headers=headers,
182
+ **({"json": args["body"]} if args.get("body") is not None else {}),
183
+ )
184
+ return _text(response.text or f"HTTP {response.status_code}", response.status_code >= 400)
185
+
186
+
187
+ def _resource_url(request: Request) -> str:
188
+ """The MCP endpoint's public URL: MCP_RESOURCE_URL, else what the request used."""
189
+ if MCP_RESOURCE:
190
+ return MCP_RESOURCE.rstrip("/")
191
+ proto = request.headers.get("x-forwarded-proto", request.url.scheme).split(",")[0].strip()
192
+ host = request.headers.get("x-forwarded-host", request.headers.get("host", "localhost")).split(",")[0].strip()
193
+ return f"{proto}://{host}{MCP_PATH}"
194
+
195
+
196
+ def _metadata_url(request: Request) -> str:
197
+ resource = urlsplit(_resource_url(request))
198
+ return f"{resource.scheme}://{resource.netloc}{PRM_PATH}{resource.path}"
199
+
200
+
201
+ def mount_mcp(app: FastAPI) -> None:
202
+ """Serve the routes marked with mcp_tool as MCP tools at POST /mcp. Call it after the routers are included."""
203
+ tools: Dict[str, dict] = {}
204
+
205
+ async def list_tools(ctx: Any, params: Any) -> types.ListToolsResult:
206
+ return types.ListToolsResult(
207
+ tools=[
208
+ types.Tool(
209
+ name=tool["name"],
210
+ description=tool["description"],
211
+ input_schema=tool["inputSchema"],
212
+ annotations=types.ToolAnnotations(
213
+ read_only_hint=tool["readOnly"], destructive_hint=tool["destructive"]
214
+ ),
215
+ )
216
+ for tool in tools.values()
217
+ ]
218
+ )
219
+
220
+ async def call_tool(ctx: Any, params: types.CallToolRequestParams) -> types.CallToolResult:
221
+ tool = tools.get(params.name)
222
+ if tool is None:
223
+ return _text(f"Unknown tool {params.name}", True)
224
+ # No caller headers means no credentials, and the route refuses the call.
225
+ return await _call_tool(app, tool, params.arguments or {}, getattr(ctx.request, "headers", {}))
226
+
227
+ server = Server(app.title or "api", version=app.version or "1.0", on_list_tools=list_tools, on_call_tool=call_tool)
228
+ manager = StreamableHTTPSessionManager(app=server, stateless=True, json_response=True)
229
+
230
+ class Endpoint:
231
+ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
232
+ request = Request(scope, receive)
233
+ if request.method != "POST":
234
+ await Response(status_code=405, headers={"allow": "POST"})(scope, receive, send)
235
+ return
236
+ try:
237
+ # The same check every /api route runs: API key, then the user's token.
238
+ await require_auth(request, Response())
239
+ except HTTPException as e:
240
+ headers = dict(e.headers or {})
241
+ presents_key = "x-api-key" in request.headers or "x-apso-service-token" in request.headers
242
+ if e.status_code == 401 and not presents_key:
243
+ # 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 "authorization" in request.headers:
246
+ challenge += ', error="invalid_token"'
247
+ headers["www-authenticate"] = challenge
248
+ await JSONResponse({"detail": e.detail}, status_code=e.status_code, headers=headers)(scope, receive, send)
249
+ return
250
+ await manager.handle_request(scope, receive, send)
251
+
252
+ async def metadata(request: Request) -> Response:
253
+ # Tells an MCP client where to sign in. Public by design, and readable
254
+ # from a browser-based client on another origin.
255
+ return JSONResponse(
256
+ {
257
+ "resource": _resource_url(request),
258
+ # Every provider's issuer, in .apsorc order. For Better Auth that
259
+ # is its base URL, the issuer of its OAuth access tokens.
260
+ "authorization_servers": [p["issuer"] for p in _PROVIDERS],
261
+ "bearer_methods_supported": ["header"],
262
+ },
263
+ headers={"access-control-allow-origin": "*", "cache-control": "max-age=300"},
264
+ )
265
+
266
+ app.router.routes.extend(
267
+ [
268
+ Route(MCP_PATH, endpoint=Endpoint()),
269
+ Route(PRM_PATH, metadata, methods=["GET"]),
270
+ Route(PRM_PATH + MCP_PATH, metadata, methods=["GET"]),
271
+ ]
272
+ )
273
+
274
+ inner = app.router.lifespan_context
275
+
276
+ @asynccontextmanager
277
+ async def lifespan(started: Any):
278
+ # Read the tools once every route is registered; a bad marker stops start-up.
279
+ tools.update({tool["name"]: tool for tool in tools_from_document(app.openapi())})
280
+ async with manager.run():
281
+ async with inner(started) as state:
282
+ yield state
283
+
284
+ app.router.lifespan_context = lifespan
@@ -53,7 +53,8 @@ class <%= it.name %>(Base):
53
53
  <%= c.name %>: Mapped[<%~ c.pyType %>] = mapped_column(<%~ c.args.join(', ') %>)
54
54
  <% }) %>
55
55
 
56
- # Relationships
56
+ # Relationships. A relation is loaded only when a request joins it
57
+ # (selectinload in the query builder), never by reading the attribute.
57
58
  <% it.associations.forEach((assoc) => { %>
58
59
  <% if (assoc.type === 'OneToMany') { %>
59
60
  <%= assoc.pluralizedRelationshipName %>: Mapped[List["<%= assoc.name %>"]] = relationship(
@@ -61,21 +62,21 @@ class <%= it.name %>(Base):
61
62
  back_populates="<%= assoc.inverseSidePropertyName %>",
62
63
  # The foreign key's ON DELETE decides, not the ORM (it would null it).
63
64
  passive_deletes="all",
64
- lazy="selectin"
65
+ lazy="raise"
65
66
  )
66
67
  <% } else if (assoc.type === 'ManyToOne' || (assoc.type === 'OneToOne' && assoc.joinTable)) { %>
67
68
  <%= assoc.relationshipName %>: Mapped[Optional["<%= assoc.name %>"]] = relationship(
68
69
  "<%= assoc.name %>",
69
70
  foreign_keys=[<%= assoc.type === 'ManyToOne' ? assoc.camelCasedId : assoc.fkColumn %>],
70
71
  <% if (assoc.biDirectional) { %>back_populates="<%= assoc.inverseSidePropertyName %>",<% } %>
71
- lazy="selectin"
72
+ lazy="raise"
72
73
  )
73
74
  <% } else if (assoc.type === 'ManyToMany' && assoc.secondary) { %>
74
75
  <%= assoc.pluralizedRelationshipName %>: Mapped[List["<%= assoc.name %>"]] = relationship(
75
76
  "<%= assoc.name %>",
76
77
  secondary="<%= assoc.secondary %>",
77
78
  <% if (assoc.biDirectional) { %>back_populates="<%= assoc.inverseSidePropertyName %>",<% } %>
78
- lazy="selectin"
79
+ lazy="raise"
79
80
  )
80
81
  <% } else if (assoc.type === 'OneToOne') { %>
81
82
  <%= assoc.relationshipName %>: Mapped[Optional["<%= assoc.name %>"]] = relationship(
@@ -83,7 +84,7 @@ class <%= it.name %>(Base):
83
84
  <% if (assoc.biDirectional) { %>back_populates="<%= assoc.inverseSidePropertyName %>",<% } %>
84
85
  uselist=False,
85
86
  cascade="all, delete-orphan",
86
- lazy="selectin"
87
+ lazy="raise"
87
88
  )
88
89
  <% } %>
89
90
  <% }) %>
@@ -0,0 +1,121 @@
1
+ <%~ includeFile('./header.eta', it) %>
2
+
3
+ """
4
+ Role permissions from .apsorc, checked on every route of the generated /api
5
+ router after authentication.
6
+
7
+ A signed-in user may perform a guarded operation when any of these holds:
8
+ - one of its roles is in the .apsorc default list
9
+ - its token carries the permission (for example Auth0 RBAC "permissions")
10
+ <% if (it.permissions.grants) { %>
11
+ - a <%= it.permissions.grants.entity %> row grants the permission to one of its roles<% if (it.permissions.grants.tenantField) { %>
12
+ in its tenant (or in every tenant, when <%= it.permissions.grants.tenantField %> is null)<% } %>
13
+
14
+ <% } %>
15
+ Grants only add access; they never take away a default. An operation that is
16
+ not listed is open to any authenticated caller. A service caller (valid API
17
+ key) is not limited by role. Every interface that calls this API (REST, SDK,
18
+ MCP) goes through this check.
19
+ """
20
+ import re
21
+ from typing import Dict, List, Set
22
+
23
+ from fastapi import Depends, HTTPException, Request, status
24
+ <% if (it.permissions.grants) { %>
25
+ from sqlalchemy import <% if (it.permissions.grants.tenantField) { %>String, cast, or_, <% } %>select
26
+ from sqlalchemy.ext.asyncio import AsyncSession
27
+
28
+ from app.database import get_db
29
+ from .models.<%= it.permissions.grants.entity.toLowerCase() %> import <%= it.permissions.grants.entity %>
30
+
31
+ <% } %>
32
+ from .auth import AuthContext, require_auth
33
+
34
+ # Guarded operations by route: the permission name and the roles that have it by default.
35
+ ENTITY_PERMISSIONS: Dict[str, Dict[str, dict]] = <%~ JSON.stringify(it.permissions.routes, null, 4) %>
36
+
37
+ # Read rules a join must satisfy, by relation name, so a caller who cannot
38
+ # read an entity cannot read it through a join either.
39
+ JOIN_PERMISSIONS: Dict[str, List[dict]] = <%~ JSON.stringify(it.permissions.joins, null, 4) %>
40
+
41
+ OPERATIONS = {
42
+ "GET": "read",
43
+ "HEAD": "read",
44
+ "POST": "create",
45
+ "PUT": "update",
46
+ "PATCH": "update",
47
+ "DELETE": "delete",
48
+ }
49
+
50
+ # A relation embedded in a PostgREST select: rel(...), alias:rel!inner(...).
51
+ _EMBED = re.compile(r"([A-Za-z_]\w*)(?:![A-Za-z]+)?\(")
52
+
53
+
54
+ def _joined(request: Request) -> List[str]:
55
+ """Every relation the query asks to load, under either query dialect."""
56
+ names: List[str] = []
57
+ for raw in request.query_params.getlist("join"):
58
+ names.extend(raw.split("||")[0].split("."))
59
+ for raw in request.query_params.getlist("select"):
60
+ names.extend(_EMBED.findall(raw))
61
+ return [n.strip() for n in names if n.strip()]
62
+
63
+
64
+ async def require_permission(
65
+ request: Request,
66
+ auth: AuthContext = Depends(require_auth),
67
+ <% if (it.permissions.grants) { %>
68
+ db: AsyncSession = Depends(get_db),
69
+ <% } %>
70
+ ) -> None:
71
+ """FastAPI dependency: 403 unless the caller may perform this operation."""
72
+ if auth.service_id:
73
+ return
74
+ granted: Set[str] = set()
75
+ loaded = False
76
+
77
+ async def allowed(rule: dict) -> bool:
78
+ nonlocal granted, loaded
79
+ if set(rule["roles"]) & set(auth.roles):
80
+ return True
81
+ if not loaded:
82
+ # The caller's permissions from its token and grants, loaded once per request.
83
+ granted = set(auth.permissions)
84
+ <% if (it.permissions.grants) { %>
85
+ if auth.roles:
86
+ # ponytail: one query per guarded request; cache per role and
87
+ # tenant with a short TTL if this shows up in latency.
88
+ query = select(<%= it.permissions.grants.entity %>.permission).where(<%= it.permissions.grants.entity %>.role.in_(auth.roles))
89
+ <% if (it.permissions.grants.tenantField) { %>
90
+ tenant = <%= it.permissions.grants.entity %>.<%= it.permissions.grants.tenantField %>
91
+
92
+ if auth.workspace_id in (None, ""):
93
+ query = query.where(tenant.is_(None))
94
+ else:
95
+ query = query.where(or_(tenant.is_(None), cast(tenant, String) == str(auth.workspace_id)))
96
+ <% } %>
97
+ granted.update((await db.execute(query)).scalars().all())
98
+ <% } %>
99
+ loaded = True
100
+ return rule["permission"] in granted
101
+
102
+ def deny(rule: dict) -> None:
103
+ raise HTTPException(
104
+ status_code=status.HTTP_403_FORBIDDEN,
105
+ detail=f"Missing permission {rule['permission']}",
106
+ )
107
+
108
+ route = request.scope.get("route")
109
+ path = getattr(route, "path", None) or request.url.path
110
+ # /api/invoices/{id}, or /invoices/{id} where the route keeps its router's own path.
111
+ segments = [p for p in path.split("/") if p]
112
+ if segments[:1] == ["api"]:
113
+ segments = segments[1:]
114
+ entity = segments[0].lower() if segments else ""
115
+ rule = ENTITY_PERMISSIONS.get(entity, {}).get(OPERATIONS.get(request.method, ""))
116
+ if rule and not await allowed(rule):
117
+ deny(rule)
118
+ for relation in _joined(request):
119
+ for joined in JOIN_PERMISSIONS.get(relation, []):
120
+ if not await allowed(joined):
121
+ deny(joined)
@@ -17,6 +17,9 @@ from ..schemas.<%= it.entityName.toLowerCase() %> import (
17
17
  )
18
18
  from ..services.<%= it.entityName.toLowerCase() %> import <%= it.entityName %>Service
19
19
  from ..utils.query import parse_query_params, QueryParseError
20
+ <% if (it.mcp.length) { %>
21
+ from ..mcp import LIST_PARAMETERS, mcp_tool
22
+ <% } %>
20
23
 
21
24
  router = APIRouter(
22
25
  prefix="/<%= it.pluralEntityName.toLowerCase() %>",
@@ -27,6 +30,9 @@ router = APIRouter(
27
30
  @router.get(
28
31
  "",
29
32
  summary="Retrieve multiple <%= it.pluralEntityName %>",
33
+ <% if (it.mcp.includes('read')) { %>
34
+ openapi_extra=mcp_tool("list_<%= it.mcpPluralName %>", "List <%= it.pluralEntityName %>. Supports filter, sort, join, limit and page.", LIST_PARAMETERS),
35
+ <% } %>
30
36
  response_model=Union[<%= it.entityName %>List, List[<%= it.entityName %>Schema]],
31
37
  )
32
38
  async def get_many(
@@ -88,6 +94,20 @@ async def get_many(
88
94
  detail=str(exc),
89
95
  )
90
96
 
97
+ if result.data and isinstance(result.data[0], dict):
98
+ # A fields= list: each row holds only the chosen columns.
99
+ return JSONResponse(
100
+ content=jsonable_encoder(
101
+ {
102
+ "data": result.data,
103
+ "count": result.count,
104
+ "total": result.total,
105
+ "page": result.page,
106
+ "pageCount": result.page_count,
107
+ }
108
+ )
109
+ )
110
+
91
111
  return <%= it.entityName %>List(
92
112
  data=result.data,
93
113
  count=result.count,
@@ -101,6 +121,9 @@ async def get_many(
101
121
  "/{id}",
102
122
  response_model=<%= it.entityName %>Schema,
103
123
  summary="Retrieve a single <%= it.entityName %>",
124
+ <% if (it.mcp.includes('read')) { %>
125
+ openapi_extra=mcp_tool("get_<%= it.mcpName %>", "Get one <%= it.entityName %> by id."),
126
+ <% } %>
104
127
  )
105
128
  async def get_one(
106
129
  id: <% if (it.primaryKeyType === 'uuid') { %>str<% } else { %>int<% } %>,
@@ -115,7 +138,13 @@ async def get_one(
115
138
  """
116
139
  service = <%= it.entityName %>Service(db, getattr(request.state, "auth", None))
117
140
 
118
- options = parse_query_params(request.query_params)
141
+ try:
142
+ options = parse_query_params(request.query_params)
143
+ except QueryParseError as exc:
144
+ raise HTTPException(
145
+ status_code=status.HTTP_400_BAD_REQUEST,
146
+ detail=str(exc),
147
+ )
119
148
  joins = [j.relation for j in options.joins] if options.joins else None
120
149
 
121
150
  item = await service.get_one(id, joins=joins)
@@ -132,6 +161,9 @@ async def get_one(
132
161
  response_model=<%= it.entityName %>Schema,
133
162
  status_code=status.HTTP_201_CREATED,
134
163
  summary="Create a single <%= it.entityName %>",
164
+ <% if (it.mcp.includes('create')) { %>
165
+ openapi_extra=mcp_tool("create_<%= it.mcpName %>", "Create a <%= it.entityName %>."),
166
+ <% } %>
135
167
  )
136
168
  async def create_one(
137
169
  request: Request,
@@ -167,6 +199,9 @@ async def create_many(
167
199
  "/{id}",
168
200
  response_model=<%= it.entityName %>Schema,
169
201
  summary="Update a single <%= it.entityName %>",
202
+ <% if (it.mcp.includes('update')) { %>
203
+ openapi_extra=mcp_tool("update_<%= it.mcpName %>", "Update fields of one <%= it.entityName %> by id."),
204
+ <% } %>
170
205
  )
171
206
  async def update_one(
172
207
  request: Request,
@@ -215,6 +250,9 @@ async def replace_one(
215
250
  "/{id}",
216
251
  status_code=status.HTTP_204_NO_CONTENT,
217
252
  summary="Delete a single <%= it.entityName %>",
253
+ <% if (it.mcp.includes('delete')) { %>
254
+ openapi_extra=mcp_tool("delete_<%= it.mcpName %>", "Delete one <%= it.entityName %> by id. This cannot be undone."),
255
+ <% } %>
218
256
  )
219
257
  async def delete_one(
220
258
  request: Request,
@@ -5,7 +5,7 @@ from typing import Optional, List, Any
5
5
  from datetime import datetime, date
6
6
  from decimal import Decimal
7
7
  from uuid import UUID
8
- from pydantic import BaseModel, Field, ConfigDict, field_serializer
8
+ from pydantic import BaseModel, Field, ConfigDict, field_serializer, model_validator
9
9
  from sqlalchemy import inspect as sa_inspect
10
10
  <% if (it.importEnums) { -%>
11
11
  from ..models import enums
@@ -22,6 +22,14 @@ def _columns(value: Any) -> Any:
22
22
  return {a.key: getattr(value, a.key) for a in sa_inspect(value).mapper.column_attrs}
23
23
 
24
24
 
25
+ def _loaded(value: Any) -> Any:
26
+ """An ORM row as the attributes its query loaded: a relation is in a response only when the request joined it."""
27
+ if not hasattr(value, "__table__"):
28
+ return value
29
+ state = sa_inspect(value)
30
+ return {key: getattr(value, key) for key in state.attrs.keys() if key not in state.unloaded}
31
+
32
+
25
33
  class <%= it.entityName %>Base(BaseModel):
26
34
  """Base schema with common fields for <%= it.entityName %>"""
27
35
  <% it.columns.filter(c => !['id', 'createdAt', 'updatedAt', 'created_at', 'updated_at'].includes(c.name)).forEach((field) => { -%>
@@ -60,6 +68,11 @@ class <%= it.entityName %>(BaseModel):
60
68
  """Full schema for <%= it.entityName %> including all fields"""
61
69
  model_config = ConfigDict(from_attributes=True, populate_by_name=True)
62
70
 
71
+ @model_validator(mode="before")
72
+ @classmethod
73
+ def _loaded_only(cls, value: Any) -> Any:
74
+ return _loaded(value)
75
+
63
76
  <% if (it.addDefaultPKProperty) { -%>
64
77
  <% if (it.primaryKeyType === 'uuid') { -%>
65
78
  id: UUID
@@ -81,15 +94,15 @@ class <%= it.entityName %>(BaseModel):
81
94
  <%= assoc.camelCasedId %>: Optional[<% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>UUID<% } else { %>int<% } %>] = None
82
95
  <% }); -%>
83
96
  <% /* Add relationship fields */ -%>
84
- <% it.associations.filter(a => a.type === 'OneToMany' || a.type === 'ManyToMany').forEach((assoc) => { -%>
97
+ <% it.associations.filter(a => !a.hidden && (a.type === 'OneToMany' || a.type === 'ManyToMany')).forEach((assoc) => { -%>
85
98
  <%= assoc.pluralizedRelationshipName %>: Optional[List[Any]] = None
86
99
  <% }); -%>
87
- <% it.associations.filter(a => a.type === 'ManyToOne' || a.type === 'OneToOne').forEach((assoc) => { -%>
100
+ <% it.associations.filter(a => !a.hidden && (a.type === 'ManyToOne' || a.type === 'OneToOne')).forEach((assoc) => { -%>
88
101
  <%= assoc.relationshipName %>: Optional[Any] = None
89
102
  <% }); -%>
90
103
  <% const relationFields = [
91
- ...it.associations.filter(a => a.type === 'OneToMany' || a.type === 'ManyToMany').map(a => a.pluralizedRelationshipName),
92
- ...it.associations.filter(a => a.type === 'ManyToOne' || a.type === 'OneToOne').map(a => a.relationshipName),
104
+ ...it.associations.filter(a => !a.hidden && (a.type === 'OneToMany' || a.type === 'ManyToMany')).map(a => a.pluralizedRelationshipName),
105
+ ...it.associations.filter(a => !a.hidden && (a.type === 'ManyToOne' || a.type === 'OneToOne')).map(a => a.relationshipName),
93
106
  ]; -%>
94
107
  <% if (relationFields.length > 0) { -%>
95
108