Skip to content

alinaqi/ocp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

Organizational Consciousness Protocol (OCP) v1.0

An Extension to the Agent-to-Agent (A2A) Protocol

Status: Draft Specification v1.0
Date: October 2025
Authors: Ali Naqi Shaheen Based on: A2A Protocol (https://a2a-protocol.org/latest/)


Table of Contents

  1. Introduction
  2. Protocol Overview
  3. Core Principles
  4. Message Format
  5. Message Types
  6. Transport Layer
  7. Discovery & Capabilities
  8. Security Model
  9. A2A Compatibility
  10. Implementation Guide

1. Introduction

1.1 Purpose

The Organizational Consciousness Protocol (OCP) extends the Agent-to-Agent (A2A) protocol to enable distributed, collective intelligence across teams of AI agents. While A2A provides excellent primitives for task delegation and tool invocation, it lacks mechanisms for:

  • Streaming knowledge updates between agents
  • Publish/subscribe patterns for event-driven coordination
  • Bidirectional synchronization of distributed state
  • Collective query and consensus formation
  • Real-time awareness of agent activities and context

OCP fills these gaps while maintaining full compatibility with the A2A standard.

1.2 Use Cases

OCP enables:

  • Distributed Knowledge Management: Agents share learnings automatically
  • Collective Intelligence: Query multiple agents and synthesize responses
  • Team Coordination: Real-time awareness of what team members are working on
  • Consensus Building: Distributed decision-making across agent networks
  • Event-Driven Architecture: Agents react to events in real-time

1.3 Relationship to A2A

┌─────────────────────────────────────────────────────┐ │ OCP (Organizational Consciousness Protocol) │ │ Extension Layer │ │ - Knowledge streaming │ │ - Pub/sub messaging │ │ - Collective operations │ │ - Consensus mechanisms │ └─────────────────────────────────────────────────────┘

↓ Extends

┌─────────────────────────────────────────────────────┐ │ A2A (Agent-to-Agent Protocol) │ │ Foundation Layer │ │ - Agent identity (a2a:// URIs) │ │ - Discovery protocol │ │ - Task delegation │ │ - Tool invocation │ └─────────────────────────────────────────────────────┘

OCP agents MUST support the A2A core protocol and MAY support OCP extensions. Pure A2A agents can interact with OCP agents using standard A2A messages.


2. Protocol Overview

2.1 Design Philosophy

OCP is designed around five core patterns:

  1. Streaming: Continuous flow of updates rather than request/response
  2. Event-Driven: Agents react to events as they occur
  3. Peer-to-Peer: Bidirectional, symmetric relationships
  4. Collective: Operations that span multiple agents
  5. Emergent: System behavior arises from agent interactions

2.2 Protocol Identifier

OCP messages are identified by the protocol field:protocol: "a2a+ocp"

This signals that the message uses A2A as a foundation with OCP extensions.

2.3 Versioning

OCP uses semantic versioning:version: "1.0.0"

  • Major: Breaking changes to message format or semantics
  • Minor: Backward-compatible additions
  • Patch: Bug fixes and clarifications

3. Core Principles

3.1 Compatibility First

Every OCP message MUST be compatible with A2A transport requirements. OCP agents MUST support standard A2A messages for interoperability.

3.2 Extensibility

OCP defines extension points for custom message types and payloads. Organizations can add domain-specific extensions while maintaining core compatibility.

3.3 Security by Design

All OCP messages support:

  • Message signing and verification
  • End-to-end encryption (optional)
  • Access control based on agent identity
  • Audit logging

3.4 Scalability

OCP is designed to scale from small teams (2-10 agents) to large organizations (1000+ agents) through:

  • Efficient message routing
  • Selective subscription
  • Batching and compression
  • Rate limiting

4. Message Format

4.1 Base Message Structure

// A2A Required Fields
protocol: "a2a+ocp";           // Protocol identifier
version: string;               // Protocol version (e.g., "1.0.0")
id: string;                    // Unique message ID (UUID v4)// Routing
from: string;                  // Sender agent URI (a2a://...)
to: string | string[];         // Recipient(s) or "broadcast"// Timing
timestamp: string;             // ISO 8601 timestamp
ttl?: number;                  // Time-to-live in seconds// Message Type
type: OCPMessageType;          // OCP message type// Payload
payload: OCPPayload;           // Type-specific payload// Optional Fields
correlation_id?: string;       // For request/response pairing
reply_to?: string;             // For async responses
priority?: MessagePriority;    // Message priority// Security
signature?: string;            // Message signature (base64)
encrypted?: boolean;           // Whether payload is encrypted
}enum MessagePriority {
LOW = "low",
NORMAL = "normal",
HIGH = "high",
URGENT = "urgent"
}

### 4.2 Message Type Enumeration
```typescriptenum OCPMessageType {
// Knowledge Management (ocp.knowledge.*)
KNOWLEDGE_STREAM = "ocp.knowledge.stream",
KNOWLEDGE_SUBSCRIBE = "ocp.knowledge.subscribe",
KNOWLEDGE_UNSUBSCRIBE = "ocp.knowledge.unsubscribe",
KNOWLEDGE_SYNC_REQUEST = "ocp.knowledge.sync.request",
KNOWLEDGE_SYNC_RESPONSE = "ocp.knowledge.sync.response",
KNOWLEDGE_UPDATE = "ocp.knowledge.update",
KNOWLEDGE_CONFLICT = "ocp.knowledge.conflict",// Collective Operations (ocp.collective.*)
COLLECTIVE_QUERY = "ocp.collective.query",
COLLECTIVE_RESPONSE = "ocp.collective.response",
COLLECTIVE_SYNTHESIS = "ocp.collective.synthesis",// Consensus & Coordination (ocp.consensus.*)
CONSENSUS_PROPOSE = "ocp.consensus.propose",
CONSENSUS_VOTE = "ocp.consensus.vote",
CONSENSUS_ACHIEVED = "ocp.consensus.achieved",
CONSENSUS_TIMEOUT = "ocp.consensus.timeout",// Awareness & Presence (ocp.awareness.*)
AWARENESS_BEACON = "ocp.awareness.beacon",
AWARENESS_UPDATE = "ocp.awareness.update",
AWARENESS_QUERY = "ocp.awareness.query",
AWARENESS_RESPONSE = "ocp.awareness.response",// Event System (ocp.event.*)
EVENT_PUBLISH = "ocp.event.publish",
EVENT_SUBSCRIBE = "ocp.event.subscribe",
EVENT_UNSUBSCRIBE = "ocp.event.unsubscribe",
EVENT_NOTIFICATION = "ocp.event.notification",// Synchronization (ocp.sync.*)
SYNC_REQUEST = "ocp.sync.request",
SYNC_OFFER = "ocp.sync.offer",
SYNC_ACCEPT = "ocp.sync.accept",
SYNC_COMPLETE = "ocp.sync.complete",
SYNC_CONFLICT = "ocp.sync.conflict"
}

### 4.3 Payload Types

Each message type has a specific payload structure. See Section 5 for detailed schemas.

---

## 5. Message Types

### 5.1 Knowledge Management Messages

#### 5.1.1 KNOWLEDGE_STREAM

Streams knowledge to subscribed agents.
```typescriptinterface KnowledgeStreamPayload {
streamId: string;              // Unique stream identifier
nodes: KnowledgeNode[];        // Knowledge nodes
edges?: KnowledgeEdge[];       // Relationships between nodes
isIncremental: boolean;        // Delta (true) or full (false)
sequenceNumber: number;        // For ordering
checksum?: string;             // SHA-256 of content
}interface KnowledgeNode {
id: string;                    // Node UUID
type: string;                  // Node type (extensible)
title: string;
description?: string;
data: any;                     // Type-specific data
confidence: number;            // 0.0 - 1.0
timestamp: string;             // ISO 8601
createdBy: string;             // Agent URI
tags: string[];
metadata?: Record<string, any>;
}interface KnowledgeEdge {
id: string;
source: string;                // Source node ID
target: string;                // Target node ID
relationship: string;          // Relationship type
weight: number;                // 0.0 - 1.0
metadata?: Record<string, any>;
}

**Example:**
```json{
"protocol": "a2a+ocp",
"version": "1.0.0",
"id": "msg-abc123",
"from": "a2a://claude-code-alice",
"to": "a2a://claude-code-bob",
"timestamp": "2025-10-13T10:30:00Z",
"type": "ocp.knowledge.stream",
"payload": {
"streamId": "stream-456",
"nodes": [
{
"id": "node-789",
"type": "code.solution",
"title": "WebSocket memory leak fix",
"data": {
"code": "ws.on('close', () => { connections.delete(id); })",
"tested": true
},
"confidence": 0.92,
"timestamp": "2025-10-13T10:25:00Z",
"createdBy": "a2a://claude-code-alice",
"tags": ["websocket", "memory-leak", "fix"]
}
],
"isIncremental": true,
"sequenceNumber": 42
}
}

#### 5.1.2 KNOWLEDGE_SUBSCRIBE

Subscribe to another agent's knowledge stream.
```typescriptinterface KnowledgeSubscribePayload {
subscriptionId: string;        // Unique subscription ID
filters?: {
domains?: string[];          // Knowledge domains
nodeTypes?: string[];        // Types of nodes
tags?: string[];             // Tags to filter by
minConfidence?: number;      // Minimum confidence threshold
};
deliveryMode: "push" | "pull"; // Push or pull delivery
batchSize?: number;            // For batched delivery
frequency?: number;            // Pull frequency (seconds)
}

**Example:**
```json{
"protocol": "a2a+ocp",
"version": "1.0.0",
"id": "msg-def456",
"from": "a2a://claude-code-bob",
"to": "a2a://claude-code-alice",
"timestamp": "2025-10-13T10:31:00Z",
"type": "ocp.knowledge.subscribe",
"payload": {
"subscriptionId": "sub-123",
"filters": {
"domains": ["backend"],
"tags": ["critical"],
"minConfidence": 0.8
},
"deliveryMode": "push"
}
}

#### 5.1.3 KNOWLEDGE_UNSUBSCRIBE

Unsubscribe from a knowledge stream.
```typescriptinterface KnowledgeUnsubscribePayload {
subscriptionId: string;        // Subscription to cancel
}

#### 5.1.4 KNOWLEDGE_SYNC_REQUEST

Request full synchronization of knowledge.
```typescriptinterface KnowledgeSyncRequestPayload {
syncId: string;                // Unique sync session ID
versionVector?: Record<string, number>; // For delta sync
filters?: {
domains?: string[];
updatedAfter?: string;       // ISO 8601
};
}

#### 5.1.5 KNOWLEDGE_SYNC_RESPONSE

Respond to sync request with knowledge package.
```typescriptinterface KnowledgeSyncResponsePayload {
syncId: string;
nodes: KnowledgeNode[];
edges: KnowledgeEdge[];
versionVector: Record<string, number>;
isComplete: boolean;           // More data coming?
checksum: string;
}

#### 5.1.6 KNOWLEDGE_UPDATE

Incremental update to knowledge (lighter than full stream).
```typescriptinterface KnowledgeUpdatePayload {
updates: NodeUpdate[];
deletions: string[];           // Deleted node IDs
newEdges: KnowledgeEdge[];
deletedEdges: string[];        // Deleted edge IDs
}interface NodeUpdate {
nodeId: string;
changes: Partial<KnowledgeNode>;
changeType: "modified" | "status_changed" | "metadata_updated";
}

#### 5.1.7 KNOWLEDGE_CONFLICT

Report a merge conflict that requires resolution.
```typescriptinterface KnowledgeConflictPayload {
conflictId: string;
nodeId: string;
localVersion: KnowledgeNode;
remoteVersion: KnowledgeNode;
conflictType: "content" | "contradiction" | "version";
suggestedResolution?: KnowledgeNode;
}

---

### 5.2 Collective Operations Messages

#### 5.2.1 COLLECTIVE_QUERY

Query multiple agents and request collective response.
```typescriptinterface CollectiveQueryPayload {
queryId: string;               // Unique query ID
query: string;                 // Natural language query
structuredQuery?: {
intent: string;
domains: string[];
keywords: string[];
filters?: Record<string, any>;
};
timeout: number;               // Max wait time (ms)
minResponses?: number;         // Minimum responses needed
maxResponses?: number;         // Maximum responses to collect
}

**Example:**
```json{
"protocol": "a2a+ocp",
"version": "1.0.0",
"id": "msg-ghi789",
"from": "a2a://claude-code-alice",
"to": "broadcast",
"timestamp": "2025-10-13T10:35:00Z",
"type": "ocp.collective.query",
"payload": {
"queryId": "query-abc",
"query": "What's our approach to authentication?",
"structuredQuery": {
"intent": "find_information",
"domains": ["backend", "security"],
"keywords": ["authentication", "auth", "login"]
},
"timeout": 5000,
"minResponses": 3
}
}

#### 5.2.2 COLLECTIVE_RESPONSE

Individual agent's response to collective query.
```typescriptinterface CollectiveResponsePayload {
queryId: string;               // References original query
findings: QueryFinding[];
confidence: number;            // 0.0 - 1.0
processingTime: number;        // Milliseconds
metadata?: {
nodesSearched: number;
relevanceScores: number[];
};
}interface QueryFinding {
node: KnowledgeNode;
relevance: number;             // 0.0 - 1.0
excerpt?: string;
context?: string;
}

#### 5.2.3 COLLECTIVE_SYNTHESIS

Synthesized answer from multiple responses.
```typescriptinterface CollectiveSynthesisPayload {
queryId: string;
answer: string;                // Synthesized answer
keyPoints?: string[];
confidence: number;
consensus: string[];           // Areas of agreement
dissent: string[];             // Areas of disagreement
recommendations?: string[];
sources: string[];             // Agent URIs
timestamp: string;
}

---

### 5.3 Consensus & Coordination Messages

#### 5.3.1 CONSENSUS_PROPOSE

Propose something for distributed consensus.
```typescriptinterface ConsensusProposePayload {
proposalId: string;
topic: string;
proposal: any;                 // What's being proposed
votingPeriod: number;          // Seconds
requiredVotes: number;         // Quorum
votingRule: "majority" | "unanimous" | "threshold";
threshold?: number;            // For threshold voting (0.0-1.0)
}

**Example:**
```json{
"protocol": "a2a+ocp",
"version": "1.0.0",
"id": "msg-jkl012",
"from": "a2a://claude-code-bob",
"to": "broadcast",
"timestamp": "2025-10-13T11:00:00Z",
"type": "ocp.consensus.propose",
"payload": {
"proposalId": "prop-456",
"topic": "Switch to PostgreSQL",
"proposal": {
"decision": "Migrate from MySQL to PostgreSQL",
"rationale": "Better JSON support, more features",
"impact": "2 weeks migration time"
},
"votingPeriod": 86400,
"requiredVotes": 3,
"votingRule": "majority"
}
}

#### 5.3.2 CONSENSUS_VOTE

Vote on a proposal.
```typescriptinterface ConsensusVotePayload {
proposalId: string;
vote: "approve" | "reject" | "abstain";
reasoning?: string;
votedBy: string;               // Agent URI (for transparency)
}

#### 5.3.3 CONSENSUS_ACHIEVED

Announce that consensus was reached.
```typescriptinterface ConsensusAchievedPayload {
proposalId: string;
outcome: "approved" | "rejected";
votes: {
approve: number;
reject: number;
abstain: number;
};
voters: string[];              // Agent URIs
achievedAt: string;            // ISO 8601
}

#### 5.3.4 CONSENSUS_TIMEOUT

Announce that voting period expired without consensus.
```typescriptinterface ConsensusTimeoutPayload {
proposalId: string;
votes: {
approve: number;
reject: number;
abstain: number;
};
reason: string;
}

---

### 5.4 Awareness & Presence Messages

#### 5.4.1 AWARENESS_BEACON

Broadcast current activity and status.
```typescriptinterface AwarenessBeaconPayload {
status: "working" | "blocked" | "reviewing" | "idle" | "away";
currentContext?: {
task?: string;
file?: string;
project?: string;
blockedOn?: string;
};
availability: "available" | "busy" | "away";
metadata?: Record<string, any>;
}

**Example:**
```json{
"protocol": "a2a+ocp",
"version": "1.0.0",
"id": "msg-mno345",
"from": "a2a://claude-code-carol",
"to": "broadcast",
"timestamp": "2025-10-13T11:15:00Z",
"type": "ocp.awareness.beacon",
"payload": {
"status": "blocked",
"currentContext": {
"task": "Implement OAuth",
"file": "src/auth/oauth.ts",
"blockedOn": "Waiting for API credentials"
},
"availability": "available"
}
}

#### 5.4.2 AWARENESS_UPDATE

Update awareness information (lighter than beacon).
```typescriptinterface AwarenessUpdatePayload {
changes: Partial<AwarenessBeaconPayload>;
}

#### 5.4.3 AWARENESS_QUERY

Query who is working on what.
```typescriptinterface AwarenessQueryPayload {
queryId: string;
filters?: {
status?: string[];
availability?: string[];
task?: string;
};
}

#### 5.4.4 AWARENESS_RESPONSE

Response to awareness query.
```typescriptinterface AwarenessResponsePayload {
queryId: string;
agents: Array<{
agentId: string;
awareness: AwarenessBeaconPayload;
}>;
}

---

### 5.5 Event System Messages

#### 5.5.1 EVENT_PUBLISH

Publish an event to subscribers.
```typescriptinterface EventPublishPayload {
eventId: string;
eventType: string;             // e.g., "code.deployed", "bug.found"
eventData: any;
timestamp: string;
source: string;                // Agent URI
severity?: "info" | "warning" | "error" | "critical";
}

**Example:**
```json{
"protocol": "a2a+ocp",
"version": "1.0.0",
"id": "msg-pqr678",
"from": "a2a://claude-code-dave",
"to": "broadcast",
"timestamp": "2025-10-13T11:30:00Z",
"type": "ocp.event.publish",
"payload": {
"eventId": "evt-123",
"eventType": "code.deployed",
"eventData": {
"service": "api-gateway",
"version": "2.1.0",
"environment": "production"
},
"timestamp": "2025-10-13T11:30:00Z",
"source": "a2a://claude-code-dave",
"severity": "info"
}
}

#### 5.5.2 EVENT_SUBSCRIBE

Subscribe to event type.
```typescriptinterface EventSubscribePayload {
subscriptionId: string;
eventTypes: string[];          // Event types to subscribe to
filters?: Record<string, any>; // Additional filters
}

#### 5.5.3 EVENT_UNSUBSCRIBE

Unsubscribe from events.
```typescriptinterface EventUnsubscribePayload {
subscriptionId: string;
}

#### 5.5.4 EVENT_NOTIFICATION

Notification of subscribed event.
```typescriptinterface EventNotificationPayload {
subscriptionId: string;
event: EventPublishPayload;
}

---

### 5.6 Synchronization Messages

#### 5.6.1 SYNC_REQUEST

Request to synchronize with another agent.
```typescriptinterface SyncRequestPayload {
syncId: string;
scope: string[];               // What to sync (e.g., ["knowledge", "awareness"])
lastSyncedAt?: string;         // ISO 8601
priority?: "low" | "normal" | "high";
}

#### 5.6.2 SYNC_OFFER

Offer sync data to requester.
```typescriptinterface SyncOfferPayload {
syncId: string;
dataSize: number;              // Bytes
dataTypes: string[];
estimatedTime: number;         // Seconds
}

#### 5.6.3 SYNC_ACCEPT

Accept sync offer and begin transfer.
```typescriptinterface SyncAcceptPayload {
syncId: string;
accepted: boolean;
}

#### 5.6.4 SYNC_COMPLETE

Signal sync completion.
```typescriptinterface SyncCompletePayload {
syncId: string;
bytesTransferred: number;
itemsSynced: number;
conflicts: number;
duration: number;              // Milliseconds
}

#### 5.6.5 SYNC_CONFLICT

Report sync conflict.
```typescriptinterface SyncConflictPayload {
syncId: string;
conflicts: Array<{
type: string;
itemId: string;
localVersion: any;
remoteVersion: any;
}>;
}

---

## 6. Transport Layer

### 6.1 Transport Requirements

OCP messages MUST be transmitted over a reliable, ordered transport. Supported transports:

- **WebSocket** (RECOMMENDED): For real-time, bidirectional communication
- **HTTP/2** with Server-Sent Events: For server push scenarios
- **MQTT**: For IoT and edge deployments
- **Custom transports**: As long as they guarantee message ordering and delivery

### 6.2 WebSocket Protocol

OCP over WebSocket uses subprotocol: `a2a-ocp-v1`
```typescriptconst ws = new WebSocket('wss://agent.example.com/ocp', ['a2a-ocp-v1']);

### 6.3 Message Framing

Messages are JSON-encoded and frame-delimited:[length: 4 bytes][JSON message: N bytes]

Or for text-based WebSocket:<message>JSON</message>

### 6.4 Connection LifecycleClient connects
↓
Server sends connection ack
↓
Client sends agent announcement (A2A standard)
↓
Server confirms registration
↓
Bidirectional messaging begins
↓
Client sends disconnect notice (graceful)
↓
Connection closes

---

## 7. Discovery & Capabilities

### 7.1 OCP Capability Declaration

Agents declare OCP support in their A2A profile:
```typescriptinterface A2AAgentWithOCP extends A2AAgent {
id: string;                    // a2a://...
name: string;capabilities: {
// Standard A2A
tasks: TaskCapability[];
tools: ToolCapability[];// OCP Extension
protocols: string[];         // ["a2a", "a2a+ocp"]ocp?: {
  version: string;           // "1.0.0"
  features: OCPFeature[];
  endpoints: {
    websocket?: string;      // wss://...
    http?: string;           // https://...
  };
  limits?: {
    maxStreamBandwidth?: number;  // bytes/sec
    maxSubscriptions?: number;
    maxConcurrentQueries?: number;
  };
};
};
}enum OCPFeature {
KNOWLEDGE_STREAMING = "knowledge_streaming",
COLLECTIVE_QUERY = "collective_query",
CONSENSUS_VOTING = "consensus_voting",
AWARENESS_BEACON = "awareness_beacon",
EVENT_PUBLISHING = "event_publishing",
BIDIRECTIONAL_SYNC = "bidirectional_sync"
}

