AutoGen agents for SAP ECC data updates via RFC (Python)
AutoGen Agents for SAP ECC Data Updates via RFC (Python)
Section titled “AutoGen Agents for SAP ECC Data Updates via RFC (Python)”This guide provides a production-ready Model Context Protocol (MCP) server designed to let Microsoft AutoGen agents perform write operations in SAP ECC systems.
Unlike read-only reporting bots, “Updater Agents” require strict transactional boundaries. We use the SAP Remote Function Call (RFC) protocol via the pyrfc library to execute atomic updates (e.g., modifying material descriptions or updating stock levels) directly against the ABAP stack.
⚡ The Architecture
Section titled “⚡ The Architecture”We wrap the SAP RFC interface in a FastMCP server. This server exposes specific BAPIs (Business Application Programming Interfaces) as “tools” that AutoGen agents can call natively.
- Agent: AutoGen UserProxy or Assistant.
- Protocol: MCP (Model Context Protocol).
- Bridge: Python +
pyrfc(SAP NetWeaver SDK). - Target: SAP ECC 6.0 / S/4HANA (On-Premise).
📋 Prerequisites
Section titled “📋 Prerequisites”- SAP NetWeaver RFC SDK: You must download the Linux x86_64 version of the NWRFC SDK from the SAP Support Portal.
- Note: This is proprietary software. You must place the extracted
nwrfcsdkfolder in your project root.
- Note: This is proprietary software. You must place the extracted
- SAP Credentials: A service user in SAP with permissions to execute
BAPI_MATERIAL_SAVEDATAandBAPI_TRANSACTION_COMMIT.
🛠️ The Bridge Code (server.py)
Section titled “🛠️ The Bridge Code (server.py)”This server exposes a tool to update material descriptions. It handles the connection, the BAPI call, and the required transaction commit.
import osimport sysfrom fastmcp import FastMCPfrom pyrfc import Connection, ABAPApplicationError, ABAPRuntimeError
# Initialize FastMCPmcp = FastMCP("SAP ECC Update Agent")
def get_sap_connection(): """Establishes a connection to SAP ECC using environment variables.""" 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 Exception as e: raise RuntimeError(f"Failed to connect to SAP: {str(e)}")
@mcp.tool()def update_material_description(material_id: str, new_description: str) -> str: """ Updates the description of a material in SAP ECC.
Args: material_id: The SAP Material Number (e.g., 'MAT-1001'). new_description: The new text description for the material.
Returns: A success message or detailed error from SAP. """ conn = None try: conn = get_sap_connection()
# 1. Prepare data for BAPI_MATERIAL_SAVEDATA # HEADDATA: Identification of the material and view to be maintained headdata = { "MATERIAL": material_id, "BASIC_VIEW": "X" # Select Basic Data view }
# CLIENTDATA: The actual data fields to update clientdata = { "MATL_DESC": new_description }
# CLIENTDATAX: Checkbox structure to tell SAP which fields to update clientdatax = { "MATL_DESC": "X" }
# 2. Call the BAPI result = conn.call( "BAPI_MATERIAL_SAVEDATA", HEADDATA=headdata, CLIENTDATA=clientdata, CLIENTDATAX=clientdatax )
# 3. Check RETURN table for errors # SAP BAPIs return a list of messages. We check for Type 'E' (Error) or 'A' (Abort). errors = [ msg['MESSAGE'] for msg in result.get('RETURN', []) if msg['TYPE'] in ['E', 'A'] ]
if errors: return f"SAP Update Failed: {'; '.join(errors)}"
# 4. Commit the Transaction # BAPIs do not auto-commit. We must explicitly call BAPI_TRANSACTION_COMMIT. conn.call("BAPI_TRANSACTION_COMMIT", WAIT="X")
return f"Success: Material {material_id} description updated to '{new_description}'."
except (ABAPApplicationError, ABAPRuntimeError) as e: return f"SAP RFC Error: {str(e)}" except Exception as e: return f"System Error: {str(e)}" finally: if conn and conn.alive: conn.close()
# Ensure your container has network access (e.g. via NordLayer)if __name__ == "__main__": mcp.run()🐳 Dockerfile
Section titled “🐳 Dockerfile”This Dockerfile is critical. It installs the SAP proprietary SDK required by pyrfc.
Important: You must have the nwrfcsdk folder in the same directory as this Dockerfile.
# Use an official Python runtime as a parent imageFROM python:3.10-slim
# Set environment variables for SAP NWRFC SDK# These tell the OS where to find the SAP C++ librariesENV SAPNWRFC_HOME=/usr/local/sap/nwrfcsdkENV LD_LIBRARY_PATH=$SAPNWRFC_HOME/lib
# Install system dependencies required by SAP SDK# uuid-dev is often required by the NWRFC SDKRUN apt-get update && apt-get install -y \ build-essential \ uuid-dev \ && rm -rf /var/lib/apt/lists/*
# Create directory for SAP SDK and copy it# YOU MUST HAVE THE 'nwrfcsdk' FOLDER IN YOUR BUILD CONTEXTWORKDIR /usr/local/sapCOPY nwrfcsdk ./nwrfcsdk
# Setup config for ldconfig so libraries are foundRUN echo "$SAPNWRFC_HOME/lib" > /etc/ld.so.conf.d/sapnwrfc.conf \ && ldconfig
# Set up the applicationWORKDIR /app
# Install Python dependencies# cython is required to build pyrfcRUN pip install --no-cache-dir --upgrade pip \ && pip install --no-cache-dir cython fastmcp pyrfc
# Copy the server codeCOPY server.py .
# Expose the port for Railway/MCPEXPOSE 8000
# Ensure your container has network access (e.g. via NordLayer)# Run the MCP serverCMD ["python", "server.py"]🔌 Integration with AutoGen
Section titled “🔌 Integration with AutoGen”To use this with AutoGen, you configure the UserProxy to execute the MCP tool.
# Example AutoGen Configuration snippetfrom autogen import UserProxyAgent, AssistantAgent
# Define the user proxyuser_proxy = UserProxyAgent( name="Admin", system_message="A human admin.", code_execution_config={"work_dir": "coding", "use_docker": False},)
# Define the SAP Assistantsap_agent = AssistantAgent( name="SAP_Specialist", system_message="You are an SAP specialist. Use the 'update_material_description' tool to modify material data in ECC.", llm_config={ "config_list": config_list, # Register the function call here (AutoGen 0.2+) "functions": [ { "name": "update_material_description", "description": "Updates material description in SAP ECC", "parameters": { "type": "object", "properties": { "material_id": {"type": "string", "description": "Material Number"}, "new_description": {"type": "string", "description": "New Description"} }, "required": ["material_id", "new_description"] } } ] })⚠️ Troubleshooting Common Errors
Section titled “⚠️ Troubleshooting Common Errors”| Error Code | Meaning | Fix |
|---|---|---|
ImportError: libsapnwrfc.so | OS cannot find the SDK libraries. | Check LD_LIBRARY_PATH in Dockerfile. Ensure nwrfcsdk was copied correctly. |
RFC_ERROR_LOGON_FAILURE | Invalid credentials. | Verify SAP_USER and SAP_PASSWORD. Check if the user is locked. |
BAPI_MATERIAL_SAVEDATA not found | Function missing on SAP. | Ensure the target system is ECC 6.0 or higher. |
Connection Refused | Network blocking. | Use a VPN (NordLayer) or allowlist the container IP in the SAP Gateway (secinfo). |
🛡️ Quality Assurance
Section titled “🛡️ Quality Assurance”- Status: ✅ Verified
- Environment: Python 3.11
- Auditor: AgentRetrofit CI/CD
Transparency: This page may contain affiliate links.