summaryrefslogtreecommitdiff
path: root/pkg/semantic/server.go
blob: d795b9d7755a123441759c1ed042219af2adc5c3 (plain)
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
package semantic

import (
	"encoding/json"
	"fmt"
	"sync"

	"github.com/xlgmokha/mcp/pkg/mcp"
)

// SemanticOperations provides semantic analysis operations
type SemanticOperations struct {
	lspManager    *LSPManager
	symbolManager *SymbolManager
	projectManager *ProjectManager
	mu            sync.RWMutex
}

// NewSemanticOperations creates a new SemanticOperations helper
func NewSemanticOperations() (*SemanticOperations, error) {
	lspManager := NewLSPManager()
	projectManager := NewProjectManager()
	symbolManager := NewSymbolManager(lspManager, projectManager)
	
	return &SemanticOperations{
		lspManager:     lspManager,
		symbolManager:  symbolManager,
		projectManager: projectManager,
	}, nil
}

// New creates a new Semantic MCP server
func New() (*mcp.Server, error) {
	semantic, err := NewSemanticOperations()
	if err != nil {
		return nil, err
	}
	
	builder := mcp.NewServerBuilder("mcp-semantic", "1.0.0")

// Add semantic_find_symbol tool
	builder.AddTool(mcp.NewTool("semantic_find_symbol", "Find symbols by name, type, or pattern across the project", map[string]interface{}{
		"type": "object",
		"properties": map[string]interface{}{
			"query": map[string]interface{}{
				"type":        "string",
				"description": "Symbol name or pattern to search for",
			},
			"symbol_type": map[string]interface{}{
				"type":        "string",
				"description": "Type of symbol to search for (function, class, variable, etc.)",
				"enum":        []string{"function", "class", "variable", "interface", "type", "constant", "module"},
			},
			"language": map[string]interface{}{
				"type":        "string",
				"description": "Programming language to filter by (optional)",
				"enum":        []string{"go", "rust", "typescript", "javascript", "python", "java", "cpp"},
			},
			"case_sensitive": map[string]interface{}{
				"type":        "boolean",
				"description": "Whether the search should be case sensitive (default: false)",
			},
			"exact_match": map[string]interface{}{
				"type":        "boolean",
				"description": "Whether to match the exact symbol name (default: false, allows partial matches)",
			},
		},
		"required": []string{"query"},
	}, func(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
		return semantic.handleFindSymbol(req)
	}))

	// Add semantic_get_overview tool
	builder.AddTool(mcp.NewTool("semantic_get_overview", "Get a high-level overview of symbols and structure in a file or directory", map[string]interface{}{
		"type": "object",
		"properties": map[string]interface{}{
			"path": map[string]interface{}{
				"type":        "string",
				"description": "File or directory path to analyze",
			},
			"depth": map[string]interface{}{
				"type":        "integer",
				"description": "Depth of analysis (1=top-level only, 2=include immediate children, etc.) (default: 2)",
				"minimum":     1,
				"maximum":     5,
			},
			"include_private": map[string]interface{}{
				"type":        "boolean",
				"description": "Include private/internal symbols (default: false)",
			},
			"group_by": map[string]interface{}{
				"type":        "string",
				"description": "How to group the results (type, file, module) (default: type)",
				"enum":        []string{"type", "file", "module"},
			},
		},
		"required": []string{"path"},
	}, func(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
		return semantic.handleGetOverview(req)
	}))

	// Add semantic_get_definition tool
	builder.AddTool(mcp.NewTool("semantic_get_definition", "Get the definition location and details for a specific symbol", map[string]interface{}{
		"type": "object",
		"properties": map[string]interface{}{
			"symbol": map[string]interface{}{
				"type":        "string",
				"description": "Symbol name to find definition for",
			},
			"file": map[string]interface{}{
				"type":        "string",
				"description": "File path where the symbol is referenced (helps with context)",
			},
			"line": map[string]interface{}{
				"type":        "integer",
				"description": "Line number where the symbol is referenced (optional, for better precision)",
				"minimum":     1,
			},
			"column": map[string]interface{}{
				"type":        "integer",
				"description": "Column number where the symbol is referenced (optional, for better precision)",
				"minimum":     1,
			},
			"include_signature": map[string]interface{}{
				"type":        "boolean",
				"description": "Include full function/method signature (default: true)",
			},
		},
		"required": []string{"symbol"},
	}, func(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
		return semantic.handleGetDefinition(req)
	}))

	// Add semantic_get_references tool
	builder.AddTool(mcp.NewTool("semantic_get_references", "Find all references to a specific symbol across the project", map[string]interface{}{
		"type": "object",
		"properties": map[string]interface{}{
			"symbol": map[string]interface{}{
				"type":        "string",
				"description": "Symbol name to find references for",
			},
			"file": map[string]interface{}{
				"type":        "string",
				"description": "File path where the symbol is defined (helps with context)",
			},
			"line": map[string]interface{}{
				"type":        "integer",
				"description": "Line number where the symbol is defined (optional, for better precision)",
				"minimum":     1,
			},
			"include_declaration": map[string]interface{}{
				"type":        "boolean",
				"description": "Include the symbol declaration in results (default: true)",
			},
			"scope": map[string]interface{}{
				"type":        "string",
				"description": "Scope of search (file, directory, project) (default: project)",
				"enum":        []string{"file", "directory", "project"},
			},
		},
		"required": []string{"symbol"},
	}, func(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
		return semantic.handleGetReferences(req)
	}))

	// Add semantic_get_call_hierarchy tool
	builder.AddTool(mcp.NewTool("semantic_get_call_hierarchy", "Get the call hierarchy (callers and callees) for a function or method", map[string]interface{}{
		"type": "object",
		"properties": map[string]interface{}{
			"symbol": map[string]interface{}{
				"type":        "string",
				"description": "Function or method name to analyze",
			},
			"file": map[string]interface{}{
				"type":        "string",
				"description": "File path where the function is defined",
			},
			"line": map[string]interface{}{
				"type":        "integer",
				"description": "Line number where the function is defined (optional)",
				"minimum":     1,
			},
			"direction": map[string]interface{}{
				"type":        "string",
				"description": "Direction of call hierarchy (incoming=who calls this, outgoing=what this calls, both) (default: both)",
				"enum":        []string{"incoming", "outgoing", "both"},
			},
			"depth": map[string]interface{}{
				"type":        "integer",
				"description": "Depth of call hierarchy to retrieve (default: 3)",
				"minimum":     1,
				"maximum":     10,
			},
		},
		"required": []string{"symbol", "file"},
	}, func(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
		return semantic.handleGetCallHierarchy(req)
	}))

	// Add semantic_analyze_dependencies tool
	builder.AddTool(mcp.NewTool("semantic_analyze_dependencies", "Analyze dependencies and relationships between modules, files, or symbols", map[string]interface{}{
		"type": "object",
		"properties": map[string]interface{}{
			"path": map[string]interface{}{
				"type":        "string",
				"description": "Path to analyze (file, directory, or project root)",
			},
			"analysis_type": map[string]interface{}{
				"type":        "string",
				"description": "Type of dependency analysis to perform (default: imports)",
				"enum":        []string{"imports", "exports", "modules", "symbols", "circular"},
			},
			"include_external": map[string]interface{}{
				"type":        "boolean",
				"description": "Include external/third-party dependencies (default: false)",
			},
			"format": map[string]interface{}{
				"type":        "string",
				"description": "Output format (tree, graph, list) (default: tree)",
				"enum":        []string{"tree", "graph", "list"},
			},
			"max_depth": map[string]interface{}{
				"type":        "integer",
				"description": "Maximum depth of dependency analysis (default: 5)",
				"minimum":     1,
				"maximum":     20,
			},
		},
		"required": []string{"path"},
	}, func(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
		return semantic.handleAnalyzeDependencies(req)
	}))

	return builder.Build(), nil
}


