Claude Code plugin for myfy Python framework development. Provides skills for patterns, agents for scaffolding, and commands for common operations.

version
0.1.0
GitHub stars
87

Install

/plugin install myfy@myfy-plugins

Run it inside Claude Code after adding the marketplace with /plugin marketplace add psincraian/myfy.

Contents

Discovered from source

Skills 9

CliModule - Custom CLI Commands

CliModule enables custom CLI commands with full dependency injection and Typer integration.

Quick Start

from myfy.core import Application
from myfy.commands import CliModule, cli

@cli.command()
async def seed_users(user_service: UserService, count: int = 10):
    '''Seed the database with test users.'''
    for i in range(count):
        await user_service.create(f"user{i}@example.com")
    print(f"Created {count} users")

app = Application()
app.add_module(CliModule())

# Run with: myfy app seed-users --count 20

Configuration

Environment variables use the MYFY_CLI_ prefix:

VariableDefaultDescription
MYFY_CLI_VERBOSEFalseEnable verbose output
MYFY_CLI_NO_COLORFalseDisable colored output
MYFY_CLI_TIMEOUT300Command timeout (seconds)

Defining Commands

Basic Command

from myfy.commands import cli

@cli.command()
async def hello():
    '''Say hello.'''
    print("Hello, World!")

# Run: myfy app hello

With DI Injection

Services are automatically injected:

from myfy.commands import cli
from myfy.data import AsyncSession

@cli.command()
async def count_users(session: AsyncSession):
    '''Count users in the database.'''
    result = await session.execute(select(func.count(User.id)))
    count = result.scalar()
    print(f"Total users: {count}")

# Run: myfy app count-users

With Arguments

@cli.command()
async def greet(name: str):
    '''Greet someone by name.'''
    print(f"Hello, {name}!")

# Run: myfy app greet John

With Options

@cli.command()
async def seed(count: int = 10, verbose: bool = False):
    '''Seed the database.'''
    for i in range(count):
        if verbose:
            print(f"Creating user {i + 1}/{count}")
        await create_user(i)
    print(f"Created {count} users")

# Run: myfy app seed --count 50 --verbose

Command Groups

Organize related commands:

from myfy.commands import cli

# Create a group
db = cli.group("db")

@db.command()
async def seed(session: AsyncSession):
    '''Seed the database.'''
    await seed_data(session)

@db.command()
async def reset(session: AsyncSession, force: bool = False):
    '''Reset the database.'''
    if force or confirm("Are you sure?"):
        await reset_data(session)

# Run: myfy app db:seed
#      myfy app db:reset --force

Typer Integration

Use Typer for advanced CLI features:

import typer
from myfy.commands import cli

@cli.command()
async def import_data(
    db: Database,  # DI injection
    file: str = typer.Argument(..., help="Path to import file"),
    dry_run: bool = typer.Option(False, "--dry-run", "-n", help="Simulate import"),
    format: str = typer.Option("json", "--format", "-f", help="File format"),
):
    '''Import data from a file.'''
    if dry_run:
        print(f"Would import from {file} ({format} format)")
    else:
        await db.import_from_file(file, format)

# Run: myfy app import-data users.csv --format csv --dry-run

Typer Features

import typer

@cli.command()
async def deploy(
    # Required argument
    env: str = typer.Argument(..., help="Target environment"),
    # Optional with short form
    version: str = typer.Option(None, "--version", "-v"),
    # Boolean flag
    skip_tests: bool = typer.Option(False, "--skip-tests"),
    # Choice from enum
    region: Region = typer.Option(Region.US, "--region", "-r"),
):
    '''Deploy the application.'''
    ...

# Run: myfy app deploy production -v 1.2.3 --skip-tests --region eu

Parameter Classification

Parameters are automatically classified:

PatternClassification
typer.Argument(...)CLI positional argument
typer.Option(...)CLI option/flag
Primitive with defaultCLI option
Primitive without defaultCLI argument
Complex typeDI dependency
@cli.command()
async def process(
    file: str,                    # CLI argument (required)
    count: int = 10,              # CLI option (--count)
    verbose: bool = False,        # CLI flag (--verbose)
    session: AsyncSession,        # DI injection
    settings: AppSettings,        # DI injection
):
    ...

Custom Command Names

@cli.command(name="import-users")  # Explicit name
async def import_users_handler(file: str):
    '''Import users from file.'''
    ...

# Run: myfy app import-users users.csv

Function name import_users_handler becomes command name import-users by default (underscores to hyphens).

Async vs Sync

Both async and sync handlers are supported:

# Async (recommended)
@cli.command()
async def async_task(session: AsyncSession):
    await session.execute(...)

# Sync (also works)
@cli.command()
def sync_task(settings: AppSettings):
    print(settings.app_name)

Error Handling

@cli.command()
async def risky_operation(session: AsyncSession):
    '''Perform a risky operation.'''
    try:
        await do_risky_thing(session)
    except RiskyError as e:
        print(f"Error: {e}", file=sys.stderr)
        raise typer.Exit(1)

Progress and Output

import typer

@cli.command()
async def process_files(files: list[str]):
    '''Process multiple files.'''
    with typer.progressbar(files) as progress:
        for file in progress:
            await process_file(file)

    typer.echo(typer.style("Done!", fg=typer.colors.GREEN))

Running Commands

# List available commands
myfy app --help

# Run a command
myfy app seed-users

# With options
myfy app seed-users --count 50

# Grouped command
myfy app db:reset --force

# With arguments
myfy app import users.csv

Best Practices

  1. Use docstrings - Become command help text
  2. Group related commands - Easier to discover
  3. Use Typer for complex args - Better help messages
  4. Handle errors gracefully - Use typer.Exit(1) for failures
  5. Show progress - Use typer.progressbar for long operations
  6. Inject services - Don't create DB connections manually
  7. Keep commands focused - One task per command

DataModule - Database Access

DataModule provides async SQLAlchemy integration with connection pooling and REQUEST-scoped sessions.

Quick Start

from myfy.core import Application
from myfy.data import DataModule, AsyncSession
from myfy.web import route

app = Application()
app.add_module(DataModule())

@route.get("/users/{user_id}")
async def get_user(user_id: int, session: AsyncSession) -> dict:
    # session is auto-injected (REQUEST scope)
    result = await session.execute(select(User).where(User.id == user_id))
    return {"user": result.scalar_one_or_none()}

Configuration

Environment variables use the MYFY_DATA_ prefix:

VariableDefaultDescription
MYFY_DATA_DATABASE_URLsqlite+aiosqlite:///./myfy.dbDatabase connection URL
MYFY_DATA_POOL_SIZE5Number of connections in pool
MYFY_DATA_MAX_OVERFLOW10Extra connections beyond pool_size
MYFY_DATA_POOL_TIMEOUT30.0Seconds to wait for connection
MYFY_DATA_POOL_RECYCLE3600Seconds before connection recycled
MYFY_DATA_POOL_PRE_PINGTrueTest connections before use
MYFY_DATA_ECHOFalseLog all SQL statements
MYFY_DATA_ENVIRONMENTdevelopmentEnvironment (blocks auto_create in production)

Supported Databases

# SQLite (development)
MYFY_DATA_DATABASE_URL="sqlite+aiosqlite:///./app.db"

# PostgreSQL (production)
MYFY_DATA_DATABASE_URL="postgresql+asyncpg://user:pass@localhost/db"

# MySQL
MYFY_DATA_DATABASE_URL="mysql+aiomysql://user:pass@localhost/db"

Defining Models

from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

class Base(DeclarativeBase):
    pass

class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(String(255), unique=True)
    name: Mapped[str] = mapped_column(String(100))

Auto-Create Tables (Development Only)

from myfy.data import DataModule

app.add_module(DataModule(
    auto_create_tables=True,  # Only in development!
    metadata=Base.metadata,
))

Raises AutoCreateTablesProductionError if MYFY_DATA_ENVIRONMENT=production.

Using Sessions in Routes

Sessions are REQUEST-scoped (one per HTTP request):

from myfy.data import AsyncSession
from sqlalchemy import select

@route.get("/users")
async def list_users(session: AsyncSession) -> list[dict]:
    result = await session.execute(select(User))
    users = result.scalars().all()
    return [{"id": u.id, "name": u.name} for u in users]

@route.post("/users", status_code=201)
async def create_user(body: UserCreate, session: AsyncSession) -> dict:
    user = User(**body.model_dump())
    session.add(user)
    await session.commit()
    await session.refresh(user)
    return {"id": user.id}

Using Sessions in Providers

from myfy.core import provider, REQUEST
from myfy.data import AsyncSession

@provider(scope=REQUEST)
def user_repository(session: AsyncSession) -> UserRepository:
    return UserRepository(session)

Transactions

Sessions auto-commit on success, rollback on exception:

@route.post("/transfer")
async def transfer(body: TransferRequest, session: AsyncSession) -> dict:
    # Both updates succeed or both rollback
    sender = await session.get(Account, body.sender_id)
    receiver = await session.get(Account, body.receiver_id)

    sender.balance -= body.amount
    receiver.balance += body.amount

    await session.commit()  # Explicit commit
    return {"success": True}

Using SessionFactory Directly

For background jobs or manual session management:

from myfy.data import SessionFactory

@provider(scope=SINGLETON)
def background_service(factory: SessionFactory) -> BackgroundService:
    return BackgroundService(factory)

class BackgroundService:
    async def process(self):
        async with self.factory.session_context() as session:
            # Manual session management
            await self.do_work(session)

Alembic Migrations

Initialize Alembic:

alembic init migrations

Configure alembic.ini:

sqlalchemy.url = driver://user:pass@localhost/dbname

Configure migrations/env.py:

from app.models import Base
target_metadata = Base.metadata

Create and run migrations:

alembic revision --autogenerate -m "Add users table"
alembic upgrade head

Best Practices

  1. Use async drivers - asyncpg for PostgreSQL, aiosqlite for SQLite
  2. Never share sessions - Sessions are REQUEST-scoped for a reason
  3. Use migrations in production - Don't use auto_create_tables in production
  4. Configure pool size - Match to expected concurrent connections
  5. Enable pool_pre_ping - Detects stale connections before use
  6. Use transactions - Group related operations in a single commit

Dependency Injection in myfy

myfy uses constructor-based dependency injection with three scopes.

Scopes

ScopeLifetimeUse Case
SINGLETONApplication lifetimeConfig, pools, services, caches
REQUESTPer HTTP requestSessions, user context, request logger
TASKPer background taskTask context, job-specific state

Provider Declaration

from myfy.core import provider, SINGLETON, REQUEST, TASK

# SINGLETON: Created once, shared across all requests
@provider(scope=SINGLETON)
def database_pool(settings: DatabaseSettings) -> DatabasePool:
    return DatabasePool(settings.database_url)

# REQUEST: Created per HTTP request, auto-cleaned up
@provider(scope=REQUEST)
def db_session(pool: DatabasePool) -> AsyncSession:
    return pool.get_session()

# TASK: Created per background task execution
@provider(scope=TASK)
def task_logger(ctx: TaskContext) -> Logger:
    return Logger(task_id=ctx.task_id)

Provider Options

@provider(
    scope=SINGLETON,              # Lifecycle scope
    qualifier="primary",          # Optional qualifier for multiple providers
    name="my_database",           # Optional name for resolution
    reloadable=("log_level",),    # Settings that can hot-reload
)
def database(settings: Settings) -> Database:
    return Database(settings.db_url)

Scope Dependency Rules

  1. SINGLETON can depend on: other singletons only
  2. REQUEST can depend on: singletons and other request-scoped
  3. TASK can depend on: singletons and other task-scoped

SINGLETON cannot depend on REQUEST/TASK - this fails at compile time!

# WRONG - will fail at startup
@provider(scope=SINGLETON)
def bad_service(session: AsyncSession):  # AsyncSession is REQUEST scope
    return MyService(session)

# CORRECT - use factory pattern
@provider(scope=SINGLETON)
def service_factory(pool: DatabasePool) -> ServiceFactory:
    return ServiceFactory(pool)

@provider(scope=REQUEST)
def service(factory: ServiceFactory, session: AsyncSession) -> MyService:
    return factory.create(session)

Injection in Routes

Parameters are auto-classified in order:

  1. Path parameters - from URL template like {user_id}
  2. Query parameters - annotated with Query(...) or primitives with defaults
  3. Body parameter - Pydantic model or dataclass
  4. DI dependencies - everything else (resolved from container)
from myfy.web import route, Query
from myfy.data import AsyncSession

@route.post("/users/{user_id}/orders")
async def create_order(
    user_id: int,                    # Path param
    limit: int = Query(default=10),  # Query param
    body: OrderCreate,               # Request body (Pydantic model)
    session: AsyncSession,           # DI (REQUEST scope)
    settings: AppSettings,           # DI (SINGLETON)
) -> dict:
    ...

Qualifiers for Multiple Providers

When you have multiple providers of the same type:

from myfy.core import provider, SINGLETON, Qualifier
from typing import Annotated

@provider(scope=SINGLETON, qualifier="primary")
def primary_db(settings: Settings) -> Database:
    return Database(settings.primary_url)

@provider(scope=SINGLETON, qualifier="replica")
def replica_db(settings: Settings) -> Database:
    return Database(settings.replica_url)

# Inject by qualifier
@route.get("/users")
async def list_users(
    db: Annotated[Database, Qualifier("replica")]
) -> list[dict]:
    return await db.fetch_all()

Common Patterns

Factory Pattern (REQUEST from SINGLETON)

@provider(scope=SINGLETON)
def email_client(settings: EmailSettings) -> EmailClient:
    return EmailClient(settings.api_key)

@provider(scope=REQUEST)
def email_sender(client: EmailClient, user: User) -> EmailSender:
    return EmailSender(client, from_user=user)

Optional Dependencies

from typing import Optional

@provider(scope=SINGLETON)
def cache_service(redis: Optional[RedisClient] = None) -> CacheService:
    if redis:
        return RedisCacheService(redis)
    return InMemoryCacheService()

Testing

Override providers in tests using the container's override context:

from myfy.core import override

async def test_with_mock_db():
    mock_db = MockDatabase()

    with override(Database, mock_db):
        # Inside this block, Database resolves to mock_db
        result = await my_service.do_something()

    assert result == expected

Best Practices

  1. Keep providers pure - No side effects in factory functions
  2. Use SINGLETON for shared resources - Database pools, HTTP clients, caches
  3. Use REQUEST for request-specific state - DB sessions, user context
  4. Use TASK for background job state - Task logger, job-specific clients
  5. Validate at compile time - All scope violations caught at startup
  6. Return type required - Provider functions must have return type annotation

FrontendModule - Server-Side Rendering

FrontendModule provides Jinja2 templates with Tailwind 4, DaisyUI 5, and Vite bundling.

Quick Start

from myfy.core import Application
from myfy.web import WebModule, route
from myfy.frontend import FrontendModule, render_template

app = Application()
app.add_module(WebModule())
app.add_module(FrontendModule(auto_init=True))  # Auto-scaffolds!

@route.get("/")
async def home() -> str:
    return render_template("home.html", title="Welcome")

Configuration

Environment variables use the MYFY_FRONTEND_ prefix:

VariableDefaultDescription
MYFY_FRONTEND_ENVIRONMENTdevelopmentEnvironment mode
MYFY_FRONTEND_ENABLE_VITE_DEVTrueStart Vite dev server
MYFY_FRONTEND_VITE_DEV_SERVERhttp://localhost:3001Vite server URL
MYFY_FRONTEND_STATIC_URL_PREFIX/staticStatic files URL path
MYFY_FRONTEND_CACHE_STATIC_ASSETSTrueEnable static caching
MYFY_FRONTEND_CACHE_MAX_AGE31536000Cache max-age (1 year)
MYFY_FRONTEND_SHOW_VITE_LOGSFalseShow Vite console output

Module Options

FrontendModule(
    templates_dir="frontend/templates",  # Template directory
    static_dir="frontend/static",        # Static files directory
    auto_init=True,                      # Auto-scaffold if missing
)

Auto-Scaffolding

With auto_init=True, FrontendModule creates:

frontend/
  templates/
    base.html           # Base template with Tailwind
    home.html           # Example home page
  static/
    src/
      main.js           # Entry point
      main.css          # Tailwind imports
package.json            # Node dependencies
vite.config.js          # Vite configuration
tailwind.config.js      # Tailwind configuration

Template Rendering

Basic Rendering

from myfy.frontend import render_template

@route.get("/")
async def home() -> str:
    return render_template("home.html", title="Home")

With Context

@route.get("/users/{user_id}")
async def user_profile(user_id: int, session: AsyncSession) -> str:
    user = await session.get(User, user_id)
    return render_template("profile.html", user=user)

With Request Context

from starlette.requests import Request

@route.get("/dashboard")
async def dashboard(request: Request, user: User) -> str:
    return render_template(
        "dashboard.html",
        request=request,  # For url_for, CSRF, etc.
        user=user,
    )

Base Template

<!-- frontend/templates/base.html -->
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}My App{% endblock %}</title>
    {{ vite_assets("src/main.js") }}
</head>
<body class="min-h-screen bg-base-100">
    <div class="navbar bg-base-200">
        <a class="btn btn-ghost text-xl" href="/">My App</a>
    </div>
    <main class="container mx-auto px-4 py-8">
        {% block content %}{% endblock %}
    </main>
</body>
</html>

Page Template

<!-- frontend/templates/home.html -->
{% extends "base.html" %}

{% block title %}{{ title }} - My App{% endblock %}

