pylance-mcp-server 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +213 -0
- package/bin/pylance-mcp.js +68 -0
- package/mcp_server/__init__.py +13 -0
- package/mcp_server/__pycache__/__init__.cpython-312.pyc +0 -0
- package/mcp_server/__pycache__/__init__.cpython-313.pyc +0 -0
- package/mcp_server/__pycache__/__init__.cpython-314.pyc +0 -0
- package/mcp_server/__pycache__/ai_features.cpython-313.pyc +0 -0
- package/mcp_server/__pycache__/api_routes.cpython-313.pyc +0 -0
- package/mcp_server/__pycache__/auth.cpython-313.pyc +0 -0
- package/mcp_server/__pycache__/cloud_sync.cpython-313.pyc +0 -0
- package/mcp_server/__pycache__/logging_db.cpython-312.pyc +0 -0
- package/mcp_server/__pycache__/logging_db.cpython-313.pyc +0 -0
- package/mcp_server/__pycache__/pylance_bridge.cpython-312.pyc +0 -0
- package/mcp_server/__pycache__/pylance_bridge.cpython-313.pyc +0 -0
- package/mcp_server/__pycache__/pylance_bridge.cpython-314.pyc +0 -0
- package/mcp_server/__pycache__/resources.cpython-312.pyc +0 -0
- package/mcp_server/__pycache__/resources.cpython-313.pyc +0 -0
- package/mcp_server/__pycache__/tools.cpython-312.pyc +0 -0
- package/mcp_server/__pycache__/tools.cpython-313.pyc +0 -0
- package/mcp_server/__pycache__/tracing.cpython-313.pyc +0 -0
- package/mcp_server/ai_features.py +274 -0
- package/mcp_server/api_routes.py +429 -0
- package/mcp_server/auth.py +275 -0
- package/mcp_server/cloud_sync.py +427 -0
- package/mcp_server/logging_db.py +403 -0
- package/mcp_server/pylance_bridge.py +579 -0
- package/mcp_server/resources.py +174 -0
- package/mcp_server/tools.py +642 -0
- package/mcp_server/tracing.py +84 -0
- package/package.json +53 -0
- package/requirements.txt +29 -0
- package/scripts/check-python.js +57 -0
- package/server.py +1228 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Pylance MCP Server Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
# Pylance MCP Pro
|
|
2
|
+
|
|
3
|
+
**Professional Python Intelligence Server with REST API and AI Features**
|
|
4
|
+
|
|
5
|
+
A production-ready Model Context Protocol (MCP) server that provides enhanced Pylance/Pyright language server capabilities with REST API access, AI-powered code analysis, and OpenTelemetry tracing.
|
|
6
|
+
|
|
7
|
+
## 🎯 What Makes This Different?
|
|
8
|
+
|
|
9
|
+
Unlike Microsoft's standard Pylance server, **Pylance MCP Pro** includes:
|
|
10
|
+
|
|
11
|
+
- ✅ **REST API** - HTTP endpoints for web/mobile integration
|
|
12
|
+
- ✅ **AI Features** - Claude-powered type error explanations (Pro tier)
|
|
13
|
+
- ✅ **API Key Authentication** - Secure access with tier-based rate limiting
|
|
14
|
+
- ✅ **OpenTelemetry Tracing** - Monitor performance and debug issues
|
|
15
|
+
- ✅ **Conversation Logging** - Track AI interactions for analysis
|
|
16
|
+
- ✅ **Advanced Code Intelligence** - Enhanced completions and diagnostics
|
|
17
|
+
- ✅ **Professional Branding** - Shows up distinctly in VS Code
|
|
18
|
+
- ✅ **Custom Tools** - 12 specialized Python analysis tools
|
|
19
|
+
|
|
20
|
+
## 🌐 Access Methods
|
|
21
|
+
|
|
22
|
+
### 1. MCP Protocol (Claude Desktop, Continue, Cursor)
|
|
23
|
+
|
|
24
|
+
Traditional MCP client integration via stdio.
|
|
25
|
+
|
|
26
|
+
### 2. REST API (Web/Mobile Apps)
|
|
27
|
+
|
|
28
|
+
HTTP endpoints for any application:
|
|
29
|
+
```bash
|
|
30
|
+
curl -X POST https://api.pylancemcp.com/api/v1/analyze \
|
|
31
|
+
-H "X-API-Key: pmcp_your_key" \
|
|
32
|
+
-H "Content-Type: application/json" \
|
|
33
|
+
-d '{"file_path": "test.py", "content": "x: int = \"hello\""}'
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
See [API_TESTING_GUIDE.md](API_TESTING_GUIDE.md) for full documentation.
|
|
37
|
+
|
|
38
|
+
## 🚀 Quick Installation
|
|
39
|
+
|
|
40
|
+
### One-Line Install:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
python install_to_vscode.py
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Then reload VS Code (Ctrl+Shift+P → "Developer: Reload Window")
|
|
47
|
+
|
|
48
|
+
### Manual Installation:
|
|
49
|
+
|
|
50
|
+
Add to your VS Code `settings.json`:
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"mcpServers": {
|
|
55
|
+
"pylance-mcp-pro": {
|
|
56
|
+
"command": "/path/to/.venv/Scripts/python.exe",
|
|
57
|
+
"args": ["/path/to/server.py"],
|
|
58
|
+
"env": {
|
|
59
|
+
"WORKSPACE_ROOT": "${workspaceFolder}"
|
|
60
|
+
},
|
|
61
|
+
"enabled": true
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
"chat.mcp.autostart": "always"
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## 🔧 Finding Your Tools in VS Code
|
|
69
|
+
|
|
70
|
+
After installation and reload:
|
|
71
|
+
|
|
72
|
+
1. **Open Copilot Chat** (Ctrl+Alt+I)
|
|
73
|
+
2. **Click the 🔧 tools icon** in the chat input area
|
|
74
|
+
3. **Look for "pylance-mcp-pro"** (your custom server!)
|
|
75
|
+
4. You'll see all 12 tools listed
|
|
76
|
+
|
|
77
|
+
**Note:** This shows up separately from Microsoft's "pylance" server.
|
|
78
|
+
|
|
79
|
+
## 🛠️ Available Tools (12)
|
|
80
|
+
|
|
81
|
+
### Code Intelligence:
|
|
82
|
+
- `get_completions` - Intelligent code completions with full type info
|
|
83
|
+
- `get_hover` - Type hints and documentation on hover
|
|
84
|
+
- `get_definition` - Go to definition across workspace
|
|
85
|
+
- `get_references` - Find all references to symbols
|
|
86
|
+
|
|
87
|
+
### Code Quality:
|
|
88
|
+
- `get_diagnostics` - Errors, warnings, and type issues
|
|
89
|
+
- `format_document` - Professional code formatting
|
|
90
|
+
- `rename_symbol` - Safe refactoring across files
|
|
91
|
+
|
|
92
|
+
### Navigation:
|
|
93
|
+
- `get_signature_help` - Function signatures and parameters
|
|
94
|
+
- `get_document_symbols` - File outline and structure
|
|
95
|
+
- `get_workspace_symbols` - Project-wide symbol search
|
|
96
|
+
|
|
97
|
+
### Operations:
|
|
98
|
+
- `apply_workspace_edit` - Apply code changes safely
|
|
99
|
+
- `health_check` - Monitor server status
|
|
100
|
+
|
|
101
|
+
## 📊 Features
|
|
102
|
+
|
|
103
|
+
### OpenTelemetry Tracing
|
|
104
|
+
Monitor your code intelligence operations in real-time with the AI Toolkit trace viewer.
|
|
105
|
+
|
|
106
|
+
### Smart Environment Detection
|
|
107
|
+
Automatically detects and uses:
|
|
108
|
+
- Virtual environments (.venv, venv, env)
|
|
109
|
+
- Python version from your project
|
|
110
|
+
- Workspace-specific configurations
|
|
111
|
+
|
|
112
|
+
### Professional Integration
|
|
113
|
+
- Seamless Copilot Chat integration
|
|
114
|
+
- Natural language queries
|
|
115
|
+
- Automatic tool selection
|
|
116
|
+
- Context-aware responses
|
|
117
|
+
|
|
118
|
+
## 💬 Usage Examples
|
|
119
|
+
|
|
120
|
+
Just ask naturally in Copilot Chat:
|
|
121
|
+
|
|
122
|
+
```
|
|
123
|
+
"What's the type of this variable?"
|
|
124
|
+
"Show me all references to calculate_total"
|
|
125
|
+
"Are there any type errors in this file?"
|
|
126
|
+
"Get completions for line 42, column 10"
|
|
127
|
+
"Format this document"
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The appropriate tools are invoked automatically!
|
|
131
|
+
|
|
132
|
+
## 🔍 Verification
|
|
133
|
+
|
|
134
|
+
Check if it's running:
|
|
135
|
+
|
|
136
|
+
1. **View → Output**
|
|
137
|
+
2. **Select "pylance-mcp-pro" from dropdown**
|
|
138
|
+
3. Should show: "Discovered 12 tools"
|
|
139
|
+
|
|
140
|
+
Or run the test:
|
|
141
|
+
```bash
|
|
142
|
+
python server.py --test
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## 🎓 For Users Installing Your Server
|
|
146
|
+
|
|
147
|
+
When someone installs this:
|
|
148
|
+
|
|
149
|
+
1. They run `python install_to_vscode.py`
|
|
150
|
+
2. Reload VS Code
|
|
151
|
+
3. Open Copilot Chat
|
|
152
|
+
4. Click 🔧 → See "pylance-mcp-pro" listed
|
|
153
|
+
5. Start asking Python questions!
|
|
154
|
+
|
|
155
|
+
**The tools appear professionally in the Configure Tools menu!**
|
|
156
|
+
|
|
157
|
+
## 🆚 vs Microsoft's Pylance
|
|
158
|
+
|
|
159
|
+
| Feature | Microsoft Pylance | Pylance MCP Pro |
|
|
160
|
+
|---------|------------------|-----------------|
|
|
161
|
+
| Basic Language Intelligence | ✅ | ✅ |
|
|
162
|
+
| OpenTelemetry Tracing | ❌ | ✅ |
|
|
163
|
+
| Conversation Logging | ❌ | ✅ |
|
|
164
|
+
| Custom MCP Tools | ❌ | ✅ (12 tools) |
|
|
165
|
+
| Shows in Configure Tools | Default | Distinct entry |
|
|
166
|
+
| Professional Branding | Generic | Branded |
|
|
167
|
+
|
|
168
|
+
## 📝 Configuration
|
|
169
|
+
|
|
170
|
+
All settings in `settings.json`:
|
|
171
|
+
|
|
172
|
+
```json
|
|
173
|
+
{
|
|
174
|
+
"mcpServers": {
|
|
175
|
+
"pylance-mcp-pro": {
|
|
176
|
+
"command": "python.exe",
|
|
177
|
+
"args": ["server.py"],
|
|
178
|
+
"env": {
|
|
179
|
+
"WORKSPACE_ROOT": "${workspaceFolder}"
|
|
180
|
+
},
|
|
181
|
+
"enabled": true
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
## 🐛 Troubleshooting
|
|
188
|
+
|
|
189
|
+
### Tools not showing?
|
|
190
|
+
- Reload VS Code
|
|
191
|
+
- Check Output panel for "pylance-mcp-pro"
|
|
192
|
+
- Verify `chat.mcp.autostart` is "always"
|
|
193
|
+
|
|
194
|
+
### Wrong server running?
|
|
195
|
+
- Look for "pylance-mcp-pro" not "pylance"
|
|
196
|
+
- Microsoft's is built-in, yours is custom
|
|
197
|
+
|
|
198
|
+
### Need help?
|
|
199
|
+
- Run `python server.py --test`
|
|
200
|
+
- Check MCP_USAGE.md
|
|
201
|
+
- Review Output panel logs
|
|
202
|
+
|
|
203
|
+
## 🎉 Success!
|
|
204
|
+
|
|
205
|
+
When you see in Output:
|
|
206
|
+
```
|
|
207
|
+
Starting server pylance-mcp-pro
|
|
208
|
+
Discovered 12 tools
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
**You're ready to go!** 🚀
|
|
212
|
+
|
|
213
|
+
Your professional Python intelligence server is running and available in Copilot Chat's Configure Tools menu.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pylance MCP Server Launcher
|
|
5
|
+
*
|
|
6
|
+
* This script launches the Python-based MCP server.
|
|
7
|
+
* It handles Python environment detection and server startup.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const { spawn } = require('child_process');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
|
|
14
|
+
// Find Python executable
|
|
15
|
+
function findPython() {
|
|
16
|
+
const pythonCommands = ['python3', 'python', 'py'];
|
|
17
|
+
|
|
18
|
+
for (const cmd of pythonCommands) {
|
|
19
|
+
try {
|
|
20
|
+
const { status } = require('child_process').spawnSync(cmd, ['--version'], {
|
|
21
|
+
stdio: 'ignore'
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
if (status === 0) {
|
|
25
|
+
return cmd;
|
|
26
|
+
}
|
|
27
|
+
} catch (e) {
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
console.error('Error: Python 3.8+ is required but not found in PATH.');
|
|
33
|
+
console.error('Please install Python from https://www.python.org/downloads/');
|
|
34
|
+
process.exit(1);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Get server.py path
|
|
38
|
+
const serverPath = path.join(__dirname, '..', 'server.py');
|
|
39
|
+
|
|
40
|
+
if (!fs.existsSync(serverPath)) {
|
|
41
|
+
console.error(`Error: server.py not found at ${serverPath}`);
|
|
42
|
+
process.exit(1);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Launch server
|
|
46
|
+
const python = findPython();
|
|
47
|
+
const serverProcess = spawn(python, [serverPath], {
|
|
48
|
+
stdio: 'inherit',
|
|
49
|
+
env: {
|
|
50
|
+
...process.env,
|
|
51
|
+
OTEL_SDK_DISABLED: process.env.OTEL_SDK_DISABLED || 'true',
|
|
52
|
+
WORKSPACE_PATH: process.env.WORKSPACE_PATH || process.cwd()
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// Handle exit
|
|
57
|
+
serverProcess.on('exit', (code) => {
|
|
58
|
+
process.exit(code || 0);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// Handle signals
|
|
62
|
+
process.on('SIGINT', () => {
|
|
63
|
+
serverProcess.kill('SIGINT');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
process.on('SIGTERM', () => {
|
|
67
|
+
serverProcess.kill('SIGTERM');
|
|
68
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Pylance MCP Server Package
|
|
3
|
+
|
|
4
|
+
Production-ready MCP server exposing Pylance/Pyright capabilities.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "1.0.0"
|
|
8
|
+
|
|
9
|
+
from .pylance_bridge import PylanceBridge
|
|
10
|
+
from .tools import PylanceTools
|
|
11
|
+
from .resources import PylanceResources
|
|
12
|
+
|
|
13
|
+
__all__ = ["PylanceBridge", "PylanceTools", "PylanceResources"]
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""
|
|
2
|
+
AI-powered features for Pylance MCP Pro
|
|
3
|
+
Requires ANTHROPIC_API_KEY in environment
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from typing import Dict, List, Any
|
|
8
|
+
from anthropic import Anthropic
|
|
9
|
+
|
|
10
|
+
client = Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
|
|
11
|
+
|
|
12
|
+
async def explain_type_error(
|
|
13
|
+
code: str,
|
|
14
|
+
error_message: str,
|
|
15
|
+
file_path: str,
|
|
16
|
+
line_number: int
|
|
17
|
+
) -> Dict[str, Any]:
|
|
18
|
+
"""
|
|
19
|
+
Use Claude to explain a type error in simple terms with fix suggestions
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
code: The code snippet containing the error
|
|
23
|
+
error_message: The raw Pyright error message
|
|
24
|
+
file_path: Path to the file with the error
|
|
25
|
+
line_number: Line number where error occurs
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
Dict with explanation, causes, and suggested fixes
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
prompt = f"""You are a Python type error expert. A developer has encountered this type error:
|
|
32
|
+
|
|
33
|
+
File: {file_path}
|
|
34
|
+
Line: {line_number}
|
|
35
|
+
Error: {error_message}
|
|
36
|
+
|
|
37
|
+
Code snippet:
|
|
38
|
+
```python
|
|
39
|
+
{code}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Please provide:
|
|
43
|
+
1. A clear, beginner-friendly explanation of what this error means
|
|
44
|
+
2. Why it occurred (root causes)
|
|
45
|
+
3. 2-3 concrete code fixes with examples
|
|
46
|
+
4. Best practices to avoid this error in the future
|
|
47
|
+
|
|
48
|
+
Be concise and practical. Focus on actionable solutions."""
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
message = client.messages.create(
|
|
52
|
+
model="claude-sonnet-4-20250514",
|
|
53
|
+
max_tokens=1500,
|
|
54
|
+
messages=[{
|
|
55
|
+
"role": "user",
|
|
56
|
+
"content": prompt
|
|
57
|
+
}]
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
explanation = message.content[0].text
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
"success": True,
|
|
64
|
+
"explanation": explanation,
|
|
65
|
+
"model": "claude-sonnet-4",
|
|
66
|
+
"tokens_used": message.usage.input_tokens + message.usage.output_tokens
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
except Exception as e:
|
|
70
|
+
return {
|
|
71
|
+
"success": False,
|
|
72
|
+
"error": str(e)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
async def enhance_type_annotations(
|
|
77
|
+
code: str,
|
|
78
|
+
file_path: str,
|
|
79
|
+
existing_types: List[Dict[str, Any]]
|
|
80
|
+
) -> Dict[str, Any]:
|
|
81
|
+
"""
|
|
82
|
+
Use Claude to suggest improved type annotations for code
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
code: The code to analyze
|
|
86
|
+
file_path: Path to the file
|
|
87
|
+
existing_types: Existing type information from Pyright
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
Dict with suggested type improvements
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
# Format existing types
|
|
94
|
+
types_context = "\n".join([
|
|
95
|
+
f"- {t.get('symbol', 'unknown')}: {t.get('type', 'unknown')}"
|
|
96
|
+
for t in existing_types[:10] # Limit to avoid token bloat
|
|
97
|
+
])
|
|
98
|
+
|
|
99
|
+
prompt = f"""You are a Python typing expert. Analyze this code and suggest improved type annotations.
|
|
100
|
+
|
|
101
|
+
File: {file_path}
|
|
102
|
+
|
|
103
|
+
Current types detected:
|
|
104
|
+
{types_context}
|
|
105
|
+
|
|
106
|
+
Code:
|
|
107
|
+
```python
|
|
108
|
+
{code}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Please suggest:
|
|
112
|
+
1. Missing type annotations that should be added
|
|
113
|
+
2. Generic types that could be more specific
|
|
114
|
+
3. Union types that could be simplified
|
|
115
|
+
4. Return type annotations for functions
|
|
116
|
+
5. Type aliases that would improve readability
|
|
117
|
+
|
|
118
|
+
For each suggestion, provide:
|
|
119
|
+
- Line number
|
|
120
|
+
- Current code
|
|
121
|
+
- Suggested improvement
|
|
122
|
+
- Reasoning
|
|
123
|
+
|
|
124
|
+
Format as JSON array of suggestions."""
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
message = client.messages.create(
|
|
128
|
+
model="claude-sonnet-4-20250514",
|
|
129
|
+
max_tokens=2000,
|
|
130
|
+
messages=[{
|
|
131
|
+
"role": "user",
|
|
132
|
+
"content": prompt
|
|
133
|
+
}]
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
suggestions = message.content[0].text
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
"success": True,
|
|
140
|
+
"suggestions": suggestions,
|
|
141
|
+
"model": "claude-sonnet-4",
|
|
142
|
+
"tokens_used": message.usage.input_tokens + message.usage.output_tokens
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
except Exception as e:
|
|
146
|
+
return {
|
|
147
|
+
"success": False,
|
|
148
|
+
"error": str(e)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
async def analyze_code_patterns(
|
|
153
|
+
code: str,
|
|
154
|
+
diagnostics: List[Dict[str, Any]]
|
|
155
|
+
) -> Dict[str, Any]:
|
|
156
|
+
"""
|
|
157
|
+
Use Claude to identify code patterns and suggest improvements
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
code: The code to analyze
|
|
161
|
+
diagnostics: Existing diagnostics from Pyright
|
|
162
|
+
|
|
163
|
+
Returns:
|
|
164
|
+
Dict with pattern analysis and suggestions
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
# Format diagnostics
|
|
168
|
+
diag_summary = "\n".join([
|
|
169
|
+
f"- Line {d.get('line', '?')}: {d.get('message', 'unknown')}"
|
|
170
|
+
for d in diagnostics[:5]
|
|
171
|
+
])
|
|
172
|
+
|
|
173
|
+
prompt = f"""Analyze this Python code for patterns and improvements.
|
|
174
|
+
|
|
175
|
+
Existing issues:
|
|
176
|
+
{diag_summary}
|
|
177
|
+
|
|
178
|
+
Code:
|
|
179
|
+
```python
|
|
180
|
+
{code}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Identify:
|
|
184
|
+
1. Anti-patterns or code smells
|
|
185
|
+
2. Type safety issues
|
|
186
|
+
3. Opportunities for better abstractions
|
|
187
|
+
4. Performance considerations
|
|
188
|
+
5. Maintainability improvements
|
|
189
|
+
|
|
190
|
+
Prioritize suggestions by impact. Be specific and actionable."""
|
|
191
|
+
|
|
192
|
+
try:
|
|
193
|
+
message = client.messages.create(
|
|
194
|
+
model="claude-sonnet-4-20250514",
|
|
195
|
+
max_tokens=1500,
|
|
196
|
+
messages=[{
|
|
197
|
+
"role": "user",
|
|
198
|
+
"content": prompt
|
|
199
|
+
}]
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
analysis = message.content[0].text
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
"success": True,
|
|
206
|
+
"analysis": analysis,
|
|
207
|
+
"model": "claude-sonnet-4",
|
|
208
|
+
"tokens_used": message.usage.input_tokens + message.usage.output_tokens
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
except Exception as e:
|
|
212
|
+
return {
|
|
213
|
+
"success": False,
|
|
214
|
+
"error": str(e)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
async def suggest_type_stubs(
|
|
219
|
+
library_name: str,
|
|
220
|
+
usage_examples: List[str]
|
|
221
|
+
) -> Dict[str, Any]:
|
|
222
|
+
"""
|
|
223
|
+
Generate type stub suggestions for untyped libraries
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
library_name: Name of the library
|
|
227
|
+
usage_examples: Code examples showing library usage
|
|
228
|
+
|
|
229
|
+
Returns:
|
|
230
|
+
Dict with stub file suggestions
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
examples = "\n\n".join(usage_examples[:3])
|
|
234
|
+
|
|
235
|
+
prompt = f"""Generate type stub (.pyi) suggestions for the library '{library_name}'.
|
|
236
|
+
|
|
237
|
+
Usage examples:
|
|
238
|
+
```python
|
|
239
|
+
{examples}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
Create a type stub file that includes:
|
|
243
|
+
1. Function signatures with proper types
|
|
244
|
+
2. Class definitions with methods
|
|
245
|
+
3. Constants and module-level variables
|
|
246
|
+
4. Docstrings for complex types
|
|
247
|
+
|
|
248
|
+
Format as a complete .pyi file."""
|
|
249
|
+
|
|
250
|
+
try:
|
|
251
|
+
message = client.messages.create(
|
|
252
|
+
model="claude-sonnet-4-20250514",
|
|
253
|
+
max_tokens=2000,
|
|
254
|
+
messages=[{
|
|
255
|
+
"role": "user",
|
|
256
|
+
"content": prompt
|
|
257
|
+
}]
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
stub_content = message.content[0].text
|
|
261
|
+
|
|
262
|
+
return {
|
|
263
|
+
"success": True,
|
|
264
|
+
"stub_content": stub_content,
|
|
265
|
+
"library": library_name,
|
|
266
|
+
"model": "claude-sonnet-4",
|
|
267
|
+
"tokens_used": message.usage.input_tokens + message.usage.output_tokens
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
except Exception as e:
|
|
271
|
+
return {
|
|
272
|
+
"success": False,
|
|
273
|
+
"error": str(e)
|
|
274
|
+
}
|