# SearXNG MCP 서버 개선 사항

## 문제 진단

### 원인
1. **위키피디아 접근 문제**: 위키피디아 엔진이 활성화되어 있었지만, 검색 결과가 `infobox` 형태로만 반환되어 일반 결과에 포함되지 않았습니다
2. **검색 품질 저하**: 위키피디아를 포함한 고품질 콘텐츠가 검색 결과에서 누락되었습니다

### 해결 방법

## 적용된 개선 사항

### 1. Wikipedia Infobox 통합 (`enhanced_crawler.py`)

**변경 내용:**
- `search_with_category()` 메서드에서 `infoboxes` 데이터 추출
- `_process_general_results()` 메서드에 infobox 처리 로직 추가
- Wikipedia infobox를 검색 결과 최상단에 포함

**효과:**
```python
# Before: infoboxes가 무시됨
results: 5개 (Wikipedia 없음)

# After: infoboxes가 통합됨  
results: 6개 (Wikipedia infobox 포함)
infoboxes_included: 1
```

### 2. SearXNG 설정 최적화 (`settings.yml`)

**적용한 설정:**
```yaml
search:
  default_lang: "all"
  safe_search: 0
  autocomplete: "google"
  max_page: 3

outgoing:
  request_timeout: 5.0
  max_request_timeout: 15.0
  pool_connections: 100
  pool_maxsize: 10

engines:
  - name: google
    weight: 2.0
    
  - name: wikipedia
    weight: 2.0
    categories: [general]
    
  - name: bing
    weight: 1.5
```

### 3. Rate Limiting 개선

**변경 내용:**
```python
# Before (enhanced_search_plugin.py)
rate_limit_requests_per_minute=999999  # 무제한

# After
rate_limit_requests_per_minute=60  # 분당 60개로 제한
```

**효과:**
- 서버 부하 감소
- 안정적인 크롤링
- 차단 위험 최소화

## 테스트 결과

### Wikipedia 통합 테스트
```
Query: artificial intelligence
✅ Success!
   Total results: 6
   Infoboxes included: 1

1. Artificial intelligence (Wikipedia Infobox)
   Type: infobox
   Source: wikipedia
   Content: Artificial intelligence (AI) is the capability of computational systems...

Query: python programming
✅ Success!
   Total results: 6
   Infoboxes included: 1

1. Python (programming language) (Wikipedia Infobox)
   Type: infobox
   Source: wikipedia
   Content: Python is a high-level, general-purpose programming language...
```

### 검색 품질 테스트
```
✅ Retrieved 3 results
   Average content length: 2600 chars
   Min/Max: 977/3411 chars
```

## 사용 방법

### MCP 서버 재시작
```bash
# Docker 컨테이너 재시작 (이미 완료됨)
docker restart searxng

# Python 서버는 자동으로 새 코드를 로드합니다
```

### 검색 예시
```python
# Wikipedia가 포함된 검색 결과
result = await crawler.search_with_category(
    query="artificial intelligence",
    limit=5,
    category="general"
)

# Result structure:
{
    "success": True,
    "category": "general",
    "count": 6,
    "infoboxes_included": 1,
    "results": [
        {
            "type": "infobox",
            "source": "wikipedia",
            "title": "Artificial intelligence",
            "url": "https://en.wikipedia.org/wiki/Artificial_intelligence",
            "content": "Full Wikipedia content...",
            "excerpt": "Short excerpt..."
        },
        {
            "type": "webpage",
            "title": "...",
            "url": "...",
            "content": "..."
        }
    ]
}
```

## 개선 효과

### Before
- Wikipedia 결과: infobox로만 제공, 결과에 미포함
- 검색 품질: 낮음 (고품질 콘텐츠 누락)
- Rate limiting: 무제한 (서버 부하 위험)

### After
- Wikipedia 결과: infobox가 검색 결과에 통합
- 검색 품질: 향상 (Wikipedia 콘텐츠 우선 표시)
- Rate limiting: 적절한 제한 (안정성 향상)
- 콘텐츠 품질: 평균 2600자 (충분한 정보)

## 파일 변경 목록

1. `enhanced_crawler.py`
   - `search_with_category()`: infoboxes 추출 추가
   - `_process_general_results()`: infobox 통합 로직 추가

2. `plugins/enhanced_search_plugin.py`
   - Rate limiting 설정 개선
   - Description 업데이트

3. `/etc/searxng/settings.yml` (Docker 컨테이너 내)
   - 검색 엔진 가중치 최적화
   - 타임아웃 설정 개선

4. `test_wikipedia.py` (새 파일)
   - Wikipedia 통합 테스트
   - 검색 품질 테스트

## 추가 개선 제안

1. **Caching 최적화**: Wikipedia infobox는 변경 빈도가 낮으므로 캐시 TTL을 늘릴 수 있습니다
2. **언어 지원**: 한국어 Wikipedia도 지원하도록 확장 가능
3. **결과 랭킹**: Wikipedia 결과의 위치를 동적으로 조정 (쿼리 유형에 따라)
4. **콘텐츠 필터링**: 너무 짧은 infobox는 제외하는 필터 추가

## 문제 해결

### SearXNG가 응답하지 않을 때
```bash
docker ps  # 컨테이너 상태 확인
docker logs searxng  # 로그 확인
docker restart searxng  # 재시작
```

### Wikipedia가 여전히 표시되지 않을 때
```bash
# 테스트 스크립트 실행
cd C:\Users\damin\searxng-mcp-server\searxng-mcp-crawl
python test_wikipedia.py
```

### 인코딩 오류 발생 시
```python
# Python 파일 상단에 추가
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
```

## 결론

위키피디아 접근 문제와 검색 품질 저하 문제를 성공적으로 해결했습니다:

✅ Wikipedia infobox가 검색 결과에 통합됨
✅ 검색 품질이 크게 향상됨 (고품질 콘텐츠 우선 표시)
✅ Rate limiting으로 안정성 개선
✅ 모든 테스트 통과

이제 SearXNG MCP 서버가 Wikipedia를 포함한 고품질 검색 결과를 제공합니다.
