Skip to content
Back to search

forgemax

Code Mode inspired local sandboxed MCP Gateway - collapses N servers x M tools into 2 tools (~1,000 tokens)

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/postrv--forgemax/badge.svg)](/listings/postrv--forgemax)

HTML

<a href="/listings/postrv--forgemax"><img src="/api/listings/postrv--forgemax/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

**npm** (recommended):

npm install -g forgemax

**Homebrew** (macOS/Linux):

brew tap postrv/forgemax && brew install forgemax

**Shell installer** (macOS/Linux):

curl -fsSL https://raw.githubusercontent.com/postrv/forgemax/main/install.sh | bash

**PowerShell** (Windows):

irm https://raw.githubusercontent.com/postrv/forgemax/main/install.ps1 | iex

**Scoop** (Windows):

scoop bucket add forgemax https://github.com/postrv/scoop-forgemax
scoop install forgemax

**Cargo** (from source):

cargo install forgemax

**From source**:

cargo build --release
# Binaries: target/release/forgemax + target/release/forgemax-worker

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 428 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # Forgemax
  2. **Code Mode MCP Gateway** — collapses N servers x M tools into 2 tools (~1,000 tokens).
  3. Instead of dumping every tool schema into the LLM's context window, Forgemax exposes exactly two MCP tools:
  4. - **`search`** — query a capability manifest to discover tools (read-only, sandboxed)
  5. - **`execute`** — run JavaScript against the tool API in a sandboxed V8 isolate
  6. Additional sandbox APIs (the MCP surface stays at exactly 2 tools):
  7. - **`forge.readResource(server, uri)`** — read MCP resources from downstream servers
  8. - **`forge.stash`** — session-scoped key-value store for sharing data across executions
  9. - **`forge.parallel(calls, opts)`** — bounded concurrent execution of tool/resource calls
  10. The LLM writes JavaScript that calls through typed proxy objects. Credentials, file paths, and internal state never leave the host — the sandbox only sees opaque bindings. TypeScript definitions (`forge.d.ts`) are compiled into the binary and served in MCP server instructions, giving LLMs full type awareness.
  11. Forgemax's Code Mode approach draws inspiration from [Cloudflare's sandbox tool-calling pattern](https://blog.cloudflare.com/code-mode/) — their implementation of sandboxed code execution for MCP tool orchestration is excellent and well worth studying. We encourage supporting their work.
  12. ## Why
  13. | Traditional MCP | Forgemax Code Mode |
  14. |---|---|
  15. | 76 tools = ~15,000 tokens of schema | 2 tools = ~1,000 tokens |
  16. | 5-10 sequential round-trips | 1 `execute()` call with chaining |
  17. | Every new tool widens the context | Tool count is invisible to the LLM |
  18. LLMs are trained on billions of lines of code. They're better at writing `narsil.symbols.find({pattern: "handle_*"})` than picking the right tool from a 76-item JSON schema list.
  19. ## Performance
  20. | Scenario | Raw MCP (tokens) | Forgemax (tokens) | Savings |
  21. |----------|------------------|-------------------|---------|
  22. | 10 tools | ~4,200 | ~1,100 | 73% |
  23. | 50 tools | ~20,700 | ~1,100 | 94% |
  24. | 76 tools | ~33,100 | ~1,100 | 96% |
  25. | 150 tools | ~61,800 | ~1,100 | 98% |
  26. Forgemax schema size is constant (~1,100 tokens) regardless of how many tools are connected.
  27. Run the benchmark yourself: `cargo run -p forge-manifest --example token_savings`
  28. ## Architecture
  29. ```
  30. forgemax Binary entry point (stdio MCP transport)
  31. forge-config TOML config loading, env var expansion, file watching
  32. forge-client MCP client connections (stdio + HTTP/SSE), routing
  33. forge-server MCP server handler (search + execute via rmcp)
  34. forge-sandbox V8 sandbox (deno_core, AST validator, worker pool)
  35. forgemax-worker Isolated child process for V8 execution
  36. forge-manifest Capability manifest, LiveManifest, TypeScript defs
  37. forge-error Typed DispatchError enum, structured errors, fuzzy matching
  38. forge-audit Audit event types and structured logging
  39. forge-test-server Mock MCP server for integration tests
  40. ```
  41. ### forge-sandbox
  42. The core innovation. Uses `deno_core` to run LLM-generated JavaScript in a locked-down V8 isolate:
  43. - No filesystem, network, environment, or child process access
  44. - Fresh runtime per execution (no state leakage)
  45. - AST-based code validation via oxc — static analysis catches dangerous patterns before V8 runs (28 bypass tests)
  46. - Multi-hop alias detection — tracks `const e = eval; e("code")` and destructured `globalThis` through multiple assignment hops
  47. - Timeout + heap limit enforcement with typed errors (`Timeout`, `HeapLimit`, `JsError`) preserved across the IPC boundary
  48. - Output size caps and tool call rate limiting
  49. - Opaque bindings — credentials never exposed to sandbox code
  50. - Dual-mode execution: in-process (tests) or isolated child process (production)
  51. - Worker pool with warm process reuse, pre-warming, background reaping, and health checks (optional `worker-pool` feature)
  52. - Resource reading with URI scheme blocklist, path traversal prevention, and rate limiting
  53. - Session stash with TTL, group isolation, size limits, and per-execution rate limiting
  54. - Bounded parallel execution (`forge.parallel()`) with concurrency caps
  55. - Prometheus metrics for execution counters, duration histograms, and pool gauges (optional `metrics` feature)
  56. ### forgemax-worker
  57. Separate child process binary for production execution. Communicates with the parent via length-delimited JSON IPC over stdin/stdout and starts with a cleared environment. Process separation limits crash and memory-corruption impact on the gateway; it does not provide an operating-system filesystem or network sandbox if V8 itself is compromised.
  58. ### forge-manifest
  59. Queryable index of all tools across all connected MCP servers. Supports progressive discovery:
  60. - **Layer 0**: Server names + descriptions (~50 tokens)
  61. - **Layer 1**: Categories per server (~200 tokens)
  62. - **Layer 2**: Tool list per category (~500 tokens)
  63. - **Layer 3**: Full schema per tool (~200 tokens each)
  64. Built dynamically from live `tools/list` responses when downstream servers connect. `LiveManifest` provides lock-free reads via `arc-swap` with atomic swap for background refresh — periodic re-discovery on a configurable interval, plus SIGHUP-triggered refresh on Unix. TypeScript definitions (`forge.d.ts`) are compiled into the binary at build time and served in MCP server instructions.
  65. ### forge-client
  66. MCP client connections to downstream servers. Supports stdio and HTTP/SSE transports. `RouterDispatcher` routes `callTool(server, tool, args)` to the correct downstream connection with pre-dispatch tool name validation — misspelled tools return `TOOL_NOT_FOUND` with Levenshtein-based suggestions before ever hitting the upstream server. `ReconnectingClient` decorator auto-reconnects on permanent transport failures (broken pipe, channel overflow) with exponential backoff — default enabled for stdio transports.
  67. ### forge-server
  68. Implements `ServerHandler` from rmcp. Exposes `search` and `execute` as MCP tools, wires them to the sandbox executor, and serves over stdio. Key operations are instrumented with `tracing` spans for structured observability.
  69. ### forge-error
  70. Typed `DispatchError` enum replacing `anyhow::Error` across all dispatchers. Variants: `ServerNotFound`, `ToolNotFound`, `Timeout`, `CircuitOpen`, `GroupPolicyDenied`, `Upstream`, `TransportDead`, `RateLimit`, `Internal`. `TransportDead` distinguishes permanent transport failures (broken pipe, channel closed) from transient upstream errors — triggers circuit breaker but is not retryable without reconnection. Includes fuzzy matching — `find_symbls` suggests `find_symbols` via Levenshtein distance. Errors serialize to structured JSON with `{error, code, message, retryable, suggested_fix}`.
  71. ### forge-audit
  72. Audit event types for structured logging. Every sandbox execution is logged with code hash, tool calls, duration, outcome, worker reuse status, and pool size at acquisition. Code previews are redacted before logging.
  73. ### forge-config
  74. TOML configuration with environment variable expansion (`${GITHUB_TOKEN}`). Configures downstream servers, explicit stdio `env` entries, transports, sandbox limits, and execution mode. Per-server `reconnect` and `max_reconnect_backoff_secs` fields control auto-reconnection on transport death (default: enabled for stdio). Optional config file watching via `notify` crate with debounced reload (requires `config-watch` feature). Startup concurrency is configurable (`startup_concurrency`, default 8) for parallel server connections.
  75. ## Install
  76. **npm** (recommended):
  77. ```bash
  78. npm install -g forgemax
  79. ```
  80. **Homebrew** (macOS/Linux):
  81. ```bash
  82. brew tap postrv/forgemax && brew install forgemax
  83. ```
  84. **Shell installer** (macOS/Linux):
  85. ```bash
  86. curl -fsSL https://raw.githubusercontent.com/postrv/forgemax/main/install.sh | bash
  87. ```
  88. **PowerShell** (Windows):
  89. ```powershell
  90. irm https://raw.githubusercontent.com/postrv/forgemax/main/install.ps1 | iex
  91. ```
  92. **Scoop** (Windows):
  93. ```powershell
  94. scoop bucket add forgemax https://github.com/postrv/scoop-forgemax
  95. scoop install forgemax
  96. ```
  97. **Cargo** (from source):
  98. ```bash
  99. cargo install --locked forgemax forge-sandbox-worker
  100. ```
  101. **From source**:
  102. ```bash
  103. cargo build --release --locked --workspace
  104. # Binaries: target/release/forgemax + target/release/forgemax-worker
  105. ```
  106. ## Quick Start
  107. ```bash
  108. # 1. Generate a config file
  109. forgemax init
  110. # 2. Edit forge.toml to add your servers and tokens
  111. # 3. Validate your setup
  112. forgemax doctor
  113. # 4. Run (serves MCP over stdio)
  114. RUST_LOG=info forgemax
  115. # Run tests (development)
  116. cargo test --workspace
  117. ```
  118. ### CLI Commands
  119. | Command | Description |
  120. |---------|-------------|
  121. | `forgemax` | Start the MCP gateway server (default) |
  122. | `forgemax serve` | Explicit alias for server mode |
  123. | `forgemax doctor` | Validate configuration and connectivity |
  124. | `forgemax manifest` | Inspect the capability manifest |
  125. | `forgemax run <file>` | Execute a JavaScript file against servers |
  126. | `forgemax init` | Generate a starter config file |
  127. ### Configuration
  128. Copy the example config and add your tokens:
  129. ```bash
  130. cp forge.toml.example forge.toml
  131. ```
  132. The example includes pre-configured connections for 11 reputable MCP servers:
  133. | Server | Company | Transport | Auth |
  134. |--------|---------|-----------|------|
  135. | narsil | — | stdio | None |
  136. | github | GitHub | stdio (Docker) | Personal access token |
  137. | playwright | Microsoft | stdio (npx) | None |
  138. | sentry | Sentry | stdio (npx) | Auth token |
  139. | cloudflare | Cloudflare | SSE | OAuth |
  140. | supabase | Supabase | stdio (npx) | Access token |
  141. | notion | Notion | stdio (npx) | Integration token |
  142. | figma | Figma | SSE | OAuth |
  143. | stripe | Stripe | stdio (npx) | Secret key |
  144. | linear | Linear | SSE | OAuth |
  145. | atlassian | Atlassian | SSE | OAuth |
  146. Uncomment only the servers you need. Environment variables are expanded (`${GITHUB_TOKEN}`).
  147. <details>
  148. <summary>Minimal config (narsil only)</summary>
  149. ```toml
  150. [servers.narsil]
  151. command = "narsil-mcp"
  152. args = ["--repos", "."]
  153. transport = "stdio"
  154. [sandbox]
  155. timeout_secs = 5
  156. max_heap_mb = 64
  157. execution_mode = "child_process"
  158. ```
  159. </details>
  160. <details>
  161. <summary>Advanced options</summary>
  162. ```toml
  163. # Per-server resilience
  164. [servers.narsil]
  165. command = "narsil-mcp"
  166. args = ["--repos", "."]
  167. transport = "stdio"
  168. timeout_secs = 30
  169. circuit_breaker = true
  170. failure_threshold = 3
  171. recovery_timeout_secs = 60
  172. reconnect = true # Auto-reconnect on transport death (default: true for stdio)
  173. max_reconnect_backoff_secs = 30 # Max backoff between retries
  174. # Cross-server data flow isolation
  175. [groups.internal]
  176. servers = ["supabase"]
  177. isolation = "strict"
  178. [groups.external]
  179. servers = ["notion", "linear", "atlassian"]
  180. isolation = "strict"
  181. [groups.tools]
  182. servers = ["narsil", "playwright", "github"]
  183. isolation = "open"
  184. ```
  185. </details>
  186. ## How It Works
  187. **1. Agent discovers tools via `search()`:**
  188. ```javascript
  189. async () => {
  190. return manifest.servers.map(s => ({
  191. name: s.name,
  192. categories: Object.keys(s.categories)
  193. }));
  194. }
  195. ```
  196. **2. Agent calls tools via `execute()`:**
  197. ```javascript
  198. async () => {
  199. const symbols = await forge.callTool("narsil", "symbols.find", {
  200. pattern: "handle_*"
  201. });
  202. const refs = await forge.callTool("narsil", "symbols.references", {
  203. symbol: symbols[0].name
  204. });
  205. return { symbols, refs };
  206. }
  207. ```
  208. **3. Or using the proxy API:**
  209. ```javascript
  210. async () => {
  211. const result = await forge.server("narsil").ast.parse({ file: "main.rs" });
  212. return result;
  213. }
  214. ```
  215. **4. Reading resources and using the stash:**
  216. ```javascript
  217. async () => {
  218. // Read a resource from a downstream server
  219. const schema = await forge.readResource("db", "postgres://mydb/tables");
  220. // Store it in the session stash for later executions
  221. await forge.stash.put("db_schema", schema, { ttl: 3600 });
  222. // Make parallel calls
  223. const { results } = await forge.parallel([
  224. () => forge.callTool("narsil", "ast.parse", { file: "a.rs" }),
  225. () => forge.callTool("narsil", "ast.parse", { file: "b.rs" }),
  226. ]);
  227. return results;
  228. }
  229. ```
  230. **5. Structured errors with fuzzy matching:**
  231. Typos in server or tool names return helpful suggestions instead of opaque errors:
  232. ```json
  233. {
  234. "error": true,
  235. "code": "TOOL_NOT_FOUND",
  236. "message": "Tool 'find_symbls' not found on server 'narsil'",
  237. "retryable": true,
  238. "suggested_fix": "Did you mean 'find_symbols'?"
  239. }
  240. ```
  241. The sandbox executes JavaScript, routes `forge.callTool()` to real MCP servers via the `ToolDispatcher` trait, and returns JSON. The LLM never sees credentials, connection details, or raw API surfaces.
  242. ## Security Model
  243. ```
  244. AST Validator oxc-powered static analysis — import/require/eval/Deno/process
  245. blocked before V8 runs, multi-hop alias tracking, 28 bypass tests
  246. |
  247. V8 Bootstrap eval/Function constructor removal at runtime
  248. |
  249. V8 Isolate No fs/net/env, fresh per call, memory-isolated
  250. |
  251. API Boundary Opaque bindings, arg validation, rate limits
  252. |
  253. Manifest Sanitization Tool metadata sanitized to prevent prompt injection
  254. |
  255. Typed Errors Structured {code, message, retryable, suggested_fix} JSON —
  256. fuzzy matching suggests corrections for typos
  257. |
  258. Content Size Limits OOM prevention for text (10MB), binary (1MB) responses
  259. |
  260. Resource Validation URI scheme blocklist (data/javascript/ftp/gopher/telnet/ldap),
  261. path traversal, null bytes, control chars
  262. |
  263. Session Stash Key validation, value/total size limits, TTL enforcement,
  264. group isolation, per-execution rate limiting
  265. |
  266. Parallel Execution Bounded concurrency, shared rate limit counter
  267. |
  268. Error Redaction URLs, IPs, paths, credentials, stack traces stripped
  269. before reaching the LLM — validation errors preserved
  270. |
  271. Resource Limits Timeout, heap cap, output size cap, concurrency cap
  272. |
  273. Header Security Sensitive headers (auth, token, key, cookie, secret,
  274. credential, password) stripped on plain HTTP
  275. |
  276. Per-Server Timeouts Individual timeout per downstream server
  277. |
  278. Circuit Breakers Closed → Open → HalfOpen state machine per server,
  279. prevents cascade failures from flaky downstreams
  280. |
  281. Transport Resilience TransportDead detection (broken pipe, channel overflow),
  282. auto-reconnection with exponential backoff (1s → max),
  283. CAS-guarded concurrent reconnection prevention
  284. |
  285. Server Groups Opt-in strict/open isolation policies controlling
  286. cross-server data flow within a single execution
  287. |
  288. Process Isolation Child process, clean env, kill-on-timeout (production mode)
  289. |
  290. Worker Pool Warm process reuse with health checks, idle reaping,
  291. typed error preservation across IPC boundary
  292. |
  293. Binary Security Absolute paths only, permission checks, no PATH fallback
  294. |
  295. IPC Protocol Length-delimited JSON, configurable message size limits,
  296. protocol desync prevention, typed ErrorKind across boundary
  297. |
  298. Audit Logging Every execution logged — code hash, tool calls, duration,
  299. outcome, worker reuse, pool size, redacted code preview
  300. ```
  301. See [SECURITY.md](SECURITY.md) for the full threat model, defense-in-depth table, and hardening checklist. See [ARCHITECTURE.md](ARCHITECTURE.md) for detailed design.
  302. ## Examples
  303. The `examples/` directory contains runnable JavaScript files demonstrating all sandbox APIs:
  304. | File | Features |
  305. |------|----------|
  306. | `basic-tool-chaining.js` | `forge.callTool` chaining |
  307. | `multi-server-pipeline.js` | `forge.server()` fluent API |
  308. | `stash-workflow.js` | `forge.stash` put/get/keys |
  309. | `parallel-fan-out.js` | `forge.parallel()` concurrency |
  310. | `resource-reading.js` | `forge.readResource()` |
  311. | `error-handling.js` | Structured errors + fuzzy matching |
  312. | `parallel-stash-pipeline.js` | Hero: parallel + stash pipeline |
  313. Run an example: `forgemax run examples/basic-tool-chaining.js`
  314. ## Tests
  315. ~790 tests across the workspace:
  316. ```bash
  317. cargo test --workspace
  318. ```
  319. ## Dependencies
  320. | Crate | Version | Purpose |
  321. |---|---|---|
  322. | deno_core | 0.391 | V8 sandbox runtime |
  323. | rmcp | 1.2 | MCP protocol (server + client) |
  324. | tokio | 1.x | Async runtime |
  325. | serde | 1.x | Serialization |
  326. | schemars | 1.0 | JSON Schema (matches rmcp) |
  327. | oxc_parser / oxc_ast | 0.115 | AST-based code validation |
  328. | arc-swap | 1.x | Lock-free LiveManifest reads |
  329. | strsim | 0.11 | Levenshtein fuzzy matching |
  330. | sha2 | 0.10 | Code hashing for audit log |
  331. | chrono | 0.4 | Audit timestamps |
  332. | notify | 7.x | Config file watching (optional) |
  333. | prometheus-client | 0.22 | Metrics export (optional) |
  334. ## License
  335. [FSL-1.1-ALv2](LICENSE) — Functional Source License, Version 1.1, with Apache License 2.0 future grant.
  336. You can use, modify, and redistribute Forgemax for any purpose **except** offering a competing commercial product or service. After two years from each release, that version converts to Apache 2.0.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.