Skip to main content
Glama
LocalREPL MCP Server

LocalREPL MCP Server

by angrysky56

LocalREPL MCP Server

A locally-running Python REPL server that integrates with Claude Desktop through the Model Context Protocol (MCP).

local-repl-cli skill

This repo ships an agent skill at local-repl-cli-skill/ that teaches Claude to drive modern, token-efficient CLI tools (rg, fd, ast-grep, bat, sd, jq, yq, tokei, eza, dust, procs, delta, hyperfine, watchexec, just) through the LocalREPL shell bridge — with a count-before-enumerate discipline, structured --json output, and the MCP-subprocess gotchas documented under local-repl-cli-skill/reference/.

Deploy it to ~/.claude/skills/ as a live symlink (no copying, no drift):

just deploy-skill          # symlinks ~/.claude/skills/local-repl-cli -> local-repl-cli-skill/
just check-skill-tools     # verify the expected CLI tools are installed

For a general, execution-agnostic version of this CLI knowledge (cross-platform, not tied to LocalREPL or any one MCP), see the separate AI-CLI skill in the ai_workspace.

Related MCP server: MCP Python Toolbox

Features

  • Local REPL: Runs a Python REPL server locally

1. System Discovery Workflow

  • Purpose: Methodical exploration of the full system capabilities

  • Approach: Phase-by-phase discovery with comprehensive documentation

  • Output: Complete system mapping and enhancement opportunities

2. Advanced Workflow Orchestration

  • Purpose: Complex multi-stage workflows with dependency management

  • Features: Task execution engine, error handling, performance monitoring

  • Templates: Data analysis, research, multi-agent coordination workflows

3. Strategic Capability Enhancement

  • Purpose: Systematic enhancement of system capabilities

  • Framework: Phase 1 (Planning) → Phase 2 (Execution) → Phase 3 (Adaptation)

  • Implementation: Sample agent communication and performance monitoring systems

**4. Agent Communication and Performance Monitoring

  • Persistent Agent Intelligence with JSON state storage

  • Empowerment Optimization Framework with energy tracking

  • Advanced Memory Systems with categorization and tagging

  • Workflow Orchestration capabilities

  • Evolution Database tracking agent learning

  • Multi-REPL Coordination for parallel processing

5. Other Advantages

  • Completely Local: Run Python code directly on your machine without any remote dependencies

  • State Persistence: Maintain state between code executions (completely local)

  • MCP Integration: Fully compatible with Claude Desktop through the Model Context Protocol

  • No API Keys: No registration or signup required

  • Privacy-Focused: Your code never leaves your machine if you use local models

  • Simple & Secure: Straightforward implementation with minimal dependencies

  • New Additions: See Modular-Empowerment-README.md or just try the prompts!

Potential Use Cases for LocalREPL

There are several powerful use cases for a local Python REPL integrated with Claude:

1. Interactive Learning Environment

  • Perfect for teaching programming concepts with immediate feedback

  • Step through algorithms with Claude explaining each part

  • Build understanding iteratively without switching between tools

2. Data Analysis Workflow

  • Process and analyze data with state persistence

  • Incrementally build analysis pipelines with guidance from Claude

  • Visualize results and refine approach without context switching

3. Secure Code Experimentation

  • Experiment with sensitive code or data that shouldn't leave your machine

  • Test financial algorithms, personal automation, or proprietary code

  • Avoid exposing intellectual property to third-party services

4. Incremental Development

  • Build solutions step-by-step with Claude's guidance

  • Maintain context and state throughout development sessions

  • Refine code based on immediate feedback and results

5. Local AI Integration Testing

  • Test integrations with local AI models

  • Process inputs and outputs for AI systems

  • Build preprocessing and postprocessing pipelines

6. Automated Documentation Generation

  • Generate documentation from code inspection

  • Test and refine documentation examples

  • Create interactive tutorials with working code examples

7. Private API Testing

  • Explore internal or sensitive APIs without exposing credentials

  • Build up complex API requests incrementally

  • Test authentication flows and data handling