{% block content %}
<div class="hero min-h-[50vh]">
    <div class="hero-content text-center">
        <div class="max-w-md">
            <h1 class="text-5xl font-bold">Hello, World!</h1>
            <p class="py-6">Welcome to your myfy application.</p>
            <button class="btn btn-primary">Get Started</button>
        </div>
    </div>
</div>
{% endblock %}

DaisyUI Components

DaisyUI 5 provides ready-to-use components:

<!-- Buttons -->
<button class="btn btn-primary">Primary</button>
<button class="btn btn-secondary">Secondary</button>
<button class="btn btn-outline">Outline</button>

<!-- Cards -->
<div class="card bg-base-100 shadow-xl">
    <div class="card-body">
        <h2 class="card-title">Card Title</h2>
        <p>Card content here.</p>
        <div class="card-actions justify-end">
            <button class="btn btn-primary">Action</button>
        </div>
    </div>
</div>

<!-- Forms -->
<div class="form-control">
    <label class="label">
        <span class="label-text">Email</span>
    </label>
    <input type="email" class="input input-bordered" />
</div>

<!-- Alerts -->
<div class="alert alert-success">
    <span>Success! Your action was completed.</span>
</div>

Theme Switching

<!-- Theme toggle -->
<label class="swap swap-rotate">
    <input type="checkbox" class="theme-controller" value="dark" />
    <svg class="swap-on w-6 h-6" fill="currentColor"><!-- sun icon --></svg>
    <svg class="swap-off w-6 h-6" fill="currentColor"><!-- moon icon --></svg>
</label>

Static Assets

Vite Helper

<!-- Loads JS and CSS with HMR in development -->
{{ vite_assets("src/main.js") }}

Manual Asset URLs

<img src="{{ asset_url('images/logo.png') }}" alt="Logo">

Development Workflow

  1. Start the application:

    myfy run
    

    Vite dev server starts automatically with HMR.

  2. Edit templates and CSS - changes reflect instantly.

  3. Build for production:

    npm run build
    

    Creates optimized assets in frontend/static/dist/.

Production Build

# Build assets
npm run build

# Set production mode
export MYFY_FRONTEND_ENVIRONMENT=production
export MYFY_FRONTEND_ENABLE_VITE_DEV=false

# Run application
myfy run

Assets are served from the built manifest with cache headers.

Custom Jinja Filters

from myfy.frontend import FrontendModule
from starlette.templating import Jinja2Templates

# After module initialization
templates: Jinja2Templates = container.get(Jinja2Templates)
templates.env.filters["currency"] = lambda x: f"${x:.2f}"

Use in templates:

<span>{{ price | currency }}</span>

Best Practices

  1. Use auto_init for new projects - Gets you started quickly
  2. Extend base.html - Keep consistent layout
  3. Use DaisyUI components - Pre-styled, accessible
  4. Enable caching in production - Set long cache max-age
  5. Build assets before deploy - Don't rely on Vite in production
  6. Use template inheritance - Keep templates DRY
  7. Pass request for url_for - Enables dynamic URL generation

Module Development in myfy

Modules are the building blocks of myfy applications. Each module follows a protocol with lifecycle hooks.

Available Modules

myfy provides these built-in modules:

ModulePackagePurpose
WebModulemyfy.webHTTP routing, ASGI, FastAPI-like decorators
DataModulemyfy.dataSQLAlchemy async, migrations, sessions
FrontendModulemyfy.frontendJinja2, Tailwind 4, DaisyUI 5, Vite
TasksModulemyfy.tasksBackground jobs, SQL-based task queue
UserModulemyfy.userAuth, OAuth, user management
CliModulemyfy.commandsCustom CLI commands
AuthModulemyfy.web.authType-based authentication, protected routes
RateLimitModulemyfy.web.ratelimitRate limiting per IP or user

Module Protocol

from myfy.core import BaseModule, Container, SINGLETON

class MyModule(BaseModule):
    """Custom module following the Module protocol."""

    def __init__(self):
        super().__init__(name="my-module")

    @property
    def requires(self) -> list[type]:
        """Module types this module depends on."""
        return []  # e.g., [WebModule, DataModule]

    @property
    def provides(self) -> list[type]:
        """Extension protocols this module implements."""
        return []  # e.g., [IWebExtension]

    def configure(self, container: Container) -> None:
        """Phase 1: Register providers in DI container."""
        container.register(
            type_=MyService,
            factory=lambda: MyService(),
            scope=SINGLETON,
        )

    def extend(self, container: Container) -> None:
        """Phase 2: Modify other modules' registrations (optional)."""
        pass

    def finalize(self, container: Container) -> None:
        """Phase 3: Configure singletons after compilation (optional)."""
        # Safe to get singletons here - container is compiled
        service = container.get(MyService)
        service.setup()

    async def start(self) -> None:
        """Phase 4: Start runtime services (connect to DB, etc.)."""
        pass

    async def stop(self) -> None:
        """Phase 5: Cleanup resources gracefully."""
        pass

Lifecycle Phases

  1. Discovery - Application discovers all modules
  2. Dependency Validation - Validates module dependency graph
  3. Configure - Each module registers services in DI
  4. Extend - Modules can modify other modules' registrations
  5. Compile - DI container builds injection plans
  6. Finalize - Modules configure singleton services
  7. Start - Runtime services start (in dependency order)
  8. Stop - Graceful shutdown (reverse order)

Module Dependencies

Declare dependencies via the requires property:

from myfy.web import WebModule
from myfy.data import DataModule

class MyModule(BaseModule):
    @property
    def requires(self) -> list[type]:
        # This module needs WebModule and DataModule to be registered
        return [WebModule, DataModule]

The application validates all required modules are present and initializes them in topological order.

Registering Settings

Modules typically register their own settings:

from myfy.core.config import load_settings
from myfy.core.di.types import ProviderKey

class MyModule(BaseModule):
    def __init__(self, settings: MySettings | None = None):
        super().__init__("my-module")
        self._settings = settings

    def configure(self, container: Container) -> None:
        # Check if settings already registered (avoid double registration)
        key = ProviderKey(MySettings)
        if key not in container._providers:
            if self._settings is None:
                self._settings = load_settings(MySettings)
            container.register(
                type_=MySettings,
                factory=lambda: self._settings,
                scope=SINGLETON,
            )

Extension Protocols

Define extension interfaces using provides:

from myfy.web.extensions import IWebExtension

class MyModule(BaseModule):
    @property
    def provides(self) -> list[type]:
        return [IWebExtension]

    def finalize(self, container: Container) -> None:
        # Access ASGIApp after compilation
        asgi_app = container.get(ASGIApp)
        asgi_app.app.mount("/my-path", MyASGIApp())

Complete Module Example

"""
MyFeature module for myfy.

Provides feature X with Y capabilities.
"""
from __future__ import annotations

import logging
from typing import TYPE_CHECKING

from myfy.core import BaseModule, SINGLETON
from myfy.core.config import load_settings
from myfy.core.di.types import ProviderKey

from .config import MyFeatureSettings
from .service import MyFeatureService

if TYPE_CHECKING:
    from myfy.core.di import Container

logger = logging.getLogger(__name__)


class MyFeatureModule(BaseModule):
    """
    MyFeature module.

    Features:
    - Feature capability 1
    - Feature capability 2
    """

    def __init__(self, settings: MyFeatureSettings | None = None):
        super().__init__("my-feature")
        self._settings = settings

    @property
    def requires(self) -> list[type]:
        return []

    @property
    def provides(self) -> list[type]:
        return []

    def configure(self, container: Container) -> None:
        logger.debug("Configuring MyFeatureModule...")

        # Register settings
        key = ProviderKey(MyFeatureSettings)
        if key not in container._providers:
            if self._settings is None:
                self._settings = load_settings(MyFeatureSettings)
            container.register(
                type_=MyFeatureSettings,
                factory=lambda: self._settings,
                scope=SINGLETON,
            )

        # Register services
        container.register(
            type_=MyFeatureService,
            factory=lambda settings=self._settings: MyFeatureService(settings),
            scope=SINGLETON,
        )

        logger.debug("MyFeatureModule configured")

    async def start(self) -> None:
        logger.info("MyFeature module started")

    async def stop(self) -> None:
        logger.info("MyFeature module stopped")


# Module instance for entry point discovery
my_feature_module = MyFeatureModule()

Best Practices

  1. Always call super().init(name) - Required by BaseModule
  2. Use logging - Add debug/info logs for troubleshooting
  3. Allow settings injection - Accept optional settings in init for testing
  4. Check for existing registrations - Avoid double registration errors
  5. Keep configure() pure - Only register providers, no side effects
  6. Use finalize() for singletons - Safe to resolve singletons here
  7. Make start/stop idempotent - Safe to call multiple times
  8. Include docstrings - Document what the module provides

myfy Framework Patterns

