search_within_kanun
Search specific Turkish legislation articles using keywords and advanced query operators to find relevant legal provisions without loading entire documents.
Instructions
Search for a keyword within a specific legislation's articles with advanced query operators.
This tool is optimized for large legislation (e.g., Sermaye Piyasası Kanunu with 142 articles). Instead of loading the entire legislation into context, it:
Fetches the full content
Splits it into individual articles (madde)
Returns only the articles that match the search query
Sorts results by relevance score (based on match count)
Query Syntax (operators must be uppercase):
Simple keyword: yatırımcı
Exact phrase: "mali sıkıntı"
AND operator: yatırımcı AND tazmin (both terms must be present)
OR operator: yatırımcı OR müşteri (at least one term must be present)
NOT operator: yatırımcı NOT kurum (first term present, second must not be)
Combinations: "mali sıkıntı" AND yatırımcı NOT kurum
Returns formatted text with:
Article number and title
Relevance score (higher = more matches)
Full article content for matching articles
Example use cases:
Search for "yatırımcı" in Kanun 6362 (Capital Markets Law)
Search for "ceza AND temyiz" in Kanun 5237 (Turkish Penal Code)
Search for "vergi OR ücret" in tax-related legislation
Search for '"iş kazası" AND işveren NOT işçi' for specific labor law articles
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| mevzuat_no | Yes | The legislation number to search within (e.g., '6362', '5237') | |
| keyword | Yes | Search query supporting advanced operators: simple keyword ("yatırımcı"), exact phrase ("mali sıkıntı"), AND/OR/NOT operators (yatırımcı AND tazmin, yatırımcı OR müşteri, yatırımcı NOT kurum). Operators must be uppercase. | |
| mevzuat_tertip | No | Legislation series from search results (e.g., '3', '5') | 5 |
| case_sensitive | No | Whether to match case when searching (default: False) | |
| max_results | No | Maximum number of matching articles to return (1-50, default: 25) |
Implementation Reference
- mevzuat_mcp_server.py:130-220 (handler)Primary handler function for the 'search_within_kanun' MCP tool. Fetches full content of a specific Kanun using MevzuatApiClientNew, performs article-level search using helper functions, formats results, handles errors, and returns formatted string of matching articles sorted by relevance.@app.tool() async def search_within_kanun( mevzuat_no: str = Field( ..., description="The legislation number to search within (e.g., '6362', '5237')" ), keyword: str = Field( ..., description='Search query supporting advanced operators: simple keyword ("yatırımcı"), exact phrase ("mali sıkıntı"), AND/OR/NOT operators (yatırımcı AND tazmin, yatırımcı OR müşteri, yatırımcı NOT kurum). Operators must be uppercase.' ), mevzuat_tertip: str = Field( "5", description="Legislation series from search results (e.g., '3', '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 legislation's articles with advanced query operators. This tool is optimized for large legislation (e.g., Sermaye Piyasası Kanunu with 142 articles). Instead of loading the entire legislation 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: yatırımcı - Exact phrase: "mali sıkıntı" - AND operator: yatırımcı AND tazmin (both terms must be present) - OR operator: yatırımcı OR müşteri (at least one term must be present) - NOT operator: yatırımcı NOT kurum (first term present, second must not be) - Combinations: "mali sıkıntı" AND yatırımcı NOT kurum Returns formatted text with: - Article number and title - Relevance score (higher = more matches) - Full article content for matching articles Example use cases: - Search for "yatırımcı" in Kanun 6362 (Capital Markets Law) - Search for "ceza AND temyiz" in Kanun 5237 (Turkish Penal Code) - Search for "vergi OR ücret" in tax-related legislation - Search for '"iş kazası" AND işveren NOT işçi' for specific labor law articles """ logger.info(f"Tool 'search_within_kanun' called: {mevzuat_no}, keyword: '{keyword}'") try: # Get full content content_result = await mevzuat_client.get_content( mevzuat_no=mevzuat_no, mevzuat_tur=1, # Kanun mevzuat_tertip=mevzuat_tertip ) if content_result.error_message: return f"Error fetching legislation 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=1, keyword=keyword, total_matches=len(matches), matching_articles=matches ) if len(matches) == 0: return f"No articles found containing '{keyword}' in Kanun {mevzuat_no}" return format_search_results(result) except Exception as e: logger.exception(f"Error in tool 'search_within_kanun' for {mevzuat_no}") return f"An unexpected error occurred: {str(e)}"
- mevzuat_mcp_server.py:132-154 (schema)Pydantic Field definitions providing input schema validation, descriptions, and constraints for the tool's parameters (mevzuat_no, keyword, mevzuat_tertip, case_sensitive, max_results). Defines the tool's input interface.mevzuat_no: str = Field( ..., description="The legislation number to search within (e.g., '6362', '5237')" ), keyword: str = Field( ..., description='Search query supporting advanced operators: simple keyword ("yatırımcı"), exact phrase ("mali sıkıntı"), AND/OR/NOT operators (yatırımcı AND tazmin, yatırımcı OR müşteri, yatırımcı NOT kurum). Operators must be uppercase.' ), mevzuat_tertip: str = Field( "5", description="Legislation series from search results (e.g., '3', '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:
- mevzuat_mcp_server.py:130-130 (registration)FastMCP @app.tool() decorator registers the search_within_kanun function as a named tool available via the MCP protocol.@app.tool()
- article_search.py:176-251 (helper)Key helper function that parses markdown into articles (using split_into_articles), evaluates complex queries via _matches_query (supports AND/OR/NOT/exact phrases), computes match scores, generates previews, and returns sorted list of top MaddeMatch results. Called directly from the handler.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]
- article_search.py:254-272 (helper)Helper function that formats the ArticleSearchResult object into a human-readable string, including keyword summary, article headers, titles, match counts, and full contents of matching articles.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)