8. Local System Automation

  • Control and interact with local services securely

  • Build automation scripts that don't require internet access

  • Test system modifications in a controlled environment

9. Continuous Computational Context

  • Maintain a persistent computational environment between conversations

  • Build on previous calculations without starting over

  • Create complex multi-step analyses with Claude's guidance

10. Educational Demonstrations

  • Create interactive coding tutorials

  • Demonstrate concepts with working code examples

  • Allow students to experiment safely within Claude

alt text

Installation

Prerequisites

Setup

  1. Clone this repository

    git clone https://github.com/angrysky56/local-repl-mcp.git

Quickstart:

You can just copy this into your mcp config json edit the path to your own, and should be good to go:

{
  "mcpServers": {
    "LocalREPL": {
      "command": "uv",
      "args": [
        "--directory",
        "/absolute/path/to/local-repl-mcp",
        "run",
        "-m",
        "local_repl"
      ]
    }
  }
}

alt text

alt text

Usage

Some of these packages will take some time to install, I suggest you do this if they take too long to install:

Optional: Install additional packages you want to use in your REPL:

cd local-repl-mcp

# Using uv (recommended)
# uv .venv/bin/activate && uv pip install <required-packages>
# If you don't have uv installed, you can install it with:
# pip install uv
# Then if not made by the server activating via Claude you can create then activate the virtual environment with:
# uv venv --python 3.12 --seed
# Then you can activate the virtual environment with:
uv .venv/bin/activate
# And install the packages with:
uv add numpy pandas matplotlib scipy scikit-learn tensorflow torch torchvision torchtext torchaudio seaborn sympy requests networkx beautifulsoup4 jupyter fastapi

Once the server is installed in Claude Desktop, you can use the following tools,

This info and much more is also available to Claude via the prompts folder and attachable by the + in the Desktop UI or /LocalREPL in others:

  • create_python_repl() - Creates a new Python REPL and returns its ID

  • run_python_in_repl(code, repl_id) - Runs Python code in the specified REPL

  • list_active_repls() - Lists all active REPL instances

  • get_repl_info(repl_id) - Shows information about a specific REPL

  • delete_repl(repl_id) - Deletes a REPL instance

Shell, Streaming, and Operational Memory (v0.2)

As of v0.2 the REPL is no longer Python-only. Three modules expand it into a full CLI orchestration layer:

Shell bridge (shell_bridge.py)

Run one-shot commands with structured output. Every call auto-logs to evolution.db so past executions become queryable memory.

  • run_shell(command, repl_id, timeout_seconds=30, cwd=None, use_shell=False, env_extra=None) Returns {command, cwd, stdout, stderr, exit_code, duration_ms, timed_out, truncated_stdout, truncated_stderr}. use_shell=True enables pipes/redirects via /bin/sh. Blocklist refuses sudo, rm -rf /, dd of=/dev/…, shutdown/reboot, fork bombs, and chained variants like echo x && sudo poweroff.

  • set_repl_cwd(repl_id, path) / get_repl_cwd(repl_id) - track a working directory per REPL so subsequent run_shell calls start there.

Streaming (streaming.py)

Long-running processes with non-blocking output drain.

  • spawn_shell(command, repl_id, cwd=None, use_shell=False) → returns proc_id (separate from OS PID to avoid reuse issues).

  • tail_shell_output(proc_id, n_lines=50, stream='both', drain=False) - read recent lines without blocking. Use drain=True in polling loops so the next call sees only NEW output.

  • send_to_shell(proc_id, input_text) - write to stdin for interactive REPLs/servers.

  • kill_shell(proc_id, signal_name='SIGTERM') - supports SIGTERM/SIGKILL/ SIGINT/SIGHUP.

  • wait_shell(proc_id, timeout_seconds=30) - block until exit.

  • list_shells() / reap_exited() - inventory and cleanup.

Operational memory (evolution_memory.py)

