apcore
Build once, invoke by Code or AI.
A schema-enforced module standard for the AI-Perceivable era.
apcore is an AI-Perceivable module standard that makes every interface naturally perceivable and understandable by AI through enforced Schema definitions and behavioral annotations. It provides strict type safety, access control, middleware pipelines, and built-in observability — enabling you to define modules with structured input/output schemas that are easily consumed by both code and AI.
Features
- Schema-driven modules — Define input/output contracts using
schemars-derived types with automatic validation - Execution Pipeline — Context creation, call chain guard, ACL enforcement, approval gate, middleware before, validation, execution, output validation, middleware after, and return — with step metadata (
match_modules,ignore_errors,pure,timeout_ms) and YAML pipeline configuration Moduletrait — Implement theModuletrait to create fully schema-aware modules- YAML bindings — Register modules declaratively without modifying source code
- Access control (ACL) — Pattern-based, first-match-wins rules with wildcard support
- Middleware system — Composable before/after hooks with error recovery
- Observability — Tracing (spans), metrics collection, and structured context logging
- Async support — Built on
tokiofor seamless async module execution - Safety guards — Call depth limits, circular call detection, frequency throttling
- Approval system — Pluggable approval gate with async handlers, Phase B resume, and audit events
- Extension points — Unified extension management for discoverers, middleware, ACL, approval handlers, span exporters, and module validators
- Async task management — Background module execution with status tracking, cancellation, and concurrency limiting
- Behavioral annotations — Declare module traits (readonly, destructive, idempotent, cacheable, paginated, streaming) for AI-aware orchestration
- W3C Trace Context —
traceparentheader injection/extraction for distributed tracing interop
API Overview
Core
| Type | Description |
|---|---|
APCore |
High-level client — register modules, call, stream, validate |
Registry |
Module storage — discover, register, get, list, watch |
Executor |
Execution engine — call with middleware pipeline, ACL, approval |
Context |
Request context — trace ID, identity, call chain, cancel token |
Config |
Configuration — from_defaults with env overrides, load YAML/JSON, get/set dot-path, validate, reload |
Identity |
Caller identity — id, type, roles, attributes |
Module |
Core trait for implementing schema-aware modules |
Access Control & Approval
| Type | Description |
|---|---|
ACL |
Access control — rule-based caller/target authorization |
ApprovalHandler |
Pluggable approval gate trait |
AlwaysDenyHandler / AutoApproveHandler |
Built-in approval handlers |
Middleware
| Type | Description |
|---|---|
Middleware |
Pipeline hooks — before/after/on_error interception |
BeforeMiddleware / AfterMiddleware |
Single-phase middleware adapters |
ObsLoggingMiddleware |
Structured logging middleware |
RetryMiddleware |
Automatic retry with backoff |
ErrorHistoryMiddleware |
Records errors into ErrorHistory |
PlatformNotifyMiddleware |
Emits events on error rate/latency spikes |
Schema
| Type | Description |
|---|---|
SchemaLoader |
Load schemas from YAML or native types |
SchemaValidator |
Validate data against schemas |
SchemaExporter |
Export schemas for MCP, OpenAI, Anthropic, generic |
RefResolver |
Resolve $ref references in JSON Schema |
Observability
| Type | Description |
|---|---|
TracingMiddleware |
Distributed tracing with span export |
MetricsMiddleware / MetricsCollector |
Call count, latency, error rate metrics |
ContextLogger |
Context-aware structured logging |
ErrorHistory |
Ring buffer of recent errors with deduplication |
UsageCollector |
Per-module usage statistics and trends |
Events & Extensions
| Type | Description |
|---|---|
EventEmitter |
Event system — subscribe, unsubscribe, emit, emit_filtered, flush |
WebhookSubscriber |
Built-in event subscriber |
ExtensionManager |
Unified extension point management |
AsyncTaskManager |
Background module execution with status tracking |
CancelToken |
Cooperative cancellation token |
BindingLoader |
Load modules from YAML binding files |
Documentation
For full documentation, including Quick Start guides for Python and Rust, visit: https://aiperceivable.github.io/apcore/getting-started.html
Requirements
- Rust >= 1.75
- Tokio async runtime
Installation
Add to your Cargo.toml:
[]
= "0.16"
= { = "1", = ["full"] }
= "1"
Quick Start
Simple client
use APCore;
use Module;
use Context;
use ;
;
async
With configuration
use ;
use Path;
async
Module with typed schemas
use ;
use Context;
use ;
use ;
;
Add middleware
use ;
client.use_middleware;
// TracingMiddleware requires a SpanExporter — see observability docs
Access control
use ;
let acl = ACLnew;
YAML bindings
Register modules without touching Rust source — define a binding.yaml:
bindings:
- module_id: "utils.format_date"
target: "format_date::format_date_string"
description: "Format a date string into a specified format"
tags:
version: "1.0.0"
input_schema:
type: object
properties:
date_string:
output_format:
required:
output_schema:
type: object
properties:
formatted:
required:
Load it at runtime:
use BindingLoader;
let loader = new;
loader.load_from_file.unwrap;
Examples
The examples/ directory contains runnable demos. Run any example with:
simple_client — Implement Module and execute directly
Defines two modules (AddModule, GreetModule), builds an Identity + Context, and calls them directly without a registry.
use ;
use ModuleError;
use Module;
use async_trait;
use ;
use HashMap;
;
async
greet — Typed input/output with serde and default field values
Uses #[serde(default)] for optional fields and shows schema introspection and validation error handling.
use ;
use ModuleError;
use Module;
use async_trait;
use ;
use ;
use HashMap;
;
async
get_user — Readonly module with ModuleAnnotations and ModuleExample
Demonstrates behavioral annotations (readonly, idempotent), ModuleExample for AI-perceivable documentation, and looking up records by ID.
use ;
// ...
user-1: {"email":"alice@example.com","id":"user-1","name":"Alice"}
user-2: {"email":"bob@example.com","id":"user-2","name":"Bob"}
user-999: {"email":"unknown@example.com","id":"user-999","name":"Unknown"}
send_email — Destructive module with sensitive fields
Shows x-sensitive: true on schema fields (for log redaction), ModuleAnnotations with metadata, and behavioral annotation for destructive operations.
cancel_token — Cooperative cancellation during long-running execution
CancelToken is a cloneable, shared cancellation signal. Modules poll token.is_cancelled() between steps to stop early.
use CancelToken;
// Attach a token to the context
let mut ctx: = new;
let token = new;
ctx.cancel_token = Some;
// Cancel from another task after 80 ms
spawn;
// Module checks the token between steps
async
=== Run 1: normal execution ===
[SlowModule] Executing step 0...
[SlowModule] Executing step 1...
[SlowModule] Executing step 2...
Result: {"completed_steps":3}
=== Run 2: cancelled mid-flight ===
[SlowModule] Executing step 0...
[SlowModule] Executing step 1...
[main] Sending cancel signal…
[SlowModule] Cancelled at step 2
Error (expected): Execution cancelled after 2 steps
Tests
Run all tests:
Run a specific test file:
Run a specific test by name:
Run with output visible:
Development
Prerequisites
Install Rust via rustup:
|
Clone and build
Run tests
Run tests with output
Run a specific test
Lint and format
Build documentation
Check without building
License
Apache-2.0
Links
- Documentation: https://aiperceivable.github.io/apcore/
- Website: aiperceivable.com
- GitHub: aiperceivable/apcore-rust
- crates.io: apcore
- Issues: GitHub Issues
- Discussions: GitHub Discussions