Skip to main content
Glama
Acode Cyber Operations & Developer Command Center

Acode Cyber Operations & Developer Command Center

Acode Cyber Operations & Developer Command Center

A local Model Context Protocol (MCP) server built with Node.js 22, TypeScript, and the official MCP TypeScript SDK v2. It runs inside Acode's Alpine Linux terminal on Android (ARM64 / aarch64, musl libc) and exposes the same unified tool surface over Streamable HTTP (multi-client, Bearer-authenticated) or STDIO (single configured client). It combines workspace access, developer commands, web diagnostics, authorized security assessments, system diagnostics, a local self-pentest, and an interactive terminal command center.

Scope notice: Both transports share one tool registry, one execution engine, one permission model, and one event monitor. Mutating operations are opt-in per permission: filesystem.write, git.write, and terminal.execute are not default, and file_delete additionally requires confirm: true. There is no arbitrary shell, exploit payload delivery, brute-force/fuzzing, or external traffic to undeclared hosts. HTTP default permissions are read-only; the STDIO default is a broader read/diagnostic set described below.


1. Architecture

There is one tool surface for both transports. src/core/services.ts builds a single ServiceBundle per process (config, clients, workspaces, web services, audit, monitor, registry, command/process registries, destination policy) and derives a per-client ToolServices view. src/core/registry.ts installs every tool through one ToolRegistry wrapper, and src/core/monitor.ts gives every invocation one operation id and lifecycle stream. HTTP and STDIO only differ in how a client identity is established; they call the same installAllTools() path, so schemas, permissions, audit records, timeouts, and terminal views stay identical.

  • Unified core — src/core/services.ts (shared bundle + per-client view + single installer), src/core/registry.ts (one registry, metadata from _meta, 180 s default invocation timeout), src/core/monitor.ts (invoke/running/progress/completed/failed events with sanitized detail and bounded history), src/core/command-runner.ts + src/core/background-processes.ts (allowlisted, shell-free child processes with tracking), and src/tools/tool-helpers.ts (audited wrapper).

  • HTTP transport — src/app.ts composes loopback Host/Origin guards, request limits, /health, Bearer auth, and error handlers; src/transport/http.ts creates one McpServer + NodeStreamableHTTPServerTransport per session with owner checks, capacity limits, and TTL reaping; src/server.ts owns bind/ready/shutdown and the terminal runtime.

  • STDIO transport — src/stdio.ts serves MCP on stdout with all logs on stderr. The identity comes from MCP_STDIO_CLIENT_ID / MCP_STDIO_PERMISSIONS; there is no Bearer token and no interactive TUI on the stdio stream.

  • Config & auth — src/config/env.ts (Zod validation, non-overriding .env, fail-fast errors without secrets), src/config/version.ts, src/config/security.ts, src/auth/tokens.ts (SHA-256 + constant-time compare), src/auth/client-registry.ts, src/middleware/auth.ts, and src/config/web-targets.ts.

  • Security model — one shared DestinationPolicy (src/web/destination.ts) for host allowlists/SSRF checks, src/web/security-client.ts for configured-target sessions, and src/workspace/workspace-service.ts for workspace containment, bounded I/O, and fixed-argument git.

  • Tool modules — src/tools/workspace-tools.ts, web-tools.ts, developer-tools.ts, web-diagnostics-tools.ts, security-tools.ts, system-tools.ts, and pentest-tools.ts; supporting services live in src/developer/project-inspector.ts, src/web/web-diagnostics.ts, src/pentest/assessments.ts, and src/pentest/self-pentest.ts.

  • Audit & logging — src/audit/audit-logger.ts, src/utils/logger.ts (Pino redaction), src/logging/log-files.ts (0600 NDJSON rotation), src/logging/log-router.ts, and src/logging/runtime.ts (dashboard/command center lifecycle).

  • Terminal UI — src/ui/command-center.ts (five views driven by the real registry/monitor), plus dashboard.ts, event-store.ts, log-format.ts, startup-animation.ts, terminal.ts, and theme.ts.

  • Errors — src/utils/errors.ts returns sanitized JSON / JSON-RPC 2.0 errors with no stack traces.

Directory Layout

acode-mcp-server/
├── src/
│   ├── app.ts
│   ├── server.ts
│   ├── stdio.ts
│   ├── audit/
│   │   └── audit-logger.ts
│   ├── auth/
│   │   ├── client-registry.ts
│   │   └── tokens.ts
│   ├── config/
│   │   ├── env.ts
│   │   ├── security.ts
│   │   ├── version.ts
│   │   └── web-targets.ts
│   ├── core/
│   │   ├── background-processes.ts
│   │   ├── command-runner.ts
│   │   ├── monitor.ts
│   │   ├── registry.ts
│   │   └── services.ts
│   ├── developer/
│   │   └── project-inspector.ts
│   ├── logging/
│   │   ├── log-files.ts
│   │   ├── log-router.ts
│   │   └── runtime.ts
│   ├── middleware/
│   │   └── auth.ts
│   ├── pentest/
│   │   ├── assessments.ts
│   │   └── self-pentest.ts
│   ├── tools/
│   │   ├── developer-tools.ts
│   │   ├── pentest-tools.ts
│   │   ├── security-tools.ts
│   │   ├── system-tools.ts
│   │   ├── tool-helpers.ts
│   │   ├── web-diagnostics-tools.ts
│   │   ├── web-tools.ts
│   │   └── workspace-tools.ts
│   ├── transport/
│   │   └── http.ts
│   ├── types/
│   │   └── index.ts
│   ├── ui/
│   │   ├── command-center.ts
│   │   ├── dashboard.ts
│   │   ├── event-store.ts
│   │   ├── log-format.ts
│   │   ├── startup-animation.ts
│   │   ├── terminal.ts
│   │   └── theme.ts
│   ├── utils/
│   │   ├── errors.ts
│   │   └── logger.ts
│   ├── web/
│   │   ├── account-store.ts
│   │   ├── destination.ts
│   │   ├── security-analysis.ts
│   │   ├── security-client.ts
│   │   └── web-diagnostics.ts
│   └── workspace/
│       └── workspace-service.ts
├── tests/
│   ├── auth.test.ts
│   ├── command-policy.test.ts
│   ├── compat.test.ts
│   ├── config.test.ts
│   ├── developer-tools.test.ts
│   ├── health.test.ts
│   ├── logging.test.ts
│   ├── mcp.test.ts
│   ├── monitor-registry.test.ts
│   ├── multi-client.test.ts
│   ├── multiclient-config.test.ts
│   ├── pentest-tools.test.ts
│   ├── server.test.ts
│   ├── startup-animation.test.ts
│   ├── support.ts
│   ├── tui.test.ts
│   ├── web-diagnostics.test.ts
│   ├── web-tools.test.ts
│   └── workspace.test.ts
├── scripts/
│   ├── account-admin.mjs
│   ├── client-admin.mjs
│   ├── generate-token.mjs
│   ├── mcp-compat-probe.mjs
│   ├── self-pentest.ts
│   └── verify-runtime.ts
├── docs/
│   ├── codex-config.example.toml
│   ├── command-center.md
│   ├── opencode-config.example.json
│   └── tool-catalog.md
├── .env.example
├── .gitignore
├── .mcp-web-targets.example.json
├── package.json
├── package-lock.json
├── tsconfig.json
├── vitest.config.ts
└── README.md

