Skip to content

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.

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).

  1. 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 nwrfcsdk folder in your project root.
  2. SAP Credentials: A service user in SAP with permissions to execute BAPI_MATERIAL_SAVEDATA and BAPI_TRANSACTION_COMMIT.

This server exposes a tool to update material descriptions. It handles the connection, the BAPI call, and the required transaction commit.

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

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 image
FROM python:3.10-slim
# Set environment variables for SAP NWRFC SDK
# These tell the OS where to find the SAP C++ libraries
ENV SAPNWRFC_HOME=/usr/local/sap/nwrfcsdk
ENV LD_LIBRARY_PATH=$SAPNWRFC_HOME/lib
# Install system dependencies required by SAP SDK
# uuid-dev is often required by the NWRFC SDK
RUN 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 CONTEXT
WORKDIR /usr/local/sap
COPY nwrfcsdk ./nwrfcsdk
# Setup config for ldconfig so libraries are found
RUN echo "$SAPNWRFC_HOME/lib" > /etc/ld.so.conf.d/sapnwrfc.conf \
&& ldconfig
# Set up the application
WORKDIR /app
# Install Python dependencies
# cython is required to build pyrfc
RUN pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir cython fastmcp pyrfc
# Copy the server code
COPY server.py .
# Expose the port for Railway/MCP
EXPOSE 8000
# Ensure your container has network access (e.g. via NordLayer)
# Run the MCP server
CMD ["python", "server.py"]

To use this with AutoGen, you configure the UserProxy to execute the MCP tool.

# Example AutoGen Configuration snippet
from autogen import UserProxyAgent, AssistantAgent
# Define the user proxy
user_proxy = UserProxyAgent(
name="Admin",
system_message="A human admin.",
code_execution_config={"work_dir": "coding", "use_docker": False},
)
# Define the SAP Assistant
sap_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"]
}
}
]
}
)
Error CodeMeaningFix
ImportError: libsapnwrfc.soOS cannot find the SDK libraries.Check LD_LIBRARY_PATH in Dockerfile. Ensure nwrfcsdk was copied correctly.
RFC_ERROR_LOGON_FAILUREInvalid credentials.Verify SAP_USER and SAP_PASSWORD. Check if the user is locked.
BAPI_MATERIAL_SAVEDATA not foundFunction missing on SAP.Ensure the target system is ECC 6.0 or higher.
Connection RefusedNetwork blocking.Use a VPN (NordLayer) or allowlist the container IP in the SAP Gateway (secinfo).

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

Transparency: This page may contain affiliate links.