Skip to content

Repository files navigation

Nexmon SDK

Production-Grade, Zero-Hard-Dependency TypeScript AI Agent Runtime Engine.

npm version Documentation License: MIT TypeScript

nexmon is a high-performance, deterministic TypeScript AI Agent SDK built for production server environments (Node.js, Bun, Deno, and Edge runtimes). It provides an event-sourced execution engine, declarative tool risk governance, human-in-the-loop (HITL) approval interrupts, strongly-typed dependency injection (AgentConfig<TContext>), parallel tool execution, hard token budget enforcement, dry-run simulation mode, bi-directional Model Context Protocol (MCP) support, multi-agent fleet/DAG orchestration, enterprise security guardrails, built-in standard tools, and native OpenTelemetry tracing with token cost calculation.


What is Nexmon?

Nexmon is engineered specifically to provide a production-grade, zero-hard-dependency, event-sourced runtime engine for full-stack and backend TypeScript developers who require deterministic, secure, and observable AI agents in production.

Unlike generic wrappers or non-deterministic frameworks, Nexmon combines strict type-safe dependency injection, parallel tool execution, hard token budget enforcement, declarative risk governance, time-travel replay, and bi-directional Model Context Protocol (MCP) support into a unified, high-performance TypeScript engine.


🏗️ Architectural Overview (7-Layer Stack)

┌────────────────────────────────────────────────────────────────────────┐
│                        NEXMON AGENT RUNTIME STACK                      │
├────────────────────────────────────────────────────────────────────────┤
│ 7. Observability & Auditing   : OpenTelemetry Tracing + USD Token Cost │
│ 6. Tooling & MCP Integration  : MCP Client, MCP Server Export, Tools   │
│ 5. Security & Sandboxing      : PII Redaction, Guardrails, RBAC        │
│ 4. Multi-Agent Fleet          : Swarm Handoffs, DAG Workflows, Voting  │
│ 3. Tiered Memory System       : WorkingMemory, ShortTerm, VectorStore  │
│ 2. Tool Risk Governance       : Risk Levels, HITL Approval Interrupts  │
│ 1. Core Execution Engine      : Event Sourcing, DI, Parallel, Budget  │
└────────────────────────────────────────────────────────────────────────┘

⚡ Architectural Pillars & Core Capabilities

Architectural Pillar What Nexmon Delivers Production Benefit
Zero-Hard-Dependency Core Runs natively on Node.js, Bun, Deno, and Edge runtimes with zero heavy native binaries. Instant cold starts & universal serverless deployment.
Immutable Event Sourcing Every step, tool call, and human approval emits an append-only AgentEvent. 100% auditability & time-travel process resumption (resumeFromStore).
Typed Context Dependency Injection Strongly-typed generic context AgentConfig<TContext> passed to all tool handlers. Safe access to user sessions, tenant context & DB handles in tools.
Parallel Tool Execution Multi-tool requests run concurrently via Promise.allSettled() by default. Latency reduction for multi-search & batch API calls.
Token Budget Hard Caps Native tokenBudget limits (maxPromptTokens, maxCompletionTokens, maxTotalTokens). Prevents runaway LLM costs with graceful "budget_exceeded" exit.
Dry-Run Simulation Mode Opt-in dryRun: true and dryRunMocks to preview execution without side-effects. Risk-free pre-flight testing & prompt verification in staging.
Bi-Directional MCP Protocol Native MCP Client (Stdio/SSE) + MCP Server Exporter (exportAgentAsMCPServer). Seamless integration with Claude Desktop, Cursor & external tools.
Declarative Tool Governance Tool risk levels (LOW..CRITICAL) and HITL predicates (requiresApproval). Prevents unauthorized high-risk state mutations (e.g. money transfers).
Enterprise Security Suite Native PIIRedactor, SecurityGuardrail injection defense, RBAC, & process sandbox. Enterprise data compliance & prompt-injection safeguards out of the box.
Rate Limit Resilience Exponential backoff with full random jitter and 429/503 error detection. Prevents thundering herd problems during provider rate limits.

Project Scaffolding CLI & Web Studio

Scaffold a complete, production-ready TypeScript agent project in seconds using either the interactive Web Studio or the headless CLI generator.