### 7.2 Feature Negotiation

Agents negotiate features during connection:
```typescript// Client sends capability announcement
{
"protocol": "a2a+ocp",
"type": "capability.announce",
"payload": {
"features": ["knowledge_streaming", "collective_query"],
"version": "1.0.0"
}
}// Server responds with supported features
{
"protocol": "a2a+ocp",
"type": "capability.confirm",
"payload": {
"supportedFeatures": ["knowledge_streaming", "collective_query"],
"version": "1.0.0"
}
}

### 7.3 Discovery Query

Find OCP-capable agents:
```typescript// A2A discovery with OCP filter
const agents = await discovery.findAgents({
protocols: ["a2a+ocp"],
features: ["knowledge_streaming"],
workspace: "acme-engineering"
});

---

## 8. Security Model

### 8.1 Authentication

OCP inherits A2A's agent identity system. Each agent MUST have:

- Unique agent URI (`a2a://...`)
- Cryptographic key pair (Ed25519 or RSA)
- Signed agent profile

### 8.2 Message Signing

All OCP messages SHOULD be signed:
```typescript// Sign message
const canonical = JSON.stringify({
protocol: msg.protocol,
id: msg.id,
from: msg.from,
to: msg.to,
type: msg.type,
timestamp: msg.timestamp,
payload: msg.payload
});const signature = await sign(canonical, privateKey);
msg.signature = signature;

### 8.3 Message Verification

Recipients MUST verify signatures:
```typescriptasync function verifyMessage(msg: OCPMessage): Promise<boolean> {
// Get sender's public key
const sender = await discovery.getAgent(msg.from);// Verify signature
return await verify(msg, sender.publicKey);
}

