get_legal_term_kb
Search legal terms and discover homonyms and term relationships. Access clear definitions and related concepts for accurate legal research.
Instructions
[지식베이스] 법령용어 검색. 동음이의어·용어관계 포함.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | 검색할 법령용어 | |
| display | Yes | 결과 수 (기본:20) | |
| page | Yes | 페이지 (기본:1) | |
| apiKey | No | 법제처 Open API 인증키(OC). 사용자가 제공한 경우 전달 |
Implementation Reference
- src/tools/knowledge-base.ts:24-72 (handler)Handler function for get_legal_term_kb tool. Calls the lawSearch.do API with target 'lstrm' (legal term knowledge base), parses the XML response using parseKBXML with root tag 'LsTrmAISearch', and returns formatted results showing term names, homonym indicators, term/article relationship links. On empty results, suggests fallback to search_legal_terms.
export async function getLegalTermKB( apiClient: LawApiClient, args: GetLegalTermKBInput ): Promise<{ content: Array<{ type: string; text: string }>; isError?: boolean }> { try { const xmlText = await apiClient.fetchApi({ endpoint: "lawSearch.do", target: "lstrm", extraParams: { query: args.query, display: (args.display || 20).toString(), page: (args.page || 1).toString(), }, apiKey: args.apiKey, }); const result = parseKBXML(xmlText, "LsTrmAISearch"); if (!result.data) { throw new Error("응답 형식 오류"); } const totalCount = parseInt(result.totalCnt || "0"); const items = result.data; if (totalCount === 0 || items.length === 0) { return { content: [{ type: "text", text: `'${args.query}' 검색 결과가 없습니다.\n\n💡 search_legal_terms로 기본 용어 검색을 시도해보세요.` }], isError: true, }; } let output = `📚 법령용어 지식베이스 (${totalCount}건):\n\n`; for (const item of items) { output += `📌 ${item.법령용어명 || item.용어명}\n`; if (item.동음이의어) output += ` ⚠️ 동음이의어 있음\n`; if (item.용어간관계링크) output += ` 🔗 용어관계: 있음\n`; if (item.조문간관계링크) output += ` 📜 조문관계: 있음\n`; output += `\n`; } output += `\n💡 상세 정의: get_legal_term_detail(query="용어명")`; output += `\n💡 일상용어 연계: get_term_daily_link(query="용어명")`; return { content: [{ type: "text", text: output }] }; } catch (error) { return formatToolError(error, "get_legal_term_kb"); } } - src/tools/knowledge-base.ts:15-20 (schema)Zod schema for get_legal_term_kb: query (required string), display (1-100, default 20), page (min 1, default 1), apiKey (optional).
export const getLegalTermKBSchema = z.object({ query: z.string().describe("검색할 법령용어"), display: z.number().min(1).max(100).default(20).describe("결과 수 (기본:20)"), page: z.number().min(1).default(1).describe("페이지 (기본:1)"), apiKey: z.string().optional().describe("법제처 Open API 인증키(OC). 사용자가 제공한 경우 전달"), }); - src/tool-registry.ts:534-539 (registration)Tool registration entry mapping the name 'get_legal_term_kb' to its schema and handler function, imported from src/tools/knowledge-base.ts.
{ name: "get_legal_term_kb", description: "[지식베이스] 법령용어 검색. 동음이의어·용어관계 포함.", schema: getLegalTermKBSchema, handler: getLegalTermKB }, - src/tools/kb-utils.ts:12-77 (helper)KB utility: KBItem interface with Korean field names, parseKBXML function that extracts items from XML by trying multiple item tags (lstrm, lstrmAI, law, jo, rel, item) and maps fields like 법령용어명, 동음이의어, 용어간관계링크, etc.
export interface KBItem { 법령용어명?: string 용어명?: string 법령용어ID?: string 동음이의어?: boolean 용어간관계링크?: string 조문간관계링크?: string 법령명?: string 법령ID?: string 조문번호?: string 조문제목?: string 관계유형?: string 법령종류?: string 연계용어명?: string 일상용어명?: string } export interface KBParseResult { totalCnt: string data: KBItem[] } export function parseKBXML(xml: string, _rootTag: string): KBParseResult { const result: KBParseResult = { totalCnt: "0", data: [] } // totalCnt 추출 const totalCntMatch = xml.match(/<totalCnt>(\d+)<\/totalCnt>/i) || xml.match(/<검색결과개수>(\d+)<\/검색결과개수>/i) result.totalCnt = totalCntMatch ? totalCntMatch[1] : "0" // 아이템 추출 (다양한 태그명 지원) const itemTags = ["lstrm", "lstrmAI", "law", "jo", "rel", "item"] for (const itemTag of itemTags) { const itemRegex = new RegExp(`<${itemTag}[^>]*>([\\s\\S]*?)<\\/${itemTag}>`, "gi") const matches = xml.matchAll(itemRegex) for (const match of matches) { const itemContent = match[1] const item: KBItem = {} // 공통 필드 추출 item.법령용어명 = extractTag(itemContent, "법령용어명") || extractTag(itemContent, "용어명") item.법령용어ID = extractTag(itemContent, "법령용어ID") || extractTag(itemContent, "용어ID") item.동음이의어 = extractTag(itemContent, "동음이의어존재여부") === "Y" item.용어간관계링크 = extractTag(itemContent, "용어간관계링크") || extractTag(itemContent, "용어관계") item.조문간관계링크 = extractTag(itemContent, "조문간관계링크") || extractTag(itemContent, "조문관계") item.법령명 = extractTag(itemContent, "법령명") item.법령ID = extractTag(itemContent, "법령ID") || extractTag(itemContent, "법령일련번호") item.조문번호 = extractTag(itemContent, "조문번호") || extractTag(itemContent, "조번호") item.조문제목 = extractTag(itemContent, "조문제목") item.관계유형 = extractTag(itemContent, "관계유형") || extractTag(itemContent, "연계유형") item.법령종류 = extractTag(itemContent, "법령종류") || extractTag(itemContent, "법종류") item.연계용어명 = extractTag(itemContent, "연계용어명") || extractTag(itemContent, "관련용어") item.일상용어명 = extractTag(itemContent, "일상용어명") || extractTag(itemContent, "일상용어") // 빈 객체가 아닌 경우만 추가 if (item.법령용어명 || item.법령명 || item.연계용어명) { result.data.push(item) } } if (result.data.length > 0) break } return result } - src/lib/xml-parser.ts:17-33 (helper)XML tag extraction utility supporting CDATA, regular tags, and self-closing tags. Used by kb-utils.ts parseKBXML to extract Korean-named fields from legal term API responses.
export function extractTag(content: string, tag: string): string { // CDATA 형식 먼저 시도 const cdataRegex = new RegExp(`<${tag}><!\\[CDATA\\[([\\s\\S]*?)\\]\\]><\\/${tag}>`) const cdataMatch = content.match(cdataRegex) if (cdataMatch) return cdataMatch[1] // 일반 형식 (태그 내 중첩 태그 허용: [\s\S]*? 사용) const regex = new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`) const match = content.match(regex) if (match) return match[1].trim() // Self-closing 태그: <tag/> const selfClosingRegex = new RegExp(`<${tag}\\s*/>`) if (selfClosingRegex.test(content)) return "" return "" }