Skip to main content
Glama

statlab-mcp — Statistical Analysis MCP Server

Standalone project, not affiliated with any vendor's official plugin (README historical note: not affiliated with DeepSeek Harness). Gives AI agents (Claude Code / Cursor / DeepSeek Harness / Codex, etc.) real statistical capability: LLMs computing statistics by mental math will fabricate numbers; every statistical result in this project comes from real computation (numpy / scipy / statsmodels / scikit-learn / pmdarima), the AI only handles invocation and interpretation; no LLM is allowed to participate in computation within the first layer of 25 tools.


What it's for

After installing it, when you tell the AI "help me analyze this sales data", the AI no longer makes groundless assertions — it calls 25 real statistical tools: compute descriptive statistics, check correlations, run hypothesis tests, fit regressions, perform clustering, forecast time series, draw Chinese charts — every number comes from a validated statistical library, reproducible and accountable. The summary field gives a one-sentence Chinese conclusion, and result gives the full structured data, e.g.:

{"status": "ok", "result": {"p_value": 0.0241, "mean_diff": 5.5, "effect_size": 0.65},
 "summary": "Welch t 检验:均值差 5.5(95% CI [0.74, 10.26]),p=0.0241 <0.05 拒绝 H0……相关≠因果"}

Related MCP server: Stats Engine MCP Server

Who it's for

Audience

How to use

Benefit

People writing code / doing analysis with AI (data analysts, operations, product)

Have Claude Code / Cursor etc. call it on demand

Analysis conclusions are backed by real computation, no more worrying about AI fabricating numbers

AI Agent developers

Plug it in as a statistics backend into your own agent/workflow

25 deterministic tools + unified protocol, easy to integrate and test

People who studied statistics but don't want to hand-code

Ask in natural language, AI calls the tools on their behalf

Hypothesis testing / regression / time series fully auto-selected, with step-by-step explanations

People who need accountable analysis reports

Combine with the auto_analysis scheme (decision tree + template + prompt)

Every number in the report is tagged with its source tool, guarding against hallucination

Students who want to quickly chart their data

A set of plot_* tools

Chinese-labeled charts with statistics marked directly on the plot

What problems it solves

Your problem

Corresponding capability

"What does this pile of data look like, is it dirty"

describe / data_type_check / missing_report: physical exam, household register, absence sheet

"Are those two columns related? Real or coincidence"

correlation_matrix (with fdr_bh multiple-comparison correction) + heatmap

"Is there really a difference between group A and group B"

normality_test → hypothesis_test (Welch t) → effect_size triple

"How much of the sales difference across three stores is real"

anova_test: automatic Levene→Welch→Tukey/Games-Howell post-hoc comparison

"What drives revenue? Can it be predicted"

linear_regression (R²/VIF/residual diagnostics) + feature_importance

"Will a new customer buy (yes/no)"

logistic_regression: OR + AUC + confusion matrix + separation warning

"How many segments can customers be split into?"

cluster_analysis (centroids restored to original units + silhouette coefficient k±1 comparison)

"About how much will sales be next month?"

trend_analysis → time_series_forecast (SARIMA auto order selection)

"Which day in this date series is off"

anomaly_detect (STL/differenced IQR/rolling z-score, only reports, never deletes data)

"I don't want to look at tables, I want charts and reports"

plot_* five-piece set + auto_analysis report template

Features and standout capabilities

  1. Determinism above all: all random processes fixed with seed (42); running the same file twice yields byte-for-byte identical results (this is the foundation of accountability, with dedicated assertions in tests)

  2. Anti-hallucination design: the first layer of 25 tools has zero LLM involvement; conclusion copy is generated by code templates assembling numbers; p<0.001 is uniformly shown as "<0.001"; every conclusion is accompanied by a fixed limitations statement (correlation ≠ causation, whether corrected, sample size)

  3. Caliber locked down and recomputable: q1/q3 = linear interpolation (same caliber as Excel QUARTILE.INC), skewness/kurtosis = scipy Fisher caliber, std = ddof=1 (Excel STDEV.S) — documented in writing, tests cross-check against manual formulas and standard libraries independently (223 pytest cases, coverage in docs/)

  4. Full Chinese pipeline: Chinese column names, automatic GBK encoding fallback, Chinese-font charts (falls back to English with a note when no font is available), Chinese error messages with solution suggestions

  5. Hardcore security and protection: local files only, rejects UNC/NUL paths, no network upload, triple protection at >50MB / 2 million rows / 500MB memory, xlsx zip-bomb and date-span protection, error output capped (prevents malicious input from hanging the process)

  6. Uniform calling experience: all tools are isomorphic (parameter validation → Chinese error or result+summary), so both agents and humans pick it up painlessly; MCP tool descriptions = full docstring (parameter tables/return structure/examples), when the agent opens the tool list, that is the user manual

  7. Engineering completeness: 12 design documents (per-tool parameter tables/boundary tables/JSON Schema/validation methods) + client integration configs + coverage of 82–96% + full ruff pass + stdio protocol smoke test

Quick start

# 1. 安装(Python 3.13+,仅 pip)
git clone https://github.com/good-boy4069/statlab-mcp.git
cd statlab-mcp
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt --timeout 60

# 2. 验证能跑(应输出 ALL-STDIO-OK)
$env:PYTHONUTF8="1"
.\.venv\Scripts\python.exe tests\smoke_stdio.py

Connect to Claude Code (project root .mcp.json):

{
  "mcpServers": {
    "statlab-mcp": {
      "command": "C:\\path\\to\\statlab-mcp\\.venv\\Scripts\\python.exe",
      "args": ["-m", "statlab_mcp.server"],
      "cwd": "C:\\path\\to\\statlab-mcp",
      "env": {"PYTHONUTF8": "1"}
    }
  }
}

Three musts: -m statlab_mcp.server (not the server.py path), cwd pointing to the project root, and PYTHONUTF8=1. Other clients (Cursor/VSCode/Codex/Hermes/DSH) see docs/clients.md.

First call (usable directly from the command line without a client):

