| description | Plain-language introduction to apcore's core building blocks: modules, schemas, annotations, context, governance (ACL and approval), and the execution pipeline. |
|---|
Everything you need to understand how apcore works — explained from the ground up, with links to deep references when you need them.
Traditional software has two interfaces: a UI for humans and an API for code. When AI agents enter the picture, plain functions and HTTP endpoints are not enough on their own — an agent needs to know what a capability does and what parameters it accepts, and your application needs a reliable place to enforce who may run it, whether a human must approve it, and what happened afterward.
Define each capability once as a Module. Callers in code, HTTP, CLI, MCP, or A2A can go through the same Executor to share validation, access rules, and approval policy.
# Without apcore: callable from Python, but no contract, no safety gate, no audit trail
def issue_refund(order_id, amount_cents):
...
# With apcore: machine-readable contract + automatic validation + destructive-call protection
from typing import Annotated
from apcore import APCore
from pydantic import Field
client = APCore()
@client.module(
id="billing.refund",
description="Issue a refund for a customer order",
destructive=True,
)
def issue_refund(order_id: str, amount_cents: Annotated[int, Field(ge=1)]) -> dict:
return {"refunded": order_id, "amount_cents": amount_cents}You do not have to rewrite existing business code to adopt apcore. You can register functions with a decorator, wrap existing service methods without editing them, or bind them externally with YAML files (see Creating Modules).
A Module is a single callable capability — such as email.send, billing.refund, or users.lookup. Every module has four required pieces:
| Part | Purpose |
|---|---|
| Module ID | A unique dot-separated name (for example billing.refund or executor.email.send_email). When using directory discovery, the file path is the ID so Python, TypeScript, and Rust produce identical IDs from the same folder layout. |
description |
Plain text (≤ 200 chars) explaining what the capability does so humans and agents can match it to an intent. |
input_schema & output_schema |
JSON Schema Draft 2020-12 contracts for the arguments and the module’s return value. |
execute() |
Your actual business logic (sync, async, or streaming). |
Deep dive: Module Interface · Creating Modules · Cross-language module IDs{ #27-ids-across-languages }
A Schema defines the exact shape and constraints of inputs and outputs (types, required fields, ranges, enums, patterns).
In the standard strategy:
- Inputs are validated after
before()middleware and before the module executes. Invalid inputs raiseSCHEMA_VALIDATION_ERROR. - Module outputs are validated before
after()middleware runs. Anafter()hook that replaces the output is responsible for its shape. - AI-friendly hints can be added with
x-*extension fields (such asx-sensitive: trueto redact secrets/PII from logs and traces, orx-when-to-usefor agent guidance).
Deep dive: Schema Definition Guide · Schema System
Schemas describe data; annotations describe side effects and risk. Both agents and the apcore runtime read them:
| Annotation | Meaning |
|---|---|
readonly |
Does not modify state (safe to retry or explore). |
destructive |
Performs an irreversible or high-impact change. Under the default ExecutionPolicy, destructive modules fail closed until an ApprovalHandler approves the call. |
requires_approval |
Always requires explicit approval before running. |
idempotent |
Calling repeatedly with the same inputs produces the same effect. |
open_world |
Interacts with external systems (email, webhooks, public APIs). |
streaming / cacheable / paginated |
Signals incremental output, caching eligibility, or paginated results. |
Deep dive: Module annotations · Usage examples{ #24-examples-usage-examples } · Extension metadata{ #25-metadata-extension-metadata }
Every invocation gets a Context object that travels down the entire call chain — including nested module-to-module calls:
trace_id— W3C-compatible 32-char hex ID linking every nested call and log line into one trace.caller_id&call_chain— Who initiated the call (@externalor another module ID) and the active call stack used to stop infinite loops and excessive depth.identity— Caller identity (id,type,roles,attrs) used by ACL rules and audit logs.data— A request-scoped map shared across parent and child calls (never store unredacted secrets withoutx-sensitive).cancel_token— Cooperative cancellation signal for long-running work.
Deep dive: Context Object · Identity System
The Executor can check access and approval before your code runs.
- ACL ("May this caller run this module at all?") — Attach an ACL and use a strategy with
acl_checkto enforce access rules. The first matching rule wins, and a ruleset withdefault_effect: denydenies unmatched calls. Rules can match roles, identity types, and call depth, and emit structured audit entries. - Approval ("Should this specific call proceed right now?") — In the standard strategy, the approval gate asks a pluggable
ApprovalHandlerwhen a call requires approval. Under the default policy this includes calls markeddestructive. The handler can decide immediately or returnpendingso a human can approve later and resume with_approval_token. With no handler configured, the gate fails closed (APPROVAL_DENIED).
Deep dive: ACL Configuration Guide · Cookbook — Approval Flow
- Registry — The in-memory catalog of registered or auto-discovered modules.
- Executor — Runs the steps selected by the execution strategy. The standard order is context creation → call-chain guard → module lookup → ACL check → approval gate → middleware
before→ input validation → execute → output validation → middlewareafter→ return. - Middleware — Onion-model
before/after/on_errorhooks wrapped around calls for logging, tracing, metrics, or custom cross-cutting logic. - Structured Errors —
ModuleErrorcarries a machine-readablecode,retryable,user_fixable,suggestion, andai_guidanceso callers and agents know how to recover instead of parsing stack traces. APCoreClient — The high-level facade that wiresRegistry,Executor, optionalConfig, middleware, and events together so you rarely have to assemble them by hand.
Deep dive: APCore Client · Execution Pipeline · Error System · Observability{ #213-observability }
Tracing{ #tracing } · Logging{ #logging } · Metrics{ #metrics }
The standard pipeline includes these stages.
Caller (direct code · HTTP · CLI · MCP · A2A)
│
▼
┌──────────────────────────────────────────────────────────┐
│ APCore Client / Executor │
│ │
│ 1. Build Context (trace_id, identity, call_chain) │
│ 2. Check Call Chain Guard (depth & cycle protection) │
│ 3. Look up Module in Registry │
│ 4. Check the attached ACL │
│ 5. Enforce Approval Gate (fail closed if required) │
│ 6. Run Middleware before() hooks │
│ 7. Validate inputs against input_schema │
│ 8. Run Module.execute() (or stream()) │
│ 9. Validate the module output against output_schema │
│ 10. Run Middleware after() hooks │
└──────────────────────────────────────────────────────────┘
│
▼
Return the result (after() may replace the module output)
| Principle | What it means in practice |
|---|---|
| Schema mandatory | Every module has an explicit input/output contract — callers never guess parameter shapes. |
| Governance | An attached ACL can deny unmatched calls. Under the default approval policy, the approval gate denies calls that need approval when no handler is configured. |
| Zero-config to start, config-driven to scale | Start in memory with APCore() and zero YAML files; add apcore.yaml, ACL files, and directory discovery when your app grows. |
| Protocol-neutral | Direct code, HTTP, CLI, MCP, and A2A can use the same Executor for shared runtime governance. |
| Cross-language consistency | Python, TypeScript, and Rust follow one specification and shared conformance fixtures. |
- Ready to run code? Follow the 5-minute Getting Started guide.
- Building your first real modules? Read Creating Modules{ #12-the-ai-collaboration-lifecycle } and Schema Definition.
- Want the deep technical design? Read Architecture or browse the Feature Reference.