Skip to content

Handling SAP ECC RFC Authentication for AI Agents (Python)

Handling SAP ECC RFC Authentication for AI Agents (Python)

Section titled “Handling SAP ECC RFC Authentication for AI Agents (Python)”

Connecting modern AI agents (like CrewAI, LangGraph, or OpenAI Operator) to SAP ECC often requires bypassing the slow GUI and talking directly to the system’s “binary brain”—the RFC (Remote Function Call) interface.

While REST/OData adapters exist for newer SAP S/4HANA systems, millions of lines of business logic still live in ECC 6.0 (or older) systems that only speak RFC. This guide provides a production-ready FastMCP server to authenticate and execute BAPIs on SAP ECC.

Unlike standard Python libraries, SAP RFC requires the proprietary SAP NetWeaver RFC SDK.

  1. Download: You must download the SAP NW RFC SDK 7.50 from the SAP Support Portal (requires S-User).
  2. Extract: Unzip the Linux version into a folder named nwrfcsdk in your project root.
  3. VPN: SAP ECC is rarely exposed to the public internet. Your Docker container must run inside a VPN (e.g., NordLayer, Tailscale) or on-premise network.

This MCP server exposes a generic tool execute_bapi that agents can use to call any remote function module (e.g., BAPI_USER_GET_DETAIL, RFC_READ_TABLE). It handles the connection handshake and authentication.

import os
from fastmcp import FastMCP
from pyrfc import Connection, LogonError, CommunicationError
# Initialize FastMCP
mcp = FastMCP("SAP-ECC-RFC-Gateway")
# Ensure your container has network access (e.g. via NordLayer)
@mcp.tool()
def execute_bapi(
function_name: str,
parameters: dict = None
) -> dict:
"""
Authenticates with SAP ECC and executes a BAPI/RFC function.
Args:
function_name: The name of the SAP Function Module (e.g. 'STFC_CONNECTION', 'BAPI_SALESORDER_GETLIST').
parameters: A dictionary of import parameters and tables required by the function.
Returns:
A dictionary containing the export parameters and tables returned by SAP.
"""
if parameters is None:
parameters = {}
# 1. Configuration (Load from Environment Variables for Security)
# In production, use Docker secrets or a vault.
sap_config = {
'ashost': os.getenv("SAP_HOST", "192.168.1.10"),
'sysnr': os.getenv("SAP_SYSNR", "00"),
'client': os.getenv("SAP_CLIENT", "100"),
'user': os.getenv("SAP_USER"),
'passwd': os.getenv("SAP_PASSWORD"),
'lang': os.getenv("SAP_LANG", "EN"),
# For SNC (Secure Network Communications), uncomment below:
# 'snc_partnername': os.getenv("SAP_SNC_PARTNER"),
# 'snc_lib': os.getenv("SAP_SNC_LIB"),
}
try:
# 2. Establish Connection
with Connection(**sap_config) as conn:
# 3. Execute the RFC
result = conn.call(function_name, **parameters)
return result
except LogonError as e:
return {"error": "Authentication Failed", "details": str(e)}
except CommunicationError as e:
return {"error": "Network/Communication Error", "details": str(e)}
except Exception as e:
return {"error": "Unknown SAP Error", "details": str(e)}
if __name__ == "__main__":
mcp.run()

This Dockerfile is critical. It sets up the Linux environment to recognize the SAP proprietary C++ libraries (libsapnwrfc.so) before installing the Python wrapper.

Directory Structure:

/my-project
├── nwrfcsdk/ # <--- Extracted SAP SDK folder
├── server.py
├── requirements.txt
└── Dockerfile

Dockerfile:

# Use a slim Python base
FROM python:3.11-slim
# Install system dependencies required by SAP SDK
# 'unzip' and 'gcc' might be needed depending on your specific SDK operations
RUN apt-get update && apt-get install -y \
gcc \
g++ \
make \
&& rm -rf /var/lib/apt/lists/*
# 1. Setup SAP SDK Environment
# Create directory for the SDK
WORKDIR /usr/local/sap
# COPY the local extracted SDK folder into the container
# NOTE: You must download nwrfcsdk from SAP Support Portal first
COPY nwrfcsdk /usr/local/sap/nwrfcsdk
# Set Environment Variables so Python can find the C++ libraries
ENV SAPNWRFC_HOME=/usr/local/sap/nwrfcsdk
ENV LD_LIBRARY_PATH=$SAPNWRFC_HOME/lib
# 2. Install Python Dependencies
WORKDIR /app
COPY requirements.txt .
# Install pyrfc (which compiles against the SDK) and fastmcp
RUN pip install --no-cache-dir -r requirements.txt
# 3. Copy Application Code
COPY server.py .
# Ensure your container has network access (e.g. via NordLayer)
# 4. Expose Port 8000 for Railway/MCP
EXPOSE 8000
# 5. Run the Server
CMD ["python", "server.py"]

requirements.txt:

pyrfc==3.3
fastmcp

SAP RFC uses port 33xx (where xx is the System Number, e.g., 3300). Most SAP systems are behind aggressive corporate firewalls.

  • Local Dev: Use a VPN client on your host machine.
  • Cloud Deployment: Use a “Sidecar” container (like NordLayer or Tailscale) in your pod to tunnel traffic to the on-premise SAP server.
  1. Basic Auth: (Used above) user/passwd. Easiest for prototypes, but credentials should be rotated frequently.
  2. SNC (Secure Network Communications): Connects via X.509 certificates. Requires the libsapcrypto.so library (also from SAP) and setting the snc_partnername parameter. This is the recommended standard for production agents.
  • ImportError: libsapnwrfc.so: cannot open shared object file:
    • Fix: Your LD_LIBRARY_PATH in the Dockerfile is incorrect, or you forgot to COPY the nwrfcsdk folder.
  • CommunicationError: partner '192.168.x.x:3300' not reached:
    • Fix: The container cannot see the SAP server. Check your VPN or firewall whitelist.

  • Status: ✅ Verified
  • Environment: Python 3.11
  • Auditor: AgentRetrofit CI/CD

Transparency: This page may contain affiliate links.