.\.venv\Scripts\python.exe -c "import sys; sys.path.insert(0,'.'); from statlab_mcp.tools.data_exploration_describe_statistics import describe_statistics; import json; print(json.dumps(describe_statistics('samples/clean.csv'), ensure_ascii=False, indent=1))"

Three iron rules for data: ① only csv/xlsx/tsv/json accepted, absolute paths freely given (Chinese/GBK/empty values/invalid dates all handled automatically); ② put real data outside the project directory; ③ for every statistic, first read the plain-Chinese conclusion in summary, then flip through the structured numbers in result.

The 25 tools at a glance

Group

Tools

Data exploration

describe_statistics, correlation_matrix, missing_report, outlier_detect, data_type_check

Statistical inference

hypothesis_test, anova_test, chi_square_test, normality_test, confidence_interval, effect_size

Modeling

linear_regression, logistic_regression, cluster_analysis, pca_analysis, feature_importance

Time series

time_series_forecast, seasonal_decompose, trend_analysis, anomaly_detect

Visualization

plot_scatter, plot_histogram, plot_heatmap, plot_forecast, plot_box

Orchestration layer

auto_analysis (deliverable: decision-tree document + report template + agent prompt, not an MCP tool)

Core value and unified protocol

  • Accountable numbers: results are deterministic, reproducible, and testable; the same input run twice gives identical results (global seed=42)

  • Unified structure: success {status:"ok", result:{...}, summary:"one-sentence Chinese conclusion"}; failure {status:"error", message:"Chinese reason with a useful hint"}

  • Image attachments: image-bearing tools attach __image__ at the top level of the returned JSON (absolute image path, base64 forbidden)

Environment preparation (Windows)

  1. Requires Python 3.13+, a dedicated virtual environment (pip only; uv/poetry/conda forbidden):

    python -m venv .venv
    .\.venv\Scripts\Activate.ps1
    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt --timeout 60
  2. requirements.txt is the single authoritative source for dependencies (pyproject.toml holds only metadata).

  3. UTF-8 must be set before running (otherwise stdio writes Chinese JSON in GBK and the MCP connection breaks immediately):

    $env:PYTHONUTF8="1"

    As a fallback, the server entry file also has sys.stdout.reconfigure(encoding="utf-8") at the very top.

  4. Data reading uniformly goes through the read_table() wrapper: utf-8-sig trial read → on csv/tsv failure automatically switch to gbk → on further failure a Chinese error "file encoding unrecognized, please save as UTF-8"; format whitelist {csv, xlsx, tsv, json}, xlsx reads only the first sheet.

How agents view images

  • DeepSeek Harness: use the read_image tool to read the absolute path returned by __image__

  • Claude Code: use the Read tool to read the same path

  • All images are stored in reports/plots/YYYYmmdd/ (archived by date to prevent buildup), filenames toolname_<primary column name or all>_YYYYmmdd_HHMMSS_fff.png, Chinese fonts Microsoft YaHei/SimHei (falls back to English with an in-chart note when missing), dpi=150; the directory may be cleaned at any time (does not affect any computation)

Security statement

  • Only analyzes locally provided data files that you actively hand over; rejects UNC/NUL paths; no network uploads whatsoever

  • Path trust statement: tools do not verify file provenance (they read directly from the path you give), so do not pass paths from untrusted sources; put real data outside the project directory

  • Big-data protection: >50MB rejected; 5–50MB first estimates row count/memory and rejects if over limit; zip bombs and date-span attack surfaces also hard-protected

Testing and acceptance

& .\.venv\Scripts\python.exe -m pytest tests\ -q
  • Test data is generated by tests/make_fixtures.py with fixed seed and committed to the repo; key numbers are cross-checked against independent third-party computation (statistics.mean / manually computed expected-value tables) — no circular reasoning allowed

  • Acceptance workflow (AI-assisted mode since 2026-08-26): full pytest pass + real-run verification on two datasets (full real stdout archived in the acceptance record) → commit + PROGRESS entry; users retain the right to spot-check at any time

  • Quality baseline: 223 pytest cases, tool module coverage 82–96%, full ruff pass, stdio protocol smoke ALL-STDIO-OK

Technical notes (mcp 2.x)

Dependency pinned to mcp==2.1.0: mcp.server.fastmcp.FastMCP has been superseded by mcp.server.mcpserver.MCPServer (API-compatible add_tool/tool decorators; list_tools/call_tool/run_stdio_async are async).

Documentation navigation

  • docs/clients.md — client integration configs (Claude Code/Cursor/VSCode/Codex/Hermes/DSH)

  • docs/SPEC.md — protocol and statistical calibers (return structure/number protocol/image protocol/behavior contract)

  • docs/design/ — interface design for each tool (parameter tables/boundary behavior tables/JSON Schema/validation methods, the user manual for agents and secondary developers)

  • docs/example_report.md — example report for auto_analysis scheme A (a demonstration of the anti-hallucination iron rules)

Directory structure

statlab_mcp/          # server.py(只注册工具+to_jsonable)+ tools/<组>_<工具>.py
docs/                  # SPEC.md(协议与统计口径)、design/(各工具接口设计文档)、clients.md(接入配置)
samples/               # 入库样例数据 + 生成脚本
tests/                 # pytest + fixtures 生成脚本
data/                  # 使用者亲手造的测试数据(gitignore,不入库)
reports/plots/         # 图片输出(gitignore,按日期归档可随时清理)

License

MIT (Copyright © 2026 周翔宇).

Available Tools

30 tools
analysis_planA

analysis_plan —— 编排层 · 分析计划生成(工具 30,v1.2.0 方案 B 落地)。

把 design/08 决策树变成 100% 确定性规则工具:显式关键词表 + 列类型规则 + 表序优先级, 零 LLM、零模糊匹配;只出计划不执行(执行由外层 agent 逐步调用第一层工具)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/11_analysis_plan.md 同步维护。

参数: question (str): 必填,非空自然语言问题(空白/控制字符 → E1001) file_path (str|None): 可选数据源(与 inline_data 二选一,用于结构感知; 双缺合法 → data_aware=false、data_source=null;双给 → E1001) inline_data (list|dict|None): 内联小数据(同 file_path 二选一规则) column_hints (dict[str,str]|None): {"列名": "数值|类别|日期"} 显式类型覆盖; 值域非法 → E1001;引用不存在列 → 忽略并在 summary 注明