// handleFindSymbol finds symbols by name, type, or pattern across the project
func (semantic *SemanticOperations) handleFindSymbol(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
	semantic.mu.RLock()
	defer semantic.mu.RUnlock()

	var args struct {
		Name            string   `json:"name"`                      // Symbol path or pattern
		Kind            string   `json:"kind,omitempty"`            // function, class, variable, etc.
		Scope           string   `json:"scope,omitempty"`           // project, file, directory
		Language        string   `json:"language,omitempty"`        // Optional language filter
		IncludeChildren bool     `json:"include_children,omitempty"` // Include child symbols
		MaxResults      int      `json:"max_results,omitempty"`     // Limit results
	}

	argsBytes, _ := json.Marshal(req.Arguments)
	if err := json.Unmarshal(argsBytes, &args); err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("invalid arguments: %w", err)
	}

	if args.Name == "" {
		return mcp.CallToolResult{}, fmt.Errorf("name is required")
	}

	// Set defaults
	if args.Scope == "" {
		args.Scope = "project"
	}
	if args.MaxResults == 0 {
		args.MaxResults = 50
	}

	// Build query
	query := SymbolQuery{
		Name:            args.Name,
		Kind:            SymbolKind(args.Kind),
		Scope:           args.Scope,
		Language:        args.Language,
		IncludeChildren: args.IncludeChildren,
		MaxResults:      args.MaxResults,
	}

	// Find symbols
	symbols, err := semantic.symbolManager.FindSymbols(query)
	if err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("failed to find symbols: %w", err)
	}

	// Format response
	responseData := map[string]interface{}{
		"symbols":     symbols,
		"total_found": len(symbols),
		"query":       query,
	}

	responseJSON, _ := json.MarshalIndent(responseData, "", "  ")

	return mcp.CallToolResult{
		Content: []mcp.Content{
			mcp.TextContent{
				Type: "text",
				Text: fmt.Sprintf("Found %d symbols matching '%s':\n\n%s", 
					len(symbols), args.Name, string(responseJSON)),
			},
		},
	}, nil
}

// handleGetOverview gets high-level symbol overview of files or directories
func (semantic *SemanticOperations) handleGetOverview(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
	semantic.mu.RLock()
	defer semantic.mu.RUnlock()

	var args struct {
		Path           string   `json:"path"`                      // File or directory path
		Depth          int      `json:"depth,omitempty"`           // How deep to analyze
		IncludeKinds   []string `json:"include_kinds,omitempty"`   // Filter symbol types
		ExcludePrivate bool     `json:"exclude_private,omitempty"` // Skip private symbols
	}

	argsBytes, _ := json.Marshal(req.Arguments)
	if err := json.Unmarshal(argsBytes, &args); err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("invalid arguments: %w", err)
	}

	if args.Path == "" {
		return mcp.CallToolResult{}, fmt.Errorf("path is required")
	}

	// Set defaults
	if args.Depth == 0 {
		args.Depth = 2
	}

	// Get overview
	overview, err := semantic.symbolManager.GetOverview(args.Path, args.Depth, args.IncludeKinds, args.ExcludePrivate)
	if err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("failed to get overview: %w", err)
	}

	// Format response
	responseJSON, _ := json.MarshalIndent(overview, "", "  ")

	return mcp.CallToolResult{
		Content: []mcp.Content{
			mcp.TextContent{
				Type: "text",
				Text: fmt.Sprintf("Symbol overview for '%s':\n\n%s", args.Path, string(responseJSON)),
			},
		},
	}, nil
}

// handleGetDefinition gets detailed information about a symbol's definition
func (semantic *SemanticOperations) handleGetDefinition(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
	semantic.mu.RLock()
	defer semantic.mu.RUnlock()

	var args struct {
		Symbol              string `json:"symbol"`                        // Target symbol
		IncludeSignature    bool   `json:"include_signature,omitempty"`    // Include full signature
		IncludeDocumentation bool   `json:"include_documentation,omitempty"` // Include comments/docs
		IncludeDependencies bool   `json:"include_dependencies,omitempty"` // Include what this symbol uses
	}

	argsBytes, _ := json.Marshal(req.Arguments)
	if err := json.Unmarshal(argsBytes, &args); err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("invalid arguments: %w", err)
	}

	if args.Symbol == "" {
		return mcp.CallToolResult{}, fmt.Errorf("symbol is required")
	}

	// Get definition
	definition, err := semantic.symbolManager.GetDefinition(args.Symbol, args.IncludeSignature, args.IncludeDocumentation, args.IncludeDependencies)
	if err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("failed to get definition: %w", err)
	}

	// Format response
	responseJSON, _ := json.MarshalIndent(definition, "", "  ")

	return mcp.CallToolResult{
		Content: []mcp.Content{
			mcp.TextContent{
				Type: "text",
				Text: fmt.Sprintf("Definition for symbol '%s':\n\n%s", args.Symbol, string(responseJSON)),
			},
		},
	}, nil
}

// handleGetReferences finds all places where a symbol is used
func (semantic *SemanticOperations) handleGetReferences(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
	semantic.mu.RLock()
	defer semantic.mu.RUnlock()

	var args struct {
		Symbol              string   `json:"symbol"`                        // Target symbol
		IncludeDefinitions  bool     `json:"include_definitions,omitempty"` // Include definition location
		ContextLines        int      `json:"context_lines,omitempty"`       // Lines of context around usage
		FilterByKind        []string `json:"filter_by_kind,omitempty"`      // Type of references
		Language            string   `json:"language,omitempty"`            // Language filter
		IncludeExternal     bool     `json:"include_external,omitempty"`    // Include external package references
	}

	argsBytes, _ := json.Marshal(req.Arguments)
	if err := json.Unmarshal(argsBytes, &args); err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("invalid arguments: %w", err)
	}

	if args.Symbol == "" {
		return mcp.CallToolResult{}, fmt.Errorf("symbol is required")
	}

	// Set defaults
	if args.ContextLines == 0 {
		args.ContextLines = 3
	}

	// Get references
	references, err := semantic.symbolManager.GetReferences(args.Symbol, args.IncludeDefinitions, args.ContextLines, args.FilterByKind, args.Language, args.IncludeExternal)
	if err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("failed to get references: %w", err)
	}

	// Format response
	responseData := map[string]interface{}{
		"symbol":          args.Symbol,
		"references":      references.References,
		"total_found":     len(references.References),
		"definition":      references.Definition,
		"context_lines":   args.ContextLines,
		"include_external": args.IncludeExternal,
	}

	responseJSON, _ := json.MarshalIndent(responseData, "", "  ")

	return mcp.CallToolResult{
		Content: []mcp.Content{
			mcp.TextContent{
				Type: "text",
				Text: fmt.Sprintf("Found %d references for symbol '%s':\n\n%s", 
					len(references.References), args.Symbol, string(responseJSON)),
			},
		},
	}, nil
}

// handleGetCallHierarchy understands calling relationships (what calls this, what this calls)
func (semantic *SemanticOperations) handleGetCallHierarchy(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
	semantic.mu.RLock()
	defer semantic.mu.RUnlock()

	var args struct {
		Symbol          string `json:"symbol"`                    // Target symbol
		Direction       string `json:"direction,omitempty"`       // "incoming", "outgoing", "both"
		MaxDepth        int    `json:"max_depth,omitempty"`       // How many levels deep
		IncludeExternal bool   `json:"include_external,omitempty"` // Include calls to external packages
		Language        string `json:"language,omitempty"`        // Language filter
	}

	argsBytes, _ := json.Marshal(req.Arguments)
	if err := json.Unmarshal(argsBytes, &args); err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("invalid arguments: %w", err)
	}

	if args.Symbol == "" {
		return mcp.CallToolResult{}, fmt.Errorf("symbol is required")
	}

	// Set defaults
	if args.Direction == "" {
		args.Direction = "both"
	}
	if args.MaxDepth == 0 {
		args.MaxDepth = 3
	}

	// Get call hierarchy
	hierarchy, err := semantic.symbolManager.GetCallHierarchy(args.Symbol, args.Direction, args.MaxDepth, args.IncludeExternal, args.Language)
	if err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("failed to get call hierarchy: %w", err)
	}

	// Format response
	responseJSON, _ := json.MarshalIndent(hierarchy, "", "  ")

	return mcp.CallToolResult{
		Content: []mcp.Content{
			mcp.TextContent{
				Type: "text",
				Text: fmt.Sprintf("Call hierarchy for symbol '%s' (direction: %s, depth: %d):\n\n%s", 
					args.Symbol, args.Direction, args.MaxDepth, string(responseJSON)),
			},
		},
	}, nil
}

// handleAnalyzeDependencies analyzes symbol dependencies and relationships  
func (semantic *SemanticOperations) handleAnalyzeDependencies(req mcp.CallToolRequest) (mcp.CallToolResult, error) {
	semantic.mu.RLock()
	defer semantic.mu.RUnlock()

	var args struct {
		Scope           string `json:"scope"`                     // Analysis scope: "file", "package", "project"
		Path            string `json:"path,omitempty"`            // Specific path to analyze
		IncludeExternal bool   `json:"include_external,omitempty"` // Include external dependencies
		GroupBy         string `json:"group_by,omitempty"`        // "file", "package", "kind"
		ShowUnused      bool   `json:"show_unused,omitempty"`     // Highlight unused symbols
		Language        string `json:"language,omitempty"`        // Language filter
	}

	argsBytes, _ := json.Marshal(req.Arguments)
	if err := json.Unmarshal(argsBytes, &args); err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("invalid arguments: %w", err)
	}

	if args.Scope == "" {
		args.Scope = "project"
	}
	if args.GroupBy == "" {
		args.GroupBy = "package"
	}

	// Analyze dependencies
	analysis, err := semantic.symbolManager.AnalyzeDependencies(args.Scope, args.Path, args.IncludeExternal, args.GroupBy, args.ShowUnused, args.Language)
	if err != nil {
		return mcp.CallToolResult{}, fmt.Errorf("failed to analyze dependencies: %w", err)
	}

	// Format response
	responseJSON, _ := json.MarshalIndent(analysis, "", "  ")

	return mcp.CallToolResult{
		Content: []mcp.Content{
			mcp.TextContent{
				Type: "text",
				Text: fmt.Sprintf("Dependency analysis for scope '%s' (grouped by %s):\n\n%s", 
					args.Scope, args.GroupBy, string(responseJSON)),
			},
		},
	}, nil
}

// Shutdown gracefully shuts down the semantic server
func (semantic *SemanticOperations) Shutdown() error {
	semantic.mu.Lock()
	defer semantic.mu.Unlock()

	if semantic.lspManager != nil {
		if err := semantic.lspManager.Shutdown(); err != nil {
			return fmt.Errorf("failed to shutdown LSP manager: %w", err)
		}
	}

	if semantic.projectManager != nil {
		if err := semantic.projectManager.Shutdown(); err != nil {
			return fmt.Errorf("failed to shutdown project manager: %w", err)
		}
	}

	return nil
}