flask-apcore 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,34 @@
1
+ """flask-apcore: Flask Extension for apcore AI-Perceivable Core integration."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from flask_apcore.extension import Apcore
6
+
7
+ from apcore import module
8
+
9
+ from apcore import (
10
+ ACL,
11
+ Config,
12
+ Context,
13
+ Executor,
14
+ Identity,
15
+ Middleware,
16
+ ModuleAnnotations,
17
+ ModuleDescriptor,
18
+ Registry,
19
+ )
20
+
21
+ __all__ = [
22
+ "Apcore",
23
+ "__version__",
24
+ "module",
25
+ "ACL",
26
+ "Config",
27
+ "Context",
28
+ "Executor",
29
+ "Identity",
30
+ "Middleware",
31
+ "ModuleAnnotations",
32
+ "ModuleDescriptor",
33
+ "Registry",
34
+ ]
flask_apcore/cli.py ADDED
@@ -0,0 +1,299 @@
1
+ """Click CLI commands for flask-apcore.
2
+
3
+ Provides the 'flask apcore' command group with 'scan' and 'serve' subcommands.
4
+ Adapted from django-apcore's management/commands/apcore_scan.py and apcore_serve.py.
5
+
6
+ Features:
7
+ - scan: --output is optional; omit for direct registry registration
8
+ - serve: supports --validate-inputs, --log-level, metrics_collector passthrough
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from typing import Any
15
+
16
+ import click
17
+ from flask import current_app
18
+ from flask.cli import AppGroup, with_appcontext
19
+
20
+ from flask_apcore.registry import get_executor
21
+
22
+ apcore_cli = AppGroup("apcore", help="apcore AI-Perceivable Core commands.")
23
+
24
+
25
+ @apcore_cli.command("scan")
26
+ @click.option(
27
+ "--source",
28
+ "-s",
29
+ type=click.Choice(["auto", "native", "smorest", "restx"]),
30
+ default="auto",
31
+ help="Scanner source. 'auto' detects the best scanner.",
32
+ )
33
+ @click.option(
34
+ "--output",
35
+ "-o",
36
+ type=click.Choice(["yaml"]),
37
+ default=None,
38
+ help="Output format. Omit to register directly.",
39
+ )
40
+ @click.option(
41
+ "--dir",
42
+ "-d",
43
+ "output_dir",
44
+ type=click.Path(),
45
+ default=None,
46
+ help="Output directory. Defaults to APCORE_MODULE_DIR config.",
47
+ )
48
+ @click.option(
49
+ "--dry-run",
50
+ is_flag=True,
51
+ default=False,
52
+ help="Preview output without writing files or registering modules.",
53
+ )
54
+ @click.option(
55
+ "--include",
56
+ type=str,
57
+ default=None,
58
+ help="Regex pattern: only include matching module IDs.",
59
+ )
60
+ @click.option(
61
+ "--exclude",
62
+ type=str,
63
+ default=None,
64
+ help="Regex pattern: exclude matching module IDs.",
65
+ )
66
+ @with_appcontext
67
+ def scan_command(source, output, output_dir, dry_run, include, exclude):
68
+ """Scan Flask routes and generate apcore module definitions."""
69
+ app = current_app._get_current_object()
70
+ settings = app.extensions["apcore"]["settings"]
71
+ registry = app.extensions["apcore"]["registry"]
72
+
73
+ # Resolve output directory
74
+ if output_dir is None:
75
+ output_dir = settings.module_dir
76
+
77
+ # Validate regex patterns
78
+ if include:
79
+ try:
80
+ re.compile(include)
81
+ except re.error as e:
82
+ raise click.ClickException(f"Invalid --include pattern: '{include}'. " f"Must be valid regex. Error: {e}")
83
+
84
+ if exclude:
85
+ try:
86
+ re.compile(exclude)
87
+ except re.error as e:
88
+ raise click.ClickException(f"Invalid --exclude pattern: '{exclude}'. " f"Must be valid regex. Error: {e}")
89
+
90
+ # Get scanner
91
+ from flask_apcore.scanners import get_scanner, auto_detect_scanner
92
+
93
+ try:
94
+ if source == "auto":
95
+ scanner = auto_detect_scanner(app)
96
+ else:
97
+ scanner = get_scanner(source)
98
+ except (ImportError, ValueError) as e:
99
+ raise click.ClickException(str(e))
100
+
101
+ source_name = scanner.get_source_name()
102
+ click.echo(f"[flask-apcore] Scanning {source_name} routes...")
103
+
104
+ # Run scan
105
+ try:
106
+ modules = scanner.scan(app, include=include, exclude=exclude)
107
+ except re.error as e:
108
+ raise click.ClickException(f"Invalid regex pattern. Error: {e}")
109
+
110
+ click.echo(f"[flask-apcore] Found {len(modules)} API routes.")
111
+
112
+ if not modules:
113
+ click.echo(f"[flask-apcore] No routes found for source '{source_name}'. " f"Ensure your API is configured.")
114
+ raise SystemExit(1)
115
+
116
+ # Report warnings
117
+ all_warnings = []
118
+ for module in modules:
119
+ all_warnings.extend(module.warnings)
120
+ if all_warnings:
121
+ click.echo(f"[flask-apcore] Warnings: {len(all_warnings)}")
122
+ for warning in all_warnings:
123
+ click.echo(f"[flask-apcore] - {warning}")
124
+
125
+ # Get writer and write output
126
+ from flask_apcore.output import get_writer
127
+
128
+ writer = get_writer(output)
129
+
130
+ if output is None:
131
+ # Direct registration mode
132
+ if dry_run:
133
+ click.echo("[flask-apcore] Dry run -- no modules registered.")
134
+ writer.write(modules, registry, dry_run=True)
135
+ else:
136
+ result = writer.write(modules, registry)
137
+ click.echo(f"[flask-apcore] Registered {len(result)} modules.")
138
+ else:
139
+ # YAML file mode
140
+ if dry_run:
141
+ click.echo("[flask-apcore] Dry run -- no files written.")
142
+ writer.write(modules, output_dir, dry_run=True)
143
+ else:
144
+ writer.write(modules, output_dir)
145
+ click.echo(f"[flask-apcore] Generated {len(modules)} module definitions.")
146
+ click.echo(f"[flask-apcore] Written to {output_dir}/")
147
+
148
+
149
+ @apcore_cli.command("serve")
150
+ @click.option(
151
+ "--stdio",
152
+ "transport",
153
+ flag_value="stdio",
154
+ default=True,
155
+ help="Use stdio transport (default).",
156
+ )
157
+ @click.option(
158
+ "--http",
159
+ "transport",
160
+ flag_value="streamable-http",
161
+ help="Use HTTP Streamable transport.",
162
+ )
163
+ @click.option(
164
+ "--host",
165
+ type=str,
166
+ default=None,
167
+ help="Host for HTTP transport. Default: APCORE_SERVE_HOST config.",
168
+ )
169
+ @click.option(
170
+ "--port",
171
+ "-p",
172
+ type=int,
173
+ default=None,
174
+ help="Port for HTTP transport. Default: APCORE_SERVE_PORT config.",
175
+ )
176
+ @click.option(
177
+ "--name",
178
+ type=str,
179
+ default=None,
180
+ help="MCP server name. Default: APCORE_SERVER_NAME config.",
181
+ )
182
+ @click.option(
183
+ "--validate-inputs",
184
+ is_flag=True,
185
+ default=False,
186
+ help="Validate tool inputs against schemas before execution.",
187
+ )
188
+ @click.option(
189
+ "--log-level",
190
+ type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR"]),
191
+ default=None,
192
+ help="Set the log level for the apcore-mcp logger.",
193
+ )
194
+ @with_appcontext
195
+ def serve_command(
196
+ transport: str,
197
+ host: str | None,
198
+ port: int | None,
199
+ name: str | None,
200
+ validate_inputs: bool,
201
+ log_level: str | None,
202
+ ) -> None:
203
+ """Start an MCP server exposing registered apcore modules as tools."""
204
+ app = current_app._get_current_object()
205
+ settings = app.extensions["apcore"]["settings"]
206
+ registry = app.extensions["apcore"]["registry"]
207
+ metrics_collector = app.extensions["apcore"].get("metrics_collector")
208
+
209
+ # Resolve with config fallbacks
210
+ transport = transport or settings.serve_transport
211
+ host = host or settings.serve_host
212
+ port = port if port is not None else settings.serve_port
213
+ name = name or settings.server_name
214
+
215
+ # Use config fallbacks for validate_inputs and log_level
216
+ if not validate_inputs:
217
+ validate_inputs = settings.serve_validate_inputs
218
+ if log_level is None:
219
+ log_level = settings.serve_log_level
220
+
221
+ # Check module count
222
+ if registry.count == 0:
223
+ raise click.ClickException(
224
+ "No apcore modules registered. "
225
+ "Run 'flask apcore scan' first or define modules "
226
+ "with @module decorator."
227
+ )
228
+
229
+ # Validate port
230
+ if not (1 <= port <= 65535):
231
+ raise click.ClickException(f"--port must be between 1 and 65535. Got: {port}.")
232
+
233
+ # Security warning for 0.0.0.0
234
+ if transport in ("streamable-http", "sse") and host == "0.0.0.0":
235
+ click.echo(
236
+ "[flask-apcore] WARNING: Binding to 0.0.0.0 exposes the MCP "
237
+ "server to all network interfaces. Ensure the server is "
238
+ "behind a firewall.",
239
+ err=True,
240
+ )
241
+
242
+ # Detect if executor is needed
243
+ use_executor = bool(settings.middlewares or settings.acl_path or settings.executor_config)
244
+
245
+ if use_executor:
246
+ registry_or_executor = get_executor(app)
247
+ else:
248
+ registry_or_executor = registry
249
+
250
+ click.echo(f"[flask-apcore] Starting MCP server '{name}' via {transport}...")
251
+ click.echo(f"[flask-apcore] {registry.count} modules registered.")
252
+
253
+ _do_serve(
254
+ registry_or_executor,
255
+ transport=transport,
256
+ host=host,
257
+ port=port,
258
+ name=name,
259
+ validate_inputs=validate_inputs,
260
+ log_level=log_level,
261
+ metrics_collector=metrics_collector,
262
+ )
263
+
264
+
265
+ def _do_serve(
266
+ registry_or_executor: Any,
267
+ *,
268
+ transport: str,
269
+ host: str,
270
+ port: int,
271
+ name: str,
272
+ validate_inputs: bool = False,
273
+ log_level: str | None = None,
274
+ metrics_collector: Any | None = None,
275
+ ) -> None:
276
+ """Delegate to apcore_mcp.serve().
277
+
278
+ Separated for testability (can be mocked in tests).
279
+
280
+ Adapted from django-apcore's management/commands/apcore_serve.py serve()
281
+ function.
282
+ """
283
+ try:
284
+ from apcore_mcp import serve
285
+ except ImportError:
286
+ raise click.ClickException(
287
+ "apcore-mcp is required for 'flask apcore serve'. " "Install with: pip install flask-apcore[mcp]"
288
+ )
289
+
290
+ serve(
291
+ registry_or_executor,
292
+ transport=transport,
293
+ host=host,
294
+ port=port,
295
+ name=name,
296
+ validate_inputs=validate_inputs,
297
+ log_level=log_level,
298
+ metrics_collector=metrics_collector,
299
+ )
flask_apcore/config.py ADDED
@@ -0,0 +1,345 @@
1
+ """APCORE_* settings resolution and validation.
2
+
3
+ Reads all APCORE_* settings from Flask's app.config, applies defaults,
4
+ validates types and values, and exposes a frozen dataclass for internal use.
5
+
6
+ Adapted from django-apcore's settings.py, replacing django.conf.settings
7
+ with app.config and ImproperlyConfigured with ValueError.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import TYPE_CHECKING, Any
15
+
16
+ if TYPE_CHECKING:
17
+ from flask import Flask
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # Defaults
21
+ # ---------------------------------------------------------------------------
22
+ DEFAULT_MODULE_DIR = "apcore_modules/"
23
+ DEFAULT_AUTO_DISCOVER = True
24
+ DEFAULT_SERVE_TRANSPORT = "stdio"
25
+ DEFAULT_SERVE_HOST = "127.0.0.1"
26
+ DEFAULT_SERVE_PORT = 9100
27
+ DEFAULT_SERVER_NAME = "apcore-mcp"
28
+ DEFAULT_BINDING_PATTERN = "*.binding.yaml"
29
+ DEFAULT_SCANNER_SOURCE = "auto"
30
+
31
+ # New MCP Serve defaults
32
+ DEFAULT_SERVE_VALIDATE_INPUTS = False
33
+
34
+ # New Observability defaults
35
+ DEFAULT_TRACING_ENABLED = False
36
+ DEFAULT_TRACING_EXPORTER = "stdout"
37
+ DEFAULT_TRACING_SERVICE_NAME = "flask-apcore"
38
+ DEFAULT_METRICS_ENABLED = False
39
+ DEFAULT_LOGGING_ENABLED = False
40
+ DEFAULT_LOGGING_FORMAT = "json"
41
+ DEFAULT_LOGGING_LEVEL = "INFO"
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # Valid choices
45
+ # ---------------------------------------------------------------------------
46
+ VALID_TRANSPORTS = ("stdio", "streamable-http", "sse")
47
+ VALID_SCANNER_SOURCES = ("auto", "native", "smorest", "restx")
48
+ VALID_SERVE_LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")
49
+ VALID_TRACING_EXPORTERS = ("stdout", "memory", "otlp")
50
+ VALID_LOGGING_FORMATS = ("json", "text")
51
+ VALID_LOGGING_LEVELS = ("trace", "debug", "info", "warn", "error", "fatal")
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class ApcoreSettings:
56
+ """Validated APCORE_* settings.
57
+
58
+ All fields are immutable after validation. Created by load_settings().
59
+ """
60
+
61
+ # Existing
62
+ module_dir: str
63
+ auto_discover: bool
64
+ serve_transport: str
65
+ serve_host: str
66
+ serve_port: int
67
+ server_name: str
68
+ binding_pattern: str
69
+ scanner_source: str
70
+ module_packages: list[str]
71
+ middlewares: list[str]
72
+ acl_path: str | None
73
+ context_factory: str | None
74
+ server_version: str | None
75
+ executor_config: dict[str, Any] | None
76
+
77
+ # New MCP Serve
78
+ serve_validate_inputs: bool
79
+ serve_log_level: str | None
80
+
81
+ # New Observability
82
+ tracing_enabled: bool
83
+ tracing_exporter: str
84
+ tracing_otlp_endpoint: str | None
85
+ tracing_service_name: str
86
+ metrics_enabled: bool
87
+ metrics_buckets: list[float] | None
88
+ logging_enabled: bool
89
+ logging_format: str
90
+ logging_level: str
91
+
92
+ # New Extensions
93
+ extensions: list[str]
94
+
95
+
96
+ def load_settings(app: Flask) -> ApcoreSettings:
97
+ """Read and validate APCORE_* settings from app.config.
98
+
99
+ Each Flask config key is ``APCORE_`` + uppercase field name
100
+ (e.g. ``APCORE_MODULE_DIR``). ``None`` values fall back to defaults.
101
+
102
+ Args:
103
+ app: Flask application instance.
104
+
105
+ Returns:
106
+ Validated, frozen ApcoreSettings dataclass.
107
+
108
+ Raises:
109
+ ValueError: If any setting is invalid.
110
+ """
111
+ # === Existing fields ===
112
+
113
+ # --- module_dir ---
114
+ module_dir = app.config.get("APCORE_MODULE_DIR", DEFAULT_MODULE_DIR)
115
+ if module_dir is None:
116
+ module_dir = DEFAULT_MODULE_DIR
117
+ if not isinstance(module_dir, (str, Path)):
118
+ actual = type(module_dir).__name__
119
+ raise ValueError(f"APCORE_MODULE_DIR must be a string path. Got: {actual}")
120
+ module_dir = str(module_dir)
121
+
122
+ # --- auto_discover ---
123
+ auto_discover = app.config.get("APCORE_AUTO_DISCOVER", DEFAULT_AUTO_DISCOVER)
124
+ if auto_discover is None:
125
+ auto_discover = DEFAULT_AUTO_DISCOVER
126
+ if not isinstance(auto_discover, bool):
127
+ actual = type(auto_discover).__name__
128
+ raise ValueError(f"APCORE_AUTO_DISCOVER must be a boolean. Got: {actual}")
129
+
130
+ # --- serve_transport ---
131
+ serve_transport = app.config.get("APCORE_SERVE_TRANSPORT", DEFAULT_SERVE_TRANSPORT)
132
+ if serve_transport is None:
133
+ serve_transport = DEFAULT_SERVE_TRANSPORT
134
+ if serve_transport not in VALID_TRANSPORTS:
135
+ choices = ", ".join(VALID_TRANSPORTS)
136
+ raise ValueError(f"APCORE_SERVE_TRANSPORT must be one of: {choices}." f" Got: '{serve_transport}'")
137
+
138
+ # --- serve_host ---
139
+ serve_host = app.config.get("APCORE_SERVE_HOST", DEFAULT_SERVE_HOST)
140
+ if serve_host is None:
141
+ serve_host = DEFAULT_SERVE_HOST
142
+ if not isinstance(serve_host, str):
143
+ actual = type(serve_host).__name__
144
+ raise ValueError(f"APCORE_SERVE_HOST must be a string. Got: {actual}")
145
+
146
+ # --- serve_port ---
147
+ serve_port = app.config.get("APCORE_SERVE_PORT", DEFAULT_SERVE_PORT)
148
+ if serve_port is None:
149
+ serve_port = DEFAULT_SERVE_PORT
150
+ if not isinstance(serve_port, int) or isinstance(serve_port, bool):
151
+ actual = type(serve_port).__name__
152
+ raise ValueError(f"APCORE_SERVE_PORT must be an integer between 1 and 65535." f" Got: {actual}")
153
+ if not (1 <= serve_port <= 65535):
154
+ raise ValueError(f"APCORE_SERVE_PORT must be an integer between 1 and 65535." f" Got: {serve_port}")
155
+
156
+ # --- server_name ---
157
+ server_name = app.config.get("APCORE_SERVER_NAME", DEFAULT_SERVER_NAME)
158
+ if server_name is None:
159
+ server_name = DEFAULT_SERVER_NAME
160
+ if not isinstance(server_name, str) or len(server_name) == 0 or len(server_name) > 100:
161
+ raise ValueError("APCORE_SERVER_NAME must be a non-empty string up to 100 characters.")
162
+
163
+ # --- binding_pattern ---
164
+ binding_pattern = app.config.get("APCORE_BINDING_PATTERN", DEFAULT_BINDING_PATTERN)
165
+ if binding_pattern is None:
166
+ binding_pattern = DEFAULT_BINDING_PATTERN
167
+ if not isinstance(binding_pattern, str):
168
+ raise ValueError("APCORE_BINDING_PATTERN must be a valid glob pattern string.")
169
+
170
+ # --- scanner_source ---
171
+ scanner_source = app.config.get("APCORE_SCANNER_SOURCE", DEFAULT_SCANNER_SOURCE)
172
+ if scanner_source is None:
173
+ scanner_source = DEFAULT_SCANNER_SOURCE
174
+ if scanner_source not in VALID_SCANNER_SOURCES:
175
+ choices = ", ".join(VALID_SCANNER_SOURCES)
176
+ raise ValueError(f"APCORE_SCANNER_SOURCE must be one of: {choices}." f" Got: '{scanner_source}'")
177
+
178
+ # --- module_packages ---
179
+ module_packages = app.config.get("APCORE_MODULE_PACKAGES", [])
180
+ if module_packages is None:
181
+ module_packages = []
182
+ if not isinstance(module_packages, list) or not all(isinstance(p, str) for p in module_packages):
183
+ raise ValueError("APCORE_MODULE_PACKAGES must be a list of dotted path strings.")
184
+
185
+ # --- middlewares ---
186
+ middlewares = app.config.get("APCORE_MIDDLEWARES", [])
187
+ if middlewares is None:
188
+ middlewares = []
189
+ if not isinstance(middlewares, list) or not all(isinstance(m, str) for m in middlewares):
190
+ raise ValueError("APCORE_MIDDLEWARES must be a list of dotted path strings.")
191
+
192
+ # --- acl_path ---
193
+ acl_path = app.config.get("APCORE_ACL_PATH", None)
194
+ if acl_path is not None and not isinstance(acl_path, str):
195
+ actual = type(acl_path).__name__
196
+ raise ValueError(f"APCORE_ACL_PATH must be a string path. Got: {actual}")
197
+
198
+ # --- context_factory ---
199
+ context_factory = app.config.get("APCORE_CONTEXT_FACTORY", None)
200
+ if context_factory is not None and not isinstance(context_factory, str):
201
+ actual = type(context_factory).__name__
202
+ raise ValueError(f"APCORE_CONTEXT_FACTORY must be a dotted path string. Got: {actual}")
203
+
204
+ # --- server_version ---
205
+ server_version = app.config.get("APCORE_SERVER_VERSION", None)
206
+ if server_version is not None and (not isinstance(server_version, str) or len(server_version) == 0):
207
+ raise ValueError("APCORE_SERVER_VERSION must be a non-empty string if set.")
208
+
209
+ # --- executor_config ---
210
+ executor_config = app.config.get("APCORE_EXECUTOR_CONFIG", None)
211
+ if executor_config is not None and not isinstance(executor_config, dict):
212
+ actual = type(executor_config).__name__
213
+ raise ValueError(f"APCORE_EXECUTOR_CONFIG must be a dict. Got: {actual}")
214
+
215
+ # === New MCP Serve fields ===
216
+
217
+ # --- serve_validate_inputs ---
218
+ serve_validate_inputs = app.config.get("APCORE_SERVE_VALIDATE_INPUTS", DEFAULT_SERVE_VALIDATE_INPUTS)
219
+ if serve_validate_inputs is None:
220
+ serve_validate_inputs = DEFAULT_SERVE_VALIDATE_INPUTS
221
+ if not isinstance(serve_validate_inputs, bool):
222
+ actual = type(serve_validate_inputs).__name__
223
+ raise ValueError(f"APCORE_SERVE_VALIDATE_INPUTS must be a boolean. Got: {actual}")
224
+
225
+ # --- serve_log_level ---
226
+ serve_log_level = app.config.get("APCORE_SERVE_LOG_LEVEL", None)
227
+ if serve_log_level is not None:
228
+ if not isinstance(serve_log_level, str):
229
+ actual = type(serve_log_level).__name__
230
+ raise ValueError(f"APCORE_SERVE_LOG_LEVEL must be a string. Got: {actual}")
231
+ if serve_log_level not in VALID_SERVE_LOG_LEVELS:
232
+ choices = ", ".join(VALID_SERVE_LOG_LEVELS)
233
+ raise ValueError(f"APCORE_SERVE_LOG_LEVEL must be one of: {choices}." f" Got: '{serve_log_level}'")
234
+
235
+ # === New Observability fields ===
236
+
237
+ # --- tracing_enabled ---
238
+ tracing_enabled = app.config.get("APCORE_TRACING_ENABLED", DEFAULT_TRACING_ENABLED)
239
+ if tracing_enabled is None:
240
+ tracing_enabled = DEFAULT_TRACING_ENABLED
241
+ if not isinstance(tracing_enabled, bool):
242
+ actual = type(tracing_enabled).__name__
243
+ raise ValueError(f"APCORE_TRACING_ENABLED must be a boolean. Got: {actual}")
244
+
245
+ # --- tracing_exporter ---
246
+ tracing_exporter = app.config.get("APCORE_TRACING_EXPORTER", DEFAULT_TRACING_EXPORTER)
247
+ if tracing_exporter is None:
248
+ tracing_exporter = DEFAULT_TRACING_EXPORTER
249
+ if tracing_exporter not in VALID_TRACING_EXPORTERS:
250
+ choices = ", ".join(VALID_TRACING_EXPORTERS)
251
+ raise ValueError(f"APCORE_TRACING_EXPORTER must be one of: {choices}." f" Got: '{tracing_exporter}'")
252
+
253
+ # --- tracing_otlp_endpoint ---
254
+ tracing_otlp_endpoint = app.config.get("APCORE_TRACING_OTLP_ENDPOINT", None)
255
+ if tracing_otlp_endpoint is not None and not isinstance(tracing_otlp_endpoint, str):
256
+ actual = type(tracing_otlp_endpoint).__name__
257
+ raise ValueError(f"APCORE_TRACING_OTLP_ENDPOINT must be a string. Got: {actual}")
258
+
259
+ # --- tracing_service_name ---
260
+ tracing_service_name = app.config.get("APCORE_TRACING_SERVICE_NAME", DEFAULT_TRACING_SERVICE_NAME)
261
+ if tracing_service_name is None:
262
+ tracing_service_name = DEFAULT_TRACING_SERVICE_NAME
263
+ if not isinstance(tracing_service_name, str) or len(tracing_service_name) == 0:
264
+ raise ValueError("APCORE_TRACING_SERVICE_NAME must be a non-empty string.")
265
+
266
+ # --- metrics_enabled ---
267
+ metrics_enabled = app.config.get("APCORE_METRICS_ENABLED", DEFAULT_METRICS_ENABLED)
268
+ if metrics_enabled is None:
269
+ metrics_enabled = DEFAULT_METRICS_ENABLED
270
+ if not isinstance(metrics_enabled, bool):
271
+ actual = type(metrics_enabled).__name__
272
+ raise ValueError(f"APCORE_METRICS_ENABLED must be a boolean. Got: {actual}")
273
+
274
+ # --- metrics_buckets ---
275
+ metrics_buckets = app.config.get("APCORE_METRICS_BUCKETS", None)
276
+ if metrics_buckets is not None:
277
+ if not isinstance(metrics_buckets, list) or not all(
278
+ isinstance(b, (int, float)) and not isinstance(b, bool) for b in metrics_buckets
279
+ ):
280
+ raise ValueError("APCORE_METRICS_BUCKETS must be a list of numeric values.")
281
+
282
+ # --- logging_enabled ---
283
+ logging_enabled = app.config.get("APCORE_LOGGING_ENABLED", DEFAULT_LOGGING_ENABLED)
284
+ if logging_enabled is None:
285
+ logging_enabled = DEFAULT_LOGGING_ENABLED
286
+ if not isinstance(logging_enabled, bool):
287
+ actual = type(logging_enabled).__name__
288
+ raise ValueError(f"APCORE_LOGGING_ENABLED must be a boolean. Got: {actual}")
289
+
290
+ # --- logging_format ---
291
+ logging_format = app.config.get("APCORE_LOGGING_FORMAT", DEFAULT_LOGGING_FORMAT)
292
+ if logging_format is None:
293
+ logging_format = DEFAULT_LOGGING_FORMAT
294
+ if logging_format not in VALID_LOGGING_FORMATS:
295
+ choices = ", ".join(VALID_LOGGING_FORMATS)
296
+ raise ValueError(f"APCORE_LOGGING_FORMAT must be one of: {choices}." f" Got: '{logging_format}'")
297
+
298
+ # --- logging_level ---
299
+ logging_level = app.config.get("APCORE_LOGGING_LEVEL", DEFAULT_LOGGING_LEVEL)
300
+ if logging_level is None:
301
+ logging_level = DEFAULT_LOGGING_LEVEL
302
+ if not isinstance(logging_level, str):
303
+ actual = type(logging_level).__name__
304
+ raise ValueError(f"APCORE_LOGGING_LEVEL must be a string. Got: {actual}")
305
+ if logging_level.lower() not in VALID_LOGGING_LEVELS:
306
+ choices = ", ".join(VALID_LOGGING_LEVELS)
307
+ raise ValueError(f"APCORE_LOGGING_LEVEL must be one of: {choices}." f" Got: '{logging_level}'")
308
+
309
+ # === New Extensions ===
310
+
311
+ # --- extensions ---
312
+ extensions = app.config.get("APCORE_EXTENSIONS", [])
313
+ if extensions is None:
314
+ extensions = []
315
+ if not isinstance(extensions, list) or not all(isinstance(e, str) for e in extensions):
316
+ raise ValueError("APCORE_EXTENSIONS must be a list of dotted path strings.")
317
+
318
+ return ApcoreSettings(
319
+ module_dir=module_dir,
320
+ auto_discover=auto_discover,
321
+ serve_transport=serve_transport,
322
+ serve_host=serve_host,
323
+ serve_port=serve_port,
324
+ server_name=server_name,
325
+ binding_pattern=binding_pattern,
326
+ scanner_source=scanner_source,
327
+ module_packages=module_packages,
328
+ middlewares=middlewares,
329
+ acl_path=acl_path,
330
+ context_factory=context_factory,
331
+ server_version=server_version,
332
+ executor_config=executor_config,
333
+ serve_validate_inputs=serve_validate_inputs,
334
+ serve_log_level=serve_log_level,
335
+ tracing_enabled=tracing_enabled,
336
+ tracing_exporter=tracing_exporter,
337
+ tracing_otlp_endpoint=tracing_otlp_endpoint,
338
+ tracing_service_name=tracing_service_name,
339
+ metrics_enabled=metrics_enabled,
340
+ metrics_buckets=metrics_buckets,
341
+ logging_enabled=logging_enabled,
342
+ logging_format=logging_format,
343
+ logging_level=logging_level,
344
+ extensions=extensions,
345
+ )