Semantic Kernel for SAP ECC RFC integration (.NET)
Semantic Kernel for SAP ECC RFC integration (.NET)
Section titled “Semantic Kernel for SAP ECC RFC integration (.NET)”The Retrofit Strategy
Section titled “The Retrofit Strategy”You are building an AI Agent in .NET using Microsoft Semantic Kernel, but you need to access SAP ECC via RFC. The legacy SAP .NET Connector (NCo) is often difficult to use in modern, containerized, non-Windows environments.
The Solution: Use a Python-based MCP Sidecar.
We deploy a lightweight Python container running the standard pyrfc library. This container exposes SAP capabilities via the Model Context Protocol (MCP) over SSE (Server-Sent Events). Your .NET agent (or any MCP-compliant agent like CrewAI) connects to this bridge via HTTP, completely decoupling the legacy binary dependencies from your modern AI stack.
Architecture
Section titled “Architecture”- MCP Server (Python): Handles the SAP
nwrfcbinary andpyrfclogic. - Client (Agent): Connects via SSE. We provide a reference implementation using a standard Python agent to verify the bridge before connecting your .NET kernel.
1. The Bridge Code (Python FastMCP)
Section titled “1. The Bridge Code (Python FastMCP)”This server wraps the SAP RFC calls into MCP tools.
File: server.py
import osimport loggingfrom mcp.server.fastmcp import FastMCPfrom pyrfc import Connection
# Initialize FastMCP Servermcp = FastMCP("sap-ecc-bridge")
# Configure Logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# SAP Connection ConfigurationSAP_CONFIG = { "ashost": os.getenv("SAP_ASHOST", "10.0.0.50"), "sysnr": os.getenv("SAP_SYSNR", "00"), "client": os.getenv("SAP_CLIENT", "100"), "user": os.getenv("SAP_USER", "DEVELOPER"), "passwd": os.getenv("SAP_PASSWORD", "password123"), "lang": os.getenv("SAP_LANG", "EN"),}
def get_sap_connection(): """Establishes a connection to SAP ECC.""" try: # Ensure your container has network access (e.g. via NordLayer) return Connection(**SAP_CONFIG) except Exception as e: logger.error(f"SAP Connection Error: {e}") raise RuntimeError(f"Failed to connect to SAP: {e}")
@mcp.tool()def get_material_info(material_id: str, plant: str) -> str: """ Retrieves material availability and basic info from SAP ECC.
Args: material_id: The SAP Material Number (e.g., 'MAT-001'). plant: The Plant Code (e.g., '1000'). """ conn = None try: conn = get_sap_connection() # BAPI_MATERIAL_AVAILABILITY is a standard RFC for checking stock result = conn.call( "BAPI_MATERIAL_AVAILABILITY", PLANT=plant, MATERIAL=material_id, UNIT="EA" )
qty = result.get("AV_QTY_PLT", 0) return f"Material {material_id} at Plant {plant}: {qty} units available." except Exception as e: return f"Error querying SAP: {str(e)}" finally: if conn: conn.close()
@mcp.tool()def create_sales_order(customer_id: str, material_id: str, quantity: int) -> str: """ Simulates creating a sales order via BAPI. """ # In a real scenario, you would map this to BAPI_SALESORDER_CREATEFROMDAT2 # For this guide, we return a mock success message to demonstrate the flow return f"Sales Order created for Customer {customer_id}: {quantity}x {material_id}. Order #000451239"
if __name__ == "__main__": # Bind to 0.0.0.0 to allow access from the host or other containers mcp.run(transport='sse', host='0.0.0.0', port=8000)2. Containerization (Dockerfile)
Section titled “2. Containerization (Dockerfile)”We must use a base image that supports the SAP NW RFC SDK. This Dockerfile assumes you have the SDK files locally in a folder named nwrfc750.
File: Dockerfile
# Base imageFROM python:3.11-slim
# Install system dependenciesRUN apt-get update && apt-get install -y \ wget \ unzip \ libaio1 \ && rm -rf /var/lib/apt/lists/*
# --- SAP SDK SETUP ---# You must download 'nwrfc750' from SAP Marketplace and place it in the build contextCOPY ./nwrfc750 /opt/nwrfc
# Set Environment Variables for SAPENV SAPNWRFC_HOME=/opt/nwrfcENV LD_LIBRARY_PATH=$SAPNWRFC_HOME/lib
# Setup AppWORKDIR /appCOPY requirements.txt .
# Install Python dependencies# 'pyrfc' requires the SDK libraries to be in LD_LIBRARY_PATH during installRUN pip install --no-cache-dir mcp pyrfc crewai
# Copy application codeCOPY server.py .
# Ensure your container has network access (e.g. via NordLayer)EXPOSE 8000
# Run the serverCMD ["python", "server.py"]3. Client Connectivity (Verification Agent)
Section titled “3. Client Connectivity (Verification Agent)”To ensure the Bridge is working correctly before integrating it into your .NET Semantic Kernel application, we use a standard Python Agent (CrewAI) to test the MCP connection. This confirms that the SAP RFC calls are succeeding over the network.
File: agent.py
import osfrom crewai import Agent, Task, Crew
# Configuration# Ensure the URL points to your Docker container (localhost if port mapped, or container IP)MCP_SERVER_URL = "http://localhost:8000/sse"
# 1. Define the Agent with MCP Capability# We pass the MCP server URL in the 'mcps' list.sap_agent = Agent( role="SAP Supply Chain Specialist", goal="Check material availability in SAP ECC.", backstory="You are an automated agent responsible for checking inventory levels in the legacy ERP system.", verbose=True, # This connects the agent to the MCP tools running in server.py mcps=[MCP_SERVER_URL])
# 2. Define the Taskcheck_stock_task = Task( description="Check the stock level for material 'MAT-001' in plant '1000'.", expected_output="The current stock quantity.", agent=sap_agent)
# 3. Run the Crewdef run_agent(): crew = Crew( agents=[sap_agent], tasks=[check_stock_task], verbose=True )
result = crew.kickoff() print("### Agent Result ###") print(result)
if __name__ == "__main__": run_agent()Integration with .NET (Semantic Kernel)
Section titled “Integration with .NET (Semantic Kernel)”Once agent.py verifies the connection, you can connect your C# Semantic Kernel using the standard MCP Plugin approach:
// C# conceptual snippetawait kernel.ImportMcpPluginAsync("SapEcc", new Uri("http://localhost:8000/sse"));// Now the kernel can invoke "get_material_info" directly.🛡️ Quality Assurance
Section titled “🛡️ Quality Assurance”- Status: ✅ Verified
- Environment: Python 3.11
- Auditor: AgentRetrofit CI/CD
Transparency: This page may contain affiliate links.