Skip to main content
Glama
saidsurucu

Mevzuat MCP

by saidsurucu

search_within_khk

Search specific Decree Laws (KHK) by keyword to find relevant articles, using advanced query operators to filter results efficiently.

Instructions

Search for a keyword within a specific Decree Law's (KHK) articles with advanced query operators.

This tool is optimized for large KHKs. Instead of loading the entire decree law into context, it:

  1. Fetches the full content

  2. Splits it into individual articles (madde)

  3. Returns only the articles that match the search query

  4. Sorts results by relevance score (based on match count)

Query Syntax (operators must be uppercase):

  • Simple keyword: değişiklik

  • Exact phrase: "kanun hükmünde"

  • AND operator: kanun AND değişiklik (both terms must be present)

  • OR operator: madde OR fıkra (at least one term must be present)

  • NOT operator: değişiklik NOT yürürlük (first term present, second must not be)

  • Combinations: "kanun hükmünde" AND değişiklik NOT yürürlük

Returns formatted text with:

  • Article number and title

  • Relevance score (higher = more matches)

  • Full article content for matching articles

Example use cases:

  • Search for "anayasa" in KHK 703 (Constitutional amendments)

  • Search for "sağlık AND düzenleme" in KHK 663 (Health regulations)

  • Search for "bakanlık OR kurum" in organizational KHKs

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
mevzuat_noYesThe KHK number to search within (e.g., '703', '700', '665')
keywordYesSearch query supporting advanced operators: simple keyword ("değişiklik"), exact phrase ("kanun hükmünde"), AND/OR/NOT operators (kanun AND değişiklik, madde OR fıkra, değişiklik NOT yürürlük). Operators must be uppercase.
mevzuat_tertipNoKHK series from search results (e.g., '5')5
case_sensitiveNoWhether to match case when searching (default: False)
max_resultsNoMaximum number of matching articles to return (1-50, default: 25)

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main handler function for the 'search_within_khk' tool. Fetches KHK content using MevzuatApiClient, performs article-level search using search_articles_by_keyword, formats results, and returns formatted string output.
    async def search_within_khk(
        mevzuat_no: str = Field(
            ...,
            description="The KHK number to search within (e.g., '703', '700', '665')"
        ),
        keyword: str = Field(
            ...,
            description='Search query supporting advanced operators: simple keyword ("değişiklik"), exact phrase ("kanun hükmünde"), AND/OR/NOT operators (kanun AND değişiklik, madde OR fıkra, değişiklik NOT yürürlük). Operators must be uppercase.'
        ),
        mevzuat_tertip: str = Field(
            "5",
            description="KHK series from search results (e.g., '5')"
        ),
        case_sensitive: bool = Field(
            False,
            description="Whether to match case when searching (default: False)"
        ),
        max_results: int = Field(
            25,
            ge=1,
            le=50,
            description="Maximum number of matching articles to return (1-50, default: 25)"
        )
    ) -> str:
        """
        Search for a keyword within a specific Decree Law's (KHK) articles with advanced query operators.
    
        This tool is optimized for large KHKs.
        Instead of loading the entire decree law into context, it:
        1. Fetches the full content
        2. Splits it into individual articles (madde)
        3. Returns only the articles that match the search query
        4. Sorts results by relevance score (based on match count)
    
        Query Syntax (operators must be uppercase):
        - Simple keyword: değişiklik
        - Exact phrase: "kanun hükmünde"
        - AND operator: kanun AND değişiklik (both terms must be present)
        - OR operator: madde OR fıkra (at least one term must be present)
        - NOT operator: değişiklik NOT yürürlük (first term present, second must not be)
        - Combinations: "kanun hükmünde" AND değişiklik NOT yürürlük
    
        Returns formatted text with:
        - Article number and title
        - Relevance score (higher = more matches)
        - Full article content for matching articles
    
        Example use cases:
        - Search for "anayasa" in KHK 703 (Constitutional amendments)
        - Search for "sağlık AND düzenleme" in KHK 663 (Health regulations)
        - Search for "bakanlık OR kurum" in organizational KHKs
        """
        logger.info(f"Tool 'search_within_khk' called: {mevzuat_no}, keyword: '{keyword}'")
    
        try:
            # Get full content
            content_result = await mevzuat_client.get_content(
                mevzuat_no=mevzuat_no,
                mevzuat_tur=4,  # KHK
                mevzuat_tertip=mevzuat_tertip
            )
    
            if content_result.error_message:
                return f"Error fetching KHK content: {content_result.error_message}"
    
            # Search within articles
            matches = search_articles_by_keyword(
                markdown_content=content_result.markdown_content,
                keyword=keyword,
                case_sensitive=case_sensitive,
                max_results=max_results
            )
    
            result = ArticleSearchResult(
                mevzuat_no=mevzuat_no,
                mevzuat_tur=4,
                keyword=keyword,
                total_matches=len(matches),
                matching_articles=matches
            )
    
            if len(matches) == 0:
                return f"No articles found containing '{keyword}' in KHK {mevzuat_no}"
    
            return format_search_results(result)
    
        except Exception as e:
            logger.exception(f"Error in tool 'search_within_khk' for {mevzuat_no}")
            return f"An unexpected error occurred while searching KHK {mevzuat_no}: {str(e)}"
  • Core search logic that splits legislation markdown into articles and scores them based on keyword matches with support for AND/OR/NOT/quoted phrases.
    def search_articles_by_keyword(
        markdown_content: str,
        keyword: str,
        case_sensitive: bool = False,
        max_results: int = 50
    ) -> List[MaddeMatch]:
        """
        Search for keyword within articles with support for advanced operators.
    
        Query syntax:
        - Simple keyword: "yatırımcı"
        - Exact phrase: "mali sıkıntı"
        - AND operator: yatırımcı AND tazmin
        - OR operator: yatırımcı OR müşteri
        - NOT operator: yatırımcı NOT kurum
        - Combinations: "mali sıkıntı" AND yatırımcı NOT kurum
    
        Args:
            markdown_content: Full legislation content in markdown
            keyword: Search query with optional operators (AND, OR, NOT, "exact phrase")
            case_sensitive: Whether to match case
            max_results: Maximum number of matching articles to return
    
        Returns:
            List of matching articles sorted by relevance (score based on match count)
        """
        articles = split_into_articles(markdown_content)
        matches = []
    
        for article in articles:
            content = article['madde_content']
    
            # Check if article matches query
            matches_query, score = _matches_query(content, keyword, case_sensitive)
    
            if matches_query and score > 0:
                # Generate preview (first occurrence of a search term)
                search_content = content if case_sensitive else content.lower()
                search_keyword = keyword if case_sensitive else keyword.lower()
    
                # Try to find first quoted phrase or first word
                preview_terms = re.findall(r'"([^"]*)"', search_keyword)
                if not preview_terms:
                    # Use first word (excluding operators)
                    words = re.split(r'\s+(?:AND|OR|NOT)\s+', search_keyword)
                    preview_terms = [w.strip() for w in words if w.strip() and w.strip() not in ('AND', 'OR', 'NOT')]
    
                preview = ""
                if preview_terms:
                    first_term = preview_terms[0] if case_sensitive else preview_terms[0].lower()
                    if first_term in search_content:
                        keyword_pos = search_content.find(first_term)
                        start = max(0, keyword_pos - 100)
                        end = min(len(content), keyword_pos + len(first_term) + 100)
                        preview = content[start:end]
    
                        if start > 0:
                            preview = "..." + preview
                        if end < len(content):
                            preview = preview + "..."
    
                if not preview:
                    preview = content[:200] + "..."
    
                matches.append(MaddeMatch(
                    madde_no=article['madde_no'],
                    madde_title=article['madde_title'],
                    madde_content=content,
                    match_count=score,
                    preview=preview
                ))
    
        # Sort by score (most relevant first)
        matches.sort(key=lambda x: x.match_count, reverse=True)
    
        return matches[:max_results]
  • Formats the ArticleSearchResult into a readable string with article headers, titles, match counts, and full content.
    def format_search_results(result: ArticleSearchResult) -> str:
        """Format search results as readable text."""
        output = []
        output.append(f"Keyword: '{result.keyword}'")
        output.append(f"Total matching articles: {result.total_matches}")
        output.append("")
    
        for i, match in enumerate(result.matching_articles, 1):
            output.append(f"=== MADDE {match.madde_no} ===")
            if match.madde_title:
                output.append(f"Title: {match.madde_title}")
            output.append(f"Matches: {match.match_count}")
            output.append("")
            output.append("Full content:")
            output.append(match.madde_content)
            output.append("")
    
        return "\n".join(output)
  • FastMCP @app.tool() decorator registers the search_within_khk function as an MCP tool.
    async def search_within_khk(
  • Pydantic Field definitions provide input schema and descriptions for the tool parameters.
        mevzuat_no: str = Field(
            ...,
            description="The KHK number to search within (e.g., '703', '700', '665')"
        ),
        keyword: str = Field(
            ...,
            description='Search query supporting advanced operators: simple keyword ("değişiklik"), exact phrase ("kanun hükmünde"), AND/OR/NOT operators (kanun AND değişiklik, madde OR fıkra, değişiklik NOT yürürlük). Operators must be uppercase.'
        ),
        mevzuat_tertip: str = Field(
            "5",
            description="KHK series from search results (e.g., '5')"
        ),
        case_sensitive: bool = Field(
            False,
            description="Whether to match case when searching (default: False)"
        ),
        max_results: int = Field(
            25,
            ge=1,
            le=50,
            description="Maximum number of matching articles to return (1-50, default: 25)"
        )
    ) -> str:
