-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_connection.py
More file actions
173 lines (145 loc) Β· 5.85 KB
/
test_connection.py
File metadata and controls
173 lines (145 loc) Β· 5.85 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
#!/usr/bin/env python3
"""
Test script to verify SourceGraph MCP server configuration.
Run this before configuring Claude Desktop to ensure everything works.
Tests both code search and symbol search functionality.
"""
import asyncio
import json
import os
import sys
from pathlib import Path
# Add server.py to path
sys.path.insert(0, str(Path(__file__).parent))
from server import load_config, search_code, search_symbols
async def test_connection():
"""Test connection to SourceGraph."""
print("=" * 60)
print("SourceGraph MCP Server - Connection Test")
print("=" * 60)
print()
# Load configuration
config = load_config()
print("π Configuration:")
print(f" URL: {config['sourcegraph_url']}")
print(f" Token: {'β Set' if config['access_token'] else 'β Not set'}")
print(f" Timeout: {config['timeout']}s")
print()
if not config['access_token']:
print("β ERROR: No access token configured")
print()
print("Please set SOURCEGRAPH_TOKEN environment variable:")
print(" export SOURCEGRAPH_TOKEN='your-token'")
print()
print("Or create config.json:")
print(" cp config.example.json config.json")
print(" # Edit config.json with your token")
return False
# Test 1: Simple code search
print("π Test 1: Code Search")
print(" Query: 'function' (finding any occurrence)")
print()
result = await search_code("function", max_results=3)
if "error" in result:
print(f"β Search failed: {result['error']}")
print()
print("Common issues:")
print(" - SourceGraph is not running")
print(" - Wrong URL in configuration")
print(" - Invalid access token")
print(" - Network connectivity issues")
return False
if "errors" in result:
print(f"β GraphQL error: {result['errors'][0].get('message')}")
return False
try:
search_data = result["data"]["search"]
match_count = search_data["results"]["matchCount"]
results = search_data["results"]["results"]
print(f"β
Code search successful! Found {match_count} matches")
if results:
print()
print("Sample results:")
for i, res in enumerate(results[:3], 1):
if res["__typename"] == "FileMatch":
file_info = res["file"]
repo = file_info["repository"]
print(f" {i}. {repo['name']}/{file_info['path']}")
print()
except (KeyError, TypeError) as e:
print(f"β Unexpected response format: {e}")
print()
print("Response:")
print(json.dumps(result, indent=2))
return False
# Test 2: Symbol search
print("π Test 2: Symbol Search")
print(" Query: Finding symbols (functions, classes, etc.)")
print()
# Try a common symbol name that's likely to exist
symbol_result = await search_symbols("main", max_results=3)
if "error" in symbol_result:
print(f"β οΈ Symbol search error: {symbol_result['error']}")
print(" (This may be normal if your repos don't have indexed symbols)")
elif "errors" in symbol_result:
print(f"β οΈ Symbol search GraphQL error: {symbol_result['errors'][0].get('message')}")
print(" (This may be normal if symbol indexing is not enabled)")
else:
try:
symbol_data = symbol_result["data"]["search"]
symbol_matches = symbol_data["results"]["matchCount"]
symbol_results = symbol_data["results"]["results"]
print(f"β
Symbol search successful! Found {symbol_matches} symbol matches")
if symbol_results:
print()
print("Sample symbol results:")
for i, res in enumerate(symbol_results[:3], 1):
if res["__typename"] == "FileMatch":
file_info = res["file"]
symbols = res.get("symbols", [])
if symbols:
for sym in symbols[:2]: # Show first 2 symbols per file
location = sym["location"]
line = location["range"]["start"]["line"]
print(f" {i}. {sym['name']} ({sym['kind']}) at line {line}")
print(f" in {file_info['path']}")
else:
print("β οΈ No symbols found (repos may not have indexed symbols yet)")
print()
except (KeyError, TypeError) as e:
print(f"β οΈ Unexpected symbol response format: {e}")
print(" (Symbol indexing may not be available)")
print()
print("=" * 60)
print("β
All tests passed!")
print()
print("Features available:")
print(" β Code search (text-based)")
print(" β Symbol search (definitions)")
print(" β Reference search (usages)")
print(" β Regex search")
print()
print("Next steps:")
print("1. Configure Claude Desktop/Code (see README.md)")
print("2. Restart your MCP client")
print("3. Try commands like:")
print(" - 'Find the definition of ProcessOrder'")
print(" - 'Show me all references to CustomerService'")
print(" - 'Search for error handling code'")
print("=" * 60)
return True
def main():
"""Run the test."""
try:
success = asyncio.run(test_connection())
sys.exit(0 if success else 1)
except KeyboardInterrupt:
print("\n\nβ Test cancelled")
sys.exit(1)
except Exception as e:
print(f"\n\nβ Unexpected error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()