Skip to main content
Glama

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

TableJSON Schema
NameRequiredDescriptionDefault
queryYes검색할 법령용어
displayYes결과 수 (기본:20)
pageYes페이지 (기본:1)
apiKeyNo법제처 Open API 인증키(OC). 사용자가 제공한 경우 전달

Implementation Reference

  • 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");
      }
    }
  • 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). 사용자가 제공한 경우 전달"),
    });
  • 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
    },
  • 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
    }
  • 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 ""
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description only provides basic search behavior and content scope. It does not disclose authentication requirements, rate limits, or side effects. However, it does indicate included features (homonyms, relationships), which is helpful.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Extremely concise single line that conveys the essential purpose and unique features. No unnecessary words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Adequate for a simple search tool with full schema coverage. Lacks details on pagination behavior and output structure, but the schema provides parameter specifics. Could be improved by mentioning pagination or result format.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so the schema already describes parameters. The description adds no additional meaning beyond what is in the schema, but this is acceptable given the schema completeness.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('검색' = search) and resource ('법령용어' = legal terms), and adds that it includes homonyms and term relationships, distinguishing it from generic search tools like 'search_legal_terms'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus alternatives such as 'search_legal_terms' or 'get_legal_term_detail'. The description does not mention context or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/workbookbulb863/korean-law-alio-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server