#
tokens: 46159/50000 2/145 files (page 9/11)
lines: on (toggle) GitHub
raw markdown copy reset
This is page 9 of 11. Use http://codebase.md/saidsurucu/yargi-mcp?lines=true&page={x} to view the full context.

# Directory Structure

```
├── __main__.py
├── .dockerignore
├── .env.example
├── .gitattributes
├── .github
│   └── workflows
│       └── publish.yml
├── .gitignore
├── .serena
│   ├── .gitignore
│   └── project.yml
├── 5ire-settings.png
├── analyze_kik_hash_generation.py
├── anayasa_mcp_module
│   ├── __init__.py
│   ├── bireysel_client.py
│   ├── client.py
│   ├── models.py
│   └── unified_client.py
├── asgi_app.py
├── bddk_mcp_module
│   ├── __init__.py
│   ├── client.py
│   └── models.py
├── bedesten_mcp_module
│   ├── __init__.py
│   ├── client.py
│   ├── enums.py
│   └── models.py
├── check_response_format.py
├── CLAUDE.md
├── danistay_mcp_module
│   ├── __init__.py
│   ├── client.py
│   └── models.py
├── docker-compose.yml
├── Dockerfile
├── docs
│   └── DEPLOYMENT.md
├── emsal_mcp_module
│   ├── __init__.py
│   ├── client.py
│   └── models.py
├── example_fastapi_app.py
├── fly-no-auth.toml
├── fly.toml
├── kik_mcp_module
│   ├── __init__.py
│   ├── client_v2.py
│   ├── client.py
│   ├── models_v2.py
│   └── models.py
├── kvkk_mcp_module
│   ├── __init__.py
│   ├── client.py
│   └── models.py
├── LICENSE
├── mcp_auth
│   ├── __init__.py
│   ├── clerk_config.py
│   ├── middleware.py
│   ├── oauth.py
│   ├── policy.py
│   └── storage.py
├── mcp_auth_factory.py
├── mcp_auth_http_adapter.py
├── mcp_auth_http_simple.py
├── mcp_server_main.py
├── nginx.conf
├── ornek.png
├── Procfile
├── pyproject.toml
├── railway.json
├── README.md
├── redis_session_store.py
├── rekabet_mcp_module
│   ├── __init__.py
│   ├── client.py
│   └── models.py
├── requirements.txt
├── run_asgi.py
├── saidsurucu-yargi-mcp-f5fa007
│   ├── __main__.py
│   ├── .dockerignore
│   ├── .env.example
│   ├── .gitattributes
│   ├── .github
│   │   └── workflows
│   │       └── publish.yml
│   ├── .gitignore
│   ├── 5ire-settings.png
│   ├── anayasa_mcp_module
│   │   ├── __init__.py
│   │   ├── bireysel_client.py
│   │   ├── client.py
│   │   ├── models.py
│   │   └── unified_client.py
│   ├── asgi_app.py
│   ├── bddk_mcp_module
│   │   ├── __init__.py
│   │   ├── client.py
│   │   └── models.py
│   ├── bedesten_mcp_module
│   │   ├── __init__.py
│   │   ├── client.py
│   │   ├── enums.py
│   │   └── models.py
│   ├── check_response_format.py
│   ├── danistay_mcp_module
│   │   ├── __init__.py
│   │   ├── client.py
│   │   └── models.py
│   ├── docker-compose.yml
│   ├── Dockerfile
│   ├── docs
│   │   └── DEPLOYMENT.md
│   ├── emsal_mcp_module
│   │   ├── __init__.py
│   │   ├── client.py
│   │   └── models.py
│   ├── example_fastapi_app.py
│   ├── kik_mcp_module
│   │   ├── __init__.py
│   │   ├── client.py
│   │   └── models.py
│   ├── kvkk_mcp_module
│   │   ├── __init__.py
│   │   ├── client.py
│   │   └── models.py
│   ├── LICENSE
│   ├── mcp_auth
│   │   ├── __init__.py
│   │   ├── clerk_config.py
│   │   ├── middleware.py
│   │   ├── oauth.py
│   │   ├── policy.py
│   │   └── storage.py
│   ├── mcp_auth_factory.py
│   ├── mcp_auth_http_adapter.py
│   ├── mcp_auth_http_simple.py
│   ├── mcp_server_main.py
│   ├── nginx.conf
│   ├── ornek.png
│   ├── Procfile
│   ├── pyproject.toml
│   ├── railway.json
│   ├── README.md
│   ├── redis_session_store.py
│   ├── rekabet_mcp_module
│   │   ├── __init__.py
│   │   ├── client.py
│   │   └── models.py
│   ├── run_asgi.py
│   ├── sayistay_mcp_module
│   │   ├── __init__.py
│   │   ├── client.py
│   │   ├── enums.py
│   │   ├── models.py
│   │   └── unified_client.py
│   ├── starlette_app.py
│   ├── stripe_webhook.py
│   ├── uyusmazlik_mcp_module
│   │   ├── __init__.py
│   │   ├── client.py
│   │   └── models.py
│   └── yargitay_mcp_module
│       ├── __init__.py
│       ├── client.py
│       └── models.py
├── sayistay_mcp_module
│   ├── __init__.py
│   ├── client.py
│   ├── enums.py
│   ├── models.py
│   └── unified_client.py
├── starlette_app.py
├── stripe_webhook.py
├── uv.lock
├── uyusmazlik_mcp_module
│   ├── __init__.py
│   ├── client.py
│   └── models.py
└── yargitay_mcp_module
    ├── __init__.py
    ├── client.py
    └── models.py
```

# Files

--------------------------------------------------------------------------------
/example_fastapi_app.py:
--------------------------------------------------------------------------------

