-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmcp_core_server.py
More file actions
2544 lines (2304 loc) · 132 KB
/
mcp_core_server.py
File metadata and controls
2544 lines (2304 loc) · 132 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
#!/usr/bin/env python3
"""
Core MCP Server
- Handles MCP protocol and tool registration
- Extensible tool system for adding new functionalities
- Core service that can be consumed by other applications
"""
import json
import asyncio
from pathlib import Path
from typing import List, Dict, Any, Optional, Callable, Union
def _metadata_str(val: Any) -> str:
"""Normalize a metadata field value to a string (item metadata can have list values e.g. action)."""
if val is None:
return ""
if isinstance(val, str):
return val
if isinstance(val, list):
return " ".join(str(x).strip() for x in val if x is not None and str(x).strip())
return str(val)
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import os
# Import our modular components
from models import SearchRequest, SearchResponse, InferenceRequest, InferenceResult, DatasetType
from tool_registry import ToolRegistry
from dataset_registry import DatasetRegistry, Dataset
from model_registry import ModelRegistry
from config import MCP_CONFIG, MCP_PROTOCOL_CONFIG, BASE_DIR, LLM_CONFIG, IMAGES_DIR, IMAGES_TRY_SPECIES_FIRST
# Optional imports
try:
from llm_service import LLMService
LLM_AVAILABLE = True
except ImportError:
LLM_AVAILABLE = False
LLMService = None
# IMPORTANT: This import happens at module load time
# Make sure croissant_crawler.py is in the same directory as this file
print("=" * 60)
print("🔍 CHECKING CROISSANT CRAWLER IMPORT...")
print("=" * 60)
try:
import sys
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
print(f"📁 Current file directory: {current_dir}")
print(f"📁 Working directory: {os.getcwd()}")
print(f"📁 Python path (first 3): {sys.path[:3]}")
crawler_file = os.path.join(current_dir, "croissant_crawler.py")
print(f"📄 Looking for: {crawler_file}")
print(f"📄 File exists: {os.path.exists(crawler_file)}")
if not os.path.exists(crawler_file):
# Try current directory
crawler_file = "croissant_crawler.py"
print(f"📄 Trying current dir: {crawler_file}")
print(f"📄 File exists: {os.path.exists(crawler_file)}")
print(f"🔍 Attempting import...")
from croissant_crawler import CroissantCrawler
CROISSANT_CRAWLER_AVAILABLE = True
print("=" * 60)
print("✅ SUCCESS: Croissant crawler imported successfully!")
print(f" CroissantCrawler class: {CroissantCrawler}")
print("=" * 60)
except ImportError as e:
CROISSANT_CRAWLER_AVAILABLE = False
CroissantCrawler = None
print("=" * 60)
print(f"❌ FAILED: Croissant crawler import error (ImportError)")
print(f" Error: {e}")
print("=" * 60)
import traceback
traceback.print_exc()
print("=" * 60)
except Exception as e:
CROISSANT_CRAWLER_AVAILABLE = False
CroissantCrawler = None
print("=" * 60)
print(f"❌ FAILED: Croissant crawler import error (Other)")
print(f" Error: {e}")
print("=" * 60)
import traceback
traceback.print_exc()
print("=" * 60)
class MCPServer:
"""Core MCP Server that manages tools and provides MCP protocol endpoints"""
def __init__(self):
self.name = MCP_PROTOCOL_CONFIG["server_name"]
self.version = MCP_PROTOCOL_CONFIG["server_version"]
self.description = MCP_PROTOCOL_CONFIG["server_description"]
print(f"🚀 Initializing {self.name} v{self.version}")
print(f"📁 Base directory: {BASE_DIR}")
print(f"📁 Looking for MCP data files in: {BASE_DIR}")
# Check what MCP files exist
mcp_files = list(BASE_DIR.glob("*_mcp_data.json"))
print(f"🔍 Found {len(mcp_files)} MCP data files:")
for f in mcp_files:
print(f" - {f.name}")
# Initialize registries
print("🔧 Initializing tool registry...")
self.tool_registry = ToolRegistry()
print("📁 Initializing dataset registry...")
self.dataset_registry = DatasetRegistry()
print("🤖 Initializing model registry...")
self.model_registry = ModelRegistry()
# Initialize LLM service
print("🧠 Initializing LLM service...")
# Check environment variables (Azure takes precedence over OpenAI when set)
import os
google_key = os.getenv("GOOGLE_API_KEY")
openai_key = os.getenv("OPENAI_API_KEY")
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
azure_key = os.getenv("AZURE_OPENAI_API_KEY")
print(f"🧠 Environment check:")
print(f" AZURE_OPENAI_ENDPOINT: {'SET' if azure_endpoint else 'NOT SET'}")
print(f" AZURE_OPENAI_API_KEY: {'SET' if azure_key else 'NOT SET'}")
print(f" OPENAI_API_KEY: {'SET' if openai_key else 'NOT SET'}")
print(f" GOOGLE_API_KEY: {'SET' if google_key else 'NOT SET'}")
if google_key:
print(f" GOOGLE_API_KEY length: {len(google_key)}")
if LLM_AVAILABLE and LLMService:
self.llm_service = LLMService(
api_key=LLM_CONFIG.get("api_key"),
model=LLM_CONFIG.get("model"),
azure_endpoint=LLM_CONFIG.get("azure_endpoint") or None,
azure_api_key=LLM_CONFIG.get("azure_api_key") or None,
azure_deployment=LLM_CONFIG.get("azure_deployment") or None,
azure_api_version=LLM_CONFIG.get("azure_api_version") or None,
)
print(f"🧠 LLM service: {'enabled' if self.llm_service.is_available() else 'disabled (fallback to rules)'}")
if self.llm_service:
print(f" OpenAI available: {self.llm_service.openai_available}")
print(f" Gemini available: {self.llm_service.gemini_available}")
print(f" Provider: {self.llm_service.provider}")
else:
self.llm_service = None
print("🧠 LLM service: not available (module not found)")
# Setup FastAPI app
print("🌐 Setting up FastAPI app...")
self.app = FastAPI(title=self.name, version=self.version)
self._setup_middleware()
self._setup_routes()
self._register_default_tools()
print(f"✅ Initialized {self.name} v{self.version}")
print(f"📊 Summary:")
print(f" - Tools: {len(self.tool_registry.get_all_tools())}")
print(f" - Datasets: {len(self.dataset_registry.get_all_datasets())}")
print(f" - Models: {len(self.model_registry.get_all_models())}")
def _setup_middleware(self):
"""Setup CORS and other middleware"""
self.app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure as needed for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def _setup_routes(self):
"""Setup MCP protocol routes and API endpoints"""
# Health check
@self.app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"server": self.name,
"version": self.version,
"datasets_loaded": len(self.dataset_registry.datasets),
"tools_available": len(self.tool_registry.get_all_tools()),
"models_available": len(self.model_registry.get_all_models())
}
# MCP Protocol endpoints
@self.app.get("/mcp")
async def mcp_info():
"""MCP protocol information"""
return {
"name": self.name,
"version": self.version,
"description": self.description,
"capabilities": {
"resources": self._get_resources(),
"tools": self._get_tools()
},
"endpoints": {
"mcp_base": "/mcp",
"health": "/health",
"tools": "/mcp/tools",
"resources": "/mcp/resources",
"datasets": "/api/datasets",
"models": "/api/models"
}
}
# MCP Tools
@self.app.get("/mcp/tools")
async def list_tools():
"""List all available tools"""
return {
"tools": self.tool_registry.get_all_tools(),
"total": len(self.tool_registry.get_all_tools())
}
@self.app.get("/mcp/tools/{tool_name}")
async def execute_tool_get(tool_name: str, request: Request):
"""Execute a tool via GET (for tools that don't require input)"""
# Check if tool exists
if tool_name not in self.tool_registry.tools:
available_tools = list(self.tool_registry.tools.keys())
raise HTTPException(
status_code=404,
detail=f"Tool '{tool_name}' not found. Available tools: {', '.join(available_tools)}. Use POST /mcp/tools/{tool_name} with JSON body for tools that require input."
)
# For GET requests, use empty body (only works for tools that don't require input)
body = {}
# Check if tool requires input by looking at its schema
tool = self.tool_registry.get_tool(tool_name)
if tool and tool.input_schema.get("properties"):
# Tool has required properties - suggest using POST
required = tool.input_schema.get("required", [])
if required:
raise HTTPException(
status_code=405,
detail=f"Tool '{tool_name}' requires input parameters: {', '.join(required)}. Please use POST /mcp/tools/{tool_name} with a JSON body."
)
print(f"🔧 Executing tool via GET: {tool_name}")
print(f" Input data: {body}")
try:
result = await self.tool_registry.execute_tool(tool_name, body)
print(f"✅ Tool {tool_name} executed successfully")
return result
except Exception as e:
print(f"❌ Tool execution error: {e}")
import traceback
traceback.print_exc()
raise HTTPException(
status_code=500,
detail=f"Tool execution failed: {str(e)}. Try using POST /mcp/tools/{tool_name} with a JSON body."
)
@self.app.post("/mcp/tools/{tool_name}")
async def execute_tool(tool_name: str, request: Request):
"""Execute a specific tool"""
try:
# Check if tool exists first
if tool_name not in self.tool_registry.tools:
available_tools = list(self.tool_registry.tools.keys())
raise HTTPException(
status_code=404,
detail=f"Tool '{tool_name}' not found. Available tools: {', '.join(available_tools)}"
)
# Handle empty body or missing JSON
try:
body = await request.json()
except Exception as json_error:
# If no JSON body, use empty dict (some tools don't need input)
body = {}
print(f"⚠️ No JSON body provided, using empty dict: {json_error}")
print(f"🔧 Executing tool: {tool_name}")
print(f" Input data: {body}")
result = await self.tool_registry.execute_tool(tool_name, body)
print(f"✅ Tool {tool_name} executed successfully")
return result
except HTTPException:
# Re-raise HTTP exceptions as-is
raise
except ValueError as e:
# Tool not found or validation error
print(f"❌ Tool execution error (ValueError): {e}")
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
# Other errors
print(f"❌ Tool execution error: {e}")
import traceback
traceback.print_exc()
raise HTTPException(status_code=500, detail=f"Tool execution failed: {str(e)}")
# OPTIMIZATION: Cache directory listing to avoid repeated iterations
_image_dir_cache = {}
_image_dir_cache_time = {}
_image_dir_cache_ttl = 60 # Cache for 60 seconds
def _get_cached_dir_listing(images_dir: Path) -> List[Path]:
"""Get cached directory listing to avoid repeated iterations"""
import time
current_time = time.time()
dir_str = str(images_dir)
if dir_str in _image_dir_cache:
cache_time = _image_dir_cache_time.get(dir_str, 0)
if current_time - cache_time < _image_dir_cache_ttl:
return _image_dir_cache[dir_str]
# Cache miss - refresh cache
try:
listing = list(images_dir.iterdir())
_image_dir_cache[dir_str] = listing
_image_dir_cache_time[dir_str] = current_time
return listing
except Exception as e:
print(f"⚠️ Error listing directory {images_dir}: {e}")
return []
# Image serving endpoint
@self.app.get("/images/{filename:path}")
async def serve_image(filename: str):
"""Serve images: order by IMAGES_TRY_SPECIES_FIRST (Taiga = subdirs only → species subdir first)."""
try:
from pathlib import Path
from fastapi.responses import FileResponse
images_dir = Path(IMAGES_DIR)
filename_no_ext = Path(filename).stem
image_path_flat = images_dir / filename
try:
images_dir_resolved = images_dir.resolve()
image_path_flat_resolved = (images_dir_resolved / filename).resolve()
except OSError:
image_path_flat_resolved = image_path_flat
flat_to_try = image_path_flat_resolved if image_path_flat_resolved != image_path_flat else image_path_flat
def _try_species():
if "_" not in filename_no_ext:
return None
subdir = filename_no_ext.split("_")[0]
species_dir = images_dir / subdir
sub_path = species_dir / filename
if sub_path.exists() and sub_path.is_file():
return FileResponse(str(sub_path))
for ext in ['.jpg', '.jpeg', '.png', '.gif', '.JPG', '.JPEG', '.PNG', '.GIF']:
sub_path = species_dir / f"{filename_no_ext}{ext}"
if sub_path.exists() and sub_path.is_file():
return FileResponse(str(sub_path))
return None
print(f"🖼️ MCP Server: Looking for image: {filename}")
if IMAGES_TRY_SPECIES_FIRST:
r = _try_species()
if r is not None:
return r
if flat_to_try.exists() and flat_to_try.is_file():
return FileResponse(str(flat_to_try))
else:
if flat_to_try.exists() and flat_to_try.is_file():
return FileResponse(str(flat_to_try))
r = _try_species()
if r is not None:
return r
filename_lower = filename.lower()
dir_listing = _get_cached_dir_listing(images_dir)
for item in dir_listing:
if item.is_file() and item.name.lower() == filename_lower:
return FileResponse(str(item))
for ext in ['.jpg', '.jpeg', '.png', '.gif', '.JPG', '.JPEG', '.PNG', '.GIF']:
potential_file = images_dir / f"{filename_no_ext}{ext}"
if potential_file.exists() and potential_file.is_file():
return FileResponse(str(potential_file))
print(f"❌ MCP Server: Image not found: {filename}")
print(f" Flat path resolved: {image_path_flat_resolved} (exists={image_path_flat_resolved.exists()})")
prefix = filename_no_ext.split("_")[0] if "_" in filename_no_ext else filename_no_ext
try:
same_prefix = [p.name for p in _get_cached_dir_listing(images_dir) if p.is_file() and p.name.lower().startswith(prefix.lower() + "_")]
if same_prefix:
print(f" Files with prefix '{prefix}_': {same_prefix[:10]}{'...' if len(same_prefix) > 10 else ''}")
else:
print(f" No files with prefix '{prefix}_' in images dir.")
except Exception:
pass
raise HTTPException(status_code=404, detail=f"Image {filename} not found")
except HTTPException:
raise
except Exception as e:
print(f"❌ MCP Server: Error serving image: {e}")
import traceback
traceback.print_exc()
raise HTTPException(status_code=500, detail=f"Error serving image: {str(e)}")
# MCP Resources
@self.app.get("/mcp/resources")
async def list_resources():
"""List all available resources"""
return {
"resources": self._get_resources(),
"total": len(self._get_resources())
}
@self.app.get("/mcp/resources/{resource_name}")
async def get_resource(resource_name: str):
"""Get a specific resource"""
resources = self._get_resources()
if resource_name not in resources:
raise HTTPException(status_code=404, detail=f"Resource {resource_name} not found")
return resources[resource_name]
# Dataset API
@self.app.get("/api/datasets")
async def list_datasets():
"""List all available datasets"""
return {
"datasets": self.dataset_registry.get_all_datasets(),
"total": len(self.dataset_registry.get_all_datasets())
}
@self.app.get("/api/datasets/{dataset_name}")
async def get_dataset(dataset_name: str):
"""Get specific dataset information"""
dataset = self.dataset_registry.get_dataset(dataset_name)
if not dataset:
raise HTTPException(status_code=404, detail=f"Dataset {dataset_name} not found")
return dataset
@self.app.get("/api/datasets/{dataset_name}/images")
async def get_dataset_images(dataset_name: str, limit: int = 100, offset: int = 0):
"""Get images from a specific dataset"""
images = self.dataset_registry.get_images(dataset_name)
if not images:
raise HTTPException(status_code=404, detail=f"Dataset {dataset_name} not found or has no images")
total = len(images)
paginated_images = images[offset:offset + limit]
return {
"dataset": dataset_name,
"images": paginated_images,
"total_count": total,
"limit": limit,
"offset": offset
}
# Model API
@self.app.get("/api/models")
async def list_models():
"""List all available models"""
# Get all models and convert to serializable format
all_models = self.model_registry.get_all_models()
models_dict = {}
for name, model_info in all_models.items():
models_dict[name] = {
"name": model_info.name,
"type": model_info.type.value if hasattr(model_info.type, 'value') else str(model_info.type),
"description": model_info.description,
"version": model_info.version,
"supported_datasets": model_info.supported_datasets,
"parameters": model_info.parameters,
"metadata": model_info.metadata
}
return {
"models": models_dict,
"total": len(models_dict)
}
@self.app.get("/api/models/{model_name}")
async def get_model(model_name: str):
"""Get specific model information"""
from models import ModelInfo
model = self.model_registry.get_model(model_name)
if not model:
raise HTTPException(status_code=404, detail=f"Model {model_name} not found")
# Convert Model to ModelInfo (removes non-serializable handler)
model_info = ModelInfo(
name=model.name,
type=model.type,
description=model.description,
version=model.version,
supported_datasets=model.supported_datasets,
parameters=model.parameters,
metadata=model.metadata
)
# Convert to dict for JSON serialization
return {
"name": model_info.name,
"type": model_info.type.value if hasattr(model_info.type, 'value') else str(model_info.type),
"description": model_info.description,
"version": model_info.version,
"supported_datasets": model_info.supported_datasets,
"parameters": model_info.parameters,
"metadata": model_info.metadata
}
# Search API
@self.app.post("/api/search")
async def search_images(request: Request):
"""Search across all datasets"""
try:
body = await request.json()
search_request = SearchRequest(**body)
# This will be implemented to search across all datasets
# For now, return a placeholder
return {
"message": "Search functionality will be implemented",
"request": body
}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
# Datasets API
@self.app.get("/api/datasets")
async def get_datasets():
"""Get all available datasets"""
try:
datasets = []
for dataset_name, dataset in self.dataset_registry.datasets.items():
# Get images from the registry instead of accessing dataset.images
images = self.dataset_registry.get_images(dataset_name)
dataset_info = {
"name": dataset_name,
"description": dataset.description,
"type": dataset.dataset_type.value,
"image_count": len(images),
"collections": list(dataset.collections.keys()),
"filters": self._extract_dataset_filters(dataset)
}
datasets.append(dataset_info)
return {"datasets": datasets}
except Exception as e:
print(f"❌ Error getting datasets: {e}")
import traceback
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
# Inference API
@self.app.post("/api/inference")
async def run_inference(request: Request):
"""Run model inference"""
try:
body = await request.json()
inference_request = InferenceRequest(**body)
result = await self.model_registry.run_inference(inference_request)
return result
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
def _get_resources(self) -> Dict[str, Any]:
"""Get available resources"""
return {
"mcp://aifarms.org/resources/core": {
"name": "Core Server Resources",
"description": "Core MCP server resources and capabilities",
"schema": {
"type": "object",
"properties": {
"server_info": {"type": "object"},
"available_tools": {"type": "array"},
"available_datasets": {"type": "array"},
"available_models": {"type": "array"}
}
}
},
"mcp://aifarms.org/resources/datasets": {
"name": "Available Datasets",
"description": "List of all available datasets and their schemas",
"schema": {
"type": "object",
"properties": {
"datasets": {"type": "array", "items": {"type": "object"}}
}
}
},
"mcp://aifarms.org/resources/models": {
"name": "Available Models",
"description": "List of all available ML models and their capabilities",
"schema": {
"type": "object",
"properties": {
"models": {"type": "array", "items": {"type": "object"}}
}
}
}
}
def _get_tools(self) -> Dict[str, Any]:
"""Get available tools from registry"""
tools = {}
for tool_name, tool_info in self.tool_registry.get_all_tools().items():
tools[f"mcp://aifarms.org/tools/{tool_name}"] = tool_info
return tools
def _register_default_tools(self):
"""Register default tools with the server"""
# Search tool
self.tool_registry.register_tool(
name="search_images",
description="Search for images across all datasets using natural language queries and filters",
input_schema={
"type": "object",
"properties": {
"query": {"type": "string", "description": "Natural language search query"},
"dataset": {"type": "string", "description": "Specific dataset to search in"},
"filters": {"type": "object", "description": "Search filters"},
"limit": {"type": "integer", "default": 50},
"offset": {"type": "integer", "default": 0}
}
},
handler=self._search_tool_handler,
tags=["search", "images", "datasets"]
)
# Inference tool
self.tool_registry.register_tool(
name="run_inference",
description="Run ML model inference on images",
input_schema={
"type": "object",
"properties": {
"dataset_name": {"type": "string", "description": "Dataset to run inference on"},
"model_name": {"type": "string", "description": "Model to use for inference"},
"image_ids": {"type": "array", "items": {"type": "string"}, "description": "Image IDs to process"},
"parameters": {"type": "object", "description": "Additional model parameters"}
}
},
handler=self._inference_tool_handler,
tags=["inference", "ml", "models"]
)
# LLM-powered search tool
self.tool_registry.register_tool(
name="llm_search",
description="Intelligent search using LLM query understanding",
input_schema={
"type": "object",
"properties": {
"query": {"type": "string", "description": "Natural language search query"},
"dataset": {"type": "string", "description": "Specific dataset to search in"},
"limit": {"type": "integer", "default": 50},
"offset": {"type": "integer", "default": 0},
"dataset_offset": {"type": "integer", "default": 0, "description": "Skip this many datasets to load next batch (e.g. 100 for next 100)"}
}
},
handler=self._llm_search_handler,
tags=["search", "llm", "intelligent", "semantic"]
)
# Dataset info tool
self.tool_registry.register_tool(
name="get_dataset_info",
description="Get information about available datasets",
input_schema={
"type": "object",
"properties": {
"dataset_name": {"type": "string", "description": "Specific dataset name (optional)"}
}
},
handler=self._dataset_info_tool_handler,
tags=["datasets", "info"]
)
# Model info tool
self.tool_registry.register_tool(
name="get_model_info",
description="Get information about available ML models",
input_schema={
"type": "object",
"properties": {
"model_name": {"type": "string", "description": "Specific model name (optional)"}
}
},
handler=self._model_info_tool_handler,
tags=["models", "info"]
)
# Croissant dataset crawler tool
print(f"🔧 Checking Croissant crawler availability: {CROISSANT_CRAWLER_AVAILABLE}")
print(f" CROISSANT_CRAWLER_AVAILABLE value: {CROISSANT_CRAWLER_AVAILABLE}")
print(f" CroissantCrawler class: {CroissantCrawler}")
if CROISSANT_CRAWLER_AVAILABLE:
try:
print(f"🔧 Attempting to register crawl_croissant_datasets tool...")
self.tool_registry.register_tool(
name="crawl_croissant_datasets",
description="Crawl AI Institute portals for Croissant-formatted datasets",
input_schema={
"type": "object",
"properties": {}
},
handler=self._crawl_croissant_datasets_handler,
tags=["crawler", "datasets", "croissant"]
)
print("✅ Successfully registered crawl_croissant_datasets tool")
# Verify it was actually registered
all_tools = list(self.tool_registry.get_all_tools().keys())
if "crawl_croissant_datasets" in all_tools:
print(f"✅ Verified: crawl_croissant_datasets is in registered tools list")
else:
print(f"❌ WARNING: crawl_croissant_datasets NOT found in tools list!")
print(f" Registered tools: {all_tools}")
except Exception as e:
print(f"❌ Failed to register crawl_croissant_datasets tool: {e}")
import traceback
traceback.print_exc()
else:
print("⚠️ Croissant crawler tool NOT registered (CROISSANT_CRAWLER_AVAILABLE is False)")
print(" This means the import failed. Check the import error messages above.")
# Tool handlers
def _search_tool_handler(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
"""Handler for search tool"""
query = input_data.get("query", "")
dataset = input_data.get("dataset")
filters = input_data.get("filters", {})
limit = input_data.get("limit", 50)
offset = input_data.get("offset", 0)
print(f"🔍 Search request: query='{query}', dataset='{dataset}', filters={filters}")
if dataset:
# Search in specific dataset using adapter
print(f"🔍 Searching in specific dataset: {dataset}")
filtered_results = self.dataset_registry.search_dataset(dataset, query, filters)
if filtered_results is None:
return {
"dataset": dataset,
"query": query,
"results": [],
"total_count": 0,
"error": f"Dataset {dataset} not found or has no images"
}
return {
"dataset": dataset,
"query": query,
"results": filtered_results[offset:offset + limit],
"total_count": len(filtered_results)
}
else:
# Search across all datasets using adapters
# Apply category pre-filtering for performance
category_filter = filters.get("category", [])
datasets_to_search = []
if category_filter:
# Filter datasets by category first (same logic as _llm_search_handler)
print(f"🔍 Category pre-filtering: {category_filter}")
for dataset_name, dataset_obj in self.dataset_registry.datasets.items():
dataset_category = dataset_obj.type.value.lower()
# Map category filter to dataset type
category_mapping = {
"pest": ["pests"],
"animal": ["wildlife"],
"wildlife": ["wildlife"],
"plant": ["plants"]
}
should_include = False
for cat in category_filter:
cat_lower = cat.lower()
if cat_lower in category_mapping:
if dataset_category in category_mapping[cat_lower]:
should_include = True
break
elif cat_lower == dataset_category:
should_include = True
break
if should_include:
datasets_to_search.append(dataset_name)
else:
# No category filter - search all datasets
datasets_to_search = list(self.dataset_registry.datasets.keys())
print(f"🔍 Searching {len(datasets_to_search)} datasets (out of {len(self.dataset_registry.datasets)} total)")
all_results = []
for dataset_name in datasets_to_search:
print(f"🔍 Searching dataset: {dataset_name}")
filtered_results = self.dataset_registry.search_dataset(dataset_name, query, filters)
if filtered_results:
# Add dataset info to each result
for result in filtered_results:
result['dataset'] = dataset_name
all_results.extend(filtered_results)
print(f"🔍 Total results found: {len(all_results)}")
return {
"query": query,
"results": all_results[offset:offset + limit],
"total_count": len(all_results),
"searched_datasets": datasets_to_search
}
def _apply_search_filters(self, images: List[Dict[str, Any]], query: str, filters: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Apply search filters to images (legacy method - now uses adapters via search_dataset)"""
# This method is kept for backward compatibility but search_dataset now uses adapters
# The adapter-based search is handled in dataset_registry.search_dataset()
filtered_images = images.copy()
# Apply text search if query provided
if query.strip():
query_lower = query.lower()
filtered_images = [
img for img in filtered_images
if self._image_matches_query(img, query_lower)
]
# Apply category filter
if filters.get("category"):
category_filter = [c.lower() for c in filters["category"]]
filtered_images = [
img for img in filtered_images
if img.get("category", "").lower() in category_filter
]
# Apply species filter
if filters.get("species"):
species_filter = [s.lower() for s in filters["species"]]
filtered_images = [
img for img in filtered_images
if img.get("collection", "").lower() in species_filter
]
# Apply time filter
if filters.get("time"):
time_filter = [t.lower() for t in filters["time"]]
filtered_images = [
img for img in filtered_images
if self._image_matches_time(img, time_filter)
]
# Apply season filter
if filters.get("season"):
season_filter = [s.lower() for s in filters["season"]]
filtered_images = [
img for img in filtered_images
if self._image_matches_season(img, season_filter)
]
return filtered_images
async def _llm_search_handler(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
"""Handle LLM-powered search with intelligent query understanding"""
query = input_data.get("query", "")
dataset = input_data.get("dataset")
limit = input_data.get("limit", 50)
offset = input_data.get("offset", 0)
dataset_offset = max(0, int(input_data.get("dataset_offset", 0)))
print(f"🧠 LLM search request: query='{query}', dataset='{dataset}', dataset_offset={dataset_offset}")
try:
# Get available filters for LLM context
available_filters = {}
if dataset:
if dataset in self.dataset_registry.datasets:
available_filters = self._extract_dataset_filters(self.dataset_registry.datasets[dataset])
# Also add collections to available_filters for species matching
dataset_obj = self.dataset_registry.datasets[dataset]
if dataset_obj.collections:
if "collections" not in available_filters:
available_filters["collections"] = []
available_filters["collections"].extend(list(dataset_obj.collections))
else:
# Combine filters from all datasets
all_collections = set()
for dataset_name, dataset_obj in self.dataset_registry.datasets.items():
dataset_filters = self._extract_dataset_filters(dataset_obj)
for key, values in dataset_filters.items():
if key not in available_filters:
available_filters[key] = []
available_filters[key].extend(values)
# Collect collections from all datasets
if dataset_obj.collections:
all_collections.update(dataset_obj.collections)
# Add collections to available_filters
if all_collections:
available_filters["collections"] = sorted(list(all_collections))
# Treat dataset names as valid species so e.g. "raspberry" matches dataset "raspberry"
for dataset_name in self.dataset_registry.datasets:
if dataset_name and dataset_name.strip():
available_filters.setdefault("species", []).append(dataset_name.strip())
# Remove duplicates
for key in available_filters:
available_filters[key] = sorted(list(set(available_filters[key])))
# Add opossum/oppossum to species options when we have Virginia opossum dataset so LLM can match and return high confidence
opossum_datasets = [d for d in self.dataset_registry.datasets if d and ("opossum" in d.lower() or "oppossum" in d.lower())]
if opossum_datasets:
for syn in ("opossum", "oppossum", "opossums", "oppossums"):
if syn not in available_filters.get("species", []):
available_filters.setdefault("species", []).append(syn)
available_filters["species"] = sorted(list(set(available_filters["species"])))
# Use LLM to understand the query - require LLM, no rule-based fallback
if not self.llm_service or not self.llm_service.is_available():
return {
"query": query,
"error": "LLM service is not available. Please set OPENAI_API_KEY environment variable.",
"results": [],
"total_count": 0,
"llm_understanding": None
}
print(f"🧠 Understanding query with LLM...")
print(f" LLM Service available: {self.llm_service.is_available() if self.llm_service else False}")
if self.llm_service:
print(f" OpenAI available: {self.llm_service.openai_available}")
print(f" Gemini available: {self.llm_service.gemini_available}")
print(f" Provider: {self.llm_service.provider}")
query_understanding = await self.llm_service.understand_query(query, available_filters)
# Normalize filters so every value is a list of strings (LLM sometimes returns nested lists or non-strings)
def _flatten_filter_val(v):
if v is None:
return []
if isinstance(v, str):
return [v.strip()] if v.strip() else []
if isinstance(v, list):
out = []
for x in v:
if isinstance(x, list):
out.extend(_flatten_filter_val(x))
elif x is not None and str(x).strip():
out.append(str(x).strip())
return out
return [str(v).strip()] if str(v).strip() else []
if getattr(query_understanding, "filters", None):
for key in list(query_understanding.filters.keys()):
query_understanding.filters[key] = _flatten_filter_val(query_understanding.filters[key])
# Normalize species: LLMs sometimes return "(moth)" or "[moth]" — strip parens/brackets so we match "moth"
if query_understanding.filters.get("species"):
normalized = []
for s in query_understanding.filters["species"]:
t = str(s).strip()
while t and t[0] in "([{\"" and t[-1] in ")]}\"":
t = t[1:-1].strip()
if t:
normalized.append(t)
if normalized:
query_understanding.filters["species"] = normalized
# Map opossum/oppossum to canonical dataset name (e.g. virginia_opossum) so pre-filtering finds the dataset
if query_understanding.filters.get("species") and self.dataset_registry.datasets:
species_list = query_understanding.filters["species"]
opossum_vals = {"opossum", "oppossum", "opossums", "oppossums"}
if any(str(s).lower() in opossum_vals for s in species_list):
canonical = [d for d in self.dataset_registry.datasets if d and ("opossum" in d.lower() or "oppossum" in d.lower())]
if canonical:
rest = [s for s in species_list if str(s).lower() not in opossum_vals]
query_understanding.filters["species"] = sorted(list(set(rest + canonical)))
# Reject rule-based fallback results - require real LLM understanding
if query_understanding.confidence < 0.7:
print(f"⚠️ Low confidence ({query_understanding.confidence}) - this might be rule-based fallback")
# Still proceed but log warning
print(f"🧠 LLM Understanding:")
print(f" Intent: {query_understanding.intent}")
print(f" Entities: {query_understanding.entities}")
print(f" Filters: {query_understanding.filters}")
print(f" Confidence: {query_understanding.confidence}")
print(f" Reasoning: {query_understanding.reasoning}")
# Ensure plant_state is set when query clearly asks for ripeness (e.g. "raspberry ripe")
# LLM sometimes omits it; without it we return all images and strict filter never runs
query_lower = query.lower()
plant_fruit_species = {"raspberry", "raspberries", "strawberry", "strawberries", "blueberry", "blueberries", "blackberry", "blackberries"}
species_in_query = [s for s in (query_understanding.filters.get("species") or []) if s]
species_lower = {s.lower().strip().replace("_", "") for s in species_in_query}