@aimf/ncp-core
v0.1.1
Published
Neural Communication Protocol (NCP) core implementation
Maintainers
Readme
@aimf/ncp-core
Core implementation of the Neural Communication Protocol (NCP) for the AI-MCP Framework.
Installation
pnpm add @aimf/ncp-coreFeatures
- Envelope Module: Message wrapping with neural verification
- Protocol Module: JSON-RPC 2.0 message creation and handling
- Transport Module: Pluggable transport layer (STDIO, WebSocket, SSE, P2P)
- Verification Module: Neural + cryptographic hash verification
- Server Module: NCP server with method registration
Usage
Creating NCP Envelopes
import { createEnvelope, validateEnvelope, verifyEnvelopeIntegrity } from "@aimf/ncp-core";
import type { NcpEndpoint } from "@aimf/shared";
const source: NcpEndpoint = {
type: "client",
id: "client-1",
publicKey: "pk_client_1",
};
const destination: NcpEndpoint = {
type: "gateway",
id: "gateway-1",
publicKey: "pk_gateway_1",
};
// Create an envelope
const envelope = createEnvelope(
"mcp",
{ action: "test", data: [1, 2, 3] },
{ source, destination },
{ correlationId: "optional-correlation-id" }
);
// Validate envelope structure
const validation = validateEnvelope(envelope);
if (validation.valid) {
console.log("Envelope is valid:", validation.data);
}
// Verify integrity (crypto hash matches payload)
const isIntact = verifyEnvelopeIntegrity(envelope);Envelope Operations
import {
addHop,
updateConsensus,
serializeEnvelope,
deserializeEnvelope,
createResponseEnvelope,
} from "@aimf/ncp-core";
// Add routing hops
let envelope = createEnvelope("mcp", payload, context);
envelope = addHop(envelope, "node-1", true, 5);
envelope = addHop(envelope, "node-2", true, 3);
// Update consensus
envelope = updateConsensus(envelope, ["node-1", "node-2"], 0.75);
// Serialize/deserialize
const bytes = serializeEnvelope(envelope);
const restored = deserializeEnvelope(bytes);
// Create response
const response = createResponseEnvelope(envelope, { result: "success" });Creating an NCP Server
import { createNcpServer, createStdioTransport } from "@aimf/ncp-core";
const server = createNcpServer({
transport: createStdioTransport(),
});
// Register method handlers
server.method("neural.store", async (params) => {
const { content } = params as { content: string };
return { id: "rec_123", hash: "abc..." };
});
// Register notification handlers
server.notification("ncp.ping", () => {
console.log("Received ping");
});
// Start the server
await server.start();Creating NCP Messages
import { createRequest, createResponse, createNotification } from "@aimf/ncp-core";
const request = createRequest("neural.store", {
content: "Hello, World!",
});
const response = createResponse(request.id, {
id: "rec_123",
hash: "abc...",
});
const notification = createNotification("ncp.ping");Exports
- Envelope:
createEnvelope,validateEnvelope,verifyEnvelopeIntegrity,addHop,updateConsensus,serializeEnvelope,deserializeEnvelope,createResponseEnvelope - Protocol:
createRequest,createResponse,createNotification,NcpHandlerRegistry - Transport:
BaseTransport,NcpTransport,TransportConfig,TransportMetrics,TransportFactoryStdioTransport,createStdioTransport- Standard input/output with Content-Length framingSSETransport,createSSETransport- Server-Sent Events with HTTP POST sendingWebSocketTransport,createWebSocketTransport- Bidirectional WebSocketcreateTransport,registerTransport- Factory for creating transports
- Verification: Neural + crypto hash verification
NeuralHasher,MockEmbeddingProvider,createMockNeuralHasher- Neural embedding generationhash,hmac,verifyHash,timingSafeEqual- Cryptographic operationsNcpVerifier,createNcpVerifier- Combined verification
- Server:
NcpServer,createNcpServer
Verification Layer
The verification layer combines neural embeddings with cryptographic hashes:
Neural Hashing
import { NeuralHasher, MockEmbeddingProvider } from "@aimf/ncp-core";
const provider = new MockEmbeddingProvider(384);
const hasher = new NeuralHasher({ provider, cacheEnabled: true });
const result = await hasher.hash("Hello, World!");
console.log(result.cryptoHash); // SHA-256 of content
console.log(result.embeddingHash); // Hash of embedding vector
console.log(result.combinedHash); // Combined neural + crypto hash
// Check semantic similarity
const similarity = await hasher.areSimilar("Hello", "Hi there", 0.8);
console.log(similarity.similar, similarity.similarity);Envelope Verification
import { NcpVerifier, createMockNeuralHasher } from "@aimf/ncp-core";
const verifier = new NcpVerifier({
neuralHasher: createMockNeuralHasher(),
similarityThreshold: 0.95,
requireConsensus: false,
});
// Verify an envelope
const result = await verifier.verify({ envelope });
if (!result.valid) {
console.error("Verification failed:", result.errors);
}
// Sign an envelope with this node
const signed = await verifier.signEnvelope(envelope, "node-123");Transport Layer
The transport layer provides a unified interface for multi-protocol communication:
Stdio Transport
import { createStdioTransport } from "@aimf/ncp-core";
// Uses Content-Length framing (MCP compatible)
const transport = createStdioTransport({
input: process.stdin,
output: process.stdout,
});
await transport.connect();SSE Transport
import { createSSETransport } from "@aimf/ncp-core";
const transport = createSSETransport({
mode: "sse",
endpoint: "https://api.example.com/ncp/events",
sendEndpoint: "https://api.example.com/ncp/send",
reconnect: true,
withCredentials: true,
});
await transport.connect();WebSocket Transport
import { createWebSocketTransport } from "@aimf/ncp-core";
const transport = createWebSocketTransport({
mode: "websocket",
endpoint: "wss://api.example.com/ncp",
reconnect: true,
protocols: ["ncp-v1"],
});
await transport.connect();Transport Factory
import { createTransport, registerTransport } from "@aimf/ncp-core";
// Create transport from config
const transport = createTransport({ mode: "stdio" });
// Register custom transport
registerTransport("p2p", myP2PFactory);License
MIT
