Back to Insights Hub

Connecting Legacy Systems & Internal Databases to Claude via Model Context Protocol

An architectural blueprint for engineering leaders: how to expose 10-to-20-year-old relational databases (SQL Server, Oracle, MySQL) and internal REST/SOAP APIs to Claude Desktop and Cursor using secure, read-only MCP gateways without rewriting your backend.

EXECUTIVE SUMMARY // DIRECT DEFINITION

To connect legacy systems and internal tools to Claude or Cursor via Model Context Protocol (MCP), organizations deploy a containerized MCP Gateway Microservice. Rather than modifying legacy codebases, this gateway acts as an adapter layer that translates LLM JSON-RPC tool calls into existing stored procedures, SQL queries, or REST endpoints. Security is enforced through SQL AST query parsing (rejecting DDL/DML mutations), strict statement timeouts, and dynamic PII redaction, enabling non-technical executives and developers to query core databases with zero data leakage.

The Enterprise Modernization Dilemma

Most enterprise organizations have 10 to 20 years of accumulated business logic residing inside Microsoft SQL Server, Oracle, legacy SAP/ERP setups, and bespoke internal portals. Rewriting these systems for AI is a multi-million-dollar non-starter. Model Context Protocol allows engineering teams to wrap legacy assets into an intelligent tool abstraction layer in weeks rather than quarters.

1. Why Traditional REST & SQL Approaches Fail with AI Agents

When engineering executives attempt to connect generative AI models directly to legacy backends using traditional API plugins or raw database connections, three critical failure modes emerge immediately:

Failure Mode 1: Context Window Saturation & Schema Bloat

Legacy enterprise databases often contain hundreds of denormalized tables with cryptic column abbreviations (e.g., VNDR_INVC_STUS_CD). Feeding raw database schemas into LLM context windows consumes thousands of expensive tokens and causes the model to guess hallucinated relationships.

Failure Mode 2: Unchecked DML Write Mutations on Production

Granting an LLM direct database credentials is an existential hazard. Even when instructed to be "read-only" via system prompts, stochastic token drift or prompt injections can induce the model to emit UPDATE, DELETE, or recursive table-locking subqueries that crash core production ledgers.

Failure Mode 3: Authentication & VPC Impedance Mismatch

Desktop AI clients (Claude Desktop, Cursor IDE) run on individual employee workstations, while legacy databases sit behind isolated corporate VPCs, Kerberos domains, or hardware firewalls. Opening public database ports is a severe compliance violation.

ENTERPRISE LEGACY INTEGRATION

Need to Connect Your Legacy Systems to Claude Desktop?

I architect custom, containerized Model Context Protocol (MCP) servers that safely expose internal databases and private tools with 100% client code ownership. Review our custom MCP server development services.

Explore MCP Services

2. The MCP Adapter Pattern: How the Gateway Works

The solution is the MCP Adapter Pattern: an isolated microservice that sits between modern AI clients and legacy enterprise infrastructure.

The microservice speaks the open Model Context Protocol (SSE transport) to client applications while connecting to legacy databases over local private subnets with strict least-privilege credentials.

High-Level Architecture Pipeline:

ACTIVE PRODUCTION GATEWAY // LEGACY ADAPTER TOPOLOGY
FAST-MCP · SSE GATEWAY · SQLGLOT AST GUARDRAILS

Client Tier: Claude Desktop / Cursor IDE

Employee or executive submits natural-language questions (e.g., "Summarize unpaid vendor invoices over $50k from Q3").

CLIENT TIERDesktop UI
Encrypted SSE + Bearer JWT Authentication (TLS 1.3)

Security Gateway: FastMCP Container on AWS ECS

Authenticates client sessions, validates Bearer tokens, and unpacks JSON-RPC 2.0 tool invocation requests.

GATEWAY NODEReverse Proxy
Abstract Syntax Tree (AST) Inspection via sqlglot

Security Guardrail: SQL AST Validator & Limiter

Inspects syntax tree to guarantee zero INSERT/UPDATE/DELETE/DROP nodes. Enforces LIMIT 100 and statement_timeout = 2500ms.

