A minimal demonstration of Python-to-VS Code communication via WebSocket. This project showcases how Python scripts can interact with VS Code editors through a simple WebSocket bridge.
π― Quick Start: Run python demo.py
for an interactive demonstration of all capabilities!
This repository provides a minimum reproducible example of bidirectional communication between Python and VS Code, demonstrating:
- π’ Sending notifications to VS Code from Python
- π Getting information about open editors
- π Reading text content from specific files
- βοΈ Modifying text content in the active editor
sequenceDiagram
participant Python as Python Script
participant Bridge as VSCodeBridge
participant WS as WebSocket
participant Server as VS Code Extension
participant VSCode as VS Code API
Python->>+Bridge: bridge.notify("Hello")
Bridge->>Bridge: Encode to JSON command
Note over Bridge: {"command": "notify", "params": {"message": "Hello"}}
Bridge->>+WS: Send JSON over WebSocket
WS->>+Server: Forward raw message
Server->>Server: Parse JSON & validate
Server->>Server: Route to handleNotifyCommand()
Server->>+VSCode: vscode.window.showInformationMessage()
VSCode-->>-Server: Success/Error
Server->>Server: Create response JSON
Note over Server: {"result": null} or {"error": {...}}
Server->>-WS: Send response JSON
WS->>-Bridge: Forward response
Bridge->>Bridge: Parse JSON & check errors
Bridge-->>-Python: Return result or throw exception
- VS Code Extension (
src/
): WebSocket server that handles commands - Demo Workspace (
workspace/
): Contains all demo files opened by Extension Development Hostpython_client/
: Python client libraryexamples/
: Demonstration scriptsdemo.py
: Interactive demonstration script- Sample files:
test-file.txt
,sample.js
,sample.py
# Install dependencies
yarn install
# Compile extension
yarn compile
- Press
F5
in VS Code to launch Extension Development Host - The Extension Development Host will open the
workspace/
folder with demo files - The extension will start automatically and create a WebSocket server on port 60123
In the Extension Development Host window (the one that opened from F5):
-
Open Terminal in VS Code:
- Press
Ctrl+`` (backtick) or
Cmd+`` on Mac - Or use menu: Terminal β New Terminal
- Press
-
Install Python dependencies:
pip install -r python_client/requirements.txt
In the same terminal in VS Code:
# Run the complete interactive demonstration
python demo.py
This will walk you through all the bridge capabilities with explanations and real-time demonstrations.
# Basic notification
python examples/basic_notify.py
# Get editor information
python examples/editor_info.py
# Text manipulation
python examples/text_replacement.py
# Complex workflow
python examples/automated_workflow.py
π‘ Note: All Python commands should be run in the VS Code terminal within the Extension Development Host window.
The extension accepts JSON messages with this structure:
{
"command": "command_name",
"params": {
// command-specific parameters
}
}
Command | Description | Parameters |
---|---|---|
notify |
Display notification in VS Code | message : string |
get_titles_of_active_editors |
Get list of open editors | none |
get_text_from_named_editor |
Get text from specific file | filename : string |
set_text_of_active_editor |
Set text in active editor | text : string |
from vscode_bridge import VSCodeBridge
bridge = VSCodeBridge()
# Send notification
bridge.notify("Hello from Python!")
# Get editor information
editors = bridge.get_editor_titles()
# Read file content
content = bridge.get_text_from_editor("filename.txt")
# Set active editor content
bridge.set_active_editor_text("New content")
Demonstrates the simplest integration: sending a notification from Python to VS Code.
Shows how to query VS Code for information about all currently open editors.
Demonstrates reading content from a file and replacing the active editor's content.
Complex example that combines all APIs to perform automated code analysis:
- Scans all open files
- Counts errors, warnings, and TODOs
- Generates a comprehensive report
- Displays results in VS Code
# Development build with sourcemap
yarn compile
# Watch mode for development
yarn watch
# Production build (minified)
yarn vscode:prepublish
# Type checking only
yarn typecheck
- Launch the extension in VS Code (
F5
) - Open some test files in the Extension Development Host
- Run the Python examples from the terminal
- Observe notifications and text changes in VS Code
- Port: 60123 (localhost only)
- Protocol: JSON-based message exchange
- Connection: Single persistent connection per Python client
Request:
{
"command": "notify",
"params": {
"message": "Hello World"
}
}
Success Response:
{
"result": null
}
Error Response:
{
"error": {
"message": "Error description",
"code": 400
}
}
This project demonstrates the Command Design Pattern - a behavioral design pattern that encapsulates requests as objects, allowing you to parameterize clients with different requests and queue operations.
- Command Interface: JSON message structure defining
command
andparams
- Concrete Commands: Specific commands like
notify
,get_titles_of_active_editors
- Invoker: Python client (
VSCodeBridge
) that creates and sends commands - Receiver: VS Code extension (
GenericWebSocketServer
) that executes commands - Client: Python scripts that use the bridge to perform operations
- Decoupling: Python scripts don't need to know VS Code API details
- Extensibility: New commands can be added without modifying existing code
- Undo/Redo Potential: Commands could be stored and replayed
- Queuing: Multiple commands can be batched and executed sequentially
- Logging: All command execution can be logged for debugging
- Python Method Call:
bridge.notify("Hello from Python!")
- Command Object Creation (
vscode_bridge.py:146-152
):command = { "command": "notify", "params": {"message": message} }
- JSON Serialization (
vscode_bridge.py:114
):json.dumps(message)
- WebSocket Transmission: Raw JSON string sent over WebSocket connection
- VS Code Reception (
websocketServer.ts:64
): Buffer converted to string - JSON Parsing (
websocketServer.ts:71
):JSON.parse(message)
- Command Validation: Check for required
command
field and valid structure
- Command Router (
websocketServer.ts:183-217
): Switch statement routes to handler - Parameter Validation: Each handler validates required parameters
- VS Code API Call: Handler calls appropriate VS Code API
- Response Generation: Success/error response object created
- JSON Serialization: Response serialized to JSON string
- WebSocket Response: JSON sent back to Python client
- Python Parsing (
vscode_bridge.py:118
): JSON parsed and errors checked - Result Extraction: Return
result
field or raiseVSCodeBridgeError
Commands can fail at multiple stages:
- Connection Errors: WebSocket connection unavailable
- JSON Errors: Malformed JSON in either direction
- Validation Errors: Missing or invalid command parameters
- Execution Errors: VS Code API calls fail
- Application Errors: No active editor, file not found, etc.
Each error is encoded as:
{
"error": {
"message": "Description of what went wrong",
"code": 400|404|500
}
}
This project demonstrates several important software engineering concepts:
- Command Design Pattern: Encapsulating requests as objects for flexible execution
- Inter-Process Communication: WebSocket-based messaging between different runtimes
- Protocol Design: JSON-based command/response protocol with error handling
- Error Propagation: Comprehensive error management across distributed systems
- Client-Server Architecture: Clear separation of concerns between components
- Language Integration: Bridging Python and TypeScript/JavaScript ecosystems
- Serialization/Deserialization: JSON encoding/decoding for data transmission
- Validation Patterns: Parameter validation and type checking across boundaries
To add new commands:
- Add command handler in VS Code (
src/websocketServer.ts
):
case 'your_new_command':
return await this.handleYourNewCommand(message.params);
- Add method to Python client (
python_client/vscode_bridge.py
):
def your_new_method(self, param: str) -> str:
command = {
"command": "your_new_command",
"params": {"param": param}
}
response = self.send_json_message(command)
return response.get('result')
- VS Code: Version 1.74.0 or higher
- Node.js: Version 16.x or higher
- Python: Version 3.7 or higher
- Dependencies: Listed in
package.json
andrequirements.txt
- Port 60123 already in use: Close other applications using this port
- Connection refused: Ensure VS Code extension is running
- Import errors in Python: Verify
websocket-client
is installed - Extension not loading: Check VS Code developer console for errors
Enable debug logging by setting:
import logging
logging.basicConfig(level=logging.DEBUG)
This project is provided as an educational example. Use and modify freely for academic and research purposes.
This is a demonstration repository, but improvements and additional examples are welcome!
Next Steps: Copy this working implementation to a new repository for standalone distribution and further development.