意图表(12 个,忠实转录 design/08 表格 11 行+头部功效路由;完整词表见 design/11): 概览/相关/类别关联/单组均值/两组比较/多组比较/预测连续/预测是否/分群/ 趋势预测/异常检测/样本量功效。多意图命中 → 按 08 表格行序取先者; 全部未命中 → fallback 计划(数据概览三件套+如实告知),不猜测任何方法。

返回: result = {intent, data_aware, data_source, chosen_methods:[{tool, reason_code, matched_keywords}], tool_calls_plan:[{step, tool, params, depends_on, needs?}], report_template:[五章], limitations:[四条]}。 summary 模板:"已生成分析计划:N 步,首选方法 X;计划由确定性规则生成, 执行请逐步调用对应工具"。

示例: analysis_plan("这两个门店的销量差多少是真实的", file_path="sales.csv") analysis_plan("帮我看看这堆数据长什么样", inline_data={"header":["v"],"rows":[[1]]})

Inputs: question (required), file_path, inline_data, column_hints.

anomaly_detectA

anomaly_detect —— 时序组 · 时序异常检测(工具 20,简化实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/06_timeseries.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) date_col / value_col (str): 日期列与数值列 method (str, "stl"): stl / iqr / rolling_zscore stl: statsmodels STL(robust=True) 残差 |resid| > threshold残差标准差 (std(ddof=1) 判据;MAD_std=1.4826median|resid-median| 对"主体集中+ 稀疏厚尾"残差低估尺度,实现期修订弃用,见 statlab_mcp/docs/design/06) iqr: 一阶差分上 IQR 规则(Q1-1.5IQR / Q3+1.5IQR,同探查组口径), threshold 参数不参与 iqr 判据,索引映射回原行 rolling_zscore: 窗口 7 滚动 mean/std(min_periods=3),|z| > threshold threshold (float, 3.0): >0;仅 stl 与 rolling_zscore 使用

保证: 异常点仅报告不剔除;常数序列(尺度 0)无异常并注明。

示例: anomaly_detect("samples/timeseries.csv", date_col="date", value_col="value") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: method, date_col, file_path, threshold, +2 more.

anova_testA

anova_test —— 统计推断组 · 方差分析(工具 7,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/04_inference_batch2.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) group_col (str): 分组列(类别或数值均可,按唯一值分组;2~20 组) value_col (str): 数值列(检验对象) alpha (float, 0.05): 显著性水平 ∈ (0,1)

流程(确定性): 1. 前置:Levene 方差齐性(scipy.stats.levene,稳健中位数版)+ 各组 Shapiro (3<=n<=5000 时执行,违反警示不阻断) 2. 方差齐 -> scipy.stats.f_oneway;方差不齐(Levene p<alpha)-> Welch ANOVA (statsmodels.stats.oneway.anova_oneway(use_var="unequal"),避免手写公式出错) 3. 事后:齐 -> Tukey HSD(statsmodels pairwise_tukeyhsd,含 p 值与族校正); 不齐 -> Games-Howell(手写:libqsturng.qsturng 学生化极差临界值, se=sqrt(si2/ni+sj2/nj),显著判定 = |diff| > q*se/sqrt(2); p 值省略并以"CI 是否含 0"判定,输出注明——statsmodels 无现成实现,诚实披露)

示例: anova_test("samples/clean.csv", group_col="category", value_col="score") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: alpha, file_path, group_col, value_col, +1 more.

backtest_forecastA

backtest_forecast —— 时序组 · 滚动回测(工具 29,v1.2.0 新增)。

time_series_forecast 的可信度自评:滚动窗口回测输出 MAE/RMSE/MAPE, 让预测结论自带"历史表现"背书。前置处理与 forecast 完全同口径 (_prepare_series 五项统一前置),逐窗独立重放以杜绝真值泄漏 (验证窗不含任何由未来观测构造的插值点——design/06 防泄漏节)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/06_timeseries.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json),仅接受本地路径 date_col (str): 日期列;value_col (str): 数值值列(语义与 time_series_forecast 一致) horizon (int): 每窗验证段长度,1 <= horizon <= 有效样本×50%(E1001) windows (int, 3): 回测窗口数,1..10(auto_arima 每窗一次拟合,防耗时爆炸;E1001) method (str, "auto_arima"): auto_arima / naive / seasonal_naive (两个 naive 基线为封闭公式,用于对照;seasonal_naive 的周期逐窗取 _estimate_period,不可估或 > 训练段长时退化为 naive 并记 period_used_fallback)

门槛链(校验顺序红线 D9): 参数合法 → n>=30(低于报错 E1010)→ n >= horizon*(windows+1) 且 train_min = n - windowshorizon >= max(15, 2period_full_est)(E1010 带调参建议) → n<=100000(E1005 防大表卡顿)→ 逐窗计算。

指标: 每窗口逐点 pred/actual/abs_err + 汇总 MAE/RMSE/MAPE; 真实值含 |actual|<=1e-12 时该窗口 MAPE=null 并注明 zero_note(禁止除零假值)。 明细总量上限 10000 点,超出截断最旧窗并记 truncated=true(汇总永不截断)。

局限声明(固定附于 summary 末尾):回测表现不代表未来;未做外部验证。

示例: backtest_forecast("samples/clean.csv", "date", "score", horizon=3) backtest_forecast("samples/clean.csv", "date", "score", horizon=2, windows=2, method="naive") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: method, horizon, windows, date_col, +3 more.

chi_square_testA

chi_square_test —— 统计推断组 · 卡方独立性检验(工具 8,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/04_inference_batch2.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) col_a / col_b (str): 两列类别变量(均须存在;数值列自动等宽分箱 ≤8 箱并注明)