### 8.4 End-to-End Encryption

For sensitive knowledge, use E2E encryption:
```typescriptinterface EncryptedOCPMessage extends OCPMessage {
encrypted: true;
payload: {
ciphertext: string;        // Base64 encrypted payload
algorithm: string;         // e.g., "AES-256-GCM"
recipientKeys: Array<{
agentId: string;
encryptedKey: string;    // Encrypted symmetric key
}>;
};
}

### 8.5 Access Control

Knowledge nodes support access control:
```typescriptinterface KnowledgeNode {
// ... other fields
visibility: "private" | "team" | "workspace" | "public";
sharedWith?: string[];       // Specific agent URIs
}

Agents MUST respect visibility rules when streaming knowledge.

---

## 9. A2A Compatibility

### 9.1 Fallback to A2A

OCP agents MUST support fallback to pure A2A:
```typescriptclass OCPAgent {
async sendMessage(to: string, message: OCPMessage): Promise<void> {
const recipient = await discovery.getAgent(to);if (recipient.capabilities.protocols?.includes("a2a+ocp")) {
  // Send OCP message
  await this.sendOCP(message);
} else {
  // Fallback to A2A task
  await this.sendA2AEquivalent(message);
}
}private async sendA2AEquivalent(msg: OCPMessage): Promise<void> {
// Convert OCP message to A2A task
if (msg.type === "ocp.knowledge.stream") {
// Use A2A task: "receive_knowledge"
await this.delegateTask(msg.to, {
task: "receive_knowledge",
input: msg.payload
});
}
// ... handle other types
}
}

### 9.2 OCP Operations as A2A Tasks

For compatibility, OCP operations can be exposed as A2A tasks:

| OCP Message | A2A Task Equivalent |
|-------------|---------------------|
| `ocp.knowledge.stream` | `receive_knowledge` |
| `ocp.collective.query` | `search_and_respond` |
| `ocp.consensus.propose` | `vote_on_proposal` |

### 9.3 Interoperability Testing

Implementations SHOULD pass the OCP Compatibility Test Suite (separate document).

---

## 10. Implementation Guide

### 10.1 Minimal Implementation

A minimal OCP agent MUST support:

1. **Message parsing and serialization**
2. **At least one OCP feature** (e.g., knowledge streaming)
3. **A2A fallback** for non-OCP agents
4. **Message signing and verification**

### 10.2 Reference Implementation

See: https://github.com/ocp-protocol/reference-implementation

### 10.3 Client Libraries

Official libraries:

- **TypeScript/JavaScript**: `@ocp/client`
- **Python**: `ocp-client`
- **Go**: `github.com/ocp-protocol/go-client`
- **Rust**: `ocp-client`

### 10.4 Testing

Use the OCP Test Suite:
```bashnpm install -g @ocp/test-suite
ocp-test --agent wss://your-agent.com/ocp

