MCPcopy
hub / github.com/MetapriseAI/OrgKernel

github.com/MetapriseAI/OrgKernel @main sqlite

repository ↗ · DeepWiki ↗
221 symbols 699 edges 14 files 149 documented · 67%
README

OrgKernel

Enterprise Trust Layer for AI Agents

Cryptographically secure identity, scoped execution, and tamper-evident audit trails —

transparent by design, not by promise.

License: Apache 2.0 GitHub Stars GitHub Issues Pull Requests Python 3.10+ FastAPI PostgreSQL

3 Core Modules (Phase 1)  ·  27 REST Endpoints  ·  5 Build Phases  ·  PostgreSQL / MySQL / SQLite Persistence


Overview

OrgKernel is the security and governance foundation for the AI Agent system. It ensures every agent has a verifiable cryptographic identity, every mission operates within strict boundaries, and every action leaves a tamper-evident audit trail — all without a running AI model.

Phase 1 delivers the three cryptographic primitives. Phases 2–5 add mission lifecycle, policy engine, authority graph, and tool gateway.

Capability Status Description
Cryptographic Identity (PKI) ✅ Phase 1 Ed25519 keypairs, Org CA signing, CSR, and challenge-response verification
Scoped Execution Tokens ✅ Phase 1 Mission-scoped permission tokens with tool allowlists, numeric parameter bounds, and Ed25519 signatures to prevent token grafting
Hash-Chained Audit Trail ✅ Phase 1 Three-layer audit (IDENTITY / EXECUTION / COMPLIANCE) persisted to PostgreSQL with SHA-256 hash chaining and integrity verification
Mission Lifecycle 🔲 Phase 2 8-state mission state machine with enforced transitions
Tool Gateway 🔲 Phase 3 Token scope enforcement before every external tool call
Policy Engine 🔲 Phase 3 Declarative policy CRUD with version history and constraint derivation
Authority Graph 🔲 Phase 3 Org hierarchy traversal, approval level determination, spend authority resolution
Data Classifier 🔲 Phase 3 Rule-based data classification producing routing tiers and scope constraints

Build Phases

Phase Status Scope
Phase 1 ✅ Complete Core primitives: Identity, Token, Audit
Phase 2 🔲 Planned Mission lifecycle with state machine
Phase 3 🔲 Planned Gateway, Policy, Authority, Classifier
Phase 4 🔲 Planned Full DB persistence & version history
Phase 5 🔲 Planned Optimization & Iteration

System Architecture

OrgKernel currently orchestrates three services (Phase 1). When Phases 2–5 are complete, the full flow will be: Mission Launch → Approval → Tool Execution → Close/Escalate, with every phase writing to a specific audit layer.

Complete Flow — Five Phases (Phases 2–5 not yet implemented)

Phase Component(s) Called Audit Layer Key Behavior
1 Mission Launch (Phase 1 available) AgentIdentityService L1 Business Validates agent identity before any operation
2 State Transition (Phase 2 — planned) MissionService.submit() L2 Execution Mission enters approval queue
3 Triple Review (Phase 3 — planned) PolicyEngine + AuthorityGraph + DataClassifier L2 Execution Constraints frozen into MissionBoundary. ExecutionTokenService.mint() issues signed token
4 Tool Execution (Phase 3 — planned) ToolGatewayService.validate_tool_call() L2 Execution Five gateway checks on every call: token valid, CA signature correct, agent_id match, tool in scope, tool not forbidden
5 Mission Close (Phase 2 — planned) MissionService.close() L2 Execution Token consumed, state → CLOSED
6 Escalation (Phase 2 — planned) MissionService.escalate() L3 Compliance Only path to L3 audit layer

Three-Layer Audit Semantics (Phase 1)

Audit Layer Triggered By Semantics
L1 Business AuditChainService.initialize() Business perspective: who, in which org, for which mission
L2 Execution Every tool call + state transition + approval + close Execution perspective: every behavior the system performed
L3 Compliance Only MissionService.escalate() (Phase 2) Compliance perspective: what triggered human compliance intervention

Architecture Diagram (Phase 1)

