API Reference
Complete API documentation for SocketCloud integration
MeshNetwork
Core mesh networking class that manages peer discovery, connection establishment, and distributed routing across the SocketCloud network.
Constructor
new MeshNetwork(config: MeshNetworkConfig)
Methods
initialize()
initialize(): Promise<void>
Initializes the mesh network and establishes peer connections. Must be called before using other methods.
join()
join(
bootstrapPeers: string[],
nodeId?: string
): Promise<{
success: boolean,
nodeId: string,
peers: string[]
}>
Joins the distributed mesh network using bootstrap peers for initial discovery.
Parameter |
Type |
Description |
identity |
MeshServiceIdentity |
Complete service identity with mesh-specific properties |
requireConsensus |
boolean? |
Whether to require consensus for registration (default: true) |
establishSession()
establishSession(
service: MeshServiceIdentity,
participantNodes: string[],
timeoutMs?: number
): Promise<{
success: boolean,
sessionId?: string,
coordinatorNode: string
}>
Establishes a distributed session across specified mesh nodes.
authorizeOperation()
authorizeOperation(
request: MeshAuthorizationRequest
): Promise<MeshAuthorizationResponse>
Authorizes an MCP operation with optional consensus-based decision making.
authorizeBatchOperations()
authorizeBatchOperations(
requests: MeshAuthorizationRequest[]
): Promise<MeshAuthorizationResponse[]>
Batch authorizes multiple operations for improved performance.
generateComplianceReport()
generateComplianceReport(
query: ComplianceQuery
): Promise<ComplianceReport>
Generates a comprehensive compliance report for audit and regulatory purposes.
getSecurityStatus()
getSecurityStatus(): Promise<SecurityStatus>
Returns current security status including component health and active threats.
shutdown()
shutdown(): Promise<void>
Gracefully shuts down the gateway and all components.
Factory Functions
createMeshNetwork()
createMeshNetwork(
config: MeshNetworkConfig
): MeshNetwork
Creates a mesh network instance with the specified configuration.
createSecurityGateway()
createSecurityGateway(
nodeId: string,
networkId: string,
consensusAlgorithm: ConsensusAlgorithm,
overrides?: Partial<SecurityGatewayConfig>
): SecurityGateway
Creates a security gateway for distributed authorization and audit.
getRecommendedConfig()
getRecommendedConfig(
scenario:
| 'development'
| 'staging'
| 'production'
| 'high-security',
nodeId: string,
networkId: string
): Partial<MeshNetworkConfig>
Returns recommended configuration for different deployment scenarios.
MCP Integration
Advanced Model Context Protocol (MCP) agent coordination with flexible capability management, distributed consensus, and comprehensive security controls for AI agent deployments at scale.
createMCPSecurityGateway()
createMCPSecurityGateway(
meshNetwork: MeshNetwork,
mcpConfig: MCPSecurityConfig
): MCPSecurityGateway
Creates an MCP-specific security gateway that integrates with the mesh network for AI agent coordination.
MCPSecurityConfig
interface MCPSecurityConfig {
enableCapabilityDelegation: boolean;
mcpAgentTimeout: number;
enableCrossAgentConsensus: boolean;
auditMCPOperations: boolean;
defaultRiskLevel:
| 'safe'
| 'elevated'
| 'dangerous'
| 'critical';
maxConcurrentAgents: number;
capabilityConstraints: CapabilityConstraints;
}
Flexible MCP Capability System
SocketCloud provides a modern, flexible capability system for MCP agents that adapts to diverse and evolving AI use cases.
MCPCapability Interface
interface MCPCapability {
domain: string;
// Resource domain: 'data', 'compute', 'network', 'device', 'system'
operation: string;
// Action type: 'read', 'write', 'execute', 'monitor', 'configure'
scope: string;
// Access scope: 'user', 'application', 'system', 'global'
temporal: string;
// Timing pattern: 'immediate', 'scheduled', 'continuous', 'batch'
riskLevel: RiskLevel;
// Security risk assessment
resources?: string[];
// Specific resource identifiers
constraints?: CapabilityConstraints;
// Operational limits
}
enum RiskLevel {
SAFE = 'safe',
// No security concerns
ELEVATED = 'elevated',
// Requires authentication
DANGEROUS = 'dangerous',
// Requires authorization
CRITICAL = 'critical'
// Requires consensus
}
CapabilityBuilder Utility
Pre-built capability patterns for common MCP operations:
// Memory operations
CapabilityBuilder.memory(
| 'read'
| 'write'
| 'delete'
| 'search'
)
// Filesystem operations
CapabilityBuilder.filesystem(
| 'read'
| 'write'
| 'delete'
| 'list'
| 'search'
)
// Network operations
CapabilityBuilder.network(
| 'fetch'
| 'search'
| 'connect'
| 'monitor'
)
// Compute operations
CapabilityBuilder.compute(
| 'execute'
| 'analyze'
| 'process'
| 'transform'
)
// Device operations
CapabilityBuilder.device(
| 'configure'
| 'monitor'
| 'control'
| 'query'
)
// Streaming operations
CapabilityBuilder.stream(
| 'subscribe'
| 'publish'
| 'monitor'
| 'analyze'
)
// AI operations
CapabilityBuilder.ai(
| 'reason'
| 'generate'
| 'classify'
| 'translate'
)
Usage Examples
// Basic capability creation
const memoryAccess = CapabilityBuilder.memory('read');
const fileSystem = CapabilityBuilder.filesystem('write', {
scope: 'user',
constraints: {
dataVolume: '1GB',
rateLimit: '100/min'
}
});
// Custom capability for specialized AI operations
const customCapability: MCPCapability = {
domain: 'ai-trading',
operation: 'execute-strategy',
scope: 'application',
temporal: 'continuous',
riskLevel: RiskLevel.CRITICAL,
resources: ['portfolio-management', 'market-data'],
constraints: {
dataVolume: '10GB',
rateLimit: '1000/sec',
userConsent: true,
auditLevel: 'comprehensive'
}
};
// Risk-based capability authorization
const isHighRisk = capability.riskLevel === 'dangerous' ||
capability.riskLevel === 'critical';
Distributed Capability Management
interface DistributedMCPCapability {
capability: MCPCapability;
nodeScope:
| 'local'
| 'mesh'
| 'global';
consensusRequired: boolean;
replicationLevel: number;
delegationDepth: number;
}
MCP Agent Identity & Attestation
interface MCPAgentIdentity {
id: string;
publicKey: string;
serverUrl?: string;
toolManifest: MCPToolManifest;
capabilities: MCPCapability[];
attestation: MCPAttestation;
rateLimits?: MCPRateLimits;
}
interface MCPAttestation {
id: string;
issuer: string;
subject: string;
claims: MCPAttestationClaims;
proofs: ZeroKnowledgeProof[];
signature: string;
issuedAt: number;
expiresAt: number;
status:
| 'active'
| 'revoked'
| 'expired'
| 'suspended';
}
Security Policies
interface MCPSecurityPolicy {
id: string;
name: string;
description: string;
rules: PolicyRule[];
priority: number;
enabled: boolean;
}
interface PolicyRule {
capability: MCPCapability;
condition: PolicyCondition;
effect:
| 'allow'
| 'deny';
auditLevel:
| 'none'
| 'basic'
| 'detailed'
| 'comprehensive';
}
Types & Interfaces
MeshServiceIdentity
interface MeshServiceIdentity {
id: string;
publicKey: string;
capabilities: Capability[];
attestation: ServiceAttestation;
// Mesh-specific properties
nodeId: string;
meshRole:
| 'coordinator'
| 'participant'
| 'observer';
trustedPeers: string[];
consensusWeight: number;
minimumConsensus: number;
}
MeshAuthorizationRequest
interface MeshAuthorizationRequest {
sessionId: string;
serviceId: string;
capability: Capability;
resources: string[];
context?: AuthorizationContext;
requestingNode: string;
consensusRequired: boolean;
crossNode: boolean;
delegation?: DelegationChain;
}
Capability
interface Capability {
domain: string;
// e.g., 'data', 'compute', 'network', 'storage'
operation: string;
// e.g., 'read', 'write', 'execute', 'manage'
resource?: string;
// optional resource identifier
level: CapabilityLevel;
}
enum CapabilityLevel {
READ = 'read',
WRITE = 'write',
ADMIN = 'admin',
SYSTEM = 'system'
}
// Common capability patterns
type CommonCapabilities =
| 'data:read'
| 'data:write'
| 'compute:execute'
| 'network:connect'
| 'storage:read'
| 'storage:write'
| 'mesh:coordinate'
| 'consensus:participate'
| 'security:authorize';
SecurityStatus
interface SecurityStatus {
overall:
| 'healthy'
| 'degraded'
| 'critical'
| 'offline';
components: {
identity: ComponentStatus;
capabilities: ComponentStatus;
sessions: ComponentStatus;
authorization: ComponentStatus;
audit: ComponentStatus;
};
networkTopology: MeshTopology;
activeThreats: MeshSecurityEvent[];
recommendations: string[];
}
Events
The SocketCloud mesh networking framework emits various events for monitoring and integration:
Service Events
mesh.on('serviceRegistered', (event) => {
console.log(
`Service ${event.serviceId} registered on node ${event.nodeId}`
);
});
mesh.on('serviceDeregistered', (event) => {
console.log(
`Service ${event.serviceId} deregistered: ${event.reason}`
);
});
Mesh Events
mesh.on('nodeJoined', (event) => {
console.log(
`Node ${event.nodeId} joined the mesh`
);
});
mesh.on('nodeLeft', (event) => {
console.log(
`Node ${event.nodeId} left the mesh: ${event.reason}`
);
});
mesh.on('consensusReached', (event) => {
console.log(
`Consensus reached for ${event.proposalId}`
);
});
Network Events
mesh.on('connectionEstablished', (event) => {
console.log(
`Connection established with ${event.peerId}`
);
});
mesh.on('networkPartition', (event) => {
console.log(
`Network partition detected: ${event.partitionSize} nodes isolated`
);
});
mesh.on('networkHealed', (event) => {
console.log(
`Network partition healed, ${event.reconnectedNodes} nodes rejoined`
);
});
Security Events
mesh.on('authorizationRequested', (event) => {
console.log(
`Authorization requested for ${event.capability}`
);
});
mesh.on('securityThreatDetected', (event) => {
console.log(
`Security threat detected: ${event.threatType}`
);
});
Error Handling
MeshSecurityError
class MeshSecurityError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly nodeId: string,
public readonly networkId: string,
public readonly recoverable: boolean = true
)
}
Common Error Codes
- IDENTITY_EXISTS: Service identity already registered
- IDENTITY_NOT_FOUND: Service identity not found
- SESSION_NOT_FOUND: Session not found or expired
- INSUFFICIENT_CAPABILITY: Service lacks required capability
- CONSENSUS_FAILED: Consensus process failed
- NODE_UNAVAILABLE: Required node is unavailable
- EMERGENCY_MODE: Gateway in emergency mode
Error Handling Example
try {
await gateway.authorizeOperation(request);
} catch (error) {
if (error instanceof MeshSecurityError) {
console.error(
`Security error on ${error.nodeId}: ${error.message}`
);
if (error.recoverable) {
// Implement retry logic
}
}
}
Configuration
MeshNetworkConfig
interface MeshNetworkConfig {
nodeId: string;
networkId: string;
consensusAlgorithm: ConsensusAlgorithm;
// Core mesh configuration
transport: TransportConfig;
discovery: DiscoveryConfig;
security: SecurityConfig;
// Performance settings
maxPeers: number;
healthCheckIntervalMs: number;
consensusTimeoutMs: number;
}
SecurityGatewayConfig
interface SecurityGatewayConfig {
enableAuditLogging: boolean;
enableMetrics: boolean;
autoRecoveryEnabled: boolean;
emergencyShutdownThreshold: number;
}
Configuration Examples
Development Configuration
const devConfig = getRecommendedConfig(
'development',
'dev-node-1',
'dev-network',
consensusAlgorithm
);
// Reduced security, disabled monitoring
Production Configuration
const prodConfig = getRecommendedConfig(
'production',
'prod-node-1',
'financial-mesh',
consensusAlgorithm
);
// Full security, comprehensive monitoring
High-Security Configuration
const secureConfig = getRecommendedConfig(
'high-security',
'secure-node-1',
'regulated-network',
consensusAlgorithm
);
// Maximum security, disabled caching, strict policies
Security Utilities
SocketCloud provides comprehensive security utilities including enhanced hashing capabilities with support for multiple algorithms.
HashingUtils
The HashingUtils class provides a unified interface for multiple hash algorithms, supporting SHA-256, SHA-3 family, BLAKE2b, and SHAKE algorithms.
hash()
HashingUtils.hash(
data: Buffer | string,
algorithm?: HashAlgorithm,
options?: HashOptions
): Buffer
Hashes data using the specified algorithm.
Parameter |
Type |
Description |
data |
Buffer | string |
The data to hash |
algorithm |
HashAlgorithm? |
Hash algorithm to use (default: 'sha256') |
options |
HashOptions? |
Additional options (e.g., outputLength for SHAKE) |
hmac()
HashingUtils.hmac(
data: Buffer | string,
key: Buffer | string,
algorithm?: HashAlgorithm
): Buffer
Creates an HMAC (Hash-based Message Authentication Code) for the data.
verify()
HashingUtils.verify(
data: Buffer | string,
hash: Buffer | string,
algorithm?: HashAlgorithm
): boolean
Verifies that the provided hash matches the data using the specified algorithm.
compare()
HashingUtils.compare(
hash1: Buffer | string,
hash2: Buffer | string
): boolean
Compares two hashes using constant-time comparison to prevent timing attacks.
Supported Hash Algorithms
type HashAlgorithm =
| 'sha256' // SHA-256 (default, compatibility)
| 'sha3-256' // SHA3-256 (NIST standard)
| 'sha3-512' // SHA3-512 (high security)
| 'shake128' // SHAKE128 (variable output)
| 'shake256' // SHAKE256 (variable output)
| 'blake2b'; // BLAKE2b (high performance)
Usage Examples
⚠ Enterprise License Required
Access to SocketCloud packages requires an active enterprise license. Contact contact@socketcloud.com to obtain credentials.
import { HashingUtils } from '@socketcloud/security';
// Basic hashing
const hash = HashingUtils.hash('my data'); // SHA-256 by default
// SHA-3 for enhanced security
const sha3Hash = HashingUtils.hash('sensitive data', 'sha3-256');
// SHAKE for key derivation
const key = HashingUtils.hash('seed', 'shake256', {
outputLength: 32
});
// HMAC for authentication
const hmac = HashingUtils.hmac('message', 'secret-key', 'sha3-256');
// Verify data integrity
if (HashingUtils.verify(data, storedHash, 'sha3-256')) {
console.log('Data integrity verified');
}
// Secure comparison
if (HashingUtils.compare(hash1, hash2)) {
console.log('Hashes match');
}
Algorithm Selection Guide
- sha256: Default choice for backward compatibility and standards compliance
- sha3-256/sha3-512: NIST-standardized with different internals than SHA-2 for algorithm diversity
- shake128/shake256: Extendable output functions (XOF) for variable-length keys and custom applications
- blake2b: High-performance hashing for speed-critical operations