> ## Documentation Index
> Fetch the complete documentation index at: https://nekzus-32.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# LiopServer

> Building autonomous Data Nodes and migrating legacy MCP tools

The `LiopServer` class is the heart of the Data Node. It represents the host infrastructure that securely orchestrates incoming Logic-Injection-on-Origin intent from remote Agents.

Instead of writing custom execution environments to manage WebAssembly, isolation, and networking, you define straightforward JavaScript/TypeScript functions. The SDK abstracts the complex sandboxing automatically.

## Initialization and Configuration

You create a Data Node by telling the Mesh who you are and providing configuration properties, such as data security controls.

```typescript theme={null}
import { LiopServer, PII_PRESETS } from "@nekzus/liop";

const server = new LiopServer(
  {
    name: "EnterpriseDatabaseNode",
    version: "3.2.0",
  },
  {
    // Canonical slug for deterministic token resolution
    tokenSlug: "BANK",
    // Scales decryption & WASI sandboxing across all CPU cores instantly
    workerPool: { enabled: true, maxThreads: 16, maxHeapMb: 128 },
    // Strict security configuration and data leak prevention using flexible regional presets
    security: {
      piiPatterns: [
        ...PII_PRESETS.US_COMPLIANT,
        /[A-Z]{3}-\d{5}/ // Custom internal regex tracking number
      ],
      forbiddenKeys: ["password", "clinical_record", "secret_token"],
      enableNerScanning: true,
      rateLimit: { maxPerWindow: 30, windowMs: 60_000 }
    },
    // Data domain classification for Mesh taxonomy
    taxonomy: {
      domain: "healthcare",
      clearanceTier: 3,
      executionTypes: ["aggregation", "analytics"]
    }
  }
);
```

### Configuration Options

When instantiating a `LiopServer`, the second parameter allows you to define advanced characteristics of the node:

* **`tokenSlug` (Deterministic Token Resolution):** A canonical string (e.g. `"BANK"`) that allows remote agents to securely resolve the PQC access token from their host environment (`LIOP_TOKEN_<tokenSlug>`). Must match the regex `/^[A-Z][A-Z0-9_]*$/`.
* **`workerPool.maxHeapMb` (Heap Defense):** Maximum V8 heap size in megabytes per worker thread (default: `64`). Can also be set via the `LIOP_WORKER_MAX_HEAP_MB` environment variable. Prevents Heap Bomb DoS attacks by terminating workers that exceed the memory limit.
* **`security.forbiddenKeys` (Egress Filter):** An array of strings. If the model attempts to return a JSON containing any of these keys (e.g., `"clinical_history"`), the Egress Filter will destroy the response before it leaves the server mapping through objects recursively. Defaults to blocking `"password"`, `"token"`, `"secret"`, and `"privateKey"`.
* **`security.piiPatterns` (Sanitization):** Arrays of `PiiRule` objects. You can use our out-of-the-box templates (`PII_PRESETS.GLOBAL_STRICT`, `EU_GDPR`, `US_COMPLIANT`) and merge them with custom raw strings or regexes. The engine will intercept any outgoing text that matches combinations of IBAN logic, credit card numbers, or internal tracking IDs. Defaults to `GLOBAL_STRICT` if omitted.
* **`security.enableNerScanning` (NLP Detection):** When set to `true`, activates Named Entity Recognition scanning via the `compromise` NLP library to detect person names, locations, and organizations in output values. Adds \~10ms latency for typical output sizes. Default: `false`.
* **`security.rateLimit` (Sliding Window):** Configures the per-tool rate limiter to prevent micro-query exfiltration attacks. `maxPerWindow` (default: `30`) and `windowMs` (default: `60000`) define the sliding window parameters.
* **`taxonomy` (Domain Classification):** Optional metadata that classifies the server's data domain (`domain`), security clearance tier as a `number` (`clearanceTier`), and supported execution types (`executionTypes`). This metadata is announced on the DHT and used for intelligent routing.
* **Dynamic Return Structure (Auto-i18n) \[PLANNED]:** This feature is on the roadmap. When implemented, the `LiopServer` will automatically inject *Dynamic Return Structure* directives into payloads, forcing the AI to respect and return JSON keys exactly in the same native language the client used when making the request, eliminating the need for internationalization (i18n) libraries on your frontend.

## Creating Capabilities (Tools)

In MCP, these are called Tools. In LIOP, we refer to them as **Capabilities**.

To the developer, defining a Capability in LIOP looks virtually identical to defining an MCP Tool. You provide a name, a description, a Zod schema for type-safety, and an execution handler.

```typescript theme={null}
import { z } from "zod";

server.tool(
  "analyze_employee_data",
  "Analyzes sensitive payroll information inside the Sandbox.",
  { department: z.string() },
  async ({ department }) => {
    // The Agent's injected logic stops here.
    // The Data Node executes the local request under its own permissions.
    const result = await database.query(department);

    return {
      content: [{ type: "text", text: `Payroll evaluated: ${result.summary}` }]
    };
  }
);
```

### How this differs from MCP

If the code looks exactly the same, what makes it LIOP?