Related MCP server: Terminal Controller MCP Server

2. Requirements

  • Runtime: Node.js >=22.0.0 <23.0.0 (target v22.23.4)

  • Package Manager: npm >=10.0.0 (target v10.9.1)

  • Target OS: Alpine Linux 3.21 (aarch64 / ARM64, musl libc) via Acode terminal on Android

  • No External Infrastructure: No Docker, cloud services, external databases, or background daemons required.


3. Installation (Alpine Linux in Acode)

apk update
apk add --no-cache nodejs npm openssl

cd acode-mcp-server
npm ci

If npm ci cannot use prebuilt optional native binaries on a restricted Android PRoot environment, inspect npm ci --verbose and see Section 12.


4. Environment Configuration

Copy .env.example to .env (never commit .env or the clients file):

cp .env.example .env

Variable

Default

Description

NODE_ENV

development

development, production, or test

MCP_HOST

127.0.0.1

Loopback bind address (127.0.0.1, localhost, or ::1 only)

MCP_PORT

3333

TCP port (1–65535; 0 allowed only in test)

MCP_ENDPOINT

/mcp

Streamable HTTP endpoint path

MCP_BEARER_TOKEN

(optional)

Legacy single-token secret. Required unless a clients file defines at least one client.

MCP_LEGACY_CLIENT_ID

codex-cli

Client id assigned to the legacy token (always read-only)

MCP_CLIENTS_FILE

auto-detect

Path to a JSON clients file. If unset, ./.mcp-clients.json is used when present.

MCP_STDIO_CLIENT_ID

opencode

Client id used by src/stdio.ts (no Bearer token on stdio).

MCP_STDIO_PERMISSIONS

read/diagnostic set

Comma-separated permissions for the stdio client. Default: filesystem.read,filesystem.search,project.inspect,web.inspect,web.diagnostics,security.assess,system.inspect,git.read. No write/execute/session permissions by default.

MCP_WEB_TARGETS_FILE

auto-detect

Path to the optional JSON web targets file. If unset, ./.mcp-web-targets.json is used when present. The web_* target tools are not registered without it.

MCP_WEB_ALLOWED_HOSTS

(empty)

Comma-separated public hosts allowed for web diagnostics and security assessments in addition to web target hosts (api.osv.dev is always allowed for dependency checks). Private/loopback/metadata hosts are skipped.

MCP_ACCOUNTS_FILE

./.mcp-accounts.json

Local 0600 store for accounts created by web_register. Contains test passwords so web_login can reuse them; never committed or returned by tools.

MCP_WORKSPACE_ROOTS

default=.

Comma-separated id=path workspace roots. A single bare path is named default. / is rejected.

MCP_REQUEST_SIZE_LIMIT

1mb

Max HTTP JSON body size (b, kb, mb, max 10mb)

MCP_SESSION_TTL_MS

1800000

Idle MCP session expiration in milliseconds (30 min)

MCP_MAX_SESSIONS

32

Maximum concurrent MCP sessions

LOG_LEVEL

info

Pino level (fatal, error, warn, info, debug, trace, silent)

MCP_TUI

auto

Terminal dashboard: auto (interactive TTY, viewport ≥ 60×18), on, or off

MCP_LOG_FORMAT

auto

Console format when the dashboard is inactive: auto, pretty, or json. Non-TTY output is always NDJSON.

MCP_LOG_FILE

.mcp/logs/server.ndjson

Append-only NDJSON server log (0600, ~5 MiB rotation, 3 backups)

MCP_AUDIT_FILE

.mcp/logs/audit.ndjson

Dedicated NDJSON audit trail (0600, same rotation)

MCP_TUI_LOG_LINES

8

Activity rows kept in the dashboard (3–20)

MCP_TUI_REFRESH_MS

150

Dashboard refresh interval in milliseconds (100–1000)

MCP_STARTUP_ANIMATION

auto

Cosmetic boot animation by npm start: auto (TTY only), on, or off

SHUTDOWN_TIMEOUT_MS

5000

Graceful shutdown force-close timeout in milliseconds

The terminal layer also reads NO_COLOR=1 (no ANSI color), MCP_ASCII=1 (ASCII frame characters), CI=1 / TERM=dumb (disable interactive rendering), and COLUMNS / LINES (viewport fallback when stdout is not a TTY). These are display switches, not Zod-validated app config; they are listed as comments in .env.example.


4.1 Startup Boot Animation

