Content
# MCP Code Mode Server
A "code as a tool" implementation based on MCP: executing TypeScript code in a secure sandbox and bridging calls to MCP servers via IPC.
**Test Coverage**: 99.41% statements · 100% lines · 100% functions
---
## Quick Start
```bash
# 1. Install dependencies
npm install
# 2. Generate TypeScript API
npm run generate-api
# 3. Build the project
npm run build
# 4. Run the test suite
npm test
```
---
## Configure Claude Desktop
### Configuration File Location
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`
### Configuration Content
```json
{
"mcpServers": {
"code-mode": {
"command": "node",
"args": [
"/absolute/path/mcp-code-mode-demo/dist/server.js"
],
"description": "Execute TypeScript in sandbox with MCP tools"
}
}
}
```
**Note**: Replace with the actual absolute path of your project.
After configuration, restart Claude Desktop to use it.
---
## Usage Examples
### Read File
```typescript
import * as fs from "./servers/filesystem/index.js";
const content = await fs.readFile({ path: "package.json" });
const pkg = JSON.parse(content);
console.log("Project:", pkg.name);
```
### Write File
```typescript
import * as fs from "./servers/filesystem/index.js";
await fs.writeFile({
path: "output.txt",
content: "Hello from Code Mode!"
});
```
### List Directory
```typescript
import * as fs from "./servers/filesystem/index.js";
const files = await fs.listDirectory({ path: "." });
console.log("Current directory files:", files);
```
### Network Request
```typescript
import * as fetch from "./servers/fetch/index.js";
const response = await fetch.fetch({
url: "https://api.github.com/repos/anthropics/claude-code"
});
const data = JSON.parse(response);
console.log("Stars:", data.stargazers_count);
```
---
## How It Works
```
Claude Desktop ↔ MCP Server (this project)
│ execute_code tool
▼
Main Process ─── fork ───▶ Child Process (executes user TS)
▲ │
│ process.send │ import './servers/...'
└────── IPC ───────────┘
│
MCP Servers (filesystem, fetch, etc.)
```
- The child process sends MCP tool invocation requests to the main process via IPC.
- The main process proxies the execution and returns the results.
- Cross-platform support: macOS / Linux / Windows
---
## Project Structure
```
src/
├── generator.ts # MCP → TypeScript API generator
├── sandbox.ts # Sandbox executor (Node.js fork + IPC)
└── server.ts # MCP Server entry point
generated-api/
├── client.ts # IPC client
└── servers/ # MCP server API encapsulation
```
---
## Testing
```bash
# Run tests
npm test
# View coverage
npm run test:coverage
```
---
## Core Features
- **IPC Bridging**: Safe invocation of main process MCP tools from child processes
- **Module Resolution**: Symlink or directory copy (automatic downgrade)
- **Cross-Platform**: Full support for macOS / Linux / Windows
- **High Test Coverage**: 36 test cases covering core paths
- **Production Ready**: Isolated execution, resource cleanup, timeout control
---
## Troubleshooting
### Server Fails to Start
1. Check if built: `npm run build`
2. Check if `dist/server.js` exists
3. Confirm Node.js version >= 18
### Code Execution Fails
1. Ensure API is generated: `npm run generate-api`
2. Check if `generated-api/servers/` directory exists
3. Verify import paths: `./servers/...`
### Claude Desktop Cannot See Tools
1. Check if the configuration file path is correct
2. Ensure using absolute paths
3. Restart Claude Desktop
4. Check developer tools console logs
---
## Secure Sandbox
This project integrates the [Anthropic Sandbox Runtime](https://github.com/anthropic-experimental/sandbox-runtime), which restricts the file system and network access permissions of processes at the OS level.
### Enable Sandbox (default)
```bash
# Run server with sandbox protection
npm run server
# Run example with sandbox protection
npm run example
```
The sandbox automatically restricts:
- **Network Access**: Only allows npm/GitHub domains
- **File Reading**: Denies access to sensitive directories like `~/.ssh`, `~/.aws`
- **File Writing**: Only allows current directory, `.sandbox-temp`, `/tmp`
- **Sensitive File Protection**: Denies writing to files like `.env`, `*.key`
### Configure Sandbox Permissions
Edit `.srt-settings.json` to customize permissions:
```json
{
"network": {
"allowedDomains": ["example.com"],
"deniedDomains": []
},
"filesystem": {
"denyRead": ["~/.ssh"],
"allowWrite": ["."],
"denyWrite": [".env", "*.key"]
}
}
```
**Configuration Item Explanation:**
- `network.allowedDomains`: Domains allowed for access (supports wildcard `*.example.com`)
- `network.deniedDomains`: Domains denied for access (higher priority than allowedDomains)
- `filesystem.denyRead`: Paths denied for reading
- `filesystem.allowWrite`: Paths allowed for writing (default is only the current directory)
- `filesystem.denyWrite`: Paths denied for writing (higher priority than allowWrite)
Path support:
- Absolute paths: `/etc/passwd`
- Relative paths: `./src`
- User directories: `~/.ssh`
- Glob patterns (macOS): `src/**/*.ts`
### Disable Sandbox
The sandbox can be disabled for testing or development:
```bash
# Run without sandbox (risk assumed)
npm run server:unsafe
npm run example:unsafe
```
**Note**: The test suite does not use the sandbox by default (`npm test` runs directly) because the testing framework requires more lenient permissions.
### Platform Dependencies
- **macOS**: No additional dependencies required (uses system-provided `sandbox-exec`)
- **Linux**: Requires installation of `bubblewrap`, `socat`, `ripgrep`
```bash
# Ubuntu/Debian
sudo apt-get install bubblewrap socat ripgrep
# Fedora
sudo dnf install bubblewrap socat ripgrep
# Arch
sudo pacman -S bubblewrap socat ripgrep
```
---
## Security Recommendations
- ✅ **Integrated OS-level sandbox** (Anthropic Sandbox Runtime)
- ✅ **Isolated execution of child processes** + IPC communication
- ✅ **File system/network whitelisting control**
- It is recommended to configure additional resource limits (CPU/memory) in production environments.
- Optional: Additional isolation at the container/system level.
---
## License
MIT
Connection Info
You Might Also Like
everything-claude-code
Complete Claude Code configuration collection - agents, skills, hooks,...
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
cc-switch
All-in-One Assistant for Claude Code, Codex & Gemini CLI across platforms.
servers
Model Context Protocol Servers
servers
Model Context Protocol Servers
Agent-Reach
Give your AI agent eyes to see the entire internet. Read & search Twitter,...