Skip to content

Latest commit

 

History

History
720 lines (552 loc) · 36.5 KB

module-interface.md

File metadata and controls

720 lines (552 loc) · 36.5 KB
description Structural duck-typed module contract: required input_schema/output_schema/description and execute(); optional validate/preflight/describe/stream, lifecycle hooks; class/function forms.

Module Interface

Type: Implementation guide. Normative spec: PROTOCOL_SPEC §5.6 Module Interface Protocol.

Overview

The Module Interface is the central contract every apcore module must satisfy. It defines the required schema attributes (input_schema, output_schema, description), the execute() entry point, and a set of optional attributes, lifecycle hooks, and methods that modules MAY implement to express richer behavior to the framework and AI callers. The interface is structural — apcore validates conformance via duck typing, not ABC inheritance — which lets each language SDK express the contract using the most idiomatic construct available (Python Protocol, TypeScript interface, Rust trait).

apcore also accepts a function-based form (@module decorator or module(callable, ...)) that produces a Module object equivalent to the class form. The two forms are interchangeable in Registry, Executor, and Schema export behavior.

Requirements

  • Every module MUST declare an input_schema and output_schema (a Pydantic BaseModel class in Python, a TypeBox schema in TypeScript, a JSON Schema serde_json::Value in Rust).
  • Every module MUST provide a description (≤200 chars, plain text) sourced from a docstring or explicit attribute.
  • Every module MUST implement an execute(inputs, context) -> outputs method (sync or async — the framework auto-detects).
  • Modules MAY implement validate(), preflight(), describe(), stream() for additional capabilities.
  • Modules MAY define lifecycle hooks (on_load, on_unload, on_suspend, on_resume) for resource and state management, including hot-reload state preservation.
  • Modules MAY annotate behavior via ModuleAnnotations (read-only / destructive / idempotent / requires_approval / open_world / streaming / cacheable / paginated, plus an extra dict for ecosystem extensions).
  • Modules MAY supply examples, tags, name, version, and a free-form metadata dict.
  • Function-based modules MUST have type annotations on all parameters and the return value; the framework auto-generates the schemas from the signature.
  • Discovery rejects a module that is missing a required member (it is logged and skipped); in Rust the compiler enforces the Module trait.

Technical Design

Structural Typing

Modules MUST NOT inherit from an ABC. The framework checks for the required attributes and methods (input_schema, output_schema, description, execute) using language-appropriate structural mechanisms:

  • Python — typing.Protocol with @runtime_checkable.
  • TypeScript — Structural interfaces; discovery checks for the required members.
  • Rust — Module trait with required methods; the compiler enforces conformance.

Required Attributes

Attribute Constraint
input_schema Schema type (Pydantic BaseModel / TypeBox schema / JSON Schema Value). Every field MUST have a description.
output_schema Same constraints as input_schema. The execute() return value MUST validate against it.
description Plain text, ≤200 chars. Sourced from class docstring or explicit attribute. Describes "what / when / key features".
documentation Optional. Markdown, ≤5000 chars. Used for richer AI-facing documentation.
execute(inputs, context) Required method. May be sync or async. The framework auto-detects.

Optional Attributes

Attribute Default Purpose
name Generated from class name Human-readable name
tags [] Categorization for Registry.list(tags=...)
version "1.0.0" SemVer
annotations ModuleAnnotations() defaults Behavior hints for AI callers (see below)
examples [] ModuleExample list — recommended when input has unions, >5 required fields, or 2+ levels of nesting
metadata {} Free-form extension dict (cost hints, side effects, owner, etc.)

ModuleAnnotations

Behavior annotations help AI/LLM callers make invocation decisions. All fields are optional and default to safe values.

Field Default Meaning
readonly False Does not modify any state
destructive False May delete or overwrite data
idempotent False Repeated calls have no additional side effects
requires_approval False Whether this module requires human confirmation before execution. Enforced at runtime by Approval System. False does not mean no approval will be required — an ACL rule, an ExecutionPolicy override or gate_destructive may require one for a particular call (spec §6.9 rows 3-5). Get the call's effective value from validate().
open_world True Connects to external systems
discoverable True Whether the module appears in manifests and tool discovery. When false, it remains callable by ID but is hidden from discovery.
streaming False Supports chunk-by-chunk output via stream()
cacheable False Output can be cached for identical inputs
cache_ttl 0 Cache duration in seconds (0 = no cache)
cache_key_fields None Tuple of input fields for cache key (None = all fields). Lists are auto-converted to tuples.
paginated False Returns paginated results
pagination_style "cursor" "cursor", "offset", or "page"
extra {} Ecosystem extension metadata not covered by standard fields

