Skip to content

Latest commit

 

History

History
183 lines (125 loc) · 11.2 KB

concepts.md

File metadata and controls

183 lines (125 loc) · 11.2 KB
description Plain-language introduction to apcore's core building blocks: modules, schemas, annotations, context, governance (ACL and approval), and the execution pipeline.

Core Concepts

Everything you need to understand how apcore works — explained from the ground up, with links to deep references when you need them.

1. Why apcore Exists

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).


2. The Six Building Blocks

2.1 Module

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 }

2.2 Schema

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 raise SCHEMA_VALIDATION_ERROR.
  • Module outputs are validated before after() middleware runs. An after() hook that replaces the output is responsible for its shape.
  • AI-friendly hints can be added with x-* extension fields (such as x-sensitive: true to redact secrets/PII from logs and traces, or x-when-to-use for agent guidance).

Deep dive: Schema Definition Guide · Schema System

2.3 Behavioral Annotations

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 }

2.4 Context

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 (@external or 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 without x-sensitive).
  • cancel_token — Cooperative cancellation signal for long-running work.

Deep dive: Context Object · Identity System

2.5 Governance: ACL & Approval

The Executor can check access and approval before your code runs.

  1. ACL ("May this caller run this module at all?") — Attach an ACL and use a strategy with acl_check to enforce access rules. The first matching rule wins, and a ruleset with default_effect: deny denies unmatched calls. Rules can match roles, identity types, and call depth, and emit structured audit entries.
  2. Approval ("Should this specific call proceed right now?") — In the standard strategy, the approval gate asks a pluggable ApprovalHandler when a call requires approval. Under the default policy this includes calls marked destructive. The handler can decide immediately or return pending so 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

2.6 Registry, Executor, Middleware & Observability

  • 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 → middleware after → return.
  • Middleware — Onion-model before / after / on_error hooks wrapped around calls for logging, tracing, metrics, or custom cross-cutting logic.
  • Structured Errors — ModuleError carries a machine-readable code, retryable, user_fixable, suggestion, and ai_guidance so callers and agents know how to recover instead of parsing stack traces.
  • APCore Client — The high-level facade that wires Registry, Executor, optional Config, 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 }


3. How the Pieces Fit Together

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)

4. Core Design Principles

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.

Next Steps