SQLite-backed log of every shell command. Like Atuin, but queryable by the agent directly.

  • query_command_history(pattern=None, repl_id=None, only_failures=False, only_timeouts=False, since=None, limit=20) - pattern uses SQL LIKE (%ripgrep%), since accepts '1h', '30m', '2d', or ISO timestamps.

  • command_stats(since=None, top_n=5) - total/pass/fail, success rate, top commands, top failures, slowest runs.

  • tag_command(command_id, tags) - attach ['flaky', 'solved'] etc.

  • forget_command(command_id) - delete rows that captured secrets.

  • vacuum_memory(keep_last_n=5000) - cap db size.

Virtual Environment Execution (venv_exec.py)

Run Python code inside isolated virtual environments with their own packages and interpreters.

  • run_python_in_venv(code, venv_path, repl_id=None) - Run Python code inside a specified virtual environment path.

  • find_venv(path=None) - Discover python virtual environments automatically.

Verify the install

After pulling these changes:

uv run python -m local_repl.doctor

Expects all 9 checks green before you restart Claude Desktop.

Note on unified server: The entry point modules server.py and __main__.py have been fully unified. The pyproject script command local-repl-mcp is now 100% feature-complete, containing all REPL, shell, streaming, memory, and virtual environment execution tools!

The shell bridge shines when paired with modern CLI utilities that produce structured, predictable output (exit codes, JSON flags, counts-first patterns). The recipes below assume Pop!_OS 24.04 / Ubuntu 24.04; other distros use the same package names with their own package manager.

Tier A — apt (one sudo command)

sudo apt update
sudo apt install -y bat git-delta hyperfine

fd / bat naming fix (no sudo). Debian/Ubuntu ship fd-find / bat as fdfind / batcat to avoid name collisions. Symlink the usual names so scripts work unchanged:

mkdir -p ~/.local/bin
ln -sf "$(which fdfind)" ~/.local/bin/fd
ln -sf "$(which batcat)" ~/.local/bin/bat
echo "$PATH" | tr ':' '\n' | grep -q '\.local/bin' && echo OK

ast-grep and nvm-installed npm binaries. If you use nvm, npm installs global binaries under ~/.nvm/versions/node/<ver>/bin/. That path is added to $PATH by shell init files, which don't fire when an MCP server launches via launchd/systemd. Symlink into ~/.local/bin so it's visible to any subprocess regardless of how the parent was started:

ln -sf "$(npm root -g)/../bin/ast-grep" ~/.local/bin/ast-grep
ast-grep --version

Tier B — user-space (no sudo)

# ast-grep: structural code search/rewrite.
npm install -g @ast-grep/cli

# tokei: per-language code statistics.
cargo install tokei

# just: self-documenting command runner via uv (no sudo, no cargo compile).
uv tool install rust-just

watchexec — prebuilt .deb (skip cargo)

Don't cargo install watchexec-cli. As of watchexec 2.5.1 the crate uses fmt::from_fn, still nightly-only on Rust 1.95 (debug_closure_helpers tracking issue #117729; stabilization PR #146099 pending). Compilation fails with error[E0658]. Use the upstream .deb instead:

WATCHEXEC_VER=2.5.1
cd /tmp
curl -fsSLO "https://github.com/watchexec/watchexec/releases/download/v${WATCHEXEC_VER}/watchexec-${WATCHEXEC_VER}-x86_64-unknown-linux-gnu.deb"
echo "9bf40f223b3651e59c99ed463c44635fa71ab3f81b69927b5343b3935a4fdb14  watchexec-${WATCHEXEC_VER}-x86_64-unknown-linux-gnu.deb" | sha256sum -c -
sudo dpkg -i "watchexec-${WATCHEXEC_VER}-x86_64-unknown-linux-gnu.deb"

For future versions, grab the matching checksum from https://github.com/watchexec/watchexec/releases/download/v<VER>/watchexec-<VER>-x86_64-unknown-linux-gnu.deb.sha256.