You are assisting a developer building an application with the myfy Python framework.

Core Principles

  1. Opinionated, not rigid - Strong defaults, full configurability
  2. Modular by design - Features are modules (web, data, tasks, frontend)
  3. Type-safe DI - Constructor injection with compile-time validation
  4. Async-native - Built on ASGI and AnyIO with contextvars
  5. Zero-config defaults - Convention over configuration

Imports

Always import from the public API:

# Core
from myfy.core import Application, provider, SINGLETON, REQUEST, TASK
from myfy.core import BaseSettings, BaseModule

# Web
from myfy.web import WebModule, route, Query, abort, errors
from myfy.web import Authenticated, Anonymous, AuthModule
from myfy.web.ratelimit import RateLimitModule, rate_limit

# Data
from myfy.data import DataModule, AsyncSession

# Tasks
from myfy.tasks import TasksModule, task, TaskContext

# Frontend
from myfy.frontend import FrontendModule, render_template

# User
from myfy.user import UserModule

# CLI Commands
from myfy.commands import CliModule, cli

Application Structure

from myfy.core import Application
from myfy.web import WebModule, route
from myfy.data import DataModule

app = Application(
    settings_class=AppSettings,  # Optional custom settings
    auto_discover=False,          # Disable auto-discovery for explicit control
)

# Add modules in dependency order
app.add_module(DataModule())
app.add_module(WebModule())

Module Categories

ModulePackagePurpose
WebModulemyfy-webHTTP routing, ASGI, FastAPI-like decorators
DataModulemyfy-dataSQLAlchemy async, migrations, sessions
FrontendModulemyfy-frontendJinja2, Tailwind 4, DaisyUI 5, Vite
TasksModulemyfy-tasksBackground jobs, SQL-based task queue
UserModulemyfy-userAuth, OAuth, user management
CliModulemyfy-commandsCustom CLI commands
AuthModulemyfy-web.authType-based authentication, protected routes
RateLimitModulemyfy-web.ratelimitRate limiting per IP or user

Key Conventions

  1. File naming: app.py, main.py, or application.py for entry point
  2. Settings: Extend BaseSettings from myfy.core
  3. Routes: Use global route decorator from myfy.web
  4. Providers: Use @provider(scope=...) decorator from myfy.core
  5. Tasks: Use @task decorator for background jobs

Common Patterns

Creating a Route with DI

from myfy.web import route
from myfy.data import AsyncSession

@route.get("/users/{user_id}")
async def get_user(user_id: int, session: AsyncSession) -> dict:
    # session is auto-injected (REQUEST scope)
    result = await session.execute(select(User).where(User.id == user_id))
    return {"user": result.scalar_one_or_none()}

Creating a Provider

from myfy.core import provider, SINGLETON

@provider(scope=SINGLETON)
def email_service(settings: AppSettings) -> EmailService:
    return EmailService(api_key=settings.email_api_key)

Settings Class

from pydantic import Field
from pydantic_settings import SettingsConfigDict
from myfy.core import BaseSettings

class AppSettings(BaseSettings):
    app_name: str = Field(default="my-app")
    debug: bool = Field(default=False)
    database_url: str = Field(default="sqlite+aiosqlite:///./app.db")

    model_config = SettingsConfigDict(
        env_prefix="MYFY_",
        env_file=".env",
    )

Error Handling

from myfy.web import abort, errors

# Quick abort
abort(404, "User not found")

# Typed errors
raise errors.NotFound("User not found")
raise errors.BadRequest("Invalid email", field="email")

When Generating Code

Always:

  • Use type hints for all function parameters and return types
  • Use async/await for all handlers
  • Import from myfy.* not internal modules
  • Follow existing project structure
  • Use Pydantic models for request/response bodies

Web Routing in myfy

myfy provides FastAPI-like routing with full DI integration.

Route Decorators

from myfy.web import route

@route.get("/path")
async def handler() -> dict:
    return {"message": "hello"}

@route.post("/path", status_code=201)
async def create() -> dict:
    return {"created": True}

@route.put("/path/{id}")
async def update(id: int) -> dict:
    return {"updated": id}

@route.delete("/path/{id}", status_code=204)
async def delete(id: int) -> None:
    pass

@route.patch("/path/{id}")
async def partial_update(id: int) -> dict:
    return {"patched": id}

Path Parameters

Extract from URL template using {param}:

@route.get("/users/{user_id}/posts/{post_id}")
async def get_post(user_id: int, post_id: int) -> dict:
    return {"user": user_id, "post": post_id}

Path parameters are:

  • Automatically type-converted based on annotation
  • Must match function parameter names exactly
  • Must be valid Python identifiers

Query Parameters

Use Query for explicit query parameters:

from myfy.web import Query

@route.get("/search")
async def search(
    q: str = Query(default=""),           # With default value
    limit: int = Query(default=10),       # Integer query param
    page: int = Query(alias="p"),         # Aliased (?p=1 in URL)
) -> dict:
    return {"query": q, "limit": limit, "page": page}

Request Body

Use Pydantic models or dataclasses for request bodies:

from pydantic import BaseModel

class UserCreate(BaseModel):
    email: str
    name: str

@route.post("/users", status_code=201)
async def create_user(body: UserCreate, session: AsyncSession) -> dict:
    user = User(**body.model_dump())
    session.add(user)
    await session.commit()
    return {"id": user.id}

Request bodies are automatically:

  • Parsed from JSON
  • Validated by Pydantic
  • Type-checked at runtime

Parameter Classification

Parameters are classified in this order:

  1. Path parameters - Names matching {param} in route path
  2. Query parameters - Annotated with Query(...)
  3. Body parameter - Pydantic model, dataclass, or dict
  4. DI dependencies - Everything else (resolved from container)
@route.post("/users/{user_id}/orders")
async def create_order(
    user_id: int,                    # 1. Path param (matches {user_id})
    limit: int = Query(default=10),  # 2. Query param (explicit Query)
    body: OrderCreate,               # 3. Request body (Pydantic model)
    session: AsyncSession,           # 4. DI dependency
    settings: AppSettings,           # 4. DI dependency
) -> dict:
    ...

Authentication

Use Authenticated for protected routes:

from myfy.web import Authenticated, AuthModule
from dataclasses import dataclass

@dataclass
class User(Authenticated):
    email: str

# Register auth provider
def my_auth(request: Request) -> User | None:
    token = request.headers.get("Authorization")
    if not token:
        return None  # Results in 401
    return User(id="123", email="user@example.com")

app.add_module(AuthModule(authenticated_provider=my_auth))

# Protected route - returns 401 if not authenticated
@route.get("/profile")
async def profile(user: User) -> dict:
    return {"id": user.id, "email": user.email}

Error Handling

Quick Errors with abort()

from myfy.web import abort

@route.get("/users/{user_id}")
async def get_user(user_id: int, session: AsyncSession) -> dict:
    user = await session.get(User, user_id)
    if not user:
        abort(404, "User not found")
    return {"user": user}

Typed Errors

from myfy.web import errors

raise errors.NotFound("User not found")
raise errors.BadRequest("Invalid email", field="email")
raise errors.Unauthorized("Invalid token")
raise errors.Forbidden("Access denied")
raise errors.Conflict("Email already exists")

Custom Exceptions

from myfy.web.exceptions import WebError

class RateLimitExceeded(WebError):
    status_code = 429
    error_type = "rate_limit_exceeded"

Rate Limiting

from myfy.web.ratelimit import RateLimitModule, rate_limit, RateLimitKey

# Add module
app.add_module(RateLimitModule())

# Rate limit by IP (default)
@route.get("/api/data")
@rate_limit(100)  # 100 requests per minute per IP
async def get_data() -> dict:
    ...

# Rate limit by authenticated user
@route.get("/api/profile")
@rate_limit(50, key=RateLimitKey.USER)
async def get_profile(user: User) -> dict:
    ...

Response Types

Routes can return:

# Dict (serialized to JSON)
@route.get("/json")
async def json_response() -> dict:
    return {"key": "value"}

# Pydantic model (serialized to JSON)
@route.get("/model")
async def model_response() -> UserResponse:
    return UserResponse(id=1, name="John")

# None for 204 No Content
@route.delete("/users/{id}", status_code=204)
async def delete_user(id: int) -> None:
    ...

Best Practices

  1. Always use async - All handlers should be async functions
  2. Type all parameters - Use type hints for auto-classification
  3. Use Pydantic for bodies - Get free validation
  4. Return typed responses - Prefer Pydantic models over dicts
  5. Use appropriate status codes - 201 for creation, 204 for deletion
  6. Handle errors explicitly - Use abort() or typed errors
  7. Document with docstrings - Add OpenAPI-compatible docs

TasksModule - Background Jobs

TasksModule provides SQL-based async task processing with DI injection and automatic retries.

Quick Start

from myfy.core import Application
from myfy.data import DataModule
from myfy.tasks import TasksModule, task

