Skip to content

KazKozDev/sap_r3_integration_tool

Repository files navigation

SAP R/3 Integration Tool for Universal LLM Agents

Python Version License Code Style Coverage

Extract data from legacy SAP R/3 systems and convert it into modern REST APIs for AI agent consumption. This tool bridges the gap between enterprise SAP systems and modern AI applications.

Features

  • Universal Tool Interface: Implements the Universal LLM Agent Tool standard
  • SAP Data Extraction: Extract orders, customers, materials, warehouses, and inventory
  • RFC Connectivity: Direct connection to SAP using Remote Function Calls
  • Data Transformation: Automatic conversion from SAP format to JSON
  • Multi-Framework Support: Works with LangChain, CrewAI, AutoGen, MCP, and more
  • Caching: Built-in caching for improved performance
  • Async Support: Handle large data extractions asynchronously
  • Security: Secure credential handling and data encryption

Requirements

  • Python 3.9+
  • SAP R/3 system (4.6C or higher)
  • SAP RFC SDK (SAP NetWeaver RFC SDK)
  • Valid SAP user credentials with appropriate permissions

Installation

1. Install SAP RFC SDK

First, download and install the SAP NetWeaver RFC SDK from the SAP Service Marketplace.

# Set environment variables
export SAPNWRFC_HOME=/path/to/sap/nwrfcsdk
export LD_LIBRARY_PATH=$SAPNWRFC_HOME/lib:$LD_LIBRARY_PATH

2. Install the Tool

pip install sap-r3-integration-tool

Or install from source:

git clone https://github.com/KazKozDev/sap_r3_integration_tool.git
cd sap_r3_integration_tool
pip install -e .

Quick Start

Basic Usage

from sap_r3_integration import SAPR3IntegrationTool, ToolConfig

# Configure the tool
config = ToolConfig(
    sap_config={
        "ashost": "sap.example.com",
        "sysnr": "00",
        "client": "100",
        "user": "SAP_USER",
        "passwd": "SAP_PASSWORD"
    }
)

# Create tool instance
tool = SAPR3IntegrationTool(config)

# Extract customer data
result = tool.execute({
    "data_type": "customers",
    "filters": {"LAND1": "US"},
    "limit": 100
})

print(f"Extracted {result['metadata']['count']} customers")

With LangChain

from langchain.agents import initialize_agent, AgentType
from langchain.llms import OpenAI

# Convert to LangChain tool
langchain_tool = tool.to_langchain()

# Create agent
llm = OpenAI(temperature=0)
agent = initialize_agent(
    [langchain_tool],
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION
)

# Use the tool
response = agent.run("Get all customers from Germany")

With MCP Server

# Convert to MCP format
mcp_tool = tool.to_mcp_server()

# Register with MCP server
mcp_server.register_tool(mcp_tool)

Supported Data Types

Data Type Description SAP Tables
orders Sales orders with items VBAK, VBAP
customers Customer master data KNA1
materials Material master data MARA, MAKT
warehouses Storage locations T001L
inventory Current stock levels MARD

Advanced Usage

Filtering Data

# Date range filter
orders = tool.execute({
    "data_type": "orders",
    "filters": {
        "ERDAT": {
            "from": "20250101",
            "to": "20250131"
        }
    }
})

# Multiple filters
inventory = tool.execute({
    "data_type": "inventory",
    "filters": {
        "WERKS": "1000",  # Plant
        "LGORT": "0001"   # Storage location
    }
})

Async Execution

import asyncio

async def extract_large_dataset():
    result = await tool.execute_async({
        "data_type": "orders",
        "limit": 10000
    })
    return result

# Run async extraction
data = asyncio.run(extract_large_dataset())

Custom Field Selection

# Extract specific fields only
customers = tool.execute({
    "data_type": "customers",
    "fields": ["KUNNR", "NAME1", "LAND1"],
    "limit": 50
})

Security

Credential Management

Never hardcode credentials. Use environment variables or secure vaults:

import os
from sap_r3_integration import SAPR3IntegrationTool, ToolConfig

config = ToolConfig(
    sap_config={
        "ashost": os.getenv("SAP_HOST"),
        "client": os.getenv("SAP_CLIENT"),
        "user": os.getenv("SAP_USER"),
        "passwd": os.getenv("SAP_PASSWORD")
    }
)

Required SAP Permissions

The SAP user needs the following authorizations:

  • S_RFC: RFC access
  • S_TABU_DIS: Table display authorization
  • Access to specific tables (VBAK, KNA1, etc.)

Architecture

┌─────────────────┐     ┌──────────────┐     ┌─────────────┐
│   AI Agent      │────▶│  Tool Layer  │────▶│  SAP R/3    │
│  (LangChain,    │     │              │     │             │
│   CrewAI, etc)  │     │  - Validate  │     │ - RFC Call  │
└─────────────────┘     │  - Transform │     │ - Tables    │
                        │  - Cache     │     └─────────────┘
                        └──────────────┘

Performance Optimization

Caching

Configure caching for frequently accessed data:

from sap_r3_integration import ToolConfig, CacheConfig

config = ToolConfig(
    cache_config=CacheConfig(
        backend="redis",
        ttl=3600,  # 1 hour
        max_size=1000
    )
)

Connection Pooling

The tool automatically manages connection pooling to optimize performance.

Testing

Run the test suite:

# Run all tests
pytest

# Run with coverage
pytest --cov=sap_r3_integration --cov-report=html

# Run specific test category
pytest tests/test_extraction.py

Troubleshooting

Common Issues

  1. RFC Connection Failed

    Error: RFC_COMMUNICATION_FAILURE
    Solution: Check network connectivity and SAP system availability
    
  2. Authorization Error

    Error: RFC_AUTHORIZATION_FAILURE
    Solution: Verify user permissions in SAP (transaction SU01)
    
  3. Data Extraction Timeout

    Solution: Reduce limit or use async execution
    

Debug Mode

Enable detailed logging:

import logging

logging.basicConfig(level=logging.DEBUG)

API Reference

Tool Configuration

class ToolConfig:
    environment: str = "prod"
    timeout: int = 30
    retries: int = 3
    cache_config: CacheConfig
    sap_config: Dict[str, Any]

Execution Parameters

{
    "data_type": str,      # Required: Type of data to extract
    "filters": dict,       # Optional: Filter criteria
    "limit": int,          # Optional: Max records (default: 100)
    "fields": List[str]    # Optional: Specific fields to extract
}

Response Format

{
    "success": bool,
    "data": List[Dict],
    "metadata": {
        "count": int,
        "extraction_time": str,
        "data_type": str,
        "execution_time": float
    },
    "error": {             # Only if success=false
        "code": str,
        "message": str
    }
}

Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License.

Acknowledgments

  • SAP NetWeaver RFC SDK team
  • PyRFC maintainers

Support

For support, please contact:

Roadmap

  • Support for SAP S/4HANA
  • Real-time change data capture
  • GraphQL API endpoint
  • Built-in data validation rules
  • Support for custom ABAP functions

Created and maintained by KazKozDev

About

SAP R/3 Integration Tool with RFC support and asynchronous operations.

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Releases

No releases published

Languages