### 10.5 Example: Simple Knowledge Streaming
```typescriptimport { OCPAgent, KnowledgeNode } from '@ocp/client';const agent = new OCPAgent({
id: 'a2a://my-agent',
privateKey: process.env.PRIVATE_KEY,
endpoint: 'wss://localhost:8080/ocp'
});// Subscribe to another agent's knowledge
await agent.subscribe('a2a://teammate-agent', {
domains: ['backend'],
deliveryMode: 'push'
});// Handle incoming knowledge
agent.on('knowledge', (knowledge: KnowledgeNode[]) => {
console.log('Received knowledge:', knowledge);
// Merge into local graph
});// Stream your own knowledge
const node: KnowledgeNode = {
id: 'node-123',
type: 'code.solution',
title: 'Fixed memory leak',
data: { /* ... */ },
confidence: 0.9,
timestamp: new Date().toISOString(),
createdBy: agent.id,
tags: ['bug-fix']
};await agent.streamKnowledge([node]);

---

## 11. Extension Mechanism

### 11.1 Custom Message Types

Organizations can define custom message types:
```typescript// Custom message type
enum CustomOCPMessageType {
CUSTOM_ANALYTICS = "ocp.custom.analytics",
CUSTOM_DEPLOY = "ocp.custom.deploy"
}// Custom payload
interface CustomAnalyticsPayload {
metrics: Metric[];
timeRange: { start: string; end: string };
}

