feat: drug_dur_check — 식약처 DUR 의약품 안전정보 조회 도구

닥터앱 "복약·검사" 탭이 핵심인데 약 정보를 조회할 수단이 없어, 상호작용·금기를
모델이 기억으로 답하거나 web_search로 블로그를 물어오고 있었다.

- data.go.kr DURPrdlstInfoService03(품목 기반) 연동. 제품명 부분일치로
  병용금기/임부금기/특정연령대금기/용량주의/투여기간주의/효능군중복/분할주의 조회
- 병용금기는 상대 성분 + 사유별로 묶어 요약(제품 단위론 수백 행이라 무의미)
- getOldSderTabooInfoList03(노인주의)는 API가 폐기 응답 → 목록에서 제외
- 성분 기반 서비스(DURIrdntInfoService03)는 이 키에 미승인 상태라 미사용
- 게이트: 닥터앱(dr_) 세션 무조건 + 일반 챗은 약물 상호작용 문맥 키워드
- 키는 vault(mfds.dur_api_key), config.json엔 참조만. SECRET_FIELD_MAP 등재

tests +2, 468개 통과. 실 API로 타이레놀·심바스타틴 병용금기 확인.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HdchNLTHsyYahp2PVQjoym
This commit is contained in:
kimandClaude Sonnet 5 committed 2026-09-02 17:11:28 +09:00
1 parent 7b0223b071
commit b0c098e76d
8 files changed
+237 -3

No files matched your search