app = Application()
app.add_module(DataModule())
app.add_module(TasksModule(auto_create_tables=True))

# Define a task
@task
async def send_email(to: str, subject: str, body: str) -> None:
    await email_service.send(to, subject, body)

# Dispatch from a route
@route.post("/notifications")
async def notify_user(body: NotifyRequest) -> dict:
    task_id = await send_email.send(
        to=body.email,
        subject="Welcome!",
        body="Thanks for signing up.",
    )
    return {"task_id": task_id}

Configuration

Environment variables use the MYFY_TASKS_ prefix:

VariableDefaultDescription
MYFY_TASKS_DEFAULT_MAX_RETRIES3Default retry attempts
MYFY_TASKS_RETRY_DELAY_SECONDS60.0Seconds between retries
MYFY_TASKS_WORKER_CONCURRENCY4Concurrent tasks per worker
MYFY_TASKS_POLL_INTERVAL1.0Seconds between queue polls
MYFY_TASKS_TASK_TIMEOUT300.0Max seconds per task

Defining Tasks

Basic Task

from myfy.tasks import task

@task
async def process_order(order_id: int) -> str:
    # Process the order
    return f"Processed order {order_id}"

Task with DI Injection

Services are automatically injected at runtime:

from myfy.tasks import task
from myfy.data import AsyncSession

@task
async def sync_user_data(user_id: int, session: AsyncSession) -> None:
    # session is TASK-scoped (injected per task execution)
    user = await session.get(User, user_id)
    await sync_to_external_service(user)

Task with Custom Options

@task(max_retries=5, retry_on=[ConnectionError, TimeoutError])
async def upload_file(file_path: str) -> str:
    # Retries up to 5 times on connection/timeout errors
    return await s3.upload(file_path)

Dispatching Tasks

Basic Dispatch

# Returns immediately with task_id
task_id = await send_email.send(to="user@example.com", subject="Hi")

Dispatch Options

task_id = await send_email.send(
    to="user@example.com",
    subject="Hi",
    _priority=10,      # Higher priority = executes first
    _delay=60,         # Wait 60 seconds before executing
    _max_retries=5,    # Override default retries
)

Getting Results

result = await send_email.get_result(task_id, timeout=60)

if result.is_completed:
    print(f"Success: {result.value}")
elif result.is_failed:
    print(f"Error: {result.error}")
elif result.is_pending:
    print("Still processing...")

TaskContext for Progress

Report progress from long-running tasks:

from myfy.tasks import task, TaskContext

@task
async def import_users(file_path: str, ctx: TaskContext) -> int:
    users = load_users_from_file(file_path)
    total = len(users)

    for i, user in enumerate(users):
        await create_user(user)
        await ctx.update_progress(
            current=i + 1,
            total=total,
            message=f"Importing user {i + 1}/{total}",
        )

    return total

Check progress from caller:

result = await import_users.get_result(task_id)
if result.progress:
    current, total = result.progress
    print(f"Progress: {current}/{total} - {result.progress_message}")

Running Workers

Start a worker process:

myfy tasks worker

With options:

myfy tasks worker --concurrency 8 --poll-interval 0.5

Workers:

  • Poll the database for pending tasks
  • Execute tasks with full DI injection
  • Handle retries automatically
  • Report progress and results
  • Gracefully shutdown on SIGTERM

Task States

StatusDescription
pendingQueued, waiting for worker
runningBeing executed by worker
completedFinished successfully
failedFailed after all retries
cancelledManually cancelled

Error Handling

Tasks automatically retry on failure:

@task(max_retries=3, retry_on=[APIError])
async def call_api(url: str) -> dict:
    response = await http.get(url)
    if response.status >= 500:
        raise APIError("Server error")  # Will retry
    return response.json()

After all retries fail:

  • Task status becomes failed
  • Error message and traceback are stored
  • Can be retrieved via get_result()

Parameter Classification

TypeBehavior
Primitives (str, int, float, bool)Serialized as task args
Lists, dictsSerialized as task args
TaskContextInjected by worker
Services (other types)DI injected at runtime
@task
async def complex_task(
    order_id: int,           # Serialized (primitive)
    items: list[str],        # Serialized (list)
    ctx: TaskContext,        # Injected (context)
    session: AsyncSession,   # DI injected (service)
    settings: AppSettings,   # DI injected (service)
) -> None:
    ...

Best Practices

  1. Keep tasks idempotent - Safe to retry on failure
  2. Serialize only primitives - Complex objects should be loaded in task
  3. Use TaskContext - Report progress for long tasks
  4. Set appropriate timeouts - Prevent zombie tasks
  5. Monitor worker logs - Watch for repeated failures
  6. Use priorities - Critical tasks get processed first
  7. Handle cleanup - TaskContext supports cleanup callbacks

UserModule - User Authentication

UserModule provides complete user authentication with email/password, OAuth, sessions, and JWT tokens.

Quick Start

from myfy.core import Application
from myfy.data import DataModule
from myfy.web import WebModule
from myfy.web.auth import AuthModule
from myfy.user import UserModule, BaseUser
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import String

# Extend BaseUser with custom fields
class User(BaseUser):
    __tablename__ = "users"
    phone: Mapped[str | None] = mapped_column(String(20))

# Create module
user_module = UserModule(
    user_model=User,
    oauth_providers=["google", "github"],
    auto_create_tables=True,
)

# Set up application
app = Application()
app.add_module(DataModule())
app.add_module(WebModule())
app.add_module(AuthModule(
    authenticated_provider=user_module.get_authenticated_provider(),
))
app.add_module(user_module)

Configuration

Environment variables use the MYFY_USER_ prefix:

VariableDefaultDescription
MYFY_USER_SECRET_KEY(auto-generated)Secret for JWT/sessions
MYFY_USER_SESSION_LIFETIME604800Session duration (7 days, in seconds)
MYFY_USER_JWT_ALGORITHMHS256JWT signing algorithm
MYFY_USER_JWT_ACCESS_TOKEN_LIFETIME3600JWT access token lifetime
MYFY_USER_PASSWORD_MIN_LENGTH8Minimum password length
MYFY_USER_REQUIRE_EMAIL_VERIFICATIONTrueRequire email verification

OAuth Configuration

# Google OAuth
MYFY_USER_OAUTH_GOOGLE_CLIENT_ID=your-client-id
MYFY_USER_OAUTH_GOOGLE_CLIENT_SECRET=your-secret

# GitHub OAuth
MYFY_USER_OAUTH_GITHUB_CLIENT_ID=your-client-id
MYFY_USER_OAUTH_GITHUB_CLIENT_SECRET=your-secret

Module Options

UserModule(
    user_model=User,              # Custom user model (must extend BaseUser)
    oauth_providers=["google"],   # OAuth providers to enable
    auto_create_tables=True,      # Create tables on start
    enable_routes=True,           # Register auth routes
    enable_templates=True,        # Provide Jinja2 templates
)

Custom User Model

from myfy.user import BaseUser
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import String, Boolean

class User(BaseUser):
    __tablename__ = "users"

    # Custom fields
    phone: Mapped[str | None] = mapped_column(String(20))
    is_admin: Mapped[bool] = mapped_column(Boolean, default=False)
    company_id: Mapped[int | None] = mapped_column(ForeignKey("companies.id"))

    # Relationships
    company: Mapped["Company"] = relationship(back_populates="users")

BaseUser provides:

  • id: Primary key
  • email: Unique email address
  • password_hash: Hashed password
  • is_active: Account active status
  • is_verified: Email verified status
  • created_at, updated_at: Timestamps

Protected Routes

from myfy.web import route, Authenticated

@route.get("/profile")
async def profile(user: User) -> dict:
    # user is injected if authenticated
    # Returns 401 if not authenticated
    return {"email": user.email, "name": user.name}

@route.get("/admin")
async def admin_dashboard(user: User) -> dict:
    if not user.is_admin:
        abort(403, "Admin access required")
    return {"message": "Welcome, admin"}

Auth Routes

UserModule registers these routes by default:

RouteMethodDescription
/auth/loginGET/POSTLogin page and handler
/auth/logoutPOSTLogout (clear session)
/auth/registerGET/POSTRegistration page and handler
/auth/forgot-passwordGET/POSTPassword reset request
/auth/reset-passwordGET/POSTPassword reset form
/auth/verify-emailGETEmail verification link
/auth/googleGETGoogle OAuth start
/auth/google/callbackGETGoogle OAuth callback
/auth/githubGETGitHub OAuth start
/auth/github/callbackGETGitHub OAuth callback

Using UserService

from myfy.user import UserService

@route.post("/users")
async def create_user(body: CreateUserRequest, user_service: UserService) -> dict:
    user = await user_service.create(
        email=body.email,
        password=body.password,
    )
    return {"id": user.id}

