@apso/cli 0.47.6 → 0.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -1
- package/dist/commands/dev.d.ts +2 -0
- package/dist/commands/dev.js +20 -3
- package/dist/commands/generate.js +55 -13
- package/dist/commands/mcp/serve.js +24 -41
- package/dist/commands/schema/diff.js +3 -4
- package/dist/commands/schema/pull.js +13 -11
- package/dist/commands/schema/push.js +6 -5
- package/dist/commands/schema/validate.d.ts +10 -0
- package/dist/commands/schema/validate.js +54 -0
- package/dist/commands/test/access.d.ts +11 -0
- package/dist/commands/test/access.js +65 -0
- package/dist/lib/access/cases.d.ts +120 -0
- package/dist/lib/access/cases.js +1163 -0
- package/dist/lib/access/index.d.ts +4 -0
- package/dist/lib/access/index.js +7 -0
- package/dist/lib/access/report.d.ts +75 -0
- package/dist/lib/access/report.js +118 -0
- package/dist/lib/access/rules.json +207 -0
- package/dist/lib/access/run.d.ts +38 -0
- package/dist/lib/access/run.js +111 -0
- package/dist/lib/access/tokens.d.ts +46 -0
- package/dist/lib/access/tokens.js +139 -0
- package/dist/lib/api/services.d.ts +10 -7
- package/dist/lib/api/services.js +19 -32
- package/dist/lib/apsorc-parser.d.ts +1 -1
- package/dist/lib/apsorc-parser.js +2 -0
- package/dist/lib/ddl/change.js +2 -0
- package/dist/lib/ddl/index.d.ts +11 -1
- package/dist/lib/ddl/index.js +30 -16
- package/dist/lib/ddl/sync.d.ts +25 -0
- package/dist/lib/ddl/sync.js +78 -0
- package/dist/lib/deploy/server-push.js +3 -1
- package/dist/lib/generators/go.d.ts +25 -7
- package/dist/lib/generators/go.js +365 -128
- package/dist/lib/generators/python.d.ts +9 -3
- package/dist/lib/generators/python.js +282 -47
- package/dist/lib/generators/typescript.d.ts +3 -5
- package/dist/lib/generators/typescript.js +78 -64
- package/dist/lib/guards.d.ts +111 -13
- package/dist/lib/guards.js +287 -23
- package/dist/lib/templates/entities/entity-col-array.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-array.eta +2 -2
- package/dist/lib/templates/go/dto/dto-col-date.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-decimal.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-enum.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-float.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-integer.eta +3 -3
- package/dist/lib/templates/go/dto/dto-col-numeric.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-string.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-text.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-timestamp.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-timestamptz.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-uuid.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-varchar.eta +1 -1
- package/dist/lib/templates/go/dto/dto.eta +17 -18
- package/dist/lib/templates/go/handlers/handler.eta +10 -8
- package/dist/lib/templates/go/handlers/scope.eta +3 -2
- package/dist/lib/templates/go/index-module.eta +10 -5
- package/dist/lib/templates/go/mcp.eta +307 -0
- package/dist/lib/templates/go/middleware/auth.eta +587 -166
- package/dist/lib/templates/go/middleware/permission.eta +174 -0
- package/dist/lib/templates/go/models/model.eta +22 -19
- package/dist/lib/templates/go/models/schema.eta +72 -0
- package/dist/lib/templates/go/services/service.eta +84 -35
- package/dist/lib/templates/go/utils/query.eta +68 -7
- package/dist/lib/templates/guards/guards.module.eta +37 -29
- package/dist/lib/templates/guards/index.eta +4 -0
- package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
- package/dist/lib/templates/guards/key.guard.eta +280 -0
- package/dist/lib/templates/guards/permission.guard.eta +168 -0
- package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
- package/dist/lib/templates/guards/scope.guard.eta +189 -41
- package/dist/lib/templates/python/auth.eta +354 -95
- package/dist/lib/templates/python/index-module.eta +7 -7
- package/dist/lib/templates/python/mcp.eta +284 -0
- package/dist/lib/templates/python/models/init.eta +24 -0
- package/dist/lib/templates/python/models/model.eta +30 -61
- package/dist/lib/templates/python/permissions.eta +121 -0
- package/dist/lib/templates/python/routers/router.eta +39 -1
- package/dist/lib/templates/python/schemas/schema-col-array.eta +1 -1
- package/dist/lib/templates/python/schemas/schema.eta +27 -14
- package/dist/lib/templates/python/services/service.eta +38 -15
- package/dist/lib/templates/python/utils/query.eta +52 -25
- package/dist/lib/templates/rest/controller-rest.eta +43 -23
- package/dist/lib/templates/rest/index-module-rest.eta +0 -4
- package/dist/lib/templates/rest/service-rest.eta +3 -44
- package/dist/lib/types/auth.d.ts +84 -80
- package/dist/lib/types/auth.js +77 -60
- package/dist/lib/types/entity.d.ts +17 -9
- package/dist/lib/types/entity.js +3 -0
- package/dist/lib/types/index.d.ts +2 -2
- package/dist/lib/types/index.js +6 -5
- package/dist/lib/utils/crud-deps.d.ts +77 -6
- package/dist/lib/utils/crud-deps.js +197 -14
- package/dist/lib/utils/field.d.ts +12 -0
- package/dist/lib/utils/field.js +18 -2
- package/dist/lib/utils/schema-convert.d.ts +20 -43
- package/dist/lib/utils/schema-convert.js +28 -78
- package/dist/lib/utils/template.d.ts +11 -0
- package/dist/lib/utils/template.js +36 -1
- package/dist/lib/verify/index.d.ts +6 -1
- package/dist/lib/verify/index.js +30 -13
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +36 -1
- package/package.json +1 -1
- package/dist/lib/templates/go/models/model-col-array.eta +0 -1
- package/dist/lib/templates/go/models/model-col-boolean.eta +0 -1
- package/dist/lib/templates/go/models/model-col-date.eta +0 -1
- package/dist/lib/templates/go/models/model-col-decimal.eta +0 -1
- package/dist/lib/templates/go/models/model-col-enum.eta +0 -2
- package/dist/lib/templates/go/models/model-col-float.eta +0 -1
- package/dist/lib/templates/go/models/model-col-integer.eta +0 -1
- package/dist/lib/templates/go/models/model-col-json.eta +0 -1
- package/dist/lib/templates/go/models/model-col-jsonb.eta +0 -1
- package/dist/lib/templates/go/models/model-col-numeric.eta +0 -1
- package/dist/lib/templates/go/models/model-col-string.eta +0 -1
- package/dist/lib/templates/go/models/model-col-text.eta +0 -1
- package/dist/lib/templates/go/models/model-col-timestamp.eta +0 -1
- package/dist/lib/templates/go/models/model-col-timestamptz.eta +0 -1
- package/dist/lib/templates/go/models/model-col-uuid.eta +0 -1
- package/dist/lib/templates/go/models/model-col-varchar.eta +0 -1
- package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
- package/dist/lib/templates/guards/auth.guard.eta +0 -233
- package/dist/lib/templates/python/models/model-col-array.eta +0 -4
- package/dist/lib/templates/python/models/model-col-boolean.eta +0 -6
- package/dist/lib/templates/python/models/model-col-date.eta +0 -4
- package/dist/lib/templates/python/models/model-col-datetime.eta +0 -5
- package/dist/lib/templates/python/models/model-col-decimal.eta +0 -4
- package/dist/lib/templates/python/models/model-col-enum.eta +0 -16
- package/dist/lib/templates/python/models/model-col-float.eta +0 -6
- package/dist/lib/templates/python/models/model-col-integer.eta +0 -6
- package/dist/lib/templates/python/models/model-col-json.eta +0 -4
- package/dist/lib/templates/python/models/model-col-jsonb.eta +0 -4
- package/dist/lib/templates/python/models/model-col-numeric.eta +0 -4
- package/dist/lib/templates/python/models/model-col-string.eta +0 -6
- package/dist/lib/templates/python/models/model-col-text.eta +0 -6
- package/dist/lib/templates/python/models/model-col-timestamp.eta +0 -11
- package/dist/lib/templates/python/models/model-col-timestamptz.eta +0 -11
- package/dist/lib/templates/python/models/model-col-uuid.eta +0 -5
- package/dist/lib/templates/python/models/model-col-varchar.eta +0 -6
|
@@ -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
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
<%~ includeFile('../header.eta', it) %>
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import event
|
|
4
|
+
|
|
5
|
+
from app.database import Base
|
|
6
|
+
<% it.modules.forEach(([m, name]) => { %>
|
|
7
|
+
from .<%= m %> import <%= name %> # noqa: F401
|
|
8
|
+
<% }) %>
|
|
9
|
+
|
|
10
|
+
# Run by create_all (DATABASE_SYNC=true) before it creates any table: the
|
|
11
|
+
# extensions the tables need, and a check that stops, printing the renames to
|
|
12
|
+
# run, when the database still has a join table or enum type under the name
|
|
13
|
+
# older generated models gave it.
|
|
14
|
+
_BEFORE_CREATE = [
|
|
15
|
+
<% it.statements.forEach((s) => { %>
|
|
16
|
+
<%~ s %>,
|
|
17
|
+
<% }) %>
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@event.listens_for(Base.metadata, "before_create")
|
|
22
|
+
def _apso_before_create(target, connection, **kw):
|
|
23
|
+
for statement in _BEFORE_CREATE:
|
|
24
|
+
connection.exec_driver_sql(statement)
|
|
@@ -6,8 +6,8 @@ from datetime import datetime, date
|
|
|
6
6
|
from decimal import Decimal
|
|
7
7
|
from uuid import UUID
|
|
8
8
|
|
|
9
|
-
from sqlalchemy import Column, Integer, String, Text, Boolean, Float, Numeric, Date, DateTime, JSON, Enum as SAEnum, ForeignKey, Index, UniqueConstraint, Table
|
|
10
|
-
from sqlalchemy.dialects.postgresql import UUID as PGUUID, JSONB, ARRAY,
|
|
9
|
+
from sqlalchemy import CHAR, Column, Integer, SmallInteger, BigInteger, String, Text, Boolean, Float, Numeric, Date, DateTime, JSON, Enum as SAEnum, ForeignKey, Index, PrimaryKeyConstraint, UniqueConstraint, Table, text
|
|
10
|
+
from sqlalchemy.dialects.postgresql import UUID as PGUUID, JSONB, ARRAY, DOUBLE_PRECISION, REAL
|
|
11
11
|
from sqlalchemy.orm import relationship, Mapped, mapped_column
|
|
12
12
|
from sqlalchemy.sql import func
|
|
13
13
|
|
|
@@ -23,13 +23,18 @@ if TYPE_CHECKING:
|
|
|
23
23
|
<% }) %>
|
|
24
24
|
<% } %>
|
|
25
25
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
# Tables, columns, keys, indexes and constraints are named and typed exactly as
|
|
27
|
+
# the migrations from `apso migrate` create them.
|
|
28
|
+
<% it.joinTables.forEach((join) => { %>
|
|
29
|
+
<%= join.name %> = Table(
|
|
30
|
+
"<%= join.name %>",
|
|
30
31
|
Base.metadata,
|
|
31
|
-
|
|
32
|
-
Column("<%=
|
|
32
|
+
<% join.columns.forEach((c) => { %>
|
|
33
|
+
Column("<%= c.name %>", <%~ c.args.join(', ') %>),
|
|
34
|
+
<% }) %>
|
|
35
|
+
<% join.tableArgs.forEach((a) => { %>
|
|
36
|
+
<%~ a %>,
|
|
37
|
+
<% }) %>
|
|
33
38
|
)
|
|
34
39
|
<% }) %>
|
|
35
40
|
|
|
@@ -38,76 +43,40 @@ class <%= it.name %>(Base):
|
|
|
38
43
|
SQLAlchemy model for <%= it.name %>
|
|
39
44
|
"""
|
|
40
45
|
__tablename__ = "<%= it.tableName %>"
|
|
41
|
-
|
|
42
|
-
<% /* Generate table arguments for indexes and unique constraints */ %>
|
|
43
|
-
<% if ((it.indexes && it.indexes.length > 0) || (it.uniques && it.uniques.length > 0)) { %>
|
|
44
46
|
__table_args__ = (
|
|
45
|
-
<% it.
|
|
46
|
-
|
|
47
|
-
<% }) %>
|
|
48
|
-
<% it.uniques.forEach((unique) => { %>
|
|
49
|
-
UniqueConstraint(<%~ unique.fields.map(f => `"${f}"`).join(', ') %><% if (unique.name) { %>, name="<%= unique.name %>"<% } %>),
|
|
47
|
+
<% it.tableArgs.forEach((a) => { %>
|
|
48
|
+
<%~ a %>,
|
|
50
49
|
<% }) %>
|
|
51
50
|
)
|
|
52
|
-
<% } %>
|
|
53
51
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
<%
|
|
57
|
-
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True)
|
|
58
|
-
<% } else { %>
|
|
59
|
-
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
|
60
|
-
<% } %>
|
|
61
|
-
<% } %>
|
|
62
|
-
|
|
63
|
-
<% /* Timestamp columns */ %>
|
|
64
|
-
<% if (it.createdAt) { %>
|
|
65
|
-
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
66
|
-
<% } %>
|
|
67
|
-
<% if (it.updatedAt) { %>
|
|
68
|
-
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
|
69
|
-
<% } %>
|
|
70
|
-
|
|
71
|
-
# Columns
|
|
72
|
-
<%
|
|
73
|
-
// Filter out id (if createPrimaryKey), createdAt, and updatedAt since they're handled separately
|
|
74
|
-
const columnsToProcess = it.columns.filter(c => {
|
|
75
|
-
if (it.createPrimaryKey && c.name === 'id') return false;
|
|
76
|
-
if (it.createdAt && c.name === 'createdAt') return false;
|
|
77
|
-
if (it.updatedAt && c.name === 'updatedAt') return false;
|
|
78
|
-
return true;
|
|
79
|
-
});
|
|
80
|
-
columnsToProcess.forEach((field) => { -%>
|
|
81
|
-
<%~ includeFile(`./model-col-${field.type}`, { field, entityName: it.name }) %>
|
|
82
|
-
<% }); %>
|
|
52
|
+
<% it.columns.forEach((c) => { %>
|
|
53
|
+
<%= c.name %>: Mapped[<%~ c.pyType %>] = mapped_column(<%~ c.args.join(', ') %>)
|
|
54
|
+
<% }) %>
|
|
83
55
|
|
|
84
|
-
# Relationships
|
|
56
|
+
# Relationships. A relation is loaded only when a request joins it
|
|
57
|
+
# (selectinload in the query builder), never by reading the attribute.
|
|
85
58
|
<% it.associations.forEach((assoc) => { %>
|
|
86
59
|
<% if (assoc.type === 'OneToMany') { %>
|
|
87
60
|
<%= assoc.pluralizedRelationshipName %>: Mapped[List["<%= assoc.name %>"]] = relationship(
|
|
88
61
|
"<%= assoc.name %>",
|
|
89
62
|
back_populates="<%= assoc.inverseSidePropertyName %>",
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
# Foreign key for <%= assoc.name %>
|
|
94
|
-
<%= assoc.camelCasedId %>: Mapped[<% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>Optional[UUID]<% } else { %>Optional[int]<% } %>] = mapped_column(
|
|
95
|
-
<% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>PGUUID(as_uuid=True)<% } else { %>Integer<% } %>,
|
|
96
|
-
ForeignKey("<%= it.tableNames[assoc.name] || assoc.name.toLowerCase() %>.id"<% if (assoc.cascadeDelete) { %>, ondelete="CASCADE"<% } %>),
|
|
97
|
-
nullable=<%= assoc.nullable ? 'True' : 'False' %><% if (assoc.index) { %>,
|
|
98
|
-
index=True<% } %>
|
|
63
|
+
# The foreign key's ON DELETE decides, not the ORM (it would null it).
|
|
64
|
+
passive_deletes="all",
|
|
65
|
+
lazy="raise"
|
|
99
66
|
)
|
|
67
|
+
<% } else if (assoc.type === 'ManyToOne' || (assoc.type === 'OneToOne' && assoc.joinTable)) { %>
|
|
100
68
|
<%= assoc.relationshipName %>: Mapped[Optional["<%= assoc.name %>"]] = relationship(
|
|
101
69
|
"<%= assoc.name %>",
|
|
70
|
+
foreign_keys=[<%= assoc.type === 'ManyToOne' ? assoc.camelCasedId : assoc.fkColumn %>],
|
|
102
71
|
<% if (assoc.biDirectional) { %>back_populates="<%= assoc.inverseSidePropertyName %>",<% } %>
|
|
103
|
-
lazy="
|
|
72
|
+
lazy="raise"
|
|
104
73
|
)
|
|
105
|
-
<% } else if (assoc.type === 'ManyToMany') { %>
|
|
74
|
+
<% } else if (assoc.type === 'ManyToMany' && assoc.secondary) { %>
|
|
106
75
|
<%= assoc.pluralizedRelationshipName %>: Mapped[List["<%= assoc.name %>"]] = relationship(
|
|
107
76
|
"<%= assoc.name %>",
|
|
108
|
-
secondary
|
|
77
|
+
secondary="<%= assoc.secondary %>",
|
|
109
78
|
<% if (assoc.biDirectional) { %>back_populates="<%= assoc.inverseSidePropertyName %>",<% } %>
|
|
110
|
-
lazy="
|
|
79
|
+
lazy="raise"
|
|
111
80
|
)
|
|
112
81
|
<% } else if (assoc.type === 'OneToOne') { %>
|
|
113
82
|
<%= assoc.relationshipName %>: Mapped[Optional["<%= assoc.name %>"]] = relationship(
|
|
@@ -115,7 +84,7 @@ columnsToProcess.forEach((field) => { -%>
|
|
|
115
84
|
<% if (assoc.biDirectional) { %>back_populates="<%= assoc.inverseSidePropertyName %>",<% } %>
|
|
116
85
|
uselist=False,
|
|
117
86
|
cascade="all, delete-orphan",
|
|
118
|
-
lazy="
|
|
87
|
+
lazy="raise"
|
|
119
88
|
)
|
|
120
89
|
<% } %>
|
|
121
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
|
-
|
|
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,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<%= it.field.name %>: <% if (!it.field.required || it.forUpdate) { %>Optional[List[<%= it.field.
|
|
1
|
+
<%= it.field.name %>: <% if (!it.field.required || it.forUpdate) { %>Optional[List[<%= it.field.arrayItemType %>]] = None<% } else { %>List[<%= it.field.arrayItemType %>]<% } %>
|