Skip to main content
Glama
twoutlook

GPT5 Event Record MCP Server

by twoutlook
README.md
# GPT5 Event Record MCP Server

A Model Context Protocol (MCP) server that provides tournament event records from the WaterPoker database. This service replaces the monolithic `FetchEventRecordByBrandSerialIdForContext` method with a reusable, scalable MCP implementation.

## Features

- **MCP Tools**:
  - `get_event_records`: Fetch and filter tournament events with intelligent natural language processing
  - `analyze_tournament_query`: Parse user queries to extract filter parameters

- **Intelligent Filtering**:
  - Natural language query understanding
  - Keyword-based filtering (guaranteed, freezeout, ladies, high roller, etc.)
  - Date range filtering
  - Multi-criteria filtering support

- **Multiple Output Formats**:
  - Detailed view with complete event information
  - Summary statistics
  - Markdown formatted tables
  - Structured JSON responses

- **Performance Optimization**:
  - Built-in caching with configurable TTL
  - Connection pooling for database efficiency
  - Async/await throughout for better concurrency

## Installation

1. Clone the repository:
```bash
cd C:\dev\Gpt5EventRecordMcp
```

2. Install dependencies:
```bash
npm install
```

3. Configure environment:
```bash
copy .env.example .env
# Edit .env with your database credentials
```

## Configuration

Edit the `.env` file with your settings:

```env
# Database Configuration
DB_HOST=localhost
DB_PORT=1433
DB_NAME=JwtAuthDb
DB_USER=sa
DB_PASSWORD=your_password
DB_ENCRYPT=false
DB_TRUST_SERVER_CERTIFICATE=true

# MCP Server Configuration
MCP_NAME=gpt5-event-record-mcp
MCP_VERSION=1.0.0
MCP_LOG_LEVEL=info

# Cache Configuration
CACHE_ENABLED=true
CACHE_TTL_SECONDS=300
CACHE_MAX_SIZE=100
```

## Usage

### Starting the Server

#### Development mode:
```bash
npm run dev
```

#### Production mode:
```bash
npm run build
npm start
```

#### HTTPS Server:

1. Generate self-signed certificates (first time only):
```bash
# Windows PowerShell
New-Item -ItemType Directory -Force -Path ./certs
$cert = New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "Cert:\CurrentUser\My" -NotAfter (Get-Date).AddYears(2)
$pwd = ConvertTo-SecureString -String "password" -Force -AsPlainText
Export-PfxCertificate -Cert $cert -FilePath ./certs/localhost.pfx -Password $pwd
# Convert to PEM format using OpenSSL
openssl pkcs12 -in ./certs/localhost.pfx -out ./certs/cert.pem -nodes -clcerts -password pass:password
openssl pkcs12 -in ./certs/localhost.pfx -out ./certs/key.pem -nodes -nocerts -password pass:password

# Linux/Mac
mkdir -p certs
openssl req -x509 -newkey rsa:4096 -keyout certs/key.pem -out certs/cert.pem -days 365 -nodes \
  -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost"
```

2. Configure HTTPS in `.env`:
```env
# HTTPS Configuration
HTTPS_ENABLED=true
HTTPS_PORT=3443
HTTPS_CERT_PATH=./certs/cert.pem
HTTPS_KEY_PATH=./certs/key.pem
```

3. Start HTTPS server:
```bash
npm run start:https
```

The HTTPS server will be available at `https://localhost:3443`

### Using with Claude Desktop

Add to your Claude Desktop configuration:

```json
{
  "mcpServers": {
    "gpt5-event-record": {
      "command": "node",
      "args": ["C:\\dev\\Gpt5EventRecordMcp\\dist\\server.js"],
      "env": {
        "NODE_ENV": "production"
      }
    }
  }
}
```

### Tool Examples

#### Get Event Records
```typescript
// Basic query
{
  "tool": "get_event_records",
  "arguments": {
    "brandSerialId": 1,
    "format": "detailed"
  }
}

// With natural language filtering
{
  "tool": "get_event_records",
  "arguments": {
    "brandSerialId": 1,
    "userQuery": "顯示所有保底賽事",
    "format": "table"
  }
}

// With explicit filters
{
  "tool": "get_event_records",
  "arguments": {
    "brandSerialId": 1,
    "filters": {
      "guaranteed": true,
      "dateRange": {
        "from": "2024-09-01",
        "to": "2024-09-30"
      }
    },
    "format": "summary"
  }
}
```

#### Analyze Tournament Query
```typescript
{
  "tool": "analyze_tournament_query",
  "arguments": {
    "query": "顯示下週所有女子保底賽事"
  }
}

// Returns:
{
  "type": "GUARANTEED",
  "keywords": ["保底", "女子"],
  "filters": {
    "guaranteed": true,
    "ladies": true
  }
}
```