Interactive Web Studio (GUI)

Launch a local visual builder at http://localhost:3456 to select modules, configure providers, test custom Zod tools, and preview generated project files:

# Launch interactive Web Studio
npx nexmon

Non-UI Direct CLI Generator (Headless)

Scaffold a default Nexmon agent project instantly via terminal without opening a browser:

# Direct CLI project creation
npx nexmon create my-agent-app

# Non-interactive CLI with defaults
npx nexmon init --yes

# Headless mode
npx nexmon init --no-web my-agent-app

# Using Bun / bunx
bunx nexmon create my-agent-app

Key Features

  • Zero-Hard-Dependency Core — Runs natively across Node.js, Bun, Deno, and Edge runtimes. SQLite storage, vector databases, and OpenTelemetry are optional pluggable modules.
  • Universal LLM Provider Abstraction — Universal OpenAI-compatible adapter (Provider) supporting custom baseUrl, apiKey, custom headers, and streaming across OpenAI, DeepSeek, OpenRouter, Mistral, Groq, Azure OpenAI, Ollama, and vLLM.
  • Typed Dependency Injection (AgentConfig<TContext>) — Pass strongly-typed application context (database sessions, tenant info, auth tokens) directly into tool executions via context.context.
  • Parallel Tool Execution — When an LLM requests multiple tools in a single step, execution runs concurrently via Promise.allSettled() by default.
  • Hard Token Budget Enforcement — Protect production agents against run-away costs using tokenBudget caps that terminate runs gracefully with status "budget_exceeded".
  • Dry-Run / Simulation Mode — Preview agent execution and event logs safely without running actual side-effecting tool logic (dryRun: true).
  • Real-time onEvent Hook — Subscribe push-style to live AgentEvents (run_started, tool_call_executed, etc.) to drive WebSockets or UI dashboards.
  • Model Context Protocol (MCP) Client & Server Exporter — Connect to external MCP servers or export any Nexmon Agent/tool collection as a JSON-RPC 2.0 MCP server over stdio or HTTP/SSE.
  • Multi-Agent Orchestration & Workflow Engines
    • AgentSwarm: Dynamic peer-to-peer agent handoffs (transfer_to_<agent>), loop limits, and context forwarding.
    • AgentWorkflow: Directed Acyclic Graph (DAG) state machine engine with static/conditional edges and shared state accumulators.
    • AgentConsensus: Worker-Reviewer feedback loops (runDebate) and parallel majority voting consensus (runMajorityVoting).
  • Enterprise Security, Guardrails & Sandboxing
    • PIIRedactor: Redacts API keys, credit cards, SSNs, and emails from strings and nested JSON objects.
    • SecurityGuardrail: Scans input prompts for jailbreak/injection attacks ("ignore previous instructions", "DAN mode") and redacts secrets.
    • createScopedTool: Dynamic RBAC context (roles, scopes) authorization enforced against caller SecurityContext.
    • LocalSubprocessSandbox: Isolated child process execution engine with timeout and buffer limits.
  • Standard Built-in Tool Library — Ready-to-use tools for httpFetch, file system I/O, codeInterpreter, SQL database queries, and PDF text RAG search.

Installation

npm install nexmon zod

Or using Bun / pnpm / Yarn:

bun add nexmon zod

Quick Start

import { createAgent, Provider, defineTool } from "nexmon";
import { z } from "zod";

// 1. Define a tool with Zod schema validation
const getSystemTimeTool = defineTool({
  name: "get_system_time",
  description: "Fetches current system time",
  parameters: z.object({}),
  execute: async () => {
    return `The current time is ${new Date().toISOString()}`;
  },
});

// 2. Create and run the Agent (using shorthand model or explicit Provider)
const agent = createAgent({
  name: "TimeAssistant",
  model: "gpt-4o-mini", // String shorthand (or pass provider: new Provider({...}))
  instructions: "You are a helpful assistant. Use tools when needed.",
  tools: [getSystemTimeTool],
});

const result = await agent.run("What time is it right now?");
console.log("Response:", result.text);
console.log("Tokens Used:", result.usage.total_tokens);
console.log("Estimated Cost:", `$${result.usage.estimatedCostUsd} USD`);

