Skip to main content
Glama
Tail-Risk-Toolkit

Tail-Risk-Toolkit

by John-Amal

Tail-Risk-Toolkit

An MCP server that gives an LLM agent a set of extreme value statistics tools for tail risk: peaks-over-threshold GPD fitting, Value-at-Risk and Expected Shortfall, return levels, threshold-stability diagnostics, and out-of-sample VaR backtesting. A small retrieval-augmented generation (RAG) layer lets the agent answer questions from your own documents, with citations.

Why

Extreme value theory is the same machinery whether the tail is a flood or a portfolio loss. A 100-year return level and a 99% VaR on annual data are the same quantile of the same fitted distribution. This server exposes that machinery as agent-callable tools, so a model can be asked "how heavy is this tail, and does the risk model hold up out of sample?" and answer it with a real estimator rather than a plausible-sounding number.

The tools are deliberately opinionated about statistical practice:

  • Threshold choice is the main judgement call in a POT analysis, so tailrisk_threshold_stability exists to make an agent check it rather than accept a single fit.

  • tailrisk_var_es returns EVT, historical and Gaussian estimates side by side, because the gap between them is the argument for using a tail model at all.

  • Backtests are strictly out of sample: every forecast is fitted on trailing data only.

  • Errors explain what to do next ("lower the threshold", "the sample is too short at this confidence level") instead of failing silently or returning a fit that should not be trusted.

Related MCP server: SportsQuant MCP Server

Tools

Tool

Purpose

tailrisk_fit_gpd

Fit a generalised Pareto distribution to threshold exceedances

tailrisk_var_es

VaR and Expected Shortfall by EVT, historical simulation and Gaussian baseline

tailrisk_return_level

Level exceeded once per return period, with the equivalent VaR confidence

tailrisk_backtest_var

Rolling-window backtest with Kupiec, Christoffersen and conditional coverage tests

tailrisk_threshold_stability

Refit across candidate thresholds to check the fit is in the asymptotic regime

tailrisk_load_csv_series

Read a numeric column from a local CSV so a series can be analysed

tailrisk_add_document

Add a local .txt, .md or .pdf file to the knowledge base

tailrisk_search_knowledge

Retrieve the passages that answer a question, with source and chunk IDs for citation

tailrisk_list_documents

List indexed documents and the search mode in use

The analytics tools are read-only and side-effect free. The knowledge-base tools only change the in-memory index; nothing is written to disk.

Install

git clone https://github.com/John-Amal/Tail-Risk-Toolkit.git
cd Tail-Risk-Toolkit
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest

Requires Python 3.10+ and MCP SDK 2.x.

Connect to an MCP client

Add to your client's server configuration (for Claude Desktop, claude_desktop_config.json):

{
  "mcpServers": {
    "tailrisk": {
      "command": "/absolute/path/to/Tail-Risk-Toolkit/.venv/bin/python",
      "args": ["-m", "tailrisk_mcp.server"]
    }
  }
}

The server speaks stdio. Use mcp.run(transport="streamable-http") in server.py for a remote deployment.

Worked example

On 5,000 draws from a Student-t with 4 degrees of freedom, asking for the 99.9% loss quantile:

Method

VaR (99.9%)

Expected Shortfall

EVT (POT, threshold at the 95th percentile)

7.52

9.97

Historical simulation

8.51

10.02

Gaussian

4.41

not defined here

The true value is 7.17. The Gaussian figure understates it by 39%, which is the practical point: at the 99.9% level a normality assumption discards most of the risk. Historical simulation happens to land close here but cannot go beyond the largest observed loss at all, so it stops working exactly where the question gets interesting.

Reproduce with:

python examples/demo.py

Knowledge base (RAG)

