Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 28 additions & 7 deletions .github/workflows/packages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ jobs:
"$temporary/venv/bin/python" -c 'from importlib.resources import files; assert files("apcore").joinpath("py.typed").is_file(), "installed wheel is missing apcore/py.typed"'
python3 "$GITHUB_WORKSPACE/conformance/extract_doc_examples.py" python "$temporary"
(cd quick-start && "$temporary/venv/bin/python" -I example.py)
(cd typed-module && "$temporary/venv/bin/python" -I example.py)
python -m venv "$temporary/full"
"$temporary/full/bin/python" -m pip install "${wheel[0]}[all]"
"$temporary/full/bin/python" -m pip check
Expand All @@ -65,17 +66,26 @@ jobs:
- uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc
with:
toolchain: 1.86.0
- run: cargo package --locked --all-features
- name: Package the macro and its SDK
shell: bash
run: |
cargo package --locked -p apcore-macros
# Cargo resolves the normalized SDK manifest against crates.io.
# Provide the same macro locally while the candidate is unpublished.
cargo --config "patch.crates-io.apcore-macros.path='$PWD/apcore-macros'" \
package --locked -p apcore --all-features
- name: Run downstream examples against the packaged crate
shell: bash
env:
CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS: fallback
run: |
archives=( "$PWD"/target/package/*.crate )
sdk=( "$PWD"/target/package/apcore-[0-9]*.crate )
macro=( "$PWD"/target/package/apcore-macros-[0-9]*.crate )
temporary=$(mktemp -d)
cd "$temporary"
mkdir sdk
tar -xzf "${archives[0]}" --strip-components=1 -C sdk
mkdir sdk macros
tar -xzf "${sdk[0]}" --strip-components=1 -C sdk
tar -xzf "${macro[0]}" --strip-components=1 -C macros
cp sdk/Cargo.lock Cargo.lock
python3 "$GITHUB_WORKSPACE/conformance/extract_doc_examples.py" rust "$temporary"
cat > Cargo.toml <<'EOF'
Expand All @@ -86,22 +96,32 @@ jobs:
rust-version = "1.86"

[dependencies]
apcore = { path = "sdk", features = ["config", "events"] }
apcore = { path = "sdk", features = ["config", "events", "macros"] }
async-trait = "0.1.92"
futures-util = "0.3"
schemars = "0.8"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

[patch.crates-io]
apcore-macros = { path = "macros" }

[[bin]]
name = "quick-start"
path = "quick-start/example.rs"

[[bin]]
name = "governed-stream"
path = "governed-stream/example.rs"

[[bin]]
name = "typed-module"
path = "typed-module/example.rs"
EOF
(cd quick-start && cargo run --quiet --manifest-path ../Cargo.toml --bin quick-start)
(cd governed-stream && cargo run --locked --quiet --manifest-path ../Cargo.toml --bin governed-stream)
(cd typed-module && cargo run --locked --quiet --manifest-path ../Cargo.toml --bin typed-module)
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: core-rust-distribution
Expand Down Expand Up @@ -137,7 +157,7 @@ jobs:
cd "$temporary"
npm init -y
npm pkg set type=module
npm install --ignore-scripts "${archive[0]}" typescript@5.5.4 @types/node@20
npm install --ignore-scripts "${archive[0]}" typescript@5.5.4 @types/node@20 zod@4
node --input-type=module -e 'import {APCore} from "apcore-js"; import "apcore-js/context-keys"; if (!APCore) throw new Error("APCore is missing");'
cat > verify-browser.mjs <<'EOF'
const url = await import.meta.resolve("apcore-js");
Expand All @@ -150,9 +170,10 @@ jobs:
node --input-type=module -e 'import {APCore} from "apcore-js/full"; import {Config} from "apcore-js/config"; import {createFilesystemDiscoveryPlugin} from "apcore-js/discovery"; if (!new APCore({config: new Config(), plugins: [createFilesystemDiscoveryPlugin()]}).registry) throw new Error("invalid full assembly");'
python3 "$GITHUB_WORKSPACE/conformance/extract_doc_examples.py" typescript "$temporary"
./node_modules/.bin/tsc --strict --module NodeNext --target ES2022 --rootDir . --outDir compiled \
quick-start/example.ts governed-stream/example.ts
quick-start/example.ts governed-stream/example.ts typed-module/example.ts
(cd quick-start && node ../compiled/quick-start/example.js)
(cd governed-stream && node ../compiled/governed-stream/example.js)
(cd typed-module && node ../compiled/typed-module/example.js)
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: core-npm-distribution
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/sdk-rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ jobs:
CONFORMANCE_SPEC_REPO: ${{ github.workspace }}

- name: Run tests
run: cargo test --locked --all-features
run: cargo test --locked --workspace --all-features
env:
CONFORMANCE_SPEC_REPO: ${{ github.workspace }}

Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Add governed typed Python module handles, TypeScript Standard Schema declarations, and optional Rust module macros and packs.
- Provide explicit configuration, discovery, and full runtime assemblies. The default profile supports in-memory execution from installed Python, TypeScript, and Rust packages.
- Add the pure TypeScript Prometheus text renderer and host-owned subscriber factories for configured event delivery.
- **Protocol 2.0.0 draft revision 2.** Add opt-in policy evaluation after input validation. The enabled pipeline combines approval requirements at one gate, binds approval to the selected module version and effective arguments, and enforces the gate before ordinary and streaming execution. Final-scope pending approvals require an explicitly compatible scoped handler.
Expand Down
1 change: 1 addition & 0 deletions conformance/extract_doc_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ def main() -> None:
(STREAM_GUIDE, "governed-stream", args.language, f"governed-stream/example.{ext}"),
(STREAM_GUIDE, "stream-config", "yaml", "governed-stream/apcore.yaml"),
(STREAM_GUIDE, "stream-acl", "yaml", "governed-stream/acl/global_acl.yaml"),
("docs/features/module-interface.md", "typed-module", args.language, f"typed-module/example.{ext}"),
)
try:
files = [(args.destination / target, example(source, label, lang)) for source, label, lang, target in sources]
Expand Down
121 changes: 120 additions & 1 deletion docs/features/module-interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ The examples below use a stand-in `Mailer` so they run as written; replace it wi
=== "Rust"

```rust
// Rust has no attribute macro; register a closure with APCore::module().
// Register a closure when the optional macros feature is disabled.
use apcore::errors::ModuleError;
use apcore::{APCore, Context};
use serde_json::{json, Value};
Expand Down Expand Up @@ -524,6 +524,125 @@ The examples below use a stand-in `Mailer` so they run as written; replace it wi

For YAML-based bindings and decorator details, see [Decorator & YAML Bindings](./decorator-bindings.md).

### 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](./approval-system.md) for the two approval timings.

## Dependencies

- [Schema System](./schema-system.md) — input/output schema loading and validation.
Expand Down
6 changes: 3 additions & 3 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ A schema makes a capability contract machine-readable and validatable. It does n
| Component | Package | Stable | In development |
|---|---|---|---|
| Protocol specification | [protocol-spec.md](spec/protocol-spec.md) | `1.66.0` | `2.0.0` (draft revision 4) |
| Python SDK | `apcore` | `0.33.0` | `1.0.0a5` |
| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.5` |
| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.5` |
| Python SDK | `apcore` | `0.33.0` | `1.0.0a6` |
| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.6` |
| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.6` |

The protocol `2.0.0` draft defines the contract for the SDK `1.0.0` release line. The three core SDKs share that release line. Surface adapters (`apcore-mcp`, `apcore-a2a`, `apcore-cli`, `apcore-toolkit`) are versioned independently and declare the core range they support in their package metadata.

Expand Down
11 changes: 9 additions & 2 deletions examples/python/golden-path/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Python Golden Path

Register an existing application function as an APCore module and call it from Python and through MCP. The two executors use the same notebook, module definitions, and governance policy. Each uses an in-memory approval store. The MCP server binds to a temporary loopback port and uses the local process as its trust boundary.
Register an application function as an APCore module and invoke it through a typed Python handle and through MCP. The two executors use the same notebook, module definitions, and governance policy. Each uses an in-memory approval store. The MCP server binds to a temporary loopback port and uses the local process as its trust boundary.

## Run the example

Expand All @@ -20,8 +20,15 @@ Set `APCORE_WHEEL` and `APCORE_MCP_WHEEL` to the absolute paths of the Core and

1. `app.py` registers the notebook's archive operation with an input type inferred from the function signature and an output schema inferred from `ArchiveResult`. It marks the operation as destructive and configures `ExecutionPolicy(strict=True, gate_destructive=True)`.
2. `verify.py` checks a normal lookup, an ACL denial, and invalid input through both entry points. An archive request stays pending until the reviewer records a decision.
3. In Python, the verifier resolves the pending result's public `audit_id` in the store. It retries the same arguments through Core with the private `approval_id` in the reserved `_approval_token` field.
3. In Python, the verifier resolves the pending result's public `audit_id` in the store. It passes the private `approval_id` to `archive.with_approval_token(...)` and invokes the handle again with the same business argument. The handle returns an `ArchiveResult` model.
4. Through MCP, the verifier reads `approvalId` and `resumeToken` from the pending tool result's `_meta.apcore.approval`. It polls `__apcore_approval_check` with the public ID, resolves the request, and checks that the status changes to approved. It then retries the original tool arguments with the private token in request `_meta.approvalId`.
5. The verifier checks that each archive executes once and prints the ACL decisions with trace ID, caller ID, and target ID. The approval credential stays out of the audit output.

The in-memory stores are for this local example. A deployed application can use an authenticated review service and a persistent scoped approval store.

## In-process agent tool

Install `openai-agents` to use `archive_tool(archive)` from `agent_tool.py`.
Pass the returned tool to `Agent(..., tools=[...])`. The tool calls the same
governed handle as the direct example. The host's approval handler still decides
whether an archive may run. [OpenAI Agents SDK function tools](https://openai.github.io/openai-agents-python/tools/#function-tools)
15 changes: 15 additions & 0 deletions examples/python/golden-path/agent_tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""Expose the same governed archive operation to an in-process Agents SDK agent."""

from agents import FunctionTool, function_tool
from apcore import BoundModule
from app import ArchiveResult


def archive_tool(archive: BoundModule[[str], ArchiveResult]) -> FunctionTool:
@function_tool
async def archive_note(note_id: str) -> str:
"""Archive a note by its ID."""
result = await archive.invoke_async(note_id)
return result.model_dump_json()

return archive_note
8 changes: 4 additions & 4 deletions examples/python/golden-path/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from dataclasses import dataclass, field

from apcore import ACL, ACLRule, APCore, ExecutionPolicy
from apcore import ACL, ACLRule, APCore, BoundModule, ExecutionPolicy
from apcore.acl import AuditEntry
from apcore_mcp import APCoreMCP, InMemoryApprovalStore
from pydantic import BaseModel
Expand All @@ -25,7 +25,7 @@ def archive(self, note_id: str) -> ArchiveResult:
return ArchiveResult(archived=note_id)


def build_app(notebook: Notebook, audit: list[AuditEntry]) -> APCore:
def build_app(notebook: Notebook, audit: list[AuditEntry]) -> tuple[APCore, BoundModule[[str], ArchiveResult]]:
client = APCore(policy=ExecutionPolicy(strict=True, gate_destructive=True))
client.executor.set_acl(
ACL(
Expand All @@ -35,7 +35,7 @@ def build_app(notebook: Notebook, audit: list[AuditEntry]) -> APCore:
)
)

@client.module(ARCHIVE, description="Archive a note", annotations={"destructive": True})
@client.module(ARCHIVE, description="Archive a note", destructive=True, requires_approval=True)
def archive(note_id: str) -> ArchiveResult:
return notebook.archive(note_id)

Expand All @@ -47,7 +47,7 @@ def lookup(note_id: str) -> dict[str, bool]:
def restricted() -> dict[str, bool]:
raise AssertionError("The ACL must prevent this function from running")

return client
return client, archive


def build_mcp(client: APCore, reviews: InMemoryApprovalStore) -> APCoreMCP:
Expand Down
Loading
Loading