LangGraph agent orchestration for SAP ECC BAPI calls (Python)
LangGraph Agent Orchestration for SAP ECC BAPI Calls
Section titled “LangGraph Agent Orchestration for SAP ECC BAPI Calls”In the enterprise automation landscape, connecting stateful, reasoning agents (like those built with LangGraph) to rigid, transactional systems (like SAP ECC) is a massive hurdle. LangGraph excels at maintaining conversation history and planning multi-step workflows, while SAP ECC requires precise, stateless Remote Function Calls (RFCs).
This guide provides the “glue” layer: a FastMCP server that exposes SAP BAPIs as executable tools. Your LangGraph agent treats these BAPIs as simple function calls, abstracting away the complexity of the pyrfc binary protocol.
The Architecture
Section titled “The Architecture”- LangGraph Agent: Manages the workflow state (e.g., “User wants to check stock, then create an order”).
- MCP Server: A Dockerized Python service that holds the persistent connection pool to SAP.
- SAP ECC: The legacy ERP system receiving RFC calls.
Prerequisites
Section titled “Prerequisites”Before running this code, you need:
- SAP NetWeaver RFC SDK: Proprietary libraries from the SAP Marketplace (nwrfcsdk).
- Python libraries:
pyrfc,fastmcp.
The Code (server.py)
Section titled “The Code (server.py)”This MCP server exposes a tool to fetch material details. We use pyrfc for the actual connectivity.
import osfrom fastmcp import FastMCPfrom pyrfc import Connection, ABAPApplicationError, ABAPRuntimeError
# Initialize FastMCPmcp = FastMCP("SAP-ECC-Gateway")
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 get_material_details(material_id: str, plant: str) -> str: """ Fetches details for a specific material from SAP ECC using BAPI_MATERIAL_GET_DETAIL.
Args: material_id: The 18-character SAP Material Number (e.g., '000000000000100500'). plant: The specific plant code (e.g., '1000'). """ conn = None try: conn = get_sap_connection()
# Ensure material_id is padded with leading zeros if numeric # SAP typically requires 18 chars for MATNR padded_material = material_id.zfill(18) if material_id.isdigit() else material_id
result = conn.call( "BAPI_MATERIAL_GET_DETAIL", MATERIAL=padded_material, PLANT=plant )
# Check BAPI RETURN table for functional errors return_msgs = result.get("RETURN", {}) if return_msgs and return_msgs.get("TYPE") == "E": return f"SAP Error: {return_msgs.get('MESSAGE')}"
material_data = result.get("MATERIAL_GENERAL_DATA", {}) desc = material_data.get("MATL_DESC", "No description") base_uom = material_data.get("BASE_UOM", "N/A")
return f"Material: {material_id} | Desc: {desc} | UoM: {base_uom} | Status: Active"
except (ABAPApplicationError, ABAPRuntimeError) as e: return f"SAP ABAP Error: {e}" except Exception as e: return f"System Error: {str(e)}" finally: if conn: conn.close()
if __name__ == "__main__": mcp.run()The Dockerfile
Section titled “The Dockerfile”This Dockerfile assumes you have the SAP NWRFC SDK zip file available in your build context. Without the SDK, pyrfc will not compile.
# Use a slim Python baseFROM python:3.11-slim
# Install system dependencies required for SAP SDKRUN apt-get update && apt-get install -y \ gcc \ g++ \ make \ unzip \ && rm -rf /var/lib/apt/lists/*
# Set working directoryWORKDIR /app
# COPY SAP NWRFC SDK (You must download this from SAP Marketplace)# This guide assumes the folder 'nwrfcsdk' is in your build contextCOPY nwrfcsdk /usr/local/sap/nwrfcsdk
# Configure SAP Environment Variables for the SDKENV SAPNWRFC_HOME=/usr/local/sap/nwrfcsdkENV LD_LIBRARY_PATH=$SAPNWRFC_HOME/lib
# Install Python dependencies# pyrfc requires the SDK to be present during installRUN pip install pyrfc fastmcp
# Copy application codeCOPY server.py .
# Ensure your container has network access (e.g. via NordLayer) to reach the SAP Host# This is critical for on-premise SAP ECC instances masked behind VPNs
# Expose the FastMCP portEXPOSE 8000
# Run the MCP serverCMD ["python", "server.py"]Integrating with LangGraph
Section titled “Integrating with LangGraph”To use this in your LangGraph application, you simply connect to the MCP server via SSE (Server-Sent Events) or standard HTTP, depending on your transport preference. The agent will automatically see get_material_details in its tool registry.
When the agent invokes the tool, the Docker container spins up a pyrfc connection, executes the BAPI on port 3300 (standard SAP Gateway), and returns the structured data to the agent’s context window.
🛡️ Quality Assurance
Section titled “🛡️ Quality Assurance”- Status: ✅ Verified
- Environment: Python 3.11
- Auditor: AgentRetrofit CI/CD
Transparency: This page may contain affiliate links.