Skip to main content
Glama
README.md
# sap-abap-mcp

**English** | [ภาษาไทย (Thai)](README.th.md)

Lightweight, safe **SAP ABAP ADT MCP server** written in Rust (`stdio` transport) with dual **HTTP/HTTPS & dynamic RFC** connectivity, **ABAP Test Cockpit (ATC)** integration, **Transport inspection**, and built-in write guardrails.

Licensed under the [MIT License](LICENSE).

## Why Rust?

- **Single static binary:** No Node.js, Python, or runtime dependencies to install or version-manage.
- **Minimal footprint:** Typically **< 15 MB RAM** with instant startup over MCP `stdio`.
- **HTTP + dynamic RFC in one binary:** Switch between modern S/4HANA HTTP(S) ADT and ECC / legacy BASIS `SADT_REST_RFC_ENDPOINT` using `--connection-type`.
- **Same binary across all systems:** Point one compiled executable at DEV, QAS, or sandbox `.env` profiles with distinct safety flags per environment.

## Features

- **Dual ADT Transport (`http` / `rfc`):**
  - `http`: Native async HTTP/HTTPS (`reqwest`, using Windows Schannel on Windows and `rustls` on Linux/macOS), cookie/CSRF handling, and optional `--insecure` for self-signed dev systems.
  - `rfc`: Dynamic runtime loading of the SAP NetWeaver RFC SDK (`SADT_REST_RFC_ENDPOINT`) for ECC, legacy BASIS releases, or RFC-only endpoints with reliable stateful lock sessions.
- **Built-in Safety Controls (`SafetyPolicy`):**
  - `--readonly`: Completely disables and omits all write/activation tools from the MCP tool list.
  - `--write-packages`: Glob-filtered package allowlist (default: `Z*,Y*,$TMP`).
  - `--require-transport`: Enforces a transport request number for non-local (non-`$`) packages (default: `true`).
  - **Standard SAP Namespace Protection:** Modifications to standard SAP objects outside customer namespaces (`Z*`, `Y*`, or `/NAMESPACE/`) are always blocked.
  - **Safe Write Pipeline:** `WriteSource` validates `SafetyPolicy` -> runs `SyntaxCheck` -> acquires `LOCK` -> uploads source (`PUT`) -> guarantees `UNLOCK` -> optionally activates.
- **Rich ATC Integration:**
  - `AtcRunCheck` and `AtcGetWorklist` enrich findings with surrounding source code snippets (`include_code_snippets`), syntax details, and `#EC` / `##` pseudo-comment suppress hints parsed from ADT documentation (`include_doc_hints`).
- **Transport Inspection & Pre-Release Gate:**
  - `TransportList` (`E070`/`E07T`) and `TransportGet` (tasks, `E071` objects, lock flags, and inactive object warnings).
  - `AtcRunTransport` runs ATC checks across all ATC-checkable ABAP code objects inside a transport request or task before release.

> **SAP NW RFC SDK Notice:** SAP NetWeaver RFC SDK binaries (`sapnwrfc.dll` on Windows, `libsapnwrfc.so` on Linux, `libsapnwrfc.dylib` on macOS, and accompanying ICU libraries) are **proprietary to SAP SE**. They are **NOT** bundled in this repository or in release binaries, and are loaded dynamically at runtime (`libloading`) **only** when `--connection-type=rfc` is selected.

## Installation

### Option 1: Prebuilt Binary (GitHub Releases)

Download the archive for your platform from the **Releases** page, verify its `.sha256` checksum, and extract `sap-abap-mcp` (or `sap-abap-mcp.exe` on Windows) to a directory on your `PATH`:

- Windows: `x86_64-pc-windows-msvc` (`.zip`)
- Linux: `x86_64-unknown-linux-gnu` (`.tar.gz`)
- macOS (Apple Silicon): `aarch64-apple-darwin` (`.tar.gz`)

### Option 2: Build from Source

Requires a stable Rust toolchain (`1.75+` recommended):

```bash
cargo build --release
```

The binary is output to `target/release/sap-abap-mcp` (`target\release\sap-abap-mcp.exe` on Windows).

### Prerequisites for Optional RFC Mode (`--connection-type=rfc`)

HTTP/HTTPS mode (`--connection-type=http`) works out of the box with zero external native libraries.

