fastapi-apcore 0.4.0__tar.gz → 0.5.1__tar.gz

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 (47) hide show
  1. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/PKG-INFO +32 -7
  2. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/README.md +27 -2
  3. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/pyproject.toml +12 -5
  4. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/cli.py +16 -4
  5. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/client.py +19 -3
  6. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/engine/shortcuts.py +12 -4
  7. fastapi_apcore-0.5.1/src/fastapi_apcore/governance.py +105 -0
  8. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/output/registry_writer.py +17 -28
  9. fastapi_apcore-0.5.1/src/fastapi_apcore/scanners/base.py +202 -0
  10. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/scanners/native.py +34 -24
  11. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/scanners/openapi.py +10 -11
  12. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore.egg-info/PKG-INFO +32 -7
  13. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore.egg-info/SOURCES.txt +3 -0
  14. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore.egg-info/requires.txt +4 -4
  15. fastapi_apcore-0.5.1/tests/test_acl_demo.py +58 -0
  16. fastapi_apcore-0.5.1/tests/test_governance.py +85 -0
  17. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_integration.py +25 -0
  18. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_scanner.py +110 -0
  19. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_writers.py +68 -0
  20. fastapi_apcore-0.4.0/src/fastapi_apcore/scanners/base.py +0 -114
  21. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/setup.cfg +0 -0
  22. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/__init__.py +0 -0
  23. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/engine/__init__.py +0 -0
  24. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/engine/config.py +0 -0
  25. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/engine/context.py +0 -0
  26. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/engine/extensions.py +0 -0
  27. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/engine/observability.py +0 -0
  28. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/engine/registry.py +0 -0
  29. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/engine/serializers.py +0 -0
  30. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/engine/tasks.py +0 -0
  31. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/output/__init__.py +0 -0
  32. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/output/yaml_writer.py +0 -0
  33. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/py.typed +0 -0
  34. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore/scanners/__init__.py +0 -0
  35. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore.egg-info/dependency_links.txt +0 -0
  36. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore.egg-info/entry_points.txt +0 -0
  37. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/src/fastapi_apcore.egg-info/top_level.txt +0 -0
  38. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_client.py +0 -0
  39. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_config.py +0 -0
  40. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_context.py +0 -0
  41. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_extensions.py +0 -0
  42. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_observability.py +0 -0
  43. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_public_api.py +0 -0
  44. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_registry.py +0 -0
  45. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_serializers.py +0 -0
  46. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_shortcuts.py +0 -0
  47. {fastapi_apcore-0.4.0 → fastapi_apcore-0.5.1}/tests/test_tasks.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastapi-apcore
3
- Version: 0.4.0
3
+ Version: 0.5.1
4
4
  Summary: FastAPI integration for apcore AI-Perceivable Core — exposes FastAPI routes as apcore modules with auto-discovery, schema extraction from Pydantic models, and OpenAPI-based scanning.
5
5
  Author-email: aiperceivable <team@aiperceivable.com>
6
6
  License-Expression: Apache-2.0
@@ -10,12 +10,12 @@ Keywords: fastapi,apcore,mcp,llm,ai,tools,pydantic,schema,module,cli,auto-discov
10
10
  Requires-Python: >=3.11
11
11
  Description-Content-Type: text/markdown
12
12
  Requires-Dist: fastapi>=0.100
13
- Requires-Dist: apcore>=0.14.0
14
- Requires-Dist: apcore-toolkit>=0.4.1
13
+ Requires-Dist: apcore>=0.32.2
14
+ Requires-Dist: apcore-toolkit>=0.14.1
15
15
  Provides-Extra: mcp
16
- Requires-Dist: apcore-mcp>=0.11.0; extra == "mcp"
16
+ Requires-Dist: apcore-mcp>=0.23.3; extra == "mcp"
17
17
  Provides-Extra: cli
18
- Requires-Dist: apcore-cli>=0.4.0; extra == "cli"
18
+ Requires-Dist: apcore-cli>=0.12.6; extra == "cli"
19
19
  Requires-Dist: click>=8.0; extra == "cli"
20
20
  Provides-Extra: all
21
21
  Requires-Dist: fastapi-apcore[cli,mcp]; extra == "all"