流程(确定性): 1. 分类化:数值列 pd.cut 等宽分箱(箱数=min(8, max(2, 唯一值数)))并注明; 类别唯一值 =1 -> error;>50 -> error(防列联表爆炸) 2. pd.crosstab 列联表;scipy.stats.chi2_contingency(含期望频数表) 3. >20% 单元格期望频数 <5:2x2 -> scipy.stats.fisher_exact(statistic=OR、df=null); 非 2x2 -> 中文报错引导合并类别 4. 效应量 Cramér's V = sqrt(chi2/(n*(min(rows,cols)-1)))(chi2 来自 chi2_contingency, fisher 路径同样给出并注明基于卡方近似) 5. 结论固定模板;summary 注明"关联≠因果"

示例: chi_square_test("samples/clean.csv", col_a="category", col_b="category") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: col_a, col_b, file_path, inline_data.

cluster_analysisA

cluster_analysis —— 建模组 · KMeans 聚类(工具 14,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/05_modeling.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) k (int): 簇数,2 <= k <= 样本数-1(非法中文报错)

口径: 仅数值列(非数值列自动排除并列出);StandardScaler z-score 标准化后 KMeans(n_clusters=k, random_state=42, n_init="auto");质心反标准化回原始单位 (标准化空间质心即簇内均值,反标准化后 = 原空间簇均值,可手算核对); 质心解读强制附簇内样本量;轮廓系数(标准化空间)+ k-1/k+1 同 seed 对照。

示例: cluster_analysis("samples/clean.csv", k=3) inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: k, file_path, inline_data.

confidence_intervalA

confidence_interval —— 统计推断组 · 置信区间(工具 10,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/03_inference_batch1.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) column (str): 分析列(须为数值列) confidence (float, 0.95): 置信水平 ∈ (0,1) method (str, "mean_t"): mean_t / bootstrap_median mean_t: mean ± t_{1-α/2, n-1} * sd/√n(sd 用 ddof=1,与 describe 同口径) bootstrap_median: 局部 default_rng(42) 重采样 1000 次取中位数,2.5%/97.5% 分位数(percentile 法)——每次调用独立可复现(不依赖全局 rng 状态)

边界: n<3 / confidence 越界 / method 非法 / 非数值或缺列 —— 中文报错; 常数列(sd=0)区间退化为点并注明。

示例: confidence_interval("samples/clean.csv", column="income") confidence_interval("samples/clean.csv", column="income", confidence=0.90, method="bootstrap_median") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: column, method, file_path, confidence, +1 more.

correlation_matrixA

correlation_matrix —— 数据探查组 · 相关矩阵(工具 4,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/02_data_exploration_batch2.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json),仅接受本地路径 method (str, "pearson"): pearson / spearman / kendall / kendalltau(逐对取 scipy, 返回对象取 .statistic/.pvalue;pandas corr 无 p 值故不用;kendall 为 kendalltau 的官方别名 v1.1.0 起,两者结果完全相同) p_adjust (str, "fdr_bh"): none / bonferroni / fdr_bh;默认 BH-FDR 并标注; 校正单元 = 实际可计算的上三角对数(常量列对 r/p=null 不参与校正) (statsmodels.multipletests)

返回: 成功 {"status":"ok","result":{...},"summary":"..."};失败 {"status":"error",...} result: {method, n_pairs, p_adjust_method, excluded_columns, correlation, p_value, n_pairwise}(嵌套全矩阵;对角 r=1.0、p=null; 常量列对 r/p=null;n_pairwise 为成对完整样本量)

口径(红队裁决 11):每对成对完整样本;常量列 r/p=null 不参与校正; 数值列 >20 拒绝;排除非数值/全缺失列后 <2 列拒绝;p<0.001 只出现在 summary 文案。

示例: correlation_matrix("samples/clean.csv") correlation_matrix("samples/clean.csv", method="spearman", p_adjust="none") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: method, p_adjust, file_path, inline_data.

data_type_checkA

data_type_check —— 数据探查组 · 列类型识别(工具 2,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/01_data_exploration_batch1.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json),仅接受本地路径(拒绝 UNC)

返回: 成功 {"status":"ok","result":{...},"summary":"一句话中文结论"} 失败 {"status":"error","message":"中文原因"} result: {n_rows, n_columns, columns: {<列名>: {detected_type, n_valid, n_missing, dirty_count, note}}, issue_summary: {mixed_columns, fully_missing_columns, invalid_date_columns}}

判定树(确定性代码;实现期修订 vs 设计文档:数值先于日期,防 "123" 被 to_datetime 误认成日期;mixed 定义 = 数值或日期转换成功数在 (0, 95%) 区间,全部失败则按 category/text 处理): 1. 全缺失列 → missing(不参与任何转换) 2. pandas 数值 dtype → numeric;值全为整数 → integer 3. object 列先试 to_numeric(errors="coerce"):成功 ≥95% → numeric (有失配时 dirty_count=失败数,note 给脏值示例;全成功且全整数 → integer) 4. 未过数值,再试 to_datetime(errors="coerce"):成功 ≥95% → date (失配 = 非法日期,如 2024-02-30,记 dirty_count 并在 note 列示例) 5. 部分可转(成功数在 (0, 95%))→ mixed(两种转换都失败的值 = 脏值) 6. 完全不可转:唯一值 ≤ min(50, 行数×20%) → category(note 给 top3) 否则 → text

示例: data_type_check("samples/dirty.csv") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: file_path, inline_data.

describe_statisticsA

describe_statistics —— 数据探查组 · 描述性统计(工具 1,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/01_data_exploration_batch1.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json),仅接受本地路径(拒绝 UNC)

返回: 成功 {"status":"ok","result":{...},"summary":"一句话中文结论"} 失败 {"status":"error","message":"中文原因"}(error 时无 result 字段) result 结构见设计文档「工具 1」JSON Schema: {n_rows, n_columns, numeric_columns, non_numeric_columns, fully_missing_columns, columns: {<列名>: {n, mean, median, std, min, q1, q3, max, skew, kurtosis, n_missing}}}

统计定义(SPEC 裁决,测试断言口径): - 分位数 q1/q3 = linear 插值(=Excel QUARTILE.INC),Series.quantile 默认即 linear; - std 用 ddof=1(=Excel STDEV.S); - skew = scipy.stats.skew(x, bias=False)(Fisher 样本偏度); - kurtosis = scipy.stats.kurtosis(x, fisher=True, bias=False)(超额峰度,正态=0)。