npm start plays a short Linux/Ubuntu-style boot sequence on an interactive terminal: GRUB-style loader lines, kernel timestamps, systemd-like pending/[ OK ] steps, boot targets, an animated progress bar, and a MOTD/neofetch-style banner with Tux, the endpoint, clients, workspaces, and web-egress status.

  GRUB loading ...
  Booting `acode-mcp-server (v0.1.1)'
  Loading Linux 6.6.118-android15 arm64 ...
  Loading initial ramdisk ...

  [    0.000000] acode-mcp-server: initializing v0.1.1 (development)
  [    0.000031] kernel Linux 6.6.118-android15 arm64 · node v22.23.4 · pid 4242
  [    0.000052] acode-init: loopback-only binding enforced
  [    0.000184] [  OK  ] loading configuration & secrets (0.004s)
  [    0.004395] [  OK  ] mounting workspace roots (1) (0.010s)
  ...
  [    0.042404] [  OK  ] Reached target Multi-Client Session Hub.
  [    0.044238] [  OK  ] Started Acode MCP Server.

  Welcome to acode-mcp-server (Linux 6.6.118-android15 arm64)
  Loopback only. Every session is permission-gated and audited.

╭──────────────────────────────────────────────────────────╮
│ ▲ ACODE MCP SERVER                                v0.1.1 │
│ GNU/Linux · security-hardened · multi-client             │
╰──────────────────────────────────────────────────────────╯

  System information as of 2026-11-15 02:09:37 UTC

       .--.       ● acode-mcp-server.service — active (running)
      |o_o |      endpoint   http://127.0.0.1:3333/mcp
      |:_/ |      bound      127.0.0.1:3333  ·  pid 4242
     //   \ \     clients    3  ·  workspaces: default
    (|     | )    web egress 1 target  ·  1 login-enabled
   /'\_   _/`\    mode       development  ·  node v22.23.4
   \___)=(___/    system     Linux 6.6.118-android15 arm64  ·  node v22.23.4

  ready · Ctrl+C to stop · MCP_STARTUP_ANIMATION=off to disable

Startup is split into two truthful phases:

  1. Boot phase (before the listener binds) — GRUB/kernel lines, [ OK ] service steps, boot targets, progress bar, and a Started Acode MCP Server. line. It never claims the service is already serving.

  2. Ready phase (after listen() succeeds) — the MOTD/neofetch banner above, or, when the terminal dashboard is active, the dashboard header itself. The active (running) status therefore only appears once the port is actually accepting connections.

On SIGINT/SIGTERM the server completes its graceful shutdown first, restores the cursor and leaves the alternate screen, then prints a matching power-off sequence (Stopped Acode MCP Server., Reached target Power-Off.) with uptime. It is cosmetic only and never changes the exit code or shutdown timing; a clean Ctrl+C exits with code 0.

  • MCP_STARTUP_ANIMATION=auto (default) — only when stdout is a real TTY; automatically off in CI, tests, TERM=dumb, and piped/background output, so structured JSON logs are never polluted.

  • MCP_STARTUP_ANIMATION=on — force the animation (plain text, no ANSI or \r, when not a TTY).

  • MCP_STARTUP_ANIMATION=off — disable both boot and power-off animations.

  • NO_COLOR=1 keeps the animation but disables ANSI colors.

  • The wide neofetch/MOTD banner is used at 66 columns or more; narrower terminals get a compact 4-line layout.

  • If Ctrl+C arrives during the boot animation, the cursor is restored before exit.

4.2 Terminal Dashboard & Structured Logging

When stdout is a real interactive TTY, MCP_TUI=auto replaces the scrollback log stream with a live, Ubuntu/Kali-style dashboard on the alternate screen. It redraws only changed rows every MCP_TUI_REFRESH_MS (default 150 ms), re-reads the viewport on SIGWINCH, and adapts to terminal width:

╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ▲ ACODE MCP SERVER                                                                               v0.1.1 · production │
│ ● active (running)   uptime 00:00:42   pid 23016   sessions 1/32                                                     │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

─ SYSTEM ───────────────────────────────────────────────── │ ─ ACTIVE SESSIONS ─────────────────────────────────────── 1
  kernel     Linux 6.6.118-android15 arm64                 │   codex-cli/b5bc6813  idle 825ms
  node       v22.23.4 · pid 23016                          │
  session    1 active / 32 max                             │ ─ WORKSPACES ──────────────────────────────────────────── 1
  ttl        30m                                           │   default /public/MCP/acode-mcp-server
                                                           │
─ ENDPOINT ─────────────────────────────────────────────── │ ─ WEB EGRESS ──────────────────────────────────────────────
  → http://127.0.0.1:3333/mcp                              │   allowlist  1 target · 1 login-enabled · 0 registration
  transport  streamable-http (stateful)                    │   ronajiwa https://ronajiwa.example
  bound      127.0.0.1:3333                                │ ─ ACTIVITY ──────────────────────────────────────────────── live
─ CLIENTS ──────────────────────────────────────────────── │  10:11:12  MCP    session opened  codex-cli · d07174f4
  Codex CLI  3 perm · 1 ws · 1 sess                        │  10:11:13  HTTP   200 GET /health  9ms ×5
  OpenCode   7 perm · 1 ws · 0 sess                        │  10:11:14  AUDIT  web_login success  ronajiwa · 812ms
● acode-mcp-server v0.1.1 · logs .mcp/logs/server.ndjson · Ctrl+C to stop
  • The header shows brand, version, environment, status dot, uptime, PID, and session usage. Status moves through starting → active (running) → stopping (graceful shutdown).

  • Panels cover system information, the MCP endpoint/transport, configured clients, active sessions (truncated ids, idle time), workspaces, web egress, and a live activity feed.

  • At ≥92 columns the layout is two-column; 60–91 columns is stacked; below 60×18 (or with MCP_TUI=on on a narrow terminal) a compact summary is used. Every line is truncated to the terminal width so ANSI styling can never wrap and corrupt the frame.

  • Consecutive identical events within 1.5 s collapse into one row with a ×N counter (for example health checks or a 20-session shutdown). History is bounded and activity rows are capped by MCP_TUI_LOG_LINES.

  • Log messages are sanitized (ANSI/control characters stripped), audit entries are tagged AUDIT, and raw JSON is never printed on the dashboard.

File logging is always on, independent of the dashboard:

Path

Contents

MCP_LOG_FILE (./.mcp/logs/server.ndjson)

Every structured record, one JSON object per line

MCP_AUDIT_FILE (./.mcp/logs/audit.ndjson)

Only records with audit: true, preserving the full audit trail for compliance

Both files are created with mode 0600 inside a 0700 directory, rotate at ~5 MiB keeping 3 backups (*.1 … *.3), and are flushed during graceful shutdown. Full session ids, client ids, durations, and error codes stay in these files even when the dashboard truncates them for display.

Fallback and non-TTY behavior:

  • MCP_TUI=off disables the alternate screen and dashboard but keeps pretty single-line console logs on a TTY.

  • Piped, CI, background, and test output always emits valid NDJSON on stdout — MCP_LOG_FORMAT=pretty is intentionally ignored there so tooling is never broken.

  • MCP_LOG_FORMAT=json disables the dashboard even on a TTY (unless MCP_TUI=on explicitly forces it).

  • NO_COLOR=1 keeps pretty layout but removes ANSI color; a closed terminal/EPIPE never crashes the server.

The dashboard and file sinks are implemented with native Node APIs only (no new runtime dependencies), which keeps the Alpine/ARM64 footprint small.

4.3 Command Center (interactive HTTP CLI)

When the terminal UI is active on the HTTP CLI (MCP_TUI=auto on a real TTY, or MCP_TUI=on), src/ui/command-center.ts replaces the passive dashboard with an interactive view. It reads the live ToolRegistry, ExecutionMonitor, session snapshot, and configured services; it never invents tool activity. STDIO never renders a TUI (stdout is the protocol stream, logs go to stderr). Full details: docs/command-center.md.

View

Key

Shows

Overview

1

Endpoint/transport, configured clients, active sessions, authorized egress count, live activity feed

Tools

2

Every tool actually registered for this process with category, permission, and !confirm marker

Operations

3

Active and recent invocations with status, duration, client id, and selected-operation detail

Events

4

Sanitized lifecycle events (tool registered/invoked/running/progress/completed/failed, client connected/disconnected, system transitions) and counters

System

5

Live Node/V8/OS/memory data, authorized destinations, session limits, body limit, log path

Keys: ← / → or Tab cycle views, 1–5 jump to a view, ↑ / ↓ move the selection in list views, r / R force a refresh, q requests a graceful shutdown (tui_quit), and Ctrl+C (SIGINT) stops the server. The frame is redrawn only when rows change, every MCP_TUI_REFRESH_MS; terminal resize (SIGWINCH) and resume (SIGCONT) are handled.


5. Multi-Client Authentication Model

Each client authenticates with its own Bearer token and receives its own identity, permissions, workspace scope, and MCP sessions. Only SHA-256 token hashes are stored; raw tokens are never persisted by the server.

Two ways to define clients:

  1. Legacy single token — set MCP_BEARER_TOKEN. It is mapped to MCP_LEGACY_CLIENT_ID (default codex-cli) with read-only permissions and access to all workspaces.

  2. Clients file — a JSON file (auto-detected at ./.mcp-clients.json or set via MCP_CLIENTS_FILE):

{
  "version": 1,
  "clients": [
    {
      "id": "codex",
      "name": "Codex CLI",
      "tokenHash": "sha256:<64-hex-digest>",
      "permissions": ["filesystem.read", "filesystem.search", "project.inspect"],
      "workspaces": ["project"],
      "revoked": false
    },
    {
      "id": "opencode",
      "name": "OpenCode",
      "tokenHash": "<64-hex-digest>",
      "permissions": ["filesystem.read", "filesystem.search", "filesystem.write", "project.inspect", "git.read"],
      "workspaces": ["project"],
      "revoked": false
    }
  ]
}
  • permissions defaults to the read-only set when omitted.

  • workspaces empty means all configured workspaces; otherwise the client is restricted to the listed ids.

  • revoked: true disables a client without deleting its entry.

  • tokenHash accepts a bare 64-char hex SHA-256 digest or the sha256:-prefixed form.

Permissions

Permission

Grants

filesystem.read

workspace_list, workspace_list_files, workspace_read_file, file_metadata, dir_inspect

filesystem.search

workspace_search

project.inspect

project_inspect and the project_* inspector tools

filesystem.write

workspace_write_file, file_create, file_delete (file_delete needs confirm: true) — opt-in

git.read

git_status, git_diff, git_log, git_branches, git_diagnostics — no shell, allowlisted flags

git.write

git_commit, git_pull, git_push — opt-in

web.inspect

web_targets, web_probe, web_security_headers, web_check_exposure (requires a targets file)

web.session

web_login, web_fetch, web_logout (uses configured/stored credentials or a saved account)

web.register

web_register, web_accounts (one account per call, hard caps, 0600 local store)

web.diagnostics

website_check, http_status, dns_lookup, ssl_certificate, http_headers, redirect_analyze, response_time, website_metadata, robots_txt, sitemap_inspect, domain_info, api_health, api_request, json_validate, web_connectivity

security.assess

security_* assessments (HTTP, headers, TLS, DNS, cookies, CORS, endpoints, exposure paths, OSV dependency check)

system.inspect

node_runtime, system_* diagnostics and reports

terminal.execute

terminal_exec, npm_run, bun_run, tsc_run, test_run, build_run, devserver_*, process_status — opt-in

pentest.self

pentest_self (local throwaway instance; opt-in, rate limited)

database.inspect

Reserved (no tool registered yet)

HTTP clients default to the read-only set filesystem.read, filesystem.search, project.inspect. The STDIO client defaults to filesystem.read,filesystem.search,project.inspect,web.inspect,web.diagnostics,security.assess,system.inspect,git.read with id opencode and all workspaces; it deliberately excludes write, git.write, terminal.execute, and web session/registration permissions. Change it with MCP_STDIO_PERMISSIONS (and optionally MCP_STDIO_CLIENT_ID). Tools a client lacks permission for are not registered at all, not merely rejected at call time.


6. Managing Clients

Use the included helper to create, rotate, revoke, and remove clients without hand-editing hashes:

# Add a read-only client (prints the raw token once)
node scripts/client-admin.mjs add codex --name "Codex CLI" --workspaces project

# Add a client that may also write, read git status, and assess websites
node scripts/client-admin.mjs add opencode \
  --permissions filesystem.read,filesystem.search,filesystem.write,project.inspect,git.read,web.inspect,web.session,web.register \
  --workspaces project

# Add a dedicated read-only website assessment client
node scripts/client-admin.mjs add web-audit \
  --permissions web.inspect,web.session \
  --workspaces project

# Inspect, update, rotate, revoke, remove
node scripts/client-admin.mjs list
node scripts/client-admin.mjs update opencode --permissions filesystem.read,filesystem.search,filesystem.write,project.inspect,git.read,web.inspect,web.session,web.register
node scripts/client-admin.mjs rotate opencode
node scripts/client-admin.mjs revoke codex
node scripts/client-admin.mjs remove codex

update changes permissions/workspaces/name in place; existing client tokens remain valid, so no token rotation is needed. Use rotate to issue a new token.

Use --file <path> to target a specific clients file. The file is written with 0600 permissions and is git-ignored.

Generate a standalone secret (for the legacy MCP_BEARER_TOKEN):

openssl rand -hex 32
# or
node scripts/generate-token.mjs

7. Build and Start the Server

Development Mode (TypeScript via tsx)

npm run dev
npm run build
NODE_ENV=production npm start

The server binds to http://127.0.0.1:3333 with MCP served at http://127.0.0.1:3333/mcp and health at http://127.0.0.1:3333/health. On an interactive terminal it shows the command center (§4.3) and still writes ./.mcp/logs/server.ndjson plus ./.mcp/logs/audit.ndjson. Piped output stays pure NDJSON.

Stop cleanly with Ctrl+C (SIGINT), kill -TERM <pid> (SIGTERM), or q in the command center.

7.1 STDIO transport

npm run build
npm run start:stdio          # node dist/stdio.js
# or, while developing:
npm run dev:stdio            # tsx src/stdio.ts

src/stdio.ts serves MCP over stdin/stdout and writes every log to stderr so the protocol stream stays clean. It uses MCP_STDIO_CLIENT_ID / MCP_STDIO_PERMISSIONS, not HTTP Bearer tokens or the clients file, but shares the same service bundle, tool installer, permission checks, audit logger, and monitor. No HTTP listener, /health, or TUI is started in this mode. SIGINT/SIGTERM stop managed child processes and close the transport.


8. Type Checks, Tests, and Runtime Verification

npm run typecheck       # strict TypeScript checking
npm test                # Vitest suite
npm run check           # typecheck + tests + build
npm run verify:runtime  # live end-to-end check against dist/server.js
npm run compat          # live MCP protocol compatibility matrix against a running server

The suites in tests/ cover configuration, authentication, health, MCP session lifecycle, invalid requests, graceful shutdown, multi-client identity/session isolation, permissions, workspace authorization, path traversal and symlink escapes, audit redaction, web tools, the self-pentest tool, terminal log formatting/aggregation, command-center rendering/keys, NDJSON file rotation, and TTY/non-TTY console gating. The commands above are for you to run on your device; this document does not assert a passing result.

8.1 Client Compatibility Probe

With the server already running, npm run compat (or node scripts/mcp-compat-probe.mjs --url http://127.0.0.1:3333/mcp --token <token>) checks the protocol surface a client actually sees: lifecycle, session isolation, protocol-version negotiation, tools/list/tools/call, logging/setLevel, SSE GET, DELETE, and graceful -32601 rejection of resources, prompts, sampling, roots, elicitation, and completion. It prints PASS/FAIL/SKIP lines and exits non-zero only on FAIL.

npm run compat -- --client codex --verbose

--client <id> picks <ID>_TOKEN from .mcp-tokens.txt (default OPENCODE_TOKEN). This server intentionally advertises only tools and logging; clients that require resources, prompts, or sampling must treat those as optional, which current MCP clients do.

8.2 Self-Pentest Harness

npm run pentest:self           # human-readable PASS/FAIL report
npm run pentest:self -- --json # machine-readable report

This runs an adversarial suite against a throwaway server instance only. The harness boots the real Express/MCP stack on a random loopback port with generated bearer tokens, four synthetic clients (including a revoked one), and a temporary workspace fixture. It then sends hostile-but-bounded traffic and asserts the server degrades safely instead of crashing or leaking data:

  • Authentication — missing/malformed schemes, invalid/truncated/revoked tokens, tokens in the wrong header.

  • Transport — defensive headers, wrong Content-Type, missing SSE Accept, malformed JSON, oversized bodies, DNS-rebinding Host/cross-site Origin, method/route guards.

  • Protocol — JSON primitives, malformed initialize, unknown methods/tools, invalid tool arguments, notification bursts.

  • Authorization — permission-scoped tool discovery, workspace isolation, cross-client session hijack (GET/POST/DELETE), forged session ids, path traversal, absolute paths, null bytes, symlink escapes.

  • Resilience — parallel auth failures, concurrent initialize bursts at the session cap, oversized search queries, TTL reaping.

  • Disclosure — every captured response is scanned for bearer tokens, stack traces, node:internal, and absolute source paths.

A /health probe runs after every case, plus process-level uncaughtException and unhandledRejection capture. The command exits non-zero on any FAIL, any unhealthy probe, or any fatal event. It never contacts an external host, never uses real credentials, and removes the fixture and shuts the server down in a finally block. It is a hardening tool, not a traffic generator against third-party systems.


9. Health Endpoint & Auth Guard

curl -sS http://127.0.0.1:3333/health

Expected (200 OK):

{
  "status": "ok",
  "service": "acode-mcp-server",
  "version": "0.1.1",
  "transport": "streamable-http",
  "endpoint": "/mcp",
  "uptimeSeconds": 4,
  "activeSessions": 0,
  "timestamp": "2026-11-13T00:00:00.000Z"
}

Missing auth is rejected with 401; an authenticated initialize handshake returns an mcp-session-id header:

curl -i -X POST http://127.0.0.1:3333/mcp \
  -H "Authorization: Bearer $MCP_BEARER_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-11-25",
      "capabilities": {},
      "clientInfo": { "name": "curl-check", "version": "0.1.1" }
    }
  }'