Agent Platform
    |
    |-- CSR submitted --> AgentIdentityService.submit_csr()
    |                      |-- validates duplicate
    |                      v
    |-- CSR issued -----> AgentIdentityService.issue_from_csr()
    |                      |-- generates Ed25519 keypair (server-side)
    |                      |-- signs certificate with Org CA
    |                      |-- returns certificate + private_key_pem ONCE
    |                      |-- persists identity record (NO private key)
    |                      v
    |                  AgentCertificate + AgentIdentity
    |
    |-- token mint ----> ExecutionTokenService.mint()
    |                      |-- Ed25519-signed by Org CA (prevents Token Grafting)
    |                      |-- tool allowlist + numeric bounds
    |                      v
    |                  ExecutionToken
    |
    |-- scope check ---> ExecutionTokenService.check_scope()
    |                      |-- tool in scope?
    |                      |-- bounded params within limits?
    |                      v
    |                  ScopeCheckResponse (ALLOWED or BLOCKED)
    |
    |-- audit init ----> AuditChainService.initialize()
    |                      |-- writes genesis IDENTITY entry (SHA-256)
    |                      v
    |-- audit append ---> AuditChainService.append()
    |                      |-- SHA-256 prev_hash chain
    |                      v
    |-- audit verify ---> AuditChainService.verify_integrity()
                           |-- recomputes all hashes
                           |-- detects deletion / tampering / reorder

Challenge-Response Authentication (Phase 1)

Step Party Action
1 Verifier Calls AgentIdentityService.request_challenge(agent_id, issued_by) — generates random nonce + challenge_id, stored in memory with 5-minute TTL
2 Verifier → Agent Sends nonce to the target Agent
3 Agent Signs the nonce with its Ed25519 private key, constructs ChallengeResponse(challenge_id, nonce, public_key, signature)
4 Verifier Calls AgentIdentityService.verify_challenge(response) — validates: nonce one-time use (anti-replay), Ed25519 signature correct, certificate ACTIVE and not expired

Attack vectors prevented: Replay attack (nonce consumed after one use), private key theft (signature must match nonce), Token Grafting (token.agent_id == caller.agent_id verified at every scope check).


Core Modules

Module 01 — Agent Identity ✅ Phase 1

PKI lifecycle management for AI agents. Generates Ed25519 keypairs, issues certificates signed by an Org CA, and manages the full revoke / suspend / reactivate lifecycle.

Tags: Ed25519 CSR Challenge-Response Revocation

Module 02 — Execution Token ✅ Phase 1

Scoped, time-bounded permission tokens for mission execution. Each token carries a tool allowlist, numeric parameter bounds, and an Ed25519 signature to prevent token grafting attacks.

Tags: Tool Scope Bounded Params Ed25519 Sig Expiry

Module 03 — Mission Lifecycle 🔲 Phase 2

8-state mission state machine: CREATED → PLANNING → WAITING_APPROVAL → APPROVED → PENDING_EXECUTION → IN_PROGRESS → EXECUTED → CLOSED. Materializes boundaries at approval time.

Tags: 8 States State Transitions Boundary Snapshot REST API

Module 04 — Tool Gateway 🔲 Phase 3

Enforces token scope before every external tool call. Validates the token signature, checks tool in scope, verifies bounded params, and writes execution audit entries. Prevents Token Grafting attacks at runtime.

Tags: Scope Guard Token Grafting Prevention Param Bounds ALLOWED/BLOCKED/PARTIAL

Module 05 — Policy Engine 🔲 Phase 3

Declarative policy CRUD with version history and audit trail. Evaluates rules at mission approval time to derive forbidden tools, time restrictions, spend limits, and dual-approval requirements.

Tags: Policy CRUD Version History Rule Evaluation 6 Policy Types

Module 06 — Authority Graph 🔲 Phase 3

Org hierarchy traversal and approval level resolution. Maps agents to org units, determines L0-L5 approval requirements, builds multi-step approval chains, and resolves spend authority for mission authorization.

Tags: Org Hierarchy L0-L5 Approval Spend Authority Approval Chain

Module 07 — Data Classifier 🔲 Phase 3

Classifies data sources accessed by a mission's tools using rule-based classification. Produces a routing classification (PUBLIC to TOP_SECRET) and data scope constraints for the MissionBoundary.

Tags: 5 Tiers 5 Scopes Rule Engine Data Constraints

Module 08 — Audit Chain ✅ Phase 1

Three-layer, hash-chained audit logging persisted to the database. Each layer (IDENTITY, EXECUTION, COMPLIANCE) maintains its own SHA-256 hash chain with integrity verification. REST API exposes chain query and cryptographic integrity checks.

Tags: 3 Audit Layers SHA-256 Chain Integrity Verify REST API


Mission 8-State Lifecycle 🔲 Phase 2 (planned)

Every mission follows this state machine once Phase 2 is implemented. Invalid transitions raise InvalidStateTransitionError. All transitions are audited via the L2 Execution layer.

Valid Transitions

