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.
⚠️ The “Big Iron” Prerequisite
Section titled “⚠️ The “Big Iron” Prerequisite”Unlike standard Python libraries, SAP RFC requires the proprietary SAP NetWeaver RFC SDK.
- Download: You must download the SAP NW RFC SDK 7.50 from the SAP Support Portal (requires S-User).
- Extract: Unzip the Linux version into a folder named
nwrfcsdkin your project root. - 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.
1. The Code (server.py)
Section titled “1. The Code (server.py)”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 osfrom fastmcp import FastMCPfrom pyrfc import Connection, LogonError, CommunicationError
# Initialize FastMCPmcp = 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()2. The Container (Dockerfile)
Section titled “2. The Container (Dockerfile)”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└── DockerfileDockerfile:
# Use a slim Python baseFROM python:3.11-slim
# Install system dependencies required by SAP SDK# 'unzip' and 'gcc' might be needed depending on your specific SDK operationsRUN 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 SDKWORKDIR /usr/local/sap
# COPY the local extracted SDK folder into the container# NOTE: You must download nwrfcsdk from SAP Support Portal firstCOPY nwrfcsdk /usr/local/sap/nwrfcsdk
# Set Environment Variables so Python can find the C++ librariesENV SAPNWRFC_HOME=/usr/local/sap/nwrfcsdkENV LD_LIBRARY_PATH=$SAPNWRFC_HOME/lib
# 2. Install Python DependenciesWORKDIR /appCOPY requirements.txt .
# Install pyrfc (which compiles against the SDK) and fastmcpRUN pip install --no-cache-dir -r requirements.txt
# 3. Copy Application CodeCOPY server.py .
# Ensure your container has network access (e.g. via NordLayer)
# 4. Expose Port 8000 for Railway/MCPEXPOSE 8000
# 5. Run the ServerCMD ["python", "server.py"]requirements.txt:
pyrfc==3.3fastmcp3. Integration Notes
Section titled “3. Integration Notes”Network Security
Section titled “Network Security”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.
Authentication Modes
Section titled “Authentication Modes”- Basic Auth: (Used above)
user/passwd. Easiest for prototypes, but credentials should be rotated frequently. - SNC (Secure Network Communications): Connects via X.509 certificates. Requires the
libsapcrypto.solibrary (also from SAP) and setting thesnc_partnernameparameter. This is the recommended standard for production agents.
Common Errors
Section titled “Common Errors”ImportError: libsapnwrfc.so: cannot open shared object file:- Fix: Your
LD_LIBRARY_PATHin the Dockerfile is incorrect, or you forgot to COPY thenwrfcsdkfolder.
- Fix: Your
CommunicationError: partner '192.168.x.x:3300' not reached:- Fix: The container cannot see the SAP server. Check your VPN or firewall whitelist.
🛡️ Quality Assurance
Section titled “🛡️ Quality Assurance”- Status: ✅ Verified
- Environment: Python 3.11
- Auditor: AgentRetrofit CI/CD
Transparency: This page may contain affiliate links.