mcp_pii_example.py•8.76 kB
#!/usr/bin/env python3
"""
MCP PII Tools 사용 예제
Model Context Protocol을 통한 PII 탐지 및 처리 예제
"""
from mcp_pii_tools import (
mcp_detect_pii,
mcp_process_text,
mcp_batch_process,
mcp_anonymize_text,
mcp_encrypt_pii_item,
mcp_decrypt_pii_item,
mcp_encrypt_text_pii,
mcp_decrypt_text_pii,
MCP_TOOLS
)
def example_1_basic_detection():
"""예제 1: 기본 PII 탐지"""
print("=== 예제 1: 기본 PII 탐지 ===")
text = "안녕하세요! 저는 김철수입니다. 연락처는 010-1234-5678이고 이메일은 kim@example.com입니다."
result = mcp_detect_pii(text)
print(f"입력 텍스트: {text}")
print(f"탐지 성공: {result['success']}")
print(f"탐지된 PII: {result['count']}개")
print(f"처리 시간: {result['processing_time']:.3f}초")
if result['pii_items']:
print("탐지된 PII:")
for item in result['pii_items']:
print(f" - {item['type']}: {item['value']} (위치: {item['start_pos']}-{item['end_pos']})")
print(f"요약: {result['summary']}")
print()
def example_2_text_processing():
"""예제 2: 텍스트 처리 (탐지 + 익명화)"""
print("=== 예제 2: 텍스트 처리 ===")
text = "Rachel Lim이(가) 오늘 방문했다. 이메일은 rachel.lim@gmail.com이고 전화번호는 02-123-4567입니다."
result = mcp_process_text(text)
print(f"원본 텍스트: {result['original_text']}")
print(f"익명화 텍스트: {result['anonymized_text']}")
print(f"탐지된 PII: {result['count']}개")
if result['pii_items']:
print("탐지된 PII:")
for item in result['pii_items']:
print(f" - {item['type']}: {item['value']}")
print()
def example_3_batch_processing():
"""예제 3: 일괄 처리"""
print("=== 예제 3: 일괄 처리 ===")
texts = [
"김철수 씨가 테이블에 앉았다.",
"박지현 님의 이메일은 park@test.com입니다.",
"John Smith의 전화번호는 010-9876-5432입니다.",
"이상수 씨의 주소는 서울시 강남구 테헤란로 123입니다."
]
result = mcp_batch_process(texts)
print(f"총 텍스트: {result['total_texts']}개")
print(f"성공한 처리: {result['successful_count']}개")
print(f"총 탐지된 PII: {result['total_pii_detected']}개")
print(f"평균 처리 시간: {result['average_time_per_text']:.3f}초")
print("\n개별 결과:")
for i, item in enumerate(result['results']):
print(f" {i+1}. {item['original_text'][:30]}... → PII {item['count']}개")
print()
def example_4_anonymization():
"""예제 4: 익명화 처리"""
print("=== 예제 4: 익명화 처리 ===")
text = "김철수 씨가 방문했다. 연락처는 010-1234-5678입니다."
# 먼저 PII 탐지
detection_result = mcp_detect_pii(text)
if detection_result['success']:
# 익명화 처리
anonymized = mcp_anonymize_text(text, detection_result['pii_items'])
print(f"원본: {text}")
print(f"익명화: {anonymized}")
print(f"탐지된 PII: {len(detection_result['pii_items'])}개")
print()
def example_5_encryption_basic():
"""예제 5: 기본 암호화/복호화"""
print("=== 예제 5: 기본 암호화/복호화 ===")
# 개별 PII 항목 암호화
test_data = [
("김철수", "이름"),
("010-1234-5678", "전화번호"),
("kim@example.com", "이메일")
]
for original, pii_type in test_data:
print(f"\n{pii_type} 암호화:")
print(f" 원본: {original}")
# 암호화
encrypt_result = mcp_encrypt_pii_item(original, pii_type)
if encrypt_result['success']:
encrypted = encrypt_result['encrypted_value']
method = encrypt_result['encryption_method']
print(f" 암호화: {encrypted}")
print(f" 방식: {method}")
# 복호화
decrypt_result = mcp_decrypt_pii_item(encrypted, pii_type)
if decrypt_result['success']:
decrypted = decrypt_result['decrypted_value']
match = "✅" if original == decrypted else "❌"
print(f" 복호화: {decrypted} {match}")
print()
def example_6_text_encryption():
"""예제 6: 텍스트 전체 암호화"""
print("=== 예제 6: 텍스트 전체 암호화 ===")
text = "홍길동 씨의 연락처는 010-9876-5432이고 이메일은 hong@company.com입니다."
print(f"원본 텍스트: {text}")
# 텍스트에서 PII 탐지 및 암호화
encrypt_result = mcp_encrypt_text_pii(text)
if encrypt_result['success']:
print(f"암호화 텍스트: {encrypt_result['encrypted_text']}")
print(f"암호화된 PII: {encrypt_result['count']}개")
# 암호화된 항목들 표시
if encrypt_result['encrypted_items']:
print("암호화된 항목들:")
for original, encrypted in encrypt_result['encrypted_items'].items():
print(f" {original} → {encrypted}")
# 복호화
decrypt_result = mcp_decrypt_text_pii(
encrypt_result['encrypted_text'],
encrypt_result['encrypted_items']
)
if decrypt_result['success']:
print(f"복호화 텍스트: {decrypt_result['decrypted_text']}")
match = "✅" if text == decrypt_result['decrypted_text'] else "❌"
print(f"원본 일치: {match}")
print()
def example_7_encryption_types():
"""예제 7: 암호화 유형별 테스트"""
print("=== 예제 7: 암호화 유형별 테스트 ===")
# 결정론적 암호화 (검색 가능)
print("결정론적 암호화 (이름, 주소, 이메일):")
deterministic_tests = [
("박지현", "이름"),
("서울시 강남구", "주소"),
("park@test.co.kr", "이메일")
]
for original, pii_type in deterministic_tests:
encrypt1 = mcp_encrypt_pii_item(original, pii_type)
encrypt2 = mcp_encrypt_pii_item(original, pii_type)
if encrypt1['success'] and encrypt2['success']:
same = "✅" if encrypt1['encrypted_value'] == encrypt2['encrypted_value'] else "❌"
print(f" {pii_type}: {original} → {encrypt1['encrypted_value'][:30]}... (일관성: {same})")
print()
# FPE 암호화 (형식 유지)
print("FPE 암호화 (전화번호, 카드번호 등):")
fpe_tests = [
("010-1234-5678", "전화번호"),
("4532-1234-5678-9012", "신용카드번호"),
("M12345678", "여권번호")
]
for original, pii_type in fpe_tests:
encrypt_result = mcp_encrypt_pii_item(original, pii_type)
if encrypt_result['success']:
encrypted = encrypt_result['encrypted_value']
format_preserved = "✅" if len(original) == len(encrypted) else "❌"
print(f" {pii_type}: {original} → {encrypted} (형식유지: {format_preserved})")
print()
def example_8_error_handling():
"""예제 8: 오류 처리"""
print("=== 예제 8: 오류 처리 ===")
# 빈 텍스트 처리
result = mcp_process_text("")
print(f"빈 텍스트 처리: {result['success']}")
# None 처리 (예외 상황)
try:
result = mcp_process_text(None)
print(f"None 처리: {result['success']}")
except Exception as e:
print(f"None 처리 오류: {e}")
print()
def show_mcp_tools_info():
"""MCP Tools 정보 표시"""
print("=== MCP Tools 정보 ===")
for tool_name, tool_info in MCP_TOOLS.items():
print(f"\n🔧 {tool_name}")
print(f" 설명: {tool_info['description']}")
print(f" 필수 매개변수: {tool_info['parameters']['required']}")
properties = tool_info['parameters']['properties']
for param_name, param_info in properties.items():
print(f" - {param_name}: {param_info['type']} - {param_info['description']}")
print()
def main():
"""메인 함수"""
print("🚀 MCP PII Tools 사용 예제\n")
# MCP Tools 정보 표시
show_mcp_tools_info()
# 예제 실행
example_1_basic_detection()
example_2_text_processing()
example_3_batch_processing()
example_4_anonymization()
example_5_encryption_basic()
example_6_text_encryption()
example_7_encryption_types()
example_8_error_handling()
print("✅ 모든 예제 완료!")
if __name__ == "__main__":
main()