Skip to content

Platform Engineering: Embedding Netherframe with nf.sdk

Every nf CLI command is built on top of netherframe.sdk (nf.sdk). If you are building an internal developer platform (IDP), a self-service FastAPI portal, a Slack/ChatOps bot, or a multi-stage deployment orchestrator in Python, call nf.sdk.Project or nf.sdk.AsyncProject directly instead of shelling out to a CLI and scraping stdout.

For the full method table and reference, see nf.sdk API Reference.


Why embed nf.sdk instead of wrapping the CLI?

  • 100% parity by test contract: test_sdk_parity fails if any CLI command or option is missing from nf.sdk.
  • Structured dataclasses & exceptions: Commands never print and never call sys.exit(). They return typed results (whose .to_dict() matches --json) and raise NfError subclasses with machine-readable .code, .exit_code, and .to_dict().
  • Concurrency-safe without os.chdir(): Project root, settings, and inputs are bound via contextvars per call, so multiple threads or async tasks can operate on different projects, environments, and settings inside one Python process simultaneously.
  • No accidental user config: nf.sdk never reads ~/.config/nf/config.toml or NF_* environment variables.

Pattern 1: Plan, inspect policy, apply the exact reviewed artifact

import tempfile
from pathlib import Path

from nf.sdk import NfError, Project


def safe_deploy(project_dir: str, app_name: str, env: str) -> dict[str, object]:
    project = Project(
        project_dir,
        settings={"max_concurrent_resources": 20, "recovery_strategy": "rollback"},
        inputs={"env": env},
    )
    with tempfile.TemporaryDirectory() as tmp:
        plan_path = str(Path(tmp) / f"{app_name}-{env}.plan.json")
        [plan] = project.plan(app=app_name, plan_out=plan_path).plans

        destructive = [c.key for c in plan.result.changes if c.action in {"delete", "replace"}]
        if destructive:
            raise RuntimeError(f"Refusing destructive plan for {env}: {', '.join(destructive)}")

        if not plan.result.changes:
            return {"changed": False, "outputs": {}}

        [run] = project.apply(app=app_name, plan_file=plan_path, auto_approve=True).runs
        if not run.success:
            raise RuntimeError("; ".join(run.result.errors))
        return {"changed": True, "outputs": run.outputs(), "exit_code": run.incomplete_exit_code}

See the runnable local examples examples/python_api and examples/canary_rollout.


Pattern 2: Custom approval and progress callbacks for portals & bots

Interactive prompts and live progress bars become plain Python callbacks in nf.sdk:

from typing import Any

from nf.sdk import Project


def deploy_with_callbacks(project_dir: str, app_name: str) -> Any:
    events: list[tuple[str, str]] = []

    def approve(plan_summary: Any) -> bool:
        # Hook into a Slack button, web UI approval, or policy service
        return not any(c.action == "delete" for c in getattr(plan_summary, "changes", ()))

    def on_progress(event: Any) -> None:
        events.append((getattr(event, "resource", ""), getattr(event, "status", "")))

    project = Project(project_dir)
    return project.apply(app=app_name, approve=approve, on_progress=on_progress)

Pattern 3: Async services (AsyncProject) and structured API errors

For FastAPI, Starlette, or anyio workers, use AsyncProject and serialize NfError cleanly into HTTP responses:

from nf.sdk import AsyncProject, NfError


async def plan_endpoint(project_dir: str, app_name: str, env: str) -> tuple[int, dict[str, object]]:
    project = AsyncProject(project_dir, inputs={"env": env})
    try:
        plans = await project.plan(app=app_name)
        return 200, plans.to_dict(diff=True)
    except NfError as exc:
        # Stable codes: NF_USAGE, NF_PROJECT, NF_NOT_FOUND, NF_INPUTS, NF_DECLINED, NF_RUN_FAILED
        status = 400 if exc.code in {"NF_USAGE", "NF_INPUTS"} else 500
        return status, exc.to_dict()

Important gotchas when embedding multi-project servers

  1. Resolve files inside app modules relative to __file__: Because Project(root) never calls os.chdir(), Netherframe resolves all Netherframe paths (state, plans, mirrors, provider cwd) against root, while ordinary open("policy.json") in app code still uses the process cwd. Always write Path(__file__).parent / "policy.json" inside app modules.
  2. Avoid colliding top-level helper module names across projects in one process: Each project's root is added to sys.path when loaded, and sys.modules is process-global. Namespace project packages (for example, acme_payments.infra instead of bare helpers).
  3. Pass secrets in memory: Project(inputs={"db_password": secret}) satisfies Secret[str] parameters directly without temporary files.