Skip to main content
Glama
README.md
# slurm-mcp — SLURM MCP Server for Claude Code

**Author:** Samuel Ahuno (ekwame001@gmail.com), Greenbaum Lab, MSKCC
**License:** MIT
**Date:** 2026-02-21

A Model Context Protocol (MCP) server that gives Claude Code native access to
SLURM job management. Submit, monitor, and cancel jobs without leaving the
conversation.

---

## Quick Start (3 steps)

### 1. Clone and install

```bash
git clone https://github.com/ahunos/slurm-mcp.git   # or copy from shared location
cd slurm-mcp
pip install -e .
```

Or install into an existing conda/venv:

```bash
conda activate myenv          # or: source myenv/bin/activate
pip install -e /path/to/slurm-mcp
```

### 2. Run the setup script

```bash
bash setup.sh
```

This will:
- Detect your Python path, SLURM account, and default partition
- Generate a partition resource limits profile (`~/.slurm-mcp/partition_limits_latest.json`)
- Validate your default resources against the selected partition's actual limits
- Ask you to confirm or change each value
- Write the MCP server config into `~/.claude.json`

If you prefer to configure manually, see [Manual Configuration](#manual-configuration) below.

### 3. Restart Claude Code

```bash
# Exit any running Claude Code session, then relaunch:
claude
```

The SLURM tools will appear automatically. Try asking Claude:
> "List my running SLURM jobs"

---

## Tools Provided

| Tool | Description |
|------|-------------|
| `slurm_submit_job` | Submit a script or `--wrap` command via sbatch |
| `slurm_job_status` | Check status of one or more jobs (squeue + sacct) |
| `slurm_list_jobs` | List all jobs for the current user |
| `slurm_job_logs` | Read stdout/stderr logs for a job |
| `slurm_cancel_job` | Cancel a running or pending job |
| `slurm_job_resources` | Get resource usage for a completed job |
| `slurm_queue_info` | Show partition availability and limits |
| `slurm_node_info` | Per-node resource availability (free RAM, free CPUs, load) |
| `slurm_submit_batch` | Submit multiple scripts, optionally chained |

### Validation modes

Before submitting, you can validate your job at two levels:

| Parameter | What it does | Talks to SLURM? |
|-----------|-------------|-----------------|
| `dry_run=True` | Returns the sbatch command without running it | No |
| `test_only=True` | Asks the SLURM scheduler to validate (partition, resources, account, estimated start time) without creating a job | Yes |

---

## Manual Configuration

If you skipped `setup.sh`, add this block to your `~/.claude.json`. Replace
the placeholder values with your own:

```json
{
  "mcpServers": {
    "slurm": {
      "type": "stdio",
      "command": "<YOUR_PYTHON_PATH>",
      "args": ["-m", "slurm_mcp.server"],
      "env": {
        "SLURM_DEFAULT_ACCOUNT": "<YOUR_SLURM_ACCOUNT>",
        "SLURM_DEFAULT_PARTITION": "<YOUR_DEFAULT_PARTITION>",
        "SLURM_DEFAULT_NODES": "1",
        "SLURM_DEFAULT_NTASKS_PER_NODE": "1",
        "SLURM_DEFAULT_CPUS_PER_TASK": "8",
        "SLURM_DEFAULT_MEM": "64G",
        "SLURM_DEFAULT_TIME": "04:00:00",
        "SLURM_LOG_DIR": "<YOUR_HOME>/slurm_logs",
        "SLURM_MAX_CPUS": "64",
        "SLURM_MAX_MEM_GB": "256",
        "SLURM_MAX_TIME_HOURS": "168",
        "SLURM_MAX_GPUS": "4",
        "SLURM_PARTITION_LIMITS": "<YOUR_HOME>/.slurm-mcp/partition_limits_latest.json"
      }
    }
  }
}
```

To find each value:

```bash
which python3                              # → YOUR_PYTHON_PATH
sacctmgr show assoc user=$USER -p | head   # → YOUR_SLURM_ACCOUNT (Account column)
sinfo -s | head                            # → YOUR_DEFAULT_PARTITION
echo $HOME                                 # → YOUR_HOME
```

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `SLURM_DEFAULT_ACCOUNT` | `""` | `--account` for sbatch (required on most clusters) |
| `SLURM_DEFAULT_PARTITION` | `""` | `--partition` for sbatch |
| `SLURM_DEFAULT_NODES` | `1` | `--nodes` for sbatch |
| `SLURM_DEFAULT_NTASKS_PER_NODE` | `1` | `--ntasks-per-node` (increase for MPI jobs) |
| `SLURM_DEFAULT_CPUS_PER_TASK` | `8` | `--cpus-per-task` (threads for minimap2 -t, samtools -@, etc.) |
| `SLURM_DEFAULT_MEM` | `64G` | Default memory per job |
| `SLURM_DEFAULT_TIME` | `04:00:00` | Default wall time |
| `SLURM_LOG_DIR` | `~/slurm_logs` | Where stdout/stderr logs are written |
| `SLURM_MAX_CPUS` | `64` | Safety limit: max CPUs per job |
| `SLURM_MAX_MEM_GB` | `256` | Safety limit: max memory (GB) |
| `SLURM_MAX_TIME_HOURS` | `168` | Safety limit: max wall time (hours) |
| `SLURM_MAX_GPUS` | `4` | Safety limit: max GPUs per job |
| `SLURM_PARTITION_LIMITS` | `""` | Path to partition limits JSON (generated by `setup.sh`) |

---

## Safety Guardrails

The server validates every submission against configurable limits before
calling sbatch. Requests exceeding any limit are rejected with a clear error.

- **Per-partition limits**: When a partition limits profile is loaded
  (`SLURM_PARTITION_LIMITS`), validation uses the actual max CPUs, memory,
  time, and GPUs for the target partition. Requesting GPUs on a CPU-only
  partition is caught before submission.
- **Global fallback limits**: CPU, memory, time, and GPU limits apply when
  no partition profile is available.
- Optional partition allowlist (`SLURM_ALLOWED_PARTITIONS`)
- Audit log at `~/slurm_logs/audit.jsonl` (every submit/cancel is recorded)

---

## Optional: PostToolUse Hook (Submission Logging)

You can add a Claude Code hook to automatically log every SLURM submission to a
human-readable markdown file. Add this to `~/.claude/settings.json`:

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "mcp__slurm__slurm_submit_job",
        "command": "~/.claude/hooks/log-slurm-submission.sh"
      }
    ]
  }
}
```

See `~/.claude/hooks/log-slurm-submission.sh` for the hook script.
Each entry records: timestamp, job ID, job name, sbatch command, and status.

---

## Known Bugs and Gotchas

### 1. SLURM `$0` resolves to `/var/spool/slurmd/` in batch scripts

**Problem:** When sbatch runs a script, it copies the script to a SLURM spool
directory (e.g. `/var/spool/slurmd/job12345/slurm_script`). If your script
uses `dirname "$0"` to find its own location (a common pattern for setting
`BASE_DIR`), it will resolve to `/var/spool/slurmd/` instead of the original
script directory. Any `mkdir` or file writes relative to that path fail with
`Permission denied`.

**Symptom:** Jobs fail in ~2 seconds with:
```
mkdir: cannot create directory '/var/spool/slurmd/logs': Permission denied
mkdir: cannot create directory '/var/spool/slurmd/data': Permission denied
```

**Fix:** Use `SLURM_SUBMIT_DIR` (set by sbatch to the directory where sbatch
was invoked) or pass the base directory as a positional argument:

```bash
# BAD — breaks under SLURM
BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"

