aigroup-econ-mcp 0.4.1__py3-none-any.whl → 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of aigroup-econ-mcp might be problematic. Click here for more details.

@@ -0,0 +1,416 @@
1
+ """
2
+ 工具描述模块
3
+ 统一管理所有MCP工具的描述信息,便于维护和复用
4
+ """
5
+
6
+ from typing import Dict, Any, List
7
+ from pydantic import Field
8
+
9
+
10
+ class ToolDescription:
11
+ """工具描述类"""
12
+
13
+ def __init__(self, name: str, description: str, field_descriptions: Dict[str, str] = None):
14
+ self.name = name
15
+ self.description = description
16
+ self.field_descriptions = field_descriptions or {}
17
+
18
+ def get_field_description(self, field_name: str, default: str = "") -> str:
19
+ """获取字段描述"""
20
+ return self.field_descriptions.get(field_name, default)
21
+
22
+
23
+ # ============================================================================
24
+ # 基础统计工具描述 (5个)
25
+ # ============================================================================
26
+
27
+ DESCRIPTIVE_STATISTICS = ToolDescription(
28
+ name="descriptive_statistics",
29
+ description="计算描述性统计量\n\n支持三种输入方式(按优先级):\n1. file_path: 文件路径 (如 \"data.csv\")\n2. file_content: 文件内容字符串\n3. data: 直接传入数据字典",
30
+ field_descriptions={
31
+ "file_path": "CSV/JSON文件路径",
32
+ "file_content": "CSV/JSON文件内容",
33
+ "file_format": "文件格式(csv/json/auto)",
34
+ "data": "数据字典(直接数据输入)"
35
+ }
36
+ )
37
+
38
+ OLS_REGRESSION = ToolDescription(
39
+ name="ols_regression",
40
+ description="OLS回归分析\n\n支持文件输入或直接数据输入。文件格式示例:\nCSV: 最后一列为因变量,其余列为自变量",
41
+ field_descriptions={
42
+ "file_path": "CSV/JSON文件路径",
43
+ "file_content": "CSV/JSON文件内容",
44
+ "file_format": "文件格式",
45
+ "y_data": "因变量(直接输入)",
46
+ "x_data": "自变量(直接输入)",
47
+ "feature_names": "特征名称"
48
+ }
49
+ )
50
+
51
+ HYPOTHESIS_TESTING = ToolDescription(
52
+ name="hypothesis_testing",
53
+ description="假设检验 - 支持文件或直接数据输入",
54
+ field_descriptions={
55
+ "file_path": "文件路径",
56
+ "file_content": "文件内容",
57
+ "file_format": "文件格式",
58
+ "data": "第一组数据",
59
+ "data2": "第二组数据",
60
+ "test_type": "检验类型(t_test/adf)"
61
+ }
62
+ )
63
+
64
+ TIME_SERIES_ANALYSIS = ToolDescription(
65
+ name="time_series_analysis",
66
+ description="时间序列分析 - 支持文件或直接数据输入",
67
+ field_descriptions={
68
+ "file_path": "文件路径",
69
+ "file_content": "文件内容",
70
+ "file_format": "文件格式",
71
+ "data": "时间序列数据"
72
+ }
73
+ )
74
+
75
+ CORRELATION_ANALYSIS = ToolDescription(
76
+ name="correlation_analysis",
77
+ description="相关性分析 - 支持文件或直接数据输入",
78
+ field_descriptions={
79
+ "file_path": "文件路径",
80
+ "file_content": "文件内容",
81
+ "file_format": "文件格式",
82
+ "data": "多变量数据",
83
+ "method": "相关系数类型"
84
+ }
85
+ )
86
+
87
+
88
+ # ============================================================================
89
+ # 面板数据工具描述 (4个)
90
+ # ============================================================================
91
+
92
+ PANEL_FIXED_EFFECTS = ToolDescription(
93
+ name="panel_fixed_effects",
94
+ description="固定效应模型 - 支持文件输入",
95
+ field_descriptions={
96
+ "file_path": "CSV文件路径。CSV格式要求:必须包含实体ID列(列名含entity_id/id/entity/firm/company/country/region之一)和时间列(列名含time_period/time/date/year/month/period/quarter之一)",
97
+ "file_content": "文件内容",
98
+ "file_format": "文件格式",
99
+ "y_data": "因变量数据",
100
+ "x_data": "自变量数据",
101
+ "entity_ids": "实体ID列表",
102
+ "time_periods": "时间周期列表",
103
+ "feature_names": "特征名称",
104
+ "entity_effects": "是否包含实体效应",
105
+ "time_effects": "是否包含时间效应"
106
+ }
107
+ )
108
+
109
+ PANEL_RANDOM_EFFECTS = ToolDescription(
110
+ name="panel_random_effects",
111
+ description="随机效应模型 - 支持文件输入",
112
+ field_descriptions={
113
+ "file_path": "CSV文件路径。CSV格式要求:必须包含实体ID列(列名含entity_id/id/entity/firm/company/country/region之一)和时间列(列名含time_period/time/date/year/month/period/quarter之一)",
114
+ "file_content": "文件内容",
115
+ "file_format": "文件格式",
116
+ "y_data": "因变量数据",
117
+ "x_data": "自变量数据",
118
+ "entity_ids": "实体ID列表",
119
+ "time_periods": "时间周期列表",
120
+ "feature_names": "特征名称",
121
+ "entity_effects": "是否包含实体效应",
122
+ "time_effects": "是否包含时间效应"
123
+ }
124
+ )
125
+
126
+ PANEL_HAUSMAN_TEST = ToolDescription(
127
+ name="panel_hausman_test",
128
+ description="Hausman检验 - 支持文件输入",
129
+ field_descriptions={
130
+ "file_path": "CSV文件路径。CSV格式要求:必须包含实体ID列(列名含entity_id/id/entity/firm/company/country/region之一)和时间列(列名含time_period/time/date/year/month/period/quarter之一)",
131
+ "file_content": "文件内容",
132
+ "file_format": "文件格式",
133
+ "y_data": "因变量数据",
134
+ "x_data": "自变量数据",
135
+ "entity_ids": "实体ID列表",
136
+ "time_periods": "时间周期列表",
137
+ "feature_names": "特征名称"
138
+ }
139
+ )
140
+
141
+ PANEL_UNIT_ROOT_TEST = ToolDescription(
142
+ name="panel_unit_root_test",
143
+ description="面板单位根检验 - 支持文件输入",
144
+ field_descriptions={
145
+ "file_path": "CSV文件路径。CSV格式要求:必须包含实体ID列(列名含entity_id/id/entity/firm/company/country/region之一)和时间列(列名含time_period/time/date/year/month/period/quarter之一)。数据量要求:至少3个实体,每个实体至少5个时间点",
146
+ "file_content": "文件内容",
147
+ "file_format": "文件格式",
148
+ "data": "时间序列数据",
149
+ "y_data": "因变量数据",
150
+ "x_data": "自变量数据",
151
+ "entity_ids": "实体ID列表",
152
+ "time_periods": "时间周期列表",
153
+ "feature_names": "特征名称",
154
+ "test_type": "检验类型"
155
+ }
156
+ )
157
+
158
+
159
+ # ============================================================================
160
+ # 高级时间序列工具描述 (5个)
161
+ # ============================================================================
162
+
163
+ VAR_MODEL_ANALYSIS = ToolDescription(
164
+ name="var_model_analysis",
165
+ description="VAR模型分析 - 支持文件输入",
166
+ field_descriptions={
167
+ "file_path": "文件路径",
168
+ "file_content": "文件内容",
169
+ "file_format": "文件格式",
170
+ "data": "多变量时间序列数据",
171
+ "max_lags": "最大滞后阶数",
172
+ "ic": "信息准则类型"
173
+ }
174
+ )
175
+
176
+ VECM_MODEL_ANALYSIS = ToolDescription(
177
+ name="vecm_model_analysis",
178
+ description="VECM模型分析 - 支持文件输入",
179
+ field_descriptions={
180
+ "file_path": "文件路径",
181
+ "file_content": "文件内容",
182
+ "file_format": "文件格式",
183
+ "data": "多变量时间序列数据",
184
+ "coint_rank": "协整秩",
185
+ "deterministic": "确定性项类型",
186
+ "max_lags": "最大滞后阶数"
187
+ }
188
+ )
189
+
190
+ GARCH_MODEL_ANALYSIS = ToolDescription(
191
+ name="garch_model_analysis",
192
+ description="GARCH模型分析 - 支持文件输入",
193
+ field_descriptions={
194
+ "file_path": "文件路径",
195
+ "file_content": "文件内容",
196
+ "file_format": "文件格式",
197
+ "data": "时间序列数据",
198
+ "order": "GARCH模型阶数",
199
+ "dist": "误差分布类型"
200
+ }
201
+ )
202
+
203
+ STATE_SPACE_MODEL_ANALYSIS = ToolDescription(
204
+ name="state_space_model_analysis",
205
+ description="状态空间模型分析 - 支持文件输入",
206
+ field_descriptions={
207
+ "file_path": "文件路径",
208
+ "file_content": "文件内容",
209
+ "file_format": "文件格式",
210
+ "data": "时间序列数据",
211
+ "state_dim": "状态维度",
212
+ "observation_dim": "观测维度",
213
+ "trend": "是否包含趋势项",
214
+ "seasonal": "是否包含季节项",
215
+ "period": "季节周期"
216
+ }
217
+ )
218
+
219
+ VARIANCE_DECOMPOSITION_ANALYSIS = ToolDescription(
220
+ name="variance_decomposition_analysis",
221
+ description="方差分解分析 - 支持文件输入",
222
+ field_descriptions={
223
+ "file_path": "文件路径",
224
+ "file_content": "文件内容",
225
+ "file_format": "文件格式",
226
+ "data": "多变量时间序列数据",
227
+ "periods": "分解期数",
228
+ "max_lags": "最大滞后阶数"
229
+ }
230
+ )
231
+
232
+
233
+ # ============================================================================
234
+ # 机器学习工具描述 (6个)
235
+ # ============================================================================
236
+
237
+ RANDOM_FOREST_REGRESSION_ANALYSIS = ToolDescription(
238
+ name="random_forest_regression_analysis",
239
+ description="随机森林回归 - 支持文件输入",
240
+ field_descriptions={
241
+ "file_path": "文件路径",
242
+ "file_content": "文件内容",
243
+ "file_format": "文件格式",
244
+ "y_data": "因变量数据",
245
+ "x_data": "自变量数据",
246
+ "feature_names": "特征名称",
247
+ "n_estimators": "树的数量",
248
+ "max_depth": "最大深度"
249
+ }
250
+ )
251
+
252
+ GRADIENT_BOOSTING_REGRESSION_ANALYSIS = ToolDescription(
253
+ name="gradient_boosting_regression_analysis",
254
+ description="梯度提升树回归 - 支持文件输入",
255
+ field_descriptions={
256
+ "file_path": "文件路径",
257
+ "file_content": "文件内容",
258
+ "file_format": "文件格式",
259
+ "y_data": "因变量数据",
260
+ "x_data": "自变量数据",
261
+ "feature_names": "特征名称",
262
+ "n_estimators": "树的数量",
263
+ "learning_rate": "学习率",
264
+ "max_depth": "最大深度"
265
+ }
266
+ )
267
+
268
+ LASSO_REGRESSION_ANALYSIS = ToolDescription(
269
+ name="lasso_regression_analysis",
270
+ description="Lasso回归 - 支持文件输入",
271
+ field_descriptions={
272
+ "file_path": "文件路径",
273
+ "file_content": "文件内容",
274
+ "file_format": "文件格式",
275
+ "y_data": "因变量数据",
276
+ "x_data": "自变量数据",
277
+ "feature_names": "特征名称",
278
+ "alpha": "正则化参数"
279
+ }
280
+ )
281
+
282
+ RIDGE_REGRESSION_ANALYSIS = ToolDescription(
283
+ name="ridge_regression_analysis",
284
+ description="Ridge回归 - 支持文件输入",
285
+ field_descriptions={
286
+ "file_path": "文件路径",
287
+ "file_content": "文件内容",
288
+ "file_format": "文件格式",
289
+ "y_data": "因变量数据",
290
+ "x_data": "自变量数据",
291
+ "feature_names": "特征名称",
292
+ "alpha": "正则化参数"
293
+ }
294
+ )
295
+
296
+ CROSS_VALIDATION_ANALYSIS = ToolDescription(
297
+ name="cross_validation_analysis",
298
+ description="交叉验证 - 支持文件输入",
299
+ field_descriptions={
300
+ "file_path": "文件路径",
301
+ "file_content": "文件内容",
302
+ "file_format": "文件格式",
303
+ "y_data": "因变量数据",
304
+ "x_data": "自变量数据",
305
+ "feature_names": "特征名称",
306
+ "model_type": "模型类型",
307
+ "cv_folds": "交叉验证折数",
308
+ "scoring": "评分指标"
309
+ }
310
+ )
311
+
312
+ FEATURE_IMPORTANCE_ANALYSIS_TOOL = ToolDescription(
313
+ name="feature_importance_analysis_tool",
314
+ description="特征重要性分析 - 支持文件输入",
315
+ field_descriptions={
316
+ "file_path": "文件路径",
317
+ "file_content": "文件内容",
318
+ "file_format": "文件格式",
319
+ "y_data": "因变量数据",
320
+ "x_data": "自变量数据",
321
+ "feature_names": "特征名称",
322
+ "method": "分析方法",
323
+ "top_k": "显示前K个重要特征"
324
+ }
325
+ )
326
+
327
+
328
+ # ============================================================================
329
+ # 工具描述映射
330
+ # ============================================================================
331
+
332
+ TOOL_DESCRIPTIONS: Dict[str, ToolDescription] = {
333
+ # 基础统计工具
334
+ "descriptive_statistics": DESCRIPTIVE_STATISTICS,
335
+ "ols_regression": OLS_REGRESSION,
336
+ "hypothesis_testing": HYPOTHESIS_TESTING,
337
+ "time_series_analysis": TIME_SERIES_ANALYSIS,
338
+ "correlation_analysis": CORRELATION_ANALYSIS,
339
+
340
+ # 面板数据工具
341
+ "panel_fixed_effects": PANEL_FIXED_EFFECTS,
342
+ "panel_random_effects": PANEL_RANDOM_EFFECTS,
343
+ "panel_hausman_test": PANEL_HAUSMAN_TEST,
344
+ "panel_unit_root_test": PANEL_UNIT_ROOT_TEST,
345
+
346
+ # 高级时间序列工具
347
+ "var_model_analysis": VAR_MODEL_ANALYSIS,
348
+ "vecm_model_analysis": VECM_MODEL_ANALYSIS,
349
+ "garch_model_analysis": GARCH_MODEL_ANALYSIS,
350
+ "state_space_model_analysis": STATE_SPACE_MODEL_ANALYSIS,
351
+ "variance_decomposition_analysis": VARIANCE_DECOMPOSITION_ANALYSIS,
352
+
353
+ # 机器学习工具
354
+ "random_forest_regression_analysis": RANDOM_FOREST_REGRESSION_ANALYSIS,
355
+ "gradient_boosting_regression_analysis": GRADIENT_BOOSTING_REGRESSION_ANALYSIS,
356
+ "lasso_regression_analysis": LASSO_REGRESSION_ANALYSIS,
357
+ "ridge_regression_analysis": RIDGE_REGRESSION_ANALYSIS,
358
+ "cross_validation_analysis": CROSS_VALIDATION_ANALYSIS,
359
+ "feature_importance_analysis_tool": FEATURE_IMPORTANCE_ANALYSIS_TOOL,
360
+ }
361
+
362
+
363
+ def get_tool_description(tool_name: str) -> ToolDescription:
364
+ """获取工具描述"""
365
+ if tool_name not in TOOL_DESCRIPTIONS:
366
+ raise ValueError(f"未知的工具名称: {tool_name}")
367
+ return TOOL_DESCRIPTIONS[tool_name]
368
+
369
+
370
+ def get_all_tool_names() -> List[str]:
371
+ """获取所有工具名称"""
372
+ return list(TOOL_DESCRIPTIONS.keys())
373
+
374
+
375
+ def get_field_description(tool_name: str, field_name: str, default: str = "") -> str:
376
+ """获取指定工具的字段描述"""
377
+ tool_desc = get_tool_description(tool_name)
378
+ return tool_desc.get_field_description(field_name, default)
379
+
380
+
381
+ # 导出主要类和函数
382
+ __all__ = [
383
+ "ToolDescription",
384
+ "TOOL_DESCRIPTIONS",
385
+ "get_tool_description",
386
+ "get_all_tool_names",
387
+ "get_field_description",
388
+
389
+ # 基础统计工具
390
+ "DESCRIPTIVE_STATISTICS",
391
+ "OLS_REGRESSION",
392
+ "HYPOTHESIS_TESTING",
393
+ "TIME_SERIES_ANALYSIS",
394
+ "CORRELATION_ANALYSIS",
395
+
396
+ # 面板数据工具
397
+ "PANEL_FIXED_EFFECTS",
398
+ "PANEL_RANDOM_EFFECTS",
399
+ "PANEL_HAUSMAN_TEST",
400
+ "PANEL_UNIT_ROOT_TEST",
401
+
402
+ # 高级时间序列工具
403
+ "VAR_MODEL_ANALYSIS",
404
+ "VECM_MODEL_ANALYSIS",
405
+ "GARCH_MODEL_ANALYSIS",
406
+ "STATE_SPACE_MODEL_ANALYSIS",
407
+ "VARIANCE_DECOMPOSITION_ANALYSIS",
408
+
409
+ # 机器学习工具
410
+ "RANDOM_FOREST_REGRESSION_ANALYSIS",
411
+ "GRADIENT_BOOSTING_REGRESSION_ANALYSIS",
412
+ "LASSO_REGRESSION_ANALYSIS",
413
+ "RIDGE_REGRESSION_ANALYSIS",
414
+ "CROSS_VALIDATION_ANALYSIS",
415
+ "FEATURE_IMPORTANCE_ANALYSIS_TOOL",
416
+ ]
@@ -7,7 +7,7 @@ from typing import Dict, Any, Optional, List, Callable
7
7
  from pydantic import Field
