Skip to main content
Glama
faanogueira

agent-risk-ai

by faanogueira

🏦 Agent Risk AI β€” ML + MCP Server

Python XGBoost scikit--learn Optuna SHAP MCP Tests License

Agent Risk AI: Your autonomous credit intelligence and risk analyst via MCP. A credit card default prediction model, trained with methodological rigor (stratified CV, Bayesian tuning with Optuna, optimized threshold, explainability via SHAP) and exposed as an MCP server β€” queryable directly by Claude Desktop/Code and AI agents in natural language.


πŸ“Œ Why this project is different from "just training a model"

Most portfolio projects stop at training the model and showing a .ipynb with metrics. This one goes a step further: the model is encapsulated in an MCP server (Model Context Protocol) with 6 business tools, which means any compatible LLM host (Claude Desktop, Claude Code) can query the model in natural language, without writing code:

πŸ—£οΈ "What is the default risk for this customer: age 46, income R$107,934, credit score 544, 2 previous defaults?" πŸ€– β†’ calls predict_default β†’ responds with probability, class, and SHAP explanation.

This is exactly the pattern emerging in risk/data teams that want to put production models "into the conversation," not behind a static dashboard.


Related MCP server: CreddyMCP

πŸ—‚οΈ The business problem

Dataset of 45,528 credit card customers with demographic, income, and credit behavior variables. Target: credit_card_default (binary), with a real imbalance of 8.1% default rate β€” a typical credit risk scenario, where naive accuracy is a misleading metric.

Training rows

45,528

Default rate

8.12% (imbalanced)

Original variables

17 (+ customer_id, name)

Variables after engineering

30


πŸ—οΈ How the System Works (Simple Architecture)

The project turns raw credit data into actionable, auditable decisions consumed by AI agents through 4 integrated stages:

flowchart LR
    A["πŸ“ 1. Dados Brutos<br/><b>train.csv / test.csv</b>"] --> B["🧹 2. Limpeza & Features<br/><b>DTI, Limite, Flags</b>"]
    B --> C["πŸ€– 3. CΓ©rebro Preditivo<br/><b>XGBoost + Optuna + SHAP</b>"]
    C --> D["πŸ”Œ 4. Servidor MCP<br/><b>6 Ferramentas de NegΓ³cio</b>"]
    D --> E["πŸ’¬ 5. Agente de IA<br/><b>Claude / Cursor / LLMs</b>"]

The 4-Step Flow:

  1. πŸ“ 1. Processing & Financial Intelligence (data_processing.py / feature_engineering.py)

    • Removes sensitive data (PII) and handles dataset anomalies (such as the retiree sentinel).

    • Creates real financial indicators: Debt-to-Income (DTI), credit utilization, and per capita income.

  2. πŸ€– 2. Machine Learning Pipeline (pipeline.py / train.py)

    • Runs transformations (imputation, one-hot encoding, and scaling) in a leak-proof manner (no data leakage).

    • Trains and tunes XGBoost via Optuna (25 trials) in 5-fold cross-validation, calibrating the optimal decision threshold ($F_1 = 0.875$).

  3. 🧠 3. Explainability & Auditing (inference.py / evaluate.py)

    • Persists the winning model and the SHAP TreeExplainer to decompose exactly which variables increase or reduce each customer's risk in real time.

  4. πŸ”Œ 4. MCP Agentic Layer (mcp_server/server.py)

    • Exposes 6 ready-made tools so any AI assistant or agent (Claude Desktop, Claude Code, etc.) can query the model, simulate scenarios, and evaluate entire portfolios in natural language.


πŸ”¬ Domain-driven feature engineering

Instead of "throwing everything into XGBoost," each derived feature has an explicit credit risk rationale:

Feature

Business rationale

debt_to_income_ratio (DTI)

How much of annual income is committed to debt β€” a classic underwriting pillar

credit_limit_to_income_ratio

Granted leverage relative to repayment capacity

credit_utilization_frac Γ— prev_defaults

Interaction: high limit usage weighs more for those who have already defaulted

income_per_family_member

Available per capita income, not just nominal

employment_tenure_ratio

Employment stability relative to age

risk_flags_sum

Sum of already observed risk flags (prior default, recent default, utilization > 80%)

is_retired_or_unemployed

Explicit flag for the sentinel value (~365,243 days) found in no_of_days_employed, which actually marks retirees/unemployed β€” treating it as a literal number would distort the model


