Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 36 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions packages/node-repl/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
dist/
build/
*.tsbuildinfo
.qwen_node_repl_cell_*
src/fixtures/napi/build/
101 changes: 101 additions & 0 deletions packages/node-repl/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# @qwen-code/node-repl-mcp

A standalone [Model Context Protocol](https://modelcontextprotocol.io) server that
exposes a **session-persistent Node.js REPL** as three MCP tools. It runs a real
Node.js kernel in a dedicated child process; top-level bindings, closures, and
module state persist across calls within a session.

This package is **fully independent of `@qwen-code/qwen-code-core`** — any MCP
client (Qwen Code via `mcpServers`, Claude, Codex, etc.) can run it.

## Tools

| Tool | Description |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `node_repl` | Execute JavaScript. `{ code, timeout_ms?, title? }`. Bindings persist across calls; top-level `await` supported. |
| `node_repl_reset` | Terminate the kernel process and discard all bindings/module state. |
| `node_repl_add_node_module_dir` | Register an extra `node_modules` directory for bare-package resolution. |

### Cell semantics

- Explicit output only: `nodeRepl.write(value)` for text, `nodeRepl.emitImage(png|jpeg|webp)`
for images; `console.*` is captured. Plain expression results are not returned.
- `nodeRepl.cwd` / `homeDir` / `tmpDir` and `nodeRepl.getHeapStatus()` are available.
- Top-level static `import` is not allowed — use dynamic `await import()`.
- Bare packages resolve from the session `cwd` `node_modules` plus any directory
registered via `node_repl_add_node_module_dir`; package entrypoints use Node
singleton caching. Local `.js`/`.mjs` reload on each execution.
- Node builtins are importable except `process`/`node:process`. Use
`(await import('node:module')).createRequire(import.meta.url)` for CommonJS or
native (N-API) addons.
- Timeout, cancellation, `node_repl_reset`, or a crash replaces the kernel process
and discards all bindings.

> Isolation note: the VM context provides lifecycle/namespace isolation, **not** an
> OS security sandbox. Imported packages and builtins run with ordinary Node.js
> authority and inherit the parent environment. Grant this server only in trusted
> contexts.

## Usage

Once published, the packaged `bin` is the simplest entry point:

```jsonc
// qwen-code settings.json (or any MCP client)
{
"mcpServers": {
"node-repl": {
"command": "npx",
"args": ["-y", "@qwen-code/node-repl-mcp"],
"cwd": "/your/workspace",
"env": { "QWEN_NODE_REPL_ROOTS": "/extra/node_modules/parent" },
},
},
}
```

For local development against a build in this repo, point at `dist/index.js`:

```jsonc
{
"mcpServers": {
"node-repl": {
"command": "node",
"args": ["/path/to/packages/node-repl/dist/index.js"],
"cwd": "/your/workspace",
},
},
}
```

The `cwd` you set is the kernel's working directory and the base for bare-package
resolution (`<cwd>/node_modules`).

Environment:

- `QWEN_NODE_REPL_ROOTS` — extra readable roots (path-list, OS delimiter).
- `QWEN_NODE_REPL_DEBUG` — set truthy for stderr debug logging.

## Build & test

```bash
npm run build # tsc (tsconfig.build.json) + copy runtime assets into dist/runtime
npm run typecheck # includes the test files
npm test # vitest: kernel integration, N-API, 100-cell + 10-kernel scale,
# line fidelity, hoisting semantics, MCP surface
npm run smoke # kernel manager + output adapter, in-process
npm run smoke:mcp # real MCP client <-> built stdio server
npm run smoke:lifecycle # proves the kernel child is reaped on stdin EOF / signals
```

> Run vitest from inside this package. A bare `npx vitest run` from the repo root
> executes every workspace project (tens of thousands of tests) and can exhaust
> the default heap.

## Provenance

Ported from the Qwen Code PR #9499 Node REPL core (kernel, module loader, cell
transform, protocol, security policy, kernel manager). The qwen-coupled result
converter was replaced by `output-adapter.ts`, which emits MCP content blocks.
The empty-in-production trusted-package / sha256-pinning layer was removed
entirely: this runtime has no trusted-package or capability mechanism.
80 changes: 80 additions & 0 deletions packages/node-repl/build.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/

/**
* Build script for @qwen-code/node-repl-mcp.
*
* tsc compiles src/**.ts -> dist, but does NOT copy the runtime .mjs assets or
* the tree-sitter JavaScript grammar wasm. This package ships its own copies
* (it does not depend on qwen-code core's asset-copy pipeline), so we copy them
* into dist/runtime/ here. resolveKernelPath() and the wasm loader probe
* ./runtime/ relative to the compiled module, so this layout works in dist.
*/
import { cpSync, existsSync, mkdirSync, rmSync } from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';

