AFD - Agent-First Development for Python
A Python toolkit for building applications with the Agent-First Development methodology.
Python follows the shared AFD feature set and agent-visible behavior, but keeps Pythonic APIs where that fits the language better. The goal is functional parity, not a byte-for-byte TypeScript port.
What is AFD?
Agent-First Development is a software development methodology where AI agents are treated as first-class users from day one. Instead of building UI first and adding API/agent access later, AFD inverts this:
Traditional: UI → API → Agent Access (afterthought)
Agent-First: Commands → Validation → UI (surface)
Core AFD surfaces stay framework-agnostic. React or browser integrations belong in examples and ecosystem layers, not in the afd core package.
Installation
# Core types only
pip install afd
# With MCP server support
pip install afd[server]
# With MCP client (network transports)
pip install afd[client]
# With CLI
pip install afd[cli]
# With testing utilities
pip install afd[testing]
# Everything
pip install afd[all]
Quick Start
Define a Command
from afd import CommandResult, success, error
from afd.server import define_command
from pydantic import BaseModel, Field
class Todo(BaseModel):
id: str
title: str
done: bool = False
class CreateTodoInput(BaseModel):
title: str = Field(..., min_length=1)
@define_command(
name="todo-create",
description="Create a new todo item",
input_schema=CreateTodoInput,
)
async def create_todo(input: CreateTodoInput) -> CommandResult[Todo]:
todo = Todo(id="todo-1", title=input.title)
return success(
data=todo,
reasoning="Created new todo with default status",
)
A handler receives the whole command input as its first argument. With input_schema, that input is validated and passed as a model instance; without it, the handler gets the raw input dict.
Create an MCP Server
from afd import ExposeOptions, success
from afd.server import create_server
server = create_server(
name="todo-app",
version="1.0.0",
)
# Todo and CreateTodoInput are defined in the example above.
@server.command(
name="todo-create",
description="Create a todo",
input_schema=CreateTodoInput,
expose=ExposeOptions(mcp=True),
)
async def create_todo(input: CreateTodoInput):
todo = Todo(id="todo-1", title=input.title)
return success(data=todo)
# Run the server (stdio for VS Code/Cursor).
server.run()
# Or serve MCP Streamable HTTP at http://127.0.0.1:8000/mcp:
# server.run(transport="streamable-http", port=8000, stateless_http=True)
Both transports serve MCP 2026-07-28 (stateless, per-request _meta) and 2025 clients that open with initialize, from one stdio connection or one /mcp endpoint. server.run() and server.run_async() pass transport options (host, port, stateless_http, json_response, transport_security, ...) to the MCP SDK, and server.streamable_http_app(**options) returns the ASGI app for mounting. server/discover returns the instructions given to create_server (a description of the meta-tools by default), and tools/list carries a ttlMs freshness hint (tools_list_ttl_ms; 5 minutes by default, 0 when contexts are set).
With contexts, an MCP 2026-07-28 request selects its context with _meta["dev.afd/context"] on tools/list and tools/call; there is no session to remember afd-context-enter, which then validates the name and returns persisted: false. 2025 clients on a stateful transport keep one context stack per connection, as before.
MCP exposure is opt-in. A command without expose=ExposeOptions(mcp=True) is invisible over MCP: it is not listed as a tool, and afd-call returns COMMAND_NOT_FOUND for it.
Test Your Commands
import pytest
from afd.testing import assert_success
# Use the mock_server fixture
async def test_create_todo(mock_server):
@mock_server.command("todo-create")
async def handler(input):
from afd import success
return success({"id": "1", "title": input["title"]})
result = await mock_server.execute("todo-create", {"title": "Test"})
data = assert_success(result)
assert data["title"] == "Test"
Testing Helpers
Execute and validate commands with automatic timing and error wrapping:
from afd.testing import test_command, create_mock_command, create_test_context
# Run a handler with timing + validation
result = await test_command(my_handler, {"title": "Test"})
assert result.is_success
assert result.execution_time_ms >= 0
# Create mock commands for testing dependencies
cmd = create_mock_command("user-get", lambda inp: {"id": inp["id"]})
result = await cmd.handler({"id": 1}, None)
assert result.success
# Batch-test with expectations
from afd.testing import test_command_multiple
results = await test_command_multiple(my_handler, [
{"input": {"title": "OK"}, "expect_success": True},
{"input": {}, "expect_success": False, "expect_error": "VALIDATION_ERROR"},
])
assert all(r["passed"] for r in results)
Validators
Non-throwing validators return a ValidationResult for programmatic use:
from afd.testing import validate_result, validate_error, validate_command_definition
vr = validate_result(result)
assert vr.valid
assert len(vr.errors) == 0
# Validate with stricter options
from afd.testing import ResultValidationOptions
vr = validate_result(result, ResultValidationOptions(require_confidence=True))
for warning in vr.warnings:
print(f"{warning.path}: {warning.message}")
Additional Assertions
from afd.testing import (
assert_has_suggestion, # Error includes recovery suggestion
assert_retryable, # Error retryable flag matches
assert_step_status, # Plan step has expected status
assert_ai_result, # Composite: confidence + reasoning + optional sources
)
# Validate error quality
error_result = error("NOT_FOUND", "Missing", suggestion="Check ID")
assert_has_suggestion(error_result)
assert_retryable(error_result, expected=False)
# Validate AI command output
ai_result = success(data, confidence=0.95, reasoning="Computed from input")
assert_ai_result(ai_result, min_confidence=0.9)
Core Types
CommandResult
The standard return type for all commands:
from afd import CommandResult, success, error
# Successful result
result = success(
data={"id": "123"},
reasoning="Created successfully",
confidence=0.95,
)
# Error result
result = error(
code="NOT_FOUND",
message="Resource not found",
suggestion="Check the ID and try again",
)
UX-Enabling Fields
AFD results include optional fields that enable rich agent experiences:
| Field | Purpose |
|---|---|
confidence |
0-1 score for UI confidence indicators |
reasoning |
Explains "why" for transparency |
sources |
Attribution for verification |
plan |
Multi-step operation visibility |
alternatives |
Other options considered |
warnings |
Non-fatal issues to surface |
Wire Format
Results cross language boundaries as JSON in the same shape as the TypeScript and
Rust packages (see spec/wire): keys are camelCase and
unset fields are omitted, never null. Python attributes stay snake_case.
from afd import CommandResult, success
from afd.core.wire import to_wire
to_wire(success({"id": "1"}, undo_command="todo-delete"))
# {'success': True, 'data': {'id': '1'}, 'undoCommand': 'todo-delete'}
# Parsing accepts camelCase and snake_case
CommandResult.model_validate({"success": True, "undoCommand": "todo-delete"})
The MCP server sends failures with isError: true, and a missing or mistyped
argument returns a VALIDATION_ERROR result with details.errors,
details.missingFields and a suggestion. Every command result carries
metadata.executionTimeMs and a per-call metadata.traceId, as in TypeScript. An
exception from a handler or a middleware becomes a COMMAND_EXECUTION_ERROR whose
message is "An internal error occurred" unless create_server(dev_mode=True). The core
registry (create_command_registry), execute_pipeline and SimpleRegistry redact the
same way and take the same dev_mode keyword.
Batches and Pipelines
afd-batch and afd-pipe run commands, never built-in tools: a batch item or pipeline
step naming afd-batch, afd-pipe, afd-call, afd-discover or afd-detail rejects
the whole request before anything runs, and so does a malformed when condition
(for example $exist or {"$eq": "x"}).
- The envelope is checked as TypeScript checks it. A blank command name,
nullin place of an omitted optional field, or a string where a boolean or number belongs returns a failedBatchResultwithINVALID_BATCH_REQUEST, or aPipelineResultwhose one step (index -1) carriesINVALID_PIPELINE_REQUEST, and nothing runs. - A batch holds at most 500 commands, with
parallelismat most 16. Configure the caps withcreate_server(max_batch_size=..., max_batch_parallelism=...); a larger request returnsINVALID_BATCH_REQUEST. - With
stopOnError, a failure stops new starts: commands already running finish normally and keep their results, and commands not yet started reportCOMMAND_SKIPPED. A batchtimeoutcancels and awaits running commands, which reportBATCH_TIMEOUT, so nothing keeps running after the result is sent. - A handler that returns something other than a
CommandResultgives its item or step anINVALID_COMMAND_RESULTfailure instead of breaking the aggregate result. - Pipelines run sequentially.
options.paralleland a step withstream: trueare not implemented: the offending step (step 0 forparallel) fails withUNSUPPORTED_OPTIONand every other step is skipped, before any command runs.DirectClient.pipe()rejects a streaming step the same way.
Telemetry
Track command execution with standardized telemetry events:
from afd import create_telemetry_event, ConsoleTelemetrySink
# Create an event from execution data
event = create_telemetry_event(
command_name="todo-create",
started_at="2024-01-15T10:30:00.000Z",
completed_at="2024-01-15T10:30:00.150Z",
success=True,
trace_id="trace-abc123",
)
# duration_ms is auto-calculated: 150.0
# Log to console (text or JSON format)
sink = ConsoleTelemetrySink(format="json")
sink.record(event)
# Implement a custom sink
class MyMonitoringSink:
def record(self, event):
send_to_monitoring(event.model_dump(exclude_none=True))
def flush(self):
pass
Middleware
Add cross-cutting concerns to command execution. As in TypeScript, middleware only runs
for a call that reaches a handler: the server rejects an unknown, unexposed or
out-of-context command, or invalid input, first. The input a middleware receives is
the validated input the handler gets (the schema's model instance).
from afd.server import (
create_server,
default_middleware,
compose_middleware,
create_logging_middleware,
create_timing_middleware,
create_retry_middleware,
)
# Zero-config: logging, timing, and auto trace ID (returns a list)
server = create_server(name="todo-app", middleware=default_middleware())
# Or compose a custom stack into one middleware; the first one runs outermost
stack = compose_middleware(
create_logging_middleware(),
create_timing_middleware(slow_threshold=500), # warn when a command takes over 500 ms
create_retry_middleware(max_retries=3),
)
server = create_server(name="todo-app", middleware=[stack])
# Retries back off exponentially like TypeScript's createRetryMiddleware: retry n waits
# min(max_delay, retry_delay * 2 ** (n - 1)) ms (defaults 100 and 5000), randomized to
# between half and all of that unless jitter=False.
retry = create_retry_middleware(max_retries=5, retry_delay=200, max_delay=2000, jitter=False)
# Fixed-window rate limit: 100 calls per minute per client. Expired windows are
# evicted; at most max_keys (default 10,000) clients are tracked at once.
from afd.server import create_rate_limit_middleware
limit = create_rate_limit_middleware(
max_requests=100,
window_ms=60_000,
key_fn=lambda ctx: ctx.extra.get("client_id", "anonymous"),
)
Command Journal
Record each call to a JSON Lines journal and replay it later to reproduce a session or
turn it into a regression test (spec/journal.md). Put the journal middleware last, so its
tape holds the clock and random values the handler read. An entry keeps the actor, the
interface and the trace ID from the context, and no other context value.
from pathlib import Path
from afd import FileJournalSink, parse_journal
from afd.server import create_journal_middleware, create_server, replay_journal
sink = FileJournalSink("session.jsonl")
server = create_server(name="todo-app", middleware=[create_journal_middleware(sink)])
# Later, against a fresh server with the same commands:
entries = parse_journal(Path("session.jsonl").read_text(encoding="utf-8"))
report = await replay_journal(fresh_server, entries)
for entry in report.entries:
if entry.status != "same":
print(entry.seq, entry.command, entry.status, entry.differences or entry.error)
MCP Client (Network)
Connect to remote MCP servers. A URL that does not end in /sse or /message uses MCP Streamable HTTP through the official MCP SDK client: MCP 2026-07-28 when the server offers it, else the 2025 initialize handshake (McpClientConfig.protocol_mode: "auto", "legacy" or "modern"). The sse and http transports of an AFD server's 2024-11-05 lane are deprecated.
from afd import McpClient, McpClientConfig, create_client
# Quick setup
client = create_client("http://localhost:3100/mcp")
await client.connect()
# Call a command (returns CommandResult)
result = await client.call("todo-create", {"title": "Hello"})
print(result.data)
# Raw tool call (no CommandResult wrapping)
raw = await client.call_tool("ping", {})
# Batch execution
batch_result = await client.batch([
{"name": "todo-create", "input": {"title": "First"}},
{"name": "todo-create", "input": {"title": "Second"}},
])
# Pipeline (variables: $prev, $first, $steps[N], $steps.<alias>, $input;
# see spec/pipeline-variables.md)
pipe_result = await client.pipe([
{"command": "user-get", "input": {"id": 1}, "as": "user"},
{"command": "order-list", "input": {"user_id": "$steps.user.id"}},
])
# Stream results
async for chunk in client.stream("long-task", {"query": "..."}):
print(chunk)
await client.disconnect()
Use transports directly for lower-level control:
from afd.transports import StreamableHttpTransport, create_transport
transport = create_transport("streamable-http", "http://localhost:3100/mcp")
await transport.connect()
result = await transport.call_tool("ping", {})
await transport.disconnect()
failure(command_error, ...) accepts the same result options as success (confidence,
reasoning, sources, plan, alternatives, warnings, suggestions, metadata and undo fields),
without a data payload. Both define_command and server.command accept errors and
execution_time (instant, fast, slow, long-running); the server decorator also
accepts handoff and handoff_protocol.
Handoff Connections
create_handoff() includes a fresh default reconnect policy: allowed, 3 attempts,
1000 ms backoff. An explicit policy replaces it. The handoff client uses the same
fallback for legacy handoffs; explicit ReconnectionOptions values win over metadata.
Unset max_attempts and backoff_ms are None and inherit metadata or the default.
Connect to streaming protocols (WebSocket, SSE) returned by handoff commands:
# Install with client dependencies
pip install afd[client]
from afd import (
connect_handoff,
create_reconnecting_handoff,
register_builtin_handlers,
HandoffConnectionOptions,
ReconnectionOptions,
)
from afd.core.handoff import is_handoff
# Register built-in WebSocket and SSE handlers
register_builtin_handlers()
# Connect to a handoff result
result = await client.call('chat-connect', {'room_id': 'room-123'})
if result.success and is_handoff(result.data):
# Simple connection
conn = await connect_handoff(result.data, HandoffConnectionOptions(
on_message=lambda msg: print('Message:', msg),
))
# Or with auto-reconnect
conn = await create_reconnecting_handoff(client, result.data,
ReconnectionOptions(
reconnect_command='chat-reconnect',
session_id=result.data.get('credentials', {}).get('sessionId'),
on_reconnect=lambda n: print(f'Reconnecting (attempt {n})'),
),
)
await conn.close() # stops any reconnect in progress; nothing stays open
- The built-in handlers read in a background task: every message reaches
on_message(parsed as JSON when it is JSON) and a close by the server reacheson_disconnect. - A
credentials.tokenis sent as anAuthorization: Bearerheader, never in the URL. - A reconnecting connection retries with exponential backoff until it connects, runs
out of attempts (
on_reconnect_failed, statefailed) or is closed. Before each attempt it callsreconnect_commandwithreconnect_argsplussessionId(the wire name, as in TypeScript) set from thesession_idoption. create_handoff()returns the wire format (sessionId,expectedLatency,expiresAt,maxAttempts,backoffMs); the handoff helpers accept camelCase or snake_case.
Private in-process approvals
create_direct_registry runs decorated commands through the server's validation and middleware,
with agent exposure checks by default (interface="cli" selects the CLI boundary). It lists
only registered, exposed commands; raw execute refuses an unexposed command with
COMMAND_NOT_EXPOSED, while DirectClient.call treats it as UNKNOWN_TOOL.
DirectClientOptions(allow=lambda name: name.startswith("item-"), middleware=[...])
(or the same keywords on create_direct_client) filters listing and calls, including
pipeline steps and nested registry calls that forward the handler context. A nested
call can narrow the policy but cannot widen it. Only an explicit True permits a name; false or a throwing predicate
returns COMMAND_NOT_ALLOWED before lookup. Client middleware uses the server's
(name, input, context, next_fn) signature and wraps each attempt in list order,
outside registry middleware, within the call's total deadline. Thrown exceptions are
redacted as COMMAND_EXECUTION_ERROR. Direct registries serve registered commands;
MCP meta-tools and the in-process tool surface remain outside this boundary.
DirectClientOptions(on_approval_needed=...) asks trusted application code with token-free
metadata; only True permits one retry. Public call/pipeline contexts cannot approve, and
held results, observers and journals receive no token. A deadline includes the human wait.
Use the server's execute only as a trusted host API when handling tokens out of band.
Without an approval middleware, create_server and create_direct_registry refuse a command whose
approval policy is not "not-required" with APPROVAL_UNAVAILABLE before its handler runs
(#1886); place retry middleware, and middleware that changes the input, before the approval
middleware, since one approval runs one handler on the approved input. Middleware that moves
next_fn to a thread uses asyncio.to_thread or contextvars.copy_context().run; otherwise a
call on a context object that overlapping calls share is refused. An input that changes while
the middleware decides (in a policy function) is refused with APPROVAL_UNAVAILABLE
(reason: "admission-mismatch"), and nobody is asked. Install one approval middleware per
engine: a second one that no policy of its own gates for a command leaves the first one's
admission to decide, but two that both gate a command's own policy each ask for it.
from afd import DirectClient, DirectClientOptions, create_direct_registry
from afd.server import create_approval_middleware
registry = create_direct_registry(commands, middleware=[
create_approval_middleware(secret=secret_from_environment),
])
client = DirectClient(registry, DirectClientOptions(on_approval_needed=ask_human))
# ask_human(request) returns True only after approval; request never contains a token.
Approvals over MCP
create_approval_middleware(..., relay="mcp-elicitation") asks the person behind an MCP client
that declares form elicitation, instead of returning a token: on MCP 2026-07-28 with an
input_required result, on a 2025 stdio or stateful HTTP connection with a server-sent
elicitation. The question shows the summary, the command and its validated input, and the call
runs once the person approves; a decline fails it with APPROVAL_REQUIRED and
details.reason: "declined". An afd-batch or afd-pipe is asked about once, before any step
runs. The relay trusts the client application to show the question to a person, so leave it off
where the agent's own code is the MCP client.
CLI
afd connect http://localhost:3100/mcp # MCP Streamable HTTP (/sse and /message URLs use the deprecated transports)
afd tools
afd call todo-create '{"title": "Hello"}'
afd call todo-create 'title="Buy milk" priority=2' -H "Authorization: Bearer $TOKEN"
afd batch '[{"command": "todo-create", "input": {"title": "One"}}, {"command": "todo-list"}]'
afd stream export-run '{"format": "csv"}'
afd batch sends one afd-batch call (a JSON array or a .json file; -s stops on the
first error, -t sets the batch deadline in milliseconds, -p the parallelism) and exits 2 when
some commands fail. afd stream takes a JSON object or key=value pairs and reads AFD's
POST /stream/<command> events, which the TypeScript server serves; -f json prints one chunk
per line, and Ctrl+C exits 130.
Arguments are one shell argument: a JSON object or key=value pairs (quote it when it holds
several pairs or spaces), whose values are parsed as JSON when they can be (count=2,
done=true) and kept as strings otherwise (title=milk). An empty argument means {}. connect, tools,
call, validate, shell, batch and stream send each -H "Name: value" header and those
in AFD_HEADERS (one per line); headers are never saved.
afd connect takes a server URL (or mock for testing); it does not start or name
servers. afd call item-delete --module ./commands.py instead loads a trusted Python file
exporting registry. It prompts for approval on an interactive terminal; --approve
explicitly authorizes one retry. JSON or noninteractive calls remain held without that flag.
--timeout 5000 includes the decision wait. Remote --approve is rejected.
Packages
| Extra | Contents |
|---|---|
| (core) | CommandResult, success(), error(), error types, metadata types |
[server] |
MCP server factory, @define_command, create_server() |
[client] |
McpClient, SSE/HTTP transports, handoff connection handlers |
[cli] |
Click-based CLI for connecting to MCP servers |
[testing] |
Assertions, helpers, validators, scenario runner, mock_server fixture |
Related
- AFD TypeScript - Original TypeScript implementation
- AFD Philosophy - Why AFD?
- Command Schema Guide - Designing commands
License
MIT
Metadata
Release files for afd 0.13.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| afd-0.13.0.tar.gz | 978.8 kB | With provenance | Details for afd-0.13.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| afd-0.13.0-py3-none-any.whl | Python 3 | none | any | Details for afd-0.13.0-py3-none-any.whl |
Total release size: 1.5 MB
Release files / afd-0.13.0.tar.gz
| Download URL | afd-0.13.0.tar.gz |
|---|---|
| Size | 978.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b1ac5cadf259af28966395c436b53064a7189d305fb9c241800d5077353bb50d
|
|
BLAKE2b-256 checksum How to use checksums |
7899ff37272a2bc28d120f31f2aba6408436a75915e048175c39780716be9881
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logRelease files / afd-0.13.0-py3-none-any.whl
| Download URL | afd-0.13.0-py3-none-any.whl |
|---|---|
| Size | 530.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6ea1393a02ed35ea10e4bf711a61330b15c722fc313f15b2230905145c948add
|
|
BLAKE2b-256 checksum How to use checksums |
c98299b078cc1ecf92dc5f34ff1ebba45143024d2a7db2a0a76cc1f43d653484
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logSecurity for afd 0.13.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for afd-0.13.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.