πŸ§ͺ Methodology and statistical rigor

  • Winsorization learned only on training (99.5th percentile) and reapplied on test/holdout β€” no data leakage.

  • Single sklearn pipeline (ColumnTransformer + model) β€” imputation and encoding are recalculated at each cross-validation fold, not just once on the entire dataset (a common mistake that artificially inflates metrics).

  • Selection metric: PR-AUC (Average Precision), not ROC-AUC or accuracy β€” the right choice for 8% prevalence of the positive class.

  • 15% holdout never seen during Optuna tuning β€” the final metrics below reflect real generalization, not overfitting to the search process.

  • Recalibrated decision threshold maximizing F1 on the holdout precision-recall curve (0.875), instead of blindly using 0.5 β€” essential when the positive class is rare.

  • Explainability via SHAP TreeExplainer β€” every MCP server prediction can be audited factor by factor (relevant for credit regulatory compliance).


πŸ“Š Results and Performance Metrics

All metrics below were calculated on the holdout set (6,830 customers), completely isolated during Optuna hyperparameter search:

1. Model Comparison (Stratified 5-Fold Cross-Validation)

Model

PR-AUC (5-fold CV)

Gain vs Baseline

Logistic Regression (balanced linear baseline)

0.9454

β€”

Random Forest (400 estimators, balanced subsample)

0.9484

+0.30%

XGBoost + Optuna (25 Bayesian TPE trials)

0.9546

+0.92%


2. Holdout Performance Metrics (Champion Model)

Statistical & Business Metric

Value

Practical Interpretation

ROC-AUC

0.9960

Near-perfect global discriminative ability between good and bad payers.

PR-AUC (Average Precision)

0.9625

Priority metric for imbalance (vs 8.12% random baseline).

Gini Index (Credit)

0.9920

$2 \times \text{ROC-AUC} - 1$ β€” excellent risk separation power.

Overall Accuracy

98.14%

6,703 correct predictions out of 6,830 evaluated customers.

Precision (PPV)

96.52%

Out of every 100 customers classified as defaulters, 96.5 actually default.

Recall / Sensitivity

80.00%

Captures 8 out of 10 real defaulters, avoiding credit losses.

Specificity (TNR)

99.75%

Preserves 99.75% of good customers, ensuring healthy lending.

False Alarm (FPR)

0.25%

Only 16 healthy customers wrongly rejected out of 6,275 analyzed.

F1-Score

0.8749

Optimal harmonic balance between precision and recall.

Optimized Decision Threshold

0.875

Threshold calibrated via PR curve (vs naive 0.5 cutoff).


3. Detailed Confusion Matrix on Holdout

Actual \ Predicted

Non-default (0)

Default (1)

Actual Total

Credit Business Impact

Actual Non-default (0)

6,259 (TN)

16 (FP)

6,275

Minimal attrition: only 16 good customers wrongly rejected (FPR = 0.25%).

Actual Default (1)

111 (FN)

444 (TP)

555

Avoided loss: 444 defaults successfully blocked (Recall = 80.00%).

Predicted Total

6,370

460

6,830

Hit rate when flagging risk: 96.52% precision.


4. Winning Hyperparameters (Optuna β€” 25 Trials)

{
  "n_estimators": 500,
  "max_depth": 4,
  "learning_rate": 0.0121,
  "subsample": 0.7244,
  "colsample_bytree": 0.7301,
  "min_child_weight": 8,
  "gamma": 3.1878,
  "reg_lambda": 3.5388,
  "reg_alpha": 0.0774,
  "scale_pos_weight": 11.3164
}

5. Top 10 Auditable Risk Factors (Mean $|\text{SHAP}|$)

Ranking

Feature

Mean $|\text{SHAP}|$

Risk Rationale

1ΒΊ

credit_score

3,3044

Dominant factor: historical credit bureau score.

2ΒΊ

credit_limit_used(%)

1,8558

Commitment of the granted revolving limit.

3ΒΊ

credit_utilization_frac

0,6122

Decimal fraction of credit limit utilization.

4ΒΊ

risk_flags_sum

0,1516

Weighted sum of pre-existing risk flags.

5ΒΊ

prev_defaults

0,1167

Number of prior default occurrences.

6ΒΊ

yearly_debt_payments

0,0445

Annual financial burden committed to payments.

7ΒΊ

no_of_days_employed

0,0382

Employment stability and time in current job.

8ΒΊ

gender_F

0,0339

Demographic category monitored for auditing.

9ΒΊ

utilization_x_prev_defaults

0,0266

Interaction: high utilization combined with past default.

10ΒΊ

occupation_type_Unknown

0,0240

Flag for unreported occupation / retired.

πŸ“ˆ Visual Artifacts in reports/figures/:

  • roc_curve.png β€” ROC curve with random baseline.

  • precision_recall_curve.png β€” Precision-Recall curve compared to base prevalence.

  • confusion_matrix.png β€” Confusion matrix at the optimal threshold.

  • shap_summary.png β€” Beeswarm summary plot of global explainability.

πŸ”’ All metrics above are reproducible and are saved in the audit metadata in models/model_metadata.json.


πŸ’‘ Guide to Interpreting the Results (For Laypeople and Business)

