Financial Risk MCP Server
Click on "Deploy 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., "@Financial Risk MCP Servercalculate Basel III SA-CCR EAD for my interest rate swap portfolio"
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.
High-Performance Financial Risk & Quantitative Analytics MCP Server
An enterprise-grade Model Context Protocol (MCP) server bridging institutional quantitative risk analytics to autonomous AI agents (Claude, Cursor, Devin, Copilot).
Designed and engineered by Shelendra Jain (Technical Architect & Hands-on Tech Lead, 19+ years experience in low-latency systems and investment banking trading platforms).
ποΈ Architectural Overview
Regulated financial institutions (Tier-1 banks, hedge funds, prime brokers) possess mission-critical quantitative engines written in C++ and distributed microservices. However, connecting these engines to modern Large Language Models (LLMs) requires strict adherence to security boundaries, deterministic arithmetic, and formal protocol standards.
This repository provides a production-hardened reference implementation of an MCP Server exposing quantitative risk functions over standard JSON-RPC 2.0:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Autonomous AI Agents / Front-Office UI β
β (Claude Desktop, Cursor, Devin, Copilot) β
βββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββ
β Standard JSON-RPC 2.0 (stdio / TCP)
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Financial Risk MCP Server β
β β’ Tools Registry β’ Dynamic Resource Provider β
β β’ Prompt Templates β’ Protocol Handshake (v1.0) β
βββββββββββββββ¬ββββββββββββββββββββββββββββ¬βββββββββββββββ
β β
βΌ βΌ
βββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββ
β Python Analytics Core β β High-Performance C++ β
β β’ BCBS 279 SA-CCR Engine β β β’ Multithreaded Engine β
β β’ Parametric VaR / CVaR β β β’ Monte Carlo PFE Sim β
β β’ Options Greeks (Delta, β β β’ 6.8M Valuations/Sec β
β Gamma, Vega, Theta) β β β’ Zero-Allocation Pools β
βββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββRelated MCP server: PA MCP Server
β‘ Key Capabilities & Quantitative Formulations
1. Basel III / BCBS 279 SA-CCR Engine
Computes Exposure at Default (EAD) under the Standardized Approach for Counterparty Credit Risk: $$\text{EAD} = \alpha \times (\text{RC} + \text{PFE})$$ where $\alpha = 1.4$.
Replacement Cost (RC):
Unmargined: $\text{RC} = \max(V - C, 0)$
Margined (CSA): $\text{RC} = \max(V - C, \text{Threshold} + \text{MTA} - \text{NICA}, 0)$
Potential Future Exposure (PFE): $$\text{PFE} = \text{Multiplier} \times \text{AddOn}^{\text{aggregate}}$$ $$\text{Multiplier} = \min\left(1.0, 0.05 + 0.95 \cdot \exp\left(\frac{V - C}{2 \times 0.95 \times \text{AddOn}^{\text{aggregate}}}\right)\right)$$
Supervisory Duration: $$\text{SD}_i = \frac{\exp(-0.05 \cdot S_i) - \exp(-0.05 \cdot E_i)}{0.05}$$
2. Multithreaded Monte Carlo Peak Forward Exposure (PFE)
Simulates stochastic rate paths across tenors from 0.25 years to 30 years using mean-reverting Ornstein-Uhlenbeck / Hull-White state diffusion.
Aggregates distribution profiles to calculate Expected Exposure (EE), PFE 95%, PFE 97.5%, and PFE 99% quantiles.
Automatically identifies the Peak Forward Exposure point along the tenor curve.
3. Value-at-Risk (VaR) & Expected Shortfall (CVaR)
Calculates regulatory holding-period VaR (10-day 99% confidence interval) and Conditional VaR (Expected Shortfall) using variance-covariance analytical scaling: $$\text{VaR}\alpha = \text{PV} \cdot Z\alpha \cdot \sigma_{\text{daily}} \sqrt{T}$$
4. Derivative Sensitivities (Greeks)
Real-time analytical first- and second-order Greeks:
Delta ($\Delta$): First-order directional sensitivity.
Gamma ($\Gamma$): Second-order underlying convexity.
Vega ($\nu$): Volatility surface exposure.
Theta ($\Theta$): Calendar time decay.
Rho ($\rho$): Risk-free interest rate sensitivity.
π Benchmark Performance (C++20 Engine)
Executed on an Intel x86_64 host (2 worker threads, 100,000 paths across 11 tenors):
Metric | Measured Value |
Total Simulated Paths | 100,000 |
Tenor Discretization | 11 steps (0.25y β 30.0y) |
Total Valuation Events | 1,100,000 |
Execution Time | 161.8 ms |
Simulation Throughput | 6,797,363 valuations / second |
π οΈ MCP Primitives Exposed
Tools
calculate_sacr_exposure: Basel III counterparty credit risk capital calculation.simulate_monte_carlo_pfe: Vectorized multi-path Monte Carlo PFE simulation across 30y tenors.compute_portfolio_var: Parametric and regulatory Value-at-Risk and Expected Shortfall.calculate_portfolio_greeks: Multi-asset portfolio Greeks aggregation (Delta, Gamma, Vega, Theta, Rho).
Resources
financial://portfolio/citi-benchmark-01: Standardized institutional benchmark portfolio with Rates, FX, and Equity options.financial://regulatory/bcbs279-factors: Regulatory reference lookup table for BCBS 279 supervisory parameters.
Prompts
audit_counterparty_risk: Guided LLM agent workflow for credit risk auditing, EAD verification, and margin adequacy analysis.stress_test_scenario: Guided agent workflow for applying macroeconomic rate shocks and volatility spikes.
π Quickstart Guide
1. Prerequisites
Python 3.10 or higher
GCC / G++ with C++17 support (optional for C++ benchmark)
pip install numpy
2. Verify Installation
git clone https://github.com/shelendra/financial-risk-mcp.git
cd financial-risk-mcp
# Run unit tests
make test
# Run C++ high-performance benchmark
make bench-cpp
# Run end-to-end sample client
make run-demoπ Integration with AI Development Environments
A. Claude Desktop
Add to your claude_desktop_config.json:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"financial-risk-engine": {
"command": "python3",
"args": ["-m", "fin_risk_mcp.server"],
"cwd": "/path/to/financial-risk-mcp",
"env": {
"PYTHONPATH": "src"
}
}
}
}B. Cursor IDE
Create or update .cursor/mcp.json in your workspace:
{
"mcpServers": {
"financial-risk-engine": {
"command": "python3",
"args": ["-m", "fin_risk_mcp.server"],
"cwd": "/path/to/financial-risk-mcp",
"env": {
"PYTHONPATH": "src"
}
}
}
}π§ͺ Testing Suite
The repository includes comprehensive unit tests verifying math accuracy against standard quantitative tables and testing full JSON-RPC protocol compliance:
$ make test
test_saccr_unmargined (test_engines.TestRiskEngines) ... ok
test_saccr_margined (test_engines.TestRiskEngines) ... ok
test_monte_carlo_pfe (test_engines.TestRiskEngines) ... ok
test_parametric_var (test_engines.TestRiskEngines) ... ok
test_greeks_calculation (test_engines.TestRiskEngines) ... ok
test_initialize (test_mcp_server.TestFinancialRiskMCPServer) ... ok
test_tools_list (test_mcp_server.TestFinancialRiskMCPServer) ... ok
test_call_calculate_sacr_exposure (test_mcp_server.TestFinancialRiskMCPServer) ... ok
test_call_simulate_monte_carlo_pfe (test_mcp_server.TestFinancialRiskMCPServer) ... ok
test_resources_read (test_mcp_server.TestFinancialRiskMCPServer) ... ok
test_prompts_get (test_mcp_server.TestFinancialRiskMCPServer) ... ok
----------------------------------------------------------------------
Ran 11 tests in 0.035s
OKπ¨βπ» Author
Shelendra Jain
Senior Vice President β Technical Architect & Tech Lead
Pune, India
Email: shelendra.jain2004@gmail.com
LinkedIn: linkedin.com/in/shelendra
π License
This project is open-sourced under the MIT License.
Available Tools
4 toolscalculate_portfolio_greeksC
Aggregates first- and second-order derivatives sensitivities: Delta, Gamma, Vega, Theta, and Rho across a book of positions.
| Name | Required | Description | Default |
|---|---|---|---|
| trades | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full behavioral burden. It implies a computation over positions but says nothing about the pricing model or assumptions, whether results are per-trade or netted, error behavior for malformed trades, or determinism/performance characteristics.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
One efficient sentence that front-loads the verb and enumerates the computed sensitivities. It is appropriately short, though the space saved is not used to cover any of the missing behavioral or parameter context.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With no output schema, no annotations, and a complex nested input array at 0% schema coverage, the description should explain the return shape (per-trade vs. portfolio-level Greeks) and pricing assumptions. Neither is present, so an agent cannot confidently predict what it will get back.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0% and the single parameter is a nested array whose fields (trade_id, notional, maturity_years, strike, volatility, option_type, underlying_price) are undocumented. The description adds nothing about required fields, units, or what option_type=LINEAR implies, leaving the caller to guess at the input contract.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description names a specific verb (aggregates) and resource (Delta, Gamma, Vega, Theta, Rho sensitivities across a book of positions), so the tool's function is unambiguous. However, it offers no differentiation from siblings like compute_portfolio_var or calculate_sacr_exposure, which also operate on a portfolio of positions.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
There is no statement of when to use this tool versus the sibling risk tools (VaR, SACR exposure, Monte Carlo PFE), nor any prerequisites such as whether trades must be options or may be linear. The agent must infer usage entirely from the name and the one-sentence purpose.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
calculate_sacr_exposureB
Calculates Basel III / BCBS 279 Standardized Approach for Counterparty Credit Risk (SA-CCR) metrics: Replacement Cost (RC), Potential Future Exposure (PFE), Supervisory Add-on, Multiplier, and Exposure at Default (EAD = 1.4 * (RC + PFE)).
| Name | Required | Description | Default |
|---|---|---|---|
| trades | Yes | List of derivative trades in the netting set | |
| threshold | No | Threshold amount under CSA | |
| is_margined | No | Whether the netting set is subject to bilateral margin / CSA agreement | |
| netting_set_id | Yes | Unique netting agreement identifier (e.g., 'NS-CITI-001') | |
| counterparty_id | Yes | Counterparty legal entity identifier or name | |
| collateral_posted | No | Total eligible collateral held (C) in USD | |
| minimum_transfer_amount | No | Minimum Transfer Amount (MTA) under CSA |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full disclosure burden. It does add real value by disclosing the computation itself, including the EAD formula (1.4 * (RC + PFE)), which tells the agent the tool is a deterministic regulatory calculation. However, it says nothing about side effects, whether results are persisted, validation failures on malformed trades, or how margined vs. unmargined netting sets alter the calculation, leaving notable gaps for a 7-parameter financial model.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single, front-loaded sentence that begins with the verb and standard, then lists outputs. Every clause carries information and nothing is repeated. It is dense but not padded, though the output enumeration could arguably be split for readability.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With no output schema, the description correctly compensates by naming the five returned metrics, so the agent knows what to expect back. Combined with 100% schema coverage on the inputs, the agent has enough to call the tool. What is missing is usage context β when this standardized approach applies versus the Monte Carlo sibling β which keeps it from a 5.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the schema already documents every parameter including threshold, is_margined, collateral_posted, and MTA. The description adds no parameter-level detail beyond what the schema provides. Baseline 3 is appropriate when the schema does the heavy lifting.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description names a specific verb (Calculates) and a precise resource (Basel III / BCBS 279 SA-CCR metrics), then enumerates the exact outputs produced: RC, PFE, Supervisory Add-on, Multiplier, and EAD. This is unambiguous about what the tool does. It does not, however, distinguish itself from the siblings simulate_monte_carlo_pfe, compute_portfolio_var, or calculate_portfolio_greeks, so it falls short of a 5.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
There is no statement of when to use the standardized SA-CCR approach versus the simulation-based sibling simulate_monte_carlo_pfe, nor any prerequisite or eligibility conditions (e.g., which counterparties qualify for the standardized approach). The agent is left to infer usage entirely from the regulatory name.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
compute_portfolio_varA
Computes regulatory Value-at-Risk (VaR) and Expected Shortfall (CVaR) for market risk across specified holding periods and confidence intervals.
| Name | Required | Description | Default |
|---|---|---|---|
| horizon_days | No | Holding period in days (e.g. 10 for Basel Market Risk) | |
| portfolio_value | Yes | Total market value of the portfolio in USD | |
| confidence_level | No | Statistical confidence level (e.g. 0.99 for 99%) | |
| daily_volatility | Yes | 1-day standard deviation of portfolio returns |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full behavioral burden. It says it 'Computes' the metrics, implying a read-only calculation, but does not disclose the VaR methodology (parametric, historical, Monte Carlo), distributional assumptions, determinism, or computational costβall material for interpreting a risk number.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single front-loaded sentence with no filler. Every clause (regulatory, VaR and CVaR, market risk, holding periods, confidence intervals) contributes useful scoping information.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Inputs are fully covered by the schema, and the description names the two conceptual outputs (VaR and CVaR). However, with no output schema and no annotations, it omits output structure and modeling assumptions, leaving the agent able to invoke it but not fully informed about what it returns.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the schema already documents all four parameters with defaults and examples. The description echoes 'holding periods and confidence intervals' (matching horizon_days and confidence_level) but adds no syntax, constraints, or semantics beyond what the schema provides, so baseline 3 applies.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description names a specific verb (Computes) and specific resources (Value-at-Risk and Expected Shortfall/CVaR) scoped to market risk, holding periods, and confidence intervals. This clearly distinguishes it from the sibling tools calculate_sacr_exposure, simulate_monte_carlo_pfe, and calculate_portfolio_greeks, which produce different risk metrics.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The 'regulatory' and 'market risk' framing implies the use case, but there is no explicit statement of when to prefer this tool over the sibling risk calculators, nor any exclusions or prerequisites. Usage is inferable but not guided.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
simulate_monte_carlo_pfeC
Executes high-performance Monte Carlo simulation (using native C++20 multithreaded core) to project Potential Future Exposure (PFE) profiles and Peak Forward Exposure across multi-year tenors (0.25y to 30y).
| Name | Required | Description | Default |
|---|---|---|---|
| trades | Yes | List of trades to simulate exposure for | |
| volatility | No | Annualized market volatility factor | |
| portfolio_id | Yes | Portfolio identifier | |
| mean_reversion | No | Mean reversion speed for rate/asset diffusion | |
| num_simulations | No | Number of Monte Carlo paths (default 10,000) |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden. It mentions an implementation detail (C++20 multithreaded core) but says nothing agent-relevant: no runtime/cost expectations, no determinism or seeding behavior, no statement about side effects or output format.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single front-loaded sentence with no wasted framing, but the parenthetical about the native C++20 multithreaded core is implementation marketing that does not help an agent decide or invoke correctly.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With no output schema, the description must characterize the return, and it only names the outputs (PFE profiles, Peak Forward Exposure) without structure, granularity, or pagination/shape. For a 5-parameter computation tool with no annotations, this leaves real gaps.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the schema already documents all five parameters and baseline is 3. The description adds one useful constraint not in the schema: the 0.25yβ30y tenor range that bounds maturity_years, but nothing about notional, volatility, or simulation count semantics.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
States a specific verb (Executes Monte Carlo simulation) and resource (PFE profiles / Peak Forward Exposure) with the tenor range made explicit. It is clear what the tool computes, though it never distinguishes itself from siblings like calculate_sacr_exposure or compute_portfolio_var.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
There is no statement of when to use this tool versus the sibling exposure/VaR/Greeks tools, nor any prerequisites or exclusions. Usage must be inferred purely from the tool name and purpose sentence.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
4 tool updates
v1.0.0- First observed
calculate_portfolio_greeks - First observed
calculate_sacr_exposure - First observed
compute_portfolio_var - First observed
simulate_monte_carlo_pfe
TDQS
Scored across 4 tools
Each tool targets a distinct risk metric: regulatory SA-CCR exposure, Monte Carlo PFE profiles, portfolio VaR/CVaR, and Greeks. The only mild overlap is between calculate_sacr_exposure and simulate_monte_carlo_pfe, since both address counterparty exposure, but the standardized-formula vs simulation distinction is clear enough to distinguish them.
All names use snake_case with a verb_noun structure (calculate_sacr_exposure, simulate_monte_carlo_pfe, compute_portfolio_var, calculate_portfolio_greeks), which is easily predictable. The verb choices vary (calculate/simulate/compute) but all are equally readable and follow the same pattern.
Four tools is a focused, well-scoped set that avoids redundancy for a risk analytics server. It is on the lean side, but each tool clearly earns its place.
The core measures are covered: exposure, PFE, VaR/CVaR, and Greeks. However, notable counterparty-risk operations are absent, including CVA/credit valuation adjustment, stress testing, and scenario or backtesting tools, leaving some obvious gaps in a full risk workflow.
Maintenance
Related MCP Connectors
Portfolio risk analytics β VaR, Monte Carlo, optimization, options Greeks, stress testing.
Connect AI agents to financial institution origination, analytics, and compliance workflows.
Crypto portfolio risk analysis: VaR, scenarios, liquidity and correlation engines as MCP tools.
AI agents query normalized financial services data and run workflows via Milemarker MCP.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceEnables MCP-compatible AI agents to retrieve quantum-computed portfolio optimisation, VaR simulations, AI-enhanced sentiment and regime detection, and cross-asset risk signals through simple metric tools.44 npmMIT
- FlicenseNot gradedqualityBmaintenanceEnables AI agents to run probabilistic portfolio analysis workflows, including input validation, instrument verification, simulation preparation, and approved interactive reporting.-
- AlicenseNot gradedqualityBmaintenanceEquips AI agents with institutional risk management and execution tools for Solana and Hyperliquid, enabling Kelly-criterion position sizing, VaR/CVaR analysis, Monte Carlo simulations, circuit breaker checks, and wallet/funding data queries through standardized MCP tools.MIT
- AlicenseNot gradedqualityBmaintenanceEnables quantitative portfolio tail-risk analysis, option Greeks, Monte Carlo stochastic simulations, fixed-income duration/convexity, and Nelson-Siegel yield-curve interpolation through MCP tools.7MIT