@@ -59,8 +59,10 @@ FastAPI integration for [apcore](https://github.com/aiperceivable/apcore-python)
59
59
 
60
60
  - Python >= 3.11
61
61
  - FastAPI >= 0.100
62
- - apcore >= 0.13.1
63
- - apcore-toolkit >= 0.4.0
62
+ - apcore >= 0.32.2
63
+ - apcore-toolkit >= 0.14.1
64
+ - apcore-mcp >= 0.23.3 (optional, `[mcp]` extra)
65
+ - apcore-cli >= 0.12.6 (optional, `[cli]` extra)
64
66
 
65
67
  ## Installation
66
68
 
@@ -394,6 +396,29 @@ All settings are read from environment variables with the `APCORE_` prefix:
394
396
  | `APCORE_ACL_PATH` | — | Path to ACL YAML rules file |
395
397
  | `APCORE_MIDDLEWARES` | — | Comma-separated middleware dotted paths |
396
398
 
399
+ #### Access control (ACL)
400
+
401
+ Set `APCORE_ACL_PATH` to a YAML rules file and apcore enforces role-based
402
+ `allow`/`deny` on every module call. Roles come from the request's
403
+ authenticated user: `FastAPIContextFactory` reads `request.state.user`
404
+ (`roles` / `groups` / `scopes`) into the apcore `Identity` that ACL conditions
405
+ match against. A denied call raises `ACLDeniedError`, which your route maps to
406
+ HTTP 403.
407
+
408
+ ```yaml
409
+ # acl.yaml
410
+ default_effect: deny
411
+ rules:
412
+ - description: Admins may call any module
413
+ callers: ["*"]
414
+ targets: ["*"]
415
+ effect: allow
416
+ conditions: { roles: ["admin"] }
417
+ ```
418
+
419
+ See **[`examples/acl_demo/`](examples/acl_demo/)** for a runnable FastAPI app
420
+ plus integration tests (`tests/test_acl_demo.py`).
421
+
397
422
  ### Observability
398
423
 
399
424
  | Variable | Default | Description |
@@ -29,8 +29,10 @@ FastAPI integration for [apcore](https://github.com/aiperceivable/apcore-python)
29
29
 
30
30
  - Python >= 3.11
31
31
  - FastAPI >= 0.100
32
- - apcore >= 0.13.1
33
- - apcore-toolkit >= 0.4.0
32
+ - apcore >= 0.32.2
33
+ - apcore-toolkit >= 0.14.1
34
+ - apcore-mcp >= 0.23.3 (optional, `[mcp]` extra)
35
+ - apcore-cli >= 0.12.6 (optional, `[cli]` extra)
34
36
 
35
37
  ## Installation
36
38
 
@@ -364,6 +366,29 @@ All settings are read from environment variables with the `APCORE_` prefix:
364
366
  | `APCORE_ACL_PATH` | — | Path to ACL YAML rules file |
365
367
  | `APCORE_MIDDLEWARES` | — | Comma-separated middleware dotted paths |
366
368
 
369
+ #### Access control (ACL)
370
+
371
+ Set `APCORE_ACL_PATH` to a YAML rules file and apcore enforces role-based
372
+ `allow`/`deny` on every module call. Roles come from the request's
373
+ authenticated user: `FastAPIContextFactory` reads `request.state.user`
374
+ (`roles` / `groups` / `scopes`) into the apcore `Identity` that ACL conditions
375
+ match against. A denied call raises `ACLDeniedError`, which your route maps to
376
+ HTTP 403.
377
+
378
+ ```yaml
379
+ # acl.yaml
380
+ default_effect: deny
381
+ rules:
382
+ - description: Admins may call any module
383
+ callers: ["*"]
384
+ targets: ["*"]
385
+ effect: allow
386
+ conditions: { roles: ["admin"] }
387
+ ```
388
+
389
+ See **[`examples/acl_demo/`](examples/acl_demo/)** for a runnable FastAPI app
390
+ plus integration tests (`tests/test_acl_demo.py`).
391
+
367
392
  ### Observability
368
393
 
369
394
  | Variable | Default | Description |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "fastapi-apcore"
7
- version = "0.4.0"
7
+ version = "0.5.1"
8
8
  description = "FastAPI integration for apcore AI-Perceivable Core — exposes FastAPI routes as apcore modules with auto-discovery, schema extraction from Pydantic models, and OpenAPI-based scanning."
9
9
  requires-python = ">=3.11"
10
10
  readme = "README.md"
@@ -28,13 +28,13 @@ keywords = [
28
28
  ]
29
29
  dependencies = [
30
30
  "fastapi>=0.100",
31
- "apcore>=0.14.0",
32
- "apcore-toolkit>=0.4.1",
31
+ "apcore>=0.32.2",
32
+ "apcore-toolkit>=0.14.1",
33
33
  ]
34
34
 
35
35
  [project.optional-dependencies]
36
- mcp = ["apcore-mcp>=0.11.0"]
37
- cli = ["apcore-cli>=0.4.0", "click>=8.0"]
36
+ mcp = ["apcore-mcp>=0.23.3"]
37
+ cli = ["apcore-cli>=0.12.6", "click>=8.0"]
38
38
  all = ["fastapi-apcore[mcp,cli]"]
39
39
  dev = [
40
40
  "apdev[dev]>=0.2.3",
@@ -64,6 +64,13 @@ src = ["src"]
64
64
  target-version = "py311"
65
65
  line-length = 120
66
66
 
67
+ [tool.ruff.lint]
68
+ # Pin the rule set explicitly. Ruff's implicit default selection changes between
69
+ # releases (0.16 widened it from E4/E7/E9/F to a much larger set), which made CI
70
+ # fail on a newer ruff while an older local ruff passed. Widening the selection
71
+ # is a deliberate change, not a side effect of upgrading the linter.
72
+ select = ["E4", "E7", "E9", "F"]
73
+
67
74
  [tool.mypy]
68
75
  python_version = "3.11"
69
76
  strict = true
@@ -136,6 +136,12 @@ def create_cli() -> Any:
136
136
  tags: str = typer.Option(None, "--tags", help="Comma-separated tags filter."),
137
137
  prefix: str = typer.Option(None, "--prefix", help="Module ID prefix filter."),
138
138
  log_level: str = typer.Option(None, "--log-level", help="Log level: DEBUG, INFO, WARNING, ERROR."),
139
+ policy: str = typer.Option(
140
+ None,
141
+ "--policy",
142
+ help="Path to an external governance policy YAML (marks requires_approval / destructive "
143
+ "on matching modules without touching the app's source).",
144
+ ),
139
145
  ) -> None:
140
146
  """Start an MCP server exposing registered apcore modules as tools."""
141
147
  app = _load_app(app_path)
@@ -144,7 +150,7 @@ def create_cli() -> Any:
144
150
  from fastapi_apcore.client import FastAPIApcore
145
151
 
146
152
  apcore = FastAPIApcore.get_instance()
147
- apcore.init_app(app)
153
+ apcore.init_app(app, policy_path=policy)
148
154
 
149
155
  from fastapi_apcore.engine.config import get_apcore_settings
150
156
  from fastapi_apcore.engine.registry import get_executor, get_registry, get_metrics_collector
@@ -217,8 +223,11 @@ def create_cli() -> Any:
217
223
  use_executor = bool(settings.middlewares or settings.acl_path or settings.executor_config)
218
224
  registry_or_executor = get_executor() if use_executor else registry
219
225
 
220
- typer.echo(f"[fastapi-apcore] Starting MCP server '{name}' via {transport}...")
221
- typer.echo(f"[fastapi-apcore] {registry.count} modules registered.")
226
+ # Diagnostics MUST go to stderr: under the stdio transport, stdout is the
227
+ # MCP JSON-RPC stream and any stray text corrupts it (strict clients like
228
+ # Claude Desktop reject the whole stream).
229
+ typer.echo(f"[fastapi-apcore] Starting MCP server '{name}' via {transport}...", err=True)
230
+ typer.echo(f"[fastapi-apcore] {registry.count} modules registered.", err=True)
222
231
 
223
232
  try:
224
233
  from apcore_mcp import serve as mcp_serve
@@ -339,6 +348,8 @@ def create_cli() -> Any:
339
348
  max_age: int = typer.Option(None, "--max-age", help="Max age in seconds for completed tasks."),
340
349
  ) -> None:
341
350
  """Clean up old completed tasks."""
351
+ import asyncio
352
+
342
353
  from fastapi_apcore.engine.config import get_apcore_settings
343
354
  from fastapi_apcore.engine.tasks import get_task_manager
344
355
 
@@ -346,7 +357,8 @@ def create_cli() -> Any:
346
357
  max_age = get_apcore_settings().task_cleanup_age
347
358
 
348
359
  tm = get_task_manager()
349
- count = tm.cleanup(max_age_seconds=max_age)
360
+ # apcore >= 0.22 made AsyncTaskManager.cleanup() a coroutine.
361
+ count = asyncio.run(tm.cleanup(max_age_seconds=max_age))
350
362
  typer.echo(f"Cleaned up {count} tasks.")
351
363
 
352
364
  return cli
@@ -73,6 +73,7 @@ class FastAPIApcore:
73
73
  simplify_ids: bool = False,
74
74
  include: str | None = None,
75
75
  exclude: str | None = None,
76
+ policy_path: str | None = None,
76
77
  ) -> None:
