Skip to content

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

pip install apcore

Requires Python 3.11+.

In a new project, set up ESM and install the SDK and the dependencies used in the example.

npm init -y
npm pkg set type=module
npm install apcore-js @sinclair/typebox
npm install --save-dev 'typescript@^5.5.0' @types/node@20

Requires Node.js 20+ and TypeScript 5.5+.

cargo add apcore async-trait serde_json
cargo add tokio --features macros,rt-multi-thread

Requires Rust 1.86+.

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 apcore

@apcore.module(id="math.add", description="Add two numbers")
def add(a: int, b: int) -> dict:
    return {"sum": a + b}

result = apcore.call("math.add", {"a": 10, "b": 5})
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.

npx tsc --strict --module NodeNext --target ES2022 --outDir dist example.ts
node dist/example.js
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:

preflight = client.validate("math.add", {"a": 10, "b": 5})
if preflight.valid:
    print("All checks passed")
else:
    print(f"Errors: {preflight.errors}")
const preflight = await client.validate('math.add', { a: 10, b: 5 });
if (preflight.valid) {
  console.log('All checks passed');
} else {
  console.log('Errors:', preflight.errors);
}
let inputs = json!({"a": 10, "b": 5});
let preflight = client.validate("math.add", &inputs, None).await?;
if preflight.valid {
    println!("All checks passed");
} else {
    println!("Errors: {:?}", preflight.errors);
}

4. Streaming

Modules that implement stream() can yield output chunks incrementally:

async for chunk in client.stream("my.streaming_module", {"query": "hello"}):
    print(chunk)
for await (const chunk of client.stream('my.streaming_module', { query: 'hello' })) {
  console.log(chunk);
}
use futures_util::StreamExt;

// `stream()` returns a Stream, not a Future — poll it, do not await it.
let mut chunks = client.stream("my.streaming_module", json!({"query": "hello"}), None, None);
while let Some(chunk) = chunks.next().await {
    println!("{}", chunk?);
}

5. Auto-Discovery (Directory as ID)

Instead of manual registration, apcore can automatically discover modules in a directory.

Project structure:

my-project/
└── extensions/
    └── math/
        └── add.py  # Contains the module

from apcore import APCore

client = APCore()
client.discover()
# Module ID is automatically "math.add"
result = client.call("math.add", {"a": 10, "b": 5})

Project structure:

my-project/
└── extensions/
    └── math/
        └── add.ts  # Export default or named module

import { APCore } from 'apcore-js';

const client = new APCore();
await client.discover();
// Module ID is automatically "math.add"
const result = await client.call('math.add', { a: 10, b: 5 });

Project structure:

my-project/
└── extensions/
    └── math/
        └── add.rs  # Rust module file

let mut client = APCore::new();
client.discover().await?;
// Module ID is automatically "math.add"
let result = client.call("math.add", json!({"a": 10, "b": 5}), None, None).await?;

6. Adding Middleware

Middleware can intercept calls for logging, tracing, or security.

from apcore import LoggingMiddleware, StdoutExporter, TracingMiddleware

client.use(LoggingMiddleware())
# TracingMiddleware requires an exporter (or a processor) — it raises otherwise.
client.use(TracingMiddleware(exporter=StdoutExporter()))
import { ObsLoggingMiddleware } from 'apcore-js/full';

client.use(new ObsLoggingMiddleware());
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:

from apcore import Registry, Executor, module

registry = Registry(extensions_dir="./extensions")
registry.discover()

executor = Executor(registry=registry)
result = executor.call("math.add", {"a": 10, "b": 5})
import { Registry, Executor } from 'apcore-js';

const registry = new Registry({ extensionsDir: './extensions' });
await registry.discover();

const executor = new Executor({ registry });
const result = await executor.call('math.add', { a: 10, b: 5 });
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:

use apcore::APCore;
use serde_json::json;

let client = APCore::new();
client.discover().await?;

let result = client.call("math.add", json!({"a": 1, "b": 2}), None, None).await?;
let modules = client.list_modules(None, Some("math."));
let desc = client.describe("math.add");

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.