Verify the toolchain

for cmd in rg jq fd bat delta tokei hyperfine watchexec ast-grep just; do
  printf "%-12s " "$cmd"
  command -v "$cmd" >/dev/null && echo "✓ $($cmd --version 2>/dev/null | head -1)" || echo "✗ MISSING"
done

Ten green checkmarks = ai-cli skill has its full toolkit.

Why these specific tools

ToolReplacesAI-relevant winrggrepRespects .gitignore; --json output; blazing fastfdfindSimpler syntax, parallel walks, respects .gitignoreast-grepregex for codeMatches code by AST pattern, not text — kills "old_string not unique" edit failuresjqsed/awk on JSONSafe, predictable JSON parsingtokeiwc -l + findPer-language code stats in one call — great first-touch overviewbatcatLine numbers + git change markers give the agent immediate contextdeltadiff viewerSide-by-side, syntax-aware diffshyperfinetime ...Statistical benchmarking with JSON exportwatchexecpolling loopsReactive file-change triggers instead of pollingjustbash scriptsSelf-documenting recipes; just --list shows every task

Known gotchas

  • sg is not ast-grep. On Debian/Ubuntu sg is the setsid/script-grep binary from util-linux. Use the full name ast-grep — the ast-grep team dropped the sg shortname in 2024 for this exact reason.

  • ast-grep pattern syntax is specific. $$$ binds to argument lists, not arbitrary bodies. To match "any function by name" use def $NAME, not def $NAME($$$): $$$ — the latter silently returns zero matches.

  • use_shell=True runs under /bin/sh, not bash. No brace expansion {a,b}, no [[ ]], no process substitution. Use POSIX sh syntax or invoke bash -c '...' explicitly.

  • rg and stdin. Ripgrep's is_readable_stdin heuristic hangs waiting on stdin if the parent's stdin is a pipe. The shell bridge handles this by passing stdin=DEVNULL by default.

  • stdin_input parameter with JSON payloads. The MCP tool-call serializer auto-parses JSON-looking strings into dicts, failing Pydantic's str check. Workaround: pipe via use_shell=True with echo '{...}' | jq ....

Example Workflow

# First create a new REPL
repl_id = create_python_repl()

# Run some code
result = run_python_in_repl(
  code="x = 42\nprint(f'The answer is {x}')",
  repl_id=repl_id
)

# Run more code in the same REPL (with state preserved)
more_results = run_python_in_repl(
  code="import math\nprint(f'The square root of {x} is {math.sqrt(x)}')",
  repl_id=repl_id
)

# Check what variables are available in the environment
environment_info = get_repl_info(repl_id)

# When done, you can delete the REPL
delete_repl(repl_id)

Development

To run the server during development:

mcp dev server.py

Try this stuff if you need to, untested:

  1. Create a virtual environment:

    # Using uv (recommended)
    uv venv --python 3.12 --seed
    
    # Or using standard venv
    python -m venv .venv
  2. Activate the virtual environment:

    # On Linux/macOS
    . .venv/bin/activate
    
    # On Windows
    .venv\Scripts\activate
  3. cd local-repl-mcp Install the package:

    # Using uv
    uv pip install -e .
    
    # Using pip
    pip install -e .

No idea if this works:

Run the following command to generate a configuration file for Claude Desktop:

mcp install server.py

Troubleshooting

  • EPIPE errors: If you see EPIPE errors, restart the Claude Desktop application

  • Missing packages: If your code requires specific packages, install them in the same virtual environment

  • Connection issues: Ensure the server path in your configuration is correct

  • MCP tools not appearing: Check your Claude Desktop configuration and restart the application

License

MIT

Available Tools

23 tools
command_statsA

Aggregate metrics across the command log.

    Args:
        since: Window to analyze (ISO or '1h'/'1d' etc). None = all time.
        top_n: How many entries to return in each top-list.
    

Inputs: since, top_n.

create_python_replC
Create a new Python REPL environment.