10. Connecting Clients

Three connection shapes are supported: HTTP with per-client Bearer tokens, HTTP with the legacy token, and STDIO with the configured stdio identity. Copy the complete examples from docs/opencode-config.example.json and docs/codex-config.example.toml.

Compatibility note: the opencode and codex CLIs are installed in this environment, and the flags below match their mcp add --help output. No live initialize / tools/list handshake from either CLI was performed for these docs, so treat the config files as compatibility examples, not tested integrations. The server-side protocol surface is independently exercised by npm run compat and the Vitest suites.

10.1 OpenAI Codex CLI

HTTP server (token kept in the environment, not TOML):

codex mcp add acode-http \
  --url http://127.0.0.1:3333/mcp \
  --bearer-token-env-var MCP_BEARER_TOKEN

Or place the equivalent in ~/.codex/config.toml (or project .codex/config.toml) as shown in the linked example. Export the token in the shell that starts codex:

export MCP_BEARER_TOKEN="<token whose hash is in the clients file, or the legacy token>"
codex

STDIO server (after npm run build):

codex mcp add acode-stdio -- node /absolute/path/to/acode-mcp-server/dist/stdio.js

--env KEY=VALUE is available for stdio servers if you need to override MCP_STDIO_CLIENT_ID or MCP_STDIO_PERMISSIONS locally. Do not export MCP_BEARER_TOKEN for the stdio entry; it is not used there.

