Skip to main content
Glama

analyze_regulation_delegation

Extract references to higher-level laws and internal regulations from Korean public institution regulations. Optionally retrieve law IDs via external law search.

Instructions

[ALIO] 특정 규정 본문에서 상위 법령/내부 상위규정 참조 추출. includeLawLookup=true 시 법제처 searchLaw 연계. 법제처 search_law 도구와의 교량.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
institutionYes기관코드(apbaId) 또는 기관명 일부
regIdNo규정 ID (list_alio_regulations 의 regId)
titleNo규정 제목 일부. regId 대체
includeLawLookupYes외부 법령 참조를 법제처 searchLaw 로 조회해 MST/lawId 첨부 (최대 5개, 느림)
lawLookupLimitYessearchLaw 호출 개수 상한

Implementation Reference

  • The main handler function `analyzeRegulationDelegation` — loads regulation index, finds the institution and regulation, extracts external/internal references from markdown body, optionally looks up external laws via searchLaw API, and formats output.
    export async function analyzeRegulationDelegation(
      apiClient: LawApiClient,
      input: AnalyzeRegulationDelegationInput
    ): Promise<ToolResponse> {
      try {
        const idx = await loadIndex()
        const inst = findInstitution(idx, input.institution)
        if (!inst) {
          return {
            content: [{ type: "text", text: `기관을 찾을 수 없습니다: '${input.institution}'` }],
            isError: true,
          }
        }
        const manifest = idx.manifests.get(inst.apbaId)
        if (!manifest) {
          return {
            content: [{ type: "text", text: `[${inst.apbaId}] manifest 없음` }],
            isError: true,
          }
        }
        const entry =
          (input.regId && manifest.regulations.find((r) => r.regId === input.regId)) ||
          (input.title && manifest.regulations.find((r) => r.title.includes(input.title!)))
        if (!entry) {
          return {
            content: [{ type: "text", text: "규정을 찾을 수 없습니다." }],
            isError: true,
          }
        }
        if (!entry.mdPath) {
          return {
            content: [
              {
                type: "text",
                text: `${entry.title} — 본문이 없어 참조 추출 불가 (첨부파일 미수집).`,
              },
            ],
          }
        }
        const md = await readRegulationMd(inst.apbaId, entry.regId)
        if (!md || entry.parseError) {
          return {
            content: [
              {
                type: "text",
                text: `${entry.title} — 본문이 파싱되지 않아 참조 추출 불가 (${entry.parseError || "본문 없음"}).`,
              },
            ],
          }
        }
    
        const refs = extractReferences(md)
    
        // 내부 참조: 같은 기관 manifest 에서 제목 부분일치로 regId 매칭
        const internalResolved = refs.internal.map((r) => {
          const match = manifest.regulations.find((reg) => reg.title.includes(r.ruleName))
          return {
            ...r,
            resolvedRegId: match?.regId,
            resolvedTitle: match?.title,
          }
        })
    
        // 외부 법령: 선택적 법제처 조회
        type ExternalResolved = (typeof refs.external)[number] & {
          lawId?: string
          mst?: string
          lookupError?: string
        }
        const externalResolved: ExternalResolved[] = [...refs.external]
        if (input.includeLawLookup && refs.external.length > 0) {
          const limit = Math.min(refs.external.length, input.lawLookupLimit)
          for (let i = 0; i < limit; i++) {
            const ref = externalResolved[i]
            try {
              const xml = await apiClient.searchLaw(ref.lawName)
              const parsed = parseFirstLawFromXml(xml)
              if (parsed) {
                ref.lawId = parsed.lawId
                ref.mst = parsed.mst
              } else {
                ref.lookupError = "검색결과 없음"
              }
            } catch (err) {
              ref.lookupError = (err as Error).message.slice(0, 80)
            }
          }
        }
    
        // 포맷 출력
        const lines: string[] = []
        lines.push(`▶ [${inst.apbaId}] ${inst.apbaNa} — ${entry.title}`)
        lines.push(`   regId=${entry.regId}, 제·개정 ${entry.issuedAt || "-"} / 수정 ${entry.revisedAt || "-"}`)
        lines.push("")
        lines.push(`● 외부 법령 참조 (${externalResolved.length}건)`)
        if (externalResolved.length === 0) {
          lines.push("   (없음)")
        } else {
          for (const r of externalResolved) {
            const art = r.article ? ` ${r.article}` : ""
            const lookup =
              r.lawId || r.mst
                ? ` [lawId=${r.lawId || "-"}, mst=${r.mst || "-"}]`
                : r.lookupError
                  ? ` [조회실패: ${r.lookupError}]`
                  : ""
            lines.push(`   - ${r.lawName}${art}${lookup}`)
          }
          if (!input.includeLawLookup) {
            lines.push(`   💡 법제처 조회 원하면 includeLawLookup=true`)
          }
        }
    
        lines.push("")
        lines.push(`● 내부 상위규정 참조 (${internalResolved.length}건)`)
        if (internalResolved.length === 0) {
          lines.push("   (없음)")
        } else {
          for (const r of internalResolved) {
            const art = r.article ? ` ${r.article}` : ""
            const resolved = r.resolvedRegId
              ? ` → [regId=${r.resolvedRegId}] ${r.resolvedTitle}`
              : " (같은 기관 manifest 에서 매칭 안 됨)"
            lines.push(`   - ${r.ruleName}${art}${resolved}`)
          }
          const solved = internalResolved.filter((r) => r.resolvedRegId)
          if (solved.length > 0) {
            lines.push(
              `   💡 본문 열람: get_alio_regulation(institution="${inst.apbaId}", regId="<resolvedRegId>")`
            )
          }
        }
    
        lines.push("")
        lines.push("● 활용 힌트")
        if (externalResolved.length > 0) {
          const first = externalResolved[0]
          lines.push(
            `   - 외부 법령 본문: search_law(query="${first.lawName}")${first.article ? ` → get_law_text(mst=<mst>, jo="${first.article}")` : ""}`
          )
        }
        if (internalResolved.filter((r) => r.resolvedRegId).length > 0) {
          lines.push(`   - 내부 상위규정 본문: get_alio_regulation (위 regId 사용)`)
        }
    
        return { content: [{ type: "text", text: truncateResponse(lines.join("\n")) }] }
      } catch (err) {
        return formatToolError(err, "analyze_regulation_delegation")
      }
    }
  • Zod schema `AnalyzeRegulationDelegationSchema` defining input fields: institution (required), regId/title (one required), includeLawLookup, lawLookupLimit.
    export const AnalyzeRegulationDelegationSchema = z
      .object({
        institution: z.string().describe("기관코드(apbaId) 또는 기관명 일부"),
        regId: z.string().optional().describe("규정 ID (list_alio_regulations 의 regId)"),
        title: z.string().optional().describe("규정 제목 일부. regId 대체"),
        includeLawLookup: z
          .boolean()
          .default(false)
          .describe("외부 법령 참조를 법제처 searchLaw 로 조회해 MST/lawId 첨부 (최대 5개, 느림)"),
        lawLookupLimit: z.number().min(1).max(10).default(5).describe("searchLaw 호출 개수 상한"),
      })
      .refine((v) => !!(v.regId || v.title), {
        message: "regId 또는 title 중 하나는 필수",
        path: ["regId"],
      })
  • Registration entry in tool-registry.ts: name 'analyze_regulation_delegation', uses AnalyzeRegulationDelegationSchema and analyzeRegulationDelegation handler.
    {
      name: "analyze_regulation_delegation",
      description: "[ALIO] 특정 규정 본문에서 상위 법령/내부 상위규정 참조 추출. includeLawLookup=true 시 법제처 searchLaw 연계. 법제처 search_law 도구와의 교량.",
      schema: AnalyzeRegulationDelegationSchema,
      handler: analyzeRegulationDelegation
    },
  • Import statement importing `analyzeRegulationDelegation` and `AnalyzeRegulationDelegationSchema` from the implementation file.
    import { analyzeRegulationDelegation, AnalyzeRegulationDelegationSchema } from "./tools/alio/analyze-delegation.js"
    import { compareRegulationTimeline, CompareRegulationTimelineSchema } from "./tools/alio/compare-timeline.js"
  • Helper function `parseFirstLawFromXml` — parses lawId/mst from searchLaw XML response using DOMParser.
    function parseFirstLawFromXml(xml: string): { lawId: string; mst: string } | null {
      try {
        const doc = new DOMParser().parseFromString(xml, "text/xml")
        const laws = doc.getElementsByTagName("law")
        if (laws.length === 0) return null
        const first = laws[0]
        const lawId = first.getElementsByTagName("법령ID")[0]?.textContent || ""
        const mst = first.getElementsByTagName("법령일련번호")[0]?.textContent || ""
        if (!lawId && !mst) return null
        return { lawId, mst }
      } catch {
        return null
      }
    }
Behavior4/5

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

No annotations are provided, so the description carries full burden. It discloses that includeLawLookup=true slows down the tool (up to 5 slow calls), which is important behavioral information. However, it does not explicitly state if the tool is read-only or if it modifies data.

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?

The description is a single, concise sentence covering the core function and key parameter behavior. It is front-loaded with the main purpose and includes essential details without redundancy.

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?

The tool has 5 parameters and no output schema. The description covers purpose and key behavioral aspects but does not describe the return format or what the extraction results look like. For a tool that analyzes and extracts, the output is not explained.

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

Parameters4/5

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

Schema coverage is 100%, but the description adds value by explaining the includeLawLookup parameter's role as a bridge to searchLaw and noting the performance impact. The lawLookupLimit parameter is also contextualized. This goes beyond the schema descriptions.

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 tool extracts references to higher laws/regulations from a specific regulation text and optionally links to law lookup. It distinguishes itself from sibling tools by focusing on delegation analysis and bridging to search_law.

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

Usage Guidelines3/5

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

The description mentions the law lookup linkage but does not provide explicit guidance on when to use this tool versus alternatives like 'search_law' or other analysis tools. The context suggests it's for analyzing delegation in regulations, but no when-to-use or when-not-to-use criteria.

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