8
8
  from typing import Annotated
9
9
 
10
- from .decorators import econometric_tool
10
+ from .base import with_file_support_decorator as econometric_tool
11
11
 
12
12
 
13
13
  # 标准文件输入参数定义
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aigroup-econ-mcp
3
- Version: 0.4.1
4
- Summary: 专业计量经济学MCP工具 - 让大模型直接进行数据分析
3
+ Version: 0.5.0
4
+ Summary: 专业计量经济学MCP工具 - 让大模型直接进行数据分析(重构版:工具描述模块化)
5
5
  Project-URL: Homepage, https://github.com/aigroup/aigroup-econ-mcp
6
6
  Project-URL: Repository, https://github.com/aigroup/aigroup-econ-mcp.git
7
7
  Project-URL: Issues, https://github.com/aigroup/aigroup-econ-mcp/issues
@@ -0,0 +1,30 @@
1
+ aigroup_econ_mcp/__init__.py,sha256=PdZxvF3Zn-a5rHMnRTZ8JgtNcmmtJ0IKJc6Clz4QCL4,511
2
+ aigroup_econ_mcp/cli.py,sha256=7yeNXWNwMdpUswAO4LsqAvb0EmCO3S6Bs6sl483uSXI,3363
3
+ aigroup_econ_mcp/config.py,sha256=ab5X4-H8isIe2nma0c0AOqlyYgwhf5kfe9Zx5XRrzIo,18876
4
+ aigroup_econ_mcp/server.py,sha256=Nqgu5bkAChdBH23Z8KmR14FO5ZDD7T6Hbug3m51ujHU,30899
5
+ aigroup_econ_mcp/tools/__init__.py,sha256=WYrsZX3Emv09c8QikvtG2BouUFZCguYkQ7eDjuwarAg,396
6
+ aigroup_econ_mcp/tools/base.py,sha256=Mv_mcKVTIg9A2dsqBBiU74_Ai2nb5sn2S3U4CNOxLKw,15218
7
+ aigroup_econ_mcp/tools/cache.py,sha256=Urv2zuycp5dS7Qh-XQWEMrwszq9RZ-il8cz_-WniGgc,15311
8
+ aigroup_econ_mcp/tools/data_loader.py,sha256=BVYvP04bQpsk3dZVFy-Y8EK3dnY4Pm0JSBYrthnHf74,5619
9
+ aigroup_econ_mcp/tools/file_parser.py,sha256=0isfNaUOz1SjlNLwy4T5J8OidWP2tEdm2KZEtyE-KRg,28203
10
+ aigroup_econ_mcp/tools/machine_learning.py,sha256=PpxrJVJw4eND95Wl0uGPEqUHXrIwTUSCd0QB1B4o4wY,1459
11
+ aigroup_econ_mcp/tools/ml_ensemble.py,sha256=XOL0PzCsx9LY_pFbKCAxjYdGny-HqEhlZyov2r1l3ww,6475
12
+ aigroup_econ_mcp/tools/ml_evaluation.py,sha256=hiwVW3-N0hnSAJfZW4luOCXt3sTh1W9Hj3CwZLRVaJk,8900
13
+ aigroup_econ_mcp/tools/ml_models.py,sha256=hJEUgARxkqYgJqu6_7eRc1WnD2HcTGxtXf8Jre_XO1U,2137
14
+ aigroup_econ_mcp/tools/ml_regularization.py,sha256=p81UXlb9ebyRuA_hSA4phmbFvORF-MaINMlYJkWKTbo,5070
15
+ aigroup_econ_mcp/tools/monitoring.py,sha256=-hcw5nu5Q91FmDz39mRBsKavrTmEqXsKfGzlXr_5f0c,16708
16
+ aigroup_econ_mcp/tools/optimized_example.py,sha256=tZVQ2jTzHY_zixTynm4Sq8gj5hz6eWg7MKqNwsxrPoQ,6784
17
+ aigroup_econ_mcp/tools/panel_data.py,sha256=uzbgcDLXACfdi9KaMRmZdRTkhMtEyWb7p3vS3mUJ-co,19254
18
+ aigroup_econ_mcp/tools/regression.py,sha256=uMGRGUQo4mU1sb8fwpP2FpkCqt_e9AtqEtUpInACtJo,6443
19
+ aigroup_econ_mcp/tools/statistics.py,sha256=2cHgNSUXwPYPLxntVOEOL8yF-x92mrgjK-R8kkxDihg,4239
20
+ aigroup_econ_mcp/tools/time_series.py,sha256=LNCO0bYXLPilQ2kSVXA3woNp8ERVq7n3jaoQhWgTCJQ,21763
21
+ aigroup_econ_mcp/tools/timeout.py,sha256=vNnGsR0sXW1xvIbKCF-qPUU3QNDAn_MaQgSxbGxkfW4,8404
22
+ aigroup_econ_mcp/tools/tool_descriptions.py,sha256=nTr373CgBPESbX9cbrRPMTTN-O8fc2d1PZ_XVIIqzBY,14710
23
+ aigroup_econ_mcp/tools/tool_handlers.py,sha256=cqv7FU95b_kjEJcZSAIGuGjUqbcCCKT0MXrmflnnelo,15028
24
+ aigroup_econ_mcp/tools/tool_registry.py,sha256=4SFpMnReZyGfEHCCDnojwHIUEpuQICS9M2u_9xuoUck,4413
25
+ aigroup_econ_mcp/tools/validation.py,sha256=F7LHwog5xtFIMjD9D48kd8jAF5MsZb7wjdrgaOg8EKo,16657
26
+ aigroup_econ_mcp-0.5.0.dist-info/METADATA,sha256=EoTmsI3tVHr48fYsWc0DkfaaXh5tcsrRBqT1tpZ-sSE,10839
27
+ aigroup_econ_mcp-0.5.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
28
+ aigroup_econ_mcp-0.5.0.dist-info/entry_points.txt,sha256=j5ZJYOc4lAZV-X3XkAuGhzHtIRcJtZ6Gz8ZKPY_QTrM,62
29
+ aigroup_econ_mcp-0.5.0.dist-info/licenses/LICENSE,sha256=DoyCJUWlDzKbqc5KRbFpsGYLwLh-XJRHKQDoITjb1yc,1083
30
+ aigroup_econ_mcp-0.5.0.dist-info/RECORD,,
@@ -1,178 +0,0 @@
1
- """
2
- 工具装饰器模块
3
- 提供自动文件输入处理、错误处理等功能
4
- """
5
-
6
- from typing import Callable, Optional, Dict, Any, List
7
- from functools import wraps
8
- from mcp.server.session import ServerSession
9
- from mcp.server.fastmcp import Context
10
- from mcp.types import CallToolResult, TextContent
11
-
12
- from .file_parser import FileParser
13
-
14
-
15
- def with_file_input(tool_type: str):
16
- """
17
- 为工具函数添加文件输入支持的装饰器
18
-
19
- 支持两种输入方式:
20
- 1. file_path: CSV/JSON文件路径
21
- 2. file_content: 文件内容字符串
22
-
23
- Args:
24
- tool_type: 工具类型 ('single_var', 'multi_var_dict', 'regression', 'panel', 'time_series')
25
-
26
- 使用示例:
27
- @with_file_input('regression')
28
- async def my_tool(ctx, y_data=None, x_data=None, file_path=None, file_content=None, file_format='auto', **kwargs):
29
- # 如果提供了file_path或file_content,数据会被自动填充
30
- pass
31
- """
32
- def decorator(func: Callable) -> Callable:
33
- @wraps(func)
34
- async def wrapper(*args, **kwargs):
35
- # 提取上下文和文件参数
36
- ctx = args[0] if args else kwargs.get('ctx')
37
- file_path = kwargs.get('file_path')
38
- file_content = kwargs.get('file_content')
39
- file_format = kwargs.get('file_format', 'auto')
40
-
41
- # 优先处理file_path
42
- if file_path:
43
- try:
44
- await ctx.info(f"检测到文件路径输入: {file_path}")
45
-
46
- # 从文件路径解析
47
- parsed = FileParser.parse_file_path(file_path, file_format)
48
-
49
- await ctx.info(
50
- f"文件解析成功:{parsed['n_variables']}个变量,"
51
- f"{parsed['n_observations']}个观测"
52
- )
53
-
54
- # 转换为工具格式
55
- converted = FileParser.convert_to_tool_format(parsed, tool_type)
56
-
57
- # 更新kwargs
58
- kwargs.update(converted)
59
-
60
- await ctx.info(f"数据已转换为{tool_type}格式")
61
-
62
- except Exception as e:
63
- await ctx.error(f"文件解析失败: {str(e)}")
64
- return CallToolResult(
65
- content=[TextContent(type="text", text=f"文件解析错误: {str(e)}")],
66
- isError=True
67
- )
68
-
69
- # 如果没有file_path但有file_content,处理文件内容
70
- elif file_content:
71
- try:
72
- await ctx.info("检测到文件内容输入,开始解析...")
73
-
74
- # 解析文件内容
75
- parsed = FileParser.parse_file_content(file_content, file_format)
76
-
77
- await ctx.info(
78
- f"文件解析成功:{parsed['n_variables']}个变量,"
79
- f"{parsed['n_observations']}个观测"
80
- )
81
-
82
- # 转换为工具格式
83
- converted = FileParser.convert_to_tool_format(parsed, tool_type)
84
-
85
- # 更新kwargs
86
- kwargs.update(converted)
87
-
88
- await ctx.info(f"数据已转换为{tool_type}格式")
89
-
90
- except Exception as e:
91
- await ctx.error(f"文件解析失败: {str(e)}")
92
- return CallToolResult(
93
- content=[TextContent(type="text", text=f"文件解析错误: {str(e)}")],
94
- isError=True
95
- )
96
-
97
- # 调用原函数
98
- return await func(*args, **kwargs)
99
-
100
- return wrapper
101
- return decorator
102
-
103
-
104
- def with_error_handling(func: Callable) -> Callable:
105
- """
106
- 为工具函数添加统一错误处理的装饰器
107
- """
108
- @wraps(func)
109
- async def wrapper(*args, **kwargs):
110
- ctx = args[0] if args else kwargs.get('ctx')
111
- tool_name = func.__name__
112
-
113
- try:
114
- return await func(*args, **kwargs)
115
- except Exception as e:
116
- await ctx.error(f"{tool_name}执行出错: {str(e)}")
117
- return CallToolResult(
118
- content=[TextContent(type="text", text=f"错误: {str(e)}")],
119
- isError=True
120
- )
121
-
122
- return wrapper
123
-
124
-
125
- def with_logging(func: Callable) -> Callable:
126
- """
127
- 为工具函数添加日志记录的装饰器
128
- """
129
- @wraps(func)
130
- async def wrapper(*args, **kwargs):
131
- ctx = args[0] if args else kwargs.get('ctx')
132
- tool_name = func.__name__
133
-
134
- await ctx.info(f"开始执行 {tool_name}")
135
- result = await func(*args, **kwargs)
136
- await ctx.info(f"{tool_name} 执行完成")
137
-
138
- return result
139
-
140
- return wrapper
141
-
142
-
143
- def econometric_tool(
144
- tool_type: str,
145
- with_file_support: bool = True,
146
- with_error_handling: bool = True,
147
- with_logging: bool = True
148
- ):
149
- """
150
- 组合装饰器:为计量经济学工具添加所有标准功能
151
-
152
- Args:
153
- tool_type: 工具类型
154
- with_file_support: 是否启用文件输入支持
155
- with_error_handling: 是否启用错误处理
156
- with_logging: 是否启用日志记录
157
-
158
- 使用示例:
159
- @econometric_tool('regression')
160
- async def ols_regression(ctx, y_data=None, x_data=None, **kwargs):
161
- # 只需要编写核心业务逻辑
162
- pass
163
- """
164
- def decorator(func: Callable) -> Callable:
165
- wrapped = func
166
-
167
- if with_error_handling:
168
- wrapped = globals()['with_error_handling'](wrapped)
169
-
170
- if with_file_support:
171
- wrapped = with_file_input(tool_type)(wrapped)
172
-
173
- if with_logging:
174
- wrapped = globals()['with_logging'](wrapped)
175
-
176
- return wrapped
177
-
178
- return decorator