Common failure: if MCP_BEARER_TOKEN is not exported for an HTTP entry, Codex reports that the environment variable is not set and never completes initialize (the server shows activeSessions: 0).

10.2 OpenCode (v2)

HTTP server (quote {env:...} so the shell writes it literally):

opencode mcp add acode-http \
  --url http://127.0.0.1:3333/mcp \
  --header 'Authorization=Bearer {env:MCP_BEARER_TOKEN}'

STDIO server (after npm run build):

opencode mcp add acode-stdio -- node /absolute/path/to/acode-mcp-server/dist/stdio.js

The JSON example file shows both mcp.servers entries; OpenCode v2 stores remote servers under mcp.servers with type: "remote". Check configured entries with opencode mcp list. Older clients pinned to a single newer protocol revision may not connect; see the compatibility note in §13.


11. Tool Catalog

Tools are registered per client from their permissions. The table below is a compact index; docs/tool-catalog.md lists every tool with its permission and input outline. The command-center Tools view renders the actual registry for the running process.

Category

Tools (permission)

Workspace & project

workspace_list, workspace_list_files, workspace_read_file (filesystem.read); workspace_search (filesystem.search); project_inspect, project_structure, project_package, project_dependencies, project_tsconfig, project_env_validate, project_imports, project_build_config, project_health (project.inspect); workspace_write_file, file_create, file_delete (filesystem.write)