边界语义(使用者已裁决): - 全缺失列:n=0、n_missing=总行数、其余统计键全 null,不中断整表; - 常数列(std=0):skew/kurtosis=null(方差为 0 无法定义); - n<2:std/q1/q3=null;n<3:skew/kurtosis=null; - 非数值列忽略统计并列入 non_numeric_columns。

示例: describe_statistics("samples/clean.csv") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: file_path, inline_data.

effect_sizeA

effect_size —— 统计推断组 · 效应量(工具 11,简化实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/04_inference_batch2.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) group_col (str): 分组列(须恰好 2 组) value_col (str): 数值列 method (str, "cohens_d"): cohens_d / hedges_g / cliff_delta paired (bool, False): True 时两组样本数必须相等,按"各自有效值序列的 第 i 个"配对(简化语义:无 ID 列时的确定性约定,见设计文档)

口径: cohens_d: |m1-m2|/pooled_sd(pooled_sd 同 hypothesis_test) hedges_g: d * (1 - 3/(4(n1+n2)-9))(小样本修正) cliff_delta: delta = (gt-lt)/(n1n2),gt/lt 为所有跨组值对比较计数(numpy 向量化, 不依赖 mannwhitneyu 的 U 定义,避免方向歧义) CI: 正态近似 se(d/g: sqrt(1/n1+1/n2+d^2/(2(n1+n2)));cliff: sqrt((1-delta^2)/(n1n2))), mean ± 1.96*se;输出注明"正态近似" 阈值(标注为经验惯例):d/g 0.2/0.5/0.8(Cohen);cliff 0.147/0.33/0.474(Romano)

【简化】略过声明: 无 bootstrap CI、无分布假设检验、cliff_delta 无配对版本。

示例: effect_size("samples/clean.csv", group_col="category", value_col="score") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: method, paired, file_path, group_col, +2 more.

feature_importanceA

feature_importance —— 建模组 · 特征重要性(工具 16,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/05_modeling.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) target (str): 目标列(<=20 类 -> 分类随机森林 class_weight=balanced;连续 -> 回归森林) method (str, "permutation"): permutation(打乱验证集特征,验证集思想)/ impurity(训练集内基尼/方差减少;两者都输出,默认 permutation) n_estimators (int, 200): 森林树数 >=10 random_state (int, 42): 森林与划分固定种子 n_repeats (int, 10): permutation 专用,打乱次数 >=1

硬性门槛: n < 50 拒绝(规格);特征重要性排序 + "重要性≠因果"尾注。

第 4.1 条实现(确定性): train_test_split(0.25, random_state) 划分;模型在训练集拟合;impurity 取 feature_importances_;permutation 在测试集上打乱(sklearn.inspection.permutation_importance)。

示例: feature_importance("samples/clean.csv", target="income") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: method, target, file_path, n_repeats, +3 more.

hypothesis_testA

hypothesis_test —— 统计推断组 · 假设检验(工具 6,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/03_inference_batch1.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) column (str): 分析列(须为数值列) test (str, "one_sample"): one_sample / independent / paired group_col (str|None): test=independent 时必填,须恰好 2 组且每组 n>=2 sample2_col (str|None): test=paired 时必填(与 column 成对对齐) mu0 (float, 0.0): one_sample 的 H0 假设均值 alternative (str, "two_sided"): two_sided / less / greater alpha (float, 0.05): 显著性水平 ∈ (0,1)

方法(设计文档口径): one_sample -> scipy.stats.ttest_1samp;independent -> ttest_ind(equal_var=False) (Welch's t,规格硬性规定,df 用 Welch-Satterthwaite 公式手算,跨版本稳定); paired -> ttest_rel(差值 = column - sample2_col,成正态预检对象)。 检验前 Shapiro 预检(3<=n<=5000):违反只警示不阻断,可转用 nonparametric_test (Wilcoxon/Mann-Whitney)。 CI 一律双侧(1-alpha,t 分布);效应量 Cohen's d(单样本|mean-mu0|/sd、 独立 pooled sd、配对差值 sd)。结论文案固定模板 p<alpha 拒绝 H0 / p>=alpha 不能拒绝。

示例: hypothesis_test("samples/clean.csv", column="score", test="one_sample", mu0=70.0) hypothesis_test("samples/clean.csv", column="score", test="independent", group_col="category") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: mu0, test, alpha, column, +5 more.

impute_missingA

impute_missing —— 数据探查组 · 缺失值插补(工具 28,v1.2.0 新增)。

与 missing_report 互补的确定性整治工具:只做规则插补(mean/median/ffill/bfill/constant), 不做任何"智能推断";绝不修改输入文件,插补结果写入 reports/imputed/ 新 CSV 并以 output 返回绝对路径(SPEC 第 11 节文件输出协议)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/01_data_exploration_batch1.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json),仅接受本地路径 columns (list[str]|None): 待插补的数值列清单;缺省 = 全部含缺失的数值列 (显式传入时逐列校验:不存在 → E1008;非数值列含 object 伪数值列 → E1009) strategy (str, "mean"): mean / median / ffill / bfill / constant; mean/median 仅基于有限观测计算(±Inf 不算缺失也不计入均值——排除数进 result) value (float|None): 仅 strategy="constant" 时必填的填充值(有限数, 拒绝 NaN/Inf/bool);其它策略携带本参数 → E1001

边界(钉死): - 无任何可插补对象 → E1012 中文报错,三种情形 message 独立: 全表无缺失 / 指定列均无缺失 / 缺失仅位于非数值列; - 列全缺失且策略为 mean/median/ffill/bfill 时无来源可用 → 该列跳过原样保留, 在 result.skipped_columns 与 summary 如实注明(不报错);constant 对全缺失列生效; - 输出文件 = reports/imputed/YYYYmmdd/impute_missing_<干名>_<策略>_YYYYmmdd_HHMMSS_fff.csv (utf-8-sig;Excel 公式注入转义与控制字符清洗见 SPEC 第 11 节第 5 条)。