77
78
  """Initialize fastapi-apcore with a FastAPI application.
78
79
 
@@ -117,6 +118,14 @@ class FastAPIApcore:
117
118
  from fastapi_apcore.output import get_writer
118
119
 
119
120
  scanned = self.scan(app, source=scan_source, simplify_ids=simplify_ids, include=include, exclude=exclude)
121
+ # Apply external governance policy (marks requires_approval /
122
+ # destructive) before registration so approval gating reflects the
123
+ # operator's decision — without modifying the target app's source.
124
+ effective_policy = policy_path or getattr(settings, "policy_path", None)
125
+ if scanned and effective_policy:
126
+ from fastapi_apcore.governance import apply_policy, load_policy
127
+
128
+ scanned = apply_policy(scanned, load_policy(effective_policy))
120
129
  if scanned:
121
130
  writer = get_writer(None) # RegistryWriter
122
131
  writer.write(scanned, registry)
@@ -656,7 +665,7 @@ class FastAPIApcore:
656
665
  import click
657
666
  from apcore_cli.cli import GroupedModuleGroup, set_docs_url, set_verbose_help
658
667
  from apcore_cli.discovery import register_discovery_commands
659
- from apcore_cli.shell import configure_man_help, register_shell_commands
668
+ from apcore_cli.shell import configure_man_help, register_completion_command
660
669
  except ImportError:
661
670
  raise ImportError(
662
671
  "apcore-cli is required for create_cli(). " "Install with: pip install fastapi-apcore[cli]"
@@ -724,7 +733,14 @@ class FastAPIApcore:
724
733
  ctx_settings["max_content_width"] = max_content_width
725
734
 
726
735
  effective_width = max_content_width
727
- _cli_description = f"{prog_name} — CLI for {app.title or 'FastAPI'} API."
736
+ _cli_description = (
737
+ f"{prog_name} — CLI for {app.title or 'FastAPI'} API.\n\n"
738
+ "Tips:\n"
739
+ f" {prog_name} --help --verbose Show all options including built-in apcore flags\n"
740
+ f" {prog_name} --help --man Generate a full roff man page for all commands\n"
741
+ f" {prog_name} list List all available commands\n"
742
+ f" {prog_name} describe MODULE_ID Show schema and annotations for a command"
743
+ )
728
744
 
729
745
  @click.group(
730
746
  cls=GroupedModuleGroup,
@@ -764,7 +780,7 @@ class FastAPIApcore:
764
780
  set_verbose_help(True)
765
781
 
766
782
  register_discovery_commands(cli, registry)
767
- register_shell_commands(cli, prog_name=prog_name)
783
+ register_completion_command(cli, prog_name=prog_name)
768
784
 
769
785
  # Enable --help --man to generate a full roff man page covering all commands.
770
786
  configure_man_help(
@@ -116,9 +116,13 @@ def cancellable_call(
116
116
  if context is None:
117
117
  if request is not None:
118
118
  context = get_context_factory().create_context(request)
119
+ context.cancel_token = token
119
120
  else:
120
- context = Context.create()
121
- context.cancel_token = token
121
+ # apcore >= 0.22 exposes cancel_token as a first-class Context.create()
122
+ # parameter, replacing the post-hoc `context.cancel_token = token` anti-pattern.
123
+ context = Context.create(cancel_token=token)
124
+ else:
125
+ context.cancel_token = token
122
126
 
123
127
  if timeout is None:
124
128
  timeout = get_apcore_settings().cancel_default_timeout
@@ -158,9 +162,13 @@ async def cancellable_call_async(
158
162
  if context is None:
159
163
  if request is not None:
160
164
  context = get_context_factory().create_context(request)
165
+ context.cancel_token = token
161
166
  else:
162
- context = Context.create()
163
- context.cancel_token = token
167
+ # apcore >= 0.22 exposes cancel_token as a first-class Context.create()
168
+ # parameter, replacing the post-hoc `context.cancel_token = token` anti-pattern.
169
+ context = Context.create(cancel_token=token)
170
+ else:
171
+ context.cancel_token = token
164
172
 
165
173
  if timeout is None:
166
174
  timeout = get_apcore_settings().cancel_default_timeout
@@ -0,0 +1,105 @@
1
+ """External governance policy for scanned modules.
2
+
3
+ Behavioral annotations inferred from HTTP method (``GET`` -> readonly,
4
+ ``DELETE`` -> destructive) never set ``requires_approval`` -- and a money-moving
5
+ ``POST`` (e.g. ``/refund``) is not even flagged destructive. Deciding *what needs
6
+ human approval* is a governance choice, not something a heuristic can infer.
7
+
8
+ This module lets an operator declare that choice in an **external policy file**,
9
+ applied to scanned modules **without touching the target application's source**
10
+ (the outside-in governance model). A policy is a mapping::
11
+
12
+ # governance.yaml
13
+ require_approval: # module_id glob patterns -> requires_approval=True
14
+ - "*delete*"
15
+ - "*refund*"
16
+ mark_destructive: # module_id glob patterns -> destructive=True (optional)
17
+ - "*refund*"
18
+
19
+ Patterns are matched against each module's ``module_id`` with :func:`fnmatch.fnmatch`.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import dataclasses
25
+ import logging
26
+ from fnmatch import fnmatch
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from apcore import ModuleAnnotations
31
+
32
+ logger = logging.getLogger("fastapi_apcore")
33
+
34
+ # Modules are typed ``Any``: fastapi-apcore's local ``scanners.base.ScannedModule``
35
+ # and the canonical ``apcore_toolkit.types.ScannedModule`` have drifted into two
36
+ # distinct dataclasses. Policy application is duck-typed on the ``module_id`` and
37
+ # ``annotations`` fields, which both variants share.
38
+
39
+ _PATTERN_KEYS = ("require_approval", "mark_destructive")
40
+
41
+
42
+ def load_policy(path: str | Path) -> dict[str, Any]:
43
+ """Load a governance policy from a YAML file.
44
+
45
+ Returns an empty policy (no-op) if the path does not exist so callers can
46
+ pass a conventional default path unconditionally.
47
+ """
48
+ p = Path(path)
49
+ if not p.exists():
50
+ logger.warning("Governance policy not found at %s; no rules applied.", p)
51
+ return {}
52
+ import yaml
53
+
54
+ data = yaml.safe_load(p.read_text()) or {}
55
+ if not isinstance(data, dict):
56
+ raise ValueError(f"Governance policy at {p} must be a mapping, got {type(data).__name__}.")
57
+ return data
58
+
59
+
60
+ def _matches(module_id: str, patterns: Any) -> bool:
61
+ if not isinstance(patterns, (list, tuple)):
62
+ return False
63
+ return any(isinstance(pat, str) and fnmatch(module_id, pat) for pat in patterns)
64
+
65
+
66
+ def apply_policy(modules: list[Any], policy: dict[str, Any]) -> list[Any]:
67
+ """Return ``modules`` with annotations updated per ``policy``.
68
+
69
+ Sets ``requires_approval=True`` on modules whose ``module_id`` matches any
70
+ ``require_approval`` pattern, and ``destructive=True`` for ``mark_destructive``.
71
+ Modules that match nothing are returned unchanged. Emits an INFO line per
72
+ change so the governance decision is auditable at startup.
73
+ """
74
+ if not policy:
75
+ return modules
76
+
77
+ require_approval = policy.get("require_approval")
78
+ mark_destructive = policy.get("mark_destructive")
79
+ unknown = [k for k in policy if k not in _PATTERN_KEYS]
80
+ if unknown:
81
+ logger.warning("Governance policy: ignoring unknown keys %s", unknown)
82
+
83
+ result: list[Any] = []
84
+ for mod in modules:
85
+ needs_approval = _matches(mod.module_id, require_approval)
86
+ make_destructive = _matches(mod.module_id, mark_destructive)
87
+ if not (needs_approval or make_destructive):
88
+ result.append(mod)
89
+ continue
90
+
91
+ base = mod.annotations if isinstance(mod.annotations, ModuleAnnotations) else ModuleAnnotations()
92
+ changes: dict[str, bool] = {}
93
+ if needs_approval and not base.requires_approval:
94
+ changes["requires_approval"] = True
95
+ if make_destructive and not base.destructive:
96
+ changes["destructive"] = True
97
+ if not changes:
98
+ result.append(mod)
99
+ continue
100
+
101
+ new_ann = dataclasses.replace(base, **changes)
102
+ result.append(dataclasses.replace(mod, annotations=new_ann))
103
+ logger.info("Governance: %s -> %s", mod.module_id, ", ".join(f"{k}=True" for k in changes))
104
+
105
+ return result
@@ -13,7 +13,6 @@ from typing import TYPE_CHECKING, Any
13
13
  from apcore_toolkit.output.registry_writer import RegistryWriter