The agent can ground its answers in your own material: methodology notes, model documentation, validation reports, desk procedures. Drop .txt, .md or .pdf files into knowledge/ (or set TAILRISK_KNOWLEDGE_DIR), or add a file during a conversation with tailrisk_add_document. The repository ships four short notes describing this toolkit's own methods, so it works from a clean clone.

How it works:

  1. Ingest and chunk. Each document is split into passages of about 900 characters, keeping paragraphs intact, with a short overlap so a statement that straddles a boundary is still found.

  2. Retrieve. Keyword search uses BM25 (implemented with numpy, no extra dependency). Set TAILRISK_EMBEDDING_MODEL=all-MiniLM-L6-v2 (after pip install -e ".[rag]") to add semantic search with sentence embeddings; the two rankings are then combined by reciprocal rank fusion (hybrid search).

  3. Guardrail. A passage is returned only if it covers at least a quarter of the query's information (IDF-weighted terms) or, in hybrid mode, passes an embedding-similarity threshold. When nothing qualifies, the tool returns no passages and tells the agent not to answer from general knowledge as if it came from the documents.

  4. Generate. The MCP client's LLM writes the answer from the returned passages and cites them by source and chunk_id.

Retrieval is evaluated on a labelled set of 16 questions, each worded differently from the document that answers it (tests/test_knowledge.py, run in pytest):

Mode

Hit rate @1

Hit rate @3

MRR

Keyword (BM25)

0.94

1.00

0.97

Off-topic queries such as "capital of France" or "mortgage interest rates" return no passages. The keyword guardrail can still be fooled by a single shared word ("football results" matches the backtesting note on "results"), which is the case semantic search is there to handle.

python examples/rag_demo.py

Methods

Exceedances above a threshold u are modelled with a GPD by maximum likelihood, giving shape xi and scale sigma. The tail is

P(X > z) = zeta_u * [1 + xi (z - u) / sigma] ** (-1 / xi)

where zeta_u is the empirical exceedance rate. Inverting it gives both VaR (set the exceedance probability to 1 - q) and return levels (set it to 1 / T). Expected Shortfall follows in closed form as (VaR + sigma - xi*u) / (1 - xi) and is reported as undefined when xi >= 1, since the tail then has no finite mean.

Backtesting uses the Kupiec proportion-of-failures test for breach frequency and the Christoffersen test for breach independence, combined into a conditional coverage statistic.

References: Coles (2001); McNeil and Frey (2000); Kupiec (1995); Christoffersen (1998).

Testing

pytest runs 28 tests: 17 for the estimators and 11 for the knowledge base. The statistical ones simulate from distributions with known tail behaviour and check the estimators recover it: a Pareto(3) sample should return a shape near 1/3, and EVT VaR on Student-t data should match the analytic quantile within 10%. The calibration test evaluates coverage across several random seeds, because with around 20 breaches per run the independence statistic is noisy enough that a single seed will occasionally reject correctly specified data.

Limitations

  • Observations are assumed independent and identically distributed. Real financial returns are volatility-clustered, so a production implementation would filter with a GARCH model first and fit the GPD to the standardised residuals, following McNeil and Frey. This server fits the raw series.

  • Parameter uncertainty is not propagated: no confidence intervals on VaR, ES or return levels. Profile likelihood or a bootstrap would be the next addition.

  • No multivariate or dependence modelling, so nothing here addresses portfolio aggregation across risk factors.

  • The knowledge base is held in memory and rebuilt at start-up, which suits tens of documents rather than thousands; a larger corpus would need a persistent vector store. Retrieval quality is measured on a small hand-labelled set, so the figures above are indicative rather than a benchmark.

Licence

MIT.

Available Tools

6 tools
tailrisk_backtest_varA
Read-onlyIdempotent

Backtest a VaR model out of sample with Kupiec and Christoffersen tests.

Each forecast uses only trailing data, so the result is a genuine out-of-sample assessment of whether breaches occur at the right rate and without clustering. This is the evidence a model validation report needs.