返回: 成功 result 含 {columns_processed:[{column,strategy,filled,value_or_direction, excluded_nonfinite,residual_missing}], skipped_columns:[...], output_dir} + 顶层 output = 插补文件绝对路径。 局限声明(固定附于 summary 末尾):插补值为确定性规则估计,会低估方差、可能引入偏差, 后续分析请注明使用了插补数据。

示例: impute_missing("samples/dirty.csv") # 默认全部数值缺失列、均值 impute_missing("samples/dirty.csv", columns=["score"], strategy="median") impute_missing("samples/dirty.csv", columns=["note"], strategy="constant", value=0) inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: value, columns, strategy, file_path, +1 more.

linear_regressionA

linear_regression —— 建模组 · 线性回归(工具 12,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/05_modeling.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) target (str): 连续因变量(数值列) features (list[str]): 自变量(数值列直用;类别列自动 one-hot 并输出映射) add_constant (bool, True): 是否加截距(False 时 GOF 指标参考意义受限,注明) alpha (float, 0.05): 显著性阈值(报告用,∈(0,1))

口径: statsmodels OLS 矩阵接口(禁 formula);类别列 get_dummies(drop_first=False) + 映射; 零方差列自动剔除并报告;缺失 listwise dropna 并注明"已剔除 N 行"; n <= 设计矩阵列数+2 拒绝(无法稳定估计);VIF>10 标注强共线性; 残差 Shapiro + Durbin-Watson;残差诊断图(残差vs拟合 + 直方图,image 顶层)。

示例: linear_regression("samples/clean.csv", target="income", features=["age"]) linear_regression("samples/clean.csv", target="score", features=["age", "category"]) inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: alpha, target, features, file_path, +2 more.

logistic_regressionA

logistic_regression —— 建模组 · 逻辑回归(工具 13,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/05_modeling.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) target (str): 二分类目标列(恰好 2 类;类名映射为 0/1 输出 label_mapping) features (list[str]): 数值特征(本工具不做 one-hot,规格未要求;非数值报错) test_size (float, 0.3): train/test 分层划分比例 ∈(0,1) random_state (int, 42): 划分与复制的固定随机种子 class_weight (str, "balanced"): balanced 用少数类确定性复制实现(statsmodels Logit 无内置类权重,如实披露;复制样本 w=n/(2*n_class) 于训练集内,seed 固定)

固定五项输出(规格硬性): 类别分布 / accuracy(仅对照,受类别不平衡影响)/ 混淆矩阵 / ROC-AUC+95%CI (Hanley-McNeil 正态近似)/ 特征 OR 与 p 值(statsmodels Logit 矩阵接口, OR=exp(beta))。ConvergenceWarning(完美可分)-> convergence_warning 注明系数不稳定。

示例: logistic_regression("tests/fixtures/binary_noisy.csv", target="label", features=["score"]) inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: target, features, file_path, test_size, +3 more.

missing_reportA

missing_report —— 数据探查组 · 缺失报告(工具 3,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/01_data_exploration_batch1.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json),仅接受本地路径(拒绝 UNC)

返回: 成功 {"status":"ok","result":{...},"summary":"一句话中文结论"} 失败 {"status":"error","message":"中文原因"} result: {n_rows, n_columns, total_missing, overall_missing_rate, columns: {<列名>: {n_missing, missing_rate}}, complete_rows, rows_with_missing, patterns: [{columns, rows, note}]}

缺失定义: 空单元格与空串在读表层统一为 NaN(read_csv 默认),一律计入缺失; 全缺失列 rate=1.0 并注记;成对模式 = 两列同时缺失的行数(同源故障信号); patterns 最多 10 条,按缺失行数降序;无缺失时 patterns=[]。

示例: missing_report("samples/dirty.csv") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: file_path, inline_data.

nonparametric_testA

nonparametric_test —— 统计推断组 · 非参数检验(工具 26,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/09_inference_batch3.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) test (str, "wilcoxon"): wilcoxon(配对)/ mann_whitney(两组独立)/ kruskal_wallis(多组) column (str): test=wilcoxon 时必填(配对的第一组测量) sample2_col (str): test=wilcoxon 时必填(配对第二组测量) group_col (str): test=mann_whitney / kruskal_wallis 时必填(分组列) value_col (str): test=mann_whitney / kruskal_wallis 时必填(数值列) alpha (float, 0.05): 显著性水平 ∈ (0,1) alternative (str, "two_sided"): two_sided / less / greater(仅 wilcoxon 与 mann_whitney 生效;kruskal_wallis 恒为双侧)

口径(设计文档 09 钉死): wilcoxon: scipy.stats.wilcoxon(zero_method="wilcox", correction=False, method="auto")——0 差剔除(zero_method=wilcox 语义);method="auto": 小样本无 ties 用精确分布,否则正态近似;效应量 matched rank-biserial r = 2×(正秩和)/n(n+1) − 1,等价式 1 − 4W/(n(n+1))(W=scipy 返回的较小秩和), 方向以 mean(column − sample2_col) 符号定(column 高为正侧),n=剔除 0 差后的对数。 mann_whitney: scipy.stats.mannwhitneyu(use_continuity=True, method="auto") ——注明 ties 时用正态近似含连续性校正;效应量 rank-biserial r = 2U/(n1·n2) − 1(U=scipy 对 group1 的统计量),方向 group1 高为正侧。 kruskal_wallis: scipy.stats.kruskal——统计量 H(未做 ties 校正,注明); 效应量 epsilon² = H/(N−1)(= (ΣᵢRᵢ²/nᵢ − 3(N+1))/(N−1),N 为总样本量), 近似解释为"组间秩差异占总秩变异的比例"。 结论固定模板:p<α 拒绝 H0 / p≥α 不能拒绝;局限声明(非参检验功效通常低于 参数检验、ties 处理、样本量)。

边界: 样本不足(wilcoxon 有效对数 n<5;mann_whitney 每组 n<2;kruskal 组数 2~20 且每组 n>=2)、差值无变异/常量组、alpha/alternative 非法、NaN/Inf 防御—— 一律中文报错;无图。

示例: nonparametric_test("samples/clean.csv", test="mann_whitney", group_col="category", value_col="score") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: test, alpha, column, file_path, +5 more.

normality_testA

