Getting Started¶
apcore defines a governed, agent-readable capability boundary for your application. It combines enforced schemas, behavioral metadata, access rules, approval gates, and structured error guidance without promising that a model will select or repair a call automatically.
Whether you are building from scratch or upgrading a legacy system, apcore provides a path for you. See Choose Your Integration Path for details.
1. Installation¶
2. Your First Module¶
The APCore client is the recommended entry point. It manages Registry and Executor for you.
from apcore import APCore
client = APCore()
@client.module(id="math.add", description="Add two numbers", tags=["math"])
def add(a: int, b: int) -> dict:
return {"sum": a + b}
# Call the module
result = client.call("math.add", {"a": 10, "b": 5})
assert result == {"sum": 15}
print(result) # {'sum': 15}
For simple scripts, you can also use the global apcore.* functions directly:
import assert from 'node:assert/strict';
import { Type } from '@sinclair/typebox';
import { APCore } from 'apcore-js';
const client = new APCore();
const addition = client.module({
id: 'math.add',
description: 'Add two numbers',
tags: ['math'],
inputSchema: Type.Object({ a: Type.Number(), b: Type.Number() }),
outputSchema: Type.Object({ sum: Type.Number() }),
execute: (inputs) => ({ sum: (inputs.a as number) + (inputs.b as number) }),
});
await addition.registration;
const result = await client.call('math.add', { a: 10, b: 5 });
assert.deepEqual(result, { sum: 15 });
console.log(result); // { sum: 15 }
Save the example as example.ts, then compile and run it.
use apcore::errors::ModuleError;
use apcore::{APCore, Context, Module};
use async_trait::async_trait;
use serde_json::{json, Value};
struct AddModule;
// The module ID is supplied at registration, not by the trait.
#[async_trait]
impl Module for AddModule {
fn description(&self) -> &str { "Add two numbers" }
fn input_schema(&self) -> Value {
json!({
"type": "object",
"properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
"required": ["a", "b"]
})
}
fn output_schema(&self) -> Value {
json!({"type": "object", "properties": {"sum": {"type": "integer"}}})
}
async fn execute(
&self,
inputs: Value,
_ctx: &Context<Value>,
) -> Result<Value, ModuleError> {
let a = inputs["a"].as_i64().unwrap_or(0);
let b = inputs["b"].as_i64().unwrap_or(0);
Ok(json!({"sum": a + b}))
}
}
#[tokio::main]
async fn main() -> Result<(), ModuleError> {
let client = APCore::new();
client.register("math.add", Box::new(AddModule))?;
let result = client
.call("math.add", json!({"a": 10, "b": 5}), None, None)
.await?;
assert_eq!(result, json!({"sum": 15}));
println!("{result}"); // {"sum":15}
Ok(())
}
Save the example as src/main.rs in your Cargo project and run cargo run.
3. Preflight Validation¶
Before executing, you can validate inputs without running the module:
4. Streaming¶
Modules that implement stream() can yield output chunks incrementally:
5. Auto-Discovery (Directory as ID)¶
Instead of manual registration, apcore can automatically discover modules in a directory.
Project structure:
Project structure:
6. Adding Middleware¶
Middleware can intercept calls for logging, tracing, or security.
use apcore::middleware::LoggingMiddleware;
use apcore::observability::TracingMiddleware;
client.use_middleware(Box::new(LoggingMiddleware::with_defaults()))?;
// There is one TracingMiddleware. The `OtelTracingMiddleware` alias existed
// only to dodge a name collision with a second, withdrawn one; see
// features/middleware-system.md §1.3.
client.use_middleware(Box::new(TracingMiddleware::new(exporter)))?;
7. Advanced: Manual Registry + Executor¶
For full control, you can manage Registry and Executor separately:
use apcore::{Config, Executor, Registry};
use serde_json::json;
// Enable the `discovery` Cargo feature to scan an extensions directory,
// or register modules directly on `Registry::new()`.
let registry = Registry::new();
let executor = Executor::new(registry, Config::default());
let result = executor.call("math.add", json!({"a": 10, "b": 5}), None, None).await?;
8. Global Entry Points¶
All APCore client methods are also available as module-level functions via a default client instance:
import apcore
# Registration
@apcore.module(id="math.add", description="Add two numbers")
def add(a: int, b: int) -> dict:
return {"sum": a + b}
apcore.register("math.add", my_module) # Direct registration
apcore.discover() # Auto-discover from extensions dir
# Execution
result = apcore.call("math.add", {"a": 1, "b": 2})
preflight = apcore.validate("math.add", {"a": 1})
# apcore.stream(), apcore.call_async() also available
# Discovery & Inspection
modules = apcore.list_modules(prefix="math.")
desc = apcore.describe("math.add")
# Middleware
apcore.use(LoggingMiddleware())
apcore.use_before(lambda mid, inp, ctx: print(f"→ {mid}"))
apcore.use_after(lambda mid, inp, out, ctx: print(f"← {mid}"))
apcore.remove(mw)
# Events & Control (requires config with sys_modules enabled)
sub = apcore.on("apcore.module.toggled", handler)
apcore.off(sub)
apcore.disable("some.module", reason="maintenance")
apcore.enable("some.module", reason="done")
TypeScript does not have module-level functions. Use an APCore instance directly:
import { APCore, LoggingMiddleware } from "apcore-js";
const client = new APCore();
// Registration
await client.register("math.add", myModule);
await client.discover();
// Execution
const result = await client.call("math.add", { a: 1, b: 2 });
const preflight = await client.validate("math.add", { a: 1 });
// Discovery & Inspection
const modules = client.listModules({ prefix: "math." });
const desc = client.describe("math.add");
// Middleware
client.use(new LoggingMiddleware());
client.useBefore((mid, inp, ctx) => console.log(`→ ${mid}`));
client.useAfter((mid, inp, out, ctx) => console.log(`← ${mid}`));
// Events & Control
const sub = client.on("apcore.module.toggled", handler);
client.off(sub);
await client.disable("some.module", "maintenance");
await client.enable("some.module");
Rust does not provide a global singleton. Use an explicit APCore instance:
See APCore Client for the full reference.
9. System Modules¶
When configured with sys_modules.enabled: true, APCore auto-registers built-in system.* modules for health monitoring, usage analytics, manifest inspection, and runtime control.
from apcore import APCore
from apcore.config import Config
config = Config.load("apcore.yaml")
client = APCore(config=config)
# Health overview
health = client.call("system.health.summary", {})
print(health["summary"]) # {"total_modules": 12, "healthy": 10, ...}
# Usage statistics
usage = client.call("system.usage.summary", {"period": "24h"})
# Module manifest
manifest = client.call("system.manifest.full", {"prefix": "math."})
# Runtime control (requires approval handler + events enabled)
client.disable("risky.module", reason="investigating issue")
client.enable("risky.module", reason="issue resolved")
import { APCore, Config } from 'apcore-js/full';
const config = Config.load('apcore.yaml');
const client = new APCore({ config });
// Health overview
const health = await client.call('system.health.summary', {});
console.log(health.summary); // { total_modules: 12, healthy: 10, ... }
// Usage statistics
const usage = await client.call('system.usage.summary', { period: '24h' });
// Module manifest
const manifest = await client.call('system.manifest.full', { prefix: 'math.' });
// Runtime control (requires approval handler + events enabled)
await client.disable('risky.module', 'investigating issue');
await client.enable('risky.module', 'issue resolved');
use apcore::APCore;
use serde_json::json;
let client = APCore::from_path("apcore.yaml")?;
// Health overview
let health = client.call("system.health.summary", json!({}), None, None).await?;
// Usage statistics
let usage = client.call("system.usage.summary", json!({"period": "24h"}), None, None).await?;
// Module manifest
let manifest = client.call("system.manifest.full", json!({"prefix": "math."}), None, None).await?;
See System Modules for the full module reference.
Next Steps¶
Before exposing modules to external callers, attach an ACL and configure approval enforcement for sensitive operations. Review the security setup and the output publication boundary.
- APCore Client - Complete unified client reference.
- Creating Modules Guide - Deep dive into module definition.
- Schema Definition Guide - Learn about advanced validation.
- ACL Configuration - Secure your modules.
- Event System - Framework event bus and subscribers.
- System Modules - Built-in health, usage, and control modules.
- apcore-toolkit - Shared scanner, schema extraction, and output toolkit.
- apcore-mcp - Expose these modules as an MCP Server.
- apcore-a2a - Expose these modules as an A2A Agent.
- apcore-cli - Expose these modules as CLI commands.