Developer Recipes & Core Guides

1. Typed Context Dependency Injection (AgentConfig<TContext>)

Thread application state (e.g., user session, database handle, tenant ID) cleanly into tools without global state or closures:

import { createAgent, defineTool } from "nexmon";
import { z } from "zod";

interface AppContext {
  userId: string;
  role: string;
}

const getUserProfileTool = defineTool<z.ZodTypeAny, any, AppContext>({
  name: "get_user_profile",
  description: "Fetches user profile details",
  parameters: z.object({}),
  execute: async (_input, context) => {
    // Strongly typed context!
    const user = context?.context;
    return { userId: user?.userId, role: user?.role, status: "Active" };
  },
});

const agent = createAgent<AppContext>({
  name: "UserAgent",
  tools: [getUserProfileTool],
  context: { userId: "user_9988", role: "admin" },
});

const result = await agent.run("Fetch my profile information.");
console.log(result.text);

2. Defining & Governing Tools (HITL Approvals)

Tools declare parameter schemas using Zod and specify risk levels (LOW, MEDIUM, HIGH, CRITICAL) along with dynamic approval predicates for Human-in-the-Loop authorization:

import { createAgent, defineTool, RiskLevel } from "nexmon";
import { z } from "zod";

const transferFundsTool = defineTool({
  name: "transfer_funds",
  description: "Transfer money to another account",
  parameters: z.object({
    recipientId: z.string(),
    amount: z.number().positive(),
  }),
  riskLevel: RiskLevel.HIGH,
  requiresApproval: (input) => input.amount > 1000,
  execute: async ({ recipientId, amount }) => {
    return `Successfully transferred $${amount} to recipient ${recipientId}`;
  },
});

const agent = createAgent({
  name: "BankAgent",
  tools: [transferFundsTool],
});

const runResult = await agent.run("Transfer $5,000 to user_99");

if (runResult.status === "paused" && runResult.pendingApproval) {
  console.log("Execution Paused for Approval:", runResult.pendingApproval);

  // Resume execution after human approval
  const finalResult = await agent.resume(runResult, {
    approved: true,
    humanFeedback: "Approved by finance manager",
  });
  console.log("Final Output:", finalResult.text);
}

3. Token Budget Limits & Dry-Run Simulation Mode

import { createAgent } from "nexmon";

const agent = createAgent({
  name: "SafetyAgent",
  tokenBudget: { maxTotalTokens: 100 }, // Stop execution cleanly if token count exceeds 100
});

// Run in simulation mode without side-effects
const simResult = await agent.run({
  prompt: "Process dataset and trigger notifications.",
  dryRun: true,
});

console.log("Status:", simResult.status); // "budget_exceeded" or "completed"

4. Model Context Protocol (MCP) Integration

Connecting an Agent to an MCP Server (MCP Client Integration)

Connect external MCP servers (such as Filesystem, GitHub, or Postgres MCP servers over Stdio or SSE) directly to a Nexmon Agent:

import { createAgent, MCPClient, StdioMCPTransport, getToolsFromMCPClient } from "nexmon";

// 1. Create transport to connect to external MCP server process over stdio
const transport = new StdioMCPTransport({
  command: "npx",
  args: ["-y", "@modelcontextprotocol/server-filesystem", "./data"],
});

// 2. Instantiate MCP Client & connect
const mcpClient = new MCPClient(transport, { name: "filesystem_mcp" });
await mcpClient.connect();

// 3. Discover MCP tools and translate them natively into Nexmon Agent tools
const mcpTools = await getToolsFromMCPClient(mcpClient);

// 4. Attach discovered MCP tools directly to a Nexmon Agent
const agent = createAgent({
  name: "MCPAgent",
  instructions: "You inspect and manage workspace files via MCP tools.",
  tools: mcpTools,
});

const result = await agent.run("List all files in ./data and summarize their contents.");
console.log(result.text);

await mcpClient.disconnect();

Exporting a Nexmon Agent as an MCP Server (MCP Server Exporter)

Export any Nexmon agent or tool collection as a standard JSON-RPC 2.0 MCP server so external environments (like Claude Desktop or Cursor) can invoke it:

import { createAgent, exportAgentAsMCPServer } from "nexmon";

const agent = createAgent({ name: "ExportedAgent" });

const mcpServer = exportAgentAsMCPServer(agent, {
  name: "my_nexmon_mcp_server",
  version: "1.0.0",
});

await mcpServer.startStdio();

5. Multi-Agent Orchestration & Workflow Engines

import { createAgent, AgentSwarm } from "nexmon";

const triageAgent = createAgent({ name: "TriageAgent" });
const billingAgent = createAgent({ name: "BillingAgent" });

const swarm = new AgentSwarm({
  agents: [triageAgent, billingAgent],
  defaultAgent: "TriageAgent",
});

const result = await swarm.run("I need help with my monthly invoice.");
console.log("Swarm Final Response:", result.text);

Environment Variables Configuration

Environment Variable Description Default Fallback
NEXMON_API_KEY API Key for LLM Provider (OpenAI, DeepSeek, OpenRouter, etc.) Optional if passed in Provider
NEXMON_BASE_URL Base URL for OpenAI-compatible endpoint https://api.openai.com/v1
NEXMON_MODEL Default model identifier gpt-4o-mini
OTEL_SERVICE_NAME / NEXMON_SERVICE_NAME OpenTelemetry Service Name nexmon-agent
OTEL_EXPORTER_OTLP_ENDPOINT / NEXMON_OTLP_ENDPOINT OTLP Collector Endpoint URL http://localhost:4318/v1/traces
NEXMON_SQLITE_PATH Filepath for SQLite Event Store :memory:

Runnable Examples

Run any of the 23 runnable example scripts using npx tsx:

  • examples/01-basic-agent.ts — Basic agent run & tool execution.
  • examples/02-custom-baseurl.ts — Connecting custom LLM endpoints (Ollama, DeepSeek, OpenRouter).
  • examples/03-governed-tool.ts — Human-in-the-loop (HITL) governance and approval interrupts.
  • examples/04-time-travel-replay.ts — Immutable event sourcing, state reduction, and process crash recovery.
  • examples/05-tiered-memory.ts — Context window management, short-term TTL memory, and episodic vector search.
  • examples/06-subagent-fleet.ts — MCP client tool discovery and subagent fleet parallel execution.
  • examples/07-opentelemetry-hardening.ts — OpenTelemetry span export, cost calculation, and token logging.
  • examples/08-real-life-autonomous-agent.ts — Full enterprise real-world autonomous agent without mocks.
  • examples/09-swarm-handoff.ts — Multi-agent peer-to-peer swarm handoffs.
  • examples/10-workflow-dag.ts — Directed Acyclic Graph (DAG) workflow routing & consensus loops.
  • examples/11-security-guardrails.ts — PII redaction, prompt injection protection, RBAC, and subprocess sandboxing.
  • examples/12-mcp-server-export.ts — Exporting a Nexmon agent as an MCP Server over JSON-RPC.
  • examples/13-standard-tools.ts — Built-in HTTP fetch scraper, file system I/O, and code interpreter tools.
  • examples/15-structured-output.ts — Zod schema validation with automatic retry and repair loops.
  • examples/16-streaming-agent.ts — Real-time event streaming for text chunks and tool calls.
  • examples/18-typed-context-di.ts — Typed context dependency injection (AgentConfig<TContext>).
  • examples/19-parallel-tools.ts — Parallel tool execution with Promise.allSettled().
  • examples/20-token-budget.ts — Token budget enforcement caps and "budget_exceeded" handling.
  • examples/21-on-event-streaming.ts — Real-time push-based event streaming via onEvent hook.
  • examples/22-dry-run.ts — Zero-side-effects simulation mode (dryRun: true).
  • examples/23-prompt-caching.ts — Automatic system prompt caching annotations (cache_control).
npx tsx examples/18-typed-context-di.ts

Verification & Testing

To run full TypeScript typechecks, linting, build, and unit test suites:

npm run typecheck # TypeScript compiler check
npm run lint      # Biome linter check
npm run build     # Compile TypeScript to ./dist
npm test          # Run full test suite (89 unit tests across 29 suites)

License

MIT © Nexmon Team

Releases

Packages

Contributors

Languages