MCP활용 강사정보 추출하기

소개

회사와 계약된 100여명의 사외코치들의 정보를 관리하며

필요시 매칭된 코치정보를 추출하여 md파일로 만들어내는 초간단 mcp 사례입니다.

진행 방법

클로드와 mcp를 연결하고, cursor를 통해 내용을 수정하여

댕댕이멍멍님이 알려주신 mcp를 사례를 제 csv파일에 적용하여 활용해보았습니다.

@mcp.tool()
def get_coachInfo_csv_to_md(name: str) -> str:
    """
    주어진 코치 이름에 해당하는 정보를 md 파일로 추출하여 다운로드할 수 있도록 하는 함수.
    
    :param name: 코치의 이름
    :return: md 파일의 경로 또는 오류 메시지
    """
    import os
    import csv
    
    try:
        file_path = os.path.join(os.path.dirname(__file__), 'data', 'coachInfo.csv')
        
        # CSV 파일을 읽고 코치 정보를 찾기
        with open(file_path, 'r', encoding='utf-8') as file:
            csv_reader = csv.reader(file, delimiter='\t')
            
            # 첫 줄은 헤더일 수 있으므로 확인용 변수
            header_checked = False
            indices = {}
            
            for row in csv_reader:
                # 첫 줄이 헤더인 경우 인덱스 설정
                if not header_checked:
                    header_checked = True
                    headers = row
                    indices = {
                        'name': headers.index('name'),
                        'birth': headers.index('birth'),
                        'gender': headers.index('gender'),
                        'phone': headers.index('phone'),
                        'email': headers.index('email'),
                        'coachFrom': headers.index('coachFrom'),
                        'qualificationKCA': headers.index('qualificationKCA'),
                        'qualificationICF': headers.index('qualificationICF'),
                        '2024Activity': headers.index('2024Activity'),
                        'coach': headers.index('coach')
                    }
                    continue
                
                # 코치 이름이 일치하는지 확인
                if row[indices['name']] == name:
                    # 코칭 자격 정보 처리
                    qualification_kca = row[indices['qualificationKCA']] if row[indices['qualificationKCA']] else ""
                    qualification_icf = row[indices['qualificationICF']] if row[indices['qualificationICF']] else ""
                    
                    # 2024 활동 내역 처리
                    activity_2024 = row[indices['2024Activity']].strip() if row[indices['2024Activity']].strip() else "해당사항 없음"
                    activity_2024_lines = "\n".join([f"- {line.strip()}" for line in activity_2024.split('\n')])
                    
                    # 전체 활동 내역 처리
                    coach = row[indices['coach']].strip() if row[indices['coach']].strip() else "해당사항 없음"
                    coach_lines = "\n".join([f"- {line.strip()}" for line in coach.split('\n')])
                    
                    # md 파일 생성
                    md_content = f"## {row[indices['name']]} ( {row[indices['birth']]}, {row[indices['gender']]} )\n"
                    md_content += f"- 전화번호 : {row[indices['phone']]}\n"
                    md_content += f"- email : {row[indices['email']]}\n"
                    md_content += f"- 기본정보 : {row[indices['coachFrom']]}\n"
                    md_content += f"- 코칭자격 : {qualification_kca}. {qualification_icf}\n\n"
                    md_content += "## 자사 계열사 코칭활동\n"
                    md_content += "#### 2024년 활동내역\n"
                    md_content += f"{activity_2024_lines}\n"
                    md_content += "#### 전체 활동내역\n"
                    md_content += f"{coach_lines}\n"
                    
                    md_file_path = os.path.join(os.path.dirname(__file__), f"{name}.md")
                    with open(md_file_path, 'w', encoding='utf-8') as md_file:
                        md_file.write(md_content)
                    
                    return f"MD 파일이 생성되었습니다: {md_file_path}"
        
        # 코치 이름이 발견되지 않으면 메시지 반환
        return f"코치 '{name}'을(를) 찾을 수 없습니다."
        
    except FileNotFoundError:
        return f"데이터 파일을 찾을 수 없습니다. 경로: {os.path.join('data', 'coachInfo.csv')}"
    except Exception as e:
        return f"오류가 발생했습니다: {str(e)}"

결과와 배운 점

100여명의 코치 중, 해당 이름을 검색하면 기본정보를 md파일로 생성하는 내용입니다.

Python3 Python3 Python3 Python3 Python3

도움 받은 글 (옵션)

스터디에서 댕댕이멍멍님이 알려주신 내용으로 시작해봤고,

이후 구글drive에서 데이터를 가져와서 html 형식으로 이미지와 주요 활동내역이 page로 정리될 수 있도록 업데이트해보려고 합니다.

아직 개념상으로 이해한 수준은 아니지만, 따라하며 시도해볼 수 있어서 감사했습니다.

3

뉴스레터 무료 구독