Custom types MUST use namespace: `ocp.custom.*`

### 11.2 Payload Extensions

Standard payloads can be extended:
```typescriptinterface ExtendedKnowledgeNode extends KnowledgeNode {
customFields?: {
organizationSpecific?: any;
};
}

Extensions SHOULD use optional fields prefixed with organization identifier.

---

## 12. Performance Considerations

### 12.1 Message Batching

For high-frequency updates, use batching:
```typescriptinterface BatchedKnowledgeStream {
type: "ocp.knowledge.stream",
payload: {
batched: true,
items: KnowledgeStreamPayload[]
}
}

### 12.2 Compression

Large payloads SHOULD be compressed:
```typescriptinterface OCPMessage {
// ... standard fields
compression?: "gzip" | "brotli";
compressedPayload?: string;  // Base64
}

### 12.3 Rate Limiting

Agents SHOULD implement rate limiting:

- Max 100 messages/minute per agent
- Max 10 broadcast messages/minute
- Max 5 collective queries/minute

### 12.4 Backpressure

Streaming agents SHOULD implement backpressure:
```typescriptinterface KnowledgeStreamControl {
type: "ocp.knowledge.control",
payload: {
streamId: string,
action: "pause" | "resume" | "cancel"
}
}

---

## 13. Future Extensions

