sometrend-mcp-server
Version:
TM2 기반의 썸트렌드(sometrend) MCP 서버 - 트렌드 분석 및 데이터 처리
597 lines (481 loc) • 16.4 kB
Markdown
<<<<<<< README.md
# 썸트렌드(sometrend) MCP 서버
TM2 기반의 썸트렌드 MCP 서버입니다.
TM2 API 서비스와 [Model Context Protocol (MCP)](https://github.com/modelcontextprotocol/mcp) 표준을 연결하는 프록시 서버입니다.
이 서버는 TM2(Sometrend) API의 다양한 텍스트 분석 기능을 MCP 클라이언트에서 쉽게 사용할 수 있도록 브리지 역할을 수행합니다.
## ✨ 최신 업데이트 (v1.0.0)
- **NPX 배포 완료**: `npx sometrend-mcp-server`로 전 세계 즉시 사용 가능
- **MCP v1.18.0 지원**: 최신 Model Context Protocol 표준 완전 준수
- **간편한 설정**: API 키 설정 후 바로 Claude Desktop에서 사용
- **하이브리드 리소스 프리로딩**: 핵심 카테고리 데이터 메모리 캐시로 빠른 응답 (0ms)
- **메모리 최적화**: 도구 설명 최적화로 약 50% 메모리 사용량 감소
- **14개 전문 프롬프트**: 평판분석, 위기관리, 마케팅분석 등 비즈니스 시나리오 지원
- **프로덕션 레디**: PM2 클러스터, Redis 캐시, MariaDB 통합으로 엔터프라이즈 수준 안정성
## 서버 호출 방법
다음과 같은 다양한 이름으로 서버를 호출할 수 있습니다:
- "썸트렌드 MCP를 이용해서 분석해줘"
- "TM2 MCP를 이용해서 분석해줘"
- "sometrend MCP를 이용해서 분석해줘"
## 주요 기능
- 트렌드 분석 및 데이터 처리
- SNS 채널 관리 및 분석
- 카테고리 리소스 관리
### 📊 텍스트 분석 서비스
- **감정 분석 (Opinion Mining)**: 텍스트의 긍정/부정 감정 분석
- **감정 인식 (Emotion Analysis)**: 기쁨, 슬픔, 분노 등 세부 감정 분석
- **키워드 추출 (Keyword Extraction)**: 핵심 키워드 자동 추출
- **문서 분류 (Document Classification)**: 텍스트 자동 카테고리 분류
- **요약 (Summarization)**: 긴 텍스트의 핵심 내용 요약
- **개체명 인식 (Named Entity Recognition)**: 인명, 지명, 기관명 등 추출
### 📈 분석 시나리오 지원
- **브랜드 평판 분석** (Brand Reputation)
- **시장 조사** (Market Research)
- **소셜 리스닝** (Social Listening)
- **고객 감정 분석** (Customer Sentiment)
- **경쟁사 분석** (Competitor Analysis)
- **트렌드 분석** (Trend Analysis)
### 🔧 MCP 표준 지원
- **도구 (Tools)**: TM2 API 호출을 위한 구조화된 도구 제공
- **리소스 (Resources)**: 카테고리 및 채널 정보 제공
- **프롬프트 (Prompts)**: 분석 작업을 위한 최적화된 프롬프트 템플릿
## 🛠️ 기술 스택
- **Runtime**: Node.js (>= 18.0.0)
- **Language**: TypeScript 5.0.0
- **Framework**: @modelcontextprotocol/sdk 1.18.0 (최신)
- **Transport**: Server-Sent Events (SSE) + STDIO
- **HTTP Server**: Express.js 5.1.0
- **HTTP Client**: Axios 1.9.0
- **Environment**: dotenv 17.2.2
- **Process Manager**: PM2 6.0.10
- **Caching**: Redis 5.7.0 + 인메모리 하이브리드 캐시
- **Database**: MariaDB 3.4.5
- **Logging**: Winston 3.17.0
- **Security**: Express Rate Limit 8.1.0
## 🚀 빠른 시작 (NPX)
### 1단계: API 키 설정
```bash
npx sometrend-mcp-server --setup
```
### 2단계: Claude Desktop 설정
`claude_desktop_config.json` 파일에 추가:
```json
{
"mcpServers": {
"sometrend": {
"command": "npx",
"args": ["sometrend-mcp-server"],
"env": {
"TM2_API_KEY": "your-api-key-here"
}
}
}
}
```
### 3단계: Claude Desktop 재시작
설정 완료 후 Claude Desktop을 재시작하세요.
**API 키 발급 문의:** `biz@vaiv.kr`
---
## 📋 사전 요구사항 (개발용)
- Node.js 18.0.0 이상
- npm 패키지 매니저
- TM2 API 서버 접근 권한
## 🔧 개발자 설치 및 설정
### 1. 프로젝트 클론 및 설치
```bash
git clone <repository-url>
cd tm2_mcp_server_proxy
npm install
```
### 2. 환경 변수 설정
`.env` 파일을 생성하고 다음 설정을 추가하세요:
```env
# TM2 API 키
TM2_API_KEY=your_api_key_here
# API 타임아웃 (밀리초)
API_TIMEOUT=60000
# TM2 서버 URL
TM2_BASE_URL=http://10.1.41.49:9292
```
### 3. 빌드 및 실행
#### SSE 모드 (Claude Desktop 원격 연결)
```bash
# 개발 모드
npm run dev
# 프로덕션 빌드 및 실행
npm run build
npm start
```
#### STDIO 모드 (로컬 MCP 클라이언트)
```bash
# STDIO 모드로 실행
npm run start:stdio
# 테스트 실행
npm test
```
서버가 시작되면 다음과 같은 엔드포인트가 제공됩니다:
- `GET /sse`: SSE 스트림 연결 (Claude Desktop용)
- `POST /messages`: MCP 메시지 처리
- `GET /health`: 서버 상태 확인
- `GET /info`: 서버 정보 및 사용법
## 📁 프로젝트 구조
```
tm2_mcp_server_proxy/
├── src/
│ ├── assets/ # 정적 리소스
│ │ ├── tm2-sm-categories.json
│ │ ├── tm2-sns-channels.json
│ │ └── tm2-tsn3-categories.json
│ ├── constants/ # 상수 정의
│ │ ├── analysis.constants.ts
│ │ ├── api-endpoints.constants.ts
│ │ ├── api-guide.constants.ts
│ │ ├── app-data.constants.ts
│ │ └── category-resource.constants.ts
│ ├── definitions/ # MCP 정의
│ │ ├── PromptDefinitions.ts
│ │ ├── ResourceDefinitions.ts
│ │ └── ToolDefinitions.ts
│ ├── services/ # 핵심 서비스
│ │ ├── CacheService.ts
│ │ ├── CategoryResourceService.ts
│ │ ├── PromptGeneratorService.ts
│ │ ├── PromptHandlerService.ts
│ │ ├── SnsChannelService.ts
│ │ └── TM2ApiClient.ts
│ ├── types/ # TypeScript 타입 정의
│ │ ├── analysis.ts
│ │ ├── index.ts
│ │ ├── prompts.ts
│ │ ├── resources.ts
│ │ └── tools.ts
│ ├── index.ts # 진입점
│ └── TM2Server.ts # 메인 서버 클래스
├── test/ # 테스트 파일
├── docs/ # 문서
├── .env # 환경 변수
├── package.json
└── tsconfig.json
```
## 🎯 사용 예시
### Claude Desktop에서 사용하기
1. 서버 시작:
```bash
npm run dev
```
2. Claude Desktop 설정에서 MCP 서버 추가:
```json
{
"mcpServers": {
"sometrend": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-sse", "http://localhost:3000/sse"]
}
}
}
```
### 로컬 MCP 클라이언트 연결
```typescript
import { StdioServerTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
const transport = new StdioServerTransport({
command: 'node',
args: ['dist/index.js']
});
const client = new Client({
name: "sometrend-client",
version: "1.0.0"
}, {
capabilities: {}
});
await client.connect(transport);
```
### 도구 호출 예시
```typescript
// 키워드 카테고리 분류
const result = await client.callTool({
name: "getKeywordCategory",
arguments: {
dataSource: "blog",
categoryType: "SM",
keyword: "스마트폰"
}
});
// 연관어 분석
const associations = await client.callTool({
name: "getAssociationAnalysis",
arguments: {
dataSource: "blog",
categoryType: "TSN3",
keyword: "아이폰",
period: "1M"
}
});
```
### 리소스 조회 예시
```typescript
// 카테고리 정보 조회
const categories = await client.readResource({
uri: "tm2://categories/sm"
});
// SNS 채널 정보 조회
const channels = await client.readResource({
uri: "tm2://channels/sns"
});
```
### 프롬프트 사용 예시
```typescript
// 평판 분석 프롬프트
const prompt = await client.getPrompt({
name: "reputation_analysis",
arguments: {
organization: "삼성전자",
analysis_period: "최근 3개월",
focus_area: "제품"
}
});
// 위기 관리 프롬프트
const crisis = await client.getPrompt({
name: "crisis_issue_management",
arguments: {
organization_or_brand: "우리회사",
risk_keywords: "사고,논란,클레임",
alert_sensitivity: "높음"
}
});
```
## 📊 분석 기능 및 프롬프트
### 핵심 분석 도구 (24개 도구)
| 카테고리 | 도구명 | 설명 |
|---------|------|------|
| 시스템 | `getAvailableDataSources` | 분석 가능한 데이터 소스 목록 |
| 시스템 | `getAvailableSnsChannels` | SNS 채널별 세부 정보 |
| 분류 | `getKeywordCategory` | 키워드 카테고리 자동 분류 |
| 분류 | `getCategoryBatch` | 다중 키워드 일괄 분류 |
| 분석 | `getDocumentCount` | 키워드별 문서량 분석 |
| 분석 | `getBuzzAnalysis` | 키워드 언급량 및 트렌드 분석 |
| 분석 | `getAssociationAnalysis` | 연관어 분석 |
| 분석 | `getSentimentAnalysis` | 감성 분석 |
### 전문 프롬프트 (14개 프롬프트)
| 카테고리 | 프롬프트명 | 비즈니스 활용 |
|---------|----------|-------------|
| 기본분석 | `analyze_social_trend` | 소셜미디어 트렌드 종합 분석 |
| 기본분석 | `sentiment_analysis` | 키워드 감성 분석 |
| 전문분석 | `reputation_analysis` | 브랜드 평판 및 이미지 분석 |
| 전문분석 | `crisis_issue_management` | 위기 감지 및 대응 전략 |
| 전문분석 | `marketing_analysis` | 마케팅 4P 요소 분석 |
| 전문분석 | `competitor_comparison_analysis` | 경쟁사 비교 분석 |
| 전문분석 | `product_analysis` | 상품 구매요인 분석 |
| 전략분석 | `comprehensive_brand_monitoring` | 통합 브랜드 모니터링 |
## ⚙️ API 설정
### 지원하는 분석 API
- **Opinion Mining**: 감정 극성 분석
- **Emotion Analysis**: 다차원 감정 분석
- **Keyword Extraction**: 핵심 키워드 추출
- **Document Classification**: 자동 문서 분류
- **Summarization**: 텍스트 요약
- **Named Entity Recognition**: 개체명 인식
### 설정 가능한 파라미터
### Interface: `AnalysisConfig`
데이터 분석 요청을 구성하는 설정 인터페이스입니다.
### 속성 (Properties)
| 이름 | 타입 | 필수 | 설명 |
|------|------|------|------|
| `analysis_type` | `AnalysisCategory` | ✅ | 수행할 분석의 카테고리 (예: 연관어 분석, 감성 분석 등) |
| `apis_to_use` | `RecommendedApiType[]` | ✅ | 사용할 API 목록 (추천되는 MCP API들) |
| `parameters` | `Record<string, unknown>` | ✅ | 분석에 필요한 추가 파라미터 (동적으로 다양한 파라미터 입력 가능) |
| `output_format` | `'json' \| 'csv' \| 'xlsx'` | ✅ | 결과 출력 포맷 |
| `max_processing_time` | `number` | ⛔ | (선택) 분석의 최대 처리 시간 (단위: 초) |
| `enable_parallel_processing` | `boolean` | ⛔ | (선택) 병렬 처리 활성화 여부 |
### 예시
```ts
const config: AnalysisConfig = {
analysis_type: 'SENTIMENT',
apis_to_use: ['SENTIMENT_ANALYSIS', 'KEYWORD_EXTRACTION'],
parameters: {
keyword: 'AI 분석',
source: 'blog',
date_range: ['2025-06-01', '2025-06-07']
},
output_format: 'json',
max_processing_time: 60,
enable_parallel_processing: true
};
```
## 🔧 개발 도구
```bash
# 개발 서버 실행 (SSE 모드)
npm run dev
# STDIO 모드 실행
npm run start:stdio
# 빌드
npm run build
# 프로덕션 실행
npm start
# 테스트
npm test
# 린트 및 타입 체크
npm run lint
npm run typecheck
# 빌드 정리
npm run clean
```
## 🚀 성능 최적화 기능
### 하이브리드 리소스 프리로딩
- **핵심 데이터 캐싱**: SM(13개), TSN3(16개) 카테고리 데이터를 서버 시작시 메모리 프리로드
- **즉시 응답**: 캐시된 데이터는 0ms 응답 시간으로 초고속 처리
- **메모리 효율성**: 필요한 데이터만 선택적으로 캐싱하여 메모리 사용량 최적화
### 메모리 최적화
- **도구 설명 간소화**: 62KB → 약 30KB로 50% 메모리 사용량 감소
- **AI 호환성 유지**: 핵심 정보는 보존하여 AI의 정확한 도구 사용 보장
- **공통 상수 활용**: 반복되는 설명을 상수로 추출하여 중복 제거
## 🐛 디버깅
### 로그 활성화
```
env DEBUG_MODE=true
```
### API 테스트
```
bash npm run test
```
### MCP Inspector 사용
```
bash npm run inspector
```
## 📝 환경별 설정
### 개발 환경 (`.env.development`)
- 디버그 모드 활성화
- 짧은 타임아웃 설정
- 상세한 로깅
### 프로덕션 환경 (`.env.production`)
- 최적화된 설정
- 긴 타임아웃
- 필수 로그만 출력
## 🔗 관련 링크
- [Model Context Protocol](https://github.com/modelcontextprotocol/mcp)
- [MCP SDK Documentation](https://modelcontextprotocol.io/docs)
- [Claude Desktop](https://claude.ai/desktop)
- [TM2 API 문서](http://10.1.41.49:9292)
- [TypeScript 문서](https://www.typescriptlang.org/)
## 📝 추가 정보
### 서버 상태 확인
```bash
curl http://localhost:3000/health
```
### 서버 정보 확인
```bash
curl http://localhost:3000/info
```
### 로그 모니터링
서버 실행 시 다음과 같은 로그를 확인할 수 있습니다:
- `CategoryResourceService 초기화 시작...`: 리소스 프리로딩 시작
- `카테고리 데이터 프리로드 완료: SM (13개 항목)`: SM 카테고리 로드 완료
- `카테고리 데이터 프리로드 완료: TSN3 (16개 항목)`: TSN3 카테고리 로드 완료
- `✅ 서비스 초기화 및 리소스 프리로딩 완료`: 모든 초기화 완료
## 🏭 프로덕션 배포
### PM2를 이용한 프로덕션 배포
#### 1. 환경 설정
```bash
# 환경 설정 파일 생성
cp .env.example .env
# 설정 파일 편집
nano .env
```
#### 2. 프로덕션 서버 시작
```bash
# 프로덕션 모드로 시작 (클러스터 모드)
npm run prod:start
# 또는 직접 스크립트 실행
./scripts/start.sh production
```
#### 3. 서버 관리
```bash
# 서버 상태 확인
npm run prod:status
# 서버 모니터링
npm run prod:monitor
# 로그 확인
npm run prod:logs
# 서버 재시작
npm run prod:restart
# 서버 종료
npm run prod:stop
```
#### 4. 스테이징 환경
```bash
# 스테이징 서버 시작
npm run staging:start
# 스테이징 상태 확인
npm run staging:status
# 스테이징 서버 종료
npm run staging:stop
```
### 시스템 요구사항 (프로덕션)
#### 필수 구성요소
- **Node.js**: 18.0.0 이상
- **Redis**: 캐시 및 세션 관리
- **MariaDB**: 사용자 관리 및 API 사용 통계
- **PM2**: 프로세스 관리
#### 리소스 권장사항
- **CPU**: 2 코어 이상
- **메모리**: 1GB 이상
- **디스크**: 10GB 이상
- **네트워크**: 1Gbps
#### 포트 설정
- **8000**: MCP 서버 (SSE)
- **6379**: Redis
- **3306**: MariaDB
### 보안 고려사항
#### API 키 관리
```bash
# 새 API 키 생성 (MariaDB에 추가)
INSERT INTO api_users (api_key, name, email, organization, rate_limit)
VALUES ('your-secure-api-key', 'User Name', 'user@company.com', 'Company', 1000);
```
#### Rate Limiting
- **기본 제한**: 15분당 100 요청
- **SSE 연결**: 5분당 10 연결
- **메시지**: 1분당 30 메시지
#### 모니터링
```bash
# 실시간 상태 모니터링
./scripts/status.sh --watch
# 헬스체크
./scripts/status.sh --health
# 상세 정보
./scripts/status.sh --detailed
```
### 클러스터 배포
#### 로드밸런서 설정 (Nginx)
```nginx
upstream sometrend_mcp {
server localhost:8000;
server localhost:8001;
server localhost:8002;
}
server {
listen 80;
server_name mcp.sometrend.com;
location / {
proxy_pass http://sometrend_mcp;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
```
#### 다중 인스턴스 실행
```bash
# 포트별 인스턴스 시작
PORT=8000 ./scripts/start.sh production
PORT=8001 ./scripts/start.sh production
PORT=8002 ./scripts/start.sh production
```
---
**버전**: v1.0.0
**MCP 호환성**: v1.18.0
**프로덕션 준비**: ✅ 완료
**최종 업데이트**: 2025-09-15
=======
# tm2_mcp_server_proxy_v3