# Architecture

URL: https://docs.hanzo.ai/docs/zap/overview/architecture

> ZAP system architecture and component design

This document describes the internal architecture of the ZAP protocol and its key components.

## System Overview

```text
+------------------------------------------------------------------+
|                        Agent Application                          |
+------------------------------------------------------------------+
                              |
                              v
+------------------------------------------------------------------+
|                         ZAP Client                                |
|  +-------------+  +-------------+  +-------------+               |
|  | RPC Layer   |  | Security    |  | Connection  |               |
|  | (Cap'n      |  | (PQ-TLS,    |  | Manager     |               |
|  |  Proto)     |  |  DID)       |  |             |               |
|  +-------------+  +-------------+  +-------------+               |
+------------------------------------------------------------------+
                              |
                      Wire Protocol
                              |
                              v
+------------------------------------------------------------------+
|                        ZAP Server                                 |
|  +-------------+  +-------------+  +-------------+               |
|  | Gateway     |  | Coordinator |  | Consensus   |               |
|  | (MCP Bridge)|  | (Discovery) |  | (Corona)  |               |
|  +-------------+  +-------------+  +-------------+               |
+------------------------------------------------------------------+
```

## Core Components

### ZAP Interface

The primary interface for tool/resource operations:

```c
interface Zap {
  # Initialize connection with capability exchange
  init @0 (client :ClientInfo) -> (server :ServerInfo);

  # Tool operations
  listTools @1 () -> (tools :ToolList);
  callTool @2 (call :ToolCall) -> (result :ToolResult);

  # Resource operations
  listResources @3 () -> (resources :ResourceList);
  readResource @4 (uri :Text) -> (content :ResourceContent);
  subscribe @5 (uri :Text) -> (stream :ResourceStream);

  # Prompt operations
  listPrompts @6 () -> (prompts :PromptList);
  getPrompt @7 (name :Text, args :Metadata) -> (messages :List(PromptMessage));

  # Logging
  log @8 (level :LogLevel, message :Text, data :Data);
}
```

### Gateway

Bridges MCP and ZAP servers:

```c
interface Gateway extends(Zap) {
  addServer @0 (name :Text, url :Text, config :ServerConfig) -> (id :Text);
  removeServer @1 (id :Text) -> ();
  listServers @2 () -> (servers :List(ConnectedServer));
  serverStatus @3 (id :Text) -> (status :ServerStatus);
}
```

Transport configuration:

```c
struct ServerConfig {
  transport @0 :Transport;
  auth @1 :Auth;
  timeout @2 :UInt32;  # milliseconds

  enum Transport {
    stdio @0;
    http @1;
    websocket @2;
    zap @3;
    unix @4;
  }
}
```

### Coordinator

Agent discovery and registration:

```c
interface Coordinator {
  register @0 (agent :AgentInfo) -> (id :Text, gateway :Gateway);
  heartbeat @1 (id :Text) -> (ok :Bool);
  discover @2 (filter :AgentFilter) -> (agents :List(AgentInfo));
}
```

## Security Architecture

### Post-Quantum Handshake

```text
Client                                Server
  |                                      |
  |  PQHandshakeInit                     |
  |  (X25519 pub, ML-KEM pub, nonce)     |
  |------------------------------------->|
  |                                      |
  |  PQHandshakeResponse                 |
  |  (X25519 pub, ML-KEM ct, sig)        |
  |<-------------------------------------|
  |                                      |
  |  [Derive shared secret from both]    |
  |  [X25519 DH + ML-KEM decapsulation]  |
  |                                      |
  |  PQChannelMessage (encrypted RPC)    |
  |<------------------------------------>|
```

Key derivation:

1. Perform X25519 Diffie-Hellman
2. Decapsulate ML-KEM ciphertext
3. HKDF-SHA256(X25519\_secret || ML-KEM\_secret)

### Channel Security

```c
struct PQChannelMessage {
  sequence @0 :UInt64;       # Replay protection
  ciphertext @1 :Data;       # AEAD encrypted
  tag @2 :Data;              # Authentication tag
  associatedData @3 :Data;   # Plaintext metadata
}
```

## Consensus Architecture

### Corona Threshold Signing

Two-round protocol for distributed signatures:

```text
Round 1: Commitment
  Each party i:
    - Sample random r_i
    - Compute D_i = A * r_i
    - Broadcast D_i with MACs

Round 2: Response
  Each party i:
    - Receive all D_j
    - Compute challenge c = H(D_1 || ... || D_k || message)
    - Compute z_i = r_i + c * s_i (secret share)
    - Broadcast z_i

Finalization:
  Combiner:
    - Verify all z_i against D_i
    - Compute z = sum(z_i)
    - Compute delta correction
    - Output signature (c, z, delta)
```

### Agent Consensus

Voting-based response aggregation:

```c
struct AgentConsensusConfig {
  threshold @0 :Float64;        # Required vote fraction
  minResponses @1 :UInt32;      # Minimum responses
  timeoutSecs @2 :UInt32;       # Query timeout
  requireSignatures @3 :Bool;   # Require agent signatures
}
```

Consensus flow:

1. Submit query to all agents
2. Collect responses with optional signatures
3. Hash responses and count votes
4. Return majority response if threshold met

## Identity Architecture

### W3C DID Document

```c
struct DidDocument {
  context @0 :List(Text);
  id @1 :Text;
  controller @2 :Text;

  verificationMethod @3 :List(VerificationMethod);

  # Verification relationships
  authentication @4 :List(Text);
  assertionMethod @5 :List(Text);
  keyAgreement @6 :List(Text);
  capabilityInvocation @7 :List(Text);
  capabilityDelegation @8 :List(Text);

  service @9 :List(Service);
}
```

### DID Methods

| Method  | Anchoring       | Use Case             |
| ------- | --------------- | -------------------- |
| did:lux | Lux blockchain  | Production, staking  |
| did:key | Self-certifying | Development, testing |
| did:web | DNS             | Web integration      |

## Data Flow

### Tool Invocation

```text
1. Client calls callTool(ToolCall)
2. Gateway routes to appropriate server
3. Server executes tool
4. Server returns ToolResult
5. Gateway relays to client
```

### Resource Streaming

```text
1. Client calls subscribe(uri)
2. Server returns ResourceStream capability
3. Client calls stream.next() in loop
4. Server pushes ResourceContent updates
5. Client calls stream.cancel() when done
```

### Multi-Agent Consensus

```text
1. Coordinator receives query
2. Query broadcast to registered agents
3. Agents submit responses
4. Consensus service tallies votes
5. Majority response returned
```

## Deployment Patterns

### Single Agent

```text
Agent <---> ZAP Server
```

### Gateway Aggregation

```text
Agent <---> Gateway <---> MCP Server 1
                    <---> MCP Server 2
                    <---> ZAP Server 1
```

### Coordinated Agents

```text
Agent 1 <--+
           |
Agent 2 <--+--> Coordinator <---> Gateway <---> Servers
           |
Agent 3 <--+
```

### Threshold Signing

```text
Agent 1 <--+
           |
Agent 2 <--+--> Corona Coordinator ---> Blockchain
           |
Agent 3 <--+
```