Returns:
    str: ID of the new REPL

Inputs: no named parameters.

delete_replA
Delete a REPL instance.

Args:
    repl_id: ID of the REPL to delete

Returns:
    str: Confirmation message

Inputs: repl_id (required).

find_venvA

Locate a virtual environment in the REPL's current directory.

    Checks, in order: .venv/, venv/, env/. Returns the path to the
    python binary if found, so it can be fed directly to
    run_python_in_venv.

    Args:
        repl_id: REPL whose cwd to search under.
    

Inputs: repl_id (required).

forget_commandB

Delete a command log row. Use when a logged command captured a secret (token in argv, etc.) that shouldn't persist on disk.

Inputs: command_id (required).

get_repl_cwdB

Return the REPL's current working directory.

Inputs: repl_id (required).

get_repl_infoC
Get information about a specific REPL instance.

Args:
    repl_id: ID of the REPL to get info for

Returns:
    str: Information about the REPL

Inputs: repl_id (required).

initialize_modular_empowermentC
Initialize the Modular Empowerment Framework in a specific REPL.

Args:
    repl_id: ID of the REPL to initialize in

Returns:
    str: Result of the initialization

Inputs: repl_id (required).

kill_shellB

Send a signal to a spawned process.

    Args:
        signal_name: 'SIGTERM' (graceful, default), 'SIGKILL' (force),
            or 'SIGINT' (Ctrl-C equivalent).
        remove_from_registry: Drop from _PROCESSES after signalling.
    

Inputs: proc_id (required), signal_name, remove_from_registry.

list_active_replsA

List all active REPL instances and their IDs.

Inputs: no named parameters.

list_shellsA

Return info on all spawned processes (live and recently-exited).

Inputs: no named parameters.

query_command_historyA

Search the command execution log.

    Args:
        pattern: SQL LIKE pattern against the command text (case-insensitive).
            Use % as wildcard, e.g. '%ripgrep%' or 'git commit%'.
        repl_id: Filter to commands run in a specific REPL.
        only_failures: Return only non-zero exit codes.
        only_timeouts: Return only commands that hit the timeout.
        since: ISO timestamp, or relative like '1h', '30m', '2d'.
        limit: Max rows to return (capped at 200).

    Returns:
        List of CommandLogEntry dicts, newest first.
    

Inputs: limit, since, pattern, repl_id, +2 more.

reap_exitedA

Remove exited processes from the registry. Call occasionally to keep list_shells tidy, especially after running many short spawns.

Inputs: no named parameters.

run_python_in_replB
Execute Python code in a REPL. (Create new or use an existing REPL)

Args:
    code: Python code to execute
    repl_id: ID of the REPL to use

Returns:
    str: Result of the execution including stdout, stderr, and the return value

Inputs: code (required), repl_id (required).

run_python_in_venvA

Run Python code inside a project's virtual environment.

    Spawns a fresh subprocess running `<venv>/bin/python -c CODE`.
    No namespace carries over between calls — each invocation is a
    new interpreter. Use this when the project has dependencies that
    aren't installed in the MCP server's Python environment.

    Args:
        code: Python source to execute.
        venv_path: Path to the venv directory (e.g., "/proj/.venv")
            OR direct path to the python binary. `~` is expanded.
        repl_id: Optional REPL to inherit cwd from. Falls back to
            cwd argument, then to server's cwd.
        cwd: Explicit working directory override.
        timeout_seconds: Kill after N seconds (capped at 600).
        env_extra: Additional env vars merged onto os.environ.
            PYTHONPATH is NOT auto-set — pass it via env_extra if
            the project uses src-layout and needs it.

    Returns:
        VenvResult dict with ok/python_path/cwd/stdout/stderr/
        exit_code/duration_ms/timed_out/truncation flags/error.
    

Inputs: code (required), venv_path (required), cwd, repl_id, +2 more.

run_shellA

