Skip to content

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.

  1. LangGraph Agent: Manages the workflow state (e.g., “User wants to check stock, then create an order”).
  2. MCP Server: A Dockerized Python service that holds the persistent connection pool to SAP.
  3. SAP ECC: The legacy ERP system receiving RFC calls.

Before running this code, you need:

  1. SAP NetWeaver RFC SDK: Proprietary libraries from the SAP Marketplace (nwrfcsdk).
  2. Python libraries: pyrfc, fastmcp.

This MCP server exposes a tool to fetch material details. We use pyrfc for the actual connectivity.

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

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 base
FROM python:3.11-slim
# Install system dependencies required for SAP SDK
RUN apt-get update && apt-get install -y \
gcc \
g++ \
make \
unzip \
&& rm -rf /var/lib/apt/lists/*
# Set working directory
WORKDIR /app
# COPY SAP NWRFC SDK (You must download this from SAP Marketplace)
# This guide assumes the folder 'nwrfcsdk' is in your build context
COPY nwrfcsdk /usr/local/sap/nwrfcsdk
# Configure SAP Environment Variables for the SDK
ENV SAPNWRFC_HOME=/usr/local/sap/nwrfcsdk
ENV LD_LIBRARY_PATH=$SAPNWRFC_HOME/lib
# Install Python dependencies
# pyrfc requires the SDK to be present during install
RUN pip install pyrfc fastmcp
# Copy application code
COPY 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 port
EXPOSE 8000
# Run the MCP server
CMD ["python", "server.py"]

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.


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

Transparency: This page may contain affiliate links.