14
14
 
15
15
  if TYPE_CHECKING:
16
- from apcore import FunctionModule
17
16
  from apcore_toolkit.types import ScannedModule
18
17
 
19
18
  logger = logging.getLogger("fastapi_apcore")
@@ -36,6 +35,7 @@ class FastAPIRegistryWriter(RegistryWriter):
36
35
  dry_run: bool = False,
37
36
  verify: bool = False,
38
37
  verifiers: Any = None,
38
+ allowed_prefixes: list[str] | None = None,
39
39
  ) -> list[Any]:
40
40
  from apcore_toolkit.output.types import WriteResult
41
41
  from apcore_toolkit.output.verifiers import RegistryVerifier, run_verifier_chain
@@ -46,7 +46,7 @@ class FastAPIRegistryWriter(RegistryWriter):
46
46
  results.append(WriteResult(module_id=mod.module_id))
47
47
  continue
48
48
 
49
- fm = self._to_function_module(mod)
49
+ fm = self._to_function_module(mod, allowed_prefixes=allowed_prefixes)
50
50
  with contextlib.suppress(KeyError, ValueError):
51
51
  registry.unregister(mod.module_id)
52
52
  registry.register(mod.module_id, fm)
@@ -73,32 +73,21 @@ class FastAPIRegistryWriter(RegistryWriter):
73
73
  results.append(result)