Behavior4/5

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

With no annotations provided, the description carries full burden and does an excellent job explaining the tool's behavior. It details the 4-step process (fetch, split, return matches, sort), specifies that results are sorted by relevance score, describes the return format, and mentions optimization for large KHKs. The only minor gap is it doesn't mention rate limits or authentication requirements, but those aren't critical omissions.

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 perfectly structured and front-loaded: it starts with the core purpose, then explains the optimization approach, details query syntax, describes return format, and provides use cases. Every sentence adds value with zero redundancy. The length is appropriate for a tool with complex query capabilities.

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

Completeness5/5

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

Given the tool's complexity (5 parameters, advanced query syntax), no annotations, but with an output schema present, the description is remarkably complete. It explains the tool's purpose, behavior, query syntax with examples, return format, and optimization rationale. The output schema means the description doesn't need to detail return values, allowing it to focus on usage guidance and behavioral context.

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 description coverage is 100%, so the baseline is 3. The description adds significant value by explaining the query syntax in detail with multiple examples, which goes beyond what the schema's 'keyword' parameter description provides. It also clarifies the tool's optimization approach and result formatting, which helps users understand how parameters affect behavior.

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 specific action ('Search for a keyword within a specific Decree Law's (KHK) articles') and distinguishes it from siblings by focusing on KHKs and advanced query operators. It explicitly mentions 'within a specific Decree Law's (KHK) articles' which differentiates it from broader search tools like 'search_khk' that likely search across multiple KHKs.

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool ('optimized for large KHKs', 'instead of loading the entire decree law into context') and includes example use cases. However, it doesn't explicitly state when NOT to use it or name specific alternatives among the sibling tools, though the context implies it's for focused searching within a single KHK.

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/saidsurucu/mevzuat-mcp'

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