To use `--connection-type=rfc`:

1. Obtain the **SAP NetWeaver RFC SDK** from the SAP Support Portal (requires a valid SAP license).
2. Make the shared libraries (`sapnwrfc.dll` / `libsapnwrfc.so` / `libsapnwrfc.dylib` and the bundled ICU libraries) discoverable by either:
   - Setting `SAPNWRFC_HOME` to the SDK directory (containing `lib/`), or
   - Adding the SDK `lib` directory to `PATH` (Windows), `LD_LIBRARY_PATH` (Linux), or `DYLD_LIBRARY_PATH` (macOS).
3. Ensure the SAP user has authorization for `S_RFC` on `SADT_REST_RFC_ENDPOINT` as well as standard ADT/ATC/CTS authorizations.

## Configuration

Create a `.env` file outside your repository (see [`.env.example`](.env.example)):

```env
SAP_URL=http://sap-host.example.com:8000
SAP_CLIENT=100
SAP_USERNAME=DEVELOPER
SAP_PASSWORD=CHANGE_ME
SAP_LANGUAGE=EN

# Transport layer: "http" or "rfc"
SAP_CONNECTION_TYPE=http

# Optional explicit SAP system number for RFC (derived from port 80XX -> XX if omitted)
# SAP_SYSNR=00
```

> Never commit `.env` files or real credentials. See [SECURITY.md](SECURITY.md) for best practices.

### CLI Flags

All flags match [`src/config.rs`](src/config.rs):

| Flag | Env Var | Default | Description |
|---|---|---|---|
| `--env-path <PATH>` | `SAP_ENV_PATH` | — | Path to `.env` file containing `SAP_URL`, `SAP_CLIENT`, `SAP_USERNAME`, `SAP_PASSWORD`, `SAP_LANGUAGE` |
| `--connection-type <http\|rfc>` | `SAP_CONNECTION_TYPE` | `http` | Connection transport layer: `http` (ADT REST over HTTP/HTTPS) or `rfc` (`SADT_REST_RFC_ENDPOINT`) |
| `--sysnr <XX>` | `SAP_SYSNR` | Derived from port (`80XX -> XX`, else `00`) | Explicit 2-digit SAP system number for RFC mode |
| `--readonly` | — | `false` | Enforce read-only mode; write and activation tools are disabled and omitted from `tools/list` |
| `--write-packages <LIST>` | — | `Z*,Y*,$TMP` | Comma-separated allowed packages for write operations (supports `*` suffix) |
| `--require-transport <true\|false>` | — | `true` | Require a transport request number for non-local (non-`$`) packages |
| `--insecure` | — | `false` | Skip TLS certificate verification for self-signed HTTPS SAP servers |
| `--timeout-secs <N>` | — | `30` | HTTP request timeout in seconds (minimum `1`) |
| `--enho-runner-class <NAME>` | `SAP_ENHO_RUNNER_CLASS` | `ZCL_ENH_SOURCE_RUN` | Optional SE24 `$TMP` helper class implementing `IF_OO_ADT_CLASSRUN` for `EnhancementRead` / `EnhancementUpdate` |
| `--enable-enho-write` | — | `false` | Opt-in flag to expose `EnhancementUpdate` (DEV systems only; ignored if `--readonly` is set) |
| `--disable-sql` | `SAP_DISABLE_SQL` | `false` | Disable `RunSqlQuery` completely and omit it from `tools/list` (strongly recommended on QAS/PRD or systems containing sensitive PII/patient/HR data) |
| `--sql-allowed-tables <LIST>` | `SAP_SQL_ALLOWED_TABLES` | *(empty = all)* | Comma-separated allowed table patterns for `RunSqlQuery` (supports `*` suffix, e.g. `T000,DD02*,TSTC`) |
| `--sql-blocked-tables <LIST>` | `SAP_SQL_BLOCKED_TABLES` | *(empty)* | Comma-separated blocked table patterns for `RunSqlQuery` (supports `*` suffix, checked before allowlist, e.g. `PA0*,USR02`) |

## MCP Tools (19 Total)

### Read-Only, Search, ATC & Transport Tools (16 — Always Registered)