Git

git_status, git_diff, git_log, git_branches, git_diagnostics (git.read); git_commit, git_pull, git_push (git.write)

Developer & processes

terminal_exec, npm_run, bun_run, tsc_run, test_run, build_run, devserver_start, devserver_status, devserver_stop, process_status (terminal.execute); file_metadata, dir_inspect (filesystem.read); node_runtime (system.inspect)

Web targets

web_targets, web_probe, web_security_headers, web_check_exposure (web.inspect); web_login, web_fetch, web_logout (web.session); web_register, web_accounts (web.register). Registered only when a targets file exists.

Web diagnostics

website_check, http_status, dns_lookup, ssl_certificate, http_headers, redirect_analyze, response_time, website_metadata, robots_txt, sitemap_inspect, domain_info, api_health, api_request, json_validate, web_connectivity (web.diagnostics)

Security assessments

security_http_assess, security_headers_inspect, security_web_config, security_exposed_config, security_sensitive_files, security_cookies_inspect, security_cors_inspect, security_endpoints_assess, security_findings_report, security_tls_check, security_dns_inspect, security_dependencies_check (security.assess)

System

system_runtime, system_memory, system_tools, system_processes, system_workspaces, system_connectivity, system_mcp_health, system_dependencies, system_events, system_report (system.inspect)

Self-test

pentest_self (pentest.self)

In one line: workspace tools inspect/read/write confined files; project tools inspect package/TS/env/imports; git tools read or (opt-in) commit/sync; developer tools run allowlisted commands and managed dev servers; web target tools assess configured sites with stored sessions; web diagnostics make bounded requests to authorized hosts; security tools classify live findings; system tools report real local state; pentest_self exercises a throwaway instance of this server. See §12 for the enforcement boundaries.

11.1 Website Security Assessment (Optional, Non-Destructive)

Authorization required. Only add websites you own or have explicit written permission to test. The tools perform passive configuration review and authenticated page inspection — not exploitation.

Create .mcp/web-targets.json with mode 0600 (see .mcp-web-targets.example.json) and point MCP_WEB_TARGETS_FILE at it:

{
  "version": 1,
  "targets": [
    {
      "id": "my-site",
      "baseUrl": "https://example.com",
      "allowedHosts": ["example.com", "www.example.com"],
      "allowPrivateNetwork": false,
      "maxRequestsPerMinute": 20,
      "exposurePaths": ["/.env", "/.git/config", "/.DS_Store", "/server-status"],
      "login": {
        "path": "/login",
        "contentType": "application/x-www-form-urlencoded",
        "usernameField": "username",
        "passwordField": "password",
        "successStatuses": [200],
        "successBodyIncludes": "dashboard",
        "csrf": {
          "tokenField": "_csrf",
          "sourcePath": "/login",
          "postField": "_csrf"
        }
      },
      "credentials": { "username": "audit-account", "password": "..." }
    },
    {
      "id": "spa-api",
      "baseUrl": "https://app.example.com",
      "allowedHosts": ["app.example.com"],
      "allowPrivateNetwork": false,
      "maxRequestsPerMinute": 20,
      "exposurePaths": ["/.env", "/.git/config"],
      "login": {
        "path": "/api/auth/login",
        "contentType": "application/json",
        "usernameField": "email",
        "passwordField": "password",
        "successStatuses": [200],
        "tokenJsonPath": "data.accessToken"
      },
      "credentials": { "username": "audit@example.com", "password": "..." },
      "registration": {
        "path": "/api/auth/register",
        "contentType": "application/json",
        "usernameField": "email",
        "passwordField": "password",
        "displayNameField": "displayName",
        "successStatuses": [200, 201],
        "tokenJsonPath": "data.token",
        "emailDomain": "example.com",
        "emailPrefix": "audit",
        "allowProvidedCredentials": true,
        "autoLogin": true,
        "maxAccountsPerDay": 3,
        "maxAttemptsPerHour": 5,
        "profiles": [
          {
            "id": "audit-profile-1",
            "username": "audit-profile-1@example.com",
            "password": "...",
            "displayName": "Audit Profile 1"
          }
        ]
      }
    }
  ]
}

For SPA/API targets that return a bearer/JWT token instead of a cookie, set login.tokenJsonPath to the dot path of the token in the JSON response (e.g. data.accessToken). If omitted, common field names (accessToken, access_token, token, jwt, idToken, id_token) are auto-detected, including inside data/result/session/auth. The token is held in memory per client+target and sent as Authorization: Bearer … by web_fetch; it is never returned by a tool or written to logs.

For cookie-based forms protected by a hidden CSRF field, set login.csrf:

  • tokenField (required): name of the hidden <input> to read from the login page, e.g. _csrf.

  • sourcePath (optional): fixed GET path that renders the form; defaults to login.path.

  • postField (optional): field name sent in the login POST; defaults to tokenField.

web_login then performs one bounded GET to sourcePath, stores the returned cookies in the same client+target session, extracts one hidden input value (max 512 characters), and includes it with the configured credentials in the POST. If the field is missing, the login POST is not sent and the error code is csrf_token_missing. No token or dynamic value is accepted from tool arguments; the handshake consumes the target's normal rate limit for each request.

11.2 Account Registration (Optional, One Account per Call)

web_register requires the separate web.register permission. It creates exactly one account per call through the configured registration endpoint and stores the credentials in .mcp-accounts.json (mode 0600, git-ignored) so web_login can reuse them later:

// 1. Generate a fresh email/password (default; uses emailPrefix + emailDomain)
{ "target": "spa-api" }

// 2. Use a profile defined in registration.profiles
{ "target": "spa-api", "profile": "audit-profile-1" }

// 3. Register credentials supplied by the user (requires allowProvidedCredentials)
{ "target": "spa-api", "username": "new-user@example.com", "password": "..." }
  • web_register returns only metadata: accountId, username, display name, source (generated / provided / profile), auth mode, and whether a session was saved. Passwords are never returned.

  • Generated accounts use <emailPrefix>+<unique-tag>@<emailDomain> (a plus-alias on services such as Gmail). Set emailDomain explicitly, or the domain is derived from the configured login username.

  • autoLogin: true reuses a token from the registration response or performs one login automatically. Otherwise call web_login with { "target": "...", "account": "<accountId>" } (or "latest").

  • web_accounts lists saved accounts without passwords. Delete .mcp-accounts.json to forget them all.

  • Terminal helpers: node scripts/account-admin.mjs list, node scripts/account-admin.mjs show <id|latest> (prints the password), and node scripts/account-admin.mjs remove <id>.

  • Hard caps, not configurable from tool arguments: one account per call, maxAccountsPerDay (default 3, max 10) and maxAttemptsPerHour (default 5, max 10) per client+target.

  • Registration is rejected by default for user-provided credentials unless allowProvidedCredentials: true. A rejected registration never stores an account and invalidates any previous session for that target.

Hard guardrails (not configurable from tool arguments):

  • Host allowlist: only baseUrl/allowedHosts hosts are contacted; tool input can only choose a path.

  • Private network blocked: loopback/RFC1918/CGNAT/link-local destinations require allowPrivateNetwork: true (for LAN staging only). DNS results are re-checked.

  • Bounded methods: web_probe/web_fetch/web_check_exposure use GET only; POST exists solely for the configured login and registration endpoints. The separate web.diagnostics tool api_request allows GET/HEAD/POST/PUT/PATCH/DELETE/OPTIONS but rejects authentication headers, caps the body at 64 KiB, and only targets authorized destinations. No uploads or arbitrary credential headers.

  • Bounded: 10 s timeout, max 5 redirects (no HTTPS→HTTP downgrade), 256 KB response cap, 8 KB text preview, 32 exposure paths, maxRequestsPerMinute (default 20, max 60), 5 login attempts per 10 minutes, and the registration caps above.

  • No brute force or payload injection: exposure checks visit only the fixed configured paths; no directory discovery, fuzzing, or SQLi/XSS payloads. Registration never creates bulk accounts.

  • Secrets stay server-side: login credentials come from the targets file; registration credentials come from a configured profile, generated locally, or the explicit web_register arguments. They are never logged or returned, and cookie/bearer-token values are never returned either. Generated/provided passwords are written only to the local 0600 accounts file.

  • Sessions: cookies and bearer tokens are held in memory per client+target for 30 minutes; web_logout clears them and a failed login/registration invalidates any previous session for that target.