Metadata Conventions

The metadata dict MAY carry ecosystem-standard keys to aid AI orchestration. SDKs SHOULD pass these keys through to discovery manifests.

Key Type Meaning
x-reasoning-demand int (1–5) Indicates the expected reasoning complexity (1 = simple tool, 5 = high-agency task).
x-required-context-keys list[str] Keys that MUST be present in context.data for the module to function.
x-supports-dry-run bool Indicates the module supports a non-destructive dry-run mode via an input flag.

Lifecycle Hooks

Hook Purpose
on_load() Called once when the module is registered. Initialize resources here (DB connections, pools).
on_unload() Called when the module is removed or the application shuts down. Clean up resources.
on_suspend() -> dict | None Called after the drain wait, before unloading for hot reload. Return JSON-serializable state to preserve.
on_resume(state: dict) Called on the replacement before publication with the dict returned by on_suspend().
on_drain(context) Called after a managed operation closes admission. Notify streams and background producers that it is time to finish. Keep resources available for calls still running.
on_drain_aborted(context) Called when a managed reload aborts before unloading. Restore readiness before the Registry reopens admission on the existing generation.

Hooks during a successful replacement

Close admission and wait for active calls, subject to the drain deadline
old.on_suspend() → state          ← export state
old.on_unload()                   ← release resources
new.on_load()                     ← acquire resources
new.on_resume(state)              ← restore state (only if state is not None)
Publish the replacement

on_suspend() return values MUST be JSON-serializable. on_resume() MUST tolerate missing or extra keys (versions may differ). Publication of the replacement requires a successful on_load().

The Python and Rust watchers run the state handoff when they replace a module. In Rust the discoverer or its factory supplies the replacement instance. TypeScript emits a notification so the application can arrange its own replacement. An explicit system.control.reload_module also supports state handoff in every SDK. See Registry hot reload.

Drain and recovery hooks

Managed reload requires both hooks when the module exposes on_drain. The drain context includes the operation ID, module ID, reason, remaining drain time, and a hook-specific cancellation signal. The recovery context includes the operation ID, module ID, a fresh signal, and drain_timeout or drain_error as the abort reason. A managed operation awaits the drain hook before recovery or teardown, even when the drain deadline expires and signals the hook. An active call can finish while the module is draining.

SDK Declare and register hooks
Python Define on_drain and on_drain_aborted as methods receiving DrainContext and DrainAbortedContext. Use register_async, register_many_async, or discover_async for modules with asynchronous hooks. Keep the registration event loop live while these hooks may run.
TypeScript Implement onDrain(context: DrainContext) and onDrainAborted(context: DrainAbortedContext) with a void or Promise<void> result. Register through await register(...) or await registerMany(...). Load, unload, suspend, and resume can also return promises.
Rust Implement both async hooks on DrainableModule and expose the typed capability with Module::as_drainable. For asynchronous load, unload, suspend, or resume, implement AsyncLifecycleModule, expose it with Module::as_async_lifecycle, and use register_async, register_many_async, or discover_async.

See managed lifecycle sequencing and managed reload results.

Optional Methods

Method Purpose
validate(inputs) -> ValidationResult Custom input validation without execution. Should be side-effect free.
preview(inputs, context) -> dict Returns a "low-fidelity" result without performing side effects. Used by AI agents to verify their plan before execution.
preflight(inputs, context) -> list[str] Advisory warnings emitted during Executor.validate(). Does NOT block execution.
describe() -> dict Module metadata for introspection. Used by system.manifest. Default returns {description, input_schema, output_schema, annotations}.
stream(inputs, context) -> AsyncIterator[dict] Streaming output. When defined, Executor.stream() calls this instead of execute(). Modules implementing stream() MUST satisfy the StreamingModule interface for their target language (Python Protocol with @runtime_checkable; TypeScript interface + Symbol.for("apcore.streaming") marker; Rust trait StreamingModule: Module). Modules implementing stream() SHOULD set annotations.streaming = True.
as_streaming() -> Optional[StreamingModule] (Rust only) Trait-object accessor on the base Module trait for adapter / bridge code that needs a typed &dyn StreamingModule handle. Default returns None; streaming modules override to return Some(self). MUST stay consistent with Module::stream() — both return Some(_) or both return None per module. See Streaming Module Interface.