@route.get("/users/{user_id}")
async def get_user(user_id: int, user_service: UserService) -> dict:
    user = await user_service.get_by_id(user_id)
    if not user:
        abort(404, "User not found")
    return {"email": user.email}

Session vs JWT

Session-Based (Web)

Default for web routes. Session ID stored in cookie.

@route.get("/dashboard")
async def dashboard(user: User) -> str:
    # Session cookie auto-validated
    return render_template("dashboard.html", user=user)

JWT-Based (API)

For API clients, use JWT tokens.

from myfy.user import JWTService

@route.post("/api/login")
async def api_login(body: LoginRequest, jwt_service: JWTService, user_service: UserService) -> dict:
    user = await user_service.authenticate(body.email, body.password)
    if not user:
        abort(401, "Invalid credentials")
    token = jwt_service.create_token(user)
    return {"token": token}

Client sends token in header:

Authorization: Bearer <token>

OAuth Integration

Google OAuth

user_module = UserModule(
    user_model=User,
    oauth_providers=["google"],
)

Login link:

<a href="/auth/google" class="btn">Login with Google</a>

GitHub OAuth

user_module = UserModule(
    user_model=User,
    oauth_providers=["github"],
)

Login link:

<a href="/auth/github" class="btn">Login with GitHub</a>

Email Verification

Enable verification:

MYFY_USER_REQUIRE_EMAIL_VERIFICATION=true

Users must verify email before full access. Verification link sent on registration.

Password Reset

  1. User requests reset at /auth/forgot-password
  2. Reset email sent with secure token
  3. User clicks link to /auth/reset-password?token=...
  4. User enters new password

Custom Templates

Override default templates by placing files in your templates directory:

frontend/templates/auth/
  login.html
  register.html
  forgot-password.html
  reset-password.html
  verify-email.html

Best Practices

  1. Set a strong SECRET_KEY - Use a long random string
  2. Enable email verification - For production apps
  3. Use OAuth where possible - Reduces password management burden
  4. Extend BaseUser - Don't modify it directly
  5. Use sessions for web, JWT for API - Different use cases
  6. Hash passwords - UserService handles this automatically
  7. Rate limit auth routes - Prevent brute force attacks

Commands 2

myfy Check Command

Validate the myfy application configuration and run health checks.

Process

  1. Run myfy doctor
uv run myfy doctor

This checks:

  • Application can be discovered and loaded
  • All modules are properly configured
  • DI container compiles successfully
  • Settings are valid
  1. Run linting
uv run ruff check .
  1. Run type checking (if ty is available)
uv run ty check .
  1. Run tests
uv run pytest
  1. Report results

Summarize:

  • Doctor check: PASS/FAIL
  • Linting: PASS/FAIL (with issue count)
  • Type checking: PASS/FAIL
  • Tests: PASS/FAIL (with test count)

If any checks fail, provide guidance on how to fix the issues.

Quick Mode

If the user just wants a quick check:

uv run myfy doctor && uv run ruff check . && uv run pytest -x

Arguments

  • --quick - Only run myfy doctor
  • --fix - Auto-fix linting issues with ruff check --fix
  • --verbose - Show detailed output

myfy Scaffolding Wizard

Help the user create myfy components interactively.

Process

  1. Ask what to scaffold

Present these options to the user:

  • Module - Create a new myfy module with settings and service
  • Route - Create a new route handler with DI
  • Provider - Create a DI provider with correct scope
  • Task - Create a background task
  • Settings - Create a settings class
  • Full Feature - Create module + routes + providers + tasks for a complete feature
  1. For each choice, gather requirements

Module

  • Module name (e.g., "notifications", "payments")
  • Dependencies (WebModule, DataModule, etc.)
  • What services it provides
  • Description

Route

  • HTTP method (GET, POST, PUT, DELETE, PATCH)
  • Path (e.g., "/users/{user_id}")
  • Request body model (for POST/PUT/PATCH)
  • Required DI dependencies
  • Authentication required?

Provider

  • Service type being provided
  • Scope (SINGLETON, REQUEST, TASK)
  • Dependencies it needs
  • Purpose

Task

  • Task name and purpose
  • Parameters
  • Progress reporting needed?
  • Retry behavior

Settings

  • Setting fields and types
  • Default values
  • Environment prefix
  • Validation rules

Full Feature

  • Feature name (e.g., "notifications")
  • Then gather requirements for all components
  1. Generate the code

Use the appropriate scaffolding patterns from the myfy plugin agents.

  1. Show the user what was created

List all created files and provide usage examples.

Example Interaction

User: /myfy:scaffold

Agents 5

Module Scaffolding Agent

You are an expert at creating myfy modules. Guide the user through creating a new module.

Process

  1. Gather Requirements

    • Module name (e.g., "notifications", "caching", "analytics")
    • Module dependencies (WebModule, DataModule, etc.)
    • Services it should provide
    • Whether it needs settings
  2. Generate Files

Module File ({module_name}/module.py)

"""
{ModuleName} module for myfy.

{Description}
"""
from __future__ import annotations

import logging
from typing import TYPE_CHECKING

from myfy.core import BaseModule, SINGLETON
from myfy.core.config import load_settings
from myfy.core.di.types import ProviderKey

from .config import {ModuleName}Settings
from .service import {ModuleName}Service

if TYPE_CHECKING:
    from myfy.core.di import Container

logger = logging.getLogger(__name__)


class {ModuleName}Module(BaseModule):
    """
    {ModuleName} module.

    Features:
    - {Feature 1}
    - {Feature 2}
    """

    def __init__(
        self,
        settings: {ModuleName}Settings | None = None,
    ) -> None:
        super().__init__("{module-name}")
        self._settings = settings

    @property
    def requires(self) -> list[type]:
        return [{RequiredModules}]

    @property
    def provides(self) -> list[type]:
        return []

    def configure(self, container: Container) -> None:
        """Register services in DI container."""
        logger.debug(f"Configuring {ModuleName}Module...")

        # Register settings
        key = ProviderKey({ModuleName}Settings)
        if key not in container._providers:
            if self._settings is None:
                self._settings = load_settings({ModuleName}Settings)
            container.register(
                type_={ModuleName}Settings,
                factory=lambda: self._settings,
                scope=SINGLETON,
            )

        # Register services
        container.register(
            type_={ModuleName}Service,
            factory=lambda settings=self._settings: {ModuleName}Service(settings),
            scope=SINGLETON,
        )

        logger.debug(f"{ModuleName}Module configured")

    async def start(self) -> None:
        """Start runtime services."""
        logger.info("{ModuleName} module started")

    async def stop(self) -> None:
        """Stop and cleanup."""
        logger.info("{ModuleName} module stopped")

    def __repr__(self) -> str:
        return f"{ModuleName}Module()"


# Module instance for entry point
{module_name}_module = {ModuleName}Module()

Settings File ({module_name}/config.py)

"""Settings for {ModuleName} module."""
from pydantic import Field
from pydantic_settings import SettingsConfigDict

from myfy.core import BaseSettings


class {ModuleName}Settings(BaseSettings):
    """{ModuleName} configuration."""

    enabled: bool = Field(default=True, description="Enable {module_name}")
    # Add your settings here

    model_config = SettingsConfigDict(
        env_prefix="MYFY_{MODULE_NAME}_",
        env_file=".env",
    )

Service File ({module_name}/service.py)

"""Service for {ModuleName} module."""
from .config import {ModuleName}Settings


class {ModuleName}Service:
    """{ModuleName} service."""

    def __init__(self, settings: {ModuleName}Settings) -> None:
        self._settings = settings

    # Add your methods here

Init File ({module_name}/__init__.py)

"""{ModuleName} module for myfy."""
from .config import {ModuleName}Settings
from .module import {ModuleName}Module, {module_name}_module
from .service import {ModuleName}Service

__all__ = [
    "{ModuleName}Module",
    "{ModuleName}Service",
    "{ModuleName}Settings",
    "{module_name}_module",
]
  1. Provide Usage Example
from myfy.core import Application
from {module_name} import {ModuleName}Module

app = Application()
app.add_module({ModuleName}Module())

Naming Conventions

  • Module class: {ModuleName}Module (PascalCase + "Module")
  • Settings class: {ModuleName}Settings (PascalCase + "Settings")
  • Module instance: {module_name}_module (snake_case + "_module")
  • Package name: {module_name} (snake_case)
  • Env prefix: MYFY_{MODULE_NAME}_ (uppercase with underscore)

Guidelines

  • Always use type hints
  • Include logging for debugging
  • Support settings injection for testing
  • Check for existing registrations to avoid duplicates
  • Make start/stop idempotent

Provider Scaffolding Agent

You help create myfy DI providers with correct scope selection.

Scope Selection Guide

ScopeWhen to UseExamples
SINGLETONShared, stateless, expensive to createConfig, pools, HTTP clients, caches
REQUESTPer-request state, database sessionsDB sessions, user context, request logger
TASKPer-background-job stateTask logger, job-specific clients

