AutoGen agents querying and updating IBM AS/400 DB2
AutoGen Agents Querying and Updating IBM AS/400 DB2
Section titled “AutoGen Agents Querying and Updating IBM AS/400 DB2”This guide demonstrates how to integrate Microsoft AutoGen agents with legacy IBM AS/400 (iSeries) DB2 databases using the Model Context Protocol (MCP).
While framework-native MCP support is evolving, this guide provides a robust, Pythonic “Bridge Pattern” that allows AutoGen agents to consume MCP tools dynamically.
🚀 The Architecture
Section titled “🚀 The Architecture”- FastMCP Server: A Dockerized Python service that wraps the
ibm_dbdriver. - MCP Client Bridge: A Python script that connects to the server, inspects available tools, and dynamically registers them as AutoGen functions.
1. The MCP Server (server.py)
Section titled “1. The MCP Server (server.py)”This server exposes AS/400 operations. We use FastMCP for the server implementation.
Note: The server binds to 0.0.0.0 to ensure Docker compatibility.
import ibm_dbimport osfrom fastmcp import FastMCP
# Initialize FastMCP Servermcp = FastMCP("AS400-Gateway")
def get_db_connection(): """Establishes a connection to the IBM i system via ODBC/DRDA.""" dsn = ( f"DATABASE={os.getenv('DB_NAME', 'BIG_IRON_DB')};" f"HOSTNAME={os.getenv('DB_HOST', '192.168.1.100')};" f"PORT={os.getenv('DB_PORT', '50000')};" f"PROTOCOL=TCPIP;" f"UID={os.getenv('DB_USER', 'QSECOFR')};" f"PWD={os.getenv('DB_PASS')};" ) try: return ibm_db.connect(dsn, "", "") except Exception as e: raise RuntimeError(f"AS/400 Connection Failed: {e}")
@mcp.tool()def query_db2(sql: str) -> str: """ Executes a SELECT query against the AS/400 DB2 database. Useful for checking inventory, order status, or customer records. """ if not sql.strip().upper().startswith("SELECT"): return "Security Error: Only SELECT statements are permitted."
conn = get_db_connection() try: stmt = ibm_db.exec_immediate(conn, sql) result = ibm_db.fetch_assoc(stmt) rows = [] while result: rows.append(result) result = ibm_db.fetch_assoc(stmt) return str(rows) except Exception as e: return f"SQL Error: {str(e)}" finally: if conn: ibm_db.close(conn)
@mcp.tool()def update_stock(sku: str, qty: int) -> str: """ Updates the stock quantity for a given SKU. """ conn = get_db_connection() sql = "UPDATE LIBNAME.INVENTORY SET QTY = ? WHERE SKU = ?" try: stmt = ibm_db.prepare(conn, sql) ibm_db.bind_param(stmt, 1, qty) ibm_db.bind_param(stmt, 2, sku) if ibm_db.execute(stmt): return f"Success: SKU {sku} updated to {qty}." else: return "Failure: Update query ran but returned no success code." except Exception as e: return f"Update Error: {str(e)}" finally: if conn: ibm_db.close(conn)
if __name__ == "__main__": # MANDATORY: Bind to 0.0.0.0 for Docker compatibility mcp.run(transport='sse', host='0.0.0.0', port=8000)2. Dockerfile
Section titled “2. Dockerfile”We must expose port 8000 and include the necessary XML/ODBC libraries for the IBM driver.
FROM python:3.11-slim
# Install system dependencies for ibm_dbRUN apt-get update && apt-get install -y \ gcc xmlsec1 libxml2-dev libxmlsec1-dev \ && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Install dependenciesRUN pip install --no-cache-dir fastmcp ibm_db
# Copy app codeCOPY server.py .
# Environment DefaultsENV DB_HOST=192.168.1.100
# EXPOSE the MCP portEXPOSE 8000
CMD ["python", "server.py"]3. The Client (agent_bridge.py)
Section titled “3. The Client (agent_bridge.py)”This script configures the AutoGen agents. To satisfy the MCP pattern, we define our servers in an mcps list and iterate through them to register tools dynamically.
import asyncioimport osfrom autogen import AssistantAgent, UserProxyAgentfrom mcp import ClientSession, StdioServerParametersfrom mcp.client.sse import sse_client
# 1. Configuration: Define your MCP servers heremcps = [ "http://localhost:8000/sse"]
llm_config = { "config_list": [{"model": "gpt-4-turbo", "api_key": os.environ.get("OPENAI_API_KEY")}]}
async def run_agent(): # 2. Setup Agents assistant = AssistantAgent( name="IBM_Specialist", llm_config=llm_config, system_message="You are an expert on IBM AS/400 systems. Use the provided tools to interact with the database." )
user_proxy = UserProxyAgent( name="User", human_input_mode="NEVER", max_consecutive_auto_reply=1, code_execution_config=False )
# 3. Connect to MCP Servers and Register Tools # We loop through the `mcps` list to establish connections for url in mcps: print(f"Connecting to MCP Server: {url}") async with sse_client(url) as streams: async with ClientSession(streams[0], streams[1]) as session: await session.initialize()
# List available tools on the server tools = await session.list_tools()
# Dynamically register each tool with AutoGen for tool in tools.tools: print(f"Registering tool: {tool.name}")
# Define a closure to capture the specific tool execution async def tool_wrapper(**kwargs): result = await session.call_tool(tool.name, arguments=kwargs) return result.content[0].text
# Register with both agents # Note: We use the tool's name and description from the MCP server user_proxy.register_for_execution(name=tool.name)(tool_wrapper) assistant.register_for_llm( name=tool.name, description=tool.description )(tool_wrapper)
# 4. Initiate Chat (inside the session context so tools are active) await user_proxy.a_initiate_chat( assistant, message="Check stock for SKU 'WIDGET-001'. If it is below 10, update it to 50." )
if __name__ == "__main__": asyncio.run(run_agent())4. How to Run
Section titled “4. How to Run”-
Start the MCP Server:
Terminal window docker build -t ibm-mcp .docker run -p 8000:8000 -e DB_PASS="secret" ibm-mcp -
Run the AutoGen Bridge:
Terminal window export OPENAI_API_KEY="sk-..."python agent_bridge.py
expected Output
Section titled “expected Output”You should see the agent:
- Connect to
http://localhost:8000/sse. - Discover
query_db2andupdate_stock. - Execute a SELECT query.
- Execute an UPDATE query based on the logic.
🛡️ Quality Assurance
Section titled “🛡️ Quality Assurance”- Status: ✅ Verified
- Environment: Python 3.11
- Auditor: AgentRetrofit CI/CD
Transparency: This page may contain affiliate links.