Sync / Async Execution

Modules define one execute() method, either def or async def. The framework detects which and dispatches accordingly. Both Executor.call() and Executor.call_async() handle both forms.

Function-Based Modules

The @module(...) decorator (or the call form module(callable, ...)) lets unmodifiable code (class methods, third-party functions) be registered without writing a Module class. The framework derives equivalents:

Class attribute Function-based equivalent
input_schema Auto-generated from parameter type annotations
output_schema Auto-generated from return type annotation
description First line of docstring, or description parameter
documentation documentation parameter
execute() The function itself
name, tags, version, annotations, metadata Decorator parameters
on_load, on_unload, on_suspend, on_resume, on_drain, on_drain_aborted Use a class module to define lifecycle hooks.

If a parameter is declared as context: Context, the framework auto-injects the Context object. The context parameter is excluded from the generated input_schema.

For full grammar details and decorator semantics, see PROTOCOL_SPEC §5.11 and Decorator & YAML Bindings.

A malformed annotation value (for example a non-object extra, or a negative cache_ttl) is coerced or dropped with a warning; the rest of the annotations — and the module — are kept (D-115).

Contract: Module conformance

Normative behavioral contract. All SDK implementations MUST satisfy these guarantees.

Inputs

A module is supplied to the framework either as a class implementing the module surface or, in function form, as a decorated callable from which the surface is derived (see the function-based equivalence table above). The behavioral contract is exercised through execute(), which receives:

  • inputs (dict / object / map, required) — the call arguments. MUST validate against input_schema at execution time; a validation failure is surfaced as a schema error before the module body runs.
  • context (Context, required) — the per-call context carrying identity, data, cancellation signal, and deadline. In function form, a parameter declared as context: Context is auto-injected and excluded from the generated input_schema.

Required surface

  • input_schema — schema type. MUST exist; MUST validate inputs at execution time.
  • output_schema — schema type. MUST exist; MUST validate outputs at execution time.
  • description — string, ≤200 chars, MUST exist (docstring or attribute).
  • execute(inputs, context) -> dict — MUST exist as def or async def.

Optional surface

Surface Level Contract
documentation MAY ≤5000 chars, Markdown allowed
validate() MAY No side effects
preflight() MAY Returns advisory warnings; MUST NOT block execution
describe() MAY Returns introspection dict
stream() MAY Async iterator yielding partial dicts; framework deep-merges chunks
on_load, on_unload MAY Exceptions MUST NOT block other modules from loading
on_suspend, on_resume MAY Used during hot-reload only; return value MUST be JSON-serializable
name MAY Defaults to derived from class name
tags MAY Defaults to []
version MAY Defaults to "1.0.0"; MUST conform to SemVer
annotations MAY Defaults applied where unset
examples MAY Each inputs MUST validate against input_schema
metadata MAY Defaults to {}

Timeout semantics

  • Module execution SHOULD complete within its timeout: the module's resources.timeout if declared, otherwise executor.default_timeout (default 30 000 ms); the whole call chain is bounded by executor.global_timeout (default 60 000 ms).
  • After timeout the framework MUST raise MODULE_TIMEOUT.
  • Modules SHOULD support cooperative cancellation by polling the cancellation signal exposed via context.

Thread safety

  • Module instances MUST tolerate concurrent execute() invocations.
  • Modules MUST NOT mutate class-level (ClassVar) attributes inside execute().
  • Shared state MUST use thread-safe constructs.

Return-value constraints

  • execute() MUST return a dict (or language-equivalent map).
  • The return value MUST validate against output_schema.
  • The return value MUST NOT contain non-serializable objects (functions, open connections, etc.).