Process

  1. Determine Scope

    • Does it hold request-specific state? -> REQUEST
    • Is it shared across all requests? -> SINGLETON
    • Is it for background tasks? -> TASK
  2. Generate Provider

SINGLETON Provider

from myfy.core import provider, SINGLETON

@provider(scope=SINGLETON)
def email_service(settings: AppSettings) -> EmailService:
    """
    Create email service singleton.

    This is created once at startup and shared across all requests.
    """
    return EmailService(
        api_key=settings.email_api_key,
        from_address=settings.email_from,
    )

REQUEST Provider

from myfy.core import provider, REQUEST
from myfy.data import AsyncSession

@provider(scope=REQUEST)
def user_repository(session: AsyncSession) -> UserRepository:
    """
    Create user repository for this request.

    Created per-request, uses the request-scoped session.
    Automatically cleaned up after request completes.
    """
    return UserRepository(session)

TASK Provider

from myfy.core import provider, TASK
from myfy.tasks import TaskContext

@provider(scope=TASK)
def task_notifier(ctx: TaskContext, settings: AppSettings) -> TaskNotifier:
    """
    Create notifier for this background task.

    Created per-task execution, has access to task context.
    """
    return TaskNotifier(task_id=ctx.task_id, webhook_url=settings.webhook_url)

Common Patterns

Factory Pattern (for REQUEST-scoped from SINGLETON)

When you need REQUEST-scoped instances but the configuration is SINGLETON:

# Singleton factory holds configuration
@provider(scope=SINGLETON)
def service_factory(settings: AppSettings) -> ServiceFactory:
    """Singleton factory for creating request-scoped services."""
    return ServiceFactory(settings)

# Request-scoped instances created by factory
@provider(scope=REQUEST)
def my_service(factory: ServiceFactory, session: AsyncSession) -> MyService:
    """Create service instance for this request."""
    return factory.create(session)

HTTP Client

import httpx

@provider(scope=SINGLETON)
def http_client(settings: AppSettings) -> httpx.AsyncClient:
    """
    Shared HTTP client with connection pooling.

    Use SINGLETON to reuse connections across requests.
    """
    return httpx.AsyncClient(
        timeout=settings.http_timeout,
        headers={"User-Agent": settings.app_name},
    )

Cache Service

@provider(scope=SINGLETON)
def cache_service(settings: CacheSettings) -> CacheService:
    """Application-wide cache."""
    if settings.redis_url:
        return RedisCacheService(settings.redis_url)
    return InMemoryCacheService()

Repository Pattern

@provider(scope=REQUEST)
def user_repository(session: AsyncSession) -> UserRepository:
    """User repository for database operations."""
    return UserRepository(session)

@provider(scope=REQUEST)
def order_repository(session: AsyncSession) -> OrderRepository:
    """Order repository for database operations."""
    return OrderRepository(session)

With Qualifiers

from myfy.core import provider, SINGLETON, Qualifier
from typing import Annotated

@provider(scope=SINGLETON, qualifier="primary")
def primary_database(settings: Settings) -> Database:
    """Primary database for writes."""
    return Database(settings.primary_db_url)

@provider(scope=SINGLETON, qualifier="replica")
def replica_database(settings: Settings) -> Database:
    """Replica database for reads."""
    return Database(settings.replica_db_url)

# Usage in routes
@route.get("/users")
async def list_users(
    db: Annotated[Database, Qualifier("replica")]
) -> list[dict]:
    return await db.fetch_all("SELECT * FROM users")

Scope Rules

  1. SINGLETON can only depend on other SINGLETON providers
  2. REQUEST can depend on SINGLETON or REQUEST providers
  3. TASK can depend on SINGLETON or TASK providers

Invalid (will fail at startup):

@provider(scope=SINGLETON)
def bad_service(session: AsyncSession):  # AsyncSession is REQUEST!
    return MyService(session)

Guidelines

  • Return type annotation is required
  • Use descriptive docstrings
  • Keep provider functions pure (no side effects)
  • SINGLETON providers should be thread-safe
  • REQUEST/TASK providers can hold state

Route Scaffolding Agent

You help create myfy route handlers with proper DI injection.

Process

  1. Gather Requirements

    • HTTP method (GET, POST, PUT, DELETE, PATCH)
    • Path with parameters (e.g., /users/{user_id})
    • Required DI dependencies (AsyncSession, services, etc.)
    • Request body model (for POST/PUT/PATCH)
    • Response structure
    • Authentication requirements
  2. Generate Route

Basic Route Template

from myfy.web import route, Query, errors

@route.{method}("/{path}", status_code={status_code})
async def {handler_name}(
    # Path parameters first
    {path_param}: int,
    # Query parameters
    limit: int = Query(default=10),
    # Request body (POST/PUT/PATCH)
    body: {RequestModel},
    # DI dependencies
    session: AsyncSession,
    service: MyService,
) -> {ReturnType}:
    """
    {Description}

    Args:
        {path_param}: {param description}
        body: Request body
        session: Database session

    Returns:
        {return description}

    Raises:
        errors.NotFound: If resource not found
    """
    # Implementation
    result = await service.do_something(body)

    if not result:
        raise errors.NotFound("Resource not found")

    return {"id": result.id}

CRUD Patterns

List (GET collection)

@route.get("/resources")
async def list_resources(
    limit: int = Query(default=10),
    offset: int = Query(default=0),
    session: AsyncSession,
) -> dict:
    """List resources with pagination."""
    query = select(Resource).limit(limit).offset(offset)
    result = await session.execute(query)
    resources = result.scalars().all()
    return {"items": [r.to_dict() for r in resources], "count": len(resources)}

Get (GET single)

@route.get("/resources/{id}")
async def get_resource(id: int, session: AsyncSession) -> dict:
    """Get a single resource by ID."""
    resource = await session.get(Resource, id)
    if not resource:
        raise errors.NotFound("Resource not found")
    return resource.to_dict()

Create (POST)

from pydantic import BaseModel

class ResourceCreate(BaseModel):
    name: str
    description: str | None = None

@route.post("/resources", status_code=201)
async def create_resource(body: ResourceCreate, session: AsyncSession) -> dict:
    """Create a new resource."""
    resource = Resource(**body.model_dump())
    session.add(resource)
    await session.commit()
    await session.refresh(resource)
    return {"id": resource.id, "name": resource.name}

Update (PUT)

class ResourceUpdate(BaseModel):
    name: str
    description: str | None = None

@route.put("/resources/{id}")
async def update_resource(
    id: int,
    body: ResourceUpdate,
    session: AsyncSession,
) -> dict:
    """Update a resource."""
    resource = await session.get(Resource, id)
    if not resource:
        raise errors.NotFound("Resource not found")

    for key, value in body.model_dump().items():
        setattr(resource, key, value)

    await session.commit()
    return resource.to_dict()

Delete (DELETE)

@route.delete("/resources/{id}", status_code=204)
async def delete_resource(id: int, session: AsyncSession) -> None:
    """Delete a resource."""
    resource = await session.get(Resource, id)
    if not resource:
        raise errors.NotFound("Resource not found")

    await session.delete(resource)
    await session.commit()

Authenticated Routes

from myfy.web import Authenticated
from dataclasses import dataclass

@dataclass
class User(Authenticated):
    email: str

@route.get("/me")
async def get_current_user(user: User) -> dict:
    """Get current authenticated user."""
    return {"id": user.id, "email": user.email}

@route.get("/my/resources")
async def get_my_resources(user: User, session: AsyncSession) -> dict:
    """Get resources owned by current user."""
    query = select(Resource).where(Resource.owner_id == user.id)
    result = await session.execute(query)
    return {"items": [r.to_dict() for r in result.scalars().all()]}

Guidelines

  • Always use async handlers
  • Type all parameters
  • Use Pydantic models for request bodies
  • Return dicts or Pydantic models
  • Use appropriate status codes (201 for creation, 204 for deletion)
  • Handle errors explicitly with errors.NotFound, errors.BadRequest, etc.
  • Add docstrings for documentation

Settings Scaffolding Agent

You help create myfy settings classes with proper validation.

Process

  1. Gather Requirements

    • Setting fields and their types
    • Default values
    • Environment variable prefix
    • Validation rules
  2. Generate Settings

Basic Settings

from pydantic import Field
from pydantic_settings import SettingsConfigDict

from myfy.core import BaseSettings


class AppSettings(BaseSettings):
    """
    Application settings.

    All settings can be configured via environment variables
    with the MYFY_ prefix.
    """

    # Application info
    app_name: str = Field(
        default="my-app",
        description="Application name",
    )

    debug: bool = Field(
        default=False,
        description="Enable debug mode",
    )

    # API configuration
    api_key: str = Field(
        description="API key for external service",
    )

    api_timeout: int = Field(
        default=30,
        ge=1,
        le=300,
        description="API timeout in seconds",
    )

    # Database
    database_url: str = Field(
        default="sqlite+aiosqlite:///./app.db",
        description="Database connection URL",
    )

    model_config = SettingsConfigDict(
        env_prefix="MYFY_",
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
    )