### 13.1 Planned Features (v1.1+)

- **Federation**: Cross-organization agent networks
- **Query optimization**: Intelligent query routing
- **Conflict resolution strategies**: More sophisticated merge algorithms
- **Analytics**: Built-in metrics and observability
- **Graph queries**: Native graph traversal queries

### 13.2 Extension Proposals

Community can propose extensions via:
- GitHub Issues: https://github.com/ocp/spec
- Mailing list: TBD

---

## 14. Appendices

### Appendix A: Complete TypeScript Types

See: https://github.com/ocp-protocol/typescript-types

### Appendix B: JSON Schema Definitions

See: https://github.com/ocp-protocol/json-schemas

### Appendix C: Example Implementations

See: https://github.com/ocp-protocol/examples

### Appendix D: Changelog

**v1.0.0** (October 2025)
- Initial specification
- Core message types
- Knowledge streaming
- Collective operations
- Consensus protocol

---

## 15. License

This specification is released under the MIT License.

Copyright (c) 2025 OCP Protocol Authors

---

## 16. Contributing

Contributions welcome! See CONTRIBUTING.md

---

## 17. Contact

- **Specification Issues**: https://github.com/ocp/spec/issues
- **Mailing List**: [email protected]
- **Chat**: #ocp-protocol on A2A Discord


**End of OCP v1.0 Specification**

About

Organization Consciousness Protocol

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published