forked from saidsurucu/yargi-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_fastapi_app.py
More file actions
1680 lines (1450 loc) · 75.8 KB
/
example_fastapi_app.py
File metadata and controls
1680 lines (1450 loc) · 75.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
FastAPI Comprehensive Endpoints with Complete MCP Documentation
This is the complete version with all descriptions and docstrings from MCP server.
"""
import os
from typing import List, Dict, Any, Optional
from datetime import datetime
from fastapi import FastAPI, HTTPException, Query, Depends, Body
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
import json
# Import the main MCP app
from mcp_server_main import app as mcp_server
# Create MCP ASGI app
mcp_asgi_app = mcp_server.http_app(path="/mcp")
# Create FastAPI app with MCP lifespan
app = FastAPI(
title="Yargı MCP API - Turkish Legal Database REST API",
description="""
Comprehensive REST API for Turkish Legal Databases with complete MCP tool coverage.
This API provides access to 8 major Turkish legal institutions including:
• Yargıtay (Court of Cassation) - Supreme civil/criminal court
• Danıştay (Council of State) - Supreme administrative court
• Constitutional Court - Constitutional review and individual applications
• Competition Authority - Antitrust and merger decisions
• Public Procurement Authority - Government contracting disputes
• Court of Accounts - Public audit and accountability
• Emsal (UYAP Precedents) - Cross-court precedent database
• Local and Appellate Courts - First and second instance decisions
Features complete coverage of 33 MCP tools with enhanced documentation,
typed request models, and comprehensive legal context.
Tool Properties (from MCP annotations):
• Read-only: All tools are read-only and do not modify system state
• Idempotent: Same inputs produce same outputs for reliable research
• Open-world search: Search tools explore comprehensive legal databases
• Deterministic document retrieval: Document tools return consistent content
""",
version="1.0.0",
lifespan=mcp_asgi_app.lifespan
)
# Add CORS middleware
cors_origins = os.getenv("ALLOWED_ORIGINS", "*").split(",")
app.add_middleware(
CORSMiddleware,
allow_origins=cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Mount MCP server
app.mount("/mcp-server", mcp_asgi_app)
# Response models (keeping from original)
class ToolInfo(BaseModel):
name: str
description: str
parameters: Dict[str, Any]
class ServerInfo(BaseModel):
name: str
version: str
description: str
tools_count: int
databases: List[str]
mcp_endpoint: str
api_docs: str
class HealthCheck(BaseModel):
status: str
timestamp: datetime
uptime_seconds: Optional[float] = None
tools_operational: bool
# Track server start time
SERVER_START_TIME = datetime.now()
# MCP tool caller helper
async def call_mcp_tool(tool_name: str, arguments: Dict[str, Any]):
"""Call an MCP tool with given arguments"""
try:
tool = mcp_server._tool_manager._tools.get(tool_name)
if not tool:
raise HTTPException(status_code=404, detail=f"Tool '{tool_name}' not found")
result = await tool.fn(**arguments)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=f"Tool execution failed: {str(e)}")
# ============================================================================
# COMPREHENSIVE REQUEST MODELS WITH FULL MCP DOCUMENTATION
# ============================================================================
class YargitaySearchRequest(BaseModel):
"""
Search request for Court of Cassation (Yargıtay) decisions using primary official API.
The Court of Cassation is Turkey's highest court for civil and criminal matters,
equivalent to a Supreme Court. Provides access to comprehensive supreme court precedents.
"""
arananKelime: str = Field(
...,
description="""Keyword to search for with advanced operators:
• Space between words = OR logic (arsa payı → "arsa" OR "payı")
• "exact phrase" = Exact match ("arsa payı" → exact phrase)
• word1+word2 = AND logic (arsa+payı → both words required)
• word* = Wildcard (bozma* → bozma, bozması, bozmanın, etc.)
• +"phrase1" +"phrase2" = Multiple required phrases
• +"required" -"excluded" = Include and exclude
Turkish Examples:
• Simple OR: arsa payı (~523K results)
• Exact phrase: "arsa payı" (~22K results)
• Multiple AND: +"arsa payı" +"bozma sebebi" (~234 results)
• Wildcard: bozma* (bozma, bozması, bozmanın, etc.)
• Exclude: +"arsa payı" -"kira sözleşmesi"
""",
example='+"mülkiyet hakkı" +"iptal"'
)
birimYrgKurulDaire: Optional[str] = Field(
"",
description="""Chamber/board selection (52 options):
Civil Chambers: 1-23. Hukuk Dairesi
Criminal Chambers: 1-23. Ceza Dairesi
General Assemblies: Hukuk Genel Kurulu, Ceza Genel Kurulu
Special Boards: Hukuk/Ceza Daireleri Başkanlar Kurulu, Büyük Genel Kurulu
Use "" for ALL chambers or specify exact chamber name.
""",
example="1. Hukuk Dairesi"
)
baslangicTarihi: Optional[str] = Field(None, description="Start date (DD.MM.YYYY)", example="01.01.2020")
bitisTarihi: Optional[str] = Field(None, description="End date (DD.MM.YYYY)", example="31.12.2024")
pageSize: int = Field(20, description="Results per page (1-100)", ge=1, le=100, example=20)
class YargitayBedestenSearchRequest(BaseModel):
"""
Search request for Court of Cassation using Bedesten API (alternative source).
Complements primary API with different search capabilities and recent decisions.
"""
phrase: str = Field(
...,
description="""Aranacak kavram/kelime. İki farklı arama türü desteklenir:
• Normal arama: "mülkiyet hakkı" - kelimeler ayrı ayrı aranır
• Tam cümle arama: "\"mülkiyet hakkı\"" - tırnak içindeki ifade aynen aranır
Tam cümle aramalar daha kesin sonuçlar verir.
Search phrase with exact matching support:
• Regular search: "mülkiyet hakkı" - searches individual words separately
• Exact phrase search: "\"mülkiyet hakkı\"" - searches for exact phrase as unit
Exact phrase search provides more precise results with fewer false positives.
""",
example="\"mülkiyet hakkı\""
)
birimAdi: Optional[str] = Field(
None,
description="""Daire/Kurul seçimi (52 seçenek - ana API ile aynı):
• Hukuk daireleri: 1. Hukuk Dairesi - 23. Hukuk Dairesi
• Ceza daireleri: 1. Ceza Dairesi - 23. Ceza Dairesi
• Genel kurullar: Hukuk Genel Kurulu, Ceza Genel Kurulu
• Özel kurullar: Hukuk/Ceza Daireleri Başkanlar Kurulu, Büyük Genel Kurulu
Chamber filtering (52 options - same as primary API):
• Civil chambers: 1. Hukuk Dairesi through 23. Hukuk Dairesi
• Criminal chambers: 1. Ceza Dairesi through 23. Ceza Dairesi
• General assemblies: Hukuk Genel Kurulu, Ceza Genel Kurulu
• Special boards: Hukuk/Ceza Daireleri Başkanlar Kurulu, Büyük Genel Kurulu
Use None for ALL chambers, or specify exact chamber name.
""",
example="1. Hukuk Dairesi"
)
kararTarihiStart: Optional[str] = Field(
None,
description="""Karar başlangıç tarihi (ISO 8601 formatı):
Format: YYYY-MM-DDTHH:MM:SS.000Z
Örnek: "2024-01-01T00:00:00.000Z" - 1 Ocak 2024'ten itibaren kararlar
kararTarihiEnd ile birlikte tarih aralığı filtrelemesi için kullanılır.
Decision start date filter (ISO 8601 format):
Format: YYYY-MM-DDTHH:MM:SS.000Z
Example: "2024-01-01T00:00:00.000Z" for decisions from Jan 1, 2024
Use with kararTarihiEnd for date range filtering.
""",
example="2024-01-01T00:00:00.000Z"
)
kararTarihiEnd: Optional[str] = Field(
None,
description="""Karar bitiş tarihi (ISO 8601 formatı):
Format: YYYY-MM-DDTHH:MM:SS.000Z
Örnek: "2024-12-31T23:59:59.999Z" - 31 Aralık 2024'e kadar kararlar
kararTarihiStart ile birlikte tarih aralığı filtrelemesi için kullanılır.
Decision end date filter (ISO 8601 format):
Format: YYYY-MM-DDTHH:MM:SS.000Z
Example: "2024-12-31T23:59:59.999Z" for decisions until Dec 31, 2024
Use with kararTarihiStart for date range filtering.
""",
example="2024-12-31T23:59:59.999Z"
)
pageSize: int = Field(20, description="Results per page (1-100)", ge=1, le=100)
class DanistayKeywordSearchRequest(BaseModel):
"""
Keyword-based search for Council of State (Danıştay) decisions with Boolean logic.
The Council of State is Turkey's highest administrative court, providing final
rulings on administrative law matters with Boolean keyword operators.
"""
andKelimeler: List[str] = Field(
...,
description="ALL keywords must be present (AND logic)",
example=["idari işlem", "iptal"]
)
orKelimeler: Optional[List[str]] = Field(
None,
description="ANY keyword can be present (OR logic)",
example=["ruhsat", "izin", "lisans"]
)
notKelimeler: Optional[List[str]] = Field(
None,
description="EXCLUDE if keywords present (NOT logic)",
example=["vergi"]
)
pageSize: int = Field(20, description="Results per page (1-100)", ge=1, le=100)
class DanistayDetailedSearchRequest(BaseModel):
"""
Detailed search for Council of State decisions with comprehensive filtering.
Provides the most comprehensive search capabilities for administrative court decisions.
"""
daire: Optional[str] = Field(
None,
description="Chamber/Department filter (1. Daire through 17. Daire, special councils)",
example="3. Daire"
)
baslangicTarihi: Optional[str] = Field(None, description="Start date (DD.MM.YYYY)", example="01.01.2020")
bitisTarihi: Optional[str] = Field(None, description="End date (DD.MM.YYYY)", example="31.12.2024")
esas: Optional[str] = Field(None, description="Case number (Esas No)", example="2024/123")
karar: Optional[str] = Field(None, description="Decision number (Karar No)", example="2024/456")
class DanistayBedestenSearchRequest(BaseModel):
"""
Council of State search using Bedesten API with chamber filtering and exact phrase search.
Provides access to administrative court decisions with 27 chamber options.
"""
phrase: str = Field(..., description="Search phrase (supports exact matching with quotes)")
birimAdi: Optional[str] = Field(
None,
description="""Chamber filtering (27 options):
Main Councils: Büyük Gen.Kur., İdare Dava Daireleri Kurulu, Vergi Dava Daireleri Kurulu
Chambers: 1. Daire through 17. Daire
Military: Askeri Yüksek İdare Mahkemesi chambers
""",
example="3. Daire"
)
kararTarihiStart: Optional[str] = Field(None, description="Start date (ISO 8601)")
kararTarihiEnd: Optional[str] = Field(None, description="End date (ISO 8601)")
pageSize: int = Field(20, description="Results per page", ge=1, le=100)
class EmsalSearchRequest(BaseModel):
"""
Search Precedent (Emsal) decisions from UYAP system across multiple court levels.
Provides access to precedent decisions from various Turkish courts.
"""
keyword: str = Field(..., description="Search keyword across decision texts")
decision_year_karar: Optional[str] = Field(None, description="Decision year filter", example="2024")
results_per_page: int = Field(20, description="Results per page", ge=1, le=100)
class UyusmazlikSearchRequest(BaseModel):
"""
Search Court of Jurisdictional Disputes decisions.
Resolves jurisdictional disputes between different court systems.
"""
keywords: List[str] = Field(..., description="Search keywords", example=["görev", "uyuşmazlık"])
page_to_fetch: int = Field(1, description="Page number", ge=1)
class AnayasaNormSearchRequest(BaseModel):
"""
Search Constitutional Court norm control (judicial review) decisions.
Turkey's highest constitutional authority for reviewing law constitutionality.
"""
keywords_all: List[str] = Field(..., description="All required keywords", example=["eğitim hakkı", "anayasa"])
period: Optional[str] = Field(None, description="Constitutional period (1=1961, 2=1982)", example="2")
application_type: Optional[str] = Field(None, description="Application type (1=İptal)", example="1")
results_per_page: int = Field(20, description="Results per page", ge=1, le=100)
class AnayasaBireyselSearchRequest(BaseModel):
"""
Search Constitutional Court individual application decisions.
Human rights violation cases through individual citizen petitions.
"""
keywords: List[str] = Field(..., description="Search keywords", example=["ifade özgürlüğü", "basın"])
page_to_fetch: int = Field(1, description="Page number", ge=1)
class KikSearchRequest(BaseModel):
"""
Search Public Procurement Authority (KİK) decisions.
Government procurement disputes and regulatory interpretations.
"""
karar_tipi: Optional[str] = Field(
None,
description="Decision type (rbUyusmazlik=Disputes, rbDuzenleyici=Regulatory, rbMahkeme=Court)",
example="rbUyusmazlik"
)
karar_metni: Optional[str] = Field(None, description="Decision text search", example="ihale iptali")
basvuru_konusu_ihale: Optional[str] = Field(None, description="Tender subject", example="danışmanlık")
karar_tarihi_baslangic: Optional[str] = Field(None, description="Start date", example="01.01.2023")
class RekabetSearchRequest(BaseModel):
"""
Search Competition Authority decisions.
Antitrust, merger control, and competition law enforcement.
"""
KararTuru: Optional[str] = Field(
None,
description="Decision type (Birleşme ve Devralma, Rekabet İhlali, Muafiyet, etc.)",
example="Birleşme ve Devralma"
)
PdfText: Optional[str] = Field(
None,
description="Full-text search in decisions. Use quotes for exact phrases.",
example="\"market definition\" telecommunications"
)
YayinlanmaTarihi: Optional[str] = Field(None, description="Publication date", example="01.01.2020")
page: int = Field(1, description="Page number", ge=1)
class BedestenSearchRequest(BaseModel):
"""
Generic search request for Bedesten API courts (Yerel Hukuk, İstinaf Hukuk, KYB).
Supports exact phrase search and date filtering.
"""
phrase: str = Field(
...,
description="Search phrase. Use quotes for exact matching: \"legal term\"",
example="\"sözleşme ihlali\""
)
kararTarihiStart: Optional[str] = Field(None, description="Start date (ISO 8601)")
kararTarihiEnd: Optional[str] = Field(None, description="End date (ISO 8601)")
pageSize: int = Field(20, description="Results per page", ge=1, le=100)
class SayistaySearchRequest(BaseModel):
"""
Search Court of Accounts (Sayıştay) decisions.
Public audit, accountability, and financial oversight decisions.
"""
keywords: List[str] = Field(..., description="Search keywords", example=["mali sorumluluk", "denetim"])
page_to_fetch: int = Field(1, description="Page number", ge=1)
# ============================================================================
# BASIC SERVER ENDPOINTS (keeping from original)
# ============================================================================
@app.get("/", response_model=ServerInfo)
async def root():
"""Get comprehensive server information with database coverage"""
return ServerInfo(
name="Yargı MCP Server - Turkish Legal Database API",
version="1.0.0",
description="Complete REST API for Turkish legal databases with 33 MCP tools",
tools_count=len(mcp_server._tool_manager._tools),
databases=[
"Yargıtay (Court of Cassation) - 4 tools",
"Danıştay (Council of State) - 5 tools",
"Emsal (UYAP Precedents) - 2 tools",
"Uyuşmazlık Mahkemesi (Jurisdictional Disputes) - 2 tools",
"Anayasa Mahkemesi (Constitutional Court) - 4 tools",
"Kamu İhale Kurulu (Public Procurement) - 2 tools",
"Rekabet Kurumu (Competition Authority) - 2 tools",
"Sayıştay (Court of Accounts) - 6 tools",
"Bedesten API Courts (Local/Appellate/KYB) - 6 tools"
],
mcp_endpoint="/mcp-server/mcp/",
api_docs="/docs"
)
@app.get("/health", response_model=HealthCheck)
async def health_check():
"""Health check with comprehensive system status"""
uptime = (datetime.now() - SERVER_START_TIME).total_seconds()
return HealthCheck(
status="healthy",
timestamp=datetime.now(),
uptime_seconds=uptime,
tools_operational=len(mcp_server._tool_manager._tools) == 33
)
@app.get("/api/tools", response_model=List[ToolInfo])
async def list_tools(
search: Optional[str] = Query(None, description="Search tools by name or description"),
database: Optional[str] = Query(None, description="Filter by database name")
):
"""List all 33 MCP tools with filtering capabilities"""
tools = []
for tool in mcp_server._tool_manager._tools.values():
if search and search.lower() not in tool.name.lower() and search.lower() not in tool.description.lower():
continue
if database:
db_lower = database.lower()
if db_lower not in tool.name.lower() and db_lower not in tool.description.lower():
continue
params = {}
if hasattr(tool, 'schema') and tool.schema:
if hasattr(tool.schema, 'parameters'):
params = tool.schema.parameters
elif hasattr(tool.schema, '__annotations__'):
params = {k: str(v) for k, v in tool.schema.__annotations__.items()}
tools.append(ToolInfo(
name=tool.name,
description=tool.description,
parameters=params
))
return tools
# ============================================================================
# YARGITAY (COURT OF CASSATION) ENDPOINTS - 4 TOOLS
# ============================================================================
@app.post(
"/api/yargitay/search",
tags=["Yargıtay"],
summary="Search Court of Cassation (Primary API)",
description="""Search Turkey's Supreme Court for civil and criminal precedents using advanced operators.
Key Features:
• Advanced search: AND (+), OR (space), NOT (-), wildcards (*), exact phrases ("")
• 52 chamber options (23 Civil + 23 Criminal + General Assemblies)
• Date range filtering • Case/decision number filtering • Pagination
Search Examples:
• OR search: property share (finds ANY words)
• Exact phrase: "property share" (finds exact phrase)
• AND required: +"property share" +"annulment reason"
• Wildcard: construct* (construction, constructive, etc.)
• Exclude terms: +"property share" -"construction contract"
Use for supreme court precedent research and legal principle analysis."""
)
async def search_yargitay(request: YargitaySearchRequest):
"""
Searches Court of Cassation (Yargıtay) decisions using the primary official API.
The Court of Cassation (Yargıtay) is Turkey's highest court for civil and criminal matters,
equivalent to a Supreme Court. This tool provides access to the most comprehensive database
of supreme court precedents with advanced search capabilities and filtering options.
Key Features:
• Advanced search operators (AND, OR, wildcards, exclusions)
• Chamber filtering: 52 options (23 Civil (Hukuk) + 23 Criminal (Ceza) + General Assemblies (Genel Kurullar))
• Date range filtering with DD.MM.YYYY format
• Case number filtering (Case No (Esas No) and Decision No (Karar No))
• Pagination support (1-100 results per page)
• Multiple sorting options (by case number, decision number, date)
SEARCH SYNTAX GUIDE:
• Words with spaces: OR search ("property share" finds ANY of the words)
• "Quotes": Exact phrase search ("property share" finds exact phrase)
• Plus sign (+): AND search (property+share requires both words)
• Asterisk (*): Wildcard (construct* matches variations)
• Minus sign (-): Exclude terms (avoid unwanted results)
Common Search Patterns:
• Simple OR: property share (finds ~523K results)
• Exact phrase: "property share" (finds ~22K results)
• Multiple required: +"property share" +"annulment reason (bozma sebebi)" (finds ~234 results)
• Wildcard expansion: construct* (matches construction, constructive, etc.)
• Exclude unwanted: +"property share" -"construction contract"
Use cases:
• Research supreme court precedents and legal principles
• Find decisions from specific chambers (Civil (Hukuk) vs Criminal (Ceza))
• Search for interpretations of specific legal concepts
• Analyze court reasoning on complex legal issues
• Track legal developments over time periods
Returns structured search results with decision metadata. Use get_yargitay_document_markdown()
to retrieve full decision texts for detailed analysis.
"""
args = {
"arananKelime": request.arananKelime,
"birimYrgKurulDaire": request.birimYrgKurulDaire,
"pageSize": request.pageSize
}
if request.baslangicTarihi:
args["baslangicTarihi"] = request.baslangicTarihi
if request.bitisTarihi:
args["bitisTarihi"] = request.bitisTarihi
return await call_mcp_tool("search_yargitay_detailed", args)
@app.post(
"/api/yargitay/search-bedesten",
tags=["Yargıtay"],
summary="Search Court of Cassation (Bedesten API)",
description="""Alternative Court of Cassation search with exact phrase matching and recent decisions.
Key Features:
• Exact phrase search: "\"legal term\"" for precise matching
• Regular search: "legal term" for individual word matching
• 52 chamber filtering options (same as primary API)
• ISO 8601 date filtering • Recent decision coverage
Use alongside primary search for comprehensive coverage. Exact phrase search provides
higher precision with fewer false positives."""
)
async def search_yargitay_bedesten(request: YargitayBedestenSearchRequest):
"""Search Court of Cassation using Bedesten API. Complements primary API for complete coverage."""
args = {"phrase": request.phrase, "pageSize": request.pageSize}
if request.birimAdi:
args["birimAdi"] = request.birimAdi
if request.kararTarihiStart:
args["kararTarihiStart"] = request.kararTarihiStart
if request.kararTarihiEnd:
args["kararTarihiEnd"] = request.kararTarihiEnd
return await call_mcp_tool("search_yargitay_bedesten", args)
@app.get(
"/api/yargitay/document/{decision_id}",
tags=["Yargıtay"],
summary="Get Court of Cassation Document (Primary API)",
description="""Retrieve complete Court of Cassation decision in Markdown format.
Content includes:
• Complete legal reasoning and precedent analysis
• Detailed examination of lower court decisions
• Citations of laws, regulations, and prior cases
• Final ruling with legal justification
Perfect for detailed legal analysis, precedent research, and citation building."""
)
async def get_yargitay_document(decision_id: str):
"""Get full Court of Cassation decision text in clean Markdown format."""
return await call_mcp_tool("get_yargitay_document_markdown", {"id": decision_id})
@app.get(
"/api/yargitay/bedesten-document/{document_id}",
tags=["Yargıtay"],
summary="Get Court of Cassation Document (Bedesten API)",
description="""Retrieve Court of Cassation decision from Bedesten API in Markdown format.
Features:
• Supports both HTML and PDF source documents
• Clean Markdown conversion with legal structure preserved
• Removes technical artifacts for easy reading
• Compatible with documentId from Bedesten search results"""
)
async def get_yargitay_bedesten_document(document_id: str):
"""Get Court of Cassation document from Bedesten API in Markdown format."""
return await call_mcp_tool("get_yargitay_bedesten_document_markdown", {"documentId": document_id})
# ============================================================================
# DANISTAY (COUNCIL OF STATE) ENDPOINTS - 5 TOOLS
# ============================================================================
@app.post(
"/api/danistay/search-keyword",
tags=["Danıştay"],
summary="Search Council of State (Keyword Logic)",
description="""Search Turkey's highest administrative court using Boolean keyword logic.
Boolean Operators:
• AND keywords: ALL must be present (required terms)
• OR keywords: ANY can be present (alternative terms)
• NOT keywords: EXCLUDE if present (unwanted terms)
Examples:
• Administrative acts: andKelimeler=["idari işlem", "iptal"]
• Permits/licenses: orKelimeler=["ruhsat", "izin", "lisans"]
• Exclude tax cases: notKelimeler=["vergi"]
Perfect for administrative law research and government action reviews."""
)
async def search_danistay_keyword(request: DanistayKeywordSearchRequest):
"""
Searches Council of State (Danıştay) decisions using keyword-based logic.
The Council of State (Danıştay) is Turkey's highest administrative court, responsible for
reviewing administrative actions and providing administrative law precedents. This tool
provides flexible keyword-based searching with Boolean logic operators.
Key Features:
• Boolean logic operators: AND, OR, NOT combinations
• Multiple keyword lists for complex search strategies
• Pagination support (1-100 results per page)
• Administrative law focus (permits, licenses, public administration)
• Complement to search_danistay_detailed for comprehensive coverage
Keyword Logic:
• andKelimeler: ALL keywords must be present (AND logic)
• orKelimeler: ANY keyword can be present (OR logic)
• notAndKelimeler: EXCLUDE if ALL keywords present (NOT AND)
• notOrKelimeler: EXCLUDE if ANY keyword present (NOT OR)
Administrative Law Use Cases:
• Research administrative court precedents
• Find decisions on specific government agencies
• Search for rulings on permits (ruhsat) and licenses (izin)
• Analyze administrative procedure interpretations
• Study public administration legal principles
Examples:
• Simple AND: andKelimeler=["administrative act (idari işlem)", "annulment (iptal)"]
• OR search: orKelimeler=["permit (ruhsat)", "permission (izin)", "license (lisans)"]
• Complex: andKelimeler=["municipality (belediye)"], notOrKelimeler=["tax (vergi)"]
Returns structured search results. Use get_danistay_document_markdown() for full texts.
For comprehensive Council of State (Danıştay) research, also use search_danistay_detailed and search_danistay_bedesten.
"""
args = {"andKelimeler": request.andKelimeler, "pageSize": request.pageSize}
if request.orKelimeler:
args["orKelimeler"] = request.orKelimeler
if request.notKelimeler:
args["notKelimeler"] = request.notKelimeler
return await call_mcp_tool("search_danistay_by_keyword", args)
@app.post(
"/api/danistay/search-detailed",
tags=["Danıştay"],
summary="Search Council of State (Detailed Criteria)",
description="""Most comprehensive Council of State search with advanced filtering.
Advanced Filtering:
• Chamber targeting (1. Daire through 17. Daire, special councils)
• Case/decision number ranges • Date range filtering
• Legislation cross-referencing • Multiple sorting options
Use for specialized administrative law research, chamber-specific decisions,
and regulatory compliance analysis."""
)
async def search_danistay_detailed(request: DanistayDetailedSearchRequest):
"""Search Council of State with comprehensive filtering for specialized administrative law research."""
args = {}
for field in ["daire", "baslangicTarihi", "bitisTarihi", "esas", "karar"]:
if getattr(request, field):
args[field] = getattr(request, field)
return await call_mcp_tool("search_danistay_detailed", args)
@app.post(
"/api/danistay/search-bedesten",
tags=["Danıştay"],
summary="Search Council of State (Bedesten API)",
description="""Council of State search via Bedesten API with 27 chamber options and exact phrase search.
Key Features:
• 27 chamber options (Main Councils, 17 Chambers, Military courts)
• Exact phrase search with double quotes for precision
• ISO 8601 date filtering • Alternative data source
Use with other Danıştay tools for complete administrative law coverage."""
)
async def search_danistay_bedesten(request: DanistayBedestenSearchRequest):
"""Search Council of State via Bedesten API. Use with other Danıştay tools for complete coverage."""
args = {"phrase": request.phrase, "pageSize": request.pageSize}
for field in ["birimAdi", "kararTarihiStart", "kararTarihiEnd"]:
if getattr(request, field):
args[field] = getattr(request, field)
return await call_mcp_tool("search_danistay_bedesten", args)
@app.get(
"/api/danistay/document/{decision_id}",
tags=["Danıştay"],
summary="Get Council of State Document (Primary API)",
description="""Retrieve complete administrative court decision in Markdown format.
Content includes:
• Complete administrative law reasoning and precedent analysis
• Review of administrative actions and government decisions
• Citations of administrative laws and regulations
• Final administrative ruling with legal justification
Essential for administrative law research and government compliance analysis."""
)
async def get_danistay_document(decision_id: str):
"""Get full Council of State decision text in clean Markdown format."""
return await call_mcp_tool("get_danistay_document_markdown", {"id": decision_id})
@app.get(
"/api/danistay/bedesten-document/{document_id}",
tags=["Danıştay"],
summary="Get Council of State Document (Bedesten API)",
description="""Retrieve Council of State decision from Bedesten API in Markdown format."""
)
async def get_danistay_bedesten_document(document_id: str):
"""Get Council of State document from Bedesten API in Markdown format."""
return await call_mcp_tool("get_danistay_bedesten_document_markdown", {"documentId": document_id})
# ============================================================================
# BEDESTEN API COURTS (LOCAL/APPELLATE/KYB) - 6 TOOLS
# ============================================================================
@app.post(
"/api/yerel-hukuk/search",
tags=["Yerel Hukuk"],
summary="Search Local Civil Courts",
description="""Search first-instance civil court decisions using Bedesten API.
Local Civil Courts handle:
• Contract disputes • Property rights • Family law • Tort claims
• Commercial disputes • Consumer protection
Only available tool for local court decisions. Supports exact phrase search
and date filtering for precise legal research."""
)
async def search_yerel_hukuk(request: BedestenSearchRequest):
"""
Searches Yerel Hukuk Mahkemesi (Local Civil Court) decisions using Bedesten API.
This provides access to local court decisions that are not available through other APIs.
Currently the only available tool for searching Yerel Hukuk Mahkemesi decisions.
Local civil courts represent the first instance of civil litigation in Turkey.
Local Civil Courts handle:
• Contract disputes and commercial litigation
• Property rights and real estate disputes
• Family law matters (divorce, custody, inheritance)
• Tort claims and compensation cases
• Consumer protection issues
• Employment disputes
Returns structured search results with decision metadata. Use get_yerel_hukuk_bedesten_document_markdown()
to retrieve full decision texts for detailed analysis.
"""
args = {"phrase": request.phrase, "pageSize": request.pageSize}
for field in ["kararTarihiStart", "kararTarihiEnd"]:
if getattr(request, field):
args[field] = getattr(request, field)
return await call_mcp_tool("search_yerel_hukuk_bedesten", args)
@app.get("/api/yerel-hukuk/document/{document_id}", tags=["Yerel Hukuk"])
async def get_yerel_hukuk_document(document_id: str):
"""
Retrieves a Yerel Hukuk Mahkemesi decision document from Bedesten API and converts to Markdown.
This tool fetches complete local court decision texts using documentId from search results.
Perfect for detailed analysis of first-instance civil court rulings.
Supports both HTML and PDF content types, automatically converting to clean Markdown format.
Use documentId from search_yerel_hukuk_bedesten results.
"""
return await call_mcp_tool("get_yerel_hukuk_bedesten_document_markdown", {"documentId": document_id})
@app.post(
"/api/istinaf-hukuk/search",
tags=["İstinaf Hukuk"],
summary="Search Civil Courts of Appeals",
description="""Search intermediate appellate court decisions using Bedesten API.
İstinaf Courts are intermediate appellate courts handling appeals from local civil courts
before cases reach the Court of Cassation. Only available tool for İstinaf decisions."""
)
async def search_istinaf_hukuk(request: BedestenSearchRequest):
"""
Searches İstinaf Hukuk Mahkemesi (Civil Court of Appeals) decisions using Bedesten API.
İstinaf courts are intermediate appellate courts in the Turkish judicial system that handle
appeals from local civil courts before cases reach Yargıtay (Court of Cassation).
This is the only available tool for accessing İstinaf Hukuk Mahkemesi decisions.
Key Features:
• Date range filtering with ISO 8601 format (YYYY-MM-DDTHH:MM:SS.000Z)
• Exact phrase search using double quotes: "\"legal term\""
• Regular search for individual keywords
• Pagination support (1-100 results per page)
Use cases:
• Research appellate court precedents
• Track appeals from specific lower courts
• Find decisions on specific legal issues at appellate level
• Analyze intermediate court reasoning before supreme court review
Returns structured data with decision metadata including dates, case numbers, and summaries.
Use get_istinaf_hukuk_bedesten_document_markdown() to retrieve full decision texts.
"""
args = {"phrase": request.phrase, "pageSize": request.pageSize}
for field in ["kararTarihiStart", "kararTarihiEnd"]:
if getattr(request, field):
args[field] = getattr(request, field)
return await call_mcp_tool("search_istinaf_hukuk_bedesten", args)
@app.get("/api/istinaf-hukuk/document/{document_id}", tags=["İstinaf Hukuk"])
async def get_istinaf_hukuk_document(document_id: str):
"""
Retrieves the full text of an İstinaf Hukuk Mahkemesi decision document in Markdown format.
This tool converts the original decision document (HTML or PDF) from Bedesten API
into clean, readable Markdown format suitable for analysis and processing.
Input Requirements:
• documentId: Use the ID from search_istinaf_hukuk_bedesten results
• Document ID must be non-empty string
Output Format:
• Clean Markdown text with proper formatting
• Preserves legal structure (headers, paragraphs, citations)
• Removes extraneous HTML/PDF artifacts
Use for:
• Reading full appellate court decision texts
• Legal analysis of İstinaf court reasoning
• Citation extraction and reference building
• Content analysis and summarization
"""
return await call_mcp_tool("get_istinaf_hukuk_bedesten_document_markdown", {"documentId": document_id})
@app.post(
"/api/kyb/search",
tags=["KYB"],
summary="Search Extraordinary Appeals (KYB)",
description="""Search Kanun Yararına Bozma (Extraordinary Appeal) decisions.
KYB is an extraordinary legal remedy where the Public Prosecutor's Office requests
review of finalized decisions in favor of law and defendants. Very rare but important
legal precedents. Only available tool for KYB decisions."""
)
async def search_kyb(request: BedestenSearchRequest):
"""
Searches Kanun Yararına Bozma (KYB - Extraordinary Appeal) decisions using Bedesten API.
KYB is an extraordinary legal remedy in the Turkish judicial system where the
Public Prosecutor's Office can request review of finalized decisions in favor of
the law and defendants. This is the only available tool for accessing KYB decisions.
Key Features:
• Date range filtering with ISO 8601 format (YYYY-MM-DDTHH:MM:SS.000Z)
• Exact phrase search using double quotes: "\"extraordinary appeal\""
• Regular search for individual keywords
• Pagination support (1-100 results per page)
Legal Significance:
• Extraordinary remedy beyond regular appeals
• Initiated by Public Prosecutor's Office
• Reviews finalized decisions for legal errors
• Can benefit defendants retroactively
• Rare but important legal precedents
Use cases:
• Research extraordinary appeal precedents
• Study prosecutorial challenges to final decisions
• Analyze legal errors in finalized cases
• Track KYB success rates and patterns
Returns structured data with decision metadata. Use get_kyb_bedesten_document_markdown()
to retrieve full decision texts for detailed analysis.
"""
args = {"phrase": request.phrase, "pageSize": request.pageSize}
for field in ["kararTarihiStart", "kararTarihiEnd"]:
if getattr(request, field):
args[field] = getattr(request, field)
return await call_mcp_tool("search_kyb_bedesten", args)
@app.get("/api/kyb/document/{document_id}", tags=["KYB"])
async def get_kyb_document(document_id: str):
"""
Retrieves the full text of a Kanun Yararına Bozma (KYB) decision document in Markdown format.
This tool converts the original extraordinary appeal decision document (HTML or PDF)
from Bedesten API into clean, readable Markdown format for analysis.
Input Requirements:
• documentId: Use the ID from search_kyb_bedesten results
• Document ID must be non-empty string
Output Format:
• Clean Markdown text with legal formatting preserved
• Structured content with headers and citations
• Removes technical artifacts from source documents
Special Value for KYB Documents:
• Contains rare extraordinary appeal reasoning
• Shows prosecutorial arguments for legal review
• Documents correction of finalized legal errors
• Provides precedent for similar extraordinary circumstances
Use for:
• Analyzing extraordinary appeal legal reasoning
• Understanding prosecutorial review criteria
• Research on legal error correction mechanisms
• Studying retroactive benefit applications
"""
return await call_mcp_tool("get_kyb_bedesten_document_markdown", {"documentId": document_id})
# ============================================================================
# ADDITIONAL COURTS - 12 TOOLS
# ============================================================================
@app.post("/api/emsal/search", tags=["Emsal"], summary="Search UYAP Precedents")
async def search_emsal(request: EmsalSearchRequest):
"""
Searches for Precedent (Emsal) decisions using detailed criteria.
The Precedent (Emsal) database contains precedent decisions from various Turkish courts
integrated through the UYAP (National Judiciary Informatics System). This tool provides
access to a comprehensive collection of court decisions that serve as legal precedents.
Key Features:
• Multi-court coverage (BAM, Civil courts, Regional chambers)
• Keyword-based search across decision texts
• Court-specific filtering for targeted research
• Case number filtering (Case No (Esas No) and Decision No (Karar No) with ranges)
• Date range filtering with DD.MM.YYYY format
• Multiple sorting options and pagination support
Court Selection Options:
• BAM Civil Courts: Higher regional civil courts
• Civil Courts: Local and first-instance civil courts
• Regional Civil Chambers: Specialized civil court departments
Precedent Research Use Cases:
• Find precedent (emsal) decisions across multiple court levels
• Research court interpretations of specific legal concepts
• Analyze consistent legal reasoning patterns
• Study regional variations in legal decisions
• Track precedent development over time
• Compare decisions from different court types
Returns structured precedent data with court information and decision metadata.
Use get_emsal_document_markdown() to retrieve full precedent decision texts.
"""
args = {"keyword": request.keyword, "results_per_page": request.results_per_page}
if request.decision_year_karar:
args["decision_year_karar"] = request.decision_year_karar
return await call_mcp_tool("search_emsal_detailed_decisions", args)
@app.get("/api/emsal/document/{decision_id}", tags=["Emsal"])
async def get_emsal_document(decision_id: str):
"""
Retrieves the full text of a specific Emsal (UYAP Precedent) decision in Markdown format.
This tool fetches complete precedent decision documents from the UYAP system and converts
them to clean, readable Markdown format suitable for legal precedent analysis.
Input Requirements:
• decision_id: Decision ID from search_emsal_detailed_decisions results
• ID must be non-empty string from UYAP Emsal database
Output Format:
• Clean Markdown text with legal precedent structure preserved
• Organized sections: court info, case facts, legal reasoning, conclusion
• Proper formatting for legal citations and cross-references
• Removes technical artifacts from source documents
Precedent Decision Content:
• Complete court reasoning and legal analysis
• Detailed examination of legal principles applied
• Citation of relevant laws, regulations, and prior precedents
• Final ruling with precedent-setting reasoning
• Court-specific interpretations and legal standards
Use for legal precedent research, citation building, and comparative legal analysis.
"""
return await call_mcp_tool("get_emsal_document_markdown", {"decision_id": decision_id})
@app.post("/api/uyusmazlik/search", tags=["Uyuşmazlık"], summary="Search Jurisdictional Disputes")
async def search_uyusmazlik(request: UyusmazlikSearchRequest):
"""
Searches for Court of Jurisdictional Disputes (Uyuşmazlık Mahkemesi) decisions.
The Court of Jurisdictional Disputes (Uyuşmazlık Mahkemesi) resolves jurisdictional disputes between different court systems
in Turkey, determining which court has jurisdiction over specific cases. This specialized
court handles conflicts between civil, criminal, and administrative jurisdictions.
Key Features:
• Department filtering (Criminal, Civil, General Assembly decisions)
• Dispute type classification (Jurisdiction vs Judgment disputes)
• Decision outcome filtering (dispute resolution results)
• Case number and date range filtering
• Advanced text search with Boolean logic operators
• Official Gazette reference search
Dispute Types:
• Jurisdictional Disputes (Görev Uyuşmazlığı): Which court has authority
• Judgment Disputes (Hüküm Uyuşmazlığı): Conflicting final decisions
Departments:
• Criminal Section (Ceza Bölümü): Criminal section decisions
• Civil Section (Hukuk Bölümü): Civil section decisions
• General Assembly Decisions (Genel Kurul Kararları): General Assembly decisions
Use cases:
• Research jurisdictional precedents
• Understand court system boundaries
• Analyze dispute resolution patterns
• Study inter-court conflict resolution
• Legal procedure and jurisdiction research
Returns structured search results with dispute resolution information.
"""
return await call_mcp_tool("search_uyusmazlik_decisions", {
"keywords": request.keywords,