Module Settings

Settings for a specific module:

class EmailSettings(BaseSettings):
    """Email service configuration."""

    provider: str = Field(
        default="smtp",
        description="Email provider (smtp, sendgrid, ses)",
    )

    smtp_host: str | None = Field(
        default=None,
        description="SMTP host",
    )

    smtp_port: int = Field(
        default=587,
        ge=1,
        le=65535,
        description="SMTP port",
    )

    api_key: str | None = Field(
        default=None,
        description="API key for email service",
    )

    from_address: str = Field(
        description="Default from address",
    )

    model_config = SettingsConfigDict(
        env_prefix="MYFY_EMAIL_",
        env_file=".env",
    )

Settings with Validation

from pydantic import Field, field_validator, model_validator


class DatabaseSettings(BaseSettings):
    """Database configuration with validation."""

    url: str = Field(
        default="sqlite+aiosqlite:///./app.db",
        description="Database URL",
    )

    pool_size: int = Field(
        default=5,
        ge=1,
        le=100,
        description="Connection pool size",
    )

    echo: bool = Field(
        default=False,
        description="Echo SQL queries",
    )

    @field_validator("url")
    @classmethod
    def validate_url(cls, v: str) -> str:
        """Validate database URL format."""
        if not v.startswith(("sqlite", "postgresql", "mysql")):
            raise ValueError("Invalid database URL scheme")
        return v

    model_config = SettingsConfigDict(
        env_prefix="MYFY_DATABASE_",
    )

Settings with Cross-Field Validation

from pydantic import model_validator
from typing import Literal


class AuthSettings(BaseSettings):
    """Authentication settings with cross-field validation."""

    provider: Literal["jwt", "session", "oauth"] = Field(
        default="session",
        description="Auth provider type",
    )

    jwt_secret: str | None = Field(
        default=None,
        description="JWT secret key",
    )

    session_secret: str | None = Field(
        default=None,
        description="Session secret key",
    )

    oauth_client_id: str | None = Field(
        default=None,
        description="OAuth client ID",
    )

    @model_validator(mode="after")
    def validate_provider_config(self) -> "AuthSettings":
        """Validate that required fields are set for chosen provider."""
        if self.provider == "jwt" and not self.jwt_secret:
            raise ValueError("jwt_secret required when provider=jwt")
        if self.provider == "session" and not self.session_secret:
            raise ValueError("session_secret required when provider=session")
        if self.provider == "oauth" and not self.oauth_client_id:
            raise ValueError("oauth_client_id required when provider=oauth")
        return self

    model_config = SettingsConfigDict(
        env_prefix="MYFY_AUTH_",
    )

Nested Settings

class AppSettings(BaseSettings):
    """Main application settings with nested module settings."""

    app_name: str = Field(default="my-app")
    debug: bool = Field(default=False)

    # Nested settings (auto-loaded from environment)
    database: DatabaseSettings = Field(default_factory=DatabaseSettings)
    email: EmailSettings = Field(default_factory=EmailSettings)

    model_config = SettingsConfigDict(
        env_prefix="MYFY_",
        env_file=".env",
    )

Usage

In Application

from myfy.core import Application

app = Application(settings_class=AppSettings)
# Settings are automatically loaded and registered in DI

In Routes/Providers

@route.get("/config")
async def get_config(settings: AppSettings) -> dict:
    # model_dump_safe() redacts sensitive fields
    return settings.model_dump_safe()

@provider(scope=SINGLETON)
def email_service(settings: EmailSettings) -> EmailService:
    return EmailService(settings)

Environment Variables

# .env file
MYFY_APP_NAME=my-production-app
MYFY_DEBUG=false
MYFY_API_KEY=secret-key-here

# Nested settings use their own prefix
MYFY_DATABASE_URL=postgresql+asyncpg://user:pass@localhost/db
MYFY_DATABASE_POOL_SIZE=10
MYFY_EMAIL_PROVIDER=sendgrid
MYFY_EMAIL_API_KEY=sg-api-key

Field Options

OptionDescription
defaultDefault value
default_factoryFactory for mutable defaults
descriptionField description
ge, gtGreater than or equal, greater than
le, ltLess than or equal, less than
min_length, max_lengthString length constraints
patternRegex pattern for validation

Guidelines

  • Use descriptive description for each field
  • Set sensible defaults for optional fields
  • Use Field() for all fields with options
  • Add validation for complex requirements
  • Use model_dump_safe() to avoid exposing secrets
  • Keep env prefixes consistent (MYFY_{MODULE}_)

Task Scaffolding Agent

You help create myfy background tasks.

Process

  1. Gather Requirements

    • Task name and purpose
    • Input parameters
    • Progress reporting needs
    • Retry behavior
    • Return value
  2. Generate Task

Basic Task

from myfy.tasks import task

@task
async def send_welcome_email(user_id: int, email: str) -> None:
    """
    Send welcome email to new user.

    Args:
        user_id: The user's ID
        email: The user's email address
    """
    await email_service.send(
        to=email,
        template="welcome",
        context={"user_id": user_id},
    )

Task with Progress Reporting

from myfy.tasks import task, TaskContext

@task
async def process_batch(items: list[str], ctx: TaskContext) -> int:
    """
    Process a batch of items with progress reporting.

    Args:
        items: List of items to process
        ctx: Task context for progress updates

    Returns:
        Number of successfully processed items
    """
    processed = 0

    for i, item in enumerate(items):
        # Check for cancellation
        if ctx.is_cancelled:
            return processed

        # Process item
        await process_item(item)
        processed += 1

        # Report progress
        await ctx.update_progress(
            current=i + 1,
            total=len(items),
            message=f"Processing {item}",
        )

    return processed

Task with Retry Configuration

@task(max_retries=5, retry_on=[ConnectionError, TimeoutError])
async def fetch_external_data(url: str) -> dict:
    """
    Fetch data from external API with retry support.

    Automatically retries up to 5 times on connection errors.

    Args:
        url: The URL to fetch

    Returns:
        The fetched data as dict
    """
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        response.raise_for_status()
        return response.json()

Task with Custom Name

@task(name="emails.send_bulk")
async def send_bulk_emails(
    recipients: list[str],
    subject: str,
    body: str,
    ctx: TaskContext,
) -> dict:
    """
    Send emails to multiple recipients.

    Custom name allows better organization in task monitoring.
    """
    sent = 0
    failed = 0

    for i, email in enumerate(recipients):
        try:
            await send_email(email, subject, body)
            sent += 1
        except Exception:
            failed += 1

        await ctx.update_progress(
            current=i + 1,
            total=len(recipients),
        )

    return {"sent": sent, "failed": failed}

Task with DI Dependencies

Tasks support dependency injection using the TASK scope:

from myfy.core import provider, TASK
from myfy.tasks import task, TaskContext

@provider(scope=TASK)
def task_logger(ctx: TaskContext) -> TaskLogger:
    return TaskLogger(task_id=ctx.task_id)

@task
async def process_order(
    order_id: int,
    logger: TaskLogger,  # Injected per-task
) -> None:
    """Process an order with task-scoped logger."""
    logger.info(f"Processing order {order_id}")
    # ... process order
    logger.info("Order processed successfully")

Dispatching Tasks

# Dispatch and get task ID (non-blocking)
task_id = await send_welcome_email.send(user_id=123, email="user@example.com")

# Dispatch and wait for result (blocking)
result = await process_batch.send_and_wait(items=["a", "b", "c"])

# Get result later by task ID
result = await send_welcome_email.get_result(task_id)

Module Setup

from myfy.core import Application
from myfy.data import DataModule
from myfy.tasks import TasksModule

app = Application()
app.add_module(DataModule())
app.add_module(TasksModule(auto_create_tables=True))

Running Workers

# Start worker with default concurrency
myfy tasks worker

# Start worker with custom concurrency
myfy tasks worker --concurrency 4

Task Options

OptionTypeDescription
namestrCustom task name (default: module.qualname)
max_retriesintOverride default max retries
retry_onlist[Exception]Exception types that trigger retry

TaskContext Methods

MethodDescription
ctx.task_idGet the current task ID
ctx.is_cancelledCheck if task was cancelled
ctx.update_progress(current, total, message)Report progress

Guidelines

  • Always use async functions
  • Add type hints for all parameters
  • Use TaskContext for long-running tasks
  • Handle cancellation gracefully
  • Add retry logic for network operations
  • Keep tasks idempotent when possible

Sponsors

Details

Marketplace
psincraian/myfy
Source
plugins/claude-code
Author
myfy
Category
Frameworks
License
MIT
Keywords
python, framework, web, di, scaffolding