```python
   1 | """
   2 | FastAPI Comprehensive Endpoints with Complete MCP Documentation
   3 | This is the complete version with all descriptions and docstrings from MCP server.
   4 | """
   5 | 
   6 | import os
   7 | from typing import List, Dict, Any, Optional
   8 | from datetime import datetime
   9 | 
  10 | from fastapi import FastAPI, HTTPException, Query, Depends, Body
  11 | from fastapi.middleware.cors import CORSMiddleware
  12 | from fastapi.responses import JSONResponse
  13 | from pydantic import BaseModel, Field
  14 | import json
  15 | 
  16 | # Import the main MCP app
  17 | from mcp_server_main import app as mcp_server
  18 | 
  19 | # Create MCP ASGI app
  20 | mcp_asgi_app = mcp_server.http_app(path="/mcp")
  21 | 
  22 | # Create FastAPI app with MCP lifespan
  23 | app = FastAPI(
  24 |     title="Yargı MCP API - Turkish Legal Database REST API",
  25 |     description="""
  26 |     Comprehensive REST API for Turkish Legal Databases with complete MCP tool coverage.
  27 |     
  28 |     This API provides access to 8 major Turkish legal institutions including:
  29 |     • Yargıtay (Court of Cassation) - Supreme civil/criminal court
  30 |     • Danıştay (Council of State) - Supreme administrative court  
  31 |     • Constitutional Court - Constitutional review and individual applications
  32 |     • Competition Authority - Antitrust and merger decisions
  33 |     • Public Procurement Authority - Government contracting disputes
  34 |     • Court of Accounts - Public audit and accountability
  35 |     • Emsal (UYAP Precedents) - Cross-court precedent database
  36 |     • Local and Appellate Courts - First and second instance decisions
  37 |     
  38 |     Features complete coverage of 33 MCP tools with enhanced documentation,
  39 |     typed request models, and comprehensive legal context.
  40 |     
  41 |     Tool Properties (from MCP annotations):
  42 |     • Read-only: All tools are read-only and do not modify system state
  43 |     • Idempotent: Same inputs produce same outputs for reliable research
  44 |     • Open-world search: Search tools explore comprehensive legal databases
  45 |     • Deterministic document retrieval: Document tools return consistent content
  46 |     """,
  47 |     version="1.0.0",
  48 |     lifespan=mcp_asgi_app.lifespan
  49 | )
  50 | 
  51 | # Add CORS middleware
  52 | cors_origins = os.getenv("ALLOWED_ORIGINS", "*").split(",")
  53 | app.add_middleware(
  54 |     CORSMiddleware,
  55 |     allow_origins=cors_origins,
  56 |     allow_credentials=True,
  57 |     allow_methods=["*"],
  58 |     allow_headers=["*"],
  59 | )
  60 | 
  61 | # Mount MCP server
  62 | app.mount("/mcp-server", mcp_asgi_app)
  63 | 
  64 | # Response models (keeping from original)
  65 | class ToolInfo(BaseModel):
  66 |     name: str
  67 |     description: str
  68 |     parameters: Dict[str, Any]
  69 | 
  70 | class ServerInfo(BaseModel):
  71 |     name: str
  72 |     version: str
  73 |     description: str
  74 |     tools_count: int
  75 |     databases: List[str]
  76 |     mcp_endpoint: str
  77 |     api_docs: str
  78 | 
  79 | class HealthCheck(BaseModel):
  80 |     status: str
  81 |     timestamp: datetime
  82 |     uptime_seconds: Optional[float] = None
  83 |     tools_operational: bool
  84 | 
  85 | # Track server start time
  86 | SERVER_START_TIME = datetime.now()
  87 | 
  88 | # MCP tool caller helper
  89 | async def call_mcp_tool(tool_name: str, arguments: Dict[str, Any]):
  90 |     """Call an MCP tool with given arguments"""
  91 |     try:
  92 |         tool = mcp_server._tool_manager._tools.get(tool_name)
  93 |         if not tool:
  94 |             raise HTTPException(status_code=404, detail=f"Tool '{tool_name}' not found")
  95 |         result = await tool.fn(**arguments)
  96 |         return result
  97 |     except Exception as e:
  98 |         raise HTTPException(status_code=500, detail=f"Tool execution failed: {str(e)}")
  99 | 
 100 | # ============================================================================
 101 | # COMPREHENSIVE REQUEST MODELS WITH FULL MCP DOCUMENTATION
 102 | # ============================================================================
 103 | 
 104 | class YargitaySearchRequest(BaseModel):
 105 |     """
 106 |     Search request for Court of Cassation (Yargıtay) decisions using primary official API.
 107 |     
 108 |     The Court of Cassation is Turkey's highest court for civil and criminal matters,
 109 |     equivalent to a Supreme Court. Provides access to comprehensive supreme court precedents.
 110 |     """
 111 |     arananKelime: str = Field(
 112 |         ..., 
 113 |         description="""Keyword to search for with advanced operators:
 114 |         • Space between words = OR logic (arsa payı → "arsa" OR "payı")
 115 |         • "exact phrase" = Exact match ("arsa payı" → exact phrase)
 116 |         • word1+word2 = AND logic (arsa+payı → both words required)
 117 |         • word* = Wildcard (bozma* → bozma, bozması, bozmanın, etc.)
 118 |         • +"phrase1" +"phrase2" = Multiple required phrases
 119 |         • +"required" -"excluded" = Include and exclude
 120 |         
 121 |         Turkish Examples:
 122 |         • Simple OR: arsa payı (~523K results)
 123 |         • Exact phrase: "arsa payı" (~22K results)
 124 |         • Multiple AND: +"arsa payı" +"bozma sebebi" (~234 results)
 125 |         • Wildcard: bozma* (bozma, bozması, bozmanın, etc.)
 126 |         • Exclude: +"arsa payı" -"kira sözleşmesi"
 127 |         """,
 128 |         example='+"mülkiyet hakkı" +"iptal"'
 129 |     )
 130 |     birimYrgKurulDaire: Optional[str] = Field(
 131 |         "", 
 132 |         description="""Chamber/board selection (52 options):
 133 |         Civil Chambers: 1-23. Hukuk Dairesi
 134 |         Criminal Chambers: 1-23. Ceza Dairesi
 135 |         General Assemblies: Hukuk Genel Kurulu, Ceza Genel Kurulu
 136 |         Special Boards: Hukuk/Ceza Daireleri Başkanlar Kurulu, Büyük Genel Kurulu
 137 |         
 138 |         Use "" for ALL chambers or specify exact chamber name.
 139 |         """,
 140 |         example="1. Hukuk Dairesi"
 141 |     )
 142 |     baslangicTarihi: Optional[str] = Field(None, description="Start date (DD.MM.YYYY)", example="01.01.2020")
 143 |     bitisTarihi: Optional[str] = Field(None, description="End date (DD.MM.YYYY)", example="31.12.2024")
 144 |     pageSize: int = Field(20, description="Results per page (1-100)", ge=1, le=100, example=20)
 145 | 
 146 | class YargitayBedestenSearchRequest(BaseModel):
 147 |     """
 148 |     Search request for Court of Cassation using Bedesten API (alternative source).
 149 |     Complements primary API with different search capabilities and recent decisions.
 150 |     """
 151 |     phrase: str = Field(
 152 |         ..., 
 153 |         description="""Aranacak kavram/kelime. İki farklı arama türü desteklenir:
 154 |         • Normal arama: "mülkiyet hakkı" - kelimeler ayrı ayrı aranır
 155 |         • Tam cümle arama: "\"mülkiyet hakkı\"" - tırnak içindeki ifade aynen aranır
 156 |         Tam cümle aramalar daha kesin sonuçlar verir.
 157 |         
 158 |         Search phrase with exact matching support:
 159 |         • Regular search: "mülkiyet hakkı" - searches individual words separately
 160 |         • Exact phrase search: "\"mülkiyet hakkı\"" - searches for exact phrase as unit
 161 |         Exact phrase search provides more precise results with fewer false positives.
 162 |         """,
 163 |         example="\"mülkiyet hakkı\""
 164 |     )
 165 |     birimAdi: Optional[str] = Field(
 166 |         None, 
 167 |         description="""Daire/Kurul seçimi (52 seçenek - ana API ile aynı):
 168 |         • Hukuk daireleri: 1. Hukuk Dairesi - 23. Hukuk Dairesi
 169 |         • Ceza daireleri: 1. Ceza Dairesi - 23. Ceza Dairesi
 170 |         • Genel kurullar: Hukuk Genel Kurulu, Ceza Genel Kurulu
 171 |         • Özel kurullar: Hukuk/Ceza Daireleri Başkanlar Kurulu, Büyük Genel Kurulu
 172 |         
 173 |         Chamber filtering (52 options - same as primary API):
 174 |         • Civil chambers: 1. Hukuk Dairesi through 23. Hukuk Dairesi
 175 |         • Criminal chambers: 1. Ceza Dairesi through 23. Ceza Dairesi
 176 |         • General assemblies: Hukuk Genel Kurulu, Ceza Genel Kurulu
 177 |         • Special boards: Hukuk/Ceza Daireleri Başkanlar Kurulu, Büyük Genel Kurulu
 178 |         
 179 |         Use None for ALL chambers, or specify exact chamber name.
 180 |         """,
 181 |         example="1. Hukuk Dairesi"
 182 |     )
 183 |     kararTarihiStart: Optional[str] = Field(
 184 |         None, 
 185 |         description="""Karar başlangıç tarihi (ISO 8601 formatı):
 186 |         Format: YYYY-MM-DDTHH:MM:SS.000Z
 187 |         Örnek: "2024-01-01T00:00:00.000Z" - 1 Ocak 2024'ten itibaren kararlar
 188 |         kararTarihiEnd ile birlikte tarih aralığı filtrelemesi için kullanılır.
 189 |         
 190 |         Decision start date filter (ISO 8601 format):
 191 |         Format: YYYY-MM-DDTHH:MM:SS.000Z
 192 |         Example: "2024-01-01T00:00:00.000Z" for decisions from Jan 1, 2024
 193 |         Use with kararTarihiEnd for date range filtering.
 194 |         """,
 195 |         example="2024-01-01T00:00:00.000Z"
 196 |     )
 197 |     kararTarihiEnd: Optional[str] = Field(
 198 |         None, 
 199 |         description="""Karar bitiş tarihi (ISO 8601 formatı):
 200 |         Format: YYYY-MM-DDTHH:MM:SS.000Z
 201 |         Örnek: "2024-12-31T23:59:59.999Z" - 31 Aralık 2024'e kadar kararlar
 202 |         kararTarihiStart ile birlikte tarih aralığı filtrelemesi için kullanılır.
 203 |         
 204 |         Decision end date filter (ISO 8601 format):
 205 |         Format: YYYY-MM-DDTHH:MM:SS.000Z
 206 |         Example: "2024-12-31T23:59:59.999Z" for decisions until Dec 31, 2024
 207 |         Use with kararTarihiStart for date range filtering.
 208 |         """,
 209 |         example="2024-12-31T23:59:59.999Z"
 210 |     )
 211 |     pageSize: int = Field(20, description="Results per page (1-100)", ge=1, le=100)
 212 | 
 213 | class DanistayKeywordSearchRequest(BaseModel):
 214 |     """
 215 |     Keyword-based search for Council of State (Danıştay) decisions with Boolean logic.
 216 |     
 217 |     The Council of State is Turkey's highest administrative court, providing final
 218 |     rulings on administrative law matters with Boolean keyword operators.
 219 |     """
 220 |     andKelimeler: List[str] = Field(
 221 |         ..., 
 222 |         description="ALL keywords must be present (AND logic)",
 223 |         example=["idari işlem", "iptal"]
 224 |     )
 225 |     orKelimeler: Optional[List[str]] = Field(
 226 |         None, 
 227 |         description="ANY keyword can be present (OR logic)",
 228 |         example=["ruhsat", "izin", "lisans"]
 229 |     )
 230 |     notKelimeler: Optional[List[str]] = Field(
 231 |         None, 
 232 |         description="EXCLUDE if keywords present (NOT logic)",
 233 |         example=["vergi"]
 234 |     )
 235 |     pageSize: int = Field(20, description="Results per page (1-100)", ge=1, le=100)
 236 | 
 237 | class DanistayDetailedSearchRequest(BaseModel):
 238 |     """
 239 |     Detailed search for Council of State decisions with comprehensive filtering.
 240 |     Provides the most comprehensive search capabilities for administrative court decisions.
 241 |     """
 242 |     daire: Optional[str] = Field(
 243 |         None, 
 244 |         description="Chamber/Department filter (1. Daire through 17. Daire, special councils)",
 245 |         example="3. Daire"
 246 |     )
 247 |     baslangicTarihi: Optional[str] = Field(None, description="Start date (DD.MM.YYYY)", example="01.01.2020")
 248 |     bitisTarihi: Optional[str] = Field(None, description="End date (DD.MM.YYYY)", example="31.12.2024")
 249 |     esas: Optional[str] = Field(None, description="Case number (Esas No)", example="2024/123")
 250 |     karar: Optional[str] = Field(None, description="Decision number (Karar No)", example="2024/456")
 251 | 
 252 | class DanistayBedestenSearchRequest(BaseModel):
 253 |     """
 254 |     Council of State search using Bedesten API with chamber filtering and exact phrase search.
 255 |     Provides access to administrative court decisions with 27 chamber options.
 256 |     """
 257 |     phrase: str = Field(..., description="Search phrase (supports exact matching with quotes)")
 258 |     birimAdi: Optional[str] = Field(
 259 |         None, 
 260 |         description="""Chamber filtering (27 options):
 261 |         Main Councils: Büyük Gen.Kur., İdare Dava Daireleri Kurulu, Vergi Dava Daireleri Kurulu
 262 |         Chambers: 1. Daire through 17. Daire
 263 |         Military: Askeri Yüksek İdare Mahkemesi chambers
 264 |         """,
 265 |         example="3. Daire"
 266 |     )
 267 |     kararTarihiStart: Optional[str] = Field(None, description="Start date (ISO 8601)")
 268 |     kararTarihiEnd: Optional[str] = Field(None, description="End date (ISO 8601)")
 269 |     pageSize: int = Field(20, description="Results per page", ge=1, le=100)
 270 | 
 271 | class EmsalSearchRequest(BaseModel):
 272 |     """
 273 |     Search Precedent (Emsal) decisions from UYAP system across multiple court levels.
 274 |     Provides access to precedent decisions from various Turkish courts.
 275 |     """
 276 |     keyword: str = Field(..., description="Search keyword across decision texts")
 277 |     decision_year_karar: Optional[str] = Field(None, description="Decision year filter", example="2024")
 278 |     results_per_page: int = Field(20, description="Results per page", ge=1, le=100)
 279 | 
 280 | class UyusmazlikSearchRequest(BaseModel):
 281 |     """
 282 |     Search Court of Jurisdictional Disputes decisions.
 283 |     Resolves jurisdictional disputes between different court systems.
 284 |     """
 285 |     keywords: List[str] = Field(..., description="Search keywords", example=["görev", "uyuşmazlık"])
 286 |     page_to_fetch: int = Field(1, description="Page number", ge=1)
 287 | 
 288 | class AnayasaNormSearchRequest(BaseModel):
 289 |     """
 290 |     Search Constitutional Court norm control (judicial review) decisions.
 291 |     Turkey's highest constitutional authority for reviewing law constitutionality.
 292 |     """
 293 |     keywords_all: List[str] = Field(..., description="All required keywords", example=["eğitim hakkı", "anayasa"])
 294 |     period: Optional[str] = Field(None, description="Constitutional period (1=1961, 2=1982)", example="2")
 295 |     application_type: Optional[str] = Field(None, description="Application type (1=İptal)", example="1")
 296 |     results_per_page: int = Field(20, description="Results per page", ge=1, le=100)
 297 | 
 298 | class AnayasaBireyselSearchRequest(BaseModel):
 299 |     """
 300 |     Search Constitutional Court individual application decisions.
 301 |     Human rights violation cases through individual citizen petitions.
 302 |     """
 303 |     keywords: List[str] = Field(..., description="Search keywords", example=["ifade özgürlüğü", "basın"])
 304 |     page_to_fetch: int = Field(1, description="Page number", ge=1)
 305 | 
 306 | class KikSearchRequest(BaseModel):
 307 |     """
 308 |     Search Public Procurement Authority (KİK) decisions.
 309 |     Government procurement disputes and regulatory interpretations.
 310 |     """
 311 |     karar_tipi: Optional[str] = Field(
 312 |         None, 
 313 |         description="Decision type (rbUyusmazlik=Disputes, rbDuzenleyici=Regulatory, rbMahkeme=Court)",
 314 |         example="rbUyusmazlik"
 315 |     )
 316 |     karar_metni: Optional[str] = Field(None, description="Decision text search", example="ihale iptali")
 317 |     basvuru_konusu_ihale: Optional[str] = Field(None, description="Tender subject", example="danışmanlık")
 318 |     karar_tarihi_baslangic: Optional[str] = Field(None, description="Start date", example="01.01.2023")
 319 | 
 320 | class RekabetSearchRequest(BaseModel):
 321 |     """
 322 |     Search Competition Authority decisions.
 323 |     Antitrust, merger control, and competition law enforcement.
 324 |     """
 325 |     KararTuru: Optional[str] = Field(
 326 |         None, 
 327 |         description="Decision type (Birleşme ve Devralma, Rekabet İhlali, Muafiyet, etc.)",
 328 |         example="Birleşme ve Devralma"
 329 |     )
 330 |     PdfText: Optional[str] = Field(
 331 |         None, 
 332 |         description="Full-text search in decisions. Use quotes for exact phrases.",
 333 |         example="\"market definition\" telecommunications"
 334 |     )
 335 |     YayinlanmaTarihi: Optional[str] = Field(None, description="Publication date", example="01.01.2020")
 336 |     page: int = Field(1, description="Page number", ge=1)
 337 | 
 338 | class BedestenSearchRequest(BaseModel):
 339 |     """
 340 |     Generic search request for Bedesten API courts (Yerel Hukuk, İstinaf Hukuk, KYB).
 341 |     Supports exact phrase search and date filtering.
 342 |     """
 343 |     phrase: str = Field(
 344 |         ..., 
 345 |         description="Search phrase. Use quotes for exact matching: \"legal term\"",
 346 |         example="\"sözleşme ihlali\""
 347 |     )
 348 |     kararTarihiStart: Optional[str] = Field(None, description="Start date (ISO 8601)")
 349 |     kararTarihiEnd: Optional[str] = Field(None, description="End date (ISO 8601)")
 350 |     pageSize: int = Field(20, description="Results per page", ge=1, le=100)
 351 | 
 352 | class SayistaySearchRequest(BaseModel):
 353 |     """
 354 |     Search Court of Accounts (Sayıştay) decisions.
 355 |     Public audit, accountability, and financial oversight decisions.
 356 |     """
 357 |     keywords: List[str] = Field(..., description="Search keywords", example=["mali sorumluluk", "denetim"])
 358 |     page_to_fetch: int = Field(1, description="Page number", ge=1)
 359 | 
 360 | # ============================================================================
 361 | # BASIC SERVER ENDPOINTS (keeping from original)
 362 | # ============================================================================
 363 | 
 364 | @app.get("/", response_model=ServerInfo)
 365 | async def root():
 366 |     """Get comprehensive server information with database coverage"""
 367 |     return ServerInfo(
 368 |         name="Yargı MCP Server - Turkish Legal Database API",
 369 |         version="1.0.0", 
 370 |         description="Complete REST API for Turkish legal databases with 33 MCP tools",
 371 |         tools_count=len(mcp_server._tool_manager._tools),
 372 |         databases=[
 373 |             "Yargıtay (Court of Cassation) - 4 tools",
 374 |             "Danıştay (Council of State) - 5 tools", 
 375 |             "Emsal (UYAP Precedents) - 2 tools",
 376 |             "Uyuşmazlık Mahkemesi (Jurisdictional Disputes) - 2 tools",
 377 |             "Anayasa Mahkemesi (Constitutional Court) - 4 tools",
 378 |             "Kamu İhale Kurulu (Public Procurement) - 2 tools",
 379 |             "Rekabet Kurumu (Competition Authority) - 2 tools",
 380 |             "Sayıştay (Court of Accounts) - 6 tools",
 381 |             "Bedesten API Courts (Local/Appellate/KYB) - 6 tools"
 382 |         ],
 383 |         mcp_endpoint="/mcp-server/mcp/",
 384 |         api_docs="/docs"
 385 |     )
 386 | 
 387 | @app.get("/health", response_model=HealthCheck)
 388 | async def health_check():
 389 |     """Health check with comprehensive system status"""
 390 |     uptime = (datetime.now() - SERVER_START_TIME).total_seconds()
 391 |     return HealthCheck(
 392 |         status="healthy",
 393 |         timestamp=datetime.now(),
 394 |         uptime_seconds=uptime,
 395 |         tools_operational=len(mcp_server._tool_manager._tools) == 33
 396 |     )
 397 | 
 398 | @app.get("/api/tools", response_model=List[ToolInfo])
 399 | async def list_tools(
 400 |     search: Optional[str] = Query(None, description="Search tools by name or description"),
 401 |     database: Optional[str] = Query(None, description="Filter by database name")
 402 | ):
 403 |     """List all 33 MCP tools with filtering capabilities"""
 404 |     tools = []
 405 |     for tool in mcp_server._tool_manager._tools.values():
 406 |         if search and search.lower() not in tool.name.lower() and search.lower() not in tool.description.lower():
 407 |             continue
 408 |         if database:
 409 |             db_lower = database.lower()
 410 |             if db_lower not in tool.name.lower() and db_lower not in tool.description.lower():
 411 |                 continue
 412 |         
 413 |         params = {}
 414 |         if hasattr(tool, 'schema') and tool.schema:
 415 |             if hasattr(tool.schema, 'parameters'):
 416 |                 params = tool.schema.parameters
 417 |             elif hasattr(tool.schema, '__annotations__'):
 418 |                 params = {k: str(v) for k, v in tool.schema.__annotations__.items()}
 419 |         
 420 |         tools.append(ToolInfo(
 421 |             name=tool.name,
 422 |             description=tool.description,
 423 |             parameters=params
 424 |         ))
 425 |     return tools
 426 | 
 427 | # ============================================================================
 428 | # YARGITAY (COURT OF CASSATION) ENDPOINTS - 4 TOOLS
 429 | # ============================================================================
 430 | 
 431 | @app.post(
 432 |     "/api/yargitay/search", 
 433 |     tags=["Yargıtay"],
 434 |     summary="Search Court of Cassation (Primary API)",
 435 |     description="""Search Turkey's Supreme Court for civil and criminal precedents using advanced operators.
 436 | 
 437 | Key Features:
 438 | • Advanced search: AND (+), OR (space), NOT (-), wildcards (*), exact phrases ("")
 439 | • 52 chamber options (23 Civil + 23 Criminal + General Assemblies)
 440 | • Date range filtering • Case/decision number filtering • Pagination
 441 | 
 442 | Search Examples:
 443 | • OR search: property share (finds ANY words)
 444 | • Exact phrase: "property share" (finds exact phrase)
 445 | • AND required: +"property share" +"annulment reason"
 446 | • Wildcard: construct* (construction, constructive, etc.)
 447 | • Exclude terms: +"property share" -"construction contract"
 448 | 
 449 | Use for supreme court precedent research and legal principle analysis."""
 450 | )
 451 | async def search_yargitay(request: YargitaySearchRequest):
 452 |     """
 453 |     Searches Court of Cassation (Yargıtay) decisions using the primary official API.
 454 | 
 455 |     The Court of Cassation (Yargıtay) is Turkey's highest court for civil and criminal matters,
 456 |     equivalent to a Supreme Court. This tool provides access to the most comprehensive database
 457 |     of supreme court precedents with advanced search capabilities and filtering options.
 458 | 
 459 |     Key Features:
 460 |     • Advanced search operators (AND, OR, wildcards, exclusions)
 461 |     • Chamber filtering: 52 options (23 Civil (Hukuk) + 23 Criminal (Ceza) + General Assemblies (Genel Kurullar))
 462 |     • Date range filtering with DD.MM.YYYY format
 463 |     • Case number filtering (Case No (Esas No) and Decision No (Karar No))
 464 |     • Pagination support (1-100 results per page)
 465 |     • Multiple sorting options (by case number, decision number, date)
 466 | 
 467 |     SEARCH SYNTAX GUIDE:
 468 |     • Words with spaces: OR search ("property share" finds ANY of the words)
 469 |     • "Quotes": Exact phrase search ("property share" finds exact phrase)
 470 |     • Plus sign (+): AND search (property+share requires both words)
 471 |     • Asterisk (*): Wildcard (construct* matches variations)
 472 |     • Minus sign (-): Exclude terms (avoid unwanted results)
 473 | 
 474 |     Common Search Patterns:
 475 |     • Simple OR: property share (finds ~523K results)
 476 |     • Exact phrase: "property share" (finds ~22K results)
 477 |     • Multiple required: +"property share" +"annulment reason (bozma sebebi)" (finds ~234 results)
 478 |     • Wildcard expansion: construct* (matches construction, constructive, etc.)
 479 |     • Exclude unwanted: +"property share" -"construction contract"
 480 | 
 481 |     Use cases:
 482 |     • Research supreme court precedents and legal principles
 483 |     • Find decisions from specific chambers (Civil (Hukuk) vs Criminal (Ceza))
 484 |     • Search for interpretations of specific legal concepts
 485 |     • Analyze court reasoning on complex legal issues
 486 |     • Track legal developments over time periods
 487 | 
 488 |     Returns structured search results with decision metadata. Use get_yargitay_document_markdown()
 489 |     to retrieve full decision texts for detailed analysis.
 490 |     """
 491 |     args = {
 492 |         "arananKelime": request.arananKelime,
 493 |         "birimYrgKurulDaire": request.birimYrgKurulDaire, 
 494 |         "pageSize": request.pageSize
 495 |     }
 496 |     if request.baslangicTarihi:
 497 |         args["baslangicTarihi"] = request.baslangicTarihi
 498 |     if request.bitisTarihi:
 499 |         args["bitisTarihi"] = request.bitisTarihi
 500 |     return await call_mcp_tool("search_yargitay_detailed", args)
 501 | 
 502 | @app.post(
 503 |     "/api/yargitay/search-bedesten",
 504 |     tags=["Yargıtay"], 
 505 |     summary="Search Court of Cassation (Bedesten API)",
 506 |     description="""Alternative Court of Cassation search with exact phrase matching and recent decisions.
 507 | 
 508 | Key Features:
 509 | • Exact phrase search: "\"legal term\"" for precise matching
 510 | • Regular search: "legal term" for individual word matching  
 511 | • 52 chamber filtering options (same as primary API)
 512 | • ISO 8601 date filtering • Recent decision coverage
 513 | 
 514 | Use alongside primary search for comprehensive coverage. Exact phrase search provides
 515 | higher precision with fewer false positives."""
 516 | )
 517 | async def search_yargitay_bedesten(request: YargitayBedestenSearchRequest):
 518 |     """Search Court of Cassation using Bedesten API. Complements primary API for complete coverage."""
 519 |     args = {"phrase": request.phrase, "pageSize": request.pageSize}
 520 |     if request.birimAdi:
 521 |         args["birimAdi"] = request.birimAdi
 522 |     if request.kararTarihiStart:
 523 |         args["kararTarihiStart"] = request.kararTarihiStart
 524 |     if request.kararTarihiEnd:
 525 |         args["kararTarihiEnd"] = request.kararTarihiEnd
 526 |     return await call_mcp_tool("search_yargitay_bedesten", args)
 527 | 
 528 | @app.get(
 529 |     "/api/yargitay/document/{decision_id}",
 530 |     tags=["Yargıtay"],
 531 |     summary="Get Court of Cassation Document (Primary API)", 
 532 |     description="""Retrieve complete Court of Cassation decision in Markdown format.
 533 | 
 534 | Content includes:
 535 | • Complete legal reasoning and precedent analysis
 536 | • Detailed examination of lower court decisions  
 537 | • Citations of laws, regulations, and prior cases
 538 | • Final ruling with legal justification
 539 | 
 540 | Perfect for detailed legal analysis, precedent research, and citation building."""
 541 | )
 542 | async def get_yargitay_document(decision_id: str):
 543 |     """Get full Court of Cassation decision text in clean Markdown format."""
 544 |     return await call_mcp_tool("get_yargitay_document_markdown", {"id": decision_id})
 545 | 
 546 | @app.get(
 547 |     "/api/yargitay/bedesten-document/{document_id}",
 548 |     tags=["Yargıtay"],
 549 |     summary="Get Court of Cassation Document (Bedesten API)",
 550 |     description="""Retrieve Court of Cassation decision from Bedesten API in Markdown format.
 551 | 
 552 | Features:
 553 | • Supports both HTML and PDF source documents
 554 | • Clean Markdown conversion with legal structure preserved
 555 | • Removes technical artifacts for easy reading
 556 | • Compatible with documentId from Bedesten search results"""
 557 | )
 558 | async def get_yargitay_bedesten_document(document_id: str):
 559 |     """Get Court of Cassation document from Bedesten API in Markdown format."""
 560 |     return await call_mcp_tool("get_yargitay_bedesten_document_markdown", {"documentId": document_id})
 561 | 
 562 | # ============================================================================
 563 | # DANISTAY (COUNCIL OF STATE) ENDPOINTS - 5 TOOLS  
 564 | # ============================================================================
 565 | 
 566 | @app.post(
 567 |     "/api/danistay/search-keyword",
 568 |     tags=["Danıştay"],
 569 |     summary="Search Council of State (Keyword Logic)",
 570 |     description="""Search Turkey's highest administrative court using Boolean keyword logic.
 571 | 
 572 | Boolean Operators:
 573 | • AND keywords: ALL must be present (required terms)
 574 | • OR keywords: ANY can be present (alternative terms)  
 575 | • NOT keywords: EXCLUDE if present (unwanted terms)
 576 | 
 577 | Examples:
 578 | • Administrative acts: andKelimeler=["idari işlem", "iptal"]
 579 | • Permits/licenses: orKelimeler=["ruhsat", "izin", "lisans"]
 580 | • Exclude tax cases: notKelimeler=["vergi"]
 581 | 
 582 | Perfect for administrative law research and government action reviews."""
 583 | )
 584 | async def search_danistay_keyword(request: DanistayKeywordSearchRequest):
 585 |     """
 586 |     Searches Council of State (Danıştay) decisions using keyword-based logic.
 587 | 
 588 |     The Council of State (Danıştay) is Turkey's highest administrative court, responsible for
 589 |     reviewing administrative actions and providing administrative law precedents. This tool
 590 |     provides flexible keyword-based searching with Boolean logic operators.
 591 | 
 592 |     Key Features:
 593 |     • Boolean logic operators: AND, OR, NOT combinations
 594 |     • Multiple keyword lists for complex search strategies
 595 |     • Pagination support (1-100 results per page)
 596 |     • Administrative law focus (permits, licenses, public administration)
 597 |     • Complement to search_danistay_detailed for comprehensive coverage
 598 | 
 599 |     Keyword Logic:
 600 |     • andKelimeler: ALL keywords must be present (AND logic)
 601 |     • orKelimeler: ANY keyword can be present (OR logic)
 602 |     • notAndKelimeler: EXCLUDE if ALL keywords present (NOT AND)
 603 |     • notOrKelimeler: EXCLUDE if ANY keyword present (NOT OR)
 604 | 
 605 |     Administrative Law Use Cases:
 606 |     • Research administrative court precedents
 607 |     • Find decisions on specific government agencies
 608 |     • Search for rulings on permits (ruhsat) and licenses (izin)
 609 |     • Analyze administrative procedure interpretations
 610 |     • Study public administration legal principles
 611 | 
 612 |     Examples:
 613 |     • Simple AND: andKelimeler=["administrative act (idari işlem)", "annulment (iptal)"]
 614 |     • OR search: orKelimeler=["permit (ruhsat)", "permission (izin)", "license (lisans)"]
 615 |     • Complex: andKelimeler=["municipality (belediye)"], notOrKelimeler=["tax (vergi)"]
 616 | 
 617 |     Returns structured search results. Use get_danistay_document_markdown() for full texts.
 618 |     For comprehensive Council of State (Danıştay) research, also use search_danistay_detailed and search_danistay_bedesten.
 619 |     """
 620 |     args = {"andKelimeler": request.andKelimeler, "pageSize": request.pageSize}
 621 |     if request.orKelimeler:
 622 |         args["orKelimeler"] = request.orKelimeler
 623 |     if request.notKelimeler:
 624 |         args["notKelimeler"] = request.notKelimeler
 625 |     return await call_mcp_tool("search_danistay_by_keyword", args)
 626 | 
 627 | @app.post(
 628 |     "/api/danistay/search-detailed",
 629 |     tags=["Danıştay"],
 630 |     summary="Search Council of State (Detailed Criteria)",
 631 |     description="""Most comprehensive Council of State search with advanced filtering.
 632 | 
 633 | Advanced Filtering:
 634 | • Chamber targeting (1. Daire through 17. Daire, special councils)
 635 | • Case/decision number ranges • Date range filtering
 636 | • Legislation cross-referencing • Multiple sorting options
 637 | 
 638 | Use for specialized administrative law research, chamber-specific decisions,
 639 | and regulatory compliance analysis."""
 640 | )
 641 | async def search_danistay_detailed(request: DanistayDetailedSearchRequest):
 642 |     """Search Council of State with comprehensive filtering for specialized administrative law research."""
 643 |     args = {}
 644 |     for field in ["daire", "baslangicTarihi", "bitisTarihi", "esas", "karar"]:
 645 |         if getattr(request, field):
 646 |             args[field] = getattr(request, field)
 647 |     return await call_mcp_tool("search_danistay_detailed", args)
 648 | 
 649 | @app.post(
 650 |     "/api/danistay/search-bedesten",
 651 |     tags=["Danıştay"],
 652 |     summary="Search Council of State (Bedesten API)",
 653 |     description="""Council of State search via Bedesten API with 27 chamber options and exact phrase search.
 654 | 
 655 | Key Features:
 656 | • 27 chamber options (Main Councils, 17 Chambers, Military courts)
 657 | • Exact phrase search with double quotes for precision
 658 | • ISO 8601 date filtering • Alternative data source
 659 | 
 660 | Use with other Danıştay tools for complete administrative law coverage."""
 661 | )
 662 | async def search_danistay_bedesten(request: DanistayBedestenSearchRequest):
 663 |     """Search Council of State via Bedesten API. Use with other Danıştay tools for complete coverage."""
 664 |     args = {"phrase": request.phrase, "pageSize": request.pageSize}
 665 |     for field in ["birimAdi", "kararTarihiStart", "kararTarihiEnd"]:
 666 |         if getattr(request, field):
 667 |             args[field] = getattr(request, field)
 668 |     return await call_mcp_tool("search_danistay_bedesten", args)
 669 | 
 670 | @app.get(
 671 |     "/api/danistay/document/{decision_id}",
 672 |     tags=["Danıştay"],
 673 |     summary="Get Council of State Document (Primary API)",
 674 |     description="""Retrieve complete administrative court decision in Markdown format.
 675 | 
 676 | Content includes:
 677 | • Complete administrative law reasoning and precedent analysis
 678 | • Review of administrative actions and government decisions
 679 | • Citations of administrative laws and regulations
 680 | • Final administrative ruling with legal justification
 681 | 
 682 | Essential for administrative law research and government compliance analysis."""
 683 | )
 684 | async def get_danistay_document(decision_id: str):
 685 |     """Get full Council of State decision text in clean Markdown format."""
 686 |     return await call_mcp_tool("get_danistay_document_markdown", {"id": decision_id})
 687 | 
 688 | @app.get(
 689 |     "/api/danistay/bedesten-document/{document_id}",
 690 |     tags=["Danıştay"],
 691 |     summary="Get Council of State Document (Bedesten API)",
 692 |     description="""Retrieve Council of State decision from Bedesten API in Markdown format."""
 693 | )
 694 | async def get_danistay_bedesten_document(document_id: str):
 695 |     """Get Council of State document from Bedesten API in Markdown format."""
 696 |     return await call_mcp_tool("get_danistay_bedesten_document_markdown", {"documentId": document_id})
 697 | 
 698 | # ============================================================================
 699 | # BEDESTEN API COURTS (LOCAL/APPELLATE/KYB) - 6 TOOLS
 700 | # ============================================================================
 701 | 
 702 | @app.post(
 703 |     "/api/yerel-hukuk/search",
 704 |     tags=["Yerel Hukuk"],
 705 |     summary="Search Local Civil Courts",
 706 |     description="""Search first-instance civil court decisions using Bedesten API.
 707 | 
 708 | Local Civil Courts handle:
 709 | • Contract disputes • Property rights • Family law • Tort claims
 710 | • Commercial disputes • Consumer protection
 711 | 
 712 | Only available tool for local court decisions. Supports exact phrase search
 713 | and date filtering for precise legal research."""
 714 | )
 715 | async def search_yerel_hukuk(request: BedestenSearchRequest):
 716 |     """
 717 |     Searches Yerel Hukuk Mahkemesi (Local Civil Court) decisions using Bedesten API.
 718 |     
 719 |     This provides access to local court decisions that are not available through other APIs.
 720 |     Currently the only available tool for searching Yerel Hukuk Mahkemesi decisions.
 721 |     Local civil courts represent the first instance of civil litigation in Turkey.
 722 | 
 723 |     Local Civil Courts handle:
 724 |     • Contract disputes and commercial litigation
 725 |     • Property rights and real estate disputes
 726 |     • Family law matters (divorce, custody, inheritance)
 727 |     • Tort claims and compensation cases
 728 |     • Consumer protection issues
 729 |     • Employment disputes
 730 |     
 731 |     Returns structured search results with decision metadata. Use get_yerel_hukuk_bedesten_document_markdown()
 732 |     to retrieve full decision texts for detailed analysis.
 733 |     """
 734 |     args = {"phrase": request.phrase, "pageSize": request.pageSize}
 735 |     for field in ["kararTarihiStart", "kararTarihiEnd"]:
 736 |         if getattr(request, field):
 737 |             args[field] = getattr(request, field)
 738 |     return await call_mcp_tool("search_yerel_hukuk_bedesten", args)
 739 | 
 740 | @app.get("/api/yerel-hukuk/document/{document_id}", tags=["Yerel Hukuk"])
 741 | async def get_yerel_hukuk_document(document_id: str):
 742 |     """
 743 |     Retrieves a Yerel Hukuk Mahkemesi decision document from Bedesten API and converts to Markdown.
 744 |     
 745 |     This tool fetches complete local court decision texts using documentId from search results.
 746 |     Perfect for detailed analysis of first-instance civil court rulings.
 747 |     
 748 |     Supports both HTML and PDF content types, automatically converting to clean Markdown format.
 749 |     Use documentId from search_yerel_hukuk_bedesten results.
 750 |     """
 751 |     return await call_mcp_tool("get_yerel_hukuk_bedesten_document_markdown", {"documentId": document_id})
 752 | 
 753 | @app.post(
 754 |     "/api/istinaf-hukuk/search",
 755 |     tags=["İstinaf Hukuk"],
 756 |     summary="Search Civil Courts of Appeals",
 757 |     description="""Search intermediate appellate court decisions using Bedesten API.
 758 | 
 759 | İstinaf Courts are intermediate appellate courts handling appeals from local civil courts
 760 | before cases reach the Court of Cassation. Only available tool for İstinaf decisions."""
 761 | )
 762 | async def search_istinaf_hukuk(request: BedestenSearchRequest):
 763 |     """
 764 |     Searches İstinaf Hukuk Mahkemesi (Civil Court of Appeals) decisions using Bedesten API.
 765 | 
 766 |     İstinaf courts are intermediate appellate courts in the Turkish judicial system that handle
 767 |     appeals from local civil courts before cases reach Yargıtay (Court of Cassation).
 768 |     This is the only available tool for accessing İstinaf Hukuk Mahkemesi decisions.
 769 | 
 770 |     Key Features:
 771 |     • Date range filtering with ISO 8601 format (YYYY-MM-DDTHH:MM:SS.000Z)
 772 |     • Exact phrase search using double quotes: "\"legal term\"" 
 773 |     • Regular search for individual keywords
 774 |     • Pagination support (1-100 results per page)
 775 | 
 776 |     Use cases:
 777 |     • Research appellate court precedents
 778 |     • Track appeals from specific lower courts
 779 |     • Find decisions on specific legal issues at appellate level
 780 |     • Analyze intermediate court reasoning before supreme court review
 781 | 
 782 |     Returns structured data with decision metadata including dates, case numbers, and summaries.
 783 |     Use get_istinaf_hukuk_bedesten_document_markdown() to retrieve full decision texts.
 784 |     """
 785 |     args = {"phrase": request.phrase, "pageSize": request.pageSize}
 786 |     for field in ["kararTarihiStart", "kararTarihiEnd"]:
 787 |         if getattr(request, field):
 788 |             args[field] = getattr(request, field)
 789 |     return await call_mcp_tool("search_istinaf_hukuk_bedesten", args)
 790 | 
 791 | @app.get("/api/istinaf-hukuk/document/{document_id}", tags=["İstinaf Hukuk"])
 792 | async def get_istinaf_hukuk_document(document_id: str):
 793 |     """
 794 |     Retrieves the full text of an İstinaf Hukuk Mahkemesi decision document in Markdown format.
 795 | 
 796 |     This tool converts the original decision document (HTML or PDF) from Bedesten API
 797 |     into clean, readable Markdown format suitable for analysis and processing.
 798 | 
 799 |     Input Requirements:
 800 |     • documentId: Use the ID from search_istinaf_hukuk_bedesten results
 801 |     • Document ID must be non-empty string
 802 | 
 803 |     Output Format:
 804 |     • Clean Markdown text with proper formatting
 805 |     • Preserves legal structure (headers, paragraphs, citations)
 806 |     • Removes extraneous HTML/PDF artifacts
 807 | 
 808 |     Use for:
 809 |     • Reading full appellate court decision texts
 810 |     • Legal analysis of İstinaf court reasoning
 811 |     • Citation extraction and reference building
 812 |     • Content analysis and summarization
 813 |     """
 814 |     return await call_mcp_tool("get_istinaf_hukuk_bedesten_document_markdown", {"documentId": document_id})
 815 | 
 816 | @app.post(
 817 |     "/api/kyb/search",
 818 |     tags=["KYB"],
 819 |     summary="Search Extraordinary Appeals (KYB)",
 820 |     description="""Search Kanun Yararına Bozma (Extraordinary Appeal) decisions.
 821 | 
 822 | KYB is an extraordinary legal remedy where the Public Prosecutor's Office requests
 823 | review of finalized decisions in favor of law and defendants. Very rare but important
 824 | legal precedents. Only available tool for KYB decisions."""
 825 | )
 826 | async def search_kyb(request: BedestenSearchRequest):
 827 |     """
 828 |     Searches Kanun Yararına Bozma (KYB - Extraordinary Appeal) decisions using Bedesten API.
 829 | 
 830 |     KYB is an extraordinary legal remedy in the Turkish judicial system where the
 831 |     Public Prosecutor's Office can request review of finalized decisions in favor of
 832 |     the law and defendants. This is the only available tool for accessing KYB decisions.
 833 | 
 834 |     Key Features:
 835 |     • Date range filtering with ISO 8601 format (YYYY-MM-DDTHH:MM:SS.000Z)
 836 |     • Exact phrase search using double quotes: "\"extraordinary appeal\""
 837 |     • Regular search for individual keywords
 838 |     • Pagination support (1-100 results per page)
 839 | 
 840 |     Legal Significance:
 841 |     • Extraordinary remedy beyond regular appeals
 842 |     • Initiated by Public Prosecutor's Office
 843 |     • Reviews finalized decisions for legal errors
 844 |     • Can benefit defendants retroactively
 845 |     • Rare but important legal precedents
 846 | 
 847 |     Use cases:
 848 |     • Research extraordinary appeal precedents
 849 |     • Study prosecutorial challenges to final decisions
 850 |     • Analyze legal errors in finalized cases
 851 |     • Track KYB success rates and patterns
 852 | 
 853 |     Returns structured data with decision metadata. Use get_kyb_bedesten_document_markdown()
 854 |     to retrieve full decision texts for detailed analysis.
 855 |     """
 856 |     args = {"phrase": request.phrase, "pageSize": request.pageSize}
 857 |     for field in ["kararTarihiStart", "kararTarihiEnd"]:
 858 |         if getattr(request, field):
 859 |             args[field] = getattr(request, field)
 860 |     return await call_mcp_tool("search_kyb_bedesten", args)
 861 | 
 862 | @app.get("/api/kyb/document/{document_id}", tags=["KYB"])
 863 | async def get_kyb_document(document_id: str):
 864 |     """
 865 |     Retrieves the full text of a Kanun Yararına Bozma (KYB) decision document in Markdown format.
 866 | 
 867 |     This tool converts the original extraordinary appeal decision document (HTML or PDF)
 868 |     from Bedesten API into clean, readable Markdown format for analysis.
 869 | 
 870 |     Input Requirements:
 871 |     • documentId: Use the ID from search_kyb_bedesten results
 872 |     • Document ID must be non-empty string
 873 | 
 874 |     Output Format:
 875 |     • Clean Markdown text with legal formatting preserved
 876 |     • Structured content with headers and citations
 877 |     • Removes technical artifacts from source documents
 878 | 
 879 |     Special Value for KYB Documents:
 880 |     • Contains rare extraordinary appeal reasoning
 881 |     • Shows prosecutorial arguments for legal review
 882 |     • Documents correction of finalized legal errors
 883 |     • Provides precedent for similar extraordinary circumstances
 884 | 
 885 |     Use for:
 886 |     • Analyzing extraordinary appeal legal reasoning
 887 |     • Understanding prosecutorial review criteria
 888 |     • Research on legal error correction mechanisms
 889 |     • Studying retroactive benefit applications
 890 |     """
 891 |     return await call_mcp_tool("get_kyb_bedesten_document_markdown", {"documentId": document_id})
 892 | 
 893 | # ============================================================================
 894 | # ADDITIONAL COURTS - 12 TOOLS
 895 | # ============================================================================
 896 | 
 897 | @app.post("/api/emsal/search", tags=["Emsal"], summary="Search UYAP Precedents")
 898 | async def search_emsal(request: EmsalSearchRequest):
 899 |     """
 900 |     Searches for Precedent (Emsal) decisions using detailed criteria.
 901 | 
 902 |     The Precedent (Emsal) database contains precedent decisions from various Turkish courts
 903 |     integrated through the UYAP (National Judiciary Informatics System). This tool provides
 904 |     access to a comprehensive collection of court decisions that serve as legal precedents.
 905 | 
 906 |     Key Features:
 907 |     • Multi-court coverage (BAM, Civil courts, Regional chambers)
 908 |     • Keyword-based search across decision texts
 909 |     • Court-specific filtering for targeted research
 910 |     • Case number filtering (Case No (Esas No) and Decision No (Karar No) with ranges)
 911 |     • Date range filtering with DD.MM.YYYY format
 912 |     • Multiple sorting options and pagination support
 913 | 
 914 |     Court Selection Options:
 915 |     • BAM Civil Courts: Higher regional civil courts
 916 |     • Civil Courts: Local and first-instance civil courts
 917 |     • Regional Civil Chambers: Specialized civil court departments
 918 | 
 919 |     Precedent Research Use Cases:
 920 |     • Find precedent (emsal) decisions across multiple court levels
 921 |     • Research court interpretations of specific legal concepts
 922 |     • Analyze consistent legal reasoning patterns
 923 |     • Study regional variations in legal decisions
 924 |     • Track precedent development over time
 925 |     • Compare decisions from different court types
 926 | 
 927 |     Returns structured precedent data with court information and decision metadata.
 928 |     Use get_emsal_document_markdown() to retrieve full precedent decision texts.
 929 |     """
 930 |     args = {"keyword": request.keyword, "results_per_page": request.results_per_page}
 931 |     if request.decision_year_karar:
 932 |         args["decision_year_karar"] = request.decision_year_karar
 933 |     return await call_mcp_tool("search_emsal_detailed_decisions", args)
 934 | 
 935 | @app.get("/api/emsal/document/{decision_id}", tags=["Emsal"])
 936 | async def get_emsal_document(decision_id: str):
 937 |     """
 938 |     Retrieves the full text of a specific Emsal (UYAP Precedent) decision in Markdown format.
 939 | 
 940 |     This tool fetches complete precedent decision documents from the UYAP system and converts
 941 |     them to clean, readable Markdown format suitable for legal precedent analysis.
 942 | 
 943 |     Input Requirements:
 944 |     • decision_id: Decision ID from search_emsal_detailed_decisions results
 945 |     • ID must be non-empty string from UYAP Emsal database
 946 | 
 947 |     Output Format:
 948 |     • Clean Markdown text with legal precedent structure preserved
 949 |     • Organized sections: court info, case facts, legal reasoning, conclusion
 950 |     • Proper formatting for legal citations and cross-references
 951 |     • Removes technical artifacts from source documents
 952 | 
 953 |     Precedent Decision Content:
 954 |     • Complete court reasoning and legal analysis
 955 |     • Detailed examination of legal principles applied
 956 |     • Citation of relevant laws, regulations, and prior precedents
 957 |     • Final ruling with precedent-setting reasoning
 958 |     • Court-specific interpretations and legal standards
 959 | 
 960 |     Use for legal precedent research, citation building, and comparative legal analysis.
 961 |     """
 962 |     return await call_mcp_tool("get_emsal_document_markdown", {"decision_id": decision_id})
 963 | 
 964 | @app.post("/api/uyusmazlik/search", tags=["Uyuşmazlık"], summary="Search Jurisdictional Disputes")
 965 | async def search_uyusmazlik(request: UyusmazlikSearchRequest):
 966 |     """
 967 |     Searches for Court of Jurisdictional Disputes (Uyuşmazlık Mahkemesi) decisions.
 968 | 
 969 |     The Court of Jurisdictional Disputes (Uyuşmazlık Mahkemesi) resolves jurisdictional disputes between different court systems
 970 |     in Turkey, determining which court has jurisdiction over specific cases. This specialized
 971 |     court handles conflicts between civil, criminal, and administrative jurisdictions.
 972 | 
 973 |     Key Features:
 974 |     • Department filtering (Criminal, Civil, General Assembly decisions)
 975 |     • Dispute type classification (Jurisdiction vs Judgment disputes)
 976 |     • Decision outcome filtering (dispute resolution results)
 977 |     • Case number and date range filtering
 978 |     • Advanced text search with Boolean logic operators
 979 |     • Official Gazette reference search
 980 | 
 981 |     Dispute Types:
 982 |     • Jurisdictional Disputes (Görev Uyuşmazlığı): Which court has authority
 983 |     • Judgment Disputes (Hüküm Uyuşmazlığı): Conflicting final decisions
 984 | 
 985 |     Departments:
 986 |     • Criminal Section (Ceza Bölümü): Criminal section decisions
 987 |     • Civil Section (Hukuk Bölümü): Civil section decisions  
 988 |     • General Assembly Decisions (Genel Kurul Kararları): General Assembly decisions
 989 | 
 990 |     Use cases:
 991 |     • Research jurisdictional precedents
 992 |     • Understand court system boundaries
 993 |     • Analyze dispute resolution patterns
 994 |     • Study inter-court conflict resolution
 995 |     • Legal procedure and jurisdiction research
 996 | 
 997 |     Returns structured search results with dispute resolution information.
 998 |     """
 999 |     return await call_mcp_tool("search_uyusmazlik_decisions", {
1000 |         "keywords": request.keywords,
1001 |         "page_to_fetch": request.page_to_fetch
1002 |     })
1003 | 
1004 | @app.get("/api/uyusmazlik/document", tags=["Uyuşmazlık"])
1005 | async def get_uyusmazlik_document(document_url: str):
1006 |     """
1007 |     Retrieves the full text of a specific Uyuşmazlık Mahkemesi decision from its URL in Markdown format.
1008 | 
1009 |     This tool fetches complete jurisdictional dispute resolution decisions and converts them
1010 |     to clean, readable Markdown format suitable for legal analysis of inter-court disputes.
1011 | 
1012 |     Input Requirements:
1013 |     • document_url: Full URL to the decision document from search_uyusmazlik_decisions results
1014 |     • URL must be valid HttpUrl format from official Uyuşmazlık Mahkemesi database
1015 | 
1016 |     Output Format:
1017 |     • Clean Markdown text with jurisdictional dispute structure preserved
1018 |     • Organized sections: dispute facts, jurisdictional analysis, resolution ruling
1019 |     • Proper formatting for legal citations and court system references
1020 |     • Removes technical artifacts from source documents
1021 | 
1022 |     Jurisdictional Dispute Decision Content:
1023 |     • Complete analysis of jurisdictional conflicts between court systems
1024 |     • Detailed examination of applicable jurisdictional rules
1025 |     • Citation of relevant procedural laws and court organization statutes
1026 |     • Final resolution determining proper court jurisdiction
1027 |     • Reasoning for jurisdictional boundaries and court authority
1028 | 
1029 |     Use for understanding court system boundaries, analyzing jurisdictional precedents,
1030 |     and legal practice guidance on proper court selection.
1031 |     """
1032 |     return await call_mcp_tool("get_uyusmazlik_document_markdown_from_url", {"document_url": document_url})
1033 | 
1034 | @app.post("/api/anayasa/search-norm", tags=["Anayasa"], summary="Search Constitutional Court (Norm Control)")
1035 | async def search_anayasa_norm(request: AnayasaNormSearchRequest):
1036 |     """
1037 |     Searches Constitutional Court (Anayasa Mahkemesi) norm control decisions with comprehensive filtering.
1038 | 
1039 |     The Constitutional Court is Turkey's highest constitutional authority, responsible for judicial
1040 |     review of laws, regulations, and constitutional amendments. Norm control (Norm Denetimi) is the
1041 |     court's power to review the constitutionality of legal norms.
1042 | 
1043 |     Key Features:
1044 |     • Boolean keyword search (AND, OR, NOT logic)
1045 |     • Constitutional period filtering (1961 vs 1982 Constitution)
1046 |     • Case and decision number filtering
1047 |     • Date range filtering for review and decision dates
1048 |     • Application type classification (İptal, İtiraz, etc.)
1049 |     • Applicant filtering (government entities, opposition parties)
1050 |     • Official Gazette publication filtering
1051 |     • Judicial opinion analysis (dissents, different reasoning)
1052 |     • Court member and rapporteur filtering
1053 |     • Norm type classification (laws, regulations, decrees)
1054 |     • Review outcome filtering (constitutionality determinations)
1055 |     • Constitutional basis article referencing
1056 | 
1057 |     Constitutional Review Types:
1058 |     • Abstract review: Ex ante constitutional control
1059 |     • Concrete review: Constitutional questions during litigation
1060 |     • Legislative review: Parliamentary acts and government decrees
1061 |     • Regulatory review: Administrative regulations and bylaws
1062 | 
1063 |     Use cases:
1064 |     • Constitutional law research and analysis
1065 |     • Legislative drafting constitutional compliance
1066 |     • Academic constitutional law study
1067 |     • Legal precedent analysis for constitutional questions
1068 |     • Government policy constitutional assessment
1069 | 
1070 |     Returns structured constitutional court data with comprehensive metadata.
1071 |     """
1072 |     args = {"keywords_all": request.keywords_all, "results_per_page": request.results_per_page}
1073 |     for field in ["period", "application_type"]:
1074 |         if getattr(request, field):
1075 |             args[field] = getattr(request, field)
1076 |     return await call_mcp_tool("search_anayasa_norm_denetimi_decisions", args)
1077 | 
1078 | @app.get("/api/anayasa/norm-document", tags=["Anayasa"])
1079 | async def get_anayasa_norm_document(document_url: str, page_number: int = 1):
1080 |     """Get Constitutional Court norm control decision in paginated Markdown format."""
1081 |     return await call_mcp_tool("get_anayasa_norm_denetimi_document_markdown", {
1082 |         "document_url": document_url, "page_number": page_number
1083 |     })
1084 | 
1085 | @app.post("/api/anayasa/search-bireysel", tags=["Anayasa"], summary="Search Constitutional Court (Individual Applications)")
1086 | async def search_anayasa_bireysel(request: AnayasaBireyselSearchRequest):
1087 |     """
1088 |     Search Constitutional Court individual application (Bireysel Başvuru) decisions for human rights violation reports with keyword filtering.
1089 |     
1090 |     Individual applications allow citizens to petition the Constitutional Court directly for
1091 |     violations of fundamental rights and freedoms. This tool generates decision search reports
1092 |     that help identify relevant human rights violation cases.
1093 |     
1094 |     Key Features:
1095 |     • Keyword-based search with AND logic
1096 |     • Human rights violation case identification
1097 |     • Individual petition decision analysis
1098 |     • Fundamental rights and freedoms research
1099 |     • Pagination support for large result sets
1100 |     
1101 |     Individual Application System:
1102 |     • Direct citizen access to Constitutional Court
1103 |     • Human rights and fundamental freedoms protection
1104 |     • Alternative to European Court of Human Rights
1105 |     • Domestic remedy for constitutional violations
1106 |     • Individual justice and rights enforcement
1107 |     
1108 |     Human Rights Categories:
1109 |     • Right to life and personal liberty
1110 |     • Right to fair trial and due process
1111 |     • Freedom of expression and press
1112 |     • Freedom of religion and conscience
1113 |     • Property rights and economic freedoms
1114 |     • Right to privacy and family life
1115 |     • Political rights and democratic participation
1116 |     
1117 |     Use cases:
1118 |     • Human rights violation research
1119 |     • Individual petition precedent analysis
1120 |     • Constitutional rights interpretation study
1121 |     • Legal remedies for rights violations
1122 |     • Academic human rights law research
1123 |     • Civil society and NGO legal research
1124 |     
1125 |     Returns search report with case summaries and violation categories.
1126 |     Use get_anayasa_bireysel_document for full decision texts.
1127 |     """
1128 |     return await call_mcp_tool("search_anayasa_bireysel_basvuru_report", {
1129 |         "keywords": request.keywords, "page_to_fetch": request.page_to_fetch
1130 |     })
1131 | 
1132 | @app.get("/api/anayasa/bireysel-document", tags=["Anayasa"])
1133 | async def get_anayasa_bireysel_document(document_url: str, page_number: int = 1):
1134 |     """
1135 |     Retrieve the full text of a Constitutional Court individual application decision in paginated Markdown format.
1136 |     
1137 |     This tool fetches complete human rights violation decisions from individual applications
1138 |     and converts them to clean, readable Markdown format. Content is paginated into
1139 |     5,000-character chunks for easier processing.
1140 |     
1141 |     Input Requirements:
1142 |     • document_url: URL path (e.g., /BB/YYYY/NNNN) from search results
1143 |     • page_number: Page number for pagination (1-indexed, default: 1)
1144 |     
1145 |     Output Format:
1146 |     • Clean Markdown text with human rights case structure preserved
1147 |     • Organized sections: applicant info, violation claims, court analysis, ruling
1148 |     • Proper formatting for human rights law citations and references
1149 |     • Paginated content with navigation information
1150 |     
1151 |     Individual Application Decision Content:
1152 |     • Complete human rights violation analysis
1153 |     • Detailed examination of fundamental rights claims
1154 |     • Citation of constitutional articles and international human rights law
1155 |     • Final determination on rights violations with remedies
1156 |     • Analysis of domestic court proceedings and their adequacy
1157 |     • Individual remedy recommendations and compensation
1158 |     
1159 |     Use for:
1160 |     • Reading full human rights violation decisions
1161 |     • Human rights law research and precedent analysis
1162 |     • Understanding constitutional rights protection standards
1163 |     • Individual petition strategy development
1164 |     • Academic human rights and constitutional law study
1165 |     • Civil society monitoring of rights violations
1166 |     """
1167 |     return await call_mcp_tool("get_anayasa_bireysel_basvuru_document_markdown", {
1168 |         "document_url": document_url, "page_number": page_number
1169 |     })
1170 | 
1171 | @app.post("/api/kik/search", tags=["KİK"], summary="Search Public Procurement Authority")
1172 | async def search_kik(request: KikSearchRequest):
1173 |     """
1174 |     Search Public Procurement Authority (Kamu İhale Kurulu - KIK) decisions with comprehensive filtering for public procurement law and administrative dispute research.
1175 |     
1176 |     The Public Procurement Authority (KIK) is Turkey's procurement oversight body, responsible for
1177 |     regulating public procurement processes, resolving procurement disputes, and issuing interpretive
1178 |     decisions on public contracting laws. This tool provides access to official procurement decisions
1179 |     and regulatory guidance.
1180 |     
1181 |     Key Features:
1182 |     • Decision type filtering (Disputes, Regulatory, Court decisions)
1183 |     • Decision date range filtering for temporal analysis
1184 |     • Applicant and procuring entity filtering
1185 |     • Tender subject and content-based search
1186 |     • Decision number and reference tracking
1187 |     • Comprehensive metadata extraction
1188 |     
1189 |     Public Procurement Decision Types:
1190 |     • Uyuşmazlık Kararları: Dispute resolution decisions
1191 |     • Düzenleyici Kararlar: Regulatory and interpretive decisions
1192 |     • Mahkeme Kararları: Court decisions and judicial precedents
1193 |     
1194 |     Procurement Law Areas:
1195 |     • Tender procedure compliance and violations
1196 |     • Bid evaluation and award criteria disputes
1197 |     • Contractor qualification and eligibility
1198 |     • Contract modification and scope changes
1199 |     • Performance guarantees and penalty applications
1200 |     • Public procurement ethics and transparency
1201 |     • Emergency procurement and exceptional procedures
1202 |     
1203 |     Use cases:
1204 |     • Public procurement law research and compliance guidance
1205 |     • Tender dispute resolution precedent analysis
1206 |     • Government contracting risk assessment
1207 |     • Procurement policy and regulatory interpretation
1208 |     • Academic public administration and law study
1209 |     • Legal strategy development for procurement disputes
1210 |     
1211 |     Returns structured procurement authority data with comprehensive case metadata.
1212 |     Use get_kik_document for full decision texts with detailed reasoning.
1213 |     """
1214 |     args = {}
1215 |     for field in ["karar_tipi", "karar_metni", "basvuru_konusu_ihale", "karar_tarihi_baslangic"]:
1216 |         if getattr(request, field):
1217 |             args[field] = getattr(request, field)
1218 |     return await call_mcp_tool("search_kik_decisions", args)
1219 | 
1220 | @app.get("/api/kik/document/{decision_id}", tags=["KİK"])
1221 | async def get_kik_document(decision_id: str):
1222 |     """
1223 |     Retrieve the full text of a Public Procurement Authority (KIK) decision in paginated Markdown format.
1224 |     
1225 |     This tool fetches complete public procurement decisions and converts them from PDF to clean,
1226 |     readable Markdown format. Content is paginated into manageable chunks for processing lengthy
1227 |     procurement law decisions and regulatory interpretations.
1228 |     
1229 |     Input Requirements:
1230 |     • decision_id: KIK decision ID (base64 encoded karar_id) from search results
1231 |     • Decision ID must be non-empty string
1232 |     
1233 |     Output Format:
1234 |     • Clean Markdown text converted from original PDF documents
1235 |     • Organized sections: case summary, legal analysis, regulatory interpretation, decision
1236 |     • Proper formatting for procurement law citations and regulatory references
1237 |     • Paginated content with navigation information
1238 |     • Metadata including PDF source link and document information
1239 |     
1240 |     Public Procurement Decision Content:
1241 |     • Complete procurement dispute analysis and resolution
1242 |     • Detailed examination of tender procedures and compliance
1243 |     • Citation of procurement laws, regulations, and precedents
1244 |     • Final determination on procurement violations with corrective measures
1245 |     • Regulatory guidance and policy interpretations
1246 |     • Contractor liability and penalty determinations
1247 |     
1248 |     Use for:
1249 |     • Reading full public procurement authority decisions
1250 |     • Procurement law research and precedent analysis
1251 |     • Government contracting compliance and risk assessment
1252 |     • Tender dispute resolution strategy development
1253 |     • Academic public administration and procurement law study
1254 |     • Policy analysis and regulatory interpretation
1255 |     """
1256 |     return await call_mcp_tool("get_kik_document_markdown", {"decision_id": decision_id})
1257 | 
1258 | @app.post("/api/rekabet/search", tags=["Rekabet"], summary="Search Competition Authority")
1259 | async def search_rekabet(request: RekabetSearchRequest):
1260 |     """
1261 |     Search Competition Authority (Rekabet Kurumu) decisions with comprehensive filtering for competition law and antitrust research.
1262 |     
1263 |     The Competition Authority (Rekabet Kurumu) is Turkey's competition authority, responsible for enforcing antitrust laws,
1264 |     preventing anti-competitive practices, and regulating mergers and acquisitions. This tool
1265 |     provides access to official competition law decisions and regulatory interpretations.
1266 |     
1267 |     Key Features:
1268 |     • Decision type filtering (Mergers, Violations, Exemptions, etc.)
1269 |     • Title and content-based text search with exact phrase matching
1270 |     • Publication date filtering
1271 |     • Case year and decision number filtering
1272 |     • Pagination support for large result sets
1273 |     
1274 |     Competition Law Decision Types:
1275 |     • Birleşme ve Devralma: Merger and acquisition approvals
1276 |     • Rekabet İhlali: Competition violation investigations
1277 |     • Muafiyet: Exemption and negative clearance decisions
1278 |     • Geçici Tedbir: Interim measures and emergency orders
1279 |     • Sektör İncelemesi: Sector inquiry and market studies
1280 |     • Diğer: Other regulatory and interpretive decisions
1281 |     
1282 |     Competition Law Areas:
1283 |     • Anti-competitive agreements and cartels
1284 |     • Abuse of dominant market position
1285 |     • Merger control and market concentration
1286 |     • Vertical agreements and distribution restrictions
1287 |     • Unfair competition and consumer protection
1288 |     • Market definition and economic analysis
1289 |     
1290 |     Advanced Search:
1291 |     • Exact phrase matching with double quotes for precise legal terms
1292 |     • Content search across full decision texts (PdfText parameter)
1293 |     • Title search for specific case names or topics
1294 |     • Date range filtering for temporal analysis
1295 |     
1296 |     Example for exact phrase search: PdfText=\"tender process\" consultancy
1297 |     
1298 |     Use cases:
1299 |     • Competition law research and precedent analysis
1300 |     • Merger and acquisition due diligence
1301 |     • Antitrust compliance and risk assessment
1302 |     • Market analysis and competitive intelligence
1303 |     • Academic competition economics study
1304 |     • Legal strategy development for competition cases
1305 |     
1306 |     Returns structured competition authority data with comprehensive metadata.
1307 |     Use get_rekabet_document for full decision texts (paginated PDF conversion).
1308 |     """
1309 |     args = {"page": request.page}
1310 |     for field in ["KararTuru", "PdfText", "YayinlanmaTarihi"]:
1311 |         if getattr(request, field):
1312 |             args[field] = getattr(request, field)
1313 |     return await call_mcp_tool("search_rekabet_kurumu_decisions", args)
1314 | 
1315 | @app.get("/api/rekabet/document/{karar_id}", tags=["Rekabet"])
1316 | async def get_rekabet_document(karar_id: str, page_number: int = 1):
1317 |     """
1318 |     Retrieve the full text of a Competition Authority (Rekabet Kurumu) decision in paginated Markdown format converted from PDF.
1319 |     
1320 |     This tool fetches complete competition authority decisions and converts them from PDF to clean,
1321 |     readable Markdown format. Content is paginated for easier processing of lengthy competition law decisions.
1322 |     
1323 |     Input Requirements:
1324 |     • karar_id: GUID (kararId) from search_rekabet_kurumu_decisions results
1325 |     • page_number: Page number for pagination (1-indexed, default: 1)
1326 |     
1327 |     Output Format:
1328 |     • Clean Markdown text converted from original PDF documents
1329 |     • Organized sections: case summary, market analysis, legal reasoning, decision
1330 |     • Proper formatting for competition law citations and references
1331 |     • Paginated content with navigation information
1332 |     • Metadata including PDF source link and document information
1333 |     
1334 |     Competition Authority Decision Content:
1335 |     • Complete competition law analysis and market assessment
1336 |     • Detailed examination of anti-competitive practices
1337 |     • Economic analysis and market definition studies
1338 |     • Citation of competition laws, regulations, and precedents
1339 |     • Final determination on competition violations with remedies
1340 |     • Merger and acquisition approval conditions
1341 |     • Regulatory guidance and policy interpretations
1342 |     
1343 |     Use for:
1344 |     • Reading full competition authority decisions
1345 |     • Competition law research and precedent analysis
1346 |     • Market analysis and economic impact assessment
1347 |     • Antitrust compliance and risk evaluation
1348 |     • Academic competition economics and law study
1349 |     • Legal strategy development for competition cases
1350 |     """
1351 |     return await call_mcp_tool("get_rekabet_kurumu_document", {
1352 |         "karar_id": karar_id, "page_number": page_number
1353 |     })
1354 | 
1355 | # ============================================================================
1356 | # SAYISTAY (COURT OF ACCOUNTS) ENDPOINTS - 6 TOOLS
1357 | # ============================================================================
1358 | 
1359 | @app.post("/api/sayistay/search-genel-kurul", tags=["Sayıştay"], summary="Search Court of Accounts (General Assembly)")
1360 | async def search_sayistay_genel_kurul(request: SayistaySearchRequest):
1361 |     """
1362 |     Search Sayıştay Genel Kurul (General Assembly) decisions - highest-level audit precedents and interpretive rulings with keyword-based filtering.
1363 |     
1364 |     The General Assembly represents the highest decision-making body of Turkey's Court of Accounts,
1365 |     issuing authoritative interpretations of audit laws, precedential rulings on complex accountability
1366 |     issues, and binding guidance for audit practice. These decisions establish fundamental principles
1367 |     for public financial oversight and accountability standards.
1368 |     
1369 |     Key Features:
1370 |     • Keyword-based search with AND logic for precise case finding
1371 |     • Highest-level audit precedent identification
1372 |     • Interpretive ruling analysis and legal guidance extraction
1373 |     • Complex accountability issue resolution tracking
1374 |     • Pagination support for comprehensive result sets
1375 |     
1376 |     General Assembly Decision Authority:
1377 |     • Ultimate audit law interpretation and clarification
1378 |     • Precedential rulings binding on all audit chambers
1379 |     • Complex inter-chamber jurisdiction dispute resolution
1380 |     • Policy guidance for audit methodology and standards
1381 |     • Final determination on constitutional audit questions
1382 |     
1383 |     Public Audit Areas:
1384 |     • Government budget execution and compliance
1385 |     • Public institution financial management
1386 |     • State-owned enterprise oversight and accountability
1387 |     • Local government and municipal audit standards
1388 |     • Public procurement oversight and compliance monitoring
1389 |     • Performance audit methodology and effectiveness standards
1390 |     • Public revenue collection and tax administration audit
1391 |     
1392 |     Use Cases:
1393 |     • Research authoritative audit law interpretations
1394 |     • Find binding precedents for complex audit questions
1395 |     • Study evolution of public accountability standards
1396 |     • Analyze audit methodology development and refinement
1397 |     • Academic public administration and audit research
1398 |     • Government policy and accountability framework analysis
1399 |     
1400 |     Returns structured General Assembly data with comprehensive legal precedent metadata.
1401 |     Use get_sayistay_genel_kurul_document for full decision texts with detailed reasoning.
1402 |     """
1403 |     return await call_mcp_tool("search_sayistay_genel_kurul", {
1404 |         "keywords": request.keywords, "page_to_fetch": request.page_to_fetch
1405 |     })
1406 | 
1407 | @app.get("/api/sayistay/genel-kurul-document", tags=["Sayıştay"])
1408 | async def get_sayistay_genel_kurul_document(document_url: str, page_number: int = 1):
1409 |     """
1410 |     Retrieve the full text of a Sayıştay Genel Kurul decision document in Markdown format for detailed analysis.
1411 |     
1412 |     This tool converts the original General Assembly decision document into clean,
1413 |     readable Markdown format suitable for legal analysis and research.
1414 |     
1415 |     Input Requirements:
1416 |     • decision_id: Use the ID from search_sayistay_genel_kurul results
1417 |     • Decision ID must be non-empty string
1418 |     
1419 |     Output Format:
1420 |     • Clean Markdown text with legal formatting preserved
1421 |     • Structured content with reasoning and conclusions
1422 |     • Removes technical artifacts from source documents
1423 |     
1424 |     Use for:
1425 |     • Detailed analysis of audit precedents
1426 |     • Research on public accountability standards
1427 |     • Citation and reference building
1428 |     • Legal interpretation and case study development
1429 |     """
1430 |     return await call_mcp_tool("get_sayistay_genel_kurul_document_markdown", {
1431 |         "document_url": document_url, "page_number": page_number
1432 |     })
1433 | 
1434 | @app.post("/api/sayistay/search-temyiz-kurulu", tags=["Sayıştay"], summary="Search Court of Accounts (Appeals Board)")
1435 | async def search_sayistay_temyiz_kurulu(request: SayistaySearchRequest):
1436 |     """
1437 |     Search Sayıştay Temyiz Kurulu (Appeals Board) decisions - appellate review of audit chamber findings with advanced filtering and institutional analysis.
1438 |     
1439 |     The Appeals Board serves as the intermediate appellate authority in Turkey's audit system,
1440 |     reviewing first-instance chamber decisions on audit findings, liability determinations,
1441 |     and sanctions. Appeals Board decisions refine audit standards and ensure consistency
1442 |     across different audit chambers.
1443 |     
1444 |     Key Features:
1445 |     • Chamber-specific filtering for targeted appeals analysis
1446 |     • Institutional type categorization for audit pattern analysis
1447 |     • Decision and account year filtering for temporal trends
1448 |     • Audit subject matter classification and content search
1449 |     • Appeal outcome tracking and precedent identification
1450 |     • Pagination support for comprehensive coverage
1451 |     
1452 |     Appeals Board Authority:
1453 |     • Review and modification of chamber audit findings
1454 |     • Standardization of audit liability determinations
1455 |     • Consistency enforcement across audit chambers
1456 |     • Intermediate precedent development for audit practice
1457 |     • Quality control for first-instance audit decisions
1458 |     
1459 |     Audit Review Areas:
1460 |     • Government agency financial accountability appeals
1461 |     • Municipality and local government audit review
1462 |     • State enterprise oversight and performance audit appeals
1463 |     • Educational institution audit finding review
1464 |     • Healthcare system financial accountability appeals
1465 |     • Public procurement oversight and compliance review
1466 |     • Tax administration and revenue audit appeals
1467 |     
1468 |     Use Cases:
1469 |     • Research audit appeals patterns and outcomes
1470 |     • Study chamber decision consistency and standards
1471 |     • Analyze audit liability determination evolution
1472 |     • Find precedents for specific audit finding types
1473 |     • Track institutional audit patterns and compliance
1474 |     • Academic public accountability and audit law research
1475 |     
1476 |     Returns structured Appeals Board data with comprehensive appellate analysis metadata.
1477 |     Use get_sayistay_temyiz_kurulu_document for full appeals decisions with detailed reasoning.
1478 |     """
1479 |     return await call_mcp_tool("search_sayistay_temyiz_kurulu", {
1480 |         "keywords": request.keywords, "page_to_fetch": request.page_to_fetch
1481 |     })
1482 | 
1483 | @app.get("/api/sayistay/temyiz-kurulu-document", tags=["Sayıştay"])
1484 | async def get_sayistay_temyiz_kurulu_document(document_url: str, page_number: int = 1):
1485 |     """
1486 |     Retrieve the full text of a Sayıştay Temyiz Kurulu decision document in Markdown format for detailed appeals analysis.
1487 |     
1488 |     This tool converts the original Appeals Board decision document into clean,
1489 |     readable Markdown format for analysis of appellate reasoning and standards.
1490 |     
1491 |     Input Requirements:
1492 |     • decision_id: Use the ID from search_sayistay_temyiz_kurulu results
1493 |     • Decision ID must be non-empty string
1494 |     
1495 |     Output Format:
1496 |     • Clean Markdown text with appellate reasoning preserved
1497 |     • Structured content with original findings and appeals analysis
1498 |     • Removes technical artifacts from source documents
1499 |     
1500 |     Use for:
1501 |     • Analysis of appeals board reasoning and standards
1502 |     • Research on audit liability determination evolution
1503 |     • Understanding chamber decision review criteria
1504 |     • Precedent analysis for audit appeal cases
1505 |     """
1506 |     return await call_mcp_tool("get_sayistay_temyiz_kurulu_document_markdown", {
1507 |         "document_url": document_url, "page_number": page_number
1508 |     })
1509 | 
1510 | @app.post("/api/sayistay/search-daire", tags=["Sayıştay"], summary="Search Court of Accounts (Chambers)")
1511 | async def search_sayistay_daire(request: SayistaySearchRequest):
1512 |     """
1513 |     Search Sayıştay Daire (Chamber) decisions - first-instance audit findings and sanctions from individual audit chambers with comprehensive filtering and subject categorization.
1514 |     
1515 |     Chamber decisions represent first-instance audit findings, sanctions, and
1516 |     liability determinations issued by specialized audit chambers. These form
1517 |     the foundation of Turkey's public financial accountability system.
1518 |     
1519 |     Key Features:
1520 |     • Chamber-specific filtering (8 specialized audit chambers)
1521 |     • Decision and account year filtering (2012-2025)
1522 |     • Public administration type categorization
1523 |     • Subject matter classification and full-text search
1524 |     • Audit report tracking and institutional analysis
1525 |     
1526 |     Use Cases:
1527 |     • Research specific audit findings and sanctions
1528 |     • Study chamber specialization and jurisdiction
1529 |     • Analyze audit patterns by institution type
1530 |     • Find precedents for financial irregularities
1531 |     • Track audit evolution across fiscal years
1532 |     """
1533 |     return await call_mcp_tool("search_sayistay_daire", {
1534 |         "keywords": request.keywords, "page_to_fetch": request.page_to_fetch
1535 |     })
1536 | 
1537 | @app.get("/api/sayistay/daire-document", tags=["Sayıştay"])
1538 | async def get_sayistay_daire_document(document_url: str, page_number: int = 1):
1539 |     """
1540 |     Retrieve the full text of a Sayıştay Daire decision document in Markdown format for detailed audit findings analysis.
1541 |     
1542 |     This tool converts the original chamber decision document into clean,
1543 |     readable Markdown format for analysis of first-instance audit findings.
1544 |     
1545 |     Input Requirements:
1546 |     • decision_id: Use the ID from search_sayistay_daire results  
1547 |     • Decision ID must be non-empty string
1548 |     
1549 |     Output Format:
1550 |     • Clean Markdown text with audit findings preserved
1551 |     • Structured content with violations and sanctions
1552 |     • Removes technical artifacts from source documents
1553 |     
1554 |     Use for:
1555 |     • Detailed analysis of audit findings and methodology
1556 |     • Research on specific types of financial irregularities
1557 |     • Understanding chamber jurisdiction and specialization
1558 |     • Case study development for audit training and compliance
1559 |     """
1560 |     return await call_mcp_tool("get_sayistay_daire_document_markdown", {
1561 |         "document_url": document_url, "page_number": page_number
1562 |     })
1563 | 
1564 | # ============================================================================
1565 | # ADDITIONAL API ENDPOINTS
1566 | # ============================================================================
1567 | 
1568 | @app.get("/api/databases")
1569 | async def list_databases():
1570 |     """Comprehensive database information with tool mappings"""
1571 |     return {
1572 |         "total_tools": 33,
1573 |         "databases": {
1574 |             "yargitay": {
1575 |                 "name": "Yargıtay (Court of Cassation)",
1576 |                 "description": "Turkey's Supreme Court for civil and criminal matters",
1577 |                 "tools": 4,
1578 |                 "chambers": 52,
1579 |                 "search_tools": ["search_yargitay", "search_yargitay_bedesten"],
1580 |                 "document_tools": ["get_yargitay_document", "get_yargitay_bedesten_document"]
1581 |             },
1582 |             "danistay": {
1583 |                 "name": "Danıştay (Council of State)", 
1584 |                 "description": "Turkey's Supreme Administrative Court",
1585 |                 "tools": 5,
1586 |                 "chambers": 27,
1587 |                 "search_tools": ["search_danistay_keyword", "search_danistay_detailed", "search_danistay_bedesten"],
1588 |                 "document_tools": ["get_danistay_document", "get_danistay_bedesten_document"]
1589 |             },
1590 |             "anayasa": {
1591 |                 "name": "Anayasa Mahkemesi (Constitutional Court)",
1592 |                 "description": "Constitutional review and individual applications",
1593 |                 "tools": 4,
1594 |                 "features": ["norm_control", "individual_applications", "human_rights"]
1595 |             },
1596 |             "rekabet": {
1597 |                 "name": "Rekabet Kurumu (Competition Authority)",
1598 |                 "description": "Antitrust and merger control",
1599 |                 "tools": 2,
1600 |                 "coverage": ["mergers", "cartels", "market_abuse", "sector_inquiries"]
1601 |             },
1602 |             "kik": {
1603 |                 "name": "Kamu İhale Kurulu (Public Procurement Authority)",
1604 |                 "description": "Government procurement disputes",
1605 |                 "tools": 2,
1606 |                 "coverage": ["procurement_disputes", "regulatory_decisions", "tender_violations"]
1607 |             },
1608 |             "sayistay": {
1609 |                 "name": "Sayıştay (Court of Accounts)",
1610 |                 "description": "Public audit and financial accountability", 
1611 |                 "tools": 6,
1612 |                 "levels": ["general_assembly", "appeals_board", "audit_chambers"]
1613 |             },
1614 |             "emsal": {
1615 |                 "name": "Emsal (UYAP Precedents)",
1616 |                 "description": "Cross-court precedent database",
1617 |                 "tools": 2,
1618 |                 "coverage": ["multi_court", "precedent_analysis"]
1619 |             },
1620 |             "uyusmazlik": {
1621 |                 "name": "Uyuşmazlık Mahkemesi (Jurisdictional Disputes)",
1622 |                 "description": "Inter-court jurisdiction disputes",
1623 |                 "tools": 2,
1624 |                 "specialization": "jurisdictional_conflicts"
1625 |             },
1626 |             "bedesten_courts": {
1627 |                 "name": "Bedesten API Courts (Local/Appellate/KYB)",
1628 |                 "description": "First instance, appellate, and extraordinary appeal courts",
1629 |                 "tools": 6,
1630 |                 "courts": ["yerel_hukuk", "istinaf_hukuk", "kyb"],
1631 |                 "coverage": "complete_court_hierarchy"
1632 |             }
1633 |         }
1634 |     }
1635 | 
1636 | @app.get("/api/stats")
1637 | async def get_statistics():
1638 |     """Comprehensive API statistics and capabilities"""
1639 |     uptime = (datetime.now() - SERVER_START_TIME).total_seconds()
1640 |     return {
1641 |         "server": {
1642 |             "uptime_seconds": uptime,
1643 |             "start_time": SERVER_START_TIME.isoformat(),
1644 |             "version": "1.0.0",
1645 |             "status": "operational"
1646 |         },
1647 |         "coverage": {
1648 |             "total_tools": 33,
1649 |             "total_databases": 9,
1650 |             "total_chambers": 79,  # 52 Yargıtay + 27 Danıştay
1651 |             "search_tools": 16,
1652 |             "document_tools": 17
1653 |         },
1654 |         "capabilities": {
1655 |             "advanced_search_operators": True,
1656 |             "exact_phrase_search": True,
1657 |             "date_range_filtering": True,
1658 |             "chamber_filtering": True,
1659 |             "boolean_logic": True,
1660 |             "wildcard_search": True,
1661 |             "pagination": True,
1662 |             "markdown_conversion": True,
1663 |             "pdf_processing": True,
1664 |             "dual_api_support": True
1665 |         },
1666 |         "legal_coverage": {
1667 |             "supreme_courts": ["Yargıtay", "Danıştay"],
1668 |             "constitutional_law": "Anayasa Mahkemesi",
1669 |             "administrative_law": "Full coverage",
1670 |             "competition_law": "Rekabet Kurumu",
1671 |             "public_procurement": "KİK",
1672 |             "public_audit": "Sayıştay",
1673 |             "court_hierarchy": "Complete (Local → Appellate → Supreme)",
1674 |             "specialized_courts": ["Uyuşmazlık", "Constitutional", "Administrative"]
1675 |         }
1676 |     }
1677 | 
1678 | if __name__ == "__main__":
1679 |     import uvicorn
1680 |     uvicorn.run(app, host="0.0.0.0", port=8000)
1681 | 
```

