-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1797 lines (1452 loc) · 53.1 KB
/
Copy pathmain.py
File metadata and controls
1797 lines (1452 loc) · 53.1 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
"""
V Language MCP Server
A Model Context Protocol server that provides comprehensive information about
the V programming language to help LLMs understand and generate V code.
"""
import os
import re
import json
import logging
import time
from pathlib import Path
from typing import List, Dict, Any, Optional
from functools import lru_cache
from fastmcp import FastMCP
import asyncio
from dataclasses import dataclass
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
@dataclass
class VServerConfig:
"""Configuration for the V MCP Server."""
v_repo_path: Path
v_ui_path: Optional[Path] = None
cache_ttl_seconds: int = 300 # 5 minutes default
max_search_results: int = 50
log_level: str = "INFO"
@classmethod
def from_env(cls) -> 'VServerConfig':
"""Create configuration from environment variables."""
# V repository path
v_repo_path = os.getenv('V_REPO_PATH')
if v_repo_path:
repo_path = Path(v_repo_path)
else:
# Default to parent directory
repo_path = Path(__file__).parent.parent
# V UI repository path (optional)
v_ui_path = os.getenv('V_UI_PATH')
if v_ui_path:
ui_path = Path(v_ui_path)
else:
# Default to v-ui submodule in parent directory
ui_path = repo_path / "v-ui"
if not ui_path.exists():
ui_path = None
# Cache TTL
cache_ttl = int(os.getenv('V_CACHE_TTL_SECONDS', '300'))
# Max search results
max_results = int(os.getenv('V_MAX_SEARCH_RESULTS', '50'))
# Log level
log_level = os.getenv('V_LOG_LEVEL', 'INFO').upper()
return cls(
v_repo_path=repo_path,
v_ui_path=ui_path,
cache_ttl_seconds=cache_ttl,
max_search_results=max_results,
log_level=log_level
)
# Initialize FastMCP server
mcp = FastMCP("V Language Assistant")
# Load configuration
config = VServerConfig.from_env()
# Configure logging level
logging.getLogger().setLevel(getattr(logging, config.log_level, logging.INFO))
class VDocumentationServer:
"""Server for providing V language documentation and examples."""
def __init__(self, config: VServerConfig):
self.config = config
self.v_repo_path = config.v_repo_path
self.docs_path = config.v_repo_path / "doc"
self.examples_path = config.v_repo_path / "examples"
self.vlib_path = config.v_repo_path / "vlib"
# V UI paths (optional)
self.v_ui_path = config.v_ui_path
self.v_ui_examples_path = config.v_ui_path / "examples" if config.v_ui_path else None
self.v_ui_docs_path = config.v_ui_path / "docs.md" if config.v_ui_path else None
# Cache with TTL (time-to-live) in seconds
self._cache = {}
self._cache_ttl = config.cache_ttl_seconds
self._cache_timestamps = {}
self._max_search_results = config.max_search_results
# Store path validation results for graceful degradation
self._path_status = self._validate_paths()
def _validate_paths(self) -> Dict[str, bool]:
"""Validate that required paths exist and return status."""
path_status = {
"docs": self.docs_path.exists(),
"examples": self.examples_path.exists(),
"stdlib": self.vlib_path.exists(),
"v_ui": self.v_ui_path.exists() if self.v_ui_path else False,
"v_ui_examples": self.v_ui_examples_path.exists() if self.v_ui_examples_path else False
}
missing_paths = []
for component, exists in path_status.items():
if not exists and component not in ["v_ui", "v_ui_examples"]: # V UI is optional
path = getattr(self, f"{component}_path", None)
if path:
missing_paths.append(f"{component.title()}: {path}")
if missing_paths:
logger.warning(f"Some V repository components are missing: {', '.join(missing_paths)}")
logger.warning("Server functionality will be limited to available components")
else:
logger.info("All V repository components found successfully")
if path_status.get("v_ui"):
logger.info("V UI repository found and will be indexed")
elif self.v_ui_path:
logger.info(f"V UI repository path specified but not found: {self.v_ui_path}")
return path_status
def _get_cache(self, key: str) -> Any:
"""Get item from cache if it exists and hasn't expired."""
if key in self._cache:
if time.time() - self._cache_timestamps.get(key, 0) < self._cache_ttl:
return self._cache[key]
else:
# Remove expired entry
del self._cache[key]
del self._cache_timestamps[key]
return None
def _set_cache(self, key: str, value: Any) -> None:
"""Store item in cache with current timestamp."""
self._cache[key] = value
self._cache_timestamps[key] = time.time()
def _clear_expired_cache(self) -> None:
"""Remove all expired cache entries."""
current_time = time.time()
expired_keys = [
key for key, timestamp in self._cache_timestamps.items()
if current_time - timestamp >= self._cache_ttl
]
for key in expired_keys:
del self._cache[key]
del self._cache_timestamps[key]
def clear_cache(self) -> Dict[str, int]:
"""Clear all cache entries and return statistics."""
cache_count = len(self._cache)
timestamp_count = len(self._cache_timestamps)
self._cache.clear()
self._cache_timestamps.clear()
return {
"cleared_entries": cache_count,
"cleared_timestamps": timestamp_count,
"message": f"Cleared {cache_count} cache entries"
}
def get_cache_stats(self) -> Dict[str, int]:
"""Get cache statistics without clearing."""
return {
"entries": len(self._cache),
"timestamps": len(self._cache_timestamps),
"ttl_seconds": self._cache_ttl
}
def _validate_query(self, query: str, min_length: int = 2) -> str:
"""Validate and sanitize search query."""
if not query or len(query.strip()) < min_length:
raise ValueError(f"Query must be at least {min_length} characters long")
return query.strip()
def _read_file_content(self, file_path: Path) -> str:
"""Read file content safely."""
try:
if not file_path.exists():
return f"Error: File not found: {file_path}"
with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
return f.read()
except PermissionError:
return f"Error: Permission denied reading file {file_path}"
except UnicodeDecodeError:
return f"Error: Unable to decode file {file_path} (encoding issue)"
except Exception as e:
logger.error(f"Unexpected error reading file {file_path}: {e}")
return f"Error reading file {file_path}: {str(e)}"
def _search_in_file(self, file_path: Path, pattern: str, context_lines: int = 3) -> List[Dict]:
"""Search for pattern in file and return matches with enhanced context."""
try:
if not file_path.exists():
return [{'error': f'File not found: {file_path}'}]
if not pattern or len(pattern.strip()) < 1:
return [{'error': 'Search pattern cannot be empty'}]
with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
matches = []
# Create case-insensitive pattern with word boundaries for better matching
search_pattern = r'\b' + re.escape(pattern) + r'\b'
compiled_pattern = re.compile(search_pattern, re.IGNORECASE | re.MULTILINE)
lines = content.split('\n')
for i, line in enumerate(lines):
if compiled_pattern.search(line):
# Enhanced context: try to get paragraph-level context
start_line = max(0, i - context_lines)
end_line = min(len(lines), i + context_lines + 1)
# Look for paragraph boundaries (empty lines)
while start_line > 0 and lines[start_line - 1].strip():
start_line -= 1
while end_line < len(lines) and lines[end_line].strip():
end_line += 1
context_lines_list = lines[start_line:end_line]
context = '\n'.join(context_lines_list).strip()
# Calculate relevance score based on:
# - Exact match bonus
# - Position in line (earlier = higher score)
# - Context richness
score = 1.0
if pattern.lower() in line.lower():
score += 0.5 # Exact match bonus
if line.lower().startswith(pattern.lower()):
score += 0.3 # Starts with pattern bonus
if len(context) > len(line):
score += 0.2 # Rich context bonus
matches.append({
'line': i + 1,
'content': line.strip(),
'context': context,
'file': str(file_path.relative_to(self.v_repo_path)),
'score': score,
'pattern': pattern
})
# Sort by relevance score (highest first)
matches.sort(key=lambda x: x['score'], reverse=True)
return matches
except re.error as e:
return [{'error': f'Invalid regex pattern: {pattern} - {str(e)}'}]
except PermissionError:
return [{'error': f'Permission denied reading file: {file_path}'}]
except Exception as e:
logger.error(f'Unexpected error searching file {file_path}: {e}')
return [{'error': f'Error searching file {file_path}: {str(e)}'}]
def get_documentation_sections(self) -> Dict[str, str]:
"""Extract main sections from V documentation."""
cache_key = "docs_sections"
# Try cache first
cached_result = self._get_cache(cache_key)
if cached_result:
return cached_result
docs_file = self.docs_path / "docs.md"
if not docs_file.exists():
result = {"error": "Documentation file not found"}
self._set_cache(cache_key, result)
return result
content = self._read_file_content(docs_file)
# Split by main headers
sections = {}
current_section = None
current_content = []
for line in content.split('\n'):
if line.startswith('# '):
if current_section:
sections[current_section] = '\n'.join(current_content)
current_section = line[2:].strip()
current_content = [line]
elif line.startswith('## '):
if current_section:
sections[current_section] = '\n'.join(current_content)
current_section = line[3:].strip()
current_content = [line]
else:
current_content.append(line)
if current_section:
sections[current_section] = '\n'.join(current_content)
# Cache the result
self._set_cache(cache_key, sections)
return sections
def search_documentation(self, query: str) -> List[Dict]:
"""Search V documentation for relevant information."""
try:
query = self._validate_query(query)
docs_file = self.docs_path / "docs.md"
if not docs_file.exists():
return [{"error": f"Documentation file not found at {docs_file}"}]
return self._search_in_file(docs_file, query)
except ValueError as e:
return [{"error": str(e)}]
except Exception as e:
logger.error(f"Error searching documentation: {e}")
return [{"error": f"Failed to search documentation: {str(e)}"}]
def get_examples_list(self) -> List[Dict]:
"""Get list of available V examples."""
cache_key = "examples_list"
# Try cache first
cached_result = self._get_cache(cache_key)
if cached_result:
return cached_result
if not self.examples_path.exists():
result = [{"error": "Examples directory not found"}]
self._set_cache(cache_key, result)
return result
examples = []
for item in self.examples_path.rglob("*.v"):
if item.is_file():
examples.append({
'name': item.stem,
'path': str(item.relative_to(self.v_repo_path)),
'description': self._extract_example_description(item)
})
# Cache the result
self._set_cache(cache_key, examples)
return examples
def _extract_example_description(self, file_path: Path) -> str:
"""Extract description from example file comments."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()[:10] # Check first 10 lines
for line in lines:
if line.strip().startswith('//') or line.strip().startswith('/*'):
desc = line.strip()[2:].strip()
if desc and not desc.startswith('Copyright'):
return desc
except:
pass
return f"V example: {file_path.stem}"
def get_example_content(self, example_name: str) -> Dict:
"""Get content of a specific example."""
cache_key = f"example_content_{example_name}"
# Try cache first
cached_result = self._get_cache(cache_key)
if cached_result:
return cached_result
for item in self.examples_path.rglob(f"{example_name}.v"):
if item.is_file():
result = {
'name': example_name,
'path': str(item.relative_to(self.v_repo_path)),
'content': self._read_file_content(item)
}
# Cache the result
self._set_cache(cache_key, result)
return result
result = {"error": f"Example '{example_name}' not found"}
# Cache negative results too to avoid repeated filesystem searches
self._set_cache(cache_key, result)
return result
def search_examples(self, query: str) -> List[Dict]:
"""Search through V examples for patterns."""
try:
query = self._validate_query(query)
if not self.examples_path.exists():
return [{"error": f"Examples directory not found at {self.examples_path}"}]
results = []
v_files = list(self.examples_path.rglob("*.v"))
if not v_files:
return [{"error": "No V example files found"}]
for v_file in v_files[:self._max_search_results]: # Limit based on configuration
matches = self._search_in_file(v_file, query)
if matches:
for match in matches:
if 'error' not in match: # Only add successful matches
match['example_name'] = v_file.stem
results.append(match)
return results
except ValueError as e:
return [{"error": str(e)}]
except Exception as e:
logger.error(f"Error searching examples: {e}")
return [{"error": f"Failed to search examples: {str(e)}"}]
def get_stdlib_modules(self) -> List[Dict]:
"""Get list of V standard library modules."""
cache_key = "stdlib_modules"
# Try cache first
cached_result = self._get_cache(cache_key)
if cached_result:
return cached_result
if not self.vlib_path.exists():
result = [{"error": "Standard library directory not found"}]
self._set_cache(cache_key, result)
return result
modules = []
for item in self.vlib_path.iterdir():
if item.is_dir() and not item.name.startswith('.'):
readme_file = item / "README.md"
description = "V standard library module"
if readme_file.exists():
content = self._read_file_content(readme_file)
# Extract first meaningful line as description
for line in content.split('\n')[:5]:
line = line.strip()
if line and not line.startswith('#') and len(line) > 10:
description = line
break
modules.append({
'name': item.name,
'path': str(item.relative_to(self.v_repo_path)),
'description': description
})
sorted_modules = sorted(modules, key=lambda x: x['name'])
# Cache the result
self._set_cache(cache_key, sorted_modules)
return sorted_modules
def get_module_info(self, module_name: str) -> Dict:
"""Get information about a specific standard library module."""
module_path = self.vlib_path / module_name
if not module_path.exists():
return {"error": f"Module '{module_name}' not found"}
info = {
'name': module_name,
'files': [],
'readme': None
}
# Get README if available
readme_file = module_path / "README.md"
if readme_file.exists():
info['readme'] = self._read_file_content(readme_file)
# List V files in the module
for v_file in module_path.rglob("*.v"):
if v_file.is_file():
info['files'].append({
'name': v_file.name,
'path': str(v_file.relative_to(self.v_repo_path)),
'size': v_file.stat().st_size
})
return info
def get_v_ui_examples_list(self) -> List[Dict]:
"""Get a list of all V UI examples."""
cache_key = "v_ui_examples_list"
# Try cache first
cached_result = self._get_cache(cache_key)
if cached_result:
return cached_result
if not self.v_ui_examples_path or not self.v_ui_examples_path.exists():
result = [{"error": "V UI examples directory not found"}]
self._set_cache(cache_key, result)
return result
examples = []
for item in self.v_ui_examples_path.rglob("*.v"):
if item.is_file():
examples.append({
'name': item.stem,
'path': str(item.relative_to(self.v_ui_path)),
'full_path': str(item)
})
sorted_examples = sorted(examples, key=lambda x: x['name'])
# Cache the result
self._set_cache(cache_key, sorted_examples)
return sorted_examples
def get_v_ui_example_content(self, example_name: str) -> Dict:
"""Get the content of a specific V UI example."""
cache_key = f"v_ui_example_{example_name}"
# Try cache first
cached_result = self._get_cache(cache_key)
if cached_result:
return cached_result
if not self.v_ui_examples_path or not self.v_ui_examples_path.exists():
result = {"error": "V UI examples directory not found"}
self._set_cache(cache_key, result)
return result
# Search for the example file
for item in self.v_ui_examples_path.rglob(f"{example_name}.v"):
if item.is_file():
content = self._read_file_content(item)
result = {
'name': example_name,
'path': str(item.relative_to(self.v_ui_path)),
'content': content
}
self._set_cache(cache_key, result)
return result
result = {"error": f"V UI example '{example_name}' not found"}
self._set_cache(cache_key, result)
return result
def search_v_ui_examples(self, query: str) -> List[Dict]:
"""Search through V UI examples for specific patterns."""
try:
query = self._validate_query(query)
if not self.v_ui_examples_path or not self.v_ui_examples_path.exists():
return [{"error": f"V UI examples directory not found at {self.v_ui_examples_path}"}]
results = []
v_files = list(self.v_ui_examples_path.rglob("*.v"))
if not v_files:
return [{"error": "No V UI example files found"}]
for file_path in v_files:
matches = self._search_in_file(file_path, query)
for match in matches:
match['source'] = 'v_ui'
match['file'] = str(file_path.relative_to(self.v_ui_path))
results.append(match)
# Sort by relevance score and limit results
results.sort(key=lambda x: x.get('score', 0), reverse=True)
results = results[:self._max_search_results]
return results if results else [{"message": f"No matches found for '{query}' in V UI examples"}]
except ValueError as e:
return [{"error": str(e)}]
except Exception as e:
logger.error(f"Error searching V UI examples: {e}")
return [{"error": f"Error searching V UI examples: {str(e)}"}]
# Initialize the documentation server
v_server = VDocumentationServer(config)
# MCP Tools
@mcp.tool
def get_v_documentation(section: Optional[str] = None) -> str:
"""
Get V programming language documentation.
Provides access to the complete V programming language documentation.
When no section is specified, returns an overview of all available sections.
When a specific section is requested, returns detailed content for that section.
Args:
section: Optional specific section to retrieve (e.g., 'Structs', 'Functions', 'Modules')
Returns:
Documentation content for the requested section or overview of available sections
"""
try:
# Check if documentation is available
if not v_server._path_status.get("docs", False):
return """# V Documentation - Not Available
❌ **V documentation is not available on this system.**
This could be because:
- The V repository is not properly set up
- The documentation files are missing
- The V_REPO_PATH environment variable points to the wrong location
## Solutions:
1. **Verify V repository location:**
```bash
# Check if you're in the correct directory
ls -la
# Should see doc/, examples/, vlib/ directories
```
2. **Set V_REPO_PATH if needed:**
```bash
export V_REPO_PATH="/path/to/v/repository"
```
3. **Check server configuration:**
Use `get_v_config()` to see current settings
4. **Restart the MCP server** after fixing the path
**Alternative:** Use `explain_v_syntax(feature)` for specific language features or `get_v_quick_reference()` for basic syntax."""
sections = v_server.get_documentation_sections()
if "error" in sections:
return f"""# V Documentation - Error
❌ **Error loading V documentation:** {sections['error']}
This might be a temporary issue. Try:
- `clear_v_cache()` to refresh cached content
- `get_v_config()` to check server status
- Restarting the MCP server
**Alternative resources:**
- Use `explain_v_syntax(feature)` for specific language features
- Use `get_v_quick_reference()` for basic syntax reference"""
if section:
if section in sections:
return f"# {section}\n\n{sections[section]}"
else:
available_sections = list(sections.keys())
return f"""# Section Not Found
❌ **Section '{section}' not found in V documentation.**
**Available sections:**
{chr(10).join(f"- {sec}" for sec in available_sections[:10])}
**Suggestions:**
- Check spelling and capitalization
- Use `get_v_documentation()` to see all sections
- Try `search_v_docs('{section}')` for related content"""
else:
# Return overview of main sections
overview = "# V Programming Language Documentation\n\n"
overview += f"✅ **Documentation loaded successfully** ({len(sections)} sections available)\n\n"
overview += "**Available sections:**\n\n"
for sec in sections.keys():
overview += f"- {sec}\n"
overview += "\n**Usage:** `get_v_documentation(section_name)` to get specific sections."
return overview
except Exception as e:
logger.error(f"Unexpected error in get_v_documentation: {e}")
return f"""# Documentation Error
❌ **Unexpected error loading V documentation:** {str(e)}
Please try:
- `get_v_config()` to check server status
- `clear_v_cache()` to reset cache
- Restarting the MCP server
**Alternative:** Use `explain_v_syntax(feature)` for specific language features."""
@mcp.tool
def search_v_docs(query: str) -> str:
"""
Search through V documentation for specific topics.
Performs full-text search across the V programming language documentation.
Returns relevant sections with context where the search terms are found.
Args:
query: Search term to look for in V documentation (minimum 2 characters)
Returns:
Search results with relevant documentation sections and context
"""
results = v_server.search_documentation(query)
if not results:
return f"No results found for '{query}' in V documentation."
output = f"# Search Results for '{query}'\n\n"
successful_results = [r for r in results if 'error' not in r]
if successful_results:
output += f"Found {len(successful_results)} matches (showing top 10):\n\n"
for result in successful_results[:10]: # Show top 10 by relevance score
output += f"**File:** {result['file']}\n"
output += f"**Line {result['line']}:** {result['content']}\n"
output += f"**Context:**\n```\n{result['context']}\n```\n\n"
else:
# Show any error messages
for result in results:
if 'error' in result:
output += f"Error: {result['error']}\n\n"
return output
@mcp.tool
def list_v_examples() -> str:
"""
Get a list of available V programming examples.
Returns a comprehensive list of all available V code examples from the repository.
Each example includes its name, file path, and description extracted from comments.
Returns:
Formatted list of example programs with descriptions (shows first 20 examples)
"""
try:
# Check if examples are available
if not v_server._path_status.get("examples", False):
return """# V Examples - Not Available
❌ **V code examples are not available on this system.**
This could be because:
- The V repository is not properly set up
- The examples directory is missing
- The V_REPO_PATH environment variable points to the wrong location
## Solutions:
1. **Verify examples directory exists:**
```bash
# Check if examples directory exists
ls -la examples/
```
2. **Set V_REPO_PATH if needed:**
```bash
export V_REPO_PATH="/path/to/v/repository"
```
3. **Check server configuration:**
Use `get_v_config()` to see current settings
4. **Restart the MCP server** after fixing the path
**Alternative:** Use `explain_v_syntax(feature)` to learn V language features with code examples."""
examples = v_server.get_examples_list()
if not examples:
return """# No Examples Found
❌ **No V examples were found.**
This might be because:
- The examples directory exists but is empty
- File permissions prevent reading
- The V repository structure has changed
Try:
- `get_v_config()` to check server status
- `clear_v_cache()` to refresh cached content
- Restarting the MCP server"""
# Check if there are any actual examples (not just error entries)
valid_examples = [ex for ex in examples if 'error' not in ex]
error_examples = [ex for ex in examples if 'error' in ex]
output = "# V Programming Examples\n\n"
if error_examples:
output += f"⚠️ **Warning:** {len(error_examples)} example(s) could not be loaded.\n\n"
if valid_examples:
output += f"✅ **Found {len(valid_examples)} examples**\n\n"
for example in valid_examples[:20]: # Limit to first 20 examples
output += f"**{example['name']}**\n"
output += f"- Path: {example['path']}\n"
output += f"- Description: {example['description']}\n\n"
if len(valid_examples) > 20:
output += f"\n*Showing first 20 of {len(valid_examples)} examples.*\n"
output += "*Use `get_v_example(name)` to see the full code for any example.*"
else:
output += "*Use `get_v_example(name)` to see the full code for any example.*"
else:
output += "❌ **No valid examples could be loaded.**\n\n"
output += "**Troubleshooting:**\n"
output += "- Check file permissions in the examples directory\n"
output += "- Verify the examples contain .v files\n"
output += "- Try `get_v_config()` for detailed status"
return output
except Exception as e:
logger.error(f"Unexpected error in list_v_examples: {e}")
return f"""# Examples Error
❌ **Unexpected error loading V examples:** {str(e)}
Please try:
- `get_v_config()` to check server status
- `clear_v_cache()` to reset cache
- Restarting the MCP server
**Alternative:** Use `explain_v_syntax(feature)` for language feature explanations."""
@mcp.tool
def get_v_example(example_name: str) -> str:
"""
Get the source code of a specific V example.
Retrieves the complete source code for a named V programming example.
The example name should match the filename without the .v extension.
Args:
example_name: Name of the example to retrieve (e.g., 'fibonacci', 'hello_world')
Returns:
Complete source code of the example with syntax highlighting, or error message if not found
"""
result = v_server.get_example_content(example_name)
if 'error' in result:
return f"""# Example Not Found
❌ **Example '{example_name}' not found.**
**Possible reasons:**
- Incorrect spelling or capitalization
- Example doesn't exist in the repository
- Examples directory is not available
**Suggestions:**
- Use `list_v_examples()` to see all available examples
- Try `search_v_examples('{example_name}')` for similar examples
- Check `get_v_config()` for server status
**Error details:** {result['error']}"""
output = f"# V Example: {result['name']}\n\n"
output += f"**Path:** {result['path']}\n\n"
output += "## Source Code\n\n"
output += f"```v\n{result['content']}\n```\n"
return output
@mcp.tool
def search_v_examples(query: str) -> str:
"""
Search through V example code for specific patterns or features.
Performs full-text search across all V programming examples in the repository.
Useful for finding code patterns, specific functions, or language features in use.
Args:
query: Search term to look for in example code (minimum 2 characters)
Returns:
Examples containing the search term with context and file information
"""
results = v_server.search_examples(query)
if not results:
return f"No examples found containing '{query}'."
output = f"# Examples containing '{query}'\n\n"
successful_results = [r for r in results if 'error' not in r]
if successful_results:
output += f"Found {len(successful_results)} matches across examples:\n\n"
current_example = None
for result in successful_results[:15]: # Show top 15 results
if current_example != result['example_name']:
current_example = result['example_name']
output += f"## Example: {current_example}\n\n"
output += f"**File:** {result['file']}\n"
output += f"**Line {result['line']}:** {result['content']}\n"
output += f"**Context:**\n```v\n{result['context']}\n```\n\n"
else:
# Show any error messages
for result in results:
if 'error' in result:
output += f"Error: {result['error']}\n\n"
return output
@mcp.tool
def list_v_stdlib_modules() -> str:
"""
Get a list of V standard library modules.
Returns a comprehensive list of all available modules in V's standard library.
Each module includes its name, description, and indicates its functionality.
Returns:
Formatted list of standard library modules with descriptions
"""
modules = v_server.get_stdlib_modules()
if not modules:
return "No standard library modules found."
output = "# V Standard Library Modules\n\n"
for module in modules:
if 'error' in module:
output += f"Error: {module['error']}\n"
else:
output += f"**{module['name']}**\n"
output += f"- Description: {module['description']}\n\n"
output += "\nUse `get_v_module_info(module_name)` to get detailed information about a specific module."
return output
@mcp.tool
def get_v_module_info(module_name: str) -> str:
"""
Get detailed information about a V standard library module.
Provides comprehensive information about a specific V standard library module,
including its README documentation (if available) and list of source files.
Args:
module_name: Name of the module to get information about (e.g., 'os', 'json', 'net')
Returns:
Detailed information including files, documentation, and module structure
"""
result = v_server.get_module_info(module_name)
if 'error' in result:
return f"Error: {result['error']}\n\nUse `list_v_stdlib_modules()` to see available modules."
output = f"# V Standard Library Module: {result['name']}\n\n"
if result['readme']:
output += "## Documentation\n\n"
output += result['readme']
output += "\n\n"
if result['files']:
output += "## Files\n\n"
for file_info in result['files'][:10]: # Limit to first 10 files
output += f"- **{file_info['name']}** ({file_info['size']} bytes)\n"
output += f" - Path: {file_info['path']}\n"
if len(result['files']) > 10:
output += f"\n*... and {len(result['files']) - 10} more files*\n"
return output
@mcp.tool
def explain_v_syntax(feature: str) -> str:
"""
Explain V programming language syntax and features.
Provides detailed explanations of V programming language concepts and syntax.
Includes code examples and practical usage patterns for each feature.
Args:
feature: The V language feature to explain (e.g., 'arrays', 'structs', 'functions', 'concurrency')
Returns:
Comprehensive explanation of the requested V language feature with examples
"""
# Common V language features and their explanations
features = {
'variables': """
# V Variables
V supports several types of variables: