@minjunkwon/localgovernment-welfare-mcp-server
Version:
MCP server for Korean Local Government Welfare Services - provides intelligent search and information retrieval for local government social welfare programs
114 lines • 5.21 kB
JavaScript
import xml2js from 'xml2js';
const SERVICE_KEY = 'Z%2FbWsLsT6z7AAvV4XvUvq9Qb%2FhDVfAV9%2FoRoHOcRFf%2FbsRPdyCRi%2BE3J5oJ%2FGpS%2FlW%2B7G0S8ecCcc5NlcJFzbw%3D%3D';
const BASE_URL = 'https://apis.data.go.kr/B554287/LocalGovernmentWelfareInformations';
export class LocalWelfareAPI {
serviceKey;
constructor(serviceKey) {
this.serviceKey = serviceKey || SERVICE_KEY;
}
async makeRequest(endpoint, params) {
const url = new URL(`${BASE_URL}/${endpoint}`);
// 이미 인코딩된 서비스키를 직접 설정
url.search = `serviceKey=${this.serviceKey}`;
// params가 null이나 undefined인지 체크
if (params && typeof params === 'object') {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
url.searchParams.append(key, value.toString());
}
});
}
// 디버깅을 위한 URL 출력
console.error('API Request URL:', url.toString());
try {
const response = await fetch(url.toString());
if (!response.ok) {
const errorText = await response.text();
console.error('HTTP Error Response:', errorText);
throw new Error(`HTTP error! status: ${response.status}, response: ${errorText}`);
}
const xmlText = await response.text();
console.error('Raw XML Response:', xmlText.substring(0, 500) + '...');
// XML 파싱 시 더 안전한 처리 - 매번 새로운 파서 인스턴스 생성
try {
const parser = new xml2js.Parser({
explicitArray: false,
ignoreAttrs: true,
trim: true,
normalize: true,
normalizeTags: false
});
const jsonResult = await parser.parseStringPromise(xmlText);
return jsonResult;
}
catch (parseError) {
console.error('XML Parse Error:', parseError);
console.error('Failed XML:', xmlText);
throw new Error(`XML parsing failed: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
}
}
catch (error) {
console.error('Request Error Details:', error);
if (error instanceof Error) {
throw error;
}
throw new Error(`API request failed: ${String(error)}`);
}
}
async getLocalWelfareList(params) {
if (!params || typeof params !== 'object') {
throw new Error('Invalid params provided to getLocalWelfareList');
}
const requestParams = {
pageNo: params.pageNo || 1,
numOfRows: params.numOfRows || 10
};
// spread 연산자 대신 명시적으로 복사
const paramKeys = Object.keys(params);
for (const key of paramKeys) {
if (params[key] !== undefined) {
requestParams[key] = params[key];
}
}
const result = await this.makeRequest('LcgvWelfarelist', requestParams);
// 디버깅을 위한 전체 응답 로깅
console.error('API Response:', JSON.stringify(result, null, 2));
// 다양한 응답 구조 확인
if (!result || !result.wantedList) {
throw new Error(`API Error: Invalid response structure. Response: ${JSON.stringify(result)}`);
}
const resultCode = result.wantedList.resultCode;
const resultMessage = result.wantedList.resultMessage;
if (resultCode !== '0' && resultCode !== 0) {
throw new Error(`API Error: ${resultMessage || 'Unknown error'} (Code: ${resultCode})`);
}
// 단일 항목을 배열로 변환
if (result.wantedList?.servList && !Array.isArray(result.wantedList.servList)) {
result.wantedList.servList = [result.wantedList.servList];
}
return result;
}
async getLocalWelfareDetail(params) {
console.error('getLocalWelfareDetail called with params:', params);
if (!params || typeof params !== 'object') {
throw new Error('Invalid params provided to getLocalWelfareDetail');
}
if (!params.servId) {
throw new Error('servId is required');
}
const result = await this.makeRequest('LcgvWelfaredetailed', params);
// 디버깅을 위한 전체 응답 로깅
console.error('Detail API Response:', JSON.stringify(result, null, 2));
// 응답 구조 확인
if (!result || !result.wantedDtl) {
throw new Error(`API Error: Invalid response structure. Response: ${JSON.stringify(result)}`);
}
const resultCode = result.wantedDtl.resultCode;
const resultMessage = result.wantedDtl.resultMessage;
if (resultCode !== '0' && resultCode !== '00') {
throw new Error(`API Error: ${resultMessage || 'Unknown error'} (Code: ${resultCode})`);
}
return result;
}
}
//# sourceMappingURL=api.js.map