--------------------------------------------------------------------------------
/saidsurucu-yargi-mcp-f5fa007/example_fastapi_app.py:
--------------------------------------------------------------------------------

```python
   1 | """
   2 | FastAPI Comprehensive Endpoints with Complete MCP Documentation
   3 | This is the complete version with all descriptions and docstrings from MCP server.
   4 | """
   5 | 
   6 | import os
   7 | from typing import List, Dict, Any, Optional
   8 | from datetime import datetime
   9 | 
  10 | from fastapi import FastAPI, HTTPException, Query, Depends, Body
  11 | from fastapi.middleware.cors import CORSMiddleware
  12 | from fastapi.responses import JSONResponse
  13 | from pydantic import BaseModel, Field
  14 | import json
  15 | 
  16 | # Import the main MCP app
  17 | from mcp_server_main import app as mcp_server
  18 | 
  19 | # Create MCP ASGI app
  20 | mcp_asgi_app = mcp_server.http_app(path="/mcp")
  21 | 
  22 | # Create FastAPI app with MCP lifespan
  23 | app = FastAPI(
  24 |     title="Yargı MCP API - Turkish Legal Database REST API",
  25 |     description="""
  26 |     Comprehensive REST API for Turkish Legal Databases with complete MCP tool coverage.
  27 |     
  28 |     This API provides access to 8 major Turkish legal institutions including:
  29 |     • Yargıtay (Court of Cassation) - Supreme civil/criminal court
  30 |     • Danıştay (Council of State) - Supreme administrative court  
  31 |     • Constitutional Court - Constitutional review and individual applications
  32 |     • Competition Authority - Antitrust and merger decisions
  33 |     • Public Procurement Authority - Government contracting disputes
  34 |     • Court of Accounts - Public audit and accountability
  35 |     • Emsal (UYAP Precedents) - Cross-court precedent database
  36 |     • Local and Appellate Courts - First and second instance decisions
  37 |     
  38 |     Features complete coverage of 33 MCP tools with enhanced documentation,
  39 |     typed request models, and comprehensive legal context.
  40 |     
  41 |     Tool Properties (from MCP annotations):
  42 |     • Read-only: All tools are read-only and do not modify system state
  43 |     • Idempotent: Same inputs produce same outputs for reliable research
  44 |     • Open-world search: Search tools explore comprehensive legal databases
  45 |     • Deterministic document retrieval: Document tools return consistent content
  46 |     """,
  47 |     version="1.0.0",
  48 |     lifespan=mcp_asgi_app.lifespan
  49 | )
  50 | 
  51 | # Add CORS middleware
  52 | cors_origins = os.getenv("ALLOWED_ORIGINS", "*").split(",")
  53 | app.add_middleware(
  54 |     CORSMiddleware,
  55 |     allow_origins=cors_origins,
  56 |     allow_credentials=True,
  57 |     allow_methods=["*"],
  58 |     allow_headers=["*"],
  59 | )
  60 | 
  61 | # Mount MCP server
  62 | app.mount("/mcp-server", mcp_asgi_app)
  63 | 
  64 | # Response models (keeping from original)
  65 | class ToolInfo(BaseModel):
  66 |     name: str
  67 |     description: str
  68 |     parameters: Dict[str, Any]
  69 | 
  70 | class ServerInfo(BaseModel):
  71 |     name: str
  72 |     version: str
  73 |     description: str
  74 |     tools_count: int
  75 |     databases: List[str]
  76 |     mcp_endpoint: str
  77 |     api_docs: str
  78 | 
  79 | class HealthCheck(BaseModel):
  80 |     status: str
  81 |     timestamp: datetime
  82 |     uptime_seconds: Optional[float] = None
  83 |     tools_operational: bool
  84 | 
  85 | # Track server start time
  86 | SERVER_START_TIME = datetime.now()
  87 | 
  88 | # MCP tool caller helper
  89 | async def call_mcp_tool(tool_name: str, arguments: Dict[str, Any]):
  90 |     """Call an MCP tool with given arguments"""
  91 |     try:
  92 |         tool = mcp_server._tool_manager._tools.get(tool_name)
  93 |         if not tool:
  94 |             raise HTTPException(status_code=404, detail=f"Tool '{tool_name}' not found")
  95 |         result = await tool.fn(**arguments)
  96 |         return result
  97 |     except Exception as e:
  98 |         raise HTTPException(status_code=500, detail=f"Tool execution failed: {str(e)}")
  99 | 
 100 | # ============================================================================
 101 | # COMPREHENSIVE REQUEST MODELS WITH FULL MCP DOCUMENTATION
 102 | # ============================================================================
 103 | 
 104 | class YargitaySearchRequest(BaseModel):
 105 |     """
 106 |     Search request for Court of Cassation (Yargıtay) decisions using primary official API.
 107 |     
 108 |     The Court of Cassation is Turkey's highest court for civil and criminal matters,
 109 |     equivalent to a Supreme Court. Provides access to comprehensive supreme court precedents.
 110 |     """
 111 |     arananKelime: str = Field(
 112 |         ..., 
 113 |         description="""Keyword to search for with advanced operators:
 114 |         • Space between words = OR logic (arsa payı → "arsa" OR "payı")
 115 |         • "exact phrase" = Exact match ("arsa payı" → exact phrase)
 116 |         • word1+word2 = AND logic (arsa+payı → both words required)
 117 |         • word* = Wildcard (bozma* → bozma, bozması, bozmanın, etc.)
 118 |         • +"phrase1" +"phrase2" = Multiple required phrases
 119 |         • +"required" -"excluded" = Include and exclude
 120 |         
 121 |         Turkish Examples:
 122 |         • Simple OR: arsa payı (~523K results)
 123 |         • Exact phrase: "arsa payı" (~22K results)
 124 |         • Multiple AND: +"arsa payı" +"bozma sebebi" (~234 results)
 125 |         • Wildcard: bozma* (bozma, bozması, bozmanın, etc.)
 126 |         • Exclude: +"arsa payı" -"kira sözleşmesi"
 127 |         """,
 128 |         example='+"mülkiyet hakkı" +"iptal"'
 129 |     )
 130 |     birimYrgKurulDaire: Optional[str] = Field(
 131 |         "", 
 132 |         description="""Chamber/board selection (52 options):
 133 |         Civil Chambers: 1-23. Hukuk Dairesi
 134 |         Criminal Chambers: 1-23. Ceza Dairesi
 135 |         General Assemblies: Hukuk Genel Kurulu, Ceza Genel Kurulu
 136 |         Special Boards: Hukuk/Ceza Daireleri Başkanlar Kurulu, Büyük Genel Kurulu
 137 |         
 138 |         Use "" for ALL chambers or specify exact chamber name.
 139 |         """,
 140 |         example="1. Hukuk Dairesi"
 141 |     )
 142 |     baslangicTarihi: Optional[str] = Field(None, description="Start date (DD.MM.YYYY)", example="01.01.2020")
 143 |     bitisTarihi: Optional[str] = Field(None, description="End date (DD.MM.YYYY)", example="31.12.2024")
 144 |     pageSize: int = Field(20, description="Results per page (1-100)", ge=1, le=100, example=20)
 145 | 
 146 | class YargitayBedestenSearchRequest(BaseModel):
 147 |     """
 148 |     Search request for Court of Cassation using Bedesten API (alternative source).
 149 |     Complements primary API with different search capabilities and recent decisions.
 150 |     """
 151 |     phrase: str = Field(
 152 |         ..., 
 153 |         description="""Aranacak kavram/kelime. İki farklı arama türü desteklenir:
 154 |         • Normal arama: "mülkiyet hakkı" - kelimeler ayrı ayrı aranır
 155 |         • Tam cümle arama: "\"mülkiyet hakkı\"" - tırnak içindeki ifade aynen aranır
 156 |         Tam cümle aramalar daha kesin sonuçlar verir.
 157 |         
 158 |         Search phrase with exact matching support:
 159 |         • Regular search: "mülkiyet hakkı" - searches individual words separately
 160 |         • Exact phrase search: "\"mülkiyet hakkı\"" - searches for exact phrase as unit
 161 |         Exact phrase search provides more precise results with fewer false positives.
 162 |         """,
 163 |         example="\"mülkiyet hakkı\""
 164 |     )
 165 |     birimAdi: Optional[str] = Field(
 166 |         None, 
 167 |         description="""Daire/Kurul seçimi (52 seçenek - ana API ile aynı):
 168 |         • Hukuk daireleri: 1. Hukuk Dairesi - 23. Hukuk Dairesi
 169 |         • Ceza daireleri: 1. Ceza Dairesi - 23. Ceza Dairesi
 170 |         • Genel kurullar: Hukuk Genel Kurulu, Ceza Genel Kurulu
 171 |         • Özel kurullar: Hukuk/Ceza Daireleri Başkanlar Kurulu, Büyük Genel Kurulu
 172 |         
 173 |         Chamber filtering (52 options - same as primary API):
 174 |         • Civil chambers: 1. Hukuk Dairesi through 23. Hukuk Dairesi
 175 |         • Criminal chambers: 1. Ceza Dairesi through 23. Ceza Dairesi
 176 |         • General assemblies: Hukuk Genel Kurulu, Ceza Genel Kurulu
 177 |         • Special boards: Hukuk/Ceza Daireleri Başkanlar Kurulu, Büyük Genel Kurulu
 178 |         
 179 |         Use None for ALL chambers, or specify exact chamber name.
 180 |         """,
 181 |         example="1. Hukuk Dairesi"
 182 |     )
 183 |     kararTarihiStart: Optional[str] = Field(
 184 |         None, 
 185 |         description="""Karar başlangıç tarihi (ISO 8601 formatı):
 186 |         Format: YYYY-MM-DDTHH:MM:SS.000Z
 187 |         Örnek: "2024-01-01T00:00:00.000Z" - 1 Ocak 2024'ten itibaren kararlar
 188 |         kararTarihiEnd ile birlikte tarih aralığı filtrelemesi için kullanılır.
 189 |         
 190 |         Decision start date filter (ISO 8601 format):
 191 |         Format: YYYY-MM-DDTHH:MM:SS.000Z
 192 |         Example: "2024-01-01T00:00:00.000Z" for decisions from Jan 1, 2024
 193 |         Use with kararTarihiEnd for date range filtering.
 194 |         """,
 195 |         example="2024-01-01T00:00:00.000Z"
 196 |     )
 197 |     kararTarihiEnd: Optional[str] = Field(
 198 |         None, 
 199 |         description="""Karar bitiş tarihi (ISO 8601 formatı):
 200 |         Format: YYYY-MM-DDTHH:MM:SS.000Z
 201 |         Örnek: "2024-12-31T23:59:59.999Z" - 31 Aralık 2024'e kadar kararlar
 202 |         kararTarihiStart ile birlikte tarih aralığı filtrelemesi için kullanılır.
 203 |         
 204 |         Decision end date filter (ISO 8601 format):
 205 |         Format: YYYY-MM-DDTHH:MM:SS.000Z
 206 |         Example: "2024-12-31T23:59:59.999Z" for decisions until Dec 31, 2024
 207 |         Use with kararTarihiStart for date range filtering.
 208 |         """,
 209 |         example="2024-12-31T23:59:59.999Z"
 210 |     )
 211 |     pageSize: int = Field(20, description="Results per page (1-100)", ge=1, le=100)
 212 | 
 213 | class DanistayKeywordSearchRequest(BaseModel):
 214 |     """
 215 |     Keyword-based search for Council of State (Danıştay) decisions with Boolean logic.
 216 |     
 217 |     The Council of State is Turkey's highest administrative court, providing final
 218 |     rulings on administrative law matters with Boolean keyword operators.
 219 |     """
 220 |     andKelimeler: List[str] = Field(
 221 |         ..., 
 222 |         description="ALL keywords must be present (AND logic)",
 223 |         example=["idari işlem", "iptal"]
 224 |     )
 225 |     orKelimeler: Optional[List[str]] = Field(
 226 |         None, 
 227 |         description="ANY keyword can be present (OR logic)",
 228 |         example=["ruhsat", "izin", "lisans"]
 229 |     )
 230 |     notKelimeler: Optional[List[str]] = Field(
 231 |         None, 
 232 |         description="EXCLUDE if keywords present (NOT logic)",
 233 |         example=["vergi"]
 234 |     )
 235 |     pageSize: int = Field(20, description="Results per page (1-100)", ge=1, le=100)
 236 | 
 237 | class DanistayDetailedSearchRequest(BaseModel):
 238 |     """
 239 |     Detailed search for Council of State decisions with comprehensive filtering.
 240 |     Provides the most comprehensive search capabilities for administrative court decisions.
 241 |     """
 242 |     daire: Optional[str] = Field(
 243 |         None, 
 244 |         description="Chamber/Department filter (1. Daire through 17. Daire, special councils)",
 245 |         example="3. Daire"
 246 |     )
 247 |     baslangicTarihi: Optional[str] = Field(None, description="Start date (DD.MM.YYYY)", example="01.01.2020")
 248 |     bitisTarihi: Optional[str] = Field(None, description="End date (DD.MM.YYYY)", example="31.12.2024")
 249 |     esas: Optional[str] = Field(None, description="Case number (Esas No)", example="2024/123")
 250 |     karar: Optional[str] = Field(None, description="Decision number (Karar No)", example="2024/456")
 251 | 
 252 | class DanistayBedestenSearchRequest(BaseModel):
 253 |     """
 254 |     Council of State search using Bedesten API with chamber filtering and exact phrase search.
 255 |     Provides access to administrative court decisions with 27 chamber options.
 256 |     """
 257 |     phrase: str = Field(..., description="Search phrase (supports exact matching with quotes)")
 258 |     birimAdi: Optional[str] = Field(
 259 |         None, 
 260 |         description="""Chamber filtering (27 options):
 261 |         Main Councils: Büyük Gen.Kur., İdare Dava Daireleri Kurulu, Vergi Dava Daireleri Kurulu
 262 |         Chambers: 1. Daire through 17. Daire
 263 |         Military: Askeri Yüksek İdare Mahkemesi chambers
 264 |         """,
 265 |         example="3. Daire"
 266 |     )
 267 |     kararTarihiStart: Optional[str] = Field(None, description="Start date (ISO 8601)")
 268 |     kararTarihiEnd: Optional[str] = Field(None, description="End date (ISO 8601)")
 269 |     pageSize: int = Field(20, description="Results per page", ge=1, le=100)
 270 | 
 271 | class EmsalSearchRequest(BaseModel):
 272 |     """
 273 |     Search Precedent (Emsal) decisions from UYAP system across multiple court levels.
 274 |     Provides access to precedent decisions from various Turkish courts.
 275 |     """
 276 |     keyword: str = Field(..., description="Search keyword across decision texts")
 277 |     decision_year_karar: Optional[str] = Field(None, description="Decision year filter", example="2024")
 278 |     results_per_page: int = Field(20, description="Results per page", ge=1, le=100)
 279 | 
 280 | class UyusmazlikSearchRequest(BaseModel):
 281 |     """
 282 |     Search Court of Jurisdictional Disputes decisions.
 283 |     Resolves jurisdictional disputes between different court systems.
 284 |     """
 285 |     keywords: List[str] = Field(..., description="Search keywords", example=["görev", "uyuşmazlık"])
 286 |     page_to_fetch: int = Field(1, description="Page number", ge=1)
 287 | 
 288 | class AnayasaNormSearchRequest(BaseModel):
 289 |     """
 290 |     Search Constitutional Court norm control (judicial review) decisions.
 291 |     Turkey's highest constitutional authority for reviewing law constitutionality.
 292 |     """
 293 |     keywords_all: List[str] = Field(..., description="All required keywords", example=["eğitim hakkı", "anayasa"])
 294 |     period: Optional[str] = Field(None, description="Constitutional period (1=1961, 2=1982)", example="2")
 295 |     application_type: Optional[str] = Field(None, description="Application type (1=İptal)", example="1")
 296 |     results_per_page: int = Field(20, description="Results per page", ge=1, le=100)
 297 | 
 298 | class AnayasaBireyselSearchRequest(BaseModel):
 299 |     """
 300 |     Search Constitutional Court individual application decisions.
 301 |     Human rights violation cases through individual citizen petitions.
 302 |     """
 303 |     keywords: List[str] = Field(..., description="Search keywords", example=["ifade özgürlüğü", "basın"])
 304 |     page_to_fetch: int = Field(1, description="Page number", ge=1)
 305 | 
 306 | class KikSearchRequest(BaseModel):
 307 |     """
 308 |     Search Public Procurement Authority (KİK) decisions.
 309 |     Government procurement disputes and regulatory interpretations.
 310 |     """
 311 |     karar_tipi: Optional[str] = Field(
 312 |         None, 
 313 |         description="Decision type (rbUyusmazlik=Disputes, rbDuzenleyici=Regulatory, rbMahkeme=Court)",
 314 |         example="rbUyusmazlik"
 315 |     )
 316 |     karar_metni: Optional[str] = Field(None, description="Decision text search", example="ihale iptali")
 317 |     basvuru_konusu_ihale: Optional[str] = Field(None, description="Tender subject", example="danışmanlık")
 318 |     karar_tarihi_baslangic: Optional[str] = Field(None, description="Start date", example="01.01.2023")
 319 | 
 320 | class RekabetSearchRequest(BaseModel):
 321 |     """
 322 |     Search Competition Authority decisions.
 323 |     Antitrust, merger control, and competition law enforcement.
 324 |     """
 325 |     KararTuru: Optional[str] = Field(
 326 |         None, 
 327 |         description="Decision type (Birleşme ve Devralma, Rekabet İhlali, Muafiyet, etc.)",
 328 |         example="Birleşme ve Devralma"
 329 |     )
 330 |     PdfText: Optional[str] = Field(
 331 |         None, 
 332 |         description="Full-text search in decisions. Use quotes for exact phrases.",
 333 |         example="\"market definition\" telecommunications"
 334 |     )
 335 |     YayinlanmaTarihi: Optional[str] = Field(None, description="Publication date", example="01.01.2020")
 336 |     page: int = Field(1, description="Page number", ge=1)
 337 | 
 338 | class BedestenSearchRequest(BaseModel):
 339 |     """
 340 |     Generic search request for Bedesten API courts (Yerel Hukuk, İstinaf Hukuk, KYB).
 341 |     Supports exact phrase search and date filtering.
 342 |     """
 343 |     phrase: str = Field(
 344 |         ..., 
 345 |         description="Search phrase. Use quotes for exact matching: \"legal term\"",
 346 |         example="\"sözleşme ihlali\""
 347 |     )
 348 |     kararTarihiStart: Optional[str] = Field(None, description="Start date (ISO 8601)")
 349 |     kararTarihiEnd: Optional[str] = Field(None, description="End date (ISO 8601)")
 350 |     pageSize: int = Field(20, description="Results per page", ge=1, le=100)
 351 | 
 352 | class SayistaySearchRequest(BaseModel):
 353 |     """
 354 |     Search Court of Accounts (Sayıştay) decisions.
 355 |     Public audit, accountability, and financial oversight decisions.
 356 |     """
 357 |     keywords: List[str] = Field(..., description="Search keywords", example=["mali sorumluluk", "denetim"])
 358 |     page_to_fetch: int = Field(1, description="Page number", ge=1)
 359 | 
 360 | # ============================================================================
 361 | # BASIC SERVER ENDPOINTS (keeping from original)
 362 | # ============================================================================
 363 | 
 364 | @app.get("/", response_model=ServerInfo)
 365 | async def root():
 366 |     """Get comprehensive server information with database coverage"""
 367 |     return ServerInfo(
 368 |         name="Yargı MCP Server - Turkish Legal Database API",
 369 |         version="1.0.0", 
 370 |         description="Complete REST API for Turkish legal databases with 33 MCP tools",
 371 |         tools_count=len(mcp_server._tool_manager._tools),
 372 |         databases=[
 373 |             "Yargıtay (Court of Cassation) - 4 tools",
 374 |             "Danıştay (Council of State) - 5 tools", 
 375 |             "Emsal (UYAP Precedents) - 2 tools",
 376 |             "Uyuşmazlık Mahkemesi (Jurisdictional Disputes) - 2 tools",
 377 |             "Anayasa Mahkemesi (Constitutional Court) - 4 tools",
 378 |             "Kamu İhale Kurulu (Public Procurement) - 2 tools",
 379 |             "Rekabet Kurumu (Competition Authority) - 2 tools",
 380 |             "Sayıştay (Court of Accounts) - 6 tools",
 381 |             "Bedesten API Courts (Local/Appellate/KYB) - 6 tools"
 382 |         ],
 383 |         mcp_endpoint="/mcp-server/mcp/",
 384 |         api_docs="/docs"
 385 |     )
 386 | 
 387 | @app.get("/health", response_model=HealthCheck)
 388 | async def health_check():
 389 |     """Health check with comprehensive system status"""
 390 |     uptime = (datetime.now() - SERVER_START_TIME).total_seconds()
 391 |     return HealthCheck(
 392 |         status="healthy",
 393 |         timestamp=datetime.now(),
 394 |         uptime_seconds=uptime,
 395 |         tools_operational=len(mcp_server._tool_manager._tools) == 33
 396 |     )
 397 | 
 398 | @app.get("/api/tools", response_model=List[ToolInfo])
 399 | async def list_tools(
 400 |     search: Optional[str] = Query(None, description="Search tools by name or description"),
 401 |     database: Optional[str] = Query(None, description="Filter by database name")
 402 | ):
 403 |     """List all 33 MCP tools with filtering capabilities"""
 404 |     tools = []
 405 |     for tool in mcp_server._tool_manager._tools.values():
 406 |         if search and search.lower() not in tool.name.lower() and search.lower() not in tool.description.lower():
 407 |             continue
 408 |         if database:
 409 |             db_lower = database.lower()
 410 |             if db_lower not in tool.name.lower() and db_lower not in tool.description.lower():
 411 |                 continue
 412 |         
 413 |         params = {}
 414 |         if hasattr(tool, 'schema') and tool.schema:
 415 |             if hasattr(tool.schema, 'parameters'):
 416 |                 params = tool.schema.parameters
 417 |             elif hasattr(tool.schema, '__annotations__'):
 418 |                 params = {k: str(v) for k, v in tool.schema.__annotations__.items()}
 419 |         
 420 |         tools.append(ToolInfo(
 421 |             name=tool.name,
 422 |             description=tool.description,
 423 |             parameters=params
 424 |         ))
 425 |     return tools
 426 | 
 427 | # ============================================================================
 428 | # YARGITAY (COURT OF CASSATION) ENDPOINTS - 4 TOOLS
 429 | # ============================================================================
 430 | 
 431 | @app.post(
 432 |     "/api/yargitay/search", 
 433 |     tags=["Yargıtay"],
 434 |     summary="Search Court of Cassation (Primary API)",
 435 |     description="""Search Turkey's Supreme Court for civil and criminal precedents using advanced operators.
 436 | 
 437 | Key Features:
 438 | • Advanced search: AND (+), OR (space), NOT (-), wildcards (*), exact phrases ("")
 439 | • 52 chamber options (23 Civil + 23 Criminal + General Assemblies)
 440 | • Date range filtering • Case/decision number filtering • Pagination
 441 | 
 442 | Search Examples:
 443 | • OR search: property share (finds ANY words)
 444 | • Exact phrase: "property share" (finds exact phrase)
 445 | • AND required: +"property share" +"annulment reason"
 446 | • Wildcard: construct* (construction, constructive, etc.)
 447 | • Exclude terms: +"property share" -"construction contract"
 448 | 
 449 | Use for supreme court precedent research and legal principle analysis."""
 450 | )
 451 | async def search_yargitay(request: YargitaySearchRequest):
 452 |     """
 453 |     Searches Court of Cassation (Yargıtay) decisions using the primary official API.
 454 | 
 455 |     The Court of Cassation (Yargıtay) is Turkey's highest court for civil and criminal matters,
 456 |     equivalent to a Supreme Court. This tool provides access to the most comprehensive database
 457 |     of supreme court precedents with advanced search capabilities and filtering options.
 458 | 
 459 |     Key Features:
 460 |     • Advanced search operators (AND, OR, wildcards, exclusions)
 461 |     • Chamber filtering: 52 options (23 Civil (Hukuk) + 23 Criminal (Ceza) + General Assemblies (Genel Kurullar))
 462 |     • Date range filtering with DD.MM.YYYY format
 463 |     • Case number filtering (Case No (Esas No) and Decision No (Karar No))
 464 |     • Pagination support (1-100 results per page)
 465 |     • Multiple sorting options (by case number, decision number, date)
 466 | 
 467 |     SEARCH SYNTAX GUIDE:
 468 |     • Words with spaces: OR search ("property share" finds ANY of the words)
 469 |     • "Quotes": Exact phrase search ("property share" finds exact phrase)
 470 |     • Plus sign (+): AND search (property+share requires both words)
 471 |     • Asterisk (*): Wildcard (construct* matches variations)
 472 |     • Minus sign (-): Exclude terms (avoid unwanted results)
 473 | 
 474 |     Common Search Patterns:
 475 |     • Simple OR: property share (finds ~523K results)
 476 |     • Exact phrase: "property share" (finds ~22K results)
 477 |     • Multiple required: +"property share" +"annulment reason (bozma sebebi)" (finds ~234 results)
 478 |     • Wildcard expansion: construct* (matches construction, constructive, etc.)
 479 |     • Exclude unwanted: +"property share" -"construction contract"
 480 | 
 481 |     Use cases:
 482 |     • Research supreme court precedents and legal principles
 483 |     • Find decisions from specific chambers (Civil (Hukuk) vs Criminal (Ceza))
 484 |     • Search for interpretations of specific legal concepts
 485 |     • Analyze court reasoning on complex legal issues
 486 |     • Track legal developments over time periods
 487 | 
 488 |     Returns structured search results with decision metadata. Use get_yargitay_document_markdown()
 489 |     to retrieve full decision texts for detailed analysis.
 490 |     """
 491 |     args = {
 492 |         "arananKelime": request.arananKelime,
 493 |         "birimYrgKurulDaire": request.birimYrgKurulDaire, 
 494 |         "pageSize": request.pageSize
 495 |     }
 496 |     if request.baslangicTarihi:
 497 |         args["baslangicTarihi"] = request.baslangicTarihi
 498 |     if request.bitisTarihi:
 499 |         args["bitisTarihi"] = request.bitisTarihi
 500 |     return await call_mcp_tool("search_yargitay_detailed", args)
 501 | 
 502 | @app.post(
 503 |     "/api/yargitay/search-bedesten",
 504 |     tags=["Yargıtay"], 
 505 |     summary="Search Court of Cassation (Bedesten API)",
 506 |     description="""Alternative Court of Cassation search with exact phrase matching and recent decisions.
 507 | 
 508 | Key Features:
 509 | • Exact phrase search: "\"legal term\"" for precise matching
 510 | • Regular search: "legal term" for individual word matching  
 511 | • 52 chamber filtering options (same as primary API)
 512 | • ISO 8601 date filtering • Recent decision coverage
 513 | 
 514 | Use alongside primary search for comprehensive coverage. Exact phrase search provides
 515 | higher precision with fewer false positives."""
 516 | )
 517 | async def search_yargitay_bedesten(request: YargitayBedestenSearchRequest):
 518 |     """Search Court of Cassation using Bedesten API. Complements primary API for complete coverage."""
 519 |     args = {"phrase": request.phrase, "pageSize": request.pageSize}
 520 |     if request.birimAdi:
 521 |         args["birimAdi"] = request.birimAdi
 522 |     if request.kararTarihiStart:
 523 |         args["kararTarihiStart"] = request.kararTarihiStart
 524 |     if request.kararTarihiEnd:
 525 |         args["kararTarihiEnd"] = request.kararTarihiEnd
 526 |     return await call_mcp_tool("search_yargitay_bedesten", args)
 527 | 
 528 | @app.get(
 529 |     "/api/yargitay/document/{decision_id}",
 530 |     tags=["Yargıtay"],
 531 |     summary="Get Court of Cassation Document (Primary API)", 
 532 |     description="""Retrieve complete Court of Cassation decision in Markdown format.
 533 | 
 534 | Content includes:
 535 | • Complete legal reasoning and precedent analysis
 536 | • Detailed examination of lower court decisions  
 537 | • Citations of laws, regulations, and prior cases
 538 | • Final ruling with legal justification
 539 | 
 540 | Perfect for detailed legal analysis, precedent research, and citation building."""
 541 | )
 542 | async def get_yargitay_document(decision_id: str):
 543 |     """Get full Court of Cassation decision text in clean Markdown format."""
 544 |     return await call_mcp_tool("get_yargitay_document_markdown", {"id": decision_id})
 545 | 
 546 | @app.get(
 547 |     "/api/yargitay/bedesten-document/{document_id}",
 548 |     tags=["Yargıtay"],
 549 |     summary="Get Court of Cassation Document (Bedesten API)",
 550 |     description="""Retrieve Court of Cassation decision from Bedesten API in Markdown format.
 551 | 
 552 | Features:
 553 | • Supports both HTML and PDF source documents
 554 | • Clean Markdown conversion with legal structure preserved
 555 | • Removes technical artifacts for easy reading
 556 | • Compatible with documentId from Bedesten search results"""
 557 | )
 558 | async def get_yargitay_bedesten_document(document_id: str):
 559 |     """Get Court of Cassation document from Bedesten API in Markdown format."""
 560 |     return await call_mcp_tool("get_yargitay_bedesten_document_markdown", {"documentId": document_id})
 561 | 
 562 | # ============================================================================
 563 | # DANISTAY (COUNCIL OF STATE) ENDPOINTS - 5 TOOLS  
 564 | # ============================================================================
 565 | 
 566 | @app.post(
 567 |     "/api/danistay/search-keyword",
 568 |     tags=["Danıştay"],
 569 |     summary="Search Council of State (Keyword Logic)",
 570 |     description="""Search Turkey's highest administrative court using Boolean keyword logic.
 571 | 
 572 | Boolean Operators:
 573 | • AND keywords: ALL must be present (required terms)
 574 | • OR keywords: ANY can be present (alternative terms)  
 575 | • NOT keywords: EXCLUDE if present (unwanted terms)
 576 | 
 577 | Examples:
 578 | • Administrative acts: andKelimeler=["idari işlem", "iptal"]
 579 | • Permits/licenses: orKelimeler=["ruhsat", "izin", "lisans"]
 580 | • Exclude tax cases: notKelimeler=["vergi"]
 581 | 
 582 | Perfect for administrative law research and government action reviews."""
 583 | )
 584 | async def search_danistay_keyword(request: DanistayKeywordSearchRequest):
 585 |     """
 586 |     Searches Council of State (Danıştay) decisions using keyword-based logic.
 587 | 
 588 |     The Council of State (Danıştay) is Turkey's highest administrative court, responsible for
 589 |     reviewing administrative actions and providing administrative law precedents. This tool
 590 |     provides flexible keyword-based searching with Boolean logic operators.
 591 | 
 592 |     Key Features:
 593 |     • Boolean logic operators: AND, OR, NOT combinations
 594 |     • Multiple keyword lists for complex search strategies
 595 |     • Pagination support (1-100 results per page)
 596 |     • Administrative law focus (permits, licenses, public administration)
 597 |     • Complement to search_danistay_detailed for comprehensive coverage
 598 | 
 599 |     Keyword Logic:
 600 |     • andKelimeler: ALL keywords must be present (AND logic)
 601 |     • orKelimeler: ANY keyword can be present (OR logic)
 602 |     • notAndKelimeler: EXCLUDE if ALL keywords present (NOT AND)
 603 |     • notOrKelimeler: EXCLUDE if ANY keyword present (NOT OR)
 604 | 
 605 |     Administrative Law Use Cases:
 606 |     • Research administrative court precedents
 607 |     • Find decisions on specific government agencies
 608 |     • Search for rulings on permits (ruhsat) and licenses (izin)
 609 |     • Analyze administrative procedure interpretations
 610 |     • Study public administration legal principles
 611 | 
 612 |     Examples:
 613 |     • Simple AND: andKelimeler=["administrative act (idari işlem)", "annulment (iptal)"]
 614 |     • OR search: orKelimeler=["permit (ruhsat)", "permission (izin)", "license (lisans)"]
 615 |     • Complex: andKelimeler=["municipality (belediye)"], notOrKelimeler=["tax (vergi)"]
 616 | 
 617 |     Returns structured search results. Use get_danistay_document_markdown() for full texts.
 618 |     For comprehensive Council of State (Danıştay) research, also use search_danistay_detailed and search_danistay_bedesten.
 619 |     """
 620 |     args = {"andKelimeler": request.andKelimeler, "pageSize": request.pageSize}
 621 |     if request.orKelimeler:
 622 |         args["orKelimeler"] = request.orKelimeler
 623 |     if request.notKelimeler:
 624 |         args["notKelimeler"] = request.notKelimeler
 625 |     return await call_mcp_tool("search_danistay_by_keyword", args)
 626 | 
 627 | @app.post(
 628 |     "/api/danistay/search-detailed",
 629 |     tags=["Danıştay"],
 630 |     summary="Search Council of State (Detailed Criteria)",
 631 |     description="""Most comprehensive Council of State search with advanced filtering.
 632 | 
 633 | Advanced Filtering:
 634 | • Chamber targeting (1. Daire through 17. Daire, special councils)
 635 | • Case/decision number ranges • Date range filtering
 636 | • Legislation cross-referencing • Multiple sorting options
 637 | 
 638 | Use for specialized administrative law research, chamber-specific decisions,
 639 | and regulatory compliance analysis."""
 640 | )
 641 | async def search_danistay_detailed(request: DanistayDetailedSearchRequest):
 642 |     """Search Council of State with comprehensive filtering for specialized administrative law research."""
 643 |     args = {}
 644 |     for field in ["daire", "baslangicTarihi", "bitisTarihi", "esas", "karar"]:
 645 |         if getattr(request, field):
 646 |             args[field] = getattr(request, field)
 647 |     return await call_mcp_tool("search_danistay_detailed", args)
 648 | 
 649 | @app.post(
 650 |     "/api/danistay/search-bedesten",
 651 |     tags=["Danıştay"],
 652 |     summary="Search Council of State (Bedesten API)",
 653 |     description="""Council of State search via Bedesten API with 27 chamber options and exact phrase search.
 654 | 
 655 | Key Features:
 656 | • 27 chamber options (Main Councils, 17 Chambers, Military courts)
 657 | • Exact phrase search with double quotes for precision
 658 | • ISO 8601 date filtering • Alternative data source
 659 | 
 660 | Use with other Danıştay tools for complete administrative law coverage."""
 661 | )
 662 | async def search_danistay_bedesten(request: DanistayBedestenSearchRequest):
 663 |     """Search Council of State via Bedesten API. Use with other Danıştay tools for complete coverage."""
 664 |     args = {"phrase": request.phrase, "pageSize": request.pageSize}
 665 |     for field in ["birimAdi", "kararTarihiStart", "kararTarihiEnd"]:
 666 |         if getattr(request, field):
 667 |             args[field] = getattr(request, field)
 668 |     return await call_mcp_tool("search_danistay_bedesten", args)
 669 | 
 670 | @app.get(
 671 |     "/api/danistay/document/{decision_id}",
 672 |     tags=["Danıştay"],
 673 |     summary="Get Council of State Document (Primary API)",
 674 |     description="""Retrieve complete administrative court decision in Markdown format.
 675 | 
 676 | Content includes:
 677 | • Complete administrative law reasoning and precedent analysis
 678 | • Review of administrative actions and government decisions
 679 | • Citations of administrative laws and regulations
 680 | • Final administrative ruling with legal justification
 681 | 
 682 | Essential for administrative law research and government compliance analysis."""
 683 | )
 684 | async def get_danistay_document(decision_id: str):
 685 |     """Get full Council of State decision text in clean Markdown format."""
 686 |     return await call_mcp_tool("get_danistay_document_markdown", {"id": decision_id})
 687 | 
 688 | @app.get(
 689 |     "/api/danistay/bedesten-document/{document_id}",
 690 |     tags=["Danıştay"],
 691 |     summary="Get Council of State Document (Bedesten API)",
 692 |     description="""Retrieve Council of State decision from Bedesten API in Markdown format."""
 693 | )
 694 | async def get_danistay_bedesten_document(document_id: str):
 695 |     """Get Council of State document from Bedesten API in Markdown format."""
 696 |     return await call_mcp_tool("get_danistay_bedesten_document_markdown", {"documentId": document_id})
 697 | 
 698 | # ============================================================================
 699 | # BEDESTEN API COURTS (LOCAL/APPELLATE/KYB) - 6 TOOLS
 700 | # ============================================================================
 701 | 
 702 | @app.post(
 703 |     "/api/yerel-hukuk/search",
 704 |     tags=["Yerel Hukuk"],
 705 |     summary="Search Local Civil Courts",
 706 |     description="""Search first-instance civil court decisions using Bedesten API.
 707 | 
 708 | Local Civil Courts handle:
 709 | • Contract disputes • Property rights • Family law • Tort claims
 710 | • Commercial disputes • Consumer protection
 711 | 
 712 | Only available tool for local court decisions. Supports exact phrase search
 713 | and date filtering for precise legal research."""
 714 | )
 715 | async def search_yerel_hukuk(request: BedestenSearchRequest):
 716 |     """
 717 |     Searches Yerel Hukuk Mahkemesi (Local Civil Court) decisions using Bedesten API.
 718 |     
 719 |     This provides access to local court decisions that are not available through other APIs.
 720 |     Currently the only available tool for searching Yerel Hukuk Mahkemesi decisions.
 721 |     Local civil courts represent the first instance of civil litigation in Turkey.
 722 | 
 723 |     Local Civil Courts handle:
 724 |     • Contract disputes and commercial litigation
 725 |     • Property rights and real estate disputes
 726 |     • Family law matters (divorce, custody, inheritance)
 727 |     • Tort claims and compensation cases
 728 |     • Consumer protection issues
 729 |     • Employment disputes
 730 |     
 731 |     Returns structured search results with decision metadata. Use get_yerel_hukuk_bedesten_document_markdown()
 732 |     to retrieve full decision texts for detailed analysis.
 733 |     """
 734 |     args = {"phrase": request.phrase, "pageSize": request.pageSize}
 735 |     for field in ["kararTarihiStart", "kararTarihiEnd"]:
 736 |         if getattr(request, field):
 737 |             args[field] = getattr(request, field)
 738 |     return await call_mcp_tool("search_yerel_hukuk_bedesten", args)
 739 | 
 740 | @app.get("/api/yerel-hukuk/document/{document_id}", tags=["Yerel Hukuk"])
 741 | async def get_yerel_hukuk_document(document_id: str):
 742 |     """
 743 |     Retrieves a Yerel Hukuk Mahkemesi decision document from Bedesten API and converts to Markdown.
 744 |     
 745 |     This tool fetches complete local court decision texts using documentId from search results.
 746 |     Perfect for detailed analysis of first-instance civil court rulings.
 747 |     
 748 |     Supports both HTML and PDF content types, automatically converting to clean Markdown format.
 749 |     Use documentId from search_yerel_hukuk_bedesten results.
 750 |     """
 751 |     return await call_mcp_tool("get_yerel_hukuk_bedesten_document_markdown", {"documentId": document_id})
 752 | 
 753 | @app.post(
 754 |     "/api/istinaf-hukuk/search",
 755 |     tags=["İstinaf Hukuk"],
 756 |     summary="Search Civil Courts of Appeals",
 757 |     description="""Search intermediate appellate court decisions using Bedesten API.
 758 | 
 759 | İstinaf Courts are intermediate appellate courts handling appeals from local civil courts
 760 | before cases reach the Court of Cassation. Only available tool for İstinaf decisions."""
 761 | )
 762 | async def search_istinaf_hukuk(request: BedestenSearchRequest):
 763 |     """
 764 |     Searches İstinaf Hukuk Mahkemesi (Civil Court of Appeals) decisions using Bedesten API.
 765 | 
 766 |     İstinaf courts are intermediate appellate courts in the Turkish judicial system that handle
 767 |     appeals from local civil courts before cases reach Yargıtay (Court of Cassation).
 768 |     This is the only available tool for accessing İstinaf Hukuk Mahkemesi decisions.
 769 | 
 770 |     Key Features:
 771 |     • Date range filtering with ISO 8601 format (YYYY-MM-DDTHH:MM:SS.000Z)
 772 |     • Exact phrase search using double quotes: "\"legal term\"" 
 773 |     • Regular search for individual keywords
 774 |     • Pagination support (1-100 results per page)
 775 | 
 776 |     Use cases:
 777 |     • Research appellate court precedents
 778 |     • Track appeals from specific lower courts
 779 |     • Find decisions on specific legal issues at appellate level
 780 |     • Analyze intermediate court reasoning before supreme court review
 781 | 
 782 |     Returns structured data with decision metadata including dates, case numbers, and summaries.
 783 |     Use get_istinaf_hukuk_bedesten_document_markdown() to retrieve full decision texts.
 784 |     """
 785 |     args = {"phrase": request.phrase, "pageSize": request.pageSize}
 786 |     for field in ["kararTarihiStart", "kararTarihiEnd"]:
 787 |         if getattr(request, field):
 788 |             args[field] = getattr(request, field)
 789 |     return await call_mcp_tool("search_istinaf_hukuk_bedesten", args)
 790 | 
 791 | @app.get("/api/istinaf-hukuk/document/{document_id}", tags=["İstinaf Hukuk"])
 792 | async def get_istinaf_hukuk_document(document_id: str):
 793 |     """
 794 |     Retrieves the full text of an İstinaf Hukuk Mahkemesi decision document in Markdown format.
 795 | 
 796 |     This tool converts the original decision document (HTML or PDF) from Bedesten API
 797 |     into clean, readable Markdown format suitable for analysis and processing.
 798 | 
 799 |     Input Requirements:
 800 |     • documentId: Use the ID from search_istinaf_hukuk_bedesten results
 801 |     • Document ID must be non-empty string
 802 | 
 803 |     Output Format:
 804 |     • Clean Markdown text with proper formatting
 805 |     • Preserves legal structure (headers, paragraphs, citations)
 806 |     • Removes extraneous HTML/PDF artifacts
 807 | 
 808 |     Use for:
 809 |     • Reading full appellate court decision texts
 810 |     • Legal analysis of İstinaf court reasoning
 811 |     • Citation extraction and reference building
 812 |     • Content analysis and summarization
 813 |     """
 814 |     return await call_mcp_tool("get_istinaf_hukuk_bedesten_document_markdown", {"documentId": document_id})
 815 | 
 816 | @app.post(
 817 |     "/api/kyb/search",
 818 |     tags=["KYB"],
 819 |     summary="Search Extraordinary Appeals (KYB)",
 820 |     description="""Search Kanun Yararına Bozma (Extraordinary Appeal) decisions.
 821 | 
 822 | KYB is an extraordinary legal remedy where the Public Prosecutor's Office requests
 823 | review of finalized decisions in favor of law and defendants. Very rare but important
 824 | legal precedents. Only available tool for KYB decisions."""
 825 | )
 826 | async def search_kyb(request: BedestenSearchRequest):
 827 |     """
 828 |     Searches Kanun Yararına Bozma (KYB - Extraordinary Appeal) decisions using Bedesten API.
 829 | 
 830 |     KYB is an extraordinary legal remedy in the Turkish judicial system where the
 831 |     Public Prosecutor's Office can request review of finalized decisions in favor of
 832 |     the law and defendants. This is the only available tool for accessing KYB decisions.
 833 | 
 834 |     Key Features:
 835 |     • Date range filtering with ISO 8601 format (YYYY-MM-DDTHH:MM:SS.000Z)
 836 |     • Exact phrase search using double quotes: "\"extraordinary appeal\""
 837 |     • Regular search for individual keywords
 838 |     • Pagination support (1-100 results per page)
 839 | 
 840 |     Legal Significance:
 841 |     • Extraordinary remedy beyond regular appeals
 842 |     • Initiated by Public Prosecutor's Office
 843 |     • Reviews finalized decisions for legal errors
 844 |     • Can benefit defendants retroactively
 845 |     • Rare but important legal precedents
 846 | 
 847 |     Use cases:
 848 |     • Research extraordinary appeal precedents
 849 |     • Study prosecutorial challenges to final decisions
 850 |     • Analyze legal errors in finalized cases
 851 |     • Track KYB success rates and patterns
 852 | 
 853 |     Returns structured data with decision metadata. Use get_kyb_bedesten_document_markdown()
 854 |     to retrieve full decision texts for detailed analysis.
 855 |     """
 856 |     args = {"phrase": request.phrase, "pageSize": request.pageSize}
 857 |     for field in ["kararTarihiStart", "kararTarihiEnd"]:
 858 |         if getattr(request, field):
 859 |             args[field] = getattr(request, field)
 860 |     return await call_mcp_tool("search_kyb_bedesten", args)
 861 | 
 862 | @app.get("/api/kyb/document/{document_id}", tags=["KYB"])
 863 | async def get_kyb_document(document_id: str):
 864 |     """
 865 |     Retrieves the full text of a Kanun Yararına Bozma (KYB) decision document in Markdown format.
 866 | 
 867 |     This tool converts the original extraordinary appeal decision document (HTML or PDF)
 868 |     from Bedesten API into clean, readable Markdown format for analysis.
 869 | 
 870 |     Input Requirements:
 871 |     • documentId: Use the ID from search_kyb_bedesten results
 872 |     • Document ID must be non-empty string
 873 | 
 874 |     Output Format:
 875 |     • Clean Markdown text with legal formatting preserved
 876 |     • Structured content with headers and citations
 877 |     • Removes technical artifacts from source documents
 878 | 
 879 |     Special Value for KYB Documents:
 880 |     • Contains rare extraordinary appeal reasoning
 881 |     • Shows prosecutorial arguments for legal review
 882 |     • Documents correction of finalized legal errors
 883 |     • Provides precedent for similar extraordinary circumstances
 884 | 
 885 |     Use for:
 886 |     • Analyzing extraordinary appeal legal reasoning
 887 |     • Understanding prosecutorial review criteria
 888 |     • Research on legal error correction mechanisms
 889 |     • Studying retroactive benefit applications
 890 |     """
 891 |     return await call_mcp_tool("get_kyb_bedesten_document_markdown", {"documentId": document_id})
 892 | 
 893 | # ============================================================================
 894 | # ADDITIONAL COURTS - 12 TOOLS
 895 | # ============================================================================
 896 | 
 897 | @app.post("/api/emsal/search", tags=["Emsal"], summary="Search UYAP Precedents")
 898 | async def search_emsal(request: EmsalSearchRequest):
 899 |     """
 900 |     Searches for Precedent (Emsal) decisions using detailed criteria.
 901 | 
 902 |     The Precedent (Emsal) database contains precedent decisions from various Turkish courts
 903 |     integrated through the UYAP (National Judiciary Informatics System). This tool provides
 904 |     access to a comprehensive collection of court decisions that serve as legal precedents.
 905 | 
 906 |     Key Features:
 907 |     • Multi-court coverage (BAM, Civil courts, Regional chambers)
 908 |     • Keyword-based search across decision texts
 909 |     • Court-specific filtering for targeted research
 910 |     • Case number filtering (Case No (Esas No) and Decision No (Karar No) with ranges)
 911 |     • Date range filtering with DD.MM.YYYY format
 912 |     • Multiple sorting options and pagination support
 913 | 
 914 |     Court Selection Options:
 915 |     • BAM Civil Courts: Higher regional civil courts
 916 |     • Civil Courts: Local and first-instance civil courts
 917 |     • Regional Civil Chambers: Specialized civil court departments
 918 | 
 919 |     Precedent Research Use Cases:
 920 |     • Find precedent (emsal) decisions across multiple court levels
 921 |     • Research court interpretations of specific legal concepts
 922 |     • Analyze consistent legal reasoning patterns
 923 |     • Study regional variations in legal decisions
 924 |     • Track precedent development over time
 925 |     • Compare decisions from different court types
 926 | 
 927 |     Returns structured precedent data with court information and decision metadata.
 928 |     Use get_emsal_document_markdown() to retrieve full precedent decision texts.
 929 |     """
 930 |     args = {"keyword": request.keyword, "results_per_page": request.results_per_page}
 931 |     if request.decision_year_karar:
 932 |         args["decision_year_karar"] = request.decision_year_karar
 933 |     return await call_mcp_tool("search_emsal_detailed_decisions", args)
 934 | 
 935 | @app.get("/api/emsal/document/{decision_id}", tags=["Emsal"])
 936 | async def get_emsal_document(decision_id: str):
 937 |     """
 938 |     Retrieves the full text of a specific Emsal (UYAP Precedent) decision in Markdown format.
 939 | 
 940 |     This tool fetches complete precedent decision documents from the UYAP system and converts
 941 |     them to clean, readable Markdown format suitable for legal precedent analysis.
 942 | 
 943 |     Input Requirements:
 944 |     • decision_id: Decision ID from search_emsal_detailed_decisions results
 945 |     • ID must be non-empty string from UYAP Emsal database
 946 | 
 947 |     Output Format:
 948 |     • Clean Markdown text with legal precedent structure preserved
 949 |     • Organized sections: court info, case facts, legal reasoning, conclusion
 950 |     • Proper formatting for legal citations and cross-references
 951 |     • Removes technical artifacts from source documents
 952 | 
 953 |     Precedent Decision Content:
 954 |     • Complete court reasoning and legal analysis
 955 |     • Detailed examination of legal principles applied
 956 |     • Citation of relevant laws, regulations, and prior precedents
 957 |     • Final ruling with precedent-setting reasoning
 958 |     • Court-specific interpretations and legal standards
 959 | 
 960 |     Use for legal precedent research, citation building, and comparative legal analysis.
 961 |     """
 962 |     return await call_mcp_tool("get_emsal_document_markdown", {"decision_id": decision_id})
 963 | 
 964 | @app.post("/api/uyusmazlik/search", tags=["Uyuşmazlık"], summary="Search Jurisdictional Disputes")
 965 | async def search_uyusmazlik(request: UyusmazlikSearchRequest):
 966 |     """
 967 |     Searches for Court of Jurisdictional Disputes (Uyuşmazlık Mahkemesi) decisions.
 968 | 
 969 |     The Court of Jurisdictional Disputes (Uyuşmazlık Mahkemesi) resolves jurisdictional disputes between different court systems
 970 |     in Turkey, determining which court has jurisdiction over specific cases. This specialized
 971 |     court handles conflicts between civil, criminal, and administrative jurisdictions.
 972 | 
 973 |     Key Features:
 974 |     • Department filtering (Criminal, Civil, General Assembly decisions)
 975 |     • Dispute type classification (Jurisdiction vs Judgment disputes)
 976 |     • Decision outcome filtering (dispute resolution results)
 977 |     • Case number and date range filtering
 978 |     • Advanced text search with Boolean logic operators
 979 |     • Official Gazette reference search
 980 | 
 981 |     Dispute Types:
 982 |     • Jurisdictional Disputes (Görev Uyuşmazlığı): Which court has authority
 983 |     • Judgment Disputes (Hüküm Uyuşmazlığı): Conflicting final decisions
 984 | 
 985 |     Departments:
 986 |     • Criminal Section (Ceza Bölümü): Criminal section decisions
 987 |     • Civil Section (Hukuk Bölümü): Civil section decisions  
 988 |     • General Assembly Decisions (Genel Kurul Kararları): General Assembly decisions
 989 | 
 990 |     Use cases:
 991 |     • Research jurisdictional precedents
 992 |     • Understand court system boundaries
 993 |     • Analyze dispute resolution patterns
 994 |     • Study inter-court conflict resolution
 995 |     • Legal procedure and jurisdiction research
 996 | 
 997 |     Returns structured search results with dispute resolution information.
 998 |     """
 999 |     return await call_mcp_tool("search_uyusmazlik_decisions", {
1000 |         "keywords": request.keywords,
1001 |         "page_to_fetch": request.page_to_fetch
1002 |     })
1003 | 
1004 | @app.get("/api/uyusmazlik/document", tags=["Uyuşmazlık"])
1005 | async def get_uyusmazlik_document(document_url: str):
1006 |     """
1007 |     Retrieves the full text of a specific Uyuşmazlık Mahkemesi decision from its URL in Markdown format.
1008 | 
1009 |     This tool fetches complete jurisdictional dispute resolution decisions and converts them
1010 |     to clean, readable Markdown format suitable for legal analysis of inter-court disputes.
1011 | 
1012 |     Input Requirements:
1013 |     • document_url: Full URL to the decision document from search_uyusmazlik_decisions results
1014 |     • URL must be valid HttpUrl format from official Uyuşmazlık Mahkemesi database
1015 | 
1016 |     Output Format:
1017 |     • Clean Markdown text with jurisdictional dispute structure preserved
1018 |     • Organized sections: dispute facts, jurisdictional analysis, resolution ruling
1019 |     • Proper formatting for legal citations and court system references
1020 |     • Removes technical artifacts from source documents
1021 | 
1022 |     Jurisdictional Dispute Decision Content:
1023 |     • Complete analysis of jurisdictional conflicts between court systems
1024 |     • Detailed examination of applicable jurisdictional rules
1025 |     • Citation of relevant procedural laws and court organization statutes
1026 |     • Final resolution determining proper court jurisdiction
1027 |     • Reasoning for jurisdictional boundaries and court authority
1028 | 
1029 |     Use for understanding court system boundaries, analyzing jurisdictional precedents,
1030 |     and legal practice guidance on proper court selection.
1031 |     """
1032 |     return await call_mcp_tool("get_uyusmazlik_document_markdown_from_url", {"document_url": document_url})
1033 | 
1034 | @app.post("/api/anayasa/search-norm", tags=["Anayasa"], summary="Search Constitutional Court (Norm Control)")
1035 | async def search_anayasa_norm(request: AnayasaNormSearchRequest):
1036 |     """
1037 |     Searches Constitutional Court (Anayasa Mahkemesi) norm control decisions with comprehensive filtering.
1038 | 
1039 |     The Constitutional Court is Turkey's highest constitutional authority, responsible for judicial
1040 |     review of laws, regulations, and constitutional amendments. Norm control (Norm Denetimi) is the
1041 |     court's power to review the constitutionality of legal norms.
1042 | 
1043 |     Key Features:
1044 |     • Boolean keyword search (AND, OR, NOT logic)
1045 |     • Constitutional period filtering (1961 vs 1982 Constitution)
1046 |     • Case and decision number filtering
1047 |     • Date range filtering for review and decision dates
1048 |     • Application type classification (İptal, İtiraz, etc.)
1049 |     • Applicant filtering (government entities, opposition parties)
1050 |     • Official Gazette publication filtering
1051 |     • Judicial opinion analysis (dissents, different reasoning)
1052 |     • Court member and rapporteur filtering
1053 |     • Norm type classification (laws, regulations, decrees)
1054 |     • Review outcome filtering (constitutionality determinations)
1055 |     • Constitutional basis article referencing
1056 | 
1057 |     Constitutional Review Types:
1058 |     • Abstract review: Ex ante constitutional control
1059 |     • Concrete review: Constitutional questions during litigation
1060 |     • Legislative review: Parliamentary acts and government decrees
1061 |     • Regulatory review: Administrative regulations and bylaws
1062 | 
1063 |     Use cases:
1064 |     • Constitutional law research and analysis
1065 |     • Legislative drafting constitutional compliance
1066 |     • Academic constitutional law study
1067 |     • Legal precedent analysis for constitutional questions
1068 |     • Government policy constitutional assessment
1069 | 
1070 |     Returns structured constitutional court data with comprehensive metadata.
1071 |     """
1072 |     args = {"keywords_all": request.keywords_all, "results_per_page": request.results_per_page}
1073 |     for field in ["period", "application_type"]:
1074 |         if getattr(request, field):
1075 |             args[field] = getattr(request, field)
1076 |     return await call_mcp_tool("search_anayasa_norm_denetimi_decisions", args)
1077 | 
1078 | @app.get("/api/anayasa/norm-document", tags=["Anayasa"])
1079 | async def get_anayasa_norm_document(document_url: str, page_number: int = 1):
1080 |     """Get Constitutional Court norm control decision in paginated Markdown format."""
1081 |     return await call_mcp_tool("get_anayasa_norm_denetimi_document_markdown", {
1082 |         "document_url": document_url, "page_number": page_number
1083 |     })
1084 | 
1085 | @app.post("/api/anayasa/search-bireysel", tags=["Anayasa"], summary="Search Constitutional Court (Individual Applications)")
1086 | async def search_anayasa_bireysel(request: AnayasaBireyselSearchRequest):
1087 |     """
1088 |     Search Constitutional Court individual application (Bireysel Başvuru) decisions for human rights violation reports with keyword filtering.
1089 |     
1090 |     Individual applications allow citizens to petition the Constitutional Court directly for
1091 |     violations of fundamental rights and freedoms. This tool generates decision search reports
1092 |     that help identify relevant human rights violation cases.
1093 |     
1094 |     Key Features:
1095 |     • Keyword-based search with AND logic
1096 |     • Human rights violation case identification
1097 |     • Individual petition decision analysis
1098 |     • Fundamental rights and freedoms research
1099 |     • Pagination support for large result sets
1100 |     
1101 |     Individual Application System:
1102 |     • Direct citizen access to Constitutional Court
1103 |     • Human rights and fundamental freedoms protection
1104 |     • Alternative to European Court of Human Rights
1105 |     • Domestic remedy for constitutional violations
1106 |     • Individual justice and rights enforcement
1107 |     
1108 |     Human Rights Categories:
1109 |     • Right to life and personal liberty
1110 |     • Right to fair trial and due process
1111 |     • Freedom of expression and press
1112 |     • Freedom of religion and conscience
1113 |     • Property rights and economic freedoms
1114 |     • Right to privacy and family life
1115 |     • Political rights and democratic participation
1116 |     
1117 |     Use cases:
1118 |     • Human rights violation research
1119 |     • Individual petition precedent analysis
1120 |     • Constitutional rights interpretation study
1121 |     • Legal remedies for rights violations
1122 |     • Academic human rights law research
1123 |     • Civil society and NGO legal research
1124 |     
1125 |     Returns search report with case summaries and violation categories.
1126 |     Use get_anayasa_bireysel_document for full decision texts.
1127 |     """
1128 |     return await call_mcp_tool("search_anayasa_bireysel_basvuru_report", {
1129 |         "keywords": request.keywords, "page_to_fetch": request.page_to_fetch
1130 |     })
1131 | 
1132 | @app.get("/api/anayasa/bireysel-document", tags=["Anayasa"])
1133 | async def get_anayasa_bireysel_document(document_url: str, page_number: int = 1):
1134 |     """
1135 |     Retrieve the full text of a Constitutional Court individual application decision in paginated Markdown format.
1136 |     
1137 |     This tool fetches complete human rights violation decisions from individual applications
1138 |     and converts them to clean, readable Markdown format. Content is paginated into
1139 |     5,000-character chunks for easier processing.
1140 |     
1141 |     Input Requirements:
1142 |     • document_url: URL path (e.g., /BB/YYYY/NNNN) from search results
1143 |     • page_number: Page number for pagination (1-indexed, default: 1)
1144 |     
1145 |     Output Format:
1146 |     • Clean Markdown text with human rights case structure preserved
1147 |     • Organized sections: applicant info, violation claims, court analysis, ruling
1148 |     • Proper formatting for human rights law citations and references
1149 |     • Paginated content with navigation information
1150 |     
1151 |     Individual Application Decision Content:
1152 |     • Complete human rights violation analysis
1153 |     • Detailed examination of fundamental rights claims
1154 |     • Citation of constitutional articles and international human rights law
1155 |     • Final determination on rights violations with remedies
1156 |     • Analysis of domestic court proceedings and their adequacy
1157 |     • Individual remedy recommendations and compensation
1158 |     
1159 |     Use for:
1160 |     • Reading full human rights violation decisions
1161 |     • Human rights law research and precedent analysis
1162 |     • Understanding constitutional rights protection standards
1163 |     • Individual petition strategy development
1164 |     • Academic human rights and constitutional law study
1165 |     • Civil society monitoring of rights violations
1166 |     """
1167 |     return await call_mcp_tool("get_anayasa_bireysel_basvuru_document_markdown", {
1168 |         "document_url": document_url, "page_number": page_number
1169 |     })
1170 | 
1171 | @app.post("/api/kik/search", tags=["KİK"], summary="Search Public Procurement Authority")
1172 | async def search_kik(request: KikSearchRequest):
1173 |     """
1174 |     Search Public Procurement Authority (Kamu İhale Kurulu - KIK) decisions with comprehensive filtering for public procurement law and administrative dispute research.
1175 |     
1176 |     The Public Procurement Authority (KIK) is Turkey's procurement oversight body, responsible for
1177 |     regulating public procurement processes, resolving procurement disputes, and issuing interpretive
1178 |     decisions on public contracting laws. This tool provides access to official procurement decisions
1179 |     and regulatory guidance.
1180 |     
1181 |     Key Features:
1182 |     • Decision type filtering (Disputes, Regulatory, Court decisions)
1183 |     • Decision date range filtering for temporal analysis
1184 |     • Applicant and procuring entity filtering
1185 |     • Tender subject and content-based search
1186 |     • Decision number and reference tracking
1187 |     • Comprehensive metadata extraction
1188 |     
1189 |     Public Procurement Decision Types:
1190 |     • Uyuşmazlık Kararları: Dispute resolution decisions
1191 |     • Düzenleyici Kararlar: Regulatory and interpretive decisions
1192 |     • Mahkeme Kararları: Court decisions and judicial precedents
1193 |     
1194 |     Procurement Law Areas:
1195 |     • Tender procedure compliance and violations
1196 |     • Bid evaluation and award criteria disputes
1197 |     • Contractor qualification and eligibility
1198 |     • Contract modification and scope changes
1199 |     • Performance guarantees and penalty applications
1200 |     • Public procurement ethics and transparency
1201 |     • Emergency procurement and exceptional procedures
1202 |     
1203 |     Use cases:
1204 |     • Public procurement law research and compliance guidance
1205 |     • Tender dispute resolution precedent analysis
1206 |     • Government contracting risk assessment
1207 |     • Procurement policy and regulatory interpretation
1208 |     • Academic public administration and law study
1209 |     • Legal strategy development for procurement disputes
1210 |     
1211 |     Returns structured procurement authority data with comprehensive case metadata.
1212 |     Use get_kik_document for full decision texts with detailed reasoning.
1213 |     """
1214 |     args = {}
1215 |     for field in ["karar_tipi", "karar_metni", "basvuru_konusu_ihale", "karar_tarihi_baslangic"]:
1216 |         if getattr(request, field):
1217 |             args[field] = getattr(request, field)
1218 |     return await call_mcp_tool("search_kik_decisions", args)
1219 | 
1220 | @app.get("/api/kik/document/{decision_id}", tags=["KİK"])
1221 | async def get_kik_document(decision_id: str):
1222 |     """
1223 |     Retrieve the full text of a Public Procurement Authority (KIK) decision in paginated Markdown format.
1224 |     
1225 |     This tool fetches complete public procurement decisions and converts them from PDF to clean,
1226 |     readable Markdown format. Content is paginated into manageable chunks for processing lengthy
1227 |     procurement law decisions and regulatory interpretations.
1228 |     
1229 |     Input Requirements:
1230 |     • decision_id: KIK decision ID (base64 encoded karar_id) from search results
1231 |     • Decision ID must be non-empty string
1232 |     
1233 |     Output Format:
1234 |     • Clean Markdown text converted from original PDF documents
1235 |     • Organized sections: case summary, legal analysis, regulatory interpretation, decision
1236 |     • Proper formatting for procurement law citations and regulatory references
1237 |     • Paginated content with navigation information
1238 |     • Metadata including PDF source link and document information
1239 |     
1240 |     Public Procurement Decision Content:
1241 |     • Complete procurement dispute analysis and resolution
1242 |     • Detailed examination of tender procedures and compliance
1243 |     • Citation of procurement laws, regulations, and precedents
1244 |     • Final determination on procurement violations with corrective measures
1245 |     • Regulatory guidance and policy interpretations
1246 |     • Contractor liability and penalty determinations
1247 |     
1248 |     Use for:
1249 |     • Reading full public procurement authority decisions
1250 |     • Procurement law research and precedent analysis
1251 |     • Government contracting compliance and risk assessment
1252 |     • Tender dispute resolution strategy development
1253 |     • Academic public administration and procurement law study
1254 |     • Policy analysis and regulatory interpretation
1255 |     """
1256 |     return await call_mcp_tool("get_kik_document_markdown", {"decision_id": decision_id})
1257 | 
1258 | @app.post("/api/rekabet/search", tags=["Rekabet"], summary="Search Competition Authority")
1259 | async def search_rekabet(request: RekabetSearchRequest):
1260 |     """
1261 |     Search Competition Authority (Rekabet Kurumu) decisions with comprehensive filtering for competition law and antitrust research.
1262 |     
1263 |     The Competition Authority (Rekabet Kurumu) is Turkey's competition authority, responsible for enforcing antitrust laws,
1264 |     preventing anti-competitive practices, and regulating mergers and acquisitions. This tool
1265 |     provides access to official competition law decisions and regulatory interpretations.
1266 |     
1267 |     Key Features:
1268 |     • Decision type filtering (Mergers, Violations, Exemptions, etc.)
1269 |     • Title and content-based text search with exact phrase matching
1270 |     • Publication date filtering
1271 |     • Case year and decision number filtering
1272 |     • Pagination support for large result sets
1273 |     
1274 |     Competition Law Decision Types:
1275 |     • Birleşme ve Devralma: Merger and acquisition approvals
1276 |     • Rekabet İhlali: Competition violation investigations
1277 |     • Muafiyet: Exemption and negative clearance decisions
1278 |     • Geçici Tedbir: Interim measures and emergency orders
1279 |     • Sektör İncelemesi: Sector inquiry and market studies
1280 |     • Diğer: Other regulatory and interpretive decisions
1281 |     
1282 |     Competition Law Areas:
1283 |     • Anti-competitive agreements and cartels
1284 |     • Abuse of dominant market position
1285 |     • Merger control and market concentration
1286 |     • Vertical agreements and distribution restrictions
1287 |     • Unfair competition and consumer protection
1288 |     • Market definition and economic analysis
1289 |     
1290 |     Advanced Search:
1291 |     • Exact phrase matching with double quotes for precise legal terms
1292 |     • Content search across full decision texts (PdfText parameter)
1293 |     • Title search for specific case names or topics
1294 |     • Date range filtering for temporal analysis
1295 |     
1296 |     Example for exact phrase search: PdfText=\"tender process\" consultancy
1297 |     
1298 |     Use cases:
1299 |     • Competition law research and precedent analysis
1300 |     • Merger and acquisition due diligence
1301 |     • Antitrust compliance and risk assessment
1302 |     • Market analysis and competitive intelligence
1303 |     • Academic competition economics study
1304 |     • Legal strategy development for competition cases
1305 |     
1306 |     Returns structured competition authority data with comprehensive metadata.
1307 |     Use get_rekabet_document for full decision texts (paginated PDF conversion).
1308 |     """
1309 |     args = {"page": request.page}
1310 |     for field in ["KararTuru", "PdfText", "YayinlanmaTarihi"]:
1311 |         if getattr(request, field):
1312 |             args[field] = getattr(request, field)
1313 |     return await call_mcp_tool("search_rekabet_kurumu_decisions", args)
1314 | 
1315 | @app.get("/api/rekabet/document/{karar_id}", tags=["Rekabet"])
1316 | async def get_rekabet_document(karar_id: str, page_number: int = 1):
1317 |     """
1318 |     Retrieve the full text of a Competition Authority (Rekabet Kurumu) decision in paginated Markdown format converted from PDF.
1319 |     
1320 |     This tool fetches complete competition authority decisions and converts them from PDF to clean,
1321 |     readable Markdown format. Content is paginated for easier processing of lengthy competition law decisions.
1322 |     
1323 |     Input Requirements:
1324 |     • karar_id: GUID (kararId) from search_rekabet_kurumu_decisions results
1325 |     • page_number: Page number for pagination (1-indexed, default: 1)
1326 |     
1327 |     Output Format:
1328 |     • Clean Markdown text converted from original PDF documents
1329 |     • Organized sections: case summary, market analysis, legal reasoning, decision
1330 |     • Proper formatting for competition law citations and references
1331 |     • Paginated content with navigation information
1332 |     • Metadata including PDF source link and document information
1333 |     
1334 |     Competition Authority Decision Content:
1335 |     • Complete competition law analysis and market assessment
1336 |     • Detailed examination of anti-competitive practices
1337 |     • Economic analysis and market definition studies
1338 |     • Citation of competition laws, regulations, and precedents
1339 |     • Final determination on competition violations with remedies
1340 |     • Merger and acquisition approval conditions
1341 |     • Regulatory guidance and policy interpretations
1342 |     
1343 |     Use for:
1344 |     • Reading full competition authority decisions
1345 |     • Competition law research and precedent analysis
1346 |     • Market analysis and economic impact assessment
1347 |     • Antitrust compliance and risk evaluation
1348 |     • Academic competition economics and law study
1349 |     • Legal strategy development for competition cases
1350 |     """
1351 |     return await call_mcp_tool("get_rekabet_kurumu_document", {
1352 |         "karar_id": karar_id, "page_number": page_number
1353 |     })
1354 | 
1355 | # ============================================================================
1356 | # SAYISTAY (COURT OF ACCOUNTS) ENDPOINTS - 6 TOOLS
1357 | # ============================================================================
1358 | 
1359 | @app.post("/api/sayistay/search-genel-kurul", tags=["Sayıştay"], summary="Search Court of Accounts (General Assembly)")
1360 | async def search_sayistay_genel_kurul(request: SayistaySearchRequest):
1361 |     """
1362 |     Search Sayıştay Genel Kurul (General Assembly) decisions - highest-level audit precedents and interpretive rulings with keyword-based filtering.
1363 |     
1364 |     The General Assembly represents the highest decision-making body of Turkey's Court of Accounts,
1365 |     issuing authoritative interpretations of audit laws, precedential rulings on complex accountability
1366 |     issues, and binding guidance for audit practice. These decisions establish fundamental principles
1367 |     for public financial oversight and accountability standards.
1368 |     
1369 |     Key Features:
1370 |     • Keyword-based search with AND logic for precise case finding
1371 |     • Highest-level audit precedent identification
1372 |     • Interpretive ruling analysis and legal guidance extraction
1373 |     • Complex accountability issue resolution tracking
1374 |     • Pagination support for comprehensive result sets
1375 |     
1376 |     General Assembly Decision Authority:
1377 |     • Ultimate audit law interpretation and clarification
1378 |     • Precedential rulings binding on all audit chambers
1379 |     • Complex inter-chamber jurisdiction dispute resolution
1380 |     • Policy guidance for audit methodology and standards
1381 |     • Final determination on constitutional audit questions
1382 |     
1383 |     Public Audit Areas:
1384 |     • Government budget execution and compliance
1385 |     • Public institution financial management
1386 |     • State-owned enterprise oversight and accountability
1387 |     • Local government and municipal audit standards
1388 |     • Public procurement oversight and compliance monitoring
1389 |     • Performance audit methodology and effectiveness standards
1390 |     • Public revenue collection and tax administration audit
1391 |     
1392 |     Use Cases:
1393 |     • Research authoritative audit law interpretations
1394 |     • Find binding precedents for complex audit questions
1395 |     • Study evolution of public accountability standards
1396 |     • Analyze audit methodology development and refinement
1397 |     • Academic public administration and audit research
1398 |     • Government policy and accountability framework analysis
1399 |     
1400 |     Returns structured General Assembly data with comprehensive legal precedent metadata.
1401 |     Use get_sayistay_genel_kurul_document for full decision texts with detailed reasoning.
1402 |     """
1403 |     return await call_mcp_tool("search_sayistay_genel_kurul", {
1404 |         "keywords": request.keywords, "page_to_fetch": request.page_to_fetch
1405 |     })
1406 | 
1407 | @app.get("/api/sayistay/genel-kurul-document", tags=["Sayıştay"])
1408 | async def get_sayistay_genel_kurul_document(document_url: str, page_number: int = 1):
1409 |     """
1410 |     Retrieve the full text of a Sayıştay Genel Kurul decision document in Markdown format for detailed analysis.
1411 |     
1412 |     This tool converts the original General Assembly decision document into clean,
1413 |     readable Markdown format suitable for legal analysis and research.
1414 |     
1415 |     Input Requirements:
1416 |     • decision_id: Use the ID from search_sayistay_genel_kurul results
1417 |     • Decision ID must be non-empty string
1418 |     
1419 |     Output Format:
1420 |     • Clean Markdown text with legal formatting preserved
1421 |     • Structured content with reasoning and conclusions
1422 |     • Removes technical artifacts from source documents
1423 |     
1424 |     Use for:
1425 |     • Detailed analysis of audit precedents
1426 |     • Research on public accountability standards
1427 |     • Citation and reference building
1428 |     • Legal interpretation and case study development
1429 |     """
1430 |     return await call_mcp_tool("get_sayistay_genel_kurul_document_markdown", {
1431 |         "document_url": document_url, "page_number": page_number
1432 |     })
1433 | 
1434 | @app.post("/api/sayistay/search-temyiz-kurulu", tags=["Sayıştay"], summary="Search Court of Accounts (Appeals Board)")
1435 | async def search_sayistay_temyiz_kurulu(request: SayistaySearchRequest):
1436 |     """
1437 |     Search Sayıştay Temyiz Kurulu (Appeals Board) decisions - appellate review of audit chamber findings with advanced filtering and institutional analysis.
1438 |     
1439 |     The Appeals Board serves as the intermediate appellate authority in Turkey's audit system,
1440 |     reviewing first-instance chamber decisions on audit findings, liability determinations,
1441 |     and sanctions. Appeals Board decisions refine audit standards and ensure consistency
1442 |     across different audit chambers.
1443 |     
1444 |     Key Features:
1445 |     • Chamber-specific filtering for targeted appeals analysis
1446 |     • Institutional type categorization for audit pattern analysis
1447 |     • Decision and account year filtering for temporal trends
1448 |     • Audit subject matter classification and content search
1449 |     • Appeal outcome tracking and precedent identification
1450 |     • Pagination support for comprehensive coverage
1451 |     
1452 |     Appeals Board Authority:
1453 |     • Review and modification of chamber audit findings
1454 |     • Standardization of audit liability determinations
1455 |     • Consistency enforcement across audit chambers
1456 |     • Intermediate precedent development for audit practice
1457 |     • Quality control for first-instance audit decisions
1458 |     
1459 |     Audit Review Areas:
1460 |     • Government agency financial accountability appeals
1461 |     • Municipality and local government audit review
1462 |     • State enterprise oversight and performance audit appeals
1463 |     • Educational institution audit finding review
1464 |     • Healthcare system financial accountability appeals
1465 |     • Public procurement oversight and compliance review
1466 |     • Tax administration and revenue audit appeals
1467 |     
1468 |     Use Cases:
1469 |     • Research audit appeals patterns and outcomes
1470 |     • Study chamber decision consistency and standards
1471 |     • Analyze audit liability determination evolution
1472 |     • Find precedents for specific audit finding types
1473 |     • Track institutional audit patterns and compliance
1474 |     • Academic public accountability and audit law research
1475 |     
1476 |     Returns structured Appeals Board data with comprehensive appellate analysis metadata.
1477 |     Use get_sayistay_temyiz_kurulu_document for full appeals decisions with detailed reasoning.
1478 |     """
1479 |     return await call_mcp_tool("search_sayistay_temyiz_kurulu", {
1480 |         "keywords": request.keywords, "page_to_fetch": request.page_to_fetch
1481 |     })
1482 | 
1483 | @app.get("/api/sayistay/temyiz-kurulu-document", tags=["Sayıştay"])
1484 | async def get_sayistay_temyiz_kurulu_document(document_url: str, page_number: int = 1):
1485 |     """
1486 |     Retrieve the full text of a Sayıştay Temyiz Kurulu decision document in Markdown format for detailed appeals analysis.
1487 |     
1488 |     This tool converts the original Appeals Board decision document into clean,
1489 |     readable Markdown format for analysis of appellate reasoning and standards.
1490 |     
1491 |     Input Requirements:
1492 |     • decision_id: Use the ID from search_sayistay_temyiz_kurulu results
1493 |     • Decision ID must be non-empty string
1494 |     
1495 |     Output Format:
1496 |     • Clean Markdown text with appellate reasoning preserved
1497 |     • Structured content with original findings and appeals analysis
1498 |     • Removes technical artifacts from source documents
1499 |     
1500 |     Use for:
1501 |     • Analysis of appeals board reasoning and standards
1502 |     • Research on audit liability determination evolution
1503 |     • Understanding chamber decision review criteria
1504 |     • Precedent analysis for audit appeal cases
1505 |     """
1506 |     return await call_mcp_tool("get_sayistay_temyiz_kurulu_document_markdown", {
1507 |         "document_url": document_url, "page_number": page_number
1508 |     })
1509 | 
1510 | @app.post("/api/sayistay/search-daire", tags=["Sayıştay"], summary="Search Court of Accounts (Chambers)")
1511 | async def search_sayistay_daire(request: SayistaySearchRequest):
1512 |     """
1513 |     Search Sayıştay Daire (Chamber) decisions - first-instance audit findings and sanctions from individual audit chambers with comprehensive filtering and subject categorization.
1514 |     
1515 |     Chamber decisions represent first-instance audit findings, sanctions, and
1516 |     liability determinations issued by specialized audit chambers. These form
1517 |     the foundation of Turkey's public financial accountability system.
1518 |     
1519 |     Key Features:
1520 |     • Chamber-specific filtering (8 specialized audit chambers)
1521 |     • Decision and account year filtering (2012-2025)
1522 |     • Public administration type categorization
1523 |     • Subject matter classification and full-text search
1524 |     • Audit report tracking and institutional analysis
1525 |     
1526 |     Use Cases:
1527 |     • Research specific audit findings and sanctions
1528 |     • Study chamber specialization and jurisdiction
1529 |     • Analyze audit patterns by institution type
1530 |     • Find precedents for financial irregularities
1531 |     • Track audit evolution across fiscal years
1532 |     """
1533 |     return await call_mcp_tool("search_sayistay_daire", {
1534 |         "keywords": request.keywords, "page_to_fetch": request.page_to_fetch
1535 |     })
1536 | 
1537 | @app.get("/api/sayistay/daire-document", tags=["Sayıştay"])
1538 | async def get_sayistay_daire_document(document_url: str, page_number: int = 1):
1539 |     """
1540 |     Retrieve the full text of a Sayıştay Daire decision document in Markdown format for detailed audit findings analysis.
1541 |     
1542 |     This tool converts the original chamber decision document into clean,
1543 |     readable Markdown format for analysis of first-instance audit findings.
1544 |     
1545 |     Input Requirements:
1546 |     • decision_id: Use the ID from search_sayistay_daire results  
1547 |     • Decision ID must be non-empty string
1548 |     
1549 |     Output Format:
1550 |     • Clean Markdown text with audit findings preserved
1551 |     • Structured content with violations and sanctions
1552 |     • Removes technical artifacts from source documents
1553 |     
1554 |     Use for:
1555 |     • Detailed analysis of audit findings and methodology
1556 |     • Research on specific types of financial irregularities
1557 |     • Understanding chamber jurisdiction and specialization
1558 |     • Case study development for audit training and compliance
1559 |     """
1560 |     return await call_mcp_tool("get_sayistay_daire_document_markdown", {
1561 |         "document_url": document_url, "page_number": page_number
1562 |     })
1563 | 
1564 | # ============================================================================
1565 | # ADDITIONAL API ENDPOINTS
1566 | # ============================================================================
1567 | 
1568 | @app.get("/api/databases")
1569 | async def list_databases():
1570 |     """Comprehensive database information with tool mappings"""
1571 |     return {
1572 |         "total_tools": 33,
1573 |         "databases": {
1574 |             "yargitay": {
1575 |                 "name": "Yargıtay (Court of Cassation)",
1576 |                 "description": "Turkey's Supreme Court for civil and criminal matters",
1577 |                 "tools": 4,
1578 |                 "chambers": 52,
1579 |                 "search_tools": ["search_yargitay", "search_yargitay_bedesten"],
1580 |                 "document_tools": ["get_yargitay_document", "get_yargitay_bedesten_document"]
1581 |             },
1582 |             "danistay": {
1583 |                 "name": "Danıştay (Council of State)", 
1584 |                 "description": "Turkey's Supreme Administrative Court",
1585 |                 "tools": 5,
1586 |                 "chambers": 27,
1587 |                 "search_tools": ["search_danistay_keyword", "search_danistay_detailed", "search_danistay_bedesten"],
1588 |                 "document_tools": ["get_danistay_document", "get_danistay_bedesten_document"]
1589 |             },
1590 |             "anayasa": {
1591 |                 "name": "Anayasa Mahkemesi (Constitutional Court)",
1592 |                 "description": "Constitutional review and individual applications",
1593 |                 "tools": 4,
1594 |                 "features": ["norm_control", "individual_applications", "human_rights"]
1595 |             },
1596 |             "rekabet": {
1597 |                 "name": "Rekabet Kurumu (Competition Authority)",
1598 |                 "description": "Antitrust and merger control",
1599 |                 "tools": 2,
1600 |                 "coverage": ["mergers", "cartels", "market_abuse", "sector_inquiries"]
1601 |             },
1602 |             "kik": {
1603 |                 "name": "Kamu İhale Kurulu (Public Procurement Authority)",
1604 |                 "description": "Government procurement disputes",
1605 |                 "tools": 2,
1606 |                 "coverage": ["procurement_disputes", "regulatory_decisions", "tender_violations"]
1607 |             },
1608 |             "sayistay": {
1609 |                 "name": "Sayıştay (Court of Accounts)",
1610 |                 "description": "Public audit and financial accountability", 
1611 |                 "tools": 6,
1612 |                 "levels": ["general_assembly", "appeals_board", "audit_chambers"]
1613 |             },
1614 |             "emsal": {
1615 |                 "name": "Emsal (UYAP Precedents)",
1616 |                 "description": "Cross-court precedent database",
1617 |                 "tools": 2,
1618 |                 "coverage": ["multi_court", "precedent_analysis"]
1619 |             },
1620 |             "uyusmazlik": {
1621 |                 "name": "Uyuşmazlık Mahkemesi (Jurisdictional Disputes)",
1622 |                 "description": "Inter-court jurisdiction disputes",
1623 |                 "tools": 2,
1624 |                 "specialization": "jurisdictional_conflicts"
1625 |             },
1626 |             "bedesten_courts": {
1627 |                 "name": "Bedesten API Courts (Local/Appellate/KYB)",
1628 |                 "description": "First instance, appellate, and extraordinary appeal courts",
1629 |                 "tools": 6,
1630 |                 "courts": ["yerel_hukuk", "istinaf_hukuk", "kyb"],
1631 |                 "coverage": "complete_court_hierarchy"
1632 |             }
1633 |         }
1634 |     }
1635 | 
1636 | @app.get("/api/stats")
1637 | async def get_statistics():
1638 |     """Comprehensive API statistics and capabilities"""
1639 |     uptime = (datetime.now() - SERVER_START_TIME).total_seconds()
1640 |     return {
1641 |         "server": {
1642 |             "uptime_seconds": uptime,
1643 |             "start_time": SERVER_START_TIME.isoformat(),
1644 |             "version": "1.0.0",
1645 |             "status": "operational"
1646 |         },
1647 |         "coverage": {
1648 |             "total_tools": 33,
1649 |             "total_databases": 9,
1650 |             "total_chambers": 79,  # 52 Yargıtay + 27 Danıştay
1651 |             "search_tools": 16,
1652 |             "document_tools": 17
1653 |         },
1654 |         "capabilities": {
1655 |             "advanced_search_operators": True,
1656 |             "exact_phrase_search": True,
1657 |             "date_range_filtering": True,
1658 |             "chamber_filtering": True,
1659 |             "boolean_logic": True,
1660 |             "wildcard_search": True,
1661 |             "pagination": True,
1662 |             "markdown_conversion": True,
1663 |             "pdf_processing": True,
1664 |             "dual_api_support": True
1665 |         },
1666 |         "legal_coverage": {
1667 |             "supreme_courts": ["Yargıtay", "Danıştay"],
1668 |             "constitutional_law": "Anayasa Mahkemesi",
1669 |             "administrative_law": "Full coverage",
1670 |             "competition_law": "Rekabet Kurumu",
1671 |             "public_procurement": "KİK",
1672 |             "public_audit": "Sayıştay",
1673 |             "court_hierarchy": "Complete (Local → Appellate → Supreme)",
1674 |             "specialized_courts": ["Uyuşmazlık", "Constitutional", "Administrative"]
1675 |         }
1676 |     }
1677 | 
1678 | if __name__ == "__main__":
1679 |     import uvicorn
1680 |     uvicorn.run(app, host="0.0.0.0", port=8000)
1681 | 
```
Page 9/11FirstPrevNextLast