SECURITY NODEStrict Read-Only
VALIDATED QUERY // LOCAL VPCEXECUTION

Legacy Database / ERP Backend

Executes against Microsoft SQL Server, Oracle, or MySQL read-replicas over local VPC peering. Results returned to adapter buffer.

SANITIZATION LAYER // OUTBOUNDGOVERNANCE

Dynamic PII Redaction Engine

Scans tabular output records using regex to mask customer emails, phone numbers, and SSNs before returning JSON to Claude.

Zero sensitive customer data leaks into LLM context

3. Code Walkthrough: Production FastMCP Gateway Implementation

Below is the production architecture for an enterprise legacy database adapter built using FastMCP in Python. It implements strict SQL AST parsing, timeout limits, and automated PII redaction:

python · gateway/legacy_adapter.py
Production FastMCP Gateway
"""
Production MCP Legacy System Adapter Gateway
Exposes legacy relational databases (SQL Server, Oracle, MySQL) and internal REST APIs
to Claude Desktop and Cursor IDE using FastMCP with AST guardrails and dynamic PII redaction.
"""
import os
import sys
import re
import logging
from typing import Dict, Any, List, Optional
from pydantic import BaseModel, Field
from mcp.server.fastmcp import FastMCP
import sqlglot
from sqlglot import exp