normality_test —— 统计推断组 · 正态性检验(工具 9,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/03_inference_batch1.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) column (str): 分析列(须为数值列) method (str, "auto"): auto / shapiro / dagostino auto: n<=5000 -> Shapiro-Wilk(scipy 官方建议 3~5000);5000<n<=100000 -> D'Agostino-Pearson(scipy.stats.normaltest);n>100000 -> 中文报错提示抽样

输出: method_used, n, statistic, p_value, skew(Fisher 样本偏度,同 describe), kurtosis(超额峰度,正态=0), normal(判定 = p_value > 0.05), threshold_alpha(固定 0.05 并在输出注明)

边界: n<3 / 常数列(方差 0)/ 显式 shapiro 但 n>5000(scipy 限制)/ dagostino 且 n<8(scipy 要求)/ 非数值或缺失列 —— 全部中文报错。

示例: normality_test("samples/clean.csv", column="score") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: column, method, file_path, inline_data.

outlier_detectA

outlier_detect —— 数据探查组 · 异常值检测(工具 5,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/02_data_exploration_batch2.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json),仅接受本地路径 method (str, "iqr"): 仅支持 iqr(规格 4 唯一定义;zscore 场景在时序组 rolling_zscore)

口径: IQR 法:lower = Q1 - 1.5IQR,upper = Q3 + 1.5IQR(分位数 linear 插值,同 describe); 异常值 = 有效值中 <lower 或 >upper 的值;绝不自动剔除,只报告; 数值列有效值 n<4 → IQR 无定义,bounds=null、n_outliers=0;常量列 bounds 相等无异常; 非数值列跳过并列入 skipped_columns;单列异常值超 100 个时截断显示并注明。

图(附录 D): 并列箱线图(异常值红色 scatter);文件名 outlier_detect_all_YYYYmmdd_HHMMSS.png 存 reports/plots/;返回 JSON 顶层附加 image(绝对路径,禁 base64,与 result 平级)。

示例: outlier_detect("samples/dirty.csv") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: method, file_path, inline_data.

pca_analysisA

pca_analysis —— 建模组 · 主成分分析(工具 15,核心实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/05_modeling.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) n_components (int): 主成分数,1 <= n <= min(样本数, 特征数)(超界中文报错)

口径: 仅数值列(自动排除列出);StandardScaler 标准化后 sklearn PCA(random_state=42, PCA 本身无随机性,仅为接口一致);输出方差解释率+累积; 载荷反标准化 = 成分向量 × 特征标准差(原单位近似权重,规格要求); 载荷图(方差解释条形 + 前两主成分载荷向量,image 顶层); 结论注明"主成分是特征的线性组合,不等于业务因子"。

示例: pca_analysis("samples/clean.csv", n_components=2) inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: file_path, inline_data, n_components.

plot_boxA

plot_box —— 可视化组 · 箱线图(工具 25,核心实现)。

单列箱线图:图上标五数概括(min/q1/中位/q3/max)与 IQR 异常数(同 outlier_detect 口径, 但仅单列、无异常点导出表——异常定位请用工具 5)。 inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: column, file_path, inline_data.

plot_forecastA

plot_forecast —— 可视化组 · 时序折线图(工具 24,核心实现)。

原值折线 + 7 日移动平均线;仅作图不预测(预测见工具 17)。 五项统一前置由 _common._prepare_series 承载(插值/聚合/时区均报告)。 inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: date_col, file_path, value_col, inline_data.

plot_heatmapA

plot_heatmap —— 可视化组 · 相关热力图(工具 23,核心实现)。

全部数值列两两 Pearson 相关热力图(格内标 r;常量列对应 r=null)。 矩阵用 pandas .corr()(与 correlation_matrix 的 scipy pearsonr 同公式), 本工具不做 p 值与校正(与工具 4 明确分工)。 inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: file_path, inline_data.

plot_histogramA

plot_histogram —— 可视化组 · 直方图(工具 22,核心实现)。

单列分布直方图,图上标 n/mean/std;分箱 = min(40, max(8, ceil(sqrt(n))))。 inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: column, file_path, inline_data.

plot_scatterA

plot_scatter —— 可视化组 · 散点图(工具 21,核心实现)。

生成 x-y 散点图,图上标注 Pearson r 与样本量;缺失按成对剔除并报数。 图协议走 _common.save_plot(附录 D);返回顶层 image 绝对路径。 inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: x_col, y_col, file_path, inline_data.

power_analysisA

power_analysis —— 统计推断组 · 功效分析/样本量计算(工具 27,v1.1.0 新增)。

回答两类问题:「要检出效应量,需要多少样本」与「给定样本量能检出多大效应 / 实际功效多少」。 纯封闭公式计算(statsmodels.stats.power 精确非中心 t / 正态近似),零 LLM、确定性输出。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/10_power_analysis.md 同步维护。

参数: scenario (str): one_sample_t(单样本/配对 t,n=总样本)/ two_sample_t(独立两样本 t,n=每组样本量)/ two_proportions(两独立比例,n=每组样本量) effect_size (float|None): Cohen's d(仅 t 系场景);与 n 至少提供一个;必须 >0 的有限数 n (int|None): 样本量;与 effect_size 至少提供一个;必须是 >=2 的整数 p1 (float|None), p2 (float|None): 两个总体比例 ∈(0,1),仅 two_proportions 场景且须成对; 工具内部换算 Cohen's h = 2·arcsin√p₁ − 2·arcsin√p₂ 并随 result/summary 报告 alpha (float, 0.05): 显著性水平 ∈(0,1) power_target (float, 0.80): 目标功效(求 n 时使用)∈(0,1) alternative (str, "two_sided"): two_sided / less / greater

模式决策表(任务书钉死): 只给效应侧 → mode="solve_n"(求 n_required_exact 与 n_recommended=向上取整) 只给 n → mode="detect_effect"(可检出标准化效应) 都给 → mode="verify"(返回实际 power 验算结果) 都不给 → E1001 中文报错

返回: 成功 {"status":"ok","result":{...},"summary":"..."}; result 含 scenario/n_each/n_total 及各模式专属字段;两比例场景另报 cohens_h。 局限声明(固定附在 summary 末尾):功效计算依赖效应量假设,实际效应量未知时结论仅供参考。

