fix(aym,uyusmazlik): adapt to rebuilt AYM and Uyuşmazlık sites
Both sites were rebuilt and their old endpoints now 404:
- AYM moved to a single-page app backed by a JSON API
(POST /api/core/public/search, kararTipi NormDenetimi/BireyselBasvuru;
full text via {id, size:1} -> "icerik" HTML). Old /Ara, /ND/, /BB/ gone.
- Uyuşmazlık moved to ASP.NET WebForms (viewstate postback to /, GridView
results, decisions served as /Uploads/{EsasNo}.pdf). Old /Arama/Search gone.
Changes:
- New anayasa_mcp_module/api_client.py: shared KBB JSON client, base64url
document-id codec, HTML->Markdown + HTML text stripping helpers.
- Rewrite anayasa client/bireysel_client/unified_client over the new API,
preserving public method names and response models.
- Rewrite uyusmazlik client for the postback flow + GridView parse + PDF
document conversion; simplify request model to text + scope + paging.
- Trim search_anayasa_unified and search_uyusmazlik_decisions tool signatures
to parameters the new APIs actually support; drop dead enums.
Verified live via FastMCP client: search + document retrieval work for AYM
norm/bireysel and Uyuşmazlık.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
6bbc656dc6
commit
fadc3b0bc0
+125
-197
@@ -1,251 +1,179 @@
|
||||
# uyusmazlik_mcp_module/client.py
|
||||
#
|
||||
# Client for the rebuilt Uyuşmazlık Mahkemesi search site
|
||||
# (https://kararlar.uyusmazlik.gov.tr). The site is an ASP.NET WebForms app:
|
||||
# searching is a form postback against "/" that returns an HTML page with a
|
||||
# GridView of results, and each decision is a PDF served from /Uploads/.
|
||||
#
|
||||
# The previous AJAX endpoint (/Arama/Search) was retired and now returns 404.
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import logging
|
||||
import re
|
||||
from typing import Dict, List, Optional
|
||||
from urllib.parse import urljoin
|
||||
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
from typing import Dict, Any, List, Optional, Union, Tuple
|
||||
import logging
|
||||
import html
|
||||
import re
|
||||
import io
|
||||
from markitdown import MarkItDown
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from .models import (
|
||||
UyusmazlikSearchRequest,
|
||||
UyusmazlikApiDecisionEntry,
|
||||
UyusmazlikSearchResponse,
|
||||
UyusmazlikDocumentMarkdown,
|
||||
UyusmazlikBolumEnum,
|
||||
UyusmazlikTuruEnum,
|
||||
UyusmazlikKararSonucuEnum
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
if not logger.hasHandlers():
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
|
||||
# --- Mappings from user-friendly Enum values to API IDs ---
|
||||
BOLUM_ENUM_TO_ID_MAP = {
|
||||
UyusmazlikBolumEnum.CEZA_BOLUMU: "f6b74320-f2d7-4209-ad6e-c6df180d4e7c",
|
||||
UyusmazlikBolumEnum.GENEL_KURUL_KARARLARI: "e4ca658d-a75a-4719-b866-b2d2f1c3b1d9",
|
||||
UyusmazlikBolumEnum.HUKUK_BOLUMU: "96b26fc4-ef8e-4a4f-a9cc-a3de89952aa1",
|
||||
UyusmazlikBolumEnum.TUMU: "", # Represents "...Seçiniz..." or all - empty string for API
|
||||
"ALL": "" # Also map the new "ALL" literal to empty string for backward compatibility
|
||||
}
|
||||
# ASP.NET hidden fields that must be round-tripped on every postback.
|
||||
_HIDDEN_FIELDS = ("__VIEWSTATE", "__VIEWSTATEGENERATOR", "__EVENTVALIDATION")
|
||||
|
||||
UYUSMAZLIK_TURU_ENUM_TO_ID_MAP = {
|
||||
UyusmazlikTuruEnum.GOREV_UYUSMAZLIGI: "7b1e2cd3-8f09-418a-921c-bbe501e1740c",
|
||||
UyusmazlikTuruEnum.HUKUM_UYUSMAZLIGI: "19b88402-172b-4c1d-8339-595c942a89f5",
|
||||
UyusmazlikTuruEnum.TUMU: "", # Represents "...Seçiniz..." or all - empty string for API
|
||||
"ALL": "" # Also map the new "ALL" literal to empty string for backward compatibility
|
||||
}
|
||||
|
||||
KARAR_SONUCU_ENUM_TO_ID_MAP = {
|
||||
# These IDs are from the form HTML provided by the user
|
||||
UyusmazlikKararSonucuEnum.HUKUM_UYUSMAZLIGI_OLMADIGINA_DAIR: "6f47d87f-dcb5-412e-9878-000385dba1d9",
|
||||
UyusmazlikKararSonucuEnum.HUKUM_UYUSMAZLIGI_OLDUGUNA_DAIR: "5a01742a-c440-4c4a-ba1f-da20837cffed",
|
||||
# Add all other 'Karar Sonucu' enum members and their corresponding GUIDs
|
||||
# by inspecting the 'KararSonucuList' checkboxes in the provided form HTML.
|
||||
}
|
||||
# --- End Mappings ---
|
||||
|
||||
class UyusmazlikApiClient:
|
||||
BASE_URL = "https://kararlar.uyusmazlik.gov.tr"
|
||||
SEARCH_ENDPOINT = "/Arama/Search"
|
||||
# Individual documents are fetched by their full URLs obtained from search results.
|
||||
SEARCH_PATH = "/"
|
||||
|
||||
def __init__(self, request_timeout: float = 30.0):
|
||||
self.request_timeout = request_timeout
|
||||
# Create shared httpx client for all requests
|
||||
# A persistent cookie-aware client so ASP.NET session/viewstate are kept.
|
||||
self.http_client = httpx.AsyncClient(
|
||||
base_url=self.BASE_URL,
|
||||
headers={
|
||||
"Accept": "*/*",
|
||||
"Accept-Encoding": "gzip, deflate, br, zstd",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Accept-Language": "tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
"Origin": self.BASE_URL,
|
||||
"Referer": self.BASE_URL + "/",
|
||||
},
|
||||
timeout=request_timeout,
|
||||
verify=False
|
||||
verify=False,
|
||||
follow_redirects=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _extract_hidden_fields(html_content: str) -> Dict[str, str]:
|
||||
soup = BeautifulSoup(html_content, "html.parser")
|
||||
fields: Dict[str, str] = {}
|
||||
for name in _HIDDEN_FIELDS:
|
||||
tag = soup.find("input", attrs={"name": name})
|
||||
fields[name] = tag["value"] if tag and tag.has_attr("value") else ""
|
||||
return fields
|
||||
|
||||
async def search_decisions(
|
||||
self,
|
||||
params: UyusmazlikSearchRequest
|
||||
) -> UyusmazlikSearchResponse:
|
||||
|
||||
bolum_id_for_api = BOLUM_ENUM_TO_ID_MAP.get(params.bolum, "")
|
||||
uyusmazlik_id_for_api = UYUSMAZLIK_TURU_ENUM_TO_ID_MAP.get(params.uyusmazlik_turu, "")
|
||||
|
||||
form_data_list: List[Tuple[str, str]] = []
|
||||
@staticmethod
|
||||
def _parse_results(html_content: str, base_url: str) -> UyusmazlikSearchResponse:
|
||||
soup = BeautifulSoup(html_content, "html.parser")
|
||||
|
||||
def add_to_form_data(key: str, value: Optional[str]):
|
||||
# API expects empty strings for omitted optional fields based on user payload example
|
||||
form_data_list.append((key, value or ""))
|
||||
decisions: List[UyusmazlikApiDecisionEntry] = []
|
||||
grid = soup.find("table", id="GridView1")
|
||||
if grid:
|
||||
rows = grid.find_all("tr")
|
||||
for row in rows[1:]: # skip header row
|
||||
cells = row.find_all("td")
|
||||
if len(cells) < 4:
|
||||
continue
|
||||
# The İşlemler cell holds the PDF "Görüntüle" link. Pager rows also
|
||||
# contain <a> tags (javascript:__doPostBack ...), so require a real
|
||||
# document link and skip everything else.
|
||||
link_tag = cells[3].find(
|
||||
"a", href=lambda h: h and not h.strip().lower().startswith("javascript:")
|
||||
)
|
||||
if not link_tag:
|
||||
continue
|
||||
href = link_tag["href"].strip()
|
||||
if "uploads" not in href.lower() and not href.lower().endswith(".pdf"):
|
||||
continue
|
||||
document_url = urljoin(base_url + "/", href)
|
||||
decisions.append(UyusmazlikApiDecisionEntry(
|
||||
esas_sayisi=cells[0].get_text(strip=True) or None,
|
||||
karar_sayisi=cells[1].get_text(strip=True) or None,
|
||||
karar_tarihi=cells[2].get_text(strip=True) or None,
|
||||
document_url=document_url,
|
||||
))
|
||||
|
||||
add_to_form_data("BolumId", bolum_id_for_api)
|
||||
add_to_form_data("UyusmazlikId", uyusmazlik_id_for_api)
|
||||
|
||||
if params.karar_sonuclari:
|
||||
for enum_member in params.karar_sonuclari:
|
||||
api_id = KARAR_SONUCU_ENUM_TO_ID_MAP.get(enum_member)
|
||||
if api_id: # Only add if a valid ID is found
|
||||
form_data_list.append(('KararSonucuList', api_id))
|
||||
|
||||
add_to_form_data("EsasYil", params.esas_yil)
|
||||
add_to_form_data("EsasSayisi", params.esas_sayisi)
|
||||
add_to_form_data("KararYil", params.karar_yil)
|
||||
add_to_form_data("KararSayisi", params.karar_sayisi)
|
||||
add_to_form_data("KanunNo", params.kanun_no)
|
||||
add_to_form_data("KararDateBegin", params.karar_date_begin)
|
||||
add_to_form_data("KararDateEnd", params.karar_date_end)
|
||||
add_to_form_data("ResmiGazeteSayi", params.resmi_gazete_sayi)
|
||||
add_to_form_data("ResmiGazeteDate", params.resmi_gazete_date)
|
||||
add_to_form_data("Icerik", params.icerik)
|
||||
add_to_form_data("Tumce", params.tumce)
|
||||
add_to_form_data("WildCard", params.wild_card)
|
||||
add_to_form_data("Hepsi", params.hepsi)
|
||||
add_to_form_data("Herhangibirisi", params.herhangi_birisi)
|
||||
add_to_form_data("NotHepsi", params.not_hepsi)
|
||||
# Try to read a "N kayıt/sonuç/karar bulundu" style count if present.
|
||||
total_records: Optional[int] = None
|
||||
count_match = re.search(r'(\d+)\s*(?:adet\s*)?(?:kayıt|sonuç|karar)\b', html_content, re.IGNORECASE)
|
||||
if count_match:
|
||||
total_records = int(count_match.group(1))
|
||||
|
||||
# Convert form data to dict for httpx
|
||||
form_data_dict = {}
|
||||
for key, value in form_data_list:
|
||||
if key in form_data_dict:
|
||||
# Handle multiple values (like KararSonucuList)
|
||||
if not isinstance(form_data_dict[key], list):
|
||||
form_data_dict[key] = [form_data_dict[key]]
|
||||
form_data_dict[key].append(value)
|
||||
else:
|
||||
form_data_dict[key] = value
|
||||
return UyusmazlikSearchResponse(decisions=decisions, total_records_found=total_records)
|
||||
|
||||
logger.info(f"UyusmazlikApiClient (httpx): Performing search to {self.SEARCH_ENDPOINT} with form_data: {form_data_dict}")
|
||||
|
||||
try:
|
||||
# Use shared httpx client
|
||||
response = await self.http_client.post(
|
||||
self.SEARCH_ENDPOINT,
|
||||
data=form_data_dict,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
|
||||
async def search_decisions(self, params: UyusmazlikSearchRequest) -> UyusmazlikSearchResponse:
|
||||
# 1. Load the landing page to obtain a fresh viewstate + session cookie.
|
||||
landing = await self.http_client.get(self.SEARCH_PATH)
|
||||
landing.raise_for_status()
|
||||
form_data = self._extract_hidden_fields(landing.text)
|
||||
|
||||
# 2. Submit the search form.
|
||||
form_data.update({
|
||||
"txtSearch": params.icerik or "",
|
||||
"rblSearchScope": params.search_scope,
|
||||
"btnSearch": "Ara",
|
||||
})
|
||||
if params.case_sensitive:
|
||||
form_data["chkCaseSensitive"] = "on"
|
||||
|
||||
logger.info("UyusmazlikApiClient: search icerik=%r scope=%s page=%s",
|
||||
params.icerik, params.search_scope, params.page_number)
|
||||
response = await self.http_client.post(
|
||||
self.SEARCH_PATH,
|
||||
data=form_data,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
html_content = response.text
|
||||
|
||||
# 3. Navigate the GridView pager if a later page is requested.
|
||||
if params.page_number > 1:
|
||||
page_fields = self._extract_hidden_fields(html_content)
|
||||
page_fields.update({
|
||||
"txtSearch": params.icerik or "",
|
||||
"rblSearchScope": params.search_scope,
|
||||
"__EVENTTARGET": "GridView1",
|
||||
"__EVENTARGUMENT": f"Page${params.page_number}",
|
||||
})
|
||||
if params.case_sensitive:
|
||||
page_fields["chkCaseSensitive"] = "on"
|
||||
page_response = await self.http_client.post(
|
||||
self.SEARCH_PATH,
|
||||
data=page_fields,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
html_content = response.text
|
||||
logger.debug("UyusmazlikApiClient (httpx): Received HTML response for search.")
|
||||
|
||||
except httpx.HTTPError as e:
|
||||
logger.error(f"UyusmazlikApiClient (httpx): HTTP client error during search: {e}")
|
||||
raise # Re-raise to be handled by the MCP tool
|
||||
except Exception as e:
|
||||
logger.error(f"UyusmazlikApiClient (httpx): Error processing search request: {e}")
|
||||
raise
|
||||
page_response.raise_for_status()
|
||||
html_content = page_response.text
|
||||
|
||||
# --- HTML Parsing (remains the same as previous version) ---
|
||||
soup = BeautifulSoup(html_content, 'html.parser')
|
||||
total_records_text_div = soup.find("div", class_="pull-right label label-important")
|
||||
total_records = None
|
||||
if total_records_text_div:
|
||||
match_records = re.search(r'(\d+)\s*adet kayıt bulundu', total_records_text_div.get_text(strip=True))
|
||||
if match_records:
|
||||
total_records = int(match_records.group(1))
|
||||
|
||||
result_table = soup.find("table", class_="table-hover")
|
||||
processed_decisions: List[UyusmazlikApiDecisionEntry] = []
|
||||
if result_table:
|
||||
rows = result_table.find_all("tr")
|
||||
if len(rows) > 1: # Skip header row
|
||||
for row in rows[1:]:
|
||||
cols = row.find_all('td')
|
||||
if len(cols) >= 5:
|
||||
try:
|
||||
popover_div = cols[0].find("div", attrs={"data-rel": "popover"})
|
||||
popover_content_raw = popover_div["data-content"] if popover_div and popover_div.has_attr("data-content") else None
|
||||
|
||||
link_tag = cols[0].find('a')
|
||||
doc_relative_url = link_tag['href'] if link_tag and link_tag.has_attr('href') else None
|
||||
|
||||
if not doc_relative_url: continue
|
||||
document_url_str = urljoin(self.BASE_URL, doc_relative_url)
|
||||
return self._parse_results(html_content, self.BASE_URL)
|
||||
|
||||
pdf_link_tag = cols[5].find('a', href=re.compile(r'\.pdf$', re.IGNORECASE)) if len(cols) > 5 else None
|
||||
pdf_url_str = urljoin(self.BASE_URL, pdf_link_tag['href']) if pdf_link_tag and pdf_link_tag.has_attr('href') else None
|
||||
|
||||
decision_data_parsed = {
|
||||
"karar_sayisi": cols[0].get_text(strip=True),
|
||||
"esas_sayisi": cols[1].get_text(strip=True),
|
||||
"bolum": cols[2].get_text(strip=True),
|
||||
"uyusmazlik_konusu": cols[3].get_text(strip=True),
|
||||
"karar_sonucu": cols[4].get_text(strip=True),
|
||||
"popover_content": html.unescape(popover_content_raw) if popover_content_raw else None,
|
||||
"document_url": document_url_str,
|
||||
"pdf_url": pdf_url_str
|
||||
}
|
||||
decision_model = UyusmazlikApiDecisionEntry(**decision_data_parsed)
|
||||
processed_decisions.append(decision_model)
|
||||
except Exception as e:
|
||||
logger.warning(f"UyusmazlikApiClient: Could not parse decision row. Row content: {row.get_text(strip=True, separator=' | ')}, Error: {e}")
|
||||
|
||||
return UyusmazlikSearchResponse(
|
||||
decisions=processed_decisions,
|
||||
total_records_found=total_records
|
||||
)
|
||||
|
||||
def _convert_html_to_markdown_uyusmazlik(self, full_decision_html_content: str) -> Optional[str]:
|
||||
"""Converts direct HTML content (from an Uyuşmazlık decision page) to Markdown."""
|
||||
if not full_decision_html_content:
|
||||
return None
|
||||
|
||||
processed_html = html.unescape(full_decision_html_content)
|
||||
# As per user request, pass the full (unescaped) HTML to MarkItDown
|
||||
html_input_for_markdown = processed_html
|
||||
|
||||
markdown_text = None
|
||||
def _convert_pdf_to_markdown(self, pdf_bytes: bytes) -> Optional[str]:
|
||||
try:
|
||||
# Convert HTML string to bytes and create BytesIO stream
|
||||
html_bytes = html_input_for_markdown.encode('utf-8')
|
||||
html_stream = io.BytesIO(html_bytes)
|
||||
|
||||
# Pass BytesIO stream to MarkItDown to avoid temp file creation
|
||||
md_converter = MarkItDown()
|
||||
conversion_result = md_converter.convert(html_stream)
|
||||
markdown_text = conversion_result.text_content
|
||||
logger.info("UyusmazlikApiClient: HTML to Markdown conversion successful.")
|
||||
pdf_stream = io.BytesIO(pdf_bytes)
|
||||
conversion_result = MarkItDown().convert(pdf_stream, file_extension=".pdf")
|
||||
return conversion_result.text_content
|
||||
except Exception as e:
|
||||
logger.error(f"UyusmazlikApiClient: Error during MarkItDown HTML to Markdown conversion: {e}")
|
||||
return markdown_text
|
||||
logger.error("UyusmazlikApiClient: PDF to Markdown conversion error: %s", e)
|
||||
return None
|
||||
|
||||
async def get_decision_document_as_markdown(self, document_url: str) -> UyusmazlikDocumentMarkdown:
|
||||
"""
|
||||
Retrieves a specific Uyuşmazlık decision from its full URL and returns content as Markdown.
|
||||
"""
|
||||
logger.info(f"UyusmazlikApiClient (httpx for docs): Fetching Uyuşmazlık document for Markdown from URL: {document_url}")
|
||||
"""Fetch an Uyuşmazlık decision PDF and return its content as Markdown."""
|
||||
logger.info("UyusmazlikApiClient: Fetching document PDF from %s", document_url)
|
||||
try:
|
||||
# Using a new httpx.AsyncClient instance for this GET request for simplicity
|
||||
async with httpx.AsyncClient(verify=False, timeout=self.request_timeout) as doc_fetch_client:
|
||||
get_response = await doc_fetch_client.get(document_url, headers={"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"})
|
||||
get_response.raise_for_status()
|
||||
html_content_from_api = get_response.text
|
||||
|
||||
if not isinstance(html_content_from_api, str) or not html_content_from_api.strip():
|
||||
logger.warning(f"UyusmazlikApiClient: Received empty or non-string HTML from URL {document_url}.")
|
||||
return UyusmazlikDocumentMarkdown(source_url=document_url, markdown_content=None)
|
||||
|
||||
markdown_content = await asyncio.to_thread(self._convert_html_to_markdown_uyusmazlik, html_content_from_api)
|
||||
response = await self.http_client.get(
|
||||
document_url,
|
||||
headers={"Accept": "application/pdf,*/*"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
markdown_content = await asyncio.to_thread(self._convert_pdf_to_markdown, response.content)
|
||||
return UyusmazlikDocumentMarkdown(source_url=document_url, markdown_content=markdown_content)
|
||||
except httpx.RequestError as e:
|
||||
logger.error(f"UyusmazlikApiClient (httpx for docs): HTTP error fetching Uyuşmazlık document from {document_url}: {e}")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"UyusmazlikApiClient (httpx for docs): General error processing Uyuşmazlık document from {document_url}: {e}")
|
||||
except httpx.HTTPError as e:
|
||||
logger.error("UyusmazlikApiClient: HTTP error fetching document from %s: %s", document_url, e)
|
||||
raise
|
||||
|
||||
async def close_client_session(self):
|
||||
"""Close the shared httpx client session."""
|
||||
if hasattr(self, 'http_client') and self.http_client:
|
||||
if hasattr(self, "http_client") and self.http_client and not self.http_client.is_closed:
|
||||
await self.http_client.aclose()
|
||||
logger.info("UyusmazlikApiClient: HTTP client session closed.")
|
||||
else:
|
||||
logger.info("UyusmazlikApiClient: No persistent client session from __init__ to close.")
|
||||
@@ -1,86 +1,41 @@
|
||||
# uyusmazlik_mcp_module/models.py
|
||||
|
||||
from pydantic import BaseModel, Field, HttpUrl
|
||||
from typing import List, Optional
|
||||
from enum import Enum
|
||||
from typing import List, Optional, Literal
|
||||
|
||||
# Enum definitions for user-friendly input based on the provided HTML form
|
||||
class UyusmazlikBolumEnum(str, Enum):
|
||||
"""User-friendly names for 'BolumId'."""
|
||||
TUMU = "ALL" # Represents "...Seçiniz..." or all
|
||||
CEZA_BOLUMU = "Ceza Bölümü"
|
||||
GENEL_KURUL_KARARLARI = "Genel Kurul Kararları"
|
||||
HUKUK_BOLUMU = "Hukuk Bölümü"
|
||||
# The Uyuşmazlık Mahkemesi search site was rebuilt as an ASP.NET WebForms app.
|
||||
# It now offers only a single free-text search with a scope selector; the old
|
||||
# Bölüm / Uyuşmazlık Türü / Karar Sonucu / Esas-Karar year filters no longer exist.
|
||||
|
||||
class UyusmazlikTuruEnum(str, Enum):
|
||||
"""User-friendly names for 'UyusmazlikId'."""
|
||||
TUMU = "ALL" # Represents "...Seçiniz..." or all
|
||||
GOREV_UYUSMAZLIGI = "Görev Uyuşmazlığı"
|
||||
HUKUM_UYUSMAZLIGI = "Hüküm Uyuşmazlığı"
|
||||
UyusmazlikSearchScope = Literal["All", "EsasNo", "KararNo"]
|
||||
|
||||
class UyusmazlikKararSonucuEnum(str, Enum): # Based on checkbox text in the form
|
||||
"""User-friendly names for 'KararSonucuList' items."""
|
||||
HUKUM_UYUSMAZLIGI_OLMADIGINA_DAIR = "Hüküm Uyuşmazlığı Olmadığına Dair"
|
||||
HUKUM_UYUSMAZLIGI_OLDUGUNA_DAIR = "Hüküm Uyuşmazlığı Olduğuna Dair"
|
||||
# Add other "Karar Sonucu" options from the form's checkboxes as Enum members
|
||||
# Example: GOREVLI_YARGI_YERI_ADLI = "Görevli Yargı Yeri Belirlenmesine Dair (Adli Yargı)"
|
||||
# The client will map these enum values (which are strings) to their respective IDs.
|
||||
|
||||
class UyusmazlikSearchRequest(BaseModel): # This is the model the MCP tool will accept
|
||||
"""Model for Uyuşmazlık Mahkemesi search request using user-friendly terms."""
|
||||
icerik: Optional[str] = Field("", description="Search text")
|
||||
|
||||
bolum: Optional[UyusmazlikBolumEnum] = Field(
|
||||
UyusmazlikBolumEnum.TUMU,
|
||||
description="Department"
|
||||
class UyusmazlikSearchRequest(BaseModel):
|
||||
"""Model for the Uyuşmazlık Mahkemesi search request."""
|
||||
icerik: str = Field("", description="Search text (txtSearch).")
|
||||
search_scope: UyusmazlikSearchScope = Field(
|
||||
"All",
|
||||
description="Search scope: 'All' (full text), 'EsasNo' (by case number), 'KararNo' (by decision number).",
|
||||
)
|
||||
uyusmazlik_turu: Optional[UyusmazlikTuruEnum] = Field(
|
||||
UyusmazlikTuruEnum.TUMU,
|
||||
description="Dispute type"
|
||||
)
|
||||
|
||||
# User provides a list of user-friendly names for Karar Sonucu
|
||||
karar_sonuclari: Optional[List[UyusmazlikKararSonucuEnum]] = Field( # Changed to list of Enums
|
||||
default_factory=list,
|
||||
description="Decision types"
|
||||
)
|
||||
|
||||
esas_yil: Optional[str] = Field("", description="Case year")
|
||||
esas_sayisi: Optional[str] = Field("", description="Case no")
|
||||
karar_yil: Optional[str] = Field("", description="Decision year")
|
||||
karar_sayisi: Optional[str] = Field("", description="Decision no")
|
||||
kanun_no: Optional[str] = Field("", description="Law no")
|
||||
|
||||
karar_date_begin: Optional[str] = Field("", description="Start date (DD.MM.YYYY)")
|
||||
karar_date_end: Optional[str] = Field("", description="End date (DD.MM.YYYY)")
|
||||
|
||||
resmi_gazete_sayi: Optional[str] = Field("", description="Gazette no")
|
||||
resmi_gazete_date: Optional[str] = Field("", description="Gazette date (DD.MM.YYYY)")
|
||||
|
||||
# Detailed text search fields from the "icerikDetail" section of the form
|
||||
tumce: Optional[str] = Field("", description="Exact phrase")
|
||||
wild_card: Optional[str] = Field("", description="Wildcard search")
|
||||
hepsi: Optional[str] = Field("", description="All words")
|
||||
herhangi_birisi: Optional[str] = Field("", description="Any word")
|
||||
not_hepsi: Optional[str] = Field("", description="Exclude words")
|
||||
case_sensitive: bool = Field(False, description="Whether the search is case sensitive (chkCaseSensitive).")
|
||||
page_number: int = Field(1, ge=1, description="Result page number (GridView pager).")
|
||||
|
||||
|
||||
class UyusmazlikApiDecisionEntry(BaseModel):
|
||||
"""Model for an individual decision entry parsed from Uyuşmazlık API's HTML search response."""
|
||||
karar_sayisi: Optional[str] = Field(None)
|
||||
esas_sayisi: Optional[str] = Field(None)
|
||||
bolum: Optional[str] = Field(None)
|
||||
uyusmazlik_konusu: Optional[str] = Field(None)
|
||||
karar_sonucu: Optional[str] = Field(None)
|
||||
popover_content: Optional[str] = Field(None, description="Summary")
|
||||
document_url: HttpUrl # Full URL to the decision document HTML page
|
||||
pdf_url: Optional[HttpUrl] = Field(None, description="PDF URL")
|
||||
"""A single decision row parsed from the Uyuşmazlık GridView results."""
|
||||
esas_sayisi: Optional[str] = Field(None, description="Case number (Esas No).")
|
||||
karar_sayisi: Optional[str] = Field(None, description="Decision number (Karar No).")
|
||||
karar_tarihi: Optional[str] = Field(None, description="Decision date (DD/MM/YYYY).")
|
||||
document_url: HttpUrl = Field(..., description="Full URL to the decision PDF document.")
|
||||
|
||||
class UyusmazlikSearchResponse(BaseModel): # This is what the MCP tool will return
|
||||
"""Response model for Uyuşmazlık Mahkemesi search results for the MCP tool."""
|
||||
|
||||
class UyusmazlikSearchResponse(BaseModel):
|
||||
"""Response model for Uyuşmazlık Mahkemesi search results."""
|
||||
decisions: List[UyusmazlikApiDecisionEntry]
|
||||
total_records_found: Optional[int] = Field(None, description="Total number of records found for the query, if available.")
|
||||
total_records_found: Optional[int] = Field(None, description="Total number of records found, if reported.")
|
||||
|
||||
|
||||
class UyusmazlikDocumentMarkdown(BaseModel):
|
||||
"""Model for an Uyuşmazlık decision document, containing only Markdown content."""
|
||||
source_url: HttpUrl # The URL from which the content was fetched
|
||||
markdown_content: Optional[str] = Field(None, description="The decision content converted to Markdown.")
|
||||
"""Model for an Uyuşmazlık decision document, containing Markdown content."""
|
||||
source_url: HttpUrl
|
||||
markdown_content: Optional[str] = Field(None, description="The decision PDF content converted to Markdown.")
|
||||
|
||||
Reference in New Issue
Block a user