web_security_headers returns individual findings plus a weighted score (0–100) and grade. This is a heuristic configuration review, not a penetration test and not proof that a site is secure.

Use a dedicated low-privilege test account for web_login; avoid real customer/admin credentials. Only register accounts on sites you own or have explicit written permission to test.

11.3 Self-Pentest Tool (pentest_self)

Grant the opt-in permission to a client (it is not in the default read-only set):

node scripts/client-admin.mjs update opencode \
  --permissions filesystem.read,filesystem.search,project.inspect,pentest.self

Then call it from the MCP client:

{ "name": "pentest_self", "arguments": { "detail": "summary" } }

The tool has no URL, host, path, or credential input, so it cannot be pointed at an external system. It boots a throwaway server on a random loopback port, runs the suite in §8.2, and returns counts plus any failures (detail: "full" adds every case). Access is capped at 3 runs per 10 minutes per client, with a single-flight guard, and every call is audited. Harness exceptions are logged server-side and returned as a generic pentest_error so temporary fixture paths never reach the client.


12. Audit & Security Notes

  • Every tool call emits a structured audit event (audit: true) with clientId, optional sessionId, operation, optional workspace or target, result (success / denied / error), durationMs, and optional errorCode.

  • Audit records are mirrored into the dedicated MCP_AUDIT_FILE (./.mcp/logs/audit.ndjson, 0600) so the trail survives log rotation and can be reviewed independently of the dashboard.

  • Bearer tokens, token hashes, and file contents are never written to logs; Pino redaction also covers Authorization headers and token fields.

  • Sessions are owned by the authenticated client. Presenting another client's Mcp-Session-Id returns 404.

  • Authentication compares all candidate token digests with crypto.timingSafeEqual and no early exit.

  • The HTTP server is loopback-only by default. There is no arbitrary shell: child processes come from a fixed command/argument policy, and state changes are permission-gated.

12.1 Security boundaries

  • Workspace sandbox — roots are canonicalized at startup (realpath); every path must be relative, free of null bytes, and inside an authorized root after realpath. Absolute paths, .. traversal, and symlink escapes are rejected. Reads cap at 1 MiB (default 256 KiB), writes at 256 KiB, listings at 500 entries, and searches at 100 results / 2000 files / depth 8. Writes are 0600; file_create refuses to overwrite.

  • Command allowlist — terminal_exec and wrapper tools spawn only git, npm, bun, node, tsc, or vitest with shell: false, an allowlisted subcommand/flag set (max 24 args), and cwd fixed to the workspace. Timeouts are 1–180 s (default 60 s); stdout is capped at 256 KiB and stderr at 16 KiB. Background dev servers are limited to 8 per process and owned by the starting client.

  • Destination allowlist / SSRF — web tools only contact hosts from the web targets file and MCP_WEB_ALLOWED_HOSTS; diagnostics additionally permit the fixed api.osv.dev host for dependency checks. Hostnames like localhost, *.local, *.internal, and cloud metadata endpoints are rejected; private/reserved IPv4/IPv6 is blocked unless a target explicitly opts in. DNS results are re-checked before connect, credentials in URLs are rejected, and only safe header names/values reach outbound requests.

  • Redirect validation — every hop is re-validated against the destination policy. The configured-target client follows at most 5 redirects and refuses HTTPS→HTTP downgrades; the diagnostics client uses a policy limit of up to 3 and validates each location before following. Response bodies are capped at 256 KiB.

  • Destructive confirmations — file_delete requires the literal confirm: true in its schema and refuses symlinks/directories. filesystem.write and git.write are opt-in permissions; git_commit, git_pull, and git_push are permission-gated but do not use a per-call confirmation. No exploit payloads, fuzzing, or brute-force endpoints exist.


13. Android / Acode / Alpine Linux ARM64 Limitations

  • PRoot & Process Lifecycle: Acode runs Alpine in Android user-space (typically PRoot without systemd). Android's battery optimizer / Low Memory Killer can suspend or terminate background terminal sessions. Run the compiled dist/server.js (lower RAM than tsx) and disable battery optimization for Acode when keeping sessions open.

  • Native Addons & musl libc: Runtime dependencies are pure JavaScript/TypeScript with zero native C++ (node-gyp) addons. Dev tools (vitest, tsx) publish linux-arm64-musl binaries; typescript is pure JavaScript.

  • Device Verification Status: The validation commands in §8 are provided for the target hardware (Node 22, aarch64, Alpine/musl). This document does not assert that they were run here; treat first-run behavior on a physical Android device as requiring a smoke test.

  • Protocol Compatibility: This implementation targets the stateful Streamable HTTP initialize handshake and negotiates 2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05, and 2024-10-07. It does not implement the newer 2026-07-28 server/discover entry point; a client pinned exclusively to 2026-07-28 will not connect. STDIO uses the SDK's stdio server with the same tool set.

  • Loopback Only: HTTP binding to non-loopback interfaces (0.0.0.0) is blocked to avoid exposing local capabilities over untrusted mobile networks. STDIO has no listener.

  • Outbound Egress (Optional): Web target tools contact only hosts in the targets file; diagnostics/assessments also honor MCP_WEB_ALLOWED_HOSTS and the fixed OSV host. With no targets file and no extra hosts, the web_* target tools are not registered and the server stays local. Mobile data/Wi-Fi is required for network tools, and Android battery optimisation may delay long scans.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides secure access to Kali Linux security tools through a dockerized environment for authorized penetration testing and defensive security. Enables network scanning, web application testing, system enumeration, and credential testing with built-in input sanitization and network restrictions.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables users to run shell commands with compressed output, extract information from large files, drive local opencode and Codex agents, perform browser-automation tasks, and monitor runs via a live dashboard.
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables professional penetration testers to run reconnaissance, vulnerability scanning, brute-force checks, traffic capture, exploitation support, and report generation through a unified tool interface. Supports local and networked transports with bearer/OIDC authentication.
      133 npm
      GPL 3.0