const require = createRequire(import.meta.url);
const here = path.dirname(fileURLToPath(import.meta.url));
const distRuntime = path.join(here, 'dist', 'runtime');

// 0. Clean dist AND the incremental build info together. Removing dist alone
// would leave tsc's buildinfo claiming everything is up to date, so
// `tsc --build` would emit nothing and produce an empty dist.
rmSync(path.join(here, 'dist'), { recursive: true, force: true });
rmSync(path.join(here, 'tsconfig.build.tsbuildinfo'), { force: true });

// 1. Compile TypeScript (tsconfig.build.json excludes *.test.ts from dist).
// Resolve tsc through node rather than `npx` so this also works on Windows,
// where execFileSync cannot resolve `npx.cmd` without a shell.
execFileSync(
process.execPath,
[require.resolve('typescript/bin/tsc'), '--build', 'tsconfig.build.json'],
{ cwd: here, stdio: 'inherit' },
);

// 2. Copy the runtime .mjs kernel + module loader into dist/runtime.
rmSync(distRuntime, { recursive: true, force: true });
mkdirSync(distRuntime, { recursive: true });
for (const asset of ['kernel.mjs', 'module-loader.mjs']) {
cpSync(
path.join(here, 'src', 'runtime', asset),
path.join(distRuntime, asset),
);
}

// 3. Copy the tree-sitter JavaScript grammar wasm from node_modules.
const grammarRelative = path.join(
'tree-sitter-wasms',
'out',
'tree-sitter-javascript.wasm',
);
const grammarSource = [
path.join(here, 'node_modules', grammarRelative),
path.join(here, '..', '..', 'node_modules', grammarRelative),
].find(existsSync);
if (!grammarSource) {
throw new Error(
'node_repl JavaScript grammar asset (tree-sitter-javascript.wasm) was not found',
);
}
cpSync(grammarSource, path.join(distRuntime, 'tree-sitter-javascript.wasm'));

// 4. Sanity-check the emit. A stale buildinfo or a misconfigured tsconfig can
// make `tsc --build` silently emit nothing, leaving a dist that only has the
// copied assets — which then fails at runtime instead of at build time.
for (const required of ['index.js', 'kernel-manager.js', 'mcp-server.js']) {
const emitted = path.join(here, 'dist', required);
if (!existsSync(emitted)) {
throw new Error(
`build produced no dist/${required} — tsc emitted nothing (stale tsconfig.build.tsbuildinfo?)`,
);
}
}

console.log(`node-repl-mcp: runtime assets copied to ${distRuntime}`);
58 changes: 58 additions & 0 deletions packages/node-repl/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
{
"name": "@qwen-code/node-repl-mcp",
"version": "0.21.11",
"description": "Standalone MCP server exposing a session-persistent Node.js REPL (node_repl) — independent of qwen-code core.",
"repository": {
"type": "git",
"url": "git+https://github.com/QwenLM/qwen-code.git",
"directory": "packages/node-repl"
},
"type": "module",
"license": "Apache-2.0",
"engines": {
"node": ">=22"
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": {
"node-repl-mcp": "dist/index.js"
},
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./package.json": "./package.json"
},
"files": [
"dist",
"!dist/**/*.test.*"
],
"scripts": {
"build": "node build.mjs",
"build:ts": "tsc --build tsconfig.build.json",
"clean": "rm -rf dist tsconfig.tsbuildinfo tsconfig.build.tsbuildinfo",
"test": "vitest run",
"test:ci": "vitest run",
"smoke": "node scripts/smoke.mjs",
"smoke:mcp": "node scripts/mcp-smoke.mjs",
"smoke:lifecycle": "node scripts/lifecycle-smoke.mjs",
"typecheck": "tsc --noEmit",
"watch": "tsc --watch"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.30.0",
"tree-sitter-wasms": "^0.1.13",
"web-tree-sitter": "^0.24.7",
"zod": "^3.25.76"
},
"devDependencies": {
"@types/node": "^22.13.10",
"typescript": "^5.3.3",
"vitest": "^3.1.1"
},
"bugs": {
"url": "https://github.com/QwenLM/qwen-code/issues"
},
"homepage": "https://github.com/QwenLM/qwen-code/tree/main/packages/node-repl#readme"
}
Loading
Loading