# Configure dedicated stderr logger (never pollute stdout in stdio mode)
logging.basicConfig(stream=sys.stderr, level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger("legacy_mcp_gateway")

# Initialize FastMCP Server
mcp = FastMCP(
    name="enterprise-legacy-gateway",
    instructions="Secure enterprise gateway exposing read-only legacy ERP/CRM database analytics."
)

# 1. PII Redaction Regex Patterns
PII_PATTERNS = {
    "EMAIL": re.compile(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+"),
    "PHONE": re.compile(r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b"),
    "SSN_TIN": re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
}

def redact_sensitive_pii(text: str) -> str:
    """Redacts proprietary customer PII before sending tool results to Claude."""
    redacted = text
    for pii_type, pattern in PII_PATTERNS.items():
        redacted = pattern.sub(f"[REDACTED_{pii_type}]", redacted)
    return redacted

# 2. Strict AST Read-Only Query Validator
FORBIDDEN_EXPRESSIONS = (exp.Insert, exp.Update, exp.Delete, exp.Drop, exp.Alter, exp.Create)

def validate_legacy_sql(sql_query: str) -> str:
    """
    Parses SQL syntax trees using sqlglot to guarantee 100% read-only operations.
    Rejects mutations and forces safe execution limits.
    """
    try:
        parsed = sqlglot.parse_one(sql_query, read="tsql") # Supports T-SQL / Oracle dialects
    except Exception as exc:
        raise ValueError(f"Malformed SQL syntax: {exc}")

    # Inspect AST nodes for write or schema mutations
    if any(parsed.find_all(FORBIDDEN_EXPRESSIONS)):
        raise PermissionError("Security Exception: Only read-only SELECT queries are authorized on legacy backends.")

    # Enforce safe upper ceiling on returned rows (prevent context window exhaustion)
    if not parsed.args.get("limit"):
        parsed = parsed.limit(100)

    return parsed.sql(dialect="tsql")

# 3. Typed Tool Input Contracts
class LegacyQueryInput(BaseModel):
    query: str = Field(..., description="Read-only SELECT query against legacy ERP reporting views.")
    purpose: str = Field(..., description="Business intent for audit logging (e.g., 'Q3 ledger reconciliation').")

@mcp.tool()
async def query_legacy_ledger(params: LegacyQueryInput) -> Dict[str, Any]:
    """
    Executes a sanitized read-only query against the legacy corporate database.
    Applies AST inspection, statement execution timeouts, and PII masking.
    """
    logger.info(f"Audit Log: Executing query for purpose: {params.purpose}")
    
    # 1. Validate & sanitize SQL statement
    sanitized_sql = validate_legacy_sql(params.query)
    
    # 2. Execute via pooled read-only database connection with strict 2500ms timeout
    # (Mocked driver execution for architectural reference)
    raw_results = await execute_legacy_db_with_timeout(
        query=sanitized_sql,
        statement_timeout_ms=2500
    )
    
    # 3. Redact any PII before serializing output
    clean_records = [
        {k: redact_sensitive_pii(str(v)) for k, v in row.items()}
        for row in raw_results
    ]
    
    return {
        "status": "success",
        "returned_rows": len(clean_records),
        "data": clean_records
    }

if __name__ == "__main__":
    # Run over SSE transport in VPC or stdio in local desktop sandbox
    mcp.run(transport="sse")

4. The Four Pillars of Enterprise Legacy Security

Exposing enterprise data to LLMs requires multiple overlapping defensive layers. The architecture is hardened with four core controls:

1. Abstract Syntax Tree (AST) Enforcement

Regex-based SQL filtering is easily bypassed by comments or encoded quotes. By parsing queries into an Abstract Syntax Tree via sqlglot, the gateway inspects the grammatical intent of the query and rejects any mutation command before it touches the database driver.

2. Dedicated Read-Only Database Roles & Replication

The MCP gateway never connects to production primary instances. It connects exclusively to read-replicas using a dedicated database role configured with CONNECT and SELECT grants only.

3. Hard Query Timeout Limits (2500ms)

To prevent an LLM from accidentally generating a cartesian product join that exhausts server CPU or locks shared buffer pools, the gateway forces SET statement_timeout = 2500 on every connection checkout.

4. Dynamic PII Redaction Layer

Sensitive fields (customer phone numbers, credit card tokens, personal emails) are automatically redacted in the gateway's serialization layer before the JSON-RPC response is framed, ensuring proprietary PII never leaves corporate boundaries.

5. Enterprise MCP Implementation Roadmap

For engineering leaders planning an internal rollout, we recommend a disciplined 4-week architectural sprint:

PHASE 1 (WEEK 1)

Schema Audit & Tool Surface Design

Audit legacy database catalogs. Identify high-value business reporting views. Write declarative Pydantic schemas defining exactly what tools and parameters will be exposed to Claude.

PHASE 2 (WEEK 2)

FastMCP Gateway Scaffolding

Implement the containerized FastMCP server using async connection pools. Integrate sqlglot AST validation guardrails and the PII redaction layer.

PHASE 3 (WEEK 3)

VPC Staging & Security Pen-Testing

Deploy gateway into private AWS/GCP subnets. Conduct automated adversarial testing attempting SQL injection, DDL mutation bypasses, and context window flooding.

PHASE 4 (WEEK 4)

Client Rollout & OpenTelemetry Tracing

Distribute pre-configured Claude Desktop configuration files with Bearer token authentication. Enable OpenTelemetry distributed tracing to monitor query latencies in production.

6. Real-World Case Study Reference

To see this exact architecture deployed in production, explore our verified Enterprise PostgreSQL MCP Server Case Study. Learn how a custom FastMCP server connected production read-replicas directly to Claude Desktop with JWT authentication and AST validation, eliminating 84% of ad-hoc reporting tickets to core engineering.

For transport protocol selection criteria, review our comprehensive deep dive: Model Context Protocol: stdio vs. SSE Transports in Production.

ENTERPRISE MCP SPRINT

Need to Safely Connect Your Legacy Databases to Claude?

Eliminate ad-hoc SQL reporting bottlenecks without rewriting your stack. Book an Enterprise MCP Architecture Audit with Awais Ansari. We will evaluate your schema boundaries, security constraints, and adapter design.

Book Architecture Audit

Summary & Implementation Takeaways

Legacy enterprise systems do not need to be rebuilt from scratch to participate in the AI era. By adopting the MCP adapter pattern with strict AST validation and statement timeouts, engineering organizations can unlock decades of accumulated business data for natural-language analysis while maintaining total operational security.

Start a Technical Conversation

Ready to Connect Your Legacy Systems to Claude?

Book an architecture scoping session directly with Awais Ansari. We will evaluate your schema boundaries, security constraints, and map out a 3-week MCP delivery sprint.

100% Client Code & IP Ownership
Zero-Data-Retention & NDA Compliant
Direct Principal Engineer Consultation