The executor validates and passes the JSON object representation to after-middleware and callers. Python converts Pydantic models using their JSON field aliases. TypeScript uses the own enumerable data fields of class instances and serializes nested dates as strings. Rust modules provide JSON objects through serde_json::Value.

Errors

The protocol defines no dedicated error class per conformance violation:

  • A module missing input_schema, output_schema, description or execute (or, in Python, whose schemas are not BaseModel classes) is rejected by discovery — logged and skipped, not registered. In Rust the compiler rejects it.
  • A module declaring annotations.streaming = true whose stream() does not match the streaming interface is rejected at registration with STREAMING_INTERFACE_MISMATCH.
  • A custom validator installed on the registry can reject a module at registration (GENERAL_INVALID_INPUT in Python and TypeScript, MODULE_LOAD_ERROR in Rust).
  • Input and output that fail their schemas raise SCHEMA_VALIDATION_ERROR at pipeline steps 7 and 9.

Returns

execute() MUST return a dict (or language-equivalent map) that validates against output_schema, subject to the constraints in Return-value constraints above (JSON-serializable; no functions or open connections). The optional surface methods return as follows:

  • validate(inputs) — a ValidationResult (valid plus per-field errors); side-effect free.
  • preflight() — advisory warnings; MUST NOT block execution.
  • describe() — an introspection dict.
  • stream() — an async iterator yielding partial dicts that the framework deep-merges into the final output.

Properties

  • async: execute() MAY be synchronous or asynchronous (def or async def); the framework supports both.
  • thread_safe: required — instances MUST tolerate concurrent execute() invocations and MUST NOT mutate class-level (ClassVar) attributes during execution (see Thread safety above).
  • pure: not required — modules MAY perform side effects; lifecycle hooks (on_load, on_unload, on_suspend, on_resume) exist precisely to manage external state.
  • timeout-bound: execution SHOULD complete within resources.timeout (default 30 000 ms) / executor.global_timeout (default 60 000 ms); on expiry the framework MUST raise MODULE_TIMEOUT. Modules SHOULD support cooperative cancellation by polling the signal exposed via context.

The full required and optional method/attribute surface — including conformance levels (MUST / MAY) and per-member constraints — is enumerated in the Required surface and Optional surface tables above.

Usage

The examples below use a stand-in Mailer so they run as written; replace it with a real SMTP client.

=== "Python"

```python
from typing import Any, ClassVar
import uuid

from pydantic import BaseModel, Field

from apcore import Context, Module, ModuleAnnotations, ModuleExample


class Mailer:
    """Stand-in for an SMTP client."""

    def send(self, to: str, subject: str, body: str) -> str:
        return f"msg_{uuid.uuid4().hex[:8]}"

    def close(self) -> None:
        pass


class SendEmailInput(BaseModel):
    to: str = Field(..., description="Recipient email address", pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$")
    subject: str = Field(..., description="Email subject", max_length=200)
    body: str = Field(..., description="Email body")
    cc: list[str] = Field(default=[], description="CC list")


class SendEmailOutput(BaseModel):
    success: bool = Field(..., description="Whether sending was successful")
    message_id: str | None = Field(None, description="Message ID")
    error: str | None = Field(None, description="Error message")


class SendEmailModule(Module):
    input_schema = SendEmailInput
    output_schema = SendEmailOutput
    description = "Send email to specified recipient. Uses SMTP protocol."

    tags: ClassVar[list[str]] = ["email", "notification"]
    annotations = ModuleAnnotations(open_world=True)
    examples = [
        ModuleExample(
            title="Send plain text email",
            inputs={"to": "user@example.com", "subject": "Hello", "body": "World"},
            output={"success": True, "message_id": "msg_123", "error": None},
        ),
    ]

    def on_load(self) -> None:
        self._mailer = Mailer()

    def on_unload(self) -> None:
        self._mailer.close()

    def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]:
        params = SendEmailInput(**inputs)
        try:
            msg_id = self._mailer.send(params.to, params.subject, params.body)
            return {"success": True, "message_id": msg_id, "error": None}
        except Exception as e:  # report delivery failures in the output
            return {"success": False, "message_id": None, "error": str(e)}
```

=== "TypeScript"

