agent-risk-ai
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@agent-risk-aiPredict default probability for a 45-year-old with income $90k and credit score 620."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
π¦ Agent Risk AI β ML + MCP Server
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 (+ |
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. 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. 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. 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. 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 |
| How much of annual income is committed to debt β a classic underwriting pillar |
| Granted leverage relative to repayment capacity |
| Interaction: high limit usage weighs more for those who have already defaulted |
| Available per capita income, not just nominal |
| Employment stability relative to age |
| Sum of already observed risk flags (prior default, recent default, utilization > 80%) |
| Explicit flag for the sentinel value (~365,243 days) found in |
π§ͺ 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%) andBAIXO(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%) andMUITO_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 |
| Probability + class + risk band of one customer |
| Top SHAP factors behind the score (audit/compliance) |
| "What if the used limit dropped to 30%?" β policy simulation |
| Batch scoring of an entire CSV on disk |
| Expected loss (PD Γ exposure), risk distribution, top customers |
| 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.pyAccess 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.serverConnect 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_defaultwith 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
This server cannot be installed
Maintenance
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
- AlicenseAqualityFmaintenanceProvides 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.95MIT
- AlicenseNot gradedqualityBmaintenanceA 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.1MIT
- AlicenseAqualityCmaintenanceProvides 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.71MIT
- FlicenseNot gradedqualityCmaintenanceA natural-language interface to a credit risk database, with SQL guardrails that enforce read-only, allowlisted access to tables and columns.
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
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
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