1. **No Polling:** The Data Node announces the `analyze_employee_data` schema cryptographically over the Kademlia DHT. The Agent instantly knows the schema exists without wasting a network request asking for `listTools()`.
2. **Binary Transport:** When the Agent invokes this Tool, the parameters (e.g., `department: "HR"`) are compressed into pure Protobuf bytes, skipping JSON entirely.

## Exposing Data Schemas (Resources)

LIOP Servers can also expose **Resources** (static data, schemas, or descriptions) that Agents can discover to understand the shape of the data they will analyze *before* they inject their logic. This enables true Zero-Shot autonomy.

```typescript theme={null}
server.resource(
  "Employee Records Schema",
  "liop://schema/employee_records",
  "The exact JSON schema representing the employee databases.",
  "application/json",
  JSON.stringify(EmployeeSchema)
);
```

These resources are flawlessly bridged to LLMs via standard MCP `resources/list` and `resources/read` methods.

## Advanced AI Planning (Prompts & Autonomy)

Just like MCP, LIOP natively supports **Prompts**—templated conversational instructions that help Agents structure their tasks before executing Logic-Injection-on-Origin.

```typescript theme={null}
server.prompt(
  "analyze_codebase",
  "Instructs the agent on how to traverse the codebase securely.",
  [
    { name: "language", description: "Target language (e.g., rust, ts)", required: true }
  ],
  (request) => ({
    description: "Codebase Analysis Prompts",
    messages: [
      { role: "user", content: { type: "text", text: `Analyze the ${request.arguments?.language} codebase securely.`} }
    ]
  })
);
```

### Zero-Shot Autonomy (The Blind Analyst)

LIOP ships with an industrial Master System Prompt designed to instruct standard LLMs (like Claude or GPT-4) on how to generate `.wasm` or JavaScript logic dynamically without hallucinating or breaking the Data Node Sandbox.

You can activate this structural instruction explicitly:

```typescript theme={null}
server.enableZeroShotAutonomy();
```

This automatically registers the `liop_blind_analyst` intelligent prompt into the Mesh, dynamically injecting your Data Dictionary into it as well.

## Security & Memory Management

When a Data Node receives a `.wasm` or `.js` payload, the **`GuardianTS`** module performs a Zero-Time Heuristic Inspection on its Abstract Syntax Tree (AST) to ensure absolute security.

Before any WebAssembly module is even instantiated or executed, `GuardianTS` scans all imports. It strictly rejects any payload that attempts to bind to unauthorized host APIs. Only standard WASI APIs (`wasi_snapshot_preview1`) and native `LIOP` sandboxed functions are allowed, categorically preventing sandbox escapes.

This rigorous AST evaluation is aggressively cached in memory `O(1)` for blazing-fast subsequent executions of the exact same logic payload.

If you are hot-deploying Zero-Day security patches on the host or need to forcefully invalidate the execution memory, you can purge the AST cache manually:

```typescript theme={null}
server.clearAstCache();
```

## Bridging Legacy MCP Servers

LIOP's primary goal is rapid industry adoption. If you have spent months building a standard Model Context Protocol (MCP) server, you do not need to rewrite it to join the Mesh.

The `@nekzus/liop` ships with the `LiopMcpBridge`.

This powerful adapter intercepts incoming LIOP binary mesh requests, translates them into standard JSON-RPC 2.0 locally, forwards them to your unmodified MCP Server via stdio or SSE, and repackages the standard MCP response back into the ultra-fast P2P network.

```typescript theme={null}
import { LiopMcpBridge } from "@nekzus/liop/bridge";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

// Your standard legacy MCP implementation
const mcpServer = new McpServer({ name: "LegacyWeatherApp", version: "1.0" });

// Wrap it in the LIOP Bridge with full options
const bridge = new LiopMcpBridge(mcpServer, {
  publishToMesh: true,             // Announce this server on the P2P DHT
  meshIdentity: "WeatherNode_01",  // Unique node identifier
  serverInfo: { name: "WeatherBridge", version: "2.0" },  // Override server identity
  security: {                      // Optional PII/egress protection
    forbiddenKeys: ["api_key", "internal_token"],
    piiPatterns: [...] 
  }
});

// Start the bridge
await bridge.connect();
```

Your legacy application is now fully accessible to Web3, decentralized, Post-Quantum AI agents around the globe without changing a single line of your original MCP logic.

## Runtime and Lifecycle API

In addition to `connect()`, `LiopServer` exposes low-level lifecycle and mesh inspection methods:

```typescript theme={null}
// Explicit mesh bootstrap (same behavior as connect alias)
await server.connectToMesh({
  port: 50051,
  meshConfig: {
    bootstrapNodes: ["/ip4/1.2.3.4/tcp/4001/p2p/PEER_ID"],
    listenAddresses: ["/ip4/0.0.0.0/tcp/0"],
    identityPath: "~/.liop/identity.json"
  }
});

const info = server.getServerInfo();
const meshNode = server.getMeshNode();
const grpcPort = server.getBoundPort();

// Graceful shutdown for tests and production process teardown
await server.close();
```

## Starting the Server

Once your tools, watchdogs, and bridges are configured, you launch the Data Node by binding it to the network:

```typescript theme={null}
await server.connect();
console.log(`Logic Node online. Listening for incoming Wasms...`);
```