To facilitate communication between data scientists, credit analysts, and non-technical directors, each system output has a direct business meaning:

1. πŸ“ˆ Probability of Default (PD) & Action Bands

  • What it is: The estimated probability (from 0% to 100%) that the customer will be more than 90 days late on their bill payment in the following months.

  • How to act based on the band:

    • 🟒 MUITO_BAIXO (< 5%) and BAIXO (5% to 15%): Credit granting and limit increases recommended automatically with competitive rates.

    • 🟑 MODERADO (15% to 35%): Borderline customer. Conservative initial limit or income proof request recommended.

    • πŸ”΄ ALTO (35% to 60%) and MUITO_ALTO (β‰₯ 60%): High default risk. Proposal rejection or requirement of guarantors/real collateral recommended.

2. πŸ“Š How to Read the SHAP Explainability Chart

  • πŸ”΄ Bars to the RIGHT (Positive Contribution): Registration or behavioral factors that push risk UP (e.g., low score, excessive revolving limit usage, prior default).

  • 🟒 Bars to the LEFT (Negative Contribution): Healthy factors that protect the customer and push risk DOWN (e.g., years of job stability, high income, high score).

  • πŸ“ Bar Length: The longer the bar, the more decisive that variable was for the AI's final verdict.

3. πŸ“‰ What is the What-If Simulation?

  • It allows simulating the impact of changes in rules or guiding denied customers. For example: "If you reduce your limit utilization from 73% to 30%, your risk will drop from 68% to 22%, allowing your card to be approved."

4. πŸ’° Total Exposure and Expected Loss of the Portfolio

  • Total Exposure: The total financial volume the institution put at stake (sum of granted credit limits).

  • Expected Loss ($PD \times \text{Exposure}$): The amount in Reais the institution projects to statistically lose from default if no action is taken.

  • Loss Rate (%): Direct basis for the Allowance for Doubtful Accounts (PDD / IFRS 9).


πŸ”Œ The MCP server β€” 6 business tools

Tool

Use

predict_default

Probability + class + risk band of one customer

explain_prediction

Top SHAP factors behind the score (audit/compliance)

what_if_analysis

"What if the used limit dropped to 30%?" β€” policy simulation

score_portfolio_csv

Batch scoring of an entire CSV on disk

portfolio_risk_summary

Expected loss (PD Γ— exposure), risk distribution, top customers

get_model_performance

Model technical sheet (metrics, hyperparameters, features)

Risk bands used by the server: MUITO_BAIXO (<5%) Β· BAIXO (5–15%) Β· MODERADO (15–35%) Β· ALTO (35–60%) Β· MUITO_ALTO (β‰₯60%).


🌐 Web Chat Interface in the Browser (Streamlit)

The project includes a complete conversational web interface built in Streamlit for demonstrations, quick tests, and operational use by credit and underwriting teams:

make web
# ou: streamlit run app.py

Access it in your browser: http://localhost:8501

✨ Main Features of the Web Interface:

  • πŸ’¬ Natural Language Chat: Ask free-form questions about customers, simulations, or portfolios in Portuguese.

  • ⚑ Quick Actions (All 5 Risk Bands): Instantly load representative profiles of each band with 1 click:

    • 🟒 1. Very Low (<5%): Prime Customer (high income, score 910, limit usage 10%).

    • 🟒 2. Low (5–15%): Healthy Customer (score 810, limit usage 25%, 0 defaults).

    • 🟑 3. Moderate (15–35%): Borderline Customer (score 580, limit usage 50%, no late payments).

    • πŸ”΄ 4. High (35–60%): Alert Customer (score 580, limit usage 50%, 1 recent default).

    • β›” 5. Very High (β‰₯60%): Critical Customer (score 544, limit usage 73%, 2 defaults).

  • πŸ› οΈ Suggested Query Grid:

    • πŸ“Š Technical Sheet: Displays validation metrics, ROC-AUC, PR-AUC, and accuracy.

    • πŸ“ CSV Portfolio: Evaluates entire portfolios with vectorized scoring of 11,000 customers in 0.7s, calculating the Expected Loss (R$) and total exposure.

    • πŸ“‰ What-If Simulation: Simulate limit reductions (30%), debt settlement, or score increases (+150 points).

    • πŸ”¬ SHAP Audit: Ranking and bar charts with the biggest credit risk drivers.

  • πŸ’‘ Expandable Guides for Laypeople: Each response contains a didactic caption explaining the meaning of SHAP charts, probability deltas, and loss provisioning.


πŸ”Œ Option 2: MCP Server (Claude Desktop / Claude Code)

# 1. Instalar dependΓͺncias
pip install -r requirements.txt --break-system-packages   # ou use um venv

# 2. Treinar o modelo (gera models/*.joblib e model_metadata.json)
python -m src.train