# GOOD — SLURM-safe with fallback
BASE_DIR="${1:-${SLURM_SUBMIT_DIR:-$(cd "$(dirname "$0")/.." && pwd)}}"
```

When submitting via the MCP server, prefer `--wrap` with an explicit argument:
```
wrap: bash /path/to/script.sh /path/to/base_dir
```

### 2. Account/partition must be specified

**Problem:** On MSKCC's cluster, omitting `--account` causes:
```
sbatch: error: Batch job submission failed: Invalid account or account/partition combination specified
```

**Fix:** Set `SLURM_DEFAULT_ACCOUNT=greenbab` and
`SLURM_DEFAULT_PARTITION=componc_cpu` in the MCP config. The server
automatically injects `--account` into every sbatch call.

### 3. MCP server must be restarted to pick up config changes

After editing `~/.claude.json`, you must restart Claude Code (exit and
relaunch) for the MCP server to pick up new environment variables.

---

## Project Structure

```
slurm-mcp/
  setup.sh                       # Interactive setup (detects account, partition, generates limits)
  pyproject.toml                 # Package metadata, dependencies
  LICENSE                        # MIT
  src/slurm_mcp/
    __init__.py
    server.py                    # MCP tool/resource definitions (FastMCP)
    slurm_cli.py                 # SLURM CLI wrappers + partition-aware validation
  tests/
    test_slurm_mcp.py            # 74 tests (all mocked, no real SLURM needed)
  docs/
    devlog.md                    # Development journal
    job_resource_profiles.md     # Comp-bio job classification (Q1-Q4 resource profiles)
```

---

## Testing

```bash
cd slurm-mcp
pytest tests/ --tb=short   # 74 tests, no real SLURM needed (all mocked)
```

---

## How It Works

1. Claude Code spawns the server as a subprocess via stdio transport
2. The server exposes SLURM tools via the Model Context Protocol
3. Claude calls tools like `mcp__slurm__slurm_submit_job` with parameters
4. The server validates resources, builds an sbatch command, and executes it
5. Results (job ID, log paths, etc.) are returned as JSON