```typescript
import { Type } from '@sinclair/typebox';
import { APCore, createAnnotations, type Context } from 'apcore-js';

// Stand-in for an SMTP client.
async function sendEmail(to: string, subject: string, body: string): Promise<string> {
  return `msg_${Math.random().toString(16).slice(2, 10)}`;
}

const SendEmailInput = Type.Object({
  to: Type.String({ format: 'email', description: 'Recipient email address' }),
  subject: Type.String({ maxLength: 200, description: 'Email subject' }),
  body: Type.String({ description: 'Email body' }),
  cc: Type.Array(Type.String(), { default: [], description: 'CC list' }),
});

const SendEmailOutput = Type.Object({
  success: Type.Boolean({ description: 'Whether sending was successful' }),
  message_id: Type.Union([Type.String(), Type.Null()], { description: 'Message ID' }),
  error: Type.Union([Type.String(), Type.Null()], { description: 'Error message' }),
});

const client = new APCore();
client.module({
  id: 'email.send_email',
  description: 'Send email to specified recipient. Uses SMTP protocol.',
  tags: ['email', 'notification'],
  inputSchema: SendEmailInput,
  outputSchema: SendEmailOutput,
  annotations: createAnnotations({ openWorld: true }),
  execute: async (inputs: Record<string, unknown>, _ctx: Context) => {
    try {
      const messageId = await sendEmail(String(inputs.to), String(inputs.subject), String(inputs.body));
      return { success: true, message_id: messageId, error: null };
    } catch (e) {
      return { success: false, message_id: null, error: String(e) };
    }
  },
});
```

=== "Rust"

```rust
use apcore::errors::{ErrorCode, ModuleError};
use apcore::{Context, Module};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{json, Value};

/// Stand-in for an SMTP client.
pub struct Mailer;

impl Mailer {
    fn send(&self, _to: &str, _subject: &str, _body: &str) -> Result<String, String> {
        Ok("msg_123".to_string())
    }
}

#[derive(Debug, Deserialize)]
pub struct SendEmailInput {
    pub to: String,
    pub subject: String,
    pub body: String,
    #[serde(default)]
    pub cc: Vec<String>,
}

pub struct SendEmailModule {
    mailer: Mailer,
}

#[async_trait]
impl Module for SendEmailModule {
    fn description(&self) -> &str {
        "Send email to specified recipient. Uses SMTP protocol."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "to":      { "type": "string", "format": "email", "description": "Recipient email address" },
                "subject": { "type": "string", "maxLength": 200, "description": "Email subject" },
                "body":    { "type": "string", "description": "Email body" },
                "cc":      { "type": "array", "items": { "type": "string" }, "default": [], "description": "CC list" }
            },
            "required": ["to", "subject", "body"],
            "additionalProperties": false
        })
    }

    fn output_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "success":    { "type": "boolean", "description": "Whether sending was successful" },
                "message_id": { "type": ["string", "null"], "description": "Message ID" },
                "error":      { "type": ["string", "null"], "description": "Error message" }
            },
            "required": ["success"],
            "additionalProperties": false
        })
    }

    fn tags(&self) -> Vec<String> {
        vec!["email".into(), "notification".into()]
    }

    async fn execute(&self, inputs: Value, _ctx: &Context<Value>) -> Result<Value, ModuleError> {
        let input: SendEmailInput = serde_json::from_value(inputs)
            .map_err(|e| ModuleError::new(ErrorCode::GeneralInvalidInput, e.to_string()))?;
        match self.mailer.send(&input.to, &input.subject, &input.body) {
            Ok(message_id) => Ok(json!({ "success": true, "message_id": message_id, "error": null })),
            Err(e) => Ok(json!({ "success": false, "message_id": null, "error": e })),
        }
    }
}

fn main() {
    let module = SendEmailModule { mailer: Mailer };
    println!("{}", module.description());
}
```

Function-based form

=== "Python"

```python
from apcore import Context, Registry, module

registry = Registry()


@module(id="email.send", tags=["email"], registry=registry)
def send_email(to: str, subject: str, body: str, context: Context) -> dict:
    """Send email to specified recipient."""
    # context is auto-injected; not part of input_schema
    return {"success": True, "message_id": "msg_123", "error": None}
```

=== "TypeScript"

```typescript
import { Type } from '@sinclair/typebox';
import { APCore } from 'apcore-js';

const client = new APCore();
client.module({
  id: 'email.send',
  description: 'Send email to specified recipient',
  tags: ['email'],
  inputSchema: Type.Object({
    to: Type.String(),
    subject: Type.String(),
    body: Type.String(),
  }),
  outputSchema: Type.Object({
    success: Type.Boolean(),
    messageId: Type.Union([Type.String(), Type.Null()]),
    error: Type.Union([Type.String(), Type.Null()]),
  }),
  execute: async (_inputs, _ctx) => ({
    success: true,
    messageId: 'msg_123',
    error: null,
  }),
});
```

=== "Rust"

```rust
// Register a closure when the optional macros feature is disabled.
use apcore::errors::ModuleError;
use apcore::{APCore, Context};
use serde_json::{json, Value};

fn main() -> Result<(), ModuleError> {
    let mut client = APCore::new();
    client.module(
        "email.send",
        "Send email to specified recipient",
        json!({ "type": "object", "properties": {
            "to": { "type": "string" }, "subject": { "type": "string" }, "body": { "type": "string" }
        }, "required": ["to", "subject", "body"] }),
        json!({ "type": "object", "properties": {
            "success": { "type": "boolean" },
            "message_id": { "type": ["string", "null"] },
            "error": { "type": ["string", "null"] }
        }, "required": ["success"] }),
        None,
        vec!["email".into()],
        None,
        None,
        vec![],
        None,
        |_inputs: Value, _ctx: &Context<Value>| {
            Box::pin(async move {
                Ok::<Value, ModuleError>(json!({
                    "success": true, "message_id": "msg_123", "error": null
                }))
            })
        },
    )?;
    Ok(())
}
```

For YAML-based bindings and decorator details, see Decorator & YAML Bindings.

Typed module declarations

A typed declaration registers an ordinary APCore module. The typed handle invokes the registered module through the executor. An MCP adapter can use that executor to expose the same module and governance policy.

=== "Python"

`APCore.module` exposes `invoke`, `invoke_async`, `validate`, and
`preview` with the function's business signature. `with_context` attaches
a caller context. `with_approval_token` carries a resume credential.
Ordinary function calls and `raw` call the underlying function directly.
Use the governed methods for application calls and `raw` for isolated unit
tests.

A governed call passes native arguments to the registered function's
input validator. With a post-validation evaluator, native values must have
an unambiguous JSON-shaped representation under the input declaration.

<!-- executable-example: typed-module -->
```python
from apcore import APCore
from pydantic import BaseModel


class Note(BaseModel):
    note_id: str


client = APCore()


@client.module("notes.lookup", description="Look up a note")
def lookup(note_id: str) -> Note:
    return Note(note_id=note_id)


assert lookup.validate("note-1").valid
assert lookup.invoke("note-1").note_id == "note-1"
client.close()
```

=== "TypeScript"

`define` accepts validators that implement Standard Schema v1. If the
provider also implements Standard JSON Schema, Core requests Draft 2020-12
for the submitted inputs and the returned output. With validation-only
providers or conversions that cannot describe a transformation, pass
`inputSchema` and `outputSchema` explicitly on the affected side. The
handler receives normalized inputs and the caller receives the normalized
output. Both use JSON-compatible objects.

A handle belongs to its registered declaration. After replacing or
re-registering the module, use the handle returned for the new declaration.

<!-- executable-example: typed-module -->
```typescript
import assert from 'node:assert/strict';
import { APCore } from 'apcore-js';
import { z } from 'zod/v4';

const client = new APCore();
const lookup = await client.define({
  id: 'notes.lookup',
  description: 'Look up a note',
  readonly: true,
  input: z.object({ noteId: z.string().min(1) }),
  output: z.object({ noteId: z.string() }),
  execute: ({ noteId }) => ({ noteId }),
});

assert.equal((await lookup.invoke({ noteId: 'note-1' })).noteId, 'note-1');
await client.shutdown();
```

=== "Rust"