Returns: str: JSON with n_forecasts, n_breaches, breach_rate, expected_breach_rate, the Kupiec, Christoffersen and conditional coverage statistics with p-values, and a plain-language verdict.

Inputs: params (required). Returns: result

tailrisk_fit_gpdA
Read-onlyIdempotent

Fit a generalised Pareto distribution to threshold exceedances.

Use this first when asked how heavy a tail is. The shape parameter is the headline number: above zero means a heavy tail with no upper bound, near zero means exponential decay, below zero means a finite worst case.

Returns: str: JSON with keys threshold, shape, scale, n_observations, n_exceedances, exceedance_rate, log_likelihood and an interpretation string.

Inputs: params (required). Returns: result

tailrisk_load_csv_seriesA
Read-onlyIdempotent

Read one numeric column from a local CSV so a series can be analysed.

Call this before the analysis tools when the data lives in a file rather than in the conversation. Non-numeric and empty cells are skipped and counted so data quality is visible.

Returns: str: JSON with values (the parsed numbers), count, skipped_rows and truncated.

Inputs: params (required). Returns: result

tailrisk_return_levelA
Read-onlyIdempotent

Estimate the level exceeded once per return period.

This is the same POT quantile as VaR in a different vocabulary: a 100-period return level equals the 99% VaR on data at that frequency. Use it when the question is phrased as a 1-in-N event rather than a confidence level.

Returns: str: JSON with return_period, return_level, equivalent_var_confidence, threshold and shape.

Inputs: params (required). Returns: result

tailrisk_threshold_stabilityA
Read-onlyIdempotent

Refit across candidate thresholds to test whether the tail fit is stable.

Threshold choice is the main judgement call in a POT analysis. Call this before trusting a single fit: if the shape parameter drifts steadily with the threshold, the estimate is not yet in the asymptotic regime.

Returns: str: JSON with a scan list (one record per threshold, each with quantile, threshold, shape, scale, modified_scale, n_exceedances), the shape_range across the scan, and a stability verdict.

Inputs: params (required). Returns: result

tailrisk_var_esA
Read-onlyIdempotent

Estimate VaR and Expected Shortfall by three methods for comparison.

The EVT estimate extrapolates beyond the observed sample, the historical estimate cannot, and the Gaussian estimate is a deliberately naive baseline. A large gap between the EVT and Gaussian figures is the quantitative case for using a tail model at all.

Returns: str: JSON with an evt object (var, es, shape, threshold), historical and gaussian objects, plus evt_vs_gaussian_ratio and the confidence level. Individual methods report a note instead of a number when undefined.

Inputs: params (required). Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 6 tools

    Disambiguation5/5

    Each tool targets a distinct stage of tail-risk analysis: data loading, threshold diagnostics, GPD fitting, VaR/ES estimation, return levels, and backtesting. Even the related VaR/ES and return-level tools are clearly separated by phrasing (confidence level vs. return period).

    Naming Consistency4/5

    All tools share a consistent tailrisk_ prefix and use snake_case, making the family instantly recognizable. However, the second part mixes verb-object forms like fit_gpd and backtest_var with noun phrases like var_es and threshold_stability, so the naming is not perfectly uniform.

    Tool Count5/5

    Six tools is well-scoped for a specialized tail-risk toolkit. Each tool contributes a necessary part of the workflow without redundancy or bloat.

    Completeness5/5

    The toolkit covers the full practical workflow: loading data, assessing threshold stability, fitting the GPD, computing VaR/ES and return levels, and backtesting the VaR model. There are no obvious dead ends or missing core operations for the stated domain.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      B
      quality
      Not graded
      maintenance
      Enables LLMs to retrieve, analyze, and visualize stock prices and financial report data for quantitative trading research and investment analysis. Provides real-time and historical stock data, financial statement analysis, key metric calculations, and trading signal visualization.
      13
      -
    • A
      license
      A
      quality
      D
      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