时间序列预测服务器

基于MCP协议的时间序列预测服务,支持RNN、LSTM和GRU三种深度学习算法,适用于各种时间序列数据预测场景。

  • by Heny114514
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 Heny114514/Simple_MCP_Server

使用说明

Time series prediction MCP server

A time series prediction service based on MCP (Model Context Protocol), supporting three deep learning algorithms: RNN, LSTM, and GRU.

Author: Heny(兰翔)、LovelyFlash(王李超)

Course: 人工智能引论 25秋

Tool List:

Tools

  • train_rnn_model -Training RNN Regression Model
  • train_lstm_model -Training LSTM Regression Model
  • train_gru_model -Training GRU Regression Model
  • predict_model -Using trained models for prediction
  • compare_models -Compare the performance of three models and automatically select the best one
  • get_available_models -Retrieve the list of currently trained and available models
  • get_server_config -Get server configuration information

Resources

  • hello_resource -Example MCP Resources

Prompts

  • greet_user -Greetings generation prompt
  • predict_workflow -Time series prediction complete workflow prompt

1、 Project Structure

Simple_MCP_Server/
├── server.py              # 服务器入口
├── setup.py              # 安装脚本
├── config.yaml           # 配置文件
├── pyproject.toml        # 依赖管理
├── .gitignore           # Git忽略文件
├── README.md             # 本文档
│
├── tools/                # MCP工具
│   ├── __init__.py       # 工具包初始化
│   ├── hello_tool.py     # 示例工具
│   ├── time_series_models.py  # RNN/LSTM/GRU模型实现
│   └── time_series_tools.py  # 时间序列工具函数
│
├── prompts/              # MCP提示词模板
│   ├── __init__.py       # 提示包初始化
│   ├── hello_prompt.py   # 示例提示
│   └── predict_prompt.py # 时间序列预测工作流提示
│
├── resources/            # MCP资源
│   ├── __init__.py       # 资源包初始化
│   └── hello_resource.py # 示例资源
│
├── core/                 # 核心功能模块
│   ├── __init__.py       # 核心包初始化
│   └── hello_secrets.py  # 示例secrets管理
│
├── utils/                # 公共工具模块
│   ├── __init__.py       # 工具包初始化
│   ├── config.py         # 配置管理
│   ├── logger.py         # 日志管理
│   ├── errors.py         # 错误处理
│   ├── helpers.py        # 辅助函数
│   ├── middleware.py     # 中间件
│   ├── security.py       # 安全模块
│   └── system.py         # 系统工具
│
├── examples/             # 示例代码
│   ├── __init__.py       # 示例包初始化
│   └── sdk_client.py     # Python SDK客户端
│
├── logs/                 # 日志文件目录
├── modules/              # 模块目录
│
├── deploy.sh             # Linux部署脚本
└── deploy.bat            # Windows部署脚本

2、 Quick Start

1. Install dependencies

uv venv
uv sync

2. Start the server

uv run server.py

Server address: http://127.0.0.1:12346


3、 Detailed explanation of tools

3.1 train_rnn_madel - RNN model training dialogue example

User: I have a set of temperature data and I want to train an RNN model.

AI: Okay, we can use ittrain_rnn_modelTools to train RNN regression models. You need to provide time series data, such as [20.5, 21.2, 19.8, 22.0, 21.5, 20.9, 22.1, 21.8, 20.4, 23.0], and set parameters such as the number of training rounds. Do you need to adjust the default parameters?

AI: Call tool training:

result = await client.train_rnn_model(
    data=[20.5, 21.2, 19.8, 22.0, 21.5, 20.9, 22.1, 21.8, 20.4, 23.0],
    epochs=50,
    sequence_length=3,
    hidden_size=32
)

AI: Training completed!

{
  "status": "success",
  "model_type": "rnn",
  "final_loss": 0.0123,
  "metrics": {
    "mse": 0.011,
    "rmse": 0.105,
    "mae": 0.082
  },
  "sample_predictions": [21.1, 19.9, 22.2],
  "sample_actuals": [21.2, 19.8, 22.0]
}

AI: RNN model training successful! The final loss is 0.0123 and the MSE is 0.011. It can be seen that the predicted value is very close to the actual value.


3.2 train_1stm_madel - LSTM model training dialogue example

User: I have a long time series data with 50 points, and I want to use an LSTM model for prediction.

AI: Okay, LSTM is suitable for processing long sequence data and has stronger memory ability. We can usetrain_lstm_modelTools. I see that you have 50 data points, so we can set the sequence length to 5, the hidden layer size to 64, and the training rounds to 100. Is the data ready?

AI: Start training the LSTM model:

result = await client.train_lstm_model(
    data=[2.1, 2.3, 2.0, 2.5, 2.2, 2.8, 1.9, 3.0, 2.7, 2.4, 2.9, 2.1, 3.2, 2.6, 2.8, 3.1, 2.5, 3.3, 2.7, 3.0, 2.8, 2.9, 3.4, 2.6, 3.5, 2.9, 3.1, 3.2, 2.8, 3.6, 3.0, 3.3, 3.1, 2.9, 3.7, 3.2, 3.4, 3.1, 3.0, 3.8, 3.3, 3.5, 3.2, 3.1, 3.9, 3.4, 3.6, 3.2, 3.3, 4.0],
    epochs=100,
    sequence_length=5,
    hidden_size=64
)

AI: LSTM training results:

{
  "status": "success",
  "model_type": "lstm",
  "final_loss": 0.0089,
  "metrics": {
    "mse": 0.007,
    "rmse": 0.084,
    "mae": 0.061
  },
  "sample_predictions": [3.35, 3.5, 3.2],
  "sample_actuals": [3.4, 3.5, 3.2]
}

AI: The LSTM model has been successfully trained! Compared to RNN, LSTM performs more stably when processing long sequences, with a final loss of 0.0089 and MSE of 0.007. It seems that the prediction accuracy is very high.


3.3 train_gru_madel - GRU model training dialogue example

User: My device has limited performance and I want to use the minimum number of parameters for time series prediction. Is GRU suitable for me?

AI: Indeed, GRU has fewer parameters than LSTM and is suitable for resource constrained environments. We can usetrain_gru_modelTools. Let me show you a simple example that only requires a few data points and small hidden layers.

AI: Training GRU model:

result = await client.train_gru_model(
    data=[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
    epochs=30,
    sequence_length=2,
    hidden_size=16
)

AI: GRU training results:

{
  "status": "success",
  "model_type": "gru",
  "final_loss": 0.0156,
  "metrics": {
    "mse": 0.014,
    "rmse": 0.118,
    "mae": 0.091
  },
  "sample_predictions": [9.8, 10.1, 10.5],
  "sample_actuals": [10.0, 10.0, 11.0]
}

AI: Great! The GRU model has been successfully trained. Although the number of parameters is small, the performance is still good, with a final loss of 0.0156 and MSE of 0.014. For devices with limited resources, this is a great choice.


3.4 predict_madel - Example of using a model to predict conversations

User: I have already trained an LSTM model and now I want to make predictions on future data. How do I do it?

AI: Okay, we can use itpredict_modelTools to use trained models for prediction. Firstly, you need to ensure that the model has been trained, and then provide the data sequence to be predicted.

AI: Firstly, check the available models:

await client.get_available_models()

AI: If LSTM has been trained, it can make predictions:

result = await client.predict_model(
    data=[10.0, 11.0, 12.5],
    model_type="lstm"
)

AI: Prediction results:

{
  "status": "success",
  "model_type": "lstm",
  "predictions": [13.1, 14.2, 15.3, 16.5, 17.8],
  "prediction_count": 5
}

AI: Successfully predicted the next 5 data points! According to the input sequence [10.0, 11.0, 12.5], the model predicts the values for the next stage to be [13.1, 14.2, 15.3, 16.5, 17.8].

User: I want to predict other models, but I haven't trained them yet.

AI: This will return an error message:

{
  "status": "error",
  "message": "Model 'rnn' not trained yet. Please train the model first."
}

AI: It seems that the corresponding model needs to be trained first before making predictions.


3.5 compare_models - Model comparison and automatic selection dialogue examples

User: I find it difficult to decide which model to use, RNN, LSTM, or GRU? Is there any tool that can help me compare them?

AI: Of course there is! We can usecompare_modelsTool to train three models simultaneously and automatically select the best performing one. This tool will compare MSE (Mean Squared Error) to determine which model is most suitable.

AI: Call the comparison tool:

result = await client.compare_models(
    data=[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0],
    epochs=100,
    sequence_length=3,
    hidden_size=64
)

AI: Model comparison results:

{
  "status": "success",
  "results": {
    "rnn": {
      "mse": 0.031,
      "rmse": 0.176,
      "mae": 0.145
    },
    "lstm": {
      "mse": 0.012,
      "rmse": 0.109,
      "mae": 0.085
    },
    "gru": {
      "mse": 0.022,
      "rmse": 0.148,
      "mae": 0.112
    }
  },
  "best_model": "lstm",
  "best_mse": 0.012
}

AI: Great! After comparison, the LSTM model performs the best with an MSE of only 0.012, which is better than RNN's 0.031 and GRU's 0.022. The system automatically recommends using the LSTM model for subsequent prediction, which is the most suitable for long sequence data.


3.6 getbioavailable models - Check for available model dialogue examples

User: I want to know which models have been trained so far.

AI: No problem, we can use itget_available_modelsTool to view the list of currently trained and available models. This tool does not require any parameters.

AI: Check available models:

result = await client.get_available_models()

AI: Query results:

{
  "status": "success",
  "available_models": ["lstm", "gru"],
  "model_count": 2
}

AI: Okay, we have already trained two models: LSTM and GRU. Now you can directly use these two models for prediction without retraining.


3.7 get_ server config - Get Server Configuration Dialogue Example

User: I want to know the current configuration of the server.

AI: We can useget_server_configTool to obtain server configuration information. You can specify the specific configuration key to query, otherwise the default value will be returned.

AI: Get server configuration:

result = await client.get_server_config(key="server.name")

AI: Configuration query result:

{
  "status": "success",
  "config_key": "server.name",
  "config_value": "TimeSeriesMCPServer",
  "description": "当前服务器名称"
}

AI: If you want to view all configurations, you can also obtain complete configuration information without passing the key parameter.

3.8 predictsprompt - Time Series Prediction Workflow Dialogue Example

User: Predicting time series [1.02, 2.11, 2.98, 4.05, 5.12, 6.03, 7.19, 8.25, 9.17, 10.28, 11.33, 12.41, 13.29, 14.45, 15.52, 16.37, 17.58, 18.64, 19.71, 20.83, 21.92, 22.78, 23.89, 25.01, 26.10, 27.05, 28.18, 29.27, 30.34, 31.42, 32.51, 33.63, 34.72, 35.81, 36.90, 37.95, 39.08, 40.13, 41.27, 42.39, The last five terms of 43.48, 44.55, 45.69, 46.77, 47.84, 48.91, 50.02, 51.15, 52.23, 53.31]

AI: Based on the analysis of time series data and model training, the following is a comparative analysis of prediction results and models:

Predict the last five items

Based on the trained LSTM model, the last five predicted values of the time series are:

  • Item 51:fifty-three point three one → Predicted as fifty-four point four zero
  • Item 52:fifty-four point four zero → Predicted as fifty-five point four nine
  • Item 53:fifty-five point four nine → Predicted as fifty-six point five eight
  • Item 54:fifty-six point five eight → Predicted as fifty-seven point six seven
  • Item 55:fifty-seven point six seven → Predicted as fifty-eight point seven six

(Note: The above is a continuous prediction based on the trend of the model, calculated according to the pattern of the last few points.)

Model performance comparison

We compared the performance of three models, RNN, LSTM, and GRU, on the same dataset, with evaluation metrics including mean square error (MSE), root mean square error (RMSE), and mean absolute error (MAE):

Model MSE RMSE MAE Final Loss
RNN 0.0671 0.2591 0.2192 0.0000276
LSTM zero point zero two three six zero point one five three seven zero point one three four six zero point zero zero zero zero zero nine five
GRU 0.0249 0.1576 0.1375 0.0000083

Conclusion and Recommendation

  • Best Model:LSTMAmong all indicators, it performs the best, especially significantly better than RNN and GRU in MSE and RMSE.
  • Suboptimal model:GRU, The performance is very similar to LSTM, but slightly inferior to LSTM.
  • The worst model:RNN, The error is significantly higher than the other two models, making it unsuitable for this time series task.

recommend

Recommended to useLSTM modelFor subsequent prediction, its prediction accuracy is the highest and its ability to capture trends is the strongest.


4、 Large model call configuration

Cursor/Cline

{
  "mcpServers": {
    "timeseries-mcp": {
      "url": "http://127.0.0.1:12346/sse"
    }
  }
}

Claude Desktop

%APPDATA%\Claude\claude_desktop_config.json:

{
  "mcpServers": {
    "timeseries-mcp": {
      "command": "uv",
      "args": ["run", "--directory", "D:\\desktop\\Simple_MCP_Server", "server.py"]
    }
  }
}

Python SDK

from examples import TimeSeriesMCPClient
import asyncio

async def main():
    async with TimeSeriesMCPClient(cwd=".") as client:
        # 训练模型
        result = await client.train_lstm(data=[1,2,3,4,5], epochs=50)
        
        # 预测
        pred = await client.predict(data=[6,7], model_type="lstm")

asyncio.run(main())

5、 Configuration Description

modify config.yaml:

server:
  name: TimeSeriesMCPServer
  version: 0.1.0

transport:
  type: "sse"      # stdio 或 sse
  port: 12346

security:
  enabled: false   # 启用安全认证
  api_key: "your-key"

6、 Algorithm selection

Scenario Recommendation Reason
Short sequence RNN Simple and fast
Long sequence LSTM Strong memory ability
Resource limited GRU Low parameter count