74
74
  return results
75
75
 
76
- def _to_function_module(self, mod: ScannedModule) -> FunctionModule:
77
- from apcore import FunctionModule as FuncModule
78
- from apcore_toolkit.pydantic_utils import resolve_target
79
-
80
- func = resolve_target(mod.target)
81
-
82
- # Apply Pydantic flattening
83
- try:
84
- from apcore_toolkit import flatten_pydantic_params
85
-
86
- func = flatten_pydantic_params(func)
87
- except ImportError:
88
- pass
89
-
90
- input_model = _schema_to_pydantic(f"{mod.module_id}_Input", mod.input_schema)
91
- output_model = _schema_to_pydantic(f"{mod.module_id}_Output", mod.output_schema)
92
-
93
- return FuncModule(
94
- func=func,
95
- module_id=mod.module_id,
96
- description=mod.description,
97
- tags=mod.tags,
98
- version=mod.version,
99
- input_schema=input_model,
100
- output_schema=output_model,
101
- )
76
+ # NOTE: this writer no longer overrides ``_to_function_module``. Doing so
77
+ # previously dropped ``annotations``, silently disabling approval/ACL gating
78
+ # (that keys on ``requires_approval``) for scanned routes. Field mapping —
79
+ # including annotations — is now centralized in the toolkit base writer's
80
+ # ``_build_function_module``; here we override only the narrow schema hooks.
81
+
82
+ def _build_input_schema(self, mod: ScannedModule) -> Any:
83
+ """Build an explicit input model from the scanned OpenAPI/Pydantic schema
84
+ so ``FunctionModule`` skips function introspection."""
85
+ return _schema_to_pydantic(f"{mod.module_id}_Input", mod.input_schema)
86
+
87
+ def _build_output_schema(self, mod: ScannedModule) -> Any:
88
+ """Build an explicit output model from the scanned schema. See
89
+ :meth:`_build_input_schema`."""
90
+ return _schema_to_pydantic(f"{mod.module_id}_Output", mod.output_schema)
102
91
 