## Project Structure

```
src/
├── server.ts               # Main MCP server entry
├── services/
│   ├── databaseService.ts  # SQL Server database operations
│   ├── eventRecordService.ts # Core business logic
│   ├── filterService.ts    # Query analysis and filtering
│   ├── formatterService.ts # Output formatting (markdown, table, etc.)
│   └── cacheService.ts     # In-memory caching
└── utils/
    └── logger.ts           # Winston logging configuration
```

## Development

### Building

```bash
npm run build
```

### Testing

```bash
npm test
```

### Linting

```bash
npm run lint
```

### Clean Build

```bash
npm run clean
npm run build
```

## Integration with ASP.NET Core

To integrate with the existing `Gpt5EventRecordController`:

1. Install MCP client library in the .NET project
2. Replace the `FetchEventRecordByBrandSerialIdForContext` method call:

```csharp
// Before
var tournamentData = await FetchEventRecordByBrandSerialIdForContext(
    brandSerialId, message, cts);

// After
var mcpClient = new McpClient("gpt5-event-record-mcp");
var result = await mcpClient.InvokeTool("get_event_records", new {
    brandSerialId = brandSerialId,
    userQuery = message,
    format = "detailed"
});
var tournamentData = result.formatted;
```

## Performance

- **Caching**: 5-minute TTL by default, configurable
- **Database**: Connection pooling with 10 concurrent connections
- **Memory**: Maximum 100 cached entries (configurable)
- **Response Time**: <100ms for cached queries, <500ms for database queries

## Logging

Logs are written to console with configurable levels:
- `error`: Error messages only
- `warn`: Warnings and errors
- `info`: General information (default)
- `debug`: Detailed debugging information

## Error Handling

- Database connection failures are logged and reported
- Invalid parameters return descriptive error messages
- Cached results are returned if database is temporarily unavailable
- Graceful shutdown on SIGINT/SIGTERM

## License

MIT

## Support

For issues or questions, please contact the WaterPoker Development Team.

---

# GPT5 事件記錄 MCP 伺服器

一個提供 WaterPoker 資料庫錦標賽事件記錄的模型上下文協議 (MCP) 伺服器。此服務以可重用、可擴展的 MCP 實作取代原本的 `FetchEventRecordByBrandSerialIdForContext` 方法。

## 功能特色

- **MCP 工具**:
  - `get_event_records`:使用智慧自然語言處理來取得和篩選錦標賽事件
  - `analyze_tournament_query`:解析使用者查詢以提取篩選參數

- **智慧篩選**:
  - 自然語言查詢理解
  - 基於關鍵字的篩選(保底、凍結賽、女子賽、高額賽等)
  - 日期範圍篩選
  - 多條件篩選支援

- **多種輸出格式**:
  - 完整事件資訊的詳細檢視
  - 摘要統計
  - Markdown 格式表格
  - 結構化 JSON 回應

- **效能最佳化**:
  - 內建快取與可設定的 TTL
  - 資料庫連線池以提高效率
  - 全程使用 async/await 改善並發處理

## 安裝

1. 複製儲存庫:
```bash
cd C:\dev\Gpt5EventRecordMcp
```

2. 安裝相依套件:
```bash
npm install
```

3. 設定環境:
```bash
copy .env.example .env
# 編輯 .env 填入您的資料庫憑證
```

## 設定

編輯 `.env` 檔案設定您的配置:

```env
# 資料庫設定
DB_HOST=localhost
DB_PORT=1433
DB_NAME=JwtAuthDb
DB_USER=sa
DB_PASSWORD=your_password
DB_ENCRYPT=false
DB_TRUST_SERVER_CERTIFICATE=true

# MCP 伺服器設定
MCP_NAME=gpt5-event-record-mcp
MCP_VERSION=1.0.0
MCP_LOG_LEVEL=info

# 快取設定
CACHE_ENABLED=true
CACHE_TTL_SECONDS=300
CACHE_MAX_SIZE=100
```

## 使用方式

### 啟動伺服器

#### 開發模式:
```bash
npm run dev
```

#### 生產模式:
```bash
npm run build
npm start
```

#### HTTPS 伺服器:

