Content
# OpenCode_MCP
[과제3] 오픈코드(OpenCode) 연동 MCP 개발 — **준법감시 사전확인 어시스턴트**
AI에 업무 내용을 입력하기 전에, OpenCode에 자연어로 요청하면 로컬 Ollama 모델이 우리 MCP 서버의
준법감시 툴을 호출해 민감정보·공시위험을 사전 점검하는 체인을 구현한다.
```
사용자 자연어 요청 → OpenCode → Ollama (qwen3-instruct-16k, 로컬) → MCP 서버 (mcp_server.py)
```
**과제 제약: MCP 서버에서 외부 상용 LLM API(OpenAI/Anthropic/Google) 및 Web/외부 API 호출 금지 — 로컬 전용.**
> **구현 범위 안내:** 4개 툴 모두 실제 로컬 로직으로 동작한다. `search_compliance_rule`과
> `check_disclosure_risk`는 `compliance/rag/data/`의 로컬 코퍼스를 청킹한 뒤 Ollama `bge-m3`
> 임베딩과 Chroma 벡터DB, BM25 하이브리드 검색을 사용한다. 검색된 원문 snippet과
> 결정론 키워드 신호만 qwen 로컬 LLM에 전달해 근거 기반 자연어 답변을 만들며,
> 법적 적합성은 단정하지 않는다.
## Tool List
| Tool | Status | Function | Implementation Plan |
| --- | --- | --- | --- |
| `scan_sensitive_info(text)` | ✅ **Actual** | Detect and mask sensitive information using regular expressions | — |
| `check_disclosure_risk(text)` | ✅ **Actual** | Conservatively guide disclosure risks and automatically record audit logs | — |
| `search_compliance_rule(query)` | ✅ **Actual** | Return relevant snippets from local regulations corpus using Chroma + BM25 hybrid search | — |
| `log_ai_usage(tool_name, input_text, result_summary, requires_human_review)` | ✅ **Actual** | Record audit logs using SQLite hash chain | — |
Design Principle: All tools do not **definitely** determine compliance or non-compliance, but provide guidance on regulatory references and the need for human review (`requires_human_review`). All tools respond with a common output schema (dict) defined in `compliance/schema.py`.
## File Configuration
| File | Role |
| --- | --- |
| `mcp_server.py` | MCP server (Python SDK `FastMCP`, stdio). Registers the above 4 tools |
| `compliance/` | Tool logic — `detector.py`, `rag/`, `audit/`, `schema.py` |
| `compliance/rag/data/` | Local regulations corpus (PDF/text). Not committed to Git |
| `opencode.json` | OpenCode settings — Ollama provider + MCP server (`local`) registration |
| `Modelfile.instruct` | For generating derivative models (`qwen3-instruct-16k`) |
| `scripts/check_client.py` | Manual verification client (stdio) |
| `tests/` | Pytest unit tests (run in CI) |
## Development Environment Setup
### 1. Prerequisites
- Python 3.11+, Node.js (npm)
- Install [Ollama](https://ollama.com) and run `ollama serve`
### 2. Model Preparation
Generate derivative models:
```bash
ollama pull qwen3:4b-instruct
ollama create qwen3-instruct-16k -f Modelfile.instruct
ollama pull bge-m3
```
### 3. OpenCode Installation
```bash
npm install -g opencode-ai
```
### 4. Python Environment
Create a virtual environment:
```bash
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt
```
Fix `chromadb` version:
### 5. RAG Corpus Preparation
Place regulation PDFs or text files in `compliance/rag/data/`. This path is treated as local data and ignored by `.gitignore`.
## Verification
```bash
# 1. MCP server standalone (without OpenCode) — list and call all 4 tools
.venv/bin/python scripts/check_client.py
# 2. OpenCode ↔ MCP connection verification (from repo root)
opencode mcp list
# 3. E2E: natural language → LLM → tool call
opencode run --auto -m ollama/qwen3-instruct-16k \
"Scan for sensitive information in this text: 담당자 연락처는 010-1234-5678 입니다"
# 4. RAG direct verification
.venv/bin/python - <<'PY'
from compliance import rag
print(rag.search_compliance_rule("준법감시인 사전확인 광고 투자권유")["summary"])
print(rag.check_disclosure_risk("3분기 실적 발표 전 내부 검토 자료")["summary"])
PY
```
## Notes
- **CPU-only machine performance**: Cold fill ~30 tok/s → first request may take 5 minutes+. Warm-up is essential.
- **Minimize tool count**: Tool schema increases fill tokens, making responses slower. Disable built-in tools and register only MCP 4 tools.
- **Split long sessions**: Accumulated conversation and tool results increase fill tokens. Use new sessions for demo scenarios.
## Development Rules
- GitFlow: `feature/*` → `develop` → `main` (no direct push to main/develop, PR + 1 approval required)
- Commit convention: `type: English description` (e.g., `feat: add account number detection`)