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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
|
# Semantic MCP Server - Comprehensive Design Document
## 1. Executive Summary
The **Semantic MCP Server** provides intelligent, symbol-aware code operations that go beyond text manipulation to understand code structure, relationships, and semantics. Inspired by [Serena](https://github.com/oraios/serena), this server enables AI assistants to perform precise code editing, analysis, and refactoring at the semantic level.
### Key Value Propositions
- **Symbol-first operations**: Edit functions, classes, and variables as semantic units
- **Cross-language consistency**: Unified interface for Go, Rust, Python, TypeScript, Java, C#
- **Relationship awareness**: Understand how code symbols interact and depend on each other
- **Safe refactoring**: Precise edits with automatic context preservation
- **AI-optimized**: Designed specifically for LLM workflows and code understanding
## 2. Architecture Overview
### 2.1 Core Components
```
SemanticServer
├── LanguageServerManager # LSP client pool for different languages
├── SymbolManager # Symbol discovery, caching, and operations
├── ProjectManager # Project context and boundary management
├── ToolRegistry # 20+ semantic tools for code operations
└── IntegrationLayer # Connects to existing MCP ecosystem
```
### 2.2 Technology Stack
**Language Server Protocol (LSP) Foundation:**
- **Primary approach**: Leverage existing language servers (gopls, rust-analyzer, pylsp, etc.)
- **Protocol**: JSON-RPC communication with language servers
- **Synchronous wrapper**: Simplified async handling for tool reliability
**Supporting Technologies:**
- **Tree-sitter**: Fallback parsing for languages without LSP support
- **File watching**: Monitor project changes for cache invalidation
- **Symbol caching**: In-memory and persistent symbol information
- **Project indexing**: Background analysis for large codebases
### 2.3 Integration Architecture
```mermaid
graph TB
Claude[Claude Code] --> MCP[Semantic MCP Server]
MCP --> LSM[Language Server Manager]
MCP --> SM[Symbol Manager]
MCP --> PM[Project Manager]
LSM --> gopls[gopls - Go]
LSM --> rust[rust-analyzer]
LSM --> pylsp[Python LSP]
LSM --> tsserver[TypeScript Server]
SM --> Cache[Symbol Cache]
SM --> Index[Project Index]
MCP --> Git[Git MCP Server]
MCP --> FS[Filesystem MCP Server]
MCP --> Mem[Memory MCP Server]
```
## 3. Tool Specification
### 3.1 Symbol Discovery Tools
#### `semantic_find_symbol`
**Purpose**: Find symbols by name, type, or pattern across the project
**Parameters:**
```json
{
"name": "UserService.authenticate", // Symbol path or pattern
"kind": "method", // function, class, variable, etc.
"scope": "project", // project, file, directory
"language": "go", // Optional language filter
"include_children": false, // Include child symbols
"max_results": 50 // Limit results
}
```
**Response:**
```json
{
"symbols": [
{
"name": "authenticate",
"full_path": "UserService.authenticate",
"kind": "method",
"file_path": "src/services/user.go",
"location": {"line": 45, "column": 6},
"signature": "func (u *UserService) authenticate(email, password string) (*User, error)",
"visibility": "public",
"language": "go"
}
],
"total_found": 1
}
```
#### `semantic_get_overview`
**Purpose**: Get high-level symbol overview of files or directories
**Parameters:**
```json
{
"path": "src/services", // File or directory path
"depth": 2, // How deep to analyze
"include_kinds": ["class", "function"], // Filter symbol types
"exclude_private": true // Skip private symbols
}
```
### 3.2 Symbol Analysis Tools
#### `semantic_get_references`
**Purpose**: Find all places where a symbol is used
**Parameters:**
```json
{
"symbol": "UserService.authenticate", // Target symbol
"include_definitions": false, // Include definition location
"context_lines": 3, // Lines of context around usage
"filter_by_kind": ["call", "import"] // Type of references
}
```
#### `semantic_get_definition`
**Purpose**: Get detailed information about a symbol's definition
**Parameters:**
```json
{
"symbol": "UserService.authenticate", // Target symbol
"include_signature": true, // Include full signature
"include_documentation": true, // Include comments/docs
"include_dependencies": true // Include what this symbol uses
}
```
#### `semantic_get_call_hierarchy`
**Purpose**: Understand calling relationships (what calls this, what this calls)
**Parameters:**
```json
{
"symbol": "UserService.authenticate", // Target symbol
"direction": "both", // "incoming", "outgoing", "both"
"max_depth": 3, // How many levels deep
"include_external": false // Include calls to external packages
}
```
### 3.3 Symbol Editing Tools
#### `semantic_replace_symbol`
**Purpose**: Replace a symbol's implementation while preserving context
**Parameters:**
```json
{
"symbol": "UserService.authenticate", // Target symbol to replace
"new_code": "func (u *UserService) authenticate(email, password string) (*User, error) {\n // New implementation\n}",
"preserve_signature": true, // Keep existing signature
"preserve_comments": true, // Keep existing documentation
"dry_run": false // Preview changes without applying
}
```
#### `semantic_insert_after_symbol`
**Purpose**: Insert new code after a specific symbol
**Parameters:**
```json
{
"target_symbol": "UserService.authenticate", // Reference point
"new_code": "func (u *UserService) logout() error {\n // Implementation\n}",
"auto_indent": true, // Match indentation
"add_spacing": true // Add appropriate spacing
}
```
#### `semantic_rename_symbol`
**Purpose**: Rename a symbol across the entire project
**Parameters:**
```json
{
"old_name": "UserService.authenticate", // Current symbol name
"new_name": "UserService.login", // New symbol name
"scope": "project", // "file", "package", "project"
"preview_changes": true, // Show what will be changed
"include_comments": true // Update references in comments
}
```
### 3.4 Project Analysis Tools
#### `semantic_analyze_dependencies`
**Purpose**: Analyze symbol dependencies and relationships
**Parameters:**
```json
{
"scope": "src/services", // Analysis scope
"include_external": false, // Include external dependencies
"group_by": "package", // "file", "package", "kind"
"show_unused": true // Highlight unused symbols
}
```
#### `semantic_get_impact_analysis`
**Purpose**: Analyze what would be affected by changing a symbol
**Parameters:**
```json
{
"symbol": "UserService.authenticate", // Symbol to analyze
"change_type": "signature", // "delete", "rename", "signature"
"include_tests": true, // Include test file impacts
"include_docs": true // Include documentation impacts
}
```
## 4. Implementation Details
### 4.1 Language Server Integration
**Supported Languages & Servers:**
```go
type LanguageServerConfig struct {
Language string `json:"language"`
ServerCmd string `json:"server_cmd"`
Args []string `json:"args"`
FileExts []string `json:"file_extensions"`
Initialized bool `json:"initialized"`
}
var DefaultLanguageServers = map[string]LanguageServerConfig{
"go": {
Language: "go",
ServerCmd: "gopls",
Args: []string{"serve"},
FileExts: []string{".go"},
},
"rust": {
Language: "rust",
ServerCmd: "rust-analyzer",
Args: []string{},
FileExts: []string{".rs"},
},
"ruby": {
Language: "ruby",
ServerCmd: "solargraph",
Args: []string{"stdio"},
FileExts: []string{".rb", ".rbw", ".rake", ".gemspec"},
},
"python": {
Language: "python",
ServerCmd: "pylsp",
Args: []string{},
FileExts: []string{".py"},
},
"typescript": {
Language: "typescript",
ServerCmd: "typescript-language-server",
Args: []string{"--stdio"},
FileExts: []string{".ts", ".tsx", ".js", ".jsx"},
},
"html": {
Language: "html",
ServerCmd: "vscode-html-language-server",
Args: []string{"--stdio"},
FileExts: []string{".html", ".htm", ".xhtml"},
},
"css": {
Language: "css",
ServerCmd: "vscode-css-language-server",
Args: []string{"--stdio"},
FileExts: []string{".css", ".scss", ".sass", ".less"},
},
"java": {
Language: "java",
ServerCmd: "jdtls",
Args: []string{},
FileExts: []string{".java"},
},
"csharp": {
Language: "csharp",
ServerCmd: "omnisharp",
Args: []string{"--stdio"},
FileExts: []string{".cs"},
},
}
```
**LSP Communication Pattern:**
```go
type LSPClient struct {
cmd *exec.Cmd
stdin io.WriteCloser
stdout io.ReadCloser
stderr io.ReadCloser
requestID int
responses map[int]chan LSPResponse
mu sync.RWMutex
}
func (c *LSPClient) SendRequest(method string, params interface{}) (*LSPResponse, error) {
c.mu.Lock()
requestID := c.requestID
c.requestID++
c.mu.Unlock()
request := LSPRequest{
JSONRPC: "2.0",
ID: requestID,
Method: method,
Params: params,
}
// Send request and wait for response
return c.sendAndWait(request)
}
```
### 4.2 Symbol Management
**Symbol Representation:**
```go
type Symbol struct {
Name string `json:"name"`
FullPath string `json:"full_path"`
Kind SymbolKind `json:"kind"`
Location SourceLocation `json:"location"`
Signature string `json:"signature,omitempty"`
Documentation string `json:"documentation,omitempty"`
Visibility string `json:"visibility"`
Language string `json:"language"`
Children []Symbol `json:"children,omitempty"`
References []SourceLocation `json:"references,omitempty"`
Dependencies []string `json:"dependencies,omitempty"`
}
type SymbolKind string
const (
SymbolKindFile SymbolKind = "file"
SymbolKindModule SymbolKind = "module"
SymbolKindNamespace SymbolKind = "namespace"
SymbolKindPackage SymbolKind = "package"
SymbolKindClass SymbolKind = "class"
SymbolKindMethod SymbolKind = "method"
SymbolKindProperty SymbolKind = "property"
SymbolKindField SymbolKind = "field"
SymbolKindConstructor SymbolKind = "constructor"
SymbolKindEnum SymbolKind = "enum"
SymbolKindInterface SymbolKind = "interface"
SymbolKindFunction SymbolKind = "function"
SymbolKindVariable SymbolKind = "variable"
SymbolKindConstant SymbolKind = "constant"
SymbolKindString SymbolKind = "string"
SymbolKindNumber SymbolKind = "number"
SymbolKindBoolean SymbolKind = "boolean"
SymbolKindArray SymbolKind = "array"
SymbolKindObject SymbolKind = "object"
SymbolKindKey SymbolKind = "key"
SymbolKindNull SymbolKind = "null"
SymbolKindEnumMember SymbolKind = "enum_member"
SymbolKindStruct SymbolKind = "struct"
SymbolKindEvent SymbolKind = "event"
SymbolKindOperator SymbolKind = "operator"
SymbolKindTypeParameter SymbolKind = "type_parameter"
)
type SourceLocation struct {
FilePath string `json:"file_path"`
Line int `json:"line"`
Column int `json:"column"`
EndLine int `json:"end_line,omitempty"`
EndColumn int `json:"end_column,omitempty"`
}
```
**Symbol Cache Management:**
```go
type SymbolCache struct {
symbols map[string][]Symbol // file_path -> symbols
references map[string][]Reference // symbol_path -> references
index map[string][]string // name -> file_paths
lastUpdate map[string]time.Time // file_path -> last_modified
mu sync.RWMutex
}
func (c *SymbolCache) InvalidateFile(filePath string) {
c.mu.Lock()
defer c.mu.Unlock()
// Remove symbols for this file
delete(c.symbols, filePath)
delete(c.lastUpdate, filePath)
// Update index
c.rebuildIndex()
}
func (c *SymbolCache) FindSymbolsByName(name string) []Symbol {
c.mu.RLock()
defer c.mu.RUnlock()
var results []Symbol
if filePaths, exists := c.index[name]; exists {
for _, filePath := range filePaths {
if symbols, exists := c.symbols[filePath]; exists {
for _, symbol := range symbols {
if symbol.Name == name || strings.Contains(symbol.FullPath, name) {
results = append(results, symbol)
}
}
}
}
}
return results
}
```
### 4.3 Project Management
**Project Context:**
```go
type ProjectManager struct {
rootPath string
gitignoreRules []string
languageFiles map[string][]string // language -> file_paths
projectConfig *ProjectConfig
watcher *fsnotify.Watcher
mu sync.RWMutex
}
type ProjectConfig struct {
Name string `json:"name"`
RootPath string `json:"root_path"`
Languages []string `json:"languages"`
ExcludePatterns []string `json:"exclude_patterns"`
IncludePatterns []string `json:"include_patterns"`
CustomSettings map[string]string `json:"custom_settings"`
}
func (pm *ProjectManager) DiscoverProject(rootPath string) error {
// 1. Detect languages by file extensions
// 2. Load .gitignore and exclude patterns
// 3. Scan for language-specific config files
// 4. Initialize project boundaries
// 5. Start file system watcher
}
func (pm *ProjectManager) GetFilesByLanguage(language string) []string {
pm.mu.RLock()
defer pm.mu.RUnlock()
return pm.languageFiles[language]
}
func (pm *ProjectManager) IsFileInProject(filePath string) bool {
// Check if file is within project boundaries
// Apply gitignore and exclude patterns
// Validate file extension for supported languages
}
```
### 4.4 Integration with Existing MCP Servers
**Git Integration:**
```go
func (s *SemanticServer) handleSemanticCommitSymbols(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
var args struct {
Symbols []string `json:"symbols"`
Message string `json:"message"`
}
// 1. Find all files containing the symbols
files := s.getFilesForSymbols(args.Symbols)
// 2. Call git MCP server to stage files
gitResult := s.callGitServer("git_add", map[string]interface{}{
"files": files,
})
// 3. Generate semantic commit message
semanticMessage := s.generateSemanticCommitMessage(args.Symbols, args.Message)
// 4. Call git MCP server to commit
return s.callGitServer("git_commit", map[string]interface{}{
"message": semanticMessage,
})
}
```
**Memory Integration:**
```go
func (s *SemanticServer) handleStoreSymbolGraph(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
// 1. Analyze symbol relationships in project
graph := s.buildSymbolDependencyGraph()
// 2. Convert to memory MCP format
entities := s.convertSymbolsToEntities(graph.Symbols)
relations := s.convertDependenciesToRelations(graph.Dependencies)
// 3. Store in memory MCP server
memoryResult := s.callMemoryServer("create_entities", map[string]interface{}{
"entities": entities,
})
return s.callMemoryServer("create_relations", map[string]interface{}{
"relations": relations,
})
}
```
**Filesystem Integration:**
```go
func (s *SemanticServer) handleSemanticReadFile(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
var args struct {
FilePath string `json:"file_path"`
Symbols []string `json:"symbols,omitempty"`
}
if len(args.Symbols) == 0 {
// Fallback to regular file read
return s.callFilesystemServer("read_file", map[string]interface{}{
"file_path": args.FilePath,
})
}
// 1. Get symbols from file
symbols := s.getSymbolsFromFile(args.FilePath, args.Symbols)
// 2. Extract code for specified symbols only
codeSegments := s.extractSymbolCode(args.FilePath, symbols)
// 3. Return structured response
return mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: s.formatSymbolCode(codeSegments),
},
},
}, nil
}
```
## 5. Performance Considerations
### 5.1 Language Server Management
**Connection Pooling:**
```go
type LanguageServerPool struct {
servers map[string]*LSPClient
maxIdle time.Duration
mu sync.RWMutex
}
func (p *LanguageServerPool) GetServer(language string) (*LSPClient, error) {
p.mu.RLock()
if server, exists := p.servers[language]; exists && server.IsHealthy() {
p.mu.RUnlock()
return server, nil
}
p.mu.RUnlock()
// Start new language server
return p.startLanguageServer(language)
}
```
**Lazy Initialization:**
- Language servers started on-demand when first tool call requires them
- Automatic shutdown after idle timeout to conserve resources
- Health checking to restart failed servers
**Request Batching:**
```go
func (s *SemanticServer) batchSymbolRequests(requests []SymbolRequest) []Symbol {
// Group requests by language/file for efficient LSP calls
batches := s.groupRequestsByLanguage(requests)
var results []Symbol
for language, batch := range batches {
languageResults := s.processLanguageBatch(language, batch)
results = append(results, languageResults...)
}
return results
}
```
### 5.2 Caching Strategy
**Multi-Level Caching:**
1. **In-Memory Cache**: Hot symbols and recent operations
2. **File-based Cache**: Persistent symbol index across sessions
3. **Incremental Updates**: Only re-analyze changed files
**Cache Invalidation:**
```go
func (s *SemanticServer) onFileChanged(filePath string) {
// 1. Invalidate symbol cache for file
s.symbolCache.InvalidateFile(filePath)
// 2. Invalidate dependent files (imports, etc.)
dependentFiles := s.getDependentFiles(filePath)
for _, depFile := range dependentFiles {
s.symbolCache.InvalidateFile(depFile)
}
// 3. Trigger background re-analysis
go s.reanalyzeFile(filePath)
}
```
### 5.3 Scalability Limits
**Resource Limits:**
- **Max concurrent language servers**: 5
- **Symbol cache size**: 50MB per project
- **File watch limit**: 10,000 files
- **Symbol query timeout**: 30 seconds
**Large Project Optimization:**
```go
func (s *SemanticServer) optimizeForLargeProject(projectSize int) {
if projectSize > 100000 { // 100k+ files
// Enable aggressive caching
s.symbolCache.SetMaxSize(200 * 1024 * 1024) // 200MB
// Reduce file watching scope
s.projectManager.SetWatchPatterns([]string{
"**/*.go", "**/*.rs", "**/*.py", "**/*.ts",
})
// Enable background indexing
s.enableBackgroundIndexing()
}
}
```
## 6. Error Handling & Reliability
### 6.1 Language Server Failures
**Graceful Degradation:**
```go
func (s *SemanticServer) handleSymbolRequest(req SymbolRequest) (*Symbol, error) {
// Try LSP first
if server, err := s.getLanguageServer(req.Language); err == nil {
if symbol, err := server.GetSymbol(req); err == nil {
return symbol, nil
}
}
// Fallback to tree-sitter parsing
if parser, err := s.getTreeSitterParser(req.Language); err == nil {
return parser.ParseSymbol(req)
}
// Final fallback to regex-based parsing
return s.parseSymbolWithRegex(req)
}
```
**Health Monitoring:**
```go
func (s *SemanticServer) monitorLanguageServerHealth() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for range ticker.C {
for language, server := range s.languageServers {
if !server.IsHealthy() {
log.Printf("Language server %s is unhealthy, restarting", language)
s.restartLanguageServer(language)
}
}
}
}
```
### 6.2 File System Issues
**Concurrent Access:**
```go
func (s *SemanticServer) safeFileOperation(filePath string, operation func() error) error {
// File-level locking to prevent concurrent modifications
lock := s.getFileLock(filePath)
lock.Lock()
defer lock.Unlock()
// Verify file still exists and is accessible
if !s.isFileAccessible(filePath) {
return fmt.Errorf("file not accessible: %s", filePath)
}
return operation()
}
```
**Data Integrity:**
```go
func (s *SemanticServer) validateSymbolData(symbol *Symbol) error {
if symbol.Name == "" {
return errors.New("symbol name is required")
}
if symbol.Location.Line < 1 {
return errors.New("invalid symbol location")
}
if !s.projectManager.IsFileInProject(symbol.Location.FilePath) {
return errors.New("symbol file is outside project boundaries")
}
return nil
}
```
## 7. Configuration & Deployment
### 7.1 Server Configuration
**Configuration File** (`semantic-config.json`):
```json
{
"project": {
"auto_discover": true,
"max_project_size": 100000,
"exclude_patterns": [
"**/node_modules/**",
"**/vendor/**",
"**/.git/**",
"**/target/**",
"**/dist/**"
]
},
"language_servers": {
"go": {
"enabled": true,
"server_cmd": "gopls",
"args": ["serve"],
"timeout": 30
},
"rust": {
"enabled": true,
"server_cmd": "rust-analyzer",
"timeout": 60
}
},
"cache": {
"max_memory_mb": 100,
"persist_to_disk": true,
"cache_dir": "$HOME/.mcp/semantic-cache"
},
"performance": {
"max_concurrent_servers": 5,
"symbol_query_timeout": 30,
"file_watch_enabled": true
}
}
```
**Command Line Flags:**
```bash
mcp-semantic \
--project-root=/path/to/project \
--config=/path/to/semantic-config.json \
--cache-dir=/path/to/cache \
--log-level=info \
--enable-dashboard \
--dashboard-port=8080
```
### 7.2 Dependencies
**Language Server Requirements:**
```bash
# Go
go install golang.org/x/tools/gopls@latest
# Rust
rustup component add rust-analyzer
# Ruby
gem install solargraph
# Python
pip install python-lsp-server
# JavaScript/TypeScript
npm install -g typescript-language-server typescript
# HTML
npm install -g vscode-langservers-extracted
# CSS
npm install -g vscode-langservers-extracted
# Java (Eclipse JDT Language Server)
# Download from: https://download.eclipse.org/jdtls/snapshots/
# C# (OmniSharp)
# Download from: https://github.com/OmniSharp/omnisharp-roslyn
```
**Optional Dependencies:**
```bash
# Tree-sitter parsers for fallback parsing
npm install tree-sitter tree-sitter-go tree-sitter-rust tree-sitter-python
# File watching
go get github.com/fsnotify/fsnotify
# Git integration
go get github.com/go-git/go-git/v5
```
### 7.3 Integration Setup
**Claude Code Configuration:**
```json
{
"mcpServers": {
"semantic": {
"command": "/usr/local/bin/mcp-semantic",
"args": [
"--project-root", ".",
"--config", "~/.config/semantic-mcp.json"
]
}
}
}
```
**Goose Integration:**
```yaml
# ~/.config/goose/contexts/semantic-dev.yaml
GOOSE_MODEL: qwen2.5
GOOSE_PROVIDER: ollama
mcp_servers:
semantic:
command: /usr/local/bin/mcp-semantic
args: ["--project-root", "."]
git:
command: /usr/local/bin/mcp-git
args: ["--repository", "."]
filesystem:
command: /usr/local/bin/mcp-filesystem
args: ["--allowed-directory", "."]
```
## 8. Testing Strategy
### 8.1 Unit Tests
**Symbol Management Tests:**
```go
func TestSymbolCache_FindByName(t *testing.T) {
cache := NewSymbolCache()
// Add test symbols
symbols := []Symbol{
{Name: "UserService", FullPath: "services.UserService", Kind: SymbolKindClass},
{Name: "authenticate", FullPath: "services.UserService.authenticate", Kind: SymbolKindMethod},
}
cache.AddSymbols("test.go", symbols)
// Test search
results := cache.FindSymbolsByName("authenticate")
assert.Len(t, results, 1)
assert.Equal(t, "authenticate", results[0].Name)
}
```
**Language Server Integration Tests:**
```go
func TestLSPClient_GetSymbols(t *testing.T) {
if !hasLanguageServer("go") {
t.Skip("gopls not available")
}
client, err := NewLSPClient("go")
require.NoError(t, err)
defer client.Shutdown()
symbols, err := client.GetDocumentSymbols("testdata/sample.go")
require.NoError(t, err)
assert.Greater(t, len(symbols), 0)
}
```
### 8.2 Integration Tests
**End-to-End Workflow Tests:**
```go
func TestSemanticWorkflow_FindAndEdit(t *testing.T) {
server := setupTestServer(t)
defer server.Shutdown()
// 1. Find symbol
findReq := mcp.CallToolRequest{
Name: "semantic_find_symbol",
Arguments: map[string]interface{}{
"name": "UserService.authenticate",
"kind": "method",
},
}
findResult, err := server.CallTool(findReq)
require.NoError(t, err)
// 2. Edit symbol
editReq := mcp.CallToolRequest{
Name: "semantic_replace_symbol",
Arguments: map[string]interface{}{
"symbol": "UserService.authenticate",
"new_code": "func (u *UserService) authenticate(email, password string) (*User, error) {\n return nil, nil\n}",
},
}
editResult, err := server.CallTool(editReq)
require.NoError(t, err)
// 3. Verify edit was applied
// ... verification logic
}
```
### 8.3 Performance Tests
**Benchmark Large Projects:**
```go
func BenchmarkSymbolSearch_LargeProject(b *testing.B) {
server := setupLargeProjectServer(b) // 10k+ files
defer server.Shutdown()
req := mcp.CallToolRequest{
Name: "semantic_find_symbol",
Arguments: map[string]interface{}{
"name": "main",
"scope": "project",
},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := server.CallTool(req)
require.NoError(b, err)
}
}
```
**Memory Usage Tests:**
```go
func TestMemoryUsage_SymbolCache(t *testing.T) {
var m1, m2 runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&m1)
// Load large project
server := setupLargeProjectServer(t)
defer server.Shutdown()
runtime.GC()
runtime.ReadMemStats(&m2)
memoryUsed := m2.Alloc - m1.Alloc
assert.Less(t, memoryUsed, uint64(100*1024*1024)) // <100MB
}
```
## 9. Future Enhancements
### 9.1 Advanced Features
**AI-Powered Code Analysis:**
```go
// semantic_suggest_refactoring
func (s *SemanticServer) suggestRefactoring(symbol *Symbol) []RefactoringSuggestion {
// Analyze code patterns, complexity, dependencies
// Suggest extract method, rename, move class, etc.
}
// semantic_generate_tests
func (s *SemanticServer) generateTests(symbol *Symbol) string {
// Generate unit tests based on symbol signature and dependencies
}
// semantic_optimize_imports
func (s *SemanticServer) optimizeImports(filePath string) []ImportChange {
// Remove unused imports, organize, suggest better imports
}
```
**Cross-Project Analysis:**
```go
// semantic_find_duplicate_code
func (s *SemanticServer) findDuplicateCode(threshold float64) []DuplicateMatch {
// Find similar code patterns across projects
}
// semantic_track_symbol_evolution
func (s *SemanticServer) trackSymbolEvolution(symbol string) []SymbolChange {
// Track how symbols change over time via git history
}
```
### 9.2 Language Extensions
**Additional Language Support:**
- **PHP**: PHP Language Server
- **Ruby**: Solargraph
- **C/C++**: clangd
- **Swift**: sourcekit-lsp
- **Kotlin**: Kotlin Language Server
**Domain-Specific Languages:**
- **SQL**: SQL language server for database schema analysis
- **YAML/JSON**: Schema-aware editing for configuration files
- **Markdown**: Documentation structure analysis
### 9.3 Integration Enhancements
**IDE Integration:**
```go
// Export LSP proxy for IDEs
func (s *SemanticServer) ExportLSPProxy() *LSPProxy {
// Allow IDEs to use semantic server as LSP backend
}
```
**CI/CD Integration:**
```go
// semantic_validate_changes
func (s *SemanticServer) validateChanges(pullRequest *PullRequest) []ValidationResult {
// Analyze PR for breaking changes, test coverage, etc.
}
```
**Documentation Integration:**
```go
// semantic_generate_docs
func (s *SemanticServer) generateDocumentation(scope string) string {
// Generate API documentation from symbols
}
```
## 10. Conclusion
The Semantic MCP Server represents a significant advancement in AI-assisted code editing, moving beyond text manipulation to true semantic understanding. By leveraging Language Server Protocol and providing a rich set of symbol-aware tools, it enables AI assistants to perform precise, safe, and intelligent code operations.
**Key Benefits:**
- **Precision**: Symbol-level operations instead of error-prone text manipulation
- **Safety**: Context-aware editing with automatic formatting preservation
- **Intelligence**: Understanding of code relationships and dependencies
- **Consistency**: Unified interface across multiple programming languages
- **Integration**: Seamless connection with existing MCP ecosystem
**Implementation Priority:**
1. **Phase 1**: Core symbol discovery and basic editing tools
2. **Phase 2**: Advanced analysis tools (references, call hierarchy)
3. **Phase 3**: Integration with existing MCP servers
4. **Phase 4**: Performance optimization and caching
5. **Phase 5**: Advanced features and additional language support
This design provides a solid foundation for building a production-ready semantic code editing system that can significantly enhance AI-assisted software development workflows.
|