# 3. (Opcional) Gerar os grΓ‘ficos de avaliaΓ§Γ£o em reports/figures/
python -m src.evaluate

# 4. Rodar os testes
pytest -v

# 5. Subir o servidor MCP (stdio)
python -m mcp_server.server

Connect to Claude Desktop / Claude Code

Copy mcp_server/claude_desktop_config.example.json to the MCP configuration file of your client, adjusting the absolute paths:

{
  "mcpServers": {
    "agent-risk-ai": {
      "command": "python",
      "args": ["-m", "mcp_server.server"],
      "cwd": "/caminho/absoluto/para/agent-risk-ai",
      "env": { "PYTHONPATH": "/caminho/absoluto/para/agent-risk-ai" }
    }
  }
}

Restart the client and ask, for example: "Using the agent-risk-ai server, what is the risk of this customer: ..."


πŸ“ Project structure

agent-risk-ai/
β”œβ”€β”€ app.py                       # Interface Web Chat conversacional no navegador (Streamlit)
β”œβ”€β”€ data/raw/                    # train.csv, test.csv, sample_submission.csv
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config.py                 # caminhos, sementes, regras de negΓ³cio centralizadas
β”‚   β”œβ”€β”€ data_processing.py        # limpeza (sentinelas, winsorizaΓ§Γ£o, PII)
β”‚   β”œβ”€β”€ feature_engineering.py    # features de domΓ­nio (DTI, utilizaΓ§Γ£o, tenure...)
β”‚   β”œβ”€β”€ pipeline.py                # ColumnTransformer sklearn (sem vazamento)
β”‚   β”œβ”€β”€ train.py                   # baselines + Optuna + XGBoost + SHAP + persistΓͺncia
β”‚   β”œβ”€β”€ evaluate.py                # gera grΓ‘ficos (ROC, PR, confusΓ£o, SHAP)
β”‚   └── inference.py                # camada de prediΓ§Γ£o reutilizada pelo MCP e Web Chat
β”œβ”€β”€ mcp_server/
β”‚   β”œβ”€β”€ server.py                   # servidor MCP com as 6 ferramentas
β”‚   └── claude_desktop_config.example.json
β”œβ”€β”€ models/                         # modelo treinado + metadados (gerado por train.py)
β”œβ”€β”€ reports/figures/                 # grΓ‘ficos de avaliaΓ§Γ£o (gerado por evaluate.py)
β”œβ”€β”€ tests/test_pipeline.py            # 7 testes unitΓ‘rios (pytest)
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ Makefile
└── README.md

⚠️ Known limitations and next steps

Transparency about limitations is part of doing serious data science:

  • LGD assumed at 100% in the expected loss calculation (portfolio_risk_summary) for simplicity β€” in production, this would come from historical recovery data.

  • No drift monitoring β€” the natural next step would be to instrument predict_default with feature distribution logging over time.

  • Probability calibration was not validated with CalibratedClassifierCV β€” the probabilities are discriminative (good for ranking risk), but may not be perfectly calibrated on an absolute scale.

  • occupation_type = "Unknown" is the most frequent category (~31% of the base) and coincides with the retired/unemployed flag β€” a future refinement would be to break down this category.


🧠 Technical stack

Python 3.12 Β· pandas Β· scikit-learn Β· XGBoost Β· Optuna (Bayesian tuning via TPE) Β· SHAP (explainability) Β· matplotlib Β· pytest Β· MCP Python SDK


F
license - not found
Not graded
quality - not tested
B
maintenance

Maintenance

–Maintainers
–Response time
–Release cycle
–Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • A
    license
    A
    quality
    F
    maintenance
    Provides DeFi vault risk analytics for AI agents to search, compare, and perform due diligence on over 700 vaults across major protocols like Morpho and Aave. It enables natural language analysis of risk scores, platform security, and portfolio-level risk assessments.
    9
    5
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    A credit-risk analytics MCP server enabling natural language queries over 30,000 real credit records, default risk prediction with an interpretable model, and live Turkish economic indicators.
    1
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    Provides AI agents with quantitative risk tools such as VaR, expected shortfall, GARCH volatility, backtesting, stress testing, tail risk analysis, and credit scoring using synthetic or user-supplied data.
    7
    1
    MIT
  • F
    license
    Not graded
    quality
    C
    maintenance
    A natural-language interface to a credit risk database, with SQL guardrails that enforce read-only, allowlisted access to tables and columns.

View all related MCP servers

Related MCP Connectors

  • Credit scores for AI agents. Underwrite an unknown counterparty before extending credit.

  • Deterministic what-if & scenario simulation for AI agents: projections, sensitivity & break-even.

  • Agent credit issuance and scoring β€” programmable credit lines on Base L2

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/faanogueira/agent-risk-ai'

If you have feedback or need assistance with the MCP directory API, please join our Discord server