| Tool | Description | Parameters |
|---|---|---|
| `SearchObject` | Search ABAP objects via ADT `quickSearch` | `query` (required), `object_type` (optional), `max_results` (optional, default `25`) |
| `GetSource` | Read ABAP source code of a program, class (or class include: `definitions`, `implementations`, `macros`, `testclasses`), interface, function module, CDS view, or BDEF | `object_type` (required), `name` (required), `parent` (optional, for `FUNC`), `include` (optional, for `CLAS`) |
| `GetWhereUsed` | Find where-used references of an ABAP object | `object_type` (required), `name` (required), `parent` (optional) |
| `GetPackageContents` | List objects inside an ABAP package | `package_name` (required), `max_objects` (optional, default `200`) |
| `RunSqlQuery` | Execute a read-only Open SQL `SELECT` query via ADT Data Preview (`datapreview/freestyle`); enforces `--sql-allowed-tables` / `--sql-blocked-tables` and is omitted under `--disable-sql` | `sql` (required), `row_number` (optional, default `100`) |
| `ReadAdtUri` | Read any `/sap/bc/adt/...` resource via GET | `uri` (required), `accept` (optional) |
| `SyntaxCheck` | Run ABAP syntax check (`abapCheckRun`) on saved or unsaved source code | `object_type` (required), `name` (required), `source` (optional), `parent` (optional), `version` (optional, default `active`) |
| `GetInactiveObjects` | List currently inactive ABAP objects for the logged-in user | *(none)* |
| `AtcGetCustomizing` | Read ATC system customizing (`systemCheckVariant`, `ciCheckFlavour`, exemption reasons) | *(none)* |
| `AtcListVariants` | List available ATC / Code Inspector check variants (custom `Z*`/`Y*` listed first) | `filter` (optional), `include_veri` (optional, default `false`) |
| `AtcRunCheck` | Run an ATC check on an ABAP object or package and return findings enriched with source lines, syntax details, and `#EC`/`##` suppress hints | `object_name` (optional), `object_type` (optional), `object_uri` (optional), `check_variant` (optional), `max_verdicts` (optional, default `200`), `include_exempted` (optional, default `true`), `include_code_snippets` (optional, default `true`), `include_doc_hints` (optional, default `true`) |
| `AtcGetWorklist` | Retrieve findings from an existing ATC worklist ID | `worklist_id` (required), `include_exempted` (optional, default `true`), `include_code_snippets` (optional, default `true`), `include_doc_hints` (optional, default `true`) |
| `TransportList` | List transport requests (`E070`/`E07T` SQL with automatic ADT CTS API fallback via `/sap/bc/adt/cts/transportrequests` and `/sap/bc/adt/cts/transports?_action=FIND`) | `user` (optional), `status` (`D`/`R`/`ALL`, default `D`), `category` (`K`/`W`/`ALL`, default `ALL`), `filter` (optional), `max_results` (optional, default `50`) |
| `TransportGet` | Inspect a transport request or task (metadata, tasks, `E071` objects, lock flags, inactive check; includes ADT CTS REST fallback) | `transport_number` (required), `include_inactive_check` (optional, default `true`) |
| `AtcRunTransport` | Run ATC across all ATC-checkable ABAP code objects inside a transport request or task before release | `transport_number` (required), `check_variant` (optional), `max_verdicts` (optional, default `500`), `include_exempted` (optional, default `true`), `include_code_snippets` (optional, default `true`), `include_doc_hints` (optional, default `true`) |
| `EnhancementRead` | Read/dump customer `ENHO` hook implementations via optional SE24 `$TMP` classrun helper (`ZCL_ENH_SOURCE_RUN`) | `enho_name` (optional), `runner_class` (optional), `max_results` (optional, default `50`) |

> **⚠️ Data Privacy Warning (`RunSqlQuery`):** `RunSqlQuery` is **enabled by default** (read-only `SELECT` via ADT Data Preview), which means the AI client can query **any SAP table** that the configured `SAP_USERNAME` is authorized to read — including sensitive HR, financial, customer, or patient/PII data on systems containing real records. On QAS, PRD, or systems with real data, choose whether to disable SQL completely (`--disable-sql`) or restrict accessible tables (`--sql-allowed-tables` / `--sql-blocked-tables`) according to your security policy.

### Write & Activation Tools (2 Standard + 1 Opt-In ENHO — Omitted Under `--readonly`)

