Skip to content

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.

  1. FastMCP Server: A Dockerized Python service that wraps the ibm_db driver.
  2. MCP Client Bridge: A Python script that connects to the server, inspects available tools, and dynamically registers them as AutoGen functions.

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_db
import os
from fastmcp import FastMCP
# Initialize FastMCP Server
mcp = 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)

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_db
RUN apt-get update && apt-get install -y \
gcc xmlsec1 libxml2-dev libxmlsec1-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Install dependencies
RUN pip install --no-cache-dir fastmcp ibm_db
# Copy app code
COPY server.py .
# Environment Defaults
ENV DB_HOST=192.168.1.100
# EXPOSE the MCP port
EXPOSE 8000
CMD ["python", "server.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 asyncio
import os
from autogen import AssistantAgent, UserProxyAgent
from mcp import ClientSession, StdioServerParameters
from mcp.client.sse import sse_client
# 1. Configuration: Define your MCP servers here
mcps = [
"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())

  1. Start the MCP Server:

    Terminal window
    docker build -t ibm-mcp .
    docker run -p 8000:8000 -e DB_PASS="secret" ibm-mcp
  2. Run the AutoGen Bridge:

    Terminal window
    export OPENAI_API_KEY="sk-..."
    python agent_bridge.py

You should see the agent:

  1. Connect to http://localhost:8000/sse.
  2. Discover query_db2 and update_stock.
  3. Execute a SELECT query.
  4. Execute an UPDATE query based on the logic.

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

Transparency: This page may contain affiliate links.