Skip to content

Latest commit

 

History

History
337 lines (263 loc) · 12.9 KB

getting-started.md

File metadata and controls

337 lines (263 loc) · 12.9 KB
description Quick-start for apcore: install the Python, TypeScript, or Rust SDK and run your first governed module with schema validation and destructive-action approval.

Getting Started

In 5 minutes, you will install an apcore SDK, define a governed business capability (billing.refund), and see three core guarantees in action:

  1. Fail-closed safety — a module marked destructive refuses to execute until an approval handler is wired.
  2. Enforced contracts — invalid inputs are rejected before your business function ever runs.
  3. One definition, any surface — the same registered module can be called from code or projected to MCP, A2A, CLI, or HTTP.

!!! tip "Upgrading an existing codebase?" You do not need to rewrite existing services. See Choose Your Integration Path or Integrating Existing Projects for zero-intrusion registration and YAML bindings.

1. Installation

=== "Python"

```bash
pip install apcore
```

Requires Python 3.11+.

=== "TypeScript"

In a new project, enable ESM and install the SDK along with TypeBox for schemas.

```bash
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+.

=== "Rust"

```bash
cargo new --bin apcore-quickstart
cd apcore-quickstart
cargo add apcore async-trait serde_json
cargo add tokio --features macros,rt-multi-thread
```

Requires Rust 1.86+.

2. Your First Governed Module

The APCore client is the recommended entry point. It manages the Registry and Executor for you.

This example defines billing.refund as a destructive module, verifies that it fails closed without an approval handler, attaches a handler, executes a valid call, and confirms that a zero-cent refund is rejected before the function runs.

=== "Python"

<!-- executable-example: quick-start -->

```python
from typing import Annotated

from apcore import APCore, ApprovalDeniedError, AutoApproveHandler, SchemaValidationError
from pydantic import Field

client = APCore()


@client.module(
    id="billing.refund",
    description="Issue a refund for an order",
    destructive=True,
)
def refund(order_id: str, amount_cents: Annotated[int, Field(ge=1)]) -> dict:
    return {"refunded": order_id, "amount_cents": amount_cents}


# 1. Destructive modules fail closed until an approval handler is attached.
try:
    client.call("billing.refund", {"order_id": "ord-1", "amount_cents": 2500})
    raise AssertionError("expected ApprovalDeniedError")
except ApprovalDeniedError as err:
    print(f"Blocked without handler: {err.code}")

# 2. Attach an approval handler (use a real review policy in production).
client.executor.set_approval_handler(AutoApproveHandler())

# 3. Valid calls run and return validated output.
result = client.call("billing.refund", {"order_id": "ord-1", "amount_cents": 2500})
assert result == {"refunded": "ord-1", "amount_cents": 2500}
print(result)

# 4. Invalid inputs are rejected before your function ever executes.
try:
    client.call("billing.refund", {"order_id": "ord-1", "amount_cents": 0})
    raise AssertionError("expected SchemaValidationError")
except SchemaValidationError as err:
    print(f"Rejected invalid input: {err.code}")
```

Save the example as `example.py` and run `python example.py`.

=== "TypeScript"

<!-- executable-example: quick-start -->

```typescript
import assert from 'node:assert/strict';
import { Type } from '@sinclair/typebox';
import {
  APCore,
  ApprovalDeniedError,
  AutoApproveHandler,
  SchemaValidationError,
  createAnnotations,
} from 'apcore-js';

const client = new APCore();

const refund = client.module({
  id: 'billing.refund',
  description: 'Issue a refund for an order',
  annotations: createAnnotations({ destructive: true }),
  inputSchema: Type.Object({
    order_id: Type.String(),
    amount_cents: Type.Integer({ minimum: 1 }),
  }),
  outputSchema: Type.Object({
    refunded: Type.String(),
    amount_cents: Type.Integer(),
  }),
  execute: (inputs) => ({
    refunded: inputs.order_id as string,
    amount_cents: inputs.amount_cents as number,
  }),
});

await refund.registration;

// 1. Destructive modules fail closed until an approval handler is attached.
await assert.rejects(
  () => client.call('billing.refund', { order_id: 'ord-1', amount_cents: 2500 }),
  ApprovalDeniedError,
);

// 2. Attach an approval handler (use a real review policy in production).
client.executor.setApprovalHandler(new AutoApproveHandler());

// 3. Valid calls run and return validated output.
const result = await client.call('billing.refund', { order_id: 'ord-1', amount_cents: 2500 });
assert.deepEqual(result, { refunded: 'ord-1', amount_cents: 2500 });
console.log(result);

// 4. Invalid inputs are rejected before your function ever executes.
await assert.rejects(
  () => client.call('billing.refund', { order_id: 'ord-1', amount_cents: 0 }),
  SchemaValidationError,
);
```

Save the example as `example.ts`, then compile and run it:

```bash
npx tsc --strict --module NodeNext --target ES2022 --outDir dist example.ts
node dist/example.js
```

=== "Rust"

<!-- executable-example: quick-start -->

```rust
use apcore::errors::ModuleError;
use apcore::{
    APCore, APCoreOptions, AutoApproveHandler, Context, ErrorCode, Module, ModuleAnnotations,
};
use async_trait::async_trait;
use serde_json::{json, Value};

