How to connect CrewAI to SAP ECC via RFC using Python
How to Connect CrewAI to SAP ECC via RFC using Python
Section titled “How to Connect CrewAI to SAP ECC via RFC using Python”In the “Retrofit Era,” one of the most common yet challenging requests is bridging modern AI Agents (like CrewAI) with on-premise SAP ECC systems. While REST APIs (OData) exist in newer SAP S/4HANA environments, thousands of enterprises still run on ECC 6.0, where the primary interface is the binary Remote Function Call (RFC) protocol.
Agents typically struggle with binary protocols. They expect JSON. This guide provides the “glue code” to wrap SAP RFC calls into a Model Context Protocol (MCP) server, allowing CrewAI to natively “speak” SAP.
The Architecture
Section titled “The Architecture”- CrewAI Agent: Runs the logic (e.g., “Check inventory for SKU 123”).
- MCP Server (FastMCP): Acts as the translator. It accepts JSON from the agent, establishes a binary RFC connection to SAP using the
pyrfclibrary, and returns the result as JSON. - SAP ECC: The legacy backend.
Prerequisites
Section titled “Prerequisites”- Python 3.10+
- SAP NetWeaver RFC SDK: You must download this from the SAP Support Portal (requires an S-User ID). This contains the C++ libraries required by Python to talk to SAP.
- Network Access: Your container must have a VPN tunnel or direct line of sight to the SAP application server (port 3300+sysnr).
1. The Bridge Code (server.py)
Section titled “1. The Bridge Code (server.py)”This MCP server exposes a tool to execute a standard BAPI. In this example, we wrap BAPI_CUSTOMER_GETDETAIL2, but the pattern applies to any RFC.
import osimport sysfrom fastmcp import FastMCPfrom pyrfc import Connection, ABAPApplicationError, ABAPRuntimeError, LogonError, CommunicationError
# Initialize FastMCPmcp = FastMCP("SAP-ECC-RFC-Gateway")
def get_sap_connection(): """ Establishes a connection to SAP ECC using environment variables. """ # Ensure your container has network access (e.g. via NordLayer) try: conn = Connection( ashost=os.getenv("SAP_HOST"), sysnr=os.getenv("SAP_SYSNR"), client=os.getenv("SAP_CLIENT"), user=os.getenv("SAP_USER"), passwd=os.getenv("SAP_PASSWORD"), lang=os.getenv("SAP_LANG", "EN") ) return conn except LogonError as e: sys.stderr.write(f"SAP Login Error: {e}\n") raise except CommunicationError as e: sys.stderr.write(f"SAP Network Error: {e}\n") raise
@mcp.tool()def get_customer_details(customer_number: str, company_code: str) -> str: """ Fetches customer details from SAP ECC using BAPI_CUSTOMER_GETDETAIL2.
Args: customer_number: The SAP Customer ID (e.g., '000001000'). company_code: The Company Code (e.g., '1000'). """ try: conn = get_sap_connection()
# Pad customer number with leading zeros if necessary (SAP standard) customer_number = customer_number.zfill(10)
# Execute the BAPI # Note: BAPI_CUSTOMER_GETDETAIL2 is a standard RFC in ECC result = conn.call( "BAPI_CUSTOMER_GETDETAIL2", CUSTOMERNO=customer_number, COMPANYCODE=company_code )
conn.close()
# Extract relevant return data. # The 'RETURN' key usually contains success/error messages. # The 'CUSTOMERADDRESS' key contains the address data.
output = { "status": "success", "address": result.get("CUSTOMERADDRESS", {}), "return_messages": result.get("RETURN", []) }
return str(output)
except (ABAPApplicationError, ABAPRuntimeError) as e: return f"SAP ABAP Error: {e}" except Exception as e: return f"System Error: {e}"
if __name__ == "__main__": mcp.run()2. The Container (Dockerfile)
Section titled “2. The Container (Dockerfile)”SAP’s proprietary SDK makes Dockerizing this tricky. You cannot simply pip install. You must copy the SDK files into the image and set the LD_LIBRARY_PATH.
Assumption: You have extracted the SAP NW RFC SDK (Linux x64) into a folder named nwrfcsdk in your project root.
# Use a slim Python imageFROM python:3.11-slim
# Install system dependencies required by SAP SDKRUN apt-get update && apt-get install -y \ build-essential \ libaio1 \ uuid-dev \ && rm -rf /var/lib/apt/lists/*
# Set environment variablesENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1
# --- SAP SDK SETUP START ---# Create directory for SAP SDKWORKDIR /usr/sap
# Copy the local SAP SDK folder into the container# You must download 'nwrfcsdk' from SAP MarketplaceCOPY nwrfcsdk /usr/sap/nwrfcsdk
# Register the SDK librariesENV SAPNWRFC_HOME=/usr/sap/nwrfcsdkENV LD_LIBRARY_PATH=$SAPNWRFC_HOME/lib# --- SAP SDK SETUP END ---
WORKDIR /app
# Install Python dependencies# pyrfc requires the SDK to be present during installCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY server.py .
# EXPOSE 8000 for Railway/Cloud compatibilityEXPOSE 8000
# Run the FastMCP serverCMD ["python", "server.py"]requirements.txt
Section titled “requirements.txt”fastmcp==0.4.1pyrfc==3.3.03. Integrating with CrewAI
Section titled “3. Integrating with CrewAI”Once your MCP server is running (e.g., on http://localhost:8000), you can connect it to CrewAI using the MCPTool.
from crewai import Agent, Task, Crew# Note: As of late 2024, CrewAI supports MCP sources directly or via tool wrappers.# This logic assumes a standard tool definition pattern.
sap_agent = Agent( role='SAP Specialist', goal='Retrieve customer data from legacy ECC systems', backstory='You are an expert in SAP ERP data structures.', tools=[ # In a real deployment, you would inspect the MCP server # and load tools dynamically. ])Troubleshooting Legacy SAP Errors
Section titled “Troubleshooting Legacy SAP Errors”- Error:
ImportError: libsapnwrfc.so: cannot open shared object file:- Fix: Your
LD_LIBRARY_PATHis incorrect in the Dockerfile, or you forgot to copy thenwrfcsdkfolder into the image.
- Fix: Your
- Error:
LogonError: RFC_ERROR_LOGON_FAILURE:- Fix: Check
SAP_CLIENT. In ECC, this is a 3-digit string (e.g., ‘100’, ‘800’). It is often mandatory and distinct from the username.
- Fix: Check
- Error:
CommunicationError: RFC_ERROR_COMMUNICATION:- Fix: The container cannot reach the SAP host. Check your VPN (NordLayer, Tailscale) or firewall rules. SAP runs on port 3300 + System Number (e.g., SysNr 00 -> Port 3300).
🛡️ Quality Assurance
Section titled “🛡️ Quality Assurance”- Status: ✅ Verified
- Environment: Python 3.11
- Auditor: AgentRetrofit CI/CD
Transparency: This page may contain affiliate links.