Run a shell command inside a REPL context with structured output.

    Returns a dict so the caller can branch on exit_code and parse
    stdout without string-scraping. Every call is logged to evolution.db
    for later recall via `query_command_history`.

    Args:
        command: The shell command to execute.
        repl_id: REPL whose cwd the command runs in.
        timeout_seconds: Kill the process if it exceeds this (capped at 600).
        cwd: Override the REPL's cwd for this one call.
        use_shell: If True, pass to /bin/sh (enables pipes, redirects,
            glob expansion). Default False = tokenized exec, safer.
        env_extra: Additional env vars merged onto os.environ.
        stdin_input: Optional string piped to the command's stdin.
            Enables first-class stdin piping so CLI tools that read
            from stdin (jq, wc, grep, etc.) work without shell pipe
            syntax.  When None the child's stdin is /dev/null.
    

Inputs: command (required), repl_id (required), cwd, env_extra, +3 more.

send_to_shellB

Write to a spawned process's stdin. Useful for interactive REPLs.

Inputs: proc_id (required), input_text (required), append_newline.

set_repl_cwdC

Change a REPL's tracked working directory for future shell calls.

Inputs: path (required), repl_id (required).

spawn_shellA

Spawn a long-running process. Returns a proc_id for follow-up calls.

    Use this for watchers (watchexec, tail -f), servers, REPLs, or any
    command you want to poll output from over time. For one-shot
    commands use run_shell instead — it's simpler and auto-logs.

    Returns proc_id which is passed to tail_shell_output, send_to_shell,
    kill_shell, and wait_shell.
    

Inputs: command (required), repl_id (required), cwd, env_extra, +1 more.

tag_commandC

Attach tags to a logged command for later recall.

Useful for marking commands as e.g. 'flaky', 'slow', 'solved', 'security-review'. Replaces any existing tags on that row.

Inputs: tags (required), command_id (required).

tail_shell_outputA

Return the most recent lines from a spawned process's output.

    Args:
        proc_id: From spawn_shell.
        n_lines: How many recent lines to return (capped at 500).
        stream: 'stdout', 'stderr', or 'both'.
        drain: If True, remove returned lines from the buffer so the
            next call sees only NEW output. Useful for polling loops.
    

Inputs: proc_id (required), drain, stream, n_lines.

vacuum_memoryA

Keep only the most recent N rows and reclaim disk space. Call occasionally to prevent unbounded growth.

Inputs: keep_last_n.

wait_shellC

Block until a spawned process exits (or timeout). Returns exit info.

Inputs: proc_id (required), timeout_seconds.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 23 tools

    Disambiguation5/5

    Each tool targets a distinct operation: REPL lifecycle, shell process management, command history logging, and virtual environment usage. No two tools have overlapping purposes; descriptions clearly differentiate between one-shot shell commands, long-running processes, and Python execution contexts.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern in snake_case (e.g., create_python_repl, run_shell, query_command_history). The naming is predictable and intuitive, making it easy for an agent to infer functionality.

    Tool Count4/5

    With 23 tools, the server covers a broad but coherent set of functionalities for local REPL and shell management. While slightly above the typical sweet spot, each tool serves a specific purpose and justifies its presence without feeling redundant.

    Completeness5/5

    The tool surface comprehensively covers the domain: REPL creation/deletion/inspection, Python execution (both in-REPL and in-venv), shell command execution (one-shot and long-running), process management, command logging, and history queries. No obvious gaps for the stated purpose.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      F
      maintenance
      A Model Context Protocol server that enables AI assistants like Claude to perform Python development tasks through file operations, code analysis, project management, and safe code execution.
      9
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      A custom Model Context Protocol server that gives Claude Desktop and other LLMs access to file system operations and command execution capabilities through standardized tool interfaces.
      23
      Apache 2.0
    • A
      license
      A
      quality
      D
      maintenance
      A server that lets Claude desktop app execute terminal commands on your computer and edit files through Model Context Protocol, featuring command execution, process management, and advanced file operations.
      19
      740,317 npm
      6
      MIT