示例: power_analysis("two_sample_t", effect_size=0.5) # 经典配置 → 64/组 power_analysis("one_sample_t", n=34) # 反查可检出的 d power_analysis("two_proportions", p1=0.50, p2=0.80, n=100) # verify 实际功效

Inputs: scenario (required), n, p1, p2, +4 more.

seasonal_decomposeA

seasonal_decompose —— 时序组 · 季节分解(工具 18,简化实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/06_timeseries.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) date_col / value_col (str): 日期列与数值列 period (int|None, None): 周期;默认 FFT 主频自动估计(_common._estimate_period) model (str, "auto"): additive / multiplicative / auto auto: 全正值 -> multiplicative,否则 additive(注明选择依据)

口径: statsmodels.seasonal_decompose(extrapolate_trend="freq"); multiplicative 要求全正值(显式指定且含非正值 -> 中文报错)。 输出分量统计 + 最后完整周期季节因子 + 4 子图(image 顶层)。

示例: seasonal_decompose("samples/timeseries.csv", date_col="date", value_col="value") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: model, period, date_col, file_path, +2 more.

time_series_forecastA

time_series_forecast —— 时序组 · 时间序列预测(工具 17,简化实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/06_timeseries.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) date_col / value_col (str): 日期列与数值列 horizon (int): 预测步数,1 <= horizon <= 样本量*50%(超限中文报错)

口径: auto_arima(pmdarima,stepwise=True, random_state=42, max_order=8)自动定阶; 季节可估判定(FFT 主频 period 且 n>=2*period)-> SARIMA 否则 ARIMA 并注明; 五项统一前置由 _common._prepare_series 完成(插值/聚合/时区等均入 metadata); 输出预测值 + 95% CI(predict(return_conf_int=True))+ 历史/预测图(image 顶层); 常数列退化为均值预测并注明。

示例: time_series_forecast("samples/timeseries.csv", date_col="date", value_col="value", horizon=14) inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: horizon, date_col, file_path, value_col, +1 more.

trend_analysisA

trend_analysis —— 时序组 · 趋势分析(工具 19,简化实现)。

docstring = agent 使用说明书,与 statlab_mcp/docs/design/06_timeseries.md 同步维护。

参数: file_path (str): 本地数据文件(csv/tsv/xlsx/json) date_col / value_col (str): 日期列与数值列 method (str, "mann_kendall"): mann_kendall / theil_sen

口径: Mann-Kendall:scipy.stats.kendalltau(y, 时间序号) 的 tau 与 p(MK 检验的 tau 统计量 + 正态近似双侧 p,scipy 官方实现,输出注明该口径); Theil-Sen 斜率:点对斜率中位数(n<=2000 全枚举;n>2000 固定 seed 抽样 50000 对并注明);两种方法都输出 tau/p/slope,method 决定 slope 的计算主口径 (theil_sen 时 slope 为点对中位数;mann_kendall 时 slope 同样用 Theil-Sen 斜率, tau 为主统计量)。 含季节成分时输出"趋势结论需谨慎"警示(设计文档:不校正)。

示例: trend_analysis("samples/timeseries.csv", date_col="date", value_col="value") inline 数据: 本工具支持可选 inline_data 参数(v1.2.0 起):与 file_path 二选一, 支持 records 数组或 {"header": [...], "rows": [[...], ...]} 对象两种形态; 规模上限/类型域/data_source 来源标注见 statlab_mcp/docs/SPEC.md 第 12 节。

Inputs: method, date_col, file_path, value_col, +1 more.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 30 tools

    Disambiguation4/5

    Tools are organized into clear functional groups (exploration, inference, modeling, time series, visualization, orchestration) and descriptions explicitly cross-reference each other to resolve boundary cases (e.g., plot_heatmap defers p-values to correlation_matrix; outlier_detect points time-series cases to anomaly_detect). However, genuine overlap remains: four tools handle two-group comparison (hypothesis_test, anova_test, nonparametric_test, effect_size) and correlation_matrix vs plot_heatmap compute essentially the same matrix, so an agent could hesitate on selection.

    Naming Consistency4/5

    All names are clean snake_case with recognizable domain nouns, and subfamilies are internally consistent (plot_*, *_test, *_analysis, *_detect). The main deviation is verb placement: some tools are verb-first (describe_statistics, impute_missing, backtest_forecast) while others are verb-last (outlier_detect, anomaly_detect, seasonal_decompose), but the pattern remains readable and predictable.

    Tool Count3/5

    30 tools is a heavy surface, above the 16-25 band that already feels dense, and would strain an agent's selection space. However, the server's scope is genuinely broad—six distinct statistical domains—and each tool serves a specific analytical purpose, so the count is defensible even if it approaches the upper limit of what is reasonable for one MCP server.

    Completeness4/5

    Coverage is comprehensive for the stated purpose: exploration (describe/type/missing/correlation/outlier/impute), inference (parametric, nonparametric, chi-square, ANOVA, CI, effect size, power), modeling (linear/logistic regression, clustering, PCA, feature importance), time series (forecast/backtest/decompose/trend/anomaly), visualization, and an orchestration planner. Minor gaps: no stationarity test (e.g., ADF) for time series, no general-purpose bar or line chart for categorical data, and no way to apply a fitted model to new data.

    Maintenance

    ActivityInactive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to perform statistical process control calculations using validated, deterministic tools such as control charts, capability analysis, and tolerance intervals.
      3
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A statistical analysis MCP server offering 30 tools for descriptive statistics, hypothesis tests, regression, and time series, all returning Markdown reports with automatic interpretations to enable AI agents to perform comprehensive data analysis.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides a virtual statistician for AI agents, offering real statistical methods such as design of experiments, hypothesis testing, regression, and process control. It includes an advisor tool to recommend appropriate analyses and generates plain-language interpretations of results.
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables agents to run zero-dependency statistical modeling and data analysis through MCP, including multivariate linear regression via gradient descent, anomaly detection, time-series forecasting, hypothesis testing, and PCA dimensionality reduction.
      7
      MIT