103
92
 
104
93
  _JSON_TYPE_MAP: dict[str, type] = {
@@ -0,0 +1,202 @@
1
+ """Base scanner interface and ScannedModule dataclass for FastAPI.
2
+
3
+ All scanners (NativeFastAPIScanner, OpenAPIScanner) extend BaseScanner
4
+ and produce lists of ScannedModule instances.
5
+
6
+ ScannedModule keeps FastAPI-specific fields (http_method, url_path) as
7
+ top-level attributes. The toolkit's domain-agnostic ScannedModule stores
8
+ these in metadata instead.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from abc import ABC, abstractmethod
15
+ from collections.abc import Iterable
16
+ from dataclasses import dataclass
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ from apcore import ModuleAnnotations
20
+ from apcore_toolkit import BaseScanner as _ToolkitBaseScanner
21
+ from apcore_toolkit.types import ScannedModule as _CanonicalScannedModule
22
+
23
+ if TYPE_CHECKING:
24
+ from fastapi import FastAPI
25
+
26
+
27
+ # Module-ID normalisation mirrors apcore-toolkit's OpenAPI scanner
28
+ # (``apcore-toolkit >= 0.13.0``): split camelCase/acronyms into words, replace
29
+ # characters outside the Canonical ID alphabet, lowercase, and strip leading
30
+ # underscores per dot-separated segment. An ID apcore already accepts
31
+ # (PROTOCOL_SPEC §2.7) is returned unchanged.
32
+ _ACRONYM_BOUNDARY_RE = re.compile(r"([A-Z])([A-Z][a-z])")
33
+ _WORD_BOUNDARY_RE = re.compile(r"([a-z0-9])([A-Z])")
34
+ _OUTSIDE_ID_ALPHABET_RE = re.compile(r"[^A-Za-z0-9_.]")
35
+ _LEGAL_SEGMENT_RE = re.compile(r"[a-z][a-z0-9_]*")
36
+
37
+
38
+ @dataclass
39
+ class ScannedModule(_CanonicalScannedModule):
40
+ """Result of scanning a single FastAPI endpoint.
41
+
42
+ Extends the canonical :class:`apcore_toolkit.types.ScannedModule` — every
43
+ shared field (``annotations``, ``examples``, ``display``,
44
+ ``suggested_alias``, ``metadata``, ``warnings``, ...) is **inherited**, so
45
+ this type can never drift from the canonical shape the way the previous
46
+ standalone fork did. That drift dropped ``examples`` and crashed toolkit
47
+ code reading ``mod.examples``; see apcore-toolkit-python#7 (item 3).
48
+
49
+ ``http_method`` / ``url_path`` are FastAPI-specific extensions kept as
50
+ top-level attributes for scanner ergonomics; the canonical type stores such
51
+ route data in ``metadata``. They default to ``""`` (required-in-practice —
52
+ every scanner sets them) because a dataclass subclass cannot add fields
53
+ without defaults after the parent's defaulted fields.
54
+ """
55
+
56
+ http_method: str = ""
57
+ url_path: str = ""
58
+
59
+
60
+ class BaseScanner(ABC):
61
+ """Abstract base class for all FastAPI scanners.
62
+
63
+ Subclasses must implement scan() and get_source_name().
64
+ """
65
+
66
+ @abstractmethod
67
+ def scan(
68
+ self,
69
+ app: FastAPI,
70
+ include: str | None = None,
71
+ exclude: str | None = None,
72
+ ) -> list[ScannedModule]:
73
+ """Scan FastAPI app endpoints and return module definitions."""
74
+ ...
75
+
76
+ @abstractmethod
77
+ def get_source_name(self) -> str:
78
+ """Return human-readable scanner name."""
79
+ ...
80
+
81
+ def filter_modules(
82
+ self,
83
+ modules: list[ScannedModule],
84
+ include: str | None = None,
85
+ exclude: str | None = None,
86
+ ) -> list[ScannedModule]:
87
+ """Apply include/exclude regex filters to scanned modules."""
88
+ result = modules
89
+ if include is not None:
90
+ pattern = re.compile(include)
91
+ result = [m for m in result if pattern.search(m.module_id)]
92
+ if exclude is not None:
93
+ pattern = re.compile(exclude)
94
+ result = [m for m in result if not pattern.search(m.module_id)]
95
+ return result
96
+
97
+ @staticmethod
98
+ def infer_annotations_from_method(method: str) -> ModuleAnnotations:
99
+ """Infer behavioral annotations from an HTTP method."""
100
+ return _ToolkitBaseScanner.infer_annotations_from_method(method)
101
+
102
+ def collect_api_routes(
103
+ self,
104
+ routes: Iterable[Any],
105
+ prefix: str = "",
106
+ extra_tags: tuple[str, ...] = (),
107
+ ) -> list[tuple[Any, str, tuple[str, ...]]]:
108
+ """Recursively collect APIRoute instances with their effective prefix and tags.
109
+
110
+ FastAPI >=0.128 stopped flattening included routers into ``app.routes``;
111
+ it inserts a lazy ``_IncludedRouter`` node that references the original
112
+ ``APIRouter`` instead of copying its routes. Older versions expose
113
+ ``APIRoute`` objects directly. This walk handles both shapes so routes
114
+ are discovered regardless of the installed FastAPI version.
115
+
116
+ Args:
117
+ routes: Route objects to walk (typically ``app.routes``).
118
+ prefix: URL prefix accumulated from enclosing routers/mounts.
119
+ extra_tags: Tags accumulated from enclosing ``include_router`` calls.
120
+
121
+ Returns:
122
+ List of ``(route, prefix, extra_tags)`` tuples, one per APIRoute.
123
+ """
124
+ from fastapi.routing import APIRoute
125
+
126
+ collected: list[tuple[Any, str, tuple[str, ...]]] = []
127
+ for route in routes:
128
+ if isinstance(route, APIRoute):
129
+ collected.append((route, prefix, extra_tags))
130
+ continue
131
+
132
+ # FastAPI >=0.128 lazy include node: descend into the referenced router.
133
+ original_router = getattr(route, "original_router", None)
134
+ if original_router is not None:
135
+ context = getattr(route, "include_context", None)
136
+ include_prefix = getattr(context, "prefix", "") or ""
137
+ include_tags = tuple(str(t) for t in (getattr(context, "tags", None) or ()))
138
+ collected.extend(
139
+ self.collect_api_routes(
140
+ original_router.routes,
141
+ prefix + include_prefix,
142
+ extra_tags + include_tags,
143
+ )
144
+ )
145
+ continue
146
+
147
+ # Starlette Mount / sub-router exposing nested routes directly.
148
+ sub_routes = getattr(route, "routes", None)
149
+ if sub_routes:
150
+ mount_prefix = getattr(route, "path", "") or ""
151
+ collected.extend(self.collect_api_routes(sub_routes, prefix + mount_prefix, extra_tags))
152
+ return collected
153
+
154
+ def deduplicate_ids(self, modules: list[ScannedModule]) -> list[ScannedModule]:
155
+ """Resolve duplicate module IDs by appending _2, _3, etc.
156
+
157
+ Delegates to the canonical toolkit implementation, which pre-scans
158
+ existing IDs so a generated suffix never collides with an ID that is
159
+ already present, and records the rename in ``warnings``.
160
+ """
161
+ result: list[ScannedModule] = _ToolkitBaseScanner.deduplicate_ids(self, modules)
162
+ return result
163
+
164
+ @staticmethod
165
+ def canonicalize_module_id(candidate: str) -> str:
166
+ """Normalise a generated module ID into apcore's Canonical ID alphabet.
167
+
168
+ Framework scanners compose IDs from tags, function names and path
169
+ segments, which may carry camelCase (``getUser``) or punctuation
170
+ (``user-profiles``). apcore's registry only accepts
171
+ ``^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)*$`` (PROTOCOL_SPEC §2.7), so
172
+ such IDs were previously rejected at registration time.
173
+
174
+ The algorithm is byte-identical to apcore-toolkit's OpenAPI scanner:
175
+ split acronym and word boundaries, replace characters outside
176
+ ``[A-Za-z0-9_.]`` with ``_``, lowercase, then strip leading
177
+ underscores from each dot-separated segment and drop empty segments.
178
+ An already-legal ID is returned unchanged (runs of ``_`` are kept,
179
+ so FastAPI's ``read_item_items__item_id__get`` registers as before).
180
+ """
181
+ candidate = _ACRONYM_BOUNDARY_RE.sub(r"\1_\2", candidate)
182
+ candidate = _WORD_BOUNDARY_RE.sub(r"\1_\2", candidate)
183
+ candidate = _OUTSIDE_ID_ALPHABET_RE.sub("_", candidate)
184
+ candidate = candidate.lower()
185
+ segments = (seg.lstrip("_") for seg in candidate.split("."))
186
+ return ".".join(seg for seg in segments if seg)
187
+
188
+ @staticmethod
189
+ def module_id_warning(module_id: str) -> str | None:
190
+ """Return a warning if *module_id* is not a legal apcore ID.
191
+
192
+ A segment that still begins with a digit (``/v1/2fa``) is not
193
+ repaired, because that would invent a name; the module is emitted
194
+ with this warning so the caller can rename it via a binding.
195
+ """
196
+ for segment in module_id.split("."):
197
+ if _LEGAL_SEGMENT_RE.fullmatch(segment) is None:
198
+ return (
199
+ f"module_id '{module_id}' is not a legal apcore module ID: segment '{segment}' "
200
+ "must match ^[a-z][a-z0-9_]*$; rename it with a binding display.alias"
201
+ )
202
+ return None