| Tool | Description | Parameters |
|---|---|---|
| `WriteSource` | Safely write ABAP source (`SafetyPolicy::check_write` -> `SyntaxCheck` -> `LOCK` -> `PUT` -> guaranteed `UNLOCK` -> optional `ACTIVATE`) | `object_type` (required), `name` (required), `source` (required), `package` (optional), `transport` (optional), `activate` (optional, default `true`), `parent` (optional), `include` (optional) |
| `ActivateObject` | Activate an inactive ABAP object (gated by `SafetyPolicy`) | `object_type` (required), `name` (required), `transport` (optional), `parent` (optional) |
| `EnhancementUpdate` *(opt-in: `--enable-enho-write`)* | DEV-only tool to update an existing `ENHO` hook implementation via `$TMP` `ZCL_ENH_SOURCE_RUN` with `dry_run=true` default, `SafetyPolicy` checks, TR enforcement, and guaranteed runner restore | `enho_name` (required), `full_name` (required), `source` (required), `package` (optional), `transport` (optional), `dry_run` (optional, default `true`), `activate` (optional, default `true`), `runner_class` (optional) |

## Optional: Source-Code Enhancement (`ENHO`) Read & Edit via `ZCL_ENH_SOURCE_RUN`

Standard SAP ADT APIs do not provide direct source-code PUT editing for implicit/explicit `ENHO` hook implementations. To support inspecting and updating `ENHO` hooks cleanly, this repository ships [`abap/ZCL_ENH_SOURCE_RUN.abap`](abap/ZCL_ENH_SOURCE_RUN.abap).

### Manual Setup Required in SE24

> **Important:** `ZCL_ENH_SOURCE_RUN` is **NOT automatically installed** on your SAP system. All other 15 tools (`SearchObject`, `GetSource`, `AtcRunCheck`, `WriteSource`, etc.) work without it, but `EnhancementRead` and `EnhancementUpdate` require you to create the helper class yourself first:

1. Open transaction **`SE24`** in your **DEV** SAP GUI.
2. Create class **`ZCL_ENH_SOURCE_RUN`** (`Public`, `Final`) and save it in package **`$TMP` (Local Object)** — **never assign it to a transportable package or transport it to QAS/PRD**.
3. Switch to **Source Code-Based** editor mode, paste the entire contents of [`abap/ZCL_ENH_SOURCE_RUN.abap`](abap/ZCL_ENH_SOURCE_RUN.abap), **Save**, and **Activate** (`Ctrl+F3`).
4. Verify in read-only mode by asking your AI client to run `EnhancementRead`.

### Critical Safety Warnings Before Enabling `--enable-enho-write`

- **DEV systems only:** Never enable `--enable-enho-write` or install `ZCL_ENH_SOURCE_RUN` on QAS or PRD.
- **Direct impact on SAP standard programs:** `ENHO` hook code is injected inside standard SAP programs/classes. A syntax error or bad runtime change inside an `ENHO` can trigger short dumps in standard SAP transactions (e.g., ME21N, MIGO, VA01). Always start with `dry_run: true` (the default), inspect the diff carefully, run syntax/ATC checks, and test in SAP GUI immediately after activation.
- **Strict `$TMP` requirement:** `EnhancementUpdate` refuses to run if `ZCL_ENH_SOURCE_RUN` is in any package other than `$*` (to prevent temporary dispatch code from ever entering a Transport Request).
- **Avoid concurrent ENHO updates on the same class:** Two simultaneous `EnhancementUpdate` calls sharing the same `ZCL_ENH_SOURCE_RUN` class can race. If multiple developers share a DEV client, give each developer their own `$TMP` class (e.g. `--enho-runner-class=ZCL_ENH_SOURCE_RUN_DEV1`).
- **Automatic restore guardrail:** `EnhancementUpdate` patches only between `*>>MCP_DISPATCH_START` and `*<<MCP_DISPATCH_END`, runs `IF_OO_ADT_CLASSRUN`, and **unconditionally restores `dump_all( out ).`** afterward. If a catastrophic network drop interrupts restoration, reset those markers manually in SE24.
- **Clean Core recommendation:** For new enhancements, create the `ENHO` once in SAP GUI calling a single method on a `ZCL_*` class, then maintain business logic in normal ABAP classes via `WriteSource`.

## Client Configuration Examples

