-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
151 lines (121 loc) · 5.17 KB
/
main.py
File metadata and controls
151 lines (121 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""
main.py - MCP Optimizer 패턴 적용
26개 도구 → 8개 도구 (get 7개 + call 1개 패턴)
토큰 절약률: ~82%
"""
from fastmcp import FastMCP
import warnings
import logging
warnings.filterwarnings('ignore')
# ClientDisconnect 에러 필터링 클래스
class ClientDisconnectFilter(logging.Filter):
"""ClientDisconnect 예외를 필터링하여 로그에 남기지 않음"""
def filter(self, record):
msg = record.getMessage().lower() if hasattr(record, 'getMessage') else str(record.msg).lower()
if "clientdisconnect" in msg or "client disconnect" in msg:
return False
if record.exc_info:
exc_type = record.exc_info[0]
exc_msg = str(record.exc_info[1]) if record.exc_info[1] else ""
if exc_type and ("ClientDisconnect" in str(exc_type) or "client disconnected" in exc_msg.lower()):
return False
return True
# 로깅 설정
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
disconnect_filter = ClientDisconnectFilter()
mcp_loggers = [
"mcp", "mcp.server", "mcp.server.lowlevel",
"mcp.server.streamable_http", "uvicorn", "uvicorn.access"
]
for logger_name in mcp_loggers:
mcp_logger = logging.getLogger(logger_name)
mcp_logger.setLevel(logging.WARNING)
mcp_logger.addFilter(disconnect_filter)
# MCP 서버 인스턴스 생성
mcp = FastMCP("Trading Research MCP Server (Optimized)")
# Server Instructions
mcp.instructions = """
# Trading Strategy Research Agent (Optimized)
이 서버는 get/call 패턴을 사용합니다.
카테고리별 get_xxx_tools로 도구 정보 확인 → call_algotrading_research_tool로 실행
## 사용 가능한 카테고리
| 카테고리 | get 도구 (정보 조회) |
|----------|---------------------|
| 전략 생성 | get_strategy_creation_tools |
| 전략 관리 | get_strategy_management_tools |
| 메타전략 생성 | get_meta_strategy_creation_tools |
| 메타전략 관리 | get_meta_strategy_management_tools |
| 전략 백테스트 | get_backtest_strategy_tools |
| 메타전략 백테스트 | get_backtest_meta_strategy_tools |
| 최적화 | get_optimization_tools |
## 사용법
1. 사용자 요청에 맞는 카테고리의 get_xxx_tools 호출 → 도구 정보 확인
2. call_algotrading_research_tool(tool_name="도구이름", params={...}) 호출 → 실행
"""
# ========================================
# Proxy 도구 등록 (8개: get 7개 + call 1개)
# ========================================
from src.tools.proxy_tools import (
# 카테고리별 도구 정보 조회 (7개)
get_strategy_creation_tools,
get_strategy_management_tools,
get_meta_strategy_creation_tools,
get_meta_strategy_management_tools,
get_backtest_strategy_tools,
get_backtest_meta_strategy_tools,
get_optimization_tools,
# 통합 도구 실행 (1개)
call_algotrading_research_tool,
)
# 카테고리별 도구 정보 조회
mcp.tool()(get_strategy_creation_tools)
mcp.tool()(get_strategy_management_tools)
mcp.tool()(get_meta_strategy_creation_tools)
mcp.tool()(get_meta_strategy_management_tools)
mcp.tool()(get_backtest_strategy_tools)
mcp.tool()(get_backtest_meta_strategy_tools)
mcp.tool()(get_optimization_tools)
# 통합 도구 실행
mcp.tool()(call_algotrading_research_tool)
# ========================================
# MCP Resources 등록
# ========================================
from src.resources import register_strategy_resources
register_strategy_resources(mcp)
# ========================================
# 서버 실행
# ========================================
if __name__ == "__main__":
from src.strategy.loader import list_strategies, list_meta_strategies
from src.config.settings import ensure_directories
ensure_directories()
print("=" * 60)
print("Trading Research MCP Server (Optimized)")
print("26개 도구 -> 8개 도구 (get 7개 + call 1개)")
print("=" * 60)
cert_count = len(list_strategies("certificated"))
uncert_count = len(list_strategies("uncertificated"))
print(f"전략 로드됨 (certificated: {cert_count}, uncertificated: {uncert_count})")
ms_cert_count = len(list_meta_strategies("certificated"))
ms_uncert_count = len(list_meta_strategies("uncertificated"))
print(f"메타전략 로드됨 (certificated: {ms_cert_count}, uncertificated: {ms_uncert_count})")
print("\n등록된 도구 (8개):")
print(" [get] 카테고리별 도구 정보 조회 (7개)")
print(" - get_strategy_creation_tools")
print(" - get_strategy_management_tools")
print(" - get_meta_strategy_creation_tools")
print(" - get_meta_strategy_management_tools")
print(" - get_backtest_strategy_tools")
print(" - get_backtest_meta_strategy_tools")
print(" - get_optimization_tools")
print(" [call] 통합 도구 실행 (1개)")
print(" - call_algotrading_research_tool")
print("\nHTTP 서버 시작 중 (port 8000)...")
print("=" * 60)
try:
mcp.run(transport="http", port=8000)
except KeyboardInterrupt:
logger.info("서버가 사용자에 의해 종료되었습니다.")
except Exception as e:
logger.error(f"서버 오류 발생: {e}", exc_info=True)