loading…
Search for a command to run...
loading…
A production-grade MCP server that automates financial compliance audits by combining LLMs with structured analysis, enabling policy validation, risk profiling,
A production-grade MCP server that automates financial compliance audits by combining LLMs with structured analysis, enabling policy validation, risk profiling, and automated reporting.
MCP Protocol FastMCP Python License
AI-Native Compliance Infrastructure — A production-grade MCP server that combines Large Language Models with structured financial analysis to automate enterprise compliance workflows.
This project implements a modular compliance audit system built on the Model Context Protocol (MCP). It enables AI agents to perform sophisticated financial compliance analysis through a standardized tool interface.
Enterprise finance teams need to audit thousands of transactions across multiple vendors, checking for:
This system automates that analysis pipeline end-to-end.
┌─────────────────────────────────────────────────────────────────────────────┐
│ ORCHESTRATION LAYER │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Host Client (host.py) │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐ │ │
│ │ │ Rate Limiter│ │ RBAC Engine │ │ Audit Logger │ │ │
│ │ │ (1 req/sec) │ │(Role-based) │ │ (RotatingFileHandler) │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────────────────┘ │ │
│ │ ┌─────────────────────────────────────────────────────────────┐ │ │
│ │ │ Groq LLM Integration (llama-3.3-70b) │ │ │
│ │ │ • Tool Selection • Argument Generation │ │ │
│ │ └─────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
│
│ HTTP/MCP Protocol
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ MCP SERVER LAYER │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ FastMCP Server (server.py) │ │
│ │ Port: 8000 │ │
│ │ ┌─────────────────────────────────────────────────────────────┐ │ │
│ │ │ TOOLS (5) │ │ │
│ │ │ ┌─────────────────┐ ┌─────────────────┐ ┌────────────────┐ │ │ │
│ │ │ │validate_policy │ │flag_high_value │ │get_vendor_risk │ │ │ │
│ │ │ │ _tools() │ │ _transactions()│ │ _profile() │ │ │ │
│ │ │ └─────────────────┘ └─────────────────┘ └────────────────┘ │ │ │
│ │ │ ┌─────────────────┐ ┌─────────────────┐ │ │ │
│ │ │ │enrich_transaction│ │generate_audit_ │ │ │ │
│ │ │ │ _context() │ │ _report() │ │ │ │
│ │ │ └─────────────────┘ └─────────────────┘ │ │ │
│ │ └─────────────────────────────────────────────────────────────┘ │ │
│ │ ┌─────────────────────────────────────────────────────────────┐ │ │
│ │ │ RESOURCES (1) │ │ │
│ │ │ db://schema (Database Introspection) │ │ │
│ │ └─────────────────────────────────────────────────────────────┘ │ │
│ │ ┌─────────────────────────────────────────────────────────────┐ │ │
│ │ │ PROMPTS (1) │ │ │
│ │ │ compliance_audit_prompt (System Template) │ │ │
│ │ └─────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
│
│ SQL/JSON/Filesystem
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ DATA LAYER │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌─────────────────┐ │
│ │ SQLite │ │ Static JSON │ │ Log Files │ │ Generated │ │
│ │ (audit.db) │ │ (risk_db.json)│ │(JSONL format)│ │ Reports │ │
│ │ │ │ │ │ │ │ (PDF/PNG) │ │
│ │ • transactions│ │ • vendor_risk│ │ • audit_trace│ │ │ │
│ │ • audit_hist │ │ _scores │ │ │ │ │ │
│ │ • vendor_risk│ │ │ │ │ │ │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
│
│ HTTP
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ VISUALIZATION LAYER │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ FastAPI Dashboard (dashboard.py) │ │
│ │ Port: 8000 (shared) │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ JWT Auth │ │ Plotly Charts │ │ KPI Metrics │ │ │
│ │ │ (Bearer Token) │ │ (Interactive) │ │ (Real-time) │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ │ ┌──────────────────────────────────────────────────────────────┐ │ │
│ │ │ Security Middleware: Rate Limiting, HSTS, X-Frame-Options │ │ │
│ │ └──────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
MCP-Server/
├── server.py # MCP server entry point (73 lines)
├── host.py # LLM orchestrator with audit loop
├── dashboard.py # FastAPI web dashboard with security
├── db/
│ ├── __init__.py
│ └── connection.py # SQLite with WAL mode, connection pooling
├── models/ # Pydantic schemas for validation
├── prompts/
│ └── compliance_audit.py # MCP prompt templates
├── resources/
│ └── schema.py # db://schema resource implementation
├── tools/ # Modular MCP tools
│ ├── __init__.py
│ ├── validation_tools.py # Policy validation, high-value flagging
│ ├── enrichment.py # Vendor risk enrichment
│ └── reporting.py # PDF report generation
├── utils/ # Utility functions
├── templates/
│ └── dashboard.html # Jinja2 dashboard template
├── requirements.txt
├── Dockerfile
└── .gitignore # Properly excludes .env, *.db, etc.
# Validates against:
- Blacklisted vendors (configurable set)
- Category spending limits (Legal: $25K, IT: $40K, Travel: $20K)
- Pending transaction aggregation ($50K threshold)
The host client uses Groq's Llama 3.3 70B model to:
# Z-score based anomaly detection
if z_score > 2.0:
flag_statistical_anomaly()
perform_root_cause_analysis()
Raw Finding → Vendor Lookup → Risk Score Calculation → Enriched Output
│ │ │ │
▼ ▼ ▼ ▼
Transaction risk_db.json Weighted Algorithm Final Report
validate_transaction_policiesValidates transactions against enterprise policies.
Input: None (queries all transactions)
Output:
[
{
"severity": "HIGH",
"issue": "Blacklisted Vendor",
"vendor": "Fraudulent Corp",
"category": "IT",
"amount": 50000.00
}
]
flag_high_value_transactionsFlags transactions exceeding monetary threshold.
Input:
{
"min_amount": 10000.0
}
Output:
[
{
"vendor": "LegalEdge LLP",
"amount": 25000.00,
"category": "Legal"
}
]
get_vendor_risk_profileRetrieves historical transaction statistics for a vendor.
Input:
{
"vendor_name": "OfficeSupply Co"
}
Output:
{
"vendor": "OfficeSupply Co",
"transaction_count": 45,
"total_spend": 125000.00,
"avg_transaction": 2777.78,
"max_transaction": 15000.00
}
enrich_transaction_contextAdds external risk context to vendor data.
Input:
{
"vendor_name": "OfficeSupply Co"
}
Output:
{
"vendor": "OfficeSupply Co",
"past_issues": true,
"conflict_of_interest": true,
"regulatory_flag": false,
"risk_score": 82
}
generate_audit_markdown_reportGenerates comprehensive compliance report.
Input:
{
"findings": [...],
"flow_id": "AUDIT_a1b2c3d4",
"user_id": "auditor_01",
"role": "partner"
}
Output: Markdown string with embedded KPIs and chart references
db://schemaReturns database schema for introspection.
Output:
{
"transactions": [
{"column": "vendor", "type": "TEXT"},
{"column": "amount", "type": "REAL"},
{"column": "category", "type": "TEXT"},
{"column": "status", "type": "TEXT"}
]
}
compliance_audit_promptSystem prompt for LLM-based compliance analysis.
Content:
You are a Senior Financial Compliance Analyst.
- Group findings by severity.
- Provide recommended actions for HIGH severity.
- Maintain professional tone.
- Use only supplied data.
# Clone repository
git clone https://github.com/nikhil-sharma-dotcom/MCP-Server.git
cd MCP-Server
# Install dependencies
pip install -r requirements.txt
# Set environment variables
export GROQ_API_KEY="your_groq_api_key"
export SECRET_KEY="your_jwt_secret_key"
export PORT=8000
export ENVIRONMENT=development # or 'production' for HTTPS enforcement
# Terminal 1: Start MCP Server
python server.py
# Terminal 2: Start Dashboard
uvicorn dashboard:app --host 0.0.0.0 --port 8000
# Terminal 3: Run Audit Workflow
python host.py
MCP ready.
--- Enriched Audit Report ---
[LLM-generated compliance analysis]
--- Final Audit Markdown Report ---
# Enterprise Financial Compliance Report
## Executive KPIs
- **Total Risk Exposure:** $1,250,000.00
- **Total Findings:** 15
...
# Build image
docker build -t mcp-audit-server .
# Run container
docker run -p 8000:8000 \
-e GROQ_API_KEY="your_key" \
-e SECRET_KEY="your_secret" \
-e PORT=8000 \
-e ENVIRONMENT=production \
mcp-audit-server
# docker-compose.yml
version: '3.8'
services:
mcp-server:
build: .
ports:
- "8000:8000"
environment:
- GROQ_API_KEY=${GROQ_API_KEY}
- SECRET_KEY=${SECRET_KEY}
- PORT=8000
- ENVIRONMENT=production
volumes:
- ./data:/app/data
# ECR Push
docker build -t mcp-audit-server .
docker tag mcp-audit-server:latest $AWS_ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/mcp-audit-server:latest
docker push $AWS_ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/mcp-audit-server:latest
# ECS/Fargate Deployment
# Use AWS Console or Terraform for production deployment
# List available tools
curl http://localhost:8000/mcp/tools
# Call a tool
curl -X POST http://localhost:8000/mcp/tools/flag_high_value_transactions \
-H "Content-Type: application/json" \
-d '{"min_amount": 10000}'
# Health check
curl http://localhost:8000/health
# Get audit history (with JWT)
curl http://localhost:8000/secure-history \
-H "Authorization: Bearer <token>"
# View dashboard
curl http://localhost:8000/ \
-H "Authorization: Bearer <token>"
from fastmcp import Client
import asyncio
async def audit_client():
async with Client("http://localhost:8000/mcp") as session:
# List tools
tools = await session.list_tools()
print(f"Available tools: {[t.name for t in tools]}")
# Call tool
result = await session.call_tool(
"flag_high_value_transactions",
{"min_amount": 5000}
)
print(result)
asyncio.run(audit_client())
| Feature | Implementation |
|---|---|
| Authentication | JWT with role-based claims |
| Rate Limiting | slowapi (60/min default, 20/min sensitive) |
| HTTPS | Automatic redirect in production |
| Security Headers | HSTS, X-Frame-Options, X-Content-Type-Options, X-XSS-Protection |
| Secrets Management | Environment variables only |
| Logging | RotatingFileHandler with 5MB rotation |
# Required
export GROQ_API_KEY="your_groq_api_key"
export SECRET_KEY="your_jwt_secret_min_32_chars"
# Optional
export PORT=8000 # Server port
export ENVIRONMENT=development # or 'production'
export DB_PATH="audit.db" # Database path
"I took a 665-line monolithic MCP server and refactored it into a modular architecture with:
- 73-line clean entry point
- Proper package separation (tools/, db/, models/)
- Environment-based configuration
- Comprehensive security middleware
- Professional logging with rotation"
This demonstrates technical debt management and continuous improvement — key senior-engineer traits.
# server.py - Clean entry point (73 lines)
from fastmcp import FastMCP
from tools import ALL_TOOLS
from resources import database_schema_resource
from prompts import compliance_audit_prompt
mcp = FastMCP("Enterprise_Audit_Framework", version="2024-11-05")
# Register all tools with descriptions
for tool in ALL_TOOLS:
mcp.tool(
name=tool.__name__,
description=TOOL_DESCRIPTIONS.get(tool.__name__)
)(tool)
mcp.resource("db://schema")(database_schema_resource)
mcp.prompt()(compliance_audit_prompt)
# db/connection.py - WAL mode for better concurrency
def get_write_connection():
conn = sqlite3.connect(DB_PATH, check_same_thread=False, timeout=10)
conn.execute("PRAGMA journal_mode=WAL;") # Write-Ahead Logging
conn.execute("PRAGMA foreign_keys=ON;")
conn.row_factory = sqlite3.Row
return conn
# dashboard.py - Production-ready security
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
response.headers["Strict-Transport-Security"] = "max-age=31536000"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
return response
# Rate limiting
limiter = Limiter(key_func=get_remote_address, default_limits=["60/minute"])
# host.py - Intelligent tool selection
response = groq_client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[{"role": "user", "content": "Run full policy validation audit."}],
tools=groq_tools, # Dynamically generated from MCP tools
tool_choice="auto"
)
# RotatingFileHandler for production
logger = logging.getLogger("audit")
handler = RotatingFileHandler(
"audit_trace.log",
maxBytes=5_000_000, # 5MB rotation
backupCount=5
)
logger.addHandler(handler)
This is a personal portfolio project. While not actively seeking contributions, feedback and suggestions are welcome via GitHub issues.
MIT License - See LICENSE for details.
Nikhil Sharma
GitHub: @nikhil-sharma-dotcom
Run in your terminal:
claude mcp add enterprise-financial-compliance-audit-framework -- npx Security
Low riskAutomated heuristic from public metadata — not a security guarantee.