Output Writers¶
apcore-toolkit provides several ways to export the ScannedModule metadata into formats used by the apcore ecosystem.
YAMLWriter¶
Generates individual .binding.yaml files for each scanned module. These files are typically placed in an extensions/ or bindings/ directory and loaded by apcore.BindingLoader.
Features¶
- File-per-Module: Each module is written to its own file for easy management.
- Sanitized Filenames: Replaces periods and special characters in module IDs to ensure valid file names.
- Header Injection: Optionally adds a "Generated by" header to all files.
- Conditional
displayEmission: Top-leveldisplaykey is emitted only whenScannedModule.displayis non-None, preserving user overlays on round-trip without cluttering output. spec_versionStamp: Emitsspec_version: "1.0"at the top of every binding document for forward-compatibility. Consumers can detect schema evolution without parsing the full document.
from apcore_toolkit import YAMLWriter
writer = YAMLWriter()
writer.write(modules, output_dir="./bindings", dry_run=False)
import { YAMLWriter } from "apcore-toolkit";
const writer = new YAMLWriter();
writer.write(modules, "./bindings", { dryRun: false });
use apcore_toolkit::YAMLWriter;
YAMLWriter.write(&modules, "./bindings", /* dry_run */ false, /* verify */ false, None)?;
Use BindingLoader for the inverse operation: reading .binding.yaml back into ScannedModule.
PythonWriter / TypeScriptWriter / RustWriter¶
Generates source files containing wrapper functions or handler stubs. PythonWriter/TypeScriptWriter are useful for migrating legacy code to the apcore decorator pattern without manual re-writing, wrapping an existing target function. RustWriter instead generates a fresh handler-stub file per module — see below.
Features (PythonWriter / TypeScriptWriter)¶
- Auto-Decorators: Generates the decorator with all extracted metadata.
- Target Integration: Points to the original view function as the
targetof the module. - Standard Formatting: Produces clean, idiomatic code for the target language.
from apcore_toolkit import PythonWriter
writer = PythonWriter()
writer.write(modules, output_dir="./generated_apcore", dry_run=False)
import { TypeScriptWriter } from "apcore-toolkit";
const writer = new TypeScriptWriter();
writer.write(modules, "./generated_apcore", { dryRun: false });
RustWriter¶
Unlike PythonWriter/TypeScriptWriter, RustWriter does not wrap an existing target function — Rust has no dynamic-import equivalent to point a generated wrapper at. Instead, for each ScannedModule it writes a fresh .rs file (module-id dot-separated path converted to a directory hierarchy, e.g. users.get_user → users/get_user.rs) containing an #[module(id = "...", description = "...")]-annotated handler whose body is todo!("Implement handler for {module_id}") — a starting-point stub the caller fills in, not a ready-to-run implementation.
use apcore_toolkit::RustWriter;
let writer = RustWriter::new("./generated_apcore");
writer.write(&modules)?;
Contract: PythonWriter.write¶
Inputs¶
modules: list ofScannedModule, requiredoutput_dir: string or Path, required — directory where generated.pyfiles will be writtendry_run: bool, optional, default=false — if true, no files are writtenverify: bool, optional, default=false — if true, runsSyntaxVerifier(AST parse check) after each writeverifiers: list of verifier objects, optional — additional custom verifiers
Errors¶
WriteError(path, cause)— file system write failure- All SDKs wrap verifier exceptions into
WriteResult.verification_errorrather than re-raising
Returns¶
- On success: list of
WriteResult— one per module;pathpoints to the generated.pyfile
Properties¶
- async: false
- pure: false (writes to filesystem unless dry_run=true)
- thread_safe: true
- idempotent: true (writing same modules twice produces same files)
- availability: Python only — TypeScript writes TypeScript (
TypeScriptWriter); Rust writes Rust stubs (RustWriter, see below) rather than wrapping an existing target
Contract: TypeScriptWriter.write¶
Inputs¶
modules: list ofScannedModule, requiredoutputDir: string, required — directory where generated.tsfiles will be writtenoptions: object, optional —{ dryRun?: boolean, verify?: boolean, verifiers?: Verifier[], errorMode?: "throw" | "collect" }.errorMode(default"throw") is the sharedFileWriteOptionsflag — see theYAMLWriter.writeContract for full semantics.
Errors¶
WriteError(path, cause)— file system write failure (only whenerrorMode="throw";"collect"captures it in the returnedWriteResult)- All SDKs wrap verifier exceptions into
WriteResult.verificationErrorrather than re-raising
Returns¶
- On success:
WriteResult[]— one per module;pathpoints to the generated.tsfile
Properties¶
- async: false
- pure: false (writes to filesystem unless dryRun=true)
- thread_safe: true
- idempotent: true
- availability: TypeScript only — Python writes Python (
PythonWriter); Rust writes Rust stubs (RustWriter, see below) rather than wrapping an existing target
Contract: RustWriter.write¶
Inputs¶
modules:&[ScannedModule], required
Errors¶
WriteError— file system write failure (directory creation or file write)
Returns¶
- On success:
Result<Vec<WriteResult>, WriteError>— oneWriteResultper module;pathpoints to the generated.rsstub file
Properties¶
- async: false
- pure: false (writes to filesystem)
- thread_safe: true
- idempotent: true (writing the same modules twice overwrites with identical stub content)
- availability: Rust only — the generated stub body is
todo!(...), a starting point for the caller to implement, unlikePythonWriter/TypeScriptWriterwhich wrap an already-existing target function. Provides structural (not behavioral) parity with those two writers.
RegistryWriter¶
Directly registers the scanned modules into an active apcore.Registry instance. This is ideal for "live" scanning where you want to expose existing endpoints without generating intermediate files.
Features¶
- No Disk Usage: Modules are held only in memory.
- Hot-Reload Ready: Can be re-run to refresh the Registry as endpoints change.
from apcore import Registry
from apcore_toolkit import RegistryWriter
registry = Registry()
writer = RegistryWriter()
writer.write(modules, registry, dry_run=False)
import { Registry } from "apcore-js";
import { RegistryWriter } from "apcore-toolkit";
const registry = new Registry();
const writer = new RegistryWriter();
writer.write(modules, registry, { dryRun: false });
HTTPProxyRegistryWriter (Python, TypeScript, and Rust)¶
Registers scanned modules as HTTP proxy classes that forward requests to a running web API. This enables CLI execution without invoking route handlers directly (which depend on framework DI systems).
Features¶
- No Direct Handler Invocation: Proxies requests over HTTP instead of calling view functions.
- Path Parameter Substitution: Automatically maps path parameters (e.g.,
/items/{item_id}) from input values. - Auth Support: Pluggable
auth_header_factoryfor Bearer tokens or custom headers. - Success Range: Accepts any
2xxresponse as success;204 No Contentreturns{}.
Installation¶
Requires the httpx optional dependency:
pip install apcore-toolkit[http-proxy]
Included in the standard apcore-toolkit package. Uses the global fetch API (available in Node.js 20+, browsers, Deno, and workers — no additional dependencies required).
Enabled by default — a plain dependency declaration is enough:
[dependencies]
apcore-toolkit = "0.15"
# To opt out (omit the `reqwest` dependency for lean builds):
apcore-toolkit = { version = "0.15", default-features = false }
Usage¶
from apcore import Registry
from apcore_toolkit import HTTPProxyRegistryWriter
registry = Registry()
writer = HTTPProxyRegistryWriter(
base_url="http://localhost:8000",
auth_header_factory=lambda: {"Authorization": "Bearer xxx"},
)
writer.write(modules, registry)
import { Registry } from "apcore-js";
import { HTTPProxyRegistryWriter } from "apcore-toolkit";
const registry = new Registry();
const writer = new HTTPProxyRegistryWriter({
baseUrl: "http://localhost:8000",
authHeaderFactory: () => ({ Authorization: "Bearer xxx" }),
});
writer.write(modules, registry);
use apcore::Registry;
use apcore_toolkit::HTTPProxyRegistryWriter;
let mut registry = Registry::new();
let writer = HTTPProxyRegistryWriter::new(
"http://localhost:8000".into(),
None, // auth headers
30.0, // timeout seconds
)?;
writer.write(&modules, &mut registry);
Constructor parameter naming
Each SDK names the timeout parameter idiomatically for its language: Python timeout: float = 60.0 (seconds), Rust timeout_secs: f64 (seconds; constructor returns Err(InvalidTimeout) if non-positive or non-finite), TypeScript timeoutMs: number = 60_000 (milliseconds; default is 60 seconds). Default behavior is identical at 60 s; cross-language porters MUST translate the unit when explicitly passing a value.
TypeScript-only constructor option: fetchImpl
The TypeScript constructor accepts an optional fetchImpl?: typeof fetch to inject a custom fetch implementation (useful for tests, edge runtimes, or proxy-aware HTTP clients). When omitted, the writer uses globalThis.fetch (available in Node.js 20+, browsers, Deno, and workers). If neither options.fetchImpl nor globalThis.fetch is available at construction time, the constructor throws. Python (httpx) and Rust (reqwest) inject their own HTTP clients and do not surface an equivalent option.
auth_header_factory Invocation Contract¶
Verified 2026-09-08 against the shipped 0.11.1 sources in all three SDKs. Recorded here because device-auth.md depends on the answer.
The factory is invoked once per outbound request, from inside the proxy
module's execute, not once at construction:
| SDK | Call site |
|---|---|
| Python | output/http_proxy_writer.py — inside ProxyModule.execute, before each httpx call |
| TypeScript | output/http-proxy-writer.ts — inside the execute closure, before each fetch |
| Rust | output/http_proxy_writer.rs — inside the request-building path, before each reqwest send |
Two consequences follow, and both matter to any credential provider wired into this seam:
- A factory returning a rotating value works. Transparent token refresh is reachable without changing the writers, because a token acquired after construction is picked up on the next call.
- The factory is synchronous in all three SDKs. Its return type is a plain
header mapping —
dict[str, str],Record<string, string>,HashMap<String, String>— with no promise, future, or coroutine anywhere in the signature. A provider that needs a network round-trip to refresh therefore cannot perform it inside the factory in TypeScript or Rust. This is a real constraint on any async credential source, not an oversight to route around; seedevice-auth.mdOpen Question 1 for the four options and the recommendation.
The writers also validate the return value: a non-mapping return raises
TypeError (Python) / throws TypeError (TypeScript) rather than being
silently coerced or ignored.
metadata Contract¶
The writer reads the route to call from ScannedModule.metadata, never
from target (target is a human-readable descriptor, not a callable
reference, for a module representing a remote endpoint — see
scanning.md). Any scanner producing
modules for this writer, including the OpenAPI Scanner,
should emit the following flat, snake_case route keys.
metadata key |
Value | Example |
|---|---|---|
http_method |
Uppercase HTTP method | "GET" |
url_path |
Path template, {param} braces retained, leading slash |
"/users/{user_id}" |
Legacy route defaults and casing
A legacy module can fall back to "GET" or "/" when route metadata
is absent. The Rust writer matches uppercase methods. The Python
writer uses uppercase methods to select the body encoding. TypeScript
uppercases the configured method. The effective preflight reports
unavailable route fields before registration.
The writer extracts path-parameter names from url_path and removes
them from the remaining inputs. It sends the remaining inputs as a JSON
body for POST, PUT and PATCH, and as query parameters for
GET, DELETE, HEAD and OPTIONS. The effective preflight checks
whether the selected operation fits this method-based partition.
Cross-SDK reader asymmetry (documented, not yet reconciled)
Rust reads metadata only. Python and TypeScript also honour top-level
http_method / url_path attributes on framework-specific
ScannedModule subclasses, and TypeScript additionally accepts
camelCase metadata.httpMethod / metadata.urlPath. No shipped scanner
relies on the wider surface — every scanner (including the OpenAPI
Scanner) writes the snake_case metadata keys, the intersection all
three readers honour — but the asymmetry itself is worth knowing before
assuming "documented for one SDK" means "true for all three".
Effective OpenAPI Forwarding¶
Modules from effective parameter scanning
carry metadata.openapi.proxy_inputs. Their route must be origin-relative,
start with a single slash and contain no literal query or fragment delimiters
or backslashes. Placeholders use balanced braces and have nonempty names.
The writer substitutes only these placeholders and URL-encodes their scalar
values, so a/b becomes a%2Fb. Colons in effective paths remain literal.
Legacy modules continue to support brace and colon placeholders.
The portable proxy supports simple scalar path parameters, scalar query parameters and default exploded form arrays of scalars. An exploded array uses repeated query keys. The preflight rejects unsupported path and query encodings, query inputs on body methods, and JSON body inputs on query methods. It also reports name collisions between path, query and body inputs and mismatches between the route, the published schema and the input metadata. Header and cookie declarations are outside this tool input contract. Request headers can be supplied through the writer's header configuration.
The effective scanner resolves same-document Request Body Objects and
uses the exact application/json media type. The portable body shape is a
flat object with named properties. The writer sends a representable required
JSON body even when the caller supplies no fields, using {} when all
properties are optional. TRACE is outside the portable proxy contract
because the default TypeScript Fetch transport rejects it.
Effective Proxy Diagnostics¶
Call the toolkit validator on the final selected modules before calling
HTTPProxyRegistryWriter.write. Importers can use the detector to report all
findings without registering anything. Neither API makes HTTP requests.
The writer still reports individual registration failures in its
WriteResult values.
| SDK | Detector | Validator | Wire conversion |
|---|---|---|---|
| Python | detect_effective_proxy_hazards(modules) |
validate_effective_proxy_modules(modules) raises ValueError when findings exist |
hazard.to_dict() |
| TypeScript | detectEffectiveProxyHazards(modules) |
validateEffectiveProxyModules(modules) throws Error when findings exist |
effectiveHazardToWire(hazard) |
| Rust | detect_effective_proxy_hazards(&modules) |
validate_effective_proxy_modules(&modules) returns Result<(), EffectiveProxyValidationError> |
Serialize with Serde |
Rust exports the detector, validator and typed error with the http-proxy
feature, which is enabled by default. The error exposes its findings in
hazards.
Each serialized finding has module_id, http_method, url_path and
kind. The outer method and path contain the selected route values, with
? for an unavailable value. kind.code selects the remaining fields.
kind.code |
Additional fields on kind |
|---|---|
missing_effective_inputs |
None |
invalid_effective_inputs |
detail |
missing_route_metadata |
key (http_method or url_path) |
unsupported_http_method |
method |
parameter_resolution |
problem |
query_on_body_method |
parameters |
body_on_query_method |
properties |
name_collision |
name, locations in path, query, body order |
path_template_mismatch |
undeclared, unused |
input_schema_mismatch |
unlocated, unpublished |
Each problem has kind and scope (path_item or operation).
invalid_list has no additional fields. invalid_parameter adds index,
reference adds index, reference and reason, and duplicate adds
name and location. An external reference is displayed as
<external-ref>.
An unsupported_input has operation scope and includes location,
name and reason. Path and query issues use the parameter name and
path_serialization or query_serialization. Body issues use
requestBody and one of request_body_reference,
request_body_media_type or request_body_schema.
Contract: HTTPProxyRegistryWriter.write¶
Inputs¶
modules: list ofScannedModule, requiredregistry:apcore.Registry(Python) /Registry(TypeScript, fromapcore-js) /&apcore::Registry(Rust), required — the live registry to register HTTP proxy modules into
Errors¶
- None raised. Per-module failures (registry rejection, target validation, proxy-class build error) are captured into a failed
WriteResult(Python:verified=False, verification_error=...; TypeScript:createWriteResult(..., false, msg); Rust:WriteResult::failed(...)) and returned in the result list, so one failing module does not abort the batch. HTTP requests themselves are issued later, at module call-time — not duringwrite. Callers should iterate the returned list and check each entry'sverifiedfield.
Returns¶
- On success: list of
WriteResult—pathisNone/null(no file written)
Properties¶
- async: false
- pure: false (mutates registry)
- availability: Python (always — requires
httpx; install withapcore-toolkit[http-proxy]), TypeScript (included in the standard package; uses globalfetch— available in Node.js 20+, browsers, Deno, and workers), and Rust (thehttp-proxyCargo feature is enabled by default so a vanilla dependency declaration exposesHTTPProxyRegistryWriter; opt out withdefault-features = falsefor lean builds).
get_writer() Factory¶
The get_writer(format) factory function returns the appropriate writer instance for a given output format, avoiding the need to import each writer class individually.
Supported Formats¶
| Format | Returns | Language |
|---|---|---|
"yaml" |
YAMLWriter instance |
Python, TypeScript, Rust |
"python" |
PythonWriter instance |
Python |
"typescript" |
TypeScriptWriter instance |
TypeScript |
"registry" |
RegistryWriter instance |
Python, TypeScript, Rust |
"http-proxy" |
HTTPProxyRegistryWriter instance |
Python, TypeScript, Rust (feature http-proxy) |
from apcore_toolkit.output import get_writer
writer = get_writer("yaml") # YAMLWriter
writer = get_writer("python") # PythonWriter
writer = get_writer("registry") # RegistryWriter
writer = get_writer("http-proxy", base_url="http://localhost:8000") # HTTPProxyRegistryWriter
import { getWriter } from "apcore-toolkit";
const writer = getWriter("yaml"); // YAMLWriter
const writer = getWriter("typescript"); // TypeScriptWriter
const writer = getWriter("registry"); // RegistryWriter
const writer = getWriter("http-proxy", { baseUrl: "http://localhost:8000" }); // HTTPProxyRegistryWriter
Contract: get_writer¶
Inputs¶
format: string, required — output format name. Canonical formats are matched case-sensitively in all three SDKs.- Python:
"yaml","python","registry","http-proxy"— raisesValueErrorfor anything else - TypeScript:
"yaml","typescript","registry","http-proxy"— raisesInvalidFormatErrorfor anything else - Rust: returns
Result<OutputFormat, InvalidFormatError>(not a writer instance — idiomatic Rust divergence). Supported variants:Yaml,Registry, and (with thehttp-proxyCargo feature)HttpProxy. Unknown formats yieldErr(InvalidFormatError::Unknown(format)). - HTTP-proxy aliases (cross-SDK guarantee). All three SDKs accept the aliases
"http-proxy"(canonical),"http_proxy", and"httpproxy"for the HTTP-proxy variant. Rust additionally matches the http-proxy alias set case-insensitively (e.g.,"HTTP_PROXY"); Python and TypeScript match these aliases case-sensitively only. - Additional keyword args (Python only): forwarded to the writer constructor (e.g.,
base_urlfor"http-proxy")
Errors¶
ValueError(Python) /InvalidFormatError(TypeScript) — unknown format stringImportError(Python,"http-proxy"only) —httpxnot installed- Python only:
TypeErrorraised byget_writer(...)when extra keyword arguments are passed to a format that does not accept them ("yaml","python","registry"). TypeScript and Rust factories take typed options and cannot receive extra kwargs at the API surface. - TypeScript only:
TypeErrorraised bygetWriter("http-proxy", options)whenoptions.baseUrlis missing. Python catches the equivalent missing-argument case in theHTTPProxyRegistryWriterconstructor; Rust'sHttpProxyvariant carries no inline configuration and the missing-config case surfaces at writer-construction sites elsewhere.
Returns¶
- On success: writer instance (
YAMLWriter,PythonWriter,TypeScriptWriter,RegistryWriter,HTTPProxyRegistryWriter) - Rust exception: returns
OutputFormatenum variant (caller matches and constructs the writer)
Properties¶
- async: false
- pure: true (constructs a new instance, no side effects)
Contract: Verifier.verify¶
Inputs¶
path: string or Path, required — path to the written artifact (may beNone/nullfor RegistryWriter output; verifiers should handle gracefully)module_id: string, required — the module ID of the written artifact
Errors¶
- None raised — verifier implementations MUST NOT raise; they must catch internal errors and return
VerifyResult(ok=False, error="..."). Uncaught exceptions are caught by the verifier chain and wrapped intoWriteResult.verification_error.
Returns¶
- On success:
VerifyResult(ok=True)— artifact is well-formed - On failure:
VerifyResult(ok=False, error="<human-readable message>")
Properties¶
- async: false
- pure: false (reads filesystem or registry)
- thread_safe: true (implementations should not share mutable state)
Contract: WriteResult¶
Inputs¶
N/A — this is a data class, not a callable function.
Errors¶
N/A — data classes are not called and do not raise secondary exceptions.
Returns¶
N/A — data classes are not called and do not return values.
Fields¶
module_id/moduleId: string — the module that was writtenpath: string | None / string | null — output file path;None/nullfor RegistryWriter (no file written)verified: bool / boolean — whether verification passed; alwaysTrue/truewhenverify=falseverification_error/verificationError: string | None / string | null — error message if verification failed
Properties¶
- immutable: true (data-only result object, not mutated after construction)
- availability: All three SDKs (field names are camelCase in TypeScript, snake_case in Python/Rust)
Contract: WriteError¶
Inputs¶
N/A — this is an exception/error class, not a callable function.
Errors¶
N/A — exception classes are not called and do not raise secondary exceptions.
Returns¶
N/A — exception classes are not called and do not return values.
Fields¶
path: string — the file path that could not be written (or the registry key that could not be registered)cause: Exception / Error / std::io::Error — the underlying OS or framework error
Properties¶
- immutable: true
- availability: Python (raised), TypeScript (thrown), Rust (returned as
Err(WriteError))
Built-In Verifiers Overview¶
All built-in verifiers implement the Verifier protocol. Each reads the artifact and checks well-formedness. None raises — failures are returned as VerifyResult(ok=False, error=...). The five built-in classes each have their own Contract block below.
| Verifier | Used By | Checks |
|---|---|---|
YAMLVerifier |
YAMLWriter |
File exists, YAML parses without error, module_id and target keys present |
SyntaxVerifier |
PythonWriter / TypeScriptWriter |
File exists, source code parses without syntax errors (AST/TS compiler) |
RegistryVerifier |
RegistryWriter |
registry.get(module_id) returns a valid module |
MagicBytesVerifier |
(custom use) | File header matches expected format signature |
JSONVerifier |
(custom use) | File parses as valid JSON; optional schema validation |
Contract: YAMLVerifier.verify¶
Inputs¶
path: string, required — filesystem path to the YAML artifact. An empty string is treated as a registry-backed module (skipped gracefully — returns ok=true).module_id: string, required — module ID being verified.
Errors¶
- None raised. Failure modes (file not found, malformed YAML, missing
module_id/targetkeys) are returned asVerifyResult(ok=False, error="...").
Returns¶
- On success:
VerifyResult(ok=True). - On verification failure:
VerifyResult(ok=False, error="<reason>").
Properties¶
- async: false
- pure: false (reads filesystem)
- thread_safe: true
Contract: SyntaxVerifier.verify¶
Inputs¶
path: string, required — filesystem path to the source artifact (.pyor.ts). An empty string is skipped gracefully.module_id: string, required.
Errors¶
- None raised. Failure modes (file not found, parse / AST error, TypeScript compiler diagnostic) are returned as
VerifyResult(ok=False, error="...").
Returns¶
- On success:
VerifyResult(ok=True). - On parse failure:
VerifyResult(ok=False, error="<reason>").
Properties¶
- async: false
- pure: false (reads filesystem; may invoke a subprocess for TS)
- thread_safe: true
Contract: RegistryVerifier.verify¶
Inputs¶
path: string, required — ignored by this verifier; pass""for registry-backed modules.module_id: string, required — looked up in the suppliedregistry.
Errors¶
- None raised. Failure mode (
registry.get(module_id)returns null/None) is returned asVerifyResult(ok=False, error="Module \"<id>\" not found in registry"). If the registry instance does not expose agetmethod, the verifier returnsVerifyResult(ok=False, error="Registry does not have a get method")(fixed in v0.9.0 — the verifier previously called the nonexistentgetModule()).
Returns¶
- On success:
VerifyResult(ok=True). - On absence:
VerifyResult(ok=False, error="<reason>").
Properties¶
- async: false
- pure: false (reads from the registry)
- thread_safe: true (reads only)
Contract: MagicBytesVerifier.verify¶
Inputs¶
path: string, required — filesystem path to the artifact. An empty string is skipped gracefully.module_id: string, required.
Errors¶
- None raised. Failure modes (file not found, header mismatch with expected signature) are returned as
VerifyResult(ok=False, error="...").
Returns¶
- On success:
VerifyResult(ok=True). - On signature mismatch:
VerifyResult(ok=False, error="<reason>").
Properties¶
- async: false
- pure: false (reads filesystem)
- thread_safe: true
Contract: JSONVerifier.verify¶
Inputs¶
path: string, required — filesystem path to the JSON artifact. An empty string is skipped gracefully.module_id: string, required.
Constructor¶
- Python:
JSONVerifier(schema: dict | None = None)— optional JSON Schema validated viajsonschema. - TypeScript:
new JSONVerifier(schema?: Record<string, unknown>)— optional schema validated viaAjv(strict: false). - Rust:
JSONVerifier::new()/JSONVerifier::default()— no schema parameter. The Rust verifier only checks that the artifact parses as valid JSON. Schema validation is Python/TypeScript only; Rust callers who need schema enforcement should chain a custom verifier afterJSONVerifierin the verifier chain.
Errors¶
- None raised. Failure modes (file not found, malformed JSON, optional schema validation failure in Python/TypeScript only) are returned as
VerifyResult(ok=False, error="...").
Returns¶
- On success:
VerifyResult(ok=True). - On parse / schema failure:
VerifyResult(ok=False, error="<reason>").
Properties¶
- async: false
- pure: false (reads filesystem)
- thread_safe: true
Output Verification¶
Writers can optionally verify that their output artifacts are well-formed after writing. This prevents silent failures where a writer produces a file that apcore cannot load.
Verification by Writer Type¶
| Writer | Verification Checks |
|---|---|
YAMLWriter |
File exists, YAML parses without error, contains required module_id and target fields |
PythonWriter / TypeScriptWriter |
File exists, source code parses without syntax errors (AST/TS compiler check) |
RegistryWriter |
Module ID is registered, registry.get(module_id) returns a valid module |
Usage¶
Verification is enabled via the verify parameter. All writers support verify and verifiers:
from apcore_toolkit import YAMLWriter, PythonWriter, RegistryWriter
# YAMLWriter
writer = YAMLWriter()
results = writer.write(modules, output_dir="./bindings", verify=True, verifiers=[])
# PythonWriter
writer = PythonWriter()
results = writer.write(modules, output_dir="./generated", verify=True, verifiers=[])
# RegistryWriter
writer = RegistryWriter()
results = writer.write(modules, registry, verify=True, verifiers=[])
# results contains verification status per module
for r in results:
if not r.verified:
print(f"WARNING: {r.module_id} — {r.verification_error}")
import { YAMLWriter, TypeScriptWriter, RegistryWriter } from "apcore-toolkit";
// YAMLWriter
const yamlWriter = new YAMLWriter();
const results1 = yamlWriter.write(modules, "./bindings", { verify: true, verifiers: [] });
// TypeScriptWriter
const tsWriter = new TypeScriptWriter();
const results2 = tsWriter.write(modules, "./generated", { verify: true, verifiers: [] });
// RegistryWriter
const regWriter = new RegistryWriter();
const results3 = regWriter.write(modules, registry, { verify: true, verifiers: [] });
for (const r of results1) {
if (!r.verified) {
console.warn(`WARNING: ${r.moduleId} — ${r.verificationError}`);
}
}
Verification Result¶
Each write operation returns a list of WriteResult objects:
| Field (Python / TypeScript) | Python Type | TypeScript Type | Description |
|---|---|---|---|
module_id / moduleId |
str |
string |
The module that was written |
path |
str \| None |
string \| null |
Output file path (None/null for RegistryWriter) |
verified |
bool |
boolean |
Whether verification passed (always True if verify=False) |
verification_error / verificationError |
str \| None |
string \| null |
Error message if verification failed |
Use in CI
Enable verification in CI pipelines to catch binding generation issues before deployment. A scan → write → verify cycle ensures that generated artifacts are always loadable by apcore.
Custom Verifiers¶
The built-in verification checks (YAML parsability, AST syntax, Registry lookup) cover common cases. For domain-specific needs, writers accept a pluggable Verifier interface.
Verifier Protocol¶
from typing import Protocol
class Verifier(Protocol):
def verify(self, path: str, module_id: str) -> VerifyResult: ...
@dataclass
class VerifyResult:
ok: bool
error: str | None = None
interface Verifier {
verify(path: string, moduleId: string): VerifyResult;
}
interface VerifyResult {
ok: boolean;
error?: string;
}
Built-in Verifiers¶
| Verifier | Used By | Checks |
|---|---|---|
YAMLVerifier |
YAMLWriter |
YAML parses, required fields present |
SyntaxVerifier |
PythonWriter / TypeScriptWriter |
Source code parses without errors |
RegistryVerifier |
RegistryWriter |
Module registered and retrievable |
MagicBytesVerifier |
(available for custom use) | File header matches expected format |
JSONVerifier |
(available for custom use) | JSON parses, optional schema validation |
Custom Verifier Example¶
from apcore_toolkit.output import YAMLWriter, Verifier, VerifyResult
class StrictYAMLVerifier:
"""Verify YAML bindings have descriptions for all parameters."""
def verify(self, path: str, module_id: str) -> VerifyResult:
with open(path) as f:
data = yaml.safe_load(f)
schema = data.get("input_schema", {})
for prop, spec in schema.get("properties", {}).items():
if "description" not in spec:
return VerifyResult(ok=False, error=f"Missing description for {prop}")
return VerifyResult(ok=True)
writer = YAMLWriter()
results = writer.write(modules, output_dir="./bindings", verify=True, verifiers=[StrictYAMLVerifier()])
Verifier Chain¶
When multiple verifiers are provided, they run in order. The first failure stops the chain and sets WriteResult.verified = False.
results = writer.write(
modules,
output_dir="./bindings",
verify=True,
verifiers=[YAMLVerifier(), StrictYAMLVerifier(), CustomSchemaVerifier()],
)
Lesson from CLI-Anything
The CLI-Anything project validates output with magic bytes, pixel analysis, and RMS audio levels — never trusting exit code alone. The same principle applies: always verify the artifact, not the process exit status. The MagicBytesVerifier is directly inspired by this approach.
Contract: run_verifier_chain¶
run_verifier_chain / runVerifierChain is the public helper that orchestrates a sequence of verifiers against a single written artifact. Writers call it internally after each write step; callers can also invoke it directly to run a verifier chain outside the writer workflow (e.g., for post-build CI checks against already-written .binding.yaml files).
Inputs¶
verifiers: list ofVerifier/Verifier[]/&[&dyn Verifier], required — ordered chain of verifiers to runpath: string, required — passed to eachverifier.verify(path, module_id). For Registry-backed artifacts that have no on-disk file, callers pass the empty string""(the convention used byRegistryWriteritself, seeoutput/registry_writer). Built-in file-based verifiers (YAMLVerifier,JSONVerifier,MagicBytesVerifier,SyntaxVerifier) skip gracefully whenpathis"". All three SDKs share this signature: Pythonstr, TypeScriptstring, Rust&str.module_id/moduleId: string, required — module ID passed to each verifier for error context
Errors¶
- None raised. Verifier exceptions (both declared and unexpected) are caught by the chain and surfaced as
VerifyResult(ok=False, error="Verifier crashed: …"). In Rust the chain wraps eachverifycall instd::panic::catch_unwind, so a panicking verifier becomesVerifyResult { ok: false, error: "Verifier crashed: …" }rather than unwinding through the writer. Python and TypeScript additionally append a(verifier: <ClassName>)suffix to the crash message; Rust omits the suffix because trait objects (&dyn Verifier) erase type names.
Returns¶
- On success: the first failing
VerifyResultencountered in the chain, ORVerifyResult(ok=True)if every verifier passed. - Short-circuit: evaluation stops at the first failure; subsequent verifiers in the chain are not invoked.
Properties¶
- async: false
- pure: false (verifiers typically read filesystem or registry state)
- thread_safe: true (no shared mutable state within the chain)
- availability: all three SDKs —
run_verifier_chain(Python, Rust),runVerifierChain(TypeScript)
Example¶
from apcore_toolkit.output import run_verifier_chain, YAMLVerifier
result = run_verifier_chain(
[YAMLVerifier(), StrictYAMLVerifier()],
path="./bindings/users.create.binding.yaml",
module_id="users.create",
)
if not result.ok:
print(f"Verification failed: {result.error}")
import { runVerifierChain, YAMLVerifier } from "apcore-toolkit";
const result = runVerifierChain(
[new YAMLVerifier(), new StrictYAMLVerifier()],
"./bindings/users.create.binding.yaml",
"users.create",
);
if (!result.ok) {
console.warn(`Verification failed: ${result.error}`);
}
use apcore_toolkit::{run_verifier_chain, Verifier, YAMLVerifier};
let yaml = YAMLVerifier;
let verifiers: Vec<&dyn Verifier> = vec![&yaml];
let result = run_verifier_chain(
&verifiers,
"./bindings/users.create.binding.yaml",
"users.create",
);
if !result.ok {
eprintln!("Verification failed: {:?}", result.error);
}
Error Handling¶
Writers and verifiers follow a consistent error handling pattern:
| Scenario | Behavior |
|---|---|
| Write succeeds, verify succeeds | WriteResult(verified=True) |
| Write succeeds, verify fails | WriteResult(verified=False, verification_error="...") — artifact exists but is malformed |
| Write fails (I/O error) | Raises WriteError with path and cause |
| Verifier itself throws | Caught and wrapped as WriteResult(verified=False, verification_error="Verifier crashed: ...") |
Writers never silently swallow errors. If verify=False, verification is skipped entirely (not suppressed).
from apcore_toolkit.output import WriteError
try:
results = writer.write(modules, output_dir="./bindings", verify=True)
except WriteError as e:
print(f"Failed to write {e.path}: {e.cause}")
Contract: YAMLWriter.write¶
Inputs¶
modules: list ofScannedModule, requiredoutput_dir: string or Path, required — directory where.binding.yamlfiles will be written (one file per module)dry_run: bool, optional, default=false — if true, no files are written; returns what would be writtenverify: bool, optional, default=false — if true, runs built-inYAMLVerifierafter writing each fileverifiers: list of verifier objects, optional — additional custom verifiers to run after write- TypeScript-only option:
options.errorMode: "throw" | "collect"(default:"throw") — applies to the file writers (YAMLWriter,TypeScriptWriter), defined onFileWriteOptions. "throw"— raisesWriteErroron the first file-system write failure (default)."collect"— accumulates failures intoWriteResultobjects instead of throwing; useful for batch writes where you want to continue after individual failures.- Python and Rust file writers always raise/return-
Erron write failure (noerrorModeequivalent).RegistryWriterdoes not supporterrorModein any language (it always collects — see its Contract).
Errors¶
WriteError/WriteError— file system write failure (in TypeScript, only whenerrorMode="throw"; with"collect"the failure is captured in the returnedWriteResult)- All three SDKs wrap verifier results into
WriteResult.verification_error(Python/Rust) /WriteResult.verificationError(TypeScript). Verifier exceptions are caught and stored as verification errors rather than being re-raised.
Returns¶
- Python/TypeScript:
list[WriteResult]/WriteResult[]on success; raises/throwsWriteErroron I/O failure - Rust:
Result<Vec<WriteResult>, WriteError>— callers must handle the Result explicitly
Each WriteResult has module_id, path, ok, verified, verification_error.
Properties¶
- async: false
- pure: false (writes to filesystem unless dry_run=true)
- idempotent: true (writing same modules twice produces same files)
Contract: RegistryWriter.write¶
Inputs¶
modules: list ofScannedModule, requiredregistry:apcore.Registry/Registry(fromapcore-js), required — the live registry to register modules intodry_run: bool, optional, default=false — if true, no modules are registered; returns what would be registeredverify: bool, optional, default=false — if true, runs built-inRegistryVerifierafter each registrationverifiers: list of verifier objects, optional — additional custom verifiersallowed_prefixes/allowedPrefixes: list of str, optional, default=None/undefined(no restriction) — security allow-list of permitted module-id target prefixes. When set, each module's resolved target is validated against the list before registration; a target outside the allow-list is rejected as a per-module failure (see Errors). Defence-in-depth against arbitrary-code-execution via attacker-influenced targets. Present in all three SDKs (registry_writer.py,registry-writer.ts,registry_writer.rs) — but the matching semantics are language-specific, not portable values; seepydantic.md§resolve_target/resolveTargetfor exactly what a "prefix" means in each language.
Note:
RegistryWriter.writedoes not accept anerrorModeoption. Unlike the file writers, it never aborts the batch on a per-module failure — see Errors below. TheerrorMode: "throw" | "collect"option belongs to the file writers (YAMLWriter/TypeScriptWriter), documented under their Contracts.
Errors¶
RegistryWriter.writecollects per-module failures rather than raising — this is identical across Python, TypeScript, and Rust. If target resolution, theallowed_prefixescheck, orregistry.registerfails for a module, that module gets a failedWriteResult(verified=false,verification_error/verificationErrorset) and the batch continues; one bad module never aborts the rest.- Verifier results are likewise wrapped into
WriteResult.verification_error(Python/Rust) /WriteResult.verificationError(TypeScript); verifier exceptions are caught and stored, not re-raised. - Rust's
writereturns a bareVec<WriteResult>(not wrapped inResult) — per-module registration failures are reported exclusively via failedWriteResultentries, the same mechanism Python/TypeScript use. There is no top-level error channel in any of the three SDKs;WriteResult.verifiedis always the source of truth.
Returns¶
- On success: list of
WriteResult— one per module;pathisNone/null(no file written)
Properties¶
- async:
false(Python, Rust) /true(TypeScript) — the TypeScriptRegistryWriter.writereturnsPromise<WriteResult[]>because itawaitsresolveTarget(target)internally (dynamic module resolution). Python and Rust resolve targets synchronously. TypeScript callers mustawaitthe call:await writer.write(modules, registry). - pure: false (mutates registry unless dry_run=true)
- idempotent: false — registering the same
module_idtwice raisesInvalidInputError(code=DUPLICATE_MODULE_ID)(apcore 0.22.0+).RegistryWriter.writeregisters modules sequentially; a duplicate appears as a failedWriteResultentry in the returned list and the batch continues.
StreamingModule support (apcore 0.22.0+)
RegistryWriter automatically detects and handles streaming targets:
- Python / TypeScript — if the resolved target has an async
stream()method,RegistryWriterwraps it in a streaming-capable adapter (_StreamingFunctionModule/StreamingFunctionModule) that satisfies theStreamingModuleProtocol / interface. The adapter passesisinstance(m, StreamingModule)/isStreamingModule(m)without triggering the duck-typing deprecation warning. - Rust — supply a
StreamingHandlerFactoryviaRegistryWriter::with_streaming_handler_factory(factory). When the factory returnsSome(stream_fn)for a module'starget, the module is registered as aStreamingFunctionModule(implements bothModuleandStreamingModule, somodule.as_streaming()returnsSome).
If annotations.streaming=True but the target provides no streaming implementation (no async stream() method in Python/TypeScript, or the factory returns None in Rust), RegistryWriter logs a WARNING and clears the streaming flag so Registry.register does not raise StreamingInterfaceError. The module is registered as a non-streaming FunctionModule.
Registration Ordering Invariant (apcore 0.22.0+)
RegistryWriter.write registers modules sequentially. Under apcore 0.22.0's deferred-publish guarantee, each module is not visible to registry.get() / registry.list() until its on_load callbacks complete. When write() returns, all successfully registered modules are guaranteed to be immediately discoverable.
Choosing a Writer¶
| Use Case | Recommended Writer |
|---|---|
| Configuration-first approach | YAMLWriter |
| Migrating legacy views to decorators | PythonWriter / TypeScriptWriter |
| Live, dynamic module exposure | RegistryWriter |
| Fast, zero-config integration | RegistryWriter |
| CLI execution against a running API (Python, TypeScript, Rust) | HTTPProxyRegistryWriter |
Conformance: annotation preservation¶
Approval and ACL gating key on a module's requires_approval annotation, which is only
reachable if annotations survive scan → register → get_definition. A writer that drops
them during registration disables that gate silently — no error, no warning.
To make that failure mode impossible to ship unnoticed, the toolkit provides a shared,
framework-agnostic conformance check (added in 0.10.0). It registers a module through a
writer and asserts its behavioral annotations (requires_approval, destructive) round-trip.
Import it into each adapter's test suite:
from apcore_toolkit import assert_annotations_preserved
assert_annotations_preserved(MyRegistryWriter(), scanned_module, Registry()) # raises AssertionError
import { assertAnnotationsPreserved } from 'apcore-toolkit';
await assertAnnotationsPreserved(new MyRegistryWriter(), scannedModule, new Registry()); // throws
use apcore_toolkit::assert_annotations_preserved;
assert_annotations_preserved(&MyRegistryWriter::new(), &module, &Registry::new()); // panics
Python writer hooks (0.10.0)
In the Python SDK, RegistryWriter centralizes field mapping in _build_function_module
and exposes narrow override hooks — _adapt_func, _build_input_schema,
_build_output_schema. Subclass writers customize only these; they can no longer drop a
field (such as annotations) by hand-copying the constructor argument list. The TypeScript
and Rust writers already preserved annotations, so no equivalent refactor was needed there.