Skip to content

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.

  1. CrewAI Agent: Runs the logic (e.g., “Check inventory for SKU 123”).
  2. MCP Server (FastMCP): Acts as the translator. It accepts JSON from the agent, establishes a binary RFC connection to SAP using the pyrfc library, and returns the result as JSON.
  3. SAP ECC: The legacy backend.
  • 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).

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 os
import sys
from fastmcp import FastMCP
from pyrfc import Connection, ABAPApplicationError, ABAPRuntimeError, LogonError, CommunicationError
# Initialize FastMCP
mcp = 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()

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 image
FROM python:3.11-slim
# Install system dependencies required by SAP SDK
RUN apt-get update && apt-get install -y \
build-essential \
libaio1 \
uuid-dev \
&& rm -rf /var/lib/apt/lists/*
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# --- SAP SDK SETUP START ---
# Create directory for SAP SDK
WORKDIR /usr/sap
# Copy the local SAP SDK folder into the container
# You must download 'nwrfcsdk' from SAP Marketplace
COPY nwrfcsdk /usr/sap/nwrfcsdk
# Register the SDK libraries
ENV SAPNWRFC_HOME=/usr/sap/nwrfcsdk
ENV LD_LIBRARY_PATH=$SAPNWRFC_HOME/lib
# --- SAP SDK SETUP END ---
WORKDIR /app
# Install Python dependencies
# pyrfc requires the SDK to be present during install
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY server.py .
# EXPOSE 8000 for Railway/Cloud compatibility
EXPOSE 8000
# Run the FastMCP server
CMD ["python", "server.py"]
fastmcp==0.4.1
pyrfc==3.3.0

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.
]
)
  • Error: ImportError: libsapnwrfc.so: cannot open shared object file:
    • Fix: Your LD_LIBRARY_PATH is incorrect in the Dockerfile, or you forgot to copy the nwrfcsdk folder into the image.
  • 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.
  • 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).

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

Transparency: This page may contain affiliate links.