Reuse **one binary** across multiple SAP systems (e.g., DEV with RFC write access + QAS in strict `--readonly` mode).

### Claude Desktop (`claude_desktop_config.json`)

```json
{
  "mcpServers": {
    "abap-dev": {
      "command": "/path/to/sap-abap-mcp",
      "args": [
        "--env-path=/path/to/secrets/sap-dev.env",
        "--connection-type=rfc",
        "--sysnr=00",
        "--write-packages=Z*,Y*,$TMP",
        "--require-transport=true"
      ]
    },
    "abap-qas": {
      "command": "/path/to/sap-abap-mcp",
      "args": [
        "--env-path=/path/to/secrets/sap-qas.env",
        "--connection-type=rfc",
        "--readonly",
        "--disable-sql"
      ]
    }
  }
}
```

On Windows, point `"command"` to `C:\\Tools\\sap-abap-mcp\\sap-abap-mcp.exe` and use Windows paths for `--env-path`.

### Claude Code (`.mcp.json` or `claude mcp add`)

Add via CLI:

```bash
# DEV system (RFC mode with transport enforcement)
claude mcp add abap-dev -- /path/to/sap-abap-mcp \
  --env-path=/path/to/secrets/sap-dev.env \
  --connection-type=rfc \
  --write-packages=Z*,Y*,$TMP \
  --require-transport=true

# QAS system (strict read-only HTTP mode)
claude mcp add abap-qas -- /path/to/sap-abap-mcp \
  --env-path=/path/to/secrets/sap-qas.env \
  --connection-type=http \
  --readonly
```

Example usage prompts in your AI client:

- *"Search for `ZMY_CLASS` and check its source code."*
- *"Run `AtcRunCheck` on `ZMY_PROGRAM` and show any findings with suppress hints."*
- *"Inspect transport `DEVK900001` with `TransportGet` and run `AtcRunTransport` before release."*

## Common Workflows

1. **Read & Analyze ABAP Code Safely (`--readonly`)**
   - `SearchObject` -> `GetPackageContents` -> `GetSource` / `GetWhereUsed` / `RunSqlQuery`
2. **Fix ATC Findings End-to-End**
   - `AtcGetCustomizing` / `AtcListVariants` -> `AtcRunCheck` (returns surrounding source lines + syntax errors + `#EC` / `##` pseudo-comment suppress hints) -> `SyntaxCheck` -> `WriteSource` -> re-run `AtcRunCheck`
3. **Pre-Release Transport Gate**
   - `TransportList` -> `TransportGet` (verifies tasks, `E071` objects, locks, and flags inactive objects) -> `AtcRunTransport` (checks all ATC-checkable ABAP code inside the transport before release)

## Troubleshooting

- **HTTP 423 (`Resource locked` / stateful lock error on write/check):**
  Some SAP systems (especially ECC or behind certain proxies/ICM setups) drop stateful HTTP lock cookies across ADT requests. Switch to `--connection-type=rfc` (`--sysnr=XX`), where `SADT_REST_RFC_ENDPOINT` keeps locks inside the stateful RFC connection.
- **SAP NW RFC SDK library not found (`rfc` mode):**
  Ensure `sapnwrfc.dll` (`PATH` / `SAPNWRFC_HOME\lib`) or `libsapnwrfc.so` / `libsapnwrfc.dylib` plus its matching ICU libraries are on your library search path and match the 64-bit architecture of `sap-abap-mcp`.
- **Self-signed HTTPS certificates on dev SAP systems:**
  Pass `--insecure` when using `--connection-type=http` against internal HTTPS endpoints without a public CA certificate.
- **RFC system number (`--sysnr`):**
  If `SAP_URL` uses a standard ICM port like `:8000` or `:8081`, `--sysnr` automatically derives `00` or `81`. For reverse-proxied or non-standard ports, set `--sysnr=XX` (or `SAP_SYSNR=XX` in `.env`) explicitly.

## Development & Testing

All tests run offline without a live SAP system or SAP NW RFC SDK binaries:

```bash
# Check formatting
cargo fmt --all -- --check

# Lint with Clippy
cargo clippy --all-targets -- -D warnings

# Run unit and integration tests
cargo test
```

See [CONTRIBUTING.md](CONTRIBUTING.md) for clean-room contribution rules and PR requirements.