1. 產生自簽憑證(僅首次需要):
```bash
# Windows PowerShell
New-Item -ItemType Directory -Force -Path ./certs
$cert = New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "Cert:\CurrentUser\My" -NotAfter (Get-Date).AddYears(2)
$pwd = ConvertTo-SecureString -String "password" -Force -AsPlainText
Export-PfxCertificate -Cert $cert -FilePath ./certs/localhost.pfx -Password $pwd
# 使用 OpenSSL 轉換為 PEM 格式
openssl pkcs12 -in ./certs/localhost.pfx -out ./certs/cert.pem -nodes -clcerts -password pass:password
openssl pkcs12 -in ./certs/localhost.pfx -out ./certs/key.pem -nodes -nocerts -password pass:password

# Linux/Mac
mkdir -p certs
openssl req -x509 -newkey rsa:4096 -keyout certs/key.pem -out certs/cert.pem -days 365 -nodes \
  -subj "/C=TW/ST=Taiwan/L=Taipei/O=Organization/CN=localhost"
```

2. 在 `.env` 中設定 HTTPS:
```env
# HTTPS 設定
HTTPS_ENABLED=true
HTTPS_PORT=3443
HTTPS_CERT_PATH=./certs/cert.pem
HTTPS_KEY_PATH=./certs/key.pem
```

3. 啟動 HTTPS 伺服器:
```bash
npm run start:https
```

HTTPS 伺服器將在 `https://localhost:3443` 提供服務

### 與 Claude Desktop 搭配使用

在您的 Claude Desktop 設定中加入:

```json
{
  "mcpServers": {
    "gpt5-event-record": {
      "command": "node",
      "args": ["C:\\dev\\Gpt5EventRecordMcp\\dist\\server.js"],
      "env": {
        "NODE_ENV": "production"
      }
    }
  }
}
```

### 工具範例

#### 取得事件記錄
```typescript
// 基本查詢
{
  "tool": "get_event_records",
  "arguments": {
    "brandSerialId": 1,
    "format": "detailed"
  }
}

// 使用自然語言篩選
{
  "tool": "get_event_records",
  "arguments": {
    "brandSerialId": 1,
    "userQuery": "顯示所有保底賽事",
    "format": "table"
  }
}

// 使用明確篩選條件
{
  "tool": "get_event_records",
  "arguments": {
    "brandSerialId": 1,
    "filters": {
      "guaranteed": true,
      "dateRange": {
        "from": "2024-09-01",
        "to": "2024-09-30"
      }
    },
    "format": "summary"
  }
}
```

#### 分析錦標賽查詢
```typescript
{
  "tool": "analyze_tournament_query",
  "arguments": {
    "query": "顯示下週所有女子保底賽事"
  }
}

// 回傳:
{
  "type": "GUARANTEED",
  "keywords": ["保底", "女子"],
  "filters": {
    "guaranteed": true,
    "ladies": true
  }
}
```

## 專案結構

```
src/
├── server.ts               # 主要 MCP 伺服器進入點
├── services/
│   ├── databaseService.ts  # SQL Server 資料庫操作
│   ├── eventRecordService.ts # 核心業務邏輯
│   ├── filterService.ts    # 查詢分析與篩選
│   ├── formatterService.ts # 輸出格式化(markdown、表格等)
│   └── cacheService.ts     # 記憶體快取
└── utils/
    └── logger.ts           # Winston 日誌設定
```

## 開發

### 建置

```bash
npm run build
```

### 測試

```bash
npm test
```

### 程式碼檢查

```bash
npm run lint
```

### 清理建置

```bash
npm run clean
npm run build
```

## 與 ASP.NET Core 整合

要與現有的 `Gpt5EventRecordController` 整合:

1. 在 .NET 專案中安裝 MCP 客戶端函式庫
2. 取代 `FetchEventRecordByBrandSerialIdForContext` 方法呼叫:

```csharp
// 之前
var tournamentData = await FetchEventRecordByBrandSerialIdForContext(
    brandSerialId, message, cts);

// 之後
var mcpClient = new McpClient("gpt5-event-record-mcp");
var result = await mcpClient.InvokeTool("get_event_records", new {
    brandSerialId = brandSerialId,
    userQuery = message,
    format = "detailed"
});
var tournamentData = result.formatted;
```

## 效能

- **快取**:預設 5 分鐘 TTL,可設定
- **資料庫**:連線池支援 10 個並發連線
- **記憶體**:最多 100 個快取項目(可設定)
- **回應時間**:快取查詢 <100ms,資料庫查詢 <500ms

## 日誌記錄

日誌寫入控制台,可設定等級:
- `error`:僅錯誤訊息
- `warn`:警告和錯誤
- `info`:一般資訊(預設)
- `debug`:詳細除錯資訊

## 錯誤處理

- 資料庫連線失敗會記錄並回報
- 無效參數會回傳描述性錯誤訊息
- 資料庫暫時無法使用時會回傳快取結果
- 在 SIGINT/SIGTERM 時優雅關閉

## 授權

MIT

## 支援

如有問題或疑問,請聯絡 WaterPoker 開發團隊。