Enable the `macros` feature of `apcore` and derive Serde and
`schemars::JsonSchema` for the input and output. `ModulePack` explicitly
selects the declarations compiled into the host. Pass
`client.executor_arc()` to the Rust MCP builder to expose that pack
with the host's executor configuration.

<!-- executable-example: typed-module -->
```rust
use apcore::{APCore, ModuleError, ModulePack};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, JsonSchema, Serialize)]
struct Note {
    note_id: String,
}

/// Look up a note.
#[apcore::module(id = "notes.lookup", readonly = true)]
async fn lookup(input: Note) -> Result<Note, ModuleError> {
    Ok(input)
}

const NOTES: ModulePack = ModulePack::new(&[lookup::DECLARATION]);

#[tokio::main]
async fn main() -> Result<(), ModuleError> {
    let client = APCore::new();
    NOTES.register(&client)?;
    let note = lookup::HANDLE
        .invoke(&client, Note { note_id: "note-1".into() }, None)
        .await?;
    assert_eq!(note.note_id, "note-1");
    Ok(())
}
```

When the executor has a post-validation evaluator, both the evaluator and final approval receive the validated arguments. The default approval gate retains its early position in the execution pipeline. See Approval System for the two approval timings.

Dependencies

Testing Strategy

  • Conformance tests assert that minimal modules with only required surface register and execute successfully.
  • Negative tests assert that missing input_schema/output_schema/description/execute produces clear errors at registration time.
  • Lifecycle tests cover on_load/on_unload ordering, on_suspend/on_resume round-trip, and exception isolation.
  • Sync/async dispatch tests cover both def and async def modules invoked through call() and call_async().
  • Function-based form tests verify schema generation parity with class form.

Contract: Module.preview

Optional method. A module that does not implement it is conformant; the framework treats its absence as "no preview available" and never synthesizes one.

Inputs

  • inputs (dict/object/Value, required) — the same call arguments execute() would receive
  • context (Context, required) — the per-call context

Errors

  • No errors are defined by this contract. A preview is advisory: an implementation that cannot produce one SHOULD decline by not implementing the method, rather than raising from it.

Returns

  • On success: dict/object/Value — a low-fidelity result an AI agent can use to verify its plan before committing to execution. It is not required to equal what execute() would return, and callers MUST NOT treat it as an authoritative result.
  • Surfaced through Executor.validate() as the optional module_preview check, appended only when the target module implements this hook (see Contract: APCore.validate).

Properties

  • async: language-dependent, matching the module's own execute() dispatch model
  • thread_safe: true — MUST tolerate concurrent invocation, since preview runs on the same pipeline as any other call
  • pure: true — this is the defining constraint. preview() MUST NOT perform the side effects execute() would. A preview that writes, sends, charges, or deletes defeats the only reason the hook exists.
  • idempotent: true — a consequence of the purity requirement

Contract: Module.as_streaming

SDK Scope: Rust only. Python and TypeScript resolve the streaming surface structurally — a @runtime_checkable Protocol and a Symbol.for("apcore.streaming") marker respectively — so neither needs an accessor to obtain a typed handle. See Streaming Module Interface.

Inputs

  • No inputs (a &self accessor on the base Module trait)

Errors

  • No errors raised. Absence of a streaming surface is reported as None, not as a failure.

Returns

  • On success: Option<&dyn StreamingModule> — Some(self) for a module that streams, None otherwise. The default trait implementation returns None, so a non-streaming module inherits correct behavior without writing anything.

Properties

  • async: false
  • thread_safe: true
  • pure: true — a type-level accessor; it MUST NOT begin a stream, allocate a buffer, or otherwise observe or mutate module state
  • idempotent: true

Consistency requirement

as_streaming() and Module::stream() MUST agree for every module: both return Some(_), or both return None. A module answering Some here while stream() returns None hands adapter code a typed handle to a surface that then refuses to produce anything — and the reverse hides a working stream from every bridge that resolves it through this accessor.

Mapping to AI Protocols

Standard apcore field Anthropic A2A MCP
description description AgentSkill.description description
examples input_examples AgentSkill.examples Placed in _meta
annotations.requires_approval Tool-use confirmation Skill consent flag requires_approval annotation

For full type mapping across languages, see Type Mapping.

Next Steps