+3
View File
@@ -395,5 +395,8 @@
},
"legal": {
"law_go_kr_api_key": "vault:legal.law_go_kr_api_key"
},
"mfds": {
"dur_api_key": "vault:mfds.dur_api_key"
}
}
+1
View File
@@ -332,6 +332,7 @@ const SECRET_FIELD_MAP: Array<[string[], string]> = [
[['news', 'newsdata_api_key'], 'news.newsdata_api_key'],
[['nvr', 'password'], 'nvr.password'],
[['legal', 'law_go_kr_api_key'], 'legal.law_go_kr_api_key'],
[['mfds', 'dur_api_key'], 'mfds.dur_api_key'],
[['legal', 'courtlistener_api_key'], 'legal.courtlistener_api_key'],
[['writer', 'providers', 'google_books', 'apiKey'], 'writer.providers.google_books.apiKey'],
[['writer', 'providers', 'aladin', 'apiKey'], 'writer.providers.aladin.apiKey'],
+20
View File
@@ -742,6 +742,26 @@ export function createBuildTools(isOrchestrationSkillEnabled: () => boolean) {
},
},
},
{
type: 'function',
function: {
name: 'drug_dur_check',
description:
"식약처(MFDS) DUR 데이터로 특정 약의 병용금기·임부금기·연령금기·용량주의·효능군중복 등을 조회한다. " +
"복용 중인 약 이름(제품명/브랜드명)을 주면 해당 성분에 등록된 DUR 경고를 성분·사유별로 정리해 준다. " +
"제품명은 부분일치이므로 '타이레놀'처럼 아는 만큼만 넣으면 된다. 한국 허가 의약품 전용. " +
"약 상호작용·금기 질문에는 web_search 대신 이 도구를 쓸 것. " +
"답변에는 '식약처 DUR 참고용이며 최종 판단은 약사·의사'라는 취지를 반드시 덧붙일 것.",
parameters: {
type: 'object', required: ['drug_name'],
properties: {
drug_name: { type: 'string', description: '제품명 또는 브랜드명 (부분일치). 예: "타이레놀", "쿠마딘정2mg"' },
checks: { type: 'array', items: { type: 'string', enum: ['병용금기', '임부금기', '특정연령대금기', '용량주의', '투여기간주의', '효능군중복', '분할주의'] },
description: '조회 항목. 생략 시 [병용금기, 임부금기, 특정연령대금기, 효능군중복]' },
},
},
},
},
// Email tools
{
type: 'function',
+6
View File
@@ -97,6 +97,11 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string)
// cms_hospital_compare — CMS Medicare hospital data (ownership / star rating / mortality /
// readmission). ~450-token schema, only relevant to US-hospital-performance questions, so
// gate it rather than carry it on every turn.
// drug_dur_check — 식약처 DUR(병용금기·임부금기 등). 닥터앱 탭에서는 무조건, 일반 챗에서는
// 약 이름·상호작용을 실제로 물을 때만. "약"은 너무 흔해서 단독으로 넣지 않고 문맥형으로만.
const hasDrugKeyword =
/병용금기|임부금기|수유부|복약|약물\s*상호작용|약\s*상호작용|같이\s*(먹어|복용|드셔)|함께\s*(먹어|복용)|DUR|처방전|약봉투|성분\s*겹|중복\s*처방|이\s*약(을|은|이|,|\s|의|도|과|와|\?)|먹는\s*약|드시는\s*약|복용\s*중(인|during)?\s*약|drug\s*interaction|contraindicat/i
.test(message);
const hasHospitalDataKeyword =
/\bCMS\b|메디케어|\bmedicare\b|care\s*compare|hospital\s*compare|hospital\s*(rating|ratings|star|quality|ownership|performance)|병원.{0,6}(비교|평가|등급|순위|별점|소유|영리|비영리|성과|퀄리티|데이터)|(영리|비영리|투자자\s*소유).{0,4}병원|(for-?profit|non-?profit|nonprofit|investor-owned).{0,20}hospital/i
.test(message);
@@ -301,6 +306,7 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string)
if (pptxToolNames.has(name) && !hasPptxKeyword) return false;
if (academicToolNames.has(name) && !isDoctorAppSession && !hasPptxKeyword && !hasAcademicKeyword) return false;
if (name === 'cms_hospital_compare' && !hasHospitalDataKeyword) return false;
if (name === 'drug_dur_check' && !isDoctorAppSession && !hasDrugKeyword) return false;
if (emailToolNames.has(name) && !hasEmailKeyword) return false;
if (name === 'kakao_send_message' && !hasKakaoKeyword) return false;
if (name === 'sqlite_query' && !hasSqliteKeyword) return false;
+191
View File
@@ -0,0 +1,191 @@
import { ToolResult } from '../types.js';
import { getConfig } from '../config/config.js';
/**
* mfds.ts — 식약처(MFDS) 의약품 DUR 품목정보 조회
*
* data.go.kr `DURPrdlstInfoService03` (건강보험심사평가원·식약처 DUR).
* 제품명(itemName) 부분일치로만 필터가 걸린다 — ingrName/typeName 파라미터는
* 서버가 무시한다(2026-09-02 실측). 그래서 사용자가 준 약 이름을 itemName에
* 그대로 넣고 부분일치로 찾는다.
*
* getOldSderTabooInfoList03(노인주의)는 "해당 오픈API 서비스가 없거나 폐기됨"으로
* 응답하므로 목록에서 뺐다. 노인 관련 경고는 특정연령대금기(SpcifyAgrde)에 일부 포함.
*
* 개인 복약 정리 보조용 — 처방·진단을 대체하지 않는다. 최종 판단은 약사·의사.
*/
const BASE = 'https://apis.data.go.kr/1471000/DURPrdlstInfoService03';
interface CheckSpec {
key: string;
label: string;
op: string;
/** 병용금기는 상대 약(MIXTURE_*)이 핵심이라 별도 포맷 */
kind: 'interaction' | 'attention';
}
const CHECKS: CheckSpec[] = [
{ key: '병용금기', label: '병용금기 (같이 먹으면 안 되는 약)', op: 'getUsjntTabooInfoList03', kind: 'interaction' },
{ key: '임부금기', label: '임부금기 (임신 중 금기)', op: 'getPwnmTabooInfoList03', kind: 'attention' },
{ key: '특정연령대금기', label: '특정연령대금기 (소아·고령자 등)', op: 'getSpcifyAgrdeTabooInfoList03', kind: 'attention' },
{ key: '용량주의', label: '용량주의 (1일 최대용량 등)', op: 'getCpctyAtentInfoList03', kind: 'attention' },
{ key: '투여기간주의', label: '투여기간주의', op: 'getMdctnPdAtentInfoList03', kind: 'attention' },
{ key: '효능군중복', label: '효능군중복 (성분이 겹치는 약)', op: 'getEfcyDplctInfoList03', kind: 'attention' },
{ key: '분할주의', label: '분할주의 (쪼개 먹으면 안 되는 제형)', op: 'getSeobangjeongPartitnAtentInfoList03', kind: 'attention' },
];
const DEFAULT_CHECKS = ['병용금기', '임부금기', '특정연령대금기', '효능군중복'];
const ROWS = 100;
function getApiKey(): string | undefined {
try {
const cm = getConfig();
const cfg: any = cm.getConfig();
return cm.resolveSecret(cfg?.mfds?.dur_api_key) || undefined;
} catch {}
return undefined;
}
function asArray(items: any): any[] {
if (items == null || items === '') return [];
return Array.isArray(items) ? items : [items];
}
/** "이트라코나졸고체분산체", "클래리트로마이신제피과립" → "이트라코나졸", "클래리트로마이신" */
function baseIngr(name: string): string {
return String(name || '')
.replace(/(고체분산체|제피과립|정제|나트륨|칼륨|염산염|황산염|인산염|말레산염|타르타르산염|스테아르산염|수화물|무수물|프로필렌글리콜|스티노프레이트)+$/g, '')
.trim() || String(name || '').trim();
}
async function callDur(op: string, itemName: string, apiKey: string): Promise<{ rows: any[]; total: number; error?: string }> {
const p = new URLSearchParams();
p.set('serviceKey', apiKey);
p.set('type', 'json');
p.set('pageNo', '1');
p.set('numOfRows', String(ROWS));
p.set('itemName', itemName);
let res: Response;
try {
res = await fetch(`${BASE}/${op}?${p}`, {
signal: AbortSignal.timeout(15_000),
headers: { Accept: 'application/json', 'User-Agent': 'SmallClaw/1.0 dur-check' },
});
} catch (e: any) {
return { rows: [], total: 0, error: `요청 실패: ${e?.message || e}` };
}
const text = await res.text().catch(() => '');
if (!res.ok) return { rows: [], total: 0, error: `HTTP ${res.status}` };
let data: any;
try { data = JSON.parse(text); } catch { return { rows: [], total: 0, error: `응답 파싱 실패: ${text.slice(0, 120)}` }; }
// data.go.kr 공통 오류 포맷
const authErr = data?.OpenAPI_ServiceResponse?.cmmMsgHeader?.returnAuthMsg
|| data?.OpenAPI_ServiceResponse?.cmmMsgHeader?.errMsg;
if (authErr) return { rows: [], total: 0, error: String(authErr) };
const rc = data?.header?.resultCode;
if (rc && rc !== '00') return { rows: [], total: 0, error: `${data?.header?.resultMsg || rc}` };
return { rows: asArray(data?.body?.items), total: Number(data?.body?.totalCount || 0) };
}
export const drugDurCheckTool = {
name: 'drug_dur_check',
description:
"식약처(MFDS) 의약품 DUR 데이터로 특정 약의 병용금기·임부금기·연령금기·용량주의·효능군중복 등을 조회한다. " +
"복용 중인 약 이름(제품명/브랜드명)을 주면 해당 성분에 등록된 DUR 경고를 성분·사유별로 정리해 돌려준다. " +
"제품명은 부분일치로 찾으므로 '타이레놀', '아스피린프로텍트정100mg'처럼 아는 만큼만 넣으면 된다. " +
"한국 허가 의약품 전용. 이 데이터는 처방·진단을 대체하지 않으며 최종 판단은 약사·의사 몫임을 답변에 반드시 명시할 것. " +
"약 상호작용·금기 질문에는 web_search 대신 이 도구를 쓸 것.",
schema: {
drug_name: '조회할 약의 제품명 또는 브랜드명 (부분일치). 예: "타이레놀", "쿠마딘정2mg"',
checks: `조회 항목 배열. 생략 시 [${DEFAULT_CHECKS.join(', ')}]. 가능: ${CHECKS.map(c => c.key).join(', ')}`,
},
jsonSchema: {
type: 'object',
required: ['drug_name'],
properties: {
drug_name: { type: 'string' },
checks: { type: 'array', items: { type: 'string', enum: CHECKS.map(c => c.key) } },
},
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const drugName = String(args?.drug_name || '').trim();
if (!drugName) return { success: false, error: 'drug_name(제품명)이 필요합니다.' };
const apiKey = getApiKey();
if (!apiKey) {
return { success: false, error: '식약처 DUR API 키 미설정. config.json에 { "mfds": { "dur_api_key": "..." } } 추가 (저장 시 자동 vault 이관).' };
}
const want = asArray(args?.checks).map(String);
const specs = CHECKS.filter(c => (want.length ? want.includes(c.key) : DEFAULT_CHECKS.includes(c.key)));
if (!specs.length) return { success: false, error: `checks 값이 올바르지 않습니다. 가능: ${CHECKS.map(c => c.key).join(', ')}` };
const results = await Promise.all(specs.map(async (spec) => ({ spec, ...(await callDur(spec.op, drugName, apiKey)) })));
const lines: string[] = [`💊 DUR 조회: "${drugName}" (제품명 부분일치)`, ''];
const data: Record<string, any> = {};
let anyHit = false;
const errs: string[] = [];
for (const { spec, rows, total, error } of results) {
if (error) { errs.push(`${spec.key}: ${error}`); continue; }
if (!rows.length) { lines.push(`✅ ${spec.label}: 해당 없음`); data[spec.key] = []; continue; }
anyHit = true;
if (spec.kind === 'interaction') {
// 상대 성분 + 사유별로 묶는다 (제품 단위로는 수백 행이라 무의미)
const groups = new Map<string, { partner: string; reason: string; example: string; count: number }>();
for (const r of rows) {
const partner = baseIngr(r.MIXTURE_INGR_KOR_NAME || r.MIXTURE_INGR_ENG_NAME || '(미상)');
const reason = String(r.PROHBT_CONTENT || '').trim().replace(/\s+/g, ' ') || '(사유 미기재)';
const gk = `${partner}|${reason}`;
const g = groups.get(gk) || { partner, reason, example: r.MIXTURE_ITEM_NAME || '', count: 0 };
g.count++;
groups.set(gk, g);
}
const self = baseIngr(rows[0].INGR_KOR_NAME || rows[0].INGR_NAME || drugName);
lines.push(`⛔ ${spec.label} — 성분 "${self}" 기준${total > rows.length ? ` (상위 ${rows.length}/${total}행)` : ''}`);
const arr = [...groups.values()].sort((a, b) => b.count - a.count);
for (const g of arr) lines.push(` • ${g.partner} 계열과 병용 금지 — ${g.reason}${g.example ? ` (예: ${g.example.trim()})` : ''}`);
data[spec.key] = arr.map(g => ({ partner_ingredient: g.partner, reason: g.reason, example_product: g.example }));
} else {
// 성분 + 사유(+비고)별로 묶는다
const groups = new Map<string, { ingr: string; reason: string; remark: string; example: string; count: number }>();
for (const r of rows) {
const ingr = String(r.INGR_NAME || r.INGR_KOR_NAME || '(미상)').trim();
const reason = String(r.PROHBT_CONTENT || '').trim().replace(/\s+/g, ' ');
const remark = String(r.REMARK || '').trim().replace(/\s+/g, ' ');
const gk = `${ingr}|${reason}|${remark}`;
const g = groups.get(gk) || { ingr, reason, remark, example: r.ITEM_NAME || '', count: 0 };
g.count++;
groups.set(gk, g);
}
lines.push(`⚠️ ${spec.label}${total > rows.length ? ` (상위 ${rows.length}/${total}행)` : ''}`);
const arr = [...groups.values()];
for (const g of arr) {
const bits = [g.ingr, g.reason || null, g.remark ? `[${g.remark}]` : null].filter(Boolean);
lines.push(` • ${bits.join(' — ')}${g.example ? ` (예: ${g.example.trim()})` : ''}`);
}
data[spec.key] = arr.map(g => ({ ingredient: g.ingr, content: g.reason, remark: g.remark, example_product: g.example }));
}
lines.push('');
}
if (errs.length) { lines.push(''); lines.push(`(조회 실패: ${errs.join(' / ')})`); }
lines.push('');
lines.push('출처: 식약처 DUR 품목정보(data.go.kr). 이 정보는 참고용이며 처방·복약 조정은 반드시 약사·의사와 상의하세요.');
if (!anyHit && !errs.length) {
return {
success: true,
stdout: `"${drugName}"에 대해 조회한 DUR 항목(${specs.map(s => s.key).join(', ')})에서 등록된 경고가 없습니다.\n` +
`제품명이 정확하지 않으면 결과가 안 나올 수 있습니다 — 처방전·약봉투의 정확한 제품명으로 다시 시도해 보세요.\n\n` +
`출처: 식약처 DUR 품목정보(data.go.kr).`,
data: { drug_name: drugName, checks: data },
};
}
return { success: true, stdout: lines.join('\n'), data: { drug_name: drugName, checks: data } };
},
};
+3
View File
@@ -29,6 +29,7 @@ import { kakaoSendTool } from './kakao.js';
import { koreanLawSearchTool, koreanLawFetchTool, usCaseSearchTool } from './legal.js';
import { excelReadTool, excelWriteTool } from './excel.js';
import { cmsHospitalCompareTool } from './cms.js';
import { drugDurCheckTool } from './mfds.js';
export interface Tool {
name: string;
@@ -201,6 +202,8 @@ class ToolRegistry {
this.registerSafe(openalexSearchTool);
this.registerSafe(semanticSearchTool);
this.registerSafe(cmsHospitalCompareTool);
// 식약처 DUR 의약품 안전정보 (병용금기·임부금기·연령금기 등)
this.registerSafe(drugDurCheckTool);
// Document & data tools
this.registerSafe(pdfReadTool);
this.registerSafe(pdfExtractImagesTool);
+3
View File
@@ -387,6 +387,9 @@ export interface SmallClawConfig {
legal?: {
law_go_kr_api_key?: string;
};
mfds?: {
dur_api_key?: string;
};
semantic_scholar?: {
api_key?: string;
};
+10 -3
View File
@@ -307,18 +307,25 @@ describe('앱 세션 게이트 — 탭 안에서는 키워드 없이도 열린
}
});
test('닥터 탭은 학술 도구를 키워드 없이 받는다', () => {
test('닥터 탭은 학술 도구 + DUR 도구를 키워드 없이 받는다', () => {
for (const sid of ['dr_main', 'dr_case_42', 'dr_a1b2c3']) {
const f = inApp(sid, '이 약 장기복용해도 괜찮을까요?');
for (const n of ['pubmed_search', 'pubmed_fetch', 'pubmed_fulltext', 'openalex_search', 'semantic_search']) {
for (const n of ['pubmed_search', 'pubmed_fetch', 'pubmed_fulltext', 'openalex_search', 'semantic_search', 'drug_dur_check']) {
assert.equal(f(n), true, `${sid}: ${n} 누락`);
}
}
});
test('메인챗에서도 약물 상호작용 문맥이면 drug_dur_check는 열린다', () => {
assert.equal(inApp('sess_main', '와파린이랑 아스피린 같이 먹어도 되나요?')('drug_dur_check'), true);
assert.equal(inApp('sess_main', '이 약 병용금기 있어?')('drug_dur_check'), true);
// 학술 도구는 닥터 탭 밖에서는 여전히 키워드 필요
assert.equal(inApp('sess_main', '와파린이랑 아스피린 같이 먹어도 되나요?')('pubmed_search'), false);
});
test('메인챗은 영향받지 않는다 — 키워드 없으면 그대로 닫힘', () => {
const f = inApp('sess_main', '오늘 기분 어때?');
for (const n of ['korean_law_search', 'news_search', 'excel_read', 'pubmed_search', 'openalex_search']) {
for (const n of ['korean_law_search', 'news_search', 'excel_read', 'pubmed_search', 'openalex_search', 'drug_dur_check']) {
assert.equal(f(n), false, `${n} 이(가) 메인챗에 새어나옴`);
}
});