struct RefundModule;

// The module ID is supplied at registration, not by the trait.
#[async_trait]
impl Module for RefundModule {
    fn description(&self) -> &str {
        "Issue a refund for an order"
    }

    fn annotations(&self) -> ModuleAnnotations {
        ModuleAnnotations {
            destructive: true,
            ..Default::default()
        }
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "order_id": {"type": "string"},
                "amount_cents": {"type": "integer", "minimum": 1}
            },
            "required": ["order_id", "amount_cents"]
        })
    }

    fn output_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "refunded": {"type": "string"},
                "amount_cents": {"type": "integer"}
            },
            "required": ["refunded", "amount_cents"]
        })
    }

    async fn execute(&self, inputs: Value, _ctx: &Context<Value>) -> Result<Value, ModuleError> {
        let order_id = inputs["order_id"].as_str().unwrap_or_default();
        let amount_cents = inputs["amount_cents"].as_i64().unwrap_or(0);
        Ok(json!({"refunded": order_id, "amount_cents": amount_cents}))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Destructive modules fail closed until an approval handler is configured.
    let ungated = APCore::new();
    ungated.register("billing.refund", Box::new(RefundModule))?;
    let denied = ungated
        .call(
            "billing.refund",
            json!({"order_id": "ord-1", "amount_cents": 2500}),
            None,
            None,
        )
        .await
        .unwrap_err();
    assert_eq!(denied.code, ErrorCode::ApprovalDenied);

    // 2. Configure an approval handler (use a real review policy in production).
    let client = APCore::try_start(APCoreOptions {
        approval_handler: Some(Box::new(AutoApproveHandler)),
        ..Default::default()
    })?;
    client.register("billing.refund", Box::new(RefundModule))?;

    // 3. Valid calls run and return validated output.
    let result = client
        .call(
            "billing.refund",
            json!({"order_id": "ord-1", "amount_cents": 2500}),
            None,
            None,
        )
        .await?;
    assert_eq!(result, json!({"refunded": "ord-1", "amount_cents": 2500}));
    println!("{result}");

    // 4. Invalid inputs are rejected before your module ever executes.
    let invalid = client
        .call(
            "billing.refund",
            json!({"order_id": "ord-1", "amount_cents": 0}),
            None,
            None,
        )
        .await
        .unwrap_err();
    assert_eq!(invalid.code, ErrorCode::SchemaValidationError);
    Ok(())
}
```

Save the example as `src/main.rs` in your Cargo project and run `cargo run`.

!!! note "Replace AutoApproveHandler before production" AutoApproveHandler is useful for local tests and demos. In production, wire a CallbackApprovalHandler or human review workflow — see the Approval Flow cookbook.

3. Dry-Run Checks with Preflight

Before running a side-effecting call, callers (or an agent UI) can dry-run the pipeline checks — call-chain guard, module lookup, ACL, approval requirement, and input validation — without executing the module:

=== "Python"

```python
preflight = client.validate("billing.refund", {"order_id": "ord-1", "amount_cents": 2500})
print(f"valid={preflight.valid}, requires_approval={preflight.requires_approval}")
```

=== "TypeScript"

```typescript
const preflight = await client.validate('billing.refund', { order_id: 'ord-1', amount_cents: 2500 });
console.log({ valid: preflight.valid, requiresApproval: preflight.requiresApproval });
```

=== "Rust"

```rust
let inputs = json!({"order_id": "ord-1", "amount_cents": 2500});
let preflight = client.validate("billing.refund", &inputs, None).await?;
println!("valid={}, requires_approval={}", preflight.valid, preflight.requires_approval);
```

4. Expose the Same Module to Agents

Once a capability is registered with apcore, you do not have to re-implement schemas, ACL rules, or approval checks for each caller surface:

  • MCP tools: project registered modules with apcore-mcp.
  • A2A skills: publish Agent Card metadata and skills with apcore-a2a.
  • CLI commands: map module schemas to flags and subcommands with apcore-cli.
  • End-to-end walkthrough: see the runnable Python Golden Path example, which calls the exact same governed module from both Python code and MCP.

Next Steps

Before exposing modules to external callers, attach an ACL file and review the security setup and output publication boundary.

Goal Go to
Understand the 5 core building blocks Core Concepts
Wrap existing functions, classes, or YAML bindings Creating Modules Guide
Add real human-in-the-loop approval (sync or async resume) Cookbook — Approval Flow
Enforce caller → target permissions (default_effect: deny) ACL Configuration Guide
Add logging, tracing, and x-sensitive redaction Cookbook — Observability
Adopt apcore in an existing HTTP service Integrating Existing Projects
Choose in-memory vs. full config-driven runtime Runtime Profiles
Stream results Streaming Cookbook{ #4-streaming }
Discover modules from a directory Class-Based Modules and Auto-Discovery{ #5-auto-discovery-directory-as-id }
Add middleware Writing Middleware{ #6-adding-middleware }
Assemble a Registry and Executor Core Executor{ #7-advanced-manual-registry-executor }
Use Python’s module-level shortcuts Function Registration{ #8-global-entry-points }
Use built-in health, usage, or control modules System Modules{ #9-system-modules }