From State Allowed Transitions How It Happens
CREATED PLANNING Only path — set by launch() internally
PLANNING WAITING_APPROVAL or → APPROVED submit() goes to WAITING_APPROVAL; L0 agents can self-approve → APPROVED directly
WAITING_APPROVAL APPROVED or → CLOSED approve()APPROVED; reject() or close(CANCELLED)CLOSED
APPROVED PENDING_EXECUTION or → IN_PROGRESS start_execution() skips queue → IN_PROGRESS directly; otherwise → PENDING_EXECUTION
PENDING_EXECUTION IN_PROGRESS or → WAITING_APPROVAL or → CLOSED Normal start → IN_PROGRESS; rollback → WAITING_APPROVAL; close(CANCELLED)CLOSED
IN_PROGRESS EXECUTED or → WAITING_APPROVAL or → CLOSED complete_execution()EXECUTED; rollback → WAITING_APPROVAL; close() or escalate()CLOSED
EXECUTED CLOSED Only path — close() with SUCCESS or FAILED
CLOSED none Terminal — no further transitions allowed

State Diagram

CREATED --> PLANNING --> WAITING_APPROVAL
                |              |
                |         reject/close(CANCELLED)
                |              |
                +-----> APPROVED <-----------+
                (L0 self-approval)           |
                                 |           |
                                 v           |
                        PENDING_EXECUTION    |
                                 |      rollback
                                 v           |
                           IN_PROGRESS ------+
                                 |
                                 v
                            EXECUTED --> CLOSED (terminal)

Escape to CLOSED from: WAITING_APPROVAL, PENDING_EXECUTION, IN_PROGRESS
Only escalate() writes L3 Compliance — all other CLOSE writes L2

Security Model

Token Grafting Prevention

The Execution Token is Ed25519-signed by the Org CA covering the full payload (scope, bounds, expiry). Any modification invalidates the signature. The scope check verifies token.agent_id == caller.agent_id on every call.

Challenge-Response Authentication

Agents prove identity via Ed25519 challenge-response with one-time nonces. Certificates are verified against the Org CA's public key. Revocation and expiry are enforced at verification time.

Tamper-Evident Audit Chain

Every audit entry carries a SHA-256 hash of its content and a prev_hash linking to the previous entry. The integrity API recomputes all hashes and detects any deleted, modified, or reordered entries.

Audit Chain Integrity Checks

Check Detects
Hash present Hash stripped by attacker
Sequence continuity (IDs increment by 1) Entry deletion
prev_hash linkage Entry modification or reordering
Content hash match (stored == recomputed SHA-256) Entry content tampering

Quick Start

Install

Requires Python 3.10+. From a local checkout:

cd /path/to/orgkernel
pip install -e ".[postgres]"   # postgres | mysql | sqlite

Database driver extras: - pip install orgkernel[postgres] — PostgreSQL (recommended) - pip install orgkernel[mysql] — MySQL / MariaDB - pip install orgkernel[sqlite] — SQLite for local dev

Service layer

Direct Python async — no HTTP, no API key.

```python from datetime import datetime, timedelta, timezone from sqlalchemy.ext.asyncio import AsyncSession

from orgkernel.database import async_engine, i

Core symbols most depended-on inside this repo

get_by_id
called by 7
src/orgkernel/services/agent_identity_service.py
append
called by 7
src/orgkernel/services/audit_chain_service.py
_model_to_pydantic
called by 6
src/orgkernel/services/execution_token_service.py
_ensure_ca_keypair
called by 5
src/orgkernel/crypto_utils.py
_model_to_out
called by 5
src/orgkernel/services/execution_token_service.py
_now_utc
called by 5
src/orgkernel/services/agent_identity_service.py
sign_payload
called by 4
src/orgkernel/crypto_utils.py
_model_to_pydantic
called by 4
src/orgkernel/services/agent_identity_service.py

Shape

Method 83
Function 75
Class 35
Route 28

Languages

Python100%

Modules by API surface

src/orgkernel/pyapi/router.py62 symbols
src/orgkernel/schemas/agent_identity.py35 symbols
src/orgkernel/services/agent_identity_service.py28 symbols
src/orgkernel/schemas/execution_token.py23 symbols
src/orgkernel/services/execution_token_service.py20 symbols
src/orgkernel/schemas/audit_chain.py19 symbols
src/orgkernel/services/audit_chain_service.py15 symbols
src/orgkernel/crypto_utils.py10 symbols
src/orgkernel/models.py5 symbols
src/orgkernel/database.py4 symbols

Dependencies from manifests, versioned

cryptography41.0 · 1×
fastapi0.109 · 1×
pydantic2.0 · 1×
sqlalchemy2.0 · 1×

Datastores touched

(mysql)Database · 1 repos
orgkernelDatabase · 1 repos

For agents

$ claude mcp add OrgKernel \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact